Java绘制迷宫动画并显示的示例代码

 更新时间:2022年08月29日 17:02:59   作者:天人合一peng  
这篇文章主要为大家详细介绍了如何利用Java语言实现绘制迷宫动画并显示,文中的示例代码讲解详细,对我们学习Java有一定帮助,需要的可以参考一下

一次性全部绘制出来

实现代码

import java.awt.*;
 
public class AlgoVisualizer {
 
    private static int DELAY = 200;
    private static int blockSide = 8;
 
    private MazeData data;
    private AlgoFrame frame;
 
    public AlgoVisualizer(String mazeFile){
 
        // 初始化数据
        data = new MazeData(mazeFile);
        int sceneHeight = data.N() * blockSide;
        int sceneWidth = data.M() * blockSide;
        
 
        // 初始化视图
        EventQueue.invokeLater(() -> {
            frame = new AlgoFrame("Maze Solver Visualization", sceneWidth, sceneHeight);
 
            new Thread(() -> {
                run();
            }).start();
        });
    }
 
    public void run(){
 
        setData();
    }
 
    private void setData(){
    	
		frame.render(data);
        AlgoVisHelper.pause(DELAY);	 
    	
 
    }
 
    
    public static void main(String[] args) {
 
        String mazeFile = "maze_101_101.txt";
 
        AlgoVisualizer vis = new AlgoVisualizer(mazeFile);
 
    }
}
 
 
 
 
 
 
 
 
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Scanner;
 
 
public class MazeData {
 
    public static final char ROAD = ' ';
    public static final char WALL = '#';
 
    private int N, M;
    private char[][] maze;
    
 
    public MazeData(String filename){
 
        if(filename == null)
            throw new IllegalArgumentException("Filename can not be null!");
 
        Scanner scanner = null;
        try{
            File file = new File(filename);
            if(!file.exists())
                throw new IllegalArgumentException("File " + filename + " doesn't exist");
 
            FileInputStream fis = new FileInputStream(file);
            scanner = new Scanner(new BufferedInputStream(fis), "UTF-8");
 
            // 读取第一行
            String nmline = scanner.nextLine();
            String[] nm = nmline.trim().split("\\s+");
            //System.out.print(nm[0] + ' ' + nm[1]);
 
            N = Integer.parseInt(nm[0]);
            // System.out.println("N = " + N);
            M = Integer.parseInt(nm[1]);
            // System.out.println("M = " + M);
 
            // 读取后续的N行
            maze = new char[N][M];
            for(int i = 0 ; i < N ; i ++){
                String line = scanner.nextLine();
 
                // 每行保证有M个字符
                if(line.length() != M)
                    throw new IllegalArgumentException("Maze file " + filename + " is invalid");
                for(int j = 0 ; j < M ; j ++)
                    maze[i][j] = line.charAt(j);
            }
        }
        catch(IOException e){
            e.printStackTrace();
        }
        finally {
            if(scanner != null)
                scanner.close();
        }
        
    }
 
    public int N(){ return N; }
    public int M(){ return 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];
    }
 
    public boolean inArea(int x, int y){
        return x >= 0 && x < N && y >= 0 && y < M;
    }
 
    public void print(){
        System.out.println(N + " " + M);
        for(int i = 0 ; i < N ; i ++){
            for(int j = 0 ; j < M ; j ++)
                System.out.print(maze[i][j]);
            System.out.println();
        }
        return;
    }
 
}
 
 
 
 
 
 
 
import java.awt.*;
import java.awt.geom.Ellipse2D;
 
import java.awt.geom.Rectangle2D;
import java.lang.InterruptedException;
 
 
public class AlgoVisHelper {
 
    private AlgoVisHelper(){}
 
    public static final Color Red = new Color(0xF44336);
    public static final Color Pink = new Color(0xE91E63);
    public static final Color Purple = new Color(0x9C27B0);
    public static final Color DeepPurple = new Color(0x673AB7);
    public static final Color Indigo = new Color(0x3F51B5);
    public static final Color Blue = new Color(0x2196F3);
    public static final Color LightBlue = new Color(0x03A9F4);
    public static final Color Cyan = new Color(0x00BCD4);
    public static final Color Teal = new Color(0x009688);
    public static final Color Green = new Color(0x4CAF50);
    public static final Color LightGreen = new Color(0x8BC34A);
    public static final Color Lime = new Color(0xCDDC39);
    public static final Color Yellow = new Color(0xFFEB3B);
    public static final Color Amber = new Color(0xFFC107);
    public static final Color Orange = new Color(0xFF9800);
    public static final Color DeepOrange = new Color(0xFF5722);
    public static final Color Brown = new Color(0x795548);
    public static final Color Grey = new Color(0x9E9E9E);
    public static final Color BlueGrey = new Color(0x607D8B);
    public static final Color Black = new Color(0x000000);
    public static final Color White = new Color(0xFFFFFF);
 
 
    public static void strokeCircle(Graphics2D g, int x, int y, int r){
 
        Ellipse2D circle = new Ellipse2D.Double(x-r, y-r, 2*r, 2*r);
        g.draw(circle);
    }
 
