Krowe3 Krowe3 - 1 year ago 45
C++ Question

I made a rougelike game in visual studio and i want to display the players health

I made a player class which holds everything related to the player. Can I call player.h in my GameSystem.h and do cout your health and go player._health. Am I doing something wrong cause it says class player type name is now aloud.

class Player
{
public:
Player();
void init(int level, int health, int attack, int defense, int experience);

int attack();
int takeDamage(int attack);



// Set Player funtion
void setPosition(int x, int y);

void addExperience(int experience);

void setHP(int hp);

void setMaxHP(int hp);

// Get player position
void getPosition(int &x, int &y);


private:
// Player porperties
int _level;
int _health;
int _maxHp;
int _attack;
int _defense;
int _experience;

// Player Position
int _x;
int _y;


};


I want to call the players health in my GameSystem.cpp how would I go about doing that.

#include "GameSystem.h"
#include "Player.h"
#include <iostream>
#include <conio.h>


// Constructor which sets up the game
GameSystem::GameSystem(string levelFilename)
{
_player.init(1, 100, 10, 10, 0);

_level.load(levelFilename, _player);

system("pause");
}

void GameSystem::playGame()
{
bool isDone = false;

while (isDone != true)
{
_level.print();
playerMove();
}
}

void GameSystem::playerMove()
{
char input;
printf(" Enter a move command (w/s/a/d: ");
input = _getch();
cout << " Your Health:" << Player._health;

_level.movePlayer(input, _player);


}

Answer Source

You probably understands the concept of private/public. If not, you should understand that private means that, everything on that scope cannot be accessed from outside. For your problem you should create a public method, like your getPosition that returns the health, like

int getHealth(){ return this->_health; }

Study private and public. C++ is a complex language, even if, for now, it does not seems like that hard it will get hard, specially if you are trying to write a game.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download