java 可视化、行走迷宫游戏的实现(包括 DFS 自动查找迷宫解决方案) - 数据层
最编程
2024-06-29 21:04:10
...
本实例需要从 .txt 文件中读取迷宫并绘制,所以先来实现文件读取IO类 MazeData.java,该程序在构造函数运行时将外部文件读入,并完成迷宫各种参数的初始化,注意规定了外部 .txt 文件的第一行两个数字分别代表迷宫的行数和列数。此外还提供了各类接口来读取或操作私有数据。
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;
private int entranceX, entranceY; // 入口
private int exitX, exitY; // 出口
public boolean[][] visited; // 记录寻路过程某位置是否被访问过
public boolean[][] path; // 存储迷宫的解
public boolean showPath; // 是否打印系统提示的开关
public Position player; // 玩家所处位置
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+"); // 正则 匹配任意空白字符
N = Integer.parseInt(nm[0]);
上一篇: 迷宫算法,右手定则