def progress_harvest_consumable(state, state_machine, game_item, step,
                                previous_state, reference_item,
                                previous_reference_item, *state_args):
    return lambda task, progress, i, *args: \
        task["_action"] in "inventoryAdded" and state.get("-harvestingState") == "1" and reference_item is not None and (
                progress_parameter_implies("_type", lookup_item_by_code(reference_item.split(":")[0]).get("-type",""))(task, progress, i, *args) and \
                progress_parameter_implies("_subtype", lookup_item_by_code(reference_item.split(":")[0]).get("-subtype",""))(task, progress, i, *args) and \
                progress_parameter_implies_contains("_item", reference_item.split(":")[0])(task, progress, i, *args)) \
def progress_harvest(state, state_machine, game_item, step, previous_state, reference_item, previous_reference_item, *state_args):
    return lambda task, progress, i, *args: \
        task["_action"] == "harvest" and previous_reference_item is not None and (
                previous_reference_item.split(":")[0] in  task.get("_item", "").split(',') or
                   progress_parameter_equals("_subtype", lookup_item_by_code(previous_reference_item.split(":")[0]).get("-subtype",""))(task, progress, i, *args)
                   or all_lambda(progress_parameter_equals("_isUpgrade", "true"),
                                 lambda *args: lookup_item_by_code(previous_reference_item.split(":")[0]).get("-type","upgrade"),
                                 progress_nested_parameter_implies("unit", "_subtype", lookup_item_by_code(previous_reference_item.split(":")[1]).get("-subtype","") if len(previous_reference_item.split(":")) > 1 else "")
                                 )(task, progress, i, *args)
                        ) \
        and reference_item == None
def prepopulate_task(task):
    if task["_action"] == 'countPlaced':
        item = lookup_item_by_code(task["_item"])
        if 'stateMachineValues' in item:
            state_machine = lookup_state_machine(item['stateMachineValues']['-stateMachineName'],
                                                 item['stateMachineValues'].get('define', []))
        else:
            state_machine = None
        objects = lookup_objects_by_item_name(item['-name'])
        built_objects = [e for e in objects if
                 int(e.get('state', 0)) >= (int(state_machine['-builtState']) if state_machine else 0)]
        number_built = len(built_objects)
        return min(number_built, int(task["_total"])), number_built >= int(task["_total"])
    if task["_action"] == 'countPlacements':
        item = lookup_item_by_code(task.get("_item", task.get('_code')))
        objects = lookup_objects_by_item_name(item['-name'])
        number_placed = len(objects)
        return min(number_placed, int(task["_total"])), number_placed >= int(task["_total"])
    elif task["_action"] == 'inventoryCount':
        item_inventory = session['user_object']["userInfo"]["player"]["inventory"]["items"]
        return min(item_inventory.get(task["_item"], 0), int(task["_total"])), item_inventory.get(task["_item"], 0) >= int(task["_total"])
    elif task["_action"] == 'population':
        return min(session['population'], int(task["_total"])), session['population'] >= int(task["_total"])
    elif task["_action"] == 'neighborsAdded':
        neighbor_count = len([ally for ally in allies.values() if ally.get("friend") and ally.get("neighbor")])
        return min(neighbor_count, int(task["_total"])), neighbor_count >= int(task["_total"])
    elif task["_action"] == 'countUpgrades':
        research = session['user_object']["userInfo"]["world"]["research"]
        total = 0
        unit = task["unit"]
        for k, v in research.items():
            if "_item" in unit:
                if k == unit["_item"]:
                    total += len(v)
            elif "_unitClass" in unit:
                item = lookup_item_by_code(k)
                if item["-unitClass"] == unit["_unitClass"]:
                    total += len(v)
            elif "_subtype" in unit:
                item = lookup_item_by_code(k)
                if item["-subtype"] == unit["_subtype"]:
                    total += len(v)

        return min(total, int(task["_total"])), total >= int(task["_total"])
    elif task["_action"] == 'autoComplete':
        return 1, True
    else:
        return 0, False
