有人在留言问我:
我是个新手java初学者,您可以给我一份用java编程的推箱子游戏代码吗?新手可以看得懂的
我也是新手!那就分享给大家,没做到位的一起学习!
![](https://img-blog.csdnimg.cn/direct/b5d6cf7647ae443393ee7ba817dfcbff.png)
以下是代码:
import java.util.Scanner;
public class Sokoban {
private static final char WALL = '#';
private static final char BOX = '$';
private static final char TARGET = '.';
private static final char PLAYER = '@';
private static final char FLOOR = ' ';
private static final String[] LEVELS = {
"#####
" +
"#@ $ #
" +
"#####",
"#####
" +
"# $#
" +
"# @ #
" +
"#####"
};
public static void main(String[] args) {
int level = 0;
while (true) {
playLevel(level);
level++;
if (level >= LEVELS.length) {
System.out.println("恭喜你完成了所有关卡!");
break;
}
}
}
private static void playLevel(int level) {
char[][] map = parseLevel(LEVELS[level]);
int playerX = -1, playerY = -1;
for (int y = 0; y < map.length; y++) {
for (int x = 0; x < map[y].length; x++) {
if (map[y][x] == PLAYER) {
playerX = x;
playerY = y;
}
}
}
while (true) {
printMap(map);
System.out.println("请输入移动方向(w/a/s/d):");
Scanner scanner = new Scanner(System.in);
char move = scanner.next().charAt(0);
int newX = playerX, newY = playerY;
switch (move) {
case 'w':
newY--;
break;
case 'a':
newX--;
break;
case 's':
newY++;
break;
case 'd':
newX++;
break;
default:
System.out.println("无效的输入,请重新输入。");
continue;
}
if (map[newY][newX] == WALL) {
System.out.println("不能撞墙,请重新输入。");
continue;
}
if (map[newY][newX] == BOX) {
int boxNewX = newX * 2 - playerX;
int boxNewY = newY * 2 - playerY;
if (map[boxNewY][boxNewX] == WALL || map[boxNewY][boxNewX] == BOX) {
System.out.println("不能推动箱子,请重新输入。");
continue;
}
map[boxNewY][boxNewX] = BOX;
}
map[playerY][playerX] = FLOOR;
playerX = newX;
playerY = newY;
map[playerY][playerX] = PLAYER;
boolean win = true;
for (int y = 0; y < map.length; y++) {
for (int x = 0; x < map[y].length; x++) {
if (map[y][x] == BOX && map[y][x] != TARGET) {
win = false;
break;
}
}
}
if (win) {
System.out.println("恭喜你过关了!");
break;
}
}
}
private static char[][] parseLevel(String level) {
String[] lines = level.split("
");
char[][] map = new char[lines.length][];
for (int i = 0; i < lines.length; i++) {
map[i] = lines[i].toCharArray();
}
return map;
}
private static void printMap(char[][] map) {
for (char[] row : map) {
for (char cell : row) {
System.out.print(cell);
}
System.out.println();
}
}
}
这是一个用Java编写的简单的推箱子游戏。游戏中有两个关卡,玩家需要将箱子推到目标位置上。玩家可以使用w/a/s/d键控制角色上下左右移动。如果成功完成所有关卡,程序会输出“恭喜你完成了所有关卡!”。