[英]Python draw n-pointed star with turtle graphics
我的教授讓我們班寫了一個 Python 函數,它的作用如下:
在名為 star(turtle, n, d) 的函數中繪制一個帶 d 邊的常規 n 尖星
這是我到目前為止的代碼:
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。
感謝您的幫助!
通過使用 GCD 例程查找互質並將失敗視為異常,您可以使用相同的代碼繪制大多數奇數和偶數尖星:
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 的輸出示例
這段代碼將繪制一個點數大於 5 的星星。它有兩個參數: n
是頂點數, size
控制海龜步數的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)
(偶數):
我的教授讓我們班寫了一個 Python 函數,它的作用如下:
在名為 star(turtle, n, d) 的函數中繪制一個帶 d 邊的規則 n 尖星
這是我到目前為止的代碼:
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。
感謝您的幫助!
你的公式有點錯誤:
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)`
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.