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

swift/app/pong.swift · 9930 字节 · 下载原文

▶ 在浏览器里试玩

// 对打(Pong)—— 用 **Swift** 写的手机小游戏
// Pong — a small phone game written in **Swift**
//
// 玩法(与 `Examples/c/app/pong.c` / `Examples/python/app/pong.py` 同一套):
// Gameplay (same rules as the C / Python versions):
//   · 左板跟手指(点/拖左半屏),右板是 AI 追球,先到 5 分;
//   · the left paddle follows the finger (tap/drag on the left half), the right one is an AI, first to 5 wins;
//   · 球碰上下边界反弹,碰板反弹并提速;出界对方得分;
//   · the ball bounces off the top/bottom and off a paddle (speed up); going out scores for the opponent;
//   · 结束后点屏幕 / ESC / 回车重开。
//   · after the match ends, tap the screen / ESC / Enter to play again.
//
// ◆ Swift 前端的实测约束(见 `Examples/swift/app/memory.swift` 文件头)
// ◆ Measured constraints of the Swift frontend (see the header of `Examples/swift/app/memory.swift`)
//
//   ① **状态只能放数组**:模块级标量读出来是垃圾;**整个程序只允许一个全局数组**;
//   ① **State lives in arrays only**: module-level scalars read back as garbage; **exactly one global array**;
//   ② 常量写成 `main` 里的局部变量 / 无参函数;③ 颜色写负数十进制;
//   ② constants are locals in `main` / zero-argument functions; ③ colours are negative decimals;
//   ④ 整数除法向零截断(触摸坐标可能为负,先挡再除);
//   ④ integer division truncates toward zero (touch coordinates can be negative; reject first);
//   ⑤ 函数名避开 `add`/`min`/`max`/`abs`/`pow`/`sum`(本文件全部 `pg` 前缀);
//   ⑤ avoid function names `add`/`min`/`max`/`abs`/`pow`/`sum` (everything here carries a `pg` prefix);
//   ⑥ `ui_msg_fetch_wait(ms)` 的返回值就是那条消息(0 = 超时);
//   ⑥ `ui_msg_fetch_wait(ms)` returns the message itself (0 = timeout);
//   ⑦ 触摸坐标取 `ui_msg_get_a()` / `ui_msg_get_b()`。
//   ⑦ touch coordinates come from `ui_msg_get_a()` / `ui_msg_get_b()`.
//
// 跑法 —— 手机:`vml run examples/swift/pong.swift`
// How to run — on the phone: `vml run examples/swift/pong.swift`
// 跑法 —— 桌面:`vmlcli Examples/swift/pong.swift --screen 480x640 --frames /tmp/fr`
// How to run — on the desktop: `vmlcli Examples/swift/pong.swift --screen 480x640 --frames /tmp/fr`

#include <vml_ui.swift>

// 状态表 —— **只用一个全局数组**(见文件头 ①),下标分区:
// State table — **one global array only** (see header ①), partitioned by index:
//   0=左板 y 1=右板 y 2=球 x 3=球 y 4=球 vx 5=球 vy
//   0=left paddle y 1=right paddle y 2=ball x 3=ball y 4=ball vx 5=ball vy
//   6=左分 7=右分 8=w 9=h 10=padW 11=padH 12=ballR 13=lang 14=frames 15=seed
//   16=结束标志 17=发球方向 18=最近一次触摸 y(验收读数)
var A = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

// 16 位 LCG(本前端的整数会溢出,别照搬 C 的 32 位公式)
// 16-bit LCG (integers overflow here; do not copy C's 32-bit formula)
func pgRnd(n: Int) -> Int {
    A[15] = (A[15] * 1103 + 12345) % 32768
    return (A[15] / 256) % n
}

func pgLayout() {
    var w = ui_scr_get_w()
    var h = ui_scr_get_h()
    if w <= 0 { w = 360 }
    if h <= 0 { h = 620 }
    A[8] = w
    A[9] = h
    var pw = w / 28
    if pw < 8 { pw = 8 }
    A[10] = pw
    var ph = h / 6
    if ph < 40 { ph = 40 }
    A[11] = ph
    var br = w / 40
    if br < 4 { br = 4 }
    A[12] = br
}

