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

Migrated from github.com/amirmushichge/pixel-plays

Add Bowls Green: roll four biased woods to rest nearer the jack than the rival woods #144

Merged opened this

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

Merged

ledger/pixel-plays:ledger/96-add-bowls-green-roll-four-biased-woods-t → main 2 commits fork

  • Merged. ledger/96-add-bowls-green-roll-four-biased-woods-t was merged into main as ffa2a51.

Review

Sign in to review this change.
10 files changed +689 −2
README.md +3 −2
@@ -46,6 +46,7 @@ Concept by [abhi](https://x.com/awwbhi2). Game by [AmirMushich](https://x.com/Am
4646 | [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 |
4747 | [Egg Basket](egg-basket/) | A red henhouse with a sloping tin roof and three hens on the ridge: they lay brown eggs (1 point) and rare golden ones (3) that roll down one of four roof lanes and drop off the eave; slide the basket under each before it reaches the ground, where it cracks; rolling speeds up every ten eggs laid (never so fast that the basket cannot cross three lanes in time), three cracks end the round and 25 or more wins (forged by the crew on the engine and shell above, not by the original creators) | Drag the basket; Left and Right arrows move one lane |
4848 | [Coconut Shy](coconut-shy/) | A village-fete stall with bunting and a stallholder, five coconuts on wooden posts: drag back and release to throw (or Left and Right to aim, hold Space for power, release to throw); a ball inside the square window knocks a coconut off its post, two glancing hits knock it too, and clearing all five wins a bonus ball; five balls a round, three rounds with the posts moved further back each time, and nine down or more of the game wins (forged by the crew on the engine and shell above, not by the original creators; rules in `coconut-shy/shy.js`) | Drag back and release; Left and Right to aim, hold Space |
49 | [Bowls Green](bowls-green/) | A flat lawn bowls green floating on white, a white jack at the far end, a mat at the near end, two rival woods already resting near the jack and a low hedge behind: drag back from the mat and release to roll (or Left and Right to set the line, hold Space to build weight, release to roll); weight sets how far the wood runs (quadratic in weight, against a pace that is one seeded constant per game) and each wood bends towards its bias side as it slows, so aiming straight at the jack misses; a wood off the back of the green (or into the ditch at the side) is dead; one end of four woods, and one or more resting nearer the jack than the nearest rival wood wins (forged by the crew on the engine and shell above, not by the original creators; rules in `bowls-green/bowls.js`) | Drag back and release; Left and Right to aim, hold Space |
4950 | [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 |
5051 | [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 |
5152 | [Hot Air Balloon](hot-air-balloon/) | Five flights over patchwork farm fields with hedgerows, a windsock and one field marked with a white cross: hold the burner and the balloon climbs slowly after a short lag, let go and it sinks; the air has three height bands that each blow their own way and a little differently each flight, shown by drifting cloud wisps, three arrows at the left and a pennant on the basket, so you steer only by choosing a height (the ready screen before each flight already shows that flight's winds, so read them first); touching the ground ends the flight and the landing scores by distance from the cross (on it 5, inside its field 3, a neighbouring field 1, trees or the pond 0), each flight from a new launch point; 15 or more of 25 wins; the balloon's shadow on the fields shows where it is over (forged by the crew on the engine and shell above, not by the original creators) | Press and hold the canvas; hold space or the up arrow |
@@ -70,7 +71,7 @@ On the forge, `forge.json` runs `bun serve.mjs` with health check `/`. State is
7071 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.
7172
7273 ## Add a game
73 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 and Coconut Shy 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`.
74 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 and Bowls Green 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`.
7475
7576 - `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.
7677 - `engine.js` provides the camera, depth buffer, colour ramps, shadows, edges, figures, trees and wind as globals.
@@ -86,7 +87,7 @@ Create `<id>/index.html`, load `../shell.js`, call `PixelPlays.mount({ id, rules
8687 - Depth-buffer edges: darker where an object sits in front, a warm rim on upper-left edges.
8788 - Large flat surfaces use closely spaced tones; wide steps make the dither read as a checkerboard.
8889 - Characters stay sharp: flat bands with no dither, a dark silhouette on their own pixels, patterns at least 3px wide.
89 - Ambient motion only where the scene names it: grass and leaves sway in whole pixels at 8 fps, Tram Line's waiting passengers shift their weight, Espresso Bar's machine steam and awning fringe move, Sheepdog's crow on the wall shifts and dips its head, Hot Air Balloon's windsock and cloud wisps drift, Cloakroom's coats sway and the light under its door moves, Go-Kart Fete's chequered flags flutter and its spectators wave, Egg Basket's hens peck and the straw in its basket stirs (its rolling eggs are play, not ambience, and still move), and Dinghy Race's water ripples come and go and its start-line flags flutter (the boats are play, and still sail), and Coconut Shy's bunting flutters and its stallholder shifts and waves (the thrown ball and wobbling coconuts are play, and still move); all of it stops under `prefers-reduced-motion`.
90 - Ambient motion only where the scene names it: grass and leaves sway in whole pixels at 8 fps, Tram Line's waiting passengers shift their weight, Espresso Bar's machine steam and awning fringe move, Sheepdog's crow on the wall shifts and dips its head, Hot Air Balloon's windsock and cloud wisps drift, Cloakroom's coats sway and the light under its door moves, Go-Kart Fete's chequered flags flutter and its spectators wave, Egg Basket's hens peck and the straw in its basket stirs (its rolling eggs are play, not ambience, and still move), and Dinghy Race's water ripples come and go and its start-line flags flutter (the boats are play, and still sail), and Coconut Shy's bunting flutters and its stallholder shifts and waves (the thrown ball and wobbling coconuts are play, and still move), and Bowls Green's hedge leaves stir and a cloud shadow drifts across its green (the rolling woods are play, and still move); all of it stops under `prefers-reduced-motion`.
9091
9192 ## Empire Age
9293
bowls-green/bowls.js added +116
@@ -0,0 +1,116 @@
1 'use strict';
2 // The bowls green rules: one end of four biased woods against two rival woods already at rest. Metres, seconds, degrees.
3 // x runs across the green (right is positive), y runs from the mat towards the jack. A wood is plain data
4 // { x, y, vx, vy }; `step` moves it by one small time step, `roll` steps it to rest, `throwWood` plays one of the
5 // four. No DOM, no timers, no Math.random: the pace and the bias side of the green come from the seed.
6 (function (root) {
7 const WOODS = 4; // woods in an end
8 const JACK = { x: 0, y: 16 }; // m from the front of the mat
9 const BACK = 20, HALF_WIDTH = 2.6; // the back edge of the green; the ditch lies beyond either side
10 const MAX_SPEED = 6.4; // m/s at full weight
11 const BIAS_RATE = .2, SOFT = .5; // rad/s * (m/s): a bent wood turns at BIAS_RATE / (speed + SOFT) towards its bias side
12 const PACE_MIN = .7, PACE_MAX = .9; // m/s^2 of rolling drag, one constant per game (a fast green is a low number)
13 const LINE_MAX = 15; // degrees either side of straight
14 const DT = .02, MAX_STEPS = 2000; // s per step; a safety cap, no wood rolls for 40 s
15 const RESTING = .03; // m/s: slower than this it is at rest
16 const RIVALS = [{ x: .62, y: 15.35 }, { x: -.5, y: 17.4 }]; // the two rival woods, already resting near the jack
17
18 const finite = v => (Number.isFinite(v) ? v : 0);
19 const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
20 // a repeatable number in [0, 1) for this seed and slot
21 function noise(seed, n) {
22 let h = (Math.imul(finite(seed) | 0, 374761393) + Math.imul(n | 0, 668265263)) | 0;
23 h = Math.imul(h ^ (h >>> 13), 1274126177);
24 return ((h ^ (h >>> 16)) >>> 0) / 4294967296;
25 }
26 const dist = (a, b) => Math.hypot(a.x - b.x, a.y - b.y);
27 const speedOf = w => Math.hypot(w.vx, w.vy);
28
29 // how far a wood of this weight (0..1) travels along its path before it stops: v^2 / (2 pace), so quadratic in weight
30 const reach = pace => MAX_SPEED * MAX_SPEED / (2 * pace);
31 const distanceFor = (weight, pace) => reach(pace) * clamp(finite(weight), 0, 1) ** 2;
32 // the weight that carries a wood this far along its path (inverse of distanceFor), for aim helpers and tests
33 const weightFor = (distance, pace) => clamp(Math.sqrt(Math.max(0, finite(distance)) / reach(pace)), 0, 1);
34
35 // the pure step: a wood, the bias (+1 bends right, -1 bends left), the pace and a time step in, the wood after it out.
36 // It slows by `pace` m/s every second and, while it rolls, its heading turns towards the bias side at
37 // bias * BIAS_RATE / (speed + SOFT) rad/s: the slower it goes the faster it turns, so most of the bend comes late.
38 function step(wood, bias, pace, dt = DT) {
39 const speed = speedOf(wood);
40 if (speed <= RESTING) return { x: wood.x, y: wood.y, vx: 0, vy: 0 };
41 const t = Math.min(dt, speed / pace); // the time left before it stops, if sooner
42 const next = Math.max(0, speed - pace * t);
43 const turn = clamp(finite(bias), -1, 1) * BIAS_RATE / ((speed + next) / 2 + SOFT) * t;
44 const heading = Math.atan2(wood.vx, wood.vy), mid = heading + turn / 2, run = (speed + next) / 2 * t;
45 return { x: wood.x + Math.sin(mid) * run, y: wood.y + Math.cos(mid) * run, vx: Math.sin(heading + turn) * next, vy: Math.cos(heading + turn) * next };
46 }
47 // a wood is dead once it is off the back of the green or over either side into the ditch
48 const isDead = p => p.y > BACK || Math.abs(p.x) > HALF_WIDTH;
49
50 // roll a wood from the front of the mat with this line (degrees from straight, right positive) and weight (0..1)
51 // until it stops or dies; returns where it stopped, whether it is dead, and its path every DT seconds
52 function roll(game, input = {}) {
53 const a = clamp(finite(input.line), -LINE_MAX, LINE_MAX) * Math.PI / 180, v = clamp(finite(input.weight), 0, 1) * MAX_SPEED;
54 let w = { x: 0, y: 0, vx: Math.sin(a) * v, vy: Math.cos(a) * v };
55 const path = [[w.x, w.y]];
56 for (let n = 0; n < MAX_STEPS && speedOf(w) > RESTING; n++) {
57 w = step(w, game.bias, game.pace);
58 path.push([w.x, w.y]);
59 if (isDead(w)) return { x: w.x, y: w.y, dead: true, path };
60 }
61 return { x: w.x, y: w.y, dead: false, path };
62 }
63
64 function newGame(best = 0, seed = 0) {
65 const s = finite(seed) >>> 0;
66 return { phase: 'aim', wood: 1, woods: [], jack: { ...JACK }, rivals: RIVALS.map(r => ({ ...r })), bias: noise(s * 7919 + 13, 1) < .5 ? -1 : 1,
67 pace: PACE_MIN + noise(s * 104729 + 5, 2) * (PACE_MAX - PACE_MIN), best: Math.max(0, finite(best)), count: 0, nearest: null, over: false, outcome: '',
68 line: 'Four woods against two rivals: roll one nearer the jack.', seed: s };
69 }
70 // the player's live woods nearest the jack, as a distance in metres, or null when none is on the green
71 const nearestOf = (s) => {
72 const live = s.woods.filter(w => !w.dead).map(w => dist(w, s.jack));
73 return live.length ? Math.min(...live) : null;
74 };
75 const rivalNearest = s => Math.min(...s.rivals.map(r => dist(r, s.jack)));
76 // the player's woods nearer the jack than the nearest rival wood (a dead wood never counts)
77 const countNearer = s => s.woods.filter(w => !w.dead && dist(w, s.jack) < rivalNearest(s)).length;
78
79 // roll the next wood: returns { state, event }, leaves the state you passed untouched; no event when no wood is left to roll
80 function throwWood(state, input = {}) {
81 if (state.phase !== 'aim' || state.over) return { state, event: null };
82 const res = roll(state, input), s = { ...state, woods: [...state.woods, { x: res.x, y: res.y, dead: res.dead }] };
83 s.nearest = nearestOf(s); s.count = countNearer(s);
84 if (s.woods.length >= WOODS) {
85 s.phase = 'over'; s.over = true; s.wood = WOODS; s.best = Math.max(s.best, s.count);
86 s.outcome = s.count >= 1 ? 'won' : 'lost';
87 s.line = s.count >= 1 ? 'You win: ' + s.count + (s.count === 1 ? ' wood' : ' woods') + ' nearer the jack than the rival' : 'You lose: no wood nearer the jack than the rival';
88 } else {
89 s.wood = s.woods.length + 1;
90 s.line = res.dead ? 'Dead: off the back of the green.' : 'Rested ' + dist(res, s.jack).toFixed(2) + ' m from the jack.';
91 if (res.dead && Math.abs(res.x) > HALF_WIDTH) s.line = 'Dead: into the ditch.';
92 }
93 return { state: s, event: { dead: res.dead, rest: { x: res.x, y: res.y }, path: res.path, distance: dist(res, s.jack), wood: s.woods.length } };
94 }
95 // a fresh end after one has finished (new seed, best kept); null while one is in play
96 const again = state => (state.over ? newGame(state.best, state.seed + 1) : null);
97
98 // the throw, out of the given lines and weights, whose wood comes to rest nearest `target` (default the jack) and alive;
99 // for aim helpers, the scripted round and the tests
100 function bestThrow(state, lines, weights, target = state.jack) {
101 let best = null;
102 for (const line of lines) for (const weight of weights) {
103 const r = roll(state, { line, weight });
104 if (r.dead) continue;
105 const d = dist(r, target);
106 if (!best || d < best.distance) best = { line, weight, distance: d, rest: { x: r.x, y: r.y } };
107 }
108 return best;
109 }
110
111 const api = {
112 WOODS, JACK, BACK, HALF_WIDTH, MAX_SPEED, BIAS_RATE, SOFT, PACE_MIN, PACE_MAX, LINE_MAX, DT, RESTING, RIVALS,
113 reach, distanceFor, weightFor, step, isDead, roll, newGame, throwWood, again, bestThrow, dist, countNearer, rivalNearest, nearestOf,
114 };
115 if (typeof module !== 'undefined') module.exports = api; else root.Bowls = api;
116 })(typeof window !== 'undefined' ? window : globalThis);
bowls-green/bowls.test.mjs added +198
@@ -0,0 +1,198 @@
1 import { test, expect } from 'bun:test';
2 import { WOODS, JACK, BACK, HALF_WIDTH, MAX_SPEED, PACE_MIN, PACE_MAX, LINE_MAX, RIVALS, reach, distanceFor, weightFor, step, roll, newGame, throwWood, again, bestThrow, dist, countNearer, rivalNearest } from './bowls.js';
3
4 const LINES = Array.from({ length: 61 }, (_, i) => (i - 30) * LINE_MAX / 30), WEIGHTS = Array.from({ length: 40 }, (_, i) => (i + 1) / 40);
5 // roll a wood by hand with the pure step only, from a given speed straight ahead, until it stops
6 const run = (bias, pace, speed, wood = { x: 0, y: 0, vx: 0, vy: speed }) => {
7 const trail = [wood];
8 for (let n = 0; n < 5000 && Math.hypot(wood.vx, wood.vy) > 0; n++) { wood = step(wood, bias, pace); trail.push(wood); }
9 return trail;
10 };
11 // the game with a known bias and pace, for tests that must not depend on the seed
12 const green = (bias, pace = .8) => ({ ...newGame(0, 1), bias, pace });
13 // a state with the first `rest` woods already thrown to the given places
14 const withWoods = (s, places) => ({ ...s, woods: places.map(p => ({ ...p, dead: !!p.dead })) });
15
16 test('the pace is a constant of the game: the same seed gives the same green, and every seed is inside the stated range', () => {
17 expect(newGame(0, 5).pace).toBe(newGame(9, 5).pace);
18 expect(newGame(0, 5).bias).toBe(newGame(9, 5).bias);
19 const paces = new Set(), sides = new Set();
20 for (let seed = 0; seed < 40; seed++) {
21 const g = newGame(0, seed);
22 expect(g.pace).toBeGreaterThanOrEqual(PACE_MIN);
23 expect(g.pace).toBeLessThanOrEqual(PACE_MAX);
24 paces.add(g.pace); sides.add(g.bias);
25 }
26 expect(paces.size).toBeGreaterThan(20);
27 expect([...sides].sort()).toEqual([-1, 1]);
28 });
29
30 test('the step is pure: the same wood, bias and pace always give the same next wood, and the wood passed in is untouched', () => {
31 const w = { x: .3, y: 4, vx: .5, vy: 3 }, copy = { ...w };
32 expect(step(w, 1, .8)).toEqual(step(w, 1, .8));
33 expect(w).toEqual(copy);
34 });
35
36 test('a bowl slows by the pace every second and stops dead still', () => {
37 const trail = run(0, .8, 4);
38 expect(Math.hypot(trail[1].vx, trail[1].vy)).toBeCloseTo(4 - .8 * .02, 9);
39 const last = trail.at(-1);
40 expect(last.vx).toBe(0);
41 expect(last.vy).toBe(0);
42 expect(step(last, 1, .8)).toEqual(last); // at rest it stays put
43 });
44
45 test('weight to distance: a straight wood rests v^2 / (2 pace) away, so quadratic in weight, and weightFor inverts it', () => {
46 for (const pace of [PACE_MIN, .8, PACE_MAX]) for (const w of [.3, .5, .8, 1]) {
47 const trail = run(0, pace, w * MAX_SPEED);
48 expect(trail.at(-1).y).toBeCloseTo(distanceFor(w, pace), 2) // to within the last creep below the resting speed;
49 expect(trail.at(-1).x).toBeCloseTo(0, 9);
50 expect(weightFor(distanceFor(w, pace), pace)).toBeCloseTo(w, 9);
51 }
52 expect(distanceFor(1, .8)).toBeCloseTo(reach(.8), 9);
53 expect(distanceFor(.5, .8)).toBeCloseTo(reach(.8) / 4, 9);
54 expect(distanceFor(1, PACE_MIN)).toBeGreaterThan(distanceFor(1, PACE_MAX)); // a faster green (lower drag) runs further
55 expect(distanceFor(NaN, .8)).toBe(0);
56 });
57
58 test('the bias curve: a wood bends towards its bias side, mirror-wise, and bends more the slower it goes', () => {
59 const right = run(1, .8, 5), left = run(-1, .8, 5), none = run(0, .8, 5);
60 expect(right.at(-1).x).toBeGreaterThan(1);
61 expect(left.at(-1).x).toBeCloseTo(-right.at(-1).x, 9);
62 expect(left.at(-1).y).toBeCloseTo(right.at(-1).y, 9);
63 expect(none.at(-1).x).toBe(0);
64 expect(right.every(p => p.x >= 0)).toBe(true); // it never swings away from its bias side
65 // the heading turns by more in a step late in the roll than in a step early in it
66 const turn = (a, b) => Math.abs(Math.atan2(b.vx, b.vy) - Math.atan2(a.vx, a.vy));
67 expect(turn(right[right.length - 20], right[right.length - 19])).toBeGreaterThan(turn(right[1], right[2]) * 3);
68 });
69
70 test('aiming straight at the jack misses it, on the side of the bias, for every seed', () => {
71 for (let seed = 0; seed < 20; seed++) {
72 const g = newGame(0, seed), r = roll(g, { line: 0, weight: weightFor(JACK.y, g.pace) });
73 expect(r.dead).toBe(false);
74 expect(dist(r, JACK)).toBeGreaterThan(1.2);
75 expect(Math.sign(r.x)).toBe(g.bias);
76 }
77 });
78
79 test('aiming off the bias side can bring the wood in to the jack', () => {
80 for (let seed = 0; seed < 20; seed++) {
81 const g = newGame(0, seed), b = bestThrow(g, LINES, WEIGHTS);
82 expect(b.distance).toBeLessThan(.5);
83 expect(Math.sign(b.line)).toBe(-g.bias);
84 }
85 });
86
87 test('a roll lays its path down every step and ends where the wood rests', () => {
88 const g = green(1), r = roll(g, { line: -4, weight: .75 });
89 expect(r.path[0]).toEqual([0, 0]);
90 expect(r.path.at(-1)).toEqual([r.x, r.y]);
91 expect(r.path.length).toBeGreaterThan(100);
92 expect(roll(g, { line: -4, weight: .75 })).toEqual(r); // the same throw rolls the same way
93 });
94
95 test('a wood that runs off the back of the green is dead, and so is one that leaves by the side', () => {
96 const g = green(1);
97 const hard = roll(g, { line: -5, weight: 1 });
98 expect(hard.dead).toBe(true);
99 expect(hard.y).toBeGreaterThan(BACK);
100 expect(roll(g, { line: 0, weight: weightFor(BACK - 1, g.pace) }).dead).toBe(false);
101 expect(roll(g, { line: LINE_MAX, weight: .8 }).dead).toBe(true);
102 expect(roll(g, { line: LINE_MAX, weight: .8 }).x).toBeGreaterThan(HALF_WIDTH);
103 });
104
105 test('the input is clamped: nonsense weight and line never throw, and no weight means a wood that stays on the mat', () => {
106 const g = green(1);
107 expect(roll(g, { line: 400, weight: 9 })).toEqual(roll(g, { line: LINE_MAX, weight: 1 }));
108 expect(roll(g, { line: NaN, weight: NaN })).toMatchObject({ x: 0, y: 0, dead: false });
109 expect(roll(g)).toMatchObject({ x: 0, y: 0 });
110 });
111
112 test('a game is one end of four woods against two resting rival woods', () => {
113 const s = newGame(2, 3);
114 expect(WOODS).toBe(4);
115 expect(s.rivals).toHaveLength(2);
116 expect(s).toMatchObject({ wood: 1, best: 2, count: 0, nearest: null, over: false, phase: 'aim' });
117 let t = s;
118 for (let k = 1; k <= 4; k++) {
119 expect(t.wood).toBe(k);
120 const { state, event } = throwWood(t, { line: 0, weight: .5 });
121 expect(event.wood).toBe(k);
122 t = state;
123 }
124 expect(t.over).toBe(true);
125 expect(t.woods).toHaveLength(4);
126 expect(throwWood(t, { line: 0, weight: .5 }).event).toBeNull();
127 expect(s.woods).toHaveLength(0); // the state passed in was never touched
128 });
129
130 test('the nearest distance to the jack is the best of the live woods; dead woods do not count', () => {
131 let s = green(1);
132 s = throwWood(s, { line: 0, weight: .4 }).state;
133 const first = s.nearest;
134 expect(first).toBeCloseTo(dist(s.woods[0], JACK), 9);
135 s = throwWood(s, { line: -5, weight: 1 }).state; // runs off the back
136 expect(s.woods[1].dead).toBe(true);
137 expect(s.nearest).toBe(first);
138 expect(s.line).toMatch(/dead/i);
139 });
140
141 test('the rival woods can be beaten: from a scripted line and weight the wood rests nearer the jack than both', () => {
142 expect(rivalNearest(newGame())).toBeGreaterThan(.5); // not on the jack: there is room to beat them
143 for (let seed = 0; seed < 20; seed++) {
144 const g = newGame(0, seed), b = bestThrow(g, LINES, WEIGHTS);
145 const { state, event } = throwWood(g, { line: b.line, weight: b.weight });
146 expect(event.dead).toBe(false);
147 expect(event.distance).toBeLessThan(rivalNearest(g));
148 expect(state.count).toBe(1);
149 }
150 });
151
152 test('the count is the player\'s woods nearer the jack than the nearest rival wood', () => {
153 const s = newGame(), near = rivalNearest(s);
154 expect(near).toBeCloseTo(Math.min(...RIVALS.map(r => dist(r, JACK))), 9);
155 const at = d => ({ x: JACK.x, y: JACK.y + d });
156 expect(countNearer(withWoods(s, [at(near - .1), at(near - .2), at(near + .1), at(near + .5)]))).toBe(2);
157 expect(countNearer(withWoods(s, [at(near + .1)]))).toBe(0);
158 expect(countNearer(withWoods(s, [RIVALS.reduce((a, b) => dist(a, JACK) < dist(b, JACK) ? a : b)]))).toBe(0); // level with the rival is not nearer
159 expect(countNearer(withWoods(s, [{ ...at(.1), dead: true }]))).toBe(0); // a dead wood never counts
160 expect(countNearer(withWoods(s, [at(.1), at(.2), at(.3), at(.4)]))).toBe(4);
161 });
162
163 test('one wood or more nearer the jack wins the end, with the count in the win line', () => {
164 let s = newGame(0, 2);
165 const b = bestThrow(s, LINES, WEIGHTS);
166 s = throwWood(s, { line: b.line, weight: b.weight }).state;
167 for (let k = 1; k < 4; k++) s = throwWood(s, { line: 0, weight: .1 }).state; // three short ones that count for nothing
168 expect(s.over).toBe(true);
169 expect(s.count).toBe(1);
170 expect(s.outcome).toBe('won');
171 expect(s.line).toBe('You win: 1 wood nearer the jack than the rival');
172 expect(s.best).toBe(1);
173 // two nearer: plural
174 let t = newGame(0, 2);
175 for (let k = 0; k < 4; k++) t = throwWood(t, k < 2 ? { line: b.line, weight: b.weight } : { line: 0, weight: .1 }).state;
176 expect(t.count).toBe(2);
177 expect(t.line).toBe('You win: 2 woods nearer the jack than the rival');
178 });
179
180 test('no wood nearer than the rivals loses the end, whether short, wide or dead', () => {
181 let s = newGame(5, 2);
182 for (let k = 0; k < 4; k++) s = throwWood(s, [{ line: 0, weight: .3 }, { line: 0, weight: 1 }, { line: 12, weight: .8 }, { line: 0, weight: weightFor(JACK.y, s.pace) }][k]).state;
183 expect(s.count).toBe(0);
184 expect(s.outcome).toBe('lost');
185 expect(s.line).toBe('You lose: no wood nearer the jack than the rival');
186 expect(s.best).toBe(5); // the best is kept, and a loss does not lower it
187 });
188
189 test('the best is the most woods beaten the rivals in an end, and a new end keeps it', () => {
190 let s = newGame(3, 1);
191 for (let k = 0; k < 4; k++) s = throwWood(s, { line: 0, weight: .1 }).state;
192 expect(s.best).toBe(3);
193 expect(again(newGame())).toBeNull(); // not while one is in play
194 const next = again(s);
195 expect(next.best).toBe(3);
196 expect(next.woods).toHaveLength(0);
197 expect(next.seed).toBe(s.seed + 1);
198 });
bowls-green/index.html added +350
@@ -0,0 +1,350 @@
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>Bowls Green</title>
7 <!-- og:begin -->
8 <meta name="description" content="Drag back to set line and weight and curve your woods in close to the jack">
9 <link rel="canonical" href="https://pixel-plays--forge-trevato-apps.open-platform.sh/bowls-green/">
10 <meta property="og:type" content="website">
11 <meta property="og:site_name" content="Pixel Plays">
12 <meta property="og:title" content="Bowls Green">
13 <meta property="og:description" content="Drag back to set line and weight and curve your woods in close to the jack">
14 <meta property="og:url" content="https://pixel-plays--forge-trevato-apps.open-platform.sh/bowls-green/">
15 <meta property="og:image" content="https://pixel-plays--forge-trevato-apps.open-platform.sh/og/bowls-green.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="Bowls Green: 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: #6b675f; --paper: #fff; --accent: #4f7f3f; }
24 * { box-sizing: border-box; }
25 html, body { -webkit-user-select: none; user-select: none; -webkit-touch-callout: none; -webkit-tap-highlight-color: transparent; height: 100%; margin: 0; background: var(--paper); color: var(--ink); }
26 body { font: 13px/1.35 ui-monospace, "Cascadia Mono", Consolas, Menlo, monospace; overflow: hidden; }
27 #stage { position: fixed; inset: 0; display: grid; place-items: center; }
28 canvas { display: block; image-rendering: pixelated; touch-action: none; cursor: pointer; }
29 canvas:focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; }
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 #power { width: 72px; height: 4px; margin-top: 4px; background: rgba(79, 127, 63, .18); }
37 #power i { display: block; height: 100%; background: var(--accent); transform-origin: left; transform: scaleX(0); }
38 #line { color: var(--muted); min-height: 1.35em; }
39 button { pointer-events: auto; font: inherit; color: var(--muted); background: none; border: 0; padding: 10px; margin: -10px; cursor: pointer; }
40 button:hover, button:focus-visible { color: var(--ink); }
41 button:focus-visible { outline: 2px solid var(--accent); }
42 noscript p { position: fixed; z-index: 3; inset: 40px 0 auto; margin: 0; padding: 12px 16px; background: var(--paper); }
43 </style>
44 </head>
45 <body>
46 <noscript>
47 <p>Bowls Green needs JavaScript. It is one end of lawn bowls: roll four biased woods from the mat towards the white jack, against two rival woods already at rest; each wood curves towards its bias side as it slows, so aim off the jack. One or more woods nearer the jack than the nearest rival wood wins.</p>
48 </noscript>
49 <div id="stage"><canvas id="c" tabindex="0" aria-label="A lawn bowls green: a white jack at the far end, a mat at the near end, two rival woods already resting near the jack and a low hedge behind. Drag back from the mat and release to roll, or press Left and Right to set the line, hold Space to build weight and release it to roll. Your woods curve towards their bias side as they slow, so aim off the jack. Four woods; one or more resting nearer the jack than the nearest rival wood wins."></canvas></div>
50 <div id="scores">
51 <div class="row"><b id="wood">1</b><span>of 4 woods</span></div>
52 <div class="row"><b id="nearest">–</b><span>m, nearest the jack</span></div>
53 <div class="row"><b id="best">0</b><span>best, woods nearer</span></div>
54 <div class="row"><span id="aimed"></span></div>
55 <div id="power"><i></i></div>
56 </div>
57 <div class="hud" id="bottom">
58 <div id="line"><span id="status" role="status" aria-live="polite"></span></div>
59 <button id="mute" type="button" aria-pressed="false">sound on</button>
60 </div>
61 <script src="../shell.js"></script>
62 <script>
63 PixelPlays.mount({
64 id: 'bowls-green',
65 rules: [
66 'Drag back from the mat and release to roll, or Left and Right for the line and hold Space for weight.',
67 'Four woods. Each curves towards its bias side as it slows, so aim off the jack. Off the back is dead.',
68 'One or more woods nearer the jack than the nearest rival wood wins the end.',
69 ],
70 });
71 </script>
72 <script>window.PP_SCENE = { originY: 6, shadowX: 1.3, shadowY: -.12 };</script>
73 <script src="../engine.js"></script>
74 <script src="bowls.js"></script>
75 <script>
76 'use strict';
77
78 const BEST_KEY = 'pixel-plays-bowls-green-best';
79 const WEIGHT_TIME = 1.6, PULL = 100, KEY_STEP = .5, PLAYBACK = 2; // seconds to full weight; canvas pixels to full weight; degrees per key press; a roll plays at twice its speed
80 const SC = 1.4, OFF = 13.3, EDGE_NEAR = -1.5, EDGE_FAR = 20.5, GREEN_HALF = 4.2; // metres to world; world shift along the green; the lawn's ends and half width in metres
81 const HEDGE_Y = 20.8, HEDGE_H = 1.5, WOOD_R = .3, JACK_R = .18;
82 const LAWN = [[122, 156, 70], [112, 148, 66]], DITCH = [[86, 112, 58], [78, 104, 54]];
83 const RUBBER = [58, 56, 54], CHALK = [250, 246, 236];
84 const HEDGE = [44, 82, 52], LEAF = [96, 138, 64], LEAF_LIGHT = [132, 168, 80];
85 const MINE = [60, 104, 176], RIVAL = [190, 62, 52], JACK_C = [250, 248, 240];
86 const lawn = [0, 1].map(k => rampOf(LAWN[k]));
87 const KEY_AIM = { ArrowLeft: -1, ArrowDown: -1, a: -1, A: -1, ArrowRight: 1, ArrowUp: 1, d: 1, D: 1 };
88 const at = (lat, fwd, z = 0) => [fwd * SC - OFF, lat * SC, z]; // the rules' (across, along) to the engine's world
89 const SIDE = b => b > 0 ? 'right' : 'left';
90
91 /* ---------- state: what the page itself keeps; every rule is in Bowls ---------- */
92 const best0 = (() => { try { return Number(localStorage.getItem(BEST_KEY)) || 0; } catch (e) { return 0; } })();
93 let R = Bowls.newGame(best0, (Math.random() * 1e9) | 0);
94 const G = { time: 0, status: '', line: 0, held: 0, charging: false, pull: null, drag: null, flight: null, pending: null, settle: 9, rested: [] };
95 const nodes = {};
96 for (const id of ['wood', 'nearest', 'best', 'status', 'aimed']) nodes[id] = document.getElementById(id);
97 nodes.power = document.querySelector('#power i');
98 const weightNow = () => G.pull ? G.pull.weight : G.charging ? clamp(G.held / WEIGHT_TIME, 0, 1) : 0;
99 function renderHud() {
100 nodes.wood.textContent = R.wood;
101 nodes.nearest.textContent = R.nearest == null ? '–' : R.nearest.toFixed(2);
102 nodes.best.textContent = R.best;
103 nodes.aimed.textContent = 'line ' + (G.line > 0 ? 'right ' : G.line < 0 ? 'left ' : '') + Math.abs(G.line).toFixed(1) + '° · bends ' + SIDE(R.bias);
104 }
105 function setStatus(text) {
106 if (text === G.status) return;
107 G.status = text;
108 nodes.status.textContent = text;
109 }
110 const tail = () => R.over ? ' · tap or press space to play again' : '';
111 const HINT = 'drag back from the mat and release, or Left and Right, hold space, release';
112
113 /* ---------- baked scene: the lawn, the mat, the hedge ---------- */
114 function groundColor(x, y, ix, iy) {
115 const fwd = (x + OFF) / SC, lat = y / SC;
116 const mid = (EDGE_FAR + EDGE_NEAR) / 2, half = (EDGE_FAR - EDGE_NEAR) / 2;
117 const rough = Math.max(Math.abs(fwd - mid) / half, Math.abs(lat) / GREEN_HALF) + (noise(x * 1.1, y * 1.1) - .5) * .1;
118 if (rough > 1.06) return 0;
119 if (rough > .95 && hash(ix, iy) < (rough - .95) / .11) return 0;
120 if (fwd > -1.2 && fwd < 0 && Math.abs(lat) < .45) return rgb(...RUBBER);
121 if (Math.abs(fwd - 20) < .08 && Math.abs(lat) < 2.6) return rgb(...CHALK);
122 const band = Math.floor((fwd + 2) / 2) & 1, ditch = Math.abs(lat) > 2.6 && Math.abs(lat) < 3.1;
123 const ramp = ditch ? rampOf(DITCH[band]) : lawn[band];
124 return ramp[clamp(Math.floor(2.2 - band * .5 + (noise(x * .6, y * .6) - .5) * .5 + (bayerAt(ix, iy) - .5) * .5), 1, 3)];
125 }
126 function hedge() {
127 const [x0, y0] = at(-4.4, HEDGE_Y), [x1, y1] = at(4.4, HEDGE_Y + 1.1);
128 box(x0, y0, 0, x1, y1, HEDGE_H, HEDGE, 5);
129 for (let y = y0 + .1; y < y1; y += .45) for (let z = .2; z < HEDGE_H + .1; z += .45) sphere(x1 - .05, y, z, .3, LEAF, 'rough');
130 for (let y = y0; y <= y1; y += .5) for (let z = 0; z < HEDGE_H; z += .4) castShadow(x0, y, z, .5, 1, 0);
131 }
132 function bake() {
133 ground.fill(0); shadowMask.fill(0); staticShadow.fill(0);
134 zb.fill(-1e9);
135 pix.fill(rgb(255, 255, 255));
136 for (let iy = 0; iy < H; iy++) for (let ix = 0; ix < W; ix++) {
137 const g = unproject(ix + .5, iy + .5), i = iy * W + ix, c = groundColor(g.x, g.y, ix, iy);
138 if (!c) continue;
139 pix[i] = c; ground[i] = 1;
140 zb[i] = (g.x + g.y) / R2 * COS;
141 }
142 groundZ.set(zb);
143 hedge();
144 bakeOcclusion();
145 staticShadow.set(shadowMask);
146 applyShadows(groundZ);
147 bakedPix.set(pix);
148 bakedZ.set(zb);
149 }
150
151 /* ---------- ambient: a cloud shadow drifts over the green, and only the hedge leaves stir ---------- */
152 function cloud() {
153 const t = STILL ? 0 : Math.floor(G.time * 8) / 8, cx = ((Math.round(t * 6) + 120) % 520) - 100, cy = 150 - Math.round(t * 2) % 40, rx = 70, ry = 26;
154 for (let iy = Math.max(0, cy - ry); iy < Math.min(H, cy + ry); iy++) for (let ix = Math.max(0, cx - rx); ix < Math.min(W, cx + rx); ix++) {
155 const i = iy * W + ix;
156 if (!ground[i]) continue;
157 const dx = (ix - cx) / rx, dy = (iy - cy) / ry;
158 if (dx * dx + dy * dy + (bayerAt(ix, iy) - .5) * .5 > 1) continue;
159 const c = pix[i];
160 pix[i] = rgb((c & 255) * .88, (c >> 8 & 255) * .9, (c >> 16 & 255) * .96);
161 }
162 }
163 function stir() {
164 const t = STILL ? 0 : Math.floor(G.time * 8) / 8, [x] = at(0, HEDGE_Y + 1.1);
165 for (let k = 0, y = -4.3 * SC; y < 4.4 * SC; y += .5, k++) {
166 const sway = Math.round(Math.sin(t * 2.4 + k * 1.3) * 1.5) * .06;
167 sphere(x - .02, y + sway, HEDGE_H + .1 + (k & 1) * .15, .22, k % 3 ? LEAF_LIGHT : LEAF, 'rough');
168 }
169 }
170
171 /* ---------- figures ---------- */
172 function wood(lat, fwd, colour, mark) {
173 const [x, y] = at(lat, fwd);
174 sphere(x, y, WOOD_R, WOOD_R, colour, 'gloss');
175 sphere(x - .1, y - .02 + mark * .1, WOOD_R + .12, .07, [250, 248, 240], 'solid');
176 castShadow(x, y, WOOD_R, WOOD_R, 1, 0);
177 }
178 function jack() {
179 const [x, y] = at(R.jack.x, R.jack.y);
180 sphere(x, y, JACK_R, JACK_R, JACK_C, 'gloss');
181 castShadow(x, y, JACK_R, JACK_R, 1, 0);
182 }
183 function flightAt() {
184 const f = G.flight;
185 if (!f) return null;
186 const i = Math.min(f.path.length - 1, Math.floor(f.i)), p = f.path[i], q = f.path[Math.min(f.path.length - 1, i + 1)], u = f.i - i;
187 return [p[0] + (q[0] - p[0]) * u, p[1] + (q[1] - p[1]) * u];
188 }
189 function aimDots() {
190 const a = G.line * Math.PI / 180, w = weightNow(), pts = [], len = 1.5 + w * 7;
191 for (let k = 1; k <= 8; k++) {
192 const s = len * k / 8, [x, y, z] = at(Math.sin(a) * s, Math.cos(a) * s, .03), q = project(x, y, z);
193 pts.push([q.sx, q.sy]);
194 }
195 drawDots(pts, SIGNAL);
196 }
197 function draw() {
198 pix.set(bakedPix);
199 zb.set(bakedZ);
200 pendingShadows.length = 0;
201 cloud();
202 stir();
203 jack();
204 R.rivals.forEach((r, i) => wood(r.x, r.y, RIVAL, i ? -1 : 1));
205 R.woods.forEach(w => { if (!w.dead) wood(w.x, w.y, MINE, R.bias); });
206 const flying = flightAt();
207 if (flying) wood(flying[0], flying[1], MINE, R.bias);
208 else if (!R.over) wood(0, -.6, MINE, R.bias);
209 flushShadows();
210 applyShadows(bakedZ);
211 shadeEdges();
212 if (!G.flight && !R.over) aimDots();
213 ctx.putImageData(image, 0, 0);
214 }
215
216 /* ---------- game: the page turns input into Bowls.throwWood and shows what the rules answer ---------- */
217 function release(weight, line) {
218 const res = Bowls.throwWood(R, { weight, line });
219 if (!res.event) return;
220 G.pending = res;
221 G.flight = { path: res.event.path, i: 0 };
222 G.charging = false; G.held = 0; G.pull = null; G.drag = null;
223 setStatus('');
224 sound('roll', weight);
225 }
226 function land() {
227 const { state, event } = G.pending, was = R;
228 G.pending = null; G.flight = null; G.settle = 0;
229 R = state;
230 sound(event.dead ? 'dead' : 'rest');
231 if (R.over) {
232 if (R.best > was.best) try { localStorage.setItem(BEST_KEY, String(R.best)); } catch (err) { /* private window: the best lives for this visit */ }
233 sound(R.outcome === 'won' ? 'win' : 'dead');
234 }
235 setStatus(R.line + tail());
236 renderHud();
237 }
238 function advance() { // a tap after the end: the rules say what comes next
239 const next = R.over ? Bowls.again(R) : null;
240 if (!next) return false;
241 if (G.settle < .5) return true;
242 R = next; G.line = 0;
243 setStatus(R.line + ' · ' + HINT);
244 renderHud();
245 return true;
246 }
247 function update(dt) {
248 G.time += dt;
249 G.settle += dt;
250 if (G.charging) G.held += dt;
251 if (G.flight) { G.flight.i += dt / Bowls.DT * PLAYBACK; if (G.flight.i >= G.flight.path.length - 1) land(); }
252 nodes.power.style.transform = 'scaleX(' + weightNow() + ')';
253 }
254
255 /* ---------- input ---------- */
256 const busy = () => !!G.flight || G.settle < .35;
257 const FWD = [.894, .447], ACROSS = [-.894, .447]; // the green's two axes on the screen: along it, and to the bowler's right
258 function pullTo(e) {
259 const r = canvas.getBoundingClientRect(), x = (e.clientX - r.left) / (r.width || W) * W, y = (e.clientY - r.top) / (r.height || H) * H;
260 const dx = x - G.drag.x, dy = y - G.drag.y;
261 G.line = clamp(Math.round(-(dx * ACROSS[0] + dy * ACROSS[1]) * .5) / 2, -Bowls.LINE_MAX, Bowls.LINE_MAX); // pull towards the bowler's right, roll to the left
262 G.pull = { weight: clamp(-(dx * FWD[0] + dy * FWD[1]) / PULL, 0, 1) };
263 renderHud();
264 }
265 canvas.addEventListener('pointerdown', e => {
266 ensureAudio();
267 canvas.focus({ preventScroll: true });
268 if (advance() || busy() || R.over) return;
269 const r = canvas.getBoundingClientRect();
270 G.drag = { id: e.pointerId, x: (e.clientX - r.left) / (r.width || W) * W, y: (e.clientY - r.top) / (r.height || H) * H };
271 try { canvas.setPointerCapture(e.pointerId); } catch (err) { /* synthetic pointers have nothing to capture */ }
272 G.pull = { weight: 0 };
273 });
274 canvas.addEventListener('pointermove', e => { if (G.drag && G.drag.id === e.pointerId) pullTo(e); });
275 canvas.addEventListener('pointerup', e => {
276 if (!G.drag || G.drag.id !== e.pointerId) return;
277 pullTo(e);
278 const weight = G.pull.weight;
279 G.drag = null; G.pull = null;
280 if (weight >= .05) release(weight, G.line);
281 });
282 canvas.addEventListener('pointercancel', () => { G.drag = null; G.pull = null; });
283 canvas.addEventListener('keydown', e => {
284 const k = KEY_AIM[e.key];
285 if (!k && e.key !== ' ' && e.key !== 'Enter') return;
286 e.preventDefault();
287 ensureAudio();
288 if (k) { if (!busy() && !R.over) G.line = clamp(G.line + k * KEY_STEP, -Bowls.LINE_MAX, Bowls.LINE_MAX); renderHud(); return; }
289 if (e.repeat) return;
290 if (advance() || busy() || R.over) return;
291 G.charging = true; G.held = 0; G.drag = null; G.pull = null;
292 });
293 canvas.addEventListener('keyup', e => {
294 if (e.key !== ' ' && e.key !== 'Enter') return;
295 if (!G.charging) return;
296 const weight = clamp(G.held / WEIGHT_TIME, 0, 1);
297 G.charging = false; G.held = 0;
298 if (weight >= .05) release(weight, G.line);
299 });
300 canvas.addEventListener('blur', () => { G.charging = false; G.held = 0; G.drag = null; G.pull = null; });
301
302 /* ---------- sound ---------- */
303 let audio = null, muted = false;
304 function ensureAudio() {
305 if (audio) { if (audio.state === 'suspended') audio.resume(); return; }
306 const AC = window.AudioContext || window.webkitAudioContext;
307 if (AC) audio = new AC();
308 }
309 function sound(kind, n = 0) {
310 if (!audio || muted) return;
311 const now = audio.currentTime, gain = audio.createGain(), osc = audio.createOscillator();
312 const spec = {
313 roll: [120 + n * 100, 90, .3, .04, 'triangle'],
314 rest: [320, 240, .1, .06, 'sine'],
315 dead: [180, 70, .25, .07, 'sine'],
316 win: [520, 1040, .3, .07, 'triangle'],
317 }[kind];
318 osc.type = spec[4];
319 osc.frequency.setValueAtTime(spec[0], now);
320 osc.frequency.exponentialRampToValueAtTime(spec[1], now + spec[2]);
321 gain.gain.setValueAtTime(spec[3], now);
322 gain.gain.exponentialRampToValueAtTime(.0005, now + spec[2]);
323 osc.connect(gain).connect(audio.destination);
324 osc.start(now); osc.stop(now + spec[2] + .01);
325 }
326 const muteButton = document.getElementById('mute');
327 muteButton.addEventListener('click', () => {
328 muted = !muted;
329 muteButton.textContent = muted ? 'sound off' : 'sound on';
330 muteButton.setAttribute('aria-pressed', String(muted));
331 });
332
333 /* ---------- fit and boot ---------- */
334 addEventListener('resize', fit);
335 fit();
336 bake();
337 setStatus(R.line + ' · ' + HINT);
338 renderHud();
339 canvas.focus({ preventScroll: true });
340 let last = performance.now();
341 function frame(now) {
342 update(Math.min(.04, (now - last) / 1000));
343 last = now;
344 draw();
345 requestAnimationFrame(frame);
346 }
347 requestAnimationFrame(frame);
348 </script>
349 </body>
350 </html>
index.html +1
@@ -96,6 +96,7 @@ footer a::after { content: none; }
9696 <li data-kind="Catching" data-input="Tap" style="--accent:#c9b43a"><a href="firefly-jar/">Firefly Jar</a><span>Tap the fireflies into a jar while they glow, a dim one flies off, shoo the moths before they reach the lantern</span><span>Game forged by the crew</span><span class="tags">Catching · Tap</span></li>
9797 <li data-kind="Catching" data-input="Drag" style="--accent:#d08a2e"><a href="egg-basket/">Egg Basket</a><span>Slide the basket under the eave and catch the eggs before three crack</span><span>Game forged by the crew</span><span class="tags">Catching · Drag</span></li>
9898 <li data-kind="Throwing" data-input="Drag" style="--accent:#7a4a2a"><a href="coconut-shy/">Coconut Shy</a><span>Drag and release to knock the coconuts off their posts, five balls a round</span><span>Game forged by the crew</span><span class="tags">Throwing · Drag</span></li>
99 <li data-kind="Sport" data-input="Drag" style="--accent:#4f7f3f"><a href="bowls-green/">Bowls Green</a><span>Drag back to set line and weight and curve your woods in close to the jack</span><span>Game forged by the crew</span><span class="tags">Sport · Drag</span></li>
99100 <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>
100101 <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>
101102 <li data-kind="Precision" data-input="Hold" style="--accent:#d0453c"><a href="hot-air-balloon/">Hot Air Balloon</a><span>Five flights over the farms: hold the burner to climb into a different wind, land on the cross for 5</span><span>Game forged by the crew</span><span class="tags">Precision · Hold</span></li>
og/bowls-green.png added
Binary file not shown.
og/home.png
Binary file not shown.
rounds.mjs +13
@@ -2,6 +2,7 @@
22 // repeated until the game says the round is over. `over` matches the line the player reads at the end.
33 import { boot } from './playtest.mjs';
44 import { powerFor, MAX_SPEED, GRAVITY } from './coconut-shy/shy.js';
5 import { bestThrow, LINE_MAX } from './bowls-green/bowls.js';
56
67 const MID = [180, 140];
78 const tapping = (wait = .3) => g => { g.tap(...MID); g.run(wait); };
@@ -32,6 +33,18 @@ export const ROUNDS = {
3233 g.keyUp(' ');
3334 g.run(2);
3435 } },
36 // find the line and weight whose wood rests nearest the jack (lines in half degrees, weights in whole frames of the 1.6 s hold), set the line, hold Space and let go
37 'bowls-green': { over: /play again/, outcome: /You win: \d+ woods? nearer/, beat: g => {
38 if (g.read('R.over')) { g.press(' ', .6); return; }
39 if (g.read('busy()')) { g.run(.5); return; }
40 const lines = Array.from({ length: LINE_MAX * 4 + 1 }, (_, i) => i / 2 - LINE_MAX), weights = Array.from({ length: 40 }, (_, i) => (i + 1) / 40);
41 const t = bestThrow(g.read('R'), lines, weights);
42 for (let n = Math.round((t.line - g.read('G.line')) * 2); n !== 0; n -= Math.sign(n)) g.press(n < 0 ? 'ArrowLeft' : 'ArrowRight', .04);
43 g.keyDown(' ');
44 g.step(Math.round(t.weight * 40));
45 g.keyUp(' ');
46 g.run(1);
47 } },
3548 // hold the sail at half the angle to the wind, which is what drives the boat best
3649 'dinghy-race': { over: /play again|race again/, outcome: /(First|Second) place in \d+\.\d s: a win/, beat: g => {
3750 const x = 30 + g.read('Dinghy.bestSail(Dinghy.windAngle(R.heading, R.wind))') / 90 * 300;
serve.test.mjs +7
@@ -437,6 +437,13 @@ test('Coconut Shy and its rules script are served without a track', async () =>
437437 expect((await fetch(base + '/coconut-shy/shy.js')).status).toBe(200);
438438 });
439439
440 test('Bowls Green and its rules script are served without a track', async () => {
441 const page = await fetch(base + '/bowls-green/');
442 expect(page.status).toBe(200);
443 expect(page.headers.get('content-type')).toBe('text/html; charset=utf-8');
444 expect((await fetch(base + '/bowls-green/bowls.js')).status).toBe(200);
445 });
446
440447 test('Dinghy Race and its rules script are served without a track', async () => {
441448 const page = await fetch(base + '/dinghy-race/');
442449 expect(page.status).toBe(200);
shell.js +1
@@ -40,6 +40,7 @@ window.PixelPlays = (() => {
4040 { 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 },
4141 { id: 'egg-basket', title: 'Egg Basket', blurb: 'Slide the basket under the eave and catch the eggs before three crack', kind: 'Catching', input: 'Drag', accent: '#d08a2e', music: false, forged: true },
4242 { id: 'coconut-shy', title: 'Coconut Shy', blurb: 'Drag and release to knock the coconuts off their posts, five balls a round', kind: 'Throwing', input: 'Drag', accent: '#7a4a2a', music: false, forged: true },
43 { id: 'bowls-green', title: 'Bowls Green', blurb: 'Drag back to set line and weight and curve your woods in close to the jack', kind: 'Sport', input: 'Drag', accent: '#4f7f3f', music: false, forged: true },
4344 { 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 },
4445 { 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 },
4546 { id: 'hot-air-balloon', title: 'Hot Air Balloon', blurb: 'Five flights over the farms: hold the burner to climb into a different wind, land on the cross for 5', kind: 'Precision', input: 'Hold', accent: '#d0453c', music: false, forged: true },

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs