Maze generation: Difference between revisions
Content added Content deleted
m (→{{header|Tcl}}: tinkering) |
m (→{{header|Tcl}}: more tinkering, making this code a class) |
||
Line 234: | Line 234: | ||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
{{trans|Javascript}} |
{{trans|Javascript}} |
||
<lang tcl>package require Tcl 8. |
<lang tcl>package require TclOO; # Or Tcl 8.6 |
||
# Helper to pick a random number |
# Helper to pick a random number |
||
proc rand n {expr {int(rand() * $n)}} |
proc rand n {expr {int(rand() * $n)}} |
||
# Helper to pick a random element of a list |
# Helper to pick a random element of a list |
||
proc pick list { |
proc pick list {lindex $list [rand [llength $list]]} |
||
lindex $list [rand [llength $list]] |
|||
} |
|||
# Helper _function_ to index into a list of lists |
# Helper _function_ to index into a list of lists |
||
proc tcl::mathfunc::idx {v x y} {lindex $v $x $y} |
proc tcl::mathfunc::idx {v x y} {lindex $v $x $y} |
||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
} |
|||
oo::class create maze { |
|||
# Maze builder; returns a dictionary |
|||
variable x y horiz verti |
|||
proc maze {y x} { |
|||
constructor {width height} { |
|||
⚫ | |||
set y $width |
|||
if {$n < 0} {error "illegal maze dimensions"} |
|||
set x $height |
|||
set horiz [set verti [lrepeat [expr {$x+1}] [lrepeat [expr {$y+1}] 0]]] |
|||
set unvisited [lrepeat [expr {$x+2}] [lrepeat [expr {$y+2}] 0]] |
|||
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 unvisited [lrepeat [expr {$x+2}] [lrepeat [expr {$y+2}] 0]] |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
} |
} |
||
⚫ | |||
lappend stack [set here [list [rand $x] [rand $y]]] |
|||
⚫ | |||
for {set j 0} {$j < $x} {incr j} { |
|||
⚫ | |||
lassign $here hx hy |
|||
unvisited= $j $k [expr {$here ne [list $j $k]}] |
|||
set neighbours {} |
|||
⚫ | |||
⚫ | |||
⚫ | |||
} |
} |
||
} |
} |
||
⚫ | |||
⚫ | |||
while {0 < $n} { |
|||
⚫ | |||
lassign $here hx hy |
|||
set neighbours {} |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
} |
|||
⚫ | |||
⚫ | |||
⚫ | |||
unvisited= $nx $ny 0 |
|||
if {$nx == $hx} { |
|||
⚫ | |||
⚫ | |||
⚫ | |||
} |
|||
⚫ | |||
⚫ | |||
} else { |
} else { |
||
⚫ | |||
⚫ | |||
⚫ | |||
} |
} |
||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
} |
} |
||
} |
} |
||
return [dict create x $x y $y horiz $horiz verti $verti] |
|||
} |
|||
# Maze displayer; takes a maze dictionary |
# Maze displayer; takes a maze dictionary, returns a string |
||
method view {} { |
|||
set text {} |
|||
dict with m { |
|||
for {set j 0} {$j < $x*2+1} {incr j} { |
for {set j 0} {$j < $x*2+1} {incr j} { |
||
set line {} |
set line {} |
||
Line 315: | Line 317: | ||
} |
} |
||
} |
} |
||
⚫ | |||
} |
} |
||
⚫ | |||
} |
} |
||
# Demonstration |
# Demonstration |
||
maze create m 11 8 |
|||
puts [m view]</lang> |
|||
Output: |
Output: |
||
<pre> |
<pre> |