Java Reference
In-Depth Information
public void paint(Graphics g)
{
super .paint(g);
Graphics2D g2 = (Graphics2D) g ;
g2 . setColor (Color .RED) ;
for (Square r : squares) {
r . draw(g2 , xImage , oImage) ;
}
} ...
The method is similar to the paintComponent method. However, since an applet is not
a JPanel ,the paint method needs to be called. An object of type JApplet has a default
panel that does not need to be created. The paint method is called to draw on it. Our
implementation starts by clearing the window by calling super.paint(g) . Then we set the
brush color to red and we draw the squares. Note that it is the responsibility of each square
to display both its boarders and the image inside it (when present).
Next, let us examine the inner MousePressed class.
public class TicTacToe extends JApplet {
class MyMouseListener extends MouseAdapter
{
public void mousePressed (MouseEvent e )
{
for (Square r : squares) {
if (r . contains(e. getPoint ()))
{
if (! r . hasValue() ) {
r . placeCharacter( 'x' );
repaint () ;
if ( isGameOver () )
{
return ;
computerMove () ;
repaint () ;
if ( isGameOver () )
{
return ;
}
}
}
}
}
} ...
}
The method iterates over all the squares of the board. The expression e.getPoint()
returns the coordinates of where the mouse was pressed. If these coordinates are inside a
square, then we interpret this as the player trying to put an X in the square. Note that the
contains method checks if a point is inside a rectangle. If the square already has value,
then we do not need to do anything. Otherwise, the program places an X in the square
and repaints the canvas. If the game is over, then the method terminates. Otherwise, the
computer makes a move and the program checks again if the game is over.
Next, let us start developing the logic of the isGameOver and computerMove methods.
The first method checks to see if there is a line by the player or the computer. The second
method determines the best possible move for the computer. We will start by creating
several auxiliary methods.
public boolean isLine( int i, int j, int k, char c)
{
return (squares . get( i ) . isCharacter(c)
 
Search WWH ::




Custom Search