def migrate(meta, version, target_version):
    if version == "0.02a" and version != target_version:
        for q in session["quests"]:
            if not q["complete"]:
                q["completedTasks"] = 0
                print("Reset quest completion")

        handle_quest_progress(
            meta, lambda task, progress, i, extra, *args: zero_yield(extra))

        session['user_object']["userInfo"]["player"]["expansions"]["data"] = [
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
        ]
        unlock_expansion(156)
        unlock_expansion(157)
        unlock_expansion(181)
        unlock_expansion(182)
        unlock_expansion(206)
        unlock_expansion(207)

        version = "0.03a"
        session['save_version'] = version
    if version == "0.03a" and version != target_version:
        create_backup("Update to 0.04a")
        version = "0.04a"
        session['save_version'] = version
    if version == "0.04a" and version != target_version:
        create_backup("Update to 0.05a")
        version = "0.05a"
        session['save_version'] = version
    if version == "0.05a" and version != target_version:  # upcoming 0.06
        # create_backup("Update to 0.06a") # for release
        # version = "0.06a"
        #
        session['user_object']["experiments"]["empire_decorations_master"] = 2
def handle_win(baddie_strengths, meta, params):
    if sum(baddie_strengths) == 0:
        print("Enemy defeated")
        session["battle"] = None
        handle_quest_progress(meta, progress_action("fight"))
        map_name, current_island, map_item = get_current_island(params)
        if current_island is not None:
            handle_quest_progress(
                meta,
                all_lambda(
                    progress_action("islandWin"),
                    progress_parameter_equals("_island", str(current_island))))
            do_rewards("Campaign",
                       map_item['island'][current_island].get("reward"), meta)
            do_rewards("Liberty Bond", {
                "_type": "item",
                "_item": "xk01",
                "_count": "1"
            }, meta)

            next_island_id = map_item['island'][current_island].get('-unlocks')
            if next_island_id is not None:
                print("Activating next island", map_name, next_island_id)
                set_active_island_by_map(map_name, int(next_island_id))
            else:
                print("Current island group finished", map_name)
                set_active_island_by_map(map_name, len(map_item['island']))
Beispiel #3
0
def migrate(meta, version, target_version):
    if version == "0.02a" and version != target_version:
        for q in session["quests"]:
            if not q["complete"]:
                q["completedTasks"] = 0
                print("Reset quest completion")

        handle_quest_progress(
            meta, lambda task, progress, i, extra, *args: zero_yield(extra))

        session['user_object']["userInfo"]["player"]["expansions"]["data"] = [
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
        ]
        unlock_expansion(156)
        unlock_expansion(157)
        unlock_expansion(181)
        unlock_expansion(182)
        unlock_expansion(206)
        unlock_expansion(207)

        version = "0.03a"
        session['save_version'] = version
    if version == "0.03a" and version != target_version:
        create_backup("Update to 0.04a")
        version = "0.04a"
        session['save_version'] = version
    if version == "0.04a" and version != target_version:
        create_backup("Update to 0.05a")
        version = "0.05a"
        session['save_version'] = version
    if version and version.startswith(
            "0.05a") and version != target_version:  # upcoming 0.06
        create_backup("Update to 0.06a")
        version = "0.06a"
        govt_fixer()
        session['user_object']["experiments"]["empire_decorations_master"] = 2
        session['user_object']["experiments"]["empire_doober_pickup"] = 3
        session['user_object']["experiments"]["empires_consumable_2"] = 3
        session['user_object']["experiments"][
            "empire_research_shield_upgrade"] = 2
        session['user_object']["experiments"]["empires_support_units"] = 5
        session['user_object']["experiments"][
            "empire_buildable_zrig_master"] = 3
        session['save_version'] = version
    if version and version.startswith(
            "0.06a") and version != target_version:  # upcoming 0.07
        # create_backup("Update to 0.07a") # for release
        pass
