From 4c3312a642f1876427d17a41eeb9c912f9cd4b06 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Fri, 7 May 2021 10:41:30 -0300 Subject: Add 30 math questions and 30 science questions to trivia_quiz.json --- bot/resources/evergreen/trivia_quiz.json | 331 +++++++++++++++++++++++++++++++ 1 file changed, 331 insertions(+) diff --git a/bot/resources/evergreen/trivia_quiz.json b/bot/resources/evergreen/trivia_quiz.json index a4225eb1..b20b953f 100644 --- a/bot/resources/evergreen/trivia_quiz.json +++ b/bot/resources/evergreen/trivia_quiz.json @@ -44,6 +44,24 @@ ], "question": "What was the first game Yoshi appeared in?", "answer": "Super Mario World" + }, + { + "id": 6, + "hints": [ + "They were used alternatively to playing cards.", + "They generally have handdrawn nature images on them." + ], + "question": "What did Nintendo make before video games and toys?", + "answer": "Hanafuda, Hanafuda cards" + }, + { + "id": 7, + "hints": [ + "Before being Nintendo's main competitor in home gaming, they were successful in arcades.", + "Their first console was called the Master System." + ], + "question": "Who was Nintendo's biggest competitor in 1990?", + "answer": "Sega" } ], "general": [ @@ -269,5 +287,318 @@ "answer": "1492", "info": "The explorer Christopher Columbus made four trips across the Atlantic Ocean from Spain: in 1492, 1493, 1498 and 1502. He was determined to find a direct water route west from Europe to Asia, but he never did. Instead, he stumbled upon the Americas" } + ], + "math": [ + { + "id": 201, + "question": "What is the highest power of a biquadratic polynomial?", + "answer": "4, four" + }, + { + "id": 202, + "question": "What is the formula for surface area of a sphere?", + "answer": "4pir^2, 4πr^2" + }, + { + "id": 203, + "question": "Which theorem states that hypotenuse2 = base2 + height2?", + "answer": "Pythagorean's, Pythagorean's theorem" + }, + { + "id": 204, + "question": "Which trigonometric function is defined as hypotenuse/opposite?", + "answer": "cosecant, cosec, csc" + }, + { + "id": 205, + "question": "Does the harmonic series converge or diverge?", + "answer": "diverge" + }, + { + "id": 206, + "question": "How many quadrants are there in a cartesian plane?", + "answer": "4, four" + }, + { + "id": 207, + "question": "What is the (0,0) coordinate in a cartesian plane termed as?", + "answer": "origin" + }, + { + "id": 208, + "question": "What's the following formula that finds the area of a triangle called?", + "img_url": "https://wikimedia.org/api/rest_v1/media/math/render/png/d22b8566e8187542966e8d166e72e93746a1a6fc", + "answer": "Heron's formula" + }, + { + "id": 209, + "dynamic_id": 201, + "question": "Solve the following system of linear equations (format your answer like this & ):\n{}x + {}y = {},\n{}x + {}y = {}", + "answer": "{} & {}" + }, + { + "id": 210, + "dynamic_id": 202, + "question": "What's {} + {} mod {} congruent to?", + "answer": "{}" + }, + { + "id": 211, + "question": "What is the bottom number on a fraction called?", + "answer": "denominator" + }, + { + "id": 212, + "dynamic_id": 203, + "question": "How many vertices are on a {}gonal prism?", + "answer": "{}" + }, + { + "id": 213, + "question": "What is the term used to describe two triangles that have equal corresponding sides and angle measures?", + "answer": "congruent" + }, + { + "id": 214, + "question": "⅓πr2h is the volume of which 3 dimensional figure?", + "answer": "cone" + }, + { + "id": 215, + "dynamic_id": 204, + "question": "Find the square root of -{}.", + "answer": "{}i" + }, + { + "id": 216, + "question": "In set builder notation, {p/q | q ≠ 0, p & q ∈ Z} represents what?", + "answer": "Rational Numbers" + }, + { + "id": 217, + "question": "What is the natural log of -1 (use i for imaginary number)?", + "answer": "pi*i, pii, πi" + }, + { + "id": 218, + "question": "When is the *inaugural* World Maths Day (format your answer in MM/DD)?", + "answer": "03/13" + }, + { + "id": 219, + "question": "As the Fibonacci sequence extends to infinity, what's the ratio of each number `n` and its preceding number `n-1` approaching?", + "answer": "Golden Ratio" + }, + { + "id": 220, + "question": "0, 1, 1, 2, 3, 5, 8, 13, 21, 34 are numbers of which sequence?", + "answer": "Fibonacci" + }, + { + "id": 221, + "question": "Prime numbers only have __ factors.", + "answer": "2, two" + }, + { + "id": 222, + "question": "In probability, the ________ ______ of an experiment or random trial is the set of all possible outcomes of it.", + "answer": "sample space" + }, + { + "id": 223, + "question": "In statistics, what does this formula represent?", + "img_url": "https://www.statisticshowto.com/wp-content/uploads/2013/11/sample-standard-deviation.jpg", + "answer": "sample standard deviation, standard deviation of a sample" + }, + { + "id": 224, + "question": "\"Hexakosioihexekontahexaphobia\" is the fear of which number?", + "answer": "666" + }, + { + "id": 225, + "question": "Prove or disprove the Riemann Hypothesis", + "answer": "" + }, + { + "id": 226, + "dynamic_id": 205, + "question": "BASE TWO QUESTION: Calculate {} {} {}", + "answer": "{}" + }, + { + "id": 227, + "question": "What is the only number in the entire number system which can be spelled with the same number of letters as itself?", + "answer": "4, four" + + }, + { + "id": 228, + "question": "1/100th of a second is also termed as what?", + "answer": "jiffy" + }, + { + "id": 229, + "question": "What is this triangle called?", + "img_url": "https://cdn.askpython.com/wp-content/uploads/2020/07/Pascals-triangle.png", + "answer": "Pascal's triangle, Pascal" + }, + { + "id": 230, + "question": "6a^2 is the surface area of which 3 dimensional figure?", + "answer": "cube" + } + ], + "science": [ + { + "id": 301, + "question": "The three main components of a normal atom are: protons, neutrons, and…", + "answer": "electrons" + }, + { + "id": 302, + "question": "As of 2021, how many elements are there in the Periodic Table?", + "answer": "118" + }, + { + "id": 303, + "question": "What is the universal force discovered by Newton that causes objects with mass to attract each other called?", + "answer": "gravity" + }, + { + "id": 304, + "question": "What do you call an organism composed of only one cell?", + "answer": "unicellular, single-celled" + }, + { + "id": 305, + "question": "The Heisenberg’s Uncertainty Principle states that the position and ________ of a quantum object can’t be both exactly measured at the same time.", + "answer": "velocity, momentum" + }, + { + "id": 306, + "question": "A ____________ reaction is the one wherein an atom or a set of atoms is/are replaced by another atom or a set of atoms", + "answer": "displacement, exchange" + }, + { + "id": 307, + "question": "What is the process by which green plants and certain other organisms transform light energy into chemical energy?", + "answer": "photosynthesis" + }, + { + "id": 308, + "question": "DYNAMIC QUESTION, TO BE DETERMINED", + "answer": "DYNAMIC QUESTION, TO BE DETERMINED" + }, + { + "id": 309, + "question": "DYNAMIC QUESTION, TO BE DETERMINED", + "answer": "DYNAMIC QUESTION, TO BE DETERMINED" + }, + { + "id": 310, + "question": "DYNAMIC QUESTION, TO BE DETERMINED", + "answer": "DYNAMIC QUESTION, TO BE DETERMINED" + }, + { + "id": 311, + "question": "How does one call the direct phase transition from gas to solid?", + "answer": "deposition" + }, + { + "id": 312, + "question": "What is the intermolecular force caused by temporary and induced dipoles?", + "answer": "LDF, London dispersion, London dispersion force" + }, + { + "id": 313, + "question": "What is the force that causes objects to float in fluids called?", + "answer": "buoyancy" + }, + { + "id": 314, + "question": "About how many neurons are in the human brain? (A. 1 billion, B. 10 billion, C. 100 billion, D. 300 billion)", + "answer": "C, 100 billion, 100 bil" + }, + { + "id": 315, + "question": "What is the name of our galaxy group in which the Milky Way resides?", + "answer": "Local Group" + }, + { + "id": 316, + "question": "Which cell organelle is nicknamed \"the powerhouse of the cell\"?", + "answer": "mitochondria" + }, + { + "id": 317, + "question": "Which vascular tissue transports water and minerals from the roots to the rest of a plant?", + "answer": "xylem" + }, + { + "id": 318, + "question": "Who discovered the theories of relativity?", + "answer": "Albert Einstein, Einstein" + }, + { + "id": 319, + "question": "In particle physics, the hypothetical isolated elementary particle with only one magnetic pole is termed as...", + "answer": "magnetic monopole" + }, + { + "id": 320, + "question": "How does one describe a chemical reaction wherein heat is released?", + "answer": "exothermic" + }, + { + "id": 321, + "question": "What range of frequency are the average human ears capable of hearing (A. 10Hz-10kHz, B. 20Hz-20kHz, C. 20Hz-2000Hz, D. 10kHz-20kHz)?", + "answer": "B, 20Hz-20kHz" + }, + { + "id": 322, + "question": "What is the process used to separate substances with different polarity in a mixture, using a stationary and mobile phase?", + "answer": "chromatography" + }, + { + "id": 323, + "question": "Which law states that the current through a conductor between two points is directly proportional to the voltage across the two points?", + "answer": "Ohm's law" + }, + { + "id": 324, + "question": "The type of rock that is formed by the accumulation or deposition of mineral or organic particles at the Earth's surface, followed by cementation, is called...", + "answer": "sedimentary, sedimentary rock" + }, + { + "id": 325, + "question": "Is the Richter scale (common earthquake scale) linear or logarithmic?", + "answer": "logarithmic" + }, + { + "id": 326, + "question": "What type of image is formed by a convex mirror?", + "answer": "virtual image, virtual" + }, + { + "id": 327, + "question": "How does one call the branch of physics that deals with the study of mechanical waves in gases, liquids, and solids including topics such as vibration, sound, ultrasound and infrasound", + "answer": "acoustics" + }, + { + "id": 328, + "question": "Which law states that the global entropy in a closed system can only increase?", + "answer": "second law of thermodynamics" + }, + { + "id": 329, + "question": "Which particle is emitted during the beta decay of a radioactive element?", + "answer": "an electron, electron" + }, + { + "id": 330, + "question": "When DNA is unzipped, two strands are formed. What are they called (separate both answers by the word \"and\")?", + "answer": "leading and lagging, leading strand and lagging strand" + } ] } -- cgit v1.2.3 From 113a20a62fdd55776052e3e1968a52aae2c07771 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Fri, 7 May 2021 11:03:16 -0300 Subject: Implement the math and science questions, added a dynamic_id checker --- bot/exts/evergreen/trivia_quiz.py | 241 ++++++++++++++++++++++++++++---------- 1 file changed, 182 insertions(+), 59 deletions(-) diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index fe692c2a..1139e3e1 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -25,34 +25,58 @@ class TriviaQuiz(commands.Cog): def __init__(self, bot: commands.Bot) -> None: self.bot = bot - self.questions = self.load_questions() + self.game_status = {} # A variable to store the game status: either running or not running. self.game_owners = {} # A variable to store the person's ID who started the quiz game in a channel. - self.question_limit = 4 + + self.questions = self.load_questions() + self.question_limit = 7 + self.player_scores = {} # A variable to store all player's scores for a bot session. self.game_player_scores = {} # A variable to store temporary game player's scores. + self.categories = { - "general": "Test your general knowledge" - # "retro": "Questions related to retro gaming." + "general": "Test your general knowledge.", + "retro": "Questions related to retro gaming.", + "math": "General questions about mathematics ranging from grade 8 to grade 12.", + "science": "Put your understanding of science to the test!", } + @commands.command() + async def test(self, ctx: commands.Context) -> None: + embed = discord.Embed( + title="yeet", + description="yeet", + ) + + print("yeet") + embed.set_image(url="") + + await ctx.send(embed=embed) + @staticmethod def load_questions() -> dict: """Load the questions from the JSON file.""" p = Path("bot", "resources", "evergreen", "trivia_quiz.json") + with p.open(encoding="utf8") as json_data: questions = json.load(json_data) return questions @commands.group(name="quiz", aliases=["trivia"], invoke_without_command=True) - async def quiz_game(self, ctx: commands.Context, category: str = None) -> None: + async def quiz_game(self, ctx: commands.Context, category: Optional[str], questions: Optional[int]) -> None: """ Start a quiz! Questions for the quiz can be selected from the following categories: - - general : Test your general knowledge. (default) + - general: Test your general knowledge. (default) + - retro: Questions related to retro gaming. + - math: General questions about mathematics ranging from grade 8 to grade 12. + - science: Put your understanding of science to the test! + (More to come!) """ + if ctx.channel.id not in self.game_status: self.game_status[ctx.channel.id] = False @@ -61,11 +85,13 @@ class TriviaQuiz(commands.Cog): # Stop game if running. if self.game_status[ctx.channel.id] is True: - return await ctx.send( - f"Game is already running..." + await ctx.send( + "Game is already running..." f"do `{self.bot.command_prefix}quiz stop`" ) + return + # Send embed showing available categories if inputted category is invalid. if category is None: category = random.choice(list(self.categories)) @@ -76,6 +102,30 @@ class TriviaQuiz(commands.Cog): await ctx.send(embed=embed) return + topic = self.questions[category] + topic_length = len(topic) + + if questions: + if questions > topic_length: + await ctx.send( + embed=self.make_error_embed( + f"This category only has {topic_length} questions. " + "Please input a lower value!" + ) + ) + return + + elif questions < 1: + await ctx.send( + embed=self.make_error_embed( + "Please do at least one question." + ) + ) + return + + else: + self.question_limit = questions - 1 + # Start game if not running. if self.game_status[ctx.channel.id] is False: self.game_owners[ctx.channel.id] = ctx.author @@ -85,16 +135,17 @@ class TriviaQuiz(commands.Cog): await ctx.send(embed=start_embed) # send an embed with the rules await asyncio.sleep(1) - topic = self.questions[category] - done_question = [] hint_no = 0 - answer = None + answers = None + while self.game_status[ctx.channel.id]: # Exit quiz if number of questions for a round are already sent. if len(done_question) > self.question_limit and hint_no == 0: await ctx.send("The round has ended.") - await self.declare_winner(ctx.channel, self.game_player_scores[ctx.channel.id]) + await self.declare_winner( + ctx.channel, self.game_player_scores[ctx.channel.id] + ) self.game_status[ctx.channel.id] = False del self.game_owners[ctx.channel.id] @@ -111,23 +162,39 @@ class TriviaQuiz(commands.Cog): done_question.append(question_dict["id"]) break - q = question_dict["question"] - answer = question_dict["answer"] + if "dynamic_id" not in question_dict: + q = question_dict["question"] + answers = question_dict["answer"].split(", ") + else: + q, answers = DYNAMIC_QUESTIONS_FORMAT_FUNCS[ + question_dict["dynamic_id"] + ]( + question_dict["question"], + question_dict["answer"], + ) + + answers = [answers] + + embed = discord.Embed( + colour=discord.Colour.gold(), + title=f"Question #{len(done_question)}", + description=q, + ) + + if "img_url" in question_dict: + embed.set_image(url=question_dict["img_url"]) - embed = discord.Embed(colour=discord.Colour.gold()) - embed.title = f"Question #{len(done_question)}" - embed.description = q await ctx.send(embed=embed) # Send question embed. # A function to check whether user input is the correct answer(close to the right answer) def check(m: discord.Message) -> bool: - return ( - m.channel == ctx.channel - and fuzz.ratio(answer.lower(), m.content.lower()) > 85 + return m.channel == ctx.channel and any( + fuzz.ratio(answer.lower(), m.content.lower()) > VARIATION_TOLERANCE + for answer in answers ) try: - msg = await self.bot.wait_for('message', check=check, timeout=10) + msg = await self.bot.wait_for("message", check=check, timeout=10) except asyncio.TimeoutError: # In case of TimeoutError and the game has been stopped, then do nothing. if self.game_status[ctx.channel.id] is False: @@ -136,9 +203,14 @@ class TriviaQuiz(commands.Cog): # if number of hints sent or time alerts sent is less than 2, then send one. if hint_no < 2: hint_no += 1 + if "hints" in question_dict: hints = question_dict["hints"] - await ctx.send(f"**Hint #{hint_no+1}\n**{hints[hint_no]}") + + await ctx.send( + f"**Hint #{hint_no}\n**" + f"{hints[hint_no - 1]}" + ) else: await ctx.send(f"{30 - hint_no * 10}s left!") @@ -151,19 +223,22 @@ class TriviaQuiz(commands.Cog): response = random.choice(WRONG_ANS_RESPONSE) await ctx.send(response) - await self.send_answer(ctx.channel, question_dict) + await self.send_answer(ctx.channel, answers, question_dict) await asyncio.sleep(1) hint_no = 0 # init hint_no = 0 so that 2 hints/time alerts can be sent for the new question. - await self.send_score(ctx.channel, self.game_player_scores[ctx.channel.id]) + await self.send_score( + ctx.channel, self.game_player_scores[ctx.channel.id] + ) + await asyncio.sleep(2) else: if self.game_status[ctx.channel.id] is False: break # Reduce points by 25 for every hint/time alert that has been sent. - points = 100 - 25*hint_no + points = 100 - 25 * hint_no if msg.author in self.game_player_scores[ctx.channel.id]: self.game_player_scores[ctx.channel.id][msg.author] += points else: @@ -177,24 +252,49 @@ class TriviaQuiz(commands.Cog): hint_no = 0 - await ctx.send(f"{msg.author.mention} got the correct answer :tada: {points} points!") - await self.send_answer(ctx.channel, question_dict) - await self.send_score(ctx.channel, self.game_player_scores[ctx.channel.id]) + await ctx.send( + f"{msg.author.mention} got the correct answer :tada: {points} points!" + ) + + await self.send_answer(ctx.channel, answers, question_dict) + await self.send_score( + ctx.channel, self.game_player_scores[ctx.channel.id] + ) + await asyncio.sleep(2) - @staticmethod - def make_start_embed(category: str) -> discord.Embed: + def make_start_embed(self, category: str) -> discord.Embed: """Generate a starting/introduction embed for the quiz.""" - start_embed = discord.Embed(colour=discord.Colour.red()) - start_embed.title = "Quiz game Starting!!" - start_embed.description = "Each game consists of 5 questions.\n" - start_embed.description += "**Rules :**\nNo cheating and have fun!" - start_embed.description += f"\n **Category** : {category}" + start_embed = discord.Embed( + colour=discord.Colour.red(), + title="Quiz game starting!", + description=( + f"Each game consists of {self.question_limit + 1} questions.\n" + "**Rules: **No cheating and have fun!\n" + f"**Category**: {category}" + ), + ) + start_embed.set_footer( - text="Points for each question reduces by 25 after 10s or after a hint. Total time is 30s per question" + text=( + "Points for each question reduces by 25 after 10s or after a hint." + "Total time is 30s per question" + ) ) + return start_embed + @staticmethod + def make_error_embed(desc: str) -> discord.Embed: + """Generate an error embed with the given description.""" + error_embed = discord.Embed( + colour=discord.Colour.red(), + title=random.choice(NEGATIVE_REPLIES), + description=desc, + ) + + return error_embed + @quiz_game.command(name="stop") async def stop_quiz(self, ctx: commands.Context) -> None: """ @@ -204,18 +304,23 @@ class TriviaQuiz(commands.Cog): """ if self.game_status[ctx.channel.id] is True: # Check if the author is the game starter or a moderator. - if ( - ctx.author == self.game_owners[ctx.channel.id] - or any(Roles.moderator == role.id for role in ctx.author.roles) + if ctx.author == self.game_owners[ctx.channel.id] or any( + Roles.moderator == role.id for role in ctx.author.roles ): + await ctx.send("Quiz stopped.") - await self.declare_winner(ctx.channel, self.game_player_scores[ctx.channel.id]) + await self.declare_winner( + ctx.channel, self.game_player_scores[ctx.channel.id] + ) self.game_status[ctx.channel.id] = False del self.game_owners[ctx.channel.id] self.game_player_scores[ctx.channel.id] = {} + else: - await ctx.send(f"{ctx.author.mention}, you are not authorised to stop this game :ghost:!") + await ctx.send( + f"{ctx.author.mention}, you are not authorised to stop this game :ghost:!" + ) else: await ctx.send("No quiz running.") @@ -231,13 +336,15 @@ class TriviaQuiz(commands.Cog): await channel.send("No one has made it onto the leaderboard yet.") return - embed = discord.Embed(colour=discord.Colour.blue()) - embed.title = "Score Board" - embed.description = "" + embed = discord.Embed( + colour=discord.Colour.blue(), + title="Score Board", + description="", + ) sorted_dict = sorted(player_data.items(), key=lambda a: a[1], reverse=True) for item in sorted_dict: - embed.description += f"{item[0]} : {item[1]}\n" + embed.description += f"{item[0]}: {item[1]}\n" await channel.send(embed=embed) @@ -250,7 +357,6 @@ class TriviaQuiz(commands.Cog): # Check if more than 1 player has highest points. if no_of_winners > 1: - word = "You guys" winners = [] points_copy = list(player_data.values()).copy() @@ -261,36 +367,53 @@ class TriviaQuiz(commands.Cog): winners_mention = " ".join(winner.mention for winner in winners) else: - word = "You" author_index = list(player_data.values()).index(highest_points) winner = list(player_data.keys())[author_index] winners_mention = winner.mention await channel.send( f"Congratulations {winners_mention} :tada: " - f"{word} have won this quiz game with a grand total of {highest_points} points!" + f"You have won this quiz game with a grand total of {highest_points} points!" ) def category_embed(self) -> discord.Embed: """Build an embed showing all available trivia categories.""" - embed = discord.Embed(colour=discord.Colour.blue()) - embed.title = "The available question categories are:" - embed.set_footer(text="If a category is not chosen, a random one will be selected.") - embed.description = "" + embed = discord.Embed( + colour=discord.Colour.blue(), + title="The available question categories are:", + description="", + ) + + embed.set_footer( + text="If a category is not chosen, a random one will be selected." + ) for cat, description in self.categories.items(): - embed.description += f"**- {cat.capitalize()}**\n{description.capitalize()}\n" + embed.description += ( + f"**- {cat.capitalize()}**\n" + f"{description.capitalize()}\n" + ) return embed @staticmethod - async def send_answer(channel: discord.TextChannel, question_dict: dict) -> None: + async def send_answer( + channel: discord.TextChannel, + answers: List[str], + question_dict: dict, + ) -> None: + """Send the correct answer of a question to the game channel.""" - answer = question_dict["answer"] - info = question_dict["info"] - embed = discord.Embed(color=discord.Colour.red()) - embed.title = f"The correct answer is **{answer}**\n" - embed.description = "" + if "info" in question_dict: + info = question_dict["info"] + else: + info = "" + + embed = discord.Embed( + color=discord.Colour.red(), + title=f"The correct answer is/are **{', '.join(answers)}**\n", + description="", + ) if info != "": embed.description += f"**Information**\n{info}\n\n" -- cgit v1.2.3 From 9e6004f26d7d95537cef6e60c8ee7bf78e705a82 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Fri, 7 May 2021 11:19:31 -0300 Subject: fix NameError, add some forgotten imports --- bot/exts/evergreen/trivia_quiz.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index 1139e3e1..2158ac9c 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -9,11 +9,12 @@ from discord.ext import commands from fuzzywuzzy import fuzz from bot.constants import Roles +from bot.constants import NEGATIVE_REPLIES +from typing import Optional, List, Tuple logger = logging.getLogger(__name__) - WRONG_ANS_RESPONSE = [ "No one answered correctly!", "Better luck next time" -- cgit v1.2.3 From 0913bf2ba9a66bb7d6dc7c729d689b98dfdcb520 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Fri, 7 May 2021 14:06:34 -0300 Subject: Add dynamically generated science questions --- bot/resources/evergreen/trivia_quiz.json | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/bot/resources/evergreen/trivia_quiz.json b/bot/resources/evergreen/trivia_quiz.json index b20b953f..ce33e8c9 100644 --- a/bot/resources/evergreen/trivia_quiz.json +++ b/bot/resources/evergreen/trivia_quiz.json @@ -435,7 +435,7 @@ { "id": 228, "question": "1/100th of a second is also termed as what?", - "answer": "jiffy" + "answer": "a jiffy, jiffy" }, { "id": 229, @@ -487,18 +487,22 @@ }, { "id": 308, - "question": "DYNAMIC QUESTION, TO BE DETERMINED", - "answer": "DYNAMIC QUESTION, TO BE DETERMINED" + "dynamic_id": 301, + "question": "What is the {} planet of our Solar System?", + "answer": "{}" }, { "id": 309, - "question": "DYNAMIC QUESTION, TO BE DETERMINED", - "answer": "DYNAMIC QUESTION, TO BE DETERMINED" + "dynamic_id": 302, + "question": "In the biological taxonomic hierarchy, what is placed directly above {}?", + "answer": "{}" }, { "id": 310, - "question": "DYNAMIC QUESTION, TO BE DETERMINED", - "answer": "DYNAMIC QUESTION, TO BE DETERMINED" + "dynamic_id": 303, + "question": "How does one describe the unit {} in SI base units?\n**IMPORTANT:** use * for multiplication, ^ for exponentiation, and place your base units in this order: m - kg - s - A", + "img_url": "https://i.imgur.com/NRzU6tf.png", + "answer": "{}" }, { "id": 311, @@ -533,7 +537,7 @@ { "id": 317, "question": "Which vascular tissue transports water and minerals from the roots to the rest of a plant?", - "answer": "xylem" + "answer": "the xylem, xylem" }, { "id": 318, @@ -593,7 +597,7 @@ { "id": 329, "question": "Which particle is emitted during the beta decay of a radioactive element?", - "answer": "an electron, electron" + "answer": "an electron, the electron, electron" }, { "id": 330, -- cgit v1.2.3 From c940d96a9d11ddfaaf4b599f429d559b2da60d1b Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Fri, 7 May 2021 14:08:39 -0300 Subject: Add dynamic question formatters and its constants --- bot/exts/evergreen/trivia_quiz.py | 164 +++++++++++++++++++++++++++++++++++++- 1 file changed, 162 insertions(+), 2 deletions(-) diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index 2158ac9c..d57ddc09 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -15,11 +15,171 @@ from typing import Optional, List, Tuple logger = logging.getLogger(__name__) +VARIATION_TOLERANCE = 83 + WRONG_ANS_RESPONSE = [ "No one answered correctly!", - "Better luck next time" + "Better luck next time...", +] + +N_PREFIX_STARTS_AT = 5 +N_PREFIXES = [ + "penta", "hexa", "hepta", "octa", "nona", + "deca", "hendeca", "dodeca", "trideca", "tetradeca", +] + +PLANETS = [ + ("1st", "Mercury"), + ("2nd", "Venus"), + ("3rd", "Earth"), + ("4th", "Mars"), + ("5th", "Jupiter"), + ("6th", "Saturn"), + ("7th", "Uranus"), + ("8th", "Neptune"), +] + +TAXONOMIC_HIERARCHY = [ + "species", "genus", "family", "order", + "class", "phylum", "kingdom", "domain", ] +UNITS_TO_BASE_UNITS = { + "hertz": ("(unit of frequency)", "s^-1"), + "newton": ("(unit of force)", "m*kg*s^-2"), + "pascal": ("(unit of pressure & stress)", "m^-1*kg*s^-2"), + "joule": ("(unit of energy & quantity of heat)", "m^2*kg*s^-2"), + "watt": ("(unit of power)", "m^2*kg*s^-3"), + "coulomb": ("(unit of electric charge & quantity of electricity)", "s*A"), + "volt": ("(unit of voltage & electromotive force)", "m^2*kg*s^-3*A^-1"), + "farad": ("(unit of capacitance)", "m^-2*kg^-1*s^4*A^2"), + "ohm": ("(unit of electric resistance)", "m^2*kg*s^-3*A^-2"), + "weber": ("(unit of magnetic flux)", "m^2*kg*s^-2*A^-1"), + "tesla": ("(unit of magnetic flux density)", "kg*s^-2*A^-1"), +} + + +def linear_system(q_format: str, a_format: str) -> Tuple[str, str]: + x, y = random.randint(2, 5), random.randint(2, 5) + answer = a_format.format(x, y) + + nums = [i for i in range(1, 6)] + coeffs = [nums.pop(random.randint(0, len(nums) - 1)) for _ in range(4)] + + question = q_format.format( + coeffs[0], + coeffs[1], + ( + coeffs[0] * x + coeffs[1] * y + ), + coeffs[2], + coeffs[3], + ( + coeffs[2] * x + coeffs[3] * y + ), + ) + + return question, answer + + +def mod_arith(q_format: str, a_format: str) -> Tuple[str, str]: + quotient, m, b = random.randint(30, 40), random.randint(10, 20), random.randint(200, 350) + ans = random.randint(0, 9) # max 9 because min mod 10 + a = quotient * m + ans - b + + question = q_format.format(a, b, m) + answer = a_format.format(ans) + + return question, answer + + +def ngonal_prism(q_format: str, a_format: str) -> Tuple[str, str]: + n = random.randint(0, len(N_PREFIXES) - 1) + + question = q_format.format(N_PREFIXES[n]) + answer = a_format.format((n + N_PREFIX_STARTS_AT) * 2) + + return question, answer + + +def imag_sqrt(q_format: str, a_format: str) -> Tuple[str, str]: + ans_coeff = random.randint(3, 10) + + question = q_format.format(ans_coeff ** 2) + answer = a_format.format(ans_coeff) + + return question, answer + + +def binary_calc(q_format: str, a_format: str) -> Tuple[str, str]: + a = random.randint(15, 20) + b = random.randint(10, a) + oper = random.choice( + ( + ("+", lambda x, y: x + y), + ("-", lambda x, y: x - y), + ("*", lambda x, y: x * y), + ) + ) + + if oper[0] == "*": + a -= 5 + b -= 5 + + question = q_format.format( + bin(a)[2:], + oper[0], + bin(b)[2:], + ) + answer = a_format.format( + bin(oper[1](a, b))[2:] + ) + + return question, answer + + +def solar_system(q_format: str, a_format: str) -> Tuple[str, str]: + planet = random.choice(PLANETS) + + question = q_format.format(planet[0]) + answer = a_format.format(planet[1]) + + return question, answer + + +def taxonomic_rank(q_format: str, a_format: str) -> Tuple[str, str]: + level = random.randint(0, len(TAXONOMIC_HIERARCHY) - 2) + + question = q_format.format(TAXONOMIC_HIERARCHY[level]) + answer = a_format.format(TAXONOMIC_HIERARCHY[level + 1]) + + return question, answer + + +def base_units_convert(q_format: str, a_format: str) -> Tuple[str, str]: + unit = random.choice(list(UNITS_TO_BASE_UNITS.keys())) + + question = q_format.format( + unit + " " + UNITS_TO_BASE_UNITS[unit][0] + ) + answer = a_format.format( + UNITS_TO_BASE_UNITS[unit][1] + ) + + return question, answer + + +DYNAMIC_QUESTIONS_FORMAT_FUNCS = { + 201: linear_system, + 202: mod_arith, + 203: ngonal_prism, + 204: imag_sqrt, + 205: binary_calc, + 301: solar_system, + 302: taxonomic_rank, + 303: base_units_convert, +} + class TriviaQuiz(commands.Cog): """A cog for all quiz commands.""" @@ -412,7 +572,7 @@ class TriviaQuiz(commands.Cog): embed = discord.Embed( color=discord.Colour.red(), - title=f"The correct answer is/are **{', '.join(answers)}**\n", + title=f"The correct answer is/are **`{', '.join(answers)}`**\n", description="", ) -- cgit v1.2.3 From b80588d0c74f78f3d78b0580ba52d0ec8d23aeec Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Fri, 7 May 2021 14:27:10 -0300 Subject: Fix lint failures: adding docstrings, removing whitespace --- bot/exts/evergreen/trivia_quiz.py | 28 +++++++++++----------------- 1 file changed, 11 insertions(+), 17 deletions(-) diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index d57ddc09..7bbb8a15 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -8,10 +8,10 @@ import discord from discord.ext import commands from fuzzywuzzy import fuzz -from bot.constants import Roles -from bot.constants import NEGATIVE_REPLIES +from typing import List, Optional, Tuple -from typing import Optional, List, Tuple +from bot.constants import NEGATIVE_REPLIES +from bot.constants import Roles logger = logging.getLogger(__name__) @@ -60,6 +60,7 @@ UNITS_TO_BASE_UNITS = { def linear_system(q_format: str, a_format: str) -> Tuple[str, str]: + """Generates a system of linear equations with two unknowns.""" x, y = random.randint(2, 5), random.randint(2, 5) answer = a_format.format(x, y) @@ -83,6 +84,7 @@ def linear_system(q_format: str, a_format: str) -> Tuple[str, str]: def mod_arith(q_format: str, a_format: str) -> Tuple[str, str]: + """Generate a basic modular arithmetic question.""" quotient, m, b = random.randint(30, 40), random.randint(10, 20), random.randint(200, 350) ans = random.randint(0, 9) # max 9 because min mod 10 a = quotient * m + ans - b @@ -94,6 +96,7 @@ def mod_arith(q_format: str, a_format: str) -> Tuple[str, str]: def ngonal_prism(q_format: str, a_format: str) -> Tuple[str, str]: + """Generate a question regarding vertices on n-gonal prisms.""" n = random.randint(0, len(N_PREFIXES) - 1) question = q_format.format(N_PREFIXES[n]) @@ -103,6 +106,7 @@ def ngonal_prism(q_format: str, a_format: str) -> Tuple[str, str]: def imag_sqrt(q_format: str, a_format: str) -> Tuple[str, str]: + """Generates a negative square root question.""" ans_coeff = random.randint(3, 10) question = q_format.format(ans_coeff ** 2) @@ -112,6 +116,7 @@ def imag_sqrt(q_format: str, a_format: str) -> Tuple[str, str]: def binary_calc(q_format: str, a_format: str) -> Tuple[str, str]: + """Generates a binary calculation question.""" a = random.randint(15, 20) b = random.randint(10, a) oper = random.choice( @@ -139,6 +144,7 @@ def binary_calc(q_format: str, a_format: str) -> Tuple[str, str]: def solar_system(q_format: str, a_format: str) -> Tuple[str, str]: + """Generates a question on the planets of the Solar System.""" planet = random.choice(PLANETS) question = q_format.format(planet[0]) @@ -148,6 +154,7 @@ def solar_system(q_format: str, a_format: str) -> Tuple[str, str]: def taxonomic_rank(q_format: str, a_format: str) -> Tuple[str, str]: + """Generates a question on taxonomic classification.""" level = random.randint(0, len(TAXONOMIC_HIERARCHY) - 2) question = q_format.format(TAXONOMIC_HIERARCHY[level]) @@ -157,6 +164,7 @@ def taxonomic_rank(q_format: str, a_format: str) -> Tuple[str, str]: def base_units_convert(q_format: str, a_format: str) -> Tuple[str, str]: + """Generates a SI base units conversion question.""" unit = random.choice(list(UNITS_TO_BASE_UNITS.keys())) question = q_format.format( @@ -203,18 +211,6 @@ class TriviaQuiz(commands.Cog): "science": "Put your understanding of science to the test!", } - @commands.command() - async def test(self, ctx: commands.Context) -> None: - embed = discord.Embed( - title="yeet", - description="yeet", - ) - - print("yeet") - embed.set_image(url="") - - await ctx.send(embed=embed) - @staticmethod def load_questions() -> dict: """Load the questions from the JSON file.""" @@ -237,7 +233,6 @@ class TriviaQuiz(commands.Cog): (More to come!) """ - if ctx.channel.id not in self.game_status: self.game_status[ctx.channel.id] = False @@ -563,7 +558,6 @@ class TriviaQuiz(commands.Cog): answers: List[str], question_dict: dict, ) -> None: - """Send the correct answer of a question to the game channel.""" if "info" in question_dict: info = question_dict["info"] -- cgit v1.2.3 From c742604f310097339e130688232862f27052cc3b Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Fri, 7 May 2021 14:28:31 -0300 Subject: Fix wrong import order lint failure --- bot/exts/evergreen/trivia_quiz.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index 7bbb8a15..d024f856 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -3,13 +3,12 @@ import json import logging import random from pathlib import Path +from typing import List, Optional, Tuple import discord from discord.ext import commands from fuzzywuzzy import fuzz -from typing import List, Optional, Tuple - from bot.constants import NEGATIVE_REPLIES from bot.constants import Roles -- cgit v1.2.3 From 92dd10e62dbea4cbed9d12c239ca9f666f69f90a Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Fri, 7 May 2021 17:51:25 -0300 Subject: fixed weird 8-space indents on lines 556-558 --- bot/exts/evergreen/trivia_quiz.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index d024f856..5553898d 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -553,9 +553,9 @@ class TriviaQuiz(commands.Cog): @staticmethod async def send_answer( - channel: discord.TextChannel, - answers: List[str], - question_dict: dict, + channel: discord.TextChannel, + answers: List[str], + question_dict: dict, ) -> None: """Send the correct answer of a question to the game channel.""" if "info" in question_dict: -- cgit v1.2.3 From 1854cd45dc4b79bed492a95bd00bcadf8ff116af Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Sun, 9 May 2021 14:00:08 -0400 Subject: use random.sample for more concise expression on line 66 Co-authored-by: Anand Krishna <40204976+anand2312@users.noreply.github.com> --- bot/exts/evergreen/trivia_quiz.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index 5553898d..620a4377 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -63,8 +63,7 @@ def linear_system(q_format: str, a_format: str) -> Tuple[str, str]: x, y = random.randint(2, 5), random.randint(2, 5) answer = a_format.format(x, y) - nums = [i for i in range(1, 6)] - coeffs = [nums.pop(random.randint(0, len(nums) - 1)) for _ in range(4)] + coeffs = random.sample(range(1, 6), 4) question = q_format.format( coeffs[0], -- cgit v1.2.3 From 961e3f788ce4d99782418ec9bc4d33998af42124 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Sun, 9 May 2021 16:31:32 -0400 Subject: use dict.get for retrieving a default value instead of a condition Co-authored-by: ToxicKidz <78174417+ToxicKidz@users.noreply.github.com> --- bot/exts/evergreen/trivia_quiz.py | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index 620a4377..6f39d9f2 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -557,10 +557,7 @@ class TriviaQuiz(commands.Cog): question_dict: dict, ) -> None: """Send the correct answer of a question to the game channel.""" - if "info" in question_dict: - info = question_dict["info"] - else: - info = "" + info = question_dict.get("info", "") embed = discord.Embed( color=discord.Colour.red(), -- cgit v1.2.3 From c57a8557f0f52ab35c9ef79c6894bad04f73c8d2 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Sun, 9 May 2021 17:36:27 -0300 Subject: use `operator` module instead of lambda functions --- bot/exts/evergreen/trivia_quiz.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index 6f39d9f2..10237be9 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -2,6 +2,7 @@ import asyncio import json import logging import random +import operator from pathlib import Path from typing import List, Optional, Tuple @@ -119,9 +120,9 @@ def binary_calc(q_format: str, a_format: str) -> Tuple[str, str]: b = random.randint(10, a) oper = random.choice( ( - ("+", lambda x, y: x + y), - ("-", lambda x, y: x - y), - ("*", lambda x, y: x * y), + ("+", operator.add), + ("-", operator.sub), + ("*", operator.mul), ) ) -- cgit v1.2.3 From bfc7c4335a4e7156f877607b62491b7aaf2faa58 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Sun, 9 May 2021 17:37:42 -0300 Subject: lint failure fix, imported in alphabetical order --- bot/exts/evergreen/trivia_quiz.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index 10237be9..7a498ebd 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -1,8 +1,8 @@ import asyncio import json import logging -import random import operator +import random from pathlib import Path from typing import List, Optional, Tuple -- cgit v1.2.3 From 66480996e0a227506c01260e8899ea4256db6eb9 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Sun, 9 May 2021 17:41:34 -0300 Subject: use binary formatting instead of `bin()` in function --- bot/resources/evergreen/trivia_quiz.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/bot/resources/evergreen/trivia_quiz.json b/bot/resources/evergreen/trivia_quiz.json index ce33e8c9..79e79d00 100644 --- a/bot/resources/evergreen/trivia_quiz.json +++ b/bot/resources/evergreen/trivia_quiz.json @@ -423,8 +423,8 @@ { "id": 226, "dynamic_id": 205, - "question": "BASE TWO QUESTION: Calculate {} {} {}", - "answer": "{}" + "question": "BASE TWO QUESTION: Calculate {:b} {} {:b}", + "answer": "{:b}" }, { "id": 227, -- cgit v1.2.3 From 8b0eb4aa07fbc9c20f7748888d0db00f2264b774 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Sun, 9 May 2021 17:43:33 -0300 Subject: delete `bin()`s --- bot/exts/evergreen/trivia_quiz.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index 7a498ebd..03aadd19 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -131,12 +131,12 @@ def binary_calc(q_format: str, a_format: str) -> Tuple[str, str]: b -= 5 question = q_format.format( - bin(a)[2:], + a, oper[0], - bin(b)[2:], + b, ) answer = a_format.format( - bin(oper[1](a, b))[2:] + oper[1](a, b) ) return question, answer -- cgit v1.2.3 From f8e5ec95028f8a73cf0e9d96356696a047001c41 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Sun, 9 May 2021 16:45:30 -0400 Subject: add space at the end of string on line 435 Co-authored-by: ToxicKidz <78174417+ToxicKidz@users.noreply.github.com> --- bot/exts/evergreen/trivia_quiz.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index 03aadd19..1e1c973c 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -432,7 +432,7 @@ class TriviaQuiz(commands.Cog): start_embed.set_footer( text=( - "Points for each question reduces by 25 after 10s or after a hint." + "Points for each question reduces by 25 after 10s or after a hint. " "Total time is 30s per question" ) ) -- cgit v1.2.3 From 9d5ea922a5a9d045b15610a66ebc07cd5b4424b1 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Sun, 9 May 2021 16:47:30 -0400 Subject: remove redundant `description` kwarg pass Co-authored-by: ToxicKidz <78174417+ToxicKidz@users.noreply.github.com> --- bot/exts/evergreen/trivia_quiz.py | 1 - 1 file changed, 1 deletion(-) diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index 1e1c973c..d3def4f2 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -563,7 +563,6 @@ class TriviaQuiz(commands.Cog): embed = discord.Embed( color=discord.Colour.red(), title=f"The correct answer is/are **`{', '.join(answers)}`**\n", - description="", ) if info != "": -- cgit v1.2.3 From af709306d716d2d1c19c288cec08a3fa74a20a5c Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Sun, 9 May 2021 16:48:47 -0400 Subject: use walrus so dict lookup is only performed once Co-authored-by: ToxicKidz <78174417+ToxicKidz@users.noreply.github.com> --- bot/exts/evergreen/trivia_quiz.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index d3def4f2..88c44971 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -336,8 +336,8 @@ class TriviaQuiz(commands.Cog): description=q, ) - if "img_url" in question_dict: - embed.set_image(url=question_dict["img_url"]) + if img_url := question_dict.get("image_url"): + embed.set_image(url=img_url) await ctx.send(embed=embed) # Send question embed. -- cgit v1.2.3 From 17aee2141770085bc66c04d948249de954359f6a Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Sun, 9 May 2021 17:53:01 -0300 Subject: changed error embed color to `bot.constants.Colours.soft_red` --- bot/exts/evergreen/trivia_quiz.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index 88c44971..4496082e 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -10,6 +10,7 @@ import discord from discord.ext import commands from fuzzywuzzy import fuzz +from bot.constants import Colours from bot.constants import NEGATIVE_REPLIES from bot.constants import Roles @@ -443,7 +444,7 @@ class TriviaQuiz(commands.Cog): def make_error_embed(desc: str) -> discord.Embed: """Generate an error embed with the given description.""" error_embed = discord.Embed( - colour=discord.Colour.red(), + colour=Colours.soft_red, title=random.choice(NEGATIVE_REPLIES), description=desc, ) -- cgit v1.2.3 From 84f2b8783a28e2d90d601cbab33c6c3a439040bf Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Sun, 9 May 2021 18:05:01 -0300 Subject: add a space at end of string on line 245 --- bot/exts/evergreen/trivia_quiz.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index 4496082e..2bd8f7d4 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -242,7 +242,7 @@ class TriviaQuiz(commands.Cog): # Stop game if running. if self.game_status[ctx.channel.id] is True: await ctx.send( - "Game is already running..." + "Game is already running... " f"do `{self.bot.command_prefix}quiz stop`" ) -- cgit v1.2.3 From 21282d531208a613083362a2e5b22aebb8c53573 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Sun, 9 May 2021 18:35:58 -0300 Subject: reverted all undesired black formatting changes --- bot/exts/evergreen/trivia_quiz.py | 47 +++++++++++---------------------------- 1 file changed, 13 insertions(+), 34 deletions(-) diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index 2bd8f7d4..79cf1318 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -224,13 +224,11 @@ class TriviaQuiz(commands.Cog): async def quiz_game(self, ctx: commands.Context, category: Optional[str], questions: Optional[int]) -> None: """ Start a quiz! - Questions for the quiz can be selected from the following categories: - general: Test your general knowledge. (default) - retro: Questions related to retro gaming. - math: General questions about mathematics ranging from grade 8 to grade 12. - science: Put your understanding of science to the test! - (More to come!) """ if ctx.channel.id not in self.game_status: @@ -299,9 +297,7 @@ class TriviaQuiz(commands.Cog): # Exit quiz if number of questions for a round are already sent. if len(done_question) > self.question_limit and hint_no == 0: await ctx.send("The round has ended.") - await self.declare_winner( - ctx.channel, self.game_player_scores[ctx.channel.id] - ) + await self.declare_winner(ctx.channel, self.game_player_scores[ctx.channel.id]) self.game_status[ctx.channel.id] = False del self.game_owners[ctx.channel.id] @@ -319,12 +315,12 @@ class TriviaQuiz(commands.Cog): break if "dynamic_id" not in question_dict: - q = question_dict["question"] + question = question_dict["question"] answers = question_dict["answer"].split(", ") else: - q, answers = DYNAMIC_QUESTIONS_FORMAT_FUNCS[ - question_dict["dynamic_id"] - ]( + format_func = DYNAMIC_QUESTIONS_FORMAT_FUNCS[question_dict["dynamic_id"]] + + question, answers = format_func( question_dict["question"], question_dict["answer"], ) @@ -334,7 +330,7 @@ class TriviaQuiz(commands.Cog): embed = discord.Embed( colour=discord.Colour.gold(), title=f"Question #{len(done_question)}", - description=q, + description=question, ) if img_url := question_dict.get("image_url"): @@ -363,10 +359,7 @@ class TriviaQuiz(commands.Cog): if "hints" in question_dict: hints = question_dict["hints"] - await ctx.send( - f"**Hint #{hint_no}\n**" - f"{hints[hint_no - 1]}" - ) + await ctx.send(f"**Hint #{hint_no}\n**{hints[hint_no - 1]}") else: await ctx.send(f"{30 - hint_no * 10}s left!") @@ -384,10 +377,7 @@ class TriviaQuiz(commands.Cog): hint_no = 0 # init hint_no = 0 so that 2 hints/time alerts can be sent for the new question. - await self.send_score( - ctx.channel, self.game_player_scores[ctx.channel.id] - ) - + await self.send_score(ctx.channel, self.game_player_scores[ctx.channel.id]) await asyncio.sleep(2) else: if self.game_status[ctx.channel.id] is False: @@ -408,14 +398,10 @@ class TriviaQuiz(commands.Cog): hint_no = 0 - await ctx.send( - f"{msg.author.mention} got the correct answer :tada: {points} points!" - ) + await ctx.send(f"{msg.author.mention} got the correct answer :tada: {points} points!") await self.send_answer(ctx.channel, answers, question_dict) - await self.send_score( - ctx.channel, self.game_player_scores[ctx.channel.id] - ) + await self.send_score(ctx.channel, self.game_player_scores[ctx.channel.id]) await asyncio.sleep(2) @@ -455,7 +441,6 @@ class TriviaQuiz(commands.Cog): async def stop_quiz(self, ctx: commands.Context) -> None: """ Stop a quiz game if its running in the channel. - Note: Only mods or the owner of the quiz can stop it. """ if self.game_status[ctx.channel.id] is True: @@ -465,18 +450,14 @@ class TriviaQuiz(commands.Cog): ): await ctx.send("Quiz stopped.") - await self.declare_winner( - ctx.channel, self.game_player_scores[ctx.channel.id] - ) + await self.declare_winner(ctx.channel, self.game_player_scores[ctx.channel.id]) self.game_status[ctx.channel.id] = False del self.game_owners[ctx.channel.id] self.game_player_scores[ctx.channel.id] = {} else: - await ctx.send( - f"{ctx.author.mention}, you are not authorised to stop this game :ghost:!" - ) + await ctx.send(f"{ctx.author.mention}, you are not authorised to stop this game :ghost:!") else: await ctx.send("No quiz running.") @@ -540,9 +521,7 @@ class TriviaQuiz(commands.Cog): description="", ) - embed.set_footer( - text="If a category is not chosen, a random one will be selected." - ) + embed.set_footer(text="If a category is not chosen, a random one will be selected.") for cat, description in self.categories.items(): embed.description += ( -- cgit v1.2.3 From 675d2a03ececa926b5e3f7c129afb3f51b2a8213 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Sun, 9 May 2021 18:40:49 -0300 Subject: fix lint failure; add a newline at line 444 --- bot/exts/evergreen/trivia_quiz.py | 1 + 1 file changed, 1 insertion(+) diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index 79cf1318..f20a21f5 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -441,6 +441,7 @@ class TriviaQuiz(commands.Cog): async def stop_quiz(self, ctx: commands.Context) -> None: """ Stop a quiz game if its running in the channel. + Note: Only mods or the owner of the quiz can stop it. """ if self.game_status[ctx.channel.id] is True: -- cgit v1.2.3 From 2cd8c03c9d9daf410624589f8a94dfe4348c063c Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Sun, 9 May 2021 18:42:43 -0300 Subject: fix another linting fail regarding newlines in docstrings --- bot/exts/evergreen/trivia_quiz.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index f20a21f5..60dc2d0c 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -224,11 +224,13 @@ class TriviaQuiz(commands.Cog): async def quiz_game(self, ctx: commands.Context, category: Optional[str], questions: Optional[int]) -> None: """ Start a quiz! + Questions for the quiz can be selected from the following categories: - general: Test your general knowledge. (default) - retro: Questions related to retro gaming. - math: General questions about mathematics ranging from grade 8 to grade 12. - science: Put your understanding of science to the test! + (More to come!) """ if ctx.channel.id not in self.game_status: -- cgit v1.2.3 From 9c1dc83992cddca8aaa59d38afc55b1b8df34143 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Sun, 9 May 2021 18:46:22 -0300 Subject: docstring tweaks; consistency and imperative mood --- bot/exts/evergreen/trivia_quiz.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index 60dc2d0c..9d6e695f 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -61,7 +61,7 @@ UNITS_TO_BASE_UNITS = { def linear_system(q_format: str, a_format: str) -> Tuple[str, str]: - """Generates a system of linear equations with two unknowns.""" + """Generate a system of linear equations with two unknowns.""" x, y = random.randint(2, 5), random.randint(2, 5) answer = a_format.format(x, y) @@ -106,7 +106,7 @@ def ngonal_prism(q_format: str, a_format: str) -> Tuple[str, str]: def imag_sqrt(q_format: str, a_format: str) -> Tuple[str, str]: - """Generates a negative square root question.""" + """Generate a negative square root question.""" ans_coeff = random.randint(3, 10) question = q_format.format(ans_coeff ** 2) @@ -116,7 +116,7 @@ def imag_sqrt(q_format: str, a_format: str) -> Tuple[str, str]: def binary_calc(q_format: str, a_format: str) -> Tuple[str, str]: - """Generates a binary calculation question.""" + """Generate a binary calculation question.""" a = random.randint(15, 20) b = random.randint(10, a) oper = random.choice( @@ -144,7 +144,7 @@ def binary_calc(q_format: str, a_format: str) -> Tuple[str, str]: def solar_system(q_format: str, a_format: str) -> Tuple[str, str]: - """Generates a question on the planets of the Solar System.""" + """Generate a question on the planets of the Solar System.""" planet = random.choice(PLANETS) question = q_format.format(planet[0]) @@ -154,7 +154,7 @@ def solar_system(q_format: str, a_format: str) -> Tuple[str, str]: def taxonomic_rank(q_format: str, a_format: str) -> Tuple[str, str]: - """Generates a question on taxonomic classification.""" + """Generate a question on taxonomic classification.""" level = random.randint(0, len(TAXONOMIC_HIERARCHY) - 2) question = q_format.format(TAXONOMIC_HIERARCHY[level]) @@ -164,7 +164,7 @@ def taxonomic_rank(q_format: str, a_format: str) -> Tuple[str, str]: def base_units_convert(q_format: str, a_format: str) -> Tuple[str, str]: - """Generates a SI base units conversion question.""" + """Generate a SI base units conversion question.""" unit = random.choice(list(UNITS_TO_BASE_UNITS.keys())) question = q_format.format( @@ -556,5 +556,5 @@ class TriviaQuiz(commands.Cog): def setup(bot: commands.Bot) -> None: - """Load the cog.""" + """Load the TriviaQuiz cog.""" bot.add_cog(TriviaQuiz(bot)) -- cgit v1.2.3 From cb49ea232cd9d4d3c54637b386b89dd0f1b21a90 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Sun, 9 May 2021 20:05:31 -0300 Subject: did some changes per the new reviews and suggestions implemented all suggested changes from vcokltfre and almost all from decorator-factory --- bot/exts/evergreen/trivia_quiz.py | 49 ++++++++++++++++++--------------------- 1 file changed, 22 insertions(+), 27 deletions(-) diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index 9d6e695f..f2dfe6a9 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -16,6 +16,8 @@ from bot.constants import Roles logger = logging.getLogger(__name__) +QAndA = Tuple[str, str] + VARIATION_TOLERANCE = 83 WRONG_ANS_RESPONSE = [ @@ -60,7 +62,7 @@ UNITS_TO_BASE_UNITS = { } -def linear_system(q_format: str, a_format: str) -> Tuple[str, str]: +def linear_system(q_format: str, a_format: str) -> QAndA: """Generate a system of linear equations with two unknowns.""" x, y = random.randint(2, 5), random.randint(2, 5) answer = a_format.format(x, y) @@ -83,7 +85,7 @@ def linear_system(q_format: str, a_format: str) -> Tuple[str, str]: return question, answer -def mod_arith(q_format: str, a_format: str) -> Tuple[str, str]: +def mod_arith(q_format: str, a_format: str) -> QAndA: """Generate a basic modular arithmetic question.""" quotient, m, b = random.randint(30, 40), random.randint(10, 20), random.randint(200, 350) ans = random.randint(0, 9) # max 9 because min mod 10 @@ -95,7 +97,7 @@ def mod_arith(q_format: str, a_format: str) -> Tuple[str, str]: return question, answer -def ngonal_prism(q_format: str, a_format: str) -> Tuple[str, str]: +def ngonal_prism(q_format: str, a_format: str) -> QAndA: """Generate a question regarding vertices on n-gonal prisms.""" n = random.randint(0, len(N_PREFIXES) - 1) @@ -105,7 +107,7 @@ def ngonal_prism(q_format: str, a_format: str) -> Tuple[str, str]: return question, answer -def imag_sqrt(q_format: str, a_format: str) -> Tuple[str, str]: +def imag_sqrt(q_format: str, a_format: str) -> QAndA: """Generate a negative square root question.""" ans_coeff = random.randint(3, 10) @@ -115,7 +117,7 @@ def imag_sqrt(q_format: str, a_format: str) -> Tuple[str, str]: return question, answer -def binary_calc(q_format: str, a_format: str) -> Tuple[str, str]: +def binary_calc(q_format: str, a_format: str) -> QAndA: """Generate a binary calculation question.""" a = random.randint(15, 20) b = random.randint(10, a) @@ -136,14 +138,12 @@ def binary_calc(q_format: str, a_format: str) -> Tuple[str, str]: oper[0], b, ) - answer = a_format.format( - oper[1](a, b) - ) + answer = a_format.format(oper[1](a, b)) return question, answer -def solar_system(q_format: str, a_format: str) -> Tuple[str, str]: +def solar_system(q_format: str, a_format: str) -> QAndA: """Generate a question on the planets of the Solar System.""" planet = random.choice(PLANETS) @@ -153,7 +153,7 @@ def solar_system(q_format: str, a_format: str) -> Tuple[str, str]: return question, answer -def taxonomic_rank(q_format: str, a_format: str) -> Tuple[str, str]: +def taxonomic_rank(q_format: str, a_format: str) -> QAndA: """Generate a question on taxonomic classification.""" level = random.randint(0, len(TAXONOMIC_HIERARCHY) - 2) @@ -163,7 +163,7 @@ def taxonomic_rank(q_format: str, a_format: str) -> Tuple[str, str]: return question, answer -def base_units_convert(q_format: str, a_format: str) -> Tuple[str, str]: +def base_units_convert(q_format: str, a_format: str) -> QAndA: """Generate a SI base units conversion question.""" unit = random.choice(list(UNITS_TO_BASE_UNITS.keys())) @@ -216,9 +216,7 @@ class TriviaQuiz(commands.Cog): """Load the questions from the JSON file.""" p = Path("bot", "resources", "evergreen", "trivia_quiz.json") - with p.open(encoding="utf8") as json_data: - questions = json.load(json_data) - return questions + return json.loads(p.read_text()) @commands.group(name="quiz", aliases=["trivia"], invoke_without_command=True) async def quiz_game(self, ctx: commands.Context, category: Optional[str], questions: Optional[int]) -> None: @@ -274,7 +272,7 @@ class TriviaQuiz(commands.Cog): elif questions < 1: await ctx.send( embed=self.make_error_embed( - "Please do at least one question." + "You must choose to complete at least one question." ) ) return @@ -283,7 +281,7 @@ class TriviaQuiz(commands.Cog): self.question_limit = questions - 1 # Start game if not running. - if self.game_status[ctx.channel.id] is False: + if not self.game_status[ctx.channel.id]: self.game_owners[ctx.channel.id] = ctx.author self.game_status[ctx.channel.id] = True start_embed = self.make_start_embed(category) @@ -338,23 +336,21 @@ class TriviaQuiz(commands.Cog): if img_url := question_dict.get("image_url"): embed.set_image(url=img_url) - await ctx.send(embed=embed) # Send question embed. + await ctx.send(embed=embed) - # A function to check whether user input is the correct answer(close to the right answer) - def check(m: discord.Message) -> bool: + def contains_correct_answer(m: discord.Message) -> bool: return m.channel == ctx.channel and any( fuzz.ratio(answer.lower(), m.content.lower()) > VARIATION_TOLERANCE for answer in answers ) try: - msg = await self.bot.wait_for("message", check=check, timeout=10) + msg = await self.bot.wait_for("message", check=contains_correct_answer, timeout=10) except asyncio.TimeoutError: # In case of TimeoutError and the game has been stopped, then do nothing. - if self.game_status[ctx.channel.id] is False: + if not self.game_status[ctx.channel.id]: break - # if number of hints sent or time alerts sent is less than 2, then send one. if hint_no < 2: hint_no += 1 @@ -385,7 +381,6 @@ class TriviaQuiz(commands.Cog): if self.game_status[ctx.channel.id] is False: break - # Reduce points by 25 for every hint/time alert that has been sent. points = 100 - 25 * hint_no if msg.author in self.game_player_scores[ctx.channel.id]: self.game_player_scores[ctx.channel.id][msg.author] += points @@ -471,13 +466,13 @@ class TriviaQuiz(commands.Cog): @staticmethod async def send_score(channel: discord.TextChannel, player_data: dict) -> None: - """A function which sends the score.""" + """Send the score.""" if len(player_data) == 0: await channel.send("No one has made it onto the leaderboard yet.") return embed = discord.Embed( - colour=discord.Colour.blue(), + colour=Colours.blue, title="Score Board", description="", ) @@ -519,7 +514,7 @@ class TriviaQuiz(commands.Cog): def category_embed(self) -> discord.Embed: """Build an embed showing all available trivia categories.""" embed = discord.Embed( - colour=discord.Colour.blue(), + colour=Colours.blue, title="The available question categories are:", description="", ) @@ -544,7 +539,7 @@ class TriviaQuiz(commands.Cog): info = question_dict.get("info", "") embed = discord.Embed( - color=discord.Colour.red(), + color=Colours.bright_green, title=f"The correct answer is/are **`{', '.join(answers)}`**\n", ) -- cgit v1.2.3 From 1f0231d725deb44b3d1ab603448680228b1942a2 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Sun, 9 May 2021 20:13:53 -0300 Subject: add gold colour --- bot/constants.py | 1 + 1 file changed, 1 insertion(+) diff --git a/bot/constants.py b/bot/constants.py index 6cbfa8db..884cf3a8 100644 --- a/bot/constants.py +++ b/bot/constants.py @@ -151,6 +151,7 @@ class Colours: python_blue = 0x4B8BBE python_yellow = 0xFFD43B grass_green = 0x66ff00 + gold = 0xE6C200 easter_like_colours = [ (255, 247, 0), -- cgit v1.2.3 From a3cf147787058832740316df03a358e3f1039bc9 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Sun, 9 May 2021 20:15:45 -0300 Subject: use gold colour from constants.py for consistency --- bot/exts/evergreen/trivia_quiz.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index f2dfe6a9..31d9dbce 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -328,7 +328,7 @@ class TriviaQuiz(commands.Cog): answers = [answers] embed = discord.Embed( - colour=discord.Colour.gold(), + colour=Colours.gold, title=f"Question #{len(done_question)}", description=question, ) -- cgit v1.2.3 From 5320a38afe1810ccb445f61e74a7facf5b0e9e5a Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Sun, 9 May 2021 20:45:13 -0300 Subject: minor tweaks as suggested by vcokltfre see their five change requests for details --- bot/exts/evergreen/trivia_quiz.py | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index 31d9dbce..51e24226 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -88,7 +88,7 @@ def linear_system(q_format: str, a_format: str) -> QAndA: def mod_arith(q_format: str, a_format: str) -> QAndA: """Generate a basic modular arithmetic question.""" quotient, m, b = random.randint(30, 40), random.randint(10, 20), random.randint(200, 350) - ans = random.randint(0, 9) # max 9 because min mod 10 + ans = random.randint(0, 9) # max remainder is 9, since the minimum modulus is 10 a = quotient * m + ans - b question = q_format.format(a, b, m) @@ -133,11 +133,7 @@ def binary_calc(q_format: str, a_format: str) -> QAndA: a -= 5 b -= 5 - question = q_format.format( - a, - oper[0], - b, - ) + question = q_format.format(a, oper[0], b) answer = a_format.format(oper[1](a, b)) return question, answer @@ -165,7 +161,7 @@ def taxonomic_rank(q_format: str, a_format: str) -> QAndA: def base_units_convert(q_format: str, a_format: str) -> QAndA: """Generate a SI base units conversion question.""" - unit = random.choice(list(UNITS_TO_BASE_UNITS.keys())) + unit = random.choice(list(UNITS_TO_BASE_UNITS)) question = q_format.format( unit + " " + UNITS_TO_BASE_UNITS[unit][0] @@ -405,7 +401,7 @@ class TriviaQuiz(commands.Cog): def make_start_embed(self, category: str) -> discord.Embed: """Generate a starting/introduction embed for the quiz.""" start_embed = discord.Embed( - colour=discord.Colour.red(), + colour=Colours.blue, title="Quiz game starting!", description=( f"Each game consists of {self.question_limit + 1} questions.\n" @@ -538,9 +534,11 @@ class TriviaQuiz(commands.Cog): """Send the correct answer of a question to the game channel.""" info = question_dict.get("info", "") + word = "is" if len(answers) == 1 else "are" + embed = discord.Embed( color=Colours.bright_green, - title=f"The correct answer is/are **`{', '.join(answers)}`**\n", + title=f"The correct answer {word} **`{', '.join(answers)}`**\n", ) if info != "": -- cgit v1.2.3 From 7bbf7b18a5066b17475bcd2b8c1dc87417692f75 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Sun, 9 May 2021 20:57:03 -0300 Subject: fixed no description embed error --- bot/exts/evergreen/trivia_quiz.py | 1 + 1 file changed, 1 insertion(+) diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index 51e24226..23aac5fa 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -539,6 +539,7 @@ class TriviaQuiz(commands.Cog): embed = discord.Embed( color=Colours.bright_green, title=f"The correct answer {word} **`{', '.join(answers)}`**\n", + description="", ) if info != "": -- cgit v1.2.3 From 2e58fca5d444e8eb8adf7eba1223daff2f5fc14c Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Sun, 9 May 2021 21:09:23 -0300 Subject: reduce default no of questions to 7, add actual content to "Remaining questions: " --- bot/exts/evergreen/trivia_quiz.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index 23aac5fa..8d1a27ba 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -195,7 +195,7 @@ class TriviaQuiz(commands.Cog): self.game_owners = {} # A variable to store the person's ID who started the quiz game in a channel. self.questions = self.load_questions() - self.question_limit = 7 + self.question_limit = 6 self.player_scores = {} # A variable to store all player's scores for a bot session. self.game_player_scores = {} # A variable to store temporary game player's scores. @@ -366,7 +366,7 @@ class TriviaQuiz(commands.Cog): response = random.choice(WRONG_ANS_RESPONSE) await ctx.send(response) - await self.send_answer(ctx.channel, answers, question_dict) + await self.send_answer(ctx.channel, answers, question_dict, len(done_question)) await asyncio.sleep(1) hint_no = 0 # init hint_no = 0 so that 2 hints/time alerts can be sent for the new question. @@ -393,7 +393,7 @@ class TriviaQuiz(commands.Cog): await ctx.send(f"{msg.author.mention} got the correct answer :tada: {points} points!") - await self.send_answer(ctx.channel, answers, question_dict) + await self.send_answer(ctx.channel, answers, question_dict, len(done_question)) await self.send_score(ctx.channel, self.game_player_scores[ctx.channel.id]) await asyncio.sleep(2) @@ -530,6 +530,7 @@ class TriviaQuiz(commands.Cog): channel: discord.TextChannel, answers: List[str], question_dict: dict, + q_left: int, ) -> None: """Send the correct answer of a question to the game channel.""" info = question_dict.get("info", "") @@ -545,7 +546,7 @@ class TriviaQuiz(commands.Cog): if info != "": embed.description += f"**Information**\n{info}\n\n" - embed.description += "Let's move to the next question.\nRemaining questions: " + embed.description += f"Let's move to the next question.\nRemaining questions: {q_left}" await channel.send(embed=embed) -- cgit v1.2.3 From 119f08411eeb9ec205b4678959feb270ff76548c Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Sun, 9 May 2021 21:23:01 -0300 Subject: fix bug where remaining questions go up instead of down --- bot/exts/evergreen/trivia_quiz.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index 8d1a27ba..5ec37b25 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -366,7 +366,7 @@ class TriviaQuiz(commands.Cog): response = random.choice(WRONG_ANS_RESPONSE) await ctx.send(response) - await self.send_answer(ctx.channel, answers, question_dict, len(done_question)) + await self.send_answer(ctx.channel, answers, question_dict, self.question_limit - len(done_question)) await asyncio.sleep(1) hint_no = 0 # init hint_no = 0 so that 2 hints/time alerts can be sent for the new question. @@ -393,7 +393,7 @@ class TriviaQuiz(commands.Cog): await ctx.send(f"{msg.author.mention} got the correct answer :tada: {points} points!") - await self.send_answer(ctx.channel, answers, question_dict, len(done_question)) + await self.send_answer(ctx.channel, answers, question_dict, self.question_limit - len(done_question)) await self.send_score(ctx.channel, self.game_player_scores[ctx.channel.id]) await asyncio.sleep(2) -- cgit v1.2.3 From f22cebc139e03cd965e5b1d470795126d02250fd Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Sun, 9 May 2021 21:25:40 -0300 Subject: increase readability, fix lint failure --- bot/exts/evergreen/trivia_quiz.py | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index 5ec37b25..43d786bc 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -366,7 +366,13 @@ class TriviaQuiz(commands.Cog): response = random.choice(WRONG_ANS_RESPONSE) await ctx.send(response) - await self.send_answer(ctx.channel, answers, question_dict, self.question_limit - len(done_question)) + + await self.send_answer( + ctx.channel, + answers, + question_dict, + self.question_limit - len(done_question) + ) await asyncio.sleep(1) hint_no = 0 # init hint_no = 0 so that 2 hints/time alerts can be sent for the new question. @@ -393,7 +399,12 @@ class TriviaQuiz(commands.Cog): await ctx.send(f"{msg.author.mention} got the correct answer :tada: {points} points!") - await self.send_answer(ctx.channel, answers, question_dict, self.question_limit - len(done_question)) + await self.send_answer( + ctx.channel, + answers, + question_dict, + self.question_limit - len(done_question) + ) await self.send_score(ctx.channel, self.game_player_scores[ctx.channel.id]) await asyncio.sleep(2) -- cgit v1.2.3 From d2e1d52c762b73e240dabdbee1004e73315a5b4e Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Sun, 9 May 2021 21:31:10 -0300 Subject: forgot to increment by one, fixed --- bot/exts/evergreen/trivia_quiz.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index 43d786bc..bd3b136e 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -371,7 +371,7 @@ class TriviaQuiz(commands.Cog): ctx.channel, answers, question_dict, - self.question_limit - len(done_question) + self.question_limit - len(done_question) + 1 ) await asyncio.sleep(1) @@ -403,7 +403,7 @@ class TriviaQuiz(commands.Cog): ctx.channel, answers, question_dict, - self.question_limit - len(done_question) + self.question_limit - len(done_question) + 1 ) await self.send_score(ctx.channel, self.game_player_scores[ctx.channel.id]) -- cgit v1.2.3 From 1012c8b7421b30cf80ff26798308f9ee1586e0f7 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Sun, 9 May 2021 21:50:33 -0300 Subject: final minor refinery as requested by vcokltfre --- bot/exts/evergreen/trivia_quiz.py | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index bd3b136e..56929fe7 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -370,8 +370,9 @@ class TriviaQuiz(commands.Cog): await self.send_answer( ctx.channel, answers, + False, question_dict, - self.question_limit - len(done_question) + 1 + self.question_limit - len(done_question) + 1, ) await asyncio.sleep(1) @@ -402,8 +403,9 @@ class TriviaQuiz(commands.Cog): await self.send_answer( ctx.channel, answers, + True, question_dict, - self.question_limit - len(done_question) + 1 + self.question_limit - len(done_question) + 1, ) await self.send_score(ctx.channel, self.game_player_scores[ctx.channel.id]) @@ -540,6 +542,7 @@ class TriviaQuiz(commands.Cog): async def send_answer( channel: discord.TextChannel, answers: List[str], + answer_is_correct: bool, question_dict: dict, q_left: int, ) -> None: @@ -550,14 +553,20 @@ class TriviaQuiz(commands.Cog): embed = discord.Embed( color=Colours.bright_green, - title=f"The correct answer {word} **`{', '.join(answers)}`**\n", + title=( + "You got it! " if answer_is_correct else "" + f"The correct answer {word} **`{', '.join(answers)}`**\n" + ), description="", ) if info != "": embed.description += f"**Information**\n{info}\n\n" - embed.description += f"Let's move to the next question.\nRemaining questions: {q_left}" + embed.description += ( + "Let's move to the next question." if q_left > 0 else "" + f"\nRemaining questions: {q_left}" + ) await channel.send(embed=embed) -- cgit v1.2.3 From d7e3937d019025578b09fed0bfc59bb0e174ed84 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Mon, 10 May 2021 08:43:40 -0400 Subject: Update bot/exts/evergreen/trivia_quiz.py Co-authored-by: Shivansh-007 --- bot/exts/evergreen/trivia_quiz.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index 56929fe7..bd319910 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -72,9 +72,7 @@ def linear_system(q_format: str, a_format: str) -> QAndA: question = q_format.format( coeffs[0], coeffs[1], - ( - coeffs[0] * x + coeffs[1] * y - ), + coeffs[0] * x + coeffs[1] * y, coeffs[2], coeffs[3], ( -- cgit v1.2.3 From f8ea21fd364adb09f26b092aa4ef0cbbeeca0430 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Mon, 10 May 2021 08:44:16 -0400 Subject: remove redundant parentheses Co-authored-by: Shivansh-007 --- bot/exts/evergreen/trivia_quiz.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index bd319910..045fedbf 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -75,9 +75,7 @@ def linear_system(q_format: str, a_format: str) -> QAndA: coeffs[0] * x + coeffs[1] * y, coeffs[2], coeffs[3], - ( - coeffs[2] * x + coeffs[3] * y - ), + coeffs[2] * x + coeffs[3] * y, ) return question, answer -- cgit v1.2.3 From 5f9242749db72912abc7c52a8e1da90ca09c6848 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Mon, 10 May 2021 09:52:59 -0300 Subject: apply some changes suggested by Shivansh-007 made send_score docstring more precise, added a comment for better understanding, and changed an error embed description --- bot/exts/evergreen/trivia_quiz.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index 045fedbf..2620dea1 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -125,6 +125,7 @@ def binary_calc(q_format: str, a_format: str) -> QAndA: ) ) + # if the operator is multiplication, lower the values of the two operands to make it easier if oper[0] == "*": a -= 5 b -= 5 @@ -264,7 +265,8 @@ class TriviaQuiz(commands.Cog): elif questions < 1: await ctx.send( embed=self.make_error_embed( - "You must choose to complete at least one question." + "You must choose to complete at least one question. " + "(or enter 0 for the default value of 7 questions)" ) ) return @@ -471,7 +473,7 @@ class TriviaQuiz(commands.Cog): @staticmethod async def send_score(channel: discord.TextChannel, player_data: dict) -> None: - """Send the score.""" + """Send the current scores of players in the game channel.""" if len(player_data) == 0: await channel.send("No one has made it onto the leaderboard yet.") return -- cgit v1.2.3 From 6040e351403c5a708e77a26d1f8167f767988c56 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Mon, 10 May 2021 12:06:19 -0300 Subject: make vartol stricter when it's a generated question also fixed image not displaying bug --- bot/exts/evergreen/trivia_quiz.py | 34 +++++++++++++++++++--------------- 1 file changed, 19 insertions(+), 15 deletions(-) diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index 2620dea1..c00d91ae 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -4,7 +4,7 @@ import logging import operator import random from pathlib import Path -from typing import List, Optional, Tuple +from typing import Callable, List, Optional, Tuple import discord from discord.ext import commands @@ -18,7 +18,8 @@ logger = logging.getLogger(__name__) QAndA = Tuple[str, str] -VARIATION_TOLERANCE = 83 +STANDARD_VARIATION_TOLERANCE = 83 +DYNAMICALLY_GEN_VARIATION_TOLERANCE = 95 WRONG_ANS_RESPONSE = [ "No one answered correctly!", @@ -215,13 +216,11 @@ class TriviaQuiz(commands.Cog): async def quiz_game(self, ctx: commands.Context, category: Optional[str], questions: Optional[int]) -> None: """ Start a quiz! - Questions for the quiz can be selected from the following categories: - general: Test your general knowledge. (default) - retro: Questions related to retro gaming. - math: General questions about mathematics ranging from grade 8 to grade 12. - science: Put your understanding of science to the test! - (More to come!) """ if ctx.channel.id not in self.game_status: @@ -311,6 +310,8 @@ class TriviaQuiz(commands.Cog): if "dynamic_id" not in question_dict: question = question_dict["question"] answers = question_dict["answer"].split(", ") + + var_tol = STANDARD_VARIATION_TOLERANCE else: format_func = DYNAMIC_QUESTIONS_FORMAT_FUNCS[question_dict["dynamic_id"]] @@ -318,28 +319,32 @@ class TriviaQuiz(commands.Cog): question_dict["question"], question_dict["answer"], ) - answers = [answers] + var_tol = DYNAMICALLY_GEN_VARIATION_TOLERANCE + embed = discord.Embed( colour=Colours.gold, title=f"Question #{len(done_question)}", description=question, ) - if img_url := question_dict.get("image_url"): + if img_url := question_dict.get("img_url"): embed.set_image(url=img_url) await ctx.send(embed=embed) - def contains_correct_answer(m: discord.Message) -> bool: - return m.channel == ctx.channel and any( - fuzz.ratio(answer.lower(), m.content.lower()) > VARIATION_TOLERANCE - for answer in answers - ) + def check_func(variation_tolerance: int) -> Callable[[discord.Message], bool]: + def contains_correct_answer(m: discord.Message) -> bool: + return m.channel == ctx.channel and any( + fuzz.ratio(answer.lower(), m.content.lower()) > variation_tolerance + for answer in answers + ) + + return contains_correct_answer try: - msg = await self.bot.wait_for("message", check=contains_correct_answer, timeout=10) + msg = await self.bot.wait_for("message", check=check_func(var_tol), timeout=10) except asyncio.TimeoutError: # In case of TimeoutError and the game has been stopped, then do nothing. if not self.game_status[ctx.channel.id]: @@ -445,7 +450,6 @@ class TriviaQuiz(commands.Cog): async def stop_quiz(self, ctx: commands.Context) -> None: """ Stop a quiz game if its running in the channel. - Note: Only mods or the owner of the quiz can stop it. """ if self.game_status[ctx.channel.id] is True: @@ -552,7 +556,7 @@ class TriviaQuiz(commands.Cog): embed = discord.Embed( color=Colours.bright_green, title=( - "You got it! " if answer_is_correct else "" + ("You got it! " if answer_is_correct else "") + f"The correct answer {word} **`{', '.join(answers)}`**\n" ), description="", @@ -562,7 +566,7 @@ class TriviaQuiz(commands.Cog): embed.description += f"**Information**\n{info}\n\n" embed.description += ( - "Let's move to the next question." if q_left > 0 else "" + ("Let's move to the next question." if q_left > 0 else "") + f"\nRemaining questions: {q_left}" ) await channel.send(embed=embed) -- cgit v1.2.3 From aab59b138e877fab349314b4b326ede914ea56c3 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Mon, 10 May 2021 12:10:54 -0300 Subject: lint failure fixes --- bot/exts/evergreen/trivia_quiz.py | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index c00d91ae..94dc9f06 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -216,11 +216,13 @@ class TriviaQuiz(commands.Cog): async def quiz_game(self, ctx: commands.Context, category: Optional[str], questions: Optional[int]) -> None: """ Start a quiz! + Questions for the quiz can be selected from the following categories: - general: Test your general knowledge. (default) - retro: Questions related to retro gaming. - math: General questions about mathematics ranging from grade 8 to grade 12. - science: Put your understanding of science to the test! + (More to come!) """ if ctx.channel.id not in self.game_status: @@ -450,6 +452,7 @@ class TriviaQuiz(commands.Cog): async def stop_quiz(self, ctx: commands.Context) -> None: """ Stop a quiz game if its running in the channel. + Note: Only mods or the owner of the quiz can stop it. """ if self.game_status[ctx.channel.id] is True: @@ -556,8 +559,8 @@ class TriviaQuiz(commands.Cog): embed = discord.Embed( color=Colours.bright_green, title=( - ("You got it! " if answer_is_correct else "") + - f"The correct answer {word} **`{', '.join(answers)}`**\n" + ("You got it! " if answer_is_correct else "") + + f"The correct answer {word} **`{', '.join(answers)}`**\n" ), description="", ) @@ -566,8 +569,8 @@ class TriviaQuiz(commands.Cog): embed.description += f"**Information**\n{info}\n\n" embed.description += ( - ("Let's move to the next question." if q_left > 0 else "") + - f"\nRemaining questions: {q_left}" + ("Let's move to the next question." if q_left > 0 else "") + + f"\nRemaining questions: {q_left}" ) await channel.send(embed=embed) -- cgit v1.2.3 From 3f0388556c886d9d8e26b7a0373e3a6d2d9ba5ad Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Tue, 11 May 2021 09:05:09 -0400 Subject: fix original copy paste error in math question Co-authored-by: Matteo Bertucci --- bot/resources/evergreen/trivia_quiz.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bot/resources/evergreen/trivia_quiz.json b/bot/resources/evergreen/trivia_quiz.json index 79e79d00..1e85542f 100644 --- a/bot/resources/evergreen/trivia_quiz.json +++ b/bot/resources/evergreen/trivia_quiz.json @@ -301,7 +301,7 @@ }, { "id": 203, - "question": "Which theorem states that hypotenuse2 = base2 + height2?", + "question": "Which theorem states that hypotenuse^2 = base^2 + height^2?", "answer": "Pythagorean's, Pythagorean's theorem" }, { -- cgit v1.2.3 From fa0f365acebfdef1130330dc2835945e9da3a69b Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Tue, 11 May 2021 10:08:40 -0300 Subject: add one more correct answer to science (q328) --- bot/resources/evergreen/trivia_quiz.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bot/resources/evergreen/trivia_quiz.json b/bot/resources/evergreen/trivia_quiz.json index 1e85542f..774c235a 100644 --- a/bot/resources/evergreen/trivia_quiz.json +++ b/bot/resources/evergreen/trivia_quiz.json @@ -592,7 +592,7 @@ { "id": 328, "question": "Which law states that the global entropy in a closed system can only increase?", - "answer": "second law of thermodynamics" + "answer": "second law, second law of thermodynamics" }, { "id": 329, -- cgit v1.2.3 From d2754ce38232955e17322264e78ca90b0a3d7cb7 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Tue, 11 May 2021 10:57:36 -0300 Subject: made comment more precise as described by decorator-factory --- bot/exts/evergreen/trivia_quiz.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index 94dc9f06..94d9e374 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -381,7 +381,7 @@ class TriviaQuiz(commands.Cog): ) await asyncio.sleep(1) - hint_no = 0 # init hint_no = 0 so that 2 hints/time alerts can be sent for the new question. + hint_no = 0 # Reset the hint counter so that on the next round, it's in the initial state await self.send_score(ctx.channel, self.game_player_scores[ctx.channel.id]) await asyncio.sleep(2) -- cgit v1.2.3 From 5241fc893d1d378f6a4dcae32925f672ce8f87a7 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Tue, 11 May 2021 15:29:13 -0300 Subject: change weird google docs unicode to standard ones --- bot/resources/evergreen/trivia_quiz.json | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/bot/resources/evergreen/trivia_quiz.json b/bot/resources/evergreen/trivia_quiz.json index 774c235a..e2054f43 100644 --- a/bot/resources/evergreen/trivia_quiz.json +++ b/bot/resources/evergreen/trivia_quiz.json @@ -301,7 +301,7 @@ }, { "id": 203, - "question": "Which theorem states that hypotenuse^2 = base^2 + height^2?", + "question": "Which theorem states that hypotenuse2 = base2 + height2?", "answer": "Pythagorean's, Pythagorean's theorem" }, { @@ -360,7 +360,7 @@ }, { "id": 214, - "question": "⅓πr2h is the volume of which 3 dimensional figure?", + "question": "⅓πr^2h is the volume of which 3 dimensional figure?", "answer": "cone" }, { @@ -452,7 +452,7 @@ "science": [ { "id": 301, - "question": "The three main components of a normal atom are: protons, neutrons, and…", + "question": "The three main components of a normal atom are: protons, neutrons, and...", "answer": "electrons" }, { @@ -472,7 +472,7 @@ }, { "id": 305, - "question": "The Heisenberg’s Uncertainty Principle states that the position and ________ of a quantum object can’t be both exactly measured at the same time.", + "question": "The Heisenberg's Uncertainty Principle states that the position and ________ of a quantum object can't be both exactly measured at the same time.", "answer": "velocity, momentum" }, { @@ -500,9 +500,9 @@ { "id": 310, "dynamic_id": 303, - "question": "How does one describe the unit {} in SI base units?\n**IMPORTANT:** use * for multiplication, ^ for exponentiation, and place your base units in this order: m - kg - s - A", + "question": "How does one describe the unit {} in SI base units?\n**IMPORTANT:** enclose answer in backticks, use \\* for multiplication, ^ for exponentiation, and place your base units in this order: m - kg - s - A", "img_url": "https://i.imgur.com/NRzU6tf.png", - "answer": "{}" + "answer": "`{}`" }, { "id": 311, -- cgit v1.2.3 From 91db03e5fde06efb41341d595d75424b9ff759b2 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Tue, 11 May 2021 15:30:34 -0300 Subject: fix copy paste error --- bot/resources/evergreen/trivia_quiz.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bot/resources/evergreen/trivia_quiz.json b/bot/resources/evergreen/trivia_quiz.json index e2054f43..1ba5ea7b 100644 --- a/bot/resources/evergreen/trivia_quiz.json +++ b/bot/resources/evergreen/trivia_quiz.json @@ -301,7 +301,7 @@ }, { "id": 203, - "question": "Which theorem states that hypotenuse2 = base2 + height2?", + "question": "Which theorem states that hypotenuse^2 = base^2 + height2^?", "answer": "Pythagorean's, Pythagorean's theorem" }, { -- cgit v1.2.3 From febe3e7d5fea74ed939b903306e552177b2c61c2 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Tue, 11 May 2021 15:32:30 -0300 Subject: fix unicode corruption errors by encoding to utf-8 --- bot/exts/evergreen/trivia_quiz.py | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index 94d9e374..7fdd3f5f 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -10,9 +10,7 @@ import discord from discord.ext import commands from fuzzywuzzy import fuzz -from bot.constants import Colours -from bot.constants import NEGATIVE_REPLIES -from bot.constants import Roles +from bot.constants import Colours, NEGATIVE_REPLIES, Roles logger = logging.getLogger(__name__) @@ -210,7 +208,7 @@ class TriviaQuiz(commands.Cog): """Load the questions from the JSON file.""" p = Path("bot", "resources", "evergreen", "trivia_quiz.json") - return json.loads(p.read_text()) + return json.loads(p.read_text(encoding="utf-8")) @commands.group(name="quiz", aliases=["trivia"], invoke_without_command=True) async def quiz_game(self, ctx: commands.Context, category: Optional[str], questions: Optional[int]) -> None: -- cgit v1.2.3 From 8ee99da88cb5d2b0fc9b1e3dcf24f72bca5679a4 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Wed, 12 May 2021 08:38:53 -0400 Subject: fix ANOTHER copy paste error 3rd copy paste error- smh Co-authored-by: Shivansh-007 --- bot/resources/evergreen/trivia_quiz.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bot/resources/evergreen/trivia_quiz.json b/bot/resources/evergreen/trivia_quiz.json index 1ba5ea7b..acf7375a 100644 --- a/bot/resources/evergreen/trivia_quiz.json +++ b/bot/resources/evergreen/trivia_quiz.json @@ -301,7 +301,7 @@ }, { "id": 203, - "question": "Which theorem states that hypotenuse^2 = base^2 + height2^?", + "question": "Which theorem states that hypotenuse^2 = base^2 + height^2?", "answer": "Pythagorean's, Pythagorean's theorem" }, { -- cgit v1.2.3 From 4448f0d04987ac2628f74e43f6262a5856509f9d Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Wed, 12 May 2021 09:41:05 -0300 Subject: add one more possible answer to math q208 --- bot/resources/evergreen/trivia_quiz.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bot/resources/evergreen/trivia_quiz.json b/bot/resources/evergreen/trivia_quiz.json index acf7375a..3a907de1 100644 --- a/bot/resources/evergreen/trivia_quiz.json +++ b/bot/resources/evergreen/trivia_quiz.json @@ -328,7 +328,7 @@ "id": 208, "question": "What's the following formula that finds the area of a triangle called?", "img_url": "https://wikimedia.org/api/rest_v1/media/math/render/png/d22b8566e8187542966e8d166e72e93746a1a6fc", - "answer": "Heron's formula" + "answer": "Heron's formula, Heron" }, { "id": 209, -- cgit v1.2.3 From 358e5641d16ac27ca68c73f52cbccf12299818d6 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Wed, 12 May 2021 10:56:18 -0300 Subject: fix inconsistency of hexadecimal letter cases in Colours class --- bot/constants.py | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/bot/constants.py b/bot/constants.py index 9b45b89a..28ec477d 100644 --- a/bot/constants.py +++ b/bot/constants.py @@ -140,19 +140,19 @@ class Client(NamedTuple): class Colours: - blue = 0x0279fd - bright_green = 0x01d277 - dark_green = 0x1f8b4c - orange = 0xe67e22 - pink = 0xcf84e0 - purple = 0xb734eb - soft_green = 0x68c290 - soft_orange = 0xf9cb54 - soft_red = 0xcd6d6d - yellow = 0xf9f586 + blue = 0x0279FD + bright_green = 0x01D277 + dark_green = 0x1F8B4C + orange = 0xE67E22 + pink = 0xCF84E0 + purple = 0xB734EB + soft_green = 0x68C290 + soft_orange = 0xF9CB54 + soft_red = 0xCD6D6D + yellow = 0xF9F586 python_blue = 0x4B8BBE python_yellow = 0xFFD43B - grass_green = 0x66ff00 + grass_green = 0x66FF00 gold = 0xE6C200 easter_like_colours = [ @@ -180,7 +180,7 @@ class Emojis: envelope = "\U0001F4E8" trashcan = environ.get("TRASHCAN_EMOJI", "<:trashcan:637136429717389331>") ok_hand = ":ok_hand:" - hand_raised = "\U0001f64b" + hand_raised = "\U0001F64B" dice_1 = "<:dice_1:755891608859443290>" dice_2 = "<:dice_2:755891608741740635>" -- cgit v1.2.3 From 4430760c56f71046040369b3b1f248d8344bf968 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Wed, 12 May 2021 11:45:06 -0300 Subject: 0 as an input to `questions` would now also raise an error before it would go to the default of 7 --- bot/exts/evergreen/trivia_quiz.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index 7fdd3f5f..c2f891e2 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -16,6 +16,7 @@ logger = logging.getLogger(__name__) QAndA = Tuple[str, str] +DEFAULT_QUESTION_LIMIT = 6 STANDARD_VARIATION_TOLERANCE = 83 DYNAMICALLY_GEN_VARIATION_TOLERANCE = 95 @@ -191,7 +192,7 @@ class TriviaQuiz(commands.Cog): self.game_owners = {} # A variable to store the person's ID who started the quiz game in a channel. self.questions = self.load_questions() - self.question_limit = 6 + self.question_limit = 0 self.player_scores = {} # A variable to store all player's scores for a bot session. self.game_player_scores = {} # A variable to store temporary game player's scores. @@ -251,7 +252,9 @@ class TriviaQuiz(commands.Cog): topic = self.questions[category] topic_length = len(topic) - if questions: + if questions is None: + self.question_limit = DEFAULT_QUESTION_LIMIT + else: if questions > topic_length: await ctx.send( embed=self.make_error_embed( @@ -265,7 +268,7 @@ class TriviaQuiz(commands.Cog): await ctx.send( embed=self.make_error_embed( "You must choose to complete at least one question. " - "(or enter 0 for the default value of 7 questions)" + "(or enter nothing for the default value of 7 questions)" ) ) return -- cgit v1.2.3 From cb3b7a394f5fe60f75279d7ac9e4cdb47b267a20 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Wed, 12 May 2021 11:53:04 -0300 Subject: make the error embed change accordingly if DQL constant is modified --- bot/exts/evergreen/trivia_quiz.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index c2f891e2..0b242947 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -268,7 +268,7 @@ class TriviaQuiz(commands.Cog): await ctx.send( embed=self.make_error_embed( "You must choose to complete at least one question. " - "(or enter nothing for the default value of 7 questions)" + f"(or enter nothing for the default value of {DEFAULT_QUESTION_LIMIT + 1} questions)" ) ) return -- cgit v1.2.3 From 8f4911ad75d0860c8710e977a3d6928378fd703e Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Wed, 12 May 2021 14:23:24 -0300 Subject: quality-of-life refinery --- bot/exts/evergreen/trivia_quiz.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index 0b242947..cc1bb0bb 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -423,7 +423,7 @@ class TriviaQuiz(commands.Cog): colour=Colours.blue, title="Quiz game starting!", description=( - f"Each game consists of {self.question_limit + 1} questions.\n" + f"This game consists of {self.question_limit + 1} questions.\n" "**Rules: **No cheating and have fun!\n" f"**Category**: {category}" ), @@ -555,13 +555,13 @@ class TriviaQuiz(commands.Cog): """Send the correct answer of a question to the game channel.""" info = question_dict.get("info", "") - word = "is" if len(answers) == 1 else "are" + plurality = " is" if len(answers) == 1 else "s are" embed = discord.Embed( color=Colours.bright_green, title=( ("You got it! " if answer_is_correct else "") - + f"The correct answer {word} **`{', '.join(answers)}`**\n" + + f"The correct answer{word} **`{', '.join(answers)}`**\n" ), description="", ) -- cgit v1.2.3 From 7df1d38400a275fb6c2d079f27ffaedad5bd4453 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Wed, 12 May 2021 14:24:41 -0300 Subject: fix 4th copy paste error --- bot/exts/evergreen/trivia_quiz.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index cc1bb0bb..e1a06aa5 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -561,7 +561,7 @@ class TriviaQuiz(commands.Cog): color=Colours.bright_green, title=( ("You got it! " if answer_is_correct else "") - + f"The correct answer{word} **`{', '.join(answers)}`**\n" + + f"The correct answer{plurality} **`{', '.join(answers)}`**\n" ), description="", ) -- cgit v1.2.3 From b125a1ab1cdb8355d6c4c5225f1b048ca760e957 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Thu, 13 May 2021 08:49:41 -0400 Subject: change the unsolvable math question to a linalg question --- bot/resources/evergreen/trivia_quiz.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/bot/resources/evergreen/trivia_quiz.json b/bot/resources/evergreen/trivia_quiz.json index 3a907de1..94082849 100644 --- a/bot/resources/evergreen/trivia_quiz.json +++ b/bot/resources/evergreen/trivia_quiz.json @@ -417,8 +417,8 @@ }, { "id": 225, - "question": "Prove or disprove the Riemann Hypothesis", - "answer": "" + "question": "A matrix multiplied by its inverse matrix equals...", + "answer": "the identity matrix, identity matrix" }, { "id": 226, -- cgit v1.2.3 From 62345be36b0ebf8f867e0fb6597ebd5e29488d1c Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Thu, 13 May 2021 15:20:09 -0300 Subject: implement decorator-factory's changes except for the major refactoring, which would probably be in a separate pr --- bot/exts/evergreen/trivia_quiz.py | 55 ++++++++++++++++++++++----------------- 1 file changed, 31 insertions(+), 24 deletions(-) diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index e1a06aa5..7aab8b87 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -3,8 +3,9 @@ import json import logging import operator import random +from dataclasses import dataclass from pathlib import Path -from typing import Callable, List, Optional, Tuple +from typing import Callable, List, Optional import discord from discord.ext import commands @@ -14,8 +15,6 @@ from bot.constants import Colours, NEGATIVE_REPLIES, Roles logger = logging.getLogger(__name__) -QAndA = Tuple[str, str] - DEFAULT_QUESTION_LIMIT = 6 STANDARD_VARIATION_TOLERANCE = 83 DYNAMICALLY_GEN_VARIATION_TOLERANCE = 95 @@ -62,7 +61,13 @@ UNITS_TO_BASE_UNITS = { } -def linear_system(q_format: str, a_format: str) -> QAndA: +@dataclass(frozen=True) +class QuizEntry: + question: str + answer: str + + +def linear_system(q_format: str, a_format: str) -> QuizEntry: """Generate a system of linear equations with two unknowns.""" x, y = random.randint(2, 5), random.randint(2, 5) answer = a_format.format(x, y) @@ -78,10 +83,10 @@ def linear_system(q_format: str, a_format: str) -> QAndA: coeffs[2] * x + coeffs[3] * y, ) - return question, answer + return QuizEntry(question, answer) -def mod_arith(q_format: str, a_format: str) -> QAndA: +def mod_arith(q_format: str, a_format: str) -> QuizEntry: """Generate a basic modular arithmetic question.""" quotient, m, b = random.randint(30, 40), random.randint(10, 20), random.randint(200, 350) ans = random.randint(0, 9) # max remainder is 9, since the minimum modulus is 10 @@ -90,30 +95,30 @@ def mod_arith(q_format: str, a_format: str) -> QAndA: question = q_format.format(a, b, m) answer = a_format.format(ans) - return question, answer + return QuizEntry(question, answer) -def ngonal_prism(q_format: str, a_format: str) -> QAndA: +def ngonal_prism(q_format: str, a_format: str) -> QuizEntry: """Generate a question regarding vertices on n-gonal prisms.""" n = random.randint(0, len(N_PREFIXES) - 1) question = q_format.format(N_PREFIXES[n]) answer = a_format.format((n + N_PREFIX_STARTS_AT) * 2) - return question, answer + return QuizEntry(question, answer) -def imag_sqrt(q_format: str, a_format: str) -> QAndA: +def imag_sqrt(q_format: str, a_format: str) -> QuizEntry: """Generate a negative square root question.""" ans_coeff = random.randint(3, 10) question = q_format.format(ans_coeff ** 2) answer = a_format.format(ans_coeff) - return question, answer + return QuizEntry(question, answer) -def binary_calc(q_format: str, a_format: str) -> QAndA: +def binary_calc(q_format: str, a_format: str) -> QuizEntry: """Generate a binary calculation question.""" a = random.randint(15, 20) b = random.randint(10, a) @@ -133,30 +138,30 @@ def binary_calc(q_format: str, a_format: str) -> QAndA: question = q_format.format(a, oper[0], b) answer = a_format.format(oper[1](a, b)) - return question, answer + return QuizEntry(question, answer) -def solar_system(q_format: str, a_format: str) -> QAndA: +def solar_system(q_format: str, a_format: str) -> QuizEntry: """Generate a question on the planets of the Solar System.""" planet = random.choice(PLANETS) question = q_format.format(planet[0]) answer = a_format.format(planet[1]) - return question, answer + return QuizEntry(question, answer) -def taxonomic_rank(q_format: str, a_format: str) -> QAndA: +def taxonomic_rank(q_format: str, a_format: str) -> QuizEntry: """Generate a question on taxonomic classification.""" level = random.randint(0, len(TAXONOMIC_HIERARCHY) - 2) question = q_format.format(TAXONOMIC_HIERARCHY[level]) answer = a_format.format(TAXONOMIC_HIERARCHY[level + 1]) - return question, answer + return QuizEntry(question, answer) -def base_units_convert(q_format: str, a_format: str) -> QAndA: +def base_units_convert(q_format: str, a_format: str) -> QuizEntry: """Generate a SI base units conversion question.""" unit = random.choice(list(UNITS_TO_BASE_UNITS)) @@ -167,7 +172,7 @@ def base_units_convert(q_format: str, a_format: str) -> QAndA: UNITS_TO_BASE_UNITS[unit][1] ) - return question, answer + return QuizEntry(question, answer) DYNAMIC_QUESTIONS_FORMAT_FUNCS = { @@ -231,7 +236,7 @@ class TriviaQuiz(commands.Cog): self.game_player_scores[ctx.channel.id] = {} # Stop game if running. - if self.game_status[ctx.channel.id] is True: + if self.game_status[ctx.channel.id]: await ctx.send( "Game is already running... " f"do `{self.bot.command_prefix}quiz stop`" @@ -318,10 +323,12 @@ class TriviaQuiz(commands.Cog): else: format_func = DYNAMIC_QUESTIONS_FORMAT_FUNCS[question_dict["dynamic_id"]] - question, answers = format_func( + quiz_entry = format_func( question_dict["question"], question_dict["answer"], ) + + question, answers = quiz_entry.question, quiz_entry.answer answers = [answers] var_tol = DYNAMICALLY_GEN_VARIATION_TOLERANCE @@ -492,7 +499,7 @@ class TriviaQuiz(commands.Cog): description="", ) - sorted_dict = sorted(player_data.items(), key=lambda a: a[1], reverse=True) + sorted_dict = sorted(player_data.items(), key=operator.itemgetter(1), reverse=True) for item in sorted_dict: embed.description += f"{item[0]}: {item[1]}\n" @@ -553,7 +560,7 @@ class TriviaQuiz(commands.Cog): q_left: int, ) -> None: """Send the correct answer of a question to the game channel.""" - info = question_dict.get("info", "") + info = question_dict.get("info") plurality = " is" if len(answers) == 1 else "s are" @@ -566,7 +573,7 @@ class TriviaQuiz(commands.Cog): description="", ) - if info != "": + if info is not None: embed.description += f"**Information**\n{info}\n\n" embed.description += ( -- cgit v1.2.3 From b090b15b4df08b7908cca6016a65802fc779cf3c Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Thu, 13 May 2021 15:23:15 -0300 Subject: add a docstring to the dataclass --- bot/exts/evergreen/trivia_quiz.py | 1 + 1 file changed, 1 insertion(+) diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index 7aab8b87..b5a18516 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -63,6 +63,7 @@ UNITS_TO_BASE_UNITS = { @dataclass(frozen=True) class QuizEntry: + """Dataclass for a quiz entry (a question and a string containing answers separated by commas)""" question: str answer: str -- cgit v1.2.3 From cf513ebd52cb337f760ae34e33380d1f09285c73 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Thu, 13 May 2021 15:24:40 -0300 Subject: fix the QuizEntry dataclass --- bot/exts/evergreen/trivia_quiz.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index b5a18516..4d18eaef 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -63,7 +63,8 @@ UNITS_TO_BASE_UNITS = { @dataclass(frozen=True) class QuizEntry: - """Dataclass for a quiz entry (a question and a string containing answers separated by commas)""" + """Dataclass for a quiz entry (a question and a string containing answers separated by commas).""" + question: str answer: str -- cgit v1.2.3 From aa3a38649e465c1299f3adfc5a5e4aa6fb8102b8 Mon Sep 17 00:00:00 2001 From: Objectivitix <79152594+Objectivitix@users.noreply.github.com> Date: Thu, 13 May 2021 15:27:08 -0300 Subject: delete trailing whitespace after docstring smh i have to stop making these errors lmao, definitely going to see that precommit thing after this --- bot/exts/evergreen/trivia_quiz.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bot/exts/evergreen/trivia_quiz.py b/bot/exts/evergreen/trivia_quiz.py index 4d18eaef..6d421668 100644 --- a/bot/exts/evergreen/trivia_quiz.py +++ b/bot/exts/evergreen/trivia_quiz.py @@ -64,7 +64,7 @@ UNITS_TO_BASE_UNITS = { @dataclass(frozen=True) class QuizEntry: """Dataclass for a quiz entry (a question and a string containing answers separated by commas).""" - + question: str answer: str -- cgit v1.2.3