所以,我正在使用Unity中的一个项目(使用C#脚本,虽然这个问题主要与语言无关),而且我用一个非常简单的状态机代表各种游戏状态。 / p>
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-elses来检测我所处的状态。
我可以单独制作&#34; HandleGameCommand()&#34;每个状态的方法 - HandleGameCommand-Initialized(),HandleGameCommand-ShowBriefing(),但这似乎很草率。
我可以创建一个Dictionary<State, List<string>>
,并预先建立一个列表,列出每个州要处理的命令。
是否有一个坚实的模式来做我想做的事情?