Created
November 16, 2014 11:36
-
-
Save JaHIY/e84e18fbacd3b5a9b634 to your computer and use it in GitHub Desktop.
Maze in TCL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env tclsh -- | |
set maze [list [list 2 2 2 2 2 2 2 2 2] \ | |
[list 0 0 2 2 2 2 0 2 2] \ | |
[list 2 0 0 0 0 0 0 0 2] \ | |
[list 2 0 2 2 0 2 2 0 2] \ | |
[list 0 2 0 2 0 2 2 0 2] \ | |
[list 2 2 0 2 0 2 2 0 2] \ | |
[list 2 2 0 2 0 0 0 0 2] \ | |
[list 2 2 0 2 0 2 2 2 2] \ | |
[list 2 2 2 2 0 2 2 2 2]] | |
proc lpop {listVar} { | |
upvar 1 $listVar l | |
set r [lindex $l end] | |
set l [lreplace $l [set l end] end] ; # Make sure [lreplace] operates on unshared object | |
return $r | |
} | |
proc is_empty {listVar} { | |
upvar 1 $listVar l | |
return [expr {[llength $l] == 0}] | |
} | |
proc print_maze {} { | |
global maze | |
for {set x 0} {$x < 9} {incr x} { | |
for {set y 0} {$y < 10} {incr y} { | |
if {[lindex $maze $x $y] == 2} { | |
puts -nonewline {■} | |
} elseif {[lindex $maze $x $y] == 1} { | |
puts -nonewline {☆} | |
} else { | |
puts -nonewline {□} | |
} | |
} | |
puts {} | |
} | |
} | |
proc visit {listVar x y} { | |
global maze | |
upvar 1 $listVar l | |
lset maze $x $y 1 | |
lappend l [list $x $y] | |
puts "$x $y" | |
} | |
proc main {} { | |
global maze | |
print_maze | |
set x 1 | |
set y 0 | |
lappend stack [list $x $y] | |
while {! [is_empty stack]} { | |
set p [lpop stack] | |
set x [lindex $p 0] | |
set y [lindex $p 1] | |
if {$x == 8 && $y == 4} { | |
break | |
} | |
if {$x+1 < 9 && [lindex $maze $x+1 $y] == 0} { | |
visit stack [expr {$x+1}] $y | |
} | |
if {$y+1 < 9 && [lindex $maze $x $y+1] == 0} { | |
visit stack $x [expr {$y+1}] | |
} | |
if {$x-1 >= 0 && [lindex $maze $x-1 $y] == 0} { | |
visit stack [expr {$x-1}] $y | |
} | |
if {$y-1 >= 0 && [lindex $maze $x $y-1] == 0} { | |
visit stack $x [expr {$y-1}] | |
} | |
} | |
print_maze | |
} | |
main |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment