由Turtle绘制的Random(?)生成的多边形需要根据其大小填充颜色,但不会填充完成的形状。 这是我已经编写的代码。
import turtle, random
def drawpoly (sTurtle, sSides, sLength):
for i in range (sSides):
sTurtle.begin_fill()
sTurtle.forward(sLength)
sTurtle.left(360/sSides)
sTurtle.end_fill()
sides = random.randint (3, 21)
size = random.randint (30, 200)
wn = turtle.Screen()
wn.bgcolor('black')
mac = turtle.Turtle()
mac.color('black')
mac.fillcolor()
mac.pensize(3)
for each in (size, sides):
if each <= 99:
mac.fillcolor('red')
elif each <= 149:
mac.fillcolor('white')
elif each >149:
mac.fillcolor('blue')
drawpoly(mac, sides, size)
最后,我尝试的大多数操作最终仅更改了Turtle线条颜色。我似乎无法获得Mac(乌龟)绘制的(半随机)多边形以填充颜色。
答案 0 :(得分:0)
我发现的主要问题是以下代码:
for i in range (sSides):
sTurtle.begin_fill()
sTurtle.forward(sLength)
sTurtle.left(360/sSides)
sTurtle.end_fill()
您正在尝试填充线条而不是多边形。您真正想要的是:
sTurtle.begin_fill()
for i in range (sSides):
sTurtle.forward(sLength)
sTurtle.left(360/sSides)
sTurtle.end_fill()
这段代码简直令人困惑:
for each in (size, sides):
if each <= 99:
mac.fillcolor('red')
elif each <= 149:
mac.fillcolor('white')
elif each >149:
mac.fillcolor('blue')
您说您要根据 size 进行着色,但最后要覆盖它,并按 sides 进行着色。这是我对您的代码的重做,可以解决这两个问题:
from turtle import Screen, Turtle
from random import randint
def drawpoly(sTurtle, sSides, sLength):
sTurtle.begin_fill()
for _ in range(sSides):
sTurtle.forward(sLength)
sTurtle.left(360 / sSides)
sTurtle.end_fill()
sides = randint(3, 21)
size = randint(30, 200)
wn = Screen()
wn.bgcolor('black')
mac = Turtle()
mac.pensize(3)
if size < 100:
mac.fillcolor('red')
elif size < 150:
mac.fillcolor('white')
else:
mac.fillcolor('blue')
drawpoly(mac, sides, size)
wn.exitonclick()