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

python/app/snake.py · 8518 字节 · 下载原文

▶ 在浏览器里试玩

# snake.py —— 贪吃蛇(VML 的 Python 前端)
# snake.py -- Snake (VML's Python frontend)
#
# 与 `Examples/c/app/snake.c` **同一套玩法**,区别只在语言:
# Same rules as `Examples/c/app/snake.c`; only the language differs:
#   界面走共享调用库(`Lib/shared/src/vmlui.c` → python 的 `Libs`),
#   the UI goes through the shared call library (attached to python's `Libs`),
#   所以这里的 `ui_*` 与 C 那边**同签名**(`py` 是逐参数转发的)。
#   so the `ui_*` calls here have the **same signatures** as on the C side
#   (`py` forwards every parameter).
#
# 玩法:蛇每 STEP_TICKS 拍走一格,吃豆变长加分;撞墙或撞自己结束;
# Rules: the snake advances one cell every STEP_TICKS ticks; eating a bean grows it and scores;
# 点屏幕四边转向(离哪边最近就往那边走),ESC 重开。
# tapping a screen edge turns it (whichever side is nearest); ESC restarts.

# 显式引入共享库声明(GenLib 生成,勿手写):形参个数写错在**编译期**报错。
# Explicitly import the shared-library declarations (generated by GenLib, do not hand-write):
# a wrong argument count becomes a **compile-time** error.
import vml_ui

MAX_FRAMES = 4000
STEP_TICKS = 4
GW = 16
GH = 16

SW = 360
SH = 620
CELL = 20
OX = 20
OY = 80

body_x = [0] * 256
body_y = [0] * 256
length = 3
dir = 0            # 0=右 1=下 2=左 3=上
next_dir = 0
food_x = 5
food_y = 5
score = 0
alive = 1
seed = 20261


