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