java推箱子小游戏代码
时间: 2023-07-02 22:04:45 浏览: 37
以下是一个简单的 Java 推箱子小游戏的代码:
```java
import java.util.Scanner;
public class PushBoxGame {
// 地图数组
private static char[][] map = {
{'#', '#', '#', '#', '#', '#', '#', '#', '#', '#'},
{'#', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', '#'},
{'#', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', '#'},
{'#', ' ', ' ', ' ', ' ', ' ', '#', '#', '#', '#'},
{'#', ' ', ' ', ' ', 'O', ' ', ' ', ' ', ' ', '#'},
{'#', ' ', ' ', ' ', 'O', ' ', ' ', ' ', ' ', '#'},
{'#', '#', '#', '#', '#', '#', '#', '#', '#', '#'}
};
// 玩家位置
private static int playerX = 4;
private static int playerY = 1;
// 箱子位置
private static int boxX = 4;
private static int boxY = 4;
public static void main(String[] args) {
while (true) {
// 打印地图
printMap();
// 获取用户输入
Scanner scanner = new Scanner(System.in);
System.out.print("请输入移动方向(w:上,s:下,a:左,d:右):");
String input = scanner.nextLine();
// 移动玩家
switch (input) {
case "w":
if (map[playerX - 1][playerY] == ' ') {
map[playerX][playerY] = ' ';
playerX--;
map[playerX][playerY] = '@';
} else if (map[playerX - 1][playerY] == 'O' && map[playerX - 2][playerY] == ' ') {
map[playerX][playerY] = ' ';
playerX--;
map[playerX][playerY] = '@';
map[boxX][boxY] = ' ';
boxX--;
map[boxX][boxY] = 'O';
}
break;
case "s":
if (map[playerX + 1][playerY] == ' ') {
map[playerX][playerY] = ' ';
playerX++;
map[playerX][playerY] = '@';
} else if (map[playerX + 1][playerY] == 'O' && map[playerX + 2][playerY] == ' ') {
map[playerX][playerY] = ' ';
playerX++;
map[playerX][playerY] = '@';
map[boxX][boxY] = ' ';
boxX++;
map[boxX][boxY] = 'O';
}
break;
case "a":
if (map[playerX][playerY - 1] == ' ') {
map[playerX][playerY] = ' ';
playerY--;
map[playerX][playerY] = '@';
} else if (map[playerX][playerY - 1] == 'O' && map[playerX][playerY - 2] == ' ') {
map[playerX][playerY] = ' ';
playerY--;
map[playerX][playerY] = '@';
map[boxX][boxY] = ' ';
boxY--;
map[boxX][boxY] = 'O';
}
break;
case "d":
if (map[playerX][playerY + 1] == ' ') {
map[playerX][playerY] = ' ';
playerY++;
map[playerX][playerY] = '@';
} else if (map[playerX][playerY + 1] == 'O' && map[playerX][playerY + 2] == ' ') {
map[playerX][playerY] = ' ';
playerY++;
map[playerX][playerY] = '@';
map[boxX][boxY] = ' ';
boxY++;
map[boxX][boxY] = 'O';
}
break;
default:
System.out.println("无效输入,请重新输入!");
}
// 判断是否胜利
if (map[boxX][boxY] == '#' && map[boxX - 1][boxY] == '#' && map[boxX][boxY - 1] == '#' && map[boxX][boxY + 1] == '#' && map[boxX + 1][boxY] == '#') {
System.out.println("恭喜你,推箱子成功!");
break;
}
}
}
// 打印地图
private static void printMap() {
for (char[] row : map) {
for (char c : row) {
System.out.print(c);
}
System.out.println();
}
}
}
```
运行代码后,会在控制台中显示一个初始地图,然后等待用户输入移动方向。用户输入移动方向后,程序会根据输入移动玩家和箱子,并重新打印地图。当箱子被移动到指定位置时,程序会提示用户推箱子成功,游戏结束。