Custom Retro Snake Game with Skins

import pygame

import tkinter as tk

from tkinter import filedialog, simpledialog

from PIL import Image

import os

import random

import sys


# === Constants ===

TILE_SIZE = 20

DEFAULT_GRID = 20

FPS = 10


# === Globals (updated via GUI) ===

snake_head_img_path = "assets/default_head.png"

snake_body_img_path = "assets/default_body.png"

GRID_SIZE = DEFAULT_GRID



def load_skin(path, size):

    img = Image.open(path).resize((size, size)).convert("RGBA")

    return pygame.image.fromstring(img.tobytes(), img.size, img.mode)



def ask_user_inputs():

    global snake_head_img_path, snake_body_img_path, GRID_SIZE


    root = tk.Tk()

    root.withdraw()


    if filedialog.askyesno("Snake Skin", "Do you want to upload custom snake head image?"):

        snake_head_img_path = filedialog.askopenfilename(title="Select Head Image")


    if filedialog.askyesno("Snake Skin", "Do you want to upload custom snake body image?"):

        snake_body_img_path = filedialog.askopenfilename(title="Select Body Image")


    try:

        GRID_SIZE = int(simpledialog.askstring("Grid Size", "Enter grid size (e.g., 20 for 20x20):") or DEFAULT_GRID)

    except:

        GRID_SIZE = DEFAULT_GRID



def draw_grid(screen, color=(40, 40, 40)):

    for x in range(0, GRID_SIZE * TILE_SIZE, TILE_SIZE):

        for y in range(0, GRID_SIZE * TILE_SIZE, TILE_SIZE):

            rect = pygame.Rect(x, y, TILE_SIZE, TILE_SIZE)

            pygame.draw.rect(screen, color, rect, 1)



class Snake:

    def __init__(self):

        self.body = [(5, 5), (4, 5), (3, 5)]

        self.direction = (1, 0)

        self.grow = False


    def move(self):

        head = self.body[0]

        new_head = (head[0] + self.direction[0], head[1] + self.direction[1])

        self.body.insert(0, new_head)

        if not self.grow:

            self.body.pop()

        else:

            self.grow = False


    def change_direction(self, new_dir):

        # Prevent reversing

        if (new_dir[0] * -1, new_dir[1] * -1) != self.direction:

            self.direction = new_dir


    def draw(self, screen, head_img, body_img):

        for i, segment in enumerate(self.body):

            x, y = segment[0] * TILE_SIZE, segment[1] * TILE_SIZE

            if i == 0:

                screen.blit(head_img, (x, y))

            else:

                screen.blit(body_img, (x, y))


    def check_collision(self):

        head = self.body[0]

        return (

            head in self.body[1:] or

            head[0] < 0 or head[1] < 0 or

            head[0] >= GRID_SIZE or head[1] >= GRID_SIZE

        )



def generate_food(snake):

    while True:

        pos = (random.randint(0, GRID_SIZE - 1), random.randint(0, GRID_SIZE - 1))

        if pos not in snake.body:

            return pos



def main():

    ask_user_inputs()


    pygame.init()

    screen = pygame.display.set_mode((GRID_SIZE * TILE_SIZE, GRID_SIZE * TILE_SIZE))

    pygame.display.set_caption("šŸ Custom Snake Game")

    clock = pygame.time.Clock()


    head_img = load_skin(snake_head_img_path, TILE_SIZE)

    body_img = load_skin(snake_body_img_path, TILE_SIZE)


    snake = Snake()

    food = generate_food(snake)


    running = True

    while running:

        clock.tick(FPS)

        screen.fill((0, 0, 0))

        draw_grid(screen)


        for event in pygame.event.get():

            if event.type == pygame.QUIT:

                running = False

            elif event.type == pygame.KEYDOWN:

                if event.key == pygame.K_UP:

                    snake.change_direction((0, -1))

                elif event.key == pygame.K_DOWN:

                    snake.change_direction((0, 1))

                elif event.key == pygame.K_LEFT:

                    snake.change_direction((-1, 0))

                elif event.key == pygame.K_RIGHT:

                    snake.change_direction((1, 0))


        snake.move()


        if snake.body[0] == food:

            snake.grow = True

            food = generate_food(snake)


        if snake.check_collision():

            print("Game Over!")

            pygame.quit()

            sys.exit()


        snake.draw(screen, head_img, body_img)

        fx, fy = food[0] * TILE_SIZE, food[1] * TILE_SIZE

        pygame.draw.rect(screen, (255, 0, 0), (fx, fy, TILE_SIZE, TILE_SIZE))


        pygame.display.flip()



