【发布时间】:2021-06-19 23:19:45
【问题描述】:
我正在尝试在 Python 中创建一个可以绘制 n 角星的程序。我对有 6、14、22、... 点的星星有问题。我不知道如何解决这种模式。
这是我目前所拥有的:
from turtle import *
# Settings
speed(5)
width(1)
color('red', 'yellow') # outline, fill
x=int(input('Enter the number of points you want the star to have.'))
begin_fill()
# If a star has even number of points, then it needs to be drawn differently
if x%4 == 0:
for i in range(x):
y=180-360/x
right(y)
forward(300)
y+=360/x
# For special cases such as 10, 18, 26, ...
elif x%2 == 0:
for i in range(x):
y=90+180/x
right(y)
forward(300)
# For special cases such as 6, 14, 22, ...
# I need help here (this condition needs to be changed)...
elif x%2 == 0:
for i in range(x):
y=2*180/x
right(y)
forward(300)
# For stars with odd number of points
else:
for i in range(x):
right(180-180/x)
forward(300)
end_fill()
hideturtle()
exitonclick()
【问题讨论】:
-
所以你想检查不是4的倍数的偶数?
-
是的,但实际上是这些数字的一个子集。例如,10,18,26, ... 也不是 4 的倍数,但我找到了一种在该模式组中绘制星星的方法。但是,对于具有 6、14、22、... 点的星星,我似乎无法做到这一点。另外,有没有更优雅的方法来解决这个问题?
-
首先在纸上绘制并手动计算角度 - 然后在代码中使用这些信息来计算角度。
-
我认为您无法使用您的方法绘制这些星星 - 您使用单线/多边形绘制它,但星星 6 是由两个分开的三角形/多边形创建的。使用单线/多边形您应该只绘制没有内部元素的外部线。
-
@hilberts_drinking_problem 很好的例子:)
标签: python turtle-graphics python-turtle