125 lines
2.9 KiB
Python
125 lines
2.9 KiB
Python
|
|
|
|
import pygame
|
|
|
|
from typing import List, Dict
|
|
|
|
|
|
|
|
class RenderTiles:
|
|
|
|
def __init__(self, tile_size: int = 64):
|
|
|
|
self.tile_size = tile_size
|
|
|
|
self.tile_sprites = {}
|
|
|
|
|
|
|
|
def load_tile_sprites(self, asset_manifest: Dict) -> Dict:
|
|
|
|
self.tile_sprites = {}
|
|
|
|
for tile_type, sprite_path in asset_manifest.get('tiles', {}).items():
|
|
|
|
try:
|
|
|
|
sprite = pygame.image.load(sprite_path).convert_alpha()
|
|
|
|
self.tile_sprites[tile_type] = pygame.transform.scale(sprite, (self.tile_size, self.tile_size))
|
|
|
|
except pygame.error:
|
|
|
|
print(f"Failed to load tile sprite: {sprite_path}")
|
|
|
|
self.tile_sprites[tile_type] = self._create_placeholder_tile(tile_type)
|
|
|
|
return self.tile_sprites
|
|
|
|
|
|
|
|
def draw_map(self, surface: pygame.Surface, map_tiles: List[List[Dict]], camera: Dict) -> None:
|
|
|
|
if not map_tiles:
|
|
|
|
return
|
|
|
|
|
|
|
|
camera_x = camera.get('x', 0)
|
|
|
|
camera_y = camera.get('y', 0)
|
|
|
|
zoom = camera.get('zoom', 1.0)
|
|
|
|
|
|
|
|
screen_width = surface.get_width()
|
|
|
|
screen_height = surface.get_height()
|
|
|
|
|
|
|
|
start_col = max(0, int(camera_x // self.tile_size))
|
|
|
|
start_row = max(0, int(camera_y // self.tile_size))
|
|
|
|
end_col = min(len(map_tiles[0]), int((camera_x + screen_width / zoom) // self.tile_size) + 1)
|
|
|
|
end_row = min(len(map_tiles), int((camera_y + screen_height / zoom) // self.tile_size) + 1)
|
|
|
|
|
|
|
|
for row in range(start_row, end_row):
|
|
|
|
for col in range(start_col, end_col):
|
|
|
|
if row < len(map_tiles) and col < len(map_tiles[row]):
|
|
|
|
tile_data = map_tiles[row][col]
|
|
|
|
tile_type = tile_data.get('type', 'grass')
|
|
|
|
sprite = self.tile_sprites.get(tile_type, self._create_placeholder_tile(tile_type))
|
|
|
|
|
|
|
|
screen_x = (col * self.tile_size - camera_x) * zoom
|
|
|
|
screen_y = (row * self.tile_size - camera_y) * zoom
|
|
|
|
|
|
|
|
scaled_sprite = pygame.transform.scale(sprite, (int(self.tile_size * zoom), int(self.tile_size * zoom)))
|
|
|
|
surface.blit(scaled_sprite, (screen_x, screen_y))
|
|
|
|
|
|
|
|
def _create_placeholder_tile(self, tile_type: str) -> pygame.Surface:
|
|
|
|
surface = pygame.Surface((self.tile_size, self.tile_size), pygame.SRCALPHA)
|
|
|
|
color_map = {
|
|
|
|
'grass': (100, 200, 100),
|
|
|
|
'water': (100, 100, 255),
|
|
|
|
'mountain': (150, 150, 150),
|
|
|
|
'forest': (50, 150, 50),
|
|
|
|
'sand': (240, 230, 140)
|
|
|
|
}
|
|
|
|
color = color_map.get(tile_type, (200, 200, 200))
|
|
|
|
surface.fill(color)
|
|
|
|
pygame.draw.rect(surface, (50, 50, 50), surface.get_rect(), 1)
|
|
|
|
return surface
|
|
|