#include #include #include "consts.h" #include "protos.h" char is_board_solved(BOARD board) { char cases[8] = {EMPTY}; char i; // rows and cols for (i = 0; i < 3; i++) { cases[i] = board[i][0] * board[i][1] * board[i][2]; cases[i + 3] = board[0][i] * board[1][i] * board[2][i]; } // diagonals cases[6] = board[0][0] * board[1][1] * board[2][2]; cases[7] = board[0][2] * board[1][1] * board[2][0]; // check cases for winner for (i = 0; i < 8; i++) { if (cases[i] == 1) { // X won return X; } else if (cases[i] == 8) { // O won return O; } } // check cases for remaining moves for (i = 0; i < 9; i++) { if (cases[i] == EMPTY) { // more spaces left; game continues return EMPTY; } } // stalemate return TIE; } void print_board(BOARD board) { char i, j; for (i = 0; i < 3; i++) { for (j = 0; j < 3; j++) { printf("%d ", board[i][j]); } printf("\n"); } } int main() { char solution = EMPTY; char move = EMPTY; char move_x = EMPTY; char move_y = EMPTY; BOARD board = {{EMPTY}, {EMPTY}, {EMPTY}}; while (1) { print_board(board); solution = is_board_solved(board); switch (solution) { case X: printf("X won"); break; case O: printf("O won"); break; case TIE: printf("Stalemate"); break; default: printf("Enter a move..."); } printf("\n"); cursor(1); move = cgetc() - '0' - 1; // if move is not a number then bail // if (move < 1 || move > 8) { invalid! } move_x = move % 3; move_y = move / 3; // if move not already taken board[move_y][move_x] = X; } return 0; }