制作骰子游戏.试图让循环在玩家达到100的时候被打破

Making a dice game. Trying to get the loop to break as soon as one player reaches 100

本文关键字:玩家 游戏 循环      更新时间:2023-10-16

对c++相当陌生。我将创建一个骰子游戏,让你设置骰子的面数和玩家的数量。每个人都从1分开始,只要有人投中100分或更多,游戏就结束了。

这是我到目前为止写的代码

int players = 5;
int playerPosition[players];
for(int i=0; i < players; i++)
{
    playerPosition[i] = 1;
}
for(int i = 0; i < players; i++)
{
    while(playerPosition[i] < 100)
    {
        int roll;
        for (int j = 0; j < players; j++)
        {
            roll = dieRoll(6);
            // dieRoll is a function I made to simulate a die roll
            playerPosition[j] += roll;
            cout << "Player " << j + 1 << " rolled a " << roll << " and is now in position " << playerPosition [j] << endl;
        }
    }
}

所以此时,输出将打印出每个玩家的每个回合。问题在于,它会一直持续下去,直到每个玩家都达到>= 100。我试过添加

if(playerPosition[i] >= 100)
{
   break;
}

在for循环和while循环中。它们还是不像我想的那样好用。你能告诉我可能是什么问题吗?

谢谢。

问题是你每次滚动一个玩家,直到他们达到100点。你需要检查每次掷骰子时是否有玩家超过100

可以这样做的一种方法是在外部for循环之外声明一个bool gameOver变量,其初始值设置为false。每次你增加一个球员的得分,你可以添加 一行
playerPosition[j] += roll;
gameOver = playerPosition[j] >= 100

现在,如果你把代码改成

结构
while(!gameOver) {
for(int i = 0; i < players; i++) {

应该按照预期的方式运行。完整的代码因此变成

int players = 5;
bool gameOver = false;
int playerPosition[players];
for(int i=0; i < players; i++) 
{
    playerPosition[i] = 1;
}
while(!gameOver) {
for(int i = 0; i < players; i++) {
    int roll;
        roll = dieRoll(6);
        // dieRoll is a function I made to simulate a die roll
        playerPosition[j] += roll;
        gameOver = playerPosition[j] >= 100
       if (gameOver)
       {
          break;
       }
        cout << "Player " << j + 1 << " rolled a " << roll << " and is now in position " << playerPosition [j] << endl;
    }
}
}

你应该在每次玩家的总和增加后检查他是否超过了100:

int players = 5;
int playerPosition[players];
for(int i=0; i < players; i++)
{
    playerPosition[i] = 1;
}
while(true)
{
    int roll;
    for (int j = 0; j < players; j++)
    {
        roll = dieRoll(6);
        // dieRoll is a function I made to simulate a die roll
        playerPosition[j] += roll;
        cout << "Player " << j + 1 << " rolled a " << roll << " and is now in position " << playerPosition [j] << endl;
        if(playerPosition[j] >= 100)
        {
            return;
        }
    }
}