terminal_graphics_interactive 0.2.0

Keyboard and mouse input for terminal_graphics: build interactive terminal games, art and animations. Almost no unsafe.
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
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
//! SAIL: a sailboat on the open sea, under a sky that turns from dawn to day,
//! dusk and night. The boat never jumps: steer it left and right and it sails
//! on whatever the weather does. Fireballs fall out of the sky toward the
//! boat, and one that reaches the water fizzles out in a cloud of steam. The
//! farther you sail, the rougher the sea and the faster they come. Three lives,
//! a score for the leagues you sail, and a bonus when a fireball passes close.
//!
//! A and D (or the arrows) steer, p or Esc pauses, q quits.

use std::cell::RefCell;
use std::f32::consts::{PI, TAU};
use terminal_graphics_interactive::game::*;

fn main() -> std::io::Result<()> {
    run(start(tuning()))
}

/// The numbers the website lets you change while the game runs.
pub fn tuning() -> Tuning {
    Tuning::new()
        .knob("fireball_rate", "fireball rate (x)", 1.0, 0.2, 3.0)
        .knob("wave_height", "wave height (x)", 1.0, 0.0, 2.0)
        .knob("boat_speed", "boat speed (x)", 1.0, 0.5, 2.0)
}

/// The title screen, reading `tuning` while it plays.
pub fn start(tuning: Tuning) -> impl Game {
    Title::new(0).tuned(tuning)
}

// ---------------------------------------------------------------------------
// Time, distance and how far the voyage has got
// ---------------------------------------------------------------------------

/// Seconds of play in one day, from dawn to dawn.
const DAY_SECONDS: f32 = 120.0;

/// Leagues at which the voyage reaches its roughest: progress 1. About 150
/// seconds of play, since the boat sails a bit faster as it goes.
const DISTANCE_MAX: f32 = 165.0;

/// Leagues a second at the start, and at progress 1.
const SPEED_CALM: f32 = 1.0;
const SPEED_STORM: f32 = 1.2;

/// Clamps `x` to 0..1, and reads a value that is not finite as 0.
fn unit(x: f32) -> f32 {
    if x.is_finite() {
        x.clamp(0.0, 1.0)
    } else {
        0.0
    }
}

/// The straight line from `from` to `to`, at `t` (0 to 1).
fn lerp(from: f32, to: f32, t: f32) -> f32 {
    from + (to - from) * t
}

/// How far the voyage has got, from 0 at the start to 1 at [`DISTANCE_MAX`]
/// leagues. The sea, the fireballs and the speed all follow it.
fn progress_of(distance: f32) -> f32 {
    unit(distance / DISTANCE_MAX)
}

/// Leagues a second the boat sails at `progress`.
fn sail_speed(progress: f32) -> f32 {
    lerp(SPEED_CALM, SPEED_STORM, unit(progress))
}

/// How far through the day `seconds` of play is, from 0 (dawn) to 1 (the next dawn).
fn day_phase(seconds: f32) -> f32 {
    if seconds.is_finite() {
        (seconds / DAY_SECONDS).rem_euclid(1.0)
    } else {
        0.0
    }
}

/// How bright the sky is, from 0 (midnight) to 1 (midday), at `seconds` of play.
/// It starts at dawn (0.5), so the sky is brightest at 30 seconds.
fn daylight(seconds: f32) -> f32 {
    (day_phase(seconds) * TAU).sin() * 0.5 + 0.5
}

/// How dark the sky is, from 0 (no night) to 1 (midnight), given the daylight
/// from [`daylight`]. It is zero from dawn to dusk and grows toward midnight.
/// Stars fade in once it passes [`STAR_NIGHT`].
fn night(daylight: f32) -> f32 {
    ((0.5 - unit(daylight)) * 2.0).clamp(0.0, 1.0)
}

/// The night amount above which stars start to show.
const STAR_NIGHT: f32 = 0.4;

/// The name of the time of day at `seconds` of play, for the HUD.
fn time_of_day(seconds: f32) -> &'static str {
    let light = daylight(seconds);
    let phase = day_phase(seconds);
    if night(light) > 0.5 {
        "night"
    } else if light >= 0.85 {
        "day"
    } else if phase < 0.25 {
        // the first quarter of the day rises from dawn, the second falls to dusk
        "dawn"
    } else {
        "dusk"
    }
}

/// Where the still water sits, as a share of the screen height from the top.
const WATER_LEVEL: f32 = 0.72;

/// The row of the still water on a screen `rows` high.
fn level(rows: f32) -> f32 {
    WATER_LEVEL * rows.max(1.0)
}

// ---------------------------------------------------------------------------
// The sea: four swells, from calm to rough
// ---------------------------------------------------------------------------

/// The sea's lowest trough may come no closer than this many rows to the bottom
/// of the screen, so the keel of the boat (which sits in the trough) stays on it.
const BOTTOM_ROOM: f32 = 1.5;

/// The most the swells can lift or dip the sea at `progress`, in rows: the sum of
/// their heights, with the set at its biggest.
fn deepest_swell(progress: f32) -> f32 {
    let total: f32 = swells(progress, 0.0).iter().map(|s| s.0).sum();
    total * (1.0 + SET_DEPTH)
}

/// How much the swells are scaled on a screen `rows` high at `progress`. It is 1
/// when the deepest trough keeps [`BOTTOM_ROOM`] to spare, and otherwise shrinks
/// the swells so that it just fits. A tall screen keeps the full swell.
fn swell_fit(progress: f32, rows: f32) -> f32 {
    let room = (rows - BOTTOM_ROOM - level(rows)).max(0.0);
    let deep = deepest_swell(progress);
    if deep <= room {
        1.0
    } else {
        room / deep
    }
}

/// The four swells at progress 0 (calm) and at progress 1 (rough). Wavelengths
/// are in columns, heights in rows, and speeds in wavelengths a second (negative
/// runs left, so the boat seems to sail right). The wavelengths are not simple
/// multiples of one another, so the sea never settles into a pattern. The
/// fourth swell fades in from nothing.
const CALM_WAVELENGTH: [f32; 4] = [38.0, 23.0, 14.0, 9.0];
const STORM_WAVELENGTH: [f32; 4] = [15.0, 8.5, 4.4, 2.9];
const CALM_HEIGHT: [f32; 4] = [0.5, 0.25, 0.1, 0.0];
const STORM_HEIGHT: [f32; 4] = [2.4, 1.2, 0.7, 0.35];
const CALM_SPEED: [f32; 4] = [-0.05, -0.08, -0.12, -0.2];
const STORM_SPEED: [f32; 4] = [-0.15, -0.25, -0.35, -0.5];

/// The sets: the whole sea swells and dies down, by this share, this fast.
const SET_DEPTH: f32 = 0.35;
const SET_SPEED: f32 = 0.27;

/// The `(height, wavelength, speed)` of each swell at `progress`. Each wavelength
/// is nudged by up to 4% by `phase`, which is set per run, so no two seas match.
/// The nudge does not change with progress, so the swells change smoothly.
fn swells(progress: f32, phase: f32) -> [(f32, f32, f32); 4] {
    let p = unit(progress);
    let mut out = [(0.0, 1.0, 0.0); 4];
    for (i, slot) in out.iter_mut().enumerate() {
        let nudge = 1.0 + 0.04 * math::sin(phase + i as f32 * 2.3);
        *slot = (
            lerp(CALM_HEIGHT[i], STORM_HEIGHT[i], p),
            lerp(CALM_WAVELENGTH[i], STORM_WAVELENGTH[i], p) * nudge,
            lerp(CALM_SPEED[i], STORM_SPEED[i], p),
        );
    }
    out
}

/// The sea at `progress`, at play time `t`, for a run with the given `phase`.
/// It is rebuilt every tick. The swells change slowly, so the height at one
/// column changes only a little from one tick to the next. The game itself now
/// calls [`sea_scaled`]; this is the unscaled sea the tests compare against.
#[cfg(test)]
fn sea(progress: f32, t: f32, phase: f32, rows: f32) -> Waves {
    sea_scaled(progress, t, phase, rows, 1.0)
}

/// [`sea`] with every swell's height multiplied by `scale` (the wave height knob).
fn sea_scaled(progress: f32, t: f32, phase: f32, rows: f32, scale: f32) -> Waves {
    let set = 1.0 + SET_DEPTH * math::sin(SET_SPEED * t + phase);
    let fit = swell_fit(progress, rows) * scale;
    let mut waves = Waves::new();
    for (height, wavelength, speed) in swells(progress, phase) {
        waves = waves.layer(height * set * fit, wavelength, speed);
    }
    waves
}

/// The shade of the sea at `depth` rows below the surface, for the column `x`.
/// It is brightest (foam) at the surface and darkens with depth. The small
/// ripple in the bands follows the surface a few columns away, so the depths
/// echo the waves. Nothing here is random, so neighbouring cells never jump.
fn sea_value(depth: f32, x: f32, t: f32, waves: &Waves) -> f32 {
    let band = 0.08 * (1.7 * depth + 0.8 * waves.height(x - 3.0, t)).sin();
    (1.0 - 0.4 * depth + band).clamp(-1.0, 1.0)
}

/// Whether the picture at pixel `(px, py)` is above the water in its column.
fn above_water(waves: &Waves, t: f32, water: f32, px: i32, py: i32) -> bool {
    let centre_row = (py as f32 + 0.5) / 2.0;
    centre_row < waves.surface_y(px as f32, t, water)
}

// ---------------------------------------------------------------------------
// Difficulty
// ---------------------------------------------------------------------------

/// Seconds between fireballs, from the first to the stormiest.
const SPAWN_CALM: f32 = 1.8;
const SPAWN_STORM: f32 = 0.4;

/// Seconds between fireballs at `progress`. It falls as the voyage goes on.
fn spawn_interval(progress: f32) -> f32 {
    lerp(SPAWN_CALM, SPAWN_STORM, unit(progress))
}

/// How much faster fireballs fall at `progress`, from 1 to 1.6.
fn fall_scale(progress: f32) -> f32 {
    lerp(1.0, 1.6, unit(progress))
}

/// The chance that a spawn comes as a volley of two or three, at `progress`.
/// There are none at the start, and this chance is the most at the end.
const VOLLEY_CHANCE: f32 = 0.35;
fn volley_chance(progress: f32) -> f32 {
    VOLLEY_CHANCE * unit(progress)
}

// ---------------------------------------------------------------------------
// The boat
// ---------------------------------------------------------------------------

/// The boat's picture is this many pixels wide and tall. A pixel is a column
/// across and a half row down, so it is square on screen.
const BOAT_WIDTH: f32 = 17.0;
const BOAT_HEIGHT: f32 = 12.0;

/// Columns a second the boat sails sideways when a key is held, and how quickly
/// its speed eases toward that.
const SAIL_SPEED: f32 = 22.5;
const SAIL_EASE: f32 = 5.0;

/// How fast the hull's keel chases the water, as a spring: stiffness and damping.
const SPRING: f32 = 36.0;
const DAMPING: f32 = 7.0;

/// The boat: `x` is its left column, and `keel` is the pixel row of the bottom
/// of its picture, which sits just under the water. It only moves sideways.
#[derive(Clone, Copy, Debug)]
struct Boat {
    x: f32,
    vx: f32,
    keel: f32,
    keel_v: f32,
}

impl Boat {
    /// A boat not yet on the water. Its `keel` is NaN until [`Boat::place`].
    fn new() -> Boat {
        Boat {
            x: f32::NAN,
            vx: 0.0,
            keel: f32::NAN,
            keel_v: 0.0,
        }
    }

    /// The column of the middle of the hull.
    fn centre(&self) -> f32 {
        self.x + BOAT_WIDTH / 2.0
    }

    /// The pixel row of the top of the picture.
    fn top(&self) -> f32 {
        self.keel - (BOAT_HEIGHT - 1.0)
    }

    /// The picture as a rectangle, for collisions. Both are in pixels.
    fn hit(&self) -> Hit {
        Hit::rect(self.x, self.top(), BOAT_WIDTH, BOAT_HEIGHT)
    }

    /// On the first call, puts the boat `across` (0 to 1) of the way across the
    /// screen, with its keel where `keel_under` says the water is. Then does
    /// nothing.
    fn place(&mut self, width: f32, across: f32, keel_under: impl Fn(f32) -> f32) {
        if self.keel.is_nan() {
            self.x = width * across;
            self.keel = keel_under(self.centre());
            self.keel_v = 0.0;
        }
    }

    /// Eases the speed toward `wanted` columns a second, then moves the boat
    /// and keeps its left column between `near` and `far`. Reaching an edge also
    /// stops the boat, so it does not push against it. `min` then `max` is used
    /// rather than `clamp`, which panics when its bounds cross.
    fn steer(&mut self, wanted: f32, dt: f32, near: f32, far: f32) {
        let ease = (dt * SAIL_EASE).min(1.0);
        self.vx += (wanted - self.vx) * ease;
        let free = self.x + self.vx * dt;
        let moved = free.min(far).max(near);
        if moved != free {
            self.vx = 0.0;
        }
        self.x = moved;
    }

    /// Pulls the keel toward `target` with a spring, so the boat bobs on the
    /// swell rather than snapping to it.
    fn settle(&mut self, target: f32, dt: f32) {
        let accel = SPRING * (target - self.keel) - DAMPING * self.keel_v;
        self.keel_v += accel * dt;
        self.keel += self.keel_v * dt;
    }
}

/// Whether the boat can be hit: it cannot be while its invulnerable time lasts.
/// It blinks, off on every other [`BLINK_SECONDS`] slot, so the player sees it.
fn boat_visible(elapsed: f32, invulnerable_until: f32) -> bool {
    if elapsed >= invulnerable_until {
        return true;
    }
    (elapsed / BLINK_SECONDS).floor() as i64 % 2 == 0
}

/// How long one on or off slot of an invulnerable boat's blinking lasts.
const BLINK_SECONDS: f32 = 0.08;

/// The keel row for the water under column `x`: just below the surface.
fn keel_under(waves: &Waves, x: f32, t: f32, water: f32) -> f32 {
    2.0 * waves.surface_y(x, t, water) + 1.0
}

// ---------------------------------------------------------------------------
// Fireballs
// ---------------------------------------------------------------------------

/// A fireball is a disc of this many pixels across the radius, with a glow.
const FIREBALL_RADIUS: f32 = 2.5;
const FIREBALL_GLOW: f32 = 7.0;

/// The most fireballs at once.
const FIREBALL_LIMIT: usize = 16;

/// A fireball starts this many pixels above the top (so it falls into view), in
/// pixels a second down at the start, and how fast that speeds up.
const FALL_FROM: f32 = -2.0;
const FALL_START: f32 = 4.8;
const FALL_GRAVITY: f32 = 12.8;

/// Wind pushes fireballs left, by this many columns a second.
const WIND_MIN: f32 = 3.4;
const WIND_MAX: f32 = 10.2;

/// One spawn in this many aims near the boat, within this many columns.
const AIM_CHANCE: f32 = 0.4;
const AIM_SPREAD: f32 = 5.0;

/// A fireball that has drifted this far past the left edge has left the screen.
const OFF_LEFT: f32 = -4.0;

/// Once a fireball reaches the water it sinks for this long, sliding down
/// slowly and fading from fire to grey. Drag stops it quickly at first.
const SINK_SECONDS: f32 = 1.2;
const SINK_DRAG: f32 = 6.0;
const SINK_DRIFT: f32 = 3.0;

/// The colours a sinking fireball steps through, from fire to grey.
const SINK_RAMP: [Colour; 5] = [
    Colour::BrightYellow,
    Colour::BrightRed,
    Colour::White,
    Colour::BrightBlack,
    Colour::Blue,
];

/// Which colour of [`SINK_RAMP`] a fireball is, given how far through its
/// sinking it is (0 to 1). It only goes up as the sinking goes on.
fn sink_step(sunk: f32) -> usize {
    ((unit(sunk) * SINK_RAMP.len() as f32) as usize).min(SINK_RAMP.len() - 1)
}

/// The colour of a sinking fireball that is `sunk` through its sinking.
fn sink_colour(sunk: f32) -> Colour {
    SINK_RAMP[sink_step(sunk)]
}

/// Where a fireball is in its life.
#[derive(Clone, Copy, Debug, PartialEq)]
enum Stage {
    /// In the air. It can hit the boat.
    Flying,
    /// In the water, for this many seconds. It cannot hit the boat.
    Sinking(f32),
    /// Gone: removed at the end of the tick.
    Spent,
}

/// A fireball. `x` is a column and `y` a pixel row. `vx` is columns a second
/// and `vy` pixels a second, and `gravity` speeds up `vy`. `passed` has a bit set for each boat
/// it has crossed the column of, so its near miss counts once for each.
#[derive(Clone, Copy, Debug, PartialEq)]
struct Fireball {
    x: f32,
    y: f32,
    vx: f32,
    vy: f32,
    gravity: f32,
    passed: u8,
    stage: Stage,
}

impl Fireball {
    fn new(x: f32, y: f32, vx: f32, vy: f32, gravity: f32) -> Fireball {
        Fireball {
            x,
            y,
            vx,
            vy,
            gravity,
            passed: 0,
            stage: Stage::Flying,
        }
    }

    /// The fireball as a circle for collisions, in pixels.
    fn hit_shape(&self) -> Hit {
        Hit::circle(self.x, self.y, FIREBALL_RADIUS)
    }

    /// Carries a flying fireball on by `dt`: gravity speeds its fall and the
    /// wind carries it left.
    fn fall(&mut self, dt: f32) {
        self.vy += self.gravity * dt;
        self.x += self.vx * dt;
        self.y += self.vy * dt;
    }

    /// Carries a sinking fireball on by `dt`. Drag slows it, and it drifts down
    /// a little. When its time is up it is spent.
    fn sink(&mut self, dt: f32) {
        let keep = math::exp(-SINK_DRAG * dt);
        self.vx *= keep;
        self.vy *= keep;
        self.y += (self.vy + SINK_DRIFT) * dt;
        if let Stage::Sinking(age) = self.stage {
            let age = age + dt;
            self.stage = if age >= SINK_SECONDS {
                Stage::Spent
            } else {
                Stage::Sinking(age)
            };
        }
    }

    /// How far through its sinking it is, from 0 (just reached the water) to 1
    /// (gone). A flying fireball is at 0.
    fn sunk(&self) -> f32 {
        match self.stage {
            Stage::Sinking(age) => unit(age / SINK_SECONDS),
            _ => 0.0,
        }
    }

    /// The radius in pixels: full while flying, shrinking to nothing as it sinks.
    fn radius(&self) -> f32 {
        FIREBALL_RADIUS * (1.0 - self.sunk())
    }
}