def do_state_rewards(state, reference_item, meta, playback_tend=False):
    player = session['user_object']["userInfo"]["player"]
    player['xp'] += int(state.get('-xp', 0))
    energy = int(state.get('-energy', 0))
    if playback_tend:
        energy = max(energy, 0);
    player['energy'] += energy
    player['cash'] += int(state.get('-cash', 0))
    player['socialXpGood'] += int(state.get('-socialXpGood', 0))
    player['socialXpBad'] += int(state.get('-socialXpBad', 0))

    if  str(state.get('-elementZ',0)) != '0':
        if not state.get('-elementZ',0) in player["inventory"]["items"]:
            player["inventory"]["items"][state.get('-elementZ',0)] = 1
        else:
            player["inventory"]["items"][state.get('-elementZ', 0)] +=1

    world = session['user_object']["userInfo"]["world"]
    resources = world['resources']
    resources['coins'] += int(state.get('-coins', 0))
    resources['energy'] += energy  #which one?
    resources['oil'] += int(state.get('-oil', '0').split('|')[0])
    resources['wood'] += int(state.get('-wood', '0').split('|')[0])

    resource_order = world['resourceOrder']
    resources[resource_order[0]] += int(state.get('-rare', '0').split('|')[0])
    resources[resource_order[0]] += int(state.get('-nrare0', '0').split('|')[0])
    resources[resource_order[1]] += int(state.get('-nrare1', '0').split('|')[0])
    resources[resource_order[2]] += int(state.get('-nrare2', '0').split('|')[0])
    resources[resource_order[3]] += int(state.get('-nrare3', '0').split('|')[0])
    resources[resource_order[4]] += int(state.get('-nrare4', '0').split('|')[0])
    resources["aluminum"] += int(state.get('-aluminum', '0').split('|')[0])
    resources["copper"] += int(state.get('-copper', '0').split('|')[0])
    resources["gold"] += int(state.get('-gold', '0').split('|')[0])
    resources["iron"] += int(state.get('-iron', '0').split('|')[0])
    resources["uranium"] += int(state.get('-uranium', '0').split('|')[0])

    item_inventory = player["inventory"]["items"]
    if int(state.get('-buildable', '0')):
        if reference_item:
            item_inventory[reference_item] = item_inventory.get(reference_item, 0) + 1
            print("Adding", reference_item, "to inventory")
        else:
            print("ERROR: Buildable present but no reference item")

    research = world["research"]
    if int(state.get('-upgrade', '0')):
        if reference_item:
            if reference_item.split(":")[0] not in research.get(reference_item.split(":")[1],[]):
                research[reference_item.split(":")[1]] = research.get(reference_item.split(":")[1],[])  + [reference_item.split(":")[0]]
                print("Adding", reference_item, "to research")
                handle_quest_progress(meta, progress_upgrades_count())
            else:
                print("ERROR: Upgrade already added")
        else:
            print("ERROR: Upgrade present but no reference item")

    level_cash = 0
    levels_count = 0
    levels = [level for level in game_settings['settings']['levels']['level'] if
              int(level["-num"]) > player['level'] and int(level["-requiredXP"]) <= player['xp']]
    for level in levels:
        energy_cap = ([e['-cap'] for e in game_settings['settings']['energycaps']['energycap'] if e['-level'] == level["-num"]] + [46])[0]
        print("Level increased to", level["-num"], "New energy:", energy_cap)
        player['level'] = int(level["-num"])
        player['energy'] = int(energy_cap)
        player['energyMax'] = int(energy_cap)
        levels_count += 1
        if "reward" in level and level["reward"]["-type"] == "cash":
            player['cash'] += int(level["reward"]["-count"])
            level_cash += int(level["reward"]["-count"])
        create_backup("Level " + level["-num"])

    log_rewards = ", ".join(
        [label + " " + ("+" if int(increment) > 0 else "") + str(increment) + " (" + str(total) + ")" for
         (label, increment, total)
         in
         [("xp:", state.get('-xp', '0'), player['xp']),
          ("energy:", str(energy), player['energy']),
          ("coins:", state.get('-coins', '0'), resources['coins']),
          ("oil:", state.get('-oil', '0'), resources['oil']),
          ("wood:", state.get('-wood', '0'), resources['wood']),
          ("cash:", state.get('-cash', '0'), player['cash']),
          ("cash (level):", str(level_cash), player['cash']),
          ("levels:", str(levels_count), player['level']),
          ("socialXpGood:", state.get('-socialXpGood', '0'), player['socialXpGood']),
          ("socialXpBad:", state.get('-socialXpBad', '0'), player['socialXpBad']),
          ("buildable:", state.get('-buildable', '0'), sum(item_inventory.values())),
          (resource_order[0] + ":", state.get('-rare', '0'), resources[resource_order[0]]),
          (resource_order[0] + ":", state.get('-nrare0', '0'), resources[resource_order[0]]),
          (resource_order[1] + ":", state.get('-nrare1', '0'), resources[resource_order[1]]),
          (resource_order[2] + ":", state.get('-nrare2', '0'), resources[resource_order[2]]),
          (resource_order[3] + ":", state.get('-nrare3', '0'), resources[resource_order[3]]),
          (resource_order[4] + ":", state.get('-nrare4', '0'), resources[resource_order[4]]),
          ("aluminum" + ":", state.get('-aluminum', '0'), resources["aluminum"]),
          ("copper" + ":", state.get('-copper', '0'), resources["copper"]),
          ("gold" + ":", state.get('-gold', '0'), resources["gold"]),
          ("iron" + ":", state.get('-iron', '0'), resources["iron"]),
          ("uranium" + ":", state.get('-uranium', '0'), resources["uranium"])
          ] if int(increment.split('|')[0]) != 0])
    if log_rewards:
        print("State rewards:", log_rewards)
    handle_quest_progress(meta, progress_resource_added_count(state, "-"))
