DEADSOFTWARE

6cb2a9d85bf5232fb8e7b37750c336f7e0aa0f38
[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 sprite.setOriginCenter()
46 sprite.setPosition(x, y)
47 sprite.setScale(1.25f)
48 sprite.draw(spriteBatch)
49 sprite.setScale(1f)
50 }
52 fun draw(spriteBatch: SpriteBatch, shapeRenderer: ShapeRenderer, x: Float, y: Float) {
53 if (item.isNone()) {
54 return
55 }
57 val sprite = item.sprite
58 spriteBatch.drawSprite(sprite, x, y)
60 if (amount < 2) {
61 return
62 }
64 if (item.isTool()) {
65 spriteBatch.end()
66 shapeRenderer.begin(ShapeRenderer.ShapeType.Filled)
67 shapeRenderer.color = Color.GREEN
68 shapeRenderer.rect(
69 /* x = */ x,
70 /* y = */ y + 1.px - 2,
71 /* width = */ 1.px * (amount.toFloat() / item.params.maxStack.toFloat()),
72 /* height = */ 2f
73 )
74 shapeRenderer.end()
75 spriteBatch.begin()
76 } else {
77 val amountString = amount.toString()
78 drawAmountText(
79 spriteBatch = spriteBatch,
80 text = amountString,
81 x = x + 1.px - Assets.getStringWidth(amountString),
82 y = y + 1.px - Assets.getStringHeight(amountString)
83 )
84 }
85 }
87 }