Quiz Game with Timer
Abstract
Quiz Game with Timer is a Python project that challenges users with timed questions. It demonstrates event-driven programming, GUI development, and time management. This project is ideal for learning about interactive games, user input, and countdown timers in Python.
Prerequisites
- Python 3.6 or above
- tkinter (usually pre-installed)
- random (built-in)
Before you Start
Ensure Python is installed. No external packages are required. For GUI, make sure Tkinter is available.
Getting Started
- Create a folder named
quiz-game-timer
quiz-game-timer
. - Create a file named
quiz_game_with_timer.py
quiz_game_with_timer.py
. - Copy the code below into your file.
⚙️ Quiz Game with Timer
Quiz Game with Timer
"""
Quiz Game with Timer
A Python-based quiz game where players must answer questions within a time limit. The game includes:
- A set of multiple-choice questions
- A timer for each question
- Score calculation based on correct answers
"""
import time
import threading
from tkinter import Tk, Label, Button, messagebox
class QuizGameWithTimer:
def __init__(self, root):
self.root = root
self.root.title("Quiz Game with Timer")
self.questions = [
{"question": "What is the capital of France?", "options": ["Paris", "London", "Berlin", "Madrid"], "answer": "Paris"},
{"question": "What is 5 + 7?", "options": ["10", "12", "14", "16"], "answer": "12"},
{"question": "Which planet is known as the Red Planet?", "options": ["Earth", "Mars", "Jupiter", "Venus"], "answer": "Mars"},
]
self.current_question_index = 0
self.score = 0
self.time_left = 10
self.timer_thread = None
self.timer_running = False
self.setup_ui()
self.display_question()
def setup_ui(self):
"""Set up the user interface."""
self.question_label = Label(self.root, text="", wraplength=400, font=("Arial", 14))
self.question_label.pack(pady=20)
self.option_buttons = []
for i in range(4):
button = Button(self.root, text="", command=lambda i=i: self.check_answer(i), width=20)
button.pack(pady=5)
self.option_buttons.append(button)
self.timer_label = Label(self.root, text="Time left: 10 seconds", font=("Arial", 12))
self.timer_label.pack(pady=10)
def display_question(self):
"""Display the current question and options."""
if self.current_question_index >= len(self.questions):
self.end_game()
return
question_data = self.questions[self.current_question_index]
self.question_label.config(text=question_data["question"])
for i, option in enumerate(question_data["options"]):
self.option_buttons[i].config(text=option)
self.time_left = 10
self.timer_label.config(text=f"Time left: {self.time_left} seconds")
self.start_timer()
def start_timer(self):
"""Start the countdown timer."""
self.timer_running = True
self.timer_thread = threading.Thread(target=self.countdown)
self.timer_thread.start()
def countdown(self):
"""Countdown timer logic."""
while self.time_left > 0 and self.timer_running:
time.sleep(1)
self.time_left -= 1
self.timer_label.config(text=f"Time left: {self.time_left} seconds")
if self.time_left == 0:
self.timer_running = False
self.root.after(0, self.time_up)
def time_up(self):
"""Handle the event when time is up."""
messagebox.showinfo("Time's Up!", "You ran out of time for this question.")
self.next_question()
def check_answer(self, index):
"""Check if the selected answer is correct."""
if not self.timer_running:
return
self.timer_running = False
question_data = self.questions[self.current_question_index]
selected_option = self.option_buttons[index].cget("text")
if selected_option == question_data["answer"]:
self.score += 1
self.next_question()
def next_question(self):
"""Move to the next question."""
self.current_question_index += 1
self.display_question()
def end_game(self):
"""End the game and display the score."""
messagebox.showinfo("Game Over", f"Your score: {self.score}/{len(self.questions)}")
self.root.destroy()
def main():
root = Tk()
app = QuizGameWithTimer(root)
root.mainloop()
if __name__ == "__main__":
main()
Quiz Game with Timer
"""
Quiz Game with Timer
A Python-based quiz game where players must answer questions within a time limit. The game includes:
- A set of multiple-choice questions
- A timer for each question
- Score calculation based on correct answers
"""
import time
import threading
from tkinter import Tk, Label, Button, messagebox
class QuizGameWithTimer:
def __init__(self, root):
self.root = root
self.root.title("Quiz Game with Timer")
self.questions = [
{"question": "What is the capital of France?", "options": ["Paris", "London", "Berlin", "Madrid"], "answer": "Paris"},
{"question": "What is 5 + 7?", "options": ["10", "12", "14", "16"], "answer": "12"},
{"question": "Which planet is known as the Red Planet?", "options": ["Earth", "Mars", "Jupiter", "Venus"], "answer": "Mars"},
]
self.current_question_index = 0
self.score = 0
self.time_left = 10
self.timer_thread = None
self.timer_running = False
self.setup_ui()
self.display_question()
def setup_ui(self):
"""Set up the user interface."""
self.question_label = Label(self.root, text="", wraplength=400, font=("Arial", 14))
self.question_label.pack(pady=20)
self.option_buttons = []
for i in range(4):
button = Button(self.root, text="", command=lambda i=i: self.check_answer(i), width=20)
button.pack(pady=5)
self.option_buttons.append(button)
self.timer_label = Label(self.root, text="Time left: 10 seconds", font=("Arial", 12))
self.timer_label.pack(pady=10)
def display_question(self):
"""Display the current question and options."""
if self.current_question_index >= len(self.questions):
self.end_game()
return
question_data = self.questions[self.current_question_index]
self.question_label.config(text=question_data["question"])
for i, option in enumerate(question_data["options"]):
self.option_buttons[i].config(text=option)
self.time_left = 10
self.timer_label.config(text=f"Time left: {self.time_left} seconds")
self.start_timer()
def start_timer(self):
"""Start the countdown timer."""
self.timer_running = True
self.timer_thread = threading.Thread(target=self.countdown)
self.timer_thread.start()
def countdown(self):
"""Countdown timer logic."""
while self.time_left > 0 and self.timer_running:
time.sleep(1)
self.time_left -= 1
self.timer_label.config(text=f"Time left: {self.time_left} seconds")
if self.time_left == 0:
self.timer_running = False
self.root.after(0, self.time_up)
def time_up(self):
"""Handle the event when time is up."""
messagebox.showinfo("Time's Up!", "You ran out of time for this question.")
self.next_question()
def check_answer(self, index):
"""Check if the selected answer is correct."""
if not self.timer_running:
return
self.timer_running = False
question_data = self.questions[self.current_question_index]
selected_option = self.option_buttons[index].cget("text")
if selected_option == question_data["answer"]:
self.score += 1
self.next_question()
def next_question(self):
"""Move to the next question."""
self.current_question_index += 1
self.display_question()
def end_game(self):
"""End the game and display the score."""
messagebox.showinfo("Game Over", f"Your score: {self.score}/{len(self.questions)}")
self.root.destroy()
def main():
root = Tk()
app = QuizGameWithTimer(root)
root.mainloop()
if __name__ == "__main__":
main()
- Run the script:
python quiz_game_with_timer.py
python quiz_game_with_timer.py
Explanation
Code Breakdown
- Import modules
import tkinter as tk
import random
import tkinter as tk
import random
- Set up questions and timer
questions = [
{'q': 'What is 2+2?', 'a': '4'},
{'q': 'Capital of France?', 'a': 'Paris'}
]
questions = [
{'q': 'What is 2+2?', 'a': '4'},
{'q': 'Capital of France?', 'a': 'Paris'}
]
- Timer mechanism
def start_timer():
# Countdown logic
pass
def start_timer():
# Countdown logic
pass
- GUI for quiz
root = tk.Tk()
root.title('Quiz Game with Timer')
# ...setup widgets for questions, input, timer...
root.mainloop()
root = tk.Tk()
root.title('Quiz Game with Timer')
# ...setup widgets for questions, input, timer...
root.mainloop()
Features
- Timed questions
- Score tracking
- Randomized questions
- GUI for interaction
How It Works
- Displays questions one by one
- Starts timer for each question
- User enters answer before time runs out
- Updates score and moves to next question
GUI Components
- Label: Shows question
- Entry box: For answer
- Timer display: Shows remaining time
- Score display: Tracks correct answers
Use Cases
- Practice quick thinking
- Educational quizzes
- Game nights
Next Steps
You can enhance this project by:
- Adding more questions
- Implementing difficulty levels
- Adding sound alerts
- Keeping high scores
- Supporting multiplayer
Enhanced Version Ideas
def add_sound_alert():
# Play sound when time is up
pass
def multiplayer_mode():
# Allow multiple players
pass
def add_sound_alert():
# Play sound when time is up
pass
def multiplayer_mode():
# Allow multiple players
pass
Troubleshooting Tips
- Timer not working: Check countdown logic
- GUI not showing: Ensure Tkinter is installed
- Questions not loading: Check question list
Conclusion
This project teaches event-driven programming, timers, and GUI basics. Extend it for more features and challenge levels.
Was this page helpful?
Let us know how we did