CS Project

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 23

PM SHRI KENDRIYA

VIDYALAYA
ANDREWS GANJ

COMPUTER SCIENCE PROJECT

2024 - 2025

Submitted By –Debabrata Dhakai


Class – 12th - A
Topic – Quizz using Database
Submitted To – Swati Saxena
CONTENTS
1. Certificate
2. Acknowledgement
3. Requirements
4. General Description
5. Sources
6. Functions And Their Purpose
7. Flowchart
8. Output
9. Advantages
10. Disadvantages
11. Bibliography
Certificate
This is to certify that Debabrata Dhakai has
successfully completed his Computer Science
Project File during academic session 2024 – 2025
as per guidelines issued by CBSE.

Teacher’s Signature
ACKNOWLEDGEMENT
I wish to express our sincere thanks to
Dr. Rajkumar Sharma Principal, Kendriya Vidyalaya
Andrews Ganj, New Delhi for guiding us to cause the
successful outcome of the project.

I wish to express our deep and profound sense of


gratitude to our guide teacher Ms. Swati Saxena
(Computer Science), for her expert help & valuable
guidance, comments and suggestions.

I also place on record, our sincere Gratitude to one


and all who directly or indirectly. Have lent their
helping hand in this venture.
REQUIREMENTS
 Hardware
 Printer to print the project report
 Laptop/Desktop
 Ram 4 GB
 Hard Disk 1024Gb
 Software
 Operating System Windows 10 or
10+
 Python 3.8 or 3.8+For Execution of
Program
 MYSQL database for storing data
 MS Word For Report Presentation
GENERAL DESCRIPTION
This Python script sets up a game where players answer science-related questions, their answers are validated,
and their scores are saved in a MySQL database.

Overview of the Script:


