C++ 尝试制作游戏,但在 while 循环中返回函数值时遇到问题。将不胜感激

标签 c++

#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/

相关文章:

c++ - 在二维数组的矩形区域内快速找到最大值的方法

c++ - boost deadline_timer 最小示例 : should I substitute "sleep"?

c++ - 没有转换的 dynamic_cast 类型检查功能?

c++ - 在 C 中的 16 字符数组中连接 32 位 int block

c++ - C++工作草案的措辞可能有缺陷(整数转换等级规则)

4 级继承链中的 C++ 虚拟析构函数。

c++ - 如何处理指针成员的不同所有权策略?

c++ - 给定一个迭代器,声明一个具有正确 size_type 的索引

c++ - Eigen 矩阵 vector 除法

c++ - 使用来自 OSG Cookbook 的绘图实例渲染点云数据不起作用