View Single Post
  #3 (permalink)  
Old 07-03-2007, 08:45 PM
Albert Albert is offline
Senior Member
 
Join Date: Jun 2007
Posts: 114
Albert is on a distinguished road
First of all, you'll need a board.
Code:
private char[][] board = new char[3][3];
I would recommend making final chars to represent what is in each sqaure.
Code:
private final char EMPTY = ' '; private final char PLAYER1 = 'X'; private final char PLAYER2 = 'O';
you need to initialize the board.
Code:
public void init() { for (int x = 0; x < 3; x++) { for (int y = 0; y < 3; y++) { board[x][y] = EMPTY; } } }
to check the winner, this gets a bit tedious.
Code:
public char winner() { for (int i = 0; i < board.length; i++) { /* check horizontally */ if (board[i][0] == board[i][1] && board[i][0] == board[i][2]) { if (board[i][0] != EMPTY) { return board[i][0]; } } /* check vertically */ if (board[0][i] == board[1][i] && board[0][i] == board[2][i]) { if (board[0][i] != EMPTY) { return board[0][i]; } } } /* check diagonally */ if (board[0][0] == board[1][1] && board[0][0] == board[2][2]) { if (board[0][0] != EMPTY) { return board[0][0]; } } if (board[0][2] == board[1][1] && board[0][2] == board[2][0]) { if (board[0][2] != EMPTY)) { return board[0][2]; } } return EMPTY; }
Greetings

Albert
Reply With Quote