summaryrefslogtreecommitdiff
path: root/rules.js
blob: 55cd22138f9f1750578c7ec3912143b3901b4115 (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
"use strict"

const COMMUNE = "Commune";
const VERSAILLES = "Versailles";

var game, view, states = {}

exports.scenarios = [ "Standard" ]
exports.roles = [ COMMUNE, VERSAILLES ]

const first_commune_cube = 0
const last_commune_cube = 17
const first_versailles_cube = 18
const last_versailles_cube = 35

const first_commune_disc = 36
const last_commune_disc = 37
const first_versailles_disc = 38
const last_versailles_disc = 39

const card_names = [
	"Initiative",
	"Jules Ducatel",
	"The Murder of Vincenzini",
	"Brassardiers",
	"Jules Ferry",
	"Le Figaro",
	"Général Louis Valentin",
	"Général Espivent",
	"Les Amis de l'Ordre",
	"Socialist Newspaper Ban",
	"Fortification of Mont-Valérien",
	"Adolphe Thiers",
	"Otto von Bismarck",
	"Général Ernest de Cissey",
	"Colonel de Lochner",
	"Jules Favre",
	"Hostage Decree",
	"Maréchal Macmahon",
	"Paule Minck",
	"Walery Wroblewski",
	"Banque de France",
	"Le Réveil",
	"Execution of Generals",
	"Les Cantinières",
	"Eugène Protot",
	"Paul Cluseret",
	"Gaston Crémieux",
	"Luise Michel",
	"Jaroslav Dombrowski",
	"Raoul Rigault",
	"Karl Marx",
	"Blanquists",
	"Général Lullier",
	"Jules Vallès",
	"Charles Delescluze",
	"Conciliation",
	"Georges Clemenceau",
	"Archbishop Georges Darboy",
	"Victor Hugo",
	"Léon Gambetta",
	"Elihu Washburne",
	"Freemason Parade",
	"Paris Cannons",
	"Aux Barricades!",
	"Commune's Stronghold",
	"Fighting in Issy Village",
	"Battle of Mont-Valérien",
	"Raid on Château de Vincennes",
	"Revolution in the Press",
	"Pius IX",
	"Socialist International",
	"Royalists Dissension",
	"Rise of Republicanism",
	"Legitimacy",
]

const card_ops = [
	0,
	// Commune
	1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 4,
	// Versailles
	1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 4,
	// Neutral
	3, 3, 3, 3, 3, 3, 3,
	// Objective
	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
]

const space_names = [
	"National Assembly",
	"Royalists",
	"Republicans",
	"Press",
	"Catholic Church",
	"Social Movements",
	"Mont-Valérien",
	"Fort D'Issy",
	"Château de Vincennes",
	"Butte Montmartre",
	"Butte-Aux-Cailles",
	"Père Lachaise",
	"Prussian Occupied Territory",
	"Versailles HQ",
	"Red Cube Pool 1",
	"Red Cube Pool 2",
	"Red Cube Pool 3",
	"Red Crisis Track Start",
	"Red Crisis Track Escalation",
	"Red Crisis Track Tension",
	"Red Crisis Track Final Crisis",
	"Red Bonus Cubes 1",
	"Red Bonus Cubes 2",
	"Red Bonus Cubes 3",
	"Blue Cube Pool",
	"Blue Crisis Track Start",
	"Blue Crisis Track Escalation",
	"Blue Crisis Track Tension",
	"Blue Crisis Track Final Crisis",
	"Blue Bonus Cubes 1",
	"Blue Bonus Cubes 2",
	"Blue Bonus Cubes 3",
	"Prussian Collaboration 1",
	"Prussian Collaboration 2",
	"Prussian Collaboration 3",
]

const RED_CUBE_POOL = [14, 15, 16]
const RED_CRISIS_TRACK = [17, 18, 19, 20]
const RED_BONUS_CUBES = [21, 22, 23]
const BLUE_CUBE_POOL = 24
const BLUE_CRISIS_TRACK = [25, 26, 27, 28]
const BLUE_BONUS_CUBES = [29, 30, 31]
const PRUSSIAN_COLLABORATION = [32, 33, 34]

const S_NATIONAL_ASSEMBLY = 0
const S_ROYALISTS = 1
const S_REPUBLICANS = 2

const S_PRESS = 3
const S_CATHOLIC_CHURCH = 4
const S_SOCIAL_MOVEMENTS = 5

const S_MONT_VALERIEN = 6
const S_FORT_D_ISSY = 7
const S_CHATEAU_DE_VINCENNES = 8

const S_BUTTE_MONTMARTRE = 9
const S_BUTTE_AUX_CAILLES = 10
const S_PERE_LACHAISE = 11

const S_PRUSSIAN_OCCUPIED_TERRITORY = 12
const S_VERSAILLES_HQ = 13

const first_space = S_NATIONAL_ASSEMBLY
const last_space = S_PERE_LACHAISE
const space_count = last_space + 1

const POLITICAL = [
	S_NATIONAL_ASSEMBLY,
	S_ROYALISTS,
	S_REPUBLICANS,
	S_PRESS,
	S_CATHOLIC_CHURCH,
	S_SOCIAL_MOVEMENTS,
]

const MILITARY = [
	S_MONT_VALERIEN,
	S_FORT_D_ISSY,
	S_CHATEAU_DE_VINCENNES,
	S_BUTTE_MONTMARTRE,
	S_BUTTE_AUX_CAILLES,
	S_PERE_LACHAISE,
]

function is_political_space(s) {
	return (
		s === S_NATIONAL_ASSEMBLY ||
		s === S_ROYALISTS ||
		s === S_REPUBLICANS ||
		s === S_PRESS ||
		s === S_CATHOLIC_CHURCH ||
		s === S_SOCIAL_MOVEMENTS
	)
}

function is_military_space(s) {
	return (
		s === S_MONT_VALERIEN ||
		s === S_FORT_D_ISSY ||
		s === S_CHATEAU_DE_VINCENNES ||
		s === S_BUTTE_MONTMARTRE ||
		s === S_BUTTE_AUX_CAILLES ||
		s === S_PERE_LACHAISE
	)
}

const DIM_INSTITUTIONAL = [ S_NATIONAL_ASSEMBLY, S_ROYALISTS, S_REPUBLICANS ]
const DIM_PUBLIC_OPINION = [ S_PRESS, S_CATHOLIC_CHURCH, S_SOCIAL_MOVEMENTS ]

const DIM_FORTS = [ S_MONT_VALERIEN, S_FORT_D_ISSY, S_CHATEAU_DE_VINCENNES ]
const DIM_PARIS = [ S_BUTTE_MONTMARTRE, S_BUTTE_AUX_CAILLES, S_PERE_LACHAISE ]

const ADJACENT_TO = [
	[ S_ROYALISTS, S_REPUBLICANS ],
	[ S_PRESS, S_CATHOLIC_CHURCH ],
	[ S_PRESS, S_SOCIAL_MOVEMENTS ],
	[ S_ROYALISTS, S_REPUBLICANS, S_CATHOLIC_CHURCH, S_SOCIAL_MOVEMENTS ],
	[ S_ROYALISTS, S_PRESS ],
	[ S_REPUBLICANS, S_PRESS ],
	[ S_BUTTE_MONTMARTRE, S_VERSAILLES_HQ ],
	[ S_CHATEAU_DE_VINCENNES, S_BUTTE_AUX_CAILLES, S_VERSAILLES_HQ ],
	[ S_FORT_D_ISSY, S_PERE_LACHAISE, S_PRUSSIAN_OCCUPIED_TERRITORY ],
	[ S_MONT_VALERIEN, S_BUTTE_AUX_CAILLES, S_PERE_LACHAISE ],
	[ S_FORT_D_ISSY, S_BUTTE_MONTMARTRE, S_PERE_LACHAISE ],
	[ S_CHATEAU_DE_VINCENNES, S_BUTTE_MONTMARTRE, S_BUTTE_AUX_CAILLES, S_PRUSSIAN_OCCUPIED_TERRITORY ],
	[ S_CHATEAU_DE_VINCENNES, S_PERE_LACHAISE ],
	[ S_MONT_VALERIEN, S_FORT_D_ISSY ],
]

const ADJACENT_FROM = [
	[ ],
	[ S_NATIONAL_ASSEMBLY, S_PRESS, S_CATHOLIC_CHURCH ],
	[ S_NATIONAL_ASSEMBLY, S_PRESS, S_SOCIAL_MOVEMENTS ],
	[ S_ROYALISTS, S_REPUBLICANS, S_CATHOLIC_CHURCH, S_SOCIAL_MOVEMENTS ],
	[ S_ROYALISTS, S_PRESS ],
	[ S_REPUBLICANS, S_PRESS ],
	[ S_BUTTE_MONTMARTRE, S_VERSAILLES_HQ ],
	[ S_CHATEAU_DE_VINCENNES, S_BUTTE_AUX_CAILLES, S_VERSAILLES_HQ ],
	[ S_FORT_D_ISSY, S_PERE_LACHAISE, S_PRUSSIAN_OCCUPIED_TERRITORY ],
	[ S_MONT_VALERIEN, S_BUTTE_AUX_CAILLES, S_PERE_LACHAISE ],
	[ S_FORT_D_ISSY, S_BUTTE_MONTMARTRE, S_PERE_LACHAISE ],
	[ S_CHATEAU_DE_VINCENNES, S_BUTTE_MONTMARTRE, S_BUTTE_AUX_CAILLES, S_PRUSSIAN_OCCUPIED_TERRITORY ],
	[ S_CHATEAU_DE_VINCENNES, S_PERE_LACHAISE ],
	[ S_MONT_VALERIEN, S_FORT_D_ISSY ],
]

// === GAME STATE ===

function is_objective_card(c) {
	return c >= 42 && c <= 53
}

function is_strategy_card(c) {
	return !is_objective_card(c) && c !== 17 && c !== 34
}

function is_commune_card(c) {
	return c >= 18 && c <= 34
}

function is_versailles_card(c) {
	return c >= 1 && c <= 17
}

function is_neutral_card(c) {
	return c >= 35 && c <= 41
}

function enemy_player() {
	if (game.active === COMMUNE)
		return VERSAILLES
	return COMMUNE
}

function player_hand(current) {
	if (current === COMMUNE)
		return game.red_hand
	return game.blue_hand
}

function is_space(s) {
	return s >= first_space && s <= last_space
}

function can_advance_momentum() {
	if (game.active === COMMUNE)
		return game.red_momentum < 3
	return game.blue_momentum < 3
}

function can_play_event(c) {
	if (game.active === COMMUNE)
		return is_commune_card(c) || is_neutral_card(c)
	return is_versailles_card(c) || is_neutral_card(c)
}

var c_count = new Array(space_count).fill(0)
var v_count = new Array(space_count).fill(0)

function update_presence_and_control() {
	c_count.fill(0)
	v_count.fill(0)

	for (let p = first_commune_cube; p <= last_commune_cube; ++p) {
		let s = game.pieces[p]
		if (is_space(s))
			c_count[s] += 1
	}

	for (let p = first_versailles_cube; p <= last_versailles_cube; ++p) {
		let s = game.pieces[p]
		if (is_space(s))
			v_count[s] += 1
	}

	for (let p = first_commune_disc; p <= last_commune_disc; ++p) {
		let s = game.pieces[p]
		if (is_space(s))
			c_count[s] += 1
	}

	for (let p = first_versailles_disc; p <= last_versailles_disc; ++p) {
		let s = game.pieces[p]
		if (is_space(s))
			v_count[s] += 1
	}

	game.presence = 0
	game.control = 0

	// Permanent Presence
	game.presence |= (1 << (S_PERE_LACHAISE))
	game.presence |= (1 << (S_SOCIAL_MOVEMENTS))
	game.presence |= (1 << (S_ROYALISTS + space_count))

	for (let s = first_space; s <= last_space; ++s) {
		let c_bit = (1 << (s))
		let v_bit = (1 << (s + space_count))
		if (c_count[s] > 0)
			game.presence |= c_bit
		if (v_count[s] > 0)
			game.presence |= v_bit
		if (c_count[s] > v_count[s])
			game.control |= c_bit
		if (v_count[s] > c_count[s])
			game.control |= v_bit
	}

}

function is_present(side, s) {
	if (side === COMMUNE)
		return game.presence & (1 << (s))
	return game.presence & (1 << (s + space_count))
}

function is_commune_control(s) {
	if (s === S_VERSAILLES_HQ)
		return false
	if (s === S_PRUSSIAN_OCCUPIED_TERRITORY)
		return false
	return game.control & (1 << (s))
}

function is_versailles_control(s) {
	if (s === S_VERSAILLES_HQ)
		return true
	if (s === S_PRUSSIAN_OCCUPIED_TERRITORY)
		return game.blue_momentum === 3
	return game.control & (1 << (s + space_count))
}

function is_control(side, s) {
	if (side === COMMUNE)
		return is_commune_control(s)
	return is_versailles_control(s)
}

function is_adjacent_to_control(side, here) {
	for (let s of ADJACENT_TO[here])
		if (is_control(side, s))
			return true
	return false
}

function is_control_dimension(side, dim) {
	for (let s of dim)
		if (!is_control(side, s))
			return false
	return true
}

function count_commune_cubes(s) {
	let n = 0
	for (let p = first_commune_cube; p <= last_commune_cube; ++p)
		if (game.pieces[p] === s)
			++n
	return n
}

function count_versailles_cubes(s) {
	let n = 0
	for (let p = first_versailles_cube; p <= last_versailles_cube; ++p)
		if (game.pieces[p] === s)
			++n
	return n
}

function count_commune_discs(s) {
	let n = 0
	for (let p = first_commune_disc; p <= last_commune_disc; ++p)
		if (game.pieces[p] === s)
			++n
	return n
}

function count_versailles_discs(s) {
	let n = 0
	for (let p = first_versailles_disc; p <= last_versailles_disc; ++p)
		if (game.pieces[p] === s)
			++n
	return n
}

function count_commune_pieces(s) {
	return count_commune_cubes(s) + count_commune_discs(s)
}

function count_versailles_pieces(s) {
	return count_versailles_cubes(s) + count_versailles_discs(s)
}

function count_enemy_pieces(s) {
	if (game.active === COMMUNE)
		return count_versailles_pieces(s)
	return count_commune_pieces(s)
}

function find_commune_cube(s) {
	for (let p = first_commune_cube; p <= last_commune_cube; ++p)
		if (game.pieces[p] === s)
			return p
	return -1
}

function find_versailles_cube(s) {
	for (let p = first_versailles_cube; p <= last_versailles_cube; ++p)
		if (game.pieces[p] === s)
			return p
	return -1
}

function find_commune_disc(s) {
	for (let p = first_commune_disc; p <= last_commune_disc; ++p)
		if (game.pieces[p] === s)
			return p
	return -1
}

function find_versailles_disc(s) {
	for (let p = first_versailles_disc; p <= last_versailles_disc; ++p)
		if (game.pieces[p] === s)
			return p
	return -1
}

function find_enemy_cube(s) {
	if (game.active === COMMUNE)
		return find_versailles_cube(s)
	return find_commune_cube(s)
}

function find_enemy_disc(s) {
	if (game.active === COMMUNE)
		return find_versailles_disc(s)
	return find_commune_disc(s)
}

function find_friendly_cube(s) {
	if (game.active === COMMUNE)
		return find_commune_cube(s)
	return find_versailles_cube(s)
}

function find_friendly_disc(s) {
	if (game.active === COMMUNE)
		return find_commune_disc(s)
	return find_versailles_disc(s)
}

function has_enemy_cube(s) {
	return find_enemy_cube(s) >= 0
}

function has_enemy_disc(s) {
	return find_enemy_disc(s) >= 0
}

function has_enemy_piece(s) {
	return has_enemy_cube(s) || has_enemy_disc(s)
}

function is_commune_cube(p) {
	return p >= first_commune_cube && p <= last_commune_cube
}

function is_versailles_cube(p) {
	return p >= first_versailles_cube && p <= last_versailles_cube
}

function is_disc(p) {
	return p >= 36
}

function remove_piece(p) {
	if (is_commune_cube(p)) {
		game.pieces[p] = RED_CUBE_POOL[0] // TODO...
	} else if (is_versailles_cube(p)) {
		game.pieces[p] = BLUE_CUBE_POOL
	} else {
		game.pieces[p] = -1
	}
}

function place_piece(p, s) {
	game.pieces[p] = s
}

function find_available_cube() {
	let p = -1
	if (game.active === COMMUNE) {
		for (let i = 0; i < 3; ++i) {
			p = find_commune_cube(RED_CUBE_POOL[i])
			if (p >= 0)
				return p
		}
		for (let i = 0; i < 4; ++i) {
			p = find_commune_cube(RED_CRISIS_TRACK[i])
			if (p >= 0)
				return p
		}
	} else {
		p = find_versailles_cube(BLUE_CUBE_POOL)
		if (p >= 0)
			return p
		for (let i = 0; i < 4; ++i) {
			p = find_versailles_cube(BLUE_CRISIS_TRACK[i])
			if (p >= 0)
				return p
		}
	}
}

function for_each_enemy_cube(s, f) {
	if (game.active === COMMUNE)
		for_each_versailles_cube(s, f)
	else
		for_each_commune_cube(s, f)
}

function for_each_friendly_cube(s, f) {
	if (game.active === COMMUNE)
		for_each_commune_cube(s, f)
	else
		for_each_versailles_cube(s, f)
}

function for_each_enemy_disc(s, f) {
	if (game.active === COMMUNE)
		for_each_versailles_disc(s, f)
	else
		for_each_commune_disc(s, f)
}

function for_each_friendly_disc(s, f) {
	if (game.active === COMMUNE)
		for_each_commune_disc(s, f)
	else
		for_each_versailles_disc(s, f)
}

function for_each_commune_cube(s, f) {
	for (let p = first_commune_cube; p <= last_commune_cube; ++p)
		if (game.pieces[p] === s)
			f(p)
}

function for_each_versailles_cube(s, f) {
	for (let p = first_versailles_cube; p <= last_versailles_cube; ++p)
		if (game.pieces[p] === s)
			f(p)
}

function for_each_commune_disc(s, f) {
	for (let p = first_commune_disc; p <= last_commune_disc; ++p)
		if (game.pieces[p] === s)
			f(p)
}

function for_each_versailles_disc(s, f) {
	for (let p = first_versailles_disc; p <= last_versailles_disc; ++p)
		if (game.pieces[p] === s)
			f(p)
}

// === OBJECTIVE PHASE ===

states.choose_objective_card = {
	inactive: "choose an objective card",
	prompt(current) {
		view.prompt = "Choose an Objective card."
		for (let c of player_hand(current))
			if (is_objective_card(c))
				gen_action_card(c)
	},
	card(c, current) {
		if (current === COMMUNE) {
			game.red_objective = c
			game.red_hand = game.red_hand.filter(c => !is_objective_card(c))
		} else {
			game.blue_objective = c
			game.blue_hand = game.blue_hand.filter(c => !is_objective_card(c))
		}
		if (game.red_objective > 0 && game.blue_objective > 0)
			goto_initiative_phase()
		else if (game.red_objective > 0)
			game.active = VERSAILLES
		else if (game.blue_objective > 0)
			game.active = COMMUNE
		else
			game.active = "Both"
	},
}

// === INITIATIVE PHASE ===

function commune_political_vp() {
	return game.political_vp
}

function versailles_political_vp() {
	return -game.political_vp
}

function goto_initiative_phase() {
	let c_level = commune_political_vp() - game.red_momentum
	let v_level = versailles_political_vp() - game.blue_momentum
	if (c_level >= v_level)
		game.active = game.initiative = COMMUNE
	else
		game.active = game.initiative = VERSAILLES
	game.state = "initiative_phase"
}

states.initiative_phase = {
	inactive: "decide player order",
	prompt() {
		view.prompt = "Decide player order."
		view.actions.commune = 1
		view.actions.versailles = 1
	},
	commune() {
		log("Initiative: Commune")
		game.initiative = COMMUNE
		game.active = game.initiative
		goto_strategy_phase()
	},
	versailles() {
		log("Initiative: Versailles")
		game.initiative = VERSAILLES
		game.active = game.initiative
		goto_strategy_phase()
	},
}

// === STRATEGY PHASE ===

function goto_strategy_phase() {
	clear_undo()
	log_h2(game.active)
	game.state = "strategy_phase"
}

function resume_strategy_phase() {
	game.active = enemy_player()
	goto_strategy_phase()
}

states.strategy_phase = {
	inactive: "play a card",
	prompt() {
		view.prompt = "Play a card."
		let hand = player_hand(game.active)
		let n_strategy = 0
		for (let c of hand)
			if (is_strategy_card(c))
				n_strategy += 1
		for (let c of hand) {
			if (is_strategy_card(c)) {
				if (can_play_event(c))
					gen_action("card_event", c)
				gen_action("card_ops_political", c)
				gen_action("card_ops_military", c)
				if (game.discard > 0 && can_play_event(game.discard))
					gen_action("card_use_discarded", c)
				if (can_advance_momentum())
					gen_action("card_advance_momentum", c)
			}
			if (c === 17 || c === 34) {
				if (n_strategy > 0) {
					gen_action("card_ops_political", c)
					gen_action("card_ops_military", c)
				}
			}
		}
	},
	card_event(c) {
		push_undo()
		log(`Played #${c} for event.`)
		array_remove_item(player_hand(game.active), c)
		game.discard = c
		goto_play_event()
	},
	card_ops_political(c) {
		push_undo()
		if (c === 17 || c === 34)
			return goto_final_crisis_discard(c, POLITICAL)
		log(`Played #${c} for ${card_ops[c]} Political ops.`)
		array_remove_item(player_hand(game.active), c)
		game.discard = c
		goto_operations(card_ops[c], POLITICAL)
	},
	card_ops_military(c) {
		push_undo()
		if (c === 17 || c === 34)
			return goto_final_crisis_discard(c, MILITARY)
		log(`Played #${c} for ${card_ops[c]} Military ops.`)
		array_remove_item(player_hand(game.active), c)
		game.discard = c
		goto_operations(card_ops[c], MILITARY)
	},
	card_advance_momentum(c) {
		push_undo()
		log(`Played #${c} to advance momentum.`)
		array_remove_item(player_hand(game.active), c)
		game.discard = c
		if (game.active === COMMUNE)
			game.red_momentum += 1
		else
			game.blue_momentum += 1
		// TODO: momentum trigger
		resume_strategy_phase()
	},
	card_use_discarded(c) {
		push_undo()
		log(`Discarded #${c} to play #${game.discard}.`)
		let old_c = game.discard
		array_remove_item(player_hand(game.active), c)
		game.discard = c
		goto_play_event(old_c)
	},
}

// === OPERATIONS ===

function goto_operations(count, spaces) {
	game.count = count
	game.spaces = spaces
	goto_operations_remove()
}

function goto_final_crisis_discard(c, spaces) {
	game.state = "discard_final_crisis"
	game.count = 4
	game.spaces = spaces
	array_remove_item(player_hand(game.active), c)
}

states.discard_final_crisis = {
	inactive: "discard a card to play final crisis",
	prompt() {
		view.prompt = "Discard a card to play Final Crisis card for ops."
		let hand = player_hand(game.active)
		for (let c of hand)
			if (is_strategy_card(c))
				gen_action("card", c)
	},
	card(c) {
		push_undo()
		log(`Discarded #${c} to play Final Crisis card for ops.`)
		array_remove_item(player_hand(game.active), c)
		game.discard = c
		goto_operations_remove()
	},
}

// OPERATIONS: REMOVE

function goto_operations_remove() {
	update_presence_and_control()
	if (can_operations_remove())
		game.state = "operations_remove"
	else
		goto_operations_place()
}

function can_operations_remove() {
	for (let s of game.spaces)
		if (can_operations_remove_space(s))
			return true
	return false
}

function can_operations_remove_space(s) {
	if (is_present(game.active, s) || is_adjacent_to_control(game.active, s)) {
		let c = has_enemy_cube(s)
		let d = has_enemy_disc(s)
		if (c || d) {
			if (is_political_space(s))
				return true
			if (is_military_space(s))
				if (!d || game.count >= 2)
					return true
		}
	}
	return false
}

function military_strength(s) {
	let str = 0
	for (let next of ADJACENT_FROM[s])
		if (is_control(game.active, next))
			str += 1
	if (is_present(game.active, s))
		str += 1
	if (is_control(game.active, s))
		str += 1
	return str
}

states.operations_remove = {
	prompt() {
		view.prompt = "Operations: Remove opponent's pieces."
		for (let s of game.spaces) {
			if (can_operations_remove_space(s)) {
				if (has_enemy_cube(s))
					for_each_enemy_cube(s, gen_action_piece)
				else
					for_each_enemy_disc(s, gen_action_piece)
			}
		}
		view.actions.end_remove = 1
	},
	piece(p) {
		push_undo()
		let s = game.pieces[p]

		if (has_enemy_disc(s))
			game.count -= 2
		else
			game.count -= 1

		if (is_military_space(s)) {
			let str = military_strength(s)
			if (str >= 3) {
				log("Military strength " + str + ".")
				remove_piece(p)
			} else if (game.count >= 1) {
				log("Military strength " + str + ".")
				game.who = p
				game.state = "operations_remove_spend"
			} else {
				log("Military strength " + str + ".")
				game.who = p
				game.state = "operations_remove_draw"
			}
		} else {
			remove_piece(p)
		}

		resume_operations_remove()
	},
	end_remove() {
		push_undo()
		goto_operations_place()
	},
}

states.operations_remove_spend = {
	prompt() {
		view.prompt = "Operations: Spend extra Operations Point before drawing?"
		view.actions.spend = 1
		view.actions.draw = 1
	},
	spend() {
		log("Spent 1 ops.")
		game.count -= 1
		attempt_remove_piece(1)
	},
	draw() {
		attempt_remove_piece(0)
	},
}

states.operations_remove_draw = {
	prompt() {
		view.prompt = "Operations: Draw card for Military removal."
		view.actions.draw = 1
	},
	draw() {
		attempt_remove_piece(0)
	},
}

function attempt_remove_piece(extra) {
	clear_undo()
	let p = game.who
	let s = game.pieces[p]
	let c = game.strategy_deck.pop()
	let str = military_strength(s) + extra
	let ops = card_ops[c]
	log("Military strength " + str + ".")
	log("Removed card #" + c + " for " + ops + " strength.")
	if (str >= ops)
		remove_piece(p)
	game.who = -1
	resume_operations_remove()
}

function resume_operations_remove() {
	if (game.count === 0)
		goto_operations_done()
	else if (!can_operations_remove())
		goto_operations_place()
}

// OPERATIONS: PLACE

function goto_operations_place() {
	update_presence_and_control()
	if (can_operations_place())
		game.state = "operations_place"
	else
		game.state = "operations_done"
}

function can_operations_place() {
	if (find_available_cube() < 0)
		return false
	for (let s of game.spaces)
		if (can_operations_place_space(s))
			return true
	return false
}

function can_operations_place_space(s) {
	if (is_present(game.active, s) || is_adjacent_to_control(game.active, s)) {
		let d = has_enemy_disc(s)
		if (!d || game.count >= 2)
			return true
	}
	return false
}

states.operations_place = {
	prompt() {
		view.prompt = "Operations: Place cubes into Political spaces."
		for (let s of game.spaces)
			if (can_operations_place_space(s))
				gen_action_space(s)
		view.actions.end_turn = 1
	},
	space(s) {
		push_undo()
		if (has_enemy_disc(s))
			game.count -= 2
		else
			game.count -= 1
		place_piece(find_available_cube(), s)
		resume_operations_place()
	},
	end_turn() {
		end_operations()
	},
}

function resume_operations_place() {
	if (game.count === 0 || !can_operations_place())
		goto_operations_done()
}

// OPERATIONS: DONE

function goto_operations_done() {
	game.state = "operations_done"
}

states.operations_done = {
	prompt() {
		view.prompt = "Operations: All done."
		view.actions.end_turn = 1
	},
	end_turn() {
		end_operations()
	},
}

function end_operations() {
	clear_undo()
	resume_strategy_phase()
}

// === EVENTS ===

function goto_play_event(c) {
	switch (c) {
	// TODO
	}
	resume_strategy_phase()
}


// === SETUP ===

exports.setup = function (seed, scenario, options) {
	game = {
		seed: seed,
		log: [],
		undo: [],
		active: "Both",
		state: "choose_objective_card",

		round: 1,
		initiative: null,
		political_vp: 0,
		military_vp: 0,
		red_momentum: 0,
		blue_momentum: 0,

		strategy_deck: [],
		objective_deck: [],
		discard: 0,

		red_hand: [ 34 ],
		red_objective: 0,

		blue_hand: [ 17 ],
		blue_objective: 0,

		presence: 0,
		control: 0,

		pieces: [
			// Commune cubes
			RED_CRISIS_TRACK[0],
			RED_CRISIS_TRACK[0],
			RED_CRISIS_TRACK[0],
			RED_CRISIS_TRACK[1],
			RED_CRISIS_TRACK[1],
			RED_CRISIS_TRACK[2],
			RED_CRISIS_TRACK[2],
			RED_CRISIS_TRACK[3],
			RED_CRISIS_TRACK[3],
			RED_BONUS_CUBES[0],
			RED_BONUS_CUBES[0],
			RED_BONUS_CUBES[1],
			RED_BONUS_CUBES[1],
			RED_BONUS_CUBES[2],
			RED_BONUS_CUBES[2],
			S_PRESS,
			S_SOCIAL_MOVEMENTS,
			S_PERE_LACHAISE,
			// Versailles cubes
			BLUE_CRISIS_TRACK[0],
			BLUE_CRISIS_TRACK[1],
			BLUE_CRISIS_TRACK[1],
			BLUE_CRISIS_TRACK[2],
			BLUE_CRISIS_TRACK[3],
			BLUE_CRISIS_TRACK[3],
			BLUE_BONUS_CUBES[0],
			BLUE_BONUS_CUBES[1],
			BLUE_BONUS_CUBES[2],
			BLUE_BONUS_CUBES[2],
			BLUE_CUBE_POOL,
			BLUE_CUBE_POOL,
			BLUE_CUBE_POOL,
			BLUE_CUBE_POOL,
			BLUE_CUBE_POOL,
			BLUE_CUBE_POOL,
			S_ROYALISTS,
			S_PRESS,
			// Commune discs
			-1, -1,
			// Versailles discs
			-1, -1,
		],

		count: 0,
		spaces: null,
		who: -1,
	}

	log_h1("Red Flag Over Paris")
	log_h1("Round 1")

	for (let c = 1; c <= 41; ++c)
		if (c !== 17 && c !== 34)
			game.strategy_deck.push(c)

	for (let c = 42; c <= 53; ++c)
		game.objective_deck.push(c)

	shuffle(game.strategy_deck)
	shuffle(game.objective_deck)

	for (let i = 0; i < 4; ++i) {
		game.red_hand.push(game.strategy_deck.pop())
		game.blue_hand.push(game.strategy_deck.pop())
	}

	for (let i = 0; i < 2; ++i) {
		game.red_hand.push(game.objective_deck.pop())
		game.blue_hand.push(game.objective_deck.pop())
	}

	return game
}

// === VIEW ===

exports.is_checkpoint = function (a, b) {
	return a.round !== b.round
}

exports.view = function(state, player) {
	game = state

	view = {
		log: game.log,
		prompt: null,
		actions: null,

		round: game.round,
		initiative: game.initiative,
		political_vp: game.political_vp,
		military_vp: game.military_vp,

		red_hand: game.red_hand.length,
		blue_hand: game.blue_hand.length,
		red_momentum: game.red_momentum,
		blue_momentum: game.blue_momentum,

		pieces: game.pieces,

		discard: game.discard,
		hand: 0,
		objective: 0
	}

	if (player === COMMUNE) {
		view.hand = game.red_hand
		view.objective = game.red_objective
	}
	if (player === VERSAILLES) {
		view.hand = game.blue_hand
		view.objective = game.blue_objective
	}

	if (game.state === "game_over") {
		view.prompt = game.victory
	} else if (player === "Observer" || (game.active !== player && game.active !== "Both")) {
		if (states[game.state]) {
			let inactive = states[game.state].inactive || game.state
			view.prompt = `Waiting for ${game.active} to ${inactive}...`
		} else {
			view.prompt = "Unknown state: " + game.state
		}
	} else {
		view.actions = {}
		if (states[game.state])
			states[game.state].prompt(player)
		else
			view.prompt = "Unknown state: " + game.state
		if (view.actions.undo === undefined) {
			if (game.undo && game.undo.length > 0)
				view.actions.undo = 1
			else
				view.actions.undo = 0
		}
	}

	return view
}

exports.action = function (state, player, action, arg) {
	game = state
	if (states[game.state] && action in states[game.state]) {
		states[game.state][action](arg, player)
	} else {
		if (action === "undo" && game.undo && game.undo.length > 0)
			pop_undo()
		else
			throw new Error("Invalid action: " + action)
	}
	return game
}

// === GAME OVER ===

exports.resign = function (state, player) {
	game = state
	if (game.state !== "game_over") {
		if (current === COMMUNE)
			goto_game_over(VERSAILLES, "Commune resigned.");
		if (current === VERSAILLES)
			goto_game_over(COMMON, "Versailles resigned.");
	}
	return game
}

function goto_game_over(result, victory) {
	game.state = "game_over"
	game.active = "None"
	game.result = result
	game.victory = victory
	log_br()
	log(game.victory)
}

states.game_over = {
	get inactive() {
		return game.victory
	},
	prompt() {
		view.prompt = game.victory
	},
}

// === ACTIONS ===

function gen_action(action, argument) {
	if (!(action in view.actions))
		view.actions[action] = []
	set_add(view.actions[action], argument)
}

function gen_action_card(c) {
	gen_action("card", c)
}

function gen_action_piece(p) {
	gen_action("piece", p)
}

function gen_action_space(s) {
	gen_action("space", s)
}

// === LOGGING ===

function log(msg) {
	game.log.push(msg)
}

function log_br() {
	if (game.log.length > 0 && game.log[game.log.length - 1] !== "")
		game.log.push("")
}

function logi(msg) {
	game.log.push(">" + msg)
}

function log_h1(msg) {
	log_br()
	log(".h1 " + msg)
	log_br()
}

function log_h2(msg) {
	log_br()
	log(".h2 " + msg)
	log_br()
}

// === COMMON LIBRARY ===

function clear_undo() {
	if (game.undo.length > 0)
		game.undo = []
}

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 = object_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 random(range) {
	// An MLCG using integer arithmetic with doubles.
	// https://www.ams.org/journals/mcom/1999-68-225/S0025-5718-99-00996-5/S0025-5718-99-00996-5.pdf
	// m = 2**35 − 31
	return (game.seed = game.seed * 200105 % 34359738337) % range
}

function random_bigint(range) {
	// Largest MLCG that will fit its state in a double.
	// Uses BigInt for arithmetic, so is an order of magnitude slower.
	// https://www.ams.org/journals/mcom/1999-68-225/S0025-5718-99-00996-5/S0025-5718-99-00996-5.pdf
	// m = 2**53 - 111
	return (game.seed = Number(BigInt(game.seed) * 5667072534355537n % 9007199254740881n)) % range
}

function shuffle(list) {
	// Fisher-Yates shuffle
	for (let i = list.length - 1; i > 0; --i) {
		let j = random(i + 1)
		let tmp = list[j]
		list[j] = list[i]
		list[i] = tmp
	}
}

function shuffle_bigint(list) {
	// Fisher-Yates shuffle
	for (let i = list.length - 1; i > 0; --i) {
		let j = random_bigint(i + 1)
		let tmp = list[j]
		list[j] = list[i]
		list[i] = tmp
	}
}

// Fast deep copy for objects without cycles
function object_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] = object_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] = object_copy(v)
			else
				copy[i] = v
		}
		return copy
	}
}