/// How long it takes to fall `distance` pixels from `v0` pixels a second, with
/// `gravity` speeding it up. Used to aim a fireball at the boat.
fn fall_time(distance: f32, v0: f32, gravity: f32) -> f32 {
    if gravity <= 0.0 {
        return distance / v0.max(f32::MIN_POSITIVE);
    }
    (-v0 + (v0 * v0 + 2.0 * gravity * distance.max(0.0)).sqrt()) / gravity
}

/// The gap in pixels between a fireball at `y` and the boat's top and bottom.
/// Zero when it is level with the boat.
fn gap_to_boat(y: f32, top: f32, bottom: f32) -> f32 {
    if y < top {
        top - y
    } else if y > bottom {
        y - bottom
    } else {
        0.0
    }
}

/// A fireball this close to the boat as it passes, but missing, scores a bonus.
const NEAR_PX: f32 = 6.0;
const NEAR_BONUS: u32 = 5;

/// A "+5" that rises from the boat and fades.
#[derive(Clone, Copy, Debug)]
struct Floater {
    x: f32,
    y: f32,
    age: f32,
}

/// The most floating texts at once, how many rows a second they rise, and how
/// long they last in seconds.
const FLOATER_LIMIT: usize = 8;
const FLOATER_RISE: f32 = 2.0;
const FLOATER_LIFE: f32 = 0.8;

// ---------------------------------------------------------------------------
// Lives and effects
// ---------------------------------------------------------------------------

/// The boat starts with this many lives, and is safe for this long after a hit.
const LIVES: u32 = 3;
const INVULNERABLE_SECONDS: f32 = 1.5;

/// How long the screen flashes after a hit.
const FLASH_SECONDS: f32 = 0.15;

/// Columns a second the island scrolls, as a share of the screen: the island
/// moves one screen width for every this many leagues sailed.
const ISLAND_LEAGUES: f32 = 10.0;

/// How long a wake droplet lives and how often one is shed.
const WAKE_SECONDS: f32 = 0.15;
const SPRAY_FALL: f32 = 12.0;

/// The most spray droplets, embers and steam particles at once.
const SPRAY_LIMIT: usize = 200;
const EMBER_LIMIT: usize = 400;
const STEAM_LIMIT: usize = 160;

/// Embers a flying fireball leaves each tick, how long each lives in seconds,
/// and how fast they rise (negative gravity: rows a second each second).
const EMBERS_PER_TICK: usize = 2;
const EMBER_LIFE: f32 = 0.5;
const EMBER_RISE: f32 = -6.0;

/// Steam in the cloud when a fireball reaches the water, and grey droplets.
const STEAM_BURST: usize = 14;
const DROPLETS: usize = 5;

// ---------------------------------------------------------------------------
// The sky
// ---------------------------------------------------------------------------

/// The sky's colours, from the darkest to the brightest: night, a faint glow at
/// the horizon, the reds and yellows of sunrise and sunset, then white by day.
/// There is no blue or cyan here: those belong to the water.
const SKY_RAMP: [Colour; 7] = [
    Colour::Black,
    Colour::BrightBlack,
    Colour::Red,
    Colour::BrightRed,
    Colour::BrightYellow,
    Colour::White,
    Colour::BrightWhite,
];

/// The palette the sky is drawn with.
fn sky_palette() -> Palette {
    Palette::new(&SKY_RAMP)
}

/// How much the horizon glows at the bottom of the sky, on the 0 to 1 ramp.
const HORIZON_GLOW: f32 = 0.07;

/// Eases a value from 0 to 1 so that it stays low for longer at the bottom and
/// top: night stays black well past dusk, and day stays white.
fn smooth(x: f32) -> f32 {
    x * x * (3.0 - 2.0 * x)
}

/// The value of the sky at one cell, from -1 (darkest) to 1 (brightest), for
/// the given daylight, flash and play time. Clouds drift in slow bands: at noon
/// they are a little grey against the white, at dawn and dusk they catch the
/// light, and at night they are hard to see.
fn sky_value(cell: &Cell, daylight: f32, flash: f32, t: f32) -> f32 {
    let horizon = if cell.height > 0.0 {
        unit(cell.y / cell.height)
    } else {
        1.0
    };
    let cloud = cloud_amount(cell.x, cell.y, t);
    let twilight = 1.0 - (2.0 * unit(daylight) - 1.0).abs();
    let light = smooth(unit(daylight)) + HORIZON_GLOW * horizon - 0.14 * daylight * cloud
        + 0.12 * twilight * cloud
        + 0.2 * flash;
    unit(light) * 2.0 - 1.0
}

/// How much cloud is at pixel `(x, y)` at play time `t`, from 0 (clear) to 1.
fn cloud_amount(x: f32, y: f32, t: f32) -> f32 {
    let wave = (x * 0.07 + t * 0.12).sin() + (x * 0.031 - y * 0.35 + t * 0.05).sin();
    ((wave - 1.1) * 1.5).clamp(0.0, 1.0)
}

/// Stars over the sky above pixel row `sky_bottom`, twinkling with play time
/// `t`. They are single pixels, only at night, and fullest at midnight.
fn paint_stars(screen: &mut Screen, night: f32, t: f32, sky_bottom: f32) {
    if night <= STAR_NIGHT {
        return;
    }
    let fullness = unit((night - STAR_NIGHT) / (1.0 - STAR_NIGHT));
    // out of every thousand pixels, this many are stars at full night
    let chance = (fullness * 30.0) as u32;
    let twinkle = (t * 2.0).floor() as i32;
    let width = screen.width();
    // pixel rows 0 and 1 are the HUD's, so the stars start at row 2
    for py in 2..sky_bottom.floor() as i32 {
        for px in 0..width {
            if mix(px, py, 0) % 1000 >= chance || mix(px, py, twinkle) % 4 == 0 {
                continue;
            }
            let colour = match mix(px, py, 1) % 3 {
                0 => Colour::BrightWhite,
                1 => Colour::White,
                _ => Colour::BrightYellow,
            };
            screen.pixel(px, py, colour);
        }
    }
}

/// A cheap, deterministic hash of a pixel and a salt, using only wrapping
/// arithmetic, so the same inputs always give the same bits and nothing panics.
fn mix(x: i32, y: i32, salt: i32) -> u32 {
    let mut h = (x as u32).wrapping_mul(0x9E37_79B1)
        ^ (y as u32).wrapping_mul(0x85EB_CA77)
        ^ (salt as u32).wrapping_mul(0xC2B2_AE3D);
    h ^= h >> 15;
    h = h.wrapping_mul(0x2C1B_3C6D);
    h ^ (h >> 12)
}

/// Where a body is on its arc across the sky at `seconds`: how far along the
/// arc from the left (0 to 1) and how high (0 at the horizon, 1 at the top).
/// `start` is the day phase at which it rises. None when it is below the horizon.
fn arc(seconds: f32, start: f32) -> Option<(f32, f32)> {
    if !seconds.is_finite() {
        return None;
    }
    let along = (day_phase(seconds) - start).rem_euclid(1.0) * 2.0;
    if along >= 1.0 {
        return None;
    }
    Some((along, (PI * along).sin()))
}

/// The sun rises at dawn and sets at dusk. None at night.
fn sun_arc(seconds: f32) -> Option<(f32, f32)> {
    arc(seconds, 0.0)
}

/// The moon is the opposite: it rises at dusk and sets at dawn. None by day.
fn moon_arc(seconds: f32) -> Option<(f32, f32)> {
    arc(seconds, 0.5)
}

/// The pixel row a body at `height` (0 to 1) sits on: the horizon at 0, the top
/// of the sky at 1.
fn body_row(height: f32, water: f32) -> f32 {
    lerp(2.0 * water, SKY_TOP, height)
}

/// The row the sun and moon reach at their highest, clear of the HUD.
const SKY_TOP: f32 = 9.0;
const SUN_RADIUS: f32 = 4.0;
const SUN_GLOW: f32 = 14.0;
const MOON_RADIUS: f32 = 3.0;
const MOON_GLOW: f32 = 9.0;

/// Draws a disc of pixels, but only the pixels that are above the water, so
/// the waves cover the lower edge of a body that is setting.
#[allow(clippy::too_many_arguments)]
fn disc_above_water(
    screen: &mut Screen,
    centre: (f32, f32),
    radius: f32,
    colour: Colour,
    waves: &Waves,
    t: f32,
    water: f32,
) {
    let (cx, cy) = centre;
    let reach = radius.ceil() as i32 + 1;
    let (x0, y0) = (cx.round() as i32, cy.round() as i32);
    for py in (y0 - reach)..=(y0 + reach) {
        for px in (x0 - reach)..=(x0 + reach) {
            let dx = px as f32 + 0.5 - cx;
            let dy = py as f32 + 0.5 - cy;
            if dx * dx + dy * dy < radius * radius && above_water(waves, t, water, px, py) {
                screen.pixel(px, py, colour);
            }
        }
    }
}

/// Draws the sun and the moon, each with a soft glow, at their places on the
/// arc for `seconds` of play. Their pixels are clipped to the sky.
#[allow(clippy::too_many_arguments)]
fn paint_celestial(
    screen: &mut Screen,
    look: &Look,
    seconds: f32,
    waves: &Waves,
    t: f32,
    water: f32,
) {
    let width = screen.width() as f32;
    if let Some((along, height)) = sun_arc(seconds) {
        let centre = (lerp(0.12, 0.88, along) * width, body_row(height, water));
        screen.glow(centre.0, centre.1, SUN_GLOW, &look.sun_glow);
        disc_above_water(
            screen,
            centre,
            SUN_RADIUS,
            Colour::BrightYellow,
            waves,
            t,
            water,
        );
    }
    if let Some((along, height)) = moon_arc(seconds) {
        let centre = (lerp(0.88, 0.12, along) * width, body_row(height, water));
        screen.glow(centre.0, centre.1, MOON_GLOW, &look.grey_glow);
        disc_above_water(
            screen,
            centre,
            MOON_RADIUS,
            Colour::BrightWhite,
            waves,
            t,
            water,
        );
    }
}

/// Paints the sky over the top `horizon` rows with the sky formula.
fn paint_sky(
    screen: &mut Screen,
    palette: &Palette,
    daylight: f32,
    flash: f32,
    t: f32,
    horizon: f32,
) {
    let width = screen.width();
    let rows = horizon.max(0.0).floor() as i32;
    screen.backdrop_in(0, 0, width, rows, palette, |cell| {
        sky_value(cell, daylight, flash, t)
    });
}

/// The colour of the sea palette at `value` (-1 to 1), for a single pixel.
fn ramp_colour(palette: &Palette, value: f32) -> Colour {
    let colours = palette.colours();
    let steps = colours.len() - 1;
    let position = ((unit((value + 1.0) / 2.0)) * steps as f32).round() as usize;
    colours[position.min(steps)]
}

/// Paints the sea from a little above the still water to the bottom of the
/// screen. Each cell is shaded with a block, as the sketch art does. A cell
/// whose top half is in the sky but whose bottom half is in the water gets a
/// lower-half pixel, so the surface moves at half-row steps and not whole rows.
fn paint_sea(screen: &mut Screen, palette: &Palette, waves: &Waves, t: f32, water: f32) {
    let (width, height) = screen.size();
    for x in 0..width as i32 {
        let column = x as f32;
        let surface = waves.surface_y(column, t, water);
        let first = (surface.floor() as i32 - 1).max(0);
        for y in first..height as i32 {
            let row = y as f32;
            if row + 0.25 > surface {
                let value = sea_value(row + 0.5 - surface, column, t, waves);
                let (block, fg, bg) = palette.shade_signed(value);
                screen.put_on(x, y, block, fg, bg);
            } else if row + 0.75 > surface {
                let value = sea_value(row + 0.75 - surface, column, t, waves);
                screen.pixel(x, 2 * y + 1, ramp_colour(palette, value));
            }
        }
    }
}

/// Paints the pixels of `art` with its top left at pixel `(x, y)`, leaving out
/// every pixel below the water, so the island sinks behind the waves.
#[allow(clippy::too_many_arguments)]
fn paint_art_above_water(
    screen: &mut Screen,
    art: &PixelArt,
    x: i32,
    y: i32,
    waves: &Waves,
    t: f32,
    water: f32,
) {
    for row in 0..art.height() {
        for column in 0..art.width() {
            let Some(colour) = art.pixel(column, row) else {
                continue;
            };
            let (px, py) = (x + column as i32, y + row as i32);
            if above_water(waves, t, water, px, py) {
                screen.pixel(px, py, colour);
            }
        }
    }
}

/// The column of the island's left edge after the boat has sailed `distance`
/// leagues. It starts on the left and scrolls away.
fn island_column(distance: f32, width: f32) -> f32 {
    width * 0.08 - distance / ISLAND_LEAGUES * width
}

/// Paints the island on the horizon at the left, for the voyage's `distance`.
#[allow(clippy::too_many_arguments)]
fn paint_island(
    screen: &mut Screen,
    look: &Look,
    distance: f32,
    waves: &Waves,
    t: f32,
    water: f32,
) {
    let x = island_column(distance, screen.width() as f32).round() as i32;
    let top = (2.0 * water).round() as i32 - ISLAND_RISE;
    paint_art_above_water(screen, &look.island, x, top, waves, t, water);
}

/// How many pixel rows the island's picture is, from its top to the water: its
/// sand sits on the water, and the waves cover what is below it.
const ISLAND_RISE: i32 = 11;

/// Draws the boat's picture with its left column at `x` and its keel at pixel
/// row `keel`, leaning as the water under it does.
fn draw_boat(screen: &mut Screen, boats: &[PixelArt; 3], x: f32, keel: f32, tilt: Tilt) {
    let top = keel - (BOAT_HEIGHT - 1.0);
    let art = match tilt {
        Tilt::Left => &boats[0],
        Tilt::Level => &boats[1],
        Tilt::Right => &boats[2],
    };
    screen.pixel_art(x.round() as i32, top.round() as i32, art);
}

/// Draws a fireball: a fire-coloured disc with a glow while it flies, and as it
/// sinks, a grey one that shrinks to nothing.
fn draw_fireball(screen: &mut Screen, look: &Look, f: &Fireball) {
    match f.stage {
        Stage::Flying => {
            screen.glow(f.x, f.y, FIREBALL_GLOW, &look.fire_glow);
            screen.disc(f.x, f.y, FIREBALL_RADIUS, Colour::BrightRed);
            screen.disc(f.x, f.y, FIREBALL_RADIUS * 0.5, Colour::BrightYellow);
        }
        Stage::Sinking(_) => {
            let sunk = f.sunk();
            screen.glow(f.x, f.y, FIREBALL_GLOW * (1.0 - sunk), &look.grey_glow);
            screen.disc(f.x, f.y, f.radius(), sink_colour(sunk));
        }
        Stage::Spent => {}
    }
}

/// What the HUD shows.
struct Hud {
    /// Leagues sailed, in tenths of a league.
    tenths: u32,
    score: u32,
    best: u32,
    /// The lives each player has left; only the first `players` count.
    lives: [u32; MAX_BOATS],
    players: usize,
    /// Which player this screen is for.
    me: usize,
    time: &'static str,
}

/// The strip along the top: the leagues and the score on the left, the time of
/// day in the middle, the best score and one heart per life on the right (red
/// while it lasts, grey once lost).
fn draw_hud(screen: &mut Screen, hud: &Hud) {
    let width = screen.width();
    screen.fill(0, 0, width, 1, ' ', Colour::White, Colour::Black);
    draw_leagues(screen, 1, 0, hud.tenths, Colour::BrightWhite);
    screen.text(17, 0, "score ", Colour::BrightYellow);
    number(screen, 23, 0, hud.score, Colour::BrightYellow);
    screen.text_centred(0, hud.time, Colour::BrightCyan);
    let best_at = width - 2 * LIVES as i32 - 12;
    screen.text(best_at, 0, "best ", Colour::White);
    number(screen, best_at + 5, 0, hud.best, Colour::White);
    let first = width - 2 * LIVES as i32;
    let mine = hud.lives.get(hud.me).copied().unwrap_or(0);
    for life in 0..LIVES {
        let colour = if life < mine {
            Colour::BrightRed
        } else {
            Colour::BrightBlack
        };
        screen.put_on(first + 2 * life as i32, 0, '♥', colour, Colour::Black);
    }
    if hud.players > 1 {
        draw_crews(screen, hud);
    }
}

/// In a match, a second strip under the HUD: each player's name and hearts,
/// yours in white and the others in blue.
fn draw_crews(screen: &mut Screen, hud: &Hud) {
    let mut x = 1;
    for player in 0..hud.players.min(MAX_BOATS) {
        let colour = if player == hud.me {
            Colour::BrightWhite
        } else {
            Colour::BrightBlue
        };
        screen.put_on(x, 1, 'P', colour, Colour::Black);
        screen.put_on(
            x + 1,
            1,
            (b'1' + player as u8) as char,
            colour,
            Colour::Black,
        );
        for life in 0..LIVES {
            let heart = if life < hud.lives[player] {
                Colour::BrightRed
            } else {
                Colour::BrightBlack
            };
            screen.put_on(x + 3 + 2 * life as i32, 1, '♥', heart, Colour::Black);
        }
        x += 4 + 2 * LIVES as i32 + 1;
    }
}

/// Draws the distance as leagues with one decimal, such as `12.4 leagues`,
/// starting at `(x, y)`, without allocating a string. Returns the column after.
fn draw_leagues(screen: &mut Screen, x: i32, y: i32, tenths: u32, colour: Colour) -> i32 {
    let end = number(screen, x, y, tenths / 10, colour);
    screen.put(end, y, '.', colour);
    screen.put(end + 1, y, (b'0' + (tenths % 10) as u8) as char, colour);
    screen.text(end + 2, y, " leagues", colour);
    end + 2 + " leagues".len() as i32
}

/// Draws `n` in decimal starting at `(x, y)`, one cell a digit, without
/// allocating a string. Returns the column after the last digit.
fn number(screen: &mut Screen, x: i32, y: i32, n: u32, colour: Colour) -> i32 {
    // least significant digit first; a u32 has at most ten digits
    let mut digits = [0u8; 10];
    let mut count = 0;
    let mut rest = n;
    loop {
        digits[count] = b'0' + (rest % 10) as u8;
        count += 1;
        rest /= 10;
        if rest == 0 {
            break;
        }
    }
    for (column, digit) in digits[..count].iter().rev().enumerate() {
        screen.put(x + column as i32, y, *digit as char, colour);
    }
    x + count as i32
}

// ---------------------------------------------------------------------------
// Pictures
// ---------------------------------------------------------------------------

/// The boat's colours: a red hull with a bright red trim, a yellow deck and
/// mast, a white sail with a dark foot (so it shows against the bright sky), and
/// a red pennant.
const BOAT_LEGEND: [(char, Colour); 7] = [
    ('H', Colour::Red),
    ('T', Colour::BrightRed),
    ('D', Colour::Yellow),
    ('M', Colour::Yellow),
    ('F', Colour::BrightRed),
    ('S', Colour::White),
    ('W', Colour::BrightBlack),
];