def apply_consumable_direct_impact(meta, selected_consumable, targeted_unit,
                                   units, units_strengths, params, ally,
                                   active_consumables):
    unit_current_strength = units_strengths[targeted_unit]
    direct_impact = int(selected_consumable["consumable"].get("-di", 0))
    damage = direct_impact
    against = simple_list(selected_consumable["consumable"].get("against", ''))
    # TODO: also units have against mod damage: Man_O_War_Battleship, Spec_Ops_Man_O_War_Battleship, LE_Elite_ManOWar_Battleship,
    # pirateship04(npc), pirateship03(npc), pirateinfantry02 PU2(npc), pirateInfantry02 PU4(npc), pirateAntiAir02(npc), pirateAntiAir03(npc),
    # pirateBalloon01(npc), pirateFighter01, pirateBomber01, pirateFighter02, pirateBomber02, pirateFighter03,pirateBomber03, pirateFighter05, pirateBomber05,
    # pirateUBoat03, pirateCaptainKrunsch and many more
    for a in against:
        if a['-type'] in (get_unit_type(units[targeted_unit]),
                          get_unit_terrain(units[targeted_unit])):
            damage *= float(a['-mod'])

    if damage > 0 and is_shielded(("ally" if ally else "enemy", targeted_unit),
                                  active_consumables) == True:
        consume_shield(("ally" if ally else "enemy", targeted_unit),
                       active_consumables)

    elif units_strengths[targeted_unit] > 0:  #can't damage/heal dead units
        units_strengths[targeted_unit] -= damage
        if not ally and 1 >= units_strengths[targeted_unit] > 0:
            units_strengths[targeted_unit] = 0
            print("Enemy inced to prevent 1 strength")
        if units_strengths[targeted_unit] <= 0:
            units_strengths[targeted_unit] = 0  # dead
            print("Enemy unit" if not ally else "Friendly unit", targeted_unit,
                  "down")
            if ally:
                handle_quest_progress(
                    meta,
                    progress_battle_damage_count("battleKill", 1, {},
                                                 units[targeted_unit]))
                doBattleRewards("kill", unit_current_strength,
                                unit_current_strength, 0)

        if units_strengths[targeted_unit] > get_unit_max_strength(
                units[targeted_unit], ally, params):
            print("Limiting heal to max strength")
            units_strengths[targeted_unit] = get_unit_max_strength(
                units[targeted_unit], ally, params)
        print("Consumable", selected_consumable["-code"],
              selected_consumable["consumable"].get("-diweapon", ""),
              "used to " + ("friendly" if ally else "baddie:"), targeted_unit,
              "di", direct_impact, "damage", damage)
    else:
        print("Consumable", selected_consumable["-code"],
              selected_consumable["consumable"].get("-diweapon", ""),
              "not used to dead " + ("friendly" if ally else "baddie:"),
              targeted_unit, "di", direct_impact, "damage", damage)

    if "-chipFactor" in selected_consumable["consumable"]:
        for i in range(len(units)):
            if units_strengths[i] > 0:
                collateral_unit_current_strength = units_strengths[i]
                colateral_damage = math.ceil(
                    get_adjacent_factor(targeted_unit, i, len(units)) *
                    int(selected_consumable["consumable"]["-chipFactor"]) *
                    int(selected_consumable["consumable"].get("-di", 0)) / 100)
                for a in against:
                    if a['-type'] in (get_unit_type(units[i]),
                                      get_unit_terrain(units[i])):
                        colateral_damage *= float(a['-mod'])
                units_strengths[i] -= colateral_damage
                if not ally and 1 >= units_strengths[i] > 0:
                    units_strengths[i] = 0
                    print("Enemy inced to prevent 1 strength")
                print("Enemy unit" if not ally else "Friendly unit suffered",
                      collateral_unit_current_strength - units_strengths[i],
                      "collateral damage")
                if units_strengths[i] <= 0:
                    units_strengths[i] = 0  # dead
                    print("Enemy unit" if not ally else "Friendly unit", i,
                          "down by collateral damage")
                    if ally:
                        handle_quest_progress(
                            meta,
                            progress_battle_damage_count(
                                "battleKill", 1, {}, units[i]))
                        doBattleRewards("kill",
                                        collateral_unit_current_strength,
                                        collateral_unit_current_strength, 0)
