Extra 5% OFF Use Code: OL05
Free Shipping over ₹999

Tic-Tac-Toe Game

Building a Tic-Tac-Toe Game in C

Creating a Tic-Tac-Toe game in C is a fun and educational project that demonstrates how to use arrays, loops, conditionals, and functions. The game will allow two players to take turns placing their markers (X and O) on a 3×3 grid, with the goal of getting three in a row.

Step-by-Step Implementation

  1. Define the Game Board: Use a 2D array to represent the Tic-Tac-Toe grid.
  2. Display the Board: Create a function to print the current state of the board.
  3. Check for Win or Draw: Implement functions to check if a player has won or if the game is a draw.
  4. Take Player Input: Allow players to choose their position on the board.
  5. Control the Game Loop: Use a loop to alternate between players until there’s a win or a draw.

Example Code

Here’s a complete implementation of a Tic-Tac-Toe game in C:

#include <stdio.h>

#define SIZE 3  // Define the size of the Tic-Tac-Toe board

// Function prototypes
void printBoard(char board[SIZE][SIZE]);
int checkWin(char board[SIZE][SIZE]);
int checkDraw(char board[SIZE][SIZE]);
void resetBoard(char board[SIZE][SIZE]);

int main() {
    char board[SIZE][SIZE];  // Create the game board
    int row, col, result;
    char currentPlayer = 'X';  // Start with player X

    resetBoard(board);  // Initialize the board

    // Main game loop
    while (1) {
        printBoard(board);  // Display the current board
        printf("Player %c, enter your move (row and column): ", currentPlayer);
        scanf("%d %d", &row, &col);  // Get player input

        // Validate the move
        if (row < 0 || row >= SIZE || col < 0 || col >= SIZE || board[row][col] != ' ') {
            printf("Invalid move. Try again.\n");
            continue;  // Ask for input again
        }

        // Place the player's mark on the board
        board[row][col] = currentPlayer;

        // Check for a win
        result = checkWin(board);
        if (result == 1) {
            printBoard(board);
            printf("Player %c wins!\n", currentPlayer);
            break;
        }

        // Check for a draw
        if (checkDraw(board)) {
            printBoard(board);
            printf("It's a draw!\n");
            break;
        }

        // Switch players
        currentPlayer = (currentPlayer == 'X') ? 'O' : 'X';
    }

    return 0;
}

// Function to print the game board
void printBoard(char board[SIZE][SIZE]) {
    printf("\n");
    for (int i = 0; i < SIZE; i++) {
        for (int j = 0; j < SIZE; j++) {
            printf(" %c ", board[i][j]);
            if (j < SIZE - 1) printf("|");
        }
        printf("\n");
        if (i < SIZE - 1) {
            for (int j = 0; j < SIZE; j++) printf("---");
            printf("\n");
        }
    }
    printf("\n");
}

// Function to check if a player has won
int checkWin(char board[SIZE][SIZE]) {
    // Check rows and columns
    for (int i = 0; i < SIZE; i++) {
        if ((board[i][0] == board[i][1] && board[i][1] == board[i][2] && board[i][0] != ' ') ||
            (board[0][i] == board[1][i] && board[1][i] == board[2][i] && board[0][i] != ' ')) {
            return 1;  // A player has won
        }
    }
    // Check diagonals
    if ((board[0][0] == board[1][1] && board[1][1] == board[2][2] && board[0][0] != ' ') ||
        (board[0][2] == board[1][1] && board[1][1] == board[2][0] && board[0][2] != ' ')) {
        return 1;  // A player has won
    }
    return 0;  // No winner yet
}

// Function to check for a draw
int checkDraw(char board[SIZE][SIZE]) {
    for (int i = 0; i < SIZE; i++) {
        for (int j = 0; j < SIZE; j++) {
            if (board[i][j] == ' ') {
                return 0;  // There are still moves left
            }
        }
    }
    return 1;  // The game is a draw
}

// Function to reset the game board
void resetBoard(char board[SIZE][SIZE]) {
    for (int i = 0; i < SIZE; i++) {
        for (int j = 0; j < SIZE; j++) {
            board[i][j] = ' ';  // Initialize all positions to empty
        }
    }
}

Explanation of the Code

  1. Define Constants: The size of the Tic-Tac-Toe board is defined using a macro.
  2. Function Prototypes: Functions for printing the board, checking for wins, checking for draws, and resetting the board are declared.
  3. Main Function:
    • Initializes the board and sets the current player to ‘X’.
    • Enters a loop where it displays the board, takes player input, and validates the move.
    • Calls the appropriate functions to check for wins or draws after each move.
    • Switches the current player after each valid move.
  4. Print Board Function: Displays the current state of the board in a formatted way.
  5. Check Win Function: Checks all rows, columns, and diagonals for three matching symbols (either ‘X’ or ‘O’).
  6. Check Draw Function: Checks if all positions on the board are filled without a winner, indicating a draw.
  7. Reset Board Function: Initializes the board to empty spaces (‘ ‘).

Sample Output

Here’s how the program runs in a terminal:

Player X, enter your move (row and column): 0 0

   |   |   
 X |---|   
   |   |   
   |   |   
 
Player O, enter your move (row and column): 1 1

   |   |   
 X |---|   
   | O |   
   |   |   
 
Player X, enter your move (row and column): 0 1

   |   |   
 X |---|   
 X | O |   
   |   |   
 
Player O, enter your move (row and column): 1 0

   |   |   
 X |---|   
 O | O |   
   |   |   
 
Player X, enter your move (row and column): 0 2

   |   |   
 X |---|   
 X | O |   
   |   |   

Player X wins!

    Leave a Reply

    Your email address will not be published.

    Need Help?