GAMES TWO: LESSON Nine: Tic Tac Toe: Random Moves

Often you actually want to play the computer in a game since sometimes there is not a human around to play the role of opponent. This applet will actually make moves on its own for the X player and you get to be the O player. Notice that there is not any delay of any kind when the computer makes a move. A nice feature to add would be some kind of delay to give the impression that the computer is thinking about its move.

As you probably noticed, the moves made by the computer in this applet are random. The computer uses no strategy at all when deciding on its move. It just randomly generates possible moves until it finds an empty cell to fill. In order to randomly generate numbers we must use the Random class which is part of the java.util package which we must load with the other packages.

import java.awt.*; import java.applet.*; import java.awt.event.*; import java.util.*;
Most of this applet is just like the last sample applet except that one new method is used:
public void computer_move(){ Random r = new Random(); int index = 0; do{ index=Math.abs(r.nextInt()%9); }while(!grid[index].equals("") ); grid[index]="X"; turn++; if(turn==9) gameOver=true; }
The computer_move method gets called in the init method, in the reset methods, and at the end of the move method. You should notice the use of a do-while loop to determine the computer's move. As already mentioned, this is not a very intelligent way of selecting moves.


ASSIGNMENT: