diff --git a/rust/role-playing-game/Cargo.toml b/rust/role-playing-game/Cargo.toml new file mode 100644 index 0000000..ab9f24f --- /dev/null +++ b/rust/role-playing-game/Cargo.toml @@ -0,0 +1,4 @@ +[package] +name = "role_playing_game" +version = "0.1.0" +edition = "2021" diff --git a/rust/role-playing-game/HELP.md b/rust/role-playing-game/HELP.md new file mode 100644 index 0000000..40d8a33 --- /dev/null +++ b/rust/role-playing-game/HELP.md @@ -0,0 +1,85 @@ +# Help + +## Running the tests + +Execute the tests with: + +```bash +$ cargo test +``` + +All but the first test have been ignored. After you get the first test to +pass, open the tests source file which is located in the `tests` directory +and remove the `#[ignore]` flag from the next test and get the tests to pass +again. Each separate test is a function with `#[test]` flag above it. +Continue, until you pass every test. + +If you wish to run _only ignored_ tests without editing the tests source file, use: + +```bash +$ cargo test -- --ignored +``` + +If you are using Rust 1.51 or later, you can run _all_ tests with + +```bash +$ cargo test -- --include-ignored +``` + +To run a specific test, for example `some_test`, you can use: + +```bash +$ cargo test some_test +``` + +If the specific test is ignored, use: + +```bash +$ cargo test some_test -- --ignored +``` + +To learn more about Rust tests refer to the online [test documentation][rust-tests]. + +[rust-tests]: https://doc.rust-lang.org/book/ch11-02-running-tests.html + +## Submitting your solution + +You can submit your solution using the `exercism submit src/lib.rs Cargo.toml` command. +This command will upload your solution to the Exercism website and print the solution page's URL. + +It's possible to submit an incomplete solution which allows you to: + +- See how others have completed the exercise +- Request help from a mentor + +## Need to get help? + +If you'd like help solving the exercise, check the following pages: + +- The [Rust track's documentation](https://exercism.org/docs/tracks/rust) +- [Exercism's support channel on gitter](https://gitter.im/exercism/support) +- The [Frequently Asked Questions](https://exercism.org/docs/using/faqs) + +Should those resources not suffice, you could submit your (incomplete) solution to request mentoring. + +## Rust Installation + +Refer to the [exercism help page][help-page] for Rust installation and learning +resources. + +## Submitting the solution + +Generally you should submit all files in which you implemented your solution (`src/lib.rs` in most cases). If you are using any external crates, please consider submitting the `Cargo.toml` file. This will make the review process faster and clearer. + +## Feedback, Issues, Pull Requests + +The GitHub [track repository][github] is the home for all of the Rust exercises. If you have feedback about an exercise, or want to help implement new exercises, head over there and create an issue. Members of the rust track team are happy to help! + +If you want to know more about Exercism, take a look at the [contribution guide]. + +## Submitting Incomplete Solutions +It's possible to submit an incomplete solution so you can see how others have completed the exercise. + +[help-page]: https://exercism.org/tracks/rust/learning +[github]: https://github.com/exercism/rust +[contribution guide]: https://exercism.org/docs/community/contributors \ No newline at end of file diff --git a/rust/role-playing-game/HINTS.md b/rust/role-playing-game/HINTS.md new file mode 100644 index 0000000..de2efd2 --- /dev/null +++ b/rust/role-playing-game/HINTS.md @@ -0,0 +1 @@ +# Hints \ No newline at end of file diff --git a/rust/role-playing-game/README.md b/rust/role-playing-game/README.md new file mode 100644 index 0000000..c3d17d0 --- /dev/null +++ b/rust/role-playing-game/README.md @@ -0,0 +1,163 @@ +# Role-Playing Game + +Welcome to Role-Playing Game on Exercism's Rust Track. +If you need help running the tests or submitting your code, check out `HELP.md`. +If you get stuck on the exercise, check out `HINTS.md`, but try and solve it without using those first :) + +## Introduction + +## Null-References + +If you have ever used another programming language (C/C++, Python, Java, Ruby, Lisp, etc.), it is likely that you have encountered `null` or `nil` before. +The use of `null` or `nil` is the way that these languages indicate that a particular variable has no value. +However, this makes accidentally using a variable that points to `null` an easy (and frequent) mistake to make. +As you might imagine, trying to call a function that isn't there, or access a value that doesn't exist can lead to all sorts of bugs and crashes. +The creator of `null` went so far as to call it his ['billion-dollar mistake'.](https://www.infoq.com/presentations/Null-References-The-Billion-Dollar-Mistake-Tony-Hoare/) + +## The `Option` Type + +To avoid these problems, Rust does not use null-references. +However, it still needs a safe way to indicate that a particular variable has no value. +This is where `Option` comes in. +Instead of having a variable which lacks a value, Rust variables can use the `Option` enum. +This enum has two variants: `None`, Rust's null-equivalent; and `Some(T)`, where T is a value of any type. + +It looks like this: + +```rust +enum Option { + None, + Some(T), +} +``` + +You can think of `Option` as a layer of safety between you and the problems that null-references can cause, while still retaining their conceptual usefulness. + +## Using `Option` + +Setting a variable to `None` is fairly straightforward: + +```rust +let nothing: Option = None; // Variable nothing is set to None +``` + +However, if you wish for the `Option` type to carry a value, you cannot assign this value directly. +An `Option` type variable and, say, an `i32` type variable are not equivalent. +You will need to use `Some`: + +```rust +let wrong_way: Option = -4; // This will not work + +let right_way: Option = Some(-4); // This will work +let another_right_way = Some(-4); // Compiler infers that this is Option +``` + +It's also for this reason that the following will not work: + +```rust +let number = 47; +let option_number = Some(15); + +let compile_error = number + option_number; // Cannot add an i32 and an Option - they are of different types +``` + +If you wish to get the value that is contained by Some, you will first need to check that it exists: + +```rust +let mut some_words = Some("choose something to say"); // some_words set to something + +match some_words { + Some(str) => println!("Here, we will {}", str), + None => println!("I've got nothing to say"), +} // Prints "Here, we will choose something to say" + +some_words = None; // some_words now set to None + +// exactly the same match block as above +match some_words { + Some(str) => println!("Here, we will {}", str), + None => println!("I've got nothing to say"), +} // Prints "I've got nothing to say" +``` + +Besides `match`, Rust has other tools available for checking and accessing values contained within `Option`, but `match` should be familiar to you by now. + +Additionally, consider this a demonstration of why Rust uses `Option` instead of a null-reference. +The point is that **you _must_ check** whether or not the `Option` variable is `Some` (in which case you can go ahead and extract and use the value contained within), or `None`. +Anything else, and your program will not compile; the compiler is keeping you safe from `null`. + +## Instructions + +You're working on implementing a role-playing game. The player's character is represented by the following: + +```rust +pub struct Player { + health: u32, + mana: Option, + level: u32, +} +``` + +Players in this game must reach level 10 before they unlock a mana pool so that they can start casting spells. Before that point, the Player's mana is `None`. + +You're working on two pieces of functionality in this game, the revive mechanic and the spell casting mechanic. + +The `revive` method should check to ensure that the Player is indeed dead (their health has reached 0), and if they are, the method should return a new Player instance with 100 health. +If the Player's level is 10 or above, they should also be revived with 100 mana. +If the Player's level is below 10, their mana should be `None`. The `revive` method should preserve the Player's level. + +```rust +let dead_player = Player { health: 0, mana: None, level: 2 }; +dead_player.revive() +// Returns Player { health: 100, mana: None, level: 2 } +``` + +If the `revive` method is called on a Player whose health is 1 or above, then the method should return `None`. + +```rust +let alive_player = Player { health: 1, mana: Some(15), level: 11 }; +alive_player.revive() +// Returns None +``` + +The `cast_spell` method takes a mutable reference to the Player as well as a `mana_cost` parameter indicating how much mana the spell costs. It returns the amount of damage that the cast spell performs, which will always be two times the mana cost of the spell if the spell is successfully cast. + +- If the player does not have access to a mana pool, attempting to cast the spell must decrease their health by the mana cost of the spell. The damage returned must be 0. + + ```rust + let not_a_wizard_yet = Player { health: 79, mana: None, level: 9 }; + assert_eq!(not_a_wizard_yet.cast_spell(5), 0) + assert_eq!(not_a_wizard_yet.health, 74); + assert_eq!(not_a_wizard_yet.mana, None); + ``` + +- If the player has a mana pool but insufficient mana, the method should not affect the pool, but instead return 0 + + ```rust + let low_mana_wizard = Player { health: 93, mana: Some(3), level: 12 }; + assert_eq!(low_mana_wizard.cast_spell(10), 0); + assert_eq!(low_mana_wizard.health, 93); + assert_eq!(low_mana_wizard.mana, Some(3)); + ``` + +- Otherwise, the `mana_cost` should be deducted from the Player's mana pool and the appropriate amount of damage should be returned. + + ```rust + let wizard = Player { health: 123, mana: Some(30), level: 18 }; + assert_eq!(wizard.cast_spell(10), 20); + assert_eq!(wizard.health, 123); + assert_eq!(wizard.mana, Some(20)); + ``` + +Have fun! + +## Source + +### Created by + +- @seanchen1991 +- @coriolinus + +### Contributed to by + +- @PaulT89 \ No newline at end of file diff --git a/rust/role-playing-game/src/lib.rs b/rust/role-playing-game/src/lib.rs new file mode 100644 index 0000000..3be65e1 --- /dev/null +++ b/rust/role-playing-game/src/lib.rs @@ -0,0 +1,38 @@ +// This stub file contains items that aren't used yet; feel free to remove this module attribute +// to enable stricter warnings. +#![allow(unused)] + +pub struct Player { + pub health: u32, + pub mana: Option, + pub level: u32, +} + +impl Player { + pub fn revive(&self) -> Option { + match self.health { + 0 => { + let mut new_mana = Some(100); + if (self.level < 10) { new_mana = None; } + Some(Player { health: 100, mana: new_mana, level: self.level}) + }, + _ => None + } + } + + pub fn cast_spell(&mut self, mana_cost: u32) -> u32 { + match self.mana { + None => { + self.health = self.health.saturating_sub(mana_cost); + 0 + }, + Some(mana) if mana < mana_cost => { + 0 + }, + Some(mana) => { + self.mana = Some(mana - mana_cost); + mana_cost * 2 + } + } + } +} diff --git a/rust/role-playing-game/tests/role-playing-game.rs b/rust/role-playing-game/tests/role-playing-game.rs new file mode 100644 index 0000000..4993207 --- /dev/null +++ b/rust/role-playing-game/tests/role-playing-game.rs @@ -0,0 +1,136 @@ +use role_playing_game::*; + +#[test] +fn test_reviving_dead_player() { + let dead_player = Player { + health: 0, + mana: Some(0), + level: 34, + }; + let revived_player = dead_player + .revive() + .expect("reviving a dead player must return Some(player)"); + assert_eq!(revived_player.health, 100); + assert_eq!(revived_player.mana, Some(100)); + assert_eq!(revived_player.level, dead_player.level); +} + +#[test] +#[ignore] +fn test_reviving_dead_level9_player() { + let dead_player = Player { + health: 0, + mana: None, + level: 9, + }; + let revived_player = dead_player + .revive() + .expect("reviving a dead player must return Some(player)"); + assert_eq!(revived_player.health, 100); + assert_eq!(revived_player.mana, None); + assert_eq!(revived_player.level, dead_player.level); +} + +#[test] +#[ignore] +fn test_reviving_dead_level10_player() { + let dead_player = Player { + health: 0, + mana: Some(0), + level: 10, + }; + let revived_player = dead_player + .revive() + .expect("reviving a dead player must return Some(player)"); + assert_eq!(revived_player.health, 100); + assert_eq!(revived_player.mana, Some(100)); + assert_eq!(revived_player.level, dead_player.level); +} + +#[test] +#[ignore] +fn test_reviving_alive_player() { + let alive_player = Player { + health: 1, + mana: None, + level: 8, + }; + assert!(alive_player.revive().is_none()); +} + +#[test] +#[ignore] +fn test_cast_spell_with_enough_mana() { + const HEALTH: u32 = 99; + const MANA: u32 = 100; + const LEVEL: u32 = 100; + const MANA_COST: u32 = 3; + + let mut accomplished_wizard = Player { + health: HEALTH, + mana: Some(MANA), + level: LEVEL, + }; + + assert_eq!(accomplished_wizard.cast_spell(MANA_COST), MANA_COST * 2); + assert_eq!(accomplished_wizard.health, HEALTH); + assert_eq!(accomplished_wizard.mana, Some(MANA - MANA_COST)); + assert_eq!(accomplished_wizard.level, LEVEL); +} + +#[test] +#[ignore] +fn test_cast_spell_with_insufficient_mana() { + let mut no_mana_wizard = Player { + health: 56, + mana: Some(2), + level: 22, + }; + + // we want to clone so we can compare before-and-after effects of casting the spell, + // but we don't want to introduce that concept to the student yet, so we have to do it manually + let clone = Player { ..no_mana_wizard }; + + assert_eq!(no_mana_wizard.cast_spell(3), 0); + assert_eq!(no_mana_wizard.health, clone.health); + assert_eq!(no_mana_wizard.mana, clone.mana); + assert_eq!(no_mana_wizard.level, clone.level); +} + +#[test] +#[ignore] +fn test_cast_spell_with_no_mana_pool() { + const MANA_COST: u32 = 10; + + let mut underleveled_player = Player { + health: 87, + mana: None, + level: 6, + }; + + let clone = Player { + ..underleveled_player + }; + + assert_eq!(underleveled_player.cast_spell(MANA_COST), 0); + assert_eq!(underleveled_player.health, clone.health - MANA_COST); + assert_eq!(underleveled_player.mana, clone.mana); + assert_eq!(underleveled_player.level, clone.level); +} + +#[test] +#[ignore] +fn test_cast_large_spell_with_no_mana_pool() { + const MANA_COST: u32 = 30; + + let mut underleveled_player = Player { + health: 20, + mana: None, + level: 6, + }; + + assert_eq!(underleveled_player.cast_spell(MANA_COST), 0); + assert_eq!(underleveled_player.health, 0); + assert_eq!(underleveled_player.mana, None); + assert_eq!(underleveled_player.level, 6); +}