Wasm Mini Game of Maze 🚗

Mini Game in Rust & Wasm
20th Oct 2024
Introduction
In the programming I usually do, a game loop is not necessary. However, it is necessary when programing games.
I'm going to share some insights from my experience implementing a game loop with Rust and WASM.
What I learned
Here are the websites I referred to when coding the game loop.
- The code has implemented a sophisticated technique to synchronize rendering with the browser's actual frame rate.
const FRAME_SIZE: f64 = 1.0 / 60.0 * 1000.0;
while game_loop.accumulated_delta > FRAME_SIZE {
game.update(&keystate);
game_loop.accumulated_delta -= FRAME_SIZE;
}
game_loop.last_frame = perf;
game.draw(&renderer);
- Rust ownership, particularly the concept of borrowing and lifetimes, is crucial for understanding this implementation.
impl GameLoop {
let f: SharedLoopClosure = Rc::new(RefCell::new(None));
let g = f.clone();
let mut keystate = KeyState::new();
*g.borrow_mut() = Some(browser::create_raf_closure(move |perf: f64| {
let _= browser::request_animation_frame(f.borrow().as_ref().unwrap());
}));
browser::request_animation_frame(
g.borrow()
.as_ref()
.ok_or_else(|| anyhow!("GameLoop: Loop is None"))?,
)?;
Ok(())
}
What was fun experience
Forty years ago, my first personal computer was an MSX2. I enjoyed programming by typing in the source code published in BASIC Magazine. The first program I typed was a racing game similar to the one I've created recently. Though my memory is a bit hazy, I recall the walls being represented by "#" and the car by a diamond character "♢". I remember spending hours correcting typos while referencing the magazine's source code. The joy I felt when the copied program finally ran is something I'll never forget. The excitement of seeing a program come to life hasn't changed at all, even now.