package edu.calstatela.cs.csun;
public class TTTBean {
boolean turn; // player one's move
int[] board;
public TTTBean()
{
turn = true; // player one's move
board = new int[9];
for( int i=0 ; i < board.length ; ++i ) board[i] = 0;
}
public void setMove( int move )
{
if( move < 9 && move >= 0 && board[move] == 0 )
{
board[move] = turn ? 1 : 2;
turn = !turn;
}
}
public void setNew( String n )
{
if( n != null )
{
turn = true;
for( int i=0 ; i < board.length ; ++i ) board[i] = 0;
}
}
public int getStatus()
{
// check all rows
for( int i=0 ; i < 8 ; i += 3 )
if( board[i] != 0 && board[i] == board[i+1] && board[i+1] == board[i+2] )
return board[i];
// check all columns
for( int i=0 ; i < 3 ; ++i )
if( board[i] != 0 && board[i] == board[i+3] && board[i+3] == board[i+6] )
return board[i];
// check diagonals
if( board[0] != 0 && board[0] == board[4] && board[4] == board[8] )
return board[0];
if( board[2] != 0 && board[2] == board[4] && board[4] == board[6] )
return board[2];
// at this point nobody is winning so we check for a tie
for( int i=0 ; i < 9 ; ++i ) if( board[i] == 0 ) return 0;
// tied
return 3;
}
public String[] getBoard()
{
String b[] = new String[9];
for( int i=0 ; i < board.length ; ++i )
{
switch( board[i] )
{
case 0:
b[i] = "_";
break;
case 1:
b[i] = "O";
break;
case 2:
b[i] = "X";
break;
default:
}
}
return b;
}
} // end of TTTBean