我的编程空间,编程开发者的网络收藏夹
学习永远不晚

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

短信预约 -IT技能 免费直播动态提醒
省份

北京

  • 北京
  • 上海
  • 天津
  • 重庆
  • 河北
  • 山东
  • 辽宁
  • 黑龙江
  • 吉林
  • 甘肃
  • 青海
  • 河南
  • 江苏
  • 湖北
  • 湖南
  • 江西
  • 浙江
  • 广东
  • 云南
  • 福建
  • 海南
  • 山西
  • 四川
  • 陕西
  • 贵州
  • 安徽
  • 广西
  • 内蒙
  • 西藏
  • 新疆
  • 宁夏
  • 兵团
手机号立即预约

请填写图片验证码后获取短信验证码

看不清楚,换张图片

免费获取短信验证码

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迷宫内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

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

下载Word文档到电脑,方便收藏和打印~

下载Word文档

猜你喜欢

Android绘制平移动画的示例代码怎么编写

今天就跟大家聊聊有关Android绘制平移动画的示例代码怎么编写,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。1、具体操作步骤创建ImageView对象创建ObjectAnimato
2023-06-26

Java实现可视化走迷宫小游戏的示例代码

这篇文章主要介绍了Java如何实现可视化走迷宫小游戏。本程序适用于java程序员巩固类与对象、文件读取、事件响应、awt包中各种工具的相关概念以及对逻辑能力的锻炼,需要的可以参考一下
2022-11-13

C语言实现绘制绕线画的示例代码

绕线画简单点来说,就是在木板上钉一圈钉子,通过绕线进行构图,最终呈现出一幅图像。本文将用C语言实现这一效果,感兴趣的小伙伴可以尝试一下
2022-11-13

python绘制字符画视频的示例代码怎么写

读取视频通过imageio读取视频,除了pip install imageio之外,还需要pip install imageio-ffmpeg。由于视频中的图像都是彩色的,故而需要将rgb三色转为单一的强度,并将转化后的图像装入一个列表中
2023-06-25

编程热搜

  • Python 学习之路 - Python
    一、安装Python34Windows在Python官网(https://www.python.org/downloads/)下载安装包并安装。Python的默认安装路径是:C:\Python34配置环境变量:【右键计算机】--》【属性】-
    Python 学习之路 - Python
  • chatgpt的中文全称是什么
    chatgpt的中文全称是生成型预训练变换模型。ChatGPT是什么ChatGPT是美国人工智能研究实验室OpenAI开发的一种全新聊天机器人模型,它能够通过学习和理解人类的语言来进行对话,还能根据聊天的上下文进行互动,并协助人类完成一系列
    chatgpt的中文全称是什么
  • C/C++中extern函数使用详解
  • C/C++可变参数的使用
    可变参数的使用方法远远不止以下几种,不过在C,C++中使用可变参数时要小心,在使用printf()等函数时传入的参数个数一定不能比前面的格式化字符串中的’%’符号个数少,否则会产生访问越界,运气不好的话还会导致程序崩溃
    C/C++可变参数的使用
  • css样式文件该放在哪里
  • php中数组下标必须是连续的吗
  • Python 3 教程
    Python 3 教程 Python 的 3.0 版本,常被称为 Python 3000,或简称 Py3k。相对于 Python 的早期版本,这是一个较大的升级。为了不带入过多的累赘,Python 3.0 在设计的时候没有考虑向下兼容。 Python
    Python 3 教程
  • Python pip包管理
    一、前言    在Python中, 安装第三方模块是通过 setuptools 这个工具完成的。 Python有两个封装了 setuptools的包管理工具: easy_install  和  pip , 目前官方推荐使用 pip。    
    Python pip包管理
  • ubuntu如何重新编译内核
  • 改善Java代码之慎用java动态编译

目录