sneak/Shared/FSM.cs

38 lines
955 B
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> {
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(T obj, float modelTime, World world);
2020-03-05 22:39:17 +00:00
}
public class FSM<T> {
readonly Dictionary<string, IState<T>> states;
IState<T> state;
2020-03-05 22:39:17 +00:00
public FSM(Dictionary<string, IState<T>> states, string initial) {
2020-03-05 22:39:17 +00:00
this.states = states;
StateName = initial;
Transition(StateName);
}
public string StateName { get; private set; }
public void Update(T obj, float modelTime, World world) {
string newState = state.Update(obj, modelTime, world);
2020-03-05 22:39:17 +00:00
if (newState != null) {
Transition(newState);
}
}
void Transition(string state) {
StateName = state;
IState<T> newState = states[state];
2020-03-05 22:39:17 +00:00
this.state = newState;
this.state.Enter();
}
}
}