DEADSOFTWARE

Add my repo for automultibind
[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 private fun drawAmountText(spriteBatch: SpriteBatch, text: String, x: Float, y: Float) {
35 spriteBatch.drawString(text, x + 1, y + 1, Color.BLACK)
36 spriteBatch.drawString(text, x, y, Color.WHITE)
37 }
39 fun drawSelected(spriteBatch: SpriteBatch, x: Float, y: Float) {
40 if (item.isNone()) {
41 return
42 }
44 val sprite = item.sprite
45 val amountString = amount.toString()
46 spriteBatch.drawSprite(sprite, x - 10f, y - 10f, rotation = 0f, width = 20f, height = 20f)
47 drawAmountText(
48 spriteBatch = spriteBatch,
49 text = amountString,
50 x = x + 10f - Assets.getStringWidth(amountString) + 1f,
51 y = y + 10f - Assets.getStringHeight(amountString) + 1f
52 )
53 }
55 fun draw(spriteBatch: SpriteBatch, shapeRenderer: ShapeRenderer, x: Float, y: Float) {
56 if (item.isNone()) {
57 return
58 }
60 val sprite = item.sprite
61 spriteBatch.drawSprite(sprite, x, y)
63 if (amount < 2) {
64 return
65 }
67 if (item.isTool()) {
68 spriteBatch.end()
69 shapeRenderer.begin(ShapeRenderer.ShapeType.Filled)
70 shapeRenderer.color = Color.GREEN
71 shapeRenderer.rect(
72 /* x = */ x,
73 /* y = */ y + 1.px - 2,
74 /* width = */ 1.px * (amount.toFloat() / item.params.maxStack.toFloat()),
75 /* height = */ 2f
76 )
77 shapeRenderer.end()
78 spriteBatch.begin()
79 } else {
80 val amountString = amount.toString()
81 drawAmountText(
82 spriteBatch = spriteBatch,
83 text = amountString,
84 x = x + 1.px - Assets.getStringWidth(amountString),
85 y = y + 1.px - Assets.getStringHeight(amountString)
86 )
87 }
88 }
90 }