sneak/Shared/FSM.cs

41 lines
1.1 KiB
C#
Raw Normal View History

2020-03-09 16:22:33 +00:00
using System.Collections.Generic;
2020-03-05 22:39:17 +00:00
namespace SemiColinGames {
public interface IState<T> {
// Called automatically whenever this state is transitioned to. Should reset whichever
// state-specific variables need resetting.
2020-03-05 22:39:17 +00:00
public void Enter();
// Returns the name of the new state, or null if we should stay in the same state.
public string Update(float modelTime, SneakWorld world, T input);
2020-03-05 22:39:17 +00:00
}
public class FSM<T> {
readonly Dictionary<string, IState<T>> states;
2020-03-05 22:39:17 +00:00
public FSM(string initialStateName, Dictionary<string, IState<T>> states) {
2020-03-05 22:39:17 +00:00
this.states = states;
StateName = initialStateName;
2020-03-05 22:39:17 +00:00
Transition(StateName);
}
public string StateName { get; private set; }
public IState<T> State { get; private set; }
public void Update(float modelTime, SneakWorld world, T input) {
string newState = State.Update(modelTime, world, input);
2020-03-05 22:39:17 +00:00
if (newState != null) {
Transition(newState);
}
}
void Transition(string state) {
StateName = state;
IState<T> newState = states[state];
State = newState;
State.Enter();
2020-03-05 22:39:17 +00:00
}
}
}