File size: 49,368 Bytes
8c72a82
8d23ae4
8c72a82
94adeb7
 
8c72a82
9f06ea8
94adeb7
 
 
8c72a82
 
 
 
 
 
 
 
 
 
 
94adeb7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c72a82
 
 
 
 
94adeb7
8c72a82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94adeb7
 
8c72a82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94adeb7
 
8c72a82
 
 
94adeb7
80d591d
 
 
 
 
 
 
8c72a82
 
 
 
80d591d
8c72a82
 
80d591d
 
 
 
 
 
 
94adeb7
8c72a82
 
 
94adeb7
8c72a82
 
 
 
 
94adeb7
 
 
 
 
8c72a82
 
 
 
 
80d591d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c72a82
80d591d
 
 
 
94adeb7
80d591d
 
 
33175c1
 
 
 
94adeb7
80d591d
94adeb7
 
80d591d
 
94adeb7
80d591d
94adeb7
80d591d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e8598c4
80d591d
33175c1
94adeb7
80d591d
94adeb7
80d591d
94adeb7
80d591d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33175c1
 
983eb92
 
f2298d3
 
8c72a82
983eb92
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c72a82
 
cb32d35
8c72a82
96daa83
 
 
8c72a82
 
 
 
 
 
 
 
94adeb7
8c72a82
 
 
 
94adeb7
8c72a82
94adeb7
8c72a82
 
 
 
 
94adeb7
 
 
8c72a82
 
94adeb7
 
8c72a82
 
94adeb7
 
8c72a82
 
94adeb7
 
 
8c72a82
94adeb7
 
8c72a82
 
 
 
94adeb7
 
 
 
8c72a82
 
94adeb7
 
8c72a82
94adeb7
 
96daa83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94adeb7
 
 
8c72a82
 
 
 
 
 
 
94adeb7
8c72a82
 
 
 
 
94adeb7
8c72a82
94adeb7
8c72a82
 
 
94adeb7
8c72a82
 
94adeb7
 
8c72a82
 
b34f8e3
 
 
 
 
 
 
 
 
 
 
81f9092
 
 
b34f8e3
967c298
 
 
 
 
 
 
 
 
 
b34f8e3
 
967c298
 
 
b34f8e3
 
 
81f9092
e8598c4
81f9092
967c298
 
 
81f9092
 
 
 
 
 
b34f8e3
 
967c298
 
 
b34f8e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96daa83
 
 
b34f8e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96daa83
 
94adeb7
 
 
8c72a82
 
94adeb7
8c72a82
 
94adeb7
a92047f
d3198c1
 
a92047f
 
 
d3198c1
8c72a82
 
 
94adeb7
 
 
 
33175c1
 
 
94adeb7
33175c1
94adeb7
 
96daa83
 
 
 
 
 
 
 
 
 
 
 
 
94adeb7
 
 
 
 
 
 
 
 
 
 
33175c1
 
 
94adeb7
 
 
 
 
 
 
 
 
33175c1
94adeb7
 
33175c1
 
 
 
 
 
94adeb7
 
 
 
 
33175c1
94adeb7
33175c1
94adeb7
33175c1
 
94adeb7
 
983eb92
 
 
 
 
 
 
 
 
e8598c4
983eb92
 
 
 
 
 
 
 
 
e57dc60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94adeb7
 
 
 
 
 
 
7b137ab
 
 
 
94adeb7
 
 
 
 
 
 
 
 
 
 
 
 
f2298d3
94adeb7
 
 
8d23ae4
94adeb7
 
f2298d3
 
9f06ea8
 
 
f2298d3
 
 
 
 
 
 
 
 
 
 
 
 
 
9f06ea8
983eb92
f2298d3
 
 
 
 
 
983eb92
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f06ea8
 
983eb92
 
9f06ea8
 
 
983eb92
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f06ea8
983eb92
 
 
 
 
9f06ea8
983eb92
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
253d356
 
 
983eb92
 
253d356
983eb92
 
 
 
 
253d356
983eb92
 
 
9f06ea8
 
 
 
 
 
 
 
 
 
 
 
 
 
983eb92
 
 
 
 
 
 
 
9f06ea8
983eb92
9f06ea8
400cce7
9f06ea8
400cce7
983eb92
 
 
 
 
 
400cce7
 
983eb92
400cce7
 
 
983eb92
400cce7
983eb92
 
400cce7
983eb92
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f06ea8
 
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
"""
Procedural sprite drawing for TreasureHuntForTwo (PIL, no asset files).

Draws characters, houses, chests, coins, keys, themed rooms and a welcome splash
given screen coordinates. `experiment_structure.py` composes these.
"""
import math
import os

from PIL import Image, ImageDraw, ImageFont


def _darker(c, f=0.7):
    return tuple(int(x * f) for x in c)


def _lighter(c, f=1.3):
    return tuple(min(255, int(x * f)) for x in c)


# ---------------------------------------------------------------------------
# Fonts (DejaVu ships with matplotlib, which is already a dependency)
# ---------------------------------------------------------------------------
_FONT_CACHE = {}


def font(size, bold=False):
    key = (int(size), bool(bold))
    if key in _FONT_CACHE:
        return _FONT_CACHE[key]
    f = None
    try:
        import matplotlib
        name = "DejaVuSans-Bold.ttf" if bold else "DejaVuSans.ttf"
        f = ImageFont.truetype(os.path.join(matplotlib.get_data_path(), "fonts", "ttf", name), size)
    except Exception:
        f = ImageFont.load_default()
    _FONT_CACHE[key] = f
    return f


