File size: 63,570 Bytes
fc7a567
bd2c7cd
fc7a567
bd2c7cd
 
 
 
3c85229
1a3e907
3c85229
1a3e907
 
 
 
bd2c7cd
 
cb32d35
bd2c7cd
 
 
 
 
 
 
fc7a567
 
bd2c7cd
916c1cd
c72006e
916c1cd
be9ce32
d3198c1
de32f5e
fc7a567
 
c72006e
 
fc7a567
 
 
 
 
33175c1
fc7a567
8c72a82
a1250db
bf22a94
c72006e
fc7a567
 
bd2c7cd
fc7a567
 
 
c8a6ce6
 
 
 
 
 
fc7a567
 
c72006e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e8598c4
c72006e
 
fc7a567
3c85229
fc7a567
cb32d35
967c298
3c85229
bd2c7cd
3c85229
cb32d35
3c85229
a044289
3c85229
 
 
 
fc7a567
 
 
3c85229
7b137ab
fc7a567
 
 
056d99b
94adeb7
fc7a567
bd2c7cd
 
 
fc7a567
bd2c7cd
 
 
 
 
3c85229
bd2c7cd
 
8c72a82
 
bd2c7cd
 
fc7a567
 
 
3c85229
fc7a567
 
 
9538496
 
 
 
 
 
 
 
 
967c298
 
cb32d35
 
a1250db
 
 
fc7a567
 
 
 
bd2c7cd
 
 
 
 
9538496
 
 
 
3c85229
bd2c7cd
 
fc7a567
 
3c85229
 
bd2c7cd
 
c72006e
 
bd2c7cd
 
 
9538496
 
bd2c7cd
9538496
 
 
cb32d35
 
9538496
 
 
967c298
 
3c85229
 
 
 
 
fc7a567
 
 
3c85229
fc7a567
 
 
bd2c7cd
 
 
 
 
fc7a567
 
a1250db
bd2c7cd
3c85229
 
 
 
bd2c7cd
a1250db
3c85229
9538496
 
fc7a567
bd2c7cd
 
 
 
 
c72006e
bd2c7cd
 
 
a1250db
bd2c7cd
a1250db
9538496
 
a1250db
cb32d35
a1250db
 
9538496
967c298
 
fc7a567
3c85229
fc7a567
bd2c7cd
3c85229
 
bd2c7cd
3c85229
 
 
 
 
bd2c7cd
 
8c72a82
3c85229
bd2c7cd
3c85229
 
9538496
 
967c298
9538496
3c85229
8c72a82
 
3c85229
9538496
 
c72006e
 
3c85229
 
bd2c7cd
e8598c4
c72006e
 
 
 
3c85229
 
967c298
 
a1250db
967c298
 
 
 
9538496
 
3c85229
bd2c7cd
 
 
967c298
fc7a567
bd2c7cd
94adeb7
3c85229
bd2c7cd
3c85229
967c298
9538496
bd2c7cd
 
cb32d35
 
ea29ada
bd2c7cd
 
 
 
 
94adeb7
bd2c7cd
 
 
9538496
 
bd2c7cd
 
 
 
3c85229
fc7a567
bd2c7cd
3c85229
 
 
bd2c7cd
 
3c85229
bd2c7cd
cb32d35
bd2c7cd
c72006e
 
bd2c7cd
fc7a567
 
 
 
bd2c7cd
fc7a567
bd2c7cd
3c85229
fc7a567
 
a1250db
 
 
 
 
 
9538496
 
a1250db
 
9538496
967c298
 
9538496
cb32d35
a1250db
 
 
 
 
 
 
 
 
 
ae1081d
 
 
 
 
 
 
bf22a94
 
a1250db
 
3421e60
 
a1250db
 
 
 
 
fc7a567
 
 
bd2c7cd
fc7a567
3c85229
8c72a82
bd2c7cd
8c72a82
 
fc7a567
 
 
 
 
 
33175c1
 
 
 
 
 
 
 
983eb92
a6f7c10
983eb92
cb32d35
 
 
 
