Turtles draw simple animations - Tower of Hanoi

    The Tower of Hanoi , also known as the Tower of Hanoi, is an educational toy that 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. Related methods of 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 grammatical 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 grammatical 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 grammatical 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 grammatical 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 grammatical 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 grammatical 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 grammatical structure is as follows:

turtle.onkey(fun, key)

 An example of 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 the number of custom Tower of Hanoi disk layers (3~20 optional), adding disk size adaptation (automatically adjust the disk according to the number of disk layers) size).

##############################################
# 设计 Zhang Ruilin    创建 2020-01-08 07:28 #
# 海龟绘制简单动画——汉诺塔圆盘移动动画演示 #
##############################################
'''根据海龟例子套件:tdemo_minimal_hanoi.py改编
一个“汉诺塔”的动画:盘片数(塔的层数)由用户输入,介于3~20之间
盘片用其侧面“方形”的海龟表示,大小盘子通过shapesize()拉伸为矩形,尺寸自适应。
'''
from turtle import *

_No = numinput(title='输入参数', prompt='请设置几层汉诺塔', default=6,
       minval=3, maxval=20)                         # 用户输入汉诺塔层数

class Disc(Turtle):                                 # 按第n层生成对应尺寸盘片(自适应)
    def __init__(self, n):
        global _n
        Turtle.__init__(self, shape="square", visible=False) # 设置为方块形状
        self.pu()
        self.shapesize(1.5, _n*n*1.5, 2)            # 按层从大到小拉伸方块为矩形
        self.fillcolor(n/_No, 0, 1-n/_No)           # 颜色为1.0模式,0~1.0,红蓝渐变
        self.st()                                   # 显示此方块形状(海龟图标)

class Tower(list):
    '''汉诺塔, 内置子类类型列表'''
    def __init__(self, x):
        '''创建一个空塔。x是塔柱的位置'''
        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

def hanoi(n, from_, with_, to_):
    if n > 0:                                       # 递归算法
        hanoi(n-1, from_, to_, with_)               # 将from_上n-1张盘片通过to_移至with_
        to_.push(from_.pop())                       # 最后1张盘片从源移至目标(弹出压入目标)
        hanoi(n-1, with_, from_, to_)               # n-1张盘片在with_上通过from_移至to_

def play():
    onkey(None,"space")                             # 按空格开始
    clear()
    try:
        hanoi(_No, t1, t2, t3)
        write("关闭窗口退出", 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                               # 盘片宽度比例因子(自适尺寸时用)
    ht(); penup(); goto(0, -225)                    # 隐藏海龟图标,抬笔,移动到指定点
    t1 = Tower(-250)                                # 定义三根塔柱对象
    t2 = Tower(0)
    t3 = Tower(250)
    # 设置_No层的汉诺塔(在源柱,即t1上,先大后小压入t1(A柱))
    for i in range(int(_No),0,-1):
        t1.push(Disc(i))
    # 操作提示 ;-)
    write("按空格键开始游戏", align="center", font=("simhei", 16, "bold"))
    onkey(play, "space")
    listen()
    return "事件循环"

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 corresponding layer of the Tower of Hanoi 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 Input the number of floors of the Tower of Hanoi

Figure 3 Initial state

Figure 4 Intermediate process

Figure 5 final state

Guess you like

Origin blog.csdn.net/hz_zhangrl/article/details/129700332