#!/usr/bin/env python3"""Animated Towers of Hanoi using Tk with optional bitmap file in background.Usage: hanoi.py [n [bitmapfile]]n is the number of pieces to animate; default is 4, maximum 15.The bitmap file can be any X11 bitmap file (look in /usr/include/X11/bitmaps forsamples); it is displayed as the background of the animation. Default is nobitmap."""from tkinter import Tk, Canvas# Basic Towers-of-Hanoi algorithm: move n pieces from a to b, using c# as temporary. For each move, call report()def hanoi(n, a, b, c, report):if n <= 0: returnhanoi(n-1, a, c, b, report)report(n, a, b)hanoi(n-1, c, b, a, report)# The graphical interfaceclass Tkhanoi:# Create our objectsdef __init__(self, n, bitmap = None):self.n = nself.tk = tk = Tk()self.canvas = c = Canvas(tk)c.pack()width, height = tk.getint(c['width']), tk.getint(c['height'])# Add background bitmapif bitmap:self.bitmap = c.create_bitmap(width//2, height//2,bitmap=bitmap,foreground='blue')# Generate pegspegwidth = 10pegheight = height//2pegdist = width//3x1, y1 = (pegdist-pegwidth)//2, height*1//3x2, y2 = x1+pegwidth, y1+pegheightself.pegs = []p = c.create_rectangle(x1, y1, x2, y2, fill='black')self.pegs.append(p)x1, x2 = x1+pegdist, x2+pegdistp = c.create_rectangle(x1, y1, x2, y2, fill='black')self.pegs.append(p)x1, x2 = x1+pegdist, x2+pegdistp = c.create_rectangle(x1, y1, x2, y2, fill='black')self.pegs.append(p)self.tk.update()# Generate piecespieceheight = pegheight//16maxpiecewidth = pegdist*2//3minpiecewidth = 2*pegwidthself.pegstate = [[], [], []]self.pieces = {}x1, y1 = (pegdist-maxpiecewidth)//2, y2-pieceheight-2x2, y2 = x1+maxpiecewidth, y1+pieceheightdx = (maxpiecewidth-minpiecewidth) // (2*max(1, n-1))for i in range(n, 0, -1):p = c.create_rectangle(x1, y1, x2, y2, fill='red')self.pieces[i] = pself.pegstate[0].append(i)x1, x2 = x1 + dx, x2-dxy1, y2 = y1 - pieceheight-2, y2-pieceheight-2self.tk.update()self.tk.after(25)# Run -- never returnsdef run(self):while 1:hanoi(self.n, 0, 1, 2, self.report)hanoi(self.n, 1, 2, 0, self.report)hanoi(self.n, 2, 0, 1, self.report)hanoi(self.n, 0, 2, 1, self.report)hanoi(self.n, 2, 1, 0, self.report)hanoi(self.n, 1, 0, 2, self.report)# Reporting callback for the actual hanoi functiondef report(self, i, a, b):if self.pegstate[a][-1] != i: raise RuntimeError # Assertiondel self.pegstate[a][-1]p = self.pieces[i]c = self.canvas# Lift the piece above peg aax1, ay1, ax2, ay2 = c.bbox(self.pegs[a])while 1:x1, y1, x2, y2 = c.bbox(p)if y2 < ay1: breakc.move(p, 0, -1)self.tk.update()# Move it towards peg bbx1, by1, bx2, by2 = c.bbox(self.pegs[b])newcenter = (bx1+bx2)//2while 1:x1, y1, x2, y2 = c.bbox(p)center = (x1+x2)//2if center == newcenter: breakif center > newcenter: c.move(p, -1, 0)else: c.move(p, 1, 0)self.tk.update()# Move it down on top of the previous piecepieceheight = y2-y1newbottom = by2 - pieceheight*len(self.pegstate[b]) - 2while 1:x1, y1, x2, y2 = c.bbox(p)if y2 >= newbottom: breakc.move(p, 0, 1)self.tk.update()# Update peg stateself.pegstate[b].append(i)def main():import sys# First argument is number of pegs, default 4if sys.argv[1:]:n = int(sys.argv[1])else:n = 4# Second argument is bitmap file, default noneif sys.argv[2:]:bitmap = sys.argv[2]# Reverse meaning of leading '@' compared to Tkif bitmap[0] == '@': bitmap = bitmap[1:]else: bitmap = '@' + bitmapelse:bitmap = None# Create the graphical objects...h = Tkhanoi(n, bitmap)# ...and run!h.run()# Call main when run as scriptif __name__ == '__main__':main()
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。