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

public class TicTacToe extends Applet {
                                                 
    TextArea echoArea;  
    Grid board;
    char player = Cell.EX;   // Current player: EX, or OH
    
    public void init() {
        // Set the background color and listen for the mouse
        setBackground(Color.white);
        addMouseListener(new MouseHandler());
	
        // Create a button and add it to the Frame.
        Button newGame = new Button("New Game");
        newGame.setForeground(Color.black);
        newGame.setBackground(Color.lightGray);
        add(newGame);
        newGame.addActionListener(new NewGameHandler());
	
        // Create a echo area and add it to the Frame
        echoArea = new TextArea(2, 40);
        echoArea.setEditable(false);
        add(echoArea);

	// Place a 3x3 board to the Frame
	board = new Grid(3, 40, 120);
    } // init

    public void paint(Graphics g) { board.paint(g); }
        
    private class MouseHandler extends MouseAdapter {
	public void mouseClicked(MouseEvent e) {
	    if (board.contains(e.getX(), e.getY())) {
		Cell c = board.getCell(board.row, board.col);
		if (c.get() == Cell.OFF) {
		    c.set(player);
		    if (player == Cell.EX) 
			player = Cell.OH;
		    else player = Cell.EX;
		    repaint();
		}
		else echoArea.setText("Invalid move, try again");
	    }
	    else echoArea.setText("Please click inside the board");
	}
    }
    
    // Called when the user selects clear Button
    private class NewGameHandler implements ActionListener {
	public void actionPerformed (ActionEvent e) {
	    echoArea.setText("New Game button selected ");
	    board.clear();
	    player = Cell.EX;
	    repaint( );
	}
    }

} // class TicTacToe
