Member-only story
Build a Tetris Game Using SwiftUI
Create your own version of the classic game in code

In 1979 Alexey Pajitnov created a game that he called Tetris. A game that would become a 2D classic with a huge following that is still alive and kicking today. A game with some great coding challenges within it. Join me as I try and build Tetris using SwiftUI.
Gameplay
Bon — so what are the rules to this game — it’s elementary; different shape blocks appear at the top of the screen and slowly fall to the bottom. The player can rotate and move blocks left or right so they will all fit together when they get to there.
When the player completes a line, it disappears, lowering all the blocks above it. The game’s goal is to ensure the block line never reaches the screen’s top. The official [wikipedia] block shapes look like this.
Journey
Be warned as you read this; the solution takes several twists and turns; read everything before you copy anything.
Cells
I started then with a simple SwiftUI grid of 128 cells — 8 cells across and 16 cells down.

The colour of the cell is managed through a message, which signals a change to red.
The cell itself will change back after half a second unless expressly told not to do so in the message.
A timer manages the firing of the messages, and an array tracks the last cell in each line.
Beyond the automated actions, I have added a drag gesture to the code, which I am using here to change the column the activated cells passed down.
Lines
Bon — the next stage was detect and remove completed lines.