knightstour.tcl 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. # Copyright (C) 2008 Pat Thoyts <patthoyts@users.sourceforge.net>
  2. #
  3. # Calculate a Knight's tour of a chessboard.
  4. #
  5. # This uses Warnsdorff's rule to calculate the next square each
  6. # time. This specifies that the next square should be the one that
  7. # has the least number of available moves.
  8. #
  9. # Using this rule it is possible to get to a position where
  10. # there are no squares available to move into. In this implementation
  11. # this occurs when the starting square is d6.
  12. #
  13. # To solve this fault an enhancement to the rule is that if we
  14. # have a choice of squares with an equal score, we should choose
  15. # the one nearest the edge of the board.
  16. #
  17. # If the call to the Edgemost function is commented out you can see
  18. # this occur.
  19. #
  20. # You can drag the knight to a specific square to start if you wish.
  21. # If you let it repeat then it will choose random start positions
  22. # for each new tour.
  23. package require Tk
  24. # Return a list of accessible squares from a given square
  25. proc ValidMoves {square} {
  26. set moves {}
  27. foreach pair {{-1 -2} {-2 -1} {-2 1} {-1 2} {1 2} {2 1} {2 -1} {1 -2}} {
  28. set col [expr {($square % 8) + [lindex $pair 0]}]
  29. set row [expr {($square / 8) + [lindex $pair 1]}]
  30. if {$row >= 0 && $row < 8 && $col >= 0 && $col < 8} {
  31. lappend moves [expr {$row * 8 + $col}]
  32. }
  33. }
  34. return $moves
  35. }
  36. # Return the number of available moves for this square
  37. proc CheckSquare {square} {
  38. variable visited
  39. set moves 0
  40. foreach test [ValidMoves $square] {
  41. if {[lsearch -exact -integer $visited $test] < 0} {
  42. incr moves
  43. }
  44. }
  45. return $moves
  46. }
  47. # Select the next square to move to. Returns -1 if there are no available
  48. # squares remaining that we can move to.
  49. proc Next {square} {
  50. variable visited
  51. set minimum 9
  52. set nextSquare -1
  53. foreach testSquare [ValidMoves $square] {
  54. if {[lsearch -exact -integer $visited $testSquare] < 0} {
  55. set count [CheckSquare $testSquare]
  56. if {$count < $minimum} {
  57. set minimum $count
  58. set nextSquare $testSquare
  59. } elseif {$count == $minimum} {
  60. # to remove the enhancement to Warnsdorff's rule
  61. # remove the next line:
  62. set nextSquare [Edgemost $nextSquare $testSquare]
  63. }
  64. }
  65. }
  66. return $nextSquare
  67. }
  68. # Select the square nearest the edge of the board
  69. proc Edgemost {a b} {
  70. set colA [expr {3-int(abs(3.5-($a%8)))}]
  71. set colB [expr {3-int(abs(3.5-($b%8)))}]
  72. set rowA [expr {3-int(abs(3.5-($a/8)))}]
  73. set rowB [expr {3-int(abs(3.5-($b/8)))}]
  74. return [expr {($colA * $rowA) < ($colB * $rowB) ? $a : $b}]
  75. }
  76. # Display a square number as a standard chess square notation.
  77. proc N {square} {
  78. return [format %c%d [expr {97 + $square % 8}] \
  79. [expr {$square / 8 + 1}]]
  80. }
  81. # Perform a Knight's move and schedule the next move.
  82. proc MovePiece {dlg last square} {
  83. variable visited
  84. variable delay
  85. variable continuous
  86. $dlg.f.txt insert end "[llength $visited]. [N $last] .. [N $square]\n" {}
  87. $dlg.f.txt see end
  88. $dlg.f.c itemconfigure [expr {1+$last}] -state normal -outline black
  89. $dlg.f.c itemconfigure [expr {1+$square}] -state normal -outline red
  90. $dlg.f.c moveto knight {*}[lrange [$dlg.f.c coords [expr {1+$square}]] 0 1]
  91. lappend visited $square
  92. set next [Next $square]
  93. if {$next ne -1} {
  94. variable aid [after $delay [list MovePiece $dlg $square $next]]
  95. } else {
  96. $dlg.tf.b1 configure -state normal
  97. if {[llength $visited] == 64} {
  98. variable initial
  99. if {$initial == $square} {
  100. $dlg.f.txt insert end "Closed tour!"
  101. } else {
  102. $dlg.f.txt insert end "Success\n" {}
  103. if {$continuous} {
  104. after [expr {$delay * 2}] [namespace code \
  105. [list Tour $dlg [expr {int(rand() * 64)}]]]
  106. }
  107. }
  108. } else {
  109. $dlg.f.txt insert end "FAILED!\n" {}
  110. }
  111. }
  112. }
  113. # Begin a new tour of the board given a random start position
  114. proc Tour {dlg {square {}}} {
  115. variable visited {}
  116. $dlg.f.txt delete 1.0 end
  117. $dlg.tf.b1 configure -state disabled
  118. for {set n 0} {$n < 64} {incr n} {
  119. $dlg.f.c itemconfigure $n -state disabled -outline black
  120. }
  121. if {$square eq {}} {
  122. set coords [lrange [$dlg.f.c coords knight] 0 1]
  123. set square [expr {[$dlg.f.c find closest {*}$coords 0 65]-1}]
  124. }
  125. variable initial $square
  126. after idle [list MovePiece $dlg $initial $initial]
  127. }
  128. proc Stop {} {
  129. variable aid
  130. catch {after cancel $aid}
  131. }
  132. proc Exit {dlg} {
  133. Stop
  134. destroy $dlg
  135. }
  136. proc SetDelay {new} {
  137. variable delay [expr {int($new)}]
  138. }
  139. proc DragStart {w x y} {
  140. $w dtag selected
  141. $w addtag selected withtag current
  142. variable dragging [list $x $y]
  143. }
  144. proc DragMotion {w x y} {
  145. variable dragging
  146. if {[info exists dragging]} {
  147. $w move selected [expr {$x - [lindex $dragging 0]}] \
  148. [expr {$y - [lindex $dragging 1]}]
  149. variable dragging [list $x $y]
  150. }
  151. }
  152. proc DragEnd {w x y} {
  153. set square [$w find closest $x $y 0 65]
  154. $w moveto selected {*}[lrange [$w coords $square] 0 1]
  155. $w dtag selected
  156. variable dragging ; unset dragging
  157. }
  158. proc CreateGUI {} {
  159. catch {destroy .knightstour}
  160. set dlg [toplevel .knightstour]
  161. wm title $dlg "Knights tour"
  162. wm withdraw $dlg
  163. set f [ttk::frame $dlg.f]
  164. set c [canvas $f.c -width 240 -height 240]
  165. text $f.txt -width 10 -height 1 \
  166. -yscrollcommand [list $f.vs set] -font {Arial 8}
  167. ttk::scrollbar $f.vs -command [list $f.txt yview]
  168. variable delay 600
  169. variable continuous 0
  170. ttk::frame $dlg.tf
  171. ttk::label $dlg.tf.ls -text Speed
  172. ttk::scale $dlg.tf.sc -from 8 -to 2000 -command [list SetDelay] \
  173. -variable [namespace which -variable delay]
  174. ttk::checkbutton $dlg.tf.cc -text Repeat \
  175. -variable [namespace which -variable continuous]
  176. ttk::button $dlg.tf.b1 -text Start -command [list Tour $dlg]
  177. ttk::button $dlg.tf.b2 -text Exit -command [list Exit $dlg]
  178. set square 0
  179. for {set row 7} {$row >= 0} {incr row -1} {
  180. for {set col 0} {$col < 8} {incr col} {
  181. if {(($col & 1) ^ ($row & 1))} {
  182. set fill tan3 ; set dfill tan4
  183. } else {
  184. set fill bisque ; set dfill bisque3
  185. }
  186. set coords [list [expr {$col * 30 + 4}] [expr {$row * 30 + 4}] \
  187. [expr {$col * 30 + 30}] [expr {$row * 30 + 30}]]
  188. $c create rectangle $coords -fill $fill -disabledfill $dfill \
  189. -width 2 -state disabled -outline black
  190. }
  191. }
  192. if {[tk windowingsystem] ne "x11"} {
  193. catch {eval font create KnightFont -size -24}
  194. $c create text 0 0 -font KnightFont -text "\u265e" \
  195. -anchor nw -tags knight -fill black -activefill "#600000"
  196. } else {
  197. # On X11 we cannot reliably tell if the \u265e glyph is available
  198. # so just use a polygon
  199. set pts {
  200. 2 25 24 25 21 19 20 8 14 0 10 0 0 13 0 16
  201. 2 17 4 14 5 15 3 17 5 17 9 14 10 15 5 21
  202. }
  203. $c create polygon $pts -tag knight -offset 8 \
  204. -fill black -activefill "#600000"
  205. }
  206. $c moveto knight {*}[lrange [$c coords [expr {1 + int(rand() * 64)}]] 0 1]
  207. $c bind knight <Button-1> [namespace code [list DragStart %W %x %y]]
  208. $c bind knight <Motion> [namespace code [list DragMotion %W %x %y]]
  209. $c bind knight <ButtonRelease-1> [namespace code [list DragEnd %W %x %y]]
  210. grid $c $f.txt $f.vs -sticky news
  211. grid rowconfigure $f 0 -weight 1
  212. grid columnconfigure $f 1 -weight 1
  213. grid $f - - - - - -sticky news
  214. set things [list $dlg.tf.ls $dlg.tf.sc $dlg.tf.cc $dlg.tf.b1]
  215. if {![info exists ::widgetDemo]} {
  216. lappend things $dlg.tf.b2
  217. if {[tk windowingsystem] ne "aqua"} {
  218. set things [linsert $things 0 [ttk::sizegrip $dlg.tf.sg]]
  219. }
  220. }
  221. pack {*}$things -side right
  222. if {[tk windowingsystem] eq "aqua"} {
  223. pack configure {*}$things -padx {4 4} -pady {12 12}
  224. pack configure [lindex $things 0] -padx {4 24}
  225. pack configure [lindex $things end] -padx {16 4}
  226. }
  227. grid $dlg.tf - - - - - -sticky ew
  228. if {[info exists ::widgetDemo]} {
  229. grid [addSeeDismiss $dlg.buttons $dlg] - - - - - -sticky ew
  230. }
  231. grid rowconfigure $dlg 0 -weight 1
  232. grid columnconfigure $dlg 0 -weight 1
  233. bind $dlg <Control-F2> {console show}
  234. bind $dlg <Return> [list $dlg.tf.b1 invoke]
  235. bind $dlg <Escape> [list $dlg.tf.b2 invoke]
  236. bind $dlg <Destroy> [namespace code [list Stop]]
  237. wm protocol $dlg WM_DELETE_WINDOW [namespace code [list Exit $dlg]]
  238. wm deiconify $dlg
  239. tkwait window $dlg
  240. }
  241. if {![winfo exists .knightstour]} {
  242. if {![info exists widgetDemo]} { wm withdraw . }
  243. set r [catch [linsert $argv 0 CreateGUI] err]
  244. if {$r} {
  245. tk_messageBox -icon error -title "Error" -message $err
  246. }
  247. if {![info exists widgetDemo]} { exit $r }
  248. }