/* snake.c —— 贪吃蛇（网格 + 方向键 / 点屏幕四个方向）
 * snake.c -- Snake (grid movement; arrow keys, or tap one of the four screen edges)
 *
 * 玩法：蛇每 `STEP_TICKS` 拍走一格，吃到豆子变长并加分；撞墙或撞自己结束。
 * Rules: the snake advances one cell every `STEP_TICKS` ticks; eating a bean grows it and scores;
 * hitting a wall or itself ends the game.
 *
 * 操作：方向键；或者**点屏幕边缘**（上半/下半/左半/右半里离哪边最近就转向哪边），
 * Controls: arrow keys; or **tap the screen edge** (whichever of the four sides is nearest).
 * 手指操作在手机上比方向键顺手。
 * Touch beats arrow keys on a phone.
 *
 * 格子数按画布现算，所以横屏竖屏都能玩（格宽取整后可能留一圈边，居中摆）。
 * The grid size is computed from the canvas, so it plays in both orientations (any leftover
 * pixels become an even margin).
 */

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

#define MAX_FRAMES 3000
#define MAX_LEN    256
#define STEP_TICKS 4

#define C_BG    0xFF101018
#define C_HEAD  0xFF51E86E
#define C_BODY  0xFF2E7D4F
#define C_FOOD  0xFFE06C50
#define C_TEXT  0xFFE8E8F0
#define C_DIM   0xFF9AA0B0

static int SW, SH, g_lang, g_frames;
static int cell, ox, oy, gw, gh;      /* 格子边长 / 原点 / 格数 */
static int body_x[MAX_LEN], body_y[MAX_LEN];
static int len, dir, next_dir;
static int food_x, food_y, score, alive, step;

static unsigned int seed = 20261116;
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 - 90 ? SW : SH - 90;
    gw = 16;
    cell = side / gw;
    if (cell < 6) cell = 6;
    gh = side / cell;
    ox = (SW - gw * cell) / 2;
    oy = 60 + (SH - 60 - gh * cell) / 2;
}

static int cell_has_snake(int x, int y)
{
    int i;
    for (i = 0; i < len; i++)
        if (body_x[i] == x && body_y[i] == y) return 1;
    return 0;
}

static void place_food(void)
{
    int x, y, guard = 0;
    do {
        x = rnd(gw);
        y = rnd(gh);
        guard = guard + 1;
    } while (cell_has_snake(x, y) && guard < 500);
    food_x = x;
    food_y = y;
}

static void new_game(void)
{
    len = 3;
    body_x[0] = gw / 2;     body_y[0] = gh / 2;
    body_x[1] = gw / 2 - 1; body_y[1] = gh / 2;
    body_x[2] = gw / 2 - 2; body_y[2] = gh / 2;
    dir = 0;                /* 0=右 1=下 2=左 3=上 */
    next_dir = 0;
    score = 0;
    alive = 1;
    step = 0;
    place_food();
}

static void draw(void)
{
    int i;
    char buf[16];

    ui_2d_clear(C_BG);

    /* 棋盘格底纹（浅色交替）—— 有格子才看得出"走了一格" */
    for (i = 0; i < gw; i++) {
        int j;
        for (j = 0; j < gh; j++) {
            if (((i + j) & 1) == 0) continue;
            ui_2d_rect(ox + i * cell, oy + j * cell, cell, cell, 0xFF16161E, 1, 0, 0);
        }
    }

    ui_2d_rect(ox + food_x * cell + 2, oy + food_y * cell + 2, cell - 4, cell - 4, C_FOOD, 1, 0, cell / 2);
    for (i = len - 1; i >= 0; i--)
        ui_2d_rect(ox + body_x[i] * cell + 1, oy + body_y[i] * cell + 1, cell - 2, cell - 2,
                   i == 0 ? C_HEAD : C_BODY, 1, 0, 2);

    itoa(score, buf);
    ui_2d_text(8, 16, buf, C_TEXT, 15, VML_ANCHOR_LEFT);
    if (!alive) {
        ui_2d_text(SW / 2, oy + gh * cell + 18, g_lang == 0 ? "撞了，ESC 重来" : "Crashed - ESC to restart",
                   C_TEXT, 14, VML_ANCHOR_CENTER);
    } else {
        ui_2d_text(SW / 2, SH - 16, g_lang == 0 ? "方向键 / 点屏幕四边" : "Arrows / tap a screen edge",
                   C_DIM, 11, VML_ANCHOR_CENTER);
    }
    ui_2d_present();
}

/* 按触点决定往哪边转：离哪条边最近就转向哪边（不许 180° 掉头） */
static void turn_by_touch(int x, int y)
{
    int dl = x, dr = SW - x, dt = y, db = SH - y;
    int want = dir;
    if (dl <= dr && dl <= dt && dl <= db) want = 2;
    else if (dr <= dt && dr <= db) want = 0;
    else if (dt <= db) want = 3;
    else want = 1;
    if ((want + 2) % 4 == dir) return;
    next_dir = want;
}

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

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

    tid = ui_timer_set(50, 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) {
            if (alive) turn_by_touch(msg[1], msg[2]);
            else { new_game(); draw(); }
            continue;
        }
        if (t == VML_MSG_KEYDOWN) {
            if (msg[1] == VML_KEY_ESCAPE) { new_game(); draw(); continue; }
            if (!alive) continue;
            if (msg[1] == VML_KEY_RIGHT && dir != 2) next_dir = 0;
            if (msg[1] == VML_KEY_DOWN  && dir != 3) next_dir = 1;
            if (msg[1] == VML_KEY_LEFT  && dir != 0) next_dir = 2;
            if (msg[1] == VML_KEY_UP    && dir != 1) next_dir = 3;
            continue;
        }

        if (t == VML_MSG_TIMER) {
            int i, nx, ny;

            g_frames = g_frames + 1;
            if (g_frames >= MAX_FRAMES) done = 1;
            step = step + 1;
            if (step < STEP_TICKS || !alive) { draw(); continue; }
            step = 0;

            dir = next_dir;
            nx = body_x[0] + (dir == 0 ? 1 : (dir == 2 ? -1 : 0));
            ny = body_y[0] + (dir == 1 ? 1 : (dir == 3 ? -1 : 0));

            if (nx < 0 || ny < 0 || nx >= gw || ny >= gh) { alive = 0; draw(); continue; }
            /* 尾巴让位：这一拍尾巴要挪走，所以撞到"最后一节"是合法的 */
            for (i = 0; i < len - 1; i++)
                if (body_x[i] == nx && body_y[i] == ny) { alive = 0; break; }
            if (!alive) { draw(); continue; }

            for (i = len - 1; i > 0; i--) { body_x[i] = body_x[i - 1]; body_y[i] = body_y[i - 1]; }
            body_x[0] = nx;
            body_y[0] = ny;

            if (nx == food_x && ny == food_y) {
                if (len < MAX_LEN) len = len + 1;
                body_x[len - 1] = body_x[len - 2];
                body_y[len - 1] = body_y[len - 2];
                score = score + 10;
                place_food();
            }
            draw();
            continue;
        }

        if (t == VML_MSG_WINDOWRESIZE) { relayout(); draw(); continue; }
        if (t == VML_MSG_WINDOWCLOSE) break;
    }

    ui_timer_kill(tid);
    ui_win_close();
    itoa(score, buf);
    printf("snake: score=%s len=%d alive=%d done\n", buf, len, alive);
    return 0;
}
