Initial commit

This commit is contained in:
2023-11-20 00:18:02 +01:00
commit bbe64c9ff6
5 changed files with 132 additions and 0 deletions

63
src/Generator.php Normal file
View File

@@ -0,0 +1,63 @@
<?php
namespace Osmal\Maze;
class Generator
{
private $maze;
private $width;
private $height;
public function __construct($width, $height) {
$this->width = $width;
$this->height = $height;
$this->maze = $this->generate();
}
public function getMaze() {
return $this->maze;
}
private function generate() {
$maze = array_fill(0, $this->height * 2 + 1, array_fill(0, $this->width *2 + 1, 1));
$this->carveMaze(1, 1, $maze);
// Opening Start/End Walls
$maze[0][1] = 0;
$maze[$this->height *2][($this->width *2)-1] = 0;
return $maze;
}
private function carveMaze($x, $y, &$maze) {
$maze[$y][$x] = 0;
$directions = [
[0, 0],
[-2, 0],
[2, 0],
[0, -2],
[0, 2]
];
shuffle($directions);
foreach ($directions as $dir) {
$nx = $x + $dir[0];
$ny = $y + $dir[1];
if ($nx > 0 && $nx < count($maze[0]) && $ny > 0 && $ny < count($maze) && $maze[$ny][$nx] === 1) {
$mx = $x + $dir[0] / 2;
$my = $y + $dir[1] / 2;
$maze[$my][$mx] = 0;
$this->carveMaze($nx, $ny, $maze);
}
}
}
public function print() {
foreach ($this->maze as $row) {
foreach ($row as $cell) {
echo $cell ? '⬛' : '⬜';
}
echo PHP_EOL;
}
}
}