veloren/common/src/comp/inventory/mod.rs

82 lines
1.9 KiB
Rust
Raw Normal View History

//Re-Exports
pub mod item;
2019-07-25 12:46:54 +00:00
// Reexports
pub use self::item::Item;
use specs::{Component, NullStorage, HashMapStorage};
2019-07-25 12:46:54 +00:00
use specs_idvs::IDVStorage;
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Inventory {
pub slots: Vec<Option<Item>>,
}
impl Inventory {
pub fn slots(&self) -> &[Option<Item>] {
&self.slots
}
2019-07-25 22:52:28 +00:00
pub fn len(&self) -> usize {
self.slots.len()
}
pub fn insert(&mut self, item: Item) -> Option<Item> {
match self.slots.iter_mut().find(|slot| slot.is_none()) {
Some(slot) => {
*slot = Some(item);
None
}
None => Some(item),
}
}
// Get info about an item slot
pub fn get(&self, cell: usize) -> Option<Item> {
self.slots.get(cell).cloned().flatten()
}
// Insert an item to a slot if its empty
pub fn swap(&mut self, cell: usize, item: Item) -> Option<Item> {
//TODO: Check if a slot is empty first.
self.slots.get_mut(cell).and_then(|cell| cell.replace(item))
}
2019-07-25 22:52:28 +00:00
pub fn swap_slots(&mut self, a: usize, b: usize) {
if a.max(b) < self.slots.len() {
self.slots.swap(a, b);
}
}
// Remove an item from the slot
2019-07-25 12:46:54 +00:00
pub fn remove(&mut self, cell: usize) -> Option<Item> {
self.slots.get_mut(cell).and_then(|item| item.take())
}
}
2019-07-25 14:02:05 +00:00
impl Default for Inventory {
fn default() -> Inventory {
2019-07-25 22:52:28 +00:00
let mut this = Inventory {
slots: vec![None; 8],
2019-07-25 22:52:28 +00:00
};
this.insert(Item::default());
this.insert(Item::default());
this.insert(Item::default());
this
2019-07-25 14:02:05 +00:00
}
}
impl Component for Inventory {
2019-07-31 09:30:46 +00:00
type Storage = HashMapStorage<Self>;
}
// ForceUpdate
#[derive(Copy, Clone, Debug, Default, Serialize, Deserialize)]
pub struct InventoryUpdate;
impl Component for InventoryUpdate {
type Storage = NullStorage<Self>;
}