用 java 写一个推箱子的代码
时间: 2023-05-15 08:08:13 浏览: 75
好的,以下是一个简单的推箱子游戏的 Java 代码:
```
import java.util.Scanner;
public class PushBoxGame {
static 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}
};
static int playerX = 1;
static int playerY = 1;
static int boxX = 3;
static int boxY = 3;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
printMap();
System.out.print("请输入移动方向(w/a/s/d): ");
String direction = scanner.next();
movePlayer(direction);
if (isWin()) {
System.out.println("恭喜你,推箱子成功!");
break;
}
}
}
public 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("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();
}
}
public static void movePlayer(String direction) {
int newX = playerX;
int newY = playerY;
switch (direction) {
case "w":
newY--;
break;
case "a":
newX--;
break;
case "s":
newY++;
break;
case "d":
newX++;
break;
}
if (map[newY][newX] == 0) {
playerX = newX;
playerY = newY;
} else if (newX == boxX && newY == boxY) {
int newBoxX = boxX;
int newBoxY = boxY;
switch (direction) {
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;
playerX = newX;
playerY = newY;
}
}
}
public static boolean isWin() {
return boxX == 5 && boxY == 5;
}
}
```
这个代码实现了一个简单的推箱子游戏,玩家可以通过输入"w/a/s/d"来移动角色,将箱子推到指定位置即可获胜。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)