Hey guys, I'm fairly new to c++ and I've been creating a NIM game. So the user picks the starting total and the maximum subtracting value. To win this game, you want to always subtract to a multiple of the maximum subtract value + 1. So for example if it was 10, you'd always want to subtract to 11 or 22 or 33 or 44. The problem im having is the computer will subtract to negative numbers to get to a multiple and i dont know why.
// Nim game
#include <iostream>
#include "stdafx.h"
usingnamespace std;
int main()
{
int total, userInput, subtractNum, computerMultiple, i, num_to_subtract;
cout << "Welcome to NIM. Pick a starting total: " << endl;
cin >> total; //gets the game's starting total
while (total < 0) //checks if the total is valid
{
cout << "Invalid input. Number must be greater than 0." << endl;
cout << "Re-enter: " << endl;
cin >> total; //gets the game's new starting total if the first total was invalid
}
cout << "Enter the maximum substraction value: " << endl;
cin >> subtractNum; //gets the game's maximum subtraction value
while (subtractNum > total || subtractNum < 1)
{
cout << "Invalid input. Number must be greater than 0 and less than the total." << endl;
cout << "Re-enter: " << endl;
cin >> subtractNum; //gets the game's new subtract maximum
}
computerMultiple = subtractNum + 1;
i = total; //loop increment
//game loop
while (true)
{
//Computer Strategy
while ((total > 0))
{
while (i >= 1)
{
if (i == 1)
{
num_to_subtract = 1;
break;
}
elseif ((i % computerMultiple != 0))
{
i--;
}
else
{
num_to_subtract = total - i;
break;
}
}
break;
}
//subtracts the computer's number from the total
total -= num_to_subtract;
cout << "I'm subtracting " << num_to_subtract << endl;
cout << "Total is now " << total << endl;
//checks if the computer has won
if (total == 0)
{
cout << "I win!" << endl;
break;
}
// players turn
cout << "Enter a number to subtract (1 - " << subtractNum << "): " << endl;
cin >> userInput;
//checks if the user input is a valid value to subtract
while (userInput < 1 || userInput > subtractNum)
{
cout << "Invalid input. Number must be between 1 and " << subtractNum << endl;
cout << "Re-enter: ";
cin >> userInput;
}
//subtracts the user input from the total
total -= userInput;
cout << "New total is " << total << endl;
if (total == 0)
{
cout << "You win!" << endl;
break;
}
}
system("PAUSE");
return 0;
}