Advertisement
fmasanori

Minimal Hanoi

Oct 24th, 2011
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.72 KB | None | 0 0
  1. """
  2. A minimal 'Towers of Hanoi' animation:
  3. A tower of 6 discs is transferred from the
  4. left to the right peg.
  5.  
  6. An imho quite elegant and concise
  7. implementation using a tower class, which
  8. is derived from the built-in type list.
  9.  
  10. Discs are turtles with shape "square", but
  11. stretched to rectangles by turtlesize()
  12. """
  13. from turtle import *
  14.  
  15. class Disc(Turtle):
  16.     def __init__(self, n):
  17.         Turtle.__init__(self, shape="square", visible=False)
  18.         self.pu()
  19.         self.turtlesize(1.5, n*1.5, 2) # square-->rectangle
  20.         self.fillcolor(n/6., 0, 1-n/6.)
  21.         self.st()
  22.  
  23. class Tower(list):
  24.     "Hanoi tower, a subclass of built-in type list"
  25.     def __init__(self, x):
  26.         "create an empty tower. x is x-position of peg"
  27.         self.x = x
  28.     def push(self, d):
  29.         d.setx(self.x)
  30.         d.sety(-150+34*len(self))
  31.         self.append(d)
  32.     def pop(self):
  33.         d = list.pop(self)
  34.         d.sety(150)
  35.         return d
  36.  
  37. def hanoi(n, _from, _with, _to):
  38.     if n > 0:
  39.         hanoi(n-1, _from, _to, _with)
  40.         _to.push(_from.pop())
  41.         hanoi(n-1, _with, _from, _to)
  42.  
  43. def play():
  44.     onkey(None,"space")
  45.     clear()
  46.     hanoi(6, t1, t2, t3)
  47.    
  48. def main():
  49.     global t1, t2, t3
  50.     ht(); penup(); goto(0, -225)   # writer turtle
  51.     t1 = Tower(-250)
  52.     t2 = Tower(0)
  53.     t3 = Tower(250)
  54.     # make tower of 6 discs
  55.     for i in range(6,0,-1):
  56.         t1.push(Disc(i))
  57.     # prepare spartanic user interface ;-)        
  58.     write("press spacebar to start game",
  59.           align="center", font=("Courier", 16, "bold"))
  60.     onkey(play, "space")
  61.     listen()
  62.     return "EVENTLOOP"
  63.    
  64. if __name__=="__main__":    
  65.     msg = main()
  66.     print (msg)
  67.     mainloop()
  68.  
  69.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement