Files
mice/units/unit.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

74 lines
2.2 KiB
Python

from abc import ABC, abstractmethod
import uuid
class Unit(ABC):
"""
Abstract base class for all game units.
Attributes
----------
id : UUID
Unique identifier for the unit.
game : Game
Reference to the main game object.
position : tuple
The current position of the unit (x, y).
position_before : tuple
The position of the unit before the last update.
age : int
The age of the unit in game ticks.
speed : float
Movement speed of the unit.
partial_move : float
Partial movement progress for smooth animation.
bbox : tuple
Bounding box for collision detection (x1, y1, x2, y2).
stop : int
Number of ticks to remain stationary.
collision_layer : int
Collision layer for the optimized collision system.
Methods
-------
move()
Update unit position and state (must be implemented by subclasses).
draw()
Render the unit on screen (must be implemented by subclasses).
collisions()
Handle collisions with other units (optional override).
die()
Remove unit from game and handle cleanup.
"""
def __init__(self, game, position=(0, 0), id=None, collision_layer=0):
"""Initialize a unit with game reference and position."""
self.id = id if id else uuid.uuid4()
self.game = game
self.position = position
self.position_before = position
self.age = 0
self.speed = 1.0
self.partial_move = 0
self.bbox = (0, 0, 0, 0)
self.stop = 0
self.collision_layer = collision_layer
@abstractmethod
def move(self):
"""Update unit position and state. Must be implemented by subclasses."""
pass
@abstractmethod
def draw(self):
"""Render the unit on screen. Must be implemented by subclasses."""
pass
def collisions(self):
"""Handle collisions with other units. Default implementation does nothing."""
pass
def die(self, score=None):
"""Remove unit from game and handle basic cleanup."""
if self.id in self.game.units:
self.game.units.pop(self.id)