summaryrefslogtreecommitdiff
path: root/src/storage.rs
blob: fbb99b17722c49054119adfc53b28371386a3875 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
use crate::item::{Item, ItemType};

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Storage {
    pub items: Vec<Item>,
    carrying: usize,
    capacity: usize,
}

impl Storage {
    pub fn new(items: Vec<Item>, capacity: usize) -> Storage {
        let mut carrying = 0;
        for item in items.iter() {
            carrying += item.size;
        }
        Storage {
            items,
            capacity,
            carrying,
        }
    }

    pub fn take_item(&mut self, item_type: ItemType) -> Option<Item> {
        match self
            .items
            .iter()
            .position(|item| item.item_type == item_type)
        {
            Some(index) => {
                let item = self.items.remove(index);
                self.carrying -= item.size;
                Some(item)
            }
            None => None,
        }
    }

    pub fn give_item(&mut self, item: Item) -> bool {
        if self.capacity >= self.carrying + item.size {
            self.carrying += item.size;
            self.items.push(item);
            true
        } else {
            false
        }
    }

    pub fn item_count(&self, item_type: ItemType) -> usize {
        self.items
            .iter()
            .filter(|item| item.item_type == item_type)
            .count()
    }
}