Java Reference
In-Depth Information
&& squares . get(j) . isCharacter(c) && squares . get(k) . isCharacter(c)) ;
}
The method checks if the squares i , j ,and k are all marked as the character c .Note
that we assume that the method is only called on an actual line on the board. Next we
create a method that checks to see if there is a winning combination with the character c .
public boolean wins( char c)
{
for ( int i=0;i < 3 ;
i ++)
{
if (isLine(3
i, 3 i+1,3 i+2,c) ||
// horizontal line
isLine(i, i+3, i+6,c))) {
//vertical line
return true ;
}
if (isLine(0, 4, 8, c)
||
isLine(2, 4, 6, c))
{
//diagonal
return true ;
return false ;
}
The method first checks all horizontal and vertical lines. If there is a line in which all
squares are marked with the character c , then this is a winning combination and true
is returned. Otherwise, the two diagonals are checked. If the method is unable to find a
winning combination with the character c , then the value false is returned.
We next present the isBoardFull method. It simply checks to see if the board is full.
It will be used by the isGameOver method to determine if we have reached a tie.
public boolean isBoardFull ()
{
for (Square r : squares) {
if (! r . hasValue () )
{
return false ;
}
return true ;
}
The method examines all the squares. If one of them is empty, then it returns false .
Otherwise, if all the squares are full, the method returns true .
The isGameOver method is presented next. It first checks to see if one of the players
wins. Then it checks if the board is full. If neither of these conditions are true, then the
method returns false . Otherwise, the method displays an appropriate message to inform
the user that the current game is over. After that, the initBoard method is called to start
a new game.
public boolean isGameOver ()
{
if (wins( 'o' )) {
JOptionPane . showMessageDialog( this , "I win!" );
initBoard() ;
return true ;
if (wins( 'x' )) {
JOptionPane . showMessageDialog( this , "You win!" );
initBoard() ;
return true ;
if (isBoardFull ()) {
JOptionPane . showMessageDialog( this , "It's a tie!" );
 
Search WWH ::




Custom Search