Ejemplo n.º 1
0
Archivo: map.py Proyecto: rgeyer/MAD
    def get_map_mons(self):
        neLat, neLon, swLat, swLon, oNeLat, oNeLon, oSwLat, oSwLon = getBoundParameter(
            request)
        timestamp = request.args.get("timestamp", None)

        data = self._db.get_mons_in_rectangle(neLat=neLat,
                                              neLon=neLon,
                                              swLat=swLat,
                                              swLon=swLon,
                                              oNeLat=oNeLat,
                                              oNeLon=oNeLon,
                                              oSwLat=oSwLat,
                                              oSwLon=oSwLon,
                                              timestamp=timestamp)

        mons_raw = {}

        for i, mon in enumerate(data):
            try:
                id = data[i]["mon_id"]
                if str(id) in mons_raw:
                    mon_raw = mons_raw[str(id)]
                else:
                    mon_raw = get_raid_boss_cp(id)
                    mons_raw[str(id)] = mon_raw

                data[i]["encounter_id"] = str(data[i]["encounter_id"])
                data[i]["name"] = i8ln(mon_raw["name"])
            except Exception:
                pass

        return jsonify(data)
Ejemplo n.º 2
0
 def settings_ivlists(self):
     try:
         identifier = request.args.get('id')
         current_mons = self._data_manager.get_resource(
             'monivlist', identifier)['mon_ids_iv']
     except Exception:
         current_mons = []
     all_pokemon = self.get_pokemon()
     mondata = all_pokemon['mondata']
     current_mons_list = []
     for mon_id in current_mons:
         try:
             mon_name = i8ln(mondata[str(mon_id)]["name"])
         except KeyError:
             mon_name = "No-name-in-file-please-fix"
         current_mons_list.append({
             "mon_name": mon_name,
             "mon_id": str(mon_id)
         })
     required_data = {
         'identifier': 'id',
         'base_uri': 'api_monivlist',
         'data_source': 'monivlist',
         'redirect': 'settings_ivlists',
         'html_single': 'settings_singleivlist.html',
         'html_all': 'settings_ivlists.html',
         'subtab': 'monivlist',
         'passthrough': {
             'current_mons_list': current_mons_list
         }
     }
     return self.process_element(**required_data)
Ejemplo n.º 3
0
    def game_stats_mon(self):
        minutes_spawn = request.args.get('minutes_spawn', 10)

        # Spawn
        iv = []
        noniv = []
        sumg = []
        sumup = {}

        data = self._db_stats_reader.get_pokemon_count(minutes_spawn)
        for dat in data:
            if dat[2] == 1:
                iv.append([(self.utc2local(dat[0]) * 1000), dat[1]])
            else:
                noniv.append([(self.utc2local(dat[0]) * 1000), dat[1]])

            if (self.utc2local(dat[0]) * 1000) in sumup:
                sumup[(self.utc2local(dat[0]) * 1000)] += dat[1]
            else:
                sumup[(self.utc2local(dat[0]) * 1000)] = dat[1]

        for dat in sumup:
            sumg.append([dat, sumup[dat]])

        spawn = {'iv': iv, 'noniv': noniv, 'sum': sumg}

        # good_spawns avg
        good_spawns = []
        data = self._db_stats_reader.get_best_pokemon_spawns()
        if data is not None:
            for dat in data:
                mon = "%03d" % dat[1]
                monPic = 'asset/pokemon_icons/pokemon_icon_' + mon + '_00.png'
                monName_raw = (get_raid_boss_cp(dat[1]))
                monName = i8ln(monName_raw['name'])
                if self._args.db_method == "rm":
                    lvl = calculate_mon_level(dat[6])
                else:
                    lvl = dat[6]
                good_spawns.append({
                    'id':
                    dat[1],
                    'iv':
                    round(calculate_iv(dat[3], dat[4], dat[5]), 0),
                    'lvl':
                    lvl,
                    'cp':
                    dat[7],
                    'img':
                    monPic,
                    'name':
                    monName,
                    'periode':
                    datetime.datetime.fromtimestamp(self.utc2local(
                        dat[2])).strftime(self._datetimeformat)
                })

        stats = {'spawn': spawn, 'good_spawns': good_spawns}
        return jsonify(stats)
Ejemplo n.º 4
0
 def get_pokemon(self):
     mondata = open_json_file('pokemon')
     # Why o.O
     stripped_mondata = {}
     for mon_id in mondata:
         stripped_mondata[mondata[str(mon_id)]["name"]] = mon_id
         if os.environ['LANGUAGE'] != "en":
             try:
                 localized_name = i8ln(mondata[str(mon_id)]["name"])
                 stripped_mondata[localized_name] = mon_id
             except KeyError:
                 pass
     return {'mondata': mondata, 'locale': stripped_mondata}
