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

kotlin/app/whack.kt · 8793 字节 · 下载原文

▶ 在浏览器里试玩

// 打地鼠 —— 用 **Kotlin** 写的手机小游戏
// Whack-a-mole — a small phone game written in **Kotlin**
//
// 玩法(与 `Examples/c/app/whack.c` / `Examples/python/app/whack.py` 同一套):
// Gameplay (same rules as the C / Python versions):
//   · 3×3 九个洞,每 SHOW_TICKS 拍有一个洞冒出地鼠;
//   · nine holes in a 3x3; every SHOW_TICKS ticks one hole pops a mole;
//   · 在它缩回去之前点中 +1 分,超时没点中扣一条命;三条命用完结束;
//   · tapping it before it ducks back scores +1; missing it costs a life; three lives ends the run;
//   · 结束后点屏幕 / ESC 重开。
//   · after the run ends, tap the screen / press ESC for a new one.
//
// ## "计时归谁管"是这一类游戏的关键
// ## **Who owns the clock** is the key thing in this genre
//
// 地鼠的存活时间记在**拍数**上(`gMoleTicks`),不是 `time()` —— 定时器就是心跳,
// "一只地鼠活多少拍"可计算、不随机器快慢漂移。
// A mole's lifetime is counted in **ticks** (`gMoleTicks`), not `time()` -- the timer is the
// heartbeat, so "how many ticks a mole stays" is computable and does not drift with the machine.
//
// ## 这一份用到的 Kotlin 特性
// ## Kotlin features used here
//
//   · **顶层 `var` 状态**与 `const val` 常量;
//   · **file-level `var` state** and `const val` constants;
//   · **字符串模板**(`"$gScore"`)画分数/命数;
//   · **string templates** (`"$gScore"`) for the score/lives;
//   · **多参数函数**(`fun tap(tx: Int, ty: Int)` / `fun holeRect(...)` 的拆分写法);
//   · **multi-parameter functions** (`fun tap(tx: Int, ty: Int)` etc.).
//
// 跑法 —— 手机:`vml run examples/kotlin/whack.kt`
// How to run — on the phone: `vml run examples/kotlin/whack.kt`
// 跑法 —— 桌面:`vmlcli Examples/kotlin/whack.kt --screen 480x640 --frames /tmp/fr`
// How to run — on the desktop: `vmlcli Examples/kotlin/whack.kt --screen 480x640 --frames /tmp/fr`

// ── 显式引用:下面用到的 `ui_*` 来自共享库 vmlui.vml ──────────────────
// ── Explicit reference: the `ui_*` used below come from the shared library vmlui.vml ──
// ⚠ `.*` 必须有:`import vmlui`(无 `.*`)会被 `ExtractImports` 的正则**静默忽略**。
// ⚠ The `.*` is required: `import vmlui` (without `.*`) is silently ignored.
// ⚠ 但整行删掉也照样编、照样跑 —— 前端靠 `ui_` 前缀**自动**链 `vmlui.vml`。
// ⚠ Deleting the line still compiles and runs — the frontend auto-links `vmlui.vml` from the `ui_` prefix.
#include <vml_ui.kt>
import vmlui.*

const val MAX_FRAMES = 6000
const val GRID = 3
const val SHOW_TICKS = 14        // 一只地鼠活 14 拍 ≈ 0.7 秒 / a mole lives 14 ticks ~= 0.7 s

const val C_BG = 0xFF101018
const val C_HOLE = 0xFF1A1A24
const val C_MOLE = 0xFFD9B44A
const val C_TEXT = 0xFFE8E8F0
const val C_DIM = 0xFF9AA0B0
const val C_MISS = 0xFFE06C50

var LANG = 0
var SW = 360
var SH = 620
var CELL = 120
var OX = 0
var OY = 130
// 矮屏(240x240 一类)用压缩排版
// Compact layout flag for short screens (240x240 etc.)
var COMPACT = 0

var gMoleAt = -1
var gMoleTicks = 0
var gWaitTicks = 6
var gScore = 0
var gLives = 3
var gOver = 0
var gHitFlash = 0
var gSeed = 20267
var gMaxPrims = 0

/// 确定性伪随机(验收要能复现同一局)
/// Deterministic PRNG (acceptance needs to reproduce the same run)
fun rnd(n: Int): Int {
    gSeed = (gSeed * 1103 + 12345) % 32768
    return (gSeed / 256) % n
}

fun relayout() {
    SW = ui_scr_get_w()
    SH = ui_scr_get_h()
    if (SW <= 0) { SW = 360 }
    if (SH <= 0) { SH = 620 }
    COMPACT = 0
    OY = 130
    var bottom = 48
    if (SH < 420) {
        COMPACT = 1
        OY = 56
        bottom = 50
    }
    // 九宫格同时受宽、高(扣掉顶部得分行与底部提示)约束
    // The 3x3 grid respects both width and height (minus the top score line and the bottom hint)
    var side = SW - 24
    var sideH = SH - OY - bottom
    if (sideH < side) { side = sideH }
    CELL = side / GRID
    if (CELL < 8) { CELL = 8 }
    OX = (SW - GRID * CELL) / 2
}

fun pickHole() {
    gMoleAt = rnd(GRID * GRID)
    gMoleTicks = SHOW_TICKS
}

fun newGame() {
    gScore = 0
    gLives = 3
    gOver = 0
    gHitFlash = 0
    gMoleAt = -1
    gWaitTicks = 6
}

