Beispiel #1
0
def spawn_pokemon(channel, name=None):
    """Spawn the pokemon with given name in the channel.

    Creates a new Pokemon instance following the name or random if None given.
    The notification of pokemon appearance is then send to a specified
    channel and users can catch the pokemon.
    """
    if name:
        pkmn = Pokemon.spawn_from_name(name)
    else:
        pkmn = Pokemon.spawn_random()
    log.info('spawning {}'.format(pkmn))
    img_url = pkmn.get_img_url()
    em = discord.Embed(title='A wild {} has appeared!'.format(pkmn.name),
                       description=('Type \'catch {}\' before '
                                    'it escapes.'.format(pkmn.name)),
                       colour=0x00AE86)
    em.set_image(url=img_url)
    yield from client.send_message(channel, embed=em)
    message = yield from client.wait_for_message(300,
                                                 channel=channel,
                                                 content='catch {}'.format(
                                                     pkmn.name))
    if message is None:
        yield from client.send_message(channel,
                                       '{} escaped.'.format(pkmn.name))
    else:
        add_caught_pokemon(message.author, pkmn, channel)
 def make_pokemon(self, name, type_name):
     trainer_id = users.get_current_user().user_id()
     pokemon = Pokemon(parent=trainer_key(trainer_id)) #Define a Trainer as the parent of the new pokemon. This trainer's key is the current user id. Thus every user has his own pokemon list
     pokemon.img_url = self.get_pokemon_image(name)
     pokemon.name = name
     pokemon.type = Type.query(Type.name == type_name).get()
     return pokemon
Beispiel #3
0
def start_trade(message):
    seller = message.author
    buyer = message.mentions[0]
    channel = message.channel

    tokens = message.content.split()
    pkmn_name = ' '.join(tokens[3:])
    database.connect()
    try:
        seller_pkmn = Pokemon.get(Pokemon.owner_id == seller.id,
                                  Pokemon.name == pkmn_name)
    except Pokemon.DoesNotExist:
        return
    finally:
        database.close()

    # pokemon exists, send invitation to trade
    text = ("{}, {} invites you to trade and offers {}.\n"
            "Enter 'pkmn offer {} <pokemon>' to trade.".format(
                buyer.mention, seller.name, pkmn_name, seller.mention))
    yield from client.send_message(channel, text)

    # wait for buyer to accept trade
    def check(message):
        return message.content.startswith('pkmn offer {}'.format(
            seller.mention))

    response = yield from client.wait_for_message(300,
                                                  channel=channel,
                                                  author=buyer,
                                                  check=check)
    if not response:
        yield from client.send_message(channel, 'Trade cancelled.')
        return
    tokens = response.content.split()
    pkmn_name = ' '.join(tokens[3:])
    database.connect()
    try:
        buyer_pkmn = Pokemon.get(Pokemon.owner_id == buyer.id,
                                 Pokemon.name == pkmn_name)
        buyer_pkmn.owner_id = seller.id
        seller_pkmn.owner_id = buyer.id
        buyer_pkmn.storage = seller_pkmn.storage = BOX
        buyer_pkmn.save()
        seller_pkmn.save()
        database.commit()
    except Pokemon.DoesNotExist:
        return
    except:
        database.rollback()
        raise
    finally:
        database.close()

    yield from client.send_message(channel, 'Trade completed.')
