import turtle
import random

# 设置屏幕
screen = turtle.Screen()
screen.title("Python 迷宫游戏")
screen.bgcolor("#f0f0f0")
screen.setup(600, 600)

# 关闭自动刷新，让动画更流畅
screen.tracer(0)

# 迷宫墙画笔
wall = turtle.Turtle()
wall.hideturtle()
wall.speed(0)
wall.pensize(3)
wall.color("black")

# 玩家小球
player = turtle.Turtle()
player.shape("circle")
player.color("red")
player.penup()
player.speed(0)
player.goto(-280, 280)  # 起点在左上角

# 终点
end = turtle.Turtle()
end.shape("square")
end.color("green")
end.penup()
end.goto(260, -260)

# 迷宫格子大小
CELL = 20
GRID_SIZE = 28

# 迷宫地图（1=墙，0=路）
maze = [[1 for _ in range(GRID_SIZE)] for _ in range(GRID_SIZE)]

# 随机生成迷宫（DFS算法）
def generate_maze(x, y):
    maze[y][x] = 0
    directions = [(0, 2), (2, 0), (0, -2), (-2, 0)]
    random.shuffle(directions)
    
    for dx, dy in directions:
        nx, ny = x + dx, y + dy
        if 0 <= nx < GRID_SIZE and 0 <= ny < GRID_SIZE and maze[ny][nx] == 1:
            maze[y + dy//2][x + dx//2] = 0
            generate_maze(nx, ny)

generate_maze(1, 1)

# 画迷宫
def draw_maze():
    for y in range(GRID_SIZE):
        for x in range(GRID_SIZE):
            if maze[y][x] == 1:
                wall.goto(x * CELL - 280, 280 - y * CELL)
                wall.pendown()
                wall.begin_fill()
                for _ in range(4):
                    wall.forward(CELL)
                    wall.right(90)
                wall.end_fill()
                wall.penup()

draw_maze()

# 移动函数
def move(x, y):
    new_x = player.xcor() + x
    new_y = player.ycor() + y
    
    # 检查是否撞墙
    gx = int((new_x + 280) / CELL)
    gy = int((280 - new_y) / CELL)
    if 0 <= gx < GRID_SIZE and 0 <= gy < GRID_SIZE and maze[gy][gx] == 0:
        player.goto(new_x, new_y)
    
    # 到达终点
    if abs(player.xcor() - 260) < 15 and abs(player.ycor() + 260) < 15:
        turtle.write("恭喜通关！", font=("Arial", 30, "bold"), align="center")

# 键盘控制
screen.listen()
screen.onkey(lambda: move(0, CELL), "Up")
screen.onkey(lambda: move(0, -CELL), "Down")
screen.onkey(lambda: move(-CELL, 0), "Left")
screen.onkey(lambda: move(CELL, 0), "Right")

screen.mainloop()