Game of nim vs computer.

After i choose my marbles and the computer chooses it's marbles. I get to choose again but for some reason the number of marbles left resets to 35 instead of being subtracted again. Can anyone see why ? Thanks in advanced. Oh and rules are in the beginning of the program.

#include <iostream>
#include <ctime>
#include <cstdlib>

using namespace std;

const int HUMAN = 1;
const int COMPUTER = 0;

int getHumanMove(int);
int getComputerMove(int);
void playTheGame(int player);


int main()
{
int currentPlayer = 0;
char choice = ' ';
int marbles = 35;
bool i = false;

cout << "Welcome to the game of NIM!" << endl;
cout << "---------------------------" << endl;
cout << "---------------------------" << endl;
cout << endl;
cout << "Rules of the game: " << endl;
cout << "1. The game begins with 35 marbles in a jar." << endl;
cout << "2. Each player must take between 1-5 marbles from the jar." << endl;
cout << "3. The player to take the last marble wins." << endl << endl;;


cout << "Would you like to go first(Y/N)?: ";
cin >> choice;
choice = toupper(choice);

do
{
switch (choice)
{
case 'Y':
currentPlayer = HUMAN;
break;
case 'N':
currentPlayer = COMPUTER;
break;
default:
cout << "Invalid choice try again: " << endl;
}
playTheGame(currentPlayer);
} while (marbles > 0);



system("pause");
return 0;
}
int getHumanMove(int numMarbles)
{
int choice = 0;
cout << "How many marbles do you want to take(1-5)?" << endl;
cin >> choice;
while (choice > numMarbles || choice > 5 || choice < 1)
{
cout << "Invalid number try again: " << endl;
cin >> choice;
}
numMarbles = numMarbles - choice;
cout << "There are " << numMarbles << " marbles left in the jar " << endl;
return choice;
}
int getComputerMove(int numMarbles)
{
srand(time(0));
numMarbles = 1 + (rand() % 5);
cout << "The computer took " << numMarbles << " marble(s). " << endl;

return numMarbles;
}
void playTheGame(int player)
{
int numMarbles = 35;
int currentMove = 0;
int marblesLeft = 0;

while (numMarbles > 0)
{
if (player == HUMAN)
{
currentMove = getHumanMove(numMarbles);
if (marblesLeft = 0)
{
cout << "Winner!!" << endl;
}
numMarbles = numMarbles - currentMove;
cout << numMarbles << " marbles left" << endl;
}
else if (player == COMPUTER)
{
currentMove = getComputerMove(numMarbles);
marblesLeft = numMarbles - currentMove;

cout << marblesLeft << " marbles left" << endl;
if (numMarbles = 0)
{
cout << "Loser!!" << endl;
}
marblesLeft = numMarbles - currentMove;
}
player = !player;
}

}
The marbles variable needs to be global. In the playTheGame function, you don't update the numMarbles value to the overall marbles value, at the end of the function you don't update the marbles value to match marblesLeft. numMarbles and marblesLeft should all just be marbles. It would be awesome if instead of making marbles global, you wrapped this all up into a class so that marbles could be a member variable. Games with out chance rock!
Last edited on
Topic archived. No new replies allowed.