/* match3.c —— 三消（点两个相邻格交换，连成三个以上就消）
 * match3.c -- match-3 (tap two adjacent cells; a run of three or more clears)
 *
 * 8×8 六种颜色：相邻交换后形成横/竖 3 连就消掉、加分、上方落下补位；
 * 8x8 with six colors: a swap that forms a run of three clears it, scores, and refills from above;
 * 不形成 3 连的交换**还原**（经典规则）。点两格 = 一次交换。
 * a swap that forms nothing is **reverted** (classic rule). Two taps = one swap.
 */
#include <vml_ui.h>
#include <stdlib.h>
#include <stdio.h>

#define MAX_FRAMES 30000
#define GN 8

static int SW, SH, g_lang, g_frames, cell, ox, oy;
static int g[GN][GN], sel_x = -1, sel_y = -1, score;

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

static const int COLOR[6] = {0xFFE06C50, 0xFFD9B44A, 0xFF51E86E, 0xFF4A90D9, 0xFF9B6CF0, 0xFF4AD9C6};

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 - 120 ? SW - 16 : SH - 140;
    cell = side / GN;
    if (cell < 8) cell = 8;
    ox = (SW - GN * cell) / 2;
    oy = 90;
}

/* 这一格参与 3 连吗（横或竖） */
static int run3(int x, int y)
{
    int c = g[x][y], n = 1, k;
    if (c < 0) return 0;
    for (k = x - 1; k >= 0 && g[k][y] == c; k--) n++;
    for (k = x + 1; k < GN && g[k][y] == c; k++) n++;
    if (n >= 3) return 1;
    n = 1;
    for (k = y - 1; k >= 0 && g[x][k] == c; k--) n++;
    for (k = y + 1; k < GN && g[x][k] == c; k++) n++;
    return n >= 3;
}

/* 消除 + 下落 + 补新，直到棋盘稳定 */
static void settle(void)
{
    int x, y, k, got = 1, moved;
    while (got) {
        got = 0;
        for (x = 0; x < GN; x++)
            for (y = 0; y < GN; y++)
                if (run3(x, y)) { g[x][y] = -1; got = 1; }
        if (!got) break;
        score = score + 10;
        for (x = 0; x < GN; x++) {
            moved = 1;
            while (moved) {                       /* 冒泡把空位换到上面 */
                moved = 0;
                for (y = GN - 1; y > 0; y--)
                    if (g[x][y] == -1 && g[x][y - 1] != -1) {
                        k = g[x][y]; g[x][y] = g[x][y - 1]; g[x][y - 1] = k; moved = 1;
                    }
            }
            for (y = 0; y < GN; y++)
                if (g[x][y] == -1) g[x][y] = rnd(6);
        }
    }
}

static void new_game(void)
{
    int x, y;
    for (x = 0; x < GN; x++)
        for (y = 0; y < GN; y++) {
            do { g[x][y] = rnd(6); } while (run3(x, y));   /* 开局不许自带 3 连 */
        }
    score = 0;
    sel_x = -1;
}

static void draw(void)
{
    int x, y;
    char b[16];

    ui_2d_clear(0xFF101018);
    for (x = 0; x < GN; x++)
        for (y = 0; y < GN; y++) {
            int px = ox + x * cell, py = oy + y * cell;
            ui_2d_rect(px + 2, py + 2, cell - 4, cell - 4, g[x][y] >= 0 ? COLOR[g[x][y]] : 0xFF16161E, 1, 0, 6);
            if (x == sel_x && y == sel_y) ui_2d_rect(px + 1, py + 1, cell - 2, cell - 2, 0xFFFFFFFF, 0, 3, 7);
        }
    itoa(score, b);
    ui_2d_text(10, 24, b, 0xFFFFFFFF, 16, VML_ANCHOR_LEFT);
    ui_2d_text(SW / 2, SH - 12, g_lang == 0 ? "点两个相邻格交换" : "Tap two adjacent cells to swap",
               0xFF9AA0B0, 11, VML_ANCHOR_CENTER);
    ui_2d_present();
}

int main(void)
{
    int msg[4], tid, done = 0;

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

    tid = ui_timer_set(150, 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) {
            int x = (msg[1] - ox) / cell, y = (msg[2] - oy) / cell;
            if (x >= 0 && y >= 0 && x < GN && y < GN) {
                if (sel_x < 0) { sel_x = x; sel_y = y; }
                else {
                    int adx = x - sel_x, ady = y - sel_y, tmp;
                    if (adx < 0) adx = -adx;
                    if (ady < 0) ady = -ady;
                    if (adx + ady == 1) {
                        tmp = g[x][y]; g[x][y] = g[sel_x][sel_y]; g[sel_x][sel_y] = tmp;
                        if (!run3(x, y) && !run3(sel_x, sel_y)) {          /* 不成 3 连：还原 */
                            tmp = g[x][y]; g[x][y] = g[sel_x][sel_y]; g[sel_x][sel_y] = tmp;
                        } else settle();
                    }
                    sel_x = -1;
                }
            }
            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; continue; }
        if (t == VML_MSG_WINDOWCLOSE) break;
    }

    ui_timer_kill(tid);
    ui_win_close();
    printf("match3: score=%d\n", score);
    return 0;
}
