DEADSOFTWARE

49cc59d6a5366f484df8a51a6ecd400d538a2a14
[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.drawString
9 import ru.deadsoftware.cavedroid.misc.utils.px
10 import java.io.Serializable
12 class InventoryItem @JvmOverloads constructor(
13 val itemKey: String,
14 var amount: Int = 1,
15 ) : Serializable {
17 @Transient
18 lateinit var item: Item
19 private set
21 @JvmOverloads
22 constructor(_item: Item, amount: Int = 1) : this(_item.params.key, amount) {
23 item = _item
24 }
26 fun init(gameItemsHolder: GameItemsHolder) {
27 if (this::item.isInitialized) {
28 return
29 }
30 item = gameItemsHolder.getItem(itemKey)
31 }
33 private fun drawAmountText(spriteBatch: SpriteBatch, text: String, x: Float, y: Float) {
34 spriteBatch.drawString(text, x + 1, y + 1, Color.BLACK)
35 spriteBatch.drawString(text, x, y, Color.WHITE)
36 }
38 fun draw(spriteBatch: SpriteBatch, shapeRenderer: ShapeRenderer, x: Float, y: Float) {
39 if (item.isNone()) {
40 return
41 }
43 val sprite = item.sprite
44 spriteBatch.draw(sprite, x, y)
46 if (amount < 2) {
47 return
48 }
50 if (item.isTool()) {
51 spriteBatch.end()
52 shapeRenderer.begin(ShapeRenderer.ShapeType.Filled)
53 shapeRenderer.color = Color.GREEN
54 shapeRenderer.rect(
55 /* x = */ x,
56 /* y = */ y + 1.px - 2,
57 /* width = */ 1.px * (amount.toFloat() / item.params.maxStack.toFloat()),
58 /* height = */ 2f
59 )
60 shapeRenderer.end()
61 spriteBatch.begin()
62 } else {
63 val amountString = amount.toString()
64 drawAmountText(
65 spriteBatch = spriteBatch,
66 text = amountString,
67 x = x + 1.px - Assets.getStringWidth(amountString),
68 y = y + 1.px - Assets.getStringHeight(amountString)
69 )
70 }
71 }
73 }