KEMBAR78
Python 6 | PDF | Length
0% found this document useful (0 votes)
32 views18 pages

Python 6

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

Python 6

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

# database_manager.

py - Enhanced database management


import sqlite3
import json
from datetime import datetime, timedelta
import hashlib

class DatabaseManager:
def __init__(self, db_path="quarix.db"):
self.db_path = db_path
self.init_database()

def init_database(self):
"""Initialize all database tables"""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()

# Users table
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL,
email TEXT UNIQUE NOT NULL,
password_hash TEXT NOT NULL,
coins INTEGER DEFAULT 100,
gems INTEGER DEFAULT 5,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
current_streak INTEGER DEFAULT 0,
last_activity DATE,
total_score INTEGER DEFAULT 0,
avatar_id INTEGER DEFAULT 1,
rank_title TEXT DEFAULT 'Beginner'
)
''')

# Quiz history table


cursor.execute('''
CREATE TABLE IF NOT EXISTS quiz_history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER,
class_level TEXT,
subject TEXT,
topic TEXT,
score REAL,
total_questions INTEGER,
correct_answers INTEGER,
time_taken INTEGER,
completed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users (id)
)
''')
# Achievements table
cursor.execute('''
CREATE TABLE IF NOT EXISTS achievements (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
description TEXT,
icon TEXT,
requirement_type TEXT,
requirement_value INTEGER,
reward_coins INTEGER DEFAULT 0,
reward_gems INTEGER DEFAULT 0
)
''')

# User achievements table


cursor.execute('''
CREATE TABLE IF NOT EXISTS user_achievements (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER,
achievement_id INTEGER,
earned_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users (id),
FOREIGN KEY (achievement_id) REFERENCES achievements
(id)
)
''')

# Shop items table


cursor.execute('''
CREATE TABLE IF NOT EXISTS shop_items (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
description TEXT,
icon TEXT,
price_coins INTEGER DEFAULT 0,
price_gems INTEGER DEFAULT 0,
item_type TEXT,
effect_data TEXT
)
''')

# User inventory table


cursor.execute('''
CREATE TABLE IF NOT EXISTS user_inventory (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER,
item_id INTEGER,
quantity INTEGER DEFAULT 1,
purchased_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users (id),
FOREIGN KEY (item_id) REFERENCES shop_items (id)
)
''')

# Study sessions table


cursor.execute('''
CREATE TABLE IF NOT EXISTS study_sessions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER,
subject TEXT,
topic TEXT,
duration INTEGER,
session_date DATE,
FOREIGN KEY (user_id) REFERENCES users (id)
)
''')

conn.commit()
self.populate_default_data(cursor)
conn.close()

def populate_default_data(self, cursor):


"""Populate default achievements and shop items"""
# Default achievements
achievements = [
("First Steps", "Complete your first quiz", "🎯",
"quiz_count", 1, 50, 0),
("Quiz Master", "Complete 10 quizzes", "🏆", "quiz_count",
10, 200, 1),
("Perfect Score", "Get 100% on a quiz", "⭐",
"perfect_score", 1, 100, 1),
("Streak Starter", "Maintain a 3-day streak", "🔥",
"streak", 3, 150, 0),
("Dedicated Learner", "Maintain a 7-day streak", "📚",
"streak", 7, 300, 2),
("Knowledge Seeker", "Answer 100 questions correctly",
"🧠", "correct_answers", 100, 250, 1),
("Speed Demon", "Complete a quiz in under 2 minutes", "⚡",
"speed", 120, 100, 0),
("Subject Expert", "Get 90%+ in 5 quizzes of same
subject", "🎓", "subject_mastery", 5, 400, 2)
]

for achievement in achievements:


cursor.execute('''
INSERT OR IGNORE INTO achievements
(name, description, icon, requirement_type,
requirement_value, reward_coins, reward_gems)
VALUES (?, ?, ?, ?, ?, ?, ?)
''', achievement)

# Default shop items


shop_items = [
("Double Coins", "Double coins for next quiz", "💰", 100,
0, "powerup", '{"effect": "double_coins", "duration": 1}'),
("Time Freeze", "Freeze your streak for 1 day", "❄️
", 0, 1,
"utility", '{"effect": "streak_freeze", "duration": 1}'),
("Hint Master", "Get hints for next 3 questions", "💡",
150, 0, "powerup", '{"effect": "hints", "quantity": 3}'),
("Lucky Charm", "50% chance to get question right", "🍀",
0, 2, "powerup", '{"effect": "lucky_guess", "quantity": 1}'),
("Study Boost", "Unlock premium study materials", "📖",
300, 0, "upgrade", '{"effect": "premium_study", "duration": 7}'),
("Avatar Frame", "Golden avatar frame", "", 500, 0,
"cosmetic", '{"effect": "avatar_frame", "type": "gold"}'),
("Gem Multiplier", "2x gems for next quiz", "💎", 200, 0,
"powerup", '{"effect": "double_gems", "duration": 1}'),
("Skip Question", "Skip difficult questions", "", 0, 1,
"powerup", '{"effect": "skip_question", "quantity": 2}')
]

for item in shop_items:


cursor.execute('''
INSERT OR IGNORE INTO shop_items
(name, description, icon, price_coins, price_gems,
item_type, effect_data)
VALUES (?, ?, ?, ?, ?, ?, ?)
''', item)

def hash_password(self, password):


"""Hash password for secure storage"""
return hashlib.sha256(password.encode()).hexdigest()

def create_user(self, username, email, password):


"""Create new user account"""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()

try:
password_hash = self.hash_password(password)
cursor.execute('''
INSERT INTO users (username, email, password_hash)
VALUES (?, ?, ?)
''', (username, email, password_hash))

user_id = cursor.lastrowid
conn.commit()
return user_id
except sqlite3.IntegrityError:
return None
finally:
conn.close()

def authenticate_user(self, username, password):


"""Authenticate user login"""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()

password_hash = self.hash_password(password)
cursor.execute('''
SELECT * FROM users WHERE username = ? AND password_hash =
?
''', (username, password_hash))

user = cursor.fetchone()
conn.close()

if user:
return {
'id': user[0],
'username': user[1],
'email': user[2],
'coins': user[4],
'gems': user[5],
'current_streak': user[7],
'total_score': user[9],
'avatar_id': user[10],
'rank_title': user[11]
}
return None

def update_user_stats(self, user_id, coins_earned=0,


gems_earned=0, score_added=0):
"""Update user statistics"""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()

cursor.execute('''
UPDATE users
SET coins = coins + ?, gems = gems + ?, total_score =
total_score + ?,
last_activity = DATE('now')
WHERE id = ?
''', (coins_earned, gems_earned, score_added, user_id))

conn.commit()
conn.close()

def save_quiz_result(self, user_id, class_level, subject, topic,


score, total_questions, correct_answers, time_taken):
"""Save quiz results"""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()

cursor.execute('''
INSERT INTO quiz_history
(user_id, class_level, subject, topic, score,
total_questions, correct_answers, time_taken)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
''', (user_id, class_level, subject, topic, score,
total_questions, correct_answers, time_taken))

conn.commit()
conn.close()

def get_user_statistics(self, user_id):


"""Get comprehensive user statistics"""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()

# Basic stats
cursor.execute('''
SELECT COUNT(*) as total_quizzes,
SUM(total_questions) as total_questions,
SUM(correct_answers) as correct_answers,
AVG(score) as average_score,
SUM(time_taken) as total_time
FROM quiz_history WHERE user_id = ?
''', (user_id,))

stats = cursor.fetchone()

# User info
cursor.execute('SELECT coins, gems, current_streak FROM users
WHERE id = ?', (user_id,))
user_info = cursor.fetchone()

conn.close()

return {
'total_quizzes': stats[0] or 0,
'total_questions': stats[1] or 0,
'correct_answers': stats[2] or 0,
'average_score': stats[3] or 0.0,
'total_time': stats[4] or 0,
'coins': user_info[0] if user_info else 0,
'gems': user_info[1] if user_info else 0,
'current_streak': user_info[2] if user_info else 0
}
def get_leaderboard(self, limit=10):
"""Get top users leaderboard"""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()

cursor.execute('''
SELECT u.username, u.total_score, u.current_streak,
COUNT(qh.id) as quiz_count,
AVG(qh.score) as avg_score
FROM users u
LEFT JOIN quiz_history qh ON u.id = qh.user_id
GROUP BY u.id
ORDER BY u.total_score DESC
LIMIT ?
''', (limit,))

leaderboard = cursor.fetchall()
conn.close()

return [
{
'rank': i + 1,
'username': row[0],
'total_score': row[1],
'current_streak': row[2],
'quiz_count': row[3],
'average_score': row[4] or 0
}
for i, row in enumerate(leaderboard)
]

# Enhanced AI Question Generator


class EnhancedQuestionGenerator:
def __init__(self, api_key=None):
self.api_key = api_key
self.fallback_questions = self.load_fallback_questions()

if api_key and api_key != "YOUR_GEMINI_API_KEY_HERE":


try:
import google.generativeai as genai
genai.configure(api_key=api_key)
self.model = genai.GenerativeModel('gemini-pro')
self.ai_available = True
except Exception as e:
print(f"AI initialization failed: {e}")
self.ai_available = False
else:
self.ai_available = False
def load_fallback_questions(self):
"""Load comprehensive fallback questions"""
return {
"Mathematics": {
"Algebra": [
{
"question": "Solve for x: 2x + 5 = 13",
"options": ["x = 4", "x = 6", "x = 8", "x =
9"],
"correct": 0,
"explanation": "Subtract 5 from both sides: 2x
= 8, then divide by 2: x = 4"
},
{
"question": "What is the value of x² when x =
-3?",
"options": ["6", "-6", "9", "-9"],
"correct": 2,
"explanation": "(-3)² = (-3) × (-3) = 9. When
squaring a negative number, the result is positive."
},
{
"question": "Simplify: 3x + 2x - x",
"options": ["4x", "5x", "6x", "2x"],
"correct": 0,
"explanation": "Combine like terms: 3x + 2x -
x = (3 + 2 - 1)x = 4x"
}
],
"Geometry": [
{
"question": "What is the area of a rectangle
with length 8 and width 5?",
"options": ["13", "26", "40", "80"],
"correct": 2,
"explanation": "Area of rectangle = length ×
width = 8 × 5 = 40 square units"
},
{
"question": "How many degrees are in a
triangle?",
"options": ["90°", "180°", "270°", "360°"],
"correct": 1,
"explanation": "The sum of all angles in any
triangle is always 180°"
}
]
},
"English": {
"Grammar": [
{
"question": "Which sentence is grammatically
correct?",
"options": [
"She don't like apples",
"She doesn't like apples",
"She doesn't likes apples",
"She don't likes apples"
],
"correct": 1,
"explanation": "'She' is third person
singular, so we use 'doesn't' (does not), not 'don't' (do not)"
},
{
"question": "What type of word is 'quickly' in
the sentence 'She ran quickly'?",
"options": ["Noun", "Verb", "Adjective",
"Adverb"],
"correct": 3,
"explanation": "'Quickly' describes how she
ran (modifies the verb), making it an adverb"
}
],
"Literature": [
{
"question": "Who wrote 'Romeo and Juliet'?",
"options": ["Charles Dickens", "William
Shakespeare", "Jane Austen", "Mark Twain"],
"correct": 1,
"explanation": "William Shakespeare wrote the
famous tragedy 'Romeo and Juliet' around 1595"
}
]
},
"Physics": {
"Motion": [
{
"question": "What is the unit of force?",
"options": ["Joule", "Newton", "Watt",
"Pascal"],
"correct": 1,
"explanation": "Force is measured in Newtons
(N), named after Sir Isaac Newton"
},
{
"question": "What is the acceleration due to
gravity on Earth?",
"options": ["9.8 m/s²", "10.8 m/s²", "8.9
m/s²", "11.2 m/s²"],
"correct": 0,
"explanation": "The standard acceleration due
to gravity on Earth is approximately 9.8 m/s²"
}
]
},
"Chemistry": {
"Atoms": [
{
"question": "What is the chemical symbol for
gold?",
"options": ["Go", "Gd", "Au", "Ag"],
"correct": 2,
"explanation": "Gold's symbol is Au, from the
Latin word 'aurum' meaning gold"
},
{
"question": "How many protons does a carbon
atom have?",
"options": ["4", "6", "8", "12"],
"correct": 1,
"explanation": "Carbon has 6 protons, which
defines its atomic number"
}
]
},
"Biology": {
"Human Body": [
{
"question": "Which organ pumps blood through
the body?",
"options": ["Liver", "Lungs", "Heart",
"Kidney"],
"correct": 2,
"explanation": "The heart is a muscular organ
that pumps blood throughout the circulatory system"
},
{
"question": "What is the largest organ in the
human body?",
"options": ["Brain", "Liver", "Lungs",
"Skin"],
"correct": 3,
"explanation": "The skin is the largest organ,
covering the entire body and protecting internal organs"
}
]
}
}

def generate_questions(self, class_level, subject, topic,


num_questions=10, difficulty="medium"):
"""Generate questions using AI or fallback"""
if self.ai_available:
try:
return self.generate_ai_questions(class_level,
subject, topic, num_questions, difficulty)
except Exception as e:
print(f"AI generation failed: {e}")

return self.get_fallback_questions(subject, topic,


num_questions)

def generate_ai_questions(self, class_level, subject, topic,


num_questions, difficulty):
"""Generate questions using Gemini AI"""
prompt = f"""
Generate {num_questions} multiple choice questions for
{class_level} students about {subject} - {topic}.
Difficulty level: {difficulty}

Format each question as JSON with this structure:


{{
"question": "Question text here",
"options": ["Option A", "Option B", "Option C", "Option
D"],
"correct": 0,
"explanation": "Detailed explanation of the correct
answer"
}}

Make questions educational, age-appropriate, and engaging.


Include clear explanations.
Return only valid JSON array of questions.
"""

response = self.model.generate_content(prompt)

try:
# Clean and parse the response
response_text = response.text.strip()
if response_text.startswith('```json'):
response_text = response_text[7:-3]
elif response_text.startswith('```'):
response_text = response_text[3:-3]

questions = json.loads(response_text)

# Validate questions
validated_questions = []
for q in questions:
if self.validate_question(q):
validated_questions.append(q)

return validated_questions[:num_questions]

except Exception as e:
print(f"Error parsing AI response: {e}")
return self.get_fallback_questions(subject, topic,
num_questions)

def validate_question(self, question):


"""Validate question format"""
required_keys = ['question', 'options', 'correct',
'explanation']

if not all(key in question for key in required_keys):


return False

if not isinstance(question['options'], list) or


len(question['options']) != 4:
return False

if not isinstance(question['correct'], int) or


question['correct'] not in range(4):
return False

return True

def get_fallback_questions(self, subject, topic, num_questions):


"""Get fallback questions from local database"""
questions = []

if subject in self.fallback_questions:
subject_questions = self.fallback_questions[subject]

# Try to get questions from specific topic


if topic in subject_questions:
questions.extend(subject_questions[topic])

# If not enough questions, get from other topics in same


subject
if len(questions) < num_questions:
for other_topic, topic_questions in
subject_questions.items():
if other_topic != topic:
questions.extend(topic_questions)
if len(questions) >= num_questions:
break

# If still not enough, get from other subjects


if len(questions) < num_questions:
for other_subject, subject_data in
self.fallback_questions.items():
if other_subject != subject:
for topic_questions in subject_data.values():
questions.extend(topic_questions)
if len(questions) >= num_questions:
break
if len(questions) >= num_questions:
break

# Shuffle and return requested number


import random
random.shuffle(questions)
return questions[:num_questions]

# Achievement System
class AchievementSystem:
def __init__(self, db_manager):
self.db = db_manager

def check_achievements(self, user_id, quiz_data):


"""Check and award achievements based on quiz performance"""
new_achievements = []

# Get user stats


stats = self.db.get_user_statistics(user_id)

# Check various achievement conditions


achievements_to_check = [
self.check_first_quiz(stats),
self.check_quiz_master(stats),
self.check_perfect_score(quiz_data),
self.check_streak_achievements(stats),
self.check_knowledge_seeker(stats),
self.check_speed_demon(quiz_data),
]

for achievement_id in achievements_to_check:


if achievement_id and not
self.user_has_achievement(user_id, achievement_id):
self.award_achievement(user_id, achievement_id)
new_achievements.append(achievement_id)

return new_achievements

def check_first_quiz(self, stats):


"""Check if user completed first quiz"""
return 1 if stats['total_quizzes'] >= 1 else None
def check_quiz_master(self, stats):
"""Check if user completed 10 quizzes"""
return 2 if stats['total_quizzes'] >= 10 else None

def check_perfect_score(self, quiz_data):


"""Check if user got perfect score"""
return 3 if quiz_data.get('score', 0) == 100 else None

def check_streak_achievements(self, stats):


"""Check streak-based achievements"""
streak = stats['current_streak']
if streak >= 7:
return 5 # Dedicated Learner
elif streak >= 3:
return 4 # Streak Starter
return None

def check_knowledge_seeker(self, stats):


"""Check if user answered 100 questions correctly"""
return 6 if stats['correct_answers'] >= 100 else None

def check_speed_demon(self, quiz_data):


"""Check if quiz completed in under 2 minutes"""
return 7 if quiz_data.get('time_taken', float('inf')) < 120
else None

def user_has_achievement(self, user_id, achievement_id):


"""Check if user already has achievement"""
conn = sqlite3.connect(self.db.db_path)
cursor = conn.cursor()

cursor.execute('''
SELECT id FROM user_achievements
WHERE user_id = ? AND achievement_id = ?
''', (user_id, achievement_id))

result = cursor.fetchone()
conn.close()

return result is not None

def award_achievement(self, user_id, achievement_id):


"""Award achievement to user"""
conn = sqlite3.connect(self.db.db_path)
cursor = conn.cursor()

# Add to user achievements


cursor.execute('''
INSERT INTO user_achievements (user_id, achievement_id)
VALUES (?, ?)
''', (user_id, achievement_id))

# Get achievement rewards


cursor.execute('''
SELECT reward_coins, reward_gems FROM achievements WHERE
id = ?
''', (achievement_id,))

rewards = cursor.fetchone()
if rewards:
# Award coins and gems
cursor.execute('''
UPDATE users SET coins = coins + ?, gems = gems + ?
WHERE id = ?
''', (rewards[0], rewards[1], user_id))

conn.commit()
conn.close()

# Enhanced main application with all features


def create_enhanced_main():
"""Create the complete main.py with all enhancements"""

enhanced_main = '''
# main.py - Complete Quarix Quiz Application
import customtkinter as ctk
import tkinter as tk
from tkinter import messagebox
import pygame
import json
import os
import sqlite3
import threading
import time
from datetime import datetime, timedelta
import random
from database_manager import DatabaseManager,
EnhancedQuestionGenerator, AchievementSystem