/// The other players' boat: the same picture with a blue hull and pennant.
const RIVAL_LEGEND: [(char, Colour); 7] = [
    ('H', Colour::Blue),
    ('T', Colour::BrightBlue),
    ('D', Colour::Yellow),
    ('M', Colour::Yellow),
    ('F', Colour::BrightBlue),
    ('S', Colour::White),
    ('W', Colour::BrightBlack),
];

/// The boat, level on the water. The hull is the bottom rows.
const BOAT_LEVEL: &str = r"
        MFF
        M
        MS
        MSS
        MSSS
        MSSSS
        MSSSSS
        MWWWWW
     DDDDDDDDDDD
    HHHHHHHHHHHHH
     HHHHHHHHHHHH
      THHHHHHHHHT
";

/// The boat leaning left: its hull is shorter at the back and the bow dips.
const BOAT_LEFT: &str = r"
        MFF
        M
        MS
        MSS
        MSSS
        MSSSS
        MSSSSS
        MWWWWW
      DDDDDDDDD
   HHHHHHHHHHHHH
    HHHHHHHHHHHH
     THHHHHHHHHT
";

/// The island's colours: sand, a green hill, the palm's fronds and trunk.
const ISLAND_LEGEND: [(char, Colour); 6] = [
    ('Y', Colour::Yellow),
    ('y', Colour::BrightYellow),
    ('G', Colour::Green),
    ('g', Colour::BrightGreen),
    ('T', Colour::Red),
    ('L', Colour::BrightGreen),
];

/// The island: a sand mound with a green hill and a palm tree, on the horizon.
const ISLAND: &str = r"
                 LLLLL
                LLLLLLL
                  LTL
                   T
         GG        T
       GGGGGG      T
     GGGGGGGGGG    T
   GGGGGGGGGGGGGG  T
GGGGGGGGGGGGGGGGGGGG
yyyyyyyyyyyyyyyyyyyyyyyyyyyy
YYYYYYYYYYYYYYYYYYYYYYYYYYYYYY
";

/// The colours and pictures the game draws with. Made once per scene, so that
/// drawing allocates nothing.
struct Look {
    sky: Palette,
    sea: Palette,
    fire_glow: Palette,
    grey_glow: Palette,
    sun_glow: Palette,
    /// Indexed as [`draw_boat`] reads it: leaning left, level, leaning right.
    boats: [PixelArt; 3],
    /// The same boat in blue, for the other players in a match.
    rivals: [PixelArt; 3],
    island: PixelArt,
}

impl Look {
    fn new() -> Look {
        let left = PixelArt::new(BOAT_LEFT, &BOAT_LEGEND);
        let rival_left = PixelArt::new(BOAT_LEFT, &RIVAL_LEGEND);
        Look {
            sky: sky_palette(),
            sea: Palette::ocean(),
            fire_glow: Palette::new(&[
                Colour::Black,
                Colour::Red,
                Colour::BrightRed,
                Colour::Yellow,
                Colour::BrightYellow,
            ]),
            grey_glow: Palette::new(&[Colour::Black, Colour::BrightBlack, Colour::White]),
            sun_glow: Palette::new(&[
                Colour::Red,
                Colour::BrightRed,
                Colour::Yellow,
                Colour::BrightYellow,
            ]),
            boats: [
                left.clone(),
                PixelArt::new(BOAT_LEVEL, &BOAT_LEGEND),
                left.flipped(),
            ],
            rivals: [
                rival_left.clone(),
                PixelArt::new(BOAT_LEVEL, &RIVAL_LEGEND),
                rival_left.flipped(),
            ],
            island: PixelArt::new(ISLAND, &ISLAND_LEGEND),
        }
    }
}

// ---------------------------------------------------------------------------
// Scenes
// ---------------------------------------------------------------------------

/// The letters of the name, in block capitals, five rows high.
const LETTER_S: &str = r"
#####
#
#####
    #
#####
";
const LETTER_A: &str = r"
 ###
#   #
#####
#   #
#   #
";
const LETTER_I: &str = r"
#####
  #
  #
  #
#####
";
const LETTER_L: &str = r"
#
#
#
#
#####
";

/// Columns from one block letter to the next: five wide and one space.
const LETTER_STEP: i32 = 6;

/// The first screen: the name in block letters, the sea and the sky, and a
/// boat sailing calmly away from an island.
struct Title {
    best: u32,
    look: Look,
    letters: [Sprite; 4],
    tuning: Tuning,
    /// The wave height knob as the last update read it.
    wave_scale: f32,
}

impl Title {
    fn new(best: u32) -> Title {
        Title {
            best,
            look: Look::new(),
            letters: [
                Sprite::new(LETTER_S, Colour::BrightRed),
                Sprite::new(LETTER_A, Colour::BrightYellow),
                Sprite::new(LETTER_I, Colour::BrightGreen),
                Sprite::new(LETTER_L, Colour::BrightCyan),
            ],
            tuning: Tuning::new(),
            wave_scale: 1.0,
        }
    }

    /// Reads the knobs from `tuning` while the title plays, and hands them on.
    fn tuned(mut self, tuning: Tuning) -> Title {
        self.tuning = tuning;
        self
    }
}

impl Game for Title {
    fn update(&mut self, ctx: &mut Context<'_>) -> Next {
        self.wave_scale = wave_scale_of(&self.tuning);
        if ctx.keys.pressed(KeyCode::Enter) {
            Next::switch(Play::new(ctx.seed, self.best).tuned(self.tuning.clone()))
        } else if ctx.keys.pressed(KeyCode::Char('q')) {
            Next::quit()
        } else {
            Next::stay()
        }
    }

    fn draw(&self, screen: &mut Screen) {
        // the title is not paused, so the screen clock is its time; the sky
        // drifts slowly from dawn toward day
        let t = screen.time();
        let rows = screen.height() as f32;
        let water = level(rows);
        let waves = sea_scaled(0.0, t, 0.0, rows, self.wave_scale);
        paint_sky(screen, &self.look.sky, daylight(t * 0.25), 0.0, t, rows);
        paint_sea(screen, &self.look.sea, &waves, t, water);
        // the island scrolls away as the boat sails, one league a second
        paint_island(screen, &self.look, t, &waves, t, water);
        let x = screen.width() as f32 / 3.0;
        let centre = x + BOAT_WIDTH / 2.0;
        let keel = keel_under(&waves, centre, t, water);
        draw_boat(screen, &self.look.boats, x, keel, waves.tilt(centre, t));
        let word = LETTER_STEP * self.letters.len() as i32 - 1;
        let left = (screen.width() - word) / 2;
        // a dark band behind the letters, so they read over the busy sky
        screen.fill(left - 2, 1, word + 4, 7, ' ', Colour::White, Colour::Black);
        for (i, letter) in self.letters.iter().enumerate() {
            screen.sprite(left + LETTER_STEP * i as i32, 2, letter);
        }
        strip(screen, 0, "best ", self.best);
        let keys = "A/D or arrows steer   p pause   q quit";
        let panel = Panel::new(screen, keys.chars().count() as i32, 2, screen.height() - 5);
        panel.draw(screen);
        panel.text_line(screen, 0, "press Enter to sail", Colour::BrightWhite);
        panel.text_line(screen, 1, keys, Colour::White);
    }
}

/// A black strip across row `row` that says `label` and a number.
fn strip(screen: &mut Screen, row: i32, label: &str, n: u32) {
    let width = screen.width();
    screen.fill(0, row, width, 1, ' ', Colour::White, Colour::Black);
    screen.text(1, row, label, Colour::White);
    number(
        screen,
        1 + label.chars().count() as i32,
        row,
        n,
        Colour::White,
    );
}

/// Drawn over the game, which stays as it was while paused.
struct Paused;

impl Game for Paused {
    fn update(&mut self, ctx: &mut Context<'_>) -> Next {
        if ctx.keys.pressed(KeyCode::Char('p')) || ctx.keys.pressed(KeyCode::Esc) {
            Next::pop()
        } else if ctx.keys.pressed(KeyCode::Char('q')) {
            Next::quit()
        } else {
            Next::stay()
        }
    }

    fn draw(&self, screen: &mut Screen) {
        let text = "PAUSED  (p to resume)";
        let width = text.chars().count() as i32;
        let panel = Panel::new(screen, width, 1, (screen.height() - 3) / 2);
        panel.draw(screen);
        panel.text_line(screen, 0, text, Colour::BrightWhite);
    }
}

/// The game-over screen, shown when the last life is lost. The sky stays at the
/// time of day the round ended, and the sea keeps moving.
struct Over {
    score: u32,
    best: u32,
    at: f32,
    progress: f32,
    phase: f32,
    look: Look,
    tuning: Tuning,
    /// The wave height the round ended with, so the sea does not jump.
    wave_scale: f32,
}

impl Over {
    fn new(score: u32, best: u32, at: f32, progress: f32, phase: f32) -> Over {
        Over {
            score,
            best,
            at,
            progress,
            phase,
            look: Look::new(),
            tuning: Tuning::new(),
            wave_scale: 1.0,
        }
    }

    /// Reads the knobs from `tuning`, and passes them on to the next round.
    fn tuned(mut self, tuning: Tuning) -> Over {
        self.tuning = tuning;
        self
    }

    /// The wave height the sea is drawn with, as the round left it.
    fn waves_at(mut self, scale: f32) -> Over {
        self.wave_scale = scale;
        self
    }
}

impl Game for Over {
    fn update(&mut self, ctx: &mut Context<'_>) -> Next {
        self.wave_scale = wave_scale_of(&self.tuning);
        if ctx.keys.pressed(KeyCode::Enter) {
            let seed = ctx.seed.wrapping_add(ctx.tick);
            Next::switch(Play::new(seed, self.best).tuned(self.tuning.clone()))
        } else if ctx.keys.pressed(KeyCode::Char('q')) {
            Next::quit()
        } else {
            Next::stay()
        }
    }

    fn draw(&self, screen: &mut Screen) {
        let t = screen.time();
        let rows = screen.height() as f32;
        let water = level(rows);
        let light = daylight(self.at);
        let waves = sea_scaled(self.progress, t, self.phase, rows, self.wave_scale);
        paint_sky(screen, &self.look.sky, light, 0.0, t, rows);
        paint_stars(screen, night(light), t, (water - 4.0) * 2.0);
        paint_celestial(screen, &self.look, self.at, &waves, t, water);
        paint_sea(screen, &self.look.sea, &waves, t, water);
        // the words sit in a panel up in the sky; it is drawn last, so nothing covers it
        let longest = (OVER_TITLE.chars().count() as i32)
            .max(OVER_HINT.chars().count() as i32)
            .max(6 + digit_count(self.score).max(digit_count(self.best)));
        let top = (screen.height() as f32 * 0.3) as i32;
        let panel = Panel::new(screen, longest, 6, top);
        panel.draw(screen);
        panel.text_line(screen, 0, OVER_TITLE, Colour::BrightRed);
        panel.number_line(screen, 2, "score ", self.score, Colour::BrightYellow);
        panel.number_line(screen, 3, "best ", self.best, Colour::White);
        panel.text_line(screen, 5, OVER_HINT, Colour::White);
    }
}

/// The game-over screen's first line and its last.
const OVER_TITLE: &str = "the sea wins this time";
const OVER_HINT: &str = "Enter: sail again   q: quit";

/// The colours of a panel's border and of the inside it is filled with.
const PANEL_EDGE: Colour = Colour::BrightYellow;
const PANEL_INSIDE: Colour = Colour::Black;

/// A framed panel of text, centred across the screen: a border, and lines of
/// text inside it. Draw it last, after everything it is over.
#[derive(Clone, Copy, Debug)]
struct Panel {
    x: i32,
    y: i32,
    w: i32,
    h: i32,
}

impl Panel {
    /// A panel for lines up to `width` columns wide, `lines` lines tall, with its
    /// top edge `top` rows down. It has two columns of padding inside its border.
    fn new(screen: &Screen, width: i32, lines: i32, top: i32) -> Panel {
        let w = width + 6;
        Panel {
            x: (screen.width() - w) / 2,
            y: top,
            w,
            h: lines + 2,
        }
    }

    /// Draws the border and fills the inside.
    fn draw(&self, screen: &mut Screen) {
        screen.frame(self.x, self.y, self.w, self.h, PANEL_EDGE, PANEL_INSIDE);
    }

    /// Line `line` (from 0) of `text`, centred inside the panel.
    fn text_line(&self, screen: &mut Screen, line: i32, text: &str, colour: Colour) {
        let left = self.x + (self.w - text.chars().count() as i32) / 2;
        screen.text(left, self.y + 1 + line, text, colour);
    }

    /// Line `line` of `label` and then `n`, centred inside the panel.
    fn number_line(&self, screen: &mut Screen, line: i32, label: &str, n: u32, colour: Colour) {
        let label_width = label.chars().count() as i32;
        let left = self.x + (self.w - label_width - digit_count(n)) / 2;
        let row = self.y + 1 + line;
        screen.text(left, row, label, colour);
        number(screen, left + label_width, row, n, colour);
    }
}

/// How many decimal digits `n` has.
fn digit_count(n: u32) -> i32 {
    let mut digits = 1;
    let mut rest = n;
    while rest >= 10 {
        rest /= 10;
        digits += 1;
    }
    digits
}

/// The keys the game answers to.
#[derive(Clone, Copy, PartialEq)]
enum Action {
    Left,
    Right,
    Pause,
}

fn controls() -> Controls<Action> {
    Controls::new()
        .bind(Action::Left, &[KeyCode::Left, KeyCode::Char('a')])
        .bind(Action::Right, &[KeyCode::Right, KeyCode::Char('d')])
        .bind(Action::Pause, &[KeyCode::Char('p'), KeyCode::Esc])
}

// ---------------------------------------------------------------------------
// The simulation: every rule of a round, with no screen, no keys and no clock
// ---------------------------------------------------------------------------

/// The most boats in one sea.
const MAX_BOATS: usize = 8;

/// One update in seconds. The simulation never reads a clock.
const STEP: f32 = 1.0 / 60.0;

/// What one player wants this update: -1 to steer left, 0 to hold, 1 to steer right.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
struct Steer(i8);

/// What the simulation is told about its surroundings, which is not a player's
/// input. In a game on one machine it follows the window and the sliders; in a
/// match between machines it is fixed at the start, so that every machine plays
/// the same sea.
#[derive(Clone, Copy, Debug, PartialEq)]
struct Env {
    /// The width of the sea in columns, and its height in rows.
    width: f32,
    rows: f32,
    wave_scale: f32,
    boat_speed: f32,
    fireball_rate: f32,
}

impl Env {
    /// A sea `size` cells big, with every knob at its default.
    fn new(size: (u32, u32)) -> Env {
        Env {
            width: size.0 as f32,
            rows: size.1 as f32,
            wave_scale: 1.0,
            boat_speed: 1.0,
            fireball_rate: 1.0,
        }
    }

    /// The sea `size` cells big, with the knobs as `tuning` has them now.
    fn tuned(size: (u32, u32), tuning: &Tuning) -> Env {
        Env {
            wave_scale: wave_scale_of(tuning),
            boat_speed: tuning.get("boat_speed", 1.0),
            fireball_rate: tuning.get("fireball_rate", 1.0),
            ..Env::new(size)
        }
    }
}

/// One player's boat and what it has left.
#[derive(Clone, Copy, Debug)]
struct Sailor {
    boat: Boat,
    lives: u32,
    /// Play time until which the boat cannot be hit. Negative infinity means never hit.
    invulnerable_until: f32,
}

/// Something that happened in the last update, for the picture to react to
/// (sparks, steam, a "+5"). It is not part of the rules: it is never hashed.
#[derive(Clone, Copy, Debug, PartialEq)]
enum Fx {
    /// A boat was hit, at column `x`, row `row`.
    Struck { x: f32, row: f32 },
    /// A fireball reached the water.
    Steamed { x: f32, row: f32 },
    /// A fireball passed close to a boat.
    Near { x: f32, y: f32 },
}

/// The rules of a round for one or more boats. It holds no random generator
/// of its own: `step` is given one, so a match can share one stream.
struct SailSim {
    env: Env,
    elapsed: f32,
    /// Leagues sailed so far.
    distance: f32,
    /// Bonus points for fireballs that passed close, for everyone together.
    bonus: u32,
    /// Per run, so that no two seas match.
    phase: f32,
    sailors: Vec<Sailor>,
    fireballs: Pool<Fireball>,
    spawn: Timer,
    /// Whether fireballs are sent at all. Off gives a calm sea to practise on.
    launching: bool,
    /// What happened in the last step.
    fx: Vec<Fx>,
}

impl SailSim {
    /// A round for `players` boats (1 to [`MAX_BOATS`]) in a sea of `env`.
    fn new(players: usize, env: Env, rng: &mut Rng) -> SailSim {
        let phase = rng.f32() * TAU;
        let sailors = (0..players.clamp(1, MAX_BOATS))
            .map(|_| Sailor {
                boat: Boat::new(),
                lives: LIVES,
                // finished from the start, so the boat begins vulnerable
                invulnerable_until: f32::NEG_INFINITY,
            })
            .collect();
        SailSim {
            env,
            elapsed: 0.0,
            distance: 0.0,
            bonus: 0,
            phase,
            sailors,
            fireballs: Pool::with_capacity(FIREBALL_LIMIT),
            spawn: Timer::every(SPAWN_CALM),
            launching: true,
            fx: Vec::with_capacity(8),
        }
    }

    /// The score: a point for every tenth of a league sailed, and the bonuses.
    fn score(&self) -> u32 {
        ((self.distance * 10.0).floor() as u32).saturating_add(self.bonus)
    }

    /// Whether every boat has lost its last life.
    fn over(&self) -> bool {
        self.sailors.iter().all(|s| s.lives == 0)
    }

    /// Runs one update: `inputs[i]` steers boat `i`, and a missing input holds.
    fn advance(&mut self, inputs: &[Steer], rng: &mut Rng) {
        self.fx.clear();
        let dt = STEP;
        let (width, rows) = (self.env.width, self.env.rows);
        let water = level(rows);
        self.elapsed += dt;
        self.distance += sail_speed(progress_of(self.distance)) * dt;
        let progress = progress_of(self.distance);
        let t = self.elapsed;
        let waves = sea_scaled(progress, t, self.phase, rows, self.env.wave_scale);

        for (i, sailor) in self.sailors.iter_mut().enumerate() {
            if sailor.lives == 0 {
                continue;
            }
            let boat = &mut sailor.boat;
            // boats start side by side, the first a third of the way across; they
            // may overlap, because the sea is small and boats do not collide
            boat.place(width, 0.3 + 0.1 * i as f32, |x| {
                keel_under(&waves, x, t, water)
            });
            let across = inputs.get(i).copied().unwrap_or_default().0.clamp(-1, 1) as f32;
            boat.steer(
                across * SAIL_SPEED * self.env.boat_speed,
                dt,
                width * 0.2,
                width * 0.6,
            );
            let target = keel_under(&waves, boat.centre(), t, water);
            boat.settle(target, dt);
        }

        self.spawn
            .set_seconds(spawn_interval(progress) / self.env.fireball_rate);
        let horizon = 2.0 * water;
        let due = if self.launching {
            self.spawn.ticks(dt)
        } else {
            0
        };
        for _ in 0..due {
            self.launch(width, horizon, progress, rng);
        }
        self.fly_fireballs(dt, &waves, water);
    }

    /// The column of the middle of a boat to aim at: the only one still afloat,
    /// or a random one of those. `None` once every boat is lost.
    fn aim_at(&self, rng: &mut Rng) -> Option<f32> {
        let alive = self.sailors.iter().filter(|s| s.lives > 0).count();
        let skip = if alive > 1 {
            rng.range_i32(0, alive as i32) as usize
        } else {
            0
        };
        self.sailors
            .iter()
            .filter(|s| s.lives > 0)
            .nth(skip)
            .map(|s| s.boat.centre())
    }

    /// Sends one fireball, or a volley of two or three, down from above the top.
    fn launch(&mut self, width: f32, horizon: f32, progress: f32, rng: &mut Rng) {
        let volley = if rng.chance(volley_chance(progress)) {
            2 + rng.range_i32(0, 2)
        } else {
            1
        };
        for _ in 0..volley {
            let f = self.new_fireball(width, horizon, progress, rng);
            let _ = self.fireballs.push(f);
        }
    }

    /// A fireball from above the top. Most are dropped at random across the
    /// screen; some are aimed where a boat will be, so they land on it.
    fn new_fireball(&mut self, width: f32, horizon: f32, progress: f32, rng: &mut Rng) -> Fireball {
        let scale = fall_scale(progress);
        let vx = -rng.range_f32(WIND_MIN, WIND_MAX);
        let vy = FALL_START * scale;
        let gravity = FALL_GRAVITY * scale;
        let x = if rng.chance(AIM_CHANCE) {
            let boat_at = self.aim_at(rng).unwrap_or(width * 0.3);
            let aim = boat_at + rng.range_f32(-AIM_SPREAD, AIM_SPREAD);
            // the wind carries it left, so start it as far right as it will drift
            let fall = fall_time(horizon - FALL_FROM, vy, gravity);
            aim - vx * fall
        } else {
            lerp(0.3 * width, 1.15 * width, rng.f32())
        };
        Fireball::new(x, FALL_FROM, vx, vy, gravity)
    }

    /// Moves every fireball, strikes the first boat each flying one touches,
    /// and sinks any that reach the water. A fireball that passes close to a
    /// boat scores once for it.
    fn fly_fireballs(&mut self, dt: f32, waves: &Waves, water: f32) {
        let t = self.elapsed;
        let mut struck = [false; MAX_BOATS];
        for f in self.fireballs.iter_mut() {
            match f.stage {
                Stage::Flying => {
                    f.fall(dt);
                    let hit = self.sailors.iter().enumerate().position(|(i, s)| {
                        s.lives > 0
                            && t >= s.invulnerable_until
                            && !struck[i]
                            && s.boat.hit().overlaps(&f.hit_shape())
                    });
                    if let Some(i) = hit {
                        struck[i] = true;
                        f.stage = Stage::Spent;
                        continue;
                    }
                    if f.y >= 2.0 * waves.surface_y(f.x, t, water) {
                        f.stage = Stage::Sinking(0.0);
                        self.fx.push(Fx::Steamed {
                            x: f.x,
                            row: f.y / 2.0,
                        });
                    } else if f.x < OFF_LEFT {
                        f.stage = Stage::Spent;
                    }
                    for (i, s) in self.sailors.iter().enumerate() {
                        let bit = 1u8 << i;
                        if s.lives == 0 || f.passed & bit != 0 || f.x > s.boat.centre() {
                            continue;
                        }
                        f.passed |= bit;
                        let (top, bottom) = (s.boat.top(), s.boat.top() + BOAT_HEIGHT);
                        let gap = gap_to_boat(f.y, top, bottom);
                        if f.stage == Stage::Flying && gap <= NEAR_PX {
                            self.bonus += NEAR_BONUS;
                            self.fx.push(Fx::Near {
                                x: s.boat.centre(),
                                y: top / 2.0,
                            });
                        }
                    }
                }
                Stage::Sinking(_) => f.sink(dt),
                Stage::Spent => {}
            }
        }
        for (i, sailor) in self.sailors.iter_mut().enumerate() {
            if struck[i] {
                sailor.lives = sailor.lives.saturating_sub(1);
                sailor.invulnerable_until = t + INVULNERABLE_SECONDS;
                self.fx.push(Fx::Struck {
                    x: sailor.boat.centre(),
                    row: sailor.boat.keel / 2.0 - 1.5,
                });
            }
        }
        self.fireballs.retain(|f| f.stage != Stage::Spent);
    }
}

impl Encode for Steer {
    fn encode(&self, out: &mut Vec<u8>) {
        out.push(self.0 as u8);
    }
}

impl Decode for Steer {
    fn decode(r: &mut Reader<'_>) -> Result<Steer, DecodeError> {
        Ok(Steer(r.u8()? as i8))
    }
}

impl Sim for SailSim {
    type Input = Steer;

    fn step(&mut self, inputs: &[Steer], rng: &mut Rng) {
        self.advance(inputs, rng);
    }

    /// Everything the rules read or write. The events in `fx` are left out:
    /// they are for the picture.
    fn hash(&self, h: &mut Hasher) {
        let env = &self.env;
        h.f32(env.width)
            .f32(env.rows)
            .f32(env.wave_scale)
            .f32(env.boat_speed)
            .f32(env.fireball_rate);
        h.f32(self.elapsed)
            .f32(self.distance)
            .u32(self.bonus)
            .f32(self.phase)
            .bool(self.launching)
            .f32(self.spawn.remaining());
        for s in &self.sailors {
            h.f32(s.boat.x)
                .f32(s.boat.vx)
                .f32(s.boat.keel)
                .f32(s.boat.keel_v)
                .u32(s.lives)
                .f32(s.invulnerable_until);
        }
        h.u32(self.fireballs.len() as u32);
        for f in self.fireballs.iter() {
            h.f32(f.x)
                .f32(f.y)
                .f32(f.vx)
                .f32(f.vy)
                .f32(f.gravity)
                .u8(f.passed);
            match f.stage {
                Stage::Flying => h.u8(0),
                Stage::Sinking(age) => h.u8(1).f32(age),
                Stage::Spent => h.u8(2),
            };
        }
    }
}

// ---------------------------------------------------------------------------
// The view: sparks, steam and spray. Looks only, so it has its own random
// numbers and never changes the rules.
// ---------------------------------------------------------------------------

struct View {
    rng: Rng,
    embers: Particles,
    steam: Particles,
    spray: Particles,
    wake: Timer,
    floaters: Pool<Floater>,
    /// Play time until which the screen flashes after a hit.
    flash_until: f32,
}

impl View {
    fn new(seed: u64) -> View {
        View {
            rng: Rng::new(seed ^ 0x5eed_c0de),
            embers: Particles::new(EMBER_LIMIT).gravity(EMBER_RISE).drag(0.5),
            steam: Particles::new(STEAM_LIMIT)
                .gravity(-6.0)
                .drag(0.5)
                .palette(Palette::new(&[
                    Colour::BrightBlack,
                    Colour::White,
                    Colour::BrightWhite,
                ])),
            spray: Particles::new(SPRAY_LIMIT)
                .gravity(SPRAY_FALL)
                .drag(0.2)
                .palette(Palette::new(&[
                    Colour::Cyan,
                    Colour::BrightCyan,
                    Colour::White,
                    Colour::BrightWhite,
                ])),
            wake: Timer::every(WAKE_SECONDS),
            floaters: Pool::with_capacity(FLOATER_LIMIT),
            flash_until: f32::NEG_INFINITY,
        }
    }

    /// Whether the screen is flashing after a hit, at play time `elapsed`.
    fn flashing(&self, elapsed: f32) -> bool {
        elapsed < self.flash_until
    }

    /// Moves the effects on by one update of `sim`, and reacts to what just
    /// happened in it.
    fn observe(&mut self, sim: &SailSim) {
        let dt = STEP;
        // the boats always sail forward, so each leaves a wake behind its stern
        if self.wake.tick(dt) {
            for s in sim.sailors.iter().filter(|s| s.lives > 0) {
                self.spray
                    .emit(s.boat.x, s.boat.keel / 2.0, -2.0, -1.5, 0.5);
            }
        }
        self.spray.step(dt);
        self.steam.step(dt);
        self.embers.step(dt);

        for fx in &sim.fx {
            match *fx {
                Fx::Struck { x, row } => {
                    self.embers.burst(&mut self.rng, x, row, 40, 14.0, 1.0);
                    self.flash_until = sim.elapsed + FLASH_SECONDS;
                }
                Fx::Steamed { x, row } => {
                    self.steam
                        .burst(&mut self.rng, x, row, STEAM_BURST, 6.0, 1.2);
                    self.spray.burst(&mut self.rng, x, row, DROPLETS, 5.0, 0.6);
                }
                Fx::Near { x, y } => {
                    let _ = self.floaters.push(Floater { x, y, age: 0.0 });
                }
            }
        }
        // every fireball that is still flying leaves embers behind it
        for f in sim.fireballs.iter() {
            if f.stage != Stage::Flying {
                continue;
            }
            for _ in 0..EMBERS_PER_TICK {
                let vx = self.rng.range_f32(0.5, 2.0);
                let vy = self.rng.range_f32(-1.5, 0.0);
                self.embers.emit(f.x + 1.0, f.y / 2.0, vx, vy, EMBER_LIFE);
            }
        }
        for floater in self.floaters.iter_mut() {
            floater.y -= FLOATER_RISE * dt;
            floater.age += dt;
        }
        self.floaters.retain(|floater| floater.age < FLOATER_LIFE);
    }
}

/// The wave height knob's value, or 1 when no knob is set.
fn wave_scale_of(tuning: &Tuning) -> f32 {
    tuning.get("wave_height", 1.0)
}

/// Draws a round for the player `me`: sky, sea, boats, fireballs, effects, HUD.
/// Every value here comes from play time, so a paused game does not move.
fn draw_round(screen: &mut Screen, look: &Look, sim: &SailSim, view: &View, me: usize, best: u32) {
    let t = sim.elapsed;
    let water = level(screen.height() as f32);
    let progress = progress_of(sim.distance);
    let waves = sea_scaled(
        progress,
        t,
        sim.phase,
        screen.height() as f32,
        sim.env.wave_scale,
    );
    let light = daylight(t);
    let flash = if view.flashing(t) { 1.0 } else { 0.0 };
    paint_sky(screen, &look.sky, light, flash, t, screen.height() as f32);
    paint_stars(screen, night(light), t, (water - 4.0) * 2.0);
    paint_celestial(screen, look, t, &waves, t, water);
    paint_sea(screen, &look.sea, &waves, t, water);
    paint_island(screen, look, sim.distance, &waves, t, water);
    view.steam.draw(screen);
    view.embers.draw(screen);
    view.spray.draw(screen);
    for f in sim.fireballs.iter() {
        draw_fireball(screen, look, f);
    }
    for floater in view.floaters.iter() {
        let colour = if floater.age < 0.4 {
            Colour::BrightYellow
        } else {
            Colour::Yellow
        };
        let x = floater.x.round() as i32 - 1;
        screen.text(x, floater.y.round() as i32, "+5", colour);
    }
    // the other players' boats first, so your own is always on top
    for (_, s) in sim.sailors.iter().enumerate().filter(|(i, _)| *i != me) {
        if s.lives > 0 && boat_visible(t, s.invulnerable_until) {
            let tilt = waves.tilt(s.boat.centre(), t);
            draw_boat(screen, &look.rivals, s.boat.x, s.boat.keel, tilt);
        }
    }
    if let Some(mine) = sim.sailors.get(me) {
        if mine.lives > 0 && boat_visible(t, mine.invulnerable_until) {
            let tilt = waves.tilt(mine.boat.centre(), t);
            draw_boat(screen, &look.boats, mine.boat.x, mine.boat.keel, tilt);
        }
    }
    let mut lives = [0; MAX_BOATS];
    for (slot, s) in lives.iter_mut().zip(&sim.sailors) {
        *slot = s.lives;
    }
    let hud = Hud {
        tenths: (sim.distance * 10.0).floor() as u32,
        score: sim.score(),
        best,
        lives,
        players: sim.sailors.len(),
        me,
        time: time_of_day(t),
    };
    draw_hud(screen, &hud);
}

/// A solo round: one boat, steered by the keys, on this machine.
struct Play {
    best: u32,
    look: Look,
    sim: SailSim,
    /// The sim's random numbers.
    rng: Rng,
    view: View,
    controls: Controls<Action>,
    /// The knobs the page may change while the round runs.
    tuning: Tuning,
}

impl Play {
    fn new(seed: u64, best: u32) -> Play {
        let mut rng = Rng::new(seed);
        let sim = SailSim::new(1, Env::new((80, 24)), &mut rng);
        Play {
            best,
            look: Look::new(),
            tuning: Tuning::new(),
            sim,
            rng,
            view: View::new(seed),
            controls: controls(),
        }
    }

    /// Reads the knobs from `tuning` while the round runs.
    fn tuned(mut self, tuning: Tuning) -> Play {
        self.tuning = tuning;
        self
    }

    fn score(&self) -> u32 {
        self.sim.score()
    }
}

impl Game for Play {
    fn draw(&self, screen: &mut Screen) {
        draw_round(screen, &self.look, &self.sim, &self.view, 0, self.best);
    }

    fn update(&mut self, ctx: &mut Context<'_>) -> Next {
        // checked before anything moves, so a paused round stands still
        if self.controls.pressed(ctx.keys, Action::Pause) {
            return Next::push(Paused);
        }
        if ctx.keys.pressed(KeyCode::Char('q')) {
            return Next::quit();
        }
        self.sim.env = Env::tuned(ctx.size, &self.tuning);
        let across = self.controls.axis(ctx.keys, Action::Left, Action::Right);
        self.sim.step(&[Steer(across as i8)], &mut self.rng);
        self.view.observe(&self.sim);
        if self.sim.over() {
            let best = self.best.max(self.score());
            let progress = progress_of(self.sim.distance);
            let over = Over::new(
                self.score(),
                best,
                self.sim.elapsed,
                progress,
                self.sim.phase,
            );
            return Next::switch(
                over.tuned(self.tuning.clone())
                    .waves_at(self.sim.env.wave_scale),
            );
        }
        Next::stay()
    }
}

// ---------------------------------------------------------------------------
// Playing together: the same rules on several machines
// ---------------------------------------------------------------------------

/// What every machine in a match must agree on before it starts. The host
/// makes it and sends it with `announce`; the others read it with
/// `await_message`.
#[derive(Clone, Debug, PartialEq, Eq)]
#[allow(dead_code)] // used by the `sail_together` example, which includes this file
pub struct Settings {
    /// The seed of the shared random numbers.
    pub seed: u64,
    /// The size of the sea in columns and rows, the host's window. Every window must be at least
    /// this big (one row more, for the terminal).
    pub width: u32,
    pub rows: u32,
    /// How many steps a key press waits before it takes effect.
    pub delay: u32,
}

#[allow(dead_code)]
impl Settings {
    /// A sea of 80 by 24 and an input delay of 3 steps (50 ms); see [`Settings::sized`] for one as big as a window.
    pub fn new(seed: u64) -> Settings {
        Settings {
            seed,
            width: 80,
            rows: 24,
            delay: 3,
        }
    }

    /// A sea as big as a host's window of `columns` by `window_rows`: the
    /// game uses one row less than the window, which the terminal needs.
    pub fn sized(seed: u64, columns: u32, window_rows: u32) -> Settings {
        Settings {
            width: columns.max(1),
            rows: window_rows.saturating_sub(1).max(1),
            ..Settings::new(seed)
        }
    }
}

impl Encode for Settings {
    fn encode(&self, out: &mut Vec<u8>) {
        self.seed.encode(out);
        self.width.encode(out);
        self.rows.encode(out);
        self.delay.encode(out);
    }
}

impl Decode for Settings {
    fn decode(r: &mut Reader<'_>) -> Result<Settings, DecodeError> {
        Ok(Settings {
            seed: r.u64()?,
            width: r.u32()?,
            rows: r.u32()?,
            delay: r.u32()?,
        })
    }
}

/// Where a match stands, for the words shown over the sea.
#[derive(Debug)]
enum Status {
    Playing,
    /// Waiting for these players' inputs to arrive.
    Waiting(Vec<PlayerId>),
    /// Every boat is lost.
    Over,
    /// The match cannot go on; these lines say why.
    Stopped(Vec<String>),
}

/// A match: the same sea on every machine, one boat for each player.
struct Together<T: Transport> {
    lock: Lockstep<SailSim, T>,
    view: View,
    look: Look,
    controls: Controls<Action>,
    size: (u32, u32),
    me: usize,
    status: Status,
    /// The sea is drawn here at its agreed size, then copied into the window.
    world: RefCell<Screen>,
}

impl<T: Transport> Together<T> {
    fn new(transport: T, config: Config, settings: &Settings) -> Together<T> {
        let config = config.seed(settings.seed).delay(settings.delay);
        let size = (settings.width.max(1), settings.rows.max(1));
        let mut setup = Rng::new(settings.seed ^ 0x5a11);
        let sim = SailSim::new(config.players(), Env::new(size), &mut setup);
        let me = config.me().index();
        Together {
            view: View::new(settings.seed ^ me as u64),
            look: Look::new(),
            controls: controls(),
            size,
            me,
            status: Status::Playing,
            world: RefCell::new(Screen::new(size.0, size.1)),
            lock: Lockstep::new(sim, transport, config),
        }
    }

    /// The lines to show in a panel over the sea, if there is something to say.
    fn words(&self) -> Option<Vec<String>> {
        match &self.status {
            Status::Playing => None,
            Status::Waiting(players) => {
                let names: Vec<String> = players.iter().map(|p| (p.0 + 1).to_string()).collect();
                let noun = if names.len() == 1 {
                    "player"
                } else {
                    "players"
                };
                Some(vec![format!("waiting for {noun} {}", names.join(" and "))])
            }
            Status::Over => Some(vec![
                OVER_TITLE.to_string(),
                format!("score {}", self.lock.sim().score()),
                "q: quit".to_string(),
            ]),
            Status::Stopped(lines) => {
                let mut lines = lines.clone();
                lines.push("q: quit".to_string());
                Some(lines)
            }
        }
    }
}

