sokoban-elements 0.2.1

Parsing and writing Sokoban, Hexoban, Trioban and Octoban file formats.
Documentation
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
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
mod edges;
mod errors;
mod hexoban_board;
mod index;
mod iterator;
mod octoban_board;
mod parser;
mod sokoban_board;
mod transform;
mod trioban_board;

use std::num::NonZeroU16;

pub use edges::{HorizontalEdge, VerticalEdge};
pub use errors::{BoardSyntaxError, BoardSyntaxErrorKind};
use hexoban_board::HexobanBoardParser;
pub use iterator::GameBoardIter;
use octoban_board::OctobanBoardParser;
pub(crate) use parser::is_board_line;
use parser::{
    BoardParser, BoardPrinter, BoardRect, BoardResizer, ParsedBoard, grown, normalize_dimensions,
};
use sokoban_board::SokobanBoardParser;
pub(crate) use transform::BoardTransform;
pub use transform::{MirrorAxis, Rotation};
use trioban_board::TriobanBoardParser;

use crate::{
    Boxbox, Goal, Point2D, Pusher, Size2D, SokobanPlus, StaticBoardAnalysis, Tessellation, TileKind,
};

/// Parsed game board for some [`Tessellation`](crate::Tessellation).
///
/// Encapsulates game board as 2D matrix of [`TileKind`](crate::TileKind).
///
/// - coordinate system origin `(0, 0)` is at the top left of board
/// - `X` axis points from left to right
/// - `Y` axis points from top to down
///
/// `GameBoard` is end result of parsing and editing game puzzles. As such it is not optimized data
/// structure playing the game, implementing game engines or game solvers. `GameBoard` is meant to
/// be used only as input for these uses and will have to be converted into more suitable data
/// structure.
///
/// `GameBoard` doesn't place any restrictions on it's width, height or on number of pushers, boxes
/// and goals. When implementing game engines or game solvers, you'll want to validate parsed
/// `GameBoard` against concrete engine or solver requirements.
///
/// [`BoxID`](crate::BoxID), [`GoalID`](crate::GoalID), [`PusherID`](crate::PusherID) and
/// [`PlusID`](crate::PlusID) ** do restrict** numeric IDs that they can represent. Having
/// `GameBoard` with more pushers, boxes or goals than these can represent is possible, but you will
/// not be able to represent ids of it's pieces. Again and by design, there is no mechanism in
/// `GameBoard` to prevent this situation.
///
/// `GameBoard` supports `Index` and `IndexMut` for `(x, y)`, `Point2D` and linear `usize`.
///
/// `GameBoard` supports `iter()` yielding row-major `((x, y), TileKind)` pairs.
///
/// Depending on [`Tessellation`], a board position has related [`TileShape`](crate::TileShape) that
/// can be calculated via
/// [`Tessellation::tile_shape_from_pos(x, y)`](Tessellation::tile_shape_from_pos) or via
/// [`Point2D::tile_shape(tessellation)`](Point2D::tile_shape)
///
/// # Examples
///
/// ```rust
/// use sokoban_elements::*;
///
/// # fn main() -> Result<(), BoardSyntaxError> {
/// let board_text = [
///     "    #####",
///     "    #   #",
///     "    #$  #",
///     "  ###  $##",
///     "  #  $ $ #",
///     "### # ## #   ######",
///     "#   # ## #####  ..#",
///     "# $  $          ..#",
///     "##### ### #@##  ..#",
///     "    #     #########",
///     "    #######",
/// ]
/// .join("\n");
///
/// let mut board = GameBoard::parsed(&board_text, Tessellation::Sokoban)?;
///
/// assert_eq!(board.width(), 19);
/// assert_eq!(board.height(), 11);
///
/// // tiles are read by (x, y)...
/// assert_eq!(board[(4, 0)], TileKind::Wall);
///
/// // ... or by linear board position: y * width + x
/// let position: usize = 4;
/// assert_eq!(board[position], TileKind::Wall);
///
/// // short rows are padded with floor tiles
/// assert_eq!(board[(18, 0)], TileKind::Floor);
///
/// // tiles are writable
/// board[(4, 0)] = TileKind::Floor;
/// assert_eq!(board[(4, 0)], TileKind::Floor);
///
/// // iteration is row major over ((x, y), tile) pairs
/// assert_eq!(board.iter().count(), board.width() * board.height());
/// assert_eq!(board.iter().next(), Some(((0, 0), TileKind::Floor)));
///
/// # Ok(())
/// # }
/// ```
///
/// # Board size
///
/// Board data is always width-normalized: all rows have exactly [`width()`](GameBoard::width())
/// tiles. Rows shorter than board width are padded with
/// [`TileKind::Floor`](crate::TileKind::Floor). Parsing, resizing, rotation and mirroring ensure
/// that this always holds. `Index<(usize, usize)>` and `Index<Point2D>` would've panicked for
/// perfectly valid board coordinates, if the rows were ragged. `Index<usize>` wouldn't even panic -
/// in case of ragged rows it would silently return wrong board tile.
///
/// A board with no columns and or no rows is empty: [`width()`](GameBoard::width()) is zero if and
/// only if [`height()`](GameBoard::height()) is zero. Constructing or editing a board in a way that
/// would leave it with rows of zero length silently produces the empty board instead. There is no
/// error for this.
///
/// These rules is what makes indexing board position well defined.
///
/// Resizing edits one edge at a time, so callers control operation order. Additions to a non-empty
/// board apply `count` exactly, and methods return how many lines were applied.
///
/// **Removals saturate.** `remove_rows(Top, 42)` on a 11-row board removes 11, it is not an error.
/// In that case we'd removed all the rows from the board, so there are no columns left either.
///
/// The result of chaining board edge edits depends on order of calls. Any individual step may
/// collapse the board to size zero (because removals saturate).
///
/// Once edge editing empties a board, the one-edge-at-a-time methods cannot grow it back: there are
/// no rows to add columns to, and rows added to a board with no columns are of zero length, which
/// is the empty board again. Use [`grow()`](GameBoard::grow()) for that.
///
/// `Top` and `Left` resizing shifts existing content. To compensate what would otherwise be a break
/// in tile geometry, `GameBoard` adds or removes one padding line in perpendicular axis. This means
/// that `Top` and `Left` resizing may have side effect of changing **both** board dimensions. This
/// depends on concrete `Tessellation`:
///
/// - `add_rows(Top, 1)` on a `Trioban` or `Octoban` board also adds a left column;
///   `add_columns(Left,1)` also adds a top row.
/// - `Hexoban` needs it on odd `Top` counts when the retained board spans both row parities. Even
///   counts need nothing
///
/// `Bottom` and `Right` resizing never adds perpendicular padding.
///
/// Each resizing count is one batched shift. Adding two `Top` rows to `Trioban` adds no padding,
/// while two separate one-row calls each add a column.
///
/// If you need to tighten the resulting board after this padding, call
/// [`trim()`](GameBoard::trim()) explicitly.
///
/// # Transformations
///
/// [`rotate()`](GameBoard::rotate()) applies one tessellation-specific step; see
/// [`Tessellation::rotation_step_degrees()`]. A transform may add one row or column because its
/// result must be re-anchored with a rigid motion of the tiling; integer translation periods are
/// exposed by [`Tessellation::translation_period()`]. A full turn likewise takes four steps for
/// Sokoban and Octoban, and six for Hexoban and Trioban. Rotation keeps its complete bounding box;
/// call [`trim()`](GameBoard::trim()) separately when a tight board is wanted.
///
/// Mirroring twice restores the original content, but may retain padding added by re-anchoring.
///
/// # Normalization and enclosing
///
/// [`grow()`](GameBoard::grow()) and [`enclose()`](GameBoard::enclose()) are the two resizing
/// methods that are not per-edge, because neither takes an edge to work on: `grow()` is told a
/// size, and `enclose()` derives the edges it must grow from where the play area reaches.
///
/// [`enclose()`](GameBoard::enclose()) walls the play area in, so it is the operation that makes a
/// board "closed".
///
/// [`normalize()`](GameBoard::normalize()) does **not** produce a closed board. A play area that
/// reaches the board edge is confined by the edge, not by a wall, and no wall is invented for it.
///
/// # Edits invalidate emergent types and properties
///
/// Editing, resizing, mirroring and rotation invalidates everything keyed to position:
///
/// - [`BoxID`](crate::BoxID), [`GoalID`](crate::GoalID), and [`PusherID`](crate::PusherID) are
///   reassigned by scanning the edited board in row-major order
/// - [`SokobanPlus`](crate::SokobanPlus) is keyed to those IDs and is silently invalidated.
/// - [`SavedGame`](crate::SavedGame) moves are directional and no longer describe the transformed
///   board. In particular, Trioban direction changes depend on each triangle's orientation and
///   cannot be repaired by substituting direction characters.
/// - Zobrist hashes of boards (game engine feature) are position-keyed and do not survive editing.
///
/// Invalidation is natural consequences of how all of above types are defined: they need a stable
/// board configuration to make any sense. Important thing to have in mind when editing the board:
/// finish the design before assigning ie. `Sokoban+` to it.
///
/// # Serde
///
/// With the `serde` feature, `GameBoard` is a two field map of the printed board and the
/// [`Tessellation`] needed to parse it back:
///
/// ```json
/// { "tessellation": "Sokoban", "board": "#####\n#@$.#\n#####" }
/// ```
///
/// Deserialization goes through [`parsed()`](GameBoard::parsed()), so a document can never produce
/// a board that violates the width-normalization invariant. Unknown fields are rejected. The board
/// text is accepted in any form [`parsed()`](GameBoard::parsed()) accepts, run-length encoding
/// included, but is always written out uncompressed with visible floors.
///
/// ```rust
/// use sokoban_elements::*;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # #[cfg(feature = "serde")] {
/// #[rustfmt::skip]
/// let board_text = [
///     "#####",
///     "#@$.#",
///     "#####",
/// ]
/// .join("\n");
///
/// let board = GameBoard::parsed(&board_text, Tessellation::Sokoban)?;
///
/// let json = serde_json::to_string(&board)?;
/// assert_eq!(serde_json::from_str::<GameBoard>(&json)?, board);
/// # }
/// #     Ok(())
/// # }
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GameBoard {
    data:         ParsedBoard,
    tessellation: Tessellation,
}

impl GameBoard {
    /// Constructs blank board of given size, all of it's tiles being
    /// [`TileKind::Floor`](crate::TileKind::Floor).
    ///
    /// A board with no columns is the empty board: if either `width` or `height` is zero, both
    /// [`width()`](GameBoard::width()) and [`height()`](GameBoard::height()) of constructed board
    /// are zero.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use sokoban_elements::*;
    ///
    /// let board = GameBoard::new(0, 5, Tessellation::Sokoban);
    ///
    /// assert_eq!(board.width(), 0);
    /// assert_eq!(board.height(), 0);
    /// ```
    pub fn new(width: usize, height: usize, tessellation: Tessellation) -> Self {
        if width == 0 || height == 0 {
            return Self {
                data: ParsedBoard::new(),
                tessellation,
            };
        }

        let row = vec![TileKind::Floor; width];
        Self {
            data: std::iter::repeat_n(row, height).collect(),
            tessellation,
        }
    }

    pub fn tessellation(&self) -> Tessellation { self.tessellation }

    /// Parses board string in context of given [`Tessellation`].
    ///
    /// # Examples
    ///
    /// Constructing `GameBoard` from text:
    ///
    /// ```rust
    /// use sokoban_elements::*;
    ///
    /// # fn main() -> Result<(), BoardSyntaxError> {
    /// let board_text = [
    ///     "    #####",
    ///     "    #   #",
    ///     "    #$  #",
    ///     "  ###  $##",
    ///     "  #  $ $ #",
    ///     "### # ## #   ######",
    ///     "#   # ## #####  ..#",
    ///     "# $  $          ..#",
    ///     "##### ### #@##  ..#",
    ///     "    #     #########",
    ///     "    #######",
    /// ]
    /// .join("\n");
    ///
    /// let board = GameBoard::parsed(&board_text, Tessellation::Sokoban)?;
    /// #     Ok(())
    /// # }
    /// ```
    ///
    /// # Grammar
    ///
    /// Game board strings use following characters:
    ///
    /// | tile           | char          |
    /// | -------------- | ------------- |
    /// | Wall           | '#'           |
    /// | Pusher         | 'p', '@', 'm' |
    /// | Pusher on goal | 'P', '+', 'M' |
    /// | Box            | 'b', '$'      |
    /// | Goal           | '.' , 'o'     |
    /// | Floor          | ' ', '-', '_' |
    ///
    /// Game board strings mostly follow
    /// [SokobanYASC](https://sourceforge.net/projects/sokobanyasc/) specification:
    ///
    /// ```sok_file_format
    /// ::::::::::::::::::::::::::: Board ::::::::::::::::::::::::::
    /// ::                                                        ::
    /// :: Remarks:                                               ::
    /// ::                                                        ::
    /// ::   The first and the last non-empty square in each row  ::
    /// ::   must be a wall or a box on a goal. An empty interior ::
    /// ::   row is written with at least one "-" or "_".         ::
    /// ::                                                        ::
    /// ::   Boards may be run-length encoded (RLE), e.g.,        ::
    /// ::   "###----p.#" may be encoded as "3#4-p.#", and        ::
    /// ::   "#-#-#-##-#-#-#" may be encoded as "2(3(#-)#)".      ::
    /// ::   A row cannot be split over multiple lines.           ::
    /// ::                                                        ::
    /// ::   Rows may be combined on a single line by using "|"   ::
    /// ::   as a row separator, e.g., "--3#|3#-#|#pb.#|5#".      ::
    /// ::   A "|" at the end of a line is optional and may be    ::
    /// ::   omitted.                                             ::
    /// ```
    ///
    /// - [RLE grammar](https://raw.githubusercontent.com/tadams42/sokoban-elements/main/crates/sokoban-elements/doc/img/rle_grammar.svg)
    pub fn parsed(
        printed_board: &str, tessellation: Tessellation,
    ) -> Result<Self, BoardSyntaxError> {
        let mut data = match tessellation {
            Tessellation::Sokoban => SokobanBoardParser::parse(printed_board),
            Tessellation::Hexoban => HexobanBoardParser::parse(printed_board),
            Tessellation::Trioban => TriobanBoardParser::parse(printed_board),
            Tessellation::Octoban => OctobanBoardParser::parse(printed_board),
        }?;
        normalize_dimensions(&mut data);

        Ok(Self { data, tessellation })
    }

    /// Constructs board from row major slice of [`TileKind`](crate::TileKind).
    ///
    /// A board with no columns is the empty board: if either `width` or `height` is zero, `data`
    /// must be empty and constructed board is the empty board.
    ///
    /// # Errors
    ///
    /// [`InputSizeNotMatchedByDeclaredSize`](crate::BoardSyntaxErrorKind::InputSizeNotMatchedByDeclaredSize)
    /// when length of `data` is not exactly `width * height`. Sizes too large to be represented
    /// are reported the same way.
    pub fn parsed_from_tiles(
        data: &[TileKind], width: usize, height: usize, tessellation: Tessellation,
    ) -> Result<Self, BoardSyntaxError> {
        if width.checked_mul(height) != Some(data.len()) {
            return Err(BoardSyntaxError::new(
                BoardSyntaxErrorKind::InputSizeNotMatchedByDeclaredSize {
                    input:           data.len(),
                    declared_width:  width,
                    declared_height: height,
                },
            ));
        }

        // Size check above guarantees `data` is empty when either dimension is zero.
        let body: ParsedBoard = if width == 0 || height == 0 {
            ParsedBoard::new()
        } else {
            data.chunks_exact(width).map(<[TileKind]>::to_vec).collect()
        };

        Ok(Self {
            data: body,
            tessellation,
        })
    }

    pub fn printed(&self, visible_floor: bool) -> String {
        match self.tessellation {
            Tessellation::Sokoban => SokobanBoardParser::print(&self.data, visible_floor),
            Tessellation::Trioban => TriobanBoardParser::print(&self.data, visible_floor),
            Tessellation::Hexoban => HexobanBoardParser::print(&self.data, visible_floor),
            Tessellation::Octoban => OctobanBoardParser::print(&self.data, visible_floor),
        }
    }

    /// Number of board columns.
    ///
    /// Returns `0` for empty board. Board width and [`height()`](GameBoard::height()) are either
    /// both zero or both greater than zero.
    pub fn width(&self) -> usize {
        if self.data.is_empty() {
            0
        } else {
            self.data[0].len()
        }
    }

    /// Number of board rows.
    ///
    /// Returns `0` for empty board. Board height and [`width()`](GameBoard::width()) are either
    /// both zero or both greater than zero.
    pub fn height(&self) -> usize { self.data.len() }

    pub fn size(&self) -> Size2D {
        Size2D {
            width:  self.width(),
            height: self.height(),
        }
    }

    pub fn pushers_count(&self) -> usize {
        self.data
            .iter()
            .flatten()
            .filter(|&&x| x.has_pusher())
            .count()
    }

    pub fn boxes_count(&self) -> usize {
        self.data.iter().flatten().filter(|&&x| x.has_box()).count()
    }

    pub fn goals_count(&self) -> usize {
        self.data
            .iter()
            .flatten()
            .filter(|&&x| x.has_goal())
            .count()
    }

    pub fn is_blank(&self) -> bool {
        self.data
            .iter()
            .all(|row| row.iter().all(TileKind::is_empty_floor))
    }

    /// All [`Pusher`] pieces on this board, in row major order.
    ///
    /// [`PusherID`](crate::PusherID) of each piece is assigned by scanning board top to bottom and
    /// each row left to right, starting from `0`. See [`PusherID`](crate::PusherID) docs.
    ///
    /// Tile with pusher standing on goal
    /// ([`TileKind::PusherOnGoal`](crate::TileKind::PusherOnGoal)) yields both a [`Pusher`] here
    /// and a [`Goal`] in [`goals()`](GameBoard::goals()).
    ///
    /// # Errors
    ///
    /// [`TooManyPushers`](crate::BoardSyntaxErrorKind::TooManyPushers) when board has more pushers
    /// than [`PusherID`](crate::PusherID) can represent.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use sokoban_elements::*;
    ///
    /// # fn main() -> Result<(), BoardSyntaxError> {
    /// #[rustfmt::skip]
    /// let board_text = [
    ///     "#####",
    ///     "#@$.#",
    ///     "#####",
    /// ]
    /// .join("\n");
    ///
    /// let board = GameBoard::parsed(&board_text, Tessellation::Sokoban)?;
    ///
    /// let pushers = board.pushers()?;
    ///
    /// assert_eq!(pushers.len(), board.pushers_count());
    /// assert_eq!(pushers[0].id, PusherID::from(0_u8));
    /// assert_eq!((pushers[0].x, pushers[0].y), (1, 1));
    /// #     Ok(())
    /// # }
    /// ```
    pub fn pushers(&self) -> Result<Vec<Pusher>, BoardSyntaxError> {
        self.iter()
            .filter(|(_, tile)| tile.has_pusher())
            .enumerate()
            .map(|(idx, ((x, y), _))| {
                let p = StaticBoardAnalysis::build_pusher(idx, x, y)?;
                Ok(p)
            })
            .collect()
    }

