예제 #1
0
 async def choose_role_from(self, roles: List[Role]) -> None:
     entries = [role.name.title().replace("_", " ") for role in roles]
     await self.send(
         "You will be asked to choose a new role from these:\n**{choices}**".format(
             choices=", ".join(entries)
         )
     )
     try:
         can_dm = True
         role = await self.game.ctx.bot.paginator.Choose(
             entries=entries, return_index=True, title="Choose a new role",
         ).paginate(self.game.ctx, location=self.user)
         role = roles[role]
     except self.game.ctx.bot.paginator.NoChoice:
         role = random.choice(roles)
         await self.send(
             "You didn't choose anything. A random role was chosen for you."
         )
     except discord.Forbidden:
         can_dm = False
         role = random.choice(roles)
         await self.game.ctx.send(
             "I couldn't send a DM. A random role was chosen for them."
         )
     self.role = role
     if can_dm:
         await self.send(
             f"Your new role is now **{self.role.name.title().replace('_', ' ')}**."
         )
         await self.send_information()
예제 #2
0
 async def get_random_name(self, gender, avoid):
     if gender == "f":
         data = self.girlnames
     else:
         data = self.boynames
     name = random.choice(data).strip("\n")
     while name in avoid:
         name = random.choice(data)  # avoid duplicate names
     return name
예제 #3
0
파일: maze.py 프로젝트: Garnet-0/IdleRPG
 def __init__(self, x, y, walls):
     self.x = x
     self.y = y
     self.walls = set(walls)
     self.trap = random.choice([False] * 9 + [True])  # 10% Chance of being a trap
     if not self.trap:
         self.enemy = random.choice(
             [False] * 9 + [True]
         )  # If no trap, 10% Chance of an enemy here
     else:
         self.enemy = False
     self.treasure = False
예제 #4
0
파일: __init__.py 프로젝트: indij/IdleRPG
    async def play(self, ctx):
        _(
            """Play with your pet to raise its joy points. Your pet can gain from 1 to 12 Joy points per play.

            Only rangers can use this command.
            (This command has a cooldown of 6 hours.)"""
        )
        value = random.randint(0, 11) + 1  # On average, it'll stay as is
        await self.bot.pool.execute(
            'UPDATE pets SET "joy"=CASE WHEN "joy"+$1>=100 THEN 100 ELSE "joy"+$1 END'
            ' WHERE "user"=$2;',
            value,
            ctx.author.id,
        )
        await ctx.send(
            _(
                "You have been {activity} with your pet and it gained **{value}** joy!"
            ).format(
                activity=random.choice(
                    [
                        _("playing football :soccer:"),
                        _("playing American football :football:"),
                        _("playing rugby :rugby_football:"),
                        _("playing basketball :basketball:"),
                        _("playing tennis :tennis:"),
                        _("playing ping-pong :ping_pong:"),
                        _("boxing :boxing_glove:"),
                        _("skiing :ski:"),
                    ]
                ),
                value=value,
            )
        )
예제 #5
0
 async def get_ai_move(self):
     if self.colors[self.player] == "black":
         self.msg = await self.ctx.send(
             _(
                 "**Move {move_no}**\nLet me think... This might take up to 2"
                 " minutes"
             ).format(move_no=self.move_no)
         )
     else:
         await self.msg.edit(
             content=_(
                 "**Move {move_no}**\nLet me think... This might take up to 2"
                 " minutes"
             ).format(move_no=self.move_no)
         )
     try:
         async with timeout(120):
             move = await self.engine.play(self.board, self.limit)
     except asyncio.TimeoutError:
         move = random.choice(list(self.board.legal_moves))
         await self.msg.delete()
         return move
     await self.msg.delete()
     if move.draw_offered:
         return "draw"
     elif move.resigned:
         return "resign"
     else:
         return move.move
