← 都来码 / Dolaima← 例程索引csharp/app/pong.cs▶ 在浏览器里试玩 原文

csharp/app/pong.cs · 22509 字节 · 下载原文

▶ 在浏览器里试玩

// 乒乓(单人版)—— 用 **C#** 写的手机小游戏
// Pong (single player) — a small phone game written in **C#**
//
// 玩法:手指在**上半屏**上下滑动控制左挡板(键盘 W/S 也行),右边是电脑。
// Gameplay: slide a finger in the **upper half** to move the left paddle (W/S on a keyboard
// 球碰到挡板会加速;先得 7 分者胜。回车/空格重开,ESC 退出。
// works too); the right paddle is the computer. The ball speeds up on every paddle hit;
// first to 7 wins. Enter/Space restarts, ESC quits.
//
// ◆ 这个示例想讲清楚的三件事
// ◆ The three things this sample is meant to show
//
//   ① **运动按墙钟欠账补步**(用户 2026-10-04 口径):定时器只负责唤醒,
//   ① **Motion is advanced from wall-clock debt** (user rule of 2026-10-04): the timer only wakes the loop;
//      每帧该走几步 = 已经过去的毫秒数 ÷ 每步毫秒数。各平台定时器分辨率不一样,
//      steps per frame = elapsed milliseconds / milliseconds per step. Timer resolution differs per platform,
//      拿"收到几拍"当时间会让游戏在慢机器上变慢、快机器上变快。
//      so treating "how many ticks arrived" as time makes the game slow on slow hosts and fast on fast ones.
//
//   ② **整数物理**:位置、速度都用"像素 ×10"的整数表示,碰撞在整数域里判 ——
//   ② **Integer physics**: positions and velocities are integers in "pixels x10", and collisions are tested
//      不会出现浮点比较的误差累积,也让结果**完全可复现**(demo 模式就是靠这一点做判据)。
//      in the integer domain — no floating-point drift, and the result is **fully reproducible**
//      (that is what the demo mode's checkpoints rely on).
//
//   ③ **逐帧数字走 `drawNum`**(逐位画、零分配):这个前端的字符串 `+` 是真拼接,
//   ③ **Per-frame numbers go through `drawNum`** (digit by digit, zero allocation): string `+` really
//      但每一次都会分配一块不回收的内存 —— 放进 `draw()` 里就是每帧漏几块。
//      concatenates here, but every one allocs a block that is never freed — inside `draw()` that
//      leaks a few blocks per frame.
//
// 数值的唯一真源仍是 `Lib/c/vml_ui.h`。
// The single source of truth for these numbers is still `Lib/c/vml_ui.h`.
//
// 跑法:手机 `vml run examples/csharp/app/pong.cs`;
// How to run: phone `vml run examples/csharp/app/pong.cs`;
//       桌面 `vmlcli Examples/csharp/app/pong.cs --screen 411x726 --frames /tmp/fr`
//       desktop `vmlcli Examples/csharp/app/pong.cs --screen 411x726 --frames /tmp/fr`
//       `--arg demo` 是无头验收模式:先跑两段固定物理,再跑 60 拍渲染后自己退出。
//       `--arg demo` is the headless acceptance mode: two fixed physics checks first, then 60 rendered ticks, then exit.

using Vml.Ui;

class PongCs
{
    // ── 消息类型 / 键码(源:Lib/c/vml_ui.h)──
    // ── Message types / key codes (source: Lib/c/vml_ui.h) ──
    const int MSG_KEYDOWN   = 1;
    const int MSG_MOUSEDOWN = 4;
    const int MSG_TOUCHDOWN = 6;
    const int MSG_TOUCHMOVE = 7;
    const int MSG_TOUCHUP   = 8;
    const int MSG_TIMER     = 9;
    const int MSG_CLOSE     = 10;
    const int MSG_RESIZE    = 11;
    const int MSG_ORIENT    = 12;

    const int KEY_ESC   = 27;
    const int KEY_ENTER = 13;
    const int KEY_SPACE = 32;
    const int KEY_UP    = 38;
    const int KEY_DOWN  = 40;
    const int KEY_W     = 87;
    const int KEY_S     = 83;