    /// All [`Boxbox`] pieces on this board, in row major order.
    ///
    /// [`BoxID`](crate::BoxID) of each piece is assigned by scanning board top to bottom and each
    /// row left to right, starting from `0`. See [`BoxID`](crate::BoxID) docs.
    ///
    /// Tile with box standing on goal ([`TileKind::BoxOnGoal`](crate::TileKind::BoxOnGoal)) yields
    /// both a `Boxbox` here and a [`Goal`] in [`goals()`](GameBoard::goals()).
    ///
    /// `Sokoban+ ID` of each piece is looked up in `sokoban_plus` by assigned
    /// [`BoxID`](crate::BoxID). Without `sokoban_plus`, no box gets `Sokoban+ ID`. See
    /// [`SokobanPlus`](crate::SokobanPlus).
    ///
    /// # Errors
    ///
    /// [`TooManyBoxes`](crate::BoardSyntaxErrorKind::TooManyBoxes) when board has more boxes than
    /// [`BoxID`](crate::BoxID) can represent.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use sokoban_elements::*;
    ///
    /// # fn main() -> Result<(), BoardSyntaxError> {
    /// #[rustfmt::skip]
    /// let board_text = [
    ///     "#####",
    ///     "#@$*#",
    ///     "#####",
    /// ]
    /// .join("\n");
    ///
    /// let board = GameBoard::parsed(&board_text, Tessellation::Sokoban)?;
    ///
    /// let boxes = board.boxes(None)?;
    ///
    /// assert_eq!(boxes.len(), board.boxes_count());
    /// assert_eq!(boxes[0].id, BoxID::from(0_u8));
    /// assert_eq!((boxes[0].x, boxes[0].y), (2, 1));
    /// assert_eq!(boxes[0].plus_id, None);
    ///
    /// // box standing on goal is both a box and a goal
    /// assert_eq!((boxes[1].x, boxes[1].y), (3, 1));
    /// assert_eq!(board.goals(None)?.len(), 1);
    /// #     Ok(())
    /// # }
    /// ```
    ///
    /// Reading `Sokoban+ IDs`:
    ///
    /// ```rust
    /// use sokoban_elements::*;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// #[rustfmt::skip]
    /// let board_text = [
    ///     "#####",
    ///     "#@$*#",
    ///     "#####",
    /// ]
    /// .join("\n");
    ///
    /// let board = GameBoard::parsed(&board_text, Tessellation::Sokoban)?;
    /// let sokoban_plus = SokobanPlus::parsed("0 42", "42 0")?;
    ///
    /// let boxes = board.boxes(Some(&sokoban_plus))?;
    ///
    /// assert_eq!(boxes[0].plus_id, None);
    /// assert_eq!(boxes[1].plus_id, Some(PlusID::new(42)?));
    /// #     Ok(())
    /// # }
    /// ```
    pub fn boxes(
        &self, sokoban_plus: Option<&SokobanPlus>,
    ) -> Result<Vec<Boxbox>, BoardSyntaxError> {
        self.iter()
            .filter(|(_, tile)| tile.has_box())
            .enumerate()
            .map(|(idx, ((x, y), _))| {
                let b = StaticBoardAnalysis::build_box(idx, x, y, sokoban_plus)?;
                Ok(b)
            })
            .collect()
    }

    /// All [`Goal`] pieces on this board, in row major order.
    ///
    /// [`GoalID`](crate::GoalID) of each piece is assigned by scanning board top to bottom and each
    /// row left to right, starting from `0`. See [`GoalID`](crate::GoalID) docs.
    ///
    /// Tiles with box or pusher standing on goal
    /// ([`TileKind::BoxOnGoal`](crate::TileKind::BoxOnGoal),
    /// [`TileKind::PusherOnGoal`](crate::TileKind::PusherOnGoal)) yield a [`Goal`] here in addition
    /// to the piece standing on it.
    ///
    /// `Sokoban+ ID` of each piece is looked up in `sokoban_plus` by assigned
    /// [`GoalID`](crate::GoalID). Without `sokoban_plus`, no goal gets `Sokoban+ ID`. See
    /// [`SokobanPlus`](crate::SokobanPlus).
    ///
    /// # Errors
    ///
    /// [`TooManyGoals`](crate::BoardSyntaxErrorKind::TooManyGoals) when board has more goals than
    /// [`GoalID`](crate::GoalID) can represent.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use sokoban_elements::*;
    ///
    /// # fn main() -> Result<(), BoardSyntaxError> {
    /// #[rustfmt::skip]
    /// let board_text = [
    ///     "#####",
    ///     "#+$.#",
    ///     "#####",
    /// ]
    /// .join("\n");
    ///
    /// let board = GameBoard::parsed(&board_text, Tessellation::Sokoban)?;
    ///
    /// let goals = board.goals(None)?;
    ///
    /// assert_eq!(goals.len(), board.goals_count());
    ///
    /// // pusher standing on goal is both a pusher and a goal
    /// assert_eq!(goals[0].id, GoalID::from(0_u8));
    /// assert_eq!((goals[0].x, goals[0].y), (1, 1));
    /// assert_eq!((goals[1].x, goals[1].y), (3, 1));
    /// #     Ok(())
    /// # }
    /// ```
    pub fn goals(&self, sokoban_plus: Option<&SokobanPlus>) -> Result<Vec<Goal>, BoardSyntaxError> {
        self.iter()
            .filter(|(_, tile)| tile.has_goal())
            .enumerate()
            .map(|(idx, ((x, y), _))| {
                let g = StaticBoardAnalysis::build_goal(idx, x, y, sokoban_plus)?;
                Ok(g)
            })
            .collect()
    }

    /// Row major iterator over `((x, y), tile)` pairs of this board.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use sokoban_elements::*;
    ///
    /// let board = GameBoard::new(3, 2, Tessellation::Sokoban);
    ///
    /// let positions: Vec<(usize, usize)> = board.iter().map(|(position, _)| position).collect();
    ///
    /// assert_eq!(positions, vec![(0, 0), (1, 0), (2, 0), (0, 1), (1, 1), (2, 1)]);
    /// ```
    pub fn iter(&self) -> GameBoardIter<'_> { GameBoardIter::new(self) }

    /// Restores board data invariant after editing.
    ///
    /// Editing primitives are free to produce rows of zero length on their way to a final result;
    /// a board with no columns is the empty board. Every method editing `self.data` must call
    /// this. See `GameBoard` docs.
    fn normalize_dimensions(&mut self) { normalize_dimensions(&mut self.data); }

    fn crop(&mut self, source: BoardRect) {
        match self.tessellation {
            Tessellation::Sokoban => SokobanBoardParser::crop(&mut self.data, source),
            Tessellation::Trioban => TriobanBoardParser::crop(&mut self.data, source),
            Tessellation::Hexoban => HexobanBoardParser::crop(&mut self.data, source),
            Tessellation::Octoban => OctobanBoardParser::crop(&mut self.data, source),
        }
        self.normalize_dimensions();
    }

    /// Mirrors the board across `axis` as a rigid motion of its tessellation.
    ///
    /// [`MirrorAxis::Horizontal`] exchanges the top and bottom edges;
    /// [`MirrorAxis::Vertical`] exchanges the left and right edges. Re-anchoring may add one row or
    /// column to keep tile geometry intact.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use sokoban_elements::*;
    ///
    /// # fn main() -> Result<(), BoardSyntaxError> {
    /// let mut board = GameBoard::parsed("@$.", Tessellation::Sokoban)?;
    /// board.mirror(MirrorAxis::Vertical);
    /// assert_eq!(board.printed(false), ".$@");
    /// # Ok(())
    /// # }
    /// ```
    pub fn mirror(&mut self, axis: MirrorAxis) {
        let transform = match axis {
            MirrorAxis::Horizontal => BoardTransform::MirrorHorizontal,
            MirrorAxis::Vertical => BoardTransform::MirrorVertical,
        };
        self.data = transform::transformed(&self.data, self.tessellation, transform);
        self.normalize_dimensions();
    }

    /// Rotates the board by one natural step of its tessellation.
    ///
    /// The step is 90 degrees for Sokoban and Octoban, and 60 degrees for Hexoban and Trioban;
    /// see [`Tessellation::rotation_step_degrees()`]. Rotation keeps the complete rotated bounding
    /// box and does not trim floor-only edges.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use sokoban_elements::*;
    ///
    /// # fn main() -> Result<(), BoardSyntaxError> {
    /// #[rustfmt::skip]
    /// let board_text = [
    ///     "@",
    ///     "$",
    ///     ".",
    /// ]
    /// .join("\n");
    /// let mut board = GameBoard::parsed(&board_text, Tessellation::Sokoban)?;
    /// board.rotate(Rotation::Clockwise);
    /// assert_eq!(board.printed(false), ".$@");
    /// # Ok(())
    /// # }
    /// ```
    pub fn rotate(&mut self, rotation: Rotation) {
        let transform = match rotation {
            Rotation::Clockwise => BoardTransform::RotateClockwise,
            Rotation::CounterClockwise => BoardTransform::RotateCounterClockwise,
        };
        self.data = transform::transformed(&self.data, self.tessellation, transform);
        self.normalize_dimensions();
    }

    /// Grows the board to at least `width` columns and `height` rows, filling with
    /// [`TileKind::Floor`](crate::TileKind::Floor).
    ///
    /// Each axis is grown independently to the larger of its current and its wanted size, so a
    /// board is never shrunk: an axis already at or past its wanted size is left alone, and a call
    /// asking for no growth on either axis is a no-op.
    ///
    /// Growth is added to the Bottom and Right edges only. Existing tiles therefore keep their
    /// `(x, y)`, and no perpendicular padding line is ever added, whatever the
    /// [`Tessellation`].
    ///
    /// This is also the way back from the empty board, which the one-edge-at-a-time methods cannot
    /// grow.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::num::NonZeroU16;
    ///
    /// use sokoban_elements::*;
    ///
    /// # fn main() -> Result<(), std::num::TryFromIntError> {
    /// let mut board = GameBoard::new(3, 2, Tessellation::Sokoban);
    ///
    /// board.grow(NonZeroU16::try_from(5)?, NonZeroU16::try_from(1)?);
    ///
    /// // width grew, height was already past the wanted one and stayed
    /// assert_eq!(board.width(), 5);
    /// assert_eq!(board.height(), 2);
    ///
    /// // editing can empty a board, and growing is the way back
    /// board.remove_columns(VerticalEdge::Left, 42);
    /// assert_eq!(board.size(), Size2D::new(0, 0));
    ///
    /// board.grow(NonZeroU16::try_from(4)?, NonZeroU16::try_from(3)?);
    /// assert_eq!(board.size(), Size2D::new(4, 3));
    /// # Ok(())
    /// # }
    /// ```
    pub fn grow(&mut self, width: NonZeroU16, height: NonZeroU16) {
        let target_width = self.width().max(usize::from(width.get()));
        let target_height = self.height().max(usize::from(height.get()));

        grown(&mut self.data, target_width, target_height);
        self.normalize_dimensions();
    }

    /// Adds `count` rows of [`TileKind::Floor`](crate::TileKind::Floor) to given board edge.
    ///
    /// Returns `count` when the board is non-empty. A Top addition may also add one left padding
    /// column to preserve tile geometry.
    ///
    /// Does nothing to the empty board: a board with no columns can only grow rows of zero length,
    /// and a board with no columns is the empty board. Grow the empty board with
    /// [`grow()`](GameBoard::grow()) instead.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use sokoban_elements::*;
    ///
    /// let mut board = GameBoard::new(3, 2, Tessellation::Sokoban);
    ///
    /// board.add_rows(HorizontalEdge::Top, 2);
    ///
    /// assert_eq!(board.width(), 3);
    /// assert_eq!(board.height(), 4);
    /// ```
    pub fn add_rows(&mut self, edge: HorizontalEdge, count: usize) -> usize {
        let applied = match self.tessellation {
            Tessellation::Sokoban => SokobanBoardParser::add_rows(&mut self.data, edge, count),
            Tessellation::Trioban => TriobanBoardParser::add_rows(&mut self.data, edge, count),
            Tessellation::Hexoban => HexobanBoardParser::add_rows(&mut self.data, edge, count),
            Tessellation::Octoban => OctobanBoardParser::add_rows(&mut self.data, edge, count),
        };
        self.normalize_dimensions();
        applied
    }

