你的位置:首页 > 软件开发 > ASP.net > 《游戏编程模式》(2)

《游戏编程模式》(2)

发布时间:2016-12-28 13:00:03
Chatper 2 命令模式命令是一个具象化(实例化)的方法调用。A command is a reified method call. 定义一个基类,命令的控制对象由参数传入:1 class Command2 {3 public:4 virtual ~Comman ...

Chatper 2 命令模式

命令是一个具象化(实例化)的方法调用。

A command is a reified method call.

 

定义一个基类,命令的控制对象由参数传入

1 class Command2 {3 public:4  virtual ~Command() {}5  virtual void execute(GameActor& actor) = 0;6 };

对游戏中的AI对象也可以简单地提供命令对象以供执行。

空对象模式:在这里可以提供一个什么都不做的命令。

 

撤销和重做:

execute中记录上一次的位置:

 1 class Command 2 { 3 public: 4  virtual ~Command() {} 5  virtual void execute() = 0; 6  virtual void undo() = 0; 7 }; 8 class MoveUnitCommand : public Command 9 {10 public:11  MoveUnitCommand(Unit* unit, int x, int y)12  : unit_(unit),13   xBefore_(0),14   yBefore_(0),15   x_(x),16   y_(y)17  {}18 19  virtual void execute()20  {21   // Remember the unit's position before the move22   // so we can restore it.23   xBefore_ = unit_->x();24   yBefore_ = unit_->y();25 26   unit_->moveTo(x_, y_);27  }28 29  virtual void undo()30  {31   unit_->moveTo(xBefore_, yBefore_);32  }33 34 private:35  Unit* unit_;36  int xBefore_, yBefore_;37  int x_, y_;38 };

多次撤销可以维护一个命令列表和对当前命令的一个引用。

 

 

Chapter 3 享元模式

将数据对象切分成两种类型:

  1. 不属于单一实例对象并能被所有对象共享的数据;
  2. 对每个对象都是唯一的数据。

 

地形类:

 1 class Terrain 2 { 3 public: 4  Terrain(int movementCost, 5      bool isWater, 6      Texture texture) 7  : movementCost_(movementCost), 8   isWater_(isWater), 9   texture_(texture)10  {}11 12  int getMovementCost() const { return movementCost_; }13  bool isWater() const { return isWater_; }14  const Texture& getTexture() const { return texture_; }15 16 private:17  int movementCost_;18  bool isWater_;19  Texture texture_;20 };

 

单链表写法(避免造成动态内存分配):

 1 class Subject 2 { 3  Subject() 4  : head_(NULL) 5  {} 6  7  // Methods... 8 private: 9  Observer* head_;10 };11 class Observer12 {13  friend class Subject;14 15 public:16  Observer()17  : next_(NULL)18  {}19 20  // Other stuff...21 private:22  Observer* next_;23 };24 void Subject::addObserver(Observer* observer)25 {26  observer->next_ = head_;27  head_ = observer;28 }29 void Subject::removeObserver(Observer* observer)30 {31  if (head_ == observer)32  {33   head_ = observer->next_;34   observer->next_ = NULL;35   return;36  }37 38  Observer* current = head_;39  while (current != NULL)40  {41   if (current->next_ == observer)42   {43    current->next_ = observer->next_;44    observer->next_ = NULL;45    return;46   }47 48   current = current->next_;49  }50 }51 void Subject::notify(const Entity& entity, Event event)52 {53  Observer* observer = head_;54  while (observer != NULL)55  {56   observer->onNotify(entity, event);57   observer = observer->next_;58  }59 }

C#:event关键字,观察者成为一个代理。

原标题:《游戏编程模式》(2)

关键词:

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

可能感兴趣文章

我的浏览记录