This repository was archived by the owner on May 30, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgame.py
1593 lines (1280 loc) · 63.8 KB
/
game.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# - - - - - - - Imports - - - - - - -#
import os
import threading
import time
import html
import random
from Maxs_Modules.files import SaveFile, load_questions_from_file, UserData
from Maxs_Modules.network import get_ip, QuizGameServer, QuizGameClient, get_free_port
from Maxs_Modules.tools import try_convert, set_if_none, string_bool, sort_multi_array
from Maxs_Modules.debug import debug_message, error
from Maxs_Modules.renderer import Menu, Colour, print_text_on_same_line, clear, render_text, get_input, \
render_header, render_quiz_header, round_to_decimal
# - - - - - - - Variables - - - - - - -#
GAME_STORED_LOCATION = "UserData/Games/"
CATEGORY_OFFSET_API = 9
MAX_NUMBER_OF_QUESTIONS = 50
quiz_categories = ("General Knowledge", "Books", "Film", "Music", "Musicals & Theatres", "Television", "Video Games",
"Board Games", "Science & Nature", "Computers", "Mathematics", "Mythology", "Sports", "Geography",
"History", "Politics", "Art", "Celebrities", "Animals", "Vehicles", "Comics", "Gadgets",
"Japanese Anime & Manga", "Cartoon & Animations")
HOST_SERVER_BY_DEFAULT = False
MAX_NUMBER_OF_PLAYERS = 10
# - - - - - - - Functions - - - - - - -#
def generate_new_save_file():
"""
Generates a new save file name by searching through the data folder for a name that is not already taken in the
format of "Game_0.json" (where 0 is the number of the save file). If more than 1000 save files are found, then an
exception is raised to prevent infinite looping as most likely something has gone wrong.
@return: The name of the save file
"""
# Get all the save files
already_saved = get_saved_games()
# Create a name for the save file
name = "Game_"
name_index = 0
save_name = name + str(name_index) + ".json"
# Check if the save file already exists
while save_name in already_saved:
name_index += 1
save_name = name + str(name_index) + ".json"
# If there is more than 1000 save files, then something probably went wrong
if name_index > 1000:
raise Exception("Could not find a save file name")
return save_name
def get_saved_games():
"""
Gets a list of all the saved games (note this returns a list of all JSON files in the data folder and if a user
has tampered with the data folder, a JSON file that isn't a save file may be returned)
@return: A list of all the saved games
"""
# Get a list of all the files in the data folder
files = os.listdir(GAME_STORED_LOCATION)
debug_message("Files in data folder: " + str(files), "Game")
# Remove all the files that are not .json files
for file in files:
if not file.endswith(".json"):
files.remove(file)
# Return the files
return files
# - - - - - - - Classes - - - - - - -#
class Question:
category = None
question_type = None
difficulty = None
question = None
correct_answer = None
incorrect_answers = None
def __init__(self) -> None:
pass
# Note uses the string representation of Question class as it has not been defined therefore cant use it in type the
# hints
def load(self, data: dict) -> "Question":
"""
Takes a dictionary of data and loads it into the question object. The data is also html character unescaped
when loaded
@param data: The dict to load the data from. Needs to have the following keys: category, type, difficulty,
question, correct_answer, incorrect_answers
@return: The question object
"""
self.category = data.get("category")
self.question_type = data.get("type")
self.difficulty = data.get("difficulty")
self.question = html.unescape(data.get("question"))
self.correct_answer = html.unescape(data.get("correct_answer"))
self.incorrect_answers = data.get("incorrect_answers")
# Unescape the incorrect answers
for answer_index in range(len(self.incorrect_answers)):
self.incorrect_answers[answer_index] = html.unescape(self.incorrect_answers[answer_index])
return self
class User:
# Game Variables
player_type = "User"
name = None
colour = None
icon = None
points = 0
correct = 0
incorrect = 0
streak = 0
highest_streak = 0
questions_missed = 0
answers = []
times = []
# Calculated Stats
questions_answered = 0
average_time = 0
average_time_correct = 0
average_time_incorrect = 0
average_time_missed = 0
accuracy = 0
# States
is_host = False
is_connected = False
has_answered = False
def __int__(self, name: str, colour: str, icon: str) -> None:
"""
Creates a new user
@param name: The name of the user
@param colour: The colour of the user
@param icon: The path to the icon of the user
"""
self.name = name
self.colour = colour
self.icon = icon
def load(self, data: dict) -> None:
"""
Loads the data from a dictionary into the user object, if the data is None, then the default value is used.
@param data: A dictionary of data to load into the user object. May contain the following keys: name, colour,
icon, points, correct, incorrect, streak, highest_streak, questions_missed, answers, times, has_answered
"""
# Game Variables
self.name = data.get("name")
self.colour = data.get("colour")
self.icon = data.get("icon")
self.points = data.get("points")
self.correct = data.get("correct")
self.incorrect = data.get("incorrect")
self.streak = data.get("streak")
self.highest_streak = data.get("highest_streak")
self.questions_missed = data.get("questions_missed")
self.answers = data.get("answers")
self.times = data.get("times")
# States
self.has_answered = data.get("has_answered")
self.load_defaults()
def load_defaults(self) -> None:
"""
Loads the default values for the user, should any of the values be None.
"""
self.name = set_if_none(self.name, "Player")
self.colour = set_if_none(self.colour, Colour.WHITE)
self.icon = set_if_none(self.icon, "X")
self.points = set_if_none(self.points, 0)
self.correct = set_if_none(self.correct, 0)
self.incorrect = set_if_none(self.incorrect, 0)
self.streak = set_if_none(self.streak, 0)
self.highest_streak = set_if_none(self.highest_streak, 0)
self.questions_missed = set_if_none(self.questions_missed, 0)
self.answers = set_if_none(self.answers, [])
self.times = set_if_none(self.times, [])
# States
self.has_answered = set_if_none(self.has_answered, False)
def calculate_stats(self) -> None:
"""
Calculates the stats for the user, this saves time as the stats only need to be calculated when the user selects
to display them. The stats are stored in the following variables: questions_answered, accuracy, average_time,
average_time_correct, average_time_incorrect, average_time_missed
"""
# Simple stats
self.questions_answered = self.correct + self.incorrect
# Dont divide by 0
if self.questions_answered != 0:
self.accuracy = self.correct / self.questions_answered
# Add all the times together and then divide by the length to get the mean
if len(self.times) != 0:
self.average_time = sum(self.times) / len(self.times)
# Loop through the answers and times and calculate the average time for correct and incorrect answers
time_correct = []
time_incorrect = []
time_missed = []
for i in range(len(self.answers)):
if self.answers[i] == "Correct":
time_correct.append(self.times[i])
elif self.answers[i] == "Incorrect":
time_incorrect.append(self.times[i])
elif self.answers[i] == "Missed_Correct" or self.answers[i] == "Missed_Incorrect":
time_missed.append(self.times[i])
# Calculate the average time for correct incorrect and missed answers (skip if zero as that causes a divide by
# zero error)
if len(time_correct) != 0:
self.average_time_correct = sum(time_correct) / len(time_correct)
if len(time_incorrect) != 0:
self.average_time_incorrect = sum(time_incorrect) / len(time_incorrect)
if len(time_missed) != 0:
self.average_time_missed = sum(time_missed) / len(time_missed)
def show_stats(self) -> None:
"""
Calculates and then prints the stats for the user.
"""
# Calculate any stats that aren't just supplied by the game
self.calculate_stats()
# Print the stats
render_text(self.styled_name() + "'s Stats: ")
render_text("Type: " + self.player_type)
render_text("Score: " + str(round_to_decimal(self.points)))
render_text("Streak: " + str(self.streak))
render_text("Highest Streak: " + str(self.highest_streak))
render_text("Questions Answered: " + str(self.questions_answered))
render_text("Questions Correct: " + str(self.correct))
render_text("Questions Incorrect: " + str(self.incorrect))
render_text("Questions Skipped: " + str(self.questions_missed))
render_text("Average Time: " + str(round_to_decimal(self.average_time)))
render_text("Average Time Correct: " + str(round_to_decimal(self.average_time_correct)))
render_text("Average Time Incorrect: " + str(round_to_decimal(self.average_time_incorrect)))
render_text("Average Time Skipped: " + str(round_to_decimal(self.average_time_missed)))
render_text("Accuracy: " + str(self.accuracy * 100) + "%")
def reset(self) -> None:
"""
Removes all the set answers, 0s out the points, correct, incorrect, steak, questions_missed variables. Name,
icon and colour are kept.
"""
# Clear the arrays
self.answers.clear()
self.times.clear()
# Zero out the vars
self.points = 0
self.correct = 0
self.incorrect = 0
self.streak = 0
self.questions_missed = 0
# An alternative way to do this is to None the vars and then call load_defaults()
def styled_name(self) -> str:
"""
Returns the name of the user with the colour (includes reset char)
@return: The name of the user with the colour (includes reset char)
"""
return self.colour + self.name + Colour.RESET
class Bot(User):
accuracy = 0.5
def __int__(self, name: str, colour: str, icon: str, accuracy: float) -> None:
"""
Creates a new bot and assigns it a name, colour and icon
@param name: The name of the bot
@param colour: The colour of the bot
@param icon: The path to the icon of the bot
@param accuracy: How likely the bot is to get the question correct
"""
self.accuracy = accuracy
# Set up the user
super().__int__(name, colour, icon)
def load(self, data: dict) -> None:
"""
Loads the data from the dictionary into the bot using the function provided by the User class with the added
variable of accuracy. The defaults are then loaded.
@param data: The dictionary containing the data to load, should contain the same keys as the User.load()
function with an added accuracy key
"""
super().load(data)
self.accuracy = data.get("accuracy")
self.load_defaults()
def load_defaults(self) -> None:
"""
Loads the default values for the bot, the defaults are the same as the User class with the addition of a
default accuracy of 0.5 (50%). Also sets the player_type to "Bot"
"""
super().load_defaults()
self.accuracy = set_if_none(self.accuracy, 0.5)
self.player_type = "Bot"
def show_stats(self) -> None:
"""
Prints the collected stats variables to the console. The actual accuracy is printed and the expected accuracy
is also printed.
"""
# Ensure that calculations don't mess with accuracy
save_accuracy = self.accuracy
# Calculate the stats
super().show_stats()
# Reset the accuracy
self.accuracy = save_accuracy
# Print the stats
render_text("Accuracy (EXPECTED): " + str(self.accuracy * 100) + "%")
def answer(self, question: Question) -> str:
"""
Using the accuracy, the bot will return the correct answer if random.random() is less than the accuracy,
otherwise it will return a random incorrect answer
@param question: The question object where the bot should get its answer from
@return: The answer the bot chose
"""
# Check if the bot got the question correct
correct = random.random() < self.accuracy
if correct:
return question.correct_answer
else:
return random.choice(question.incorrect_answers)
class Game(SaveFile):
# User Chosen Settings
host_a_server = None
time_limit = None
show_score_after_question_or_game = None
show_correct_answer_after_question_or_game = None
points_for_correct_answer = None
points_for_incorrect_answer = None
points_for_no_answer = None
points_multiplier_for_a_streak = None
points_multiplier_for_a_streak_base = None
randomise_questions = None
randomise_answer_placement = None
pick_random_question = None
bot_difficulty = None
server_name = None
server_port = None
max_players = None
how_many_players = None
how_many_bots = None
quiz_category = None
quiz_difficulty = None
question_amount = None
question_type = None
# State Settings
current_question = None
current_user_playing = None
current_user_playing_net_name = None
online_enabled = None
game_finished = None
joined_game = None
game_started = False
game_loaded = False
cancelled = False
# API Conversion
api_category = None
api_type = None
# Game data
users = None
questions = None
bots = None
backend = None
server_thread = None
user_reference = User
bot_reference = Bot
def __init__(self, quiz_save: str = None) -> None:
"""
Creates a new game. If the quiz_save is not none, then load the quiz save because the user wants to continue a
game otherwise generate a new save file. After the save file is loaded, the default settings are set and then
converted into their relevant classes.
@param quiz_save: The name of the save file to load, if none then a new save file will be generated. (Default:
None)
"""
# Call the super class and pass the save file name, this will automatically load the settings
# If the quiz save is not none, then load the quiz save because the user wants to continue a game otherwise
# generate a new save file
if quiz_save is not None:
super().__init__(GAME_STORED_LOCATION + quiz_save)
self.game_loaded = True
else:
super().__init__(GAME_STORED_LOCATION + generate_new_save_file())
# Set the online enabled variable, note it is not saved because the online state can change between runs
usersettings = UserData()
self.online_enabled = usersettings.network
# Load the save data into variables
self.load_from_saved()
# Set the default settings if the settings are none
self.set_settings_default()
# Convert everything back
self.convert_all_from_save_data()
def load_from_saved(self) -> None:
"""
Loads the game's variables from the saved data (self.save_data)
"""
# Load User Settings
self.host_a_server = try_convert(self.save_data.get("host_a_server"), bool)
self.time_limit = try_convert(self.save_data.get("time_limit"), int)
self.show_score_after_question_or_game = try_convert(self.save_data.get("show_score_after_question_or_game"),
str)
self.show_correct_answer_after_question_or_game = try_convert(
self.save_data.get("show_correct_answer_after_question_or_game"), str)
self.points_for_correct_answer = try_convert(self.save_data.get("points_for_correct_answer"), int)
self.points_for_incorrect_answer = try_convert(self.save_data.get("points_for_incorrect_answer"), int)
self.points_for_no_answer = try_convert(self.save_data.get("points_for_no_answer"), int)
self.points_multiplier_for_a_streak = try_convert(self.save_data.get("points_multiplier_for_a_streak"), int)
self.points_multiplier_for_a_streak_base = try_convert(
self.save_data.get("points_multiplier_for_a_streak_base"), int)
self.randomise_questions = try_convert(self.save_data.get("randomise_questions"), bool)
self.randomise_answer_placement = try_convert(self.save_data.get("randomise_answer_placement"), bool)
self.pick_random_question = try_convert(self.save_data.get("pick_random_question"), bool)
self.bot_difficulty = try_convert(self.save_data.get("bot_difficulty"), int)
self.server_name = try_convert(self.save_data.get("server_name"), str)
self.server_port = try_convert(self.save_data.get("server_port"), int)
self.max_players = try_convert(self.save_data.get("max_players"), int)
self.how_many_players = try_convert(self.save_data.get("how_many_players"), int)
self.how_many_bots = try_convert(self.save_data.get("how_many_bots"), int)
self.quiz_category = try_convert(self.save_data.get("quiz_category"), str)
self.quiz_difficulty = try_convert(self.save_data.get("quiz_difficulty"), str)
self.question_amount = try_convert(self.save_data.get("question_amount"), int)
self.question_type = try_convert(self.save_data.get("question_type"), str)
# Load State Settings
self.current_question = try_convert(self.save_data.get("current_question"), int)
self.current_user_playing = try_convert(self.save_data.get("current_user_playing"), int)
self.game_finished = try_convert(self.save_data.get("game_finished"), bool)
self.joined_game = try_convert(self.save_data.get("joined_game"), bool)
# Load Game Data
self.users = try_convert(self.save_data.get("users"), list)
self.questions = try_convert(self.save_data.get("questions"), list)
self.bots = try_convert(self.save_data.get("bots"), list)
def set_settings_default(self) -> None:
"""
Sets the default settings if the settings are none
"""
# User Chosen Settings
self.host_a_server = set_if_none(self.host_a_server, HOST_SERVER_BY_DEFAULT)
self.time_limit = set_if_none(self.time_limit, 10)
self.show_score_after_question_or_game = set_if_none(self.show_score_after_question_or_game, "Game")
self.show_correct_answer_after_question_or_game = set_if_none(self.show_correct_answer_after_question_or_game,
"Question")
self.points_for_correct_answer = set_if_none(self.points_for_correct_answer, 1)
self.points_for_incorrect_answer = set_if_none(self.points_for_incorrect_answer, -1)
self.points_for_no_answer = set_if_none(self.points_for_no_answer, 0)
self.points_multiplier_for_a_streak = set_if_none(self.points_multiplier_for_a_streak, 1.1)
self.points_multiplier_for_a_streak_base = set_if_none(self.points_multiplier_for_a_streak_base, 1.1)
self.randomise_questions = set_if_none(self.randomise_questions, True)
self.randomise_answer_placement = set_if_none(self.randomise_answer_placement, True)
self.pick_random_question = set_if_none(self.pick_random_question, True)
self.bot_difficulty = set_if_none(self.bot_difficulty, 50)
self.server_name = set_if_none(self.server_name, "Quiz Game Server")
self.server_port = set_if_none(self.server_port, 1234)
self.max_players = set_if_none(self.max_players, 4)
self.how_many_players = set_if_none(self.how_many_players, 1)
self.how_many_bots = set_if_none(self.how_many_bots, 0)
self.quiz_category = set_if_none(self.quiz_category, "Any")
self.quiz_difficulty = set_if_none(self.quiz_difficulty, "Any")
self.question_amount = set_if_none(self.question_amount, 10)
self.question_type = set_if_none(self.question_type, "Any")
# State Settings
self.current_question = set_if_none(self.current_question, 0)
self.current_user_playing = set_if_none(self.current_user_playing, 0)
self.game_finished = set_if_none(self.game_finished, False)
self.joined_game = set_if_none(self.joined_game, False)
# Game Data
self.users = set_if_none(self.users, [])
self.bots = set_if_none(self.bots, [])
self.questions = set_if_none(self.questions, [])
# __ DATA RELATED FUNCTIONS __
def set_settings(self) -> None:
"""
Shows the user various menus related to settings, allowing them to change the settings. Starts with the main
gameplay settings menu
"""
self.settings_gameplay()
def convert_to_object(self, dicts: list, object_type: object) -> None:
"""
Converts the dicts list from a list of item to a list of object_type objects. It will only attempt convert
the item if it is not already an object_type object, therefore this function can be called without knowing the
state of each item in the list
"""
# For each user in the list of users convert the dict to a User object using the load() function
for x in range(len(dicts)):
# Check if the user is already a User object
if isinstance(dicts[x], object_type):
continue
# Load
new_object = object_type()
new_object.load(dicts[x])
dicts[x] = new_object
def set_players(self) -> None:
"""
Clears the list of users and bots, and then gets a colour and name for each user. The amount of users is set in
the settings menu. After the users have been set the bots are then created. The amount of bots is set in the
settings menu
"""
# Clear the users and bots lists
self.users = []
self.bots = []
user_id = 0
while user_id != self.how_many_players:
# Clear the screen
clear()
# Show the title
render_header("Set Up Player")
colour_menu = Menu(" Choose a colour for ", Colour.colours_names_list)
# Create a new user
user_id += 1
user = User()
# Get name and check if it is valid
while user.name is None:
user.name = colour_menu.get_input_option(str, "Enter the name for user " + str(user_id) + ": ")
# Get colour
colour_menu.title += user.name
colour_menu.clear_screen = False
colour_menu.get_input()
user.colour = Colour.colours_list[Colour.colours_names_list.index(colour_menu.user_input)]
if user.name == "Max":
user.colour += Colour.ITALIC
# Add to list of users
self.users.append(user)
# Create the bots
for x in range(self.how_many_bots):
bot = Bot()
bot.name = "Bot " + str(x + 1)
bot.colour = Colour.GREY + Colour.ITALIC
bot.accuracy = self.bot_difficulty / 100
self.bots.append(bot)
def get_questions(self) -> None:
"""
Gets the questions from the API or from the file depending on the online_enabled setting. Afterward it converts
the questions into Question objects and then shuffles the questions if the randomise_questions setting is True.
Finally, it saves the questions to the file.
"""
# Check if the user is online
if self.online_enabled:
render_text("Getting questions from the internet...")
# Import the api_get_questions function, this is only imported if the user is online as it is not needed
# if the user is offline and don't want to run the requests installation
from Maxs_Modules.network import api_get_questions
# Convert the settings to the api syntax
self.convert_question_settings_to_api()
# Use the api to get the questions
self.questions = api_get_questions(self.question_amount, self.api_category, self.quiz_difficulty,
self.api_type)
else:
render_text("Loading questions from file...")
# Load the question from the saved questions
self.questions = load_questions_from_file()
debug_message("Questions: " + str(self.questions), "Game")
# Convert the data into a list of Question objects
self.convert_to_object(self.questions, Question)
def convert_question_settings_to_api(self) -> None:
"""
Since the API uses indices for the categories and lowercase strings for the types, this function converts the
user set settings into syntax that the API can understand
"""
# Convert the category if it is not any
if self.quiz_category != "Any":
# Get the index of the question type
category_index = quiz_categories.index(self.quiz_category)
# Add the offset to the index. This is because the api starts at 9 and not 0 (ends at 32)
self.api_category = category_index + CATEGORY_OFFSET_API
# Convert the type if it is not any
if self.question_type != "Any":
match self.question_type:
case "Multiple Choice":
self.api_type = "multiple"
case "True/False":
self.api_type = "boolean"
# __ GAME FUNCTIONS __
def begin(self) -> None:
"""
Starts the game. It first gets the questions if there are none, then shuffles the questions if the user wants
(only if the game is a new one as when continuing the game the questions should be in the same order). If the
game is set to be hosted then a server is started up. Afterward the game is checked to see if it is finished
otherwise it will continue to play from the current state
"""
# If there are no questions then get them
if len(self.questions) == 0:
self.get_questions()
# Shuffle the questions if the user wants to
if self.randomise_questions and not self.game_loaded:
random.shuffle(self.questions)
if self.host_a_server:
self.wait_for_players()
return
# Corrupt file recovery can cause there to be no users
if len(self.users) == 0:
self.set_players()
# Start the game, check if the game has finished or play the game
if self.check_game_finished():
# If the game has finished then show the results
self.game_end()
else:
self.game_started = True
self.play()
def show_scores(self) -> None:
"""
Shows the scores of all the players in a menu with the points beside them sorted from highest to lowest. If the
user selects a player their individual stats are show i.e. accuracy and time etc.
"""
# Array to store the names and scores
score_menu_players = []
score_menu_scores = []
# Add the users and their scores to the arrays
for user in self.users:
score_menu_players.append(user.styled_name())
score_menu_scores.append(round_to_decimal(user.points))
# Add the bots and their scores to the arrays
for bot in self.bots:
score_menu_players.append(bot.styled_name())
score_menu_scores.append(round_to_decimal(bot.points))
# Sort the arrays based on the scores
score_menu_multi = [score_menu_players, score_menu_scores]
debug_message("Score menu multi unsorted: " + str(score_menu_multi), "Game")
score_menu_multi = sort_multi_array(score_menu_multi, True)
debug_message("Score menu multi sorted: " + str(score_menu_multi), "Game")
# Convert the scores to strings
for x in range(len(score_menu_multi[1])):
score_menu_multi[1][x] = str(score_menu_multi[1][x])
# Add the next option (has to be after sort as "Game Finished/Next Question" is added to the end and also
# causes errors because they are not ints)
score_menu_multi[0].append("Next")
if self.game_finished:
score_menu_multi[1].append("Game Finished")
else:
score_menu_multi[1].append("Next Question")
# Show the menu
score_menu = Menu("Scores", score_menu_multi, True)
score_menu.get_input()
# If the user selected a user then show their stats
if score_menu.user_input != "Next":
# Find the user selected
for user in self.users:
# If the user is found then show their stats
if user.styled_name() == score_menu.user_input:
user.show_stats()
# Give time for the user to read the stats
get_input("Press enter to continue...")
self.show_scores()
# Find the bot selected
for bot in self.bots:
# If the bot is found then show their stats
if bot.styled_name() == score_menu.user_input:
bot.show_stats()
# Give time for the user to read the stats
get_input("Press enter to continue...")
self.show_scores()
def show_question_markings(self) -> None:
"""
Shows the answer each player submitted for the questions. It begins at current_question and then goes through
each question after that, so when called best practice is to set current_question to 0. It will call itself
in a loop until it reaches the end of the questions array
"""
# Get the current question
question = self.questions[self.current_question]
# Array to store the names and answers
marking_menu_players = []
marking_menu_answers = []
# Loop through each user adding their name and answer to the arrays
for user in self.users:
marking_menu_players.append(user.styled_name())
# Check if the user answered all the questions, if not there is an error
if len(user.answers) < self.current_question:
marking_menu_answers.append("ERROR")
else:
marking_menu_answers.append(user.answers[self.current_question])
# Loop through each bot adding their name and answer to the arrays
for bot in self.bots:
marking_menu_players.append(bot.styled_name())
# Check if the bot answered all the questions, if not there is an error
if len(bot.answers) < self.current_question:
marking_menu_answers.append("ERROR")
else:
marking_menu_answers.append(bot.answers[self.current_question])
# Add the correct answer
marking_menu_players.append("Correct Answer")
marking_menu_answers.append(question.correct_answer)
# Add the next and skip option
marking_menu_players.append("Next Question")
marking_menu_answers.append("Game Finished")
# Show the menu
marking_menu = Menu("Question: " + question.question, [marking_menu_players, marking_menu_answers], True)
# Note to self, because python is python with its syntax, the "_" is what default is
match marking_menu.get_input():
case "Next Question":
if self.current_question == len(self.questions) - 1:
return
# If there are any questions left to overview then show the next question
else:
self.current_question += 1
self.show_question_markings()
case "Correct Answer":
render_text("These players got the question correct: ")
# Show all the users that got the question correct
for user in self.users:
if user.answers[self.current_question] == question.correct_answer:
render_text(user.styled_name())
# Give time for the user to read the correct users
get_input("Press enter to continue...")
self.show_question_markings()
case _:
# Find the user selected
for user in self.users:
# If the user is found then show their stats
if user.styled_name() == marking_menu.user_input:
user.show_stats()
# Give time for the user to read the stats
get_input("Press enter to continue...")
self.show_question_markings()
# Find the bot selected
for bot in self.bots:
# If the bot is found then show their stats
if bot.styled_name() == marking_menu.user_input:
bot.show_stats()
# Give time for the user to read the stats
get_input("Press enter to continue...")
self.show_question_markings()
def mark_question(self, user_input, current_user) -> None:
"""
Marks the question and updates the user class based on the mark. The marking (Correct, Incorrect, Missed) is
added on to the current valued stored in the user's, answers array therefore before calling the marking
function set the string to be "" or "Missed_".
@param user_input: The answer submitted by the player, this is what will be checked against the correct answer
@param current_user: The user that answered the question, and where the points will be added to.
"""
# Get the current question
question = self.questions[self.current_question]
debug_message(current_user.player_type + " " + current_user.name + " answered: " + user_input, "Game")
# Check if the answer is correct
if user_input == question.correct_answer:
# Tell the user that the answer is correct
if current_user.player_type == "User":
render_text("Correct!")
# Add the answer to the user
current_user.answers[len(current_user.answers) - 1] += "Correct"
# Set the point to the default point
point = self.points_for_correct_answer
# Check if the user has a streak
if current_user.streak > 0:
# If the user has a streak then add the streak to the point
point = self.points_multiplier_for_a_streak * current_user.streak
# If the answer is correct then add a point to the user
current_user.points += point
# Add a point to the streak
current_user.streak += 1
if current_user.streak > current_user.highest_streak:
current_user.highest_streak = current_user.streak
# Add correct
current_user.correct += 1
else:
if current_user.player_type == "User":
render_text("Incorrect.")
if self.show_correct_answer_after_question_or_game == "Question":
render_text("The correct answer was: " + question.correct_answer)
# Add the answer to the user
current_user.answers[len(current_user.answers) - 1] += "Incorrect"
# Reset the streak
current_user.streak = 0
self.points_multiplier_for_a_streak = self.points_multiplier_for_a_streak_base
# Add incorrect
current_user.incorrect += 1
# If the answer is not correct then remove a point from the user
current_user.points += self.points_for_incorrect_answer
def play(self) -> None:
"""
Shows the user the question in a menu and gets the user to answer it, utilising the Menu class's time_limit
to force the user to answer in the specified amount of time. Then it marks the question and calculates the
score for the player. Afterward it runs the next question. The start time and end time of this function is
calculated and then stored for later use to work out the timings for the stats.
"""
# Save the users progress
self.save()
# Get the current question & user
question = self.questions[self.current_question]
current_user = self.users[self.current_user_playing]
# Create options
options = question.incorrect_answers.copy()
options.append(question.correct_answer)
# Shuffle the options
if self.randomise_answer_placement:
random.shuffle(options)
# Create the question menu
question_menu = Menu(question.question, options)
# Clear the screen
clear()
# Print some info
render_quiz_header(self)
# Don't clear the screen as information is printed before the menu
question_menu.clear_screen = False
# Timings
start_time = time.time()
# Show the question and get the user input
question_menu.time_limit = self.time_limit
question_menu.get_input()
if question_menu.user_input is not None:
# As the user didn't miss then just leave the preheader blank
current_user.answers.append("")
# Mark the question
self.mark_question(question_menu.user_input, current_user)
else:
# If the game should pick a random question when the time runs out
if self.pick_random_question:
# Add the Missed part to the user
current_user.answers.append("Missed_")
# Get a random option
random_option = random.choice(options)
render_text("Auto picking: " + random_option)
self.mark_question(random_option, current_user)
else:
# Add the points for no answer
current_user.answers.append("Missed_Incorrect")
current_user.points += self.points_for_no_answer
# Add missed question to the user
current_user.questions_missed += 1
render_text("\nTime's up!")
# Store the time data
end_time = time.time() - start_time
debug_message("Time taken: " + str(end_time) + " seconds", "Game")
current_user.times.append(end_time)
# Make the bots answer
if self.current_user_playing == 0:
for bot in self.bots:
# Get the bot to answer the question
bot_answer = bot.answer(question)
# As the bot cant miss then just leave the preheader blank
bot.answers.append("")
# Mark the question
self.mark_question(bot_answer, bot)
# Add the time, for use in stats
bot.times.append(0)