Quiz Game with Leaderboard 🎮

import tkinter as tk

from tkinter import messagebox

import random

import json


# Load questions from a JSON file or use a dictionary

questions = [

    {"question": "What keyword is used to define a function in Python?", 

     "options": ["func", "define", "def", "function"], 

     "answer": "def"},

    

    {"question": "Which of the following is used to create a loop in Python?", 

     "options": ["for", "while", "do-while", "Both A and B"], 

     "answer": "Both A and B"},

    

    {"question": "What is the correct way to open a file in read mode?", 

     "options": ["open('file.txt', 'r')", "open('file.txt', 'w')", "open('file.txt', 'rw')", "open('file.txt')"], 

     "answer": "open('file.txt', 'r')"},

    

    {"question": "Which data structure follows the Last In, First Out (LIFO) principle?", 

     "options": ["Queue", "Stack", "List", "Dictionary"], 

     "answer": "Stack"},

    

    {"question": "Which method is used to add an element to a list?", 

     "options": ["append()", "insert()", "extend()", "add()"], 

     "answer": "append()"},

    

    {"question": "Which library is commonly used for data analysis in Python?", 

     "options": ["NumPy", "Pandas", "Matplotlib", "Seaborn"], 

     "answer": "Pandas"},

    

    {"question": "Which symbol is used to comment a single line in Python?", 

     "options": ["//", "#", "/*", "--"], 

     "answer": "#"},

    

    {"question": "What will be the output of `len(['Python', 'Java', 'C++'])`?", 

     "options": ["2", "3", "4", "Error"], 

     "answer": "3"},

    

    {"question": "What does the `range(5)` function return?", 

     "options": ["[1,2,3,4,5]", "[0,1,2,3,4]", "(0,1,2,3,4)", "None"], 

     "answer": "[0,1,2,3,4]"},

    

    {"question": "Which of the following is a mutable data type in Python?", 

     "options": ["Tuple", "String", "List", "Integer"], 

     "answer": "List"}

]



# Load leaderboard from file

def load_leaderboard():

    try:

        with open("leaderboard.json", "r") as f:

            return json.load(f)

    except FileNotFoundError:

        return {}


# Save leaderboard to file

def save_leaderboard(leaderboard):

    with open("leaderboard.json", "w") as f:

        json.dump(leaderboard, f, indent=4)


class QuizGame:

    def __init__(self, root):

        self.root = root

        self.root.title("Quiz Game with Leaderboard")

        self.root.geometry("500x400")


        self.score = 0

        self.current_question = 0

        self.username = ""


        self.start_screen()


    def start_screen(self):

        """Start screen to enter player's name."""

        self.clear_window()

        

        tk.Label(self.root, text="Enter Your Name:", font=("Arial", 14)).pack(pady=10)

        self.name_entry = tk.Entry(self.root, font=("Arial", 12))

        self.name_entry.pack(pady=5)

        

        tk.Button(self.root, text="Start Quiz", command=self.start_quiz, font=("Arial", 12)).pack(pady=20)


    def start_quiz(self):

        """Start the quiz after getting the user's name."""

        self.username = self.name_entry.get()

        if not self.username:

            messagebox.showerror("Error", "Please enter your name!")

            return

        

        random.shuffle(questions)

        self.score = 0

        self.current_question = 0

        self.show_question()


    def show_question(self):

        """Display a question and answer options."""

        self.clear_window()

        

        if self.current_question < len(questions):

            q_data = questions[self.current_question]

            self.correct_answer = q_data["answer"]


            tk.Label(self.root, text=f"Q{self.current_question + 1}: {q_data['question']}", font=("Arial", 14), wraplength=400).pack(pady=10)

            

            self.answer_var = tk.StringVar()


            for option in q_data["options"]:

                tk.Radiobutton(self.root, text=option, variable=self.answer_var, value=option, font=("Arial", 12)).pack(anchor="w", padx=20)

            

            tk.Button(self.root, text="Submit", command=self.check_answer, font=("Arial", 12)).pack(pady=10)

        

        else:

            self.show_result()


    def check_answer(self):

        """Check the selected answer."""

        selected_answer = self.answer_var.get()

        

        if not selected_answer:

            messagebox.showerror("Error", "Please select an answer!")

            return

        

        if selected_answer == self.correct_answer:

            self.score += 1

        

        self.current_question += 1

        self.show_question()


    def show_result(self):

        """Display the final score and update leaderboard."""

        self.clear_window()

        

        leaderboard = load_leaderboard()

        leaderboard[self.username] = self.score

        save_leaderboard(leaderboard)


        tk.Label(self.root, text=f"Quiz Over! {self.username}, your score: {self.score}/{len(questions)}", font=("Arial", 14)).pack(pady=10)


        tk.Button(self.root, text="View Leaderboard", command=self.show_leaderboard, font=("Arial", 12)).pack(pady=10)

        tk.Button(self.root, text="Play Again", command=self.start_screen, font=("Arial", 12)).pack(pady=5)

        tk.Button(self.root, text="Exit", command=self.root.quit, font=("Arial", 12)).pack(pady=5)


    def show_leaderboard(self):

        """Display the leaderboard."""

        self.clear_window()

        leaderboard = load_leaderboard()

        sorted_leaderboard = sorted(leaderboard.items(), key=lambda x: x[1], reverse=True)


        tk.Label(self.root, text="🏆 Leaderboard 🏆", font=("Arial", 16, "bold")).pack(pady=10)


        for rank, (player, high_score) in enumerate(sorted_leaderboard, start=1):

            tk.Label(self.root, text=f"{rank}. {player} - {high_score}", font=("Arial", 12)).pack()


        tk.Button(self.root, text="Back to Menu", command=self.start_screen, font=("Arial", 12)).pack(pady=10)


    def clear_window(self):

        """Clear the window for new content."""

        for widget in self.root.winfo_children():

            widget.destroy()


