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

python/app/game2048.py · 11731 字节 · 下载原文

▶ 在浏览器里试玩

# game2048.py —— 2048(VML 的 Python 前端)
# game2048.py -- 2048 (VML's Python frontend)
#
# 与 `Examples/c/app/game2048.c` **同一套玩法**,区别只在语言:
# Same rules as `Examples/c/app/game2048.c`; only the language differs:
#   · 4×4 棋盘,方向键 / 点屏幕四边往一个方向滑;
#   · a 4x4 board; arrow keys / tapping one of the four screen edges slide everything that way;
#   · 相同数字相撞合成两倍、得分加上合成值,每滑一次冒一个新数字(10% 是 4);
#   · equal numbers merge and score the merged value; each slide spawns a new tile (4 with 10% odds);
#   · 到 2048 算赢(还能继续),没空格且四邻无相等算输。
#   · reaching 2048 wins (you may keep playing); no empty cell and no adjacent equal pair loses.
#
# ⚠ 本前端的两条硬约束(写 snake/tetris 时量到的,这份照样遵守):
# ⚠ Two hard rules of this frontend (measured while writing snake/tetris; obeyed here too):
#   ① 坐标/尺寸一律整数,`/` 是真除法(float 按位型传进去会画到屏幕外)⇒ 全用 `//`;
#   ① coordinates/sizes are integers and `/` is true division (a float is passed as its bit
#      pattern and draws off-screen) => use `//` everywhere;
#   ② 没有二维数组 ⇒ 棋盘用**平铺**列表 `board[x * N + y]`(嵌套列表写不生效)。
#   ② there are no 2-D arrays => the board is a **flat** list `board[x * N + y]`
#      (writes into nested lists do not take effect).
#
# 合并的**先后**容易写错:一次滑动里每个块只许合并一次(`4 4 4 4` 滑一次是 `8 8`,不是 `16`),
# The merge order is easy to get wrong: each tile may merge only once per slide
# (`4 4 4 4` becomes `8 8`, not `16`), so collapse from the far end.
# 所以从滑动方向的**最远端**往回收。
# (Same sentence as the C file; kept for parity.)

# 显式引入共享库声明(GenLib 生成,勿手写):形参个数写错在**编译期**报错。
# Explicitly import the shared-library declarations (generated by GenLib, do not hand-write):
# a wrong argument count becomes a **compile-time** error.
# ⚠ 注释行别以 `Import` / `Include` 开头 —— 前端会把整行当 `#include` 指令。
# ⚠ Never start a comment line with `Import` / `Include` -- the frontend treats it as `#include`.
import vml_ui

MAX_FRAMES = 20000
N = 4

C_BG = 0xFF101018
C_EMPTY = 0xFF1A1A24
C_TEXT = 0xFFE8E8F0
C_DIM = 0xFF9AA0B0

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

board = [0] * (N * N)
score = 0
won = 0
over = 0
seed = 20263


def rnd(n):
    # 自带 LCG(不用库 rand):同一台机器两次跑起来序列可复现。
    # Own LCG (not the library rand): the sequence is reproducible across runs on one machine.
    # ⚠ 用 **16 位**状态:本前端的整数是 32 位,照 C 的 `seed * 1103515245 % 4294967296`
    #   写会溢出 ⇒ 每次 `rnd` 都返回 0(实测:2048 两个初始块都落在 (0,0))。
    # ⚠ Keep the state **16-bit**: this frontend's ints are 32-bit, so the C formula
    #   `seed * 1103515245 % 4294967296` overflows => every `rnd` returns 0
    #   (measured: both 2048 starting tiles landed on (0,0)).
    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
    # 棋盘取「宽度」与「扣掉顶栏/底部提示后的高度」里较小的那个:
    # 方形小画布(240x240)上原来的 `SW < SH - 150` 会落到「按高度」分支,
    # 只剩 60px 的棋盘。这里让两档都用同一套上下留白。
    # The board takes the smaller of "width" and "height after the header/footer":
    # on a square tiny canvas the old `SW < SH - 150` branch left only a 60px board.
    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 empty_count():
    n = 0
    i = 0
    while i < N * N:
        if board[i] == 0:
            n = n + 1
        i = i + 1
    return n


def spawn():
    global seed
    if empty_count() == 0:
        return
    guard = 0
    x = 0
    y = 0
    while guard < 500:
        x = rnd(N)
        y = rnd(N)
        if board[x * N + y] == 0:
            break
        guard = guard + 1
    board[x * N + y] = 4 if rnd(10) == 0 else 2


def new_game():
    global score, won, over
    i = 0
    while i < N * N:
        board[i] = 0
        i = i + 1
    score = 0
    won = 0
    over = 0
    spawn()
    spawn()


# 往一个方向滑:dir 0=左 1=右 2=上 3=下。返回是否真的动了。
# Slide one way: dir 0=left 1=right 2=up 3=down. Returns whether anything moved.
def slide(d):
    global score, won, over
    moved = 0
    i = 0
    while i < N:
        # 把这一行/列按滑动方向**从远端往回收**
        # Collapse this row/column from the far end of the slide direction.
        line = [0] * N
        n = 0
        x = 0
        while x < N:
            v = 0
            if d == 0:
                v = board[x * N + i]
            elif d == 1:
                v = board[(N - 1 - x) * N + i]
            elif d == 2:
                v = board[i * N + x]
            else:
                v = board[i * N + (N - 1 - x)]
            if v != 0:
                line[n] = v
                n = n + 1
            x = x + 1

        # 合并:相邻相等的合成一个(每块只合并一次)
        # Merge: adjacent equal tiles combine (each tile merges at most once).
        out = [0] * N
        on = 0
        k = 0
        while k < n:
            if k + 1 < n and line[k] == line[k + 1]:
                out[on] = line[k] * 2
                score = score + line[k] * 2
                if line[k] * 2 >= 2048:
                    won = 1
                on = on + 1
                k = k + 2
            else:
                out[on] = line[k]
                on = on + 1
                k = k + 1

        # 写回
        # Write back.
        x = 0
        while x < N:
            if d == 0:
                idx = x * N + i
            elif d == 1:
                idx = (N - 1 - x) * N + i
            elif d == 2:
                idx = i * N + x
            else:
                idx = i * N + (N - 1 - x)
            if board[idx] != out[x]:
                moved = 1
            board[idx] = out[x]
            x = x + 1
        i = i + 1

    # 没动就没得玩(也不该冒新数字)
    # Nothing moved => nothing to play with (and no new tile either).
    if moved == 1:
        spawn()

    # 输了:没空格,且四邻无相等
    # Lost: no empty cell and no equal neighbours.
    if empty_count() == 0:
        any_pair = 0
        x = 0
        while x < N:
            y = 0
            while y < N:
                if x + 1 < N and board[x * N + y] == board[(x + 1) * N + y]:
                    any_pair = 1
                if y + 1 < N and board[x * N + y] == board[x * N + y + 1]:
                    any_pair = 1
                y = y + 1
            x = x + 1
        if any_pair == 0:
            over = 1
    return moved