# Set appearance mode and color theme


ctk.set_appearance_mode("dark")
ctk.set_default_color_theme("blue")

class QuarixApp:
def __init__(self):
# Initialize pygame for sound
pygame.mixer.init()

# Initialize database and systems


self.db_manager = DatabaseManager()
self.achievement_system = AchievementSystem(self.db_manager)

# Load configuration
self.load_config()

# Initialize question generator


api_key = self.config.get("gemini_api_key", "")
self.question_generator = EnhancedQuestionGenerator(api_key)

# Initialize main window


self.root = ctk.CTk()
self.root.title("Quarix - AI-Powered Quiz App")
self.root.geometry("1200x800")
self.root.minsize(1000, 700)

# Center window on screen


self.center_window()

# Initialize variables
self.current_user = None
self.current_questions = []
self.current_question_index = 0
self.user_answers = []
self.quiz_start_time = None
self.selected_option = tk.StringVar()

# Create main interface


self.create_main_interface()

# Show splash screen


self.show_splash_screen()

def load_config(self):
"""Load application configuration"""
try:
with open("config.json", "r") as f:
self.config = json.load(f)
except FileNotFoundError:
self.config = {
"gemini_api_key": "",
"app_settings": {
"theme": "dark",
"sound_enabled": True,
"auto_advance": True,
"default_questions": 10
}
}

