A comprehensive backend system for a programming educational game with AI-powered hint generation, user management, and analytics.
- 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
- 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 registration and authentication with JWT tokens
- Progress persistence across sessions
- User analytics and performance tracking
- Secure password hashing
- Code execution analytics (success rates, common errors)
- User behavior tracking (attempts, hints used, time spent)
- Performance metrics (execution time, completion rates)
- Health monitoring endpoints
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
- Python 3.8+
- pip package manager
-
Clone the repository
git clone <repository-url> cd GAME_PROJECT
-
Install dependencies
pip install -r requirements.txt
-
Set up environment variables (optional) Create a
.envfile:SECRET_KEY=your-secret-key-here DATABASE_URL=sqlite:///game.db AI_MODEL_NAME=microsoft/DialoGPT-medium JWT_SECRET_KEY=your-jwt-secret
-
Initialize the database
python main.py
The database will be created automatically on first run.
python main.pyAccess the game at: http://localhost:5000
python api.pyAccess the API at: http://localhost:5000/api/
POST /api/auth/register- Register new userPOST /api/auth/login- Login userGET /api/auth/profile- Get user profile
GET /api/game/levels- Get all levels with progressGET /api/game/level/<id>- Get specific levelPOST /api/game/submit- Submit code for testingGET /api/game/hint/<id>- Get AI-generated hintGET /api/game/progress- Get user progressPOST /api/game/reset- Reset user progress
GET /api/analytics/user/<id>- Get user analyticsGET /api/health- Health check
GET /api/levels- Get all levelsGET /api/level/<id>- Get specific levelPOST /api/submit- Submit codeGET /api/hint/<id>- Get hintGET /api/hints/<id>- Get multiple hints
curl -X POST http://localhost:5000/api/auth/register \
-H "Content-Type: application/json" \
-d '{
"username": "player1",
"email": "player1@example.com",
"password": "password123"
}'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"
}'curl "http://localhost:5000/api/hint/1?user_code=def%20double_number(n):&attempt_count=2"The AI hint generator uses a local transformer model to provide contextual hints:
- 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)
# In config.py
AI_MODEL_NAME = "microsoft/DialoGPT-medium" # Local model
AI_MAX_LENGTH = 100
AI_TEMPERATURE = 0.7The code executor provides a safe environment for running user code:
- 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)
- 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.)
id- Primary keyusername- Unique usernameemail- Unique emailpassword_hash- Hashed passwordcurrent_level- Current unlocked leveltotal_score- Total game scoretotal_attempts- Total code attemptstotal_hints_used- Total hints used
id- Primary keyuser_id- Foreign key to userlevel_number- Level numbercompleted- Whether level is completedscore- Score for this levelattempts- Number of attemptshints_used- Number of hints usedcompleted_at- Completion timestamp
id- Primary keyuser_id- Foreign key to userlevel_number- Level numbercode- User's submitted codeis_correct- Whether code was correcterror_message- Error message if failedexecution_time- Time taken to execute
SECRET_KEY- Flask secret keyDATABASE_URL- Database connection stringAI_MODEL_NAME- AI model to use for hintsAI_MAX_LENGTH- Maximum hint lengthAI_TEMPERATURE- AI generation temperatureJWT_SECRET_KEY- JWT signing key
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)
- Edit
levels.jsonto add new level data - Each level should have:
title- Level titleinstruction- Task descriptionfunction_name- Expected function nametest_input- Test input valueexpected_output- Expected outputhint- Default hint text
- Modify
ai_hint_generator.pyto add new hint types - Update the context creation for better AI prompts
- Add new rule-based hint patterns
- Create new models in
models.pyif needed - Add API endpoints in
api.py - Update the main application in
main.py
- 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
- Database indexing on frequently queried fields
- AI model caching to avoid reloading
- Code execution timeouts to prevent hanging
- Connection pooling for database connections
- Check internet connection for model download
- Verify sufficient disk space
- Check PyTorch installation
- The system will fallback to rule-based hints
- Ensure write permissions in the directory
- Check database URL configuration
- Run database migrations if needed
- Check Python version compatibility
- Verify all dependencies are installed
- Check system resources (memory, CPU)
This project is licensed under the MIT License - see the LICENSE file for details.
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests if applicable
- Submit a pull request
For support and questions, please open an issue on the repository.