    const int ANCHOR_LEFT   = 0;
    const int ANCHOR_CENTER = 1;
    const int VANCHOR_MIDDLE = 1;

    const int LANG_ZH = 0;
    const int WIN_PORTRAIT = 0;
    const int WIN_NO_GAMEPAD = 0;

    // ── 配色(0xAARRGGBB 的十进制负数形式)──
    // ── Colors (decimal-negative 0xAARRGGBB) ──
    const int BG       = -15724520;   // 0xFF101018
    const int COURT    = -15066588;   // 0xFF1A1A24
    const int LINE     = -12829620;   // 0xFF3C3C4C
    const int TEXT     = -1513232;    // 0xFFE8E8F0
    const int MUTED    = -6643536;    // 0xFF9AA0B0
    const int P1       = -11890471;   // 0xFF4A90D9
    const int P2       = -2069424;    // 0xFFE06C50
    const int BALL_C   = -8096;       // 0xFFFFE060
    const int GOLD     = -8096;
    const int GREEN    = -11409298;   // 0xFF51E86E

    // ── 规则 ──
    // ── Rules ──
    const int TICK_MS     = 16;       // ≈60fps 的物理节拍(定时器只负责唤醒)
    // physics beat of about 60 fps (the timer only wakes the loop)
    const int PADDLE_H    = 84;
    const int PADDLE_W    = 12;
    const int PADDLE_STEP = 6;        // 键盘按住时每拍挪多少 px
    // px per tick while a key is held
    const int AI_STEP     = 5;        // 电脑每拍最多挪多少 px
    // the computer moves at most this many px per tick
    const int BALL_R      = 7;
    const int SERVE_VX    = 40;       // 发球速度:px/拍 ×10
    // serve speed: px per tick x10
    const int SERVE_VY    = 18;
    const int MAX_V       = 130;      // 速度上限(防穿透)
    // speed cap (stops tunnelling)
    const int WIN_SCORE   = 7;
    const int SERVE_WAIT  = 45;       // 得分后停多少拍再发球
    // ticks to wait after a point before serving

    // ── 状态 ──
    // ── State ──
    static int sw;
    static int sh;
    static int lang;

    static int courtTop;
    static int courtBot;
    static int leftX;
    static int rightX;

    static int leftY;
    static int rightY;
    static int ballX10;               // 球心 x ×10
    // ball centre x, x10
    static int ballY10;               // 球心 y ×10
    // ball centre y, x10
    static int vx10;
    static int vy10;
    static int scoreL;
    static int scoreR;
    static int winner;                // 0 = 未结束,1 = 左方,2 = 右方
    // 0 = playing, 1 = left won, 2 = right won
    static int state;                 // 0 = 进行中,1 = 结束
    // 0 = playing, 1 = over
    static int serveWait;
    static int serveDir;              // +1 = 发向右,-1 = 发向左
    // +1 serves to the right, -1 to the left
    static int rally;
    static int maxRally;
    static int bounces;               // 墙反弹次数(demo 判据用)
    // wall bounces (used by the demo checkpoints)
    static int frames;
    static int frameLimit;            // >0 = demo:跑到这么多拍就退出
    // >0 = demo: exit after this many ticks
    static int acc;
    static int lastMs;

    static string T(string zh, string en)
    {
        if (lang == LANG_ZH) return zh;
        return en;
    }

    static int clamp(int v, int lo, int hi)
    {
        if (v < lo) return lo;
        if (v > hi) return hi;
        return v;
    }

    static int absI(int v)
    {
        if (v < 0) return 0 - v;
        return v;
    }

    // ── 逐位画数字(不拼字符串、不分配)──
    // ── Draw a number digit by digit (no strings, no allocation) ──
    static int numDigits(int v)
    {
        if (v < 10) return 1;
        if (v < 100) return 2;
        if (v < 1000) return 3;
        return 4;
    }

