0

I want to program a small game in C++.

I want to write a method "attack" that sets the states of the figure after an attack. I have two instances the player and the enemy. The class looks like:

class figure {
   private:
       string name;
       int    hp;
       int    strength;
       int    defense;

  public:
       void attack(int xstrength) {
       // This method gets the Input values of the player and should calculate 
       // and set the new hp stats of the enemy after an attack, sort of

         hp = hp - (xstrength - defense);
       }
};

But how can I call this methode? Do i need to programm a separate methode that only gets the srength value of an instance?, because I cant call the instances this way:

enemy.attack(); 

Because I need to Input the strength of the instance player. Or can i only access one value of an instance such like

enemy.attack(player->get_xstrength)

with the method:

void get_strength() {
    return stength
};

If I extend the class figure with more values like, resistance, level, status etc. I must program a lot of get and set methodes.

dandan78
  • 13,328
  • 13
  • 64
  • 78
E1M1
  • 1
  • yes you can do it. using `get_xstrength` will return the player's strength to enemey and you can attack him. But you also need to use `set_xstrength()` to set the strength of the player after enemy attack. you need to pass the player object for that. – ha9u63a7 Nov 14 '14 at 12:11
  • I don't understand the problem. – Lightness Races in Orbit Nov 14 '14 at 12:16

1 Answers1

0

Your method should instead be:

void attack(figure & target) {
   target.hp -= strength - target.defense;
}

This way you specify the target that figure attacks, and that can give you access to the attacked figure properties. Then you can:

figure player, enemy;
enemy.attack(player);

Also note that you will have to have some kind of a method that sets those properties, which are private and not set in a constructor, so in the class as it is right now there is no way to set those values, meaning they will be garbage memory representation, or at best - zeroes, depending on the compiler implementation.

Last but not least, you might also want to do a check after the target hp calculation to see if that figure is still alive, i.e. if (target.hp <= 0) ... // "target" is dead

dtech
  • 47,916
  • 17
  • 112
  • 190
  • Hey thx ddriver, that worked perfect, as i said before it's been a while since i programmed in c++. But i did the method like "void attack(figure *target)" instead of "void attack(figure & target)" – E1M1 Nov 16 '14 at 21:04