예제 #6
0
파일: misc.py 프로젝트: Garnet-0/IdleRPG
def calcchance(sword,
               shield,
               dungeon,
               level,
               luck,
               returnsuccess=False,
               booster=False,
               bonus=0):
    if returnsuccess is False:
        val1 = sword + shield + 75 - dungeon * 10
        val2 = sword + shield + 75 - dungeon * 2
        val1 = round(val1 * luck) if val1 >= 0 else round(val1 / luck)
        val2 = round(val2 * luck) if val2 >= 0 else round(val2 / luck)
        if booster:
            val1 += 25
            val2 += 25
        return (val1, val2, level)
    else:
        randomn = random.randint(0, 100)
        success = (sword + shield + 75 - (dungeon * (random.randint(2, 10))) +
                   random.choice([level, -level]) + bonus)
        if success >= 0:
            success = round(success * luck)
        else:
            success = round(success / luck)
        if booster:
            success += 25
        return randomn <= success
예제 #7
0
    async def date(self, ctx):
        _("""Take your partner on a date to increase *their* lovescore. To increase your own lovescore, your partner should go on a date with you.

            The lovescore gained from dates can range from 10 to 150 in steps of 10.

            Only players who are married can use this command.
            (This command has a cooldown of 12 hours.)""")
        num = random.randint(1, 15) * 10
        marriage = ctx.character_data["marriage"]
        if not marriage:
            await self.bot.reset_cooldown(ctx)
            return await ctx.send(_("You are not married yet."))
        await self.bot.pool.execute(
            'UPDATE profile SET "lovescore"="lovescore"+$1 WHERE "user"=$2;',
            num,
            marriage,
        )

        partner = await self.bot.get_user_global(marriage)
        scenario = random.choice([
            _("You and {partner} went on a nice candlelit dinner."),
            _("You and {partner} had stargazed all night."),
            _("You and {partner} went to a circus that was in town."),
            _("You and {partner} went out to see a romantic movie."),
            _("You and {partner} went out to get ice cream."),
            _("You and {partner} had an anime marathon."),
            _("You and {partner} went for a spontaneous hiking trip."),
            _("You and {partner} decided to visit Paris."),
            _("You and {partner} went ice skating together."),
        ]).format(partner=(partner.mention if partner else _("Unknown User")))
        text = _("This increased their lovescore by {num}").format(num=num)
        await ctx.send(f"{scenario} {text}")
예제 #8
0
파일: misc.py 프로젝트: Gelbpunkt/IdleRPG
def calcchance(sword,
               shield,
               dungeon,
               level,
               luck,
               returnsuccess=False,
               booster=False,
               bonus=0):
    if returnsuccess is False:
        val1 = sword + shield + 75 - dungeon * 7 + bonus - level / Decimal("2")
        val2 = sword + shield + 75 - dungeon + bonus + level
        val1 = round(val1 * luck) if val1 >= 0 else round(val1 / luck)
        val2 = round(val2 * luck) if val2 >= 0 else round(val2 / luck)
        if booster:
            val1 += 25
            val2 += 25
        return (val1, val2)
    else:
        randomn = random.randint(0, 100)
        if booster:
            randomn -= 25
        success = (sword + shield + 75 - (dungeon * (random.randint(1, 7))) +
                   random.choice([level, -level / Decimal("2")]) + bonus)
        if success >= 0:
            success = round(success * luck)
        else:
            success = round(success / luck)
        return randomn <= success
예제 #9
0
    async def launch(self) -> None:
        with open("assets/data/names.txt") as f:
            names = f.read().splitlines()

        asyncio.create_task(self.event_handler())

        recommended_shard_count = await get_gateway_info()
        shard_count = recommended_shard_count + config.launcher.additional_shards
        clusters = get_cluster_list(shard_count)
        name, id = await get_app_info()
        print(f"[MAIN] Starting {name} ({id}) - {len(clusters)} clusters")
        used_names = []
        for i, shard_list in enumerate(clusters, 1):
            if not shard_list:
                continue
            name = ""
            while name == "" or name in used_names:
                name = random.choice(names)
            used_names.append(name)
            instance = Instance(i,
                                len(clusters),
                                shard_list,
                                shard_count,
                                name,
                                main=self)
            await instance.start()
            self.instances.append(instance)

        try:
            await asyncio.wait([i.future for i in self.instances])
        except Exception:
            print("[MAIN] Shutdown requested, stopping clusters")
            for instance in self.instances:
                await instance.stop()
