Skip to content

Commit

Permalink
feat: Added Inventory::transferAllFrom(), getItemQuantity() returns 0…
Browse files Browse the repository at this point in the history
… if no item, closes #1131
  • Loading branch information
AlmasB committed Feb 3, 2023
1 parent b31db7b commit 9204a7f
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 2 deletions.
Expand Up @@ -82,10 +82,14 @@ class Inventory<T>(
}

/**
* @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 {
Expand Down Expand Up @@ -202,6 +206,23 @@ class Inventory<T>(
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<T>): 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.
*
Expand Down
Expand Up @@ -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<String>(5)

assertTrue(other.transferAllFrom(inventory))
assertThat(other.getItemQuantity("Hello"), `is`(5))
assertThat(other.getItemQuantity("Hi"), `is`(3))

val other2 = Inventory<String>(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)
Expand Down

0 comments on commit 9204a7f

Please sign in to comment.