983eb92
 
94adeb7
 
 
 
 
bd2c7cd
94adeb7
 
8c72a82
 
 
 
3c85229
 
bd2c7cd
3c85229
bd2c7cd
 
94adeb7
3c85229
 
8c72a82
bd2c7cd
 
 
 
3c85229
8c72a82
3c85229
8c72a82
 
 
 
 
 
bd2c7cd
8c72a82
 
 
 
 
 
bd2c7cd
 
 
b1b0f48
8c72a82
 
 
bd2c7cd
94adeb7
3c85229
8c72a82
 
33175c1
 
 
 
983eb92
bd2c7cd
8c72a82
 
 
 
 
cb32d35
 
f2298d3
 
8c72a82
983eb92
e8598c4
983eb92
729f62d
983eb92
 
 
729f62d
983eb92
729f62d
3c85229
 
 
94adeb7
 
bd2c7cd
 
7b137ab
 
 
 
 
 
 
 
732f6ed
a6f7c10
732f6ed
 
 
 
 
 
cb32d35
732f6ed
 
a6f7c10
967c298
 
 
 
 
e8598c4
729f62d
967c298
729f62d
e8598c4
967c298
e8598c4
729f62d
967c298
729f62d
 
967c298
729f62d
 
967c298
e8598c4
983eb92
d3198c1
967c298
 
 
d3198c1
 
bd2c7cd
3c85229
bd2c7cd
fc7a567
a1250db
cb32d35
 
bd2c7cd
 
fc7a567
bd2c7cd
c72006e
94adeb7
7b137ab
fc7a567
33175c1
 
94adeb7
33175c1
 
 
fc7a567
94adeb7
 
967c298
 
 
 
3c85229
 
cb32d35
967c298
 
a1250db
b34f8e3
3c85229
be9ce32
3c85229
c72006e
 
 
 
 
967c298
 
c8a6ce6
967c298
 
 
 
d3198c1
a6f7c10
732f6ed
 
 
983eb92
732f6ed
 
890c710
 
734d133
 
bd2c7cd
 
 
916c1cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e8598c4
916c1cd
 
 
 
 
 
 
983eb92
916c1cd
 
 
 
 
0e192ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
916c1cd
 
 
cb32d35
 
 
916c1cd
 
cb32d35
916c1cd
 
 
 
 
 
 
bd2c7cd
9538496
bd2c7cd
 
9538496
cb32d35
a1250db
cb32d35
 
 
 
 
bd2c7cd
 
 
b34f8e3
94adeb7
d3198c1
a1250db
bd2c7cd
a1250db
 
bd2c7cd
 
a1250db
bd2c7cd
 
94adeb7
 
bd2c7cd
a1250db
 
b34f8e3
a1250db
 
b34f8e3
a1250db
94adeb7
 
3c85229
 
fc7a567
bd2c7cd
3c85229
bd2c7cd
 
 
 
 
 
 
fc7a567
 
 
bd2c7cd
fc7a567
3c85229
 
fc7a567
 
 
bd2c7cd
 
 
 
9538496
 
a1250db
81f9092
a1250db
33175c1
 
94adeb7
a1250db
33175c1
 
 
accac24
 
9f06ea8
e8598c4
9f06ea8
 
 
 
 
33175c1
 
c8a6ce6
 
 
 
 
a1250db
9538496
 
 
 
bd2c7cd
cb32d35
 
bd2c7cd
cb32d35
bd2c7cd
 
9538496
 
 
 
 
c8a6ce6
bd2c7cd
 
 
 
fc7a567
 
586eefb
 
fc7a567
 
bd2c7cd
fc7a567
 
 
 
10e348e
 
 
1ce3dc3
10e348e
e8598c4
10e348e
1ce3dc3
 
10e348e
 
a044289
 
 
 
 
 
 
 
 
fc7a567
 
bd2c7cd
3c85229
fc7a567
 
bd2c7cd
3c85229
fc7a567
 
a1250db
 
 
 
 
 
 
 
 
c7a3196
a1250db
3421e60
a1250db
4895777
bf22a94
 
 
 
 
 
 
4895777
ae1081d
 
bf22a94
 
a1250db
 
 
 
10e348e
 
 
 
c72006e
 
10e348e
 
11318a1
 
 
c72006e
 
 
 
12599ab
e8598c4
c72006e
12599ab
 
 
 
 
 
 
 
 
c72006e
 
12599ab
 
 
 
 
c72006e
 
 
 
 
 
 
11318a1
 
734d133
 
 
 
 
11318a1
3b18c3d
734d133
 
967c298
 
0e192ea
be9ce32
0e192ea
734d133
 
 
f44164d
 
 
 
 
 
 
 
 
 
 
916c1cd
 
10e348e
 
c72006e
10e348e
916c1cd
 
 
 
 
 
32d488d
 
 
 
 
 
916c1cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a1250db
bd2c7cd
a1250db
bd2c7cd
 
 
8410662
bd2c7cd
 
 
94adeb7
 
 
c72006e
e8598c4
9f06ea8
 
c72006e
 
983eb92
400cce7
e8598c4
983eb92
 
fc7a567
983eb92
 
 
e8598c4
729f62d
400cce7
e8598c4
729f62d
fc7a567
729f62d
 
983eb92
 
 
 
94adeb7
983eb92
9f06ea8
 
729f62d
3c85229
9f06ea8
bd2c7cd
 
983eb92
 
e8598c4
 
983eb92
 
 
9f06ea8
983eb92
 
 
9f06ea8
 
983eb92
 
 
9f06ea8
 
c72006e
 
6ef786e
253d356
e8598c4
253d356
e8598c4
6ef786e
 
 
 
 
400cce7
 
bd2c7cd
 
 
94adeb7
 
 
a152862
 
 
 
 
c72006e
 
 
729f62d
e8598c4
729f62d
 
400cce7
e8598c4
729f62d
9f06ea8
e8598c4
729f62d
 
e8598c4
c72006e
e8598c4
253d356
cb32d35
e8598c4
bd2c7cd
 
 
a6f7c10
e8598c4
a6f7c10
 
 
 
 
 
 
 
 
e8598c4
 
 
a6f7c10
 
 
 
bf22a94
 
 
 
 
 
 
 
 
 
 
 
 
33175c1
 
 
94adeb7
983eb92
 
 
 
 
 
a6f7c10
983eb92
 
c8a6ce6
983eb92
 
33175c1
 
 
 
e8598c4
a6f7c10
 
983eb92
 
df66332
 
 
 
 
 
c8a6ce6
33175c1
 
94adeb7
 
33175c1
 
 
 
983eb92
 
 
 
 
 
 
9f06ea8
983eb92
 
 
 
 
33175c1
94adeb7
 
8410662
 
94adeb7
 
9f06ea8
983eb92
729f62d
983eb92
bf22a94
 
94adeb7
33175c1
c72006e
 
d3198c1
 
c72006e
e8598c4
bf22a94
 
81f9092
 
 
6fe78ac
 
b34f8e3
a152862
 
 
 
 
 
b34f8e3
 
 
 
 
983eb92
b34f8e3
983eb92
b34f8e3
a152862
b34f8e3
 
c72006e
a152862
239028e
 
 
e8598c4
239028e
 
a152862
 
81f9092
 
 
a152862
6fe78ac
 
a152862
b34f8e3
33175c1
 
94adeb7
 
983eb92
 
 
e8598c4
94adeb7
983eb92
729f62d
983eb92
94adeb7
 
33175c1
 
94adeb7
 