    static int pow10(int n)
    {
        if (n <= 0) return 1;
        if (n == 1) return 10;
        if (n == 2) return 100;
        return 1000;
    }

    static string digitText(int d)
    {
        if (d == 0) return "0";
        if (d == 1) return "1";
        if (d == 2) return "2";
        if (d == 3) return "3";
        if (d == 4) return "4";
        if (d == 5) return "5";
        if (d == 6) return "6";
        if (d == 7) return "7";
        if (d == 8) return "8";
        return "9";
    }

    static void drawNum(int x, int y, int v, int color, int size, int anchor)
    {
        int n = numDigits(v);
        int dw = size * 14 / 25;      // 字宽实测值(见 g2048.cs 的文件头)
        // measured glyph advance (see the header of g2048.cs)
        int total = n * dw;
        int startX = x;
        if (anchor == ANCHOR_CENTER) startX = x - total / 2;
        int i = 0;
        while (i < n)
        {
            int d = (v / pow10(n - 1 - i)) % 10;
            ui_2d_text(startX + i * dw, y, digitText(d), color, size, ANCHOR_LEFT);
            i = i + 1;
        }
    }

    // ── 排版:全部由屏宽屏高推出来 ──
    // ── Layout: all derived from the screen size ──
    static void layout()
    {
        courtTop = 74;
        courtBot = sh - 18;
        leftX = 14;
        rightX = sw - 14 - PADDLE_W;
        leftY = clamp(leftY, courtTop, courtBot - PADDLE_H);
        rightY = clamp(rightY, courtTop, courtBot - PADDLE_H);
    }

    static int courtH()
    {
        return courtBot - courtTop;
    }

    static void newMatch()
    {
        scoreL = 0;
        scoreR = 0;
        winner = 0;
        state = 0;
        rally = 0;
        maxRally = 0;
        bounces = 0;
        serveWait = SERVE_WAIT;
        serveDir = 1;
        leftY = courtTop + (courtH() - PADDLE_H) / 2;
        rightY = leftY;
        ballX10 = sw * 5;
        ballY10 = (courtTop + courtH() / 2) * 10;
        vx10 = 0;
        vy10 = 0;
    }

    static void serve()
    {
        ballX10 = sw * 5;
        ballY10 = (courtTop + courtH() / 2) * 10;
        vx10 = SERVE_VX * serveDir;
        vy10 = SERVE_VY;
        rally = 0;
    }

