Код: Выделить всё
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
}
}
Код: Выделить всё
//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}
}
Код: Выделить всё
abstract class Enemy {
abstract val name: String
abstract val currentWeapon: Weapon
val currentHealth: Health = Health(10000) //
Подробнее здесь: [url]https://stackoverflow.com/questions/79179359/jetpack-compose-internal-class-state-change[/url]