Ejemplo n.º 5
0
def generate_quest(quest):
    gettext.find('quest', 'locales', all=True)
    lang = gettext.translation('quest', localedir='locale', fallback=True)
    lang.install()

    quest_reward_type = questreward(quest['quest_reward_type'])
    quest_type = questtype(quest['quest_type'])
    if '{0}' in quest_type:
        quest_type = quest_type.replace('{0}', str(quest['quest_target']))

    item_id = 0
    item_amount = 1
    pokemon_id = '000'
    pokemon_name = ''
    item_type = ''
    pokemon_form = '00'
    pokemon_costume = '00'
    pokemon_asset_bundle = '00'

    if quest_reward_type == _('Item'):
        item_amount = quest['quest_item_amount']
        item_type = rewarditem(quest['quest_item_id'])
        item_id = quest['quest_item_id']
    elif quest_reward_type == _('Stardust'):
        item_amount = quest['quest_stardust']
        item_type = _('Stardust')
    elif quest_reward_type == _('Pokemon'):
        item_type = 'Pokemon'
        pokemon_name = i8ln(pokemonname(str(quest['quest_pokemon_id'])))
        pokemon_id = quest['quest_pokemon_id']
        pokemon_form = quest['quest_pokemon_form_id']
        pokemon_costume = quest['quest_pokemon_costume_id']
        if pokemon_form != '00':
            pokemon_asset_bundle = form_mapper(int(pokemon_id), pokemon_form)
    elif quest_reward_type == _('Energy'):
        item_type = _('Mega Energy')
        if quest['quest_pokemon_id'] and int(quest['quest_pokemon_id']) > 0:
            pokemon_name = i8ln(pokemonname(str(quest['quest_pokemon_id'])))
            pokemon_id = quest['quest_pokemon_id']
        else:
            pokemon_name = ''
        item_amount = quest['quest_item_amount']

    if not quest['task']:
        quest_task = questtask(quest['quest_type'], quest['quest_condition'],
                               quest['quest_target'], quest['quest_template'])
    else:
        quest_task = quest['task']

    quest_raw = ({
        'pokestop_id': quest['pokestop_id'],
        'name': quest['name'],
        'url': quest['image'],
        'latitude': quest['latitude'],
        'longitude': quest['longitude'],
        'timestamp': quest['quest_timestamp'],
        'item_id': item_id,
        'item_amount': item_amount,
        'item_type': item_type,
        'pokemon_id': pokemon_id,
        'pokemon_name': pokemon_name,
        'pokemon_form': pokemon_form,
        'pokemon_asset_bundle_id': pokemon_asset_bundle,
        'pokemon_costume': pokemon_costume,
        'quest_type': quest_type,
        'quest_type_raw': quest['quest_type'],
        'quest_reward_type': quest_reward_type,
        'quest_reward_type_raw': quest['quest_reward_type'],
        'quest_task': quest_task,
        'quest_target': quest['quest_target'],
        'quest_condition': quest['quest_condition'],
        'quest_template': quest['quest_template'],
    })
    return quest_raw
