Skip to content

Latest commit

ย 

History

30 Commits

Folders and files

NameName
Last commit message
Last commit date
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

CODE ESCAPE ROOM v2.0

A Matrix-themed, AI-powered cybersecurity quiz platform where players hack their way out of digital vaults โ€” one coding puzzle at a time.

Live Demo Python Flask NVIDIA NIM JWT Database


Code Escape Room โ€” gameplay preview

๐ŸŽฎ Launch the App ย โ€ขย  โšก Quick Start ย โ€ขย  ๐Ÿง  The AI Engine ย โ€ขย  ๐Ÿ“ก API Reference

Note

The live demo is hosted on Render's free tier. If the instance has been idle it may take ~30โ€“60 seconds to wake up on the first request โ€” grab a coffee, then hack away. โ˜•


The Mission

You've been trapped inside a rogue AI's mainframe. The only way out is to breach a series of encrypted vaults โ€” each one guarded by puzzles in a different programming language. Answer correctly to advance. Waste your lives, and the rogue AI wins.

Code Escape Room turns a programming quiz into a high-stakes, cinematic hacking experience. Behind the Matrix-rain and terminal glow sits a full-stack Flask application with JWT auth, a relational quiz engine, a global leaderboard, an anti-cheat question distributor, and a triple-model NVIDIA NIM AI pipeline that generates questions, whispers hints, explains mistakes, and delivers a personalized mission debrief.

Built as an educational tool for BTech IT students โ€” equal parts game, learning aid, and classroom management console.

Features

Gameplay

  • Immersive hacker aesthetic โ€” live Matrix-rain canvas, terminal typography, glassmorphism panels, atmospheric BGM + game-over stinger, and victory confetti.
  • 7 programming realms โ€” breach vaults in C, C++, Java, SQL, Python, DSA & DAA.
  • Lives, timers & difficulty tiers โ€” 3 lives, a countdown per vault, and Easy/Medium/Hard modes that reshape time and hint budgets.
  • MCQ & fill-in-the-blank puzzles with optional code snippets and AI-generated illustrations.

Intelligence

  • AI hint system โ€” cryptic, spoiler-free nudges on demand.
  • AI mistake explainer โ€” learn why a wrong answer was wrong.
  • AI mission debrief โ€” a personalized study plan generated from your performance.
  • AI question factory โ€” admins generate entire question sets (and images) from a prompt.

๐Ÿ›ก๏ธ Admin Console

  • Full student lifecycle โ€” create, bulk-import, ban/unban, activate/deactivate, delete.
  • Room & question management โ€” CRUD vaults, hand-author or AI-generate questions.
  • Access control โ€” assign vaults per-student or to an entire batch at once.
  • Live dashboard โ€” sessions, completions, top scorers, and a player-issue tracker.

Security & Fair Play

  • JWT authentication with bcrypt-hashed passwords and role-based routes.
  • Anti-cheat question buckets โ€” students in the same room deterministically receive different question sets.
  • Answers never leave the server until a question is submitted.
  • Ban & deactivation enforcement at the login gate.

The 7 Realms

Each vault is themed to a language, colour-coded, and time-boxed. Clear all four questions before the timer hits zero to breach it.

Realm Language Signature Colour Focus
๐ŸŸ  C #ff6b35 Pointers, memory, printf sorcery
๐ŸŸก C++ #ffb700 OOP, constructors/destructors, std::
๐Ÿ”ต Java #00aaff The String Pool, the JVM, classes
๐ŸŸข SQL #00ff41 WHERE vs HAVING, joins, aggregates
๐Ÿฉท DSA #ff00aa Data structures & time complexity
๐ŸŸฃ DAA #aa00ff Divide-and-conquer, DP, greedy
๐Ÿฉต Python #00f5ff Indentation-as-syntax, the Pythonic way

Admins aren't limited to these โ€” the question generator also understands JavaScript, C#, Go, and HTML/CSS, so new vaults can be spun up on demand.


Gameplay Mechanics

