The Wayback Machine - https://web.archive.org/web/20241108025812/https://www.geeksforgeeks.org/tic-tac-toe-game-in-cpp/
Open In App

Tic-Tac-Toe Game in C++

Last Updated : 31 Dec, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this article, we will learn how to develop a tic-tac-toe game in C++. Tic-tac-toe is a game played between two players usually with paper and pencil but here, we will create a C++ program that will display the game on the console screen and players can use different keys from the keyboard to play it.

tic tac toe game in c++

 

Before we start, let’s understand some rules to play the game:

Rules of Tic-Tac-Toe

Following are the rules that define how to play the tic tac toe game:

  • A player can put only a single letter X or O in the 3 x 3 grid in each chance.
  • Both players will get chances alternatively one after another till someone wins or draws. 
  • To win this game, the player must create a horizontal, vertical, or diagonal line consisting of three same letters.
  • The game is drawn, if all grids are filled with X or O letters but no line is made.

Feature of Tic-Tac-Toe in C++

This game provides the following features:

  • This game is developed on a 3×3 grid.
  • This game is designed for two players.
  • Every player may choose a letter between X and O.
  • Both players will get their chances to turn by turn.

Components of the Game

The game is made of the following components that include the functions and data structures to provide the basic operations of the game.

1. Game Board

To create a tic-tac-toe board, a 3 x 3 array initialized with space is used.

char board[3][3] = {{' ', ' ', ' '}, {' ', ' ', ' '}, {' ', ' ', ' '}};

In this array, we will fill the X and O characters based on the moves of the players.

2. Movement Of Player

Now we will create a function drawBoard() to display the Board. It will initialize the array and display the board after each move.

The logic for user input and valid input checking is defined inside the main() function itself.

How to check if the input is valid or not?

  • Valid input: If the cell is empty and is within the boundary
  • Invalid input: If the cell has already been filled with another letter or is outside the bounds.

3. Win, Lose or Draw

The checkWin() function is used to check whether the player has won or not. The draw condition is checked in the main() function.

C++ Program for Tic Tac Toe Game

Below is the complete code for a basic console-based Tic-Tac-Toe game in C++:

C++




// C++ program to implement tic tac toe game
#include <iostream>
using namespace std;
  
// Function to draw the Tic-Tac-Toe board
void drawBoard(char board[3][3])
{
    cout << "-------------\n";
    for (int i = 0; i < 3; i++) {
        cout << "| ";
        for (int j = 0; j < 3; j++) {
            cout << board[i][j] << " | ";
        }
        cout << "\n-------------\n";
    }
}
  
// Function to check for a win
bool checkWin(char board[3][3], char player)
{
    // Check rows, columns, and diagonals
    for (int i = 0; i < 3; i++) {
        if (board[i][0] == player && board[i][1] == player
            && board[i][2] == player)
            return true;
        if (board[0][i] == player && board[1][i] == player
            && board[2][i] == player)
            return true;
    }
    if (board[0][0] == player && board[1][1] == player
        && board[2][2] == player)
        return true;
    if (board[0][2] == player && board[1][1] == player
        && board[2][0] == player)
        return true;
    return false;
}
  
int main()
{
    // Initialize the board and players
    char board[3][3] = { { ' ', ' ', ' ' },
                         { ' ', ' ', ' ' },
                         { ' ', ' ', ' ' } };
    char player = 'X';
    int row, col;
    int turn; // Declare turn here
  
    cout << "Welcome to Tic-Tac-Toe!\n";
  
    // Game loop
    for (turn = 0; turn < 9; turn++) {
        // Draw the board
        drawBoard(board);
  
        // Prompt for valid input
        while (true) {
            cout << "Player " << player
                 << ", enter row (0-2) and column (0-2): ";
            cin >> row >> col;
  
            if (board[row][col] != ' ' || row < 0 || row > 2
                || col < 0 || col > 2) {
                cout << "Invalid move. Try again.\n";
            }
            else {
                break; // Valid input, exit the loop.
            }
        }
  
        // Make the move
        board[row][col] = player;
  
        // Check for a win after making a move
        if (checkWin(board, player)) {
            drawBoard(board);
            cout << "Player " << player << " wins!\n";
            break; // Exit the loop after a win.
        }
  
        // Switch to the other player
        player = (player == 'X') ? 'O' : 'X';
    }
  
    // End of the game
    drawBoard(board);
  
    // Check for a draw
    if (turn == 9 && !checkWin(board, 'X')
        && !checkWin(board, 'O')) {
        cout << "It's a draw!\n";
    }
  
    return 0;
}


Output

