Python 如何从不同的类中生成随机数,而不是从您选择的类中生成随机数';重新使用这些数字
在我的大脑课堂上,我需要不断为我的随机运动设定随机加速度,以改变方向和从我的圆点克隆运动的可能性,但对了,它会生成一个数字,并不断将其添加到我的速度中。简言之,我的圆点是直线运动的。我如何解决这个问题 我没怎么试过,因为我不知道怎么做。我是初学者,所以我不知道具体的代码Python 如何从不同的类中生成随机数,而不是从您选择的类中生成随机数';重新使用这些数字,python,random,pygame,Python,Random,Pygame,在我的大脑课堂上,我需要不断为我的随机运动设定随机加速度,以改变方向和从我的圆点克隆运动的可能性,但对了,它会生成一个数字,并不断将其添加到我的速度中。简言之,我的圆点是直线运动的。我如何解决这个问题 我没怎么试过,因为我不知道怎么做。我是初学者,所以我不知道具体的代码 def wander(self): if self.pos[0] < 5 or self.pos[0] > WIDTH - 5 or self.pos[1] < 5 or self.pos[1]
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()
def漂移(自):
如果self.pos[0]<5或self.pos[0]>宽度-5或self.pos[1]<5或self.pos[1]>高度-5:
self.vel=0
其他:
self.vel=self.vel+acc
self.pos=self.pos+self.vel
#--------------------------------------------------------------------------
#--------------------------------------------------------------------------
班脑:
acc=0.02*np.随机。随机(2)-0.01
#--------------------------------------------------------------------------
点=[]
对于范围(200)内的i:#生成n个单元格
点=点()
点。追加(点)
#--------------------------------------------------------------------------
def mainloop():
尽管如此:
对于pygame.event.get()中的事件:
如果event.type==退出:#如果按X键,退出程序
pygame.quit()#停止pygame
sys.exit()#停止程序
屏幕。填充((0,0,0))#清除屏幕;
对于点中的i:#更新所有点
i、 游荡
i、 画()
pygame.display.update()#更新显示
mainloop()
现在,你正在用一个共享的acc
值初始化你的大脑
类(整个类,甚至不是每个单独的实例)——因此你选择了一个随机数,然后在程序的整个生命周期中使用它,这使得它不是非常随机的。(这一现象的另一个例子是:)
尝试以下方法:
class Brain:
def __init__(self):
self.acc = 0.0
def think(self):
self.acc = 0.02 * np.random.random(2) - 0.01
然后确保在“漫游”开始时或大脑需要自我更新的任何其他时间调用
think()
。如果一个答案适合你,那么“接受”它将向其他人显示这个问题已经得到了回答。:)