使用海龟图形在Python中绘制n角星
我的教授让我们班写一个Python函数,功能是:
用一个叫做star(turtle, n, d)的函数画一个规则的n角星,边长为d。
这是我目前写的代码:
def star(turtle, n, d):
angle = (180-((180*(n-2))/n))*2
for i in range(n):
t.forward(d)
t.left(angle)
return angle
我遇到的问题是,我的函数只能画出角数为奇数的星星(比如5角、7角、9角的星)。当我让它画一个角数为偶数的星星时,它却画出了边数为n/2的多边形。所以当我要求画一个8角星时,它画出了一个正方形,6角星则变成了一个三角形,依此类推。
我尝试过多次修改角度的计算公式,但无论怎么改,都无法正确处理任何给定的n。
谢谢大家的帮助!
3 个回答
-1
你的公式有一点错误:
def star(turtle, n, d):
for i in range(n):
angle = 180.0 - 180.0 / n
turtle.forward(d)
turtle.right(angle)
turtle.forward(d)`
1
这段代码可以画出一个星星,前提是星星的尖角数量要大于5个。它需要两个参数:n
表示尖角的数量,size
控制小海龟每一步的大小。
import turtle
turtle.showturtle()
turtle.shape("classic")
def turtle_star(n, size = 100):
extent = 360 / n
if n % 2 == 0:
coords = []
for a in range(0, n):
turtle.penup()
coords.append(turtle.pos())
turtle.circle(size, extent)
for b in range(0, len(coords)):
if b % 2 == 0:
turtle.pendown()
turtle.goto(coords[b][0], coords[b][1])
else:
continue
turtle.goto(coords[0][0], coords[0][1])
turtle.penup()
for c in range(0, (len(coords) + 1)):
if c % 2 != 0:
turtle.goto(coords[c][0], coords[c][1])
turtle.pendown()
else:
continue
turtle.goto(coords[1][0], coords[1][1])
else:
angle = 180 - (180 / n)
for a in range(n):
turtle.forward(size)
turtle.right(angle)
turtle_star(11)
(奇数)和turtle(6)
(偶数)画出来的效果如下:
3
你可以用同样的代码来画出大多数奇数和偶数尖的星星,只需要用一个求最大公约数的程序来找互质的数,并把失败的情况当作例外处理:
import sys
import turtle
from time import sleep
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
def normal_star(size, color, points):
if points <= 4:
raise ValueError('Not enough points')
turtle.color(color)
for coprime in range(points // 2, 1, -1):
if gcd(points, coprime) == 1:
print("({},{})".format(points, coprime), file=sys.stderr)
start = turtle.position()
for _ in range(points):
turtle.forward(size)
turtle.left(360.0 / points * coprime)
turtle.setposition(start)
return
abnormal_star(size, color, points)
def abnormal_star(size, color, points):
# deal with special cases here
print("Exception:", points, file=sys.stderr)
for points in range(5, 20):
turtle.reset()
normal_star(200, 'red', points)
sleep(5)
turtle.exitonclick()
对于点数从5到20的星星,只有在点数为6的时候找不到解决方案,这个情况需要特别处理,也就是说你可以写一些专门的代码,或者直接告诉用户这是一个你无法处理的例外:
> python3 test.py
(5,2)
Exception: 6
(7,3)
(8,3)
(9,4)
(10,3)
(11,5)
(12,5)
(13,6)
(14,5)
(15,7)
(16,7)
(17,8)
(18,7)
(19,9)
(20,9)
>
下面是一个参数为200,'red',10的输出示例