New Computer Science Project
New Computer Science Project
Register No. :
INDIA
Class–XII 2024-25
1
VELAMMALVIDYALAYA
PARUTHIPATTU
PROJECT REPORT ON
Register no :
Name : anandha kaarthick s
Class : XII B
SUBJECT : COMPUTER SCIENCE
SUB CODE : 083
2
VELAMMAL VIDYALAYA
PARUTHIPATTU
CLASS–XII PROJECT
Register No.:
CERTIFICATE
This is to certify that Anandha kaarthick S of class XII-B,
work entitled The quiz game using python and MySql in the subject
Secondary Education.
3
INDEX
S.NO. DESCRIPTION PAGE NO.
01 ACKNOWLEDGEMENT 05
02 INTRODUCTION 06
04 OVERVIEW 07
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.
INTRODUCTION
5
This is the interactive game which a user can play in the way of quiz
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.
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()
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
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
Questions tables:
16
User tables
Scoreboard table
17