// Array remove and insert (faster than splice)

function array_remove_item(array, item) {
	let n = array.length
	for (let i = 0; i < n; ++i)
		if (array[i] === item)
			return array_remove(array, i)
}

function array_remove(array, index) {
	let n = array.length
	for (let i = index + 1; i < n; ++i)
		array[i - 1] = array[i]
	array.length = n - 1
}

function array_insert(array, index, item) {
	for (let i = array.length; i > index; --i)
		array[i] = array[i - 1]
	array[index] = item
}

function array_remove_pair(array, index) {
	let n = array.length
	for (let i = index + 2; i < n; ++i)
		array[i - 2] = array[i]
	array.length = n - 2
}

function array_insert_pair(array, index, key, value) {
	for (let i = array.length; i > index; i -= 2) {
		array[i] = array[i-2]
		array[i+1] = array[i-1]
	}
	array[index] = key
	array[index+1] = value
}

// Set as plain sorted array

function set_clear(set) {
	set.length = 0
}

function set_has(set, item) {
	let a = 0
	let b = set.length - 1
	while (a <= b) {
		let m = (a + b) >> 1
		let x = set[m]
		if (item < x)
			b = m - 1
		else if (item > x)
			a = m + 1
		else
			return true
	}
	return false
}

function set_add(set, item) {
	let a = 0
	let b = set.length - 1
	while (a <= b) {
		let m = (a + b) >> 1
		let x = set[m]
		if (item < x)
			b = m - 1
		else if (item > x)
			a = m + 1
		else
			return
	}
	array_insert(set, a, item)
}

