2014-12-02 59 views
0

现在我正在尝试编写一个关于日本RPG游戏机制的简单Java程序。 我在实施消耗品的使用方面遇到了麻烦,也就是说,改变特定状态的项目,无论是来自变量HP还是MP中的“字符”类。下面是类“项目”的粗略代码现在:RPG游戏中的消耗品设计java

abstract class Items{ 
int stock; 

public int checkCategory(); 
public int use(); 
} 

class HPitems extends Items{ 

public int checkCategory(){ 
return 1; // this only means that category '1' heals HP, not MP 
} 

} 

class Potion extends HPitems{ 

public int use(){ 
stock--; 
return 50; //this means potion heals 50 HP 
} 

} 

,所以我相信你现在的想法,我打算让班级MPitems扩展了返回2.类别,每当我的球员对象消耗物品一个项目,使用消耗(项目e),它将使用多个if语句来检查类别。如果返回类别1,我将使用相应Items子类的use()返回的值,并将该值添加到播放器HP.我认为现在没有任何问题,但是如果有很多Items类别,例如给出另一种状态效果的项目,我认为它效率不高。有没有更好的方法来做到这一点?

顺便说一句,这是球员类,如果你需要它:

public class Player{ 
int HP; 
int MP; 

public void consume(Items e){ 
if(e.checkCategory() == 1){ 
    this.HP = this.HP+e.use(); 
else{ 
    this.MP = this.MP+e.use(); 
} 
} 

} // consume 

} 
+1

你可以给使用方法玩家作为参数:使用(玩家p),然后在Potion类中使用(玩家p){p.HP + = 50}这样你就不需要很多if-子句。另一方面,使用功能现在绑定到玩家。如果其他对象也需要“使用”药水,我会创建一个新的类字符,例如并定义使用(字符c)。玩家会从角色继承。然后,消费方法看起来像是消耗(项目e){e.use(this)},而与项目类型无关。顺便说一句,它应该是项目,而不是项目:) – Michael 2014-12-02 14:17:19

+0

@迈克尔很好。非常好:D谢谢 – Rei 2014-12-02 14:29:38

回答

1

而不是使用e.checkCategory的,使用更自然的方式通过调度

class Player { 
    int hp; 
    int mp; 

    void use(Potion p) { 
     p.use(this); 
    } 
} 

interface Potion { 
    void use(Player p); 
} 

class HPPotion implements Potion { 
    public void use(Player p) { 
     p.hp += 50; 
    } 
} 

class MPPotion implements Potion { 
    public void use(Player p) { 
     p.mp += 50; 
    } 
} 
+0

我明白你在说什么。这就是我要找的,谢谢:D – Rei 2014-12-02 14:30:19

+1

那家伙偷走了我的答案:P – Michael 2014-12-02 14:51:33

+1

@Michael,对不起) – mishadoff 2014-12-02 16:37:33