-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlistbuilder.py
executable file
·1798 lines (1533 loc) · 66.2 KB
/
listbuilder.py
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
#!/usr/bin/env python3
import shutil
import os
import zipfile
import argparse
import sqlite3
import re
import random
import logging
import logging.handlers
PWD = os.getcwd()
_handler = logging.handlers.WatchedFileHandler("/var/log/shrimp.log")
logging.basicConfig(handlers=[_handler], level=logging.INFO)
g_import_vlb = os.path.abspath("vlb-out.vlog")
g_vlb_path = os.path.abspath("list.vlb")
g_working_path = os.path.abspath(os.path.join(PWD, "working"))
g_export_to = os.path.abspath("vlb-out.vlog")
g_import_aff = os.path.abspath("test.aff")
g_import_flt = os.path.abspath("list.flt")
g_conn = os.path.abspath("vlb_pieces.vlo")
g_import_vlog = False
""" These dicts translate between canonical names and non-canonical
(some misspelled, mostly just shorthand). Because they all have
to match the Vassal name (as that's what the db is generated
from), the Vassal errors dict translates correct keys to the
corresponding incorrect Vassal values, while the listbuilder errors
dict translates incorrect keys to Vassal values regardless of the
correctness of the Vassal value.
"exectuorclass": "executorclass" is a special case because the
reference in the card itself to the ship token is wrong. I have no
idea why it is able to successfully spawn in-game, but this fixes
it on my side soooo...
"""
# "canon": "non-canon",
vassal_nomenclature_errors = {
"arc170starfightersquadron": "arc170squadron",
"arquitensclasscommandcruiser": "arquitenscommandcruiser",
"arquitensclasslightcruiser": "arquitenslightcruiser",
"bailorgana": "bailorganacom",
"belbullab22starfightersquadron": "belbullab22squadron",
"coloneljendonlambdaclassshuttle": "coloneljendon",
"consularclasschargerc70": "consularclasschargerc70retrofit",
"dist81": "distb1",
"exectuorclass": "executorclass",
"executoriclassstardreadnought": "executoristardn",
"executoriiclassstardreadnought": "executoriistardn",
"gladiatoriclassstardestroyer": "gladiatori",
"gladiatoriiclassstardestroyer": "gladiatorii",
"gozanticlassassaultcarriers": "gozantiassaultcarriers",
"gozanticlasscruisers": "gozanticruisers",
"gozanticlasscruiserscis": "gozanticruiserscis",
"greensquadronawing": "greensquadron",
"greensquadronawingsquadron": "greensquadron",
"hwk290": "hwk290lightfreighter",
"hyenaclassdroidbombersquadron": "hyenabombersquadron",
"imperialiclassstardestroyer": "imperiali",
"imperialiiclassstardestroyer": "imperialii",
"imperialstardestroyercymoon1refit": "cymoon1refit",
"imperialstardestroyerkuatrefit": "kuatrefit",
"independence": "independance",
"isdcymoon1refit": "cymoon1refit",
"isdkuatrefit": "kuatrefit",
"kyrstaagatecom": "kyrstaagate",
"landocalrissianoff": "landocalrissian",
"lieutenantblountz95headhuntersquadron": "lieutenantblount",
"mandaloriangauntletfighter": "mandogauntletfighter",
"modifiedpeltaclassassaultship": "peltaclassassaultship",
"modifiedpeltaclasscommandship": "peltaclasscommandship",
"obiwankenobi": "obiwankenobicom",
"providenceclasscarrier": "providencecarrier",
"providenceclasscarrierreb": "providencecarrierreb",
"providenceclassdreadnought": "providencedreadnought",
"quasarfireiclasscruisercarrier": "quasarfirei",
"quasarfireiiclasscruisercarrier": "quasarfireii",
"raidericlasscorvette": "raideri",
"raideriiclasscorvette": "raiderii",
"recusantclasslightdestroyer": "recusantlightdestroyer",
"recusantclasssupportdestroyer": "recusantsupportdestroyer",
"stardreadnoughtassaultprototype": "stardnassaultprototype",
"stardreadnoughtcommandprototype": "stardncommandprototype",
"vcx100freighter": "vcx100lightfreighter",
"venatoriclassstardestroyer": "venatori",
"venatoriiclassstardestroyer": "venatorii",
"venatoriiclassstardestroyerimp": "venatoriiimp",
"venatoriiclassstardestroyerimperial": "venatoriiimp",
"victoryiclassstardestroyer": "victoryi",
"victoryiclassstardestroyergar": "victoryigar",
"victoryiiclassstardestroyer": "victoryii",
"vultureclassdroidfightersquadron": "vulturedroidsquadron",
"yt1300": "yt1300lightfreighter",
"yt2400": "yt2400lightfreighter",
"yv666": "yv666lightfreighter",
}
# "non-canon": "vassal-canon",
listbuilder_nomenclature_errors = {
"7thfleetstardestroyer": "seventhfleetstardestroyer",
"acclamatori": "acclamatoriclassassaultship",
"acclamatorii": "acclamatoriiclassassaultship",
"acclamatoriclass": "acclamatoriclassassaultship",
"acclamatoriiclass": "acclamatoriiclassassaultship",
"admiralozzelcom": "admiralozzel",
"ahsokatanooff": "ahsokatano",
"anakinskywalkerbtlb": "anakinskywalkerbtlbywing",
"anakinskywalkerdelta": "anakinskywalkerdelta7",
"anakinskywalkeryrep": "anakinskywalkerbtlbywing",
"armedcruiser": "consularclassarmedcruiser",
"assaultfrigatemk2a": "assaultfrigatemarkiia",
"assaultfrigatemk2b": "assaultfrigatemarkiib",
"assaultfrigatemkiia": "assaultfrigatemarkiia",
"assaultfrigatemkiib": "assaultfrigatemarkiib",
"battlerefit": "hardcellclassbattlerefit",
"bltbywingsquadron": "btlbywingsquadron",
"chargerc70": "consularclasschargerc70retrofit",
"clonecmdrwolffe": "clonecommanderwolffe",
"commsfrigate": "munificentclasscommsfrigate",
"consulararmedcruiser": "consularclassarmedcruiser",
"consularchargerc70": "consularclasschargerc70retrofit",
"cr90acorvette": "cr90corvettea",
"cr90bcorvette": "cr90corvetteb",
"cr90corelliancorvettea": "cr90corvettea",
"cr90corelliancorvetteb": "cr90corvetteb",
"darthvaderdefender": "darthvadertiedefender",
"dby827heavyturbolaser": "dby827heavyturbolasers",
"genericritrcommander": "admiralkonstantine",
"hardcellbattlerefit": "hardcellclassbattlerefit",
"hardcelltransport": "hardcellclasstransport",
"hardendbulkheads": "hardenedbulkheads",
"hyenadroidbombersquadron": "hyenabombersquadron",
# "ig88ig2000": "ig88",
"interdictorclasssuppressionrefit": "interdictorsuppressionrefit",
"interdictorclasscombatrefit": "interdictorcombatrefit",
"lambdashuttle": "lambdaclassshuttle",
"lancerpursuitcraft": "lancerclasspursuitcraft",
"landocarissian": "landocalrissian",
"lietenantblount": "lieutenantblount",
"linkedturbolaserturrets": "linkedturbolasertowers",
"locationfirecontrol": "localfirecontrol",
"maareksteele": "maarekstele",
"moncalamariexodusfleet": "moncalexodusfleet",
"munificentcommsfrigate": "munificentclasscommsfrigate",
"munificentstarfrigate": "munificentclassstarfrigate",
"munitionsresuppy": "munitionsresupply",
"onagerstardestroyer": "onagerclassstardestroyer",
"onagertestbed": "onagerclasstestbed",
"partsresuppy": "partsresupply",
"peltaassaultship": "peltaclassassaultship",
"peltacommandship": "peltaclasscommandship",
"peltamedicalfrigate": "peltaclassmedicalfrigate",
"peltatransportfrigate": "peltaclasstransportfrigate",
"rayantilles": "raymusantilles",
"solorcorona": "solarcorona",
"ssdexecutori": "executoristardn",
"ssdexecutorii": "executoriistardn",
"ssdcommandprototype": "stardncommandprototype",
"ssdassaultprototype": "stardnassaultprototype",
"starfrigate": "munificentclassstarfrigate",
"starhawkclassmki": "starhawkmarki",
"starhawkclassmkii": "starhawkmarkii",
"starhawkbattleshipmarki": "starhawkmarki",
"starhawkbattleshipmarkii": "starhawkmarkii",
"starhawkclassbattleshipmarki": "starhawkmarki",
"starhawkclassbattleshipmarkii": "starhawkmarkii",
"supriseattack": "surpriseattack",
"transport": "hardcellclasstransport",
"vulturedroidfightersquadron": "vulturedroidsquadron",
"xcustomcommander": "admiralkonstantine",
"x17turbolasers": "xi7turbolasers",
# SQUADRON EXTENDED NOMENCLATURE TRANSLATION
"axe": "axev19torrent",
"baktoidprototypes": "baktoidprototypeshyenabomber",
"biggsdarklighter": "biggsdarklighterxwing",
"blacksquadron": "blacksquadrontiefighter",
"bobafett": "bobafettslave1",
"bossk": "bosskhoundstooth",
"captainjonus": "captainjonustiebomber",
"cienaree": "cienareetieinterceptor",
"coloneljendon": "coloneljendonlambdaclass",
"corranhorn": "corranhornewing",
"daggersquadron": "daggersquadronbwing",
"dashrendar": "dashrendaroutrider",
"dbs404": "dbs404hyenabomber",
"dengar": "dengarpunishingone",
"dfs311": "dfs311vulturedroid",
"distb1": "distb1droidtrifighter",
"dutchvander": "dutchvanderywing",
"gammasquadron": "gammasquadrontiebomber",
"garsaxon": "garsaxongauntletfighter",
"generalgrievous": "generalgrievousbelbullab22",
"goldsquadron": "goldsquadronywing",
"greensquadron": "greensquadronawing",
"hansolo": "hansolomillenniumfalcon",
"haorchallprototypes": "haorchallprototypesvulturedroid",
"howlrunner": "howlrunnertiefighter",
"ig88b": "ig88big2000b",
"ig88": "ig88ig2000",
"janors": "janorsmoldycrow",
"kananjarrus": "kananjarrushwk290",
"ketsuonyo": "ketsuonyoshadowcaster",
"keyanfarlander": "keyanfarlanderbwing",
"kickback": "kickbackv19torrent",
"kitfisto": "kitfistodelta7",
"lieutenantblount": "lieutenantblountz95",
"lukeskywalker": "lukeskywalkerxwing",
"maarekstele": "maareksteletiedefender",
"majorrhymer": "majorrhymertiebomber",
"maleehurra": "maleehurrascurrgh6",
"martmattin": "martmattinsatoshammer",
"maulermithel": "maulermitheltiefighter",
"moraloeval": "moraloevalyv666",
"mornakee": "mornakeevt49decimator",
"norrawexley": "norrawexleyywing",
"nym": "nymhavoc",
"oddball": "oddballarc170",
"phlacarphoccprototypes": "phlacarphoccprototypesdroidtrifighter",
"plokoon": "plokoondelta7",
"roguesquadron": "roguesquadronxwing",
"sabersquadron": "sabersquadrontieinterceptor",
"sharabey": "sharabeyawing",
"soontirfel": "soontirfeltieinterceptor",
"teltrevura": "teltrevurajumpmaster",
"tempestsquadron": "tempestsquadrontieadvanced",
"tennumb": "tennumbbwing",
"tychocelchu": "tychocelchuawing",
"valenrudor": "valenrudortiefighter",
"whisper": "whispertiephantom",
"zertikstrom": "zertikstromtieadvanced",
}
nomenclature_translation = {
**vassal_nomenclature_errors,
**listbuilder_nomenclature_errors,
}
""" This dict pairs names of identically-named cards (Darth Vader, Leia Organa,
etc) with their costs in a tuple (the key) to reference their Vassal name and
card type.
"""
ambiguous_names = {
("admiralozzel", "20"): ("admiralozzel", "upgrade"),
("admiralozzel", "2"): ("admiralozzeloff", "upgrade"),
("ahsokatano", "23"): ("ahsokatanodelta7", "squadron"),
("ahsokatano", "2"): ("ahsokatano", "upgrade"),
("ahsokatano", "6"): ("ahsokatanorepoff", "upgrade"),
("ahsokatano", "23"): ("ahsokatanodelta7", "squadron"),
("anakinskywalker", "19"): ("anakinskywalkerbtlbywing", "squadron"),
("anakinskywalker", "24"): ("anakinskywalkerdelta7", "squadron"),
("anakinskywalker", "29"): ("anakinskywalkercom", "upgrade"),
("darthvader", "36"): ("darthvadercom", "upgrade"),
("darthvader", "3"): ("darthvaderwpn", "upgrade"),
("darthvader", "1"): ("darthvaderoff", "upgrade"),
("darthvader", "21"): ("darthvadertieadvanced", "squadron"),
("darthvader", "25"): ("darthvadertiedefender", "squadron"),
("emperorpalpatine", "35"): ("emperorpalpatinecom", "upgrade"),
("emperorpalpatine", "3"): ("emperorpalpatineoff", "upgrade"),
("generaldraven", "28"): ("generaldravencom", "upgrade"),
("generaldraven", "3"): ("generaldraven", "upgrade"),
("generalgrievous", "20"): ("generalgrievouscom", "upgrade"),
("generalgrievous", "22"): ("generalgrievousbelbullab22", "squadron"),
("gozanticruisers", "27"): ("gozanticruiserscis", "shipcard"),
("gozanticruisers", "23"): ("gozanticruiser", "shipcard"),
("herasyndulla", "28"): ("herasyndullaghost", "squadron"),
("herasyndulla", "23"): ("herasyndullaxwing", "squadron"),
("hondoohnaka", "24"): ("hondoohnakaslave1", "squadron"),
("hondoohnaka", "2"): ("hondoohnaka", "upgrade"),
("kyrstaagate", "20"): ("kyrstaagate", "upgrade"),
("kyrstaagate", "5"): ("kyrstaagateoff", "upgrade"),
("landocalrissian", "23"): ("landocalrissianmillenniumfalcon", "squadron"),
("landocalrissian", "4"): ("landocalrissian", "upgrade"),
("leiaorgana", "28"): ("leiaorganacom", "upgrade"),
("leiaorgana", "3"): ("leiaorganaoff", "upgrade"),
("luminaraunduli", "23"): ("luminaraundulidelta7", "squadron"),
("luminaraunduli", "25"): ("luminaraundulicom", "upgrade"),
("plokoon", "26"): ("plokooncom", "upgrade"),
("plokoon", "24"): ("plokoondelta7", "squadron"),
("providenceclasscarrier", "95"): ("providencecarrierreb", "shipcard"),
("providenceclasscarrier", "105"): ("providencecarrier", "shipcard"),
# ("venatoriiclassstardestroyer", "100"): ("venatoriiimp", "shipcard"),
# ("venatoriiclassstardestroyer", "100"): ("venatorii", "shipcard"),
("victoryiclassstardestroyer", "73"): ("victoryi", "shipcard"),
("victoryiclassstardestroyer", "75"): ("victoryigar", "shipcard"),
("wattambor", "5"): ("wattambor", "upgrade"),
("wattambor", "20"): ("wattamborbelbullab22", "squadron"),
("wedgeantilles", "19"): ("wedgeantillesxwing", "squadron"),
("wedgeantilles", "4"): ("wedgeantillesoff", "upgrade"),
}
def unzipall(zip_file_path, tar_path):
"""Unzips all of the files in the zip file at zip_file_path and
dumps all those files into directory tar_path.
I'm pretty sure this duplicates a built-in function, but, I mean...
it works."""
zip_ref = zipfile.ZipFile(zip_file_path, "r")
zip_ref.extractall(tar_path)
zip_ref.close()
def zipall(tar_path, zip_file_path):
"""Creates a new zip file at zip_file_path and populates it with
the zipped contents of tar_path.
I'm pretty sure this duplicates a built-in function, but, I mean...
it works."""
shittyname = shutil.make_archive(zip_file_path, "zip", tar_path)
shutil.move(shittyname, zip_file_path)
def ident_format(fleet_text):
formats = {
"fab": 0.0,
"warlord": 0.0,
"afd": 0.0,
"kingston": 0.0,
"aff": 0.0,
"vlog": 0.0,
"vlb": 0.0,
}
# format_names = {'fab': "Fab's Armada Fleet Builder",
# 'warlord': "Armada Warlords",
# 'afd': "Armada Fleets Designer for Android",
# 'kingston': "Ryan Kingston's Armada Fleet Builder",
# 'aff': "Armada Fleet Format",
# 'vlog': "VASSAL Log File",
# 'vlb': "VASSAL Armada Listbuilder"}
# Fab's
if " • " in fleet_text:
formats["fab"] += 1.0
if "FLEET" in fleet_text.split("\n")[0]:
formats["fab"] += 1.0
if "armada.fabpsb.net" in fleet_text.lower():
formats["fab"] += 5.0
i = 0
for line in fleet_text.split("\n"):
try:
if " • " in line and line[0].isdigit():
if int(line[0]) == i + 1:
formats["fab"] += 1
i += int(line[0])
except IndexError:
pass
# Warlords
ft = fleet_text.replace("•", "\u2022")
if "[flagship]" in ft.replace(" ", ""):
formats["warlord"] += 5.0
if "Armada Warlords" in ft:
formats["warlord"] += 5.0
if "Commander: " in ft:
formats["warlord"] += 2.0
for line in ft.split("\n"):
if "\t points)" in line:
formats["warlord"] += 1
if line.strip().startswith("- "):
formats["warlord"] += 0.5
# Armada Fleets Designer
if "+" in fleet_text:
formats["afd"] += 1.0
if "/400)" in fleet_text.split("\n")[0]:
formats["afd"] += 2.0
for lineloc, line in enumerate(fleet_text.split("\n")):
if lineloc > 0:
if (len(fleet_text.split("\n")[lineloc - 1]) == line.count("=") + 1) and (
line.count("=") > 3
):
formats["afd"] += 5.0
if line.strip().startswith("· "):
formats["afd"] += 1
# Kingston
if "Faction:" in ft:
formats["kingston"] += 1.0
if "Commander: " in ft:
formats["kingston"] += 2.0
for line in ft.split("\n"):
if line.strip().startswith("• ") or line.strip().startswith("\u2022"):
formats["kingston"] += 1
# AFF
if fleet_text[0] == "{":
formats["aff"] += 30.0
if fleet_text.startswith("ship:"):
formats["aff"] += 30.0
if fleet_text.startswith("squadron:"):
formats["aff"] += 30
logging.info("Format detection: {}".format(str(formats)))
return max(formats.keys(), key=(lambda x: formats[x]))
def import_from_list(import_from, output_to, working_path, conn, isvlog=False):
ingest_format = {
"fab": import_from_fabs,
"warlord": import_from_warlords,
"afd": import_from_afd,
"kingston": import_from_kingston,
"aff": import_from_aff,
"vlog": import_from_vlog,
}
if isvlog:
import_from_vlog(import_from, output_to, working_path, conn)
else:
if os.path.exists(import_from):
logging.info(import_from)
with open(import_from) as fleet_list:
fleet_text = fleet_list.read()
else:
fleet_text = import_from
fmt = ident_format(fleet_text)
success, f = ingest_format[fmt](fleet_text, output_to, working_path, conn)
logging.info(success, f)
if not success:
return (success, f)
with open(output_to, "w") as vlb:
vlb.write("a1\r\nbegin_save{}\r\nend_save{}\r\n".format(chr(27), chr(27)))
vlb.write(
"LOG\tCHAT<Listbuilder> - "
+ "Fleet imported by Shrimpbot on the Armada Discord.{}\r\n".format(
chr(27)
)
+ "LOG\tCHAT<Listbuilder> - "
+ "https://discord.gg/jY4K4d6{}\r\n\r\n".format(chr(27))
)
for s in f.ships:
vlb.write(s.shipcard.content + chr(27))
vlb.write(s.shiptoken.content + chr(27))
vlb.write(s.shipcmdstack.content + chr(27))
[vlb.write(u.content + chr(27)) for u in s.upgrades]
for sq in f.squadrons:
vlb.write(sq.squadroncard.content + chr(27))
vlb.write(sq.squadrontoken.content + chr(27))
for o in f.objectives:
vlb.write(f.objectives[o].content + chr(27))
return (True, None)
def import_from_fabs(import_list, vlb_path, working_path, conn):
"""Imports a Fab's Fleet Builder list into a Fleet object"""
f = Fleet("Food", conn=conn)
last_line = ""
for line in import_list.split("\n"):
logging.info(line)
last_line = line
try:
if line.strip():
if line.strip()[0].isdigit():
this_line = line.replace("•", "\u2022").strip()
this_line = "".join(
"".join(this_line.split(" {} ".format("\u2022"))[1::]).split(
" ("
)[:-1]
)
# only ships & objs are broken up with " - ", and objs are labelled
# otherwise, it's either sqd or upgradeless ship--indistinguishable
if " - " in this_line:
if this_line.startswith("Objective"):
pass
else:
working_line = this_line.split(" - ")
s = f.add_ship(working_line[0].strip())
for u in working_line[1::]:
s.add_upgrade(u.strip())
else:
issquadron = False
isship = False
issquadronfancy = False
this_line = scrub_piecename(this_line)
if this_line in nomenclature_translation:
t = nomenclature_translation[this_line]
logging.info(
"[-] Translated {} to {} - Fab's.".format(this_line, t)
)
this_line = t
logging.info(
"Searching for Fab's piece {} in {}".format(
scrub_piecename(this_line), str(conn)
)
)
try:
with sqlite3.connect(conn) as connection:
issquadron = connection.execute(
"""SELECT * FROM pieces
WHERE piecetype='squadroncard'
AND piecename LIKE ?;""",
("%" + scrub_piecename(this_line) + "%",),
).fetchall()
except ValueError as err:
logging.exception(err)
try:
with sqlite3.connect(conn) as connection:
isship = connection.execute(
"""SELECT * FROM pieces
WHERE piecetype='shipcard'
AND piecename LIKE ?;""",
("%" + scrub_piecename(this_line),),
).fetchall()
except ValueError as err:
logging.exception(err)
try:
if this_line.lower()[-8::] == "squadron":
ltmp = this_line[0:-8]
with sqlite3.connect(conn) as connection:
issquadronfancy = connection.execute(
"""SELECT * FROM pieces
WHERE piecetype='squadroncard'
AND piecename LIKE ?;""",
("%" + scrub_piecename(ltmp) + "%",),
).fetchall()
except ValueError as err:
logging.exception(err)
if bool(issquadron):
# sq = f.add_squadron(l.strip())
f.add_squadron(this_line.strip())
elif bool(issquadronfancy):
_ = f.add_squadron(ltmp.strip())
elif bool(isship):
s = f.add_ship(this_line.strip())
else:
logging.info(
"{}{} IS FUCKED UP, YO{}".format(
"=" * 40, this_line, "=" * 40
)
)
except Exception as err:
logging.exception(err)
return (False, last_line)
return (True, f)
def import_from_warlords(import_list, vlb_path, working_path, conn):
"""Imports an Armada Warlords list into a Fleet object"""
f = Fleet("Food", conn=conn)
shipnext = False
is_flagship = False
logging.info("Warlords")
# Set the flag if it looks like Flagship format to enable the custom error
flagship_regex = re.compile(r"\)\n= [\d]{1,3} points\n")
if flagship_regex.search(import_list):
logging.info("[!] FLAGSHIP LIST -- UNSUPPORTED!")
is_flagship = True
# Make sure the cretinous user isn't just schwacking off all the garbage at
# the top of a Warlords export.
ship_regex = re.compile(r".*\([\d]{1,3} points\)")
squadron_regex = re.compile(r"^[\d]{1,2}.*\(.*[\d]{1,3} points\)")
ship_check = import_list.split("\n")[0].strip()
if ship_regex.search(ship_check):
logging.info("Ship check regex hit on: " + str(ship_regex.search(ship_check)))
ship_check = ship_check.split()[0]
logging.info(
"SELECT piecetype FROM pieces where piecename LIKE %"
+ scrub_piecename(ship_check)
+ "%"
)
with sqlite3.connect(conn) as connection:
ship_query = connection.execute(
'''SELECT piecetype FROM pieces where piecename LIKE ?" "''',
("%" + scrub_piecename(ship_check) + "%",),
).fetchall()
if len(ship_query) > 0:
if ("ship",) in ship_query or ("shipcard",) in ship_query:
shipnext = True
for line in import_list.split("\n"):
card_name = line.strip()
last_line = card_name
logging.info(card_name)
try:
logging.info(card_name.split())
if len(card_name.split()) <= 1:
shipnext = True
elif card_name.split()[0].strip() in [
"Faction:",
"Points:",
"Commander:",
"Author:",
]:
pass
elif card_name.split()[1] == "Objective:":
objective = [card_name.split()[0], card_name.split(":")[1]]
f.add_objective(objective[0], objective[1])
shipnext = False
elif squadron_regex.search(card_name):
# squadron, cost = card_name.split("(", 1)
squadron = "".join(card_name.split("(")[0:-1])
cost = card_name.split("(")[-1]
squadron = scrub_piecename(
"".join(card_name.split("(")[0].split()[1::])
)
cost = scrub_piecename(cost.split()[0])
if card_name.split()[0].isdigit:
if int(card_name.split()[0]) > 1:
squadron = squadron[:-1]
if (squadron, cost) in ambiguous_names:
squadron_new = ambiguous_names[(squadron, cost)][0]
logging.info(
"Ambiguous name {} ({}) translated to {}.".format(
squadron, cost, squadron_new
)
)
squadron = squadron_new
# sq = f.add_squadron(squadron)
f.add_squadron(squadron)
shipnext = False
elif card_name[0] == "=":
shipnext = True
elif shipnext:
ship = "(".join(card_name.split("]")[-1].split("(")[0:-1])
cost = card_name.split("]")[-1].split("(")[-1]
ship = scrub_piecename(ship.strip(" -\t"))
cost = scrub_piecename(cost.split()[0])
if (ship, cost) in ambiguous_names:
ship_new = ambiguous_names[(ship, cost)][0]
logging.info(
"Ambiguous name {} ({}) translated to {}.".format(
ship, cost, ship_new
)
)
ship = ship_new
s = f.add_ship(ship)
shipnext = False
elif card_name[0] == "-":
upgrade, cost = card_name.rsplit("(", 1)
upgrade = scrub_piecename(upgrade)
cost = scrub_piecename(cost.split()[0])
if (upgrade, cost) in ambiguous_names:
upgrade_new = ambiguous_names[(upgrade, cost)][0]
logging.info(
"Ambiguous name {} ({}) translated to {}.".format(
upgrade, cost, upgrade_new
)
)
upgrade = upgrade_new
_ = s.add_upgrade(upgrade)
shipnext = False
except Exception as err:
logging.exception(err)
if is_flagship:
last_line = (
last_line
+ "\n"
+ "=" * 40
+ "\nThis appears to be a Flagship list. Shrimpbot currently "
+ "supports Flagship only only insofar as it conforms to Warlords' "
+ "format. *Usually* you can make it work by removing and manually "
+ "spawning squadrons. \nSee "
+ "https://github.com/sprintska/shrimpbot/issues/59"
)
return (False, last_line)
return (True, f)
def import_from_afd(import_list, vlb_path, working_path, conn):
"""Imports an Armada Fleets Designer list into a Fleet object"""
f = Fleet("Food", conn=conn)
start = False
obj_category = "assault"
# shipnext = False
for line in import_list.strip().split("\n"):
try:
last_line = line.strip()
card_name = line.strip().split(" x ", 1)[-1]
logging.info(card_name)
if card_name.startswith("==="):
start = True
elif start and len(card_name) > 0:
if card_name[0] == "·":
upgrade, cost = card_name.split("(")
upgrade = scrub_piecename(upgrade)
cost = cost.split(")")[0]
if upgrade in nomenclature_translation:
translated = nomenclature_translation[upgrade]
logging.info(
"[-] Translated {} to {} - AFD.".format(upgrade, translated)
)
upgrade = translated
if (upgrade, cost) in ambiguous_names:
upgrade_new = ambiguous_names[(upgrade, cost)][0]
logging.info(
"Ambiguous name {} ({}) translated to {}.".format(
upgrade, cost, upgrade_new
)
)
upgrade = upgrade_new
_ = s.add_upgrade(upgrade)
elif "(" not in card_name:
logging.info("Hit the conditional for {}.".format(card_name))
card_name = scrub_piecename(str(card_name))
f.add_objective(obj_category, card_name)
# TODO: retool the objs to not care about categories... :/
if obj_category == "assault":
obj_category = "defense"
else:
obj_category = "navigation"
else:
card_name, cost = card_name.split(" (", 1)
cost = cost.split(" x ")[-1].split(")")[0]
issquadron = False
isship = False
card_name = scrub_piecename(card_name)
try:
if card_name in nomenclature_translation:
t = nomenclature_translation[card_name]
logging.info(
"[-] Translated {} to {} - AFD.".format(card_name, t)
)
card_name = t
if (card_name, cost) in ambiguous_names:
card_name_new = ambiguous_names[(card_name, cost)][0]
logging.info(
"Ambiguous name {} ({}) translated to {}.".format(
card_name, cost, card_name_new
)
)
card_name = card_name_new
logging.info(
"Searching for AFD piece {} in {}".format(
scrub_piecename(card_name), str(conn)
)
)
with sqlite3.connect(conn) as connection:
issquadron = connection.execute(
"""SELECT * FROM pieces
WHERE piecetype='squadroncard'
AND piecename LIKE ?;""",
("%" + scrub_piecename(card_name) + "%",),
).fetchall()
except ValueError as err:
logging.exception(err)
try:
logging.info(
"Searching for AFD piece {} in {}".format(
card_name, str(conn)
)
)
with sqlite3.connect(conn) as connection:
isship = connection.execute(
"""SELECT * FROM pieces
WHERE piecetype='shipcard'
AND piecename LIKE ?;""",
("%" + card_name,),
).fetchall()
except ValueError as err:
logging.exception(err)
if bool(issquadron):
_ = f.add_squadron(card_name)
elif bool(isship):
s = f.add_ship(card_name)
else:
logging.info(
"{}{} IS FUCKED UP, YO{}".format(
"=" * 40, card_name, "=" * 40
)
)
except Exception as err:
logging.exception(err)
return (False, last_line)
return (True, f)
def import_from_kingston(import_list, vlb_path, working_path, conn):
"""Imports an Ryan Kingston list into a Fleet object"""
f = Fleet("Food", conn=conn)
logging.info("Fleet created with database {}.".format(str(conn)))
shipnext = True
faction = None
for line in import_list.split("\n"):
try:
card_name = line.replace("•", "\u2022").strip()
logging.info(card_name)
last_line = card_name
if card_name:
if card_name.split(":")[0].strip() in [
"Name",
"Commander",
"Author",
]:
pass
# Track faction to disambiguate Venator-II variants later
elif card_name.split(":")[0].strip() == "Faction":
faction = card_name.split(":")[-1].strip()
logging.info("Faction identified: {}".format(faction))
elif card_name.split(":")[0] in ["Assault", "Defense", "Navigation"]:
if card_name.strip()[-1] != ":":
logging.info("{}".format(card_name))
_ = f.add_objective(
card_name.split(":")[0].lower().strip(),
card_name.split(":")[1].lower().strip(),
)
elif shipnext:
if card_name.lower().strip() == "squadrons:":
logging.info("Squadrons next")
shipnext = False
elif "\u2022" in card_name:
card_name, cost = card_name.split(" (", 1)
card_name = scrub_piecename(card_name)
cost = cost.split(")")[0]
if (card_name, cost) in ambiguous_names:
card_name_new = ambiguous_names[(card_name, cost)][0]
logging.info(
"Ambiguous name {} ({}) translated to {}.".format(
card_name, cost, card_name_new
)
)
card_name = card_name_new
_ = s.add_upgrade(card_name)
elif card_name[0] == "=":
pass
else:
# Can't disambiguate Venator-II on cost because both variants are identical *sigh*
if card_name == "Venator II (100)" and faction == "Imperial":
logging.info(
"[Debug] Found Imperial Venator. Setting card name."
)
card_name = "Venator II Imp"
s = f.add_ship(card_name.split(" (", 1)[0].strip())
elif "\u2022" in card_name and card_name[0] != "=":
cost = card_name.split(" (")[-1]
cost = cost.split(")")[0]
card_name = "".join(card_name.split(" x ")[-1].split(" (")[0:-1])
card_name = scrub_piecename(card_name)
if (card_name, cost) in ambiguous_names:
card_name_new = ambiguous_names[(card_name, cost)][0]
logging.info(
"Ambiguous name {} ({}) translated to {}.".format(
card_name, cost, card_name_new
)
)
card_name = card_name_new
_ = f.add_squadron(card_name)
except Exception as err:
logging.exception(err)
return (False, last_line)
return (True, f)
def import_from_aff(import_list, vlb_path, working_path, conn):
"""Imports a .aff (Armada Fleet Format) file into a Fleet object"""
f = Fleet("Food", conn=conn)
# with open(import_list) as aff_in:
for line in import_list.split("\n"):
logging.info(line)
# for line in aff_in.readlines():
if line.lower().startswith("ship:"):
s = f.add_ship(line.split(":")[-1].strip())
elif line.lower().startswith("upgrade:"):
_ = s.add_upgrade(line.split(":")[-1].strip())
elif line.lower().startswith("squadron:"):
_ = f.add_squadron(line.split(":")[-1].strip())
return f
def import_from_vlog(import_from, vlb_path, working_path, conn):
"""Strips out all the compression and obfuscation from a VASSAL
log/continution .vlog file at path import_from and creates an
unobfuscated .vlb text file at path vlb_path."""
unzipall(import_from, working_path)
with open(os.path.join(working_path, "savedGame"), "r") as vlog:
b_vlog = vlog.read()
xor_key_str = b_vlog[5:7]
if xor_key.isdigit():
xor_key = int(xor_key_str, 16)
else:
logging.info(
"VLOG {} is malformed: encountered an invalid XOR key. Key {} is not a digit.".format(
str(import_from), str(xor_key)
)
)
xor_key = int("0", 16)
obfuscated = b_vlog[6::]
obf_pair = ""
clear = ""
for charloc, char in enumerate(obfuscated):
obf_pair += char
if not charloc % 2:
clearint = int(obf_pair, 16) ^ xor_key
clear += chr(clearint)
obf_pair = ""
clear = clear[1::].replace("\t", "\t\r\n").replace(chr(27), chr(27) + "\r\n\r\n")
with open(vlb_path, "w") as vlb:
vlb.write(xor_key_str + "\r\n")
vlb.write(clear)
def export_to_vlog(export_to, vlb_path, working_path=g_working_path):
"""Adds all the obfuscation and compression to turn a .vlb
VASSAL listbuilder file (at vlb_path), along with boilerplate
savedata and moduledata XML files in working_path, into a VASSAL-
compatible .vlog replay file."""
out_path = os.path.join(working_path, "..", "out")
for afile in os.listdir(out_path):
file_path = os.path.join(out_path, afile)
try:
if os.path.isfile(file_path):
os.unlink(file_path)
elif os.path.isdir(file_path):
shutil.rmtree(file_path)
except Exception as e:
logging.exception(e)
shutil.copyfile(
os.path.join(working_path, "moduledata"), os.path.join(out_path, "moduledata")
)
shutil.copyfile(