游戏编程技巧 - Type Object

时间:2023-03-08 19:44:34

Type Object

使用场景

你在制作一款和LOL类似的游戏,里面有许多英雄,因此你想建立一个英雄基类,然后把各种英雄都继承自该基类,这些英雄类都有生命值和攻击力等属性。每次策划想增加一个英雄,你都要设计一个新英雄类。到后来,已经有几百个英雄,而这些英雄类的结构都一样,只是里面的属性值不同,很明显代码设计出问题了。
类图如下:
游戏编程技巧 - Type Object
代码如下:

public abstract class Hero {
  private int mHp;
  private int mAttack;
  public Hero(int hp, int attack) {
    mHp = hp;
    mAttack = attack;
  }
}

public class Tryndamere : Hero {
  public Tryndamere(int hp, int attack) {
    base(hp, attack);
  }
}

public class Blademaster : Hero {
  public Blademaster(int hp, int attack) {
    base(hp, attack);
  }
}

Type Object描述

定义一个类表示英雄类型,英雄类保存该类型类的引用。

代码

public class HeroType {
  private int mHp;
  public int Hp {
    set { mHP = value; }
    get { return mHp; }
  }

  private int mAttack;
  public int Attack {
    set { mAttack = value; }
    get { return mAttack; }
  }
}

public class Hero {
  private int mHp;
  private int mAttack;
  private HeroType mType;
  public Hero(HeroType heroType) {
    mHp = heroType.Hp;
    mAttack = heroType.Attack;
    mType = heroType;
  }
}

从这些代码来看,你可能发现不了该模式的优点。让我们来给出一个使用例子来深入说明一下。

使用

通常来说,数值都是从配置表中读取的,比如有以下的英雄数值:

"Tryndamere" : {
  "hp" : 100,
  "attack" : 50,
}

则我们读取这些数据后,可以像下面这样使用:

HeroType TryndamereType = new HeroType(table["Tryndamere"]["hp"], table["Tryndamere"]["attack"]);
Hero Tryndamere = new Hero(TryndamereType);

可见,我们可以创建任意多的英雄类型而不再需要设计新的英雄类。


其他设计方案

  • 在HeroType中提供一个工厂方法,利用该方法创建英雄类。
  • 在HeroType中实现继承(不是用编程语言中的继承)

    public class ObjectType {
      private int mValue;
      public int Value {
    set { mValue = value; }
    get { return mValue; }
      }
      public ObjectType(ObjectType parent, int value) {
    if(parent != null) {
      if(value == 0) mValue = parent.Value;
    } else {
      mValue = value;
    }
      }
    }

参考

游戏设计模式