// type 'board_type' is an alias (another name) for the type '2d array of 3x3 char'
// http://en.cppreference.com/w/cpp/language/type_aliasusing board_type = char[3][3] ;
// return character for winner if any, otherwise return 0
// we pass the board (the array) by reference (to const)
// see 'Arguments passed by value and by reference' in http://www.cplusplus.com/doc/tutorial/functions/char check_rows( const board_type& board ) {
// http://www.stroustrup.com/C++11FAQ.html#auto
// http://www.stroustrup.com/C++11FAQ.html#forfor( constauto& row : board ) { // for each row in the board
// if the characters in each cell of the row are the same
// we have a winner: return the character (of the winner)
if( row[0] == row[1] && row[1] == row[2] ) return row[0] ;
}
return 0 ; // no winner in any of the rows
}
// return character for winner if any, otherwise return 0
char check_cols( const board_type& board ) {
for( int col = 0 ; col < 3 ; ++col ) { // for each column 1, 2, 3
// if the three characters in each row of that column are the same
// we have a winner: return the character (of the winner)
if( board[0][col] == board[1][col+3] && board[0][col] == board[2][col] ) return board[0][col] ;
}
return 0 ; // no winner in any of the columns
}
// return character for winner if any, otherwise return 0
char check_diags( const board_type& board ) {
// check diagonal top left to bottom right
if( board[0][0] == board[1][1] && board[0][0] == board[2][2] ) return board[0][0] ;
// check diagonal top right to bottom left
if( board[0][2] == board[1][1] && board[0][2] == board[2][0] ) return board[0][2] ;
return 0 ; // no winner in either of the columns
}
// return character for winner if any, otherwise return 0
char check_winner( const board_type& board ) {
char winner = check_rows(board) ; // check the rows for a winner
// if there is no winner in any of the rows (check_rows returned 0)
// check the columns for a winner
if( !winner ) winner = check_cols(board) ;
// if there is no winner in any of the columns (check_cols returned 0)
// check the diagonals for a winner
if( !winner ) winner = check_diags(board) ;
return winner ;
}