# Run the application

if __name__ == "__main__":

    root = tk.Tk()

    app = QuizGame(root)

    root.mainloop()

Habit Tracker

 import sqlite3

import tkinter as tk

from tkinter import messagebox


# Database Setup

conn = sqlite3.connect("habits.db")

cursor = conn.cursor()

cursor.execute("""

    CREATE TABLE IF NOT EXISTS habits (

        id INTEGER PRIMARY KEY AUTOINCREMENT,

        name TEXT NOT NULL,

        status TEXT DEFAULT 'Pending'

    )

""")

conn.commit()


# Function to add a new habit

def add_habit():

    habit_name = habit_entry.get().strip()

    if habit_name:

        cursor.execute("INSERT INTO habits (name, status) VALUES (?, 'Pending')", (habit_name,))

        conn.commit()

        habit_entry.delete(0, tk.END)

        load_habits()

    else:

        messagebox.showwarning("Warning", "Please enter a habit name!")


# Function to mark a habit as completed

def complete_habit(habit_id):

    cursor.execute("UPDATE habits SET status = 'Completed' WHERE id = ?", (habit_id,))

    conn.commit()

    load_habits()


# Function to delete a habit

def delete_habit(habit_id):

    cursor.execute("DELETE FROM habits WHERE id = ?", (habit_id,))

    conn.commit()

    load_habits()


# Function to load habits from the database

def load_habits():

    habit_list.delete(0, tk.END)

    cursor.execute("SELECT id, name, status FROM habits")

    for habit in cursor.fetchall():

        habit_id, name, status = habit

        habit_list.insert(tk.END, f"{habit_id}. {name} - {status}")


# GUI Setup

root = tk.Tk()

root.title("Habit Tracker")

root.geometry("400x500")


tk.Label(root, text="Enter a New Habit:", font=("Arial", 12)).pack(pady=5)

habit_entry = tk.Entry(root, width=40)

habit_entry.pack(pady=5)

tk.Button(root, text="Add Habit", command=add_habit).pack(pady=5)


tk.Label(root, text="Your Habits:", font=("Arial", 12)).pack(pady=5)

habit_list = tk.Listbox(root, width=50, height=10)

habit_list.pack()


tk.Button(root, text="Mark as Completed", command=lambda: complete_habit(habit_list.get(tk.ACTIVE).split('.')[0])).pack(pady=5)

tk.Button(root, text="Delete Habit", command=lambda: delete_habit(habit_list.get(tk.ACTIVE).split('.')[0])).pack(pady=5)


load_habits()


root.mainloop()


Secure Notes App

 import os

import tkinter as tk

from tkinter import messagebox, simpledialog

from cryptography.fernet import Fernet


# Generate a key file if it doesn’t exist

KEY_FILE = "secret.key"

NOTES_FILE = "secure_notes.txt"


def generate_key():

    key = Fernet.generate_key()

    with open(KEY_FILE, "wb") as key_file:

        key_file.write(key)


def load_key():

    if not os.path.exists(KEY_FILE):

        generate_key()

    with open(KEY_FILE, "rb") as key_file:

        return key_file.read()


# Load encryption key

key = load_key()

cipher_suite = Fernet(key)


def encrypt_message(message):

    return cipher_suite.encrypt(message.encode()).decode()


def decrypt_message(encrypted_message):

    return cipher_suite.decrypt(encrypted_message.encode()).decode()


def save_note():

    note = note_text.get("1.0", tk.END).strip()

    if not note:

        messagebox.showwarning("Warning", "Note cannot be empty!")

        return

    

    encrypted_note = encrypt_message(note)

    with open(NOTES_FILE, "a") as file:

        file.write(encrypted_note + "\n")

    

    messagebox.showinfo("Success", "Note saved securely!")

    note_text.delete("1.0", tk.END)


