我创建了一个测试项目,但我遇到了一些我不能理解的事情。
我正在试着给FightManager里的怪物打电话。我希望怪物的变量(name,health,damage和defense)等于任何随机的怪物(WolfMonster或GoblinMonster)
以前我只有一个怪物,我设法做到了,但是现在有两个怪物,如果选择了不同的怪物,我怎么能给变量传递一个不同的值呢?
public class Units {
int health;
int damage;
int defense;
String name;
public boolean isAlive(){
if(health >= 1){
return true;
}else{
return false;
}
}
}
public class Monster extends Units{
public Monster(String name,int health,int damage,int defense){
this.name = name;
this.health = health;
this.damage = damage;
this.defense = defense;
}
}
public class GoblinMonster extends Monster {
public GoblinMonster(String name, int health, int damage, int defense) {
super("Goblin",50,5,6);
this.name = name;
this.health = health;
this.damage = damage;
this.defense = defense;
}
}
public class WolfMonster extends Monster {
public WolfMonster(String name, int health, int damage, int defense) {
super("Wolf",50,5,6);
this.name = name;
this.health = health;
this.damage = damage;
this.defense = defense;
}
}
public class FightManager {
GameManager manage = new GameManager();
Player player = new Player("Player",100,10,5);
GoblinMonster gobli = new GoblinMonster("Goblin", 40, 7, 4);
WolfMonster wolf = new WolfMonster("Wolf",50,9,6);
boolean myTurn = true;
....我想知道如何根据生成的怪物来分配怪物的值。
发布于 2017-05-09 00:18:20
我不认为这里需要多个子类和父单元类。你可以简单地创建不同的怪物对象,命名为WolfMonster,GoblinMonster。
public class Monster {
int health;
int damage;
int defense;
String name;
Monster(String name, int health, int damage, int defense)
{
this.name = name;
this.health = health;
this.damage = damage;
this.defense = defense;
}
public boolean isAlive()
{
if(health >= 1){
return true;
}else{
return false;
}
}
}
public class FightManager {
GameManager manage = new GameManager();
Player player = new Player("Player",100,10,5);
//changes
Monster gobli = new Monster("Goblin", 40, 7, 4);
Monster wolf = new Monster("Wolf",50,9,6);
boolean myTurn = true;
// To-Do
}发布于 2017-05-09 00:14:03
也许你想要做的是在每个构造函数中将"name“设置为一个常量。
例如,WolfMonster将为:
public class WolfMonster extends Monster {
public static String TYPE = "Wolf";
public WolfMonster(int health, int damage, int defense) {
super(WolfMonster.TYPE,health,damage,defense);
}
}请注意,您不需要重新指定成员字段,因为将在调用super()时分配。
发布于 2017-05-09 00:21:29
为此,您必须使用多态性,通过将单元类声明为接口.The方法isAlive()作为抽象以及属性.In,另一方面,Monster类应实现Unit接口,其余的Monster类将扩展classe monster。
https://stackoverflow.com/questions/43852316
复制相似问题