它的编码是从100到0半径一个接一个地转,就像红色,蓝色,红色,蓝色。我用if else做到了,但我相信我可以用更高级的方式做到这一点,比如随机、列表等。你能帮上忙吗?
import turtle
screen = turtle.Screen()
turtle = turtle.Turtle('turtle')
turtle.pensize(3)
turtle.pencolor('red')
def circle(x, y, r):
if r <= 0:
return
turtle.penup()
turtle.goto(0, -r)
turtle.pendown()
turtle.circle(r)
if (turtle.pencolor() == 'red'):
turtle.pencolor('blue')
else:
turtle.pencolor('red')
circle(0, 0, r-10)
circle(0, 0, 100)
screen.exitonclick()发布于 2020-12-17 22:22:46
您可以使用itertools.cycle在颜色之间循环:
from itertools import cycle
colors = cycle(["red", "blue"])
# ...
def circle(...):
turtle.pencolor(next(colors)) # will assign alternating values
# ...发布于 2020-12-18 03:10:20
您可以使用三元运算符在一行中设置颜色,而不是使用if-else的4行:
color = "red" if turtle.pencolor() == "blue" else "blue"
turtle.pencolor(color)它节省了几行代码,但与您的代码相比,它并没有真正优化任何东西。
https://stackoverflow.com/questions/65342484
复制相似问题