def progress_build(state, state_machine, game_item, step, previous_state, reference_item, previous_reference_item, *state_args):
    return lambda task, progress, i, *args: \
        task["_action"] == "build" and reference_item is not None and (
                reference_item.split(":")[0] in task.get("_item", "").split(',') or
                progress_parameter_equals("_resourceType",
                                          lookup_item_by_code(reference_item.split(":")[0]).get("-resourceType", ""))(
                    task, progress, i, *args)
        ) \
        and previous_reference_item == None
def progress_upgrades(unit, maximum_total, extra, progress):
    research = session['user_object']["userInfo"]["world"]["research"]
    total = 0
    for k, v in research.items():
        if "_item" in unit:
            if k == unit["_item"]:
                total += len(v)
        elif "_unitClass" in unit:
            item = lookup_item_by_code(k)
            if item["-unitClass"] == unit["_unitClass"]:
                total += len(v)
        elif "_subtype" in unit:
            item = lookup_item_by_code(k)
            if item["-subtype"] == unit["_subtype"]:
                total += len(v)

    extra["total"] = min(total, int(maximum_total))
    return total != progress
def handle_accurancy_upgrades(crit, direct, friendlies, player_unit_id):
    research = session['user_object']["userInfo"]["world"]["research"]
    upgrades = research.get(friendlies[player_unit_id]["-code"], [])
    for upgrade in upgrades:
        upgrade_item = lookup_item_by_code(upgrade)
        mod_accuracy = upgrade_item["modifier"].get("-accuracy")
        if mod_accuracy:
            crit -= float(mod_accuracy) / 100
            direct -= float(mod_accuracy) / 100
            print("Applying hit chance upgrade for", mod_accuracy, "percent")

    return crit, direct
def handle_strength_upgrades(strength, unit):
    research = session['user_object']["userInfo"]["world"]["research"]
    upgrades = research.get(unit["-code"], [])
    for upgrade in upgrades:
        upgrade_item = lookup_item_by_code(upgrade)
        mod_damage = upgrade_item["modifier"].get("-strength")
        if mod_damage:
            if upgrade_item["modifier"].get("-percent"):
                strength *= 1 + float(mod_damage) / 100
                print("Applying strength upgrade for", mod_damage, "percent")
            else:
                strength += int(mod_damage)
                print("Applying strength upgrade for", mod_damage, "more")
    return strength
def handle_damage_upgrades(damage, friendlies, player_unit_id):
    research = session['user_object']["userInfo"]["world"]["research"]
    upgrades = research.get(friendlies[player_unit_id]["-code"], [])
    for upgrade in upgrades:
        upgrade_item = lookup_item_by_code(upgrade)
        mod_damage = upgrade_item["modifier"].get("-damage")
        if mod_damage:
            if upgrade_item["modifier"].get("-percent"):
                damage *= 1 + float(mod_damage) / 100
                print("Applying damage upgrade for", mod_damage, "percent")
            else:
                damage += int(mod_damage)
                print("Applying damage upgrade for", mod_damage, "more")
    return damage
