我在一个项目中使用Numpy和Python,其中2D地图由ndarray
表示:
map = [[1,2,3,4,5],
[2,3,4,2,3],
[2,2,2,1,2],
[3,2,1,2,3],
[4,6,5,7,4]]
MAP_WIDTH = 5, MAP_HEIGHT = 5
对象具有元组位置:
actor.location = (3,3)
和视图范围:
actor.range = 2
如何编写函数actor.view_map(map)
,以便地图返回演员位置周围的区域到一个范围。例如(使用上面的地图),
range = 1
location = (3, 2)
=>
[[2,3,4],
[3,4,2],
[2,2,1]]
但如果演员的范围延伸太远,我希望地图填充-1:
range = 1
location = (1,1)
[[-1,-1,-1],
[-1, 1, 2],
[-1, 2, 3]]
最简单的情况是0的范围,它返回当前的正方形:
range = 0
location = (1, 2)
[[2]]
如何将地图切割到某个边界?
答案 0 :(得分:4)
所以,多亏了Joe Kington,我在地图周围添加了一个边框(填充-1s)。
我是这样做的,但这可能不是非常Pythonic,因为我刚开始使用语言/库:
map = numpy.random.randint(10, size=(2 * World.MAP_WIDTH, 2 * World.MAP_HEIGHT))
map[0 : World.MAP_WIDTH / 4, :] = -1
map[7 * World.MAP_WIDTH / 4 : 2 * World.MAP_WIDTH, :] = -1
map[:, 0 : World.MAP_HEIGHT / 4] = -1
map[:, 7 * World.MAP_HEIGHT / 4 : 2 * World.MAP_WIDTH] = -1
答案 1 :(得分:2)
这是一个小课程Box
,可以更轻松地使用方框 -
from __future__ import division
import numpy as np
class Box:
""" B = Box( 2d numpy array A, radius=2 )
B.box( j, k ) is a box A[ jk - 2 : jk + 2 ] clipped to the edges of A
@askewchan, use np.pad (new in numpy 1.7):
padA = np.pad( A, pad_width, mode="constant", edge=-1 )
B = Box( padA, radius )
"""
def __init__( self, A, radius ):
self.A = np.asanyarray(A)
self.radius = radius
def box( self, j, k ):
""" b.box( j, k ): square around j, k clipped to the edges of A """
return self.A[ self.box_slice( j, k )]
def box_slice( self, j, k ):
""" square, jk-r : jk+r clipped to A.shape """
# or np.clip ?
r = self.radius
return np.s_[ max( j - r, 0 ) : min( j + r + 1, self.A.shape[0] ),
max( k - r, 0 ) : min( k + r + 1, self.A.shape[1] )]
#...............................................................................
if __name__ == "__main__":
A = np.arange(5*7).reshape((5,7))
print "A:\n", A
B = Box( A, radius=2 )
print "B.box( 0, 0 ):\n", B.box( 0, 0 )
print "B.box( 0, 1 ):\n", B.box( 0, 1 )
print "B.box( 1, 2 ):\n", B.box( 1, 2 )