← 都来码 / Dolaima← 例程索引typescript/app/snake.ts▶ 在浏览器里试玩 原文

typescript/app/snake.ts · 10005 字节 · 下载原文

▶ 在浏览器里试玩

// snake.ts —— 贪吃蛇(VML 的 TypeScript 前端)
// snake.ts -- Snake (VML's TypeScript frontend)
//
// 与 `Examples/c/app/snake.c` / `Examples/go/app/snake.go` **同一套玩法**:
// Same rules as the C / Python versions:
//   20×18 格,蛇每 150 毫秒前进一格;吃到食物长一节、加 1 分并提速;
//   a 20x18 grid, the snake advances one cell every 150 ms; eating food grows it by one, +1 point, faster;
//   撞墙或咬到自己结束;方向键 / WASD 转向,点屏幕四边也能转向;回车 / ESC 重开。
//   hitting a wall or biting yourself ends the run; arrows / WASD steer, tapping a screen edge also turns;
//   Enter / ESC restarts.
//
// ⚠ 本前端两条实测约束(见 `memory.ts` 文件头):
// ⚠ Two measured rules of this frontend (see the header of `memory.ts`):
//   · `/` 是浮点除法 ⇒ 全用 `~~(a / b)`;
//   · `/` is floating division => `~~(a / b)` everywhere;
//   · `VML_MSG_*` 常量不会被自动引入 ⇒ 就地声明成 `const`。
//   · `VML_MSG_*` constants are not auto-imported => declare them here as `const`.
//
// 跑法 —— 手机:`vml run examples/typescript/snake.ts`
// How to run — on the phone: `vml run examples/typescript/snake.ts`
// 跑法 —— 桌面:`vmlcli Examples/typescript/snake.ts --screen 480x640 --frames /tmp/fr`
// How to run — on the desktop: `vmlcli Examples/typescript/snake.ts --screen 480x640 --frames /tmp/fr`

const MSG_KEYDOWN: number = 1;
const MSG_MOUSEDOWN: number = 4;
const MSG_TOUCHDOWN: number = 6;
const MSG_TIMER: number = 9;
const MSG_CLOSE: number = 10;
const MSG_RESIZE: number = 11;
const KEY_ESC: number = 27;

const MAX_FRAMES: number = 20000;
const GRID_W: number = 20;
const GRID_H: number = 18;
const BODY_MAX: number = 64;

const C_BG: number = 0xFF101018;
const C_CELL: number = 0xFF1A1A24;
const C_HEAD: number = 0xFF51E86E;
const C_BODY: number = 0xFF4A90D9;
const C_FOOD: number = 0xFFE06C50;
const C_TEXT: number = 0xFFE8E8F0;
const C_DIM: number = 0xFF9AA0B0;

// S slots:
//   0 w 1 h 2 cell 3 ox 4 oy 5 lang 6 len 7 dx 8 dy 9 fx 10 fy
//   11 score 12 alive 13 stepMs 14 seed 15 frames 16 headX 17 headY
let S: number[] = [360, 620, 20, 10, 40, 0, 3, 1, 0, 5, 5, 0, 1, 150, 20263, 0, 10, 9];
// 蛇身:2i=x, 2i+1=y(i=0 是头)。⚠ `push` 不扩容(本前端的数组容量 = 字面量格数),
// 所以照 `Examples/javascript/app/maze.js` 的 `bigArr()` 用 `concat` 翻倍到 256 槽。
// Body: 2i = x, 2i+1 = y (i = 0 is the head). ⚠ `push` never grows (a literal's capacity is
// exactly its slot count), so double it with `concat` up to 256 slots, like `bigArr()` in the JS maze.
let B: number[] = [0, 0];
B = B.concat(B);
B = B.concat(B);
B = B.concat(B);
B = B.concat(B);
B = B.concat(B);
B = B.concat(B);
B = B.concat(B);

function snRnd(n: number): number {
    S[14] = (S[14] * 1103 + 12345) % 32768;
    return ~~(S[14] / 256) % n;
}

