forked from maduck/GoWDiscordTeamBot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
search.py
1631 lines (1481 loc) · 70 KB
/
search.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
import calendar
import copy
import datetime
import importlib
import json
import logging
import operator
import re
from collections import defaultdict
import translations
from configurations import CONFIG
from data_source.game_data import GameData
from game_constants import COLORS, EVENT_TYPES, GEM_TUTORIAL_IDS, RARITY_COLORS, SOULFORGE_ALWAYS_AVAILABLE, \
SOULFORGE_REQUIREMENTS, TROOP_RARITIES, \
UNDERWORLD_SOULFORGE_REQUIREMENTS, WEAPON_RARITIES
from models.bookmark import Bookmark
from models.toplist import Toplist
from util import batched, dig, extract_search_tag, get_next_monday_in_locale, translate_day
WEEK_DAY_FORMAT = '%b %d'
LOGLEVEL = logging.DEBUG
formatter = logging.Formatter('%(asctime)-15s [%(levelname)s] %(message)s')
handler = logging.StreamHandler()
handler.setFormatter(formatter)
handler.setLevel(LOGLEVEL)
log = logging.getLogger(__name__)
log.setLevel(LOGLEVEL)
log.addHandler(handler)
t = translations.Translations()
_ = t.get
def update_translations():
global _
try:
importlib.reload(translations)
_ = translations.Translations().get
except (NameError, json.decoder.JSONDecodeError):
log.exception('Could not update translations, stacktrace follows.')
class TeamExpander:
my_emojis = {}
def __init__(self):
world = GameData()
world.populate_world_data()
self.troops = world.troops
self.troop_types = world.troop_types
self.spells = world.spells
self.effects = world.effects
self.positive_effects = world.positive_effects
self.weapons = world.weapons
self.classes = world.classes
self.banners = world.banners
self.traits = world.traits
self.kingdoms = world.kingdoms
self.pet_effects = world.pet_effects
self.pets = world.pets
self.talent_trees = world.talent_trees
self.spoilers = world.spoilers
self.events = world.events
self.campaign_week = world.campaign_week
self.campaign_name = world.campaign_name
self.campaign_tasks = world.campaign_tasks
self.task_skip_costs = world.campaign_skip_costs
self.reroll_tasks = world.campaign_rerolls
self.soulforge = world.soulforge
self.summons = world.summons
self.traitstones = world.traitstones
self.levels = world.levels
self.rooms = {}
self.toplists = Toplist()
self.bookmarks = Bookmark()
self.adventure_board = world.adventure_board
self.drop_chances = world.drop_chances
self.event_key_drops = world.event_chest_drops
self.event_kingdoms = world.event_kingdoms
self.weekly_event = world.weekly_event
self.active_gems = world.gem_events
self.store_data = world.store_data
self.user_data = world.user_data
self.hoard_potions = world.hoard_potions
self.orbs = world.orbs
@classmethod
def extract_code_from_message(cls, raw_code):
return [int(n.strip()) for n in raw_code.split(',') if n and n.isdigit()]
def get_team_from_code(self, code, lang):
result = {
'troops': [],
'banner': {},
'class': None,
'talents': [],
'class_title': _('[CLASS]', lang),
'troops_title': _('[TROOPS]', lang),
}
has_weapon = False
has_class = False
for i, element in enumerate(code):
if troop := self.troops.get(element):
troop = troop.copy()
self.translate_troop(troop, lang)
result['troops'].append(troop)
continue
if weapon := self.weapons.get(element):
weapon = weapon.copy()
self.translate_weapon(weapon, lang)
result['troops'].append(weapon)
has_weapon = True
continue
if _class := self.classes.get(element):
result['class'] = _(_class['name'], lang)
result['class_talents'] = _class['talents']
has_class = True
continue
if banner := self.banners.get(element):
result['banner'] = self.translate_banner(banner, lang)
continue
if 0 <= element <= 3:
result['talents'].append(element)
self.trim_talents(result)
continue
has_class = self.fill_up_troops_banner_and_class(i, result, has_class, lang)
hero_present = has_weapon and has_class
if hero_present:
result['talents'] = self.populate_talents(result, lang)
else:
result['class'] = None
result['talents'] = None
return result
def fill_up_troops_banner_and_class(self, i, result, has_class, lang):
if i <= 3:
result['troops'].append(self.troops['`?`'])
elif i == 4:
banner = {
'colors': [('questionmark', 1)],
'name': '[REQUIREMENTS_NOT_MET]',
'filename': 'Locked',
'id': '`?`'
}
result['banner'] = self.translate_banner(banner, lang)
elif i == 12:
result['class'] = _('[REQUIREMENTS_NOT_MET]', lang)
result['talents'] = []
return True
return has_class
@staticmethod
def populate_talents(result, lang):
new_talents = []
for talent_no, talent_code in enumerate(result['talents']):
talent = '-'
if talent_code > 0:
talent = _(result['class_talents'][talent_code - 1][talent_no]['name'], lang)
new_talents.append(talent)
return new_talents
def trim_talents(self, result):
if len(result['talents']) > 7:
result['talents'] = result['talents'][-7:]
def get_team_from_message(self, user_code, lang):
if code := self.extract_code_from_message(user_code):
return self.get_team_from_code(code, lang)
else:
return
@staticmethod
def search_item(search_term, lang, items, lookup_keys, translator, sort_by='name'):
if search_term.startswith('#'):
search_term = search_term[1:]
if search_term.isdigit():
if item := items.get(int(search_term)):
result = item.copy()
translator(result, lang)
return [result]
return []
possible_matches = []
real_search = extract_search_tag(search_term)
if not real_search:
return []
for base_item in items.values():
if base_item['name'] == '`?`' or base_item['id'] == '`?`':
continue
item = base_item.copy()
translator(item, lang)
lookups = {
k: extract_search_tag(dig(item, k)) for k in lookup_keys
}
if real_search == extract_search_tag(item['name']):
return [item]
for key, lookup in lookups.items():
if real_search in lookup:
possible_matches.append(item)
break
return sorted(possible_matches, key=operator.itemgetter(sort_by))
def search_troop(self, search_term, lang):
lookup_keys = [
'name',
'kingdom',
'type',
'roles',
'spell.description',
'shiny',
]
return self.search_item(search_term, lang,
items=self.troops,
lookup_keys=lookup_keys,
translator=self.translate_troop)
def translate_troop(self, troop, lang):
troop['name'] = _(troop['name'], lang, default=troop['reference_name'])
troop['description'] = _(troop['description'], lang).replace('widerbeleben',
'wiederbeleben')
troop['color_code'] = "".join(troop['colors'])
troop['rarity_title'] = _('[RARITY]', lang)
troop['raw_rarity'] = troop['rarity']
rarity_number = 1
if troop['rarity'] in TROOP_RARITIES:
rarity_number = TROOP_RARITIES.index(troop['rarity'])
troop['rarity'] = _(f'[RARITY_{rarity_number}]', lang)
troop['traits_title'] = _('[TRAITS]', lang)
troop['traits'] = self.enrich_traits(troop['traits'], lang)
troop['roles_title'] = _('[TROOP_ROLE]', lang)
troop['roles'] = [_(f'[TROOP_ROLE_{role.upper()}]', lang) for role in troop['roles']]
troop['type_title'] = _('[FILTER_TROOPTYPE]', lang)
troop['raw_types'] = troop['types']
types = [
_(f'[TROOPTYPE_{_type.upper()}]', lang) for _type in troop['types']
]
troop['type'] = ' / '.join(types)
troop['kingdom_title'] = _('[KINGDOM]', lang)
reference_name = troop['kingdom'].get('reference_name', troop['kingdom']['name'])
troop['kingdom'] = _(troop['kingdom']['name'], lang)
if self.is_untranslated(troop['kingdom']):
troop['kingdom'] = reference_name
troop['spell'] = self.translate_spell(troop['spell_id'], lang)
troop['spell_title'] = _('[TROOPHELP_SPELL0]', lang)
self.translate_traitstones(troop, lang)
troop['bonuses_title'] = _('[BONUSES]', lang)
if troop['has_shiny']:
troop['shiny'] = _('[SHINY_LEVEL_HINT_FIND_TOKENS]', lang)
troop['shiny_spell'] = self.translate_spell(troop['shiny_spell_id'], lang)
@staticmethod
def translate_traitstones(item, lang):
item['traitstones_title'] = _('[SOULFORGE_TAB_TRAITSTONES]', lang)
if 'traitstones' not in item:
item['traitstones'] = []
traitstones = [
f'{_(rune["name"], lang)} ({rune["amount"]})'
for rune in item['traitstones']
]
item['traitstones'] = traitstones
@staticmethod
def enrich_traits(traits, lang, delve_id=None):
new_traits = []
for trait in traits:
new_trait = trait.copy()
new_trait['name'] = _(trait['name'], lang)
new_trait['description'] = _(trait['description'], lang)
if delve_id is not None:
new_trait['description'] = _(f'[TREASURE_HOARD_POTION_DESC_{delve_id}]', lang)
new_traits.append(new_trait)
return new_traits
def search_kingdom(self, search_term, lang):
lookup_keys = ['name']
return self.search_item(search_term, lang, items=self.kingdoms, lookup_keys=lookup_keys,
translator=self.translate_kingdom)
def search_faction(self, search_term, lang):
lookup_keys = ['name', 'translated_colors']
items = {k: v for k, v in self.kingdoms.items() if v['underworld']}
return self.search_item(search_term, lang, items=items, lookup_keys=lookup_keys,
translator=self.translate_kingdom)
def kingdom_summary(self, lang):
kingdoms = [k.copy() for k in self.kingdoms.values() if k['location'] == 'krystara' and len(k['colors']) > 0]
for kingdom in kingdoms:
self.translate_kingdom(kingdom, lang)
return sorted(kingdoms, key=operator.itemgetter('name'))
def translate_kingdom(self, kingdom, lang):
kingdom['name'] = _(kingdom['name'], lang)
if self.is_untranslated(kingdom['name']):
kingdom['name'] = kingdom['reference_name']
kingdom['description'] = _(kingdom['description'], lang)
kingdom['punchline'] = _(kingdom['punchline'], lang)
kingdom['troop_title'] = _('[TROOPS]', lang)
kingdom['troops'] = []
for troop_id in kingdom['troop_ids']:
if troop_id not in self.troops:
continue
troop = self.troops[troop_id].copy()
self.translate_troop(troop, lang)
kingdom['troops'].append(troop)
kingdom['troops'] = sorted(kingdom['troops'], key=operator.itemgetter('name'))
kingdom['weapons_title'] = _('[WEAPONS:]', lang)
kingdom['weapons'] = sorted([
{'name': _(self.weapons[_id]['name'], lang),
'id': _id
} for _id in kingdom['weapon_ids']
], key=operator.itemgetter('name'))
kingdom['banner_title'] = _('[BANNERS]', lang)
kingdom['banner'] = self.translate_banner(self.banners[kingdom['id']], lang)
kingdom['linked_kingdom'] = None
if kingdom['linked_kingdom_id']:
kingdom['linked_kingdom'] = _(self.kingdoms[kingdom['linked_kingdom_id']]['name'], lang)
if kingdom['linked_kingdom'] and self.is_untranslated(kingdom['linked_kingdom']):
kingdom['linked_kingdom'] = None
kingdom['map'] = _('[MAPNAME_MAIN]', lang)
kingdom['linked_map'] = _('[MAPNAME_UNDERWORLD]', lang)
if kingdom['underworld']:
kingdom['map'] = _('[MAPNAME_UNDERWORLD]', lang)
kingdom['linked_map'] = _('[MAPNAME_MAIN]', lang)
if 'primary_color' in kingdom:
deed_num = COLORS.index(kingdom['primary_color'])
kingdom['deed'] = _(f'[DEED{deed_num:02d}]', lang)
color_emojis = [self.my_emojis.get(c) for c in kingdom['colors']]
kingdom['color_emojis'] = "".join(color_emojis)
kingdom['translated_colors'] = [_(f'[GEM_{c.upper()}]', lang) for c in kingdom['colors']]
kingdom['color_title'] = _('[GEM_MASTERY]', lang)
kingdom['stat_title'] = _('[STAT_BONUS]', lang)
if 'class_id' in kingdom:
kingdom['class_title'] = _('[CLASS]', lang)
kingdom['class'] = _(self.classes[kingdom['class_id']]['name'], lang)
if 'primary_stat' in kingdom:
kingdom['primary_stat'] = _(f'[{kingdom["primary_stat"].upper()}]', lang)
if 'pet' in kingdom:
kingdom['pet_title'] = _('[PET_RESCUE_PET]', lang)
kingdom['pet'] = kingdom['pet'].translations[lang]
if 'event_weapon' in kingdom:
kingdom['event_weapon_title'] = _('[FACTION_WEAPON]', lang)
kingdom['event_weapon_id'] = kingdom['event_weapon']['id']
event_weapon = kingdom['event_weapon'].copy()
self.translate_weapon(event_weapon, lang)
kingdom['event_weapon'] = event_weapon
kingdom['max_power_level_title'] = _('[KINGDOM_POWER_LEVELS]', lang)
def search_class(self, search_term, lang):
lookup_keys = ['name']
return self.search_item(search_term, lang,
items=self.classes,
translator=self.translate_class,
lookup_keys=lookup_keys)
def class_summary(self, lang):
classes = [c.copy() for c in self.classes.values()]
for c in classes:
self.translate_class(c, lang)
return sorted(classes, key=operator.itemgetter('name'))
def translate_class(self, _class, lang):
kingdom = self.kingdoms[_class['kingdom_id']]
_class['kingdom'] = _(kingdom['name'], lang, default=kingdom['reference_name'])
weapon = self.weapons[_class['weapon_id']]
_class['weapon'] = _(weapon['name'], lang)
_class['name'] = _(_class['name'], lang)
translated_trees = []
for tree in _class['talents']:
translated_talents = [
{
'name': _(talent['name'], lang),
'description': _(talent['description'], lang),
}
for talent in tree
]
translated_trees.append(translated_talents)
self.translate_traitstones(_class, lang)
_class['talents_title'] = _('[TALENT_TREES]', lang)
_class['kingdom_title'] = _('[KINGDOM]', lang)
_class['traits_title'] = _('[TRAITS]', lang)
_class['traits'] = self.enrich_traits(_class['traits'], lang)
_class['weapon_title'] = _('[WEAPON]', lang)
_class['talents'] = translated_trees
_class['trees'] = [_(f'[TALENT_TREE_{tree.upper()}]', lang) for tree in _class['trees']]
_class['type_short'] = _(f'[TROOPTYPE_{_class["type"].upper()}]', lang)
_class['type'] = _(f'[PERK_TYPE_{_class["type"].upper()}]', lang)
_class['weapon_bonus'] = _('[MAGIC_BONUS]', lang) + " " + _(
f'[MAGIC_BONUS_{COLORS.index(_class["weapon_color"])}]', lang)
def get_all_talents(self, lang):
result = []
for input_tree in self.talent_trees.values():
tree = input_tree.copy()
self.translate_talent_tree(tree, lang)
result.append(tree)
return sorted(result, key=operator.itemgetter('name'))
def search_talent(self, search_term, lang):
possible_matches = []
for tree in self.talent_trees.values():
translated_name = extract_search_tag(_(tree['name'], lang))
translated_talents = [_(talent['name'], lang) for talent in tree['talents']]
talents_search_tags = [extract_search_tag(talent) for talent in translated_talents]
real_search = extract_search_tag(search_term)
if real_search == translated_name or real_search in talents_search_tags:
result = tree.copy()
self.translate_talent_tree(result, lang)
return [result]
elif real_search in translated_name:
result = tree.copy()
self.translate_talent_tree(result, lang)
possible_matches.append(result)
elif talent_matches := [
tag for tag in talents_search_tags if real_search in tag
]:
result = tree.copy()
result['talent_matches'] = talent_matches
self.translate_talent_tree(result, lang)
possible_matches.append(result)
return sorted(possible_matches, key=operator.itemgetter('name'))
@staticmethod
def translate_talent_tree(tree, lang):
tree['talents_title'] = _('[TALENT_TREES]', lang)
tree['name'] = _(tree['name'], lang)
translated_talents = [
{
'name': _(talent['name'], lang),
'description': _(talent['description'], lang),
}
for talent in tree['talents']
]
tree['talents'] = translated_talents
tree['classes'] = [
{'id': c['id'],
'name': _(c['name'], lang)
}
for c in tree['classes']
]
def get_troops_with_trait(self, trait, lang):
return self.get_objects_by_trait(trait, self.troops, self.translate_troop, lang)
def get_classes_with_trait(self, trait, lang):
return self.get_objects_by_trait(trait, self.classes, self.translate_class, lang)
@staticmethod
def get_objects_by_trait(trait, objects, translator, lang):
result = []
for o in objects.values():
trait_codes = [trait['code'] for trait in o['traits']] if 'traits' in o else []
if trait['code'] in trait_codes:
translated_object = o.copy()
translator(translated_object, lang)
result.append(translated_object)
return result
def search_trait(self, search_term, lang):
possible_matches = []
for code, trait in self.traits.items():
translated_name = extract_search_tag(_(trait['name'], lang))
translated_description = extract_search_tag(_(trait['description'], lang))
real_search = extract_search_tag(search_term)
if real_search == translated_name:
result = trait.copy()
result['troops'] = self.get_troops_with_trait(trait, lang)
result['troops_title'] = _('[TROOPS]', lang)
result['classes'] = self.get_classes_with_trait(trait, lang)
result['classes_title'] = _('[CLASS]', lang)
if result['troops'] or result['classes']:
return self.enrich_traits([result], lang)
elif real_search in translated_name or real_search in translated_description:
result = trait.copy()
result['troops'] = self.get_troops_with_trait(trait, lang)
result['troops_title'] = _('[TROOPS]', lang)
result['classes'] = self.get_classes_with_trait(trait, lang)
result['classes_title'] = _('[CLASS]', lang)
if result['troops'] or result['classes']:
possible_matches.append(result)
return sorted(self.enrich_traits(possible_matches, lang), key=operator.itemgetter('name'))
def search_pet(self, search_term, lang):
return self.pets.search(search_term, lang)
def search_weapon(self, search_term, lang):
lookup_keys = [
'name',
'type',
'roles',
'spell.description',
]
return self.search_item(search_term, lang,
items=self.weapons,
lookup_keys=lookup_keys,
translator=self.translate_weapon)
def translate_weapon(self, weapon, lang):
weapon['name'] = _(weapon['name'], lang)
weapon['description'] = _(weapon['description'], lang)
weapon['color_code'] = "".join(sorted(weapon['colors']))
weapon['spell_title'] = _('[TROOPHELP_SPELL0]', lang)
weapon['rarity_title'] = _('[RARITY]', lang)
weapon['raw_rarity'] = weapon['rarity']
rarity_number = WEAPON_RARITIES.index(weapon['rarity'])
weapon['rarity'] = _(f'[RARITY_{rarity_number}]', lang)
weapon['spell'] = self.translate_spell(weapon['spell_id'], lang)
weapon['upgrade_title'] = _('[UPGRADE_WEAPON]', lang)
bonus_title = _('[BONUS]', lang)
upgrade_numbers = zip(weapon['armor_increase'], weapon['attack_increase'], weapon['health_increase'],
weapon['magic_increase'])
upgrade_titles = (
_('[ARMOR]', lang),
_('[ATTACK]', lang),
_('[LIFE]', lang),
_('[MAGIC]', lang),
)
upgrades = []
for upgrade in upgrade_numbers:
upgrades.extend(
{
'name': f'{upgrade_titles[i]} {bonus_title}',
'description': f'+{amount} {upgrade_titles[i]}',
}
for i, amount in enumerate(upgrade)
if amount
)
weapon['upgrades'] = upgrades + [self.translate_spell(spell['id'], lang) for spell in weapon['affixes']]
weapon['kingdom_title'] = _('[KINGDOM]', lang)
weapon['kingdom_id'] = weapon['kingdom']['id']
weapon['kingdom'] = _(weapon['kingdom']['name'], lang, default=weapon['kingdom']['reference_name'])
weapon['roles_title'] = _('[WEAPON_ROLE]', lang)
weapon['roles'] = [_(f'[TROOP_ROLE_{role.upper()}]', lang) for role in weapon['roles']]
weapon['type_title'] = _('[FILTER_WEAPONTYPE]', lang)
weapon['type'] = _(f'[WEAPONTYPE_{weapon["type"].upper()}]', lang)
weapon['has_mastery_requirement_color'] = False
if weapon['requirement'] < 1000:
weapon['requirement_text'] = _('[WEAPON_MASTERY_REQUIRED]', lang) + \
str(weapon['requirement'])
weapon['has_mastery_requirement_color'] = True
elif weapon['requirement'] == 1000:
weapon['requirement_text'] = _('[WEAPON_AVAILABLE_FROM_CHESTS_AND_EVENTS]', lang)
elif weapon['requirement'] == 1002:
_class = _(weapon.get('class', '[NO_CLASS]'), lang)
weapon['requirement_text'] = _('[CLASS_REWARD_TITLE]', lang) + f' ({_class})'
elif weapon['requirement'] == 1003:
weapon['requirement_text'] = _('[SOULFORGE_WEAPONS_TAB_EMPTY_ERROR]', lang)
if weapon.get('event_faction'):
weapon['requirement_text'] += ' (' + _(f'[{weapon["event_faction"]}_NAME]', lang) + ' ' + _(
'[FACTION_WEAPON]', lang) + ')'
def search_affix(self, search_term, lang):
real_search = extract_search_tag(search_term)
results = {}
for weapon in self.weapons.values():
my_weapon = weapon.copy()
self.translate_weapon(my_weapon, lang)
affixes = [affix for affix in my_weapon['upgrades'] if 'cost' in affix]
for affix in affixes:
search_name = extract_search_tag(affix['name'])
search_desc = extract_search_tag(affix['description'])
if real_search == search_name \
or real_search == search_desc \
or real_search in search_name \
or real_search in search_desc:
if affix['name'] in results:
results[affix['name']]['weapons'].append(my_weapon)
results[affix['name']]['num_weapons'] += 1
else:
results[affix['name']] = affix.copy()
results[affix['name']]['weapons_title'] = _('[SOULFORGE_TAB_WEAPONS]', lang)
results[affix['name']]['weapons'] = [my_weapon]
results[affix['name']]['num_weapons'] = 1
for name, affix in results.items():
if real_search == extract_search_tag(name):
return [affix]
return sorted(results.values(), key=operator.itemgetter('name'))
def search_traitstone(self, search_term, lang):
return self.search_item(search_term, lang,
items=self.traitstones,
lookup_keys=['name'],
translator=self.translate_traitstone)
def translate_traitstone(self, traitstone, lang):
troops = []
for troop_id in traitstone['troop_ids']:
amount = sum(troop['amount']
for troop in self.troops[troop_id]['traitstones']
if troop['id'] == traitstone['id'])
troops.append([_(self.troops[troop_id]['name'], lang), amount])
traitstone['troops'] = sorted(troops, key=operator.itemgetter(1), reverse=True)
classes = []
for class_id in traitstone['class_ids']:
amount = sum(_class['amount'] for _class in self.classes[class_id]['traitstones']
if _class['id'] == traitstone['id'])
classes.append([_(self.classes[class_id]['name'], lang), amount])
traitstone['classes'] = classes
kingdoms = [
_(self.kingdoms[int(kingdom_id)]['name'], lang)
for kingdom_id in traitstone['kingdom_ids']
]
if not traitstone['kingdom_ids']:
kingdoms.append(_('[ALL_KINGDOMS]', lang))
traitstone['kingdoms'] = kingdoms
traitstone['name'] = _(traitstone['name'], lang)
traitstone['troops_title'] = _('[TROOPS]', lang)
traitstone['classes_title'] = _('[CLASS]', lang)
traitstone['kingdoms_title'] = _('[KINGDOMS]', lang)
def translate_spell(self, spell_id, lang):
spell = self.spells[spell_id]
magic = _('[MAGIC]', lang)
description = self.translate_spell_description(spell['description'], lang)
for i, (multiplier, amount) in enumerate(spell['effects'], start=1):
spell_amount = f' + {amount}' if amount else ''
divisor, multiplier_text = self.translate_spell_multiplier(multiplier)
damage = f'[{multiplier_text}{magic}{divisor}{spell_amount}]'
number_of_replacements = len(re.findall(r'\{\d}', description))
has_half_replacement = len(spell['effects']) == number_of_replacements - 1
if '{2}' in description and has_half_replacement:
multiplier *= 0.5
amount *= 0.5
if amount == int(amount):
amount = int(amount)
half_damage = f'[{multiplier} ⨯ {magic}{divisor} + {amount}]'
description = description.replace('{1}', half_damage)
description = description.replace('{2}', damage)
else:
description = description.replace(f'{{{i}}}', damage)
boost = self.calculate_boost(spell)
description = f'{description}{boost}'
return {
'name': _(spell['name'], lang),
'cost': spell['cost'],
'description': description,
}
def translate_spell_multiplier(self, multiplier):
multiplier_text = ''
if multiplier > 1:
if multiplier == int(multiplier):
multiplier_text = f'{multiplier:.0f} ⨯ '
else:
multiplier_text = f'{multiplier} ⨯ '
divisor = ''
if multiplier < 1:
number = int(round(1 / multiplier))
divisor = f' / {number}'
return divisor, multiplier_text
@staticmethod
def calculate_boost(spell):
boost = ''
if spell['boost']:
if spell['boost'] > 100:
boost = f' [x{int(round(spell["boost"] / 100))}]'
elif spell['boost'] != 1:
boost = f' [{100 / spell["boost"]:0.0f}:1]'
return boost
def translate_spell_description(self, description, lang):
description = _(description, lang)
if description.startswith('&&'):
description = description \
.replace('&&', _('[CHOICE_CHOOSE_ONE_DESC]', lang), 1) \
.replace('&&', _('[OR_CAPITALISED]', lang))
return description
def translate_banner(self, banner, lang):
result = {
'name': _(banner['name'], lang),
'kingdom': _(self.kingdoms[banner['id']]['name'], lang),
'colors': [(_(c[0], 'en').lower(), c[1]) for c in banner['colors'] if c[1]],
'filename': banner['filename'],
}
colors_shorthand = []
for color, amount in result['colors']:
if amount > 0:
colors_shorthand.append(color[0].upper())
else:
colors_shorthand.append(color[0].lower())
result['colors_shorthand'] = ''.join(colors_shorthand)
if not result['colors']:
result['available'] = _('[AVAILABLE_FROM_KINGDOM]', lang).replace('%1', _(f'[{banner["id"]}_NAME]', lang))
return result
def get_event_kingdoms(self, lang):
today = datetime.date.today()
start = today + datetime.timedelta(days=-today.weekday(), weeks=1)
result = self.guess_weekly_kingdom_from_troop_spoilers(lang)
prediction = ''
for kingdom_id in self.event_kingdoms:
end = start + datetime.timedelta(days=7)
if kingdom_id != 0:
event_data = {
'start': start,
'end': end,
'kingdom': _(self.kingdoms[kingdom_id]['name'], lang,
default=self.kingdoms[kingdom_id]['reference_name']) + prediction,
}
result[start] = event_data
else:
prediction = ' *'
start = end
return sorted(result.values(), key=operator.itemgetter('start'))
def guess_weekly_kingdom_from_troop_spoilers(self, lang):
result = {}
latest_date = datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc)
for spoiler in self.spoilers:
if spoiler['type'] == 'troop' \
and spoiler['date'].weekday() == 0 \
and spoiler['date'] > latest_date:
troop = self.troops[spoiler['id']]
if troop['rarity'] == 'Mythic':
continue
kingdom = troop['kingdom']
if not kingdom.get('name') and not kingdom.get('reference_name'):
continue
if kingdom['id'] in self.event_kingdoms:
continue
result[spoiler['date'].date()] = {
'start': spoiler['date'].date(),
'end': spoiler['date'].date() + datetime.timedelta(days=7),
'kingdom': _(kingdom['name'], lang,
default=kingdom['reference_name']) + ' *',
}
latest_date = spoiler['date']
return result
def get_events(self, lang):
today = datetime.date.today()
return [
self.translate_event(e, lang)
for e in self.events
if today <= e['start']
]
def _extend_event_extra_info(self, entry, lang):
event_type = entry['type']
gacha = entry['gacha']
gacha_pools = {
'[BOUNTY]': self.troops,
'[HIJACK]': self.troops,
'[DELVE_EVENT]': self.troops,
'[RAIDBOSS]': self.troops,
'[TOWER_OF_DOOM]': self.troops,
'[CLASS_EVENT]': self.classes,
}
gacha_pool = gacha_pools.get(event_type)
if gacha_pool and gacha and gacha in gacha_pool:
item = gacha_pool[gacha]
return _(item['name'], lang, default=item.get('reference_name', item['name']))
elif event_type == '[PETRESCUE]' and gacha and gacha in self.pets:
return self.pets[gacha][lang].name
elif event_type == '[HIJACK]' and entry['troops']:
troops = [self.troops[troop] for troop in entry['troops']]
return ', '.join(_(troop['name'], lang, default=troop['reference_name']) for troop in troops)
return ''
def translate_event(self, event, lang):
entry = event.copy()
entry['extra_info'] = self._extend_event_extra_info(entry, lang)
if entry['type'] == '[INVASION]' and entry['gacha'] and entry['gacha'] in self.troops:
troop = self.troops[entry['gacha']]
troop_name = _(troop['name'], lang)
entry['kingdom_id'] = troop.get('kingdom_id', '`?`')
troop_types = [_(f'[TROOPTYPE_{tt.upper()}]', lang) for tt in troop['types']]
entry['extra_info'] = f'{troop_name} ({", ".join(troop_types)})'
elif entry['type'] in ('[WEEKLY_EVENT]', '[RARITY_5]') and entry['gacha'] and entry['gacha'] in self.troops:
troop = self.troops[entry['gacha']]
troop_name = _(troop['name'], lang, default=troop['reference_name'])
kingdom = _(self.kingdoms[entry['kingdom_id']]['name'], lang,
default=self.kingdoms[entry['kingdom_id']]['reference_name'])
entry['extra_info'] = f'{troop_name} ({kingdom})'
entry['kingdom'] = kingdom
elif entry['type'] == '[VAULT]':
entry['kingdom_id'] = 3038
if entry['kingdom_id']:
kingdom = self.kingdoms[entry['kingdom_id']]
entry['kingdom'] = _(kingdom['name'], lang, default=kingdom['reference_name'])
locale = translations.LANGUAGE_CODE_MAPPING.get(lang, lang)
locale = translations.LOCALE_MAPPING.get(locale, 'en_GB') + '.UTF8'
with calendar.different_locale(locale):
entry['formatted_start'] = entry['start'].strftime(WEEK_DAY_FORMAT)
entry['start_day'] = entry['start'].strftime('%A')
entry['formatted_end'] = entry['end'].strftime(WEEK_DAY_FORMAT)
entry['end_day'] = entry['end'].strftime('%A')
entry['raw_type'] = entry['type']
entry['type'] = _(entry['type'], lang)
if self.is_untranslated(entry['type']) and entry['names']:
entry['type'] = entry['names'][translations.LOCALE_MAPPING[lang].replace('en_GB', 'en_US')]
return entry
def get_campaign_tasks(self, lang, _filter=None):
result = {'heading': f'{_("[CAMPAIGN]", lang)}: {_("[TASKS]", lang)}'}
tiers = ['bronze', 'silver', 'gold']
result['campaigns'] = {
f'[MEDAL_LEVEL_{i}]': [self.translate_campaign_task(task, lang) for task in self.campaign_tasks[tier]]
for i, tier in reversed(list(enumerate(tiers))) if _filter is None or tier.lower() == _filter.lower()
}
formatted_start, start_date = get_next_monday_in_locale(date=None, lang=lang)
result['has_content'] = any(len(c) > 0 for c in result['campaigns'].values())
result['background'] = f'Background/{self.campaign_tasks["kingdom"]["filename"]}_full.png'
result['gow_logo'] = 'Atlas/gow_logo.png'
kingdom_filebase = self.campaign_tasks['kingdom']['filename']
result['kingdom_logo'] = f'Troopcardshields_{kingdom_filebase}_full.png'
result['kingdom'] = _(self.campaign_tasks['kingdom']['name'], lang)
result['raw_date'] = start_date
result['date'] = formatted_start
result['lang'] = lang
result['texts'] = {
'campaign': _('[CAMPAIGN]', lang),
'team': _('[LITE_CHAT_TEAM_START]', lang),
}
return result
def get_reroll_tasks(self, lang, _filter=None):
tiers = ['bronze', 'silver', 'gold']
return {
f'[MEDAL_LEVEL_{i}]': [
self.translate_campaign_task(task, lang)
for task in self.reroll_tasks[tier]
]
for i, tier in reversed(list(enumerate(tiers)))
if _filter is None or tier.lower() == _filter.lower()
}
def __task_name_replacements(self, task, color, lang):
replacements = {
'{WeaponType}': '[WEAPONTYPE_{c:u}]',
'{Kingdom}': '[{d:u}_NAME]',
'{Banner}': '[{c:u}_BANNERNAME]',
'{Class}': '[HEROCLASS_{c:l}_NAME]',
'{Color}': f'[GEM_{color}]',
'{TroopType}': '[TROOPTYPE_{value1:u}]',
'{Troop}': '{{[{value1}][name]}}',
'{Value0}': task['value0'],
'{Value1}': task['value1'],
'{0}': '{x}',
'{1}': task['c'],
'{2}': '{x} {y}',
}
for before, after in replacements.items():
if before in task['title'] or before in task['name']:
translated = _(after.format(**task).format(self.troops), lang, plural=task['plural'])
if '`?`' in translated:
translated = '`?`'
task['title'] = task['title'].replace(before, translated)
task['name'] = task['name'].replace(before, translated)
def translate_campaign_task(self, task, lang):
new_task = task.copy()
color_code = int(new_task['value1']) if new_task['value1'].isdigit() else 666
color = COLORS[color_code].upper() if color_code < len(COLORS) else '`?`'
if isinstance(new_task.get('y'), str):
new_task['y'] = _(f'[{new_task["y"].upper()}]', lang)
new_task['plural'] = int(new_task.get('x', 1)) != 1
new_task['title'] = _(new_task['title'], lang, plural=new_task['plural'])
new_task['name'] = _(new_task["name"], lang, plural=new_task['plural'])
if '{0}' not in new_task['name'] and '{2}' not in new_task['name']:
new_task['name'] = f'{task["x"]}x ' + new_task['name']
self.__task_name_replacements(new_task, color, lang)
new_task['name'] += self.__task_solution_location(new_task, task, color, lang)
return new_task
def __task_solution_location(self, new_task, task, color, lang):
where = ''
if new_task['value1'] == '`?`':
pass
elif task['name'] == '[TASK_KILL_TROOP_COLOR]' and color != '`?`':
color_kingdoms = self.get_color_kingdoms(lang)
target_kingdom = color_kingdoms[color.lower()]['name']
where = f' --> {target_kingdom}'
elif task['name'] == '[TASK_KILL_TROOP_ID]':
target_kingdom = _(self.troops[int(task['value1'])]['kingdom']['name'], lang)
pvp = _('[PVP]', lang)
weekly_event = _('[WEEKLY_EVENT]', lang)
where = f' --> {target_kingdom} / {pvp} / {weekly_event}'
elif task['name'] == '[TASK_KILL_TROOP_TYPE]':
troop_type_kingdoms = dict(self.get_type_kingdoms(lang))
troop_type = _(f'[TROOPTYPE_{task["value1"].upper()}]', lang)
target_kingdom = troop_type_kingdoms[troop_type]['name']
where = f' --> {target_kingdom}'
elif task['name'] == '[TASK_KILL_TREASURE_GNOMES]':
vault = _(self.kingdoms[3038]['name'], lang)
where = f' --> {vault}'
return where
def get_spoilers(self, lang):
spoilers = []
now = datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc)
near_term_spoilers = [s for s in self.spoilers if now <= s['date'] <= now + datetime.timedelta(days=180)]
for spoiler in near_term_spoilers:
if translated := self.translate_spoiler(spoiler, lang):
spoilers.append(translated)
return spoilers
def translate_spoiler(self, spoiler, lang):
# this is transitional until all new models are in place.
if spoiler['type'] in ['pet']:
if item := getattr(self, spoiler['type'] + 's').get(spoiler['id']):
entry = item[translations.LANGUAGE_CODE_MAPPING.get(lang, lang)].data.copy()
else:
return
else:
entry = getattr(self, spoiler['type'] + 's').get(spoiler['id'], {}).copy()
if not entry:
return None
entry['name'] = _(entry['name'], lang)
if self.is_untranslated(entry['name']):
entry['name'] = entry.get('reference_name', entry['name'])
entry['type'] = spoiler['type']
entry['date'] = spoiler['date'].date()
entry['event'] = _('[GLOG_EVENT]', lang) + ': ' if entry.get('event') else ''
if 'rarity' in entry:
entry['rarity_title'] = _('[RARITY]', lang)
if entry['rarity'] in TROOP_RARITIES:
rarity_number = TROOP_RARITIES.index(entry['rarity'])
entry['rarity'] = _(f'[RARITY_{rarity_number}]', lang)
if kingdom_id := entry.get('kingdom_id'):
kingdom = self.kingdoms[kingdom_id]
entry['kingdom'] = _(kingdom['name'], lang)
if self.is_untranslated(entry['kingdom']):
entry['kingdom'] = kingdom['reference_name']
return entry
def get_soulforge(self, lang):
title = _('[SOULFORGE]', lang)
craftable_items = {}
for category, recipes in self.soulforge.items():
recipe_type = _(category, lang)
craftable_items[recipe_type] = [self.translate_recipe(r, lang) for r in recipes]
return title, craftable_items
def get_summons(self, lang):
title = _('[SUMMONING_STONE_MENU_HEADING]', lang)
result = {}
for stone, contents in self.summons.items():
stone_name = _(stone, lang)
troops = [
{
'name': _(self.troops[troop['troop_id']]['name'], lang),
'rarity': self.troops[troop['troop_id']]['rarity'],
'count': troop['count'],
'id': troop['troop_id']
}
for troop in contents
]
result[stone_name] = troops
return title, result
@staticmethod
def translate_recipe(recipe, lang):
new_recipe = recipe.copy()
new_recipe['name'] = _(recipe['name'], lang)
rarity_number = WEAPON_RARITIES.index(new_recipe['rarity'])
new_recipe['rarity_number'] = rarity_number
new_recipe['raw_rarity'] = new_recipe['rarity']
new_recipe['rarity'] = _(f'[RARITY_{rarity_number}]', lang)
return new_recipe
@staticmethod
def translate_categories(categories, lang):
def try_different_translated_versions_because_devs_are_stupid(cat):