Ejemplo n.º 6
0
def questtask(typeid, condition, target, quest_template):
    gettext.find('quest', 'locales', all=True)
    lang = gettext.translation('quest', localedir='locale', fallback=True)
    lang.install()

    pokemonTypes = open_json_file('pokemonTypes')
    items = open_json_file('items')
    throwTypes = {
        "10": _("Nice"),
        "11": _("Great"),
        "12": _("Excellent"),
        "13": _("Curveball")
    }
    arr = {}
    arr['0'] = target
    text = questtype(typeid)
    # TODO use the dict instead of regex parsing in all logic
    condition_dict = {}
    if condition is not None and condition != '':
        condition_dict = json.loads(condition)

    if typeid == 4:
        arr['wb'] = ""
        arr['type'] = ""
        arr['poke'] = ""
        arr['different'] = ""
        arr['item'] = ""

        text = _("Catch {0}{different} {type}Pokemon{wb}")
        match_object = re.search(r'"pokemon_type": \[([0-9, ]+)\]', condition)
        if match_object is not None:
            pt = match_object.group(1).split(', ')
            last = len(pt)
            cur = 1
            if last == 1:
                arr['type'] = pokemonTypes[pt[0]].title() + _('-type ')
            else:
                for ty in pt:
                    arr['type'] += (_('or ') if last == cur else '') + \
                                   pokemonTypes[ty].title() + (_('-type ')
                                                               if last == cur else '-, ')
                    cur += 1
        if re.search(r'"type": 3', condition) is not None:
            arr['wb'] = _(" with weather boost")
        elif re.search(r'"type": 21', condition) is not None:
            arr['different'] = _(" different species of")
        match_object = re.search(r'"pokemon_ids": \[([0-9, ]+)\]', condition)
        if match_object is not None:
            pt = match_object.group(1).split(', ')
            last = len(pt)
            cur = 1
            if last == 1:
                arr['poke'] = i8ln(pokemonname(pt[0]))
            else:
                for ty in pt:
                    arr['poke'] += (_('or ') if last == cur else '') + \
                                   i8ln(pokemonname(ty)) + ('' if last == cur else ', ')
                    cur += 1
            text = _('Catch {0} {poke}')
    elif typeid == 5:
        text = _("Spin {0} Pokestops or Gyms")
        if re.search(r'"type": 12', condition) is not None:
            text = _("Spin {0} Pokestops you haven't visited before")
    elif typeid == 6:
        text = _("Hatch {0} Eggs")
    elif typeid == 7:
        if re.search(r'"type": 9', condition) is not None:
            text = _("Win {0} Gym Battles")
        elif re.search(r'"type": 10', condition) is not None:
            text = _("Use a supereffective Charged Attack in {0} Gym battles")
        else:
            text = _("Battle in a Gym {0} times")
    elif typeid == 8:
        if re.search(r'"type": 6', condition) is not None:
            text = _("Win {0} Raids")
            if re.search(r'"raid_level": \[3, 4, 5\]', condition) is not None:
                text = _('Win a level 3 or higher raid')
            if re.search(r'"raid_level": \[2, 3, 4, 5\]',
                         condition) is not None:
                text = _('Win a level 2 or higher raid')
            if re.search(r'"raid_level": \[6\]', condition) is not None:
                text = _('Win a Mega raid')
        else:
            text = _("Battle in {0} Raids")
    elif typeid == 10:
        text = _("Transfer {0} Pokemon")
    elif typeid == 11:
        text = _("Favourite {0} Pokemon")
    elif typeid == 13:
        text = _('Use {0} {type}Berries to help catch Pokemon')
        arr['type'] = ""
        match_object = re.search(r'"item": ([0-9]+)', condition)
        if match_object is not None:
            arr['type'] = items[match_object.group(1)]['name'].replace(
                _(' Berry'), '') + " "
    elif typeid == 14:
        text = _('Power up Pokemon {0} times')
    elif typeid == 15 or typeid == 43:
        arr['mega'] = ""
        text = _("{mega}Evolve {0} Pokemon")
        if typeid == 43:
            arr['mega'] = _("Mega ")

        for con in condition_dict:
            if con.get('type', 0) == 11:
                text = _("Use an item to {mega}evolve {0} Pokemon")
                # Try to find the exact evolution item needed
                # [{"type": 11, "with_item": {"item": 1106}}]
                with_item = con.get('with_item', {}).get('item', None)
                if with_item is not None:
                    text = _('Use {item} to {mega}evolve {0} Pokemon')
                    arr['item'] = items[str(with_item)]['name']
            if con.get('type', 0) == 1:
                text = _("{mega}Evolve {0} {type}Pokemon")
                arr['wb'] = ""
                arr['type'] = ""
                arr['poke'] = ""
                match_object = re.search(r'"pokemon_type": \[([0-9, ]+)\]',
                                         condition)
                if match_object is not None:
                    pt = match_object.group(1).split(', ')
                    last = len(pt)
                    cur = 1
                    if last == 1:
                        arr['type'] = pokemonTypes[pt[0]].title() + _('-type ')
                    else:
                        for ty in pt:
                            arr['type'] += (_('or ') if last == cur else
                                            '') + pokemonTypes[ty].title() + (
                                                _('-type ')
                                                if last == cur else '-, ')
                            cur += 1
            if con.get('type', 0) == 2:
                arr['wb'] = ""
                arr['type'] = ""
                arr['poke'] = ""

                match_object = re.search(r'"pokemon_ids": \[([0-9, ]+)\]',
                                         condition)
                if match_object is not None:
                    pt = match_object.group(1).split(', ')
                    last = len(pt)
                    cur = 1
                    if last == 1:
                        arr['poke'] = i8ln(pokemonname(pt[0]))
                    else:
                        for ty in pt:
                            arr['poke'] += (_('or ') if last == cur else
                                            '') + i8ln(pokemonname(ty)) + (
                                                '' if last == cur else ', ')
                            cur += 1
                    text = _('{mega}Evolve {0} {poke}')
    elif typeid == 16:
        arr['inrow'] = ""
        arr['curve'] = ""
        arr['type'] = ""
        if re.search(r'"type": 14', condition) is not None:
            arr['inrow'] = _(" in a row")
        if re.search(r'"type": 15', condition) is not None:
            arr['curve'] = _("Curveball ")
        match_object = re.search(r'"throw_type": ([0-9]{2})', condition)
        if match_object is not None:
            arr['type'] = throwTypes[match_object.group(1)] + " "
        text = _("Make {0} {type}{curve}Throws{inrow}")
    elif typeid == 17:
        text = _('Earn {0} Candies walking with your buddy')
    elif typeid == 22:
        if int(target) == int(1):
            text = _('Make a new friend')
        else:
            text = _('Make {0} new friends')
    elif typeid == 23:
        text = _('Trade {0} Pokemon')
        arr['distance'] = ""
        if re.search(r'"type": 25', condition) is not None:
            arr['distance'] = re.search(r'"distance_km": ([0-9, ]+)',
                                        condition).group(1)
            if int(target) == int(1):
                text = _('Trade Pokemon caught {distance} km apart')
            else:
                text = _('Trade {0} Pokemon caught {distance} km apart')
    elif typeid == 24:
        text = _('Send {0} gifts to friends')
    elif typeid == 27:
        for con in condition_dict:
            if con.get('type', 0) == 22:
                # PVP against team leader.
                text = _('Battle a Team Leader {0} times')
            elif con.get('type') == 23:
                gotta_win = con.get('with_pvp_combat',
                                    {}).get('requires_win') is True

                if gotta_win:
                    text = _('Win a battle against another Trainer {0} times')
                else:
                    text = _('Battle another Trainer {0} times')

                in_go_battle_league = any(x in con.get(
                    'with_pvp_combat', {}).get('combat_league_template_id', [])
                                          for x in [
                                              "COMBAT_LEAGUE_VS_SEEKER_GREAT",
                                              "COMBAT_LEAGUE_VS_SEEKER_ULTRA",
                                              "COMBAT_LEAGUE_VS_SEEKER_MASTER"
                                          ])
                vs_player = any(x in con.get('with_pvp_combat', {}).get(
                    'combat_league_template_id', []) for x in [
                        "COMBAT_LEAGUE_DEFAULT_GREAT",
                        "COMBAT_LEAGUE_DEFAULT_ULTRA",
                        "COMBAT_LEAGUE_DEFAULT_MASTER"
                    ])
                if not vs_player and in_go_battle_league and gotta_win:
                    text = _('Win in the GO Battle League {0} times')
                elif in_go_battle_league and not vs_player:
                    text = _('Battle in the GO Battle League {0} times')
    elif typeid == 28:
        # Take snapshots quest
        if re.search(r'"type": 28', condition) is not None:
            text = _("Take {0} snapshots of your Buddy")
        elif re.search(r'"type": 2', condition) is not None:
            arr['poke'] = ""

            match_object = re.search(r'"pokemon_ids": \[([0-9, ]+)\]',
                                     condition)
            if match_object is not None:
                pt = match_object.group(1).split(', ')
                last = len(pt)
                cur = 1
                if last == 1:
                    arr['poke'] = i8ln(pokemonname(pt[0]))
                else:
                    for ty in pt:
                        arr['poke'] += (_('or ') if last == cur else
                                        '') + i8ln(pokemonname(ty)) + (
                                            '' if last == cur else ', ')
                        cur += 1
                text = _("Take {0} snapshots of {poke}")
        elif re.search(r'"type": 1', condition) is not None:
            text = _("Take {0} snapshots of {type} Pokemon")
            arr['wb'] = ""
            arr['type'] = ""
            arr['poke'] = ""
            match_object = re.search(r'"pokemon_type": \[([0-9, ]+)\]',
                                     condition)
            if match_object is not None:
                pt = match_object.group(1).split(', ')
                last = len(pt)
                cur = 1
                if last == 1:
                    arr['type'] = pokemonTypes[pt[0]].title() + _('-type ')
                else:
                    for ty in pt:
                        arr['type'] += (_('or ') if last == cur else
                                        '') + pokemonTypes[ty].title() + (
                                            _('-type ')
                                            if last == cur else '-, ')
                        cur += 1
    elif typeid == 29:
        # QUEST_BATTLE_TEAM_ROCKET Team Go rucket grunt batles.
        if int(target) == int(1):
            text = _('Battle a Team Rocket Grunt')

        for con in condition_dict:
            if con.get('type', 0) == 27 and con.get('with_invasion_character',
                                                    {}).get('category') == 1:
                text = _('Battle {0} times against the Team GO Rocket Leaders')
                # TODO Handle category for specific team leaders as well (Arlo, Cliff, Sierra)
            if con.get('type', 0) == 18:
                # Condition type 18 means win a battle
                # TODO change WIN to Defeat like in-game
                text = text.replace(_('Battle'), _('Defeat'))

    quest_templates = open_json_file('quest_templates')
    if quest_template is not None and quest_template in quest_templates:
        text = _(quest_templates[quest_template])

    if int(target) == int(1):
        text = text.replace(_(' Eggs'), _('n Egg'))
        text = text.replace(_(' Raids'), _(' Raid'))
        text = text.replace(_(' Battles'), _(' Battle'))
        text = text.replace(_(' candies'), _(' candy'))
        text = text.replace(_(' gifts'), _(' gift'))
        text = text.replace(_(' Pokestops'), _(' Pokestop'))
        text = text.replace(_(' {0} snapshots'), _(' a snapshot'))
        text = text.replace(_('Make {0} {type}{curve}Throws'),
                            _('Make a {type}{curve}Throw'))
        text = text.replace(_(' {0} times'), '')
        text = text.replace(_('{0} hearts'), _('a heart'))
        arr['0'] = _("a")

    for key, val in arr.items():
        text = text.replace('{' + key + '}', str(val))

    text = text.replace('  ', ' ').strip()
    return text
