In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains "how to learn Rust to write a simple game", the content of the article is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in depth, together to study and learn "how to learn Rust to write a simple game" bar!
Install Rust
You can install a Rust tool chain using Rustup, or you can try Rust online instead of installing it locally.
If you install locally, you should update it regularly with rustup update to keep your toolchain fresh and use cargo update to keep your library up-to-date.
Guessing numbers in Rust language version
Rust is a language that gives anyone the ability to build reliable and efficient software. You can explore Rust by writing a Rust version of the "guessing numbers" game.
The first step is to write a Cargo.toml file. You can use the cargo new command to generate a skeleton Cargo.toml. This is almost the best way to start a Rust project.
$cargo new guess$ cd guess$ ls-1Cargo.tomlsrc/
The Cargo.toml file names your package, gives it some metadata and, most importantly, indicates that it depends on rand crate.
[package] name = "guess" version = "2020.11.0" authors = ["Moshe Zadka"] edition = "2018" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] rand = "*"
Many things in Rust are not provided by languages or standard libraries. Instead, you can get them from some external crate, and these crate can do many things.
The program logic is in src/main.rs:
Use rand::Rng;use std::io::BufRead; fn main () {let mut rng = rand::thread_rng (); let random = rng.gen_range (1.. 101); println! ("Guess a number between 1 and 100"); for line in std::io::stdin (). Lock (). Lines () {let parsed = line.ok (). As_deref (). Map (str::parse::) If let Some (Ok (guess)) = parsed {match guess {_ if guess
< random =>Println! ("Too low"), _ if guess > random = > println! ("Too high"), _ = > {println! ("That's right"); break;}
The first two lines of the code declare what you want to do. In this case, rand::Rng generates a guess, while trait std::io::BufRead makes it readable from standard input.
The entry to the Rust code is in the main () function, so the next step is to define main ().
To assign a value to a variable, first put let, then the name of the variable, followed by the = sign. This creates an immutable variable.
Most variables in Rust are immutable, but rng objects must be immutable (mut). For example, the statement let random = 0 assigns a zero value to the random variable.
The first line of the function creates a thread-safe Rng object and assigns it to the variable rng. Rust is based on thread and memory safety, so you have to think about these things when you start writing code.
The next line of the program reads the result of the function gen_range () and assigns it to a variable named random. This function takes a minimum value (inclusive) and an upper bound (not included). To include the upper bound, you can mark a larger number with an equal sign (for example, 1. Limit 100), or you can set the upper bound to 1 greater than your expected maximum, as I did in the code. In this case, the range is 1 to 100, making the game just enough challenging.
The central loop iterates over the lines in std::io::stdin (). Due to various exceptions that may cause rows to be unreadable, Rust requires you to wrap a row with a Result. Sometimes it may not be possible to resolve a row to an integer.
This code uses conditional pattern matching to ignore all lines that cause errors:
Let parsed = line.ok (). As_deref (). Map (str::parse::); if let Some (Ok (guess)) = parsed {/ /.}
The first line creates a Result object because it may fail in the read or parse step. Because the next line matches only on Some (Ok (guess)), it skips the if statement whenever the result of the line is a mismatched value. This is a powerful way to ignore errors.
Rust supports conditional expressions and process controls, such as loops. In the "guessing numbers" game, as long as the guessed value is not equal to random,Rust, the loop continues.
The body of the if statement contains a three-way branch of the match statement of Rust. Although match is most commonly used for pattern matching, it can also check for arbitrary conditions. In this case, an appropriate message is printed, and if the guess is correct, the break loop is interrupted.
Sample output
Now that you have written your Rust program, you can run it to play the number guessing game. Each time you run the program, Rust chooses a different random number, so keep guessing until you find the correct number.
$cargo run Compiling guess v2020.11.0 (/ Users/mzadka/src/guess) Finished dev [unoptimized + debuginfo] target (s) in 0.70s Running `target/debug/ guess`Guess a number between 1 and 10050Too high25Too high12Too low18Too high15Too high13Too low14That's right
A typical practice is to test the program with cargo run. Eventually, you may use cargo build to build an executable and run it in two separate steps.
Thank you for your reading, the above is the content of "how to learn Rust to write a simple game". After the study of this article, I believe you have a deeper understanding of how to learn Rust to write a simple game, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.