Quiz Game in Python

Introduction

The Quiz Game is an interactive, educational game where players answer multiple-choice questions from various topics. This Python implementation of the Quiz Game provides an engaging way to test your knowledge across different subjects. Players are presented with a series of questions, and they must choose the correct answer from four options. The game keeps track of the score, provides immediate feedback on the correctness of each answer, and uses text-to-speech functionality to read the questions and options aloud. This game is a great way to enhance your learning and have fun simultaneously.

Prerequisites

Before running the quiz game, ensure that you have the following installed and set up:

  • Python 3.x: The script is written in Python, so you need Python installed on your machine.
  • Libraries:
    • random: This library is part of the Python Standard Library.
    • pyttsx3: This library is used for text-to-speech conversion.
    • seaborn and matplotlib: These libraries are used for data visualization (plotting the quiz results).

Learning Objectives

By the end of this project, you should be able to:

  1. Understand how to use Python for basic game development.
  2. Utilize the random module for selecting random elements.
  3. Implement text-to-speech functionality using the pyttsx3
  4. Visualize data using seaborn and matplotlib.
  5. Write a program that integrates user input, control flow, and basic data visualization.

Installation Guide

Install Python:

Install Required Libraries:

  • Open a terminal or command prompt.
  • Run the following commands to install the required libraries: pip install pyttsx3 seaborn matplotlib

Download the Script:

  • Save the quiz game script provided in this documentation to a file named quiz_game.py.

Project Steps

  1. Initialization: Set up the question list, options list, correct answers list, and necessary global variables.
    • Define the questions, multiple-choice options, and correct answers.
    • Create lists for questions, corresponding options, and correct answers.
    • Initialize variables for keeping track of the score, count of correct and incorrect answers, and the list of asked question indices.
  2. User Input: Prompt players to input their answers (options) for each question.
    • Prompt for the player’s name.
    • Greet the player and wish them good luck for the quiz.
    • Display each question and its options.
    • Ask the player to choose an option by entering the corresponding number.
  3. Game Logic: Implement functions to update the game state, check for correct or incorrect answers, and provide feedback.
    • Function speak to read out text using the text-to-speech engine.
    • Function new_ans to check if the player’s selected option matches the correct answer.
    • Provide immediate feedback based on whether the answer is correct or incorrect.
    • Update the player’s score and keep track of the number of correct and incorrect answers.
    • Store feedback messages for correct and incorrect answers.
  4. Gameplay Loop: Run the game in a loop until the player answers a predetermined number of questions.
    • Randomly select and display a question and its options for each turn.
    • Continuously prompt the player for answers until all questions have been asked or the desired number of questions has been answered.
    • After each question, provide feedback and update the score.
    • End the game after the predetermined number of questions has been answered.
    • Display the final score and thank the player for participating.
  5. Visualization: Visualize the results of the quiz game.
    • Use matplotlib to create a pie chart showing the percentage of correct and incorrect answers.
    • Display the pie chart to provide a visual summary of the player’s performance.

By following these steps, you will create an interactive quiz game that engages players, tests their knowledge across various topics, and provides immediate feedback and visual results.

Code

				
					import random
import seaborn as sns
import matplotlib.pyplot as plt
import pyttsx3
engine = pyttsx3.init()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[1].id)
engine.setProperty('rate', 225)
ques=["What is the capital of India?",
   "Which river is considered the holiest river in India?",
   "Who was the first Prime Minister of India?",
   "Which Indian city is known as the 'Silicon Valley of India'?",
   "Which festival is known as the 'Festival of Lights' in India?",
   "Which planet is known as the Red Planet?",
   "Who wrote the play 'Romeo and Juliet'?",
   "What is the largest ocean on Earth?",
   "What is the capital city of Japan?",
   "Which element has the chemical symbol 'O'?",
   "Who is known as the father of modern physics?",
  "What is the smallest country in the world by land area?",
  "Which continent is known as the 'Dark Continent'?",
  "What is the main ingredient in traditional Japanese miso soup?",
  "In what year did the Titanic sink?",
  "Which country is known as the Land of the Rising Sun?",
  "What is the hardest natural substance on Earth?",
  "Which famous artist painted the Mona Lisa?",
  "What is the chemical formula for water?",
  "Who was the first President of the United States?"]