Beispiel #4
0
    def apply_ailment(self, move_used: Move, defending_pokemon: Pokemon):
        ailment = move_used.info.ailment
        if (any(status.non_volatile for status in defending_pokemon.statuses)
                and ailment.non_volatile):
            # A Pokémon cannot gain a non-volatile status if it's already afflicted by another one.
            return

        if ailment == Ailment.UNKNOWN:
            # Tri Attack was used
            # We don't support freeze, so return if it (i.e. unknown) is selected randomly
            ailment = random.choice(
                [Ailment.UNKNOWN, Ailment.BURN, Ailment.PARALYSIS])
            if ailment == Ailment.UNKNOWN:
                return
        # Fire-type Pokemon cannot be burned by a Fire-type move
        if ailment == Ailment.BURN and (Type.FIRE
                                        not in defending_pokemon.species.types
                                        or move_used.info.type != Type.FIRE):
            self.print_battle_text(
                f"{defending_pokemon.nickname} is burned by the attack!")
            defending_pokemon.statuses.add(PokemonStatus.BURNED)
            # TODO: Halve its Attack
        # Ground-type Pokemon cannot be paralyzed by an Electric-type move
        elif ailment == Ailment.PARALYSIS and (
                Type.GROUND not in defending_pokemon.species.types
                or move_used.info.type != Type.ELECTRIC):
            self.print_battle_text(
                f"{defending_pokemon.nickname} is paralyzed by the attack!")
            defending_pokemon.statuses.add(PokemonStatus.PARALYZED)
            # TODO: Decrease Speed by 75%
        # Poison-type Pokemon cannot be poisoned
        elif ailment == Ailment.POISON and Type.POISON not in defending_pokemon.species.types:
            if move_used.info.api_id == 92:
                # The "Toxic" move was used
                self.print_battle_text(
                    f"{defending_pokemon.nickname} is badly poisoned by the attack!"
                )
                defending_pokemon.statuses.add(PokemonStatus.BADLY_POISONED)
            else:
                self.print_battle_text(
                    f"{defending_pokemon.nickname} is poisoned by the attack!")
                defending_pokemon.statuses.add(PokemonStatus.POISONED)
        elif ailment == Ailment.CONFUSION:
            self.print_battle_text(
                f"{defending_pokemon.nickname} is confused by the attack!")
            defending_pokemon.statuses.add(PokemonStatus.CONFUSED)
            defending_pokemon.confusion_turns = random.randint(1, 5)
        # Pokemon can only be bound by one binding move at a time
        elif ailment == Ailment.TRAP and PokemonStatus.BOUND not in defending_pokemon.statuses:
            self.print_battle_text(
                f"{defending_pokemon.nickname} is trapped by the attack!")
            defending_pokemon.statuses.add(PokemonStatus.BOUND)
            defending_pokemon.bound_turns = random.choices(
                [2, 3, 4, 5], [0.375, 0.375, 0.125, 0.125])[0]
Beispiel #5
0
def create_pokemon():
    pokemon = load_json('pokemon.json')

    for next_pokemon in pokemon:
        print("working pokemon" + next_pokemon)
        name = next_pokemon
        type = pokemon[next_pokemon]['type']
        move = pokemon[next_pokemon]['moves']
        attack = pokemon[next_pokemon]['attack']
        defense = pokemon[next_pokemon]['defense']
        spdefense = pokemon[next_pokemon]['special-defense']
        specialattack = pokemon[next_pokemon]['special-attack']
        image = pokemon[next_pokemon]['img']

        newPokemon = Pokemon(name=name,
                             type=type,
                             move=move,
                             attack=attack,
                             defense=defense,
                             spdefense=spdefense,
                             specialattack=specialattack,
                             image=image)
        # After I create the book, I can then add it to my session.
        session.add(newPokemon)
        # commit the session to my DB.
        session.commit()
Beispiel #6
0
def start_training(message):
    """Command: start training - starts a one hour training."""
    if message.author.id in stop_training_events:
        yield from client.send_message(message.channel,
                                       "You are already training.")
        return
    stop_event = asyncio.Event()
    stop_training_events[message.author.id] = stop_event
    start_time = client.loop.time() - 5
    handler = client.loop.call_later(3600, stop_event.set)
    yield from client.send_message(message.channel, "Training started.")
    yield from stop_event.wait()
    handler.cancel()
    del stop_training_events[message.author.id]
    delta_time = (client.loop.time() - start_time) // 60
    database.connect()
    try:
        team = (Pokemon.select().where((Pokemon.owner_id == message.author.id)
                                       & (Pokemon.storage == TEAM)))
        for pkmn in team:
            pkmn.add_exp(delta_time)
            pkmn.save()
        database.commit()
    finally:
        database.close()
    ensure_future(
        client.send_message(
            message.author,
            "Training finished. You trained for %u minutes." % delta_time))
Beispiel #7
0
def init_db():
    """Import all modules here that might define models so that
    they will be registered properly on the metadata. Otherwise
    you will have to import them first before calling init_db()
    """
    from models import Department, Employee, Pokemon, Role
    Base.metadata.drop_all(bind=engine)
    Base.metadata.create_all(bind=engine)

    engineering = Department(name="Engineering")
    db_session.add(engineering)
    hr = Department(name="Human Resources")
    db_session.add(hr)

    manager = Role(name="manager")
    db_session.add(manager)
    engineer = Role(name="engineer")
    db_session.add(engineer)

    peter = Employee(name="Peter", department=engineering, role=engineer)
    db_session.add(peter)
    roy = Employee(name="Roy", department=engineering, role=engineer)
    db_session.add(roy)
    tracy = Employee(name="Tracy", department=hr, role=manager)
    db_session.add(tracy)
    db_session.commit()

    charzard = Pokemon(name="Charzard", level=100, type="fire")
    db_session.add(charzard)
    db_session.commit()
