File size: 39,018 Bytes
232313d
 
d25cd8a
232313d
 
 
 
 
 
 
 
 
 
 
 
 
 
d25cd8a
 
232313d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d25cd8a
232313d
 
 
 
 
 
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
"""JevSpatial: an evaluation-only benchmark of games and spatial relations where CODE computes the consequences and the
model decides (the game code works out what each move would do, words it, and the model answers one question per
move). Every gold label is computed by the generators below. Gold is exact.

Skills (every item carries "split"):
- game_q: the consequence is written INSIDE each yes/no question ("Moving up: the snake moves closer to the food.
  Should the snake move up?") over a minimal status state. One noul per move; gold true for the best move(s).
  Items carry "pick": the scorer also reports whether argmax P(yes) over the moves is a best move.
- game_s: the same situations with the consequences in the STATE ({"if the snake moves up": ...}), plain questions
  ("Is moving up a good move?" per move, plus a choice over the moves when one move is strictly best).
- game_rule: the situation is in the state, the rule in the question ("A cactus within 60 px must be jumped over.
  Should the dinosaur jump now?"): a noul per option and a choice.
- spatial_coord: relations from coordinates in the state (left / right / above / below, which is nearer under a stated
  metric, inside a rectangle, which move reduces the distance, within a distance).
- spatial_grid: ASCII grids 5x5 to 9x9 with a legend (relative position, free cell, counts in a row / column,
  adjacency).

Games: Snake and Dino ("seen_game") and Breakout, Whac-A-Mole, Knife Hit, 2048, Tetris, Pac-Man ("unseen_game": games
whose mechanics differ from the common ones, a generalisation split).
"""

import gzip
import hashlib
import json
import random
from collections import deque

import bench_common as X
from bench_common import choice, noul, noul_target, onehot, score as score_q

VERSION = "v1"
BENCH = "JevSpatial"
LICENSE = "CC0-1.0 (generated by code)"
SKILLS = ("game_q", "game_s", "game_rule", "spatial_coord", "spatial_grid")
SEEN = ("Snake", "Dino")
UNSEEN = ("Breakout", "Whac-A-Mole", "Knife Hit", "2048", "Tetris", "Pac-Man")
SIZES = {"game_q": 440, "game_s": 440, "game_rule": 320, "spatial_coord": 420, "spatial_grid": 420}
# situations per game, shared by game_q and game_s
GAME_N = {"Snake": 130, "Dino": 70, "Breakout": 40, "Whac-A-Mole": 40, "Knife Hit": 40, "2048": 40, "Tetris": 40,
          "Pac-Man": 40}
RULE_N = {"Dino": 110, "Breakout": 70, "Whac-A-Mole": 70, "Pac-Man": 70}

DIRS = {"up": (-1, 0), "down": (1, 0), "left": (0, -1), "right": (0, 1)}


def split_of(game: str) -> str:
    return "seen_game" if game in SEEN else "unseen_game"


def _item(id, skill, game, state, questions, targets, pick=False, source=None):
    st = state if isinstance(state, str) else json.dumps(state, ensure_ascii=False)
    key = st + " " + " ".join(q["instructions"] for q in questions.values())
    it = X._item(id, skill, source or f"spatial:{skill}:{game}", st, questions, targets, LICENSE, key)
    it.update(bench=BENCH, split=split_of(game) if game in SEEN + UNSEEN else "generic", pick=pick)
    return it


# ===================================================================== game situations
# A situation: {"game", "unit", "status", "moves": [{"id", "gerund", "ask", "ask_s", "subj", "effect", "rank",
# "good"}]}; good moves share the top rank, so a move's label does not depend on the other moves of the situation.
def _mv(id, gerund, ask, ask_s, subj, effect, rank, good):
    return {"id": id, "gerund": gerund, "ask": ask, "ask_s": ask_s, "subj": subj, "effect": effect, "rank": rank,
            "good": good}


def _finish(game, unit, status, moves):
    good = [m for m in moves if m["good"]]
    if not good or len(good) == len(moves) or len({m["rank"] for m in good}) != 1:
        return None
    if min(m["rank"] for m in good) <= max([m["rank"] for m in moves if not m["good"]] or [-1]):
        return None
    return {"game": game, "unit": unit, "status": status, "moves": moves}


def _bfs(blocked, start, goal, n):
    seen = {start: 0}
    q = deque([start])
    while q:
        r, c = q.popleft()
        if (r, c) == goal:
            return seen[(r, c)]
        for dr, dc in DIRS.values():
            nb = (r + dr, c + dc)
            if 0 <= nb[0] < n and 0 <= nb[1] < n and nb not in blocked and nb not in seen:
                seen[nb] = seen[(r, c)] + 1
                q.append(nb)
    return None


