A competitive online puzzle game built with Python, FastAPI, and real-time WebSocket support. Players compete in seed-based leaderboards where everyone plays the same daily puzzle, with social features including friends lists and online presence.
Critical Region is a falling-block puzzle played with the 12 pentominoes on a 12×24 board. Lines don't clear. Instead, filling a solid 5×5 square triggers a clear that spreads out along its rows and up its columns until it hits a hole, so a carefully built board can set off big cascades. Everyone gets the same piece sequence each day (a UTC daily seed), and scores go on that day's leaderboard.
The full rules are in Critical_Region.md.
- Pure Python game logic, decoupled from server and UI
- Modular game modes
- Core components: Board, Piece, GameState
- No external dependencies on server or client
- FastAPI-based REST API and WebSocket support
- Secure user authentication (JWT tokens, bcrypt password hashing)
- SQLite database with parameterized queries
- Server-side validation of all game actions
- Social features (friends list, friend requests)
- Minimal JavaScript for canvas rendering only
- HTML/CSS interface
- All game logic executed server-side
- Seed-Based Competition: Daily puzzle challenges where all players compete on the same game seed
- Leaderboards: Compare scores and times with other players globally and among friends
- User Authentication: JWT-based auth with email verification via Brevo
- Social System: Friends list, friend requests, online presence tracking
- Real-time Updates: WebSocket-based presence and leaderboard updates
- Rate Limiting: Comprehensive rate limits on all sensitive endpoints
- Account Security: Login attempt tracking, account lockouts, password strength requirements
- Token Management: Token blacklist for secure logout and revocation
- Admin Controls: Admin API for user management and system monitoring
- Authentication: JWT tokens with bcrypt password hashing and token blacklist
- Email Verification: Brevo-powered email verification with timed codes
- Input Validation: Comprehensive server-side validation and sanitization
- SQL Injection Prevention: Parameterized queries with aiosqlite
- XSS Prevention: HTML escaping and Content-Security-Policy headers
- Password Requirements: Enforced strong password policy (8+ chars, uppercase, lowercase, digit, special)
- CORS Protection: Configurable allowed origins with strict defaults
- Rate Limiting: SlowAPI-based rate limiting on auth, registration, API, and game endpoints
- Login Protection: Failed login tracking with progressive lockouts
- Trusted Hosts: Middleware to prevent host header attacks
- Clone and setup environment:
git clone https://github.com/gage-marshall/CriticalRegion.git
cd CriticalRegion
python -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate- Install dependencies:
pip install -r requirements.txt # Production dependencies
pip install -r requirements-dev.txt # Development tools (optional)- Configure environment:
cp .env.example .env
# Edit .env with your configuration:
# - Generate SECRET_KEY: python -c "import secrets; print(secrets.token_urlsafe(32))"
# - Set up Brevo API key for email verification (optional for local dev)
# - Configure CORS_ORIGINS and ALLOWED_HOSTS- Run the server:
# Using uvicorn (development)
uvicorn server.api.main:app --reload --host 0.0.0.0 --port 8000
# Or use the convenience scripts:
# Windows: start_local.bat
# Linux/Mac: ./start_local.sh- Access the application:
- Game UI: http://localhost:8000/
- API Docs: http://localhost:8000/api/docs (if DEBUG=true)
- Health Check: http://localhost:8000/health
See DEPLOYMENT.md and RENDER_DEPLOYMENT.md for detailed deployment instructions.
The application is configured for Render deployment via render.yaml with:
- Gunicorn production server (configured in
gunicorn.conf.py) - Environment variables for secrets management
- SQLite database (can be upgraded to PostgreSQL)
- Rate limiting and security hardening
POST /register- Register new user with email verificationPOST /verify-email- Verify email with verification codePOST /resend-verification- Resend verification codePOST /token- Login and get JWT access tokenGET /me- Get current authenticated user infoPOST /logout- Logout and blacklist current tokenPOST /change-password- Change user password
POST /game/start- Start anonymous game sessionPOST /game/{game_id}/action- Perform game actionGET /game/{game_id}- Get game state
POST /create- Create new game session with seedGET /{game_id}- Get current game statePOST /{game_id}/action- Perform game action with validationPOST /{game_id}/submit- Submit final score to leaderboardGET /leaderboard/{seed}- Get leaderboard for specific seedGET /daily- Get current daily seed and leaderboard
GET /friends- Get user's friends list with online statusPOST /friends/request/{user_id}- Send friend requestPOST /friends/accept/{request_id}- Accept friend requestDELETE /friends/reject/{request_id}- Reject friend requestGET /friends/requests/incoming- Get incoming friend requestsGET /friends/requests/outgoing- Get outgoing friend requestsDELETE /friends/{friend_id}- Remove friendGET /search- Search users by username
WS /ws- WebSocket connection for online presence tracking- Real-time updates on friends' online/offline status and leaderboard changes
GET /users- List all users (requires admin API key)DELETE /users/{user_id}- Delete user accountGET /stats- Get system statistics
GET /health- Health check endpointGET /- Serve game UI
CriticalRegion/
├── engine/ # Core game engine (decoupled)
│ ├── core/ # Core game components
│ │ ├── board.py # Board logic
│ │ ├── piece.py # Piece logic
│ │ ├── pentomino.py # The 12 pentominoes
│ │ └── game_state.py # Game state management
│ └── modes/ # Game mode implementations
│ ├── base_mode.py # Base game mode interface
│ └── critical_region.py # Critical Region rules
│
├── server/ # Server API layer
│ ├── api/ # API routes
│ │ ├── main.py # FastAPI app entry point
│ │ └── routes/ # Route modules
│ │ ├── auth.py # Authentication endpoints
│ │ ├── game.py # Game management endpoints
│ │ ├── social.py # Social features (friends)
│ │ ├── presence.py # Online presence tracking
│ │ ├── admin.py # Admin API
│ │ └── public_game.py # Anonymous game endpoints
│ ├── core/ # Core server logic
│ │ ├── config.py # Configuration management
│ │ ├── security.py # JWT auth & password hashing
│ │ ├── validation.py # Input validation & sanitization
│ │ ├── database.py # SQLite database operations
│ │ ├── game_manager.py # Game session management
│ │ ├── presence_manager.py # Online presence WebSocket manager
│ │ ├── token_blacklist.py # JWT token revocation
│ │ ├── rate_limiter.py # Rate limiting configuration
│ │ └── email_service.py # Brevo email integration
│ └── models/ # Pydantic models
│ ├── user.py # User models
│ ├── game.py # Game models
│ └── social.py # Social feature models
│
├── client/ # Client interface
│ ├── static/ # Static assets
│ │ ├── js/ # JavaScript for canvas rendering
│ │ └── css/ # Stylesheets
│ └── templates/ # HTML templates
│ └── index.html # Game UI
│
├── tests/ # Test suite
│
├── start.py # Production entry point
├── gunicorn.conf.py # Gunicorn production config
├── requirements.txt # Production dependencies
├── requirements-dev.txt # Development dependencies
├── render.yaml # Render deployment config
├── .env.example # Environment template
├── .gitignore # Git ignore rules
├── start_local.bat # Windows start script
├── start_local.sh # Unix start script
│
├── Critical_Region.md # Full game rules
├── DEPLOYMENT.md # Deployment guide
├── RENDER_DEPLOYMENT.md # Render-specific deployment
└── RUNNING_LOCALLY.md # Local development guide
# Install dev dependencies
pip install -r requirements-dev.txt
# Run all tests
pytest
# Run with coverage
pytest --cov=server --cov-report=html
- Follow PEP 8 guidelines
- Use type hints throughout
- Document all security-critical functions
- Validate all user inputs server-side
- Use parameterized SQL queries exclusively
- pytest: Testing framework
- black: Code formatting
- flake8: Linting
- mypy: Type checking (optional)
Key environment variables (see .env.example for full list):
| Variable | Description | Required |
|---|---|---|
SECRET_KEY |
JWT signing key (generate random 32+ bytes) | Yes |
ADMIN_API_KEY |
Admin API authentication key | Yes |
BREVO_API_KEY |
Brevo email service API key | Yes (if email enabled) |
DATABASE_URL |
SQLite database path | Yes |
CORS_ORIGINS |
JSON list of allowed CORS origins | Yes |
ALLOWED_HOSTS |
JSON list of allowed host headers | Yes |
EMAIL_VERIFICATION_ENABLED |
Enable email verification | No (default: true) |
DEBUG |
Enable debug mode (disables in production) | No (default: false) |
Rate limiting and security settings are also configurable via environment variables.
- Never commit
.envfile with secrets - Generate strong
SECRET_KEYusing:python -c "import secrets; print(secrets.token_urlsafe(32))" - Always validate and sanitize user inputs
- Use parameterized queries for all database operations
- Keep dependencies updated regularly
- HTTPS Required: Always use HTTPS in production
- Strong Secrets: Use cryptographically random keys (32+ bytes)
- Email Verification: Keep
EMAIL_VERIFICATION_ENABLED=true - Rate Limiting: Configure appropriate rate limits for your traffic
- Database: Consider migrating from SQLite to PostgreSQL for better concurrency
- Monitoring: Implement logging and monitoring for security events
- Backups: Regular database backups
- Updates: Keep Python and dependencies up to date
- Backend: FastAPI 0.115+, Python 3.13+
- Server: Uvicorn (dev), Gunicorn (production)
- Database: SQLite (aiosqlite), upgradeable to PostgreSQL
- Authentication: JWT (python-jose), bcrypt password hashing
- Email: Brevo API for email verification
- Real-time: WebSockets for game updates and presence
- Rate Limiting: SlowAPI
- Security: Pydantic validation, CORS, Trusted Host middleware
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Make your changes with tests
- Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
For deployment issues, see:
- DEPLOYMENT.md - General deployment guide
- RENDER_DEPLOYMENT.md - Render-specific instructions
- RUNNING_LOCALLY.md - Local development guide
MIT. See LICENSE.