impl<T: Transport> Game for Together<T> {
    fn update(&mut self, ctx: &mut Context<'_>) -> Next {
        if ctx.keys.pressed(KeyCode::Char('q')) {
            let _ = self.lock.leave();
            return Next::quit();
        }
        if matches!(self.status, Status::Over | Status::Stopped(_)) {
            return Next::stay();
        }
        let across = self.controls.axis(ctx.keys, Action::Left, Action::Right);
        let view = &mut self.view;
        let result = self.lock.tick(Steer(across as i8), |sim| view.observe(sim));
        self.status = match result {
            Ok(Progress::Advanced(_)) if self.lock.sim().over() => Status::Over,
            Ok(Progress::Advanced(_)) => Status::Playing,
            Ok(Progress::Stalled { waiting_for }) => Status::Waiting(waiting_for),
            Ok(Progress::Desync(d)) => Status::Stopped(vec![
                "the two games drifted apart".to_string(),
                format!("between step {} and step {}", d.last_agreed, d.tick),
                "are you both running the same version?".to_string(),
            ]),
            Ok(Progress::Lost(player)) => {
                Status::Stopped(vec![format!("player {} left the game", player.0 + 1)])
            }
            Err(e) => Status::Stopped(vec![format!("the connection failed: {e}")]),
        };
        Next::stay()
    }

    fn draw(&self, screen: &mut Screen) {
        let (width, rows) = self.size;
        screen.clear(Colour::Black);
        if screen.width() < width as i32 || screen.height() < rows as i32 {
            let text = format!(
                "make the window at least {width} columns by {} rows (it is {} by {})",
                rows + 1,
                screen.width(),
                screen.height() + 1
            );
            screen.text_centred(screen.height() / 2, &text, Colour::BrightWhite);
            return;
        }
        {
            let mut world = self.world.borrow_mut();
            world.clear(Colour::Black);
            draw_round(
                &mut world,
                &self.look,
                self.lock.sim(),
                &self.view,
                self.me,
                0,
            );
            world.finish_frame();
            screen.blit(&world, (screen.width() - width as i32) / 2, 0);
        }
        if let Some(lines) = self.words() {
            let longest = lines.iter().map(|l| l.chars().count()).max().unwrap_or(0);
            let panel = Panel::new(screen, longest as i32, lines.len() as i32, rows as i32 / 4);
            panel.draw(screen);
            for (i, line) in lines.iter().enumerate() {
                panel.text_line(screen, i as i32, line, Colour::BrightWhite);
            }
        }
    }
}

/// A match over `transport`: `config` says how many players there are and
/// which one this machine is; `settings` is what the host announced. Play it
/// with `run`. The host is player 0; see `examples/sail_together.rs`.
#[allow(dead_code)]
pub fn together<T: Transport + 'static>(
    transport: T,
    config: Config,
    settings: &Settings,
) -> impl Game {
    Together::new(transport, config, settings)
}
#[cfg(test)]
mod tests {
    use super::*;
    use std::time::Duration;

    /// Drives a [`Play`] one update at a time, with its own keys and clock.
    struct Rig {
        keys: Keys,
        pointer: Pointer,
        tick: u64,
        size: (u32, u32),
    }

    impl Rig {
        fn new(size: (u32, u32)) -> Rig {
            Rig {
                keys: Keys::new().real_release(true),
                pointer: Pointer::default(),
                tick: 0,
                size,
            }
        }

        /// The time of the next update, as the keys see it.
        fn now(&self) -> Duration {
            Duration::from_secs_f64(self.tick as f64 / 60.0)
        }

        fn press(&mut self, code: KeyCode) {
            let now = self.now();
            self.keys.event(&Event::Key(Key::new(code)), now);
        }

        fn release(&mut self, code: KeyCode) {
            let now = self.now();
            self.keys.event(&Event::KeyUp(Key::new(code)), now);
        }

        /// Runs one update of `play` and returns what it asked for.
        fn update(&mut self, play: &mut impl Game) -> Next {
            let now = self.now();
            self.keys.tick(now);
            let mut ctx = Context {
                keys: &self.keys,
                pointer: &self.pointer,
                dt: 1.0 / 60.0,
                tick: self.tick,
                size: self.size,
                seed: 7,
                players: 1,
                me: PlayerId(0),
            };
            let next = play.update(&mut ctx);
            self.keys.end_tick();
            self.tick += 1;
            next
        }

        fn run(&mut self, play: &mut Play, ticks: u32) {
            for _ in 0..ticks {
                self.update(play);
            }
        }
    }

    /// The sea as the game has it right now.
    fn waves_now(play: &Play, rows: f32) -> Waves {
        sea(
            progress_of(play.sim.distance),
            play.sim.elapsed,
            play.sim.phase,
            rows,
        )
    }

    /// The keel row the water asks for under the boat's middle, now.
    fn keel_wanted(play: &Play, rows: f32) -> f32 {
        keel_under(
            &waves_now(play, rows),
            play.sim.sailors[0].boat.centre(),
            play.sim.elapsed,
            level(rows),
        )
    }

    /// A play with no random fireballs, so a test can place its own.
    fn quiet(seed: u64) -> Play {
        let mut play = Play::new(seed, 0);
        play.sim.launching = false;
        play
    }

    /// The sky cell at column `x`, `y_rows` rows down a sky `height_rows` tall.
    fn sky_cell(x: f32, y_rows: f32, height_rows: f32) -> Cell {
        Cell {
            x,
            y: y_rows * 2.0,
            t: 0.0,
            mouse_x: 0.0,
            mouse_y: 0.0,
            mouse_down: false,
            width: 80.0,
            height: height_rows * 2.0,
        }
    }

    /// Draws `play` on a fresh screen and finishes the frame, as the loop does.
    fn frame(play: &Play, width: u32, height: u32) -> Screen {
        let mut screen = Screen::new(width, height);
        screen.clear(Colour::Black);
        play.draw(&mut screen);
        screen.finish_frame();
        screen
    }

    #[test]
    fn the_hop_keys_do_nothing_because_a_sailboat_does_not_jump() {
        let mut play = Play::new(1, 0);
        let mut rig = Rig::new((80, 24));
        rig.run(&mut play, 120);
        for code in [KeyCode::Char(' '), KeyCode::Up, KeyCode::Char('w')] {
            rig.press(code);
            rig.update(&mut play);
            rig.release(code);
            let gap = (play.sim.sailors[0].boat.keel - keel_wanted(&play, 24.0)).abs();
            assert!(
                gap < 2.0,
                "{code:?} must not lift the boat: {gap} pixels off"
            );
            rig.run(&mut play, 30);
        }
    }

    #[test]
    fn the_boat_stays_between_a_fifth_and_three_fifths_of_the_width() {
        let mut play = Play::new(1, 0);
        let mut rig = Rig::new((80, 24));
        rig.run(&mut play, 1);
        assert!(
            (play.sim.sailors[0].boat.x - 24.0).abs() < 0.01,
            "a third of the way across: {}",
            play.sim.sailors[0].boat.x
        );
        rig.press(KeyCode::Right);
        rig.run(&mut play, 600);
        assert!(
            (play.sim.sailors[0].boat.x - 48.0).abs() < 0.01,
            "stopped at 0.6 of 80: {}",
            play.sim.sailors[0].boat.x
        );
        rig.release(KeyCode::Right);
        rig.press(KeyCode::Left);
        rig.run(&mut play, 600);
        assert!(
            (play.sim.sailors[0].boat.x - 16.0).abs() < 0.01,
            "stopped at 0.2 of 80: {}",
            play.sim.sailors[0].boat.x
        );
    }

    #[test]
    fn the_boat_follows_the_water_once_settled() {
        // at the roughest sea the swell is several pixels high, so a boat that
        // ignored the water would be far off it; the boat must keep up
        let mut play = Play::new(1, 0);
        play.sim.launching = false; // a hit would end the round and park the boat
        play.sim.distance = DISTANCE_MAX;
        let mut rig = Rig::new((80, 24));
        rig.run(&mut play, 300);
        let mut worst = 0.0_f32;
        for _ in 0..600 {
            rig.update(&mut play);
            worst = worst.max((play.sim.sailors[0].boat.keel - keel_wanted(&play, 24.0)).abs());
        }
        // the spring trails the fastest swells by up to two pixels; a boat that
        // ignored the water is more than eight pixels off it at the storm
        assert!(
            worst <= 2.5,
            "the keel was {worst} pixels off the water at its worst"
        );
    }

    #[test]
    fn distance_grows_by_about_one_league_a_second_at_the_start() {
        let mut play = Play::new(1, 0);
        let mut rig = Rig::new((80, 24));
        rig.run(&mut play, 60);
        assert!(
            (0.99..1.03).contains(&play.sim.distance),
            "one league in the first second: {}",
            play.sim.distance
        );
    }

    #[test]
    fn progress_is_zero_at_the_start_grows_with_distance_and_is_clamped() {
        assert_eq!(progress_of(0.0), 0.0);
        assert!((progress_of(DISTANCE_MAX / 2.0) - 0.5).abs() < 1e-6);
        assert_eq!(progress_of(DISTANCE_MAX * 9.0), 1.0, "clamped at the top");
        assert_eq!(progress_of(-4.0), 0.0, "never below zero");
        assert_eq!(progress_of(f32::NAN), 0.0, "NaN counts as zero");
    }

    #[test]
    fn the_swells_shorten_and_grow_steadily_from_calm_to_rough() {
        let mut last = swells(0.0, 0.7);
        for i in 1..=100 {
            let now = swells(i as f32 / 100.0, 0.7);
            for layer in 0..4 {
                assert!(
                    now[layer].1 <= last[layer].1 + 1e-4,
                    "wavelength {layer} at {i}"
                );
                assert!(
                    now[layer].0 >= last[layer].0 - 1e-6,
                    "height {layer} at {i}"
                );
            }
            last = now;
        }
    }

    #[test]
    fn the_calm_sea_has_long_low_swells_and_the_rough_one_short_high_ones() {
        let calm = swells(0.0, 0.0);
        assert!(calm[0].1 >= 35.0, "a long first swell: {}", calm[0].1);
        assert!(calm[0].0 <= 0.6, "a low first swell: {}", calm[0].0);
        let rough = swells(1.0, 0.0);
        assert!(
            rough[0].0 >= 2.0,
            "a high first swell at the end: {}",
            rough[0].0
        );
        assert!(calm[3].0 == 0.0, "the fourth swell starts from nothing");
    }

    #[test]
    fn rebuilding_the_sea_each_tick_never_makes_a_column_jump_more_than_0_15_rows() {
        let phase = 1.3;
        let dt = 1.0 / 60.0;
        let mut distance = 0.0_f32;
        let mut elapsed = 0.0_f32;
        let mut previous = sea(0.0, 0.0, phase, 24.0);
        let mut worst = 0.0_f32;
        for _ in 0..12000 {
            let progress = progress_of(distance);
            elapsed += dt;
            let waves = sea(progress, elapsed, phase, 24.0);
            // the same moment on both sides, so only the rebuild can change the height
            for x in 0..80 {
                let jump =
                    (waves.height(x as f32, elapsed) - previous.height(x as f32, elapsed)).abs();
                worst = worst.max(jump);
            }
            previous = waves;
            distance += sail_speed(progress) * dt;
        }
        assert!(worst <= 0.15, "the sea jumped by {worst} rows in one tick");
    }

    #[test]
    fn fireballs_come_from_above_the_top_fall_and_drift_left() {
        let mut play = quiet(1);
        let mut rig = Rig::new((80, 24));
        rig.run(&mut play, 1);
        play.sim.launch(80.0, 30.0, 0.0, &mut play.rng);
        let f = *play.sim.fireballs.get(0).expect("one fireball");
        assert!(f.y < 0.0, "it starts above the top: {}", f.y);
        assert!((-10.2..=-3.4).contains(&f.vx), "wind to the left: {}", f.vx);
        rig.run(&mut play, 30);
        let later = *play.sim.fireballs.get(0).expect("still in the air");
        assert!(later.y > f.y, "it falls: {} then {}", f.y, later.y);
        assert!(later.x < f.x, "it drifts left");
    }

    #[test]
    fn fireballs_fall_faster_and_come_quicker_as_the_voyage_goes_on() {
        assert!((spawn_interval(0.0) - 1.8).abs() < 1e-5, "first gap 1.8 s");
        assert!((spawn_interval(1.0) - 0.4).abs() < 1e-5, "last gap 0.4 s");
        let mut last = f32::MAX;
        for i in 0..=100 {
            let gap = spawn_interval(i as f32 / 100.0);
            assert!(gap <= last + 1e-6, "the gap rose at {i}");
            last = gap;
        }
        assert!((fall_scale(0.0) - 1.0).abs() < 1e-5);
        assert!(
            (fall_scale(1.0) - 1.6).abs() < 1e-5,
            "the top speed is 1.6 times the start"
        );
        let mut last_scale = 0.0_f32;
        for i in 0..=100 {
            let scale = fall_scale(i as f32 / 100.0);
            assert!(
                scale >= last_scale - 1e-6,
                "the fall speed fell back at {i}"
            );
            last_scale = scale;
        }
    }

    #[test]
    fn volleys_are_never_at_the_start_and_grow_to_0_35_at_the_end() {
        assert_eq!(volley_chance(0.0), 0.0, "no volleys at the start");
        assert!((volley_chance(1.0) - 0.35).abs() < 1e-5);
    }

    #[test]
    fn a_fireball_that_reaches_the_water_sinks_instead_of_vanishing() {
        let mut play = quiet(1);
        let mut rig = Rig::new((80, 24));
        rig.run(&mut play, 1);
        let x = 60.0;
        let water = 2.0 * waves_now(&play, 24.0).surface_y(x, play.sim.elapsed, level(24.0));
        assert!(play
            .sim
            .fireballs
            .push(Fireball::new(x, water + 0.5, -6.0, 0.0, 0.0))
            .is_ok());
        rig.update(&mut play);
        let f = *play.sim.fireballs.get(0).expect("it is still there");
        assert!(matches!(f.stage, Stage::Sinking(_)), "{:?}", f.stage);
    }

    #[test]
    fn a_sinking_fireball_is_removed_after_1_2_seconds() {
        let mut play = quiet(1);
        let mut rig = Rig::new((80, 24));
        rig.run(&mut play, 1);
        assert!(play
            .sim
            .fireballs
            .push(Fireball::new(60.0, 40.0, -6.0, 0.0, 0.0))
            .is_ok());
        play.sim
            .fireballs
            .iter_mut()
            .for_each(|f| f.stage = Stage::Sinking(0.0));
        rig.run(&mut play, 60); // one second in
        assert_eq!(play.sim.fireballs.len(), 1, "still sinking at 1 s");
        rig.run(&mut play, 20); // 1.33 s in
        assert!(play.sim.fireballs.is_empty(), "gone after 1.2 s");
    }

    #[test]
    fn a_sinking_fireball_cannot_hit_the_boat() {
        let mut play = quiet(1);
        let mut rig = Rig::new((80, 24));
        rig.run(&mut play, 1);
        let boat = play.sim.sailors[0].boat;
        let mut f = Fireball::new(boat.centre(), boat.top() + 3.0, 0.0, 0.0, 0.0);
        f.stage = Stage::Sinking(0.0);
        assert!(play.sim.fireballs.push(f).is_ok());
        rig.update(&mut play);
        assert_eq!(
            play.sim.sailors[0].lives, LIVES,
            "the sinking one does nothing"
        );
    }

    #[test]
    fn a_sinking_fireball_steps_toward_grey_and_shrinks() {
        let mut last = 0;
        for i in 0..=100 {
            let step = sink_step(i as f32 / 100.0);
            assert!(step >= last, "the colour went back at {i}");
            last = step;
        }
        let young = Fireball {
            stage: Stage::Sinking(0.0),
            ..Fireball::new(0.0, 0.0, 0.0, 0.0, 0.0)
        };
        let old = Fireball {
            stage: Stage::Sinking(SINK_SECONDS * 0.9),
            ..young
        };
        assert!(old.radius() < young.radius(), "it shrinks");
        assert!(old.radius() > 0.0, "and is not gone yet");
        assert!(matches!(sink_colour(0.0), Colour::BrightYellow));
        assert!(matches!(sink_colour(1.0), Colour::Blue));
    }

    #[test]
    fn a_fireball_reaching_the_water_throws_up_a_cloud_of_steam() {
        let mut play = quiet(1);
        let mut rig = Rig::new((80, 24));
        rig.run(&mut play, 1);
        let water = 2.0 * waves_now(&play, 24.0).surface_y(60.0, play.sim.elapsed, level(24.0));
        assert!(play
            .sim
            .fireballs
            .push(Fireball::new(60.0, water + 0.5, -6.0, 0.0, 0.0))
            .is_ok());
        rig.update(&mut play);
        assert!(
            play.view.steam.len() >= STEAM_BURST,
            "steam: {}",
            play.view.steam.len()
        );
    }

    #[test]
    fn a_falling_fireball_on_the_boat_hits_it_and_costs_a_life() {
        let mut play = quiet(1);
        let mut rig = Rig::new((80, 24));
        rig.run(&mut play, 1);
        let boat = play.sim.sailors[0].boat;
        let hit = Fireball::new(boat.centre(), boat.top() + 3.0, 0.0, 0.0, 0.0);
        assert!(play.sim.fireballs.push(hit).is_ok());
        rig.update(&mut play);
        assert_eq!(play.sim.sailors[0].lives, LIVES - 1, "one life lost");
        assert!(play.sim.fireballs.is_empty(), "the one that hit is gone");
        assert_eq!(play.view.embers.len(), 40, "the explosion");
    }

    #[test]
    fn after_a_hit_a_second_hit_within_1_5_seconds_does_nothing_but_a_later_one_counts() {
        let mut play = quiet(1);
        let mut rig = Rig::new((80, 24));
        rig.run(&mut play, 1);
        let boat = play.sim.sailors[0].boat;
        let hit = |y: f32| Fireball::new(boat.centre(), y, 0.0, 0.0, 0.0);
        assert!(play.sim.fireballs.push(hit(boat.top() + 3.0)).is_ok());
        rig.update(&mut play);
        assert_eq!(play.sim.sailors[0].lives, LIVES - 1);
        assert!(play.sim.fireballs.push(hit(boat.top() + 3.0)).is_ok());
        rig.update(&mut play);
        assert_eq!(
            play.sim.sailors[0].lives,
            LIVES - 1,
            "invulnerable: the second hit does nothing"
        );
        rig.run(&mut play, 92); // a little over 1.5 seconds after the first hit
        play.sim.fireballs.clear();
        assert!(play.sim.fireballs.push(hit(boat.top() + 3.0)).is_ok());
        rig.update(&mut play);
        assert_eq!(play.sim.sailors[0].lives, LIVES - 2, "vulnerable again");
    }

