0
所以我作出了snake game,但如果我從一個方向移動到另一真快,然後它說我做了身體碰撞並結束遊戲(例如,如果我向左走,我打了下來,然後再次離開,真的很快或下來,真的很快,等等)貪吃蛇遊戲 - 衝突錯誤
我已經嘗試了幾件事。我改變了檢查衝突的方式,將它作爲.intersects
而不是檢查if (x == body[i][0] && y = body[i][1]
)。我也做了一些System.out.println()
的查看是否有可能出現問題。我注意到有時候有一個值重複出現(x或y取決於方向),但我無法弄清楚爲什麼......我認爲重複是爲什麼它弄亂了碰撞,但我找不到它會重複的地方。
x和y正在被一個線程改變。
這是我的代碼的「繪圖」部分。如果您需要其他代碼片段,請告訴我。
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (numOfFood == 1) {//Checks wether there is food on the GUI
g.setColor(Color.BLUE);
g.fillRect(foodX,foodY,12,12);
}
else {
foodX = random.nextInt(103)*12; //Both this and the below line get a random x or y value to put on GUI for food placement
foodY = random.nextInt(57)*12;
numOfFood = 1;
}
Rectangle headRect = new Rectangle(x, y, 12, 12); //Actual rectangle of the head
Rectangle foodRect = new Rectangle(foodX, foodY, 12, 12); //Food rectangle
g.setColor(Color.RED);
g.fillRect(x,y,12,12); //Draws head of Snake
g.setColor(Color.WHITE);
g.fillRect(x+2,y+2,8,8); //Draws a white square in the head of the snake
for (int i = 0; i < n; ++i) { //Collision Checker
Rectangle bodyRect = new Rectangle(body[i][0],body[i][1],12,12);
if (headRect.intersects(bodyRect)) {
for (int j = 0; j < n; ++j) {
body[j][0] = -1;
body[j][1] = -1;
}
numOfFood = 1;
n = 0;
x = 624;
y = 348;
endGame = true;
}
}
g.setColor(Color.RED);
if (n > 0) { //Puts the snakes body behind the head
for (int i = 0;i < n; ++i) {
g.fillRect(body[i][0],body[i][1],12,12);
}
}
for (int i = n-1;i >= 0; --i) { //Inserts the head at the first part of the array so that the body moves
if (body[i][0] != -1 && body[i][1] != -1) {
body[i+1][0] = body[i][0];
body[i+1][1] = body[i][1];
}
if (i == 0) {
body[i][0] = x;
body[i][1] = y;
}
}
if (headRect.intersects(foodRect)) { //If the food rectangle and the head rectangle intersect then the snake got the food.
numOfFood = 0;
n++;
}
}
同樣,您在paintComponent方法中不存在程序邏輯。問題是你無法完全控制何時或者甚至是否調用paintComponent方法。通過程序邏輯,我的意思是任何使用隨機變量,任何碰撞檢查,任何在此方法之外的變量的設置,如endGame,numOfFood和body數組。你需要把這個邏輯放在你的遊戲循環中,用它來設置類字段,調用repaint,然後讓paintComponent畫出圖像,就是這樣。 –
這與我在最後一個主題中給出的建議是一樣的,但我猜你不相信我? –
@HovercraftFullOfEels我搬了一些東西,我想我沒有完全理解你告訴我做的一些事情。我將邊框和背景顏色的東西移到了較早的區域,並且它有所幫助。它使蛇能夠被繪製在哪裏。我現在要做你在這裏說的話。再次感謝。 – Aerophite