Files
mice/units/mine.py
T
enne2 12836dd2d2 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.
2025-10-24 19:13:30 +02:00

65 lines
2.3 KiB
Python

from .unit import Unit
from .bomb import Explosion
from engine.collision_system import CollisionLayer
class Mine(Unit):
def __init__(self, game, position=(0,0), id=None):
super().__init__(game, position, id, collision_layer=CollisionLayer.MINE)
self.speed = 1.0 # Mine doesn't move but needs speed for consistency
self.armed = True # Mine is active and ready to explode
def move(self):
"""Mines don't move, but we need to check for collision with rats each frame."""
pass
def collisions(self):
"""Check if a rat steps on the mine using optimized collision system."""
if not self.armed:
return
# Use collision system to check for rats at mine's position_before
victim_ids = self.game.collision_system.get_units_in_cell(
self.position, use_before=True
)
for victim_id in victim_ids:
rat_unit = self.game.get_unit_by_id(victim_id)
if rat_unit and hasattr(rat_unit, 'sex'): # Check if it's a rat
# Mine explodes and kills the rat
self.explode(rat_unit)
break
def explode(self, victim_rat):
"""Mine explodes, killing the rat and destroying itself."""
if not self.armed:
return
self.game.render_engine.play_sound("POISON.WAV")
# Kill the rat that stepped on the mine
if victim_rat.id in self.game.units:
victim_rat.die(score=5)
# Remove the mine from the game
self.die()
def draw(self):
"""Draw the mine using the mine asset."""
if not self.armed:
return
# Use mine asset
image = self.game.assets["BMP_POISON"]
image_size = self.game.render_engine.get_image_size(image)
# Center the mine in the cell
x_pos = self.position[0] * self.game.cell_size + (self.game.cell_size - image_size[0]) // 2
y_pos = self.position[1] * self.game.cell_size + (self.game.cell_size - image_size[1]) // 2
self.game.render_engine.draw_image(x_pos, y_pos, image, anchor="nw", tag="unit")
def die(self, score=None):
"""Remove mine from game and disarm it."""
self.armed = False
super().die(score)