    #[test]
    fn the_third_hit_ends_the_round_and_the_first_two_do_not() {
        let mut play = quiet(1);
        let mut rig = Rig::new((80, 24));
        rig.run(&mut play, 1);
        let boat = play.sim.sailors[0].boat;
        let mut outcomes = Vec::new();
        for _ in 0..3 {
            let hit = Fireball::new(boat.centre(), boat.top() + 3.0, 0.0, 0.0, 0.0);
            assert!(play.sim.fireballs.push(hit).is_ok());
            outcomes.push(rig.update(&mut play));
            rig.run(&mut play, 92);
            play.sim.fireballs.clear();
        }
        assert!(matches!(outcomes[0], Next::Stay), "the first hit");
        assert!(matches!(outcomes[1], Next::Stay), "the second hit");
        assert!(
            matches!(outcomes[2], Next::Switch(_)),
            "the third ends the round"
        );
        assert_eq!(play.sim.sailors[0].lives, 0);
    }

    #[test]
    fn a_fireball_that_passes_close_above_the_boat_scores_five_once() {
        let mut play = quiet(1);
        let mut rig = Rig::new((80, 24));
        rig.run(&mut play, 1);
        let boat = play.sim.sailors[0].boat;
        let close = Fireball::new(boat.centre() + 0.3, boat.top() - 4.0, -25.0, 0.0, 0.0);
        assert!(play.sim.fireballs.push(close).is_ok());
        rig.update(&mut play);
        assert_eq!(play.sim.sailors[0].lives, LIVES, "a miss is not a hit");
        assert_eq!(play.sim.bonus, NEAR_BONUS, "the bonus for passing close");
        assert_eq!(play.view.floaters.len(), 1, "and a +5 floats up");
        rig.run(&mut play, 10);
        assert_eq!(play.sim.bonus, NEAR_BONUS, "no second bonus");
    }

    #[test]
    fn the_score_is_a_point_for_each_tenth_of_a_league_sailed() {
        let mut play = quiet(1);
        let mut rig = Rig::new((80, 24));
        rig.run(&mut play, 120);
        assert!(
            (19..=20).contains(&play.score()),
            "two leagues: {}",
            play.score()
        );
    }

    #[test]
    fn a_hit_flashes_the_screen_for_0_15_seconds() {
        let mut play = quiet(1);
        let mut rig = Rig::new((80, 24));
        rig.run(&mut play, 1);
        let boat = play.sim.sailors[0].boat;
        assert!(play
            .sim
            .fireballs
            .push(Fireball::new(
                boat.centre(),
                boat.top() + 3.0,
                0.0,
                0.0,
                0.0
            ))
            .is_ok());
        rig.update(&mut play);
        assert!(play.view.flashing(play.sim.elapsed), "the hit flashes");
        rig.run(&mut play, 5);
        assert!(play.view.flashing(play.sim.elapsed), "still flashing");
        rig.run(&mut play, 6);
        assert!(!play.view.flashing(play.sim.elapsed), "the flash is over");
    }

    #[test]
    fn a_boat_that_is_invulnerable_blinks_on_and_off() {
        assert!(
            boat_visible(0.01, INVULNERABLE_SECONDS),
            "shown in the first slot"
        );
        assert!(
            !boat_visible(0.10, INVULNERABLE_SECONDS),
            "hidden in the next slot"
        );
        assert!(boat_visible(0.17, INVULNERABLE_SECONDS), "and shown again");
        assert!(
            boat_visible(5.0, INVULNERABLE_SECONDS),
            "and always shown once it is over"
        );
    }

    #[test]
    fn the_pools_never_grow_past_their_limits_over_6000_ticks_of_play() {
        let mut play = Play::new(7, 0);
        let mut rig = Rig::new((80, 24));
        let mut script = Rng::new(3);
        let moves = [KeyCode::Left, KeyCode::Right, KeyCode::Char(' ')];
        let (mut most_fireballs, mut most_embers, mut hits) = (0, 0, 0);
        let mut lives = LIVES;
        for tick in 0..6000 {
            if tick % 15 == 0 {
                for code in moves {
                    rig.release(code);
                }
                let code = moves[script.range_i32(0, 3) as usize];
                rig.press(code);
            }
            rig.update(&mut play);
            assert!(
                play.sim.fireballs.len() <= FIREBALL_LIMIT,
                "fireballs at {tick}"
            );
            assert!(
                play.view.floaters.len() <= FLOATER_LIMIT,
                "floaters at {tick}"
            );
            assert!(play.view.embers.len() <= EMBER_LIMIT, "embers at {tick}");
            assert!(play.view.steam.len() <= STEAM_LIMIT, "steam at {tick}");
            assert!(play.view.spray.len() <= SPRAY_LIMIT, "spray at {tick}");
            most_fireballs = most_fireballs.max(play.sim.fireballs.len());
            most_embers = most_embers.max(play.view.embers.len());
            if play.sim.sailors[0].lives < lives {
                hits += 1;
                lives = play.sim.sailors[0].lives;
            }
        }
        assert!(most_fireballs > 0, "fireballs came in");
        assert!(most_embers > 0, "and left embers");
        assert!(
            play.score() > 0,
            "the script sailed for a while: {hits} hits"
        );
    }

    #[test]
    fn sailing_leaves_a_wake_of_spray_behind_the_stern() {
        let mut play = quiet(1);
        let mut rig = Rig::new((80, 24));
        rig.run(&mut play, 60);
        assert!(
            play.view.spray.len() >= 2,
            "a wake: {}",
            play.view.spray.len()
        );
    }

    #[test]
    fn q_quits_the_round() {
        let mut play = Play::new(1, 0);
        let mut rig = Rig::new((80, 24));
        rig.run(&mut play, 3);
        rig.press(KeyCode::Char('q'));
        assert!(matches!(rig.update(&mut play), Next::Quit), "q quits");
    }

    #[test]
    fn p_pauses_by_pushing_the_pause_screen_before_time_moves() {
        let mut play = Play::new(1, 0);
        let mut rig = Rig::new((80, 24));
        rig.run(&mut play, 30);
        let before = (play.sim.elapsed, play.sim.distance);
        rig.press(KeyCode::Char('p'));
        let next = rig.update(&mut play);
        assert!(matches!(next, Next::Push(_)), "p pushes the pause screen");
        assert_eq!(
            (play.sim.elapsed, play.sim.distance),
            before,
            "the pausing update moves nothing"
        );
    }

    #[test]
    fn the_pause_screen_freezes_the_time_of_day_the_distance_and_the_sea() {
        let mut game = Headless::new(Play::new(1, 0)).size(80, 24);
        game.step(300);
        game.tap(KeyCode::Char('p'));
        let frozen = game.text();
        game.step(300);
        assert_eq!(game.text(), frozen, "five seconds of pause changed nothing");
    }

    #[test]
    fn the_same_seed_and_the_same_keys_give_the_same_screen_after_1500_ticks() {
        assert_eq!(scripted_round(7), scripted_round(7));
        assert_ne!(
            scripted_round(7),
            scripted_round(8),
            "another seed is another round"
        );
    }

    /// Plays 1500 ticks of scripted keys from the title and returns the screen.
    fn scripted_round(seed: u64) -> String {
        let mut game = Headless::new(Title::new(0)).seed(seed).size(80, 24);
        game.tap(KeyCode::Enter);
        for tick in 0..1500 {
            match tick % 90 {
                0 => game.press(KeyCode::Right),
                45 => game.release(KeyCode::Right),
                _ => {}
            }
            game.step(1);
        }
        game.text()
    }

    #[test]
    fn the_sea_is_rough_only_later_on_the_voyage() {
        let calm = swells(0.0, 0.0);
        let rough = swells(1.0, 0.0);
        let calm_surface: f32 = calm.iter().map(|s| s.0).sum();
        let rough_surface: f32 = rough.iter().map(|s| s.0).sum();
        assert!(
            rough_surface > 3.0 * calm_surface,
            "{calm_surface} then {rough_surface}"
        );
    }

    #[test]
    fn a_day_is_120_seconds_from_dawn_through_noon_dusk_and_midnight() {
        assert!((daylight(0.0) - 0.5).abs() < 1e-5, "dawn");
        assert!((daylight(30.0) - 1.0).abs() < 1e-5, "midday");
        assert!((daylight(60.0) - 0.5).abs() < 1e-5, "dusk");
        assert!(daylight(90.0) < 1e-5, "midnight");
        assert!((daylight(120.0) - 0.5).abs() < 1e-5, "dawn again");
    }

    #[test]
    fn night_is_one_at_midnight_zero_at_midday_and_always_in_range() {
        assert_eq!(night(1.0), 0.0, "midday has no night");
        assert_eq!(night(0.0), 1.0, "midnight is full night");
        for i in 0..=100 {
            let amount = night(i as f32 / 100.0);
            assert!((0.0..=1.0).contains(&amount), "{i}: {amount}");
        }
    }

    #[test]
    fn the_time_of_day_reads_dawn_day_dusk_and_night() {
        assert_eq!(time_of_day(0.0), "dawn");
        assert_eq!(time_of_day(30.0), "day");
        assert_eq!(time_of_day(60.0), "dusk");
        assert_eq!(time_of_day(90.0), "night");
    }

    #[test]
    fn the_sky_ramp_has_no_blue_or_cyan_because_those_belong_to_the_water() {
        for colour in SKY_RAMP {
            assert!(
                !matches!(
                    colour,
                    Colour::Blue | Colour::BrightBlue | Colour::Cyan | Colour::BrightCyan
                ),
                "{colour:?} is in the sky"
            );
        }
    }

    #[test]
    fn the_sky_is_dark_at_midnight_and_bright_at_midday() {
        let cell = sky_cell(10.0, 2.0, 10.0);
        let midnight = sky_value(&cell, 0.0, 0.0, 0.0);
        let midday = sky_value(&cell, 1.0, 0.0, 0.0);
        assert!(midnight < -0.7, "midnight is dark: {midnight}");
        assert!(midday > 0.7, "midday is bright: {midday}");
    }

    #[test]
    fn midday_sky_is_white_and_midnight_sky_is_black_or_very_dark() {
        let mut screen = Screen::new(40, 12);
        paint_sky(&mut screen, &sky_palette(), 1.0, 0.0, 30.0, 10.0);
        let noon = screen.display().pixel(5, 3).unwrap().background();
        assert!(
            matches!(noon, Colour::White | Colour::BrightWhite),
            "noon: {noon:?}"
        );
        let mut night_screen = Screen::new(40, 12);
        paint_sky(&mut night_screen, &sky_palette(), 0.0, 0.0, 90.0, 10.0);
        let midnight = night_screen.display().pixel(5, 3).unwrap().background();
        assert!(
            matches!(midnight, Colour::Black | Colour::BrightBlack),
            "midnight: {midnight:?}"
        );
    }

    #[test]
    fn the_sky_formula_is_finite_at_every_time_of_day_and_progress() {
        let cell = sky_cell(3.0, 1.0, 10.0);
        for i in 0..30 {
            let t = i as f32 * 4.1;
            let v = sky_value(&cell, daylight(t), 0.5, t);
            assert!(v.is_finite() && (-1.0..=1.0).contains(&v), "{t}: {v}");
            let waves = sea(i as f32 / 29.0, t, 0.4, 24.0);
            let sea_v = sea_value(1.0, 5.0, t, &waves);
            assert!(sea_v.is_finite() && (-1.0..=1.0).contains(&sea_v));
        }
    }

    /// A black screen of `width` by `height`, with nothing drawn yet.
    fn black_screen(width: u32, height: u32) -> Screen {
        let mut screen = Screen::new(width, height);
        screen.clear(Colour::Black);
        screen
    }

    /// How many cells in rows `from..to` show a colour other than black. Only
    /// things drawn on a black screen are counted, so the count is what was drawn.
    fn lit_cells(screen: &Screen, from: i32, to: i32) -> usize {
        let (width, _) = screen.size();
        let display = screen.display();
        let mut count = 0;
        for y in from..to {
            for x in 0..width as isize {
                if let Some(pixel) = display.pixel(x, y as isize) {
                    if pixel.colour() != Colour::Black || pixel.background() != Colour::Black {
                        count += 1;
                    }
                }
            }
        }
        count
    }

    #[test]
    fn stars_show_only_at_night_and_only_in_the_sky() {
        let mut day = black_screen(80, 24);
        paint_stars(&mut day, 0.0, 0.0, 15.0);
        day.finish_frame();
        assert_eq!(lit_cells(&day, 0, 24), 0, "no stars at midday");
        let mut night_screen = black_screen(80, 24);
        paint_stars(&mut night_screen, 1.0, 0.0, 15.0);
        night_screen.finish_frame();
        let stars = lit_cells(&night_screen, 0, 24);
        assert!((5..200).contains(&stars), "a sparse sky of stars: {stars}");
        assert_eq!(
            lit_cells(&night_screen, 8, 24),
            0,
            "none below the sky, which ends at pixel row 15"
        );
    }

    #[test]
    fn the_sun_arcs_across_by_day_and_the_moon_by_night() {
        assert!(sun_arc(30.0).is_some(), "the sun at noon");
        assert!(sun_arc(90.0).is_none(), "no sun at midnight");
        assert!(moon_arc(90.0).is_some(), "the moon at midnight");
        assert!(moon_arc(30.0).is_none(), "no moon at noon");
        let (along, height) = sun_arc(30.0).unwrap();
        assert!(
            (along - 0.5).abs() < 1e-5 && (height - 1.0).abs() < 1e-5,
            "highest at noon"
        );
    }

    /// The cell at the middle of the sky, where the sun is at noon and the moon
    /// at midnight (both are high and in the middle of the arc).
    fn sky_middle(screen: &Screen) -> Colour {
        screen.display().pixel(40, 4).unwrap().background()
    }

    #[test]
    fn the_sun_is_a_yellow_disc_at_noon_and_the_moon_takes_its_place_at_midnight() {
        let mut play = Play::new(1, 0);
        play.sim.elapsed = 30.0;
        let noon = frame(&play, 80, 24);
        assert_eq!(
            sky_middle(&noon),
            Colour::BrightYellow,
            "the sun is drawn at noon"
        );
        play.sim.elapsed = 90.0;
        let midnight = frame(&play, 80, 24);
        assert_eq!(
            sky_middle(&midnight),
            Colour::BrightWhite,
            "the moon, not the sun, at midnight"
        );
    }

    #[test]
    fn the_moon_is_drawn_at_night_and_not_by_day() {
        assert!(moon_arc(90.0).is_some(), "the moon rises at night");
        assert!(moon_arc(30.0).is_none(), "and is down at noon");
        let mut play = Play::new(1, 0);
        play.sim.elapsed = 30.0;
        let noon = frame(&play, 80, 24);
        assert_ne!(sky_middle(&noon), Colour::BrightWhite, "no moon at noon");
    }

    #[test]
    fn the_sun_is_clipped_by_the_water_so_it_never_shows_below_the_surface() {
        let mut screen = black_screen(80, 24);
        let waves = sea(0.0, 0.0, 0.0, 24.0);
        let water = level(24.0);
        // at dawn the sun sits on the horizon, so the waves hide most of it. The
        // glow is painted on cells, so the sea is painted after it, as in a frame
        let look = Look::new();
        paint_celestial(&mut screen, &look, 0.0, &waves, 0.0, water);
        paint_sea(&mut screen, &look.sea, &waves, 0.0, water);
        screen.finish_frame();
        for row in 0..24_i32 {
            for column in 0..80_i32 {
                let both_under = !above_water(&waves, 0.0, water, column, 2 * row)
                    && !above_water(&waves, 0.0, water, column, 2 * row + 1);
                if both_under {
                    let pixel = screen
                        .display()
                        .pixel(column as isize, row as isize)
                        .unwrap();
                    assert_ne!(
                        pixel.background(),
                        Colour::BrightYellow,
                        "the sun under the water at {column},{row}"
                    );
                }
            }
        }
    }

    #[test]
    fn the_boats_picture_is_drawn_on_the_boat_cell() {
        let mut play = quiet(1);
        let mut rig = Rig::new((80, 24));
        rig.run(&mut play, 60);
        play.sim.elapsed = 30.0;
        let screen = frame(&play, 80, 24);
        let x = play.sim.sailors[0].boat.centre().round() as isize;
        let row = (play.sim.sailors[0].boat.keel / 2.0).round() as isize;
        let boat_colours = [Colour::BrightWhite, Colour::Red, Colour::Yellow];
        let cell = screen.display().pixel(x, row).unwrap();
        assert!(
            boat_colours.contains(&cell.colour()) || boat_colours.contains(&cell.background()),
            "the boat is pixel art at its cell: {:?} {:?}",
            cell.colour(),
            cell.background()
        );
    }

    #[test]
    fn the_sea_near_the_surface_is_brighter_than_in_the_deep() {
        let waves = sea(0.0, 0.0, 0.0, 24.0);
        let surface = waves.surface_y(10.0, 0.0, level(24.0));
        let near = sea_value(0.5, 10.0, 0.0, &waves);
        let deep = sea_value(6.0, 10.0, 0.0, &waves);
        assert!(near > deep + 0.3, "surface {near}, deep {deep}");
        let _ = surface;
    }

    #[test]
    fn the_sea_has_no_noise_so_neighbouring_cells_never_jump() {
        let waves = sea(0.5, 12.0, 0.9, 24.0);
        for x in 0..80 {
            let column = x as f32;
            let mut last = sea_value(1.0, column, 12.0, &waves);
            for step in 1..20 {
                let depth = 1.0 + step as f32;
                let value = sea_value(depth, column, 12.0, &waves);
                // the depth slope is 0.4 a row and the ripple adds at most 0.16 more
                assert!(
                    (value - last).abs() <= 0.6,
                    "a jump of {} at column {x}",
                    value - last
                );
                last = value;
            }
        }
    }

    #[test]
    fn the_island_scrolls_away_as_the_boat_sails() {
        let width = 80.0;
        let start = island_column(0.0, width);
        let later = island_column(4.0, width);
        assert!(later < start, "the island moves left: {start} then {later}");
        assert!(
            island_column(ISLAND_LEAGUES, width) <= -width * 0.9,
            "one screen width after ten leagues"
        );
    }