def click_next_state(do_click, id, meta, step, reference_item, speed_up=False, tending=False, save=None, playback_tend=False, tend_type=None, cancel=True):
    cur_object = lookup_object(id) if not tending else lookup_object_save(save, id)
    print("cur_object used:", repr(cur_object))
    tend = tending or playback_tend

    game_item = lookup_item_by_name(cur_object['itemName'])
    print("item used:", repr(game_item))

    timestamp = datetime.now().timestamp()
    if 'stateMachineValues' in game_item:
        state_machine = lookup_state_machine(game_item['stateMachineValues']['-stateMachineName'],
                                             game_item['stateMachineValues'].get('define', []),
                                             (lookup_reference_item(cur_object) or {}).get('referenceValues',{}).get('define'))

        print("state_machine used:", repr(state_machine))
        state = lookup_state(state_machine, cur_object.get('state', 0), cur_object, True)
        print("cur state:", repr(state))

        while '-autoNext' in state and state['-stateName'] != state['-autoNext']:   # '-clientDuration': '2.0s', '-duration': '0' respect duration for harvest?
            duration =  parse_duration(state.get('-duration', '0'))
            if cur_object.get('lastUpdated', 0) / 1000 +  duration <= timestamp or speed_up or tend:
                if cur_object.get('lastUpdated', 0) / 1000 + duration > timestamp:
                    speed_up = False  # consumes speed up
                    tend = False
                    print("speed up used")
                next_state_id = state['-autoNext']  # not all states have this!! end states? autostate after time?
                previous_state = state
                state = lookup_state(state_machine, next_state_id, cur_object, True)
                check_state(state_machine, state, cur_object, tending)
                if not tending:
                    do_state_rewards(state, cur_object.get('referenceItem'), meta, playback_tend=playback_tend)
                if 'lastUpdated' not in cur_object:
                    cur_object['lastUpdated'] = 0  #init?
                cur_object['lastUpdated'] += duration * 1000
                cur_object['state'] = next_state_id
                print("pre auto_next_state:", repr(state), 'time', cur_object['lastUpdated'], "duration", duration)
                if not tending:
                    handle_world_state_change(meta, state, state_machine, game_item, step, previous_state, cur_object.get('referenceItem'), cur_object.get('referenceItem'))
            else:
                print("state has autoNext, but not enough time was passed")
                break

        if (do_click or tend):
            try:
               next_state_id = state['-clickNext'] if not cancel else state['-cancelNext']
            except:
                next_state_id = state['-clickNext']
            if reference_item != cur_object.get('referenceItem'):
                state_machine = lookup_state_machine(game_item['stateMachineValues']['-stateMachineName'],
                                                     game_item['stateMachineValues'].get('define', []),
                                                     (lookup_item_by_code(reference_item.split(":")[0]) if reference_item else {})
                                                     .get('referenceValues', {}).get('define'))
            next_click_state = lookup_state(state_machine, next_state_id, cur_object, True)
            check_state(state_machine, next_click_state, cur_object, tending)
            print("next_click_state:", repr(next_click_state))
            if cancel:
                print("canceled state")
            if not tending:
                do_state_rewards(next_click_state, cur_object.get('referenceItem'), meta, playback_tend=playback_tend)
                handle_world_state_change(meta, next_click_state, state_machine, game_item, step, state, reference_item, cur_object.get('referenceItem'))
            else:
                if tend_type == "mine":
                    standard_resources = ["coins", "oil", "wood", "aluminum", "copper", "gold", "iron", "uranium"]
                    tend_type += standard_resources[save['user_object']["userInfo"]["player"]["playerResourceType"]]
                elif tend_type == "harvest":
                    tend_type += "_" + game_item['stateMachineValues']['-referenceType'] if '-referenceType' in game_item['stateMachineValues'] else ""
                    tend_type += "_" + game_item['stateMachineValues']['-referenceSubtype'] if '-referenceSubtype' in game_item['stateMachineValues'] else ""
                elif tend_type == "clear":
                    tend_type += game_item['-subtype']
                #TODO Crew tax

                reward = lookup_visitor_reward(tend_type)
                do_state_rewards(reward, cur_object.get('referenceItem'), meta)

            while '-autoNext' in next_click_state and next_state_id != next_click_state['-autoNext'] and next_click_state.get('-duration', '0') in ['0', '0s']:   #'-clientDuration': '2.0s', '-duration': '0' respect duration for harvest?
                next_state_id = next_click_state['-autoNext']
                previous_state = next_click_state
                next_click_state = lookup_state(state_machine, next_state_id, cur_object, True)
                check_state(state_machine, next_click_state, cur_object, tending)
                print("auto_next_state:", repr(next_click_state))
                if not tending:
                    do_state_rewards(next_click_state, reference_item, meta, playback_tend=playback_tend)
                    handle_world_state_change(meta, next_click_state, state_machine, game_item, step, previous_state, reference_item, reference_item)

            cur_object['state'] = next_state_id
            cur_object['lastUpdated'] = timestamp * 1000
        else:
            print("state has no clicknext, click does nothing" if do_click else "not clicking, only autonexts")
            cur_object['lastUpdated'] = timestamp * 1000
    else:
        print("object has no statemachine, click does nothing")
        cur_object['lastUpdated'] = timestamp * 1000
        if not tending:
            handle_world_state_change(meta, {}, None, game_item, step, {}, reference_item, reference_item)