fun draw() {
    ui_2d_clear(C_BG)

    var i = 0
    while (i < GRID * GRID) {
        var cx = OX + (i % GRID) * CELL + CELL / 2
        var cy = OY + (i / GRID) * CELL + CELL / 2
        var r = CELL / 3
        ui_2d_ellipse(cx, cy + r / 3, r + CELL / 12, r / 2 + CELL / 20, C_HOLE, 1, 0)
        if (i == gMoleAt) {
            var mc = C_MOLE
            if (gHitFlash == 1) { mc = 0xFFFFFFFF }
            ui_2d_circle(cx, cy, r, mc, 1, 0)
            ui_2d_circle(cx - r / 3, cy - r / 4, r / 5, 0xFF101018, 1, 0)
            ui_2d_circle(cx + r / 3, cy - r / 4, r / 5, 0xFF101018, 1, 0)
        }
        i = i + 1
    }

    ui_2d_text(10, 24, "$gScore", C_TEXT, 18, VML_ANCHOR_LEFT)
    if (LANG == 0) { ui_2d_text(10, 48, "得分", C_DIM, 10, VML_ANCHOR_LEFT) }
    else { ui_2d_text(10, 48, "score", C_DIM, 10, VML_ANCHOR_LEFT) }
    ui_2d_text(SW - 10, 24, "$gLives", C_MISS, 18, VML_ANCHOR_RIGHT)
    if (LANG == 0) { ui_2d_text(SW - 10, 48, "命", C_DIM, 10, VML_ANCHOR_RIGHT) }
    else { ui_2d_text(SW - 10, 48, "lives", C_DIM, 10, VML_ANCHOR_RIGHT) }

    // 矮屏把提示行贴紧九宫格、字号缩小
    // On short screens the hint hugs the grid with a smaller font
    var hintDy = 30
    var hintFs = 12
    var overFs = 16
    if (COMPACT == 1) { hintDy = 16; hintFs = 10; overFs = 11 }
    if (gOver == 1) {
        if (LANG == 0) { ui_2d_text(SW / 2, OY + GRID * CELL + hintDy, "结束,点一下再来", C_TEXT, overFs, VML_ANCHOR_CENTER) }
        else { ui_2d_text(SW / 2, OY + GRID * CELL + hintDy, "Over - tap to retry", C_TEXT, overFs, VML_ANCHOR_CENTER) }
    } else {
        if (LANG == 0) { ui_2d_text(SW / 2, OY + GRID * CELL + hintDy, "冒头就点它", C_DIM, hintFs, VML_ANCHOR_CENTER) }
        else { ui_2d_text(SW / 2, OY + GRID * CELL + hintDy, "Tap the mole when it pops", C_DIM, hintFs, VML_ANCHOR_CENTER) }
    }

    var n = ui_res_get_count(0)
    if (n > gMaxPrims) { gMaxPrims = n }
    ui_2d_present()
}

fun tap(tx: Int, ty: Int) {
    if (gOver == 1) {
        newGame()
        return
    }
    var x = (tx - OX) / CELL
    var y = (ty - OY) / CELL
    if (x < 0 || y < 0 || x >= GRID || y >= GRID) { return }
    var idx = y * GRID + x
    if (idx == gMoleAt) {
        gScore = gScore + 1
        gMoleAt = -1
        gWaitTicks = 4 + rnd(4)
        gHitFlash = 1
    }
}

fun main() {
    LANG = ui_scr_get_language()

    relayout()
    if (LANG == 0) { ui_win_open_ex("打地鼠", 0, 0, VML_WIN_PORTRAIT, VML_WIN_NO_GAMEPAD) }
    else { ui_win_open_ex("Whack", 0, 0, VML_WIN_PORTRAIT, VML_WIN_NO_GAMEPAD) }
    ui_scr_lock_orientation(VML_LOCK_PORTRAIT)
    relayout()
    newGame()
    draw()

    var tid = ui_timer_set(50, 1)
    var frames = 0
    var done = 0
    while (done == 0 && ui_win_is_closed() == 0) {
        var t = ui_msg_fetch_wait(50)
        if (t == 10) { break }                  // MSG_WINDOWCLOSE

        if (t == 6 || t == 4) {                 // MSG_TOUCHDOWN / MSG_MOUSEDOWN
            tap(ui_msg_get_a(), ui_msg_get_b())
            draw()
            continue
        }

        if (t == 1) {                           // MSG_KEYDOWN
            var k = ui_msg_get_a()
            if (k == 27 || k == 82) { newGame(); draw() }
            continue
        }

        if (t == 11) { relayout(); draw(); continue }   // MSG_WINDOWRESIZE
        if (t == 12) { continue }                       // MSG_WINDOWORIENT

        if (t == 9) {                           // MSG_TIMER
            frames = frames + 1
            if (frames >= MAX_FRAMES) { done = 1 }
            if (gOver == 0) {
                gHitFlash = 0
                if (gMoleAt >= 0) {
                    gMoleTicks = gMoleTicks - 1
                    if (gMoleTicks <= 0) {
                        // 没点中:扣命 / missed: lose a life
                        gMoleAt = -1
                        gLives = gLives - 1
                        gWaitTicks = 8
                        if (gLives <= 0) {
                            gOver = 1
                            done = 1
                        }
                    }
                } else {
                    gWaitTicks = gWaitTicks - 1
                    if (gWaitTicks <= 0) { pickHole() }
                }
            }
            draw()
            continue
        }
    }

    ui_timer_kill(tid)
    ui_win_close()
}

main()