aboutsummaryrefslogtreecommitdiff
path: root/tools/build.py
blob: b45368132642cebda0cee1c4c19d2b719ec0b664 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
#!/usr/bin/env python3
"""Build the complete English translation of Famicom Igo Nyuumon (I'MAX, 1991).

Reads:  ../roms/original/Famicom Igo Nyuumon (Japan).nes
Writes: ../roms/english/Famicom Igo Nyuumon (English).nes (327,696 bytes)

Expands the MMC1 ROM to 16 x 16 KiB PRG + 16 x 4 KiB CHR banks, translating
the title screen, all book/course menus, BASICS 1 & 2 lessons (PRG bank 14),
ADVANCED lessons (PRG bank 8), Study-Course Drills (PRG bank 9), Study-Course
Results, PLAY/Review/Victory/Defeat screens & runtime scripts, and all 300
TEST prompts + 900 A/B/C feedback messages while preserving all original art
and animations.
"""
import json, os, sys
from PIL import Image, ImageDraw, ImageFont

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
from font8 import glyph
from bank3_en import E as BANK3_EN
from feedback_en import FEEDBACK_EN
from basics_en import BASICS_MESSAGES
from advanced_en import ADV_MESSAGES, DRILL_PROMPTS, DRILL_FEEDBACKS
import make_book
import title_screen

ROM = os.path.join(HERE, '..', 'roms', 'original', 'Famicom Igo Nyuumon (Japan).nes')
OUT = os.path.join(HERE, '..', 'roms', 'english', 'Famicom Igo Nyuumon (English).nes')

raw = open(ROM, 'rb').read()
prg = bytearray(raw[16:16 + 8 * 16384])
chr_ = bytearray(raw[16 + 8 * 16384:])

# Title screen is built by title_screen.py (called below when packing b3).


# ------------------------------------------------------------ English font
# Place all English 8x8 letters and punctuation in the unused kana region
# ($A0-$C3) of CHR bank 8.  Keeping $00-$7F untouched preserves all three
# instructor portraits (Seimoku $0A-$3F, Sadasaki $40-$67, Kuzumi $4A-$7F)
# as well as the A/B/C choice-panel art and the board/box decorations.
b2 = chr_[2 * 4096:3 * 4096]
bank8 = bytearray(b2)
def put8(code, ch, both=False):
    g = glyph(ch)
    for y in range(8):
        lo = 0
        for x in range(8):
            if g[y][x]: lo |= 1 << (7 - x)
        bank8[code * 16 + y] = lo
        bank8[code * 16 + 8 + y] = lo if both else 0

CHR8_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.,?!-:/'()"
CHR8_MAP = {ch: 0xA0 + i for i, ch in enumerate(CHR8_CHARS)}
for ch, code in CHR8_MAP.items():
    put8(code, ch)
# Quiz/drill question prefix uses $48 ("Q" over 第) and $49 (blank over 問);
# neither tile is used by any portrait (Sadasaki ends at $47, Kuzumi starts
# at $4A).  Digits live at $70-$79 with both planes set.
put8(0x48, 'Q')
for _k in range(16): bank8[0x49 * 16 + _k] = 0
for _d in range(10):
    put8(0x70 + _d, chr(ord('0') + _d), both=True)
    CHR8_MAP[chr(ord('0') + _d)] = 0x70 + _d
# Keep the original eight CHR banks at their original indices, add the
# English font as bank 8, and pad to 16 banks (power of two).
# Book-page font bank 9: copy of the 16x16 book font bank 1 with
# English 8x8 glyphs written into free tile codes.
intro_en, intro_c, menu_en, menu_c, bank9 = make_book.build()
# The original title logo and kana subtitle are sprites from CHR bank 1.
# Blank those sprite tiles so the new background logo is the only one seen.
bank10 = bytearray(4096)
bank11 = bytearray(chr_[4 * 4096:5 * 4096])
bank12 = bytearray(4096)
bank13 = bytearray(4096)
bank14 = bytearray(4096)
bank15 = bytearray(4096)

# ------------------------------------------------------------ text bank
b4 = bytearray(prg[4 * 16384:5 * 16384])
txtbank = bytearray(b4)
def encode(s):
    s = s.upper()
    out = []
    for ch in s:
        if ch == ' ':
            out.append(0x20)
        elif ch in CHR8_MAP:
            out.append(CHR8_MAP[ch])
        else:
            raise SystemExit('unmapped text char: ' + repr(ch))
    return bytes(out)
# Pack all 146 BASICS and BASICS PART 2 messages directly into PRG bank 14
# starting at $8000, matching the fixed-bank pointer table at $F283..$F3A6
# 1-to-1.  Each lesson box holds up to two 26-cell lines.
pos = 0
basics_ptrs = []
for mi, lines in enumerate(BASICS_MESSAGES):
    assert 1 <= len(lines) <= 2, (mi, lines)
    assert all(line and len(line) <= 26 for line in lines), (mi, lines)
    basics_ptrs.append(0x8000 + pos)
    for li, line in enumerate(lines):
        enc = encode(line) + (b'\x00' if li + 1 < len(lines) else b'')
        txtbank[pos:pos + len(enc)] = enc
        pos += len(enc)
    txtbank[pos] = 0xFF
    pos += 1
assert pos <= 0x2535, (pos, 'BASICS text collides with original $A535 area')
print('BASICS text bytes:', pos, '/', hex(0x2535), 'messages:', len(basics_ptrs))
# Lesson 8 (END) title shown in the PTS box: "owari-kata" -> END.
# This string lives in the lesson text bank (the engine reads bank 14),
# not in the bank-5 feedback table.
assert txtbank[0x33B8:0x33BD] == bytes([0xB5, 0xDC, 0xD8, 0xB6, 0xC0]), \
    txtbank[0x33B8:0x33BD].hex()
txtbank[0x33B8:0x33BD] = bytes([CHR8_MAP['E'], CHR8_MAP['N'], CHR8_MAP['D'], 0xFE, 0xFE])

# ------------------------------------------------------------ new ROM
# Preserve the original PRG banks 0-7 at their original indices (some
# code restores "bank 7" to get the fixed bank).  Put the translated
# ADVANCED lessons in bank 8, the Study-Course Drills in bank 9, the
# BASICS text bank at 14, and a copy of the fixed bank at slot 15.
banks = [bytearray(prg[i * 16384:(i + 1) * 16384]) for i in range(8)]
# The same lesson-title string also exists in the original bank 4 (some
# code paths still read that bank), so patch both copies.
assert banks[4][0x33B8:0x33BD] == bytes([0xB5, 0xDC, 0xD8, 0xB6, 0xC0])
banks[4][0x33B8:0x33BD] = bytes([CHR8_MAP['E'], CHR8_MAP['N'], CHR8_MAP['D'], 0xFE, 0xFE])
# English book intro (screen 11) and lesson menu (screen 12).  They fit
# in the original compressed slots, so no pointer changes are needed.
b3 = banks[3]
# Japanese-styled English title screen (Screen 0 + CHR0 + CHR7 stamp).
# Original $E57E OAM coordinates stay untouched so the white NIHON KIIN
# APPROVED stamp sits in the exact position of the 日本棋院推薦 stamp.
title_c = title_screen.build(b3, chr_)
assert len(title_c) <= 0x020A, (len(title_c), 'title screen does not fit')
b3[0:len(title_c)] = title_c
b3[len(title_c):0x020A] = b'\x00' * (0x020A - len(title_c))

b3[0x1256:0x1256 + len(intro_c)] = intro_c
b3[0x148D:0x148D + len(menu_c)] = menu_c

# Lesson-list continuation/results pages (screens 13-16) were still Japanese.
# They show extra portrait/background art, so give them their own copy of
# the book-font bank and only replace tiles that are unused on those pages.
_lesson_pages = [(0x16F0, 0x193A), (0x193A, 0x1B73),
                 (0x1B73, 0x1DB5), (0x1DB5, 0x1FB8)]
_keep_page = {0x01}  # live per-question status marker on screen 16
for _off, _end in _lesson_pages:
    _pg = make_book.decompress(b3, _off)[0]
    for _r in range(30):
        for _c in range(32):
            if _off == 0x1DB5:
                # Keep the portrait and the runtime status/score cells.
                _is_text = ((6 <= _r <= 21 and 3 <= _c <= 4) or
                            (_r == 4 and 18 <= _c <= 28) or
                            (8 <= _r <= 17 and 20 <= _c <= 28) or
                            (18 <= _r <= 19 and 18 <= _c <= 28))
            else:
                _is_text = ((3 <= _r <= 24 and 3 <= _c <= 13) or
                            (3 <= _r <= 16 and 17 <= _c <= 28))
            if not _is_text:
                _keep_page.add(_pg[_r * 32 + _c])
_page_free = [i for i in range(1, 256) if i not in _keep_page and i not in (0xFE, 0xFF)]
_page_chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.,!?-/:'
lesson_codes = dict(zip(_page_chars, _page_free))
assert len(lesson_codes) == len(_page_chars), 'out of lesson-page tile codes'
bank15[:] = chr_[1 * 4096:2 * 4096]
for _ch, _code in lesson_codes.items():
    _g = glyph(_ch)
    for _y in range(8):
        _mask = 0
        for _x in range(8):
            if _g[_y][_x]: _mask |= 1 << (7 - _x)
        _inv = 0xFF ^ _mask
        bank15[_code * 16 + _y] = _inv
        bank15[_code * 16 + 8 + _y] = _inv