Welcome to Tic-Tac-Toe!
-------------
|   |   |   | 
-------------
|   |   |   | 
-------------
|   |   |   | 
-------------
Player X, enter row (0-2) and column (0-2): 1 1
-------------
|   |   |   | 
-------------
|   | X |   | 
-------------
|   |   |   | 
-------------
Player O, enter row (0-2) and column (0-2): 0 0
-------------
| O |   |   | 
-------------
|   | X |   | 
-------------
|   |   |   | 
-------------
Player X, enter row (0-2) and column (0-2): 1 0
-------------
| O |   |   | 
-------------
| X | X |   | 
-------------
|   |   |   | 
-------------
Player O, enter row (0-2) and column (0-2): 2 2
-------------
| O |   |   | 
-------------
| X | X |   | 
-------------
|   |   | O | 
-------------
Player X, enter row (0-2) and column (0-2): 1 2
-------------
| O |   |   | 
-------------
| X | X | X | 
-------------
|   |   | O | 
-------------
Player X wins!
-------------
| O |   |   | 
-------------
| X | X | X | 
-------------
|   |   | O | 
-------------


Similar Reads

Create Bingo Game Using C++
Bingo, a timeless game of chance and anticipation, has been captivating players for generations. The thrill of marking numbers off your card and the excitement of shouting "Bingo!" are experiences that transcend time. In this article, we will guide you through the process of creating your very own Bingo game using the versatile and powerful C++ pro
8 min read
Hangman Game in C++
With friends, many of us had played the hangman game where one player gave a hint to the other to make a correct guess of a particular thing. Here a simple representation of the game 'Hangman' is done using C++ programming language. The player will guess the fruit's name and the Computer will give a hint to the player to make the correct guess. Rul
6 min read
Rock Paper Scissor Game in C++
Stone Paper Scissor or Rock Paper Scissor is a game played between two players where each player in this game forms one of three shapes and the winner is decided as per the rules of the game. Description of the ProjectIt is a simple command line interface project for Rock, Paper, and Scissors games. The user gets the first chance to pick the Rock,
4 min read
C++ Programming Language
C++ is the most used and most popular programming language developed by Bjarne Stroustrup. C++ is a high-level and object-oriented programming language. This language allows developers to write clean and efficient code for large applications and software development, game development, and operating system programming. It is an expansion of the C pr
9 min read
8 Ways to Initialize Vector in C++
Initializing a vector means assigning some initial values to the std::vector elements. In this article, we will learn 8 different ways to initialize a vector in C++. Table of Content Using Initializer ListOne by One InitializationWith a Single ValueFrom an ArrayFrom Another VectorFrom Any STL ContainerUsing std::fill() FunctionUsing std::iota() Fun
5 min read
30 OOPs Interview Questions and Answers (2024) Updated
Object-oriented programming, or OOPs, is a programming paradigm that implements the concept of objects in the program. It aims to provide an easier solution to real-world problems by implementing real-world entities such as inheritance, abstraction, polymorphism, etc. in programming. OOPs concept is widely used in many popular languages like Java,
15+ min read
Top 50 C++ Project Ideas For Beginners & Advanced
C++ is one of the most popular programming languages widely used in the software industry for projects in different domains like games, operating systems, web browsers, DBMS, etc due to its fast speed, versatility, lower-level memory access, and many more. Many top companies like Microsoft, Google, Apple, Netflix, etc use C++ to develop their produ
15+ min read
C++ Programming Examples
Writing C++ programs yourself is the best way to learn the C++ language. C++ programs are also asked in the interviews. This article covers the top practice problems for basic C++ programs on topics like control flow, patterns, and functions to complex ones like pointers, arrays, and strings. C++ Tutorial C++ Recent Articles Topics: Basic Programs
9 min read
C++ Interview Questions and Answers (2024)
C++ - the must-known and all-time favourite programming language of coders. It is still relevant as it was in the mid-80s. As a general-purpose and object-oriented programming language is extensively employed mostly every time during coding. As a result, some job roles demand individuals be fluent in C++. It is utilized by top IT companies such as
15+ min read
Left Shift and Right Shift Operators in C/C++
In C/C++, left shift (<<) and right shift (>>) operators are binary bitwise operators that are used to shift the bits either left or right of the first operand by the number of positions specified by the second operand allowing efficient data manipulation. In this article, we will learn about the left shift and right shift operators. Le
6 min read
vector erase() and clear() in C++
The std::vector::erase() and std::vector::clear() methods in C++ are used to remove elements from the std::vector container. They are the member function of std::vector class defined inside <vector> header file. In this article, we will learn how to use vector::erase() and vector::clear() in C++. Table of Content vector::erase()vector::clear(
3 min read
Substring in C++
The substring function is used for handling string operations like strcat(), append(), etc. It generates a new string with its value initialized to a copy of a sub-string of this object. In C++, the header file which is required for std::substr(), string functions is <string>. The substring function takes two values pos and len as an argument
8 min read
Virtual Function in C++
A virtual function (also known as virtual methods) is a member function that is declared within a base class and is re-defined (overridden) by a derived class. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class's version of the meth
6 min read
Inheritance in C++
The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one of the most important features of Object Oriented Programming in C++. In this article, we will learn about inheritance in C++, its modes and types along with the information about how it affects different properties of the
15+ min read
C++ Polymorphism
The word "polymorphism" means having many forms. In simple words, we can define polymorphism as the ability of a message to be displayed in more than one form. A real-life example of polymorphism is a person who at the same time can have different characteristics. A man at the same time is a father, a husband, and an employee. So the same person ex
7 min read
C++ Classes and Objects
In C++, classes and objects are the basic building block that leads to Object-Oriented programming in C++. In this article, we will learn about C++ classes, objects, look at how they work and how to implement them in our C++ program. What is a Class in C++?A class is a user-defined data type, which holds its own data members and member functions, w
10 min read
Decision Making in C (if , if..else, Nested if, if-else-if )
The conditional statements (also known as decision control structures) such as if, if else, switch, etc. are used for decision-making purposes in C programs. They are also known as Decision-Making Statements and are used to evaluate one or more conditions and make the decision whether to execute a set of statements or not. These decision-making sta
11 min read
C++ Data Types
All variables use data type during declaration to restrict the type of data to be stored. Therefore, we can say that data types are used to tell the variables the type of data they can store. Whenever a variable is defined in C++, the compiler allocates some memory for that variable based on the data type with which it is declared. Every data type
11 min read
Convert String to int in C++
Converting a string to int is one of the most frequently encountered tasks in C++. As both string and int are not in the same object hierarchy, we cannot perform implicit or explicit type casting as we can do in case of double to int or float to int conversion. Conversion is mostly done so that we can convert numbers that are stored as strings. Exa
8 min read
std::sort() in C++ STL
std::sort() is an STL function that is used to sort the given range in desired order. It provides a simple and efficient way to sort the data in C++ but it only works on data structure which have random access to its elements such as vectors and arrays. It is defined inside <algorithm> header file. Syntaxstd::sort (first, last, comp);Paramete
4 min read
Priority Queue in C++ Standard Template Library (STL)
A C++ priority queue is a type of container adapter, specifically designed such that the first element of the queue is either the greatest or the smallest of all elements in the queue, and elements are in non-increasing or non-decreasing order (hence we can see that each element of the queue has a priority {fixed order}). In C++ STL, the top elemen
11 min read
Vector in C++ STL
Vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements are placed in contiguous storage so that they can be accessed and traversed using iterators. In vectors, data is inserted at the end. Inse
11 min read
Map in C++ Standard Template Library (STL)
Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have the same key values. std::map is the class template for map containers and it is defined inside the <map> header file. Basic std::map Member FunctionsSome basic functions associated with std::
9 min read
C++ Standard Template Library (STL)
The C++ Standard Template Library (STL) is a set of template classes and functions that provides the implementation of common data structures and algorithms such as lists, stacks, arrays, sorting, searching, etc. It also provides the iterators and functors which makes it easier to work with algorithms and containers. STL was originally designed by
9 min read
Object Oriented Programming in C++
Object-oriented programming - As the name suggests uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc. in programming. The main aim of OOP is to bind together the data and the functions that operate on them so that no other part of the code can access this data
10 min read
Operator Overloading in C++
in C++, Operator overloading is a compile-time polymorphism. It is an idea of giving special meaning to an existing operator in C++ without changing its original meaning. In this article, we will further discuss about operator overloading in C++ with examples and see which operators we can or cannot overload in C++. C++ Operator OverloadingC++ has
9 min read
Templates in C++ with Examples
A template is a simple yet very powerful tool in C++. The simple idea is to pass the data type as a parameter so that we don't need to write the same code for different data types. For example, a software company may need to sort() for different data types. Rather than writing and maintaining multiple codes, we can write one sort() and pass the dat
10 min read
Friend Class and Function in C++
A friend class can access private and protected members of other classes in which it is declared as a friend. It is sometimes useful to allow a particular class to access private and protected members of other classes. For example, a LinkedList class may be allowed to access private members of Node. We can declare a friend class in C++ by using the
6 min read
Constructors in C++
Constructor in C++ is a special method that is invoked automatically at the time an object of a class is created. It is used to initialize the data members of new objects generally. The constructor in C++ has the same name as the class or structure. It constructs the values i.e. provides data for the object which is why it is known as a constructor
7 min read
Bitwise Operators in C
In C, the following 6 operators are bitwise operators (also known as bit operators as they work at the bit-level). They are used to perform bitwise operations in C. The & (bitwise AND) in C takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1. The | (bitwise OR) in C takes two nu
7 min read
three90RightbarBannerImg