    public static void fillCircle(Graphics2D g, int x, int y, int r){
 
        Ellipse2D circle = new Ellipse2D.Double(x-r, y-r, 2*r, 2*r);
        g.fill(circle);
    }
 
    public static void strokeRectangle(Graphics2D g, int x, int y, int w, int h){
 
        Rectangle2D rectangle = new Rectangle2D.Double(x, y, w, h);
        g.draw(rectangle);
    }
 
    public static void fillRectangle(Graphics2D g, int x, int y, int w, int h){
 
        Rectangle2D rectangle = new Rectangle2D.Double(x, y, w, h);
        g.fill(rectangle);
    }
 
    public static void setColor(Graphics2D g, Color color){
        g.setColor(color);
    }
 
    public static void setStrokeWidth(Graphics2D g, int w){
        int strokeWidth = w;
        g.setStroke(new BasicStroke(strokeWidth, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
    }
 
    public static void pause(int t) {
        try {
            Thread.sleep(t);
//            System.out.println("Dely");
        }
        catch (InterruptedException e) {
            System.out.println("Error sleeping");
        }
    }
 
}
 
 
 
 
 
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.getMaze(i, j) == MazeData.WALL)
                        AlgoVisHelper.setColor(g2d, AlgoVisHelper.LightBlue);
                    else
                        AlgoVisHelper.setColor(g2d, AlgoVisHelper.White);
                    
                    AlgoVisHelper.fillRectangle(g2d, j * w, i * h, w, h);
                }
            }
        }
 
        @Override
        public Dimension getPreferredSize(){
            return new Dimension(canvasWidth, canvasHeight);
        }
    }
}

一个一个的动画显示

DELAY时间不能太小,小了会绘制时出错,可能是线程出问题了???

import java.awt.*;
 
public class AlgoVisualizer {
 
    private static int DELAY = 10;
    private static int blockSide = 8;
 
    private MazeData data;
    private AlgoFrame frame;
 
    public AlgoVisualizer(String mazeFile){
 
        // 初始化数据
        data = new MazeData(mazeFile);
        int sceneHeight = data.N() * blockSide;
        int sceneWidth = data.M() * blockSide;
        
 
        // 初始化视图
        EventQueue.invokeLater(() -> {
            frame = new AlgoFrame("Maze Solver Visualization", sceneWidth, sceneHeight);
 
            new Thread(() -> {
                run();
            }).start();
        });
    }
 
    public void run(){
    	      
        for (int i = 0; i < data.N(); i++) {
        	
        	for (int j = 0; j < data.M(); j++) {
        		setData(i, j); 
			}
		}      
    }
 
    private void setData(int i, int j){
    	
      	data.currentN = i;
    	data.currentM = j;
  
		frame.render(data);
        AlgoVisHelper.pause(DELAY);	 
 
    }
 
    
    public static void main(String[] args) {
 
        String mazeFile = "maze_101_101.txt";
 
        AlgoVisualizer vis = new AlgoVisualizer(mazeFile);
 
    }
}
 
 
 
 
 
 
 
 
 
import java.awt.*;
 
public class AlgoVisualizer {
 
    private static int DELAY = 10;
    private static int blockSide = 8;
 
    private MazeData data;
    private AlgoFrame frame;
 
    public AlgoVisualizer(String mazeFile){
 
        // 初始化数据
        data = new MazeData(mazeFile);
        int sceneHeight = data.N() * blockSide;
        int sceneWidth = data.M() * blockSide;
        
 
        // 初始化视图
        EventQueue.invokeLater(() -> {
            frame = new AlgoFrame("Maze Solver Visualization", sceneWidth, sceneHeight);
 
            new Thread(() -> {
                run();
            }).start();
        });
    }
 
    public void run(){
    	      
        for (int i = 0; i < data.N(); i++) {
        	
        	for (int j = 0; j < data.M(); j++) {
        		setData(i, j); 
			}
		}      
    }
 
