Spaces:
Sleeping
Sleeping
| """ | |
| Building Entity with Collision Detection | |
| """ | |
| from dataclasses import dataclass, field | |
| from enum import Enum | |
| from config import BUILDING_BASE_SIZE, BUILDING_MIN_DISTANCE | |
| from .enums import ItemType | |
| class BuildingType(Enum): | |
| HOUSE = "house" | |
| STORAGE = "storage" | |
| WORKSHOP = "workshop" | |
| TOWNHALL = "townhall" | |
| class Building: | |
| id: int | |
| x: float | |
| y: float | |
| building_type: BuildingType | |
| level: int | |
| sprite: object | |
| storage: dict = field(default_factory=lambda: {ItemType.FOOD.value: 0, ItemType.WOOD.value: 0}) | |
| max_storage: int = 50 | |
| def get_size(self) -> int: | |
| """Get building size based on type and level""" | |
| base = BUILDING_BASE_SIZE | |
| if self.building_type == BuildingType.TOWNHALL: | |
| base = 80 | |
| return base + (self.level - 1) * 8 | |
| def get_collision_radius(self) -> float: | |
| """Get collision radius for this building""" | |
| return self.get_size() / 2 + 10 # Add 10px padding | |
| def store_resource(self, resource_type: str, amount: int) -> int: | |
| """Store resources, return amount actually stored""" | |
| current = self.storage.get(resource_type, 0) | |
| can_store = min(amount, self.max_storage - current) | |
| self.storage[resource_type] = current + can_store | |
| return can_store | |
| def upgrade(self): | |
| """Upgrade building""" | |
| if self.level < 3: | |
| self.level += 1 | |
| self.max_storage += 25 | |
| # Sprite will be regenerated by world | |
| def check_collision(x: float, y: float, existing_buildings: list, new_type: BuildingType) -> bool: | |
| """Check if position collides with existing buildings""" | |
| from rendering.sprite_generator import SpriteGenerator | |
| # Get size of new building | |
| temp_size = BUILDING_BASE_SIZE | |
| if new_type == BuildingType.TOWNHALL: | |
| temp_size = 80 | |
| new_radius = temp_size / 2 | |
| for building in existing_buildings: | |
| dx = building.x - x | |
| dy = building.y - y | |
| distance = (dx**2 + dy**2) ** 0.5 | |
| # Check if too close | |
| min_dist = building.get_collision_radius() + new_radius + BUILDING_MIN_DISTANCE | |
| if distance < min_dist: | |
| return True # Collision detected | |
| return False # No collision | |