/Demo/tkinter/guido/hanoi.py

http://unladen-swallow.googlecode.com/ · Python · 154 lines · 100 code · 23 blank · 31 comment · 20 complexity · f4de1c64427225868f1cf16e5a6f2065 MD5 · raw file

  1. # Animated Towers of Hanoi using Tk with optional bitmap file in
  2. # background.
  3. #
  4. # Usage: tkhanoi [n [bitmapfile]]
  5. #
  6. # n is the number of pieces to animate; default is 4, maximum 15.
  7. #
  8. # The bitmap file can be any X11 bitmap file (look in
  9. # /usr/include/X11/bitmaps for samples); it is displayed as the
  10. # background of the animation. Default is no bitmap.
  11. # This uses Steen Lumholt's Tk interface
  12. from Tkinter import *
  13. # Basic Towers-of-Hanoi algorithm: move n pieces from a to b, using c
  14. # as temporary. For each move, call report()
  15. def hanoi(n, a, b, c, report):
  16. if n <= 0: return
  17. hanoi(n-1, a, c, b, report)
  18. report(n, a, b)
  19. hanoi(n-1, c, b, a, report)
  20. # The graphical interface
  21. class Tkhanoi:
  22. # Create our objects
  23. def __init__(self, n, bitmap = None):
  24. self.n = n
  25. self.tk = tk = Tk()
  26. self.canvas = c = Canvas(tk)
  27. c.pack()
  28. width, height = tk.getint(c['width']), tk.getint(c['height'])
  29. # Add background bitmap
  30. if bitmap:
  31. self.bitmap = c.create_bitmap(width//2, height//2,
  32. bitmap=bitmap,
  33. foreground='blue')
  34. # Generate pegs
  35. pegwidth = 10
  36. pegheight = height//2
  37. pegdist = width//3
  38. x1, y1 = (pegdist-pegwidth)//2, height*1//3
  39. x2, y2 = x1+pegwidth, y1+pegheight
  40. self.pegs = []
  41. p = c.create_rectangle(x1, y1, x2, y2, fill='black')
  42. self.pegs.append(p)
  43. x1, x2 = x1+pegdist, x2+pegdist
  44. p = c.create_rectangle(x1, y1, x2, y2, fill='black')
  45. self.pegs.append(p)
  46. x1, x2 = x1+pegdist, x2+pegdist
  47. p = c.create_rectangle(x1, y1, x2, y2, fill='black')
  48. self.pegs.append(p)
  49. self.tk.update()
  50. # Generate pieces
  51. pieceheight = pegheight//16
  52. maxpiecewidth = pegdist*2//3
  53. minpiecewidth = 2*pegwidth
  54. self.pegstate = [[], [], []]
  55. self.pieces = {}
  56. x1, y1 = (pegdist-maxpiecewidth)//2, y2-pieceheight-2
  57. x2, y2 = x1+maxpiecewidth, y1+pieceheight
  58. dx = (maxpiecewidth-minpiecewidth) // (2*max(1, n-1))
  59. for i in range(n, 0, -1):
  60. p = c.create_rectangle(x1, y1, x2, y2, fill='red')
  61. self.pieces[i] = p
  62. self.pegstate[0].append(i)
  63. x1, x2 = x1 + dx, x2-dx
  64. y1, y2 = y1 - pieceheight-2, y2-pieceheight-2
  65. self.tk.update()
  66. self.tk.after(25)
  67. # Run -- never returns
  68. def run(self):
  69. while 1:
  70. hanoi(self.n, 0, 1, 2, self.report)
  71. hanoi(self.n, 1, 2, 0, self.report)
  72. hanoi(self.n, 2, 0, 1, self.report)
  73. hanoi(self.n, 0, 2, 1, self.report)
  74. hanoi(self.n, 2, 1, 0, self.report)
  75. hanoi(self.n, 1, 0, 2, self.report)
  76. # Reporting callback for the actual hanoi function
  77. def report(self, i, a, b):
  78. if self.pegstate[a][-1] != i: raise RuntimeError # Assertion
  79. del self.pegstate[a][-1]
  80. p = self.pieces[i]
  81. c = self.canvas
  82. # Lift the piece above peg a
  83. ax1, ay1, ax2, ay2 = c.bbox(self.pegs[a])
  84. while 1:
  85. x1, y1, x2, y2 = c.bbox(p)
  86. if y2 < ay1: break
  87. c.move(p, 0, -1)
  88. self.tk.update()
  89. # Move it towards peg b
  90. bx1, by1, bx2, by2 = c.bbox(self.pegs[b])
  91. newcenter = (bx1+bx2)//2
  92. while 1:
  93. x1, y1, x2, y2 = c.bbox(p)
  94. center = (x1+x2)//2
  95. if center == newcenter: break
  96. if center > newcenter: c.move(p, -1, 0)
  97. else: c.move(p, 1, 0)
  98. self.tk.update()
  99. # Move it down on top of the previous piece
  100. pieceheight = y2-y1
  101. newbottom = by2 - pieceheight*len(self.pegstate[b]) - 2
  102. while 1:
  103. x1, y1, x2, y2 = c.bbox(p)
  104. if y2 >= newbottom: break
  105. c.move(p, 0, 1)
  106. self.tk.update()
  107. # Update peg state
  108. self.pegstate[b].append(i)
  109. # Main program
  110. def main():
  111. import sys, string
  112. # First argument is number of pegs, default 4
  113. if sys.argv[1:]:
  114. n = string.atoi(sys.argv[1])
  115. else:
  116. n = 4
  117. # Second argument is bitmap file, default none
  118. if sys.argv[2:]:
  119. bitmap = sys.argv[2]
  120. # Reverse meaning of leading '@' compared to Tk
  121. if bitmap[0] == '@': bitmap = bitmap[1:]
  122. else: bitmap = '@' + bitmap
  123. else:
  124. bitmap = None
  125. # Create the graphical objects...
  126. h = Tkhanoi(n, bitmap)
  127. # ...and run!
  128. h.run()
  129. # Call main when run as script
  130. if __name__ == '__main__':
  131. main()