Example #1
0
    async def edit(self, ctx, modifier, *, value):
        i = ModifierCheck(modifier, self.tournament.modifiers)

        if i is False:
            raise commands.BadArgument(f"`{modifier}` is not active.")

        modifier = self.tournament.modifiers[i]
        if isinstance(modifier, str):
            raise commands.BadArgument(
                f"The value for `{modifier}` cannot be edited.")

        old_value = modifier['value']
        j = self.modifiers[ModifierCheck(modifier['name'], self.modifiers)]
        modifier['value'] = await ModifierUtils.convert_value(
            ctx, j['value'], value)

        if old_value == modifier['value']:
            await ctx.send("Nothing changed. Silly!")
            return

        await ctx.send(
            f"{Emote.check} The value for `{modifier['name']}` was changed to **{modifier['value']}**."
        )
        fields = [{
            'name': "Old Value",
            'value': old_value
        }, {
            'name': "New Value",
            'value': modifier['value']
        }]
        Log("Modifier Edited",
            description=
            f"{ctx.author.mention} changed the value of `{modifier['name']}` for **{self.tournament.name}**.",
            color=Color.dark_teal(),
            fields=fields)
Example #2
0
    async def spectate(self, ctx):
        await self.CheckRequirements(ctx.author)
        if ModifierCheck("SpectatorsAllowed",
                         self.tournament.modifiers) is False:
            raise TournamentJoinException(
                "spectators are not allowed for this tournament!")

        if ctx.author in self.tournament.spectators:
            raise TournamentJoinException("you are already a spectator!")

        spec_count = len(self.tournament.spectators)
        join_msg = f"{Emote.join} {ctx.author.mention} joined the spectators. **{str(spec_count + 1)}** spectators are now watching the tournament."
        if spec_count == 0:  # First join, make singular
            i = join_msg[-35:].index("s are") + len(join_msg) - 35
            join_msg = join_msg[:i] + " is" + join_msg[i + 5:]

        await ctx.author.add_roles(self.roles.spectator)
        await self.channels.t_chat.send(join_msg)
        self.tournament.spectators.append(ctx.author)
        Log("Spectator Joined",
            description=
            f"{ctx.author.mention} joined **{self.tournament.name}**.",
            color=Color.dark_green(),
            fields=[{
                'name': "Spectator Count",
                'value': str(spec_count + 1)
            }])

        embed = UpdatedEmbed(self.tournament)
        await self.tournament.msg.edit(embed=embed)
Example #3
0
    async def join(self, ctx):
        await self.CheckRequirements(ctx.author)

        player_count = len(self.tournament.get_participants())
        mod_index = ModifierCheck("MaxParticipants", self.tournament.modifiers)

        if mod_index is not False:
            max_count = self.tournament.modifiers[mod_index]['value']
        else:
            max_count = 15  # Default
        if player_count >= max_count:
            raise TournamentJoinException(
                f"the tournament is full! The maximum number of participants is **{str(max_count)}**."
            )

        join_msg = f"{Emote.join} {ctx.author.mention} joined. **{str(player_count + 1)}** players are now ready."

        if player_count == 0:  # First join, make singular
            i = join_msg[-35:].index("s are") + len(join_msg) - 35
            join_msg = join_msg[:i] + " is" + join_msg[i + 5:]

        user = User.fetch_by_id(ctx, ctx.author.id)

        if user.participations == 0:
            join_msg += "\nThis is the first tournament they are participating in. Welcome! 🎉"
            await SendFirstTournamentMessage(ctx)
        if user.ign is None:
            join_msg += "\nThis player does not have an IGN set yet."
        else:
            join_msg += f"\nIGN: `{user.ign}`"

        ign_cache[ctx.author.id] = user.ign
        await ctx.author.add_roles(self.roles.participant)
        await ctx.author.remove_roles(self.roles.spectator)
        await self.channels.t_chat.send(join_msg)
        Log("Participant Joined",
            description=
            f"{ctx.author.mention} joined **{self.tournament.name}**.",
            color=Color.dark_green(),
            fields=[{
                'name': "Player Count",
                'value': str(player_count + 1)
            }])
        self.tournament.add_participant(ctx.author)
        if ctx.author in self.tournament.spectators:
            self.tournament.spectators.remove(ctx.author)

        embed = UpdatedEmbed(self.tournament)
        await self.tournament.msg.edit(embed=embed)
        await self.checklist.update_text(ctx, self.tournament)
Example #4
0
    async def add(self, ctx, modifier, *, value=None):
        i = ModifierCheck(modifier, self.modifiers)

        if i is False:
            raise commands.BadArgument(f"Unknown modifier `{modifier}`.")

        if value is None and modifier not in self.modifiers:
            raise commands.errors.MissingRequiredArgument(
                Parameter('value', Parameter.KEYWORD_ONLY))

        if ModifierCheck(modifier, self.tournament.modifiers) is not False:
            raise commands.BadArgument(
                f"`{modifier}` has already been added to the tournament.")

        modifier = self.modifiers[i]
        fields = []

        if isinstance(modifier, dict):  # Value Settable Modifier
            modifier = modifier.copy()
            modifier['value'] = await ModifierUtils.convert_value(
                ctx, modifier['value'], value)
            fields.append({'name': "New Value", 'value': modifier['value']})
            await ctx.send(
                f"{Emote.check} `{modifier['name']}` was set to **{value}**.")
        else:
            await ctx.send(
                f"{Emote.check} `{modifier}` is now active for this tournament."
            )

        self.tournament.modifiers.append(modifier)
        if isinstance(modifier, dict):
            modifier = modifier['name']
        Log("Modifier Added",
            description=
            f"{ctx.author.mention} added the modifier `{modifier}` to **{self.tournament.name}**.",
            color=Color.dark_teal(),
            fields=fields)
