import pygame

# ========== 设置 ==========
WINDOW_WIDTH = 960
WINDOW_HEIGHT = 720
TILE_SIZE = 48

# 复杂迷宫地图 0=空地 1=墙
game_map = [
    [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],
    [1,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1],
    [1,0,1,0,1,0,1,1,1,0,1,0,1,1,1,1,1,1,0,1],
    [1,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,1],
    [1,0,1,1,1,1,1,0,1,1,1,1,1,1,1,1,0,1,0,1],
    [1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,1],
    [1,1,1,1,1,0,1,1,1,1,1,1,1,1,0,1,1,1,0,1],
    [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
    [1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1],
    [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
    [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]
]

# 颜色
WALL_COLOR = (140, 140, 140)
FLOOR_COLOR = (210, 210, 210)
PLAYER_COLOR = (100, 150, 255)

# 玩家格子坐标
player_x = 2
player_y = 2

pygame.init()
screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("复杂二维地图｜按键一次移动一格")
clock = pygame.time.Clock()
FPS = 60

def draw_map():
    for row_idx, row in enumerate(game_map):
        for col_idx, cell in enumerate(row):
            px = col_idx * TILE_SIZE
            py = row_idx * TILE_SIZE
            if cell == 1:
                pygame.draw.rect(screen, WALL_COLOR, (px, py, TILE_SIZE-1, TILE_SIZE-1))
            else:
                pygame.draw.rect(screen, FLOOR_COLOR, (px, py, TILE_SIZE-1, TILE_SIZE-1))

def draw_player(px, py):
    sx = px * TILE_SIZE
    sy = py * TILE_SIZE
    pygame.draw.rect(screen, PLAYER_COLOR, (sx+6, sy+6, TILE_SIZE-12, TILE_SIZE-12))

def can_move(nx, ny):
    rows = len(game_map)
    cols = len(game_map[0])
    if 0 <= ny < rows and 0 <= nx < cols:
        if game_map[ny][nx] == 0:
            return True
    return False

running = True
while running:
    screen.fill((0,0,0))

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        # ⭐重点：只有按下一瞬间才移动一格，按住不会一直走
        if event.type == pygame.KEYDOWN:
            dx, dy = 0, 0
            if event.key == pygame.K_w:
                dy = -1
            elif event.key == pygame.K_s:
                dy = 1
            elif event.key == pygame.K_a:
                dx = -1
            elif event.key == pygame.K_d:
                dx = 1
            new_x = player_x + dx
            new_y = player_y + dy
            if can_move(new_x, new_y):
                player_x, player_y = new_x, new_y

    draw_map()
    draw_player(player_x, player_y)
    pygame.display.flip()
    clock.tick(FPS)

pygame.quit()
