diff options
| author | 2019-10-02 09:38:20 +0530 | |
|---|---|---|
| committer | 2019-10-02 09:38:20 +0530 | |
| commit | abce0ecc6a072d6d25035c6b55d45f2f85327c22 (patch) | |
| tree | fa86272f673ccc0d84489bbae0d5045d0991ae4b | |
| parent | added function annotations to the check method (diff) | |
Worked on the requested changes and also made a few other changes:
- when the user uses the command to stop the game, the bot fails to reply back with the winners list. This is because the varibale player_data is being initialised to {} at the start of the command. I solved this by making a player_data variable in the cog __init__() with the channel id being the key and dict as value
| -rw-r--r-- | bot/resources/evergreen/trivia_quiz.json | 120 | ||||
| -rw-r--r-- | bot/seasons/evergreen/trivia_quiz.py | 139 |
2 files changed, 112 insertions, 147 deletions
diff --git a/bot/resources/evergreen/trivia_quiz.json b/bot/resources/evergreen/trivia_quiz.json index 9c3259cd..69a834f8 100644 --- a/bot/resources/evergreen/trivia_quiz.json +++ b/bot/resources/evergreen/trivia_quiz.json @@ -2,13 +2,13 @@ "retro": [ { "id": 1, - "hints": ["It was not a mainline Mario Game, although the plumber was present.", "It was not a mainline Zelda Game, although Link was present."], - "question": "What was the best selling game on the Nintendo Gamecube?", + "hints": ["It is not a mainline Mario Game, although the plumber is present.", "It is not a mainline Zelda Game, although Link is present."], + "question": "What is the best selling game on the Nintendo GameCube?", "answer": "Super Smash Bros" }, { "id": 2, - "hints": ["It was released before the 90s.", "It was released after 1980."], + "hints": ["It was released before the 90's.", "It was released after 1980."], "question": "What year was Tetris released?", "answer": "1984" }, @@ -20,8 +20,8 @@ }, { "id": 4, - "hints": ["It was revelead in the Nintendo Character Guide in 1993.", "His last name has to do with eating Mario's enemies."], - "question": "What is Yoshi's(from Mario Bros) full name?", + "hints": ["It was revealed in the Nintendo Character Guide in 1993.", "His last name has to do with eating Mario's enemies."], + "question": "What is Yoshi's (from Mario Bros.) full name?", "answer": "Yoshisaur Munchakoopas" }, { @@ -34,109 +34,108 @@ "general":[ { "id": 100, - "question": "Name the land of thousand lakes", + "question": "Name \"the land of a thousand lakes\"", "answer": "Finland", - "info": "Finland is a country in Northern Europe. Sweden borders it to the northwest, Estonia to the south, Russia to the east, and Norway to the north. Finland is part of the European Union with its capital city being Helsinki. With a population of 5.5 million people, it has over 187,000 lakes. The thousands of lakes in Finland are the reason why the country's nickname is “the land of a thousand lakes." + "info": "Finland is a country in Northern Europe. Sweden borders it to the northwest, Estonia to the south, Russia to the east, and Norway to the north. Finland is part of the European Union with its capital city being Helsinki. With a population of 5.5 million people, it has over 187,000 lakes. The thousands of lakes in Finland are the reason why the country's nickname is \"the land of a thousand lakes.\"" }, { "id": 101, - "question": "Winner of FIFA 2018", + "question": "Who was the winner of FIFA 2018?", "answer": "France", "info": "France 4 - 2 Croatia" }, { "id": 102, - "question": "Remind me the largest Ocean in the world.", + "question": "What is the largest ocean in the world?", "answer": "Pacific", "info": "The Pacific Ocean is the largest and deepest of the world ocean basins. Covering approximately 63 million square miles and containing more than half of the free water on Earth, the Pacific is by far the largest of the world's ocean basins." }, { "id": 103, - "question": "Have you heard of The Statue Of Liberty ? Who gifted it?", - "answer": "French", - "info": "The Statue of Liberty was a gift from the French people commemorating the alliance of France and the United States during the American Revolution. Yet, it represented much more to those individuals who proposed the gift. A photograph of Edouard de Laboulaye from the Galerie Contemporaine collection." + "question": "Who gifted the Statue Of Liberty?", + "answer": "France", + "info": "The Statue of Liberty was a gift from the French people commemorating the alliance of France and the United States during the American Revolution. Yet, it represented much more to those individuals who proposed the gift." }, { "id": 104, - "question": "Land Of The Rising Sun?", + "question": "Which country is known as the \"Land Of The Rising Sun\"?", "answer": "Japan", - "info": "According to the words of the Japanese envoy himself, that name was chosen because the country was so close to where the sun rises. In any event, the name stuck, and for the last 1400 years or so, the world has referred to Japan as Nippon, the land of the rising sun." + "info": "The title stems from the Japanese names for Japan, Nippon/Nihon, both literally translating to \"the suns origin\"." }, { "id": 105, - "question": "Is there a play ground in Europe ?Name the Play Ground of Europe", - "answer": "SWITZERLAND", + "question": "What's known as the \"Playground of Europe\"?", + "answer": "Switzerland", "info": "It comes from the title of a book written in 1870 by Leslie Stephen (father of Virginia Woolf) detailing his exploits of mountain climbing (not skiing) of which sport he was one of the pioneers and trekking or walking." }, { "id": 106, - "question": "Have you been struck by Thunder ? If not your very lucky but this place has gone through lot of large violent thunderstorms, called the Land Of Thunderbolt, name it.", - "answer": "Bhutan", - "info": "Bhutan is called Land of Thunder Dragon. Because of the violent and large thunderstorms that whip down through the valleys from the Himalayas, Bhutan is known as the Land of Thunderbolt. The sparkling light of thunderbolts were believed to be red fire of a dragon." + "question": "Which country is known as the \"Land of Thunderbolt\"?", + "info": "\"Bhutan is known as the \\\"Land of Thunder Dragon\\\" or \\\"Land of Thunderbolt\\\" due to the violent and large thunderstorms that whip down through the valleys from the Himalayas. The dragon reference was due to people thinking the sparkling light of thunderbolts was the red fire of a dragon.\"" }, { "id": 107, - "question": "Largest producer of tea in the world?", + "question": "Which country is the largest producer of coffee?", "answer": "China", "info": "Tea is mainly grown in Asia, Africa, South America, and around the Black and Caspian Seas. The four biggest tea-producing countries today are China, India, Sri Lanka and Kenya. Together they represent 75% of world production." }, { "id": 108, - "question": "Remind me the largest producer of Coffee ?", + "question": "Which country is the largest producer of tea in the world?", "answer": "Brazil", "info": "Brazil is the world's largest coffee producer. In 2016, Brazil produced a staggering 2,595,000 metric tons of coffee beans. It is not a new development, as Brazil has been the highest global producer of coffee beans for over 150 years." }, { "id": 109, - "question": "Mount Etna, one of the active volcano, where is it located?", + "question": "Which country is Mount Etna, one of the most active volcanoes in the world, located?", "answer": "Italy", - "info": "Mount Etna is the highest and most active volcano in Europe. Towering above the city of Catania on the island of Sicily, it has been growing for about 500,000 years and is in the midst of a series of eruptions that began in 2001.It is also possible to visit Mount Etna independently, but the advantages of a guided excursion are very numerous. Mount Etna is on of the highest volcano in Europe and on of the most active in the world. The volcano shaped the Sicilian history and landscape and still affects the island today." + "info": "Mount Etna is the highest volcano in Europe. Towering above the city of Catania on the island of Sicily, it has been growing for about 500,000 years and is in the midst of a series of eruptions that began in 2001." }, { "id": 110, - "question": "Which country is called Battleground of Europe?", + "question": "Which country is called \"Battleground of Europe?\"", "answer": "Belgium", - "info": "Belgium has been the battleground of Europe since the Roman Empire… Belgium was the battleground of Europe for centuries as it had no natural protection from its big neighboring countries. ... The battles of Oudenaarde, Ramillies, Waterloo, Ypres and Bastogne were all fought on Belgian soil." + "info": "Belgium has been the \"Battleground of Europe\" since the Roman Empire as it had no natural protection from its larger neighbouring countries. The battles of Oudenaarde, Ramillies, Waterloo, Ypres and Bastogne were all fought on Belgian soil." }, { "id": 111, - "question": "Largest tropical rain forest in the world?", + "question": "Which is the largest tropical rain forest in the world?", "answer": "Amazon", - "info": "The Amazon is regarded as vital in the fight against global warming due to its ability to absorb carbon from the air. It's often referred to as the “lungs of the Earth,” as more than 20 per cent of the world's oxygen is produced there." + "info": "The Amazon is regarded as vital in the fight against global warming due to its ability to absorb carbon from the air. It's often referred to as the \"lungs of the Earth,\" as more than 20 per cent of the world's oxygen is produced there." }, { "id": 112, - "question": "Do you know the biggest Island in the World ?", + "question": "Which is the largest island in the world?", "answer": "Greenland", - "info": "" + "info": "Commonly thought to be Australia, but as it's actually a continental landmass, it doesn't get to make it in the list." }, { "id": 113, - "question": "Give me the name of the tallest waterfall in the world.", + "question": "What's the name of the tallest waterfall in the world.", "answer": "Angel", "info": "Angel Falls (Salto Ángel) in Venezuela is the highest waterfall in the world. The falls are 3230 feet in height, with an uninterrupted drop of 2647 feet. Angel Falls is located on a tributary of the Rio Caroni." }, { "id": 114, - "question": "Have you seen white elephants? If not then there is a place called Land of White Elephants, does anyone know the place?", + "question": "What country is called \"Land of White Elephants\"?", "answer": "Thailand", "info": "White elephants were regarded to be holy creatures in ancient Thailand and some other countries. Today, white elephants are still used as a symbol of divine and royal power in the country. Ownership of a white elephant symbolizes wealth, success, royalty, political power, wisdom, and prosperity." }, { "id": 115, - "question": "How many continents have you been to? Maybe you can visit 2 at once, name the city of two continents.", + "question": "Which city is in two continents?", "answer": "Istanbul", "info": "Istanbul embraces two continents, one arm reaching out to Asia, the other to Europe." }, { "id": 116, - "question": "the Vally Of The Kings is located in the country...?", + "question": "The Vally Of The Kings is located in which country?", "answer": "Egypt", "info": "The Valley of the Kings, also known as the Valley of the Gates of the Kings, is a valley in Egypt where, for a period of nearly 500 years from the 16th to 11th century BC, rock cut tombs were excavated for the pharaohs and powerful nobles of the New Kingdom (the Eighteenth to the Twentieth Dynasties of Ancient Egypt)." }, { "id": 117, - "question": "Diamonds are always nice in Minecraft, but did you know that there is a \"Diamond Capital in the World?\" can anyone name it?", + "question": "Diamonds are always nice in Minecraft, but can you name the \"Diamond Capital in the World\"?", "answer": "Antwerp", "info": "Antwerp, Belgium is where 60-80% of the world's diamonds are cut and traded, and is known as the \"Diamond Capital of the World.\"" }, @@ -154,7 +153,7 @@ }, { "id": 120, - "question": "The world's largest coral reef system \"Great Barrier Reef\" is located in?", + "question": "What country is the world's largest coral reef system, the \"Great Barrier Reef\", located in?", "answer": "Australia", "info": "The Great Barrier Reef is the world's largest coral reef system composed of over 2,900 individual reefs and 900 islands stretching for over 2,300 kilometres (1,400 mi) over an area of approximately 344,400 square kilometres (133,000 sq mi). The reef is located in the Coral Sea, off the coast of Queensland, Australia." }, @@ -166,88 +165,57 @@ }, { "id": 122, - "question": "Which is the only mammal that can’t jump?", - "answer": "elephant", - "info": "It is true that adult elephants can't jump. But there are other mammals that can't either, like sloths, hippos and rhinos. Although, unlike elephants, hippos and rhinos can have all four feet off the ground at the same time when they run." - + "question": "Which is the largest desert in the world (exclude cold deserts.) ?", + "answer": "Sahara", + "info": "The Sahara Desert covers 3.6 million square miles. It is almost the same size as the United States or China. There are sand dunes in the Sahara as tall as 590 feet." }, { "id": 123, "question": "Who lived at 221B, Baker Street, London?", "answer": "Sherlock Holmes", - "info": "You guys know this very well, xD." - + "info": "" }, { "id": 124, "question": "When did the Second World War end?", "answer": "1945", "info": "World War 2 ended with the unconditional surrender of the Axis powers. On 8 May 1945, the Allies accepted Germany's surrender, about a week after Adolf Hitler had committed suicide. VE Day – Victory in Europe celebrates the end of the Second World War on 8 May 1945." - }, { "id": 125, - "question": "Name the largest Dam in the World", + "question": "What is the name of the largest Dam in the world?", "answer": "Three Gorges Dam", "info": "At 1.4 miles wide (2.3 kilometers) and 630 feet (192 meters) high, Three Gorges Dam is the largest hydroelectric dam in the world, according to International Water Power & Dam Construction magazine. Three Gorges impounds the Yangtze River about 1,000 miles (1,610 km) west of Shanghai." - }, { "id": 126, - "question": "Name the largest river in the World.", + "question": "What's the name of the largest river in the world?", "answer": "Nile", "info": "The Nile, which is about 6,650 km (4,130 mi) long, is an \"international\" river as its drainage basin covers eleven countries, namely, Tanzania, Uganda, Rwanda, Burundi, the Democratic Republic of the Congo, Kenya, Ethiopia, Eritrea, South Sudan, Republic of the Sudan and Egypt." - }, { "id": 127, - "question": "Which is the smallest planet in the Solar System? Earth?", + "question": "Which is the smallest planet in the Solar System?", "answer": "Mercury", "info": "Mercury is the smallest planet in our solar system. It's just a little bigger than Earth's moon. It is the closest planet to the sun, but it's actually not the hottest. Venus is hotter." - }, { "id": 128, - "question": "Is your country the smallest? Well it is if it is this perticular place, name the smallest country.", - "answer": "Vatican city", + "question": "What is the smallest country?", + "answer": "Vatican City", "info": "With an area of 0.17 square miles (0.44 km2) and a population right around 1,000, Vatican City is the smallest country in the world, both in terms of size and population." - }, { "id": 129, - "question": "Have you seen the largest bird? If so then name it.", + "question": "What's the name of the largest bird?", "answer": "Ostrich", "info": "The largest living bird, a member of the Struthioniformes, is the ostrich (Struthio camelus), from the plains of Africa and Arabia. A large male ostrich can reach a height of 2.8 metres (9.2 feet) and weigh over 156 kilograms (344 pounds)." - }, { "id": 130, "question": "Expand GPRS", "answer": "General Packet Radio Service", "info": "General Packet Radio Service (GPRS) is a packet-based mobile data service on the global system for mobile communications (GSM) of 3G and 2G cellular communication systems. It is a non-voice, high-speed and useful packet-switching technology intended for GSM networks." - - }, - { - "id": 120, - "question": "", - "answer": "", - "info": "" - - }, - { - "id": 120, - "question": "", - "answer": "", - "info": "" - - }, - { - "id": 120, - "question": "", - "answer": "", - "info": "" - } - ] } diff --git a/bot/seasons/evergreen/trivia_quiz.py b/bot/seasons/evergreen/trivia_quiz.py index ac72ed95..c7778c88 100644 --- a/bot/seasons/evergreen/trivia_quiz.py +++ b/bot/seasons/evergreen/trivia_quiz.py @@ -30,9 +30,10 @@ class TriviaQuiz(commands.Cog): self.questions = self.load_questions() self.game_status = {} self.game_owners = {} - self.question_limit = 3 + self.question_limit = 4 + self.player_dict = {} self.categories = { - "general": "Test your general knwoledge" + "general": "Test your general knowledge" # "retro": "Questions related to retro gaming." } @@ -44,8 +45,8 @@ class TriviaQuiz(commands.Cog): questions = json.load(json_data) return questions - @commands.command(name="quiz") - async def quiz_game(self, ctx: commands.Context, option: str, category: str = "general") -> None: + @commands.command(name="quiz", aliases=["trivia", "tquiz"]) + async def quiz_game(self, ctx: commands.Context, category: str = "general") -> None: """ Start/Stop a quiz! @@ -59,42 +60,36 @@ class TriviaQuiz(commands.Cog): (we wil be adding more later) """ category = category.lower() - player_data = {} # a dict to store players and their points. + # player_data = {} # a dict to store players and their points. if ctx.channel.id not in self.game_status: - self.game_status[ctx.channel.id] = None - - if option == "start": - if self.game_status[ctx.channel.id] is True: - await ctx.send("Game already running.") - return - else: - self.game_owners[ctx.channel.id] = ctx.author - self.game_status[ctx.channel.id] = True - 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.set_footer( - text="Points for that question reduces by 25 after 10s.Total time is 30s per question" - ) - await ctx.send(embed=start_embed) # send an embed with the rules - await asyncio.sleep(1) - - elif option == "stop": - if self.game_status[ctx.channel.id] is False: - await ctx.send("No game running, nothing to stop here.") - return + self.game_status[ctx.channel.id] = False + self.player_dict[ctx.channel.id] = {} + + 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 = 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.set_footer( + text="Points for a question reduces by 25 after 10s or after a hint.Total time is 30s per question" + ) + await ctx.send(embed=start_embed) # send an embed with the rules + await asyncio.sleep(1) + + else: + if ( + ctx.author == self.game_owners[ctx.channel.id] + or Roles.moderator in [role.id for role in ctx.author.roles] + ): + await ctx.send("Quiz is no longer running.") + await self.declare_winner(ctx.channel, self.player_dict[ctx.channel.id]) + self.game_status[ctx.channel.id] = False + del self.game_owners[ctx.channel.id] else: - if ( - ctx.author == self.game_owners[ctx.channel.id] - or Roles.moderator in [role.id for role in ctx.author.roles] - ): - await self.declare_winner(ctx.channel, player_data) - self.game_status[ctx.channel.id] = False - del self.game_owners[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: !") if category not in self.categories: embed = self.category_embed @@ -106,15 +101,14 @@ class TriviaQuiz(commands.Cog): done_question = [] hint_no = 0 answer = None - hints = None - while self.game_status[ctx.channel.id] is True: + while self.game_status[ctx.channel.id]: if len(done_question) > self.question_limit and hint_no == 0: await ctx.send("The round ends here.") - await self.declare_winner(ctx.channel, player_data) + await self.declare_winner(ctx.channel, self.player_dict[ctx.channel.id]) break if unanswered > 3: await ctx.send("Game stopped due to inactivity.") - await self.declare_winner(ctx.channel, player_data) + await self.declare_winner(ctx.channel, self.player_dict[ctx.channel.id]) break if hint_no == 0: while True: @@ -132,42 +126,43 @@ class TriviaQuiz(commands.Cog): def check(m: discord.Message) -> bool: ratio = fuzz.ratio(answer.lower(), m.content.lower()) - return ratio > 80 and m.channel == ctx.channel + return ratio > 85 and m.channel == ctx.channel try: msg = await self.bot.wait_for('message', check=check, timeout=10) - except Exception as e: + except asyncio.TimeoutError: if self.game_status[ctx.channel.id] is False: break - if isinstance(e, asyncio.TimeoutError): - 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]}") - else: - await ctx.send(f"Cmon guys, {30-hint_no*10}s left!") - + 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]}") else: - response = random.choice(WRONG_ANS_RESPONSE) - expression = random.choice(ANNOYED_EXPRESSIONS) - await ctx.send(f"{response} {expression}") - await self.send_answer(ctx.channel, question_dict) - await asyncio.sleep(1) - hint_no = 0 - unanswered += 1 - await self.send_score(ctx.channel, player_data) + await ctx.send(f"Cmon guys, {30-hint_no*10}s left!") + + else: + response = random.choice(WRONG_ANS_RESPONSE) + expression = random.choice(ANNOYED_EXPRESSIONS) + await ctx.send(f"{response} {expression}") + await self.send_answer(ctx.channel, question_dict) + await asyncio.sleep(1) + hint_no = 0 + unanswered += 1 + await self.send_score(ctx.channel, self.player_dict[ctx.channel.id]) + await asyncio.sleep(2) else: points = 100 - 25*hint_no - if msg.author in player_data: - player_data[msg.author] += points + if msg.author in self.player_dict[ctx.channel.id]: + self.player_dict[ctx.channel.id][msg.author] += points else: - player_data[msg.author] = points + self.player_dict[ctx.channel.id][msg.author] = points hint_no = 0 unanswered = 0 await ctx.send(f"{msg.author.mention} got the correct answer :tada: {points} points for ya.") await self.send_answer(ctx.channel, question_dict) - await self.send_score(ctx.channel, player_data) + await self.send_score(ctx.channel, self.player_dict[ctx.channel.id]) + await asyncio.sleep(2) @staticmethod async def send_score(channel: discord.TextChannel, player_data: dict) -> None: @@ -181,13 +176,14 @@ class TriviaQuiz(commands.Cog): @staticmethod async def declare_winner(channel: discord.TextChannel, player_data: dict) -> None: - """A function declare the winner of the quiz.""" + """Announce the winner of the quiz in the game channel.""" if player_data: highest_points = max(list(player_data.values())) no_of_winners = list(player_data.values()).count(highest_points) # 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() for _ in range(no_of_winners): @@ -199,17 +195,18 @@ class TriviaQuiz(commands.Cog): winners_mention += f"{winner.mention} " 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"Congratz {winners_mention} :tada: " - f"You have won this quiz game with a grand total of {highest_points} points!!" + f"{word} have won this quiz game with a grand total of {highest_points} points!!" ) @property def category_embed(self) -> discord.Embed: - """A function which returns an embed showing all avilable categories.""" + """Build an embed showing all available trivia categories.""" embed = discord.Embed(colour=discord.Colour.blue()) embed.title = "The available question categories are:" embed.description = "" @@ -220,19 +217,19 @@ class TriviaQuiz(commands.Cog): @staticmethod async def send_answer(channel: discord.TextChannel, question_dict: dict) -> None: - """A function that sends the answer.""" + """Send the correct the 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 != "": - embed.description += f"**Information**\n{info}\n" - embed.description += "Lets move to the next question." + embed.description += f"**Information**\n{info}\n\n" + embed.description += "Lets move to the next question.\nRemaining questions: " await channel.send(embed=embed) def setup(bot: commands.Bot) -> None: """Loading the cog.""" bot.add_cog(TriviaQuiz(bot)) - logger.debug("TriviaQuiz cog loaded!") + logger.debug("TriviaQuiz cog loaded") |