In this article, we are going to create Tic Tac Toe Game in C++. This will be a simple console-based application in which the player can play the Tic Tac Toe game and also the player can choose from two available modes which are playing with a computer and playing with a friend. Even if you have little knowledge of C++, you will be able to follow this article and build this wonderful game. Let’s start
Features
- Two game modes are available to play. First play with a computer and second play with a friend
- Max score of both the player is updated after each round
- The player can decide to replay the game after each round
Complete Code for Tic Tac Toe Game in C++
We will use Code::Blocks IDE to develop this application. Open the Code::Blocks IDE and create a new project with the name tictactoe, now in the main.cpp file paste the following code and run it.
#include <iostream> #include<list> #include <cstdlib> #include<string> #include <ctime> using namespace std; typedef struct{ int *row; }WinList; class Player { private: string name; // used to keep the name of current player int score; // used to keep count of score of current player public: Player() :Player {""}{} Player(string n) :score{0}, name{n}{} void won(){ //increment the score score++; } //This method will return the score of current player int getScore(){ return this->score; } //This method will return the name of current player string getName(){ return this->name; } }; class Game { private: char board[9]; int emptyIndex[9]; int gameOn, againstComputer; int emptyCount; WinList winlist[8]; //This method is used to display the playing board on the screen void displayBoard(){ system("cls"); cout<<"\t\t\t<=======================================>"<<endl; cout<<"\t\t\t Welcome to the Game "<<endl; cout<<"\t\t\t Tic Tac Toe "<<endl; cout<<"\t\t\t<=======================================>"<<endl<<endl<<endl<<endl<<endl; cout <<endl; cout << "\t\t\t\t\t | | "<<endl; cout << "\t\t\t\t\t "<< board[0] <<" | "<<board[1]<<" | "<<board[2]<<endl; cout << "\t\t\t\t\t | | "<<endl; cout << "\t\t\t\t\t-----------"<<endl; cout << "\t\t\t\t\t | | "<<endl; cout << "\t\t\t\t\t "<< board[3] <<" | "<<board[4]<<" | "<<board[5]<<endl; cout << "\t\t\t\t\t | | "<<endl; cout << "\t\t\t\t\t-----------"<<endl; cout << "\t\t\t\t\t | | "<<endl; cout << "\t\t\t\t\t "<< board[6] <<" | "<<board[7]<<" | "<<board[8]<<endl; cout << "\t\t\t\t\t | | "<<endl; cout <<endl; } //This method is used to generate the input from the computer void computerInput(){ int pos; pos = rand()%10; //generate any value between 1-9 randomly // check if this space is empty if not then retry otherwise place 'O' symbol at that place if(emptyIndex[pos] == 1){ if(emptyCount < 0) return; computerInput(); } else { cout<< "Computer choose: " << pos+1 << endl; emptyIndex[pos] =1; emptyCount-=1; board[pos] = 'O'; } } //This method is used to take the input from the user and check if the inputed place is empty or not //If not empty then ask to enter again. If empty then simply place 'X' symbol void playerInput(Player &player){ int pos; cout << endl; cout << "\t " << player.getName() <<" Turn"<<endl; cout <<"\t Enter the position(1-9):" << endl; cin >> pos; pos -=1; if(emptyIndex[pos] == 1){ cout << "-----Position not empty-------"<< endl; playerInput(player); } else { emptyIndex[pos] =1; emptyCount-=1; player.getName().compare("Your") == 0 ? board[pos] ='X': board[pos] ='O'; } } //This method is used to check the winning of any player void checkWin(Player &p1,Player &p2){ int i,j,k; bool flag = false; char first_symbol; for(i=0; i<8; i++){ first_symbol = board[winlist[i].row[0]]; if((first_symbol != 'X') && (first_symbol != 'O')){ flag = false; continue; } flag = true; for(j=0;j<3;j++){ if(first_symbol != board[winlist[i].row[j]]){ flag = false; break; } } if(flag){ gameOn = 0; if(first_symbol == 'X'){ cout << "-----------------------"<< endl; cout << "\t You WIN"<< endl; cout << "-----------------------"<< endl; p1.won(); } else { p2.won(); if(againstComputer){ cout << "-----------------------"<< endl; cout << "\t Computer WON"<< endl; cout << "-----------------------"<< endl; } else { cout << "-----------------------"<< endl; cout << "\t Your friend WON"<< endl; cout << "-----------------------"<< endl; } } displayScore(p1,p2); //display the score of both the player break; } } } // This is the method which is called after the user has picked the mode void play(Player &p1,Player &p2){ char rematch ='\0'; int hand = 0; gameOn =1; displayBoard(); while((emptyCount > 0) && (gameOn != 0)){ if(againstComputer) hand == 1 ? computerInput(): playerInput(p2); else hand == 1 ? playerInput(p1): playerInput(p2); hand= !hand; displayBoard(); checkWin(p1,p2); } if (emptyCount <=0){ cout << " -----------------------"<< endl; cout << "\t No WINNER"<< endl; cout << " -----------------------"<< endl; } cout<< endl; cout << "Rematch Y/N: "; cin >> rematch; if((rematch == 'Y')||(rematch == 'y')){ init(); play(p1,p2); } } // This method is used to display the score on the screen void displayScore(Player &p1, Player &p2){ cout << endl; cout << "\t SCORE: \t"; if(againstComputer) cout<<" You: " <<p1.getScore()<<" \t Computer: "<<p2.getScore()<< endl; else cout<<" You: " <<p1.getScore()<<" \t Your friend: "<<p2.getScore()<< endl; } public: Game(): emptyCount{0}, gameOn{1}, againstComputer{0}{ init(); winlist[0].row = new int[3]{0,1,2}; winlist[1].row = new int[3]{3,4,5}; winlist[2].row = new int[3]{6,7,8}; winlist[3].row = new int[3]{0,3,6}; winlist[4].row = new int[3]{1,4,7}; winlist[5].row = new int[3]{2,5,8}; winlist[6].row = new int[3]{0,4,8}; winlist[7].row = new int[3]{2,4,6}; } void init(){ gameOn = 1; emptyCount =0; srand(time(0)); for(size_t i=0; i<10; i++){ emptyIndex[i] = 0; board[i] = ' '; emptyCount++; } emptyCount--; } //If one player game then set the first player to You and second player to computer void onePlayerGame(){ //Creating Player Player p("Your"); Player c("Computer"); cout << " -----------------------"<< endl; cout << "\t You: X \t Computer: O"<< endl; cout << " -----------------------"<< endl; cout << endl; againstComputer = 1; play(c,p); } //If two player game then set the first player to You and second player to your friend void twoPlayerGame(){ //Creating Player Player p("Your"); Player c("Your friend"); cout << " -----------------------"<< endl; cout << "\t You: X \t Your friend: O"<< endl; cout << " -----------------------"<< endl; cout << endl; againstComputer = 0; play(c,p); } }; int main() { system("color 0E"); system("title Tic Tac Toe @copyassignment"); int ch; while(1){ cout<<"\t\t\t<=======================================>"<<endl; cout<<"\t\t\t Welcome to the Game "<<endl; cout<<"\t\t\t Tic Tac Toe "<<endl; cout<<"\t\t\t<=======================================>"<<endl<<endl<<endl<<endl<<endl; cout<< " <----------Please choose the Mode---------->" << endl << endl; cout << "\t 1. Play with computer" <<endl; cout << "\t 2. Play with friend" <<endl; cout << "\t 3. To exit " <<endl; cout <<" <------------------------------------------>" << endl; cout << endl; cout <<"\t Select an option from above" << endl; cin >> ch; switch(ch){ case 1:{ Game *game = new Game; game->init(); game->onePlayerGame(); } break; case 2:{ Game *game = new Game; game->init(); game->twoPlayerGame(); } break; case 3: return 0; default: cout << "Invalid Option! TRY AGAIN"; } } return 0; }
Output for Tic Tac Toe Game in C++
Image Output:
Video Output:
Conclusion
We have built the Tic Tac Toe Game in C++ which is very simple to follow and develop. I hope you enjoyed building this cool game. Now it’s your turn to add more features in this game like asking the user for their name and instead of showing Your Turn, show the player’s name or change the terminal color and text by using different system method arguments.
Thank you for visiting our website.
Also Read:
- Simple Code to compare Speed of Python, Java, and C++?
- Falling Stars Animation on Python.Hub October 2024
- Most Underrated Database Trick | Life-Saving SQL Command
- Python List Methods
- Top 5 Free HTML Resume Templates in 2024 | With Source Code
- How to See Connected Wi-Fi Passwords in Windows?
- 2023 Merry Christmas using Python Turtle
- 23 AI Tools You Won’t Believe are Free
- Python 3.12.1 is Now Available
- Best Deepfake Apps and Websites You Can Try for Fun
- Amazon launched free Prompt Engineering course: Enroll Now
- 10 GitHub Repositories to Master Machine Learning
- Hello World in 35 Programming Languages
- How to Scrape Data From Any Website with Python?
- Become Job Ready With Free Harvard Computer Science course: Enroll Now
- Free Python Certification course from Alison: Good for Resume
- Download 1000+ Projects, All B.Tech & Programming Notes, Job, Resume & Interview Guide, and More – Get Your Ultimate Programming Bundle!
- Udacity Giving Free Python Course: Here is how to Enroll
- Love Babbar’s Income Revealed
- Top 5 Websites to Learn Programming in 2024
- Python Internship for college students and freshers: Apply Here
- Microsoft Giving Free Python Course in 2023: Enroll Now
- Top 5 Free Python Courses on YouTube in 2024
- Complete Python Roadmap for Beginners in 2024
- New secrets to Earn money with Python in 2024
- Connect with HR Directly – Job Hack
- Google offering free Python course: Enroll Today
- What is an AI Tool?
- Google Internship 2024
- TCS Launched Free Certification Course with Industry Recognized Value