mardi 19 septembre 2017

23 STICKS GAME, NESTED LOOPS AND LOGIC ERRORS

I haveseen similar questions to my own on this forum, however, rather tahn copying the program, I worked mine from scratch and would like to better understand how to nest my loops properly. The game is a user vs computer game where you can take 1, 2 or 3 sticks for your turn and the comp will pick 4-theuserPick. Once there are at least 4 sticks left, the comp will choose the most amont of sticks to leave the user with 1, which will make the user loose. cpu always wins / Please help me understand how I need to be nesting the if/else statements for the loops in order to ontinue promting the user for an input so it goes back and forth between the cpu, and then then ultimatley prompts the user for another game.

I am having a huge brainfart and am sure the explanation will be silly simple. Sample Dialogue: Enter the number of sticks you wish to pick: 2 You picked: 2. 21 sticks left. Computer picked 2 sticks. 19 left. Your turn...etc

#include <iostream>
using namespace std;
int main()
{
int userPick, cPick, toothpicks=23;
char answer;
cout << "Lets play a game of 23!\n";

do
{
    cout << "Enter the number of sticks you wish to pick: ";
    cin >> userPick;
    if (userPick < 1 || userPick >3)
    {
        cout<< "Wrong number of sticks. Please pick 1, 2, or 3 sticks: ";
    }
}
    while(userPick<1 || userPick>3);


do
{
if (userPick>=1 || userPick<=3)
    {
        toothpicks = toothpicks - userPick;
        cout << "You picked " << userPick << " sticks. " <<toothpicks << " 
left" << endl;

    if (toothpicks>4)
    {
        cPick = 4-userPick;
        toothpicks= toothpicks - cPick;
        cout << "Computer picked " << cPick << " sticks. ";
        cout << toothpicks << " left"  << endl;

        cout<< "Your turn. Enter the number of sticks you wish to pick: ";
        cin >> userPick;
    }
    else if (toothpicks==4)
    { 
        cPick= toothpicks-3;
        toothpicks = toothpicks - cPick;
        cout << "Computer picked " << cPick << " sticks. ";

        cout<< "Your turn. Enter the number of sticks you wish to pick: ";
        cin >> userPick;
    }
    else if (toothpicks == 3)
    {
        cPick= toothpicks-2;
        toothpicks = toothpicks - cPick;
        cout << "Computer picked " << cPick << " sticks. ";

        cout<< "Your turn. Enter the number of sticks you wish to pick: ";
        cin >> userPick;
    }
    else if (toothpicks == 2)
    {
        cPick= toothpicks-1;
        toothpicks = toothpicks - cPick;
        cout << "Computer picked " << cPick << " sticks. ";

        cout<< "Your turn. Enter the number of sticks you wish to pick: ";
        cin >> userPick;
    }
    else if (toothpicks == 1 && userPick == 1) 
    {
        cout << "You picked the last stick. Sorry the computer beat you!" << 
endl;
    }
}
}
while (toothpicks >=1);





return 0;
}

Aucun commentaire:

Enregistrer un commentaire