我正处于游戏开发的初期。这是某种基于回合的游戏,例如《战锤》或《魔兽争霸》。一些生物可以再生他们遭受的伤害,并代表这个,我有一个像这样的界面
public interface Regenerative {
void regenerates();
}
所以一个再生的生物是
public class SomeMonster() extends BaseCreature implements Regeneative{
//Code
private int hitPoints;
public void regenerates(){
hitPoints = hitPoints + regenerateValue;
}
}
我面临的问题是,并非所有生物都能再生相同数量的生命值,因此我必须将其数量(regenerateValue)放置在某个地方。由于我无法将其放置在界面上(因为我不希望所有生物的数量相同),所以我考虑在生物类中添加新属性
public class SomeMonster() extends BaseCreature implements Regeneative{
//Code
private int regenerateValue;
public void regenerates(){
hitPoints = hitPoints + regenerateValue;
}
}
但是我不喜欢这种方式(为什么不再生的生物的regenerateValue应该为0?)。我认为这给了类不必要的属性,因此设计很糟糕。您认为此案例的最佳方法是什么?
最佳答案
我使用的解决方案可能有点过头了,但这可以进行很多扩展(再生,毒害,保护...)
我使用接口“ CreatureProperties”定义一个整数值和一个ID,并且可以在每个回合上对怪物执行操作。您可以将这些属性子类化以执行给定的属性
abstract class CreatureProperties {
protected String id = "";
protectd int propertyValue = 0;
public void actOn(BaseMonster);
// plus setter and getter
}
public RegenerationProperty implements CreatureProperties {
final public REGENERATION_ID = "Regeneration";
int regenerationValue = 0;
public RegenerationProperty(int value){
id = REGENERATION_ID;
propertyValue= value;
}
public void actOn(BaseMonster monster){
monster.setHitPoint(monster.getHitPoints()+propertyValue);
}
}
in the BaseMonster class, you manage a set of MonsterProperty, initially empty.
class BaseMonster {
protected List<CreatureProperties> properties =
new ArrayList<CreatureProperties>();
// plus management of propeties : add remove, iterator...
public void update(){
// perform all properties-linked update to monster
foreach (CreatureProperty property : properties){
property.actOn(this);
}
}
}
在SomeMonster的子类中,您只需在实例化过程中添加此类怪物的属性集即可。
class SomeMonster extends BaseMonster {
public SomeMonster(){
properties.add(new RegenerationProperty(5)); // presto : monster regenerate
}
}
在某些情况下,我会使用Id,但该属性不会在每个刻度上都使用(例如,更新中没有任何内容),而是例如减少伤害(id =“ LightningReduction”)或修改现有属性的列表(删除所有再生属性并添加相同值的PoisonProperty ...)。