用Python绘制一个给定循环数的旋风?

2024-05-16 04:38:06 发布

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

我好像不能用输入的循环次数来画旋风。该代码应该让用户点击一个开始和结束点,然后将绘制一个旋风分离器,输入从起点到终点的循环。在

from math import *
from graphics import *

def main():
    win = GraphWin("Drawing a Cyclone",600,450)            
    win.setCoords(0,0,600,450)                             
    msg = "Please enter the number of cycles, and click the start and end positions in the window."
    Text(Point(300, 438), msg).draw(win)
    Text(Point(65,415),"# of cycles:").draw(win)
    inbox =Entry(Point(130,415),5)
    inbox.draw(win)


    start=win.getMouse()
    start.setFill("red")
    start.draw(win)
    stop=win.getMouse()
    stop.setFill("red")
    stop.draw(win)

    cycles=eval(inbox.getText())
    radius = 0                                                 
    length = sqrt((stop.x-start.x)**2+(stop.y-start.y)**2)  
    step_radius = length / (120*cycles)
    radian = atan((stop.y-start.y)/(stop.x-start.x))
    initial_angle = int(degrees(radian))

    for i in (0, cycles*360, 3):
        radius = radius + step_radius
        theta=radians(initial_angle + (360*cycles*i)+3*i)
        stop.x = start.x + radius*cos(theta)
        stop.y = start.y + radius*sin(theta)
        line=Line(start,stop)
        line.draw(win)
        start.x=stop.x
        start.y=stop.y


    win.getMouse()
    win.close()

main()

This is what I'm getting

This is what I'm supposed to get


Tags: thefromimportmainstartwinpointstop
1条回答
网友
1楼 · 发布于 2024-05-16 04:38:06

我认为你的大部分问题都集中在以下代码上:

theta=radians(initial_angle + (360*cycles*i)+3*i)
stop.x = start.x + radius*cos(theta)
stop.y = start.y + radius*sin(theta)

i变量已经在跟踪圆了,因此theta应该是i的弧度等价物,并对初始角度进行了调整,但是您已经用i做了很多额外的数学运算。另外,停止位置应该是cos()sin()计算的函数,修正了图形的原点,但使用了start,它最初是原点,但在循环中是一个移动的目标。在

进行调试的一种方法是将循环设置为1并设置radius = length而不是{}。这将给你一个简单的圆,以解决正确的定位,半径等问题,而不会增加螺旋的复杂性。然后再加上螺旋线。在

沿着这些思路,你可能会得到一些解决办法:

^{pr2}$

在某些象限中,初始角度的正确性仍然存在问题,但这是可以解决的问题。另外,如果您单击正确的点,您可以生成一个除以零的除法,因此您也需要处理这个问题:

enter image description here

请注意,尽管from graphics import *通常是这样做的,from math import *风险更大,例如,math.pow()覆盖了Python的内置{},两者并不相同。考虑进口更安全。在

相关问题 更多 >