Quote:
Originally Posted by DaWei
You can't have the computer remove a random number of sticks in the range 1-3, always. You have remove a number in the range 1 to the lesser of 3 or the number of sticks left (if there are two left, you can't take 3).
You need a variable, sticksLeft. You need to compare sticksLeft to 3 and generate a random number in the range 1-3 or 1-sticksLeft, accordingly. When sticks are removed, you subtract that number from sticksLeft. When sticksLeft is zero, the game is over.
Obviously, after you've subtracted the player's number, it's the computer's turn. When the computer is through, it's the player's turn. That cycle gets broken by "game over".
|
Folks, I took a total different direction in my code. Instead of using local variables, I used global ones. The entire game works fine when a user wins and loses. But, but when the user loses, the program is not closing, it's starting over everything. I have tried to work around the loop, but still, it's not working. Here is the code
[HTML]
#include <iostream>
using namespace std;
int playSticks,removeSticks, compRemove;
//Function Declaration start here
void userWelcome();
int userInput1();
int userInput2();
int compTurn();
int main ()
{
userWelcome();
userInput1();
//the core loop of the game
do{
userInput2();
compTurn();
} while (playSticks>=0);
//return 0;
}
/* F U N C T I O N D E F I N I T I O N S S T A R T S H E R E */
void userWelcome(){
//Friendly user welcome
using namespace std;
cout<<"Weclome to the inteletual game of NIM.\n";
return;
}
int userInput1(){
do {
cout << "Please enter total number of sticks to be removed"<<endl;
cin >> playSticks;
} while (playSticks<=8);
return playSticks;
}
int userInput2()
{
cout<<"Please enter the amount of sticks to be removed. \n";
do{
cin>>removeSticks;
}while ((removeSticks>=5) || (removeSticks<=0));
playSticks=playSticks-removeSticks;
cout<<"There are "<<playSticks<<" left. \n";
if (playSticks==0)
{cout << "You win"<<endl;}
system ("PAUSE");
return 0;}
else {};
return playSticks;
}
int compTurn()
{
if (playSticks%5==0)
{
playSticks=playSticks-1;
cout<<"Computer removed 1. There are "<<playSticks<<" left \n";
return playSticks;
}
else
{
compRemove=playSticks%5;
playSticks=playSticks-compRemove;
cout<<"Computer removed "<<compRemove<<". There are "<<playSticks<<" left \n";}
if (playSticks==0)
{
cout << "You lost"<<endl;
system ("PAUSE");
return 0;
}
else {} ;
return playSticks;
}
[/HTML]
What else would you suggest to improve stylistically etc..?
Thank you