2020-03-09 16:22:33 +00:00
|
|
|
|
using System.Collections.Generic;
|
2020-03-05 22:39:17 +00:00
|
|
|
|
|
|
|
|
|
namespace SemiColinGames {
|
2020-03-25 21:04:58 +00:00
|
|
|
|
public interface IState<T> {
|
2020-03-25 19:16:31 +00:00
|
|
|
|
// 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();
|
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.
|
2020-07-15 19:17:19 +00:00
|
|
|
|
public string Update(float modelTime, SneakWorld world, T input);
|
2020-03-05 22:39:17 +00:00
|
|
|
|
}
|
|
|
|
|
|
2020-03-25 21:04:58 +00:00
|
|
|
|
public class FSM<T> {
|
|
|
|
|
readonly Dictionary<string, IState<T>> states;
|
2020-03-05 22:39:17 +00:00
|
|
|
|
|
2020-03-25 21:04:58 +00:00
|
|
|
|
public FSM(string initialStateName, Dictionary<string, IState<T>> states) {
|
2020-03-05 22:39:17 +00:00
|
|
|
|
this.states = states;
|
2020-03-25 19:16:31 +00:00
|
|
|
|
StateName = initialStateName;
|
2020-03-05 22:39:17 +00:00
|
|
|
|
Transition(StateName);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public string StateName { get; private set; }
|
|
|
|
|
|
2020-03-25 21:04:58 +00:00
|
|
|
|
public IState<T> State { get; private set; }
|
|
|
|
|
|
2020-07-15 19:17:19 +00:00
|
|
|
|
public void Update(float modelTime, SneakWorld world, T input) {
|
2020-03-25 21:04:58 +00:00
|
|
|
|
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;
|
2020-03-25 21:04:58 +00:00
|
|
|
|
IState<T> newState = states[state];
|
|
|
|
|
State = newState;
|
|
|
|
|
State.Enter();
|
2020-03-05 22:39:17 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|