码迷,mamicode.com
首页 > 其他好文 > 详细

11-13 游戏编程行为模式

时间:2015-01-20 19:50:35      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:

### Behavioral Pattern

#### interpreter pattern
    string -> code
    
    
instruction set: 提供基本操作
virtual machine: 执行指令

front-end: 生成效率更高的字节码

```
void setHealth(int wizard, int amount);
void setWisdom(int wizard, int amount);
void setAgility(int wizard, int amount);
void playSound(int soundId);
void spawnParticles(int particleType);

enum Instruction
{
  INST_SET_HEALTH      = 0x00,
  INST_SET_WISDOM      = 0x01,
  INST_SET_AGILITY     = 0x02,
  INST_PLAY_SOUND      = 0x03,
  INST_SPAWN_PARTICLES = 0x04
};

switch (instruction)
{
  case INST_SET_HEALTH:
    setHealth(0, 100);
    break;

  case INST_SET_WISDOM:
    setWisdom(0, 100);
    break;

  case INST_SET_AGILITY:
    setAgility(0, 100);
    break;

  case INST_PLAY_SOUND:
    playSound(SOUND_BANG);
    break;

  case INST_SPAWN_PARTICLES:
    spawnParticles(PARTICLE_FLAME);
    break;
}



### stack matchine

class VM
{
public:
  VM()
  : stackSize_(0)
  {}
  

private:
  void push(int value)
  {
    // Check for stack overflow.
    assert(stackSize_ < MAX_STACK);
    stack_[stackSize_++] = value;
  }

  int pop()
  {
    // Make sure the stack isn‘t empty.
    assert(stackSize_ > 0);
    return stack_[--stackSize_];
  }

private:
  static const int MAX_STACK = 128;
  int stackSize_;
  int stack_[MAX_STACK];
};

case INST_ADD:
{
  int b = pop();
  int a = pop();
  push(a + b);
  break;
}


```



### subclass 沙箱

子类使用父类提供的方法

#### Type Object

```
class Monster{}
class Drogon: Monster {}
class Troll: Monster {}

    VS
class Breed {}
class Monster{
    public Breed breed;
}


Monster drogon = new Monster{ breed= new Breed("drogon")};

Breed read config


// 好处
// monster的breed可以随便修改, 配置生成生物,不用重新编译代码

```

 

11-13 游戏编程行为模式

标签:

原文地址:http://www.cnblogs.com/lightlfyan/p/4236711.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!