import pygame
import sys

# 初始化pygame
pygame.init()

# 窗口设置
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 400
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("简易马里奥 Pygame")
clock = pygame.time.Clock()
FPS = 60

# 颜色常量
SKY_BLUE = (52, 152, 219)
GROUND_GREEN = (46, 204, 113)
PLATFORM_BROWN = (160, 110, 60)
MARIO_RED = (230, 30, 30)
SKIN = (255, 210, 160)
OVERALL_BLUE = (30, 70, 200)


class Mario:
    def __init__(self):
        self.x = 50
        self.y = 280
        self.w = 32
        self.h = 40
        self.vx = 0
        self.vy = 0
        self.speed = 5
        self.gravity = 0.8
        self.jump_power = -16
        self.on_ground = True
        self.flip = False  # 是否左右翻转

    def update(self, plats):
        # 水平移动
        self.x += self.vx
        if self.vx > 0:
            self.flip = False
        elif self.vx < 0:
            self.flip = True

        # 重力下落
        self.vy += self.gravity
        self.y += self.vy

        # 左右边界限制
        if self.x < 0:
            self.x = 0
        if self.x + self.w > SCREEN_WIDTH:
            self.x = SCREEN_WIDTH - self.w

        # 平台碰撞检测
        self.on_ground = False
        mario_rect = pygame.Rect(self.x, self.y, self.w, self.h)
        for p in plats:
            if mario_rect.colliderect(p):
                # 从上往下落到平台上
                if self.vy > 0 and self.y + self.h - self.vy <= p.y:
                    self.y = p.y - self.h
                    self.vy = 0
                    self.on_ground = True

    def jump(self):
        if self.on_ground:
            self.vy = self.jump_power

    def draw(self, surf):
        # 手绘简易马里奥
        # 帽子
        pygame.draw.rect(surf, MARIO_RED, (self.x, self.y, 32, 12))
        # 脸部
        pygame.draw.rect(surf, SKIN, (self.x + 4, self.y + 12, 24, 12))
        # 上衣
        pygame.draw.rect(surf, MARIO_RED, (self.x + 2, self.y + 24, 28, 10))
        # 背带裤
        pygame.draw.rect(surf, OVERALL_BLUE, (self.x + 4, self.y + 34, 24, 6))


# 平台列表
platforms = [
    pygame.Rect(0, 340, 800, 60),
    pygame.Rect(200, 270, 100, 20),
    pygame.Rect(380, 220, 100, 20),
    pygame.Rect(550, 170, 120, 20),
]

mario = Mario()

# 主循环
while True:
    clock.tick(FPS)
    screen.fill(SKY_BLUE)

    # 事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                mario.jump()

    # 按键控制左右
    keys = pygame.key.get_pressed()
    mario.vx = 0
    if keys[pygame.K_a] or keys[pygame.K_LEFT]:
        mario.vx = -mario.speed
    if keys[pygame.K_d] or keys[pygame.K_RIGHT]:
        mario.vx = mario.speed

    mario.update(platforms)

    # 画平台
    for p in platforms:
        pygame.draw.rect(screen, PLATFORM_BROWN, p)

    mario.draw(screen)

    pygame.display.update()