    /// Removes up to `count` rows from given board edge and returns the number removed.
    ///
    /// Removal saturates at the board height. A Top removal that retains rows may also add one left
    /// padding column to preserve tile geometry.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use sokoban_elements::*;
    ///
    /// let mut board = GameBoard::new(3, 2, Tessellation::Sokoban);
    ///
    /// board.remove_rows(HorizontalEdge::Bottom, 1);
    /// assert_eq!(board.height(), 1);
    ///
    /// // removing more rows than there are empties the board
    /// board.remove_rows(HorizontalEdge::Bottom, 42);
    /// assert_eq!(board.width(), 0);
    /// assert_eq!(board.height(), 0);
    /// ```
    pub fn remove_rows(&mut self, edge: HorizontalEdge, count: usize) -> usize {
        let applied = match self.tessellation {
            Tessellation::Sokoban => SokobanBoardParser::remove_rows(&mut self.data, edge, count),
            Tessellation::Trioban => TriobanBoardParser::remove_rows(&mut self.data, edge, count),
            Tessellation::Hexoban => HexobanBoardParser::remove_rows(&mut self.data, edge, count),
            Tessellation::Octoban => OctobanBoardParser::remove_rows(&mut self.data, edge, count),
        };
        self.normalize_dimensions();
        applied
    }

    /// Adds `count` columns of [`TileKind::Floor`](crate::TileKind::Floor) to given board edge.
    ///
    /// Returns `count` when the board is non-empty. An odd Left addition on Trioban or Octoban also
    /// adds one top padding row to preserve tile geometry.
    ///
    /// Does nothing to the empty board, which has no rows to add columns to. Grow the empty board
    /// with [`grow()`](GameBoard::grow()) instead.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use sokoban_elements::*;
    ///
    /// let mut board = GameBoard::new(3, 2, Tessellation::Sokoban);
    ///
    /// board.add_columns(VerticalEdge::Right, 4);
    ///
    /// assert_eq!(board.width(), 7);
    /// assert_eq!(board.height(), 2);
    /// ```
    pub fn add_columns(&mut self, edge: VerticalEdge, count: usize) -> usize {
        let applied = match self.tessellation {
            Tessellation::Sokoban => SokobanBoardParser::add_columns(&mut self.data, edge, count),
            Tessellation::Trioban => TriobanBoardParser::add_columns(&mut self.data, edge, count),
            Tessellation::Hexoban => HexobanBoardParser::add_columns(&mut self.data, edge, count),
            Tessellation::Octoban => OctobanBoardParser::add_columns(&mut self.data, edge, count),
        };
        self.normalize_dimensions();
        applied
    }

    /// Removes up to `count` columns from given board edge and returns the number removed.
    ///
    /// Removal saturates at the board width. An odd Left removal that retains columns on Trioban or
    /// Octoban also adds one top padding row to preserve tile geometry. Removing all columns also
    /// removes the rows, because a board with no columns is the empty board.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use sokoban_elements::*;
    ///
    /// let mut board = GameBoard::new(3, 2, Tessellation::Sokoban);
    ///
    /// board.remove_columns(VerticalEdge::Left, 1);
    /// assert_eq!(board.width(), 2);
    ///
    /// board.remove_columns(VerticalEdge::Left, 2);
    /// assert_eq!(board.width(), 0);
    /// assert_eq!(board.height(), 0);
    /// ```
    pub fn remove_columns(&mut self, edge: VerticalEdge, count: usize) -> usize {
        let applied = match self.tessellation {
            Tessellation::Sokoban => {
                SokobanBoardParser::remove_columns(&mut self.data, edge, count)
            }
            Tessellation::Trioban => {
                TriobanBoardParser::remove_columns(&mut self.data, edge, count)
            }
            Tessellation::Hexoban => {
                HexobanBoardParser::remove_columns(&mut self.data, edge, count)
            }
            Tessellation::Octoban => {
                OctobanBoardParser::remove_columns(&mut self.data, edge, count)
            }
        };
        self.normalize_dimensions();
        applied
    }

    /// Removes "outer" floor-only rows and columns in one geometry-preserving crop.
    ///
    /// A tile is retained when it is not
    /// [empty floor](crate::TileKind::is_empty_floor()) - walls, boxes, goals and pushers all
    /// count, so a goal-only or pusher-only edge line survives trimming.
    ///
    /// The result is the smallest rigidly anchored rectangle. It may retain one padding row or
    /// column when the tight rectangle would change tile geometry.
    ///
    /// Trimming leaves the [empty board](Self::new()) exactly when there is nothing to retain,
    /// which is what [`is_blank()`](Self::is_blank()) reports.
    pub fn trim(&mut self) {
        match self.tessellation {
            Tessellation::Sokoban => SokobanBoardParser::trim(&mut self.data),
            Tessellation::Trioban => TriobanBoardParser::trim(&mut self.data),
            Tessellation::Hexoban => HexobanBoardParser::trim(&mut self.data),
            Tessellation::Octoban => OctobanBoardParser::trim(&mut self.data),
        }
        self.normalize_dimensions();
    }

    /// Surrounds the play area with walls, growing the board where there is no room for them.
    ///
    /// [`StaticBoardAnalysis::flood_fill()`](crate::StaticBoardAnalysis::flood_fill()) stops at
    /// walls and at the board edge, so the play area is *always* confined by the two together.
    /// A board is "closed" exactly when the edge is not doing any of that work, which is what
    /// [`StaticBoardAnalysis::is_playable_area_confined()`](crate::StaticBoardAnalysis::is_playable_area_confined())
    /// reports and what this method establishes. There is no need to reconstruct anything inward:
    /// every on-board position next to the play area and not in it is already a wall, because that
    /// is why the flood stopped there.
    ///
    /// One row or column is added to each edge the play area reaches, and then every [empty
    /// floor](crate::TileKind::is_empty_floor()) tile on the resulting outer edge becomes a
    /// [`Wall`](crate::TileKind::Wall). Edges are grown Bottom, Right, Top, Left, because only Top
    /// and Left shift content and may add a perpendicular padding line. Those padding lines are
    /// floor too, so walling the outer edge afterwards seals them without tracking where they
    /// landed.
    ///
    /// Nothing is overwritten but floor, so no piece, goal or wall is ever lost. Two consequences:
    ///
    /// - Dead floor on an edge that was *not* grown becomes wall as well. It lies outside the play
    ///   area, so the puzzle is unchanged, and it only happens on a board that was leaking
    ///   somewhere - an already closed board is left exactly as it is, which makes this method
    ///   idempotent.
    /// - The result is not tightened. Follow with [`trim()`](Self::trim()) or
    ///   [`normalize()`](Self::normalize()) when a tight board is wanted.
    ///
    /// A board with no [`Pusher`] has no play area to enclose and is left untouched, as is the
    /// empty board.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use sokoban_elements::*;
    ///
    /// # fn main() -> Result<(), BoardSyntaxError> {
    /// // The pusher can walk off the top of this board, so the top is not a wall's job yet.
    /// #[rustfmt::skip]
    /// let board_text = [
    ///     "#-@-#",
    ///     "#####",
    /// ]
    /// .join("\n");
    ///
    /// let mut board = GameBoard::parsed(&board_text, Tessellation::Sokoban)?;
    /// board.enclose()?;
    ///
    /// #[rustfmt::skip]
    /// let enclosed = [
    ///     "#####",
    ///     "#-@-#",
    ///     "#####",
    /// ]
    /// .join("\n");
    ///
    /// assert_eq!(board.printed(true), enclosed);
    ///
    /// // Enclosing an already closed board changes nothing.
    /// board.enclose()?;
    /// assert_eq!(board.printed(true), enclosed);
    /// #     Ok(())
    /// # }
    /// ```
    pub fn enclose(&mut self) -> Result<(), BoardSyntaxError> {
        let analysis = StaticBoardAnalysis::new(
            self.iter().map(|(_, t)| t),
            self.size(),
            self.tessellation,
            None,
        )?;

        // No play area means nothing to enclose: a board with no pusher, or the empty board.
        let Some((top_left, bottom_right)) = analysis.playable_area().bounds() else {
            return Ok(());
        };

        // The bounding box of the play area touches an edge exactly when some playable position
        // lies on it.
        let touches_top = top_left.y == 0;
        let touches_left = top_left.x == 0;
        let touches_bottom = bottom_right.y.saturating_add(1) >= self.height();
        let touches_right = bottom_right.x.saturating_add(1) >= self.width();

        if !(touches_top || touches_bottom || touches_left || touches_right) {
            return Ok(());
        }

        if touches_bottom {
            self.add_rows(HorizontalEdge::Bottom, 1);
        }
        if touches_right {
            self.add_columns(VerticalEdge::Right, 1);
        }
        if touches_top {
            self.add_rows(HorizontalEdge::Top, 1);
        }
        if touches_left {
            self.add_columns(VerticalEdge::Left, 1);
        }

        let (width, height) = (self.width(), self.height());
        for y in 0..height {
            for x in 0..width {
                let is_outer_edge = x == 0
                    || y == 0
                    || x.saturating_add(1) == width
                    || y.saturating_add(1) == height;
                if is_outer_edge && self[(x, y)].is_empty_floor() {
                    self[(x, y)] = TileKind::Wall;
                }
            }
        }

        self.normalize_dimensions();

        Ok(())
    }

