Skip to content

Kit4Some/LevelUPCoder2D

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

2 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

LevelUP Coder - Architecture Documentation

Overview

LevelUP Coder is a gamified coding education platform that transforms programming practice into an engaging RPG experience. The system combines real-time coding tracking, achievement systems, and interactive challenges with immersive 2D pixel art aesthetics.

System Architecture

Technology Stack

Backend

  • Framework: FastAPI (Python 3.13+)
  • Database: SQLite with SQLAlchemy ORM
  • Authentication: JWT-based authentication
  • WebSocket: Real-time communication for live updates
  • API Documentation: Auto-generated OpenAPI/Swagger

Frontend

  • Framework: React 19 with Vite
  • State Management: Zustand
  • Routing: React Router v6
  • Styling: Tailwind CSS with custom pixel art components
  • 3D Graphics: Three.js with React Three Fiber
  • Animations: GSAP and Framer Motion
  • Internationalization: i18next (KO, EN, JA, ZH)
  • Real-time: Socket.io client

Core Components

1. Authentication System

Flow: User Registration β†’ JWT Token Generation β†’ Protected Routes
  • User Model: Stores credentials and basic info
  • JWT Tokens: 24-hour expiration with HS256 algorithm
  • Password Security: Bcrypt hashing
  • Session Management: Token refresh on activity

2. Game Mechanics Engine

Experience System

  • Base XP Calculation: 1 XP per line of code
  • Multipliers: Language-specific bonuses
  • Level Progression: Exponential curve (level^2 * 100)

Currency System

  • Coins: Earned through coding and quests
  • Gems: Premium currency for special items
  • Exchange Rate: 100 coins = 1 gem

3. Real-time Communication

WebSocket Architecture:
Client β†’ WS Connection β†’ ConnectionManager β†’ Event Handlers
  • Connection Management: User-specific channels
  • Event Types:
    • coding_update: Track real-time coding progress
    • xp_update: Notify XP gains
    • achievement_unlocked: Instant achievement notifications
    • battle_update: Dungeon battle state changes

Database Schema

Core Tables

users
β”œβ”€β”€ id (PK)
β”œβ”€β”€ username (unique)
β”œβ”€β”€ email (unique)
β”œβ”€β”€ hashed_password
└── created_at

user_profiles
β”œβ”€β”€ id (PK)
β”œβ”€β”€ user_id (FK β†’ users)
β”œβ”€β”€ level
β”œβ”€β”€ experience
β”œβ”€β”€ coins
β”œβ”€β”€ gems
β”œβ”€β”€ coding_streak
β”œβ”€β”€ avatar_data (JSON)
└── statistics (JSON)

coding_sessions
β”œβ”€β”€ id (PK)
β”œβ”€β”€ user_id (FK β†’ users)
β”œβ”€β”€ start_time
β”œβ”€β”€ end_time
β”œβ”€β”€ lines_written
β”œβ”€β”€ xp_earned
└── project_name

Game Content Tables

dungeons
β”œβ”€β”€ id (PK)
β”œβ”€β”€ name
β”œβ”€β”€ difficulty
β”œβ”€β”€ required_level
β”œβ”€β”€ enemies (JSON)
└── rewards (JSON)

challenges
β”œβ”€β”€ id (PK)
β”œβ”€β”€ type (CTF, BUG_BOUNTY, SYSTEM_DESIGN)
β”œβ”€β”€ difficulty
β”œβ”€β”€ xp_reward
β”œβ”€β”€ coin_reward
└── solution_hash

quests
β”œβ”€β”€ id (PK)
β”œβ”€β”€ type (DAILY, WEEKLY)
β”œβ”€β”€ requirements (JSON)
β”œβ”€β”€ rewards (JSON)
└── expiry_date

Application Flow

1. User Journey

Entry β†’ Authentication β†’ Dashboard β†’ Game Modes β†’ Progress Tracking
  1. Registration/Login

    • Form validation
    • API authentication
    • Token storage
    • Profile initialization
  2. Dashboard Access

    • Load user profile
    • Fetch active quests
    • Display statistics
    • Initialize WebSocket
  3. Game Mode Selection

    • Coding Mode: Real-time XP tracking
    • Dungeons: Turn-based battles
    • Challenges: CTF, Bug Bounty, System Design
    • Quests: Daily/Weekly objectives

2. Coding Session Flow

Start Session β†’ Track Activity β†’ Calculate XP β†’ Update Profile β†’ End Session
  1. Session Initialization

    POST /api/game/coding/start
    β†’ Create session record
    β†’ Return session_id
  2. Real-time Tracking

    WebSocket: coding_update event
    β†’ Lines of code counter
    β†’ Character tracking
    β†’ File modification count
  3. Session Completion

    POST /api/game/coding/end
    β†’ Calculate total XP
    β†’ Update user level
    β†’ Check achievements
    β†’ Return rewards

3. Battle System (Dungeons)

Select Dungeon β†’ Initialize Battle β†’ Turn-based Combat β†’ Victory/Defeat β†’ Rewards
  1. Battle Initialization

    • Load enemy data
    • Set player stats
    • Initialize turn order
  2. Combat Loop

    while not battle_ended:
        player_action = await get_player_action()
        execute_action(player_action)
        enemy_action = calculate_enemy_action()
        execute_action(enemy_action)
        check_battle_status()
  3. Damage Calculation

    damage = base_damage * type_multiplier * critical_modifier
    # Type advantages: Fire > Grass > Water > Fire

API Structure

Authentication Endpoints

POST /api/auth/register     - User registration
POST /api/auth/login        - User login
GET  /api/auth/me           - Current user info
POST /api/auth/refresh      - Token refresh

Game Endpoints

