# L-16 MCS 275 Wed 20 Feb 2008 : hfilling.py

# Consider the following definition of a space
# filling curve.  Start with a big H drawn on canvas.
# Place at the four extreme ends of the big H, one H 
# of the size one half smaller than the big H.
# Each smaller H touches the bigger H at its center.
# Describe the design of a GUI to draw this space
# filling curve.  Give the Python code for the 
# recursive drawing functions.

from Tkinter import *
import math

class HFilling:
   """
   Filling the canvas with H's.
   """
   def __init__(self,wdw,dimension):
      """
      Defines a canvas, buttons, and scale.
      """
      wdw.title('H filling curves')
      self.dim = dimension # dimension of the canvas
      self.n = 1
      self.c = Canvas(wdw,width=10+self.dim,\
        height=10+self.dim,bg ='white')
      self.c.grid(row=0,column=0,columnspan=2)
      self.b = Button(wdw,text='clear',command=self.Clear)
      self.b.grid(row=1,column=1,sticky=W+E)
      self.sn = Scale(wdw,orient='horizontal',\
        from_=0,to=8,variable=self.n,command=self.Draw)
      self.sn.set(0)
      self.sn.grid(row=1,column=0,sticky=W+E)

   def PlotH(self,n,cx,cy,h):
      """
      Recursive plotting of H.
      """
      if n > 0:
         self.c.create_line(cx-h,cy,cx+h,cy,width=2)
         self.c.create_line(cx-h,cy-h,cx-h,cy+h,width=2)
         self.c.create_line(cx+h,cy-h,cx+h,cy+h,width=2)
         self.PlotH(n-1,cx-h,cy-h,h/2)
         self.PlotH(n-1,cx-h,cy+h,h/2)
         self.PlotH(n-1,cx+h,cy-h,h/2)
         self.PlotH(n-1,cx+h,cy+h,h/2)

   def Draw(self,v):
      """
      Draws an H on canvas.
      """
      n = int(v)
      h = self.dim/4
      a = self.dim/2
      b = self.dim/2
      self.PlotH(n,a,b,h)

   def Clear(self):
      """
      Clears the canvas and resets the initial position.
      """
      self.c.delete(ALL)

def main():
   top = Tk()
   dimension = 400 # dimension of the canvas
   show = HFilling(top,dimension)
   top.mainloop()

if __name__ == "__main__": main()