def snake_moves(walk, food, n):
    """The four moves of a snake (cells tail first, head last) on an n x n board with the consequence of each."""
    head = walk[-1]
    d0 = _bfs(set(walk[1:]), head, food, n)
    moves = []
    for name, (dr, dc) in DIRS.items():
        new = (head[0] + dr, head[1] + dc)
        if not (0 <= new[0] < n and 0 <= new[1] < n):
            eff, rank = "would crash into a wall and die", 0
        elif new in walk[1:]:
            eff, rank = "would run into its own body and die", 0
        elif new == food:
            eff, rank = "would eat the food", 4
        else:
            d1 = _bfs(set(walk[1:]), new, food, n)  # the tail cell is vacated, the old head is body now
            if d1 is None:
                eff, rank = "would be cut off, with no free path left to the food", 1
            elif d0 is not None and d1 < d0:
                eff, rank = "moves closer to the food", 3
            else:
                eff, rank = "moves farther from the food", 2
        moves.append(_mv(name, f"Moving {name}", f"Should the snake move {name}?", f"Is moving {name} a good move?",
                         f"if the snake moves {name}", eff, rank, rank >= 3))
    return moves


def snake_sit(rng):
    n = rng.randint(8, 12)
    for _ in range(50):
        cell = (rng.randrange(n), rng.randrange(n))
        walk = [cell]
        target = rng.randint(3, 16)
        while len(walk) < target:
            opts = [(walk[-1][0] + dr, walk[-1][1] + dc) for dr, dc in DIRS.values()]
            opts = [o for o in opts if 0 <= o[0] < n and 0 <= o[1] < n and o not in walk]
            if not opts:
                break
            walk.append(rng.choice(opts))
        if len(walk) >= 3:
            break
    else:
        return None
    free = [(r, c) for r in range(n) for c in range(n) if (r, c) not in walk]
    food = rng.choice(free)
    moves = snake_moves(walk, food, n)
    eaten = len(walk) - 3
    status = {"game": "Snake", "board": f"{n}x{n}", "length": len(walk), "apples eaten": max(0, eaten),
              "turn": rng.randint(len(walk), 400)}
    return _finish("Snake", "the snake", status, moves)


DINO_OBS = {"small cactus": "cactus", "tall cactus": "cactus", "cactus cluster": "cactus", "high bird": "high",
            "low bird": "low"}


def dino_sit(rng):
    obs = rng.choice(list(DINO_OBS) + ["clear"] * 1)
    phase = "clear" if obs == "clear" else rng.choice(["far", "now", "now"])
    status = {"game": "Dino", "score": rng.randint(20, 3000), "speed": rng.choice(["slow", "medium", "fast"])}
    return _finish("Dino", "the dinosaur", status, dino_moves(obs, phase))


def dino_moves(obs, phase):
    """jump / duck / run for the next obstacle `obs` (or "clear") in phase clear | far | now (act now)."""
    need = "run" if phase in ("clear", "far") else ("duck" if DINO_OBS.get(obs) == "high" else "jump")
    eff = {}
    if phase == "clear":
        eff = {"run": "keeps running along a clear track", "jump": "jumps although nothing is in the way and loses speed",
               "duck": "ducks although nothing is in the way and loses speed"}
    elif phase == "far":
        eff = {"run": f"keeps running; the {obs} is still far away", "jump": f"jumps too early and lands before the {obs}",
               "duck": f"ducks too early and stands up again before the {obs} arrives"}
    else:
        kind = DINO_OBS[obs]
        eff = {"run": f"runs straight into the {obs}"}
        if kind == "high":
            eff["duck"] = f"passes safely under the {obs}"
            eff["jump"] = f"jumps right into the {obs}"
        else:
            eff["jump"] = f"jumps over the {obs} and clears it"
            eff["duck"] = f"ducks and is hit by the {obs}" if kind == "low" else f"ducks and runs into the {obs}"
    verbs = {"jump": ("Jumping", "jump", "jumping"), "duck": ("Ducking", "duck", "ducking"),
             "run": ("Continuing to run", "keep running", "continuing to run")}
    moves = []
    for m in ("jump", "duck", "run"):
        g, v, ing = verbs[m]
        sentence = "Should the dinosaur " + ("keep running" if m == "run" else f"{v} now") + "?"
        moves.append(_mv(m, g, sentence, f"Is {ing} a good move?", f"if the dinosaur {'keeps running' if m == 'run' else m + 's'}",
                         eff[m], 2 if m == need else 0, m == need))
    return moves


