GAMES TWO: LESSON Ten: Tic Tac Toe: Detecting Winner
Detecting a winner is really easy to do since there are only eight possible
ways of winning the game of tic tac toe. So, the only major modification
needed to detect a winner is to write a method which inspects the grid array
for a winning pattern and integrate it into the rest of the applet.
Here is the winner method:
public boolean winner(int patt){
String symbol = "X";
if(patt==1) symbol="O";
if(grid[0].equals(symbol) && grid[1].equals(symbol) &&
grid[2].equals(symbol) ) {
gameOver=true;
win = patt;
}
else if(grid[3].equals(symbol) && grid[4].equals(symbol) &&
grid[5].equals(symbol) ) {
gameOver=true;
win = patt;
}
else if(grid[6].equals(symbol) && grid[7].equals(symbol) &&
grid[8].equals(symbol) ) {
gameOver=true;
win = patt;
}
else if(grid[0].equals(symbol) && grid[3].equals(symbol) &&
grid[6].equals(symbol) ) {
gameOver=true;
win = patt;
}
else if(grid[1].equals(symbol) && grid[4].equals(symbol) &&
grid[7].equals(symbol) ) {
gameOver=true;
win = patt;
}
else if(grid[2].equals(symbol) && grid[5].equals(symbol) &&
grid[8].equals(symbol) ) {
gameOver=true;
win = patt;
}
else if(grid[0].equals(symbol) && grid[4].equals(symbol) &&
grid[8].equals(symbol) ) {
gameOver=true;
win = patt;
}
else if(grid[2].equals(symbol) && grid[4].equals(symbol) &&
grid[6].equals(symbol) ) {
gameOver=true;
win = patt;
}
if(win != -1) return true;
else return false;
}
The winner method gets called from either the move or computer_move method.
Integrating this method into the applet does require several other changes
throughout the applet.
ASSIGNMENT: