Files
plateformer-evolve/game/map.py
T

82 lines
2.5 KiB
Python

"""
Represent a map in the game.
Contains the map data :
- Map name
- Map width and height
- Map difficulty
- The map layout (2D array of blocks)
"""
from game.blocks.block import Block
class Map:
def __init__(self, map_data: dict):
self.name = map_data.get('name', 'Unknown')
self.difficulty = float(map_data.get('difficulty', 0.0))
self.min_moves = map_data.get('min_moves', None)
self.layout = map_data.get('layout', [])
self.width = max(len(row) for row in self.layout) if self.layout else 0
self.height = len(self.layout) if self.layout else 0
def get_block_at(self, x, y) -> Block | None:
if 0 <= x < self.width and 0 <= y < self.height:
return self.layout[y][x]
return None
def is_position_in_bounds(self, position):
x, y = position
return 0 <= x < self.width and 0 <= y < self.height
def get_first_block_type_position(self, block_type):
for y in range(self.height):
for x in range(self.width):
block = self.get_block_at(x, y)
if block and block.type == block_type:
return (x, y)
return None
def count_blocks_of_type(self, block_type):
return sum(
block is not None and block.type == block_type
for row in self.layout
for block in row
)
def get_block_type_at_position(self, position):
x, y = position
block = self.get_block_at(x, y)
if block:
return block.type
return None
def get_min_moves(self):
return self.min_moves
def to_string_dict(self):
"""
Returns a string matrix representation of the map layout.
"""
string_array = []
for row in self.layout:
string_array_row = []
for block in row:
if block is None:
string_array_row.append(" ")
else:
string_array_row.append(block.to_string())
string_array.append(string_array_row)
return string_array
def to_type_dict(self):
"""Returns a matrix containing block types and None for empty spaces."""
return [
[self._visible_block_type(block) for block in row]
for row in self.layout
]
@staticmethod
def _visible_block_type(block):
if block is None or getattr(block, "collected", False):
return None
return block.type