Example #5
0
    async def start(self, ctx):
        if self.tournament.status >= 3:
            raise commands.BadArgument("The tournament has already started.")

        req = ('name', 'host')
        missing = []
        for attr in req:
            if getattr(self.tournament, attr) is None:
                missing.append("`" + attr + "`")
        if missing:
            items = " and ".join(item for item in missing)
            raise commands.BadArgument(
                f"You have not specified a {items} for the tournament.")

        if self.tournament.time is None:
            self.tournament.time = datetime.utcnow()

        await self.tournament.host.add_roles(self.roles.temp_host)
        host_id = self.tournament.host.id
        ign_cache[host_id] = User.fetch_attr_by_id(host_id, "IGN")
        User.fetch_attr_by_id(host_id, "IGN")

        await ctx.message.add_reaction(Emote.check)
        Log("Tournament Started",
            description=
            f"{ctx.author.mention} started **{self.tournament.name}**.",
            color=Color.green())

        self.tournament.status = Status.Opened
        embed = UpdatedEmbed(self.tournament)

        try:
            msg = await self.channels.t_channel.fetch_message(
                self.channels.t_channel.last_message_id)
            await msg.delete()
        except (AttributeError, NotFound):
            pass

        self.tournament.msg = await self.channels.t_channel.send(
            f"Tournament **{self.tournament.name}** has started!"
            f" {self.roles.tournament.mention}",
            embed=embed)
        await self.tournament.msg.add_reaction(Emote.join)
        if ModifierCheck("SpectatorsAllowed",
                         self.tournament.modifiers) is not False:
            await self.tournament.msg.add_reaction("📽️")

        self.checklist = await Checklist.create(ctx)
Example #6
0
    async def remove(self, ctx, modifier):
        i = ModifierCheck(modifier, self.tournament.modifiers)

        if i is False:
            raise commands.BadArgument(
                f"Modifier `{modifier}` is not active on this tournament.")

        old = self.tournament.modifiers[i]
        self.tournament.modifiers.pop(i)
        await ctx.send(f"{Emote.check} `{modifier}` has been removed.")
        fields = []
        if isinstance(old, dict):
            fields.append({'name': "Old Value", 'value': old['value']})
        Log("Modifier Removed",
            description=
            f"{ctx.author.mention} has removed `{modifier}` from **{self.tournament.name}**.",
            color=Color.dark_teal(),
            fields=fields)
Example #7
0
    def calculate_xp_for(self, player, streak):
        '''
        Participation: 50xp
        Winner: 100xp
        Solo win: 50xp
        Win streak: 25xp * streak
        Full tournament: 25xp
        '''
        xp = 50  # Default for participation
        summary = "Participation: `50xp`"

        if player in self.winners:
            xp += 100
            summary += "\nWinner: `100xp`"

            if len(self.winners) == 1:
                xp += 50
                summary += "\nSolo Win: `50xp`"

            if streak >= 2:
                add = streak * 25
                xp += add
                summary += f"\n{streak}x Win Streak: `{add}xp`"

        player_count = len(self.participants)
        mindex = ModifierCheck('MaxParticipants', self.modifiers)

        if mindex is not False:
            max_players = self.modifiers[mindex]['value']
        else:
            max_players = 15

        if player_count == max_players:
            xp += 25
            summary += "\nFull Tournament: `25xp`"

        summary += f"\n\n**Total:** `{xp}xp`"

        return summary, xp
Example #8
0
    def embed_message(self):
        embed = Embed()  # This acts as the list of fields
        # Tournament Info
        for attr in ['host', 'prize', 'roles', 'note']:
            value = getattr(self, attr)
            if attr is not None and value is not None:
                if attr == 'host':
                    value = value.mention
                embed.add_field(name=attr.title(), value=value, inline=True)

        # Participant List
        p_list = ""
        player_list = self.get_participants()
        for user in player_list:
            p_list += user.mention + "\n"
        if p_list == "":
            p_list = "This seems empty..."

        if ModifierCheck('SpectatorsAllowed', self.modifiers) is not False:
            spectators_count = len(self.spectators)
            if spectators_count > 0:
                p_list += f"\n**{spectators_count}** player is also spectating this tournament."
                if spectators_count >= 2:  # Make plural
                    sindex = p_list.find(" is")
                    p_list = p_list[:sindex] + "s are" + p_list[sindex + 5:]

        participants_count = str(len(player_list))
        mindex = ModifierCheck('MaxParticipants', self.modifiers)
        if mindex is not False:
            title = f"Participants ({participants_count}/{self.modifiers[mindex]['value']})"
        else:
            title = f"Participants ({participants_count}/15)"
        embed.add_field(name=title, value=p_list, inline=False)

        # Tournament Modifiers and Joins
        if self.status == Status.Opened:
            embed.add_field(
                name=
                f"You can join the tournament by adding a {Emote.join} reaction to this message.",
                value=
                f"You can also type `;join` in <#553886807373381635> to enter the game.",
                inline=False)

            index = ModifierCheck('RequiredRole', self.modifiers)
            if index is not False:
                embed.add_field(
                    name="Required role to join",
                    value=
                    f"You must have the {self.modifiers[index]['value'].mention} role in order to join this tournament!",
                    inline=False)

            if ModifierCheck('SpectatorsAllowed', self.modifiers) is not False:
                embed.add_field(
                    name="Spectators can enter this tournament",
                    value=
                    "You can react with the 📽️ emoji or type `;spectate` to join as a spectator!",
                    inline=False)

        else:
            embed.add_field(
                name="This tournament has started a few minutes ago",
                value="You can no longer join this game!",
                inline=False)

        return embed