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

// TODO: auto-allocate corsair hits?
// TODO: don't auto-allocate gunboats?

const US = "United States";
const TR = "Tripolitania";

const { SPACES, PIECES } = require('./data');

exports.scenarios = [
	"Fortress Tripoli",
	"Standard",
];

exports.roles = [ US, TR ];

function get_piece_id(name) {
	return PIECES.indexOf(name);
}

function get_space_id(name) {
	return SPACES.indexOf(name);
}

function create_piece_list(n, name) {
	let list = [];
	for (let i = 1; i <= n; ++i)
		list.push(get_piece_id(name + i));
	return list;
}

const US_FRIGATES = create_piece_list(8, 'us_frigate_');
const TR_FRIGATES = create_piece_list(2, 'tr_frigate_');
const SE_FRIGATES = create_piece_list(2, 'se_frigate_');
const US_GUNBOATS = create_piece_list(3, 'us_gunboat_');
const TR_CORSAIRS = create_piece_list(9, 'tr_corsair_');
const AL_CORSAIRS = create_piece_list(9, 'al_corsair_');
const US_MARINES = create_piece_list(4, 'us_marine_');
const AR_INFANTRY = create_piece_list(10, 'ar_infantry_');
const TR_INFANTRY = create_piece_list(20, 'tr_infantry_');

const SPRING = 0;
const FALL = 2;
const WINTER = 3;
const SEASON_NAMES = [ "Spring", "Summer", "Fall", "Winter" ];

const ALEXANDRIA = get_space_id("Alexandria");
const ALGIERS = get_space_id("Algiers");
const ALGIERS_PATROL_ZONE = get_space_id("Algiers Patrol Zone");
const BENGHAZI = get_space_id("Benghazi");
const DERNE = get_space_id("Derne");
const GIBRALTAR = get_space_id("Gibraltar");
const GIBRALTAR_PATROL_ZONE = get_space_id("Gibraltar Patrol Zone");
const MALTA = get_space_id("Malta");
const TANGIER = get_space_id("Tangier");
const TANGIER_PATROL_ZONE = get_space_id("Tangier Patrol Zone");
const TRIPOLI = get_space_id("Tripoli");
const TRIPOLI_PATROL_ZONE = get_space_id("Tripoli Patrol Zone");
const TUNIS = get_space_id("Tunis");
const TUNIS_PATROL_ZONE = get_space_id("Tunis Patrol Zone");
const UNITED_STATES_SUPPLY = get_space_id("United States Supply");
const TRIPOLITAN_SUPPLY = get_space_id("Tripolitan Supply");
const TRACK_1801 = get_space_id("1801");
const TRACK_1802 = get_space_id("1802");
const TRACK_1803 = get_space_id("1803");
const TRACK_1804 = get_space_id("1804");
const TRACK_1805 = get_space_id("1805");
const TRACK_1806 = get_space_id("1806");

const YEAR_TURN_TRACK = {
	1801: TRACK_1801,
	1802: TRACK_1802,
	1803: TRACK_1803,
	1804: TRACK_1804,
	1805: TRACK_1805,
	1806: TRACK_1806,
};

const FRIGATE_SPACES = [
	ALEXANDRIA,
	ALGIERS,
	ALGIERS_PATROL_ZONE,
	BENGHAZI,
	DERNE,
	GIBRALTAR,
	GIBRALTAR_PATROL_ZONE,
	MALTA,
	TANGIER,
	TANGIER_PATROL_ZONE,
	TRIPOLI,
	TRIPOLI_PATROL_ZONE,
	TUNIS,
	TUNIS_PATROL_ZONE,
];

const BATTLE_SPACES = [
	ALGIERS,
	BENGHAZI,
	DERNE,
	TANGIER,
	TRIPOLI,
	TUNIS,
];

const PATROL_ZONES = [
	ALGIERS_PATROL_ZONE,
	GIBRALTAR_PATROL_ZONE,
	TANGIER_PATROL_ZONE,
	TRIPOLI_PATROL_ZONE,
	TUNIS_PATROL_ZONE,
];

const PATROL_ZONE_OF_HARBOR = {
	[ALGIERS]: ALGIERS_PATROL_ZONE,
	[GIBRALTAR]: GIBRALTAR_PATROL_ZONE,
	[TANGIER]: TANGIER_PATROL_ZONE,
	[TRIPOLI]: TRIPOLI_PATROL_ZONE,
	[TUNIS]: TUNIS_PATROL_ZONE,
}

const THOMAS_JEFFERSON = 1;
const SWEDISH_FRIGATES_ARRIVE = 2;
const HAMETS_ARMY_CREATED = 3;
const TREATY_OF_PEACE_AND_AMITY = 4;
const ASSAULT_ON_TRIPOLI = 5;
const NAVAL_MOVEMENT_1 = 6;
const NAVAL_MOVEMENT_2 = 7;
const NAVAL_MOVEMENT_3 = 8;
const NAVAL_MOVEMENT_4 = 9;
const EARLY_DEPLOYMENT = 10;
const A_SHOW_OF_FORCE = 11;
const TRIBUTE_PAID = 12;
const CONSTANTINOPLE_DEMANDS_TRIBUTE = 13;
const HAMET_RECRUITS_BEDOUINS = 14;
const BAINBRIDGE_SUPPLIES_INTEL = 15;
const CONGRESS_AUTHORIZES_ACTION = 16;
const CORSAIRS_CONFISCATED = 17;
const BURN_THE_PHILADELPHIA = 18;
const LAUNCH_THE_INTREPID = 19;
const GENERAL_EATON_ATTACKS_DERNE = 20;
const GENERAL_EATON_ATTACKS_BENGHAZI = 21;

const LIEUTENANT_STERETT_IN_PURSUIT = 22;
const PREBLES_BOYS_TAKE_AIM = 23;
const THE_DARING_STEPHEN_DECATUR = 24;
const SEND_IN_THE_MARINES = 25;
const LIEUTENANT_OBANNON_LEADS_THE_CHARGE = 26;
const MARINE_SHARPSHOOTERS = 27;

const YUSUF_QARAMANLI = 28;
const MURAD_REIS_BREAKS_OUT = 29;
const CONSTANTINOPLE_SENDS_AID = 30;
const US_SUPPLIES_RUN_LOW = 31;
const ALGERINE_CORSAIRS_RAID_1 = 32;
const ALGERINE_CORSAIRS_RAID_2 = 33;
const MOROCCAN_CORSAIRS_RAID_1 = 34;
const MOROCCAN_CORSAIRS_RAID_2 = 35;
const TUNISIAN_CORSAIRS_RAID_1 = 36;
const TUNISIAN_CORSAIRS_RAID_2 = 37;
const TROOPS_TO_DERNE = 38;
const TROOPS_TO_BENGHAZI = 39;
const TROOPS_TO_TRIPOLI = 40;
const STORMS = 41;
const TRIPOLI_ATTACKS = 42;
const SWEDEN_PAYS_TRIBUTE = 43;
const TRIPOLI_ACQUIRES_CORSAIRS = 44;
const THE_PHILADELPHIA_RUNS_AGROUND = 45;
const ALGIERS_DECLARES_WAR = 46;
const MOROCCO_DECLARES_WAR = 47;
const TUNIS_DECLARES_WAR = 48;

const US_SIGNAL_BOOKS_OVERBOARD = 49;
const UNCHARTED_WATERS = 50;
const MERCHANT_SHIP_CONVERTED = 51;
const HAPPY_HUNTING = 52;
const THE_GUNS_OF_TRIPOLI = 53;
const MERCENARIES_DESERT = 54;

const CARD_NAMES = [
	// No Card
	null,

	// United States Cards
	"Thomas Jefferson",
	"Swedish Frigates Arrive",
	"Hamet\u{2019}s Army Created",
	"Treaty of Peace and Amity",
	"Assault on Tripoli",
	"Naval Movement",
	"Naval Movement",
	"Naval Movement",
	"Naval Movement",
	"Early Deployment",
	"A Show of Force",
	"Tribute Paid",
	"Constantinople Demands Tribute",
	"Hamet Recruits Bedouins",
	"Bainbridge Supplies Intel",
	"Congress Authorizes Action",
	"Corsairs Confiscated",
	"Burn the Philadelphia",
	"Launch the Intrepid",
	"General Eaton Attacks Derne",
	"General Eaton Attacks Benghazi",
	"Lieutenant Sterett in Pursuit",
	"Preble\u{2019}s Boys Take Aim",
	"The Daring Stephen Decatur",
	"Send in the Marines",
	"Lieutenant O'Bannon Leads the Charge",
	"Marine Sharpshooters",

	// Tripolitan Cards
	"Yusuf Qaramanli",
	"Murad Reis Breaks Out",
	"Constantinople Sends Aid",
	"US Supplies Run Low",
	"Algerine Corsairs Raid",
	"Algerine Corsairs Raid",
	"Moroccan Corsairs Raid",
	"Moroccan Corsairs Raid",
	"Tunisian Corsairs Raid",
	"Tunisian Corsairs Raid",
	"Troops to Derne",
	"Troops to Benghazi",
	"Troops to Tripoli",
	"Storms",
	"Tripoli Attacks",
	"Sweden Pays Tribute",
	"Tripoli Acquires Corsairs",
	"The Philadelphia Runs Aground",
	"Algiers Declares War",
	"Morocco Declares War",
	"Tunis Declares War",
	"US Signal Books Overboard",
	"Uncharted Waters",
	"Merchant Ship Converted",
	"Happy Hunting",
	"The Guns of Tripoli",
	"Mercenaries Desert",
];

const REMOVE_AFTER_PLAY = [
	THOMAS_JEFFERSON,
	SWEDISH_FRIGATES_ARRIVE,
	HAMETS_ARMY_CREATED,
	CONGRESS_AUTHORIZES_ACTION,
	CORSAIRS_CONFISCATED,
	BURN_THE_PHILADELPHIA,
	LAUNCH_THE_INTREPID,
	GENERAL_EATON_ATTACKS_DERNE,
	GENERAL_EATON_ATTACKS_BENGHAZI,
	YUSUF_QARAMANLI,
	MURAD_REIS_BREAKS_OUT,
	CONSTANTINOPLE_SENDS_AID,
	SWEDEN_PAYS_TRIBUTE,
	TRIPOLI_ACQUIRES_CORSAIRS,
	THE_PHILADELPHIA_RUNS_AGROUND,
	ALGIERS_DECLARES_WAR,
	MOROCCO_DECLARES_WAR,
	TUNIS_DECLARES_WAR,
];

const states = {};

let game = null;

function random(n) {
	if (game.rng === 1)
		return Math.floor(((game.seed = game.seed * 48271 % 0x7fffffff) / 0x7fffffff) * n);
	return (game.seed = game.seed * 200105 % 34359738337) % n
}

function log(...args) {
	let s = Array.from(args).join("");
	game.log.push(s);
}

function log_blank() {
	game.log.push("");
}

function flush_summary(text, add_plural_s=false) {
	game.summary.sort();
	let last = game.summary[0];
	let n = 0;
	for (let entry of game.summary) {
		if (entry !== last) {
			if (add_plural_s && n > 1)
				text += "\n" + n + " " + last + "s";
			else
				text += "\n" + n + " " + last;
			n = 0;
		}
		++n;
		last = entry;
	}
	if (add_plural_s && n > 1)
		text += "\n" + n + " " + last + "s";
	else if (n > 0)
		text += "\n" + n + " " + last;
	else
		text += "\nnone";
	log(text);
	delete game.summary;
}

function is_inactive_player(current) {
	return current === "Observer" || (game.active !== current && game.active !== "Both");
}

function you_may_play(current, list) {
	let msg = is_inactive_player(current) ? " \u2014 opponent may play " : " \u2014 you may play ";
	if (Array.isArray(list)) {
		list = list.map(c => "\u201c" + CARD_NAMES[c] + "\u201d");
		if (list.length === 1)
			msg += list[0] + ".";
		else if (list.length === 2)
			msg += list[0] + " or " + list[1] + ".";
		else {
			for (let i = 0; i < list.length-1; ++i)
				msg += list[i] + ", ";
			msg += "or " + list[list.length-1] + ".";
		}
	} else {
		msg += "\u201c" + CARD_NAMES[list] + "\u201d.";
	}
	return msg;
}

function remove_from_array(array, item) {
	let i = array.indexOf(item);
	if (i >= 0)
		array.splice(i, 1);
}

function deep_copy(original) {
	if (Array.isArray(original)) {
		let n = original.length
		let copy = new Array(n)
		for (let i = 0; i < n; ++i) {
			let v = original[i]
			if (typeof v === "object" && v !== null)
				copy[i] = deep_copy(v)
			else
				copy[i] = v
		}
		return copy
	} else {
		let copy = {}
		for (let i in original) {
			let v = original[i]
			if (typeof v === "object" && v !== null)
				copy[i] = deep_copy(v)
			else
				copy[i] = v
		}
		return copy
	}
}

