Programming lesson
Build a Two-Player Trivia Game in Python: OOP with Classes and Modules
Learn to create a two-player trivia game in Python using object-oriented programming. This tutorial covers classes, modules, and game logic with a step-by-step approach.
Introduction: Why Build a Trivia Game in Python?
Trivia games are a fun and practical way to practice Python programming, especially object-oriented programming (OOP). In this tutorial, you'll build a two-player trivia game using classes, modules, and a driver program. This project mirrors real-world applications like quiz apps, study tools, and even AI-powered trivia bots. By the end, you'll have a solid grasp of OOP principles and modular design.
Understanding the Assignment Structure
The assignment is split into three modules:
- Questions Class – Defines a class to hold a trivia question and its four answers.
- Trivia Questions – Creates a list of at least 10 trivia question objects.
- Driver Program – Runs the game for two players, alternating turns.
This modular approach is common in software development. Think of it like building a game show: you need a blueprint for each question (class), a set of questions (module), and a host to run the show (driver).
Step 1: Designing the Questions Class
Start by creating a class named Question. It should have attributes for the question text, four answer choices, and the correct answer number. Use an __init__ method to initialize these attributes. You may also add a __str__ method to display the question nicely.
class Question:
def __init__(self, text, ans1, ans2, ans3, ans4, correct):
self.text = text
self.ans1 = ans1
self.ans2 = ans2
self.ans3 = ans3
self.ans4 = ans4
self.correct = correct
def __str__(self):
return f"{self.text}\n1. {self.ans1}\n2. {self.ans2}\n3. {self.ans3}\n4. {self.ans4}"This class is your blueprint. Each question object will hold one trivia item. You can also add accessor methods (getters) if needed.
Step 2: Creating the Trivia Questions Module
In a separate file (e.g., trivia_questions.py), import the Question class and define a function that returns a list of at least 10 questions. The total number must be even so each player gets the same number of turns.
from question_class import Question
def get_questions():
questions = []
questions.append(Question("How many days are in a lunar year?", "354", "365", "243", "379", 1))
questions.append(Question("What is the largest planet?", "Mars", "Jupiter", "Earth", "Pluto", 2))
questions.append(Question("What is the largest kind of whale?", "Orca whale", "Humpback whale", "Beluga whale", "Blue whale", 4))
questions.append(Question("Which dinosaur could fly?", "Triceratops", "Tyrannosaurus Rex", "Pteranodon", "Diplodocus", 3))
questions.append(Question("Which of these Winnie the Pooh characters is a donkey?", "Pooh", "Eeyore", "Piglet", "Kanga", 2))
questions.append(Question("What is the hottest planet?", "Mars", "Pluto", "Earth", "Venus", 4))
questions.append(Question("Which dinosaur had the largest brain compared to body size?", "Troodon", "Stegosaurus", "Ichthyosaurus", "Gigantoraptor", 1))
questions.append(Question("What is the largest type of penguins?", "Chinstrap penguins", "Macaroni penguins", "Emperor penguins", "White-flippered penguins", 3))
questions.append(Question("Which children's story character is a monkey?", "Winnie the Pooh", "Curious George", "Horton", "Goofy", 2))
questions.append(Question("How long is a year on Mars?", "550 Earth days", "498 Earth days", "126 Earth days", "687 Earth days", 4))
return questionsThis module is your question bank. You can customize questions to match any theme—sports, gaming, AI, or pop culture. For example, you could add questions about the latest viral AI app or a trending esports event.
Step 3: Building the Driver Program
The driver program imports the question list, then runs the game loop. It tracks scores for two players and alternates turns. After all questions are answered, it displays the winner.
from trivia_questions import get_questions
def main():
questions = get_questions()
player1_score = 0
player2_score = 0
for i, q in enumerate(questions):
if i % 2 == 0:
print(f"Question for the first player:")
else:
print(f"Question for the second player:")
print(q)
answer = int(input("Enter your solution (a number between 1 and 4): "))
if answer == q.correct:
print("That is the correct answer.")
if i % 2 == 0:
player1_score += 1
else:
player2_score += 1
else:
print(f"That is incorrect. The correct answer is {q.correct}")
print(f"The first player earned {player1_score} points.")
print(f"The second player earned {player2_score} points.")
if player1_score > player2_score:
print("The first player wins the game.")
elif player2_score > player1_score:
print("The second player wins the game.")
else:
print("It's a tie!")
if __name__ == "__main__":
main()This driver program is the game engine. It uses a loop to iterate through questions, alternating between players. The % 2 trick ensures even-indexed questions go to player 1, odd to player 2.
Enhancing the Game: Ideas and Extensions
Once you have the basic game working, consider these enhancements:
- Randomize questions – Use
random.shuffleto mix up the order each game. - Add a timer – Use
time.time()to limit answer time, like in a real quiz show. - Incorporate trending topics – Replace some questions with ones about current events, like the latest AI breakthrough or a popular game release.
- Save high scores – Write scores to a file so players can compete over time.
- Create a GUI version – Use tkinter or Pygame to make a visual game.
These extensions make the project more engaging and teach additional Python concepts like file I/O, randomization, and GUI programming.
Common Pitfalls and How to Avoid Them
When building this trivia game, watch out for:
- Off-by-one errors – Ensure answer numbers match the correct attribute (1-4).
- Module import issues – Make sure all files are in the same directory and import paths are correct.
- Input validation – The driver should handle non-numeric or out-of-range inputs gracefully (use a loop).
- Even number of questions – If you add or remove questions, ensure the total is even to give each player the same turns.
Testing each module separately helps catch errors early.
Real-World Connections: OOP in Modern Tech
Object-oriented programming isn't just for assignments. It's used in building apps like Duolingo (quiz-based learning), Trivia Crack, and even in AI systems where each object represents a data point. The modular design mirrors how large software projects are organized—think of how a game like Fortnite separates its game engine, assets, and UI into different modules. By mastering classes and modules, you're learning skills used by professional developers every day.
Conclusion
You've now built a complete two-player trivia game in Python using OOP. This project teaches you class design, module separation, and game logic—all fundamental concepts for any aspiring developer. Customize your questions, add features, and challenge your friends. Happy coding!