到目前为止,我一直在将数组与单个变量进行比较,例如播放器的位置:
for position in ships:
if player_location_x > position[0]-100 and player_location_x < position[0]+100 and player_location_y > position[1]-100 and player_location_y < position[1]+100:
#Do something (e.g. draw bullets between the two locations)我如何将其扩展到比较数组本身的值,例如比较“船舶”的x值和y值,以检查它们之间的距离,以及比较“船只”和“多船”之间的x和y值?
ships = numpy.array([
[
shuttle_class.npc_x[0],
shuttle_class.npc_y[0],
shuttle_class.img,
shuttle_class.hp
],
[
shuttle_class.npc_x[1],
shuttle_class.npc_y[1],
shuttle_class.img,
shuttle_class.hp
],
[
shuttle_class.npc_x[2],
shuttle_class.npc_y[2],
shuttle_class.img,
shuttle_class.hp
]
])
more_ships = numpy.array([
[
shuttle_class.npc_x[3],
shuttle_class.npc_y[3],
shuttle_class.img,
shuttle_class.hp
],
[
shuttle_class.npc_x[4],
shuttle_class.npc_y[4],
shuttle_class.img,
shuttle_class.hp
],
[
shuttle_class.npc_x[5],
shuttle_class.npc_y[5],
shuttle_class.img,
shuttle_class.hp
]
])发布于 2016-12-30 11:16:40
让我们从两个用于船只的数组x1, y1开始。您希望使用x2, y2生成每个成对的距离。为了讨论起见,假设您有5艘船和3艘more_ships。所以我们使用numpy网格:
xx1, xx2 = np.meshgrid(x1, x2) # both these are 3x5 arrays
yy1, yy2 = np.meshgrid(y1, y2)
dx = xx1 - xx2 # np.abs(xx1 - xx2) if you want just absolute values
dy = yy1 - yy2现在您可以使用np.where获得最终列表:
sel = np.where( (dx <= d_max) & (dy <= d_max) )sel是一个2xn数组。这些值是满足条件的n点的指标。
编辑:根据OP.的要求添加示例代码
import matplotlib.pyplot as plt
import numpy as np
sx = np.array([0, 250, 500])
sy = np.array([100, 100, 100])
mx = np.array([1000, 0])
my = np.array([0,0])
plt.scatter(sx, sy)
plt.scatter(mx, my, c='r', marker='o')
plt.grid()我们有三艘船(s)和两艘more_ships (m)。
xx1, xx2 = np.meshgrid(sx, mx)
yy1, yy2 = np.meshgrid(sy, my)让我们看一下这一点:np.shape(xx1)是(2,3)。第一个索引引用m (更多的船只),第二个索引引用s。
dx = np.abs(xx1 - xx2)
dy = np.abs(yy1 - yy2)
d_max = 200.0
sel = np.where( (dx <= d_max) & (dy <= d_max) )
print sel您将看到sel有两个数组。第一个数组引用第一个轴(m)的索引,第二个引用(s)。在这种情况下,数组的值为1和0,这意味着more_ships[1]位于ships[0]的200个像素以内。
如果您将sx更改为np.array([0, 250, 1000]),那么sel将是array([0, 1]), array([2, 0]) --这意味着more_ships[0]在ships[2]的200像素以内,more_ships[1]在ships[0]附近。
https://stackoverflow.com/questions/41394631
复制相似问题