DEADSOFTWARE

548c44a5bbfb7a12fa0237dfa56d94cc2402d8a4
[cavedroid.git] / core / src / 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 @Transient
27 lateinit var item: Item
28 private set
30 init {
31 item = _item
32 }
34 fun initItem(gameItemsHolder: GameItemsHolder) {
35 if (this::item.isInitialized) {
36 return
37 }
39 item = gameItemsHolder.getItem(itemKey)
40 }
42 fun canMagnetTo(rectangle: Rectangle): Boolean {
43 val magnetArea = getMagnetArea()
44 return Intersector.overlaps(magnetArea, rectangle)
45 }
47 @JvmOverloads
48 fun subtract(count: Int = 1) {
49 if (count < 0) {
50 throw IllegalArgumentException("Can't subtract negative amount")
51 }
53 amount -= count
54 }
56 private fun getMagnetArea(): Rectangle {
57 return Rectangle(
58 /* x = */ x - MAGNET_DISTANCE,
59 /* y = */ y - MAGNET_DISTANCE,
60 /* width = */ width + MAGNET_DISTANCE * 2,
61 /* height = */ height + MAGNET_DISTANCE * 2,
62 )
63 }
65 override fun getSaveData(): SaveDataDto.DropSaveData {
66 return SaveDataDto.DropSaveData(
67 version = SAVE_DATA_VERSION,
68 x = x,
69 y = y,
70 width = width,
71 height = height,
72 velocityX = velocity.x,
73 velocityY = velocity.y,
74 itemKey = itemKey,
75 amount = amount,
76 pickedUp = pickedUp
77 )
78 }
80 companion object {
81 private const val SAVE_DATA_VERSION = 1
83 private const val MAGNET_DISTANCE = 8f
85 const val MAGNET_VELOCITY = 256f
86 const val DROP_SIZE = 8f
88 private fun getInitialVelocity(): Vector2 = Vector2(0f, -1f)
90 fun fromSaveData(saveData: SaveDataDto.DropSaveData, gameItemsHolder: GameItemsHolder): Drop {
91 saveData.verifyVersion(SAVE_DATA_VERSION)
93 return Drop(
94 x = saveData.x,
95 y = saveData.y,
96 _item = gameItemsHolder.getItem(saveData.itemKey),
97 _amount = saveData.amount,
98 ).apply {
99 velocity.x = saveData.velocityX
100 velocity.y = saveData.velocityY
101 pickedUp = saveData.pickedUp