function push_undo() {
	let copy = {}
	for (let k in game) {
		let v = game[k]
		if (k === "undo") continue
		else if (k === "log") v = v.length
		else if (typeof v === "object" && v !== null) v = deep_copy(v)
		copy[k] = v
	}
	game.undo.push(copy)
}

function pop_undo() {
	let save_log = game.log
	let save_undo = game.undo
	game = save_undo.pop()
	save_log.length = game.log
	game.log = save_log
	game.undo = save_undo
}

function clear_undo() {
	game.undo = []
}

function gen_action_undo(view) {
	if (!view.actions)
		view.actions = {}
	if (game.undo && game.undo.length > 0)
		view.actions.undo = 1;
	else
		view.actions.undo = 0;
}

function gen_action(view, action, argument) {
	if (!view.actions)
		view.actions = {}
	if (argument !== undefined) {
		if (!(action in view.actions))
			view.actions[action] = [ argument ];
		else
			view.actions[action].push(argument);
	} else {
		view.actions[action] = 1;
	}
}

function roll_d6() {
	return random(6) + 1;
}

function reshuffle_discard(draw, discard) {
	while (discard.length > 0)
		draw.push(discard.pop());
}

function draw_cards(hand, draw, n) {
	for (let i = 0; i < n; ++i) {
		let c = random(draw.length);
		hand.push(draw[c]);
		draw.splice(c, 1);
	}
}

function discard_random_card(hand, discard) {
	let i = random(hand.length);
	let c = hand[i];
	discard.push(c);
	hand.splice(i, 1);
	return c;
}

function is_not_removed(card) {
	return game.us.hand.includes(card) ||
		game.us.draw.includes(card) ||
		game.us.discard.includes(card) ||
		game.tr.hand.includes(card) ||
		game.tr.draw.includes(card) ||
		game.tr.discard.includes(card);
}

function count_pieces(list, where) {
	let n = 0;
	for (let p of list)
		if (game.location[p] === where)
			++n;
	return n;
}

function discard_card(player, card, reason = "") {
	log(game.active + " discarded a card" + reason + ".");
	remove_from_array(player.hand, card);
	player.discard.push(card);
	game.active_card = game.active;
}

function play_card(player, card) {
	log(game.active + " played #" + card + ".");
	remove_from_array(player.core, card);
	remove_from_array(player.hand, card);
	remove_from_array(player.discard, card);
	if (!REMOVE_AFTER_PLAY.includes(card))
		player.discard.push(card);
	game.active_card = card;
}

function play_battle_card(player, card) {
	log(game.active + " played #" + card + ".");
	remove_from_array(player.hand, card);
}

function deploy(piece_name, space) {
	game.location[get_piece_id(piece_name)] = space;
}

function move_one_piece(list, from, to) {
	for (let p of list) {
		if (game.location[p] === from) {
			game.location[p] = to;
			return;
		}
	}
}

function move_all_pieces(list, from, to) {
	for (let p of list) {
		if (game.location[p] === from) {
			game.location[p] = to;
		}
	}
}

function roll_many_dice(what, n, hit=6) {
	let hits = 0;
	if (n > 0) {
		let rolls = [];
		for (let i = 0; i < n; ++i) {
			let roll = roll_d6();
			if (roll >= hit)
				++hits;
			rolls.push(roll);
		}
		log(what + rolls.join(", ") + ".");
	}
	return hits;
}

function count_swedish_frigates(where) {
	return count_pieces(SE_FRIGATES, where);
}

function count_available_american_frigates() {
	let n = 0;
	for (let space of FRIGATE_SPACES)
		n += count_pieces(US_FRIGATES, space);
	return n;
}

function count_american_frigates(where) {
	return count_pieces(US_FRIGATES, where);
}

function count_american_gunboats(where) {
	return count_pieces(US_GUNBOATS, where);
}

function count_tripolitan_frigates(where) {
	return count_pieces(TR_FRIGATES, where);
}

function count_tripolitan_corsairs(where) {
	return count_pieces(TR_CORSAIRS, where);
}

function count_allied_corsairs(where) {
	return count_pieces(AL_CORSAIRS, where);
}

function count_corsairs(where) {
	return count_tripolitan_corsairs(where) + count_allied_corsairs(where);
}

function count_tripolitan_infantry(where) {
	return count_pieces(TR_INFANTRY, where);
}

function count_american_marines(where) {
	return count_pieces(US_MARINES, where);
}

function count_arab_infantry(where) {
	return count_pieces(AR_INFANTRY, where);
}

function count_american_troops(where) {
	return count_american_marines(where) + count_arab_infantry(where);
}

function count_tripolitan_pieces(where) {
	return count_tripolitan_frigates(where) +
		count_tripolitan_corsairs(where) +
		count_tripolitan_infantry(where);
}

function is_fall_of_1805_or_later() {
	return ((game.year === 1805 && game.season >= FALL) || (game.year > 1805));
}

function hamets_army_location() {
	if (count_american_troops(ALEXANDRIA) > 0) return ALEXANDRIA;
	if (count_american_troops(DERNE) > 0) return DERNE;
	if (count_american_troops(BENGHAZI) > 0) return BENGHAZI;
	return null;
}

function is_hamets_army_created() {
	return hamets_army_location() !== null;
}

function is_derne_captured() {
	let space = hamets_army_location();
	return space === DERNE || space === BENGHAZI;
}

function is_benghazi_captured() {
	let space = hamets_army_location();
	return space === BENGHAZI;
}

function is_naval_battle_location(space) {
	let n_us = count_american_frigates(space);
	let n_tr = count_tripolitan_frigates(space) + count_corsairs(space);
	return (n_us > 0 && n_tr > 0);
}

function is_naval_bombardment_location(space) {
	let n_us = count_american_frigates(space) + count_american_gunboats(space);
	let n_tr = count_tripolitan_infantry(space);
	return (n_us > 0 && n_tr > 0);
}

function is_naval_battle_or_bombardment_location(space) {
	let n_us = count_american_frigates(space);
	let n_tr_ships = count_tripolitan_frigates(space) + count_corsairs(space);
	let n_tr_infantry = count_tripolitan_infantry(space);
	return (n_us > 0 && (n_tr_ships > 0 || n_tr_infantry > 0));
}

function count_naval_battle_or_bombardment_locations() {
	let n = 0;
	for (let space of BATTLE_SPACES)
		if (is_naval_battle_or_bombardment_location(space))
			++n;
	return n;
}

function can_build_gunboat_in_malta() {
	return count_pieces(US_GUNBOATS, UNITED_STATES_SUPPLY) > 0;
}

function can_build_corsair_in_tripoli() {
	return count_pieces(TR_CORSAIRS, TRIPOLITAN_SUPPLY) > 0;
}

function can_pirate_raid_from_tripoli() {
	return count_pieces(TR_CORSAIRS, TRIPOLI) > 0;
}

function start_of_year() {
	log(".year " + game.year);
	log_blank();

	game.season = SPRING;

	move_all_pieces(US_FRIGATES, YEAR_TURN_TRACK[game.year], GIBRALTAR);
	move_all_pieces(TR_FRIGATES, YEAR_TURN_TRACK[game.year], TRIPOLI);

	if (game.year <= 1804) {
		draw_cards(game.us.hand, game.us.draw, 6);
		draw_cards(game.tr.hand, game.tr.draw, 6);
	}
	if (game.year === 1805) {
		reshuffle_discard(game.us.draw, game.us.discard);
		draw_cards(game.us.hand, game.us.draw, 6);
		reshuffle_discard(game.tr.draw, game.tr.discard);
		draw_cards(game.tr.hand, game.tr.draw, 6);
	}
	if (game.year === 1806) {
		draw_cards(game.us.hand, game.us.draw, game.us.draw.length);
		draw_cards(game.tr.hand, game.tr.draw, game.tr.draw.length);
	}

	goto_hand_size();
}

function goto_hand_size() {
	game.state = 'hand_size';
	if (game.tr.hand.length > 8)
		game.tr.queue = [];
	if (game.us.hand.length > 8)
		game.us.queue = [];

	if (game.tr.queue && game.us.queue)
		game.active = "Both";
	else if (game.tr.queue)
		game.active = TR;
	else if (game.us.queue)
		game.active = US;
	else
		goto_american_play();
}

function format_discard(n) {
	if (n === 0) return " \u2014 done.";
	if (n === 1) return " \u2014 discard 1 card.";
	return " \u2014 discard " + n + " cards.";
}

states.hand_size = {
	prompt(view, current) {
		if (current === TR) {
			if (game.tr.queue) {
				view.actions = {};
				view.actions.undo = (game.tr.queue.length > 0);
				if (game.tr.hand.length > 8) {
					for (let c of game.tr.hand)
						gen_action(view, 'discard', c);
				} else {
					gen_action(view, 'next');
				}
				let n = game.tr.hand.length - 8;
				return view.prompt = "Tripolitania: Hand Limit" + format_discard(n);
			} else {
				return view.prompt = "United States: Hand Limit.";
			}
		}
		if (current === US) {
			if (game.us.queue) {
				view.actions = {};
				view.actions.undo = (game.us.queue.length > 0);
				if (game.us.hand.length > 8) {
					for (let c of game.us.hand)
						gen_action(view, 'discard', c);
				} else {
					gen_action(view, 'next');
				}
				let n = game.us.hand.length - 8;
				return view.prompt = "United States: Hand Limit" + format_discard(n);
			} else {
				return view.prompt = "Tripolitania: Hand Limit.";
			}
		}
		view.prompt = "Hand Limit.";
	},
	discard(card, current) {
		if (current === TR) {
			remove_from_array(game.tr.hand, card);
			game.tr.queue.push(card);
		}
		if (current === US) {
			remove_from_array(game.us.hand, card);
			game.us.queue.push(card);
		}
	},
	next(_, current) {
		if (current === TR) {
			let n = game.tr.queue.length;
			if (n > 1)
				log(current + " discarded " + n + " cards.");
			else if (n === 1)
				log(current + " discarded " + n + " card.");
			for (let card of game.tr.queue)
				game.tr.discard.push(card);
			delete game.tr.queue;
		}
		if (current === US) {
			let n = game.us.queue.length;
			if (n > 1)
				log(current + " discarded " + n + " cards.");
			else if (n === 1)
				log(current + " discarded " + n + " card.");
			for (let card of game.us.queue)
				game.us.discard.push(card);
			delete game.us.queue;
		}
		if (game.tr.queue && game.us.queue)
			game.active = "Both";
		else if (game.tr.queue)
			game.active = TR;
		else if (game.us.queue)
			game.active = US;
		else
			goto_american_play();
	},
	undo(_, current) {
		if (current === TR && game.tr.queue.length > 0) {
			let card = game.tr.queue.pop();
			game.tr.hand.push(card);
		}
		if (current === US && game.us.queue.length > 0) {
			let card = game.us.queue.pop();
			game.us.hand.push(card);
		}
	}
}

function goto_american_play() {
	log_blank();
	log(".season " + SEASON_NAMES[game.season]);
	log_blank();

	game.active = US;
	game.state = 'american_play';
}

function end_american_play() {
	log_blank();
	clear_undo();
	game.where = null;
	game.active = TR;
	game.state = 'tripolitan_play';
}

function end_tripolitan_play() {
	log_blank();
	clear_undo();
	game.where = null;
	end_of_season();
}

function end_of_season() {
	if (game.season === WINTER) {
		end_of_year();
	} else {
		++game.season;
		goto_american_play();
	}
}

function end_of_year() {
	if (game.year === 1806)
		return goto_game_over("Draw", "The game ended in a draw.");
	++game.year;
	start_of_year();
}

states.american_play = {
	prompt(view, current) {
		view.prompt = "United States: Play an event, move two frigates, or build a gunboat.";
		if (is_inactive_player(current))
			return;
		let build = can_build_gunboat_in_malta();
		for (let c of game.us.core) {
			if (can_play_american_event(c))
				gen_action(view, 'card_event', c);
		}
		for (let c of game.us.hand) {
			gen_action(view, 'card_move_frigates', c);
			if (build)
				gen_action(view, 'card_build_gunboat', c);
			if (can_play_american_event(c))
				gen_action(view, 'card_event', c);
		}
		if (game.us.hand.length === 0)
			gen_action(view, 'pass');
	},
	card_build_gunboat(c) {
		discard_card(game.us, c, " to build a gunboat in Malta");
		move_one_piece(US_GUNBOATS, UNITED_STATES_SUPPLY, MALTA);
		end_american_play();
	},
	card_move_frigates(c) {
		discard_card(game.us, c, " to move up to two frigates");
		goto_move_up_to_n_american_frigates(2);
	},
	card_event: play_american_event,
	pass() {
		log(game.active + " passed.");
		end_american_play();
	}
}

