/* towerdef.c —— 塔防：敌人沿路走，点空地放塔
 * towerdef.c -- tower defense: enemies march a path; tap off-path ground to build a tower
 *
 * 玩法：敌人从顶部沿一条折线路径往下走，漏掉一个扣一点命；
 * Rules: enemies march down a bent path from the top and each leak costs a life;
 * 点**路径外的空地**放塔（每座 10 块，钱靠击杀累积），塔自动打射程内最近的敌人；
 * tapping **off-path ground** builds a tower (10 coins; coins come from kills); towers auto-fire at
 * the nearest enemy in range;
 * 命用完或击杀分到 300 结束。
 * losing all lives or scoring 300 ends the run.
 */
#include <vml_ui.h>
#include <stdlib.h>
#include <stdio.h>

#define MAX_FRAMES 30000
#define GW 8
#define GH 10
#define MAX_E 12
#define MAX_T 10

static int SW, SH, g_lang, g_frames;
static int cell, ox, oy;
static int ex[MAX_E], ey[MAX_E], ehp[MAX_E], eon[MAX_E];
static int tx[MAX_T], ty[MAX_T], ton[MAX_T];
static int path[GH], lives, coins, score, over;

static unsigned int seed = 20261126;
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 - 120 ? SW - 12 : SH - 130;
    cell = side / GW;
    if (cell < 6) cell = 6;
    ox = (SW - GW * cell) / 2;
    oy = 84;
}

static int is_path(int x, int y) { return path[y] == x; }

static void new_game(void)
{
    int i;
    for (i = 0; i < GH; i++) path[i] = (i < 4) ? 2 : (i < 7 ? 5 : 3);
    for (i = 0; i < MAX_E; i++) eon[i] = 0;
    for (i = 0; i < MAX_T; i++) ton[i] = 0;
    lives = 3; coins = 40; score = 0; over = 0;
}

static void spawn(void)
{
    int i;
    for (i = 0; i < MAX_E; i++)
        if (!eon[i]) { eon[i] = 1; ex[i] = 0; ey[i] = 0; ehp[i] = 2; return; }
}

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

    ui_2d_clear(0xFF101018);
    for (y = 0; y < GH; y++)
        for (x = 0; x < GW; x++)
            ui_2d_rect(ox + x * cell, oy + y * cell, cell - 2, cell - 2,
                       is_path(x, y) ? 0xFF2A2A36 : 0xFF16161E, 1, 0, 3);
    for (i = 0; i < MAX_T; i++)
        if (ton[i]) ui_2d_rect(ox + tx[i] * cell + 4, oy + ty[i] * cell + 4, cell - 10, cell - 10, 0xFF4A90D9, 1, 0, 3);
    for (i = 0; i < MAX_E; i++)
        if (eon[i]) ui_2d_circle(ox + ex[i] * cell + cell / 2, oy + ey[i] * cell + cell / 2, cell / 3,
                                 ehp[i] > 1 ? 0xFFE06C50 : 0xFFD9B44A, 1, 0);

    itoa(coins, b); ui_2d_text(8, 20, b, 0xFFFFD040, 15, VML_ANCHOR_LEFT);
    itoa(lives, b); ui_2d_text(SW / 2, 20, b, 0xFF51E86E, 15, VML_ANCHOR_CENTER);
    itoa(score, b); ui_2d_text(SW - 8, 20, b, 0xFFFFFFFF, 15, VML_ANCHOR_RIGHT);
    ui_2d_text(SW / 2, SH - 12,
               over ? (g_lang == 0 ? "结束，ESC 重开" : "Over - ESC")
                    : (g_lang == 0 ? "点路径外空地放塔（10 块）" : "Tap off-path ground to build (10)"),
               0xFF9AA0B0, 11, VML_ANCHOR_CENTER);
    ui_2d_present();
}

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

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

    tid = ui_timer_set(80, 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 gx = (msg[1] - ox) / cell, gy = (msg[2] - oy) / cell;
            if (!over && gx >= 0 && gy >= 0 && gx < GW && gy < GH && !is_path(gx, gy) && coins >= 10)
                for (i = 0; i < MAX_T; i++)
                    if (!ton[i]) { ton[i] = 1; tx[i] = gx; ty[i] = gy; coins = coins - 10; break; }
            draw(); continue;
        }
        if (t == VML_MSG_KEYDOWN) { if (msg[1] == VML_KEY_ESCAPE) { new_game(); draw(); } continue; }

        if (t == VML_MSG_TIMER) {
            int k;
            g_frames = g_frames + 1;
            if (g_frames >= MAX_FRAMES) done = 1;
            if (!over) {
                tick = tick + 1;
                if ((tick % 30) == 0) spawn();
                for (i = 0; i < MAX_E; i++) {
                    if (!eon[i]) continue;
                    for (k = 0; k < MAX_T; k++) {
                        int dx, dy;
                        if (!ton[k]) continue;
                        dx = tx[k] - ex[i]; dy = ty[k] - ey[i];
                        if (dx < 0) dx = -dx;
                        if (dy < 0) dy = -dy;
                        if (dx + dy <= 3) ehp[i] = ehp[i] - 1;      /* 塔的射程：曼哈顿 3 */
                    }
                    if (ehp[i] <= 0) { eon[i] = 0; coins = coins + 6; score = score + 10; continue; }
                    if ((tick % 14) == 0) {
                        if (ey[i] < GH - 1) ey[i] = ey[i] + 1;
                        else { eon[i] = 0; lives = lives - 1; if (lives <= 0) { over = 1; done = 1; } }
                    }
                }
                if (score >= 300) { over = 1; 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();
    printf("towerdef: score=%d lives=%d\n", score, lives);
    return 0;
}
