pub struct Eevee {
pub level: u8,
pub health: u16,
pub attack: u16,
pub defense: u16,
}
Expand description
This type represents a basic Eevee
pokemon. It has a level, as well as health,
attack, and defense stats.
Something to note is that while it is possible to implement getters and setters for struct fields as if they were objects in OOP-paradigm languages, it is generally unnecessary for Rust. It can even get you into trouble with the borrow checker when dealing with fields that are references (we may talk about this when we get to lifetimes in week 7).
Marking a field as pub
, coupled with the borrow checker, will give you very similar
semantics as to normal getters and setters.
There are, of course, places where you do want these. And when we talk about traits in week 5, we will need to have them if we want to share behavior among types.
Fields§
§level: u8
For this part of the homework,
level
doesn’t actually represent anything important.
health: u16
§attack: u16
§defense: u16
Implementations§
source§impl Eevee
impl Eevee
sourcepub fn new() -> Self
pub fn new() -> Self
Creates an Eevee with the following base stats:
level: 0
health: 100
attack: 55
defense: 20
Note: We 0-level because we’re programmers 😎
let new_eevee = Eevee::new();
assert_eq!(new_eevee.level, 0);
assert_eq!(new_eevee.health, 100);
assert_eq!(new_eevee.attack, 55);
assert_eq!(new_eevee.defense, 20);
sourcepub fn take_damage(&mut self, damage: u16)
pub fn take_damage(&mut self, damage: u16)
Deals damage
amount of damage to the Eevee’s health.
let mut new_eevee = Eevee::new();
assert_eq!(new_eevee.health, 100);
assert_eq!(new_eevee.defense, 20);
new_eevee.take_damage(10);
assert_eq!(new_eevee.health, 100); // Not enough damage to overcome defense
new_eevee.take_damage(30);
assert_eq!(new_eevee.health, 90); // 30 - 20 = 10 damage taken
This function should panic with the message "Eevee fainted!"
if it takes more damage
than it has health. In other words, it should faint when it reaches 0 health.
sourcepub fn evolve(self, evolution: ElementalStone) -> EvolvedEevee
pub fn evolve(self, evolution: ElementalStone) -> EvolvedEevee
Given an Elemental Stone, evolve the Eevee into an EvolvedEevee
.
If given a stone that an Eevee cannot use to evolve, this function should
panic with the message "Encountered a weird rock..."
.
let mut new_eevee = Eevee::new();
let vaporeon = new_eevee.evolve(ElementalStone::HydroStone);
assert!(matches!(vaporeon, EvolvedEevee::Vaporeon(_, _)));