Guessing game
Guess a number from 1 to 100. The first real program I wrote in Rust, compiled to WebAssembly and running in your browser.
What it is
The computer picks a whole number from 1 to 100. You guess, and after every guess it says "Too less!" or "Too more!" until you land on it.
It is the program from chapter 2 of The Rust Programming Language, the first project in the book. I wrote it while working through the book. The messages are mine. The book says "Too small!" and "Too big!".
How it was made
I wrote it as a terminal program. It loops until you guess right: print a prompt, wait for a line of input, compare it with the secret, print the answer.
let secret_number = rand::thread_rng().gen_range(1..=100);
loop {
println!("Please input your guess.");
let mut guess = String::new();
io::stdin()
.read_line(&mut guess)
.expect("Failed to read line");
// parse the line, then compare it with secret_number
}
That program cannot run on a web page as it is, for two reasons.
A web page has no standard input. In a terminal, read_line stops the program until you press Enter. A browser works the other way round. It runs a page's code when something happens, such as a key press, and the page is frozen until that code returns. A Rust loop that waited for input would freeze the page before you could type anything. So the loop turned inside out. Rust no longer asks for a guess. The page hands it one, Rust answers, and control goes back to the page.
WebAssembly cannot reach the operating system. WebAssembly is the format browsers run besides JavaScript, and Rust can compile to it. thread_rng() asks the operating system for a random seed, and a WebAssembly module has no operating system to ask. Compiling the original for the browser fails on exactly that:
error: the wasm*-unknown-unknown targets are not supported by default, you may need to enable the "js" feature. For more information see: https://docs.rs/getrandom/#webassembly-support
A module can only use what the page gives it. So the page draws a random number with crypto.getRandomValues and passes it in as the seed.
What is left in Rust is the game itself, in two functions:
static SECRET: AtomicU32 = AtomicU32::new(0);
#[unsafe(no_mangle)]
pub extern "C" fn new_game(seed: u32) {
let secret = SmallRng::seed_from_u64(seed.into()).gen_range(1..=100);
SECRET.store(secret, Relaxed);
}
#[unsafe(no_mangle)]
pub extern "C" fn guess(n: u32) -> i32 {
n.cmp(&SECRET.load(Relaxed)) as i32
}
guess is the same cmp as the original. It returns the Ordering as a number: -1 for too low, 0 for correct, 1 for too high. Without extra tooling, a function exported from Rust to WebAssembly takes and returns plain numbers. So all the text lives in the page's JavaScript: reading what you type, and every line the game prints.
cargo build --release --target wasm32-unknown-unknown turns this into a .wasm file smaller than one kilobyte. The page downloads it and calls the two functions through WebAssembly.instantiate. There is no wasm-bindgen, the usual tool for passing strings and objects between Rust and JavaScript, because two numbers do not need it.
One line of the original is gone: println!("Secret number is {secret_number}"). The book prints the secret while you test, then removes it at the end of the chapter. On a public page it would give the game away.