我正在写一个用java绘制一系列矩形的蛇程序。我不明白如何按顺序延迟块的方向更改,以便蛇形矩形在与箭头键相同的位置全部改变方向。我需要在一种方法中等待程序的其余部分继续运行。当按下箭头键,它会触发这个方法来改变我的矩形的方向(U最多,d为降...)如何在一个单一的方法内延迟,而不是延迟在java中的整个程序?
`public void changeDirection(String dir)
{
for(int i = 0; i<snakearray.size(); i++)
{
//checks to make sure youre not changing straight from l to r or u to d
if(dir.equals("r")||dir.equals("l"))
{
if(//direction of currect element is up or down)
//makes the current element of the array change to the new direction
{snakearray.set(i, snakearray.get(i).newDirection(dir));}
}
else if(dir.equals("u")||dir.equals("d"))
{
if(//current element's direction is right or left)
{snakearray.set(i, snakearray.get(i).newDirection(dir));}
}
//pause method but not game method needed here????
}
}`
有实现暂停,我需要一种方式?我已经尝试了thread.sleep(20)方法,但暂停了我的整个程序...
此代码将需要在它自己的线程 –
如果你想要这种行为,你应该创建另一个线程并使用它。 但直到你这样做,你会睡主线程 –
只是在你的主要方法把线程t =新线程(changeDirection),然后t.sleep(无论)。 –