Implement optimized collision detection system using NumPy

- Introduced a hybrid collision detection approach that utilizes NumPy for vectorized operations, improving performance for games with many entities (200+).
- Added a spatial grid for efficient lookups and AABB (Axis-Aligned Bounding Box) collision detection.
- Implemented a new `CollisionSystem` class with methods for registering units, checking collisions, and managing spatial data.
- Created performance tests to benchmark the new collision system against the old O(n²) method, demonstrating significant speed improvements.
- Updated existing code to integrate the new collision detection system and ensure compatibility with game logic.
This commit is contained in:
John Doe
2025-10-24 19:13:30 +02:00
parent 47028c95ae
commit 12836dd2d2
17 changed files with 1591 additions and 64 deletions
+39 -18
View File
@@ -1,6 +1,7 @@
from .unit import Unit
from . import rat
from .points import Point
from engine.collision_system import CollisionLayer
import uuid
import random
@@ -11,7 +12,7 @@ NUCLEAR_TIMER = 50 # 1 second at ~50 FPS
class Bomb(Unit):
def __init__(self, game, position=(0,0), id=None):
super().__init__(game, position, id)
super().__init__(game, position, id, collision_layer=CollisionLayer.BOMB)
# Specific attributes for bombs
self.speed = 4 # Bombs age faster
self.fight = False
@@ -50,7 +51,7 @@ class Timer(Bomb):
self.die()
def die(self, unit=None, score=None):
"""Handle bomb explosion and chain reactions."""
"""Handle bomb explosion and chain reactions using vectorized collision system."""
score = 10
print("BOOM")
target_unit = unit if unit else self
@@ -65,24 +66,16 @@ class Timer(Bomb):
# Bomb-specific behavior: create explosion
self.game.spawn_unit(Explosion, target_unit.position)
# Collect all explosion positions using vectorized approach
explosion_positions = []
# Check for chain reactions in all four directions
for direction in ["N", "S", "E", "W"]:
x, y = target_unit.position
while True:
if not self.game.map.is_wall(x, y):
self.game.spawn_unit(Explosion, (x, y))
for victim in self.game.unit_positions.get((x, y), []):
if victim.id in self.game.units:
if victim.partial_move >= 0.5:
victim.die(score=score)
if score < 160:
score *= 2
for victim in self.game.unit_positions_before.get((x, y), []):
if victim.id in self.game.units:
if victim.partial_move < 0.5:
victim.die(score=score)
if score < 160:
score *= 2
explosion_positions.append((x, y))
else:
break
if direction == "N":
@@ -93,12 +86,40 @@ class Timer(Bomb):
x += 1
elif direction == "W":
x -= 1
# Create all explosions at once
for pos in explosion_positions:
self.game.spawn_unit(Explosion, pos)
# Use optimized collision system to get all rats in explosion area
# This replaces the nested loop with a single vectorized operation
victim_ids = self.game.collision_system.get_units_in_area(
explosion_positions,
layer_filter=CollisionLayer.RAT
)
# Kill all victims with score multiplier
for victim_id in victim_ids:
victim = self.game.get_unit_by_id(victim_id)
if victim and victim.id in self.game.units:
# Determine position based on partial_move
victim_pos = victim.position if victim.partial_move >= 0.5 else victim.position_before
if victim_pos in explosion_positions:
victim.die(score=score)
if score < 160:
score *= 2
class Explosion(Bomb):
def __init__(self, game, position=(0,0), id=None):
# Initialize with proper EXPLOSION layer
Unit.__init__(self, game, position, id, collision_layer=CollisionLayer.EXPLOSION)
self.speed = 20 # Bombs age faster * 5
self.fight = False
def move(self):
self.age += self.speed*5
if self.age == AGE_THRESHOLD:
self.age += self.speed
if self.age >= AGE_THRESHOLD:
self.die()
def draw(self):
@@ -114,7 +135,7 @@ class Explosion(Bomb):
class NuclearBomb(Unit):
def __init__(self, game, position=(0,0), id=None):
super().__init__(game, position, id)
super().__init__(game, position, id, collision_layer=CollisionLayer.BOMB)
self.speed = 1 # Slow countdown
self.fight = False
self.timer = NUCLEAR_TIMER # 1 second timer