function set_delete(set, item) {
	let a = 0
	let b = set.length - 1
	while (a <= b) {
		let m = (a + b) >> 1
		let x = set[m]
		if (item < x)
			b = m - 1
		else if (item > x)
			a = m + 1
		else {
			array_remove(set, m)
			return
		}
	}
}

function set_toggle(set, item) {
	let a = 0
	let b = set.length - 1
	while (a <= b) {
		let m = (a + b) >> 1
		let x = set[m]
		if (item < x)
			b = m - 1
		else if (item > x)
			a = m + 1
		else {
			array_remove(set, m)
			return
		}
	}
	array_insert(set, a, item)
}

// Map as plain sorted array of key/value pairs

function map_clear(map) {
	map.length = 0
}

function map_has(map, key) {
	let a = 0
	let b = (map.length >> 1) - 1
	while (a <= b) {
		let m = (a + b) >> 1
		let x = map[m<<1]
		if (key < x)
			b = m - 1
		else if (key > x)
			a = m + 1
		else
			return true
	}
	return false
}

function map_get(map, key, missing) {
	let a = 0
	let b = (map.length >> 1) - 1
	while (a <= b) {
		let m = (a + b) >> 1
		let x = map[m<<1]
		if (key < x)
			b = m - 1
		else if (key > x)
			a = m + 1
		else
			return map[(m<<1)+1]
	}
	return missing
}

function map_set(map, key, value) {
	let a = 0
	let b = (map.length >> 1) - 1
	while (a <= b) {
		let m = (a + b) >> 1
		let x = map[m<<1]
		if (key < x)
			b = m - 1
		else if (key > x)
			a = m + 1
		else {
			map[(m<<1)+1] = value
			return
		}
	}
	array_insert_pair(map, a<<1, key, value)
}

function map_delete(map, item) {
	let a = 0
	let b = (map.length >> 1) - 1
	while (a <= b) {
		let m = (a + b) >> 1
		let x = map[m<<1]
		if (item < x)
			b = m - 1
		else if (item > x)
			a = m + 1
		else {
			array_remove_pair(map, m<<1)
			return
		}
	}
}