experiments-monogame/UPWG/UPWG.Core/StateMachine.cs

45 lines
1.1 KiB
C#
Raw Normal View History

2024-09-06 23:47:51 +00:00
using System;
using System.Collections.Generic;
namespace UPWG.Core
{
public class StateMachine<T>
where T : Enum
{
public T CurrentState { get; private set; }
public double TimeInState { get; private set; }
private Dictionary<T, (double, T)> _transitions;
public StateMachine(T initial)
{
CurrentState = initial;
TimeInState = 0;
_transitions = new Dictionary<T, (double, T)>();
}
public void AddTransition(T from, T to, double after = 0)
{
_transitions[from] = (after, to);
}
public void SetState(T newState)
{
CurrentState = newState;
TimeInState = 0;
}
public void Update(double elapsed)
{
TimeInState += elapsed;
if (!_transitions.ContainsKey(CurrentState))
return;
var (maxTime, nextState) = _transitions[CurrentState];
if (TimeInState > maxTime)
{
SetState(nextState);
}
}
}
}