canvas随机生成一个迷宫并自动寻找出口算法效果代码
代码语言:html
所属分类:其他
代码描述:canvas随机生成一个迷宫并自动寻找出口算法效果代码
下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style>
form {
padding: 20px;
}
label {
padding: 5px;
}
</style>
</head>
<body>
<form name="mazedetails" action="javascript:letsGo()">
<label for="width">Width:</label> <input type="number" name="width" id="width" value="40" size="5" min="2" max="40">
<label for="height">Height:</label> <input type="number" name="height" id="height" value="24" size="5" min="2" max="40">
<label for="boxsize">Box Size:</label> <input type="number" name="boxsize" id="boxsize" value="15" size="5" min="6" max="50">
<input type="submit" value="Generate a new maze">
<button type="button" onclick="javascript:solveAnimation()">Solve Animation</button>
</form>
<canvas id="mymaze" width="650" height="650"></canvas>
<script>
let maze, interval;
class Square {
constructor() {
this.south = true;
this.east = true;
this.accessible = false;
this.color = "white";
}
openSouth() {
this.south = false;
}
openEast() {
this.east = false;
}
markAccessible() {
this.accessible = true;
}
setColor(color) {
this.color = color;
}}
class Maze {
constructor(height, width, pixels) {
this.height = height;
this.width = width;
this.pixels = pixels;
this.starth = -1;
this.endh = -1;
this.squares = new Array(height);
for (let h = 0; h < height; h++) {
this.squares[h] = new Array(width);
for (let w = 0; w < width; w++) {
this.squares[h][w] = new Square();
}
}
}
getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
resetAccessibility() {
for (let h = 1; h < this.height; h++) {
for (let w = 1; w < this.width; w++) {
this.squares[h][w].accessible = false;
this.squares[h][w].setColor("white");
}
}
}
build() {
for (let w = 0; w < this.width; w++) {
this.squares[0][w].south = true;
this.squares[0][w].east = false;
this.squares[0][w].acessible = true;
}
for (let h = 0; h < this.height; h++) {
this.squares[h][0].south = false;
this.squares[h][0].east = true;
this.squares[h][0].accessible = true;
}
this.squares[0][0].east = false;
let start_w = this.getRandomInt(1, this.width);
let start_h = this.getRandomInt(1, this.height);
this.pipeline = [[start_h, start_w, -100, -100]];
this.breakWall();
this.starth = this.getRandomInt(1, this.height);
this.endh = this.getRandomInt(1, this.height);
this.squares[this.starth][0].east = false;
this.squares[this.endh][this.width - 1].east = false;
}
addRoom(start_h, start_w, parent_h, parent_w) {
if (
.........完整代码请登录后点击上方下载按钮下载查看
网友评论0