bd2c7cd
 
 
94adeb7
bd2c7cd
3c85229
a1250db
94adeb7
bd2c7cd
9f06ea8
3c85229
fc7a567
8d23ae4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
"""
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 ('<div id="stateImageContainer" style="display:flex;justify-content:center;align-items:center;">'
            f'<img id="stateImage" src="{src}" style="width:100%;height:100%;object-fit:contain;"></div>')


async def env_stage_display_fn(stage, container, timestep):
    image = nicewebrl.base64_npimage(stage.render_fn(timestep))
    with container.style("align-items: center;"):
        nicewebrl.clear_element(container)
        ui.html(_img_html(image))


def _arm_outcome_autoclose(mode):
    """Arm (OUTCOME) or cancel (any other screen) the outcome viewing-hold on the client.

    Called from step_and_send_timestep, which runs on EVERY transition, unlike display_fn,
    which nicewebrl only calls on episode resets (the per-trial image is swapped client-side).
    On the OUTCOME screen: lock keys for a minimum viewing time, then show 'Press SPACE' and
    let Space advance (it does NOT advance on its own; arrows stay blocked the whole time).
    """
    if int(mode) == M_OUTCOME:
        ui.run_javascript(
            f"window.accept_keys = false; window.__inOutcome = true;"
            f"if (window.armOutcomeTimer) window.armOutcomeTimer({OUTCOME_HOLD_MS});"
        )
    else:
        ui.run_javascript(
            "window.__inOutcome = false; window.accept_keys = true;"
            "if (window.cancelOutcomeTimer) window.cancelOutcomeTimer();"
        )


def never_success(timestep, params=None):
    return jnp.int32(0)


def all_done(timestep):
    return timestep.last()


class OrderedEnvStage(EnvStage):
    """Rebuilds env_params for THIS participant (from their PID) just before the reset.

    Safe under concurrency: env_params is only used by reset(), which runs synchronously
    at the very start of activate() with no await in between; step() ignores params.
    """
    async def activate(self, container):
        task = self.metadata.get("task", "main")
        try:
            app.storage.user["in_main"] = (task == "main")   # gates the 'Take a break' button
            if task == "practice":
                self.env_params = practice_params(app.storage.user.get("pid", "practice"))
            else:
                pid = app.storage.user.get("pid", "0001")
                # A parent and their child share one pid (BEAR dyads), so the role has to
                # reach make_order or they get the same 12 houses in the same order. Empty
                # for every non-dyad session, where it changes nothing.
                role = app.storage.user.get("role", "")
                # A pool entry, when the study assigned one, overrides both: the design is
                # then a function of the rando id and the pid is only a label.
                rando = app.storage.user.get("rando")
                n = int(app.storage.user.get("dev_trials", N_TRIALS))   # dev: fewer trials/house
                houses = app.storage.user.get("dev_houses")   # dev: fewer houses total
                active = dev_active_mask(int(houses)) if houses else _MAIN_ACTIVE
                self.env_params = build_env_params(
                    orders.make_order(pid, role, rando), n, active, 0)
        except Exception as e:
            logger.warning(f"order build failed, using default: {e}")
        await super().activate(container)

    async def step_and_send_timestep(self, container, update_display=True):
        # 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 = None
        s = None
        try:
            ts = self.get_user_data("stage_state").timestep
            s = ts.state
            mode = 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 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.
        #
        # clearSwap is the one exception: EVERY keypress re-enters this function, even ones
        # that don't change anything (e.g. a stray arrow press while awaiting_start is still
        # set, or the same trial re-stepped). _maybe_swap below only starts a swap once per
        # trial, so any such extra step used to call clearSwap() mid-slide and rip out the
        # overlay before its own animation/timeout finished -- a visible "rubberband" snap on
        # fast keypresses. playSwap() already clears any previous swap itself before drawing,
        # and self-clears via its own timeout, so it doesn't need this safety net while still
        # in CHOICE mode; only clear it here when actually leaving CHOICE (to OVERWORLD/RATING).
        if mode != M_OUTCOME:
            try:
                js = ("if(window.clearCoinFloat) window.clearCoinFloat();"
                      "if(window.hidePracticeFeedback) window.hidePracticeFeedback();")
                if mode != M_CHOICE:
                    js += "if(window.clearSwap) window.clearSwap();"
                ui.run_javascript(js)
            except Exception as e:
                logger.warning(f"overlay clear failed: {e}")
                await _log_glitch("overlay_clear", e)

        if mode is None:
            return
        try:
            if mode == M_OUTCOME:
                so = int(s.last_self_outcome)
                oo = int(s.last_other_outcome)
                cb = int(np.clip(int(s.current_block), 0, N_PLACES - 1))
                fo = int(np.asarray(s.float_order)[cb])
                cs = int(s.chosen_side)
                # chest-open clink, then the coins float to the pockets (sounds fire per coin)
                ui.run_javascript(
                    "if(window.clearSwap) window.clearSwap();"   # drop any mid-slide swap overlay
                    "if(window.sfx) window.sfx.chest();"
                    f"if(window.playCoinFloat) window.playCoinFloat({so},{oo},{fo},{cs});")
                if int(s.practice) == 1:        # red blinking guided narration for THIS step
                    step = PRACTICE_SCRIPT[min(int(s.trial), len(PRACTICE_SCRIPT) - 1)]
                    src = _b64png(_render_feedback_overlay(" ".join(step["narration"])))
                    ui.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'
                    # toast (we show our own 'press the space bar' prompt on the end card). It's
                    # created just after this hook, so sweep it a few times.
                    if int(s.practice) == 1:
                        act = np.asarray(s.house_active).astype(bool)
                        con = np.asarray(s.consumed).astype(bool)
                        if int((con & act).sum()) >= int(act.sum()):
                            ui.run_javascript(
                                "[40,150,350,700].forEach(function(t){setTimeout(function(){"
                                "document.querySelectorAll('.q-notification').forEach("
                                "function(e){e.remove();});},t);});")
                elif mode == M_CHOICE:
                    self._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 two
        chests have traded sides vs the previous trial, slide them across (window.playSwap)."""
        try:
            block = int(np.clip(int(s.current_block), 0, N_PLACES - 1))
            tr = int(s.trial)
            # only act ONCE per CHOICE trial. Pressing a wrong/blocked box (practice) re-enters
            # this trial unchanged, and without this guard the swap would replay each time.
            key = f"{int(s.practice)}-{block}-{tr}"
            if app.storage.user.get("_swap_key") == key:
                return
            app.storage.user["_swap_key"] = key
            if tr == 0:                                       # house entry: cache the backdrop
                bg = _b64png(_render_room_backdrop(s))
                ui.run_javascript(f"if(window.setSwapBackdrop) window.setSwapBackdrop({json.dumps(bg)});")
                return
            tp = np.asarray(s.trial_pairs)
            ss = np.asarray(s.side_schedule)
            pl, pr = _layout_np(tp[block, tr - 1], ss[block, tr - 1])
            cl, cr = int(s.left_letter), int(s.right_letter)
            if cl == pr and cr == pl and cl != cr:            # same two chests, sides exchanged
                lc = _b64png(_render_chest_layer(s, 0))
                rc = _b64png(_render_chest_layer(s, 1))
                ui.run_javascript(f"if(window.playSwap) window.playSwap({json.dumps(lc)},{json.dumps(rc)});")
        except Exception as e:
            logger.warning(f"chest swap animation failed: {e}")


