Skip to main content

Tic-tac-toe Game


A tic-tac-toe game in C++ using basic data structures and algorithm. In this game initially there is a matrix of size 3X3 on the console. Two players select one character each from {0, X}. Alternatively they place their character at one unused cell of the matrix. If a player makes a straight combination of three similar characters of his choice,that player wins the game otherwise game is a draw. This game was developed in C++ using code-blocks IDE.

Code :
#include <iostream>
#include<windows.h>
using namespace std;

// play matrix
char matrix[3][3] = {'1','2','3','4','5','6','7','8','9'};
char player = 'X'; // initially I have set player X's turn
int n = 0; // to count the number of cells filled

// to draw the play matrix
void Draw(){
    system("cls");// Console is made clear when Draw() function is called
    cout<<"Tic-tac-toe game v1.0"<<endl<<endl;
    for(int i=0;i<3;i++){
        for(int j=0;j<3;j++){
            cout<<matrix[i][j]<<" ";
        }
        cout<<endl;
    }
    cout<<endl;
}

// to give the input
void Input(){
    int a;
    cout<<"It's "<<player<<"'s turn.Press the number of the field: ";
    cin>>a;
    if(a==1){
        if(matrix[0][0]!='1'){
            cout<<"This field is already in use, try again"<<endl;
            Input();
        }
        else matrix[0][0]=player;
    }
    else if(a==2){
        if(matrix[0][1]!='2'){
            cout<<"This field is already in use, try again"<<endl;
            Input();
        }
        else matrix[0][1]=player;
    }
    else if(a==3){
        if(matrix[0][2]!='3'){
            cout<<"This field is already in use, try again"<<endl;
            Input();
        }
        else matrix[0][2]=player;
    }
    else if(a==4){
        if(matrix[1][0]!='4'){
            cout<<"This field is already in use, try again"<<endl;
            Input();
        }
        else matrix[1][0]=player;
    }
    else if(a==5){
        if(matrix[1][1]!='5'){
            cout<<"This field is already in use, try again"<<endl;
            Input();
        }
        else matrix[1][1]=player;
    }
    else if(a==6){
        if(matrix[1][2]!='6'){
            cout<<"This field is already in use, try again"<<endl;
            Input();
        }
        else matrix[1][2]=player;
    }
    else if(a==7){
        if(matrix[2][0]!='7'){
            cout<<"This field is already in use, try again"<<endl;
            Input();
        }
        else matrix[2][0]=player;
    }
    else if(a==8){
        if(matrix[2][1]!='8'){
            cout<<"This field is already in use, try again"<<endl;
            Input();
        }
        else matrix[2][1]=player;
    }
    else if(a==9){
        if(matrix[2][2]!='9'){
            cout<<"This field is already in use, try again"<<endl;
            Input();
        }
        else matrix[2][2]=player;
    }
}

// to toggle the turn 
void TogglePlayer(){
    if(player=='X')
        player='O';
    else
        player='X';
}

// to check whether three inputs aligned in straight are same or not
bool isSame(int a, int b, int c){
   if(a==b && b==c) return true;
   else return false;
}

// to check the winner player 
char Win(){
   for(int i=0;i<3;i++){
        // to check three inputs in a row
        if(isSame(matrix[i][0], matrix[i][1], matrix[i][2]))
           return matrix[i][0];
        // to check three inputs in a column
        if(isSame(matrix[0][i], matrix[1][i], matrix[2][i]))
           return matrix[0][i];
   }
   // to check the diagonals
   if(isSame(matrix[0][0], matrix[1][1], matrix[2][2]))
      return matrix[0][0];
   if(isSame(matrix[2][0], matrix[1][1], matrix[0][2]))
      return matrix[2][0];
   // to indicate that match is a draw
   return '/';
}


// main entry point of the program
int main()
{
    Draw(); // to setup the matrix first time
    while(1){
        Input();
        Draw(); // after input is given, screen will be made clear and again draw()
        n++; // increment the cell's count which are used (which are filled)
        if(Win()=='X'){
            cout<<"X won !"<<endl;
            break;
        }else if(Win()=='O'){
            cout<<"O won !"<<endl;
            break;
        }
        else if(Win()=='/' && n==9){
            cout<<"It's a draw match."<<endl;
            break;
        }
        TogglePlayer(); // changing the player's turn
    }
    system("pause"); // program to wait to see the output until player hits enter 
    return 0;
}

I hope you enjoy the game.

Comments

Popular Articles

Rotate the Matrix: You are given a NxN matrix.You have to rotate same coloured rectangle clockwise or anticlockwise alternatively by a ‘k’ value. K value keeps on increasing by one as we move from outer to inner loop.Suppose in the given figure outermost loop is rotated by 1 place clockwise followed by next loop rotated by 2 places anticlockwise and so on. [Give only Inplace solution]. // Picture taken from :  https://www.geeksforgeeks.org/factset-interview-experience-set-12-campus/ Solution: #include <iostream> using namespace std; #define N 5 void printMatrix (int A[][N]){     for(int i=0; i<N; i++){         for(int j=0; j<N; j++)             cout<<A[i][j]<<' ';         cout<<endl;     }     } void rotateMatrix (int A[][N]){     int l = 0, r = N-1, t = 0, b = N-1;     int k = 1; ...

Min Heap Implementation

Min heap is an almost complete binary tree in which root element's value is lesser than all children and the same rule applies for all other nodes as well. // A C++ program to showcase the common min heap operations #include <iostream> using namespace std; void swapValues(int *a, int *b){     int t = *a;     *a = *b;     *b = t; } // A class for minHeap class MinHeap {     int *harr; // pointer to array of elements in min heap     int capacity; // maximum capacity of heap     int current_size; // count of elements currently present  in heap     public:         MinHeap(int capacity); // constructor         int getMin(); // minimum element of the heap         int extractMin(); // extract minimum element from the heap         int left(int i); // index of left child of the element present at index i   ...

Snake and Fruit Game

A Snake and fruit game in C++ using basic data structures and algorithm. In this game initially there is a fruit at some random location and snake head lies in the middle of the console. By pressing left, right, top, down buttons, snake head moves accordingly. If stop button is pressed, game is paused.  If the snake eats the fruit then its tail’s length increase, score increases by ten points and a new fruit is generated at some random location in the console. If snake hits the wall or bites itself then the game will terminate. This game was developed in C/C++ using code-blocks IDE. Code :  //  header files #include <bits\stdc++.h> #include<conio.h> #include<windows.h> using namespace std; bool gameOver; // to check whether game is over or not const int width = 30;   // width of the window const int height = 20;  // height of the window int x; // current x-position of the snake int y; //  current y-pos...