states.tripolitan_play = {
	prompt(view, current) {
		view.prompt = "Tripolitania: Play an event, pirate raid, or build a corsair.";
		if (is_inactive_player(current))
			return;
		let build = can_build_corsair_in_tripoli();
		let raid = can_pirate_raid_from_tripoli();
		for (let c of game.tr.core) {
			if (can_play_tripolitan_event(c))
				gen_action(view, 'card_event', c);
		}
		for (let c of game.tr.hand) {
			if (build)
				gen_action(view, 'card_build_corsair', c);
			if (raid)
				gen_action(view, 'card_pirate_raid', c);
			if (can_play_tripolitan_event(c))
				gen_action(view, 'card_event', c);
		}
		if (game.tr.hand.length === 0)
			gen_action(view, 'pass');
	},
	card_build_corsair(c) {
		discard_card(game.tr, c, " to build a corsair in Tripoli");
		move_one_piece(TR_CORSAIRS, TRIPOLITAN_SUPPLY, TRIPOLI);
		end_tripolitan_play();
	},
	card_pirate_raid(c) {
		discard_card(game.tr, c, " to Pirate Raid from Tripoli");
		goto_pirate_raid(TRIPOLI);
	},
	card_event: play_tripolitan_event,
	pass() {
		log(game.active + " passed.");
		end_tripolitan_play();
	}
}

// PIRATE RAID

function give_gold(n) {
	game.tr.gold += n;
	if (game.tr.gold > 12)
		game.tr.gold = 12;
}

function take_gold(n) {
	game.tr.gold -= n;
	if (game.tr.gold < 0)
		game.tr.gold = 0;
}

function goto_pirate_raid(from) {
	game.where = from;
	if (can_play_lieutenant_sterett_in_pursuit()) {
		game.active = US;
		game.state = 'raid_before_intercept';
		return;
	}
	goto_pirate_raid_intercept(2);
}

states.raid_before_intercept = {
	prompt(view, current) {
		view.prompt = "United States: Pirate Raid from " + SPACES[game.where];
		view.prompt += you_may_play(current, LIEUTENANT_STERETT_IN_PURSUIT);
		if (is_inactive_player(current))
			return;
		if (game.us.hand.includes(LIEUTENANT_STERETT_IN_PURSUIT))
			gen_action(view, 'card_event', LIEUTENANT_STERETT_IN_PURSUIT);
		gen_action(view, 'next');
	},
	card_event(card) {
		play_battle_card(game.us, card);
		game.active = TR;
		goto_pirate_raid_intercept(3);
	},
	next() {
		game.active = TR;
		goto_pirate_raid_intercept(2);
	},
}

function goto_pirate_raid_intercept(us_dice) {
	game.happy_hunting = false;
	interception_roll(game.where, us_dice);
	if (can_play_happy_hunting() || can_play_us_signal_books_overboard())
		game.state = 'raid_before_hunt';
	else
		goto_pirate_raid_hunt();
}

states.raid_before_hunt = {
	prompt(view, current) {
		let list = [];
		if (can_play_happy_hunting())
			list.push(HAPPY_HUNTING);
		if (can_play_us_signal_books_overboard())
			list.push(US_SIGNAL_BOOKS_OVERBOARD);
		view.prompt = "Tripolitania: Pirate Raid from " + SPACES[game.where];
		view.prompt += you_may_play(current, list);
		if (is_inactive_player(current))
			return;
		for (let card of list)
			if (game.tr.hand.includes(card))
				gen_action(view, 'card_event', card);
		gen_action(view, 'next');
	},
	card_event(card) {
		play_battle_card(game.tr, card);
		if (card === US_SIGNAL_BOOKS_OVERBOARD) {
			let c = discard_random_card(game.us.hand, game.us.discard);
			log("United States discarded #" + c + ".");
		}
		if (card === HAPPY_HUNTING) {
			game.happy_hunting = true;
		}
		if (!can_play_happy_hunting() && !can_play_us_signal_books_overboard())
			goto_pirate_raid_hunt();
	},
	next() {
		goto_pirate_raid_hunt();
	},
}

function goto_pirate_raid_hunt() {
	let corsairs = count_corsairs(game.where);
	let merchants = roll_many_dice("Corsairs raided: ", corsairs, 5);
	if (game.happy_hunting)
		merchants += roll_many_dice("Happy Hunting: ", 3, 5);
	delete game.happy_hunting;
	log("Captured: " + merchants + (merchants === 1 ? " merchant ship." : " merchant ships."));
	give_gold(merchants);
	if (check_gold_victory())
		return;
	if (can_play_merchant_ship_converted(merchants)) {
		game.state = 'raid_after_hunt';
		return;
	}
	end_pirate_raid();
}

states.raid_after_hunt = {
	prompt(view, current) {
		view.prompt = "Tripolitania: Pirate Raid from " + SPACES[game.where];
		view.prompt += you_may_play(current, MERCHANT_SHIP_CONVERTED);
		if (is_inactive_player(current))
			return;
		if (game.tr.hand.includes(MERCHANT_SHIP_CONVERTED))
			gen_action(view, 'card_event', MERCHANT_SHIP_CONVERTED);
		gen_action(view, 'next');
	},
	card_event(card) {
		play_battle_card(game.tr, card);
		move_one_piece(TR_CORSAIRS, TRIPOLITAN_SUPPLY, TRIPOLI);
		end_pirate_raid();
	},
	next() {
		end_pirate_raid();
	},
}

function end_pirate_raid() {
	if (game.raids)
		resume_yusuf_qaramanli();
	else
		end_tripolitan_play();
}

function interception_roll(harbor, us_dice) {
	let patrol_zone = PATROL_ZONE_OF_HARBOR[harbor];
	let n_se = count_swedish_frigates(patrol_zone);
	let n_us = count_american_frigates(patrol_zone);
	if (n_se + n_us > 0) {
		let n_tr = count_tripolitan_corsairs(harbor);
		let n_al = count_allied_corsairs(harbor);
		let hits = 0;
		hits += roll_many_dice("Swedish frigates intercepted:\n", n_se * 2, 6);
		hits += roll_many_dice("American frigates intercepted:\n", n_us * us_dice, 6);
		if (hits > n_tr + n_al)
			hits = n_tr + n_al;
		log("Intercepted: " + hits + (hits === 1 ? " corsair." : " corsairs."));
		if (n_tr > 0)
			for (let i = 0; i < hits; ++i)
				move_one_piece(TR_CORSAIRS, harbor, TRIPOLITAN_SUPPLY);
		else
			for (let i = 0; i < hits; ++i)
				move_one_piece(AL_CORSAIRS, harbor, TRIPOLITAN_SUPPLY);
	}
}

// AMERICAN NAVAL MOVEMENT

function goto_move_up_to_n_american_frigates(n) {
	game.summary = [];
	game.moves = n;
	game.active = US;
	game.state = 'move_us_frigate_from';
}

function format_moves_left() {
	if (game.moves === 0) return " \u2014 no moves left.";
	if (game.moves === 1) return " \u2014 1 move left.";
	return " \u2014 " + game.moves + " moves left.";
}

states.move_us_frigate_from = {
	prompt(view, current) {
		if (is_inactive_player(current))
			return view.prompt = "United States: Naval Movement.";
		view.prompt = "United States: Naval Movement" + format_moves_left();
		if (game.moves > 0) {
			for (let space of FRIGATE_SPACES) {
				if (count_american_frigates(space) > 0)
					gen_action(view, 'space', space);
			}
		}
		gen_action(view, 'next');
		gen_action_undo(view);
	},
	space(space) {
		push_undo();
		game.where = space;
		game.state = 'move_us_frigate_to'
	},
	next() {
		flush_summary("Frigates moved:");
		let n = count_naval_battle_or_bombardment_locations();
		if (n === 1)
			auto_allocate_gunboats();
		else if (n > 1)
			goto_allocate_gunboats();
		else
			end_american_play();
	},
	undo: pop_undo
}

states.move_us_frigate_to = {
	prompt(view, current) {
		if (is_inactive_player(current))
			return view.prompt = "United States: Naval Movement.";
		view.prompt = "United States: Naval Movement" + format_moves_left();
		for (let space of FRIGATE_SPACES) {
			if (space === TRIPOLI || space === BENGHAZI || space === DERNE)
				if (count_tripolitan_pieces(space) === 0)
					continue; // nothing to do here...
			gen_action(view, 'space', space);
		}
		gen_action(view, 'next');
		gen_action_undo(view);
	},
	space(space) {
		push_undo();
		if (space !== game.where) {
			game.summary.push(SPACES[game.where] + " to " + SPACES[space]);
			move_one_piece(US_FRIGATES, game.where, space);
			--game.moves;
			if (count_american_frigates(game.where) > 0 && game.moves > 0)
				return;
		}
		game.where = null;
		game.state = 'move_us_frigate_from'
	},
	next() {
		flush_summary("Frigates moved:");
		let n = count_naval_battle_or_bombardment_locations();
		if (n === 1)
			auto_allocate_gunboats();
		else if (n > 1)
			goto_allocate_gunboats();
		else
			end_american_play();
	},
	undo: pop_undo
}

function auto_allocate_gunboats() {
	for (let space of BATTLE_SPACES) {
		if (is_naval_battle_location(space)) {
			move_all_pieces(US_GUNBOATS, MALTA, space);
			return goto_naval_battle(space);
		}
		if (is_naval_bombardment_location(space)) {
			move_all_pieces(US_GUNBOATS, MALTA, space);
			return goto_naval_bombardment(space);
		}
	}
}

function goto_allocate_gunboats() {
	if (count_american_gunboats(MALTA) === 0)
		return goto_select_battle();
	game.summary = [];
	game.where = MALTA;
	game.state = 'allocate_gunboats';
}

states.allocate_gunboats = {
	prompt(view, current) {
		view.prompt = "United States: Allocate gunboats to battle locations.";
		if (is_inactive_player(current))
			return;
		if (count_american_gunboats(MALTA) > 0) {
			for (let space of BATTLE_SPACES)
				if (is_naval_battle_or_bombardment_location(space))
					gen_action(view, 'space', space);
		}
		gen_action(view, 'next');
		gen_action_undo(view);
	},
	space(space) {
		push_undo();
		game.summary.push(SPACES[space]);
		move_one_piece(US_GUNBOATS, MALTA, space);
	},
	next() {
		flush_summary("Gunboats allocated:");
		game.where = null;
		goto_select_battle();
	},
	undo: pop_undo
}

function goto_select_battle() {
	clear_undo();
	game.where = null;
	game.active = US;
	if (count_naval_battle_or_bombardment_locations() > 0)
		game.state = 'select_battle';
	else
		end_american_play();
}

states.select_battle = {
	prompt(view, current) {
		view.prompt = "United States: Pick the next naval battle or bombardment."
			if (is_inactive_player(current))
				return;
		for (let space of BATTLE_SPACES)
			if (is_naval_battle_or_bombardment_location(space))
				gen_action(view, 'space', space);
	},
	space(space) {
		if (is_naval_battle_location(space))
			goto_naval_battle(space);
		else
			goto_naval_bombardment(space);
	},
}

// NAVAL BOMBARDMENT

function goto_naval_bombardment(space) {
	game.where = space;
	naval_bombardment_round();
	game.state = 'naval_bombardment_results';
}

function naval_bombardment_round() {
	let n_frigates = count_american_frigates(game.where);
	let n_gunboats = count_american_gunboats(game.where);
	if (n_frigates + n_gunboats > 0) {
		let n_infantry = count_tripolitan_infantry(game.where);
		let n_hits = 0;
		log_blank();
		log("Naval bombardment in " + SPACES[game.where] + ".");
		n_hits += roll_many_dice("American frigates:\n", n_frigates * 2, 6);
		n_hits += roll_many_dice("American gunboats:\n", n_gunboats, 6);
		if (n_hits > n_infantry)
			n_hits = n_infantry;
		log("Infantry eliminated: " + n_hits + ".");
		game.flash = n_hits + " infantry eliminated."
		for (let i = 0; i < n_hits; ++i)
			move_one_piece(TR_INFANTRY, game.where, TRIPOLITAN_SUPPLY);
	}
}

states.naval_bombardment_results = {
	prompt(view, current) {
		view.prompt = "Naval Bombardment in " + SPACES[game.where] + " \u2014 " + game.flash;
		if (is_inactive_player(current))
			return;
		gen_action(view, 'next');
	},
	next() {
		delete game.flash;
		end_naval_bombardment();
	},
}

function end_naval_bombardment() {
	move_all_pieces(US_FRIGATES, game.where, MALTA);
	move_all_pieces(US_GUNBOATS, game.where, MALTA);
	goto_select_battle();
}

