這裏是多邊形的函數:
def drawPolygon (ttl, x, y, num_side, radius):
sideLen = 2 * radius * math.sin (math.pi/num_side)
angle = 360/num_side
ttl.penup()
ttl.goto (x, y)
ttl.pendown()
for iter in range (num_side):
ttl.forward (sideLen)
ttl.left (angle)
這裏是你如何使用它:
def main():
# put label on top of page
turtle.title ('Figures')
# setup screen size
turtle.setup (800, 800, 0, 0)
# create a turtle object
ttl = turtle.Turtle()
# draw equilateral triangle
ttl.color ('blue')
drawPolygon (ttl, -200, 0, 3, 50)
# draw square
ttl.color ('red')
drawPolygon (ttl, -50, 0, 4, 50)
# draw pentagon
ttl.color ('forest green')
drawPolygon (ttl, 100, 0, 5, 50)
# draw octagon
ttl.color ('DarkOrchid4')
drawPolygon (ttl, 250, 0, 8, 50)
# persist drawing
turtle.done()
main()
不要忘記添加import turtle, math
不應該是polygon be turtle.polygon? – OldBunny2800
不幸的是我也試過,我得到了錯誤「AttributeError:模塊'烏龜'沒有屬性'多邊形'」 –
似乎你正在做一個教程。你能包含鏈接嗎? – combinatorist