Beispiel #8
0
def pokemon(pokemon_id):
    if request.method == "GET":
        try:
            obj = Pokemon.get(Pokemon.id == pokemon_id)
            return SerializadorPokemon(obj).data
        except Pokemon.DoesNotExist:
            return Response(status=STATUS_NOT_FOUND)

    elif request.method == "PUT":
        attrs = json.loads(request.data.decode("utf8"))
        pokebola = Pokemon.get(Pokemon.id == pokemon_id)
        serializador = SerializadorPokemon(pokebola, attrs=attrs)
        serializador.save()
        return Response(serializador.data,
                        status=STATUS_CREATED,
                        mimetype="application/json")
Beispiel #9
0
def step_impl(context):
    for row in context.table:
        pokemon = Pokemon(
            row['name'],
            attack=row['attack'],
            defense=row['defense'],
            )
        setattr(context, row['name'], pokemon)
Beispiel #10
0
 def pokemon_remove_group(self, request):
     """ POKEMON-REMOVE-GROUP: remove the group association """
     if not request.from_datastore:
         return Pokemon(given_name="ID of pokemon was not found")
     this_pokemon = request.key.get()
     this_pokemon.group = None
     this_pokemon.put()
     return this_pokemon
Beispiel #11
0
def pokemon(pokemon_id):
    if request.method == "GET":
        try:
            obj = Pokemon.get(Pokemon.id == pokemon_id)
            return SerializadorPokemon(obj).data
        except Pokemon.DoesNotExist:
            return Response(status=STATUS_NOT_FOUND)

    elif request.method == "PUT":
        attrs = json.loads(request.data.decode("utf8"))
        pokebola = Pokemon.get(Pokemon.id == pokemon_id)
        serializador = SerializadorPokemon(pokebola, attrs=attrs)
        serializador.save()
        return Response(
            serializador.data,
            status=STATUS_CREATED,
            mimetype="application/json"
        )
Beispiel #12
0
def list_pokemon_team(message):
    """Command: team - list the pokemons in user's team."""
    database.connect()
    text = 'Your team:\n' + '\n'.join(
        " - **{0.name}** lv. {0.level}".format(pkmn) for pkmn in
        (Pokemon.select().where((Pokemon.owner_id == message.author.id)
                                & (Pokemon.storage == TEAM))))
    database.close()
    yield from client.send_message(message.channel, text)
Beispiel #13
0
 def test_pokemon_3(self):
     pokemon = Pokemon.get_all()
     p = []
     for poke in pokemon:
         p.append({c.name: getattr(poke, c.name) for c in poke.__table__.columns})
     self.assertEqual(p[0]["POKEMON_ID"], 1)
     self.assertEqual(p[0]["POKEMON_NAME"], "Bulbasaur")
     self.assertEqual(p[1]["POKEMON_ID"], 2)
     self.assertEqual(p[1]["POKEMON_NAME"], "Ivysaur")
Beispiel #14
0
    def test_source_insert_1(self):
        s = Pokemon(name = "pikachu", type = "electric", move = "bash", attack = "100", defense = "50", spdefense = "50", specialattack = "50", image = "www.pikachu.com")
        session.add(s)
        session.commit()


        r = session.query(Pokemon).filter_by(name = "pikachu").one()
        self.assertEqual(str(r.type), 'electric')

        session.query(Pokemon).filter_by(name = "pikachu").delete()
        session.commit()
Beispiel #15
0
    def test_source_insert_2(self):
        s = Pokemon(name = "william", type = "unknown", move = "rest", attack = "100", defense = "100", spdefense = "100", specialattack = "100", image = "www.aol.com")
        session.add(s)
        session.commit()


        r = session.query(Pokemon).filter_by(name = "william").one()
        self.assertEqual(str(r.spdefense), '100')

        session.query(Pokemon).filter_by(name = "william").delete()
        session.commit()