    private void setData(int i, int j){
    	
      	data.currentN = i;
    	data.currentM = j;
  
		frame.render(data);
        AlgoVisHelper.pause(DELAY);	 
 
    }
 
    
    public static void main(String[] args) {
 
        String mazeFile = "maze_101_101.txt";
 
        AlgoVisualizer vis = new AlgoVisualizer(mazeFile);
 
    }
}
 
 
 
 
 
 
 
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 n = 0; n < data.N(); n ++ )
            {
                for(int m = 0 ; m < data.M()  ; m ++){
                	     
              	  if (data.drawFinshed[n][m]) {
              		  
                      if (data.getMaze(n, m) == MazeData.WALL)
                          AlgoVisHelper.setColor(g2d, AlgoVisHelper.LightBlue);
                      else
                          AlgoVisHelper.setColor(g2d, AlgoVisHelper.White);
                                             
                      AlgoVisHelper.fillRectangle(g2d, m * w, n * h, w, h);
  				 }
                }
            }
        
            	          	  
      	      
              for(int i = data.currentN, j = 0 ; j < data.currentM + 1 ; j ++){
            	              	                         	             	
                  if (data.getMaze(i, j) == MazeData.WALL)
                      AlgoVisHelper.setColor(g2d, AlgoVisHelper.LightBlue);
                  else
                      AlgoVisHelper.setColor(g2d, AlgoVisHelper.White);
                                         
                  AlgoVisHelper.fillRectangle(g2d, j * w, i * h, w, h);
                  data.drawFinshed[i][j] = true;
              }
                               
            
            
以前一次性全部绘制显示出来
//            for(int i = 0 ; i < data.N() ; i ++ )
//            {
//                for(int j = 0 ; j < data.M() ; j ++){
//                    if (data.getMaze(i, j) == MazeData.WALL)
//                        AlgoVisHelper.setColor(g2d, AlgoVisHelper.LightBlue);
//                    else
//                        AlgoVisHelper.setColor(g2d, AlgoVisHelper.White);
//                    
//                    AlgoVisHelper.fillRectangle(g2d, j * w, i * h, w, h);
//                }
//            }
            
        }
 
        @Override
        public Dimension getPreferredSize(){
            return new Dimension(canvasWidth, canvasHeight);
        }
    }
}

到此这篇关于Java绘制迷宫动画并显示的示例代码的文章就介绍到这了,更多相关Java迷宫内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Hibernate懒加载之<class>标签上的lazy

    Hibernate懒加载之<class>标签上的lazy

    这篇文章主要介绍了Hibernate懒加载之<class>标签上的lazy,分享了相关代码示例,小编觉得还是挺不错的,具有一定借鉴价值,需要的朋友可以参考下
    2018-02-02
  • 详细介绍使用Java调用Python的四种方法

    详细介绍使用Java调用Python的四种方法

    这篇文章主要给大家介绍了关于使用Java调用Python的四种方法,每种方法根据实际项目需求有其适用场景,其中,推荐使用Runtime.getRuntime()方法,因为它更为简洁且易于实现,需要的朋友可以参考下
    2024-10-10
  • 解决IDEA使用maven创建Web项目,出现500错误的问题

    解决IDEA使用maven创建Web项目,出现500错误的问题

    本文主要介绍了在使用Maven创建项目并导入依赖写完测试代码后运行出现500错误的解决步骤,这种问题的根本原因是Tomcat启动后缺少某些支持的jar包,导致运行出错,解决方法是在项目结构中找到Artifacts,点击要编辑的项目
    2024-10-10
  • Java中增强for循环在一维数组和二维数组中的使用方法

    Java中增强for循环在一维数组和二维数组中的使用方法

    下面小编就为大家带来一篇Java中增强for循环在一维数组和二维数组中的使用方法。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2016-10-10
  • java 中锁的性能提高办法

    java 中锁的性能提高办法

    这篇文章主要介绍了java 中锁的性能提高办法的相关资料,需要的朋友可以参考下
    2017-02-02
  • Java实现对华北、华南、华东和华中四个区域的划分

    Java实现对华北、华南、华东和华中四个区域的划分

    在Java中,通过定义枚举类、编写主程序和进行测试,本文详细介绍了如何划分华北、华南、华东和华中四个区域,首先定义枚举类标识区域,然后通过主程序接收用户输入并返回相应区域,最后通过测试用例确保正确性,文章还介绍了甘特图和饼状图的使用
    2024-09-09
  • java构造方法的作用总结

    java构造方法的作用总结

    在本篇文章里小编给大家整理了关于java构造方法的相关知识点以及实例代码,有需要的朋友们可以学习下。
    2019-07-07
  • MyBatis-plus 模糊查询的使用

    MyBatis-plus 模糊查询的使用

    这篇文章主要介绍了MyBatis-plus 模糊查询的使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-09-09
  • 简单谈谈JVM、JRE和JDK的区别与联系

    简单谈谈JVM、JRE和JDK的区别与联系

    简单的说JDK是用于开发的而JRE是用于运行Java程序的。JDK和JRE都包含了JVM,从而使得我们可以运行Java程序。JVM是Java编程语言的核心并且具有平台独立性。
    2016-05-05
  • spring cloud如何集成nacos配置中心

    spring cloud如何集成nacos配置中心

    这篇文章主要介绍了spring cloud如何集成nacos配置中心操作,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-09-09

最新评论