我需要一些关于我目前正在做的项目的帮助。这是一款植物大战僵尸的游戏,我用计时器不断添加僵尸。
Timer ZombieTimer = new Timer ();
TimerTask task = new TimerTask() { //for continuous arrival of zombies
public void run()
{
Random rand = new Random(); //puts a zombie in a random lane
int a = rand.nextInt(4);
int b=9;
Zombie z = new Zombie();
gardenField[a][b] = z;
System.out.println("New zombie in " + a + " tile " + b);
}
};
ZombieTimer.scheduleAtFixedRate(task, 1000, 8000); //new zombie every 8 seconds现在,在创建一个僵尸对象后,我想让僵尸在它所属的水平阵列中移动(移动到离植物更近的地方)。我也在考虑使用计时器,但我不知道是否应该在僵尸类中传递整个数组。有帮助吗?谢谢。
发布于 2017-06-20 21:05:19
您不需要将数组gardenField传递给僵尸类。
如果你可以在某个地方访问gardenField,那么只需要每隔x个时间间隔更新它们,循环遍历数组中的所有僵尸,并将它们的位置向右移动即可。为此设置一个单独的计时器,它应该可以工作。
发布于 2017-06-20 20:59:35
我认为您走在正确的道路上,但您不需要将列表传递给计时器。在任务的run()方法中,您只需调用外部类中定义的方法updatePositions() (将僵尸向前移动一步)。
发布于 2017-06-20 21:12:05
我会使用ScheduledExecutorService而不是定时器。另外,我会使用ExecutorService让一个线程负责移动僵尸。
例如:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class ZombiesVsPlantsExample {
private static volatile Zombie[][] map = new Zombie[100][100]; // volatile not needed if you synchronize all access to the map. not only writes
public static void main(String[] args) {
ZombiesVsPlantsExample zombiesVsPlantsExample = new ZombiesVsPlantsExample();
zombiesVsPlantsExample.doTheWork();
}
private void doTheWork() {
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); // this thread pool will be used to create zombies
ExecutorService executorService = Executors.newFixedThreadPool(1); // this thread pool will be used to move zombies
ZombieCreator zombieCreator = new ZombieCreator(map);
scheduler.scheduleAtFixedRate(zombieCreator, 2, 8, TimeUnit.SECONDS); // one new zombie every 8 seconds
executorService.submit(new ZombiesPositionProcessor(map));
}
}
class Zombie {
}
class ZombieCreator implements Runnable {
Zombie[][] map;
public ZombieCreator(Zombie[][] map) {
this.map = map;
}
@Override
public void run() {
Zombie zombie = new Zombie();
synchronized(map){
map[1][2] = zombie; // put new zombie in some random location in map
}
System.out.println("new zombie was created");
}
}
class ZombiesPositionProcessor implements Runnable {
Zombie[][] map;
public ZombiesPositionProcessor(Zombie[][] map) {
this.map = map;
}
@Override
public void run() {
while (true) {
// iterate map and move zombies one by one
System.out.println("moving one zombie");
}
}
}https://stackoverflow.com/questions/44653575
复制相似问题