def make_env_stage(name, params, metadata):
    return OrderedEnvStage(
        name=name, web_env=jax_web_env, action_keys=action_keys, action_to_name=action_to_name,
        env_params=params, render_fn=render_state, vmap_render_fn=vmap_render_fn, precompile=False,
        display_fn=env_stage_display_fn, evaluate_success_fn=never_success, check_finished=all_done,
        min_success=10_000, max_episodes=1, notify_success=False, msg_display_time=1500,
        custom_data_fn=custom_data_fn, metadata=metadata)


# ----------------------------------------------------------------------------
# Instruction text (shown by the web_app intro flow with Back/Next, mouse-only)
# ----------------------------------------------------------------------------
def _partner_age_phrase(role):
    """Kept for its role-branch call sites even though both roles now say the same thing,
    'young' read as unrelatable/unrealistic for a parent-child dyad study either way."""
    return "another person"


COVER_PART1 = """
You are an **adventurer** exploring the world to make some **money**. You wander from house to
house, and in each, you find two **treasure chests**. Open one with its key and you'll find coins.
"""


def cover_part3(role):
    partner_phrase = _partner_age_phrase(role)
    return f"""
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't
play** the game themselves. As you open chests, you'll collect coins for **yourself** and for
**your partner** at once. You're always playing for two! **Your partner** only earns or loses money
from **your** choices. Some chests are more likely to give coins to…

- **you** but not **your partner**.
- **your partner** but not **you**.
- **both** of you.
- **neither** of you.
"""


