w3resource

Develop a Quiz Game with Timer in Python


Quiz Game with Timer: Develop a quiz game with a timer for each question.

Input values:
1. User interacts with the quiz game by selecting answers to quiz questions.
2. Users can also start the timer for each question and submit their answers within the time limit.

Output value:
Visual representation of the quiz game interface displaying quiz questions, answer options, a timer countdown for each question, and feedback on user responses.

Example:

Input values:
1. Start the quiz:
- User initiates the quiz game.
Output value:
Visual representation of the quiz game interface displays the first quiz question, answer options, and starts the timer countdown.
Input values:
2. Select an answer:
- User selects an answer option for the current quiz question.
- User submits the answer before the timer runs out.
Output value:
Visual representation of the quiz game interface displays feedback on the submitted answer and moves to the next quiz question if available.
Input values:
3. Timer runs out:
- User fails to submit an answer before the timer runs out.
Output value:
Visual representation of the quiz game interface displays feedback indicating that the time has expired for the current question. It moves to the next question if available.
Input values:
4. Complete the quiz:
- User completes all quiz questions by selecting answer options and submitting answers.
Output value:
Visual representation of the quiz game interface displays the final score, including the number of correct and incorrect answers. It also provides options to review quiz questions and answers.
Input values:
5. Review the quiz questions:
- User chooses to review quiz questions and answers after completing the quiz.
Output value:
Visual representation of the quiz game interface displays the quiz questions, selected answer options, correct answers, and user responses for review.

Solution: Console-Based Quiz Game with Timer

This solution implements a simple console-based quiz game where each question has a timer. The player needs to answer the question before the timer runs out, and the game tracks the player's score.

Code:

import time
import threading

# Solution 1: Console-based Quiz Game with Timer

class QuizGame:
    def __init__(self, questions):
        self.questions = questions  # List of questions with options and answers
        self.score = 0              # Initialize player score
        self.time_out = False       # Flag to track if time is out

    def start_quiz(self):
        for question in self.questions:
            self.ask_question(question)
        self.display_final_score()

    def ask_question(self, question):
        # Reset the time_out flag for each question
        self.time_out = False
        
        # Start the countdown timer in a separate thread
        timer = threading.Thread(target=self.countdown, args=(question["time_limit"],))
        timer.start()

        # Display question and options
        print(f"\nQuestion: {question['question']}")
        for index, option in enumerate(question['options']):
            print(f"{index + 1}. {option}")

        # User input and timing
        answer = None

        while answer is None:
            try:
                # Check if time has expired
                if self.time_out:
                    break
                answer = int(input("\nSelect an option (1-4): "))
                if answer not in [1, 2, 3, 4]:
                    raise ValueError("Invalid option")
                break  # Exit the loop if a valid answer is provided
            except ValueError as e:
                print(e)
                answer = None
        
     
        if self.time_out:
            print("Time's up!")
        else:
            if question['options'][answer - 1] == question['correct']:
                print("Correct!")
                self.score += 1
            else:
                print("Incorrect.")
        
        timer.join()  # Wait for the timer thread to finish

    def countdown(self, time_limit):
        print(f"\nYou have {time_limit} seconds to answer this question.")
        time.sleep(time_limit)
        self.time_out = True  # Set time_out to True when time runs out

    def display_final_score(self):
        print(f"\nQuiz Over! Your final score is: {self.score}/{len(self.questions)}")

# Example questions for the quiz
questions = [
    {"question": "What is the capital of France?", "options": ["Berlin", "Madrid", "Paris", "Rome"], "correct": "Paris", "time_limit": 7},
    {"question": "Which planet is known as the Red Planet?", "options": ["Earth", "Mars", "Jupiter", "Venus"], "correct": "Mars", "time_limit": 7},
    {"question": "What is the largest ocean on Earth?", "options": ["Atlantic", "Indian", "Pacific", "Arctic"], "correct": "Pacific", "time_limit": 7},
]

# Start the quiz game
if __name__ == "__main__":
    quiz = QuizGame(questions)
    quiz.start_quiz()

Output:

You have 7 seconds to answer this question.

Question: What is the capital of France?
1. Berlin
2. Madrid
3. Paris
4. Rome

Select an option (1-4): 3
Correct!

You have 7 seconds to answer this question.
Question: Which planet is known as the Red Planet?
1. Earth
2. Mars
3. Jupiter
4. Venus


Select an option (1-4): 3
Time's up!

You have 7 seconds to answer this question.

Question: What is the largest ocean on Earth?
1. Atlantic
2. Indian
3. Pacific
4. Arctic

Select an option (1-4): 2
Incorrect.

Quiz Over! Your final score is: 1/3

Explanation:

  • Class Definition (QuizGame):
    • The QuizGame class manages the quiz game, including questions, user input, timers, and score.
  • Initialization (__init__ method):
    • Takes a list of questions and initializes the player's score to 0.
    • A self.time_out flag is added to track if the time has run out for a question.
  • Starting the Quiz (start_quiz method):
    • Loops through the list of questions, asking each one using the ask_question method.
    • After all questions are answered, it calls display_final_score to show the total score.
    • Asking a Question (ask_question method):
      • Resets the self.time_out flag to False before each question.
      • Starts a countdown timer in a separate thread, which runs for the specified time limit.
      • Displays the question and answer options to the user.
      • Accepts the user’s answer unless the time runs out, in which case it prints "Time's up!".
      • If time remains, it checks the user's answer for correctness and updates the score.
    • Countdown Timer (countdown method):
      • Displays the time limit to the user.
      • Pauses the program for the duration of the time limit using time.sleep().
      • Sets the self.time_out flag to True when the time runs out, which is checked in the main question loop.
    • Displaying Final Score (display_final_score method):
      • After the quiz ends, this method prints the player’s final score out of the total number of questions.
    • Questions List:
      • A sample list of questions is provided, each with a question, answer options, the correct answer, and a time limit.
    • Main Program Execution:
      • The program creates an instance of the QuizGame class with the provided questions and starts the quiz.


Follow us on Facebook and Twitter for latest update.