用Java实现一个迷宫游戏

 

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)。可以根据需要修改迷宫的大小和起点位置。

 

  • 8
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个Java实现迷宫游戏,其中包含计时器功能: ```java import java.util.*; import java.text.*; public class Maze { private int[][] maze; private int row; private int col; private int startX; private int startY; private int endX; private int endY; private long startTime; private long endTime; public Maze(int row, int col) { this.row = row; this.col = col; maze = new int[row][col]; } public void generateMaze() { Random rand = new Random(); for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { if (i == 0 || j == 0 || i == row - 1 || j == col - 1) { maze[i][j] = 1; // 设置边界为墙壁 } else { maze[i][j] = rand.nextInt(2); // 随机生成空地或墙壁 } } } startX = rand.nextInt(row - 2) + 1; startY = rand.nextInt(col - 2) + 1; endX = rand.nextInt(row - 2) + 1; endY = rand.nextInt(col - 2) + 1; maze[startX][startY] = 2; // 设置起点 maze[endX][endY] = 3; // 设置终点 } public void printMaze() { for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { if (maze[i][j] == 0) { System.out.print(" "); // 空地 } else if (maze[i][j] == 1) { System.out.print("██"); // 墙壁 } else if (maze[i][j] == 2) { System.out.print("S "); // 起点 } else if (maze[i][j] == 3) { System.out.print("E "); // 终点 } } System.out.println(); } } public void findPath() { Queue<int[]> queue = new LinkedList<>(); boolean[][] visited = new boolean[row][col]; int[][] directions = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; queue.offer(new int[]{startX, startY, 0}); visited[startX][startY] = true; while (!queue.isEmpty()) { int[] pos = queue.poll(); int x = pos[0]; int y = pos[1]; int step = pos[2]; if (x == endX && y == endY) { System.out.println("最佳路径长度为:" + step); return; } for (int[] direction : directions) { int newX = x + direction[0]; int newY = y + direction[1]; if (newX >= 0 && newX < row && newY >= 0 && newY < col && !visited[newX][newY] && maze[newX][newY] != 1) { queue.offer(new int[]{newX, newY, step + 1}); visited[newX][newY] = true; } } } System.out.println("没有找到最佳路径!"); } public void play() { Scanner scanner = new Scanner(System.in); System.out.print("请输入迷宫的行数:"); int row = scanner.nextInt(); System.out.print("请输入迷宫的列数:"); int col = scanner.nextInt(); Maze maze = new Maze(row, col); maze.generateMaze(); maze.printMaze(); startTime = System.currentTimeMillis(); while (true) { System.out.print("请输入移动方向(上:w,下:s,左:a,右:d):"); String direction = scanner.next(); int newX = startX; int newY = startY; if (direction.equals("w")) { newX--; } else if (direction.equals("s")) { newX++; } else if (direction.equals("a")) { newY--; } else if (direction.equals("d")) { newY++; } if (newX >= 0 && newX < row && newY >= 0 && newY < col && maze.maze[newX][newY] != 1) { maze.maze[startX][startY] = 0; maze.maze[newX][newY] = 2; startX = newX; startY = newY; maze.printMaze(); if (startX == endX && startY == endY) { endTime = System.currentTimeMillis(); long duration = endTime - startTime; SimpleDateFormat sdf = new SimpleDateFormat("mm:ss"); sdf.setTimeZone(TimeZone.getTimeZone("GMT")); System.out.println("恭喜你,成功走出迷宫!"); System.out.println("用时:" + sdf.format(duration)); break; } } else { System.out.println("不能移动到该位置!"); } } } public static void main(String[] args) { Maze maze = new Maze(10, 10); maze.generateMaze(); maze.printMaze(); maze.findPath(); maze.play(); } } ``` 在这个迷宫游戏中,我们使用了Java的Scanner类来读取用户输入,使用了Java的Queue接口来实现广度优先搜索算法,使用了Java的System.currentTimeMillis()方法来计时,使用了Java的SimpleDateFormat类来格式化时间。您可以根据需要修改代码以满足您的需求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值