因此,我正在使用 Unity 开发一个项目(使用 C# 脚本,尽管问题很大程度上与语言无关),并且我用一个非常简单的状态机来表示各种游戏状态。
public enum State
{
Initialized,
ShowBriefing,
Running,
Quitting
};
在我的 GameStateController 类中,我处理来自网络的一些命令,假设它看起来像这样:
if (gameState.CurrentState == GameState.State.Initialized) {
HandleGameCommand ();
NetworkInterface.Instance.HandlePresenceMessages ();
} else if (gameState.CurrentState == GameState.State.ShowBriefing) {
HandleGameCommand ();
NetworkInterface.Instance.HandlePresenceMessages ();
} else if (gameState.CurrentState == GameState.State.Running) {
HandleGameCommand ();
if (lookTargets.Count > 0) {
// do some stuff
}
NetworkInterface.Instance.HandlePresenceMessages ();
} else if (gameState.CurrentState == GameState.State.Quitting) {
NetworkInterface.Instance.Close ();
Application.Quit ();
}
HandleGameCommand 通常看起来像这样:
Messages.GameCommand gameCommand = NetworkInterface.Instance.NextMessage<Messages.GameCommand> ("game.command");
if (gameCommand != null) {
switch (gameCommand.type) {
case "show-briefing":
// Show the mission briefing. Currently a NOOP.
if (gameState.CurrentState == GameState.State.Initialized) {
gameState.CurrentState = GameState.State.ShowBriefing;
}
// Do some other stuff
break;
case "run":
// Set the gameState to Running and respond
gameState.CurrentState = GameState.State.Running;
// Do some other stuff
break;
case "detect-look-at":
if (gameState.CurrentState == GameState.State.Running) {
lookTargets.Add (json ["target"] as string);
}
// And so on
我的问题是 - 有什么更好的方法来做到这一点?我喜欢有一个统一的 GameCommand 处理程序,但我不喜欢我必须在 GameCommand 处理程序中使用 if-else 来检测我所处的状态。
我可以为每个状态创建单独的“HandleGameCommand()”方法——HandleGameCommand-Initialized()、HandleGameCommand-ShowBriefing(),但这似乎很草率。
我可以创建一个Dictionary<State, List<string>>
, 并预先构建一个列表,其中列出了要为每个状态处理哪些命令。
是否有一个可靠的模式来做我想做的事情?