对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;
}
}
}
所以目前,输出将为每个玩家打好每个回合。问题是它会一直持续到每个玩家达到&gt; = 100.我试过添加
if(playerPosition[i] >= 100)
{
break;
}
在for循环和while循环中。他们仍然没有按照我想要的方式工作。你能告诉我这个问题是什么吗?
感谢。
答案 0 :(得分:1)
在他的总和增加之后,你应该检查玩家是否每次超过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;
}
}
}
答案 1 :(得分:1)
问题是你每个玩家一次一个地滚动,直到达到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;
}
}
}