This is the first time I posted here and I hope that you guys can help me.
The code below is program which is a Tic Tac Toe Game. I finished it with some help from my sister and there is this part in the code where I dont really get it.
The part where I dont get is the check(void). There is this two for looops which calls board[i][0], which is a character but inside the for loops it adds with an integer. Thats the part I dont get. How am I gonna know the value of *p+1? Is it possible to add an integer with a char? What is the answr then?
The second thing is the IF Statement. I undertand the condition but not what it will do if it satisfies it. What will happen if you return *p or return board[0][0]? Does that makes sense?
Sorry if my question seems to be weird, I'm just a newbie.
Anyways here is the code:
Code:
/*This program creates a Tic Tac Toe game without any AI.*/
#include<stdio.h>
#include<stdlib.h>
#define SPACE ' '
char board[3][3]={SPACE,SPACE,SPACE,SPACE,SPACE,SPACE,SPACE,SPACE,SPACE};
void get_player_move(void),
get_nextplayer_move(void);
void disp_board(void);
int check(void);
main()
{
char done;
printf("This is the game of Tic-Tac-Toe.\n\n");
done=SPACE;
do
{
disp_board();
get_player_move();
done=check();
if(done!=SPACE) break;
printf("\n");
disp_board();
get_nextplayer_move();
done=check();
}
while(done==SPACE);
if(done=='X')
{printf("X is the winner!\n\n");}
else
{printf("O is the winner!!!!\n\n");}
printf("\n");
disp_board();
printf("\n\n");
system("pause");
}
/*The below code is responsible for the input and output of X.*/
void get_player_move(void)
{
int x,y;
printf("\nEnter Column for your X: ");
scanf("%d", &x);
printf("Enter Row for your X: ");
scanf("%d", &y);
x--;y--;
if(board[x][y]!=SPACE)
{
printf("\nInvalid move,try again.\n");
get_player_move();
}
else
{board[x][y]='X';}
printf("\n");
}
/*The below code is responsible for the input and output of Y.*/
void get_nextplayer_move(void)
{
int x,y;
printf("\nEnter Column for your Y: ");
scanf("%d", &x);
printf("Enter Row for your Y: ");
scanf("%d", &y);
x--;y--;
if(board[x][y]!=SPACE)
{
printf("\nInvalid move,try again.\n");
get_nextplayer_move();
}
else
{board[x][y]='O';}
printf("\n");
}
/*This code is responsible for displaying the Tic Tac Toe Board.*/
void disp_board(void)
{
int i;
for(i=0;i<3;i++){
printf(" %c | %c | %c ", board[i][0],
board[i][1], board[i][2]);
if(i!=2)
{printf("\n---|---|---\n");}
}
printf("\n");
}
/*This code is responsible for checking if the spaces are occupied or not.*/
check(void)
{
int i;
char *p;
for(i=0;i<3;i++)
{
p=&board[i][0];
if (*p==*(p+1) && *(p+1)==*(p+2))
{return *p;}
}
for(i=0;i<3;i++)
{
p=&board[0][i];
if(*p==*(p+3) && *(p+3)==*(p+6))
{return *p;}
}
if(board[0][0]==board[1][1] && board[1][1]==board[2][2])
{return board[0][0];}
if(board[0][2]==board[1][1] && board[1][1]==board[2][0])
{return board[0][2];}
return SPACE;
}