-
Notifications
You must be signed in to change notification settings - Fork 7
Getting Random Values
Random numbers in Rust are gotten using the rand
crate. However, this involves some OS-specific functionality which doesn't currently support the switch officially. In order to add support for the switch, we need to add the following section to our Cargo.toml
:
[patch.crates-io]
getrandom = { git = "https://github.com/Raytwo/getrandom" }
Then, to actually use it, we add the rand
crate to our dependencies:
[dependencies]
rand = "0.7.3"
Now, we use rand as we would in any other program:
let mut rng = rand::thread_rng();
let y: f64 = rng.gen(); // generates a float between 0 and 1
let z: u8 = rng.gen(); // generates a random 8 bit integer
For more information on using rand
, see the rust cookbook page or the documentation for it.
Be aware that your game might have its own RNG function which keeps track of state. This will bypass that and use the nnsdk version, providing now state tracking. For most uses that is more than acceptable, but keep aware of the possibility. For example, Smash Ultimate keeps track of the RNG throughout the match in order to have the same RNG during replays. For Smash, you'd want to use app::sv_math::rand
or sv_math::randf
.
Rust allows "dependency patching" to allow you to replace a dependency of a crate you use with your own version of that dependency. For more information, see the the cargo reference page