import itertools import json import math from copy import deepcopy from fighting.config import config from fighting.types import BonusTypes, ArmorClasses from fighting import constants class Fighting(): def __init__(self, data, nums): self.data = data self.nums = nums with open(config.bonus_data_file, 'r') as f: self.bonus_data = json.load(f) def list_units(self): return list(self.nums.keys()) @staticmethod def _calculate_hp_bonus(hp, bonuses): for b in bonuses: b_amount, _ = b.values() if 'Amount' in b.keys(): hp += b_amount else: hp *= b_amount hp = int(hp) return hp @staticmethod def _calculate_bonus(orig, bonuses, attack=False): for b in bonuses: b_amount, b_clss = b.values() used = False for iorig in range(len(orig)): _, clss = orig[iorig].values() if clss == b_clss: if 'Amount' in b.keys(): orig[iorig]['Amount'] += b_amount else: orig[iorig]['Amount'] *= b_amount orig[iorig]['Amount'] = int(orig[iorig]['Amount']) used = True if attack and not used: # bonus can add an attack but should not add an armor type orig.append(b) @staticmethod def generate_bonus_with_value(amount, clss): return {"Amount": amount, "Class": clss} @staticmethod def generate_bonus_with_percent(amount, clss): return {"Percent": amount, "Class": clss} def get_bonuses_from_names(self, clss, names): bonuses = [] if len(names) > 0: for name in names: bonuses.extend(self.bonus_data[clss.value][name]) return bonuses @staticmethod def get_possible_bonus_names_for_fight(attacker, defender): ''' Returns the bonuses as a tuple of lists. The first list contains attack bonuses, the second armor bonuses, and the third hp bonuses. ''' attack_bonuses = [] armor_bonuses = [] hp_bonuses = [] for bonus, names in constants.bonuses['attack'].items(): if bonus in ['Parthian Tactics']: if (attacker in names['attackers'] and defender in names['defenders']): attack_bonuses.append(bonus) elif attacker in names: attack_bonuses.append(bonus) for bonus, names in constants.bonuses['armor'].items(): if defender in names: armor_bonuses.append(bonus) for bonus, names in constants.bonuses['hp'].items(): if defender in names: hp_bonuses.append(bonus) return (attack_bonuses, armor_bonuses, hp_bonuses) def _remove_names_not_in_list(names, valid_names): for b in names: if b not in valid_names: names.remove(b) def _make_valid_bonus_names(attacker, defender, attack_bonus_names, armor_bonus_names, hp_bonus_names): all_valid_names = Fighting.get_possible_bonus_names_for_fight(attacker, defender) Fighting._remove_names_not_in_list(attack_bonus_names, all_valid_names[0]) Fighting._remove_names_not_in_list(armor_bonus_names, all_valid_names[1]) Fighting._remove_names_not_in_list(hp_bonus_names, all_valid_names[2]) def get_bonus_range(attacker, defender, attack_type, extra_attack_bonuses, extra_armor_bonuses, hp_bonuses): ''' Determines the appropriate "bonus range" for an attacker-defender pair. The poorly-named "bonus range" is the set of all possible (attack - defense) values when considering all blacksmith research and any extra research described in the `extras` argument. An example of "extra" research would be Parthian Tactics. For example, you can compute a single "bonus" (i.e., one element of the "bonus range") as follows. If there are no `extra` bonuses, and if the attacker has Iron Casting (i.e., +2 attack) and the defender has Scale Barding Armor (i.e., +1 defense), then the "bonus" for that combination is 2 (attack) - 1 (defense) = 1 (bonus). By considering bonus as a single number in this way, we do not need to consider all possible combinations of attack and armor blacksmith research. ''' possible_attack = constants.ranges[attack_type]['attack'] if attacker == 'Villager': attack_range = possible_attack['villager'] elif 'Parthian Tactics' in extra_attack_bonuses: attack_range = possible['parthian tactics'] elif attacker in constants.siege_no_chemistry: attack_range = possible_attack['siege'] elif attacker in constants.siege_with_chemistry: attack_range = possible_attack['siege (chemistry)'] else: attack_range = possible_attack['standard'] possible_armor = constants.ranges[attack_type]['armor'] if 'Loom' in hp_bonuses: armor_range = possible_armor['villager (loom)'] elif defender == 'Villager': armor_range = possible_armor['villager'] elif 'Parthian Tactics' in extra_armor_bonuses: armor_range = possible_armor['parthian tactics'] elif 'Gambesons' in extra_armor_bonuses: armor_range = possible_armor['gambesons'] elif defender in constants.siege: armor_range = possible_armor['siege'] else: armor_range = possible_armor['standard'] all_range = set() for attack in attack_range: for armor in armor_range: all_range.add(attack + armor) return sorted(list(all_range)) def get_attack_type(self, attacker_id): attacks = self.data[attacker_id]['Attacks'] val = 0 for attack in attacks: if attack['Class'] == ArmorClasses.MELEE: val = attack['Amount'] if val > 0: return ArmorClasses.MELEE else: return ArmorClasses.PIERCE @staticmethod def generate_notes(attack_bonus_names, armor_bonus_names, hp_bonus_names): notes = '' if len(hp_bonus_names) > 0: notes += f'with {" and ".join(hp_bonus_names)} applied. ' return notes @staticmethod def _powerset(elements): for size in range(len(elements) + 1): for combo in itertools.combinations(elements, size): yield list(combo) @staticmethod def generate_all_combinations(attack, armor, hp): ''' Generates all combinations of bonuses, but assumes that most attack and armor bonuses are always active. This is done because those bonuses are already accounted for in the "bonus ranges" if using generate_all_fight_results. If you are not using that function, it may not make sense to call this one. Note: avoids nonsensical combinations such as having Loom for HP but not Loom for armor. ''' armor = deepcopy(armor) for b in armor: if b in hp: armor.remove(b) attack_combos = [deepcopy(attack)] armor_combos = [armor] hp_combos = Fighting._powerset(hp) all_combos = itertools.product(attack_combos, armor_combos, hp_combos) return [Fighting._make_valid_combination(*val) for val in all_combos] @staticmethod def _make_valid_combination(attack, armor, hp): for name in hp: if name in constants.bonuses['armor'].keys(): armor.append(name) return (attack, armor, hp) def calculate_hits_to_kill(self, attacker, defender, attack_bonuses=[], armor_bonuses=[], time_to_kill=False, hp_bonuses=[]): ''' Calculates hits to kill for a single attacker and defender with one set of bonuses (i.e., no looping over attackers, defenders, or bonuses). ''' # Get base values attacks = deepcopy(self.data[self.nums[attacker]]['Attacks']) armors = deepcopy(self.data[self.nums[defender]]['Armours']) hp = self.data[self.nums[defender]]['HP'] # Apply any bonuses from technologies or civilizations Fighting._calculate_bonus(attacks, attack_bonuses, attack=True) Fighting._calculate_bonus(armors, armor_bonuses) hp = Fighting._calculate_hp_bonus(hp, hp_bonuses) damage = 0 for a in attacks: amount, clss = a.values() for d in armors: d_amount, d_clss = d.values() if clss == d_clss: damage += max(0, amount - d_amount) damage = max(1, damage) hits = math.ceil(hp/damage) if time_to_kill: reload = self.data[self.nums[attacker]]['ReloadTime'] delay = self.data[self.nums[attacker]]['AttackDelaySeconds'] hits = delay + (hits - 1)*reload hits = round(hits, config.rounding_digits) return hits def generate_fight_results(self, attacker, defender, notes='', extra_attack_bonuses=[], extra_armor_bonuses=[], hp_bonuses=[], time_to_kill=False, verbose=False): ''' For a single attacker and defender, loops over all values of (attack - defense) for blacksmith bonuses and Chemistry. Accepts extra bonuses (e.g., Bloodlines), but the values of those extra bonuses are held fixed for the duration of this function. Does not loop over attackers, defenders, or any non-blacksmith (+Chemistry) bonuses. ''' armor_class = self.get_attack_type(self.nums[attacker]) bonus_range = Fighting.get_bonus_range(attacker, defender, armor_class, extra_attack_bonuses, extra_armor_bonuses, hp_bonuses) if verbose: print(f'{attacker} attacking {defender}') if len(notes) > 0: print(notes) print('--------------------------------') results = {'hits': {}} for i in bonus_range: attack_bonuses = deepcopy(extra_attack_bonuses) armor_bonuses = deepcopy(extra_armor_bonuses) b = self.generate_bonus_with_value(abs(i), armor_class) if i < 0: armor_bonuses.append(b) else: attack_bonuses.append(b) hits = self.calculate_hits_to_kill(attacker, defender, attack_bonuses=attack_bonuses, armor_bonuses=armor_bonuses, hp_bonuses=hp_bonuses, time_to_kill=time_to_kill) results['hits'][i] = hits if verbose: print(f'Net attack bonus: {i}\thits: {hits}') results['notes'] = notes return results def generate_fight_results_from_names(self, attacker, defender, attack_bonus_names=[], armor_bonus_names=[], hp_bonus_names=[], time_to_kill=False, verbose=False): ''' Simple convenience wrapper for generate_fight_results. Accepts non-blacksmith bonuses' names (e.g., 'Bloodlines') and obtains the corresponding bonuses in the form expected by generate_fight_results (i.e., lists of dictionaries). This function does not loop over anything itself, although generate_fight_results, which this function calls, has its own looping as described in its documentation. Note: when using this wrapper for generate_fight_results, any extra attack and armor upgrades are not actually applied as bonuses. It is assumed that they are already incorporated into the provided bonus range. ''' Fighting._make_valid_bonus_names(attacker, defender, attack_bonus_names, armor_bonus_names, hp_bonus_names) hp_bonuses = self.get_bonuses_from_names(BonusTypes.HP, hp_bonus_names) notes = Fighting.generate_notes(attack_bonus_names, armor_bonus_names, hp_bonus_names) return self.generate_fight_results(attacker, defender, notes=notes, extra_attack_bonuses=[], extra_armor_bonuses=[], hp_bonuses=hp_bonuses, time_to_kill=time_to_kill, verbose=verbose) def generate_all_fight_results(self): ''' For a given group of units (specified implicitly by the nums argument, which was itself probably generated from a namelist), determines the number of hits for each unit to kill each other unit. For each pair, this function loops over all possible values of blacksmith research and any other relevant non-blacksmith bonuses found in fighting.constants.bonuses. ''' all_results = {} for attacker, defender in itertools.product(self.nums.keys(), self.nums.keys()): fight_results = [] bonus_names = Fighting.get_possible_bonus_names_for_fight(attacker, defender) combos = Fighting.generate_all_combinations(*bonus_names) for combo in combos: results = self.generate_fight_results_from_names(attacker, defender, attack_bonus_names=combo[0], armor_bonus_names=combo[1], hp_bonus_names=combo[2], time_to_kill=False, verbose=False) fight_results.append(results) all_results[(attacker, defender)] = fight_results return all_results