Here i code a very simple program for tic tac toe. Hope you would like it. Please give comments for any kind of improvement except graphics which will make this program even more complex to understand.
// Simple Program for Tic Tac Toe Game
#include<stdio.h>
#include<conio.h>
void initialize(int a[3][3]) // initializing the matrix
{
int k=2; //avoid 0 & 1
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
a[i][j]=k;
k++;
}
}
}
int checker(int a[3][3]) // check if matrix is complete or no more space remaining
{
int count=1;
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
if((a[i][j]==0)||(a[i][j]==1))
{
count++;
}
}
}
if(count==9)
return 2;
}
int check(int a[3][3]) // check for winning of candidate
{
if((a[0][0]==a[1][1]==a[2][2])||(a[0][2]==a[1][1]==a[2][0]))
{
if((a[0][0]==0) || (a[0][2]==0))
{
printf("A Wins");
return 1;
}
else
{
printf("B Wins");
return 1;
}
}
if((a[0][0]==a[0][1]==a[0][2])||(a[1][0]==a[1][1]==a[1][2])||(a[2][0]==a[2][1]==a[2][2]))
{
if((a[0][0]==0)||(a[1][0]==0)||(a[2][0]==0))
{
printf("A Wins");
return 1;
}
else
{
printf("B Wins");
return 1;
}
}
else if((a[0][0]==a[1][0]==a[2][0])||(a[0][1]==a[1][1]==a[2][1])||(a[0][2]==a[1][2]==a[2][2]))
{
if((a[0][0]==0)||(a[0][1]==0)||(a[0][2]==0))
{
printf("A Wins");
return 1;
}
else
{
printf("B Wins");
return 1;
}
}
}
void display(int a[3][3]) // display your turn
{
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
if(a[i][j]==0)
printf("%c ",'O');
else if(a[i][j]==1)
printf("%c ",'X');
else
printf("%c ",'*');
}
printf("\n\n");
}
}
void main()
{
int a[3][3],i,j,n,n1,turn,k=0;
char user;
initialize(a);
do // Continues uptil find any winner or return 1 from check() function.
{
if(k%2==0)
{
user='A';
turn=0;
}
else
{
user='B';
turn=1;
}
printf("User %c turn\n",user);
printf("Enter Your Positions\n");
scanf("%d %d",&i,&j);
a[i][j]=turn;
display(a);
n1=checker(a);
if(n1==2)
printf("No Winner");
n=check(a);
k++;
}while(n!=1);
getch();
}
Output :
Subscribe to:
Post Comments (Atom)
0 comments:
Post a Comment