Licht aus!

Spielregel: klick auf ein Feld knipst das Licht aus, wenn es an ist, und umgekehrt – allerdings bei den vier angrenzenden Feldern auch. Versuch, alle Lampen aus zu machen ... es ist Schlafenszeit!


#!/usr/bin/tclsh

lassign "$argv 3" rows

set tileSize 80

package require Tk
bind [winfo class .] <Destroy> exit
wm resizable . no no
wm title . "Licht aus, bitte!"

pack [canvas .c]

namespace path ::tcl::mathop

.c configure -width [* $rows $tileSize] -height [* $rows $tileSize]

proc toggleOneField {c r {canvas .c}} {
  variable rows
  if {$c >= 0 && $c < $rows && $r >= 0 && $r < $rows} then {
    set id [$canvas find withtag c$c&&r$r]
    if {"on" in [$canvas gettags $id]} then {
      $canvas dtag $id on
      $canvas itemconfigure $id -fill [$canvas cget -bg]
    } else {
      $canvas addtag on withtag $id
      $canvas itemconfigure $id -fill white
    }
  }
}

proc toggleField {c r {canvas .c}} {
  toggleOneField $c $r $canvas
  toggleOneField [+ $c 1] $r $canvas
  toggleOneField [- $c 1] $r $canvas
  toggleOneField $c [+ $r 1] $canvas
  toggleOneField $c [- $r 1] $canvas
  if {[$canvas find withtag on] eq ""} then {
    # wm title . "Danke schön, gute Nacht!"
    $canvas delete all
    $canvas create text\
      [/ [$canvas cget -width] 2] [/ [$canvas cget -height] 2]\
      -font "Times 24 bold italic"\
      -justify center\
      -text "Danke\nschön!\nGute\nNacht!"
  }
}

proc takeNfromList {n list} {
  if {$n > 0} then {
    set rand [expr {int(rand()*[llength $list])}]
    list [lindex $list $rand] {*}[takeNfromList [- $n 1] [lreplace $list $rand $rand]]
  }
}

apply {
  {canvas rows tileSize} {
    $canvas delete all
    for {set c 0} {$c < $rows} {incr c} {
      for {set r 0} {$r < $rows} {incr r} {
        $canvas create rectangle\
          [+ [* $c $tileSize] 1]\
          [+ [* $r $tileSize] 1]\
          [+ [* $c $tileSize] $tileSize -1]\
          [+ [* $r $tileSize] $tileSize -1]\
          -width 0 -fill white -tags "c$c r$r on"
        $canvas bind c$c&&r$r <1> "toggleField $c $r"
        lappend fields "$c $r"
      }
    }
    foreach field [takeNfromList $rows $fields] {
      toggleField {*}$field $canvas
    }
  }
} .c $rows $tileSize

(Ursprung – 11.10.2017)

<< Home | Sitemap | A-Z | Impressum | Suche >>