Python用turtle图形绘制n点星

2024-06-25 23:27:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我的教授要求我们的班级编写一个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起作用

谢谢你的帮助!


Tags: 函数in功能密码fordefrangestar
3条回答

通过使用GCD例程查找coprimes并将失败视为异常,您可以使用相同的代码绘制大多数奇偶尖星:

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

enter image description here

你的公式有点错:

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)`

此代码将绘制任意点数大于5的星。

def star(size, points):
    t.speed(-1)
    t.setheading(0)
    ext = 360 / points

    if points % 2 == 0:
        coords = []
        for a in range(0, points):
            t.penup()
            coords.append(t.pos())
            t.circle(size, ext)
        for b in range(0, len(coords)):
            if b % 2 == 0:
                t.pendown()
                t.goto(coords[b][0], coords[b][1])
            else:
                continue
        t.goto(coords[0][0], coords[0][1])
        t.penup()
        for c in range(0, (len(coords) + 1)):
            if c % 2 != 0:
                t.goto(coords[c][0], coords[c][1])
                t.pendown()
            else:
                continue
        t.goto(coords[1][0], coords[1][1])
    else:
        angle = 180 - (180 / points)
        t.forward(size)
        t.right(angle) 

相关问题 更多 >