error unlocalized variable? what do i do?

Viewed 62

I'm a first-year student studying game design and recently we've just started doing c++. I already have a good understanding of java but I have never seen C++ so I decided to code a little game (without using pointers) but I seem to constantly have this "unlocalized variable" problem I have no idea how to fix this. What can I do?

    //1DAE22 - Maxim Desmet

#include <iostream>
#include <string>

int playerAttack(int attack, int HP)
{
    return HP - attack;
}
int main()
{
    int HP{20};
    int attack{ 5 };
    std::string run;
    std::string userinput;



    for (int i = 0; i < 4; i++)
    {
        int num = rand() % 2 + 1;
        if (num == 2)
        {
            userinput = "attack";
        }
        else
        {
            userinput = "run";
        }
        if (userinput == "attack") 
        {

            playerAttack(attack,HP);
            std::cout << "total HP left : " << playerAttack(attack, HP) << "\n";
        }
        else
        {
            std::cout << "the player has ran! "<<"\n";
        }
        std::cout << HP <<"\n";
    }
    std::cout << "congrats you beat the computer<<" <<"\n";

}
1 Answers

@mch has already posted the problem: your playerAttack() function returns the remaining HP, but you do not store the result into any variable. The fixed for-loop could look like this:

for (int i = 0; i < 4; i++) {
    if (num == 2) {
        userinput = "attack";
    } else {
        userinput = "run";
    }
    if (userinput == "attack") {
        HP = playerAttack(attack, HP);
        std::cout << "total HP left : " << HP << "\n";
    } else {
        std::cout << "the player has ran! "
                  << "\n";
        // you may consider adding a "break;" here if you don't want any attacks
        // after player has run.
    }
    std::cout << HP << "\n";
}

You could also try to play a bit with std::cin to make this game more interactive :)

Related