def tile_color(v):
    if v == 0:
        return C_EMPTY
    if v == 2:
        return 0xFF3A3A48
    if v == 4:
        return 0xFF4A5A6A
    if v == 8:
        return 0xFF4A90D9
    if v == 16:
        return 0xFF51E86E
    if v == 32:
        return 0xFFD9B44A
    if v == 64:
        return 0xFFE06C50
    if v == 128:
        return 0xFFE06CA8
    return 0xFF9B6CF0


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
            v = board[x * N + y]
            ui_2d_rect(px + 3, py + 3, CELL - 6, CELL - 6, tile_color(v), 1, 0, 10)
            if v != 0:
                if v >= 100:
                    fs = CELL // 4
                else:
                    fs = CELL // 3
                # 2/4 是深色块 ⇒ 浅字;其余浅色块 ⇒ 深字
                # 2/4 are dark tiles => light text; the rest are light => dark text.
                if v <= 4:
                    tc = C_TEXT
                else:
                    tc = 0xFF101018
                ui_2d_text(px + CELL // 2, py + CELL // 2 + CELL // 8,
                           str(v), tc, fs, VML_ANCHOR_CENTER)
            y = y + 1
        x = x + 1

    ui_2d_text(10, 22, str(score), C_TEXT, 16, VML_ANCHOR_LEFT)
    if LANG == 0:
        ui_2d_text(10, 44, "分数", C_DIM, 10, VML_ANCHOR_LEFT)
    else:
        ui_2d_text(10, 44, "score", C_DIM, 10, VML_ANCHOR_LEFT)

    if over == 1:
        if LANG == 0:
            msg = "滑不动了,点一下重开"
        else:
            msg = "No moves left - tap to restart"
        ui_2d_text(SW // 2, OY + N * CELL + 28, msg, C_TEXT, 14, VML_ANCHOR_CENTER)
    elif won == 1:
        if LANG == 0:
            msg = "到 2048!继续滑"
        else:
            msg = "2048! Keep going"
        ui_2d_text(SW // 2, OY + N * CELL + 28, msg, C_TEXT, 14, VML_ANCHOR_CENTER)
    else:
        if LANG == 0:
            msg = "方向键 / 点屏幕四边"
        else:
            msg = "Arrows / tap a screen edge"
        ui_2d_text(SW // 2, OY + N * CELL + 28, msg, C_DIM, 12, VML_ANCHOR_CENTER)
    ui_2d_present()


def tap(x, y):
    if over == 1:
        new_game()
        return
    # 点四边决定方向(离哪边最近就往哪边滑)
    # A screen edge decides the direction (whichever side is nearest).
    dl = x
    dr = SW - x
    dt = y
    db = SH - y
    if dl <= dr and dl <= dt and dl <= db:
        slide(0)
    elif dr <= dt and dr <= db:
        slide(1)
    elif dt <= db:
        slide(2)
    else:
        slide(3)


def main():
    global LANG
    LANG = ui_scr_get_language()

    relayout()
    ui_win_open_ex("2048" if LANG == 0 else "2048 (py)", 0, 0, 1, 0)
    relayout()
    new_game()
    draw()

    tid = ui_timer_set(120, 1)
    frames = 0
    done = 0
    while done == 0 and ui_win_is_closed() == 0:
        # 阻塞等的返回值就是那条消息,别再 fetch 一次(那会把定时器消息丢掉)
        # The blocking wait returns the message itself; do not fetch again (that swallows timer messages).
        t = ui_msg_fetch()
        if t == 0:
            t = ui_msg_fetch_wait(120)
        if t == 0:
            continue

        if t == 6 or t == 4:                 # 触摸/鼠标按下
            # 坐标取这条消息自己的 a/b(ui_touch_get_x 只是 ui_touch_fetch 的缓存)
            # Coordinates come from this message's a/b (ui_touch_get_x is only ui_touch_fetch's cache).
            tap(ui_msg_get_a(), ui_msg_get_b())
            draw()
            continue

        if t == 1:                           # 键盘
            k = ui_msg_get_a()
            if k == 27:
                new_game()
            elif k == 37:
                slide(0)
            elif k == 39:
                slide(1)
            elif k == 38:
                slide(2)
            elif k == 40:
                slide(3)
            draw()
            continue

        if t == 11:                          # 窗口尺寸变了
            relayout()
            draw()
            continue

        if t == 9:                           # 定时器:只重画 + 帧数上限
            frames = frames + 1
            if frames >= MAX_FRAMES:
                done = 1
            draw()
            continue

        if t == 10:
            break

    ui_timer_kill(tid)
    ui_win_close()
    return 0


main()