Instruction rewrite, parent/child role, post-game questionnaire, and bug fixes
Browse files- Reword confusing/redundant instructions; split HOW_TO_PLAY into 3 shorter
screens; clarify that chest identity (not side) matters and stays
consistent all game but isn't 100% deterministic per trial.
- Add parent/child role selection at ID entry (URL param, storage, and
CSV/GitLab logging); "young person" wording now only applies to child
participants.
- Add post-game questionnaire (strategy, motivation, effort, task rating,
belief check, hypothetical parent/child battery), ported from the sibling
PE task's pattern.
- Sound: replace the on/off toggle with a No sound/Chimes/Retro picker.
- Add persistent Fullscreen button so participants can re-enter fullscreen
after exiting it.
- Fix: chest lids could stay visually open after an error in the per-step
overlay-clear hook; a held arrow key on house entry could auto-select a
chest (now requires an explicit SPACE press); mashing SPACE during the
outcome screen could wipe the coin feedback before the minimum view time;
the pause button stayed visible on the final screen.
- Add a lightweight "error" event channel to the data export for diagnosing
future stuck-game reports.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Files changed (6)
- CODEBOOK.md+2
- INSTRUCTION_CHANGES_LOG.mdAdded+123
- experiment_structure.py+116-28
- export_csv.py+21-1
- questionnaires.pyAdded+189
- web_app.py+86-31
149 unmodified lines15015115215315415546 unmodified lines202203204205206207149 unmodified lines| Column | Meaning ||--------|---------|| `started_at` / `ended_at` | First / last gameplay action (ISO). || `duration_min` | Minutes between them (includes breaks). || `n_breaks` / `total_break_ms` | Number of breaks and total break time (subtract for time-on-task). |46 unmodified lines| `attention_blocks` | Which blocks carry the attention check, e.g. `6_8` || `house_by_place` / `pos_by_place` | Physical house appearance / grid position per place slot || `houses_done` / `completed` / `last_saved` | Progress, completion flag, last-save timestamp |Use **`next_id.py`** to read this log and get the next ID to assign per group (+ a balancecheck of how often each box was used as each profile). The design columns are fully149 unmodified lines15015115215315415515646 unmodified lines203204205206207208209149 unmodified lines| Column | Meaning ||--------|---------|| `role` | `c` = child, `p` = parent — captured at ID entry (parent/child dyad study); each plays independently. Only affects instruction wording (e.g. "young person" vs "person") and the post-game questionnaire's family-member label, not randomisation/seeding. || `started_at` / `ended_at` | First / last gameplay action (ISO). || `duration_min` | Minutes between them (includes breaks). || `n_breaks` / `total_break_ms` | Number of breaks and total break time (subtract for time-on-task). |46 unmodified lines| `attention_blocks` | Which blocks carry the attention check, e.g. `6_8` || `house_by_place` / `pos_by_place` | Physical house appearance / grid position per place slot || `houses_done` / `completed` / `last_saved` | Progress, completion flag, last-save timestamp || `role` | `c` = child, `p` = parent (parent/child dyad study); does not affect the design columns above |Use **`next_id.py`** to read this log and get the next ID to assign per group (+ a balancecheck of how often each box was used as each profile). The design columns are fully
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123# Instruction / Content Text Change Log
Tracks every removed or changed instruction, quiz, cover-story, or otherparticipant-facing text, per the change plan in this session. Entries are inchronological order (most recent last). Each entry gives the file/location,the old text, the new text, and why.
---
## 2026-08-02 — Quiz wording: "meaning" → "value"
**File:** `experiment_structure.py`, `QUIZ` item 5 (~line 971)
- Old: `"Each unique chest keeps its meaning no matter where it appears on the screen."`- New: `"Each unique chest keeps its value no matter where it appears on the screen."`
Why: requested word swap — "value" is the more precise/less ambiguous term for what stays constant about a chest.
---
## 2026-08-02 — Practice narration: clarify "worth paying attention" sentence
**File:** `experiment_structure.py`, `PRACTICE_SCRIPT` step 2 (~line 490-491)
- Old second line: `"Each unique chest is more likely to give a certain number of coins no matter on which side of the table it sits, so it's worth paying attention."`- New second line: `"Pay attention to WHICH CHEST you pick, not which side it's on — that's what matters."`
Why: the old sentence didn't say what "paying attention" referred to, and mixed "position doesn't matter" with "worth attending to" in one confusing clause. New version names the chest itself as the thing to track. The fuller explanation (with the "consistent for the whole game" and "not deterministic" points) now lives once in the restructured HOW_TO_PLAY screens (see next entry) instead of being repeated here — removes redundancy.
---
## 2026-08-02 — HOW_TO_PLAY split into 3 shorter screens, "magic cups" analogy removed
**File:** `experiment_structure.py` (`HOW_TO_PLAY` constant, ~line 938-952) and `web_app.py` (`INTRO_PAGES`, ~line 519; `_intro_page()`, ~line 580-582)
Old (single page, `HOW_TO_PLAY`):```- **Walk** with the **arrow keys**, and step onto a house to go inside.- Inside are **two unique chests**. Press the **left** or **right** **arrow key** on your keyboard to open that chest.- Each **unique chest** brings a certain amount of coins — that's what matters. The chests **shuffle and swap places** between tries, like a **magic cups game** — keep your eye on the **chest** itself, not which side it's on!- The chest **opens and shows** what **you** and **your partner** got. After a couple of seconds a **Press SPACE** prompt appears — press **Space** to close it and start the next try.- Each house gives **you** **20 tries** — choose carefully, and finish all 20 before leaving each house.- Then you'll **rate which unique chest you preferred**, and head to the next house.
Let's start with a quick **practice**!```
New (split into `HOW_TO_PLAY_MOVE`, `HOW_TO_PLAY_CHESTS`, `HOW_TO_PLAY_VARIABILITY`, each its own intro screen):
`HOW_TO_PLAY_MOVE`:```- **Walk** with the **arrow keys**, and step onto a house to go inside.- Inside are **two unique chests**. Press the **left** or **right** arrow key to open one.- The chest **opens and shows** what **you** and **your partner** got. After a couple of seconds, press **Space** to close it and start the next try.- Each house gives **you 20 tries** — finish all 20 before leaving.```
`HOW_TO_PLAY_CHESTS`:```- Each **unique chest** (its color and pattern) tends to give a certain amount of coins — that's what matters, **not** where it's sitting.- The two chests **swap places** between tries — pay attention to the **chest itself**, not which side of the table it's on.- A chest's tendency stays the **same for the whole game** — if a chest has been good, it will likely keep being good, wherever you see it again.```
`HOW_TO_PLAY_VARIABILITY`:```- No chest gives the same result **every single time** — pay attention to the pattern over many tries, not just one outcome.- After your 20 tries in a house, you'll **rate which chest you preferred**, then head to the next house.
Let's start with a quick **practice**!```
Why:- Reduces one dense wall-of-text page to three shorter, single-idea screens (chunking request).- Drops the "magic cups" analogy (assumes cultural familiarity that may not translate) in favor of a plain statement of the same instruction.- Adds an explicit, previously-missing statement that chest tendencies stay consistent for the *whole game*, not just within a house — directly addresses the "does color mean the same thing in different rooms" question (yes, intentionally, so instructions now say so) and validates that "I always pick the same-colored chest because it's been good" is an expected, sound strategy rather than a possible confound.- Adds an explicit statement that no chest is 100% deterministic — addresses "each colored box doesn't always produce the same result" not being stated anywhere before.
---
## 2026-08-02 — "Young person" wording now branches on participant role (parent vs. child)
**File:** `experiment_structure.py` �� `COVER_STORY` and `QUIZ` converted from plain constants to`cover_story(role)` and `quiz_items(role)` functions (both take the new `app.storage.user["role"]`,`"c"` or `"p"`, captured at ID entry — see the parent/child role feature).
- Old (always): `"...you've been matched with an **anonymous stranger** — another young person **your** age..."` (COVER_STORY), and `"...<b>your partner</b> is another young person <b>your</b> age..."` (QUIZ item 1 feedback).- New: - Child participants (`role == "c"`): unchanged — `"another young person"`. - Parent participants (`role == "p"`): `"another person"` (drops "young").
Why: a parent participant's partner (also matched by age) isn't accurately described as "young" — this was flagged as making the cover story feel unrelatable/unrealistic. Scoped to role rather than removed everywhere, since it IS accurate for child participants (their partner is another child).
Call sites updated: `web_app.py` (`E.cover_story(app.storage.user.get("role","c"))` replacing `E.COVER_STORY`; `quiz_display()` in `experiment_structure.py` now calls `quiz_items(role)` instead of the old module-level `QUIZ` list).
---
## 2026-08-02 — New post-game questionnaire added (new file: `questionnaires.py`)
No questionnaire existed before. Six new screens now run after "Explore" and before thefinal coin-total screen, ported from the sibling task's already-running`task_pe-cu-nicewebrl/questionnaires.py` pattern (same self/partner/hypothetical-family-memberdesign) and re-worded for this task:
1. **Strategy** (free text): "What strategy (or strategies) did you use during the learning task?"2. **Motivation** (0-100 sliders, self vs. your real in-game partner): how motivated to win points / to avoid losing points, for YOURSELF and for your partner (4 items).3. **Effort** (0-100 sliders, self vs. partner): how much effort exerted to win points / to avoid losing points, for YOURSELF and for your partner (4 items).4. **Task rating**: how easy/difficult, how boring/interesting the task was (2 items).5. **Belief check**: "Did you believe that the other person would receive the money you earned for them?" (Yes/No).6. **Hypothetical cross-role** battery: "Now imagine {who} also played this same game" — `who` = "your parent" if `role == "c"`, "your child" if `role == "p"` (from the new parent/child role selector) — then asks the same motivated/effort/difficulty/interest questions about that imagined person, split self (imagined person earning for themselves) vs. other (imagined person earning for the real participant).
Why: none of this existed before; wording and self/partner/hypothetical-person structure taken verbatim from your notes and cross-checked against the equivalent already-running questionnaire in the PE sibling task for consistency across the two linked studies.22 unmodified lines2324252627282930313233343 unmodified lines3839404142432 unmodified lines46474849505181 unmodified lines13313413513613713846 unmodified lines18518618718818919038 unmodified lines22923023123223323423523623723823962 unmodified lines302303304305306307308179 unmodified lines48848949049149249349422 unmodified lines51751851952052152225 unmodified lines548549550551552553554275 unmodified lines83083183283383483583683783883984011 unmodified lines85285385485585685785885986011 unmodified lines87287387487587687735 unmodified lines91391491591691791891992092192292311 unmodified lines9359369379389399409419429439449459469479489499509519522 unmodified lines9559569579589599609619629634 unmodified lines96896997097197297397446 unmodified lines1021102210231024102510261027102810291030103112 unmodified lines104410451046104710481049105027 unmodified lines10781079108010811082108322 unmodified linesimport asyncioimport base64import ioimport jsonimport randomimport refrom typing import Optionalimport jaximport jax.numpy as jnpimport jax.tree_util as jtu3 unmodified linesimport spritesimport ordersimport nicewebrlfrom nicewebrl import JaxWebEnv, TimeStep, TimestepWrapperfrom nicewebrl import Stage, EnvStage, FeedbackStage2 unmodified lineslogger = get_logger(__name__)# ----------------------------------------------------------------------------# Constants# ----------------------------------------------------------------------------81 unmodified linesright_letter: jax.Arraychosen_side: jax.Arraychosen_letter: jax.Arraylast_self_outcome: jax.Arraylast_other_outcome: jax.Arrayrating_cursor: jax.Array46 unmodified linesself_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),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),38 unmodified linesenter_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))return _select(entering, enter_state, moved_state)def _choice(self, key, s, action, params):is_choice = (action == A_LEFT) | (action == A_RIGHT)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 outcome62 unmodified lines_select(s.mode == M_OUTCOME, oc,_select(s.mode == M_ATTENTION, at, rt))))done = (s.mode == M_RATING) & rt_donemade_choice = (s.mode == M_CHOICE) & ((action == A_LEFT) | (action == A_RIGHT))reward = jnp.where(made_choice, new_state.last_self_outcome, 0).astype(jnp.float32)return self._obs(new_state), new_state, reward, done, {}179 unmodified lines"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.","Each unique chest is more likely to give a certain number of coins no matter on which side of the table it sits, so it's worth paying attention.")),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.")),22 unmodified liness_out, o_out = _i(s.last_self_outcome), _i(s.last_other_outcome)chosen_side = _i(s.chosen_side)practice = _i(s.practice)htype = int(np.asarray(s.house_type)[place_id])house_name = sprites.HOUSE_NAMES[htype]accent = (255, 90, 90) if practice else (255, 230, 120) # practice = red, main = gold25 unmodified lines# ---- top line (choice prompt; practice feedback is a red blinking client overlay) ----if mode == M_CHOICE:if 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=14,275 unmodified lines# nicewebrl funnels EVERY state transition through here (display_fn only runs on# episode resets), so this is where we arm/cancel the OUTCOME auto-close.await super().step_and_send_timestep(container, update_display=update_display)try:ts = self.get_user_data("stage_state").timesteps = ts.statemode = int(s.mode)_arm_outcome_autoclose(mode)if mode == M_OUTCOME:so = int(s.last_self_outcome)oo = int(s.last_other_outcome)11 unmodified linesui.run_javascript("if(window.showPracticeFeedback) window.showPracticeFeedback("f"{json.dumps(src)});")else:ui.run_javascript("if(window.clearCoinFloat) window.clearCoinFloat();""if(window.hidePracticeFeedback) window.hidePracticeFeedback();""if(window.clearSwap) window.clearSwap();")if mode == M_OVERWORLD:ui.run_javascript("if(window.sfx) window.sfx.step();")# practice finished: remove the framework's 'press any arrow key to continue'11 unmodified linesself._maybe_swap(s)except Exception as e:logger.warning(f"outcome auto-close hook failed: {e}")def _maybe_swap(self, s):"""On a CHOICE screen: cache the room backdrop when a house is entered, and when the two35 unmodified lines# ----------------------------------------------------------------------------# Instruction text (shown by the web_app intro flow with Back/Next, mouse-only)# ----------------------------------------------------------------------------COVER_STORY = """You are an adventurer exploring the world to make some money. Inside each house are twotreasure chests — open one with its key and you'll find coins.Here's the twist: you've been matched with an **anonymous stranger** — another young person**your** age, from our community database, who is **not** taking part in this study. They **won'tplay** the game themselves. As **you** open chests, you'll collect coins for **yourself** and for**your partner** at once — so you're playing for two! **Your partner** only earns or loses money11 unmodified lines**Your goal:** open chests and figure out which ones are worth **your** while!"""HOW_TO_PLAY = """- **Walk** with the **arrow keys**, and step onto a house to go inside.- Inside are **two unique chests**. Press the **left** or **right** **arrow key** on yourkeyboard to open that chest.- Each **unique chest** brings a certain amount of coins — that's what matters. The chests**shuffle and swap places** between tries, like a **magic cups game** — keep your eye onthe **chest** itself, not which side it's on!- The chest **opens and shows** what **you** and **your partner** got. After a couple of secondsa **Press SPACE** prompt appears — press **Space** to close it and start the next try.- Each house gives **you** **20 tries** — choose carefully, and finish all 20 before leavingeach house.- Then you'll **rate which unique chest you preferred**, and head to the next house.Let's start with a quick **practice**!"""2 unmodified lines# ----------------------------------------------------------------------------# Quiz (after the practice round). Wrong answers lock the buttons and just advance.# ----------------------------------------------------------------------------QUIZ = [("**Your partner** is another participant who also plays this game on **your** behalf.",False, "Not quite — <b>your partner</b> is another young person <b>your</b> age that we ""randomly picked from our community database. They only earn or lose money based on ""<b>your</b> choices."),("After each choice **you** see what **you** got AND what **your partner** got.",4 unmodified lines("Coins turn into real money at the end (about $1 per 100 coins, up to $6), for both **you** ""and **your partner**.",True, "Correct — both <b>you</b> and <b>your partner</b> get a bonus payment based on the coins."),("Each unique chest keeps its meaning no matter where it appears on the screen.",True, "Correct — each unique chest tells you what it tends to give, wherever it shows up."),("Once **you** enter a house, **you** must finish all 20 choices before leaving.",True, "Correct — you make 20 choices in each house, then move on."),46 unmodified linesawait ev.wait()responses = []order = list(range(len(QUIZ)))random.shuffle(order) # randomise question order per participantfor pos, i in enumerate(order):st, co, fb = QUIZ[i]ans = await _ask_one(container, f"Quiz Question {pos + 1}/{len(QUIZ)}", st, co, fb)responses.append(dict(quizIndex=i, position=pos, statement=st,answer=("TRUE" if ans else "FALSE"),correct_answer=("TRUE" if co else "FALSE"),12 unmodified linesattempt = 2while wrong:i = wrong[0]st, co, fb = QUIZ[i]ans = await _ask_one(container, "Try again", st, co, fb)responses.append(dict(quizIndex=i, position=-1, statement=st,answer=("TRUE" if ans else "FALSE"),27 unmodified linesmake_env_stage("Practice", practice_params_default, dict(task="practice")),FeedbackStage(name="Quiz", display_fn=quiz_display, custom_key_press_fn=_ignore_keys),make_env_stage("Explore", main_params, dict(task="main")),]experiment = SimpleExperiment(stages=all_stages, name="TreasureHuntForTwo")22 unmodified lines2324252627282930313233343536373 unmodified lines414243444546472 unmodified lines5051525354555657585960616263646566676869707172737475767778798081 unmodified lines16216316416516616716816946 unmodified lines21621721821922022122238 unmodified lines26126226326426526626726826927027127227327427527662 unmodified lines339340341342343344345346179 unmodified lines52652752852953053153222 unmodified lines55555655755855956056125 unmodified lines587588589590591592593594595596597275 unmodified lines87387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390411 unmodified lines91691791891992092111 unmodified lines93393493593693793893935 unmodified lines97597697797897998098198298398498598698798898999099199211 unmodified lines10041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010312 unmodified lines103410351036103710381039104010411042104310444 unmodified lines104910501051105210531054105546 unmodified lines11021103110411051106110711081109111011111112111312 unmodified lines112611271128112911301131113227 unmodified lines11601161116211631164116511661167116811691170117122 unmodified linesimport asyncioimport base64import datetime as _dtimport ioimport jsonimport randomimport refrom typing import Optionalimport aiofilesimport jaximport jax.numpy as jnpimport jax.tree_util as jtu3 unmodified linesimport spritesimport ordersimport questionnairesimport nicewebrlfrom nicewebrl import JaxWebEnv, TimeStep, TimestepWrapperfrom nicewebrl import Stage, EnvStage, FeedbackStage2 unmodified lineslogger = get_logger(__name__)async def _log_glitch(where, message):"""Best-effort: append a lightweight 'error' event to the participant's data file (inaddition to the server-side logger.warning), so a stuck-game report shows up in theexported CSV instead of only in server logs that may not be checked."""try:seed = app.storage.user.get("seed")if seed is None:returnpid = 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# ----------------------------------------------------------------------------81 unmodified linesright_letter: jax.Arraychosen_side: jax.Arraychosen_letter: jax.Arrayawaiting_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 chestlast_self_outcome: jax.Arraylast_other_outcome: jax.Arrayrating_cursor: jax.Array46 unmodified linesself_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),38 unmodified linesenter_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 outcome62 unmodified lines_select(s.mode == M_OUTCOME, oc,_select(s.mode == M_ATTENTION, at, rt))))done = (s.mode == M_RATING) & rt_donemade_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, {}179 unmodified lines"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.")),22 unmodified liness_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])house_name = sprites.HOUSE_NAMES[htype]accent = (255, 90, 90) if practice else (255, 230, 120) # practice = red, main = gold25 unmodified lines# ---- 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 chestT(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=14,275 unmodified lines# nicewebrl funnels EVERY state transition through here (display_fn only runs on# episode resets), so this is where we arm/cancel the OUTCOME auto-close.await super().step_and_send_timestep(container, update_display=update_display)mode = Nones = Nonetry:ts = self.get_user_data("stage_state").timesteps = ts.statemode = int(s.mode)_arm_outcome_autoclose(mode)except Exception as e:logger.warning(f"outcome auto-close hook failed while reading state: {e}")await _log_glitch("read_state", e)# Clear stale open-chest/coin/swap overlays on every non-outcome step, INCLUDING when# the state above couldn't be read — a stuck-open chest lid is worse than a rare missed# animation, so this always runs regardless of what fails below.if mode != M_OUTCOME:try:ui.run_javascript("if(window.clearCoinFloat) window.clearCoinFloat();""if(window.hidePracticeFeedback) window.hidePracticeFeedback();""if(window.clearSwap) window.clearSwap();")except Exception as e:logger.warning(f"overlay clear failed: {e}")await _log_glitch("overlay_clear", e)if mode is None:returntry:if mode == M_OUTCOME:so = int(s.last_self_outcome)oo = int(s.last_other_outcome)11 unmodified linesui.run_javascript("if(window.showPracticeFeedback) window.showPracticeFeedback("f"{json.dumps(src)});")else:if mode == M_OVERWORLD:ui.run_javascript("if(window.sfx) window.sfx.step();")# practice finished: remove the framework's 'press any arrow key to continue'11 unmodified linesself._maybe_swap(s)except Exception as e:logger.warning(f"outcome auto-close hook failed: {e}")await _log_glitch("mode_dispatch", e)def _maybe_swap(self, s):"""On a CHOICE screen: cache the room backdrop when a house is entered, and when the two35 unmodified lines# ----------------------------------------------------------------------------# Instruction text (shown by the web_app intro flow with Back/Next, mouse-only)# ----------------------------------------------------------------------------def _partner_age_phrase(role):"""Parent participants aren't 'young' — only child participants get 'another young person'."""return "another person" if role == "p" else "another young person"def cover_story(role):partner_phrase = _partner_age_phrase(role)return f"""You are an adventurer exploring the world to make some money. Inside each house are twotreasure chests — open one with its key and you'll find coins.Here's the twist: you've been matched with an **anonymous stranger** — {partner_phrase}**your** age, from our community database, who is **not** taking part in this study. They **won'tplay** the game themselves. As **you** open chests, you'll collect coins for **yourself** and for**your partner** at once — so you're playing for two! **Your partner** only earns or loses money11 unmodified lines**Your goal:** open chests and figure out which ones are worth **your** while!"""HOW_TO_PLAY_MOVE = """- **Walk** with the **arrow keys**, and step onto a house to go inside.- Inside are **two unique chests**. Press the **left** or **right** arrow key to open one.- The chest **opens and shows** what **you** and **your partner** got. After a couple ofseconds, press **Space** to close it and start the next try.- Each house gives **you 20 tries** — finish all 20 before leaving."""HOW_TO_PLAY_CHESTS = """- Each **unique chest** (its color and pattern) tends to give a certain amount of coins —that's what matters, **not** where it's sitting.- The two chests **swap places** between tries — pay attention to the **chest itself**, notwhich side of the table it's on.- A chest's tendency stays the **same for the whole game** — if a chest has been good, it willlikely keep being good, wherever you see it again."""HOW_TO_PLAY_VARIABILITY = """- No chest gives the same result **every single time** — pay attention to the pattern overmany tries, not just one outcome.- After your 20 tries in a house, you'll **rate which chest you preferred**, then head to thenext house.Let's start with a quick **practice**!"""2 unmodified lines# ----------------------------------------------------------------------------# Quiz (after the practice round). Wrong answers lock the buttons and just advance.# ----------------------------------------------------------------------------def quiz_items(role):partner_phrase = _partner_age_phrase(role)return [("**Your partner** is another participant who also plays this game on **your** behalf.",False, f"Not quite — <b>your partner</b> is {partner_phrase} <b>your</b> age that we ""randomly picked from our community database. They only earn or lose money based on ""<b>your</b> choices."),("After each choice **you** see what **you** got AND what **your partner** got.",4 unmodified lines("Coins turn into real money at the end (about $1 per 100 coins, up to $6), for both **you** ""and **your partner**.",True, "Correct — both <b>you</b> and <b>your partner</b> get a bonus payment based on the coins."),("Each unique chest keeps its value no matter where it appears on the screen.",True, "Correct — each unique chest tells you what it tends to give, wherever it shows up."),("Once **you** enter a house, **you** must finish all 20 choices before leaving.",True, "Correct — you make 20 choices in each house, then move on."),46 unmodified linesawait ev.wait()responses = []quiz = quiz_items(app.storage.user.get("role", "c"))order = list(range(len(quiz)))random.shuffle(order) # randomise question order per participantfor pos, i in enumerate(order):st, co, fb = quiz[i]ans = await _ask_one(container, f"Quiz Question {pos + 1}/{len(quiz)}", st, co, fb)responses.append(dict(quizIndex=i, position=pos, statement=st,answer=("TRUE" if ans else "FALSE"),correct_answer=("TRUE" if co else "FALSE"),12 unmodified linesattempt = 2while wrong:i = wrong[0]st, co, fb = quiz[i]ans = await _ask_one(container, "Try again", st, co, fb)responses.append(dict(quizIndex=i, position=-1, statement=st,answer=("TRUE" if ans else "FALSE"),27 unmodified linesmake_env_stage("Practice", practice_params_default, dict(task="practice")),FeedbackStage(name="Quiz", display_fn=quiz_display, custom_key_press_fn=_ignore_keys),make_env_stage("Explore", main_params, dict(task="main")),questionnaires.strategy_stage(),questionnaires.motivation_stage(),questionnaires.effort_exerted_stage(),questionnaires.task_rating_stage(),questionnaires.belief_stage(),questionnaires.hypothetical_stage(),]experiment = SimpleExperiment(stages=all_stages, name="TreasureHuntForTwo")
11 unmodified lines12131415161713 unmodified lines3132333435363731 unmodified lines69707172737477 unmodified lines15215315415515615720 unmodified lines178179180181182183105 unmodified lines28929029129229329411 unmodified lines"""import csvimport globimport sysfrom datetime import datetime13 unmodified linesM_CHOICE, M_OUTCOME, M_RATING, M_ATTENTION = 1, 2, 3, 4COLUMNS = ["row_type", "pid", "gid", "orderID", "practice",# ---- trial ---- (blockIndex = experienced block 0..11 = OG block order; physical_* = the# house it happened in; float_order = which avatar's coin animates first)"blockIndex", "trialIndex", "physical_place", "physical_house", "float_order",31 unmodified lines"stim_A", "stim_B", "stim_C", "stim_D","stim_A_desc", "stim_B_desc", "stim_C_desc", "stim_D_desc","house_by_block", "place_by_block", "house_by_place", "pos_by_place", "blocks_visited_order",]77 unmodified lines"quiz_attempt": r.get("attempt", "")})continueif meta.get("type") == "Event":kind = d.get("kind", "")if kind == "break":20 unmodified lines"event_time": d.get("t", "")})elif kind == "tech":tech = dcontinueif meta.get("type") != "EnvStage":105 unmodified linespid = last.get("pid", "")summ = {**base, "row_type": "summary","pid": pid, "gid": last.get("gid", ""), "orderID": last.get("orderID", ""),"started_at": first_ts or "", "ended_at": last_ts or "","duration_min": _ms(first_ts, last_ts) / 60000.0 if first_ts and last_ts else "","n_breaks": len(breaks),11 unmodified lines1213141516171813 unmodified lines3233343536373831 unmodified lines707172737475767777 unmodified lines15515615715815916016116216316416516616716816920 unmodified lines190191192193194195196197198199200201202105 unmodified lines30830931031131231331411 unmodified lines"""import csvimport globimport jsonimport sysfrom datetime import datetime13 unmodified linesM_CHOICE, M_OUTCOME, M_RATING, M_ATTENTION = 1, 2, 3, 4COLUMNS = ["row_type", "pid", "gid", "role", "orderID", "practice",# ---- trial ---- (blockIndex = experienced block 0..11 = OG block order; physical_* = the# house it happened in; float_order = which avatar's coin animates first)"blockIndex", "trialIndex", "physical_place", "physical_house", "float_order",31 unmodified lines"stim_A", "stim_B", "stim_C", "stim_D","stim_A_desc", "stim_B_desc", "stim_C_desc", "stim_D_desc","house_by_block", "place_by_block", "house_by_place", "pos_by_place", "blocks_visited_order",# ---- post-game questionnaire (see questionnaires.py) ----"questionnaire_name", "measure", "responses_json",]77 unmodified lines"quiz_attempt": r.get("attempt", "")})continueif meta.get("type") == "FeedbackStage" and name.startswith("PostTask_"):# one row per post-game questionnaire battery (see questionnaires.py); the# individual slider/text answers are kept as a JSON blob rather than exploding# into dozens of one-off columnsrows.append({**base, "row_type": "questionnaire","questionnaire_name": name, "measure": d.get("measure", ""),"responses_json": json.dumps(d, default=str)})continueif meta.get("type") == "Event":kind = d.get("kind", "")if kind == "break":20 unmodified lines"event_time": d.get("t", "")})elif kind == "tech":tech = delif kind == "error":# diagnostic side-channel for stuck-game reports (see experiment_structure.py# _log_glitch) — reuses the click_label/click_tag columns for where/messagerows.append({**base, "row_type": "error", "event_kind": "error","pid": d.get("pid", ""), "gid": d.get("gid", ""),"click_label": d.get("where", ""), "click_tag": d.get("message", ""),"event_time": d.get("t", "")})continueif meta.get("type") != "EnvStage":105 unmodified linespid = last.get("pid", "")summ = {**base, "row_type": "summary","pid": pid, "gid": last.get("gid", ""), "orderID": last.get("orderID", ""),"role": tech.get("role", ""),"started_at": first_ts or "", "ended_at": last_ts or "","duration_min": _ms(first_ts, last_ts) / 60000.0 if first_ts and last_ts else "","n_breaks": len(breaks),
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189"""Post-game questionnaire stages for TreasureHuntForTwo, appended after the main "Explore"stage. Built as NiceWebRL FeedbackStages (like the existing Quiz), so each one collects adict of responses that gets logged like any other stage.
Structure ported from the sibling task (task_pe-cu-nicewebrl/questionnaires.py), whichalready implements this exact self/partner/hypothetical-family-member pattern for the sameparent/child dyad study: * Motivation / effort: self vs. the REAL in-game partner (win points / avoid losing points). * Task rating: difficulty, interest. * Belief check: did they believe the partner's payout was real? * Hypothetical: children imagine their parent playing this game; parents imagine their child playing it (app.storage.user["role"], set at ID entry — see web_app.pid_screen). * Strategy: free text."""
import asyncio
from nicegui import app, ui
import nicewebrlfrom nicewebrl import FeedbackStage
import orders
async def _ignore_keys(e, container): return
def _fb(name, display_fn): return FeedbackStage(name=name, display_fn=display_fn, custom_key_press_fn=_ignore_keys)
# ----------------------------------------------------------------------------# Generic slider battery (0-100, one row per item)# ----------------------------------------------------------------------------async def _slider_battery(container, title, intro, items, lo_label=None, hi_label=None, lo=0, hi=100, start=50): """items: list of (key, prompt) sharing lo_label/hi_label, or (key, prompt, item_lo_label, item_hi_label) to override the anchors for that one item. Returns {key: value}.""" nicewebrl.clear_element(container) ev = asyncio.Event() sliders = {} with container.style("align-items:center; max-width:680px;"): ui.markdown(f"## {title}") if intro: ui.markdown(intro) for item in items: key, prompt = item[0], item[1] item_lo = item[2] if len(item) > 2 else lo_label item_hi = item[3] if len(item) > 3 else hi_label with ui.column().style("width:100%; max-width:560px; margin-bottom:10px;"): ui.markdown(f"**{prompt}**") s = ui.slider(min=lo, max=hi, value=start).props("label-always") with ui.row().style("width:100%; justify-content:space-between;"): ui.label(item_lo).style("font-size:12px; color:#666;") ui.label(item_hi).style("font-size:12px; color:#666;") sliders[key] = s ui.button("Continue", on_click=lambda: ev.set()) await ev.wait() return {k: int(s.value) for k, s in sliders.items()}
def _partner_label(): pid = app.storage.user.get("partner_id") or orders.partner_id_for( app.storage.user.get("pid", "") or "0001") return f"your partner (#{pid})"
# ----------------------------------------------------------------------------# Motivation / effort — self vs. the real in-game partner# ----------------------------------------------------------------------------def motivation_stage(): async def _display(stage, container): p = _partner_label() res = await _slider_battery( container, "Motivation", "Think back to the task you just completed.", [("motiv_win_self", "How motivated were you to win points for YOURSELF?"), ("motiv_win_partner", f"How motivated were you to win points for {p}?"), ("motiv_avoid_self", "How motivated were you to avoid losing points for YOURSELF?"), ("motiv_avoid_partner", f"How motivated were you to avoid losing points for {p}?")], "Not at all motivated", "Extremely motivated") return dict(measure="post_motivation", **res) return _fb("PostTask_Motivation", _display)
def effort_exerted_stage(): async def _display(stage, container): p = _partner_label() res = await _slider_battery( container, "Effort", "", [("effort_win_self", "How much effort did you exert to win points for YOURSELF?"), ("effort_win_partner", f"How much effort did you exert to win points for {p}?"), ("effort_avoid_self", "How much effort did you exert to avoid losing points for YOURSELF?"), ("effort_avoid_partner", f"How much effort did you exert to avoid losing points for {p}?")], "Required no effort", "Required a lot of effort") return dict(measure="post_effort", **res) return _fb("PostTask_Effort", _display)
def task_rating_stage(): async def _display(stage, container): res = await _slider_battery( container, "About the task", "", [("task_difficulty", "How easy or difficult was the task?", "Very easy", "Very difficult"), ("task_interest", "How boring or interesting was the task?", "Very boring", "Very interesting")]) return dict(measure="post_task_rating", **res) return _fb("PostTask_TaskRating", _display)
def belief_stage(): """Manipulation check: did they believe the partner's payout was real?""" async def _display(stage, container): nicewebrl.clear_element(container) chosen = {"v": None} done = asyncio.Event() with container.style("align-items:center; max-width:640px;"): ui.markdown("## One more question") ui.markdown( "Did you believe that the other person would receive the money you " "earned for them?" ) radio = ui.radio({"Yes": "Yes", "No": "No"}).props("color=primary") submit = ui.button("Submit") cont = ui.button("Continue", on_click=lambda: done.set()) cont.set_visibility(False)
def go(): if radio.value is None or chosen["v"] is not None: return chosen["v"] = radio.value radio.disable(); submit.disable(); cont.set_visibility(True)
submit.on_click(go) await done.wait() return dict(measure="belief_check", believed_partner_paid=chosen["v"]) return _fb("PostTask_Belief", _display)
# ----------------------------------------------------------------------------# Hypothetical cross-role battery: children imagine their parent also played# this game; parents imagine their child did. role is set at ID entry# (web_app.pid_screen -> app.storage.user["role"], "c" or "p").# ----------------------------------------------------------------------------def _hypothetical_person(): return "your child" if app.storage.user.get("role") == "p" else "your parent"
def hypothetical_stage(): async def _display(stage, container): who = _hypothetical_person() intro = ( f"Now imagine {who} also played this same game.\n\n" "There are no right or wrong answers here — just your best guess." ) res = await _slider_battery( container, "Imagining the other generation", intro, [("hyp_motiv_self", f"How motivated do you think {who} would be to win points for themselves?"), ("hyp_motiv_other", f"How motivated do you think {who} would be to win points for YOU?"), ("hyp_effort_self", f"How much effort do you think {who} would exert to win points for themselves?"), ("hyp_effort_other", f"How much effort do you think {who} would exert to win points for YOU?")], "Not at all", "Extremely / a lot") res2 = await _slider_battery( container, "Imagining the other generation", "", [("hyp_difficulty", f"How easy or difficult do you think {who} would find the task?", "Very easy", "Very difficult"), ("hyp_interest", f"How boring or interesting do you think {who} would find the task?", "Very boring", "Very interesting")]) return dict(measure="hypothetical_cross_role", who=who, **res, **res2) return _fb("PostTask_Hypothetical", _display)
def strategy_stage(): """Free-text: what strategy did the participant use?""" async def _display(stage, container): nicewebrl.clear_element(container) done = asyncio.Event() with container.style("align-items:center; max-width:640px;"): ui.markdown("## Last question") ui.markdown("What strategy (or strategies) did you use during the learning task?") text = ui.textarea().props("outlined autogrow").style("width:100%;") ui.button("Continue", on_click=lambda: done.set()) await done.wait() return dict(measure="strategy", strategy_text=(text.value or "").strip()) return _fb("PostTask_Strategy", _display)8 unmodified lines910111213141592 unmodified lines10810911011111211332 unmodified lines146147148149150151152120 unmodified lines2732742752762772782792802812822832842852862872882894 unmodified lines2942952962972982993004 unmodified lines305306307308309310311312313314315316317318319320321322323324325326327328187 unmodified lines51651751851952052152252352452552652752852953053153253353453553653753819 unmodified lines55855956056156256356412 unmodified lines57757857958058158258358458583 unmodified lines66967067167267367467567639 unmodified lines71671771871972072169 unmodified lines791792793794795796797124 unmodified lines922923924925926927113 unmodified lines104110421043104410451046104710488 unmodified linesimport configimport nicewebrlfrom nicewebrl.logging import setup_logging, get_loggerfrom nicewebrl.utils import wait_for_button_or_keypressfrom nicewebrl import stages, TimeStepimport nicewebrl92 unmodified linesprolific_pid=app.storage.user.get("prolific_pid", ""),study_id=app.storage.user.get("study_id", ""),session_id=app.storage.user.get("session_id", ""),**info)except Exception as e:logger.warning(f"log_tech failed: {e}")32 unmodified lines"window.addEventListener('keydown', function(e){"" var isSpace = (e.key === ' ' || e.code === 'Space');"" if (window.__inOutcome && !isSpace){ e.preventDefault(); e.stopImmediatePropagation(); }"" if (window.__inOutcome && isSpace){ var p=document.getElementById('spacePrompt');"" if(p) p.style.display='none';"# clear the coins/feedback right now, so they can't linger onto the next screen (rating etc.)" if(window.clearCoinFloat) window.clearCoinFloat();"120 unmodified linesdef setup_sound():"""All sound is SYNTHESISED in the browser (Web Audio) — no asset files. Off by default;a 🔊/🔇 toggle controls a gentle background loop + event blips. Audio can only start aftera user gesture, so toggling it on (a click) is what unlocks it."""ui.add_body_html("<script>""window.sfxOn=false; window.__ac=null;""window.sfx={"" ac:function(){ if(!window.__ac){ try{window.__ac=new (window.AudioContext||window.webkitAudioContext)();}catch(e){} } return window.__ac; },"" tone:function(f,d,t,v,delay){ if(!window.sfxOn)return; var c=this.ac(); if(!c)return;"" var st=c.currentTime+(delay||0); var o=c.createOscillator(),g=c.createGain();"" o.type=t||'sine'; o.frequency.value=f;"" g.gain.setValueAtTime(0.0001,st); g.gain.exponentialRampToValueAtTime(v||0.2,st+0.02);"" g.gain.exponentialRampToValueAtTime(0.0001,st+d); o.connect(g); g.connect(c.destination);"" o.start(st); o.stop(st+d+0.03); },"4 unmodified lines" zero:function(){this.tone(500,0.16,'sine',0.06); this.tone(380,0.18,'sine',0.05,0.05);},"" step:function(){this.tone(170,0.05,'square',0.05);},"" swoosh:function(){if(!window.sfxOn)return;var c=this.ac();if(!c)return;var t=c.currentTime;"" var o=c.createOscillator(),g=c.createGain();o.type='sine';"" o.frequency.setValueAtTime(680,t);o.frequency.exponentialRampToValueAtTime(280,t+0.26);"" g.gain.setValueAtTime(0.0001,t);g.gain.exponentialRampToValueAtTime(0.10,t+0.02);"" g.gain.exponentialRampToValueAtTime(0.0001,t+0.26);o.connect(g);g.connect(c.destination);"4 unmodified lines"};""</script>")on = bool(app.storage.user.get("sound_on", False))# solid (not flat) so it stays visible over the game art, tucked into the very bottom-leftbtn = (ui.button(icon=("volume_up" if on else "volume_off")).props("round color=deep-purple-6").style("position:fixed; bottom:6px; left:6px; z-index:50; opacity:0.97;""box-shadow:0 1px 5px rgba(0,0,0,0.5);"))async def toggle():new = not bool(app.storage.user.get("sound_on", False))app.storage.user["sound_on"] = newbtn._props["icon"] = "volume_up" if new else "volume_off"btn.update()js = "true" if new else "false"await ui.run_javascript(f"window.sfxOn={js}; if(window.sfx){{var c=window.sfx.ac(); if(c)c.resume();"f" if({js}) window.sfx.startMusic(); else window.sfx.stopMusic();}}")btn.on("click", toggle)ui.run_javascript(f"window.sfxOn={'true' if on else 'false'};")def setup_telemetry():187 unmodified lines###################################### Participant ID + intro flow (mouse-only, Back/Next, no keyboard yet)#####################################INTRO_PAGES = ["welcome", "cover", "howto", "explorer"]async def pid_screen(container):"""Experimenter types the participant ID; it's stored and reflected in the URL."""nicewebrl.clear_element(container)ev = asyncio.Event()with container.style("align-items:center; max-width:600px;"):ui.markdown("**Experimenter:** enter the participant ID, then click Start.")pid_in = ui.input("Participant ID", value=str(app.storage.user.get("pid", "")))def start():pid = (pid_in.value or "").strip()app.storage.user["pid"] = pidtry:ui.run_javascript("history.replaceState(null,'','?pid='+encodeURIComponent(" + repr(pid) + "))")except Exception:pass19 unmodified linesui.markdown("Welcome! Click **Next** to learn how it works.")elif page == "cover":ui.markdown("## TreasureHuntForTwo!")ui.markdown(E.COVER_STORY)# a short 'matching' reveal -> the (deterministic, cover-story) anonymous partnerpartner = orders.partner_id_for(app.storage.user.get("pid", "") or "0001")app.storage.user["partner_id"] = partner12 unmodified linesf'You were matched with your partner (<b style="color:#1d6fb8">#{partner}</b> '"from our community database).</div>")ui.timer(0.1, reveal_partner, once=True)elif page == "howto":ui.markdown("## How to play")ui.markdown(E.HOW_TO_PLAY)elif page == "explorer":ui.markdown("## Choose your explorer")ui.markdown("Click the adventurer you'd like to be, then press **Next**.")83 unmodified linesasync def run_intro(container):await desktop_gate(container) # keyboard-device check + fullscreen prompt# if the ID was passed in the URL (?pid=...), skip the experimenter set-up screenif not app.storage.user.get("pid"):await pid_screen(container)idx = 0while idx < len(INTRO_PAGES):39 unmodified linesasync def finish_experiment(container):app.storage.user["experiment_finished"] = True# save quietly (no feedback prompt)with container:69 unmodified linestry:row = orders.manifest_row(app.storage.user["pid"])hd = int(app.storage.user.get("houses_done", 0))row.update(houses_done=hd, completed=int(hd >= E.N_PLACES), last_saved=_now_iso())await asyncio.to_thread(gitlab_save.append_to_log, row)except Exception as e:logger.warning(f"rando-log append failed: {e}")124 unmodified linesif pid_q and not app.storage.user.get("pid"):app.storage.user["pid"] = pid_q# dev/pilot shortcuts, e.g. ?dev=1&start=main&trials=3 (skip front matter; flagged in data)if request.query_params.get("dev") in ("1", "true", "yes"):app.storage.user["dev_mode"] = True113 unmodified linesasync def footer(footer_container):"""Empty footer — fullscreen is handled by the 'Continue in fullscreen' gate."""returnui.run(storage_secret=os.getenv("STORAGE_SECRET", "private key to secure the browser session cookie"),8 unmodified lines910111213141592 unmodified lines10810911011111211311432 unmodified lines147148149150151152153154155156120 unmodified lines2772782792802812822832842852862872882892902912922932942954 unmodified lines3003013023033043053064 unmodified lines311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343187 unmodified lines53153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457519 unmodified lines59559659759859960060112 unmodified lines61461561661761861962062162262362462562662762883 unmodified lines71271371471571671771871972039 unmodified lines76076176276376476576669 unmodified lines836837838839840841842843124 unmodified lines968969970971972973974975976977978113 unmodified lines1092109310941095109610971098109911001101110211038 unmodified linesimport configimport nicewebrlfrom nicewebrl.logging import setup_logging, get_loggerfrom nicewebrl.utils import wait_for_button_or_keypress, toggle_fullscreenfrom nicewebrl import stages, TimeStepimport nicewebrl92 unmodified linesprolific_pid=app.storage.user.get("prolific_pid", ""),study_id=app.storage.user.get("study_id", ""),session_id=app.storage.user.get("session_id", ""),role=app.storage.user.get("role", ""),**info)except Exception as e:logger.warning(f"log_tech failed: {e}")32 unmodified lines"window.addEventListener('keydown', function(e){"" var isSpace = (e.key === ' ' || e.code === 'Space');"" if (window.__inOutcome && !isSpace){ e.preventDefault(); e.stopImmediatePropagation(); }"# only clear the feedback once the minimum viewing time has actually elapsed# (window.accept_keys) — otherwise mashing/holding Space during the hold wipes the# coin/feedback overlay early even though the trial hasn't really advanced yet." if (window.__inOutcome && isSpace && window.accept_keys){ var p=document.getElementById('spacePrompt');"" if(p) p.style.display='none';"# clear the coins/feedback right now, so they can't linger onto the next screen (rating etc.)" if(window.clearCoinFloat) window.clearCoinFloat();"120 unmodified linesdef setup_sound():"""All sound is SYNTHESISED in the browser (Web Audio) — no asset files. "No sound" bydefault; a floating button opens a small menu to pick a sound style ("Chimes"/"Retro") orturn sound off again. Audio can only start after a user gesture, so picking a style (a click)is what unlocks it. window.sfxStyle picks the oscillator timbre; window.sfxOn just gateswhether any tone plays at all."""ui.add_body_html("<script>""window.sfxOn=false; window.sfxStyle='off'; window.__ac=null;""window.sfx={"" ac:function(){ if(!window.__ac){ try{window.__ac=new (window.AudioContext||window.webkitAudioContext)();}catch(e){} } return window.__ac; },"" tone:function(f,d,t,v,delay){ if(!window.sfxOn)return; var c=this.ac(); if(!c)return;"" var st=c.currentTime+(delay||0); var o=c.createOscillator(),g=c.createGain();"" o.type=(window.sfxStyle==='retro')?'square':(t||'sine'); o.frequency.value=f;"" g.gain.setValueAtTime(0.0001,st); g.gain.exponentialRampToValueAtTime(v||0.2,st+0.02);"" g.gain.exponentialRampToValueAtTime(0.0001,st+d); o.connect(g); g.connect(c.destination);"" o.start(st); o.stop(st+d+0.03); },"4 unmodified lines" zero:function(){this.tone(500,0.16,'sine',0.06); this.tone(380,0.18,'sine',0.05,0.05);},"" step:function(){this.tone(170,0.05,'square',0.05);},"" swoosh:function(){if(!window.sfxOn)return;var c=this.ac();if(!c)return;var t=c.currentTime;"" var o=c.createOscillator(),g=c.createGain();o.type=(window.sfxStyle==='retro')?'square':'sine';"" o.frequency.setValueAtTime(680,t);o.frequency.exponentialRampToValueAtTime(280,t+0.26);"" g.gain.setValueAtTime(0.0001,t);g.gain.exponentialRampToValueAtTime(0.10,t+0.02);"" g.gain.exponentialRampToValueAtTime(0.0001,t+0.26);o.connect(g);g.connect(c.destination);"4 unmodified lines"};""</script>")style = str(app.storage.user.get("sound_style", "off"))if style not in ("off", "chimes", "retro"):style = "off"icons = {"off": "volume_off", "chimes": "volume_up", "retro": "graphic_eq"}labels = {"off": "No sound", "chimes": "Chimes", "retro": "Retro"}# solid (not flat) so it stays visible over the game art, tucked into the very bottom-leftbtn = (ui.button(icon=icons[style]).props("round color=deep-purple-6").style("position:fixed; bottom:6px; left:6px; z-index:50; opacity:0.97;""box-shadow:0 1px 5px rgba(0,0,0,0.5);"))async def set_style(new_style):app.storage.user["sound_style"] = new_stylebtn._props["icon"] = icons[new_style]btn.update()on_js = "true" if new_style != "off" else "false"await ui.run_javascript(f"window.sfxStyle={new_style!r}; window.sfxOn={on_js};"f" if(window.sfx){{var c=window.sfx.ac(); if(c)c.resume();}}")with btn:with ui.menu():for s in ("off", "chimes", "retro"):ui.menu_item(labels[s], on_click=lambda s=s: set_style(s))ui.run_javascript(f"window.sfxStyle={style!r}; window.sfxOn={'true' if style != 'off' else 'false'};")def setup_telemetry():187 unmodified lines###################################### Participant ID + intro flow (mouse-only, Back/Next, no keyboard yet)#####################################INTRO_PAGES = ["welcome", "cover", "howto_move", "howto_chests", "howto_variability", "explorer"]async def pid_screen(container):"""Experimenter types the participant ID and picks their role (parent/child) for this dyadstudy; both are stored in app.storage.user['pid']/['role'] and reflected in the URL."""nicewebrl.clear_element(container)ev = asyncio.Event()with container.style("align-items:center; max-width:600px;"):ui.markdown("**Experimenter:** enter the participant ID, select their role, then click Start.")pid_in = ui.input("Participant ID", value=str(app.storage.user.get("pid", "")))sel = {"role": app.storage.user.get("role") or "c"}ui.markdown("Is this participant the **parent** or the **child**?")btns = {}def restyle():for r, b in btns.items():b.style("border:3px solid " + ("#7c5cff" if sel["role"] == r else "transparent") + ";")def pick_role(r):sel["role"] = rrestyle()with ui.row():for r, label in (("c", "Child"), ("p", "Parent")):btns[r] = (ui.button(label, on_click=lambda r=r: pick_role(r)).props("rounded color=deep-purple-6"))restyle()def start():pid = (pid_in.value or "").strip()role = sel["role"]app.storage.user["pid"] = pidapp.storage.user["role"] = roletry:ui.run_javascript("history.replaceState(null,'','?pid='+encodeURIComponent(" + repr(pid) + ")""+'&role='+encodeURIComponent(" + repr(role) + "))")except Exception:pass19 unmodified linesui.markdown("Welcome! Click **Next** to learn how it works.")elif page == "cover":ui.markdown("## TreasureHuntForTwo!")ui.markdown(E.cover_story(app.storage.user.get("role", "c")))# a short 'matching' reveal -> the (deterministic, cover-story) anonymous partnerpartner = orders.partner_id_for(app.storage.user.get("pid", "") or "0001")app.storage.user["partner_id"] = partner12 unmodified linesf'You were matched with your partner (<b style="color:#1d6fb8">#{partner}</b> '"from our community database).</div>")ui.timer(0.1, reveal_partner, once=True)elif page == "howto_move":ui.markdown("## How to play")ui.markdown(E.HOW_TO_PLAY_MOVE)elif page == "howto_chests":ui.markdown("## The chests")ui.markdown(E.HOW_TO_PLAY_CHESTS)elif page == "howto_variability":ui.markdown("## One more thing")ui.markdown(E.HOW_TO_PLAY_VARIABILITY)elif page == "explorer":ui.markdown("## Choose your explorer")ui.markdown("Click the adventurer you'd like to be, then press **Next**.")83 unmodified linesasync def run_intro(container):await desktop_gate(container) # keyboard-device check + fullscreen prompt# if BOTH the ID and role were passed in the URL (?pid=...&role=...), skip the# experimenter set-up screen; if either is missing, show it (role must always be picked)if not app.storage.user.get("pid") or not app.storage.user.get("role"):await pid_screen(container)idx = 0while idx < len(INTRO_PAGES):39 unmodified linesasync def finish_experiment(container):app.storage.user["experiment_finished"] = Trueapp.storage.user["in_main"] = False # hide the 'Take a break' button — nothing left to pause# save quietly (no feedback prompt)with container:69 unmodified linestry:row = orders.manifest_row(app.storage.user["pid"])hd = int(app.storage.user.get("houses_done", 0))row.update(houses_done=hd, completed=int(hd >= E.N_PLACES), last_saved=_now_iso(),role=app.storage.user.get("role", ""))await asyncio.to_thread(gitlab_save.append_to_log, row)except Exception as e:logger.warning(f"rando-log append failed: {e}")124 unmodified linesif pid_q and not app.storage.user.get("pid"):app.storage.user["pid"] = pid_q# parent/child role for this dyad study, e.g. ?role=c or ?role=prole_q = (request.query_params.get("role") or "").strip().lower()if role_q in ("c", "p") and not app.storage.user.get("role"):app.storage.user["role"] = role_q# dev/pilot shortcuts, e.g. ?dev=1&start=main&trials=3 (skip front matter; flagged in data)if request.query_params.get("dev") in ("1", "true", "yes"):app.storage.user["dev_mode"] = True113 unmodified linesasync def footer(footer_container):"""Footer shown on every screen: a 'Fullscreen' toggle so participants can get back intofullscreen if they ever exit it (Esc, OS shortcut, etc.) — the initial gate only requestsfullscreen once, with no way back in otherwise."""with footer_container:ui.button("Fullscreen", icon="fullscreen", on_click=toggle_fullscreen) \.props("flat").style("position:fixed; bottom:6px; right:6px; z-index:50; opacity:0.92;")ui.run(storage_secret=os.getenv("STORAGE_SECRET", "private key to secure the browser session cookie"),