帮我写个贪吃蛇,用java语言
时间: 2023-03-11 14:35:47 浏览: 168
好的,我可以帮你写个贪吃蛇。请注意,我们需要使用Java语言来编写它:// 声明类
public class Snake {
// 定义常量
public static final int UP = 0;
public static final int DOWN = 1;
public static final int LEFT = 2;
public static final int RIGHT = 3;
// 定义变量
private int direction;
private List<Point> body;
// 构造函数
public Snake(int x, int y, int len, int direction) {
this.direction = direction;
body = new ArrayList<Point>();
// 初始化贪吃蛇的身体
for (int i = 0; i < len; i++) {
body.add(new Point(x - i, y));
}
}
// 改变方向
public void turn(int direction) {
this.direction = direction;
}
// 移动
public void move() {
Point head = body.get(0);
int newX = head.x;
int newY = head.y;
switch (direction) {
case UP:
newY--;
break;
case DOWN:
newY++;
break;
case LEFT:
newX--;
break;
case RIGHT:
newX++;
break;
}
body.add(0, new Point(newX, newY));
body.remove(body.size() - 1);
}
}
阅读全文