我正在练习我的Python技能。我很好奇如何使用海龟和函数绘制这朵花,而不使用turtle.circle(radius)
。
https://i.stack.imgur.com/ZYUsz.png
此外,我制作了一个像这样的多边形螺旋:
import turtle
import math
def draw_polygons():
""""Make t draws a polygon of side sd and length l"""
sd = 20
area = 50000
while sd >= 3:
side_length = math.sqrt(area / sd * 4 * math.atan(math.pi / sd))
for i in range(sd):
for a_color in ["red", "yellow", "blue", "brown", "pink", "green", "black", "orange", "purple"]:
rest.fillcolor(a_color)
rest.begin_fill()
rest.forward(side_length)
rest.left(360/sd)
print("side length =", side_length)
rest.penup()
rest.forward(side_length / 2)
rest.pendown()
rest.right(30)
sd -= 1
rest = turtle.Turtle()
wn = turtle.Screen()
draw_polygons()
wn.exitonclick()
我想用不同颜色填充每个多边形,我做错了什么步骤?或者接下来我应该做什么步骤?
示例多边形螺旋看起来像这样:
答案 0 :(得分:1)
你问两个不同的程序,让我们先解决第二个问题。除了你的颜色问题,你的循环逻辑不正确,内部是begin_fill()
而不是内部循环之外。让我们重新编写该程序:
from turtle import Turtle, Screen
import math
COLORS = ["red", "yellow", "blue", "brown", "pink", "green", "black", "orange", "purple"]
def draw_polygons(sides, area):
""" Draws a polygon with 'sides' sides and area 'area' """
for i, sd in enumerate(range(sides, 2, -1)):
side_length = math.sqrt(area / sd * 4 * math.atan(math.pi / sd))
# print("side length =", side_length)
a_color = COLORS[i % len(COLORS)]
rest.fillcolor(a_color)
rest.pendown()
rest.begin_fill()
for _ in range(sd):
rest.forward(side_length)
rest.left(360 / sd)
rest.end_fill()
rest.penup()
rest.forward(side_length / 2)
rest.right(30)
wn = Screen()
rest = Turtle()
rest.speed('fastest')
draw_polygons(20, 40_000)
rest.hideturtle()
wn.exitonclick()
要回到原来的问题,一种方法是在做下一个矩形颜色之前放下矩形的每种颜色。这是你的代码的返工,只绘制图像的花瓣部分,因为我认为这就是你所要求的。我只是看了下面的一些距离和角度,你需要做数学计算才能使它们正确:
from turtle import Turtle, Screen
import math
COLORS = ["green", "orange", "red", "yellow"]
def draw_polygons(area):
""" Draws a circle using rectangles with area 'area' """
side_length = math.sqrt(area * math.atan(math.pi / 4))
for a_color in COLORS:
for _ in range(12):
rest.fillcolor(a_color)
rest.forward(3 * side_length / 10)
rest.right(15)
rest.left(112) # I eyeballed this angle, need to do math
rest.pendown()
rest.begin_fill()
for _ in range(2):
rest.forward(side_length * 2)
rest.left(90)
rest.forward(side_length / 2)
rest.left(90)
rest.end_fill()
rest.penup()
rest.right(112) # undo rotation
rest.forward(3 * side_length / 10)
rest.right(15)
# I eyeballed these opposing parameters -- need to do the math
rest.forward(2 * side_length / 13)
rest.right(7.5)
wn = Screen()
rest = Turtle()
rest.speed('fastest')
rest.penup()
rest.sety(120)
draw_polygons(20_000)
rest.hideturtle()
wn.exitonclick()
答案 1 :(得分:0)
我一眼就说你的缩进是错误的。
for a_color in ["red", "yellow", "blue", "brown", "pink", "green", "black", "orange", "purple"]:
rest.fillcolor(a_color)
rest.begin_fill()
在这里,您遍历所有颜色,然后填写形状。 颜色将始终为紫色,因为这是您在rest.fillcolor
中设置的最后一种颜色作为解决问题的一种方法,您可以通过调用rest.fillcolor(colors[(i % len(colors)))
来创建颜色列表并获得所需的颜色。