need way to switch between players' turns in pick up sticks

#include<iostream>
using namespace std;

int main(){
cout<<"*** Welcome to Pickup Sticks ***"<<endl;
string name1, name2, playerTurn;
int sticks, sticksTaken;
char ans;
sticks = 21;
do{
cout<<"Enter name of player 1: ";
cin>>name1;
cout<<"Enter name of player 2: ";
cin>>name2;
cout<<endl;

while(sticks!=0){
cout<<"("<<sticks<<")";
for(int i = 0; i < sticks; i++)
cout<<"|"<<" ";
cout<<endl;
cout<<playerTurn<<"-How many sticks? ";
cin>> sticksTaken;
if((sticksTaken<1)||(sticksTaken>3))
cout<<"Sorry, you must take between 1 and 3 sticks."<<endl;
else{
if(sticks>=3)
sticks-=sticksTaken;
else if(sticks==2){
if(sticksTaken==3)
cout<<"Sorry, only 2 sticks left!"<<endl;
else if(sticksTaken==2)
sticks-=sticksTaken;
cout<<" wins!"<<endl;
else
sticks-=sticksTaken;
cout<<playerTurn<<"wins!"<<endl;
}
else{
if((sticksTaken==3)||(sticksTaken==2))
cout<<"Sorry, only 1 stick left!"<<endl;
else
sticks-=sticksTaken;
cout<<"wins!"<<endl;
break;
}
}
//winning statement
}
cout<<"Play Again? (Y/N)";
cin>>ans;
}while(ans=='y'||ans=='Y');
cout<<endl;
cout<<"*** Thanks for playing Pickup Sticks ***"<<endl;

return(0);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <string>
#include <algorithm>

int main()
{
    std::string name1, name2 ;
    std::cout << "Enter name of player 1: ";
    std::cin >> name1;
    std::cout << "Enter name of player 2: ";
    std::cin >> name2;

    int sticks = 21 ;
    int current_player = 1 ; // start with name1

    while( sticks > 0 )
    {
        // display sticks
        std::cout << "\n\nsticks (" << sticks << "): " << std::string( sticks, '|' ) << '\n' ;

        const int max_pick = std::min( sticks, 3 ) ; // maximum that can be picked

        int npick = 0 ;
        while( npick < 1 || npick > max_pick )
        {
            std::cout << ( current_player == 1 ? name1 : name2 ) // show current players name
                      << ", how many sticks? [1-" << max_pick << "]? " ;
            std::cin >> npick ;
        }

        sticks -= npick ;

        // switch between the players turns
        if( current_player == 1 ) current_player = 2 ; else current_player = 1 ;
    }
}
Topic archived. No new replies allowed.