-
-
Save onsclom/bf07edb965b33cf05c96eaa31c1f8602 to your computer and use it in GitHub Desktop.
typescript maze
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const mazeSize = Deno.args[0] ? parseInt(Deno.args[0]) : 4 | |
type Vec2d = { | |
x: number | |
y: number | |
} | |
const WALL = "#" | |
const PATH = " " | |
const sides = [...Array(mazeSize)].map(() => Array(mazeSize + 1).fill(false)) | |
const topBots = [...Array(mazeSize + 1)].map(() => Array(mazeSize).fill(false)) | |
function printMaze() { | |
let maze = "" | |
for (let y = 0; y <= mazeSize * 2; y++) { | |
for (let x = 0; x <= mazeSize * 2; x++) { | |
const halfY = Math.floor(y / 2) | |
const halfX = Math.floor(x / 2) | |
if (x % 2 === 0 && y % 2 === 0) maze += WALL | |
else if (y % 2 === 0) { | |
if (topBots[halfY][halfX]) maze += PATH | |
else maze += WALL | |
} else if (x % 2 === 0) { | |
if (sides[halfY][halfX]) maze += PATH | |
else maze += WALL | |
} else { | |
maze += PATH | |
} | |
} | |
maze += "\n" | |
} | |
console.log(maze) | |
} | |
const toVisit: Vec2d[] = [{ x: 0, y: 0 }] | |
const visited = [...Array(mazeSize)].map(() => Array(mazeSize).fill(false)) | |
visited[0][0] = true | |
const dirs = [ | |
{ x: 1, y: 0 }, | |
{ x: -1, y: 0 }, | |
{ x: 0, y: 1 }, | |
{ x: 0, y: -1 }, | |
] | |
while (toVisit.length > 0) { | |
const { x, y } = toVisit[toVisit.length - 1] | |
const visitable = dirs.filter(({ x: dx, y: dy }) => { | |
const newX = x + dx | |
const newY = y + dy | |
return ( | |
newX >= 0 && | |
newX < mazeSize && | |
newY >= 0 && | |
newY < mazeSize && | |
!visited[newY][newX] | |
) | |
}) | |
if (!visitable.length) { | |
toVisit.pop() | |
continue | |
} | |
const nextDir = visitable[Math.floor(Math.random() * visitable.length)] | |
const next = { x: x + nextDir.x, y: y + nextDir.y } | |
visited[next.y][next.x] = true | |
toVisit.push(next) | |
if (nextDir.x === 0 && nextDir.y === 1) topBots[next.y][next.x] = true | |
else if (nextDir.x === 1 && nextDir.y === 0) sides[next.y][next.x] = true | |
else if (nextDir.x === 0 && nextDir.y === -1) topBots[y][x] = true | |
else if (nextDir.x === -1 && nextDir.y === 0) sides[y][x] = true | |
} | |
// printMaze() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment