// Purpose.  GridLayout and Buttons lab answer

import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;

public class GridGameApplet extends Applet implements ActionListener {
   private int  SIZE = 9;
   private int  x, y;
   private Font font = new Font( "Helvetica", Font.BOLD, 16 );
   private Button[][] btns;

   public void init() {
      String size = getParameter( "size" );
      if (size != null) SIZE = Integer.parseInt( size );

      setLayout( new GridLayout(SIZE,SIZE) );
      btns = new Button[SIZE][SIZE];

      for (int i=0; i < SIZE; i++)
         for (int j=0; j < SIZE; j++) {
            btns[i][j] = new Button();
            btns[i][j].setFont( font );
            btns[i][j].setActionCommand( Integer.toString(i) + "," + j );
            btns[i][j].addActionListener( this );
            add( btns[i][j] );
         }
   }
   public void start() {
      x = ((int) (Math.random() * 1000)) % SIZE;
      y = ((int) (Math.random() * 1000)) % SIZE;
      for (int i=0; i < SIZE; i++)
         for (int j=0; j < SIZE; j++) {
            btns[i][j].setBackground( Color.white );
            btns[i][j].setForeground( Color.black );
            btns[i][j].setLabel( "  " );
         }
   }
   public void actionPerformed( ActionEvent e) {
      System.out.println( e.getActionCommand() );
      Button btn = (Button) e.getSource();
      String lab = e.getActionCommand();
      int x = Integer.parseInt( lab.substring( 0, 1 ) );
      int y = Integer.parseInt( lab.substring( 2, 3 ) );
      btn.setBackground( Color.yellow );
      btn.setForeground( Color.red );
      btn.setLabel( Integer.toString( guess(x,y) ) );
   }
   public int guess( int a, int b ) {
      return Math.abs( a - x ) + Math.abs( b - y );
   }
}
