Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

C programming Implement an interactive tic tac toe game where player 2 is automa

ID: 3841892 • Letter: C

Question

C programming

Implement an interactive tic tac toe game where player 2 is automated by the computer. the game starts by printing an empty board. Each player takes turns and adds an 'X' or an 'O' to the appropriate location. the game ends when the users or the computer wins, or the board is full. Your code should employ at least the following two functions. int check_board(int x[][3]);//returns 0 if player 1 wins, 1 if player 2 wins, or 2 if lie void print.board(int x[][3]);//prints the board on screen Sample execution Player 1 enter your name: Nicholas Nicholas, Let's play tic tac toe: Player 1, enter an 'X': 1 1 the computer entered an 'O' at position: 2 2

Explanation / Answer

Answer -> I write this program in c according to the requirements of the question.

-------------------------------------------------------------------------------------------------------------------------------------------------------------

#include <stdio.h>
#include <stdlib.h>
int check_board(char[3][3]);
void user_turn(char[3][3]);
void computer_turn(char[3][3]);
void print_board(char[3][3]);
int main(void)
{
int i, j;
char p[3][3];
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
p[i][j] = ' ';
}
int result=-1;
do {
print_board(p);
user_turn(p);
result = check_board(p);
if(result > 0) break;
computer_turn(p);
result = check_board(p);
} while(result < 0);

if(result == 0)
{
printf("player 1 means user won ");
}
else if(result == 1)
{
printf("player 2 means computer won ");
}
else if(result == 2)
{
printf(" tie ");
}
print_board(p);

return 0;
}

void user_turn(char p[3][3])
{
int x, y;

printf("Enter X,Y coordinates for your move: ");
scanf("%d%*c%d", &x, &y);
x--; y--;

if(p[x][y]!= ' '){
printf("Invalid , try again. ");
user_turn(p);
}
else p[x][y] = 'X';
}

void computer_turn(char p[3][3])
{
int i, j;
for(i=0; i<3; i++){
for(j=0; j<3; j++)
if(p[i][j]==' ') break;
if(p[i][j]==' ') break;
}

if(i*j==9) {
printf("tie ");
exit(0);
}
else
p[i][j] = 'O';
}
void print_board(char x[3][3])
{
int t;

for(t=0; t<3; t++) {
printf(" %c | %c | %c ",x[t][0],x[t][1], x[t][2]);
if(t!=2) printf(" ---|---|--- ");
}
printf(" ");
}


int check_board(char x[3][3])
{
int i;

for(i=0; i<3; i++)
if(x[i][0]==x[i][1] && x[i][0]==x[i][2])
{
if(x[i][0]=='X')
{
return 0;
}
else if(x[i][0]=='O')
{
return 1;
}
}

for(i=0; i<3; i++)
if(x[0][i]==x[1][i] && x[0][i]==x[2][i])
{
if(x[0][i]=='X')
{
return 0;
}
else if(x[0][i]=='O')
{
return 1;
}
}
  

if(x[0][0]==x[1][1] && x[1][1]==x[2][2])
{
if(x[0][0]=='X')
{
return 0;
}
else if(x[0][0]=='O')
{
return 1;
}
}
  

if(x[0][2]==x[1][1] && x[1][1]==x[2][0])
{
if(x[0][2]=='X')
{
return 0;
}
else if(x[0][2]=='O')
{
return 1;
}
}

return 2;
}