/* pong.c —— 球类对打（Pong）：最老的那种"两块板 + 一个球"
 * pong.c -- Pong: the oldest "two paddles and a ball" game
 *
 * 玩法（自己写的规则，没抄任何实现的代码）：
 * Rules (written from scratch, no code taken from any implementation):
 *   ① 左右各一块竖直挡板，球在中间弹；球碰到上下边反弹，越过左右边 = 对方得分；
 *   ① one vertical paddle on each side, the ball bounces between them; it rebounds off the top and
 *      bottom edges, and crossing the left/right edge scores for the opponent;
 *   ② 玩家用**手指拖动**控制左板（点哪跟到哪，拖到哪跟到哪）；右板是 AI（追球但有速度上限）；
 *   ② the player drags a finger to steer the left paddle (it follows the tap and the drag); the right
 *      paddle is an AI that chases the ball, with a speed cap;
 *   ③ 先到 5 分结束，按 ESC / 点右上角「重开」再打一局。
 *   ③ the first to 5 wins; ESC (or the "restart" button at the top right) starts a new game.
 *
 * 输入怎么拿：`ui_msg_wait` 出来的 `TOUCHDOWN` / `TOUCHMOVE` 里 `msg[1]` 是 x、`msg[2]` 是 y
 * How input arrives: `TOUCHDOWN` / `TOUCHMOVE` from `ui_msg_wait`, `msg[1]` is x and `msg[2]` is y
 * （见 `vml_ui.h`）—— 手指拖动的每一拍都会来一条，正是挡板要的。
 * (see `vml_ui.h`) -- one arrives every frame of a drag, exactly what the paddle needs.
 *
 * ⚠ 本程序**有界退出**：到 `MAX_FRAMES` 自己停（无头跑/产图标时不会挂住），
 * ⚠ The program **exits within a bound**: it stops by itself at `MAX_FRAMES` (so headless runs and
 *    icon generation never hang).
 */

#include <vml_ui.h>
#include <stdlib.h>
#include <stdio.h>

#define MAX_FRAMES 1500        /* 25 秒（60ms 一拍）；无头跑时到点自己停 */
#define WIN_SCORE  5

/* 配色（真彩，暗底亮色；与其它例程同一套，缩略图看起来是一家人） */
#define C_BG     0xFF101018
#define C_PANEL  0xFF1A1A24
#define C_PLAYER 0xFF51E86E
#define C_AI     0xFFE06C50
#define C_BALL   0xFFFFFFFF
#define C_TEXT   0xFFE8E8F0
#define C_DIM    0xFF9AA0B0

static int SW, SH, g_lang;
static int g_frames;

/* 球与板（都按画布尺寸现算，见 relayout） */
static int pad_w, pad_h, ball_r;
static int lx, ly;             /* 左板左上角 */
static int rx, ry;
static int bx, by, bvx, bvy;
static int score_l, score_r;

/* 自己带的伪随机（不用库里的 rand：本平台 rand 长期只有声明没有实现，且自带的序列可复现） */
static unsigned int seed = 20261114;
static int rnd(int n)
{
    seed = seed * 1103515245u + 12345u;
    return (int)((seed >> 16) % (unsigned int)n);
}

static void relayout(void)
{
    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;
    ball_r = SW / 40;
    if (ball_r < 6) ball_r = 6;
    if (ly <= 0) ly = SH / 2 - pad_h / 2;
    if (ry <= 0) ry = SH / 2 - pad_h / 2;
}

static void serve(int dir)
{
    bx = SW / 2;
    by = SH / 2;
    bvx = dir * (SW / 110 + 3);
    bvy = (rnd(2) == 0 ? -1 : 1) * (SH / 150 + 2);
}

static void new_game(void)
{
    score_l = 0;
    score_r = 0;
    ly = SH / 2 - pad_h / 2;
    ry = SH / 2 - pad_h / 2;
    serve(rnd(2) == 0 ? -1 : 1);
}

static void num(char *buf, int v)
{
    itoa(v, buf);
}

/* 画一块板 */
static void draw_paddle(int x, int y, int color)
{
    ui_2d_rect(x, y, pad_w, pad_h, color, 1, 0, 3);
}

