import pygame
import sys
import os

# 初始化pygame
pygame.init()

# 窗口设置
BLOCK_SIZE = 40
MAZE_WIDTH = 15
MAZE_HEIGHT = 12
SCREEN_W = BLOCK_SIZE * MAZE_WIDTH
SCREEN_H = BLOCK_SIZE * MAZE_HEIGHT
screen = pygame.display.set_mode((SCREEN_W, SCREEN_H))
pygame.display.set_caption("迷宫小游戏")

# 颜色定义
WALL_COLOR = (40, 40, 40)
PATH_COLOR = (220, 220, 220)
PLAYER_COLOR = (30, 144, 255)
END_COLOR = (255, 60, 60)

# 迷宫数组 1=墙 0=通路
maze = [
    [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,1],
    [1,0,1,0,1,0,1,1,1,0,1,0,1,0,1],
    [1,0,1,0,0,0,0,0,1,0,0,0,1,0,1],
    [1,0,1,1,1,1,1,0,1,1,1,1,1,0,1],
    [1,0,0,0,0,0,1,0,0,0,0,0,0,0,1],
    [1,1,1,1,1,0,1,1,1,1,1,1,1,0,1],
    [1,0,0,0,0,0,0,0,0,0,0,0,1,0,1],
    [1,0,1,1,1,1,1,1,1,1,1,0,1,0,1],
    [1,0,0,0,0,0,0,0,0,0,1,0,0,0,1],
    [1,0,1,1,1,1,1,1,1,0,1,1,1,0,1],
    [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]
]

# 玩家起始坐标 (格子下标)
player_x = 1
player_y = 1
end_x = 13
end_y = 10

clock = pygame.time.Clock()
# ==========修复字体！不用None，改用系统默认字体名称，规避int类型报错==========
try:
    font = pygame.font.SysFont("simhei", 60)
except:
    font = pygame.font.Font(None,60)


def draw_maze():
    for y in range(MAZE_HEIGHT):
        for x in range(MAZE_WIDTH):
            rect = pygame.Rect(x*BLOCK_SIZE, y*BLOCK_SIZE, BLOCK_SIZE-1, BLOCK_SIZE-1)
            if maze[y][x] == 1:
                pygame.draw.rect(screen, WALL_COLOR, rect)
            else:
                pygame.draw.rect(screen, PATH_COLOR, rect)
    # 终点
    end_rect = pygame.Rect(end_x*BLOCK_SIZE, end_y*BLOCK_SIZE, BLOCK_SIZE-1, BLOCK_SIZE-1)
    pygame.draw.rect(screen, END_COLOR, end_rect)
    # 玩家
    player_rect = pygame.Rect(player_x*BLOCK_SIZE, player_y*BLOCK_SIZE, BLOCK_SIZE-1, BLOCK_SIZE-1)
    pygame.draw.rect(screen, PLAYER_COLOR, player_rect)


def show_win():
    text = font.render("恭喜通关!", True, (255,215,0))
    screen.blit(text,(SCREEN_W//2 - 120, SCREEN_H//2))
    pygame.display.update()
    pygame.time.delay(2000)
    pygame.quit()
    sys.exit()


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

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        # 按键单次移动
        if event.type == pygame.KEYDOWN:
            nx, ny = player_x, player_y
            if event.key == pygame.K_UP:
                ny -= 1
            elif event.key == pygame.K_DOWN:
                ny += 1
            elif event.key == pygame.K_LEFT:
                nx -= 1
            elif event.key == pygame.K_RIGHT:
                nx += 1
            # 判断不是墙壁才可移动
            if maze[ny][nx] == 0:
                player_x, player_y = nx, ny
            # 判断到达终点
            if player_x == end_x and player_y == end_y:
                show_win()

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

pygame.quit()
