Fix remove(slot) method

- Add Remove/AddItemTransactionBlock
This commit is contained in:
atomicint
2016-02-17 20:45:43 -05:00
parent a56ac01203
commit 6744df2a57
3 changed files with 82 additions and 1 deletions
@@ -421,7 +421,10 @@ public final class Inventory {
public Optional<Item> remove(int slot) {
Item item = get(slot);
if (item != null) {
remove(item);
int amount = remove(item);
if (amount != item.getAmount()) {
return Optional.of(new Item(item.getId(), amount));
}
return Optional.of(item);
}
return Optional.empty();
@@ -0,0 +1,43 @@
package org.apollo.game.model.inv.transaction.block;
import org.apollo.game.model.Item;
import org.apollo.game.model.inv.Inventory;
import org.apollo.game.model.inv.transaction.TransactionBlock;
/**
* A TransactionBlock which adds an Item to an Inventory.
*/
public final class AddItemTransactionBlock implements TransactionBlock {
/**
* The Inventory the Item is being added to.
*/
private final Inventory inventory;
/**
* The Item we are adding to the Inventory.
*/
private final Item item;
/**
* Creates a new {@link AddItemTransactionBlock}.
*
* @param inventory The Inventory we are adding the specified Item to.
* @param item The Item to add to the Inventory.
*/
public AddItemTransactionBlock(Inventory inventory, Item item) {
this.inventory = inventory;
this.item = item;
}
@Override
public boolean commit() {
return !inventory.add(item).isPresent();
}
@Override
public void revert() {
inventory.remove(item);
}
}
@@ -0,0 +1,35 @@
package org.apollo.game.model.inv.transaction.block;
import java.util.Optional;
import org.apollo.game.model.Item;
import org.apollo.game.model.inv.Inventory;
import org.apollo.game.model.inv.transaction.TransactionBlock;
public final class RemoveItemTransactionBlock implements TransactionBlock {
private final Inventory inventory;
private final Item item;
private Optional<Item> removed = Optional.empty();
public RemoveItemTransactionBlock(Inventory inventory, Item item) {
this.inventory = inventory;
this.item = item;
}
@Override
public boolean commit() {
int slot = inventory.slotOf(item.getId());
removed = inventory.remove(slot);
return removed.get().equals(item);
}
@Override
public void revert() {
removed.ifPresent(inventory::add);
removed = Optional.empty();
}
}