用java写一个推箱子的游戏
时间: 2023-05-18 07:06:27 浏览: 84
好的,以下是一个简单的推箱子游戏的 Java 代码:
```
import java.util.Scanner;
public class PushBoxGame {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
char[][] map = {
{'#', '#', '#', '#', '#', '#', '#', '#', '#', '#'},
{'#', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', '#'},
{'#', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', '#'},
{'#', ' ', ' ', ' ', ' ', ' ', '#', '#', '#', '#'},
{'#', ' ', ' ', ' ', ' ', ' ', '#', ' ', ' ', '#'},
{'#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#'},
{'#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#'},
{'#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#'},
{'#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#'},
{'#', '#', '#', '#', '#', '#', '#', '#', '#', '#'}
};
int playerRow = 5;
int playerCol = 5;
int boxRow = 4;
int boxCol = 5;
while (true) {
// 打印地图
for (int i = 0; i < map.length; i++) {
for (int j = 0; j < map[i].length; j++) {
if (i == playerRow && j == playerCol) {
System.out.print('P');
} else if (i == boxRow && j == boxCol) {
System.out.print('B');
} else {
System.out.print(map[i][j]);
}
}
System.out.println();
}
// 判断是否完成
if (boxRow == 2 && boxCol == 8) {
System.out.println("You win!");
break;
}
// 获取用户输入
System.out.print("Please input direction (w/a/s/d): ");
String direction = scanner.nextLine();
// 移动箱子
int boxNewRow = boxRow;
int boxNewCol = boxCol;
switch (direction) {
case "w":
boxNewRow--;
break;
case "a":
boxNewCol--;
break;
case "s":
boxNewRow++;
break;
case "d":
boxNewCol++;
break;
}
if (map[boxNewRow][boxNewCol] == ' ') {
map[boxRow][boxCol] = ' ';
map[boxNewRow][boxNewCol] = 'B';
boxRow = boxNewRow;
boxCol = boxNewCol;
}
// 移动玩家
int playerNewRow = playerRow;
int playerNewCol = playerCol;
switch (direction) {
case "w":
playerNewRow--;
break;
case "a":
playerNewCol--;
break;
case "s":
playerNewRow++;
break;
case "d":
playerNewCol++;
break;
}
if (map[playerNewRow][playerNewCol] == ' ') {
playerRow = playerNewRow;
playerCol = playerNewCol;
}
}
}
}
```
这个代码实现了一个简单的推箱子游戏,玩家可以通过输入 w/a/s/d 来移动箱子和玩家,当箱子被推到指定位置时,游戏结束。
阅读全文