我正在尝试做一个模拟简单的生物和食肉动物的模拟。
我有一个名为creature的类和一个名为carnCreature的子类。我在生物中有一个名为eat的方法,它接受一种类型的对象,但我需要carnCreature类中的eat方法来接受一个生物列表。我尝试将该方法命名为与生物类中相同的名称,但当我尝试调用它时,java不接受更新后的参数。
package simulationObjects;
import java.awt.Color;
import java.util.List;
import java.util.Random;
import java.lang.Math.*;
public class Creature {
public int x;
public int y;
public int maxTilesX;
public int maxTilesY;
public Color color;
public float health = 50;
public int life = 0;
public Creature (int x, int y, Color color, int maxTilesX, int maxTilesY) {
this.x = x;
this.y = y;
this.color = color;
this.maxTilesX = maxTilesX;
this.maxTilesY = maxTilesY;
}
public void update(Tile tile) {
eat(tile);
life++;
health-=1;
}
public void eat(Tile currentTile) {
if (currentTile.color == this.color) {
health += 3;
currentTile.color = Color.GRAY;
}
}
public boolean isCarnivore() {
return false;
}
}
package simulationObjects;
import java.awt.Color;
import java.util.List;
public class CarnCreature extends Creature{
private static final boolean CANABOLIC = false;
public CarnCreature(int x, int y, Color color, int maxTilesX, int maxTilesY) {
super(x, y, color, maxTilesX, maxTilesY);
// TODO Auto-generated constructor stub
}
public void update(List<Creature> creatures) {
eat(creatures);
life++;
health-=1;
}
public void eat(List<Creature> creatures) {
for (Creature creature : creatures) {
if (CANABOLIC) {
if (creature.color == this.color) {
health += 3;
creature.health = 0;
}
} else {
if (creature.color == this.color && creature.isCarnivore() == false) {
health += 3;
creature.health = 0;
}
}
}
}
public boolean isCarnivore() {
return true;
}
}
稍后将调用eat函数,如下所示:
for (Creature creature : creatures) {
if (creature.isCarnivore()) {
creature.upadte(creatures);
} else {
creature.update(tiles.get(creature.x).get(creature.y));
}
}
我正在尝试将这些生物和carnCreatures存储在同一个列表中,即“生物”。这就是问题所在吗?我是否需要将它们存储在单独的列表中?
谢谢
发布于 2018-08-11 04:44:42
你有两个选择:
第二种选择是更优雅的。使用多态性的“魔力”,每个类都会调用它的方法,并且不需要使用isCarnivore()方法检查类。但是你需要从图块中获取生物的列表。
https://stackoverflow.com/questions/51793729
复制相似问题