Java Reference
In-Depth Information
and a score of 4 is returned. Next, the method checks to see if it can prevent the player
from completing a line. If it can, then this is the next best alternative and a score of 3 is
returned. In all other cases, a score of 2 is returned. As the reader can probably guess, this
is a very primitive method that does not always choose the best available move. It is left as
an exercise for the reader to identify possible improvements. For example, the next move to
consider may be a move that can win the game in two moves regardless of what the human
player chooses to do.
The
winsWithNextMove
method is shown next.
public boolean
winsWithNextMove( Square r ,
char
c)
{
r . placeCharacter(c) ;
if
(wins(c))
{
r.clear();
return true
;
r.clear();
return false
;
}
The method needs to check if placing the character
c
at the square
r
is a winning move.
It first places the character on the board. It then checks if it is a winning move. As a final
step, the character is removed from the board. This is a very common practice in board
games. A move is made (e.g., a character is placed). We evaluate the position and the move
is undone if necessary.
The complete code of the game, including imports, is shown next. Connect the program
with the .html file that is shown at the beginning of this chapter. Open the web page and
see if you can beat the game.
import
java .awt .
∗
;
import
java .awt. event .
∗
;
import
java .awt.geom.
∗
;
import
java. io .File ;
import
java . net .URL;
import
java . util .
∗
;
import
javax . imageio .ImageIO;
import
javax . swing .
∗
;
{
public class
TicTacToe
extends
JApplet
private
ArrayList
<
Square
>
squares =
new
ArrayList
<>
() ;
private
Image xImage , oImage ;
public void
initBoard()
{
squares =
new
ArrayList
<>
() ;
Dimension d = getSize () ;
double
dx = d.getWidth() / 3.0;
double
dy = d . getHeight () / 3 . 0 ;
for
(
int
x=0;x
<
3 ; x++)
{
for
(
double
y=0;y
<
3 ; y++)
{
squares .add(
new
Square(x
dx , y
dy , dx , dy) ) ;
∗
∗
}
repaint () ;
}
public void
init()
{
try
{