    /// All non-playable tiles are replaced by floors and missing walls around play area are
    /// reconstructed.
    ///
    /// The reconstructed board is cropped once using the same smallest rigid anchor as
    /// [`trim()`](Self::trim). The crop is the bounding box of everything this method keeps: the
    /// play area plus the reconstructed walls confining it.
    ///
    /// This does **not** make a board closed. A play area that reaches the board edge is confined
    /// there by the edge itself rather than by a wall, and those edge tiles are kept as they are -
    /// no wall is invented around them. [`enclose()`](Self::enclose()) is the operation that makes
    /// room and walls them, and the two compose: `board.enclose()?; board.normalize()?;`.
    ///
    /// A board with no [`Pusher`] has no play area to normalize around, and is left untouched.
    ///
    /// ![](https://raw.githubusercontent.com/tadams42/sokoban-elements/main/crates/sokoban-elements/doc/img/playable_area2.png)
    ///
    /// becomes
    ///
    /// ![](https://raw.githubusercontent.com/tadams42/sokoban-elements/main/crates/sokoban-elements/doc/img/normalized_board.png)
    ///
    /// # Todo
    ///
    /// Following is the stuff that `SokobanYASC` does, see what we can implement too
    ///
    /// - fill jagged (i.e., "stair-case" like) wall edges
    /// - remove redundant walls and floors,
    /// - remove unused boxes and goals
    /// - change immovable boxes on non goal squares to walls
    /// - change immovable boxes on goal squares to walls
    /// - fill unnecessary illegal box squares
    pub fn normalize(&mut self) -> Result<(), BoardSyntaxError> {
        let analysis = StaticBoardAnalysis::new(
            self.iter().map(|(_, t)| t),
            self.size(),
            self.tessellation,
            None,
        )?;
        let significant_walls = analysis.significant_walls();

        // Everything this method keeps: the play area itself plus the walls confining it. The crop
        // below has to be anchored on this same set - anchoring it on the significant walls alone
        // discards playable tiles that reach the board edge, which have no off-board neighbor that
        // could become a significant wall.
        let mut retained = significant_walls.clone();
        for pos in analysis.playable_area() {
            retained.add_point(pos);
        }

        // No pusher means no play area, and therefore no significant walls either: there is nothing
        // to normalize around, so leave the board alone rather than floor every tile of it. Nothing
        // is mutated on this path, so `normalize_dimensions()` has nothing to fix up.
        let Some((top_left, bottom_right)) = retained.bounds() else {
            return Ok(());
        };

        // Replace all non-playable tiles with floor
        let tmp: Vec<Point2D> = self
            .iter()
            .filter_map(|((x, y), _)| {
                let pos = Point2D::new(x, y);
                if retained.contains(pos) {
                    None
                } else {
                    Some(pos)
                }
            })
            .collect();
        for pos in tmp {
            self[(pos.x, pos.y)] = TileKind::Floor;
        }

        // reconstruct missing walls
        for pos in &significant_walls {
            self[(pos.x, pos.y)] = TileKind::Wall;
        }

        self.crop(BoardRect {
            left:   top_left.x,
            top:    top_left.y,
            width:  bottom_right.x.saturating_sub(top_left.x).saturating_add(1),
            height: bottom_right.y.saturating_sub(top_left.y).saturating_add(1),
        });

        Ok(())
    }
}

#[cfg(feature = "serde")]
mod serde_impl {
    use serde::de::Error as _;
    use serde::{Deserialize, Deserializer, Serialize, Serializer};

    use super::GameBoard;
    use crate::Tessellation;

    /// Wire format of [`GameBoard`]: the printed board plus the [`Tessellation`] needed to parse it
    /// back.
    #[derive(Serialize, Deserialize)]
    #[serde(rename = "GameBoard", deny_unknown_fields)]
    struct GameBoardRepr {
        tessellation: Tessellation,
        board:        String,
    }

    impl Serialize for GameBoard {
        fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
            // `printed(true)` is mandatory, not cosmetic: with `false`, the default printer trims
            // trailing `TileKind::Floor` from every row, so board width is lost. It also
            // guarantees no printed row is blank. Hexoban ignores the flag and always prints
            // visible floors.
            GameBoardRepr {
                tessellation: self.tessellation,
                board:        self.printed(true),
            }
            .serialize(serializer)
        }
    }

    impl<'de> Deserialize<'de> for GameBoard {
        fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
            let repr = GameBoardRepr::deserialize(deserializer)?;

            // Parsing (rather than assembling `data` directly) is what keeps the
            // width-normalization invariant intact.
            GameBoard::parsed(&repr.board, repr.tessellation).map_err(D::Error::custom)
        }
    }
}

#[cfg(test)]
mod tests {
    use std::error::Error;

    use indoc::indoc;

    use super::*;
    use crate::{BoxID, GoalID, PlusID, PusherID};

    fn board_text() -> String {
        [
            "    #####",
            "    #   #",
            "    #$  #",
            "  ###  $##",
            "  #  $ $ #",
            "### # ## #   ######",
            "#   # ## #####  ..#",
            "# $  $          ..#",
            "##### ### #@##  ..#",
            "    #     #########",
            "    #######",
        ]
        .join("\n")
    }

    fn board() -> Result<GameBoard, BoardSyntaxError> {
        GameBoard::parsed(&board_text(), Tessellation::Sokoban)
    }

    /// Board data invariant: all rows have exactly `width()` tiles and a board with no columns is
    /// the empty board.
    fn assert_invariant(board: &GameBoard) {
        assert!(
            board.data.iter().all(|row| row.len() == board.width()),
            "rows are not width-normalized: {:?}",
            board.data
        );
        assert_eq!(
            board.width() == 0,
            board.height() == 0,
            "board is {}x{}, but a board with no columns must have no rows",
            board.width(),
            board.height()
        );
        assert_eq!(board.iter().count(), board.width() * board.height());
    }

    fn assert_empty(board: &GameBoard) {
        assert_invariant(board);
        assert_eq!(board.width(), 0);
        assert_eq!(board.height(), 0);
        assert!(board.data.is_empty());
        assert!(board.iter().next().is_none());
    }

    fn content_signature(board: &GameBoard) -> Vec<(usize, usize, TileKind)> {
        let non_floor: Vec<_> = board
            .iter()
            .filter(|(_, tile)| *tile != TileKind::Floor)
            .collect();
        let min_x = non_floor.iter().map(|((x, _), _)| *x).min().unwrap_or(0);
        let min_y = non_floor.iter().map(|((_, y), _)| *y).min().unwrap_or(0);
        non_floor
            .into_iter()
            .map(|((x, y), tile)| (x - min_x, y - min_y, tile))
            .collect()
    }

    fn patterned_board(tessellation: Tessellation) -> Result<GameBoard, BoardSyntaxError> {
        let markers = [
            TileKind::Wall,
            TileKind::Pusher,
            TileKind::Box,
            TileKind::Goal,
            TileKind::BoxOnGoal,
            TileKind::PusherOnGoal,
        ];
        let tiles: Vec<_> = (0..12)
            .map(|index| markers[index % markers.len()])
            .collect();
        GameBoard::parsed_from_tiles(&tiles, 4, 3, tessellation)
    }

    #[test]
    fn it_reports_width_and_height_of_non_square_board() -> Result<(), BoardSyntaxError> {
        let board = board()?;

        assert_eq!(board.width(), 19);
        assert_eq!(board.height(), 11);

        Ok(())
    }

    #[test]
    fn when_board_is_constructed_with_zero_dimension_it_is_empty() {
        for tessellation in Tessellation::ALL {
            assert_empty(&GameBoard::new(0, 5, tessellation));
            assert_empty(&GameBoard::new(5, 0, tessellation));
            assert_empty(&GameBoard::new(0, 0, tessellation));
        }
    }

    #[test]
    fn when_board_is_empty_printing_round_trips() -> Result<(), BoardSyntaxError> {
        for tessellation in Tessellation::ALL {
            let board = GameBoard::new(0, 0, tessellation);

            assert_eq!(board.printed(true), "");
            assert_eq!(board.printed(false), "");
            assert_eq!(GameBoard::parsed(&board.printed(true), tessellation)?, board);
        }

        Ok(())
    }

    #[test]
    fn when_board_is_empty_editing_preserves_the_invariant() {
        for tessellation in Tessellation::ALL {
            let mut board = GameBoard::new(0, 0, tessellation);

            board.trim();
            assert_empty(&board);

            board.mirror(MirrorAxis::Horizontal);
            assert_empty(&board);

            board.mirror(MirrorAxis::Vertical);
            assert_empty(&board);

            board.remove_rows(HorizontalEdge::Top, 1);
            board.remove_columns(VerticalEdge::Left, 1);
            assert_empty(&board);

            board.add_rows(HorizontalEdge::Top, 1);
            board.add_columns(VerticalEdge::Left, 1);
            assert_empty(&board);
        }
    }

    #[test]
    fn every_transform_preserves_piece_counts() -> Result<(), BoardSyntaxError> {
        for tessellation in Tessellation::ALL {
            let original = patterned_board(tessellation)?;
            let expected = (
                original.boxes_count(),
                original.goals_count(),
                original.pushers_count(),
            );

            for transform in [
                BoardTransform::MirrorHorizontal,
                BoardTransform::MirrorVertical,
                BoardTransform::RotateClockwise,
                BoardTransform::RotateCounterClockwise,
            ] {
                let mut board = original.clone();
                match transform {
                    BoardTransform::MirrorHorizontal => board.mirror(MirrorAxis::Horizontal),
                    BoardTransform::MirrorVertical => board.mirror(MirrorAxis::Vertical),
                    BoardTransform::RotateClockwise => board.rotate(Rotation::Clockwise),
                    BoardTransform::RotateCounterClockwise => {
                        board.rotate(Rotation::CounterClockwise);
                    }
                }
                assert_eq!(
                    (board.boxes_count(), board.goals_count(), board.pushers_count()),
                    expected,
                    "{tessellation:?} {transform:?}"
                );
            }
        }

        Ok(())
    }

    mod test_parsing {
        use super::*;

        #[test]
        fn it_pads_short_rows_to_board_width() -> Result<(), BoardSyntaxError> {
            let board =
                GameBoard::parsed(&["###", "#@#####", "###"].join("\n"), Tessellation::Sokoban)?;

            assert_eq!(board.width(), 7);
            assert_eq!(board.height(), 3);
            assert_eq!(board.iter().count(), 21);

            // row 0 is only 3 characters long in board text
            assert_eq!(board[(6, 0)], TileKind::Floor);

            Ok(())
        }

        /// Width-normalization pads short rows with floor tiles. Printing without visible floor
        /// trims them back, so it round trips to original board text. Printing with visible
        /// floor renders them, so all printed lines have equal length.
        #[test]
        fn when_rows_are_padded_only_visible_floor_printing_shows_it()
        -> Result<(), BoardSyntaxError> {
            let board = board()?;

            assert_eq!(board.printed(false), board_text());

            let printed = board.printed(true);
            assert!(
                printed
                    .split('\n')
                    .all(|line| line.chars().count() == board.width())
            );
            assert_eq!(
                GameBoard::parsed(&printed, Tessellation::Sokoban)?,
                board,
                "printing with visible floor must round trip"
            );

            Ok(())
        }

