java推箱子游戏源代码
时间: 2023-07-01 11:09:55 浏览: 160
以下是一个简单的 Java 推箱子游戏的源代码:
```java
import java.util.Scanner;
public class PushBoxGame {
private int[][] map; // 地图
private int playerX; // 玩家横坐标
private int playerY; // 玩家纵坐标
private int boxX; // 箱子横坐标
private int boxY; // 箱子纵坐标
private int targetX; // 目标点横坐标
private int targetY; // 目标点纵坐标
public PushBoxGame() {
// 初始化地图
map = new int[][] {
{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}
};
// 初始化玩家和箱子位置
playerX = 1;
playerY = 1;
boxX = 3;
boxY = 3;
// 初始化目标点位置
targetX = 5;
targetY = 5;
// 显示初始地图
showMap();
}
private void showMap() {
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 (i == targetY && j == targetX) {
System.out.print("T ");
} else if (map[i][j] == 1) {
System.out.print("# ");
} else {
System.out.print(". ");
}
}
System.out.println();
}
}
private void movePlayer(int dx, int dy) {
// 判断玩家是否越界
if (playerX + dx < 0 || playerX + dx >= map[0].length
|| playerY + dy < 0 || playerY + dy >= map.length) {
System.out.println("你不能走出边界!");
return;
}
// 判断玩家是否遇到墙壁
if (map[playerY + dy][playerX + dx] == 1) {
System.out.println("你不能穿过墙壁!");
return;
}
// 判断玩家是否推动箱子
if (playerX + dx == boxX && playerY + dy == boxY) {
// 判断箱子是否越界
if (boxX + dx < 0 || boxX + dx >= map[0].length
|| boxY + dy < 0 || boxY + dy >= map.length) {
System.out.println("箱子不能被推出边界!");
return;
}
// 判断箱子是否遇到墙壁
if (map[boxY + dy][boxX + dx] == 1) {
System.out.println("箱子不能被推穿过墙壁!");
return;
}
// 移动箱子和玩家
boxX += dx;
boxY += dy;
playerX += dx;
playerY += dy;
} else {
// 移动玩家
playerX += dx;
playerY += dy;
}
}
private boolean checkWin() {
return boxX == targetX && boxY == targetY;
}
public void play() {
Scanner input = new Scanner(System.in);
while (true) {
System.out.print("请输入方向(上:w,下:s,左:a,右:d):");
String direction = input.next().toLowerCase();
switch (direction) {
case "w":
movePlayer(0, -1);
break;
case "s":
movePlayer(0, 1);
break;
case "a":
movePlayer(-1, 0);
break;
case "d":
movePlayer(1, 0);
break;
default:
System.out.println("无效的方向!");
break;
}
showMap();
if (checkWin()) {
System.out.println("恭喜你获胜!");
break;
}
}
input.close();
}
public static void main(String[] args) {
PushBoxGame game = new PushBoxGame();
game.play();
}
}
```
这个推箱子游戏只是一个简单的示例,地图、玩家、箱子和目标点都是固定的,如果你想要实现更加复杂的游戏,可以考虑设计更加灵活的地图和随机生成游戏元素的算法。
阅读全文