예제 #10
0
    async def jester(self, ctx):
        _(
            """*Use to have Jester cast a spell ✨*

            This custom command was added on November 30th 2019, requested by User Jester😈🍭LaVorre.
            Anyone can use this command."""
        )
        await ctx.send(
            random.choice(
                [
                    _(
                        "Jester casts Spirit Guardians on herself. She, and the"
                        " spiritual hamster unicorns have a dance party."
                    ),
                    _(
                        "Jester casts Spiritual Weapon. A comically large spectral"
                        " lollipop🍭 suddenly appears."
                    ),
                    _(
                        "Jester casts Invoke Duplicity.... Now there's twice the Jester"
                        " for twice the pranks!"
                    ),
                ]
            )
        )
예제 #11
0
 async def combine(self, ctx):
     _("""Combine the mysterious puzzle pieces.""")
     async with self.bot.pool.acquire() as conn:
         if (await conn.fetchval(
                 'SELECT puzzles FROM profile WHERE "user"=$1;',
                 ctx.author.id) != 6):
             return await ctx.send(
                 _("The mysterious puzzles don't fit together... Maybe some are"
                   " missing?"))
         bg = random.choice([
             "https://i.imgur.com/iLJEGOf.png",
             "https://i.imgur.com/LDax1ag.png",
             "https://i.imgur.com/FpWXBev.png",
         ])
         await conn.execute(
             "UPDATE profile SET backgrounds=array_append(backgrounds, $1) WHERE"
             ' "user"=$2;',
             bg,
             ctx.author.id,
         )
         await conn.execute('UPDATE profile SET puzzles=0 WHERE "user"=$1;',
                            ctx.author.id)
     await ctx.send(
         _("You combined the puzzles! In your head a voice whispers: *Well done."
           " Now use `{prefix}eventbackground 1` to set your new background that"
           " you just acquired...*").format(prefix=ctx.prefix))
예제 #12
0
파일: __init__.py 프로젝트: indij/IdleRPG
    async def guess(self, ctx):
        _(
            """Guess a user by their avatar and discriminator (the four numbers after the # in a discord tag).

            Both their tag and nickname are accepted as answers. You have 20 seconds to guess.

            (This command has a channel cooldown of 20 seconds.)"""
        )
        m = random.choice(ctx.guild.members)
        em = discord.Embed(
            title=_("Can you guess who this is?"),
            description=_("Their discriminant is `#{disc}`").format(
                disc=m.discriminator
            ),
            color=m.color,
        )
        em.set_image(url=m.avatar_url)
        await ctx.send(embed=em)

        def check(msg):
            return (
                msg.content == m.name or msg.content == m.nick or msg.content == str(m)
            ) and msg.channel == ctx.channel

        try:
            msg = await self.bot.wait_for("message", check=check, timeout=20)
        except asyncio.TimeoutError:
            return await ctx.send(
                _("You didn't guess correctly! It was `{member}`!").format(member=m)
            )
        await ctx.send(_("{user}, you are correct!").format(user=msg.author.mention))
예제 #13
0
파일: __init__.py 프로젝트: indij/IdleRPG
 async def _ball(self, ctx, *, question: str):
     _(
         """Provides a variety of answers to all of your questions. If in doubt, ask the magic 8ball."""
     )
     results = [
         _("It is certain"),
         _("It is decidedly so"),
         _("Without a doubt"),
         _("Yes, definitely"),
         _("You may rely on it"),
         _("As I see it, yes"),
         _("Most likely"),
         _("Outlook good"),
         _("Yes"),
         _("Signs point to yes"),
         _("Reply hazy try again"),
         _("Ask again later"),
         _("Better not tell you now"),
         _("Cannot predict now"),
         _("Concentrate and ask again"),
         _("Don't count on it"),
         _("My reply is no"),
         _("My sources say no"),
         _("Outlook not so good"),
         _("Very doubtful"),
     ]
     await ctx.send(
         _("The :8ball: says: **{result}**.").format(result=random.choice(results))
     )
