# mario_game/game.py
import pygame
import sys
import random

def run():
    # 初始化
    pygame.init()
    screen = pygame.display.set_mode((800, 400))
    pygame.display.set_caption("我的超级玛丽小游戏")
    clock = pygame.time.Clock()

    # 颜色
    SKY = (135, 206, 235)
    GROUND = (139, 69, 19)
    RED = (255, 0, 0)
    BLUE = (0, 0, 255)

    # 玩家
    player_size = 40
    player_x = 50
    player_y = 300
    player_speed = 5
    jump_speed = 15
    gravity = 0.8
    velocity_y = 0
    is_jump = False

    # 障碍物
    obstacle_x = 700
    obstacle_y = 320
    obstacle_w = 30
    obstacle_h = 50
    obstacle_speed = 4

    score = 0
    # 加载支持中文的字体（如果没有这个字体，会自动回退到系统默认）
    font = pygame.font.SysFont(["SimHei", "Microsoft YaHei", "WenQuanYi Micro Hei"], 40)

    # 游戏主循环
    running = True
    while running:
        screen.fill(SKY)

        # 地面
        pygame.draw.rect(screen, GROUND, (0, 360, 800, 40))

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

        # 按键
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT] and player_x > 0:
            player_x -= player_speed
        if keys[pygame.K_RIGHT] and player_x < 800 - player_size:
            player_x += player_speed
        if keys[pygame.K_SPACE] and not is_jump:
            is_jump = True
            velocity_y = -jump_speed

        # 跳跃 & 重力
        if is_jump:
            velocity_y += gravity
            player_y += velocity_y
            if player_y >= 300:
                player_y = 300
                is_jump = False
                velocity_y = 0

        # 障碍物移动
        obstacle_x -= obstacle_speed
        if obstacle_x < -50:
            obstacle_x = 800 + random.randint(0, 200)
            score += 1

        # 绘制
        pygame.draw.rect(screen, RED, (player_x, player_y, player_size, player_size))
        pygame.draw.rect(screen, BLUE, (obstacle_x, obstacle_y, obstacle_w, obstacle_h))

        # 分数（中文）
        score_text = font.render(f"分数: {score}", True, (0, 0, 0))
        screen.blit(score_text, (20, 20))

        # 碰撞
        player_rect = pygame.Rect(player_x, player_y, player_size, player_size)
        obs_rect = pygame.Rect(obstacle_x, obstacle_y, obstacle_w, obstacle_h)
        if player_rect.colliderect(obs_rect):
            over = font.render("游戏结束!", True, (255, 0, 0))
            screen.blit(over, (350, 150))
            pygame.display.update()
            pygame.time.delay(1000)
            running = False

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

    pygame.quit()
    sys.exit()