#include <iostream>
#include <ctime>
#include <random>
using namespace std;
int playerhealth = 100;
int enemyhealth = 100;
default_random_engine random(time(NULL));
uniform_real_distribution<float> chance(0.0, 1.0);
float hit = chance(random);
int playerturn() {
if (hit > 0.5) {
enemyhealth -= 10;
return enemyhealth;
}
}
int enemyturn() {
if (hit > 0.5) {
playerhealth -= 10;
return playerhealth;
}
}
int main() {
cout << "simulating combat" << endl;
while ((enemyhealth > 0) && (playerhealth > 0)) {
playerturn();
cout << " enemy" << enemyhealth << endl;
enemyturn();
cout << "player"<<playerhealth << endl;
//the values inside the playerturn and enemy turn don't change
}
}
我认为我的代码是不言自明的。我正在尝试遍历 while 循环,让敌人的健康和玩家的健康在每次成功攻击后减少 10,但它并没有改变。我该如何解决?另外,附带问题,我可以做些什么来改进我的代码吗?
最佳答案
float hit = chance(random);
对 chance
的调用只会发生一次,因此 hit
只有一个值。这就像在游戏开始时掷一次骰子,然后每次攻击都以此掷骰为基础。相反,您应该在每位玩家的回合开始时掷骰子。
关于C++ 尝试制作游戏,但在 while 循环中返回函数值时遇到问题。将不胜感激,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28343856/