    #[test]
    fn a_fireball_is_drawn_where_it_is() {
        let mut play = quiet(1);
        assert!(play
            .sim
            .fireballs
            .push(Fireball::new(30.0, 10.0, -6.0, 0.0, 0.0))
            .is_ok());
        let screen = frame(&play, 80, 24);
        assert_eq!(
            screen.display().pixel(30, 5).unwrap().background(),
            Colour::BrightRed,
            "the disc's fire colour at its cell"
        );
    }

    #[test]
    fn a_sinking_fireball_is_only_grey_or_blue_once_it_has_faded() {
        let mut play = quiet(1);
        let mut f = Fireball::new(30.0, 20.0, 0.0, 0.0, 0.0);
        f.stage = Stage::Sinking(SINK_SECONDS * 0.7);
        assert!(play.sim.fireballs.push(f).is_ok());
        let screen = frame(&play, 80, 24);
        let grey_or_blue = |c: Colour| {
            matches!(
                c,
                Colour::White
                    | Colour::BrightBlack
                    | Colour::Black
                    | Colour::Blue
                    | Colour::BrightWhite
            )
        };
        let cell = screen.display().pixel(30, 10).unwrap();
        assert!(
            grey_or_blue(cell.colour())
                || grey_or_blue(cell.background())
                || cell.background() == Colour::BrightBlack,
            "{:?} {:?}",
            cell.colour(),
            cell.background()
        );
    }

    #[test]
    fn the_hud_shows_the_leagues_the_score_the_best_score_and_the_lives_as_hearts() {
        let mut game = Headless::new(Play::new(1, 7)).size(80, 24);
        game.step(2);
        let text = game.text();
        let top = text.lines().next().unwrap_or("");
        assert!(top.contains("0.0 leagues"), "{top}");
        assert!(top.contains("score 0"), "{top}");
        assert!(top.contains("best 7"), "{top}");
        assert!(top.contains("♥ ♥ ♥"), "{top}");
        assert!(top.contains("dawn"), "the time of day, centred: {top}");
    }

    #[test]
    fn distance_is_shown_as_leagues_with_one_decimal() {
        let mut play = Play::new(1, 0);
        play.sim.distance = 12.4;
        let mut screen = Screen::new(80, 24);
        play.draw(&mut screen);
        let row: String = (0..80)
            .map(|x| screen.display().pixel(x, 0).unwrap().character())
            .collect();
        assert!(row.contains("12.4 leagues"), "{row:?}");
    }

    #[test]
    fn a_lost_life_is_a_grey_heart_and_a_kept_life_is_red() {
        let mut play = Play::new(1, 0);
        play.sim.sailors[0].lives = 1;
        let mut screen = Screen::new(80, 24);
        play.draw(&mut screen);
        let first = screen.display().pixel(74, 0).unwrap();
        let lost = screen.display().pixel(78, 0).unwrap();
        assert_eq!(first.colour(), Colour::BrightRed, "the one life left");
        assert_eq!(lost.colour(), Colour::BrightBlack, "a lost life");
    }

    #[test]
    fn enter_on_the_title_starts_a_round_with_no_score() {
        let mut game = Headless::new(Title::new(4)).size(80, 24);
        game.tap(KeyCode::Enter);
        let text = game.text();
        assert!(text.contains("score 0"), "a round is on screen: {text}");
        assert!(text.contains("best 4"), "with the best score kept: {text}");
    }

    #[test]
    fn q_quits_from_the_title() {
        let mut game = Headless::new(Title::new(0));
        game.tap(KeyCode::Char('q'));
        assert!(game.quit());
    }

    #[test]
    fn the_title_shows_the_name_in_block_letters_and_how_to_start() {
        let mut game = Headless::new(Title::new(0)).size(80, 24);
        game.step(3);
        let text = game.text();
        assert!(text.contains("press Enter to sail"), "{text}");
        let lettered = text
            .lines()
            .skip(2)
            .take(5)
            .filter(|line| line.contains("#####"))
            .count();
        assert!(lettered >= 3, "block letters on about five rows:\n{text}");
    }

    #[test]
    fn the_title_letters_sit_on_a_dark_band_so_they_read_over_the_sky() {
        let mut screen = Screen::new(80, 24);
        Title::new(0).draw(&mut screen);
        let left = (80 - 23) / 2;
        let behind = screen.display().pixel(left - 1, 4).unwrap().background();
        assert_eq!(behind, Colour::Black, "just left of the S");
    }

    #[test]
    fn p_or_esc_resumes_from_the_pause_screen_and_q_quits_from_it() {
        let mut game = Headless::new(Play::new(1, 0)).size(80, 24);
        game.tap(KeyCode::Char('p'));
        assert!(game.text().contains("PAUSED"));
        game.tap(KeyCode::Char('p'));
        assert!(!game.text().contains("PAUSED"), "p resumes");
        game.tap(KeyCode::Esc);
        assert!(game.text().contains("PAUSED"), "Esc pauses");
        game.tap(KeyCode::Esc);
        assert!(!game.text().contains("PAUSED"), "Esc resumes");
        game.tap(KeyCode::Char('p'));
        game.tap(KeyCode::Char('q'));
        assert!(game.quit(), "q quits from the pause screen");
    }

    #[test]
    fn the_pause_screen_is_drawn_over_the_round() {
        let mut game = Headless::new(Play::new(1, 0)).size(80, 24);
        game.step(60);
        game.tap(KeyCode::Char('p'));
        let text = game.text();
        assert!(text.contains("PAUSED  (p to resume)"), "{text}");
        assert!(
            text.contains("score"),
            "the round is still behind it: {text}"
        );
    }

    #[test]
    fn enter_on_the_game_over_screen_sails_again_and_keeps_the_best() {
        let mut game = Headless::new(Over::new(3, 9, 0.0, 0.0, 0.0)).size(80, 24);
        game.tap(KeyCode::Enter);
        let text = game.text();
        assert!(text.contains("score 0"), "a fresh round: {text}");
        assert!(text.contains("best 9"), "the best is kept: {text}");
    }

    #[test]
    fn q_quits_from_the_game_over_screen() {
        let mut game = Headless::new(Over::new(3, 9, 0.0, 0.0, 0.0));
        game.tap(KeyCode::Char('q'));
        assert!(game.quit());
    }

    #[test]
    fn the_game_over_screen_shows_the_score_the_best_and_how_to_go_on() {
        let mut game = Headless::new(Over::new(3, 9, 0.0, 0.0, 0.0)).size(80, 24);
        game.step(2);
        let text = game.text();
        assert!(text.contains("score 3"), "{text}");
        assert!(text.contains("best 9"), "{text}");
        assert!(text.contains("Enter: sail again"), "{text}");
    }

    /// Seconds for a fireball to fall from its spawn to the water under column
    /// 32.5 (the boat's middle on an 80 by 24 screen) at `progress`. It is averaged
    /// over three runs of the sea and 200 moments, the same way the baseline was.
    fn seconds_to_the_water(progress: f32) -> f32 {
        let scale = fall_scale(progress);
        let dt = 1.0 / 60.0;
        let (mut total, mut n) = (0.0_f32, 0);
        for phase in [0.0_f32, 2.0, 4.0] {
            for k in 0..200 {
                let t0 = k as f32 * 0.05;
                let mut f = Fireball::new(
                    32.5,
                    FALL_FROM,
                    0.0,
                    FALL_START * scale,
                    FALL_GRAVITY * scale,
                );
                let mut elapsed = 0.0_f32;
                loop {
                    f.fall(dt);
                    elapsed += dt;
                    let t = t0 + elapsed;
                    let surface = sea(progress, t, phase, 24.0).surface_y(32.5, t, level(24.0));
                    if f.y >= 2.0 * surface || elapsed > 10.0 {
                        break;
                    }
                }
                total += elapsed;
                n += 1;
            }
        }
        total / n as f32
    }

    /// The fall to the water before this change, measured on the old sea (level
    /// 0.64, no scaling) with the method of [`seconds_to_the_water`]: 1.667 s at
    /// progress 0 and 1.185 s at progress 1.
    const FALL_SECONDS_CALM_BEFORE: f32 = 1.6672;
    const FALL_SECONDS_STORM_BEFORE: f32 = 1.1847;

    #[test]
    fn fireballs_take_at_least_a_fifth_longer_to_reach_the_water_when_calm_and_15_percent_longer_in_the_storm(
    ) {
        let calm = seconds_to_the_water(0.0);
        let storm = seconds_to_the_water(1.0);
        assert!(
            calm >= 1.2 * FALL_SECONDS_CALM_BEFORE,
            "calm: {calm} s, was {FALL_SECONDS_CALM_BEFORE} s"
        );
        assert!(
            storm >= 1.15 * FALL_SECONDS_STORM_BEFORE,
            "storm: {storm} s, was {FALL_SECONDS_STORM_BEFORE} s"
        );
    }

    /// The boat's top speed in columns a second, held to the right on a screen 400
    /// columns wide so that no edge stops it. Before this change it was 18.
    fn boat_top_speed() -> f32 {
        let mut play = Play::new(1, 0);
        play.sim.launching = false;
        let mut rig = Rig::new((400, 24));
        rig.run(&mut play, 1);
        rig.press(KeyCode::Right);
        let mut top = 0.0_f32;
        for _ in 0..180 {
            rig.update(&mut play);
            top = top.max(play.sim.sailors[0].boat.vx);
        }
        top
    }

    #[test]
    fn the_boat_sails_about_a_quarter_faster_than_its_old_top_speed_of_18_columns_a_second() {
        let top = boat_top_speed();
        assert!(
            (1.2 * 18.0..=1.4 * 18.0).contains(&top),
            "the top speed is {top} columns a second; it should be 1.2 to 1.4 times 18"
        );
    }

    /// Seconds for the boat to sail from 0.2 to 0.6 of an 80 column screen, held to
    /// the right. It was 2.017 seconds before the boat was made faster.
    fn crossing_seconds() -> f32 {
        let mut play = Play::new(1, 0);
        play.sim.launching = false;
        let mut rig = Rig::new((80, 24));
        rig.run(&mut play, 1);
        rig.press(KeyCode::Left);
        rig.run(&mut play, 600);
        rig.release(KeyCode::Left);
        assert!(
            (play.sim.sailors[0].boat.x - 16.0).abs() < 0.01,
            "parked at 0.2: {}",
            play.sim.sailors[0].boat.x
        );
        rig.press(KeyCode::Right);
        let mut ticks = 0;
        while play.sim.sailors[0].boat.x < 48.0 - 1e-3 && ticks < 3000 {
            rig.update(&mut play);
            ticks += 1;
        }
        ticks as f32 / 60.0
    }

    #[test]
    fn the_boat_crosses_the_middle_of_the_screen_about_a_fifth_sooner() {
        let seconds = crossing_seconds();
        assert!(
            seconds <= 0.85 * 2.017,
            "the crossing took {seconds} s; it took 2.017 s before"
        );
    }

    #[test]
    fn the_title_controls_sit_in_a_framed_panel_like_the_other_screens() {
        let mut game = Headless::new(Title::new(0)).size(80, 24);
        game.step(3);
        let text = game.text();
        assert_eq!(text.matches('\u{25C6}').count(), 4, "four corners:\n{text}");
        assert!(
            text.contains("A/D or arrows steer   p pause   q quit"),
            "{text}"
        );
    }

    #[test]
    fn the_still_water_sits_low_at_seventy_two_hundredths_of_the_screen() {
        assert!((level(100.0) - 72.0).abs() < 1e-4, "{}", level(100.0));
    }

    #[test]
    fn the_stormy_troughs_stay_a_row_and_a_half_above_the_bottom_on_short_screens() {
        for rows in [20.0_f32, 24.0, 40.0] {
            for phase in [0.0_f32, 1.3] {
                for k in 0..600 {
                    let t = k as f32 / 10.0;
                    let waves = sea(1.0, t, phase, rows);
                    for x in 0..100 {
                        let y = waves.surface_y(x as f32, t, level(rows));
                        assert!(
                            y <= rows - 1.5 + 1e-3,
                            "{rows} rows: column {x} at {t} s is at row {y}"
                        );
                    }
                }
            }
        }
    }

    /// The column where `needle` starts in `line`, counted in characters.
    fn column_of(line: &str, needle: &str) -> usize {
        let byte = line.find(needle).expect("the text is on this line");
        line[..byte].chars().count()
    }

    #[test]
    fn the_game_over_text_sits_in_a_framed_panel_with_diamond_corners() {
        let mut game = Headless::new(Over::new(3, 9, 0.0, 0.0, 0.0)).size(80, 24);
        game.step(2);
        let text = game.text();
        let lines: Vec<&str> = text.lines().collect();
        let corner_rows: Vec<usize> = (0..lines.len())
            .filter(|&row| lines[row].contains('\u{25C6}'))
            .collect();
        assert_eq!(corner_rows.len(), 2, "a top and a bottom edge:\n{text}");
        let (top, bottom) = (corner_rows[0], corner_rows[1]);
        let left = column_of(lines[top], "\u{25C6}");
        let right = lines[top]
            .rfind('\u{25C6}')
            .map(|b| lines[top][..b].chars().count());
        let right = right.expect("a right corner");
        assert!(
            lines[top].contains('\u{2550}'),
            "a double line along the top:\n{text}"
        );
        for line in &lines[top + 1..bottom] {
            assert!(line.contains('\u{2551}'), "the sides:\n{text}");
        }
        for word in [
            "the sea wins this time",
            "score 3",
            "best 9",
            "Enter: sail again   q: quit",
        ] {
            let row = lines.iter().position(|l| l.contains(word)).expect(word);
            assert!(
                row > top && row < bottom,
                "{word} is inside the panel:\n{text}"
            );
            let start = column_of(lines[row], word);
            assert!(
                start > left && start + word.chars().count() < right,
                "{word} is inside the panel's sides:\n{text}"
            );
        }
    }

    /// The top left and bottom right diamonds of the panel on `screen`, as cells.
    fn panel_box(screen: &Screen) -> ((isize, isize), (isize, isize)) {
        let (width, height) = screen.size();
        let mut corners = Vec::new();
        for y in 0..height as isize {
            for x in 0..width as isize {
                if screen.display().pixel(x, y).unwrap().character() == '\u{25C6}' {
                    corners.push((x, y));
                }
            }
        }
        (corners[0], corners[corners.len() - 1])
    }

    #[test]
    fn nothing_shows_through_the_game_over_panel_with_the_moon_and_stars_behind_it() {
        let mut game = Headless::new(Over::new(3, 9, 90.0, 1.0, 0.4)).size(80, 24);
        game.step(2);
        let screen = game.screen();
        let ((x0, y0), (x1, y1)) = panel_box(screen);
        for y in y0 + 1..y1 {
            for x in x0 + 1..x1 {
                let cell = screen.display().pixel(x, y).unwrap();
                assert_eq!(cell.background(), PANEL_INSIDE, "({x}, {y}) is the panel's");
                assert!(
                    !matches!(
                        cell.character(),
                        '\u{2580}' | '\u{2584}' | '\u{2588}' | '\u{2591}' | '\u{2592}' | '\u{2593}'
                    ),
                    "a picture shows through at ({x}, {y}): {:?}",
                    cell.character()
                );
            }
        }
    }

    #[test]
    fn both_panels_are_whole_on_every_screen_from_60_by_18_to_200_by_50() {
        for width in (60..=200).step_by(5) {
            for height in 18..=50 {
                let mut over =
                    Headless::new(Over::new(123_456, 999_999, 90.0, 0.5, 0.4)).size(width, height);
                over.step(2);
                let text = over.text();
                assert_eq!(
                    text.matches('\u{25C6}').count(),
                    4,
                    "the game-over panel's four corners at {width}x{height}:\n{text}"
                );
                assert!(text.contains("Enter: sail again"), "{width}x{height}");

                let mut paused = Headless::new(Play::new(1, 0)).size(width, height);
                paused.step(2);
                paused.tap(KeyCode::Char('p'));
                let text = paused.text();
                assert_eq!(
                    text.matches('\u{25C6}').count(),
                    4,
                    "the pause panel's four corners at {width}x{height}:\n{text}"
                );
                assert!(text.contains("PAUSED  (p to resume)"), "{width}x{height}");
            }
        }
    }

    #[test]
    fn no_black_gap_shows_in_the_sky_above_a_trough_at_noon_in_the_roughest_sea() {
        // the troughs swell and die down, so look at a stretch of the bright middle of the day
        let mut play = Play::new(1, 0);
        play.sim.distance = DISTANCE_MAX;
        let water = level(24.0);
        for k in 0..80 {
            let t = 20.0 + k as f32 * 0.25;
            play.sim.elapsed = t;
            let screen = frame(&play, 80, 24);
            let waves = sea(1.0, t, play.sim.phase, 24.0);
            for x in 0..80 {
                let surface = waves.surface_y(x as f32, t, water);
                for row in 1..24 {
                    if (row as f32) + 1.0 < surface - 0.5 {
                        let bg = screen.display().pixel(x, row).unwrap().background();
                        assert_ne!(bg, Colour::Black, "a gap at {t} s, column {x}, row {row}");
                    }
                }
            }
        }
    }

    #[test]
    fn a_tall_screen_keeps_the_full_swell_and_a_short_one_scales_it_down() {
        assert_eq!(swell_fit(1.0, 40.0), 1.0, "40 rows: the full storm");
        assert!(swell_fit(1.0, 24.0) < 1.0, "24 rows: scaled a little");
        assert!(swell_fit(1.0, 20.0) < 1.0, "20 rows: scaled down");
        assert_eq!(swell_fit(0.0, 20.0), 1.0, "the calm sea always fits");
    }

    /// The cells of the screen as (character, colour, background), row by row.
    fn cells(game: &mut Headless) -> Vec<(char, Colour, Colour)> {
        cells_of(game.screen())
    }

    /// The cells of `screen` as (character, colour, background), row by row.
    fn cells_of(screen: &Screen) -> Vec<(char, Colour, Colour)> {
        let (width, height) = screen.size();
        let display = screen.display();
        let mut out = Vec::new();
        for y in 0..height as isize {
            for x in 0..width as isize {
                let pixel = display.pixel(x, y).expect("the cell is on screen");
                out.push((pixel.character(), pixel.colour(), pixel.background()));
            }
        }
        out
    }

    /// A fingerprint of every cell on the screen: character and both colours.
    fn fingerprint(game: &mut Headless) -> u64 {
        let mut hash = 0xcbf2_9ce4_8422_2325_u64;
        for cell in cells(game) {
            for byte in format!("{cell:?}").bytes() {
                hash = (hash ^ byte as u64).wrapping_mul(0x100_0000_01b3);
            }
        }
        hash
    }