Beispiel #16
0
    def test_source_insert_3(self):
        s = Pokemon(name = "deyuan", type = "str8_fire", move = "ancient_power", attack = "101", defense = "101", spdefense = "101", specialattack = "101", image = "www.google.com")
        session.add(s)
        session.commit()


        r = session.query(Pokemon).filter_by(name = "deyuan").one()
        self.assertEqual(str(r.image), 'www.google.com')

        session.query(Pokemon).filter_by(name = "deyuan").delete()
        session.commit()
Beispiel #17
0
 def test_pokemon_1(self):
     pokemon = Pokemon.get_id(1)
     p = {c.name: getattr(pokemon, c.name) for c in pokemon.__table__.columns}
     self.assertEqual(p["POKEMON_ID"], 1)
     self.assertEqual(p["POKEMON_NAME"], "Bulbasaur")
     self.assertEqual(p["POKEMON_HP"], 45)
     self.assertEqual(p["POKEMON_ATK"], 49)
     self.assertEqual(p["POKEMON_DEF"], 49)
     self.assertEqual(p["POKEMON_SPATK"], 65)
     self.assertEqual(p["POKEMON_SPDEF"], 65)
     self.assertEqual(p["POKEMON_SPD"], 45)
Beispiel #18
0
 def _pokemon_from_species(self,
                           poke_species: PokemonSpecies,
                           level: int = 100) -> Pokemon:
     full_stats = self.calc_all_stats(poke_species.base_stats, level)
     move_set = self._random_moves(poke_species)
     nickname = self._random_name()
     return Pokemon(poke_species,
                    hp=full_stats.total_hp,
                    stats=full_stats,
                    move_set=move_set,
                    nickname=nickname)
Beispiel #19
0
    def pokemon_insert(self, pokemon):
        """ POKEMON-ADD: add a pokemon under the user's account """
        if pokemon.from_datastore:
            pokemon_with_parent = pokemon
            pokemon_with_parent.put()
        else:
            user = endpoints.get_current_user()
            pokemon_with_parent = Pokemon(parent=get_parent_key(user),
                                          given_name=pokemon.given_name,
                                          species_name=pokemon.species_name,
                                          species_id=pokemon.species_id,
                                          level=pokemon.level)

            this_key = pokemon_with_parent.put()
            this_instance = this_key.get()
            this_instance.pokemon_key = this_key.urlsafe()
            this_instance.put()
            pokemon_with_parent = this_instance

        return pokemon_with_parent
Beispiel #20
0
 def test_pokemon_7(self):
     pokemon = Pokemon.get_id(74)
     p = {c.name: getattr(pokemon, c.name) for c in pokemon.__table__.columns}
     self.assertEqual(p["POKEMON_ID"], 74)
     self.assertEqual(p["POKEMON_NAME"], "Geodude")
     self.assertEqual(p["POKEMON_HP"], 40)
     self.assertEqual(p["POKEMON_ATK"], 80)
     self.assertEqual(p["POKEMON_DEF"], 100)
     self.assertEqual(p["POKEMON_SPATK"], 30)
     self.assertEqual(p["POKEMON_SPDEF"], 30)
     self.assertEqual(p["POKEMON_SPD"], 20)
     self.assertEqual(p["POKEMON_EV"], "DEF: 1 ")
Beispiel #21
0
def insert_pokemon(session, pokemon, time):
    pokemon_obj = Pokemon(
        encounter_id=str(pokemon['encounter_id']),
        spawnpoint_id=str(pokemon['spawnpoint_id']),
        disappear_time=dt_from_epoch(int(pokemon['disappear_time'])),
        pokemon_id=int(pokemon['pokemon_id']),
        pokemon_name=unicode(pokemon['pokemon_name']),
        time=time,
        geom='SRID=4326;POINT(%s %s)' %
        (float(pokemon['longitude']), float(pokemon['latitude'])))

    session.merge(pokemon_obj)
Beispiel #22
0
def pokemons():
    if request.method == "GET":
        return Response(SerializadorPokemon(Pokemon.select(), many=True).data,
                        status=STATUS_OK,
                        mimetype="application/json")
    elif request.method == "POST":
        attrs = json.loads(request.data.decode("utf8"))
        serializador = SerializadorPokemon(attrs=attrs)
        serializador.save()
        return Response(serializador.data,
                        status=STATUS_CREATED,
                        mimetype="application/json")
Beispiel #23
0
 def test_pokemon_5(self):
     pokemon = Pokemon.get_id(373)
     p = {c.name: getattr(pokemon, c.name) for c in pokemon.__table__.columns}
     self.assertEqual(p["POKEMON_ID"], 373)
     self.assertEqual(p["POKEMON_NAME"], "Salamence")
     self.assertEqual(p["POKEMON_HP"], 95)
     self.assertEqual(p["POKEMON_ATK"], 135)
     self.assertEqual(p["POKEMON_DEF"], 80)
     self.assertEqual(p["POKEMON_SPATK"], 110)
     self.assertEqual(p["POKEMON_SPDEF"], 80)
     self.assertEqual(p["POKEMON_SPD"], 100)
     self.assertEqual(p["POKEMON_EV"], "ATK: 3 ")
Beispiel #24
0
 def test_pokemon_4(self):
     pokemon = Pokemon.get_id(13)
     p = {c.name: getattr(pokemon, c.name) for c in pokemon.__table__.columns}
     self.assertEqual(p["POKEMON_ID"], 13)
     self.assertEqual(p["POKEMON_NAME"], "Weedle")
     self.assertEqual(p["POKEMON_HP"], 40)
     self.assertEqual(p["POKEMON_ATK"], 35)
     self.assertEqual(p["POKEMON_DEF"], 30)
     self.assertEqual(p["POKEMON_SPATK"], 20)
     self.assertEqual(p["POKEMON_SPDEF"], 20)
     self.assertEqual(p["POKEMON_SPD"], 50)
     self.assertEqual(p["POKEMON_EV"], "SPD: 1 ")
Beispiel #25
0
 def test_pokemon_6(self):
     pokemon = Pokemon.get_id(218)
     p = {c.name: getattr(pokemon, c.name) for c in pokemon.__table__.columns}
     self.assertEqual(p["POKEMON_ID"], 218)
     self.assertEqual(p["POKEMON_NAME"], "Slugma")
     self.assertEqual(p["POKEMON_HP"], 40)
     self.assertEqual(p["POKEMON_ATK"], 40)
     self.assertEqual(p["POKEMON_DEF"], 40)
     self.assertEqual(p["POKEMON_SPATK"], 70)
     self.assertEqual(p["POKEMON_SPDEF"], 40)
     self.assertEqual(p["POKEMON_SPD"], 20)
     self.assertEqual(p["POKEMON_EV"], "SPATK: 1 ")
Beispiel #26
0
def withdraw_pokemon(message):
    database.connect()
    num = (Pokemon.select().where((Pokemon.storage == TEAM) & (
        Pokemon.owner_id == message.author.id)).count())
    if num >= TEAM_SIZE:
        database.close()
        yield from client.send_message(message.channel, 'Your team is full.')
        return
    try:
        tokens = message.content.split()
        pkmn_name = ' '.join(tokens[2:])
        pkmn = (
            Pokemon.select().where((Pokemon.storage == BOX)
                                   & (Pokemon.owner_id == message.author.id)
                                   & (Pokemon.name == pkmn_name)).first())
        pkmn.storage = TEAM
        pkmn.save()
    finally:
        database.commit()
        database.close()
    yield from client.send_message(message.channel,
                                   '{} withdrawn.'.format(pkmn.name))
Beispiel #27
0
    def group_delete(self, request):
        """ GROUP-DELETE: deletes a specific group under the user's account """
        if not request.from_datastore:
            return PokemonGroup(
                group_name="ERROR: group key not found in datastore")

        #remove any pokemon association to this group
        all_pokemons = Pokemon.query(Pokemon.group == request.key).fetch()
        for pokemon in all_pokemons:
            pokemon.group = None
            pokemon.put()

        request.key.delete()
        return PokemonGroup(group_name="Group has been deleted.")
Beispiel #28
0
    def is_hit(self, attacking_pokemon: Pokemon, defending_pokemon: Pokemon,
               move_used: MoveInfo):
        # TODO: Account for stage multipliers (stat changers)
        if move_used.accuracy is None:
            return True

        if defending_pokemon.has_status(PokemonStatus.INVULNERABLE):
            return False

        accuracy_val = math.floor(move_used.accuracy * 255)
        threshold = max(min(accuracy_val, 255), 1)
        # Yes this does actually implement the possible miss for a 100% accuracy move bug in Gen 1
        rand_val = random.randint(0, 255)
        return rand_val < threshold
