Python图绘花

2024-04-18 01:37:48 发布

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

我正在学习用python编程(指thinkpython 2),并对一个程序感到震惊。问题语句:Python program to draw a symmetric flower after seeking the size of and number of petals from user

下面是我编写的代码,只是我无法从数学上正确地计算出每片花瓣之间的夹角(代码接近结束状态的部分)。有人能帮忙吗?

import math
radius=int(input("What is the radius of the flower? "))
petals=int(input("How many petals do you want? "))
#radius=100
#petals=4


def draw_arc(b,r):  #bob the turtle,corner-to-corner length (radius) of petal (assume 60 degree central angle of sector for simplicity)
    c=2*math.pi*r #Circumference of circle
    ca=c/(360/60)  #Circumference of arc (assume 60 degree central angle of sector as above)
    n=int(ca/3)+1  #number of segments
    l=ca/n  #length of segment
    for i in range(n):
        b.fd(l)
        b.lt(360/(n*6))

def draw_petal(b,r):
    draw_arc(b,r)
    b.lt(180-60)
    draw_arc(b,r)

import turtle
bob=turtle.Turtle()

#draw_petal(bob,radius)

for i in range(petals):
    draw_petal(bob,radius)
    bob.lt(360/petals)

turtle.mainloop()

Expected Flower 正确(对称) Incorrect Flower 不正确(不对称)


Tags: ofthetoltforcaintbob
2条回答

我认为这个问题比你做的要简单。

第一个问题是画一片花瓣会改变海龟的方向,你要做的是数学运算,让它回到开始的地方。在这里,我们只需在画花瓣之前记录标题,然后再还原它,不需要计算。

第二个问题是,当turtle可以使用turtle.circle()的extent参数来实现这一点时,您正在实现自己的arc代码,这会产生相同的结果,但速度要快得多:

from turtle import Turtle, Screen

def draw_petal(turtle, radius):
    heading = turtle.heading()
    turtle.circle(radius, 60)
    turtle.left(120)
    turtle.circle(radius, 60)
    turtle.setheading(heading)

my_radius = int(input("What is the radius of the flower? "))
my_petals = int(input("How many petals do you want? "))

bob = Turtle()

for _ in range(my_petals):
    draw_petal(bob, my_radius)
    bob.left(360 / my_petals)

bob.hideturtle()

screen = Screen()
screen.exitonclick()

用法

> python3 test.py
What is the radius of the flower? 100
How many petals do you want? 10

输出

enter image description here

就这样修改代码(在draw_petals中添加b.rt(360/petals-30,并将bob.lt(360/petals)更正为360/4):

import math
radius=int(input("What is the radius of the flower? "))
petals=int(input("How many petals do you want? "))
#radius=100
#petals=4


def draw_arc(b,r):  #bob the turtle,corner-to-corner length (radius) of petal (assume 60 degree central angle of sector for simplicity)
    c=2*math.pi*r #Circumference of circle
    ca=c/(360/60)  #Circumference of arc (assume 60 degree central angle of sector as above)
    n=int(ca/3)+1  #number of segments
    l=ca/n  #length of segment
    for i in range(n):
        b.fd(l)
        b.lt(360/(n*6))


def draw_petal(b,r):
    draw_arc(b,r)
    b.lt(180-60)
    draw_arc(b,r)
    b.rt(360/petals-30)  # this will take care of the correct angle b/w petals


import turtle
bob=turtle.Turtle()
#draw_petal(bob,radius)

for i in range(petals):
    draw_petal(bob,radius)
    bob.lt(360/4)

相关问题 更多 >

    热门问题