tictactoe.c
#include <stdio.h>
#define BOARD_SIZE 3
// Function to initialize the Tic Tac Toe board with empty spaces
void initializeBoard(char board[BOARD_SIZE][BOARD_SIZE]) {
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
board[i][j] = ' ';
}
}
}
// Function to display the Tic Tac Toe board
void displayBoard(char board[BOARD_SIZE][BOARD_SIZE]) {
printf("\n");
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
printf(" %c ", board[i][j]);
if (j < BOARD_SIZE - 1) {
printf("|");
}
}
printf("\n");
if (i < BOARD_SIZE - 1) {
printf("---+---+---\n");
}
}
printf("\n");
}
// Function to check if a player has won
// if there is a winning condition, return 1
int checkWin(char board[BOARD_SIZE][BOARD_SIZE], char player) {
// Check rows
// Check columns
// Check diagonals
return 0;
}
// Function to check if the board is full (draw)
int checkDraw(char board[BOARD_SIZE][BOARD_SIZE]) {
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
if (board[i][j] == ' ') {
return 0; // There's an empty space, the game is not a draw yet.
}
}
}
return 1; // The board is full, it's a draw.
}
int main() {
char board[BOARD_SIZE][BOARD_SIZE];
char player1 = 'X';
char player2 = 'O';
int currentPlayer = 1;
int row, col;
int moves = 0;
initializeBoard(board);
printf("Tic Tac Toe\n");
printf("Player 1: X | Player 2: O\n");
displayBoard(board);
while (1) {
printf("Player %d, enter row (0-2) and column (0-2) separated by a space: ", currentPlayer);
// Get the player's move
if (scanf("%d %d", &row, &col) != 2 || row < 0 || row >= BOARD_SIZE || col < 0 || col >= BOARD_SIZE) {
printf("Invalid input. Please try again.\n");
while (getchar() != '\n'); // Clear input buffer
continue;
}
// Check if the selected cell is empty
if (board[row][col] != ' ') {
printf("That cell is already taken. Please try again.\n");
continue;
}
// Make the move for the current player
board[row][col] = (currentPlayer == 1) ? player1 : player2;
displayBoard(board);
// Check if the current player has won
if (checkWin(board, (currentPlayer == 1) ? player1 : player2)) {
printf("Player %d wins!\n", currentPlayer);
break;
}
// Check if the game is a draw
if (checkDraw(board)) {
printf("It's a draw!\n");
break;
}
// Switch to the other player for the next turn
currentPlayer = (currentPlayer == 1) ? 2 : 1;
moves++;
}
return 0;
}
Last updated