opt = [
  ["Mumbai", "Kolkata", "New Delhi", "Bangalore"],
  ["Yamuna", "Ganga", "Godavari", "Narmada"],
  ["Mahatma Gandhi", "Sardar Vallabhbhai Patel", "Jawaharlal Nehru", "Dr. B.R. Ambedkar"],
  ["Hyderabad", "Chennai", "Pune", "Bangalore"],
  ["Holi", "Diwali", "Eid", "Pongal"],
  ["Earth", "Mars", "Venus", "Jupiter"],
  ["William Shakespeare", "Charles Dickens", "Mark Twain", "Jane Austen"],
  ["Atlantic Ocean", "Indian Ocean", "Arctic Ocean", "Pacific Ocean"],
  ["Beijing", "Seoul", "Tokyo", "Bangkok"],
  ["Gold", "Oxygen", "Silver", "Hydrogen"],
  ["Isaac Newton", "Albert Einstein", "Galileo Galilei", "Niels Bohr"],
  ["Monaco", "San Marino", "Liechtenstein", "Vatican City"],
  ["Asia", "Africa", "South America", "Antarctica"],
  ["Tofu", "Seaweed", "Miso paste", "Rice"],
  ["1912", "1905", "1915", "1920"],
  ["China", "Japan", "South Korea", "Thailand"],
  ["Gold", "Diamond", "Iron", "Quartz"],
  ["Vincent van Gogh", "Pablo Picasso", "Leonardo da Vinci", "Michelangelo"],
  ["CO2", "H2O", "O2", "H2SO4"],
  ["Thomas Jefferson", "John Adams", "Abraham Lincoln", "George Washington"]
]
corr1 = [
  "New Delhi", "Ganga", "Jawaharlal Nehru", "Bangalore", "Diwali", "Mars",
  "William Shakespeare", "Pacific Ocean", "Tokyo", "Oxygen", "Albert Einstein",
  "Vatican City", "Africa", "Miso paste", "1912", "Japan", "Diamond",
  "Leonardo da Vinci", "H2O", "George Washington"
]
c_exc = [
    "Hurray!! your answer is correct ",
    "Well done!! your answer is correct",
    "Excellent!!your answer is correct",
    "Fantastic!!your answer is correct",
    "Bravo!!you are doing great",
    "You got it!!your answer is correct",
    "Great job!!you are doing well",
    "Perfect!!your answer is correct",
    "Spot on!!your answer is correct",
]


ic_exc = [
    "Oops!!your answer is incorrect",
    "Oh no!!your answer is incorrect ",
    "Not quite!!you are wrong",
    "your answer is wrong.Better luck next time!!",
    "your answer is Close, but not quite!!",
    "Sorry, that's wrong!!",
    "Unfortunately, your answer is wrong!!",
    "your answer is wrong.Maybe next time!!"
]
def speak(text):
    engine.say(text)
    engine.runAndWait()
def new_ans(ans):
    idx = ans-1
    flag = True
    if opt[a][idx]==corr1[a]: flag=True
    else                : flag=False
    return flag
name=input("enter your name.\n")
speak(f"Hello {name} ! All the best for your quiz")
print("--------------------YOUR QUESTIONS ARE ON YOUR SCREEN--------------------")

idx=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19]
score=0
cc=0 #count for correct
cw=0 #count for incorrect
for i in range(10):
    a=random.choice(idx)
    idx.remove(a)
    print(f"Q {i+1}: {ques[a]}\n")
    speak(f"{ques[a]}")
    random.shuffle(opt[a])
    for j in range(4):
        print(f"{j+1}: {opt[a][j]}")
        speak(f"{j+1}: {opt[a][j]}")    
    speak("Enter your answer.")
    ans=int(input("Enter your answer: "))
    new_ans(ans) 
    if new_ans(ans):
        score+=10
        cc+=1
        print(f"your answer is correct. +10\nScore is {score}\n")
        #rm=random.choice(c_exc)
        speak(f"{random.choice(c_exc)}")
        speak(f"your score is {score}")
    else:
        score-=5
        cw+=1
        print(f"your answer is incorrect. -5\nScore is {score}\n")
        #rm=random.choice(ic_exc)
        speak(f"{random.choice(ic_exc)}")
        speak(f"your score is {score}")        
    print("--------------------------------------------------------------------------------")