GET  /api/game/profile      - User game profile
POST /api/game/coding/start - Start coding session
POST /api/game/coding/end   - End coding session
GET  /api/game/dungeons     - Available dungeons
POST /api/game/dungeons/battle - Dungeon battle action
GET  /api/game/challenges   - Available challenges
POST /api/game/challenges/submit - Submit challenge solution
GET  /api/game/quests       - Active quests
POST /api/game/quests/complete - Complete quest
GET  /api/game/shop         - Shop inventory
POST /api/game/shop/purchase - Purchase item
GET  /api/game/inventory    - User inventory
POST /api/game/inventory/equip - Equip/unequip item
GET  /api/game/leaderboard  - Global rankings

Frontend Architecture

Component Hierarchy

App
β”œβ”€β”€ AuthProvider (Context)
β”‚   └── Router
β”‚       β”œβ”€β”€ Public Routes
β”‚       β”‚   β”œβ”€β”€ Login
β”‚       β”‚   └── Register
β”‚       └── Protected Routes
β”‚           └── PixelLayout
β”‚               β”œβ”€β”€ Header (Stats Bar)
β”‚               β”œβ”€β”€ Navigation
β”‚               └── Page Components
β”‚                   β”œβ”€β”€ Dashboard
β”‚                   β”œβ”€β”€ CodingMode
β”‚                   β”œβ”€β”€ Dungeons
β”‚                   β”œβ”€β”€ Challenges
β”‚                   β”œβ”€β”€ Quests
β”‚                   β”œβ”€β”€ Shop
β”‚                   β”œβ”€β”€ Inventory
β”‚                   β”œβ”€β”€ Leaderboard
β”‚                   └── Profile

State Management

// Zustand Store Structure
gameStore
β”œβ”€β”€ user
β”‚   β”œβ”€β”€ profile
β”‚   β”œβ”€β”€ stats
β”‚   └── preferences
β”œβ”€β”€ session
β”‚   β”œβ”€β”€ currentSession
β”‚   β”œβ”€β”€ sessionHistory
β”‚   └── realTimeStats
β”œβ”€β”€ game
β”‚   β”œβ”€β”€ dungeons
β”‚   β”œβ”€β”€ challenges
β”‚   β”œβ”€β”€ quests
β”‚   └── inventory
└── ui
    β”œβ”€β”€ notifications
    β”œβ”€β”€ modals
    └── loading

Component Design Patterns

  1. Pixel Art Components

    // Consistent pixel art styling
    const PixelButton = ({ children, onClick }) => (
      <button className="pixel-button" onClick={onClick}>
        {children}
      </button>
    );
  2. Real-time Updates

    useEffect(() => {
      const ws = new WebSocket(WS_URL);
      ws.onmessage = (event) => {
        const data = JSON.parse(event.data);
        updateGameState(data);
      };
      return () => ws.close();
    }, []);
  3. Lazy Loading

    const Dungeons = lazy(() => import('./pages/Dungeons'));

Performance Optimization

Backend Optimizations

  • Database Indexing: Indexed columns for frequent queries
  • Connection Pooling: SQLAlchemy connection pool
  • Async Operations: FastAPI async endpoints
  • Caching: In-memory caching for static game data

Frontend Optimizations

  • Code Splitting: Route-based lazy loading
  • Memoization: React.memo for expensive components
  • Virtual Scrolling: For leaderboard and inventory lists
  • Asset Optimization: Compressed images and lazy loading

Security Measures

Authentication Security

  • JWT Token Security: Short expiration, secure storage
  • Password Policy: Minimum 8 characters, bcrypt hashing
  • Rate Limiting: API endpoint throttling
  • CORS Configuration: Whitelisted origins only

Data Validation

  • Input Sanitization: Pydantic models for request validation
  • SQL Injection Prevention: SQLAlchemy ORM parameterized queries
  • XSS Protection: React's automatic escaping

Deployment Architecture

Development Environment

Backend:  http://localhost:8000
Frontend: http://localhost:5176
Database: SQLite (local file)

Production Considerations

Backend:  HTTPS with SSL certificate
Frontend: CDN deployment (Vercel/Netlify)
Database: PostgreSQL with replication
Cache:    Redis for session management
Monitor:  Logging and error tracking

Monitoring and Analytics

Metrics Tracked

  • User Engagement: Daily active users, session duration
  • Game Metrics: XP earned, levels gained, items purchased
  • Performance: API response times, error rates
  • System Health: CPU usage, memory consumption, database queries

Error Handling

try:
    # Game logic
except GameException as e:
    log_error(e)
    return error_response(e.message)
except Exception as e:
    log_critical(e)
    return generic_error_response()

Future Scalability

Microservices Architecture

API Gateway
β”œβ”€β”€ Auth Service
β”œβ”€β”€ Game Service
β”œβ”€β”€ Battle Service
β”œβ”€β”€ Achievement Service
└── Analytics Service

Database Sharding

  • User data sharding by user_id
  • Game content replication
  • Read replicas for leaderboards

Real-time Scaling

  • WebSocket server clustering
  • Redis pub/sub for inter-server communication
  • Load balancing with sticky sessions

Development Workflow

Local Development

# Backend
cd backend
pip install -r requirements.txt
python -m app.main

# Frontend
cd frontend
npm install
npm run dev

Testing Strategy

  • Unit Tests: Individual function testing
  • Integration Tests: API endpoint testing
  • E2E Tests: User journey testing
  • Performance Tests: Load testing with multiple users

CI/CD Pipeline

Pipeline:
  - Lint & Format
  - Run Tests
  - Build Application
  - Deploy to Staging
  - Run E2E Tests
  - Deploy to Production

Conclusion

LevelUP Coder demonstrates a robust architecture combining modern web technologies with gamification principles. The system's modular design allows for easy feature additions and scaling while maintaining code quality and performance standards.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published