点击上方“简说Python”,选择“置顶/星标公众号”
福利干货,第一时间送达!
【作者简介】
冒绿光的盒子,公众号投稿作者,个人简书主页:https://www.jianshu.com/u/cbacf40d927f。
走迷宫
显示迷宫
迷宫生成等等再提,先看一下迷宫的读取和显示。
第一行是行数和列数,代表有101行101列,这个迷宫后面可以使用最小生成树生成。读进一个迷宫:
public class MazeData {
private char[][] maze;private int N, M;public static final char ROAD = '#';public static final char WALL = ' ';public MazeData(String fileName) {
if (fileName == null) {
throw new IllegalArgumentException("filename can't be null!");
}
Scanner scanner = null;try {
File file = new File(fileName);if (!file.exists()) {
throw new IllegalArgumentException("File is not exist!");
}
FileInputStream fileInputStream = new FileInputStream(file);
scanner = new Scanner(new BufferedInputStream(fileInputStream), "UTF-8");
String nm = scanner.nextLine();
String[] nmC = nm.trim().split("\\s+");
N = Integer.parseInt(nmC[0]);
M = Integer.parseInt(nmC[1]);
maze = new char[N][M];for (int i = 0; i String line = scanner.nextLine();if (line.length() != M) {
throw new IllegalArgumentException("Message of file is not completed!");
}for (int j = 0; j maze[i][j] = line.charAt(j);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (scanner != null) {
scanner.close();
}
}
}public char getMaze(int i, int j) {
if (!inArea(i, j)) {
throw new IllegalArgumentException("out of range!");
}return maze[i][j];
}public boolean inArea(int x, int y) {
return x >= 0 && x = 0 && y }public int N() {
return N;
}public int M() {
return M;
}
}
使用File来获得当前文件,如果没有就要抛出异常。scanner获得输入流之后可以通过读取下一行获得每一行的内容,列数在前面已经提到了,所以要检查每一行是不是M列,不是就没得读了。#就是墙,空格是路,可以设置两个静态变量表示。同时还需要各种辅助函数,比如是否是在整区域里面的,返回当前区域的值等等。然后就是显示函数了:
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.ROAD){
AlgorithmHelper.setColor(graphics2D, AlgorithmHelper.LightBlue);
}else {
AlgorithmHelper.setColor(graphics2D, AlgorithmHelper.White);
}
AlgorithmHelper.fillRectangle(graphics2D, j * w, i * h, w, h);