Exemplo n.º 10
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
Exemplo n.º 11
0
def init_battle(params):
    if 'target' not in params:
        if params.get("name") == "AI":
            print("AI fleet")
            future_enemy_fleet = get_new_enemy_fleet_name()
            friendlies = [
                lookup_item_by_code(friendly.split(',')[0])
                for friendly in session['fleets'][get_previous_fleet(
                    get_previous_fleet(get_previous_fleet(
                        future_enemy_fleet)))]
            ]
            baddies = [
                lookup_item_by_code(baddy[1:]) for sub_fleet in simple_list(
                    session['fleets'][get_previous_fleet(
                        get_previous_fleet(future_enemy_fleet))])
                for baddy, count in sub_fleet.items()
                for i in range(int(count))
            ]
        elif isinstance(
                simple_list(
                    session['fleets']
                    [params['fleet'] if params['fleet'] else params['name']])
            [0], str):
            print("Ally direct target")
            friendlies = [
                lookup_item_by_code(friendly.split(',')[0])
                for friendly in session['fleets']
                [params['fleet'] if params['fleet'] else params['name']]
            ]
            baddies = [
                lookup_item_by_code(baddy[1:])
                for sub_fleet in simple_list(session['fleets'][get_next_fleet(
                    params['fleet'] if params['fleet'] else params['name'])])
                for baddy, count in sub_fleet.items()
                for i in range(int(count))
            ]
        else:
            baddies = [
                lookup_item_by_code(baddy[1:]) for sub_fleet in simple_list(
                    session['fleets']
                    [params['fleet'] if params['fleet'] else params['name']])
                for baddy, count in sub_fleet.items()
                for i in range(int(count))
            ]
            friendlies = [
                lookup_item_by_code(friendly.split(',')[0])
                for friendly in session['fleets'][get_previous_fleet(
                    params['fleet'] if params['fleet'] else params['name'])]
            ]
    elif params['target'].startswith('fleet'):
        baddies = [
            lookup_item_by_code(baddy[1:])
            for sub_fleet in simple_list(session['fleets'][params['target']])
            for baddy, count in sub_fleet.items() for i in range(int(count))
        ]
        friendlies = [
            lookup_item_by_code(friendly.split(',')[0])
            for friendly in session['fleets'][params['fleet']]
        ]
    elif params['target'] == "FleetName":
        baddies = [
            lookup_item_by_code(baddy.split(',')[0]) for sub_fleet in
            simple_list(session['fleets'][get_next_fleet(params['fleet'])])
            for baddy in sub_fleet["units"]
        ]
        friendlies = [
            lookup_item_by_code(friendly.split(',')[0])
            for friendly in session['fleets'][params['fleet']]
        ]
    else:
        quest = lookup_quest(params['target'])
        tasks = get_tasks(quest)
        [task] = [t for t in tasks if t["_action"] == "fight"]
        enemy_fleet = lookup_item_by_code(task["_item"])
        baddies = [
            lookup_item_by_code(baddie_slot["-item"])
            for baddie_slot in simple_list(enemy_fleet["baddie"])
        ]
        friendlies = [
            lookup_item_by_code(friendly[1:])
            for friendly, count in task["fleet"].items()
            for i in range(int(count))
        ]

    if "battle" not in session or not session["battle"]:
        baddie_strengths = [
            get_unit_max_strength(baddie, False, params) for baddie in baddies
        ]
        friendly_strengths = [
            get_unit_max_strength(friendly, True) for friendly in friendlies
        ]
        active_consumables = []
        session["battle"] = (friendly_strengths, baddie_strengths,
                             active_consumables)
    else:
        (friendly_strengths, baddie_strengths,
         active_consumables) = session["battle"]
    return friendlies, friendly_strengths, baddies, baddie_strengths, active_consumables
Exemplo n.º 12
0
def get_current_island(params):
    if params and 'map' in params and params['map'] and params['map'][0] == 'C':
        map_item = lookup_item_by_code(params["map"])
        return get_active_island_by_map(params['map']) + (map_item, )
    return None, None, None