jpayne@69: #!/usr/bin/env python3 jpayne@69: """ turtle-example-suite: jpayne@69: jpayne@69: tdemo_minimal_hanoi.py jpayne@69: jpayne@69: A minimal 'Towers of Hanoi' animation: jpayne@69: A tower of 6 discs is transferred from the jpayne@69: left to the right peg. jpayne@69: jpayne@69: An imho quite elegant and concise jpayne@69: implementation using a tower class, which jpayne@69: is derived from the built-in type list. jpayne@69: jpayne@69: Discs are turtles with shape "square", but jpayne@69: stretched to rectangles by shapesize() jpayne@69: --------------------------------------- jpayne@69: To exit press STOP button jpayne@69: --------------------------------------- jpayne@69: """ jpayne@69: from turtle import * jpayne@69: jpayne@69: class Disc(Turtle): jpayne@69: def __init__(self, n): jpayne@69: Turtle.__init__(self, shape="square", visible=False) jpayne@69: self.pu() jpayne@69: self.shapesize(1.5, n*1.5, 2) # square-->rectangle jpayne@69: self.fillcolor(n/6., 0, 1-n/6.) jpayne@69: self.st() jpayne@69: jpayne@69: class Tower(list): jpayne@69: "Hanoi tower, a subclass of built-in type list" jpayne@69: def __init__(self, x): jpayne@69: "create an empty tower. x is x-position of peg" jpayne@69: self.x = x jpayne@69: def push(self, d): jpayne@69: d.setx(self.x) jpayne@69: d.sety(-150+34*len(self)) jpayne@69: self.append(d) jpayne@69: def pop(self): jpayne@69: d = list.pop(self) jpayne@69: d.sety(150) jpayne@69: return d jpayne@69: jpayne@69: def hanoi(n, from_, with_, to_): jpayne@69: if n > 0: jpayne@69: hanoi(n-1, from_, to_, with_) jpayne@69: to_.push(from_.pop()) jpayne@69: hanoi(n-1, with_, from_, to_) jpayne@69: jpayne@69: def play(): jpayne@69: onkey(None,"space") jpayne@69: clear() jpayne@69: try: jpayne@69: hanoi(6, t1, t2, t3) jpayne@69: write("press STOP button to exit", jpayne@69: align="center", font=("Courier", 16, "bold")) jpayne@69: except Terminator: jpayne@69: pass # turtledemo user pressed STOP jpayne@69: jpayne@69: def main(): jpayne@69: global t1, t2, t3 jpayne@69: ht(); penup(); goto(0, -225) # writer turtle jpayne@69: t1 = Tower(-250) jpayne@69: t2 = Tower(0) jpayne@69: t3 = Tower(250) jpayne@69: # make tower of 6 discs jpayne@69: for i in range(6,0,-1): jpayne@69: t1.push(Disc(i)) jpayne@69: # prepare spartanic user interface ;-) jpayne@69: write("press spacebar to start game", jpayne@69: align="center", font=("Courier", 16, "bold")) jpayne@69: onkey(play, "space") jpayne@69: listen() jpayne@69: return "EVENTLOOP" jpayne@69: jpayne@69: if __name__=="__main__": jpayne@69: msg = main() jpayne@69: print(msg) jpayne@69: mainloop()