    #[test]
    fn a_scripted_round_draws_the_same_frames_as_when_it_was_recorded() {
        // A guard for refactoring the rules: the frames of a seeded round with
        // scripted keys. If this changes, so did how the game plays or looks.
        let mut game = Headless::new(Title::new(0)).seed(3).size(80, 24);
        game.tap(KeyCode::Enter);
        let mut seen = Vec::new();
        for tick in 0..1800 {
            match tick % 100 {
                0 => game.press(KeyCode::Right),
                40 => game.release(KeyCode::Right),
                50 => game.press(KeyCode::Left),
                80 => game.release(KeyCode::Left),
                _ => {}
            }
            game.step(1);
            if tick % 450 == 449 {
                seen.push(fingerprint(&mut game));
            }
        }
        assert_eq!(
            seen,
            [
                18329081847994442042,
                16797105654941453651,
                17474861275096509298,
                10541715977374162731
            ]
        );
    }

    fn hash_of(sim: &SailSim) -> u64 {
        let mut h = Hasher::new();
        sim.hash(&mut h);
        h.finish()
    }

    /// Two boats on scripted steering for `steps` updates.
    fn two_boats(steps: u32) -> (SailSim, Rng) {
        let mut rng = Rng::new(11);
        let mut sim = SailSim::new(2, Env::new((80, 24)), &mut rng);
        for tick in 0..steps {
            let a = Steer(match (tick / 70) % 3 {
                0 => 1,
                1 => 0,
                _ => -1,
            });
            let b = Steer(match (tick / 50) % 3 {
                0 => -1,
                1 => 1,
                _ => 0,
            });
            sim.step(&[a, b], &mut rng);
        }
        (sim, rng)
    }

    #[test]
    fn two_boats_over_3000_steps_reach_the_recorded_state_on_every_machine() {
        // CI runs this on Linux, macOS (arm64) and Windows: the same number
        // there is evidence that the rules agree across machines
        let (sim, rng) = two_boats(3000);
        assert!(
            sim.sailors.iter().any(|s| s.lives < LIVES) || sim.bonus > 0,
            "the run should see some action"
        );
        assert_eq!(
            (hash_of(&sim), rng.state()),
            (17047842182560643922, 12371428055675856712)
        );
    }

    #[test]
    fn boats_may_overlap_and_do_not_get_in_each_others_way() {
        // the sea is small enough that boats share it: there are no collisions
        let mut rng = Rng::new(1);
        let mut sim = SailSim::new(2, Env::new((80, 24)), &mut rng);
        sim.launching = false;
        for _ in 0..600 {
            sim.step(&[Steer(1), Steer(1)], &mut rng);
        }
        let (a, b) = (sim.sailors[0].boat.x, sim.sailors[1].boat.x);
        assert_eq!(a, b, "both reached the far edge, on top of each other");
        assert!(sim.sailors.iter().all(|s| s.lives == LIVES));
    }

    #[test]
    fn the_hash_follows_the_rules_state_and_ignores_the_picture_events() {
        let (mut sim, _) = two_boats(500);
        let before = hash_of(&sim);
        sim.fx.push(Fx::Near { x: 1.0, y: 2.0 });
        assert_eq!(hash_of(&sim), before, "events are for the picture only");
        sim.sailors[1].boat.x += 0.001;
        assert_ne!(hash_of(&sim), before, "a boat moved");
        let (other, _) = two_boats(501);
        assert_ne!(hash_of(&other), before, "one step later");
    }

    #[test]
    fn the_same_inputs_and_seed_give_the_same_state_and_another_seed_does_not() {
        let (a, _) = two_boats(800);
        let (b, _) = two_boats(800);
        assert_eq!(hash_of(&a), hash_of(&b));
        let mut rng = Rng::new(12);
        let mut c = SailSim::new(2, Env::new((80, 24)), &mut rng);
        for _ in 0..800 {
            c.step(&[Steer(1), Steer(0)], &mut rng);
        }
        assert_ne!(hash_of(&c), hash_of(&a));
    }

    #[test]
    fn a_steering_input_round_trips_through_its_bytes() {
        for value in [-1, 0, 1] {
            assert_eq!(
                Steer::from_bytes(&Steer(value).to_bytes()),
                Ok(Steer(value))
            );
        }
        assert_eq!(Steer(-1).to_bytes().len(), 1);
    }

    /// Two machines playing together over an in-process network.
    fn match_of_two(seed: u64) -> (Together<Local>, Together<Local>) {
        let mut ends = Local::network(2).into_iter();
        let settings = Settings::new(seed);
        let make =
            |end, me| Together::new(end, Config::new(2, PlayerId(me)).star(false), &settings);
        (make(ends.next().unwrap(), 0), make(ends.next().unwrap(), 1))
    }

    /// One update of `game` on a screen 80 columns by 24 rows.
    fn update_of(rig: &mut Rig, game: &mut impl Game) -> Next {
        rig.update(game)
    }

    fn drawn_text(game: &impl Game, width: u32, height: u32) -> String {
        let screen = painted(game, width, height);
        let (w, h) = screen.size();
        let display = screen.display();
        let mut out = String::new();
        for y in 0..h as isize {
            for x in 0..w as isize {
                out.push(display.pixel(x, y).unwrap().character());
            }
            out.push('\n');
        }
        out
    }

    #[test]
    fn two_machines_sail_the_same_sea_and_steer_their_own_boats() {
        let (mut one, mut two) = match_of_two(5);
        let (mut rig_one, mut rig_two) = (Rig::new((80, 24)), Rig::new((80, 24)));
        rig_one.press(KeyCode::Right);
        rig_two.press(KeyCode::Left);
        for _ in 0..900 {
            update_of(&mut rig_one, &mut one);
            update_of(&mut rig_two, &mut two);
        }
        assert!(matches!(one.status, Status::Playing), "{:?}", one.status);
        assert!(matches!(two.status, Status::Playing), "{:?}", two.status);
        let (a, b) = (one.lock.sim(), two.lock.sim());
        assert!(a.elapsed > 10.0, "{} s", a.elapsed);
        // each machine steered its own boat, and the other machine saw it
        assert!(a.sailors[0].boat.x > a.sailors[1].boat.x);
        assert!((a.sailors[0].boat.x - b.sailors[0].boat.x).abs() < 3.0);
        assert!((a.sailors[1].boat.x - b.sailors[1].boat.x).abs() < 3.0);
    }

    #[test]
    fn the_hud_names_every_player_and_marks_nothing_for_a_single_boat() {
        let (mut one, mut two) = match_of_two(5);
        let (mut rig_one, mut rig_two) = (Rig::new((80, 24)), Rig::new((80, 24)));
        for _ in 0..30 {
            update_of(&mut rig_one, &mut one);
            update_of(&mut rig_two, &mut two);
        }
        let text = drawn_text(&one, 80, 24);
        let row_one: &str = text.lines().nth(1).unwrap();
        assert!(
            row_one.contains("P1") && row_one.contains("P2"),
            "{row_one}"
        );
        let solo = drawn_text(&Play::new(1, 0), 80, 24);
        assert!(!solo.lines().nth(1).unwrap().contains("P1"));
    }

    #[test]
    fn a_machine_whose_partner_is_silent_says_who_it_is_waiting_for() {
        let (mut one, _two) = match_of_two(5);
        let mut rig = Rig::new((80, 24));
        for _ in 0..40 {
            update_of(&mut rig, &mut one);
        }
        let text = drawn_text(&one, 80, 24);
        assert!(text.contains("waiting for player 2"), "{text}");
    }

    #[test]
    fn leaving_with_q_stops_the_other_machine_with_a_clear_message() {
        let (mut one, mut two) = match_of_two(5);
        let (mut rig_one, mut rig_two) = (Rig::new((80, 24)), Rig::new((80, 24)));
        for _ in 0..30 {
            update_of(&mut rig_one, &mut one);
            update_of(&mut rig_two, &mut two);
        }
        rig_two.press(KeyCode::Char('q'));
        assert!(matches!(update_of(&mut rig_two, &mut two), Next::Quit));
        rig_one.release(KeyCode::Char('q'));
        for _ in 0..40 {
            update_of(&mut rig_one, &mut one);
        }
        let text = drawn_text(&one, 80, 24);
        assert!(text.contains("player 2 left the game"), "{text}");
    }

    #[test]
    fn a_window_smaller_than_the_sea_says_how_big_it_must_be() {
        let (one, _two) = match_of_two(5);
        let text = drawn_text(&one, 60, 10);
        assert!(text.contains("at least 80 columns by 25 rows"), "{text}");
    }

    #[test]
    fn once_the_match_has_ended_nothing_more_runs() {
        let (mut one, mut two) = match_of_two(5);
        let (mut rig_one, mut rig_two) = (Rig::new((80, 24)), Rig::new((80, 24)));
        for _ in 0..30 {
            update_of(&mut rig_one, &mut one);
            update_of(&mut rig_two, &mut two);
        }
        one.status = Status::Over;
        let frozen = one.lock.sim().elapsed;
        for _ in 0..30 {
            update_of(&mut rig_one, &mut one);
            update_of(&mut rig_two, &mut two);
        }
        assert!(matches!(one.status, Status::Over));
        assert_eq!(one.lock.sim().elapsed, frozen);
    }
    #[test]
    fn the_end_of_the_round_shows_the_score_and_how_to_leave() {
        let (mut one, _two) = match_of_two(5);
        one.status = Status::Over;
        let text = drawn_text(&one, 80, 24);
        assert!(text.contains("the sea wins this time"), "{text}");
        assert!(text.contains("q: quit"), "{text}");
    }
    #[test]
    fn the_tuning_has_the_three_knobs_at_their_defaults() {
        let knobs = tuning().knobs();
        let names: Vec<&str> = knobs.iter().map(|k| k.name).collect();
        assert_eq!(names, ["fireball_rate", "wave_height", "boat_speed"]);
        assert!(knobs.iter().all(|k| k.default == 1.0), "{knobs:?}");
    }

    #[test]
    fn with_the_default_tuning_a_round_looks_exactly_as_it_did_before() {
        let mut plain = Headless::new(Title::new(0)).seed(1).size(80, 24);
        let mut tuned = Headless::new(start(tuning())).seed(1).size(80, 24);
        plain.tap(KeyCode::Enter);
        tuned.tap(KeyCode::Enter);
        plain.step(600);
        tuned.step(600);
        assert_eq!(tuned.text(), plain.text());
        assert_eq!(cells(&mut tuned), cells(&mut plain), "the colours too");
    }

    /// Paints `game` on a fresh screen and finishes the frame, as the loop does.
    fn painted(game: &impl Game, width: u32, height: u32) -> Screen {
        let mut screen = Screen::new(width, height);
        screen.clear(Colour::Black);
        game.draw(&mut screen);
        screen.finish_frame();
        screen
    }

    /// Whether the deepest rows of the sea look the same in every column.
    fn deep_water_is_flat(screen: &Screen) -> bool {
        let display = screen.display();
        let cell = |x: isize, y: isize| {
            display
                .pixel(x, y)
                .map(|p| (p.character(), p.colour(), p.background()))
        };
        (20..24).all(|y| (0..80).all(|x| cell(x, y) == cell(0, y)))
    }

    #[test]
    fn the_fireball_rate_sends_more_fireballs_when_it_is_higher() {
        fn in_the_air_after_900_ticks(rate: f32) -> usize {
            let knobs = tuning();
            knobs.set("fireball_rate", rate);
            let mut play = Play::new(1, 0).tuned(knobs);
            let mut rig = Rig::new((80, 24));
            rig.run(&mut play, 900);
            play.sim.fireballs.len()
        }
        let high = in_the_air_after_900_ticks(3.0);
        let low = in_the_air_after_900_ticks(0.2);
        assert!(high > low, "at 3x there were {high}, at 0.2x {low}");
    }

    #[test]
    fn a_wave_height_of_nothing_makes_the_sea_flat() {
        let flat = sea_scaled(1.0, 3.7, 0.4, 24.0, 0.0);
        for x in 0..80 {
            assert_eq!(flat.height(x as f32, 3.7), 0.0, "column {x}");
        }
    }

    #[test]
    fn a_wave_height_of_two_raises_the_biggest_swell() {
        let biggest = |scale: f32| {
            let mut most = 0.0_f32;
            for i in 0..200 {
                let t = i as f32 * 0.1;
                let waves = sea_scaled(1.0, t, 0.4, 24.0, scale);
                for x in 0..80 {
                    most = most.max(waves.height(x as f32, t).abs());
                }
            }
            most
        };
        let normal = biggest(1.0);
        let doubled = biggest(2.0);
        assert!(doubled > 1.9 * normal, "{doubled} against {normal}");
    }

    #[test]
    fn the_round_reads_the_wave_height_on_every_update() {
        let knobs = tuning();
        knobs.set("wave_height", 0.0);
        let mut play = Play::new(1, 0).tuned(knobs.clone());
        let mut rig = Rig::new((80, 24));
        rig.run(&mut play, 1);
        assert_eq!(play.sim.env.wave_scale, 0.0);
        knobs.set("wave_height", 2.0);
        rig.run(&mut play, 1);
        assert_eq!(play.sim.env.wave_scale, 2.0);
    }

    #[test]
    fn with_no_wave_height_the_water_is_drawn_flat_in_every_column() {
        let knobs = tuning();
        knobs.set("wave_height", 0.0);
        let mut play = Play::new(1, 0).tuned(knobs);
        play.sim.launching = false;
        let mut rig = Rig::new((80, 24));
        rig.run(&mut play, 300);
        assert!(deep_water_is_flat(&painted(&play, 80, 24)), "flat when 0");
    }

    #[test]
    fn the_drawn_sea_follows_the_wave_height_the_round_last_read() {
        let mut play = quiet(1);
        let mut rig = Rig::new((80, 24));
        rig.run(&mut play, 300);
        play.sim.env.wave_scale = 0.0;
        let flat = cells_of(&painted(&play, 80, 24));
        play.sim.env.wave_scale = 2.0;
        let high = cells_of(&painted(&play, 80, 24));
        assert_ne!(flat, high, "the picture ignored the wave height");
    }

    #[test]
    fn the_game_over_sea_keeps_the_flat_water_it_ended_with() {
        let over = Over::new(3, 9, 0.0, 0.0, 0.0).waves_at(0.0);
        assert!(deep_water_is_flat(&painted(&over, 80, 24)));
    }

    #[test]
    fn boat_speed_two_sails_farther_in_thirty_steps_than_one() {
        fn sailed_in_thirty_steps(speed: f32) -> f32 {
            let knobs = tuning();
            knobs.set("boat_speed", speed);
            let mut play = Play::new(1, 0).tuned(knobs);
            play.sim.launching = false;
            let mut rig = Rig::new((80, 24));
            rig.run(&mut play, 1);
            let before = play.sim.sailors[0].boat.x;
            rig.press(KeyCode::Right);
            rig.run(&mut play, 30);
            play.sim.sailors[0].boat.x - before
        }
        let normal = sailed_in_thirty_steps(1.0);
        let fast = sailed_in_thirty_steps(2.0);
        assert!(fast > 1.5 * normal, "at 2x {fast} columns, at 1x {normal}");
    }

    #[test]
    fn a_knob_moved_during_a_round_changes_that_round_at_once() {
        fn sailed_in_the_last_thirty(change_to: Option<f32>) -> f32 {
            let knobs = tuning();
            let mut play = Play::new(1, 0).tuned(knobs.clone());
            play.sim.launching = false;
            let mut rig = Rig::new((400, 24));
            rig.run(&mut play, 1);
            rig.press(KeyCode::Right);
            rig.run(&mut play, 60);
            if let Some(speed) = change_to {
                knobs.set("boat_speed", speed);
            }
            let before = play.sim.sailors[0].boat.x;
            rig.run(&mut play, 30);
            play.sim.sailors[0].boat.x - before
        }
        let unchanged = sailed_in_the_last_thirty(None);
        let changed = sailed_in_the_last_thirty(Some(2.0));
        assert!(
            changed > 1.3 * unchanged,
            "after the change {changed}, without it {unchanged}"
        );
    }

    #[test]
    fn the_title_hands_its_tuning_on_to_the_round_it_starts() {
        let knobs = tuning();
        let mut game = Headless::new(start(knobs.clone())).seed(1).size(80, 24);
        game.tap(KeyCode::Enter);
        knobs.set("wave_height", 0.0);
        game.step(120);
        let mut control = Headless::new(start(tuning())).seed(1).size(80, 24);
        control.tap(KeyCode::Enter);
        control.step(120);
        assert_ne!(
            game.text(),
            control.text(),
            "the round saw the new wave height"
        );
    }

    #[test]
    fn the_game_over_screen_hands_its_tuning_on_to_the_next_round() {
        let knobs = tuning();
        let over = Over::new(3, 9, 0.0, 0.0, 0.0).tuned(knobs.clone());
        let mut game = Headless::new(over).seed(1).size(80, 24);
        game.tap(KeyCode::Enter);
        knobs.set("wave_height", 0.0);
        game.step(120);
        let over = Over::new(3, 9, 0.0, 0.0, 0.0).tuned(tuning());
        let mut control = Headless::new(over).seed(1).size(80, 24);
        control.tap(KeyCode::Enter);
        control.step(120);
        assert_ne!(
            game.text(),
            control.text(),
            "the next round saw the new wave height"
        );
    }

    #[test]
    fn with_no_wave_height_the_boat_settles_on_the_flat_water_that_is_drawn() {
        let knobs = tuning();
        knobs.set("wave_height", 0.0);
        let mut play = Play::new(1, 0).tuned(knobs);
        play.sim.distance = DISTANCE_MAX;
        play.sim.launching = false;
        let mut rig = Rig::new((80, 24));
        rig.run(&mut play, 600);
        let flat_keel = 2.0 * level(24.0) + 1.0;
        assert!(
            (play.sim.sailors[0].boat.keel - flat_keel).abs() < 0.5,
            "keel {} should sit at the flat water {flat_keel}",
            play.sim.sailors[0].boat.keel
        );
    }

    #[test]
    fn a_settled_boat_keeps_its_keel_on_the_screen_in_the_roughest_sea() {
        for rows in [20_u32, 24, 40] {
            let mut play = Play::new(1, 0);
            play.sim.distance = DISTANCE_MAX;
            play.sim.launching = false;
            let mut rig = Rig::new((80, rows));
            rig.run(&mut play, 600);
            // fifty seconds of sailing to and fro, so the boat meets the troughs of many columns
            for tick in 0..3000 {
                if tick % 240 == 0 {
                    let (off, on) = if (tick / 240) % 2 == 0 {
                        (KeyCode::Left, KeyCode::Right)
                    } else {
                        (KeyCode::Right, KeyCode::Left)
                    };
                    rig.release(off);
                    rig.press(on);
                }
                rig.update(&mut play);
                assert!(
                    play.sim.sailors[0].boat.keel < 2.0 * rows as f32,
                    "{rows} rows: the keel is at pixel {} of {}",
                    play.sim.sailors[0].boat.keel,
                    2 * rows
                );
            }
        }
    }
}