예제 #14
0
 async def create_random_item(self,
                              minstat,
                              maxstat,
                              minvalue,
                              maxvalue,
                              owner,
                              insert=True,
                              conn=None):
     owner = owner.id if isinstance(owner, (discord.User,
                                            discord.Member)) else owner
     item = {}
     item["owner"] = owner
     type_ = random.choice(ALL_ITEM_TYPES)
     hand = type_.get_hand()
     item["hand"] = hand.value
     item["type_"] = type_.value
     item["damage"] = (random.randint(minstat, maxstat)
                       if type_ != ItemType.Shield else 0)
     item["armor"] = (random.randint(minstat, maxstat)
                      if type_ == ItemType.Shield else 0)
     item["value"] = random.randint(minvalue, maxvalue)
     item["name"] = fn.weapon_name(type_.value)
     if hand == Hand.Both:
         item["damage"] = round(
             item["damage"] *
             2)  # both hands = higher damage, else they would be worse
         # The issue with multiplying by 2
         # is that everything will be even
         # so we have to force uneven ones
         if random.randint(1, 2) == 1:
             item["damage"] -= 1
     if insert:
         return await self.create_item(**item, conn=conn)
     return item
예제 #15
0
 async def start_joins(self):
     id_ = "".join(random.choice(string.ascii_letters) for i in range(7))
     await self.session.get(
         f"https://join.idlerpg.xyz/toggle/{id_}",
         headers={"Authorization": self.config.external.raidauth},
     )
     return id_
예제 #16
0
 async def _open(self, ctx):
     _("""Open the Winter Calendar once every day.""")
     today = datetime.datetime.utcnow().date()
     christmas_too_late = datetime.date(2021, 12, 25)
     first_dec = datetime.date(2021, 12, 1)
     if today >= christmas_too_late or today < first_dec:
         return await ctx.send(_("It's not calendar time yet..."))
     reward = rewards[today.day]
     reward_text = _("**You opened day {today}!**").format(today=today.day)
     async with self.bot.pool.acquire() as conn:
         if reward["puzzle"]:
             await conn.execute(
                 'UPDATE profile SET "puzzles"="puzzles"+1 WHERE "user"=$1;',
                 ctx.author.id,
             )
             text = _("A mysterious puzzle piece")
             reward_text = f"{reward_text}\n- {text}"
         if reward["crates"]:
             rarity = random.choice(["legendary"] + ["magic"] * 2 +
                                    ["rare"] * 5 + ["uncommon"] * 10 +
                                    ["common"] * 20)
             await conn.execute(
                 f'UPDATE profile SET "crates_{rarity}"="crates_{rarity}"+$1 WHERE'
                 ' "user"=$2;',
                 reward["crates"],
                 ctx.author.id,
             )
             await self.bot.log_transaction(
                 ctx,
                 from_=1,
                 to=ctx.author.id,
                 subject="crates",
                 data={
                     "Rarity": rarity,
                     "Amount": reward["crates"]
                 },
                 conn=conn,
             )
             text = _("{crates} {rarity} crate").format(
                 crates=reward["crates"], rarity=rarity)
             reward_text = f"{reward_text}\n- {text}"
         if reward["money"]:
             await conn.execute(
                 'UPDATE profile SET "money"="money"+$1 WHERE "user"=$2;',
                 reward["money"],
                 ctx.author.id,
             )
             await self.bot.log_transaction(
                 ctx,
                 from_=1,
                 to=ctx.author.id,
                 subject="money",
                 data={"Amount": reward["money"]},
                 conn=conn,
             )
             reward_text = f"{reward_text}\n- ${reward['money']}"
     await ctx.send(reward_text)
예제 #17
0
 async def process_levelup(self, ctx, new_level, old_level, conn=None):
     if conn is None:
         conn = await self.pool.acquire()
         local = True
     else:
         local = False
     if (reward := random.choice(["crates", "money", "item"])) == "crates":
         if new_level < 6:
             column = "crates_common"
             amount = new_level
             reward_text = f"**{amount}** <:CrateCommon:598094865666015232>"
         elif new_level < 10:
             column = "crates_uncommon"
             amount = round(new_level / 2)
             reward_text = f"**{amount}** <:CrateUncommon:598094865397579797>"
         elif new_level < 18:
             column = "crates_rare"
             amount = 2
             reward_text = "**2** <:CrateRare:598094865485791233>"
         elif new_level < 27:
             column = "crates_rare"
             amount = 3
             reward_text = "**3** <:CrateRare:598094865485791233>"
         else:
             column = "crates_magic"
             amount = 1
             reward_text = "**1** <:CrateMagic:598094865611358209>"
         await self.log_transaction(
             ctx,
             from_=0,
             to=ctx.author.id,
             subject="crates",
             data={
                 "Rarity": column.split("_")[1],
                 "Amount": amount
             },
         )
         await self.pool.execute(
             f'UPDATE profile SET {column}={column}+$1 WHERE "user"=$2;',
             amount,
             ctx.author.id,
         )
         await self.cache.update_profile_cols_rel(ctx.author.id,
                                                  **{column: amount})
