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
No known key found for this signature in database
GPG Key ID: CD80BE9AAEE78097
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.
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) {
Some(slot) => {
*slot = item;
None
let old = slot.take();
*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)
}
/// 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
pub fn swap_slots(&mut self, a: usize, b: usize) {
if a.max(b) < self.slots.len() {

View File

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