用java写一个推箱子游戏
时间: 2023-05-18 22:07:33 浏览: 32
好的,推箱子游戏是一种经典的益智游戏,以下是一个简单的Java实现:
```java
import java.util.Scanner;
public class PushBoxGame {
// 地图数组
private static char[][] map = {
{'#', '#', '#', '#', '#', '#', '#', '#', '#', '#'},
{'#', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', '#'},
{'#', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', '#'},
{'#', ' ', ' ', ' ', ' ', ' ', '#', '#', '#', '#'},
{'#', ' ', ' ', ' ', ' ', ' ', '#', ' ', ' ', '#'},
{'#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#'},
{'#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#'},
{'#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#'},
{'#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#'},
{'#', '#', '#', '#', '#', '#', '#', '#', '#', '#'}
};
// 箱子的位置
private static int boxX = 4;
private static int boxY = 4;
// 人的位置
private static int playerX = 2;
private static int playerY = 1;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
// 打印地图
printMap();
// 判断是否胜利
if (isWin()) {
System.out.println("恭喜你,游戏胜利!");
break;
}
// 获取用户输入
System.out.print("请输入移动方向(w上 s下 a左 d右):");
String direction = scanner.next();
// 移动人
movePlayer(direction);
// 移动箱子
moveBox(direction);
}
}
// 打印地图
private static void printMap() {
for (int i = 0; i < map.length; i++) {
for (int j = 0; j < map[i].length; j++) {
if (i == playerY && j == playerX) {
System.out.print('人');
} else if (i == boxY && j == boxX) {
System.out.print('箱');
} else {
System.out.print(map[i][j]);
}
}
System.out.println();
}
}
// 判断是否胜利
private static boolean isWin() {
return map[boxY][boxX] == 'G';
}
// 移动人
private static void movePlayer(String direction) {
int newX = playerX;
int newY = playerY;
switch (direction) {
case "w":
newY--;
break;
case "s":
newY++;
break;
case "a":
newX--;
break;
case "d":
newX++;
break;
default:
break;
}
if (map[newY][newX] == ' ') {
playerX = newX;
playerY = newY;
}
}
// 移动箱子
private static void moveBox(String direction) {
int newX = boxX;
int newY = boxY;
switch (direction) {
case "w":
newY--;
break;
case "s":
newY++;
break;
case "a":
newX--;
break;
case "d":
newX++;
break;
default:
break;
}
if (map[newY][newX] == ' ') {
boxX = newX;
boxY = newY;
}
}
}
```
这个推箱子游戏使用二维字符数组来表示地图,其中#表示墙,空格表示空地,G表示目标点,人用“人”字表示,箱子用“箱”字表示。玩家可以通过输入w、s、a、d来控制人的移动,当箱子被推到目标点上时,游戏胜利。