Maze generation: Difference between revisions

(→‎{{header|jq}}: simplify)
Line 5,589:
</pre>
In the following, a maze is represented by a matrix, each of whose elements
is in turn a booleanJSON arrayobject representing the bounding box:
$box[$i"N"] is true iff edgethe $inorthern edge open, and similarly for the
other points of the compass.
where $i is:
 
Note that for simplicity, in the following, the "walk" always starts at the (0,0) cell.
0 for the top (north) side,
cell; this is just to make it clear that walk starts at the top left of the
1 bottom (south)
display.
2 right (east)
3 left (west)
 
Note that for simplicity, in the following the "walk" always starts at the (0,0) cell.
<syntaxhighlight lang="jq">
# Output: a prn in range(0;$n) where $n is .
Line 5,622 ⟶ 5,619:
| .a
end;
 
# Arrays wherein `false` and `null` are the only falsey values.
# The input array and $y need not be of the same length.
def lor($y): [., $y] | transpose | map(.[0] or .[1]);
def falsey: all(.[]; IN(false, null) );
 
# Create an array such that .[$n] is true, and .[$i] is null for $i < $n
def bit($n): [] | .[$n] = true;
 
# Compass is a JSON object {n,s,e,w} representing the four possible
# directions in which to move, i.e. to open a gate.
# For example, Compass.n corresponds to a move north (i.e. dx is 0, dy is 1),
# and Compass.n.gates[0"N"] is true indicating that the "northern" gate should be opened.
def Compass:
{n: { gates: bit(0){"N": true}, dx: 0, dy: -1},
s: { gates: bit(1){"S": true}, dx: 0, dy: 1},
e: { gates: bit(2){"E": true}, dx: 1, dy: 0},
w: { gates: bit(3){"W": true}, dx:-1, dy: 0} }
| .n.opposite = .s
| .s.opposite = .n
Line 5,648 ⟶ 5,637:
# Produce a matrix representing an $x x $y maze.
# .[$i][$j] represents the box in row $i, column $j.
# Initially, all the gates of all the boxes are closed (falsey).
def MazeMatrix($x; $y):
[range(0;$x) | []{} ] as $v | [range(0;$y) | $v];
 
# Input: a MazeMatrix
Line 5,662 ⟶ 5,651:
($cx + $v.dx) as $nx
| ($cy + $v.dy) as $ny
| if interior($nx; $x) and interior($ny; $y) and (.[$nx][$ny]|falsey) == {}
then .[$cx][$cy] |+= lor($v.gates)
| .[$nx][$ny] |+= lor($v.opposite.gates)
| generate($nx; $ny)
end );
Line 5,676 ⟶ 5,665:
# draw the north edge
| ([range(0;$x) as $j
| if $maze[$j][$i][0"N"] then "+ " else "+---" end] | join("")) + "+",
# draw the west edge
([range(0;$x) as $j
| if $maze[$j][$i][3"W"] then " " else "| " end] | join("")) + "|" ),
# draw the bottom line
($x * "+---") + "+"
;
 
# AlwaysStart startthe walk at (0,0)the top left
def amaze($x;$y):
MazeMatrix($x; $y)
2,489

edits