import json import random def _check_string_is_number_in_range(prompt: str, min: int, max: int) -> bool: """Checks if given string can be converted into a number savely and if it lies within a given range. Args: prompt (str): Can recieve any string. min (int): Min value for comparison. Operates >= max (int): Max value for comparison. Operates <= Returns: bool: Returns if string is a number within given range. """ try: out = int(prompt) except ValueError: return False if out >= min and out <= max: return True else: return False def _show_score(score: int, max_score: int): """Prints given data in a fine way. Args: score (int): Score achieved. count (int): Maximum score. """ print("Your score is", score, "/", max_score, "\n\n") def _user_input_question() -> dict: prompt_quest = 'Write your question.\n' prompt_correct_answer = 'Write the CORRECT answer.\n' prompt_wrong_answer = 'Write a wrong answer.\n' question = {} question['question'] = input(prompt_quest) question['correct'] = input(prompt_correct_answer) question['false1'] = input(prompt_wrong_answer) question['false2'] = input(prompt_wrong_answer) question['false3'] = input(prompt_wrong_answer) return question def _user_check_dict(data: dict) -> bool: """Asks the user to check any given dict. Args: data (dict): Dict to be checked. Returns: bool: Returns whether dict was accepted or not. """ print("Please double check your data:\n") #TODO: add print limiter for X number of rows; use modulo for key, val in data.items(): if len(key) <= 6: print(key, '\t\t', val) else: print(key, '\t', val) user_input = input(("If your input is correct, please enter 'yes'.\n"+ "Elsewise enter anything or nothing.\n")) if user_input.lower() == "yes": return True else: return False def add_new_question_user(question_json: str): """Allows a user to add a new question. """ new_question = _user_input_question() if not _user_check_dict(new_question): return _export_questions_into_json(new_question, question_json) def _export_questions_into_json(new_question: dict, filedir: str): """Gets information of json file, adds new question and saves the data. Args: filedir (str, optional): Directory of json. Defaults to "ho_projects/quiz/questions.json". """ original_data = _import_questions_into_program(filedir) original_data['questions'].append(new_question) with open(filedir, 'w') as f: json.dump(original_data, f) def _import_questions_into_program(questions_json: str) -> dict: """Function to import question from any specified .json file. Args: filedir (str): Directory of json. """ with open(questions_json, 'r') as f: questions = json.load(f) random.shuffle(questions['questions']) return questions def _read_dict_data(question: dict) -> tuple[str, list[str], str]: """Read dict data and return isolated information. Args: question (dict): input dict of question-structure. Returns: tuple[str, list[str]]: return tuple with (Question, list of possible answers, correct answer) """ possible_answers = [] # clear answer list for key, val in question.items(): if key == "question": question = val elif key == "correct": correct_answer = val.lower() possible_answers.append(val) else: possible_answers.append(val) random.shuffle(possible_answers) return question, possible_answers, correct_answer def _ask_question(question_prompt: str, count: int, possible_answers: list[str], correct_answer: str) -> bool: """Present question and possible answeres to user. Checks if answer is correct, based on argument. Args: question_prompt (str): Question prompt. count (int): Number of the question. possible_answers (list[str]): List of possible answeres. correct_answer (str): The one true answer. Only one correct answer is allowed. Returns: bool: Return whether the answer was correct or not. """ prompt_wrong_input = "\nYou're input was wrong!\tWROOOONG!!!!\n" prompt_input = "Choose your answer by entering the according number:\t" prompt_correct_answer = "\tYou're answere was right! =D\n" prompt_wrong_answer = "\tYou're answer was wrong... too bad!:-(\n" for _ in range(999_999_999): # better: while True i = 1 print("Question ", count, ":\n", question_prompt) for i, answer in enumerate(possible_answers): print(i, "\t", answer) user_input = input(prompt_input) if not _check_string_is_number_in_range(user_input, 0, i): print(prompt_wrong_input) else: break if correct_answer.lower() == possible_answers[int(user_input)].lower(): print(prompt_correct_answer) return True else: print(prompt_wrong_answer) return False def main_menu(questions_json: str): """The main menu of the quiz game.""" prompt = ( "\nWelcome to another quiz.\nWhat do you wanna do?\n" + "1\tPlay the game!\n2\tAdd another question\n3\tSurrender....\n" ) prompt_wrong_input = "Wrong input. Please choose a number shown." prompt_exit = "As you wish...." for _ in range(999_999_999): # better: while True user_input = input(prompt) if _check_string_is_number_in_range(user_input, 1, 3): break else: print(prompt_wrong_input) user_input = int(user_input) if user_input == 1: game(questions_json) if user_input == 2: add_new_question_user(questions_json) if user_input == 3: print(prompt_exit) exit() def game(questions_json: str, max_questions: int = 10): """A simple quiz game. Args: max_questions (int, optional): Maximum amount of numbers. Defaults to 10. """ questions = _import_questions_into_program(questions_json) score = 0 question_list = questions['questions'] random.shuffle(question_list) for count, question in enumerate(questions['questions']): count += 1 prompt_q, possible_answers, correct_answer = _read_dict_data(question) if _ask_question(prompt_q, count, possible_answers, correct_answer): score += 1 if count == max_questions: # check if limit of questions was reached break _show_score(score, count) def main(): questions_json = "questions.json" for _ in range(999_999_999): # better: while True main_menu(questions_json) if __name__ == '__main__': main()