【发布时间】:2017-09-09 00:12:54
【问题描述】:
我正在用 Java 编写一个绘制一系列矩形的蛇形程序。我不明白如何延迟块的方向变化,以便蛇形矩形在按下箭头键的同一位置改变方向。当程序的其余部分继续运行时,我需要在一种方法中等待。当按下箭头键时,它会触发此方法来改变我的矩形的方向(u 代表向上,d 代表向下......)
`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) 方法,但这会暂停我的整个程序......
【问题讨论】:
-
这段代码需要在自己的线程中
-
如果你想要这种行为,你应该创建另一个线程并使用它。但在你这样做之前,你会睡主线程
-
在你的 main 方法中放 Thread t = new Thread(changeDirection) 然后 t.sleep(whatever)。
-
听起来像是 XY 问题。 meta.stackexchange.com/questions/66377/what-is-the-xy-problem 实现蛇游戏不需要线程和延迟。
-
@ammoQ 确实如此,更糟糕的是人们正在回答 Y。
标签: java thread-sleep pause delayed-execution