随机化0到2pi之间的角度时的错误(程序也会因长绘图循环而停止响应)

时间:2016-03-12 20:51:25

标签: python random pygame

我正在尝试编写一个小程序来说明使用pygame在二维星中使用光子的平均自由路径的想法。我是python的新手(这是我玩python的第8周)并且刚刚开始在pygame中进行实验。

基本上我的程序应该做的是在圆心开始有一条线,并在它变成一个随机数量的弧度之前移动一些长度'l'然后再移动另一个长度'l'并重复这个直到它击中圆圈的边缘。

我在角度随机化方面遇到了问题。目前我已经在0到2pi之间使用了random.uniform(),但我注意到这条线每次都喜欢几乎直线向下。任何有关此问题的帮助或建议都将不胜感激。

第15行是我定义用于下一行的角度的地方,我也注意到如果我的路径长度'l'足够低,程序将在完成之前停止响应。我确信有一个简单的解释,我只是没有意识到,但如果有人知道为什么我可能会想知道。

编辑:schwobaseggl指出了第一个问题,我在第16行的y坐标中写了一个错误的变量。我仍然没有弄清楚为什么程序在绘制之后停止响应虽然。

到目前为止我的代码:

import pygame
import random
import math

def mfp():
    Rho = float(input('Enter average density: '))
    K = float(input('Enter opacity: '))
    l = 1/(K * Rho)
    return l

def line(l, screen):
    a = [250, 250]
    n = 0
    while ((a[0]-250)**2)+((a[1]-250)**2) < 220**2:
        ang = random.uniform(0, 2*math.pi)
        print(ang)
        #changed sin(l) to sin(ang)
        b = [a[0]+l*math.cos(ang), a[1]+l*math.sin(ang)]
        pygame.draw.line(screen, [255, 255, 255], a, b, 1)
        a = b
        pygame.display.flip()
        print('2') #debug

def vis():
    size = [500, 500]
    screen = pygame.display.set_mode(size)
    pygame.draw.circle(screen, [255, 255, 255], [250, 250], 220)
    pygame.draw.circle(screen, [0, 0, 0], [250, 250], 219)
    pygame.display.flip()
    print('1') #debug
    return screen


def stop():
    done = False
    while not done:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True
    pygame.quit()



def main():
    line(mfp(), vis())
    stop()

main()

1 个答案:

答案 0 :(得分:2)

问题在于这一行:

b = [a[0]+l*math.cos(ang), a[1]+l*math.sin(l)]

当然,你想要math.sin(ang)