Rule Value
โค๏ธ Lives 3 โ€” lose one for every wrong answer
๐Ÿงฉ Questions per vault 4 (randomised from the room's bank)
๐Ÿ† Score +20 points per correct answer
โฑ๏ธ Base timer 180s per vault (admin-configurable)
๐Ÿ’ก Hints Limited budget, scaled by difficulty

Difficulty Tiers

The chosen difficulty rescales the vault timer and your hint allowance:

Difficulty Time Multiplier Effective Timer* Hints
๐ŸŸข Easy ร—1.5 ~270s 5
๐ŸŸก Medium ร—1.0 180s 3
๐Ÿ”ด Hard ร—0.7 ~126s 1

*Based on the default 180s room limit.

Anti-Cheat: Disjoint Question Buckets

To stop side-by-side copying, the quiz engine sorts a room's question bank into stable buckets and assigns each student a bucket based on their user ID (bucket = user_id % number_of_buckets). Neighbours in the same vault get genuinely different questions โ€” no shared answer key.


Architecture

flowchart TD
    subgraph Client["๐Ÿ–ฅ๏ธ  Frontend โ€” Vanilla JS / Matrix UI"]
        L["login.html / signup.html"]
        I["index.html โ€” Mission Select"]
        G["game.html โ€” In-Game Engine"]
        S["summary.html โ€” Mission Debrief"]
        A["admin.html โ€” Control Console"]
    end

    subgraph Server["โš™๏ธ  Flask API  (app:create_app)"]
        AUTH["/api/auth"]
        QUIZ["/api/quiz"]
        LB["/api/leaderboard"]
        STU["/api/student"]
        ADM["/api/admin"]
        AI["/api/ai"]
    end

    subgraph Data["๐Ÿ’พ  Persistence"]
        DB[("SQLAlchemy ORM<br/>SQLite ยท PostgreSQL")]
    end

    subgraph Cloud["๐Ÿง   NVIDIA NIM"]
        LLAMA["DeepSeek V4 Flash<br/>question generation"]
        MISTRAL["DeepSeek V4 Flash<br/>hints ยท explain ยท debrief"]
        SDXL["Stable Diffusion XL<br/>question images"]
    end

    Client -->|JWT Bearer token| Server
    Server --> DB
    ADM --> LLAMA
    ADM --> SDXL
    AI --> MISTRAL
Loading

Request lifecycle: the browser authenticates once (/api/auth/login), stores the JWT, and attaches it as a Bearer token to every subsequent call. Flask blueprints validate the token, enforce role/ownership rules, read/write through SQLAlchemy, and โ€” for AI routes โ€” proxy to NVIDIA NIM's OpenAI-compatible endpoint with graceful fallbacks if the model is unreachable.


๐Ÿ› ๏ธ Tech Stack

Layer Technology
Backend Flask 3.0 ยท Python 3.12
Database SQLAlchemy ORM โ†’ SQLite (default) ยท PostgreSQL (psycopg2) ยท MySQL (PyMySQL)
Auth Flask-JWT-Extended (8h access / 30d refresh) ยท Flask-Bcrypt
AI Engine NVIDIA NIM (OpenAI-compatible) โ€” DeepSeek V4 Flash ยท SDXL
Frontend Vanilla HTML5 / CSS3 / JavaScript ยท <canvas> Matrix rain ยท glassmorphism
Fonts Orbitron ยท Share Tech Mono ยท VT323
Server Gunicorn (production) ยท Flask dev server (local)
Hosting Render.com (primary)

The AI Engine

Every AI feature runs through NVIDIA NIM using its OpenAI-compatible API. Three specialised models power distinct experiences, and every route degrades gracefully โ€” if the model times out, a curated static fallback keeps the game playable.

Capability Endpoint Model What it does
Question Generation POST /api/admin/questions/generate deepseek-ai/deepseek-v4-flash Generates full MCQ sets from a language + syllabus prompt, with strict in-language validation & retries
Question Illustrations (same route, opt-in) stabilityai/sdxl Produces a Base64 image for questions when include_images is on
Hints POST /api/ai/hint deepseek-ai/deepseek-v4-flash Cryptic, encouraging nudges that never reveal the answer
Mistake Explainer POST /api/ai/explain deepseek-ai/deepseek-v4-flash Explains why an answer was wrong and the right one is right
Mission Debrief POST /api/ai/summary deepseek-ai/deepseek-v4-flash Personalized study advice from per-room performance & weak topics
Room Tips POST /api/ai/room-tip deepseek-ai/deepseek-v4-flash A dramatic, in-character concept reminder before you enter a vault

๐Ÿ“‚ Project Structure

Code-Escape-Room/
โ”‚
โ”œโ”€โ”€ app.py                 # Flask entry point & create_app() factory
โ”œโ”€โ”€ wsgi.py                # WSGI entry (PythonAnywhere)
โ”œโ”€โ”€ config.py              # Config: DB URL, JWT, NVIDIA key, game constants
โ”œโ”€โ”€ extensions.py          # Shared extensions (SQLAlchemy, Bcrypt, JWT)
โ”œโ”€โ”€ models.py              # 7 ORM models (User, Room, Question, sessionsโ€ฆ)
โ”œโ”€โ”€ init_db.py             # Reset DB + seed the default admin account
โ”œโ”€โ”€ requirements.txt       # Python dependencies
โ”œโ”€โ”€ runtime.txt            # Pinned Python version (3.12.7)
โ”‚
โ”œโ”€โ”€ api_routes/            # ๐Ÿงฉ Backend โ€” API blueprints
โ”‚   โ”œโ”€โ”€ auth.py            #   login ยท signup ยท register ยท setup ยท me
โ”‚   โ”œโ”€โ”€ admin.py           #   students ยท rooms ยท access ยท AI generation ยท issues
โ”‚   โ”œโ”€โ”€ student.py         #   my rooms ยท history ยท profile ยท issue reports
โ”‚   โ”œโ”€โ”€ quiz.py            #   start ยท questions ยท answer ยท complete ยท summary
โ”‚   โ”œโ”€โ”€ leaderboard.py     #   per-room ยท overall ยท per-batch rankings
โ”‚   โ””โ”€โ”€ ai.py              #   hint ยท explain ยท summary ยท room-tip
โ”‚
โ”œโ”€โ”€ frontend/              # ๐ŸŽจ Everything the browser loads (served at /)
โ”‚   โ”œโ”€โ”€ login.html  signup.html  index.html   #   Matrix-themed pages
โ”‚   โ”œโ”€โ”€ game.html   summary.html  admin.html   #   (one screen per file)
โ”‚   โ”œโ”€โ”€ style.css          #   Global hacker aesthetics
โ”‚   โ”œโ”€โ”€ script.js          #   Shared Matrix-rain + helpers
โ”‚   โ”œโ”€โ”€ favicon.svg        #   Terminal-green favicon
โ”‚   โ”œโ”€โ”€ hitman.mp3         #   ๐ŸŽต Atmospheric background score
โ”‚   โ””โ”€โ”€ Game Over sound.mp3 #     Defeat stinger
โ”‚
โ”œโ”€โ”€ instance/              # ๐Ÿ’พ Local SQLite database (app.db is tracked as seed data)
โ””โ”€โ”€ assets/                # ๐ŸŽฌ README media (demo.gif)

๐Ÿ”’ The app serves files only from frontend/, so backend source (config.py, models.py, api_routes/ โ€ฆ) is never reachable over HTTP.


API Reference

All routes are JSON. Protected routes require an Authorization: Bearer <access_token> header. A public GET /health returns service status.

๐Ÿ” Auth โ€” /api/auth
Method Endpoint Auth Description
POST /login โ€” Log in with username or email
POST /signup โ€” Public player self-registration
POST /register Admin Admin creates a student account
GET /me JWT Current logged-in user
POST /change-password JWT Update your password
POST /setup โ€” Create the first admin (one-time)
๐ŸŽฎ Quiz Engine โ€” /api/quiz
Method Endpoint Description
GET /rooms All active rooms (with question counts)
POST /start Start a session for selected/assigned rooms
GET /room/<id>/questions Random questions for a room (no answers)
POST /answer Submit an answer โ†’ scored & revealed
POST /room/complete Finalise a room attempt
POST /session/finish End the run
GET /summary/<session_id> Full per-room performance breakdown
๐Ÿ† Leaderboard โ€” /api/leaderboard
Method Endpoint Description
GET /room/<id> Best scores for a single room
GET /overall Combined ranking across all rooms
GET /batch/<batch> Ranking within one batch
๐ŸŽ“ Student โ€” /api/student
Method Endpoint Description
GET /rooms My assigned + public rooms
GET /history My last 10 quiz sessions
GET /profile Profile + aggregate stats
POST /issues Report a bug / issue
๐Ÿ›ก๏ธ Admin โ€” /api/admin
Method Endpoint Description
GET / POST /students List / create students
POST /students/bulk Bulk-import students
POST /students/<id>/ban Ban / unban
POST /students/<id>/toggle Activate / deactivate
GET / POST / PATCH / DELETE /rooms ยท /rooms/<id> Manage vaults
POST / DELETE /students/<id>/access ยท /โ€ฆ/<rid> Grant / revoke room access
POST /batch-access Assign rooms to a whole batch
POST /questions/generate ๐Ÿง  AI-generate questions (+ images)
GET / POST / DELETE /rooms/<id>/questions ยท /questions/<id> Manage questions
GET /stats Dashboard metrics + top students
GET / POST / DELETE /issues ยท /issues/<id>/resolve Issue tracker
๐Ÿค– AI โ€” /api/ai
Method Endpoint Description
POST /hint Spoiler-free hint for a question
POST /explain Explain why an answer was wrong
POST /summary Personalized post-game study advice
POST /room-tip Quick concept tip before a vault

โšก Quick Start

Prerequisites: Python 3.12+, pip, and an NVIDIA NIM API key (free tier available) for the AI features.

# 1 โ€” Clone
git clone https://github.com/SofDev007/Code-Escape-Room.git
cd Code-Escape-Room

# 2 โ€” (Recommended) create a virtual environment
python -m venv venv
# Windows:  venv\Scripts\activate
# macOS/Linux:  source venv/bin/activate

# 3 โ€” Install dependencies
pip install -r requirements.txt

# 4 โ€” Configure environment (see table below) โ€” create a .env file
#     NVIDIA_API_KEY, SECRET_KEY, JWT_SECRET_KEY โ€ฆ

# 5 โ€” Initialize the database (โš ๏ธ wipes existing data, seeds the admin)
python init_db.py

# 6 โ€” Launch
python app.py

Then open http://localhost:5000 and log in.

Default admin (from init_db.py): ย  admin@escaperoom.com / admin123 ย  โ€” change this password immediately.

๐Ÿ”ง Environment Variables

Variable Required Default Description
NVIDIA_API_KEY โœ… (for AI) โ€” NVIDIA NIM key powering all AI features
SECRET_KEY ๐Ÿ”ถ dev fallback Flask session/crypto secret
JWT_SECRET_KEY ๐Ÿ”ถ dev fallback Signing key for JWTs
DATABASE_URL โฌœ sqlite:///app.db Any SQLAlchemy URL; postgres:// is auto-normalised
FLASK_DEBUG โฌœ true Set false in production

๐Ÿ”ถ = has an insecure development fallback โ€” always override in production.


Deployment

Render.com (recommended)

  1. New โ†’ Web Service, connect this repository.
  2. Configure the build:
    • Environment: Python 3
    • Build Command: pip install -r requirements.txt
    • Start Command: gunicorn "app:create_app()" --timeout 400 (the AI question-generation route can retry the NVIDIA call up to 3 times at 120s each โ€” gunicorn's default 30s worker timeout will silently kill the request mid-generation and the browser sees a bare "Network error" instead of the real cause, so this must exceed that worst case)
  3. Under Environment, add NVIDIA_API_KEY, SECRET_KEY, JWT_SECRET_KEY, and FLASK_DEBUG=false.
  4. Persist your data. SQLite on Render's ephemeral disk is wiped on every deploy. Choose one:
    • Postgres (best): create a Render PostgreSQL instance and set DATABASE_URL to its connection string โ€” the app auto-normalises the legacy postgres:// prefix.
    • Persistent disk: attach a disk (e.g. mounted at /data) and point DATABASE_URL=sqlite:////data/app.db.
  5. First deploy only โ€” run python init_db.py once (via a Render Shell or a one-off job) to create tables and the seed admin.

The frontend already targets https://code-escape-room-kk9h.onrender.com/api in production and localhost:5000 in development, with CORS configured to match โ€” update these URLs if you deploy to your own domain.

PythonAnywhere (alternative)

A ready-made wsgi.py exposes application = create_app(). Point your PythonAnywhere web app at it and set PROJECT_DIR to your project path.


Admin Guide

  1. Log in with the seed admin (admin@escaperoom.com / admin123) and immediately change the password via /api/auth/change-password. Fresh install with no admin? Bootstrap one instead:
    POST /api/auth/setup
    { "name": "Head Moderator", "username": "admin",
      "email": "admin@college.com", "password": "your_secure_password" }
  2. Create vaults in the Admin Console (name, language, time limit, public/assigned).
  3. Fill each vault โ€” hand-author questions or fire up the ๐Ÿง  AI generator: pick a language, difficulty, optional syllabus focus, and toggle image generation.
  4. Onboard players โ€” create accounts individually or bulk-import, then assign rooms per-student or to an entire batch at once.
  5. Run the room โ€” monitor sessions, completions, and top scorers on the live dashboard, and triage player-reported issues.

๐Ÿ—บ๏ธ Roadmap

  • Real-time multiplayer race mode
  • Timed tournaments & seasonal leaderboards
  • Richer analytics (per-topic mastery heatmaps)
  • More languages as first-class vaults (JS, Go, Rustโ€ฆ)
  • Achievement badges & streaks

๐Ÿ‘ฅ The Team

Built with caffeine and questionable sleep schedules by:

Name Role
Arnav Development
Devansh Research & Development

BTech IT โ€” Group Project #3


๐Ÿ“„ License & Acknowledgements

This project was built for academic purposes. AI capabilities are powered by NVIDIA NIM; typography by Google Fonts (Orbitron, Share Tech Mono, VT323).


> SYSTEM SECURE. GOOD LUCK, AGENT.

โญ If you enjoyed breaking out, drop a star on the repo. โญ

About

No description, website, or topics provided.

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages