예제 #1
0
 async def get_pokedex_embed(self, ctx, mon, shiny=False):
     pokedex = self.bot.get_emoji_named('Pokedex')
     evo = await get_evolution_chain(ctx, mon['num'])
     embed = discord.Embed(
         description=wrap(f"__{mon['name']}{get_star(mon)}'s Information__",
                          pokedex) +
         f"\n**ID:** {mon['num']}\n**Type:** {' & '.join(mon['type'])}"
         f"\n**Evolutions:**\n{evo}")
     embed.color = await get_pokemon_color(ctx, mon=mon)
     return embed
예제 #2
0
 async def get_pokedex_embed(self, mon):
     pokedex = self.bot.get_emoji_named('Pokedex')
     evo = await mon.get_evolution_chain()
     embed = discord.Embed(
         description=wrap(f"__{mon.display_name}{mon.star}'s Information__",
                          pokedex) +
         f"\n**ID:** {mon.num}\n**Type:** {' & '.join(mon.type)}"
         f"\n**Evolutions:**\n{evo}")
     embed.color = mon.color
     return embed
예제 #3
0
    async def sell(self, ctx):
        spacer = SPACER * 24
        player_name = ctx.author.name
        trainer = await Trainer.from_user_id(ctx, ctx.author.id)
        user_pokemon = await trainer.get_pokemon()
        await ctx.log_event('shop_accessed', multiple=0)
        inventory = trainer.inventory
        header = f'**{player_name}**,\nSelect Pokemon to sell.\n' + wrap(f'**100**\ua750 normal | **600**\ua750'
                                                                         f' Legendary {STAR} | **1000**\ua750'
                                                                         f' Mythical {GLOWING_STAR}', spacer, sep='\n')
        names = []
        options = []
        for mon in user_pokemon:
            shiny = GLOWING_STAR if mon.shiny else ''
            options.append("{} **{}.** {}{}{}".format('\📍' if mon.party_position is not None else '',
                mon.num, mon.display_name, mon.star, shiny))
            names.append(mon.display_name)
        if not options:
            await ctx.send("You don't have any pokemon to sell.", delete_after=60)
            return
        selected = await self.reaction_menu(options, ctx.author, ctx.channel, -1, per_page=20, header=header,
                                            code=False, multi=True, return_from=user_pokemon, display=names)
        if not selected:
            return
        named = []
        sold = []
        sold_objs = []
        total = 0
        selected = unique(selected, key=lambda m: m.id)
        for mon in sorted(selected, key=lambda m: m.num):
            if mon.shiny:
                total += 1000
            if mon.mythical:
                total += 1000
            elif mon.legendary:
                total += 600
            else:
                total += 100
            sold_objs.append(mon)

            if mon.num not in named:
                count = 0
                for m in selected:
                    if m.num == mon.num:
                        count += 1
                shiny = GLOWING_STAR if mon.shiny else ''
                sold.append(f"{mon.display_name}{shiny}{f' x{count}' if count > 1 else ''}")
                named.append(mon.num)
        for mon in sold_objs:
            await mon.transfer_ownership(None)
        inventory['money'] += total
        await ctx.log_event('shop_sold', pokemon=[m.id for m in sold_objs], received=total)
        await trainer.set_inventory(inventory)
        await ctx.send(f'{player_name} sold the following for {total}\ua750:\n' + '\n'.join(sold), delete_after=60)
예제 #4
0
 async def list_roles(self, ctx):
     """Lists all of the game roles."""
     roles = sorted(self.game_aliases.keys())
     header = "**Game List**"
     spacer = '-=-=-=--=-=-=--=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-'
     key = f'{ARROWS[0]} Click to go back a page.\n{ARROWS[1]} Click to go forward a page.\n{CANCEL} Click to exit the list.'
     info = wrap(
         'To assign yourself one of these roles just use **!roles add ``Game``**.',
         spacer,
         sep='\n')
     header = '\n'.join([header, key, info])
     await self.reaction_menu(roles,
                              ctx.author,
                              ctx.channel,
                              0,
                              per_page=20,
                              timeout=120,
                              code=False,
                              header=header,
                              return_from=roles)
예제 #5
0
    async def get_pc_info_embed(self, mon):
        pokedex = self.bot.get_emoji_named('Pokedex')
        em = discord.Embed()
        em.color = mon.color
        name = mon.display_name
        level = mon.level
        needed_xp = xp_to_level(level + 1) - xp_to_level(level)
        current_xp = mon.exp - xp_to_level(level)
        bar_length = 10
        FILLED_BAR = '■'
        UNFILLED_BAR = '□'
        bar = f'[{UNFILLED_BAR * bar_length}]()'
        percent_needed = (current_xp / needed_xp)
        filled_bars = int(bar_length * percent_needed)
        if filled_bars != 0:
            bar = f"[{(FILLED_BAR * filled_bars).ljust(bar_length, UNFILLED_BAR)}]()"

        em.description = wrap(f'__Your {name}{mon.star}\'s Information__',
                              pokedex)
        em.description += f"\n**ID:** {mon.num}\n" \
                          f"**Level:** {level}\n" \
                          f"**EXP:** {current_xp}/{needed_xp}\n{bar}\n" \
                          f"**Type:** {' & '.join(mon.type)}\n" \
                          f"**Caught Using:** {self.bot.get_emoji_named(mon.ball)}\n"

        if mon.party_position is not None:
            em.description += f"**Party Position**: {mon.party_position + 1}"

        shiny_status = 'shiny' if mon.shiny else 'normal'
        image = self.image_path.format(
            shiny_status, mon.num,
            0)  # replace 0 with mon['form_id'] to support forms

        stats = mon.stats
        em.add_field(name='Statistics',
                     value='\n'.join(
                         f"**{stat.replace('_', '. ').title()}**: {val}"
                         for stat, val in stats.items()))
        evo = await mon.get_evolution_chain()
        em.add_field(name='Evolutions', value=evo, inline=False)
        return em, image
예제 #6
0
파일: camera.py 프로젝트: jfzhang95/PoseAug
def camera_to_world(X, R, t):
    return wrap(qrot, False, np.tile(R, X.shape[:-1] + (1,)), X) + t
예제 #7
0
파일: camera.py 프로젝트: jfzhang95/PoseAug
def world_to_camera(X, R, t):
    Rt = wrap(qinverse, False, R)  # Invert rotation
    return wrap(qrot, False, np.tile(Rt, X.shape[:-1] + (1,)), X - t)  # Rotate and translate
