Is there anyway to loop this instead? (C++ Dice Game)

  c++, if-statement, while-loop

I’m trying to make a Dice Game in C++. Basically what my bunch of code is doing is declaring if the Computer wins, or the Player wins. The game is best of 3 so first to 2 rounds wins. I was wondering if there is any way to loop this until a winner is declared instead of using if/else statements all the time. I’m thinking of using a while-loop since I don’t know how many times the game will be played. I just don’t understand how I’m supposed to implement this code in to a loop.

I’m really just trying to learn here and I don’t expect someone to solve it for me, perhaps just point me in the right direction 🙂

int pDice1, pDice2, cDice1, cDice2;
int pResult, cResult;
int pTotal = 0;
int cTotal = 0;

srand(time(0));
pDice1 = rand() % 6 + 1;
pDice2 = rand() % 6 + 1;
cDice1 = rand() % 6 + 1;
cDice2 = rand() % 6 + 1;

pResult = pDice1 + pDice2;
cResult = cDice1 + cDice2;

cout << "Player score is: " << pResult << endl;
cout << "Computer score is: " << cResult << endl;

if (pResult > cResult) {
    cout << "Player wins!" << endl;
    pTotal++;
}
else if (cResult > pResult) {
    cout << "Computer wins!" << endl;
    cTotal++;
}



if (pResult > cResult) {
    cout << "Player wins!" << endl;
    pTotal++;
}
else if (cResult > pResult) {
    cout << "Computer wins!" << endl;
    cTotal++;
}

if (pTotal == 2) {
    cout << "Player wins this round!" << endl;
}
else if (cTotal == 2) {
    cout << "Computer wins this round!" << endl;
}

Source: Windows Questions C++

LEAVE A COMMENT