X-Git-Url: http://deadsoftware.ru/gitweb?a=blobdiff_plain;f=core%2Fsrc%2Fru%2Fdeadsoftware%2Fcavedroid%2Fgame%2Fmodel%2Fitem%2FInventoryItem.kt;h=f847f7d0e3dd4d1f19ed91ee37266d3355a218c0;hb=3d972278cf3a54b6a7b574690ca4b41577464dce;hp=aa646cbe8fb88437cae365ea8c4c724fd335319d;hpb=c1b8f5c93482cb9933dd608c48f41622ce2994c6;p=cavedroid.git diff --git a/core/src/ru/deadsoftware/cavedroid/game/model/item/InventoryItem.kt b/core/src/ru/deadsoftware/cavedroid/game/model/item/InventoryItem.kt index aa646cb..f847f7d 100644 --- a/core/src/ru/deadsoftware/cavedroid/game/model/item/InventoryItem.kt +++ b/core/src/ru/deadsoftware/cavedroid/game/model/item/InventoryItem.kt @@ -4,17 +4,29 @@ import com.badlogic.gdx.graphics.Color import com.badlogic.gdx.graphics.g2d.SpriteBatch import com.badlogic.gdx.graphics.glutils.ShapeRenderer import ru.deadsoftware.cavedroid.game.GameItemsHolder +import ru.deadsoftware.cavedroid.game.mobs.player.Inventory import ru.deadsoftware.cavedroid.misc.Assets import ru.deadsoftware.cavedroid.misc.utils.drawSprite import ru.deadsoftware.cavedroid.misc.utils.drawString import ru.deadsoftware.cavedroid.misc.utils.px import java.io.Serializable +import kotlin.contracts.ExperimentalContracts +import kotlin.contracts.contract 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 @@ -33,17 +45,25 @@ class InventoryItem @JvmOverloads constructor( @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 !item.isTool() && amount + count <= item.params.maxStack + return amount + count <= item.params.maxStack } private fun drawAmountText(spriteBatch: SpriteBatch, text: String, x: Float, y: Float) { @@ -73,7 +93,9 @@ class InventoryItem @JvmOverloads constructor( } val sprite = item.sprite - spriteBatch.drawSprite(sprite, x, y) + val placeableMarginTop = (item as? Item.Placeable)?.block?.params?.spriteMargins?.top ?: 0 + val placeableMarginLeft = (item as? Item.Placeable)?.block?.params?.spriteMargins?.left ?: 0 + spriteBatch.drawSprite(sprite, x + placeableMarginLeft, y + placeableMarginTop) if (amount < 2) { return @@ -102,4 +124,12 @@ class InventoryItem @JvmOverloads constructor( } } + companion object { + + @OptIn(ExperimentalContracts::class) + fun InventoryItem?.isNoneOrNull(): Boolean { + contract { returns(false) implies(this@isNoneOrNull != null) } + return this?.item == null || this.item.isNone() + } + } }