Building Tetris with Rust's macroquad library
I recently build my own tetris clone using Rust's macroquad library. Here's some quick thoughts about the project.
I decided to represent both the game board and the pieces with the same data structure...
pub struct Element {
width: usize,
height: usize,
name: Option<String>,
data: Vec<usize>,
}
On the structure I had several helper methods to...
- Rotate the piece
- Check if a line was full or not
- Set the color of the piece
I also had some functions that...
- Overladed two elements (either as a mutation or returned a "preview" of the operation)
- Determined if a piece could be placed on the game board at a particular position.
During the game loop, My state always had two boards - one the "final" board and the other the "pending" board. Having both let me play with the amount of time a piece can float before the landing becomes permanent. This gives the player leeway to change the position of the piece once it reaches a soft landing. This mechanic is slightly different than the original tetris and is sometimes helpful and sometimes not. I kind of like the challenge that it introduces.
During development I created a playground binary bin/playground.rs
that would let me test specific game mechanisms like...
- The speed of piece movement/landing to fine tune difficulty level
- Confirm that pieces are placed and rotated correctly
- Confirm how pieces are placed and rotated along the walls
- Experiment with the menu
One last note, I had to introduce a timer data structure that kept track of how much time had elapsed since the timer was started and whether or not the timer had reach its wait limit. These timers were used to control the speed that the pieces fell, the speed that pieces move left/right, the speed if the player is pressing down, and how long the soft landing should last.
Overall, an interesting project with some fun problems to solve.