// NAVAL BATTLE

function goto_naval_battle(space) {
	game.save_active = game.active;
	game.where = space;
	game.round = 0;
	log_blank();
	log("Naval battle in " + SPACES[game.where] + ".");
	goto_naval_battle_american_card();
}

function goto_naval_battle_american_card() {
	game.prebles_boys_take_aim = false;
	if (can_play_prebles_boys_take_aim()) {
		game.active = US;
		game.state = 'naval_battle_american_card';
		return;
	}
	goto_naval_battle_tripolitan_card();
}

states.naval_battle_american_card = {
	prompt(view, current) {
		view.prompt = "United States: Naval Battle in " + SPACES[game.where];
		view.prompt += you_may_play(current, PREBLES_BOYS_TAKE_AIM);
		if (is_inactive_player(current))
			return;
		if (game.us.hand.includes(PREBLES_BOYS_TAKE_AIM))
			gen_action(view, 'card_event', PREBLES_BOYS_TAKE_AIM);
		gen_action(view, 'next');
	},
	card_event(card) {
		play_battle_card(game.us, card);
		game.prebles_boys_take_aim = true;
		goto_naval_battle_tripolitan_card();
	},
	next() {
		goto_naval_battle_tripolitan_card();
	},
}

function goto_naval_battle_tripolitan_card() {
	game.the_guns_of_tripoli = false;
	if (can_play_the_guns_of_tripoli()) {
		game.active = TR;
		game.state = 'naval_battle_tripolitan_card';
		return;
	}
	goto_naval_battle_round();
}

states.naval_battle_tripolitan_card = {
	prompt(view, current) {
		view.prompt = "Tripolitania: Naval Battle in " + SPACES[game.where];
		view.prompt += you_may_play(current, THE_GUNS_OF_TRIPOLI);
		if (is_inactive_player(current))
			return;
		if (game.tr.hand.includes(THE_GUNS_OF_TRIPOLI))
			gen_action(view, 'card_event', THE_GUNS_OF_TRIPOLI);
		gen_action(view, 'next');
	},
	card_event(card) {
		play_battle_card(game.tr, card);
		game.the_guns_of_tripoli = true;
		goto_naval_battle_round();
	},
	next() {
		goto_naval_battle_round();
	},
}

function goto_naval_battle_round() {
	clear_undo();

	game.active = game.save_active;
	game.round ++;

	if (game.active_card === ASSAULT_ON_TRIPOLI) {
		log_blank();
		log("Naval battle round " + game.round + ".");
	}

	let n_us_frigates = count_american_frigates(game.where);
	let n_us_gunboats = count_american_gunboats(game.where);
	let n_tr_frigates = count_tripolitan_frigates(game.where);
	let n_tr_corsairs = count_tripolitan_corsairs(game.where);
	let n_al_corsairs = count_allied_corsairs(game.where);

	game.n_tr_hits = 0;
	if (game.prebles_boys_take_aim)
		game.n_tr_hits += roll_many_dice("American frigates:\n", n_us_frigates * 3, 6);
	else
		game.n_tr_hits += roll_many_dice("American frigates:\n", n_us_frigates * 2, 6);
	game.n_tr_hits += roll_many_dice("American gunboats:\n", n_us_gunboats, 6);

	game.n_us_hits = 0;
	if (game.the_guns_of_tripoli)
		game.n_us_hits += roll_many_dice("The Guns of Tripoli:\n", 12, 6);
	if (game.fortress && game.where === TRIPOLI && game.round === 1)
		game.n_us_hits += roll_many_dice("Fortress Tripoli:\n", 6, 6);
	game.n_us_hits += roll_many_dice("Tripolitan frigates:\n", n_tr_frigates * 2, 6);
	game.n_us_hits += roll_many_dice("Tripolitan corsairs:\n", n_tr_corsairs, 6);
	game.n_us_hits += roll_many_dice("Allied corsairs:\n", n_al_corsairs, 6);

	log("United States scored " + game.n_tr_hits + (game.n_tr_hits === 1 ? " hit." : " hits."));
	log("Tripolitania scored " + game.n_us_hits + (game.n_us_hits === 1 ? " hit." : " hits."));

	game.summary = [];
	if (game.save_active === US)
		goto_allocate_american_hits();
	else
		goto_allocate_tripolitan_hits();
}

function goto_allocate_american_hits() {
	game.active = US;
	game.state = 'allocate_us_hits';
}

function goto_allocate_tripolitan_hits() {
	game.active = TR;
	game.state = 'allocate_tr_hits';
}

function format_allocate_hits(n) {
	if (n === 0) return "Allocate hits \u2014 done.";
	if (n === 1) return "Allocate hits \u2014 1 left.";
	return "Allocate hits \u2014 " + n + " left.";
}

states.allocate_us_hits = {
	prompt(view, current) {
		view.prompt = "United States: " + format_allocate_hits(game.n_us_hits);
		if (is_inactive_player(current))
			return;
		gen_action_undo(view);
		if (count_american_frigates(game.where) + count_american_gunboats(game.where) === 0)
			gen_action(view, 'next');
		if (game.n_us_hits > 0) {
			for (let p of US_FRIGATES)
				if (game.location[p] === game.where)
					gen_action(view, 'piece', p);
			for (let p of US_GUNBOATS)
				if (game.location[p] === game.where)
					gen_action(view, 'piece', p);
		} else {
			gen_action(view, 'next');
		}
	},
	piece(p) {
		push_undo();
		--game.n_us_hits;
		if (US_FRIGATES.includes(p)) {
			if (game.damaged.includes(p)) {
				game.summary.push("American frigate sunk");
				game.location[p] = TRIPOLITAN_SUPPLY;
				remove_from_array(game.damaged, p);
			} else {
				game.damaged.push(p);
			}
		}
		if (US_GUNBOATS.includes(p)) {
			game.summary.push("American gunboat");
			move_one_piece(US_GUNBOATS, game.where, UNITED_STATES_SUPPLY);
		}
	},
	next() {
		clear_undo();
		if (check_frigate_victory())
			return;
		if (game.save_active === US)
			goto_allocate_tripolitan_hits();
		else
			resume_naval_battle();
	},
	undo: pop_undo
}

states.allocate_tr_hits = {
	prompt(view, current) {
		view.prompt = "Tripolitania: " + format_allocate_hits(game.n_tr_hits);
		if (is_inactive_player(current))
			return;
		gen_action_undo(view);
		if (count_tripolitan_frigates(game.where) + count_tripolitan_corsairs(game.where) + count_allied_corsairs(game.where) === 0)
			gen_action(view, 'next');
		if (game.n_tr_hits > 0) {
			for (let p of TR_FRIGATES)
				if (game.location[p] === game.where)
					gen_action(view, 'piece', p);
			for (let p of TR_CORSAIRS)
				if (game.location[p] === game.where)
					gen_action(view, 'piece', p);
			for (let p of AL_CORSAIRS)
				if (game.location[p] === game.where)
					gen_action(view, 'piece', p);
		} else {
			gen_action(view, 'next');
		}
	},
	piece(p) {
		push_undo();
		--game.n_tr_hits;
		if (TR_FRIGATES.includes(p)) {
			if (game.damaged.includes(p)) {
				game.summary.push("Tripolitan frigate sunk");
				game.location[p] = TRIPOLITAN_SUPPLY;
				remove_from_array(game.damaged, p);
			} else {
				game.damaged.push(p);
			}
		}
		if (TR_CORSAIRS.includes(p)) {
			game.summary.push("Tripolitan corsair");
			move_one_piece(TR_CORSAIRS, game.where, TRIPOLITAN_SUPPLY);
		}
		if (AL_CORSAIRS.includes(p)) {
			game.summary.push("Allied corsair");
			move_one_piece(AL_CORSAIRS, game.where, TRIPOLITAN_SUPPLY);
		}
	},
	next() {
		clear_undo();
		if (game.save_active === TR)
			goto_allocate_american_hits();
		else
			resume_naval_battle();
	},
	undo: pop_undo
}

function move_damaged_frigate_to_year_track(p, supply) {
	if (game.year === 1806 || game.active_card === ASSAULT_ON_TRIPOLI)
		game.location[p] = supply;
	else
		game.location[p] = YEAR_TURN_TRACK[game.year + 1];
	remove_from_array(game.damaged, p);
}

function remove_damaged_frigates() {
	for (let p of US_FRIGATES) {
		if (game.damaged.includes(p)) {
			game.summary.push("American frigate");
			move_damaged_frigate_to_year_track(p, UNITED_STATES_SUPPLY);
		}
	}
	for (let p of TR_FRIGATES) {
		if (game.damaged.includes(p)) {
			game.summary.push("Tripolitan frigate");
			move_damaged_frigate_to_year_track(p, TRIPOLITAN_SUPPLY);
		}
	}
}

function resume_naval_battle() {
	delete game.the_guns_of_tripoli;
	delete game.prebles_boys_take_aim;

	flush_summary("Ships sunk:", true)

	if (game.active_card === ASSAULT_ON_TRIPOLI) {
		let n_tr = count_tripolitan_frigates(game.where) + count_tripolitan_corsairs(game.where);
		let n_us = count_american_frigates(game.where) + count_american_gunboats(game.where);
		if (n_tr === 0) {
			log("The Tripolitan fleet was eliminated.");
			move_all_pieces(US_MARINES, BENGHAZI, TRIPOLI);
			move_all_pieces(AR_INFANTRY, BENGHAZI, TRIPOLI);

			game.summary = [];
			remove_damaged_frigates();
			flush_summary("Ships damaged:", true)

			if (is_naval_bombardment_location(game.where)) {
				naval_bombardment_round();
				game.state = 'land_battle_bombardment_results';
			} else {
				goto_land_battle();
			}
			return;
		}
		if (n_us === 0) {
			log("The American fleet was eliminated.");
			return goto_game_over(TR, "Assault on Tripoli failed.");
		}
		return goto_naval_battle_round();
	}

	delete game.save_active;

	game.summary = [];
	remove_damaged_frigates();
	flush_summary("Ships damaged:", true)

	move_all_pieces(US_FRIGATES, game.where, MALTA);
	move_all_pieces(US_GUNBOATS, game.where, MALTA);

	if (game.where === TRIPOLI_PATROL_ZONE) {
		move_all_pieces(TR_FRIGATES, game.where, TRIPOLI);
		move_all_pieces(TR_CORSAIRS, game.where, TRIPOLI);
	}

	switch (game.active_card) {
	case TRIPOLI_ATTACKS:
	case ALGIERS_DECLARES_WAR:
	case MOROCCO_DECLARES_WAR:
	case TUNIS_DECLARES_WAR:
		end_tripolitan_play();
		break;
	default:
		goto_select_battle();
		break;
	}
}

// LAND BATTLE

states.land_battle_move_frigates = {
	prompt(view, current) {
		view.prompt = "United States: " + CARD_NAMES[game.active_card] + ".";
		if (is_inactive_player(current))
			return;
		view.prompt += " Move frigates to " + SPACES[game.where] + format_moves_left();
		gen_action_undo(view);
		gen_action(view, 'next');
		if (game.moves > 0) {
			for (let space of FRIGATE_SPACES)
				if (space !== game.where)
					if (count_american_frigates(space) > 0)
						gen_action(view, 'space', space);
		}
	},
	space(space) {
		push_undo();
		--game.moves;
		move_one_piece(US_FRIGATES, space, game.where);
	},
	next() {
		let n = count_american_frigates(game.where);
		log(n + " American frigates moved to " + SPACES[game.where] + ".");
		if (is_naval_bombardment_location(game.where)) {
			move_all_pieces(US_GUNBOATS, MALTA, game.where);
			naval_bombardment_round();
			game.state = 'land_battle_bombardment_results';
		} else {
			goto_land_battle();
		}
	},
	undo: pop_undo
}

states.land_battle_bombardment_results = {
	prompt(view, current) {
		view.prompt = "Naval Bombardment in " + SPACES[game.where] + " \u2014 " + game.flash;
		if (is_inactive_player(current))
			return;
		gen_action(view, 'next');
	},
	next() {
		delete game.flash;

		log_blank();
		log("Land battle in " + SPACES[game.where] + ".");

		goto_land_battle();
	},
}

function goto_land_battle() {
	game.round = 0;
	move_all_pieces(US_FRIGATES, game.where, MALTA);
	move_all_pieces(US_GUNBOATS, game.where, MALTA);
	goto_land_battle_american_card();
}

function goto_land_battle_american_card() {
	game.marine_sharpshooters = false;
	game.lieutenant_obannon_leads_the_charge = false;
	if (can_play_american_land_battle_card()) {
		game.active = US;
		game.state = 'land_battle_american_card';
	} else {
		goto_land_battle_tripolitan_card();
	}
}