COVER_PART4 = """
The coins you collect add up across the whole game. At the very end, your coins become
**real money** (about **$1 per 100 coins, up to $6**), paid to both **you** and **your partner** as a
bonus pocket-money payment.

**Your goal:** open chests and figure out which ones are worth your while!
"""


HOW_TO_PLAY_WALK = """
- **Walk** with the **arrow keys**, and step onto a house to go inside. **One press = one step**.
  Press again to keep going, rather than holding the key down.
"""

HOW_TO_PLAY_CHOOSE = """
- Inside each house are **two unique chests**. Press the **left** or **right** arrow key to open one.
"""

HOW_TO_PLAY_FEEDBACK = """
- When you press the arrow key, the chest opens and shows what **you** and **your partner** got.
  After you saw the feedback, press **Space** to close it and start the next try.
"""

HOW_TO_PLAY_SWAP = """
- The two unique chests **swap places** between tries. Pay attention to the chest itself, not
  which side of the table it sits on (left or right).
"""

HOW_TO_PLAY_IDENTITY = """
- Each house has its own **two brand-new chests** you've never seen before. Within that house,
  a chest tends to give a certain amount of coins across your tries there, and if it's been good,
  it will likely **keep being good** for the rest of that house. A **new house always means new
  chests**. Nothing carries over, so pay attention again from scratch each time.
"""

HOW_TO_PLAY_VARIES = """
- No chest gives the same result **every single time**. Pay attention to the **pattern** over
  many tries, not just one trial.

Let's start with a quick **practice**!
"""


# ----------------------------------------------------------------------------
# Quiz (after the practice round). Wrong answers lock the buttons and just advance.
# ----------------------------------------------------------------------------
#: Counts the first pass, so 3 retries beyond it, before a still-wrong item is let through
#: rather than re-asked forever. Matches task_pe-cu-nicewebrl's day-quiz cap.
MAX_QUIZ_ATTEMPTS = 4


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.",
     True, "Correct: every choice shows a result for both <b>you</b> and <b>your partner</b>, so "
           "make sure you use this feedback throughout the game!"),
    ("All unique chests are equally likely to give coins.",
     False, "Not quite: some unique chests are more likely to give coins than others."),
    ("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: a chest's tendency doesn't change just because it's on the left or right "
           "side; only a brand-new house brings brand-new chests."),
    ("Once you enter a house, you must finish all the tries there before leaving.",
     True, "Correct: you finish every try in a house, then move on."),
]


def _feedback_body(feedback):
    """A quiz feedback string with its "Correct:" / "Not quite:" prefix removed and the
    sentence re-capitalised.

    The prefix is dropped because the screen already shows a coloured Correct/Not quite
    tag, and a wrong answer puts "The statement is FALSE." in front of this. Without the
    re-capitalisation that read, on screen, "The statement is FALSE. your partner is
    another person your age...", a sentence starting lowercase after a full stop. The
    first LETTER is capitalised, not the first character, because several of these open
    with a <b> tag.
    """
    # the em dash stays in this character class, and only here: it is a pattern, not
    # prose, and feedback written before 2026-11-09 used one in the prefix.
    txt = re.sub(r"^\s*(correct|not quite)\s*[\u2014\-:,]?\s*", "", feedback or "", flags=re.I)
    return re.sub(r"^((?:<[^>]+>|\s)*)([a-z])",
                  lambda m: m.group(1) + m.group(2).upper(), txt)


