diff options
author | 2021-11-17 17:47:09 -0500 | |
---|---|---|
committer | 2022-02-09 18:13:37 -0500 | |
commit | 07ac7f87610d513342e9393c29ea49c67cb76215 (patch) | |
tree | 5ccbaaeb57b051c55bdc7f7e59a7ce2b9a300906 /bot | |
parent | fixing rivianight reset bugs (diff) |
bluenix review changes
Diffstat (limited to 'bot')
-rw-r--r-- | bot/exts/events/trivianight/__init__.py | 7 | ||||
-rw-r--r-- | bot/exts/events/trivianight/_questions.py | 38 | ||||
-rw-r--r-- | bot/exts/events/trivianight/_scoreboard.py | 7 | ||||
-rw-r--r-- | bot/exts/events/trivianight/trivianight.py | 7 |
4 files changed, 26 insertions, 33 deletions
diff --git a/bot/exts/events/trivianight/__init__.py b/bot/exts/events/trivianight/__init__.py index e69de29b..87de18e0 100644 --- a/bot/exts/events/trivianight/__init__.py +++ b/bot/exts/events/trivianight/__init__.py @@ -0,0 +1,7 @@ +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 diff --git a/bot/exts/events/trivianight/_questions.py b/bot/exts/events/trivianight/_questions.py index 9f2b20da..2bbff1d7 100644 --- a/bot/exts/events/trivianight/_questions.py +++ b/bot/exts/events/trivianight/_questions.py @@ -1,4 +1,3 @@ -import logging from random import choice, randrange from time import perf_counter from typing import Optional, TypedDict, Union @@ -9,19 +8,9 @@ from discord.ui import Button, View from bot.constants import Colours, NEGATIVE_REPLIES +from . import UserScore from ._scoreboard import Scoreboard -logger = logging.getLogger(__name__) - - -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.""" @@ -100,7 +89,7 @@ class QuestionView(View): self.current_labels = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"[:len(self.current_question["answers"])] question_embed = Embed( title=f"Question {self.current_question['number']}", - description=self.current_question["description"], + description=self.current_question["obfuscated_description"], color=Colours.python_yellow ) self.buttons = [QuestionButton(label, self.users_picked, self) for label in self.current_labels] @@ -128,11 +117,6 @@ class QuestionView(View): return_dict = {name: (*info, info[0] == label) for name, info in self.users_picked.items()} all_players = list(self.users_picked.items()) - # Maps the % of people who got it right to a color, from a range of red to green - percentage_to_color = { - range(0, 26): 0xFC94A1, range(26, 51): 0xFFCCCB, range(51, 76): 0xCDFFCC, range(76, 101): 0xB0F5AB - } - answer_embed = Embed( title=f"The correct answer for Question {self.current_question['number']} was..", description=self.current_question["correct"] @@ -146,13 +130,12 @@ class QuestionView(View): for answer_choice in labels } - answers_chosen = dict(sorted(answers_chosen.items(), key=lambda item: item[1], reverse=True)) - for idx, (answer, percent) in enumerate(answers_chosen.items()): # Setting the color of answer_embed to the % of people that got it correct via the mapping if idx == 0: - all_ranges = [range(0, 26), range(26, 51), range(51, 76), range(76, 101)] - answer_embed.color = percentage_to_color[all_ranges[round(percent * 100) // 25 - 1]] + # Maps the % of people who got it right to a color, from a range of red to green + percentage_to_color = [0xFC94A1, 0xFFCCCB, 0xCDFFCC, 0xB0F5AB, 0xB0F5AB] + answer_embed.color = percentage_to_color[round(percent * 100) // 25] # The `ord` function is used here to change the letter to its corresponding position answer_embed.add_field( @@ -206,6 +189,8 @@ class Questions: question_number = number - 1 self.questions[question_number]["visited"] = True + + # The `self.view` refers to the QuestionView self.view.current_question = self.questions[question_number] def list_questions(self) -> Union[Embed, str]: @@ -225,12 +210,12 @@ class Questions: ) spaces = len( sorted( - self.questions, key=lambda question: len(question['description'].replace("\u200b", "")) - )[-1]["description"].replace("\u200b", "") + self.questions, key=lambda question: len(question['description']) + )[-1]["description"] ) + 3 formatted_string = "" for question in self.questions: - question_description = question["description"].replace("\u200b", "") + question_description = question["description"] formatted_string += f"`Q{question['number']}: {question_description}" \ f"{' ' * (spaces - len(question_description) + 2)}" \ f"|` {':x:' if not question.get('visited') else ':white_check_mark:'}\n" @@ -245,8 +230,7 @@ class Questions: """Terminates answering of the question and displays the correct answer.""" scores, answer_embed, time_limit, total_points = self.view.end_question() for user, score in scores.items(): - # Overhead with calculating scores leads to inflated times, subtracts 0.5 to give an accurate depiction - time_taken = score[2] - 0.5 + time_taken = score[2] point_calculation = (1 - (time_taken / time_limit) / 2) * total_points if score[-1] is True: self.scoreboard[UserScore(user)] = {"points": point_calculation, "speed": time_taken} diff --git a/bot/exts/events/trivianight/_scoreboard.py b/bot/exts/events/trivianight/_scoreboard.py index 08025214..635660a2 100644 --- a/bot/exts/events/trivianight/_scoreboard.py +++ b/bot/exts/events/trivianight/_scoreboard.py @@ -1,5 +1,4 @@ from random import choice -from typing import Union import discord.ui from discord import ButtonStyle, Embed, Interaction, Member @@ -8,6 +7,8 @@ from discord.ui import Button, View from bot.bot import Bot from bot.constants import Colours, NEGATIVE_REPLIES +from . import UserScore + class ScoreboardView(View): """View for the scoreboard.""" @@ -110,7 +111,7 @@ class ScoreboardView(View): class Scoreboard: """Class for the scoreboard for the Trivia Night event.""" - def __setitem__(self, key: str, value: int): + def __setitem__(self, key: UserScore, value: dict): if value.get("points") and key.user_id not in self.view.points.keys(): self.view.points[key.user_id] = value["points"] elif value.get("points"): @@ -123,6 +124,6 @@ class Scoreboard: self.view.speed[key.user_id][0] + 1, self.view.speed[key.user_id][1] + value["speed"] ] - async def display(self) -> Union[Embed, View]: + async def display(self) -> tuple[Embed, View]: """Returns the embed of the main leaderboard along with the ScoreboardView.""" return await self.view.create_main_leaderboard(), self.view diff --git a/bot/exts/events/trivianight/trivianight.py b/bot/exts/events/trivianight/trivianight.py index 224b0620..615a9dd3 100644 --- a/bot/exts/events/trivianight/trivianight.py +++ b/bot/exts/events/trivianight/trivianight.py @@ -51,7 +51,7 @@ class TriviaNight(commands.Cog): The JSON provided is formatted where it is a list of dictionaries, each dictionary containing the keys below: - number: int (represents the current question #) - description: str (represents the question itself) - - answers: list (represents the different answers possible, must be a length of 4) + - answers: list[str] (represents the different answers possible, must be a length of 4) - correct: str (represents the correct answer in terms of what the correct answer is in `answers` - time: Optional[int] (represents the timer for the question and how long it should run, default is 10) - points: Optional[int] (represents how many points are awarded for each question, default is 10) @@ -79,7 +79,8 @@ class TriviaNight(commands.Cog): raise commands.BadArgument("Invalid JSON") for idx, question in enumerate(serialized_json): - serialized_json[idx] = {**question, **{"description": self.unicodeify(question["description"])}} + serialized_json[idx]["obfuscated_description"] = self.unicodeify(question["description"]) + self.questions.view = QuestionView() self.scoreboard.view = ScoreboardView(self.bot) self.questions.set_questions(serialized_json) @@ -101,7 +102,7 @@ class TriviaNight(commands.Cog): if "visited" in question.keys(): del question["visited"] - self.questions.questions = list(all_questions) + self.questions.set_questions(list(all_questions)) success_embed = Embed( title=choice(POSITIVE_REPLIES), |