if __name__ == "__main__":

    main()


Telegram Bot File Vault

 pip install python-telegram-bot==13.15


import os
import sqlite3
import uuid
import logging
from telegram import Update, File
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackContext

# === Config ===
BOT_TOKEN = 'YOUR_BOT_TOKEN_HERE'
FILES_DIR = "files"
os.makedirs(FILES_DIR, exist_ok=True)

# === Logger ===
logging.basicConfig(level=logging.INFO)

# === Database ===
conn = sqlite3.connect("vault.db", check_same_thread=False)
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS files (
    id TEXT PRIMARY KEY,
    user_id INTEGER,
    file_name TEXT,
    file_path TEXT,
    tags TEXT
)
''')
conn.commit()

# === Command Handlers ===

def start(update: Update, context: CallbackContext):
    update.message.reply_text("šŸ“ Welcome to File Vault Bot!\nSend me a file and add tags in the caption.")

def handle_file(update: Update, context: CallbackContext):
    file = update.message.document or update.message.photo[-1] if update.message.photo else None
    caption = update.message.caption or ""
    tags = caption.strip() if caption else "untagged"
    
    if not file:
        update.message.reply_text("❌ Unsupported file type.")
        return

    file_id = str(uuid.uuid4())
    file_name = file.file_name if hasattr(file, 'file_name') else f"{file_id}.jpg"
    file_path = os.path.join(FILES_DIR, file_name)

    telegram_file: File = context.bot.get_file(file.file_id)
    telegram_file.download(file_path)

    cursor.execute("INSERT INTO files VALUES (?, ?, ?, ?, ?)",
                   (file_id, update.message.from_user.id, file_name, file_path, tags))
    conn.commit()

    update.message.reply_text(f"✅ File saved with ID: {file_id} and tags: {tags}")

def get_file(update: Update, context: CallbackContext):
    if not context.args:
        update.message.reply_text("Usage: /get filename")
        return

    file_name = " ".join(context.args)
    cursor.execute("SELECT file_path FROM files WHERE file_name=?", (file_name,))
    result = cursor.fetchone()

    if result:
        update.message.reply_document(open(result[0], "rb"))
    else:
        update.message.reply_text("❌ File not found.")

def search_by_tag(update: Update, context: CallbackContext):
    if not context.args:
        update.message.reply_text("Usage: /search tag")
        return

    tag = " ".join(context.args)
    cursor.execute("SELECT file_name, tags FROM files")
    results = cursor.fetchall()

    found = [name for name, tags in results if tag.lower() in tags.lower()]
    if found:
        update.message.reply_text("šŸ” Matching files:\n" + "\n".join(found))
    else:
        update.message.reply_text("❌ No matching files.")

# === Main Bot ===

def main():
    updater = Updater(BOT_TOKEN)
    dp = updater.dispatcher

    dp.add_handler(CommandHandler("start", start))
    dp.add_handler(CommandHandler("get", get_file))
    dp.add_handler(CommandHandler("search", search_by_tag))
    dp.add_handler(MessageHandler(Filters.document | Filters.photo, handle_file))

    updater.start_polling()
    print("Bot started.")
    updater.idle()

if __name__ == '__main__':
    main()

WhatsApp Chat Analyzer

pip install pandas matplotlib emoji


import re

import emoji

import pandas as pd

import matplotlib.pyplot as plt

from collections import Counter


# Define anger and happy keywords

anger_keywords = ['angry', 'hate', 'stupid', 'idiot', 'mad', 'annoy', 'fight']

happy_keywords = ['happy', 'love', 'joy', 'awesome', 'great', '😊', '😁', 'šŸ˜']


def extract_chat_data(chat_file):

    with open(chat_file, 'r', encoding='utf-8') as f:

        lines = f.readlines()


    chat_data = []

    for line in lines:

        # Match typical WhatsApp line format

        match = re.match(r'^(\d{1,2}/\d{1,2}/\d{2,4}),\s(\d{1,2}:\d{2})\s[-–]\s(.+?):\s(.+)', line)

        if match:

            date, time, sender, message = match.groups()

            chat_data.append([date, time, sender, message])

    return pd.DataFrame(chat_data, columns=['Date', 'Time', 'Sender', 'Message'])


def count_emojis(text):

    return [char for char in text if char in emoji.EMOJI_DATA]


def analyze_emojis(df):

    emoji_counter = Counter()

    sender_emoji = {}


    for _, row in df.iterrows():

        emojis = count_emojis(row['Message'])

        emoji_counter.update(emojis)

        sender = row['Sender']

        if sender not in sender_emoji:

            sender_emoji[sender] = Counter()

        sender_emoji[sender].update(emojis)

    

    return emoji_counter.most_common(10), sender_emoji


def analyze_mood(df):

    mood_scores = []

    for _, row in df.iterrows():

        message = row['Message'].lower()

        mood = 0

        mood += sum(word in message for word in happy_keywords)

        mood -= sum(word in message for word in anger_keywords)

        mood_scores.append(mood)

    df['MoodScore'] = mood_scores

    return df


def plot_top_emoji_users(sender_emoji):

    emoji_counts = {sender: sum(emojis.values()) for sender, emojis in sender_emoji.items()}

    users = list(emoji_counts.keys())

    counts = list(emoji_counts.values())


    plt.figure(figsize=(8, 4))

    plt.bar(users, counts, color='teal')

    plt.title("Emoji Usage by User")

    plt.ylabel("Total Emojis Used")

    plt.xticks(rotation=45)

    plt.tight_layout()

    plt.show()


def plot_mood_over_time(df):

    mood_by_day = df.groupby("Date")["MoodScore"].sum()

    plt.figure(figsize=(8, 4))

    mood_by_day.plot(kind="line", marker="o", color="purple")

    plt.title("Mood Trend Over Time")

    plt.xlabel("Date")

    plt.ylabel("Mood Score")

    plt.xticks(rotation=45)

    plt.tight_layout()

    plt.show()


if __name__ == "__main__":

    chat_file = "chat.txt"  # exported WhatsApp chat file

    df = extract_chat_data(chat_file)


    df = analyze_mood(df)

    top_emojis, sender_emoji = analyze_emojis(df)


    print("\nšŸ” Top Emojis Used:")

    for emo, count in top_emojis:

        print(f"{emo}: {count}")


    print("\nšŸ™‹‍♂️ Emoji Usage by Users:")

    for sender, emojis in sender_emoji.items():

        print(f"{sender}: {sum(emojis.values())} emojis")


    plot_top_emoji_users(sender_emoji)

    plot_mood_over_time(df)

 

File Compression Tool

pip install pyminizip

import tkinter as tk
from tkinter import filedialog, messagebox
import os
import zipfile
import pyminizip

class FileCompressorApp:
    def __init__(self, root):
        self.root = root
        self.root.title("File Compression Tool šŸ—œ️")
        self.root.geometry("450x300")
        self.files = []

        self.label = tk.Label(root, text="Drag and Drop Files or Use 'Browse'", font=("Helvetica", 12))
        self.label.pack(pady=10)

        self.file_listbox = tk.Listbox(root, width=50, height=8)
        self.file_listbox.pack()

        self.browse_button = tk.Button(root, text="Browse Files", command=self.browse_files)
        self.browse_button.pack(pady=5)

        self.password_label = tk.Label(root, text="Password (optional):")
        self.password_label.pack()
        self.password_entry = tk.Entry(root, show="*")
        self.password_entry.pack(pady=2)

        self.compress_button = tk.Button(root, text="Compress to ZIP", command=self.compress_files)
        self.compress_button.pack(pady=10)

    def browse_files(self):
        paths = filedialog.askopenfilenames()
        for path in paths:
            if path not in self.files:
                self.files.append(path)
                self.file_listbox.insert(tk.END, path)

    def compress_files(self):
        if not self.files:
            messagebox.showerror("No Files", "Please select files to compress.")
            return

        zip_path = filedialog.asksaveasfilename(defaultextension=".zip", filetypes=[("ZIP files", "*.zip")])
        if not zip_path:
            return

        password = self.password_entry.get()

        try:
            if password:
                # Use pyminizip for password protection
                compression_level = 5
                pyminizip.compress_multiple(self.files, [], zip_path, password, compression_level)
            else:
                # Use zipfile for normal compression
                with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zipf:
                    for file in self.files:
                        arcname = os.path.basename(file)
                        zipf.write(file, arcname)

            messagebox.showinfo("Success", f"Files compressed successfully to:\n{zip_path}")
        except Exception as e:
            messagebox.showerror("Error", f"Compression failed:\n{str(e)}")

if __name__ == "__main__":
    root = tk.Tk()
    app = FileCompressorApp(root)
    root.mainloop()

Live Webcam Effects App

pip install opencv-python dlib numpy imutils


live_webcam_filters.py


import cv2
import dlib
import numpy as np

# Load face detector and landmark predictor
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")

# Load overlay images (with transparency)
glasses = cv2.imread("filters/glasses.png", cv2.IMREAD_UNCHANGED)
mustache = cv2.imread("filters/mustache.png", cv2.IMREAD_UNCHANGED)
dog_ears = cv2.imread("filters/dog_ears.png", cv2.IMREAD_UNCHANGED)

def overlay_transparent(background, overlay, x, y, scale=1):
    """Overlay PNG with alpha channel"""
    overlay = cv2.resize(overlay, (0, 0), fx=scale, fy=scale)
    h, w, _ = overlay.shape

    if x + w > background.shape[1] or y + h > background.shape[0]:
        return background

    alpha_overlay = overlay[:, :, 3] / 255.0
    for c in range(0, 3):
        background[y:y+h, x:x+w, c] = background[y:y+h, x:x+w, c] * (1 - alpha_overlay) + overlay[:, :, c] * alpha_overlay
    return background

cap = cv2.VideoCapture(0)

while True:
    ret, frame = cap.read()
    if not ret:
        break

    # Flip frame for mirror effect
    frame = cv2.flip(frame, 1)
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    faces = detector(gray)

    for face in faces:
        landmarks = predictor(gray, face)

        # Coordinates for glasses
        left_eye = (landmarks.part(36).x, landmarks.part(36).y)
        right_eye = (landmarks.part(45).x, landmarks.part(45).y)
        eye_center = ((left_eye[0] + right_eye[0]) // 2, (left_eye[1] + right_eye[1]) // 2)
        eye_width = int(1.5 * abs(right_eye[0] - left_eye[0]))
        glasses_resized = cv2.resize(glasses, (eye_width, int(glasses.shape[0] * eye_width / glasses.shape[1])))
        frame = overlay_transparent(frame, glasses_resized, eye_center[0] - eye_width // 2, eye_center[1] - 25)

        # Coordinates for mustache
        nose = (landmarks.part(33).x, landmarks.part(33).y)
        mustache_resized = cv2.resize(mustache, (eye_width, int(mustache.shape[0] * eye_width / mustache.shape[1])))
        frame = overlay_transparent(frame, mustache_resized, nose[0] - eye_width // 2, nose[1] + 10)

        # Dog ears
        top_head = (landmarks.part(27).x, landmarks.part(27).y - 100)
        ears_resized = cv2.resize(dog_ears, (eye_width * 2, int(dog_ears.shape[0] * (eye_width * 2) / dog_ears.shape[1])))
        frame = overlay_transparent(frame, ears_resized, top_head[0] - eye_width, top_head[1])

    cv2.imshow("Live Webcam Filters šŸ§‘‍šŸŽ¤", frame)
    if cv2.waitKey(1) == 27:
        break  # ESC to quit

cap.release()
cv2.destroyAllWindows()