Implement the Main Game Loop
Write the main game loop to allow players to take turns and interact with the game.
int main() {
initializeBoard();
int currentPlayer = 1;
while (1) {
clearScreen();
printf("Current board state:\n");
printBoard();
int row, col;
printf("Player %d, please enter a row and column (e.g., 1 2):", currentPlayer);
while (scanf("%d %d", &row, &col) != 2) {
printf("Invalid input, please try again: ");
while (getchar() != '\n');
}
if (row < 1 || row > 3 || col < 1 || col > 3 || board[row - 1][col - 1] != ' ') {
printf("Invalid move, please try again.\n");
} else {
if (currentPlayer == 1) {
board[row - 1][col - 1] = 'X';
currentPlayer = 2;
} else {
board[row - 1][col - 1] = 'O';
currentPlayer = 1;
}
}
if (isGameOver()) {
clearScreen();
printf("Game over!\n");
printBoard();
char winner = getWinner();
if (winner != ' ') {
printf("Player %c wins!\n", winner);
} else {
printf("It's a draw!\n");
}
break;
}
}
return 0;
}
Call the initializeBoard
function to initialize the game board, setting all squares to Spaces.
Create an integer variable currentPlayer
, to keep track of whose turn it is. The initial setting is 1, indicating player 1.
In the while (1)
main loop:
- Call the
clearScreen
function to clear the screen so that the display is refreshed after each turn.
- Call the
printBoard
function to print the current game board.
Player input: Prompts the current player to enter row and column coordinates via the scanf
function, e.g. Player 1, please enter a row and column (e.g., 1 2):
. If the input is Invalid (not two integers), the message Invalid input, please try again:
is displayed and the input buffer is cleared until a valid input is obtained.
Input validation: Then, check that the entered row and column coordinates are valid (on a scale of 1 to 3) and that the selected position is a space. If the input is Invalid or the selected location is already occupied, the message Invalid move, please try again.
is displayed and the player is asked to re-enter.
Chess: If the input is valid, the code places an X
or an O
at the corresponding position on the game board based on the current player (1 or 2).
Game end detection: The code then calls the isGameOver()
function to check if the game is over. If the game ends, the screen clears and a message that the game is over is displayed, including a winner (if any) or a draw.
Game result: If there is a winner, the code will say Player X wins!
Or Player O wins!
, depending on which player the winner is. If there is no winner, the code will say It's a draw!
Indicates a tie.