// 发球:球回中央,方向由 A[17] 决定
// Serve: the ball goes back to the centre, direction from A[17]
func pgServe() {
    A[2] = A[8] / 2
    A[3] = A[9] / 2
    if A[17] == 0 {
        A[4] = 0 - 5
        A[17] = 1
    } else {
        A[4] = 5
        A[17] = 0
    }
    if pgRnd(2) == 0 { A[5] = 0 - 3 } else { A[5] = 3 }
}

func pgNewGame() {
    A[0] = A[9] / 2
    A[1] = A[9] / 2
    A[6] = 0
    A[7] = 0
    A[16] = 0
    A[17] = 0
    pgServe()
}

// 一拍:球走一步、边界反弹、板反弹、AI 追球、记分
// One tick: move the ball, bounce on edges, bounce on paddles, AI chases, score
func pgStep() {
    A[2] = A[2] + A[4]
    A[3] = A[3] + A[5]

    // 上下反弹
    // Bounce off top/bottom
    if A[3] < A[12] {
        A[3] = A[12]
        A[5] = 0 - A[5]
    }
    if A[3] > A[9] - A[12] {
        A[3] = A[9] - A[12]
        A[5] = 0 - A[5]
    }

    // 左板反弹(球在左板右缘附近、且落在板的高度范围内)
    // Left paddle bounce (ball near the paddle's right edge and within its height)
    if A[4] < 0 && A[2] <= 10 + A[10] + A[12] && A[2] >= 6 {
        var top = A[0] - A[11] / 2
        if A[3] >= top && A[3] <= top + A[11] {
            A[2] = 10 + A[10] + A[12]
            A[4] = 0 - A[4] - 1
            if A[4] < 0 - 14 { A[4] = 0 - 14 }
        }
    }

    // 右板反弹
    // Right paddle bounce
    if A[4] > 0 && A[2] >= A[8] - 10 - A[10] - A[12] && A[2] <= A[8] - 6 {
        var top = A[1] - A[11] / 2
        if A[3] >= top && A[3] <= top + A[11] {
            A[2] = A[8] - 10 - A[10] - A[12]
            A[4] = 0 - A[4] + 1
            if A[4] > 14 { A[4] = 14 }
        }
    }

    // 出界记分
    // Out of bounds: score
    if A[2] < 0 - A[12] {
        A[7] = A[7] + 1
        if A[7] >= 5 { A[16] = 1 }
        pgServe()
    }
    if A[2] > A[8] + A[12] {
        A[6] = A[6] + 1
        if A[6] >= 5 { A[16] = 1 }
        pgServe()
    }

    // AI:右板每拍向球靠几像素(不瞬移)
    // AI: the right paddle inches toward the ball each tick (no teleporting)
    if A[1] < A[3] { A[1] = A[1] + 4 }
    if A[1] > A[3] { A[1] = A[1] - 4 }

    // 左板(手指控制)也要夹在屏内
    // Keep the left paddle inside the screen
    if A[0] < A[11] / 2 { A[0] = A[11] / 2 }
    if A[0] > A[9] - A[11] / 2 { A[0] = A[9] - A[11] / 2 }
    if A[1] < A[11] / 2 { A[1] = A[11] / 2 }
    if A[1] > A[9] - A[11] / 2 { A[1] = A[9] - A[11] / 2 }
}

