Jump to content

Maze generation: Difference between revisions

m
(→‎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 [expr {int(rand() * [llength $list])}]
}
# Helper to index into a list of lists with offsets
proc tcl::mathfunc::idx {v x y} {
lindex $v [expr {$x+1}] [expr {$y+1}]
}
# Helper _function_ to index into a list of lists with offsets
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 {x y x} {
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 verti [lrepeat [expr {$x+1}] [lrepeat [expr {$y+1}] 0]]
set here [list [expr {int(rand()*$x)}] [expr {int(rand()*$y)}]]
set path [list $here]
set unvisited [lrepeat [expr {$x+2}] [lrepeat [expr {$y+2}] 0]]
lappend stack [set here [list [expr {int(rand()* $x)}] [expr {int(rand()* $y)}]]]
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 0 -1} {
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} {
setlset pyhoriz $nx [expr {min($ny +, $hy - 1) / 2}] 1
lset horiz $nx $py 1
} else {
setlset pxverti [expr {min($nx +, $hx)}] -$ny 1) / 2}]
lset verti $px $ny 1
}
lappend pathstack $here
incr n -1
} else {
set here [lindex $pathstack end]
set pathstack [lrange $pathstack 0 end-1]
}
}
Line 311 ⟶ 307:
}
}
if {!$j} {set line [string replace $line 1 3 " "]}
lappend if {$x*2-1 == $j} {set linetext [string replace $line end1 end3 " "]}
lappend} textelseif {$linex*2-1 == $j} {
lappend text [string replace $line end end " "]
} else {
lappend text $line
}
}
}
return [join $text \n]
}
 
# Demonstration
puts [display [maze 8 11 8]]</lang>
Output:
<pre>
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.