Integrating Tetris into a Flask App: A Fun Experiment
I decided to add a bit of fun to my personal portfolio by embedding a fully playable Tetris game. While there are plenty of JS libraries for this, I wanted to build the integration myself to understand how to handle game state and persistence.
The Stack
- Frontend: HTML5 Canvas and Vanilla JavaScript for the game loop and rendering.
- Backend: Flask API to handle high score submissions.
- Database: A separate SQLite database (
tetris_scores.db) to keep game data isolated from my analytics data.
Challenges
The biggest challenge was security. How do you prevent someone from sending a POST request with a score of 999999?
While client-side validation is impossible to fully secure without running the game logic on the server (which introduces latency), I implemented a simple hash check. The client sends a hash of the score combined with a secret salt. The server verifies this before accepting the score. It’s not bulletproof, but it stops basic curl attacks.
Result
The game is now live on the site! It includes a global leaderboard and runs smoothly on both desktop and mobile. It was a fun diversion from standard CRUD applications and taught me a lot about canvas rendering loops.