def breakout_sit(rng):
    W = 200
    w = rng.choice([30, 40, 50, 60])
    step = rng.choice([10, 15, 20, 25])
    p = rng.randrange(w // 2, W - w // 2 + 1, 5)
    x_l = rng.randrange(10, W - 9, 5)
    moves = breakout_moves(p, x_l, w, step, W)
    status = {"game": "Breakout", "lives": rng.randint(1, 5), "bricks left": rng.randint(5, 60)}
    return _finish("Breakout", "the paddle", status, moves)


def breakout_moves(p, x_l, w, step, W=200):
    """left / stay / right for a paddle centred at p (width w, `step` px per move) and a ball landing at x_l."""
    moves = []
    for name, d in (("left", -1), ("stay", 0), ("right", 1)):
        p2 = min(W - w // 2, max(w // 2, p + d * step))
        if abs(p2 - x_l) <= w // 2:
            eff, rank = "ends under the ball, which it returns", 2
        elif abs(p2 - x_l) < abs(p - x_l):
            eff, rank = "gets closer to the ball's landing spot but still misses the ball", 1
        elif name == "stay":
            eff, rank = "stays where it is and the ball falls past it", 0
        else:
            eff, rank = "moves away from the ball's landing spot and the ball is lost", 0
        g = {"left": "Moving the paddle left", "stay": "Keeping the paddle still", "right": "Moving the paddle right"}[name]
        ask = {"left": "Should the paddle move left?", "stay": "Should the paddle stay where it is?",
               "right": "Should the paddle move right?"}[name]
        asks = {"left": "Is moving the paddle left a good move?", "stay": "Is keeping the paddle still a good move?",
                "right": "Is moving the paddle right a good move?"}[name]
        sj = {"left": "if the paddle moves left", "stay": "if the paddle stays still", "right": "if the paddle moves right"}[name]
        moves.append(_mv(name, g, ask, asks, sj, eff, rank, rank == 2))
    return moves


HOLES = ["top-left", "top-middle", "top-right", "middle-left", "center", "middle-right", "bottom-left", "bottom-middle",
         "bottom-right"]


def mole_sit(rng):
    k = rng.choice([4, 4, 5])
    holes = rng.sample(HOLES, k)
    n_good = rng.choice([1, 1, 2])
    kinds = ["mole"] * n_good + [rng.choice(["bomb", "empty", "bomb"]) for _ in range(k - n_good)]
    rng.shuffle(kinds)
    status = {"game": "Whac-A-Mole", "score": rng.randint(0, 80), "lives": rng.randint(1, 3)}
    return _finish("Whac-A-Mole", "the hammer", status, mole_moves(holes, kinds))


def mole_moves(holes, kinds):
    """One move per hole; kinds[i] is mole | bomb | empty."""
    eff = {"mole": ("hits a mole and scores a point", 3), "bomb": ("hits a bomb and loses a life", 0),
           "empty": ("swings at an empty hole and wastes the turn", 1)}
    moves = []
    for h, kd in zip(holes, kinds, strict=True):
        e, r = eff[kd]
        moves.append(_mv(h.replace("-", "_"), f"Hitting the {h} hole", f"Should the player hit the {h} hole?",
                         f"Is hitting the {h} hole a good move?", f"if the player hits the {h} hole", e, r, kd == "mole"))
    return moves


def knife_sit(rng):
    slots = 12
    stuck = set(rng.sample(range(slots), rng.randint(3, 8)))  # slots of the log holding a knife, bottom slot = 0
    waits = ["now", "after one beat", "after two beats", "after three beats"]
    moves = []
    for k, label in enumerate(waits):  # the log turns one slot per beat: slot k is at the bottom after k beats
        hit = k in stuck
        e, r = ("hits a knife already stuck in the log and bounces off", 0) if hit else ("sticks in a free spot of the log", 2)
        moves.append(_mv(f"t{k}", f"Throwing {label}", f"Should the player throw the knife {label}?",
                         f"Is throwing {label} a good move?", f"if the player throws {label}", e, r, not hit))
    status = {"game": "Knife Hit", "stage": rng.randint(1, 30), "knives left": rng.randint(2, 9)}
    return _finish("Knife Hit", "the knife", status, moves)


def _slide_line(line):
    vals = [v for v in line if v]
    out, gain, i = [], 0, 0
    while i < len(vals):
        if i + 1 < len(vals) and vals[i] == vals[i + 1]:
            out.append(vals[i] * 2)
            gain += vals[i] * 2
            i += 2
        else:
            out.append(vals[i])
            i += 1
    return out + [0] * (len(line) - len(out)), gain


def _move2048(b, d):
    nb, gain = [], 0
    if d in ("left", "right"):
        for row in b:
            r = row[::-1] if d == "right" else row
            s, g = _slide_line(r)
            nb.append(s[::-1] if d == "right" else s)
            gain += g
        return nb, gain
    cols = []
    for c in range(4):
        col = [b[r][c] for r in range(4)]
        col = col[::-1] if d == "down" else col
        s, g = _slide_line(col)
        cols.append(s[::-1] if d == "down" else s)
        gain += g
    return [[cols[c][r] for c in range(4)] for r in range(4)], gain


def g2048_sit(rng):
    b = [[0] * 4 for _ in range(4)]
    for _ in range(rng.randint(6, 12)):
        b[rng.randrange(4)][rng.randrange(4)] = rng.choice([2, 2, 4, 4, 8, 16, 32, 64])
    res = {d: _move2048(b, d) for d in DIRS}
    best = max(g for _, g in res.values())
    if best == 0:
        return None
    moves = []
    for d, (nb, g) in res.items():
        if g == best:
            e, r = f"merges tiles for the most points available (+{g})", 3
        elif g > 0:
            e, r = f"merges tiles but for fewer points than the best move (+{g})", 2
        elif nb != b:
            e, r = "slides the tiles without merging any", 1
        else:
            e, r = "changes nothing because no tile can move that way", 0
        moves.append(_mv(d, f"Swiping {d}", f"Should the player swipe {d}?", f"Is swiping {d} a good move?",
                         f"if the player swipes {d}", e, r, g == best))
    status = {"game": "2048", "score": rng.randint(100, 20000), "biggest tile": max(max(r) for r in b)}
    return _finish("2048", "the move", status, moves)


def tetris_sit(rng):
    Wd, H = 6, 12
    for _ in range(400):
        heights = [rng.randint(2, 5) for _ in range(Wd)]
        occ = set()
        for c in range(Wd):
            for y in range(heights[c]):
                if y == heights[c] - 1 or rng.random() < 0.9:
                    occ.add((y, c))
        piece = rng.choice(["O", "I"])
        plc = []
        if piece == "O":
            plc = [("O", c, [(0, 0), (0, 1), (1, 0), (1, 1)], f"the 2x2 square in columns {c + 1}-{c + 2}") for c in range(Wd - 1)]
        else:
            plc = [("Ih", c, [(0, i) for i in range(4)], f"the I bar lying flat in columns {c + 1}-{c + 4}") for c in range(Wd - 3)]
            plc += [("Iv", c, [(i, 0) for i in range(4)], f"the I bar standing up in column {c + 1}") for c in range(Wd)]
        res = []
        for tag, c, cells, label in plc:
            y = H
            while y > 0 and all((y - 1 + dy, c + dx) not in occ and 0 <= c + dx < Wd for dy, dx in cells):
                y -= 1
            placed = {(y + dy, c + dx) for dy, dx in cells}
            holes = 0
            for col in {cc for _, cc in placed}:
                low = min(r for r, cc in placed if cc == col)
                top_below = max([r for r, cc in occ if cc == col and r < low] or [-1])
                holes += low - top_below - 1
            full = occ | placed
            lines = sum(all((r, c2) in full for c2 in range(Wd)) for r in range(H))
            res.append((tag + str(c), label, lines, holes))
        clear = [r for r in res if r[2] > 0]
        if not clear or len({r[2] for r in clear}) != 1:
            continue
        others = [r for r in res if r[2] == 0]
        if len(others) < 2:
            continue
        pick = rng.sample(clear, min(len(clear), rng.choice([1, 1, 2]))) + rng.sample(others, min(len(others), 3))
        rng.shuffle(pick)
        moves = []
        for mid, label, lines, holes in pick:
            if lines:
                e, r = f"clears {lines} line" + ("s" if lines > 1 else ""), 3
            elif holes:
                e, r = f"leaves {holes} hole" + ("s" if holes > 1 else "") + " under it and clears no line", 0
            else:
                e, r = "fits flat but clears no line", 1
            moves.append(_mv(mid, f"Placing {label}", f"Should the piece be placed as {label}?",
                             f"Is placing {label} a good move?", f"if the piece is placed as {label}", e, r, lines > 0))
        status = {"game": "Tetris", "piece": "O square" if piece == "O" else "I bar", "level": rng.randint(1, 15),
                  "lines": rng.randint(0, 200)}
        return _finish("Tetris", "the piece", status, moves)
    return None


def pacman_sit(rng):
    n = 7
    walls = {(r, c) for r in range(n) for c in range(n) if rng.random() < 0.22}
    free = [(r, c) for r in range(n) for c in range(n) if (r, c) not in walls]
    if len(free) < 12:
        return None
    pac = rng.choice(free)
    ghosts = rng.sample([f for f in free if abs(f[0] - pac[0]) + abs(f[1] - pac[1]) >= 2], rng.choice([1, 2]))
    dots = {f for f in free if f != pac and f not in ghosts and rng.random() < 0.55}
    moves = []
    for d, (dr, dc) in DIRS.items():
        new = (pac[0] + dr, pac[1] + dc)
        if not (0 <= new[0] < n and 0 <= new[1] < n) or new in walls:
            e, r = "bumps into a wall and does not move", 1
        elif new in ghosts:
            e, r = "runs straight into a ghost and loses a life", 0
        elif any(abs(g[0] - new[0]) + abs(g[1] - new[1]) <= 1 for g in ghosts):
            e, r = "moves next to a ghost, which catches Pac-Man next turn", 0
        elif new in dots:
            e, r = "eats a dot", 3
        else:
            e, r = "moves onto an empty cell without a dot", 2
        moves.append(_mv(d, f"Moving {d}", f"Should Pac-Man move {d}?", f"Is moving {d} a good move?",
                         f"if Pac-Man moves {d}", e, r, r == 3))
    status = {"game": "Pac-Man", "lives": rng.randint(1, 3), "dots left": len(dots) + rng.randint(0, 100)}
    return _finish("Pac-Man", "Pac-Man", status, moves)


SIT_GEN = {"Snake": snake_sit, "Dino": dino_sit, "Breakout": breakout_sit, "Whac-A-Mole": mole_sit,
           "Knife Hit": knife_sit, "2048": g2048_sit, "Tetris": tetris_sit, "Pac-Man": pacman_sit}


def make_situations(game: str, n: int, seed: int) -> list:
    """n situations of `game`, spread evenly over the position of the (first) best move; deterministic in seed."""
    rng = random.Random(f"{seed}:{game}")
    cands, seen = [], set()
    tries = 0
    while len(cands) < 8 * n and tries < 400 * n:
        tries += 1
        s = SIT_GEN[game](rng)
        if s is None:
            continue
        sig = json.dumps(s, sort_keys=True)
        if sig in seen:
            continue
        seen.add(sig)
        cands.append(s)
    first = lambda s: next(m["id"] for m in s["moves"] if m["good"])  # noqa: E731
    out = X._sample(cands, n, rng, by=first)
    rng.shuffle(out)
    return out


# ===================================================================== renderers
Q_TEMPLATES = ("{G}: {S} {E}. {ASK}",) * 5 + ("{G}. Effect: {S} {E}. {ASK}",)


def render_q(sit: dict, rng: random.Random, i: int) -> dict:
    qs, ts = {}, {}
    for m in sit["moves"]:
        tpl = rng.choice(Q_TEMPLATES)
        text = tpl.format(G=m["gerund"], S=sit["unit"], E=m["effect"], ASK=m["ask"])
        if sit["unit"] == "the move":
            text = f"{m['gerund']}: this move {m['effect']}. {m['ask']}"
        qs[m["id"]] = noul(text)
        ts[m["id"]] = noul_target(m["good"])
    return _item(f"spatial-game_q-{sit['game']}-{i:04d}", "game_q", sit["game"], sit["status"], qs, ts, pick=True)


def render_s(sit: dict, rng: random.Random, i: int) -> dict:
    state = dict(sit["status"])
    for m in sit["moves"]:
        state[m["subj"]] = (sit["unit"] + " " if sit["unit"] != "the move" else "this move ") + m["effect"]
    items = list(state.items())
    head, tail = items[:len(sit["status"])], items[len(sit["status"]):]
    rng.shuffle(tail)
    state = dict(head + tail)
    qs, ts = {}, {}
    for m in sit["moves"]:
        qs[m["id"]] = noul(m["ask_s"])
        ts[m["id"]] = noul_target(m["good"])
    good = [m for m in sit["moves"] if m["good"]]
    if len(good) == 1:
        qs["best"] = choice("Which move is the best one here?", {m["id"]: "" for m in sit["moves"]})
        ts["best"] = onehot([m["id"] for m in sit["moves"]], good[0]["id"])
    return _item(f"spatial-game_s-{sit['game']}-{i:04d}", "game_s", sit["game"], state, qs, ts, pick=True)


# ===================================================================== game_rule
def rule_dino(rng):
    T = rng.choice([30, 40, 50, 60, 70, 80, 90])
    obs = rng.choice(list(DINO_OBS) + ["none"])
    dist = rng.choice([rng.randint(3, T - 2), rng.randint(T + 2, T + 60), T - rng.randint(0, 1), T + rng.randint(1, 3)])
    rule = (f"Rule: an obstacle on the ground (a cactus) or a low bird closer than {T} px must be jumped over; a high bird "
            f"closer than {T} px must be ducked under; in every other case the dinosaur keeps running.")
    kind = DINO_OBS.get(obs)
    near = obs != "none" and dist < T
    need = ("duck" if kind == "high" else "jump") if near else "run"
    state = {"game": "Dino", "next obstacle": obs if obs != "none" else "nothing ahead",
             "distance to it (px)": dist if obs != "none" else None, "speed (px per tick)": rng.randint(4, 12),
             "dinosaur": "running"}
    if obs == "none":
        del state["distance to it (px)"]
    ask = {"jump": "Should the dinosaur jump now?", "duck": "Should the dinosaur duck now?",
           "run": "Should the dinosaur keep running?"}
    return "Dino", state, rule, {k: v for k, v in ask.items()}, need, "Which action should the dinosaur take now?"


def rule_breakout(rng):
    N = rng.choice([10, 15, 20, 30, 40])
    off = rng.choice([rng.randint(-60, 60), rng.randint(-N - 4, N + 4)])
    p = rng.randint(60, 140)
    state = {"game": "Breakout", "paddle center x": p, "ball will land at x": p + off, "paddle speed": "fast"}
    rule = (f"Rule: if the ball will land more than {N} px to the left of the paddle's center, move the paddle left; "
            f"if more than {N} px to the right, move it right; otherwise leave it where it is.")
    need = "left" if off < -N else ("right" if off > N else "stay")
    ask = {"left": "Should the paddle move left?", "right": "Should the paddle move right?",
           "stay": "Should the paddle stay where it is?"}
    return "Breakout", state, rule, ask, need, "What should the paddle do?"


def rule_mole(rng):
    golden = rng.random() < 0.5
    if golden:
        rule = ("Rule: hit a hole that shows a mole or a golden mole; never hit a bomb or an empty hole; "
                "skip any hole whose occupant is about to hide.")
        kinds = ["mole", "bomb", "empty", "golden mole", "mole about to hide"]
    else:
        rule = ("Rule: hit a hole only if it shows a mole; never hit a bomb; ignore empty holes. "
                "A mole that is about to hide cannot be reached in time, so do not swing at it.")
        kinds = ["mole", "bomb", "empty", "mole about to hide"]
    kind = rng.choice(kinds)
    state = {"game": "Whac-A-Mole", "hole under the hammer": rng.choice(HOLES), "it shows": kind,
             "score": rng.randint(0, 60)}
    need = "hit" if kind in ("mole", "golden mole") else "wait"
    ask = {"hit": "Should the player hit this hole?", "wait": "Should the player hold back and not swing?"}
    return "Whac-A-Mole", state, rule, ask, need, "Hit the hole or hold back?"


def rule_pacman(rng):
    N = rng.choice([2, 3, 4, 5])
    gd = rng.choice([rng.randint(1, N - 1) if N > 1 else 1, rng.randint(N, N + 4), N, N + 1])
    nd = rng.randint(1, 6)
    rule = (f"Rule: if a ghost is within {N} cells, retreat from it; otherwise move toward the nearest dot; if there is "
            f"no dot in sight, wander.")
    has_dot = rng.random() < 0.8
    state = {"game": "Pac-Man", "nearest ghost (cells away)": gd, "nearest dot (cells away)": nd if has_dot else "none in sight",
             "lives": rng.randint(1, 3)}
    need = "retreat" if gd <= N else ("chase" if has_dot else "wander")
    ask = {"retreat": "Should Pac-Man retreat from the ghost?", "chase": "Should Pac-Man move toward the nearest dot?",
           "wander": "Should Pac-Man wander?"}
    return "Pac-Man", state, rule, ask, need, "What should Pac-Man do?"


RULE_GEN = {"Dino": rule_dino, "Breakout": rule_breakout, "Whac-A-Mole": rule_mole, "Pac-Man": rule_pacman}


def rule_items(game: str, n: int, seed: int) -> list:
    rng = random.Random(f"{seed}:rule:{game}")
    cands, seen = [], set()
    while len(cands) < 6 * n:
        g, state, rule, ask, need, cq = RULE_GEN[game](rng)
        sig = json.dumps([state, rule])
        if sig in seen:
            continue
        seen.add(sig)
        cands.append((g, state, rule, ask, need, cq))
    picked = X._sample(cands, n, rng, by=lambda c: c[4])
    out = []
    for i, (g, state, rule, ask, need, cq) in enumerate(picked):
        qs = {k: noul(f"{rule} {v}") for k, v in ask.items()}
        ts = {k: noul_target(k == need) for k in ask}
        qs["action"] = choice(f"{rule} {cq}", {k: "" for k in ask})
        ts["action"] = onehot(list(ask), need)
        out.append(_item(f"spatial-game_rule-{g}-{i:04d}", "game_rule", g, state, qs, ts, pick=True))
    return out


# ===================================================================== spatial_coord
OBJECTS = [("robot", "charging dock"), ("drone", "landing pad"), ("rover", "sample site"), ("cursor", "button"),
           ("player", "exit"), ("truck", "warehouse"), ("ship", "harbor"), ("hiker", "cabin")]
THINGS = ["lamp", "tree", "well", "kiosk", "bench", "tower", "gate", "flag", "crate", "sensor"]


def _axes(rng):
    up = rng.random() < 0.5
    return up, ("x grows to the right and y grows upward" if up else "x grows to the right and y grows downward")


def coord_item(kind: str, rng: random.Random, want: bool | None = None, i: int = 0):
    up, axes = _axes(rng)
    a, b, c = rng.sample(THINGS, 3)
    R = lambda: (rng.randint(-9, 9), rng.randint(-9, 9))  # noqa: E731
    state = {"coordinates": axes}
    qs, ts = {}, {}
    if kind == "side":
        (ax, ay), (bx, by) = R(), R()
        rel = rng.choice(["left of", "right of", "above", "below"])
        while (rel in ("left of", "right of") and ax == bx) or (rel in ("above", "below") and ay == by):
            (ax, ay), (bx, by) = R(), R()
        truth = {"left of": ax < bx, "right of": ax > bx,
                 "above": (ay > by) if up else (ay < by), "below": (ay < by) if up else (ay > by)}[rel]
        if want is not None and truth != want:
            return None
        state.update({a: [ax, ay], b: [bx, by]})
        qs["q"] = noul(f"Is the {a} {rel} the {b}?")
        ts["q"] = noul_target(truth)
    elif kind == "nearer":
        metric = rng.choice(["Manhattan", "Euclidean"])
        p, q1, q2 = R(), R(), R()
        d = (lambda u, v: abs(u[0] - v[0]) + abs(u[1] - v[1])) if metric == "Manhattan" else \
            (lambda u, v: (u[0] - v[0]) ** 2 + (u[1] - v[1]) ** 2)
        if d(p, q1) == d(p, q2):
            return None
        state.update({a: list(p), b: list(q1), c: list(q2), "distance": metric})
        qs["q"] = choice(f"Which object is nearer to the {a}, measured by {metric} distance?", {b: "", c: ""})
        ts["q"] = onehot([b, c], b if d(p, q1) < d(p, q2) else c)
    elif kind == "inside":
        x0, y0 = rng.randint(-8, 2), rng.randint(-8, 2)
        x1, y1 = x0 + rng.randint(2, 8), y0 + rng.randint(2, 8)
        pt = R()
        truth = x0 <= pt[0] <= x1 and y0 <= pt[1] <= y1
        if want is not None and truth != want:
            return None
        state.update({"rectangle": {"x from": x0, "x to": x1, "y from": y0, "y to": y1}, a: list(pt)})
        qs["q"] = noul(f"Is the {a} inside the rectangle (borders included)?")
        ts["q"] = noul_target(truth)
    elif kind == "reduce":
        o, t = OBJECTS[rng.randrange(len(OBJECTS))]
        p, q1 = R(), R()
        dx, dy = q1[0] - p[0], q1[1] - p[1]
        mv = rng.choice(["left", "right", "up", "down"])
        step = {"left": (-1, 0), "right": (1, 0), "up": (0, 1 if up else -1), "down": (0, -1 if up else 1)}[mv]
        if dx == 0 and dy == 0:
            return None
        d0 = (dx * dx + dy * dy)
        d1 = ((dx - step[0]) ** 2 + (dy - step[1]) ** 2)
        if d0 == d1:
            return None
        truth = d1 < d0
        if want is not None and truth != want:
            return None
        state.update({o: list(p), t: list(q1)})
        qs["q"] = noul(f"Does moving the {o} one step {mv} bring it closer to the {t} (straight-line distance)?")
        ts["q"] = noul_target(truth)
    elif kind == "best_dir":
        o, t = OBJECTS[rng.randrange(len(OBJECTS))]
        p, q1 = R(), R()
        dx, dy = q1[0] - p[0], q1[1] - p[1]
        if abs(abs(dx) - abs(dy)) < 2:
            return None
        if abs(dx) > abs(dy):
            best = "right" if dx > 0 else "left"
        else:
            best = ("up" if dy > 0 else "down") if up else ("down" if dy > 0 else "up")
        state.update({o: list(p), t: list(q1)})
        qs["q"] = choice(f"The {o} takes one step toward the {t}. Which step reduces the straight-line distance the most?",
                         {"up": "", "down": "", "left": "", "right": ""})
        ts["q"] = onehot(["up", "down", "left", "right"], best)
    elif kind == "within":
        metric = rng.choice(["Manhattan", "Euclidean"])
        p, q1 = R(), R()
        dist = abs(p[0] - q1[0]) + abs(p[1] - q1[1]) if metric == "Manhattan" else \
            ((p[0] - q1[0]) ** 2 + (p[1] - q1[1]) ** 2) ** 0.5
        thr = max(1, int(dist) + rng.choice([-3, -2, -1, 1, 2, 3]))
        truth = dist <= thr
        if want is not None and truth != want:
            return None
        state.update({a: list(p), b: list(q1)})
        qs["q"] = noul(f"Is the {b} within {thr} units of the {a} ({metric} distance)?")
        ts["q"] = noul_target(truth)
    return _item(f"spatial-spatial_coord-{kind}-{i:04d}", "spatial_coord", "coord", state, qs, ts,
                 source=f"spatial:coord:{kind}")


COORD_KINDS = ("side", "nearer", "inside", "reduce", "best_dir", "within")


def coord_items(n: int, seed: int) -> list:
    rng = random.Random(f"{seed}:coord")
    out = []
    per = n // len(COORD_KINDS)
    for kind in COORD_KINDS:
        k = 0
        while k < per + (n - per * len(COORD_KINDS) if kind == COORD_KINDS[0] else 0):
            want = (k % 2 == 0) if kind not in ("nearer", "best_dir") else None
            it = coord_item(kind, rng, want, k)
            if it:
                out.append(it)
                k += 1
    return out


# ===================================================================== spatial_grid
SYMS = [("K", "key"), ("D", "door"), ("T", "tree"), ("W", "water"), ("R", "rock"), ("C", "chest"), ("G", "guard"),
        ("S", "start")]


def _grid(rng):
    n = rng.randint(5, 9)
    m = rng.randint(5, 9)
    syms = rng.sample(SYMS, rng.randint(3, 5))
    grid = [["." for _ in range(m)] for _ in range(n)]
    for s, _ in syms:
        for _ in range(rng.randint(1, 4) if s not in ("K", "D", "S", "C") else 1):
            r, c = rng.randrange(n), rng.randrange(m)
            if grid[r][c] == ".":
                grid[r][c] = s
    return n, m, syms, grid


def _gstate(n, m, syms, grid):
    rows = "\n".join(" ".join(r) for r in grid)
    legend = ", ".join(f"{s} = {name}" for s, name in syms) + ", . = empty floor"
    return (f"Grid with {n} rows and {m} columns (row 1 is the top row, column 1 is the leftmost column):\n{rows}\n"
            f"Legend: {legend}.")


def grid_item(kind: str, rng: random.Random, want: bool | None, i: int):
    n, m, syms, grid = _grid(rng)
    name = dict(syms)
    cells = {s: [(r, c) for r in range(n) for c in range(m) if grid[r][c] == s] for s, _ in syms}
    single = [s for s, _ in syms if len(cells[s]) == 1]
    qs, ts = {}, {}
    if kind == "relative":
        if len(single) < 2:
            return None
        x, y = rng.sample(single, 2)
        (rx, cx), (ry, cy) = cells[x][0], cells[y][0]
        rel = rng.choice(["above", "below", "left of", "right of"])
        if (rel in ("above", "below") and rx == ry) or (rel in ("left of", "right of") and cx == cy):
            return None
        truth = {"above": rx < ry, "below": rx > ry, "left of": cx < cy, "right of": cx > cy}[rel]
        if want is not None and truth != want:
            return None
        qs["q"] = noul(f"Is the {name[x]} ({x}) {rel} the {name[y]} ({y}) on the grid?")
        ts["q"] = noul_target(truth)
    elif kind == "free":
        r, c = rng.randrange(n), rng.randrange(m)
        truth = grid[r][c] == "."
        if want is not None and truth != want:
            return None
        qs["q"] = noul(f"Is the cell in row {r + 1}, column {c + 1} empty floor?")
        ts["q"] = noul_target(truth)
    elif kind == "count_row" or kind == "count_col":
        s = rng.choice(syms)[0]
        if kind == "count_row":
            idx = rng.randrange(n)
            cnt = sum(1 for c in range(m) if grid[idx][c] == s)
            where = f"row {idx + 1}"
        else:
            idx = rng.randrange(m)
            cnt = sum(1 for r in range(n) if grid[r][idx] == s)
            where = f"column {idx + 1}"
        if cnt > 4:
            return None
        if kind == "count_row":
            qs["q"] = score_q(f"How many {name[s]} cells ({s}) are in {where}?", ["0", "1", "2", "3", "4"])
            ts["q"] = {str(j): float(j == cnt) for j in range(5)}
        else:
            qs["q"] = choice(f"How many {name[s]} cells ({s}) are in {where}?", {str(j): "" for j in range(5)})
            ts["q"] = onehot([str(j) for j in range(5)], str(cnt))
    elif kind == "adjacent":
        pairs = [(s, t) for s in single for t in single if s < t]
        if not pairs:
            return None
        x, y = rng.choice(pairs)
        (rx, cx), (ry, cy) = cells[x][0], cells[y][0]
        truth = abs(rx - ry) + abs(cx - cy) == 1
        if want is not None and truth != want:
            return None
        qs["q"] = noul(f"Is the {name[x]} ({x}) directly next to the {name[y]} ({y}) (sharing a side, no diagonals)?")
        ts["q"] = noul_target(truth)
    return _item(f"spatial-spatial_grid-{kind}-{i:04d}", "spatial_grid", "grid", _gstate(n, m, syms, grid), qs, ts,
                 source=f"spatial:grid:{kind}")


def _adjacent_forced(rng, i):
    """Adjacent pairs are rare at random: place two single symbols next to each other on purpose half the time."""
    n, m, syms, grid = _grid(rng)
    return n, m, syms, grid


GRID_KINDS = ("relative", "free", "count_row", "count_col", "adjacent")


def grid_items(n: int, seed: int) -> list:
    rng = random.Random(f"{seed}:grid")
    out = []
    per = n // len(GRID_KINDS)
    for kind in GRID_KINDS:
        k, tries = 0, 0
        counts = {}
        while k < per and tries < 200000:
            tries += 1
            want = (k % 2 == 0) if kind in ("relative", "free", "adjacent") else None
            it = grid_item(kind, rng, want, k)
            if not it:
                continue
            if kind.startswith("count"):  # keep the counts spread: at most 40% zeros
                gold = max(it["targets"]["q"], key=it["targets"]["q"].get)
                counts[gold] = counts.get(gold, 0) + 1
                if counts[gold] > 0.34 * per + 2:
                    counts[gold] -= 1
                    continue
            out.append(it)
            k += 1
    return out


# ===================================================================== build
def build(seed: int = 0, sizes: dict | None = None) -> tuple[list, dict]:
    scale = {**SIZES, **(sizes or {})}
    f = lambda skill: scale[skill] / SIZES[skill]  # noqa: E731
    items = []
    sits_n = {g: max(2, round(n * f("game_q"))) for g, n in GAME_N.items()}
    rng = random.Random(f"{seed}:render")
    for g in SEEN + UNSEEN:
        sits = make_situations(g, sits_n[g], seed)
        items += [render_q(s, random.Random(f"{seed}:q:{g}:{i}"), i) for i, s in enumerate(sits)]
        items += [render_s(s, random.Random(f"{seed}:s:{g}:{i}"), i) for i, s in enumerate(sits)]
    for g, n in RULE_N.items():
        items += rule_items(g, max(2, round(n * f("game_rule"))), seed)
    items += coord_items(max(6, round(SIZES["spatial_coord"] * f("spatial_coord"))), seed)
    items += grid_items(max(5, round(SIZES["spatial_grid"] * f("spatial_grid"))), seed)
    del rng
    ids = set()
    for x in items:
        assert x["id"] not in ids, x["id"]
        ids.add(x["id"])
    info = {"version": VERSION, "seed": seed,
            "counts": {s: sum(x["skill"] == s for x in items) for s in SKILLS},
            "questions": {s: sum(len(x["questions"]) for x in items if x["skill"] == s) for s in SKILLS},
            "by_split": {f"{s}/{sp}": sum(x["skill"] == s and x["split"] == sp for x in items)
                         for s in SKILLS for sp in ("seen_game", "unseen_game", "generic")
                         if any(x["skill"] == s and x["split"] == sp for x in items)},
            "by_source": {}}
    for x in items:
        info["by_source"][x["source"]] = info["by_source"].get(x["source"], 0) + 1
    info["by_source"] = dict(sorted(info["by_source"].items()))
    noul_true = [t["true"] for x in items for k, t in x["targets"].items() if x["questions"][k]["type"] == "noul"]
    info["noul_gold_true_rate"] = round(sum(noul_true) / len(noul_true), 4)
    return items, info


def state_hashes(items: list) -> list:
    return sorted({hashlib.sha1(x["state"].encode()).hexdigest() for x in items})


def write(items: list, info: dict, outdir: str = ".") -> list:
    import os

    p = os.path.join(outdir, "jevspatial_v1_items.json.gz")
    with gzip.open(p, "wt") as fh:
        json.dump(items, fh, ensure_ascii=False)
    return [p]


if __name__ == "__main__":
    import argparse

    ap = argparse.ArgumentParser(description="build JevSpatial v1 items")
    ap.add_argument("--seed", type=int, default=0)
    ap.add_argument("--out", default=".")
    a = ap.parse_args()
    its, inf = build(a.seed)
    print(json.dumps(inf, indent=1))
    print(write(its, inf, a.out))