DEADSOFTWARE

Update version
[cavedroid.git] / core / src / ru / deadsoftware / cavedroid / game / model / item / InventoryItem.kt
index 6cb2a9d85bf5232fb8e7b37750c336f7e0aa0f38..765224334d1d29b8441e0f59d1a9b0bd07df503e 100644 (file)
@@ -12,9 +12,18 @@ import java.io.Serializable
 
 class InventoryItem @JvmOverloads constructor(
     val itemKey: String,
-    var amount: Int = 1,
+    _amount: Int = 1,
 ) : Serializable {
 
+    var amount = _amount
+        set(value) {
+            field = if (value < 0) {
+                0
+            } else {
+                value
+            }
+        }
+
     @Transient
     lateinit var item: Item
         private set
@@ -31,6 +40,29 @@ class InventoryItem @JvmOverloads constructor(
         item = gameItemsHolder.getItem(itemKey)
     }
 
+    @JvmOverloads
+    fun add(count: Int = 1) {
+        if (count > 0 && Int.MAX_VALUE - count < amount) {
+            throw IllegalArgumentException("$amount + $count exceeds Int.MAX_VALUE")
+        }
+
+        amount += count
+    }
+
+    @JvmOverloads
+    fun subtract(count: Int = 1) {
+        if (count < 0) {
+            throw IllegalArgumentException("Can't subtract negative amount")
+        }
+
+        add(-count)
+    }
+
+    @JvmOverloads
+    fun canBeAdded(count: Int = 1): Boolean {
+        return amount + count <= item.params.maxStack
+    }
+
     private fun drawAmountText(spriteBatch: SpriteBatch, text: String,  x: Float, y: Float) {
         spriteBatch.drawString(text, x + 1, y + 1, Color.BLACK)
         spriteBatch.drawString(text, x, y, Color.WHITE)
@@ -42,11 +74,14 @@ class InventoryItem @JvmOverloads constructor(
         }
 
         val sprite = item.sprite
-        sprite.setOriginCenter()
-        sprite.setPosition(x, y)
-        sprite.setScale(1.25f)
-        sprite.draw(spriteBatch)
-        sprite.setScale(1f)
+        val amountString = amount.toString()
+        spriteBatch.drawSprite(sprite, x - 10f, y - 10f, rotation = 0f, width = 20f, height = 20f)
+        drawAmountText(
+            spriteBatch = spriteBatch,
+            text = amountString,
+            x = x + 10f - Assets.getStringWidth(amountString) + 1f,
+            y = y + 10f - Assets.getStringHeight(amountString) + 1f
+        )
     }
 
     fun draw(spriteBatch: SpriteBatch, shapeRenderer: ShapeRenderer, x: Float, y: Float) {