我正在编写一个模拟“左右中心”的程序。如果您不熟悉,则游戏涉及3个骰子,其中1个边为“ L”,1个边为“ R”,1个边为“ C”和3个边点。每个人都从$ 3开始。如果滚动“ L”,则向左传递一个美元。如果滚动“ R”,则向右传递一个美元。如果您按下“ C”,则将一个美元置于中间。如果滚动点,则不会采取任何措施。比赛然后转到左边。游戏继续进行,直到只有1个玩家有剩余钱,并且该玩家赢得了所有奖金。
除了一件奇怪的事情,我使程序正常运行。当我按以下方式运行时,它运行良好,通常需要70-150转才能完成。当我注释掉这些行
cout << "In gameOver(). Number of brokeJamokes: " << brokeJamokes;
cin.ignore();
该程序需要数十万(或数百万)次旋转才能完成。为什么简单的输出会改变呢?
完整代码如下:
#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";
}
答案 0 :(得分:1)
正如melpomene所说,您反复称呼srand,并设置了相同的种子(因为我认为它使用时间需要第二种分辨率)。因此,直到时间改变,您将连续获得成千上万个具有相同值的“随机”数字。想想如果每个人都得到相同的掷骰,游戏将永远不会结束。
当您使用cout行时,它将大大降低程序速度,因此将srand设置为相同的值后,可以减少连续滚动的次数。
要解决此问题,请将对srand的调用移至主函数,以便仅调用一次。