    // 一次物理步进(整数域;返回 1 = 这一拍打到了挡板,用于发声)
    // One physics step (integer domain; returns 1 when a paddle was hit, for the sound)
    static int tick()
    {
        int hit = 0;
        if (state != 0) return 0;

        if (serveWait > 0)
        {
            serveWait = serveWait - 1;
            if (serveWait == 0) serve();
            return 0;
        }

        ballX10 = ballX10 + vx10;
        ballY10 = ballY10 + vy10;

        // 上下墙
        // Top and bottom walls
        int top10 = (courtTop + BALL_R) * 10;
        int bot10 = (courtBot - BALL_R) * 10;
        if (ballY10 < top10) { ballY10 = top10; vy10 = 0 - vy10; bounces = bounces + 1; }
        if (ballY10 > bot10) { ballY10 = bot10; vy10 = 0 - vy10; bounces = bounces + 1; }

        // 球当前所处的行(px)
        // The ball's current row (px)
        int by = ballY10 / 10;

        // 左挡板
        // Left paddle
        if (vx10 < 0)
        {
            int plane = (leftX + PADDLE_W + BALL_R) * 10;
            if (ballX10 <= plane && ballX10 >= (leftX - BALL_R) * 10)
            {
                if (by >= leftY - BALL_R && by <= leftY + PADDLE_H + BALL_R)
                {
                    ballX10 = plane;
                    vx10 = 0 - vx10;
                    // 击球点决定竖直分量:打中边缘抛得陡,打中中心接近水平
                    // Where it hits sets the vertical component: edges bounce steeply, the centre goes nearly flat
                    int rel = by - (leftY + PADDLE_H / 2);
                    vy10 = clamp(rel * 2, 0 - 70, 70);
                    // 每次回球整体加速一点(有上限)
                    // Every return speeds the ball up a little (capped)
                    if (absI(vx10) < MAX_V) vx10 = vx10 + vx10 / 8;
                    rally = rally + 1;
                    if (rally > maxRally) maxRally = rally;
                    hit = 1;
                }
            }
        }

        // 右挡板(电脑)
        // Right paddle (the computer)
        if (vx10 > 0)
        {
            int plane = (rightX - BALL_R) * 10;
            if (ballX10 >= plane && ballX10 <= (rightX + PADDLE_W + BALL_R) * 10)
            {
                if (by >= rightY - BALL_R && by <= rightY + PADDLE_H + BALL_R)
                {
                    ballX10 = plane;
                    vx10 = 0 - vx10;
                    int rel = by - (rightY + PADDLE_H / 2);
                    vy10 = clamp(rel * 2, 0 - 70, 70);
                    if (absI(vx10) < MAX_V) vx10 = vx10 + vx10 / 8;
                    rally = rally + 1;
                    if (rally > maxRally) maxRally = rally;
                    hit = 1;
                }
            }
        }

        // 出界 → 对方得分
        // Out of bounds -> the opponent scores
        if (ballX10 < 0 - 60)
        {
            scoreR = scoreR + 1;
            serveDir = -1;
            serveWait = SERVE_WAIT;
            checkedWin();
            return 2;
        }
        if (ballX10 > (sw + 6) * 10)
        {
            scoreL = scoreL + 1;
            serveDir = 1;
            serveWait = SERVE_WAIT;
            checkedWin();
            return 2;
        }
        return hit;
    }

    static void checkedWin()
    {
        if (scoreL >= WIN_SCORE) { winner = 1; state = 1; }
        if (scoreR >= WIN_SCORE) { winner = 2; state = 1; }
    }

    // 电脑:只在球朝自己飞时认真追,否则慢慢回到中间
    // The computer: really tracks only when the ball is coming at it, otherwise drifts back to the middle
    static void aiMove()
    {
        int target = courtTop + (courtH() - PADDLE_H) / 2;
        if (vx10 > 0) target = ballY10 / 10 - PADDLE_H / 2;
        if (rightY < target - AI_STEP) rightY = rightY + AI_STEP;
        else if (rightY > target + AI_STEP) rightY = rightY - AI_STEP;
        rightY = clamp(rightY, courtTop, courtBot - PADDLE_H);
    }

    // 手指(上半屏)→ 左挡板
    // Finger (upper half) -> the left paddle
    static void aimLeft(int fy)
    {
        leftY = fy - PADDLE_H / 2;
        leftY = clamp(leftY, courtTop, courtBot - PADDLE_H);
    }

