Hello. I'm writing code for what is essentially the nim game, however i cant for the life of me figure out how to get my code to switch between players. I've checked everything over and over, and yet still when i run the program, it just stays on player 1's turn the entire time. Can anyone please help me understand why it won't switch to player 2?
////////////////////////////////
void mainmenu()
{
cout<<"Main menu:"<<endl;
cout<<"1. Play against another person."<<endl;
cout<<"2. Play against computer."<<endl;
cout<<"3. Exit."<<endl;
}
////////////////////////////////
int switchplayer(int player)
{
int mode; int numstones; int p1=0; int p2=0; int stonestaken;
double cp;
srand(time(NULL));
cout<<"Welcome to the last stone game"<<endl;
mainmenu();
cin>>mode;
while (mode>0 && mode<3)
{
if (mode ==1 )
{
cout<<"1. Play against another person."<<endl;
string pname1; string pname2;
cout<<"Enter name for Player 1"<<endl;
cin>>pname1;
cout<<"Enter name for Player 2"<<endl;
cin>>pname2;
numstones = rand()%(11)+10;
cp= 1;
while (numstones>0)
{
if(cp==1)
{
cout<<"Number of stones: "<<numstones<<endl;
cout<<pname1<<", PLAYER 1's Turn."<<endl;
cout<<"How many stones will you take?"<<endl;
cin>>stonestaken;
}
else
{
cout<<"Number of stones: "<<numstones<<endl;
cout<<pname2<<", PLAYER 2's Turn."<<endl;
cout<<"How many stones will you take?"<<endl;
cin>>stonestaken;
}
numstones= numstones-stonestaken;
cp= player;
}
if (cp ==1)
{
cout<<"Player 2 wins!"<<endl;
}
if (cp ==2)
{
cout<<"Player 1 wins!"<<endl;
}
if (mode==2)
{
cout<<"2. Play against computer."<<endl;
}
You never change the cp. After player 1 chooses some stones, cp = 2;. Likewise, after player 2 chooses some stones, cp = 1;.
BTW, Nim is supposed to be played with multiple piles. Otherwise the first player can always force a win by simply taking all the stones. (Or taking all but one, if taking the last stone is considered losing.)
The most common variant is three piles, which makes writing code easy: int numstones[3];
Initialize each pile of stones with some random number, let the player choose both a pile and a number of stones, and display the number of stones in each pile.