简体   繁体   中英

C++ Trying to make a game, having trouble returning a function's value inside a while loop. Would appreciate assistance

#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

    }

}

I think the my code is self explanatory. I'm trying to iterate through the while loop, having enemyhealth and playerhealth decrease after every successful attack by 10, but but it doesn't change. How can I fix that? also, side question, are there any things I can do to improve my code?

float hit = chance(random);

This call to chance will only ever happen once, so hit only ever has one value. It's like rolling a die once at the beginning of the game and then basing every attack on that roll. Instead, you should roll it at the beginning of each player's turn.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM