需要帮助用乌龟制作谢尔宾斯基三角形

Need help making Sierpinski triangle with turtle

我在 youtube 上观看了 Aperture 的视频:https://youtu.be/1w40fxsyraE?t=325

在提供的时间戳 (5:25),他开始谈论创建分形的方法。我试图在 python 程序中复制它,但我得到了不同的输出。我不知道为什么我会得到这个输出,但数学似乎是正确的,所以我不知道要改变什么。谁能解释为什么我的输出看起来与视频中的不同?

import turtle as t

drawer = t.Turtle()
drawer.speed(1000)

# drawer.hideturtle()
drawer.penup()

#make dot A

dotAx = 125
dotAy = 150
drawer.goto(dotAx, dotAy)
drawer.dot(10, "red")
#

#make dot B

dotBx = 185
dotBy = 0
drawer.goto(dotBx, dotBy)
drawer.dot(10, "red")

#

#make dot C

dotCx = 0
dotCy = 0
drawer.goto(dotCx, dotCy)
drawer.dot(10, "red")

#

#make middle dot

dotPx = 100
dotPy = 75
drawer.goto(dotPx, dotPy)
drawer.dot(5,"yellow")

#

#draw dots v
x = 0
drawer.pendown()
while True:
  if x == 0:
    dotPx = (dotPx + dotAx)/2
    dotPy = (dotPy + dotAy)/2
    drawer.goto(dotPx, dotPy)
    drawer.dot(5,"black")
    print("A", dotPx, dotPy)
    x+=1
  if x == 1:
    dotPx = (dotPx + dotBx)/2
    dotPy = (dotPy + dotBy)/2
    drawer.goto(dotPx, dotPy)
    drawer.dot(5, "black")
    print("B", dotPx, dotPy)
    x+=1
  if x == 2:
    dotPx = (dotPx + dotCx)/2
    dotPy = (dotPy + dotCy)/2
    drawer.goto(dotPx, dotPy)
    drawer.dot(5, "black")
    print("C", dotPx, dotPy)
    x = 0
  

我看了视频并玩了你的代码,看不出有什么不一致之处。但是从更远的地方看,我发现通过将 x(角选择)从 cyclic 更改为 random,它工作正常:

from turtle import Turtle
from random import randint

turtle = Turtle()
turtle.speed('fastest')
turtle.hideturtle()
turtle.penup()

# make dot A
dotAx, dotAy = 0, 0
turtle.goto(dotAx, dotAy)
turtle.dot(10, 'red')

# make dot B
dotBx, dotBy = 150, 260
turtle.goto(dotBx, dotBy)
turtle.dot(10, 'red')

# make dot C
dotCx, dotCy = 300, 0
turtle.goto(dotCx, dotCy)
turtle.dot(10, 'red')

# make random dot inside triangle
dotPx, dotPy = 100, 75
turtle.goto(dotPx, dotPy)
turtle.dot(5, 'green')

# draw dots

while True:
    x = randint(0, 2)  # pick a random corner

    if x == 0:
        dotPx = (dotAx + dotPx)/2
        dotPy = (dotAy + dotPy)/2
        turtle.goto(dotPx, dotPy)
        turtle.dot(5)
    elif x == 1:
        dotPx = (dotBx + dotPx)/2
        dotPy = (dotBy + dotPy)/2
        turtle.goto(dotPx, dotPy)
        turtle.dot(5)
    elif x == 2:
        dotPx = (dotCx + dotPx)/2
        dotPy = (dotCy + dotPy)/2
        turtle.goto(dotPx, dotPy)
        turtle.dot(5)

也许这会缩小您对视频所建议的原始方法为何失败的搜索范围。如果我是从头开始写这篇文章,并试图获得更精细的细节(和速度),我可能会通过以下方式更好地利用 turtle 和 Python:

from turtle import Screen, Turtle, Vec2D
from random import choice

VERTICES = [Vec2D(0, 0), Vec2D(150, 260), Vec2D(300, 0)]
point = Vec2D(100, 75)  # random point inside triangle

def doit():
    global point
    point = (choice(VERTICES) + point) * 0.5

    turtle.goto(point)
    turtle.dot(2)

    screen.update()
    screen.ontimer(doit)

screen = Screen()
screen.tracer(False)

turtle = Turtle()
turtle.hideturtle()
turtle.penup()

for vertex in VERTICES:
    turtle.goto(vertex)
    turtle.dot(5, 'red')

turtle.goto(point)
turtle.dot(5, 'green')

doit()

screen.mainloop()