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
|
#include <iostream>
typedef char board_type[3][3] ;
bool check_win( const board_type& board )
{
// 1, check rows
for( const auto& row : board )
if( row[0] == row[1] && row[1] == row[2] ) return true ;
// 2. check cols
for( int c = 0 ; c < 3 ; ++c )
if( board[0][c] == board[1][c] && board[1][c] == board[2][c] ) return true ;
// 3. check diagonals
if( board[0][0] == board[1][1] && board[1][1] == board[2][2] ) return true ;
if( board[2][0] == board[1][1] && board[1][1] == board[0][2] ) return true ;
return false ;
}
int main()
{
{
board_type b { {'X','O',' '}, {'X','O',' '}, {'X',' ','O'} } ;
char last_move_made_by = 'X' ;
if( check_win(b) ) std::cout << last_move_made_by << " has won.\n" ;
}
{
board_type b { {'X',' ',' '}, {' ','X','X'}, {'O','O','O'} } ;
char last_move_made_by = 'O' ;
if( check_win(b) ) std::cout << last_move_made_by << " has won.\n" ;
}
}
|