Here we're defining a simple rock-paper-scissors games which allows player to call a play function with their selected move and get an outcome in return.
WIT files are used by language-specific build tools to automatically handle all required codegen. Let's implement the play function in Rust using the cargo-component tooling.
src/lib.rs
mod bindings; // This module is automatically generated by cargo-component
use bindings::{
Guest, Metrics, Move,
Move::{Paper, Rock, Scissors},
Outcome,
Outcome::{Draw, Loss, Win}
};
use rand::Rng;
struct Component;
impl Guest for Component {
fn play(input: Move) -> Outcome {
let server_selection = [Rock, Paper, Scissors][rand::thread_rng().gen_range(0..3)];
match (input, server_selection) {
(Rock, Scissors) | (Scissors, Paper) | (Paper, Rock) => Win,
(Rock, Rock) | (Scissors, Scissors) | (Paper, Paper) => Draw,
_ => Loss,
}
}
}
bindings::export!(Component with_types_in bindings);
Accessing persistent storage
Coming soon
Further reading on the Webassembly Component Model