Spaces:
Running
Running
Download static/cornfield.js from princessamygdala/HarvestForTwo: direct link, hf CLI and curl.
- Browser
- Download file 143 kB
-
https://huggingface.co/spaces/princessamygdala/HarvestForTwo/resolve/main/static/cornfield.js
- Command line
-
hf download hf://spaces/princessamygdala/HarvestForTwo/static/cornfield.js
-
curl -L -o cornfield.js https://huggingface.co/spaces/princessamygdala/HarvestForTwo/resolve/main/static/cornfield.js
143 kB
/* ============================================================================
* cornfield.js β real-time browser game engine for the Prosocial Effort task
* (task_pe-cu-nicewebrl).
*
* Design intent (per researcher): WORK should feel STRESSFUL/aversive (the
* effort cost), while REST should feel PLEASANT and ACTIVE β not boring idle
* time. So:
* WORK = harvest N corn under a hot sun: sweat, screen-shake, a timer that
* goes red and pulses, "HURRY!" β a costly chore.
* REST = relax in the shade: stroll around, a puppy follows you, sip
* lemonade with SPACE (hearts!). Equal duration to work, so time is
* not a confound, but it's a genuinely nice break.
*
* Faithful to the Apps & Lockwood prosocial effort paradigm:
* DECISION (4 s): Rest (1 credit) vs Work (2/6/10 credits, harvest N corn),
* for YOU or the OTHER player β choose with <- / ->.
* WORK (10 s): walk onto each corn stalk + SPACE; clear all N or 0 credits.
* REST (10 s): chill -> 1 credit.
* CALIBRATION: harvest as many corn as you can in 10 s (corn respawns) -> max.
* ============================================================================ */
(function () {
"use strict";
// ---- grid / canvas geometry ------------------------------------------------
const COLS = 15, ROWS = 10, TILE = 42;
//: First walkable row in the REST scene. The rest backdrops draw their horizon
//: here, so anything above it is sky and the player must not reach it.
const REST_HORIZON_ROW = ROWS - 4;
//: Stalks per warm-up batch. Six sits in the middle of the task's range
//: (3 to 10), so steps per stalk match: 5.17 in the warm-up against 5.15 for
//: a six-stalk trial.
const CALIB_BATCH = 6;
//: Expected greedy path length per stalk, measured over the grid. Used to
//: keep trial layouts near a constant walk per stalk.
const TARGET_STEPS_PER_STALK = 5.2;
//: How long the empty-soil click stays quiet after a stalk comes in.
//: A participant clearing the field presses SPACE in bursts, so the press
//: right after a successful one usually lands on the soil they just cleared.
//: Those two sounds arriving together was reported as the harvest and the
//: empty click playing at once.
const EMPTY_CLICK_MUTE_MS = 220;
const HUD = 92;
const BOARD_W = COLS * TILE, BOARD_H = ROWS * TILE;
const W = BOARD_W, H = BOARD_H + HUD;
const DEFAULT = { decisionMs: 4000, workMs: 10000, restMs: 10000, feedbackMs: 1800 };
//: How long the outcome screen ignores SPACE. It has to outlast a burst of
//: harvesting presses, not merely the next one: someone racing the clock is
//: pressing every ~60 ms, so a 700 ms lock still let the burst clear the
//: screen at 700 ms of its intended 1800. At 1200 the outcome is readable
//: whatever the participant is doing, and a deliberate press still skips the
//: last third.
const FEEDBACK_LOCK_MS = 1200;
//: How long a gated outcome waits before giving up on the keypress. Only
//: reached if the participant has stopped responding.
const REVEAL_BACKSTOP_MS = 30000;
const STEP_MS = 110;
const C = {
workSky: "#cdd6b0", workSoil: "#9c6b3f", workSoilDark: "#8a5d35",
restSkyTop: "#aee0ff", restSkyBot: "#dff4d6",
grass: "#7cc36b", grassDark: "#6cb35c",
youAccent: "#2ecc71", otherAccent: "#3aa0e8",
panel: "rgba(0,0,0,0.55)", warn: "#ff4d4d", gold: "#ffd23f", white: "#f5f5f5",
};
// ---- avatars (farmer palettes) β participant picks one; partner is distinct -
// A varied cast: gender-coded + neutral, different skin tones, plus fun headwear.
// head: 'straw' | 'crown' | 'mushroom' | 'foxmask' | 'none'
// hair: 'short' | 'long' | 'bun' | 'pigtails' | 'none'
const AVATARS = [
{ name: "Straw-hat", skin: "#f1c27d", overalls: "#3b6fb0", head: "straw", hair: "short", hairCol: "#5a3a1a" },
{ name: "Bun", skin: "#8d5524", overalls: "#b0413b", head: "straw", hair: "bun", hairCol: "#241509" },
{ name: "Longhair", skin: "#ffdbac", overalls: "#2e8b57", head: "none", hair: "long", hairCol: "#caa24a" },
{ name: "Bearded", skin: "#c68642", overalls: "#6a4fb0", head: "none", hair: "short", hairCol: "#1c1c1c", beard: true },
{ name: "Specs", skin: "#f0c8a0", overalls: "#c0563f", head: "none", hair: "short", hairCol: "#3a2a18", glasses: true },
{ name: "Princess", skin: "#e8b98a", overalls: "#d24b8a", head: "crown", hair: "long", hairCol: "#3a2412" },
{ name: "Mushroom", skin: "#ffe0bd", overalls: "#7a8a4a", head: "mushroom", hair: "none" },
{ name: "Fox mask", skin: "#7a4a28", overalls: "#2f9e9e", head: "foxmask", hair: "short", hairCol: "#141414" },
{ name: "Beard+bald", skin: "#5c3a1e", overalls: "#caa53a", head: "none", hair: "none", beard: true },
{ name: "Pigtails", skin: "#f1c27d", overalls: "#4a8fbf", head: "none", hair: "pigtails", hairCol: "#7a3a18" },
];
// 4 partner-avatar palettes (distinct from the participant's own AVATARS,
// so the two never look identical). Drawn via the same theme-dispatched
// drawFarmerAt as everything else, so a firefly-theme partner shows as one
// of 4 night-explorer palettes, a jelly-theme partner as one of 4 snorkeler
// palettes, etc.
// NOTE: intentionally a separate table from PARTNER_PAL (below) β PARTNER_PAL
// renders the partner sprite in the live game (splash/HUD/decision scene);
// this table is only for the matching-reveal screen. Not meant to be kept
// in sync with PARTNER_PAL or with each other.
const PARTNER_AVATAR_PALETTES = [
{ name: "Partner A", skin: "#d9a066", overalls: "#3f5d7a", head: "straw", hair: "short", hairCol: "#3a2a1a" },
{ name: "Partner B", skin: "#c68642", overalls: "#4a6fa5", head: "none", hair: "long", hairCol: "#2a2015" },
{ name: "Partner C", skin: "#b98457", overalls: "#8a6a9a", head: "none", hair: "bun", hairCol: "#2a1810", glasses: true },
{ name: "Partner D", skin: "#8d5524", overalls: "#5a8a6a", head: "none", hair: "none", beard: true },
];
const PARTNER_PAL = { skin: "#e8c3a0", overalls: "#7a8a99", head: "straw", hair: "short", hairCol: "#6a6f78" };
const cfg = { avatar: 0, partnerAvatar: null, partnerName: "P2",
theme: "harvest" };
//: The partner as the participant met them. The matching screen reveals one
//: of PARTNER_AVATAR_PALETTES and the live game drew PARTNER_PAL, so the
//: person standing by the field looked like somebody else than the one on
//: the reveal, and each block's partner looked like the last one's.
//: PARTNER_PAL stays as the fallback for a canvas mounted before configure()
//: has carried an index.
function partnerPal() {
const i = cfg.partnerAvatar;
return (typeof i === "number")
? PARTNER_AVATAR_PALETTES[i % PARTNER_AVATAR_PALETTES.length]
: PARTNER_PAL;
}
// ---- themes (same mechanic every theme; only vocab/colors/character/scene
// content change). Keys mirror themes.py's THEMES dict. "boxes" stays bland.
const THEME_STYLE = {
harvest: { target: "corn", targetOne: "corn", verb: "harvest", verbIng: "harvesting",
pastLabel: "Harvested", machine: "harvester", itemEmoji: "π½", titleWord: "Harvest",
soil: "#9c6b3f", soilDark: "#8a5d35", decorate: true,
character: "farmer", puppyAccessory: null,
skyByTod: null, sunByTod: null,
restBackdrop: "farm",
finishContainer: "crate" },
jelly: { target: "jellyfish", targetOne: "jellyfish", verb: "catch", verbIng: "catching",
pastLabel: "Caught", machine: "net", itemEmoji: "πͺΌ", titleWord: "Jellyfishing",
soil: "#0f3547", soilDark: "#0b2a38", decorate: false,
character: "snorkeler", puppyAccessory: "snorkel",
skyByTod: { morning: ["#bfe8ff", "#8fd8e8"], evening: ["#123a55", "#0d2a3f"] },
sunByTod: { morning: { col: "#eaffff", glow: "rgba(200,240,255,0.35)" },
evening: { col: "#9fd0ff", glow: "rgba(140,190,255,0.3)" } },
restBackdrop: "reef",
finishContainer: "net" },
firefly: { target: "fireflies", targetOne: "firefly", verb: "catch", verbIng: "catching",
pastLabel: "Caught", machine: "jar", itemEmoji: "β¨", titleWord: "Firefly Catching",
soil: "#161a3a", soilDark: "#10132c", decorate: false,
character: "explorer", puppyAccessory: "glow-collar",
// NOTE: "morning" slot = the displayed "Evening" block (dusk);
// "evening" slot = the displayed "Night" block (deep dark).
// Both are always dark -- fireflies are never shown in daylight.
skyByTod: { morning: ["#3a2a55", "#5a3a20"], evening: ["#0a0e2a", "#05071a"] },
sunByTod: { morning: { col: "#ffe9b0", glow: "rgba(255,220,150,0.25)" },
evening: { col: "#e8ecff", glow: "rgba(220,225,255,0.25)" } },
restBackdrop: "meadowNight",
finishContainer: "jar" },
boxes: { target: "boxes", targetOne: "box", verb: "click", verbIng: "clicking",
pastLabel: "Clicked", machine: "clicker", itemEmoji: "β«οΈ", titleWord: "Box",
soil: "#bdbdbd", soilDark: "#aaaaaa", decorate: false,
character: "plain", puppyAccessory: null,
skyByTod: { morning: ["#d6d6d6", "#d6d6d6"], evening: ["#d6d6d6", "#d6d6d6"] },
sunByTod: { morning: { col: "#cfcfcf", glow: "rgba(200,200,200,0.2)" },
evening: { col: "#cfcfcf", glow: "rgba(200,200,200,0.2)" } },
restBackdrop: "plain",
finishContainer: "stack" },
};
function themeStyle() { return THEME_STYLE[cfg.theme] || THEME_STYLE.harvest; }
let canvas, ctx, raf = null, trial = null, keys = {}, lastStep = 0, lastFrame = 0;
let paused = false, pausedAt = 0;
//: Credit counts are written in a dozen places and the word was hard-coded
//: in most of them, so the decision screen read "2 credit" on every trial
//: (REST_CREDIT is 2). Same for the target count, which matters as soon as a
//: theme has a real singular ("1 boxes").
function creditsWord(n) { return Math.abs(n) === 1 ? "credit" : "credits"; }
function targetWord(n, th) { return n === 1 ? th.targetOne : th.target; }
function emit(name, data) {
if (typeof emitEvent === "function") emitEvent(name, data);
else console.warn("emitEvent unavailable", name, data);
}
// ---- sound (synthesized via WebAudio; no asset files) ----------------------
const Sound = (function () {
let actx = null, muted = false;
function ctx() {
if (!actx) { try { actx = new (window.AudioContext || window.webkitAudioContext)(); } catch (e) {} }
return actx;
}
function tone(freq, dur, type, vol, slideTo, delay) {
const a = ctx(); if (!a) return;
const t0 = a.currentTime + (delay || 0);
const o = a.createOscillator(), g = a.createGain();
o.type = type || "sine"; o.frequency.setValueAtTime(freq, t0);
if (slideTo) o.frequency.linearRampToValueAtTime(slideTo, t0 + dur);
g.gain.setValueAtTime(vol || 0.12, t0);
g.gain.exponentialRampToValueAtTime(0.001, t0 + dur);
o.connect(g); g.connect(a.destination); o.start(t0); o.stop(t0 + dur);
}
function noise(dur, vol) {
const a = ctx(); if (!a) return;
const n = a.sampleRate * dur, buf = a.createBuffer(1, n, a.sampleRate), d = buf.getChannelData(0);
for (let i = 0; i < n; i++) d[i] = (Math.random() * 2 - 1) * (1 - i / n);
const s = a.createBufferSource(), g = a.createGain();
s.buffer = buf; g.gain.value = vol || 0.1; s.connect(g); g.connect(a.destination); s.start();
}
// a wet "shhhlp" slurp: white noise through a band-pass filter that sweeps upward
function slurp() {
const a = ctx(); if (!a) return;
const dur = 0.34, t0 = a.currentTime;
const n = a.sampleRate * dur, buf = a.createBuffer(1, n, a.sampleRate), d = buf.getChannelData(0);
for (let i = 0; i < n; i++) d[i] = Math.random() * 2 - 1;
const src = a.createBufferSource(); src.buffer = buf;
const bp = a.createBiquadFilter(); bp.type = "bandpass"; bp.Q.value = 7;
bp.frequency.setValueAtTime(280, t0);
bp.frequency.exponentialRampToValueAtTime(1500, t0 + dur); // rising suction
const g = a.createGain();
g.gain.setValueAtTime(0.0001, t0);
g.gain.exponentialRampToValueAtTime(0.22, t0 + 0.06);
g.gain.exponentialRampToValueAtTime(0.001, t0 + dur);
src.connect(bp); bp.connect(g); g.connect(a.destination); src.start(t0);
tone(160, 0.10, "sine", 0.12, 110, 0.26); // little gulp at the end
}
const lib = {
button: () => tone(440, 0.09, "square", 0.10, 700),
harvest: () => { tone(540, 0.10, "triangle", 0.16, 760); noise(0.06, 0.05); },
machine: () => tone(120, 0.18, "sawtooth", 0.10, 90), // motor turning over
walk: () => tone(150, 0.04, "sine", 0.05),
earn: () => { tone(660, 0.10, "square", 0.13); tone(990, 0.16, "square", 0.13, null, 0.09); }, // ka-ching
fail: () => tone(320, 0.32, "sawtooth", 0.15, 120), // mΓΆp
hurry: () => tone(900, 0.06, "square", 0.09),
sip: () => slurp(), // wet "shhhlp" suction
// puppy "yip!": a noise transient + a quick chirp that bends up then down (woof-ish)
bark: () => { noise(0.03, 0.08); tone(380, 0.06, "sawtooth", 0.18, 820);
tone(760, 0.08, "sawtooth", 0.15, 320, 0.05); },
apple: () => { tone(700, 0.08, "triangle", 0.12, 520); noise(0.05, 0.05); }, // pluck
sit: () => tone(400, 0.30, "sine", 0.10, 300), // contented sigh
};
return {
play(n) { if (muted) return; try { const a = ctx(); if (a && a.state === "suspended") a.resume(); (lib[n] || (() => {}))(); } catch (e) {} },
resume() { try { const a = ctx(); if (a && a.state === "suspended") a.resume(); } catch (e) {} },
setMuted(m) { muted = !!m; },
isMuted() { return muted; },
};
})();
// ---- public API ------------------------------------------------------------
window.Cornfield = {
//: `tod` is the scene that is coming, "day" or "night". Given one, the
//: canvas is left blank in that scene's own colour instead of showing the
//: idle world: the Python side used to call clear() right after this, a
//: separate round trip, so a mount painted the idle field and then wiped
//: it to a slab a tenth of a second later. That is the flash reported
//: between the instruction screens and the practice, and after the warm-up.
//: The idle frame is still DRAWN, inside this same call, so the theme
//: dispatch under it stays covered by cornfield_js_harness.mjs; the browser
//: paints nothing until this call returns, so nobody sees it.
mount(containerId, tod) {
const host = document.getElementById(containerId);
if (!host) { console.error("Cornfield: container not found", containerId); return; }
const bg = (tod === "night") ? "#0d1324" : "#2b3345";
host.innerHTML = "";
canvas = document.createElement("canvas");
canvas.width = W; canvas.height = H; canvas.id = "pe_canvas";
canvas.style.cssText = "width:100%;max-width:" + W + "px;height:auto;" +
"border-radius:10px;display:block;margin:0 auto;background:" + bg +
";touch-action:none;outline:none;";
canvas.tabIndex = 0;
host.appendChild(canvas);
ctx = canvas.getContext("2d");
canvas.focus();
bindKeys();
bindVisibility();
drawWorld({ phase: "idle" });
if (tod !== undefined) {
cancel(); trial = null;
ctx.fillStyle = bg; ctx.fillRect(0, 0, W, H);
}
},
configure(opts) { Object.assign(cfg, opts || {}); },
setMuted(m) { Sound.setMuted(m); },
pause(reason) { // freeze the game + countdown
if (paused || !trial || trial.phase === "done") return;
paused = true; pausedAt = now(); cancel();
// log it: a participant who pauses mid-harvest has had extra thinking or
// resting time, which nothing else in the record would reveal. `reason`
// separates the Pause button from the tab having gone away by itself.
if (trial.pauses) trial.pauses.push({ atMs: pausedAt - trial.startMs,
phase: trial.phase,
reason: reason || "button" });
if (trial._fbTimer) { // also hold the feedback auto-advance
trial._fbRemain = Math.max(0, REVEAL_BACKSTOP_MS
- (now() - trial.feedbackStart));
clearTimeout(trial._fbTimer); trial._fbTimer = null;
}
},
resume() {
if (!paused) return;
const delta = now() - pausedAt; paused = false;
if (trial && trial.pauses && trial.pauses.length) {
const last = trial.pauses[trial.pauses.length - 1];
if (last.ms == null) last.ms = delta;
}
if (trial) {
trial.phaseStart += delta; // shift timers so the pause "didn't happen"
if (trial.feedbackStart) trial.feedbackStart += delta;
if (trial._fbRemain != null) { trial._fbTimer = setTimeout(emitResult, trial._fbRemain); trial._fbRemain = null; }
if (trial.phase !== "done") loop();
}
},
numAvatars() { return AVATARS.length; },
//: How many partner faces this app has, for tools that render
//: one PNG each so the other task can show them.
numPartnerAvatars() { return PARTNER_AVATAR_PALETTES.length; },
cover(canvasId) { splash(canvasId, "cover"); },
finish(canvasId) { splash(canvasId, "finish"); },
startTrial(spec) { cancel(); keys = {}; trial = newTrial(spec); canvas && canvas.focus(); drawWorld(trial); loop(); },
startCalibration(spec) { cancel(); keys = {}; trial = newCalibration(spec); canvas && canvas.focus(); drawWorld(trial); loop(); },
stop() { cancel(); },
// `tod` picks the blanking colour. Without it the canvas was blanked to
// one mid slab, which on a night block is brighter than the sky that
// follows it, so clearing to "hide a flash" produced one.
clear(tod) {
cancel(); trial = null;
if (!ctx) return;
ctx.fillStyle = (tod === "night") ? "#0d1324" : "#2b3345";
ctx.fillRect(0, 0, W, H);
},
// draw a standalone farmer preview into a mini-canvas (avatar chooser)
preview(canvasId, idx) {
const cv = document.getElementById(canvasId);
if (!cv) return;
const g = cv.getContext("2d");
const th = themeStyle();
g.clearRect(0, 0, cv.width, cv.height);
g.fillStyle = th.soil; g.fillRect(0, 0, cv.width, cv.height);
g.fillStyle = th.soilDark; g.fillRect(0, cv.height - 16, cv.width, 16);
drawFarmerAt(g, cv.width / 2, cv.height / 2 + 16, 0, 0, "rest",
AVATARS[idx % AVATARS.length], 1.7);
},
// draw the partner's avatar for the matching-reveal screen (one of 4
// fixed palettes, theme-dispatched the same way as the participant's own)
partnerAvatarPreview(canvasId, idx) {
const cv = document.getElementById(canvasId);
if (!cv) return;
const g = cv.getContext("2d");
const th = themeStyle();
g.clearRect(0, 0, cv.width, cv.height);
g.fillStyle = th.soil; g.fillRect(0, 0, cv.width, cv.height);
g.fillStyle = th.soilDark; g.fillRect(0, cv.height - 16, cv.width, 16);
drawFarmerAt(g, cv.width / 2, cv.height / 2 + 16, 0, 0, "rest",
PARTNER_AVATAR_PALETTES[idx % PARTNER_AVATAR_PALETTES.length], 1.7);
},
// small themed illustration for the mission-statement instruction screen:
// the field + a simple coins-to-cash visual
missionImage(canvasId) {
const cv = document.getElementById(canvasId);
if (!cv) return;
const g = cv.getContext("2d"), w = cv.width, h = cv.height, old = ctx; ctx = g;
const th = themeStyle();
const pal = SPLASH_PALETTE[cfg.theme] || SPLASH_PALETTE.harvest;
const sky = g.createLinearGradient(0, 0, 0, h);
sky.addColorStop(0, pal.sky[0]); sky.addColorStop(1, pal.sky[1]);
g.fillStyle = sky; g.fillRect(0, 0, w, h);
g.fillStyle = th.soil; g.fillRect(0, h * 0.62, w, h * 0.38);
drawFarmerAt(g, w * 0.28, h * 0.8, 0, 0, "rest", AVATARS[0], 1.6);
// a few coins arcing up into a dollar bill (simple vector shapes)
const coinCol = "#ffd23f", coinStroke = "#c98a2b";
[[w * 0.58, h * 0.55], [w * 0.68, h * 0.42], [w * 0.78, h * 0.5]].forEach(p => {
g.fillStyle = coinCol; g.beginPath(); g.arc(p[0], p[1], 10, 0, 7); g.fill();
g.strokeStyle = coinStroke; g.lineWidth = 2; g.stroke();
});
g.fillStyle = "#3a8a4a"; roundRect(w * 0.62, h * 0.18, w * 0.24, h * 0.16, 6); g.fill();
g.strokeStyle = "#2a6a38"; g.lineWidth = 2; g.strokeRect(w * 0.62, h * 0.18, w * 0.24, h * 0.16);
g.fillStyle = "#e8f5e8"; g.font = "bold 16px system-ui, sans-serif"; g.textAlign = "center";
g.fillText("$", w * 0.74, h * 0.29);
ctx = old;
},
// side-by-side WORK vs REST preview for the work-or-rest explainer screen.
// avatarIdx: the participant's own chosen avatar (same AVATARS table as
// preview()/mount()'s configure({avatar}) -- pass whatever is already
// stashed as app.storage.user["avatar"] on the Python side); defaults to
// whatever avatar configure() was last called with, for callers that
// haven't wired the explicit index through yet.
// Two stills for the night harvest's instruction slides, drawn from the
// game's own art so the screens look like the thing they describe. Emoji
// were standing in for these.
//
// 1: the partner's field at night, the participant at its edge with a
// bagful, and a "?" where the amount would be.
nightFieldPreview(canvasId, avatarIdx) {
const cv = document.getElementById(canvasId);
if (!cv) return;
const g = cv.getContext("2d"), w = cv.width, h = cv.height, old = ctx;
ctx = g;
const th = themeStyle();
const av = AVATARS[(typeof avatarIdx === "number" ? avatarIdx : cfg.avatar)
% AVATARS.length];
const sky = g.createLinearGradient(0, 0, 0, h * 0.68);
sky.addColorStop(0, "#0b1020"); sky.addColorStop(1, "#1b2747");
g.fillStyle = sky; g.fillRect(0, 0, w, h * 0.68);
g.fillStyle = "#e9eefb";
for (let i = 0; i < 22; i++) {
const sx = (i * 97) % w, sy = (i * 53) % (h * 0.6);
g.fillRect(sx, sy, 1.6, 1.6);
}
// moon
g.fillStyle = "#f2e9c8"; circle(w - 34, 28, 11);
g.fillStyle = "#0b1020"; circle(w - 29, 24, 10);
// their field
g.fillStyle = "#17351c"; g.fillRect(0, h * 0.68, w, h * 0.32);
for (let i = 0; i < 9; i++) drawMiniCorn(w * 0.34 + i * 20, h * 0.80);
drawFarmerAt(g, w * 0.16, h * 0.86, 0, 0, "rest", av, 1.25);
g.fillStyle = "rgba(0,0,0,0.55)";
roundRect(w * 0.30, h * 0.58, w * 0.56, 22, 8); g.fill();
g.fillStyle = "#ffd23f"; g.font = "bold 12px system-ui, sans-serif";
g.textAlign = "center";
g.fillText("YOUR PARTNER'S FIELD", w * 0.58, h * 0.58 + 15);
g.fillStyle = "#ff8f8f"; g.font = "bold 26px system-ui, sans-serif";
g.fillText("?", w * 0.90, h * 0.86);
ctx = old;
},
// 2: credits becoming money.
payoutPreview(canvasId) {
const cv = document.getElementById(canvasId);
if (!cv) return;
const g = cv.getContext("2d"), w = cv.width, h = cv.height, old = ctx;
ctx = g;
const th = themeStyle();
g.fillStyle = "#101828"; g.fillRect(0, 0, w, h);
const cy = h * 0.52;
for (let i = 0; i < 4; i++) drawMiniCorn(w * 0.10 + i * 20, cy + 6);
g.fillStyle = "#9fb0c4"; g.font = "bold 22px system-ui, sans-serif";
g.textAlign = "center";
g.fillText("\u2192", w * 0.44, cy + 8);
// a small stack of coins
for (let i = 0; i < 3; i++) {
const cx2 = w * 0.62 + i * 26;
g.fillStyle = "#b8860b"; circle(cx2, cy + 4, 13);
g.fillStyle = C.gold; circle(cx2, cy, 13);
g.fillStyle = "#8a6a00"; g.font = "bold 13px system-ui, sans-serif";
g.fillText("$", cx2, cy + 5);
}
g.fillStyle = "#7fd2a8"; g.font = "bold 13px system-ui, sans-serif";
g.fillText("credits \u2192 real money", w / 2, h - 10);
ctx = old;
},
workRestPreview(canvasId, avatarIdx) {
const cv = document.getElementById(canvasId);
if (!cv) return;
const g = cv.getContext("2d"), w = cv.width, h = cv.height, old = ctx; ctx = g;
const th = themeStyle();
const av = AVATARS[(typeof avatarIdx === "number" ? avatarIdx : cfg.avatar) % AVATARS.length];
const half = w / 2;
// WORK half
g.fillStyle = th.decorate ? "#cdd6b0" : (th.skyByTod ? th.skyByTod.morning[0] : "#cdd6b0");
g.fillRect(0, 0, half, h);
g.fillStyle = th.soil; g.fillRect(0, h * 0.55, half, h * 0.45);
drawFarmerAt(g, half * 0.5, h * 0.78, 0, 0, "work", av, 1.3);
// NOTE: drawTarget()'s themed sprite fns (drawJelly/drawFirefly/drawBox/drawCorn)
// derive position purely from k.c/k.r tile coords (k.c * TILE, HUD + k.r * TILE) β
// they don't read ad-hoc x/y fields, so calling drawTarget with a fake {c:0,r:0}
// cell would silently render pinned to the HUD corner instead of here. Fall back
// to drawing the theme's collectible glyph directly, same as the splash screen does.
g.font = "22px system-ui, sans-serif"; g.textAlign = "center"; g.fillStyle = "#000";
g.fillText(th.itemEmoji || "β«οΈ", half * 0.5, h * 0.4);
g.fillStyle = "#1c2533"; g.fillRect(0, 0, half, 20);
g.fillStyle = "#fff"; g.font = "bold 12px system-ui, sans-serif"; g.textAlign = "center";
g.fillText("WORK", half * 0.5, 14);
// REST half β theme-dispatch sky/ground the same way drawRestField() picks
// among drawRestFieldFarm/Reef/MeadowNight/Plain for the real REST scene,
// so e.g. jelly/firefly/boxes don't show a bright grassy-green REST preview.
let restSky = "#dff4d6", restGround = "#7cc36b"; // farm (decorate themes)
if (!th.decorate) {
if (th.restBackdrop === "reef") { restSky = th.skyByTod.morning[0]; restGround = "#e8d9a8"; } // water / sand
else if (th.restBackdrop === "meadowNight") { restSky = th.skyByTod.morning[0]; restGround = "#1c2e1c"; } // night sky / dark grass
else { restSky = "#e8e8e8"; restGround = "#d0d0d0"; } // plain (boxes)
}
g.fillStyle = restSky; g.fillRect(half, 0, half, h);
g.fillStyle = restGround; g.fillRect(half, h * 0.8, half, h * 0.2);
drawFarmerAt(g, half * 1.5, h * 0.78, 0, 0, "rest", av, 1.3);
g.fillStyle = "#173a2a"; g.fillRect(half, 0, half, 20);
g.fillStyle = "#fff"; g.fillText("REST", half * 1.5, 14);
ctx = old;
},
_debug: { THEME_STYLE, themeStyle },
};
// ---- input -----------------------------------------------------------------
function bindKeys() {
window.addEventListener("keydown", onKey, true);
window.addEventListener("keyup", onKeyUp, true);
}
//: A hidden tab has its requestAnimationFrame suspended, but the trial clock
//: is wall-clock (`now() - trial.phaseStart`). A participant who switched
//: tab, took a notification or had the window covered came back to a loop
//: that resumed, read the elapsed time and failed the trial on the spot --
//: recorded as an ordinary work failure, which in an effort task is a
//: statement about what they were willing to do. The Pause button already
//: freezes and shifts every timer, so reuse it, and hold the resume until
//: the participant asks for it rather than dropping them back into a clock
//: that has already started.
let autoPaused = false;
function onVisibility() {
if (document.hidden) {
if (trial && !paused && trial.phase !== "done" && trial.phase !== "idle") {
autoPaused = true;
window.Cornfield.pause("hidden");
}
} else if (autoPaused) {
drawAwayOverlay();
}
}
// A named handler, because mount() runs once per stage and addEventListener
// only deduplicates the same function reference.
function bindVisibility() {
document.addEventListener("visibilitychange", onVisibility);
}
function drawAwayOverlay() {
if (!ctx) return;
ctx.save();
ctx.fillStyle = "rgba(10,14,22,0.82)"; ctx.fillRect(0, HUD, W, BOARD_H);
ctx.textAlign = "center"; ctx.fillStyle = C.white;
ctx.font = "bold 26px system-ui, sans-serif";
ctx.fillText("Paused while you were away", W / 2, HUD + BOARD_H / 2 - 10);
ctx.font = "16px system-ui, sans-serif";
ctx.fillText("Press SPACE when you are ready to carry on.", W / 2, HUD + BOARD_H / 2 + 22);
ctx.restore();
}
const GAME_KEYS = { ArrowUp: 1, ArrowDown: 1, ArrowLeft: 1, ArrowRight: 1, " ": 1, Spacebar: 1 };
//: Minimum gap between two accepted presses of the SAME key. Rejected presses
//: are still logged, with rejected: 1, so the rate can be measured rather than
//: silently discarded.
const MIN_PRESS_GAP_MS = 50;
const lastPressAt = {};
function onKey(e) {
const k = e.key === "Spacebar" ? " " : e.key;
if (!GAME_KEYS[e.key] && !GAME_KEYS[k]) return;
if (!trial) return;
e.preventDefault(); e.stopPropagation();
if (autoPaused) { // the first press only comes back
autoPaused = false; window.Cornfield.resume();
return;
}
if (paused) return; // ignore game input while paused
Sound.resume(); // unlock audio on first interaction
if (!keys[k]) { // discrete press only (holding does NOT repeat)
// The keys[] guard stops auto-repeat but not a rapid keydown/keyup cycle,
// whether from a macro, a held key the OS releases between repeats, or a
// participant drumming. One pilot session logged 3008 key events in a
// single trial at a median gap of 0 ms and reached 100% success that way,
// which defeats the effort manipulation the task is built on: a trial
// stops measuring willingness to work and measures input rate instead.
// A human's fastest deliberate repeat is around 90 ms, so 50 ms rejects
// machine-speed input while leaving real fast pressing untouched.
const tnow = now();
const gap = tnow - (lastPressAt[k] || -1e9);
if (gap < MIN_PRESS_GAP_MS) {
if (trial.keyLog) {
trial.keyLog.push({ t: Math.round(tnow - trial.startMs), ph: trial.phase,
k: k, rejected: 1 });
}
trial.floodRejects = (trial.floodRejects || 0) + 1;
keys[k] = true;
return;
}
lastPressAt[k] = tnow;
if (trial.keyLog) trial.keyLog.push({ t: Math.round(tnow - trial.startMs), ph: trial.phase, k: k });
handleFirstPress(k);
}
keys[k] = true;
}
function onKeyUp(e) { const k = e.key === "Spacebar" ? " " : e.key; keys[k] = false; }
function handleFirstPress(k) {
if (!trial) return;
if (trial.phase === "decision") {
if (k === "ArrowLeft") choose("left");
else if (k === "ArrowRight") choose("right");
} else if (trial.phase === "work" || trial.phase === "calib") {
if (k === " ") tryHarvest();
else moveStep(k); // one tile per press
} else if (trial.phase === "rest") {
if (k === " ") doRestAction();
else moveStep(k);
} else if (trial.phase === "feedback") {
// A press cannot dismiss the outcome for the first FEEDBACK_LOCK_MS.
//
// A participant harvesting against the clock is pressing SPACE rapidly,
// and the outcome screen arrives mid-burst: the next press cleared it
// before it could be read, so they could not tell whether they finished
// in time or earned nothing. That is the one thing the screen exists to
// say, and losing it removes the feedback the whole trial depends on.
if (k === " " && (now() - trial.feedbackStart) >= FEEDBACK_LOCK_MS) {
emitResult();
}
}
}
// ---- seeded randomness -----------------------------------------------------
// The trial ORDER is already seeded per participant in effort_design.py, but
// what happens *inside* a trial (where the corn lands, how many presses each
// stalk takes) used to be bare Math.random(): different every run and never
// recorded, so the actual effort demanded by a trial could not be recovered
// from the data. Each trial now carries a seed from Python and draws from
// this generator, and the resulting layout is logged with the trial.
function mulberry32(a) {
return function () {
a |= 0; a = (a + 0x6D2B79F5) | 0;
let t = Math.imul(a ^ (a >>> 15), 1 | a);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
let rnd = Math.random; // replaced per trial when a seed is given
// ---- trial runtime ---------------------------------------------------------
function newTrial(spec) {
const t = Object.assign({
kind: "trial", phase: "decision",
decisionMs: DEFAULT.decisionMs, workMs: DEFAULT.workMs, restMs: DEFAULT.restMs,
restCredit: 2, randomID: "Player 2",
}, spec);
if (t.randomID) cfg.partnerName = t.randomID;
t.startMs = now(); t.phaseStart = t.startMs;
t.player = { c: (COLS / 2) | 0, r: (ROWS - 2) | 0, face: "up", frame: 0 };
t.harvested = 0; t.harvestTimes = []; t.keyLog = [];
t.choice = null; t.decisionRT = null; t.success = false; t.credits = 0;
t.corn = [];
t.fx = { shake: 0, parts: [] }; // work: sweat/dust + shake
t.rest = null; // built when rest starts
t.pauses = []; // {atMs, phase, ms} per pause
rnd = (spec && spec.seed != null) ? mulberry32(spec.seed) : Math.random;
return t;
}
// What a successful harvest pays. Night 2 pays the partner's amount when you
// chose to leave it for them; everything else pays the trial's own reward.
function payout(t) {
// The harvest-speed block pays the same whichever card is chosen; what varies is
// what spoils out of the beneficiary's store, which is not the
// participant's own credit total unless the load was bound for them.
if (t.harvestSpeed) return t.reward;
// The last field carries reward 0 and pays through workCredit, so the
// work banner read "0 credits for 6 corn" while the card promised 1.
if (t.nightWatch) return t.workCredit;
// An uncertain day-2 offer pays the draw, not the midpoint shown on the
// card. Without this the range resolves to its own centre every time.
if (t.rewardDrawn != null) return t.rewardDrawn;
return (t.night === 2 && t.choice === "work_partner") ? t.partnerReward : t.reward;
}
function newCalibration(spec) {
const t = {
kind: "calib", phase: "calib",
workMs: (spec && spec.workMs) || DEFAULT.workMs, repIndex: (spec && spec.repIndex) || 0,
};
t.startMs = now(); t.phaseStart = t.startMs;
t.player = { c: (COLS / 2) | 0, r: (ROWS - 2) | 0, face: "up", frame: 0 };
t.harvested = 0; t.harvestTimes = []; t.keyLog = [];
// A BATCH the size of a typical trial, refreshed when cleared. The warm-up
// used to place 28 stalks at once and respawn one at a time, so the nearest
// stalk was always a step or two away: 1.8 steps per stalk against 4.1 to
// 6.3 in a real trial. The same count therefore cost about twice the
// presses in the task, and an effort level set at 80% of the warm-up count
// demanded closer to 160% of the warm-up effort. Clearing successive
// batches gives the warm-up the same geometry as a trial, so the count it
// measures is a fraction of capability rather than of a denser field.
t.corn = scatterCorn(CALIB_BATCH, t.player);
t.fx = { shake: 0, parts: [] };
return t;
}
// ---- decision --------------------------------------------------------------
function choose(side) {
if (trial.phase !== "decision" || trial.choice) return;
const isWork = (side === trial.workSide);
// guided practice: only the instructed choice works this round
if (trial.guide && (isWork ? "work" : "rest") !== trial.guide) { Sound.play("button"); return; }
Sound.play("button");
trial.decisionRT = Math.round(now() - trial.phaseStart);
// The side pressed, kept verbatim. The selection tick used to be derived
// from the choice NAME (t.choice === "work"), which silently broke for
// every block that names its choices anything else: night 2 ("work_self"
// /"work_partner") and harvest speed ("quick"/"slow") both drew the tick
// on the wrong card on every trial.
trial.chosenSide = side;
// Night 2 has no rest option: both cards cost the same effort and the side
// you pick decides who is paid, not whether you work.
// Harvest speed: both cards are work and they cost DIFFERENT effort, so
// the choice sets how much there is to collect. workSide is the QUICK card.
if (trial.nightWatch) {
// Named work and rest like every other block, so one set of choice
// labels runs through the whole session and the analysis. What rest
// means here is that you fill your bag and walk home, which pays a
// fixed amount and leaves their field standing.
trial.choice = isWork ? "work" : "rest";
// Provisional. A failed harvest counts as not having brought the field
// in, so the larger loss applies, which is what _bank_credits does.
// Without the correction below the screen told them a failure cost the
// partner 2 while the server took 14.
trial.lostNow = isWork ? trial.lossWorkDrawn : trial.lossSleepDrawn;
} else if (trial.harvestSpeed) {
trial.choice = isWork ? "quick" : "slow";
trial.required = isWork ? trial.requiredQuick : trial.requiredSlow;
trial.spoiledNow = isWork ? trial.spoiled : 0;
} else {
trial.choice = (trial.night === 2) ? (isWork ? "work_self" : "work_partner")
: (isWork ? "work" : "rest");
}
// brief confirmation: keep showing the decision screen (chosen card outlined) for a
// moment, then start the chosen phase
setTimeout(startChosenPhase, 420);
}
function startChosenPhase() {
if (!trial || trial.phase !== "decision") return;
if (trial.choice !== "rest") { // "slow" and "quick" are both work
trial.phase = "work"; trial.phaseStart = now();
trial.corn = scatterCornBalanced(trial.required, trial.player);
} else {
trial.phase = "rest"; trial.phaseStart = now();
buildRest(trial);
}
}
// ---- WORK: harvest ---------------------------------------------------------
function tryHarvest() {
// you must be standing ON a corn and press SPACE β one discrete click per corn
const had = harvestNear(trial.player.c, trial.player.r, 0);
if (had) { trial.lastHarvestAt = now(); return; }
if (now() - (trial.lastHarvestAt ?? -1e9) < EMPTY_CLICK_MUTE_MS) return;
Sound.play("button"); // a click on empty soil still "clicks"
}
function harvestNear(c, r, radius) {
let best = -1, bestd = 99;
for (let i = 0; i < trial.corn.length; i++) {
const k = trial.corn[i];
if (k.done) continue;
const d = Math.max(Math.abs(k.c - c), Math.abs(k.r - r));
if (d <= radius && d < bestd) { bestd = d; best = i; }
}
if (best < 0) return false;
const k = trial.corn[best];
k.hits = (k.hits || 0) + 1;
k.jit = now();
const cx = k.c * TILE + TILE / 2, cy = HUD + k.r * TILE + TILE / 2;
// One press per stalk, so it always catches. The multi-press "balky
// harvester" was removed: it cost ~16% of max_boxes, which is what pushed
// four distinct effort levels out of the available integer range.
// it caught β harvest!
k.done = true; k.pop = now();
trial.harvested++;
trial.harvestTimes.push(Math.round(now() - trial.phaseStart));
trial.fx.shake = 6;
trial.fx.glow = now(); // beneficiary avatar lights up
spawnParts(trial, cx, cy, "dust", 6);
Sound.play("harvest");
if (trial.kind === "calib") {
// refresh the whole batch only once it is cleared, so the walk to the
// next stalk is as long as it would be in a trial
const left = trial.corn.filter(k => !k.done).length;
if (left === 0) {
trial.corn = scatterCorn(CALIB_BATCH, trial.player);
}
}
return true;
}
//: Greedy nearest-first path length through a set of stalks, in tiles. This
//: is what a trial actually costs to clear, and it is what the effort level
//: is meant to be proportional to.
function pathLength(cells, player) {
let p = { c: player.c, r: player.r }, left = cells.slice(), total = 0;
while (left.length) {
let bi = 0, bd = 1e9;
for (let i = 0; i < left.length; i++) {
const d = Math.abs(left[i].c - p.c) + Math.abs(left[i].r - p.r);
if (d < bd) { bd = d; bi = i; }
}
total += bd; p = left[bi]; left.splice(bi, 1);
}
return total;
}
//: Lay out n stalks so the walk is close to what n stalks SHOULD cost.
//:
//: Positions were drawn purely at random, so two trials at the same effort
//: level could differ by a factor of two in walking distance, and with only
//: 24 trials per beneficiary the draw could hand one side consistently
//: harder trials. A pilot participant reported exactly that, and two of eight
//: sessions show it: the same stalk count costing 2 to 4 more presses each on
//: partner trials. Effort demanded was identical to two decimal places, so
//: the difference was entirely in the layout.
//:
//: Drawing several candidate layouts and keeping the one closest to the
//: expected path length keeps positions varied while removing the drift.
function scatterCornBalanced(n, player, tries) {
const want = TARGET_STEPS_PER_STALK * n;
let best = null, bestErr = Infinity;
for (let i = 0; i < (tries || 12); i++) {
const cand = scatterCorn(n, player);
const err = Math.abs(pathLength(cand, player) - want);
if (err < bestErr) { bestErr = err; best = cand; }
}
return best;
}
//: Tiles the partner bubble covers in the work scene. A stalk placed here is
//: drawn behind the bubble and can be missed entirely, which costs the trial
//: on an all-or-nothing rule. Reported by a pilot participant.
const PARTNER_TILES = (function () {
const out = [];
for (let c = 0; c <= 2; c++) for (let r = 7; r <= ROWS - 1; r++) out.push(c + "," + r);
return out;
})();
function scatterCorn(n, player, existing) {
const taken = new Set([player.c + "," + player.r]);
PARTNER_TILES.forEach(k => taken.add(k));
(existing || []).forEach(k => { if (!k.done) taken.add(k.c + "," + k.r); });
const cells = [];
for (let r = 0; r < ROWS; r++)
for (let c = 0; c < COLS; c++)
if (!taken.has(c + "," + r)) cells.push({ c, r });
for (let i = cells.length - 1; i > 0; i--) {
const j = (rnd() * (i + 1)) | 0;
const tmp = cells[i]; cells[i] = cells[j]; cells[j] = tmp;
}
const picked = cells.slice(0, Math.max(0, n));
const needs = needsFor(picked.length);
return picked.map((p, i) => ({ c: p.c, r: p.r, done: false, pop: 0,
need: needs[i], hits: 0, jit: 0 }));
}
// Every stalk catches on a single SPACE press.
//
// The harvester used to be "balky" -- half the stalks needed 1 press, a
// quarter 2, a quarter 3. Removed because it cost resolution: more presses
// per stalk means fewer stalks clearable in 10s, which means max_boxes lands
// around 6 and four distinct effort levels no longer fit inside it (one pilot
// ended up with two levels demanding the same number of stalks). Dropping it
// raises max_boxes by roughly 16%, which is what makes four separated levels
// fit. It does NOT by itself make trials easier to complete -- the effort
// levels are a fraction of your own calibrated maximum, so raising the
// maximum raises the target in step.
function needsFor(n) {
return new Array(n).fill(1);
}
// ---- REST: pleasant activity ----------------------------------------------
function buildRest(t) {
const px = t.player.c * TILE + TILE / 2, py = HUD + t.player.r * TILE + TILE / 2;
t.rest = {
// Chosen once per trial and held, so the scene does not change under the
// participant mid-rest and so the choice can be logged.
items: restItemsFor(t),
puppy: { x: px - 60, y: py + 20, vx: 0, vy: 0, frame: 0, t: 0 },
glass: 1.0, // drink fill 0..1
sips: 0, pets: 0,
hearts: [], // floating hearts
birds: [{ x: 40, y: 40, s: 0.5 }, { x: 220, y: 26, s: 0.35 }],
sun: { ray: 0 },
};
}
// interactive rest objects you can stroll up to and use with SPACE
// Four functional slots. The MECHANIC belongs to the slot, not to the item, so
// a new variant needs only an emoji and a label. Dispatching on the item key
// (obj.k === "lemon" || obj.k === "clamshell" || ...) meant every variant had
// to be threaded into several or-chains, which is why variety was expensive
// to add before.
const REST_SLOTS = ["drink", "companion", "pick", "lounge"];
//: Per theme, the items that can fill each slot. One is chosen per trial by
//: PRESENTATION POSITION, seeded by the participant id, never by condition.
//: Presentation order is already randomised against condition, so which items
//: appear is decorrelated from beneficiary, effort and reward by construction.
//: That matters because the model assumes the value of resting is constant: if
//: a puppy is more appealing than a hay bale, rest value wobbles trial to
//: trial. Position-based assignment makes that noise rather than bias.
const REST_VARIANTS = {
harvest: {
drink: [["π","sip lemonade"],["π§","sip iced tea"],["π§","sip apple cider"],
["π₯","sip fresh milk"],["π","sip watermelon juice"],["π","sip orange juice"],
["π«","sip a berry smoothie"],["π","sip peach nectar"]],
companion: [["πΆ","pet the puppy"],["π","pet the calf"],["π","pet the lamb"],
["π±","pet the kitten"],["π¦","pet the duckling"],["π","pet the goat"],
["π·","pet the piglet"],["π΄","pet the pony"]],
pick: [["π","pick an apple"],["π»","pick a sunflower"],["π","pick a pear"],
["π","pick a strawberry"],["π«","pick a plum"],["πΌ","pick a daisy"],
["π","pick a blackberry"],["π","pick a pumpkin"]],
lounge: [["πͺ","sit & relax"],["πΎ","rest on a hay bale"],["ποΈ","lie in the hammock"],
["π§Ί","sit on the picnic blanket"],["π³","swing in the tree"],
["πͺ΅","sit on the porch bench"],["π²","rest under the oak"],
["π","sit in the tractor seat"]],
},
jelly: {
drink: [["π","sip from a clamshell"],["π₯₯","sip from a coconut"],["πΏ","sip kelp tea"],
["π","sip sea-grape juice"],["π§","sip bubble tea"]],
companion: [["π’","pet the sea turtle"],["π¦¦","pet the otter"],["π¬","pet the dolphin"],
["π¦","pet the seal"],["π‘","pet the pufferfish"],["π΄","pet the seahorse"]],
pick: [["πΈ","pluck an anemone"],["β","pick up a starfish"],["πͺ","pick up a sand dollar"],
["π¦ͺ","pick up a pearl"],["π£","pick up a sea urchin"],["π","pick up a conch"]],
lounge: [["πͺΈ","lounge on the coral"],["ποΈ","rest on the sandbank"],["πΏ","rest in the kelp"],
["π§","rest in the tide pool"],["β","rest on the shipwreck"]],
},
firefly: {
drink: [["β","sip cocoa"],["π₯","toast a marshmallow"],["π―","sip spiced cider"],
["π«","sip thermos tea"],["π§","sip berry punch"]],
companion: [["π¦","pet the hedgehog"],["π¦","greet the owl"],["π¦","pet the fox"],
["π°","pet the rabbit"],["π¦","pet the raccoon"],["π¦","greet the deer"]],
pick: [["β¨","cup a firefly"],["π","pick a moonflower"],["π","catch a falling star"],
["πΎ","pick a dandelion"],["π","pick a glowing mushroom"]],
lounge: [["π","watch the stars"],["πͺ΅","sit on the log bench"],["ποΈ","rest by the tent"],
["π₯","sit by the campfire"],["π²","rest in the treehouse"]],
},
// themes.py states that boxes stays plain, and that principle holds here.
boxes: {
drink: [["π","sip lemonade"]], companion: [["πΆ","pet the puppy"]],
pick: [["π","pick an apple"]], lounge: [["πͺ","sit & relax"]],
},
};
function themeKeyFor() {
return REST_VARIANTS[cfg.theme] ? cfg.theme : "harvest";
}
//: One item per slot for this trial, chosen by PRESENTATION POSITION and the
//: participant seed. Deterministic, so the same participant sees the same
//: scene if a trial is redrawn, and independent of the trial's condition.
function restItemsFor(t) {
const pools = REST_VARIANTS[themeKeyFor()] || REST_VARIANTS.harvest;
const pos = (t && t.trialIndex != null) ? t.trialIndex : 0;
const seed = (t && t.seed != null) ? t.seed : 0;
const out = {};
REST_SLOTS.forEach((slot, si) => {
const pool = pools[slot] || REST_VARIANTS.harvest[slot];
// Re-seed on the POSITION as well as the slot. Drawing one offset per slot
// and adding the position advances all four slots in lockstep, so the
// whole scene repeats every pool-length trials: eight distinct scenes over
// a 48-trial session. Re-seeding decorrelates the slots from each other.
const pick = mulberry32(seed + 1000 * (si + 1) + 7919 * pos)();
const idx = Math.floor(pick * pool.length) % pool.length;
out[slot] = { slot: slot, emoji: pool[idx][0], label: pool[idx][1] };
});
return out;
}
function restObjects() {
const r = trial.rest, th = themeStyle();
const positions = {
lemon: { x: 96, y: HUD + BOARD_H - 58 }, clamshell: { x: 96, y: HUD + BOARD_H - 54 },
marshmallow: { x: 96, y: HUD + BOARD_H - 50 },
puppy: { x: r.puppy.x, y: r.puppy.y },
apple: { x: W - 96, y: HUD + BOARD_H - 52 }, anemone: { x: W - 96, y: HUD + BOARD_H - 50 },
fireflyCup: { x: W - 96, y: HUD + BOARD_H - 50 },
chair: { x: W - 162, y: HUD + BOARD_H - 26 }, coral: { x: W - 162, y: HUD + BOARD_H - 30 },
blanket: { x: W - 162, y: HUD + BOARD_H - 24 },
};
const items = (trial && trial.rest && trial.rest.items) || restItemsFor(trial);
const SLOT_POS = { drink: positions.lemon, companion: positions.puppy,
pick: positions.apple, lounge: positions.chair };
return REST_SLOTS.map(slot => {
const it = items[slot], pos = SLOT_POS[slot];
return { k: slot, slot: slot, emoji: it.emoji, x: pos.x, y: pos.y,
label: it.emoji + " " + it.label };
});
}
function nearestRestObj() {
const p = trial.player, px = p.c * TILE + TILE / 2, py = HUD + p.r * TILE + TILE / 2;
let best = null, bd = 1e9;
restObjects().forEach(o => { const d = Math.hypot(o.x - px, o.y - py); if (d < bd) { bd = d; best = o; } });
return { obj: best, dist: bd };
}
function doRestAction() {
const r = trial.rest; if (!r) return;
const { obj, dist } = nearestRestObj();
const p = trial.player, px = p.c * TILE + TILE / 2, py = HUD + p.r * TILE + TILE / 2;
if (!obj || dist > 82) { Sound.play("button"); return; }
const glyph = obj.emoji;
if (obj.slot === "drink") {
if (r.glass > 0.12) { r.glass -= 0.34; if (r.glass < 0) r.glass = 0; }
r.sips++; Sound.play("sip"); spawnHeart(trial, px, py - 22, glyph);
} else if (obj.slot === "companion") {
r.pets++; Sound.play("bark");
spawnHeart(trial, obj.x, obj.y - 14, "β€"); spawnHeart(trial, obj.x + 8, obj.y - 9, "β€");
} else if (obj.slot === "pick") {
Sound.play("apple"); spawnHeart(trial, obj.x, obj.y - 10, glyph);
} else if (obj.slot === "lounge") {
Sound.play("sit"); spawnHeart(trial, px, py - 20, "π");
}
}
function updateRest(t, dt) {
const r = t.rest; if (!r) return;
// lemonade slowly refills (so you can keep sipping)
r.glass = Math.min(1, r.glass + dt * 0.12);
// puppy gently follows the farmer
const px = t.player.c * TILE + TILE / 2, py = HUD + t.player.r * TILE + TILE / 2;
const pup = r.puppy, dx = (px - 34) - pup.x, dy = (py + 10) - pup.y;
const dist = Math.hypot(dx, dy) || 1;
const speed = Math.min(dist, 90) * dt; // ease toward the farmer
if (dist > 18) { pup.x += (dx / dist) * speed; pup.y += (dy / dist) * speed; pup.face = dx < 0 ? -1 : 1; }
pup.t += dt; pup.frame = (pup.t * 6) % 2 | 0;
// an occasional happy heart from the pup when it's near you
if (dist < 40 && Math.random() < dt * 0.6) { spawnHeart(t, pup.x, pup.y - 14, "β€"); r.pets++; if (Math.random() < 0.25) Sound.play("bark"); }
// float hearts up
r.hearts.forEach(h => { h.y -= dt * 36; h.life -= dt; });
r.hearts = r.hearts.filter(h => h.life > 0);
r.birds.forEach(b => { b.x += dt * 14 * b.s * 3; if (b.x > W + 20) b.x = -20; });
r.sun.ray += dt;
}
function spawnHeart(t, x, y, glyph) {
if (!t.rest) return;
t.rest.hearts.push({ x: x + (Math.random() * 12 - 6), y, life: 1.1, glyph: glyph || "β€" });
}
// ---- particles (work) ------------------------------------------------------
function spawnParts(t, x, y, kind, n) {
for (let i = 0; i < n; i++) {
t.fx.parts.push({
x, y, vx: (Math.random() * 2 - 1) * 60, vy: -(20 + Math.random() * 60),
life: 0.5 + Math.random() * 0.3, kind,
});
}
}
function updateParts(t, dt) {
t.fx.parts.forEach(p => { p.x += p.vx * dt; p.y += p.vy * dt; p.vy += 200 * dt; p.life -= dt; });
t.fx.parts = t.fx.parts.filter(p => p.life > 0);
if (t.fx.shake > 0) t.fx.shake = Math.max(0, t.fx.shake - dt * 40);
}
// ---- movement --------------------------------------------------------------
// ONE tile per discrete key press (holding a key does NOT glide β you must press
// again for each tile). Browser key auto-repeat is ignored via the keys[] guard in onKey.
function moveStep(k) {
const p = trial.player;
let dc = 0, dr = 0, face = p.face;
if (k === "ArrowUp") { dr = -1; face = "up"; }
else if (k === "ArrowDown") { dr = 1; face = "down"; }
else if (k === "ArrowLeft") { dc = -1; face = "left"; }
else if (k === "ArrowRight") { dc = 1; face = "right"; }
else return;
p.c = clamp(p.c + dc, 0, COLS - 1);
// The rest scene has a horizon; the work grid does not. Without this the
// player walks up off the grass and stands in the sky.
const topRow = (trial.phase === "rest") ? REST_HORIZON_ROW : 0;
p.r = clamp(p.r + dr, topRow, ROWS - 1);
p.face = face; p.frame ^= 1;
Sound.play("walk");
if (trial.phase === "work" && Math.random() < 0.5)
spawnParts(trial, p.c * TILE + TILE / 2, HUD + p.r * TILE + 6, "sweat", 1);
}
// ---- loop ------------------------------------------------------------------
function loop() {
cancel(); lastFrame = now();
const tick = () => {
raf = null;
// A frame can still be delivered between the tab going away and the
// visibility handler freezing the clock. Dropping it here means the
// pause is always clean.
if (paused) return;
try {
const tMs = now();
const dt = Math.min(0.05, (tMs - lastFrame) / 1000); lastFrame = tMs;
update(tMs, dt); drawWorld(trial);
} catch (e) {
console.error("cornfield tick error (recovered):", e); // never let a draw error freeze the game
}
if (trial && trial.phase !== "done") raf = requestAnimationFrame(tick);
};
raf = requestAnimationFrame(tick);
}
function update(tMs, dt) {
if (!trial) return;
const el = tMs - trial.phaseStart;
if (trial.phase === "decision") {
// no decision time limit β the participant chooses Rest vs Work when ready
} else if (trial.phase === "work") {
updateParts(trial, dt); // movement happens on keypress (moveStep)
if (trial.harvested >= trial.required) { trial.success = true; trial.credits = payout(trial); finish("work_success"); }
else if (el >= trial.workMs) {
trial.success = false; trial.credits = 0;
// A failed harvest in the last field counts as not having brought the
// field in, so the LARGER loss applies, which is what _bank_credits
// does. The screen was still showing the small one.
if (trial.nightWatch) trial.lostNow = trial.lossSleepDrawn;
finish("work_fail");
}
} else if (trial.phase === "rest") {
updateRest(trial, dt);
if (el >= trial.restMs) { trial.success = true; trial.credits = trial.restCredit; finish("rest"); }
} else if (trial.phase === "calib") {
updateParts(trial, dt);
if (el >= trial.workMs) finishCalibration();
}
}
function finish(outcome) {
trial.outcome = outcome; trial.phase = "feedback"; trial.feedbackStart = now();
// No reveal gate: the outcome shows at once. What it does NOT do is
// advance on its own, which is the part that mattered -- a participant
// who looked away missed the only screen that says what happened.
// Light up the beneficiary and the credit line together, but only when
// something was actually earned.
if (trial.credits > 0) trial.fx.award = now();
trial._emitted = false;
Sound.play(trial.credits > 0 ? "earn" : "fail");
// auto-advance after a moment; the player can also press SPACE to continue sooner.
// A gated reveal must not be auto-advanced past, or the press would be
// pointless, so it gets a long backstop instead of the usual one: enough
// that nobody is stuck if they walk away, far longer than anyone reading.
// A long backstop, not DEFAULT.feedbackMs. The outcome is the only
// screen that says what happened, and it used to clear itself after 1.8
// seconds whether or not anyone had read it.
trial._fbTimer = setTimeout(emitResult, REVEAL_BACKSTOP_MS);
drawWorld(trial);
}
function emitResult() {
if (!trial || trial._emitted) return; // guard: fire exactly once
trial._emitted = true;
if (trial._fbTimer) { clearTimeout(trial._fbTimer); trial._fbTimer = null; }
const r = {
trialIndex: trial.trialIndex, beneficiary: trial.beneficiary, workSide: trial.workSide,
floodRejects: trial.floodRejects || 0,
restItems: trial.rest ? {
drink: trial.rest.items.drink.label, companion: trial.rest.items.companion.label,
pick: trial.rest.items.pick.label, lounge: trial.rest.items.lounge.label,
} : null,
reward: trial.reward, required: trial.required, restCredit: trial.restCredit,
choice: trial.choice, outcome: trial.outcome, decisionRT: trial.decisionRT,
success: trial.success, harvested: trial.harvested, credits: trial.credits,
harvestTimes: trial.harvestTimes,
restSips: trial.rest ? trial.rest.sips : 0, restPets: trial.rest ? trial.rest.pets : 0,
keyLog: trial.keyLog, // every discrete key press: {t, ph, k}
nKeyPresses: trial.keyLog ? trial.keyLog.length : 0,
night: trial.night || null,
partnerLoss: trial.partnerLoss != null ? trial.partnerLoss : null,
spoiledNow: trial.spoiledNow != null ? trial.spoiledNow : null,
partnerReward: trial.partnerReward != null ? trial.partnerReward : null,
pauses: trial.pauses || [], // [{atMs, phase, ms}]
nPauses: (trial.pauses || []).length,
pausedMs: (trial.pauses || []).reduce((a, p) => a + (p.ms || 0), 0),
// where the corn was and how many presses each stalk demanded. cornNeeds
// is the real effort cost of the trial: `required` counts stalks, but each
// takes 1-4 presses, so two trials at the same effort level can differ a lot.
cornLayout: (trial.corn || []).map(k => ({ c: k.c, r: k.r, need: k.need })),
cornNeedTotal: (trial.corn || []).reduce((a, k) => a + (k.need || 0), 0),
seed: trial.seed != null ? trial.seed : null,
};
const wasNight = !!(trial.night || trial.nightWatch || trial.harvestSpeed);
trial.phase = "done"; cancel(); emit("pe_trial_done", r);
// Clean hand-off frame so the old feedback cannot linger during the
// server round-trip. Painted in the block's own backdrop rather than one
// flat slab: between night trials the slab read as a flash of a different
// screen, because it is lighter than the night sky it replaces.
if (ctx) {
ctx.fillStyle = wasNight ? "#0d1324" : "#2b3345";
ctx.fillRect(0, 0, W, H);
}
}
function finishCalibration() {
const r = { repIndex: trial.repIndex, harvested: trial.harvested, harvestTimes: trial.harvestTimes,
keyLog: trial.keyLog, nKeyPresses: trial.keyLog ? trial.keyLog.length : 0 };
trial.phase = "done"; cancel(); emit("pe_calib_done", r);
}
// ---- time-of-day theming (morning vs evening harvests) ---------------------
function todOf(t) { return (t && t.timeOfDay) || "day"; }
function skyStops(t, kind) {
const tod = todOf(t);
if (kind === "rest") {
if (tod === "morning") return ["#cfeeff", "#eef8da"]; // fresh dawn
if (tod === "evening") return ["#ffb37a", "#f3cdb0"]; // warm dusk
if (tod === "night") return ["#0b1330", "#16233f"]; // deep night
return ["#aee0ff", "#dff4d6"];
}
if (tod === "morning") return ["#ffe9cf", "#d6ebb0"]; // soft morning field
if (tod === "evening") return ["#ff9866", "#caa07e"]; // orange evening field
// The harvest theme has no skyByTod and draws from here instead, so without
// a night case the night blocks kept the daytime sky on every screen that
// is not the work field.
if (tod === "night") return ["#0b1330", "#1d2a44"];
return ["#cdd6b0", "#cdd6b0"];
}
function sunInfo(t) {
const tod = todOf(t);
const th = themeStyle();
if (!th.decorate && th.sunByTod) {
const validTod = (tod === "morning" || tod === "evening") ? tod : "morning";
const pos = validTod === "morning" ? { x: W * 0.15, y: HUD + 34 } : { x: W * 0.85, y: HUD + 46 };
return Object.assign({}, pos, th.sunByTod[validTod]);
}
if (tod === "morning") return { x: W * 0.15, y: HUD + 34, col: "#fff2c2", glow: "rgba(255,235,150,0.4)" };
if (tod === "evening") return { x: W * 0.85, y: HUD + 46, col: "#ff8a44", glow: "rgba(255,120,60,0.4)" };
return { x: W - 46, y: HUD + 38, col: "rgba(255,220,120,0.9)", glow: "rgba(255,200,80,0.35)" };
}
// ---- rendering: dispatch ---------------------------------------------------
function drawWorld(t) {
if (!ctx) return;
ctx.save();
// work screen-shake
if (t && t.fx && t.fx.shake > 0 && (t.phase === "work")) {
ctx.translate((Math.random() * 2 - 1) * t.fx.shake, (Math.random() * 2 - 1) * t.fx.shake);
}
ctx.clearRect(-20, -20, W + 40, H + 40);
if (!t || t.phase === "idle") { drawRestField(null); drawHud(t, "Get readyβ¦", C.white); ctx.restore(); return; }
if (t.phase === "decision") { drawDecisionScene(t); }
else if (t.phase === "work" || t.phase === "calib") { drawWorkScene(t); }
else if (t.phase === "rest") { drawRestScene(t); }
else if (t.phase === "feedback") {
if (t.choice === "rest") drawRestField(t); else drawWorkField(t, true);
drawFeedback(t);
}
// PRACTICE badge on the action phases (the decision screen shows its own guided prompt)
if (t && t.teach && t.phase !== "idle" && t.phase !== "decision") drawPracticeBadge();
ctx.restore();
}
function drawPracticeBadge() {
ctx.textAlign = "left"; ctx.font = "bold 13px system-ui, sans-serif";
const m = "π‘ PRACTICE";
const w = ctx.measureText(m).width + 16;
ctx.fillStyle = "rgba(241,196,15,0.97)"; roundRect(6, 6, w, 22, 8); ctx.fill();
ctx.fillStyle = "#3a2e00"; ctx.fillText(m, 14, 21);
}
// ---- WORK scene ------------------------------------------------------------
function drawWorkField(t, dim) {
const th = themeStyle();
// theme base colour, further tinted by time of day (morning vs evening)
const ss = th.decorate ? skyStops(t, "work") : (th.skyByTod[todOf(t)] || th.skyByTod.morning);
const grad = ctx.createLinearGradient(0, HUD, 0, HUD + BOARD_H);
grad.addColorStop(0, ss[0]); grad.addColorStop(1, ss[1]);
ctx.fillStyle = grad; ctx.fillRect(0, HUD, W, BOARD_H);
const sun = sunInfo(t);
ctx.fillStyle = sun.glow; circle(sun.x, sun.y, 40);
ctx.fillStyle = sun.col; circle(sun.x, sun.y, 26);
// dusty soil rows
for (let r = 0; r < ROWS; r++)
for (let c = 0; c < COLS; c++) {
const x = c * TILE, y = HUD + r * TILE;
ctx.fillStyle = (r & 1) ? th.soil : th.soilDark;
ctx.fillRect(x, y, TILE, TILE);
ctx.strokeStyle = "rgba(0,0,0,0.08)"; ctx.strokeRect(x + 0.5, y + 0.5, TILE, TILE);
}
// time-of-day colour wash so morning vs evening reads clearly over the soil.
// harvest (decorate) keeps its exact original warm morning/evening wash;
// non-decorate themes derive the wash from their own skyByTod instead, so
// e.g. firefly's always-dark sky doesn't get painted over with a warm
// sunset-colored wash that would contradict its night-only premise.
let wash;
if (th.decorate) {
// The night raid was played on a full-daylight field: the soil grid is
// painted over the whole board, so the night sky underneath it is never
// seen, and only morning and evening had a wash. Raiding a sunlit field
// while the intro says your partner is asleep undercuts the one thing
// the block is asking about.
wash = todOf(t) === "morning" ? "rgba(255,236,180,0.16)"
: todOf(t) === "evening" ? "rgba(255,110,50,0.20)"
: todOf(t) === "night" ? "rgba(10,18,50,0.50)" : null;
} else {
wash = hexTint(ss[0], 0.22);
}
if (wash) { ctx.fillStyle = wash; ctx.fillRect(0, HUD, W, BOARD_H); }
if (t && t.corn) t.corn.forEach(k => { if (!k.done) drawTarget(k); });
if (t && t.player) { drawFarmer(t.player, "work"); drawSelfLabel(t.player); }
if (t && t.fx) drawParts(t.fx.parts);
// Same bubble as the rest scene. The partner is a representation in every
// scene, so drawing them as a bare figure only here made them look like a
// second character standing in the field.
// bottom left, out of the way of the field the participant walks
if (t && t.kind === "trial")
drawPartnerBubble(t, 56, HUD + BOARD_H - 52, paysOther(t));
}
function glowActive() { return trial && trial.fx && trial.fx.glow && (now() - trial.fx.glow < 280); }
//: The award pulse, fired once when the trial resolves rather than on every
//: harvest. A per-harvest pulse flickers through a ten-second work phase and
//: has nothing to mark; the moment worth marking is when the credits land.
const AWARD_MS = 1400;
function awardPulse() {
// == null, not a falsy check: now() can legitimately return 0 early in a
// page's life, and "not set" and "set at time zero" are different things.
if (!trial || !trial.fx || trial.fx.award == null) return 0;
const el = now() - trial.fx.award;
if (el > AWARD_MS) return 0;
// two clear beats, fading out, so it reads as deliberate rather than as a flicker
return Math.max(0, (1 - el / AWARD_MS)) * Math.abs(Math.sin(el / 150));
}
// a small "YOU" tag above the player so the two characters are unambiguous.
// The player lights up briefly when a harvest earns for YOU.
function drawSelfLabel(p) {
const px = p.c * TILE + TILE / 2, py = HUD + p.r * TILE + TILE / 2;
if (glowActive() && trial.beneficiary !== "other") {
ctx.fillStyle = "rgba(46,204,113,0.45)"; circle(px, py, 22);
ctx.fillStyle = "rgba(255,255,255,0.35)"; circle(px, py, 13);
}
const x = clamp(px, 18, W - 18), y = HUD + p.r * TILE - 6;
ctx.textAlign = "center"; ctx.font = "bold 11px system-ui, sans-serif";
const w = ctx.measureText("YOU").width + 12, lx = clamp(x - w / 2, 4, W - w - 4);
const ly = clamp(y, HUD + 2, H - 16);
ctx.fillStyle = "rgba(46,140,80,0.92)"; roundRect(lx, ly, w, 15, 5); ctx.fill();
ctx.fillStyle = "#eafff0"; ctx.fillText("YOU", lx + w / 2, ly + 11);
}
function drawWorkScene(t) {
drawWorkField(t, false);
const th = themeStyle();
const isCalib = t.phase === "calib";
const el = now() - t.phaseStart, total = t.workMs, frac = clamp(1 - el / total, 0, 1);
const low = !isCalib && el > total - 3000; // last 3 s = panic
// red urgency vignette as time runs out
if (!isCalib) {
const a = (1 - frac) * 0.5;
const g = ctx.createRadialGradient(W / 2, HUD + BOARD_H / 2, 80, W / 2, HUD + BOARD_H / 2, W * 0.7);
g.addColorStop(0, "rgba(0,0,0,0)"); g.addColorStop(1, "rgba(200,0,0," + a.toFixed(2) + ")");
ctx.fillStyle = g; ctx.fillRect(0, HUD, W, BOARD_H);
}
// HUD
ctx.fillStyle = "#1c130f"; ctx.fillRect(0, 0, W, HUD);
if (!isCalib) { ctx.fillStyle = accentFor(t); ctx.fillRect(0, 0, W, 6); }
ctx.textAlign = "left"; ctx.fillStyle = C.white; ctx.font = "bold 18px system-ui, sans-serif";
const forWho = paysOther(t) ? "your PARTNER" : "YOU";
const lx = (t.teach && !isCalib) ? 116 : 18; // make room for the PRACTICE badge
const verbCap = th.verb.charAt(0).toUpperCase() + th.verb.slice(1);
// In the harvest-speed block the pay is always the participant's, so
// "WORK for your PARTNER" is wrong: they are harvesting the other player's
// field and keeping the night's pay. What the field decides is whose crop
// is left behind.
const speedLead = t.harvestSpeed
? (t.beneficiary === "other" ? "HARVESTING the OTHER PLAYER'S field"
: "HARVESTING your OWN field")
// Same problem in the last field: the credits are the participant's and
// what the choice decides is whether the other player's field comes in.
: t.nightWatch ? "YOUR PARTNER'S FIELD"
: null;
ctx.fillText(isCalib ? (verbCap + " as much as you can!")
: speedLead ? speedLead : "WORK for ", lx, 28);
if (!isCalib) {
if (!speedLead) {
const lead = ctx.measureText("WORK for ").width;
ctx.fillStyle = whoColor(t); ctx.fillText(forWho, lx + lead, 28);
}
// No second line in any block. It read "press SPACE on each corn .
// 10 credits for 6 corn", which repeats the card just chosen and the
// instruction already given, while the participant is racing a clock.
// The night harvest had none and the two should not differ in what
// they put on screen during the identical work phase.
}
ctx.textAlign = "right"; ctx.fillStyle = C.gold; ctx.font = "bold 24px system-ui, sans-serif";
// Calibration still counts, because counting IS the calibration. A live
// trial does not: the running tally was a second clock to watch while
// racing the real one.
if (isCalib) ctx.fillText(th.pastLabel + ": " + t.harvested, W - 18, 30);
// big emphasized countdown (seconds remaining)
const secs = Math.max(0, Math.ceil((total - el) / 1000));
ctx.textAlign = "right"; ctx.font = "bold 22px system-ui, sans-serif";
ctx.fillStyle = low ? C.warn : "#ffe9a8";
if (!isCalib || true) ctx.fillText("β± " + secs + "s", W - 18, 52);
// timer bar green->red, pulsing when low
const col = frac > 0.5 ? "#7ed957" : frac > 0.25 ? "#ffb020" : C.warn;
const pulse = low ? (0.6 + 0.4 * Math.sin(now() / 90)) : 1;
timerBar(el, total, col, pulse);
// big central seconds when time runs low + HURRY
if (low) {
ctx.textAlign = "center"; ctx.globalAlpha = 0.55 + 0.45 * Math.sin(now() / 80);
ctx.fillStyle = C.warn; ctx.font = "bold 64px system-ui, sans-serif";
ctx.fillText(secs, W / 2, HUD + BOARD_H / 2 + 10);
ctx.font = "bold 26px system-ui, sans-serif"; ctx.fillText("HURRY!", W / 2, HUD + 34);
ctx.globalAlpha = 1;
if (t._lastHurry !== secs) { t._lastHurry = secs; Sound.play("hurry"); }
}
// practice teaching hint about the stubborn machine
if (t.teach && !isCalib) {
ctx.textAlign = "center"; ctx.font = "bold 13px system-ui, sans-serif";
const msg = "π‘ Press an arrow for each step β’ stand on a " + th.targetOne +
" and keep pressing SPACE until you get it!";
const w = Math.min(ctx.measureText(msg).width + 20, W - 8);
ctx.fillStyle = "rgba(0,0,0,0.62)"; roundRect(W / 2 - w / 2, HUD + BOARD_H - 30, w, 22, 8); ctx.fill();
ctx.fillStyle = "#ffe9a8"; ctx.fillText(msg, W / 2, HUD + BOARD_H - 15);
}
}
// ---- REST scene ------------------------------------------------------------
function drawRestField(t) {
const th = themeStyle();
if (th.decorate) return drawRestFieldFarm(t);
if (th.restBackdrop === "reef") return drawRestFieldReef(t);
if (th.restBackdrop === "meadowNight") return drawRestFieldMeadowNight(t);
return drawRestFieldPlain(t);
}
function drawMiniCoral(x, y) {
ctx.fillStyle = "#e8767a";
ctx.beginPath(); ctx.moveTo(x, y + 10); ctx.quadraticCurveTo(x - 6, y - 2, x, y - 10);
ctx.quadraticCurveTo(x + 6, y - 2, x, y + 10); ctx.fill();
}
function fishSilhouette(x, y) {
ctx.fillStyle = "rgba(20,60,80,0.45)";
ctx.beginPath(); ctx.ellipse(x, y, 7, 3, 0, 0, 7); ctx.fill();
ctx.beginPath(); ctx.moveTo(x - 7, y); ctx.lineTo(x - 12, y - 4); ctx.lineTo(x - 12, y + 4); ctx.fill();
}
function drawRestFieldReef(t) {
const th = themeStyle();
const ss = th.skyByTod[todOf(t)] || th.skyByTod.morning;
const g = ctx.createLinearGradient(0, HUD, 0, HUD + BOARD_H);
g.addColorStop(0, ss[0]); g.addColorStop(1, ss[1]);
ctx.fillStyle = g; ctx.fillRect(0, HUD, W, BOARD_H);
const sun = sunInfo(t);
ctx.save(); ctx.globalAlpha = 0.25; ctx.fillStyle = sun.col;
for (let i = 0; i < 4; i++) ctx.fillRect(30 + i * 70, HUD, 18, BOARD_H * 0.7);
ctx.restore();
ctx.fillStyle = "rgba(255,255,255,0.3)";
[[40, HUD + 60, 4], [70, HUD + 100, 3], [W - 50, HUD + 80, 5]].forEach(b => circle(b[0], b[1], b[2]));
ctx.fillStyle = "#e8d9a8";
ctx.fillRect(0, HUD + BOARD_H - 4 * TILE, W, 4 * TILE);
const hy = HUD + REST_HORIZON_ROW * TILE;
for (let i = 0; i < 20; i++) drawMiniCoral(14 + i * 32, hy - 2);
if (t && t.rest) t.rest.birds.forEach(b => fishSilhouette(b.x, b.y));
const ax = W - 96, ay = HUD + BOARD_H - 60;
ctx.fillStyle = "#3a7a5a"; roundRect(ax - 14, ay + 10, 28, 10, 4); ctx.fill();
["#e8567a", "#f28aa8", "#ff9ec4"].forEach((col, i) => {
ctx.fillStyle = col;
ctx.beginPath(); ctx.ellipse(ax - 8 + i * 8, ay + 4, 5, 8, 0, 0, 7); ctx.fill();
});
ctx.fillStyle = "#f0e4b8"; roundRect(60, HUD + BOARD_H - 68, 120, 50, 8); ctx.fill();
const crx = W - 180, cry = HUD + BOARD_H - 30;
ctx.fillStyle = "#c97a6a"; ellipse(crx + 16, cry - 6, 22, 14);
ctx.fillStyle = "#e8a08a"; ellipse(crx + 6, cry - 12, 10, 8);
}
// fallback ambient-firefly positions for the idle ("Get readyβ¦", t === null)
// frame β no per-trial state to hang the random positions off of, so these
// are just fixed, no randomness needed for an idle background.
const AMBIENT_IDLE_FALLBACK = [
{ x: 40, y: HUD + 60, ph: 0 }, { x: 100, y: HUD + 110, ph: 2 },
{ x: 170, y: HUD + 70, ph: 4 }, { x: 230, y: HUD + 130, ph: 6 },
{ x: 290, y: HUD + 80, ph: 8 }, { x: 350, y: HUD + 120, ph: 1 },
];
function drawRestFieldMeadowNight(t) {
const th = themeStyle();
const ss = th.skyByTod[todOf(t)] || th.skyByTod.morning;
const g = ctx.createLinearGradient(0, HUD, 0, HUD + BOARD_H);
g.addColorStop(0, ss[0]); g.addColorStop(1, ss[1]);
ctx.fillStyle = g; ctx.fillRect(0, HUD, W, BOARD_H);
ctx.fillStyle = "rgba(255,255,255,0.8)";
[[30, HUD + 20], [70, HUD + 40], [120, HUD + 15], [200, HUD + 30], [260, HUD + 50], [320, HUD + 18]]
.forEach(s => circle(s[0], s[1], 1.4));
const moon = sunInfo(t);
ctx.fillStyle = moon.col; circle(moon.x, moon.y, 16);
for (let r = ROWS - 4; r < ROWS; r++)
for (let c = 0; c < COLS; c++) {
const x = c * TILE, y = HUD + r * TILE;
ctx.fillStyle = ((c + r) & 1) ? "#1c2e1c" : "#182818"; ctx.fillRect(x, y, TILE, TILE);
}
const hy = HUD + REST_HORIZON_ROW * TILE;
ctx.fillStyle = "#0e1a0e";
for (let i = 0; i < 10; i++) {
const tx = 20 + i * 36;
ctx.beginPath(); ctx.ellipse(tx, hy - 6, 16, 20, 0, 0, 7); ctx.fill();
}
// t is null on the idle "Get readyβ¦" frame (drawWorld(null) -> drawRestField(null))
// -- fall back to a fixed ambient set instead of writing onto a null trial object.
const amb = t ? (t._ambientFireflies = t._ambientFireflies || Array.from({ length: 6 }, () => ({
x: Math.random() * W, y: HUD + 40 + Math.random() * 100, ph: Math.random() * 10 }))) : AMBIENT_IDLE_FALLBACK;
amb.forEach(f => {
const pulse = 0.4 + 0.4 * Math.sin(now() / 300 + f.ph);
ctx.fillStyle = "rgba(255,240,150," + pulse.toFixed(2) + ")"; circle(f.x, f.y, 2.5);
});
// "cup a firefly" hotspot art (matches restObjects()'s fireflyCup position, W-96)
const gx = W - 96, gy = HUD + BOARD_H - 50;
ctx.fillStyle = "#274a27"; ellipse(gx, gy + 8, 20, 8);
ctx.fillStyle = "rgba(255,240,150,0.55)"; circle(gx, gy, 9);
ctx.fillStyle = "rgba(255,250,200,0.9)"; circle(gx, gy, 3);
const fx = 96, fy = HUD + BOARD_H - 50;
ctx.fillStyle = "#8a5a2a"; roundRect(fx - 12, fy + 8, 24, 6, 3); ctx.fill();
ctx.fillStyle = "rgba(255,140,50,0.5)"; circle(fx, fy + 4, 10);
ctx.fillStyle = "#3a2a1a"; roundRect(140, HUD + BOARD_H - 30, 60, 14, 4); ctx.fill();
ctx.fillStyle = "#274a27"; roundRect(W - 210, HUD + BOARD_H - 40, 90, 24, 6); ctx.fill();
}
function drawRestFieldPlain(t) {
ctx.fillStyle = "#e8e8e8"; ctx.fillRect(0, HUD, W, BOARD_H);
ctx.fillStyle = "#d0d0d0"; ctx.fillRect(0, HUD + BOARD_H - 4 * TILE, W, 4 * TILE);
// plain flat markers at the "apple"/"chair" hotspots (same coordinates as
// restObjects()'s positions table) so those two advertised activities have
// some visual presence -- no icons/color, consistent with "boxes stays plain".
ctx.fillStyle = "#b0b0b0";
roundRect(W - 96 - 12, HUD + BOARD_H - 52 - 12, 24, 24, 3); ctx.fill();
roundRect(W - 162 - 16, HUD + BOARD_H - 26 - 16, 32, 32, 3); ctx.fill();
}
function drawRestFieldFarm(t) {
// soft sky gradient, tinted by time of day
const ss = skyStops(t, "rest");
const g = ctx.createLinearGradient(0, HUD, 0, HUD + BOARD_H);
g.addColorStop(0, ss[0]); g.addColorStop(1, ss[1]);
ctx.fillStyle = g; ctx.fillRect(0, HUD, W, BOARD_H);
// sun with gentle rays, positioned by time of day
const sun = sunInfo(t), sx = todOf(t) === "day" ? 52 : sun.x, sy = sun.y, ray = t && t.rest ? t.rest.sun.ray : 0;
if (todOf(t) === "night") {
// A moon, not a sun with rays. The night blocks were drawing full
// daylight here because this path had no night case.
ctx.fillStyle = "#e8eeff"; circle(sx, sy, 15);
ctx.fillStyle = "#0b1330"; circle(sx + 6, sy - 4, 13); // crescent bite
for (let i = 0; i < 9; i++) {
const stx = 30 + ((i * 97) % (W - 60)), sty = HUD + 18 + ((i * 53) % 70);
ctx.globalAlpha = 0.5 + 0.5 * Math.abs(Math.sin(i * 1.7));
ctx.fillStyle = "#ffffff"; circle(stx, sty, 1.4);
}
ctx.globalAlpha = 1;
} else {
ctx.save(); ctx.translate(sx, sy); ctx.rotate(ray * 0.2);
ctx.strokeStyle = "rgba(255,210,90,0.5)"; ctx.lineWidth = 3;
for (let i = 0; i < 8; i++) { ctx.rotate(Math.PI / 4); ctx.beginPath(); ctx.moveTo(22, 0); ctx.lineTo(34, 0); ctx.stroke(); }
ctx.restore();
ctx.fillStyle = todOf(t) === "evening" ? "#ff9e5e" : "#ffe27a"; circle(sx, sy, 18);
}
// a distant cornfield along the horizon (ambiance β your farm in the background)
const hy = HUD + REST_HORIZON_ROW * TILE;
for (let i = 0; i < 27; i++) drawMiniCorn(10 + i * 24, hy - 4);
// grassy ground
for (let r = 0; r < ROWS; r++)
for (let c = 0; c < COLS; c++) {
if (r < ROWS - 4) continue; // grass only on the lower part
const x = c * TILE, y = HUD + r * TILE;
ctx.fillStyle = ((c + r) & 1) ? C.grass : C.grassDark; ctx.fillRect(x, y, TILE, TILE);
}
// big shady apple tree (right)
const tx = W - 96, ty = HUD + BOARD_H - 96;
ctx.fillStyle = "#7a4a22"; ctx.fillRect(tx - 8, ty, 16, 80);
ctx.fillStyle = "#5b8c3a"; circle(tx, ty - 6, 54);
ctx.fillStyle = "#6ea83f"; circle(tx - 30, ty + 8, 34); circle(tx + 30, ty + 6, 34);
ctx.fillStyle = "#e0463c"; // apples (decorative)
[[tx - 18, ty - 4], [tx + 14, ty + 2], [tx - 4, ty + 20], [tx + 30, ty - 8], [tx, ty - 22]]
.forEach(a => circle(a[0], a[1], 4));
// picnic blanket
ctx.fillStyle = "#e8675a"; roundRect(60, HUD + BOARD_H - 70, 120, 54, 8); ctx.fill();
ctx.fillStyle = "rgba(255,255,255,0.5)";
for (let i = 0; i < 4; i++) ctx.fillRect(60 + i * 30, HUD + BOARD_H - 70, 3, 54);
// a comfy deck chair to chill in
const chx = W - 180, chy = HUD + BOARD_H - 30;
ctx.strokeStyle = "#caa472"; ctx.lineWidth = 4;
ctx.beginPath(); ctx.moveTo(chx, chy); ctx.lineTo(chx + 28, chy);
ctx.lineTo(chx + 40, chy - 26); ctx.stroke();
ctx.fillStyle = "#4a8fbf"; ctx.beginPath();
ctx.moveTo(chx + 2, chy - 2); ctx.lineTo(chx + 26, chy - 2);
ctx.lineTo(chx + 38, chy - 24); ctx.lineTo(chx + 18, chy - 24); ctx.closePath(); ctx.fill();
// birds
if (t && t.rest) t.rest.birds.forEach(b => bird(b.x, b.y));
// Night: the sky is already dark, but the grass, tree, blanket and chair
// are painted at full daylight brightness on top of it. Wash the ground
// only, so the moon and stars keep their contrast.
if (todOf(t) === "night") {
const gy0 = HUD + REST_HORIZON_ROW * TILE;
ctx.fillStyle = "rgba(10,18,50,0.50)";
ctx.fillRect(0, gy0 - 10, W, HUD + BOARD_H - gy0 + 10);
}
}
function drawRestScene(t) {
drawRestField(t);
const th = themeStyle();
const gx = 96, gy = HUD + BOARD_H - 58;
drawRestMeter(cfg.theme, gx, gy, t.rest.glass);
// puppy
drawPuppy(t.rest.puppy);
// In the sky, deliberately. The bubble reads as a representation rather
// than a character standing in the scene, so height is not confusing, and
// it keeps the partner clear of the grass the participant walks on.
// left, sitting on the horizon rather than floating in open sky
drawPartnerBubble(t, 72, HUD + REST_HORIZON_ROW * TILE - 16,
t.beneficiary === "other");
// farmer (relaxed)
drawFarmer(t.player, "rest");
drawSelfLabel(t.player);
// floating reactions (hearts / lemon / apple / π)
ctx.textAlign = "center";
t.rest.hearts.forEach(h => {
ctx.globalAlpha = clamp(h.life, 0, 1); ctx.font = "18px system-ui, sans-serif";
ctx.fillText(h.glyph, h.x, h.y); ctx.globalAlpha = 1;
});
// one general instruction up in the sky (no per-object hover labels).
// NOTE: the text itself is always drawn in a near-white color (#eafff0,
// below) regardless of theme, so the plate must stay dark for every theme
// (harvest's original dark-green plate already satisfied this; the bug was
// that non-decorate themes previously used a near-white plate here, which
// combined with the near-white text to become illegible).
ctx.textAlign = "center"; ctx.font = "14px system-ui, sans-serif";
ctx.fillStyle = th.decorate ? "rgba(20,50,35,0.55)" : "rgba(0,0,0,0.45)";
const emojiList = restObjects().map(o => o.emoji).join(" ");
const hint = "Do nothing, or stroll around and press SPACE to play with "
+ "things nearby " + emojiList;
const hw = Math.min(ctx.measureText(hint).width + 18, W - 12);
roundRect(W / 2 - hw / 2, HUD + 12, hw, 24, 9); ctx.fill();
ctx.fillStyle = "#eafff0"; ctx.fillText(hint, W / 2, HUD + 28);
// The HUD said "Rest" and nothing else, while the work phase said "WORK
// for YOU" or "WORK for your PARTNER". So on a partner round the option
// that pays the partner 2 credits was the only screen in the task that
// did not say whose credits were at stake, and an RA read the practice as
// a plain rest with no beneficiary. Same shape as the work HUD now, with
// the beneficiary in the same colour.
ctx.fillStyle = "#173a2a"; ctx.fillRect(0, 0, W, HUD);
ctx.fillStyle = accentFor(t); ctx.fillRect(0, 0, W, 6);
ctx.textAlign = "left"; ctx.fillStyle = C.white; ctx.font = "bold 18px system-ui, sans-serif";
const rlx = t.teach ? 116 : 18; // make room for the PRACTICE badge
ctx.fillText("REST for ", rlx, 28);
const rlead = ctx.measureText("REST for ").width;
ctx.fillStyle = restPaysOther(t) ? C.otherAccent : C.youAccent;
ctx.fillText(restPaysOther(t) ? "your PARTNER" : "YOU", rlx + rlead, 28);
// No credit line here. The work phase shows no running total and no
// promise of one, and this showed "+2 credits for YOU" throughout the
// rest phase, so the two options were described differently while they
// were being played. Both cards already state what each pays, which is
// when it bears on the choice; after the choice it is one option
// repeating its own payoff and the other staying silent. The outcome
// screen pays both the same way.
// The same countdown the work phase shows. Rest had only the bar, so one
// of the two options told you how long it had left in numbers and the
// other did not, on phases of identical length.
const rEl = now() - t.phaseStart;
const rSecs = Math.max(0, Math.ceil((t.restMs - rEl) / 1000));
ctx.textAlign = "right"; ctx.font = "bold 22px system-ui, sans-serif";
ctx.fillStyle = rSecs <= 3 ? C.warn : "#ffe9a8";
ctx.fillText("\u23F1 " + rSecs + "s", W - 18, 52);
ctx.textAlign = "center";
timerBar(rEl, t.restMs, "#7ed957", 1);
}
function drawLemonade(x, y, fill) {
ctx.fillStyle = "rgba(255,255,255,0.85)"; roundRect(x - 9, y - 26, 18, 30, 4); ctx.fill();
const h = 26 * clamp(fill, 0, 1);
ctx.fillStyle = "#ffd23f"; ctx.fillRect(x - 7, y - 2 - h, 14, h);
ctx.fillStyle = "#fff6c0"; circle(x + 3, y - 4 - h, 2); // bubble
ctx.strokeStyle = "#c98a2b"; ctx.lineWidth = 1.5; ctx.strokeRect(x - 9, y - 26, 18, 30);
// straw + lemon slice
ctx.strokeStyle = "#ff8a5b"; ctx.lineWidth = 2;
ctx.beginPath(); ctx.moveTo(x + 4, y - 26); ctx.lineTo(x + 10, y - 36); ctx.stroke();
ctx.fillStyle = "#ffe27a"; circle(x - 8, y - 28, 4);
}
//: The vessel is a theme property. Which DRINK fills it varies per trial, but
//: the container it is drawn in does not, so the meter stays recognisable.
function drawRestMeter(theme, x, y, fill) {
if (theme === "jelly") return drawClamshell(x, y, fill);
if (theme === "firefly") return drawMarshmallow(x, y, fill);
return drawLemonade(x, y, fill);
}
function drawClamshell(x, y, fill) {
ctx.fillStyle = "#ffe3d6"; ctx.beginPath(); ctx.ellipse(x, y - 6, 11, 8, 0, 0, Math.PI, true); ctx.fill();
ctx.strokeStyle = "#e8a98a"; ctx.lineWidth = 1.5;
for (let i = -2; i <= 2; i++) { ctx.beginPath(); ctx.moveTo(x, y - 6); ctx.lineTo(x + i * 4, y - 14); ctx.stroke(); }
const h = 10 * clamp(fill, 0, 1);
ctx.fillStyle = "#7fd4c8"; ctx.fillRect(x - 8, y - 2 - h, 16, h);
ctx.fillStyle = "#fff6c0"; circle(x + 3, y - 4 - h, 2);
}
function drawMarshmallow(x, y, fill) {
ctx.strokeStyle = "#7a4a22"; ctx.lineWidth = 2;
ctx.beginPath(); ctx.moveTo(x - 10, y + 8); ctx.lineTo(x + 10, y - 6); ctx.stroke();
const toast = clamp(fill, 0, 1); // 1 = untoasted (pale), 0 = fully toasted (brown)
ctx.fillStyle = toast > 0.5 ? "#fff6ea" : "#c98a4a";
roundRect(x + 4, y - 12, 12, 12, 4); ctx.fill();
ctx.fillStyle = "#ff8a3a"; circle(x - 12, y + 12, 6);
ctx.fillStyle = "rgba(255,150,60,0.3)"; circle(x - 12, y + 12, 11);
}
function drawPuppy(p) {
const x = p.x, y = p.y, f = p.face || 1, bob = p.frame ? -1 : 1;
ctx.fillStyle = "rgba(0,0,0,0.15)"; ellipse(x, y + 9, 13, 4);
ctx.fillStyle = "#caa472";
roundRect(x - 12, y - 6 + bob, 22, 13, 6); ctx.fill();
ctx.fillStyle = "#b8915f"; circle(x + f * 12, y - 6 + bob, 7);
ctx.fillStyle = "#8c6b43"; ellipse(x + f * 16, y - 12 + bob, 3, 5);
ctx.fillStyle = "#2b2b2b"; circle(x + f * 14, y - 7 + bob, 1.4);
const wag = Math.sin(p.t * 12) * 5;
ctx.strokeStyle = "#caa472"; ctx.lineWidth = 3;
ctx.beginPath(); ctx.moveTo(x - f * 11, y - 4 + bob); ctx.lineTo(x - f * 18, y - 8 + bob + wag); ctx.stroke();
const acc = themeStyle().puppyAccessory;
if (acc === "snorkel") {
ctx.strokeStyle = "#0e2430"; ctx.lineWidth = 2;
ctx.beginPath(); ctx.arc(x + f * 12, y - 6 + bob, 5, 0, Math.PI); ctx.stroke();
} else if (acc === "glow-collar") {
ctx.fillStyle = "rgba(255,240,150,0.9)"; roundRect(x - 8, y - 1 + bob, 16, 3, 2); ctx.fill();
}
}
function bird(x, y) {
ctx.strokeStyle = "rgba(60,60,80,0.5)"; ctx.lineWidth = 2;
ctx.beginPath(); ctx.moveTo(x - 6, y); ctx.quadraticCurveTo(x, y - 5, x + 1, y);
ctx.quadraticCurveTo(x + 2, y - 5, x + 8, y); ctx.stroke();
}
// ---- shared entities -------------------------------------------------------
// the collectible target, sprite chosen by theme (same jit/pop/hits mechanic
// for all of them -- only the drawing differs).
function drawTarget(k) {
const key = cfg.theme;
if (key === "jelly") return drawJelly(k);
if (key === "firefly") return drawFirefly(k);
if (key === "boxes") return drawBox(k);
return drawCorn(k);
}
function drawJelly(k) {
const jit = (k.jit && now() - k.jit < 160) ? (Math.random() * 2 - 1) * 3 : 0;
const x = k.c * TILE + jit, y = HUD + k.r * TILE, cx = x + TILE / 2, cy = y + TILE / 2 - 4;
ctx.fillStyle = "rgba(150,190,255,0.55)";
ctx.beginPath(); ctx.arc(cx, cy, 11, Math.PI, 0); ctx.fill();
ctx.strokeStyle = "rgba(180,210,255,0.7)"; ctx.lineWidth = 2;
for (let i = -2; i <= 2; i++) {
ctx.beginPath(); ctx.moveTo(cx + i * 4, cy);
ctx.quadraticCurveTo(cx + i * 4, cy + 9, cx + i * 4, cy + 15);
ctx.stroke();
}
if (k.hits > 0 && !k.done) { ctx.fillStyle = "rgba(255,255,255,0.7)"; circle(cx + 10, cy - 6, 3); }
}
function drawFirefly(k) {
const jit = (k.jit && now() - k.jit < 160) ? (Math.random() * 2 - 1) * 3 : 0;
const x = k.c * TILE + jit, y = HUD + k.r * TILE, cx = x + TILE / 2, cy = y + TILE / 2;
const pulse = 0.55 + 0.35 * Math.sin(now() / 220 + k.c + k.r);
const g = ctx.createRadialGradient(cx, cy, 0, cx, cy, 13);
g.addColorStop(0, "rgba(255,240,150," + pulse.toFixed(2) + ")");
g.addColorStop(1, "rgba(255,240,150,0)");
ctx.fillStyle = g; circle(cx, cy, 13);
ctx.fillStyle = "#fff6b0"; circle(cx, cy, 3);
if (k.hits > 0 && !k.done) { ctx.fillStyle = "rgba(255,255,255,0.6)"; circle(cx + 9, cy - 7, 2.5); }
}
function drawBox(k) {
const jit = (k.jit && now() - k.jit < 160) ? (Math.random() * 2 - 1) * 3 : 0;
const x = k.c * TILE + jit, y = HUD + k.r * TILE;
ctx.fillStyle = "#9e9e9e"; ctx.fillRect(x + 8, y + 8, TILE - 16, TILE - 16);
ctx.strokeStyle = "#707070"; ctx.lineWidth = 2; ctx.strokeRect(x + 8, y + 8, TILE - 16, TILE - 16);
if (k.hits > 0 && !k.done) { ctx.fillStyle = "#707070"; circle(x + TILE - 12, y + 12, 2.5); }
}
function drawCorn(k) {
const jit = (k.jit && now() - k.jit < 160) ? (Math.random() * 2 - 1) * 3 : 0; // judder when cranked
const x = k.c * TILE + jit, y = HUD + k.r * TILE, cx = x + TILE / 2;
ctx.strokeStyle = "#3f7d34"; ctx.lineWidth = 3;
ctx.beginPath(); ctx.moveTo(cx, y + TILE - 4); ctx.lineTo(cx, y + 8); ctx.stroke();
ctx.fillStyle = "#4f9a3f"; leaf(cx, y + 18, -1); leaf(cx, y + 26, 1);
ctx.fillStyle = C.gold; roundRect(cx - 6, y + 6, 12, 18, 5); ctx.fill();
ctx.fillStyle = "#e0a92b"; for (let i = 0; i < 3; i++) ctx.fillRect(cx - 4, y + 10 + i * 5, 8, 2);
// "won't catch" indicator while you're cranking a stubborn corn
if (k.hits > 0 && !k.done) {
ctx.fillStyle = "rgba(120,120,120,0.6)"; circle(cx + 10, y + 2, 4); circle(cx + 14, y - 3, 3);
ctx.fillStyle = "#ff5a5a"; ctx.font = "bold 11px system-ui, sans-serif"; ctx.textAlign = "center";
ctx.fillText("rrr!", cx, y - 4);
}
}
function leaf(cx, y, dir) {
ctx.beginPath(); ctx.moveTo(cx, y);
ctx.quadraticCurveTo(cx + dir * 16, y - 4, cx + dir * 20, y + 6);
ctx.quadraticCurveTo(cx + dir * 10, y + 4, cx, y + 4); ctx.fill();
}
const NEUTRAL_PAL = { skin: "#c9c9c9", overalls: "#9a9a9a", head: "none", hair: "none" };
function drawFarmerAt(g, x, y, face, frame, mode, pal, s) {
const th = themeStyle();
if (th.character === "snorkeler") return drawSnorkelerAt(g, x, y, face, frame, mode, pal, s);
if (th.character === "explorer") return drawExplorerAt(g, x, y, face, frame, mode, pal, s);
const usePal = th.character === "plain" ? NEUTRAL_PAL : pal;
return drawFarmerBodyAt(g, x, y, face, frame, mode, usePal, s);
}
function drawSnorkelerAt(g, x, y, face, frame, mode, pal, s) {
s = s || 1; const bob = frame ? -1 : 1; const old = ctx; ctx = g;
const hy = y - 10 * s + bob;
ctx.fillStyle = "rgba(0,0,0,0.18)"; ellipse(x, y + 16 * s, 14 * s, 5 * s);
ctx.fillStyle = pal.overalls || "#2b6f8f";
roundRect(x - 9 * s, y - 2 * s + bob, 18 * s, 18 * s, 4 * s); ctx.fill();
ctx.fillStyle = "#1c4a5e";
ellipse(x - 6 * s, y + 15 * s + bob, 6 * s, 3 * s);
ellipse(x + 6 * s, y + 15 * s + bob, 6 * s, 3 * s);
ctx.fillStyle = pal.skin; circle(x, hy, 8 * s);
ctx.fillStyle = "#0e2430"; roundRect(x - 7 * s, hy - 3 * s, 14 * s, 7 * s, 3 * s); ctx.fill();
ctx.fillStyle = "#bfe9ff"; circle(x, hy - 1 * s, 3 * s);
ctx.strokeStyle = "#0e2430"; ctx.lineWidth = 2 * s;
ctx.beginPath(); ctx.moveTo(x + 7 * s, hy - 4 * s); ctx.lineTo(x + 10 * s, hy - 10 * s); ctx.stroke();
if (mode === "work") { ctx.fillStyle = "#bfe6ff"; circle(x + 9 * s, hy - 2 * s, 2 * s); }
ctx = old;
}
function drawExplorerAt(g, x, y, face, frame, mode, pal, s) {
s = s || 1; const bob = frame ? -1 : 1; const old = ctx; ctx = g;
const hy = y - 10 * s + bob;
ctx.fillStyle = "rgba(0,0,0,0.18)"; ellipse(x, y + 16 * s, 14 * s, 5 * s);
ctx.fillStyle = pal.overalls || "#2a2f3a";
roundRect(x - 9 * s, y - 2 * s + bob, 18 * s, 18 * s, 4 * s); ctx.fill();
ctx.fillStyle = pal.skin; circle(x, hy, 8 * s);
ctx.fillStyle = "#1c2027"; ctx.beginPath(); ctx.arc(x, hy, 8 * s, Math.PI, 2 * Math.PI); ctx.fill();
ctx.fillStyle = "#ffe9a0"; circle(x, hy - 8 * s, 2 * s);
ctx.fillStyle = "rgba(255,233,160,0.35)"; circle(x, hy - 8 * s, 5 * s);
ctx.strokeStyle = "#8a8f9a"; ctx.lineWidth = 1.5 * s;
ctx.beginPath(); ctx.moveTo(x + 9 * s, hy); ctx.lineTo(x + 14 * s, y + 10 * s + bob); ctx.stroke();
ctx.beginPath(); ctx.ellipse(x + 15 * s, y + 12 * s + bob, 5 * s, 4 * s, 0.3, 0, 7); ctx.stroke();
if (mode === "work") { ctx.fillStyle = "#ffe9a0"; circle(x + 9 * s, hy - 2 * s, 2 * s); }
ctx = old;
}
function drawFarmerBodyAt(g, x, y, face, frame, mode, pal, s) {
s = s || 1; const bob = frame ? -1 : 1; const old = ctx; ctx = g;
const hy = y - 10 * s + bob; // head centre
ctx.fillStyle = "rgba(0,0,0,0.18)"; ellipse(x, y + 16 * s, 14 * s, 5 * s);
ctx.fillStyle = pal.overalls; roundRect(x - 9 * s, y - 2 * s + bob, 18 * s, 18 * s, 4 * s); ctx.fill();
// hair behind the head (long / bun / pigtails)
if (pal.hairCol) {
ctx.fillStyle = pal.hairCol;
if (pal.hair === "long") { roundRect(x - 9 * s, hy - 2 * s, 18 * s, 16 * s, 6 * s); ctx.fill(); }
else if (pal.hair === "pigtails") { circle(x - 9 * s, hy + 2 * s, 4 * s); circle(x + 9 * s, hy + 2 * s, 4 * s); }
else if (pal.hair === "bun") { circle(x, hy - 9 * s, 4 * s); }
}
// head
ctx.fillStyle = pal.skin; circle(x, hy, 8 * s);
// hair on top (short / front fringe for long)
if (pal.hairCol && pal.hair !== "none") {
ctx.fillStyle = pal.hairCol;
ctx.beginPath(); ctx.arc(x, hy, 8 * s, Math.PI, 2 * Math.PI); ctx.fill(); // top cap of hair
ctx.fillRect(x - 8 * s, hy - 2 * s, 16 * s, 2 * s);
}
// headwear
drawHeadwear(x, hy, s, pal);
// glasses
if (pal.glasses) {
ctx.strokeStyle = "#2a2a2a"; ctx.lineWidth = 1.4 * s;
circle2(x - 3 * s, hy, 2.4 * s); circle2(x + 3 * s, hy, 2.4 * s);
ctx.beginPath(); ctx.moveTo(x - 0.6 * s, hy); ctx.lineTo(x + 0.6 * s, hy); ctx.stroke();
}
// beard
if (pal.beard) {
ctx.fillStyle = pal.hairCol || "#3a2a18";
ctx.beginPath(); ctx.arc(x, hy + 2 * s, 7 * s, 0.15 * Math.PI, 0.85 * Math.PI); ctx.fill();
}
// expression
if (mode === "work") { ctx.fillStyle = "#bfe6ff"; circle(x + 9 * s, hy - 2 * s, 2 * s); }
else { ctx.strokeStyle = "#9a6a3a"; ctx.lineWidth = 1.3;
ctx.beginPath(); ctx.arc(x, hy + 1 * s, 3 * s, 0.1 * Math.PI, 0.9 * Math.PI); ctx.stroke(); }
ctx = old;
}
function drawHeadwear(x, hy, s, pal) {
const top = hy - 8 * s;
if (pal.head === "straw") {
ctx.fillStyle = "#e3c067"; ellipse(x, hy - 4 * s, 13 * s, 4 * s);
ctx.fillStyle = "#d9b24f"; roundRect(x - 6 * s, hy - 10 * s, 12 * s, 7 * s, 3 * s); ctx.fill();
} else if (pal.head === "crown") {
ctx.fillStyle = "#ffd23f";
ctx.beginPath();
ctx.moveTo(x - 7 * s, top); ctx.lineTo(x - 7 * s, top - 5 * s); ctx.lineTo(x - 3.5 * s, top - 1 * s);
ctx.lineTo(x, top - 6 * s); ctx.lineTo(x + 3.5 * s, top - 1 * s); ctx.lineTo(x + 7 * s, top - 5 * s);
ctx.lineTo(x + 7 * s, top); ctx.closePath(); ctx.fill();
ctx.fillStyle = "#e8567a"; circle(x, top - 3 * s, 1.3 * s);
} else if (pal.head === "mushroom") {
ctx.fillStyle = "#c0392b"; ellipse(x, hy - 6 * s, 12 * s, 8 * s); // red cap
ctx.fillStyle = "#f5e9d0"; circle(x - 4 * s, hy - 7 * s, 2 * s); circle(x + 4 * s, hy - 6 * s, 1.6 * s); circle(x, hy - 9 * s, 1.6 * s);
} else if (pal.head === "foxmask") {
ctx.fillStyle = "#e8772e"; // ears
tri(x - 7 * s, hy - 6 * s, x - 3 * s, hy - 6 * s, x - 6 * s, hy - 12 * s);
tri(x + 7 * s, hy - 6 * s, x + 3 * s, hy - 6 * s, x + 6 * s, hy - 12 * s);
ctx.fillStyle = "#fff"; roundRect(x - 7 * s, hy - 3 * s, 14 * s, 5 * s, 2 * s); ctx.fill(); // mask band
ctx.fillStyle = "#1a1a1a"; circle(x - 3 * s, hy - 0.5 * s, 1.2 * s); circle(x + 3 * s, hy - 0.5 * s, 1.2 * s);
}
}
function tri(x1, y1, x2, y2, x3, y3) {
ctx.beginPath(); ctx.moveTo(x1, y1); ctx.lineTo(x2, y2); ctx.lineTo(x3, y3); ctx.closePath(); ctx.fill();
}
function circle2(x, y, r) { ctx.beginPath(); ctx.arc(x, y, r, 0, 7); ctx.stroke(); }
function drawFarmer(p, mode) {
const x = p.c * TILE + TILE / 2, y = HUD + p.r * TILE + TILE / 2;
// Same award aura the partner gets, on YOU trials, so the two beneficiaries
// are marked the same way and the contrast is who lights up, not how.
const pulse = (trial && trial.beneficiary !== "other") ? awardPulse() : 0;
if (pulse > 0) {
ctx.save();
ctx.globalAlpha = 0.16 + 0.44 * pulse;
ctx.fillStyle = "#2f9e5c"; circle(x, y - 6, 34 + 10 * pulse);
ctx.restore();
}
drawFarmerAt(ctx, x, y, p.face, p.frame, mode,
AVATARS[cfg.avatar % AVATARS.length], 1);
}
// titleCol/subCol (+ ...Finish variants) are the title-plate text colors,
// chosen for real contrast against THIS theme's own sky/skyFinish colors
// above -- harvest/jelly-cover keep dark text on their light skies; jelly's
// dark finish sky and firefly's always-dark sky (both cover and finish) get
// light/pale text instead.
const SPLASH_PALETTE = {
harvest: { sky: ["#aee0ff", "#dff4d6"], skyFinish: ["#ffd58a", "#ffb27a"], sun: "#ffe27a", sunFinish: "#ff9e5e", ground: "#7cc36b", groundDark: "#6cb35c",
titleCol: "#2e6b3a", titleColFinish: "#3a5a2a", subCol: "#4a7a3a", subColFinish: "#4a7a3a" },
jelly: { sky: ["#8fd8e8", "#e8f6f0"], skyFinish: ["#123a55", "#0d2a3f"], sun: "#eaffff", sunFinish: "#9fd0ff", ground: "#e8d9a8", groundDark: "#d8c488",
titleCol: "#123a48", titleColFinish: "#eaf6ff", subCol: "#1f5a6b", subColFinish: "#cfeaff" },
firefly: { sky: ["#3a2a55", "#5a3a20"], skyFinish: ["#0a0e2a", "#05071a"], sun: "#ffe9b0", sunFinish: "#e8ecff", ground: "#1c2e1c", groundDark: "#152315",
titleCol: "#fff6d0", titleColFinish: "#fff6d0", subCol: "#ffe9a0", subColFinish: "#ffe9a0" },
boxes: { sky: ["#e0e0e0", "#e0e0e0"], skyFinish: ["#d0d0d0", "#d0d0d0"], sun: "#cfcfcf", sunFinish: "#cfcfcf", ground: "#c8c8c8", groundDark: "#b8b8b8",
titleCol: "#4a4a4a", titleColFinish: "#4a4a4a", subCol: "#5a5a5a", subColFinish: "#5a5a5a" },
};
function drawFinishContainer(g, x, y, key) {
const old = ctx; ctx = g;
if (key === "net") {
ctx.strokeStyle = "#8a8f9a"; ctx.lineWidth = 2;
ctx.beginPath(); ctx.ellipse(x, y, 34, 22, 0, 0, 7); ctx.stroke();
for (let i = -3; i <= 3; i++) { ctx.beginPath(); ctx.moveTo(x + i * 8, y - 18); ctx.lineTo(x + i * 6, y + 18); ctx.stroke(); }
["#a8c8ff", "#c8b8ff", "#9fd0ff"].forEach((col, i) => {
ctx.fillStyle = col; ctx.beginPath(); ctx.arc(x - 14 + i * 14, y, 8, Math.PI, 0); ctx.fill();
});
} else if (key === "jar") {
ctx.fillStyle = "rgba(210,235,255,0.55)"; roundRect(x - 20, y - 22, 40, 44, 8); ctx.fill();
ctx.strokeStyle = "#8ab0c0"; ctx.lineWidth = 2; ctx.strokeRect(x - 20, y - 22, 40, 44);
ctx.fillStyle = "#6a8a98"; roundRect(x - 14, y - 30, 28, 10, 3); ctx.fill();
[[x - 8, y - 6], [x + 6, y + 2], [x - 2, y + 10], [x + 9, y - 10]].forEach(p => {
ctx.fillStyle = "rgba(255,240,150,0.95)"; circle(p[0], p[1], 3);
ctx.fillStyle = "rgba(255,240,150,0.35)"; circle(p[0], p[1], 6);
});
} else if (key === "stack") {
["#c9c9c9", "#bdbdbd", "#d4d4d4"].forEach((col, i) => {
ctx.fillStyle = col; roundRect(x - 18 + i * 2, y - 8 - i * 12, 36 - i * 4, 12, 3); ctx.fill();
ctx.strokeStyle = "#9a9a9a"; ctx.strokeRect(x - 18 + i * 2, y - 8 - i * 12, 36 - i * 4, 12);
});
} else {
ctx.fillStyle = "#a9773f"; roundRect(x - 24, y - 6, 48, 26, 4); ctx.fill();
ctx.strokeStyle = "#7a5228"; ctx.lineWidth = 2; ctx.strokeRect(x - 24, y - 6, 48, 26);
ctx.beginPath(); ctx.moveTo(x - 24, y + 7); ctx.lineTo(x + 24, y + 7); ctx.stroke();
[[x - 14, y - 14], [x, y - 18], [x + 14, y - 14]].forEach(p => {
ctx.fillStyle = "#4f9a3f"; ctx.beginPath(); ctx.moveTo(p[0], p[1]); ctx.lineTo(p[0] - 4, p[1] - 10); ctx.lineTo(p[0] + 4, p[1] - 10); ctx.fill();
ctx.fillStyle = "#ffd23f"; roundRect(p[0] - 4, p[1] - 4, 8, 12, 3); ctx.fill();
});
}
ctx = old;
}
// ---- title / finish splash images (drawn into a standalone canvas) ---------
function splash(canvasId, kind) {
const cv = document.getElementById(canvasId);
if (!cv) return;
const g = cv.getContext("2d"), w = cv.width, h = cv.height, old = ctx; ctx = g;
const finish = (kind === "finish");
const th = themeStyle();
const pal = SPLASH_PALETTE[cfg.theme] || SPLASH_PALETTE.harvest;
// sky
const sky = g.createLinearGradient(0, 0, 0, h);
const skyPair = finish ? pal.skyFinish : pal.sky;
sky.addColorStop(0, skyPair[0]); sky.addColorStop(1, skyPair[1]);
g.fillStyle = sky; g.fillRect(0, 0, w, h);
// sun
g.fillStyle = finish ? pal.sunFinish : pal.sun; circle(w * 0.82, h * 0.24, 30);
g.strokeStyle = finish ? "rgba(255,150,80,0.5)" : "rgba(255,210,90,0.5)"; g.lineWidth = 3;
for (let i = 0; i < 8; i++) { const a = i * Math.PI / 4; g.beginPath();
g.moveTo(w * 0.82 + Math.cos(a) * 36, h * 0.24 + Math.sin(a) * 36);
g.lineTo(w * 0.82 + Math.cos(a) * 48, h * 0.24 + Math.sin(a) * 48); g.stroke(); }
// rolling hills
g.fillStyle = pal.ground; g.beginPath(); g.moveTo(0, h * 0.7);
g.quadraticCurveTo(w * 0.3, h * 0.6, w * 0.6, h * 0.72); g.quadraticCurveTo(w * 0.85, h * 0.8, w, h * 0.68);
g.lineTo(w, h); g.lineTo(0, h); g.fill();
g.fillStyle = pal.groundDark; g.fillRect(0, h * 0.82, w, h * 0.18);
// a little cornfield row (harvest theme only; other themes keep the plain band above)
if (th.decorate) {
for (let i = 0; i < 7; i++) {
const cx = w * (0.12 + i * 0.07), cy = h * 0.8;
g.strokeStyle = "#3f7d34"; g.lineWidth = 3; g.beginPath(); g.moveTo(cx, cy + 16); g.lineTo(cx, cy - 6); g.stroke();
g.fillStyle = "#ffd23f"; roundRect(cx - 4, cy - 8, 8, 14, 3); g.fill();
}
}
// you + partner standing together
drawFarmerAt(g, w * 0.40, h * 0.82, 3, 0, "rest", AVATARS[cfg.avatar % AVATARS.length], 1.8);
drawFarmerAt(g, w * 0.56, h * 0.82, 2, 0, "rest", partnerPal(), 1.8);
if (finish) { drawFinishContainer(g, w * 0.5, h * 0.85, th.finishContainer); }
// title
g.textAlign = "center";
g.fillStyle = "rgba(20,40,30,0.18)"; roundRect(w / 2 - 165, h * 0.10, 330, 66, 14); g.fill();
g.fillStyle = finish ? pal.titleColFinish : pal.titleCol;
g.font = "bold 34px system-ui, sans-serif";
g.fillText(finish ? (th.titleWord + " Complete!") : (th.titleWord + " for Two"), w / 2, h * 0.20);
g.font = "20px system-ui, sans-serif"; g.fillStyle = finish ? pal.subColFinish : pal.subCol;
const ie = th.itemEmoji || "β«οΈ";
g.fillText(finish ? (ie + " nice work! " + ie) : (ie + " " + ie + " " + ie), w / 2, h * 0.27);
ctx = old;
}
// the partner (Player 2) β always visible, highlighted on OTHER trials.
// The nameplate is clamped to stay fully on-canvas.
//: The partner sits in a soft bubble. They are present but not playing, and a
//: bubble says that without making them look like a second character the
//: participant could walk into.
//: The partner asleep: a bed, a blanket, and a z. Used on the night blocks,
//: where the whole premise is that they are not awake to see what happens.
function drawSleepingPartner(x, y, scale) {
const k = scale || 1;
ctx.save(); ctx.translate(x, y); ctx.scale(k, k);
ctx.fillStyle = "#6b4a2f"; roundRect(-26, 2, 52, 9, 3); ctx.fill(); // bed frame
ctx.fillStyle = "#e9eef7"; roundRect(-24, -7, 48, 11, 4); ctx.fill(); // mattress
ctx.fillStyle = "#cfd9ea"; circle(-15, -10, 7); // pillow
ctx.fillStyle = "#f2c9a0"; circle(-15, -12, 5); // head
ctx.fillStyle = "#7fa7d8"; roundRect(-9, -12, 30, 9, 4); ctx.fill(); // blanket
ctx.fillStyle = "#33456b"; ctx.font = "bold 11px system-ui, sans-serif";
ctx.textAlign = "left";
ctx.globalAlpha = 0.85; ctx.fillText("z", 14, -16);
ctx.globalAlpha = 0.55; ctx.fillText("z", 21, -23);
ctx.globalAlpha = 1;
ctx.restore();
}
function drawPartnerBubble(t, x, y, emphasize) {
const pulse = emphasize ? awardPulse() : 0;
ctx.save();
// aura first, so it sits behind the bubble
if (pulse > 0) {
ctx.globalAlpha = 0.16 + 0.44 * pulse;
ctx.fillStyle = "#3aa0e8"; circle(x, y - 10, 40 + 10 * pulse);
ctx.globalAlpha = 1;
}
ctx.globalAlpha = 0.20;
ctx.fillStyle = emphasize ? "#bfe4ff" : "#ffffff";
circle(x, y - 10, 32);
ctx.globalAlpha = 0.55;
ctx.strokeStyle = emphasize ? "#3aa0e8" : "rgba(255,255,255,0.8)";
ctx.lineWidth = 2;
ctx.beginPath(); ctx.arc(x, y - 10, 32, 0, Math.PI * 2); ctx.stroke();
ctx.globalAlpha = 1;
ctx.restore();
if (todOf(t) === "night") drawSleepingPartner(x, y - 6, 1.0);
else drawPartner(x, y, emphasize);
}
function drawPartner(x, y, emphasize) {
x = clamp(x, 28, W - 28); y = clamp(y, HUD + 36, H - 16);
if (emphasize) { ctx.fillStyle = "rgba(58,160,232,0.25)"; circle(x, y - 4, 24); }
if (emphasize && glowActive()) { // partner lights up when a harvest earns for them
ctx.fillStyle = "rgba(58,160,232,0.5)"; circle(x, y - 4, 26);
ctx.fillStyle = "rgba(255,255,255,0.4)"; circle(x, y - 4, 14);
}
drawFarmerAt(ctx, x, y, 0, 0, "rest", partnerPal(), 0.9);
ctx.textAlign = "center"; ctx.font = "bold 11px system-ui, sans-serif";
const label = (emphasize ? "β
" : "") + "Partner (" + cfg.partnerName + ")";
const w = Math.min(ctx.measureText(label).width + 12, W - 8);
const lx = clamp(x - w / 2, 4, W - w - 4); // keep pill on-screen horizontally
const ly = clamp(y - 40, HUD + 2, H - 18); // ...and vertically
ctx.fillStyle = emphasize ? "rgba(30,90,150,0.92)" : "rgba(20,28,40,0.8)";
roundRect(lx, ly, w, 15, 5); ctx.fill();
ctx.fillStyle = emphasize ? "#dff0ff" : "#cdd6e0";
ctx.fillText(label, lx + w / 2, ly + 11);
}
function drawParts(parts) {
parts.forEach(p => {
ctx.globalAlpha = clamp(p.life * 2, 0, 1);
if (p.kind === "sweat") { ctx.fillStyle = "#bfe6ff"; circle(p.x, p.y, 2.5); }
else { ctx.fillStyle = "#b98a55"; ctx.fillRect(p.x, p.y, 3, 3); } // dust
ctx.globalAlpha = 1;
});
}
// ---- decision --------------------------------------------------------------
// a little corn stalk for the backdrop cornfield
function drawMiniCorn(x, y) {
ctx.strokeStyle = "#3f7d34"; ctx.lineWidth = 2;
ctx.beginPath(); ctx.moveTo(x, y + 10); ctx.lineTo(x, y - 6); ctx.stroke();
ctx.fillStyle = "#4f9a3f"; ctx.beginPath(); ctx.ellipse(x - 5, y, 5, 2.5, 0.6, 0, 7); ctx.fill();
ctx.beginPath(); ctx.ellipse(x + 5, y - 2, 5, 2.5, -0.6, 0, 7); ctx.fill();
ctx.fillStyle = C.gold; roundRect(x - 3, y - 8, 6, 11, 3); ctx.fill();
}
// the corn-world backdrop used on the choice screen (sky, sun, hill, cornfield)
function drawWorldBackdrop(t) {
const th = themeStyle();
if (th.decorate && todOf(t) === "night") return drawWorldBackdropFarmNight();
if (th.decorate) return drawWorldBackdropFarm();
if (th.restBackdrop === "reef") return drawWorldBackdropReef();
if (th.restBackdrop === "meadowNight") return drawWorldBackdropNight();
return drawWorldBackdropPlain();
}
function drawWorldBackdropReef() {
const g = ctx.createLinearGradient(0, HUD, 0, HUD + BOARD_H);
g.addColorStop(0, "#8fd8e8"); g.addColorStop(1, "#e8f6f0");
ctx.fillStyle = g; ctx.fillRect(0, HUD, W, BOARD_H);
ctx.fillStyle = "rgba(255,255,255,0.3)";
[[40, HUD + 50, 4], [90, HUD + 90, 3], [W - 60, HUD + 70, 5], [W - 120, HUD + 110, 3]]
.forEach(b => circle(b[0], b[1], b[2]));
ctx.fillStyle = "#e8d9a8"; ctx.fillRect(0, HUD + BOARD_H * 0.75, W, BOARD_H * 0.25);
for (let i = 0; i < 14; i++) drawMiniCoral(10 + i * 26, HUD + BOARD_H * 0.8);
}
function drawWorldBackdropNight() {
const g = ctx.createLinearGradient(0, HUD, 0, HUD + BOARD_H);
g.addColorStop(0, "#0a0e2a"); g.addColorStop(1, "#141a3a");
ctx.fillStyle = g; ctx.fillRect(0, HUD, W, BOARD_H);
ctx.fillStyle = "rgba(255,255,255,0.7)";
[[40, HUD + 30], [100, HUD + 50], [160, HUD + 20], [240, HUD + 45], [300, HUD + 25]]
.forEach(s => circle(s[0], s[1], 1.3));
ctx.fillStyle = "#e8ecff"; circle(W - 62, HUD + 44, 18);
ctx.fillStyle = "#0e1a0e";
for (let i = 0; i < 10; i++) {
const tx = 10 + i * 32;
ctx.beginPath(); ctx.ellipse(tx, HUD + BOARD_H * 0.72, 14, 18, 0, 0, 7); ctx.fill();
}
}
function drawWorldBackdropPlain() {
ctx.fillStyle = "#e8e8e8"; ctx.fillRect(0, HUD, W, BOARD_H);
ctx.fillStyle = "#d8d8d8"; ctx.fillRect(0, HUD + BOARD_H * 0.8, W, BOARD_H * 0.2);
}
//: The choice screen for a night block. drawWorldBackdrop() took no
//: argument, so it could not know the time of day and drew full daylight
//: with a sun behind every night decision.
function drawWorldBackdropFarmNight() {
const g = ctx.createLinearGradient(0, HUD, 0, HUD + BOARD_H);
g.addColorStop(0, "#0b1330"); g.addColorStop(1, "#1d2a44");
ctx.fillStyle = g; ctx.fillRect(0, HUD, W, BOARD_H);
ctx.fillStyle = "#e8eeff"; circle(W - 62, HUD + 44, 18); // moon
ctx.fillStyle = "#0b1330"; circle(W - 55, HUD + 39, 15); // crescent
for (let i = 0; i < 14; i++) { // stars
const sx = 24 + ((i * 131) % (W - 48)), sy = HUD + 14 + ((i * 71) % 96);
ctx.globalAlpha = 0.45 + 0.5 * Math.abs(Math.sin(i * 2.1));
ctx.fillStyle = "#ffffff"; circle(sx, sy, 1.3);
}
ctx.globalAlpha = 1;
const fy = HUD + BOARD_H * 0.5;
ctx.fillStyle = "#14351f"; ctx.beginPath(); ctx.moveTo(0, fy);
ctx.quadraticCurveTo(W * 0.5, fy - 26, W, fy);
ctx.lineTo(W, HUD + BOARD_H); ctx.lineTo(0, HUD + BOARD_H); ctx.closePath(); ctx.fill();
ctx.fillStyle = "#0f2a19"; ctx.fillRect(0, HUD + BOARD_H - 26, W, 26);
}
function drawWorldBackdropFarm() {
const g = ctx.createLinearGradient(0, HUD, 0, HUD + BOARD_H);
g.addColorStop(0, "#aee0ff"); g.addColorStop(1, "#eaf6e0");
ctx.fillStyle = g; ctx.fillRect(0, HUD, W, BOARD_H);
ctx.fillStyle = "#ffe27a"; circle(W - 62, HUD + 44, 22); // sun
ctx.strokeStyle = "rgba(255,210,90,0.5)"; ctx.lineWidth = 3;
for (let i = 0; i < 8; i++) { const a = i * Math.PI / 4; ctx.beginPath();
ctx.moveTo(W - 62 + Math.cos(a) * 28, HUD + 44 + Math.sin(a) * 28);
ctx.lineTo(W - 62 + Math.cos(a) * 38, HUD + 44 + Math.sin(a) * 38); ctx.stroke(); }
const fy = HUD + BOARD_H * 0.5; // rolling hill
ctx.fillStyle = "#8fd07e"; ctx.beginPath(); ctx.moveTo(0, fy);
ctx.quadraticCurveTo(W * 0.5, fy - 26, W, fy); ctx.lineTo(W, HUD + BOARD_H); ctx.lineTo(0, HUD + BOARD_H); ctx.fill();
ctx.fillStyle = "#6cb35c"; ctx.fillRect(0, fy + 18, W, HUD + BOARD_H - (fy + 18)); // field
if (themeStyle().decorate) {
for (let i = 0; i < 27; i++) drawMiniCorn(10 + i * 24, fy + 40); // cornfield rows
}
}
function drawDecisionScene(t) {
const isOther = t.beneficiary === "other", acc = accentFor(t);
drawWorldBackdrop(t);
beneficiaryBanner(t); // the coloured top banner (green=you / blue=partner)
// the person you're earning for, standing by the cornfield (their avatar)
if (isOther) {
drawPartnerBubble(t, W / 2, HUD + BOARD_H * 0.5 + 30, true);
} else {
drawFarmerAt(ctx, W / 2, HUD + BOARD_H * 0.5 + 30, 0, 0, "rest",
AVATARS[cfg.avatar % AVATARS.length], 1.9);
}
// prominent centred callout β the first thing you read
ctx.textAlign = "center";
// The box is measured, not fixed. It was 360 wide, which fits the day
// task's "THIS ROUND, YOU EARN FOR" over "YOUR PARTNER" and nothing
// longer: the last field's two lines overflowed it and the second line
// landed on top of the first.
ctx.font = "bold 15px system-ui, sans-serif";
const calloutTop = t.nightWatch ? ""
: t.harvestSpeed ? "TONIGHT YOU ARE HARVESTING"
: t.night ? "\u{1F319} YOUR PARTNER IS ASLEEP"
: "THIS ROUND, YOU EARN FOR";
const w1 = ctx.measureText(calloutTop).width;
// The night harvest's question is a long string. At 30px it filled the
// board edge to edge and ran into the moon; it also sat at the top of a
// sky with nothing under it until the cards.
const bigPx = t.nightWatch ? 24 : 30;
ctx.font = "bold " + bigPx + "px system-ui, sans-serif";
const calloutBig = t.nightWatch ? "REST OR WORK?"
: t.harvestSpeed ? (isOther ? "THE OTHER PLAYER'S FIELD" : "YOUR OWN FIELD")
: t.night ? (t.night === 2 ? "WHOSE POCKET?" : "RAID THE FIELD?")
: (isOther ? "YOUR PARTNER" : "YOU");
// 44 of padding left the one-line version almost touching both edges,
// and a 40-high box clipped the descender on the question mark.
const pad = calloutTop ? 44 : 76;
const cw = Math.min(Math.max(w1, ctx.measureText(calloutBig).width) + pad,
W - 16);
const ch = calloutTop ? 58 : 50;
// Dropped into the middle of the sky on the night harvest, clear of the
// moon and closer to the cards it refers to.
const cTop = HUD + (t.nightWatch ? 54 : 14);
ctx.fillStyle = "rgba(255,255,255,0.78)";
roundRect(W / 2 - cw / 2, cTop, cw, ch, 14); ctx.fill();
ctx.fillStyle = "#54636f"; ctx.font = "bold 15px system-ui, sans-serif";
// The harvest-speed block pays the same whichever card is chosen, so the
// day task's "THIS ROUND, YOU EARN FOR" is wrong here: what the round
// decides is whose field it is, not who is paid.
if (calloutTop) ctx.fillText(calloutTop, W / 2, cTop + 22);
ctx.fillStyle = (t.night || t.harvestSpeed || t.nightWatch) ? "#4a5b7a" : acc;
ctx.font = "bold 30px system-ui, sans-serif";
// Centred in the box when it is the only line. Removing the top line
// left this sitting at the bottom edge of a box drawn for two.
ctx.fillText(calloutBig, W / 2, cTop + (calloutTop ? 51 : 33));
const workIsLeft = t.workSide === "left";
// guided practice direction β plain red text (no background) under the callout
if (t.guide) {
const arrow = ((t.guide === "work") === workIsLeft) ? "β" : "βΆ";
// Pulse for the first 2 s of the decision. After that it holds steady, so
// it draws the eye without flickering under a participant still reading.
const since = now() - (t.phaseStart || now());
const pulsing = since < 2000;
ctx.save();
if (pulsing) ctx.globalAlpha = 0.55 + 0.45 * Math.abs(Math.sin(since / 190));
ctx.textAlign = "center"; ctx.font = "bold 18px system-ui, sans-serif"; ctx.fillStyle = "#e23b3b";
ctx.fillText("π Choose " + t.guide.toUpperCase() + " this time to practice (press " +
// Follows the callout wherever it sits, rather than the
// fixed spot it used to occupy.
arrow + ")", W / 2, cTop + (calloutTop ? 82 : 72));
ctx.restore();
}
// two compact choice cards at the bottom
const cardW = BOARD_W * 0.44, cardH = 150, gap = (BOARD_W - 2 * cardW) / 3;
const cy = HUD + BOARD_H - cardH - 26, leftX = gap, rightX = gap * 2 + cardW;
const workX = workIsLeft ? leftX : rightX, restX = workIsLeft ? rightX : leftX;
// guided practice: subtle glow on the card to pick
if (t.guide && !t.choice) {
const gx = (t.guide === "work") ? workX : restX;
ctx.strokeStyle = "#ffd23f"; ctx.lineWidth = 4; ctx.setLineDash([8, 6]);
roundRect(gx - 3, cy - 3, cardW + 6, cardH + 6, 14); ctx.stroke(); ctx.setLineDash([]);
}
drawChoiceCard(workX, cy, cardW, cardH, "work", t);
drawChoiceCard(restX, cy, cardW, cardH, "rest", t);
// SELECTION feedback: once you choose, the chosen card gets a bold white outline + β
if (t.choice) {
const sx = (t.chosenSide === "left") ? leftX : rightX;
ctx.strokeStyle = "#ffffff"; ctx.lineWidth = 7;
roundRect(sx - 3, cy - 3, cardW + 6, cardH + 6, 14); ctx.stroke();
ctx.fillStyle = "#2ecc71"; ctx.beginPath(); ctx.arc(sx + cardW - 14, cy + 14, 13, 0, 7); ctx.fill();
ctx.fillStyle = "#fff"; ctx.font = "bold 16px system-ui, sans-serif"; ctx.textAlign = "center";
ctx.fillText("β", sx + cardW - 14, cy + 20);
}
ctx.textAlign = "center";
// An RA read the 13px version of this line, pressed an arrow expecting to
// move a cursor, and thought the task had skipped ahead when the round
// started. So it is 17px now, and it says that the press IS the choice.
const prompt = t.choice ? "β chosen!" : "one press of β or βΆ picks that card";
ctx.font = "bold 17px system-ui, sans-serif";
// Measured, not a fixed 280 as it was: at 13px the old line fitted and at
// 17px it would not, and a browser that substitutes another face for
// system-ui changes the answer again.
const pw = clamp(ctx.measureText(prompt).width + 28, 160, W - 16);
ctx.fillStyle = "rgba(0,0,0,0.6)";
roundRect(W / 2 - pw / 2, HUD + BOARD_H - 28, pw, 26, 9); ctx.fill();
ctx.fillStyle = C.white;
ctx.fillText(prompt, W / 2, HUD + BOARD_H - 9);
}
// Night cards. Both numbers are printed on the card so the participant never
// has to hold an exchange rate in their head: night 1 shows what you gain AND
// what your partner loses; night 2 shows what each pocket is worth.
function drawNightCard(x, y, w, h, kind, t) {
const th = themeStyle(), cx = x + w / 2;
const isAct = (kind === "work"); // the "go over there" card
ctx.fillStyle = C.panel; roundRect(x, y, w, h, 12); ctx.fill();
ctx.strokeStyle = isAct ? "#e08a5f" : "#8fa6c4"; ctx.lineWidth = 3;
roundRect(x, y, w, h, 12); ctx.stroke();
ctx.textAlign = "center";
ctx.font = "28px system-ui, sans-serif";
ctx.fillText(t.night === 2 ? (isAct ? "π«±" : "π") : (isAct ? "π" : "π΄"), cx, y + 40);
ctx.fillStyle = C.white; ctx.font = "bold 17px system-ui, sans-serif";
// WORK and REST, as in the day blocks. "GO TO THEIR FIELD" / "STAY ASLEEP"
// named the same two actions in different words, which makes the night
// look like a different task rather than the same choice at night.
const title = t.night === 2 ? (isAct ? "YOUR POCKET" : "THEIR POCKET")
: (isAct ? "WORK" : "REST");
ctx.fillText(title, cx, y + h - 96);
if (t.night === 2) {
const amt = isAct ? t.reward : t.partnerReward;
ctx.fillStyle = isAct ? C.gold : "#7fd2a8"; ctx.font = "bold 24px system-ui, sans-serif";
ctx.fillText("+" + amt + " " + creditsWord(amt), cx, y + h - 62);
ctx.fillStyle = isAct ? C.gold : "#7fd2a8"; ctx.font = "bold 14px system-ui, sans-serif";
ctx.fillText(isAct ? "for YOU" : "for your PARTNER", cx, y + h - 42);
ctx.fillStyle = "#dfe5ee"; ctx.font = "13px system-ui, sans-serif";
ctx.fillText("for " + th.verbIng + " " + t.required + " " + targetWord(t.required, th), cx, y + h - 14);
return;
}
if (isAct) {
ctx.fillStyle = C.gold; ctx.font = "bold 22px system-ui, sans-serif";
ctx.fillText("+" + t.reward + " for you", cx, y + h - 64);
ctx.fillStyle = "#ff8f8f"; ctx.font = "bold 20px system-ui, sans-serif";
ctx.fillText("\u2212" + t.partnerLoss + " for your partner", cx, y + h - 40);
ctx.fillStyle = "#dfe5ee"; ctx.font = "13px system-ui, sans-serif";
ctx.fillText("for " + th.verbIng + " " + t.required + " " + targetWord(t.required, th), cx, y + h - 14);
} else {
ctx.fillStyle = "#bfe3f5"; ctx.font = "bold 24px system-ui, sans-serif";
ctx.fillText("+" + t.restCredit + " for you", cx, y + h - 58);
ctx.fillStyle = "#dfe5ee"; ctx.font = "13px system-ui, sans-serif";
ctx.fillText("your partner keeps theirs", cx, y + h - 22);
}
}
// Quick and slow harvest cards. Both are work. The pay is identical and is printed
// above the cards rather than on them, so the participant is not invited to
// compare two identical numbers; what differs is how much there is to
// collect and what spoils.
function drawSpeedPayBanner(t) {
ctx.save();
ctx.textAlign = "center";
ctx.fillStyle = "#dfe5ee"; ctx.font = "bold 15px system-ui, sans-serif";
ctx.fillText("tonight's pay: " + t.reward + " " + creditsWord(t.reward)
+ ", whichever you choose", W / 2, HUD + 96);
ctx.restore();
}
function drawWatchCard(x, y, w, h, kind, t) {
const th = themeStyle(), cx = x + w / 2;
const isWork = (kind === "work"); // workSide is the WORK card
ctx.fillStyle = C.panel; roundRect(x, y, w, h, 12); ctx.fill();
ctx.strokeStyle = isWork ? "#8fa6c4" : "#e08a5f"; ctx.lineWidth = 3;
roundRect(x, y, w, h, 12); ctx.stroke();
ctx.textAlign = "center";
ctx.fillStyle = C.white; ctx.font = "bold 19px system-ui, sans-serif";
// "REST" on its own named no beneficiary while the other card named one,
// so the two options were described in different terms. Resting here pays
// the participant out of what the partner loses, which is what the YOU:
// and PARTNER: lines below spell out.
const title = isWork ? "WORK for PARTNER" : "REST for YOU";
const icon = isWork ? "\u{1F33E}" : "\u{1F634}";
const tw = ctx.measureText(title).width;
ctx.font = "20px system-ui, sans-serif";
const iw = ctx.measureText(icon).width + 8;
ctx.fillText(icon, cx - tw / 2 - iw / 2, y + 36);
ctx.fillStyle = C.white; ctx.font = "bold 19px system-ui, sans-serif";
ctx.fillText(title, cx + iw / 2, y + 36);
// The box count said "(6)" in the title, which reads as 6 credits on a
// card whose other two lines are credits. Spelled out, on the work card
// only, where it is the price being quoted.
if (isWork) {
ctx.fillStyle = "#9fb0c4"; ctx.font = "13px system-ui, sans-serif";
ctx.fillText(th.verb + " " + t.required + " " + targetWord(t.required, th),
cx, y + 56);
}
const pay = isWork ? t.workCredit : t.restCredit;
ctx.fillStyle = C.gold; ctx.font = "bold 20px system-ui, sans-serif";
ctx.fillText("YOU: " + pay + " " + creditsWord(pay), cx, y + h - 66);
ctx.fillStyle = "#c9b8a8"; ctx.font = "11px system-ui, sans-serif";
ctx.fillText("out of their loss", cx, y + h - 50);
// "PARTNER", not "THEM". Each card shows ITS OWN side's amount: a figure
// derived from the other side would carry that side's certainty across
// and break the 2x2. The "not yet known" caption is gone; a range is
// self-evidently a range.
const lo = isWork ? t.workLo : t.sleepLo;
const hi = isWork ? t.workHi : t.sleepHi;
const amt = isWork ? t.lossWork : t.lossSleep;
const vague = (lo != null && hi != null);
ctx.fillStyle = "#ff8f8f"; ctx.font = "bold 18px system-ui, sans-serif";
ctx.fillText(vague ? ("PARTNER: loses " + lo + "\u2013" + hi)
: ("PARTNER: loses " + amt), cx, y + h - 24);
}
function drawHarvestSpeedCard(x, y, w, h, kind, t) {
const th = themeStyle(), cx = x + w / 2;
const isQuick = (kind === "work"); // workSide is the QUICK card
ctx.fillStyle = C.panel; roundRect(x, y, w, h, 12); ctx.fill();
ctx.strokeStyle = isQuick ? "#e08a5f" : "#8fa6c4"; ctx.lineWidth = 3;
roundRect(x, y, w, h, 12); ctx.stroke();
ctx.textAlign = "center";
ctx.font = "28px system-ui, sans-serif";
ctx.fillText(isQuick ? "\u26A1" : "\u{1F9FA}", cx, y + 40);
ctx.fillStyle = C.white; ctx.font = "bold 17px system-ui, sans-serif";
ctx.fillText(isQuick ? "QUICKLY" : "SLOWLY", cx, y + h - 96);
const need = isQuick ? t.requiredQuick : t.requiredSlow;
ctx.fillStyle = "#dfe5ee"; ctx.font = "bold 22px system-ui, sans-serif";
ctx.fillText("collect " + need + " " + targetWord(need, th), cx, y + h - 62);
const whose = (t.beneficiary === "other") ? "THEIR" : "YOUR";
if (!isQuick) {
ctx.fillStyle = "#7fd2a8"; ctx.font = "bold 15px system-ui, sans-serif";
ctx.fillText("nothing spoils", cx, y + h - 34);
return;
}
ctx.fillStyle = "#ff8f8f"; ctx.font = "bold 15px system-ui, sans-serif";
// Hidden trials give a range; the midpoint is what the certain trials use,
// so the two differ in certainty and not in expected size.
const amount = (t.rangeLo != null)
? ("spoils " + t.rangeLo + "\u2013" + t.rangeHi)
: ("spoils " + t.spoiled);
ctx.fillText(amount + " of " + whose + " corn", cx, y + h - 34);
if (t.showHistory && t.historyTotal != null) {
ctx.fillStyle = "#c9b7a0"; ctx.font = "12px system-ui, sans-serif";
ctx.fillText("lost from their harvest so far: " + t.historyTotal, cx, y + h - 14);
}
}
function drawChoiceCard(x, y, w, h, kind, t) {
if (t.nightWatch) return drawWatchCard(x, y, w, h, kind, t);
if (t.harvestSpeed) {
if (kind === "work") drawSpeedPayBanner(t); // once per screen
return drawHarvestSpeedCard(x, y, w, h, kind, t);
}
if (t.night) return drawNightCard(x, y, w, h, kind, t);
const th = themeStyle();
const forWho = t.beneficiary === "other" ? "your PARTNER" : "YOU";
const acc = accentFor(t), cx = x + w / 2;
ctx.fillStyle = C.panel; roundRect(x, y, w, h, 12); ctx.fill();
ctx.strokeStyle = kind === "work" ? C.gold : "#bfe3f5"; ctx.lineWidth = 3;
roundRect(x, y, w, h, 12); ctx.stroke();
ctx.textAlign = "center";
// icon + title
if (kind === "work") { ctx.font = "30px system-ui, sans-serif"; ctx.fillText(th.itemEmoji || "β«οΈ", cx, y + 42); }
else { ctx.font = "26px system-ui, sans-serif"; ctx.fillText("π", cx - 12, y + 42); ctx.fillText("πΆ", cx + 14, y + 42); }
ctx.fillStyle = C.white; ctx.font = "bold 20px system-ui, sans-serif";
ctx.fillText(kind === "work" ? "WORK" : "REST", cx, y + h - 94);
// who it's for β on the card, so attention isn't split
ctx.fillStyle = acc; ctx.font = "bold 15px system-ui, sans-serif";
ctx.fillText("for " + forWho, cx, y + h - 72);
if (kind === "work") {
// Highlighted reward pill. An UNCERTAIN offer shows the range it was
// drawn around instead of the amount; the midpoint is the amount a
// matching certain trial would show, so the two conditions differ in
// certainty and not in expected size.
const vague = (t.rewardLo != null && t.rewardHi != null);
const pill = vague
? (t.rewardLo + "\u2013" + t.rewardHi + " " + creditsWord(t.rewardHi))
: (t.reward + " " + creditsWord(t.reward));
ctx.font = "bold 23px system-ui, sans-serif";
const pw = Math.min(ctx.measureText(pill).width + 22, w - 12);
ctx.fillStyle = "rgba(255,210,63,0.20)"; roundRect(cx - pw / 2, y + h - 60, pw, 32, 9); ctx.fill();
ctx.strokeStyle = C.gold; ctx.lineWidth = 2; roundRect(cx - pw / 2, y + h - 60, pw, 32, 9); ctx.stroke();
ctx.fillStyle = C.gold; ctx.fillText(pill, cx, y + h - 38);
ctx.fillStyle = vague ? "#e8c547" : "#dfe5ee";
ctx.font = (vague ? "bold " : "") + "13px system-ui, sans-serif";
ctx.fillText(vague
? ("price not in yet \u00b7 " + th.verbIng + " " + t.required + " "
+ targetWord(t.required, th))
: ("for " + th.verbIng + " " + t.required + " "
+ targetWord(t.required, th)), cx, y + h - 12);
} else {
ctx.fillStyle = "#bfe3f5"; ctx.font = "bold 23px system-ui, sans-serif";
ctx.fillText(t.restCredit + " " + creditsWord(t.restCredit), cx, y + h - 40);
ctx.fillStyle = "#dfe5ee"; ctx.font = "13px system-ui, sans-serif";
ctx.fillText("relax & have fun", cx, y + h - 14);
}
}
// ---- HUD bits --------------------------------------------------------------
//: Who this trial actually pays. Night 2 decides it from the CHOICE, not
//: from the trial: its `beneficiary` is "conflict" for the whole block, so
//: reading beneficiary === "other" made every night-2 outcome screen say
//: "for YOU" even when the credits had gone to the partner -- the one thing
//: that block asks about, reported backwards. The accounting in
//: _bank_credits was right all along; only the screen was wrong.
function paysOther(t) {
if (!t) return false;
if (t.night === 2) return t.choice === "work_partner";
return t.beneficiary === "other";
}
function whoColor(t) { return paysOther(t) ? C.otherAccent : C.youAccent; }
//: Who the REST option pays. Not paysOther(): the night harvest's trials
//: carry beneficiary "other" because the partner is who the block is about,
//: and resting there pays the participant out of that person's loss. Night 1
//: resting pays the participant too. Only a day trial's rest credit follows
//: the round's beneficiary.
function restPaysOther(t) {
if (!t || t.nightWatch || t.night || t.harvestSpeed) return false;
return t.beneficiary === "other";
}
//: The green/blue accent means "who this round pays". At night nobody else
//: is paid, so a muted night accent rather than the day task's green.
function accentFor(t) {
if (t && t.night) return "#5b6fa8";
return t && t.beneficiary === "other" ? C.otherAccent : C.youAccent;
}
function drawHud(t, title, color) {
ctx.fillStyle = "#1c2533"; ctx.fillRect(0, 0, W, HUD);
ctx.textAlign = "center"; ctx.fillStyle = color || C.white; ctx.font = "bold 22px system-ui, sans-serif";
ctx.fillText(title || "", W / 2, 40);
}
function beneficiaryBanner(t) {
const isOther = t.beneficiary === "other";
ctx.fillStyle = "#161e2a"; ctx.fillRect(0, 0, W, HUD);
ctx.fillStyle = accentFor(t); ctx.fillRect(0, 0, W, 6); // green=you / blue=partner accent
ctx.textAlign = "center"; ctx.fillStyle = "#eef2f6"; ctx.font = "bold 26px system-ui, sans-serif";
// A night trial has no round type: every one of them pays the participant,
// so the day task's "YOU ROUND" banner sat above a screen asking whether to
// raid a sleeping partner and read as if the two were the same kind of
// choice.
// Harvest speed has no round type either: the pay is the same every
// round and for both cards, so "YOU ROUND" would sit above a screen whose
// choice is about whose crop is left behind.
const label = (t.teach ? "PRACTICE: " : "")
+ (t.nightWatch ? "\u{1F319} NIGHT HARVEST"
: t.harvestSpeed ? "\u{1F319} NIGHT HARVEST"
: t.night ? "\u{1F319} NIGHT HARVEST"
: isOther ? "YOUR PARTNER ROUND" : "YOU ROUND");
ctx.fillText(label, W / 2, HUD / 2 + 11);
}
function timerBar(elapsed, total, color, pulse) {
const frac = clamp(1 - elapsed / total, 0, 1), bw = W - 40, x = 20, yy = HUD - 14;
ctx.globalAlpha = pulse == null ? 1 : pulse;
ctx.fillStyle = "rgba(0,0,0,0.25)"; roundRect(x, yy, bw, 9, 4); ctx.fill();
ctx.fillStyle = color; roundRect(x, yy, bw * frac, 9, 4); ctx.fill();
ctx.globalAlpha = 1;
}
//: The people on the outcome screen. The overlay dims the whole board, so
//: the farmer and the partner who were standing in the scene a moment ago
//: are both behind it, and "+6 credits for YOUR PARTNER" named a person it
//: did not show. One face on a day outcome, the one that was paid; two on a
//: night-harvest outcome, which states what each of them walked away with.
function drawOutcomeFaces(t) {
const fy = HUD + BOARD_H / 2 - 74;
const selfPal = AVATARS[cfg.avatar % AVATARS.length];
if (t.nightWatch) {
drawFarmerAt(ctx, W / 2 - 54, fy, 0, 0, "rest", selfPal, 1.25);
drawFarmerAt(ctx, W / 2 + 54, fy, 0, 0, "rest", partnerPal(), 1.25);
ctx.textAlign = "center"; ctx.font = "bold 11px system-ui, sans-serif";
ctx.fillStyle = C.youAccent; ctx.fillText("YOU", W / 2 - 54, fy + 30);
ctx.fillStyle = C.otherAccent;
ctx.fillText(cfg.partnerName, W / 2 + 54, fy + 30);
return;
}
drawFarmerAt(ctx, W / 2, fy, 0, 0, "rest",
paysOther(t) ? partnerPal() : selfPal, 1.35);
}
function drawFeedback(t) {
ctx.fillStyle = "rgba(10,14,22,0.72)"; ctx.fillRect(0, HUD, W, BOARD_H);
drawOutcomeFaces(t);
ctx.textAlign = "center";
// The outcome waits behind a keypress. It used to appear on its own while
// the participant was still reading the card, which on a block where the
// amount can be a range means the one number they have to see goes by
// unattended. Revealing it is now a deliberate act, on both options.
const earned = t.credits > 0, who = paysOther(t) ? "YOUR PARTNER" : "YOU";
let msg;
if (t.outcome === "work_fail") msg = "Didn't finish in time!";
else if (t.credits === 1) msg = "+" + t.credits + " credit";
else msg = "+" + t.credits + " credits";
// The credit line pulses on the same clock as the beneficiary's aura, so the
// two read as one event: this is who just got paid.
const pulse = awardPulse();
ctx.save();
if (pulse > 0) ctx.globalAlpha = 0.72 + 0.28 * pulse;
ctx.fillStyle = earned ? C.gold : C.warn;
ctx.font = "bold " + Math.round(34 + 4 * pulse) + "px system-ui, sans-serif";
ctx.fillText(msg, W / 2, HUD + BOARD_H / 2 - 14);
ctx.fillStyle = C.white; ctx.font = "bold 18px system-ui, sans-serif";
if (t.nightWatch) {
// The same two facts the card showed, in the same words. It used to
// repeat the credit figure the big line had already given, then add a
// teaching tip, so one outcome carried three numbers and a participant
// could read the partner as losing twice.
const lost = t.lostNow != null ? t.lostNow : 0;
// A failed harvest is its own case. It used to print "for you, out of
// their loss" under "Didn't finish in time!", which says the
// participant was paid out of a loss when they were paid nothing, and
// it never said why the partner's number was the big one.
if (t.outcome === "work_fail") {
ctx.fillText("You keep nothing", W / 2, HUD + BOARD_H / 2 + 14);
ctx.fillStyle = "#ff8f8f"; ctx.font = "bold 18px system-ui, sans-serif";
ctx.fillText("Your partner loses " + lost + " " + creditsWord(lost)
+ ", the same as if you had rested",
W / 2, HUD + BOARD_H / 2 + 44);
} else {
ctx.fillText("for you, out of their loss", W / 2, HUD + BOARD_H / 2 + 14);
ctx.fillStyle = "#ff8f8f"; ctx.font = "bold 18px system-ui, sans-serif";
ctx.fillText("Your partner loses " + lost + " " + creditsWord(lost),
W / 2, HUD + BOARD_H / 2 + 44);
}
} else if (t.harvestSpeed) {
// The night's pay is always the participant's, so "for YOUR PARTNER" is
// wrong here. What the owner of the field loses is the corn left
// behind, and a failed harvest leaves nothing behind either: the
// all-or-nothing rule applies to the spoilage too, so trying and
// failing cannot harm the partner.
const whose = (t.beneficiary === "other") ? "THEIR" : "YOUR";
ctx.fillText(earned ? "for you" : "0 credits, and nothing spoiled",
W / 2, HUD + BOARD_H / 2 + 14);
if (earned && t.spoiledNow) {
ctx.fillStyle = "#ff8f8f"; ctx.font = "bold 16px system-ui, sans-serif";
ctx.fillText(t.spoiledNow + " " + creditsWord(t.spoiledNow) + " of "
+ whose + " corn left to spoil", W / 2, HUD + BOARD_H / 2 + 40);
} else if (earned) {
ctx.fillStyle = "#7fd2a8"; ctx.font = "bold 16px system-ui, sans-serif";
ctx.fillText("nothing spoiled", W / 2, HUD + BOARD_H / 2 + 40);
}
} else {
ctx.fillText(earned ? ("for " + who) : ("0 credits for " + who), W / 2, HUD + BOARD_H / 2 + 14);
}
ctx.restore();
// practice teaching: explain WHY, plus the crucial rules
if (t.teach) {
const th = themeStyle();
let tip = "";
// No night-harvest tip. The outcome screen now states the two facts
// plainly, and a tip under it made three numbers where there are two.
if (t.nightWatch) {
tip = "";
} else if (t.outcome === "work_fail")
tip = "π‘ Out of time. Walk onto each " + th.targetOne +
" and press SPACE, and try to keep moving.";
else if (t.choice === "work")
tip = "π‘ You got them all before time ran out. Nice work!";
else if (t.choice === "rest")
tip = "π‘ Resting is easy and relaxing, and earns " + (t.restCredit || 2) + " " + creditsWord(t.restCredit || 2) + ".";
if (tip) {
ctx.fillStyle = "#ffe9a8"; ctx.font = "13px system-ui, sans-serif";
wrapText(tip, W / 2, HUD + BOARD_H / 2 + 44, W - 60, 16);
}
}
// Only once the press will actually do something, so nobody presses into
// a void during the lockout.
if ((now() - t.feedbackStart) >= FEEDBACK_LOCK_MS) {
ctx.fillStyle = "#aeb6c2"; ctx.font = "14px system-ui, sans-serif";
ctx.fillText("press SPACE to continue", W / 2, HUD + BOARD_H - 16);
}
}
// simple centered word-wrap for teaching tips
function wrapText(text, cx, y, maxW, lh) {
const words = text.split(" "); let line = "", yy = y;
for (let i = 0; i < words.length; i++) {
const test = line + words[i] + " ";
if (ctx.measureText(test).width > maxW && line) { ctx.fillText(line.trim(), cx, yy); line = words[i] + " "; yy += lh; }
else line = test;
}
ctx.fillText(line.trim(), cx, yy);
}
// ---- helpers ---------------------------------------------------------------
function now() { return performance.now(); }
function clamp(v, lo, hi) { return v < lo ? lo : v > hi ? hi : v; }
// "#rrggbb" -> "rgba(r,g,b,alpha)", for tinting a solid area with a theme color
function hexTint(hex, alpha) {
const h = hex.replace("#", "");
const r = parseInt(h.substring(0, 2), 16), g = parseInt(h.substring(2, 4), 16), b = parseInt(h.substring(4, 6), 16);
return "rgba(" + r + "," + g + "," + b + "," + alpha + ")";
}
function cancel() { if (raf) { cancelAnimationFrame(raf); raf = null; } }
function circle(x, y, r) { ctx.beginPath(); ctx.arc(x, y, r, 0, 7); ctx.fill(); }
function ellipse(x, y, rx, ry) { ctx.beginPath(); ctx.ellipse(x, y, rx, ry, 0, 0, 7); ctx.fill(); }
function roundRect(x, y, w, h, r) {
ctx.beginPath(); ctx.moveTo(x + r, y);
ctx.arcTo(x + w, y, x + w, y + h, r); ctx.arcTo(x + w, y + h, x, y + h, r);
ctx.arcTo(x, y + h, x, y, r); ctx.arcTo(x, y, x + w, y, r); ctx.closePath();
}
})();
/* ============================================================================
* cornfield.js β real-time browser game engine for the Prosocial Effort task
* (task_pe-cu-nicewebrl).
*
* Design intent (per researcher): WORK should feel STRESSFUL/aversive (the
* effort cost), while REST should feel PLEASANT and ACTIVE β not boring idle
* time. So:
* WORK = harvest N corn under a hot sun: sweat, screen-shake, a timer that
* goes red and pulses, "HURRY!" β a costly chore.
* REST = relax in the shade: stroll around, a puppy follows you, sip
* lemonade with SPACE (hearts!). Equal duration to work, so time is
* not a confound, but it's a genuinely nice break.
*
* Faithful to the Apps & Lockwood prosocial effort paradigm:
* DECISION (4 s): Rest (1 credit) vs Work (2/6/10 credits, harvest N corn),
* for YOU or the OTHER player β choose with <- / ->.
* WORK (10 s): walk onto each corn stalk + SPACE; clear all N or 0 credits.
* REST (10 s): chill -> 1 credit.
* CALIBRATION: harvest as many corn as you can in 10 s (corn respawns) -> max.
* ============================================================================ */
(function () {
"use strict";
// ---- grid / canvas geometry ------------------------------------------------
const COLS = 15, ROWS = 10, TILE = 42;
//: First walkable row in the REST scene. The rest backdrops draw their horizon
//: here, so anything above it is sky and the player must not reach it.
const REST_HORIZON_ROW = ROWS - 4;
//: Stalks per warm-up batch. Six sits in the middle of the task's range
//: (3 to 10), so steps per stalk match: 5.17 in the warm-up against 5.15 for
//: a six-stalk trial.
const CALIB_BATCH = 6;
//: Expected greedy path length per stalk, measured over the grid. Used to
//: keep trial layouts near a constant walk per stalk.
const TARGET_STEPS_PER_STALK = 5.2;
//: How long the empty-soil click stays quiet after a stalk comes in.
//: A participant clearing the field presses SPACE in bursts, so the press
//: right after a successful one usually lands on the soil they just cleared.
//: Those two sounds arriving together was reported as the harvest and the
//: empty click playing at once.
const EMPTY_CLICK_MUTE_MS = 220;
const HUD = 92;
const BOARD_W = COLS * TILE, BOARD_H = ROWS * TILE;
const W = BOARD_W, H = BOARD_H + HUD;
const DEFAULT = { decisionMs: 4000, workMs: 10000, restMs: 10000, feedbackMs: 1800 };
//: How long the outcome screen ignores SPACE. It has to outlast a burst of
//: harvesting presses, not merely the next one: someone racing the clock is
//: pressing every ~60 ms, so a 700 ms lock still let the burst clear the
//: screen at 700 ms of its intended 1800. At 1200 the outcome is readable
//: whatever the participant is doing, and a deliberate press still skips the
//: last third.
const FEEDBACK_LOCK_MS = 1200;
//: How long a gated outcome waits before giving up on the keypress. Only
//: reached if the participant has stopped responding.
const REVEAL_BACKSTOP_MS = 30000;
const STEP_MS = 110;
const C = {
workSky: "#cdd6b0", workSoil: "#9c6b3f", workSoilDark: "#8a5d35",
restSkyTop: "#aee0ff", restSkyBot: "#dff4d6",
grass: "#7cc36b", grassDark: "#6cb35c",
youAccent: "#2ecc71", otherAccent: "#3aa0e8",
panel: "rgba(0,0,0,0.55)", warn: "#ff4d4d", gold: "#ffd23f", white: "#f5f5f5",
};
// ---- avatars (farmer palettes) β participant picks one; partner is distinct -
// A varied cast: gender-coded + neutral, different skin tones, plus fun headwear.
// head: 'straw' | 'crown' | 'mushroom' | 'foxmask' | 'none'
// hair: 'short' | 'long' | 'bun' | 'pigtails' | 'none'
const AVATARS = [
{ name: "Straw-hat", skin: "#f1c27d", overalls: "#3b6fb0", head: "straw", hair: "short", hairCol: "#5a3a1a" },
{ name: "Bun", skin: "#8d5524", overalls: "#b0413b", head: "straw", hair: "bun", hairCol: "#241509" },
{ name: "Longhair", skin: "#ffdbac", overalls: "#2e8b57", head: "none", hair: "long", hairCol: "#caa24a" },
{ name: "Bearded", skin: "#c68642", overalls: "#6a4fb0", head: "none", hair: "short", hairCol: "#1c1c1c", beard: true },
{ name: "Specs", skin: "#f0c8a0", overalls: "#c0563f", head: "none", hair: "short", hairCol: "#3a2a18", glasses: true },
{ name: "Princess", skin: "#e8b98a", overalls: "#d24b8a", head: "crown", hair: "long", hairCol: "#3a2412" },
{ name: "Mushroom", skin: "#ffe0bd", overalls: "#7a8a4a", head: "mushroom", hair: "none" },
{ name: "Fox mask", skin: "#7a4a28", overalls: "#2f9e9e", head: "foxmask", hair: "short", hairCol: "#141414" },
{ name: "Beard+bald", skin: "#5c3a1e", overalls: "#caa53a", head: "none", hair: "none", beard: true },
{ name: "Pigtails", skin: "#f1c27d", overalls: "#4a8fbf", head: "none", hair: "pigtails", hairCol: "#7a3a18" },
];
// 4 partner-avatar palettes (distinct from the participant's own AVATARS,
// so the two never look identical). Drawn via the same theme-dispatched
// drawFarmerAt as everything else, so a firefly-theme partner shows as one
// of 4 night-explorer palettes, a jelly-theme partner as one of 4 snorkeler
// palettes, etc.
// NOTE: intentionally a separate table from PARTNER_PAL (below) β PARTNER_PAL
// renders the partner sprite in the live game (splash/HUD/decision scene);
// this table is only for the matching-reveal screen. Not meant to be kept
// in sync with PARTNER_PAL or with each other.
const PARTNER_AVATAR_PALETTES = [
{ name: "Partner A", skin: "#d9a066", overalls: "#3f5d7a", head: "straw", hair: "short", hairCol: "#3a2a1a" },
{ name: "Partner B", skin: "#c68642", overalls: "#4a6fa5", head: "none", hair: "long", hairCol: "#2a2015" },
{ name: "Partner C", skin: "#b98457", overalls: "#8a6a9a", head: "none", hair: "bun", hairCol: "#2a1810", glasses: true },
{ name: "Partner D", skin: "#8d5524", overalls: "#5a8a6a", head: "none", hair: "none", beard: true },
];
const PARTNER_PAL = { skin: "#e8c3a0", overalls: "#7a8a99", head: "straw", hair: "short", hairCol: "#6a6f78" };