我正在致力于 Snake 的实现,并且已经基本完成。我唯一的问题是,当我单击用于开始新游戏的 JMenuItem
时,游戏会卡住。相关代码如下:
this.newGame.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e){
neuesSpiel();
}
});
public void neuesSpiel()
{ //The old snake game is finished and the playing field is reseted
if(snake!=null)
{
snake.beendeSpiel();
for(int i=0; i<20;i++)
{
for(int j=0;j<10;j++)
{
spielfeld[i][j] = false;
}
}
}//the new snake game is created below
snake = new Snake(null,null, 10,5, this);
Snake snake2 = new Snake(snake,null,11,5,this);
snake.hintermann = snake2;
snake2.hintermann = new Snake(snake2,null,12,5,this);
snake.run();
}
在 Snake 类中:
public void run()
{
Game.zf.requestFocus();
while(spiellauf){
try
{
Thread.sleep( 120 );
}
catch ( InterruptedException e ) { }
if(spiellauf)
bewege(); //the Snake Block is moved
}
我很确定 run()
方法是问题所在,因为如果我不调用该方法,游戏就不会卡住。此外,neuesSpiel() 方法也应该没问题,因为当我在构造函数中调用它时,它会按预期工作。
我不知道除了使用线程之外,还能如何让我的函数等待 120 毫秒。还有其他选择吗?
提前致谢!
最佳答案
I don´t know how else i can make my function wait for 120ms besides using threads.
您没有使用线程。您正在当前线程中执行 run
方法。
如果你想在新线程中运行它,你需要类似的东西:
new Thread(snake).start();
关于java - 为什么我的 run() 方法没有从我的 Actionlistener 中正确调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31453322/