* Title Typo = / *

Hi there, I'm working on a small section of code which will be used in a very large c++ game for my final project.

I'm doing an interactive RPG/Fighting game but I'm running into an error.

I have a Player class and an Enemy class (not fully developed but just have 1 function I've been trying to test) and most likely going to become my parent classes.

In short, I'm calling an Attack function from an Enemy to a Player using get/set methods. My only problem, is that if I call the function more than once, the Player HP resets back to the original input even though the variable isn't declared constant - so I must be going out of scope somehow, but don't understand how.

If someone could help, that would be great! Here's my code:

#include <iostream>
class Player{
      public: // constructor
              Player(int hp);
              // return int of hitpoints
              int getHP();
              // set int of hitpoints
              void setHP(int hp);
      private:
              // Player hitpoints
              int m_HP;
};
 
Player::Player(int hp){
       m_HP = hp;
}

            
int Player::getHP(){
    return m_HP;
}


void Player::setHP(int hp){
     m_HP = hp;
}
#include "Player.cpp"
using namespace std;

class Enemy{
      public:
             //constructor
             Enemy(int AP);
             // Attack passing a Player object and Enemy Object
             void Attack(Player a, Enemy b);
             
      private:
              // int Attack Power which determines how much HP to remove from player
              int m_AttackPower;
              // Temporary Opponent HP 
              int tempOpponentHP;
};

Enemy::Enemy(int AP){
        m_AttackPower = AP;
}


void Enemy::Attack(Player a, Enemy b){
     // This code is a bit jumbled and not very standard; however, I have it in multiple (more obvious steps) for testing purposes!
     cout << "Dave's HP Is: " << a.getHP() << endl;
     b.tempOpponentHP = a.getHP();
     cout << "TempOPPHP is: " << b.tempOpponentHP << endl;
     b.tempOpponentHP = (b.tempOpponentHP - b.m_AttackPower);
     cout << "After attacking, TempOPPHP is: " << b.tempOpponentHP << endl;
     a.setHP(b.tempOpponentHP);
     cout << "After setting, Player hp is: " << a.getHP() << endl << endl;
     
     
}
// Main
#include <iostream>
#include "Enemy.cpp"
using namespace std;

int main(){
    Player Dave(1000);
    Enemy Illidan(500);
    
    Illidan.Attack(Dave, Illidan);
    Illidan.Attack(Dave, Illidan);
    
    system("pause");
    return 0;
}

Edited 5 Years Ago by Dmiller071: n/a

void Enemy::Attack([B]Player a[/B], Enemy b){

Yes, it's a scoping issue. You're passing a copy of a Player. You should be passing either a pointer or a reference to the Player.

Edited 5 Years Ago by Fbody: n/a

This article has been dead for over six months. Start a new discussion instead.