Tic Tac Toe - Game programming

This tutorial will teach how to code the game Tic Tac Toe. The game is pretty simple , all you have to do is to get your symbols(usually ‘X’ or ‘0’) in straight line of three .

Requirements

Graphic Library Used - Turbo C/C++ Bgi

For this program we assume Turbo C++ 3.0 IDE and installed in folder C:\TC (Please choose same directory name to keep things simple). 

This program is essentially console based and works in Windows XP (or) lower and requires to be run in fullscreen mode.

Game Setup

We first create data the game needs . In this game we need following data -

We need a 2D 3 X 3 Matrix to store the board. Each member of the board contains one the three values -

  • 'O' if there is a zero at that place.
  • 'X' if there is a cross at that place
  • '*' if there is no element at that place ie. placed has not yet been filled.
  • Now that the game data is ready, we initialize the entire board to '*'. This indicates that no block is filled.

We use a function called startboard() called in main to do this job for us.

Thus the code developed is:

 

 

#include <graphics.h>
#include <conio.h>
 
char board [3] [3]; 
 
void startboard ()
{
 int i,j;
 for (i = 0; i <= 2 ; i++)
  {
   for (j = 0; j <= 2; j++)
     {
       board [i] [j] = '*';
     }
  }
}
int main ()
{
  int gdriver = DETECT, gmode;
  initgraph (&gdriver, &gmode, "c:\\tc\\bgi");
  startboard ();
  getch ();
  closegraph ();
  return 0;
}
 

 

 

 

 

Mapping Board 

Now that the game is setup we have to initialize the graphics engine and draw a graphical image of the board from the array data.

The function drawboard() does this job. It first clears all the graphics on the present screen. Then it initiates the graphics and redraws the entire screen. It then draws the border lines. And thereafter draws a cross, a circle or nothing depending upon the values in the array.

It uses function drawcircle() and drawcross() to draw circles and cross respectively. These function take input value 0 to 9 depending upon the array position to decide what to draw.

This function is first called in initialization but will be called several times 

we call this function drawboard()-

 

