
puts stderr "start"

proc bgerror args {
  puts stderr "ERROR ( $args )"
}
proc * {a b} {expr $a*$b}

set W 6
set NX [expr int(1600/$W)]
set NY [expr int(1000/$W)]
#label .a -text HELLO
#label .b -text WORLD
canvas .c -width [* $W $NX] -height [* $W $NY]
#pack .a
#pack .b
pack .c

proc iota n {
  set z {}
  for {set i 0} {$i < $n} {incr i} {
    lappend z $i
  }
  set z
}

foreach x [iota $NX] {
  foreach y [iota $NY] {
    set x0 [expr $W*$x]
    set y0 [expr $W*$y]
    set x9 [expr $W*$x+$W-2]
    set y9 [expr $W*$y+$W-2]
    #puts stderr ".c create rectangle $x0 $y0 $x9 $y9 -fill blue"
    set R($x,$y) [
      #.c create rectangle $x0 $y0 $x9 $y9 -fill blue -activefill white
      .c create rectangle $x0 $y0 $x9 $y9 -fill white
    ]
  }
}

proc neighbors {x y} {
  set z {}
  foreach i [iota 3] {
    foreach j [iota 3] {
      lappend z [expr $x+$i-1],[expr $y+$j-1]
    }
  }
  set z
}

proc drop_to {} {
  global NX NY W R
  #set x [expr int($NX/2)]
  set x [expr int(rand()*$NX)]
  set y 0
  foreach j [iota $NY] {
    if {$y == $NY-1} {return $x,$y}
    foreach n [neighbors $x $y] {
      if {[info exists R($n)] && 
          [.c itemcget $R($n) -fill] == "black"} {
	return $x,$y
      }
    }
    set d [expr int(rand()*3)-1]
    set x [expr $x+$d]
    incr y
    #if [info exists R($x,$y)] {
    #  .c itemconfigure $R($x,$y) -fill green
    #}
  }
  return none
}

proc drop {} {
  global R
  set xy [drop_to]
  if {[info exists R($xy)]} {
    .c itemconfigure $R($xy) -fill "black"
  }
}

proc bg {} {
  drop
  drop
  drop
  drop
  drop
  drop
  drop
  drop
  drop
  drop
  after 5 bg
}

after 1000 bg