1. Database Setup:
o The script connects to a MySQL database (gamedb).
o It creates two tables: players (for player information) and scores (for storing each player's score).

2. Game Logic:
o The game asks a set of pre-defined questions (related to science).
o For each question, the player must choose an answer (A, B, C, or D). Their response is then validated.
o The score is calculated based on the number of correct answers and is displayed as a percentage.

3. Saving and Retrieving Data:


o If the player answers the questions, the score is saved to the scores table associated with their
playerid.
o If a player’s name already exists in the players table, their playerid is retrieved; otherwise, a new
player record is created.

4. Replay Option:
o The game asks if the player wants to play again after each game session. If they choose "yes", the game
starts again; otherwise, the program ends.

Code Flow:
1. Connecting to MySQL:
o The script connects to a local MySQL server and attempts to create and use the database gamedb.

2. Game Initialization:
o A series of science-related questions and answer options are defined in the dictionary questions and
options.
o The new_game() function randomly selects five questions and presents them to the player.
o Player responses are collected and compared to the correct answers, and the score is updated
accordingly.

3. Player and Score Management:


o The get_player_id() function checks if a player already exists in the database. If not, it creates a new
player record and returns their playerid.
o The save_score() function inserts the player's score into the scores table, linking it to their
playerid.

4. Game Replay:
o The player is asked if they want to play again after each round. If they answer "yes", the game
continues; otherwise, it ends.
Closing the Connection:
After the player finishes the game and decides not to replay, the MySQL connection is closed using
conn.close().This script combines a simple quiz game with MySQL integration to track and store player
scores, and it provides a nice interactive experience!
SOURCE CODE
import mysql.connector
import random
from mysql.connector import Error

# Connect to the MySQL database


# Connect to MySQL
try:
conn = mysql.connector.connect(
host='localhost',
user='root',
password='Mars@)@$18'
)
if conn.is_connected():
print("Connected to MySQL server")
except Error as e:
print(f"Error connecting to MySQL: {e}")

cursor = conn.cursor()

# Create the database if it doesn't exist


try:
cursor.execute("CREATE DATABASE IF NOT EXISTS gamedb")
print("Database 'gamedb' is created or already exists.")
except Error as e:
print(f"Error creating database: {e}")

# Switch to the created database


try:
cursor.execute("USE gamedb")
print("Switched to 'gamedb' database.")
except Error as e:
print(f"Error switching to database: {e}")

# Create tables to store player info and scores if they don't exist
cursor.execute('''CREATE TABLE IF NOT EXISTS players (
playerid INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL
)''')

cursor.execute('''CREATE TABLE IF NOT EXISTS scores (


id INT AUTO_INCREMENT PRIMARY KEY,
playerid INT NOT NULL,
score INT NOT NULL,
FOREIGN KEY(playerid) REFERENCES players(playerid)
)''')
def new_game(playerid):
# Define a set of questions and their corresponding correct answers
questions = {
"What is the speed of light in vacuum approximately?": "A",
"Which scientist formulated the laws of motion?": "A",
"What is the SI unit of electric charge?": "C",
"What is the chemical formula for methane?": "B",
"What is Avogadro's number?": "A",
"What is the name of the process by which plants make their food?": "B",
"Which gas is known as laughing gas?": "B",
"What is the study of the nature and behavior of matter and energy called?": "B",
"Who discovered the electron?": "A",
"What is the chemical symbol for sodium?": "A",
"What is the SI unit of force?": "A",
"What is the chemical formula for water?": "A",
"What is the largest organ in the human body?": "A",
"Which element is a noble gas?": "A",
"Who proposed the theory of relativity?": "B",
"Which planet is known as the Red Planet?": "A",
"What is the process of converting a liquid into vapor called?": "A",
"What is the chemical symbol for iron?": "A",
"What is the SI unit of energy?": "A",
"What is the chemical formula for carbon dioxide?": "A",
"Which organ in the human body produces insulin?": "B",
"Which element has the atomic number 1?": "A",
"What is the formula for density?": "A",
"What is the chemical symbol for hydrogen?": "A",
"What is the reaction between stoichiometric quantities of KMnO4 and KI in weakly
basic solution?": "A", # Correct answer here
"What is the reagent used in Wurtz reaction for alkanes?": "B", # Correct answer here
"What is the interpretation of dy/dx=-y/x?": "D",
"What is 2g of KMnO4 sample required 40ml of 0.5M ferrous oxalate for complete
reduction?": "D",
"Is the work done in an isochoric process equal to 0?": "A"
}
# Define a set of options corresponding to each question
options = {
"What is the speed of light in vacuum approximately?": [
"A. 3.00 x 10^8 m/s",
"B. 2.00 x 10^8 m/s",
"C. 2.50 x 10^8 m/s",
"D. 3.50 x 10^8 m/s"
],
"Which scientist formulated the laws of motion?": [
"A. Isaac Newton",
"B. Albert Einstein",
"C. Nikola Tesla",
"D. Galileo Galilei"
],
"What is the SI unit of electric charge?": [
"A. Volt",
"B. Ampere",
"C. Coulomb",
"D. Ohm"
],
"What is the chemical formula for methane?": [
"A. CO2",
"B. CH4",
"C. NH3",
"D. H2O"
],
"What is Avogadro's number?": [
"A. 6.02 x 10^23",
"B. 6.63 x 10^-34",
"C. 9.81",
"D. 3.14"
],
"What is the name of the process by which plants make their food?": [
"A. Respiration",
"B. Photosynthesis",
"C. Transpiration",
"D. Synthesis"
],
"Which gas is known as laughing gas?": [
"A. Helium",
"B. Nitrous oxide",
"C. Nitrogen",
"D. Oxygen"
],
"What is the study of the nature and behavior of matter and energy called?": [
"A. Biology",
"B. Physics",
"C. Chemistry",
"D. Geology"
],
"Who discovered the electron?": [
"A. J.J. Thomson",
"B. Marie Curie",
"C. Isaac Newton",
"D. Nikola Tesla"
],
"What is the chemical symbol for sodium?": [
"A. Na",
"B. S",
"C. Fe",
"D. Ag"
],
"What is the SI unit of force?": [
"A. Newton",
"B. Watt",
"C. Einstein",
"D. Coulomb"
],
"What is the chemical formula for water?": [
"A. H2O",
"B. CO2",
"C. O2",
"D. CH4"
],
"What is the largest organ in the human body?": [
"A. Skin",
"B. Liver",
"C. Heart",
"D. Kidney"
],
"Which element is a noble gas?": [
"A. Helium",
"B. Neon",
"C. Oxygen",
"D. Nitrogen"
],
"Who proposed the theory of relativity?": [
"A. Isaac Newton",
"B. Albert Einstein",
"C. Galileo Galilei",
"D. Niels Bohr"
],
"Which planet is known as the Red Planet?": [
"A. Mars",
"B. Venus",
"C. Jupiter",
"D. Saturn"
],
"What is the process of converting a liquid into vapor called?": [
"A. Evaporation",
"B. Condensation",
"C. Sublimation",
"D. Boiling"
],
"What is the chemical symbol for iron?": [
"A. Fe",
"B. Ir",
"C. Ni",
"D. In"
],
"What is the SI unit of energy?": [
"A. Joule",
"B. Watt",
"C. Newton",
"D. Ampere"
],
"What is the chemical formula for carbon dioxide?": [
"A. CO2",
"B. CH4",
"C. C2H6",
"D. H2O"
],
"Which organ in the human body produces insulin?": [
"A. Pancreas",
"B. Liver",
"C. Heart",
"D. Kidney"
],
"Which element has the atomic number 1?": [
"A. Hydrogen",
"B. Helium",
"C. Oxygen",
"D. Carbon"
],
"What is the formula for density?": [
"A. d = m/V",
"B. d = V/m",
"C. d = m × V",
"D. d = m - V"
],
"What is the chemical symbol for hydrogen?": [
"A. H",
"B. He",
"C. O",
"D. N"
],
# Add the missing options here:
"What is the reaction between stoichiometric quantities of KMnO4 and KI in weakly
basic solution?": [
"A. Redox reaction",
"B. Precipitation",
"C. Acid-base reaction",
"D. Substitution"
],
"What is the reagent used in Wurtz reaction for alkanes?": [
"A. Sodium hydroxide",
"B. Dry ether",
"C. Potassium iodide",
"D. Hydrochloric acid"
],
"What is the interpretation of dy/dx=-y/x?": [
"A. Parabolic",
"B. Linear",
"C. Exponential",
"D. Hyperbolic"
],
"What is 2g of KMnO4 sample required 40ml of 0.5M ferrous oxalate for complete
reduction?": [
"A. 10%",
"B. 20%",
"C. 40%",
"D. 50%"
],
"Is the work done in an isochoric process equal to 0?": [
"A. Yes",
"B. No",
"C. Depends on nature of gas"
]
}

