· 4 years ago · Jun 02, 2021, 10:46 AM
1# Imports
2import random # Used to generate a random category
3import requests # Used to request the API
4import json # Used to extract information from the API
5import time # Used to keep track of time
6import math # Used to calculate the bonus points
7
8def introduction():
9 print("Welcome to the Trivia Game!")
10 print()
11 global noInternet
12 while True:
13 noInternet = input("Enter 'Y' or 'N', would you like to play offline? ")
14 if noInternet == "Y":
15 offline()
16 break
17 elif noInternet == "N":
18 category()
19 extract()
20 break
21
22def category():
23 print("Please choose a category:")
24 print()
25 print("Enter '1' for Sports")
26 print("Enter '2' for General Knowledge")
27 print("Enter '3' for Geography")
28 print("Enter '4' for History")
29 print("Enter '5' for Animals")
30 print("Enter '6' for Random")
31 print("Enter '7' for Create Your Own")
32 print()
33
34 # Category choice
35 global choice, genre
36 choice = input("Your choice is: ")
37 print()
38
39 # Chooses a random category
40 if choice == "6":
41 num = random.randint(1, 5)
42 choice = str(num)
43
44 # If the user wants to create their own
45 if choice == "7":
46 userCreated()
47 return
48
49 # Prints the chosen category
50 genre = "Sports" if choice == "1" else "General Knowledge" if choice == "2" else "Geography" if choice == "3" else "History" if choice == "4" else "Animals"
51 print("Your category is ... " + genre)
52
53def extract():
54 global extracted
55 # Requests and extracts information from the API based on the category
56 if choice == "1":
57 info = requests.get("https://opentdb.com/api.php?amount=50&category=21")
58 extracted = info.json()
59 elif choice == "2":
60 info = requests.get("https://opentdb.com/api.php?amount=50&category=9")
61 extracted = info.json()
62 elif choice == "3":
63 info = requests.get("https://opentdb.com/api.php?amount=50&category=22")
64 extracted = info.json()
65 elif choice == "4":
66 info = requests.get("https://opentdb.com/api.php?amount=50&category=23")
67 extracted = info.json()
68 else:
69 info = requests.get("https://opentdb.com/api.php?amount=50&category=27")
70 extracted = info.json()
71
72def offline ():
73 print("Please choose a category:")
74 print()
75 print("Enter '1' for Sports")
76 print("Enter '2' for General Knowledge")
77 print("Enter '3' for Geography")
78 print("Enter '4' for Create Your Own")
79 print()
80
81 global choice, genre
82 choice = input("Your choice is: ")
83 print()
84
85 # If the user wants to create their own
86 if choice == "4":
87 userCreated()
88 return
89
90 # Prints the chosen category
91 genre = "Sports" if choice == "1" else "General Knowledge" if choice == "2" else "Geography"
92 print("Your category is ... " + genre)
93 print()
94
95 # Questions and answers
96 sports = {"In golf, what name is given to a hole score of two under par?": "Eagle",
97 "Which team won the 2015-16 English Premier League?": "Leicester City",
98 "How many scoring zones are there on a conventional dart board?": "82",
99 "In a game of snooker, what colour ball is worth 3 points?": "Green",
100 "In baseball, how many fouls are an out?": "0",
101 "What is the highest belt you can get in Taekwondo?": "Black",
102 "Which country will host the 2020 Summer Olympics?": "Japan",
103 "Which country has hosted the 2018 FIFA World Cup?": "Russia",
104 "Who won the 2015 Formula 1 World Championship?": "Lewis Hamilton",
105 "Which team was the 2015-2016 NBA Champions?": "Cleveland Cavaliers"}
106 generalKnowledge = {"Which company did Valve cooperate with in the creation of the Vive?": "HTC",
107 "When was the Declaration of Independence approved by the Second Continental Congress?": "July 4, 1776",
108 "In the video-game franchise Kingdom Hearts, the main protagonist, carries a weapon with what shape?": "Key",
109 "What is the defining characteristic of someone who is described as hirsute?": "Hairy",
110 "A doctor with a PhD is a doctor of what?": "Philosophy",
111 "Which sign of the zodiac is represented by the Crab?": "Cancer",
112 "What geometric shape is generally used for stop signs?": "Octagon",
113 "There are 86400 seconds in a day.": "True",
114 "How many colors are there in a rainbow?" : "7",
115 "Which film star has his statue in Leicester Square?": "Charlie Chaplin"}
116 geography = {"In which city, is the Big Nickel located in Canada?":"Sudbury, Ontario",
117 "Which country inside the United Kingdom does NOT appear on its flag, the Union Jack?":"Wales",
118 "Suriname is NOT a part of the Asian continent.":"True",
119 "Barbados is not located in the Caribbean":"False",
120 "The surface area of Russia is slightly larger than that of the dwarf planet Pluto.":"True",
121 "France borders Austria.":"False",
122 "What is the largest city in Morocco?":"Casablanca",
123 "What country is completely landlocked by South Africa?":"Lesotho",
124 "Israel is 7 hours ahead of New York.":"True",
125 "Alaska is the largest state in the United States.":"True"}
126
127 global points
128 points = 0 # Total number of points
129 bamboozled = 0 # Total times the user took longer than 10 seconds
130 trivia = sports if genre == "Sports" else generalKnowledge if genre == "General Knowledge" else geography
131
132 # Loops through the questions
133 for i in trivia:
134
135 start = time.time()
136 print()
137 answer = input(i + " ")
138 end = time.time()
139 totalTime = end - start
140
141 # If the answer is correct
142 if answer == trivia[i]:
143
144 # If the user took less than 10 seconds
145 if totalTime < 10:
146 bonus = 10 - math.floor(totalTime) # Calculates the bonus points
147 points = points + 10 + bonus # Calculates the total points
148
149 # If the user took 10 seconds or longer
150 else:
151 bamboozled += 1 # Increased the number of bamboolzed times by 1
152 points += 10 # Calculates the total points
153
154 # Prints message
155 print("Correct! Your total points are: " + str(points))
156
157 # If the answer is wrong
158 else:
159
160 # If the user took 10 seconds or longer
161 if totalTime >= 10:
162 bamboozled += 1 # Increased the number of bamboolzed times by 1
163
164 # Prints message
165 print("False! The correct answer is: " + trivia[i] + ". Your total points are: " + str(points))
166
167 # Ends the game if the user has been bamboozled
168 if bamboozled == 3:
169 print("Sorry, you took 10 seconds or longer for 3 questions. The game is over.")
170 break
171
172# Function for user to add and delete their own questions
173# Might need to add editing option better
174def userCreated():
175 user = {}
176 decision = input("Would you like to 'ADD' or 'DELETE' a category? ")
177 print()
178
179 if decision == "ADD":
180 genre = input("Which category would you like to add? ")
181 print()
182 numQuestions = int(input("How many questions would you like to add? "))
183 print()
184 qAndA = {}
185
186 for i in range(numQuestions):
187 question = input("What is the question? ")
188 answer = input("What is the answer? ")
189 print()
190 qAndA[question] = answer
191
192 user[genre] = qAndA
193 delete = input("Enter 'Y' or 'N', would you like to delete a question? ")
194
195 # If the user wants to delete
196 if delete == "Y":
197 question = input("Enter the question you wish to delete: ")
198 qAndA.pop(question)
199 # Prints message
200 print("Correct! Your total points are: " + str(points))
201
202 # If the answer is wrong
203 else:
204
205 # If the user took 10 seconds or longer
206 if totalTime >= 10:
207 bamboozled += 1 # Increased the number of bamboolzed times by 1
208
209 # Prints message
210 print("False! The correct answer is: " + qAndA[i] + ". Your total points are: " + str(points))
211
212 else:
213 print("Thank you for adding this genre.")
214 else:
215 genre = input("Which genre would you like to delete? ")
216 user.pop(genre)
217
218
219def game():
220 global points
221 total = 0 # Total number of questions
222 points = 0 # Total number of points
223 bamboozled = 0 # Total times the user took longer than 10 seconds
224
225 # Loops through the API
226 for data in extracted["results"]:
227
228 # Checks for problematic questions and skips them
229 if "&" not in data["question"] and ";" not in data["question"] and "#" not in data["question"] and "following" not in data["question"] and "Which" not in data["question"] and total != 10 and bamboozled < 3:
230
231 total += 1 # Total number of questions increased by 1
232 question = data["question"] # Gets the question from the API
233 start = time.time() # Start time
234 print()
235 answer = input(question + " ") # Gets the answer from the user
236 end = time.time() # End time
237 totalTime = end - start # Calculates total time
238 print()
239
240 # If the answer is correct
241 if answer == data["correct_answer"]:
242
243 # If the user took less than 10 seconds
244 if totalTime < 10:
245 bonus = 10 - math.floor(totalTime) # Calculates the bonus points
246 points = points + 10 + bonus # Calculates the total points
247
248 # If the user took 10 seconds or longer
249 else:
250 bamboozled += 1 # Increased the number of bamboolzed times by 1
251 points += 10 # Calculates the total points
252
253 # Prints message
254 print("Correct! Your total points are: " + str(points))
255
256
257def main():
258 introduction()
259 leaderboard()
260
261 global cont
262
263 # Asks the user to play again
264 while True:
265 print()
266 again = input("Enter 'Y' or 'N', would you like to play again? ")
267 print()
268 if again == "Y":
269 cont = True
270 break
271 elif again == "N":
272 cont = False
273 break
274
275# Runs until user says otherwise
276main()
277while cont:
278 main()