• 1_Command 游戏开发命令模式


    A dead simple implementation looks like:
    
    ```
    // simple 
    void InputHandler::handleInput()
    {
      if (isPressed(BUTTON_X)) jump();
      else if (isPressed(BUTTON_Y)) fireGun();
      else if (isPressed(BUTTON_A)) swapWeapon();
      else if (isPressed(BUTTON_B)) lurchIneffectively();
    }
    
    
    // command pattern
    class Command
    {
    public:
      virtual ~Command() {}
      virtual void execute() = 0;
      //virtual void execute(Actor *) = 0;
    };
    
    class JumpCommand : public Command
    {
    public:
      virtual void execute() { jump(); }
    };
    
    class FireCommand : public Command
    {
    public:
      virtual void execute() { fireGun(); }
    };
    
    
    class InputHandler
    {
    public:
      void handleInput();
    
      // Methods to bind commands...
    
    private:
      Command* buttonX_;
      Command* buttonY_;
      Command* buttonA_;
      Command* buttonB_;
    };
    
    
    
    Command* InputHandler::handleInput()
    {
      if (isPressed(BUTTON_X)) return buttonX_;
      if (isPressed(BUTTON_Y)) return buttonY_;
      if (isPressed(BUTTON_A)) return buttonA_;
      if (isPressed(BUTTON_B)) return buttonB_;
    
      // Nothing pressed, so do nothing.
      return NULL;
    }
    
    Command* command = inputHandler.handleInput();
    if (command)
    {
      command->execute(actor);
    }
    ```
    
    #### use command stream, decoupled producer and consumer
    
    ## undo and redo
    
    
    ```
    
    class Command
    {
    public:
      virtual ~Command() {}
      virtual void execute() = 0;
      virtual void undo() = 0;
    };
    
    class MoveUnitCommand : public Command
    {
    public:
      MoveUnitCommand(Unit* unit, int x, int y)
      : unit_(unit),
        xBefore_(0),
        yBefore_(0),
        x_(x),
        y_(y)
      {}
    
      virtual void execute()
      {
        // Remember the unit's position before the move
        // so we can restore it.
        xBefore_ = unit_->x();
        yBefore_ = unit_->y();
    
        unit_->moveTo(x_, y_);
      }
    
      virtual void undo()
      {
        unit_->moveTo(xBefore_, yBefore_);
      }
    
    private:
      Unit* unit_;
      int xBefore_, yBefore_;
      int x_, y_;
    };
    ```
  • 相关阅读:
    HDU
    【JZOJ1252】【洛谷P5194】天平【搜索】
    【JZOJ1252】【洛谷P5194】天平【搜索】
    【JZOJ3896】战争游戏【割点】
    【JZOJ3896】战争游戏【割点】
    【JZOJ3895】数字对【ST表】
    【JZOJ3895】数字对【ST表】
    【JZOJ3894】改造二叉树【树】【LIS】
    【JZOJ3894】改造二叉树【树】【LIS】
    【洛谷P4014】【网络流24题】分配问题【费用流】
  • 原文地址:https://www.cnblogs.com/lightlfyan/p/4224231.html
Copyright © 2020-2023  润新知