    // ── 绘制 ──
    // ── Drawing ──
    static void draw()
    {
        ui_2d_clear(BG);

        // 球场
        // Court
        ui_2d_rect(6, courtTop - 8, sw - 12, courtH() + 16, COURT, 1, 0, 12);

        // 中线(虚线)
        // Centre line (dashed)
        int y = courtTop + 4;
        while (y < courtBot - 4)
        {
            ui_2d_rect(sw / 2 - 1, y, 2, 10, LINE, 1, 0, 0);
            y = y + 22;
        }

        // 挡板
        // Paddles
        ui_2d_rect(leftX, leftY, PADDLE_W, PADDLE_H, P1, 1, 0, 5);
        ui_2d_rect(rightX, rightY, PADDLE_W, PADDLE_H, P2, 1, 0, 5);

        // 球
        // Ball
        ui_2d_circle(ballX10 / 10, ballY10 / 10, BALL_R, BALL_C, 1, 0);

        // 比分
        // Score
        drawNum(sw / 2 - 46, 50, scoreL, P1, 26, ANCHOR_CENTER);
        drawNum(sw / 2 + 46, 50, scoreR, P2, 26, ANCHOR_CENTER);
        ui_2d_text(sw / 2, 50, ":", MUTED, 24, ANCHOR_CENTER);

        // 提示:窄屏(如 240x240)用短文案,否则一整行会越出画布
        // Hints: use the short text on narrow screens (e.g. 240x240), otherwise the line runs
        // off the canvas
        if (sw < 360)
            ui_2d_text(sw / 2, sh - 6, T("滑动挡板 · 回车重开 · ESC 退出",
                                        "Slide · Enter restarts · ESC quits"),
                       MUTED, 11, ANCHOR_CENTER);
        else
            ui_2d_text(sw / 2, sh - 6, T("上半屏滑动控制挡板 · W/S · 回车重开 · ESC 退出",
                                        "Slide in the upper half · W/S · Enter restarts · ESC quits"),
                       MUTED, 11, ANCHOR_CENTER);

        if (state == 1)
        {
            ui_2d_rect(0, 0, sw, sh, -872415232, 1, 0, 0);   // 0xCC000000 遮罩
            // 0xCC000000 scrim
            if (winner == 1)
                ui_2d_text(sw / 2, sh / 2 - 20, T("你赢了!", "You win!"), GREEN, 30, ANCHOR_CENTER);
            else
                ui_2d_text(sw / 2, sh / 2 - 20, T("电脑赢了", "Computer wins"), P2, 30, ANCHOR_CENTER);
            ui_2d_text(sw / 2, sh / 2 + 24, T("回车再来一局", "Enter for another match"), TEXT, 16, ANCHOR_CENTER);
        }

        ui_2d_present();
    }

    // ── 无头验收:两段固定物理,结果完全可复现 ──
    // ── Headless acceptance: two fixed physics checks with a fully reproducible result ──
    static void demoChecks()
    {
        int i = 0;

        // ① 上墙反弹:球贴着上沿向上飞,一步之后 vy 必须变号
        // (1) Top-wall bounce: the ball hugs the top edge going up; one step later vy must flip sign
        newMatch();
        serveWait = 0;
        ballX10 = sw * 5;
        ballY10 = (courtTop + BALL_R + 2) * 10;
        vx10 = 0;
        vy10 = -30;
        tick();
        print_str("pongcs: wall-reexam=");
        if (vy10 > 0 && bounces == 1) println_str("ok"); else println_str("FAIL");

        // ② 挡板回球:球水平飞向左挡板,挡板对准球心 ⇒ 必须打中、vx 变号、回合数 +1
        // (2) Paddle return: the ball flies level at the left paddle with the paddle centred on it
        //     ⇒ it must connect, vx must flip, and the rally count must go up
        newMatch();
        serveWait = 0;
        ballX10 = sw * 5;
        ballY10 = (courtTop + courtH() / 2) * 10;
        vx10 = -40;
        vy10 = 0;
        leftY = clamp(ballY10 / 10 - PADDLE_H / 2, courtTop, courtBot - PADDLE_H);
        i = 0;
        while (i < 400 && rally == 0)
        {
            tick();
            i = i + 1;
        }
        print_str("pongcs: hit=");
        println_int(rally);
        print_str("pongcs: vx-after=");
        println_int(vx10 / 10);
        print_str("pongcs: score=");
        print_int(scoreL);
        print_str("-");
        println_int(scoreR);
    }

