java推箱子游戏源代码
时间: 2023-07-11 16:41:57 浏览: 27
下面是一个简单的 Java 推箱子游戏的源代码,希望能对你有帮助:
```
import java.util.Scanner;
public class PushBoxGame {
private static int[][] map = {
{1, 1, 1, 1, 1, 1, 1},
{1, 0, 0, 0, 0, 0, 1},
{1, 0, 3, 2, 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}
};
private static int playerX = 2, playerY = 2;
public static void main(String[] args) {
while (true) {
printMap();
if (checkWin()) {
System.out.println("Congratulations! You win!");
break;
}
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
move(input);
}
}
private 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 (map[i][j] == 1) {
System.out.print("# ");
} else if (map[i][j] == 2) {
System.out.print("O ");
} else if (map[i][j] == 3) {
System.out.print("X ");
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
private static boolean checkWin() {
for (int i = 0; i < map.length; i++) {
for (int j = 0; j < map[i].length; j++) {
if (map[i][j] == 2) {
return false;
}
}
}
return true;
}
private static void move(String input) {
int dx = 0, dy = 0;
if (input.equals("w")) {
dy = -1;
} else if (input.equals("s")) {
dy = 1;
} else if (input.equals("a")) {
dx = -1;
} else if (input.equals("d")) {
dx = 1;
}
int nextX = playerX + dx, nextY = playerY + dy;
if (map[nextY][nextX] == 0) {
playerX = nextX;
playerY = nextY;
} else if (map[nextY][nextX] == 2) {
int nextBoxX = nextX + dx, nextBoxY = nextY + dy;
if (map[nextBoxY][nextBoxX] == 0) {
playerX = nextX;
playerY = nextY;
map[nextBoxY][nextBoxX] = 2;
map[nextY][nextX] = 0;
}
}
}
}
```
这个游戏使用了一个二维数组来表示地图,其中 1 表示墙,0 表示空地,2 表示箱子,3 表示目标点,P 表示玩家。玩家可以通过输入 w、s、a、d 来移动,如果移动到了箱子旁边,可以推动箱子。当所有的箱子都被推到目标点上时,玩家获胜。