def load_notes():

    if not os.path.exists(NOTES_FILE):

        messagebox.showinfo("No Notes", "No saved notes found.")

        return

    

    with open(NOTES_FILE, "r") as file:

        encrypted_notes = file.readlines()

    

    if not encrypted_notes:

        messagebox.showinfo("No Notes", "No saved notes found.")

        return


    password = simpledialog.askstring("Password", "Enter decryption password:", show="*")

    

    if password:  # Dummy check

        try:

            decrypted_notes = [decrypt_message(note.strip()) for note in encrypted_notes]

            messagebox.showinfo("Your Notes", "\n\n".join(decrypted_notes))

        except Exception as e:

            messagebox.showerror("Error", "Failed to decrypt notes.")

    else:

        messagebox.showwarning("Warning", "Password cannot be empty!")


# GUI Setup

root = tk.Tk()

root.title("Secure Notes App")

root.geometry("400x400")


tk.Label(root, text="Enter your note:", font=("Arial", 12)).pack(pady=5)

note_text = tk.Text(root, height=8, width=40)

note_text.pack()


save_btn = tk.Button(root, text="Save Note", command=save_note)

save_btn.pack(pady=5)


load_btn = tk.Button(root, text="Load Notes", command=load_notes)

load_btn.pack(pady=5)


root.mainloop()


Password Manager

 import sqlite3

import tkinter as tk

from tkinter import messagebox

from cryptography.fernet import Fernet

import random

import string

import os


# Generate and save encryption key

KEY_FILE = "key.key"


def generate_key():

    if not os.path.exists(KEY_FILE):

        key = Fernet.generate_key()

        with open(KEY_FILE, "wb") as key_file:

            key_file.write(key)


def load_key():

    with open(KEY_FILE, "rb") as key_file:

        return key_file.read()


generate_key()

key = load_key()

cipher = Fernet(key)


# Database Setup

conn = sqlite3.connect("passwords.db")

cursor = conn.cursor()

cursor.execute("""

    CREATE TABLE IF NOT EXISTS passwords (

        id INTEGER PRIMARY KEY,

        website TEXT,

        username TEXT,

        password TEXT

    )

""")

conn.commit()


# Function to encrypt password

def encrypt_password(password):

    return cipher.encrypt(password.encode()).decode()


# Function to decrypt password

def decrypt_password(encrypted_password):

    return cipher.decrypt(encrypted_password.encode()).decode()


# Function to generate a random password

def generate_password():

    characters = string.ascii_letters + string.digits + string.punctuation

    return ''.join(random.choice(characters) for _ in range(12))


# Function to save credentials

def save_password():

    website = website_entry.get()

    username = username_entry.get()

    password = password_entry.get()


    if not website or not username or not password:

        messagebox.showerror("Error", "All fields are required!")

        return


    encrypted_password = encrypt_password(password)

    cursor.execute("INSERT INTO passwords (website, username, password) VALUES (?, ?, ?)",

                   (website, username, encrypted_password))

    conn.commit()

    messagebox.showinfo("Success", "Password saved successfully!")


    website_entry.delete(0, tk.END)

    username_entry.delete(0, tk.END)

    password_entry.delete(0, tk.END)


# Function to retrieve passwords

def retrieve_passwords():

    cursor.execute("SELECT website, username, password FROM passwords")

    records = cursor.fetchall()


    result_text.delete(1.0, tk.END)

    for record in records:

        website, username, encrypted_password = record

        decrypted_password = decrypt_password(encrypted_password)

        result_text.insert(tk.END, f"Website: {website}\nUsername: {username}\nPassword: {decrypted_password}\n\n")


# Function to generate a random password

def fill_generated_password():

    password_entry.delete(0, tk.END)

    password_entry.insert(0, generate_password())


# GUI Setup

root = tk.Tk()

root.title("Password Manager")

root.geometry("400x500")


tk.Label(root, text="Website:").pack()

website_entry = tk.Entry(root, width=40)

website_entry.pack()


tk.Label(root, text="Username:").pack()

username_entry = tk.Entry(root, width=40)

username_entry.pack()


tk.Label(root, text="Password:").pack()

password_entry = tk.Entry(root, width=40, show="*")

password_entry.pack()


tk.Button(root, text="Generate Password", command=fill_generated_password).pack(pady=5)

tk.Button(root, text="Save Password", command=save_password).pack(pady=5)

tk.Button(root, text="Retrieve Passwords", command=retrieve_passwords).pack(pady=5)


result_text = tk.Text(root, height=10, width=45)

result_text.pack()


root.mainloop()