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

python/app/memory.py · 8027 字节 · 下载原文

▶ 在浏览器里试玩

# memory.py —— 记忆翻牌(VML 的 Python 前端)
# memory.py -- Memory matching (VML's Python frontend)
#
# 与 `Examples/c/app/memory.c` **同一套玩法**:
# Same rules as `Examples/c/app/memory.c`:
#   · 4×4 共 8 对;点一张翻开,再点一张;
#   · 4x4, eight pairs; tap to flip one, tap another;
#   · 一样就留在明面,不一样 0.4 秒后扣回去;全部配对完成即通关。
#   · an equal pair stays revealed, a different pair flips back after 0.4 s; clear all pairs to win.
#
# 这里刻意演示**"延时动作"怎么写**:翻错的两张不能立刻扣回去(用户看不到第二张是什么),
# What this sample deliberately shows is **how to write a delayed action**: a wrong pair must not
# flip back immediately (the player would never see the second card), so we keep a countdown in
# **ticks** and decrement it each frame -- no extra thread, no sleep.
# 所以记一个倒计时拍数,主循环每拍减一,减到 0 才扣。
#
# ⚠ 棋盘/状态都是**平铺**列表(本前端没有二维数组,嵌套列表写不生效)。
# ⚠ Boards/state are **flat** lists (no 2-D arrays here; nested-list writes do not take effect).

# 显式引入共享库声明(GenLib 生成,勿手写)。
# Explicitly import the shared-library declarations (generated by GenLib, do not hand-write).
# ⚠ 注释行别以 `Import` / `Include` 开头 —— 前端会把整行当 `#include` 指令。
# ⚠ Never start a comment line with `Import` / `Include` -- it becomes a `#include` directive.
import vml_ui

MAX_FRAMES = 8000
N = 4
PAIRS = 8
HIDE_TICKS = 8          # 8 拍 × 50ms ≈ 0.4 秒 / 8 ticks x 50 ms ~= 0.4 s

C_BG = 0xFF101018
C_BACK = 0xFF2A2A36
C_TEXT = 0xFFE8E8F0
C_DIM = 0xFF9AA0B0

PAIR_COLOR = [0xFFE06C50, 0xFFD9B44A, 0xFF51E86E, 0xFF4A90D9,
              0xFF9B6CF0, 0xFFE06CA8, 0xFF4AD9C6, 0xFFC0C040]

SW = 360
SH = 620
CELL = 80
OX = 20
OY = 110
LANG = 0

pair_of = [-1] * (N * N)    # -1 = 已配好 / already matched
up = [0] * (N * N)          # 翻开中 / currently face up
first_x = -1
first_y = -1
hide_countdown = 0
moves = 0
matched = 0
won = 0
seed = 20265


