0% found this document useful (0 votes)
12 views48 pages

Quiz Game

cbjfbvjrrn

Uploaded by

durga
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views48 pages

Quiz Game

cbjfbvjrrn

Uploaded by

durga
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

PRINCE SRIVARI SENIOR SECONDARY

SCHOOL

12, KANNAGI STREET, MADIPAKKAM,


CHENNAI – 600091
ACADEMIC YEAR: 2023 – 2024

COMPUTER SCIENCE PROJECT


TITLE : QUIZ GAME

NAME :

CLASS & SEC : XI - A

REGISTER NUMBER :
QUIZ GAME

TEAM MEMBERS:
ADHARSH RAM.B

DEVESHWAR.S

VENKATESH.K
Mrs.Prathipa Baskaran Date:

Prince Srivari Senior Secondary School

No-12,Kannagi Street, Madipakkam, Chennai-91.

CERTIFICATE

This is to certify that the project work entitled QUIZ GAME was done

under my supervision.

The project work was submitted by of class ‘XI-A’ as a part of the

assessment in AISSCE Computer Science Practical Examination. This is the

original work done by the candidate during the academic year 2023-2024.

SIQNATURE OF PRINCIPAL SIGNATURE OF THE SUBJECT

TEACHER IN-CHARGE

SIGNATURE OF THE INTERNAL SIGNATURE OF THE EXTERNAL

EXAMINAR EXAMINAR

SCHOOL SEAL
ACKNOWLEDGEMENT

I thank my principal Mrs. K.S. SHARMILA for giving me a


wonderful opportunity to do this project.

I also thank my teacher Mrs.PRATHIPA BASKARAN who


guided and helped in completing this project. I would also like to
thank my parents, who helped me in completing this project
successfully. I would also like to thank my friends, who helped me in
completing the project.
INDEX

S.NO TOPIC PAGE


NO.
1 ABSTRACT 6

2 INTRODUCTION 7

3 OBJECTIVE 8

4 MODULE DESCRIPTION 9

5 SYSTEM REQUIREMENTS 11

6 SOURCE CODE 19

7 OUTPUT 41

8 ADVANTAGES 43

9 CONCLUSIONS 45

10 REFERENCES 46
ABSTRACT
A quiz is a form of game or mind sport in which players
attempt to answer questions correctly on one or several specific
topics. Quizzes can be used as a brief assessment in education and
similar fields to measure growth in knowledge, abilities, and skills, or
simply as a hobby.

The Objective behind to organize Quiz competition is


to evaluate the knowledge of the participants within academics as
well as beyond academics and to make them familiar with the
prospects of quizzes and the objectivity of the questions.

A Quiz game to a short test of knowledge, typically


around 10 questions in length, with question formats often including
multiple choice, fill in the blanks, true or false and short answer.
School quiz game is a form of game, in which the players attempt to
answer a series of questions correctly, to test their knowledge about
specific subjects.

The main features of a quiz are Quiz timer, View


correct answer options, View question results, Question pool,
Randomize questions, Provides the IQ of the person according to how
many the questions the person answered correctly.

This 'QUIZ GAME' Project is designed for a question


in which you can generate and manage a simple database for
questions. The question number is automatically generated by the
software and is stored in a binary file by the name 'QUESTION'.
INTRODUTION
The program has features that are provided below

Game Structure: The Quiz Game class is initialized with attributes


such as player profiles, rounds, current round, leaderboard, timer interval,
answered within time limit flag, user answer, and the number of questions per
round. Players can choose subjects, and questions are loaded based on the
chosen subject from predefined question pools.

Player Profiles: Player profiles store information about each player,


including their score, consecutive correct answers, and an IQ level.

Question Pools: Separate question pools exist for Physics,


Mathematics, Chemistry, and Computer Science. Each question in the pool
includes the question itself, options, correct answer index, and an explanation.
Timer Functionality: The timer_thread function uses threading to
manage the timer for each question, ensuring players respond within a specified
time limit.

Game Rounds: Players take turns answering questions in each round.


Unique questions are randomly selected for each player in a round, and scores
are updated accordingly. Players receive bonus points for consecutive correct
answers.

Scoring and Leaderboard: Scores are displayed at the end of each


round. The overall leaderboard is updated based on players' scores. Final scores
include bonus points for consecutive correct answers.

