The objective is to design and implement a complete feature-complete "Tetris" clone with a new garbage inserting mechanic, using a vertical array of LED matrices and a separate one for the hard mode and an LCD display for user information. The system must feature an advanced control scheme utilizing an MPU6050 for player movement, menu navigation, and buttons for game and menu interaction. The software architecture must strictly follow the Model-View-Controller (MVC) pattern to separate the complex game logic from the specific hardware implementation.
Key requirements include implementing original game mechanics like the "7-Bag" random generation system, "Ghost" piece prediction and the new garbage inserting mde. The system also needs a background idle animation for the menu, EEPROM memory storage for high scores, and a non-blocking audio system for background music and menu sound effects.
For this assignment I used:
- 1x Arduino UNO R3
- 3x 1088AS 8x8 Dot Matrix Modules with MAX7219 Drivers
- 1x 1088AS 8x8 Dot Matrix with MAX7219 Drivers on shield
- 1x 16x2 LCD Display (Parallel connection)
- 1x MPU6050 Gyroscope/Accelerometer Module
- 1x Passive Buzzer
- 2x Push Buttons
- Resistors (2x 330ohm & 4x 220ohm)
- Necessary cables
First, I constructed the display array using three 1088AS 8x8 LED matrices. Since driving 256 LEDs individually would exceed the Arduino's available pins, I used MAX7219 drivers for each matrix. I daisy-chained these modules, connecting the Data Out of one driver to the Data In of the next. This configuration allows the system to control the entire vertical display using a shift-register architecture that requires only three digital pins (Data, Clock, and Load).
For simplicity and gameplay functionality, the 4th matrix is not positioned next to the others and utilizes a shield.
For the controls, I utilized an MPU6050 sensor. While this sensor provides precise 6-axis motion tracking, I specifically utilized the accelerometer data to detect the controller's physical tilt. This allows the user to slide pieces left or right by tilting the breadboard itself. I also added extra buttons for specific actions: a Pause button and a manual Rotation button.
I also added a passive buzzer to the circuit. To protect the digital pin from overcurrent damage and manage the volume, I calculated and installed a 220ohm current-limiting resistor in series with the buzzer.
The following constants map the Arduino pins:
-
LED Matrix
-
Data = 12
-
Clock = 11
-
Load (CS) = 10
-
LCD Display (4-bit mode)
-
RS = 9
-
Enable = 8
-
D4 = 7, D5 = 6, D6 = 5, D7 = 4
-
Inputs
-
MPU6050 Gyro = A4 (SDA), A5 (SCL)
-
Rotate Button = 2
-
Pause Button = 13
-
Audio
-
Buzzer = 3
I implemented the circuit on a breadboard, carefully orienting the matrix modules to ensure they share the same alignment.
To manage the complexity of this project, I implemented a strict Model-View-Controller (MVC) architecture. This approach separates the code into three distinct logical components, maintaining a clear separation between game logic, rendering, and control systems.
Technical & Architectural Overview I implemented a strict Model-View-Controller design pattern to separate the TetrisEngine logic from the RenderDisp (hardware output). It features a hardware abstraction layer with a coordinate mapping system that translates logical game coordinates (x,y) into physical hardware addresses for the daisy-chained LED matrices.
I applied Object-Oriented Programming principles to make clear and easy to use methods for adapting the code to any hardware.
1. TetrisEngine (The Model)
The TetrisEngine class encapsulates all game logic and state management, including: piece movement, collision detection, scoring, and line clearing. It holds the core logic, manages the 24x8 grid (board[24][8]), and enforces the rules of Tetris. The update() function serves as the main game tick. It handles gravity, timing events, and state calculations. The start() method initializes the game board, resets the score, and generates the initial piece bag for a new session.
To ensure the frustration of "piece drought" does not exist, I used the original "7-Bag" random generation instead of the simple one, via spawnPiece(). The engine initializes an array containing exactly one of each tetromino type. Using the Fisher-Yates shuffle algorithm, it randomizes the order of these seven items. The system draws sequentially from this bag. Only once all seven pieces have been dealt, the system regenerates and reshuffles the array. This guarantees a statistically even distribution of piece types over time.
When a piece lands, lockPiece() adds the active falling piece into the static board grid and triggers the lock sound effect. The engine then runs checkLines() to scan the grid for fully occupied rows, clear them, shift blocks downward, and calculate the score. To assist the player, predictTetromino() calculates the ghost piece position. Whenever the active piece moves or rotates, this method creates a virtual copy of the piece's coordinates and iteratively simulates a downward movement loop. It increments the Y-position until collision logic returns false. The system then renders a visual preview at the last valid Y-coordinate, showing the player exactly where the piece will land if dropped instantly.
The integrity of the game state relies entirely on the isValidMove() function, which acts as the gatekeeper for all spatial changes. This function takes proposed coordinates and rotation states, then iterates through the tetromino's 4x4 bitmask. For every active block in the shape, it performs a dual verification: it confirms the block lies within the matrix boundaries and that the corresponding cell on the global board grid is currently empty. If even a single bit fails these checks, the move is rejected, preventing wall-clipping or block overlapping.
User actions are handled by specific methods: inputRotate() attempts to rotate the active piece 90 degrees, applying wall-kick logic if necessary, while inputHardDrop() instantly drops the active piece to the calculated ghost position and locks it. Finally, the updateMusic() function acts as a non-blocking audio scheduler that iterates through the theme melody array.
2. RenderDisp (The View)
The RenderDisp class abstracts display hardware operations for the LED matrices and LCD, handling all visual output. Responsible for visualization, it reads the abstract state from the Model and decides how to render it. The begin() method initializes the MAX7219 drivers and loads custom characters into the LCD memory. The update() function runs the rendering loop that refreshes the display buffers based on the current Game or Menu state. Contextual text and icons are handled by drawMenu(), which updates the LCD based on the current menu context. To visualize difficulty, drawGarbageTank() shows the current level of the garbage buffer on the side LED matrix. When the game is inactive, drawIdleAnim() renders a screensaver-style animation of falling pieces. The physical translation of pixels is managed by renderSinglePixel(), which translates logical (row, col) coordinates into physical device instructions, handling matrix orientation via the rotate90Cw flag. Additionally, loadMenuIcons() uploads custom bitmap icons (Play, Settings, etc.) to the LCD CGRAM for the main menu.
3. SysMenu (The State Manager)
The SysMenu class manages UI state transitions and navigation flow across menus, settings, and game states. The mainMenu state acts as the primary hub allowing users to select game modes, settings, or view information. The settingsMenu state provides user-configurable toggles for audio, visual aids (ghost piece), and starting difficulty. During gameplay, the pauseMenu state allows the user to pause the game, to resume, adjust settings, or quit. If a high score is achieved, the nameEntry state is triggered, providing a text-entry interface for the user to input a 3-character tag. Navigation is handled by MapsUp() and MapsDown(), which control cursor movement within menus and character cycling during name entry. The select() method executes the action associated with the currently highlighted menu option, while checkHighScore() compares the final game score against stored EEPROM records to determine if a new record has been set.
4. ControlSerial & HardwareController (The Controller)
The ControlSerial and HardwareController classes provide abstracted input layers for serial commands and hardware interfaces (buttons, accelerometer). The begin() method configures the MPU6050 accelerometer via I2C and sets up button input pins. The update() function runs a polling routine that reads sensor data and manages I2C reconnection logic.
To interface with the MPU6050 sensor, I utilized the Arduino Wire library, which handles the I2C protocol. The communication process begins by waking the sensor from sleep mode by writing a 0 to the Power Management register (0x6B). During the main loop, I retrieve motion data by first transmitting the starting register address 0x3B to the device. I then request 6 bytes of data using Wire.requestFrom(MPU_ADDR, 6, true).
Since the MPU6050 stores 16-bit sensor values as two separate 8-bit bytes (High and Low), I reconstruct the full integer by reading the High byte, shifting it 8 bits to the left (<< 8), and performing a bitwise OR operation with the Low byte. This operation is performed sequentially for the X, Y, and Z axes. This raw 16-bit signed integer is then passed to the input handling logic.
During gameplay, handleGameInput() interprets this reconstructed accelerometer tilt for movement and button states for rotation or drops. In the menus, handleMenuInput() maps tilt gestures to vertical menu navigation and horizontal character selection. System stability is ensured by attemptConnection(), a fault-tolerance routine that attempts to re-initialize the MPU6050 if communication is lost.
The movement logic interprets raw accelerometer data to create a natural "sliding" control scheme by reading the X-axis tilt. If the raw value exceeds the defined threshold of +/-2500, it triggers a lateral move. For lateral movement, a timer-based delay (moveDelay) is utilized to allow controlled continuous sliding when the tilt is held. However, for specific discrete actions like the 'Hold' command or Menu navigation (Back), I implemented a 'Neutral Reset Hysteresis.' After these specific actions are registered, an internal flag (actionReset) locks further input until the user returns the controller to a near-neutral position, ensuring that these sensitive commands trigger exactly once per physical gesture., ensuring that one distinct physical tilt translates to exactly one discrete game movement.
Garbage Mode Mechanic
To add a twist and increase the difficulty, I implemented a custom Garbage Mechanic that is active only in "Hard Mode". The Model maintains a buffer array called the Garbage Tank (garbageTank) that can hold up to 8 pending garbage lines. I set up a garbageInterval timer of 5000ms, meaning every 5 seconds, the logic triggers addGarbageToTank(), which pushes a new pending line into this buffer. To help the player anticipate attacks, the View layer reads the tank's state and renders a "danger bar" on the fourth LED matrix via drawGarbageTank. When the tank overflows by reaching 8 lines, the dispenseGarbage() function is triggered. This executes a board disruption by iterating through the grid and shifting every block upwards. Any blocks at the very top are pushed out, which can trigger a "Game Over." The bottom rows are then filled with "garbage" lines. Crucially, I programmed these lines to have exactly one random empty space (holePos), forcing the player to "dig" down through the solid lines to survive, rather than just building upwards.
Finite State Machines & System Utilities The application flow is controlled by two Finite State Machines (FSM).
The Game Loop FSM handles the core mechanics, validating game time against the current fall speed. As the player clears lines, the level increases, causing the logic to decrease the fallSpeed delay. Crucially, this FSM now incorporates the Hard Mode logic: if active, it tracks a separate garbageInterval timer. When this timer expires, the FSM interrupts the standard gravity cycle to trigger addGarbageToTank(), dynamically altering the board state.
For data persistence, I utilized the Arduino's EEPROM. On startup, the system checks address 0 for a specific "Magic Number" (45). If this value is absent—or if the user holds the Action button during the boot sequence—the code performs a Factory Reset, wiping the memory to clear high scores and restore default configuration. I used EEPROM.put() to store HighScoreEntry structures and EEPROM.update() to persist user preferences (Music, SFX, Ghost Piece, and Menu Sounds), ensuring these settings survive power cycles. Finally, the audio system is built on a non-blocking driver. Instead of using delay() which would freeze the game physics, the updateMusic() function checks the system time against a musicNextTime variable. The driver implements a priority system: while the background theme ("Korobeiniki") plays continuously, it is momentarily pre-empted by specific Sound Effects (locking pieces, clearing lines, or menu navigation), ensuring distinct audio feedback without causing input lag.
**Video:https://youtu.be/C_v41LGn7h8**

