/* * @topic W120111 Java <a href="http://www.c-jump.com/bcc/c123c/c123sample/Java/Week11/tic_tac_toe_class_violet.html" target="_blank">Tic-Tac-Toe Game</a> * @brief class Board */ package tictactoeapp; public class Board { // constants public static final int PIECE_EMPTY = 0; public static final int PIECE_X = 1; public static final int PIECE_O = 2; // data attributes private int[] board = { 0,0,0,0,0,0,0,0,0 }; // The squares are // 0 1 2 // 3 4 5 // 6 7 8 // operations public void print() { for ( int idx = 0; idx < board.length; ++idx ) { if ( idx % 3 == 0 ) { System.out.println(); } System.out.print( board[idx] ); } System.out.println(); }//print public void clear() { for ( int idx = 0; idx < board.length; ++idx ) { update( idx, PIECE_EMPTY ); } }//clear public void update( int idx, int piece ) { // the idx is in range 0-8 // the piece should be board[idx] = piece; }//update public int size() { return board.length; }//size public int getSquareValue( int idx ) { return board[idx]; }//getSquareValue public boolean isGameOver() { // The squares are // 0 1 2 // 3 4 5 // 6 7 8 // The winning lines are: // horizontal lines if ( isOccupied( 0, 1, 2 ) ) return true; if ( isOccupied( 3, 4, 5 ) ) return true; if ( isOccupied( 6, 7, 8 ) ) return true; // vertical lines if ( isOccupied( 0, 3, 6 ) ) return true; if ( isOccupied( 1, 4, 7 ) ) return true; if ( isOccupied( 2, 5, 8 ) ) return true; // diagonal lines if ( isOccupied( 0, 4, 8 ) ) return true; if ( isOccupied( 6, 4, 2 ) ) return true; return false; }//isGameOver // the method returns true if three squares are occupied // by the same game piece, like X or O: private boolean isOccupied( int idx1, int idx2, int idx3 ) { if ( board[idx1] != Board.PIECE_EMPTY && board[idx1] == board[idx2] && board[idx1] == board[idx3] ) { return true; } return false; }//isOccupied }//class Board