用JAVAbean实现一个贪吃蛇游戏
时间: 2024-03-24 14:40:15 浏览: 15
好的,下面是一个简单的贪吃蛇游戏的JAVAbean实现:
```
import java.util.ArrayList;
import java.util.Random;
public class SnakeGame {
private int width;
private int height;
private int[][] grid;
private ArrayList<Point> snake;
private Point food;
private Random random;
public SnakeGame(int width, int height) {
this.width = width;
this.height = height;
this.grid = new int[height][width];
this.snake = new ArrayList<>();
this.random = new Random();
init();
}
public void init() {
snake.clear();
snake.add(new Point(width / 2, height / 2));
grid[snake.get(0).y][snake.get(0).x] = 1;
food = getRandomPoint();
grid[food.y][food.x] = -1;
}
public int[][] getGrid() {
return grid;
}
public ArrayList<Point> getSnake() {
return snake;
}
public Point getFood() {
return food;
}
public boolean move(Direction direction) {
Point head = snake.get(0);
Point newHead = new Point(head.x, head.y);
switch (direction) {
case UP:
newHead.y--;
break;
case DOWN:
newHead.y++;
break;
case LEFT:
newHead.x--;
break;
case RIGHT:
newHead.x++;
break;
}
if (newHead.x < 0 || newHead.x >= width || newHead.y < 0 || newHead.y >= height) {
return false;
}
if (grid[newHead.y][newHead.x] > 0 && !newHead.equals(snake.get(snake.size() - 1))) {
return false;
}
snake.add(0, newHead);
if (newHead.equals(food)) {
food = getRandomPoint();
grid[food.y][food.x] = -1;
} else {
Point tail = snake.remove(snake.size() - 1);
grid[tail.y][tail.x] = 0;
}
grid[newHead.y][newHead.x] = 1;
return true;
}
private Point getRandomPoint() {
int x, y;
do {
x = random.nextInt(width);
y = random.nextInt(height);
} while (grid[y][x] != 0);
return new Point(x, y);
}
public enum Direction {
UP, DOWN, LEFT, RIGHT
}
public static class Point {
public int x;
public int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Point point = (Point) o;
return x == point.x &&
y == point.y;
}
@Override
public int hashCode() {
return Objects.hash(x, y);
}
}
}
```
其中,SnakeGame类表示一个贪吃蛇游戏,包含以下成员变量和方法:
- width:游戏区域宽度;
- height:游戏区域高度;
- grid:二维数组,表示游戏区域每个位置的状态,0表示空白,1表示蛇身,-1表示食物;
- snake:ArrayList,存储蛇身的每个点的坐标;
- food:Point,表示当前食物的坐标;
- random:Random,用于生成随机坐标。
初始化游戏时,首先清空蛇身和游戏区域状态,然后将蛇头放在游戏区域中心,将其状态设为1,再随机生成一个食物的坐标,将其状态设为-1。
移动蛇时,根据当前方向计算新的蛇头坐标,如果蛇头超出游戏区域或者撞到自己的身体(除了蛇尾),则游戏结束;如果蛇头吃到了食物,则增加蛇身长度,生成新的食物;否则,移动蛇身,将蛇尾去掉,并更新状态。
Point类表示一个二维坐标点,重写了equals和hashCode方法,使其可以在ArrayList中正确比较和存储。