Skip to content

Interactive Python learning game with AI-generated hints, level-based challenges and progress tracking — built with Flask + OpenAI.

Notifications You must be signed in to change notification settings

gamila-wisam/Educational-Programing-Desktop-App

Repository files navigation

Programming Educational Game Backend

A comprehensive backend system for a programming educational game with AI-powered hint generation, user management, and analytics.

Features

🎮 Game Features

  • Level-based progression with 5 programming challenges
  • Safe code execution with sandboxed environment
  • Real-time feedback with detailed error messages
  • Progress tracking with scores and statistics
  • Level unlocking system

🤖 AI Integration

  • Local AI model for hint generation (using Microsoft DialoGPT)
  • Contextual hints based on user code and errors
  • Progressive hint system (more specific hints after multiple attempts)
  • Fallback rule-based hints if AI model fails to load

🔐 User Management

  • User registration and authentication with JWT tokens
  • Progress persistence across sessions
  • User analytics and performance tracking
  • Secure password hashing

📊 Analytics & Monitoring

  • Code execution analytics (success rates, common errors)
  • User behavior tracking (attempts, hints used, time spent)
  • Performance metrics (execution time, completion rates)
  • Health monitoring endpoints

Architecture

GAME_PROJECT/
├── main.py                 # Main application (web + API)
├── api.py                  # Full REST API with authentication
├── models.py               # Database models
├── config.py               # Configuration settings
├── code_executor.py        # Safe code execution engine
├── ai_hint_generator.py    # AI-powered hint generation
├── requirements.txt        # Python dependencies
├── levels.json            # Game levels data
├── static/                # Frontend assets
├── templates/             # HTML templates
└── README.md              # This file

Installation

Prerequisites

  • Python 3.8+
  • pip package manager

Setup

  1. Clone the repository

    git clone <repository-url>
    cd GAME_PROJECT
  2. Install dependencies

    pip install -r requirements.txt
  3. Set up environment variables (optional) Create a .env file:

    SECRET_KEY=your-secret-key-here
    DATABASE_URL=sqlite:///game.db
    AI_MODEL_NAME=microsoft/DialoGPT-medium
    JWT_SECRET_KEY=your-jwt-secret
  4. Initialize the database

    python main.py

    The database will be created automatically on first run.

Usage

Running the Application

Option 1: Web Interface (Original Frontend)

python main.py

Access the game at: http://localhost:5000

Option 2: Full API Backend

python api.py

Access the API at: http://localhost:5000/api/

API Endpoints

Authentication

  • POST /api/auth/register - Register new user
  • POST /api/auth/login - Login user
  • GET /api/auth/profile - Get user profile

Game

  • GET /api/game/levels - Get all levels with progress
  • GET /api/game/level/<id> - Get specific level
  • POST /api/game/submit - Submit code for testing
  • GET /api/game/hint/<id> - Get AI-generated hint
  • GET /api/game/progress - Get user progress
  • POST /api/game/reset - Reset user progress

Analytics

  • GET /api/analytics/user/<id> - Get user analytics
  • GET /api/health - Health check

Simple API (No Auth)

  • GET /api/levels - Get all levels
  • GET /api/level/<id> - Get specific level
  • POST /api/submit - Submit code
  • GET /api/hint/<id> - Get hint
  • GET /api/hints/<id> - Get multiple hints

API Examples

Register a User

curl -X POST http://localhost:5000/api/auth/register \
  -H "Content-Type: application/json" \
  -d '{
    "username": "player1",
    "email": "player1@example.com",
    "password": "password123"
  }'

Submit Code

curl -X POST http://localhost:5000/api/submit \
  -H "Content-Type: application/json" \
  -d '{
    "level_number": 1,
    "code": "def double_number(n):\n    return n * 2"
  }'

Get AI Hint

curl "http://localhost:5000/api/hint/1?user_code=def%20double_number(n):&attempt_count=2"

AI Hint Generator

The AI hint generator uses a local transformer model to provide contextual hints:

