diff --git a/fxgl-gameplay/src/main/kotlin/com/almasb/fxgl/inventory/Inventory.kt b/fxgl-gameplay/src/main/kotlin/com/almasb/fxgl/inventory/Inventory.kt index d83b0aa29..561d47a16 100644 --- a/fxgl-gameplay/src/main/kotlin/com/almasb/fxgl/inventory/Inventory.kt +++ b/fxgl-gameplay/src/main/kotlin/com/almasb/fxgl/inventory/Inventory.kt @@ -82,10 +82,14 @@ class Inventory( } /** - * @return the total sum of all [item] stack quantities + * @return the total sum of all [item] stack quantities or 0 if [item] not present */ fun getItemQuantity(item: T): Int - = itemQuantityProperty(item).value + = try { + itemQuantityProperty(item).value + } catch (e: IllegalArgumentException) { + 0 + } @Deprecated("Use add(ItemConfig)", ReplaceWith("add(com.almasb.fxgl.inventory.ItemConfig)")) fun add(item: T, name: String, description: String, view: Node, quantity: Int): Boolean { @@ -202,6 +206,23 @@ class Inventory( return true } + /** + * Transfer all items from [other] to this inventory. + * + * @return true if operation was (at least partially) successful, if returns false then no modifications were made to either inventory objects + */ + fun transferAllFrom(other: Inventory): Boolean { + var isPartiallySuccess = false + + // toList() to create a copy since [transferFrom] modifies [other.items] + other.items.toList().forEach { + if (transferFrom(other, it.userItem, it.quantity)) + isPartiallySuccess = true + } + + return isPartiallySuccess + } + /** * Transfer [item] with [quantity] amount from [other] to this inventory. * diff --git a/fxgl-gameplay/src/test/kotlin/com/almasb/fxgl/inventory/InventoryTest.kt b/fxgl-gameplay/src/test/kotlin/com/almasb/fxgl/inventory/InventoryTest.kt index 0ba4e4b60..cce2730cc 100644 --- a/fxgl-gameplay/src/test/kotlin/com/almasb/fxgl/inventory/InventoryTest.kt +++ b/fxgl-gameplay/src/test/kotlin/com/almasb/fxgl/inventory/InventoryTest.kt @@ -286,6 +286,31 @@ class InventoryTest { assertTrue(!inventory.hasItem("Hello")) } + @Test + fun `Transfer all from inventory`() { + inventory = Inventory(5) + + inventory.add("Hello", quantity = 5) + inventory.add("Hi", quantity = 3) + + val other = Inventory(5) + + assertTrue(other.transferAllFrom(inventory)) + assertThat(other.getItemQuantity("Hello"), `is`(5)) + assertThat(other.getItemQuantity("Hi"), `is`(3)) + + val other2 = Inventory(1) + + // true because [other2] only has 1 space, so partially succeeds + assertTrue(other2.transferAllFrom(other)) + assertThat(other2.getItemQuantity("Hello"), `is`(5)) + assertThat(other2.getItemQuantity("Hi"), `is`(0)) + + + // false because [other2] now has no space, so op fails + assertFalse(other2.transferAllFrom(other)) + } + @Test fun `Transfer from inventory does not work if no item in inventory`() { inventory = Inventory(5)