1

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";

}
  • 3
    Before coding games with C++, `C++` must be learnt using a [good c++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). Once you refer to a good c++ book, you'll be able to better understand your code and see what the problem is. These books are also available as PDFs for free. – Jason Sep 21 '22 at 07:53
  • 2
    You do not change the variable `HP` in your code. `playerAttack(attack,HP);` does not change any of the variables, `HP = playerAttack(attack,HP);` would do that. – mch Sep 21 '22 at 07:53
  • But no error happens when I compile on my PC. – Sean Sep 21 '22 at 08:09

1 Answers1

1

@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 :)

Quimby
  • 17,735
  • 4
  • 35
  • 55
Watermelon
  • 51
  • 3