Features

  • Contextual hints based on user's code and errors
  • Progressive difficulty (more specific hints after multiple attempts)
  • Fallback system with rule-based hints if AI fails
  • Multiple hint types (general, specific, code examples)

Configuration

# In config.py
AI_MODEL_NAME = "microsoft/DialoGPT-medium"  # Local model
AI_MAX_LENGTH = 100
AI_TEMPERATURE = 0.7

Code Execution Engine

The code executor provides a safe environment for running user code:

Safety Features

  • Sandboxed execution with restricted builtins
  • Timeout protection (5-second limit)
  • Output size limits (10KB max)
  • Dangerous function blocking (eval, exec, file operations)
  • Import restrictions (only safe modules allowed)

Supported Operations

  • Basic Python operations (math, strings, lists, etc.)
  • Function definitions and calls
  • Control structures (if, for, while)
  • Error handling (try/except)
  • Safe imports (math, random, string, etc.)

Database Schema

Users

  • id - Primary key
  • username - Unique username
  • email - Unique email
  • password_hash - Hashed password
  • current_level - Current unlocked level
  • total_score - Total game score
  • total_attempts - Total code attempts
  • total_hints_used - Total hints used

Level Progress

  • id - Primary key
  • user_id - Foreign key to user
  • level_number - Level number
  • completed - Whether level is completed
  • score - Score for this level
  • attempts - Number of attempts
  • hints_used - Number of hints used
  • completed_at - Completion timestamp

Code Attempts

  • id - Primary key
  • user_id - Foreign key to user
  • level_number - Level number
  • code - User's submitted code
  • is_correct - Whether code was correct
  • error_message - Error message if failed
  • execution_time - Time taken to execute

Configuration

Environment Variables

  • SECRET_KEY - Flask secret key
  • DATABASE_URL - Database connection string
  • AI_MODEL_NAME - AI model to use for hints
  • AI_MAX_LENGTH - Maximum hint length
  • AI_TEMPERATURE - AI generation temperature
  • JWT_SECRET_KEY - JWT signing key

Game Settings

  • MAX_HINTS_PER_LEVEL - Maximum hints per level (default: 3)
  • POINTS_PER_LEVEL - Points for completing level (default: 10)
  • BONUS_POINTS_NO_HINTS - Bonus for completing without hints (default: 5)

Development

Adding New Levels

  1. Edit levels.json to add new level data
  2. Each level should have:
    • title - Level title
    • instruction - Task description
    • function_name - Expected function name
    • test_input - Test input value
    • expected_output - Expected output
    • hint - Default hint text

Extending the AI

  1. Modify ai_hint_generator.py to add new hint types
  2. Update the context creation for better AI prompts
  3. Add new rule-based hint patterns

Adding New Features

  1. Create new models in models.py if needed
  2. Add API endpoints in api.py
  3. Update the main application in main.py

Security Considerations

  • Code execution is sandboxed to prevent malicious code
  • User authentication with JWT tokens
  • Password hashing using Werkzeug
  • Input validation on all endpoints
  • Rate limiting can be added for production
  • HTTPS should be used in production

Performance

  • Database indexing on frequently queried fields
  • AI model caching to avoid reloading
  • Code execution timeouts to prevent hanging
  • Connection pooling for database connections

Troubleshooting

AI Model Not Loading

  • Check internet connection for model download
  • Verify sufficient disk space
  • Check PyTorch installation
  • The system will fallback to rule-based hints

Database Issues

  • Ensure write permissions in the directory
  • Check database URL configuration
  • Run database migrations if needed

Code Execution Errors

  • Check Python version compatibility
  • Verify all dependencies are installed
  • Check system resources (memory, CPU)

License

This project is licensed under the MIT License - see the LICENSE file for details.

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests if applicable
  5. Submit a pull request

Support

For support and questions, please open an issue on the repository.

About

Interactive Python learning game with AI-generated hints, level-based challenges and progress tracking — built with Flask + OpenAI.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published