async def _ask_one(container, header, statement, correct, feedback, image=None,
                   screen_name="quiz", screen_index=None):
    async with screens.watch(screen_name, "quiz", screen_index) as _s:
        ans = await _ask_one_body(container, header, statement, correct, feedback, image, _s)
        # PsychoPy's <component>.keys and <component>.corr, per question.
        _s["keys"] = "TRUE" if ans else "FALSE"
        _s["corr"] = int(bool(ans) == bool(correct))
        _s["action"] = "submit"
        return ans


async def _ask_one_body(container, header, statement, correct, feedback, image=None,
                        _s=None):
    nicewebrl.clear_element(container)
    answer = {"val": None}
    done = asyncio.Event()
    with container.style("align-items:center; max-width:720px;"):
        with ui.card().style("background:#fbf6ff; border:1px solid #e6d9f7; border-radius:16px;"
                             "padding:18px 22px; align-items:center; box-shadow:none;"):
            ui.markdown(header)
            if image is not None:
                ui.image(_b64png(image)).style("width:200px; max-width:70vw; margin:2px 0 8px;")
            ui.markdown(statement)          # plain weight (not all-bold)
            fb = ui.html("")                # html (not markdown) so the green/red color is reliable
            cont = ui.button("Continue ➜", on_click=lambda: done.set()).props("rounded color=purple-6")
            cont.set_visibility(False)
            with ui.row() as choice_row:
                btn_t = ui.button("πŸ‘ TRUE").props("rounded color=positive")
                btn_f = ui.button("πŸ‘Ž FALSE").props("rounded color=negative")

        def choose(val):
            answer["val"] = val
            ok = (val == correct)
            # drop any leading "Correct:" / "Not quite:" so it isn't shown after our
            # βœ“/βœ— tag, and recapitalise what is left (see _feedback_body)
            txt = _feedback_body(feedback)
            tag = ('<span style="color:#27ae60;font-weight:bold">πŸŽ‰ Correct!</span> ' if ok
                   else '<span style="color:#e74c3c;font-weight:bold">πŸ˜… Not quite.</span> ')
            # The statement stays visible above, but a wrong answer only implied the right one
            # through the explanation text -- say it outright, so the question and the answer
            # are both plainly stated, not just the question plus a paraphrase of the answer.
            answer_line = ("" if ok else
                            f'<br><b>The statement is {"TRUE" if correct else "FALSE"}.</b> ')
            fb.set_content(tag + answer_line + txt)
            choice_row.set_visibility(False)   # TRUE/FALSE take turns with Continue, not both at once
            cont.set_visibility(True)

        btn_t.on("click", lambda: choose(True))
        btn_f.on("click", lambda: choose(False))
    await done.wait()
    return answer["val"]


def _quiz_icon(i):
    """One illustration per quiz item (index matches quiz_items()'s fixed order)."""
    icons = {
        0: lambda: sprites.draw_two_explorers_icon(_player_pal(), _partner_pal()),
        1: sprites.draw_feedback_close_icon,
        2: sprites.draw_consistency_icon,
        3: sprites.draw_money_icon,
        4: sprites.draw_swap_icon,
    }
    fn = icons.get(i)
    return fn() if fn else None


