[Guide] python recursive Trilogy (turtle-based visualization) - a, Sierpinski triangle

Recursive trilogy:

Billion, recursion and the three principles

First, the Sierpinski triangle

Second, the Tower of Hanoi

Third, explore the maze

1, Sierpinski triangle

This tutorial is my contribution in the b station video tutorials corresponding text version (being updated)
video in more detail, a more concise text, we choose a look like

Sierpinski triangle (Sierpinski triangle),
is shown in FIG fractal
click view Sierpinski triangle drawn animation (Sierpinski Triangle)
Figure I
where an analysis process which draw
1, a drawing triangle
2, taking the midpoint of three sides of the triangle ,
every two common midpoint vertices and edges is located,
in groups of three, are combined into three smaller triangles
of the three triangles are drawn,
as shown below, respectively, ADF, DBE, FEC.
3, 2 of the three small triangles, repeat step 2.
Here Insert Picture Description
Theoretically, step two can be repeated indefinitely go on, but in terms of the code, to ensure that finite algorithm, it usually will end after a limited number of step two runs.

2, combined with the three principles of recursive writing code

First, the need to add a method draw_sierpinskito draw the specified number of triangular Sierpinski

def draw_sierpinski(triangle,depth):
	"""
	绘制指定层数的谢尔宾斯基三角形
	triangle: 指定三角形三个顶点坐标,示例:((ax,ay),(bx,by),(cx,cy))。
	depth: 指定层数
	"""

Here to explain the specific meaning under layers of depth, step two above the number that is executed
then the figure below from left to right, the number of layers are: 0,1,2,3,4
Here Insert Picture Description
next and then we re-analysis draw_sierpinskimethods should be how write
1, drawing a triangle triangle
2, the number of layers if the depth is 0 recursive exit
3, taking the midpoint of a triangle, and the three small triangle formed by the corresponding,
4, these three triangles, respectively draw_sierpinski calling method again,
drawn depth- 1 Sierpinski triangle
in order to achieve the above four steps, we need to add two auxiliary method
get_midpoint(a,b): returns a, b of the middle coordinate points
draw_triangle(a,b,c): in a, b, drawing a triangle vertex C
the final code follows

#!/usr/bin/python3
import turtle


t = turtle.Turtle()


def get_midpoint(a, b):
    ax, ay = a
    bx, by = b
    return (ax + bx) / 2, (ay + by) / 2


def draw_triangle(a, b, c):
    ax, ay = a
    bx, by = b
    cx, cy = c

    t.penup()
    t.goto(ax, ay)
    t.pendown()
    t.goto(bx, by)
    t.goto(cx, cy)
    t.goto(ax, ay)
    t.penup()


def draw_sierpinski(triangle, depth):
    """
    :param triangle: 指定三角形三个顶点坐标,示例:((ax,ay),(bx,by),(cx,cy))。
    :param depth: 指定层数
    """
    a, b, c = triangle
    draw_triangle(a, b, c)
    if depth == 0:
        return
    else:
        d = get_midpoint(a, b)
        e = get_midpoint(b, c)
        f = get_midpoint(c, a)
        draw_sierpinski([a, d, f], depth-1)
        draw_sierpinski([d, b, e], depth-1)
        draw_sierpinski([f, e, c], depth-1)


if __name__ == '__main__':
    triangle = [[-200, -100], [0, 200], [200, -100]]
    draw_sierpinski(triangle, 5)
    turtle.done()

Operating results as shown
Here Insert Picture Description
and then we look at the code in conjunction with the three principles of recursion
as shown:
Here Insert Picture Description
add that here, recursively three principles 2, and three are often performed together, and
that is to 1 base case called recursively move closer to the case method itself

3, Last added:

Problem 1: no color change
I in the station b on the Sierpinski triangle video tutorial shown as the final code in step two, but there is a small details, that there is no change in color between the different layers of the triangle with a view of the beginning of this article does not match. So we'd like to add about the color processing
Question 2: After the final run in the middle black spots
we see Step two heavy final run renderings, the middle of a dark point, the black point is the turtle brush object, generally arrow style, put in the middle of the destruction of the entire screen, hidden away enough
to solve the problem after twelve code is as follows

#!/usr/bin/python3
import turtle


t = turtle.Turtle()
t.hideturtle()
FillColors=[
    '#CAE1FF',
    '#FFEFDB',
    '#8470FF',
    '#FF6347',
    '#FFDEAD',
    '#C1FFC1'
]


def get_midpoint(a, b):
    ax, ay = a
    bx, by = b
    return (ax + bx) / 2, (ay + by) / 2


def draw_triangle(a, b, c, depth):
    ax, ay = a
    bx, by = b
    cx, cy = c

    t.penup()
    _tcolor = FillColors[depth % len(FillColors)]

    t.color("black", _tcolor)
    t.goto(ax, ay)
    t.pendown()
    t.begin_fill()
    t.goto(bx, by)
    t.goto(cx, cy)
    t.goto(ax, ay)
    t.end_fill()
    t.penup()


def draw_sierpinski(triangle, depth):
    """
    :param triangle: 指定三角形三个顶点坐标,示例:((ax,ay),(bx,by),(cx,cy))。
    :param depth: 指定层数
    """
    a, b, c = triangle
    draw_triangle(a, b, c, depth)
    if depth == 0:
        return
    else:
        d = get_midpoint(a, b)
        e = get_midpoint(b, c)
        f = get_midpoint(c, a)
        draw_sierpinski([a, d, f], depth-1)
        draw_sierpinski([d, b, e], depth-1)
        draw_sierpinski([f, e, c], depth-1)


if __name__ == '__main__':
    triangle = [[-200, -100], [0, 200], [200, -100]]
    draw_sierpinski(triangle, 5)
    turtle.done()

At this time, operating results shown in
Here Insert Picture Description
Question 3: redrawing the lines of varying thickness resulting in
if you have friends to observe carefully, you will find some of the sideline is sometimes the case of varying thickness.
Here Insert Picture Description
This is due to the second step of the drawing process is repeated every time, sideline also be redrawn, but not always, and sometimes redrawn the original edges are flush, which repeatedly lead to missing the entire line is actually how a not entirely consistent line stacked up, so it looks there will be a small rough.

In fact, in order to let everyone step two straightforward to understand recursion, so I chose this method convenient sideline redrawn to draw recursive Sierpinski triangle, convenient drawback is redrawn sideline lead to missing segments superimposed, of course, this shortcoming for starters can be ignored.

If we are to solve this problem, in fact we need to adjust our process to draw, modify the original drawing Step two in the process, but it makes recursive little trouble a little bit.
Specific can read my previous blog article written by Park, this article will use is another drawing process, to avoid duplication of drawing a line: https: //www.cnblogs.com/BigShuang/p/10837020.html
I will not carry over.

In this paper, by three examples to help you understand recursion (showing movies uploaded B station):
Sierpinski triangle (Sierpinski Triangle)
Tower of Hanoi (Tower of Hanoi)
to explore the maze (Maze Exploring)
article code has been uploaded to github: https://github.com/BigShuang/recursion-with-turtle
reference herein:
Problem Solving the Data Structures and Algorithms with a using Python
Turtle official document:
Chinese: https://docs.python.org/zh-cn/3.6/ library / turtle.html
English: https://docs.python.org/3.6/library/turtle.html

Published 14 original articles · won praise 2 · Views 1022

Guess you like

Origin blog.csdn.net/python1639er/article/details/104038495