/Demo/turtle/tdemo_minimal_hanoi.py

http://unladen-swallow.googlecode.com/ · Python · 76 lines · 71 code · 0 blank · 5 comment · 0 complexity · 216d826b781d82d5047cc00744725077 MD5 · raw file

  1. #!/usr/bin/python
  2. """ turtle-example-suite:
  3. tdemo_minimal_hanoi.py
  4. A minimal 'Towers of Hanoi' animation:
  5. A tower of 6 discs is transferred from the
  6. left to the right peg.
  7. An imho quite elegant and concise
  8. implementation using a tower class, which
  9. is derived from the built-in type list.
  10. Discs are turtles with shape "square", but
  11. stretched to rectangles by shapesize()
  12. ---------------------------------------
  13. To exit press STOP button
  14. ---------------------------------------
  15. """
  16. from turtle import *
  17. class Disc(Turtle):
  18. def __init__(self, n):
  19. Turtle.__init__(self, shape="square", visible=False)
  20. self.pu()
  21. self.shapesize(1.5, n*1.5, 2) # square-->rectangle
  22. self.fillcolor(n/6., 0, 1-n/6.)
  23. self.st()
  24. class Tower(list):
  25. "Hanoi tower, a subclass of built-in type list"
  26. def __init__(self, x):
  27. "create an empty tower. x is x-position of peg"
  28. self.x = x
  29. def push(self, d):
  30. d.setx(self.x)
  31. d.sety(-150+34*len(self))
  32. self.append(d)
  33. def pop(self):
  34. d = list.pop(self)
  35. d.sety(150)
  36. return d
  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. def play():
  43. onkey(None,"space")
  44. clear()
  45. hanoi(6, t1, t2, t3)
  46. write("press STOP button to exit",
  47. align="center", font=("Courier", 16, "bold"))
  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. if __name__=="__main__":
  64. msg = main()
  65. print msg
  66. mainloop()