java可视化,实现走迷宫小游戏(包含随机迷宫生成、BFS自动寻找迷宫解)

本文阅读 4 分钟
首页 代码,Java 正文

本文是对我之前整理的一篇文章的续集, 传送门。主要是想实现随机生成迷宫的算法并在此基础上进行走迷宫的小游戏。本程序适用于java程序员巩固类与对象、文件读取、事件响应、awt包中各种工具的相关概念以及对逻辑能力的锻炼。欢迎联系我vx:wjw0310。

最终效果如下:

img

img

数据层

设计 MazeData.java 类,来存储和迷宫相关的数据,包括迷宫的大小(行、列),存储迷宫、解的路径的字符矩阵,出口和入口以及玩家的位置信息等并提供外部可调用的查询方法。

此外,还设计了判断某一坐标是否在迷宫内、获取迷宫某一坐标处的信息的方法。

public class MazeData {

    public static final char ROAD = ' ';
    public static final char WALL = '#';

    private int N, M;
    public char[][] maze;
    public boolean[][] visited;
    public boolean[][] path;
    public Position player;
    public boolean showPath;

    private int entranceX, entranceY;
    private int exitX, exitY;

    public MazeData(int N, int M){

        if( N%2 == 0 || M%2 == 0)
            throw new IllegalArgumentException("Our Maze Generalization Algorihtm requires the width and height of the maze are odd numbers");

        this.N = N;
        this.M = M;

        maze = new char[N][M];
        visited = new boolean[N][M];
        path = new boolean[N][M];
        for(int i = 0 ; i < N ; i ++)
            for(int j = 0 ; j < M ; j ++){
                if(i%2 == 1 && j%2 == 1)
                    maze[i][j] = ROAD;
                else
                    maze[i][j] = WALL;

                visited[i][j] = false;
                path[i][j] = false;
            }
        showPath = false;

        entranceX = 1;
        entranceY = 0;
        exitX = N - 2;
        exitY = M - 1;

        maze[entranceX][entranceY] = ROAD;
        maze[exitX][exitY] = ROAD;
    }

    public int N(){ return N; }
    public int M(){ return M; }
    public int getEntranceX(){ return entranceX; }
    public int getEntranceY(){ return entranceY; }
    public int getExitX(){ return exitX; }
    public int getExitY(){ return exitY; }

    public boolean inArea(int x, int y){
        return x >= 0 && x < N && y >= 0 && y < M;
    }

    public char getMaze(int i, int j){
        if (!inArea(i, j))
            throw new IllegalArgumentException("i or j is out of index in getMaze!");

        return maze[i][j];
    }
}

同样将迷宫的各个位置封装成一个类 Position.java,便于操作,这里不做赘述。 详情

视图层

AlgoFrame.java 是绘制界面的核心代码,使用java的JFrame控件,在上面添加JPanel画板,在JFrame中定义渲染方法render来调用画板的 paintComponent 方法实现绘制,其中需要用到自己定义的绘制辅助类 AlgoVisHelper.java,在里面封装了绘制矩形,设置画笔颜色,停顿等方法,也定义了一些颜色,也可以不用定义该辅助类而直接在 AlgoFrame.java 中使用awt包中的各种方法直接实现,如有需要可自行下载代码。  

import java.awt.*;
import javax.swing.*;

public class AlgoFrame extends JFrame{

    private int canvasWidth;
    private int canvasHeight;

    public AlgoFrame(String title, int canvasWidth, int canvasHeight){

        super(title);

        this.canvasWidth = canvasWidth;
        this.canvasHeight = canvasHeight;

        AlgoCanvas canvas = new AlgoCanvas();
        setContentPane(canvas);
        pack();

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setResizable(false);

        setVisible(true);
    }

    public AlgoFrame(String title){

        this(title, 1024, 768);
    }

    public int getCanvasWidth(){return canvasWidth;}
    public int getCanvasHeight(){return canvasHeight;}

    // data
    private MazeData data;
    public void render(MazeData data){
        this.data = data;
        repaint();
    }

    private class AlgoCanvas extends JPanel{

        public AlgoCanvas(){
            // 双缓存
            super(true);
        }

        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);

            Graphics2D g2d = (Graphics2D)g;

            // 抗锯齿
            RenderingHints hints = new RenderingHints(
                    RenderingHints.KEY_ANTIALIASING,
                    RenderingHints.VALUE_ANTIALIAS_ON);
            hints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
            g2d.addRenderingHints(hints);

            // 具体绘制
            int w = canvasWidth/data.M();
            int h = canvasHeight/data.N();

            for(int i = 0 ; i < data.N() ; i ++ )
                for(int j = 0 ; j < data.M() ; j ++){
                    if(data.maze[i][j] == MazeData.WALL)
                        AlgoVisHelper.setColor(g2d, AlgoVisHelper.LightBlue);
                    else
                        AlgoVisHelper.setColor(g2d, AlgoVisHelper.White);

                    if(data.path[i][j] && data.showPath == true)
                        AlgoVisHelper.setColor(g2d, AlgoVisHelper.Yellow);

                    if (data.player.getX() == i && data.player.getY() == j)
                        AlgoVisHelper.setColor(g2d, AlgoVisHelper.Red);

                    AlgoVisHelper.fillRectangle(g2d, j * w, i * h, w, h);
            }
        }

        @Override
        public Dimension getPreferredSize(){
            return new Dimension(canvasWidth, canvasHeight);
        }
    }
}

控制层

主函数 AlgoVisualizer.java ,初始化过程封装在 initial 函数中,主要完成随机迷宫的生成以及通过基于递归的DFS算法将迷宫的解事先求出,用户按下空格则可以实现提示功能,红色表示玩家,键盘上下左右控制四个方向的移动。run()方法实现了所有的动画逻辑。

import java.awt.*;
import java.awt.event.*;

public class AlgoVisualizer {

    private static int DELAY = 5;
    private static int blockSide = 8;

    private MazeData data;
    private AlgoFrame frame;
    private static final int d[][] = {
  {-1,0},{0,1},{1,0},{0,-1}};

    public AlgoVisualizer(int N, int M){

        // 初始化数据
        data = new MazeData(N, M);
        int sceneHeight = data.N() * blockSide;
        int sceneWidth = data.M() * blockSide;

        // 初始化视图
        EventQueue.invokeLater(() -> {
            frame = new AlgoFrame("Random Maze Generation Visualization", sceneWidth, sceneHeight);
            frame.addKeyListener(new AlgoKeyListener());

            new Thread(() -> {
                run();
            }).start();
        });
    }

    private void run(){

        setRoadData(-1, -1);

        if (initial())
            System.out.println("初始化已完成");

        while (true){
            frame.render(data);
            AlgoVisHelper.pause(DELAY);
        }

    }

    private boolean initial(){
        data.player = new Position(data.getEntranceX(), data.getEntranceY());
        RandomQueue<Position> queue = new RandomQueue<Position>();
        Position first = new Position(data.getEntranceX(), data.getEntranceY()+1);
        queue.add(first);
        data.visited[first.getX()][first.getY()] = true;

        while(queue.size() != 0){
            Position curPos = queue.remove();

            for(int i = 0 ; i < 4  ; i ++){
                int newX = curPos.getX() + d[i][0]*2;
                int newY = curPos.getY() + d[i][1]*2;

                if(data.inArea(newX, newY) && !data.visited[newX][newY]){
                    queue.add(new Position(newX, newY));
                    data.visited[newX][newY] = true;
                    setRoadData(curPos.getX() + d[i][0], curPos.getY() + d[i][1]);
                }
            }
        }
        for(int i = 0 ; i < data.N() ; i ++)
            for(int j = 0 ; j < data.M() ; j ++)
                data.visited[i][j] = false;
        new Thread(() -> {
            go(data.getEntranceX(), data.getEntranceY());
        }).start();
        return true;
    }

