40 lines
1.0 KiB
C#
40 lines
1.0 KiB
C#
using System.Collections.Generic;
|
|
|
|
namespace SemiColinGames {
|
|
public interface IState {
|
|
// Called automatically whenever this state is transitioned to. Should reset whichever
|
|
// state-specific variables need resetting.
|
|
public void Enter();
|
|
|
|
// Returns the name of the new state, or null if we should stay in the same state.
|
|
public string Update(float modelTime, World world);
|
|
}
|
|
|
|
public class FSM {
|
|
readonly Dictionary<string, IState> states;
|
|
IState state;
|
|
|
|
public FSM(string initialStateName, Dictionary<string, IState> states) {
|
|
this.states = states;
|
|
StateName = initialStateName;
|
|
Transition(StateName);
|
|
}
|
|
|
|
public string StateName { get; private set; }
|
|
|
|
public void Update(float modelTime, World world) {
|
|
string newState = state.Update(modelTime, world);
|
|
if (newState != null) {
|
|
Transition(newState);
|
|
}
|
|
}
|
|
|
|
void Transition(string state) {
|
|
StateName = state;
|
|
IState newState = states[state];
|
|
this.state = newState;
|
|
this.state.Enter();
|
|
}
|
|
}
|
|
}
|