Create Tic-Tac-Toe Game in C Programming

Faraz

By Faraz -

Learn how to create a Tic-Tac-Toe game in C programming. Follow our simple, step-by-step guide to build this classic game from scratch. Perfect for beginners!


create-tic-tac-toe-game-in-c-programming.webp

Introduction

Creating a game like Tic-Tac-Toe in C programming is a great way to sharpen your coding skills while having fun. Tic-Tac-Toe is a simple yet engaging game that many people enjoy. In this blog, we will guide you step by step on how to create this classic game using C programming. Whether you're a beginner or someone looking to refresh your knowledge, this guide is for you.

We will start by setting up the game board, then move on to the game logic, and finally, we'll put everything together to make a complete, working Tic-Tac-Toe game.

Step 1: Setting Up Your Environment

Before you start coding, ensure you have a C compiler installed on your system. Popular options include GCC for Linux and Code::Blocks for Windows. Once your environment is ready, open your preferred text editor or IDE.

Installing GCC on Linux

If you are on Linux, you can install GCC by running the following command:

sudo apt-get install gcc

Installing Code::Blocks on Windows

For Windows users, download and install Code::Blocks from its official website. Follow the installation instructions to set it up.

Step 2: Creating the Game Board

The first part of our Tic-Tac-Toe game is setting up the game board. The board is a 3x3 grid where players will place their marks (X or O).

Step 2.1: Defining the Game Board

In your C program, you can represent the board using a 2D array. Here’s the code to set up the board:

#include <stdio.h>

char board[3][3];

void initializeBoard() {
    int i, j;
    for(i = 0; i < 3; i++) {
        for(j = 0; j < 3; j++) {
            board[i][j] = ' ';
        }
    }
}

Step 2.2: Displaying the Board

You also need a function to display the board so that players can see it after each move. Here’s a simple function to do that:

void displayBoard() {
    int i;
    for(i = 0; i < 3; i++) {
        printf(" %c | %c | %c \n", board[i][0], board[i][1], board[i][2]);
        if (i < 2) {
            printf("---|---|---\n");
        }
    }
}

Step 3: Handling Player Moves

The next step is to create a function that allows players to make their moves. The players will be placing their marks on the board until someone wins or the game ends in a draw.

Step 3.1: Taking Player Input

You need a function to take input from the player and update the board accordingly:

void playerMove(char mark) {
    int row, col;
    printf("Enter row (1-3) and column (1-3): ");
    scanf("%d %d", &row, &col);
    row--; col--; // Adjusting for 0-based array index

    if (board[row][col] == ' ') {
        board[row][col] = mark;
    } else {
        printf("Cell already occupied! Try again.\n");
        playerMove(mark);
    }
}

Step 3.2: Alternating Between Players

To alternate between players, you can use a simple loop. Here’s how:

void playGame() {
    int turn;
    for(turn = 0; turn < 9; turn++) {
        displayBoard();
        if(turn % 2 == 0) {
            printf("Player 1 (X) move:\n");
            playerMove('X');
        } else {
            printf("Player 2 (O) move:\n");
            playerMove('O');
        }
        // Check for win condition here (we’ll cover this next)
    }
}

Step 4: Checking for a Winner

One of the most important parts of the game is checking if a player has won. This happens when a player gets three of their marks in a row, column, or diagonal.

Step 4.1: Winning Conditions

Here’s a simple function to check for a win:

int checkWin() {
    int i;
    for(i = 0; i < 3; i++) {
        // Check rows
        if (board[i][0] == board[i][1] && board[i][1] == board[i][2] && board[i][0] != ' ') {
            return 1;
        }
        // Check columns
        if (board[0][i] == board[1][i] && board[1][i] == board[2][i] && board[0][i] != ' ') {
            return 1;
        }
    }
    // Check diagonals
    if (board[0][0] == board[1][1] && board[1][1] == board[2][2] && board[0][0] != ' ') {
        return 1;
    }
    if (board[0][2] == board[1][1] && board[1][1] == board[2][0] && board[0][2] != ' ') {
        return 1;
    }
    return 0;
}

