RUST
Create a Simple DirectMedia Layer app
David Bolton shows how to set up SDL2 with Rust and demonstrates it with a fun 400-line program to pick a person at random.
Part Three!
Catch up with previous issues – see page 64!
OUR EXPERT
David Bolton has always been a bit of a maths nerd and draws upon a book by a maths writer to find inspiration for the program in this article.
QUICK TIPS
There’s a lot of functions in SDL2 and finding out what you can call in Rust can be tricky. The best suggestion is to do a Ctrl-click on a function’s parameters and get to the source code. For instance, Ctrl-clicking on Canvas opens render.rs, which is very well commented and includes examples in comments.
We’ve called our program Choice, and you can see how it works in the Logical Dice boxout (page 96). When it’s run, it defaults to five people, but if you pass in a number from 3-8as the first parameter, it uses that. In the VS Code terminal, use this to run it for six people: $ cargo run 6
You can download the project from GitHub (https://github.com/David-HBolton/Projects/blob/main/rust_choice. zip). It includes launch.json, so you can run it in VS Code, and one TrueType font, so the TTF code can output text. When you run it, it generates horizontal lines between the member columns. Move the mouse over a person number and it highlights the path to the bottom with a red line. The line shows a different path for each person.
The program holds the horizontal lines as a Vec, where a point has two ints called start and end. To follow a player, just start with the player number and iterate through the Vec. If the current player equals the start or the end, change it to the other one. If the current person is 1, and start is 1 and end is 3, the current person becomes 3. Each path goes to a different exit, including the one with the X.
We tried with different coloured lines, but because the main loop runs at 60 frames per second, unless the colour changing is done the same in each frame, it just changes colour very quickly.
Architecture of SDL
Almost all SDL (Simple DirectMedia Layer) applications have a similar architecture.
• Initialise the screen, load any TTF fonts used, load images into surfaces.
• A game loop. It repeats these at 60fps.
• Render screen objects.
• Look for keys/mouse clicks.