用java写一个推箱子小游戏
时间: 2023-12-07 21:58:00 浏览: 101
好的,下面是一个简单的推箱子小游戏的 Java 代码实现。游戏规则是玩家需要把所有箱子推到指定的位置上,才能通关。
```java
import java.util.Scanner;
public class PushBoxGame {
// 游戏地图
private static int[][] map = {
{1, 1, 1, 1, 1, 1, 1, 1},
{1, 0, 0, 0, 0, 0, 0, 1},
{1, 0, 0, 0, 0, 0, 0, 1},
{1, 0, 0, 0, 0, 0, 0, 1},
{1, 0, 0, 2, 0, 0, 0, 1},
{1, 0, 0, 0, 3, 0, 0, 1},
{1, 0, 0, 0, 0, 3, 4, 1},
{1, 1, 1, 1, 1, 1, 1, 1}
};
// 箱子和目标位置的编号
private static final int BOX = 2;
private static final int TARGET = 3;
// 玩家坐标
private static int playerX = 4;
private static int playerY = 1;
// 游戏是否结束
private static boolean isGameOver = false;
// 打印地图
private static void printMap() {
for (int[] row : map) {
for (int col : row) {
switch (col) {
case 0:
System.out.print(" ");
break;
case 1:
System.out.print("#");
break;
case 2:
System.out.print("$");
break;
case 3:
System.out.print(".");
break;
case 4:
System.out.print("*");
break;
}
}
System.out.println();
}
}
// 判断是否胜利
private static boolean checkWin() {
for (int[] row : map) {
for (int col : row) {
if (col == BOX) {
return false;
}
}
}
return true;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (!isGameOver) {
printMap();
System.out.println("请输入方向(上:w,下:s,左:a,右:d):");
String direction = scanner.next();
int nextX = playerX;
int nextY = playerY;
// 根据玩家输入的方向计算下一个位置的坐标
switch (direction) {
case "w":
nextX--;
break;
case "s":
nextX++;
break;
case "a":
nextY--;
break;
case "d":
nextY++;
break;
}
// 判断下一个位置是否能走
if (map[nextX][nextY] == 0 || map[nextX][nextY] == TARGET) {
// 更新玩家坐标
playerX = nextX;
playerY = nextY;
} else if (map[nextX][nextY] == BOX) {
// 判断箱子能否推动
int nextBoxX = nextX;
int nextBoxY = nextY;
switch (direction) {
case "w":
nextBoxX--;
break;
case "s":
nextBoxX++;
break;
case "a":
nextBoxY--;
break;
case "d":
nextBoxY++;
break;
}
// 判断箱子下一个位置是否能推
if (map[nextBoxX][nextBoxY] == 0 || map[nextBoxX][nextBoxY] == TARGET) {
// 更新箱子坐标和玩家坐标
map[nextBoxX][nextBoxY] = BOX;
map[nextX][nextY] = 0;
playerX = nextX;
playerY = nextY;
}
}
// 判断是否胜利
if (checkWin()) {
System.out.println("恭喜您通关!");
isGameOver = true;
}
}
scanner.close();
}
}
```
这个实现比较简单,没有考虑到一些高级功能,例如悔棋、计时等,但足以作为一个简单的推箱子小游戏的范例。
阅读全文