Beispiel #29
0
def raw_data():
    """ Gets raw data for pokemons/gyms/pokestops via REST """
    pokemons, gyms, pokestops = [], [], []
    for pokemon in Pokemon.select():
        pokemons.append(model_to_dict(pokemon))
    for gym in Gym.select():
        gyms.append(model_to_dict(gym))
    for pokestop in Pokestop.select():
        pokestops.append(model_to_dict(pokestop))
    return flask.jsonify(
        pokemons=pokemons,
        gyms=gyms,
        pokestops=pokestops
    )
Beispiel #30
0
    def apply_move_rules(self, attacking_pokemon: Pokemon, move_used: Move,
                         trainer_ind: int) -> bool:
        if move_used.info.hit_info.has_invulnerable_phase:
            if not attacking_pokemon.has_status(PokemonStatus.INVULNERABLE):
                self.print_battle_text(
                    f"{attacking_pokemon.nickname} gains invulnerability for the turn"
                )
                attacking_pokemon.statuses.add(PokemonStatus.INVULNERABLE)
            else:
                # Remove the status here since we can assume that each move that makes
                # a pokemon invulnerable only does so for 1 turn.
                attacking_pokemon.statuses.remove(PokemonStatus.INVULNERABLE)

        if move_used.info.hit_info.requires_charge:
            if not attacking_pokemon.has_status(PokemonStatus.CHARGING):
                self.print_battle_text(
                    f"{attacking_pokemon.nickname} charges up {move_used.display_name}"
                )
                attacking_pokemon.statuses.add(PokemonStatus.CHARGING)
                self.move_queue[trainer_ind] = move_used
                return True
            else:
                # Reset whether the move is charged
                attacking_pokemon.statuses.remove(PokemonStatus.CHARGING)

        if move_used.info.hit_info.has_recharge:
            # This logically happens at the end of using a move, but can be done here as well
            attacking_pokemon.statuses.add(PokemonStatus.RECHARGING)

        if move_used.info.hit_info.self_destructing:
            # Self Destruction occurs on hit or miss
            self.print_battle_text(
                f"{attacking_pokemon.nickname} self-destructed")
            attacking_pokemon.hp = 0

        return False
Beispiel #31
0
def pokemons():
    if request.method == "GET":
        return Response(
            SerializadorPokemon(Pokemon.select(), many=True).data,
            status=STATUS_OK,
            mimetype="application/json"
        )
    elif request.method == "POST":
        attrs = json.loads(request.data.decode("utf8"))
        serializador = SerializadorPokemon(attrs=attrs)
        serializador.save()
        return Response(
            serializador.data,
            status=STATUS_CREATED,
            mimetype="application/json"
        )
Beispiel #32
0
def deposit_pkmn_handler(message):
    tokens = message.content.split()
    pkmn_name = ' '.join(tokens[2:])
    database.connect()
    try:
        pkmn = (
            Pokemon.select().where((Pokemon.storage == TEAM)
                                   & (Pokemon.owner_id == message.author.id)
                                   & (Pokemon.name == pkmn_name)).first())
        pkmn.storage = BOX
        pkmn.save()
    finally:
        database.commit()
        database.close()
    yield from client.send_message(message.channel,
                                   '{} sent to box'.format(pkmn.name))
Beispiel #33
0
def show_pokemon(message):
    """Command: show [index] - show the pokemon from your team.

    Displays information about the pokemon in the current channel.
    The pokemon is selected fron your team at the specified index,
    if index is not given, show the first pokemon.
    """
    num = int(message.content[10:] or 1)
    database.connect()
    pkmn = (Pokemon.select().where((Pokemon.owner_id == message.author.id) & (
        Pokemon.storage == TEAM)).offset(num - 1).limit(1).first())
    database.close()
    if pkmn is None:
        return
    em = discord.Embed(title='{} lv. {}'.format(pkmn.name, pkmn.level),
                       colour=0xC00000)
    em.set_image(url=pkmn.get_img_url())
    yield from client.send_message(message.channel, embed=em)
Beispiel #34
0
def add_pokemon():
    name = request.form["name"]
    number = request.form["number"]
    types = request.form["types"]

    poke = Pokemon.create(name=name, number=number, types=types)

    if request.method == "POST":
        image = request.files["image"]
        print(image.filename)
        image.save(
            os.path.join(app.config["UPLOAD_FOLDER"],
                         secure_filename(image.filename)))
        print("File Uploaded")

    print("Name: " + name + " Number: " + number + " Types: " + types +
          "Filename: " + image.filename)

    return redirect("/")
