Refactor stats
This commit is contained in:
59
Zennysoft.Game.Ma/src/Components/HealthComponent.cs
Normal file
59
Zennysoft.Game.Ma/src/Components/HealthComponent.cs
Normal file
@@ -0,0 +1,59 @@
|
||||
using Chickensoft.Collections;
|
||||
using Chickensoft.Serialization;
|
||||
using System;
|
||||
using Zennysoft.Ma.Adapter;
|
||||
|
||||
namespace Zennysoft.Game.Ma;
|
||||
|
||||
public class HealthComponent : IHealthComponent
|
||||
{
|
||||
[Save("current_hp")]
|
||||
public IAutoProp<int> CurrentHP => _currentHP;
|
||||
|
||||
[Save("maximum_hp")]
|
||||
public IAutoProp<int> MaximumHP => _maximumHP;
|
||||
|
||||
private readonly AutoProp<int> _currentHP;
|
||||
|
||||
private readonly AutoProp<int> _maximumHP;
|
||||
|
||||
public event Action? HealthReachedZero;
|
||||
public event Action? DamageTaken;
|
||||
|
||||
public bool AtFullHealth => CurrentHP.Value == MaximumHP.Value;
|
||||
|
||||
public HealthComponent(int initialHP)
|
||||
{
|
||||
_maximumHP = new AutoProp<int>(initialHP);
|
||||
_currentHP = new AutoProp<int>(initialHP);
|
||||
}
|
||||
|
||||
public void Heal(int healAmount)
|
||||
{
|
||||
var cappedAmount = Math.Min(healAmount + _currentHP.Value, _maximumHP.Value);
|
||||
_currentHP.OnNext(cappedAmount);
|
||||
}
|
||||
|
||||
public void Damage(int damageAmount)
|
||||
{
|
||||
var cappedAmount = Math.Max(_currentHP.Value - damageAmount, 0);
|
||||
_currentHP.OnNext(cappedAmount);
|
||||
|
||||
if (cappedAmount == 0)
|
||||
HealthReachedZero?.Invoke();
|
||||
else
|
||||
DamageTaken?.Invoke();
|
||||
}
|
||||
|
||||
public void SetHealth(int health)
|
||||
{
|
||||
var cappedAmount = Math.Min(health, _maximumHP.Value);
|
||||
_currentHP.OnNext(cappedAmount);
|
||||
}
|
||||
|
||||
public void RaiseMaximumHP(int raiseAmount)
|
||||
{
|
||||
_maximumHP.OnNext(raiseAmount);
|
||||
Heal(raiseAmount);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user