        #[test]
        fn when_board_text_has_no_columns_it_parses_to_empty_board() -> Result<(), BoardSyntaxError>
        {
            // None of these are blank, but all of them RLE-decode to whitespace only.
            for text in ["|", "|||", "3|", "2(|)", "3 ", "|  ", "  |  "] {
                for tessellation in Tessellation::ALL {
                    let board = GameBoard::parsed(text, tessellation)?;
                    assert_empty(&board);
                }
            }

            // Row separators still separate rows when there are tiles to separate.
            let board = GameBoard::parsed("-|-", Tessellation::Sokoban)?;
            assert_eq!(board.width(), 1);
            assert_eq!(board.height(), 2);
            assert_invariant(&board);

            Ok(())
        }

        #[test]
        fn when_tiles_slice_is_empty_it_constructs_empty_board() -> Result<(), BoardSyntaxError> {
            for tessellation in Tessellation::ALL {
                assert_empty(&GameBoard::parsed_from_tiles(&[], 0, 5, tessellation)?);
                assert_empty(&GameBoard::parsed_from_tiles(&[], 5, 0, tessellation)?);
                assert_empty(&GameBoard::parsed_from_tiles(&[], 0, 0, tessellation)?);
            }

            Ok(())
        }

        #[test]
        fn when_declared_size_does_not_match_tiles_slice_it_errors() {
            // Size is checked before any zero dimension is normalized away.
            let err = GameBoard::parsed_from_tiles(&[TileKind::Wall], 0, 5, Tessellation::Sokoban)
                .err()
                .unwrap();
            assert!(matches!(
                err.kind(),
                BoardSyntaxErrorKind::InputSizeNotMatchedByDeclaredSize { .. }
            ));

            // Declared size too large to be represented is reported the same way, not panicked on.
            let err = GameBoard::parsed_from_tiles(
                &[TileKind::Wall],
                usize::MAX,
                2,
                Tessellation::Sokoban,
            )
            .err()
            .unwrap();
            assert!(matches!(
                err.kind(),
                BoardSyntaxErrorKind::InputSizeNotMatchedByDeclaredSize { .. }
            ));
        }
    }

    mod test_pieces_and_sokoban_plus {
        use super::*;

        #[test]
        fn it_collects_pieces_matching_the_counters() -> Result<(), BoardSyntaxError> {
            let board = board()?;

            assert_eq!(board.pushers()?.len(), board.pushers_count());
            assert_eq!(board.boxes(None)?.len(), board.boxes_count());
            assert_eq!(board.goals(None)?.len(), board.goals_count());

            Ok(())
        }

        #[test]
        fn it_assigns_piece_ids_in_row_major_order() -> Result<(), Box<dyn Error>> {
            let board = board()?;

            for (idx, pusher) in board.pushers()?.iter().enumerate() {
                assert_eq!(pusher.id, PusherID::try_from(idx)?);
                assert!(board[(pusher.x, pusher.y)].has_pusher());
            }

            let boxes = board.boxes(None)?;
            for (idx, boxbox) in boxes.iter().enumerate() {
                assert_eq!(boxbox.id, BoxID::try_from(idx)?);
                assert!(board[(boxbox.x, boxbox.y)].has_box());
                assert_eq!(boxbox.plus_id, None);
            }

            // row major means positions are non decreasing in linear board position
            let positions: Vec<usize> = boxes.iter().map(|b| b.y * board.width() + b.x).collect();
            assert!(positions.windows(2).all(|w| w[0] < w[1]));

            for (idx, goal) in board.goals(None)?.iter().enumerate() {
                assert_eq!(goal.id, GoalID::try_from(idx)?);
                assert!(board[(goal.x, goal.y)].has_goal());
                assert_eq!(goal.plus_id, None);
            }

            Ok(())
        }

        #[test]
        fn when_piece_is_on_goal_it_is_both_a_piece_and_a_goal() -> Result<(), BoardSyntaxError> {
            // '*' is box on goal, '+' is pusher on goal
            let board = GameBoard::parsed("#######|#-$.+-*#|#######", Tessellation::Sokoban)?;

            let boxes = board.boxes(None)?;
            let goals = board.goals(None)?;
            let pushers = board.pushers()?;

            assert_eq!(
                boxes
                    .iter()
                    .map(|piece| (piece.x, piece.y))
                    .collect::<Vec<_>>(),
                vec![(2, 1), (6, 1)]
            );
            assert_eq!(
                goals
                    .iter()
                    .map(|piece| (piece.x, piece.y))
                    .collect::<Vec<_>>(),
                vec![(3, 1), (4, 1), (6, 1)]
            );
            assert_eq!(
                pushers
                    .iter()
                    .map(|piece| (piece.x, piece.y))
                    .collect::<Vec<_>>(),
                vec![(4, 1)]
            );

            Ok(())
        }

        #[test]
        fn when_board_is_empty_it_has_no_pieces() -> Result<(), BoardSyntaxError> {
            for tessellation in Tessellation::ALL {
                let board = GameBoard::new(0, 0, tessellation);

                assert!(board.pushers()?.is_empty());
                assert!(board.boxes(None)?.is_empty());
                assert!(board.goals(None)?.is_empty());
            }

            Ok(())
        }

        #[test]
        fn it_reads_plus_ids_from_sokoban_plus() -> Result<(), Box<dyn std::error::Error>> {
            let board = board()?;
            assert_eq!(board.boxes_count(), 6);
            assert_eq!(board.goals_count(), 6);

            // '0' means "this piece has no Sokoban+ ID", and pieces past the end of the sequence
            // get none either
            let sokoban_plus = SokobanPlus::parsed("1 0 2", "2 0 1")?;

            let boxes = board.boxes(Some(&sokoban_plus))?;
            let plus_id = |id: u16| PlusID::new(id).ok();

            assert_eq!(
                boxes.iter().map(|piece| piece.plus_id).collect::<Vec<_>>(),
                vec![plus_id(1), None, plus_id(2), None, None, None]
            );

            let goals = board.goals(Some(&sokoban_plus))?;
            assert_eq!(
                goals.iter().map(|piece| piece.plus_id).collect::<Vec<_>>(),
                vec![plus_id(2), None, plus_id(1), None, None, None]
            );

            Ok(())
        }

        #[test]
        fn when_board_has_more_pushers_than_pusher_id_can_represent_it_errors()
        -> Result<(), BoardSyntaxError> {
            let pushers_count = usize::from(PusherID::MAX) + 1;

            let just_enough = GameBoard::parsed(&"@".repeat(pushers_count), Tessellation::Sokoban)?;
            assert_eq!(just_enough.pushers()?.len(), pushers_count);

            let one_too_many =
                GameBoard::parsed(&"@".repeat(pushers_count + 1), Tessellation::Sokoban)?;
            let result = one_too_many.pushers();
            assert!(result.is_err(), "one pusher over PusherID::MAX must be an error");
            if let Err(err) = result {
                assert!(matches!(err.kind(), BoardSyntaxErrorKind::TooManyPushers));
                assert!(err.source().is_some(), "cause of TooManyPushers must be preserved");
                assert!(
                    err.to_string().contains(&pushers_count.to_string()),
                    "error message must state the supported maximum count: {err}"
                );
            }

            Ok(())
        }
    }

    mod test_rotation {
        use super::*;

        #[test]
        fn mirror_and_rotation_round_trips_restore_content() -> Result<(), BoardSyntaxError> {
            for tessellation in Tessellation::ALL {
                let original = patterned_board(tessellation)?;
                let expected = content_signature(&original);

                for axis in [MirrorAxis::Horizontal, MirrorAxis::Vertical] {
                    let mut board = original.clone();
                    board.mirror(axis);
                    board.mirror(axis);
                    assert_eq!(content_signature(&board), expected, "{tessellation:?} {axis:?}");
                }

                let mut board = original.clone();
                board.rotate(Rotation::Clockwise);
                board.rotate(Rotation::CounterClockwise);
                assert_eq!(
                    content_signature(&board),
                    expected,
                    "{tessellation:?} inverse rotations"
                );

                let mut board = original;
                let steps = 360 / usize::from(tessellation.rotation_step_degrees());
                for _ in 0..steps {
                    board.rotate(Rotation::Clockwise);
                }
                assert_eq!(content_signature(&board), expected, "{tessellation:?} full turn");
            }

            Ok(())
        }
    }

    mod test_resizing {
        use super::*;

        #[test]
        fn when_board_is_resized_rows_stay_width_normalized() -> Result<(), BoardSyntaxError> {
            let mut board = board()?;

            board.add_columns(VerticalEdge::Left, 1);
            board.remove_columns(VerticalEdge::Right, 1);
            board.add_rows(HorizontalEdge::Top, 1);
            board.remove_rows(HorizontalEdge::Bottom, 1);
            assert_invariant(&board);

            board.trim();
            assert_invariant(&board);

            board.mirror(MirrorAxis::Vertical);
            board.mirror(MirrorAxis::Horizontal);
            assert_invariant(&board);

            Ok(())
        }

        #[test]
        fn when_all_columns_are_removed_board_becomes_empty() -> Result<(), BoardSyntaxError> {
            // Asking to remove more columns than there are removes all of them, and a board with no
            // columns is the empty board, so it's rows go too.
            let mut removed_right = board()?;
            removed_right.remove_columns(VerticalEdge::Right, 20);
            assert_empty(&removed_right);

            let mut removed_left = board()?;
            removed_left.remove_columns(VerticalEdge::Left, 20);
            assert_empty(&removed_left);

            Ok(())
        }

        #[test]
        fn when_all_rows_are_removed_board_becomes_empty() -> Result<(), BoardSyntaxError> {
            let mut removed_bottom = board()?;
            removed_bottom.remove_rows(HorizontalEdge::Bottom, 11);
            assert_empty(&removed_bottom);

            // asking for more rows than there are is not an error either
            let mut removed_top = board()?;
            removed_top.remove_rows(HorizontalEdge::Top, 42);
            assert_empty(&removed_top);

            Ok(())
        }