Beispiel #35
0
def add_caught_pokemon(user, pkmn, channel):
    """Add caught pokemon to the user's storage.

    Adds the pokemon to the storage and sends a notification about caught
    pokemon to the channel.
    """
    text = ('Congratulations! {} caught {}.'.format(user.mention, pkmn.name))
    pkmn.owner_id = user.id
    database.connect()
    count = (Pokemon.select().where((Pokemon.owner_id == user.id)
                                    & (Pokemon.storage == 1)).count())
    if count < TEAM_SIZE:
        pkmn.storage = TEAM
    else:
        pkmn.storage = BOX
        text += '\nPokemon was added to your box.'
    pkmn.save()
    database.commit()
    database.close()
    ensure_future(client.send_message(channel, text))
Beispiel #36
0
def process_step(args, api_endpoint, access_token, profile_response,
                 pokemonsJSON, ignore, only):
    print('[+] Searching pokemons for location {} {}'.format(FLOAT_LAT, FLOAT_LONG))
    origin = LatLng.from_degrees(FLOAT_LAT, FLOAT_LONG)
    step_lat = FLOAT_LAT
    step_long = FLOAT_LONG
    parent = CellId.from_lat_lng(LatLng.from_degrees(FLOAT_LAT,
                                                     FLOAT_LONG)).parent(15)
    h = get_heartbeat(args.auth_service, api_endpoint, access_token,
                      profile_response)
    hs = [h]
    seen = set([])

    for child in parent.children():
        latlng = LatLng.from_point(Cell(child).get_center())
        set_location_coords(latlng.lat().degrees, latlng.lng().degrees, 0)
        hs.append(
            get_heartbeat(args.auth_service, api_endpoint, access_token,
                          profile_response))
    set_location_coords(step_lat, step_long, 0)
    visible = []

    for hh in hs:
        try:
            for cell in hh.cells:
                for wild in cell.WildPokemon:
                    hash = wild.SpawnPointId + ':' \
                        + str(wild.pokemon.PokemonId)
                    if hash not in seen:
                        visible.append(wild)
                        seen.add(hash)
                if cell.Fort:
                    for Fort in cell.Fort:
                        if Fort.Enabled == True:
                            if args.china:
                                (Fort.Latitude, Fort.Longitude) = \
transform_from_wgs_to_gcj(Location(Fort.Latitude, Fort.Longitude))
                            if Fort.GymPoints:
                                Gym.create_or_get(
                                    gym_id=Fort.FortId,
                                    team_id=Fort.Team,
                                    team_name=numbertoteam[Fort.Team],
                                    lat=Fort.Latitude,
                                    lon=Fort.Longitude
                                )

                            elif Fort.FortType :
                                Pokestop.create_or_get(
                                    pokestop_id=Fort.FortId,
                                    lat=Fort.Latitude,
                                    lon=Fort.Longitude
                                )
        except AttributeError:
            break

    for poke in visible:
        pokename = pokemonsJSON[str(poke.pokemon.PokemonId)]
        if args.ignore:
            if pokename.lower() in ignore:
                continue
        elif args.only:
            if pokename.lower() not in only:
                continue

        disappear_timestamp = time.time() + poke.TimeTillHiddenMs \
            / 1000

        if args.china:
            (poke.Latitude, poke.Longitude) = \
                transform_from_wgs_to_gcj(Location(poke.Latitude,
                    poke.Longitude))

        Pokemon.create_or_get(
            spawnpoint_id=poke.SpawnPointId,
            lat=poke.Latitude,
            lon=poke.Longitude,
            pokedex_num=poke.pokemon.PokemonId,
            name=pokename,
            disappear_time=disappear_timestamp
        )
Beispiel #37
0
def step_impl(context, letter):
    print('Pokemon.find_by_name(letter):', Pokemon.find_by_name(letter))
    context.target = Pokemon.find_by_name(letter)
Beispiel #38
0
def step_impl(context):
    context.target = [Pokemon.find_strongest()]
Beispiel #39
0
def step_impl(context):
    context.target = [Pokemon.find_weakest()]
