import java.util.Scanner;
public class MazeGame {
private char[][] maze;
private int startRow;
private int startCol;public MazeGame(char[][] maze, int startRow, int startCol) {
this.maze = maze;
this.startRow = startRow;
this.startCol = startCol;
}public void play() {
int currentRow = startRow;
int currentCol = startCol;while (true) {
printMaze();System.out.print("Enter your move (W/A/S/D): ");
Scanner scanner = new Scanner(System.in);
char move = scanner.nextLine().toUpperCase().charAt(0);int newRow = currentRow;
int newCol = currentCol;switch (move) {
case 'W':
newRow--;
break;
case 'A':
newCol--;
break;
case 'S':
newRow++;
break;
case 'D':
newCol++;
break;
default:
System.out.println("Invalid move! Please try again.");
continue;
}if (isValidMove(newRow, newCol)) {
currentRow = newRow;
currentCol = newCol;if (maze[currentRow][currentCol] == 'E') {
System.out.println("Congratulations! You have reached the exit.");
break;
}
} else {
System.out.println("Invalid move! Please try again.");
}
}
}private boolean isValidMove(int row, int col) {
if (row < 0 || row >= maze.length || col < 0 || col >= maze[0].length) {
return false;
}char cell = maze[row][col];
return cell != '#';
}private void printMaze() {
for (int row = 0; row < maze.length; row++) {
for (int col = 0; col < maze[0].length; col++) {
if (row == startRow && col == startCol) {
System.out.print('S');
} else {
System.out.print(maze[row][col]);
}
}
System.out.println();
}
}public static void main(String[] args) {
char[][] maze = {
{'#', '#', '#', '#', '#', '#', '#', '#', '#', '#'},
{'#', 'S', ' ', ' ', '#', ' ', ' ', ' ', ' ', '#'},
{'#', '#', '#', ' ', '#', ' ', '#', '#', ' ', '#'},
{'#', ' ', '#', ' ', '#', ' ', ' ', ' ', ' ', '#'},
{'#', ' ', '#', '#', '#', '#', '#', '#', '#', '#'},
{'#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#'},
{'#', '#', '#', '#', '#', '#', '#', '#', 'E', '#'},
};MazeGame game = new MazeGame(maze, 1, 1);
game.play();
}
}
在这个示例中,迷宫游戏使用二维字符数组来表示迷宫,其中`'#'`表示墙壁,`'S'`表示起点,`'E'`表示终点,空格表示可通行的路径。玩家可以通过输入"W"、"A"、"S"、"D"来移动,分别对应上、左、下、右。游戏会在玩家到达终点时结束。
在`play()`方法中,游戏通过循环接受玩家的移动输入,并根据输入更新当前位置。`isValidMove()`方法用于检查玩家的移动是否有效,即是否越界或撞墙。`printMaze()`方法用于打印当前迷宫状态。
在`main()`方法中,创建了一个示例迷宫,并指定起点为(1, 1)。可以根据需要修改迷宫的大小和起点位置。