CELL_SIZE = 80
class EnemyGrid:
def __init__(self): # 存储每个格子里有哪些敌人,便于快速查询 self.grid = {} # {(gx, gy): [enemy, ...]}
# 每帧重建敌人网格 def build(self, enemies):
self.grid.clear()
for e in enemies: gx = int(e["x"] // CELL_SIZE) gy = int(e["y"] // CELL_SIZE) key = (gx, gy) if key not in self.grid: self.grid[key] = [] self.grid[key].append(e)
# 获取子弹周围格子内的敌人,radius=0只查当前格 # 比如radius传80,那就是周围2格的敌人, def get_nearby(self, x, y, radius=None):
if radius is None: radius = CELL_SIZE
cells = max( 1, int(radius // CELL_SIZE) + 1 )
cx = int(x // CELL_SIZE) cy = int(y // CELL_SIZE)
result = []
for dx in range(-cells, cells + 1): for dy in range(-cells, cells + 1):
key = (cx + dx, cy + dy)
if key in self.grid: result.extend(self.grid[key])
return result
# 横线和竖线都可以统一成矩形 # ---------------- # y # ---------------- # rect = pygame.Rect(0,y - 20,settings.width,40) def query_rect(self, rect):
result = []
start_x = int(rect.left // CELL_SIZE) end_x = int(rect.right // CELL_SIZE)
start_y = int(rect.top // CELL_SIZE) end_y = int(rect.bottom // CELL_SIZE)
for gx in range(start_x, end_x + 1): for gy in range(start_y, end_y + 1): key = (gx, gy) if key in self.grid: result.extend(self.grid[key])
return result
|