What I’ve learned implementing a simple blocks game

I always wanted to make games, I have tons of games ideas, but I have always struggled while trying to implement them.

After reading an article I started to implement a simple block game.

Start simple

Event the simplest game becomes rapidly hundred of lines, dozen of functions and multiple files.

So by starting with a simple project, to learn the basic principles of the games, game loop, entity management…

Prototype then clean

To implement a new feature, I like to start to implement it with the basic algorithm and not so clean code.

When the feature works, the I look how to clean the code, refactor it.

No memory allocation/free in the main loop

Having memory allocation/free in the main loop can give huge leaks that will rapidly become segfaults. Furthermore  allocating the data at the init of the game or the level often simplify the code.

Compute the data offline

To handle the rotation, I started with a rotate function, but after some experimentation his behavior felled strange. By looking at the rotation documentation¬† I found that the implementation is complex, because of the size of the shapes (2×2, 1×4, etc).

So finally I implemented the rotation by storing the possible rotations in an array manually.

Move the complexity at the init

After the multiples cleanups, all the data transformations and creations that have to be done at run time are made at the init. All the SDL_texture for all the possible rotations are computed at init.

Beautiful does not mean complex

At first I started by looking how to implement gradients to draw the blocks. But I switched to colored block with carefully chosen colors and the result is good.