def assign_consumable_response(params):
    friendlies, friendly_strengths, baddies, baddie_strengths, active_consumables = init_battle(
        params)
    meta = {"newPVE": 0}
    targeted = False
    enemy_turn = False
    casting_ai = False

    consumables = lookup_items_by_type_and_subtype("consumable", "consumable")
    if params["code"] == "A0A":  # Ally / merc
        damaged = any([
            strength < get_unit_max_strength(unit, True)
            for unit, strength in zip(friendlies, friendly_strengths)
        ])
        if params.get('name') == "-1":
            level = session["user_object"]["userInfo"]["player"][
                "level"] + 5  #steele = player level + 5
        else:
            level = 6
            if params.get('name', '0')[0].isalpha():
                merc = lookup_item_by_code(params["name"])
                level = int(merc["level"])
            else:
                for neighbor in session['user_object']["neighbors"]:
                    if neighbor["uid"] == int(params.get('name', '0')):
                        level = neighbor["level"]
        valid_consumables = [c for c in consumables if "-secondary" not in c and \
                             int(c.get("requiredLevel", "0")) <= level and \
                             (damaged or c["consumable"].get("-target") == 'enemy' or c["consumable"].get("-target") == 'enemy' or int(c["consumable"].get("-di","0")) >= 0) and \
                             'requiredDate' not in c and \
                             c["consumable"].get("-allypower", "true") != "false"]

        if session['user_object']["userInfo"]["player"][
                "tutorialProgress"] == 'tut_step_krunsch1AllyUsed':
            print("During tut_step_krunsch1AllyUsed: fixed N04 Air Strike")
            # only one occurrence of fixed allyConsumable uses an N04
            valid_consumables = [lookup_item_by_code("N04")]

        selected_random_consumable_roll = roll_random_between(
            0,
            len(valid_consumables) - 1)

        selected_random_consumable = round(
            selected_random_consumable_roll
        )  # required roll fixed allyconsumable in tutorialstep
        selected_consumable = valid_consumables[selected_random_consumable]
        handle_quest_progress(meta,
                              progress_useAOA_consumable(selected_consumable))
    elif params.get("name") == "AI":
        secondaries = [
            get_unit_secondary(b) for b, i in zip(baddies, range(len(baddies)))
            if get_unit_secondary(b) is not None and not is_stunned(
                ("enemy", i), active_consumables)
        ]
        if len(secondaries) > 1:
            print("WARN: more that one secondary", repr(secondaries))
        if not secondaries:
            print("ERROR: no secondary", repr(secondaries))
            raise Exception("ERROR: no secondary", repr(secondaries))

        selected_consumable = lookup_item_by_code(secondaries[0])
        enemy_turn = True

        cast_chance = roll_random_float()
        cast_percent = float(selected_consumable["consumable"]["-castpercent"])

        print(("Not c" if cast_chance >= cast_percent else "C") +
              "asting secondary power", cast_chance, ">=", cast_percent)
        selected_consumable = None  #second targeted call will be made

        casting_ai = cast_chance < cast_percent

        #selected_consumable = None
    else:
        selected_consumable = lookup_item_by_code(params["code"])
        targeted = True
        enemy_turn = is_affected_by_consumable(
            ("AI", None), {"consumable": {}}, active_consumables)
        handle_quest_progress(
            meta,
            progress_useGeneral_consumable(selected_consumable, enemy_turn))

    # TODO: AI secondary abily Z-units
    if selected_consumable is not None:
        if selected_consumable["consumable"].get("-type") != "all":
            if (selected_consumable["consumable"].get("-target")
                    == 'enemy') ^ enemy_turn:
                live_baddies_index = get_alive_unit_index(baddie_strengths)
                if targeted:
                    targeted_baddie = int(params["id"])
                #TODO enemy support heals, accuracy,...
                else:
                    targeted_baddie = live_baddies_index[round(
                        roll_random_between(
                            0,
                            round(len(live_baddies_index) -
                                  1)))] if len(live_baddies_index
                                               ) > 1 else live_baddies_index[0]
                apply_consumable_direct_impact(meta, selected_consumable,
                                               targeted_baddie, baddies,
                                               baddie_strengths, params, False,
                                               active_consumables)
                # session["battle"] = None`
                # handle_win(baddie_strengths, meta, {})  #TODO next map?
                # handle_loss()

                target = ('enemy', targeted_baddie)
            else:
                live_friendly_index = get_alive_unit_index(friendly_strengths)
                if targeted:
                    targeted_friendly = int(params["id"])
                elif enemy_turn:
                    targeted_friendly = next(
                        i for s, i in zip(friendly_strengths,
                                          range(len(friendly_strengths)))
                        if s > 0 and not is_affected_by_consumable(
                            ("ally",
                             i), selected_consumable, active_consumables))
                else:
                    targeted_friendly = live_friendly_index[round(
                        roll_random_between(
                            0, round(len(live_friendly_index) - 1))
                    )] if len(
                        live_friendly_index) > 1 else live_friendly_index[0]
                apply_consumable_direct_impact(meta, selected_consumable,
                                               targeted_friendly, friendlies,
                                               friendly_strengths, params,
                                               True, active_consumables)
                target = ('ally', targeted_friendly)
        else:

            # TODO: more consumables
            # if consumable["consumable"].get("-type") == "all":
            print("Consumable", selected_consumable["-code"],
                  selected_consumable["consumable"].get("-diweapon",
                                                        ""), "affects all")

            if (selected_consumable["consumable"].get("-target")
                    == 'enemy') ^ enemy_turn:
                for i in range(len(baddies)):
                    apply_consumable_direct_impact(meta, selected_consumable,
                                                   i, baddies,
                                                   baddie_strengths, params,
                                                   False, active_consumables)
                if not targeted and not enemy_turn and len(
                        get_alive_unit_index(baddie_strengths)) > 1:
                    roll_random_float()  #required roll
                target = ('enemy', None)
            else:
                print("target allies")
                for i in range(len(friendlies)):
                    apply_consumable_direct_impact(meta, selected_consumable,
                                                   i, friendlies,
                                                   friendly_strengths, params,
                                                   True, active_consumables)
                if not targeted and not enemy_turn and len(
                        get_alive_unit_index(friendly_strengths)) > 1:
                    roll_random_float()
                target = ('ally', None)

            # for i in range(len(baddie_strengths)):
            # baddie_strengths[i] -= 15
            # print("Baddie", i, "strength", baddie_strengths[i])
            # if baddie_strengths[i] <= 0:
            #     baddie_strengths[i] = 0
            #     print("Baddie", i, "down by consumable")

        if int(selected_consumable["consumable"].get("-duration", "0")) > 0:
            active_consumables.append(
                (selected_consumable, target,
                 int(selected_consumable["consumable"].get("-duration", "0"))))

        if selected_consumable["-name"] == "consumable75":
            print(selected_consumable)
            defenseshield_activate(friendlies, active_consumables,
                                   selected_consumable)

        if targeted and enemy_turn:
            print("Consumable use ends enemy turn")
            process_consumable_end_turn(active_consumables, baddie_strengths,
                                        friendly_strengths, False)
        elif not enemy_turn:
            process_consumable_end_turn(active_consumables, baddie_strengths,
                                        friendly_strengths, True)

        handle_win(baddie_strengths, meta, params)
        handle_loss(friendly_strengths)

        report_battle_log(friendly_strengths, baddie_strengths, not enemy_turn,
                          None, None, active_consumables)

        if targeted and enemy_turn:
            consume_consumables(active_consumables)
    if casting_ai:
        active_consumables.append(({"consumable": {}}, ("AI", None), -1))

    assign_consumable_response = {
        "errorType": 0,
        "userId": 1,
        "metadata": meta,
        "data": []
    }
    return assign_consumable_response
