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 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
|
const int ROWS = 3;
const int COLS = 3;
// showBoard() displays the contents of the board
void showBoard(char board[][COLS]);
// xoTurn() allows a player (X or O) to take a turn
void xoTurn(char board[][COLS], char xo);
// gameOver() returns true if the game is over, i.e., a
// player has already won or there is a tie
bool gameOver(char board[][COLS]);
// xoWins() accepts the game board and player xo (X or O)
// as arguments and returns true if the player has won
bool xoWins(char board[][COLS], char xo);
// xoCanWin() returns true if player (X or O) can still win
bool xoCanWin(char board[][COLS], char xo);
// showWinner() displays the winner
void showWinner(char board[][COLS]);
int main()
{
char gameBoard[ROWS][COLS] = { '*', '*', '*', '*', '*', '*', '*', '*', '*' };
do {
showBoard(gameBoard); // show game board
xoTurn(gameBoard, 'X'); // player 1's turn
showBoard(gameBoard); // show game board again
if (!gameOver(gameBoard)) // if game not over
xoTurn(gameBoard, 'O'); // player 2's turn
} while (!gameOver(gameBoard));
showBoard(gameBoard); // show game board one last time
showWinner(gameBoard); // display the winner
return 0;
}
bool xoCanWin(char bd[][COLS], char xo)
{
bool status = false; // status flag
// check the first horizontal row
if ((bd[0][0] == xo || bd[0][0] == '*') && (bd[0][1] == xo || bd[0][1] == '*') && (bd[0][2] == xo || bd[0][2] == '*'))
status = true;
// check the second horizontal row
if ((bd[1][0] == xo || bd[1][0] == '*') && (bd[1][1] == xo || bd[1][1] == '*') && (bd[1][2] == xo || bd[1][2] == '*'))
status = true;
// check the third horizontal row
if ((bd[2][0] == xo || bd[2][0] == '*') && (bd[2][1] == xo || bd[2][1] == '*') && (bd[2][2] == xo || bd[2][2] == '*'))
status = true;
// check the first column
if ((bd[0][0] == xo || bd[0][0] == '*') && (bd[1][0] == xo || bd[1][0] == '*') && (bd[2][0] == xo || bd[2][0] == '*'))
status = true;
// check the second column
if ((bd[0][1] == xo || bd[0][1] == '*') && (bd[1][1] == xo || bd[1][1] == '*') && (bd[2][1] == xo || bd[2][1] == '*'))
status = true;
// check the third column
if ((bd[0][2] == xo || bd[0][2] == '*') && (bd[1][2] == xo || bd[1][2] == '*') && (bd[2][2] == xo || bd[2][2] == '*'))
status = true;
// check the diagonal
if ((bd[0][0] == xo || bd[0][0] == '*') && (bd[1][1] == xo || bd[1][1] == '*') && (bd[2][2] == xo || bd[2][2] == '*'))
status = true;
// check other diagonal
if ((bd[0][2] == xo || bd[0][2] == '*') && (bd[1][1] == xo || bd[1][1] == '*') && (bd[2][0] == xo || bd[2][0] == '*'))
status = true;
return status; // if we make it this far, player cannot win
}
|