Ergo AI / Examples / Build a tower defense game on canvas: enemies follow a path

Build a tower defense game on canvas: enemies follow a path

A beautiful weather app with animated icons, hourly and weekly forecasts, and changing skies

⚡ Build modeErgo Lite3 files
The prompt
Build a tower defense game on canvas: enemies follow a path in waves, place 3 tower types with different powers, upgrade towers, earn coins, lives and wave counter, and a start screen
Build this with Ergo →

How Ergo built it

Ergo made a plan first, then worked through it step by step:

  1. Read workspace files and locate the reported runtime error
  2. Fix the malformed game-loop declaration
  3. Audit remaining runtime paths and button handlers for errors
  4. Confirm fix and summarize

Ergo's answer

The error came from a literal \n accidentally written into the game-loop declaration:

// ---------- Game loop ----------nlet lastTime = performance.now();

That commented out the let lastTime declaration, leaving lastTime undefined when frame() ran. It is now a proper newline and declaration.

I also audited all runtime paths and controls:

  • Begin Defense and Defend Again correctly reset the game and hide overlays.
  • Tower cards / hotkeys 1–3 select Archer, Cannon, and Frost.
  • Canvas placement, tower selection, upgrading, selling, right-click, and Escape cancellation are wired.
  • Start Wave, Space, Pause/P, and Speed/F handlers work with their state guards.
  • Victory, game-over, wave bonuses, lives, coins, and restart state transitions are intact.

No other references to the broken declaration or missing element handlers were found.

Files

index.html127 lines
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Pathguard — Tower Defense</title>
  <link rel="stylesheet" href="./style.css">
</head>
<body>
  <div class="app">
    <header class="topbar">
      <div class="brand">
        <span class="brand-mark">🛡️</span>
        <div>
          <h1>PATHGUARD</h1>
          <p>Hold the road. Protect the realm.</p>
        </div>
      </div>
      <div class="stats">
        <div class="stat coins"><span class="stat-icon">🪙</span><div><small>Coins</small><strong id="coins">0</strong></div></div>
        <div class="stat lives"><span class="stat-icon">❤️</span><div><small>Lives</small><strong id="lives">0</strong></div></div>
        <div class="stat wave"><span class="stat-icon">⚔️</span><div><small>Wave</small><strong id="wave">0/15</strong></div></div>
      </div>
    </header>

    <main class="game-layout">
      <section class="board-wrap">
        <canvas id="game" width="960" height="640" aria-label="Tower defense game board"></canvas>
        <div class="board-hint" id="board-hint">Choose a tower, then click a grass tile to build.</div>
      </section>

      <aside class="sidebar">
        <section class="panel">
          <div class="panel-title"><h2>Build Towers</h2><span>Hotkeys 1–3</span></div>
          <div class="tower-list">
            <button class="tower-card" data-type="arrow">
              <span class="tower-avatar arrow-avatar">➶</span>
              <span class="tower-info"><strong>Archer <kbd>1</kbd></strong><small>Fast · long range · single target</small></span>
              <span class="cost">50 🪙</span>
            </button>
            <button class="tower-card" data-type="cannon">
              <span class="tower-avatar cannon-avatar">●</span>
              <span class="tower-info"><strong>Cannon <kbd>2</kbd></strong><small>Slow · heavy splash damage</small></span>
              <span class="cost">100 🪙</span>
            </button>
            <button class="tower-card" data-type="frost">
              <span class="tower-avatar frost-avatar">❄</span>
              <span class="tower-info"><strong>Frost <kbd>3</kbd></strong><small>Slows groups · light damage</small></span>
              <span class="cost">75 🪙</span>
            </button>
          </div>
        </section>

        <section class="panel selection-panel">
          <div class="panel-title"><h2>Selected Tower</h2><span id="enemy-count">0 enemies</span></div>
          <div id="selection-empty" class="selection-empty">
            <span>🏹</span>
            <p>Click a placed tower to inspect, upgrade, or sell it.</p>
          </div>
          <div id="selection-detail" class="hidden">
            <div class="selected-head">
              <div><strong id="selected-name">Archer</strong><span id="selected-level" class="level-badge">Lv. 1</span></div>
              <small id="selected-role">Single target</small>
            </div>
            <div class="tower-stats">
              <div><small>Damage</small><strong id="stat-damage">—</strong></div>
              <div><small>Range</small><strong id="stat-range">—</strong></div>
              <div><small>Fire rate</small><strong id="stat-rate">—</strong></div>
            </div>
            <p id="upgrade-note" class="upgrade-note"></p>
            <div class="selection-actions">
              <button id="upgrade-btn" class="btn upgrade">Upgrade</button>
              <button id="sell-btn" class="btn sell">Sell</button>
            </div>
          </div>
        </section>

        <section class="panel controls-panel">
          <button id="wave-btn" class="btn wave-btn">Start Wave 1</button>
          <div class="control-row">
            <button id="pause-btn" class="btn secondary" title="Pause (P)">⏸ Pause</button>
            <button id="speed-btn" class="btn secondary" title="Game speed (F)">▶ 1×</button>
          </div>
          <p class="shortcut-tip"><kbd>Space</kbd> next wave · <kbd>P</kbd> pause · <kbd>Esc</kbd> cancel</p>
        </section>
      </aside>
    </main>
  </div>

  <div id="start-screen" class="overlay">
    <div class="modal start-modal">
      <div class="eyebrow">A CANVAS TOWER DEFENSE GAME</div>
      <h2>PATHGUARD</h2>
      <p class="lead">Enemies are marching on the realm. Build towers beside the road, combine their powers, and survive all <strong>15 waves</strong>.</p>
      <div class="how-to">
        <div><span>1</span><p><strong>Build</strong><small>Pick a tower, then click a grass tile.</small></p></div>
        <div><span>2</span><p><strong>Upgrade</strong><small>Click your towers to improve their power.</small></p></div>
        <div><span>3</span><p><strong>Survive</strong><small>Earn coins from defeats. Don't let lives hit zero.</small></p></div>
      </div>
      <div class="enemy-legend">
        <span><i class="dot grunt"></i> Grunt</span>
        <span><i class="dot runner"></i> Runner · wave 3</span>
        <span><i class="dot tank"></i> Tank · wave 5</span>
      </div>
      <button id="start-btn" class="btn primary">Begin Defense</button>
      <small class="modal-foot">Tip: Frost towers make Cannon splash damage much easier to land.</small>
    </div>
  </div>

  <div id="end-screen" class="overlay hidden">
    <div class="modal end-modal">
      <div id="end-icon" class="end-icon">🏰</div>
      <div class="eyebrow" id="end-eyebrow">THE REALM HAS FALLEN</div>
      <h2 id="end-title">Game Over</h2>
      <p id="end-message" class="lead">The enemy broke through your defenses.</p>
      <div class="end-stats">
        <div><strong id="end-wave">0</strong><small>Waves cleared</small></div>
        <div><strong id="end-towers">0</strong><small>Towers built</small></div>
        <div><strong id="end-coins">0</strong><small>Coins earned</small></div>
      </div>
      <button id="restart-btn" class="btn primary">Defend Again</button>
    </div>
  </div>

  <script src="./script.js"></script>
</body>
</html>
style.css328 lines
/* Pathguard tower defense styles */
:root {
  --bg: #0c1420;
  --surface: #131e2e;
  --surface-2: #19273a;
  --line: #283950;
  --text: #edf4ff;
  --muted: #93a6bd;
  --gold: #ffc94a;
  --green: #53d78d;
  --red: #ff6b75;
  --blue: #67b7ff;
  --radius: 14px;
}

* { box-sizing: border-box; }

