【发布时间】:2026-01-31 11:40:01
【问题描述】:
对象应该每 5 秒改变一次模式(运动算法)。我第一次尝试使用 while 循环,但循环的迭代速度太快了。然后我添加了Thread.sleep(5000),但我的对象仍然只在一种算法中移动(scatterMode)。这是算法:
//LEVEL 1
//scatter for 7s
//chase for 20s
//scatter for 7s
//chase for 20s
//scatter for 5s
//chase for 20s
//scatter for 5s
//chase indefinite
这是代码。构造函数和变量声明在底部,如果需要查看的话。
public void updateMode() throws InterruptedException {
while(ghostalive){
if(seconds<7){
Thread.sleep(100);
mode = scatterMode;
}
if(7<seconds && seconds<27){
Thread.sleep(5000);
mode = chaseMode;
}
if(27<seconds && seconds<34){
Thread.sleep(5000);
mode = scatterMode;
}
if(34<seconds && seconds<54) {
Thread.sleep(5000);
mode = chaseMode;
}
if(54<seconds && seconds>59) {
mode = scatterMode;
}
if(59< seconds && seconds<79){
mode = chaseMode;
}
if(seconds>84){
mode = scatterMode;
ghostalive=false;
}
seconds++;
ghostalive=false;
}
}
private int seconds=0;
private boolean ghostalive=true;
protected static final int chaseMode = 0;
protected static final int scatterMode = 1;
static int mode = scatterMode; //initially ghost start in scatterMode
public Ghost(int x, int y, Maze maze) throws InterruptedException{
super(x, y, maze);
futureDirection = 0;
timer = 0;
updateMode();
//chaseMode = false;
//frightenedMode = false;
}
public static int getMode(){
return mode;
}
【问题讨论】:
-
您只是将秒数增加 1,而您的睡眠时间从十分之一秒(100 毫秒)到 5 秒(5000 毫秒)不等。
-
很抱歉,您的大部分代码没有多大意义,而且您尝试实现 Ghost 的方式也行不通。在编写游戏之前,您真的应该更多地研究 Java 基础知识。
标签: java multithreading while-loop sleep