text_based_rpg 0.1.0

A text-based RPG game
Documentation
use crate::entity::Entity;
use std::rc::Rc;

pub struct Item {
    pub name: String,
    effect: Rc<dyn Fn(&mut dyn Entity)>,
}

impl Clone for Item {
    fn clone(&self) -> Self {
        Item {
            name: self.name.clone(),
            effect: self.effect.clone(),
        }
    }
}

impl Item {
    pub fn new<F>(name: &str, effect: F) -> Self
    where
        F: Fn(&mut dyn Entity) + 'static,
    {
        Item {
            name: name.to_string(),
            effect: Rc::new(effect),
        }
    }

    pub fn apply(&self, target: &mut dyn Entity) {
        (self.effect)(target);
    }
}
impl Default for Item {
    fn default() -> Self {
        Item {
            name: "Default Potion".to_string(),
            effect: Rc::new(|_| {println!("Default Effect called")})
        }
    }
}
#[cfg(test)]
mod tests {
    use super::Item; //Generally want to use super when refering to our current mod
    use crate::entity::{Entity, Hero}; //And crate with other modules

    #[test]
    fn apply_10_damage() {
        let take_10_damage_potion =
            Item::new("Take 10 Damage Potion", |target: &mut dyn Entity| {
                target.take_damage(10);
            });

        let mut hero = Hero::default();
        let initial_health = hero.get_current_health();
        println!("Hero initial health: {}", hero.get_current_health());

        take_10_damage_potion.apply(&mut hero);
        
        let final_health = hero.get_current_health();

        assert_eq!(
            initial_health - 10,
            final_health,
            "Hero did not take 10 damage!"
        );
    }
}