import pygame

# 初始化pygame
pygame.init()
# 格子大小
TILE_SIZE = 40
# 严格匹配地图行列数量
MAP_WIDTH = 12   # 每行12个格子
MAP_HEIGHT = 7   # 地图一共7行，改成和列表行数一致
screen = pygame.display.set_mode((MAP_WIDTH * TILE_SIZE, MAP_HEIGHT * TILE_SIZE))
pygame.display.set_caption("二维像素地图")
clock = pygame.time.Clock()

# 7行 × 12列 地图
game_map = [
    [1,1,1,1,1,1,1,1,1,1,1,1],
    [1,2,0,0,1,0,0,0,0,0,0,1],
    [1,0,1,0,1,0,1,1,1,1,0,1],
    [1,0,1,0,0,0,0,0,0,1,0,1],
    [1,0,1,1,1,1,1,1,0,1,0,1],
    [1,0,0,0,0,0,0,0,0,0,0,1],
    [1,1,1,1,1,1,1,1,1,1,1,1]
]

# 颜色
COLOR_WALL = (60,60,60)
COLOR_GROUND = (220,220,220)
COLOR_PLAYER = (255,80,80)

# 查找玩家坐标
def find_player():
    for y in range(MAP_HEIGHT):
        for x in range(MAP_WIDTH):
            if game_map[y][x] == 2:
                return x, y
    return 1,1

player_x, player_y = find_player()
running = True

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

    # 绘制整张地图
    for y in range(MAP_HEIGHT):
        for x in range(MAP_WIDTH):
            rect = pygame.Rect(x*TILE_SIZE, y*TILE_SIZE, TILE_SIZE-2, TILE_SIZE-2)
            if game_map[y][x] == 1:
                pygame.draw.rect(screen, COLOR_WALL, rect)
            else:
                pygame.draw.rect(screen, COLOR_GROUND, rect)

    # 绘制玩家方块
    p_rect = pygame.Rect(player_x*TILE_SIZE, player_y*TILE_SIZE, TILE_SIZE-2, TILE_SIZE-2)
    pygame.draw.rect(screen, COLOR_PLAYER, p_rect)

    # 关闭窗口事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # 方向键控制移动
    keys = pygame.key.get_pressed()
    next_x, next_y = player_x, player_y
    if keys[pygame.K_UP]: next_y -= 1
    if keys[pygame.K_DOWN]: next_y += 1
    if keys[pygame.K_LEFT]: next_x -= 1
    if keys[pygame.K_RIGHT]: next_x += 1

    # 边界+墙体碰撞判断
    if 0 <= next_x < MAP_WIDTH and 0 <= next_y < MAP_HEIGHT:
        if game_map[next_y][next_x] != 1:
            player_x, player_y = next_x, next_y

    pygame.display.flip()
    clock.tick(60)

pygame.quit()