예제 #18
0
파일: __init__.py 프로젝트: indij/IdleRPG
    async def yesno(self, ctx, *, question: str):
        _(
            """`<question>` - The question to answer

            An alternative to `{prefix}8ball` with some more blunt answers."""
        )
        possible_answers = [
            "Maybe",
            "I think so",
            "Why are you asking?",
            "I'd say yes",
            "Sure!",
            "I don't think so",
            "Leave me alone",
            "I need some time for myself",
            "Let's please talk about something else",
            "I like it",
            "Do you know what love is?",
            "I don't want to answer this",
            "Definitely",
            "Noone cares about that",
            "Let's talk about you and me",
            "Stop it and let's have fun together",
            "Life is a lie",
            "Are you gay?",
            "Do you know I am female?",
            "42",
            "No, just no",
            "What is the meaning of life?",
            "Ohhh, of course!",
            "Kiss me pleeeease",
            "I am tending to no",
            "Are you kidding me?",
            "Uhm... Yes",
            "Can I be your waifu?",
            "I don't care at all",
            "Sorry, sweetie, I am busy",
            "Let me sleep!",
            "Do you have plans for today?",
            "A biscuit is more entertaining than you",
            "Suicide isn't always the answer",
            "It could be yes, but I don't know",
            "Who knows?",
            "Actually you bore me",
            "Are you really that boring?",
            "Having sex with you is like waking up: BORING",
            "Orum sed non laborum",
            "Eyo noone is intered in that",
            "Possibly yes",
            "Wanna have a drink?",
        ]
        result = random.choice(possible_answers)
        em = discord.Embed(title=question, description=result, colour=ctx.author.colour)
        em.set_thumbnail(url=ctx.author.avatar_url)
        em.timestamp = datetime.datetime.now()
        await ctx.send(embed=em)
예제 #19
0
파일: bot.py 프로젝트: Gelbpunkt/IdleRPG
 async def process_levelup(self, ctx, new_level, old_level, conn=None):
     if conn is None:
         conn = await self.pool.acquire()
         local = True
     else:
         local = False
     if (reward := random.choice(["crates", "money", "item"])) == "crates":
         if new_level < 6:
             column = "crates_common"
             amount = new_level
             reward_text = f"**{amount}** {self.cogs['Crates'].emotes.common}"
         elif new_level < 10:
             column = "crates_uncommon"
             amount = round(new_level / 2)
             reward_text = f"**{amount}** {self.cogs['Crates'].emotes.uncommon}"
         elif new_level < 18:
             column = "crates_rare"
             amount = 2
             reward_text = f"**2** {self.cogs['Crates'].emotes.rare}"
         elif new_level < 27:
             column = "crates_rare"
             amount = 3
             reward_text = f"**3** {self.cogs['Crates'].emotes.rare}"
         else:
             column = "crates_magic"
             amount = 1
             reward_text = f"**1** {self.cogs['Crates'].emotes.magic}"
         await self.log_transaction(
             ctx,
             from_=0,
             to=ctx.author.id,
             subject="crates",
             data={
                 "Rarity": column.split("_")[1],
                 "Amount": amount
             },
         )
         await self.pool.execute(
             f'UPDATE profile SET {column}={column}+$1 WHERE "user"=$2;',
             amount,
             ctx.author.id,
         )
예제 #20
0
    def randomize(self):
        """
        Knocks down random walls to build a random perfect maze.

        Algorithm from http://mazeworks.com/mazegen/mazetut/index.htm
        """
        cell_stack = []
        cell = random.choice(self.cells)
        n_visited_cells = 1

        while n_visited_cells < len(self.cells):
            neighbors = [c for c in self.neighbors(cell) if c.is_full()]
            if len(neighbors):
                neighbor = random.choice(neighbors)
                cell.connect(neighbor)
                cell_stack.append(cell)
                cell = neighbor
                n_visited_cells += 1
            else:
                cell = cell_stack.pop()