def battle_complete_response(params):
    friendlies, friendly_strengths, baddies, baddie_strengths, active_consumables = init_battle(
        params)
    meta = {"newPVE": 0}

    if 'id' in params:
        [player_unit_id, enemy_unit_id] = params['id']  #player turn
        player_turn = True
    else:
        player_turn = False
        enemy_unit_id, _, player_unit_id = ai_best_attack(
            friendlies, friendly_strengths, baddies, baddie_strengths,
            active_consumables)

    if enemy_unit_id is not None and player_unit_id is not None:
        ally_target = ("ally", player_unit_id)
        enemy_target = ("enemy", enemy_unit_id)
        first_target = ally_target if player_turn else enemy_target
        second_target = enemy_target if player_turn else ally_target

        # print("repr baddies", baddies)
        baddie_max_strength = get_unit_max_strength(baddies[enemy_unit_id],
                                                    False, params)
        baddie_weak = get_unit_weak(baddies[enemy_unit_id])
        baddie_unit_type = get_unit_type(baddies[enemy_unit_id])

        friendly_max_strength = get_unit_max_strength(
            friendlies[player_unit_id], True)
        friendly_weak = get_unit_weak(friendlies[player_unit_id])
        friendly_unit_type = get_unit_type(friendlies[player_unit_id])

        friendly_strength = friendly_strengths[player_unit_id]
        baddie_strength = baddie_strengths[enemy_unit_id]

        init_seed = ["init seed", get_seed_w(), get_seed_z()]
        roll = unit_roll(friendly_weak if player_turn else baddie_weak,
                         baddie_weak if player_turn else friendly_weak)

        crit, direct = get_hit_value(
            friendly_unit_type if player_turn else baddie_unit_type,
            baddie_unit_type if player_turn else friendly_unit_type)
        if player_turn:
            crit, direct = handle_accurancy_upgrades(crit, direct, friendlies,
                                                     player_unit_id)

        accuracy = (
            get_consumable_accuracy(first_target, active_consumables) -
            get_consumable_evasion(second_target, active_consumables)) * 0.01
        crit -= accuracy
        direct -= accuracy

        hit = roll >= direct

        base_damage = 25  # TODO tier difference & increments

        if player_turn:
            damage = base_damage * (3 * friendly_max_strength +
                                    baddie_strength) / (3 * baddie_strength +
                                                        friendly_max_strength)
            damage = damage / 100 * baddie_max_strength
        else:
            damage = base_damage * (3 * baddie_max_strength + friendly_strength
                                    ) / (3 * friendly_strength +
                                         baddie_max_strength)
            damage = damage / 100 * friendly_max_strength


        consumable_extra_damage = \
            get_consumable_damage(first_target, active_consumables) - \
            get_consumable_shield(second_target, active_consumables)
        damage += max(consumable_extra_damage,
                      -damage)  # can't get negative damage by shield

        if consumable_extra_damage:
            print("Consumable extra damage",
                  max(consumable_extra_damage, -damage))

        if player_turn:
            damage = handle_damage_upgrades(damage, friendlies, player_unit_id)

        damage = math.floor(damage * 10**3) / 10**3

        glance = 0.10
        critter = 1.5

        hit_type = "directhit"

        if not hit:
            damage *= glance
            hit_type = "glancinghit"
        elif roll != 2 and roll >= crit:
            damage *= critter
            hit_type = "criticalhit"

        damage = math.ceil(damage)

        if player_turn:
            baddie_strengths[enemy_unit_id] -= damage
            if baddie_strengths[enemy_unit_id] == 1:
                damage += 1
                baddie_strengths[enemy_unit_id] -= 1
                print("Enemy inced to prevent 1 strength")
            if baddie_strengths[enemy_unit_id] <= 0:
                baddie_strengths[enemy_unit_id] = 0  #dead
                print("Enemy unit", enemy_unit_id, "down")
                hit_type = "kill" if hit_type != "criticalhit" else "criticalkill"
                handle_quest_progress(
                    meta,
                    progress_battle_damage_count("battleKill", 1,
                                                 friendlies[player_unit_id],
                                                 baddies[enemy_unit_id]))
                # session["battle"] = None
            print("Attacking for", damage, "damage, enemy hp:",
                  baddie_strengths[enemy_unit_id], roll, "after seed",
                  get_seed_w(), get_seed_z(), repr(init_seed))
            doBattleRewards(hit_type, baddie_max_strength, damage,
                            friendly_max_strength)
            handle_quest_progress(
                meta,
                progress_battle_damage_count("battleDamage", damage,
                                             friendlies[player_unit_id],
                                             baddies[enemy_unit_id]))

        elif damage > 0 and is_shielded(ally_target,
                                        active_consumables) == True:
            consume_shield(ally_target, active_consumables)

        else:
            friendly_strengths[player_unit_id] -= damage
            if friendly_strengths[player_unit_id] <= 0:
                friendly_strengths[player_unit_id] = 0  # dead
                print("Player unit", player_unit_id, "down")
                # session["battle"] = None
            print("Taken", damage, "damage, player hp:",
                  friendly_strengths[player_unit_id], roll, "after seed",
                  get_seed_w(), get_seed_z(), repr(init_seed))
    else:
        print("Stun skipped turn")
        player_unit_id = next((i for strength, i in zip(
            friendly_strengths, range(len(friendly_strengths)))
                               if strength > 0), None)
        enemy_unit_id = next((i for strength, i in zip(
            baddie_strengths, range(len(baddie_strengths))) if strength > 0),
                             None)
        roll = 0

    result = {
        "attackerStunned": None,
        "psh": 1 if is_shielded(ally_target, active_consumables) else 0,
        "esh": 0,
        "ps": friendly_strengths[player_unit_id],
        "es": baddie_strengths[enemy_unit_id],
        "hv": None,
        "ur": roll,
        "playerUnit": player_unit_id,
        "enemyUnit": enemy_unit_id,
        "seeds": {
            "w": get_seed_w(),
            "z": get_seed_z()
        },
        "energy": None
    }

    process_consumable_end_turn(active_consumables, baddie_strengths,
                                friendly_strengths, player_turn)
    handle_win(baddie_strengths, meta, params)
    handle_loss(friendly_strengths)

    report_battle_log(friendly_strengths, baddie_strengths, player_turn,
                      player_unit_id, enemy_unit_id, active_consumables)
    if not player_turn:
        consume_consumables(active_consumables)
    battle_complete_response = {
        "errorType": 0,
        "userId": 1,
        "metadata": meta,
        "data": result
    }
    return battle_complete_response