states.land_battle_american_card = {
	prompt(view, current) {
		let list = [];
		if (can_play_send_in_the_marines())
			list.push(SEND_IN_THE_MARINES);
		if (can_play_marine_sharpshooters())
			list.push(MARINE_SHARPSHOOTERS);
		if (can_play_lieutenant_obannon_leads_the_charge())
			list.push(LIEUTENANT_OBANNON_LEADS_THE_CHARGE);
		view.prompt = "United States: Land Battle in " + SPACES[game.where];
		view.prompt += you_may_play(current, list);
		if (is_inactive_player(current))
			return;
		for (let card of list)
			if (game.us.hand.includes(card))
				gen_action(view, 'card_event', card);
		gen_action(view, 'next');
	},
	card_event(card) {
		play_battle_card(game.us, card);
		switch (card) {
		case SEND_IN_THE_MARINES:
			move_one_piece(US_MARINES, UNITED_STATES_SUPPLY, TRIPOLI);
			move_one_piece(US_MARINES, UNITED_STATES_SUPPLY, TRIPOLI);
			move_one_piece(US_MARINES, UNITED_STATES_SUPPLY, TRIPOLI);
			break;
		case MARINE_SHARPSHOOTERS:
			game.marine_sharpshooters = true;
			break;
		case LIEUTENANT_OBANNON_LEADS_THE_CHARGE:
			game.lieutenant_obannon_leads_the_charge = true;
			break;
		}
		if (!can_play_american_land_battle_card())
			goto_land_battle_tripolitan_card();
	},
	next() {
		goto_land_battle_tripolitan_card();
	},
}

function goto_land_battle_tripolitan_card() {
	if (can_play_mercenaries_desert()) {
		game.active = TR;
		game.state = 'land_battle_tripolitan_card';
	} else {
		goto_land_battle_round();
	}
}

states.land_battle_tripolitan_card = {
	prompt(view, current) {
		view.prompt = "Tripolitania: Land Battle in " + SPACES[game.where];
		view.prompt += you_may_play(current, MERCENARIES_DESERT);
		if (is_inactive_player(current))
			return;
		if (game.tr.hand.includes(MERCENARIES_DESERT))
			gen_action(view, 'card_event', MERCENARIES_DESERT);
		gen_action(view, 'next');
	},
	card_event(card) {
		play_battle_card(game.tr, card);
		let n = roll_many_dice("Mercenaries Desert:\n", count_arab_infantry(game.where), 6);
		for (let i = 0; i < n; ++i)
			move_one_piece(AR_INFANTRY, game.where, UNITED_STATES_SUPPLY);
		log("Deserters: " + n + " Arab infantry.");
		game.flash = n + " Arab infantry deserted.";
		game.state = 'mercenaries_desert_results';
	},
	next() {
		goto_land_battle_round();
	},
}

states.mercenaries_desert_results = {
	prompt(view, current) {
		view.prompt = "Mercenaries Desert in " + SPACES[game.where] + " \u2014 " + game.flash;
		if (is_inactive_player(current))
			return;
		gen_action(view, 'next');
	},
	next() {
		delete game.flash;
		goto_land_battle_round();
	},
}

function goto_land_battle_round() {
	delete game.flash;
	game.active = US;
	game.round ++;

	let n_us_mar = count_american_marines(game.where);
	let n_ar_inf = count_arab_infantry(game.where);
	let n_tr_inf = count_tripolitan_infantry(game.where);

	if (n_us_mar + n_ar_inf === 0) {
		delete game.marine_sharpshooters;
		delete game.lieutenant_obannon_leads_the_charge;
		return goto_game_over(TR, "Hamet\u{2019}s Army was eliminated.");
	}

	if (n_tr_inf === 0) {
		log("Americans captured " + SPACES[game.where] + ".");
		delete game.marine_sharpshooters;
		delete game.lieutenant_obannon_leads_the_charge;
		if (game.active_card === ASSAULT_ON_TRIPOLI)
			return goto_game_over(US, "Assault on Tripoli.");
		return end_american_play();
	}

	log_blank();
	log("Land battle round " + game.round + ".");

	let n_tr_hits = 0;
	if (game.lieutenant_obannon_leads_the_charge && n_us_mar > 0) {
		if (game.marine_sharpshooters) {
			n_tr_hits += roll_many_dice("Lieutenant O'Bannon: ", 3, 5);
			n_tr_hits += roll_many_dice("American marines: ", n_us_mar - 1, 5);
		} else {
			n_tr_hits += roll_many_dice("Lieutenant O'Bannon: ", 3, 6);
			n_tr_hits += roll_many_dice("American marines: ", n_us_mar - 1, 6);
		}
	} else {
		if (game.marine_sharpshooters)
			n_tr_hits += roll_many_dice("American marines: ", n_us_mar, 5);
		else
			n_tr_hits += roll_many_dice("American marines: ", n_us_mar, 6);
	}
	n_tr_hits += roll_many_dice("Arab infantry: ", n_ar_inf);

	let n_us_hits = roll_many_dice("Tripolitan infantry: ", n_tr_inf);

	if (game.fortress && game.where === TRIPOLI && game.round === 1)
		n_us_hits += roll_many_dice("Fortress Tripoli: ", 6, 6);

	game.flash = apply_tr_hits(n_tr_hits) + apply_us_hits(n_us_hits);
	log("Losses: " + game.flash + ".");
	game.state = 'land_battle_results';
}

states.land_battle_results = {
	prompt(view, current) {
		view.prompt = "Land Battle in " + SPACES[game.where] + " \u2014 " + game.flash + " lost.";
		if (is_inactive_player(current))
			return;
		gen_action(view, 'next');
	},
	next() {
		goto_land_battle_round();
	},
}

function apply_tr_hits(n) {
	let max = count_tripolitan_infantry(game.where);
	if (n > max)
		n = max;
	for (let i = 0; i < n; ++i)
		move_one_piece(TR_INFANTRY, game.where, TRIPOLITAN_SUPPLY);
	return "\n" + n + " Tripolitan infantry,"
}

function apply_us_hits(total) {
	let n = total;
	let max_ar = count_arab_infantry(game.where);
	if (n > max_ar)
		n = max_ar;
	for (let i = 0; i < n; ++i)
		move_one_piece(AR_INFANTRY, game.where, UNITED_STATES_SUPPLY);
	let msg = "\n" + n + " Arab infantry,"

	n = total - n;
	let max_us = count_american_marines(game.where);
	if (n > max_us)
		n = max_us;
	for (let i = 0; i < n; ++i)
		move_one_piece(US_MARINES, game.where, UNITED_STATES_SUPPLY);
	if (n === 1)
		return msg + "\n" + n + " American marine"
	else
		return msg + "\n" + n + " American marines"
}

// TRIPOLITAN EVENTS

function can_play_tripolitan_event(card) {
	switch (card) {
	case YUSUF_QARAMANLI: return can_play_yusuf_qaramanli();
	case MURAD_REIS_BREAKS_OUT: return can_play_murad_reis_breaks_out();
	case CONSTANTINOPLE_SENDS_AID: return can_play_constantinople_sends_aid();
	case US_SUPPLIES_RUN_LOW: return can_play_us_supplies_run_low();
	case ALGERINE_CORSAIRS_RAID_1: return can_play_algerine_corsairs_raid();
	case ALGERINE_CORSAIRS_RAID_2: return can_play_algerine_corsairs_raid();
	case MOROCCAN_CORSAIRS_RAID_1: return can_play_moroccan_corsairs_raid();
	case MOROCCAN_CORSAIRS_RAID_2: return can_play_moroccan_corsairs_raid();
	case TUNISIAN_CORSAIRS_RAID_1: return can_play_tunisian_corsairs_raid();
	case TUNISIAN_CORSAIRS_RAID_2: return can_play_tunisian_corsairs_raid();
	case TROOPS_TO_DERNE: return can_play_troops_to_derne();
	case TROOPS_TO_BENGHAZI: return can_play_troops_to_benghazi();
	case TROOPS_TO_TRIPOLI: return can_play_troops_to_tripoli();
	case STORMS: return can_play_storms();
	case TRIPOLI_ATTACKS: return can_play_tripoli_attacks();
	case SWEDEN_PAYS_TRIBUTE: return can_play_sweden_pays_tribute();
	case TRIPOLI_ACQUIRES_CORSAIRS: return can_play_tripoli_acquires_corsairs();
	case THE_PHILADELPHIA_RUNS_AGROUND: return can_play_the_philadelphia_runs_aground();
	case ALGIERS_DECLARES_WAR: return can_play_algiers_declares_war();
	case MOROCCO_DECLARES_WAR: return can_play_morocco_declares_war();
	case TUNIS_DECLARES_WAR: return can_play_tunis_declares_war();
	}
	return false;
}

function play_tripolitan_event(card) {
	play_card(game.tr, card);
	switch (card) {
	case YUSUF_QARAMANLI: return play_yusuf_qaramanli();
	case MURAD_REIS_BREAKS_OUT: return play_murad_reis_breaks_out();
	case CONSTANTINOPLE_SENDS_AID: return play_constantinople_sends_aid();
	case US_SUPPLIES_RUN_LOW: return play_us_supplies_run_low();
	case ALGERINE_CORSAIRS_RAID_1: return play_algerine_corsairs_raid();
	case ALGERINE_CORSAIRS_RAID_2: return play_algerine_corsairs_raid();
	case MOROCCAN_CORSAIRS_RAID_1: return play_moroccan_corsairs_raid();
	case MOROCCAN_CORSAIRS_RAID_2: return play_moroccan_corsairs_raid();
	case TUNISIAN_CORSAIRS_RAID_1: return play_tunisian_corsairs_raid();
	case TUNISIAN_CORSAIRS_RAID_2: return play_tunisian_corsairs_raid();
	case TROOPS_TO_DERNE: return play_troops_to_derne();
	case TROOPS_TO_BENGHAZI: return play_troops_to_benghazi();
	case TROOPS_TO_TRIPOLI: return play_troops_to_tripoli();
	case STORMS: return play_storms();
	case TRIPOLI_ATTACKS: return play_tripoli_attacks();
	case SWEDEN_PAYS_TRIBUTE: return play_sweden_pays_tribute();
	case TRIPOLI_ACQUIRES_CORSAIRS: return play_tripoli_acquires_corsairs();
	case THE_PHILADELPHIA_RUNS_AGROUND: return play_the_philadelphia_runs_aground();
	case ALGIERS_DECLARES_WAR: return play_algiers_declares_war();
	case MOROCCO_DECLARES_WAR: return play_morocco_declares_war();
	case TUNIS_DECLARES_WAR: return play_tunis_declares_war();
	}
	throw Error(card + " is not a Tripolitan event card.");
}

function can_play_yusuf_qaramanli() {
	let n = count_allied_corsairs(ALGIERS) +
		count_allied_corsairs(TANGIER) +
		count_allied_corsairs(TUNIS) +
		count_tripolitan_corsairs(TRIPOLI);
	return n > 0;
}

function play_yusuf_qaramanli() {
	game.state = 'yusuf_qaramanli';
	game.raids = [];
	if (count_allied_corsairs(ALGIERS) > 0) game.raids.push(ALGIERS);
	if (count_allied_corsairs(TANGIER) > 0) game.raids.push(TANGIER);
	if (count_allied_corsairs(TUNIS) > 0) game.raids.push(TUNIS);
	if (count_tripolitan_corsairs(TRIPOLI) > 0) game.raids.push(TRIPOLI);
}

function resume_yusuf_qaramanli() {
	game.where = null;
	if (game.raids.length > 0)
		game.state = 'yusuf_qaramanli';
	else
		end_tripolitan_play();
}

states.yusuf_qaramanli = {
	prompt(view, current) {
		view.prompt = "Tripolitania: Yusuf Qaramanli.";
		if (is_inactive_player(current))
			return;
		view.prompt += " Select a harbor with corsairs to pirate raid from."
			for (let space of game.raids)
				gen_action(view, 'space', space);
	},
	space(space) {
		log_blank();
		log("Pirate raid from " + SPACES[space] + ".");
		remove_from_array(game.raids, space);
		switch (space) {
		case ALGIERS: return goto_pirate_raid(ALGIERS);
		case TANGIER: return goto_pirate_raid(TANGIER);
		case TUNIS: return goto_pirate_raid(TUNIS);
		case TRIPOLI: return goto_pirate_raid(TRIPOLI);
		}
	},
}

function can_play_murad_reis_breaks_out() {
	return true;
}

function play_murad_reis_breaks_out() {
	game.where = GIBRALTAR;
	if (can_play_lieutenant_sterett_in_pursuit()) {
		game.active = US;
		game.state = 'murad_reis_breaks_out';
	} else {
		end_murad_reis_breaks_out(2);
	}
}

