我相信這是一個好的開始,但還有一些事情需要解決。
而不是有一個包含所有實體的2D對象數組,而應該爲每種類型的實體擁有多個列表<>,並讓所有類都包含一個Point。這樣你就可以更新殭屍位置而不會意外更新植物位置。
List<Plants> plants;
List<Zombies> zombies; // and anything else that needs to be added to the board
這也可以避免大部分時間投射。
對於遊戲計數器,您可以簡單地使用當前時間。只需存儲遊戲開始的毫秒數,然後用開始時間減去當前時間即可獲得遊戲進行的時間。你也可以用1000除以僅顯示秒。
for(Zombie zombie : zombies){
if((zombie.getLastUpdate() - System.currentTimeMillis()) > 1000){
// checking if it's time to update position. Zombie contains a long for the last time it updated
zombie.movePos(0,-1);
// adds this to the current internal Point and update last update time
}
}
您也可以凝聚,對於循環下來for(Zombie zombie : zombies) zombie.update();
,並有所有的代碼中該功能。
你應該考慮的另一件事是實現一個頂級類的層次結構來封裝所有其他類,可能以接口或抽象類的形式,就像這樣。
- Zombie interface - branching types of Zombies including normal zombie
Entity interface - Plant interface - branching types of Plants
- Shots from plants as interface - branching types of shots
要回答你的如何跟蹤跟蹤殭屍的動作和殭屍產生的問題,你可以有一個棧和遊戲不同的殭屍類型的列表開始之前,那麼隨着比賽的進行填補這一棧,它慢慢地讓所有的殭屍,讓它最終結束。
要求玩家放置植物的位置可以通過詢問植物放置位置的座標來完成。至於實際獲取輸入,您很可能需要一個單獨的輸入線程來從控制檯讀取輸入。
隨着我的建議,你給我們的樣品可以改寫爲
public static void main(String[] args) throws InterruptedException {
Stack<Zombie> zombiesToSpawn = fillZombieStack(); // creates zombies in order of when they spawn
// If you want a zombie to spawn 10 seconds after the game starts, you would set the time to be 10*1000 milliseconds plus the current time
List<Plants> plants = ArrayList<>();
List<Zombies> zombies = ArrayList<>();
while(!zombies.isEmpty()){
if(!zombiesToSpawn.empty() &&
zombiesToSpawn.peek().getLastUpdateTime() <= System.currentTimeMillis()){
// last update time gets reused here as when to spawn
Zombie currentZombie = zombiesToSpawn.pop();
zombies.add(currentZombie) // creates zombie at specified position
System.out.printf("%s appeared in Row %d Column %d\n" +
"with the following initialized values\n" +
"Health = %d\n" +
"Damage = %d\n" +
"Speed = %d\n",
currentZombie.getName(),
currentZombie.getPos().x+1,
currentZombie.getPos().y+1,
currentZombie.getHealth(),
currentZombie.getDamage(),
currentZombie.getSpeed()
);
}
for(Zombie zombie : zombies){
if(!zombie.update()) continue; // if it updates, return true, else return false
System.out.printf("Zombie previously in Row %d Column %d moved to Row %d Column %d\n",
zombie.getPos().x+1,
zombie.getPos().y+2,
zombie.getPos().x+1,
zombie.getPos().y+1
);
}
}
}
此代碼應在多個方法來擴展和遊戲對象的內部可能完成。
希望這會有所幫助!
你打算如何在文本模式下更新屏幕?你需要某種Java curses庫。 –