clige_rs/game/object/
level.rs

1use crate::{error::GameError, Entity};
2
3use super::{Action, Item, Message, Object};
4
5/// Main container for game objects.
6///
7/// Each `Level` has a name and a vector of owned objects.
8pub struct Level {
9    name: String,
10    content: Vec<Box<dyn Object>>,
11}
12
13impl Level {
14    /// Constructs `Level` with given `name` and `content`.
15    pub fn new(name: String, content: Vec<Box<dyn Object>>) -> Self {
16        Self { name, content }
17    }
18
19    /// Get level's name.
20    pub fn get_name(&self) -> &str {
21        &self.name
22    }
23
24    /// Prints on screen it's own name and then all stored objects.
25    pub fn draw(&self) {
26        color_print::cprintln!(
27            "\
28You are in <yellow, bold>{}</>.
29Here you can find:",
30            self.name
31        );
32
33        let mut i = 0;
34        for object in &self.content {
35            print!("\t{}. ", i);
36            object.draw();
37            i += 1;
38        }
39    }
40
41    /// Handles players' actions.
42    ///
43    /// `sender` is the `Entity` that issued an action.
44    ///
45    /// `target` is the index of targeted object in `content`
46    pub fn handle(
47        &mut self,
48        sender: &mut dyn Entity,
49        target: i32,
50        action: Action,
51    ) -> Result<(), GameError> {
52        let id = target as usize;
53
54        if id >= self.content.len(){
55            return Err(GameError::InvalidTarget)
56        }
57
58        let object = self.content.remove(id);
59
60        let message = object.handle(sender, action)?;
61
62        match message {
63            Message::Keep(object) => self.content.insert(id, object),
64            Message::Remove => {}
65            Message::Equip(weapon) => sender.equip_weapon(weapon),
66            Message::ChangeLocation(new_location) => sender.change_location(new_location),
67        }
68
69        Ok(())
70    }
71
72    pub fn add_child(&mut self, item: Box<impl Item + 'static>) {
73        self.content.push(item)
74    }
75
76    pub fn get_objects(&mut self) -> &mut Vec<Box<dyn Object>>{
77        &mut self.content
78    }
79}