// -------------------------------------------------------
// A short game applet to demonstrate Java 1.1 event
// handling.  The goal is to find the (hidden) gold.
// 
// 605.201.31 Introduction to Programming Using Java
//   (http://apl.jhu.edu/~paulmac/intro-java.html)
//
// 8/4/98  Paul McNamee
// -------------------------------------------------------

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

// -------------------------------------------------------

class MinerButton extends Button {
  public int fieldX, fieldY;  // x,y position of button
  public MinerButton (int x, int y) {
    setBackground(Color.blue);
    setForeground(Color.white);
    fieldX = x;
    fieldY = y;
  }
}

public class Miner extends Applet implements ActionListener {
  int xpos, ypos;  // position of the gold!
  static final int SIZE=12;

  Button [][] field;
  int count;

  public void init() {
    setBackground(Color.lightGray);
    setLayout(new GridLayout(SIZE, SIZE));

    field = new Button [SIZE][SIZE];
    for (int i=0; i<SIZE; i++) {
      for (int j=0; j<SIZE; j++) {  // horizontal loop
        field[j][i] = new MinerButton(j, i);
        field[j][i].addActionListener(this);  // reference to applet
        add(field[j][i]);                     // added in GridLayout L->R, T->B
      }
    }
  }

  public void start() {
    count = 0;
    xpos = (int) (Math.random() * SIZE);
    ypos = (int) (Math.random() * SIZE);
    for (int i=0; i<SIZE; i++)
      for (int j=0; j<SIZE; j++)
	field[j][i].setLabel("");
  }


  // This method is called when a button is clicked
  public void actionPerformed (ActionEvent e) {
    count++;
    MinerButton mb = ((MinerButton) e.getSource());
    if ((mb.fieldX == xpos) && (mb.fieldY == ypos)) {
      // Found the gold!
      showStatus("Found the gold in " + count + " moves");
      mb.setForeground(Color.yellow);
      mb.setLabel("Gold");
    } else {
      int diff = Math.abs(mb.fieldX-xpos) + Math.abs(mb.fieldY-ypos);
      showStatus("Distance to gold is " + diff);
      mb.setLabel("" + diff);
    }
  }
}
