贪吃蛇中黑体的移动
public void keyPressed(final KeyEvent e)
{
switch (e.getKeyCode())
{
case KeyEvent.VK_LEFT:
new Thread(new Runnable()
{
public synchronized void run()
{
while(e.getKeyCode() != KeyEvent.VK_LEFT) //键盘按键不为向左方向键时不循环
{
System.out.println("左边--");
try
{
Thread.sleep(1000);
}
catch(Exception e)
{
}
}
}
}).start();
break;
case KeyEvent.VK_RIGHT:
new Thread(new Runnable()
{
public synchronized void run()
{
while(e.getKeyCode() != KeyEvent.VK_RIGHT) //键盘按键不为向右方向键时不循环
{
System.out.println("右边--");
try
{
Thread.sleep(1000);
}
catch(Exception e)
{
}
}
}
}).start();
break;
case KeyEvent.VK_UP:
System.out.println("上边--");break;
case KeyEvent.VK_DOWN:
System.out.println("下边--");break;
}
这是贪吃蛇游戏中的部分代码,我想实现自动移动 和 方向改变时,只做一个方向的移动,上述代码无法实现!
请问我的代码应该怎么改进?
------解决方案--------------------
你代码打错了吧e.getKeyCode() != KeyEvent.VK_LEFT应该是e.getKeyCode()== KeyEvent.VK_LEFT
e.getKeyCode() != KeyEvent.VK_RIGHT应该是e.getKeyCode() == KeyEvent.VK_RIGHT