FSM now takes a type parameter so that we can use FSM with other classes.

This commit is contained in:
Colin McMillen 2020-03-06 12:16:33 -05:00
parent 08091106ea
commit 1b124f84df
2 changed files with 13 additions and 13 deletions

View File

@ -2,17 +2,17 @@
using System.Collections.Generic;
namespace SemiColinGames {
public interface IState {
public interface IState<T> {
public void Enter();
public string? Update(NPC npc, float modelTime, AABB[] collisionTargets);
public string? Update(T obj, float modelTime, AABB[] collisionTargets);
}
public class FSM {
public class FSM<T> {
float timeInState = 0f;
Dictionary<string, IState> states;
IState state;
Dictionary<string, IState<T>> states;
IState<T> state;
public FSM(Dictionary<string, IState> states, string initial) {
public FSM(Dictionary<string, IState<T>> states, string initial) {
this.states = states;
StateName = initial;
Transition(StateName);
@ -20,9 +20,9 @@ namespace SemiColinGames {
public string StateName { get; private set; }
public void Update(NPC npc, float modelTime, AABB[] collisionTargets) {
public void Update(T obj, float modelTime, AABB[] collisionTargets) {
timeInState += modelTime;
string? newState = state.Update(npc, modelTime, collisionTargets);
string? newState = state.Update(obj, modelTime, collisionTargets);
if (newState != null) {
Transition(newState);
}
@ -32,7 +32,7 @@ namespace SemiColinGames {
Debug.WriteLine("{0} -> {1} @ {2}", StateName, state, timeInState);
timeInState = 0f;
StateName = state;
IState newState = states[state];
IState<T> newState = states[state];
this.state = newState;
this.state.Enter();
}

View File

@ -3,7 +3,7 @@ using Microsoft.Xna.Framework.Graphics;
using System.Collections.Generic;
namespace SemiColinGames {
class IdleState : IState {
class IdleState : IState<NPC> {
float timeInState = 0;
public void Enter() {
@ -20,7 +20,7 @@ namespace SemiColinGames {
}
}
class RunState : IState {
class RunState : IState<NPC> {
public void Enter() {}
public string? Update(NPC npc, float modelTime, AABB[] collisionTargets) {
@ -50,11 +50,11 @@ namespace SemiColinGames {
private const int spriteHeight = 81;
private const int spriteCenterYOffset = 2;
private FSM fsm;
private FSM<NPC> fsm;
public NPC(Point position) {
Position = position;
fsm = new FSM(new Dictionary<string, IState> {
fsm = new FSM<NPC>(new Dictionary<string, IState<NPC>> {
{ "idle", new IdleState() },
{ "run", new RunState() }
}, "run");