Download as pdf or txt
Download as pdf or txt
You are on page 1of 9

Graphics with C

Explore the Unexplored

Simple Tic-Tac-Toe with C


graphics!
JULY 8, 2016AUGUST 15, 2016 / RRATHI
Want to create the famous Tic-Tac-Toe game on your own
with C graphics ? Sounds interesting, right ? (Don’t know
what is Tic-Tac-Toe ? See this
(https://en.wikipedia.org/wiki/Tic-tac-toe)).

Here below I will show you how to create a simple 2 Player


Tic-Tac-Toe game using C graphics!

What we are actually going to do ?

Take a look at the video below to understand what actually


the game will look like :

Simple TIC-TAC-TOE in C Graph

The game will be a simple 2 player game. All the inputs will
be taken from keyboard by arrow keys & space.

Note that creating a computer operated opponent will


increase the complexity of program, so, for the sake of
simplicity here we will discuss about 2 Player human game
only.
Overview of the Program :

The whole game will work in an infinite loop. The loop


will break if one of the 2 players wins, game draws or end
key(e/E) is pressed.
A 3×3 grid (3×3 two dimensional char array) will work as
backbone of the game structure. Each single cell of the
grid will contain either ‘X’,’O’ or ‘  ‘.
A two variables sx & sy will represent the selected_cell in
grid.
During each iteration of the loop, conditions of win &
draw will be checked.
Key pressed on the keyboard will decide the flow of
program, arrow keys will move the selected_cell in grid
while space will mark the player’s symbol in current
selected_cell.
Once the game ends, result msg will be shown.

The Code :

It is advised that you read the code along with its


explaination (provided after code), understand it & then try
to write it on your own. If you stuck anywhere take the help
of the code provided by me.

Don’t forget to change the path of “bgi” folder as per your


TurboC version.

1 //Graphics program for game tic-tac-toe


2  
3 #include "stdio.h"
4 #include "conio.h"
5 #include "stdlib.h"
6 #include "graphics.h"
7 #include "string.h"
8 #include "time.h"
9 #include "dos.h"
10  
11 #define d 35                //d=distance
12 #define s 30                //s=size
13 #define f 200               //f=display co
14 #define mx getmaxx()
15 #define my getmaxy()
16  
17 char grid[3][3];
18  
19 int getkey();               //To capture a
20 void display(int,int);      //To display g
21 int checkWin(int,int,int);  //Check win; r
22 int checkDraw(int,int);     //Check draw;
23 void end(char *);           //Game end
24  
25 void main()
26 {
27     int gd,gm,sx=0,sy=0,i,j,k,count=2,play
28     char str[25],ch;
29  
30     detectgraph(&gd,&gm);
31     initgraph(&gd,&gm,"C:\\TC\\BGI");
32  
33     for(i=0;i<3;i++)                      
34         for(j=0;j<3;j++)
35             grid[i][j]=' ';
36  
37     settextstyle(DEFAULT_FONT,HORIZ_DIR,2)
38  
39     while(1)
40     {
41         cleardevice();
42         //Print TIC-TAC-T   OE on screen
43         setcolor(BLUE);
44         outtextxy(200,150,"TIC-TAC-TOE");
45         //Print current Player number
46         player=count%2;
47         sprintf(str,"Player : %d (%c)",pla
48         setcolor(WHITE);
49         outtextxy(350,250,str);
50         display(sx,sy);
51         ch=getkey();            //Capture
52         switch(ch)
53         {
54             case 72:            //up arrow
55                 if(sy!=0)
56                     sy--;
57                 break;
58             case 80:            //down arr
59                 if(sy!=2)
60                     sy++;
61                 break;
62             case 75:            //left arr
63                 if(sx!=0)
64                     sx--;
65                 break;
66             case 77:            //right ar
67                 if(sx!=2)
68                     sx++;
69                 break;
70             case ' ':           //Space ke
71                 if(grid[sy][sx]==' ')     
72                 {
73                     if(player==0)
74                         grid[sy][sx]='X';
75                     else
76                         grid[sy][sx]='O';
77                     count++;
78                 }
79                 break;
80             case 'e':
81             case 'E':       //'e' or 'E' k
82                 cleardevice();
83                 closegraph();
84                 return;
85             default :
86                 break;
87         }
88         if(checkWin(sx,sy,player)==1||chec
89             break;
90     }
91     return;
92 }
93  
94 int getkey()
95 {
96     int ch;
97     ch=getch();
98     if(ch==0)
99     {
100         ch=getch();
101         return(ch);
102     }
103     return(ch);
104 }
105  
106 void display(int sx,int sy)
107 {
108     int i,j;
109     char str[2];
110     for(i=0;i<3;i++)
111     {
112         for(j=0;j<3;j++)
113         {
114             if(j==sx&&i==sy)              
115                 setcolor(RED);
116             else
117                 setcolor(WHITE);          
118             rectangle(j*d+f,i*d+f,j*d+s+f
119             sprintf(str,"%c",grid[i][j]); 
120             outtextxy(j*d+8+f,i*d+8+f,str)
121         }
122     }
123 }
124  
125 int checkWin(int sx,int sy,int player)
126 {
127     char str[25];
128     int i,j;
129     for(i=0;i<3;i++)
130     {
131         if((grid[i][0]==grid[i][1]&&grid[i
132         {
133             display(sx,sy);
134             getch();
135             sprintf(str,"Player %d (%c) Yo
136             end(str);
137             return(1);
138         }
139         if((grid[0][0]==grid[1][1]&&grid[1
140         {
141             display(sx,sy);
142             getch();
143             sprintf(str,"Player %d (%c) Yo
144             end(str);
145             return(1);
146         }
147     }
148     return(0);
149 }
150  
151 int checkDraw(int sx,int sy)
152 {
153     int i,j,k=0;
154     char str[25];
155     for(i=0;i<3;i++)
156         for(j=0;j<3;j++)
157             if(grid[i][j]!=' ')
158                 k++;
159     if(k==9)        //All cells marked but
160     {
161         display(sx,sy);
162         getch();
163         sprintf(str,"The game is draw!!!")
164         end(str);
165         return(1);
166     }
167     return(0);
168 }
169  
170 void end(char *str)
171 {
172     int i,j;
173     delay(800);
174     cleardevice();
175     setcolor(WHITE);
176     outtextxy(mx/2-150,my/2,str);
177     for(i=0,j=0;i14)
178             j=1;
179         setcolor(j);
180         sound(200*j);
181         circle(mx/2,my/2,i);
182         delay(100);
183     }
184     nosound();
185     outtextxy(mx/2-150,my/2,str);
186     getch();
187     closegraph();
188     return;
189 }

Explaination :

Global Variables :

grid[3][3] : The char grid is declared as global to avoid


frequent passing & recieving of grid between functions.

Definations :
mx & my are defined to getmaxx()
(https://graphicswithc.wordpress.com/all-about-built-in-
graphics-functions/) & getmaxy()
(https://graphicswithc.wordpress.com/all-about-built-in-
graphics-functions/).

I will not reveal the use of d, s and f. Try playing with these
three attributes to see what they actually affect in program.
(Note that these three attributes are only used for displaying
grid).

Details of program :

Variables gd & gm are used to initialize graphics mode with.

sx & sy give reference to selected_cell in the grid. (Note that


selected_grid is the RED grid you see in video).

i, j & k are simply used to iterate in loops.

player will hold the current_player during each iteration


(either 0 or 1). The variable count increases each time a
player marks his symbol. count helps to decide the value of
current_player. Note the statement player=count%2 in while
loop.

The string str is used to print variable data with outtextxy()


(see this
(https://graphicswithc.wordpress.com/2016/06/12/print-
variable-values-in-graphics-mode/) for more details). ch is
used to store keyboard input.

After initializing the graphics mode & setting the text style
the control enters the game loop.

The two outtextxy() outputs “Tic-Tac-Toe” & current_player


with its symbol on screen. Note that how sprintf() helps us in
printing variable data with outtextxy(). (See this
(https://graphicswithc.wordpress.com/2016/06/12/print-
variable-values-in-graphics-mode/) for more help).

Call to display() function outputs the whole grid to the


screen.

Here to take input from keyboard we have used getkey()


function. The input is stored in ch.

In the switch statement, the first 4 cases represent the 4


arrow keys. We want to move the selected_grid as per the
arrow key inputed. Hence, the values of sx & sy changes as
per the arrow key. Note that boundry conditions are checked
to avoid segmeentation faults!

72, 80, 75, 77 are codes of 4 arrow keys returned by getkey()


function. Note that these are not ascii codes!

If the player press “space”, the program first checks if the


current selected_cell is empty or not. If empty, we mark it
with the current_player’s symbol (either ‘X’ or ‘O’).

It is important to note that while accesing the cell we have to


use grid[sy][sx] and not grid[sx][sy]. This is because sy
represents the number of row i.e. y coordinate & sx
represents number of column i.e. x coordinate. count is
increamented so during next iteration the value of player
will get toggled.

To abort the game at any time, pressing the ‘E’ key will do the
work!

Once the control comes out of swtich case, win/draw is


checked. If the condition is true control is thrown out of the
loop else the while loop continues to iterate.

Functions :

getkey() : The function scans a character from the keyboard


& return its corresponding code in integer form. One can
simply use just getch() function instead of creating the
getkey() function, but sometimes using single getch()
function to scan arrow keys may fail. To avoid this and to be
on safer side it is advised to create getkey() function!

display() : The function recieves sx & sy i.e. reference to


selected_cell in grid & prints the whole Tic-Tac-Toe grid.
During printing if the cell is selected one it gets printed in
RED color. Remember the definations of d, s and f ? Check on
your own what these attributes actually do! The following
image shows some perticular outputs when display() is called
:

(https://graphicswithc.wordpress.com/2016/07/08/simple-tic-
tac-toe-with-c-graphics/screenshot-4/)
(https://graphicswithc.wordpress.com/2016/07/08/simple-tic-
tac-toe-with-c-graphics/screenshot-3/)

(https://graphicswithc.wordpress.com/2016/07/08/simple-tic-
tac-toe-with-c-graphics/screenshot-2/)
checkWin() : The function checks if any of the two players
has won the game or not. It returns 1 if any of the two
players win else returns 0. Note that the function recieves 3
integers sx, sy & player number. We simply check the win by
using two if statements, one check for all six horizontal &
vertical rows & columns while second if statement checks for
diagonals. Note that if true, the end() function is called which
prints the result & closes the graphmode.

checkDraw() : The function checks if the game is draw. If yes


it returns 1 else 0. Note that it recieves two integers sx & sy.
In this function we count number of “non-empty” cells & if
the count is 9, it means there are no more valid moves & the
game is draw, so we call the end() function.

end() : The funtion recieves char string which is nothing but


result string. end() will display the result message, close the
graphics mode & exits from the program. The loop displays
the growing circle on result screen & gives the sound. (To
know more about sound() & nosound() functions see this
(https://graphicswithc.wordpress.com/all-about-built-in-
graphics-functions/)). The image below shows the result
when end() is called :
What next ?

Done with the the above program ? Try to implement the


following additional features for your program on your game
to make it more fabulous!

More levels More fun : If you want to go beyond the 3×3


grid, you can try to implement different levels which will
feature different grid sizes like 3×3, 4×4, 5×5, etc. One has
to use variables to store level number, number of rows &
columns to manage all these.
Human Vs. Computer ? : To go beyond the concept of
Human Vs. Human, you can try to implement seperate
algorithm which will mark the move based on previous
move by human player!!
2 Players, Not enough ? : One can try to upgrade the game
with more than 2 players. This will add new symbols
apart from ‘X’ & ‘O’.

For any problems, corrections & suggestions comment below


or mail me @ [email protected].

Programs

One thought on “Simple Tic-Tac-Toe


with C graphics!”

You might also like