Satchmo Brown
Satchmo Brown

Reputation: 1437

Facilitating class communication c++

I have am writing a game and have a main class called GameManager. I want it to be as abstract as possible. Inside it, it has objects of other classes, Player, and ItemManager. Imagine I have a function in player which detects if the player is in a certain area (checking x and y values). If for instance, I wanted to spawn an item createItem() if the player is in that area. How would I facilitate communication between the classes?

Upvotes: 0

Views: 696

Answers (2)

bjames
bjames

Reputation: 1

The way i'm currently trying to do it is to define an abstract base class (dubbed 'Commando') that has a virtual function Command(string cmd), and having every game-related object (and manager of objects) inherit from that, and override Command() with code to parse strings of text (or in the case of the managers, parse or truncate and pass along to sub-objects contained in maps); this approach has limitations, but it works for my purposes.

command.h:
class Commando
{
public:
  virtual int Command(std::string const& cmd) = 0;
};

atom.h:
#include "command.h"

class Atom : public Commando
{
public:
  int Command(std::string const& cmd);
};

Upvotes: 0

Chris Hayden
Chris Hayden

Reputation: 1144

One possibility is the observer pattern. In that pattern there is a subject that maintains a list of observers. When the state of the subject changes it notifies the observers, who are free to react as they deem appropriate. In this case the Player is your subject and the GameManager is an observer. When Player's location changes, it notifies GameManager, who can then spawn an item or take some other action.

Upvotes: 3

Related Questions