如何使用乌龟在python中绘制sierpinski地毯
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何使用乌龟在python中绘制sierpinski地毯相关的知识,希望对你有一定的参考价值。
我正在尝试使用乌龟在python中创建Sierpinski地毯。到目前为止这是我的代码:
from turtle import *
# Make a screen and a pen
pen = Pen()
screen = Screen()
pen.speed(0)
pen.color('orange')
pen.width(1.5)
def s (n, l):
for i in range (4):
s(n-1, l)
pen.right(45); pen.forward(l); pen.right(45)
s(n-1, l)
pen.left(90); forward (l); pen.left(90)
s(n-1, l)
pen.right(45); pen.forward(l); pen.left(45)
s(n-1, l)
但是每当我运行它时,我收到以下消息:
line 17, in s
s(n-1, l)
[Previous line repeated 990 more times]
RecursionError: maximum recursion depth exceeded
我尝试使用if i in range(4):
,但这也不起作用,我哪里出错了?
答案
你需要“停止条件”来停止递归。
例如:
if n == 0: # "stop condition"
# draw or exit
else: # recursions
# execute some recursions
我不知道算法,但我用这段代码创建了地毯。
我使用trace(0)
和update()
只是为了更快地绘制它。
#!/usr/bin/env python3
import turtle
# --- functions ---
def s(n, l):
if n == 0: # stop conditions
# draw filled rectangle
turtle.color('black')
turtle.begin_fill()
for _ in range (4):
turtle.forward(l)
turtle.left(90)
turtle.end_fill()
else: # recursion
# around center point create 8 smalles rectangles.
# create two rectangles on every side
# so you have to repeat it four times
for _ in range(4):
# first rectangle
s(n-1, l/3)
turtle.forward(l/3)
# second rectangle
s(n-1, l/3)
turtle.forward(l/3)
# go to next corner
turtle.forward(l/3)
turtle.left(90)
# update screen
turtle.update()
# --- main ---
# stop updating screen (to make it faster)
turtle.tracer(0)
# start
s(4, 400)
# event loop
turtle.done()
维基百科:Sierpinski carpet
以上是关于如何使用乌龟在python中绘制sierpinski地毯的主要内容,如果未能解决你的问题,请参考以下文章