IQ Level Calculation: The calculate_final_scores method determines


IQ levels based on the number of correct answers.

Game End: The game concludes after a specified number of rounds,


and the final leaderboard with scores and IQ levels is displayed.

User Interaction: The game prompts users for input, such as the
number of players, player names, subject choices, time limits, and answers.

Error Handling: The code incorporates error handling for input


validation, ensuring positive integer inputs.
OBJECTIVE
 INCREASES IQ:

A person IQ is increases when he/she gets to answer the


question. They get to know more about the subjects and
increases their chances of getting more marks in the test.

 EASY TO ACCESS:
This program is very easy to access as it does not have
any special request to do so. As the program asks input which are
easy to understand.

 USER SPECIFIC:

The program is user specific as it provides what the


user needs. That is the program asks the user how many
questions to be asked and also asks how much time needed to
finish the question as it asks for each question

 MODIFICATION:

The program is modifiable as the questions in program


can be changed or altered or questions can be added.
MODULE DESCRIPTION

1. *Class Structure:*
- QuizGame: Represents the main class for the quiz game.
- Attributes:
- player_profiles: Dictionary to store player information,
including scores, consecutive correct answers, and IQ levels.
- rounds: Total number of rounds in the game.
- current_round: Tracks the current round being played.
- leaderboard: Dictionary to keep track of players' total
scores.
- timer_interval: Interval for updating the timer in seconds.
- answered_within_time_limit: Flag to track whether a player
answered within the time limit.
- user_answer: Stores the user's answer during the quiz.
- num_questions_per_round: Number of questions to ask in
each round.

2. *Methods:*
- display_intro: Displays introductory messages to players.
- initialize_player_profiles: Takes input to initialize player
profiles.
- get_positive_integer_input: Takes user input and ensures it is
a positive integer.
- time_is_up: Prints a message when the time for answering a
question is up.
- timer_thread: Manages a timer for each question in a
separate thread.
- choose_subject: Allows players to choose a subject for the
current round.
- load_question_pool: Loads questions based on the chosen
subject.
- display_scores: Displays scores for each player.
- play_round: Conducts a round of the quiz game for each
player.
- update_leaderboard: Updates the overall leaderboard based
on players' scores.
- display_winner: Displays the winner(s) of the quiz game.
- play_game: Orchestrates the entire quiz game, including
rounds and final results.
- calculate_final_scores: Calculates final scores, considering
bonus points for consecutive correct answers.
- determine_iq_level: Determines IQ level based on the
number of correct answers.
- display_leaderboard: Displays the final leaderboard with
scores and IQ levels.

3. *Execution:*
- An instance of the QuizGame class is created, and the
play_game method is called to start the game.
SYSTEM REQUIREMENTS

1. *Python Interpreter:*
- Ensure that you have Python installed on your system. The
code appears to be compatible with Python 3.

2. *Threading Support:*
- The program uses threading to manage timers. Most standard
Python installations include threading support, so this should not
be an issue.

3. *Standard Input/Output:*
- The code relies on standard input (input()) and output
(print()) for user interaction. Ensure that your system supports
these standard I/O operations.

4. *Random Module:*
- The usage of the random module for question selection
assumes that the Python interpreter includes the random module,
which is a part of the standard library.

5. *Datetime Module:*
- The datetime module is used for handling time-related
operations. This module is a standard part of Python.

6. *System Resources:*
- The program should not have demanding system resource
requirements. It primarily relies on basic Python functionality
and does not involve complex computations.
7. *Console/Command-Line Execution:*
- The program is designed to be run in a console or command-
line environment. Ensure that you can run Python scripts from
your terminal or command prompt.

To run the program:

1. Save the code to a Python file (e.g., quiz_game.py).


2. Open a terminal or command prompt.
3. Navigate to the directory containing the Python file.
4. Run the script using the command: python quiz_game.py (or
python3 quiz_game.py depending on your Python installation).
FLOWCHART

Start game
1. *Python Interpreter:*

Set up the game


(Initialize the game)set Up
Game

Display the welcome message


jgggghgjgand how to play

Enter how many players that are


going to play Initialize
Player
Enter the name of
t the player(s) Loop
over rounds

Choose the subject


(Mathematics, Computer science,
Physics, Chemistry)Loop over
players