def fetch_pokemons_list(trainer_id, number_to_fetch=None):
    pokemons_query = Pokemon.query(ancestor=trainer_key(trainer_id))
    pokemons = pokemons_query.order(Pokemon.name).fetch(number_to_fetch)
    return pokemons
Beispiel #41
0
                'type': 'stop',
                'key': pokestop.pokestop_id,
                'disappear_time': -1,
                'icon': 'static/forts/Pstop.png',
                'infobox': 'Pokestop',
                'lng': pokestop.lon,
                'lat': pokestop.lat,
            })
    return pokeMarkers


def get_map():
    fullmap = Map(
        identifier="fullmap2",
        style='height:100%;width:100%;top:0;left:0;position:absolute;z-index:200;',
        lat=origin_lat,
        lng=origin_lon,
        markers=get_pokemarkers(),
        zoom='15', )
    return fullmap


if __name__ == '__main__':
    args = get_args()
    register_background_thread(initial_registration=True)
    db.connect()
    Pokemon.create_table(fail_silently=True)
    Pokestop.create_table(fail_silently=True)
    Gym.create_table(fail_silently=True)
    app.run(debug=True, threaded=True, host=args.host, port=args.port)
Beispiel #42
0
def clear_stale_pokemons():

    current_time = float(time.time())
    query = Pokemon.delete().where(Pokemon.disappear_time < current_time)
    query.execute()
Beispiel #43
0
def get_pokemarkers():
    pokeMarkers = [{
        'icon': icons.dots.red,
        'lat': origin_lat,
        'lng': origin_lon,
        'infobox': "Start position",
        'type': 'custom',
        'key': 'start-position',
        'disappear_time': -1
    }]

    for pokemon in Pokemon.select():
        label_mapping = {}
        label_mapping['disappear_time_formatted'] = datetime.fromtimestamp(pokemon.disappear_time).strftime("%H:%M:%S")
        label_mapping['id'] = pokemon.pokedex_num
        label_mapping['disappear_time'] = pokemon.disappear_time
        label_mapping['name'] = pokemon.name
        label_mapping['lat'] = pokemon.lat
        label_mapping['lon'] = pokemon.lon

        LABEL_TMPL = u'''
<div><b>{name}</b><span> - </span><small><a href='http://www.pokemon.com/us/pokedex/{id}' target='_blank' title='View in Pokedex'>#{id}</a></small></div>
<div>Disappears at - {disappear_time_formatted} <span class='label-countdown' disappears-at='{disappear_time}'></span></div>
<div><a href='https://www.google.com/maps/dir/Current+Location/{lat},{lon}' target='_blank' title='View in Maps'>Get Directions</a></div>
'''
        label = LABEL_TMPL.format(**label_mapping)
        #  NOTE: `infobox` field doesn't render multiple line string in frontend
        label = label.replace('\n', '')

        pokeMarkers.append({
            'type': 'pokemon',
            'icon': 'static/icons/%d.png' % pokemon.pokedex_num,
            'lat': pokemon.lat,
            'lng': pokemon.lon,
            'key': pokemon.spawnpoint_id,
            'disappear_time': pokemon.disappear_time,
            'infobox': label
        })

    if args.display_gym:
        for gym in Gym.select():
            if gym.team_id == 0:
                color = "rgba(0,0,0,.4)"
            if gym.team_id == 1:
                color = "rgba(0, 0, 256, .4)"
            if gym.team_id == 2:
                color = "rgba(255, 0, 0, .4)"
            if gym.team_id == 3:
                color = "rgba(255, 255, 0, .4)"

        icon = 'static/forts/'+gym.team_name+'_large.png'
        pokeMarkers.append({
            'icon': 'static/forts/' + gym.team_name + '.png',
            'type': 'gym',
            'key': gym.gym_id,
            'disappear_time': -1,
            'lat': gym.lat,
            'lng': gym.lon,
            'infobox': "<div><center><small>Gym owned by:</small><br><b style='color:" + color + "'>Team " +
                       gym.team_name + "</b><br><img id='" + gym.team_name + "' height='100px' src='" + icon + "'></center>"

        })

    if args.display_pokestop:
        for pokestop in Pokestop.select():
            pokeMarkers.append({
                'type': 'stop',
                'key': pokestop.pokestop_id,
                'disappear_time': -1,
                'icon': 'static/forts/Pstop.png',
                'infobox': 'Pokestop',
                'lng': pokestop.lon,
                'lat': pokestop.lat,
            })
    return pokeMarkers