# Randomly select 5 questions from the pool


selected_questions = random.sample(list(questions.items()), 5)

# Initialize lists and variables for guesses and score


guesses = []
correct_guesses = 0

# Loop through each selected question


for question, correct_answer in selected_questions:
# Display the question and options
print("\n" + question)
for option in options[question]:
print(option)

# Get user input for the guess


guess = input("Enter (A, B, C, or D): ").upper()
guesses.append(guess) # Append the guess to the list of guesses

# Check the answer and update the correct guesses count


if guess == correct_answer:
print("CORRECT!")
correct_guesses += 1
else:
print(f"WRONG! The correct answer is: {correct_answer}")

# Display the final score


score = display_score(correct_guesses, guesses)
save_score(playerid, score)

def display_score(correct_guesses, guesses):


print("\n---")
print("RESULTS")

# Calculate and display the percentage score


score = int((correct_guesses / len(guesses)) * 100)
print("Your score is: " + str(score) + "%")
return score

def save_score(playerid, score):


cursor.execute("INSERT INTO scores (playerid, score) VALUES (%s, %s)", (playerid, score))
conn.commit()

def play_again():
response = input("Do you want to play again? (yes or no): ").upper()
return response == "YES"

def get_player_id(name):
cursor.execute("SELECT playerid FROM players WHERE name = %s", (name,))
result = cursor.fetchone()
if result:
return result[0] # Return the playerid if found
else:
# If player does not exist, insert into players table and return the new playerid
cursor.execute("INSERT INTO players (name) VALUES (%s)", (name,))
conn.commit()
return cursor.lastrowid # Return the last inserted playerid