예제 #8
0
    # Create 2D pose file
    print('')
    print('Computing ground-truth 2D poses...')
    dataset = Human36mDataset(output_filename + '.npz')
    output_2d_poses = {}
    for subject in dataset.subjects():
        output_2d_poses[subject] = {}
        for action in dataset[subject].keys():
            anim = dataset[subject][action]

            positions_2d = []
            for cam in anim['cameras']:
                pos_3d = world_to_camera(anim['positions'],
                                         R=cam['orientation'],
                                         t=cam['translation'])
                pos_2d = wrap(project_to_2d, True, pos_3d, cam['intrinsic'])
                pos_2d_pixel_space = image_coordinates(pos_2d,
                                                       w=cam['res_w'],
                                                       h=cam['res_h'])
                positions_2d.append(pos_2d_pixel_space.astype('float32'))
            output_2d_poses[subject][action] = positions_2d

    print('Saving...')
    metadata = {
        'num_joints':
        dataset.skeleton().num_joints(),
        'keypoints_symmetry':
        [dataset.skeleton().joints_left(),
         dataset.skeleton().joints_right()]
    }
    np.savez_compressed(output_filename_2d,
예제 #9
0
    async def pokemon(self, ctx):
        """Gives you a random Pokemon!"""
        player_name = ctx.author.name
        player_id = ctx.author.id
        trainer = await Trainer.from_user_id(ctx, player_id)
        mon = await Pokemon.random(ctx, trainer)
        shiny = GLOWING_STAR if mon.shiny else ''
        await ctx.log_event('pokemon_encountered',
                            num=mon.num,
                            shiny=mon.shiny)

        inv = trainer.inventory
        balls = [
            self.bot.get_emoji_named(ball) for ball in pokeballs
            if inv.get(ball)
        ]
        embed = discord.Embed(
            description=
            f'A wild **{mon.display_name}**{mon.star}{shiny} appears!' +
            (f'\nUse a {balls[0]} to catch it!' if balls else ''))
        embed.color = mon.color
        embed.set_author(icon_url=ctx.author.avatar_url, name=player_name)
        embed.set_image(url='attachment://pokemon.gif')
        msg = await ctx.send(embed=embed,
                             file=discord.File(self.image_path.format(
                                 'normal', mon.num, 0),
                                               filename='pokemon.gif'))
        await trainer.see(mon)
        catch_attempts = 0
        while catch_attempts <= 2:
            trainer = await Trainer.from_user_id(ctx, player_id)
            inv = trainer.inventory
            balls = [
                self.bot.get_emoji_named(ball) for ball in pokeballs
                if inv.get(ball)
            ]
            can_react_with = [*balls, CANCEL]
            for emoji in can_react_with:
                await msg.add_reaction(emoji)
            try:

                def check(reaction, user):
                    return (reaction.emoji in can_react_with
                            and reaction.message.id == msg.id
                            and user == ctx.author)

                reaction, _ = await self.bot.wait_for('reaction_add',
                                                      check=check,
                                                      timeout=20)

                await ctx.log_event('item_used', item=reaction.emoji.name)
            except asyncio.TimeoutError:
                embed.description = f'**{mon.display_name}**{mon.star}{shiny} escaped because you took too long!' \
                                    f' :stopwatch:'
                await msg.edit(embed=embed, delete_after=60)
                await msg.clear_reactions()
                return
            await msg.clear_reactions()
            if reaction.emoji in balls:
                inv[reaction.emoji.name] -= 1
                await trainer.set_inventory(inv)
                catch_attempts += 1
                if catch(mon, balls.index(reaction.emoji)):
                    embed.description = wrap(
                        f'You caught **{mon.display_name}**{mon.star}{shiny} successfully!',
                        reaction.emoji)
                    await msg.edit(embed=embed, delete_after=60)
                    found = await trainer.add_caught_pokemon(
                        mon, reaction.emoji.name)
                    await ctx.log_event('pokemon_caught',
                                        attempts=catch_attempts + 1,
                                        ball=reaction.emoji.name,
                                        id=found.id)
                    break
                else:
                    escape_quotes = [
                        'Oh no! The Pokémon broke free!',
                        'Aww... It appeared to be caught!',
                        'Aargh! Almost had it!', 'Gah! It was so close, too!'
                    ]
                    embed.description = random.choice(escape_quotes)
                await msg.edit(embed=embed)
            else:
                embed.description = wrap(
                    f'You ran away from **{mon.display_name}**{mon.star}{shiny}!',
                    ':chicken:')
                await msg.edit(embed=embed, delete_after=60)
                await ctx.log_event('pokemon_fled',
                                    attempts=catch_attempts + 1,
                                    num=mon.num,
                                    shiny=mon.shiny)
                break
        else:
            embed.description = f'**{mon.display_name}**{mon.star}{shiny} has escaped!'
            await ctx.log_event('pokemon_fled',
                                attempts=catch_attempts + 1,
                                num=mon.num,
                                shiny=mon.shiny)
            await msg.edit(embed=embed, delete_after=60)
예제 #10
0
    async def pokedex(self, ctx, *, member=None):
        """Shows you your Pokedex through a reaction menu."""
        pokedex = self.bot.get_emoji_named('Pokedex')

        member = await poke_converter(ctx, member) or ctx.author

        total_pokemon = len(await get_all_pokemon(ctx))
        if isinstance(member, discord.Member):
            trainer = await Trainer.from_user_id(ctx, member.id)
            await ctx.log_event('pokedex_accessed',
                                query_type='member',
                                query=member.id,
                                shiny=False)
            seen = await trainer.get_pokemon(seen=True)
            total_found = len(seen)

            legendaries = sum(1 for m in seen
                              if m.legendary and not m.mythical)
            mythicals = sum(1 for m in seen if m.mythical)

            header = f"__**{member.name}'s Pokedex**__"
            if total_found == 0:
                header += " __**is empty.**__"
            header = wrap(header, pokedex)
            if total_found == 0:
                return await ctx.send(header, delete_after=60)

            spacer = SPACER * 22

            key = f'{ARROWS[0]} Click to go back a page.\n{ARROWS[1]} Click to go forward a page.\n{CANCEL}' \
                  f' Click to exit your pokedex.'

            counts = wrap(
                f'**{total_found}** encountered out of {total_pokemon} total Pokemon.'
                f'\n**{total_found - mythicals - legendaries}** normal | **{legendaries}** Legendary {STAR}'
                f' | **{mythicals}** Mythical {GLOWING_STAR}',
                spacer,
                sep='\n')
            header = '\n'.join([
                header,
                'Use **!pc** to see which Pokémon you own!\nUse **!pokedex** ``#`` to take a closer look at a Pokémon!',
                key, counts
            ])

            options = []
            for mon in seen:
                options.append("**{}.** {}{}".format(mon.num, mon.display_name,
                                                     mon.star))
            await self.reaction_menu(options,
                                     ctx.author,
                                     ctx.channel,
                                     0,
                                     per_page=20,
                                     code=False,
                                     header=header)
            return
        elif isinstance(member, int):
            query_type = 'num'
            if 0 >= member or member > total_pokemon:
                return await ctx.send(f'Pokemon {member} does not exist.')

            image = self.image_path.format('normal', member, 0)
            info = await Pokemon.from_num(ctx, member)
        elif isinstance(member, str):
            query_type = 'fuzzy'
            pokemon_names = [p.base_name for p in await get_all_pokemon(ctx)]
            result = list(process.extractOne(member, pokemon_names))
            if result[1] < 70:
                return await ctx.send(f'Pokemon {member} does not exist.')
            pokemon_number = await Pokemon.from_name(ctx, result[0])
            info = await Pokemon.from_num(ctx, pokemon_number.num)
            image = self.image_path.format('normal', info.num, 0)
        else:
            query_type = None
            image = self.image_path.format('normal', 1, 0)
            info = await Pokemon.from_num(ctx, 1)
        embed = await self.get_pokedex_embed(info)
        await ctx.log_event('pokedex_accessed',
                            query_type=query_type,
                            query=member,
                            shiny=False)
        await ctx.send(embed=embed,
                       file=discord.File(image, filename='pokemon.gif'),
                       delete_after=120)
예제 #11
0
    async def pc(self, ctx, *, member: discord.Member = None):
        """Opens your PC."""
        member = member or ctx.author
        await ctx.log_event('pc_accessed',
                            query_type='member',
                            query=member.id)

        total_pokemon = len(await get_all_pokemon(ctx))
        trainer = await Trainer.from_user_id(ctx, member.id)
        found = await trainer.get_pokemon()
        total_found = len(found)
        remaining = total_pokemon - total_found

        legendaries = len([m for m in found if m.legendary])
        mythics = len([m for m in found if m.mythical])

        header = f"__**{member.name}'s PC**__"
        if total_found == 0:
            header += " __**is empty.**__"
        if total_found == 0:
            return await ctx.send(header, delete_after=60)
        spacer = SPACER * 21

        key = f'{ARROWS[0]} Click to go back a page.\n{ARROWS[1]} Click to go forward a page.\n{CANCEL}' \
              f' Click to exit your pc.'

        counts = wrap(
            f'**{total_found}** collected out of {total_pokemon} total Pokemon. {remaining} left to go!'
            f'\n**{total_found - mythics - legendaries}** normal | **{legendaries}** Legendary {STAR}'
            f' | **{mythics}** Mythical {GLOWING_STAR}',
            spacer,
            sep='\n')

        header = '\n'.join([
            header,
            'Use **!pokedex** to see which Pokémon you\'ve encountered!\nUse **!pokedex** ``#``'
            ' to take a closer look at a Pokémon!', key, counts
        ])

        options = []
        done = []
        for mon in found:
            if mon.display_name in done and mon.party_position is None:
                continue
            if mon.party_position is None:
                mon_count = sum(m.display_name == mon.display_name
                                for m in found if m.party_position is None)
                done.append(mon.display_name)
            elif mon.party_position is not None:
                mon_count = 1
            shiny = mon.shiny
            shiny = SPARKLES if shiny else ''
            count = f" x{mon_count}" if mon_count > 1 else ''
            name = mon.display_name
            options.append("{} **{}.** {}{}{}{}".format(
                '' if mon.party_position is not None else '', mon.num, name,
                mon.star, shiny, count))
        await self.reaction_menu(options,
                                 ctx.author,
                                 ctx.channel,
                                 0,
                                 per_page=20,
                                 code=False,
                                 header=header)
예제 #12
0
    async def sell(self, ctx):
        spacer = SPACER * 24
        player_name = ctx.author.name
        user_pokemon = await ctx.con.fetch(
            """
									 WITH p AS (SELECT num, name, form, form_id, legendary, mythical FROM pokemon)
									 SELECT f.id, f.num, f.name, original_owner, personality,
											p.name AS base_name, p.form, legendary, mythical FROM found f
									 JOIN p ON p.num = f.num AND p.form_id = f.form_id
									 WHERE owner = $1 ORDER BY f.num, f.form_id;
									 """, ctx.author.id)
        user_pokemon = [dict(mon) for mon in user_pokemon]
        player_data = await get_player(ctx, ctx.author.id)
        inventory = player_data['inventory']
        header = f'**{player_name}**,\nSelect Pokemon to sell.\n' + wrap(
            f'**100**\ua750 Normal | **600**\ua750'
            f' Legendary {STAR} | **1000**\ua750'
            f' Mythical {GLOWING_STAR}',
            spacer,
            sep='\n')
        names = []
        options = []
        trainers = {
            t['user_id']: t
            for t in await ctx.con.fetch(
                """
														   SELECT * FROM trainers WHERE user_id = ANY($1)
														   """, set(m['original_owner'] for m in user_pokemon))
        }
        for mon in user_pokemon:
            name = get_name(mon)
            mon['shiny'] = is_shiny(trainers[mon['original_owner']],
                                    mon['personality'])
            options.append("**{}.** {}{}{}".format(mon['num'], name,
                                                   get_star(mon),
                                                   mon['shiny']))
            names.append(name)
        if not options:
            await ctx.send("You don't have any pokemon to sell.",
                           delete_after=60)
            return
        selected = await self.reaction_menu(options,
                                            ctx.author,
                                            ctx.channel,
                                            -1,
                                            per_page=20,
                                            header=header,
                                            code=False,
                                            multi=True,
                                            return_from=user_pokemon,
                                            display=names)
        if not selected:
            return
        named = []
        sold = []
        sold_ids = []
        total = 0
        selected = unique(selected, key=lambda m: m['id'])
        for mon in sorted(selected, key=lambda m: m['num']):
            if mon['shiny']:
                total += 1000
            if mon['mythical']:
                total += 1000
            elif mon['legendary']:
                total += 600
            else:
                total += 100
            sold_ids.append(mon['id'])
            shiny = False
            if mon['num'] not in named:
                count = 0
                for m in selected:
                    if m['num'] == mon['num']:
                        count += 1
                        shiny = shiny or m['shiny']
                sold.append(
                    f"{mon['base_name']}{shiny}{f' x{count}' if count > 1 else ''}"
                )
                named.append(mon['num'])
        await ctx.con.execute(
            """
					DELETE FROM found WHERE id = ANY($1)
					""", sold_ids)
        inventory['money'] += total
        await set_inventory(ctx, ctx.author.id, inventory)
        await ctx.send(
            f'{player_name} sold the following for {total}\ua750:\n' +
            '\n'.join(sold),
            delete_after=60)
예제 #13
0
    async def pokedex(self, ctx, *, member=None):
        """Shows you your Pokedex through a reaction menu."""
        pokedex = self.bot.get_emoji_named('Pokedex')

        member = await poke_converter(ctx, member) or ctx.author

        total_pokemon = await ctx.con.fetchval("""
									  SELECT COUNT(DISTINCT num) FROM pokemon
									  """)
        if isinstance(member, discord.Member):
            seen = await ctx.con.fetch(
                """
								 WITH p AS (SELECT num, name, mythical, legendary FROM pokemon WHERE form_id = 0)
								 SELECT s.num, name, mythical, legendary FROM seen s JOIN p ON s.num = p.num
								 WHERE user_id=$1 ORDER BY s.num
								 """, member.id)
            total_found = len(seen)

            legendaries = sum(1 for m in seen
                              if m['legendary'] and not m['mythical'])
            mythicals = sum(1 for m in seen if m['mythical'])

            header = f"__**{member.name}'s Pokedex**__"
            if total_found == 0:
                header += " __**is empty.**__"
            header = wrap(header, pokedex)
            if total_found == 0:
                return await ctx.send(header, delete_after=60)

            spacer = SPACER * 22

            key = f'{ARROWS[0]} Click to go back a page.\n{ARROWS[1]} Click to go forward a page.\n{CANCEL}' \
               f' Click to exit your pokedex.'

            counts = wrap(
                f'**{total_found}** encountered out of {total_pokemon} total Pokemon.'
                f'\n**{total_found - mythicals - legendaries}** Normal | **{legendaries}** Legendary {STAR}'
                f' | **{mythicals}** Mythical {GLOWING_STAR}',
                spacer,
                sep='\n')
            header = '\n'.join([
                header,
                'Use **!pc** to see which Pokémon you own!\nUse **!pokedex** ``#`` to take a closer look at a Pokémon!',
                key, counts
            ])

            options = []
            for mon in seen:
                options.append("**{}.** {}{}".format(mon['num'], mon['name'],
                                                     get_star(mon)))
            await self.reaction_menu(options,
                                     ctx.author,
                                     ctx.channel,
                                     0,
                                     per_page=20,
                                     code=False,
                                     header=header)
            return
        elif isinstance(member, int):
            if 0 >= member or member > total_pokemon:
                return await ctx.send(f'Pokemon {member} does not exist.',
                                      delete_after=60)

            image = self.image_path.format('normal', member, 0)
            info = await get_pokemon(ctx, member)
        elif isinstance(member, str):
            pokemon_records = await ctx.con.fetch("""
										  SELECT name FROM pokemon
										  """)
            pokemon_names = [mon['name'] for mon in pokemon_records]
            result = list(process.extractOne(member, pokemon_names))
            if result[1] < 70:
                return await ctx.send(f'Pokemon {member} does not exist.',
                                      delete_after=60)
            pokemon_number = await ctx.con.fetchval(
                """
										   SELECT num FROM pokemon WHERE name=$1
										   """, result[0])
            info = await get_pokemon(ctx, pokemon_number)
            image = self.image_path.format('normal', info['num'], 0)
        embed = await self.get_pokedex_embed(ctx, info)
        embed.set_image(url=image)
        await ctx.send(embed=embed, delete_after=120)
예제 #14
0
    async def pc(self, ctx, *, member: discord.Member = None):
        """Opens your PC."""
        member = member or ctx.author

        total_pokemon = await ctx.con.fetchval("""
									  SELECT COUNT(DISTINCT num) FROM pokemon
									  """)
        found = await ctx.con.fetch(
            """
							  WITH p AS (SELECT num, name, form, form_id, legendary, mythical FROM pokemon)
							  SELECT f.num, f.name, original_owner, personality, p.name AS base_name, p.form, legendary, mythical FROM found f
							  JOIN p ON p.num = f.num AND p.form_id = f.form_id
							  WHERE owner = $1 ORDER BY f.num, f.form_id;
							  """, member.id)
        total_found = len(found)
        remaining = total_pokemon - total_found

        legendaries = await ctx.con.fetchval(
            """
									SELECT COUNT(*) FROM found WHERE owner=$1 AND num=ANY((SELECT num FROM pokemon WHERE legendary=True))
									""", member.id)
        mythics = await ctx.con.fetchval(
            """
								SELECT COUNT(*) FROM found WHERE owner=$1 AND num=ANY((SELECT num FROM pokemon WHERE mythical=True))
								""", member.id)

        header = f"__**{member.name}'s PC**__"
        if total_found == 0:
            header += " __**is empty.**__"
        if total_found == 0:
            return await ctx.send(header, delete_after=60)
        spacer = SPACER * 21

        key = f'{ARROWS[0]} Click to go back a page.\n{ARROWS[1]} Click to go forward a page.\n{CANCEL}' \
           f' Click to exit your pc.'

        counts = wrap(
            f'**{total_found}** collected out of {total_pokemon} total Pokemon. {remaining} left to go!'
            f'\n**{total_found - mythics - legendaries}** Normal | **{legendaries}** Legendary {STAR}'
            f' | **{mythics}** Mythical {GLOWING_STAR}',
            spacer,
            sep='\n')

        header = '\n'.join([
            header,
            'Use **!pokedex** to see which Pokémon you\'ve encountered!\nUse **!pokedex** ``#`` to take a closer look at a Pokémon!',
            key, counts
        ])

        trainers = {
            t['user_id']: t
            for t in await ctx.con.fetch(
                """
														   SELECT * FROM trainers WHERE user_id = ANY($1)
														   """, set(m['original_owner'] for m in found))
        }
        options = []
        done = []
        for mon in found:
            if mon['name'] is None and mon['num'] in done:
                continue
            counter = 0
            if mon['name'] is None:
                shiny = False
                for m in found:
                    if m['num'] == mon['num'] and m['name'] is None:
                        counter += 1
                        if not shiny:
                            shiny = is_shiny(trainers[m['original_owner']],
                                             m['personality'])
                done.append(mon['num'])
            else:
                shiny = is_shiny(trainers[mon['original_owner']],
                                 m['personality'])
            count = f" x{counter}" if counter > 1 else ''
            name = get_name(mon)
            options.append("**{}.** {}{}{}{}".format(mon['num'], name,
                                                     get_star(mon), shiny,
                                                     count))
        await self.reaction_menu(options,
                                 ctx.author,
                                 ctx.channel,
                                 0,
                                 per_page=20,
                                 code=False,
                                 header=header)
예제 #15
0
    async def pokemon(self, ctx):
        """Gives you a random Pokemon every 60 seconds!"""
        player_name = ctx.author.name
        player_id = ctx.author.id
        mon = await ctx.con.fetchrow('''
			SELECT num, name, form, form_id, type, legendary, mythical, rand(4294967295) as personality,
			(SELECT form FROM pokemon p2 WHERE p2.num = pokemon.num AND p2.form_id = 0) AS base_form,
			(SELECT ARRAY(SELECT color FROM types WHERE types.name = ANY(type))) AS colors
			FROM pokemon ORDER BY random() LIMIT 1''')
        trainer = await get_player(ctx, player_id)
        inv = trainer['inventory']
        balls = [
            self.bot.get_emoji_named(ball) for ball in pokeballs
            if inv.get(ball)
        ]
        star = get_star(mon)
        shiny = is_shiny(trainer, mon['personality'])
        if shiny:
            if mon['base_form']:
                form = mon['base_form'] + ' '
            else:
                form = ''
            form_id = 0
        else:
            if mon['form']:
                form = mon['form'] + ' '
            else:
                form = ''
            form_id = mon['form_id']
        embed = discord.Embed(
            description=f'A wild **{form}{mon["name"]}**{star}{shiny} appears!'
            + (f'\nUse a {balls[0]} to catch it!' if balls else ''))
        embed.color = await get_pokemon_color(ctx, mon=mon)
        embed.set_author(icon_url=ctx.author.avatar_url, name=player_name)
        embed.set_image(url=self.image_path.format('normal', mon['num'], 0))
        msg = await ctx.send(embed=embed, delete_after=60)
        await see(ctx, player_id, mon['num'])
        can_react_with = [*balls, CANCEL]
        for emoji in can_react_with:
            await msg.add_reaction(emoji)
        try:

            def check(reaction, user):
                return (reaction.emoji in can_react_with
                        and reaction.message.id == msg.id
                        and user == ctx.author)

            reaction, _ = await self.bot.wait_for('reaction_add',
                                                  check=check,
                                                  timeout=20)
        except asyncio.TimeoutError:
            embed.description = f'**{form}{mon["name"]}**{star}{shiny} escaped because you took too long! :stopwatch:'
            await msg.edit(embed=embed, delete_after=15)
            await msg.clear_reactions()
            return
        await msg.clear_reactions()
        if reaction.emoji in balls:
            if catch(mon, balls.index(reaction.emoji)):
                embed.description = wrap(
                    f'You caught **{form}{mon["name"]}**{star}{shiny} successfully!',
                    reaction.emoji)
                await msg.edit(embed=embed, delete_after=15)
                level = await ctx.con.fetchval(
                    '''
					SELECT level FROM evolutions WHERE next = $1
					''', mon['num']) or 0
                async with ctx.con.transaction():
                    await ctx.con.execute(
                        '''
						INSERT INTO found (num, form_id, ball, exp, owner, original_owner, personality) VALUES ($1, $2, $3, $4, $5, $6, $7)
						''', mon['num'], form_id, reaction.emoji.name, xp_to_level(level),
                        player_id, player_id, mon['personality'])
            else:
                embed.description = f'**{form}{mon["name"]}**{star}{shiny} has escaped!'
                await msg.edit(embed=embed, delete_after=15)
            inv[reaction.emoji.name] -= 1
            await set_inventory(ctx, player_id, inv)
        else:
            embed.description = wrap(
                f'You ran away from **{form}{mon["name"]}**{star}{shiny}!',
                ':chicken:')
            await msg.edit(embed=embed, delete_after=15)