w3resource

Trivia Quiz Game Project: CLI and GUI Solutions in Python


Trivia Quiz Game:

Develop a trivia quiz game with multiple-choice questions.

From Wikipedia - Trivia is information and data considered of little value. The word is derived from the Latin word triviae, meaning a place where a road splits into two (thus, creating a three-way intersection). It was introduced into English as the adjective trivial in the 15th and 16th centuries.

Modern usage of trivia dates back to the 1960s, when college students introduced question-and-answer contests to their universities. A board game, Trivial Pursuit, was released in 1982 in the same vein as these contests. Since its modern usage, trivia contests have been established at various academic levels as well as in casual venues such as bars and restaurants.

Input values:

User selects answers to multiple-choice questions presented by the trivia quiz game.

Output value:

Feedback on whether the selected answers are correct or incorrect, along with the final score at the end of the quiz.

Example:

Input values:
1. Select option (a, b, c, d) for Question 1: What is France's capital?
- User selects option: c) Paris
Output value:
Feedback: Correct! Paris is France's capital.
Input values:
2. Select option (a, b, c, d) for Question 2: Who painted the Mona Lisa?
- User selects option: b) Leonardo da Vinci
Output value:
Feedback: Correct! Leonardo da Vinci painted the Mona Lisa.
Input values:
3. Select option (a, b, c, d) for Question 3: What is the tallest mountain in the world?
- User selects option: d) Mount Everest
Output value:
Feedback: Correct! Mount Everest is the tallest mountain in the world.
Input values:
4. Select option (a, b, c, d) for Question 4: Who wrote "Romeo and Juliet"?
- User selects option: a) William Shakespeare
Output value:
Feedback: Correct! William Shakespeare wrote "Romeo and Juliet."
Input values:
5. Select option (a, b, c, d) for Question 5: What is the chemical symbol for water?
- User selects option: b) H2O
Output value:
Feedback: Correct! H2O is the chemical symbol for water.
Final output value:
Congratulations! You have completed the trivia quiz.
Your score is 5 out of 5.

Solution 1: Trivia Quiz Game Using a Command-Line Interface

This solution uses a simple command-line interface (CLI) to prompt the user with multiple-choice questions and collects answers.

Code:

# Solution 1: Trivia Quiz Game Using a Command-Line Interface

def display_question(question_data):
    """Display a question and its options."""
    print(question_data['question'])
    for option in question_data['options']:
        print(option)
    user_answer = input("Select an option (a, b, c, d): ").lower()
    return user_answer

def check_answer(user_answer, correct_answer):
    """Check if the user's answer is correct."""
    if user_answer == correct_answer:
        print("Feedback: Correct!")
        return True
    else:
        print(f"Feedback: Incorrect! The correct answer is {correct_answer}.")
        return False

def main():
    """Main function to run the trivia quiz game."""
    questions = [
        {"question": "What is France's capital?", "options": ["a) Lyon", "b) Marseille", "c) Paris", "d) Nice"], "answer": "c"},
        {"question": "Who painted the Mona Lisa?", "options": ["a) Vincent van Gogh", "b) Leonardo da Vinci", "c) Pablo Picasso", "d) Claude Monet"], "answer": "b"},
        {"question": "What is the tallest mountain in the world?", "options": ["a) K2", "b) Kangchenjunga", "c) Mount Kilimanjaro", "d) Mount Everest"], "answer": "d"},
        {"question": "Who wrote 'Romeo and Juliet'?", "options": ["a) William Shakespeare", "b) Charles Dickens", "c) Jane Austen", "d) Mark Twain"], "answer": "a"},
        {"question": "What is the chemical symbol for water?", "options": ["a) O2", "b) H2O", "c) CO2", "d) NaCl"], "answer": "b"},
    ]
    
    score = 0  # Initialize the score counter
    
    print("Welcome to the Trivia Quiz Game!")
    print("Answer the following questions by selecting the correct option (a, b, c, d):\n")
    
    # Loop through each question in the list
    for question_data in questions:
        user_answer = display_question(question_data)  # Display the question and get user input
        
        # Check if the answer is correct
        if check_answer(user_answer, question_data['answer']):
            score += 1  # Increment score if the answer is correct
    
    # Display the final score
    print(f"\nCongratulations! You have completed the trivia quiz.")
    print(f"Your score is {score} out of {len(questions)}.")

# Run the trivia quiz game
if __name__ == "__main__":
    main() 

Output:

Welcome to the Trivia Quiz Game!
Answer the following questions by selecting the correct option (a, b, c, d):

What is France's capital?
a) Lyon
b) Marseille
c) Paris
d) Nice
Select an option (a, b, c, d): c
Feedback: Correct!
Who painted the Mona Lisa?
a) Vincent van Gogh
b) Leonardo da Vinci
c) Pablo Picasso
d) Claude Monet
Select an option (a, b, c, d): a
Feedback: Incorrect! The correct answer is b.
What is the tallest mountain in the world?
a) K2
b) Kangchenjunga
c) Mount Kilimanjaro
d) Mount Everest
Select an option (a, b, c, d): d
Feedback: Correct!
Who wrote 'Romeo and Juliet'?
a) William Shakespeare
b) Charles Dickens
c) Jane Austen
d) Mark Twain
Select an option (a, b, c, d): a
Feedback: Correct!
What is the chemical symbol for water?
a) O2
b) H2O
c) CO2
d) NaCl
Select an option (a, b, c, d): b
Feedback: Correct!

