public interface IState { void Enter(); void Update(); void Exit(); } public class State<T> where T : IState { public delegate void StateAction(T state); public StateAction OnEnter; public StateAction OnUpdate; public StateAction OnExit; public void Enter(T state) { if (OnEnter != null) { OnEnter(state); } } public void Update(T state) { if (OnUpdate != null) { OnUpdate(state); } } public void Exit(T state) { if (OnExit != null) { OnExit(state); } } } public class IdleState : IState { public void Enter() { // Do idle behavior } public void Update() { // Do idle behavior } public void Exit() { // Do idle behavior } } public class WalkingState : IState { public void Enter() { // Do walking behavior } public void Update() { // Do walking behavior } public void Exit() { // Do walking behavior } } public class RunningState : IState { public void Enter() { // Do running behavior } public void Update() { // Do running behavior } public void Exit() { // Do running behavior } } public class StateMachine<T> where T : IState { private Stack<State<T>> stateStack = new Stack<State<T>>(); private T currentState; public void PushState(State<T> newState) { if (currentState != null) { currentState.Exit(); } stateStack.Push(newState); currentState = newState; currentState.Enter(currentState); } public void PopState() { if (stateStack.Count > 0) { currentState.Exit(); stateStack.Pop(); currentState = stateStack.Count > 0 ? stateStack.Peek() : null; if (currentState != null) { currentState.Enter(currentState); } } } public void Update() { if (currentState != null) { currentState.Update(currentState); } } }如何使用,请给出示例代码
时间: 2023-04-05 08:03:42 浏览: 155
这是一个状态机的实现,可以用于游戏开发等领域。使用方法如下:
1.定义状态类,实现IState接口,重写Enter、Update、Exit方法,分别表示进入状态、更新状态、退出状态时的行为。
2.创建StateMachine对象,指定泛型参数为状态类。
3.通过PushState方法将初始状态压入状态栈。
4.在游戏循环中,调用Update方法更新当前状态。
5.根据游戏逻辑,通过PushState和PopState方法切换状态。
示例代码如下:
IdleState idleState = new IdleState();
WalkingState walkingState = new WalkingState();
RunningState runningState = new RunningState();
StateMachine<IState> stateMachine = new StateMachine<IState>();
stateMachine.PushState(idleState);
while (true) {
stateMachine.Update();
// 根据游戏逻辑切换状态
if (playerInput == "walk") {
stateMachine.PushState(walkingState);
} else if (playerInput == "run") {
stateMachine.PushState(runningState);
} else if (playerInput == "stop") {
stateMachine.PopState();
}
}
阅读全文