Snake Game With Rust, JavaScript, and WebAssembly | Part 1
This is part of the course “Snake Game With Rust, JavaScript, and WebAssembly”.
In this course, we will build a Snake Game with Rust, JavaScript, and WebAssembly. We will learn how to export API implemented with Rust to JavaScript app. We will get to know canvas rendering, applications of vectors, and basics of game development. You can find the source code in this GitHub repository, and check out the game here.
In the first part of the course, we will make requirements for the game, think of architecture and bootstrap the project. Changes that we will introduce in this part reflected in this commit.
Game
We will create a classic snake game. When the snake eats food, it becomes longer, and the score increases. If the snake heats the wall or bites the tail game is over.
Additionally, we will allow the player to stop the game by pressing the space button. To keep the user motivated, we will save the best score and show it alongside the current one. We make sure that the game looks good on any screen size, be it a tiny mobile phone or a large TV.
Architecture
We want each component of the game to be as independent as possible. We will implement the core logic of the game with Rust and will export API to JavaScript via WebAssembly.
The main thing that we will export from Rust is Game struct with a constructor and two public methods. The first method will receive a duration from the last update and direction that the user wants a snake to take. The second method will check if the game is over.
On the JavaScript side, we will run the game loop and call API methods. We will render all game elements with canvas, capture user input, and save user best score.
Bootstrap
To bootstrap our project, we will use templates that have everything in place to compile Rust library into WebAssembly and export it to JavaScript.
First, let’s install the tools we will need.
curl https://rustwasm.github.io/wasm-pack/installer/init.sh -sSf | sh
cargo install cargo-generate
Next, we are going to use the template to bootstrap the project.
cargo generate --git https://github.com/rustwasm/wasm-pack-template.git --name rust-js-snake-game
cd rust-js-snake-game
Now we can build the project. The command below will create a wasm module and few js files that will expose wasm API.
wasm-pack build
To create a web app that will use the wasm module, we will use another template.
npm init wasm-app www
cd www
To show our web app where to search for the wasm package, we need to open package.json, and add dependencies block.
"dependencies": {
"wasm-snake-game": "file:../pkg"
}
Next, we need to modify www/index.js to import wasm-snake-game instead of the hello-wasm-pack package:
We are ready to test the whole thing!
npm install
npm run start
In the next part, we will create an instance of the Game struct from JavaScript. Stay tuned!
Reach the next level of focus and productivity with increaser.org.