def text(d, x, y, s, size=18, bold=False, fill=(255, 255, 255), center=False, outline=False):
    """Draw text with the DejaVu font; center horizontally and/or add a dark outline."""
    fnt = font(size, bold)
    if center:
        w = d.textlength(s, font=fnt)
        x = x - w / 2
    kw = {}
    if outline:
        kw = dict(stroke_width=max(2, size // 10), stroke_fill=(20, 20, 20))
    d.text((x, y), s, fill=fill, font=fnt, **kw)


# ---------------------------------------------------------------------------
# Ground tiles + decorations
# ---------------------------------------------------------------------------
def _hash(wr, wc):
    return ((wr * 73856093) ^ (wc * 19349663)) & 0xFFFFFFFF


def draw_grass_tile(d, x, y, t, wr, wc):
    base = (74, 132, 68) if (wr + wc) % 2 == 0 else (68, 124, 62)
    d.rectangle([x, y, x + t - 1, y + t - 1], fill=base)
    h = _hash(wr, wc)
    if h % 3 == 0:
        gx, gy = x + 6 + (h % 7), y + 8 + (h % 11)
        d.line([gx, gy, gx, gy - 5], fill=(60, 110, 55), width=1)
        d.line([gx + 3, gy, gx + 3, gy - 4], fill=(60, 110, 55), width=1)
    if h % 17 == 0:
        draw_tree(d, x, y, t)
    elif h % 11 == 0:
        draw_bush(d, x, y, t)
    elif h % 7 == 0:
        draw_flower(d, x, y, t, h)


def draw_tree(d, x, y, t):
    cx = x + t // 2
    d.rectangle([cx - 3, y + t - 16, cx + 3, y + t - 4], fill=(96, 64, 36))
    d.ellipse([x + 4, y + 2, x + t - 4, y + t - 10], fill=(46, 110, 50))
    d.ellipse([x + 8, y + 6, x + t - 12, y + t - 16], fill=(60, 130, 64))


def draw_bush(d, x, y, t):
    d.ellipse([x + 6, y + t - 18, x + t - 6, y + t - 4], fill=(54, 116, 56))
    d.ellipse([x + 10, y + t - 20, x + t - 12, y + t - 10], fill=(64, 130, 66))


def draw_flower(d, x, y, t, h):
    fx, fy = x + 8 + (h % 9), y + 10 + ((h >> 3) % 12)
    colors = [(231, 76, 60), (241, 196, 15), (155, 89, 182), (236, 240, 241)]
    col = colors[h % len(colors)]
    d.line([fx, fy, fx, fy + 6], fill=(46, 110, 50), width=1)
    for dx, dy in ((-2, 0), (2, 0), (0, -2), (0, 2)):
        d.ellipse([fx + dx - 2, fy + dy - 2, fx + dx + 2, fy + dy + 2], fill=col)
    d.ellipse([fx - 1, fy - 1, fx + 1, fy + 1], fill=(241, 196, 15))


# ---------------------------------------------------------------------------
# Characters: blocky humanoid, faces movement, 2-frame walk cycle, 3 styles
#   style 0 = neutral (tuft), 1 = femme-coded (long hair + bow), 2 = masc-coded (cap + beard)
# ---------------------------------------------------------------------------
def draw_character(d, cx, cy, facing=0, frame=0,
                   shirt=(52, 120, 200), skin=(245, 205, 160),
                   hair=(70, 45, 25), pants=(58, 58, 92), mask=False, style=0,
                   accent=(236, 90, 150), kind="human", hairdo=None,
                   headband=None, glasses=False, tail=None):
    """cx, cy = feet (bottom-center). mask=True => anonymous masked partner.

    style 0/1/2 = human hair/gender cues (tuft / long-hair+bow / cap+beard).
    kind adds non-human looks: 'robot', 'cat', 'fox', 'plant'. Extras: hairdo
    ('afro'/'ponytail'), headband (colour), glasses (bool), tail (colour)."""
    w = 22
    x = cx - w // 2
    top = cy - 36
    head = 12
    hx = x + (w - head) // 2
    pants_d = _darker(pants, 0.8)
    legtop = top + 26

    # tail (cat/fox), behind the hips
    if tail and facing != 1 and not mask:
        d.polygon([(x + 2, legtop + 2), (x - 7, legtop - 5), (x - 8, legtop + 5)], fill=tail)
        d.polygon([(x - 6, legtop - 3), (x - 8, legtop + 2)], fill=_lighter(tail, 1.2))

    # legs
    if facing in (2, 3):
        off = 3 if frame else -3
        d.rectangle([x + 3 + off, legtop, x + 3 + off + 7, legtop + 10], fill=pants)
        d.rectangle([x + w - 10 - off, legtop, x + w - 3 - off, legtop + 10], fill=pants_d)
    else:
        ly1 = legtop + (2 if frame else 0)
        ly2 = legtop + (0 if frame else 2)
        d.rectangle([x + 2, ly1, x + 9, ly1 + 10], fill=pants)
        d.rectangle([x + w - 9, ly2, x + w - 2, ly2 + 10], fill=pants_d)

    # femme style: a skirt over the top of the legs
    if style == 1:
        d.polygon([(x + 1, top + 24), (x + w - 1, top + 24), (x + w + 2, legtop + 4), (x - 2, legtop + 4)],
                  fill=_lighter(shirt, 1.05))

    # arms + body
    d.rectangle([x - 1, top + 13, x + 3, top + 26], fill=_darker(shirt, 0.85))
    d.rectangle([x + w - 3, top + 13, x + w + 1, top + 26], fill=_darker(shirt, 0.85))
    d.rectangle([x + 2, top + 13, x + w - 2, top + 27], fill=shirt)

    # ---- hair / fur behind the head ----
    if not mask:
        if style == 1:
            d.rectangle([hx - 3, top + 1, hx, top + 24], fill=hair)
            d.rectangle([hx + head, top + 1, hx + head + 3, top + 24], fill=hair)
        if hairdo == "afro":
            d.ellipse([hx - 5, top - 6, hx + head + 5, top + 11], fill=hair)
        elif hairdo == "ponytail":
            d.ellipse([hx + head - 2, top - 1, hx + head + 6, top + 16], fill=hair)
        # ears (cat/fox)
        if kind in ("cat", "fox"):
            eh = 7 if kind == "cat" else 11
            for ex in (hx, hx + head - 4):
                d.polygon([(ex, top + 3), (ex + 2, top - eh), (ex + 4, top + 3)], fill=hair)
                d.polygon([(ex + 1, top + 2), (ex + 2, top - eh + 4), (ex + 3, top + 2)],
                          fill=_lighter(skin, 1.12))

    # ---- head ----
    d.rectangle([hx, top, hx + head, top + head], fill=skin)
    if kind == "robot":
        d.rectangle([hx, top, hx + head, top + 3], fill=_darker(skin, 0.78))   # brow panel
    else:
        d.rectangle([hx, top, hx + head, top + 4], fill=hair)                  # fringe

    # ---- eyes ----
    eye = (70, 222, 236) if kind == "robot" else (25, 25, 25)
    es = 3 if kind == "robot" else 2
    if mask and facing != 1:
        d.rectangle([hx - 1, top + 4, hx + head + 1, top + 9], fill=(40, 42, 55))
        d.rectangle([hx + 2, top + 6, hx + 4, top + 8], fill=(225, 225, 235))
        d.rectangle([hx + head - 4, top + 6, hx + head - 2, top + 8], fill=(225, 225, 235))
    elif facing == 1:
        d.rectangle([hx, top, hx + head, top + head - 2], fill=(_darker(skin, 0.78) if kind == "robot" else hair))
    else:
        if facing == 0:
            d.rectangle([hx + 2, top + 6, hx + 2 + es, top + 6 + es], fill=eye)
            d.rectangle([hx + head - 2 - es, top + 6, hx + head - 2, top + 6 + es], fill=eye)
        elif facing == 2:
            d.rectangle([hx + 1, top + 6, hx + 1 + es, top + 6 + es], fill=eye)
        elif facing == 3:
            d.rectangle([hx + head - 1 - es, top + 6, hx + head - 1, top + 6 + es], fill=eye)

    if mask or facing == 1:
        return

    # ---- whiskers (cat/fox) ----
    if kind in ("cat", "fox"):
        d.line([hx - 3, top + 8, hx + 2, top + 9], fill=(45, 45, 45), width=1)
        d.line([hx + head - 2, top + 9, hx + head + 3, top + 8], fill=(45, 45, 45), width=1)
        d.rectangle([hx + head // 2 - 1, top + 9, hx + head // 2 + 1, top + 11], fill=(60, 40, 40))  # nose

    # ---- on-top features ----
    if kind == "robot":                       # antenna + light
        d.line([hx + head // 2, top, hx + head // 2, top - 6], fill=(120, 126, 138), width=2)
        d.ellipse([hx + head // 2 - 2, top - 10, hx + head // 2 + 2, top - 6], fill=accent)
    elif kind == "plant":                     # leaf sprout
        d.ellipse([hx + head // 2 - 1, top - 8, hx + head // 2 + 6, top - 1], fill=(98, 188, 86))
        d.ellipse([hx + head // 2 - 6, top - 7, hx + head // 2 + 1, top], fill=(118, 206, 96))
    elif kind == "human" and hairdo is None:
        if style == 1:                        # bow
            d.polygon([(hx + 1, top - 2), (hx + 5, top + 1), (hx + 1, top + 3)], fill=accent)
            d.polygon([(hx + 9, top - 2), (hx + 5, top + 1), (hx + 9, top + 3)], fill=accent)
            d.ellipse([hx + 4, top - 1, hx + 7, top + 2], fill=_darker(accent, 0.8))
        elif style == 2:                      # cap brim + beard
            d.rectangle([hx - 2, top - 1, hx + head + 2, top + 3], fill=_darker(shirt, 0.7))
            d.rectangle([hx - 4, top + 2, hx + 2, top + 4], fill=_darker(shirt, 0.7))
            d.rectangle([hx + 1, top + 9, hx + head - 1, top + head], fill=_darker(hair, 0.9))
        else:                                 # neutral tuft
            d.rectangle([hx + head // 2 - 1, top - 3, hx + head // 2 + 1, top], fill=hair)

    # ---- accessories ----
    if headband:
        d.rectangle([hx - 1, top + 3, hx + head + 1, top + 5], fill=headband)
    if glasses:
        d.rectangle([hx + 1, top + 5, hx + 5, top + 9], fill=(208, 230, 244), outline=(35, 35, 40))
        d.rectangle([hx + head - 5, top + 5, hx + head - 1, top + 9], fill=(208, 230, 244), outline=(35, 35, 40))
        d.line([hx + 5, top + 7, hx + head - 5, top + 7], fill=(35, 35, 40), width=1)


# a roster of distinct explorers (the player picks one at the start), varied skin tones,
# hair, gender cues, plus a few non-human characters. Minecraft-ish but not a copy.
AVATARS = [
    dict(shirt=(46, 175, 150), skin=(238, 205, 170), hair=(95, 75, 55), pants=(60, 95, 95),
         style=0),                                            # 0 teal, light skin, tuft
    dict(shirt=(214, 92, 150), skin=(245, 205, 178), hair=(80, 45, 95), pants=(160, 75, 130),
         style=1, accent=(255, 220, 90)),                     # 1 pink, long hair + bow
    dict(shirt=(70, 110, 205), skin=(224, 178, 138), hair=(55, 38, 26), pants=(58, 58, 88),
         style=2),                                            # 2 blue, cap + beard
    dict(shirt=(232, 140, 40), skin=(126, 84, 54), hair=(28, 22, 18), pants=(92, 62, 42),
         style=0, hairdo="afro", headband=(245, 222, 80)),    # 3 dark skin, afro, headband
    dict(shirt=(72, 168, 96), skin=(178, 128, 92), hair=(40, 30, 22), pants=(64, 92, 70),
         style=1, hairdo="ponytail", accent=(120, 200, 230)), # 4 brown skin, ponytail
    dict(shirt=(150, 90, 200), skin=(242, 212, 182), hair=(64, 48, 32), pants=(80, 70, 110),
         style=0, glasses=True),                              # 5 purple, glasses
    dict(shirt=(150, 156, 166), skin=(180, 186, 198), hair=(120, 126, 138), pants=(108, 114, 128),
         style=0, kind="robot", accent=(240, 96, 96)),        # 6 robot
    dict(shirt=(120, 150, 210), skin=(176, 178, 190), hair=(128, 130, 142), pants=(96, 100, 116),
         style=0, kind="cat", tail=(128, 130, 142)),          # 7 grey tabby cat
    dict(shirt=(86, 168, 84), skin=(154, 204, 122), hair=(72, 150, 62), pants=(92, 142, 72),
         style=0, kind="plant"),                              # 8 plant sprite
    dict(shirt=(214, 112, 60), skin=(238, 172, 112), hair=(206, 112, 50), pants=(150, 92, 56),
         style=0, kind="fox", tail=(206, 112, 50)),           # 9 fox
]
PLAYER_PAL = AVATARS[0]
# the partner: unmasked, plain gender-neutral outfit (neutral, not flashy). Kept as the
# fallback/default look; PARTNER_AVATARS below is the randomised-per-participant roster.
PARTNER_PAL = dict(shirt=(122, 150, 128), skin=(234, 200, 170), hair=(92, 76, 60),
                   pants=(96, 100, 116), style=0)

# 4 partner looks, randomised once per participant (orders.partner_avatar_for) and used
# consistently everywhere the partner appears (matching reveal + in-game). Deliberately
# plain/muted (no headband/glasses/hairdo/accent flourishes) so the gender cue from `style`
# (1=femme-coded, 2=masc-coded) stays understated rather than a strong stereotype.
PARTNER_AVATARS = [
    dict(shirt=(150, 120, 140), skin=(234, 200, 170), hair=(80, 65, 55), pants=(92, 90, 108),
         style=1, accent=(200, 195, 180)),                       # 0 dusty mauve
    dict(shirt=(118, 140, 150), skin=(196, 150, 112), hair=(50, 38, 30), pants=(100, 96, 90),
         style=1, accent=(200, 195, 180)),                       # 1 dusty teal
    dict(shirt=(140, 130, 100), skin=(220, 180, 145), hair=(70, 55, 40), pants=(85, 80, 70),
         style=2),                                                # 2 olive/khaki
    dict(shirt=(110, 120, 140), skin=(150, 105, 75), hair=(35, 28, 22), pants=(70, 72, 85),
         style=2),                                                # 3 slate blue-grey
]
PARTNER_AVATAR_GENDERS = ["f", "f", "m", "m"]


# ---------------------------------------------------------------------------
# Houses. htype 0..11 = the 12 main house types; 12 = practice-only ("forest hut")
# ---------------------------------------------------------------------------
# 12 distinct main houses (0..11) + a practice-only one (12 = forest hut)
HOUSE_NAMES = ["castle", "cottage", "mansion", "treehouse", "tower", "barn",
               "windmill", "igloo", "tent", "pagoda", "lighthouse", "log cabin", "forest hut"]


def draw_house(d, bx, by, t, htype, completed=False):
    left, right = bx + 3, bx + t - 3
    bottom = by + t - 3
    top = by - 14
    midx = (left + right) // 2

    if completed:
        d.rectangle([left - 5, top - 5, right + 5, bottom + 5], outline=(241, 196, 15), width=3)

    if htype == 0:    # castle
        d.rectangle([left, top + 8, right, bottom], fill=(150, 150, 160))
        for cx in range(left, right - 3, 9):
            d.rectangle([cx, top + 2, cx + 5, top + 10], fill=(130, 130, 140))
        d.rectangle([midx - 5, bottom - 14, midx + 5, bottom], fill=(70, 50, 40))
        d.line([right - 4, top + 2, right - 4, top - 10], fill=(120, 120, 130), width=2)
        d.polygon([(right - 4, top - 10), (right + 6, top - 7), (right - 4, top - 4)], fill=(220, 60, 60))
    elif htype == 1:  # cottage
        d.rectangle([left + 2, top + 14, right - 2, bottom], fill=(245, 226, 190))
        d.polygon([(left, top + 16), (midx, top), (right, top + 16)], fill=(200, 80, 60))
        d.rectangle([midx - 5, bottom - 13, midx + 5, bottom], fill=(120, 80, 50))
        d.rectangle([left + 6, top + 20, left + 14, top + 28], fill=(150, 210, 235))
        d.ellipse([right - 14, bottom - 8, right - 8, bottom - 2], fill=(231, 76, 60))
    elif htype == 2:  # mansion
        d.rectangle([left, top + 10, right, bottom], fill=(214, 198, 170))
        d.rectangle([left, top + 4, right, top + 12], fill=(150, 60, 55))
        for wx in (left + 4, midx - 4, right - 12):
            d.rectangle([wx, top + 16, wx + 8, top + 24], fill=(150, 210, 235))
            d.rectangle([wx, top + 28, wx + 8, top + 36], fill=(150, 210, 235))
        d.rectangle([midx - 6, bottom - 16, midx + 6, bottom], fill=(110, 70, 45))
        d.line([left + 3, top + 12, left + 3, bottom], fill=(240, 240, 235), width=2)
        d.line([right - 3, top + 12, right - 3, bottom], fill=(240, 240, 235), width=2)
    elif htype == 3:  # treehouse
        d.rectangle([midx - 4, top + 18, midx + 4, bottom], fill=(96, 64, 36))
        d.ellipse([left - 2, top - 6, right + 2, top + 30], fill=(46, 120, 52))
        d.rectangle([left + 6, top + 12, right - 6, top + 30], fill=(140, 95, 55))
        d.polygon([(left + 4, top + 14), (midx, top + 2), (right - 4, top + 14)], fill=(120, 80, 45))
        d.rectangle([midx - 3, top + 20, midx + 3, top + 30], fill=(70, 45, 25))
        d.line([midx + 6, top + 30, midx + 6, bottom], fill=(110, 80, 50), width=2)
    elif htype == 4:  # tower
        tl, tr = midx - 11, midx + 11
        d.rectangle([tl, top + 6, tr, bottom], fill=(120, 110, 170))
        d.polygon([(tl - 3, top + 8), (midx, top - 14), (tr + 3, top + 8)], fill=(95, 70, 160))
        text(d, midx - 4, top - 12, "*", size=14, bold=True, fill=(241, 196, 15))
        d.rectangle([midx - 4, top + 18, midx + 4, top + 28], fill=(150, 210, 235))
        d.rectangle([midx - 5, bottom - 12, midx + 5, bottom], fill=(70, 55, 95))
    elif htype == 5:  # barn
        d.rectangle([left, top + 14, right, bottom], fill=(178, 70, 58))
        d.polygon([(left, top + 16), (left + 6, top + 4), (right - 6, top + 4), (right, top + 16)],
                  fill=(146, 52, 44))
        d.rectangle([midx - 8, bottom - 18, midx + 8, bottom], fill=(120, 78, 50))
        d.rectangle([midx - 8, bottom - 18, midx + 8, bottom], outline=(245, 240, 230), width=2)
        d.line([midx, bottom - 18, midx, bottom], fill=(245, 240, 230), width=1)
        d.rectangle([midx - 4, top + 6, midx + 4, top + 12], fill=(240, 220, 150))
    elif htype == 6:  # windmill
        d.rectangle([midx - 12, top + 12, midx + 12, bottom], fill=(214, 206, 190))
        d.polygon([(midx - 14, top + 14), (midx, top + 2), (midx + 14, top + 14)], fill=(150, 90, 60))
        for ang in ((-10, -10, 10, 4), (10, -10, -4, 10)):
            d.line([midx + ang[0], top + 4 + ang[1], midx + ang[2], top + 4 + ang[3]],
                   fill=(120, 80, 50), width=3)
        d.line([midx - 12, top - 6, midx + 12, top + 14], fill=(120, 80, 50), width=3)
        d.line([midx + 12, top - 6, midx - 12, top + 14], fill=(120, 80, 50), width=3)
        d.rectangle([midx - 4, bottom - 12, midx + 4, bottom], fill=(90, 64, 44))
    elif htype == 7:  # igloo
        d.ellipse([left, top + 6, right, bottom + 8], fill=(225, 232, 244))
        d.rectangle([left, bottom - 4, right, bottom + 8], fill=(225, 232, 244))
        for ix in range(left + 4, right - 2, 10):
            d.line([ix, top + 8, ix, bottom], fill=(200, 210, 226), width=1)
        d.ellipse([midx - 7, bottom - 12, midx + 7, bottom + 4], fill=(120, 150, 180))
    elif htype == 8:  # tent
        d.polygon([(midx, top), (left, bottom), (right, bottom)], fill=(214, 120, 70))
        d.polygon([(midx, top), (midx - 6, bottom), (midx + 6, bottom)], fill=(70, 50, 40))
        d.line([midx, top, midx, top - 8], fill=(110, 80, 50), width=2)
        d.polygon([(midx, top - 8), (midx + 9, top - 5), (midx, top - 2)], fill=(220, 60, 60))
    elif htype == 9:  # pagoda
        for k, yy in enumerate((top + 6, top + 18, top + 30)):
            inset = 2 + k * 3
            d.polygon([(left + inset - 4, yy + 8), (midx, yy), (right - inset + 4, yy + 8)],
                      fill=(176, 70, 60))
            d.rectangle([left + inset, yy + 8, right - inset, yy + 14], fill=(214, 200, 180))
        d.rectangle([left + 8, top + 38, right - 8, bottom], fill=(190, 110, 80))
        d.rectangle([midx - 4, bottom - 12, midx + 4, bottom], fill=(90, 50, 40))
    elif htype == 10:  # lighthouse
        tl, tr = midx - 11, midx + 11
        for k, yy in enumerate(range(top + 6, bottom, 12)):
            c = (224, 80, 70) if k % 2 == 0 else (242, 242, 242)
            d.rectangle([tl, yy, tr, yy + 12], fill=c)
        d.rectangle([tl - 2, top + 2, tr + 2, top + 8], fill=(80, 80, 90))
        d.ellipse([midx - 6, top - 8, midx + 6, top + 4], fill=(255, 230, 130))
    elif htype == 11:  # log cabin
        d.rectangle([left, top + 12, right, bottom], fill=(150, 104, 62))
        for yy in range(top + 16, bottom, 8):
            d.line([left, yy, right, yy], fill=(120, 82, 48), width=2)
        d.polygon([(left - 2, top + 14), (midx, top), (right + 2, top + 14)], fill=(110, 74, 44))
        d.rectangle([right - 14, top - 2, right - 8, top + 12], fill=(90, 60, 40))  # chimney
        d.rectangle([midx - 5, bottom - 14, midx + 5, bottom], fill=(70, 46, 28))
    else:             # 12 forest hut (practice only): mossy dome + toadstool
        d.ellipse([left, top + 6, right, bottom + 6], fill=(96, 120, 70))
        d.rectangle([left + 4, top + 22, right - 4, bottom], fill=(120, 90, 60))
        d.rectangle([midx - 4, bottom - 12, midx + 4, bottom], fill=(70, 50, 35))
        d.rectangle([right - 12, bottom - 9, right - 9, bottom], fill=(150, 110, 70))
        d.ellipse([right - 16, bottom - 14, right - 5, bottom - 7], fill=(210, 70, 60))
        d.ellipse([right - 14, bottom - 13, right - 12, bottom - 11], fill=(245, 245, 245))

    if completed:
        bx2, by2 = right - 2, top - 2
        d.ellipse([bx2 - 8, by2 - 8, bx2 + 8, by2 + 8], fill=(39, 174, 96), outline=(255, 255, 255), width=2)
        d.line([bx2 - 4, by2, bx2 - 1, by2 + 4], fill=(255, 255, 255), width=2)
        d.line([bx2 - 1, by2 + 4, bx2 + 5, by2 - 4], fill=(255, 255, 255), width=2)


# ---------------------------------------------------------------------------
# Chests, coins, keys
# ---------------------------------------------------------------------------
def draw_chest(d, x, y, w, h, color, is_open=False, highlight=False):
    body_top = y + h // 3
    dark = _darker(color, 0.7)
    if highlight:
        d.rectangle([x - 6, y - 6, x + w + 6, y + h + 6], outline=(241, 196, 15), width=5)
    d.rectangle([x, body_top, x + w, y + h], fill=color, outline=(40, 30, 20), width=3)
    d.rectangle([x + w // 2 - 6, body_top + (h // 4), x + w // 2 + 6, y + h], fill=(218, 165, 32))
    d.line([x, body_top + (h // 6), x + w, body_top + (h // 6)], fill=dark, width=3)
    if not is_open:
        d.rectangle([x, y + 4, x + w, body_top + 4], fill=_lighter(color, 1.1), outline=(40, 30, 20), width=3)
        d.ellipse([x + w // 2 - 5, body_top - 4, x + w // 2 + 5, body_top + 6], fill=(218, 165, 32))
    else:
        d.rectangle([x, y - 12, x + w, y + 2], fill=dark, outline=(40, 30, 20), width=3)
        d.rectangle([x + 4, body_top - 4, x + w - 4, body_top + 6], fill=(30, 24, 16))
        d.rectangle([x + 6, body_top + 2, x + w - 6, body_top + 6], fill=(241, 196, 15))


# 26 genuinely distinct box stimuli (0..23 used in the main task, 24..25 for practice).
# Each = a unique combination of colour x material x lid-shape x pattern. The look is an
# arbitrary, randomised label.
STIM_PALETTE = [
    (214, 70, 64), (52, 130, 214), (54, 168, 96), (232, 150, 40), (150, 90, 196),
    (40, 176, 168), (224, 110, 150), (130, 150, 64), (184, 120, 72), (90, 110, 206),
    (206, 184, 64), (152, 152, 160), (108, 184, 214),
]                                                                  # 13 distinct hues
MATERIALS = ["plain", "wood", "stone", "metal", "woven", "dots", "stripes", "marble"]
LIDS = ["flat", "arched", "peaked"]
N_STIM = 26
# human-readable hue names, aligned 1:1 with STIM_PALETTE above
COLOR_NAMES = ["red", "blue", "green", "orange", "purple", "teal", "pink",
               "olive", "brown", "indigo", "yellow", "grey", "sky-blue"]

# Hand-picked, clearly-distinct designs for the 4 PRACTICE chests (ids 24-27). Each is named
# by its texture + colour in the tutorial (experiment_structure.PRACTICE_SCRIPT), so the look
# here must match those words. These ids are practice-only (the main pool is 0..23).
PRACTICE_STIM_DESIGN = {
    24: dict(color=(184, 120, 72), mat="woven",   lid="arched", desc="brown woven"),    # kind
    25: dict(color=(52, 130, 214), mat="stripes", lid="flat",   desc="blue striped"),   # greedy
    26: dict(color=(72, 170, 96),  mat="dots",    lid="peaked", desc="green dotted"),   # altruism
    27: dict(color=(98, 102, 116), mat="stone",   lid="arched", desc="dark stone"),     # both-loss
}


def stim_color(sid):
    d = PRACTICE_STIM_DESIGN.get(int(sid))
    if d:
        return d["color"]
    return STIM_PALETTE[int(sid) % len(STIM_PALETTE)]


def stim_describe(sid):
    """A verbal label for a chest stimulus, e.g. 'green arched woven', matches stim_design."""
    sid = int(sid)
    d = PRACTICE_STIM_DESIGN.get(sid)
    if d:
        return d["desc"]
    color = COLOR_NAMES[sid % len(STIM_PALETTE)]
    mat = MATERIALS[sid % len(MATERIALS)]
    lid = LIDS[(sid // 2) % len(LIDS)]
    return f"{color} {lid}-lid {mat}".replace(" plain", "").strip()


def stim_design(sid):
    sid = int(sid)
    d = PRACTICE_STIM_DESIGN.get(sid)
    if d:
        return (d["color"], d["mat"], d["lid"])
    return (STIM_PALETTE[sid % len(STIM_PALETTE)],
            MATERIALS[sid % len(MATERIALS)],
            LIDS[(sid // 2) % len(LIDS)])


def _fill_material(d, x0, y0, x1, y1, color, mat, accent):
    d.rectangle([x0, y0, x1, y1], fill=color)
    if mat == "wood":
        for yy in range(y0 + 5, y1, 9):
            d.line([x0, yy, x1, yy], fill=_darker(color, 0.82), width=2)
    elif mat == "stone":
        dk = _darker(color, 0.78)
        for k, yy in enumerate(range(y0, y1, 12)):
            d.line([x0, yy, x1, yy], fill=dk, width=1)
            off = 0 if k % 2 == 0 else (x1 - x0) // 4
            for xx in range(x0 + off, x1, max(8, (x1 - x0) // 2)):
                d.line([xx, yy, xx, min(yy + 12, y1)], fill=dk, width=1)
    elif mat == "metal":
        d.rectangle([(x0 + x1) // 2 - 4, y0, (x0 + x1) // 2 + 4, y1], fill=_lighter(color, 1.3))
        for ry in (y0 + 4, y1 - 7):
            for rx in range(x0 + 7, x1 - 4, 16):
                d.ellipse([rx, ry, rx + 4, ry + 4], fill=_darker(color, 0.65))
    elif mat == "woven":
        for yy in range(y0 + 4, y1, 8):
            d.line([x0, yy, x1, yy], fill=_lighter(color, 1.16), width=2)
        for xx in range(x0 + 4, x1, 8):
            d.line([xx, y0, xx, y1], fill=_darker(color, 0.85), width=1)
    elif mat == "dots":
        for yy in range(y0 + 9, y1, 15):
            for xx in range(x0 + 9, x1, 17):
                d.ellipse([xx - 3, yy - 3, xx + 3, yy + 3], fill=accent)
    elif mat == "stripes":
        for xx in range(x0 + 5, x1, 17):
            d.rectangle([xx, y0, xx + 6, y1], fill=accent)
    elif mat == "marble":
        for k in range(3):
            yy = y0 + 7 + k * max(6, (y1 - y0) // 3)
            d.line([(x0 + 4, yy), ((x0 + x1) // 2, yy - 6), (x1 - 4, yy + 4)],
                   fill=_lighter(color, 1.28), width=2)


def draw_stim_chest(d, x, y, w, h, stim_id, is_open=False, highlight=False):
    """One of 26 distinct chests (colour x material x lid-shape x pattern)."""
    color, mat, lid = stim_design(stim_id)
    accent = _lighter(color, 1.45) if sum(color) < 410 else _darker(color, 0.6)
    body_top = y + h // 3
    dark = _darker(color, 0.7)
    if highlight:
        d.rectangle([x - 6, y - 6, x + w + 6, y + h + 6], outline=(241, 196, 15), width=5)
    _fill_material(d, x, body_top, x + w, y + h, color, mat, accent)
    d.rectangle([x, body_top, x + w, y + h], outline=(40, 30, 20), width=3)
    d.rectangle([x + w // 2 - 6, body_top + h // 5, x + w // 2 + 6, y + h], fill=(218, 165, 32))
    if not is_open:
        if lid == "arched":
            d.pieslice([x, y - 6, x + w, body_top + 12], 180, 360,
                       fill=_lighter(color, 1.08), outline=(40, 30, 20), width=3)
        elif lid == "peaked":
            d.polygon([(x, body_top + 4), (x + w // 2, y - 6), (x + w, body_top + 4)],
                      fill=_lighter(color, 1.08), outline=(40, 30, 20))
            d.line([x, body_top + 4, x + w, body_top + 4], fill=(40, 30, 20), width=3)
        else:  # flat
            _fill_material(d, x, y + 4, x + w, body_top + 4, _lighter(color, 1.08), mat, accent)
            d.rectangle([x, y + 4, x + w, body_top + 4], outline=(40, 30, 20), width=3)
        d.ellipse([x + w // 2 - 5, body_top - 4, x + w // 2 + 5, body_top + 6], fill=(218, 165, 32))
    else:
        d.rectangle([x, y - 12, x + w, y + 2], fill=dark, outline=(40, 30, 20), width=3)
        d.rectangle([x + 4, body_top - 4, x + w - 4, body_top + 6], fill=(30, 24, 16))
        d.rectangle([x + 6, body_top + 2, x + w - 6, body_top + 6], fill=(241, 196, 15))


def draw_coin(d, cx, cy, value, r=22):
    """value is the coin amount (e.g. +100 / -100 / 0). Drawn 'floating'."""
    label = f"+{value}" if value > 0 else (str(value) if value < 0 else "0")
    if value > 0:
        d.ellipse([cx - r, cy - r, cx + r, cy + r], fill=(241, 196, 15), outline=(191, 150, 10), width=3)
        tcol = (120, 90, 10)
    elif value < 0:
        d.ellipse([cx - r, cy - r, cx + r, cy + r], fill=(231, 76, 60), outline=(150, 40, 30), width=3)
        tcol = (255, 235, 235)
    else:                                  # 0: pale coin; the "0" is an OPEN ring (not filled)
        d.ellipse([cx - r, cy - r, cx + r, cy + r], fill=(228, 228, 232),
                  outline=(20, 20, 24), width=3)
        rw, rh = int(r * 0.34), int(r * 0.48)          # oval ring -> reads as a hollow "0"
        d.ellipse([cx - rw, cy - rh, cx + rw, cy + rh], outline=(20, 20, 24), width=3)
        return
    text(d, cx, cy - 9, label, size=17, bold=True, fill=tcol, center=True, outline=True)


def draw_key(d, x, y, color):
    d.ellipse([x, y, x + 10, y + 10], outline=color, width=3)
    d.line([x + 10, y + 5, x + 24, y + 5], fill=color, width=3)
    d.line([x + 20, y + 5, x + 20, y + 10], fill=color, width=3)
    d.line([x + 24, y + 5, x + 24, y + 11], fill=color, width=3)


# ---------------------------------------------------------------------------
# Themed indoor rooms (interior matches the house type)
# ---------------------------------------------------------------------------
# per house type: wall, seam, floor, floor_line, accent(torch/decor), window=True/False
ROOM_THEMES = [
    dict(wall=(120, 122, 132), seam=(104, 106, 116), floor=(96, 96, 104), line=(80, 80, 88), accent=(240, 160, 50)),     # 0 castle
    dict(wall=(214, 196, 162), seam=(198, 180, 148), floor=(160, 116, 74), line=(138, 98, 60), accent=(231, 120, 90)),   # 1 cottage
    dict(wall=(196, 178, 150), seam=(176, 158, 132), floor=(150, 120, 92), line=(120, 94, 70), accent=(214, 180, 90)),   # 2 mansion
    dict(wall=(96, 120, 78), seam=(82, 104, 66), floor=(140, 100, 60), line=(116, 82, 48), accent=(90, 170, 90)),        # 3 treehouse
    dict(wall=(96, 80, 140), seam=(82, 68, 124), floor=(74, 60, 110), line=(60, 48, 92), accent=(255, 220, 90)),         # 4 tower
    dict(wall=(168, 84, 72), seam=(150, 70, 60), floor=(176, 150, 96), line=(150, 124, 78), accent=(240, 210, 120)),     # 5 barn
    dict(wall=(206, 198, 178), seam=(188, 180, 160), floor=(150, 128, 92), line=(124, 104, 72), accent=(200, 150, 90)),  # 6 windmill
    dict(wall=(188, 208, 224), seam=(168, 190, 210), floor=(176, 196, 214), line=(150, 172, 194), accent=(120, 170, 210)), # 7 igloo
    dict(wall=(196, 130, 96), seam=(176, 112, 82), floor=(150, 110, 76), line=(126, 90, 60), accent=(232, 150, 90)),     # 8 tent
    dict(wall=(150, 96, 92), seam=(132, 82, 78), floor=(140, 104, 80), line=(116, 84, 62), accent=(214, 120, 100)),      # 9 pagoda
    dict(wall=(120, 140, 156), seam=(102, 122, 138), floor=(132, 138, 146), line=(108, 114, 122), accent=(255, 220, 130)), # 10 lighthouse
    dict(wall=(140, 104, 68), seam=(120, 86, 54), floor=(150, 110, 70), line=(124, 88, 54), accent=(220, 160, 90)),      # 11 log cabin
    dict(wall=(110, 132, 92), seam=(94, 116, 78), floor=(132, 100, 64), line=(108, 80, 50), accent=(210, 90, 80)),       # 12 forest hut (practice)
]


def draw_room(d, W, H, floor_y, table_x0, table_x1, table_top, theme=None):
    th = theme or ROOM_THEMES[1]
    d.rectangle([0, 0, W, floor_y], fill=th["wall"])
    for x in range(0, W, 64):
        d.line([x, 0, x, floor_y], fill=th["seam"], width=1)
    d.line([0, floor_y, W, floor_y], fill=_darker(th["wall"], 0.7), width=3)
    # window with sky
    wx0, wy0, wx1, wy1 = 60, 78, 196, 184
    d.rectangle([wx0, wy0, wx1, wy1], fill=(120, 186, 222))
    d.rectangle([wx0 + 6, wy0 + 6, (wx0 + wx1) // 2 - 2, wy1 - 6], fill=(150, 205, 235))
    d.rectangle([(wx0 + wx1) // 2 + 2, wy0 + 6, wx1 - 6, wy1 - 6], fill=(150, 205, 235))
    d.ellipse([wx1 - 42, wy0 + 12, wx1 - 22, wy0 + 32], fill=(245, 230, 150))
    d.rectangle([wx0 - 4, wy0 - 4, wx1 + 4, wy1 + 4], outline=_darker(th["wall"], 0.6), width=4)
    # accent torch/sconce on the right wall
    tx = W - 130
    d.rectangle([tx, 104, tx + 8, 136], fill=_darker(th["wall"], 0.6))
    d.ellipse([tx - 7, 84, tx + 15, 108], fill=th["accent"])
    d.ellipse([tx - 3, 86, tx + 11, 102], fill=_lighter(th["accent"], 1.2))
    # floor
    d.rectangle([0, floor_y, W, H], fill=th["floor"])
    for y in range(floor_y + 18, H, 26):
        d.line([0, y, W, y], fill=th["line"], width=2)
    # table
    d.rectangle([table_x0, table_top, table_x1, table_top + 26], fill=(120, 82, 48),
                outline=(80, 54, 32), width=3)
    d.rectangle([table_x0 + 14, table_top + 26, table_x0 + 34, floor_y + 40], fill=(104, 70, 40))
    d.rectangle([table_x1 - 34, table_top + 26, table_x1 - 14, floor_y + 40], fill=(104, 70, 40))


# ---------------------------------------------------------------------------
# Avatar preview + welcome splash
# ---------------------------------------------------------------------------
def draw_avatar_preview(idx, size=130):
    img = Image.new("RGB", (size, size), (54, 60, 78))
    d = ImageDraw.Draw(img)
    tmp = Image.new("RGB", (size // 2, size // 2), (54, 60, 78))
    dt = ImageDraw.Draw(tmp)
    draw_character(dt, size // 4, size // 2 - 4, facing=0, frame=0, **AVATARS[idx])
    img.paste(tmp.resize((size, size), Image.NEAREST), (0, 0))
    return img


def partner_avatar_pal(idx):
    """Safe lookup into PARTNER_AVATARS; falls back to the plain PARTNER_PAL."""
    if idx is None or not (0 <= idx < len(PARTNER_AVATARS)):
        return PARTNER_PAL
    return PARTNER_AVATARS[idx]


def draw_partner_avatar_preview(idx, size=110):
    """Same crisp-upscale technique as draw_avatar_preview, but on a fully TRANSPARENT
    background (RGBA) so it can 'pop up' over a card without a background box, used for
    the matching-reveal screen."""
    img = Image.new("RGBA", (size, size), (0, 0, 0, 0))
    tmp = Image.new("RGBA", (size // 2, size // 2), (0, 0, 0, 0))
    dt = ImageDraw.Draw(tmp)
    draw_character(dt, size // 4, size // 2 - 4, facing=0, frame=0, **partner_avatar_pal(idx))
    img.paste(tmp.resize((size, size), Image.NEAREST), (0, 0), tmp.resize((size, size), Image.NEAREST))
    return img


#: The frame a partner's face is shown in wherever the two tasks' people
#: appear together. task_pe-cu-nicewebrl draws a head-and-shoulders portrait
#: that fills its own 144x176 render; this task draws a whole standing
#: explorer occupying about a third of the width of a square one. Shown at
#: their natural proportions side by side, the explorer comes out a third the
#: farmer's size and reads as a child next to an adult. Both go in this frame
#: instead, so whichever app asks gets two pictures that sit together.
FACE_W, FACE_H, FACE_MARGIN = 144, 176, 0.06


def draw_partner_avatar_framed(idx):
    """draw_partner_avatar_preview(idx), cropped to what is actually drawn and
    centred in a FACE_W x FACE_H transparent frame, as large as it fits.
    NEAREST on the way up: the art is pixel art and smoothing turns it to mush."""
    img = draw_partner_avatar_preview(idx, size=144)
    box = img.getbbox()
    if box:
        img = img.crop(box)
    fit_w = int(FACE_W * (1 - 2 * FACE_MARGIN))
    fit_h = int(FACE_H * (1 - 2 * FACE_MARGIN))
    scale = min(fit_w / img.width, fit_h / img.height)
    img = img.resize((max(1, round(img.width * scale)),
                      max(1, round(img.height * scale))), Image.NEAREST)
    out = Image.new("RGBA", (FACE_W, FACE_H), (0, 0, 0, 0))
    out.paste(img, ((FACE_W - img.width) // 2, (FACE_H - img.height) // 2))
    return out


def draw_welcome_splash(W, H):
    img = Image.new("RGB", (W, H), (120, 180, 224))
    d = ImageDraw.Draw(img)
    # sky gradient
    for i in range(H):
        f = i / H
        d.line([0, i, W, i], fill=(int(120 + 60 * f), int(180 + 30 * f), int(224 - 20 * f)))
    # fluffy clouds (overlapping circles)
    for cx, cy in ((110, 84), (545, 120), (325, 58)):
        for dx, dy, r in ((0, 6, 15), (20, 0, 20), (42, 6, 15), (22, 13, 17)):
            d.ellipse([cx + dx - r, cy + dy - r, cx + dx + r, cy + dy + r], fill=(248, 250, 253))
    # ground
    gy = H - 150
    d.rectangle([0, gy, W, H], fill=(86, 154, 74))
    d.rectangle([0, gy, W, gy + 10], fill=(104, 176, 88))
    for x in range(0, W, 40):
        d.rectangle([x, gy + 30, x + 38, H], outline=(76, 138, 66), width=1)
    # a couple of little houses + trees on the horizon
    draw_house(d, 70, gy - 40, 48, 1)
    draw_house(d, W - 150, gy - 40, 48, 4)
    draw_tree(d, 200, gy - 40, 48)
    draw_tree(d, W - 240, gy - 40, 48)
    # two explorers walking
    draw_character(d, W // 2 - 22, gy + 64, facing=0, frame=0, **AVATARS[0])
    draw_character(d, W // 2 + 22, gy + 64, facing=0, frame=1, **PARTNER_PAL)
    # a big treasure chest
    draw_chest(d, W // 2 - 34, gy - 8, 68, 48, (230, 170, 40))
    # title
    text(d, W // 2, 160, "TreasureHuntForTwo", size=42, bold=True, fill=(255, 238, 160),
         center=True, outline=True)
    return img


def draw_end_splash(W, H, partner_pal=None, player_pal=None):
    """A celebratory outro scene (sunset). player_pal/partner_pal let the ending reflect the
    participant's chosen avatar and their randomised partner avatar."""
    img = Image.new("RGB", (W, H), (250, 180, 120))
    d = ImageDraw.Draw(img)
    for i in range(H):
        f = i / H
        d.line([0, i, W, i], fill=(int(250 - 20 * f), int(150 + 40 * f), int(110 + 80 * f)))
    # sun low on the horizon
    gy = H - 150
    d.ellipse([W // 2 - 50, gy - 70, W // 2 + 50, gy + 30], fill=(255, 226, 150))
    # ground
    d.rectangle([0, gy, W, H], fill=(86, 140, 74))
    d.rectangle([0, gy, W, gy + 10], fill=(104, 164, 88))
    draw_tree(d, 120, gy - 40, 48)
    draw_tree(d, W - 168, gy - 40, 48)
    # two explorers + a big open treasure chest of coins between them
    draw_character(d, W // 2 - 70, gy + 60, facing=3, frame=0, **(player_pal or AVATARS[0]))
    draw_character(d, W // 2 + 70, gy + 60, facing=2, frame=0, **(partner_pal or PARTNER_PAL))
    draw_chest(d, W // 2 - 36, gy - 16, 72, 52, (230, 170, 40), is_open=True)
    for k, (cx, cy) in enumerate([(W // 2 - 18, gy - 30), (W // 2, gy - 40), (W // 2 + 18, gy - 30)]):
        d.ellipse([cx - 9, cy - 9, cx + 9, cy + 9], fill=(241, 196, 15), outline=(191, 150, 10), width=2)
    text(d, W // 2, 60, "Adventure Complete!", size=42, bold=True, fill=(255, 244, 180),
         center=True, outline=True)
    return img


# ---------------------------------------------------------------------------
# Instruction-slide illustrations. All on a plain light card background so they drop
# straight into the intro screens' white/light-blue cards without a jarring box behind them.
# ---------------------------------------------------------------------------
_ICON_BG = (245, 247, 250)
_OUTLINE = (40, 30, 20)
_GOLD = (241, 196, 15)
_GOLD_DK = (191, 150, 10)


def _icon_canvas(w, h, bg=_ICON_BG):
    img = Image.new("RGB", (w, h), bg)
    return img, ImageDraw.Draw(img)


def _plain_coin(d, cx, cy, r=15):
    """A decorative gold coin with no number on it (for generic 'coins' illustrations,
    as opposed to draw_coin which always labels a specific +/-100/0 outcome)."""
    d.ellipse([cx - r, cy - r, cx + r, cy + r], fill=_GOLD, outline=_GOLD_DK, width=2)
    d.ellipse([cx - r + 4, cy - r + 4, cx + r - 4, cy + r - 4], outline=_lighter(_GOLD, 1.15), width=1)


def draw_arrowkeys(d, x, y, key=30, gap=4, highlight=()):
    """A 4-key 'inverted-T' arrow-key cluster, top-left anchored at (x, y). `highlight` is
    an iterable of any of 'up'/'down'/'left'/'right' to draw gold instead of plain grey."""
    positions = {
        "up": (x + key + gap, y),
        "left": (x, y + key + gap),
        "down": (x + key + gap, y + key + gap),
        "right": (x + 2 * (key + gap), y + key + gap),
    }
    tris = {
        "up": lambda cx, cy: [(cx, cy - 8), (cx - 7, cy + 6), (cx + 7, cy + 6)],
        "down": lambda cx, cy: [(cx, cy + 8), (cx - 7, cy - 6), (cx + 7, cy - 6)],
        "left": lambda cx, cy: [(cx - 8, cy), (cx + 6, cy - 7), (cx + 6, cy + 7)],
        "right": lambda cx, cy: [(cx + 8, cy), (cx - 6, cy - 7), (cx - 6, cy + 7)],
    }
    for dirn, (kx, ky) in positions.items():
        on = dirn in highlight
        fill = _GOLD if on else (222, 224, 230)
        outline = _GOLD_DK if on else (120, 122, 132)
        d.rounded_rectangle([kx, ky, kx + key, ky + key], radius=6, fill=fill, outline=outline, width=2)
        cx, cy = kx + key // 2, ky + key // 2
        d.polygon(tris[dirn](cx, cy), fill=(60, 60, 68) if on else (150, 152, 160))


def draw_space_key(d, x, y, w=64, h=26, on=True):
    """A wide 'SPACE' keycap, top-left anchored at (x, y)."""
    fill = _GOLD if on else (222, 224, 230)
    outline = _GOLD_DK if on else (120, 122, 132)
    d.rounded_rectangle([x, y, x + w, y + h], radius=6, fill=fill, outline=outline, width=2)
    text(d, x + w // 2, y + h // 2 - 8, "SPACE", size=13, bold=True,
         fill=(60, 60, 68) if on else (140, 142, 150), center=True)


def _right_arrow(d, x0, x1, y, width=6, color=None):
    color = color or _GOLD_DK
    d.line([x0, y, x1 - 12, y], fill=color, width=width)
    d.polygon([(x1, y), (x1 - 16, y - 9), (x1 - 16, y + 9)], fill=color)


def draw_chest_coins_icon(w=260, h=220):
    """Part 1 of the cover story: inside a house is a treasure chest with coins."""
    img, d = _icon_canvas(w, h)
    cx = w // 2
    draw_house(d, cx - 90, h - 176, 180, 1)  # a big cottage as the backdrop
    draw_chest(d, cx - 60, h - 100, 120, 78, (196, 140, 64), is_open=True)
    for cx2, cy2, r in [(cx - 28, h - 116, 13), (cx, h - 128, 15), (cx + 28, h - 114, 13)]:
        _plain_coin(d, cx2, cy2, r)
    return img


def draw_money_icon(w=280, h=190):
    """Part 4: coins add up into real (pocket) money."""
    img, d = _icon_canvas(w, h)
    # a small pile of coins on the left
    px = 62
    for cx2, cy2, r in [(px - 16, h - 62, 15), (px + 14, h - 60, 15), (px - 2, h - 84, 16),
                        (px - 20, h - 88, 13), (px + 18, h - 88, 13)]:
        _plain_coin(d, cx2, cy2, r)
    _right_arrow(d, 118, w - 118, h - 90, width=7)
    # a simple bill + a couple of coins on the right (pocket money)
    bx, by, bw, bh = w - 118, h - 108, 96, 52
    d.rounded_rectangle([bx, by, bx + bw, by + bh], radius=8, fill=(120, 180, 110),
                        outline=(70, 120, 66), width=3)
    d.ellipse([bx + bw // 2 - 16, by + bh // 2 - 16, bx + bw // 2 + 16, by + bh // 2 + 16],
              outline=(230, 244, 220), width=2)
    text(d, bx + bw // 2, by + bh // 2 - 9, "$", size=20, bold=True, fill=(230, 244, 220), center=True)
    _plain_coin(d, bx + bw + 8, by + bh - 4, 13)
    return img


def draw_step_into_house_icon(w=280, h=190, player_pal=None):
    """HOW_TO_PLAY bullet 1: walk with arrow keys, step onto a house."""
    img, d = _icon_canvas(w, h)
    draw_arrowkeys(d, 14, h // 2 - 34, key=30, gap=4, highlight=("up", "down", "left", "right"))
    _right_arrow(d, 128, w - 108, h // 2, width=7)
    draw_house(d, w - 96, h // 2 - 6, 64, 1)
    draw_character(d, w - 118, h // 2 + 40, facing=3, frame=0, **(player_pal or PLAYER_PAL))
    return img


def draw_choose_chest_icon(w=280, h=190):
    """HOW_TO_PLAY bullet 2: two chests, left/right arrow keys to open one."""
    img, d = _icon_canvas(w, h)
    cw, ch = 90, 64
    table_y = h - 74
    d.rectangle([16, table_y + ch, w - 16, table_y + ch + 14], fill=(150, 110, 70))
    draw_stim_chest(d, w // 2 - cw - 10, table_y, cw, ch, 24)
    draw_stim_chest(d, w // 2 + 10, table_y, cw, ch, 25)
    draw_arrowkeys(d, w // 2 - 64, 14, key=26, gap=4, highlight=("left", "right"))
    return img


def _pill_chip(d, cx, cy, label, w=76, h=20, fill=(60, 150, 76)):
    d.rounded_rectangle([cx - w // 2, cy - h // 2, cx + w // 2, cy + h // 2], radius=h // 2, fill=fill)
    text(d, cx, cy - 7, label, size=11, bold=True, fill=(255, 255, 255), center=True)


def draw_feedback_close_icon(w=340, h=230):
    """HOW_TO_PLAY bullet 3: chest opens and shows the result, then SPACE closes it."""
    img, d = _icon_canvas(w, h)
    cw, ch = 88, 64
    ly = h - 74
    lx = 22
    chest_cx = lx + cw // 2
    draw_stim_chest(d, lx, ly, cw, ch, 24, is_open=True)
    _plain_coin(d, chest_cx, ly + ch // 2, 14)
    _pill_chip(d, chest_cx, ly - 46, "+10 YOU", w=84)
    _pill_chip(d, chest_cx, ly - 22, "+10 PARTNER", w=104)
    mid = w // 2 + 10
    _right_arrow(d, mid - 34, mid + 34, h // 2, width=6)
    draw_space_key(d, mid - 30, h // 2 - 46, w=60, h=24, on=True)
    draw_stim_chest(d, w - 22 - cw, ly, cw, ch, 24, is_open=False)
    return img


def draw_identity_icon(w=280, h=170):
    """HOW_TO_PLAY: within ONE house, a chest keeps its identity across tries (but a new
    house always means brand-new chests -- never the same chest twice, see draw_swap_icon-
    style callers for that companion point)."""
    img, d = _icon_canvas(w, h)
    cw, ch = 84, 60
    for (bx, label) in [(14, "Try 1"), (w - 14 - cw, "Try 5")]:
        d.rounded_rectangle([bx - 8, 20, bx + cw + 8, 20 + ch + 34], radius=8,
                            outline=(190, 195, 205), width=2)
        text(d, bx + cw // 2, 26, label, size=12, fill=(110, 114, 124), center=True)
        draw_stim_chest(d, bx, 46, cw, ch, 24)
    text(d, w // 2, h // 2 + 16, "=", size=30, bold=True, fill=(50, 120, 60), center=True)
    text(d, w // 2, h - 18, "same house, same chest", size=11, fill=(140, 144, 154), center=True)
    return img


def _rotated_arrowhead(tip, dx, dy, deg, length=16, width=9):
    """A symmetric arrowhead triangle at `tip`, pointing along (dx,dy) rotated by `deg`
    (positive = visually clockwise, since y grows downward in image coordinates)."""
    rad = math.radians(deg)
    c, s = math.cos(rad), math.sin(rad)
    dx2, dy2 = dx * c - dy * s, dx * s + dy * c
    norm = math.hypot(dx2, dy2) or 1
    ux, uy = dx2 / norm, dy2 / norm
    px, py = -uy, ux
    back = (tip[0] - ux * length, tip[1] - uy * length)
    return [tip, (back[0] + px * width, back[1] + py * width),
            (back[0] - px * width, back[1] - py * width)]


def draw_swap_icon(w=260, h=170):
    """HOW_TO_PLAY: the two chests swap places between tries."""
    img, d = _icon_canvas(w, h)
    cw, ch = 84, 60
    ly = h - 74
    lx, rx = 24, w - 24 - cw
    draw_stim_chest(d, lx, ly, cw, ch, 24)
    draw_stim_chest(d, rx, ly, cw, ch, 25)
    lcx, rcx = lx + cw // 2, rx + cw // 2
    y0, y1 = 24, ly - 10
    d.line([lcx, y0, rcx, y1], fill=_GOLD_DK, width=4)
    d.polygon(_rotated_arrowhead((rcx, y1), rcx - lcx, y1 - y0, deg=-8), fill=_GOLD_DK)
    d.line([rcx, y0, lcx, y1], fill=_GOLD_DK, width=4)
    d.polygon(_rotated_arrowhead((lcx, y1), lcx - rcx, y1 - y0, deg=8), fill=_GOLD_DK)
    return img


def draw_consistency_icon(w=280, h=150):
    """HOW_TO_PLAY: a chest's tendency stays the same all game."""
    img, d = _icon_canvas(w, h)
    chest_x, chest_w = 20, 84
    draw_stim_chest(d, chest_x, h - 100, chest_w, 60, 24)
    outcomes = [1, 1, -1, 1, 1, 1, -1, 1]
    n = len(outcomes)
    x0, y0 = chest_x + chest_w + 26, h // 2 - 6
    step = max(10, (w - x0 - 10) // (n - 1))
    for i, v in enumerate(outcomes):
        cx = x0 + i * step
        col = (60, 170, 80) if v > 0 else (214, 90, 80)
        d.ellipse([cx - 6, y0 - 6, cx + 6, y0 + 6], fill=col)
    text(d, x0 + (n - 1) * step // 2, y0 + 22, "over many tries…", size=11,
         fill=(110, 114, 124), center=True)
    return img


def draw_variability_icon(w=280, h=170):
    """HOW_TO_PLAY: no chest gives the same result every single time."""
    img, d = _icon_canvas(w, h)
    d.ellipse([w // 2 - 16, 14, w // 2 + 16, 46], fill=(255, 255, 255), outline=(214, 150, 40), width=2)
    text(d, w // 2, 18, "?", size=24, bold=True, fill=(214, 150, 40), center=True)
    draw_stim_chest(d, w // 2 - 42, h - 108, 84, 60, 24)
    for (cx, label, col) in [(38, "+10", (60, 170, 80)), (w - 38, "-10", (214, 90, 80))]:
        d.ellipse([cx - 17, h - 60, cx + 17, h - 26], fill=col)
        text(d, cx, h - 52, label, size=12, bold=True, fill=(255, 255, 255), center=True)
    return img


def draw_two_explorers_icon(player_pal, partner_pal, w=220, h=150):
    """Quiz item: you + your partner are two separate people."""
    img, d = _icon_canvas(w, h)
    gy = h - 30
    draw_character(d, w // 2 - 34, gy, facing=3, frame=0, **player_pal)
    draw_character(d, w // 2 + 34, gy, facing=2, frame=0, **partner_pal)
    text(d, w // 2 - 34, h - 20, "YOU", size=12, bold=True, fill=(90, 94, 104), center=True)
    text(d, w // 2 + 34, h - 20, "PARTNER", size=12, bold=True, fill=(90, 94, 104), center=True)
    return img


def draw_houses_row_icon(w=340, h=110):
    """The 'You're all set!' screen: a row of the houses waiting to be explored."""
    img, d = _icon_canvas(w, h)
    t = 56
    n = 5
    gap = (w - n * t) // (n + 1)
    for i in range(n):
        bx = gap + i * (t + gap)
        draw_house(d, bx, h - t - 6, t, i % 6)
    return img