I need some extra eyes on this. I can't get this code, which plays a game of nim with the user, to stop starting over after letting the computer and user play once.
#include <iostream>
#include <string>
usingnamespace std;
int main() {
bool winner,lessthanten;
int user_turn, num, pile, comp_choice;
winner = false;
lessthanten = false;
user_turn = 0;
//winner is already false, should run fine until winner declared true.
while (winner == false) {
cout << "Welcome to the game of Nim." << endl;
cout << "To start, please enter a number greater than 10 to serve as the max range of the pile size: ";
cin >> pile;
//if pile less than ten, or invalid input, should ask for input again.
if (pile < 10 || cin.fail() &&lessthanten==false) {
cin.clear();
cin.ignore(999, '\n');
cout << "Welcome to the game of Nim. To start, please enter a number greater than 10 to serve as the max range of the pile size: ";
cin >> pile;
lessthanten = true;
}
if (pile >= 10) {
cout << "The size of the pile is " << pile << endl;
cout << "The computer plays first."<< endl;
}
//wanted turns to keep going until winner equals true.
while (user_turn % 2 == 0)
{
//random number between 1 and half of stated pile.
comp_choice = rand() % (pile / 2) +1;
pile -= comp_choice;
cout << "The Computer removed " << comp_choice<< " marbles." << endl;
cout << "The size of the pile is " << pile << "." << endl;
user_turn += 1;
//This should then initiate the user's turn.
}
if (pile == 0) {
winner = true;
cout << "You lost! The game is over!" << endl;
system("pause");
break;
}
while (user_turn % 2 == 1) {
cout << "How many marbles would you like to remove?";
cin >> num;
if (cin.fail()) {
cin.clear();
cin.ignore(999, '\n');
cout << "How many marbles would you like to remove?";
cin >> num;
}
if ((num < 1) || (num >(pile / 2)) || (pile - num <= 0)) {
cin.clear();
cin.ignore(999, '\n');
cout << "Illegal move. You must remove at least 1 or at most half of the marbles." << endl;
cin >> num;
}
elseif ((num >= 1) && (num <= pile)) {
cout << "You have removed " << num << " marbles." << endl;
pile -= num;
cout << "There are " << pile << " left in the pile." << endl;
user_turn += 1;
}
if (pile == 0) {
winner = true;
cout << "The game is over! You win!" << endl;
break;
}
}
}
cout << "Thank you for playing this game.";
system("PAUSE");
}