2020-03-05 22:39:17 +00:00
|
|
|
|
using System;
|
|
|
|
|
using System.Collections.Generic;
|
|
|
|
|
|
|
|
|
|
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 17:28:58 +00:00
|
|
|
|
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-05 22:39:17 +00:00
|
|
|
|
float timeInState = 0f;
|
2020-03-06 17:16:33 +00:00
|
|
|
|
Dictionary<string, IState<T>> states;
|
|
|
|
|
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-05 22:39:17 +00:00
|
|
|
|
timeInState += modelTime;
|
2020-03-06 17:28:58 +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) {
|
|
|
|
|
Debug.WriteLine("{0} -> {1} @ {2}", StateName, state, timeInState);
|
|
|
|
|
timeInState = 0f;
|
|
|
|
|
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();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|