Anonymous user
Maze generation: Difference between revisions
m
→{{header|Tcl}}: more tinkering, making this code a class
m (→{{header|Tcl}}: tinkering) |
m (→{{header|Tcl}}: more tinkering, making this code a class) |
||
Line 234:
=={{header|Tcl}}==
{{trans|Javascript}}
<lang tcl>package require TclOO; # Or Tcl 8.
# 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 [rand [llength $list]]}
# Helper _function_ to index into a list of lists
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} {▼
upvar 1 unvisited u▼
lset u [expr {$x+1}] [expr {$y+1}] $value▼
oo::class create maze {
variable x y horiz verti
constructor {width height} {
set n [expr {$x * $y - 1}]▼
set y $width
set x $height
▲ # Helper to write into a list of lists (with offsets)
▲ proc unvisited= {x y value} {
▲ upvar 1 unvisited u
▲ lset u [expr {$x+1}] [expr {$y+1}] $value
}
}▼
lappend stack [set here [list [rand $x] [rand $y]]]
for {set j
unvisited= $j $k [expr {$here ne [list $j $k]}]
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]} {▼
while {0 < $n} {
lassign [set here [pick $neighbours]] nx ny▼
lset horiz $nx [expr {min($ny, $hy)}] 1▼
▲ lappend neighbours [list [expr {$hx+$dx}] [expr {$hy+$dy}]]
}
▲ }
unvisited= $nx $ny 0
if {$nx == $hx} {
▲ lset horiz $nx [expr {min($ny, $hy)}] 1
lset verti [expr {min($nx, $hx)}] $ny 1▼
}
} else {
▲ lset verti [expr {min($nx, $hx)}] $ny 1
}
▲ lappend stack $here
▲ incr n -1
▲ } else {
▲ set here [lindex $stack end]
▲ set stack [lrange $stack 0 end-1]
}
}
# Maze displayer; takes a maze dictionary, returns a string
for {set j 0} {$j < $x*2+1} {incr j} {
set line {}
Line 315 ⟶ 317:
}
}
}
▲ return [join $text \n]
}
# Demonstration
puts [m view]</lang>
Output:
<pre>
|