diff options
| author | 2021-10-27 19:08:34 -0400 | |
|---|---|---|
| committer | 2022-02-09 18:13:37 -0500 | |
| commit | 805cb8025433c87454027aad4e70bbe72b86dbdb (patch) | |
| tree | 8065bbe3182262ed7ea99460a12e8c5587f4cfec /bot/exts/events | |
| parent | Use partial ellipsis in revealing answer (diff) | |
Bluenix's reviews' changes
Diffstat (limited to 'bot/exts/events')
| -rw-r--r-- | bot/exts/events/trivianight/_questions.py | 32 | ||||
| -rw-r--r-- | bot/exts/events/trivianight/_scoreboard.py | 66 | ||||
| -rw-r--r-- | bot/exts/events/trivianight/trivianight.py | 3 | 
3 files changed, 51 insertions, 50 deletions
| diff --git a/bot/exts/events/trivianight/_questions.py b/bot/exts/events/trivianight/_questions.py index f94b340f..741e8422 100644 --- a/bot/exts/events/trivianight/_questions.py +++ b/bot/exts/events/trivianight/_questions.py @@ -7,9 +7,19 @@ from discord import Embed, Interaction  from discord.ui import Button, View  from bot.constants import Colours, NEGATIVE_REPLIES +  from ._scoreboard import Scoreboard +class UserScore: +    """Marker class for passing into the scoreboard to add points/record speed.""" + +    __slots__ = ("user_id",) + +    def __init__(self, user_id: int): +        self.user_id = user_id + +  class CurrentQuestion(TypedDict):      """Representing the different 'keys' of the question taken from the JSON.""" @@ -26,30 +36,26 @@ class QuestionButton(Button):          self.users_picked = users_picked          super().__init__(label=label, style=discord.ButtonStyle.green) -    def set_time(self) -> None: -        """Sets an instance attribute to a perf counter simulating the question beginning.""" -        self._time = perf_counter() -      async def callback(self, interaction: Interaction) -> None:          """When a user interacts with the button, this will be called."""          if interaction.user.id not in self.users_picked.keys(): -            self.users_picked[interaction.user.id] = [self.label, 1, perf_counter() - self._time] +            self.users_picked[interaction.user.id] = [self.label, True, perf_counter() - self._time]              await interaction.response.send_message(                  embed=Embed( -                    title="Success!", +                    title="Confirming that..",                      description=f"You chose answer {self.label}.",                      color=Colours.soft_green                  ),                  ephemeral=True              ) -        elif self.users_picked[interaction.user.id][1] < 2: +        elif self.users_picked[interaction.user.id][1] is True:              self.users_picked[interaction.user.id] = [ -                self.label, self.users_picked[interaction.user.id][1] + 1, perf_counter() - self._time +                self.label, False, perf_counter() - self._time              ]              await interaction.response.send_message(                  embed=Embed( -                    title="Success!", -                    description=f"You changed your answer to answer choice {self.label}.", +                    title="Confirming that..", +                    description=f"You changed your answer to answer {self.label}.",                      color=Colours.soft_green                  ),                  ephemeral=True @@ -86,8 +92,9 @@ class QuestionView(View):          for label, answer in zip("ABCD", self.current_question["answers"]):              question_embed.add_field(name=f"Answer {label}", value=answer, inline=False) +        current_time = perf_counter()          for button in self.buttons: -            button.set_time() +            button._time = current_time          return question_embed @@ -170,7 +177,6 @@ class Questions:          """Terminates answering of the question and displays the correct answer."""          scores, answer_embed = self.view.end_question()          for user, score in scores.items(): -            self.scoreboard[f"points: {user}"] = 1 -            self.scoreboard[f"speed: {user}"] = score[2] +            self.scoreboard[UserScore(user)] = {"points": 1, "speed": score[2]}          return answer_embed diff --git a/bot/exts/events/trivianight/_scoreboard.py b/bot/exts/events/trivianight/_scoreboard.py index c39fc666..dbec966d 100644 --- a/bot/exts/events/trivianight/_scoreboard.py +++ b/bot/exts/events/trivianight/_scoreboard.py @@ -20,36 +20,38 @@ class ScoreboardView(View):      async def create_main_leaderboard(self) -> Embed:          """Helper function that iterates through `self.points` to generate the main leaderboard embed.""" -        main_embed = Embed( -            title="Winners of the Trivia Night", -            description="See the leaderboard for who got the most points during the Trivia Night!", -            color=Colours.python_blue, -        ) -          formatted_string = "" -        participant_points = list(self.points.items())[:30] if len(self.points.items()) > 30 else self.points.items() -        for current_placement, (user, points) in participant_points: +        for current_placement, (user, points) in enumerate(self.points.items()): +            if current_placement + 1 > 30: +                break +              user = await self.bot.fetch_user(int(user))              formatted_string += f"`{current_placement + 1}`. {user.mention} "              formatted_string += f"({points} pts)\n"              if (current_placement + 1) % 10 == 0:                  formatted_string += "⎯⎯⎯⎯⎯⎯⎯⎯\n" -            current_placement += 1 + +        main_embed = Embed( +            title="Winners of the Trivia Night", +            description=formatted_string, +            color=Colours.python_blue, +        )          return main_embed      async def _create_speed_embed(self) -> Embed:          """Helper function that iterates through `self.speed` to generate a leaderboard embed."""          formatted_string = "" -        participant_speed = list(self.speed.items())[:30] if len(self.speed.items()) > 30 else self.speed.items() -        for current_placement, (user, time_taken) in enumerate(participant_speed): +        for current_placement, (user, time_taken) in enumerate(self.speed.items()): +            if current_placement + 1 > 30: +                break +              user = await self.bot.fetch_user(int(user))              formatted_string += f"`{current_placement + 1}`. {user.mention} " -            formatted_string += f"({time_taken:.1f}s)\n" +            formatted_string += f"({(time_taken[-1] / time_taken[0]):.1f}s)\n"              if (current_placement + 1) % 10 == 0:                  formatted_string += "⎯⎯⎯⎯⎯⎯⎯⎯\n" -            current_placement += 1          speed_embed = Embed(              title="Average time taken to answer a question", @@ -61,9 +63,10 @@ class ScoreboardView(View):      def _get_rank(self, member: Member) -> Embed:          """Gets the member's rank for the points leaderboard and speed leaderboard."""          rank_embed = Embed(title=f"Ranks for {member.display_name}", color=Colours.python_blue) +        # These are stored as strings so that the last digit can be determined to choose the suffix          try: -            points_rank = str(list(self.points.keys()).index(str(member.id)) + 1) -            speed_rank = str(list(self.speed.keys()).index(str(member.id)) + 1) +            points_rank = str(list(self.points.keys()).index(member.id) + 1) +            speed_rank = str(list(self.speed.keys()).index(member.id) + 1)          except ValueError:              return Embed(                  title=choice(NEGATIVE_REPLIES), @@ -76,7 +79,7 @@ class ScoreboardView(View):              name="Total Points",              value=(                  f"You got {points_rank}{'th' if not (suffix := suffixes.get(points_rank[-1])) else suffix} place" -                f" with {self.points[str(member.id)]} points." +                f" with {self.points[member.id]} points."              ),              inline=False          ) @@ -84,7 +87,7 @@ class ScoreboardView(View):              name="Average Speed",              value=(                  f"You got {speed_rank}{'th' if not (suffix := suffixes.get(speed_rank[-1])) else suffix} place" -                f" with a time of {(self.speed[str(member.id)][1] / self.speed[str(member.id)][0]):.1f} seconds." +                f" with a time of {(self.speed[member.id][1] / self.speed[member.id][0]):.1f} seconds."              ),              inline=False          ) @@ -105,24 +108,17 @@ class Scoreboard:      """Class for the scoreboard for the Trivia Night event."""      def __setitem__(self, key: str, value: int): -        if key.startswith("points: "): -            key = key.removeprefix("points: ") -            if key not in self.view.points.keys(): -                self.view.points[key] = value -            else: -                self.view.points[key] += self.view.points[key] -        elif key.startswith("speed: "): -            key = key.removeprefix("speed: ") -            if key not in self.view.speed.keys(): -                self.view.speed[key] = [1, value] -            else: -                self.view.speed[key] = [self.view.speed[key][0] + 1, self.view.speed[key][1] + value] - -    def __getitem__(self, item: str): -        if item.startswith("points: "): -            return self.view.points[item.removeprefix("points: ")] -        elif item.startswith("speed: "): -            return self.view.speed[item.removeprefix("speed: ")] +        if key.user_id not in self.view.points.keys(): +            self.view.points[key.user_id] = value["points"] +        else: +            self.view.points[key.user_id] += self.view.points[key.user_id] + +        if key.user_id not in self.view.speed.keys(): +            self.view.speed[key.user_id] = [1, value["speed"]] +        else: +            self.view.speed[key.user_id] = [ +                self.view.speed[key.user_id][0] + 1, self.view.speed[key.user_id][1] + value["speed"] +            ]      async def display(self) -> Union[Embed, View]:          """Returns the embed of the main leaderboard along with the ScoreboardView.""" diff --git a/bot/exts/events/trivianight/trivianight.py b/bot/exts/events/trivianight/trivianight.py index 2ec869ab..bb7c205b 100644 --- a/bot/exts/events/trivianight/trivianight.py +++ b/bot/exts/events/trivianight/trivianight.py @@ -1,4 +1,3 @@ -import logging  from json import loads  from random import choice @@ -7,6 +6,7 @@ from discord.ext import commands  from bot.bot import Bot  from bot.constants import Colours, POSITIVE_REPLIES +  from ._questions import QuestionView, Questions  from ._scoreboard import Scoreboard, ScoreboardView @@ -30,7 +30,6 @@ class TriviaNight(commands.Cog):          json_text = (await ctx.message.attachments[0].read()).decode("utf8")          serialized_json = loads(json_text)          self.questions.view = QuestionView() -        logging.getLogger(__name__).debug(self.questions.view)          self.scoreboard.view = ScoreboardView(self.bot)          self.questions.set_questions(serialized_json)          success_embed = Embed( | 