body {
  margin: 0;
  min-height: 100vh;
  color: var(--text);
  background:
    radial-gradient(circle at 12% 0%, rgba(61, 120, 164, .17), transparent 36%),
    radial-gradient(circle at 100% 100%, rgba(112, 72, 166, .12), transparent 35%),
    var(--bg);
  font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}

button { font: inherit; }
button:focus-visible { outline: 3px solid rgba(103, 183, 255, .55); outline-offset: 2px; }
.hidden { display: none !important; }

.app {
  width: min(1420px, 100%);
  margin: auto;
  padding: 20px clamp(14px, 3vw, 34px) 30px;
}

.topbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 20px;
  margin-bottom: 18px;
}

.brand { display: flex; align-items: center; gap: 12px; }
.brand-mark {
  display: grid;
  place-items: center;
  width: 48px;
  height: 48px;
  border: 1px solid #34516e;
  border-radius: 13px;
  background: linear-gradient(145deg, #1b344c, #132235);
  font-size: 25px;
}
.brand h1 {
  margin: 0;
  font-size: 23px;
  line-height: 1;
  letter-spacing: 3px;
  font-weight: 900;
}
.brand p { margin: 6px 0 0; color: var(--muted); font-size: 12px; }

.stats { display: flex; gap: 10px; }
.stat {
  display: flex;
  align-items: center;
  gap: 10px;
  min-width: 112px;
  padding: 9px 13px;
  border: 1px solid var(--line);
  border-radius: 12px;
  background: rgba(19, 30, 46, .9);
}
.stat-icon { font-size: 20px; }
.stat small { display: block; color: var(--muted); font-size: 10px; text-transform: uppercase; letter-spacing: 1px; }
.stat strong { display: block; margin-top: 1px; font-size: 19px; line-height: 1.15; font-variant-numeric: tabular-nums; }
.stat.coins strong { color: var(--gold); }
.stat.lives strong { color: #ff8c96; }
.stat.wave strong { color: var(--blue); }

.game-layout {
  display: grid;
  grid-template-columns: minmax(0, 1fr) 300px;
  gap: 18px;
  align-items: start;
}

.board-wrap {
  position: relative;
  overflow: hidden;
  border: 1px solid #30445c;
  border-radius: var(--radius);
  background: #234c48;
  box-shadow: 0 20px 55px rgba(0, 0, 0, .35);
}
canvas {
  display: block;
  width: 100%;
  height: auto;
  cursor: crosshair;
  touch-action: none;
  user-select: none;
}
.board-hint {
  position: absolute;
  left: 50%;
  bottom: 14px;
  transform: translateX(-50%);
  width: max-content;
  max-width: calc(100% - 28px);
  padding: 8px 14px;
  border: 1px solid rgba(255,255,255,.16);
  border-radius: 999px;
  color: #f3f8ff;
  background: rgba(7, 14, 22, .82);
  box-shadow: 0 4px 16px rgba(0,0,0,.2);
  font-size: 12px;
  text-align: center;
  pointer-events: none;
  transition: opacity .2s;
}
.board-hint.fade { opacity: 0; }

.sidebar { display: grid; gap: 13px; }
.panel {
  padding: 15px;
  border: 1px solid var(--line);
  border-radius: var(--radius);
  background: linear-gradient(155deg, rgba(25, 39, 58, .98), rgba(17, 28, 43, .98));
}
.panel-title { display: flex; align-items: center; justify-content: space-between; gap: 8px; margin-bottom: 12px; }
.panel-title h2 { margin: 0; font-size: 13px; letter-spacing: .4px; }
.panel-title span { color: var(--muted); font-size: 10px; }

.tower-list { display: grid; gap: 8px; }
.tower-card {
  position: relative;
  display: grid;
  grid-template-columns: 43px minmax(0, 1fr) auto;
  align-items: center;
  gap: 10px;
  width: 100%;
  padding: 10px;
  border: 1px solid #2e4056;
  border-radius: 11px;
  color: var(--text);
  background: #152235;
  text-align: left;
  cursor: pointer;
  transition: border-color .15s, background .15s, transform .15s;
}
.tower-card:hover:not(.disabled) { border-color: #5b7ea3; background: #1b2c43; transform: translateY(-1px); }
.tower-card.selected { border-color: #75c0ff; background: #193650; box-shadow: 0 0 0 2px rgba(103,183,255,.12); }
.tower-card.disabled { opacity: .45; cursor: not-allowed; }
.tower-avatar {
  display: grid;
  place-items: center;
  width: 43px;
  height: 43px;
  border-radius: 10px;
  font-size: 24px;
  font-weight: 900;
}
.arrow-avatar { color: #ffe098; background: linear-gradient(145deg, #715026, #413019); }
.cannon-avatar { color: #d4dee8; background: linear-gradient(145deg, #536677, #293946); }
.frost-avatar { color: #c7f4ff; background: linear-gradient(145deg, #287a9c, #184358); }
.tower-info { min-width: 0; }
.tower-info strong { display: block; font-size: 13px; }
.tower-info small { display: block; overflow: hidden; margin-top: 4px; color: var(--muted); font-size: 10px; white-space: nowrap; text-overflow: ellipsis; }
.cost { color: var(--gold); font-size: 12px; font-weight: 800; white-space: nowrap; }
kbd {
  display: inline-block;
  min-width: 17px;
  margin-left: 3px;
  padding: 1px 4px;
  border: 1px solid #46566b;
  border-radius: 4px;
  color: #c0cede;
  background: #263549;
  font: 9px/1.4 inherit;
  text-align: center;
}
.tower-card.selected kbd { border-color: #669dcc; background: #214b6c; }

.selection-empty { padding: 8px 6px 4px; color: var(--muted); text-align: center; }
.selection-empty span { display: block; margin-bottom: 7px; font-size: 26px; opacity: .7; }
.selection-empty p { margin: 0; font-size: 11px; line-height: 1.6; }
.selected-head { display: flex; align-items: flex-start; justify-content: space-between; gap: 8px; }
.selected-head strong { font-size: 15px; }
.selected-head small { display: block; margin-top: 4px; color: var(--muted); font-size: 10px; }
.level-badge {
  display: inline-block;
  margin-left: 6px;
  padding: 2px 6px;
  border-radius: 5px;
  color: #bfe5ff;
  background: #214b6c;
  font-size: 10px;
  vertical-align: 2px;
}
.tower-stats { display: grid; grid-template-columns: repeat(3, 1fr); gap: 6px; margin: 13px 0 10px; }
.tower-stats div { padding: 7px 5px; border-radius: 8px; background: rgba(6, 13, 22, .28); text-align: center; }
.tower-stats small { display: block; color: var(--muted); font-size: 9px; text-transform: uppercase; }
.tower-stats strong { display: block; margin-top: 3px; font-size: 13px; }
.upgrade-note { min-height: 15px; margin: 0 0 10px; color: #a9bfd5; font-size: 10px; line-height: 1.45; }
.selection-actions { display: grid; grid-template-columns: 1fr auto; gap: 7px; }

.btn {
  padding: 10px 13px;
  border: 1px solid transparent;
  border-radius: 9px;
  color: #07121c;
  font-weight: 800;
  font-size: 12px;
  cursor: pointer;
  transition: filter .15s, transform .15s;
}
.btn:hover:not(:disabled) { filter: brightness(1.09); }
.btn:active:not(:disabled) { transform: translateY(1px); }
.btn:disabled { opacity: .42; cursor: not-allowed; }
.btn.primary { width: 100%; padding: 13px; color: #071a13; background: linear-gradient(135deg, #72edb1, #3fcf8c); font-size: 14px; }
.btn.upgrade { color: #071625; background: linear-gradient(135deg, #8bd2ff, #55a9ed); }
.btn.sell { padding-inline: 12px; color: #ffdce0; border-color: #693642; background: #3c202a; }
.btn.secondary { color: #d3e2f1; border-color: #344960; background: #1a2a3d; }
.controls-panel { display: grid; gap: 8px; }
.wave-btn { color: #1c1402; background: linear-gradient(135deg, #ffe080, #f7ba3c); font-size: 13px; }
.wave-btn.wave-active { color: #d8e5f1; background: #263a4e; }
.control-row { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; }
.shortcut-tip { margin: 3px 0 0; color: #7f94aa; font-size: 9px; line-height: 1.6; text-align: center; }

.overlay {
  position: fixed;
  z-index: 20;
  inset: 0;
  display: grid;
  place-items: center;
  overflow-y: auto;
  padding: 22px;
  background: rgba(4, 10, 17, .82);
  backdrop-filter: blur(8px);
}
.modal {
  width: min(540px, 100%);
  padding: clamp(26px, 5vw, 42px);
  border: 1px solid #39526c;
  border-radius: 20px;
  background: linear-gradient(155deg, #192b40, #101a29);
  box-shadow: 0 30px 90px rgba(0, 0, 0, .55);
  text-align: center;
}
.eyebrow { color: #78bdec; font-size: 10px; font-weight: 900; letter-spacing: 2.4px; }
.modal h2 {
  margin: 8px 0 12px;
  font-size: clamp(35px, 8vw, 54px);
  line-height: 1;
  letter-spacing: 4px;
  font-weight: 950;
}
.lead { margin: 0 auto 22px; max-width: 440px; color: #adbed0; font-size: 13px; line-height: 1.7; }
.lead strong { color: #f4f8ff; }
.how-to { display: grid; grid-template-columns: repeat(3, 1fr); gap: 9px; margin-bottom: 20px; text-align: left; }
.how-to div { padding: 12px; border: 1px solid #2c4157; border-radius: 11px; background: rgba(7, 15, 25, .25); }
.how-to span {
  display: grid;
  place-items: center;
  width: 23px;
  height: 23px;
  margin-bottom: 9px;
  border-radius: 50%;
  color: #8bd2ff;
  background: #214b6c;
  font-size: 11px;
  font-weight: 900;
}
.how-to strong { display: block; font-size: 12px; }
.how-to small { display: block; margin-top: 4px; color: var(--muted); font-size: 10px; line-height: 1.45; }
.enemy-legend { display: flex; justify-content: center; flex-wrap: wrap; gap: 14px; margin-bottom: 22px; color: #a7bad0; font-size: 10px; }
.enemy-legend span { display: flex; align-items: center; gap: 5px; }
.dot { width: 9px; height: 9px; border-radius: 50%; }
.dot.grunt { background: #e46666; }
.dot.runner { background: #f4c453; }
.dot.tank { background: #9a6fd0; }
.modal-foot { display: block; margin-top: 13px; color: #758ba3; font-size: 10px; }
.end-icon { font-size: 50px; }
.end-stats { display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; margin: 22px 0; }
.end-stats div { padding: 14px 8px; border: 1px solid #2e4259; border-radius: 10px; background: rgba(5, 12, 20, .24); }
.end-stats strong { display: block; color: #f5d678; font-size: 24px; }
.end-stats small { display: block; margin-top: 4px; color: var(--muted); font-size: 10px; }
.modal.victory { border-color: #4b9c78; }
.modal.victory h2 { color: #83edba; }

@media (max-width: 980px) {
  .game-layout { grid-template-columns: 1fr; }
  .sidebar { grid-template-columns: 1fr 1fr; }
  .controls-panel { grid-column: 1 / -1; }
  .tower-list { grid-template-columns: repeat(3, 1fr); }
  .tower-card { grid-template-columns: 36px minmax(0,1fr); padding: 8px; gap: 7px; }
  .tower-avatar { width: 36px; height: 36px; font-size: 20px; }
  .tower-card .cost { grid-column: 2; }
  .tower-info small { display: none; }
}

@media (max-width: 650px) {
  .app { padding: 13px 10px 22px; }
  .topbar { align-items: flex-start; gap: 10px; }
  .brand p { display: none; }
  .brand-mark { width: 40px; height: 40px; }
  .brand h1 { font-size: 17px; letter-spacing: 2px; }
  .stats { gap: 5px; }
  .stat { min-width: 0; padding: 7px 8px; gap: 5px; }
  .stat-icon { display: none; }
  .stat strong { font-size: 15px; }
  .stat small { font-size: 8px; }
  .sidebar { grid-template-columns: 1fr; }
  .controls-panel { grid-column: auto; }
  .tower-list { grid-template-columns: 1fr; }
  .tower-card { grid-template-columns: 40px minmax(0,1fr) auto; }
  .tower-card .cost { grid-column: auto; }
  .tower-info small { display: block; }
  .how-to { grid-template-columns: 1fr; }
  .how-to div { display: grid; grid-template-columns: 28px 1fr; column-gap: 9px; align-items: center; }
  .how-to span { grid-row: 1 / 3; margin: 0; }
  .board-hint { bottom: 8px; font-size: 10px; }
}
script.js957 lines
"use strict";

// ---------- Setup ----------
const canvas = document.getElementById("game");
const ctx = canvas.getContext("2d");
const W = canvas.width;
const H = canvas.height;
const TILE = 40;
const MAX_WAVES = 15;
const PATH_WIDTH = 58;

const PATH = [
  { x: -50, y: 100 },
  { x: 180, y: 100 },
  { x: 180, y: 340 },
  { x: 380, y: 340 },
  { x: 380, y: 100 },
  { x: 620, y: 100 },
  { x: 620, y: 500 },
  { x: 820, y: 500 },
  { x: 820, y: 260 },
  { x: 920, y: 260 }
];

const TOWER_TYPES = {
  arrow: {
    name: "Archer", cost: 50, range: 145, damage: 13, cooldown: 0.44,
    role: "Fast single-target shots", color: "#f2c166",
    description: "Quick arrows with excellent range."
  },
  cannon: {
    name: "Cannon", cost: 100, range: 138, damage: 38, cooldown: 1.55,
    role: "Heavy area splash damage", color: "#c5d0da", splash: 62,
    description: "Explosive shells damage whole groups."
  },
  frost: {
    name: "Frost", cost: 75, range: 118, damage: 7, cooldown: 1.0,
    role: "Slows every enemy in range", color: "#83e5ff", slow: 0.52,
    description: "Icy pulses slow crowds for other towers."
  }
};

const ENEMY_TYPES = {
  grunt:  { name: "Grunt",  hp: 46,  speed: 59,  bounty: 9,  radius: 12, color: "#df6262", armor: 0 },
  runner: { name: "Runner", hp: 34,  speed: 108, bounty: 10, radius: 9,  color: "#f2c14f", armor: 0 },
  tank:   { name: "Tank",   hp: 155, speed: 39,  bounty: 22, radius: 16, color: "#9a70c7", armor: 3 }
};

const $ = id => document.getElementById(id);
const ui = {
  coins: $("coins"), lives: $("lives"), wave: $("wave"),
  enemyCount: $("enemy-count"), hint: $("board-hint"),
  buildButtons: [...document.querySelectorAll(".tower-card")],
  selectionEmpty: $("selection-empty"), selectionDetail: $("selection-detail"),
  selectedName: $("selected-name"), selectedLevel: $("selected-level"),
  selectedRole: $("selected-role"), statDamage: $("stat-damage"),
  statRange: $("stat-range"), statRate: $("stat-rate"),
  upgradeNote: $("upgrade-note"), upgradeBtn: $("upgrade-btn"),
  sellBtn: $("sell-btn"), waveBtn: $("wave-btn"),
  pauseBtn: $("pause-btn"), speedBtn: $("speed-btn"),
  startScreen: $("start-screen"), endScreen: $("end-screen")
};

let G;
let decorations = [];

function resetGame() {
  G = {
    mode: "playing", paused: false, speed: 1, time: 0,
    coins: 220, lives: 20, wave: 0, wavesCleared: 0,
    towers: [], enemies: [], projectiles: [], particles: [], rings: [], floaters: [],
    waveActive: false, spawnQueue: [], spawnTimer: 0, spawnInterval: 0.7,
    buildType: null, selectedTower: null, banner: null,
    towersBuilt: 0, coinsEarned: 0, hintOverride: "", hintTimer: 0,
    mouse: { x: 0, y: 0, inside: false }
  };
  makeDecorations();
}

function makeDecorations() {
  let seed = 92821;
  const rand = () => {
    seed |= 0; seed = seed + 0x6D2B79F5 | 0;
    let t = Math.imul(seed ^ seed >>> 15, 1 | seed);
    t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t;
    return ((t ^ t >>> 14) >>> 0) / 4294967296;
  };
  decorations = [];
  for (let i = 0; i < 110; i++) {
    const x = rand() * W;
    const y = rand() * H;
    if (distanceToPath(x, y) > PATH_WIDTH / 2 + 14) {
      decorations.push({ x, y, size: 1.5 + rand() * 2.5, shade: rand() });
    }
  }
}

// ---------- Geometry helpers ----------
function dist(ax, ay, bx, by) { return Math.hypot(ax - bx, ay - by); }

function pointSegmentDistance(px, py, ax, ay, bx, by) {
  const dx = bx - ax, dy = by - ay;
  const lengthSq = dx * dx + dy * dy;
  let t = lengthSq ? ((px - ax) * dx + (py - ay) * dy) / lengthSq : 0;
  t = Math.max(0, Math.min(1, t));
  return dist(px, py, ax + dx * t, ay + dy * t);
}

function distanceToPath(x, y) {
  let best = Infinity;
  for (let i = 0; i < PATH.length - 1; i++) {
    best = Math.min(best, pointSegmentDistance(x, y, PATH[i].x, PATH[i].y, PATH[i + 1].x, PATH[i + 1].y));
  }
  return best;
}

function towerStats(tower) {
  const base = TOWER_TYPES[tower.type];
  const level = tower.level - 1;
  return {
    damage: base.damage * (1 + level * 0.58),
    range: base.range + level * 14,
    cooldown: base.cooldown * Math.pow(0.88, level),
    splash: base.splash ? base.splash + level * 7 : 0,
    slow: base.slow || 1
  };
}

function upgradeCost(tower) {
  const base = TOWER_TYPES[tower.type].cost;
  return Math.round(base * (tower.level === 1 ? 0.8 : 1.25));
}

function sellValue(tower) { return Math.floor(tower.invested * 0.7); }
function snap(v) { return Math.floor(v / TILE) * TILE + TILE / 2; }

function canPlaceAt(x, y) {
  if (x < 22 || x > W - 22 || y < 22 || y > H - 22) return false;
  if (distanceToPath(x, y) < PATH_WIDTH / 2 + 26) return false;
  return !G.towers.some(t => dist(x, y, t.x, t.y) < 42);
}

// ---------- Waves and enemies ----------
function buildWave(wave) {
  const list = [];
  const count = 5 + wave * 2;
  for (let i = 0; i < count; i++) {
    if (wave >= 5 && i % 6 === 5) list.push("tank");
    else if (wave >= 3 && i % 3 === 2) list.push("runner");
    else list.push("grunt");
  }
  if (wave === MAX_WAVES) list.push("tank", "tank", "runner", "runner");
  return list;
}

function startNextWave() {
  if (G.mode !== "playing" || G.paused || G.waveActive || G.wave >= MAX_WAVES) return;
  G.wave++;
  G.waveActive = true;
  G.spawnQueue = buildWave(G.wave);
  G.spawnInterval = Math.max(0.34, 0.78 - G.wave * 0.025);
  G.spawnTimer = 0.15;
  showBanner(`WAVE ${G.wave}`, G.wave === MAX_WAVES ? "Final assault!" : `${G.spawnQueue.length} enemies incoming`, 2.1);
}

function spawnEnemy(type) {
  const base = ENEMY_TYPES[type];
  const scale = 1 + (G.wave - 1) * 0.3 + Math.pow(G.wave - 1, 2) * 0.025;
  const hp = Math.round(base.hp * scale);
  G.enemies.push({
    type, x: PATH[0].x, y: PATH[0].y, wp: 1,
    hp, maxHp: hp, speed: base.speed, bounty: base.bounty + Math.floor(G.wave * 0.6),
    radius: base.radius, armor: base.armor + (type === "tank" ? G.wave * 0.22 : 0),
    slowTimer: 0, slowFactor: 1, dead: false, escaped: false,
    traveled: 0, hitFlash: 0, phase: Math.random() * Math.PI * 2
  });
}

function updateEnemies(dt) {
  for (const e of G.enemies) {
    if (e.dead) continue;
    e.hitFlash = Math.max(0, e.hitFlash - dt);
    if (e.slowTimer > 0) e.slowTimer -= dt;
    else e.slowFactor = 1;

    let movement = e.speed * e.slowFactor * dt;
    while (movement > 0 && !e.escaped) {
      const target = PATH[e.wp];
      if (!target) { e.escaped = true; break; }
      const dx = target.x - e.x, dy = target.y - e.y;
      const d = Math.hypot(dx, dy);
      if (d <= movement) {
        e.x = target.x; e.y = target.y;
        e.traveled += d;
        movement -= d;
        e.wp++;
        if (e.wp >= PATH.length) e.escaped = true;
      } else {
        e.x += dx / d * movement;
        e.y += dy / d * movement;
        e.traveled += movement;
        movement = 0;
      }
    }

    if (e.escaped) {
      e.dead = true;
      const loss = e.type === "tank" ? 2 : 1;
      G.lives = Math.max(0, G.lives - loss);
      addFloater(W - 90, 238, `-${loss} ❤`, "#ff8c96", 1.2);
      if (G.lives <= 0) finishGame(false);
    }
  }
  G.enemies = G.enemies.filter(e => !e.dead);
}

function dealDamage(enemy, amount, tower) {
  if (!enemy || enemy.dead) return;
  const actual = Math.max(1, amount - enemy.armor);
  enemy.hp -= actual;
  enemy.hitFlash = 0.09;
  if (enemy.hp <= 0) {
    enemy.dead = true;
    G.coins += enemy.bounty;
    G.coinsEarned += enemy.bounty;
    if (tower) tower.kills++;
    addFloater(enemy.x, enemy.y - enemy.radius, `+${enemy.bounty}`, "#ffd76a", 0.9);
    burst(enemy.x, enemy.y, ENEMY_TYPES[enemy.type].color, enemy.type === "tank" ? 12 : 7);
  }
}

// ---------- Towers and combat ----------
function updateTowers(dt) {
  for (const tower of G.towers) {
    const stats = towerStats(tower);
    tower.cooldownLeft -= dt;
    let target = null;
    let bestProgress = -Infinity;
    for (const e of G.enemies) {
      if (e.dead) continue;
      if (dist(tower.x, tower.y, e.x, e.y) <= stats.range + e.radius && e.traveled > bestProgress) {
        target = e;
        bestProgress = e.traveled;
      }
    }

    if (target) {
      tower.angle = Math.atan2(target.y - tower.y, target.x - tower.x);
      if (tower.cooldownLeft <= 0) {
        fireTower(tower, target, stats);
        tower.cooldownLeft = stats.cooldown;
      }
    } else if (tower.cooldownLeft < 0) {
      tower.cooldownLeft = 0;
    }
  }
}

function fireTower(tower, target, stats) {
  if (tower.type === "arrow") {
    G.projectiles.push({
      kind: "arrow", x: tower.x + Math.cos(tower.angle) * 19,
      y: tower.y + Math.sin(tower.angle) * 19, target,
      damage: stats.damage, speed: 490, tower, angle: tower.angle
    });
  } else if (tower.type === "cannon") {
    G.projectiles.push({
      kind: "shell", x: tower.x, y: tower.y, tx: target.x, ty: target.y,
      damage: stats.damage, splash: stats.splash, speed: 300, tower, angle: tower.angle
    });
    burst(tower.x + Math.cos(tower.angle) * 23, tower.y + Math.sin(tower.angle) * 23, "#ffd19a", 3);
  } else {
    G.rings.push({ x: tower.x, y: tower.y, maxR: stats.range, life: 0.42, maxLife: 0.42 });
    for (const e of G.enemies) {
      if (!e.dead && dist(tower.x, tower.y, e.x, e.y) <= stats.range + e.radius) {
        dealDamage(e, stats.damage, tower);
        e.slowFactor = stats.slow;
        e.slowTimer = Math.max(e.slowTimer, 1.5);
      }
    }
  }
}

function explode(p) {
  G.rings.push({ x: p.tx, y: p.ty, maxR: p.splash, life: 0.3, maxLife: 0.3, explosion: true });
  burst(p.tx, p.ty, "#ffb15e", 12);
  for (const e of G.enemies) {
    if (e.dead) continue;
    const d = dist(p.tx, p.ty, e.x, e.y);
    if (d <= p.splash + e.radius) {
      const falloff = 1 - 0.55 * Math.min(1, d / (p.splash + e.radius));
      dealDamage(e, p.damage * falloff, p.tower);
    }
  }
}

function updateProjectiles(dt) {
  for (const p of G.projectiles) {
    if (p.kind === "arrow") {
      if (!p.target || p.target.dead) { p.remove = true; continue; }
      const dx = p.target.x - p.x, dy = p.target.y - p.y;
      const d = Math.hypot(dx, dy);
      p.angle = Math.atan2(dy, dx);
      const step = p.speed * dt;
      if (d <= step + p.target.radius * 0.55) {
        dealDamage(p.target, p.damage, p.tower);
        p.remove = true;
      } else {
        p.x += dx / d * step;
        p.y += dy / d * step;
      }
    } else {
      const dx = p.tx - p.x, dy = p.ty - p.y;
      const d = Math.hypot(dx, dy);
      const step = p.speed * dt;
      p.angle = Math.atan2(dy, dx);
      if (d <= step + 5) {
        p.x = p.tx; p.y = p.ty;
        explode(p);
        p.remove = true;
      } else {
        p.x += dx / d * step;
        p.y += dy / d * step;
      }
    }
  }
  G.projectiles = G.projectiles.filter(p => !p.remove);
}

// ---------- Effects ----------
function burst(x, y, color, count) {
  for (let i = 0; i < count; i++) {
    const angle = Math.random() * Math.PI * 2;
    const speed = 30 + Math.random() * 90;
    G.particles.push({
      x, y, vx: Math.cos(angle) * speed, vy: Math.sin(angle) * speed,
      life: 0.3 + Math.random() * 0.35, maxLife: 0.65,
      size: 2 + Math.random() * 3, color
    });
  }
}

function addFloater(x, y, text, color, life = 1) {
  G.floaters.push({ x, y, text, color, life, maxLife: life });
}

function showBanner(title, sub = "", duration = 1.8) {
  G.banner = { title, sub, time: duration, maxTime: duration };
}

function flashHint(text) {
  G.hintOverride = text;
  G.hintTimer = 2.4;
  ui.hint.textContent = text;
  ui.hint.classList.remove("fade");
}

function updateEffects(dt) {
  for (const p of G.particles) {
    p.life -= dt;
    p.x += p.vx * dt;
    p.y += p.vy * dt;
    p.vx *= 0.94;
    p.vy = p.vy * 0.94 + 35 * dt;
  }
  G.particles = G.particles.filter(p => p.life > 0);
  for (const r of G.rings) r.life -= dt;
  G.rings = G.rings.filter(r => r.life > 0);
  for (const f of G.floaters) { f.life -= dt; f.y -= 25 * dt; }
  G.floaters = G.floaters.filter(f => f.life > 0);
  if (G.banner) {
    G.banner.time -= dt;
    if (G.banner.time <= 0) G.banner = null;
  }
  if (G.hintTimer > 0) G.hintTimer -= dt;
}

// ---------- Main update ----------
function update(dt) {
  G.time += dt;
  updateEffects(dt);

  if (G.waveActive) {
    G.spawnTimer -= dt;
    while (G.spawnTimer <= 0 && G.spawnQueue.length) {
      spawnEnemy(G.spawnQueue.shift());
      G.spawnTimer += G.spawnInterval;
    }
  }

  updateEnemies(dt);
  updateTowers(dt);
  updateProjectiles(dt);

  if (G.mode === "playing" && G.waveActive && !G.spawnQueue.length && !G.enemies.length) {
    G.waveActive = false;
    G.wavesCleared = G.wave;
    const bonus = 25 + G.wave * 5;
    G.coins += bonus;
    G.coinsEarned += bonus;
    if (G.wave >= MAX_WAVES) {
      finishGame(true);
    } else {
      showBanner("WAVE CLEARED", `+${bonus} bonus coins · Build and prepare`, 2.3);
    }
  }
  updateUI();
}

function finishGame(won) {
  if (G.mode === "over" || G.mode === "won") return;
  G.mode = won ? "won" : "over";
  G.paused = false;
  $("end-icon").textContent = won ? "👑" : "🏰";
  $("end-eyebrow").textContent = won ? "THE REALM IS SAFE" : "THE REALM HAS FALLEN";
  $("end-title").textContent = won ? "Victory!" : "Game Over";
  $("end-message").textContent = won
    ? `All ${MAX_WAVES} waves defeated. The road belongs to you, commander.`
    : `The enemy broke through on wave ${G.wave}. Try combining Frost with splash damage.`;
  $("end-wave").textContent = G.wavesCleared;
  $("end-towers").textContent = G.towersBuilt;
  $("end-coins").textContent = G.coinsEarned;
  document.querySelector(".end-modal").classList.toggle("victory", won);
  ui.endScreen.classList.remove("hidden");
  updateUI();
}

// ---------- Rendering ----------
function drawGround() {
  ctx.fillStyle = "#3f7c58";
  ctx.fillRect(0, 0, W, H);
  for (let y = 0; y < H; y += TILE) {
    for (let x = 0; x < W; x += TILE) {
      ctx.fillStyle = ((x / TILE + y / TILE) % 2 === 0) ? "rgba(255,255,255,.018)" : "rgba(0,0,0,.022)";
      ctx.fillRect(x, y, TILE, TILE);
    }
  }

  // Dirt road with a darker border.
  ctx.lineCap = "round";
  ctx.lineJoin = "round";
  ctx.beginPath();
  ctx.moveTo(PATH[0].x, PATH[0].y);
  for (let i = 1; i < PATH.length; i++) ctx.lineTo(PATH[i].x, PATH[i].y);
  ctx.strokeStyle = "#8f7a52";
  ctx.lineWidth = PATH_WIDTH + 10;
  ctx.stroke();
  ctx.strokeStyle = "#b89b68";
  ctx.lineWidth = PATH_WIDTH;
  ctx.stroke();
  ctx.strokeStyle = "rgba(92,65,37,.15)";
  ctx.lineWidth = 2;
  ctx.setLineDash([5, 17]);
  ctx.stroke();
  ctx.setLineDash([]);

  for (const d of decorations) {
    ctx.fillStyle = d.shade > 0.5 ? "rgba(28,82,50,.45)" : "rgba(174,202,110,.20)";
    ctx.fillRect(d.x, d.y, d.size, d.size + 2);
  }

  // Enemy gate.
  ctx.fillStyle = "#263442";
  ctx.fillRect(0, 65, 18, 70);
  ctx.fillStyle = "#111a24";
  ctx.fillRect(0, 74, 13, 52);
  ctx.fillStyle = "#d65d5d";
  ctx.beginPath();
  ctx.moveTo(17, 70); ctx.lineTo(40, 79); ctx.lineTo(17, 88); ctx.fill();

  // The keep at the end of the road.
  const kx = 910, ky = 260;
  ctx.fillStyle = "rgba(0,0,0,.2)";
  ctx.fillRect(kx - 26, ky - 43, 70, 84);
  ctx.fillStyle = "#6c7c89";
  ctx.fillRect(kx - 30, ky - 50, 64, 95);
  ctx.fillStyle = "#8b9aa4";
  ctx.fillRect(kx - 35, ky - 56, 17, 20);
  ctx.fillRect(kx - 11, ky - 56, 17, 20);
  ctx.fillRect(kx + 13, ky - 56, 17, 20);
  ctx.fillStyle = "#263442";
  ctx.fillRect(kx - 9, ky + 12, 22, 33);
  ctx.fillStyle = G.lives > 6 ? "#72d6a0" : "#ff737e";
  ctx.beginPath();
  ctx.moveTo(kx + 2, ky - 55); ctx.lineTo(kx + 32, ky - 45);
  ctx.lineTo(kx + 2, ky - 34); ctx.fill();
}

function drawRanges() {
  const draw = (x, y, range, valid = true) => {
    ctx.fillStyle = valid ? "rgba(150,220,255,.075)" : "rgba(255,100,100,.07)";
    ctx.strokeStyle = valid ? "rgba(178,230,255,.5)" : "rgba(255,120,120,.5)";
    ctx.lineWidth = 1.5;
    ctx.setLineDash([6, 5]);
    ctx.beginPath(); ctx.arc(x, y, range, 0, Math.PI * 2); ctx.fill(); ctx.stroke();
    ctx.setLineDash([]);
  };
  if (G.selectedTower && G.towers.includes(G.selectedTower)) {
    draw(G.selectedTower.x, G.selectedTower.y, towerStats(G.selectedTower).range);
  }
  if (G.buildType && G.mouse.inside && G.mode === "playing") {
    const x = snap(G.mouse.x), y = snap(G.mouse.y);
    const ok = canPlaceAt(x, y) && G.coins >= TOWER_TYPES[G.buildType].cost;
    draw(x, y, TOWER_TYPES[G.buildType].range, ok);
  }
}

function drawPlacementGhost() {
  if (!G.buildType || !G.mouse.inside || G.mode !== "playing") return;
  const x = snap(G.mouse.x), y = snap(G.mouse.y);
  const canAfford = G.coins >= TOWER_TYPES[G.buildType].cost;
  const valid = canPlaceAt(x, y) && canAfford;
  ctx.fillStyle = valid ? "rgba(108,235,166,.28)" : "rgba(255,92,92,.28)";
  ctx.fillRect(x - TILE / 2 + 2, y - TILE / 2 + 2, TILE - 4, TILE - 4);
  ctx.globalAlpha = 0.72;
  drawTowerShape({ x, y, type: G.buildType, level: 1, angle: -Math.PI / 2 }, valid);
  ctx.globalAlpha = 1;
}

function drawTowerShape(tower, valid = true) {
  const { x, y } = tower;
  ctx.save();
  ctx.translate(x, y);
  ctx.fillStyle = "rgba(0,0,0,.22)";
  ctx.beginPath(); ctx.ellipse(2, 8, 21, 12, 0, 0, Math.PI * 2); ctx.fill();

  ctx.fillStyle = valid ? "#596773" : "#a65454";
  ctx.beginPath(); ctx.arc(0, 3, 19, 0, Math.PI * 2); ctx.fill();
  ctx.strokeStyle = valid ? "#83939d" : "#d88989";
  ctx.lineWidth = 2;
  ctx.stroke();

  ctx.rotate(tower.angle + Math.PI / 2);
  if (tower.type === "arrow") {
    ctx.fillStyle = "#6d4727";
    ctx.fillRect(-10, -11, 20, 22);
    ctx.strokeStyle = "#f1cc7c";
    ctx.lineWidth = 2.5;
    ctx.beginPath(); ctx.arc(0, -7, 12, 0.2, Math.PI - 0.2); ctx.stroke();
    ctx.strokeStyle = "#f6e7b8";
    ctx.lineWidth = 1;
    ctx.beginPath(); ctx.moveTo(-9, -4); ctx.lineTo(9, -4); ctx.stroke();
    ctx.fillStyle = "#d9e4eb";
    ctx.beginPath(); ctx.moveTo(0, -21); ctx.lineTo(-3, -14); ctx.lineTo(3, -14); ctx.fill();
  } else if (tower.type === "cannon") {
    ctx.fillStyle = "#36434d";
    ctx.beginPath(); ctx.arc(0, 0, 12, 0, Math.PI * 2); ctx.fill();
    ctx.fillStyle = "#202b32";
    ctx.fillRect(-5, -25, 10, 23);
    ctx.fillStyle = "#71818b";
    ctx.fillRect(-7, -25, 14, 5);
    ctx.fillStyle = "#9aabb3";
    ctx.beginPath(); ctx.arc(0, 1, 4, 0, Math.PI * 2); ctx.fill();
  } else {
    ctx.fillStyle = "#21657d";
    ctx.beginPath(); ctx.arc(0, 1, 12, 0, Math.PI * 2); ctx.fill();
    ctx.fillStyle = valid ? "#9cf0ff" : "#e69c9c";
    ctx.beginPath();
    ctx.moveTo(0, -23); ctx.lineTo(8, -7); ctx.lineTo(4, 7);
    ctx.lineTo(-7, 5); ctx.lineTo(-8, -8); ctx.closePath(); ctx.fill();
    ctx.strokeStyle = "#e2fbff";
    ctx.lineWidth = 1;
    ctx.beginPath(); ctx.moveTo(0, -20); ctx.lineTo(1, 3); ctx.stroke();
  }
  ctx.restore();

  if (tower.level) {
    for (let i = 0; i < tower.level; i++) {
      ctx.fillStyle = i === 2 ? "#ffe082" : "#d6e3ed";
      ctx.beginPath();
      ctx.arc(x - (tower.level - 1) * 4 + i * 8, y + 25, 2.2, 0, Math.PI * 2);
      ctx.fill();
    }
  }
}

function drawEnemy(e) {
  const base = ENEMY_TYPES[e.type];
  const bob = Math.sin(G.time * 8 + e.phase) * 1.2;
  ctx.save();
  ctx.translate(e.x, e.y + bob);
  ctx.fillStyle = "rgba(0,0,0,.25)";
  ctx.beginPath(); ctx.ellipse(1, e.radius * 0.65, e.radius, e.radius * 0.55, 0, 0, Math.PI * 2); ctx.fill();

  if (e.slowTimer > 0) {
    ctx.strokeStyle = "rgba(135,235,255,.75)";
    ctx.lineWidth = 2;
    ctx.beginPath(); ctx.arc(0, 0, e.radius + 3, 0, Math.PI * 2); ctx.stroke();
  }

  ctx.fillStyle = e.hitFlash > 0 ? "#ffffff" : base.color;
  ctx.strokeStyle = "rgba(50,20,25,.55)";
  ctx.lineWidth = 2;
  if (e.type === "runner") {
    ctx.rotate(Math.PI / 4);
    ctx.fillRect(-e.radius * 0.75, -e.radius * 0.75, e.radius * 1.5, e.radius * 1.5);
    ctx.strokeRect(-e.radius * 0.75, -e.radius * 0.75, e.radius * 1.5, e.radius * 1.5);
  } else {
    ctx.beginPath(); ctx.arc(0, 0, e.radius, 0, Math.PI * 2); ctx.fill(); ctx.stroke();
    if (e.type === "tank") {
      ctx.strokeStyle = "#d2b4ec";
      ctx.lineWidth = 3;
      ctx.beginPath(); ctx.arc(0, 0, e.radius - 4, 0, Math.PI * 2); ctx.stroke();
    }
  }
  ctx.fillStyle = "#241d22";
  const eyeOffset = e.type === "runner" ? 0 : 3;
  ctx.beginPath(); ctx.arc(-4, -eyeOffset, 1.7, 0, Math.PI * 2); ctx.arc(4, -eyeOffset, 1.7, 0, Math.PI * 2); ctx.fill();
  ctx.restore();

  if (e.hp < e.maxHp || e.type === "tank") {
    const width = e.radius * 2.2;
    const y = e.y - e.radius - 9;
    ctx.fillStyle = "rgba(8,15,18,.72)";
    ctx.fillRect(e.x - width / 2, y, width, 4);
    ctx.fillStyle = e.hp / e.maxHp > 0.4 ? "#69d78d" : "#ff7079";
    ctx.fillRect(e.x - width / 2, y, width * Math.max(0, e.hp / e.maxHp), 4);
  }
}

function drawProjectiles() {
  for (const p of G.projectiles) {
    ctx.save();
    ctx.translate(p.x, p.y);
    ctx.rotate(p.angle);
    if (p.kind === "arrow") {
      ctx.strokeStyle = "#fff0b5";
      ctx.lineWidth = 2;
      ctx.beginPath(); ctx.moveTo(-9, 0); ctx.lineTo(6, 0); ctx.stroke();
      ctx.fillStyle = "#e9f2f5";
      ctx.beginPath(); ctx.moveTo(8, 0); ctx.lineTo(3, -3); ctx.lineTo(3, 3); ctx.fill();
    } else {
      ctx.fillStyle = "#252a2d";
      ctx.beginPath(); ctx.arc(0, 0, 6, 0, Math.PI * 2); ctx.fill();
      ctx.fillStyle = "#ffbf69";
      ctx.beginPath(); ctx.arc(-5, -2, 2, 0, Math.PI * 2); ctx.fill();
    }
    ctx.restore();
  }
}

function drawEffects() {
  for (const r of G.rings) {
    const progress = 1 - r.life / r.maxLife;
    ctx.globalAlpha = (1 - progress) * 0.8;
    ctx.strokeStyle = r.explosion ? "#ffd08a" : "#a4efff";
    ctx.lineWidth = r.explosion ? 5 : 3;
    ctx.beginPath(); ctx.arc(r.x, r.y, Math.max(1, r.maxR * progress), 0, Math.PI * 2); ctx.stroke();
    if (r.explosion) {
      ctx.fillStyle = `rgba(255,160,65,${(1 - progress) * 0.25})`;
      ctx.beginPath(); ctx.arc(r.x, r.y, r.maxR * progress, 0, Math.PI * 2); ctx.fill();
    }
    ctx.globalAlpha = 1;
  }
  for (const p of G.particles) {
    ctx.globalAlpha = Math.max(0, p.life / p.maxLife);
    ctx.fillStyle = p.color;
    ctx.fillRect(p.x - p.size / 2, p.y - p.size / 2, p.size, p.size);
  }
  ctx.globalAlpha = 1;
  ctx.textAlign = "center";
  ctx.font = "bold 14px system-ui";
  for (const f of G.floaters) {
    ctx.globalAlpha = Math.min(1, f.life / f.maxLife * 1.5);
    ctx.fillStyle = f.color;
    ctx.fillText(f.text, f.x, f.y);
  }
  ctx.globalAlpha = 1;
}

function drawBanner() {
  if (!G.banner) return;
  const b = G.banner;
  const alpha = Math.min(1, (b.maxTime - b.time) * 4, b.time * 2);
  ctx.globalAlpha = Math.max(0, alpha);
  ctx.textAlign = "center";
  ctx.fillStyle = "rgba(7,15,23,.72)";
  ctx.fillRect(W / 2 - 190, 28, 380, b.sub ? 65 : 45);
  ctx.fillStyle = "#f6fbff";
  ctx.font = "900 25px system-ui";
  ctx.fillText(b.title, W / 2, b.sub ? 56 : 59);
  if (b.sub) {
    ctx.fillStyle = "#b8cadd";
    ctx.font = "12px system-ui";
    ctx.fillText(b.sub, W / 2, 78);
  }
  ctx.globalAlpha = 1;
}

function render() {
  drawGround();
  drawRanges();
  for (const tower of G.towers) drawTowerShape(tower);
  drawPlacementGhost();
  for (const e of G.enemies) if (!e.dead) drawEnemy(e);
  drawProjectiles();
  drawEffects();
  drawBanner();

  if (G.selectedTower && !G.towers.includes(G.selectedTower)) G.selectedTower = null;
  if (G.paused && G.mode === "playing") {
    ctx.fillStyle = "rgba(5,12,19,.48)";
    ctx.fillRect(0, 0, W, H);
    ctx.textAlign = "center";
    ctx.fillStyle = "#f4f8fc";
    ctx.font = "900 42px system-ui";
    ctx.fillText("PAUSED", W / 2, H / 2);
    ctx.fillStyle = "#b8cadd";
    ctx.font = "14px system-ui";
    ctx.fillText("Press P or the Resume button to continue", W / 2, H / 2 + 30);
  }
}

// ---------- UI ----------
function updateUI() {
  ui.coins.textContent = Math.floor(G.coins);
  ui.lives.textContent = G.lives;
  ui.wave.textContent = `${G.wave}/${MAX_WAVES}`;
  ui.enemyCount.textContent = `${G.enemies.length + G.spawnQueue.length} enemies`;

  for (const btn of ui.buildButtons) {
    const type = btn.dataset.type;
    btn.classList.toggle("selected", G.buildType === type);
    btn.classList.toggle("disabled", G.coins < TOWER_TYPES[type].cost);
    btn.setAttribute("aria-pressed", G.buildType === type ? "true" : "false");
  }

  if (!G.selectedTower || !G.towers.includes(G.selectedTower)) {
    ui.selectionEmpty.classList.remove("hidden");
    ui.selectionDetail.classList.add("hidden");
  } else {
    const t = G.selectedTower;
    const stats = towerStats(t);
    const base = TOWER_TYPES[t.type];
    ui.selectionEmpty.classList.add("hidden");
    ui.selectionDetail.classList.remove("hidden");
    ui.selectedName.textContent = base.name;
    ui.selectedLevel.textContent = `Lv. ${t.level}`;
    ui.selectedRole.textContent = `${base.role} · ${t.kills} defeats`;
    ui.statDamage.textContent = Math.round(stats.damage);
    ui.statRange.textContent = Math.round(stats.range);
    ui.statRate.textContent = `${(1 / stats.cooldown).toFixed(1)}/s`;
    ui.sellBtn.textContent = `Sell +${sellValue(t)} 🪙`;
    if (t.level >= 3) {
      ui.upgradeNote.textContent = "Maximum level — this tower is fully upgraded.";
      ui.upgradeBtn.textContent = "Max Level";
      ui.upgradeBtn.disabled = true;
    } else {
      const cost = upgradeCost(t);
      const next = towerStats({ ...t, level: t.level + 1 });
      ui.upgradeNote.textContent = `Next: ${Math.round(next.damage)} damage, ${Math.round(next.range)} range, faster attacks.`;
      ui.upgradeBtn.textContent = `Upgrade · ${cost} 🪙`;
      ui.upgradeBtn.disabled = G.coins < cost;
    }
  }

  if (G.wave >= MAX_WAVES && !G.waveActive) {
    ui.waveBtn.textContent = "All Waves Cleared";
    ui.waveBtn.disabled = true;
  } else if (G.waveActive) {
    ui.waveBtn.textContent = `Wave ${G.wave} in Progress`;
    ui.waveBtn.disabled = true;
  } else {
    ui.waveBtn.textContent = `Start Wave ${G.wave + 1}`;
    ui.waveBtn.disabled = G.mode !== "playing";
  }
  ui.waveBtn.classList.toggle("wave-active", G.waveActive);
  ui.pauseBtn.textContent = G.paused ? "▶ Resume" : "⏸ Pause";
  ui.pauseBtn.disabled = G.mode !== "playing";
  ui.speedBtn.textContent = `▶ ${G.speed}×`;

  if (G.hintTimer <= 0) {
    if (G.buildType) {
      ui.hint.textContent = `Placing ${TOWER_TYPES[G.buildType].name}: click grass to build · Right-click or Esc to cancel`;
    } else if (G.selectedTower) {
      ui.hint.textContent = `${TOWER_TYPES[G.selectedTower.type].name} selected · Upgrade it or choose another tower to build`;
    } else if (G.waveActive) {
      ui.hint.textContent = `${G.enemies.length + G.spawnQueue.length} enemies remain in wave ${G.wave}`;
    } else if (G.wave === 0) {
      ui.hint.textContent = "Choose a tower, then click a grass tile to build.";
    } else {
      ui.hint.textContent = "Build or upgrade towers, then start the next wave when ready.";
    }
  }
}

// ---------- Input ----------
function pointerPosition(event) {
  const rect = canvas.getBoundingClientRect();
  return {
    x: (event.clientX - rect.left) * W / rect.width,
    y: (event.clientY - rect.top) * H / rect.height
  };
}

function selectBuild(type) {
  if (G.mode !== "playing") return;
  if (G.coins < TOWER_TYPES[type].cost) {
    flashHint(`You need ${TOWER_TYPES[type].cost} coins for a ${TOWER_TYPES[type].name} tower.`);
    return;
  }
  G.buildType = G.buildType === type ? null : type;
  G.selectedTower = null;
  updateUI();
}

function placeTower(x, y) {
  const base = TOWER_TYPES[G.buildType];
  if (G.coins < base.cost) { flashHint("Not enough coins."); return; }
  if (!canPlaceAt(x, y)) {
    flashHint("Build on open grass, away from the road and other towers.");
    return;
  }
  const tower = {
    x, y, type: G.buildType, level: 1, angle: -Math.PI / 2,
    cooldownLeft: 0.15, invested: base.cost, kills: 0
  };
  G.towers.push(tower);
  G.coins -= base.cost;
  G.towersBuilt++;
  G.selectedTower = tower;
  burst(x, y, base.color, 8);
  addFloater(x, y - 27, `-${base.cost}`, "#ffd76a", 0.8);
  if (G.coins < TOWER_TYPES[G.buildType].cost) G.buildType = null;
  updateUI();
}

function upgradeSelected() {
  const t = G.selectedTower;
  if (!t || !G.towers.includes(t) || t.level >= 3) return;
  const cost = upgradeCost(t);
  if (G.coins < cost) { flashHint("Not enough coins for that upgrade."); return; }
  G.coins -= cost;
  t.invested += cost;
  t.level++;
  G.rings.push({ x: t.x, y: t.y, maxR: 48, life: 0.45, maxLife: 0.45 });
  burst(t.x, t.y, TOWER_TYPES[t.type].color, 10);
  addFloater(t.x, t.y - 28, `LEVEL ${t.level}`, "#aeeaff", 1);
  updateUI();
}

function sellSelected() {
  const t = G.selectedTower;
  if (!t || !G.towers.includes(t)) return;
  const value = sellValue(t);
  G.coins += value;
  addFloater(t.x, t.y - 20, `+${value}`, "#ffd76a", 1);
  burst(t.x, t.y, "#b5c1ca", 7);
  G.towers = G.towers.filter(tower => tower !== t);
  G.selectedTower = null;
  updateUI();
}

canvas.addEventListener("pointermove", event => {
  const pos = pointerPosition(event);
  G.mouse.x = pos.x; G.mouse.y = pos.y; G.mouse.inside = true;
});
canvas.addEventListener("pointerleave", () => { G.mouse.inside = false; });
canvas.addEventListener("pointerdown", event => {
  if (event.button === 2) {
    G.buildType = null;
    updateUI();
    return;
  }
  if (event.button !== 0 || G.mode !== "playing" || G.paused) return;
  const pos = pointerPosition(event);
  const clickedTower = [...G.towers].reverse().find(t => dist(pos.x, pos.y, t.x, t.y) <= 24);
  if (clickedTower) {
    G.selectedTower = clickedTower;
    G.buildType = null;
  } else if (G.buildType) {
    placeTower(snap(pos.x), snap(pos.y));
  } else {
    G.selectedTower = null;
  }
  updateUI();
});
canvas.addEventListener("contextmenu", event => event.preventDefault());

for (const btn of ui.buildButtons) {
  btn.addEventListener("click", () => selectBuild(btn.dataset.type));
}
ui.upgradeBtn.addEventListener("click", upgradeSelected);
ui.sellBtn.addEventListener("click", sellSelected);
ui.waveBtn.addEventListener("click", startNextWave);
ui.pauseBtn.addEventListener("click", () => {
  if (G.mode !== "playing") return;
  G.paused = !G.paused;
  updateUI();
});
ui.speedBtn.addEventListener("click", () => {
  G.speed = G.speed === 1 ? 2 : G.speed === 2 ? 3 : 1;
  updateUI();
});

function togglePause() {
  if (G.mode !== "playing") return;
  G.paused = !G.paused;
  updateUI();
}

function cancelSelection() {
  G.buildType = null;
  G.selectedTower = null;
  updateUI();
}

document.addEventListener("keydown", event => {
  if (G.mode === "start" && (event.key === "Enter" || event.key === " ")) {
    event.preventDefault();
    beginGame();
    return;
  }
  if ((G.mode === "over" || G.mode === "won") && event.key === "Enter") {
    beginGame();
    return;
  }
  if (G.mode !== "playing") return;
  if (event.key === "1") selectBuild("arrow");
  else if (event.key === "2") selectBuild("cannon");
  else if (event.key === "3") selectBuild("frost");
  else if (event.key === "Escape") cancelSelection();
  else if (event.key.toLowerCase() === "p") togglePause();
  else if (event.key.toLowerCase() === "f") {
    G.speed = G.speed === 1 ? 2 : G.speed === 2 ? 3 : 1;
    updateUI();
  } else if (event.key === " ") {
    event.preventDefault();
    startNextWave();
  }
});

function beginGame() {
  resetGame();
  ui.startScreen.classList.add("hidden");
  ui.endScreen.classList.add("hidden");
  updateUI();
}

$("start-btn").addEventListener("click", beginGame);
$("restart-btn").addEventListener("click", beginGame);

// ---------- Game loop ----------
let lastTime = performance.now();
function frame(now) {
  const realDt = Math.min(0.05, (now - lastTime) / 1000 || 0);
  lastTime = now;
  if (G.mode === "playing" && !G.paused) update(realDt * G.speed);
  else updateEffects(realDt);
  render();
  requestAnimationFrame(frame);
}

resetGame();
G.mode = "start";
updateUI();
requestAnimationFrame(frame);
Want one like this?Start from this prompt and change anything you like.
Build your own →

← All examples