2020-03-09 16:22:33 +00:00
|
|
|
|
using System.Collections.Generic;
|
2020-03-05 22:39:17 +00:00
|
|
|
|
|
|
|
|
|
namespace SemiColinGames {
|
2020-03-06 17:16:33 +00:00
|
|
|
|
public interface IState<T> {
|
2020-03-05 22:39:17 +00:00
|
|
|
|
public void Enter();
|
2020-03-06 19:20:17 +00:00
|
|
|
|
|
|
|
|
|
// 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
|
|
|
|
}
|
|
|
|
|
|
2020-03-06 17:16:33 +00:00
|
|
|
|
public class FSM<T> {
|
2020-03-09 16:48:10 +00:00
|
|
|
|
readonly Dictionary<string, IState<T>> states;
|
2020-03-06 17:16:33 +00:00
|
|
|
|
IState<T> state;
|
2020-03-05 22:39:17 +00:00
|
|
|
|
|
2020-03-06 17:16:33 +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; }
|
|
|
|
|
|
2020-03-06 17:28:58 +00:00
|
|
|
|
public void Update(T obj, float modelTime, World world) {
|
2020-03-06 19:20:17 +00:00
|
|
|
|
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;
|
2020-03-06 17:16:33 +00:00
|
|
|
|
IState<T> newState = states[state];
|
2020-03-05 22:39:17 +00:00
|
|
|
|
this.state = newState;
|
|
|
|
|
this.state.Enter();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|