You have most of the logic right, but the sequencing is wrong. Remember that the code executes sequentially.
Line 28 Since the human just moved, it doesn't matter whether c_pick == 1, the human wins if toothpicks == 1 regardless of what the computer's last move was.
Line 32: You need to exit the loop at this point, so I'd change it to
break;
.
Lines 34-45 set c_pick, but you never actually subtract this amount from toothpicks. Do that just before line 46.
Line 46: Now you're checking if the computer won. There's no need to check if h_pick==1, the computer wins if there is one toothpick left regardless of the human's last move.
Line 49: I'd change this to
break;
Lines 50-54: These should move to right after line 23. After all, you want to validate the human's input right after they give it.
Lines 55-61: This code asks whether the player wants to play again. It should go outside the play loop, so after line 62.
Line 66 is outside both loops. Get rid of it.
That should make the program work.
It looks to me like you get confused about what is happening where. That's easy to do. One way to avoid this problem is to use functions. For example you might write:
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
|
void playOneGame(); // plays the game
int getHumanMove(); // get the human's move. Keep prompting until it's valid
int getComputerMove(); // get the computer's move.
bool playAgain(); // ask user if they want to play again. Return true if yes.
int main()
{
do (
playOneGame();
} while (playAgain());
}
playOneGame()
{
int toothpicks = 23;
int pick;
while (true) {
// do the human's move
pick = getHumanMove();
toothPicks -= pick;
if (toothPicks == 1) {
cout << "You won!\jn";
break;
}
// Do the computer's move
pick = getComputerMove();
toothPicks -= pick;
if (toothPicks == 1) {
cout << "Computer won!\n";
break;
}
}
}
|
etc.
You will find that some of the functions need access to some data. For example, getComputerMove() needs to know what the human's move was. So you'll have to pass that as a parameter. Better yet, the values would be members of a class and the functions would be methods.