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()
解决方案
现在,您正在brain
使用单个共享acc
值初始化您的类(整个类,甚至不是每个实例)——因此您选择一个随机数,然后在程序的整个生命周期中使用它,这使得它不会非常随机。(此现象的另一个例子: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
然后确保think()
在开始时调用wander
,或者在大脑需要自我更新的任何其他时间调用。
推荐阅读
- python - 获取 asyncio.Queue 中的所有项目并返回它们
- spring-boot - 从 PCF 连接发布/订阅的问题
- java - Maven 尝试在“验证”阶段下载多模块依赖项
- spotfire - 根据文档属性下拉选择显示垂直直线
- javascript - 根据 Vega 条形图中的图形值显示多色
- reporting-services - SSRS 附加到组的值的总和
- python - 列表中的单引号
- java - Java 服务器套接字未连接
- tensorflow - CNN 中 5 倍交叉验证的准确率差异很大的可能原因是什么?
- mysql - 将 InnoDB 表复制到 FEDERATED 表中