function snLayout(): void {
    S[0] = ui_scr_get_w();
    S[1] = ui_scr_get_h();
    if (S[0] <= 0) { S[0] = 360; }
    if (S[1] <= 0) { S[1] = 620; }
    // 顶部留出分数区、底部留出提示行;小屏压缩这两段但绝不把提示推出画布。
    // Reserve a score band on top and a hint band at the bottom; both shrink on tiny screens.
    let top: number = 60;
    let bottom: number = 40;
    if (S[1] < 400) { top = 36; bottom = 24; }
    let byw: number = S[0] - 8;
    let byh: number = S[1] - top - bottom;
    S[2] = ~~(byw / GRID_W);
    if (~~(byh / GRID_H) < S[2]) { S[2] = ~~(byh / GRID_H); }
    if (S[2] < 4) { S[2] = 4; }
    S[3] = ~~((S[0] - S[2] * GRID_W) / 2);
    S[4] = top;
}

function snNewGame(): void {
    S[6] = 3;
    S[7] = 1;
    S[8] = 0;
    S[11] = 0;
    S[12] = 1;
    S[13] = 150;
    S[15] = 0;
    S[16] = 10;
    S[17] = 9;
    // 蛇身:头 (10,9),往左两节
    // Body: head at (10,9), two segments to the left
    B[0] = 10; B[1] = 9;
    B[2] = 9;  B[3] = 9;
    B[4] = 8;  B[5] = 9;
    snPlaceFood();
}

function snPlaceFood(): void {
    let tries: number = 0;
    let fx: number = snRnd(GRID_W);
    let fy: number = snRnd(GRID_H);
    while (tries < 300) {
        let hit: number = 0;
        let k: number = 0;
        while (k < S[6]) {
            if (B[k * 2] === fx && B[k * 2 + 1] === fy) { hit = 1; }
            k = k + 1;
        }
        if (hit === 0) { S[9] = fx; S[10] = fy; tries = 300; }
        else { fx = snRnd(GRID_W); fy = snRnd(GRID_H); }
        tries = tries + 1;
    }
}

function snStep(): void {
    if (S[12] === 0) { return; }
    let nx: number = S[16] + S[7];
    let ny: number = S[17] + S[8];
    if (nx < 0 || ny < 0 || nx >= GRID_W || ny >= GRID_H) { S[12] = 0; return; }

    let body: number = 0;
    let k: number = 0;
    while (k < S[6] - 1) {
        if (B[k * 2] === nx && B[k * 2 + 1] === ny) { body = 1; }
        k = k + 1;
    }
    if (body !== 0) { S[12] = 0; return; }

    // 整体后移一节,头插在最前
    // Shift the body back by one and put the new head at the front
    k = S[6] - 1;
    while (k > 0) {
        B[k * 2] = B[(k - 1) * 2];
        B[k * 2 + 1] = B[(k - 1) * 2 + 1];
        k = k - 1;
    }
    B[0] = nx;
    B[1] = ny;
    S[16] = nx;
    S[17] = ny;

    if (nx === S[9] && ny === S[10]) {
        // 吃到:长一节、加分、提速
        // Eat: grow, score, speed up
        if (S[6] < BODY_MAX - 1) { S[6] = S[6] + 1; }
        S[11] = S[11] + 1;
        if (S[13] > 70) { S[13] = S[13] - 10; }
        snPlaceFood();
    }
}

