I know this sounds a little crazy, but building out a game like Tetris is perfect for SwiftUI. No, I don’t mean that SwiftUI is the optimal framework for it. What I do mean is that Tetris in SwiftUI would be a fun exercise for anyone that wants to learn more about SwiftUI.

Steps to build Tetris

Let’t first try to break out a Tetris implementation into bite sized steps. This is by no means an exhaustive or final list, but we should at least know what we want to do and when we want to do it. Each step will hopefully map to 1 video / post (with the exception of this post and the next post), so I may come back and edit them a later to align more with my progress:

What Tetris looks like in SwiftUI

In Tetris, we should be able to almost entirely separate the state of the game from how the game is drawn. The view just needs to know the board’s state, when it changes, and how to send it user actions. Then, we need to have have some kind of “engine” that will drive the game to the next state. This sounds a lot like an MVVM pattern.

First, we need to have some kind of Model to save the state of the game. We’ll call this the TetrisGameModel, and this will be in charge of recording what’s on the board, the current Tetromino, and anything else we may want later (like scores). We’ll also expose methods for moving the Tetrominos.

Next, we’ll need to have some kind of ViewModel to translate all of this to something for the View. We’ll call this TetrisGameViewModel, and this will be an ObservableObject so the View will automatically update. We’ll change the board from the TetrisGameModel into squares the View can draw, and map the user actions to different Tetromino movements.

Finally, there will be a View that just display all of this to the user. We’ll call this the TetrisGameView. This will be responsible for drawing the ViewModel and listening for user actions.

The last thing we need to consider is where to put the engine. I’ve been back and forth between putting this in the Model or the ViewModel. It seems more like something that should live outside this framework, but I’ll put this inside the Model. The engine will need to know a lot about the state that the ViewModel doesn’t need to know, so the model seems like the right place.

What next?

Now that we have a basic design down, it’s time to actually code this out. We’ll start off with creating a board and a view to show the user, and we’ll implement that in my next post.

Thanks for reading!

– SchwiftyUI