Code Examples

A showcase of my coding style, problem-solving approach, and technical expertise
across various programming languages and frameworks.

JavaScript Examples - Interactive Demos

Casino Slot Machine Game

A fully functional slot machine with animations, sound effects simulation, and win calculations.

Blackjack Card Game

Play Blackjack against the dealer with proper game logic, card counting, and betting system.

Roulette Wheel Game

Animated roulette wheel with betting on numbers, colors, odds/evens, and realistic spinning animation.

Python Examples

Decorator for Function Timing

A chat UI using gemini's free api key.

import tkinter as tk
import threading
from datetime import datetime
import random  # (still used elsewhere – kept for completeness)

import markdown
from tkinterweb import HtmlFrame
import google.generativeai as genai

from api.gemini import GEMINI_API_KEY


# --------------------------------------------------------------------------- #
#  Gemini / Google-Generative-AI set-up                                       #
# --------------------------------------------------------------------------- #
# One global configuration call is enough for the whole application.
genai.configure(api_key=GEMINI_API_KEY)

# Create a model instance once and keep a single chat session so the model can
# remember the full conversation history.
MODEL_NAME = "gemini-2.5-flash"                 # adjust to whichever model you prefer
_GEN_MODEL = genai.GenerativeModel(MODEL_NAME)
_CHAT_SESSION = _GEN_MODEL.start_chat(history=[])  # remembers all messages