static void draw(void)
{
    int cx = SW / 2;
    char buf[16];

    ui_2d_clear(C_BG);
    /* 中线 */
    ui_2d_rect(cx - 1, 0, 2, SH, C_PANEL, 1, 0, 0);

    /* 比分 */
    num(buf, score_l);
    ui_2d_text(cx - SW / 6, 40, buf, C_PLAYER, 28, VML_ANCHOR_CENTER);
    num(buf, score_r);
    ui_2d_text(cx + SW / 6, 40, buf, C_AI, 28, VML_ANCHOR_CENTER);

    draw_paddle(lx, ly, C_PLAYER);
    draw_paddle(SW - pad_w - lx, ry, C_AI);        /* 右板贴右边，按镜像位置摆 */

    ui_2d_circle(bx, by, ball_r, C_BALL, 1, 0);

    ui_2d_text(cx, SH - 54, g_lang == 0 ? "拖动屏幕控制左边绿板" : "Drag to steer the green paddle",
               C_DIM, 12, VML_ANCHOR_CENTER);
    ui_2d_text(cx, SH - 32, g_lang == 0 ? "先到 5 分；ESC 重开 / 退出" : "First to 5; ESC = restart / quit",
               C_DIM, 12, VML_ANCHOR_CENTER);
    num(buf, g_frames);
    ui_2d_text(SW - 8, 12, buf, C_DIM, 10, VML_ANCHOR_RIGHT);

    ui_2d_present();
}

int main(void)
{
    int msg[4];
    int tid;
    int done = 0;
    char buf[16];

    g_lang = ui_scr_get_language();
    relayout();
    ui_win_open_ex("pong.c", 0, 0, VML_WIN_ROTATABLE, VML_WIN_NO_GAMEPAD);
    relayout();
    new_game();
    draw();

    tid = ui_timer_set(60, 1);
    while (!done && ui_win_is_closed() == 0) {
        int t = ui_msg_wait(msg, 0);
        if (t == VML_MSG_NONE) continue;

        if (t == VML_MSG_TOUCHDOWN || t == VML_MSG_TOUCHMOVE || t == VML_MSG_MOUSEDOWN
            || t == VML_MSG_MOUSEMOVE) {
            /* 左半屏才控制玩家板（右半屏留给 AI，免得滑动时两块板一起动） */
            if (msg[1] < SW / 2) {
                ly = msg[2] - pad_h / 2;
                if (ly < 0) ly = 0;
                if (ly > SH - pad_h) ly = SH - pad_h;
            }
            draw();
            continue;
        }

        if (t == VML_MSG_KEYDOWN) {
            if (msg[1] == VML_KEY_ESCAPE) {
                new_game();
            } else if (msg[1] == VML_KEY_UP) {
                ly = ly - SH / 12;
                if (ly < 0) ly = 0;
                draw();
            } else if (msg[1] == VML_KEY_DOWN) {
                ly = ly + SH / 12;
                if (ly > SH - pad_h) ly = SH - pad_h;
                draw();
            }
            continue;
        }

        if (t == VML_MSG_TIMER) {
            int step;

            g_frames = g_frames + 1;
            if (g_frames >= MAX_FRAMES) done = 1;

            /* 球走一步；拍长固定，速度写进 bvx/bvy */
            bx = bx + bvx;
            by = by + bvy;

            /* 上下边反弹 */
            if (by < ball_r) { by = ball_r; bvy = -bvy; }
            if (by > SH - ball_r) { by = SH - ball_r; bvy = -bvy; }

            /* 左板碰撞：球心落在板右侧半拍以内 && 纵向重叠 */
            if (bvx < 0 && bx - ball_r <= lx + pad_w && bx > lx
                && by + ball_r >= ly && by - ball_r <= ly + pad_h) {
                bx = lx + pad_w + ball_r;
                bvx = -bvx;
                bvy = bvy + (by - (ly + pad_h / 2)) / 12;      /* 打在板的哪儿，决定反弹角 */
            }
            /* 右板碰撞 */
            if (bvx > 0 && bx + ball_r >= SW - pad_w - lx && bx < SW - lx
                && by + ball_r >= ry && by - ball_r <= ry + pad_h) {
                bx = SW - pad_w - lx - ball_r;
                bvx = -bvx;
                bvy = bvy + (by - (ry + pad_h / 2)) / 12;
            }

            /* 出界：加分、重新发球 */
            if (bx < -ball_r * 2) {
                score_r = score_r + 1;
                if (score_r >= WIN_SCORE) done = 1;
                serve(1);
            } else if (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;
            else if (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;
        }

        if (t == VML_MSG_WINDOWRESIZE) { relayout(); draw(); continue; }
        if (t == VML_MSG_WINDOWCLOSE) break;
    }

    ui_timer_kill(tid);
    ui_win_close();

    /* 无头判据：这一行能被脚本比（画面只能肉眼看） */
    num(buf, g_frames);
    printf("pong: score=%d:%d frames=%s done\n", score_l, score_r, buf);
    return 0;
}
