gpt4 book ai didi

java - RPG游戏java中的消耗品设计

转载 作者:行者123 更新时间:2023-12-01 12:11:26 26 4
gpt4 key购买 nike

现在我正在尝试编写一个关于日本 RPG 游戏机制的简单 Java 程序。我在实现消耗品的使用时遇到麻烦,即改变特定状态的元素,无论是来自“角色”类中的可变 HP 还是 MP。以下是“Item”类的粗略代码:

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 的 Items。并且每当我的玩家对象使用 Consumer(Items 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

}

最佳答案

不要使用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;
}
}

关于java - RPG游戏java中的消耗品设计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27251526/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com