0

我正在编写一个游戏,并且有一个名为 GameManager 的主类。我希望它尽可能抽象。在它里面,它有其他类的对象,Player 和 ItemManager。想象一下,我在播放器中有一个功能,可以检测播放器是否在某个区域(检查 x 和 y 值)。例如,如果玩家在该区域,我想生成一个项目 createItem()。我将如何促进班级之间的交流?

4

2 回答 2

3

一种可能性是观察者模式。在该模式中,有一个主题维护着一个观察者列表。当主题的状态发生变化时,它会通知观察者,观察者可以自由地做出他们认为合适的反应。在这种情况下, Player 是您的主题,而 GameManager 是观察者。当玩家的位置发生变化时,它会通知 GameManager,然后谁可以生成一个项目或采取一些其他行动。

于 2012-05-24T22:53:18.897 回答
0

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);
};
于 2012-05-25T00:01:01.500 回答