DEADSOFTWARE

Remove guava
[cavedroid.git] / core / src / main / kotlin / ru / deadsoftware / cavedroid / game / objects / drop / Drop.kt
1 package ru.deadsoftware.cavedroid.game.objects.drop
3 import com.badlogic.gdx.math.Intersector
4 import com.badlogic.gdx.math.Rectangle
5 import com.badlogic.gdx.math.Vector2
6 import ru.deadsoftware.cavedroid.game.GameItemsHolder
7 import ru.deadsoftware.cavedroid.game.model.dto.SaveDataDto
8 import ru.deadsoftware.cavedroid.game.model.item.Item
9 import ru.deadsoftware.cavedroid.misc.Saveable
11 class Drop @JvmOverloads constructor(
12 x: Float,
13 y: Float,
14 _item: Item,
15 _amount: Int = 1,
16 ) : Rectangle(x, y, DROP_SIZE, DROP_SIZE), Saveable {
18 var amount: Int = _amount
19 private set
21 val itemKey = _item.params.key
22 val velocity = getInitialVelocity()
23 var pickedUp = false
25 @Suppress("UNNECESSARY_LATEINIT")
26 lateinit var item: Item
27 private set
29 init {
30 item = _item
31 }
33 fun initItem(gameItemsHolder: GameItemsHolder) {
34 if (this::item.isInitialized) {
35 return
36 }
38 item = gameItemsHolder.getItem(itemKey)
39 }
41 fun canMagnetTo(rectangle: Rectangle): Boolean {
42 val magnetArea = getMagnetArea()
43 return Intersector.overlaps(magnetArea, rectangle)
44 }
46 @JvmOverloads
47 fun subtract(count: Int = 1) {
48 if (count < 0) {
49 throw IllegalArgumentException("Can't subtract negative amount")
50 }
52 amount -= count
53 }
55 private fun getMagnetArea(): Rectangle {
56 return Rectangle(
57 /* x = */ x - MAGNET_DISTANCE,
58 /* y = */ y - MAGNET_DISTANCE,
59 /* width = */ width + MAGNET_DISTANCE * 2,
60 /* height = */ height + MAGNET_DISTANCE * 2,
61 )
62 }
64 override fun getSaveData(): SaveDataDto.DropSaveData {
65 return SaveDataDto.DropSaveData(
66 version = SAVE_DATA_VERSION,
67 x = x,
68 y = y,
69 width = width,
70 height = height,
71 velocityX = velocity.x,
72 velocityY = velocity.y,
73 itemKey = itemKey,
74 amount = amount,
75 pickedUp = pickedUp
76 )
77 }
79 companion object {
80 private const val SAVE_DATA_VERSION = 1
82 private const val MAGNET_DISTANCE = 8f
84 const val MAGNET_VELOCITY = 256f
85 const val DROP_SIZE = 8f
87 private fun getInitialVelocity(): Vector2 = Vector2(0f, -1f)
89 fun fromSaveData(saveData: SaveDataDto.DropSaveData, gameItemsHolder: GameItemsHolder): Drop {
90 saveData.verifyVersion(SAVE_DATA_VERSION)
92 return Drop(
93 x = saveData.x,
94 y = saveData.y,
95 _item = gameItemsHolder.getItem(saveData.itemKey),
96 _amount = saveData.amount,
97 ).apply {
98 velocity.x = saveData.velocityX
99 velocity.y = saveData.velocityY
100 pickedUp = saveData.pickedUp