Trying to complete an assignment for a simple tic tac toe game without using functions or anything that has not been covered in our class. Currently everything in the code is acceptable but I keep getting an infinite loop issue when picking a square and using a character that is not a number. Any help would be appreciated!
#include <iostream>
using namespace std;
int i;
char board[10];
bool gameover;
bool check_choice;
char player;
int choice = 0;
char restart;
int main()
{
do
{
for (int i = 0; i < 10; i++) board[i] = ' ';
bool gameover = false;
bool check_choice = true;
char player = 'X';
do
{
// Draw game board
cout << "+---+---+---+ \n";
cout << "| " << board[1] << " | " << board[2] << " | " << board[3] << " | \n";
cout << "+---+---+---+ \n";
cout << "| " << board[4] << " | " << board[5] << " | " << board[6] << " | \n";
cout << "+---+---+---+ \n";
cout << "| " << board[7] << " | " << board[8] << " | " << board[9] << " | \n";
cout << "+---+---+---+ \n";
// Win Check
if ((board[1] == 'X' && board[2] == 'X' && board[3] == 'X') ||
(board[4] == 'X' && board[5] == 'X' && board[6] == 'X') ||
(board[7] == 'X' && board[8] == 'X' && board[9] == 'X') ||
(board[1] == 'X' && board[4] == 'X' && board[7] == 'X') ||
(board[2] == 'X' && board[5] == 'X' && board[8] == 'X') ||
(board[3] == 'X' && board[6] == 'X' && board[9] == 'X') ||
(board[1] == 'X' && board[5] == 'X' && board[9] == 'X') ||
(board[3] == 'X' && board[5] == 'X' && board[7] == 'X'))
{
cout << "Game Over - X wins! \n";
gameover = true;
}
else if ((board[1] == 'O' && board[2] == 'O' && board[3] == 'O') ||
(board[4] == 'O' && board[5] == 'O' && board[6] == 'O') ||
(board[7] == 'O' && board[8] == 'O' && board[9] == 'O') ||
(board[1] == 'O' && board[4] == 'O' && board[7] == 'O') ||
(board[2] == 'O' && board[5] == 'O' && board[8] == 'O') ||
(board[3] == 'O' && board[6] == 'O' && board[9] == 'O') ||
(board[1] == 'O' && board[5] == 'O' && board[9] == 'O') ||
(board[3] == 'O' && board[5] == 'O' && board[7] == 'O'))
{
cout << "Game Over - O wins! \n \n";
gameover = true;
}
// Draw Check
else if ((board[1] != ' ' && board[2] != ' ' && board[3] != ' ') &&
(board[4] != ' ' && board[5] != ' ' && board[6] != ' ') &&
(board[7] != ' ' && board[8] != ' ' && board[9] != ' '))
{
cout << "Game Over - Draw \n \n";
gameover = true;
}
else
check_choice = true;
while (check_choice == true)
{
cout << "Place " << player << " at: ";
cin >> choice;
if (choice > sizeof(board) || choice == 0 || choice == 10)
{
cout << "Invalid input! 1-9 only. \n";
check_choice = true;
}
else if (board[choice] == ' ')
{
board[choice] = (player == 'X') ? 'X' : 'O';
player = (player == 'X') ? 'O' : 'X';
check_choice = false;
}
else
{
cout << "Invalid input! Position already filled. \n";
check_choice = true;
}
}
} while (gameover == false);
cout << "Would you like to play again? (Y / N): ";
cin >> restart;
cin.ignore();
} while (restart == 'y' || restart == 'Y');
cout << "Thanks for playing!! \n \n";
system("pause");
return 0;
}