def rnd(n):
    # ⚠ **16 位** LCG:本前端整数是 32 位,C 的 `seed * 1103515245 % 4294967296` 会溢出
    #   ⇒ 每次返回 0(实测:豆子永远在 (0,0))。16 位状态不溢出,序列照样可复现。
    # ⚠ A **16-bit** LCG: this frontend's ints are 32-bit, so the C formula
    #   `seed * 1103515245 % 4294967296` overflows => always 0 (measured: the bean always
    #   sat at (0,0)). A 16-bit state does not overflow and stays reproducible.
    global seed
    seed = (seed * 1103 + 12345) % 32768
    return (seed // 256) % n


def relayout():
    global SW, SH, CELL, OX, OY, GW, GH
    SW = ui_scr_get_w()
    SH = ui_scr_get_h()
    if SW <= 0:
        SW = 360
    if SH <= 0:
        SH = 620
    CELL = SW // GW
    if CELL < 6:
        CELL = 6
    GH = (SH - 100) // CELL
    OX = (SW - GW * CELL) // 2
    OY = 70


def has(x, y):
    i = 0
    while i < length:
        if body_x[i] == x and body_y[i] == y:
            return 1
        i = i + 1
    return 0


def place_food():
    global food_x, food_y
    k = 0
    while k < 300:
        food_x = rnd(GW)
        food_y = rnd(GH)
        if has(food_x, food_y) == 0:
            return
        k = k + 1


def new_game():
    global length, dir, next_dir, score, alive
    length = 3
    dir = 0
    next_dir = 0
    score = 0
    alive = 1
    body_x[0] = GW // 2
    body_y[0] = GH // 2
    body_x[1] = GW // 2 - 1
    body_y[1] = GH // 2
    body_x[2] = GW // 2 - 2
    body_y[2] = GH // 2
    place_food()


def draw():
    ui_2d_clear(0xFF101018)
    i = 0
    while i < length:
        c = 0xFF51E86E
        if i > 0:
            c = 0xFF2E7D4F
        ui_2d_rect(OX + body_x[i] * CELL + 1, OY + body_y[i] * CELL + 1,
                          CELL - 2, CELL - 2, c, 1, 0, 2)
        i = i + 1
    ui_2d_rect(OX + food_x * CELL + 2, OY + food_y * CELL + 2,
                      CELL - 4, CELL - 4, 0xFFE06C50, 1, 0, CELL // 2)
    ui_2d_text(10, 24, str(score), 0xFFFFFFFF, 15, 0)
    if alive == 0:
        ui_2d_text(SW // 2, SH - 16, "crashed - tap to restart", 0xFF9AA0B0, 12, 1)
    else:
        ui_2d_text(SW // 2, SH - 16, "tap a screen edge", 0xFF9AA0B0, 12, 1)
    ui_2d_present()


def main():
    global dir, next_dir, length, score, alive, food_x, food_y, seed

    relayout()
    ui_win_open_ex("snake.py", 0, 0, 1, 0)
    relayout()
    new_game()
    draw()

    # ⚠ 步进要**开定时器**:宿主不会凭空发 t==9,没有 `ui_timer_set` 这一局就是
    #   一张静止的初始画面(实测:只落 1 帧、蛇永远不走 —— 用户 2026-11-14 报「没写完」)。
    # ⚠ The step must **arm a timer**: the host never emits t==9 on its own, so without
    #   `ui_timer_set` the game is one frozen initial frame (measured: exactly 1 frame,
    #   the snake never advances -- the 2026-11-14 "not finished" report).
    tid = ui_timer_set(40, 1)

    msg = [0, 0, 0, 0]
    frames = 0
    tick = 0
    done = 0
    while done == 0 and ui_win_is_closed() == 0:
        # ⚠ 阻塞等的**返回值就是那条消息**:以前这里 `ui_msg_fetch_wait(40)` 不收返回值、
        #   再 `ui_msg_fetch()` 一次,定时器消息正好被丢掉 ⇒ 蛇整局不动(2026-11-14 实测)。
        # ⚠ The blocking wait's **return value is the message itself**: the old code ignored it
        #   and fetched again, which swallowed exactly the timer message -> the snake never moved (measured 2026-11-14).
        t = ui_msg_fetch()
        if t == 0:
            t = ui_msg_fetch_wait(40)
        if t == 0:
            continue

        if t == 6 or t == 4:                      # 触摸/鼠标按下:点四边转向
            # ⚠ 坐标从**这条消息**里取(`ui_msg_get_a/b`);`ui_touch_get_x/y` 是宿主缓存的
            #   "当前触点",桌面宿主不填它 ⇒ 读到 (0,0),点哪都变成「往左」(2026-11-14 实测)。
            # ⚠ Take the coordinates **from this message** (`ui_msg_get_a/b`); `ui_touch_get_x/y`
            #   is the host's cached "current touch", which the desktop host never fills -> (0,0),
            #   so every tap became "left" (measured 2026-11-14).
            x = ui_msg_get_a()
            y = ui_msg_get_b()
            # 撞死后点任意处重开(C 版 `snake.c` 同一行为;以前这里没有这一支,
            # 蛇一撞就永久停在「crashed」画面上,只能关窗 —— 用户 2026-11-14 报的「没写完」)。
            # After a crash, a tap anywhere restarts (same as `snake.c`; this branch used to be
            # missing, so the snake stayed frozen on "crashed" and only closing the window helped).
            if alive == 0:
                new_game()
                draw()
                continue
            dl = x
            dr = SW - x
            dt = y
            db = SH - y
            want = dir
            if dl <= dr and dl <= dt and dl <= db:
                want = 2
            elif dr <= dt and dr <= db:
                want = 0
            elif dt <= db:
                want = 3
            else:
                want = 1
            if (want + 2) % 4 != dir:
                next_dir = want
            draw()
            continue

        # 键盘这条在 Python 绑定里没有 ui_key_fetch(未导出)⇒ 只用触摸转向

        if t == 9:                                # 定时器:走一步
            frames = frames + 1
            if frames >= MAX_FRAMES:
                done = 1
            tick = tick + 1
            if tick >= STEP_TICKS and alive == 1:
                tick = 0
                dir = next_dir
                nx = body_x[0]
                ny = body_y[0]
                if dir == 0:
                    nx = nx + 1
                elif dir == 2:
                    nx = nx - 1
                elif dir == 1:
                    ny = ny + 1
                else:
                    ny = ny - 1

                if nx < 0 or ny < 0 or nx >= GW or ny >= GH:
                    alive = 0
                else:
                    i = 0
                    while i < length - 1:
                        if body_x[i] == nx and body_y[i] == ny:
                            alive = 0
                        i = i + 1

                if alive == 1:
                    i = length - 1
                    while i > 0:
                        body_x[i] = body_x[i - 1]
                        body_y[i] = body_y[i - 1]
                        i = i - 1
                    body_x[0] = nx
                    body_y[0] = ny
                    if nx == food_x and ny == food_y:
                        if length < 256:
                            length = length + 1
                            body_x[length - 1] = body_x[length - 2]
                            body_y[length - 1] = body_y[length - 2]
                        score = score + 10
                        place_food()
            draw()
            continue

    ui_timer_kill(tid)
    ui_win_close()
    return 0


main()