def rnd(n):
    # 16 位 LCG(32 位整数下 C 的 32 位 LCG 会溢出、恒返回 0,见 game2048.py)。
    # 16-bit LCG (the C 32-bit LCG overflows with 32-bit ints and always returns 0; see game2048.py).
    global seed
    seed = (seed * 1103 + 12345) % 32768
    return (seed // 256) % n


def relayout():
    global SW, SH, CELL, OX, OY
    SW = ui_scr_get_w()
    SH = ui_scr_get_h()
    if SW <= 0:
        SW = 360
    if SH <= 0:
        SH = 620
    # 棋盘取「宽度」与「扣掉顶栏/底部提示后的高度」里较小的那个 ——
    # 方形小画布上原来的 `SW < SH - 140` 分支会让棋盘只剩 70px。
    # The board takes the smaller of "width" and "height after header/footer" --
    # the old `SW < SH - 140` branch left a 70px board on a square tiny canvas.
    OY = 56
    side = SW - 16
    tall = SH - OY - 44
    if tall < side:
        side = tall
    CELL = side // N
    if CELL < 6:
        CELL = 6
    OX = (SW - N * CELL) // 2


def new_game():
    global first_x, first_y, hide_countdown, moves, matched, won
    # 先铺成 0,0,1,1,2,2…再洗牌(Fisher–Yates,自带随机源)
    # Lay out 0,0,1,1,2,2... then shuffle (Fisher-Yates with our own RNG).
    x = 0
    while x < N:
        y = 0
        while y < N:
            pair_of[x * N + y] = (y * N + x) // 2
            up[x * N + y] = 0
            y = y + 1
        x = x + 1
    i = N * N - 1
    while i > 0:
        j = rnd(i + 1)
        ax = i // N
        ay = i % N
        bx = j // N
        by = j % N
        t = pair_of[ax * N + ay]
        pair_of[ax * N + ay] = pair_of[bx * N + by]
        pair_of[bx * N + by] = t
        i = i - 1
    first_x = -1
    first_y = -1
    hide_countdown = 0
    moves = 0
    matched = 0
    won = 0


def draw():
    ui_2d_clear(C_BG)

    x = 0
    while x < N:
        y = 0
        while y < N:
            px = OX + x * CELL
            py = OY + y * CELL
            p = pair_of[x * N + y]
            if p < 0:
                # 已配对:淡淡地留个印子
                # Matched: leave a faint imprint.
                ui_2d_rect(px + 3, py + 3, CELL - 6, CELL - 6, 0xFF16161E, 1, 0, 6)
            elif up[x * N + y] == 1:
                ui_2d_rect(px + 3, py + 3, CELL - 6, CELL - 6, PAIR_COLOR[p], 1, 0, 8)
                # 用数字当牌面(Python 前端里字符串下标取字符不可靠)
                # Use a number as the face (string subscripting is unreliable on this frontend).
                ui_2d_text(px + CELL // 2, py + CELL // 2 + CELL // 8,
                           str(p + 1), 0xFF101018, CELL // 2, VML_ANCHOR_CENTER)
            else:
                ui_2d_rect(px + 3, py + 3, CELL - 6, CELL - 6, C_BACK, 1, 0, 8)
            y = y + 1
        x = x + 1

    ui_2d_text(10, 22, str(moves), C_TEXT, 15, VML_ANCHOR_LEFT)
    if LANG == 0:
        ui_2d_text(10, 42, "步数", C_DIM, 10, VML_ANCHOR_LEFT)
    else:
        ui_2d_text(10, 42, "moves", C_DIM, 10, VML_ANCHOR_LEFT)

    if won == 1:
        if LANG == 0:
            msg = "全配好了!点一下再来"
        else:
            msg = "All matched! Tap for a new one"
        ui_2d_text(SW // 2, OY + N * CELL + 28, msg, C_TEXT, 15, VML_ANCHOR_CENTER)
    else:
        if LANG == 0:
            msg = "翻两张一样的"
        else:
            msg = "Flip two that match"
        ui_2d_text(SW // 2, OY + N * CELL + 28, msg, C_DIM, 12, VML_ANCHOR_CENTER)
    ui_2d_present()


def tap(tx, ty):
    global first_x, first_y, hide_countdown, moves, matched, won
    if won == 1:
        new_game()
        return
    x = (tx - OX) // CELL
    y = (ty - OY) // CELL
    if x < 0 or y < 0 or x >= N or y >= N:
        return
    i = x * N + y
    if pair_of[i] < 0 or up[i] == 1 or hide_countdown > 0:
        return

    up[i] = 1
    if first_x < 0:
        first_x = x
        first_y = y
        return

    moves = moves + 1
    fi = first_x * N + first_y
    if pair_of[fi] == pair_of[i]:
        pair_of[fi] = -1
        pair_of[i] = -1
        matched = matched + 2
        if matched >= N * N:
            won = 1
        first_x = -1
    else:
        hide_countdown = HIDE_TICKS       # 记个倒计时,主循环到点扣回
                                          # Countdown; the main loop flips them back at 0.


def main():
    global LANG, hide_countdown, first_x
    LANG = ui_scr_get_language()

    relayout()
    ui_win_open_ex("记忆翻牌" if LANG == 0 else "Memory (py)", 0, 0, 1, 0)
    relayout()
    new_game()
    draw()

    tid = ui_timer_set(50, 1)
    frames = 0
    done = 0
    while done == 0 and ui_win_is_closed() == 0:
        t = ui_msg_fetch()
        if t == 0:
            t = ui_msg_fetch_wait(50)
        if t == 0:
            continue

        if t == 6 or t == 4:
            tap(ui_msg_get_a(), ui_msg_get_b())
            draw()
            continue

        if t == 1:
            if ui_msg_get_a() == 27:
                new_game()
                draw()
            continue

        if t == 11:
            relayout()
            draw()
            continue

        if t == 9:
            frames = frames + 1
            if frames >= MAX_FRAMES:
                done = 1
            if hide_countdown > 0:
                hide_countdown = hide_countdown - 1
                if hide_countdown == 0:
                    # 扣回所有翻开的牌
                    # Flip every face-up card back.
                    x = 0
                    while x < N:
                        y = 0
                        while y < N:
                            up[x * N + y] = 0
                            y = y + 1
                        x = x + 1
                    first_x = -1
            draw()
            continue

        if t == 10:
            break

    ui_timer_kill(tid)
    ui_win_close()
    return 0


main()