所以我正在创建一个名为snake的java游戏,我目前仍然坚持如何让蛇的开始在最初移动后不断移动,我试图使用thread.sleep但是我很高兴使用我在错误的地方使用它,任何提示/帮助将不胜感激!
import java.awt.event.KeyEvent;
public class snake
{
static double squareX = .5;
static double squareY = .5;
static double squareR = .02;
static double CsquareR = .01;
static double CsquareX = Math.random();
static double CsquareY = Math.random();
public static void drawScene()
{
StdDraw.clear();
StdDraw.filledSquare(squareX, squareY, squareR);
StdDraw.filledSquare(CsquareX, CsquareY, CsquareR);
StdDraw.show(1000/24);
}
public static void updateMotion() throws InterruptedException
{
if (StdDraw.isKeyPressed(KeyEvent.VK_UP))
{
squareY += .01;
Thread.sleep(10);
}
else if (StdDraw.isKeyPressed(KeyEvent.VK_DOWN))
{
squareY -= .01;
Thread.sleep(10);
}
else if (StdDraw.isKeyPressed(KeyEvent.VK_LEFT))
{
squareX -= .01;
Thread.sleep(10);
}
else if (StdDraw.isKeyPressed(KeyEvent.VK_RIGHT))
{
squareX += .01;
Thread.sleep(10);
}
}
public static void main(String[] args) throws InterruptedException
{
while(true)
{
snake.drawScene();
snake.updateMotion();
if (squareX + squareR >= 1 )
{
//TODO: show "you lose" message / stop on edge of square
break;
}
if (squareX - squareR <= 0)
{
//TODO: show "you win" message / stop on edge of square
break;
}
if (squareY + squareR >= 1 )
{
//TODO: show "you lose" message / stop on edge of square
break;
}
if (squareY - squareR <= 0)
{
//TODO: show "you win" message / stop on edge of square
break;
}
}
}
}
答案 0 :(得分:1)
按按键时,不改变位置,而是改变方向并一直更新位置。
static double xMovement = 0;
static double yMovement = 0;
public static void updatePosition() {
squareX += xMovement;
squareY += yMovement;
}
public static void updateDirection() throws InterruptedException
{
if (StdDraw.isKeyPressed(KeyEvent.VK_UP))
{
xMovement = 0.0;
yMovement = +0.1;
}
else if (StdDraw.isKeyPressed(KeyEvent.VK_DOWN))
{
xMovement = 0.0;
yMovement = -0.1;
}
else if (StdDraw.isKeyPressed(KeyEvent.VK_LEFT))
{
xMovement = -0.1;
yMovement = 0.0;
}
else if (StdDraw.isKeyPressed(KeyEvent.VK_RIGHT))
{
xMovement = +0.1;
yMovement = 0.0;
}
}
public static void main(String[] args) throws InterruptedException
{
while(true)
{
snake.drawScene();
snake.updateDirection();
snake.updatePosition();
...