    private boolean go(int x, int y){

        if(!data.inArea(x,y))
            throw new IllegalArgumentException("x,y are out of index in go function!");

        data.visited[x][y] = true;
        setPathData(x, y, true);

        if(x == data.getExitX() && y == data.getExitY())
            return true;

        for(int i = 0 ; i < 4 ; i ++){
            int newX = x + d[i][0];
            int newY = y + d[i][1];
            if(data.inArea(newX, newY) &&
                    data.maze[newX][newY] == MazeData.ROAD &&
                    !data.visited[newX][newY])
                if(go(newX, newY))
                    return true;
        }

        // 回溯
        setPathData(x, y, false);

        return false;
    }

    private void setRoadData(int x, int y){
        if(data.inArea(x, y))
            data.maze[x][y] = MazeData.ROAD;
    }

    private void setPathData(int x, int y, boolean isPath){
        if(data.inArea(x, y))
            data.path[x][y] = isPath;
    }

    private class AlgoKeyListener extends KeyAdapter{

        @Override
        public void keyPressed(KeyEvent event){
            if (event.getKeyCode() == KeyEvent.VK_LEFT){
                System.out.println("go left");
                oneStep(data.player.getX(), data.player.getY(), 3);
            }
            else if (event.getKeyCode() == KeyEvent.VK_DOWN){
                System.out.println("go down");
                oneStep(data.player.getX(), data.player.getY(), 2);
            }
            else if (event.getKeyCode() == KeyEvent.VK_RIGHT){
                System.out.println("go right");
                oneStep(data.player.getX(), data.player.getY(), 1);
            }
            else if (event.getKeyCode() == KeyEvent.VK_UP){
                System.out.println("go up");
                oneStep(data.player.getX(), data.player.getY(), 0);
            }
            else if (event.getKeyChar() == ' '){
                System.out.println("显示提示");
                data.showPath = !data.showPath;
            }
        }
    }

    private void oneStep(int x, int y, int direction){
        int newX = x + d[direction][0];
        int newY = y + d[direction][1];
        if (data.inArea(newX, newY) &&
                data.getMaze(newX, newY) == MazeData.ROAD){
            data.player.setX(newX);
            data.player.setY(newY);
        }
    }

    public static void main(String[] args) {

        int N = 101;
        int M = 101;

        AlgoVisualizer vis = new AlgoVisualizer(N, M);

    }
}

其中随机迷宫的生成算法是使用随机队列的数据结构来实现的,随机队列底层基于java的链表类 LinkedList 来实现的,数据入队的操作是随机在头部或尾部进行添加,数据出队的操作是随机在头部或尾部取出数据。初始时,将迷宫的入口位置入队,之后每次从随机队列中取出一个位置,并将与这个位置相邻的四个方向入队,循环至队列为空。

随机队列:

import java.util.LinkedList;

public class RandomQueue<E>{

    private LinkedList<E> queue;

    public RandomQueue(){
        queue = new LinkedList<E>();
    }

    public void add(E e){
        if(Math.random() < 0.5)
            queue.addFirst(e);
        else
            queue.addLast(e);
    }

    public E remove(){
        if(queue.size() == 0)
            throw new IllegalArgumentException("There's no element to remove in Random Qeuue");


        if(Math.random() < 0.5)
            return queue.removeFirst();
        else
            return queue.removeLast();
    }

    public int size(){
        return queue.size();
    }

    public boolean empty(){
        return size() == 0;
    }
}
本文为互联网自动采集或经作者授权后发布,本文观点不代表立场,若侵权下架请联系我们删帖处理!文章出自:https://wangjiawei.blog.csdn.net/article/details/105323702
-- 展开阅读全文 --
安全面试之XSS(跨站脚本攻击)
« 上一篇 07-24

发表评论

成为第一个评论的人

热门文章

标签TAG

最近回复