Step 4.2: Ending the Game

Once a win condition is met, you need to end the game. Here’s how you can do that:

void playGame() {
    int turn;
    for(turn = 0; turn < 9; turn++) {
        displayBoard();
        if(turn % 2 == 0) {
            printf("Player 1 (X) move:\n");
            playerMove('X');
        } else {
            printf("Player 2 (O) move:\n");
            playerMove('O');
        }
        
        if(checkWin()) {
            displayBoard();
            printf("Player %d wins!\n", (turn % 2) + 1);
            return;
        }
    }
    displayBoard();
    printf("It's a draw!\n");
}

Step 5: Putting It All Together

Now that we’ve built all the necessary parts, it’s time to put everything together into a complete program. Below is the full code for your Tic-Tac-Toe game in C:

#include <stdio.h>

char board[3][3];

void initializeBoard() {
    int i, j;
    for(i = 0; i < 3; i++) {
        for(j = 0; j < 3; j++) {
            board[i][j] = ' ';
        }
    }
}

void displayBoard() {
    int i;
    for(i = 0; i < 3; i++) {
        printf(" %c | %c | %c \n", board[i][0], board[i][1], board[i][2]);
        if (i < 2) {
            printf("---|---|---\n");
        }
    }
}

void playerMove(char mark) {
    int row, col;
    printf("Enter row (1-3) and column (1-3): ");
    scanf("%d %d", &row, &col);
    row--; col--; 

    if (board[row][col] == ' ') {
        board[row][col] = mark;
    } else {
        printf("Cell already occupied! Try again.\n");
        playerMove(mark);
    }
}

int checkWin() {
    int i;
    for(i = 0; i < 3; i++) {
        if (board[i][0] == board[i][1] && board[i][1] == board[i][2] && board[i][0] != ' ') {
            return 1;
        }
        if (board[0][i] == board[1][i] && board[1][i] == board[2][i] && board[0][i] != ' ') {
            return 1;
        }
    }
    if (board[0][0] == board[1][1] && board[1][1] == board[2][2] && board[0][0] != ' ') {
        return 1;
    }
    if (board[0][2] == board[1][1] && board[1][1] == board[2][0] && board[0][2] != ' ') {
        return 1;
    }
    return 0;
}

void playGame() {
    int turn;
    initializeBoard();
    for(turn = 0; turn < 9; turn++) {
        displayBoard();
        if(turn % 2 == 0) {
            printf("Player 1 (X) move:\n");
            playerMove('X');
        } else {
            printf("Player 2 (O) move:\n");
            playerMove('O');
        }
        
        if(checkWin()) {
            displayBoard();
            printf("Player %d wins!\n", (turn % 2) + 1);
            return;
        }
    }
    displayBoard();
    printf("It's a draw!\n");
}

int main() {
    playGame();
    return 0;
}

Step 6: Compiling and Running the Program

Once you've written the code, it's time to compile and run it.

  1. Compile the Code: If you're using GCC, open your terminal and navigate to the directory containing your code file. Run the following command:
    gcc tic_tac_toe.c -o tic_tac_toe
    This will compile the code and create an executable file named tic_tac_toe.
  2. Run the Program: After compiling, In the same Command Prompt window, type:
    tic_tac_toe
    This command will start your Tic-Tac-Toe game.
  3. Play the Game: You'll see the game board displayed, and you'll be prompted to enter the row and column numbers where you'd like to place your mark (X or O). The game will continue until there's a winner or the game ends in a draw.

Conclusion

Creating a Tic-Tac-Toe game in C programming is a great way to practice and improve your coding skills. By following this step-by-step guide, you've learned how to set up the game board, handle player moves, check for a winner, and tie everything together into a complete game. With this knowledge, you can now explore more complex games or add more features to this one. 

That’s a wrap!

I hope you enjoyed this article

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee.

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post

Please allow ads on our site🥺