NO
If subject ==
Mathematics

YES
NO

YES
If subject==
NNPhysics

NO

YES If subject ==
Chemistry

NO

YES
If subject ==
Computer science

NO
Enter how many
mquestions for the
Print invalid
njnkkround
subject
Display the
questionste Scores

Enter the time limit for


hghgjthe questiondisplay
Feedback

Enter option for the


jhgmhmgqueston End of

NO
If the option is
correct

YES
Print correct Print wrong
option option

Print earned a Print


point explanation

Loop of the questions asked for


jgmhfgyfeach players Display

Calculate the IQ using pointssplay


Scores

Print the scores of


player(s)
Print the consecutive
scores of the player(s)

Print the IQ level


of the person

End game
SOURCE CODE
import random

import threading

import datetime

import time

class QuizGame:

def _init_(self):

# Initialization of the game state

self.player_profiles = {}

self.rounds = 1

self.current_round = 1

self.leaderboard = {}

self.timer_interval = 1 # Timer update interval in seconds

self.answered_within_time_limit = False # Added variable

self.user_answer = None # Added variable

self.num_questions_per_round = 5 # Added variable for the


number of questions per round

def display_intro(self):

# Display introductory messages to the players

print("Welcome to the Multiplayer Quiz Game!")


print("Test your knowledge with a variety of questions.")

print("For each question, choose the correct option.")

print("Players will take turns answering questions.")