        /// Each editing call leaves a valid board behind, so a board emptied by one call cannot be
        /// grown by the next: there are no rows to add columns to, and rows added to a board with
        /// no columns are of zero length, which is the empty board again.
        ///
        /// This is the trade for editing one edge at a time. [`GameBoard::grow()`] is the way back,
        /// see `when_board_is_emptied_by_editing_grow_brings_it_back`.
        #[test]
        fn when_board_is_emptied_by_editing_it_cannot_be_grown_back() -> Result<(), BoardSyntaxError>
        {
            let mut board = board()?;

            board.remove_columns(VerticalEdge::Right, 20);
            assert_empty(&board);

            board.add_columns(VerticalEdge::Left, 2);
            assert_empty(&board);

            board.add_rows(HorizontalEdge::Top, 3);
            assert_empty(&board);

            Ok(())
        }

        #[test]
        fn when_board_is_emptied_by_editing_grow_brings_it_back() -> Result<(), BoardSyntaxError> {
            let mut board = board()?;

            board.remove_columns(VerticalEdge::Right, 20);
            assert_empty(&board);

            board.grow(NonZeroU16::new(4).unwrap(), NonZeroU16::new(3).unwrap());

            assert_eq!(board.size(), Size2D::new(4, 3));
            assert_invariant(&board);
            assert!(board.iter().all(|(_, tile)| tile == TileKind::Floor));

            Ok(())
        }

        #[test]
        fn grow_never_shrinks_a_board() {
            let mut board = GameBoard::new(5, 4, Tessellation::Sokoban);

            // both axes are already past the wanted size, so nothing happens
            board.grow(NonZeroU16::new(2).unwrap(), NonZeroU16::new(1).unwrap());
            assert_eq!(board.size(), Size2D::new(5, 4));

            // each axis grows on its own; the one that is big enough is left alone
            board.grow(NonZeroU16::new(9).unwrap(), NonZeroU16::new(1).unwrap());
            assert_eq!(board.size(), Size2D::new(9, 4));

            board.grow(NonZeroU16::new(1).unwrap(), NonZeroU16::new(7).unwrap());
            assert_eq!(board.size(), Size2D::new(9, 7));

            assert_invariant(&board);
        }

        /// Growth goes to the Bottom and Right edges, which are dimension-local in every
        /// tessellation. Reimplementing it through Top or Left would pass every other test
        /// here while silently adding a perpendicular padding line and moving every tile.
        #[test]
        fn grow_adds_no_padding_and_moves_no_tile_in_any_tessellation() {
            for tessellation in Tessellation::ALL {
                let mut board = GameBoard::new(3, 3, tessellation);
                board[(0, 0)] = TileKind::Wall;
                board[(2, 1)] = TileKind::Box;
                board[(1, 2)] = TileKind::Pusher;

                let before: Vec<((usize, usize), TileKind)> = board.iter().collect();

                // odd growth on both axes: exactly what a Top or Left edit would have to compensate
                board.grow(NonZeroU16::new(6).unwrap(), NonZeroU16::new(4).unwrap());

                assert_eq!(
                    board.size(),
                    Size2D::new(6, 4),
                    "{tessellation:?} did not grow to the wanted size"
                );
                for (position, tile) in before {
                    assert_eq!(
                        board[position], tile,
                        "{tessellation:?} moved the tile at {position:?}"
                    );
                }
                assert_invariant(&board);
            }
        }

        #[test]
        fn when_one_column_is_left_board_can_still_grow() -> Result<(), BoardSyntaxError> {
            // Stopping one column short of empty keeps the rows, so the board can still be grown.
            let mut board = board()?;

            board.remove_columns(VerticalEdge::Right, 18);
            assert_eq!(board.width(), 1);
            assert_eq!(board.height(), 11);

            board.add_columns(VerticalEdge::Left, 1);
            board.add_rows(HorizontalEdge::Top, 2);

            assert_eq!(board.width(), 2);
            assert_eq!(board.height(), 13);
            assert_invariant(&board);

            Ok(())
        }

        #[test]
        fn resizer_implementors_identify_their_tessellation() {
            assert_eq!(SokobanBoardParser::TESSELLATION, Tessellation::Sokoban);
            assert_eq!(HexobanBoardParser::TESSELLATION, Tessellation::Hexoban);
            assert_eq!(TriobanBoardParser::TESSELLATION, Tessellation::Trioban);
            assert_eq!(OctobanBoardParser::TESSELLATION, Tessellation::Octoban);
        }

        #[test]
        fn when_board_is_all_floor_trim_empties_it() -> Result<(), BoardSyntaxError> {
            let mut board = GameBoard::parsed("---", Tessellation::Sokoban)?;
            assert!(board.is_blank());

            board.trim();
            assert_empty(&board);

            Ok(())
        }

        #[test]
        fn trim_empties_exactly_the_boards_that_are_blank() -> Result<(), BoardSyntaxError> {
            // The goal-only and pusher-only cases are the ones that used to be emptied despite not
            // being blank.
            for source in ["---", "-\n-\n-", "@", ".", "+", "@--#", ".--#", "-#-"] {
                let mut board = GameBoard::parsed(source, Tessellation::Sokoban)?;
                let was_blank = board.is_blank();

                board.trim();
                assert_eq!(board.width() == 0, was_blank, "{source}");
            }

            Ok(())
        }
    }

    mod test_normalization {
        use super::*;

