Getting started with C programming - Example game (with SDL)
-
Here is a very simple shooter game made with SDL in C. This is quite a big of a jump from the last example, but everything is commented, just go to the main function at the bottom and read along, one part at a time.
This page is for Windows. You can also check the
Linux version.
Adding sound and images to SDL
SDL can't load file formats like PNG or play sounds well by default, to do it properly we need to add additional SDL modules:
- For images: SDL_image (SDL2_image-devel-X.X.X-mingw.zip). (alternate link)
- For audio: SDL_mixer (SDL2_mixer-devel-X.X.X-mingw.zip). (alternate link)
Just like in the previous example: extract those .zip files, move (and merge) the include
and lib
folders into your project folder, and also move the .dll from bin
.
Next, add the libraries to the build file:
@ECHO OFF
set libraries=-I"include" -L"lib" -lSDL2 -lSDL2_Mixer -lSDL2_Image
gcc main.c %libraries% -mwindows -o exampleshooter && (
exampleshooter
)
This is why it's good to merge the lib
and include
folders, otherwise you'd have to define the paths to every library separately.
The code
I won't put the code on this webpage since there's about 700 lines of it, instead you can download the code and assets (not including the libraries mentioned above).
Use WASD or arrow keys to move, Space to shoot, Enter to restart, Esc to quit. The enemies will start spawning faster depending on how high your score is.
The project uses some free sounds and music from mixkit.