用遞歸和Turtle庫繪制八進制的雪花。以下是遞歸深度從1~5的八面形雪花:
除了通過遞歸深度停止遞歸,還可以在半徑小于特定大小時停止遞歸。以下八面形雪花是通過将半徑遞歸的阈值設置為10生成的。現在你可以看到所有的八邊形都有相同的尺寸
源代碼
import turtle
from turtle import *
import math
import random
# 以指定的中心,畫八面形
def octagon(x, y, r): # x,y is the center
up()
goto(x, y)
seth(90)
fd(r)
left(180 - 135 / 2)
down()
begin_fill()
edgeSize = 2 * r * math.sin(math.radians(45 / 2))
for _ in range(8):
fd(edgeSize)
left(45)
end_fill()
# 畫八面形雪花
def octaflake(x, y, r, n):
# 根據遞歸深度(recursion depths)控制何時退出遞歸
# if n ==1:
# octagon(x, y, r)
# return
# 根據八面形的半徑控制,當半徑小于10時,退出遞歸
if r < 10:
octagon(x, y, r)
return
r2 = r / (1 1 / math.tan(math.radians(45 / 2)))
octaflake(x, y, r - 2 * r2, n - 1)
direction = 90
for _ in range(8):
up()
goto(x, y)
seth(direction)
fd(r - r2)
octaflake(xcor(), ycor(), r2, n - 1)
direction = 45
def main():
screen = Screen()
screen.setup(800, 600)
screen.title('cloudcloder出品--畫雪花')
bgcolor('royal blue')
fillcolor('white')
pencolor('steel blue')
speed(0)
screen.tracer(0, 0)
octaflake(-200, -200, 70, 1)
octaflake(-50, -50, 80, 2)
octaflake(-190, 100, 50, 3)
octaflake(200, 100, 80, 4)
octaflake(-190, 200, 50, 3)
octaflake(-190, 0, 50, 3)
octaflake(180, -140, 120, 5)
screen.update()
done()
if __name__ == "__main__":
hideturtle()
up()
goto(-260, 270)
write("今日頭條-cloudcoder出品", align='left', font=('fangsong', 14, 'normal'))
showturtle()
main()