SupaLidlGame/State/StateMachine.cs

54 lines
1.3 KiB
C#
Raw Normal View History

2023-05-23 00:23:53 -07:00
using Godot;
2023-07-23 23:39:20 -07:00
using SupaLidlGame.Extensions;
2023-05-23 00:23:53 -07:00
2023-06-03 18:21:46 -07:00
namespace SupaLidlGame.State;
2023-07-21 02:54:13 -07:00
public abstract partial class StateMachine<T> : Node where T : Node, 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-07-21 02:54:13 -07:00
// NOTE: proxied states can call Exit() more than once
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-07-21 02:54:13 -07:00
var previousState = CurrentState;
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
2023-07-21 02:54:13 -07:00
var nextNextState = nextState.Enter(previousState);
2023-06-03 18:21:46 -07:00
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
}
2023-07-23 23:39:20 -07:00
/// <summary>
/// Changes the current state to a state of type U which must inherit from T.
/// </summary>
public bool ChangeState<U>(out U state) where U : T
{
state = this.FindChildOfType<U>();
return ChangeState(state);
}
2023-05-23 00:23:53 -07:00
}