from tkinter import *
import random
import time

root = Tk()
root.title("简易跑酷游戏")
W = 600
H = 350
c = Canvas(root, width=W, height=H, bg="#87CEFA")
c.pack()

# 地面高度
ground = 290
# 玩家
px, py = 60, ground - 40
pw, ph = 30, 40
vy = 0
g = 1.2
jump = -22
on_ground = True

obs = []
obs_speed = 4
score = 0
spawn_count = 0

def jump_key(e):
    global vy, on_ground
    if on_ground:
        vy = jump
        on_ground = False

root.bind("<space>", jump_key)

def create_obstacle():
    w = random.randint(25, 45)
    h = random.randint(35, 70)
    x = W + random.randint(20,60)
    y = ground - h
    obs.append([x,y,w,h])

def game_loop():
    global px,py,vy,on_ground,score,spawn_count
    c.delete("all")
    # 地面
    c.create_rectangle(0,ground,W,H,fill="#58B049")

    # 重力
    vy += g
    py += vy
    # 落地
    if py+ph >= ground:
        py = ground - ph
        vy = 0
        on_ground = True

    # 生成障碍
    spawn_count +=1
    if spawn_count >80:
        create_obstacle()
        spawn_count =0

    # 障碍移动
    for i in range(len(obs)-1,-1,-1):
        x,y,w,h = obs[i]
        obs[i][0] -= obs_speed
        if x+w <0:
            obs.pop(i)
            score +=1

    # 碰撞
    player_box = [px,py,px+pw,py+ph]
    for x,y,w,h in obs:
        if not(player_box[2]<x or player_box[0]>x+w or player_box[3]<y or player_box[1]>y+h):
            c.create_text(W/2,H/2,text=f"游戏结束！得分：{score}",font=("黑体",24),fill="red")
            return

    # 绘制玩家
    c.create_rectangle(px,py,px+pw,py+ph,fill="#ff3333")
    # 绘制障碍
    for x,y,w,h in obs:
        c.create_rectangle(x,y,x+w,y+h,fill="#333333")

    # 分数
    c.create_text(40,20,text=f"分数:{score}",font=("黑体",16))

    root.after(16,game_loop)

game_loop()
root.mainloop()