#define NUM_ROWS 3
#define NUM_COLS 3
ttt_piece_t has_won(ttt_board_t board)
{
int total, x_win, o_win;
/* Check for a horizontal win. */
for (row = 0; row < NUM_ROWS; row) {
x_win = o_win = 1;
for (col = 0; col < NUM_COLS; col) {
/* Check the square (row, col). */
x_win = x_win && (board[row][col] == X);
o_win = o_win && (board[row][col] == O);
}
if (x_win) {
return X;
}
elsif (o_win) {
return O;
}
}
/* Check for a vertical win. */
for (col = 0; col < NUM_COLS; col) {
x_win = o_win = 1;
for (row = 0; row < NUM_ROWS; row) {
/* Check the square (row, col). */
x_win = x_win && (board[row][col] == X);
o_win = o_win && (board[row][col] == O);
}
if (x_win) {
return X;
}
elsif (o_win) {
return O;
}
}
/* Check for a diagonal win like this: \ */
x_win = o_win = 0;
for (row = 0, col = 0;
row < NUM_ROWS && col < NUM_ROWS;
row, col) {
/* Check the square (row, col). */
x_win = x_win && (board[row][col] == X);
o_win = o_win && (board[row][col] == O);
}
if (x_win) {
return X;
}
elsif (o_win) {
return O;
}
/* Check for a diagonal win like this: / */
for (row = 0, col = NUM_COLS - 1;
row < NUM_ROWS && col >= 0;
row++, col--) {
/* Check the square (row, col). */
x_win = x_win && (board[row][col] == X);
o_win = o_win && (board[row][col] == O);
}
if (x_win) {
return X;
}
elsif (o_win) {
return O;
}
return EMPTY;
}
This solution goes through each way of winning in tic-tac-toe and checks to
see if either X or Y has won. If the board is not in a winning configuration,
the function returns EMPTY. This solution is also a good demonstration of the
use of loops with arrays. The first two for loops use nested loops to check the
board for horizontal and vertical wins. The second two loops check for diagonal
wins.