DEADSOFTWARE

Add some survival inventory controls
[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 drawSelected(spriteBatch: SpriteBatch, x: Float, y: Float) {
39 if (item.isNone()) {
40 return
41 }
43 val sprite = item.sprite
44 sprite.setOriginCenter()
45 sprite.setPosition(x, y)
46 sprite.setScale(1.25f)
47 sprite.draw(spriteBatch)
48 sprite.setScale(1f)
49 }
51 fun draw(spriteBatch: SpriteBatch, shapeRenderer: ShapeRenderer, x: Float, y: Float) {
52 if (item.isNone()) {
53 return
54 }
56 val sprite = item.sprite
57 spriteBatch.draw(sprite, x, y)
59 if (amount < 2) {
60 return
61 }
63 if (item.isTool()) {
64 spriteBatch.end()
65 shapeRenderer.begin(ShapeRenderer.ShapeType.Filled)
66 shapeRenderer.color = Color.GREEN
67 shapeRenderer.rect(
68 /* x = */ x,
69 /* y = */ y + 1.px - 2,
70 /* width = */ 1.px * (amount.toFloat() / item.params.maxStack.toFloat()),
71 /* height = */ 2f
72 )
73 shapeRenderer.end()
74 spriteBatch.begin()
75 } else {
76 val amountString = amount.toString()
77 drawAmountText(
78 spriteBatch = spriteBatch,
79 text = amountString,
80 x = x + 1.px - Assets.getStringWidth(amountString),
81 y = y + 1.px - Assets.getStringHeight(amountString)
82 )
83 }
84 }
86 }