我正在做一個基於事件的遊戲(基本上,沒有while(true)循環:如果沒有事件,沒有代碼行得到執行)。遊戲基於房間對象,每個房間都有一個ArrayList,其中包含怪物和戰利品對象。Java - 把線程和其他對象擴展爲相同的類是一個ArrayList
問題是我需要怪物是線程,所以他們會自動啓動遊戲中的事件(如跟隨玩家並攻擊他)。
Monsters和Loot的母類是相同的:GameObject。由於我花了很多時間用這種方式進行遊戲(一個關於戰利品和怪物的列表),我想知道是否有辦法讓兩個物體在同一個列表中出現怪物和戰利品,並且仍然將怪物作爲線程。
目前我使用「implements Runnable」方法。我不知道這是否是最好的方法。
謝謝。
編輯:
這是代碼。首先是母類,GameObjects
public abstract class GameObjects {
protected int x;
protected int y;
private int height;
private int width;
private Player player; //And then there are all getters and setters.
}
然後怪物類,有各種怪物,像殭屍。
package game.projetdonjon;
public abstract class Monster extends GameObjects implements Runnable {
private char direction;
private int hp;
private boolean alive;
private Player player;
public void getDamage(int p){
this.hp=p;
if (this.pv <= 0) {
this.alive = false;
System.out.println("The monster is death.");
}
}
public boolean isAlive() {
if (isAlive)
return true;
else
return false;
}
//And then still others getters & setters...
}
殭屍類:
package game.projetdonjon;
public class Zombie extends Monster implements Runnable {
private Thread thread;
private int hp;
public Zombie(int x, int y,Player player) {
super.setDirection('E');
this.x = x;
this.y = y;
this.hp = 50;
this.thread = new Thread();
super.setHeight(50);
super.setWidth(50);
super.setHp(hp);
super.setAlive(true);
super.setPlayer(player);
}
@Override
public void run() {
System.out.println("Zombie's runnig, yo!");
while (true) {
this.setX(this.getX()+10);
try {
thread.sleep(100);
} catch (Exception e){
System.out.println(e);
}
}
}
}
最後,房類,它包含的怪物和戰利品。
package game.projetdonjon;
import java.util.ArrayList;
public class Room {
private ArrayList<GameObjects> roomElements = new ArrayList();
private ArrayList<Door> roomDoors= new ArrayList();
private int roomNumber;
public Piece(int roomNumber){
this.roomNumber = roomNumber;
roomElements.add(new Loot(somearguments...));
roomEleemnts.add(new Thread(new Zombie(50,50,player))); //Here is the
//problem, as Thread isn't a GameObjects/ doesn't extend GameObjects
}
雖然你寫了一個很好的問題;如果沒有實際的問題和/或代碼示例來證明這個問題很難回答 – epoch
也可以在創建30個怪物時注意怪物的數量並清理它們,否則會出現性能問題,您將不得不重新設計 – HRgiger