class TerminalChat:
    # --------------------------- UI helpers -------------------------------- #
    def _scroll_to_bottom(self):
        """
        Ensure the scrollbar always sits at the bottom after updating the HTML
        (works for both HtmlFrame < 5.0 and >= 5.0).
        """
        try:
            self.chat_display.text.yview_moveto(1.0)
        except AttributeError:
            try:
                self.chat_display.yview_moveto(1.0)
            except Exception:
                pass

    # -----------------------------  init  ---------------------------------- #
    def __init__(self, root: tk.Tk):
        self.root = root
        self.root.title("Gemini AI Terminal Chat")
        self.root.configure(bg="black")

        # Optional window icon
        try:
            self.root.iconphoto(False, tk.PhotoImage(file="aiicon.png"))
        except tk.TclError:
            pass  # icon not found – fail silently

        # Chat content for the HtmlFrame (HTML strings)
        self.chat_content: list[str] = []
        self.is_thinking: bool = False

        # ------------------------------------------------------------------- #
        # Styling (pure HTML/CSS – injected into each render)                 #
        # ------------------------------------------------------------------- #
        self.style = """
        
        """

        # --------------------------- Layout -------------------------------- #
        self.chat_frame = tk.Frame(root, bg="black")
        self.chat_frame.pack(expand=True, fill="both", padx=10, pady=5)

        self.chat_display = HtmlFrame(self.chat_frame)
        self.chat_display.pack(expand=True, fill="both")

        # --------------------------- Input area ---------------------------- #
        self.input_frame = tk.Frame(root, bg="black")
        self.input_frame.pack(fill="x", padx=10, pady=5)

        self.prompt_label = tk.Label(
            self.input_frame,
            text=">>",
            bg="black",
            fg="#00ff00",
            font=("Courier", 12),
        )
        self.prompt_label.pack(side="left")

        self.input_field = tk.Entry(
            self.input_frame,
            bg="black",
            fg="#00ff00",
            insertbackground="#00ff00",
            font=("Courier", 12),
            bd=0,
            highlightthickness=1,
            highlightcolor="#00ff00",
            highlightbackground="#004400",
        )
        self.input_field.pack(side="left", fill="x", expand=True)
        self.input_field.bind("", self.send_message)

        # First render
        self.display_welcome()

    # ------------------------- Rendering helpers --------------------------- #
    def display_welcome(self):
        welcome_text = """
        
╔════════════════════════════════════════╗
β•‘        Welcome to Gemini AI Chat       β•‘
β•‘    Type your message and press Enter   β•‘
β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•
        
""" self.chat_content.append(welcome_text) self.update_chat_display() def update_chat_display(self): html_content = f""" {self.style} {''.join(self.chat_content)} """ self.chat_display.load_html(html_content) # Scroll once Tk has finished rendering self.root.after_idle(self._scroll_to_bottom) # -------------------------- Event handlers --------------------------- # def send_message(self, event=None): user_input: str = self.input_field.get().strip() if not user_input: return timestamp = datetime.now().strftime("%H:%M:%S") user_message_md = markdown.markdown(user_input) user_html = f"""
[{timestamp}] You:
{user_message_md}
""" self.chat_content.append(user_html) # Show "thinking…" placeholder self.is_thinking = True thinking_html = """
Gemini is thinking...
""" self.chat_content.append(thinking_html) self.update_chat_display() # Clear input field self.input_field.delete(0, "end") # Fire AI call in background threading.Thread( target=self.get_ai_response, args=(user_input,), daemon=True, ).start() def get_ai_response(self, user_input: str): """ Handles interaction with Gemini/Generative-AI. Because we re-use the global _CHAT_SESSION, the model automatically receives the *entire* conversation context – giving it the ability to reference earlier messages without any extra work. """ try: # Feed the user message to the chat session. response = _CHAT_SESSION.send_message(user_input) # Remove "thinking" placeholder if necessary if self.is_thinking: self.chat_content.pop() # remove last added element self.is_thinking = False timestamp = datetime.now().strftime("%H:%M:%S") ai_message_md = markdown.markdown(response.text) ai_html = f"""
[{timestamp}] Gemini:
{ai_message_md}
""" self.chat_content.append(ai_html) self.update_chat_display() except Exception as e: # Remove "thinking" placeholder if it exists if self.is_thinking: self.chat_content.pop() self.is_thinking = False error_html = f"""
Error: {str(e)}
""" self.chat_content.append(error_html) self.update_chat_display() # --------------------------------------------------------------------------- # # Application entry-point # # --------------------------------------------------------------------------- # if __name__ == "__main__": root = tk.Tk() root.geometry("860x645") app = TerminalChat(root) root.mainloop()

Context Manager for Database Connections

Blooket code brute forcer, truly one of my greater programs

import random
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import threading

# Control number of instances here
NUM_INSTANCES = 4

def generate_random_id():
    return ''.join(random.choices('0123456789', k=7))

def search_game(thread_id):
    driver = webdriver.Chrome()

    while True:
        game_id = generate_random_id()
        nickname = f"jack{thread_id}"
        url = f"https://play.blooket.com/play?id={game_id}"

        driver.get(url)
        time.sleep(1.5)

        try:
            immediate_error = driver.find_element(By.CSS_SELECTOR, 'div.CustomErrorToast_errorToast__fF9HK')
            if "We couldn't find a game with that ID" in immediate_error.text:
                print(f"Thread {thread_id}: No game found for ID: {game_id}. Trying again...")
                continue
        except Exception:
            pass

        try:
            nickname_input = driver.find_element(By.CSS_SELECTOR, 'input._nameInput_1lycq_85')
            nickname_input.clear()
            nickname_input.send_keys(nickname)
            nickname_input.send_keys(Keys.RETURN)

            time.sleep(1.5)

            try:
                error_message = driver.find_element(By.CSS_SELECTOR, 'div._errorBar_1lycq_148')
                if "no game" in error_message.text or "trouble connecting" in error_message.text:
                    print(f"Thread {thread_id}: No game found for ID: {game_id}. Trying again...")
                else:
                    print(f"Thread {thread_id}: Game found with ID: {game_id} and Nickname: {nickname}")
                    while True:
                        time.sleep(1)
            except Exception as e:
                print(f"Thread {thread_id}: Error checking for game: {e}. Trying again...")
        except Exception as e:
            print(f"Thread {thread_id}: Error finding nickname input: {e}. Trying again...")

def main():
    threads = []

    # Create threads based on NUM_INSTANCES
    for i in range(NUM_INSTANCES):
        thread = threading.Thread(target=search_game, args=(i+1,))
        threads.append(thread)
        thread.start()

    # Wait for all threads
    for thread in threads:
        thread.join()

if __name__ == "__main__":
    main()

React Examples

Custom useAsync Hook

The website I did UI / UX for

https://www.mythicfootball.com
// It used react

Async Error Handler Wrapper

Original Infinite reach hack for Minecraft Updated by me

package net.jackson.hacks;

import net.jackson.mixin.ClientPlayerInteractionManagerMixin;
import net.jackson.mixin.MinecraftClientMixin;
import net.minecraft.entity.Entity;
import net.minecraft.network.packet.c2s.play.HandSwingC2SPacket;
import net.minecraft.network.packet.c2s.play.PlayerInteractEntityC2SPacket;
import net.minecraft.network.packet.c2s.play.PlayerMoveC2SPacket;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.Vec3d;
import org.lwjgl.glfw.GLFW;

import static net.jackson.client.ClientEntrypoint.*;
import static net.jackson.helper.Utils.insertToCenter;

public class Reach extends ToggledHack {
    /**
     * Hit enitities from far away
     * @see MinecraftClientMixin
     * @see ClientPlayerInteractionManagerMixin
     */
    public Reach() {
        super("Reach", GLFW.GLFW_KEY_RIGHT_BRACKET);
    }

    @Override
    public void onEnable() {
        clipReachHack.enabled = false;  // Disable clip reach
    }

    public void hitEntity(Entity target) {
        if (client.player == null) return;

        if (packetQueue.size() > 0) {
            return;  // Already running (may take multiple ticks)
        }

        Vec3d pos = client.player.getPos();
        Vec3d targetPos = target.getPos().subtract(  // Subtract a bit from the end
                target.getPos().subtract(pos).normalize().multiply(2)
        );
        // If player is still too far away, move closer
        while (target.squaredDistanceTo(pos.add(0, client.player.getStandingEyeHeight(), 0)) >= MathHelper.square(6.0)) {
            Vec3d movement = targetPos.subtract(pos);

            boolean lastPacket = false;
            if (movement.lengthSquared() >= 100) {  // Length squared is max 100 (otherwise "moved too quickly")
                // Normalize to length 10
                movement = movement.normalize().multiply(9.9);
            } else {  // If short enough, this is last packet
                lastPacket = true;
            }
            pos = pos.add(movement);

            // Add forward and backwards packets
            insertToCenter(packetQueue, new PlayerMoveC2SPacket.PositionAndOnGround(pos.x, pos.y, pos.z, true, false));
            if (!lastPacket) {  // If not the last packet, add a backwards packet (only need one at the sheep)
                insertToCenter(packetQueue, new PlayerMoveC2SPacket.PositionAndOnGround(pos.x, pos.y, pos.z, true, false));
            }
        }
        // Add hit packet in the middle and original position at the end
        insertToCenter(packetQueue, PlayerInteractEntityC2SPacket.attack(target, client.player.isSneaking()));
        packetQueue.add(new PlayerMoveC2SPacket.PositionAndOnGround(client.player.getX(), client.player.getY(), client.player.getZ(), true, false));
        packetQueue.add(new HandSwingC2SPacket(client.player.getActiveHand()));  // Serverside animation
        client.player.resetLastAttackedTicks();  // Reset attack cooldown
    }
}

Java Examples

Who doesn't love math! Pre-existing project re-made to be open source since the original owner had it closed.

Rendering pixels in a 3D space for a Minecraft mod.

package eightsidedsquare.illegal.client;

import com.mojang.blaze3d.systems.RenderSystem;
import eightsidedsquare.illegal.common.entity.DrawingBlockEntity;
import java.util.Iterator;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.render.*;
import net.minecraft.client.render.block.entity.BlockEntityRenderer;
import net.minecraft.client.render.block.entity.BlockEntityRendererFactory;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.util.math.Direction;
import net.minecraft.util.math.Vec3d;
import net.minecraft.util.math.Vec3f;
import net.minecraft.world.World;

public class DrawingBlockEntityRenderer implements BlockEntityRenderer {
    public DrawingBlockEntityRenderer(BlockEntityRendererFactory.Context ctx) {
    }

    @Environment(EnvType.CLIENT)
    public void render(DrawingBlockEntity entity, float tickDelta, MatrixStack matrices, VertexConsumerProvider provider, int light, int overlay) {
        World world = entity.getWorld();
        if (world != null) {
            MatrixStack matrixStack = RenderSystem.getModelViewStack();
            matrixStack.push();
            matrixStack.multiplyPositionMatrix(matrices.peek().getPositionMatrix());
            RenderSystem.applyModelViewMatrix();
            RenderSystem.setShader(GameRenderer::getPositionColorShader);
            RenderSystem.setShaderColor(1.0F, 1.0F, 1.0F, 1.0F);
            RenderSystem.enableDepthTest();
            RenderSystem.disableCull();
            RenderSystem.depthMask(true);
            Tessellator tessellator = Tessellator.getInstance();
            BufferBuilder bufferBuilder = tessellator.getBuffer();
            bufferBuilder.begin(VertexFormat.DrawMode.LINES, VertexFormats.POSITION_COLOR_LIGHT);
            matrices.loadIdentity();
            float d = 0.0F;
            Entity var13 = MinecraftClient.getInstance().getCameraEntity();
            if (var13 instanceof PlayerEntity) {
                PlayerEntity p = (PlayerEntity)var13;
                d = (float)p.getPos().distanceTo(new Vec3d((double)entity.getPos().getX() + 0.5, (double)entity.getPos().getY() + 0.5, (double)entity.getPos().getZ() + 0.5));
            }

            d /= 256.0F;
            Iterator var15 = entity.getPixelData().iterator();

            while(var15.hasNext()) {
                long pixelData = (Long)var15.next();
                this.renderPixel(pixelData, bufferBuilder, light, d);
            }

            tessellator.draw();
            matrixStack.pop();
            RenderSystem.applyModelViewMatrix();
            RenderSystem.depthMask(true);
            RenderSystem.disableBlend();
            RenderSystem.enableCull();
        }
    }

    public void renderPixel(long pixelData, BufferBuilder bufferBuilder, int light, float distance) {
        Vec3f[] vec3fs = new Vec3f[]{new Vec3f(-1.0F, distance, -1.0F), new Vec3f(-1.0F, distance, 1.0F), new Vec3f(1.0F, distance, 1.0F), new Vec3f(1.0F, distance, -1.0F)};
        Direction d = DrawingBlockEntity.getDirection(pixelData);

        for(int k = 0; k < 4; ++k) {
            Vec3f vec3f = vec3fs[k];
            vec3f.scale(0.5F);
            switch (d) {
                case NORTH:
                case EAST:
                    vec3f.add(-0.5F, 0.0F, -0.5F);
                    break;
                case SOUTH:
                case WEST:
                    vec3f.add(0.5F, 0.0F, -0.5F);
                    break;
                case UP:
                    vec3f.add(0.5F, 0.0F, 0.5F);
                    break;
                default:
                    vec3f.add(0.5F, 0.0F, -0.5F);
            }

            vec3f.rotate(d.getRotationQuaternion());
            vec3f.add((float)DrawingBlockEntity.getX(pixelData), (float)DrawingBlockEntity.getY(pixelData), (float)DrawingBlockEntity.getZ(pixelData));
            vec3f.scale(0.0625F);
            vec3f.add((float)(-d.getOffsetX()), (float)(-d.getOffsetY()), (float)(-d.getOffsetZ()));
        }

        float r = DrawingBlockEntity.getRed(pixelData);
        float g = DrawingBlockEntity.getGreen(pixelData);
        float b = DrawingBlockEntity.getBlue(pixelData);
        float a = 1.0F;
        int uv = OverlayTexture.DEFAULT_UV;
        bufferBuilder.vertex((double)vec3fs[0].getX(), (double)vec3fs[0].getY(), (double)vec3fs[0].getZ()).color(r, g, b, a).light(light).texture(0.0F, 0.0F).normal(0.0F, 1.0F, 0.0F).overlay(uv).next();
        bufferBuilder.vertex((double)vec3fs[1].getX(), (double)vec3fs[1].getY(), (double)vec3fs[1].getZ()).color(r, g, b, a).light(light).texture(0.0F, 0.0F).normal(0.0F, 1.0F, 0.0F).overlay(uv).next();
        bufferBuilder.vertex((double)vec3fs[2].getX(), (double)vec3fs[2].getY(), (double)vec3fs[2].getZ()).color(r, g, b, a).light(light).texture(0.0F, 0.0F).normal(0.0F, 1.0F, 0.0F).overlay(uv).next();
        bufferBuilder.vertex((double)vec3fs[3].getX(), (double)vec3fs[3].getY(), (double)vec3fs[3].getZ()).color(r, g, b, a).light(light).texture(0.0F, 0.0F).normal(0.0F, 1.0F, 0.0F).overlay(uv).next();
    }

    public int getRenderDistance() {
        return 128;
    }
}

GitHub Contributions

Check out my open-source contributions and repositories:

UnicornMaster-dev's Stats UnicornMaster-dev's Streak UnicornMaster-dev's Top Languages
View My GitHub Profile