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

Migrated from github.com/amirmushichge/pixel-plays

Add Market Barrow: the playable page and its place in the catalogue, on the rules in `market-barrow/barrow.js` #193

Parked opened this
Closed without merging

vesper/pixel-plays:vesper/169-add-market-barrow-the-playable-page-and → main 2 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
9 files changed +422 −3
README.md +2 −1
@@ -51,6 +51,7 @@ Concept by [abhi](https://x.com/awwbhi2). Game by [AmirMushich](https://x.com/Am
5151 | [Dinghy Race](dinghy-race/) | A bay with a square course of three buoys and back over a start line, the wind from the south-east and shifting a little at each buoy: the boat steers itself buoy to buoy and you trim the sail; it drives best at half the angle between boat and wind, and loses speed quadratically as the trim drifts from that, so every leg and every wind shift asks for a new setting; two seeded rivals sail at a steady pace, first or second place is a win (forged by the crew on the engine and shell above, not by the original creators; rules in `dinghy-race/dinghy.js`) | Drag left and right along the sheet; Up and Down arrows trim in and out |
5252 | [Seed Packets](seed-packets/) | A potting-shed bench with sixteen face-down seed packets in a 4x4 grid, a watering can and a clock on the wall: tap a packet to turn it face up to show its flower, then a second; a matching pair stays face up and a mismatch turns both back after 0.8 s (taps in that beat are ignored); the layout is a seeded shuffle of eight pairs and the gardener returns after 16 turns (a turn is two packets), so you can afford eight mismatches; the end shows pairs found and turns used, and the best is the fewest turns in a win (forged by the crew on the engine and shell above, not by the original creators) | Tap; arrows + space |
5353 | [Ferryman](ferryman/) | A river with a near bank, a far bank and a ferry moored at the near landing: tap a passenger to load or unload it, then tap the ferry to cross (or press 1-4 to pick a passenger and Space to cross); the fox, the goose and the grain start on the near bank, and left alone together on a bank the fox eats the goose and the goose eats the grain, so the ferry carries one at a time; three levels, the later ones add a dog, a two-seat ferry and a crossing limit, and a round is won by getting everyone across in par crossings or fewer, the HUD showing level, crossings and par as the rules report them (forged by the crew on the engine and shell above, not by the original creators; rules in `ferryman/ferry.js`) | Tap; 1-4 and Space |
54 | [Market Barrow](market-barrow/) | A village lane with four numbered stalls (Mill, Harbour, Orchard, Forge), each with a chalk price board of four numbers, and a barrow that carries up to 10 goods (wool, salt, apples, iron): tap a stall, or press 1-4 or the arrow keys, to wheel there, which costs a day, and tap a good's buy or sell button to trade one; you start day 1 with 100 coins, prices swing between half and one and a half times the usual from a seed, a board shows the price you will meet on arrival at the other stalls, and travelling on day 10 ends the game, a win at 150 coins or more (goods left over count for nothing); the HUD shows the day, coins and barrow load, prices and loads are always written as numbers, and only the stall awnings move on their own (stopped under reduced motion) (forged by the crew on the engine and shell above, not by the original creators; rules in `market-barrow/barrow.js`) | Tap a stall, then buy or sell; 1-4 or Left and Right to travel |
5455 | [Sandcastle Tide](sandcastle/) | A square beach with a sandcastle on the far edge, rocks scattered over the sand and the sea along the near edge: tap a sand square to pat down a wall (or move a cursor with the arrow keys and press Space), four walls before each tide, then tap tide (or press Enter) and the water floods every square it can reach from the sea, a little further each time, never through a wall or a rock, and washes away half the walls it touches; keep the castle dry through five tides, the HUD showing the tide, the walls left and the dry squares; input is ignored while the water spreads, the surf line ripples (stopped under reduced motion), and sand, water, walls and rocks differ by texture as well as colour (forged by the crew on the engine and shell above, not by the original creators; rules in `sandcastle/tide.js`) | Tap a sand square, then tide; arrows and Space to build, Enter for the tide |
5556 | [Lock Keeper](lock-keeper/) | A flight of three canal locks climbing left to right, red narrowboats waiting at the bottom to go up and blue ones at the top to come down, in a seeded order (three rounds shipped, each with a par): tap a paddle or gate to work it and a boat to move it into or out of its lock, or Left and Right to pick a lock and 1 to 5 for its top paddle, bottom paddle, top gate, bottom gate and a boat; a gate opens only on level water, a paddle fills or empties the lock but not while the far gate is open, two open paddles flood the lock and lose the round, a refusal says why, and the end shows operations against par (forged by the crew on the engine and shell above, not by the original creators; rules in `lock-keeper/lock.js`) | Tap; Left and Right, 1 to 5 |
5657 | [Empire Age](empire/) | A real-time strategy game on a 44 by 44 map against a red bot (easy, normal or hard): four villagers and a town center each, gather food, wood, gold and stone, build houses, camps, farms and military buildings, climb the Dark, Feudal, Castle and Imperial Ages, research upgrades, train militia, spearmen, archers, knights and rams, and destroy every town center and castle of the enemy; fog of war, a minimap, attack alerts, pause, 1x/2x/4x speed, an autopilot, a save that survives a reload and a best time per level (forged by the crew on the engine and shell above, not by the original creators) | Tap or drag a box to select, tap to command, panel buttons to build and train; arrows move the view, Enter taps its centre cross, 1-9 press buttons |
@@ -77,7 +78,7 @@ On the forge, `forge.json` runs `bun serve.mjs` with health check `/`. State is
7778 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.
7879
7980 ## Add a game
80 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, Tower Duel and Sandcastle Tide 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`.
81 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, Tower Duel, Sandcastle Tide and Market Barrow 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`.
8182
8283 - `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.
8384 - `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.
index.html +2 −1
@@ -43,7 +43,7 @@ li .tags { order: -1; font-size: .75rem; letter-spacing: .06em; text-transform:
4343 li a { order: 0; }
4444 #town { display: none; }
4545 .js #town { display: block; overflow-x: auto; max-width: 44rem; margin: 0 auto 1.5rem; }
46 .js #c { display: block; width: 100%; min-width: 600px; aspect-ratio: 2 / 1; image-rendering: pixelated; touch-action: pan-x pan-y; }
46 .js #c { display: block; width: 100%; min-width: 740px; aspect-ratio: 2 / 1; image-rendering: pixelated; touch-action: pan-x pan-y; }
4747 #status { margin: 0 0 1rem; min-height: 1.5em; }
4848 #status { visibility: hidden; }
4949 .js #status { visibility: visible; }
@@ -105,6 +105,7 @@ footer a::after { content: none; }
105105 <li data-kind="Racing" data-input="Drag" style="--accent:#2e8a7a"><a href="dinghy-race/">Dinghy Race</a><span>Drag to trim the sail to the wind and round three buoys ahead of the fleet</span><span>Game forged by the crew</span><span class="tags">Racing · Drag</span></li>
106106 <li data-kind="Memory" data-input="Tap" style="--accent:#7d9a4a"><a href="seed-packets/">Seed Packets</a><span>Tap to turn over seed packets and match every pair before the gardener comes back</span><span>Game forged by the crew</span><span class="tags">Memory · Tap</span></li>
107107 <li data-kind="Strategy" data-input="Tap" style="--accent:#4f7f6a"><a href="ferryman/">Ferryman</a><span>Row the fox, the goose and the grain across without leaving the wrong pair alone</span><span>Game forged by the crew</span><span class="tags">Strategy · Tap</span></li>
108 <li data-kind="Strategy" data-input="Tap" style="--accent:#b5733a"><a href="market-barrow/">Market Barrow</a><span>Buy cheap and sell dear between the village stalls for ten days</span><span>Game forged by the crew</span><span class="tags">Strategy · Tap</span></li>
108109 <li data-kind="Strategy" data-input="Tap" style="--accent:#d8b25a"><a href="sandcastle/">Sandcastle Tide</a><span>Pat down sand walls between tides and keep the castle dry through five high waters</span><span>Game forged by the crew</span><span class="tags">Strategy · Tap</span></li>
109110 <li data-kind="Strategy" data-input="Tap" style="--accent:#5a6e8a"><a href="lock-keeper/">Lock Keeper</a><span>Work the paddles and gates to bring every narrowboat through the flight of locks</span><span>Game forged by the crew</span><span class="tags">Strategy · Tap</span></li>
110111 <li data-kind="Strategy" data-input="Tap" style="--accent:#3a5fa8"><a href="empire/">Empire Age</a><span>A real-time strategy game against a bot: gather, build, climb four ages, train an army and destroy the enemy town center</span><span>Game forged by the crew</span><span class="tags">Strategy · Tap</span></li>
market-barrow/index.html added +402
@@ -0,0 +1,402 @@
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>Market Barrow</title>
7 <!-- og:begin -->
8 <meta name="description" content="Buy cheap and sell dear between the village stalls for ten days">
9 <link rel="canonical" href="https://pixel-plays--forge-trevato-apps.open-platform.sh/market-barrow/">
10 <meta property="og:type" content="website">
11 <meta property="og:site_name" content="Pixel Plays">
12 <meta property="og:title" content="Market Barrow">
13 <meta property="og:description" content="Buy cheap and sell dear between the village stalls for ten days">
14 <meta property="og:url" content="https://pixel-plays--forge-trevato-apps.open-platform.sh/market-barrow/">
15 <meta property="og:image" content="https://pixel-plays--forge-trevato-apps.open-platform.sh/og/market-barrow.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="Market Barrow: 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: #b5733a; }
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 0 124px 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 #trade { position: fixed; left: max(16px, env(safe-area-inset-left)); right: max(16px, env(safe-area-inset-right)); bottom: calc(max(14px, env(safe-area-inset-bottom)) + 30px); display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px; }
34 .good { display: grid; justify-items: center; gap: 3px; min-width: 0; }
35 .good > span { color: var(--muted); white-space: nowrap; }
36 .good b { color: var(--ink); font-weight: 600; font-variant-numeric: tabular-nums; }
37 .btns { display: flex; gap: 6px; }
38 .row { display: flex; align-items: center; gap: 8px; color: #8a5a28; }
39 .row b { font-size: 16px; font-weight: 600; min-width: 1ch; font-variant-numeric: tabular-nums; }
40 .row span { color: var(--muted); }
41 #status { color: var(--muted); min-height: 1.35em; }
42 button { pointer-events: auto; font: inherit; color: var(--muted); background: none; border: 0; padding: 10px; margin: -10px; cursor: pointer; }
43 button.act { color: var(--ink); border: 1px solid var(--muted); border-radius: 4px; padding: 7px 10px; margin: 0; min-width: 44px; }
44 button:hover, button:focus-visible { color: var(--ink); }
45 button.act:hover, button.act:focus-visible { border-color: var(--ink); }
46 </style>
47 </head>
48 <body>
49 <div id="stage"><canvas id="c" tabindex="0" aria-label="A village lane with four market stalls in a row, numbered 1 to 4 (Mill, Harbour, Orchard, Forge), each with a price board of four numbers, and a barrow standing at one stall carrying wool, salt, apples and iron. Tap a stall, or press 1 to 4, to travel there, which costs a day. Use the buy and sell buttons under the lane to trade one good at a time. Buy where a good is cheap and sell where it is dear, and reach 150 coins by day 10."></canvas></div>
50 <div id="scores">
51 <div class="row"><b id="day">-</b><span>day</span></div>
52 <div class="row"><b id="coins">-</b><span>coins</span></div>
53 <div class="row"><b id="load">-</b><span>in the barrow</span></div>
54 </div>
55 <div id="trade">
56 <div class="good"><span>wool <b id="p-wool">-</b></span><span>carry <b id="c-wool">0</b></span><div class="btns"><button class="act" id="buy-wool" type="button" aria-label="buy wool">buy</button><button class="act" id="sell-wool" type="button" aria-label="sell wool">sell</button></div></div>
57 <div class="good"><span>salt <b id="p-salt">-</b></span><span>carry <b id="c-salt">0</b></span><div class="btns"><button class="act" id="buy-salt" type="button" aria-label="buy salt">buy</button><button class="act" id="sell-salt" type="button" aria-label="sell salt">sell</button></div></div>
58 <div class="good"><span>apples <b id="p-apples">-</b></span><span>carry <b id="c-apples">0</b></span><div class="btns"><button class="act" id="buy-apples" type="button" aria-label="buy apples">buy</button><button class="act" id="sell-apples" type="button" aria-label="sell apples">sell</button></div></div>
59 <div class="good"><span>iron <b id="p-iron">-</b></span><span>carry <b id="c-iron">0</b></span><div class="btns"><button class="act" id="buy-iron" type="button" aria-label="buy iron">buy</button><button class="act" id="sell-iron" type="button" aria-label="sell iron">sell</button></div></div>
60 </div>
61 <div class="hud" id="bottom">
62 <div id="status" role="status" aria-live="polite"></div>
63 <button id="mute" type="button" aria-pressed="false">sound on</button>
64 </div>
65 <script src="../shell.js"></script>
66 <script>
67 PixelPlays.mount({
68 id: 'market-barrow',
69 rules: [
70 'Tap a stall, or press 1 to 4, to travel there: every trip costs a day.',
71 'Tap buy or sell under the lane to trade one good; the barrow holds 10.',
72 'A board shows the price you will meet on arrival, so plan the next stall.',
73 'Reach 150 coins by day 10: goods left in the barrow count for nothing.',
74 ],
75 });
76 </script>
77 <script>window.PP_SCENE = { originY: 14, shadowX: 1.3, shadowY: -.12 };</script>
78 <script src="../engine.js"></script>
79 <script src="barrow.js"></script>
80 <script>
81 'use strict';
82
83 const DIRT = [196, 168, 124], VERGE = [112, 150, 82], WOOD = [150, 108, 70], WOOD_DARK = [104, 74, 50], SLATE = [44, 52, 56], FRAME = [196, 160, 110];
84 const CREAM = [244, 236, 214];
85 const GOOD_COLOUR = { wool: [238, 234, 222], salt: [160, 190, 236], apples: [200, 54, 46], iron: [92, 100, 116] };
86 const GOOD_LETTER = { wool: 'W', salt: 'S', apples: 'A', iron: 'I' };
87 const AWNING = [[198, 118, 56], [60, 112, 164], [98, 152, 72], [172, 62, 52]];
88 const STALL_U = [-12, -4, 4, 12], STALL_V = -3.5, STALL_HALF_U = 3.2, STALL_HALF_V = 1.3, FRONT_V = STALL_V + STALL_HALF_V;
89 const LANE_HALF_U = 16.5, LANE_V0 = -6.8, LANE_V1 = 7.2, BARROW_V = 3.6, SPEED = 18;
90 const AWNING_FRONT_V = FRONT_V + .6, AWNING_LOW = 4.25, AWNING_HIGH = 4.75;
91 const BEST_KEY = 'pixel-plays-market-barrow-best';
92 const INK_PIX = rgb(28, 27, 25), WHITE_PIX = rgb(255, 255, 255), CHALK = rgb(246, 244, 232), HIGH_PIX = rgb(255, 196, 96);
93 // 3x5 pixel glyphs, row by row: the price boards and counter numbers are always written out
94 const GLYPH = {
95 0: '111101101101111', 1: '010110010010111', 2: '111001111100111', 3: '111001111001111', 4: '101101111001001',
96 5: '111100111001111', 6: '111100111101111', 7: '111001001001001', 8: '111101111101111', 9: '111101111001111',
97 W: '101101101111101', S: '011100010001110', A: '010101111101101', I: '111010010010111',
98 };
99
100 const world = (u, v, z) => [(u + v) / R2, (v - u) / R2, z];
101 const lastBest = (() => { try { const n = parseInt(localStorage.getItem(BEST_KEY), 10); return Number.isInteger(n) && n > 0 ? n : 0; } catch (e) { return 0; } })();
102
103 /* ---------- state ---------- */
104 let seed = Math.floor(Date.now() / 1000), R = MarketBarrow.start(seed, lastBest);
105 const G = { time: 0, noteUntil: 0, barrowU: STALL_U[0] };
106 const nodes = {};
107 for (const k of ['day', 'coins', 'load', 'status']) nodes[k] = document.getElementById(k);
108 for (const g of MarketBarrow.GOODS) { nodes['p-' + g] = document.getElementById('p-' + g); nodes['c-' + g] = document.getElementById('c-' + g); }
109 const shown = {};
110 function setText(key, text) {
111 if (shown[key] === text) return;
112 shown[key] = text;
113 nodes[key].textContent = text;
114 }
115 const stallIndex = () => MarketBarrow.STALLS.indexOf(R.stall);
116 const loadOf = () => MarketBarrow.load(R);
117 function renderHud() {
118 setText('day', `${R.day} of ${MarketBarrow.DAYS}`);
119 setText('coins', String(R.coins));
120 setText('load', `${loadOf()} of ${R.capacity}`);
121 for (const g of MarketBarrow.GOODS) { setText('p-' + g, String(R.prices[g])); setText('c-' + g, String(R.cargo[g])); }
122 }
123 function note(text) { setText('status', text); G.noteUntil = G.time + 2.5; }
124
125 /* ---------- painting ---------- */
126 function put(ramp, u, v, z, tone) {
127 const p = project((u + v) / R2, (v - u) / R2, z), ix = p.sx | 0, iy = p.sy | 0;
128 if (ix < 0 || iy < 0 || ix >= W || iy >= H) return;
129 const i = iy * W + ix;
130 if (p.d <= zb[i]) return;
131 zb[i] = p.d;
132 pix[i] = ramp[clamp(Math.floor(tone + (bayerAt(ix, iy) - .5) * .5), 0, 4)];
133 }
134 function top(ramp, u0, u1, v0, v1, z, tone, step = .08) {
135 for (let u = u0; u <= u1; u += step) for (let v = v0; v <= v1; v += step) put(ramp, u, v, typeof z === 'function' ? z(v) : z, typeof tone === 'function' ? tone(u, v) : tone);
136 }
137 function front(ramp, u0, u1, v, z0, z1, tone, step = .08) {
138 for (let u = u0; u <= u1; u += step) for (let z = z0; z <= z1; z += step) put(ramp, u, v, z, typeof tone === 'function' ? tone(u, z) : tone);
139 }
140 function side(ramp, u, v0, v1, z0, z1, tone, step = .08) {
141 for (let v = v0; v <= v1; v += step) for (let z = z0; z <= z1; z += step) put(ramp, u, v, z, typeof tone === 'function' ? tone(v, z) : tone);
142 }
143 // a solid block: lit top, mid front face, dark right face
144 function block(ramp, u0, u1, v0, v1, z0, z1, grain = 0, step = .08) {
145 const g = (a, b) => (grain ? (noise(a * 3, b * 3) - .5) * grain : 0);
146 top(ramp, u0, u1, v0, v1, z1, (u, v) => 3.3 + g(u, v), step);
147 front(ramp, u0, u1, v1, z0, z1, (u, z) => 2.3 + g(u, z), step);
148 side(ramp, u1, v0, v1, z0, z1, (v, z) => 1.2 + g(v, z), step);
149 }
150 const stripe = (u, w) => Math.floor((u + 100) / w) & 1;
151
152 const dirtRamp = rampOf(DIRT), vergeRamp = rampOf(VERGE), woodRamp = rampOf(WOOD), darkRamp = rampOf(WOOD_DARK), slateRamp = rampOf(SLATE), frameRamp = rampOf(FRAME), creamRamp = rampOf(CREAM);
153 function groundColor(x, y, ix, iy) {
154 const u = (x - y) / R2, v = (x + y) / R2;
155 if (Math.max(Math.abs(u) - LANE_HALF_U, v - LANE_V1, LANE_V0 - v) > -hash(ix, iy) * 1.2) return 0; // a ragged edge into the white
156 const t = .96 + (hash(ix, iy) - .5) * .1 + (noise(u * .6, v * .9) - .5) * .1;
157 if (v < -5.3 || v > 6.3) return rgb(VERGE[0] * t, VERGE[1] * t, VERGE[2] * t);
158 const cobble = hash(Math.floor(u * 1.6), Math.floor(v * 1.6)) > .86 ? .88 : 1; // a few darker cobbles in the lane
159 return rgb(DIRT[0] * t * cobble, DIRT[1] * t * cobble, DIRT[2] * t * cobble);
160 }
161 function bakeStall(k) {
162 const su = STALL_U[k], accent = AWNING[k], name = MarketBarrow.STALLS[k], good = MarketBarrow.GOODS[k];
163 const u0 = su - STALL_HALF_U, u1 = su + STALL_HALF_U, v0 = STALL_V - STALL_HALF_V;
164 block(woodRamp, u0, u1, v0, FRONT_V, 0, 1.5, .6);
165 for (const pu of [u0 + .15, u1 - .15]) for (const pv of [v0 + .15, FRONT_V - .15]) { // four posts up to the awning
166 capsule(world(pu, pv, 0), world(pu, pv, AWNING_HIGH), .13, .13, () => WOOD_DARK, 'solid');
167 }
168 // the price board, a chalk slate in a frame, hung under the awning on the counter's front plane
169 top(frameRamp, su - 3.05, su + 3.05, FRONT_V, FRONT_V, 4.45, 3.4);
170 front(frameRamp, su - 3.05, su + 3.05, FRONT_V + .01, 1.5, 4.45, 3);
171 front(slateRamp, su - 2.95, su + 2.95, FRONT_V + .02, 1.62, 4.35, 1.8);
172 // what the stall sells, in a small pile on the counter
173 const c = rampOf(GOOD_COLOUR[good]);
174 block(c, su - 1.2, su - .2, v0 + .3, v0 + 1.2, 1.5, 2.2, .8, .06);
175 block(c, su + .2, su + 1.1, v0 + .5, v0 + 1.3, 1.5, 2.0, .8, .06);
176 // the awning: a sloped striped roof, lower at the front
177 const aRamp = rampOf(accent), slope = v => AWNING_LOW + (AWNING_HIGH - AWNING_LOW) * (AWNING_FRONT_V - v) / (AWNING_FRONT_V - (v0 - .2));
178 top(aRamp, u0 - .3, u1 + .3, v0 - .2, AWNING_FRONT_V, slope, u => (stripe(u - su, .85) ? 3.6 : 2.4), .06);
179 top(creamRamp, u0 - .3, u0 - .25, v0 - .2, AWNING_FRONT_V, slope, 3, .05);
180 for (let q = -3; q <= 3; q++) castShadow(...world(su + q * .9, STALL_V, 0).slice(0, 2), AWNING_HIGH, .8, 1, 0);
181 return name;
182 }
183 function bake() {
184 ground.fill(0); shadowMask.fill(0); staticShadow.fill(0); kinds.fill(0);
185 tufts.length = 0; leaves.length = 0;
186 zb.fill(-1e9);
187 pix.fill(rgb(255, 255, 255));
188 for (let iy = 0; iy < H; iy++) for (let ix = 0; ix < W; ix++) {
189 const g = unproject(ix + .5, iy + .5), i = iy * W + ix, c = groundColor(g.x, g.y, ix, iy);
190 if (!c) continue;
191 pix[i] = c; ground[i] = 1;
192 zb[i] = (g.x + g.y) / R2 * COS;
193 }
194 groundZ.set(zb);
195 for (let k = 0; k < STALL_U.length; k++) bakeStall(k);
196 bakeOcclusion();
197 applyShadows(groundZ);
198 bakedPix.set(pix);
199 bakedZ.set(zb);
200 }
201
202 /* ---------- text on the canvas, in whole pixels ---------- */
203 function glyph(sx, sy, ch, pixel, scale = 2) {
204 const g = GLYPH[ch];
205 if (!g) return;
206 for (let k = 0; k < 15; k++) if (g[k] === '1') for (let dy = 0; dy < scale; dy++) for (let dx = 0; dx < scale; dx++) {
207 const x = sx + (k % 3) * scale + dx, y = sy + Math.floor(k / 3) * scale + dy;
208 if (x >= 0 && y >= 0 && x < W && y < H) pix[y * W + x] = pixel;
209 }
210 }
211 const advance = scale => 4 * scale;
212 function write(sx, sy, str, pixel, scale = 2) {
213 [...str].forEach((ch, n) => glyph(sx + n * advance(scale), sy, ch, pixel, scale));
214 }
215 function outlined(sx, sy, str, pixel) {
216 for (const [dx, dy] of [[-1, 0], [1, 0], [0, -1], [0, 1], [-1, -1], [1, 1], [-1, 1], [1, -1]]) write(sx + dx, sy + dy, str, INK_PIX);
217 write(sx, sy, str, pixel);
218 }
219 // the numbers each stall shows: the current stall's own board, and the price you would meet on arrival at the others
220 const boardPrices = k => (k === stallIndex() ? R.prices : MarketBarrow.prices(R.seed, MarketBarrow.STALLS[k], Math.min(R.day + 1, MarketBarrow.DAYS)));
221 function drawBoards() {
222 for (let k = 0; k < STALL_U.length; k++) {
223 const p = project(...world(STALL_U[k] - 2.95, FRONT_V, 4.35)), x0 = Math.round(p.sx) + 5, y0 = Math.round(p.sy) + 1, prices = boardPrices(k);
224 MarketBarrow.GOODS.forEach((good, n) => {
225 const x = x0 + (n % 2) * 29, y = y0 + (n >> 1) * 11, str = String(prices[good]).padStart(2, ' ');
226 write(x, y, GOOD_LETTER[good], rgb(...GOOD_COLOUR[good]), 2);
227 write(x + 8, y, str, k === stallIndex() ? rgb(255, 220, 90) : CHALK, 2);
228 });
229 const c = project(...world(STALL_U[k], FRONT_V, 1.4)); // the stall's number on its counter
230 outlined(Math.round(c.sx) - 3, Math.round(c.sy) - 1, String(k + 1), WHITE_PIX);
231 }
232 }
233
234 /* ---------- the barrow, drawn each frame ---------- */
235 function drawBarrow() {
236 const u = G.barrowU, v = BARROW_V, bed = rampOf(WOOD), dark = rampOf(WOOD_DARK);
237 block(bed, u - 1.7, u + 1.7, v - 1.2, v + 1.2, .6, 1.1, .6, .06);
238 for (const dv of [-1.1, 1.1]) capsule(world(u - 1.7, v + dv, 1), world(u - 3.2, v + dv, 1.8), .1, .1, () => WOOD_DARK, 'solid'); // handles
239 sphere(...world(u + 1.7, v, .6), .6, [58, 52, 48], 'solid'); // the wheel
240 const flat = [];
241 MarketBarrow.GOODS.forEach(g => { for (let n = 0; n < R.cargo[g]; n++) flat.push(g); });
242 flat.forEach((g, n) => { // each carried unit is a small crate: two layers of five
243 const col = n % 5, layer = Math.floor(n / 5), cu = u - 1.2 + col * .6, cv = v - .35, lz = 1.1;
244 block(rampOf(GOOD_COLOUR[g]), cu - .25, cu + .25, cv - .3 + (layer ? .1 : 0), cv + .3 + (layer ? .1 : 0), lz, lz + .45, .6, .05);
245 });
246 castShadow(...world(u, v, 0).slice(0, 2), 1.4, 2.1, 1, 0);
247 }
248 function draw() {
249 pix.set(bakedPix);
250 zb.set(bakedZ);
251 drawBarrow();
252 drawAwnings();
253 applyShadows(groundZ);
254 shadeEdges();
255 drawBoards();
256 const p = project(...world(G.barrowU, BARROW_V, 2.3)); // the load, as a number, above the barrow
257 outlined(Math.round(p.sx) - 3, Math.round(p.sy) - 4, String(loadOf()), WHITE_PIX);
258 if (R.status === 'over') { // a red bar over the lane's top edge when it ends
259 const c = R.result === 'won' ? HIGH_PIX : rgb(214, 48, 40);
260 for (let x = 90; x < 270; x++) for (const y of [20, 21]) pix[y * W + x] = c;
261 }
262 ctx.putImageData(image, 0, 0);
263 }
264 // the awning valances, the one thing that moves on its own: scallops that shift a pixel at 8 fps, still under reduced motion
265 function drawAwnings() {
266 const beat = STILL ? 0 : Math.floor(G.time * 8);
267 for (let k = 0; k < STALL_U.length; k++) {
268 const su = STALL_U[k], shift = STILL ? 0 : [0, .1, .2, .1][(beat + k) & 3], ramp = rampOf(AWNING[k]);
269 for (let u = su - STALL_HALF_U - .3; u <= su + STALL_HALF_U + .3; u += .05) {
270 const edge = AWNING_LOW - .45 + .22 * Math.abs(Math.sin((u + shift) * Math.PI / .85)), tone = stripe(u + shift - su, .85) ? 3.2 : 2;
271 for (let z = edge; z <= AWNING_LOW; z += .05) put(ramp, u, AWNING_FRONT_V, z, tone);
272 }
273 }
274 }
275
276 /* ---------- game ---------- */
277 const HINT = 'tap a stall to travel there, then buy or sell';
278 const REFUSALS = {
279 'barrow-full': 'the barrow is full', 'too-poor': 'not enough coins', 'not-carried': 'none of that in the barrow',
280 'bad-quantity': 'trade one at a time', 'unknown-good': 'no such good', 'unknown-stall': 'no such stall', 'game-over': 'the ten days are over',
281 };
282 function line() {
283 if (R.status === 'over') return `${R.line} · best ${R.best} · tap or press a key to play again`;
284 return R.day === MarketBarrow.DAYS ? `${R.line} · last day: travelling ends the game` : R.line;
285 }
286 function restart() {
287 ensureAudio();
288 seed++;
289 R = MarketBarrow.start(seed, R.best);
290 G.barrowU = STALL_U[0];
291 renderHud(); note(HINT);
292 }
293 function afterMove(out, tone) {
294 if (!out.ok) { sound(140, .15, 'sawtooth'); note(out.why === 'already-here' ? `you are at the ${R.stall} stall already` : REFUSALS[out.why] || out.why); return false; }
295 R = out.state;
296 sound(tone, .08, 'triangle');
297 renderHud();
298 return true;
299 }
300 function trade(kind, good) {
301 ensureAudio();
302 if (R.status === 'over') { restart(); return; }
303 if (afterMove(MarketBarrow[kind](R, good, 1), kind === 'buy' ? 360 : 520)) note(R.line);
304 }
305 function goTo(k) {
306 ensureAudio();
307 if (R.status === 'over') { restart(); return; }
308 const name = MarketBarrow.STALLS[k];
309 if (!name || !afterMove(MarketBarrow.travel(R, name), 260)) return;
310 if (R.status === 'over') {
311 try { localStorage.setItem(BEST_KEY, String(R.best)); } catch (err) { /* private window: keep it for this visit */ }
312 if (R.result === 'won') { sound(520, .3, 'sine'); sound(780, .5, 'sine', .15); } else sound(110, .6, 'sawtooth');
313 setText('status', line()); G.noteUntil = 0;
314 } else note(R.line);
315 }
316 function update(dt) {
317 G.time += dt;
318 const to = STALL_U[stallIndex()], step = SPEED * dt;
319 G.barrowU = Math.abs(to - G.barrowU) <= step ? to : G.barrowU + Math.sign(to - G.barrowU) * step;
320 if (R.status === 'over' || G.time >= G.noteUntil) setText('status', line());
321 }
322
323 /* ---------- input ---------- */
324 // the stall under a point on the canvas, or -1: its column of the lane, from the awning down to the lane's front edge
325 function stallAt(px, py) {
326 const g = unproject(px, py), u = (g.x - g.y) / R2;
327 if (py < 70 || py > 205) return -1;
328 const k = Math.floor((u + 16) / 8);
329 return k >= 0 && k < STALL_U.length ? k : -1;
330 }
331 const stallCentre = k => { const p = project(...world(STALL_U[k], FRONT_V, 2)); return [p.sx, p.sy]; };
332 canvas.addEventListener('pointerdown', e => {
333 canvas.focus({ preventScroll: true });
334 const r = canvas.getBoundingClientRect(), px = (e.clientX - r.left) / r.width * W, py = (e.clientY - r.top) / r.height * H;
335 if (R.status === 'over') { restart(); return; }
336 const k = stallAt(px, py);
337 if (k >= 0) goTo(k);
338 });
339 canvas.addEventListener('keydown', e => {
340 const n = parseInt(e.key, 10), pick = n >= 1 && n <= 4 && e.key.length === 1, step = e.key === 'ArrowRight' ? 1 : e.key === 'ArrowLeft' ? -1 : 0;
341 if (!pick && !step) return;
342 e.preventDefault();
343 if (e.repeat) return;
344 if (R.status === 'over') { restart(); return; }
345 const k = pick ? n - 1 : stallIndex() + step;
346 if (k >= 0 && k < STALL_U.length) goTo(k);
347 });
348 for (const g of MarketBarrow.GOODS) {
349 document.getElementById('buy-' + g).addEventListener('click', () => { canvas.focus({ preventScroll: true }); trade('buy', g); });
350 document.getElementById('sell-' + g).addEventListener('click', () => { canvas.focus({ preventScroll: true }); trade('sell', g); });
351 }
352
353 /* ---------- sound ---------- */
354 let audio = null, muted = false;
355 function ensureAudio() {
356 if (audio) { if (audio.state === 'suspended') audio.resume(); return; }
357 const AC = window.AudioContext || window.webkitAudioContext;
358 if (AC) audio = new AC();
359 }
360 function sound(freq, life, type, delay = 0) {
361 if (!audio || muted) return;
362 const now = audio.currentTime + delay, gain = audio.createGain(), osc = audio.createOscillator();
363 osc.type = type;
364 osc.frequency.setValueAtTime(freq, now);
365 gain.gain.setValueAtTime(.0001, now);
366 gain.gain.exponentialRampToValueAtTime(.07, now + .01);
367 gain.gain.exponentialRampToValueAtTime(.0005, now + life);
368 osc.connect(gain).connect(audio.destination);
369 osc.start(now); osc.stop(now + life + .02);
370 }
371 const muteButton = document.getElementById('mute');
372 muteButton.addEventListener('click', () => {
373 muted = !muted;
374 muteButton.textContent = muted ? 'sound off' : 'sound on';
375 muteButton.setAttribute('aria-pressed', String(muted));
376 });
377
378 /* ---------- fit and boot ---------- */
379 // the engine's fit leaves 40 px for the HUD; the trade row needs more
380 function fitLane() {
381 const dpr = window.devicePixelRatio || 1;
382 const scale = Math.max(1, Math.floor(Math.min(innerWidth / W, (innerHeight - 130) / H) * dpr)) / dpr;
383 canvas.style.width = W * scale + 'px';
384 canvas.style.height = H * scale + 'px';
385 }
386 addEventListener('resize', fitLane);
387 fitLane();
388 bake();
389 note(HINT);
390 renderHud();
391 canvas.focus({ preventScroll: true });
392 let last = performance.now();
393 function frame(now) {
394 update(Math.min(.04, (now - last) / 1000));
395 last = now;
396 draw();
397 requestAnimationFrame(frame);
398 }
399 requestAnimationFrame(frame);
400 </script>
401 </body>
402 </html>
og/home.png
Binary file not shown.
og/market-barrow.png added
Binary file not shown.
plaza.js +1 −1
@@ -3,7 +3,7 @@
33 // Needs ramp.js and town.js loaded first. Sets window.PixelPlaza.
44 (() => {
55 const Town = window.PixelTown, { rgb, rampOf, bayerAt } = window.PixelRamp;
6 const MIN_CSS_WIDTH = 600; // the canvas is never drawn narrower than this in CSS pixels (a phone scrolls it sideways), so a building stays about thumb-sized
6 const MIN_CSS_WIDTH = 740; // the canvas is never drawn narrower than this in CSS pixels (a phone scrolls it sideways), so a building stays about thumb-sized
77 const BUF_W = 640, BUF_H = 320; // the canvas's pixel size; CSS reserves the same aspect ratio, so the town fits it rather than the other way round
88 const PAD = 12, LIFT = 7; // buffer margin around the town; how far a hovered building rises, world units
99 const GRASS = [[52, 88, 52], [82, 118, 54], [34, 62, 50]];
rounds.mjs +7
@@ -158,6 +158,13 @@ export const ROUNDS = {
158158 g.tap(...g.read('ferryAt()'));
159159 g.run(.3);
160160 } },
161 // sell what the barrow carries, buy one apple, then wheel to the next stall; the tenth trip ends the game
162 'market-barrow': { over: /Won with|Lost with/, outcome: /(Won|Lost) with \d+ coins/, beat: g => {
163 for (const good of g.read('MarketBarrow.GOODS')) if (g.read(`R.cargo.${good}`) > 0) g.el(`sell-${good}`).fire('click');
164 g.el('buy-apples').fire('click');
165 g.tap(...g.read(`stallCentre((MarketBarrow.STALLS.indexOf(R.stall) + 1) % MarketBarrow.STALLS.length)`));
166 g.run(.3);
167 } },
161168 // wall off the row above the sea, then call the tide with Enter; the flood plays out before the next beat
162169 'sandcastle': { over: /castle stayed dry|sea reached the castle/, outcome: /The (castle stayed dry through \d+ tides|sea reached the castle in tide \d+)/, beat: g => {
163170 if (g.read('busy()')) { g.run(.3); return; }
serve.test.mjs +7
@@ -472,6 +472,13 @@ test('Sandcastle Tide and its rules script are served without a track', async ()
472472 expect((await fetch(base + '/sandcastle/tide.js')).status).toBe(200);
473473 });
474474
475 test('Market Barrow and its rules script are served without a track', async () => {
476 const page = await fetch(base + '/market-barrow/');
477 expect(page.status).toBe(200);
478 expect(page.headers.get('content-type')).toBe('text/html; charset=utf-8');
479 expect((await fetch(base + '/market-barrow/barrow.js')).status).toBe(200);
480 });
481
475482 test('Seed Packets and its rules script are served without a track', async () => {
476483 const page = await fetch(base + '/seed-packets/');
477484 expect(page.status).toBe(200);
shell.js +1
@@ -45,6 +45,7 @@ window.PixelPlays = (() => {
4545 { id: 'dinghy-race', title: 'Dinghy Race', blurb: 'Drag to trim the sail to the wind and round three buoys ahead of the fleet', kind: 'Racing', input: 'Drag', accent: '#2e8a7a', music: false, forged: true },
4646 { id: 'seed-packets', title: 'Seed Packets', blurb: 'Tap to turn over seed packets and match every pair before the gardener comes back', kind: 'Memory', input: 'Tap', accent: '#7d9a4a', music: false, forged: true },
4747 { id: 'ferryman', title: 'Ferryman', blurb: 'Row the fox, the goose and the grain across without leaving the wrong pair alone', kind: 'Strategy', input: 'Tap', accent: '#4f7f6a', music: false, forged: true },
48 { id: 'market-barrow', title: 'Market Barrow', blurb: 'Buy cheap and sell dear between the village stalls for ten days', kind: 'Strategy', input: 'Tap', accent: '#b5733a', music: false, forged: true },
4849 { id: 'sandcastle', title: 'Sandcastle Tide', blurb: 'Pat down sand walls between tides and keep the castle dry through five high waters', kind: 'Strategy', input: 'Tap', accent: '#d8b25a', music: false, forged: true },
4950 { id: 'lock-keeper', title: 'Lock Keeper', blurb: 'Work the paddles and gates to bring every narrowboat through the flight of locks', kind: 'Strategy', input: 'Tap', accent: '#5a6e8a', music: false, forged: true },
5051 { id: 'empire', title: 'Empire Age', blurb: 'A real-time strategy game against a bot: gather, build, climb four ages, train an army and destroy the enemy town center', kind: 'Strategy', input: 'Tap', accent: '#3a5fa8', music: false, forged: true },

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs