My code works fine up until my while loop catches a player picking a spot already chosen. when this happens, the game gets stuck in the while loop no matter what the player chooses. the code creates a vector to store each space. when a player chooses a spot (1-9) the value of that assigned value is changed to the players mark X or O. a current game board and the instruction board, to remind players what spot is what number, is printed each turn. please help.
ttt.cpp
#include <iostream>
#include "ttt_func.hpp"
#include <vector>
int main() {
std::vector<char> answer = {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '};
int turns = 1;
int player_choice;
char player1 = 'X';
char player2 = 'O';
while (turns <= 9) {
if (turns % 2 == 0) {
std::cout << "Player 2 pick a box (1-9)\n\n";
std::cout << " 1 | 2 | 3 \n";
std::cout << "___|___|___\n";
std::cout << " 4 | 5 | 6 \n";
std::cout << "___|___|___\n";
std::cout << " 7 | 8 | 9 \n";
std::cout << " | | \n";
std::cin >> player_choice;
while (answer[player_choice - 1] == 'X' || answer[player_choice - 1] == 'O') {
pick_again(answer, player_choice);
for(int i = 0; i < answer.size(); i++){
std::cout << answer[i] << " ";
}
std::cout << "\n\n";
}
answer[player_choice - 1] = player2;
display_board(answer);
} else {
std::cout << "Player 1 pick a box (1-9)\n\n";
std::cout << " 1 | 2 | 3 \n";
std::cout << "___|___|___\n";
std::cout << " 4 | 5 | 6 \n";
std::cout << "___|___|___\n";
std::cout << " 7 | 8 | 9 \n";
std::cout << " | | \n";
std::cin >> player_choice;
while (answer[player_choice - 1] == 'X' || answer[player_choice - 1] == 'O') {
for(int i = 0; i < answer.size(); i++){
std::cout << answer[i] << " ";
}
pick_again(answer, player_choice);
}
}
answer[player_choice - 1] = player1;
display_board(answer);
}
turns ++;
}
}
ttt_func.cpp
#include <vector>
#include <iostream>
void display_board(std::vector<char> answer) {
std::cout << " " << answer[0] << " | " << answer[1] << " | " << answer[2] << " \n";
std::cout << "___|___|___\n";
std::cout << " " << answer[3] << " | " << answer[4] << " | " << answer[5] << " \n";
std::cout << "___|___|___\n";
std::cout << " " << answer[6] << " | " << answer[7] << " | " << answer[8] << " \n";
std::cout << " | | \n";
}
void pick_again(std::vector<char> answer, int player_choice) {
std::cout << "Box already chosen, pick again\n";
display_board(answer);
std::cout << "\n 1 | 2 | 3 \n";
std::cout << "___|___|___\n";
std::cout << " 4 | 5 | 6 \n";
std::cout << "___|___|___\n";
std::cout << " 7 | 8 | 9 \n";
std::cout << " | | \n";
std::cin >> player_choice;
}
ttt_func.hpp
type or paste code here
#include <vector>
void display_board(std::vector<char> answer);
void pick_again(std::vector<char> answer, int player_choice);