Anonymous user
Maze generation: Difference between revisions
m
→{{header|Tcl}}: tinkering
(→Tcl: Added implementation) |
m (→{{header|Tcl}}: tinkering) |
||
Line 235:
{{trans|Javascript}}
<lang tcl>package require Tcl 8.5
# Helper to pick a random number
proc rand n {expr {int(rand() * $n)}}
# Helper to pick a random element of a list
proc pick list {
lindex $list [
# Helper to index into a list of lists with offsets▼
proc tcl::mathfunc::idx {v x y} {▼
}
▲proc tcl::mathfunc::idx {v x y} {lindex $v $x $y}
# Helper to write into a list of lists (with offsets)
proc unvisited= {x y value} {
Line 250:
# Maze builder; returns a dictionary
proc maze {
set n [expr {$x * $y - 1}]
if {$n < 0} {error "illegal maze dimensions"}
set horiz [set verti [lrepeat [expr {$x+1}] [lrepeat [expr {$y+1}] 0]]]
set here [list [expr {int(rand()*$x)}] [expr {int(rand()*$y)}]]▼
set unvisited [lrepeat [expr {$x+2}] [lrepeat [expr {$y+2}] 0]]
for {set j 0} {$j < $x} {incr j} {
for {set k 0} {$k < $y} {incr k} {
Line 263 ⟶ 261:
}
}
while {0 < $n} {
lassign $here hx hy
set neighbours {}
foreach {dx dy} {1 0 0 1 -1 0
if {idx($unvisited, $hx+$dx+1, $hy+$dy+1)} {
lappend neighbours [list [expr {$hx+$dx}] [expr {$hy+$dy}]]
}
}
if {[llength $neighbours]} {
incr n -1▼
lassign [set here [pick $neighbours]] nx ny
unvisited= $nx $ny 0
if {$nx == $hx} {
} else {
}
lappend
▲ incr n -1
} else {
set here [lindex $
set
}
}
Line 311 ⟶ 307:
}
}
if {!$j} {
lappend
lappend text [string replace $line end end " "]
} else {
lappend text $line
}
}
}
return [join $text \n]
}
# Demonstration
puts [display [maze
Output:
<pre>
|