Java写一段程序,体现贪吃蛇游戏中食物不出现在蛇身体上的部分代码
时间: 2024-05-07 18:16:50 浏览: 20
请见下面的 Java 代码,体现了贪吃蛇游戏中食物不出现在蛇身体上:
```java
import java.util.*;
public class SnakeGame {
private int width;
private int height;
private int[][] food;
private int foodIndex;
private int score;
private LinkedList<int[]> snake; // use LinkedList to implement snake
public SnakeGame(int width, int height, int[][] food) {
this.width = width;
this.height = height;
this.food = food;
foodIndex = 0;
score = 0;
snake = new LinkedList<>();
snake.add(new int[]{0, 0}); // initially the snake is at (0, 0) position
}
public int move(String direction) {
int[] head = snake.getFirst();
int[] tail = snake.removeLast();
int[] next = new int[2]; // next position of the snake's head
switch(direction) {
case "U":
next[0] = head[0] - 1;
next[1] = head[1];
break;
case "D":
next[0] = head[0] + 1;
next[1] = head[1];
break;
case "L":
next[0] = head[0];
next[1] = head[1] - 1;
break;
case "R":
next[0] = head[0];
next[1] = head[1] + 1;
break;
}
if(next[0] < 0 || next[0] >= height || next[1] < 0 || next[1] >= width) {
return -1; // hit the wall
}
for(int[] body: snake) {
if(next[0] == body[0] && next[1] == body[1]) {
return -1; // hit its own body
}
}
if(foodIndex < food.length && next[0] == food[foodIndex][0] && next[1] == food[foodIndex][1]) {
foodIndex++;
score++;
snake.addFirst(head);
snake.addLast(tail);
return score;
}
snake.addFirst(next);
return score;
}
public static void main(String[] args) {
int width = 3;
int height = 3;
int[][] food = {{2, 0}, {0, 1}, {0, 2}, {2, 2}};
SnakeGame game = new SnakeGame(width, height, food);
System.out.println(game.move("R")); // 0
System.out.println(game.move("D")); // 0
System.out.println(game.move("R")); // 1
System.out.println(game.move("U")); // 1
System.out.println(game.move("L")); // 2
System.out.println(game.move("U")); // -1 (game over)
}
}
```
在这个程序中,食物的坐标存储在一个二维数组 food 中,在每个move中判断蛇头下一步是否会碰到食物,如果是,则将蛇变长,score+1,否则,只移动蛇头。在判断下一步的位置是否合法时,需要同时判断是否碰到墙壁和蛇身,这可以通过遍历蛇身上的所有位置来实现。在这个程序中,为了使得食物不会出现在蛇身体上,我们只需要在判断蛇头下一步是否会碰到食物时,判断食物的坐标和蛇头下一步的坐标是否相同即可。