java语言写推箱子的代码
时间: 2023-10-29 08:07:11 浏览: 152
很高兴为您解答关于java语言写推箱子的代码问题。
以下是一份简单的Java推箱子代码,您可以参考并进行适当的修改和完善。
```
import java.util.Scanner;
public class Sokoban {
// 地图
private static String[][] map =
{{"#", "#", "#", "#", "#", "#", "#", "#", "#", "#"},
{"#", "O", " ", " ", "#", " ", " ", " ", " ", "#"},
{"#", " ", " ", " ", "#", " ", "X", " ", " ", "#"},
{"#", " ", " ", " ", " ", " ", "#", "X", " ", "#"},
{"#", "X", " ", " ", " ", " ", " ", " ", " ", "#"},
{"#", "X", " ", " ", " ", " ", " ", " ", " ", "#"},
{"#", " ", " ", " ", " ", " ", " ", " ", " ", "#"},
{"#", " ", " ", " ", " ", " ", " ", " ", " ", "#"},
{"#", " ", " ", " ", " ", " ", " ", " ", " ", "#"},
{"#", "#", "#", "#", "#", "#", "#", "#", "#", "#"}};
// 玩家坐标
private static int playerRow = 1;
private static int playerCol = 1;
// 移动方向
private static int[] dRow = {-1, 0, 1, 0};
private static int[] dCol = {0, 1, 0, -1};
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
printMap();
while (true) {
System.out.print("请输入移动方向(WASD):");
String direction = scanner.nextLine();
if (direction.equalsIgnoreCase("W")) {
move(-1, 0);
} else if (direction.equalsIgnoreCase("A")) {
move(0, -1);
} else if (direction.equalsIgnoreCase("S")) {
move(1, 0);
} else if (direction.equalsIgnoreCase("D")) {
move(0, 1);
} else {
System.out.println("输入有误,请重新输入。");
}
printMap();
if (isGameFinished()) {
System.out.println("恭喜你,通关了!");
break;
}
}
scanner.close();
}
// 判断是否通关
private static boolean isGameFinished() {
for (int i = 1; i <= 8; i++) {
for (int j = 1; j <= 8; j++) {
if (map[i][j].equals("X")) {
return false;
}
}
}
return true;
}
// 移动
private static void move(int dr, int dc) {
int newRow = playerRow + dr;
int newCol = playerCol + dc;
String next = map[newRow][newCol];
String nextNext = map[newRow + dr][newCol + dc];
if (next.equals(" ") || next.equals("X")) {
map[playerRow][playerCol] = " ";
if (next.equals("X")) {
map[newRow + dr][newCol + dc] = "X";
}
map[newRow][newCol] = "O";
playerRow = newRow;
playerCol = newCol;
} else if (next.equals("O") && (nextNext.equals(" ") || nextNext.equals("X"))) {
map[playerRow][playerCol] = " ";
map[newRow][newCol] = "O";
if (nextNext.equals("X")) {
map[newRow + dr][newCol + dc] = "X";
}
playerRow = newRow;
playerCol = newCol;
}
}
// 打印地图
private static void printMap() {
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
System.out.print(map[i][j]);
}
System.out.println();
}
}
}
```
希望能对您有所帮助!
阅读全文