DEADSOFTWARE

5121ab3f9f778575af8131c553cbe07f035bdefc
[cavedroid.git] / core / src / ru / deadsoftware / cavedroid / game / model / item / InventoryItem.kt
1 package ru.deadsoftware.cavedroid.game.model.item
3 import com.badlogic.gdx.graphics.Color
4 import com.badlogic.gdx.graphics.g2d.SpriteBatch
5 import com.badlogic.gdx.graphics.glutils.ShapeRenderer
6 import ru.deadsoftware.cavedroid.game.GameItemsHolder
7 import ru.deadsoftware.cavedroid.misc.Assets
8 import ru.deadsoftware.cavedroid.misc.utils.drawSprite
9 import ru.deadsoftware.cavedroid.misc.utils.drawString
10 import ru.deadsoftware.cavedroid.misc.utils.px
11 import java.io.Serializable
13 class InventoryItem @JvmOverloads constructor(
14 val itemKey: String,
15 var amount: Int = 1,
16 ) : Serializable {
18 @Transient
19 lateinit var item: Item
20 private set
22 @JvmOverloads
23 constructor(_item: Item, amount: Int = 1) : this(_item.params.key, amount) {
24 item = _item
25 }
27 fun init(gameItemsHolder: GameItemsHolder) {
28 if (this::item.isInitialized) {
29 return
30 }
31 item = gameItemsHolder.getItem(itemKey)
32 }
34 @JvmOverloads
35 fun add(count: Int = 1) {
36 amount += count
37 }
39 @JvmOverloads
40 fun subtract(count: Int = 1) {
41 add(-count)
42 }
44 @JvmOverloads
45 fun canBeAdded(count: Int = 1): Boolean {
46 return amount + count <= item.params.maxStack
47 }
49 private fun drawAmountText(spriteBatch: SpriteBatch, text: String, x: Float, y: Float) {
50 spriteBatch.drawString(text, x + 1, y + 1, Color.BLACK)
51 spriteBatch.drawString(text, x, y, Color.WHITE)
52 }
54 fun drawSelected(spriteBatch: SpriteBatch, x: Float, y: Float) {
55 if (item.isNone()) {
56 return
57 }
59 val sprite = item.sprite
60 val amountString = amount.toString()
61 spriteBatch.drawSprite(sprite, x - 10f, y - 10f, rotation = 0f, width = 20f, height = 20f)
62 drawAmountText(
63 spriteBatch = spriteBatch,
64 text = amountString,
65 x = x + 10f - Assets.getStringWidth(amountString) + 1f,
66 y = y + 10f - Assets.getStringHeight(amountString) + 1f
67 )
68 }
70 fun draw(spriteBatch: SpriteBatch, shapeRenderer: ShapeRenderer, x: Float, y: Float) {
71 if (item.isNone()) {
72 return
73 }
75 val sprite = item.sprite
76 spriteBatch.drawSprite(sprite, x, y)
78 if (amount < 2) {
79 return
80 }
82 if (item.isTool()) {
83 spriteBatch.end()
84 shapeRenderer.begin(ShapeRenderer.ShapeType.Filled)
85 shapeRenderer.color = Color.GREEN
86 shapeRenderer.rect(
87 /* x = */ x,
88 /* y = */ y + 1.px - 2,
89 /* width = */ 1.px * (amount.toFloat() / item.params.maxStack.toFloat()),
90 /* height = */ 2f
91 )
92 shapeRenderer.end()
93 spriteBatch.begin()
94 } else {
95 val amountString = amount.toString()
96 drawAmountText(
97 spriteBatch = spriteBatch,
98 text = amountString,
99 x = x + 1.px - Assets.getStringWidth(amountString),
100 y = y + 1.px - Assets.getStringHeight(amountString)