2017-11-11 66 views
-1

这是我第一次在Stackoverflow和Java编程。我总是喜欢经典的贪吃蛇游戏,开发它的副本既有趣又有启发性。爪哇蛇碰撞

我的Snake.java具有树属性;

private Position head; 
private ArrayList<Position> body; 
private char currentDirection; 

此外,它具有从箭头键移动移动方向的移动方法。该方法生成一个位置“newHead”,并将其放置在移动后“头部”必须位于的位置。

switch (newDirection) { 
case 'u': 
    if (currentDirection != 'd') { 
     newHead.y = newHead.y - 10; 
     currentDirection = 'u'; 
    } else { 
     newHead.y = newHead.y + 10; 
    } 
    break; 
    //This method continues for all directions like that. 

在此之后,我将“head”添加到“body”,并使用“newHead”作为“head”。

body.add(new Position(head.x, head.y)); 
head = new Position(newHead.x, newHead.y); 
body.remove(0); 

正如你所看到的,这提供了平滑的运动。但是,我无法弄清楚在移动时如何检查碰撞到身体或墙壁。你能给我一些想法或伪代码吗?

回答

1

你可以在下面查看我为你写的代码来获得一些想法。我用wallL和wallR代表你的墙的位置。

public boolean checkCollision(Position newhead) { 
    //To check whether newHead is collided to body, and if it occurs returns true 
    for (int i = 0; i < getBodyLength(); i++) { 
     if (newhead.x == body.get(i).x && newhead.y == body.get(i).y) { 
      return true; 
     } 
    } 
    //To check whether newHead is collided to wall, and if it occurs return true 
    if(newhead.x == wallL.x|| newhead.x == wallL.y || newhead.y == wallR.x || newhead.y == wallR.y) 
return true; 
    return false; 
} 

您需要在将前头添加到身体之前控制碰撞。

+0

我明白了,谢谢。 – roy