1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
|
enum Winner { NOBODY_WON, X_WON, Y_WON } ;
typedef int triplet[3] ; // a triplet is a 3 element array of int
const triplet triplets[] =
{
{ 0, 1, 2 }, { 3, 4, 5 }, { 6, 7, 8 }, // horizontal
{ 0, 3, 6 }, { 1, 4, 7 }, { 2, 5, 8 }, // vertical
{ 0, 4, 8 }, { 2, 5, 8 } // diagonal
};
const unsigned numTriplets = sizeof(triplets) / sizeof(triplets[0]) ;
Winner checkTriplet( const string& board, const triplet & t )
{
if ( board[t[0]] == board[t[1]] && board[t[1]] == board[t[2]] )
{
if ( board[t[0]] == 'X' )
return X_WON ;
else
if ( board[t[0]] == 'Y' )
return Y_WON ;
}
return NOBODY_WON ;
}
bool boardIsFull(const string& board)
{
for ( unsigned i=0 ; i< boardSize ; ++i )
if ( board[i] != 'X' && board[i] != 'Y' )
return false ;
return true ;
}
Winner checkForWinner(const string& board)
{
for ( unsigned i=0; i< numTriplets; ++i )
{
Winner possibleWinner = checkTriplet(board, triplets[i]) ;
if ( possibleWinner != NOBODY_WON )
return possibleWinner ;
}
return NOBODY_WON ;
}
|