def center_window(self):
"""Center the window on screen"""
self.root.update_idletasks()
width = self.root.winfo_width()
height = self.root.winfo_height()
x = (self.root.winfo_screenwidth() // 2) - (width // 2)
y = (self.root.winfo_screenheight() // 2) - (height // 2)
self.root.geometry(f"{width}x{height}+{x}+{y}")

def create_main_interface(self):
"""Create the main application interface"""
# Main container
self.main_frame = ctk.CTkFrame(self.root)
self.main_frame.pack(fill="both", expand=True, padx=10,
pady=10)

# Header frame
self.header_frame = ctk.CTkFrame(self.main_frame, height=80)
self.header_frame.pack(fill="x", padx=10, pady=(10, 5))
self.header_frame.pack_propagate(False)

# Content frame
self.content_frame = ctk.CTkFrame(self.main_frame)
self.content_frame.pack(fill="both", expand=True, padx=10,
pady=5)

# Footer frame
self.footer_frame = ctk.CTkFrame(self.main_frame, height=50)
self.footer_frame.pack(fill="x", padx=10, pady=(5, 10))
self.footer_frame.pack_propagate(False)

# Create header content


self.create_header()
self.create_footer()

def create_header(self):
"""Create application header"""
# Logo and title
title_frame = ctk.CTkFrame(self.header_frame)
title_frame.pack(side="left", fill="y", padx=20, pady=15)

logo_label = ctk.CTkLabel(
title_frame,
text="🧠 QUARIX",
font=("Arial", 24, "bold"),
text_color=("#00d4ff", "#ffffff")
)
logo_label.pack(side="left", padx=10)

subtitle_label = ctk.CTkLabel(
title_frame,
text="AI-Powered Learning Platform",
font=("Arial", 12),
text_color=("#888888", "#CCCCCC")
)
subtitle_label.pack(side="left", padx=(0, 10))

# User info frame


self.user_info_frame = ctk.CTkFrame(self.header_frame)
self.user_info_frame.pack(side="right", fill="y", padx=20,
pady=15)

self.update_user_info()

def update_user_info(self):
"""Update user information in header"""
# Clear existing widgets
for widget in self.user_info_frame.winfo_children():
widget.destroy()

if self.current_user:
# User name
user_label = ctk.CTkLabel(
self.user_info_frame,
text=f"👤 {self.current_user['username']}",
font=("Arial", 14, "bold")
)
user_label.pack(side="left", padx=10, pady=10)

# Coins
coins_label = ctk.CTkLabel(
self.user_info_frame

You might also like