Java Reference
In-Depth Information
initBoard() ;
return true
;
return false
;
}
Note that the
JOptionPane.showMessageDialog(window, s)
method displays the
string
s
in a pop-up window (a.k.a., a dialog box). The parameter
window
is the parent
window, which in this case is the
JApplet
object. The dialog box that is created is modal,
that is, no other window can be accessed until the window is closed. Fortunately, the dialog
window will have an
OK
button that can be used to close the window. Note that it does
not matter whether the
isGameOver
method first checks to see if
X
wins or whether it first
checks to see if
Y
wins. The reason is that the program logic prevents both players from
winning at the same time.
Next, let us examine the
computerMove
method. It first checks the middle square. If it is
empty, then it always places the letter
O
there. Otherwise, the method goes through all the
squares and calls the
computeScore
method on each square. The
computeScore
method
evaluates the score for placing a symbol in the square. The square with the greatest score
is then chosen and the character
o
is placed there.
public void
computerMove ()
{
if
(! squares . get(4) .hasValue())
{ // if middle is empty
squares . get(4) . placeCharacter(
'o'
);
return
;
Square bestRectangle = squares . get(0) ;
int
best = computeScore(bestRectangle) ;
for
(Square r : squares)
{
if
(computeScore(r)
>
best)
{
best = computeScore(r) ;
bestRectangle = r ;
}
}
bestRectangle . placeCharacter(
'o'
);
}
The real magic or the AI (stands for
artificial intelligence
) of the program happens in
the
computeScore
method. The method is smart enough to access the benefits of choosing
between different squares of the board. Below is our implementation.
public int
computeScore(Square r)
{
if
(r.hasValue())
{
return
0;
if
(winsWithNextMove( r ,
'o'
))
{
return
4;
if
(winsWithNextMove( r ,
'x'
))
{
return
3;
return
2;
}
The method first checks to see if the square is occupied. An occupied square is a terrible
choice and therefore a score of 0 is returned. Next, the method checks to see if the computer
can win if it places its sign in the square. If this is the case, then this is an automatic win