Files
mygame/game/map.py
2026-05-20 21:23:46 +08:00

62 lines
2.2 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, waypoints=None, bg_color=None):
self.waypoints = waypoints or PATH_WAYPOINTS
self.bg_color = bg_color or COLOR_GRASS
self.path_cells = set()
self._calc_path_cells()
def _calc_path_cells(self):
for i in range(len(self.waypoints) - 1):
x1, y1 = self.waypoints[i]
x2, y2 = self.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 self.bg_color
pygame.draw.rect(surface, color, rect)
pygame.draw.rect(surface, COLOR_GRID_LINE, rect, 1)
for i in range(len(self.waypoints) - 1):
pygame.draw.line(surface, (180, 150, 120), self.waypoints[i], self.waypoints[i + 1], 3)