states.murad_reis_breaks_out = {
	prompt(view, current) {
		view.prompt = "United States: Murad Reis Breaks Out";
		view.prompt += you_may_play(current, LIEUTENANT_STERETT_IN_PURSUIT);
		if (is_inactive_player(current))
			return;
		if (game.us.hand.includes(LIEUTENANT_STERETT_IN_PURSUIT))
			gen_action(view, 'card_event', LIEUTENANT_STERETT_IN_PURSUIT);
		gen_action(view, 'next');
	},
	card_event(card) {
		play_battle_card(game.us, card);
		game.active = TR;
		end_murad_reis_breaks_out(3);
	},
	next() {
		game.active = TR;
		end_murad_reis_breaks_out(2);
	},
}

function end_murad_reis_breaks_out(us_dice) {
	interception_roll(GIBRALTAR, us_dice);
	move_all_pieces(TR_CORSAIRS, GIBRALTAR, TRIPOLI);
	if (can_play_us_signal_books_overboard())
		game.state = 'murad_reis_overboard';
	else
		end_tripolitan_play();
}

states.murad_reis_overboard = {
	prompt(view, current) {
		view.prompt = "Tripolitania: Murad Reis Breaks Out";
		view.prompt += you_may_play(current, US_SIGNAL_BOOKS_OVERBOARD);
		if (is_inactive_player(current))
			return;
		if (game.tr.hand.includes(US_SIGNAL_BOOKS_OVERBOARD))
			gen_action(view, 'card_event', US_SIGNAL_BOOKS_OVERBOARD);
		gen_action(view, 'next');
	},
	card_event(card) {
		play_battle_card(game.tr, card);
		let c = discard_random_card(game.us.hand, game.us.discard);
		log("United States discarded #" + c + ".");
		end_tripolitan_play();
	},
	next() {
		end_tripolitan_play();
	},
}

function can_play_constantinople_sends_aid() {
	return is_derne_captured();
}

function play_constantinople_sends_aid() {
	move_one_piece(TR_FRIGATES, TRIPOLITAN_SUPPLY, TRIPOLI);
	move_one_piece(TR_CORSAIRS, TRIPOLITAN_SUPPLY, TRIPOLI);
	move_one_piece(TR_CORSAIRS, TRIPOLITAN_SUPPLY, TRIPOLI);
	move_one_piece(TR_INFANTRY, TRIPOLITAN_SUPPLY, TRIPOLI);
	move_one_piece(TR_INFANTRY, TRIPOLITAN_SUPPLY, TRIPOLI);
	end_tripolitan_play();
}

function can_play_us_supplies_run_low() {
	for (let space of PATROL_ZONES)
		if (count_american_frigates(space) > 0)
			return true;
	return false;
}

function play_us_supplies_run_low() {
	game.state = 'us_supplies_run_low';
}

states.us_supplies_run_low = {
	prompt(view, current) {
		view.prompt = "Tripolitania: US Supplies Run Low.";
		if (is_inactive_player(current))
			return;
		view.prompt += " Move one American frigate to the harbor of Malta.";
		for (let space of PATROL_ZONES)
			if (count_american_frigates(space) > 0)
				gen_action(view, 'space', space);
	},
	space(space) {
		log("Frigate from " + SPACES[space] + " moved to Malta.");
		move_one_piece(US_FRIGATES, space, MALTA);
		end_tripolitan_play();
	},
}

function can_play_algerine_corsairs_raid() {
	return count_allied_corsairs(ALGIERS) > 0;
}

function can_play_moroccan_corsairs_raid() {
	return count_allied_corsairs(TANGIER) > 0;
}

function can_play_tunisian_corsairs_raid() {
	return count_allied_corsairs(TUNIS) > 0;
}

function play_algerine_corsairs_raid() {
	goto_pirate_raid(ALGIERS);
}

function play_moroccan_corsairs_raid() {
	goto_pirate_raid(TANGIER);
}

function play_tunisian_corsairs_raid() {
	goto_pirate_raid(TUNIS);
}

function can_play_troops_to_derne() {
	return !is_derne_captured();
}

function can_play_troops_to_benghazi() {
	return !is_benghazi_captured();
}

function can_play_troops_to_tripoli() {
	return true;
}

function play_troops_to_derne() {
	move_one_piece(TR_INFANTRY, TRIPOLITAN_SUPPLY, DERNE);
	move_one_piece(TR_INFANTRY, TRIPOLITAN_SUPPLY, DERNE);
	end_tripolitan_play();
}

function play_troops_to_benghazi() {
	move_one_piece(TR_INFANTRY, TRIPOLITAN_SUPPLY, BENGHAZI);
	move_one_piece(TR_INFANTRY, TRIPOLITAN_SUPPLY, BENGHAZI);
	end_tripolitan_play();
}

function play_troops_to_tripoli() {
	move_one_piece(TR_INFANTRY, TRIPOLITAN_SUPPLY, TRIPOLI);
	move_one_piece(TR_INFANTRY, TRIPOLITAN_SUPPLY, TRIPOLI);
	end_tripolitan_play();
}

function can_play_storms() {
	for (let space of PATROL_ZONES)
		if (count_american_frigates(space) > 0)
			return true;
	return false;
}

function play_storms() {
	game.state = 'storms';
}

states.storms = {
	prompt(view, current) {
		view.prompt = "Tripolitania: Storms.";
		if (is_inactive_player(current))
			return;
		view.prompt += " Select a naval patrol zone.";
		for (let space of PATROL_ZONES)
			if (count_american_frigates(space) > 0)
				gen_action(view, 'space', space);
	},
	space(space) {
		let n = roll_many_dice("Storms: ", count_american_frigates(space), 6);
		if (n === 0) {
			log("No effect.");
		}
		if (n > 0) {
			log("One American frigate sank.");
			move_one_piece(US_FRIGATES, space, TRIPOLITAN_SUPPLY);
		}
		if (n > 1) {
			if (n === 2)
				log("One American frigate was damaged.");
			else
				log((n-1) + " American frigates were damaged.");
			for (let i = 1; i < n; ++i) {
				if (game.year === 1806)
					move_one_piece(US_FRIGATES, space, UNITED_STATES_SUPPLY);
				else
					move_one_piece(US_FRIGATES, space, YEAR_TURN_TRACK[game.year+1]);
			}
		}
		if (check_frigate_victory())
			return;
		end_tripolitan_play();
	},
}

function can_play_tripoli_attacks() {
	let n = count_tripolitan_frigates(TRIPOLI) + count_tripolitan_corsairs(TRIPOLI);
	let m = count_american_frigates(TRIPOLI_PATROL_ZONE);
	return n > 0 && m > 0;
}

function play_tripoli_attacks() {
	move_all_pieces(TR_FRIGATES, TRIPOLI, TRIPOLI_PATROL_ZONE);
	move_all_pieces(TR_CORSAIRS, TRIPOLI, TRIPOLI_PATROL_ZONE);
	goto_naval_battle(TRIPOLI_PATROL_ZONE);
}

function can_play_sweden_pays_tribute() {
	return (game.year >= 1803) && (count_swedish_frigates(TRIPOLI_PATROL_ZONE) > 0);
}

function play_sweden_pays_tribute() {
	move_all_pieces(SE_FRIGATES, TRIPOLI_PATROL_ZONE, UNITED_STATES_SUPPLY);
	give_gold(2);
	if (check_gold_victory())
		return;
	end_tripolitan_play();
}

function can_play_tripoli_acquires_corsairs() {
	return count_tripolitan_corsairs(TRIPOLITAN_SUPPLY) > 0;
}

function play_tripoli_acquires_corsairs() {
	move_one_piece(TR_CORSAIRS, TRIPOLITAN_SUPPLY, TRIPOLI);
	move_one_piece(TR_CORSAIRS, TRIPOLITAN_SUPPLY, TRIPOLI);
	end_tripolitan_play();
}

function can_play_the_philadelphia_runs_aground() {
	return count_american_frigates(TRIPOLI_PATROL_ZONE) > 0;
}

function play_the_philadelphia_runs_aground() {
	if (can_play_uncharted_waters())
		game.state = 'the_philadelphia_runs_aground';
	else
		end_the_philadelphia_runs_aground(false);
}

states.the_philadelphia_runs_aground = {
	prompt(view, current) {
		view.prompt = "Tripolitania: The Philadelphia Runs Aground";
		view.prompt += you_may_play(current, UNCHARTED_WATERS);
		if (is_inactive_player(current))
			return;
		if (game.tr.hand.includes(UNCHARTED_WATERS))
			gen_action(view, 'card_event', UNCHARTED_WATERS);
		gen_action(view, 'next');
	},
	card_event(card) {
		play_battle_card(game.tr, card);
		end_the_philadelphia_runs_aground(true);
	},
	next() {
		end_the_philadelphia_runs_aground(false);
	},
}

function end_the_philadelphia_runs_aground(two) {
	let roll = roll_d6();
	if (two) {
		let b = roll_d6();
		log("Tripolitania rolled " + roll + ", " + b + ".");
		if (b > roll)
			roll = b;
	} else {
		log("Tripolitania rolled " + roll + ".");
	}
	switch (roll) {
	case 1: case 2:
		log("Minor damage. One frigate moved to Malta.");
		move_one_piece(US_FRIGATES, TRIPOLI_PATROL_ZONE, MALTA);
		break;
	case 3: case 4:
		log("Frigate sunk.");
		move_one_piece(US_FRIGATES, TRIPOLI_PATROL_ZONE, TRIPOLITAN_SUPPLY);
		break;
	case 5: case 6:
		log("Frigate captured.");
		move_one_piece(US_FRIGATES, TRIPOLI_PATROL_ZONE, TRIPOLITAN_SUPPLY);
		move_one_piece(TR_FRIGATES, TRIPOLITAN_SUPPLY, TRIPOLI);
		break;
	}
	if (check_frigate_victory())
		return;
	end_tripolitan_play();
}

function can_play_algiers_declares_war() {
	return true;
}

function can_play_morocco_declares_war() {
	return true;
}

function can_play_tunis_declares_war() {
	return true;
}

function play_algiers_declares_war() {
	play_ally_declares_war(ALGIERS);
}

function play_morocco_declares_war() {
	play_ally_declares_war(TANGIER);
}

function play_tunis_declares_war() {
	play_ally_declares_war(TUNIS);
}

function play_ally_declares_war(harbor) {
	move_one_piece(AL_CORSAIRS, TRIPOLITAN_SUPPLY, harbor);
	move_one_piece(AL_CORSAIRS, TRIPOLITAN_SUPPLY, harbor);
	move_one_piece(AL_CORSAIRS, TRIPOLITAN_SUPPLY, harbor);
	if (count_american_frigates(harbor) > 0)
		goto_naval_battle(harbor)
	else
		end_tripolitan_play();
}

// UNITED STATES EVENTS

function can_play_american_event(card) {
	switch (card) {
	case THOMAS_JEFFERSON: return can_play_thomas_jefferson();
	case SWEDISH_FRIGATES_ARRIVE: return can_play_swedish_frigates_arrive();
	case HAMETS_ARMY_CREATED: return can_play_hamets_army_created();
	case TREATY_OF_PEACE_AND_AMITY: return can_play_treaty_of_peace_and_amity();
	case ASSAULT_ON_TRIPOLI: return can_play_assault_on_tripoli();
	case NAVAL_MOVEMENT_1: return can_play_naval_movement();
	case NAVAL_MOVEMENT_2: return can_play_naval_movement();
	case NAVAL_MOVEMENT_3: return can_play_naval_movement();
	case NAVAL_MOVEMENT_4: return can_play_naval_movement();
	case EARLY_DEPLOYMENT: return can_play_early_deployment();
	case A_SHOW_OF_FORCE: return can_play_a_show_of_force();
	case TRIBUTE_PAID: return can_play_tribute_paid();
	case CONSTANTINOPLE_DEMANDS_TRIBUTE: return can_play_constantinople_demands_tribute();
	case HAMET_RECRUITS_BEDOUINS: return can_play_hamet_recruits_bedouins();
	case BAINBRIDGE_SUPPLIES_INTEL: return can_play_bainbridge_supplies_intel();
	case CONGRESS_AUTHORIZES_ACTION: return can_play_congress_authorizes_action();
	case CORSAIRS_CONFISCATED: return can_play_corsairs_confiscated();
	case BURN_THE_PHILADELPHIA: return can_play_burn_the_philadelphia();
	case LAUNCH_THE_INTREPID: return can_play_launch_the_intrepid();
	case GENERAL_EATON_ATTACKS_DERNE: return can_play_general_eaton_attacks_derne();
	case GENERAL_EATON_ATTACKS_BENGHAZI: return can_play_general_eaton_attacks_benghazi();
	}
	return false;
}

