Skip to content

Instantly share code, notes, and snippets.

@onsclom

onsclom/maze.ts Secret

Created August 6, 2023 00:18
Show Gist options
  • Save onsclom/bf07edb965b33cf05c96eaa31c1f8602 to your computer and use it in GitHub Desktop.
Save onsclom/bf07edb965b33cf05c96eaa31c1f8602 to your computer and use it in GitHub Desktop.
typescript maze
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