/* puzzle15.c —— 数字华容道（15 格滑块拼图）
 * puzzle15.c -- the 15-puzzle (sliding tile puzzle)
 *
 * 玩法：4×4 里 15 个数字 + 1 个空格；点空格**旁边**的块就滑过去；
 * Rules: 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" --
 * 这样**一定可解**（随手随机交换那种有一半局面是死局）。
 * so it is **always solvable** (random-swapping half the time produces a dead board).
 *
 * 为什么放在例程里：它是"**二维数组 + 相邻判定 + 胜利判定**"最干净的样本，
 * Why it is here: it is the cleanest sample of "**a 2-D array + adjacency + win check**",
 * 而且手机上没有键盘也能玩（点格子就行）。
 * and it plays without a keyboard on a phone (just tap cells).
 */

#include <vml_ui.h>
#include <stdlib.h>
#include <stdio.h>

#define MAX_FRAMES 6000
#define N 4

#define C_BG    0xFF101018
#define C_TILE  0xFF4A90D9
#define C_TILE2 0xFF3A6FA8
#define C_TEXT  0xFFE8E8F0
#define C_DIM   0xFF9AA0B0

static int SW, SH, g_lang, g_frames;
static int cell, ox, oy;
static int tile[N][N];            /* 0 = 空格 */
static int blank_x, blank_y, moves, won;

static unsigned int seed = 20261118;
static int rnd(int n)
{
    seed = seed * 1103515245u + 12345u;
    return (int)((seed >> 16) % (unsigned int)n);
}

static void relayout(void)
{
    int side;
    SW = ui_scr_get_w();
    SH = ui_scr_get_h();
    if (SW <= 0) SW = 360;
    if (SH <= 0) SH = 620;
    side = SW < SH - 140 ? SW - 20 : SH - 170;
    cell = side / N;
    if (cell < 6) cell = 6;
    ox = (SW - N * cell) / 2;
    oy = 110;
}

static void swap_cells(int ax, int ay, int bx, int by)
{
    int t = tile[ax][ay];
    tile[ax][ay] = tile[bx][by];
    tile[bx][by] = t;
}

/* 合法步：空格与四邻里挑一个 */
static int slide_random(void)
{
    int dx = 0, dy = 0, k = rnd(4);
    int nx, ny;
    if (k == 0) dx = 1;
    else if (k == 1) dx = -1;
    else if (k == 2) dy = 1;
    else dy = -1;
    nx = blank_x + dx;
    ny = blank_y + dy;
    if (nx < 0 || ny < 0 || nx >= N || ny >= N) return 0;
    swap_cells(blank_x, blank_y, nx, ny);
    blank_x = nx;
    blank_y = ny;
    return 1;
}

static void new_game(void)
{
    int x, y, v = 1, i;
    for (x = 0; x < N; x++)
        for (y = 0; y < N; y++) { tile[x][y] = v; v++; }
    tile[N - 1][N - 1] = 0;
    blank_x = N - 1;
    blank_y = N - 1;
    for (i = 0; i < 400; i++) slide_random();     /* 只走合法步 ⇒ 局面一定可解 */
    moves = 0;
    won = 0;
}

static int check_win(void)
{
    int x, y, v = 1;
    for (x = 0; x < N; x++)
        for (y = 0; y < N; y++) {
            if (x == N - 1 && y == N - 1) return tile[x][y] == 0;
            if (tile[x][y] != v) return 0;
            v++;
        }
    return 1;
}

static void draw(void)
{
    int x, y;
    char buf[8];

    ui_2d_clear(C_BG);

    for (x = 0; x < N; x++) {
        for (y = 0; y < N; y++) {
            int px = ox + x * cell, py = oy + y * cell;
            if (tile[x][y] == 0) {
                ui_2d_rect(px + 2, py + 2, cell - 4, cell - 4, 0xFF16161E, 1, 0, 6);
                continue;
            }
            /* 排好的那些用亮蓝、还没回去的用暗蓝 —— 一眼看出差多少 */
            {
                int v = tile[x][y];
                int home = (v - 1) % N == x && (v - 1) / N == y;
                ui_2d_rect(px + 2, py + 2, cell - 4, cell - 4, home ? C_TILE : C_TILE2, 1, 0, 8);
            }
            itoa(tile[x][y], buf);
            ui_2d_text(px + cell / 2, py + cell / 2 + cell / 8, buf, C_TEXT, cell / 2, VML_ANCHOR_CENTER);
        }
    }

    itoa(moves, buf);
    ui_2d_text(10, 22, buf, C_TEXT, 15, VML_ANCHOR_LEFT);
    ui_2d_text(10, 42, g_lang == 0 ? "步数" : "moves", C_DIM, 10, VML_ANCHOR_LEFT);

    if (won)
        ui_2d_text(SW / 2, oy + N * cell + 28, g_lang == 0 ? "拼好了！ESC 再来" : "Solved! ESC for a new one",
                   C_TEXT, 15, VML_ANCHOR_CENTER);
    else
        ui_2d_text(SW / 2, oy + N * cell + 28, g_lang == 0 ? "点空格旁边的块" : "Tap a tile next to the blank",
                   C_DIM, 12, VML_ANCHOR_CENTER);
    ui_2d_present();
}

static void tap(int tx, int ty)
{
    int x = (tx - ox) / cell, y = (ty - oy) / cell;
    if (x < 0 || y < 0 || x >= N || y >= N) return;
    if (won) return;
    /* 只认上下左右相邻的（斜着不算） */
    if ((x == blank_x && (y == blank_y - 1 || y == blank_y + 1))
        || (y == blank_y && (x == blank_x - 1 || x == blank_x + 1))) {
        swap_cells(blank_x, blank_y, x, y);
        blank_x = x;
        blank_y = y;
        moves = moves + 1;
        won = check_win();
    }
}

int main(void)
{
    int msg[4];
    int tid;
    int done = 0;
    char buf[8];

    g_lang = ui_scr_get_language();
    relayout();
    ui_win_open_ex("puzzle15.c", 0, 0, VML_WIN_ROTATABLE, VML_WIN_NO_GAMEPAD);
    relayout();
    new_game();
    draw();

    tid = ui_timer_set(120, 1);
    while (!done && ui_win_is_closed() == 0) {
        int t = ui_msg_wait(msg, 0);
        if (t == VML_MSG_NONE) continue;

        if (t == VML_MSG_TOUCHDOWN || t == VML_MSG_MOUSEDOWN) { tap(msg[1], msg[2]); draw(); continue; }
        if (t == VML_MSG_KEYDOWN) {
            if (msg[1] == VML_KEY_ESCAPE) { new_game(); draw(); }
            continue;
        }
        if (t == VML_MSG_TIMER) {
            g_frames = g_frames + 1;
            if (g_frames >= MAX_FRAMES) done = 1;
            draw();
            continue;
        }
        if (t == VML_MSG_WINDOWRESIZE) { relayout(); draw(); continue; }
        if (t == VML_MSG_WINDOWCLOSE) break;
    }

    ui_timer_kill(tid);
    ui_win_close();
    itoa(moves, buf);
    printf("puzzle15: moves=%s won=%d done\n", buf, won);
    return 0;
}
