Я делаю небольшую игру на 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
Форум для тех, кто программирует под Android
-
Anonymous
1731404180
Anonymous
Я делаю небольшую игру на 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}
}
Подробнее здесь: [url]https://stackoverflow.com/questions/79179359/jetpack-compose-internal-class-state-change[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия