GAMES TWO: LESSON EIGHT: Tic Tac Toe: Basic Game

In this lesson we will try to get just a basic game of tic tac toe up and running. We will use the mouse to make the moves in the game and we will draw the X's and O's for each player, and we will draw a grid. This game requires two human players (or one player with a split personality).

First of all drawing the the basic grid and the player symbols is fairly easy. The player symbols are stored in an array called grid which initially contains empty strings:

String grid[] = { "", "", "", "", "", "", "", "", "" };
The grid and the player symbols are drawn in the usual way, along with basic game directions, in the paint method:
offG.setColor(Color.black); offG.setFont(new Font("serif", Font.PLAIN, 12)); offG.fillRect(10,35,80,3); offG.fillRect(10,65,80,3); offG.fillRect(35,10,3,80); offG.fillRect(65,10,3,80); if(gameOver) offG.drawString("Click to reset", 10,d.height-2); else if(turn%2==0) offG.drawString("X's move", 10, d.height-2); else offG.drawString("O's move", 10, d.height-2); offG.setFont(new Font("sansserif", Font.BOLD, 24)); for(int i=0; i<grid.length; i++){ offG.drawString(grid[i], 13+(i%3)*30, 30+(i/3)*30); }
Player moves are detected in an anonymous event class defined in the init method:
offI=createImage(d.width,d.height); this.addMouseListener(new MouseAdapter(){ public void mouseClicked(MouseEvent m) { if(gameOver){ reset(); } else{ int col=0; int row=0; int xval = m.getX(); int yval = m.getY(); if(xval<35) col=0; else if(xval<65) col=1; else col=2; if(yval<35) row=0; else if(yval<65) row=1; else row=2; move(row*3+col); } repaint(); } });
You will notice that a method called move is called in the event mouseClicked method. Here is the code for this class:
public void move(int index){ if(turn%2==0 && grid[index].equals("")) { grid[index]="X"; turn++; } else if(grid[index].equals("")){ grid[index]="O"; turn++; } if(turn==9) gameOver=true; }
Finally the game resets itself with the reset method:
public void reset(){ for(int i = 0; i<grid.length; i++){ grid[i]=""; } turn=0; gameOver=false; }


ASSIGNMENT: