Introduction

Tic-Tac-Toe is a classic two-player game where players take turns marking a grid of 3×3 with either an ‘X’ or an ‘O’. The objective of the game is to be the first to form a horizontal, vertical, or diagonal line of three matching symbols.

In this program, we will create a simple text-based Tic-Tac-Toe game in the C programming language. Players will input their moves by specifying the row and column where they want to place their symbol. The program will check for a winner after each move and declare the winner once one player achieves the objective or if the game ends in a draw.

Objective

The objective of this program is to provide a clear example of how a simple Tic-Tac-Toe game can be implemented in C. This program will demonstrate how to:

  • Create a game board using a 2D array.
  • Implement game logic to allow two players to take turns.
  • Check for a winner or a draw after every move.

Code

#include 

char board[3][3] = {{'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'}};
int player = 1;  // Player 1 starts
int choice;
int row, column;
char mark;

void printBoard() {
    printf("\n\n");
    printf(" Tic-Tac-Toe \n");
    printf(" Player 1 (X) - Player 2 (O) \n\n");
    printf("  %c | %c | %c \n", board[0][0], board[0][1], board[0][2]);
    printf(" ---|---|--- \n");
    printf("  %c | %c | %c \n", board[1][0], board[1][1], board[1][2]);
    printf(" ---|---|--- \n");
    printf("  %c | %c | %c \n", board[2][0], board[2][1], board[2][2]);
    printf("\n\n");
}

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

int checkDraw() {
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            if (board[i][j] != 'X' && board[i][j] != 'O') {
                return 0;
            }
        }
    }
    return 1;
}

int main() {
    printf("Welcome to Tic-Tac-Toe Game!\n");
    printBoard();

    while (1) {
        // Alternate between player 1 and player 2
        player = (player % 2) ? 1 : 2;

        // Get player input
        printf("Player %d, enter a number (1-9): ", player);
        scanf("%d", &choice);

        // Determine row and column
        row = (choice - 1) / 3;
        column = (choice - 1) % 3;

        // Check if the cell is already filled
        if (board[row][column] == 'X' || board[row][column] == 'O') {
            printf("This cell is already filled, please try again.\n");
            continue;
        }

        // Mark the board
        mark = (player == 1) ? 'X' : 'O';
        board[row][column] = mark;
        
        // Print the updated board
        printBoard();

        // Check if there is a winner
        if (checkWin()) {
            printf("Player %d wins!\n", player);
            break;
        }

        // Check for a draw
        if (checkDraw()) {
            printf("The game is a draw!\n");
            break;
        }

        // Switch players
        player++;
    }

    return 0;
}

Explanation of the Program Structure

This C program is designed to implement a simple Tic-Tac-Toe game for two players. Here’s a breakdown of the program’s structure:

  • Board Representation: The game board is represented as a 2D array `board[3][3]`, where each element corresponds to a cell in the grid.
  • Player Turns: The variable `player` tracks the current player (either 1 or 2). Player 1 uses ‘X’ and Player 2 uses ‘O’.
  • Input Handling: Players input their move by entering a number between 1 and 9, which corresponds to a position on the board.
  • Game Logic: After each move, the program checks for a winner using the `checkWin` function, and checks for a draw using the `checkDraw` function. If a player wins or the game ends in a draw, the game announces the result and exits.

How to Run the Program

  1. Copy the C code provided above into a text file and save it with a `.c` extension (e.g., `tictactoe.c`).
  2. Compile the code using a C compiler, for example, using GCC: gcc tictactoe.c -o tictactoe.
  3. Run the compiled program by typing: ./tictactoe in the terminal.
  4. Follow the on-screen instructions to play the game.
© 2024 Learn Programming. All rights reserved.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)