print(f"final score is:{score}/100")
print("--------------------Thanks for giving us your valuable time--------------------.")
print("--------------------I hope you enjoyed giving this quiz.--------------------")
speak(f"Your final score is {score} out of 100 marks.")
speak("Thanks for giving us your valuable time. I hope you enjoyed giving this quiz")
#visualising result
a=["correct","incorrect"]
b=[cc,cw]
plt.pie(b,labels=a, autopct='%.2f%%')
plt.show()

				
			

Code

				
					import random
import seaborn as sns
import matplotlib.pyplot as plt
import pyttsx3
engine = pyttsx3.init()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[1].id)
engine.setProperty('rate', 225)
ques=["What is the capital of India?",
   "Which river is considered the holiest river in India?",
   "Who was the first Prime Minister of India?",
   "Which Indian city is known as the 'Silicon Valley of India'?",
   "Which festival is known as the 'Festival of Lights' in India?",
   "Which planet is known as the Red Planet?",
   "Who wrote the play 'Romeo and Juliet'?",
   "What is the largest ocean on Earth?",
   "What is the capital city of Japan?",
   "Which element has the chemical symbol 'O'?",
   "Who is known as the father of modern physics?",
  "What is the smallest country in the world by land area?",
  "Which continent is known as the 'Dark Continent'?",
  "What is the main ingredient in traditional Japanese miso soup?",
  "In what year did the Titanic sink?",
  "Which country is known as the Land of the Rising Sun?",
  "What is the hardest natural substance on Earth?",
  "Which famous artist painted the Mona Lisa?",
  "What is the chemical formula for water?",
  "Who was the first President of the United States?"]
opt = [
  ["Mumbai", "Kolkata", "New Delhi", "Bangalore"],
  ["Yamuna", "Ganga", "Godavari", "Narmada"],
  ["Mahatma Gandhi", "Sardar Vallabhbhai Patel", "Jawaharlal Nehru", "Dr. B.R. Ambedkar"],
  ["Hyderabad", "Chennai", "Pune", "Bangalore"],
  ["Holi", "Diwali", "Eid", "Pongal"],
  ["Earth", "Mars", "Venus", "Jupiter"],
  ["William Shakespeare", "Charles Dickens", "Mark Twain", "Jane Austen"],
  ["Atlantic Ocean", "Indian Ocean", "Arctic Ocean", "Pacific Ocean"],
  ["Beijing", "Seoul", "Tokyo", "Bangkok"],
  ["Gold", "Oxygen", "Silver", "Hydrogen"],
  ["Isaac Newton", "Albert Einstein", "Galileo Galilei", "Niels Bohr"],
  ["Monaco", "San Marino", "Liechtenstein", "Vatican City"],
  ["Asia", "Africa", "South America", "Antarctica"],
  ["Tofu", "Seaweed", "Miso paste", "Rice"],
  ["1912", "1905", "1915", "1920"],
  ["China", "Japan", "South Korea", "Thailand"],
  ["Gold", "Diamond", "Iron", "Quartz"],
  ["Vincent van Gogh", "Pablo Picasso", "Leonardo da Vinci", "Michelangelo"],
  ["CO2", "H2O", "O2", "H2SO4"],
  ["Thomas Jefferson", "John Adams", "Abraham Lincoln", "George Washington"]
]
corr1 = [
  "New Delhi", "Ganga", "Jawaharlal Nehru", "Bangalore", "Diwali", "Mars",
  "William Shakespeare", "Pacific Ocean", "Tokyo", "Oxygen", "Albert Einstein",
  "Vatican City", "Africa", "Miso paste", "1912", "Japan", "Diamond",
  "Leonardo da Vinci", "H2O", "George Washington"
]
c_exc = [
    "Hurray!! your answer is correct ",
    "Well done!! your answer is correct",
    "Excellent!!your answer is correct",
    "Fantastic!!your answer is correct",
    "Bravo!!you are doing great",
    "You got it!!your answer is correct",
    "Great job!!you are doing well",
    "Perfect!!your answer is correct",
    "Spot on!!your answer is correct",
]

ic_exc = [
    "Oops!!your answer is incorrect",
    "Oh no!!your answer is incorrect ",
    "Not quite!!you are wrong",
    "your answer is wrong.Better luck next time!!",
    "your answer is Close, but not quite!!",
    "Sorry, that's wrong!!",
    "Unfortunately, your answer is wrong!!",
    "your answer is wrong.Maybe next time!!"
]
def speak(text):
    engine.say(text)
    engine.runAndWait()