async def quiz_display(stage, container):
    """Ask each item once; lock the buttons after answering; no re-asking."""
    nicewebrl.clear_element(container)
    # clear any leftover 'press any arrow key to continue' toast from the practice stage
    ui.run_javascript("document.querySelectorAll('.q-notification').forEach(function(e){e.remove();});")
    ev = asyncio.Event()
    with container.style("align-items:center; max-width:720px;"):
        ui.markdown("## Let's see if everything's clear! πŸ€“")
        ui.markdown("We will now ask you a couple of **Quiz** questions to check that everything "
                    "makes sense.")
        ui.button("Start quiz πŸš€", on_click=lambda: ev.set()).props("rounded color=purple-6")
    async with screens.watch("quiz_intro", "quiz"):
        await ev.wait()

    responses = []
    quiz = quiz_items(app.storage.user.get("role", "c"))
    order = list(range(len(quiz)))
    random.shuffle(order)                       # randomise question order per participant
    for pos, i in enumerate(order):
        st, co, fb = quiz[i]
        header = f"### πŸ€“ **Quiz**: Question {pos + 1} of {len(quiz)}"
        ans = await _ask_one(container, header, st, co, fb, image=_quiz_icon(i),
                             screen_name=f"quiz_q{i}", screen_index=pos)
        responses.append(dict(quizIndex=i, position=pos, statement=st,
                              answer=("TRUE" if ans else "FALSE"),
                              correct_answer=("TRUE" if co else "FALSE"),
                              is_correct=bool(ans == co), attempt=1,
                              feedback=fb))

    # re-ask the missed ones at the end, until all are answered correctly -- capped per item
    # (task_pe-cu-nicewebrl's user asked for the same cap on their day quiz, which raised the
    # question here: this loop had none, and a participant who could not pass a given item for
    # any reason -- confusion, a device issue -- had no way through it within the task's own
    # flow). MAX_QUIZ_ATTEMPTS counts the first pass, so 3 retries beyond it; a still-wrong item
    # is let through flagged forced=True rather than looping forever.
    wrong = [r["quizIndex"] for r in responses if not r["is_correct"]]
    if wrong:
        nicewebrl.clear_element(container)
        okev = asyncio.Event()
        with container.style("align-items:center; max-width:720px;"):
            ui.markdown("### πŸ” Let's revisit a couple of questions")
            ui.markdown("Please answer these again before continuing.")
            ui.button("OK", on_click=lambda: okev.set()).props("rounded color=purple-6")
        await okev.wait()
    tries = {i: 1 for i in range(len(quiz))}
    while wrong:
        i = wrong[0]
        st, co, fb = quiz[i]
        tries[i] += 1
        # Name the retry after the item it re-asks. Without this every re-ask landed in
        # the timing file as plain "quiz", so a row saying corr 0 could not be tied to the
        # question it belonged to, and two retries of two different items looked alike.
        ans = await _ask_one(container, "### πŸ” **Quiz**: Try again", st, co, fb,
                             image=_quiz_icon(i),
                             screen_name=f"quiz_q{i}_r{tries[i]}", screen_index=-1)
        correct = bool(ans == co)
        capped = tries[i] >= MAX_QUIZ_ATTEMPTS
        responses.append(dict(quizIndex=i, position=-1, statement=st,
                              answer=("TRUE" if ans else "FALSE"),
                              correct_answer=("TRUE" if co else "FALSE"),
                              is_correct=correct, attempt=tries[i],
                              forced=bool(not correct and capped),
                              feedback=fb))
        if correct or capped:
            wrong.pop(0)

    nicewebrl.clear_element(container)
    ev2 = asyncio.Event()
    with container.style("align-items:center; max-width:720px;"):
        ui.markdown("## You're all set! πŸŽ‰")
        ui.image(_b64png(sprites.draw_houses_row_icon())).style(
            "width:280px; max-width:80vw; margin:2px 0 8px;")
        ui.markdown("The real adventure begins now, with **12 houses** to explore. "
                    "Click below, then use the **arrow keys** to play.")
        ui.markdown("If you feel tired at any point, feel free to press the **PAUSE** button "
                    "in the upper right to take a little break.")
        ui.button("Start the adventure πŸ—ΊοΈ", on_click=lambda: ev2.set()).props("rounded color=purple-6")
    await ev2.wait()
    return dict(responses=responses)


async def _ignore_keys(e, container):
    return  # quiz is mouse-only; ignore stray key presses


# ----------------------------------------------------------------------------
# Assemble experiment (intro: welcome/instructions/explorer live in web_app.py)
# ----------------------------------------------------------------------------
all_stages = [
    make_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.post_game_questionnaire_stage(),
]

experiment = SimpleExperiment(stages=all_stages, name="TreasureHuntForTwo")