Congratulations! You have completed the trivia quiz.
Your score is 4 out of 5. 

Explanation:

  • Function display_question:
    • Displays a question and its options, then collects the user's answer.
  • Function check_answer:
    • Checks if the user's answer is correct and returns a boolean result.
  • Main Function main:
    • Initializes the list of questions with their respective options and correct answers.
    • Iterates through each question to display it, collect the user's answer, and check if it's correct.
    • Keeps track of the user's score and displays the final score at the end.

Solution 2: Trivia Quiz Game with a Graphical User Interface Using PyQt5

This solution uses the PyQt5 library to create a graphical user interface (GUI) for the trivia quiz game.

Code:

# Solution 2: Trivia Quiz Game with a GUI Using PyQt5

from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget, QLabel, QPushButton, QMessageBox, QButtonGroup, QRadioButton
import sys

class TriviaQuizGame(QMainWindow):
    """Class to create a Trivia Quiz Game using PyQt5."""

    def __init__(self):
        """Initialize the TriviaQuizGame with the main PyQt5 window."""
        super().__init__()
        self.setWindowTitle("Trivia Quiz Game")
        self.setGeometry(100, 100, 400, 300)
        
        self.score = 0  # Initialize score
        self.current_question = 0  # Track the current question index
        self.questions = [
            {"question": "What is France's capital?", "options": ["a) Lyon", "b) Marseille", "c) Paris", "d) Nice"], "answer": "c"},
            {"question": "Who painted the Mona Lisa?", "options": ["a) Vincent van Gogh", "b) Leonardo da Vinci", "c) Pablo Picasso", "d) Claude Monet"], "answer": "b"},
            {"question": "What is the tallest mountain in the world?", "options": ["a) K2", "b) Kangchenjunga", "c) Mount Kilimanjaro", "d) Mount Everest"], "answer": "d"},
            {"question": "Who wrote 'Romeo and Juliet'?", "options": ["a) William Shakespeare", "b) Charles Dickens", "c) Jane Austen", "d) Mark Twain"], "answer": "a"},
            {"question": "What is the chemical symbol for water?", "options": ["a) O2", "b) H2O", "c) CO2", "d) NaCl"], "answer": "b"},
        ]
        
        # Set up the user interface
        self.setup_ui()
        self.show_question()

    def setup_ui(self):
        """Set up the user interface with labels, buttons, and radio buttons."""
        self.central_widget = QWidget()
        self.setCentralWidget(self.central_widget)
        self.layout = QVBoxLayout()

        # Question label
        self.question_label = QLabel(self)
        self.layout.addWidget(self.question_label)

        # Option buttons
        self.option_group = QButtonGroup(self)
        self.option_buttons = []
        for i in range(4):
            radio_button = QRadioButton(self)
            self.layout.addWidget(radio_button)
            self.option_group.addButton(radio_button)
            self.option_buttons.append(radio_button)

        # Next button
        self.next_button = QPushButton("Next", self)
        self.next_button.clicked.connect(self.next_question)
        self.layout.addWidget(self.next_button)

        self.central_widget.setLayout(self.layout)

    def show_question(self):
        """Display the current question and its options."""
        question_data = self.questions[self.current_question]
        self.question_label.setText(question_data['question'])
        
        for i, option in enumerate(question_data['options']):
            self.option_buttons[i].setText(option)
            self.option_buttons[i].setChecked(False)

    def next_question(self):
        """Handle the next button click event."""
        selected_button = self.option_group.checkedButton()

        # Check if an option is selected
        if not selected_button:
            QMessageBox.warning(self, "No Answer", "Please select an answer before proceeding.")
            return

        # Check if the selected answer is correct
        user_answer = selected_button.text()[0].lower()
        correct_answer = self.questions[self.current_question]['answer']
        
        if user_answer == correct_answer:
            self.score += 1
            QMessageBox.information(self, "Feedback", "Correct!")
        else:
            QMessageBox.information(self, "Feedback", f"Incorrect! The correct answer is {correct_answer.upper()}.")

        # Move to the next question or show the final score
        self.current_question += 1
        if self.current_question < len(self.questions):
            self.show_question()
        else:
            QMessageBox.information(self, "Quiz Completed", f"Congratulations! You have completed the trivia quiz.\nYour score is {self.score} out of {len(self.questions)}.")
            self.close()

# Run the PyQt5 trivia quiz game
app = QApplication(sys.argv)
window = TriviaQuizGame()
window.show()
sys.exit(app.exec_())

Output:

Python: Trivia Quiz Game.

Explanation:

  • PyQt5 Setup:
    • Initializes the PyQt5 main window, sets the title, and sets up the interface layout using widgets.
  • Question Handling:
    • Displays each question and options as radio buttons, allowing the user to select an answer.
  • Next Button Functionality:
    • When the user clicks "Next," the application checks if an answer is selected, provides feedback, and moves to the next question.
  • Final Score Display:
    • At the end of the quiz, a message box displays the final score.

Both solutions create a Trivia Quiz Game with multiple-choice questions, one using a command-line interface (CLI) and the other using a graphical user interface (GUI) with PyQt5. Each solution provides a different user experience while accomplishing the same core functionality of a trivia quiz game.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/projects/python/python-trivia-quiz-game-project.php