Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

this is the current code i have for C + + to make a tic tac toe game but when I try to execute it

this is the current code i have for C++ to make a tic tac toe game but when I try to execute it, it doesn't leave an X or a O in the slots the player picks and i need some help?
#include
#include
#include
#define SIZE 3
#define EMPTY -1
void initializeBoard(int board[SIZE][SIZE]){
int num =1;
for (int i =0; i < SIZE; i++){
for (int j =0; j < SIZE; j++){
board[i][j]= num++;
}
}
}
void printBoard(int board[SIZE][SIZE]){
printf("
");
for (int i =0; i < SIZE; i++){
for (int j =0; j < SIZE; j++){
if (board[i][j]==EMPTY){
printf("");
}else {
printf("%d ", board[i][j]);
}
if (j < SIZE -1) printf("|");
}
printf("
");
if (i < SIZE -1) printf("---+---+---
");
}
printf("
");
}
int checkWin(int board[SIZE][SIZE]){
for (int i =0; i < SIZE; i++){
if (board[i][0]== board[i][1] && board[i][1]== board[i][2]) return board[i][0];
if (board[0][i]== board[1][i] && board[1][i]== board[2][i]) return board[0][i];
}
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 EMPTY;
}
int checkTie(int board[SIZE][SIZE]){
for (int i =0; i < SIZE; i++){
for (int j =0; j < SIZE; j++){
if (board[i][j]!= EMPTY) return 0;
}
}
return 1;
}
int main(){
int board[SIZE][SIZE];
int currentPlayer, choice, row, col, winner, playAgain;
char symbols[]={'X','O'};
srand(time(NULL));
do {
initializeBoard(board);
currentPlayer = rand()%2;
winner = EMPTY;
while (1){
printBoard(board);
printf("Player %c, enter your choice: ", symbols[currentPlayer]);
scanf("%d", &choice);
if (choice <1|| choice >9){
printf("Invalid choice! Please choose a number between 1 and 9.
");
continue;
}
row =(choice -1)/ SIZE;
col =(choice -1)% SIZE;
if (board[row][col]== EMPTY){
printf("Invalid choice! Please choose an empty cell.
");
continue;
}
board[row][col]= EMPTY;
if((winner = checkWin(board))!= EMPTY){
printBoard(board);
printf("Plater %c wins!
", symbols[winner]);
break;
}
currentPlayer =1- currentPlayer;
}
printf("Do you want to play again? (1 for yes, 0 for No): ");
scanf("%d", &playAgain);
} while (playAgain);
return 0;
}

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Database Concepts

Authors: David M. Kroenke, David J. Auer

7th edition

133544621, 133544626, 0-13-354462-1, 978-0133544626

Students also viewed these Databases questions