sneak/Shared/FSM.cs

41 lines
1.0 KiB
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();
public string? Update(T obj, float modelTime, World world);
2020-03-05 22:39:17 +00:00
}
public class FSM<T> {
2020-03-05 22:39:17 +00:00
float timeInState = 0f;
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) {
2020-03-05 22:39:17 +00:00
timeInState += modelTime;
string? newState = state.Update(obj, modelTime, world);
2020-03-05 22:39:17 +00:00
if (newState != null) {
Transition(newState);
}
}
void Transition(string state) {
Debug.WriteLine("{0} -> {1} @ {2}", StateName, state, timeInState);
timeInState = 0f;
StateName = state;
IState<T> newState = states[state];
2020-03-05 22:39:17 +00:00
this.state = newState;
this.state.Enter();
}
}
}