2017-11-11 64 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