I'm writing a program to simulate Left Right Center. If you're not familiar, the game involves 3 dice with 1 side "L", 1 side "R", 1 side "C", and 3 sides dots. Everyone starts with $3. If you roll an "L", you pass a dollar to the left. If you roll an "R", you pass a dollar to the right. If you roll a "C", you put a dollar in the center. If you roll a dot, you take no action. Play then passes to the left. Play continues until only 1 player has money remaining, and that player wins everything.
I got the program operating correctly, except for one strange thing. When I run it as below, it runs fine, usually taking 70-150 turns to complete. When I comment out the lines
cout << "In gameOver(). Number of brokeJamokes: " << brokeJamokes;
cin.ignore();
the program takes hundreds of thousands (or millions) of turns to complete. Why would a simple output change that?
Full code follows:
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int player[10] = {0};
int bank[10] = {0};
int rollDie() {
srand(time(NULL));
int randNum = rand()%6+1;
//cout << "In rollDie(), die roll is " << randNum << "\n";
//cin.ignore();
return randNum;
}
int distributeCash(int roll, int playerNum) {
if(roll == 1) { //pass left
bank[playerNum]--;
/* if active player is player 10 (player[9]), we need to pass to player 1 (player[0])
instead of the nonexistant player 11, so we change the array value to -1 */
if(playerNum == 9) {playerNum = -1; }
bank[playerNum + 1]++;
return 0;
}
if(roll == 2) { //pass right
bank[playerNum]--;
/* if active player is player 1 (player[0]), we need to pass to player 10 (player[9])
instead of the nonexistant player 0, so we change the array value to 11 */
if(playerNum == 0) {playerNum = 10;}
bank[playerNum - 1]++;
return 0;
}
if(roll == 3) { //pass to center
bank[playerNum]--;
return 0;
}
else {
return 0;
}
return 0;
}
int gameOver() {
int brokeJamokes = 0;
for(int i = 0; i < 10; i++) {
if(bank[i] == 0) { brokeJamokes++; }
}
cout << "In gameOver(). Number of brokeJamokes: " << brokeJamokes;
cin.ignore();
if(brokeJamokes==9) {return 1;}
else return 0;
}
void showWinner() {
for(int i = 0; i < 10; i++) {
if(bank[i] != 0) {
cout << "Player " << (i+1) << " is the winner!\n";
cin.ignore();
return;
}
}
}
int main()
{
int roll[3] = {0};
for(int x = 1; x < 10; x++) { //initialize all banks to 3 except test player (player 1)
bank[x] = 3;
}
bank[0] = 3; //test player bank initialization
int turnCount = 0;
while(!gameOver()){
for(int i = 0; i < 10; i++) {
if(gameOver()) {break;}
for(int j = 0; j < 3; j++) {
roll[j] = rollDie();
if(bank[i] != 0) {
distributeCash(roll[j], i);
}
}
/* cout << "After player " << (i + 1) << "'s roll: \n";
for(int l = 0; l < 10; l++) {
cout << "Player " << (l + 1) << " $" << bank[l] << "\n";
}
cin.ignore();
*/
turnCount++;}
}
showWinner();
cout << "Number of turns: " << turnCount << "\n";
cout << "Game over!\n";
}