Я делаю небольшую игру на Jetpack Compose (не спрашивайте, почему). У меня есть класс Health, который отвечает за здоровье. Вот его реализация:
class Health(private var maxHealth: Long) {
private var _currentHealth = maxHealth
val currentHealth: Long get() = _currentHealth
val currentMaxHealth: Long get() = maxHealth
fun applyAction(hp: Long, action: Action): Long {
when (action) {
Action.HURT -> _currentHealth -= hp
Action.HEAL -> _currentHealth = max(maxHealth, _currentHealth + hp)
Action.INCREASE_MAX_HP -> maxHealth += hp
}
return currentHealth
}
fun hurtBy(hp: Long): Long {
return applyAction(hp, Action.HURT)
}
fun healBy(hp: Long): Long {
return applyAction(hp, Action.HEAL)
}
fun increaseMaxHpBy(hp: Long): Long {
return applyAction(hp, Action.INCREASE_MAX_HP)
}
enum class Action {
HURT,
HEAL,
INCREASE_MAX_HP
}
}
Как видите, у него есть методы healthBy и HurtBy. Когда я пытаюсь их использовать, состояние врага не обновляется.
//ViewModel Class
private val _state = MutableStateFlow(Storage())
val state = _state.asStateFlow()
private val data get() = _state.value
fun attack() {
var damageToEnemy = data.player.weapon.damage.rollDamage()
if (data.enemy is MarcusKnight) {
damageToEnemy -=
if ((data.enemy as MarcusKnight).defending) (data.enemy.currentArmor * 1.5).toLong()
else data.enemy.currentArmor
}
damageToEnemy = max(damageToEnemy, 0)
data.enemy.currentHealth.hurtBy(damageToEnemy) // {
val playerArmor =
if (data.player.isDefending)
(data.player.armor * 1.5).toLong()
else
data.player.armor
val damage = data.enemy.currentWeapon.damage.rollDamage() - playerArmor
data.player.health.hurtBy(damage) //health changed
updateBattleText("${data.enemy.name} attacks you by $damage")
}
class Player {
var isDefending = false
var weapon: Weapon = HeroSword()
val health: Health = Health(5000)
val armor: Long = 100
private val inventory = mutableListOf()
val playerInventory get() = inventory
fun addItem(item: Item) {
inventory.add(item)
}
fun useItem(item: Item): ConsumableEffect? {
if (item !is Consumable) return null
return if (inventory.remove(item))
item.consume()
else
null
}
fun dropItem(item: Item) {
inventory.remove(item)
}
fun defend() {isDefending = true}
fun stopDefending() { isDefending = false}
}
Подробнее здесь: https://stackoverflow.com/questions/791 ... ate-change
Jetpack Compose: изменение состояния внутреннего класса ⇐ Android
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Jetpack Compose, как перекомпоновать при изменении внутреннего состояния
Anonymous » » в форуме Android - 0 Ответы
- 14 Просмотры
-
Последнее сообщение Anonymous
-