Here is a sample implementation of the functions described in the previous response:
// Displays the game board to the console.
void display_board(char board[3][3]) {
printf("\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf("| %c ", board[i][j]);
}
printf("|\n");
}
printf("\n");
}
// Gets the player's move.
void get_player_move(int* row, int* column) {
printf("Enter a row and column number (1-3): ");
scanf("%d %d", row, column);
// Validate the input.
while (*row < 1 || *row > 3 || *column < 1 || *column > 3) {
printf("Invalid input. Please enter a row and column number (1-3): ");
scanf("%d %d", row, column);
}
}
// Makes a move on the game board.
void make_move(char board[3][3], int row, int column) {
board[row - 1][column - 1] = 'X';
}
// Checks if there is a winner.
bool check_winner(char board[3][3]) {
// Check for horizontal wins.
for (int i = 0; i < 3; i++) {
if (board[i][0] == board[i][1] && board[i][1] == board[i][2] && board[i][0] != '-') {
return true;
}
}
// Check for vertical wins.
for (int i = 0; i < 3; i++) {
if (board[0][i] == board[1][i] && board[1][i] == board[2][i] && board[0][i] != '-') {
return true;
}
}
// Check for diagonal wins.
if (board[0][0] == board[1][1] && board[1][1] == board[2][2] && board[0][0] != '-') {
return true;
}
if (board[0][2] == board[1][1] && board[1][1] == board[2][0] && board[0][2] != '-') {
return true;
}
// No winner yet.
return false;
}
// Checks if the game is a draw.
bool check_draw(char board[3][3]) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board[i][j] == '-') {
return false; // There are still empty spaces on the board, so the game is not a draw yet.
}
}
}
// All of the board spaces are filled, so the game is a draw.
return true;
}
To use these functions, you would simply initialize the game board and then start the game loop:
// Initialize the game board.
char board[3][3] = {{'-', '-', '-'}, {'-', '-', '-'}, {'-', '-', '-'}};
// Start the game loop.
while (true) {
// Display the game board.
display_board(board);
// Get the player's move.
int row, column;
get_player_move(row, column);
// Make a move on the board.
make_move(board, row, column);
// Check if there is a winner.
if (check_winner(board)) {
// A player has won!
break;
}
// Check if the game is a draw.
if (check_draw(board)) {
// The game is a draw!
break;
}
}
You can then add additional features to your game, such as:
- Allow the player to choose their symbol at the beginning of the game.
- Implement a computer player.
- Keep track of the number of wins and losses