Remove inventory::swap and improve inventory::insert

This commit is contained in:
timokoesters
2019-08-31 00:09:25 +02:00
parent ba02956f05
commit a95893e43b
2 changed files with 14 additions and 16 deletions

View File

@ -33,15 +33,16 @@ impl Inventory {
} }
} }
/// Replaces an item in a specific slot of the inventory. Returns the item again if that slot /// Replaces an item in a specific slot of the inventory. Returns the old item or the same item again if that slot
/// was not found. /// was not found.
pub fn insert(&mut self, cell: usize, item: Option<Item>) -> Option<Item> { pub fn insert(&mut self, cell: usize, item: Item) -> Result<Option<Item>, Item> {
match self.slots.get_mut(cell) { match self.slots.get_mut(cell) {
Some(slot) => { Some(slot) => {
*slot = item; let old = slot.take();
None *slot = Some(item);
Ok(old)
} }
None => item, None => Err(item),
} }
} }
@ -50,12 +51,6 @@ impl Inventory {
self.slots.get(cell).and_then(Option::as_ref) self.slots.get(cell).and_then(Option::as_ref)
} }
/// Insert an item into 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))
}
/// Swap the items inside of two slots /// Swap the items inside of two slots
pub fn swap_slots(&mut self, a: usize, b: usize) { pub fn swap_slots(&mut self, a: usize, b: usize) {
if a.max(b) < self.slots.len() { if a.max(b) < self.slots.len() {

View File

@ -724,11 +724,14 @@ impl Server {
if let Some(stats) = if let Some(stats) =
state.ecs().write_storage::<comp::Stats>().get_mut(entity) state.ecs().write_storage::<comp::Stats>().get_mut(entity)
{ {
state // Insert old item into inventory
.ecs() if let Some(old_item) = stats.equipment.main.take() {
.write_storage::<comp::Inventory>() state
.get_mut(entity) .ecs()
.map(|inv| inv.insert(x, stats.equipment.main.take())); .write_storage::<comp::Inventory>()
.get_mut(entity)
.map(|inv| inv.insert(x, old_item));
}
stats.equipment.main = item; stats.equipment.main = item;
} }