""" Social-learning treasure-hunt task for NiceWebRL (cover story: explorers/adventurers). You are a treasure hunter exploring a world to make some money. You travel a grid, discover houses, and inside each house you find two treasure chests. Each chest is one of four kinds (A/B/C/D). Opening a chest gives an outcome for BOTH you and a real anonymous PARTNER who earns money from your choices (the partner does NOT play). Each chest kind has a hidden coin profile for self and partner: A good/good B good/bad C bad/good D bad/bad "good" => exactly 12 trials of +1 coin, 2 of -1, 2 of 0 out of 16 (75% / 12.5% / 12.5%); "bad" is the mirror image. This is an exact per-block count (orders._exact_sequence), shuffled once per option/recipient/block, NOT an i.i.d. draw per round -- see RANDOMIZATION.md ("Outcomes") for why. Both self and partner outcomes are drawn and shown SIMULTANEOUSLY every round. The 6 chest-pairs AB AC AD BC BD CD each appear twice -> 12 houses, 16 rounds each. After clearing a house you rate which of its two chests you preferred. Per session everything is randomized: house POSITIONS (drawn from a candidate pool) and which chest-pair each house holds (counterbalanced order). Modes (one EnvStage state machine): OVERWORLD -> CHOICE -> OUTCOME -> (loop) -> RATING -> OVERWORLD. A separate practice EnvStage uses one house and a few rounds with extra explanations. """ import asyncio import base64 import datetime as _dt import io import json import random import re from typing import Optional import aiofiles import jax import jax.numpy as jnp import jax.tree_util as jtu import numpy as np from flax import struct from nicegui import app, ui import sprites import orders import screens import questionnaires import nicewebrl from nicewebrl import JaxWebEnv, TimeStep, TimestepWrapper from nicewebrl import Stage, EnvStage, FeedbackStage from nicewebrl import get_logger from nicewebrl.experiment import SimpleExperiment import savequeue_fix # Before any stage is built: see savequeue_fix for what reloading the page used to # do to the rest of a participant's session. savequeue_fix.install() logger = get_logger(__name__) async def _log_glitch(where, message): """Best-effort: append a lightweight 'error' event to the participant's data file (in addition to the server-side logger.warning), so a stuck-game report shows up in the exported CSV instead of only in server logs that may not be checked.""" try: seed = app.storage.user.get("seed") if seed is None: return pid = app.storage.user.get("pid", "") rec = dict( name="Event", body="", stage_idx=-1, session_id=app.storage.browser.get("id", ""), user_data=dict(user_id=seed), metadata=dict(type="Event", kind="error"), data=dict(kind="error", pid=pid, gid=orders.parse_pid(pid)[0], t=_dt.datetime.now().isoformat(timespec="milliseconds"), where=where, message=str(message)[:200]), ) async with aiofiles.open(nicewebrl.user_data_file(), "ab") as f: await nicewebrl.write_msgpack_record(f, rec) except Exception: pass # this is a diagnostic side-channel, never let it break gameplay # ---------------------------------------------------------------------------- # Constants # ---------------------------------------------------------------------------- N_TRIALS = 16 PRAC_TRIALS = orders.PRAC_TRIALS # guided practice tutorial = 6 steps N_PLACES = 12 WORLD = 25 M_OVERWORLD, M_CHOICE, M_OUTCOME, M_RATING = 0, 1, 2, 3 A_UP, A_DOWN, A_LEFT, A_RIGHT, A_SPACE = 0, 1, 2, 3, 4 OUTCOME_HOLD_MS = 2000 # the open chest stays visible this long, then closes automatically action_keys = ["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight", " "] action_to_name = ["up", "down", "left", "right", "continue"] action_array = jnp.arange(len(action_keys)) LETTER_SELF_GOOD = jnp.array([1, 1, 0, 0], dtype=jnp.int32) # A,B good for self LETTER_OTHER_GOOD = jnp.array([1, 0, 1, 0], dtype=jnp.int32) # A,C good for partner LETTER_NAMES = ["A", "B", "C", "D"] LETTER_COLOR = {0: (46, 204, 113), 1: (52, 152, 219), 2: (230, 126, 34), 3: (155, 89, 182)} COLOR_NAMES = {0: "green", 1: "blue", 2: "orange", 3: "purple"} P_PLUS_GOOD, P_MINUS_GOOD = 0.75, 0.15 P_PLUS_BAD, P_MINUS_BAD = 0.15, 0.75 COIN = 10 # each coin outcome is +10 / -10 / 0 PRAC_HOUSE_TYPE = 6 # "forest hut" (not used in main trials) PAIRS = [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)] # AB AC AD BC BD CD PLACE_PAIRS_ARR = np.array(PAIRS + PAIRS, dtype=np.int32) # (12,2) BASE_PAIRCODE = np.array([0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5], dtype=np.int32) # candidate house positions (spread); per session we pick & shuffle 12 of these CANDIDATE_POS = np.array([ [3, 4], [2, 15], [5, 9], [4, 21], [9, 2], [8, 18], [6, 12], [11, 23], [16, 6], [17, 16], [21, 3], [20, 20], [13, 5], [7, 22], [22, 12], [3, 20], [19, 9], [14, 18], ], dtype=np.int32) N_CAND = CANDIDATE_POS.shape[0] START_POS = np.array([12, 12], dtype=np.int32) PARTNER_START = np.array([12, 13], dtype=np.int32) PRAC_HOUSE = np.array([12, 16], dtype=np.int32) # one nearby house for practice RATING_MAX = 6 # 7-point scale 0..6 # ---------------------------------------------------------------------------- # Env structs # ---------------------------------------------------------------------------- @struct.dataclass class EnvParams: # ---- physical (indexed by place slot 0..11): where/what the houses are ---- house_pos: jax.Array # (12,2) positions (one of 5 location layouts) house_type: jax.Array # (12,) 0..12 appearance # ---- by BLOCK (entry order 0..11): the experienced condition sequence (OG-style) ---- block_pairs: jax.Array # (12,2) letters per block pair_code: jax.Array # (12,) per block side_schedule: jax.Array # (12,N_TRIALS) per block outcomes: jax.Array # (12,2,2,N_TRIALS) [block, option, recipient, trial] float_order: jax.Array # (12,) 0 = you-first, 1 = partner-first (per block) trial_pairs: jax.Array # (12,N_TRIALS,2) letters shown each trial (main: same as block_pairs) directed: jax.Array # (12,N_TRIALS) -1 = free choice; else the only option that opens stim_map: jax.Array # (12,4) [block,letter] -> stim id (0..23), -1 unused; main task prac_stim_map: jax.Array # (4,) letter -> stim id (24..27); PRACTICE only, unused in main n_trials: jax.Array active_mask: jax.Array # (12,) practice: jax.Array @struct.dataclass class EnvState: mode: jax.Array agent_pos: jax.Array partner_pos: jax.Array facing: jax.Array walk_frame: jax.Array consumed: jax.Array # (12,) bool (by physical place) current_place: jax.Array # physical house currently in current_block: jax.Array # which block (entry order) this house was assigned blocks_entered: jax.Array # how many houses entered so far (= next block to assign) trial: jax.Array n_trials: jax.Array practice: jax.Array self_coins: jax.Array other_coins: jax.Array left_letter: jax.Array right_letter: jax.Array chosen_side: jax.Array chosen_letter: jax.Array awaiting_start: jax.Array # 1 right after entering a house: blocks L/R until SPACE is # pressed once, so a held movement key can't auto-select a chest last_self_outcome: jax.Array last_other_outcome: jax.Array rating_cursor: jax.Array ratings: jax.Array # (12,) by BLOCK; -1 unrated else 0..6 house_pos: jax.Array # (12,2) positions this session (by place) house_active: jax.Array # (12,) bool house_type: jax.Array # (12,) by place: appearance / room theme block_pairs: jax.Array # (12,2) letters, by block (entry order) pair_code: jax.Array # (12,) by block stim_map: jax.Array # (12,4) [block,letter] -> stim id; main task prac_stim_map: jax.Array # (4,) letter -> stim id; PRACTICE only side_schedule: jax.Array # (12, N_TRIALS) by block outcomes: jax.Array # (12,2,2,N_TRIALS) by block float_order: jax.Array # (12,) by block: 0 you-first, 1 partner-first trial_pairs: jax.Array # (12,N_TRIALS,2) letters shown each trial directed: jax.Array # (12,N_TRIALS) -1 = free; else the enforced option (practice) def _layout(opt_letters, side_bit): left = jnp.where(side_bit == 0, opt_letters[0], opt_letters[1]) right = jnp.where(side_bit == 0, opt_letters[1], opt_letters[0]) return left, right def _select(cond, a, b): return jtu.tree_map(lambda x, y: jnp.where(cond, x, y), a, b) class TreasureEnv: def _obs(self, s): return jnp.array([s.mode, s.agent_pos[0], s.agent_pos[1], s.trial, s.self_coins, s.other_coins, s.current_place, jnp.sum(s.consumed)], dtype=jnp.float32) def reset(self, key, params: EnvParams): # the whole order is precomputed (per participant) and just copied into state active = params.active_mask.astype(bool) s = EnvState( mode=jnp.int32(M_OVERWORLD), agent_pos=jnp.asarray(START_POS, jnp.int32), partner_pos=jnp.asarray(PARTNER_START, jnp.int32), facing=jnp.int32(0), walk_frame=jnp.int32(0), consumed=~active, current_place=jnp.int32(-1), current_block=jnp.int32(-1), blocks_entered=jnp.int32(0), trial=jnp.int32(0), n_trials=params.n_trials, practice=params.practice, self_coins=jnp.int32(0), other_coins=jnp.int32(0), left_letter=jnp.int32(0), right_letter=jnp.int32(0), chosen_side=jnp.int32(-1), chosen_letter=jnp.int32(-1), awaiting_start=jnp.int32(0), last_self_outcome=jnp.int32(0), last_other_outcome=jnp.int32(0), rating_cursor=jnp.int32(RATING_MAX // 2), ratings=jnp.full(N_PLACES, -1, jnp.int32), house_pos=params.house_pos.astype(jnp.int32), house_active=active, house_type=params.house_type.astype(jnp.int32), block_pairs=params.block_pairs.astype(jnp.int32), pair_code=params.pair_code.astype(jnp.int32), stim_map=params.stim_map.astype(jnp.int32), prac_stim_map=params.prac_stim_map.astype(jnp.int32), side_schedule=params.side_schedule.astype(jnp.int32), outcomes=params.outcomes.astype(jnp.int32), float_order=params.float_order.astype(jnp.int32), trial_pairs=params.trial_pairs.astype(jnp.int32), directed=params.directed.astype(jnp.int32), ) return self._obs(s), s def _overworld(self, key, s, action, params): drow = jnp.where(action == A_UP, -1, jnp.where(action == A_DOWN, 1, 0)) dcol = jnp.where(action == A_LEFT, -1, jnp.where(action == A_RIGHT, 1, 0)) gr = WORLD - 1 tr = jnp.clip(s.agent_pos[0] + drow, 0, gr) tc = jnp.clip(s.agent_pos[1] + dcol, 0, gr) target = jnp.array([tr, tc]) moved = jnp.any(target != s.agent_pos) new_partner = jnp.where(moved, s.agent_pos, s.partner_pos) facing = jnp.where(action == A_UP, 1, jnp.where(action == A_DOWN, 0, jnp.where(action == A_LEFT, 2, jnp.where(action == A_RIGHT, 3, s.facing)))) new_walk = jnp.where(moved, 1 - s.walk_frame, s.walk_frame) matches = jnp.all(s.house_pos == target, axis=1) & s.house_active & (~s.consumed) entering = jnp.any(matches) place_idx = jnp.argmax(matches) # OG-style block order: the Nth house ENTERED gets the Nth pair in the sequence block = jnp.clip(s.blocks_entered, 0, N_PLACES - 1) opt = s.trial_pairs[block, 0] left, right = _layout(opt, s.side_schedule[block, 0]) moved_state = s.replace(agent_pos=target, partner_pos=new_partner, facing=facing, walk_frame=new_walk) enter_state = moved_state.replace( mode=jnp.int32(M_CHOICE), current_place=place_idx, current_block=block, blocks_entered=s.blocks_entered + 1, trial=jnp.int32(0), left_letter=left, right_letter=right, chosen_side=jnp.int32(-1), awaiting_start=jnp.int32(1)) return _select(entering, enter_state, moved_state) def _choice(self, key, s, action, params): # right after entering a house, L/R is locked out until SPACE is pressed once, this # absorbs a movement key still being held down from walking into the house, which would # otherwise auto-select a chest the instant the screen changes. s = _select(action == A_SPACE, s.replace(awaiting_start=jnp.int32(0)), s) is_choice = ((action == A_LEFT) | (action == A_RIGHT)) & (s.awaiting_start == 0) chosen_side = jnp.where(action == A_LEFT, jnp.int32(0), jnp.int32(1)) chosen_letter = jnp.where(chosen_side == 0, s.left_letter, s.right_letter) # which option of THIS trial's pair (0 or 1), then look up the pre-baked outcome opt_idx = jnp.where(chosen_letter == s.trial_pairs[s.current_block, s.trial, 0], jnp.int32(0), jnp.int32(1)) # enforced directed choice (practice): if `directed` >= 0, only that option opens directed_opt = s.directed[s.current_block, s.trial] allowed = (directed_opt < 0) | (opt_idx == directed_opt) do_resolve = is_choice & allowed self_out = s.outcomes[s.current_block, opt_idx, 0, s.trial] other_out = s.outcomes[s.current_block, opt_idx, 1, s.trial] resolved = s.replace( mode=jnp.int32(M_OUTCOME), chosen_side=chosen_side, chosen_letter=chosen_letter, last_self_outcome=self_out, last_other_outcome=other_out, self_coins=s.self_coins + self_out, other_coins=s.other_coins + other_out) return _select(do_resolve, resolved, s) def _outcome(self, key, s, action, params): is_continue = (action == A_SPACE) # Space closes the chosen chest -> next round next_trial = s.trial + 1 place_done = next_trial >= s.n_trials nt = jnp.clip(next_trial, 0, N_TRIALS - 1) opt = s.trial_pairs[s.current_block, nt] n_left, n_right = _layout(opt, s.side_schedule[s.current_block, nt]) next_round = s.replace(mode=jnp.int32(M_CHOICE), trial=next_trial, left_letter=n_left, right_letter=n_right, chosen_side=jnp.int32(-1)) # after the 16 trials the house is done -> rate which chest you preferred place_end = s.replace(mode=jnp.int32(M_RATING), rating_cursor=jnp.int32(RATING_MAX // 2)) advanced = _select(place_done, place_end, next_round) return _select(is_continue, advanced, s) def _rating(self, key, s, action, params): is_left = action == A_LEFT is_right = action == A_RIGHT is_confirm = (action == A_SPACE) cursor = jnp.clip(s.rating_cursor + is_right.astype(jnp.int32) - is_left.astype(jnp.int32), 0, RATING_MAX) moved = s.replace(rating_cursor=cursor) new_consumed = s.consumed.at[s.current_place].set(True) # physical house done new_ratings = s.ratings.at[s.current_block].set(s.rating_cursor) # rating by block confirmed = s.replace(mode=jnp.int32(M_OVERWORLD), consumed=new_consumed, ratings=new_ratings, current_place=jnp.int32(-1)) new_state = _select(is_confirm, confirmed, moved) done = is_confirm & jnp.all(new_consumed) return new_state, done def step(self, key, s, action, params): action = jnp.asarray(action, jnp.int32) ow = self._overworld(key, s, action, params) ch = self._choice(key, s, action, params) oc = self._outcome(key, s, action, params) rt, rt_done = self._rating(key, s, action, params) new_state = _select(s.mode == M_OVERWORLD, ow, _select(s.mode == M_CHOICE, ch, _select(s.mode == M_OUTCOME, oc, rt))) done = (s.mode == M_RATING) & rt_done made_choice = (s.mode == M_CHOICE) & ((action == A_LEFT) | (action == A_RIGHT)) \ & (s.awaiting_start == 0) reward = jnp.where(made_choice, new_state.last_self_outcome, 0).astype(jnp.float32) return self._obs(new_state), new_state, reward, done, {} # ---------------------------------------------------------------------------- # Build env + params (main + practice share the JaxWebEnv) # ---------------------------------------------------------------------------- raw_env = TreasureEnv() wrapped_env = TimestepWrapper(raw_env, autoreset=True) jax_web_env = JaxWebEnv(env=wrapped_env, actions=action_array) def build_env_params(order, n_trials, active_mask, practice): """Turn an `orders.make_order(...)` dict into EnvParams (jnp arrays).""" return EnvParams( house_pos=jnp.asarray(order["house_pos"], jnp.int32), house_type=jnp.asarray(order["house_type"], jnp.int32), block_pairs=jnp.asarray(order["block_pairs"], jnp.int32), pair_code=jnp.asarray(order["pair_code"], jnp.int32), side_schedule=jnp.asarray(order["side_schedule"], jnp.int32), outcomes=jnp.asarray(order["outcomes"], jnp.int32), float_order=jnp.asarray(order["float_order"], jnp.int32), trial_pairs=jnp.asarray(order["trial_pairs"], jnp.int32), directed=jnp.asarray(order["directed"], jnp.int32), stim_map=jnp.asarray(order["stim_map"], jnp.int32), prac_stim_map=jnp.asarray(order["prac_stim_map"], jnp.int32), n_trials=jnp.int32(n_trials), active_mask=jnp.asarray(active_mask, jnp.int32), practice=jnp.int32(practice), ) _MAIN_ACTIVE = np.ones(N_PLACES, np.int32) _PRAC_ACTIVE = np.zeros(N_PLACES, np.int32); _PRAC_ACTIVE[0] = 1 def dev_active_mask(k): """Active mask for the first `k` houses only, for a short dev/pilot run.""" mask = np.zeros(N_PLACES, np.int32) mask[:max(1, min(N_PLACES, k))] = 1 return mask def main_params_for(pid, role="", rando=None): return build_env_params(orders.make_order(pid, role, rando), N_TRIALS, _MAIN_ACTIVE, 0) def practice_params(pid="practice"): return build_env_params(orders.make_practice_order(pid), PRAC_TRIALS, _PRAC_ACTIVE, 1) # default params for module-load compilation (overridden per participant at runtime) main_params = main_params_for("0001") practice_params_default = practice_params() # ---------------------------------------------------------------------------- # Rendering # ---------------------------------------------------------------------------- W, H = 720, 560 TILE = 48 VIEW_W, VIEW_H = 13, 9 BOARD_W, BOARD_H = VIEW_W * TILE, VIEW_H * TILE OX, OY = (W - BOARD_W) // 2, 104 def _i(x): return int(np.asarray(x)) def _player_pal(): """The avatar the participant chose (falls back to avatar 0).""" try: return sprites.AVATARS[int(app.storage.user.get("avatar", 0)) % len(sprites.AVATARS)] except Exception: return sprites.AVATARS[0] def _partner_pal(): """The partner's randomized-per-participant look (set during the intro's matching reveal, orders.partner_avatar_for); falls back to the plain PARTNER_PAL.""" try: return sprites.partner_avatar_pal(app.storage.user.get("partner_avatar_idx")) except Exception: return sprites.partner_avatar_pal(None) from PIL import Image, ImageDraw T = sprites.text # T(d, x, y, s, size=, bold=, fill=, center=, outline=) def _hud(d, s_coins, o_coins): T(d, 16, 12, f"YOU: {s_coins} PARTNER: {o_coins}", size=17, bold=True, fill=(245, 245, 245), outline=True) def _clip(v, lo, hi): return max(lo, min(hi, v)) def _render_overworld(s): consumed = np.asarray(s.consumed) active = np.asarray(s.house_active) hpos = np.asarray(s.house_pos) htype = np.asarray(s.house_type) ar, ac = _i(s.agent_pos[0]), _i(s.agent_pos[1]) pr, pc = _i(s.partner_pos[0]), _i(s.partner_pos[1]) facing, frame = _i(s.facing), _i(s.walk_frame) sc, oc = _i(s.self_coins), _i(s.other_coins) practice = _i(s.practice) n_active = int(active.sum()) explored = int((consumed & active).sum()) img = Image.new("RGB", (W, H), (30, 38, 50)) d = ImageDraw.Draw(img) cam_top = _clip(ar - VIEW_H // 2, 0, WORLD - VIEW_H) cam_left = _clip(ac - VIEW_W // 2, 0, WORLD - VIEW_W) def screen(wr, wc): return OX + (wc - cam_left) * TILE, OY + (wr - cam_top) * TILE house_at = {(int(hpos[i][0]), int(hpos[i][1])): i for i in range(N_PLACES) if active[i]} for vr in range(VIEW_H): for vc in range(VIEW_W): wr, wc = cam_top + vr, cam_left + vc sprites.draw_grass_tile(d, OX + vc * TILE, OY + vr * TILE, TILE, wr, wc) ents = [] for (wr, wc), idx in house_at.items(): if cam_top <= wr < cam_top + VIEW_H and cam_left <= wc < cam_left + VIEW_W: ents.append((wr, "house", idx, wc)) ents.append((pr + 0.5, "char", pc, "partner")) # partner walks alongside (no caption) ents.append((ar + 0.6, "char", ac, "player")) for key, kind, a, b in sorted(ents, key=lambda e: e[0]): if kind == "house": sx, sy = screen(int(key), b) sprites.draw_house(d, sx, sy, TILE, int(htype[a]), completed=bool(consumed[a])) else: wr = int(round(key - (0.6 if b == "player" else 0.5))) sx, sy = screen(wr, a) cxx, cyy = sx + TILE // 2, sy + TILE - 6 if b == "player": sprites.draw_character(d, cxx, cyy, facing, frame, **_player_pal()) else: sprites.draw_character(d, cxx, cyy, facing, frame, **_partner_pal()) bg = (30, 38, 50) d.rectangle([0, 0, W, OY - 3], fill=bg) d.rectangle([0, OY + BOARD_H + 2, W, H], fill=bg) d.rectangle([0, 0, OX - 3, H], fill=bg) d.rectangle([OX + BOARD_W + 2, 0, W, H], fill=bg) if practice: T(d, 16, 14, "PRACTICE", size=17, bold=True, fill=(245, 230, 150), outline=True) T(d, 16, 40, "Walk with the arrow keys and step onto a house to go inside.", size=15, fill=(205, 210, 220), outline=True) d.rectangle([OX - 2, OY - 2, OX + BOARD_W + 1, OY + BOARD_H + 1], outline=(20, 24, 32), width=2) # practice finished: back in the meadow (like re-entering the real game between houses), # with a banner prompting SPACE to continue, NOT a full-screen takeover, so it's clear # they're back in the world rather than on some separate end screen. if practice and explored >= n_active: band_top, band_h = H // 2 - 54, 92 d.rectangle([0, band_top, W, band_top + band_h], fill=(20, 26, 38)) T(d, W // 2, band_top + 14, "Great, practice done!", size=28, bold=True, fill=(245, 230, 150), center=True, outline=True) T(d, W // 2, band_top + 56, "Press the space bar to continue.", size=18, fill=(235, 235, 240), center=True, outline=True) return img def _amt(v): return f"+{v}" if v > 0 else (str(v) if v < 0 else "0") def _earn(v, who): if v > 0: return f"You earned {v} points for {who}" if v < 0: return f"You lost {abs(v)} points for {who}" return f"0 points for {who}" def _earn_combined(s, o): """One short sentence summarizing both outcomes (for the practice top line).""" def part(v, who): if v > 0: return f"{who} earned {v}" if v < 0: return f"{who} lost {abs(v)}" return f"{who} got 0" return f"{part(s, 'You')}, {part(o, 'partner')}." # Guided practice tutorial (fixed, no randomization). One step per practice trial: an enforced # `instr` ("open THIS chest"; only that chest opens) and a two-line `narration` shown red+blinking # on the outcome. `letter` is the directed chest (for the choice-screen highlight) and MUST match # orders.PRACTICE_PLAN. Covers every social outcome type, in the order the user specified. PRACTICE_SCRIPT = [ dict(letter=0, instr="Open the brown woven chest.", narration=("YOU found 10 coins for YOURSELF and 10 coins for YOUR PARTNER:", "this chest was good for both of YOU!")), dict(letter=0, instr="Open the brown woven chest again.", narration=("The same chest again: 10 coins for YOU and 10 for YOUR PARTNER.", "Pay attention to WHICH CHEST you pick, not which side it's on. That's what matters.")), dict(letter=3, instr="Open the dark stone chest.", narration=("In the dark stone chest, YOU and YOUR PARTNER both lost 10 coins:", "sometimes a chest is bad for both of YOU.")), dict(letter=1, instr="Open the blue striped chest.", narration=("In the blue striped chest, YOU found 10 coins for YOURSELF, but YOUR PARTNER lost 10 coins.", "YOUR choices always affect both YOU and YOUR PARTNER, and sometimes the result is different for each of YOU.")), dict(letter=2, instr="Open the green dotted chest.", narration=("Sometimes it's the other way around: YOU found 10 coins for YOUR PARTNER,", "but YOU lost 10 coins YOURSELF.")), dict(letter=0, instr="Open the brown woven chest.", narration=("This time YOU found 0 coins, and nothing happened for either of YOU.", "Even a pretty reliable chest sometimes gives nothing.")), ] # safety: the directed letters here must line up with the numeric plan in orders.py assert [st["letter"] for st in PRACTICE_SCRIPT] == [p[0] for p in orders.PRACTICE_PLAN], \ "PRACTICE_SCRIPT and orders.PRACTICE_PLAN are out of sync" def _render_place(s): place_id = _i(s.current_place) trial, mode = _i(s.trial), _i(s.mode) left_letter, right_letter = _i(s.left_letter), _i(s.right_letter) stim_map = np.asarray(s.stim_map) prac_stim_map = np.asarray(s.prac_stim_map) block_id = _i(s.current_block) sc, oc = _i(s.self_coins), _i(s.other_coins) s_out, o_out = _i(s.last_self_outcome), _i(s.last_other_outcome) chosen_side = _i(s.chosen_side) practice = _i(s.practice) awaiting_start = _i(s.awaiting_start) htype = int(np.asarray(s.house_type)[place_id]) accent = (255, 90, 90) if practice else (255, 230, 120) # practice = red, main = gold floor_y, table_top = 372, 338 cw, ch = 170, 116 y0 = table_top - ch lx, rx = 130, W - 130 - cw img = Image.new("RGB", (W, H), (0, 0, 0)) d = ImageDraw.Draw(img) sprites.draw_room(d, W, H, floor_y, 80, W - 80, table_top, theme=sprites.ROOM_THEMES[htype]) # practice: highlight (and the prompt names) the chest the player is told to open direct_letter = -1 if practice and mode == M_CHOICE: direct_letter = PRACTICE_SCRIPT[min(trial, len(PRACTICE_SCRIPT) - 1)]["letter"] for x, letter, side in ((lx, left_letter, 0), (rx, right_letter, 1)): chosen = (mode == M_OUTCOME) and (chosen_side == side) stim = int(prac_stim_map[letter]) if practice else int(stim_map[block_id, letter]) glow = chosen or (letter == direct_letter) sprites.draw_stim_chest(d, x, y0, cw, ch, stim, is_open=chosen, highlight=glow) sprites.draw_key(d, x + cw // 2 - 12, table_top + 4, sprites.stim_color(stim)) # ---- top line (choice prompt; practice feedback is a red blinking client overlay) ---- if mode == M_CHOICE: if awaiting_start: # blocks a movement key still held from walking in from auto-selecting a chest T(d, W // 2, 12, "Press SPACE to begin", size=22, bold=True, fill=accent, center=True, outline=True) elif practice: step = PRACTICE_SCRIPT[min(trial, len(PRACTICE_SCRIPT) - 1)] T(d, W // 2, 10, step["instr"], size=21, bold=True, fill=accent, center=True, outline=True) T(d, W // 2, 38, "press the arrow key toward the glowing chest", size=18, fill=(235, 235, 240), center=True, outline=True) else: T(d, W // 2, 12, "Pick a chest to open: press <- or ->", size=22, bold=True, fill=accent, center=True, outline=True) # ---- you + partner, brought together and CENTERED (cooperative, not versus). The single # coin feedback shows above each (this is where coins will float to in the animation) ---- you_x, par_x = W // 2 - 78, W // 2 + 78 sprites.draw_character(d, you_x, H - 12, 1, 0, **_player_pal()) sprites.draw_character(d, par_x, H - 12, 1, 0, **_partner_pal()) T(d, you_x, H - 118, "YOU", size=15, bold=True, fill=(255, 255, 255), center=True, outline=True) T(d, par_x, H - 118, "PARTNER", size=15, bold=True, fill=(255, 255, 255), center=True, outline=True) if practice: # a clear PRACTICE badge in the bottom-left, like the overworld T(d, 16, H - 34, "PRACTICE", size=16, bold=True, fill=(245, 230, 150), outline=True) # the coins themselves are drawn by the client-side float animation (window.playCoinFloat), # which lands one at each pocket (you_x/par_x, H-74) as the persistent feedback. return img # ---- chest-swap animation layers (the chests physically slide when sides switch) ---------- # The chests are baked into the static render, so to animate a side-swap we ship three layers # to the client: a chest-less room backdrop (cached per house) + one transparent layer per # chest, which the browser slides across (see web_app.playSwap). Geometry must match _render_place. _SWAP_FLOOR_Y, _SWAP_TABLE_TOP, _SWAP_CW, _SWAP_CH = 372, 338, 170, 116 _SWAP_LX, _SWAP_RX = 130, W - 130 - 170 _SWAP_Y0 = _SWAP_TABLE_TOP - _SWAP_CH def _b64png(img): """PNG (with alpha) data-URL for a PIL image or a uint8 HxWx{3,4} array.""" if not isinstance(img, Image.Image): img = Image.fromarray(np.asarray(img, dtype=np.uint8)) buf = io.BytesIO() img.save(buf, format="PNG") return "data:image/png;base64," + base64.b64encode(buf.getvalue()).decode() def _layout_np(pair, side_bit): """numpy mirror of _layout: (left_letter, right_letter) for a pair + side bit.""" p0, p1 = int(pair[0]), int(pair[1]) return (p0, p1) if int(side_bit) == 0 else (p1, p0) def _render_room_backdrop(s): """The choice room WITHOUT the chests/keys/prompt, the still backdrop during a swap.""" htype = int(np.asarray(s.house_type)[_i(s.current_place)]) img = Image.new("RGB", (W, H), (0, 0, 0)) d = ImageDraw.Draw(img) sprites.draw_room(d, W, H, _SWAP_FLOOR_Y, 80, W - 80, _SWAP_TABLE_TOP, theme=sprites.ROOM_THEMES[htype]) you_x, par_x = W // 2 - 78, W // 2 + 78 sprites.draw_character(d, you_x, H - 12, 1, 0, **_player_pal()) sprites.draw_character(d, par_x, H - 12, 1, 0, **_partner_pal()) T(d, you_x, H - 118, "YOU", size=15, bold=True, fill=(255, 255, 255), center=True, outline=True) T(d, par_x, H - 118, "PARTNER", size=15, bold=True, fill=(255, 255, 255), center=True, outline=True) return np.asarray(img, dtype=np.uint8) def _render_feedback_overlay(text): """Practice feedback as a transparent full-frame layer, drawn with the SAME PIL font + dark outline as the in-game red directions (so it matches exactly), wrapped as ONE paragraph.""" img = Image.new("RGBA", (W, H), (0, 0, 0, 0)) d = ImageDraw.Draw(img) size = 20 fnt = sprites.font(size, bold=True) max_w = int(W * 0.92) words, lines, cur = text.split(), [], "" for w in words: # greedy word-wrap to the image width t = (cur + " " + w).strip() if not cur or d.textlength(t, font=fnt) <= max_w: cur = t else: lines.append(cur) cur = w if cur: lines.append(cur) y = 14 for ln in lines: T(d, W // 2, y, ln, size=size, bold=True, fill=(255, 90, 90), center=True, outline=True) y += int(size * 1.32) return img def _render_chest_layer(s, side): """A transparent full-frame layer holding just the one chest+key on `side` (0=left,1=right).""" stim_map = np.asarray(s.stim_map) prac_stim_map = np.asarray(s.prac_stim_map) practice = _i(s.practice) block_id = _i(s.current_block) letter = _i(s.left_letter) if side == 0 else _i(s.right_letter) x = _SWAP_LX if side == 0 else _SWAP_RX stim = int(prac_stim_map[letter]) if practice else int(stim_map[block_id, letter]) img = Image.new("RGBA", (W, H), (0, 0, 0, 0)) d = ImageDraw.Draw(img) sprites.draw_stim_chest(d, x, _SWAP_Y0, _SWAP_CW, _SWAP_CH, stim, is_open=False, highlight=False) sprites.draw_key(d, x + _SWAP_CW // 2 - 12, _SWAP_TABLE_TOP + 4, sprites.stim_color(stim)) return img def _render_rating(s): block_id = _i(s.current_block) cursor = _i(s.rating_cursor) sc, oc = _i(s.self_coins), _i(s.other_coins) opt = np.asarray(s.block_pairs)[block_id] practice = _i(s.practice) stim_map = np.asarray(s.stim_map) prac_stim_map = np.asarray(s.prac_stim_map) if practice: stim_l, stim_r = int(prac_stim_map[int(opt[0])]), int(prac_stim_map[int(opt[1])]) else: stim_l, stim_r = int(stim_map[block_id, int(opt[0])]), int(stim_map[block_id, int(opt[1])]) img = Image.new("RGB", (W, H), (40, 44, 60)) d = ImageDraw.Draw(img) T(d, W // 2, 56, "You're done at this house!", size=22, bold=True, fill=(255, 230, 120), center=True, outline=True) T(d, W // 2, 96, "Which box did you prefer?", size=20, bold=True, fill=(255, 255, 255), center=True, outline=True) sprites.draw_stim_chest(d, 70, 200, 120, 96, stim_l, is_open=False) sprites.draw_stim_chest(d, W - 70 - 120, 200, 120, 96, stim_r, is_open=False) n = RATING_MAX + 1 x0, x1, y = 250, W - 250, 250 for i in range(n): cx = x0 + (x1 - x0) * i // (n - 1) r = 17 if i == cursor else 11 fill = (241, 196, 15) if i == cursor else (95, 100, 124) d.ellipse([cx - r, y - r, cx + r, y + r], fill=fill, outline=(20, 24, 32), width=2) T(d, 130, 322, "strongly prefer", size=14, fill=(220, 220, 228), center=True, outline=True) T(d, 130, 340, "this box", size=16, bold=True, fill=sprites.stim_color(stim_l), center=True, outline=True) T(d, W - 130, 322, "strongly prefer", size=14, fill=(220, 220, 228), center=True, outline=True) T(d, W - 130, 340, "this box", size=16, bold=True, fill=sprites.stim_color(stim_r), center=True, outline=True) T(d, W // 2, 322, "no preference", size=14, fill=(220, 220, 228), center=True, outline=True) T(d, W // 2, H - 70, "Move with <- / ->, then press SPACE to confirm", size=18, bold=True, fill=(255, 255, 255), center=True, outline=True) return img def render_state(timestep): s = timestep.state mode = _i(s.mode) if mode == M_OVERWORLD: img = _render_overworld(s) elif mode == M_RATING: img = _render_rating(s) else: img = _render_place(s) return np.asarray(img, dtype=np.uint8) def vmap_render_fn(batched_timesteps): n = int(np.asarray(batched_timesteps.reward).shape[0]) imgs = [render_state(jtu.tree_map(lambda x: x[i], batched_timesteps)) for i in range(n)] return np.stack(imgs) # ---------------------------------------------------------------------------- # Logging: rich per-step data so we can export an OG-style trial CSV # ---------------------------------------------------------------------------- def custom_data_fn(timestep): s = timestep.state cp = jnp.clip(s.current_place, 0, N_PLACES - 1) # physical house cb = jnp.clip(s.current_block, 0, N_PLACES - 1) # experimental block (entry order) cl = jnp.clip(s.chosen_letter, 0, 3) ct = jnp.clip(s.trial, 0, N_TRIALS - 1) pid, gid = "", -1 # stash latest non-practice totals so the final screen can show points -> money try: pid = app.storage.user.get("pid", "") gid = orders.parse_pid(pid)[0] if int(s.practice) == 0: app.storage.user["self_points"] = int(s.self_coins) app.storage.user["partner_points"] = int(s.other_coins) # number of finished houses, so the app can checkpoint-save after each one app.storage.user["houses_done"] = int(jnp.sum(s.consumed)) # a running per-trial counter (deduped so it only ticks once per NEW outcome, not # once per step while accept_keys is held false), drives the local CSV refresh if int(s.mode) == M_OUTCOME: sig = f"{int(s.practice)}-{int(s.current_block)}-{int(s.trial)}" if app.storage.user.get("_trial_sig") != sig: app.storage.user["_trial_sig"] = sig app.storage.user["trials_done"] = app.storage.user.get("trials_done", 0) + 1 except Exception: pass # to_python because a reloaded session restores its state as numpy, and indexing # a numpy array below yields a numpy scalar that msgpack refuses. savequeue_fix # also repairs the restored types and absorbs a failed record; this is the third # of the three guards, and the cheapest. return savequeue_fix.to_python(dict( pid=pid, gid=gid, mode=s.mode, block=s.current_block, place=s.current_place, trial=s.trial, n_trials=s.n_trials, practice=s.practice, pair_code=s.pair_code[cb], house_type=s.house_type[cp], float_order=s.float_order[cb], left_letter=s.left_letter, right_letter=s.right_letter, left_stim=jnp.where(s.practice, s.prac_stim_map[s.left_letter], s.stim_map[cb, s.left_letter]), right_stim=jnp.where(s.practice, s.prac_stim_map[s.right_letter], s.stim_map[cb, s.right_letter]), chosen_side=s.chosen_side, chosen_letter=s.chosen_letter, chosen_stim=jnp.where(s.practice, s.prac_stim_map[cl], s.stim_map[cb, cl]), self_outcome=s.last_self_outcome, other_outcome=s.last_other_outcome, self_coins=s.self_coins, other_coins=s.other_coins, rating=s.ratings[cb], rating_cursor=s.rating_cursor, # per-option outcomes THIS trial (for A_self/A_other ... columns), as shown (+/-10/0) opt0_letter=s.block_pairs[cb, 0], opt1_letter=s.block_pairs[cb, 1], opt0_self=s.outcomes[cb, 0, 0, ct], opt0_other=s.outcomes[cb, 0, 1, ct], opt1_self=s.outcomes[cb, 1, 0, ct], opt1_other=s.outcomes[cb, 1, 1, ct], )) # ---------------------------------------------------------------------------- # Stage callbacks # ---------------------------------------------------------------------------- def _img_html(src): return ('