void drawcircle (int position) // Draws a circle on basis of Input use mathematics reduce complexity
{
  int centrex;
  int centrey;
  centrex = 245 + (50*(position%3)) + 25;
  centrey = 165 + (50*(position/3)) + 25;
  fillellipse (centrex,centrey, 10,10);
}
void drawcross (int position)
{
 int centrex;
 int centrey;
 centrex = 245 + (50*(position%3)) + 25;
 centrey = 165 + (50*(position/3)) + 25;
 line (centrex-5,centrey+5,centrex+5,centrey-5);
 line (centrex+5,centrey+5,centrex-5,centrey-5);

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

void drawboard ()
{
 int gdriver = DETECT, gmode;
 int i,j;
 closegraph ();
 initgraph (&gdriver, &gmode, "c:\\tc\\bgi");
 // Draw 4 Lines to Form Board
 line (295,165,295,315);
 line (345,165,345,315);
 line (245,215,395,215);
 line (245,265,395,265);
 for (i = 0; i <= 2; i++)
    {
      for (j = 0; j <= 2; j++)
            {
              if ( board [i] [j]  == 'X') drawcross (3*i + j);
              if ( board [i] [j]  == 'O') drawcircle (3*i + j);
            }
    }
 

 

Game Engine -

The game engine is basically a loop that terminates after 5 user moves. It must do the following jobs in one sequence for every user turn:

Take user input .

Place user move on board.

Calculate computer move.

Place computer move on board.

Refresh Screen for next round.

Check wether there is a winner.

we use function play to be name of our game engine and game exits when the function exits. This function is called once in main.

User Input 

We create a function named user_input() which does the first two jobs of our game engine. It takes user input and if valid places that on to the data.

User is asked to input X coordinate (1 - 3) and Y coordinate (1 - 3).

If in our data board [X-1] and [Y-1] position is '*' then we place a 'X' There otherwise re-prompt for input.

The required functions are:

 

void user_input ()
{
  int x,y;
  printf ("\nEnter X Coordinate - ");
  scanf ("%d",&x);
  printf ("\nEnter Y Coordinate - ");
  scanf ("%d", &y);
  if (board [x-1] [y-1] == '*')
     {
       board [x-1] [y-1] = 'X';
     }
  else
     {
       drawboard ();
       printf ("\nWrong Coordinates");
       input ();
     }
}
void play () // Ladies and Gentleman I give you our game engine.
         
{
  int i;
  for (i = 0; i<5;i++)
    {
      input ();
      drawboard ();
    }
}
int main ()
{
  int gdriver = DETECT, gmode;
  initgraph (&gdriver, &gmode, "c:\\tc\\bgi");
  startboard ();
  play ();
  getch ();
  closegraph ();
  return 0;
}
 

 

Computer Move 

Now after user move we need to make the computer move. Since this first version of the Article we will be using simple AI .

Our AI starts from the first box and where ever it finds first empty space it puts a zero. 

We call this function computer.

The required functions are

 

void computer ()
{
  int i,j;
  for (i = 0; i < 3; i++)
  for (j = 0; j < 3; j++)
    {
      if (board [i] [j] == '*')
         {
            board [i] [j] = 'O';
            return;
         }
    }
}
void play () //game engine


{
  int i;
  for (i = 0; i<5;i++)
    {
       user_input ();
       computer ();
       drawboard ();
    }
printf ("\n\nGAME DRAW");
}
int main ()
{

 int gdriver = DETECT, gmode;
 initgraph (&gdriver, &gmode, "c:\\tc\\bgi");
 startboard ();
 play ();
 getch ();
 closegraph ();
 return 0;
}
 
 

 

 

Checking Winner 

Now last thing our game engine must do is to see wether we have a winner or not.

This function use a flag variable key (arbitary name) which is initialise to '*'

Then our function checks all possible combination of winning and if it finds a character other than '*' in series of 3 it sets key value to it.

Then we calculate whether player wins, computer wins or nobody wins and game is still 

Now here is the final code of this version - 

 

#include <graphics.h>
#include <conio.h>
          
char board [3] [3]; // Remeber Indexing Starts at zero
void drawcircle (int position) // Draws a circle on basis of Input use mathematics reduce complexity
{
  int centrex;
  int centrey;
  centrex = 245 + (50*(position%3)) + 25;
  centrey = 165 + (50*(position/3)) + 25;
  fillellipse (centrex,centrey, 10,10);
}
void drawcross (int position)


{   
  int centrex;
  int centrey;
  centrex = 245 + (50*(position%3)) + 25;
  centrey = 165 + (50*(position/3)) + 25;
  line (centrex-5,centrey+5,centrex+5,centrey-5);
  line (centrex+5,centrey+5,centrex-5,centrey-5);
}
void drawboard ()


{
 int gdriver = DETECT, gmode;
 int i,j;
 closegraph ();
 initgraph (&gdriver, &gmode, "c:\\tc\\bgi");
 
 // Draw 4 Lines to Form Board
 line (295,165,295,315);
 line (345,165,345,315);
 line (245,215,395,215);
 line (245,265,395,265);
 for (i = 0; i <= 2; i++)
    {
      for (j = 0; j <= 2; j++)
         {
           if ( board [i] [j]  == 'X') drawcross (3*i + j);
           if ( board [i] [j]  == 'O') drawcircle (3*i + j);
         }
    }
}
void startboard ()


{
  int i,j;
  for (i = 0; i < 3 ; i++)
    {
      for (j = 0; j < 3; j++)
        {
           board [i] [j] = '*';
           putchar (board [i] [j]);
        }
    }
drawboard ();
}
void user_input ()
{
  int x,y;
  printf ("\nEnter X Coordinate - ");
  scanf ("%d",&x);
  printf ("\nEnter Y Coordinate - ");
  scanf ("%d", &y);
  if (board [x-1] [y-1] == '*')
   {
     board [x-1] [y-1] = 'X';
   }
  else
   {
     drawboard ();
     printf ("\nWrong Coordinates");
     user_input ();
   }
}
void computer ()


{
  int i,j;
  for (i = 0; i < 3; i++)
    for (j = 0; j < 3; j++)
      {
        if (board [i] [j] == '*')
          {
            board [i] [j] = 'O';
            return;
          }
      }
}
void check ()
{
  int i;
  char key = '*';
    
  // Check Rows
  for (i=0; i<3;i++)
         if (board [i][0] == board [i] [1] && board [i][0] == board [i] [2] && board [i] [0] != '*') key = board [i] [0];
   
 // Check Columns
 for (i=0; i<3;i++)
        if (board [0][i] == board [1] [i] && board [0][i] == board [2] [i] && board [0] [i] != '*') key = board [0] [i];
         
 // Check Diagonals
 if (board [0][0] == board [1] [1] && board [1][1] == board [2] [2] && board [1] [1] != '*') key = board [1] [1];
 if (board [0][2] == board [1] [1] && board [1][1] == board [2] [0] && board [1] [1] != '*') key = board [1] [1];
 //Declare Winner if any
 if (key == 'X')
       {
         printf ("You Win");
         getch ();
         exit ();
       }
 if (key == 'O')
       {
         printf ("Computer Win");
         getch ();
         exit ();
      }
}
void play () // Ladies and Gentleman I give you our game engine.


{
  int i;
  for (i = 0; i<5;i++)
    {
      user_input ();
      computer ();
      drawboard ();
      check ();
    }
printf ("\n\nGAME DRAW");
}
int main ()
{
  int gdriver = DETECT, gmode;
  initgraph (&gdriver, &gmode, "c:\\tc\\bgi");
  startboard ();
  play ();
  getch ();
  closegraph ();
  return 0; 
}
 

 

 

Comments

Member since:
18 February 2009
Last activity:
1 year 21 weeks

Hi msdewana,

Please create a new forum topic for this, I will reply to it.

Founder and Admin

Member since:
3 April 2010
Last activity:
6 years 44 weeks

 can u explain each function like gmode,gdriver,initgraph ,why are you passing this in initgraph"c:\\tc\\bgi", how to take dimensions please tell.i am beginner in graphics in c. please sir guide me how i understand graphics in c 

Member since:
9 February 2010
Last activity:
7 years 17 weeks

A simple comparison vedio consists of a room full of battery-operated bunnies was seen pounding their drums,all slowing down except one with the Energizer battery.

Member since:
25 February 2010
Last activity:
7 years 17 weeks

I wonder what it requires to do gaming programming.

I think it requires talent, passion & creativity & for sure, mastering the programming language as well.

I think this the secret behind their success.

Member since:
10 February 2010
Last activity:
7 years 6 weeks

It is very informative. Thanks for sharing it.

You obviously put a lot of work into that post and its very interesting to see the thought process that you went through to come up with those conclusion. Thanks for sharing your deep thoughts. I must admit that I think you nailed it on this one.

Member since:
10 February 2010
Last activity:
7 years 6 weeks

It is always hard to predict what the next generation of video game could possibly be online as the industry sector of online gaming is developing at dramatic speed. Ever since the most traditional version of Mario Games till the latest online games, a lot of changes have been made in the business sector.

 

Note:- This post has been edited by BGNenterpreneur at Wed, 2010-02-10 00:32.

Member since:
9 February 2010
Last activity:
7 years 17 weeks

Services were created to allow players to be automatically matched against another player wishing to play or lobbies were formed where people could meet in so called game rooms. An example was the MSN Gaming Zone where online game communities were formed by active players for games.

Regards,

Free Online Games

Member since:
12 April 2009
Last activity:
3 years 47 weeks

hi kutariyar
what problem are you facing in running the program? 

Member since:
1 November 2009
Last activity:
7 years 34 weeks

Thanks ...

 

bur how we can run our program

Member since:
28 May 2009
Last activity:
4 years 47 weeks

Thanks a lot....

Keep Learning and posting