func pgDraw() {
    ui_2d_clear(-15724520)

    // 中线:一串小方块
    // Centre line: a run of small blocks
    var y = 10
    while y + 16 <= A[9] - 10 {
        ui_2d_rect(A[8] / 2 - 2, y, 4, 16, -14013898, 1, 0, 0)
        y = y + 32
    }

    // 左右板
    // Both paddles
    ui_2d_rect(10, A[0] - A[11] / 2, A[10], A[11], -11409298, 1, 0, 4)
    ui_2d_rect(A[8] - 10 - A[10], A[1] - A[11] / 2, A[10], A[11], -11890471, 1, 0, 4)

    // 球
    // Ball
    ui_2d_circle(A[2], A[3], A[12], -1513232, 1, 0)

    // 比分
    // Score
    ui_2d_text(A[8] / 2 - 70, 28, numToStr(v: A[6]), -1513232, 26, VML_ANCHOR_CENTER)
    ui_2d_text(A[8] / 2 + 70, 28, numToStr(v: A[7]), -1513232, 26, VML_ANCHOR_CENTER)

    if A[16] != 0 {
        if A[13] == 0 {
            if A[6] >= 5 { ui_2d_text(A[8] / 2, A[9] / 2 - 40, "你赢了!点一下再来", -11409298, 20, VML_ANCHOR_CENTER) }
            else { ui_2d_text(A[8] / 2, A[9] / 2 - 40, "电脑赢了,点一下再来", -2069424, 20, VML_ANCHOR_CENTER) }
        } else {
            if A[6] >= 5 { ui_2d_text(A[8] / 2, A[9] / 2 - 40, "You win! Tap to retry", -11409298, 20, VML_ANCHOR_CENTER) }
            else { ui_2d_text(A[8] / 2, A[9] / 2 - 40, "AI wins - tap to retry", -2069424, 20, VML_ANCHOR_CENTER) }
        }
    } else {
        if A[13] == 0 { ui_2d_text(A[8] / 2, 58, "左半屏滑动控制球板,先到 5 分", -6643536, 11, VML_ANCHOR_CENTER) }
        else { ui_2d_text(A[8] / 2, 58, "Drag on the left half; first to 5", -6643536, 11, VML_ANCHOR_CENTER) }
    }
    ui_2d_present()
}

func numToStr(v: Int) -> String {
    if v == 0 { return "0" }
    var s = ""
    var n = v
    while n > 0 {
        var d = n % 10
        if d == 0 { s = "0" + s }
        else if d == 1 { s = "1" + s }
        else if d == 2 { s = "2" + s }
        else if d == 3 { s = "3" + s }
        else if d == 4 { s = "4" + s }
        else if d == 5 { s = "5" + s }
        else if d == 6 { s = "6" + s }
        else if d == 7 { s = "7" + s }
        else if d == 8 { s = "8" + s }
        else { s = "9" + s }
        n = n / 10
    }
    return s
}

func pgMain() {
    A[13] = ui_scr_get_language()
    var lang = A[13]
    if lang == 0 { ui_win_open_ex("对打", 0, 0, VML_WIN_PORTRAIT, VML_WIN_NO_GAMEPAD) }
    else { ui_win_open_ex("Pong", 0, 0, VML_WIN_PORTRAIT, VML_WIN_NO_GAMEPAD) }

    pgLayout()
    A[15] = 20262
    pgNewGame()
    ui_scr_set_keep_on(1)
    pgDraw()

    var tid = ui_timer_set(33, 1)

    while ui_win_is_closed() == 0 {
        var t = ui_msg_fetch_wait(33)
        if t == 0 { continue }
        if t == 10 { break }

        if t == 9 {
            A[14] = A[14] + 1
            if A[16] == 0 { pgStep() }
            pgDraw()
            continue
        }

        if t == 6 || t == 4 {
            var ty = ui_msg_get_b()
            A[18] = ty
            if A[16] != 0 { pgNewGame() }
            else { A[0] = ty }
            pgDraw()
            continue
        }

        if t == 7 {
            var ty2 = ui_msg_get_b()
            A[18] = ty2
            if A[16] == 0 { A[0] = ty2 }
            pgDraw()
            continue
        }

        if t == 11 {
            pgLayout()
            pgDraw()
            continue
        }

        if t == 1 {
            var k = ui_msg_get_a()
            if k == 27 { break }
            if k == 13 || k == 82 { pgNewGame() }
            pgDraw()
            continue
        }
    }

    ui_timer_kill(tid)
    ui_scr_set_keep_on(0)
    ui_win_close()

    // 无头验收读数
    // Headless acceptance readouts
    println("swpong: scoreL=" + numToStr(v: A[6]))
    println("swpong: scoreR=" + numToStr(v: A[7]))
    println("swpong: ended=" + numToStr(v: A[16]))
    println("swpong: frames=" + numToStr(v: A[14]))
    println("swpong: done")
}

pgMain()