sneak/Shared/FSM.cs

39 lines
960 B
C#
Raw Normal View History

2020-03-05 22:39:17 +00:00
using System;
using System.Collections.Generic;
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> {
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();
}
}
}