import pygame
import sys

# 窗口基础设置
WIDTH, HEIGHT = 900, 600
FPS = 60

# 地形ID
TERRAIN = {
    0: {"name": "草地", "color": (70, 160, 60)},
    1: {"name": "道路", "color": (130, 110, 90)},
    2: {"name": "水域", "color": (40, 120, 190)},
    3: {"name": "山体", "color": (90, 85, 80)},
}
TERRAIN_LIST = list(TERRAIN.keys())

# 地图参数
GRID_SIZE = 40
MAP_WIDTH = 30
MAP_HEIGHT = 20

# 初始化地图（全部草地0）
game_map = [[0 for _ in range(MAP_WIDTH)] for _ in range(MAP_HEIGHT)]

class Map2D:
    def __init__(self):
        pygame.init()
        self.screen = pygame.display.set_mode((WIDTH, HEIGHT))
        pygame.display.set_caption("二维网格地图编辑器")
        self.clock = pygame.time.Clock()
        self.font = pygame.font.SysFont("SimHei", 16)

        # 视角偏移（平移地图）
        self.offset_x = 0
        self.offset_y = 0
        self.scale = 1.0
        self.current_terrain = 1
        self.drag = False
        self.last_mouse = (0, 0)

    def draw_map(self):
        cell = int(GRID_SIZE * self.scale)
        for y in range(MAP_HEIGHT):
            for x in range(MAP_WIDTH):
                tid = game_map[y][x]
                color = TERRAIN[tid]["color"]
                px = x * cell + self.offset_x
                py = y * cell + self.offset_y
                rect = pygame.Rect(px, py, cell - 1, cell - 1)
                pygame.draw.rect(self.screen, color, rect)

    def screen_to_map(self, mx, my):
        """屏幕坐标转地图格子坐标"""
        cell = GRID_SIZE * self.scale
        gx = int((mx - self.offset_x) / cell)
        gy = int((my - self.offset_y) / cell)
        return gx, gy

    def draw_ui(self):
        info1 = self.font.render(f"当前地形：{TERRAIN[self.current_terrain]['name']}", True, (255,255,255))
        info2 = self.font.render("左键放置 | 右键擦除 | 1/2/3切换地形 | 拖拽平移 | 滚轮缩放", True, (255,255,255))
        self.screen.blit(info1, (10, 10))
        self.screen.blit(info2, (10, 32))

    def run(self):
        while True:
            self.screen.fill((20, 20, 20))
            self.draw_map()
            self.draw_ui()

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()

                # 鼠标按下
                if event.type == pygame.MOUSEBUTTONDOWN:
                    mx, my = pygame.mouse.get_pos()
                    self.last_mouse = (mx, my)
                    # 左键绘制
                    if event.button == 1:
                        gx, gy = self.screen_to_map(mx, my)
                        if 0 <= gx < MAP_WIDTH and 0 <= gy < MAP_HEIGHT:
                            game_map[gy][gx] = self.current_terrain
                    # 右键擦除（恢复草地0）
                    if event.button == 3:
                        gx, gy = self.screen_to_map(mx, my)
                        if 0 <= gx < MAP_WIDTH and 0 <= gy < MAP_HEIGHT:
                            game_map[gy][gx] = 0
                    # 滚轮缩放
                    if event.button == 4:
                        self.scale = min(2.0, self.scale + 0.1)
                    if event.button == 5:
                        self.scale = max(0.4, self.scale - 0.1)

                # 拖拽平移
                if event.type == pygame.MOUSEMOTION and pygame.mouse.get_pressed()[2]:
                    mx, my = pygame.mouse.get_pos()
                    dx = mx - self.last_mouse[0]
                    dy = my - self.last_mouse[1]
                    self.offset_x += dx
                    self.offset_y += dy
                    self.last_mouse = (mx, my)

                # 按键切换地形
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_1:
                        self.current_terrain = 1
                    if event.key == pygame.K_2:
                        self.current_terrain = 2
                    if event.key == pygame.K_3:
                        self.current_terrain = 3
                    # 按P打印地图二维数组
                    if event.key == pygame.K_p:
                        print("=====地图数组=====")
                        for row in game_map:
                            print(row)

            # 持续按住左键连续绘制
            if pygame.mouse.get_pressed()[0]:
                mx, my = pygame.mouse.get_pos()
                gx, gy = self.screen_to_map(mx, my)
                if 0 <= gx < MAP_WIDTH and 0 <= gy < MAP_HEIGHT:
                    game_map[gy][gx] = self.current_terrain

            pygame.display.flip()
            self.clock.tick(FPS)

if __name__ == "__main__":
    editor = Map2D()
    editor.run()