import pygame
import sys
import os

# 初始化pygame
pygame.init()
WIDTH, HEIGHT = 800, 500
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Python 简易马里奥")
clock = pygame.time.Clock()
FPS = 60

# 颜色定义
WHITE = (255, 255, 255)
BLUE_SKY = (100, 180, 255)
BROWN_GROUND = (120, 90, 40)
BRICK_COLOR = (180, 70, 30)
MARIO_RED = (255, 0, 0)
MARIO_SKIN = (255, 200, 150)
COIN_YELLOW = (255, 220, 0)

# 马里奥类
class Mario(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.width = 32
        self.height = 48
        self.image = pygame.Surface((self.width, self.height))
        self.image.fill(MARIO_RED)
        pygame.draw.rect(self.image, MARIO_SKIN, (8, 0, 16, 16))
        self.rect = self.image.get_rect()
        self.rect.x = 50
        self.rect.bottom = HEIGHT - 40

        # 物理参数
        self.vx = 0
        self.vy = 0
        self.speed = 5
        self.jump_power = -16
        self.gravity = 0.8
        self.on_ground = False
        self.facing = 1  # 1右 -1左

    def update(self, keys, ground_group, brick_group):
        # 左右移动
        self.vx = 0
        if keys[pygame.K_a] or keys[pygame.K_LEFT]:
            self.vx = -self.speed
            self.facing = -1
        if keys[pygame.K_d] or keys[pygame.K_RIGHT]:
            self.vx = self.speed
            self.facing = 1

        # 跳跃
        if (keys[pygame.K_SPACE] or keys[pygame.K_w]) and self.on_ground:
            self.vy = self.jump_power
            self.on_ground = False

        # 重力
        self.vy += self.gravity

        # 水平移动 + 碰撞
        self.rect.x += self.vx
        self.on_ground = False
        # 地面碰撞
        for ground in ground_group:
            if self.rect.colliderect(ground.rect):
                if self.vy > 0:
                    self.rect.bottom = ground.rect.top
                    self.vy = 0
                    self.on_ground = True
        # 砖块碰撞
        for brick in brick_group:
            if self.rect.colliderect(brick.rect):
                if self.vy > 0:
                    self.rect.bottom = brick.rect.top
                    self.vy = 0
                    self.on_ground = True

        # 竖直移动
        self.rect.y += self.vy

        # 边界限制
        if self.rect.left < 0:
            self.rect.left = 0
        if self.rect.right > WIDTH:
            self.rect.right = WIDTH

# 地面类
class Ground(pygame.sprite.Sprite):
    def __init__(self, x, y, w, h):
        super().__init__()
        self.image = pygame.Surface((w, h))
        self.image.fill(BROWN_GROUND)
        self.rect = self.image.get_rect(x=x, y=y)

# 砖块方块
class Brick(pygame.sprite.Sprite):
    def __init__(self, x, y):
        super().__init__()
        self.image = pygame.Surface((32, 32))
        self.image.fill(BRICK_COLOR)
        pygame.draw.rect(self.image, (100, 40, 10), (2, 2, 28, 28), 2)
        self.rect = self.image.get_rect(x=x, y=y)

# 金币
class Coin(pygame.sprite.Sprite):
    def __init__(self, x, y):
        super().__init__()
        self.image = pygame.Surface((16, 16), pygame.SRCALPHA)
        pygame.draw.circle(self.image, COIN_YELLOW, (8, 8), 8)
        self.rect = self.image.get_rect(center=(x, y))

# 建立精灵组
all_sprites = pygame.sprite.Group()
ground_group = pygame.sprite.Group()
brick_group = pygame.sprite.Group()
coin_group = pygame.sprite.Group()

# 创建马里奥
mario = Mario()
all_sprites.add(mario)

# 生成地面
ground1 = Ground(0, HEIGHT - 40, WIDTH, 40)
ground_group.add(ground1)
all_sprites.add(ground1)

# 摆放砖块（简易关卡布局）
brick_pos = [
    (150, HEIGHT - 100),
    (182, HEIGHT - 100),
    (300, HEIGHT - 150),
    (400, HEIGHT - 180),
    (550, HEIGHT - 120),
    (650, HEIGHT - 200),
]
for pos in brick_pos:
    b = Brick(*pos)
    brick_group.add(b)
    all_sprites.add(b)
    # 砖块上方生成金币
    coin = Coin(pos[0] + 16, pos[1] - 10)
    coin_group.add(coin)
    all_sprites.add(coin)

score = 0
# ========== 修复字体代码 ==========
try:
    # 优先微软雅黑
    font = pygame.font.SysFont("msyh", 24)
except:
    try:
        # 备选黑体
        font = pygame.font.SysFont("heiti", 24)
    except:
        # 兜底系统默认字体，绝对不会报错（中文会变成方框，游戏功能正常）
        font = pygame.font.Font(None, 24)

# 主游戏循环
running = True
while running:
    clock.tick(FPS)
    screen.fill(BLUE_SKY)

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

    keys = pygame.key.get_pressed()
    mario.update(keys, ground_group, brick_group)

    # 吃到金币加分
    hit_coins = pygame.sprite.spritecollide(mario, coin_group, True)
    score += len(hit_coins) * 100

    # 绘制所有元素
    all_sprites.draw(screen)
    # 绘制分数
    score_text = font.render(f"分数：{score}", True, WHITE)
    screen.blit(score_text, (10, 10))

    pygame.display.flip()

pygame.quit()
sys.exit()