写一个Java贪吃蛇游戏代码
时间: 2024-06-03 08:13:32 浏览: 172
public class SnakeGame {
public static void main(String[] args) {
int width = 10;
int height = 10;
char[][] board = new char[width][height];
// 初始化棋盘
for(int i = 0; i < width; i++) {
for(int j = 0; j < height; j++) {
board[i][j] = ' ';
}
}
// 初始化蛇
int[] headPosition = {0, 0};
int[] tailPosition = {0, 1};
board[headPosition[0]][headPosition[1]] = '@';
board[tailPosition[0]][tailPosition[1]] = '*';
// 游戏循环
while (true) {
// 更新棋盘
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
if (i == headPosition[0] && j == headPosition[1]) {
board[i][j] = '@';
} else if (i == tailPosition[0] && j == tailPosition[1]) {
board[i][j] = '*';
} else {
board[i][j] = ' ';
}
}
}
// 显示棋盘
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
System.out.print(board[i][j]);
}
System.out.println();
}
// 读取用户输入
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = br.readLine();
// 根据输入更新蛇的位置
if (input.equals("w")) {
// 向上移动
headPosition[0]--;
tailPosition[0]--;
} else if (input.equals("s")) {
// 向下移动
headPosition[0]++;
tailPosition[0]++;
} else if (input.equals("a")) {
// 向左移动
headPosition[1]--;
tailPosition[1]--;
} else if (input.equals("d")) {
// 向右移动
headPosition[1]++;
tailPosition[1]++;
}
}
}
}
阅读全文