예제 #21
0
    def randomize(self):
        if not hasattr(self, "randomize_attributes"):
            return

        for attribute in sorted(self.randomize_attributes):
            if isinstance(self.randomize_attributes[attribute], type):
                tob = self.randomize_attributes[attribute]
                candidates = [t for t in tob.every if t.rank >= 0]
                setattr(self, attribute, random.choice(candidates).index)
            else:
                minimum, maximum = self.randomize_attributes[attribute]
                setattr(self, attribute, random.randint(minimum, maximum))
예제 #22
0
    async def donatordaily(self, ctx):
        _("""Receive a daily booster. The booster can be a time, money or luck booster.

            (This command has a cooldown of 24 hours.)""")
        type_ = random.choice(["time", "money", "luck"])
        await self.bot.pool.execute(
            f'UPDATE profile SET "{type_}_booster"="{type_}_booster"+1 WHERE'
            ' "user"=$1;',
            ctx.author.id,
        )
        await ctx.send(
            _("You received a daily {type_} booster!").format(type_=type_))
예제 #23
0
    async def randomname(self, ctx):
        _("""Sends you my nickname from a random server.

            ⚠ Caution: may contain NSFW.""")
        g = random.choice([
            g for g in self.bot.guilds
            if g.me.display_name != self.bot.user.name
        ])
        info = (g.me.display_name, g.name)
        await ctx.send(
            _("In **{server}** I am called **{name}**.").format(server=info[1],
                                                                name=info[0]))
예제 #24
0
 async def forceround(self, ctx):
     _("""Enforces a new snowball round.""")
     with open("assets/data/tournament.json", "r+") as f:
         c = json.load(f)
         f.seek(0)
         for r in c["Matches"]:
             c["Participants"].append(random.choice(r))
         c["Matches"] = list(chunks(c["Participants"], 2))
         c["Participants"] = []
         json.dump(c, f)
         f.truncate()
     await ctx.send(_("Round forced!"))
예제 #25
0
 async def run(self, ctx):
     self.ctx = ctx
     # They pay for the roll
     await self.remove_money()
     # The result of the roll
     self.result = random.choice(ALL_NUMBERS)
     self.message = await ctx.send(
         _("<a:roulette:691749187284369419> Spinning the wheel..."))
     await asyncio.sleep(3)
     if self.result in self.numbers:
         await self.handle_win()
     else:
         await self.handle_loss()
예제 #26
0
파일: __init__.py 프로젝트: indij/IdleRPG
    async def choose(self, ctx, *results: str):
        _(
            """`<results...>` - The options to choose from

            Chooses a random option of supplied possiblies. For an option with multiple words, put it in "double quotes"."""
        )
        results = list(filter(lambda a: a.lower() != "or", results))
        if not results:
            return await ctx.send(_("Cannot choose from an empty list..."))
        await ctx.send(
            _("My choice is: **{result}**.").format(result=random.choice(results)),
            escape_mentions=True,
        )
예제 #27
0
    def get_damage(self, damage):
        self._health = max(0, self._health - (damage * 0.6))
        if self.health == 0:
            return

        random_operator = random.choice(self._active_operators)
        if len(self._active_operators) > 1:
            for operator in self._active_operators:
                if operator is random_operator:
                    operator.get_damage(damage * 0.2)
                else:
                    operator.get_damage((damage * 0.2) / (len(self._active_operators) - 1))
        else:
            random_operator.get_damage(damage * 0.4)