# Main execution starts here


if __name__ == "__main__":
player_name = input("Enter your name: ")
playerid = get_player_id(player_name)

new_game(playerid)

while play_again():
new_game(playerid)
conn.close() # Close the database connection
print("Bye!")

Functions and Their Purpose


1. new_game(playerid)

 Purpose:
o Starts a new game for a player by presenting a set of pre-defined science questions.
o Randomly selects 5 questions from a pool and prompts the player to answer them.
o It then compares the player's answers to the correct answers and calculates the score.
o After completing the questions, it calls display_score to calculate the final score and save_score to
store it in the database.

2. display_score(correct_guesses, guesses)

 Purpose:
o Calculates the player's score based on the number of correct answers.
o Displays the percentage score of correct guesses out of the total questions.
o Returns the score value to be saved in the database.

3. save_score(playerid, score)

 Purpose:
o Saves the player's score in the scores table of the MySQL database by linking it to the player's unique
playerid.
o It inserts the score into the database for tracking.

4. play_again()

 Purpose:
o Prompts the player to decide if they want to play the game again.
o Returns a boolean value (True if the player chooses to play again, False otherwise).

5. get_player_id(name)

 Purpose:
o Checks if a player already exists in the players table by querying the database with the player’s name.
o If the player exists, it returns their unique playerid.
o If the player does not exist, it inserts the player's name into the database and returns the new
playerid.
FLOWCHART Start

Enter Player Name

The user is prompted to enter their name

Select 5 Random Questions


The system randomly selects 6 questions
from the avaliable pool.
OUTPUTS
Display Question & Options

Output 1 – For each selected question, the


options are displayed

Get User input

The user enters their guess ( A,


B , C or D)

Check Answer
Correct : Increase the score

Wrong: Show the correct answer

Display Score
The user’s score is calculated
based on correct answers
In this output the program starts with prompting user to enter the
name

Output 2-
Save Score
The score is stored in the
database

5 Random questions are asked by program, user selects the option and in the end it shows Score.
Yes
Close Play Again?

Output 3-

Data stored in gamedb database


ADVANTAGES
1. Database Integration for Storage:

 The program saves and stores player data, including their name and scores, in a MySQL database. This ensures
that player data is persistent and can be accessed later.
 Storing scores in a database allows for easy retrieval and tracking of a player's performance over time.

2. Automated Database Creation:

 The program automatically creates the database and tables if they do not exist, eliminating the need for manual
setup and reducing potential errors during installation.

3. User-Friendly Interface:

 The program allows users to enter their name, answer questions, and view their score. It uses an easy-to-
understand format, providing a simple yet engaging user experience.
 It provides immediate feedback by informing the user whether their answer is correct or wrong.

4. Score Calculation and Display:

 After answering all questions, the program calculates the score as a percentage, offering immediate
performance feedback to the user.
 It also displays the result in a clear and understandable format.

5. Randomized Question Selection:

 The program randomly selects 5 questions for each game, ensuring that each gameplay experience is different
and increasing replayability.
 This randomness reduces predictability and makes the game more engaging.

6. Replayability:

 Users can choose to play again after finishing a round, keeping the experience fresh and encouraging multiple
rounds of gameplay.