Ejemplo n.º 7
0
def generate_quest(quest):
    quest_reward_type = questreward(quest['quest_reward_type'])
    quest_type = questtype(quest['quest_type'])
    if '{0}' in quest_type:
        quest_type = quest_type.replace('{0}', str(quest['quest_target']))

    item_id = 0
    item_amount = 1
    pokemon_id = '000'
    pokemon_name = ''
    item_type = ''
    pokemon_form = '00'
    pokemon_costume = '00'
    pokemon_asset_bundle = '00'

    if quest_reward_type == _('Item'):
        item_amount = quest['quest_item_amount']
        item_type = rewarditem(quest['quest_item_id'])
        item_id = quest['quest_item_id']
    elif quest_reward_type == _('Stardust'):
        item_amount = quest['quest_stardust']
        item_type = _('Stardust')
    elif quest_reward_type == _('Pokemon'):
        item_type = 'Pokemon'
        pokemon_name = i8ln(pokemonname(str(quest['quest_pokemon_id'])))
        pokemon_id = quest['quest_pokemon_id']
        pokemon_form = quest['quest_pokemon_form_id']
        pokemon_costume = quest['quest_pokemon_costume_id']
        if pokemon_form != '00':
            pokemon_asset_bundle = form_mapper(int(pokemon_id), pokemon_form)
    elif quest_reward_type == _('Energy'):
        item_type = _('Mega Energy')
        if quest['quest_pokemon_id'] and int(quest['quest_pokemon_id']) > 0:
            pokemon_name = i8ln(pokemonname(str(quest['quest_pokemon_id'])))
            pokemon_id = quest['quest_pokemon_id']
        else:
            pokemon_name = ''
        item_amount = quest['quest_item_amount']
    elif quest_reward_type == _("Candy"):
        # TODO maybe we should be doing deep parsing against the reward array
        item_amount = quest['quest_item_amount']
        item_type = quest_reward_type
        pokemon_id = quest['quest_pokemon_id']
        pokemon_name = pokemon_name = i8ln(pokemonname(str(pokemon_id)))

    if not quest['task']:
        quest_task = questtask(
            quest['quest_type'], quest['quest_condition'], quest['quest_target'], quest['quest_template'])
    else:
        quest_task = quest['task']

    quest_raw = ({
        'pokestop_id': quest['pokestop_id'],
        'name': quest['name'],
        'url': quest['image'],
        'latitude': quest['latitude'],
        'longitude': quest['longitude'],
        'timestamp': quest['quest_timestamp'],
        'item_id': item_id,
        'item_amount': item_amount,
        'item_type': item_type,
        'pokemon_id': pokemon_id,
        'pokemon_name': pokemon_name,
        'pokemon_form': pokemon_form,
        'pokemon_asset_bundle_id': pokemon_asset_bundle,
        'pokemon_costume': pokemon_costume,
        'quest_type': quest_type,
        'quest_type_raw': quest['quest_type'],
        'quest_reward_type': quest_reward_type,
        'quest_reward_type_raw': quest['quest_reward_type'],
        'quest_task': quest_task,
        'quest_target': quest['quest_target'],
        'quest_condition': quest['quest_condition'],
        'quest_template': quest['quest_template'],
        'is_ar_scan_eligible': quest['is_ar_scan_eligible'],

    })
    return quest_raw
