我正在使用Numpy在数组上快速执行操作。具体地说,我希望将数组值中的每个位置设置为其所有近邻的平均值,从而有效地使值“扩散”和分散。它的预期用途实际上是模拟视频游戏中气味的行为;数组中的值表示特定对象的气味强度,并且在该对象的位置处,强度设置为每回合100。在
我知道有一些包是为了这个目的而存在的,但是我真的不想引入任何比我必须的更大的依赖性;Numpy有点像在推它!在
不幸的是,我的代码似乎不起作用。这些值完美地“传播”;不幸的是,它们实际上并没有“分散”,而是在不断累积,直到溢出为止。在
代码如下:
#Step 1: Set every object's scent value to its scentstrength at its position, simulating objects emitting scent
#(this also initializes the arrays if they haven't been yet as a side effect since scentmap is a defaultdict)
#Walls don't have smell, which is good 'cos there's a lot of em
scentsimulatedobjects=(theobj for theobj in self.objs if not isinstance(theobj,gameobjs.Wall))
for theobj in scentsimulatedobjects:
thearray=scentmap[theobj]
thearray[tuple(theobj.pos)]=theobj.scentstrength
#Step 2: Make the scents spread. This is done the same way as a simple "blur" effect in image processing;
#we just make every square's scent value the average of all of its neighbors. This is done by convolving the
#array with a blur convolution filter. I'm totally pretending I actually understand this stuff, I really don't.
spreadfactor=0.95
blur=numpy.array([spreadfactor, 1, spreadfactor])
for theobj, thearray in scentmap.items():
for idx, therow in enumerate(thearray):
thearray[idx] = numpy.convolve(therow, blur, "same")
for idx in range(self.size):
thearray[:, idx] = numpy.convolve(thearray[:, idx], blur, "same")
#Step 3: Scale the entire matrix by a decay factor, representing scents losing strength over time once their
#source #leaves
decayfactor=0.5
for theobj, thearray in self.scentmap.items():
thearray*=decayfactor
for x, therow in enumerate(thearray):
for y, scentstrength in enumerate(therow):
if scentstrength < 1:
thearray[x,y]=0
我怎么解决这个问题?在
这是一个从上下文中分离出来的算法的pastebin,因此您可以在不下载整个项目的情况下对其进行破解,这是其中的一部分: http://pastebin.com/gr2E6VWP
目前没有回答
相关问题 更多 >
编程相关推荐