function play_american_event(card) {
	play_card(game.us, card);
	switch (card) {
	case THOMAS_JEFFERSON: return play_thomas_jefferson();
	case SWEDISH_FRIGATES_ARRIVE: return play_swedish_frigates_arrive();
	case HAMETS_ARMY_CREATED: return play_hamets_army_created();
	case TREATY_OF_PEACE_AND_AMITY: return play_treaty_of_peace_and_amity();
	case ASSAULT_ON_TRIPOLI: return play_assault_on_tripoli();
	case NAVAL_MOVEMENT_1: return play_naval_movement();
	case NAVAL_MOVEMENT_2: return play_naval_movement();
	case NAVAL_MOVEMENT_3: return play_naval_movement();
	case NAVAL_MOVEMENT_4: return play_naval_movement();
	case EARLY_DEPLOYMENT: return play_early_deployment();
	case A_SHOW_OF_FORCE: return play_a_show_of_force();
	case TRIBUTE_PAID: return play_tribute_paid();
	case CONSTANTINOPLE_DEMANDS_TRIBUTE: return play_constantinople_demands_tribute();
	case HAMET_RECRUITS_BEDOUINS: return play_hamet_recruits_bedouins();
	case BAINBRIDGE_SUPPLIES_INTEL: return play_bainbridge_supplies_intel();
	case CONGRESS_AUTHORIZES_ACTION: return play_congress_authorizes_action();
	case CORSAIRS_CONFISCATED: return play_corsairs_confiscated();
	case BURN_THE_PHILADELPHIA: return play_burn_the_philadelphia();
	case LAUNCH_THE_INTREPID: return play_launch_the_intrepid();
	case GENERAL_EATON_ATTACKS_DERNE: return play_general_eaton_attacks_derne();
	case GENERAL_EATON_ATTACKS_BENGHAZI: return play_general_eaton_attacks_benghazi();
	}
	throw Error(card + " is not an American event card.");
}

function can_play_thomas_jefferson() {
	return true;
}

function play_thomas_jefferson() {
	goto_move_up_to_n_american_frigates(8);
}

function can_play_swedish_frigates_arrive() {
	return true;
}

function play_swedish_frigates_arrive() {
	move_all_pieces(SE_FRIGATES, UNITED_STATES_SUPPLY, TRIPOLI_PATROL_ZONE);
	end_american_play();
}

function can_play_hamets_army_created() {
	return (count_american_frigates(ALEXANDRIA) > 0) && (game.year >= 1804);
}

function play_hamets_army_created() {
	move_one_piece(US_MARINES, UNITED_STATES_SUPPLY, ALEXANDRIA);
	move_one_piece(AR_INFANTRY, UNITED_STATES_SUPPLY, ALEXANDRIA);
	move_one_piece(AR_INFANTRY, UNITED_STATES_SUPPLY, ALEXANDRIA);
	move_one_piece(AR_INFANTRY, UNITED_STATES_SUPPLY, ALEXANDRIA);
	move_one_piece(AR_INFANTRY, UNITED_STATES_SUPPLY, ALEXANDRIA);
	move_one_piece(AR_INFANTRY, UNITED_STATES_SUPPLY, ALEXANDRIA);
	end_american_play();
}

function can_play_treaty_of_peace_and_amity() {
	return is_fall_of_1805_or_later() &&
		(count_allied_corsairs(ALGIERS) === 0) &&
		(count_allied_corsairs(TANGIER) === 0) &&
		(count_allied_corsairs(TUNIS) === 0) &&
		(is_derne_captured()) &&
		(count_tripolitan_frigates(TRIPOLI) === 0);
}

function play_treaty_of_peace_and_amity() {
	goto_game_over(US, "Treaty of Peace and Amity.");
}

function can_play_assault_on_tripoli() {
	return is_fall_of_1805_or_later()
	// && (hamets_army_location() === BENGHAZI || game.us.hand.includes(SEND_IN_THE_MARINES));
}

function play_assault_on_tripoli() {
	move_all_pieces(US_GUNBOATS, MALTA, TRIPOLI);
	for (let space of FRIGATE_SPACES)
		if (space !== TRIPOLI)
			move_all_pieces(US_FRIGATES, space, TRIPOLI);
	goto_naval_battle(TRIPOLI);
}

function can_play_naval_movement() {
	return true;
}

function play_naval_movement() {
	goto_move_up_to_n_american_frigates(4);
}

function can_play_early_deployment() {
	if (game.year < 1806)
		return count_american_frigates(YEAR_TURN_TRACK[game.year+1]) > 0;
	return false;
}

function play_early_deployment() {
	game.state = 'early_deployment';
}

states.early_deployment = {
	prompt(view, current) {
		view.prompt = "United States: Early Deployment.";
		if (is_inactive_player(current))
			return;
		for (let space of PATROL_ZONES)
			gen_action(view, 'space', space);
	},
	space(space) {
		log("Frigate placed in " + SPACES[space] + ".");
		move_one_piece(US_FRIGATES, YEAR_TURN_TRACK[game.year+1], space);
		end_american_play();
	},
}

function can_play_a_show_of_force() {
	if (count_available_american_frigates() < 3)
		return false;
	if (count_allied_corsairs(ALGIERS) > 0) return true;
	if (count_allied_corsairs(TANGIER) > 0) return true;
	if (count_allied_corsairs(TUNIS) > 0) return true;
	return false;
}

function play_a_show_of_force() {
	game.state = 'a_show_of_force_where';
	game.summary = [];
}

states.a_show_of_force_where = {
	prompt(view, current) {
		view.prompt = "United States: A Show of Force.";
		if (is_inactive_player(current))
			return;
		view.prompt += " Select an active ally of Tripoli.";
		if (count_allied_corsairs(ALGIERS) > 0)
			gen_action(view, 'space', ALGIERS);
		if (count_allied_corsairs(TANGIER) > 0)
			gen_action(view, 'space', TANGIER);
		if (count_allied_corsairs(TUNIS) > 0)
			gen_action(view, 'space', TUNIS);
	},
	space(space) {
		push_undo();
		game.where = space;
		game.state = 'a_show_of_force_who';
		game.moves = 3 - count_american_frigates(game.where);
	},
}

states.a_show_of_force_who = {
	prompt(view, current) {
		view.prompt = "United States: A Show of Force.";
		if (is_inactive_player(current))
			return;
		view.prompt += " Move frigates to " + SPACES[game.where] + format_moves_left();
		gen_action_undo(view);
		if (count_american_frigates(game.where) >= 3) {
			gen_action(view, 'next');
		} else {
			for (let space of FRIGATE_SPACES)
				if (space !== game.where)
					if (count_american_frigates(space) > 0)
						gen_action(view, 'space', space);
		}
	},
	space(space) {
		push_undo();
		game.summary.push("from " + SPACES[space]);
		move_one_piece(US_FRIGATES, space, game.where);
		--game.moves;
	},
	next() {
		flush_summary("Frigates moved to " + SPACES[game.where] + ":");
		clear_undo();
		move_all_pieces(AL_CORSAIRS, game.where, TRIPOLITAN_SUPPLY);
		end_american_play();
	},
	undo: pop_undo
}

function can_play_tribute_paid() {
	if (count_available_american_frigates() < 1) return false;
	if (count_allied_corsairs(ALGIERS) > 0) return true;
	if (count_allied_corsairs(TANGIER) > 0) return true;
	if (count_allied_corsairs(TUNIS) > 0) return true;
	return false;
}

function play_tribute_paid() {
	game.state = 'tribute_paid_where';
}

states.tribute_paid_where = {
	prompt(view, current) {
		view.prompt = "United States: Tribute Paid.";
		if (is_inactive_player(current))
			return;
		view.prompt += " Select an active ally of Tripoli.";
		if (count_allied_corsairs(ALGIERS) > 0)
			gen_action(view, 'space', ALGIERS);
		if (count_allied_corsairs(TANGIER) > 0)
			gen_action(view, 'space', TANGIER);
		if (count_allied_corsairs(TUNIS) > 0)
			gen_action(view, 'space', TUNIS);
	},
	space(space) {
		push_undo();
		game.where = space;
		game.state = 'tribute_paid_who';
	},
}

states.tribute_paid_who = {
	prompt(view, current) {
		view.prompt = "United States: Tribute Paid.";
		if (is_inactive_player(current))
			return;
		view.prompt += " Move a frigate to " + SPACES[game.where] + ".";
		gen_action_undo(view);
		if (count_american_frigates(game.where) === 1) {
			gen_action(view, 'next');
		} else {
			for (let space of FRIGATE_SPACES)
				if (space !== game.where)
					if (count_american_frigates(space) > 0)
						gen_action(view, 'space', space);
		}
	},
	space(space) {
		push_undo();
		log("Frigate moved to " + SPACES[game.where] + " from " + SPACES[space] + ".");
		move_one_piece(US_FRIGATES, space, game.where);
	},
	next() {
		clear_undo();
		move_all_pieces(AL_CORSAIRS, game.where, TRIPOLITAN_SUPPLY);
		give_gold(2);
		if (check_gold_victory())
			return;
		end_american_play();
	},
	undo: pop_undo
}

function can_play_constantinople_demands_tribute() {
	return game.tr.gold > 0;
}

function play_constantinople_demands_tribute() {
	take_gold(2);
	end_american_play();
}

function can_play_hamet_recruits_bedouins() {
	return is_hamets_army_created();
}

function play_hamet_recruits_bedouins() {
	let space = hamets_army_location();
	move_one_piece(AR_INFANTRY, UNITED_STATES_SUPPLY, space);
	move_one_piece(AR_INFANTRY, UNITED_STATES_SUPPLY, space);
	end_american_play();
}

function can_play_bainbridge_supplies_intel() {
	return game.us.discard.length > 0;
}

function play_bainbridge_supplies_intel() {
	game.state = 'bainbridge_supplies_intel';
}

states.bainbridge_supplies_intel = {
	prompt(view, current) {
		view.prompt = "United States: Bainbridge Supplies Intel.";
		if (is_inactive_player(current))
			return;
		view.prompt += " Select a card from your discard pile.";
		for (let c of game.us.discard) {
			if (c !== BAINBRIDGE_SUPPLIES_INTEL) {
				gen_action(view, 'card_take', c);
				if (can_play_american_event(c))
					gen_action(view, 'card_event', c);
			}
		}
	},
	card_event: play_american_event,
	card_take(card) {
		log("Card placed in hand.");
		remove_from_array(game.us.discard, card);
		game.us.hand.push(card);
		end_american_play();
	},
}

function can_play_congress_authorizes_action() {
	return game.year < 1806;
}

function play_congress_authorizes_action() {
	move_one_piece(US_FRIGATES, UNITED_STATES_SUPPLY, YEAR_TURN_TRACK[game.year+1]);
	move_one_piece(US_FRIGATES, UNITED_STATES_SUPPLY, YEAR_TURN_TRACK[game.year+1]);
	end_american_play();
}

function can_play_corsairs_confiscated() {
	return count_tripolitan_corsairs(GIBRALTAR) > 0;
}

function play_corsairs_confiscated() {
	move_all_pieces(TR_CORSAIRS, GIBRALTAR, TRIPOLITAN_SUPPLY);
	remove_from_array(game.tr.core, MURAD_REIS_BREAKS_OUT);
	end_american_play();
}

function can_play_burn_the_philadelphia() {
	return count_tripolitan_frigates(TRIPOLI) > 0;
}

function play_burn_the_philadelphia() {
	if (can_play_the_daring_stephen_decatur())
		game.state = 'burn_the_philadelphia';
	else
		end_burn_the_philadelphia(false);
}

states.burn_the_philadelphia = {
	prompt(view, current) {
		view.prompt = "United States: Burn the Philadelphia";
		view.prompt += you_may_play(current, THE_DARING_STEPHEN_DECATUR);
		if (is_inactive_player(current))
			return;
		if (game.us.hand.includes(THE_DARING_STEPHEN_DECATUR))
			gen_action(view, 'card_event', THE_DARING_STEPHEN_DECATUR);
		gen_action(view, 'next');
	},
	card_event(card) {
		play_battle_card(game.us, card);
		end_burn_the_philadelphia(true);
	},
	next() {
		end_burn_the_philadelphia(false);
	},
}

function end_burn_the_philadelphia(two) {
	let roll = roll_d6();
	if (two) {
		let b = roll_d6();
		log("Burn the Philadelphia: " + roll + ", " + b + ".");
		if (b > roll)
			roll = b;
	} else {
		log("Burn the Philadelphia: " + roll + ".");
	}
	switch (roll) {
	case 1: case 2:
		log("1-2: The raid failed.");
		break;
	case 3: case 4:
		log("3-4: One Tripolitan frigate damaged.");
		if (game.year === 1806)
			move_one_piece(TR_FRIGATES, TRIPOLI, TRIPOLITAN_SUPPLY);
		else
			move_one_piece(TR_FRIGATES, TRIPOLI, YEAR_TURN_TRACK[game.year + 1]);
		break;
	case 5: case 6:
		log("5-6: One Tripolitan frigate sunk.");
		move_one_piece(TR_FRIGATES, TRIPOLI, TRIPOLITAN_SUPPLY);
		break;
	}
	end_american_play();
}

