如何从不同的类生成随机数,而不是使用这些数字的类

2024-04-25 07:20:00 发布

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

在我的大脑课堂上,我需要不断为我的随机运动设定随机加速度,以改变方向和从我的圆点克隆运动的可能性,但对了,它会生成一个数字,并不断将其添加到我的速度中。简言之,我的圆点是直线运动的。我如何解决这个问题

我没怎么试过,因为我不知道怎么做。我是初学者,所以我不知道具体的代码

def wander(self):
        if self.pos[0] < 5 or self.pos[0] > WIDTH - 5 or self.pos[1] < 5 or self.pos[1] > HEIGHT - 5:
            self.vel = 0
        else:
            self.vel = self.vel + acc
            self.pos = self.pos +self.vel



#--------------------------------------------------------------------------
#--------------------------------------------------------------------------

class brain:
    acc = 0.02 * np.random.random(2) - 0.01



#--------------------------------------------------------------------------

dots = []
for i in range(200): #generate n cells
    Dot = dot()
    dots.append(Dot)

#--------------------------------------------------------------------------

def mainloop():
    while True:
        for event in pygame.event.get():
            if event.type== QUIT: #if pressing the X, quit the program
                pygame.quit() #stop pygame
                sys.exit() #stop the program
        screen.fill((0,0,0)) #clear the screen;
        for i in dots: #update all dots
            i.wander()
            i.draw()
        pygame.display.update() #update display
mainloop()

Tags: ortheinposselfeventforif
1条回答
网友
1楼 · 发布于 2024-04-25 07:20:00

现在,您正在使用单个共享的acc值初始化brain类(整个类,甚至不是每个实例),因此您选择了一个随机数,然后在程序的整个生命周期中使用它,这使得它不是非常随机的(关于这种现象的另一个例子:https://xkcd.com/221/

尝试以下方法:

class Brain:
    def __init__(self):
        self.acc = 0.0

    def think(self):
        self.acc = 0.02 * np.random.random(2) - 0.01

然后确保在wander开始时调用think(),或者大脑需要更新自身的任何其他时间

相关问题 更多 >