Ejemplo n.º 8
0
def questtask(typeid, condition, target, quest_template):
    gettext.find('quest', 'locales', all=True)
    throw_types = {"10": _("Nice"), "11": _("Great"),
                   "12": _("Excellent"), "13": _("Curveball")}
    buddyLevels = {2: _("Good"), 3: _("Great"), 4: _("Ultra"), 5: _("Best")}
    arr = {'0': target}
    text = questtype(typeid)
    # TODO use the dict instead of regex parsing in all logic
    condition_dict = {}
    if condition is not None and condition != '':
        condition_dict = json.loads(condition)

    if typeid == 4:
        arr['wb'] = ""
        arr['type'] = ""
        arr['poke'] = ""
        arr['different'] = ""
        arr['item'] = ""

        text = _("Catch {0}{different} {type}Pokemon{wb}")

        for con in condition_dict:
            condition_type = con.get('type', 0)
            if condition_type == 1:
                # Condition type 1 is pokemon_types
                pokemon_type_array = con.get('with_pokemon_type', {}).get('pokemon_type', [])
                num_of_pokemon_types = len(pokemon_type_array)
                if num_of_pokemon_types > 1:
                    arr['type'] = "{}- or {} ".format(
                        _('-, ').join(pokemon_types[str(pt)].title() for pt in pokemon_type_array[::-1]),
                        get_pokemon_type_str(pokemon_type_array[-1]))
                elif num_of_pokemon_types == 1:
                    arr['type'] = get_pokemon_type_str(pokemon_type_array[0]) + " "
            elif condition_type == 2:
                # Condition type 2 is to catch certain kind of pokemons
                pokemon_id_array = con.get('with_pokemon_category', {}).get('pokemon_ids', [])

                if len(pokemon_id_array) > 0:
                    text = _('Catch {0} {poke}')
                    if len(pokemon_id_array) == 1:
                        arr['poke'] = i8ln(pokemonname(pokemon_id_array[0]))
                    else:
                        # More than one mon, let's make sure to list them comma separated ending with or
                        arr['poke'] = "{} or {} ".format(
                            _(', ').join(i8ln(pokemonname(pt)) for pt in pokemon_id_array[::-1]),
                            i8ln(pokemonname(pokemon_id_array[-1])))
            elif condition_type == 3:
                # Condition type 3 is weather boost.
                arr['wb'] = _(" with weather boost")
            elif condition_type == 21:
                # condition type 21 is unique pokemon
                arr['different'] = _(" different species of")
            elif condition_type == 26:
                # Condition type 26 is alignment
                alignment = con.get('with_pokemon_alignment',{}).get('alignment', [])
                # POKEMON_ALIGNMENT_UNSET = 0;
                # POKEMON_ALIGNMENT_SHADOW = 1;
                # POKEMON_ALIGNMENT_PURIFIED = 2;
                if len(alignment) == 1 and alignment[0] == 1:
                    arr['different'] = _(" shadow")
                elif len(alignment) == 1 and alignment[0] == 2:
                    # AFAIK you can't catch purified pokemon directly, but who knows..
                    arr['different'] = _(" purified")
    elif typeid == 5:
        if '"type": 12' in condition:
            text = _("Spin {0} Pokestops you haven't visited before")
        else:
            text = _("Spin {0} Pokestops or Gyms")
    elif typeid == 6:
        text = _("Hatch {0} Eggs")
    elif typeid == 7:
        if re.search(r'"type": 9', condition) is not None:
            text = _("Win {0} Gym Battles")
        elif re.search(r'"type": 10', condition) is not None:
            text = _("Use a supereffective Charged Attack in {0} Gym battles")
        else:
            text = _("Battle in a Gym {0} times")
    elif typeid == 8:
        if re.search(r'"type": 6', condition) is not None:
            text = _("Win {0} Raids")
            if re.search(r'"raid_level": \[3, 4, 5(.*)\]', condition) is not None:
                text = _('Win a level 3 or higher raid')
            if re.search(r'"raid_level": \[2, 3, 4, 5(.*)\]', condition) is not None:
                text = _('Win a level 2 or higher raid')
            if re.search(r'"raid_level": \[6\]', condition) is not None:
                text = _('Win a Mega raid')
        else:
            text = _("Battle in {0} Raids")
    elif typeid == 10:
        text = _("Transfer {0} Pokemon")
    elif typeid == 11:
        text = _("Favourite {0} Pokemon")
    elif typeid == 13:
        text = _('Use {0} {type}Berries to help catch Pokemon')
        arr['type'] = ""
        match_object = re.search(r'"item": ([0-9]+)', condition)
        if match_object is not None:
            arr['type'] = items[match_object.group(
                1)]['name'].replace(_(' Berry'), '') + " "
    elif typeid == 14:
        text = _('Power up Pokemon {0} times')
    elif typeid == 15 or typeid == 43:
        arr['mega'] = ""
        text = _("{mega}Evolve {0} Pokemon")
        if typeid == 43:
            arr['mega'] = _("Mega ")

        for con in condition_dict:
            if con.get('type', 0) == 11:
                text = _("Use an item to {mega}evolve {0} Pokemon")
                # Try to find the exact evolution item needed
                # [{"type": 11, "with_item": {"item": 1106}}]
                with_item = con.get('with_item', {}).get('item', None)
                if with_item is not None:
                    text = _('Use {item} to {mega}evolve {0} Pokemon')
                    arr['item'] = items[str(with_item)]['name']
            if con.get('type', 0) == 1:
                text = _("{mega}Evolve {0} {type}Pokemon")
                arr['wb'] = ""
                arr['type'] = ""
                arr['poke'] = ""
                match_object = re.search(
                    r'"pokemon_type": \[([0-9, ]+)\]', condition)
                if match_object is not None:
                    pt = match_object.group(1).split(', ')
                    last = len(pt)
                    cur = 1
                    if last == 1:
                        arr['type'] = pokemon_types[pt[0]].title() + _('-type ')
                    else:
                        for ty in pt:
                            arr['type'] += (_('or ') if last == cur else '') + pokemon_types[ty].title() + (
                                _('-type ') if last == cur else '-, ')
                            cur += 1
            if con.get('type', 0) == 2:
                arr['wb'] = ""
                arr['type'] = ""
                arr['poke'] = ""

                match_object = re.search(r'"pokemon_ids": \[([0-9, ]+)\]', condition)
                if match_object is not None:
                    pt = match_object.group(1).split(', ')
                    last = len(pt)
                    cur = 1
                    if last == 1:
                        arr['poke'] = i8ln(pokemonname(pt[0]))
                    else:
                        for ty in pt:
                            arr['poke'] += (_('or ') if last == cur else '') + i8ln(pokemonname(ty)) + (
                                '' if last == cur else ', ')
                            cur += 1
                    text = _('{mega}Evolve {0} {poke}')
    elif typeid == 16:
        arr['inrow'] = ""
        arr['curve'] = ""
        arr['type'] = ""
        if re.search(r'"type": 14', condition) is not None:
            arr['inrow'] = _(" in a row")
        if re.search(r'"type": 15', condition) is not None:
            arr['curve'] = _("Curveball ")
        match_object = re.search(r'"throw_type": ([0-9]{2})', condition)
        if match_object is not None:
            arr['type'] = throw_types[match_object.group(1)] + " "
        text = _("Make {0} {type}{curve}Throws{inrow}")
    elif typeid == 17:
        text = _('Earn {0} Candies walking with your buddy')
    elif typeid == 22:
        if int(target) == int(1):
            text = _('Make a new friend')
        else:
            text = _('Make {0} new friends')
    elif typeid == 23:
        text = _('Trade {0} Pokemon')
        arr['distance'] = ""
        if re.search(r'"type": 25', condition) is not None:
            arr['distance'] = re.search(r'"distance_km": ([0-9, ]+)', condition).group(1)
            if int(target) == int(1):
                text = _('Trade Pokemon caught {distance} km apart')
            else:
                text = _('Trade {0} Pokemon caught {distance} km apart')
    elif typeid == 24:
        text = _('Send {0} gifts to friends')
    elif typeid == 27:
        for con in condition_dict:
            if con.get('type', 0) == 22:
                # PVP against team leader.
                text = _('Battle a Team Leader {0} times')
            elif con.get('type') == 23:
                gotta_win = con.get('with_pvp_combat', {}).get('requires_win') is True

                if gotta_win:
                    text = _('Win a battle against another Trainer {0} times')
                else:
                    text = _('Battle another Trainer {0} times')

                in_go_battle_league = any(
                    x in con.get('with_pvp_combat', {}).get('combat_league_template_id', []) for x in
                    ["COMBAT_LEAGUE_VS_SEEKER_GREAT", "COMBAT_LEAGUE_VS_SEEKER_ULTRA",
                     "COMBAT_LEAGUE_VS_SEEKER_MASTER"])
                vs_player = any(
                    x in con.get('with_pvp_combat', {}).get('combat_league_template_id', []) for x in
                    ["COMBAT_LEAGUE_DEFAULT_GREAT", "COMBAT_LEAGUE_DEFAULT_ULTRA",
                     "COMBAT_LEAGUE_DEFAULT_MASTER"])
                if not vs_player and in_go_battle_league and gotta_win:
                    text = _('Win in the GO Battle League {0} times')
                elif in_go_battle_league and not vs_player:
                    text = _('Battle in the GO Battle League {0} times')
    elif typeid == 28:
        # Take snapshots quest
        if re.search(r'"type": 28', condition) is not None:
            text = _("Take {0} snapshots of your Buddy")
        elif re.search(r'"type": 2', condition) is not None:
            arr['poke'] = ""

            match_object = re.search(
                r'"pokemon_ids": \[([0-9, ]+)\]', condition)
            if match_object is not None:
                pt = match_object.group(1).split(', ')
                last = len(pt)
                cur = 1
                if last == 1:
                    arr['poke'] = i8ln(pokemonname(pt[0]))
                else:
                    for ty in pt:
                        arr['poke'] += (_('or ') if last == cur else '') + i8ln(pokemonname(ty)) + (
                            '' if last == cur else ', ')
                        cur += 1
                text = _("Take {0} snapshots of {poke}")
        elif re.search(r'"type": 1', condition) is not None:
            text = _("Take {0} snapshots of {type} Pokemon")
            arr['wb'] = ""
            arr['type'] = ""
            arr['poke'] = ""
            match_object = re.search(
                r'"pokemon_type": \[([0-9, ]+)\]', condition)
            if match_object is not None:
                pt = match_object.group(1).split(', ')
                last = len(pt)
                cur = 1
                if last == 1:
                    arr['type'] = pokemon_types[pt[0]].title() + _('-type ')
                else:
                    for ty in pt:
                        arr['type'] += (_('or ') if last == cur else '') + pokemon_types[ty].title() + (
                            _('-type ') if last == cur else '-, ')
                        cur += 1
    elif typeid == 29:
        # QUEST_BATTLE_TEAM_ROCKET Team Go rucket grunt batles.
        if int(target) == int(1):
            text = _('{verb} a Team Rocket Grunt')

        # TODO there's protos for battling team leaders and such as well,which are not supported (yet)
        arr['verb'] = _('Battle')
        for con in condition_dict:
            if con.get('type', 0) == 27:
                rocket_cat =  con.get('with_invasion_character', {}).get('category', [])
                if 3 in rocket_cat and 4 in rocket_cat and 5 in rocket_cat:
                    text = _('{verb} {0} times against Team GO Rocket Leaders')
            if con.get('type', 0) == 18:
                # Condition type 18 means win a battle
                arr['verb'] = _('Defeat')
        if text == _('{verb} {0} times against Team GO Rocket Leaders'):
            if int(target) == int(1):
                text = _('{verb} a Team GO Rocket Leader')
            else:
                text = _('{verb} a Team GO Rocket Leader {0} times')
    elif typeid == 36:
        arr['level'] = ""
        for con in condition_dict:
            if con.get('type', 0) == 28:
                level = con.get('with_buddy', {}).get('min_buddy_level', 0)
                arr['level'] = buddyLevels.get(level, level)

    if quest_template is not None and quest_template in quest_templates:
        text = _(quest_templates[quest_template])

    if int(target) == int(1):
        text = text.replace(_(' Eggs'), _('n Egg'))
        text = text.replace(_(' Raids'), _(' Raid'))
        text = text.replace(_(' Battles'), _(' Battle'))
        text = text.replace(_(' candies'), _(' candy'))
        text = text.replace(_(' gifts'), _(' gift'))
        text = text.replace(_(' Pokestops'), _(' Pokestop'))
        text = text.replace(_(' {0} snapshots'), _(' a snapshot'))
        text = text.replace(_('Make {0} {type}{curve}Throws'), _('Make a {type}{curve}Throw'))
        text = text.replace(_(' {0} times'), '')
        text = text.replace(_('{0} hearts'), _('a heart'))
        arr['0'] = _("a")

    for key, val in arr.items():
        text = text.replace('{' + key + '}', str(val))

    text = text.replace('  ', ' ').strip()
    return text
