61 lines
2.0 KiB
Python
61 lines
2.0 KiB
Python
import pygame
|
|
import math
|
|
from game.config import (
|
|
CELL_SIZE, GRID_COLS, GRID_ROWS, UI_TOP_HEIGHT,
|
|
COLOR_GRASS, COLOR_PATH, COLOR_GRID_LINE,
|
|
PATH_WAYPOINTS,
|
|
)
|
|
|
|
|
|
class GameMap:
|
|
def __init__(self):
|
|
self.path_cells = set()
|
|
self._calc_path_cells()
|
|
|
|
def _calc_path_cells(self):
|
|
for i in range(len(PATH_WAYPOINTS) - 1):
|
|
x1, y1 = PATH_WAYPOINTS[i]
|
|
x2, y2 = PATH_WAYPOINTS[i + 1]
|
|
dx = x2 - x1
|
|
dy = y2 - y1
|
|
dist = math.hypot(dx, dy)
|
|
steps = int(dist / (CELL_SIZE / 2))
|
|
for s in range(steps + 1):
|
|
t = s / max(steps, 1)
|
|
px = x1 + dx * t
|
|
py = y1 + dy * t
|
|
col = int(px // CELL_SIZE)
|
|
row = int((py - UI_TOP_HEIGHT) // CELL_SIZE)
|
|
if 0 <= col < GRID_COLS and 0 <= row < GRID_ROWS:
|
|
self.path_cells.add((col, row))
|
|
|
|
def is_buildable(self, col, row):
|
|
if col < 0 or col >= GRID_COLS or row < 0 or row >= GRID_ROWS:
|
|
return False
|
|
return (col, row) not in self.path_cells
|
|
|
|
def pixel_to_grid(self, px, py):
|
|
col = int(px // CELL_SIZE)
|
|
row = int((py - UI_TOP_HEIGHT) // CELL_SIZE)
|
|
return col, row
|
|
|
|
def grid_to_pixel(self, col, row):
|
|
px = col * CELL_SIZE + CELL_SIZE // 2
|
|
py = row * CELL_SIZE + CELL_SIZE // 2 + UI_TOP_HEIGHT
|
|
return px, py
|
|
|
|
def draw(self, surface):
|
|
for row in range(GRID_ROWS):
|
|
for col in range(GRID_COLS):
|
|
rect = pygame.Rect(
|
|
col * CELL_SIZE,
|
|
row * CELL_SIZE + UI_TOP_HEIGHT,
|
|
CELL_SIZE, CELL_SIZE,
|
|
)
|
|
color = COLOR_PATH if (col, row) in self.path_cells else COLOR_GRASS
|
|
pygame.draw.rect(surface, color, rect)
|
|
pygame.draw.rect(surface, COLOR_GRID_LINE, rect, 1)
|
|
|
|
for i in range(len(PATH_WAYPOINTS) - 1):
|
|
pygame.draw.line(surface, (180, 150, 120), PATH_WAYPOINTS[i], PATH_WAYPOINTS[i + 1], 3)
|