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

python/app/puzzle15.py · 7418 字节 · 下载原文

▶ 在浏览器里试玩

# puzzle15.py —— 数字华容道 / 15 格滑块拼图(VML 的 Python 前端)
# puzzle15.py -- the 15-puzzle (VML's Python frontend)
#
# 与 `Examples/c/app/puzzle15.c` **同一套玩法**:
# Same rules as `Examples/c/app/puzzle15.c`:
#   · 4×4 里 15 个数字 + 1 个空格;点空格**旁边**的块就滑过去;
#   · 15 numbers plus one blank in a 4x4 grid; tap a tile **next to** the blank and it slides over;
#   · 排成 1..15 顺序即通关;
#   · arranging 1..15 in order wins;
#   · 打乱用的是"从解好的局面随机走合法步"⇒ **一定可解**(随手随机交换有一半是死局)。
#   · the shuffle is "random legal moves from the solved board" => **always solvable**
#     (random swapping produces a dead board half the time).
#
# ⚠ 平铺列表 + 全 `//`(本前端没有二维数组,`/` 是真除法 ⇒ float 位型)。
# ⚠ Flat list + `//` everywhere (no 2-D arrays; `/` is true division => float bit patterns).

# 显式引入共享库声明(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 = 6000
N = 4

C_BG = 0xFF101018
C_TILE = 0xFF4A90D9
C_TILE2 = 0xFF3A6FA8
C_TEXT = 0xFFE8E8F0
C_DIM = 0xFF9AA0B0

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

tile = [0] * (N * N)      # 0 = 空格 / blank
blank_x = N - 1
blank_y = N - 1
moves = 0
won = 0
seed = 20266


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 swap_cells(ax, ay, bx, by):
    t = tile[ax * N + ay]
    tile[ax * N + ay] = tile[bx * N + by]
    tile[bx * N + by] = t


# 合法步:空格与四邻里挑一个
# One legal move: pick one of the blank's four neighbours.
def slide_random():
    global blank_x, blank_y
    k = rnd(4)
    dx = 0
    dy = 0
    if k == 0:
        dx = 1
    elif k == 1:
        dx = -1
    elif k == 2:
        dy = 1
    else:
        dy = -1
    nx = blank_x + dx
    ny = blank_y + dy
    if nx < 0 or ny < 0 or nx >= N or ny >= N:
        return 0
    swap_cells(blank_x, blank_y, nx, ny)
    blank_x = nx
    blank_y = ny
    return 1


def new_game():
    global blank_x, blank_y, moves, won
    v = 1
    x = 0
    while x < N:
        y = 0
        while y < N:
            tile[x * N + y] = v
            v = v + 1
            y = y + 1
        x = x + 1
    tile[N * N - 1] = 0
    blank_x = N - 1
    blank_y = N - 1
    i = 0
    while i < 400:
        slide_random()          # 只走合法步 ⇒ 局面一定可解 / legal moves only => always solvable
        i = i + 1
    moves = 0
    won = 0


def check_win():
    v = 1
    x = 0
    while x < N:
        y = 0
        while y < N:
            if x == N - 1 and y == N - 1:
                if tile[x * N + y] == 0:
                    return 1
                return 0
            if tile[x * N + y] != v:
                return 0
            v = v + 1
            y = y + 1
        x = x + 1
    return 1


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 = tile[x * N + y]
            if v == 0:
                ui_2d_rect(px + 2, py + 2, CELL - 4, CELL - 4, 0xFF16161E, 1, 0, 6)
            else:
                # 排好的那些用亮蓝、还没回去的用暗蓝 —— 一眼看出差多少
                # Tiles in place are bright blue, the rest dark blue -- see the deficit at a glance.
                if (v - 1) % N == x and (v - 1) // N == y:
                    c = C_TILE
                else:
                    c = C_TILE2
                ui_2d_rect(px + 2, py + 2, CELL - 4, CELL - 4, c, 1, 0, 8)
                ui_2d_text(px + CELL // 2, py + CELL // 2 + CELL // 8,
                           str(v), C_TEXT, CELL // 2, VML_ANCHOR_CENTER)
            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 = "Solved! 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 = "Tap a tile next to the blank"
        ui_2d_text(SW // 2, OY + N * CELL + 28, msg, C_DIM, 12, VML_ANCHOR_CENTER)
    ui_2d_present()


def tap(tx, ty):
    global blank_x, blank_y, moves, 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
    # 只认上下左右相邻的(斜着不算)
    # Only orthogonal neighbours count (diagonals do not).
    adjacent = 0
    if x == blank_x and (y == blank_y - 1 or y == blank_y + 1):
        adjacent = 1
    if y == blank_y and (x == blank_x - 1 or x == blank_x + 1):
        adjacent = 1
    if adjacent == 1:
        swap_cells(blank_x, blank_y, x, y)
        blank_x = x
        blank_y = y
        moves = moves + 1
        won = check_win()


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

    relayout()
    ui_win_open_ex("数字华容道" if LANG == 0 else "15-puzzle (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:
        t = ui_msg_fetch()
        if t == 0:
            t = ui_msg_fetch_wait(120)
        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
            draw()
            continue

        if t == 10:
            break

    ui_timer_kill(tid)
    ui_win_close()
    return 0


main()