Ejemplo n.º 9
0
    def game_stats_shiny_v2(self):
        logger.debug('game_stats_shiny_v2')
        timestamp_from = request.args.get('from', None)
        if (timestamp_from):
            timestamp_from = self.local2utc(int(timestamp_from))
            logger.debug('using timestamp_from: {}', timestamp_from)

        timestamp_to = request.args.get('to', None)
        if (timestamp_to):
            timestamp_to = self.local2utc(int(timestamp_to))
            logger.debug('using timestamp_to: {}', timestamp_to)

        tmp_perworker_v2 = {}
        data = self._db_stats_reader.get_shiny_stats_v2(
            timestamp_from, timestamp_to)
        # SELECT pokemon.pokemon_id, pokemon.form, pokemon.latitude, pokemon.longitude, pokemon.gender, pokemon.costume, tr.count, tr.timestamp_scan, tr.worker, pokemon.encounter_id
        found_shiny_mon_id = []
        shiny_count = {}
        mon_names = {}
        tmp_perhour_v2 = {}

        if data is None or len(data) == 0:
            return jsonify({'empty': True})

        shiny_stats_v2 = []
        for dat in data:
            form_suffix = "%02d" % form_mapper(dat[0], dat[1])
            mon = "%03d" % dat[0]
            monPic = 'asset/pokemon_icons/pokemon_icon_' + mon + '_' + form_suffix + '_shiny.png'
            monName_raw = (get_raid_boss_cp(dat[0]))
            monName = i8ln(monName_raw['name'])
            mon_names[dat[0]] = monName
            found_shiny_mon_id.append(
                mon
            )  # append everything now, we will set() it later to remove duplicates
            if dat[8] not in tmp_perworker_v2:
                tmp_perworker_v2[dat[8]] = 0
            tmp_perworker_v2[dat[8]] += 1

            if dat[0] not in shiny_count:
                shiny_count[dat[0]] = {}
            if dat[1] not in shiny_count[dat[0]]:
                shiny_count[dat[0]][dat[1]] = 0
            shiny_count[dat[0]][dat[1]] += 1

            # there is later strftime which converts to local time too, can't use utc2local - it will do double shift
            timestamp = datetime.datetime.fromtimestamp(dat[7])

            if timestamp.hour in tmp_perhour_v2:
                tmp_perhour_v2[timestamp.hour] += 1
            else:
                tmp_perhour_v2[timestamp.hour] = 1

            shiny_stats_v2.append({
                'img':
                monPic,
                'name':
                monName,
                'worker':
                dat[8],
                'lat':
                dat[2],
                'lat_5':
                "{:.5f}".format(dat[2]),
                'lng_5':
                "{:.5f}".format(dat[3]),
                'lng':
                dat[3],
                'timestamp':
                timestamp.strftime(self._datetimeformat),
                'form':
                dat[1],
                'mon_id':
                dat[0],
                'encounter_id':
                str(dat[9])
            })

        global_shiny_stats_v2 = []
        data = self._db_stats_reader.get_shiny_stats_global_v2(
            set(found_shiny_mon_id), timestamp_from, timestamp_to)
        for dat in data:
            if dat[1] in shiny_count and dat[2] in shiny_count[dat[1]]:
                odds = round(dat[0] / shiny_count[dat[1]][dat[2]], 0)
                form_suffix = "%02d" % form_mapper(dat[1], dat[2])
                mon = "%03d" % dat[1]
                monPic = 'asset/pokemon_icons/pokemon_icon_' + mon + '_' + form_suffix + '_shiny.png'
                global_shiny_stats_v2.append({
                    'name':
                    mon_names[dat[1]],
                    'count':
                    dat[0],
                    'img':
                    monPic,
                    'shiny':
                    shiny_count[dat[1]][dat[2]],
                    'odds':
                    odds,
                    'mon_id':
                    dat[1],
                    'form':
                    dat[2],
                    'gender':
                    dat[3],
                    'costume':
                    dat[4]
                })

        shiny_stats_perworker_v2 = []
        for worker in tmp_perworker_v2:
            shiny_stats_perworker_v2.append({
                'name': worker,
                'count': tmp_perworker_v2[worker]
            })

        shiny_stats_perhour_v2 = []
        for hour in tmp_perhour_v2:
            shiny_stats_perhour_v2.append([hour, tmp_perhour_v2[hour]])

        stats = {
            'empty': False,
            'shiny_statistics': shiny_stats_v2,
            'global_shiny_statistics': global_shiny_stats_v2,
            'per_worker': shiny_stats_perworker_v2,
            'per_hour': shiny_stats_perhour_v2
        }
        return jsonify(stats)