print("Earn bonus points for quick and consecutive correct


answers!\n")

def initialize_player_profiles(self, players):

# Initialize player profiles, including name, score, etc.

self.player_profiles = {}

for player in range(1, players + 1):

player_name = input(f"Enter the name of Player {player}: ")

self.player_profiles[player_name] = {"score": 0,
"consecutive_correct": 0, "iq_level": ""}

def get_positive_integer_input(self, prompt):

while True:

try:

value = int(input(prompt))

if value > 0:

return value

else:

print("Please enter a positive integer.")


except ValueError:

print("Invalid input. Please enter a positive integer.")

def time_is_up(self):

print("Time is up! You didn't answer within the time limit.")

def timer_thread(self, start_time, time_limit):

elapsed_time = (datetime.datetime.now() - start_time).seconds

remaining_time = time_limit - elapsed_time

while remaining_time > 0 and not


self.answered_within_time_limit:

time.sleep(1)

elapsed_time = (datetime.datetime.now() - start_time).seconds

remaining_time = time_limit - elapsed_time

if not self.answered_within_time_limit:

self.time_is_up()

def choose_subject(self):

# Allow players to choose a subject for the current round


subjects = ["Physics", "Mathematics", "Chemistry", "Computer
Science"]

subject = input(f"Choose a subject for the current round: {',


'.join(subjects)}\n").title()

if subject in subjects:

return subject

else:

print("Invalid subject choice. Please choose a valid subject.")

return self.choose_subject()

def load_question_pool(self, subject):

physics_questions = [

{"question": "What is the SI unit of force?", "options":


["Newton", "Joule", "Watt", "Pascal"], "answer": 1, "explanation":
"The SI unit of force is the Newton (N)."},

{"question": "What is Newton's second law of motion?",


"options": ["F = ma", "E = mc^2", "P = mv", "a = F/m"], "answer": 1,
"explanation": "Newton's second law states that force (F) is equal to
mass (m) multiplied by acceleration (a)."},

{"question": "What is the SI unit of electric current?",


"options": ["Volt", "Ampere", "Ohm", "Watt"], "answer": 2,
"explanation": "The SI unit of electric current is the Ampere (A)."},

{"question": "Which law of thermodynamics states that


energy cannot be created or destroyed, only converted from one form
to another?", "options": ["Zeroth Law", "First Law", "Second Law",
"Third Law"], "answer": 2, "explanation": "The First Law of
Thermodynamics, also known as the Law of Energy Conservation,
states that energy is conserved in any physical process."},

{"question": "What is the formula for calculating kinetic


energy?", "options": ["E = mc^2", "E = hf", "E = 1/2mv²", "E =
mgh"], "answer": 3, "explanation": "The kinetic energy (E) of an
object is calculated using the formula E = 1/2mv², where m is the
mass and v is the velocity."},

{"question": "Which type of electromagnetic wave has the


shortest wavelength?", "options": ["Radio waves", "Microwaves",
"Infrared", "Gamma rays"], "answer": 4, "explanation": "Gamma rays
have the shortest wavelength among the given options. They are a
form of electromagnetic radiation with high frequency and energy."},

{"question": "What is the law of reflection?", "options":


["The angle of incidence is equal to the angle of reflection", "The
angle of incidence is greater than the angle of reflection", "The angle
of incidence is less than the angle of reflection", "The angles of
incidence and reflection are unrelated"], "answer": 1, "explanation":
"According to the law of reflection, the angle of incidence is equal to
the angle of reflection when light reflects off a surface."},

{"question": "What is the unit of measure for electric


resistance?", "options": ["Ohm", "Watt", "Ampere", "Volt"],
"answer": 1, "explanation": "The unit of measure for electric
resistance is the Ohm (Ω)."},

{"question": "What is the SI unit of magnetic flux?",


"options": ["Weber", "Tesla", "Henry", "Coulomb"], "answer": 1,
"explanation": "The SI unit of magnetic flux is the Weber (Wb)."},

{"question": "In which state of matter are particles highly


organized in a fixed, repeating pattern?", "options": ["Solid",
"Liquid", "Gas", "Plasma"], "answer": 1, "explanation": "In the solid
state, particles are closely packed in a fixed, repeating pattern, giving
the substance a definite shape and volume."},

{"question": "What is the principle of conservation of


momentum?", "options": ["The total energy of an isolated system
remains constant", "The total linear momentum of an isolated system
remains constant", "The total angular momentum of an isolated
system remains constant", "The total charge of an isolated system
remains constant"], "answer": 2, "explanation": "The principle of
conservation of momentum states that the total linear momentum of
an isolated system remains constant if no external forces act on it."},

{"question": "What is the formula for calculating


gravitational potential energy?", "options": ["E = mc^2", "E = hf", "E
= 1/2mv²", "E = mgh"], "answer": 4, "explanation": "The
gravitational potential energy (E) of an object is calculated using the
formula E = mgh, where m is the mass, g is the acceleration due to
gravity, and h is the height."},

{"question": "What is the phenomenon where light waves


change direction as they pass from one medium to another?",
"options": ["Reflection", "Refraction", "Diffraction", "Interference"],
"answer": 2, "explanation": "Refraction is the phenomenon where
light waves change direction as they pass from one medium to
another, due to a change in speed."},

{"question": "Which law of motion is described by the


equation F = ma?", "options": ["Newton's First Law", "Newton's
Second Law", "Newton's Third Law", "Law of Universal
Gravitation"], "answer": 2, "explanation": "Newton's Second Law of
Motion is described by the equation F = ma, where F is the force
applied to an object, m is its mass, and a is its acceleration."}
# Add more physics questions with explanations as needed

math_questions = [

{"question": "What is the result of 2 + 3?", "options": ["4",


"5", "6", "7"], "answer": 2, "explanation": "2 + 3 = 5"},

{"question": "Solve for x: 2x - 8 = 12", "options": ["5", "8",


"10", "12"], "answer": 3, "explanation": "Add 8 to both sides, then
divide by 2: x = 10"},

{"question": "What is the square root of 64?", "options":


["6", "8", "10", "12"], "answer": 2, "explanation": "The square root of
64 is 8"},

{"question": "What is the area of a square with a side length


of 5 units?", "options": ["20 square units", "25 square units", "30
square units", "35 square units"], "answer": 2, "explanation": "The
area of a square is calculated by squaring the length of one of its
sides. For a square with a side length of 5 units, the area is 25 square
units."},

{"question": "Solve for x: 3x + 7 = 16", "options": ["2", "3",


"4", "5"], "answer": 2, "explanation": "Subtract 7 from both sides,
then divide by 3: x = 3."},

{"question": "What is the value of Ï (pi) to two decimal


places?", "options": ["3.14", "3.16", "3.18", "3.20"], "answer": 1,
"explanation": "The value of Ï to two decimal places is
approximately 3.14."},

{"question": "If a triangle has angles measuring 45 degrees,


45 degrees, and 90 degrees, what type of triangle is it?", "options":
["Equilateral", "Isosceles", "Scalene", "Right-angled"], "answer": 4,
"explanation": "A triangle with angles measuring 45 degrees, 45
degrees, and 90 degrees is a right-angled triangle."},

{"question": "What is the result of 4 factorial (4!)?",


"options": ["12", "24", "36", "48"], "answer": 2, "explanation": "4
factorial (4!) is the product of all positive integers up to 4: 4! = 4 x 3 x
2 x 1 = 24."},

{"question": "If a rectangle has a length of 8 units and a


width of 5 units, what is its perimeter?", "options": ["18 units", "26
units", "34 units", "40 units"], "answer": 2, "explanation": "The
perimeter of a rectangle is calculated by adding the lengths of all its
sides. For a rectangle with a length of 8 units and a width of 5 units,
the perimeter is 2(8 + 5) = 2 x 13 = 26 units."},

{"question": "What is the sum of the interior angles of a


hexagon?", "options": ["180 degrees", "360 degrees", "540 degrees",
"720 degrees"], "answer": 3, "explanation": "The sum of the interior
angles of a polygon is given by the formula (n-2) * 180 degrees,
where n is the number of sides. For a hexagon, it is (6-2) * 180 = 4 *
180 = 540 degrees."},

{"question": "If a right-angled triangle has legs of length 3


units and 4 units, what is the length of the hypotenuse?", "options":
["5 units", "6 units", "7 units", "8 units"], "answer": 1, "explanation":
"The length of the hypotenuse in a right-angled triangle can be
calculated using the Pythagorean theorem: c² = a² + b², where c
is the hypotenuse, and a and b are the legs. In this case, c = √(3² +
4²) = 5 units."},

{"question": "Solve for x: 2x**2 - 5x + 3 = 0", "options":


["x = 1", "x = 2", "x = 3", "x = -1"], "answer": 3, "explanation": "To
solve the quadratic equation 2x² - 5x + 3 = 0, factor or use the
quadratic formula. The solutions are x = 3 and x = 1/2."},

{"question": "What is the value of sin(60 degrees)?",


"options": ["0.5", "√3/2", "1/2", "√2/2"], "answer": 2,
"explanation": "In a 60-90-30 triangle, the sine of 60 degrees is
√3/2."},

{"question": "If a circle has a radius of 6 units, what is its


circumference?", "options": ["6Ï units", "12Ï units", "18Ï units",
"24Ï units"], "answer": 2, "explanation": "The circumference of a
circle is given by the formula C = 2Ï r, where r is the radius. For a
circle with a radius of 6 units, the circumference is 2Ï (6) = 12Ï
units."},

{"question": "What is the value of logâ‚‚(8)?", "options":


["2", "3", "4", "5"], "answer": 1, "explanation": "The logarithm base 2
of 8 is the exponent to which 2 must be raised to get 8. Therefore,
logâ‚‚(8) = 3."}

# Add more math questions with explanations as needed

chemistry_questions = [

{"question": "What is the chemical symbol for water?",


"options": ["H2O", "CO2", "O2", "CH4"], "answer": 1, "explanation":
"The chemical symbol for water is H2O."},

{"question": "Which element has the symbol 'Fe'?",


"options": ["Iron", "Gold", "Silver", "Copper"], "answer": 1,
"explanation": "The symbol 'Fe' represents the element Iron."},
{"question": "Which gas is known as the 'laughing gas'?",
"options": ["Oxygen", "Nitrogen", "Hydrogen", "Nitrous Oxide"],
"answer": 4, "explanation": "Nitrous oxide is commonly known as the
'laughing gas' due to its euphoric effects when inhaled."},

{"question": "What is the chemical symbol for silver?",


"options": ["Au", "Ag", "Fe", "Hg"], "answer": 2, "explanation": "The
chemical symbol for silver is Ag."},

{"question": "Which element is essential for human bones


and teeth?", "options": ["Calcium", "Iron", "Zinc", "Magnesium"],
"answer": 1, "explanation": "Calcium is essential for the formation
and strength of human bones and teeth."},

{"question": "What is the common name for the compound


H2O2?", "options": ["Hydrochloric Acid", "Sulfuric Acid",
"Hydrogen Peroxide", "Acetic Acid"], "answer": 3, "explanation":
"H2O2 is commonly known as hydrogen peroxide."},

{"question": "In the periodic table, which group do the


noble gases belong to?", "options": ["Group 1", "Group 2", "Group
17", "Group 18"], "answer": 4, "explanation": "The noble gases
belong to Group 18 of the periodic table."},

{"question": "What is the main component of natural gas?",


"options": ["Methane", "Ethane", "Propane", "Butane"], "answer": 1,
"explanation": "Methane is the main component of natural gas."},

{"question": "What is the chemical symbol for gold?",


"options": ["Au", "Ag", "Fe", "Hg"], "answer": 1, "explanation": "The
chemical symbol for gold is Au."},

{"question": "Which gas is known as the 'silent killer'


because it is colorless and odorless?", "options": ["Oxygen", "Carbon
Dioxide", "Nitrogen", "Carbon Monoxide"], "answer": 4,
"explanation": "Carbon monoxide is known as the 'silent killer' as it is
colorless, odorless, and can be deadly when inhaled."},

{"question": "What is the pH value of a neutral solution?",


"options": ["0", "7", "14", "10"], "answer": 2, "explanation": "The pH
value of a neutral solution is 7."},

{"question": "Which element is the most abundant in the


Earth's crust?", "options": ["Oxygen", "Silicon", "Aluminum",
"Iron"], "answer": 2, "explanation": "Silicon is the most abundant
element in the Earth's crust."},

{"question": "What is the process by which a substance


changes directly from a solid to a gas?", "options": ["Sublimation",
"Evaporation", "Condensation", "Melting"], "answer": 1,
"explanation": "Sublimation is the process by which a substance
changes directly from a solid to a gas without passing through the
liquid phase."},

{"question": "What is the chemical formula for water?",


"options": ["CO2", "H2O", "O2", "CH4"], "answer": 2, "explanation":
"The chemical formula for water is H2O."}

# Add more chemistry questions with explanations as


needed

cs_questions = [

{"question": "What is the purpose of the 'elif' keyword in


Python?", "options": ["Beginning of a loop", "End of a loop", "Else If
condition", "Exception handling"], "answer": 3, "explanation": "'elif'
is short for 'else if' and is used for additional conditional checks in
Python."},

{"question": "Which programming language is known for


its use in web development?", "options": ["Java", "C++", "HTML",
"Python"], "answer": 3, "explanation": "HTML (Hypertext Markup
Language) is primarily used for creating web pages."},

{"question": "What does the acronym 'HTML' stand for?",


"options": ["Hypertext Markup Language", "High-Level
Programming Language", "Hyper Transfer Markup Language",
"Home Tool Markup Language"], "answer": 1, "explanation":
"'HTML' stands for Hypertext Markup Language, used for creating
web pages."},

{"question": "In programming, what is the purpose of the 'if'


statement?", "options": ["Loop iteration", "Function definition",
"Conditional execution", "Variable assignment"], "answer": 3,
"explanation": "The 'if' statement is used for conditional execution in
programming."},

{"question": "Which programming language is known for


its use in artificial intelligence and machine learning?", "options":
["Java", "Python", "C++", "Ruby"], "answer": 2, "explanation":
"Python is widely used in artificial intelligence and machine learning
applications."},

{"question": "What is the primary function of an operating


system?", "options": ["Run applications", "Manage hardware
resources", "Store data", "Create graphics"], "answer": 2,
"explanation": "The primary function of an operating system is to
manage hardware resources."},

{"question": "What is the purpose of the 'git' version control


system?", "options": ["Database management", "Code collaboration",
"Graphic design", "Web development"], "answer": 2, "explanation":
"'git' is used for version control and collaborative code
development."},

{"question": "Which data structure follows the Last In, First


Out (LIFO) principle?", "options": ["Queue", "Stack", "Linked List",
"Tree"], "answer": 2, "explanation": "A stack follows the Last In,
First Out (LIFO) principle."},

{"question": "What does the acronym 'URL' stand for?",


"options": ["Uniform Resource Locator", "Universal Reference
Language", "Unified Retrieval Link", "User Runtime Locator"],
"answer": 1, "explanation": "'URL' stands for Uniform Resource
Locator, identifying the address of a resource on the web."},

{"question": "What is the purpose of the 'SQL'


programming language?", "options": ["Game development", "Web
design", "Database management", "Network security"], "answer": 3,
"explanation": "'SQL' is used for managing and querying relational
databases."},

{"question": "Which programming paradigm emphasizes


the use of functions and avoids changing state and mutable data?",
"options": ["Procedural programming", "Object-oriented
programming", "Functional programming", "Imperative
programming"], "answer": 3, "explanation": "Functional
programming emphasizes the use of functions without changing state
or mutable data."},

{"question": "What does the term 'API' stand for in software


development?", "options": ["Application Programming Interface",
"Advanced Programming Interface", "Automated Program
Integration", "Application Process Interface"], "answer": 1,
"explanation": "'API' stands for Application Programming Interface,
facilitating interaction between software components."},

{"question": "In web development, what does CSS stand


for?", "options": ["Cascading Style Sheet", "Centralized Style
Syntax", "Computer Style System", "Creative Styling Solution"],
"answer": 1, "explanation": "'CSS' stands for Cascading Style Sheet,
used for styling web pages."},

{"question": "Which sorting algorithm has an average-case


time complexity of O(n log n)?", "options": ["Bubble Sort", "Insertion
Sort", "Quick Sort", "Selection Sort"], "answer": 3, "explanation":
"Quick Sort has an average-case time complexity of O(n log n)."}

# Add more computer science questions with explanations


as needed

subject = subject.lower()

if subject == "physics":

return physics_questions

elif subject == "mathematics":

return math_questions

elif subject == "chemistry":

return chemistry_questions

elif subject == "computer science":


return cs_questions

else:

print("Invalid subject choice. Please choose a valid subject.")

return self.choose_subject()

def display_scores(self):

# Display scores for each player

print("\nCurrent Scores:")

for player_name, data in self.player_profiles.items():

print(f"{player_name}: Score - {data['score']}, Consecutive


Correct - {data['consecutive_correct']}")

def play_round(self, num_players):

# Play a round of the quiz game for each player

subject = self.choose_subject()

questions = self.load_question_pool(subject)

for player_name in self.player_profiles:

print(f"\nPlayer {player_name}'s turn:")

self.display_scores()

asked_questions = set()
self.num_questions_per_round =
self.get_positive_integer_input("Enter the number of questions for
this round:")

for _ in range(self.num_questions_per_round):

# Ensure a unique question is asked to the player

remaining_questions = [q for q in questions if q["question"]


not in asked_questions]

if not remaining_questions:

print("No more unique questions available.")

break

question_data = random.choice(remaining_questions)

asked_questions.add(question_data["question"])

print(f"\nQuestion: {question_data['question']}") # Added


line to display the question

correct_option_index = question_data["answer"] - 1

options =
random.sample(range(len(question_data["options"])),
len(question_data["options"]))
for i, option_index in enumerate(options, start=1):

option = question_data["options"][option_index]

print(f"{i}. {option}")

# Store the correct answer for later comparison

correct_answer = correct_option_index + 1

user_time_limit = self.get_positive_integer_input("Enter the


time limit (in seconds) for this question: ")

print(f"\nYou have {user_time_limit} seconds to answer.")

question_start_time = datetime.datetime.now()

self.answered_within_time_limit = False

timer_thread = threading.Thread(target=self.timer_thread,
args=(question_start_time, user_time_limit))

timer_thread.start()

try:

user_answer_index =
self.get_positive_integer_input("Your answer (enter the option
number): ")

self.answered_within_time_limit = True

user_answer_index -= 1
user_answer = options[user_answer_index]

correct_answer -= 1

except (IndexError, ValueError):

user_answer = None

timer_thread.join()

if user_answer is not None:

if user_answer == correct_answer:

print(f"Correct! You earned a point!\n")

self.player_profiles[player_name]["score"] += 1

self.player_profiles[player_name]["consecutive_correct"] += 1

else:

print(f"Wrong! The correct answer was:


{question_data['options'][correct_option_index]}\n")

print(f"Explanation:{question_data['explanation']}\n")

self.player_profiles[player_name]["consecutive_correct"] = 0

time.sleep(2) # Brief pause before displaying the next


question
print(f"End of Round {self.current_round} for Player
{player_name}.\n")

self.current_round += 1

def update_leaderboard(self):

# Update the overall leaderboard based on players' scores

for player_name, data in self.player_profiles.items():

if player_name not in self.leaderboard:

self.leaderboard[player_name] = 0

self.leaderboard[player_name] += data['score']

def display_winner(self):

# Display the winner(s) of the quiz game

max_score = max(self.leaderboard.values())

winners = [player_name for player_name, score in


self.leaderboard.items() if score == max_score]

print("\nFinal Results:")

for player_name, data in self.player_profiles.items():

print(f"{player_name}: Score - {data['score']}, Consecutive


Correct - {data['consecutive_correct']}")
print("\nLeaderboard:")

for player_name, score in self.leaderboard.items():

print(f"{player_name}: {score} points")

if len(winners) == 1:

print(f"\nCongratulations! {winners[0]} is the winner!")

else:

print(f"\nIt's a tie! The winners are: {', '.join(winners)}")

def play_game(self):

self.display_intro()

num_players = self.get_positive_integer_input("Enter the


number of players: ")

self.initialize_player_profiles(num_players)

while self.current_round <= self.rounds:

self.play_round(num_players)

self.update_leaderboard()

self.calculate_final_scores()

self.display_leaderboard()

def calculate_final_scores(self):
# Calculate final scores, considering any additional factors

for player_name, data in self.player_profiles.items():

final_score = data['score'] + (data['consecutive_correct'] * 2)


# Bonus points for consecutive correct answers

self.leaderboard[player_name] = final_score

# Determine IQ level based on the number of correct answers

iq_level = self.determine_iq_level(final_score)

data['iq_level'] = iq_level

def determine_iq_level(self, correct_answers):

# Determine IQ level based on the number of correct answers

if correct_answers >= 8:

return "Genius"

elif correct_answers >= 5:

return "Above Average"

else:

return "Average"

def display_leaderboard(self):

# Display the final leaderboard with scores and IQ levels

print("\nFinal Leaderboard:")
sorted_leaderboard = sorted(self.leaderboard.items(),
key=lambda x: x[1], reverse=True)

for position, (player_name, score) in


enumerate(sorted_leaderboard, start=1):

iq_level = self.player_profiles[player_name]["iq_level"]

print(f"{position}. {player_name}: Score - {score}, IQ Level -


{iq_level}")

# Create an instance of the QuizGame class and start the game

quiz_game = QuizGame()

quiz_game.play_game()
OUTPUT
ADVANTAGES
This quiz game program has several advantages:

1. *User Interaction:* It allows user interaction by accepting player


names, their answers, and providing feedback.

2. *Customization:* The program allows customization, such as


choosing the number of players, subjects, and rounds.

3. *Scoring System:* The scoring system includes bonus points for


consecutive correct answers, adding an element of strategy to the
game.

4. *Multi-Threading:* It uses threading for a timer, allowing


questions to have a time limit, enhancing the gaming experience.

5. *Subject Variety:* The inclusion of different subjects (Physics,


Mathematics, Chemistry, Computer Science) adds variety and
educational value.

6. *Dynamic Question Pool:* The program dynamically loads


questions based on the chosen subject, making it expandable and
versatile.
7. *Final Leaderboard:* It calculates and displays a final leaderboard,
considering additional factors like consecutive correct answers and IQ
levels.

8. *IQ Level Determination:* It assesses players' performance and


assigns an IQ level, adding a fun and informative aspect.

9. *Error Handling:* The program includes error handling for invalid


inputs, enhancing its robustness.

10. *Code Structure:* The code is well-organized into functions and


classes, making it readable and maintainable.
CONCLUSION
This quiz game allows the user to gain the knowledge more

efficiently and makes the user to feel free to access. This program is

not like other quiz games as it asks how many questions should be

asked and also asks how much time does the user need to answer for

each questions.

The main goal from the program is that to make quiz games

not so stressful. As in this you modify anything in the program such

as questions that are meant to show in the program that is you can

change, add, modify the questions that are meant to be shown in

program.

FUTURE WORKS
This program gives the oppurtunity to learn and experience

many knowledge about subjects. The program is great for improving

the student’s IQ based on the questions that the user answers. The

allows the user to get good knowledge about subjects. The program

should be implemented in all quiz game platforms.


REFERENCES

 Computer Science Textbook Class 11

 Computer Science with Python by Sumita Arora Class 11

 https://www.wikipedia.org/

 https://www.google.com

You might also like