예제 #28
0
def main(*fnames):
    data = []
    for fname in fnames:
        with open(fname, 'r+') as fp:
            data.extend(json.load(fp))
            fp.close()

    i = 0
    stop = len(data)
    while True:
        freeze = random.random() * 0.5
        step = random.randint(1, 3)
        slc = min(i + step, stop - 1)

        tmp_ = data[i:slc]
        if tmp_:
            for x in tmp_:
                x.update(status=weighted_choice([('error',
                                                  .05), ('debug',
                                                         .65), ('info', .3)]))
            func = random.choice([prettify_json, prettify_pprint])
            shoot(func(tmp_))
            i += step
        else:
            i = 0
            # clear output each time the whole trace file is out
            os.system('clear')
            spinning_cursor(random.random())

        # occasionally output line breaks
        if weighted_choice([(True, 1), (False, 9)]):
            shoot('\n')

        # occasionally output table
        if weighted_choice([(True, 0.5), (False, 9.5)]):
            shoot('\n')
            shoot_table()
            freeze = random.uniform(0.2, 0.8)

        # occasionally output the whole random file from the current dir
        if weighted_choice([(True, 0.1), (False, 9.9)]):
            try:
                shoot_file()
            except IndexError:
                pass
            freeze = random.uniform(0.2, 0.8)

        time.sleep(freeze)
예제 #29
0
    async def pray(self, ctx):
        _(
            # xgettext: no-python-format
            """Pray to your God in order to gain a random amont of favor points, ranging from 0 to 1000.

            There is a 33% chance you will gain 0 favor, a 33% chance to gain anywhere from 0 to 500 favor and a 33% chance to gain anywhere from 500 to 1000 favor.

            (This command has a cooldown until 12am UTC.)""")
        if (rand := random.randint(0, 2)) == 0:
            message = random.choice([
                _("They obviously didn't like your prayer!"),
                _("Noone heard you!"),
                _("Your voice has made them screw off."),
                _("Even a donkey would've been a better follower than you."),
            ])
            val = 0
예제 #30
0
 async def choose_idol(self) -> None:
     possible_idols = [p for p in self.game.players if p != self]
     try:
         idol = await self.choose_users(
             "Choose your Idol. You will turn into a Werewolf if they die.",
             list_of_users=possible_idols,
             amount=1,
         )
     except asyncio.TimeoutError:
         idol = [random.choice(possible_idols)]
         await self.send(
             "You didn't choose anything. A random player will be chosen for you."
         )
     if idol:
         self.idol = idol[0]
     await self.send(f"**{self.idol.user}** became your Idol.")
예제 #31
0
    def intershuffle(cls):
        if not hasattr(cls, "intershuffle_attributes"):
            return

        hard_shuffle = False
        if (len(set([o.rank for o in cls.every])) == 1
                or all([o.rank == o.index for o in cls.every])):
            hard_shuffle = True

        for attributes in cls.intershuffle_attributes:
            candidates = [o for o in cls.every
                          if o.rank >= 0 and o.intershuffle_valid]
            if hard_shuffle:
                shuffled = list(candidates)
                random.shuffle(shuffled)
            else:
                candidates = sorted(candidates, key=lambda c: c.rank)
                shuffled = list(candidates)
                max_index = len(candidates)-1
                done = set([])
                for i, o in enumerate(candidates):
                    new_index = i
                    if shuffled[i] in done:
                        continue
                    while random.choice([True, False]):
                        new_index += min(1, (max_index / 10.0))
                    new_index = int(round(new_index))
                    new_index = min(new_index, max_index)
                    a, b = shuffled[i], shuffled[new_index]
                    done.add(a)
                    shuffled[i] = b
                    shuffled[new_index] = a

            if isinstance(attributes, str) or isinstance(attributes, unicode):
                attributes = [attributes]

            for attribute in attributes:
                swaps = []
                for a, b in zip(candidates, shuffled):
                    aval, bval = getattr(a, attribute), getattr(b, attribute)
                    swaps.append(bval)
                for a, bval in zip(candidates, swaps):
                    setattr(a, attribute, bval)
예제 #32
0
 async def handle_maid(self, death: Player) -> None:
     if self.in_love:
         return
     try:
         action = await self.game.ctx.bot.paginator.Choose(
             entries=["Yes", "No"],
             return_index=True,
             title=f"Would you like to swap cards with {death.user}?",
         ).paginate(self.game.ctx, location=self.user)
     except self.game.ctx.bot.paginator.NoChoice:
         return
     if action == 0:
         self.enchanted = False
         if self.is_sheriff:
             self.is_sheriff = False
             random.choice(self.game.alive_players).is_sheriff = True
         self.role = death.role
         await self.send_information()
         if self.role == Role.WILD_CHILD:
             await self.choose_idol()