    static void Main()
    {
        lang = ui_scr_get_language();
        frameLimit = 0;
        if (ui_arg_get_count() > 1) frameLimit = 60;

        // 开窗:尺寸传 0 ⇒ 交给宿主给真实可用区(开窗之前问到的只是估算值)
        // Opening: pass 0 ⇒ the host supplies the real available area (a pre-open read is only an estimate)
        ui_win_open_ex(T("乒乓", "Pong"), 0, 0, WIN_PORTRAIT, WIN_NO_GAMEPAD);
        ui_scr_set_keep_on(1);

        sw = ui_scr_get_w();
        sh = ui_scr_get_h();
        if (sw <= 0) sw = 411;
        if (sh <= 0) sh = 726;

        leftY = 0;
        rightY = 0;
        layout();

        if (frameLimit > 0) demoChecks();

        newMatch();
        draw();

        int tid = ui_timer_set(TICK_MS, 0);
        acc = 0;
        lastMs = ui_time_get_ms();    // 墙钟起点:进主循环时取
        // wall-clock origin: taken on entering the main loop

        while (ui_win_is_closed() == 0)
        {
            int t = ui_msg_fetch_wait(TICK_MS);

            // 这一帧该走几步:**按墙钟欠账**
            // How many steps this frame: **by wall-clock debt**
            int now = ui_time_get_ms();
            acc = acc + (now - lastMs);
            lastMs = now;
            if (acc > TICK_MS * 8) acc = 0;          // 卡太久别一次补一大串(防瞬移)
            // do not catch up in one huge burst after a long stall (anti-teleport)
            if (acc >= TICK_MS)
            {
                while (acc >= TICK_MS)
                {
                    acc = acc - TICK_MS;
                    frames = frames + 1;
                    if (ui_key_is_down(KEY_W) != 0) aimLeft(leftY + PADDLE_H / 2 - PADDLE_STEP);
                    if (ui_key_is_down(KEY_S) != 0) aimLeft(leftY + PADDLE_H / 2 + PADDLE_STEP);
                    aiMove();
                    int ev = tick();
                    // 一次事件只发一个音(ui_audio_beep 是单通道的)
                    // one sound per event (ui_audio_beep is single-channel)
                    if (ev == 1) ui_audio_beep(440, 30);
                    if (ev == 2) ui_audio_beep(180, 140);
                }
                draw();
            }

            if (t == MSG_CLOSE) break;

            if (t == MSG_RESIZE || t == MSG_ORIENT)
            {
                sw = ui_scr_get_w();
                sh = ui_scr_get_h();
                if (sw <= 0) sw = 411;
                if (sh <= 0) sh = 726;
                layout();
                draw();
                continue;
            }

            if (t == MSG_KEYDOWN)
            {
                int k = ui_msg_get_a();
                if (k == KEY_ESC) break;
                if (k == KEY_ENTER || k == KEY_SPACE)
                {
                    newMatch();
                    ui_audio_beep(523, 70);
                    draw();
                }
                if (k == KEY_UP) { aimLeft(leftY + PADDLE_H / 2 - 24); draw(); }
                if (k == KEY_DOWN) { aimLeft(leftY + PADDLE_H / 2 + 24); draw(); }
                continue;
            }

            if (t == MSG_TOUCHDOWN || t == MSG_TOUCHMOVE || t == MSG_MOUSEDOWN)
            {
                int x = ui_msg_get_a();
                int y = ui_msg_get_b();
                if (state == 1)
                {
                    if (t == MSG_TOUCHDOWN || t == MSG_MOUSEDOWN)
                    {
                        newMatch();
                        ui_audio_beep(523, 70);
                        draw();
                    }
                }
                else
                {
                    if (y < sh / 2) aimLeft(y);
                    draw();
                }
                if (t == MSG_TOUCHMOVE) ui_msg_drop(1);
                continue;
            }

            if (t == MSG_TOUCHUP) continue;

            if (t == MSG_TIMER)
            {
                // 定时器只负责唤醒(推进在上面按墙钟欠账走)
                // The timer only wakes the loop (advance happens above, by wall-clock debt)
                if (frameLimit > 0 && frames >= frameLimit) break;
                continue;
            }
        }

        ui_timer_kill(tid);
        ui_scr_set_keep_on(0);
        ui_win_close();

        // 给无头验证留确定性判据
        // Deterministic checkpoints for headless verification
        print_str("pongcs: score-final=");
        print_int(scoreL);
        print_str("-");
        println_int(scoreR);
        print_str("pongcs: maxrally=");
        println_int(maxRally);
        print_str("pongcs: winner=");
        println_int(winner);
        print_str("pongcs: ball=");
        print_int(ballX10 / 10);
        print_str(",");
        println_int(ballY10 / 10);
        print_str("pongcs: frames=");
        println_int(frames);
        println_str("pongcs: done");
    }
}