Ejemplo n.º 10
0
    def shiny_stats_data(self):
        # shiny hour

        shiny_hour_temp = {}
        shiny_hour_calc = {}
        shiny_hour = []
        data = self._db_stats_reader.get_shiny_stats_hour()
        for dat in data:
            if dat[1] not in shiny_hour_temp:
                shiny_hour_temp[dat[1]] = dat[0]

        for dat in shiny_hour_temp:
            if shiny_hour_temp[dat] not in shiny_hour_calc:
                shiny_hour_calc[shiny_hour_temp[dat]] = 0
            shiny_hour_calc[shiny_hour_temp[dat]] += 1

        for dat in sorted(shiny_hour_calc):
            sht = ([
                self.utc2local(dat * 60 * 60) * 1000, shiny_hour_calc[dat]
            ])
            shiny_hour.append(sht)

        shiny_stats = []
        shiny_worker = {}
        shiny_avg = {}
        data = self._db_stats_reader.get_shiny_stats()
        for dat in data:
            form_suffix = "%02d" % form_mapper(dat[2], dat[5])
            mon = "%03d" % dat[2]
            monPic = 'asset/pokemon_icons/pokemon_icon_' + mon + '_' + form_suffix + '_shiny.png'
            monName_raw = (get_raid_boss_cp(dat[2]))
            monName = i8ln(monName_raw['name'])
            diff: int = dat[0]
            if diff == 0:
                logger.warning(
                    'No deeper mon stats are possible - not enought data '
                    '(check config.ini // game_stats_raw)')
                diff = 1

            ratio = round(dat[1] * 100 / diff, 2)
            if dat[3] not in shiny_worker: shiny_worker[dat[3]] = 0
            shiny_worker[dat[3]] += dat[1]

            if dat[2] not in shiny_avg: shiny_avg[dat[2]] = {}
            if dat[5] not in shiny_avg[dat[2]]:
                shiny_avg[dat[2]][dat[5]] = {}
                shiny_avg[dat[2]][dat[5]]['total_shiny'] = []
                shiny_avg[dat[2]][dat[5]]['total_nonshiny'] = []

            shiny_avg[dat[2]][dat[5]]['total_shiny'].append(dat[1])
            shiny_avg[dat[2]][dat[5]]['total_nonshiny'].append(diff)

            shiny_stats.append({
                'sum':
                dat[0],
                'shiny':
                dat[1],
                'img':
                monPic,
                'name':
                monName,
                'ratio':
                ratio,
                'worker':
                dat[3],
                'encounterid':
                dat[4],
                'periode':
                datetime.datetime.fromtimestamp(dat[6]).strftime(
                    self._datetimeformat)
            })

        shiny_stats_avg = []
        for dat in shiny_avg:
            for form_dat in shiny_avg[dat]:
                form_suffix = "%02d" % form_mapper(dat, form_dat)
                mon = "%03d" % dat
                monPic = 'asset/pokemon_icons/pokemon_icon_' + mon + '_' + form_suffix + '_shiny.png'
                monName_raw = (get_raid_boss_cp(dat))
                monName = i8ln(monName_raw['name'])

                total_shiny_encounters = sum(
                    shiny_avg[dat][form_dat]['total_shiny'])
                total_nonshiny_encounters = sum(
                    shiny_avg[dat][form_dat]['total_nonshiny'])
                shiny_avg_click = round(
                    total_nonshiny_encounters / total_shiny_encounters, 0)

                shiny_stats_avg.append({
                    'name': monName,
                    'img': monPic,
                    'total_shiny_encounters': total_shiny_encounters,
                    'total_nonshiny_encounters': total_nonshiny_encounters,
                    'click_for_shiny': shiny_avg_click
                })

        shiny_stats_worker = []
        for dat in shiny_worker:
            shiny_stats_worker.append({
                'sum': shiny_worker[dat],
                'worker': dat
            })

        stats = {
            'shiny': shiny_stats,
            'shiny_worker': shiny_stats_worker,
            'shiny_hour': shiny_hour,
            'shiny_stats_avg': shiny_stats_avg
        }
        return jsonify(stats)