function can_play_launch_the_intrepid() {
	let n = count_tripolitan_frigates(TRIPOLI) + count_tripolitan_corsairs(TRIPOLI);
	return n > 0;
}

function play_launch_the_intrepid() {
	if (can_play_the_daring_stephen_decatur())
		game.state = 'launch_the_intrepid';
	else
		end_launch_the_intrepid(false);
}

states.launch_the_intrepid = {
	prompt(view, current) {
		view.prompt = "United States: Launch the Intrepid";
		view.prompt += you_may_play(current, THE_DARING_STEPHEN_DECATUR);
		if (is_inactive_player(current))
			return;
		if (game.us.hand.includes(THE_DARING_STEPHEN_DECATUR))
			gen_action(view, 'card_event', THE_DARING_STEPHEN_DECATUR);
		gen_action(view, 'next');
	},
	card_event(card) {
		play_battle_card(game.us, card);
		end_launch_the_intrepid(true);
	},
	next() {
		end_launch_the_intrepid(false);
	},
}

function end_launch_the_intrepid(two) {
	let roll = roll_d6();
	if (two) {
		let b = roll_d6();
		log("Launch the Intrepid: " + roll + ", " + b + ".");
		if (b > roll)
			roll = b;
	} else {
		log("Launch the Intrepid: " + roll + ".");
	}
	switch (roll) {
	case 1: case 2:
		log("1-2: The raid failed.");
		break;
	case 3: case 4:
		log("3-4: One Tripolitan corsair sunk.");
		move_one_piece(TR_CORSAIRS, TRIPOLI, TRIPOLITAN_SUPPLY);
		break;
	case 5: case 6:
		if (count_tripolitan_frigates(TRIPOLI) > 0) {
			log("5-6: One Tripolitan frigate sunk.");
			move_one_piece(TR_FRIGATES, TRIPOLI, TRIPOLITAN_SUPPLY);
		} else {
			log("5-6: Two Tripolitan corsairs sunk.");
			move_one_piece(TR_CORSAIRS, TRIPOLI, TRIPOLITAN_SUPPLY);
			move_one_piece(TR_CORSAIRS, TRIPOLI, TRIPOLITAN_SUPPLY);
		}
		break;
	}
	end_american_play();
}

function can_play_general_eaton_attacks_derne() {
	return hamets_army_location() === ALEXANDRIA;
}

function play_general_eaton_attacks_derne() {
	move_all_pieces(US_MARINES, ALEXANDRIA, DERNE);
	move_all_pieces(AR_INFANTRY, ALEXANDRIA, DERNE);
	move_all_pieces(US_GUNBOATS, MALTA, DERNE);
	game.where = DERNE;
	game.moves = 3;
	game.state = 'land_battle_move_frigates';
}

function can_play_general_eaton_attacks_benghazi() {
	return hamets_army_location() === DERNE;
}

function play_general_eaton_attacks_benghazi() {
	move_all_pieces(US_MARINES, DERNE, BENGHAZI);
	move_all_pieces(AR_INFANTRY, DERNE, BENGHAZI);
	move_all_pieces(US_GUNBOATS, MALTA, BENGHAZI);
	game.where = BENGHAZI;
	game.moves = 3;
	game.state = 'land_battle_move_frigates';
}

// TRIPOLITAN BATTLE EVENTS

function can_play_us_signal_books_overboard() {
	let patrol_zone = PATROL_ZONE_OF_HARBOR[game.where];
	return (count_american_frigates(patrol_zone) > 0) && is_not_removed(US_SIGNAL_BOOKS_OVERBOARD);
}

function can_play_uncharted_waters() {
	return is_not_removed(UNCHARTED_WATERS);
}

function can_play_merchant_ship_converted(merchants) {
	return (game.where === TRIPOLI) &&
		(merchants > 0) &&
		(count_tripolitan_corsairs(TRIPOLITAN_SUPPLY) > 0) &&
		is_not_removed(MERCHANT_SHIP_CONVERTED);
}

function can_play_happy_hunting() {
	return (game.where === TRIPOLI) && (count_tripolitan_corsairs(TRIPOLI) > 0) && is_not_removed(HAPPY_HUNTING);
}

function can_play_the_guns_of_tripoli() {
	return (game.where === TRIPOLI) && is_not_removed(THE_GUNS_OF_TRIPOLI);
}

function can_play_mercenaries_desert() {
	if (count_tripolitan_infantry(game.where) === 0)
		return false; // no opposition left
	return (count_arab_infantry(game.where) > 0) && is_not_removed(MERCENARIES_DESERT);
}

// AMERICAN BATTLE EVENTS

function can_play_lieutenant_sterett_in_pursuit() {
	let patrol_zone = PATROL_ZONE_OF_HARBOR[game.where];
	return (count_american_frigates(patrol_zone) > 0) && is_not_removed(LIEUTENANT_STERETT_IN_PURSUIT);
}

function can_play_prebles_boys_take_aim() {
	return BATTLE_SPACES.includes(game.where) && is_not_removed(PREBLES_BOYS_TAKE_AIM);
}

function can_play_the_daring_stephen_decatur() {
	return is_not_removed(THE_DARING_STEPHEN_DECATUR);
}

function can_play_send_in_the_marines() {
	return game.active_card === ASSAULT_ON_TRIPOLI && is_not_removed(SEND_IN_THE_MARINES);
}

function can_play_lieutenant_obannon_leads_the_charge() {
	if (count_tripolitan_infantry(game.where) === 0)
		return false; // no opposition left
	return (count_american_marines(game.where) > 0) && is_not_removed(LIEUTENANT_OBANNON_LEADS_THE_CHARGE);
}

function can_play_marine_sharpshooters() {
	if (count_tripolitan_infantry(game.where) === 0)
		return false; // no opposition left
	return (count_american_marines(game.where) > 0) && is_not_removed(MARINE_SHARPSHOOTERS);
}

function can_play_american_land_battle_card() {
	return can_play_send_in_the_marines() ||
		can_play_marine_sharpshooters() ||
		can_play_lieutenant_obannon_leads_the_charge();
}

// VICTORY

function check_gold_victory() {
	if (game.tr.gold >= 12)
		return goto_game_over(TR, "Twelve gold.");
	return false;
}

function check_frigate_victory() {
	if (count_american_frigates(TRIPOLITAN_SUPPLY) >= 4)
		return goto_game_over(TR, "Four American frigates sunk.");
	return false;
}

function calculate_tr_score() {
	return Math.min(count_american_frigates(TRIPOLITAN_SUPPLY), 4) * 3 + game.tr.gold;
}

function goto_game_over(result, message) {
	game.where = null;
	game.state = 'game_over';
	game.active = "None";
	game.result = result;
	game.score = calculate_tr_score();
	if (result === TR)
		game.victory = "Tripolitan victory:\n" + message;
	else if (result === US)
		game.victory = "United States victory:\n" + message;
	else
		game.victory = message;
	log_blank();
	log(game.victory);
	return true;
}

states.game_over = {
	prompt(view) {
		return view.prompt = game.victory;
	}
}

// SETUP

exports.setup = function (seed, scenario, options) {
	game = {
		seed: seed,
		state: null,
		year: 1801,
		season: 0,
		log: [],
		location: [],
		damaged: [],
		us: {
			core: [],
			hand: [],
			draw: [],
			discard: [],
		},
		tr: {
			core: [],
			hand: [],
			draw: [],
			discard: [],
			gold: 0,
		},
		where: null,
		undo: [],
	};

	// Old RNG for ancient replays
	if (options.rng)
		game.rng = options.rng

	if (scenario === "Fortress Tripoli")
		game.fortress = 1;

	if (typeof scenario === 'number')
		game.year = scenario;

	game.tr.core.push(YUSUF_QARAMANLI);
	game.tr.core.push(MURAD_REIS_BREAKS_OUT);
	game.tr.core.push(CONSTANTINOPLE_SENDS_AID);

	game.us.core.push(THOMAS_JEFFERSON);
	game.us.core.push(SWEDISH_FRIGATES_ARRIVE);
	game.us.core.push(HAMETS_ARMY_CREATED);

	for (let i = 4; i <= 27; ++i) {
		game.us.draw.push(i);
		game.tr.draw.push(i+27);
	}

	deploy("us_frigate_1", GIBRALTAR);
	deploy("us_frigate_2", GIBRALTAR);
	deploy("us_frigate_3", GIBRALTAR);
	deploy("us_frigate_4", TRACK_1802);
	deploy("us_frigate_5", TRACK_1803);
	deploy("us_frigate_6", TRACK_1804);
	deploy("us_frigate_7", UNITED_STATES_SUPPLY);
	deploy("us_frigate_8", UNITED_STATES_SUPPLY);

	deploy("us_gunboat_1", UNITED_STATES_SUPPLY);
	deploy("us_gunboat_2", UNITED_STATES_SUPPLY);
	deploy("us_gunboat_3", UNITED_STATES_SUPPLY);

	deploy("se_frigate_1", UNITED_STATES_SUPPLY);
	deploy("se_frigate_2", UNITED_STATES_SUPPLY);

	deploy("us_marine_1", UNITED_STATES_SUPPLY);
	deploy("us_marine_2", UNITED_STATES_SUPPLY);
	deploy("us_marine_3", UNITED_STATES_SUPPLY);
	deploy("us_marine_4", UNITED_STATES_SUPPLY);

	for (let i = 1; i <= 10; ++i)
		deploy("ar_infantry_" + i, UNITED_STATES_SUPPLY);

	deploy("tr_frigate_1", TRIPOLITAN_SUPPLY);
	deploy("tr_frigate_2", TRIPOLITAN_SUPPLY);

	deploy("tr_corsair_1", GIBRALTAR);
	deploy("tr_corsair_2", GIBRALTAR);
	deploy("tr_corsair_3", TRIPOLI);
	deploy("tr_corsair_4", TRIPOLI);
	deploy("tr_corsair_5", TRIPOLI);
	deploy("tr_corsair_6", TRIPOLI);
	deploy("tr_corsair_7", TRIPOLITAN_SUPPLY);
	deploy("tr_corsair_8", TRIPOLITAN_SUPPLY);
	deploy("tr_corsair_9", TRIPOLITAN_SUPPLY);

	for (let i = 1; i <= 9; ++i)
		deploy("al_corsair_" + i, TRIPOLITAN_SUPPLY);

	deploy("tr_infantry_1", TRIPOLI);
	deploy("tr_infantry_2", TRIPOLI);
	deploy("tr_infantry_3", TRIPOLI);
	deploy("tr_infantry_4", TRIPOLI);
	deploy("tr_infantry_5", BENGHAZI);
	deploy("tr_infantry_6", BENGHAZI);
	deploy("tr_infantry_7", DERNE);
	deploy("tr_infantry_8", DERNE);
	for (let i = 9; i <= 20; ++i)
		deploy("tr_infantry_" + i, TRIPOLITAN_SUPPLY);

	start_of_year();
	return game;
}

exports.action = function (state, current, action, arg) {
	game = state;
	let S = states[game.state];
	if (action in S)
		S[action](arg, current);
	else
		throw new Error("Invalid action: " + action);
	return game;
}

exports.view = function(state, current) {
	game = state;

	let tr_score = calculate_tr_score();
	let us_score = 24 - tr_score;

	let view = {
		log: game.log,
		year: game.year,
		season: game.season,
		location: game.location,
		damaged: game.damaged,
		active: game.active,
		prompt: null,
		actions: null,
		tr: {
			core: game.tr.core,
			draw: game.tr.draw.length,
			discard: game.tr.discard.length + (game.tr.queue ? game.tr.queue.length : 0),
			hand: game.tr.hand.length,
			gold: game.tr.gold,
			score: tr_score,
		},
		us: {
			core: game.us.core,
			draw: game.us.draw.length,
			discard: game.us.discard.length + (game.us.queue ? game.us.queue.length : 0),
			hand: game.us.hand.length,
			score: us_score,
		},
		card: game.active_card,
		where: game.where,
	};

	states[game.state].prompt(view, current);

	if (current === US && game.state === 'bainbridge_supplies_intel') {
		view.hand = game.us.discard;
	} else if (current === US) {
		view.hand = game.us.hand;
	} else if (current === TR) {
		view.hand = game.tr.hand;
	} else {
		view.hand = [];
	}
	view.core = game.us.core.concat(game.tr.core);

	return view;
}