Template for a roguelike in Rust targeting desktop and the web
Template for a roguelike in Rust targeting desktop and the web
This is a template for a Roguelike written in Rust. You can build it for Windows, macOS, Linux and the Web (via WebAssembly).
If you want to dive right in, just clone this repo and run it. Or read on for a detailed guide.
Rust is a pretty good language for writing roguelikes: it is fast, modern (modules, closures, fast collections, powerful macros, great enums) and it can build standalone executables for all the major platforms as well as the web!
The last bit is especially cool for game jams -- you don't have to worry about software packaging and distribution. Just give people a URL and they can play your game.
We're going to build a skeleton for a traditional ASCII roguelike. You can take it and turn it into a real game. The same codebase will work for all three the major platforms as well as the web. And it will support multiple fonts and text sizes so you can have your square maps and readable text at the same time!
It will look like this:
You can try the web build here:
https://tomassedovic.github.io/quicksilver-roguelike/
You will need the 2018 edition of Rust to get started. Get it from the Rust website:
https://www.rust-lang.org/learn/get-started
You'll want
rustup(it should be the default) -- we'll need it for the WebAssembly backend.
WebAssembly is a new bytecode format supported in all modern desktop browsers. It's faster than JavaScript and various languages (including Rust) can be compiled into it.
The WebAssembly compilation target is not shipped by default, but you can add it like so:
$ rustup target add wasm32-unknown-unknownYou don't need this if you only care about the desktop.
cargo-web handles everything you need to ship your game on the web. Install it like so:
$ cargo install cargo-webYou don't need this if you only care about the desktop.
Create a new project like so:
$ cargo new --vcs git roguelikeThis will initialise a new git repository as well! Remove
--vcs gitif you don't want that.
If you've got everything set up properly, you should be able to run the default program:
$ cd roguelike
$ cargo run --releaseIt will print:
$ cargo run --release
Compiling roguelike v0.1.0 (/home/thomas/tmp/roguelike)
Finished release [optimized] target(s) in 0.92s
Running `target/release/roguelike`
Hello, world!Rust has several gamedev engines and frameworks. We are going to use Quicksilver because it lets you target both the desktop and web really easily!
Open your Cargo.toml in the root of your repository and add this at
the end:
[dependencies]
# More features: "collisions", "complex_shapes", "immi_ui", "sounds", gamepads
quicksilver = { version = "0.3.22", default-features = false, features = ["fonts", "saving"]}We're disabling most of the features. You don't have to do this, but some of these require libraries you might not have installed. The above should compile pretty much anywhere.
You can always add the sound or gamepad support later if you need it.
Run the program again to build the quicksilver dependency:
$ cargo run --releaseThis might take a couple of minutes. It should print out the same hello world message as before.
We'll be always building the optimised version in this guide. You can drop the
--releaseflag but if you do, you're not allowed to make any speed measurements. Rust's debug builds are slower than you think. They're slower than unoptimised C++. They're slower than Ruby.
The first thing we'll do is create a window and print some text on it.
We'll do all our coding in the src/main.rs file in the
game repository. It's less than 300 lines total.
A Quicksilver app is all encapsulated in an item that implements the
quicksilver::lifecycle::State trait:
use quicksilver::prelude::*;
struct Game;
impl State for Game {
/// Load the assets and initialise the game
fn new() -> Result {
Ok(Self)
}
/// Process keyboard and mouse, update the game state
fn update(&mut self, window: &mut Window) -> Result {
Ok(())
}
/// Draw stuff on the screen
fn draw(&mut self, window: &mut Window) -> Result {
Ok(())
}
}Our game code will go into the three methods above.
To run the game add the above to main.rs and replace the main
function with:
fn main() {
let settings = Settings {
..Default::default()
};
run::("Quicksilver Roguelike", Vector::new(800, 600), settings);
}The Settings struct lets us control various engine
settings that we'll get to later. The 800 and 600 numbers
represent the logical size of your window. Depending on your DPI
settings, it might be bigger than that.
The first line where we use * from quicksilver::prelude called a
wildcard import. It brings in every type in
the quicksilver::prelude module. Without it, we would
have to explicitly add everything we use such as Settings, Vector,
State, etc.
Importing everything from a module is generally frowned upon in Rust. A crate can add more items later on and these might break your code when you switch to the newer version. So it's safer if you always declare exactly which types you use.
It also helps other people reading your code.
However, there are situations where you will always want to import certain types. In such cases, the crate authors might provide a so-called prelude module. It contains these common types and it is thought of as a more stable interface that you're expect to import everything from.
Even Rust's standard library does this. See
the std::io::prelude or indeed
the std::prelude which is imported automatically on
top of every Rust file.
We will be relying on the prelude import in this guide. If you want to be explicit about it, these are the functions and types you need to bring in right now:
use quicksilver::{
geom::Vector,
lifecycle::{run, Settings, State, Window},
Result,
};The
quicksilver::preludemodule was added in version0.3.10. If you're using an older version, either upgrade or use the explicit imports.
This guide will import more types later on. So if you're using them explicitly, you'll need to find them yourself. The Rust compiler can often suggest them. And when it can't, search for them in the Quicksilver documentation.
Running the game should now produce an empty window filled with black:
$ cargo run --releaseYou may have noticed the following message when running the code:
Warning: no asset directory found. Please place all your assets inside
a directory called 'static' so they can be loaded
Execution continuing, but any asset-not-found errors are likely due to
the lack of a 'static' directory.Quicksilver expects all the game assets to be in the static
directory under the project's root. We don't have one, hence the
warning.
Let's create it:
$ mkdir staticOur repo should now look like this:
├── Cargo.lock
├── Cargo.toml
├── src
│ └── main.rs
├── static
└── target
└── releaseWhat goes into static? Sounds, images, models, maps and anything
else your game will need to load. Including fonts.
Let's use mononoki, a beautiful little monospace font. Go to the mononoki website and download it.
It is an open source font created by Matthias Tellen distributed under the Open Font License 1.1.
Unpack it and copy the mononoki-Regular.ttf file into our new
static directory.
All initial asset loading should happen in the State::new function.
We will load the font file, use it to render text into an image and
store it in our Game struct:
…We're rendering two bits of text: a heading 72 points big and the font's credits.
Thanks, Matthias!
Font::load returns a Future. It exits
immediately and loads the actual file in the background.
Calling and_then will let us manipulate the value (font)
when it's ready.
Quicksilver does dynamic asset loading for us!
Note that, "render" here doesn't mean "draw onto the
screen". font.render takes a text and a style (font
size & colour) and creates an image we can draw later.
Font rendering takes a lot computational of work. It has to rasterise the glyphs, handle kerning, etc. Drawing an image is much faster. So we do all the hard work once, store the results and then just draw a static image later.
To make both of our images (title and the credits) available to the
draw method, we'll store them in the Game struct:
struct Game {
title: Asset,
mononoki_font_info: Asset,
}And return them from new:
Ok(Self {
title,
mononoki_font_info,
})We wrote a bunch of code, but if we run the game, nothing changed. We
need to draw the text on screen which happens in the draw function.
Since we rendered our text black, we're going to set the window's background to white to make it visible. Let's do that and draw the text:
fn draw(&mut self, window: &mut Window) -> Result {
window.clear(Color::WHITE)?;
self.title.execute(|image| {
window.draw(
&image
.area()
.with_center((window.screen_size().x as i32 / 2, 40)),
Img(&image),
);
Ok(())
})?;
self.mononoki_font_info.execute(|image| {
window.draw(
&image
.area()
.translate((2, window.screen_size().y as i32 - 60)),
Img(&image),
);
Ok(())
})?;
Ok(())
}window.clear(color) is quite straightforward, but
what's the deal with this execute stuff?
We're not storing the images directly -- we're storing them
in an Asset. An Asset wraps a Future that is, a
value that might not actually exist yet (because the font did not
finish loading).
To get to the Asset's inner value, we need to call execute and
pass in a closure that operates on that asset (an [Image][image] in
our case). If it's loaded, the c
No open issues yet, or sync has not completed.