def new_ans(ans):
    idx = ans-1
    flag = True
    if opt[a][idx]==corr1[a]: flag=True
    else                : flag=False
    return flag

name=input("enter your name.\n")
speak(f"Hello {name} ! All the best for your quiz")
print("--------------------YOUR QUESTIONS ARE ON YOUR SCREEN--------------------")

idx=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19]
score=0
cc=0 #count for correct
cw=0 #count for incorrect
for i in range(10):
    a=random.choice(idx)
    idx.remove(a)
    print(f"Q {i+1}: {ques[a]}\n")
    speak(f"{ques[a]}")
    random.shuffle(opt[a])
    for j in range(4):
        print(f"{j+1}: {opt[a][j]}")
        speak(f"{j+1}: {opt[a][j]}")    
    speak("Enter your answer.")
    ans=int(input("Enter your answer: "))
    new_ans(ans) 
    if new_ans(ans):
        score+=10
        cc+=1
        print(f"your answer is correct. +10\nScore is {score}\n")
        #rm=random.choice(c_exc)
        speak(f"{random.choice(c_exc)}")
        speak(f"your score is {score}")
    else:
        score-=5
        cw+=1
        print(f"your answer is incorrect. -5\nScore is {score}\n")
        #rm=random.choice(ic_exc)
        speak(f"{random.choice(ic_exc)}")
        speak(f"your score is {score}")        
    print("--------------------------------------------------------------------------------")
print(f"final score is:{score}/100")
print("--------------------Thanks for giving us your valuable time--------------------.")
print("--------------------I hope you enjoyed giving this quiz.--------------------")
speak(f"Your final score is {score} out of 100 marks.")
speak("Thanks for giving us your valuable time. I hope you enjoyed giving this quiz")

#visualising result
a=["correct","incorrect"]
b=[cc,cw]
plt.pie(b,labels=a, autopct='%.2f%%')
plt.show()

				
			

Pseudo Code explaining this Python Project

				
					INITIALIZATION:
•	Import random module
•	Import pyttsx3 module
•	Import seaborn and matplotlib.pyplot modules
•	Initialize text-to-speech engine
•	Set voice properties for text-to-speech engine
•	Define questions list with corresponding questions
•	Define options list with multiple-choice options for each question
•	Define correct answers list
DEFINE HELPER FUNCTIONS:
•	Function speak(text):
o	Use text-to-speech engine to say the given text
•	Function new_ans(ans):
o	Check if the selected option matches the correct answer for the current question
o	Return True if correct, otherwise False
MAIN GAME LOOP:
•	Prompt player to enter their name
•	Use text-to-speech to greet the player and wish them good luck
•	Initialize list of question indices
•	Initialize score to 0
•	Initialize count of correct answers (cc) to 0
•	Initialize count of incorrect answers (cw) to 0
•	Loop for a predetermined number of questions (e.g., 10):
o	Randomly select an index from the list of question indices
o	Remove the selected index from the list
o	Display the current question and its options
o	Use text-to-speech to read the question and options aloud
o	Prompt player to enter their answer by selecting a number corresponding to an option
o	Call new_ans(ans) to check if the answer is correct
o	If answer is correct:
	Increment score by 10
	Increment count of correct answers (cc)
	Provide positive feedback
	Use text-to-speech to read feedback and current score
o	If answer is incorrect:
	Decrement score by 5
	Increment count of incorrect answers (cw)
	Provide negative feedback
	Use text-to-speech to read feedback and current score
•	After all questions are answered:
o	Display final score
o	Use text-to-speech to announce the final score
o	Thank player for participating
•	Visualize results:
o	Create a pie chart showing percentage of correct and incorrect answers
o	Display the pie chart

				
			

Pseudo Code explaining this Python Project

				
					INITIALIZATION:
