import pygame
import sys
import random

pygame.init()
WIDTH, HEIGHT = 800, 500
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("横版跑酷小游戏")
clock = pygame.time.Clock()
FPS = 60

# 颜色
WHITE = (255,255,255)
SKY = (135,206,235)
BROWN = (120,70,20)
RED = (255,30,30)
GREEN = (20,180,20)

# 中文字体兼容Windows
try:
    font = pygame.font.Font("C:/Windows/Fonts/simhei.ttf",32)
except:
    font = pygame.font.Font(None,32)

# 玩家参数
player_x = 80
player_y = 350
ply_w, ply_h = 40,60
vy = 0
gravity = 0.8
jump_power = -18
on_ground = True

# 地面
ground_y = 420

# 障碍物
obs_list = []
obs_speed = 6
spawn_cd = 0
obs_w, obs_h = 35,55

score = 0
game_over = False

def spawn_obs():
    x = WIDTH + random.randint(30,120)
    y = ground_y - obs_h
    obs_list.append([x,y])

running = True
while running:
    dt = clock.tick(FPS)/1000
    screen.fill(SKY)
    # 事件
    for e in pygame.event.get():
        if e.type == pygame.QUIT:
            running = False
        if e.type == pygame.KEYDOWN:
            # 空格跳跃
            if e.key == pygame.K_SPACE and on_ground and not game_over:
                vy = jump_power
                on_ground = False
            # R重新开局
            if e.key == pygame.K_r and game_over:
                # 重置数据
                player_y = 350
                vy = 0
                obs_list.clear()
                score = 0
                obs_speed =6
                game_over = False

    if not game_over:
        # 重力
        vy += gravity
        player_y += vy
        # 落地判定
        if player_y+ply_h >= ground_y:
            player_y = ground_y - ply_h
            vy =0
            on_ground = True

        # 生成障碍物
        spawn_cd +=1
        if spawn_cd > random.randint(70,120):
            spawn_obs()
            spawn_cd =0

        # 移动障碍+计分
        for ob in obs_list:
            ob[0] -= obs_speed
        # 清除出屏幕障碍、加分
        for idx in range(len(obs_list)-1,-1,-1):
            if obs_list[idx][0]+obs_w <0:
                obs_list.pop(idx)
                score +=1
        # 提速
        obs_speed = min(obs_speed+dt*0.15,12)

        # 碰撞检测
        p_rect = pygame.Rect(player_x,player_y,ply_w,ply_h)
        for ox,oy in obs_list:
            o_rect = pygame.Rect(ox,oy,obs_w,obs_h)
            if p_rect.colliderect(o_rect):
                game_over = True

    # 绘制地面
    pygame.draw.rect(screen,BROWN,(0,ground_y,WIDTH,80))
    # 绘制玩家
    pygame.draw.rect(screen,RED,(player_x,player_y,ply_w,ply_h))
    # 绘制障碍物
    for ox,oy in obs_list:
        pygame.draw.rect(screen,GREEN,(ox,oy,obs_w,obs_h))

    # 分数文字
    scr_txt = font.render(f"得分：{score}",True,(0,0,0))
    screen.blit(scr_txt,(20,20))

    if game_over:
        over_txt = font.render("游戏结束！按R重新开始",True,(220,0,0))
        screen.blit(over_txt,(WIDTH//2-over_txt.get_width()//2,HEIGHT//2))

    pygame.display.flip()

pygame.quit()
sys.exit()