void assign(int **arr, int k)
{
int i,j;
for(i=0;i<k;i++)
{
for(j=0;j<k;j++)
{
arr[i][j]=0;
}
}
}
void display(int **arr, int k)
{
int i,j;
for(i=0;i<k;i++)
{
for(j=0;j<k;j++)
{
printf("%dt",arr[i][j]);
}
printf("n");
}
}
int input(int **arr,int m)
{
int k,i,j;
k=1;
scanf("%d%d",&i,&j);
if(arr[i][j]!=0)
{
printf("n the position has already occupiedn");
}
else
{
if(m%2==0)
{
arr[i][j]=1;
}
else
{
arr[i][j]=2;
}
k=0;
}
return k;
}
int play(int **arr, int k,int r)
{
int m=1;
printf("n please enter row(i) and column(j)>0 and <%d",k);
if(r%2==0)
{
printf("n player 1 enter your positionn");
}
else
{
printf("n player 2 enter your positionn");
}
while(m)
{
m=input(arr,r);
}
r=r+1;
return r;
}
int check(int **arr, int k)
{
int i,j,m=1,t,r=0;
int cnt1,cnt2,cnt3,cnt4;
while(m<=2)
{
cnt1=0,cnt2=0,cnt3=0,cnt4=0;
for(i=0;i<k;i++)
{
cnt1=0,cnt2=0;
for(j=0;j<k;j++)
{
if(arr[i][j]==m)
{
cnt1+=1;
}
if(arr[j][i]==m)
{
cnt2+=1;
}
if(i==j)
{
if(arr[i][j]==m)
{
cnt3+=1;
}
} //end of i==j
if((i+j)==(k-1))
{
if(arr[i][j]==m)
{
cnt4+=1;
}
} //end of i+j
} //end of j loop
printf("n value of m =%d",m);
printf("n cnt1=%d cnt2=%d cnt3=%d cnt4=%dn",cnt1,cnt2,cnt3,cnt4);
if((cnt1==k)||(cnt2==k)||(cnt3==k)||(cnt4==k))
{
r=1;
t=1;
break;
}
else
{
t=0;
}
} //end of i loop
// printf("n value of m =%dn",m);
if(r==1)
{
break;
}
m=m+1;
} //end of while
if(m==3)
{
m=m-1;
}
if(t==1)
{
return m+t;
}
else
{
return t;
}
}
int main()
{
int n,move=0,flag=0;
printf("Tic Tac Toe gamen");
printf("please enter the odd no for which square matrix has to be generatedn");
scanf("%d",&n);
if(n%2==0)
{
printf("please enter the valid odd no >0");
}
else
{
int i,j;
int **a=(int **)malloc(n*sizeof(int *));
for( i=0;i<n;i++)
{
a[i]=(int *)malloc(n*sizeof(int));
}
assign(a,n);
while(move<(n*n))
{
display(a,n);
move=play(a,n,move);
if(move>2)
flag=check(a,n);
printf("n flag value is %dn",flag);
if(flag!=0)
break;
}
display(a,n);
printf("n flag value is %dn",flag);
if(flag==0)
printf("n The game is draw");
else if(flag==2)
printf("n The player 1 has won the game");
else
printf("n The player 2 has won the game");
}
getch();
}
Responses
0 Respones to "C program for playing tic tac toe"
Post a Comment