gemini-2.5-flash-preview-04-17· Google LMArena Human Preference 140K
Make a Python Script that works how kahoot
- User
Make a Python Script that works how kahoot
- Assistant
Okay, here is a Python script that simulates the core mechanics of Kahoot!
It includes:
- Defining questions with multiple-choice options and a correct answer.
- Allowing multiple players to join.
- Going through questions one by one.
- Players selecting answers.
- Scoring based on correctness and a simplified speed bonus (the first player to answer correctly gets an extra bonus).
- Displaying results after each round.
- Showing final scores and the winner(s).
This is a command-line simulation; it's not a graphical interface and players take turns answering, rather than answering simultaneously within a time limit like real Kahoot.
import time import os # Used to clear the screen def clear_screen(): """Clears the terminal screen.""" os.system('cls' if os.name == 'nt' else 'clear') def get_players(): """Prompts users to enter player names.""" players = [] print("Enter player names (type 'done' when finished):") while True: name = input(f"Player {len(players) + 1} name: ").strip() if name.lower() == 'done': if len(players) < 1: print("Please add at least one player.") continue break if name: players.append(name) else: print("Please enter a valid name.") return players def define_questions(): """Defines the list of questions, options, and correct answers.""" questions = [ { "question": "What is the capital of France?", "options": ["Berlin", "Madrid", "Paris", "Rome"], "correct_answer_index": 2 # Index of "Paris" (0-based) }, { "question": "Which planet is known as the Red Planet?", "options": ["Earth", "Mars", "Jupiter", "Venus"], "correct_answer_index": 1 # Index of "Mars" }, { "question": "What is 7 * 8?", "options": ["56", "49", "64", "72"], "correct_answer_index": 0 # Index of "56" }, { "question": "Who wrote 'Romeo and Juliet'?", "options": ["Charles Dickens", "William Shakespeare", "Jane Austen", "Mark Twain"], "correct_answer_index": 1 # Index of "William Shakespeare" } ] return questions def display_question(question_data, q_number): """Displays a single question and its options.""" print(f"\n--- Question {q_number} ---") print(question_data["question"]) print("Options:") for i, option in enumerate(question_data["options"]): print(f"{i + 1}. {option}") # Display 1-based index for user input def get_player_answer(player_name, options_count): """Gets a valid answer from a player.""" while True: try: answer_input = input(f"{player_name}, your answer (enter number): ").strip() answer_index = int(answer_input) - 1 # Convert 1-based input to 0-based index if 0 <= answer_index < options_count: return answer_index else: print(f"Invalid number. Please enter a number between 1 and {options_count}.") except ValueError: print("Invalid input. Please enter a number.") def calculate_points(is_correct, answered_first_correct): """Calculates points for a player based on correctness and speed.""" base_points = 100 first_correct_bonus = 50 # Extra points for the first correct answerer if is_correct: points = base_points if answered_first_correct: points += first_correct_bonus return points else: return 0 def display_scores(scores): """Displays the current scores.""" print("\n--- Current Scores ---") sorted_scores = sorted(scores.items(), key=lambda item: item[1], reverse=True) for player, score in sorted_scores: print(f"{player}: {score} points") print("-" * 20) def display_round_results(question_data, round_answers, round_scores_earned, scores): """Displays the results after a question round.""" correct_index = question_data["correct_answer_index"] correct_answer_text = question_data["options"][correct_index] print("\n--- Round Results ---") print(f"The correct answer was: {correct_answer_text}") print("\nIndividual Results:") # Display players based on the order they answered (simulating speed) for player, answer_index in round_answers: is_correct = (answer_index == correct_index) points_earned = round_scores_earned.get(player, 0) # Get points earned in this specific round answer_text = question_data["options"][answer_index] if 0 <= answer_index < len(question_data["options"]) else "Invalid Answer" status = "CORRECT" if is_correct else "INCORRECT" print(f"{player}: Chose '{answer_text}' - {status} (+{points_earned} points)") display_scores(scores) def display_final_results(scores): """Displays the final scores and determines the winner(s).""" print("\n" * 5) # Add some space print("=" * 30) print("--- FINAL GAME RESULTS ---") print("=" * 30) sorted_scores = sorted(scores.items(), key=lambda item: item[1], reverse=True) if not sorted_scores: print("No scores recorded.") return # Display final scores for player, score in sorted_scores: print(f"{player}: {score} points") # Determine winner(s) top_score = sorted_scores[0][1] winners = [player for player, score in sorted_scores if score == top_score] print("\n" + "=" * 30) if len(winners) == 1: print(f"The winner is: {winners[0]} with {top_score} points!") else: print(f"It's a tie! Winners are: {', '.join(winners)} with {top_score} points!") print("=" * 30) def play_game(): """Runs the main Kahoot game logic.""" clear_screen() print("Welcome to Python Kahoot!") players = get_players() if not players: print("No players joined. Exiting.") return questions = define_questions() scores = {player: 0 for player in players} # Initialize scores for all players print("\nStarting game with players:", ", ".join(players)) print("Press Enter to start the first question...") input() # Wait for user to press Enter for q_number, question_data in enumerate(questions, 1): clear_screen() display_question(question_data, q_number) # Collect answers in the order they are given to simulate speed round_answers = [] # List of tuples (player_name, answer_index) for player in players: answer_index = get_player_answer(player, len(question_data["options"])) round_answers.append((player, answer_index)) # Process answers and award points correct_index = question_data["correct_answer_index"] first_correct_awarded = False round_scores_earned = {} # Store points earned in this round for display for player, answer_index in round_answers: is_correct = (answer_index == correct_index) points = calculate_points(is_correct, is_correct and not first_correct_awarded) if is_correct and not first_correct_awarded: first_correct_awarded = True # Mark that the bonus has been given scores[player] += points round_scores_earned[player] = points # Record points earned in this round # Display results for the current round clear_screen() display_round_results(question_data, round_answers, round_scores_earned, scores) # Pause before next question or end of game if q_number < len(questions): input("\nPress Enter for the next question...") else: input("\nAll questions answered! Press Enter to see final results...") # Game over clear_screen() display_final_results(scores) # Run the game if __name__ == "__main__": play_game()How to Run the Script:
- Save the code in a file named
kahoot_sim.py(or any name ending with.py). - Open a terminal or command prompt.
- Navigate to the directory where you saved the file.
- Run the script using the command:
python kahoot_sim.py - Follow the on-screen prompts to enter player names and answers.
Explanation:
clear_screen(): A helper function to make the output cleaner.get_players(): Collects names from users until they type 'done'.define_questions(): A list of dictionaries, where each dictionary holds the question text, a list of answer options, and the index (starting from 0) of the correct option. You can easily add more questions here.display_question(): Prints the question and numbered options.get_player_answer(): Prompts a specific player for their answer, validates that it's a valid number within the range of options, and returns the 0-based index they chose.calculate_points(): Determines points based on correctness and if the player was the first among the correct to answer.display_scores(): Shows the current total scores, sorted from highest to lowest.display_round_results(): Shows the correct answer for the round, who answered what, whether they were correct, and how many points they gained in that specific round. Then callsdisplay_scores()to show the overall standings.display_final_results(): Called at the end. Prints the final scores and announces the winner(s) (handling ties).play_game(): The main function that orchestrates the game flow:- Gets players.
- Defines questions.
- Initializes scores.
- Loops through each question:
- Displays the question.
- Collects answers from each player one by one in the current
playerslist order. This order determines the "speed" simulation for the bonus. - Processes the collected answers to calculate points, awarding the speed bonus to the very first player in the collected
round_answerslist who got it right. - Updates total scores.
- Displays the round results.
- Waits for user input to proceed.
- Calls
display_final_results()after all questions.
if __name__ == "__main__":: Ensuresplay_game()runs only when the script is executed directly.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.