•	Import random module
•	Import pyttsx3 module
•	Import seaborn and matplotlib.pyplot modules
•	Initialize text-to-speech engine
•	Set voice properties for text-to-speech engine
•	Define questions list with corresponding questions
•	Define options list with multiple-choice options for each question
•	Define correct answers list
DEFINE HELPER FUNCTIONS:
•	Function speak(text):
o	Use text-to-speech engine to say the given text
•	Function new_ans(ans):
o	Check if the selected option matches the correct answer for the current question
o	Return True if correct, otherwise False
MAIN GAME LOOP:
•	Prompt player to enter their name
•	Use text-to-speech to greet the player and wish them good luck
•	Initialize list of question indices
•	Initialize score to 0
•	Initialize count of correct answers (cc) to 0
•	Initialize count of incorrect answers (cw) to 0
•	Loop for a predetermined number of questions (e.g., 10):
o	Randomly select an index from the list of question indices
o	Remove the selected index from the list
o	Display the current question and its options
o	Use text-to-speech to read the question and options aloud
o	Prompt player to enter their answer by selecting a number corresponding to an option
o	Call new_ans(ans) to check if the answer is correct
o	If answer is correct:
	Increment score by 10
	Increment count of correct answers (cc)
	Provide positive feedback
	Use text-to-speech to read feedback and current score
o	If answer is incorrect:
	Decrement score by 5
	Increment count of incorrect answers (cw)
	Provide negative feedback
	Use text-to-speech to read feedback and current score
•	After all questions are answered:
o	Display final score
o	Use text-to-speech to announce the final score
o	Thank player for participating
•	Visualize results:
o	Create a pie chart showing percentage of correct and incorrect answers
o	Display the pie chart

				
			

Flow Chart

Quiz in Python

Code Explanation

  1. Imports:
    • import random: Used to randomly select questions from the list.
    • import pyttsx3: Used for text-to-speech functionality to read questions and options aloud.
    • import seaborn as sns and import matplotlib.pyplot as plt: Used for visualizing the quiz results.
  2. Question, Options, and Correct Answers Lists:
    • ques: A list of questions to be asked in the quiz.
    • opt: A list of lists, where each sublist contains the multiple-choice options for the corresponding question.
    • corr1: A list of correct answers corresponding to each question.
  3. Feedback Messages:
    • c_exc: A list of feedback messages for correct answers.
    • ic_exc: A list of feedback messages for incorrect answers.
  4. Helper Functions:
    • speak(text): Uses the pyttsx3 library to convert the given text to speech.
    • new_ans(ans): Checks if the player’s selected option matches the correct answer for the current question.
  5. Main Game Loop:
    • Welcome Message and Player Name:
      • Prompts the player to enter their name.
      • Uses text-to-speech to greet the player and wish them good luck.
    • Initialization:
      • Initializes a list of question indices to keep track of which questions have been asked.
      • Initializes variables for the score, count of correct answers (cc), and count of incorrect answers (cw).
    • Gameplay:
      • Loops through 10 questions, randomly selecting and removing an index from the list of question indices.
      • Displays the current question and its multiple-choice options.
      • Uses text-to-speech to read the question and options aloud.
      • Prompts the player to enter their answer by selecting a number corresponding to one of the options.
      • Calls new_ans(ans) to check if the answer is correct.
      • Updates the score and provides feedback based on the correctness of the answer.
      • Uses text-to-speech to read out the feedback and current score.
    • End of Game:
      • Displays the final score after all questions have been answered.
      • Uses text-to-speech to announce the final score.
      • Thanks the player for participating and hopes they enjoyed the quiz.
    • Visualization:
      • Uses matplotlib to create a pie chart showing the percentage of correct and incorrect answers.

Displays the pie chart to provide a visual summary of the player’s performance.

Challenges and Solutions

Challenge: Integrating text-to-speech functionality.

  • Solution: Used the pyttsx3 library to read questions and options aloud.

Challenge: Randomly selecting questions without repetition.

  • Solution: Used the random library and a list to keep track of asked questions.

Challenge: Providing immediate feedback and updating the score.

  • Solution: Created functions to handle answer checking and feedback generation.

Testing

Test the program by running it multiple times and ensuring:

  • Questions and options are displayed correctly.
  • The text-to-speech function reads the questions and options correctly.
  • The score is updated accurately based on the user’s answers.
  • The pie chart displays the correct and incorrect answer distribution.

Additional Resources

FAQs

Q1: Can I add more questions to the quiz?

  • Yes, you can add more questions, options, and correct answers to the respective lists in the script.

Q2: How can I change the voice or speed of the text-to-speech engine?

  • You can modify the engine.setProperty(‘voice’, voices[1].id) and engine.setProperty(‘rate’, 225) lines to change the voice and speed.

Q3: What if I encounter an error with the text-to-speech library?

Q4: Can I change the scoring system?

  • Yes, you can modify the scoring logic within the main quiz loop to adjust how points are awarded or deducted.

Project by Anushka Khemaria, Team edSlash.