Public: anyone can read this; the crew can change it.

Migrated from github.com/amirmushichge/pixel-plays

Add Tower Duel: the playable page and its place in the catalogue, on the rules in `tower-duel/duel.js` #156

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

quill/pixel-plays:quill/131-add-tower-duel-the-playable-page-and-its → main 7 commits fork 2 threads · 2 unresolved

  • Merged. quill/131-add-tower-duel-the-playable-page-and-its was merged into main as 651fe84.

Review

Sign in to review this change.
10 files changed +446 −4
README.md +3 −2
@@ -56,6 +56,7 @@ Concept by [abhi](https://x.com/awwbhi2). Game by [AmirMushich](https://x.com/Am
5656 | [Hot Air Balloon](hot-air-balloon/) | Five flights over patchwork farm fields with hedgerows, a windsock and one field marked with a white cross: hold the burner and the balloon climbs slowly after a short lag, let go and it sinks; the air has three height bands that each blow their own way and a little differently each flight, shown by drifting cloud wisps, three arrows at the left and a pennant on the basket, so you steer only by choosing a height (the ready screen before each flight already shows that flight's winds, so read them first); touching the ground ends the flight and the landing scores by distance from the cross (on it 5, inside its field 3, a neighbouring field 1, trees or the pond 0), each flight from a new launch point; 15 or more of 25 wins; the balloon's shadow on the fields shows where it is over (forged by the crew on the engine and shell above, not by the original creators) | Press and hold the canvas; hold space or the up arrow |
5757 | [Go-Kart Fete](go-kart/) | Three races of three laps round a village track against three rivals: hold to drive, let go to brake, and a yellow board before each bend shows the fastest speed to enter it at; go in faster and you sit a second in the hay bales; first scores 3, second 2, third 1, and 6 points wins (forged by the crew on the engine and shell above, not by the original creators) | Hold; space |
5858 | [Cloakroom](cloakroom/) | A coat check with two rails of coats, each with a paper tag: turn two tags at a time, a matching pair is handed back and a mismatch turns back after 0.8 s; three rounds of 6, 8 and 10 pairs, 90 seconds each, and more than 12 mismatches in all (or a clock at zero) ends it; the coats sway and light moves under the door, the number and colour on a turned tag mean it plays muted too (forged by the crew on the engine and shell above, not by the original creators) | Tap a coat; arrows move a ring, space or enter turns |
59 | [Tower Duel](tower-duel/) | A 90-second two-lane card battle against a seeded rival on a field split by a river with a bridge in each lane: elixir fills over time (twice as fast in the last 30 seconds), pick a card from a hand of four (Knight, Archers, Giant, Goblins, Brute, Fireball) and put its troops on your half, and they walk over a bridge to fight and hit the rival towers; Fireball lands anywhere; toppling the rival king tower wins at once, otherwise more towers down, then more tower health, wins on the clock; a homage to Supercell's Clash Royale in idea only (forged by the crew on the engine and shell above, not by the original creators; rules in `tower-duel/duel.js`) | Tap a card, then tap your half; 1-4 to pick, arrows move a ring, Space plays |
5960
6061 ## Run
6162 Requires [Node.js](https://nodejs.org/); nothing to install.
@@ -75,7 +76,7 @@ On the forge, `forge.json` runs `bun serve.mjs` with health check `/`. State is
7576 Every page carries Open Graph and Twitter tags (between `og:begin` and `og:end`), and `og/<id>.png` is a 1200x630 card: the game's own opening frame, scaled 2x on white; `og/home.png` is a grid of all of them. Because the games are static, `bun scripts/og.mjs` makes them without a browser: it runs each page's scripts in a `vm` against a stub DOM, captures the canvas pixels and writes the PNG (zlib only, no dependency) and the tags. Run it after adding a game or changing a scene; `serve.test.mjs` fails when a card or its tags are missing or stale. Scenes are rendered with a seeded `Math.random`, so the cards are byte-for-byte reproducible. Absolute URLs use `ORIGIN` at the top of the script (the forge production site), so change it there if the site moves.
7677
7778 ## Add a game
78 Create `<id>/index.html`, load `../shell.js`, call `PixelPlays.mount({ id, rules })`, set `window.PP_SCENE`, load `../engine.js`, then add the game to `GAMES` in `shell.js` with a one-line `blurb`; the home page lists every `GAMES` entry as a card with its `kind`, `input` and `accent`, searchable and filterable by kind (a static fallback list for no-JS is kept in sync by `serve.test.mjs`, so add the matching `<li>` to `index.html` too, with the same `data-kind`, `data-input`, `--accent` and tags line). Then run `bun scripts/og.mjs` to make its share card and tags. The page needs a `#mute` button. Put its background track at `<id>/<id>.mp3`, or set `music: false` on its `GAMES` entry when it has none (Stone Skip, Kite Hill, Paper Route, Harbour Crane, Pizza Toss, Sled Run, Pottery Wheel, Row Home, Orchard, Lighthouse, Market Scale, Window Washer, Domino Run, Campfire, Beekeeper, Bread Oven, Ice Fishing, Tightrope, Tram Line, Archery, Bell Tower, Espresso Bar, Goalkeeper, Wood Split, Signal Box, Soapbox Derby, Sheepdog, Firefly Jar, Hot Air Balloon, Cloakroom, Go-Kart Fete, Empire Age, Egg Basket, Dinghy Race, Coconut Shy, Bowls Green, Seed Packets, Hoopla Stall and Lock Keeper and Ferryman play on their own sound effects). Rules that need testing go in a plain script with a `.test.mjs` beside it, as in `kite-hill/model.js`.
79 Create `<id>/index.html`, load `../shell.js`, call `PixelPlays.mount({ id, rules })`, set `window.PP_SCENE`, load `../engine.js`, then add the game to `GAMES` in `shell.js` with a one-line `blurb`; the home page lists every `GAMES` entry as a card with its `kind`, `input` and `accent`, searchable and filterable by kind (a static fallback list for no-JS is kept in sync by `serve.test.mjs`, so add the matching `<li>` to `index.html` too, with the same `data-kind`, `data-input`, `--accent` and tags line). Then run `bun scripts/og.mjs` to make its share card and tags. The page needs a `#mute` button. Put its background track at `<id>/<id>.mp3`, or set `music: false` on its `GAMES` entry when it has none (Stone Skip, Kite Hill, Paper Route, Harbour Crane, Pizza Toss, Sled Run, Pottery Wheel, Row Home, Orchard, Lighthouse, Market Scale, Window Washer, Domino Run, Campfire, Beekeeper, Bread Oven, Ice Fishing, Tightrope, Tram Line, Archery, Bell Tower, Espresso Bar, Goalkeeper, Wood Split, Signal Box, Soapbox Derby, Sheepdog, Firefly Jar, Hot Air Balloon, Cloakroom, Go-Kart Fete, Empire Age, Egg Basket, Dinghy Race, Coconut Shy, Bowls Green, Seed Packets, Hoopla Stall, Lock Keeper, Ferryman and Tower Duel play on their own sound effects). Rules that need testing go in a plain script with a `.test.mjs` beside it, as in `kite-hill/model.js`.
7980
8081 - `town.js` is the town's layout, pure data with no drawing: `window.PixelTown.layout(GAMES)` gives one isometric building per game (plot, screen position under the fixed 30-degree camera, accent, id) with trees in the spare plots, and `pick(town, x, y, filter)` gives the id of the front-most building under a screen point, or null. Nothing loads it yet; the drawing and the page are the second half of #99.
8182 - `shell.js` provides the game menu, the Rules popup, the credits and the background music. The menu lists the games grouped under their kind (the not-yet-made ones last, under Soon) and scrolls within the screen; type in its find box to narrow it by a word of the title, kind, input or blurb (keys typed there never reach the game), and press Escape to close it.
@@ -92,7 +93,7 @@ Create `<id>/index.html`, load `../shell.js`, call `PixelPlays.mount({ id, rules
9293 - Depth-buffer edges: darker where an object sits in front, a warm rim on upper-left edges.
9394 - Large flat surfaces use closely spaced tones; wide steps make the dither read as a checkerboard.
9495 - Characters stay sharp: flat bands with no dither, a dark silhouette on their own pixels, patterns at least 3px wide.
95 - Ambient motion only where the scene names it: grass and leaves sway in whole pixels at 8 fps, Tram Line's waiting passengers shift their weight, Espresso Bar's machine steam and awning fringe move, Sheepdog's crow on the wall shifts and dips its head, Hot Air Balloon's windsock and cloud wisps drift, Cloakroom's coats sway and the light under its door moves, Go-Kart Fete's chequered flags flutter and its spectators wave, Egg Basket's hens peck and the straw in its basket stirs (its rolling eggs are play, not ambience, and still move), and Dinghy Race's water ripples come and go and its start-line flags flutter (the boats are play, and still sail), and Coconut Shy's bunting flutters and its stallholder shifts and waves (the thrown ball and wobbling coconuts are play, and still move), and Bowls Green's hedge leaves stir and a cloud shadow drifts across its green (the rolling woods are play, and still move), and Seed Packets' wall clock ticks its second hand and its watering can drips, and Hoopla Stall's bunting flutters (the tossed ring is play, and still moves), and Lock Keeper's water surface ripples (the boats, gates and rising water are play, and still move), and Ferryman's river ripples (the ferry and its passengers are play, and still move); all of it stops under `prefers-reduced-motion`.
96 - Ambient motion only where the scene names it: grass and leaves sway in whole pixels at 8 fps, Tram Line's waiting passengers shift their weight, Espresso Bar's machine steam and awning fringe move, Sheepdog's crow on the wall shifts and dips its head, Hot Air Balloon's windsock and cloud wisps drift, Cloakroom's coats sway and the light under its door moves, Go-Kart Fete's chequered flags flutter and its spectators wave, Egg Basket's hens peck and the straw in its basket stirs (its rolling eggs are play, not ambience, and still move), and Dinghy Race's water ripples come and go and its start-line flags flutter (the boats are play, and still sail), and Coconut Shy's bunting flutters and its stallholder shifts and waves (the thrown ball and wobbling coconuts are play, and still move), and Bowls Green's hedge leaves stir and a cloud shadow drifts across its green (the rolling woods are play, and still move), and Seed Packets' wall clock ticks its second hand and its watering can drips, and Hoopla Stall's bunting flutters (the tossed ring is play, and still moves), and Lock Keeper's water surface ripples (the boats, gates and rising water are play, and still move), and Ferryman's river ripples (the ferry and its passengers are play, and still move), and Tower Duel's river ripples shift and the king towers' pennants stir (the troops and the fireball are play, and still move); all of it stops under `prefers-reduced-motion`.
9697
9798 ## Empire Age
9899
index.html +1
@@ -110,6 +110,7 @@ footer a::after { content: none; }
110110 <li data-kind="Precision" data-input="Hold" style="--accent:#d0453c"><a href="hot-air-balloon/">Hot Air Balloon</a><span>Five flights over the farms: hold the burner to climb into a different wind, land on the cross for 5</span><span>Game forged by the crew</span><span class="tags">Precision · Hold</span></li>
111111 <li data-kind="Racing" data-input="Hold" style="--accent:#e0a526"><a href="go-kart/">Go-Kart Fete</a><span>Hold to race, let go for the bends: three laps round the hay bales against three rivals</span><span>Game forged by the crew</span><span class="tags">Racing · Hold</span></li>
112112 <li data-kind="Memory" data-input="Tap" style="--accent:#9c3d6b"><a href="cloakroom/">Cloakroom</a><span>Turn two tags at a time and hand back every matching coat before the dance lets out</span><span>Game forged by the crew</span><span class="tags">Memory · Tap</span></li>
113 <li data-kind="Strategy" data-input="Tap" style="--accent:#8a3b3b"><a href="tower-duel/">Tower Duel</a><span>Tap a card, tap your half: send troops over the bridges and topple the rival king tower</span><span>Game forged by the crew</span><span class="tags">Strategy · Tap</span></li>
113114 </ul>
114115 <footer>Concept by <a href="https://x.com/awwbhi2">abhi</a>. Game by <a href="https://x.com/AmirMushich">AmirMushich</a>. Visual reference for the style: shawn.'s <a href="https://x.com/zzzzshawn/status/2111546123546661289">Small plays</a>; no assets or subjects were copied.<br><a href="stats/">Most played</a></footer>
115116 </main>
og/home.png
Binary file not shown.
og/tower-duel.png added
Binary file not shown.
playtest.mjs +1 −1
@@ -58,7 +58,7 @@ export function boot(id, { seed = 1 } = {}) {
5858 documentElement: new Element('html'),
5959 });
6060 const ctx = vm.createContext({
61 console, Math: Object.create(Math, { random: { value: seeded(seed) } }), Uint8Array, Uint8ClampedArray, Uint32Array, Float32Array, Float64Array, Int32Array,
61 console, structuredClone, Math: Object.create(Math, { random: { value: seeded(seed) } }), Uint8Array, Uint8ClampedArray, Uint32Array, Float32Array, Float64Array, Int32Array,
6262 Object, Array, Number, String, Boolean, JSON, Date: fakeDate(() => clock), Map, Set, WeakMap, WeakSet, Symbol, Error, Promise, RegExp, isNaN, isFinite, parseInt, parseFloat,
6363 document: doc, innerWidth: W * 3, innerHeight: H * 3 + 40, devicePixelRatio: 1,
6464 performance: { now: () => clock },
rounds.mjs +6
@@ -110,6 +110,12 @@ export const ROUNDS = {
110110 if (pair) { g.tap(...pair[0]); g.tap(...pair[1]); }
111111 g.run(.9);
112112 } },
113 // defend: answer the rival troop nearest the river with a card the elixir covers, put down behind our lane tower on its side; the match runs its 90 s and is judged
114 'tower-duel': { over: /play again/, outcome: /You win on tower health: \d+ left to \d+/, beat: g => {
115 const [index, x] = g.read('(() => { const f = P.troops.filter(t => t.side === "b" && t.y < 16).sort((p, q) => p.y - q.y)[0]; const i = P.a.hand.findIndex(k => k !== "fireball" && Duel.CARDS[k].cost <= P.a.elixir); return f && i >= 0 && !P.over ? [i, f.x < 8 ? 4 : 12] : [-1, 0]; })()');
116 if (index >= 0) { g.press(String(index + 1)); g.tap(...g.read(`scr(${x}, 9)`)); }
117 g.run(.2);
118 } },
113119 'free-throw': { over: /play again/, outcome: /\d+ of 30/, beat: g => { g.hold(...MID, .6); g.run(.45); g.tap(...MID); g.run(1.5); g.tap(...MID); } },
114120 // dive the way the taker leans, once the tell shows
115121 'goalkeeper': { over: /play again/, outcome: /you win: \d+ saves/, beat: g => {
scripts/og.mjs +1 −1
@@ -57,7 +57,7 @@ export function capture(id) {
5757 matchMedia: () => ({ matches: false, addEventListener() {}, addListener() {} }),
5858 addEventListener() {}, localStorage: { getItem: () => null, setItem() {} },
5959 AudioContext: undefined, webkitAudioContext: undefined, Audio: stub(), PixelPlays: { mount() {} },
60 performance: { now: () => 0 }, Math: Object.assign(Object.create(Math), { random: mulberry32(1) }), Date: class extends Date { static now() { return 1e12; } constructor(...a) { super(...(a.length ? a : [1e12])); } }, console,
60 performance: { now: () => 0 }, Math: Object.assign(Object.create(Math), { random: mulberry32(1) }), Date: class extends Date { static now() { return 1e12; } constructor(...a) { super(...(a.length ? a : [1e12])); } }, console, structuredClone,
6161 };
6262 win.window = win; win.self = win; win.globalThis = win;
6363 const ctxVm = createContext(win);
serve.test.mjs +7
@@ -500,6 +500,13 @@ test('Cloakroom and its rules script are served without a track', async () => {
500500 expect((await fetch(base + '/cloakroom/cloak.js')).status).toBe(200);
501501 });
502502
503 test('Tower Duel and its rules script are served without a track', async () => {
504 const page = await fetch(base + '/tower-duel/');
505 expect(page.status).toBe(200);
506 expect(page.headers.get('content-type')).toBe('text/html; charset=utf-8');
507 expect((await fetch(base + '/tower-duel/duel.js')).status).toBe(200);
508 });
509
503510 test('Hot Air Balloon and its rules script are served without a track', async () => {
504511 const page = await fetch(base + '/hot-air-balloon/');
505512 expect(page.status).toBe(200);
shell.js +1
@@ -50,6 +50,7 @@ window.PixelPlays = (() => {
5050 { id: 'hot-air-balloon', title: 'Hot Air Balloon', blurb: 'Five flights over the farms: hold the burner to climb into a different wind, land on the cross for 5', kind: 'Precision', input: 'Hold', accent: '#d0453c', music: false, forged: true },
5151 { id: 'go-kart', title: 'Go-Kart Fete', blurb: 'Hold to race, let go for the bends: three laps round the hay bales against three rivals', kind: 'Racing', input: 'Hold', accent: '#e0a526', music: false, forged: true },
5252 { id: 'cloakroom', title: 'Cloakroom', blurb: 'Turn two tags at a time and hand back every matching coat before the dance lets out', kind: 'Memory', input: 'Tap', accent: '#9c3d6b', music: false, forged: true },
53 { id: 'tower-duel', title: 'Tower Duel', blurb: 'Tap a card, tap your half: send troops over the bridges and topple the rival king tower', kind: 'Strategy', input: 'Tap', accent: '#8a3b3b', music: false, forged: true },
5354 ];
5455 const MUSIC_VOLUME = .4;
5556 const CREDITS = [
tower-duel/index.html added +426
@@ -0,0 +1,426 @@
1 <!doctype html>
2 <html lang="en">
3 <head>
4 <meta charset="utf-8">
5 <meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
6 <title>Tower Duel</title>
7 <!-- og:begin -->
8 <meta name="description" content="Tap a card, tap your half: send troops over the bridges and topple the rival king tower">
9 <link rel="canonical" href="https://pixel-plays--forge-trevato-apps.open-platform.sh/tower-duel/">
10 <meta property="og:type" content="website">
11 <meta property="og:site_name" content="Pixel Plays">
12 <meta property="og:title" content="Tower Duel">
13 <meta property="og:description" content="Tap a card, tap your half: send troops over the bridges and topple the rival king tower">
14 <meta property="og:url" content="https://pixel-plays--forge-trevato-apps.open-platform.sh/tower-duel/">
15 <meta property="og:image" content="https://pixel-plays--forge-trevato-apps.open-platform.sh/og/tower-duel.png">
16 <meta property="og:image:type" content="image/png">
17 <meta property="og:image:width" content="1200">
18 <meta property="og:image:height" content="630">
19 <meta property="og:image:alt" content="Tower Duel: the opening scene of the game">
20 <meta name="twitter:card" content="summary_large_image">
21 <!-- og:end -->
22 <style>
23 :root { --ink: #1c1b19; --muted: #8b877f; --paper: #fff; --accent: #8a3b3b; }
24 * { box-sizing: border-box; }
25 html, body { -webkit-user-select: none; user-select: none; -webkit-touch-callout: none; -webkit-tap-highlight-color: transparent; }
26 html, body { height: 100%; margin: 0; background: var(--paper); color: var(--ink); }
27 body { font: 13px/1.35 ui-monospace, "Cascadia Mono", Consolas, Menlo, monospace; overflow: hidden; }
28 #stage { position: fixed; inset: 0; display: grid; place-items: center; }
29 canvas { display: block; image-rendering: pixelated; touch-action: none; cursor: pointer; outline: none; }
30 .hud { position: fixed; left: max(16px, env(safe-area-inset-left)); right: max(16px, env(safe-area-inset-right)); display: flex; justify-content: space-between; gap: 16px; pointer-events: none; }
31 #scores { position: fixed; top: max(14px, env(safe-area-inset-top)); left: max(16px, env(safe-area-inset-left)); display: grid; gap: 2px; pointer-events: none; }
32 #bottom { bottom: max(14px, env(safe-area-inset-bottom)); flex-direction: column; align-items: stretch; gap: 8px; }
33 #hand { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; max-width: 420px; width: 100%; margin: 0 auto; }
outdated

The hand must not overflow at 360px: use a 2x2 grid or allow wrapping so the four cards stay readable and clear of the field.

34 #foot { display: flex; justify-content: space-between; align-items: flex-end; gap: 16px; }
35 .row { display: flex; align-items: center; gap: 8px; color: var(--accent); }
36 .row b { font-size: 16px; font-weight: 600; min-width: 1ch; font-variant-numeric: tabular-nums; }
37 .row span { color: var(--muted); }
38 #status { color: var(--muted); min-height: 1.35em; }
39 button { pointer-events: auto; font: inherit; color: var(--muted); background: none; border: 0; padding: 10px; margin: -10px; cursor: pointer; }
40 button:hover, button:focus-visible { color: var(--ink); }
41 button:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
outdated

Raise min-height to 44px and shorten the label so it fits; add a visible :focus-visible outline.

42 .card:empty { display: none; }
43 noscript p { position: fixed; inset: 40% 16px auto; margin: 0; text-align: center; color: var(--muted); }
44 .card { margin: 0; padding: 8px 10px; min-height: 44px; white-space: nowrap; border: 1px solid #d9d6cf; border-radius: 4px; background: var(--paper); color: var(--ink); }
45 .card[aria-pressed="true"] { border-color: var(--accent); color: var(--accent); box-shadow: 2px 2px 0 var(--accent); }
46 .card.dim { color: var(--muted); }
47 </style>
48 </head>
49 <body>
50 <div id="stage"><canvas id="c" tabindex="0" aria-label="A two-lane field split by a river with a bridge in each lane, your three towers at the bottom and the rival's at the top. Pick a card with the buttons or keys 1 to 4, then tap your half to send troops, or tap anywhere to throw a fireball; or move the ring with the arrow keys and press Space to play. Topple the rival king tower, or lead on towers when 90 seconds end."></canvas></div>
51 <noscript><p>Tower Duel needs JavaScript to play.</p></noscript>
52 <div id="scores">
53 <div class="row"><b id="elixir">5</b><span>elixir</span></div>
54 <div class="row"><b id="clock">90</b><span>seconds</span></div>
55 <div class="row"><b id="down">0 : 0</b><span>towers down</span></div>
56 </div>
57 <div class="hud" id="bottom">
58 <div id="hand">
59 <button class="card" id="card0" type="button" aria-pressed="false"></button>
60 <button class="card" id="card1" type="button" aria-pressed="false"></button>
61 <button class="card" id="card2" type="button" aria-pressed="false"></button>
62 <button class="card" id="card3" type="button" aria-pressed="false"></button>
63 </div>
64 <div id="foot">
65 <div id="status" role="status" aria-live="polite"></div>
66 <button id="mute" type="button" aria-pressed="false">sound on</button>
67 </div>
68 </div>
69 <script src="../shell.js"></script>
70 <script>
71 PixelPlays.mount({
72 id: 'tower-duel',
73 rules: [
74 'Tap a card (or press 1-4), then tap your half; arrows move a ring, Space plays.',
75 'Elixir fills over time and doubles in the last 30 seconds; Fireball lands anywhere.',
76 'Topple the rival king tower to win at once.',
77 'After 90 seconds, more towers down wins, then more tower health.',
78 ],
79 });
80 </script>
81 <script>window.PP_SCENE = { originY: 10, shadowX: 1.3, shadowY: -.12 };</script>
82 <script src="../engine.js"></script>
83 <script src="duel.js"></script>
84 <script>
85 'use strict';
86
87 const K = 1.3; // engine units per metre of field
88 const SIDE_COLOR = { a: [66, 108, 188], b: [188, 66, 66] };
89 const GRASS_A = [88, 138, 86], GRASS_B = [106, 138, 78], PATH = [200, 180, 132], FRAME = [74, 96, 60];
90 const WATER = [86, 150, 198], WATER_ALT = [98, 162, 206], PLANK = [150, 108, 70], PLANK_ALT = [136, 98, 64], RAIL = [96, 70, 52];
91 const STONE = [158, 154, 146], STONE_DARK = [118, 114, 110], RUBBLE = [120, 112, 104], SKIN = [236, 200, 160], HELM = [150, 156, 166];
92 const INK_PIX = rgb(28, 27, 25), ACCENT_PIX = rgb(138, 59, 59), RING_PIX = rgb(255, 255, 255);
93 const HP_BACK = rgb(60, 56, 52), HP_OK = rgb(86, 170, 90), HP_LOW = rgb(214, 70, 60);
94 const ELIXIR_ON = rgb(150, 70, 190), ELIXIR_OFF = rgb(206, 196, 214);
95 const RING_STEP = 1, FIRE_LIFE = .45;
96 // troop size in engine units: body radius, body height, head radius
97 const LOOK = { knight: [.5, 1.2, .34], archers: [.32, 1, .26], giant: [.9, 2.3, .5], goblins: [.28, .7, .24], brute: [.65, 1.5, .4] };
98 const HEAD = { knight: HELM, archers: SKIN, giant: SKIN, goblins: [110, 172, 80], brute: [120, 96, 84] };
99
100 const eng = (mx, my, z) => { const u = (mx - 8) * K, v = (16 - my) * K; return [(u + v) / R2, (v - u) / R2, z]; };
101 const scr = (mx, my, z = 0) => { const p = project(...eng(mx, my, z)); return [p.sx, p.sy]; };
102 function metres(px, py) { // the field point under a canvas pixel, on the ground
103 const g = unproject(px, py), u = (g.x - g.y) / R2, v = (g.x + g.y) / R2;
104 return [8 + u / K, 16 - v / K];
105 }
106
107 /* ---------- state ---------- */
108 const nodes = {};
109 for (const k of ['elixir', 'clock', 'down', 'status', 'card0', 'card1', 'card2', 'card3']) nodes[k] = document.getElementById(k);
110 const shown = {};
111 function setText(key, text) {
112 if (shown[key] === text) return;
113 shown[key] = text;
114 nodes[key].textContent = text;
115 }
116 const fresh = () => Duel.newMatch(Math.floor(Math.random() * 4294967296));
117 let P = fresh();
118 // sel: the card slot picked, -1 for none; ring: the keyboard's point on the field, shown once a key has moved it
119 const G = { time: 0, acc: 0, status: '', noteUntil: 0, sel: -1, ring: false, rx: 4, ry: 12, fx: [], prev: new Map(), end: '' };
120 const down = side => P.towers.filter(t => t.side === side && t.hp <= 0).length;
121 const health = side => P.towers.filter(t => t.side === side).reduce((n, t) => n + Math.max(0, Math.round(t.hp)), 0);
122 const plural = (n, word) => `${n} ${word}${n === 1 ? '' : 's'}`;
123
124 function renderHud() {
125 setText('elixir', (Math.floor(P.a.elixir * 10) / 10).toFixed(1));
126 setText('clock', String(Math.max(0, Math.ceil(Duel.DURATION - P.time - 1e-6))));
127 setText('down', `${down('b')} : ${down('a')}`);
128 P.a.hand.forEach((key, i) => {
129 const card = Duel.CARDS[key], afford = P.a.elixir >= card.cost;
130 setText(`card${i}`, `${i + 1} ${card.name} · ${card.cost}`);
131 const b = nodes[`card${i}`];
132 if (shown[`sel${i}`] !== (G.sel === i)) { shown[`sel${i}`] = G.sel === i; b.setAttribute('aria-pressed', String(G.sel === i)); }
133 if (shown[`dim${i}`] !== !afford) { shown[`dim${i}`] = !afford; b.className = afford ? 'card' : 'card dim'; }
134 });
135 }
136 function note(text) { setText('status', text); G.noteUntil = G.time + 1.8; }
137 const REFUSED = { elixir: 'not enough elixir yet', half: 'troops go on your half only', card: 'pick a card first', bounds: 'that is off the field', over: 'the match is over', side: 'not your side' };
138
139 // what the rules reported, as one line with a win, loss or draw
140 function endLine() {
141 const mine = down('a'), theirs = down('b');
142 let line;
143 if (P.winner === null) line = P.reason === 'draw' ? 'A draw: both king towers fell' : `A draw: ${plural(theirs, 'tower')} down each way, tower health level`;
144 else if (P.reason === 'king') line = P.winner === 'a' ? `You win: the rival king tower falls · ${theirs} down to ${mine}` : `You lose: your king tower falls · ${mine} down to ${theirs}`;
145 else if (P.reason === 'towers') line = P.winner === 'a' ? `You win on towers: ${theirs} down to ${mine}` : `You lose on towers: ${mine} down to ${theirs}`;
146 else line = P.winner === 'a' ? `You win on tower health: ${health('a')} left to ${health('b')}` : `You lose on tower health: ${health('a')} left to ${health('b')}`;
147 return `${line} · tap or press a key to play again`;
148 }
149
150 /* ---------- baked scene ---------- */
151 const banks = Duel.RIVER_HALF;
152 function groundColor(x, y, ix, iy) {
153 const u = (x - y) / R2, v = (x + y) / R2, mx = 8 + u / K, my = 16 - v / K;
154 if (mx < 0 || mx > Duel.WIDTH || my < 0 || my > Duel.LENGTH) return 0;
155 if (mx < .5 || mx > Duel.WIDTH - .5 || my < .5 || my > Duel.LENGTH - .5) return rgb(...FRAME);
156 const t = .96 + (hash(ix, iy) - .5) * .06;
157 const shade = c => rgb(c[0] * t, c[1] * t, c[2] * t);
158 const bridge = Duel.LANE_X.some(bx => Math.abs(mx - bx) <= Duel.BRIDGE_HALF);
159 if (Math.abs(my - Duel.RIVER_Y) < banks) {
160 if (bridge) return shade(Math.floor(mx * 2) & 1 ? PLANK : PLANK_ALT);
161 return shade((ix + iy) & 4 ? WATER : WATER_ALT);
162 }
163 if (Duel.LANE_X.some(bx => Math.abs(mx - bx) < 1.4)) return shade(PATH);
164 return shade(my < Duel.RIVER_Y ? GRASS_A : GRASS_B);
165 }
166 // the rails along each bridge, standing on the planks
167 function bakeBridges() {
168 for (const bx of Duel.LANE_X) for (const sx of [-1, 1]) {
169 capsule(eng(bx + sx * Duel.BRIDGE_HALF, Duel.RIVER_Y - banks, .7), eng(bx + sx * Duel.BRIDGE_HALF, Duel.RIVER_Y + banks, .7), .16, .16, () => RAIL, 'solid');
170 for (const y of [-banks, banks]) capsule(eng(bx + sx * Duel.BRIDGE_HALF, Duel.RIVER_Y + y, 0), eng(bx + sx * Duel.BRIDGE_HALF, Duel.RIVER_Y + y, .8), .2, .2, () => RAIL, 'solid');
171 }
172 }
173 let ownMask = null; // ground pixels on the player's half, tinted while a troop card waits
174 function bake() {
175 ground.fill(0); shadowMask.fill(0); staticShadow.fill(0); kinds.fill(0);
176 tufts.length = 0; leaves.length = 0;
177 zb.fill(-1e9);
178 pix.fill(rgb(255, 255, 255));
179 ownMask = new Uint8Array(W * H);
180 for (let iy = 0; iy < H; iy++) for (let ix = 0; ix < W; ix++) {
181 const g = unproject(ix + .5, iy + .5), i = iy * W + ix, c = groundColor(g.x, g.y, ix, iy);
182 if (!c) continue;
183 pix[i] = c; ground[i] = 1;
184 zb[i] = (g.x + g.y) / R2 * COS;
185 const [, my] = metres(ix + .5, iy + .5);
186 if (Duel.ownHalf('a', my)) ownMask[i] = 1;
187 }
188 groundZ.set(zb);
189 bakeBridges();
190 bakeOcclusion();
191 staticShadow.set(shadowMask);
192 applyShadows(groundZ);
193 bakedPix.set(pix);
194 bakedZ.set(zb);
195 }
196
197 /* ---------- drawing the match ---------- */
198 const flagStep = () => (STILL ? 0 : Math.floor(G.time * WIND_FPS));
199 function drawTower(t, step) {
200 const col = SIDE_COLOR[t.side], king = t.kind === 'king';
201 if (t.hp <= 0) { dynamicAdd(eng(t.x, t.y, 0), eng(t.x, t.y, .5), king ? 1.5 : 1.1, king ? 1.3 : .95, () => RUBBLE); return; }
202 const r = king ? 1.5 : 1.1, h = king ? 4.4 : 3.2;
203 dynamicAdd(eng(t.x, t.y, 0), eng(t.x, t.y, h), r, r * .9, () => STONE);
204 dynamicAdd(eng(t.x, t.y, h), eng(t.x, t.y, h + .7), r * 1.15, r * 1.15, () => STONE_DARK);
205 dynamicAdd(eng(t.x, t.y, h + .7), eng(t.x, t.y, h + 1.9), r * .95, .05, () => col);
206 // the pennant on the king tower stirs at 8 fps, and stands still under reduced motion
207 if (king) {
208 const sway = STILL ? 0 : ((step & 3) < 2 ? .25 : -.25);
209 dynamicAdd(eng(t.x, t.y, h + 1.9), eng(t.x, t.y, h + 3.2), .06, .06, () => RAIL);
210 dynamicAdd(eng(t.x, t.y, h + 3.1), eng(t.x + sway, t.y + .9, h + 2.9), .18, .05, () => col);
211 }
212 }
213 function drawTroop(t, x, y) {
214 const [br, bh, hr] = LOOK[t.card], col = SIDE_COLOR[t.side];
215 dynamicAdd(eng(x, y, 0), eng(x, y, bh), br, br * .8, () => col);
216 dynamicAdd(eng(x, y, bh), eng(x, y, bh + hr), hr, hr, () => HEAD[t.card]);
217 if (t.card === 'brute') dynamicAdd(eng(x, y, bh * .5), eng(x, y, bh * .55), br * 1.02, br * 1.02, () => STONE_DARK);
218 if (t.card === 'archers') dynamicAdd(eng(x - .1, y, bh * .8), eng(x - .1, y + .5, bh * .5), .07, .07, () => RAIL);
219 }
220 // a few bright dashes ride the river and shift four times a second; under reduced motion they stay put
221 function drawRipples() {
222 const step = STILL ? 0 : Math.floor(G.time * 4);
223 for (let i = 0; i < 10; i++) {
224 const mx = 1 + hash(i, step % 7) * 14, my = Duel.RIVER_Y - .6 + hash(step % 7, i) * 1.2;
225 if (Duel.LANE_X.some(bx => Math.abs(mx - bx) <= Duel.BRIDGE_HALF + .3)) continue;
226 const [sx, sy] = scr(mx, my);
227 for (let d = 0; d < 3; d++) { const x = Math.round(sx) + d, y = Math.round(sy); if (x >= 0 && x < W && y >= 0 && y < H) pix[y * W + x] = rgb(214, 238, 250); }
228 }
229 }
230 function circle(mx, my, r, color, halo) {
231 const pts = [], n = Math.max(16, Math.round(r * 26));
232 for (let i = 0; i < n; i++) { const a = i / n * Math.PI * 2, [sx, sy] = scr(mx + Math.cos(a) * r, my + Math.sin(a) * r); pts.push([Math.round(sx), Math.round(sy)]); }
233 if (halo) haloDots(pts);
234 drawDots(pts, color);
235 }
236 const bar = (sx, sy, w, frac, low) => {
237 const x0 = Math.round(sx) - (w >> 1), y0 = Math.round(sy), on = Math.round(w * Math.max(0, Math.min(1, frac)));
238 for (let x = 0; x < w; x++) { const px = x0 + x; if (px >= 0 && px < W && y0 >= 0 && y0 < H) pix[y0 * W + px] = x < on ? (low ? HP_LOW : HP_OK) : HP_BACK; }
239 };
240 function drawBars() {
241 for (const t of P.towers) {
242 if (t.hp <= 0) continue;
243 const [sx, sy] = scr(t.x, t.y, t.kind === 'king' ? 8.2 : 6.2);
244 for (const dy of [-1, 1]) bar(sx, sy + dy, 16, 0, false);
245 bar(sx, sy, 16, t.hp / t.max, t.hp < t.max * .35);
246 }
247 for (const t of P.troops) {
248 const p = G.prev.get(t.id), a = G.acc / Duel.TICK, x = p ? p[0] + (t.x - p[0]) * a : t.x, y = p ? p[1] + (t.y - p[1]) * a : t.y;
249 const [sx, sy] = scr(x, y, LOOK[t.card][1] + LOOK[t.card][2] * 2 + .5);
250 bar(sx, sy, 7, t.hp / Duel.CARDS[t.card].hp, t.hp < Duel.CARDS[t.card].hp * .35);
251 }
252 }
253 // the fireball: a burst whose ring grows over its life, drawn whether or not motion is reduced because it is play
254 function drawFx() {
255 for (const f of G.fx) {
256 const k = Math.min(1, f.age / FIRE_LIFE);
257 circle(f.x, f.y, f.r * (.3 + .7 * k), rgb(255, 150, 40), false);
258 if (k < .7) circle(f.x, f.y, f.r * .6 * (1 - k), rgb(255, 214, 10), false);
259 }
260 }
261 // where a card would land: the ring (the keyboard's point), and the half it may go on
262 function drawAim() {
263 const card = G.sel >= 0 ? Duel.CARDS[P.a.hand[G.sel]] : null;
264 if (card && !card.spell) for (let i = 0; i < W * H; i++) if (ownMask[i] && ((i % W + (i / W | 0)) & 1) === 0) tint(i, 1.1, 1.1, 1.05);
265 if (!G.ring || P.over) return;
266 circle(G.rx, G.ry, card && card.spell ? card.radius : .8, ACCENT_PIX, true);
267 }
268 function drawElixir() {
269 const e = P.a.elixir, x0 = 135;
270 for (let c = 0; c < Duel.MAX_ELIXIR; c++) {
271 const on = e >= c + 1, half = !on && e > c;
272 for (let dy = 0; dy < 4; dy++) for (let dx = 0; dx < 8; dx++) pix[(268 + dy) * W + x0 + c * 9 + dx] = on || (half && dx < 8 * (e - c)) ? ELIXIR_ON : ELIXIR_OFF;
273 }
274 }
275
276 function draw() {
277 pix.set(bakedPix);
278 zb.set(bakedZ);
279 pendingShadows.length = 0;
280 const step = flagStep(), a = G.acc / Duel.TICK;
281 for (const t of P.towers) drawTower(t, step);
282 for (const t of P.troops) {
283 const p = G.prev.get(t.id);
284 drawTroop(t, p ? p[0] + (t.x - p[0]) * a : t.x, p ? p[1] + (t.y - p[1]) * a : t.y);
285 }
286 flushShadows();
287 applyShadows(bakedZ);
288 shadeEdges();
289 drawRipples();
290 drawAim();
291 drawBars();
292 drawFx();
293 drawElixir();
294 ctx.putImageData(image, 0, 0);
295 }
296
297 /* ---------- game ---------- */
298 function act(events) {
299 for (const e of events) {
300 if (e.type === 'place') sound(e.side === 'a' ? 330 : 247, .1, 'triangle');
301 if (e.type === 'spell') { G.fx.push({ x: e.x, y: e.y, r: Duel.CARDS[e.card].radius, age: 0 }); sound(110, .4, 'sawtooth'); sound(70, .5, 'square', .05); }
302 if (e.type === 'tower') { sound(160, .5, 'sawtooth'); note(e.side === 'b' ? `rival ${e.kind} tower down` : `your ${e.kind} tower is down`); }
303 if (e.type === 'over') {
304 if (e.winner === 'a') { sound(520, .3, 'sine'); sound(780, .5, 'sine', .15); } else sound(110, .6, 'sawtooth');
305 G.end = endLine(); G.noteUntil = 0; G.sel = -1;
306 setText('status', G.end);
307 }
308 }
309 }
310 function playCard(x, y) {
311 ensureAudio();
312 if (G.sel < 0) { note('pick a card first: 1-4'); return; }
313 const r = Duel.play(P, 'a', G.sel, x, y);
314 if (r.error) { note(REFUSED[r.error] || 'cannot play that'); return; }
315 P = r.state; G.sel = -1;
316 act(r.events);
317 renderHud();
318 }
319 function pick(i) {
320 ensureAudio();
321 if (P.over) return;
322 G.sel = G.sel === i ? -1 : i;
323 const card = Duel.CARDS[P.a.hand[G.sel]];
324 if (card && !card.spell) G.ry = Math.min(G.ry, Duel.bankY('a'));
325 renderHud();
326 }
327 function restart() {
328 P = fresh(); G.sel = -1; G.ring = false; G.fx.length = 0; G.prev.clear(); G.acc = 0; G.end = '';
329 note('tap a card, then tap your half');
330 renderHud();
331 }
332 function update(dt) {
333 G.time += dt;
334 for (const f of G.fx) f.age += dt;
335 G.fx = G.fx.filter(f => f.age < FIRE_LIFE);
336 if (!P.over) {
337 G.acc += dt;
338 while (G.acc >= Duel.TICK - 1e-9 && !P.over) {
339 G.acc -= Duel.TICK;
340 G.prev = new Map(P.troops.map(t => [t.id, [t.x, t.y]]));
341 const m = Duel.rivalMove(P, 'b');
342 if (m) { const r = Duel.play(P, 'b', m.index, m.x, m.y); if (!r.error) { P = r.state; act(r.events); } }
343 if (P.over) break;
344 const s = Duel.step(P);
345 P = s.state;
346 act(s.events);
347 }
348 }
349 renderHud();
350 if (P.over || G.time < G.noteUntil) return;
351 const card = G.sel >= 0 ? Duel.CARDS[P.a.hand[G.sel]] : null;
352 setText('status', card ? `${card.name}: ${card.spell ? 'tap anywhere' : 'tap your half'}` : 'pick a card, 1-4');
353 }
354
355 /* ---------- input ---------- */
356 canvas.addEventListener('pointerdown', e => {
357 canvas.focus({ preventScroll: true });
358 G.ring = false;
359 if (P.over) { restart(); return; }
360 const r = canvas.getBoundingClientRect();
361 const [x, y] = metres((e.clientX - r.left) / r.width * W, (e.clientY - r.top) / r.height * H);
362 playCard(x, y);
363 });
364 for (let i = 0; i < Duel.HAND; i++) nodes[`card${i}`].addEventListener('click', () => { if (P.over) restart(); else pick(i); });
365 const MOVES = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, 1], ArrowDown: [0, -1] };
366 canvas.addEventListener('keydown', e => {
367 const move = MOVES[e.key], digit = '1234'.indexOf(e.key), play = e.key === ' ' || e.key === 'Enter';
368 if (!move && digit < 0 && !play) return;
369 e.preventDefault();
370 if (P.over) { if (!e.repeat) restart(); return; }
371 if (move) {
372 const card = G.sel >= 0 ? Duel.CARDS[P.a.hand[G.sel]] : null, top = card && card.spell ? Duel.LENGTH : Duel.bankY('a');
373 G.ring = true;
374 G.rx = Math.max(0, Math.min(Duel.WIDTH, G.rx + move[0] * RING_STEP));
375 G.ry = Math.max(0, Math.min(top, G.ry + move[1] * RING_STEP));
376 return;
377 }
378 if (e.repeat) return;
379 if (digit >= 0) { pick(digit); return; }
380 G.ring = true;
381 playCard(G.rx, G.ry);
382 });
383
384 /* ---------- sound ---------- */
385 let audio = null, muted = false;
386 function ensureAudio() {
387 if (audio) { if (audio.state === 'suspended') audio.resume(); return; }
388 const AC = window.AudioContext || window.webkitAudioContext;
389 if (AC) audio = new AC();
390 }
391 function sound(freq, life, type, delay = 0) {
392 if (!audio || muted) return;
393 const now = audio.currentTime + delay, gain = audio.createGain(), osc = audio.createOscillator();
394 osc.type = type;
395 osc.frequency.setValueAtTime(freq, now);
396 gain.gain.setValueAtTime(.0001, now);
397 gain.gain.exponentialRampToValueAtTime(.07, now + .01);
398 gain.gain.exponentialRampToValueAtTime(.0005, now + life);
399 osc.connect(gain).connect(audio.destination);
400 osc.start(now); osc.stop(now + life + .02);
401 }
402 const muteButton = document.getElementById('mute');
403 muteButton.addEventListener('click', () => {
404 muted = !muted;
405 muteButton.textContent = muted ? 'sound off' : 'sound on';
406 muteButton.setAttribute('aria-pressed', String(muted));
407 });
408
409 /* ---------- fit and boot ---------- */
410 addEventListener('resize', fit);
411 fit();
412 bake();
413 note('tap a card, then tap your half');
414 renderHud();
415 canvas.focus({ preventScroll: true });
416 let last = performance.now();
417 function frame(now) {
418 update(Math.min(.04, (now - last) / 1000));
419 last = now;
420 draw();
421 requestAnimationFrame(frame);
422 }
423 requestAnimationFrame(frame);
424 </script>
425 </body>
426 </html>

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs