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

Migrated from github.com/amirmushichge/pixel-plays

clash royale #112

Parked opened this in answer to
Closed without merging

mason/pixel-plays:mason/102-clash-royale → main 3 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
11 files changed +825 −3
README.md +2 −1
@@ -43,6 +43,7 @@ Concept by [abhi](https://x.com/awwbhi2). Game by [AmirMushich](https://x.com/Am
4343 | [Soapbox Derby](soapbox-derby/) | A 360 m cobbled hill in a wooden cart that rolls and gathers speed by itself: steer between the gaps in gates of hay bales that narrow down the hill (the cart answers late, so steer early); a bale slows it hard and costs one of three lives, a smooth flagstone strip gives a short boost, and the banner scores your time against your best (forged by the crew on the engine and shell above, not by the original creators) | Drag left or right; left/right arrows |
4444 | [Sheepdog](sheepdog/) | A 90-second dusk over three hillside fields, five sheep each, scattered at the top: drag the dog (or use the arrow keys) so they flee it inside a set radius, flock together and wander when calm, and push one too hard and it bolts the wrong way; each sheep that goes through the dry-stone wall's gate and then into the hurdle pen scores, one that goes round the gate scores nothing once penned; the gate moves every field, the sun lowers with the clock, and 10 or more of 15 wins (forged by the crew on the engine and shell above, not by the original creators) | Drag the dog; arrow keys |
4545 | [Firefly Jar](firefly-jar/) | A 90-second summer night in a back garden: tap a firefly while it glows to catch it into the jar (+1, golden +3), a dim one is scared off and breaks the streak, shoo the moths before they reach the lantern; the third moth ends the night (forged by the crew on the engine and shell above, not by the original creators) | Tap; Tab or arrows + space |
46 | [Tower Duel](tower-duel/) | A 90-second lane battle across a river with two bridges: pick a card from a hand of four and put it on your half (knight, archers, giant that only hunts towers, goblins, brute, or a fireball that lands anywhere), each costs elixir that refills over time and twice as fast for the last 30 seconds; troops cross at a bridge and fight, towers shoot back; the king tower falling wins at once, otherwise more towers down, then more tower health, when the clock ends; the concept is the generic two-lane card battle, with no particular game's art, names or cards copied (forged by the crew on the shell above, not by the original creators) | Tap a card, then tap your half; 1 to 4 or Tab pick, arrows move the ring, space plays |
4647
4748 ## Run
4849 Requires [Node.js](https://nodejs.org/); nothing to install.
@@ -62,7 +63,7 @@ On the forge, `forge.json` runs `bun serve.mjs` with health check `/`. State is
6263 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.
6364
6465 ## Add a game
65 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 and Firefly Jar 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`.
66 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 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`.
6667
6768 - `shell.js` provides the game menu, the Rules popup, the credits and the background music.
6869 - `engine.js` provides the camera, depth buffer, colour ramps, shadows, edges, figures, trees and wind as globals.
index.html +1
@@ -62,6 +62,7 @@ footer a::after { content: none; }
6262 <li data-kind="Throwing" data-input="Drag" style="--accent:#d9a441"><a href="balote/">Balote</a><span>Bocce against a bot, first to 5</span><span class="tags">Throwing · Drag</span></li>
6363 <li data-kind="Timing" data-input="Hold" style="--accent:#3f8fb5"><a href="stari-most/">Stari Most</a><span>Five dives off the old bridge, flip and enter the water vertically</span><span class="tags">Timing · Hold</span></li>
6464 <li data-kind="Catching" data-input="Drag" style="--accent:#c8604a"><a href="laundry/">Rooftop Laundry</a><span>Get the washing into the basket before the storm</span><span class="tags">Catching · Drag</span></li>
65 <li data-kind="Strategy" data-input="Tap" style="--accent:#3a6fc9"><a href="tower-duel/">Tower Duel</a><span>Send knights, archers and a giant across the bridges at the rival's towers, spend elixir wisely, topple the king tower first</span><span>Game forged by the crew</span><span class="tags">Strategy · Tap</span></li>
6566 <li data-kind="Sport" data-input="Tap" style="--accent:#c9683a"><a href="tie-break/">Tie-Break</a><span>Clay-court tie-break against a bot, the moment you hit decides where the ball lands</span><span class="tags">Sport · Tap</span></li>
6667 <li data-kind="Timing" data-input="Hold" style="--accent:#7a6bb0"><a href="mini-ramp/">Mini Ramp</a><span>60 seconds on a skateboard ramp, pump for height and grab in the air</span><span class="tags">Timing · Hold</span></li>
6768 <li data-kind="Timing" data-input="Hold" style="--accent:#5aa05a"><a href="kite-hill/">Kite Hill</a><span>Keep a kite in the air through 60 seconds of gusts: pull to climb, let out line when the grass bends</span><span>Game forged by the crew</span><span class="tags">Timing · Hold</span></li>
og/home.png
Binary file not shown.
og/tower-duel.png added
Binary file not shown.
rounds.mjs +11
@@ -111,6 +111,17 @@ export const ROUNDS = {
111111 g.step(1);
112112 };
113113 })() },
114 // send the dearest troop card you can pay for, down the top lane then the bottom one
115 'tower-duel': { over: /play again/, outcome: /you win \d+–\d+/, beat: (() => {
116 let lane = 0;
117 return g => {
118 const hand = g.read('R.a.hand'), elixir = g.read('R.a.elixir'), cards = g.read('Duel.CARDS');
119 let pick = -1;
120 hand.forEach((name, i) => { const c = cards[name]; if (!c.spell && c.cost <= elixir && (pick < 0 || c.cost > cards[hand[pick]].cost)) pick = i; });
121 if (pick >= 0) { g.tap(52 + pick * 86, 240); g.tap(50, 8 + (lane++ % 2 ? 13.5 : 4.5) * 10); }
122 g.run(.5);
123 };
124 })() },
114125 'window-washer': { over: /play again/, outcome: /[1-9]\d* of 500/, beat: g => g.drag([60, 100], [300, 100], .6) },
115126 };
116127
serve.test.mjs +8 −1
@@ -328,7 +328,7 @@ test('every game has a kind, input and accent, and the static list carries them'
328328 delete globalThis.PixelPlays;
329329 }
330330 for (const g of games) {
331 expect(['Sport', 'Throwing', 'Timing', 'Catching', 'Precision', 'Racing', 'Memory']).toContain(g.kind);
331 expect(['Sport', 'Throwing', 'Timing', 'Catching', 'Precision', 'Racing', 'Memory', 'Strategy']).toContain(g.kind);
332332 expect(['Tap', 'Hold', 'Drag']).toContain(g.input);
333333 expect(g.accent).toMatch(/^#[0-9a-f]{6}$/i);
334334 expect(html).toContain(`<li data-kind="${g.kind}" data-input="${g.input}" style="--accent:${g.accent}"><a href="${g.id}/">`);
@@ -416,6 +416,13 @@ test('Firefly Jar and its rules script are served without a track', async () =>
416416 expect((await fetch(base + '/firefly-jar/night.js')).status).toBe(200);
417417 });
418418
419 test('Tower Duel and its rules script are served without a track', async () => {
420 const page = await fetch(base + '/tower-duel/');
421 expect(page.status).toBe(200);
422 expect(page.headers.get('content-type')).toBe('text/html; charset=utf-8');
423 expect((await fetch(base + '/tower-duel/duel.js')).status).toBe(200);
424 });
425
419426 test('Soapbox Derby and its rules script are served without a track', async () => {
420427 const page = await fetch(base + '/soapbox-derby/');
421428 expect(page.status).toBe(200);
shell.js +2 −1
@@ -1,7 +1,7 @@
11 'use strict';
22 // Shared chrome for every game: game menu (top centre) and rules popup (top right).
33 window.PixelPlays = (() => {
4 // add a game here and give it a folder, a one-line `blurb`, a `kind` (Sport, Throwing, Timing, Catching, Precision, Racing, Memory), an `input` (Tap, Hold, Drag) and an `accent` colour for its card (the home page lists it from here) (`music: false` when it has no track, `forged: true` when it was made on the forge rather than by the original creators); `soon` entries show in the menu but do not link
4 // add a game here and give it a folder, a one-line `blurb`, a `kind` (Sport, Throwing, Timing, Catching, Precision, Racing, Memory, Strategy), an `input` (Tap, Hold, Drag) and an `accent` colour for its card (the home page lists it from here) (`music: false` when it has no track, `forged: true` when it was made on the forge rather than by the original creators); `soon` entries show in the menu but do not link
55 const GAMES = [
66 { id: 'balote', title: 'Balote', blurb: 'Bocce against a bot, first to 5', kind: 'Throwing', input: 'Drag', accent: '#d9a441' },
77 { id: 'stari-most', title: 'Stari Most', blurb: 'Five dives off the old bridge, flip and enter the water vertically', kind: 'Timing', input: 'Hold', accent: '#3f8fb5' },
@@ -37,6 +37,7 @@ window.PixelPlays = (() => {
3737 { id: 'soapbox-derby', title: 'Soapbox Derby', blurb: 'Steer a wooden cart down a cobbled hill between the hay bales, fastest time wins', kind: 'Racing', input: 'Drag', accent: '#b5562b', music: false, forged: true },
3838 { id: 'sheepdog', title: 'Sheepdog', blurb: 'Drag the dog to steer five sheep through the gate and into the pen before dusk', kind: 'Catching', input: 'Drag', accent: '#5b8a3a', music: false, forged: true },
3939 { id: 'firefly-jar', title: 'Firefly Jar', blurb: 'Tap the fireflies into a jar while they glow, a dim one flies off, shoo the moths before they reach the lantern', kind: 'Catching', input: 'Tap', accent: '#c9b43a', music: false, forged: true },
40 { id: 'tower-duel', title: 'Tower Duel', blurb: 'Send knights, archers and a giant across the bridges at the rival\'s towers, spend elixir wisely, topple the king tower first', kind: 'Strategy', input: 'Tap', accent: '#3a6fc9', music: false, forged: true },
4041 ];
4142 const MUSIC_VOLUME = .4;
4243 const CREDITS = [
tower-duel/duel.js added +241
@@ -0,0 +1,241 @@
1 'use strict';
2 // The tower duel rules: two sides face each other across a river, each with two side towers and a king tower.
3 // You spend elixir to put a card from your hand of four on your own half; troops walk their lane, cross at the
4 // bridge and fight whatever they meet, the towers shoot whatever comes in range. A fireball hits anywhere.
5 // The king tower falling ends the match at once; otherwise the clock does, and the side with more towers down
6 // (then more tower health) wins. Plain numbers in, plain numbers out, no DOM. The page draws and sounds what this decides.
7 (function (root) {
8 const MATCH = 90; // seconds in a match
9 const DOUBLE_AT = 30; // elixir comes twice as fast for the last 30 seconds
10 const MAX_ELIXIR = 10;
11 const START_ELIXIR = 5;
12 const ELIXIR_EVERY = 1.1; // seconds for one elixir
13 const ARENA = { w: 32, h: 18 };
14 const RIVER = 16, RIVER_HALF = .8; // the river runs down the middle; troops cross only on a bridge
15 const BRIDGES = [4.5, 13.5], BRIDGE_HALF = 1.4;
16 const OWN_EDGE = RIVER - RIVER_HALF - .2; // the furthest a troop can be put down
17 const AGGRO = 4.5; // a troop turns on an enemy troop this close
18 const TOWER_RANGE = 6.5, TOWER_SIZE = 1.3;
19 const RESTART_AFTER = .8;
20 const MAX_STEP = .05;
21 const SPELL = { radius: 2.5, troops: 45, towers: 20 };
22
23 // cost in elixir; troops have health, damage per hit, seconds between hits, reach, speed in tiles per second
24 const CARDS = {
25 knight: { title: 'Knight', cost: 3, count: 1, hp: 110, dmg: 14, rate: 1, range: 1.3, speed: 2.1 },
26 archers: { title: 'Archers', cost: 3, count: 2, hp: 35, dmg: 7, rate: .9, range: 5, speed: 2 },
27 giant: { title: 'Giant', cost: 5, count: 1, hp: 280, dmg: 18, rate: 1.4, range: 1.4, speed: 1.3, towersOnly: true },
28 goblins: { title: 'Goblins', cost: 2, count: 2, hp: 30, dmg: 8, rate: .7, range: 1.1, speed: 3.4 },
29 brute: { title: 'Brute', cost: 4, count: 1, hp: 190, dmg: 22, rate: 1.3, range: 1.4, speed: 1.7 },
30 fireball:{ title: 'Fireball', cost: 4, spell: true },
31 };
32 const DECK = Object.keys(CARDS);
33
34 const finite = v => (Number.isFinite(v) ? v : 0);
35 const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
36 // the generator is a 32-bit state kept on the game, so a match replays from its seed
37 function rand(s) {
38 s.rng = (s.rng + 0x6d2b79f5) >>> 0;
39 let t = s.rng;
40 t = Math.imul(t ^ t >>> 15, t | 1);
41 t ^= t + Math.imul(t ^ t >>> 7, t | 61);
42 return ((t ^ t >>> 14) >>> 0) / 4294967296;
43 }
44 const dist = (a, b) => Math.hypot(a.x - b.x, a.y - b.y);
45 const elixirRate = left => (left <= DOUBLE_AT ? 2 : 1) / ELIXIR_EVERY;
46 const nearestBridge = y => (Math.abs(y - BRIDGES[0]) <= Math.abs(y - BRIDGES[1]) ? BRIDGES[0] : BRIDGES[1]);
47 const bankSide = x => (x < RIVER - RIVER_HALF ? -1 : x > RIVER + RIVER_HALF ? 1 : 0);
48
49 function shuffled(s) {
50 const deck = DECK.slice();
51 for (let i = deck.length - 1; i > 0; i--) { const j = Math.floor(rand(s) * (i + 1)); [deck[i], deck[j]] = [deck[j], deck[i]]; }
52 return deck;
53 }
54 function newHand(s) {
55 const deck = shuffled(s);
56 return { elixir: START_ELIXIR, hand: deck.slice(0, 4), queue: deck.slice(4) };
57 }
58 function newTowers() {
59 const list = [];
60 let id = 1;
61 for (const side of ['a', 'b']) {
62 const sx = side === 'a' ? 5.5 : 26.5, kx = side === 'a' ? 1.8 : 30.2;
63 for (const y of BRIDGES) list.push({ id: id++, side, kind: 'side', x: sx, y, hp: 120, max: 120, cool: 0, down: false, flash: 0 });
64 list.push({ id: id++, side, kind: 'king', x: kx, y: ARENA.h / 2, hp: 200, max: 200, cool: 0, down: false, flash: 0 });
65 }
66 return list;
67 }
68
69 function newGame(wins = 0, seed = 1) {
70 const s = {
71 phase: 'play', verdict: '', t: 0, left: MATCH, rng: (finite(seed) >>> 0) || 1, nextId: 100,
72 a: null, b: null, towers: newTowers(), units: [], crowns: { a: 0, b: 0 }, selected: 0,
73 wins: Math.max(0, Math.floor(finite(wins))), record: false, aiWait: 4, timer: 0,
74 };
75 s.a = newHand(s); s.b = newHand(s);
76 return s;
77 }
78
79 const crowns = (s, side) => s.towers.filter(t => t.side !== side && t.down).length;
80 const towerHealth = (s, side) => s.towers.filter(t => t.side === side).reduce((n, t) => n + Math.max(0, t.hp), 0);
81
82 function end(s, verdict, events) {
83 s.phase = 'over'; s.verdict = verdict; s.timer = 0;
84 if (verdict === 'win') { s.wins++; s.record = true; }
85 events.push({ type: 'over', verdict, a: s.crowns.a, b: s.crowns.b });
86 }
87
88 function spawn(s, side, card, x, y) {
89 const c = CARDS[card];
90 for (let i = 0; i < c.count; i++) {
91 const off = c.count === 1 ? 0 : (i - (c.count - 1) / 2) * 1.1;
92 s.units.push({
93 id: s.nextId++, side, card, x: clamp(x, .5, ARENA.w - .5), y: clamp(y + off, .5, ARENA.h - .5), hp: c.hp, max: c.hp,
94 cool: 0, flash: 0,
95 });
96 }
97 }
98 function fireball(s, side, x, y, events) {
99 for (const u of s.units) if (u.side !== side && Math.hypot(u.x - x, u.y - y) <= SPELL.radius) { u.hp -= SPELL.troops; u.flash = .2; }
100 for (const t of s.towers) if (t.side !== side && !t.down && Math.hypot(t.x - x, t.y - y) <= SPELL.radius + TOWER_SIZE) { t.hp -= SPELL.towers; t.flash = .2; }
101 events.push({ type: 'fireball', side, x, y, radius: SPELL.radius });
102 }
103
104 // play the card in slot `slot` of `side`'s hand at a point; returns the events, a 'deny' when it cannot be played
105 function play(s, side, slot, x, y) {
106 const events = [];
107 if (s.phase !== 'play') return events;
108 const h = side === 'a' ? s.a : s.b;
109 slot = Math.floor(finite(slot)); x = finite(x); y = clamp(finite(y), .5, ARENA.h - .5);
110 if (slot < 0 || slot > 3) return events;
111 const card = h.hand[slot], c = CARDS[card];
112 if (h.elixir < c.cost) { events.push({ type: 'deny', why: 'elixir', side }); return events; }
113 if (!c.spell) {
114 const mine = side === 'a' ? x <= OWN_EDGE : x >= ARENA.w - OWN_EDGE;
115 if (!mine) { events.push({ type: 'deny', why: 'half', side }); return events; }
116 }
117 h.elixir -= c.cost;
118 h.hand[slot] = h.queue.shift();
119 h.queue.push(card);
120 if (c.spell) fireball(s, side, clamp(x, 0, ARENA.w), y, events);
121 else spawn(s, side, card, x, y);
122 events.push({ type: 'deploy', side, card, x, y });
123 return events;
124 }
125 const select = (s, slot) => { slot = Math.floor(finite(slot)); if (slot >= 0 && slot <= 3) s.selected = slot; };
126 const playSelected = (s, x, y) => play(s, 'a', s.selected, x, y);
127
128 // the rival: a card it can pay for, at a random lane on its own half; a fireball only where troops are bunched
129 function think(s, events) {
130 const h = s.b, pays = h.hand.map((card, slot) => ({ card, slot })).filter(o => CARDS[o.card].cost <= h.elixir);
131 if (!pays.length) { s.aiWait = .5; return; }
132 const pick = pays[Math.floor(rand(s) * pays.length)], c = CARDS[pick.card];
133 let x, y;
134 if (c.spell) {
135 const foes = s.units.filter(u => u.side === 'a');
136 const bunched = foes.map(u => ({ u, n: foes.filter(v => Math.hypot(v.x - u.x, v.y - u.y) <= SPELL.radius).length })).sort((p, q) => q.n - p.n)[0];
137 if (!bunched || bunched.n < 2) { s.aiWait = 1; return; }
138 x = bunched.u.x; y = bunched.u.y;
139 } else {
140 x = c.range > 3 ? 27 + rand(s) * 3 : 20 + rand(s) * 6;
141 y = BRIDGES[rand(s) < .5 ? 0 : 1] + (rand(s) - .5) * 2;
142 }
143 events.push(...play(s, 'b', pick.slot, x, y));
144 s.aiWait = 2 + rand(s) * 2.2;
145 }
146
147 function foesOf(s, u) { return s.units.filter(v => v.side !== u.side && v.hp > 0); }
148 // what a troop is after: the nearest enemy troop within reach of its eye (unless it only fights towers), else a tower
149 function aim(s, u) {
150 const c = CARDS[u.card];
151 if (!c.towersOnly) {
152 let best = null, bd = AGGRO;
153 for (const v of foesOf(s, u)) { const d = dist(u, v); if (d < bd) { bd = d; best = v; } }
154 if (best) return { kind: 'unit', x: best.x, y: best.y, ref: best, size: .5 };
155 }
156 const alive = s.towers.filter(t => t.side !== u.side && !t.down);
157 const sides = alive.filter(t => t.kind === 'side');
158 const pool = sides.length ? sides : alive;
159 let best = null, bd = Infinity;
160 for (const t of pool) { const d = dist(u, t) + Math.abs(t.y - nearestBridge(u.y)) * 2; if (d < bd) { bd = d; best = t; } }
161 return best && { kind: 'tower', x: best.x, y: best.y, ref: best, size: TOWER_SIZE };
162 }
163 function walk(u, target, step) {
164 const here = bankSide(u.x);
165 // across the river: slide along the bank to the bridge row, then cross
166 if (here !== 0 && here !== bankSide(target.x)) {
167 const off = nearestBridge(u.y) - u.y;
168 if (Math.abs(off) > .3) u.y += Math.sign(off) * Math.min(Math.abs(off), step);
169 else u.x += Math.sign(RIVER - u.x) * step;
170 return;
171 }
172 const dx = target.x - u.x, dy = target.y - u.y, d = Math.hypot(dx, dy) || 1;
173 u.x += dx / d * Math.min(step, d); u.y += dy / d * Math.min(step, d);
174 if (bankSide(u.x) === 0) u.y = clamp(u.y, nearestBridge(u.y) - BRIDGE_HALF, nearestBridge(u.y) + BRIDGE_HALF);
175 u.x = clamp(u.x, .5, ARENA.w - .5); u.y = clamp(u.y, .5, ARENA.h - .5);
176 }
177
178 function moveTroops(s, dt) {
179 for (const u of s.units) {
180 u.flash = Math.max(0, u.flash - dt);
181 const c = CARDS[u.card], target = aim(s, u);
182 u.cool -= dt;
183 if (!target) continue;
184 const reach = c.range + target.size + (target.kind === 'unit' ? .3 : 0);
185 if (dist(u, target) <= reach) {
186 if (u.cool <= 0) {
187 u.cool = c.rate;
188 target.ref.hp -= c.dmg; target.ref.flash = .2;
189 }
190 } else walk(u, target, c.speed * dt);
191 }
192 }
193 function shootTowers(s, dt, events) {
194 for (const t of s.towers) {
195 t.flash = Math.max(0, t.flash - dt);
196 if (t.down) continue;
197 t.cool -= dt;
198 let best = null, bd = TOWER_RANGE;
199 for (const u of s.units) { const d = dist(t, u); if (u.side !== t.side && u.hp > 0 && d < bd) { bd = d; best = u; } }
200 if (best && t.cool <= 0) { t.cool = t.kind === 'king' ? 1 : .9; best.hp -= t.kind === 'king' ? 8 : 6; best.flash = .2; }
201 }
202 for (const t of s.towers) {
203 if (t.down || t.hp > 0) continue;
204 t.down = true; t.hp = 0;
205 const other = t.side === 'a' ? 'b' : 'a';
206 s.crowns[other] = crowns(s, other);
207 events.push({ type: 'tower', side: t.side, kind: t.kind, x: t.x, y: t.y });
208 }
209 }
210
211 function advance(s, dt) {
212 const events = [];
213 dt = clamp(finite(dt), 0, MAX_STEP);
214 if (s.phase !== 'play') { s.timer += dt; return events; }
215 s.t += dt; s.left = Math.max(0, MATCH - s.t);
216 for (const h of [s.a, s.b]) h.elixir = Math.min(MAX_ELIXIR, h.elixir + elixirRate(s.left) * dt);
217 s.aiWait -= dt;
218 if (s.aiWait <= 0) think(s, events);
219 moveTroops(s, dt);
220 shootTowers(s, dt, events);
221 for (const u of s.units) if (u.hp <= 0) events.push({ type: 'fall', side: u.side, card: u.card, x: u.x, y: u.y });
222 s.units = s.units.filter(u => u.hp > 0);
223 const king = side => s.towers.find(t => t.side === side && t.kind === 'king');
224 if (king('b').down) end(s, 'win', events);
225 else if (king('a').down) end(s, 'loss', events);
226 else if (s.left <= 0) {
227 const diff = s.crowns.a - s.crowns.b, hp = towerHealth(s, 'a') - towerHealth(s, 'b');
228 end(s, diff > 0 || (diff === 0 && hp > 0) ? 'win' : diff < 0 || hp < 0 ? 'loss' : 'draw', events);
229 }
230 return events;
231 }
232
233 // a tap after the match has been over for a moment starts the next one; otherwise null
234 function again(s) { return s.phase === 'over' && s.timer > RESTART_AFTER ? newGame(s.wins, s.rng + 1) : null; }
235
236 const api = {
237 MATCH, DOUBLE_AT, MAX_ELIXIR, START_ELIXIR, ELIXIR_EVERY, ARENA, RIVER, RIVER_HALF, BRIDGES, BRIDGE_HALF, OWN_EDGE, TOWER_SIZE,
238 TOWER_RANGE, RESTART_AFTER, SPELL, CARDS, DECK, elixirRate, nearestBridge, towerHealth, newGame, select, play, playSelected, advance, again,
239 };
240 if (typeof module !== 'undefined') module.exports = api; else root.Duel = api;
241 })(typeof window !== 'undefined' ? window : globalThis);
tower-duel/duel.test.mjs added +167
@@ -0,0 +1,167 @@
1 import { test, expect } from 'bun:test';
2 import { MATCH, START_ELIXIR, MAX_ELIXIR, OWN_EDGE, BRIDGES, RIVER, CARDS, DECK, SPELL, elixirRate, newGame, select, play, playSelected, advance, again } from './duel.js';
3
4 const run = (s, seconds, dt = .02) => { const ev = []; for (let t = 0; t < seconds - 1e-9; t += dt) ev.push(...advance(s, dt)); return ev; };
5 // a quiet match: the rival does not play, the hand of 'a' is known
6 function quiet(hand = ['knight', 'archers', 'giant', 'fireball']) {
7 const s = newGame(0, 5);
8 s.aiWait = 1e9; s.a.hand = hand.slice(); s.a.queue = DECK.filter(c => !hand.includes(c));
9 return s;
10 }
11 const tower = (s, side, kind, y) => s.towers.find(t => t.side === side && t.kind === kind && (y === undefined || t.y === y));
12
13 test('elixir refills over time, twice as fast at the end, and never above ten', () => {
14 const s = quiet(); s.a.elixir = 0;
15 run(s, 1.1);
16 expect(s.a.elixir).toBeCloseTo(1, 1);
17 expect(elixirRate(20)).toBeCloseTo(elixirRate(60) * 2);
18 run(s, 60);
19 expect(s.a.elixir).toBe(MAX_ELIXIR);
20 });
21
22 test('a card costs its elixir, goes to the back of the queue and the next one takes its slot', () => {
23 const s = quiet(), queued = s.a.queue[0];
24 const ev = play(s, 'a', 0, 6, 4.5);
25 expect(ev.at(-1)).toMatchObject({ type: 'deploy', card: 'knight' });
26 expect(s.a.elixir).toBeCloseTo(START_ELIXIR - CARDS.knight.cost);
27 expect(s.a.hand[0]).toBe(queued);
28 expect(s.a.queue.at(-1)).toBe('knight');
29 expect(s.units.length).toBe(1);
30 });
31
32 test('a card you cannot pay for is refused and nothing changes', () => {
33 const s = quiet(); s.a.elixir = 2;
34 expect(play(s, 'a', 2, 6, 4.5)).toEqual([{ type: 'deny', why: 'elixir', side: 'a' }]);
35 expect(s.units.length).toBe(0);
36 expect(s.a.elixir).toBe(2);
37 });
38
39 test('troops go on your own half only, but a fireball goes anywhere', () => {
40 const s = quiet(); s.a.elixir = 10;
41 expect(play(s, 'a', 0, OWN_EDGE + 1, 4.5)[0]).toMatchObject({ type: 'deny', why: 'half' });
42 expect(play(s, 'a', 0, OWN_EDGE, 4.5).at(-1).type).toBe('deploy');
43 expect(play(s, 'a', 3, 26, 4.5).at(-1).type).toBe('deploy');
44 });
45
46 test('bad input is ignored: no slot, no number', () => {
47 const s = quiet();
48 expect(play(s, 'a', 9, 5, 5)).toEqual([]);
49 expect(play(s, 'a', -1, 5, 5)).toEqual([]);
50 play(s, 'a', 0, NaN, NaN);
51 expect(s.units.every(u => Number.isFinite(u.x) && Number.isFinite(u.y))).toBe(true);
52 select(s, 7); expect(s.selected).toBe(0);
53 select(s, 2); expect(s.selected).toBe(2); s.a.elixir = 10;
54 expect(playSelected(s, 5, 5).at(-1)).toMatchObject({ card: 'giant' });
55 });
56
57 test('a troop crosses at the bridge, not through the river', () => {
58 const s = quiet(); s.a.elixir = 10;
59 play(s, 'a', 0, 10, 9);
60 const u = s.units[0];
61 for (let i = 0; i < 400; i++) {
62 advance(s, .02);
63 if (Math.abs(u.x - RIVER) < .7) expect(BRIDGES.some(b => Math.abs(u.y - b) <= 1.45)).toBe(true);
64 }
65 expect(u.x).toBeGreaterThan(RIVER + 1);
66 });
67
68 test('the giant walks past troops to the towers; a knight stops to fight what it meets', () => {
69 const s = quiet(); s.a.elixir = 10;
70 play(s, 'a', 2, 12, 4.5);
71 s.units.push({ id: 900, side: 'b', card: 'goblins', x: 14, y: 4.5, hp: 1000, max: 1000, cool: 0, flash: 0 });
72 run(s, 2);
73 expect(s.units.find(u => u.card === 'giant').x).toBeGreaterThan(14);
74 const t = quiet(); t.a.elixir = 10;
75 play(t, 'a', 0, 12, 4.5);
76 t.units.push({ id: 900, side: 'b', card: 'goblins', x: 14, y: 4.5, hp: 1000, max: 1000, cool: 0, flash: 0 });
77 run(t, 2);
78 expect(t.units.find(u => u.card === 'knight').x).toBeLessThan(15.5);
79 expect(t.units.find(u => u.id === 900).hp).toBeLessThan(1000);
80 });
81
82 test('a fireball hurts troops and towers in its ring and no one outside', () => {
83 const s = quiet(); s.a.elixir = 10;
84 s.units.push({ id: 901, side: 'b', card: 'knight', x: 24, y: 9, hp: 110, max: 110, cool: 0, flash: 0 });
85 s.units.push({ id: 902, side: 'b', card: 'knight', x: 24 + SPELL.radius + 1, y: 9, hp: 110, max: 110, cool: 0, flash: 0 });
86 const side = tower(s, 'b', 'side', 4.5);
87 play(s, 'a', 3, 24, 9);
88 expect(s.units.find(u => u.id === 901).hp).toBe(110 - SPELL.troops);
89 expect(s.units.find(u => u.id === 902).hp).toBe(110);
90 expect(side.hp).toBe(120);
91 play(s, 'a', 0, 5, 9); s.a.hand[0] = 'fireball'; s.a.elixir = 10;
92 play(s, 'a', 0, side.x, side.y);
93 expect(side.hp).toBe(120 - SPELL.towers);
94 });
95
96 test('a tower shoots the troop that comes into its range', () => {
97 const s = quiet();
98 s.units.push({ id: 901, side: 'b', card: 'knight', x: 9, y: 4.5, hp: 110, max: 110, cool: 0, flash: 0 });
99 run(s, 1);
100 expect(s.units[0].hp).toBeLessThan(110);
101 });
102
103 test('a side tower that falls is a crown, the king tower falling ends the match', () => {
104 const s = quiet();
105 const side = tower(s, 'b', 'side', 4.5);
106 side.hp = 0;
107 const ev = run(s, .1);
108 expect(ev.find(e => e.type === 'tower')).toMatchObject({ side: 'b', kind: 'side' });
109 expect(s.crowns).toEqual({ a: 1, b: 0 });
110 expect(s.phase).toBe('play');
111 tower(s, 'b', 'king').hp = 0;
112 const over = run(s, .1).filter(e => e.type === 'over');
113 expect(over).toEqual([expect.objectContaining({ verdict: 'win', a: 2, b: 0 })]);
114 expect(s.wins).toBe(1);
115 expect(play(s, 'a', 0, 5, 5)).toEqual([]);
116 });
117
118 test('at the clock more towers down wins, then more tower health, then a draw', () => {
119 const a = quiet(); tower(a, 'b', 'side', 4.5).hp = 0; a.t = MATCH - .01;
120 run(a, .1); expect(a.verdict).toBe('win');
121 const b = quiet(); tower(b, 'a', 'side', 4.5).hp = 0; b.t = MATCH - .01;
122 run(b, .1); expect(b.verdict).toBe('loss');
123 const c = quiet(); tower(c, 'b', 'side', 13.5).hp = 60; c.t = MATCH - .01;
124 run(c, .1); expect(c.verdict).toBe('win');
125 const d = quiet(); d.t = MATCH - .01;
126 run(d, .1); expect(d.verdict).toBe('draw');
127 });
128
129 test('left alone, you lose; sending troops steadily beats the rival most of the time', () => {
130 let wins = 0, idleWins = 0;
131 for (let seed = 1; seed <= 12; seed++) {
132 const idle = newGame(0, seed), bot = newGame(0, seed);
133 for (let i = 0; i < 2300 && idle.phase === 'play'; i++) advance(idle, .04);
134 for (let i = 0; i < 2300 && bot.phase === 'play'; i++) {
135 if (i % 25 === 0) {
136 const h = bot.a; let best = -1;
137 h.hand.forEach((c, k) => { const cc = CARDS[c]; if (!cc.spell && cc.cost <= h.elixir && (best < 0 || cc.cost > CARDS[h.hand[best]].cost)) best = k; });
138 if (best >= 0) play(bot, 'a', best, 6, (i / 25 | 0) % 2 ? 13.5 : 4.5);
139 }
140 advance(bot, .04);
141 }
142 if (idle.verdict === 'win') idleWins++;
143 if (bot.verdict === 'win') wins++;
144 }
145 expect(idleWins).toBe(0);
146 expect(wins).toBeGreaterThanOrEqual(7);
147 });
148
149 test('a record of wins is kept and a tap after the pause starts a fresh match', () => {
150 const s = quiet(); s.wins = 2;
151 tower(s, 'b', 'king').hp = 0;
152 run(s, .1);
153 expect(s.record).toBe(true);
154 expect(again(s)).toBeNull();
155 run(s, 1);
156 const next = again(s);
157 expect(next.phase).toBe('play');
158 expect(next.wins).toBe(3);
159 expect(next.crowns).toEqual({ a: 0, b: 0 });
160 });
161
162 test('the same seed plays the same match', () => {
163 const a = newGame(0, 4), b = newGame(0, 4);
164 run(a, 30); run(b, 30);
165 expect(a.units.map(u => [u.x, u.y, u.hp])).toEqual(b.units.map(u => [u.x, u.y, u.hp]));
166 expect(a.units.length).toBeGreaterThan(0);
167 });
tower-duel/index.html added +352
@@ -0,0 +1,352 @@
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="Send knights, archers and a giant across the bridges at the rival's towers, spend elixir wisely, topple the king tower first">
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="Send knights, archers and a giant across the bridges at the rival's towers, spend elixir wisely, topple the king tower first">
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: #3a6fc9; }
24 * { box-sizing: border-box; }
25 html, body { height: 100%; margin: 0; background: var(--paper); color: var(--ink); }
26 html, body { -webkit-user-select: none; user-select: none; -webkit-touch-callout: none; -webkit-tap-highlight-color: transparent; }
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)); align-items: flex-end; }
33 .row { display: flex; align-items: center; gap: 8px; color: var(--accent); }
34 .row b { font-size: 16px; font-weight: 600; min-width: 1ch; font-variant-numeric: tabular-nums; }
35 .row span { color: var(--muted); }
36 #status { color: var(--muted); min-height: 1.35em; }
37 button { pointer-events: auto; font: inherit; color: var(--muted); background: none; border: 0; padding: 10px; margin: -10px; cursor: pointer; }
38 button:hover, button:focus-visible { color: var(--ink); }
39 </style>
40 </head>
41 <body>
42 <div id="stage"><canvas id="c" tabindex="0" aria-label="A small arena seen from above: a river with two bridges down the middle, your blue towers on the left and the rival's red towers on the right. Along the bottom are four cards. Tap a card, or press 1 to 4, then tap your half of the arena, or move the ring with the arrows and press space, to send troops at the rival's towers. A fireball can land anywhere. Destroy the king tower, or more towers than the rival, before the clock runs out." width="360" height="280"></canvas></div>
43 <div id="scores">
44 <div class="row"><b id="left">90</b><span>seconds left</span></div>
45 <div class="row"><b id="elixir">5</b><span>elixir</span></div>
46 <div class="row"><b id="crowns">0–0</b><span>towers down</span></div>
47 <div class="row"><b id="best">0</b><span>wins</span></div>
48 </div>
49 <div class="hud" id="bottom">
50 <div id="status" role="status" aria-live="polite"></div>
51 <button id="mute" type="button" aria-pressed="false">sound on</button>
52 </div>
53 <script src="../shell.js"></script>
54 <script>
55 PixelPlays.mount({
56 id: 'tower-duel',
57 rules: [
58 'Pick a card, then tap your half to send it: each costs elixir, which refills over time.',
59 'Troops cross at a bridge and fight; the Giant only goes for towers.',
60 'A fireball can land anywhere and hurts every troop in its ring.',
61 'Topple the king tower, or more towers than the rival, in 90 seconds.',
62 'Keys: 1 to 4 or Tab pick a card, arrows move the ring, space plays.',
63 ],
64 });
65 </script>
66 <script>window.PP_SCENE = { originY: 0 };</script>
67 <script src="duel.js"></script>
68 <script>
69 'use strict';
70
71 const W = 360, H = 280, T = 10, AX = 20, AY = 8; // arena origin and pixels per tile
72 const canvas = document.getElementById('c');
73 const ctx = canvas.getContext('2d');
74 const image = ctx.createImageData(W, H);
75 const pix = new Uint32Array(image.data.buffer);
76 const STILL = matchMedia('(prefers-reduced-motion: reduce)').matches;
77 const rgb = (r, g, b) => (255 << 24 | Math.min(255, b | 0) << 16 | Math.min(255, g | 0) << 8 | Math.min(255, r | 0)) >>> 0;
78 const { CARDS, ARENA, RIVER, RIVER_HALF, BRIDGES, BRIDGE_HALF, OWN_EDGE, TOWER_SIZE, SPELL } = Duel;
79
80 // two grass tones in checks, each with a few speckled shades baked once
81 const GRASS = [0, 1].map(k => Array.from({ length: 16 }, (_, n) => rgb(92 + k * 8 + n * 2, 136 + k * 8 + n * 2.5, 62 + k * 4 + n)));
82 const grain = (x, y) => { const h = Math.imul(x * 73856093 ^ y * 19349663, 2654435761) >>> 28; return h; };
83 const WATERS = [0, 1, 2, 3].map(n => rgb(80 + n * 4, 144 + n * 4, 208 + n * 2));
84 const WATER_HI = rgb(140, 196, 240);
85 const WOOD = rgb(150, 112, 70), WOOD_DARK = rgb(112, 80, 48), PAPER = rgb(255, 255, 255), INK = rgb(28, 27, 25), SIGNAL = rgb(255, 214, 10);
86 const SIDE = { a: { body: rgb(58, 111, 201), dark: rgb(30, 60, 120), light: rgb(140, 176, 240) }, b: { body: rgb(205, 66, 56), dark: rgb(122, 34, 30), light: rgb(240, 150, 140) } };
87 const CARD_COLOR = { knight: rgb(150, 160, 176), archers: rgb(90, 160, 96), giant: rgb(150, 110, 80), goblins: rgb(110, 170, 60), brute: rgb(176, 96, 72), fireball: rgb(240, 130, 30) };
88 const FRAME = rgb(60, 56, 70), TABLE = rgb(236, 232, 222), ELIXIR = rgb(190, 60, 200), ELIXIR_OFF = rgb(210, 190, 214);
89 const CARD_BOX = i => ({ x: 12 + i * 86, y: 212, w: 80, h: 62 });
90 const BAR = { x: 12, y: 196, w: 336, h: 9 };
91
92 /* ---------- drawing ---------- */
93 function px(x, y, c) { x |= 0; y |= 0; if (x >= 0 && y >= 0 && x < W && y < H) pix[y * W + x] = c; }
94 function rect(x, y, w, h, c) { for (let j = Math.round(y); j < Math.round(y + h); j++) for (let i = Math.round(x); i < Math.round(x + w); i++) px(i, j, c); }
95 function disc(cx, cy, r, c) { for (let j = -r; j <= r; j++) for (let i = -r; i <= r; i++) if (i * i + j * j <= r * r + r * .6) px(cx + i, cy + j, c); }
96 function ring(cx, cy, r, c, every = 1) { for (let a = 0, n = Math.max(12, Math.round(r * 6)); a < n; a += every) px(cx + Math.cos(a / n * 6.283) * r, cy + Math.sin(a / n * 6.283) * r, c); }
97 const sx = x => AX + x * T, sy = y => AY + y * T;
98 const DIGITS = ['111101101101111', '010110010010111', '111001111100111', '111001111001111', '101101111001001', '111100111001111', '111100111101111', '111001001001001', '111101111101111', '111101111001111'];
99 function digit(n, x, y, c) { const g = DIGITS[n]; for (let k = 0; k < 15; k++) if (g[k] === '1') { px(x + (k % 3) * 2, y + (k / 3 | 0) * 2, c); px(x + (k % 3) * 2 + 1, y + (k / 3 | 0) * 2, c); px(x + (k % 3) * 2, y + (k / 3 | 0) * 2 + 1, c); px(x + (k % 3) * 2 + 1, y + (k / 3 | 0) * 2 + 1, c); } }
100
101 function drawArena() {
102 rect(0, 0, W, H, PAPER);
103 for (let y = 0; y < ARENA.h * T; y++) for (let x = 0; x < ARENA.w * T; x++) px(AX + x, AY + y, GRASS[((x / T | 0) + (y / T | 0)) & 1][grain(x, y)]);
104 const rx = sx(RIVER - RIVER_HALF), rw = RIVER_HALF * 2 * T;
105 for (let y = 0; y < ARENA.h * T; y++) rect(rx, AY + y, rw, 1, WATERS[(y >> 3) % 4]);
106 for (let y = 0; y < ARENA.h * T; y += 6) { const o = STILL ? 0 : Math.floor(G.time * 4 + y) % 3; px(rx + 2 + o * 4, AY + y, WATER_HI); px(rx + 4 + o * 4, AY + y + 3, WATER_HI); }
107 for (const b of BRIDGES) {
108 rect(rx - 2, sy(b - BRIDGE_HALF), rw + 4, BRIDGE_HALF * 2 * T, WOOD);
109 for (let i = 0; i < rw + 4; i += 4) rect(rx - 2 + i, sy(b - BRIDGE_HALF), 1, BRIDGE_HALF * 2 * T, WOOD_DARK);
110 }
111 rect(AX - 1, AY - 1, ARENA.w * T + 2, 1, FRAME); rect(AX - 1, AY + ARENA.h * T, ARENA.w * T + 2, 1, FRAME);
112 rect(AX - 1, AY - 1, 1, ARENA.h * T + 2, FRAME); rect(AX + ARENA.w * T, AY - 1, 1, ARENA.h * T + 2, FRAME);
113 }
114 function bar(x, y, w, frac, c) { rect(x, y, w, 2, INK); rect(x, y, Math.max(0, Math.round(w * frac)), 2, c); }
115 function drawTower(t) {
116 const half = (t.kind === 'king' ? 1.5 : 1.15) * T, cx = sx(t.x), cy = sy(t.y), pal = SIDE[t.side];
117 if (t.down) { rect(cx - half, cy - half * .6, half * 2, half * 1.2, rgb(90, 84, 80)); rect(cx - half * .6, cy - half * .3, half * 1.2, half * .6, rgb(60, 56, 54)); return; }
118 rect(cx - half - 1, cy - half - 1, half * 2 + 2, half * 2 + 2, INK);
119 rect(cx - half, cy - half, half * 2, half * 2, t.flash > 0 ? PAPER : pal.body);
120 rect(cx - half, cy - half, half * 2, 3, pal.light);
121 rect(cx - half + 2, cy - half + 5, half * 2 - 4, half * 2 - 7, t.flash > 0 ? pal.light : pal.dark);
122 for (let i = 0; i < 3; i++) rect(cx - half + 1 + i * (half - 1), cy - half - 3, half * .5, 3, pal.body);
123 if (t.kind === 'king') { rect(cx - 2, cy - 4, 4, 4, SIGNAL); rect(cx - 3, cy - 6, 6, 2, SIGNAL); }
124 bar(cx - half, cy + half + 2, half * 2, t.hp / t.max, pal.light);
125 }
126 function drawTroop(u) {
127 const pal = SIDE[u.side], r = { knight: 4, archers: 3, giant: 6, goblins: 3, brute: 5 }[u.card], cx = Math.round(sx(u.x)), cy = Math.round(sy(u.y));
128 const bob = STILL ? 0 : Math.floor(G.time * 6 + u.id) % 2;
129 disc(cx, cy + 1, r + 1, INK);
130 disc(cx, cy - bob, r, u.flash > 0 ? PAPER : pal.body);
131 disc(cx, cy - bob - 1, Math.max(1, r - 2), CARD_COLOR[u.card]);
132 if (u.card === 'archers') px(cx + (u.side === 'a' ? r + 1 : -r - 1), cy, INK);
133 if (u.card === 'giant') rect(cx - 2, cy - r - 3, 4, 2, CARD_COLOR.giant);
134 if (u.hp < u.max) bar(cx - r, cy - r - 4, r * 2, u.hp / u.max, pal.light);
135 }
136 function drawFx() {
137 for (const f of G.fx) {
138 const k = f.age / .5;
139 ring(sx(f.x), sy(f.y), SPELL.radius * T * Math.min(1, k * 1.6), rgb(255, 170, 40));
140 ring(sx(f.x), sy(f.y), SPELL.radius * T * Math.min(1, k * 1.6) * .6, rgb(255, 230, 120));
141 }
142 for (const f of G.pops) { const k = f.age / .4; ring(sx(f.x), sy(f.y), 3 + k * 8, SIDE[f.side].light, 2); }
143 }
144 function drawElixir() {
145 rect(BAR.x - 1, BAR.y - 1, BAR.w + 2, BAR.h + 2, FRAME);
146 const e = R.a.elixir;
147 for (let i = 0; i < 10; i++) {
148 const x = BAR.x + i * 33.6, fill = Math.max(0, Math.min(1, e - i));
149 rect(x, BAR.y, 32.6, BAR.h, ELIXIR_OFF);
150 rect(x, BAR.y, 32.6 * fill, BAR.h, ELIXIR);
151 }
152 }
153 function cardIcon(name, cx, cy, side) {
154 const c = CARDS[name];
155 if (c.spell) { disc(cx, cy, 9, rgb(240, 130, 30)); disc(cx - 1, cy - 1, 5, rgb(255, 214, 80)); disc(cx - 2, cy - 2, 2, PAPER); return; }
156 const n = c.count, r = { knight: 7, archers: 5, giant: 10, goblins: 5, brute: 8 }[name];
157 for (let i = 0; i < n; i++) { const ox = n === 1 ? 0 : (i - (n - 1) / 2) * 12; disc(cx + ox, cy + 1, r + 1, INK); disc(cx + ox, cy, r, SIDE[side].body); disc(cx + ox, cy - 1, Math.max(2, r - 3), CARD_COLOR[name]); }
158 }
159 function drawCards() {
160 for (let i = 0; i < 4; i++) {
161 const b = CARD_BOX(i), name = R.a.hand[i], c = CARDS[name], on = i === R.selected, can = R.a.elixir >= c.cost;
162 rect(b.x - (on ? 2 : 0), b.y - (on ? 4 : 0), b.w + (on ? 4 : 0), b.h + (on ? 4 : 0), on ? SIGNAL : FRAME);
163 rect(b.x + 2, b.y + 2 - (on ? 4 : 0), b.w - 4, b.h - 4 + (on ? 4 : 0), TABLE);
164 cardIcon(name, b.x + b.w / 2, b.y + 30 - (on ? 2 : 0), 'a');
165 disc(b.x + 11, b.y + 11 - (on ? 3 : 0), 8, ELIXIR); digit(c.cost, b.x + 8, b.y + 6 - (on ? 3 : 0), PAPER);
166 if (!can) for (let j = b.y + 2; j < b.y + b.h - 2; j++) for (let k = b.x + 2; k < b.x + b.w - 2; k++) if ((j + k) & 1) px(k, j, rgb(190, 186, 176));
167 }
168 }
169 function drawGuide() {
170 const c = CARDS[R.a.hand[R.selected]];
171 if (R.phase !== 'play' || c.spell) return;
172 // the half you cannot play on is dimmed
173 for (let y = AY; y < AY + ARENA.h * T; y++) for (let x = sx(OWN_EDGE); x < AX + ARENA.w * T; x++) if (((x + y) & 1) === 0) px(x, y, rgb(70, 90, 60));
174 }
175 function drawCursor() {
176 if (!G.cursor || R.phase !== 'play') return;
177 const x = sx(G.cursor.x), y = sy(G.cursor.y);
178 ring(x, y, 7, INK); ring(x, y, 7, SIGNAL, 2);
179 if (CARDS[R.a.hand[R.selected]].spell) ring(x, y, SPELL.radius * T, SIGNAL, 3);
180 }
181 function draw() {
182 drawArena();
183 drawGuide();
184 for (const t of R.towers) drawTower(t);
185 for (const u of R.units.slice().sort((p, q) => p.y - q.y)) drawTroop(u);
186 drawFx();
187 drawCursor();
188 drawElixir();
189 drawCards();
190 ctx.putImageData(image, 0, 0);
191 }
192
193 /* ---------- game state ---------- */
194 const BEST_KEY = 'pixel-plays-tower-duel-wins';
195 const wins0 = (() => { try { return Number(localStorage.getItem(BEST_KEY)) || 0; } catch (e) { return 0; } })();
196 let R = Duel.newGame(wins0, Date.now() & 0xffff);
197 const G = { time: 0, noteUntil: 0, fx: [], pops: [], cursor: null };
198 const nodes = {};
199 for (const id of ['left', 'elixir', 'crowns', 'best', 'status']) nodes[id] = document.getElementById(id);
200 const hudText = {};
201 function setText(key, text) { if (hudText[key] !== text) { hudText[key] = text; nodes[key].textContent = text; } }
202 function renderHud() {
203 setText('left', String(Math.ceil(R.left)));
204 setText('elixir', String(Math.floor(R.a.elixir)));
205 setText('crowns', `${R.crowns.a}–${R.crowns.b}`);
206 setText('best', String(R.wins));
207 }
208 function note(text) { setText('status', text); G.noteUntil = G.time + 2.2; }
209 const cardLine = () => { const c = CARDS[R.a.hand[R.selected]]; return `${c.title} · ${c.cost} elixir · ${c.spell ? 'anywhere' : 'your half'}`; };
210 const HINT = 'pick a card, then tap your half of the arena';
211
212 function act(events) {
213 for (const e of events) {
214 if (e.type === 'deploy') {
215 G.pops.push({ x: e.x, y: e.y, side: e.side, age: 0 });
216 if (e.side === 'a') { note(`${CARDS[e.card].title} sent`); sound(e.card === 'fireball' ? 'boom' : 'pop'); }
217 else if (e.card === 'fireball') sound('boom');
218 } else if (e.type === 'fireball') G.fx.push({ x: e.x, y: e.y, age: 0 });
219 else if (e.type === 'deny') {
220 if (e.side === 'a') { note(e.why === 'elixir' ? 'not enough elixir yet' : 'troops go on your half only'); sound('thud'); }
221 } else if (e.type === 'tower') {
222 note(e.side === 'b' ? `rival ${e.kind} tower down` : `your ${e.kind} tower fell`);
223 sound(e.side === 'b' ? 'chime' : 'buzz');
224 } else if (e.type === 'over') {
225 if (R.record) try { localStorage.setItem(BEST_KEY, String(R.wins)); } catch (err) { /* private window: keep it for this visit */ }
226 const line = e.verdict === 'win' ? 'you win' : e.verdict === 'loss' ? 'rival wins' : 'draw';
227 nodes.status.textContent = hudText.status = `${line} ${e.a}–${e.b} · tap or press space to play again`;
228 G.noteUntil = Infinity;
229 sound(e.verdict === 'win' ? 'chime' : 'buzz');
230 }
231 }
232 renderHud();
233 }
234 function restart() {
235 const next = Duel.again(R);
236 if (!next) return false;
237 R = next; G.fx = []; G.pops = []; G.cursor = null;
238 note(HINT);
239 renderHud();
240 return true;
241 }
242 function update(dt) {
243 G.time += dt;
244 act(Duel.advance(R, dt));
245 for (const f of G.fx) f.age += dt;
246 for (const f of G.pops) f.age += dt;
247 G.fx = G.fx.filter(f => f.age < .5);
248 G.pops = G.pops.filter(f => f.age < .4);
249 if (R.phase === 'play' && G.time >= G.noteUntil) setText('status', cardLine());
250 renderHud();
251 }
252
253 /* ---------- input ---------- */
254 function choose(slot) {
255 Duel.select(R, slot);
256 note(cardLine());
257 }
258 function put(x, y) { act(Duel.playSelected(R, x, y)); }
259 canvas.addEventListener('pointerdown', e => {
260 ensureAudio();
261 canvas.focus({ preventScroll: true });
262 if (restart()) return;
263 if (R.phase !== 'play') return;
264 const rect = canvas.getBoundingClientRect(), scale = rect.width / W;
265 const x = (e.clientX - rect.left) / scale, y = (e.clientY - rect.top) / scale;
266 G.cursor = null;
267 if (y >= BAR.y - 4) {
268 for (let i = 0; i < 4; i++) { const b = CARD_BOX(i); if (x >= b.x - 3 && x <= b.x + b.w + 3) { choose(i); return; } }
269 return;
270 }
271 put((x - AX) / T, (y - AY) / T);
272 });
273 const STEP_X = 2, STEP_Y = 2.25;
274 function moveCursor(dx, dy) {
275 G.cursor = G.cursor || { x: 8, y: BRIDGES[0] };
276 G.cursor.x = Math.max(.5, Math.min(ARENA.w - .5, G.cursor.x + dx));
277 G.cursor.y = Math.max(.5, Math.min(ARENA.h - .5, G.cursor.y + dy));
278 }
279 canvas.addEventListener('keydown', e => {
280 const k = e.key;
281 if (k === ' ' || k === 'Enter') {
282 e.preventDefault();
283 ensureAudio();
284 if (e.repeat) return;
285 if (restart()) return;
286 if (R.phase !== 'play') return;
287 if (!G.cursor) moveCursor(0, 0);
288 put(G.cursor.x, G.cursor.y);
289 } else if (k >= '1' && k <= '4') { e.preventDefault(); if (R.phase === 'play') choose(Number(k) - 1); }
290 else if (k === 'Tab' && R.phase === 'play') { e.preventDefault(); choose((R.selected + (e.shiftKey ? 3 : 1)) % 4); }
291 else if (k === 'ArrowLeft') { e.preventDefault(); if (R.phase === 'play') moveCursor(-STEP_X, 0); }
292 else if (k === 'ArrowRight') { e.preventDefault(); if (R.phase === 'play') moveCursor(STEP_X, 0); }
293 else if (k === 'ArrowUp') { e.preventDefault(); if (R.phase === 'play') moveCursor(0, -STEP_Y); }
294 else if (k === 'ArrowDown') { e.preventDefault(); if (R.phase === 'play') moveCursor(0, STEP_Y); }
295 });
296
297 /* ---------- sound ---------- */
298 let audio = null, muted = false;
299 function ensureAudio() {
300 if (audio) { if (audio.state === 'suspended') audio.resume(); return; }
301 const AC = window.AudioContext || window.webkitAudioContext;
302 if (AC) audio = new AC();
303 }
304 function sound(kind) {
305 if (!audio || muted) return;
306 const now = audio.currentTime, gain = audio.createGain(), osc = audio.createOscillator();
307 const spec = {
308 pop: [420, 760, .1, .06, 'triangle'],
309 chime: [660, 1180, .3, .07, 'sine'],
310 thud: [200, 110, .12, .06, 'sine'],
311 boom: [180, 40, .35, .09, 'sawtooth'],
312 buzz: [150, 70, .3, .06, 'sawtooth'],
313 }[kind];
314 osc.type = spec[4];
315 osc.frequency.setValueAtTime(spec[0], now);
316 osc.frequency.exponentialRampToValueAtTime(spec[1], now + spec[2]);
317 gain.gain.setValueAtTime(spec[3], now);
318 gain.gain.exponentialRampToValueAtTime(.0005, now + spec[2]);
319 osc.connect(gain).connect(audio.destination);
320 osc.start(now); osc.stop(now + spec[2] + .01);
321 }
322 const muteButton = document.getElementById('mute');
323 muteButton.addEventListener('click', () => {
324 muted = !muted;
325 muteButton.textContent = muted ? 'sound off' : 'sound on';
326 muteButton.setAttribute('aria-pressed', String(muted));
327 });
328
329 /* ---------- fit and boot ---------- */
330 function fit() {
331 const dpr = window.devicePixelRatio || 1;
332 const fitScale = Math.min(innerWidth / W, (innerHeight - 40) / H);
333 const scale = Math.max(1, Math.floor(fitScale * dpr)) / dpr;
334 canvas.style.width = W * scale + 'px';
335 canvas.style.height = H * scale + 'px';
336 }
337 addEventListener('resize', fit);
338 fit();
339 note(HINT);
340 renderHud();
341 canvas.focus({ preventScroll: true });
342 let last = performance.now();
343 function frame(now) {
344 update(Math.min(.04, (now - last) / 1000));
345 last = now;
346 draw();
347 requestAnimationFrame(frame);
348 }
349 requestAnimationFrame(frame);
350 </script>
351 </body>
352 </html>
tower-duel/page.test.mjs added +41
@@ -0,0 +1,41 @@
1 import { test, expect } from 'bun:test';
2 import { boot } from '../playtest.mjs';
3
4 const card = i => [52 + i * 86, 240];
5
6 test('tapping a card then the field sends a troop and spends elixir', () => {
7 const g = boot('tower-duel');
8 const before = g.read('R.a.elixir'), troops = g.read('R.units.length');
9 g.tap(...card(0));
10 g.tap(50, 50);
11 expect(g.read('R.units.length')).toBeGreaterThan(troops);
12 expect(g.read('R.a.elixir')).toBeLessThan(before);
13 expect(g.errors).toEqual([]);
14 }, 30000);
15
16 test('the rival half refuses a troop and says so', () => {
17 const g = boot('tower-duel');
18 g.tap(...card(0));
19 const cost = g.read('Duel.CARDS[R.a.hand[R.selected]].spell');
20 if (cost) g.press('Tab');
21 g.tap(300, 50);
22 expect(g.read('R.units.length')).toBe(0);
23 expect(g.text()).toMatch(/your half only/);
24 }, 30000);
25
26 test('the keyboard picks a card, moves the ring and plays', () => {
27 const g = boot('tower-duel');
28 g.press('2');
29 expect(g.read('R.selected')).toBe(1);
30 g.press('ArrowRight');
31 g.press(' ');
32 expect(g.read('R.a.elixir')).toBeLessThan(5);
33 expect(g.errors).toEqual([]);
34 }, 30000);
35
36 test('the over line names the result', () => {
37 const g = boot('tower-duel');
38 g.run(100);
39 expect(String(g.el('status').textContent)).toMatch(/(you win|rival wins|draw) \d+–\d+ · tap or press space to play again/);
40 expect(g.errors).toEqual([]);
41 }, 30000);

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs