SupaLidlGame/State/StateMachine.cs

41 lines
906 B
C#
Raw Normal View History

2023-05-23 00:23:53 -07:00
using Godot;
2023-06-03 18:21:46 -07:00
namespace SupaLidlGame.State;
public abstract partial class StateMachine<T> : Node where T : IState<T>
2023-05-23 00:23:53 -07:00
{
2023-06-03 18:21:46 -07:00
public T CurrentState { get; protected set; }
public abstract T InitialState { get; set; }
public override void _Ready()
2023-05-23 00:23:53 -07:00
{
2023-06-03 18:21:46 -07:00
ChangeState(InitialState);
}
2023-05-23 00:23:53 -07:00
2023-06-03 18:21:46 -07:00
public virtual bool ChangeState(T nextState, bool isProxied = false)
{
if (nextState is null)
{
return false;
}
2023-05-23 00:23:53 -07:00
2023-06-03 18:21:46 -07:00
if (CurrentState is not null)
2023-05-23 00:23:53 -07:00
{
2023-06-03 18:21:46 -07:00
CurrentState.Exit(nextState);
2023-05-23 00:23:53 -07:00
}
2023-06-03 18:21:46 -07:00
CurrentState = nextState;
// if the next state decides it should enter a different state,
// then we enter that different state instead
var nextNextState = nextState.Enter(CurrentState);
if (nextNextState is T t)
2023-05-23 00:23:53 -07:00
{
2023-06-03 18:21:46 -07:00
return ChangeState(t, true);
2023-05-23 00:23:53 -07:00
}
2023-06-03 18:21:46 -07:00
return true;
2023-05-23 00:23:53 -07:00
}
}