7. Player Tracking:

 By associating each player with a unique ID, the program allows the system to track each player’s performance
over time.
 The program checks if a player already exists in the database and retrieves their scores accordingly, which helps
in maintaining a history of their scores.

8. Correct Answer Feedback:

 The program provides feedback on wrong answers by showing the correct one. This encourages learning and
helps users improve their knowledge over time.
9. Scalable for More Questions:

 The pool of questions and answers can easily be expanded, allowing the game to grow and include more
questions as needed. This scalability keeps the program relevant for long periods.

10. Simple and Efficient Design:

 The program is straightforward, focusing on a simple game mechanic without unnecessary complexity. The code
is easy to understand and maintain.
 The program focuses on functionality over complexity, making it more accessible for beginner programmers or
users.

11. Use of MySQL for Data Persistence:

 By using MySQL, the program can handle large amounts of player data and scores effectively. MySQL also
provides robust data management capabilities, which can be beneficial if the game scales up with more users.

12. Error Handling:

 The program includes error handling for database connections and operations, ensuring that the system is more
resilient to potential issues like connection errors.

13. Improves Knowledge:

 By asking questions related to science and general knowledge, the program offers an educational aspect to the
user, making it not just a game but also a tool for learning.
DISADVANTAGES
1. Limited Question Pool:

 The program uses a fixed set of 25 questions, which can make the game repetitive over time. Players may
encounter the same questions frequently, leading to boredom and reduced replay value.
 The question pool is not dynamic, meaning once a user plays a certain number of times, they may already know
the answers.

2. Lack of User Interface (UI):

 The program relies on the command line interface (CLI) for interaction, which can be off-putting for users who
prefer graphical user interfaces (GUIs). A more interactive UI (e.g., using Tkinter or another GUI library) would
make the game more accessible and engaging for a wider audience.

3. No Input Validation or Error Handling for User Input:

 The program assumes that users will input valid responses (A, B, C, or D) for each question. If a user types
something other than these options (e.g., "E"), the program will not handle this error, leading to unexpected
behavior or crashes.
 There’s no check to ensure valid player names when entering into the system, meaning users could input names
with special characters, spaces, or other unanticipated formats that may cause issues.

4. No Time Limit for Answering Questions:

 There is no timer or limit on how long a player can take to answer each question. This could lead to prolonged
sessions and may not be ideal for users looking for a fast-paced game experience.
 Without a time limit, players could potentially cheat or look up answers online, which undermines the purpose
of testing knowledge.

5. Lack of Feedback for Correct Answers:

 While the program gives feedback for wrong answers, it does not explain why an answer is correct. This can be a
missed opportunity to educate the user further. It could improve the learning experience if it included
explanations for correct answers.

6. No Support for Question Categorization:

 The questions are random, and there is no option to choose questions based on categories (e.g., physics,
chemistry, biology). This limits the educational potential and makes the game feel more like a trivia game than a
focused learning tool.

7. Database Dependency:

 The program is dependent on a MySQL database to store player data and scores. If the database connection fails
or is unavailable, the program will not function correctly. Users who do not have MySQL installed or configured
will not be able to run the program.
8. Lack of Documentation:

 The program does not have comments or documentation explaining its logic. This makes it difficult for others to
modify, maintain, or extend the program. Clear documentation would help others understand how the code
works and how to improve it.

9. No User Experience Improvements:

 The feedback on correct or wrong answers is limited to just text output. There are no graphical elements or
sound effects to enhance user interaction. This may make the game less engaging and entertaining for some
users.

10. No Option to View Past Scores:

 Once the game finishes, there is no functionality for the player to view or review their past scores. A user would
need to go into the database manually to see their score history, which is not user-friendly.
 The program does not have a "profile" for players, meaning it is not possible to track their progress over time in
a meaningful way.


BIBLIOGRAPHY
 w3schools.com
 Chatgpt
 YouTube
(Internet)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy