# pong.py —— 对打（VML 的 Python 前端）
# pong.py -- Pong (VML's Python frontend)
#
# 与 `Examples/c/app/pong.c` 同一套玩法：左板跟手指、右板 AI 追球，先到 5 分。
# Same rules as `Examples/c/app/pong.c`: the left paddle follows the finger, the right one is an AI,
# first to 5 wins.
#
# ⚠ 两条 Python 绑定的事实（写 `snake.py` 时量到的）：① **没有 `import`** —— 库函数就是全局函数；
# ⚠ Two facts about the Python bindings (measured while writing `snake.py`): ① **no `import`** --
#   library functions are plain globals;
#   ② `ui_key_fetch` 没导出 ⇒ 这一版只用触摸（点/拖左半屏控制球板）。
#   ② `ui_key_fetch` is not exported, so this version is touch-only (tap/drag the left half).

# 显式引入共享库声明（GenLib 生成，勿手写）：形参个数写错在**编译期**报错。
# Explicitly import the shared-library declarations (generated by GenLib, do not hand-write):
# a wrong argument count becomes a **compile-time** error.
import vml_ui

MAX_FRAMES = 1500
WIN_SCORE = 5

SW = 360
SH = 620
PAD_W = 12
PAD_H = 70
BALL_R = 7

lx = 10
ly = 275
ry = 275
bx = 180
by = 310
bvx = 4
bvy = 3
score_l = 0
score_r = 0
seed = 20262


def rnd(n):
    # ⚠ **16 位** LCG（同 snake.py）：32 位整数下 C 的公式会溢出、恒返回 0。
    # ⚠ A **16-bit** LCG (same as snake.py): with 32-bit ints the C formula overflows and returns 0.
    global seed
    seed = (seed * 1103 + 12345) % 32768
    return (seed // 256) % n


def relayout():
    global SW, SH, PAD_W, PAD_H, BALL_R, ly, ry
    SW = ui_scr_get_w()
    SH = ui_scr_get_h()
    if SW <= 0:
        SW = 360
    if SH <= 0:
        SH = 620
    PAD_W = SW // 28
    if PAD_W < 8:
        PAD_W = 8
    PAD_H = SH // 6
    if PAD_H < 16:
        PAD_H = 16
    BALL_R = SW // 40
    if BALL_R < 6:
        BALL_R = 6
    # ⚠ 左右球板的 y 是**模块级初值**（275），小画布上会整个落到画布外 ——
    #   开窗后重算尺寸时必须一起夹回场内。
    # ⚠ The paddles' y values are module-level initials (275); on a tiny canvas they land
    #   outside the screen -- clamp them whenever the geometry is recomputed.
    if ly > SH - PAD_H:
        ly = SH - PAD_H
    if ly < 0:
        ly = 0
    if ry > SH - PAD_H:
        ry = SH - PAD_H
    if ry < 0:
        ry = 0


def serve(d):
    global bx, by, bvx, bvy
    bx = SW // 2
    by = SH // 2
    bvx = d * (SW // 110 + 3)
    bvy = (rnd(2) * 2 - 1) * (SH // 150 + 2)


def draw():
    ui_2d_clear(0xFF101018)
    ui_2d_rect(SW // 2 - 1, 0, 2, SH, 0xFF1A1A24, 1, 0, 0)
    ui_2d_text(SW // 2 - 60, 50, str(score_l), 0xFF51E86E, 28, 1)
    ui_2d_text(SW // 2 + 60, 50, str(score_r), 0xFFE06C50, 28, 1)
    ui_2d_rect(lx, ly, PAD_W, PAD_H, 0xFF51E86E, 1, 0, 3)
    ui_2d_rect(SW - PAD_W - lx, ry, PAD_W, PAD_H, 0xFFE06C50, 1, 0, 3)
    ui_2d_circle(bx, by, BALL_R, 0xFFFFFFFF, 1, 0)
    ui_2d_text(SW // 2, SH - 30, "drag the left half", 0xFF9AA0B0, 12, 1)
    ui_2d_present()


def main():
    global ly, ry, bx, by, bvx, bvy, score_l, score_r
    frames = 0
    done = 0

    relayout()
    ui_win_open_ex("pong.py", 0, 0, 1, 0)
    relayout()
    serve(1)
    draw()

    # ⚠ 球要动就**必须开定时器**：宿主不会自己发 t==9（实测没有这一行时整局只有 1 帧、
    #   球停在中间不动 —— 用户 2026-11-14 报「没写完」）。
    # ⚠ The ball only moves with a **timer armed**: the host never emits t==9 by itself
    #   (measured: 1 frame total with the ball frozen mid-court without this line).
    tid = ui_timer_set(33, 1)

    while done == 0 and ui_win_is_closed() == 0:
        # ⚠ 阻塞等的**返回值就是那条消息**（丢掉它 = 丢掉定时器消息 ⇒ 球永远停在中间）。
        # ⚠ The blocking wait's **return value is the message itself** (dropping it drops the
        #   timer message -> the ball never moves).
        t = ui_msg_fetch()
        if t == 0:
            t = ui_msg_fetch_wait(40)
        if t == 0:
            continue

        if t == 6 or t == 7 or t == 4 or t == 3:      # 触摸按下/拖动
            # ⚠ 坐标取**这条消息**的 a/b（`ui_touch_get_x/y` 在桌面宿主上恒为 0，见 snake.py 同处注释）
            # ⚠ Coordinates come from this message's a/b (`ui_touch_get_x/y` is always 0 on the
            #   desktop host; see the same note in snake.py).
            x = ui_msg_get_a()
            y = ui_msg_get_b()
            if x < SW // 2:
                ly = y - PAD_H // 2
                if ly < 0:
                    ly = 0
                if ly > SH - PAD_H:
                    ly = SH - PAD_H
            draw()
            continue

        if t == 9:                                     # 定时器：球走一步
            frames = frames + 1
            if frames >= MAX_FRAMES:
                done = 1

            bx = bx + bvx
            by = by + bvy
            if by < BALL_R:
                by = BALL_R
                bvy = 0 - bvy
            if by > SH - BALL_R:
                by = SH - BALL_R
                bvy = 0 - bvy

            if bvx < 0 and bx - BALL_R <= lx + PAD_W and bx > lx and by + BALL_R >= ly and by - BALL_R <= ly + PAD_H:
                bx = lx + PAD_W + BALL_R
                bvx = 0 - bvx
                bvy = bvy + (by - (ly + PAD_H // 2)) // 12
            if bvx > 0 and bx + BALL_R >= SW - PAD_W - lx and bx < SW - lx and by + BALL_R >= ry and by - BALL_R <= ry + PAD_H:
                bx = SW - PAD_W - lx - BALL_R
                bvx = 0 - bvx

            if bx < 0 - BALL_R * 2:
                score_r = score_r + 1
                if score_r >= WIN_SCORE:
                    done = 1
                serve(1)
            elif bx > SW + BALL_R * 2:
                score_l = score_l + 1
                if score_l >= WIN_SCORE:
                    done = 1
                serve(-1)

            # AI：追球心，每拍最多挪 SH/40
            step = SH // 40
            if step < 3:
                step = 3
            if by > ry + PAD_H // 2 + step:
                ry = ry + step
            elif by < ry + PAD_H // 2 - step:
                ry = ry - step
            if ry < 0:
                ry = 0
            if ry > SH - PAD_H:
                ry = SH - PAD_H

            draw()
            continue

    ui_timer_kill(tid)
    ui_win_close()
    return 0


main()
