1# puzzle.tcl -- 2# 3# This demonstration script creates a 15-puzzle game using a collection 4# of buttons. 5# 6# RCS: @(#) $Id$ 7 8if {![info exists widgetDemo]} { 9 error "This script should be run from the \"widget\" demo." 10} 11 12package require Tk 13 14# puzzleSwitch -- 15# This procedure is invoked when the user clicks on a particular button; 16# if the button is next to the empty space, it moves the button into th 17# empty space. 18 19proc puzzleSwitch {w num} { 20 global xpos ypos 21 if {(($ypos($num) >= ($ypos(space) - .01)) 22 && ($ypos($num) <= ($ypos(space) + .01)) 23 && ($xpos($num) >= ($xpos(space) - .26)) 24 && ($xpos($num) <= ($xpos(space) + .26))) 25 || (($xpos($num) >= ($xpos(space) - .01)) 26 && ($xpos($num) <= ($xpos(space) + .01)) 27 && ($ypos($num) >= ($ypos(space) - .26)) 28 && ($ypos($num) <= ($ypos(space) + .26)))} { 29 set tmp $xpos(space) 30 set xpos(space) $xpos($num) 31 set xpos($num) $tmp 32 set tmp $ypos(space) 33 set ypos(space) $ypos($num) 34 set ypos($num) $tmp 35 place $w.frame.$num -relx $xpos($num) -rely $ypos($num) 36 } 37} 38 39set w .puzzle 40catch {destroy $w} 41toplevel $w 42wm title $w "15-Puzzle Demonstration" 43wm iconname $w "15-Puzzle" 44positionWindow $w 45 46label $w.msg -font $font -wraplength 4i -justify left -text "A 15-puzzle appears below as a collection of buttons. Click on any of the pieces next to the space, and that piece will slide over the space. Continue this until the pieces are arranged in numerical order from upper-left to lower-right." 47pack $w.msg -side top 48 49## See Code / Dismiss buttons 50set btns [addSeeDismiss $w.buttons $w] 51pack $btns -side bottom -fill x 52 53# Special trick: select a darker color for the space by creating a 54# scrollbar widget and using its trough color. 55 56scrollbar $w.s 57 58# The button metrics are a bit bigger in Aqua, and since we are 59# using place which doesn't autosize, then we need to have a 60# slightly larger frame here... 61 62if {[tk windowingsystem] eq "aqua"} { 63 set frameSize 168 64} else { 65 set frameSize 120 66} 67 68frame $w.frame -width $frameSize -height $frameSize -borderwidth 2\ 69 -relief sunken -bg [$w.s cget -troughcolor] 70pack $w.frame -side top -pady 1c -padx 1c 71destroy $w.s 72 73set order {3 1 6 2 5 7 15 13 4 11 8 9 14 10 12} 74for {set i 0} {$i < 15} {set i [expr {$i+1}]} { 75 set num [lindex $order $i] 76 set xpos($num) [expr {($i%4)*.25}] 77 set ypos($num) [expr {($i/4)*.25}] 78 button $w.frame.$num -relief raised -text $num -highlightthickness 0 \ 79 -command "puzzleSwitch $w $num" 80 place $w.frame.$num -relx $xpos($num) -rely $ypos($num) \ 81 -relwidth .25 -relheight .25 82} 83set xpos(space) .75 84set ypos(space) .75 85