gpt4 book ai didi

Python Turtle for 循环无限运行

转载 作者:太空宇宙 更新时间:2023-11-03 20:56:08 26 4
gpt4 key购买 nike

我有一些 Turtle 代码,之前已经成功运行过,用 Turtle IDE 在 Repl.it 的 Python 中绘制了 Sierpinski 垫片,但最近当我尝试再次运行它时,它成功地完成了所有操作,除了一旦它命中for 循环中, turtle 只是开始旋转,直到很久以后才执行 for 循环中的行。

我在for循环中添加了一个print(i),它重复打印0,就好像它是一个无限循环

import turtle
from turtle import *

t = Turtle()
t.speed(0)
t.shape('turtle')
t.color('dark green')

def SGRules(char):
if char == 'F':
return 'F+F-F-F+F'
else:
return char

def processStr(oldstr, Fractal_Rules):
newstr = ""
for char in oldstr:
newstr = newstr + Fractal_Rules(char)
return newstr

def createLSystem(iteration, axiom, Fractal_Rules):
startstr = axiom
endstr = ""
for i in range(iteration):
endstr = processStr(startstr, Fractal_Rules)
startstr = endstr
return endstr

def drawLSystem(aturtle, lsys, angle, length):
for cmd in lsys:
if cmd == 'F':
aturtle.forward(length)
elif cmd == '+':
aturtle.left(angle)
elif cmd == '-':
aturtle.right(angle)

sgstr = createLSystem(4, 'F', SGRules)
print(sgstr)
drawLSystem(t, sgstr, 120, 20)
for i in range(2):
print(i)
t.left(120)
t.forward(20 * 2**4)

它应该在到达右下角后立即绘制剩余的外三角形的两条边。

最佳答案

这种代码清理工作对我来说在 repl.it 和 Python 控制台中运行良好:

from turtle import Screen, Turtle

ANGLE = 120
LENGTH = 20
ITERATIONS = 4

def SGRules(character):
if character == 'F':
return 'F+F-F-F+F'

return character

def processStr(string, rules):
new_string = ""

for character in string:
new_string += rules(character)

return new_string

def createLSystem(iterations, axiom, rules):
string = ""

for _ in range(iterations):
string = processStr(axiom, rules)
axiom = string

return string

def drawLSystem(turtle, lsys, angle, length):
for command in lsys:
if command == 'F':
turtle.forward(length)
elif command == '+':
turtle.left(angle)
elif command == '-':
turtle.right(angle)

yertle = Turtle('turtle')
yertle.speed('fastest')
yertle.shape('turtle')
yertle.color('dark green', 'light green')

sg_string = createLSystem(ITERATIONS, 'F', SGRules)
print(sg_string)
drawLSystem(yertle, sg_string, ANGLE, LENGTH)

for _ in range(2):
yertle.left(ANGLE)
yertle.forward(LENGTH * 2 ** ITERATIONS)

screen = Screen()
screen.mainloop()

尽管你的原始代码在 Python 控制台中运行良好,但我在最后添加了到 tkinter 事件循环的传输以防止窗口关闭。

关于Python Turtle for 循环无限运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56017822/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com