# Draw bold 16x16 red/pink shaded verdict tiles for screen 16 ("PASS!" / "FAIL!").
# Palette 2 maps colour 3 = white paper, colour 2 = red stroke, colour 1 = pink shadow.
_vfree = _page_free[len(_page_chars):]
_vpos = 0
verdict16_codes = {}
for _ch in 'PASFIL!':
    tc = _vfree[_vpos:_vpos + 4]; _vpos += 4
    assert len(tc) == 4, 'out of verdict 16x16 tiles'
    verdict16_codes[_ch] = tc
    _g = glyph(_ch)
    # Render 16x16 scaled glyph with 1px drop shadow (colour 1) and red fill (colour 2)
    mask = [[False] * 16 for _ in range(16)]
    for dy in range(1, 15):
        for dx in range(1, 15):
            mask[dy][dx] = bool(_g[(dy - 1) // 2][(dx - 1) // 2])
    canvas = [[3] * 16 for _ in range(16)]
    for dy in range(16):
        for dx in range(16):
            if mask[dy][dx]:
                if dy + 1 < 16 and dx + 1 < 16:
                    canvas[dy + 1][dx + 1] = 2
    for dy in range(16):
        for dx in range(16):
            if mask[dy][dx]:
                canvas[dy][dx] = 1
    for ty in range(2):
        for tx in range(2):
            t = tc[ty * 2 + tx]
            for y in range(8):
                lo = hi = 0
                for x in range(8):
                    v = canvas[ty * 8 + y][tx * 8 + x]
                    if v & 1: lo |= 1 << (7 - x)
                    if v & 2: hi |= 1 << (7 - x)
                bank15[t * 16 + y] = lo
                bank15[t * 16 + 8 + y] = hi
# The original pending-question marker is kana tile $01.  The results
# runtime overwrites this column with its status marks, so only translate
# the pending placeholder and leave the runtime behaviour intact.
_g = glyph('-')
for _y in range(8):
    _mask = 0
    for _x in range(8):
        if _g[_y][_x]: _mask |= 1 << (7 - _x)
    _inv = 0xFF ^ _mask
    bank15[0x01 * 16 + _y] = _inv
    bank15[0x01 * 16 + 8 + _y] = _inv
# Lesson-list pages 13-15 are the continuation of the course menu.  The
# original numbers stay untouched (they use the bold book-font digits);
# only the Japanese lesson names and the right-hand description block are
# rewritten.  The names are vertical, one cell per column, matching the
# original menu layout so the selection cursor keeps working.
def make_lesson_page(off, title, part, names, clears, slot, options=()):
    page = bytearray(make_book.decompress(b3, off)[0][:1024])
    for x0, y0, x1, y1 in clears:
        make_book.clear(page, x0, y0, x1, y1)
    make_book.clear(page, 17, 3, 28, 16)
    make_book.put(page, 17, 4, title, lesson_codes)
    make_book.put(page, 17, 6, part, lesson_codes)
    make_book.put(page, 17, 9, 'CHOOSE ONE', lesson_codes)
    make_book.put(page, 17, 11, 'PRESS A', lesson_codes)
    for col, row, name in names:
        make_book.putv(page, col, row, name, lesson_codes)
    for col, row, text in options:
        make_book.putv(page, col, row, text, lesson_codes)
    c = make_book.compress(page)
    assert len(c) <= slot, (hex(off), len(c), slot)
    b3[off:off + len(c)] = c

# The numbers run right-to-left on each page, so the name columns are
# listed in the same right-to-left order as the original entries.
make_lesson_page(
    0x16F0, 'BASICS', 'PART 2',
    [(11, 6, 'OPENING'), (9, 6, 'SENTE'), (7, 6, 'HANDICAP')],
    [(13, 4, 13, 5), (3, 6, 13, 24)], 0x193A - 0x16F0,
    [(3, 6, 'MENU'), (5, 6, 'PREV')])
make_lesson_page(
    0x193A, 'ADVANCED', 'PART 1',
    [(13, 7, 'ATARI'), (11, 7, 'CAPTURE'), (9, 7, 'LADDER'),
     (7, 7, 'NET'), (5, 7, 'SNAPBACK')],
    [(3, 7, 13, 24)], 0x1B73 - 0x193A,
    [(3, 7, 'NEXT')])
# The numbers on this page are one cell to the right of the other pages.
make_lesson_page(
    0x1B73, 'ADVANCED', 'PART 2',
    [(12, 7, 'LINK'), (10, 7, 'CUT'), (8, 7, 'LIFE'),
     (12, 16, 'DEATH'), (10, 16, 'KO')],
    [(3, 6, 13, 13), (3, 14, 7, 14), (3, 15, 13, 24)], 0x1DB5 - 0x1B73,
    [(3, 7, 'MENU'), (5, 7, 'PREV')])

# Screen 16: study-course results ("PRESS A FOR MENU", "TOPICS",
# questions 1-10, and a live score out of 10).  Preserve the portrait,
# the per-question status column at x=19, and the score cell at row 19,
# column 26; those are updated by the lesson-result state machine.
results16 = bytearray(make_book.decompress(b3, 0x1DB5)[0][:1024])
make_book.clear(results16, 3, 6, 4, 21)
make_book.clear(results16, 18, 4, 28, 4)
make_book.clear(results16, 20, 8, 28, 19)
make_book.putv(results16, 3, 9, 'A: MENU', lesson_codes)
make_book.put(results16, 18, 4, 'TOPICS', lesson_codes)
for _n in range(1, 11):
    make_book.put(results16, 20, 7 + _n, f'{_n:2} ...', lesson_codes)
make_book.put(results16, 20, 18, 'OUT OF 10', lesson_codes)
make_book.put(results16, 23, 19, 'OK:', lesson_codes)
results16_c = make_book.compress(results16)
assert len(results16_c) <= 0x1FB8 - 0x1DB5, \
    (len(results16_c), 'study-course results screen does not fit')
b3[0x1DB5:0x1DB5 + len(results16_c)] = results16_c
b3[0x1DB5 + len(results16_c):0x1FB8] = \
    b'\x00' * (0x1FB8 - 0x1DB5 - len(results16_c))

# Lesson base screen (screens 17-19 share one stream at $9FB8):
# translate the small "points" legend in the box.
base, _ = make_book.decompress(b3, 0x1FB8)
base = bytearray(base)
code8 = dict(CHR8_MAP)
for i, ch in enumerate('PTS'):
    base[17 * 32 + 3 + i] = code8[ch]
base_c = make_book.compress(base)
assert len(base_c) <= 378, (len(base_c), 'lesson base does not fit')
b3[0x1FB8:0x1FB8 + len(base_c)] = base_c

# ------------------------------------------------------- PLAY setup screens
# Screens 6 (continue/new game) and 7 (PLAY settings) both use CHR 4K
# bank 4.  Build one English copy of that bank and choose letter tiles
# that are unused by the artwork of *both* screens.
s6 = bytearray(make_book.decompress(b3, 0x0813)[0])
s7 = bytearray(make_book.decompress(b3, 0x0A18)[0])
def s6clear(x0, y0, x1, y1):
    for yy in range(y0, y1 + 1):
        for xx in range(x0, x1 + 1):
            s6[yy * 32 + xx] = 0x00
def s7clear(x0, y0, x1, y1):
    for yy in range(y0, y1 + 1):
        for xx in range(x0, x1 + 1):
            s7[yy * 32 + xx] = 0x00
# Screen 6: remove the whole Japanese text block, including the
# dakuten/handakuten marks that sit one row above the kana.
for _yy in range(13, 25):
    s6clear(2, _yy, 29, _yy)
# Replace the Japanese "PLAY GO" calligraphy with a small English label.
s6clear(3, 4, 16, 11)
s7clear(3, 3, 15, 10)
s7clear(2, 12, 29, 12)
for yy in (15, 17, 19, 21, 23):
    s7clear(3, yy, 13, yy); s7clear(17, yy, 23, yy); s7clear(24, yy, 28, yy)
s7clear(2, 26, 29, 26)
# The original border rows carry stray dakuten tiles (0xDF) that paired
# with the Japanese labels; they read as random marks under the English
# text, so flatten them back to the plain border pattern.
for _yy in range(13, 25):
    for _xx in range(3, 29):
        if s7[_yy * 32 + _xx] == 0xDF:
            s7[_yy * 32 + _xx] = 0x32
keep7 = set()
for rr in range(30):
    for cc in range(32):
        s7_text = ((3 <= rr <= 10 and 3 <= cc <= 15) or rr == 12 or (
                rr in (15, 17, 19, 21, 23) and (3 <= cc <= 13 or 17 <= cc <= 22 or 24 <= cc <= 28)) or rr == 26)
        s6_text = ((13 <= rr <= 24 and 2 <= cc <= 29) or (4 <= rr <= 11 and 3 <= cc <= 16))
        if not s7_text:
            keep7.add(s7[rr * 32 + cc])
        if not s6_text:
            keep7.add(s6[rr * 32 + cc])
# The cursor/pointer and a few other runtime icons use low CHR tiles.
# Keep English text in the high, genuinely free part of the 4K bank so
# letters such as the final E in "CONTINUE" cannot overwrite one.
free7 = [i for i in range(0xC0, 0x100)
         if i not in keep7 and i not in (0xFE, 0xFF)]
chars7 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.,!?-/:<>'
assert len(free7) >= len(chars7), 'ran out of high PLAY-menu tiles'
codes7 = dict(zip(chars7, free7))
bank11[:] = chr_[4 * 4096:5 * 4096]
# The continue screen draws a small blinking kana mark at row 23 with
# tile $AC.  Its text is gone, so the mark is now a stray artifact above
# PRESS START; blank that unused tile in this screen's CHR bank.
bank11[0xAC * 16:0xAC * 16 + 16] = b'\x00' * 16
for ch, code in codes7.items():
    g = glyph(ch)
    for y in range(8):
        mask = 0
        for x in range(8):
            if g[y][x]: mask |= 1 << (7 - x)
        # The setup screen's Japanese glyphs use colour 2.  Its runtime
        # attribute writes switch colour 2 between white and orange to show
        # the active option; colour 1 stays the same in both palettes.
        bank11[code * 16 + y] = 0
        bank11[code * 16 + 8 + y] = mask
# Runtime stones/time digits are $A6-$AF (0-9).  Replace the original
# glyphs too, so changing a counter cannot resurrect Japanese font tiles.
for _d in range(10):
    _g = glyph(str(_d))
    for _y in range(8):
        _mask = 0
        for _x in range(8):
            if _g[_y][_x]: _mask |= 1 << (7 - _x)
        bank11[(0xA6 + _d) * 16 + _y] = 0
        bank11[(0xA6 + _d) * 16 + 8 + _y] = _mask
def s6put(x, y, txt):
    for i, ch in enumerate(txt):
        if ch != ' ':
            s6[y * 32 + x + i] = codes7[ch]
def s7put(x, y, txt):
    for i, ch in enumerate(txt):
        if ch != ' ':
            s7[y * 32 + x + i] = codes7[ch]
# Screen 6: "continue previous game" menu.
s6put(4, 5, 'PLAY'); s6put(5, 7, 'GO')
s6put(8, 14, 'CONTINUE GAME')
s6put(11, 17, 'CONTINUE')
s6put(11, 19, 'NEW GAME')
s6put(10, 24, 'PRESS START')
# Keep the menu labels on the original Japanese text columns (11+).  The
# selection cursor stays at columns 9-10, immediately to their left.
for _ac in (1, 2, 3, 4):
    s6[960 + 4 * 8 + _ac] = 0xFF
# PRESS START (row 24) crosses several attribute quadrants.  Force every
# top quadrant it touches to the white palette so the whole footer is one
# colour instead of changing partway through the word.
_s6a = 960 + 6 * 8
for _ac in (2, 3, 4, 5):
    s6[_s6a + _ac] = (s6[_s6a + _ac] & 0xF0) | 0x0F
s6_c = make_book.compress(s6)
assert len(s6_c) <= 0x0A18 - 0x0813, (len(s6_c), 'PLAY continue screen does not fit')
b3[0x0813:0x0813 + len(s6_c)] = s6_c
b3[0x0813 + len(s6_c):0x0A18] = b'\x00' * (0x0A18 - 0x0813 - len(s6_c))
# Screen 7: PLAY settings table.
s7put(5, 4, 'PLAY'); s7put(6, 6, 'GO')
s7put(4, 12, 'UP/DN ITEM  LT/RT SELECT')
# Restore the original right-hand value box border at column 23 and put
# the values on the Japanese text column (24).  This is the correct table
# alignment: HUMAN / WHITE / YES start exactly where the original values
# did, one cell right of the previous English build.
for yy in (15, 17, 19):
    s7[yy * 32 + 22] = 0x00
    s7[yy * 32 + 23] = 0x36
    s7[yy * 32 + 28] = 0x00
for yy, label, o1, o2 in ((15, 'OPPONENT', 'CPU', 'HUMAN'),
                           (17, 'COLOR', 'BLACK', 'WHITE'),
                           (19, 'HANDICAP', 'NO', 'YES')):
    s7put(3, yy, label); s7put(17, yy, o1); s7put(24, yy, o2)
# Stones/time retain the original live counters at columns 23 and 22-23.
# Static digits here previously collided with those counters and hid the
# original decrease/increase controls.  Keep the dynamic cells clear.
for yy, label in ((21, 'STONES'), (23, 'TIME')):
    s7put(3, yy, label)
    s7put(17, yy, 'LESS')
    s7put(21, yy, '<')
    s7put(24, yy, '>')
    s7put(25, yy, 'MORE')
# The initial 60-second value is static in the compressed Japanese page;
# only later counter changes redraw it.  Restore both of its digits.
# Remove the original dakuten mark that sat above the Japanese footer;
# it now shows as a lone artifact above START.
s7[25 * 32 + 14] = 0xFE
s7put(22, 23, '60')
s7put(4, 26, 'PRESS START')
# The footer row is entirely in the lower quadrants of attribute row 6.
# Make those quadrants white across the whole PRESS START label.
_s7a = 960 + 6 * 8
s7[_s7a + 1] = (s7[_s7a + 1] & 0x0F) | 0xF0
s7_c = make_book.compress(s7)
assert len(s7_c) <= 706, (len(s7_c), 'PLAY setup screen does not fit')
b3[0x0A18:0x0A18 + len(s7_c)] = s7_c

# ------------------------------------------------------- PLAY board panels
# Screens 1 (PLAY), 2/3/4 (in-play/scoring board), and 5 (post-game review)
# all share CHR bank 5 -> translated copy in CHR bank 14.
s1 = bytearray(make_book.decompress(b3, 0x020A)[0])
s1_orig = bytes(s1)
s2 = bytearray(make_book.decompress(b3, 0x0438)[0])
s5 = bytearray(make_book.decompress(b3, 0x0611)[0])
# Runtime-written tiles that must keep their original graphics:
#   E9-F2  the fat countdown/move/capture digits
#   5B,5C,5D,5E,6B,6C,6D  the bell/gong stand artwork rows
#   E6,E7,4A  stone icons and divider
# Allocate English panel letters exclusively from the unused kana range
# $B0-$E5 of CHR bank 5 (54 tiles; chars1 needs 43).  Keeping $00-$AF
# untouched preserves all board intersections, Black/White territory markers
# ($25/$35), stone/bowl/bell art, and runtime status tiles ($8F etc.).
free1b = [i for i in range(0xB0, 0xE6)]
chars1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.,!?-:/'
assert len(free1b) >= len(chars1), 'ran out of panel letter tiles'
codes1b = dict(zip(chars1, free1b[:len(chars1)]))
bank14[:] = chr_[5 * 4096:6 * 4096]
for ch, code in codes1b.items():
    g = glyph(ch)
    for y in range(8):
        mask = 0
        for x in range(8):
            if g[y][x]: mask |= 1 << (7 - x)
        bank14[code * 16 + y] = 0xFF ^ mask
        bank14[code * 16 + 8 + y] = mask
# Draw crisp ".5" half-point glyph in tile $FC (used by blk 93 during scoring).
_half5 = [
    0b00000000,
    0b00011110,
    0b00010000,
    0b00011100,
    0b00000010,
    0b01000010,
    0b01011100,
    0b00000000,
]
for y in range(8):
    bank14[0xFC * 16 + y] = 0xFF ^ _half5[y]
    bank14[0xFC * 16 + 8 + y] = _half5[y]
# Also replace $FA ("白") -> 'W' and $FB ("黒") -> 'B' in bank14 for territory display.
for _tile, _ch in ((0xFA, 'W'), (0xFB, 'B')):
    _g = glyph(_ch)
    for y in range(8):
        mask = 0
        for x in range(8):
            if _g[y][x]: mask |= 1 << (7 - x)
        bank14[_tile * 16 + y] = 0xFF ^ mask
        bank14[_tile * 16 + 8 + y] = mask

def _board_put(buf, x, y, txt, codes=None):
    codes = codes if codes is not None else codes1b
    for i, ch in enumerate(txt):
        buf[y * 32 + x + i] = 0xFE if ch == ' ' else codes[ch]

REGIONS1 = [(3, 3, 6, 8), (12, 3, 21, 8), (23, 3, 26, 8)]

def _setup_board_common(buf, with_time=True, with_turn=False):
    for y0, x0, y1, x1 in REGIONS1:
        for rr in range(y0, y1 + 1):
            for cc in range(x0, x1 + 1):
                buf[rr * 32 + cc] = 0xFE
    for _i, _ch in enumerate('MOVE'):
        buf[(3 + _i) * 32 + 3] = codes1b[_ch]
    if with_time:
        for _i, _ch in enumerate('TIME'):
            buf[(3 + _i) * 32 + 8] = codes1b[_ch]
    if with_turn:
        _board_put(buf, 4, 5, 'TURN')
    for i, ch in enumerate('CAPS'):
        buf[(23 + i) * 32 + 3] = codes1b[ch]
    for _rr in (23, 24, 25, 26):
        buf[_rr * 32 + 4] = 0x4A
    buf[23 * 32 + 5] = codes1b['B']
    buf[24 * 32 + 5] = 0xE6
    buf[25 * 32 + 5] = codes1b['W']
    buf[26 * 32 + 5] = 0xE7

# Screen 1: main PLAY board + Screens 2/3/4: active PLAY / scoring board.
# Pack s1 followed immediately by s2 inside their combined slot $020A..$0611
# (1031 bytes) and update the $C892 pointers for screens 2/3/4.
_setup_board_common(s1, with_time=True, with_turn=True)
for i, txt in enumerate(('PLAY', 'LAND', 'END', 'QUIT')):
    _board_put(s1, 4, 13 + 2 * i, txt)
s1_c = make_book.compress(s1)
_setup_board_common(s2, with_time=True, with_turn=False)
s2_c = make_book.compress(s2)
s2_off = 0x020A + len(s1_c)
assert s2_off + len(s2_c) <= 0x0611, (len(s1_c), len(s2_c), 'PLAY screens 1-4 do not fit')
b3[0x020A:s2_off] = s1_c
b3[s2_off:s2_off + len(s2_c)] = s2_c
b3[s2_off + len(s2_c):0x0611] = b'\x00' * (0x0611 - s2_off - len(s2_c))
print(f'PLAY boards: s1={len(s1_c)}, s2-4={len(s2_c)} (at ${0x8000+s2_off:04X}) / {0x0611-0x020A}')

# Screen 5: post-game Review ("感想戦") board (slot $0611..$0813 = 514 bytes).
_setup_board_common(s5, with_time=False, with_turn=True)
for _rr in (7, 8, 11, 12):
    for _cc in range(3, 9):
        s5[_rr * 32 + _cc] = 0xFE
_board_put(s5, 3, 7, 'REVIEW')
_board_put(s5, 4, 11, 'REVW')
for i, txt in enumerate(('TRY', 'LAND', 'PLAY', 'END')):
    _board_put(s5, 4, 13 + 2 * i, txt)
for _rr in (23, 24, 25, 26):
    for _cc in range(12, 29):
        s5[_rr * 32 + _cc] = 0xFE
_board_put(s5, 12, 24, 'REVIEW MODE.')
s5_c = make_book.compress(s5)
assert len(s5_c) <= 0x0813 - 0x0611, (len(s5_c), 'Review board screen 5 does not fit')
b3[0x0611:0x0611 + len(s5_c)] = s5_c
b3[0x0611 + len(s5_c):0x0813] = b'\x00' * (0x0813 - 0x0611 - len(s5_c))

# ------------------------------------------------------- TEST intro screen
# Screens 21/22 share a compressed page that uses CHR 4K bank 3.
# The sliding-door pattern on the right half is repainted at runtime with
# a wide set of tile codes, so the English letters must avoid all of
# them or the door turns into garbage.
DOOR_RUNTIME = set(
    [0x00, 0x01]
    + list(range(0x1A, 0x20)) + [0x2A, 0x2B, 0x2C]
    + list(range(0x38, 0x40)) + list(range(0x48, 0x50))
    + list(range(0x58, 0x60)) + list(range(0x60, 0x6D))
    + list(range(0x70, 0x7D)) + [0x7F] + list(range(0x80, 0x84))
    + [0x8E] + list(range(0x90, 0x94)) + [0x9C, 0x9E, 0x9F]
    + list(range(0xA0, 0xA4)) + [0xAC, 0xAF]
    + list(range(0xB9, 0xBD)) + list(range(0xCB, 0xD0))
    + list(range(0xDB, 0xE0)) + list(range(0xE4, 0xE7))
    + list(range(0xEC, 0xF1)) + list(range(0xF3, 0xF7))
    + [0xFB, 0xFC, 0xFE])
t21 = bytearray(make_book.decompress(b3, 0x2132)[0])
def t21clear(x0, y0, x1, y1):
    for yy in range(y0, y1 + 1):
        for xx in range(x0, x1 + 1):
            t21[yy * 32 + xx] = 0xFE
# Clear the title/banner/message areas but KEEP the portrait artwork
# (rows 14-17, cols 3-8).  The body starts on row 19; clearing from row
# 14 used to erase most of the portrait.
t21clear(3, 2, 17, 9)
# Row 18 holds a leftover dakuten from the original body text; it is the
# mark that appears above HALL in the English build.
t21clear(3, 18, 17, 26)
keep21 = set()
for rr in range(30):
    for cc in range(32):
        if (3 <= rr <= 9 and 3 <= cc <= 17) or (19 <= rr <= 26 and 3 <= cc <= 17):
            continue
        keep21.add(t21[rr * 32 + cc])
free21 = [i for i in range(1, 256) if i not in keep21
          and i not in DOOR_RUNTIME and i not in (0xFE, 0xFF)]
bank10[:] = chr_[3 * 4096:4 * 4096]
chars21 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.,!?-/:'
codes21 = dict(zip(chars21, free21[:len(chars21)]))
assert len(codes21) == len(chars21), 'ran out of TEST-intro tile codes'
for ch, code in codes21.items():
    g = glyph(ch)
    for y in range(8):
        mask = 0
        for x in range(8):
            if g[y][x]: mask |= 1 << (7 - x)
        # Page-1 body text is black on the pink page.  The page palette maps
        # colour 0 to black and colour 3 to pink, so fill the cell with
        # colour 3 and cut the letter out in colour 0 (not an inverse box).
        inv = 0xFF ^ mask
        bank10[code * 16 + y] = inv
        bank10[code * 16 + 8 + y] = inv
def t21glyph16(ch, tc):
    for t in tc:
        for k in range(16):
            bank10[t * 16 + k] = 0
    g = glyph(ch)
    # Leave a one-pixel margin on every side of the 16x16 cell.  Without
    # it the outline generator has nowhere to put the top/bottom black
    # edge, so TEST/HALL looked open at the top.
    mask = [[False] * 16 for _ in range(16)]
    for dy in range(1, 15):
        for dx in range(1, 15):
            mask[dy][dx] = bool(g[(dy - 1) // 2][(dx - 1) // 2])
    # Match the original red calligraphy with a black outline: colour 2
    # is red in the title palette and colour 1 is black.
    canvas = [[2 if mask[dy][dx] else 3 for dx in range(16)]
              for dy in range(16)]
    for dy in range(16):
        for dx in range(16):
            if mask[dy][dx]:
                continue
            if any(0 <= dy + oy < 16 and 0 <= dx + ox < 16 and
                   mask[dy + oy][dx + ox]
                   for oy in (-1, 0, 1) for ox in (-1, 0, 1)):
                canvas[dy][dx] = 0
    for dy in range(16):
        for dx in range(16):
            value = canvas[dy][dx]
            if not value:
                continue
            t = tc[(dy // 8) * 2 + (dx // 8)]
            bit = 1 << (7 - (dx % 8))
            if value & 1: bank10[t * 16 + (dy % 8)] |= bit
            if value & 2: bank10[t * 16 + 8 + (dy % 8)] |= bit
t21pos = len(chars21)
t21codes = {}
for ch in 'TESTHAL':
    tc = free21[t21pos:t21pos + 4]; t21pos += 4
    t21codes[ch] = tc
    t21glyph16(ch, tc)
def t21put16(x, y, txt):
    for i, ch in enumerate(txt):
        tc = t21codes[ch]
        for dy in range(2):
            for dx in range(2):
                t21[(y + dy) * 32 + x + i * 2 + dx] = tc[dy * 2 + dx]
def t21put(x, y, txt, codes=None):
    codes = codes21 if codes is None else codes
    for i, ch in enumerate(txt):
        t21[y * 32 + x + i] = 0xFE if ch == ' ' else codes[ch]
def t21style8(code, ch, planes, pink_background=False):
    g = glyph(ch)
    for y in range(8):
        mask = 0
        for x in range(8):
            if g[y][x]: mask |= 1 << (7 - x)
        lo = mask if planes & 1 else 0
        hi = mask if planes & 2 else 0
        if pink_background:
            # Colour 3 background with the requested foreground colour.
            lo |= 0xFF ^ mask
            hi |= 0xFF ^ mask
        bank10[code * 16 + y] = lo
        bank10[code * 16 + 8 + y] = hi
# The byline is red colour 2 on pink, unlike the body copy.  Give it
# private glyphs so the body and runtime help-page text keep their style.
byline21 = {}
for ch in dict.fromkeys('BY NIHON KIIN'.replace(' ', '')):
    byline21[ch] = free21[t21pos]; t21pos += 1
    t21style8(byline21[ch], ch, 2, pink_background=True)
# The two choices use colour 1 on pink in the original runtime palettes.
choice21 = {}
for ch in dict.fromkeys('TRYEND'):
    choice21[ch] = free21[t21pos]; t21pos += 1
    t21style8(choice21[ch], ch, 1, pink_background=True)
# Page 2 is drawn by a runtime script whose palette has colour 0 as
# black and colour 3 as the pink background.  Give it inverse glyphs
# (filled colour-3 cell, colour-0 letter) so the result is black text
# on pink, not pink text in black boxes.
page2_codes = {}
for ch in dict.fromkeys('RANKS 12 KYU TO 4 KYU.THIS TEST HAS 20 QUESTIONS'):
    if ch == ' ':
        continue
    page2_codes[ch] = free21[t21pos]; t21pos += 1
    g = glyph(ch)
    for y in range(8):
        mask = 0
        for x in range(8):
            if g[y][x]:
                mask |= 1 << (7 - x)
        bank10[page2_codes[ch] * 16 + y] = 0xFF ^ mask
        bank10[page2_codes[ch] * 16 + 8 + y] = 0xFF ^ mask
assert t21pos <= len(free21), 'ran out of styled TEST-intro tiles'
t21put16(4, 4, 'TEST'); t21put16(4, 6, 'HALL')
t21put(4, 9, 'BY NIHON KIIN', byline21)
# Page 1 uses the same rows as the Japanese original.  Page 2 is a
# runtime nametable-update script (see fb_patch below) that overwrites
# rows 19-26, exactly like the original.
# Keep page-1 text inside the rectangles that the page-2 runtime script
# overwrites.  Otherwise the longer English lines survive behind the
# page-2 text (the original Japanese lines were shorter).
t21put(4, 19, 'THIS HALL')
t21put(4, 21, 'MEASURES YOUR')
t21put(6, 23, 'GO SKILL.')
# Use the original Japanese choice columns: TRY starts at column 5 and
# END at column 13.  The selection cursor sits immediately to their left
# (columns 3-4 and 11-12), and the runtime palette makes the selected
# word pink and the other one white.
t21put(5, 26, 'TRY', choice21)
t21put(13, 26, 'END', choice21)
def t21setpal(rr0, cc0, rr1, cc1, pal):
    for _rr in range(rr0, rr1 + 1):
        for _cc in range(cc0, cc1 + 1):
            _ai = 960 + (_rr // 4) * 8 + (_cc // 4)
            _sh = ((_rr % 4) // 2) * 4 + ((_cc % 4) // 2) * 2
            _cur = (t21[_ai] >> _sh) & 3
            if _cur != pal:
                t21[_ai] = (t21[_ai] & ~(3 << _sh)) | (pal << _sh)
# Keep the original title/body/choice palettes and the portrait's private
# palette.  Only the last byline cells need palette 1; they were blank in
# the shorter Japanese byline.
t21setpal(8, 16, 9, 17, 1)

t21_c = make_book.compress(t21)
assert len(t21_c) <= 651, (len(t21_c), 'TEST intro does not fit')
b3[0x2132:0x2132 + len(t21_c)] = t21_c
b3[0x2132 + len(t21_c):0x23BD] = b'\x00' * (0x23BD - 0x2132 - len(t21_c))

# Translate the second TEST help page.  Its text is stored as raw
# nametable-update bytes in the fixed bank, not in the compressed screen.
fb = banks[7]
# Update $C892 screen pointers for screens 2, 3, 4 to packed s2_off.
_s2_addr = 0x8000 + s2_off
for _si in (2, 3, 4):
    _so = 0x0892 + 2 * _si
    assert (fb[_so] | (fb[_so + 1] << 8)) == 0x8438
    fb[_so] = _s2_addr & 0xFF
    fb[_so + 1] = _s2_addr >> 8

# Repoint all 146 BASICS & BASICS PART 2 messages ($F283..$F3A6) to the
# cleanly packed messages in PRG bank 14.
assert len(basics_ptrs) == 146
for _i, _ptr in enumerate(basics_ptrs):
    _o = 0x3283 + 2 * _i
    _old = fb[_o] | (fb[_o + 1] << 8)
    assert 0xA535 <= _old <= 0xBF50, (_i, hex(_o), hex(_old))
    fb[_o] = _ptr & 0xFF
    fb[_o + 1] = _ptr >> 8

def fb_patch(seq, text, pad=0xFE):
    global fb
    enc = bytes(pad if ch == ' ' else page2_codes[ch] for ch in text)
    start = 0
    while True:
        k = fb.find(seq, start)
        if k < 0: break
        if len(enc) > len(seq):
            raise SystemExit('fixed-bank text too long: ' + text)
        fb[k:k + len(seq)] = enc + bytes([pad]) * (len(seq) - len(enc))
        start = k + len(seq)
# Shift the last runtime line two cells right (x5 -> x7).  It then
# clears the old page-1 END tiles, which are in a different palette
# and used to leave a lone white square beside the page-2 text.
_line5 = bytes([0x23,0x45,0xFE,0xFE,0xEB,0xB4,0xC3,0xEE,0xBB,0xB2,0xE6])
_k = fb.find(_line5)
assert _k >= 0 and fb.find(_line5, _k + 1) < 0, 'page-2 line-5 patch not unique'
fb[_k + 1] = 0x67
# Put page-2 lines 2 and 3 on rows 21 and 23, exactly where the longer
# English page-1 body lives.  This overwrites the old body completely.
_line2 = bytes([0x22,0x84,0xAB,0xAD,0xF6,0xF7,0xB6,0xD7,0xE5,0xAF,0xF6,0xF7,0xCF,0xC3,0xC9])
_k = fb.find(_line2)
assert _k >= 0 and fb.find(_line2, _k + 1) < 0, 'page-2 line-2 patch not unique'
fb[_k + 1] = 0xA4
# Page-2 line 3 goes on row 23, exactly where page-1 line 3 lives.
_line3 = bytes([0x22,0xC6,0xF1,0xF2,0xDE,0xFE,0xF3,0xB2,0xCF,0xBD,0xE6])
_k = fb.find(_line3)
assert _k >= 0 and fb.find(_line3, _k + 1) < 0, 'page-2 line-3 patch not unique'
fb[_k + 1] = 0xE6
# Move the "HAS 20" line down to row 25, leaving a one-row gap after
# the second line.
_line4 = bytes([0x23,0x07,0xA8,0xA9,0xEA,0xC9,0xEA,0xB2,0xC6])
_k = fb.find(_line4)
assert _k >= 0 and fb.find(_line4, _k + 1) < 0, 'page-2 line-4 patch not unique'
fb[_k + 1] = 0x27
# Use both original blank runs on row 26 to erase the page-1 choices
# (TRY / END) after QUESTIONS has moved to row 27.
for _old, _new in (
        # Clear only the old page-1 choices (columns 5-18).  The run at
        # $22E5 is ten tiles long, so start it at column 9 (not 12); the
        # previous addresses ran through columns 19-22 and cut a strip out
        # of the sliding-door artwork on the right.
        (bytes([0x22,0xA6]) + b'\xFE' * 7, bytes([0x23,0x45]) + b'\xFE' * 7),
        (bytes([0x22,0xE5]) + b'\xFE' * 7, bytes([0x23,0x49]) + b'\xFE' * 7)):
    _k = fb.find(_old)
    assert _k >= 0 and fb.find(_old, _k + 1) < 0, 'page-2 blank row not unique'
    fb[_k:_k + len(_old)] = _new
# Explain the rank range naturally.  "Kyu" is a Go rank; the Japanese
# original says the test covers ranks 12 kyu through 4 kyu.
fb_patch(bytes([0xAA,0xAC,0xF4,0xF5,0xFE,0xFE,0xFE,0xAE,0xF4,0xF5,0xFE,0xDF]), 'RANKS 12 KYU')
fb_patch(bytes([0xAB,0xAD,0xF6,0xF7,0xB6,0xD7,0xE5,0xAF,0xF6,0xF7,0xCF,0xC3,0xC9]), 'TO 4 KYU.')
fb_patch(bytes([0xF1,0xF2,0xDE,0xFE,0xF3,0xB2,0xCF,0xBD,0xE6]), 'THIS TEST')
fb_patch(bytes([0xA8,0xA9,0xEA,0xC9,0xEA,0xB2,0xC6]), 'HAS 20')
fb_patch(bytes([0xFE,0xFE,0xEB,0xB4,0xC3,0xEE,0xBB,0xB2,0xE6]), 'QUESTIONS')


# ------------------------------------------------------- quiz/result UI text
# Screen 23 (question screen) static label: "black to play".
s23 = bytearray(make_book.decompress(b3, 0x23BD)[0])
# The small turn panel uses pale colour-3 lettering in the Japanese
# original.  The main quiz font is colour 1, so allocate private panel
# glyphs instead of recolouring every question and feedback message.
keep23 = set()
for rr in range(30):
    for cc in range(32):
        if not (rr in (11, 12) and 3 <= cc <= 8):
            keep23.add(s23[rr * 32 + cc])
reserved23 = (set(code8.values()) | set(range(0x70, 0x7A)) |
              {0x48, 0x49, 0xFE, 0xFF})
free23 = [i for i in range(1, 256) if i not in keep23 and i not in reserved23]
# Never allocate the low tiles here: $0A-$11 are live sprite tiles on
# the TEST screen (black stones, selection cursor, etc.).  Overwriting
# them turned stones into "S" and the unselected A into "Y".  Use high
# glyph slots that are free on both the quiz and lesson screens.
lessonbase_codes = set(make_book.decompress(b3, 0x1FB8)[0][:960])
panel_candidates = [0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x8C, 0x8D, 0x8E]
for code in panel_candidates:
    assert code not in keep23, (hex(code), 'TEST panel tile used by quiz art')
    assert code not in lessonbase_codes, (hex(code), 'TEST panel tile used by lesson art')
    assert code not in reserved23, (hex(code), 'TEST panel tile reserved for text')
codes23panel = {}
for ch, code in zip(dict.fromkeys('BLACKPLAYSN'), panel_candidates):
    codes23panel[ch] = code
    g = glyph(ch)
    for y in range(8):
        mask = 0
        for x in range(8):
            if g[y][x]: mask |= 1 << (7 - x)
        bank8[code * 16 + y] = mask
        bank8[code * 16 + 8 + y] = mask
for rr in range(11, 14):
    for cc in range(3, 9):
        s23[rr * 32 + cc] = 0x00
for i, ch in enumerate('BLACK'):
    s23[11 * 32 + 3 + i] = codes23panel[ch]
for i, ch in enumerate('PLAYS'):
    s23[12 * 32 + 3 + i] = codes23panel[ch]
# Replace the tiny kanji "答" at row 17 col 3 of the choice box with "ANS".
for i, ch in enumerate('ANS'):
    s23[17 * 32 + 3 + i] = codes23panel[ch]
s23_c = make_book.compress(s23)
assert len(s23_c) <= 402, (len(s23_c), 'quiz screen does not fit')
b3[0x23BD:0x23BD + len(s23_c)] = s23_c

# Screen 24 (result screen).  Keep the TEST-intro font in bank 12 and
# give the result screen its own copy in bank 10.  The result's rank
# digits and its two portraits reuse many tiles that the large TEST HALL
# lettering would otherwise overwrite.
bank12[:] = bank10
bank10[:] = chr_[3 * 4096:4 * 4096]
s24 = bytearray(make_book.decompress(b3, 0x254F)[0])
RANK_ART = ({0x6C, 0x6D, 0x6E, 0x6F, 0x7C, 0x7D, 0x7E, 0x7F}
            | set(range(0x80, 0xA0)))
RESULT_PORTRAIT = set()
for _lo, _hi in ((0x0A, 0x10), (0x1A, 0x20), (0x2A, 0x30),
                 (0x3A, 0x40), (0x40, 0x48), (0x4A, 0x50),
                 (0x50, 0x58), (0x5A, 0x60), (0x60, 0x68),
                 (0x6A, 0x70), (0x7A, 0x80)):
    RESULT_PORTRAIT |= set(range(_lo, _hi))
keep24 = set(RANK_ART) | RESULT_PORTRAIT
for rr in range(30):
    for cc in range(32):
        # Only the old heading and the kyu/desu glyphs are disposable.
        if rr in (3, 5, 6) and 3 <= cc <= 18:
            continue
        keep24.add(s24[rr * 32 + cc])
free24 = [i for i in range(1, 256)
          if i not in keep24 and i not in (0xFE, 0xFF)]
codes24 = dict(zip(chars21, free24[:len(chars21)]))
assert len(codes24) == len(chars21), 'ran out of result-screen tiles'
for ch, code in codes24.items():
    g = glyph(ch)
    for y in range(8):
        mask = 0
        for x in range(8):
            if g[y][x]: mask |= 1 << (7 - x)
        bank10[code * 16 + y] = mask
        bank10[code * 16 + 8 + y] = 0
for rr in (3, 5, 6):
    for cc in range(3, 19):
        s24[rr * 32 + cc] = 0xFE
for i, ch in enumerate('YOUR RANK'):
    if ch != ' ':
        s24[3 * 32 + 3 + i] = codes24[ch]

# The result script selects one of several rank drawings and two short
# comments.  Replace each kana run in place, retaining all command and
# skip bytes.  Blank the standalone kyu/dakuten decorations as well.
def result_patch(addr, old, text):
    old = bytes(old)
    # The final run of a script is followed directly by its skip byte;
    # intermediate runs use a 00 terminator.  Match the address and run
    # itself so both forms are handled.
    pat = bytes([addr >> 8, addr & 0xFF]) + old
    enc = bytes(0xFE if ch == ' ' else codes24[ch] for ch in text)
    assert len(enc) <= len(old), (hex(addr), text, len(old))
    enc += bytes([0xFE]) * (len(old) - len(enc))
    start, hits = 0, 0
    while True:
        k = fb.find(pat, start)
        if k < 0:
            break
        fb[k + 2:k + 2 + len(old)] = enc
        hits += 1
        start = k + len(pat)
    assert hits, (hex(addr), old.hex(), text)

for addr, old in ((0x20AD, [0xEC]), (0x20CD, [0xEE]),
                  (0x20CD, [0xED]), (0x21C6, [0xDF, 0xFE, 0xDF, 0xDF]),
                  (0x21C6, [0xDF, 0xFE, 0xFE, 0xDF]), (0x21C7, [0xDF]),
                  (0x2247, [0xDF])):
    result_patch(addr, old, '')
for addr, old, text in (
    (0x21E5, [0xCF,0xC0,0xCF,0xC0,0xC3,0xBD,0xDC,0xC8,0xE6], 'START NOW'),
    (0x21E5, [0xCF,0xC0,0xFE,0xC9,0xCB,0xCF,0xBC,0xC3,0xD6,0xE6], 'NICE TRY!'),
    (0x21E5, [0xBB,0xB7,0xB6], 'GO!'),
    (0x2225, [0xC0,0xC9,0xBC,0xD0,0xC5,0xB6,0xC0,0xC8,0xE6], 'HAVE FUN!'),
    (0x21E5, [0xB1,0xC5,0xC0,0xC5,0xD7,0xE5,0xD3,0xE4,0xC4], 'YOU CAN'),
    (0x2225, [0xC2,0xD6,0xB8,0xC5,0xDA,0xCF,0xBD,0xDC,0xE6], 'IMPROVE!'),
    (0x21E5, [0xD3,0xB3,0xFE,0xD6,0xDC,0xB2,0xC4,0xCA,0xE5], 'WELL DONE'),
    (0x2225, [0xB2,0xB4,0xCF,0xBE,0xDD,0xDC,0xD6,0xE6], 'NICE!'),
    (0x2225, [0xB5,0xC3,0xB1,0xDC,0xBE,0xBC,0xC0,0xB2,0xDC,0xE6], 'TRY AGAIN!'),
    (0x21E5, [0xB2,0xC1,0xC4], 'OH!'),
    (0x21E5, [0xDC,0xC0,0xB8,0xBC,0xE5], 'CLOSE'),
    (0x2225, [0xB5,0xB2,0xC2,0xB6,0xDA,0xBF,0xB3,0xD6,0xE6], 'TRY AGAIN'),
    (0x21E5, [0xC2,0xD6,0xB2,0xB6,0xC0,0xE9,0xE9,0xE6], 'SO CLOSE'),
    (0x2225, [0xB1,0xD8,0xCF,0xBE,0xDD,0xDC,0xE6], 'CLOSE!'),
    (0x21E5, [0xD3,0xB3,0xFE,0xB2,0xB3,0xBA,0xC4,0xCA], 'ALMOST!'),
    (0x21E5, [0xDC,0xC0,0xB8,0xBC,0xC6,0xCA], 'ALMOST'),
    (0x2225, [0xD3,0xB3,0xE5,0xB5,0xB1,0xB2,0xC3,0xCA], 'GREAT!'),
    (0x2265, [0xD1,0xD8,0xC3,0xBD,0xDC,0xC8,0xE9,0xE9,0xE6], 'BRAVO!'),
):
    result_patch(addr, old, text)

s24_c = make_book.compress(s24)
assert len(s24_c) <= 658, (len(s24_c), 'result screen does not fit')
b3[0x254F:0x254F + len(s24_c)] = s24_c

# ------------------------------------------------------- play/result dialogs
# Screens 8/9 ($0CDA) = VICTORY! ("快勝!") and Screen 10 ($0F98) = DEFEAT! ("無念!").
# Both show a framed samurai illustration in rows 4-15, the banner in rows 17-19,
# and "Review game? YES / NO" in rows 23-25.  Preserve the samurai illustrations!
dlgs = [bytearray(make_book.decompress(b3, a)[0]) for a in (0x0CDA, 0x0F98)]
regions = [(17, 10, 19, 21), (23, 10, 25, 22)]
def in_dlg_region(rr, cc):
    return any(y0 <= rr <= y1 and x0 <= cc <= x1 for y0, x0, y1, x1 in regions)
keep13 = set()
for ds in dlgs:
    for rr in range(30):
        for cc in range(32):
            if not in_dlg_region(rr, cc):
                keep13.add(ds[rr * 32 + cc])
free13 = [i for i in range(1, 256) if i not in keep13 and i not in (0xFE, 0xFF)]
chars13 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.,!?-:/'
assert len(free13) >= len(chars13), (len(free13), 'ran out of Victory/Defeat tiles')
codes13 = dict(zip(chars13, free13[:len(chars13)]))
bank13[:] = chr_[6 * 4096:7 * 4096]
for ch, code in codes13.items():
    g = glyph(ch)
    for y in range(8):
        mask = 0
        for x in range(8):
            if g[y][x]: mask |= 1 << (7 - x)
        # Original CHR6 text uses colour 1 (red scroll bg, lo=FF hi=00) and
        # colour 3 (black ink, lo=FF hi=mask).
        bank13[code * 16 + y] = 0xFF
        bank13[code * 16 + 8 + y] = mask
def dlg_put(ds, x, y, txt):
    for i, ch in enumerate(txt):
        ds[y * 32 + x + i] = 0xFE if ch == ' ' else codes13[ch]
for ds, banner in zip(dlgs, ('VICTORY!', 'DEFEAT!')):
    for y0, x0, y1, x1 in regions:
        for rr in range(y0, y1 + 1):
            for cc in range(x0, x1 + 1):
                ds[rr * 32 + cc] = 0xFE
    dlg_put(ds, 16 - len(banner) // 2, 18, banner)
    dlg_put(ds, 10, 23, 'REVIEW GAME?')
    dlg_put(ds, 13, 25, 'YES')
    dlg_put(ds, 17, 25, 'NO')
for a, ds in zip((0x0CDA, 0x0F98), dlgs):
    dc = make_book.compress(ds)
    assert len(dc) <= 0x2BE, (hex(a), len(dc))
    b3[a:a + len(dc)] = dc
    b3[a + len(dc):a + 0x2BE] = b'\x00' * (0x2BE - len(dc))

# ------------------------------------------------- fixed-bank scripts
# The in-game message/menu system runs tile-run scripts from the fixed
# bank via pointer table $E5E0 (112 entries).  Each block starts with
# total_tile_count, followed by [hi lo tiles... 00] runs (no 00 after
# the last run).  Contiguous block regions can be repacked cleanly in
# place while updating their $E5E0 pointers.

def script_patch(fb, old, new):
    assert len(new) == len(old), (old.hex(), new.hex())
    k = fb.find(old)
    assert k >= 0, 'script pattern not found: ' + old.hex()
    while True:
        nxt = fb.find(old, k + 1)
        if nxt < 0:
            break
        raise SystemExit('script pattern not unique: ' + old.hex())
    fb[k:k + len(old)] = new

def encode_script_block(runs):
    """Build a $C7B9 script block from [(ppu_addr, bytes_tiles), ...]."""
    total = sum(len(tiles) for _, tiles in runs)
    assert 1 <= total <= 127, total
    out = bytearray([total])
    for i, (addr, tiles) in enumerate(runs):
        assert 0x2000 <= addr <= 0x23FF and 0x00 not in tiles, (hex(addr), tiles)
        out.append(addr >> 8)
        out.append(addr & 0xFF)
        out.extend(tiles)
        if i + 1 < len(runs):
            out.append(0x00)
    return bytes(out)

def pack_script_region(fb, start_addr, end_addr, blocks_by_idx):
    """Pack {blk_idx: block_bytes} into [start_addr, end_addr) and update $E5E0."""
    pos = start_addr - 0xC000
    lim = end_addr - 0xC000
    for idx, data in blocks_by_idx.items():
        addr = 0xC000 + pos
        assert pos + len(data) <= lim, (idx, hex(addr), len(data), hex(end_addr))
        fb[pos:pos + len(data)] = data
        poff = 0x25E0 + 2 * idx
        fb[poff] = addr & 0xFF
        fb[poff + 1] = addr >> 8
        pos += len(data)
    fb[pos:lim] = b'\xFF' * (lim - pos)
    return pos - (start_addr - 0xC000)

def _t(text, codes, pad=0xFE):
    return bytes(pad if ch == ' ' else codes[ch] for ch in text.upper())

# --- Lesson PTS-box titles (BASICS 1-8 & BASICS PART 2) ---
script_patch(fb, bytes([0x22,0xA4,0xB2,0xBA,0xC4,0xCA]),
             bytes([0x22,0xA4,code8['G'],code8['O'],0xFE,0xFE]))     # L2
script_patch(fb, bytes([0x05,0x22,0xA4,0xB2,0xBC,0xA6]),
             bytes([0x05,0x22,0xA4,code8['S'],code8['T'],code8['N']]))  # L3
script_patch(fb, bytes([0x22,0xA4,0xB7,0xDD,0xBC,0xC3]),
             bytes([0x22,0xA4,code8['M'],code8['O'],code8['V'],code8['E']]))  # L4
script_patch(fb, bytes([0x02,0x22,0xA5,0xFA,0xF3]),
             bytes([0x02,0x22,0xA5,code8['K'],code8['O']]))       # L5
script_patch(fb, bytes([0x06,0x22,0xA4,0xB2,0xBC,0xA6]),
             bytes([0x06,0x22,0xA4,code8['S'],code8['T'],code8['N']]))  # L6
script_patch(fb, bytes([0x01,0x22,0xA5,0xA0]),
             bytes([0x01,0x22,0xA5,code8['L']]))                  # L7
script_patch(fb, bytes([0x22,0xE6,0xC4,0xD9]),
             bytes([0x22,0xE6,code8['T'],code8['K']]))            # L3 "toru"
script_patch(fb, bytes([0x22,0xE5,0xB2,0xB6,0xBD]),
             bytes([0x22,0xE5,code8['S'],code8['T'],code8['N']]))  # L6
script_patch(fb, bytes([0x05,0x22,0xA4,0xB5,0xDC,0xD8,0xB6,0xC0]),
             bytes([0x05,0x22,0xA4,code8['E'],code8['N'],code8['D'],
                    0xFE,0xFE]))
# BASICS PART 2 PTS-box labels
script_patch(fb, bytes([0x22,0xA4,0xCC,0xBE,0xB7,0xC4,0xCA]),
             bytes([0x22,0xA4,code8['O'],code8['P'],code8['E'],code8['N'],0xFE]))
script_patch(fb, bytes([0x22,0xA4,0xBE,0xDD,0xC3,0xC9,0x00,
                        0x22,0xE5,0xB7,0xD2,0xB6,0xC0]),
             bytes([0x22,0xA4,code8['T'],code8['U'],code8['R'],code8['N'],0x00,
                    0x22,0xE5,code8['W'],code8['H'],code8['O'],code8['?']]))
script_patch(fb, bytes([0x22,0x86,0xDE,0x00,
                        0x22,0xA4,0x8A,0x9D,0x83,0xE8]),
             bytes([0x22,0x86,0xFE,0x00,
                    0x22,0xA4,code8['H'],code8['C'],code8['P'],0xFE]))
# Lesson continue/"shall we learn?" choice: YES / NO (block 10 at $E761).
script_patch(fb, bytes([0x22,0x65,0xCA,0xFE,0xB2,0x00]),
             bytes([0x22,0x65,code8['Y'],code8['E'],code8['S'],0x00]))
script_patch(fb, bytes([0x22,0xC4,0xFE,0xB2,0xB2,0xB4,0x00]),
             bytes([0x22,0xC4,0xFE,code8['N'],code8['O'],0xFE,0x00]))

# --- ADVANCED 10 lesson PTS-box titles (blocks 41..45, 47..51 in $EA38..$EA87) ---
adv_pts_blocks = {
    51: encode_script_block([(0x2263, _t('ATARI', code8))]),
    50: encode_script_block([(0x2264, _t('TAKE', code8))]),
    49: encode_script_block([(0x2263, _t('LADDER', code8))]),
    48: encode_script_block([(0x2264, _t('NET', code8))]),
    47: encode_script_block([(0x2263, _t('TRAP', code8)), (0x22A3, _t('SNAP', code8))]),
    45: encode_script_block([(0x2264, _t('LINK', code8))]),
    44: encode_script_block([(0x2264, _t('CUT', code8))]),
    43: encode_script_block([(0x2264, _t('LIFE', code8))]),
    42: encode_script_block([(0x2263, _t('DEATH', code8))]),
    41: encode_script_block([(0x2265, _t('KO', code8))]),
}
_used_adv_pts = pack_script_region(fb, 0xEA38, 0xEA87, adv_pts_blocks)
print('ADVANCED PTS blocks packed:', _used_adv_pts, '/', 0xEA87 - 0xEA38, 'bytes')

# --- Study-course results screen 16 runtime blocks (blocks 53..68 in $EADA..$EC55) ---
def _verdict_block(word, col):
    top = bytes(t for ch in word for t in verdict16_codes[ch][:2])
    bot = bytes(t for ch in word for t in verdict16_codes[ch][2:])
    return encode_script_block([(0x2000 + 22 * 32 + col, top),
                                (0x2000 + 23 * 32 + col, bot)])

def _para_block(lines, start_row=14, col=5):
    return encode_script_block([(0x2000 + (start_row + 2 * i) * 32 + col,
                                 _t(line, lesson_codes))
                                for i, line in enumerate(lines)])

scr16_blocks = {
    # 4 left-page comments (horizontal, cols 5..14, rows 14..21)
    53: _para_block(['TAKE YOUR', 'TIME AND', 'TRY AGAIN!']),
    54: _para_block(['SO CLOSE!', 'YOU WILL', 'PASS NEXT', 'TIME!']),
    55: _para_block(['GREAT JOB!', 'KEEP THIS', 'UP NEXT', 'TIME TOO!']),
    56: _para_block(['PERFECT!', 'A FLAWLESS', 'SCORE!']),
    # 10 topic titles under TOPICS (row 6, centered in cols 18..28)
    67: encode_script_block([(0x2000 + 6 * 32 + 21, _t('ATARI', lesson_codes))]),
    66: encode_script_block([(0x2000 + 6 * 32 + 20, _t('CAPTURE', lesson_codes))]),
    65: encode_script_block([(0x2000 + 6 * 32 + 20, _t('LADDER', lesson_codes))]),
    64: encode_script_block([(0x2000 + 6 * 32 + 22, _t('NET', lesson_codes))]),
    63: encode_script_block([(0x2000 + 6 * 32 + 19, _t('SNAPBACK', lesson_codes))]),
    61: encode_script_block([(0x2000 + 6 * 32 + 20, _t('CONNECT', lesson_codes))]),
    60: encode_script_block([(0x2000 + 6 * 32 + 22, _t('CUT', lesson_codes))]),
    59: encode_script_block([(0x2000 + 6 * 32 + 21, _t('LIFE', lesson_codes))]),
    58: encode_script_block([(0x2000 + 6 * 32 + 21, _t('DEATH', lesson_codes))]),
    57: encode_script_block([(0x2000 + 6 * 32 + 22, _t('KO', lesson_codes))]),
    # Red 16x16 verdicts: PASS! (blk 62) and FAIL! (blk 68)
    62: _verdict_block('PASS!', 18),
    68: _verdict_block('FAIL!', 18),
}
_used_scr16 = pack_script_region(fb, 0xEADA, 0xEC55, scr16_blocks)
print('Screen 16 runtime blocks packed:', _used_scr16, '/', 0xEC55 - 0xEADA, 'bytes')

# --- PLAY / Review / Scoring / Victory-Defeat runtime blocks (69..108 in $EC55..$F1B1) ---
# Preserve bell-stand blocks 102 ($F14F) and 103 ($F16A) verbatim so clock/bell stays intact!
_orig_blk102 = bytes(fb[0x314F:0x316A])
_orig_blk103 = bytes(fb[0x316A:0x3185])
_orig_blk93  = bytes(fb[0x3019:0x301D])  # $230E: $FC (".5" half-point)
_orig_blk95  = bytes(fb[0x3022:0x302B])  # clear row 6 cols 3-8
_orig_blk108 = bytes(fb[0x319B:0x31B1])  # clear message line 2

def _b14(text): return _t(text, codes1b)
def _b14_4(text): return _t(text.ljust(4)[:4], codes1b)
BLANK4 = b'\xFE\xFE\xFE\xFE'
BLANK6 = b'\xFE' * 6
BLANK16 = b'\xFE' * 16

def _play_menu(items):
    runs = []
    for i, item in enumerate(items):
        runs.append((0x2000 + (13 + 2 * i) * 32 + 4, _b14_4(item)))
        runs.append((0x2000 + (14 + 2 * i) * 32 + 4, BLANK4))
    return runs

play_blocks = {
    # 69: 4-item PLAY menu
    69: encode_script_block(_play_menu(('PLAY', 'LAND', 'END', 'QUIT'))),
    # 70: Music menu in PLAY
    70: encode_script_block([
        (0x21A4, BLANK4), (0x21C4, _b14_4('TUNE')),
        (0x21E4, BLANK4), (0x2204, _b14_4(' YES')),
        (0x2224, BLANK4), (0x2244, _b14_4(' NO ')),
        (0x2264, BLANK4), (0x2284, BLANK4),
    ]),
    # 71: Trial-move menu (LAND / END) + status bar
    71: encode_script_block(_play_menu(('LAND', 'END')) + [
        (0x230C, _b14('TRIAL MOVE MODE.')),
    ]),
    # 72: Territory view menu (PLAY / END) + score header (keep $E6/$E7 stone icons at col 20!)
    72: encode_script_block(_play_menu(('PLAY', 'END')) + [
        (0x230C, _b14('LAND:   ') + bytes([0xE6, 0xFB, 0xFE, 0xFE])),
        (0x2354, bytes([0xE7, 0xFA, 0xFE, 0xFE])),
    ]),
    # 73: Time up! [BK/WH] WINS.
    73: encode_script_block([
        (0x230C, _b14('TIME UP!        ')),
        (0x234E, _b14(' WINS.    ')),
    ]),
    # 74: Resigned! [BK/WH] WINS.
    74: encode_script_block([
        (0x230C, _b14('RESIGNED!       ')),
        (0x234E, _b14(' WINS.    ')),
    ]),
    # 75: Entering scoring
    75: encode_script_block([
        (0x230C, _b14('SCORING GAME... ')),
    ]),
    # 76: Dead stone confirm: YES / NO + IS THIS STONE / DEAD?
    76: encode_script_block([
        (0x21A4, BLANK4), (0x21C4, _b14_4(' YES')),
        (0x2205, _b14('NO  ')),
        (0x230C, _b14('IS THIS STONE   ')),
        (0x234C, _b14('DEAD?           ')),
    ]),
    # 77: Are there dead stones?
    77: encode_script_block([
        (0x230C, _b14('ARE THERE ANY   ')),
        (0x234C, _b14('DEAD STONES?    ')),
    ]),
    # 78: Select dead stones (DONE button)
    78: encode_script_block([
        (0x21C5, _b14('DONE')), (0x2205, BLANK4),
        (0x230C, _b14('SELECT DEAD     ')),
        (0x234C, _b14('STONES.         ')),
    ]),
    # 79: Final score banner (cols 12-14 hold numeric margin + optional .5 from blk 93)
    79: encode_script_block([
        (0x21C5, BLANK4), (0x2205, BLANK4),
        (0x230C, _b14('   PTS MARGIN   ')),
        (0x234C, _b14('   WINS.        ')),
    ]),
    # 80: Review mode main menu + header + status
    80: encode_script_block([
        (0x2163, _b14(' REVW ')), (0x2183, BLANK6),
    ] + _play_menu(('TRY', 'LAND', 'PLAY', 'END')) + [
        (0x230C, _b14('REVIEW MODE.    ')),
        (0x2354, BLANK6),
    ]),
    # 81: Music menu in Review mode
    81: encode_script_block([
        (0x2163, BLANK6), (0x2183, BLANK6),
        (0x21A4, BLANK4), (0x21C4, _b14_4('TUNE')),
        (0x21E4, BLANK4), (0x2204, _b14_4(' YES')),
        (0x2224, BLANK4), (0x2244, _b14_4(' NO ')),
        (0x2264, BLANK4), (0x2284, BLANK4),
    ]),
    # 82: Trial move in Review mode
    82: encode_script_block([
        (0x2163, _b14(' END  ')), (0x2183, BLANK6),
    ] + _play_menu(('', '', '', '')) + [
        (0x230C, _b14('TRIAL MOVE MODE.')),
    ]),
    # 83: Territory view in Review mode
    83: encode_script_block([
        (0x2163, _b14(' END  ')), (0x2183, BLANK6),
    ] + _play_menu(('', '', '', '')) + [
        (0x230C, _b14('LAND:   ') + bytes([0xE6, 0xFB, 0xFE, 0xFE])),
        (0x2354, bytes([0xE7, 0xFA, 0xFE, 0xFE])),
    ]),
    # 84-90: Top-box status banners (keep cols 4-7 only so col 3 MOVE & col 8 TIME survive!)
    84: encode_script_block([(0x2084, _b14('BLK '))]),
    85: encode_script_block([(0x2084, _b14('WHT '))]),
    86: encode_script_block([(0x2084, BLANK4), (0x20A4, _b14('TURN'))]),
    87: encode_script_block([(0x2084, _b14('UNDO')), (0x20A4, BLANK4)]),
    88: encode_script_block([(0x2084, _b14('FOUL')), (0x20A4, BLANK4)]),
    89: encode_script_block([(0x2084, _b14('OVER')), (0x20A4, BLANK4)]),
    90: encode_script_block([(0x2084, BLANK4), (0x20A4, BLANK4)]),
    # 91-94: Score/result word inserts (BK / WH / .5 / LOSE)
    91: encode_script_block([(0x234C, _b14('BK'))]),
    92: encode_script_block([(0x234C, _b14('WH'))]),
    93: _orig_blk93,
    94: encode_script_block([(0x234F, _b14('LOSE'))]),
    95: _orig_blk95,
    # 96-97: 2-Player Victory banners on Screen 8/9 (uses CHR bank 13 codes13!)
    96: encode_script_block([(0x2000 + 18 * 32 + 12, _t('1P WINS!', codes13))]),
    97: encode_script_block([(0x2000 + 18 * 32 + 12, _t('2P WINS!', codes13))]),
    # 98-100: CPU resignation requests (YES / NO in left menu + message bar)
    98: encode_script_block([
        (0x21C5, _b14('YES ')), (0x2205, _b14('NO  ')),
        (0x230C, _b14('NO CHANCE LEFT. ')),
        (0x234C, _b14('MAY I RESIGN?   ')),
    ]),
    99: encode_script_block([
        (0x21C5, _b14('YES ')), (0x2205, _b14('NO  ')),
        (0x230C, _b14('I CANNOT WIN.   ')),
        (0x234C, _b14('MAY I RESIGN?   ')),
    ]),
    100: encode_script_block([
        (0x21C5, _b14('YES ')), (0x2205, _b14('NO  ')),
        (0x230C, _b14('NO HOPE TO WIN. ')),
        (0x234C, _b14('I MUST RESIGN.  ')),
    ]),
    # 101: CPU thinking ("おまちください。")
    101: encode_script_block([
        (0x230C, _b14('PLEASE WAIT...  ')),
        (0x234C, BLANK16),
    ]),
    102: _orig_blk102,
    103: _orig_blk103,
    # 106-108: Too many stones messages
    106: encode_script_block([
        (0x230C, _b14('TOO MANY STONES.')),
        (0x234C, _b14('SCORING GAME... ')),
    ]),
    107: encode_script_block([
        (0x234C, _b14('TOO MANY STONES.')),
    ]),
    108: _orig_blk108,
}
_used_play = pack_script_region(fb, 0xEC55, 0xF1B1, play_blocks)
print('PLAY runtime blocks packed:', _used_play, '/', 0xF1B1 - 0xEC55, 'bytes')


# ---------------------------------------------------------- TEST feedback
# The TEST presents 20 of 300 questions.  The starting question index is not
# fixed (it comes from the saved rank / course), so *any* of the 300x3 answer
# messages can be shown - the old per-address patch covered only the single
# 20-question path the emulator happened to take, which is why Japanese
# feedback kept showing up on other runs (usually with an English tail glued
# on through a 0x0A link).
#
# Bank 5 holds a 900-entry pointer table at $8540 (6 bytes per question:
# answer A, B, C) into the text region that starts at $8C48.  Repack the
# whole region in English and rebuild the table.  Several table entries point
# into the middle of another message (the original data shares suffixes), so
# each entry is resolved to the start of the message containing it; every
# entry then gets a self-contained English line.
def enc5(text):
    """Encode a message-bar line for CHR bank 8.

    Tile 0x20 is a solid block in this font, so blanks must use 0xFE.
    "\\n" emits 0x00, the message box's line break.
    """
    out = []
    for ch in text.upper():
        if ch == '\n':
            out.append(0x00)
        elif ch == ' ':
            out.append(0xFE)
        elif ch in CHR8_MAP:
            out.append(CHR8_MAP[ch])
        else:
            raise SystemExit('bad feedback char: ' + repr(ch))
    return bytes(out)

FEEDBACK_TABLE = 0x8540
FEEDBACK_TEXT = 0x8C48
FEEDBACK_ENTRIES = (FEEDBACK_TEXT - FEEDBACK_TABLE) // 2      # 900

b5 = banks[5]
orig_b5 = bytes(b5)

def _fb_word(off):
    return orig_b5[off] | (orig_b5[off + 1] << 8)

fb_ptr = [_fb_word(FEEDBACK_TABLE - 0x8000 + 2 * i)
          for i in range(FEEDBACK_ENTRIES)]
assert all(FEEDBACK_TEXT <= a < 0xC000 for a in fb_ptr), 'bad feedback pointer'

def _fb_base(addr):
    off = addr - 0x8000
    while off > (FEEDBACK_TEXT - 0x8000) and orig_b5[off - 1] != 0xFF:
        off -= 1
    return 0x8000 + off

fb_base = [_fb_base(a) for a in fb_ptr]
fb_bases = sorted(set(fb_base))
assert set(fb_bases) == set(FEEDBACK_EN), (
    'tools/feedback_en.py is out of date, diff: '
    + str(sorted(hex(a) for a in set(fb_bases) ^ set(FEEDBACK_EN))))

pos = FEEDBACK_TEXT - 0x8000
fb_enc = {}
fb_addr = {}
for a in fb_bases:
    enc = enc5(FEEDBACK_EN[a])
    lines = FEEDBACK_EN[a].split('\n')
    assert len(lines) <= 2 and all(len(x) <= 23 for x in lines), (
        hex(a), 'line too wide for the message box', FEEDBACK_EN[a])
    if enc not in fb_enc:
        fb_enc[enc] = 0x8000 + pos
        b5[pos:pos + len(enc)] = enc
        b5[pos + len(enc)] = 0xFF
        pos += len(enc) + 1
    fb_addr[a] = fb_enc[enc]
assert pos <= 0x4000, (pos, 'English feedback does not fit in bank 5')
b5[pos:0x4000] = b'\xFF' * (0x4000 - pos)
for i, a in enumerate(fb_base):
    o = FEEDBACK_TABLE - 0x8000 + 2 * i
    b5[o] = fb_addr[a] & 0xFF
    b5[o + 1] = fb_addr[a] >> 8
print('feedback:', len(fb_bases), 'messages,', len(fb_enc), 'unique,',
      pos - (FEEDBACK_TEXT - 0x8000), 'bytes')

# Translate every bank-3 quiz/explanation string in place.  The strings
# are addressed directly by several pointer tables, so keeping every
# original start address avoids touching those tables.  Each English
# version is checked against the original byte budget.
quiz = json.load(open(os.path.join(HERE, 'quiz_en.json')))
for qi, qe in enumerate(quiz):
    qa = qe['addr']
    off = qa - 0x8000
    j = off
    while j < 0x4000 and b3[j] != 0xFF:
        j += 1
    cap = j - off
    enc = b'\x00'.join(encode(ln) for ln in BANK3_EN[qi].split('\n'))
    assert len(enc) <= cap, (qi, hex(qa), len(enc), cap, BANK3_EN[qi])
    # Terminate immediately.  The reader ignores bytes after the first
    # 0xFF; padding to the original length used to draw spaces past the
    # 24-cell question box and over the border on long entries (Q10/Q20).
    b3[off:off + len(enc)] = enc
    b3[off + len(enc)] = 0xFF
    b3[off + len(enc) + 1:off + cap + 1] = b'\xFF' * (cap - len(enc))

# Some entries of the 300-question table in the fixed bank ($FD40) point into
# the middle of another prompt, because the original data shares suffixes.
# After translation those aliases render as fragments (".", "NO GOOD.",
# "LED.", ...), so give every such entry a dedicated English prompt placed in
# bank 3's free 0xFF padding and repoint the table entry.
question_fix = {
    0xABA5: 'USE LIBERTY SHORTAGE.',
    0xABE0: 'USE A SACRIFICE.',
    0xB173: 'KEY ATTACK OR DEFENSE?',
    0xB304: 'STOP WHITE APPROACHING.',
    0xB394: 'CAPTURE THREE STONES.',
    0xB40A: 'CAPTURE FOUR STONES.',
    0xB561: 'OIOTOSHI CAPTURES IT.',
    0xB54B: 'CAPTURE 2 WHITE STONES.',
    0xBE22: 'PLAY A NATURAL MOVE.',
    0xA872: 'HOW TO CONNECT.',
}

# Allocate dedicated `question_fix` prompts in the unused tail bytes of
# recompressed screen slots in Bank 3 (after each screen's 0x00 RLE end).
_b3_pools = []
for _slo, _shi in ((0x1256, 0x148D), (0x148D, 0x16F0), (0x16F0, 0x193A),
                   (0x193A, 0x1B73), (0x1B73, 0x1DB5)):
    _, _send = make_book.decompress(b3, _slo)
    if _send < _shi:
        _b3_pools.append([_send, _shi])

def _b3_alloc(enc):
    """Place a prompt string (+ 0xFF terminator) in free Bank 3 space."""
    need = len(enc) + 1
    for pool in _b3_pools:
        if pool[1] - pool[0] >= need:
            off = pool[0]
            b3[off:off + len(enc)] = enc
            b3[off + len(enc)] = 0xFF
            pool[0] += need
            return 0x8000 + off
    raise SystemExit('no free space in bank 3 for question prompt')

QTAB = 0x3D40          # $FD40 in the fixed bank
qtab = [banks[7][QTAB + 2 * i] | (banks[7][QTAB + 2 * i + 1] << 8)
        for i in range(300)]
new_qaddr = {a: _b3_alloc(encode(txt)) for a, txt in question_fix.items()}
assert len(set(new_qaddr.values())) == len(new_qaddr)
for i, a in enumerate(qtab):
    if a in new_qaddr:
        off = QTAB + 2 * i
        banks[7][off] = new_qaddr[a] & 0xFF
        banks[7][off + 1] = new_qaddr[a] >> 8

# ------------------------------------------------ ADVANCED & Study-Course Drills
# Pack the 167 translated ADVANCED lesson messages into PRG bank 8 (repointing
# fixed-bank table $F3A7..$F4F4) and the 100 drill prompts + 98 drill feedbacks
# into PRG bank 9 (repointing fixed-bank tables $F5B9..$F680 and $F4F5..$F5B8).
# Original banks 2 and 6 keep their board/script data 100% untouched.
def _pack_msg_bank(msg_groups):
    buf = bytearray(b'\xFF' * 16384)
    pos = 0
    dedup = {}
    ptrs = []
    for lines in msg_groups:
        assert 1 <= len(lines) <= 2, lines
        assert all(1 <= len(ln) <= 26 for ln in lines), lines
        enc = b'\x00'.join(encode(ln) for ln in lines) + b'\xFF'
        if enc not in dedup:
            assert pos + len(enc) <= 16384, 'PRG text bank overflow'
            dedup[enc] = 0x8000 + pos
            buf[pos:pos + len(enc)] = enc
            pos += len(enc)
        ptrs.append(dedup[enc])
    return buf, ptrs, pos

adv_bank, adv_ptrs, adv_bytes = _pack_msg_bank(ADV_MESSAGES)
drill_bank, drill_all_ptrs, drill_bytes = _pack_msg_bank(DRILL_PROMPTS + DRILL_FEEDBACKS)
drill_prompt_ptrs = drill_all_ptrs[:len(DRILL_PROMPTS)]
drill_fb_ptrs = drill_all_ptrs[len(DRILL_PROMPTS):]
print(f'ADVANCED bank 8: {len(adv_ptrs)} msgs, {adv_bytes} bytes')
print(f'DRILL    bank 9: {len(drill_prompt_ptrs)} prompts + {len(drill_fb_ptrs)} feedbacks, {drill_bytes} bytes')

for i, ptr in enumerate(adv_ptrs):
    o = 0x33A7 + 2 * i
    fb[o] = ptr & 0xFF
    fb[o + 1] = ptr >> 8
for i, ptr in enumerate(drill_fb_ptrs):
    o = 0x34F5 + 2 * i
    fb[o] = ptr & 0xFF
    fb[o + 1] = ptr >> 8
for i, ptr in enumerate(drill_prompt_ptrs):
    o = 0x35B9 + 2 * i
    fb[o] = ptr & 0xFF
    fb[o + 1] = ptr >> 8

banks.append(adv_bank)    # PRG bank 8: ADVANCED lessons
banks.append(drill_bank)  # PRG bank 9: Study-course drill prompts & feedbacks
banks += [bytearray(16384) for _ in range(4)]  # PRG banks 10-13 spare
banks.append(txtbank)     # PRG bank 14: BASICS / BASICS PART 2
banks.append(banks[7])    # PRG bank 15: fixed bank mirror

chr_new = chr_ + bank8 + bank9 + bank10 + bank11 + bank12 + bank13 + bank14 + bank15
prg_new = b''.join(banks)
out = bytearray(raw[:16]) + prg_new + chr_new
out[4] = 16  # 16 x 16K PRG
out[5] = 8   # 8 x 8K CHR (16 x 4K banks)
# Patch Bank 4 ($03EE text-bank selectors):
#   $80F9: BASICS / BASICS2  (4 -> 14)
#   $82D8: ADVANCED lessons  (6 -> 8)
#   $83E0, $8408: Drill prompts (2 -> 9)
#   $89E4, $89EA: Drill feedbacks (2 / 6 -> 9)
_b4off = 16 + 4 * 16384
assert out[_b4off + 0x00F9:_b4off + 0x00FB] == bytes([0xA9, 0x04])
out[_b4off + 0x00FA] = 14
assert out[_b4off + 0x02D8:_b4off + 0x02DA] == bytes([0xA9, 0x06])
out[_b4off + 0x02D9] = 8
assert out[_b4off + 0x03E0:_b4off + 0x03E2] == bytes([0xA9, 0x02])
out[_b4off + 0x03E1] = 9
assert out[_b4off + 0x0408:_b4off + 0x040A] == bytes([0xA9, 0x02])
out[_b4off + 0x0409] = 9
assert out[_b4off + 0x09E4:_b4off + 0x09E6] == bytes([0xA0, 0x02])
out[_b4off + 0x09E5] = 9
assert out[_b4off + 0x09EA:_b4off + 0x09EC] == bytes([0xA0, 0x06])
out[_b4off + 0x09EB] = 9
# lesson screens CHR0 -> 8 (fixed bank is the last PRG bank)
fixed = 16 + 15 * 16384
for idx in (17, 18, 19, 20, 23):
    out[fixed + (0xC8C8 - 0xC000) + idx] = 8
# Book intro, menu and lesson-list pages use the English book-font bank.
for idx in (11, 12):
    out[fixed + (0xC8C8 - 0xC000) + idx] = 9
for idx in (13, 14, 15, 16):
    out[fixed + (0xC8C8 - 0xC000) + idx] = 15
# PLAY board screens (1: main, 2-4: in-play/scoring, 5: post-game review) use CHR bank 14.
for idx in (1, 2, 3, 4, 5):
    out[fixed + (0xC8C8 - 0xC000) + idx] = 14
# PLAY continue/setup screens use the English CHR bank 11.
out[fixed + (0xC8C8 - 0xC000) + 6] = 11
out[fixed + (0xC8C8 - 0xC000) + 7] = 11
# TEST intro/help screens use the English CHR bank 12; the result
# screen has its own protected-art font in bank 10.
for idx in (20, 21, 22):
    out[fixed + (0xC8C8 - 0xC000) + idx] = 12
out[fixed + (0xC8C8 - 0xC000) + 24] = 10
for idx in (8, 9, 10):
    out[fixed + (0xC8C8 - 0xC000) + idx] = 13
# Quiz question screen uses the English 8x8 font bank 8.
out[fixed + (0xC8C8 - 0xC000) + 23] = 8
# Bottom legend script ($E78B): replace "ごばんと ごいし" with "GOBAN" / "STONE".
# Start STONE at col 4 ($22E4) so its last letter stays inside the PTS box
# (col 8) and never overwrites the right border at col 9.
legend = bytes([0x0A, 0x22, 0xA4]) + _t('GOBAN', code8) + bytes([0x00, 0x22, 0xE4]) + _t('STONE', code8) + bytes([0x00])
out[fixed + 0x278B:fixed + 0x278B + len(legend)] = legend
# Mirror the same fixed-bank legend patch in bank 7 copy too.
out[16 + 7 * 16384 + 0x278B:16 + 7 * 16384 + 0x278B + len(legend)] = legend
# Also mirror CHR table in bank 7 copy for completeness.
out[16 + 7 * 16384 + 0x08C8:16 + 7 * 16384 + 0x08C8 + 25] = out[fixed + 0x08C8:fixed + 0x08C8 + 25]
open(OUT, 'wb').write(out)
print('wrote', OUT, len(out), 'bytes')