the quiz game using
python and mysql
Register No. :
Under the guidance of
Mrs.LAVANYA G MICHAEL
M.Sc, M.Phil, B.Ed
A Project work submitted to
CENTRAL BOARD OF SECONDARY EDUCATION
INDIA
In partial fulfilment of the requirement for
Class–XII 2024-25
1
VELAMMALVIDYALAYA
PARUTHIPATTU
ACADEMIC YEAR 2024-25
PROJECT REPORT ON
The quiz game using
pyhon and MySql
Register no :
Name : anandha kaarthick s
Class : XII B
SUBJECT : COMPUTER SCIENCE
SUB CODE : 083
PROJECT GUIDE : MRS LAYANYA G MICHAEL
M.Sc, M.Phil, B.Ed
VELAMMAL VIDYALAYA
PARUTHIPATTU, AVADI
2
VELAMMAL VIDYALAYA
PARUTHIPATTU
CLASS–XII PROJECT
Register No.:
CERTIFICATE
This is to certify that Anandha kaarthick S of class XII-B,
Register no: has successfully completed the project
work entitled The quiz game using python and MySql in the subject
Computer science (083) and submitted it to Central Board of
Secondary Education.
During the academic year: 2024-25
INTERNAL EXAMINER EXTERNAL EXAMINER
3
INDEX
S.NO. DESCRIPTION PAGE NO.
01 ACKNOWLEDGEMENT 05
02 INTRODUCTION 06
03 OBJECTIVES OF THE PROJECT 06
04 OVERVIEW 07
05 THE MAIN PROGRAM 09
06 THE QUERY FOR SQL DATABASE 14
07 THE MENU’S GIVEN BY THE PROGRAM 14
08 OUTPUT OF THE FOLLOWING PROGRAM 15
09 MYSQL DATABASE TABLES 17S
ACKNOWLEDGEMENT
First and foremost my grateful thanks to the almighty for his divine
4
blessing and grace in making this project successful and I thank my parents
for giving me all this life and opportunity. I acknowledge my sincere thanks
to The Chairman and The Correspondent of Velammal Educational Trust for
providing me with this opportunity and the necessary facilities for
completing this study.
My profound gratitude and heartfelt thanks to Mr.Prithviraj, Senior principal
VelammalVidyalaya, Paruthipattu. Sir, thank you for your expertise,
enthusiasm, and especially for your precious time and for the kind help
in all situations throughout the academic year.
It is a proud privilege to express my sincere gratitude to my guide
Mrs.LAVANYA G MICHAEL, Faculty of Computer Science for constant
guidance for the entire study duration. Always looking ahead with new
ideas, guiding with patience and support in all situations.
I gladly extend my sincere thanks to my class in-charge and all Faculty
members for their support. Last but not least, I would like to show my
humble gratitude to my family members and all my friends who were the
back bone for me to complete this study successfully.
THE QUIZ GAME USING PYTHON AND MYSQL
INTRODUCTION
5
This is the interactive game which a user can play in the way of quiz
with many options in it
OBJECTIVES OF THE PROJECT
The objective of this project is to let the students apply the
programming knowledge into a real- world situation/problem and exposed
the students how programming skills helps in developing a good software.
1. Write programs utilizing modern software tools.
2. Apply object oriented programming principles effectively when
developing small to medium sized projects.
3. Write effective procedural code to solve small to medium sized
problems. 4. Students will demonstrate a breadth of knowledge in
computer science, as exemplified in the areas of systems, theory and
software development. 5. Students will demonstrate ability to conduct a
research or applied Computer Science project, requiring writing and
presentation skills which exemplify scholarly style in computer science.
DOCUMENTATION FOR QUIZ GAME
OVERVIEW:
6
This is a game which gives the user to play, create user, login, add
question and view the scoreboard. This game is built using python run
the game and Mysql to store the game data like user information,
scoreboard and quiz questions
FEATURES:
1. User Management:
1. User can create the user account.
2. User can login to a existing account .
2. Quiz gameplay:
1. This game is based on a multiple choice question .
2. The score can be tracked on basis of the correct answers
3.Questions:
1. Question are managed in mysql database.
4. Scoreboard:
1. The scoreboard can be seen by the user
TECHNOLOGIES:
Programming language: python
Database : MySql
Libraries used:
1. ‘mysql.connector’:
It is used for connecting and interating with python and MySql
database.
2. ‘getpass’:
It is used for securely handling password input from the user
3. ‘msvcrt’:
For handling keyboard input in a windows environment
INSTALLATION:
1. Ensure that you have installed mysql and python.
2. Ensure you have installed the above libraries
USAGE:
Menu options:
Create a new user: Allows new users to register.
7
Login: Existing users can log in with their credentials.
Play game: Start playing the quiz game.
Add question: Admin users can add new questions to the quiz.
Display scoreboard: View the leaderboard with scores.
Quit: Exit the application.
Gameplay:
Users will be presented with multiple-choice questions.
Input the number corresponding to the chosen answer.
After each question, users can decide to continue or end the game.
CODE EXPLANATION:
Main Functions
get_password(prompt): A custom function to securely input passwords
without displaying them on the screen.
create_user(): Handles user registration by inserting new user data into
the database.
login_user(): Authenticates users by checking the provided credentials
against the database.
play_game(user_id): Facilitates the quiz gameplay, tracks scores, and
checks answers against correct options.
add_question(): Allows the addition of new questions to the database.
display_scoreboard(): Fetches and displays the current scores of all
users.
ERROR HANDLING:
The application includes error handling for database operations to ensure
that users receive feedback in case of issues such as invalid input or
connection errors.
CONCLUSION:
The Quiz Game project is a simple yet engaging application that
combines user interaction, database management, and game logic. It
serves as a practical example of how to build a console application with
user authentication and dynamic content management using Python and
MySQL.
THE MAIN PROGRAM
8
import mysql.connector
import getpass
Nimport random
import msvcrt
try:
cnx = mysql.connector.connect(
user='root',
password='123456',
host='localhost',
database='quizgame'
)
except mysql.connector.Error as err:
print("Something went wrong: {}".format(err))
exit()
cursor = cnx.cursor()
def get_password(prompt):
password = ""
while True:
char = msvcrt.getch()
if char == b'\r': # Enter key
break
elif char == b'\b': # Backspace key
if password:
password = password[:-1]
print('\b \b', end='', flush=True) # Backspace and space to
erase the character
else:
password += char.decode()
print('*', end='', flush=True) # Print an asterisk to represent the
character
print() # Newline after the password
return password
def create_user():
try:
9
global id
id = input("enter your user id: ")
username = input("Enter your username: ")
password = getpass.getpass("Enter your password: ")
query = "INSERT INTO users (id,username, password) VALUES
(%s, %s, %s)"
cursor.execute(query, (id, username, password))
cnx.commit()
print("User created successfully!")
except mysql.connector.Error as err:
print("Error creating user: {}".format(err))
def login_user():
try:
username = input("Enter your username: ")
password = getpass.getpass("Enter your password: ")
query = "SELECT * FROM users WHERE username = %s AND
password = %s"
cursor.execute(query, (username, password))
user = cursor.fetchone()
if user:
return user[0]
else:
print("Invalid username or password!")
return None
except mysql.connector.Error as err:
print("Error logging in user: {}".format(err))
def play_game(user_id):
try:
score = 0
query = "SELECT * FROM question"
cursor.execute(query)
questions = cursor.fetchall()
if not questions:
print("No questions available.")
return
for question in questions:
10
if len(question) < 2:
print("Invalid question format.")
continue
print(question[1])
for i, option in enumerate(question[2].split(',')):
print(f"{i+1}. {option}")
while True:
try:
answer = int(input("Enter the number of your answer: "))
if answer < 1 or answer > len(question[2].split(',')):
print("Invalid answer! Please try again.")
else:
break
except ValueError:
print("Invalid input! Please enter a number.")
if question[2].split(',')[answer-1] == question[3]:
score += 1
print("Correct!")
else:
print("Incorrect!")
while True:
choice = input("Do you want to continue? (yes/no): ")
if choice.lower() == "yes":
break
elif choice.lower() == "no":
print(f"Your final score is {score}!")
return
else:
print("Invalid input! Please enter yes or no.")
query = "INSERT INTO scores (user_id, score) VALUES (%s, %s)"
cursor.execute(query, (user_id, score))
cnx.commit()
print(f"Your final score is {score}!")
except mysql.connector.Error as err:
print("Error playing game: {}".format(err))
def add_question():
try:
question = input("Enter the question: ")
options = input("Enter the options (comma separated): ")
11
answer = input("Enter the correct answer: ")
query = "INSERT INTO question (question, options, answer) VALUES
(%s, %s, %s)"
cursor.execute(query, (question, options, answer))
cnx.commit()
print("Question added successfully!")
except mysql.connector.Error as err:
print("Error adding question: {}".format(err))
def display_scoreboard():
try:
query = "SELECT u.username, s.score FROM users u JOIN scores s
ON u.id = s.user_id ORDER BY s.score DESC"
cursor.execute(query)
scores = cursor.fetchall()
print("Scoreboard:")
for i, score in enumerate(scores):
print(f"{i+1}. {score[0]} - {score[1]}")
except mysql.connector.Error as err:
print("Error displaying scoreboard: {}".format(err))
def main():
while True:
print("1. Create a new user")
print("2. Login")
print("3. Play game")
print("4. Add question")
print("5. Display scoreboard")
print("6. Quit")
while True:
try:
choice = int(input("Enter your choice: "))
if choice < 1 or choice > 6:
print("Invalid choice! Please try again.")
else:
break
except ValueError:
print("Invalid input! Please enter a number.")
if choice == 1:
12
create_user()
if choice == 2:
login_user()
elif choice == 3:
play_game(id)
elif choice == 4:
add_question()
elif choice == 5:
display_scoreboard()
elif choice == 6:
print("Goodbye!")
break
if id:
while True:
print("1. Play game")
print("2. Add question")
print("3. Display scoreboard")
print("4. logout")
while True:
try:
choice = int(input("Enter your choice: "))
if choice < 1 or choice > 4:
print("Invalid choice! Please try again.")
else:
break
except ValueError:
print("here is your option")
if __name__ == "__main__":
main()
THE QUERY FOR SQL DATABASES
13
FOR USERS TABLE:
CREATE TABLE
users (
id
VARCHAR(255)
PRIMARY KEY,
username FOR QUESTIONS TABLE:
VARCHAR(255)
NOT NULL,
CREATE TABLE
question
password (
VARCHAR(255)
id INT
NOT NULL);
AUTO_INCREMENT
PRIMARY KEY,
question TEXT
NOT NULL,
options TEXT FOR SCORES TABLE:
NOT NULL,
CREATE
answer TABLE
VARCHAR(255)
scores (
NOT
id NULL);
INT
AUTO_INCREMENT
PRIMARY KEY,
user_id
VARCHAR(255)
NOT NULL,
score INT NOT
NULL,
FOREIGN KEY The menu’s given by the program
(user_id) 1. Create a new user
REFERENCES 2. Login
users(id)); 3. Play game
4. Add question
5. Display scoreboard
6. Quit
OUTPUT FOR THE FOLLOWING PROGRAM:
14
1. Create a new user
2. Login
3. Play game
4. Add question
5. Display scoreboard
6. Quit
Enter your choice: 1
enter your user id: 456
Enter your username: anandha;
Enter your password:
User created successfully!
1. Create a new user
2. Login
3. Play game
4. Add question
5. Display scoreboard
6. Quit
Enter your choice: 2
Enter your username: anandha;
Enter your password:
1. Create a new user
2. Login
3. Play game
4. Add question
5. Display scoreboard
6. Quit
Enter your choice: 3
What is the largest planet in our solar system?
1. Earth
2. Saturn
3. Jupiter
4. Uranus
Enter the number of your answer: 3
Correct!
Do you want to continue? (yes/no): yes
Which musician is known as the "King of Rock and Roll"?
1. Elvis Presley
2. Chuck Berry
3. Little Richard
15
4. Bo Diddley
Enter the number of your answer: 3
Incorrect!
Do you want to continue? (yes/no): no
Your final score is 3!
1. Create a new user
2. Login
3. Play game
4. Add question
5. Display scoreboard
6. Quit
Enter your choice: 4
Enter the question: what is 1+1
Enter the options (comma separated): 1 , 2 , 3 , 4
Enter the correct answer: 2
Question added successfully!
1. Create a new user
2. Login
3. Play game
4. Add question
5. Display scoreboard
6. Quit
Enter your choice: 5
Scoreboard:
1. anandha - 3
1. Create a new user
2. Login
3. Play game
4. Add question
5. Display scoreboard
6. Quit
Enter your choice: 6
Goodbye!
the MySql database tables
Questions tables:
16
User tables
Scoreboard table
17