Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- """ turtle-example-suite:
- tdemo_minimal_hanoi.py
- A minimal 'Towers of Hanoi' animation:
- A tower of 6 discs is transferred from the
- left to the right peg.
- An imho quite elegant and concise
- implementation using a tower class, which
- is derived from the built-in type list.
- Discs are turtles with shape "square", but
- stretched to rectangles by shapesize()
- ---------------------------------------
- To exit press STOP button
- ---------------------------------------
- """
- from turtle import *
- import time
- import sys
- from tkinter import *
- """from tkinter import ttk"""
- import tkinter.simpledialog
- root = Tk()
- w = Label(root, text="Dialog Practice")
- w.pack()
- name = tkinter.simpledialog.askstring("DISX", "Tell us how many discs you want today (min=0;max=10)")
- title("The Towers of Hanoi by Aleksandar Stefanov / Student ID:51768282")
- class Disc(Turtle):
- def __init__(self, n):
- Turtle.__init__(self, shape="square", visible=False)
- self.speed(10 - n)
- self.pu()
- self.shapesize(1.5, n*1.5, 2) # square-->rectangle
- self.fillcolor(n/10., 0, 1-n/10.)
- self.st()
- class Tower(list):
- "Hanoi tower, a subclass of built-in type list"
- def __init__(self, x):
- "create an empty tower. x is x-position of peg"
- self.x = x
- def push(self, d):
- d.setx(self.x)
- d.sety(-150+34*len(self))
- self.append(d)
- def pop(self):
- d = list.pop(self)
- d.sety(150)
- return d
- moves = 0
- def hanoi(n, from_, with_, to_):
- global moves
- if int(n) > 0:
- hanoi(int(n)-1, from_, to_, with_)
- moves += 1
- to_.push(from_.pop())
- hanoi(int(n)-1, with_, from_, to_)
- clear()
- write("Total moves = "+ str(moves),
- align="center", font=("Courier", 16, "bold"))
- def play():
- onkey(None,"space")
- clear()
- hanoi(name, t1, t2, t3)
- sety(-250)
- write("press STOP button to exit",
- align="center", font=("Courier", 16, "bold"))
- def pause():
- time.sleep(3)
- def quit():
- onkey(None,"q")
- bye()
- def main():
- global t1, t2, t3
- ht(); penup(); goto(0, -225) # writer turtle
- t1 = Tower(-250)
- t2 = Tower(0)
- t3 = Tower(250)
- # make tower of 6 discs
- for i in range(int(name),0,-1):
- t1.push(Disc(i))
- # prepare spartanic user interface 😉
- write("Aleksandar Stefanov's ToH. Press spacebar to start game",
- align="center", font=("Courier", 16, "bold"))
- onkey(play, "space")
- sety(-260)
- write("Press p to Pause",
- align="center", font=("Courier", 16, "bold"))
- onkey(pause, "p")
- sety(-300)
- write("Press q to Quit",
- align="center", font=("Courier", 16, "bold"))
- onkey(quit, "q")
- listen()
- return "EVENTLOOP"
- if __name__=="__main__":
- msg = main()
- print(msg)
- mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement