Turtles draw simple animations – Tower of Hanoi

Tower of Hanoi, also known as the Tower of Hanoi, is an educational toy originated from an ancient Indian legend. When Brahma created the world, he made three diamond pillars. On one pillar, 64 gold discs were stacked in order of size from bottom to top. Brahma ordered Brahmin to rearrange the discs on another pillar in order of size from below. And it is stipulated that the disk cannot be enlarged on the small disk, and only one disk can be moved between the three pillars at a time.

Figure 1 Ten-story Tower of Hanoi

1.Methods related to turtle drawing

(1) turtle.numinput() method

This method is used to pop up a dialog window for entering numbers. The number entered must be in the range minval to maxval if given. If not, a prompt is issued and the dialog is left open for correction.

The syntax structure is as follows:

turtle. numinput(title, prompt, default=None, minval=None, maxval=None)

(2) turtle.shapesize() method

This method is used to return or set the turtle shape stretch size and outline. The turtle’s shape will be displayed stretched according to its stretch factor, with the resizing mode set to “user”.

The syntax structure is as follows:

turtle. shapesize(stretch_wid=None, stretch_len=None, outline=None)

turtle.turtlesize(stretch_wid=None, stretch_len=None, outline=None)

(3) turtle.fillcolor() method

This method is used to return or set the fill color. If the turtle shape is a polygon, the interior of that polygon is drawn using the newly set fillcolor.

The syntax structure is as follows:

turtle. fillcolor(*args)

Note: The unit parameter represents the fill color (including shape, turtle icon), available standard color name, hexadecimal color, RGB color (1.0 mode and 255 mode)

(4) turtle.write() method

This method is used to write text at the current position.

The syntax structure is as follows:

turtle.write(arg, move=false, align=’left’, font=(‘arial’,8,’normal’))

(5) turtle.setx() method

This method is used to set the horizontal coordinate of Turtle to x, and the vertical coordinate remains unchanged.

The syntax structure is as follows:

turtle. setx(x)

Parameters: x–a number (integer or floating point number), indicating the horizontal coordinate position. Equivalent to one-way goto().

(6) turtle.sety() method

This method is used to set the vertical coordinate of Turtle to y, and the horizontal coordinate remains unchanged.

The syntax structure is as follows:

turtle. sety(y)

Parameters: y–a number (integer or floating point number), indicating the vertical coordinate position. Equivalent to one-way goto().

(7) turtle.onkey() method

This method is used to bind fun to the key release event of the key (key), waiting for the user to press the key and release it. In order to be able to register for keypress events, the TurtleScreen must have focus.

The syntax structure is as follows:

turtle. onkey(fun, key)

Example Turtle drawing, drawing a simple animation – animation demonstration of the Tower of Hanoi disk movement (recursive algorithm).

This example is adapted from the turtle example suite tdemo_minimal_hanoi.py, adding a custom Hanoi disk layer (3~20 optional), adding disk size adaptation (automatically adjust the disk according to the number of disk layers) size).

################################################
# Designed by Zhang Ruilin Created 2020-01-08 07:28 #
# Sea Turtle Draws Simple Animation - Demonstration of Tower of Hanoi Disc Moving Animation #
################################################
'''Adapted from the turtle example suite: tdemo_minimal_hanoi.py
An animation of "Tower of Hanoi": the number of disks (the number of layers of the tower) is input by the user, between 3 and 20
The disk is represented by a "square" turtle on its side, and the size of the disk is stretched into a rectangle through shapesize(), and the size is adaptive.
'''
from turtle import *

_No = numinput(title='Input parameters', prompt='Please set how many floors of Hanoi Tower', default=6,
       minval=3, maxval=20) # The user enters the number of floors of the Tower of Hanoi

class Disc(Turtle): # Generate a disk of the corresponding size according to the nth layer (adaptive)
    def __init__(self, n):
        global_n
        Turtle.__init__(self, shape="square", visible=False) # set to square shape
        self. pu()
        self.shapesize(1.5, _n*n*1.5, 2) # Stretch the square into a rectangle by layer from large to small
        self.fillcolor(n/_No, 0, 1-n/_No) # color is 1.0 mode, 0~1.0, red and blue gradient
        self.st() # Display this square shape (turtle icon)

class Tower(list):
    '''Tower of Hanoi, list of built-in subclass types'''
    def __init__(self, x):
        '''Create an empty tower. x is the position of the tower '''
        self.x = x
    def push(self, d): # Move to the end of the push list
        d.setx(self.x)
        d.sety(-150 + 34*len(self))
        self. append(d)
    def pop(self): # Remove the pop list from the end
        d = list. pop(self)
        d.sety(150)
        return d

def hanoi(n, from_, with_, to_):
    if n > 0: # recursive algorithm
        hanoi(n-1, from_, to_, with_) # Move the n-1 disks on from_ to with_ through to_
        to_.push(from_.pop()) # The last disk is moved from the source to the target (pop and push the target)
        hanoi(n-1, with_, from_, to_) # n-1 discs are moved to to_ by from_ on with_

def play():
    onkey(None,"space") # start by space
    clear()
    try:
        hanoi(_No, t1, t2, t3)
        write("Close the window and exit", align="center", font=("simsun", 16, "bold"))
    except Terminator:
        pass

def main():
    global t1, t2, t3, _No, _n
    _n=1
    if _No*1.5 > 250/32:
        _n=250/32/_No # Disc width scale factor (for self-adaptive size)
    ht(); penup(); goto(0, -225) # hide the turtle icon, lift the pen, move to the specified point
    t1 = Tower(-250) # Define three tower objects
    t2 = Tower(0)
    t3 = Tower(250)
    # Set the Tower of Hanoi on the _No layer (on the source column, that is, t1, press the first big and then small into t1 (A column))
    for i in range(int(_No),0,-1):
        t1. push(Disc(i))
    # Action hints ;-)
    write("Press the space bar to start the game", align="center", font=("simhei", 16, "bold"))
    onkey(play, "space")
    listen()
    return "event loop"

if __name__=="__main__":
    msg = main()
    print(msg)
    mainloop()

After the user enters the number of floors of the Tower of Hanoi (see Figure 2), all the disks of the Tower of Hanoi on the corresponding layer are generated on the t1 (A) column (see Figure 3), press the space bar to start the game, and move through the other two columns ( See Figure 4) until all the discs are moved to the t3 (C) column (see Figure 5). The execution results are shown in Figure 2~Figure 5.

Figure 2 Enter the number of floors of the Tower of Hanoi

Figure 3 Initial state

Figure 4 Intermediate process

Figure 5 Final state