那你能写出推箱子的JAVA代码吗?
时间: 2023-04-05 20:05:11 浏览: 82
可以的,推箱子的JAVA代码如下:
```
public class PushBox {
public static void main(String[] args) {
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;
int playerY = 1;
int boxX = 2;
int boxY = 2;
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 (map[boxY][boxX] == 2) {
System.out.println("恭喜你完成了推箱子!");
break;
}
// 获取用户输入
Scanner scanner = new Scanner(System.in);
System.out.print("请输入方向(上:w,下:s,左:a,右:d):");
String direction = scanner.nextLine();
// 移动箱子
int newBoxX = boxX;
int newBoxY = boxY;
if (direction.equals("w")) {
newBoxY--;
} else if (direction.equals("s")) {
newBoxY++;
} else if (direction.equals("a")) {
newBoxX--;
} else if (direction.equals("d")) {
newBoxX++;
}
if (map[newBoxY][newBoxX] == 0 || map[newBoxY][newBoxX] == 2) {
boxX = newBoxX;
boxY = newBoxY;
}
// 移动人物
int newPlayerX = playerX;
int newPlayerY = playerY;
if (direction.equals("w")) {
newPlayerY--;
} else if (direction.equals("s")) {
newPlayerY++;
} else if (direction.equals("a")) {
newPlayerX--;
} else if (direction.equals("d")) {
newPlayerX++;
}
if (map[newPlayerY][newPlayerX] == 0 || map[newPlayerY][newPlayerX] == 2) {
playerX = newPlayerX;
playerY = newPlayerY;
}
// 更新地图
if (playerX == boxX && playerY == boxY) {
map[boxY][boxX] = 2;
} else {
map[boxY][boxX] = 0;
}
}
}
}
```
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)