制作骰子游戏.试图让循环在玩家达到100的时候被打破
Making a dice game. Trying to get the loop to break as soon as one player reaches 100
对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;
}
}
}
相关文章:
- 在C++游戏中与库存系统作斗争
- 换位表导致测试失败(但在游戏中运行良好)
- Craps游戏问题,忽略if语句
- 根据用户回答声明"Players"。用户选择玩家数量。播放器是结构体
- 矢量下标超出SFML游戏中的范围
- 我是 c++ 的新手.学习基本知识后,我想做井字游戏.对于印刷板,我在下面写代码,但它显示错误
- 玩家加速穿越世界(C++)
- 我在视觉工作室中制作了一个类似胭脂的游戏,我想显示玩家的生命值
- 如果(玩家[P] .setCoin(Gameboard,Input))将其命名为“在线”游戏板的攻击函数)
- 使用类创建井字游戏代码,但仅用于棋盘显示并定义玩家
- 为什么我的代码在 3 轮游戏后无法正确切换玩家名称?
- 需要推荐c++游戏服务器,关于玩家使用的数据结构,怪物对象,以获得性能优势
- 自动多人游戏中的坑洞,玩家可以使用自己的算法
- 我试图做一个程序,只是显示瓷砖2玩家将开始在拼字游戏,但它一直崩溃
- 制作骰子游戏.试图让循环在玩家达到100的时候被打破
- 模拟每个玩家获胜概率不同的游戏
- 2D盒子碰撞,平台游戏,我的玩家"hovers"在方块上
- C++ 重新启动我的刽子手游戏时,我的分数以及我不想要的玩家信息被删除
- c++ 2玩家骰子游戏
- 如何让敌人在一定距离内随机循环并跟随玩家?c++主机游戏