minimal_hanoi.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #!/usr/bin/env python3
  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. try:
  46. hanoi(6, t1, t2, t3)
  47. write("press STOP button to exit",
  48. align="center", font=("Courier", 16, "bold"))
  49. except Terminator:
  50. pass # turtledemo user pressed STOP
  51. def main():
  52. global t1, t2, t3
  53. ht(); penup(); goto(0, -225) # writer turtle
  54. t1 = Tower(-250)
  55. t2 = Tower(0)
  56. t3 = Tower(250)
  57. # make tower of 6 discs
  58. for i in range(6,0,-1):
  59. t1.push(Disc(i))
  60. # prepare spartanic user interface ;-)
  61. write("press spacebar to start game",
  62. align="center", font=("Courier", 16, "bold"))
  63. onkey(play, "space")
  64. listen()
  65. return "EVENTLOOP"
  66. if __name__=="__main__":
  67. msg = main()
  68. print(msg)
  69. mainloop()