用java写一个推箱子的代码
时间: 2023-05-17 20:07:05 浏览: 417
好的,以下是一个简单的 Java 推箱子游戏的代码:
```java
import java.util.Scanner;
public class PushBoxGame {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[][] map = {
{1, 1, 1, 1, 1, 1, 1},
{1, 0, 0, 0, 0, 0, 1},
{1, 0, 0, 0, 0, 0, 1},
{1, 0, 0, 0, 0, 0, 1},
{1, 0, 0, 0, 0, 0, 1},
{1, 0, 0, 0, 0, 0, 1},
{1, 1, 1, 1, 1, 1, 1}
};
int playerX = 1, playerY = 1;
int boxX = 3, boxY = 3;
while (true) {
// 打印地图
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("P");
} else if (i == boxY && j == boxX) {
System.out.print("B");
} else if (map[i][j] == 1) {
System.out.print("#");
} else {
System.out.print(" ");
}
}
System.out.println();
}
// 判断是否胜利
if (boxX == 5 && boxY == 5) {
System.out.println("You win!");
break;
}
// 获取玩家输入
System.out.print("Please input direction (w/a/s/d): ");
String input = scanner.nextLine();
// 移动箱子
int newBoxX = boxX, newBoxY = boxY;
switch (input) {
case "w":
newBoxY--;
break;
case "a":
newBoxX--;
break;
case "s":
newBoxY++;
break;
case "d":
newBoxX++;
break;
}
if (map[newBoxY][newBoxX] == 0) {
boxX = newBoxX;
boxY = newBoxY;
}
// 移动玩家
int newPlayerX = playerX, newPlayerY = playerY;
switch (input) {
case "w":
newPlayerY--;
break;
case "a":
newPlayerX--;
break;
case "s":
newPlayerY++;
break;
case "d":
newPlayerX++;
break;
}
if (map[newPlayerY][newPlayerX] == 0) {
playerX = newPlayerX;
playerY = newPlayerY;
}
}
}
}
```
这个代码实现了一个简单的推箱子游戏,玩家通过键盘输入 w/a/s/d 来控制人物移动,推动箱子到指定位置即可胜利。
阅读全文