function snDraw(): void {
    ui_2d_clear(C_BG);

    let x: number = 0;
    while (x < GRID_W) {
        let y: number = 0;
        while (y < GRID_H) {
            ui_2d_rect(S[3] + x * S[2], S[4] + y * S[2], S[2] - 1, S[2] - 1, C_CELL, 1, 0, 0);
            y = y + 1;
        }
        x = x + 1;
    }

    ui_2d_rect(S[3] + S[9] * S[2], S[4] + S[10] * S[2], S[2] - 1, S[2] - 1, C_FOOD, 1, 0, 3);

    let k: number = 0;
    while (k < S[6]) {
        if (k === 0) {
            ui_2d_rect(S[3] + B[0] * S[2], S[4] + B[1] * S[2], S[2] - 1, S[2] - 1, C_HEAD, 1, 0, 3);
        } else {
            ui_2d_rect(S[3] + B[k * 2] * S[2], S[4] + B[k * 2 + 1] * S[2], S[2] - 1, S[2] - 1, C_BODY, 1, 0, 3);
        }
        k = k + 1;
    }

    if (S[1] < 400) {
        ui_2d_text(10, 8, "" + S[11], C_TEXT, 14, 0);
        if (S[5] === 0) { ui_2d_text(10, 26, "得分", C_DIM, 9, 0); }
        else { ui_2d_text(10, 26, "score", C_DIM, 9, 0); }
    } else {
        ui_2d_text(10, 22, "" + S[11], C_TEXT, 15, 0);
        if (S[5] === 0) { ui_2d_text(10, 44, "得分", C_DIM, 10, 0); }
        else { ui_2d_text(10, 44, "score", C_DIM, 10, 0); }
    }

    // 提示行贴着棋盘下沿,但绝不越出画布 / hint sits under the board but never leaves the canvas
    let hy: number = S[4] + GRID_H * S[2] + 14;
    if (hy > S[1] - 8) { hy = S[1] - 8; }
    let msgFs: number = 15;
    let hintFs: number = 11;
    if (S[1] < 400) { msgFs = 13; hintFs = 10; }

    if (S[12] === 0) {
        if (S[5] === 0) { ui_2d_text(~~(S[0] / 2), hy, "撞上了,回车 / ESC 重开", C_TEXT, msgFs, 1); }
        else { ui_2d_text(~~(S[0] / 2), hy, "Crash - Enter / ESC to restart", C_TEXT, msgFs, 1); }
    } else {
        if (S[5] === 0) { ui_2d_text(~~(S[0] / 2), hy, "方向键 / 点屏幕四边转向", C_DIM, hintFs, 1); }
        else { ui_2d_text(~~(S[0] / 2), hy, "Arrows / tap a screen edge to steer", C_DIM, hintFs, 1); }
    }
    ui_2d_present();
}

function main(): void {
    S[5] = ui_scr_get_language();
    if (S[5] === 0) { ui_win_open("贪吃蛇", 0, 0); }
    else { ui_win_open("Snake", 0, 0); }
    ui_scr_set_keep_on(1);

    snLayout();
    snNewGame();
    snDraw();

    let tid: number = ui_timer_set(S[13], 1);
    let done: number = 0;
    let curMs: number = S[13];

    while (done === 0 && ui_win_is_closed() === 0) {
        let t: number = ui_msg_fetch_wait(S[13]);
        if (t === MSG_CLOSE) { break; }

        if (t === MSG_TIMER) {
            S[15] = S[15] + 1;
            if (S[15] >= MAX_FRAMES) { done = 1; }
            snStep();
            if (S[13] !== curMs) {
                ui_timer_kill(tid);
                curMs = S[13];
                tid = ui_timer_set(curMs, 1);
            }
            snDraw();
            continue;
        }

        if (t === MSG_KEYDOWN) {
            let k: number = ui_msg_get_a();
            if (k === KEY_ESC) { done = 1; }
            if (k === 68 && S[7] !== -1) { S[7] = 1; S[8] = 0; }
            if (k === 65 && S[7] !== 1) { S[7] = -1; S[8] = 0; }
            if (k === 87 && S[8] !== 1) { S[7] = 0; S[8] = -1; }
            if (k === 83 && S[8] !== -1) { S[7] = 0; S[8] = 1; }
            if (k === 37 && S[7] !== 1) { S[7] = -1; S[8] = 0; }
            if (k === 39 && S[7] !== -1) { S[7] = 1; S[8] = 0; }
            if (k === 38 && S[8] !== 1) { S[7] = 0; S[8] = -1; }
            if (k === 40 && S[8] !== -1) { S[7] = 0; S[8] = 1; }
            if (k === 13) { snNewGame(); }
            snDraw();
            continue;
        }

        if (t === MSG_TOUCHDOWN || t === MSG_MOUSEDOWN) {
            let tx: number = ui_msg_get_a();
            let ty: number = ui_msg_get_b();
            if (S[12] === 0) { snNewGame(); }
            else {
                let dl: number = tx;
                let dr: number = S[0] - tx;
                let dt: number = ty;
                let db: number = S[1] - ty;
                if (dl <= dr && dl <= dt && dl <= db) { if (S[7] !== 1) { S[7] = -1; S[8] = 0; } }
                else if (dr <= dt && dr <= db) { if (S[7] !== -1) { S[7] = 1; S[8] = 0; } }
                else if (dt <= db) { if (S[8] !== 1) { S[7] = 0; S[8] = -1; } }
                else { if (S[8] !== -1) { S[7] = 0; S[8] = 1; } }
            }
            snDraw();
            continue;
        }

        if (t === MSG_RESIZE) { snLayout(); snDraw(); continue; }
    }

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

main();