        #[test]
        fn it_can_normalize_board() -> Result<(), BoardSyntaxError> {
            let src = indoc! {"     ########
                               ## *. #*#
                           #####  @# #*#
                            #  $.$######
                            #   #  $ .#
                           ###### $  .#
                                #######
                                #     #"};

            let mut board = GameBoard::parsed(src, Tessellation::Sokoban)?;
            board.normalize()?;

            let result = indoc! {"    ######
                                 ## *. #
                              ####  @# #
                              #  $.$#####
                              #   #  $ .#
                              ##### $  .#
                                  #######"};

            assert_eq!(board.printed(false), result);

            Ok(())
        }

        #[test]
        fn it_can_normalize_sokoban_board() -> Result<(), BoardSyntaxError> {
            let src = indoc! {"#####   ###########
                           #@  ######       ##
                           #$  #   # . * $   #
                           #. *#$  ##        #
                           #####  $###  ######
                            ##  $ $  #      ##
                           ### # ##   # ######
                           #   # ##  ##### ..#
                           # $  $          ..#
                           ##### ### #@    .+#
                           #  ##     #########
                           #   ####  ##  ### #
                           ########  #   ### #
                           #    ###  ####### #
                           # ##              #
                           ###################"};

            let mut board = GameBoard::parsed(src, Tessellation::Sokoban)?;
            board.normalize()?;

            let result = indoc! {"#####
                              #@  #####
                              #$  #   #
                              #. *#$  #
                              #####  $###
                                #  $ $  ##
                              ### # ##   #  #####
                              #   # ##  ##### ..#
                              # $  $          ..#
                              ##### ### #@    .+#
                                  #     #########
                                  ####  #     # #
                              ###### #  #     # #
                              #    ###  ####### #
                              # ##              #
                              ###################"};

            assert_eq!(board.printed(false), result);

            Ok(())
        }

        #[test]
        fn normalize_keeps_playable_tiles_on_the_board_edge() -> Result<(), BoardSyntaxError> {
            // A play area reaching the board edge is confined by the edge itself, so those tiles
            // have no off-board neighbor that could become a significant wall. They
            // must survive anyway.
            for source in ["-@-", "@#", "#@", "@--#", "#--@"] {
                let mut board = GameBoard::parsed(source, Tessellation::Sokoban)?;
                board.normalize()?;
                assert_eq!(board.printed(true), source, "{source}");
            }

            Ok(())
        }

        #[test]
        fn when_board_has_no_pusher_normalize_leaves_it_alone() -> Result<(), BoardSyntaxError> {
            let source = indoc! {"#####
                              #-$.#
                              #####"};

            let mut board = GameBoard::parsed(source, Tessellation::Sokoban)?;
            board.normalize()?;
            assert_eq!(board.printed(true), source);

            // A pusher-less board with nothing but pieces is left alone too, not annihilated.
            let mut board = GameBoard::parsed("-$.-", Tessellation::Sokoban)?;
            board.normalize()?;
            assert_eq!(board.printed(true), "-$.-");

            for tessellation in Tessellation::ALL {
                let mut board = GameBoard::new(0, 0, tessellation);
                board.normalize()?;
                assert_empty(&board);
            }

            Ok(())
        }

        #[test]
        fn normalize_preserves_tile_shapes_of_edge_play_areas() -> Result<(), BoardSyntaxError> {
            for tessellation in [Tessellation::Trioban, Tessellation::Octoban] {
                let mut board = GameBoard::parsed("-@-$-.-", tessellation)?;
                let before: Vec<_> = board
                    .iter()
                    .filter(|(_, tile)| !tile.is_empty_floor())
                    .map(|((x, y), tile)| (tile, tessellation.tile_shape_from_pos(x, y)))
                    .collect();

                board.normalize()?;

                let after: Vec<_> = board
                    .iter()
                    .filter(|(_, tile)| !tile.is_empty_floor())
                    .map(|((x, y), tile)| (tile, tessellation.tile_shape_from_pos(x, y)))
                    .collect();
                assert_eq!(after, before, "{tessellation:?}");
            }

            Ok(())
        }

        #[test]
        fn normalization_uses_one_rigid_crop_on_trioban_and_octoban() -> Result<(), BoardSyntaxError>
        {
            let source = indoc! {"---------
                              --#####--
                              --#@$.#--
                              --#####--
                              ---------"};

            for (tessellation, expected_size, first_wall) in [
                (Tessellation::Trioban, Size2D::new(7, 3), (1_usize, 0_usize)),
                (Tessellation::Octoban, Size2D::new(6, 3), (2, 0)),
            ] {
                let mut board = GameBoard::parsed(source, tessellation)?;
                board.normalize()?;

                assert_eq!(
                    board.size(),
                    expected_size,
                    "{tessellation:?}\n{}",
                    board.printed(true)
                );
                assert_eq!(
                    board[first_wall],
                    TileKind::Wall,
                    "{tessellation:?}\n{}",
                    board.printed(true)
                );
            }

            Ok(())
        }
    }

    mod test_enclosing {
        use super::*;

        fn analysis_of(board: &GameBoard) -> Result<StaticBoardAnalysis, BoardSyntaxError> {
            StaticBoardAnalysis::new(
                board.iter().map(|(_, t)| t),
                board.size(),
                board.tessellation(),
                None,
            )
        }

        #[test]
        fn enclose_confines_the_playable_area() -> Result<(), BoardSyntaxError> {
            // No walls at all: the play area is the whole board and every edge leaks.
            let mut board = GameBoard::parsed("-@-", Tessellation::Sokoban)?;
            board.enclose()?;

            let expected = indoc! {"#####
                                #-@-#
                                #####"};
            assert_eq!(board.printed(true), expected);
            assert!(analysis_of(&board)?.is_playable_area_confined());

            // A single tile grows into the centre of a 3x3.
            let mut board = GameBoard::parsed("@", Tessellation::Sokoban)?;
            board.enclose()?;
            assert_eq!(
                board.printed(true),
                indoc! {"###
                                                 #@#
                                                 ###"}
            );

            Ok(())
        }

        #[test]
        fn enclose_is_a_no_op_on_a_closed_board() -> Result<(), BoardSyntaxError> {
            let source = indoc! {"#####
                              #@$.#
                              #####"};

            let mut board = GameBoard::parsed(source, Tessellation::Sokoban)?;
            assert!(analysis_of(&board)?.is_playable_area_confined());

            board.enclose()?;
            assert_eq!(board.printed(true), source);

            Ok(())
        }

        #[test]
        fn enclose_is_idempotent() -> Result<(), BoardSyntaxError> {
            for tessellation in Tessellation::ALL {
                let mut once = GameBoard::new(3, 3, tessellation);
                once[(1, 1)] = TileKind::Pusher;
                once[(2, 1)] = TileKind::Box;
                once.enclose()?;

                let mut twice = once.clone();
                twice.enclose()?;

                assert_eq!(twice, once, "{tessellation:?}");
            }

            Ok(())
        }

        #[test]
        fn when_board_has_no_pusher_enclose_leaves_it_alone() -> Result<(), BoardSyntaxError> {
            let mut board = GameBoard::parsed("-$.-", Tessellation::Sokoban)?;
            board.enclose()?;
            assert_eq!(board.printed(true), "-$.-");

            for tessellation in Tessellation::ALL {
                let mut board = GameBoard::new(0, 0, tessellation);
                board.enclose()?;
                assert_empty(&board);
            }

            Ok(())
        }

        #[test]
        fn enclose_confines_every_tessellation_without_losing_content()
        -> Result<(), BoardSyntaxError> {
            for tessellation in Tessellation::ALL {
                // All floor except the pieces, so the play area covers the board and leaks
                // everywhere.
                let mut board = GameBoard::new(3, 3, tessellation);
                board[(1, 1)] = TileKind::Pusher;
                board[(2, 1)] = TileKind::Box;
                board[(1, 2)] = TileKind::Goal;

                assert!(!analysis_of(&board)?.is_playable_area_confined(), "{tessellation:?}");

                board.enclose()?;

                assert!(analysis_of(&board)?.is_playable_area_confined(), "{tessellation:?}");
                assert_eq!(board.pushers_count(), 1, "{tessellation:?}");
                assert_eq!(board.boxes_count(), 1, "{tessellation:?}");
                assert_eq!(board.goals_count(), 1, "{tessellation:?}");
                assert_invariant(&board);
            }

            Ok(())
        }

        #[test]
        fn enclose_is_deterministic_when_two_edges_leak() -> Result<(), BoardSyntaxError> {
            // Walled on Bottom and Right, open on Top and Left - the two edges whose growth may add
            // a perpendicular padding line. The sizes below pin the Bottom, Right, Top,
            // Left order.
            let source = indoc! {"@-#
                              --#
                              ###"};

            for (tessellation, expected) in [
                (Tessellation::Sokoban, Size2D::new(4, 4)),
                (Tessellation::Trioban, Size2D::new(5, 5)),
                (Tessellation::Octoban, Size2D::new(5, 5)),
            ] {
                let mut board = GameBoard::parsed(source, tessellation)?;
                board.enclose()?;

                assert_eq!(board.size(), expected, "{tessellation:?}");
                assert!(analysis_of(&board)?.is_playable_area_confined(), "{tessellation:?}");
            }

            Ok(())
        }

        #[test]
        fn enclose_then_normalize_yields_a_closed_normalized_board() -> Result<(), BoardSyntaxError>
        {
            let mut board = GameBoard::parsed("-@-$-.-", Tessellation::Sokoban)?;

            board.enclose()?;
            board.normalize()?;

            assert!(analysis_of(&board)?.is_playable_area_confined());
            assert_eq!(
                board.printed(true),
                indoc! {"#########
                                                 #-@-$-.-#
                                                 #########"}
            );

            Ok(())
        }
    }

    #[cfg(feature = "serde")]
    mod test_serde {

        use super::*;

        fn round_tripped(board: &GameBoard) -> Result<GameBoard, Box<dyn Error>> {
            let json = serde_json::to_string(board)?;

            Ok(serde_json::from_str::<GameBoard>(&json)?)
        }

        fn assert_round_trips(board: &GameBoard) -> Result<(), Box<dyn Error>> {
            let parsed = round_tripped(board)?;

            assert_eq!(parsed, *board);
            assert_eq!(parsed.width(), board.width());
            assert_eq!(parsed.height(), board.height());
            assert_invariant(&parsed);

            Ok(())
        }

        #[test]
        fn it_round_trips_through_json() -> Result<(), Box<dyn Error>> {
            for tessellation in [
                Tessellation::Sokoban,
                Tessellation::Trioban,
                Tessellation::Octoban,
            ] {
                let board = GameBoard::parsed(&board_text(), tessellation)?;
                assert_round_trips(&board)?;
            }

            Ok(())
        }

        #[test]
        fn it_round_trips_hexoban_boards() -> Result<(), Box<dyn Error>> {
            let scheme1_type1 = indoc! {"---#-#-#-#----------
                                         --#-------#---------
                                         -#-@-----#----------
                                         --#-$---$-#-#-#-#-#-
                                         -#---.---.---------#
                                         --#---------------#-
                                         -#-#-#-#-#-#-#-#-#--"};

            let scheme1_type2 = indoc! {"---#-#-#-#-----------
                                         --#-------#----------
                                         -#-@-----#-----------
                                         --#-$---$-#-#-#-#-#--
                                         -#---.---.---------#-
                                         --#-----------------#
                                         -#-#-#-#-#-#-#-#-#-#-"};

            for src in [scheme1_type1, scheme1_type2] {
                let board = GameBoard::parsed(src, Tessellation::Hexoban)?;
                assert_round_trips(&board)?;
            }

            Ok(())
        }

        #[test]
        fn it_round_trips_resized_hexoban_board() -> Result<(), Box<dyn Error>> {
            let markers = [
                TileKind::Wall,
                TileKind::Pusher,
                TileKind::Box,
                TileKind::Goal,
                TileKind::BoxOnGoal,
                TileKind::PusherOnGoal,
            ];
            let mut board = GameBoard::parsed_from_tiles(&markers, 3, 2, Tessellation::Hexoban)?;
            board.add_rows(HorizontalEdge::Top, 1);
            board.remove_rows(HorizontalEdge::Top, 1);

            assert_round_trips(&board)?;

            Ok(())
        }

        #[test]
        fn it_round_trips_resized_trioban_and_octoban_boards() -> Result<(), Box<dyn Error>> {
            let markers = [
                TileKind::Wall,
                TileKind::Pusher,
                TileKind::Box,
                TileKind::Goal,
                TileKind::BoxOnGoal,
                TileKind::PusherOnGoal,
            ];

            for tessellation in [Tessellation::Trioban, Tessellation::Octoban] {
                let mut board = GameBoard::parsed_from_tiles(&markers, 3, 2, tessellation)?;
                board.add_rows(HorizontalEdge::Top, 1);
                board.add_columns(VerticalEdge::Left, 1);

                assert_round_trips(&board)?;
            }

            Ok(())
        }

        /// Hexoban stores boards in a dense internal form whose external text depends on the
        /// parity of the first non floor tile, so which rows carry content is load bearing.
        #[test]
        fn when_hexoban_content_sits_in_rows_of_one_parity_only_it_round_trips()
        -> Result<(), Box<dyn Error>> {
            for row in [0, 1] {
                let mut board = GameBoard::new(5, 4, Tessellation::Hexoban);
                board[(0, row)] = TileKind::Wall;
                board[(2, row)] = TileKind::Wall;
                board[(4, row)] = TileKind::Box;

                assert_round_trips(&board)?;
            }

            Ok(())
        }

        #[test]
        fn when_board_is_all_floor_it_round_trips() -> Result<(), Box<dyn Error>> {
            for tessellation in Tessellation::ALL {
                assert_round_trips(&GameBoard::new(6, 3, tessellation))?;
            }

            Ok(())
        }

        #[test]
        fn when_board_is_single_row_it_round_trips() -> Result<(), Box<dyn Error>> {
            for tessellation in Tessellation::ALL {
                let mut board = GameBoard::new(5, 1, tessellation);
                board[(0, 0)] = TileKind::Wall;
                board[(2, 0)] = TileKind::Pusher;

                assert_round_trips(&board)?;
            }

            Ok(())
        }

        #[test]
        fn when_board_is_empty_it_round_trips() -> Result<(), Box<dyn Error>> {
            for tessellation in Tessellation::ALL {
                assert_round_trips(&GameBoard::new(0, 5, tessellation))?;
                assert_round_trips(&GameBoard::new(4, 0, tessellation))?;
            }

            Ok(())
        }

        /// Boards are printed with visible floors precisely so that trailing floor columns are not
        /// trimmed away.
        #[test]
        fn it_preserves_trailing_floor_columns() -> Result<(), Box<dyn Error>> {
            let board = GameBoard::parsed("#@$.#\n#----", Tessellation::Sokoban)?;
            assert_eq!(board.width(), 5);

            assert_round_trips(&board)?;

            Ok(())
        }

        #[test]
        fn it_deserializes_fields_in_any_order() -> Result<(), Box<dyn Error>> {
            let board: GameBoard =
                serde_json::from_str(r##"{"board": "#@$.#", "tessellation": "Sokoban"}"##)?;

            assert_eq!(board, GameBoard::parsed("#@$.#", Tessellation::Sokoban)?);

            Ok(())
        }

        #[test]
        fn it_rejects_unknown_fields() {
            let result = serde_json::from_str::<GameBoard>(
                r##"{"tessellation": "Sokoban", "board": "#@$.#", "width": 5}"##,
            );

            assert!(result.is_err());
        }

        #[test]
        fn it_rejects_board_text_that_does_not_parse() {
            let result = serde_json::from_str::<GameBoard>(
                r##"{"tessellation": "Hexoban", "board": "#-##-#"}"##,
            );

            assert!(result.is_err());
        }
    }
}