JSFiddle - React, Tailwind, and code Playground
by Ivan Skorokhodov
HTML
<html>
<head>
<meta charset='utf-8'>
<link rel="stylesheet" type="text/css" href="maze.css">
</head>
<body>
<div id='maze'></div>
<div id='complete'><img alt='MISSION ACCOMPLISHED'src="http://www.androidtapp.com/wp-content/uploads/2012/05/Radiant-Defense-Mission-complete.png"></div>
</body>
<script type="text/javascript" src='maze.js'></script>
</html>
CSS
#maze
{
border-style: solid;
}
.block
{
float: left;
height: 10px;
width: 10px;
}
.wall
{
background-color: #000;
}
.me
{
position: relative;
}
.me:after
{
background-color: #23afee;
border-radius: 100%;
content: '';
height: 10px;
position: absolute;
top: 0;
width: 10px;
}
.finish
{
background-color: #f31d1d;
}
#complete
{
display: none;
height: 360px;
left: 20%;
position: absolute;
right: 20%;
top: 50px;
width: 640px;
z-index: 1000;
}
#complete img
{
height: 100%;
width: 100%;
}
JavaScript
!function(hate, width, maze, walls, currentPosition) {
hate = hate % 2 == 0 ? hate+1 : hate; // в статье было объяснено, почему числа должны быть нечетными
width = width % 2 == 0 ? width + 1 : width; // добавил еще 2 строчки, чтобы люди не страдали и вводили любые числа
document.getElementById('maze').setAttribute('style','height:'+hate*10+'px; width:'+width*10+'px');
for (var y=0; y<hate; y++) {
maze[y] = [];
for (var x = 0; x<width; maze[y][x++] = 'wall') {
var el = document.getElementById('maze').appendChild(document.createElement("div"));
el.className = 'block wall';
el.setAttribute('id', y+'-'+x);
}
}
function amaze(y,x,addBlockWalls) {
maze[y][x] = 'maze';
document.getElementById(y+'-'+x).className = 'block';
if (addBlockWalls && valid(y+1,x) && (maze[y+1][x] == 'wall')) walls.push([y+1, x , [y,x]]);
if (addBlockWalls && valid(y-1,x) && (maze[y-1][x] == 'wall')) walls.push([y-1, x , [y,x]]);
if (addBlockWalls && valid(y,x+1) && (maze[y][x+1] == 'wall')) walls.push([ y , x+1, [y,x]]);
if (addBlockWalls && valid(y,x-1) && (maze[y][x-1] == 'wall')) walls.push([ y , x-1, [y,x]]);
}
function valid(a,b) { return (a<hate && a>=0 && b<width && b>=0) ? true : false; };
amaze(currentPosition[0],currentPosition[1], true);
while(walls.length != 0) {
var randomWall = walls[Math.floor(Math.random() * walls.length)], host = randomWall[2], opposite = [(host[0] + (randomWall[0]-host[0])*2), (host[1] + (randomWall[1]-host[1])*2)];
if (valid(opposite[0],opposite[1])) {
if (maze[opposite[0]][opposite[1]] == 'maze') walls.splice(walls.indexOf(randomWall),1);
else amaze(randomWall[0],randomWall[1],false), amaze(opposite[0],opposite[1],true);
}
else walls.splice(walls.indexOf(randomWall),1);
}
document.getElementById('0-0').className = 'block me';
document.getElementById((parseInt(hate)-1)+'-'+(parseInt(width)-1)).className = 'block finish';
...