A town simulation in pale isometric line art, implemented with Ritmo ECS and PixiJs 3D
Pace the guide, limit shares, move the system bar up, and set ore apart
SandroMaglionebb757d771be8
diff --git a/DEVELOPMENT.md b/DEVELOPMENT.mdindex 6b56ff1..d2f3e1c 100644--- a/DEVELOPMENT.md+++ b/DEVELOPMENT.md@@ -264,7 +264,7 @@ pnpm balance -- --snapshot 40 # save each seed's town at minut## Sharing a town-**share** (bottom right, and on the reckoning) draws the town as the camera+**share** (top right, and on the reckoning) draws the town as the camerasees it into a 1200 × 630 card (at 2×), with the term's state and numbers on astrip of paper. **Save the picture** downloads it; on a phone it goes to theshare sheet instead. **Make a link** uploads the town (its save file, gzipped,@@ -286,7 +286,12 @@ and `towns/<id>.picture`:The Worker runs only for `/t/*` and `/api/*`; everything else is a staticfile, served free and unmetered. Shares are deleted after 180 days by a-lifecycle rule on the bucket. Under `pnpm dev` the same routes run in Vite+lifecycle rule on the bucket. Uploads are limited per visitor, by a hash of+their IP: 3 a minute through Cloudflare's rate-limit binding (`SHARE_BURST`,+declared in `deploy/alchemy.run.ts`; no resource behind it), and 20 a day+counted in the same bucket under `limits/<day>/<visitor>`, which a second+lifecycle rule clears after a day. Either answers 429 with a line the page+shows. Under `pnpm dev` the same routes run in Viteover a bucket in memory (shares last until the server stops), so sharingworks locally and `pnpm check:browser` checks it end to end.diff --git a/deploy/alchemy.run.ts b/deploy/alchemy.run.tsindex a2ee785..f9e7e5f 100644--- a/deploy/alchemy.run.ts+++ b/deploy/alchemy.run.ts@@ -29,14 +29,22 @@ export default Alchemy.Stack(id: "forget-old-shares",prefix: "towns/",deleteObjectsTransition: { condition: { type: "Age", maxAge: 60 * 60 * 24 * SHARE_DAYS } }+ },+ {+ // Each visitor's count of shares today (see DAILY_SHARES in src/server/handler.ts).+ id: "forget-daily-limits",+ prefix: "limits/",+ deleteObjectsTransition: { condition: { type: "Age", maxAge: 60 * 60 * 24 } }}]})+ // A few shares a minute from one visitor: a Worker binding, with nothing behind it to create or pay for.+ const burst = Cloudflare.RateLimit("SHARE_BURST", { namespaceId: 1001, simple: { limit: 3, period: 60 } })const game = yield* Cloudflare.Website.Vite("Game", {rootDir,// The Worker answers only shared towns; every other path is a static file, served without it.main: "src/server/worker.ts",- env: { SHARES: shares },+ env: { SHARES: shares, SHARE_BURST: burst },assets: { runWorkerFirst: ["/t/*", "/api/*"] },...(stage === "prod" ? { domain: productionDomain } : {})})diff --git a/docs/how-to-play.md b/docs/how-to-play.mdindex 6ff5de9..ce110f2 100644--- a/docs/how-to-play.md+++ b/docs/how-to-play.md@@ -27,7 +27,7 @@ town, the levers you hold, how a term ends, and how the town works underneath.| **1**, **2**, **3** | run at 1×, 2×, 4× || **Esc** | stop placing, close the panel |-Save, load, and new town sit in the bottom right. The town also autosaves+Share, the guide, save, load, and new town sit in the top right, beside the people. The town also autosavesevery two minutes of game time, and **load** takes whichever save is newer.New town and load ask before they replace the town you have.@@ -159,7 +159,7 @@ citizens, and last the crown, trade, and taxes. Each building it names is achip that starts placing one, and "show me where" goes to the water, woods,or rocks it means. A step is put away for good once the town has done it(shown or not), or when the ✕ skips it; *hide guide* turns it off, and the-**guide** button in the bottom right turns it back on. The guide is saved+**guide** button in the top right turns it back on. The guide is savedwith the town, and starts over with a new one.## Wear, spoilage, and wintersdiff --git a/src/asset-lab/assets.ts b/src/asset-lab/assets.tsindex adbf799..b1729b8 100644--- a/src/asset-lab/assets.ts+++ b/src/asset-lab/assets.ts@@ -138,6 +138,7 @@ for (const type of ["fir", "broadleaf", "poplar"] as const)additional.push(makeTree(type, grown, `${type}-${grown === 1 ? "grown" : grown >= 0.5 ? "young" : "sapling"}`))}for (const ore of [false, true]) for (const full of [false, true]) additional.push(makeRock(ore, full))+for (const ore of [false, true]) for (const [w, h] of [[2, 1], [2, 2], [3, 3]] as const) additional.push(makeRock(ore, true, 0, w, h))for (const stage of [0, 1, 2, 3] as const) additional.push(makeField(stage))additional.push(makeRoadPatch(), makeWater(), ...personCatalogue()){diff --git a/src/asset-lab/land.ts b/src/asset-lab/land.tsindex 4a6aeb8..fee6743 100644--- a/src/asset-lab/land.ts+++ b/src/asset-lab/land.ts@@ -135,9 +135,14 @@ export function makeTree(}/** Layered angular rock, shared by natural deposits and the quarry face. */+/** Stone is pale and rounded; ore is dark slate, with rust-red veins and sharp shards, so the two read apart at a glance. */+const stoneColors = { top: 0xeeefe8, left: 0xdcded4, right: 0xc1c7b9 }+const oreColors = { top: 0xa9aebb, left: 0x8d93a3, right: 0x737a8c }+const RUST = 0xc7825c+export function rockOutcrop(d: Drawing, u: number, v: number, radius: number, height: number, ore: boolean, variant = 0) {const start=d.asset.faces.length,n=7, turn=variant*0.29- const colors=ore?{top:0xe0e5ed,left:0xc6ceda,right:0xa9b5c7}:{top:0xeeefe8,left:0xdcded4,right:0xc1c7b9}+ const colors=ore?oreColors:stoneColorsconst ring=(scale:number,z:number,layer:number)=>Array.from({length:n},(_,i):Vertex=>{const t=i*Math.PI*2/n+turn,rough=0.66+hash(i+variant*7,variant+3)*0.34const shift=layer===3?-radius*0.17:0@@ -146,7 +151,7 @@ export function rockOutcrop(d: Drawing, u: number, v: number, radius: number, heconst rings=[ring(1,0,0),ring(0.95,height*0.32,1),ring(0.78,height*0.65,2),ring(0.51,height,3)]for(let j=0;j<3;j++)for(let i=0;i<n;i++){const a=rings[j]![i]!,b=rings[j]![(i+1)%n]!,c=rings[j+1]![(i+1)%n]!,e=rings[j+1]![i]!- d.face([a,b,c,e],i<4?colors.right:colors.left,0)+ d.face([a,b,c,e],ore&&j===1&&(i+variant)%5===0?RUST:i<4?colors.right:colors.left,0)}const summit:Vertex=[u-radius*0.19,v+radius*0.09,height*1.06]for(let i=0;i<n;i++)d.face([rings[3]![i]!,rings[3]![(i+1)%n]!,summit],i%3===0?colors.left:colors.top,0)@@ -154,13 +159,52 @@ export function rockOutcrop(d: Drawing, u: number, v: number, radius: number, hed.volume(start,0.8)}-export function makeRock(ore: boolean, full: boolean, variant = 0) {- const d=new Drawing(`${ore?"ore":"stone"}-${full?"full":"quarried"}`,`${ore?"Ore":"Stone"} · ${full?"full":"quarried"}`,"A clustered deposit with clean shaded facets and seeded silhouettes. Stone and ore use distinct mineral palettes.")- d.asset.category="land";d.asset.reference={type:"rock",x:ore?5:0,y:ore?3:0,ore,amount:full?40:10};d.asset.footprint=1- rockOutcrop(d,-2.9*U,-2.2*U,2.8*U,full?10:4,ore,variant+2)- rockOutcrop(d,0.3*U,-0.1*U,(full?4.4:4)*U,full?12+(variant%3)*1.5:6,ore,variant)- rockOutcrop(d,3.7*U,3.2*U,2.8*U,full?9:3,ore,variant+4)- for(const [u,v]of [[-4,4],[-2,5.8],[5,-3.5]] as const)rockOutcrop(d,u*U,v*U,0.7*U,1.8,ore,variant+u)+/** A crystal of ore: a leaning, five-sided spike with a rust-red face. */+export function oreShard(d: Drawing, u: number, v: number, radius: number, height: number, variant = 0) {+ const start=d.asset.faces.length,n=5,turn=hash(variant,11)*Math.PI*2+ const lean:[number,number]=[(hash(variant,5)-0.5)*radius*1.4,(hash(variant,7)-0.5)*radius*1.4]+ const base=Array.from({length:n},(_,i):Vertex=>{+ const t=i*Math.PI*2/n+turn,r=radius*(0.75+hash(i,variant+1)*0.25)+ return [u+Math.cos(t)*r,v+Math.sin(t)*r,0]+ })+ const neck=base.map(([x,y]):Vertex=>[x+(u+lean[0]-x)*0.35+lean[0]*0.5,y+(v+lean[1]-y)*0.35+lean[1]*0.5,height*0.62])+ const tip:Vertex=[u+lean[0]*1.3,v+lean[1]*1.3,height]+ for(let i=0;i<n;i++){+ const j=(i+1)%n,side=i===variant%n?RUST:i<2?oreColors.right:oreColors.left+ d.face([base[i]!,base[j]!,neck[j]!,neck[i]!],side,0)+ d.face([neck[i]!,neck[j]!,tip],i===(variant+2)%n?RUST:oreColors.top,0)+ }+ d.volume(start,0.8)+}++/**+ * A deposit of stone or ore, over `w` × `h` cells (a big outcrop is drawn+ * once over the cells it spans). Stone is a heap of rounded boulders; ore is+ * slate rubble with shards standing out of it.+ */+export function makeRock(ore: boolean, full: boolean, variant = 0, w = 1, h = 1) {+ const name=ore?"Ore":"Stone"+ const size=w*h>1?`-${w}x${h}`:""+ const d=new Drawing(`${ore?"ore":"stone"}-${full?"full":"quarried"}${size}`,`${name} · ${full?"full":"quarried"}${size?` · ${w}×${h}`:""}`,"A clustered deposit with clean shaded facets and seeded silhouettes. Stone is pale rounded boulders; ore is dark slate with rust-red shards.")+ d.asset.category="land";d.asset.reference={type:"rock",x:ore?5:0,y:ore?3:0,ore,amount:full?40:10};d.asset.footprint=Math.max(w,h)+ const A=w*8*U,B=h*8*U,small=Math.min(w,h),grow=1+(small-1)*0.55+ // The big rock in the middle, then smaller ones around it, inside the footprint.+ const spots:Array<[number,number,number]>=[[0.06,-0.02,1]]+ const around=2+w*h+ for(let i=0;i<around;i++){+ const t=i*Math.PI*2/around+hash(variant,i)*0.9+ spots.push([Math.cos(t)*(0.5+hash(i,variant)*0.2),Math.sin(t)*(0.5+hash(variant,i+3)*0.2),0.45+hash(i+5,variant)*0.25])+ }+ spots.forEach(([fu,fv,scale],i)=>{+ const u=fu*(A-3*U),v=fv*(B-3*U),r=(full?4.4:3.6)*U*grow*scale+ const z=(full?11+(variant%3)*1.5:5)*grow*scale+ if(!ore)rockOutcrop(d,u,v,r,z,false,variant+i*2)+ else if(i===0||i%2===1){+ rockOutcrop(d,u,v,r*0.9,z*0.4,true,variant+i*2)+ if(full||i===0)for(let k=0;k<(i===0?3:1);k++)oreShard(d,u+(k-1)*r*0.45,v+(k%2)*r*0.3-r*0.15,r*0.38,z*(1.35-k*0.2),variant+i*3+k)+ }else oreShard(d,u,v,r*0.4,z*(full?1:0.6),variant+i*3)+ })+ for(const [fu,fv] of [[-0.55,0.62],[-0.2,0.85],[0.7,-0.5]] as const)rockOutcrop(d,fu*(A-U),fv*(B-U),0.7*U,1.8,ore,variant+Math.round(fu*10))return d.asset}diff --git a/src/factory.css b/src/factory.cssindex 3add55d..a433284 100644--- a/src/factory.css+++ b/src/factory.css@@ -44,13 +44,11 @@ body { font-family: ui-monospace, "SF Mono", "JetBrains Mono", Menlo, monospace;.hud .good.empty { opacity: 0.55; }/* ── The toolbar: the town's panel, the tools, the speed ── */-.toolbar, .system {- position: fixed; bottom: calc(14px + env(safe-area-inset-bottom)); display: flex; align-items: stretch; gap: 8px; z-index: 2;-}-.toolbar { left: 16px; max-width: calc(100vw - 32px); overflow-x: auto; }-.system { right: 16px; transition: right 240ms cubic-bezier(.2,.8,.2,1); }-.panel-open .system { right: 376px; }-.panel-open .system button { font-size: 0; gap: 0; padding: 6px 8px; }+.toolbar, .system { position: fixed; display: flex; align-items: stretch; gap: 8px; z-index: 2; }+.toolbar { bottom: calc(14px + env(safe-area-inset-bottom)); left: 16px; max-width: calc(100vw - 32px); overflow-x: auto; }+/* Share, the guide, save, load, new town: icons in a row at the top, left of the people's card (its width set by the page). */+.system { top: 12px; right: calc(24px + var(--people-width, 330px)); transition: right 240ms cubic-bezier(.2,.8,.2,1); }+.panel-open .system { right: calc(384px + var(--people-width, 330px)); }.toolbar .group, .system {display: flex; gap: 4px; padding: 5px; background: #f7f8f4; border: 1px solid #c9cec4; border-radius: 8px; box-shadow: 0 2px 0 #dfe2db;}@@ -64,7 +62,10 @@ body { font-family: ui-monospace, "SF Mono", "JetBrains Mono", Menlo, monospace;.toolbar button kbd { font: inherit; font-size: 10px; opacity: 0.55; }.toolbar .pause { padding: 6px 9px; }.toolbar .pause.on .glyph { background: none; }-.system button { color: #5d6861; }+/* With the panel open, the people move over and leave no room beside them, unless the screen is wide. */+@media (max-width: 1440px) { .panel-open .system { display: none; } }+.system button { color: #5d6861; font-size: 0; gap: 0; padding: 6px 9px; }+.system button.labelled { font-size: 12px; gap: 7px; padding: 6px 10px; }.system .guide-toggle.on { color: #2f5a9c; background: #eef3fb; border-color: #c9d6ee; }.toolbar .town-button {padding: 8px 18px 8px 12px; gap: 10px; font-size: 14px; font-weight: 700; letter-spacing: 0.02em;@@ -83,10 +84,8 @@ body { font-family: ui-monospace, "SF Mono", "JetBrains Mono", Menlo, monospace;font-size: 12px; padding: 7px 14px; border-radius: 4px; opacity: 0; transition: opacity 160ms ease; pointer-events: none; z-index: 20;}.toast.show { opacity: 1; }-@media (max-width: 1260px) {- .system button { font-size: 0; gap: 0; padding: 6px 8px; }-}@media (max-width: 1000px) {+ .system button.labelled { font-size: 0; gap: 0; padding: 6px 9px; }.toolbar button kbd, .toolbar .town-button kbd { display: none; }.hud .stack small { display: none; }}diff --git a/src/host.ts b/src/host.tsindex c8779b7..141063b 100644--- a/src/host.ts+++ b/src/host.ts@@ -140,7 +140,7 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persistewood: "lumberjacks fell it; a sawmill saws it into planks",planks: "what homes and buildings are built from: a sawmill makes them from wood",stone: "for building and paving: quarries cut it from rocks, which run out",- ore: "mines dig it; a smithy forges it into tools",+ ore: "only for tools: once the town has 10 citizens, a mine digs it from the rust-red deposits, and a smithy forges it into tools",tools: "for building, and workshops wear one out every 50 or 60 jobs: a smithy forges them, or buy them",fish: "food for settlers: fisheries catch it by the water; it rots in about three minutes",smoked: "fish that keeps all winter: a smokehouse smokes it",@@ -353,10 +353,12 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persisteui.view = viewfor (const v of viewEls) v.button.classList.toggle("on", v.view === view)}- // New town, save, and load, out of the way in the bottom right. Founding or- // loading replaces the town, so each asks first.+ // Share, the guide, save, load, and new town: a row of icons at the top,+ // beside the people (it keeps its distance as their card grows). Founding+ // or loading replaces the town, so each asks first.+ new ResizeObserver(() => document.body.style.setProperty("--people-width", `${folk.offsetWidth}px`)).observe(folk)const action = (name: IconName, label: string, tip: string, run: () => void) => {- const button = el("button", "")+ const button = el("button", name === "share" ? "labelled" : "")button.title = tipbutton.append(iconEl(name), document.createTextNode(label))button.onclick = run@@ -365,6 +367,7 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persisteaction("share", "share", "Share a picture of the town, or a link anyone can open to watch it and play on", () => void openShare())// The guide, on or off (it is on for a new mayor).const guideButton = el("button", "guide-toggle")+ guideButton.title = "Turn the guide on or off: it tells a new mayor what to do next, and why"guideButton.append(iconEl("hint"), document.createTextNode("guide"))guideButton.onclick = () => ui.guide.push({ type: ui.stats?.guide.off ? "on" : "off" })system.append(guideButton)@@ -1568,7 +1571,7 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persistedismissed.add(off.dataset.dismiss!)return}- // The guide: put this step away, or turn the guide off (the bottom-right button turns it back on).+ // The guide: put this step away, or turn the guide off (the top-right button turns it back on).const skip = target.closest<HTMLElement>("[data-skip]")if (skip) {ui.guide.push({ type: "skip", id: skip.dataset.skip! })@@ -1576,7 +1579,7 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persiste}if (target.closest("[data-guide-off]")) {ui.guide.push({ type: "off" })- ui.toast("Guide off · turn it back on from the bottom right")+ ui.toast("Guide off · turn it back on from the top right")return}const ref = target.closest<HTMLElement>("[data-kind]")@@ -1673,7 +1676,7 @@ export const createHost = async (mount: HTMLElement, persistence: () => Persisteconst g = s.guide.stepconst guideHtml = g? [- `<div class="head guide"><span>guide · ${escapeHtml(g.chapter)}</span><span class="progress" title="Steps of the guide done">${s.guide.done} of ${s.guide.total} done</span><button class="quiet" data-guide-off title="Turn the guide off (the guide button in the bottom right turns it back on)">hide guide</button></div>`,+ `<div class="head guide"><span>guide · ${escapeHtml(g.chapter)}</span><span class="progress" title="Steps of the guide done">${s.guide.done} of ${s.guide.total} done</span><button class="quiet" data-guide-off title="Turn the guide off (the guide button in the top right turns it back on)">hide guide</button></div>`,`<div class="cell alert hint guide${g.at !== null ? " place" : ""}" data-guide>${icon("hint", 16, "mark")}<span class="text">${callouts(g.text)}</span><span class="acts">${g.at !== null ? `<button class="act locate" title="Show me where">${icon("locate", 14)}</button>` : ""}<button class="act dismiss" data-skip="${escapeHtml(g.key)}" title="Skip this step">${icon("close", 12)}</button></span></div>`]: []diff --git a/src/model-review/main.ts b/src/model-review/main.tsindex 21b8232..e8b9134 100644--- a/src/model-review/main.ts+++ b/src/model-review/main.ts@@ -4,7 +4,7 @@ import { buildAsset, exportAsset } from "../asset-lab/renderer.ts"import "./style.css"const families = {- fixes: { title: "Review fixes", ids: ["mill","bakery","weaver","warehouse","mine","farm","chapel","hospital","smokehouse","builder","townhouse","quarry","stone-full","stone-quarried","ore-full","problem-marker","smoke","firewatch"] },+ fixes: { title: "Review fixes", ids: ["mill","bakery","weaver","warehouse","mine","farm","chapel","hospital","smokehouse","builder","townhouse","quarry","stone-full","stone-quarried","ore-full","ore-quarried","stone-full-2x1","stone-full-2x2","stone-full-3x3","ore-full-2x1","ore-full-2x2","ore-full-3x3","problem-marker","smoke","firewatch"] },buildings: { title: "Buildings", ids: ["granary", "smokehouse", "firewatch", "healer", "hospital", "watchhouse", "builder"] },ornaments: { title: "Parks", ids: ["park-sample", "park-lamp", "park-fountain", "park-statue", "paved-street"] },homes: { title: "Homes & neighbourhoods", ids: ["cottage", "citizen", "townhouse", "cottage-fine", "citizen-fine", "townhouse-fine", "cottage-poor", "citizen-worn", "townhouse-worn"] },diff --git a/src/phone.css b/src/phone.cssindex 67ba6d9..b978b73 100644--- a/src/phone.css+++ b/src/phone.css@@ -13,7 +13,7 @@.toolbar button, .toolbar .town-button { font-size: 0; gap: 0; padding: 6px; min-width: 40px; min-height: 40px; justify-content: center; }.toolbar .speed button { font-size: 12px; min-width: 36px; }.toolbar button kbd { display: none; }- .system button { font-size: 0; gap: 0; padding: 6px; min-width: 38px; min-height: 38px; justify-content: center; }+ .system button, .system button.labelled { font-size: 0; gap: 0; padding: 6px; min-width: 38px; min-height: 38px; justify-content: center; }.camera-controls [data-mode="pan"], .camera-controls output { display: none; }/* The goods on one line that scrolls, a little smaller. */@@ -85,7 +85,7 @@.hud { top: calc(6px + env(safe-area-inset-top)); gap: 5px; }.hud .card .cell { padding: 5px 10px; }.toolbar { bottom: calc(6px + env(safe-area-inset-bottom)); }- .system { bottom: calc(6px + env(safe-area-inset-bottom)); }+ .system { top: calc(6px + env(safe-area-inset-top)); }.panel-open .system { display: none; }.camera-controls { bottom: calc(60px + env(safe-area-inset-bottom)); padding: 3px; }.views { bottom: calc(60px + env(safe-area-inset-bottom)); }@@ -94,6 +94,12 @@.panel { padding-top: 12px; }}+/* A small landscape window: the map views stand in a column on the right, so the ticker and the speed keep left of it. */+@media (max-width: 760px) and (max-height: 500px) {+ .hud.left { right: 66px; }+ .toolbar .speed { right: 66px; }+}+/* ── Touch: fingers instead of a mouse ── */@media (pointer: coarse) {/* No hover, so no key hints; targets big enough for a thumb. */diff --git a/src/present.ts b/src/present.tsindex 56b7ced..805d2df 100644--- a/src/present.ts+++ b/src/present.ts@@ -86,7 +86,8 @@ import { Townsfolk } from "./townsfolk.ts"import { emptyPreview, type Alert as Notice, type HitBox, type Legend, type Line, type View } from "./ui.ts"import { blockers as blockersOf, streetAdvice, type InTown, type Served, type Street } from "./rules/explain.ts"import { breadBonus, streetTax, suppliedTaxOf } from "./rules/households.ts"-import { guideDone, guideStep, guideSteps, type GuideFacts, type GuideFocus } from "./rules/guide.ts"+import { rockBlocks, type RockPart } from "./render3d/rock-blocks.ts"+import { GUIDE_QUIET, guideDone, guideStep, guideSteps, type GuideFacts, type GuideFocus } from "./rules/guide.ts"import { ticks } from "./content.ts"const cellAt = (at: Point): Point => {@@ -1126,7 +1127,18 @@ export const Interact = Game.System(trading: rates.sells.length > 0 || rates.buys.length > 0,taxed: rates.settlers !== 100 || rates.citizens !== 100,most: Math.max(...goodIds.map((g) => stock[g])),- sawTown: ui.menu === "town"+ sawTown: ui.menu === "town",+ risk: {+ fire: houses.some((row) => (maybe(row.data.risk)?.fire ?? 0) >= RISK_MAX * 0.35),+ health: houses.some((row) => (maybe(row.data.risk)?.health ?? 0) >= RISK_MAX * 0.35),+ order: houses.some((row) => (maybe(row.data.risk)?.order ?? 0) >= RISK_MAX * 0.35)+ },+ fewTrees: buildings.some((row) => {+ if (row.data.building.get().kind !== "lumberjack" || !finished(row)) return false+ const tile = row.data.tile.get()+ const reach = kinds.lumberjack.gathers!.radius+ return queries.trees.each().map(({ data }) => data.tile.get()).filter((t) => t.x >= tile.x - reach && t.x < tile.x + tile.size + reach && t.y >= tile.y - reach && t.y < tile.y + tile.size + reach).length < 6+ })}const guide = resources.guide.get()const put = new Set(guide.done)@@ -1136,7 +1148,12 @@ export const Interact = Game.System(resources.guide.update((g) => ({ ...g, done: [...g.done, ...newly] }))for (const id of newly) put.add(id)}- const step = guide.off || !playing ? null : guideStep(facts, put)+ // The guide keeps quiet a while after a step is put away; a new town (the clock gone back) starts it afresh.+ if (t < guidePace.since) Object.assign(guidePace, { shown: null, since: 0, quietUntil: 0 })+ if (guidePace.shown !== null && put.has(guidePace.shown)) Object.assign(guidePace, { shown: null, quietUntil: t + GUIDE_QUIET * 60 })+ const step = guide.off || !playing ? null : guideStep(facts, put, { shown: guidePace.shown, quiet: t < guidePace.quietUntil })+ if (step && !step.urgent?.(facts)) guidePace.shown = step.id+ guidePace.since = tconst hallTile = hallRow?.data.tile.get()/** Of some tiles, the one nearest the town hall. */const nearestHall = (tiles: ReadonlyArray<TileLike>): TileLike | undefined => {@@ -1404,7 +1421,7 @@ export const Animate = Game.System(}}),trees: Game.Query({ selection: { tree: Game.Query.read(Tree) } }),- rocks: Game.Query({ selection: { rock: Game.Query.read(Rock) } }),+ rocks: Game.Query({ selection: { rock: Game.Query.read(Rock), tile: Game.Query.read(Tile) } }),fields: Game.Query({ selection: { field: Game.Query.read(Field) } })},resources: { grid: Game.System.readResource(Grid), appeal: Game.System.readResource(Appeal) },@@ -1509,14 +1526,29 @@ export const Animate = Game.System(}for (const { entity, data } of queries.trees.each())services.treeNodes.get(entity.id)?.update(data.tree.get().growth, emphasis(entity.id))- for (const { entity, data } of queries.rocks.each()) {+ // Neighbouring rocks are drawn as one big outcrop; the blocks are formed again only when a rock runs out (or the land changes).+ const rocks = queries.rocks.each()+ const rockKey = `${rocks.length}:${rocks.reduce((n, { entity }) => n + entity.id, 0)}`+ if (rockKey !== rockShapes.key) {+ rockShapes.key = rockKey+ rockShapes.parts = rockBlocks(rocks.map(({ entity, data }) => ({ id: entity.id, ...data.tile.get(), ore: data.rock.get().ore })))+ }+ const amounts = new Map<number, number>(rocks.map(({ entity, data }) => [entity.id, data.rock.get().amount]))+ for (const { entity, data } of rocks) {const r = data.rock.get()- services.rockNodes.get(entity.id)?.update(r.ore, r.amount)+ const part = rockShapes.parts.get(entity.id)+ if (!part || !part.draws) services.rockNodes.get(entity.id)?.update(r.ore, r.amount, part ? 0 : 1, part ? 0 : 1)+ else services.rockNodes.get(entity.id)?.update(r.ore, part.members.reduce((n, id) => n + (amounts.get(id) ?? 0), 0) / part.members.length, part.w, part.h)}for (const { entity, data } of queries.fields.each()) services.fieldNodes.get(entity.id)?.update(data.field.get().growth)})+/** The guide's pace (page-side, not saved): the step it is showing, and until when it keeps quiet. */+const guidePace: { shown: string | null; since: number; quietUntil: number } = { shown: null, since: 0, quietUntil: 0 }++const rockShapes: { key: string; parts: Map<number, RockPart> } = { key: "", parts: new Map() }+/** Ghosts, the road being dragged, and outlines, redrawn every frame. */export const DrawPreview = Game.System("Town/DrawPreview",diff --git a/src/render3d/rock-blocks.ts b/src/render3d/rock-blocks.tsnew file mode 100644index 0000000..647ebf2--- /dev/null+++ b/src/render3d/rock-blocks.ts@@ -0,0 +1,59 @@+/**+ * Rocks are one per cell in the simulation, but a deposit reads better as a+ * few big outcrops than as a grid of pebbles. This joins neighbouring rocks+ * of the same kind into blocks of 3×3, 2×2, 2×1 or 1×2, drawn once by the+ * block's first cell; the others draw nothing. It only changes the picture:+ * a quarry still cuts, and a rock still runs out, one cell at a time.+ */+import { hash } from "../asset-lab/land.ts"++export interface RockCell {+ readonly id: number+ readonly x: number+ readonly y: number+ readonly ore: boolean+}++/** A cell's part in a block: it draws `w` × `h` cells from it, or (`lead` the cell that does) nothing. */+export type RockPart = { readonly draws: true; readonly w: number; readonly h: number; readonly members: ReadonlyArray<number> } | { readonly draws: false; readonly lead: number }++/** Which sizes to try at a cell, biggest first; some cells skip the bigger ones, so a deposit mixes sizes. */+const sizesAt = (x: number, y: number): ReadonlyArray<readonly [number, number]> => {+ const roll = hash(x * 13 + 5, y * 7 + 11)+ const two: ReadonlyArray<readonly [number, number]> = roll < 0.5 ? [[2, 1], [1, 2]] : [[1, 2], [2, 1]]+ if (roll < 0.45) return [[3, 3], [2, 2], ...two]+ if (roll < 0.8) return [[2, 2], ...two]+ if (roll < 0.95) return two+ return []+}++export const rockBlocks = (cells: ReadonlyArray<RockCell>): Map<number, RockPart> => {+ const at = new Map<string, RockCell>()+ for (const c of cells) at.set(`${c.x},${c.y}`, c)+ const taken = new Set<number>()+ const parts = new Map<number, RockPart>()+ const sorted = [...cells].sort((a, b) => a.y - b.y || a.x - b.x)+ for (const c of sorted) {+ if (taken.has(c.id)) continue+ let block: Array<RockCell> = [c]+ let size: readonly [number, number] = [1, 1]+ for (const [w, h] of sizesAt(c.x, c.y)) {+ const found: Array<RockCell> = []+ for (let dy = 0; dy < h; dy++)+ for (let dx = 0; dx < w; dx++) {+ const n = at.get(`${c.x + dx},${c.y + dy}`)+ if (n && n.ore === c.ore && !taken.has(n.id)) found.push(n)+ }+ if (found.length === w * h) {+ block = found+ size = [w, h]+ break+ }+ }+ for (const n of block) {+ taken.add(n.id)+ parts.set(n.id, n === c ? { draws: true, w: size[0], h: size[1], members: block.map((m) => m.id) } : { draws: false, lead: c.id })+ }+ }+ return parts+}diff --git a/src/render3d/views.ts b/src/render3d/views.tsindex 75f93e0..d36826d 100644--- a/src/render3d/views.ts+++ b/src/render3d/views.ts@@ -265,19 +265,24 @@ export class TreeView extends WorldView {export class RockView extends WorldView {private body: ModelHandleprivate variant = 0+ private cell = { x: 0, y: 0 }constructor(stage: GameScene, entity: number) {super(stage, entity)this.body = this.model()}place(x: number, y: number) {this.variant = Math.floor(hash(x,y)*6)- this.anchor.x = x + 0.5- this.anchor.y = y + 0.5- this.group.position.copy(vertex3([this.anchor.x, this.anchor.y, 0]))+ this.cell = { x, y }}- update(ore: boolean, amount: number) {+ /** `w` × `h`: the cells of the outcrop this rock draws (see `rock-blocks.ts`); 0, drawn by a neighbour. */+ update(ore: boolean, amount: number, w = 1, h = 1) {+ this.group.visible = w > 0+ if (w === 0) return+ this.anchor.x = this.cell.x + w / 2+ this.anchor.y = this.cell.y + h / 2+ this.group.position.copy(vertex3([this.anchor.x, this.anchor.y, 0]))const full = amount > ROCK_AMOUNT / 2- this.body.use(`rock/${ore}/${full}/${this.variant}`, () => makeRock(ore, full, this.variant))+ this.body.use(`rock/${ore}/${full}/${this.variant}/${w}x${h}`, () => makeRock(ore, full, this.variant, w, h))}}export class FieldView extends WorldView {diff --git a/src/rules/guide.ts b/src/rules/guide.tsindex 3c45851..705b637 100644--- a/src/rules/guide.ts+++ b/src/rules/guide.ts@@ -7,6 +7,13 @@* a mayor who already knows the game is not told what they did. The list* is in order of priority, not of chapters: a request from the crown with a* deadline goes ahead of a chain that takes minutes to build.+ *+ * Steps come when the town needs them, not back to back: each waits for a+ * sign (planks running low, the woods thinning, a fire risk rising), and+ * after one is done the guide keeps quiet for `GUIDE_QUIET` seconds. An+ * urgent step (the crown's request, winter, a fire, the sick, a building+ * falling apart) does not wait for the quiet. A step once shown stays until+ * it is done or put away, so the ticker does not hop between steps.*/import type { Amounts, KindId } from "../content.ts"@@ -42,8 +49,15 @@ export interface GuideFacts {readonly most: number/** The page: the town panel has been open. */readonly sawTown: boolean+ /** A home whose risk of fire, sickness, or theft is rising. */+ readonly risk: { readonly fire: boolean; readonly health: boolean; readonly order: boolean }+ /** A lumberjack with few trees left in reach. */+ readonly fewTrees: boolean}+/** Seconds of the town's time the guide keeps quiet after a step, before the next that is not urgent. */+export const GUIDE_QUIET = 45+/** Where a step's "show me where" goes: a place on the land, or a building of a kind. */export type GuideFocus = "hall" | "water" | "trees" | "stone" | "ore" | "worn" | "poorStreet" | { readonly kind: KindId }@@ -57,6 +71,8 @@ export interface GuideStep {readonly text: stringreadonly focus: GuideFocus | nullreadonly when: (f: GuideFacts) => boolean+ /** It cannot wait for the guide's quiet (and goes ahead of the step shown). */+ readonly urgent?: (f: GuideFacts) => booleanreadonly done: (f: GuideFacts) => boolean}@@ -85,6 +101,7 @@ export const guideSteps: ReadonlyArray<GuideStep> = [text: "The crown asks for goods by a deadline. Send them from the bar at the top for coins; an unanswered request is a fine, and three missed in a row and the mayor is dismissed.",focus: null,when: (f) => f.crown.open,+ urgent: () => true,done: (f) => f.crown.met > 0},{@@ -93,12 +110,13 @@ export const guideSteps: ReadonlyArray<GuideStep> = [text: "Winter is coming: fishing slows, homes eat faster, and fish rots in store. A granary keeps fish five times as long, and a smokehouse makes fish that keeps all winter.",focus: "hall",when: (f) => f.residents >= 20 && (f.winter || (f.winterIn !== null && f.winterIn <= 120)),+ urgent: () => true,done: (f) => has(f, "granary") || has(f, "smokehouse")},{id: "tools",chapter: "Growing citizens",- text: "Tools are scarce until a smithy makes them, and that needs 10 citizens. Keep them for the weaver, the mill, and the bakery (not lamps), or buy them from traders in the town panel (T).",+ text: "Tools are scarce until a smithy forges them from ore, and that needs 10 citizens. Keep them for the weaver, the mill, and the bakery (not lamps), or buy them from traders in the town panel (T).",focus: null,when: (f) => f.residents >= 15 && f.stock.tools <= 3 && !has(f, "weaver", "mill", "bakery"),done: (f) => has(f, "weaver", "mill", "bakery") || has(f, "smithy")@@ -108,15 +126,15 @@ export const guideSteps: ReadonlyArray<GuideStep> = [chapter: "Founding",text: "Every home and building costs planks. A lumberjack by the woods fells wood, and a sawmill saws it into planks.",focus: "trees",- when: (f) => has(f, "fishery") || f.stock.planks < 20,+ when: (f) => f.stock.planks < 25 || (f.standing.has("fishery") && f.homes >= 6),done: (f) => has(f, "lumberjack", "sawmill")},{id: "forester",chapter: "Founding",- text: "The woods run out. A forester beside the lumberjack plants new trees for it to fell.",+ text: "The lumberjack is running out of trees. A forester beside it plants new ones for it to fell.",focus: { kind: "lumberjack" },- when: (f) => has(f, "lumberjack"),+ when: (f) => f.fewTrees,done: (f) => has(f, "forester")},{@@ -124,15 +142,16 @@ export const guideSteps: ReadonlyArray<GuideStep> = [chapter: "Founding",text: "Storage, workshops, and paving take stone, and the town starts with little. A quarry cuts it from the rocks nearby.",focus: "stone",- when: (f) => has(f, "lumberjack", "sawmill") || f.stock.stone < 6,+ when: (f) => f.stock.stone < 10 || (f.standing.has("sawmill") && f.homes >= 10),done: (f) => has(f, "quarry")},{id: "firewatch",chapter: "Keeping it standing",- text: "Wooden cottages catch fire, and a fire spreads to its neighbours. A fire watch sends a watchman along the streets, and firefighters to any blaze. Press F to see the risk.",+ text: "The risk of fire is rising: wooden cottages catch fire, and a fire spreads to its neighbours. A fire watch sends a watchman along the streets, and firefighters to any blaze. Press F to see the risk.",focus: "hall",- when: (f) => f.homes >= 8 || f.burning > 0,+ when: (f) => f.risk.fire || f.burning > 0,+ urgent: (f) => f.burning > 0,done: (f) => has(f, "firewatch")},{@@ -141,6 +160,7 @@ export const guideSteps: ReadonlyArray<GuideStep> = [text: "Buildings wear out, and a run-down one works at half pace and may fall. A builder's yard mends what its builder passes, with planks and stone. Press C to see their condition.",focus: "worn",when: (f) => f.worn,+ urgent: () => true,done: (f) => has(f, "builder")},{@@ -186,17 +206,18 @@ export const guideSteps: ReadonlyArray<GuideStep> = [{id: "healer",chapter: "Keeping it standing",- text: "Hunger, crowding, and a quarry's dust make homes sick, and a sick home holds half as many. A healer's physician calls on the homes and cures them. Press A to see the risk.",+ text: "Sickness is spreading: hunger, crowding, and a quarry's dust make homes sick, and a sick home holds half as many. A healer's physician calls on the homes and cures them. Press A to see the risk.",focus: "hall",- when: (f) => f.residents >= 30 && (f.sick > 0 || f.residents >= 50),+ when: (f) => f.residents >= 30 && (f.sick > 0 || f.risk.health),+ urgent: (f) => f.sick > 0,done: (f) => has(f, "healer") || has(f, "hospital")},{id: "watchhouse",chapter: "Keeping it standing",- text: "Poor streets, half-empty homes, and low approval breed thieves. A watch house sends a constable along the streets to keep order. Press O to see the risk.",+ text: "Thieves are about: poor streets, half-empty homes, and low approval breed them. A watch house sends a constable along the streets to keep order. Press O to see the risk.",focus: "hall",- when: (f) => f.residents >= 40,+ when: (f) => f.residents >= 40 && f.risk.order,done: (f) => has(f, "watchhouse")},{@@ -218,7 +239,7 @@ export const guideSteps: ReadonlyArray<GuideStep> = [{id: "smithy",chapter: "Governing",- text: "Now open: a mine digs ore from a deposit, and a smithy forges it into tools, which every workshop and lamp needs and which wear out.",+ text: "Ore is for one thing: tools. Now open: a mine by the dark, rust-veined rocks digs ore, and a smithy forges it into tools, which every workshop and lamp needs and which wear out.",focus: "ore",when: (f) => f.citizens >= 10,done: (f) => has(f, "mine", "smithy")@@ -229,6 +250,16 @@ export const guideSteps: ReadonlyArray<GuideStep> = [export const guideDone = (f: GuideFacts, done: ReadonlySet<string>): Array<string> =>guideSteps.filter((s) => !done.has(s.id) && s.done(f)).map((s) => s.id)-/** The step to show now, if any: the first that applies and is not yet done or put away. */-export const guideStep = (f: GuideFacts, done: ReadonlySet<string>): GuideStep | null =>- guideSteps.find((s) => !done.has(s.id) && !s.done(f) && s.when(f)) ?? null+/**+ * The step to show now, if any: an urgent one first; else the step already+ * shown (`shown`), until it is done or put away; else, unless the guide is+ * keeping `quiet`, the first that applies.+ */+export const guideStep = (f: GuideFacts, done: ReadonlySet<string>, pace: { readonly shown?: string | null; readonly quiet?: boolean } = {}): GuideStep | null => {+ const open = (s: GuideStep) => !done.has(s.id) && !s.done(f)+ const urgent = guideSteps.find((s) => open(s) && s.when(f) && s.urgent?.(f))+ if (urgent) return urgent+ const shown = guideSteps.find((s) => s.id === pace.shown && open(s) && (!s.urgent || s.when(f)))+ if (shown) return shown+ return pace.quiet ? null : (guideSteps.find((s) => open(s) && s.when(f)) ?? null)+}diff --git a/src/server/handler.ts b/src/server/handler.tsindex 56df10c..642b329 100644--- a/src/server/handler.ts+++ b/src/server/handler.ts@@ -7,6 +7,10 @@* - `GET /t/:id` is the game's own page, with the town's picture and lines* written into it for link previews; the page loads the town itself.*+ * Uploads are limited per visitor (by IP): a few a minute, by Cloudflare's+ * rate-limit binding (`burst`), and `DAILY_SHARES` a day, counted in the same+ * bucket under `limits/` (which forgets them after a day). Reading is free.+ ** It is written against the few bucket and asset calls it uses, so the same* code runs on Cloudflare (an R2 bucket and the site's assets), under the* dev server, and in tests (both in memory).@@ -24,12 +28,34 @@ export interface Bucket {): Promise<unknown>}+/** What the handler needs of a Cloudflare rate-limit binding. */+export interface Limiter {+ limit(options: { readonly key: string }): Promise<{ readonly success: boolean }>+}+export interface Env {readonly bucket: Bucket+ /** A few uploads a minute from one visitor (absent: no limit by the minute, as in dev and tests). */+ readonly burst?: Limiter/** The site's static files: here, its `index.html`. */readonly assets: { fetch(request: Request): Promise<Response> }}+/** Towns one visitor may share in a day. */+export const DAILY_SHARES = 20++/** Who is asking, as far as limits go: their IP, hashed, so the bucket keeps no addresses. */+const visitorOf = async (request: Request) => {+ const ip = request.headers.get("cf-connecting-ip") ?? "local"+ const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(`inkline:${ip}`)))+ return [...digest.slice(0, 12)].map((b) => b.toString(16).padStart(2, "0")).join("")+}+const limitKey = (visitor: string) => `limits/${new Date().toISOString().slice(0, 10)}/${visitor}`+const sharedToday = async (env: Env, key: string) => {+ const object = await env.bucket.get(key)+ return object ? Number(await new Response(object.body).text()) || 0 : 0+}+const townKey = (id: string) => `towns/${id}.json.gz`const pictureKey = (id: string) => `towns/${id}.picture`@@ -90,6 +116,11 @@ const bytesOf = async (value: FormDataEntryValue | null): Promise<Uint8Array | n/** Keeps a new share and answers with its id and link. */const create = async (request: Request, env: Env) => {+ const visitor = await visitorOf(request)+ if (env.burst && !(await env.burst.limit({ key: visitor })).success) return fail(429, "Too many shares at once: wait a minute and try again")+ const today = limitKey(visitor)+ const shared = await sharedToday(env, today)+ if (shared >= DAILY_SHARES) return fail(429, `That is ${DAILY_SHARES} towns shared today: try again tomorrow`)const length = Number(request.headers.get("content-length") ?? "0")if (length > TOWN_LIMIT + PICTURE_LIMIT + 10_000) return fail(413, "That town is too large to share")let form: FormData@@ -121,6 +152,7 @@ const create = async (request: Request, env: Env) => {httpMetadata: { contentType: "application/gzip" },customMetadata: { title: meta.title, description: meta.description }})+ await env.bucket.put(today, new TextEncoder().encode(String(shared + 1)), { httpMetadata: { contentType: "text/plain" } })const origin = new URL(request.url).originreturn json({ id, url: `${origin}${sharePath(id)}` }, 201)}diff --git a/src/server/worker.ts b/src/server/worker.tsindex 4654010..2f009b0 100644--- a/src/server/worker.ts+++ b/src/server/worker.ts@@ -3,16 +3,17 @@* (`/t/*` and `/api/*`, see `deploy/alchemy.run.ts`); every other request is* a static file Cloudflare serves without running it.*/-import { handle, type Bucket } from "./handler.ts"+import { handle, type Bucket, type Limiter } from "./handler.ts"interface WorkerEnv {readonly SHARES: Bucket+ readonly SHARE_BURST: Limiterreadonly ASSETS: { fetch(request: Request): Promise<Response> }}export default {async fetch(request: Request, env: WorkerEnv): Promise<Response> {- const response = await handle(request, { bucket: env.SHARES, assets: env.ASSETS })+ const response = await handle(request, { bucket: env.SHARES, burst: env.SHARE_BURST, assets: env.ASSETS })return response ?? env.ASSETS.fetch(request)}}diff --git a/test/guide.test.ts b/test/guide.test.tsindex 67a6a9f..bc89559 100644--- a/test/guide.test.ts+++ b/test/guide.test.ts@@ -30,7 +30,9 @@ const fresh: GuideFacts = {trading: false,taxed: false,most: 40,- sawTown: false+ sawTown: false,+ risk: { fire: false, health: false, order: false },+ fewTrees: false}const town = (over: Partial<GuideFacts>, built: ReadonlyArray<KindId> = []): GuideFacts => ({...fresh,@@ -54,6 +56,33 @@ test("what the town has done is put away, shown or not", () => {assert.ok(next && !put.includes(next.id), "the next step is one not yet done")})+test("steps wait for the town to need them, not for the last one to be done", () => {+ const founded = town({ homes: 4, residents: 8 }, ["fishery", "lumberjack", "sawmill"])+ const put = new Set(guideDone(founded, none))+ // Planks in hand, stone in hand, the woods full, no risk: nothing to say.+ assert.equal(guideStep(founded, put), null)+ assert.equal(guideStep(town({ homes: 4, residents: 8, fewTrees: true }, ["fishery", "lumberjack", "sawmill"]), put)?.id, "forester")+ assert.equal(guideStep(town({ homes: 4, residents: 8, stock: amounts({ planks: 40, stone: 6 }) }, ["fishery", "lumberjack", "sawmill"]), put)?.id, "quarry")+})++test("after a step the guide keeps quiet, but not through a fire or the crown's request", () => {+ const facts = town({ homes: 8, residents: 16, fewTrees: true }, ["fishery", "lumberjack", "sawmill"])+ const put = new Set(guideDone(facts, none))+ assert.equal(guideStep(facts, put, { quiet: true }), null)+ assert.equal(guideStep({ ...facts, burning: 1 }, put, { quiet: true })?.id, "firewatch")+ assert.equal(guideStep({ ...facts, crown: { open: true, met: 0 } }, put, { quiet: true })?.id, "crown")+})++test("a step once shown stays until it is done, even if its sign fades", () => {+ const built: ReadonlyArray<KindId> = ["fishery", "lumberjack", "sawmill"]+ const put = new Set(["homes", "fishery", "planks"])+ const low = town({ homes: 4, residents: 8, stock: amounts({ planks: 40, stone: 6 }) }, built)+ assert.equal(guideStep(low, put)?.id, "quarry")+ const bought = town({ homes: 4, residents: 8, stock: amounts({ planks: 40, stone: 30 }) }, built)+ assert.equal(guideStep(bought, put), null)+ assert.equal(guideStep(bought, put, { shown: "quarry" })?.id, "quarry")+})+test("a step the mayor skipped stays away", () => {assert.notEqual(guideStep(fresh, new Set(["homes"]))?.id, "homes")})@@ -95,7 +124,7 @@ test("the guide never asks for a building before the town can build it", () => {}// Whatever else is true, a town just short of each unlock.const everything = (residents: number, citizens: number) =>- town({ homes: 30, residents, citizens, winter: true, winterIn: 60, worn: true, sick: 3, burning: 1 }, ["fishery", "lumberjack", "sawmill"])+ town({ homes: 30, residents, citizens, winter: true, winterIn: 60, worn: true, sick: 3, burning: 1, risk: { fire: true, health: true, order: true }, fewTrees: true }, ["fishery", "lumberjack", "sawmill"])for (const step of guideSteps) {for (const kind of asks[step.id] ?? []) {const { residents, citizens } = kinds[kind].unlockdiff --git a/test/ink-assets.test.ts b/test/ink-assets.test.tsindex 7cb68c9..069c1d5 100644--- a/test/ink-assets.test.ts+++ b/test/ink-assets.test.ts@@ -22,7 +22,8 @@ test("the portable catalogue covers all world object families", () => {assert.deepEqual([...hats].sort(), ["bonnet", "brim", "cap", "hood", "none", "top"])for (const tier of [1, 2]) assert.equal(inkAssets.filter((a) => a.reference?.type === "house" && a.reference.tier === tier && !a.appearance).length, 4)assert.equal(inkAssets.filter((a) => a.reference?.type === "tree").length, 9)- assert.equal(inkAssets.filter((a) => a.reference?.type === "rock").length, 4)+ // Stone and ore, full and quarried, one cell; and full outcrops over 2×1, 2×2, and 3×3 cells.+ assert.equal(inkAssets.filter((a) => a.reference?.type === "rock").length, 10)assert.equal(inkAssets.filter((a) => a.reference?.type === "field").length, 4)})diff --git a/test/share.test.ts b/test/share.test.tsindex 42c75f2..faeaa25 100644--- a/test/share.test.ts+++ b/test/share.test.ts@@ -10,7 +10,7 @@ import { gunzipSync, gzipSync } from "node:zlib"import { Effect } from "effect"import { fileOf, loadText, memoryStorage, Storage, World } from "../src/save.ts"-import { handle, memoryBucket, type Env } from "../src/server/handler.ts"+import { DAILY_SHARES, handle, memoryBucket, type Env, type Limiter } from "../src/server/handler.ts"import { checkMeta, ID_PATTERN, newId, pictureType, TOWN_LIMIT } from "../src/share/format.ts"import { headless, type Headless } from "../src/sim/headless.ts"@@ -89,6 +89,30 @@ test("what the server will not keep", async () => {assert.equal(bucket.files.size, 0)})+test("one visitor may share a few towns a minute, and so many a day", async () => {+ // A stand-in for Cloudflare's binding: two a "minute", counted per key.+ const counts = new Map<string, number>()+ const burst: Limiter = { limit: async ({ key }) => ({ success: (counts.set(key, (counts.get(key) ?? 0) + 1).get(key) ?? 0) <= 2 }) }+ const bucket = memoryBucket()+ const env: Env = { bucket, burst, assets: { fetch: async () => new Response(PAGE) } }+ const share = async (ip: string) => (await handle(new Request(`${ORIGIN}/api/towns`, { ...form({ town: gzipSync("{}"), picture: jpeg(), meta }), headers: { "cf-connecting-ip": ip } }), env))!+ assert.equal((await share("1.1.1.1")).status, 201)+ assert.equal((await share("1.1.1.1")).status, 201)+ const third = await share("1.1.1.1")+ assert.equal(third.status, 429)+ assert.match(((await third.json()) as { error: string }).error, /wait a minute/)+ assert.equal((await share("2.2.2.2")).status, 201, "another visitor is not held up")+ assert.ok(![...bucket.files.keys()].some((key) => key.includes("1.1.1.1")), "no address is kept")++ // The day's count, without the minute's limit.+ const dayBucket = memoryBucket()+ const daily: Env = { bucket: dayBucket, assets: env.assets }+ const again = async () => (await handle(new Request(`${ORIGIN}/api/towns`, { ...form({ town: gzipSync("{}"), picture: jpeg(), meta }), headers: { "cf-connecting-ip": "3.3.3.3" } }), daily))!+ for (let i = 0; i < DAILY_SHARES; i++) assert.equal((await again()).status, 201)+ assert.equal((await again()).status, 429)+ assert.equal([...dayBucket.files.keys()].filter((key) => key.endsWith(".picture")).length, DAILY_SHARES)+})+test("unknown and malformed links", async () => {const { call } = setup()assert.equal((await call("/api/towns/abcdefgh")).status, 404)