我正在尝试在我的Android游戏中实现State Machine
(请注意,这不是一个需要不断重新绘制UI的游戏,因为它只能使用标准的Android Activity
结构)。我在下面找到了如何使用State Machine
语句实现switch
的示例:
main() {
while(true) {
collectInput(); // deal with common code for filling in keyboard queues, determining mouse positions, etc.
preBookKeeping(); // do any other work that needs constant ticks, like updating streaming/sound/physics/networking receives, etc.
runLogic(); // see below
postBookKeeping(); // again any stuff that needs ticking, but would want to take into account what happened in runLogic this frame, e.g. animation/particles/networking transmit, etc
drawEverything(); // any actual rendering actions you need to take
}
}
runLogic() {
// this is where you actually have a state machine
switch (state) {
case WaitingForInput:
// look at the collected input and see if any of it is actionable
case WaitingForOpponent:
// look at the input and warn the player that they are doing stuff that isn't going to work right now e.g. a "It's not your turn!" notification.
// otherwise, use input to do things that might be valid when it's not the player's turn, like pan around the map.
case etc:
// a real game would have a ton more actual states, including transition states, start/end/options screens, etc.
}
}
虽然将我的游戏从下面的循环过渡到State Machine
,但我遇到了问题。如果从主要游戏Activity
说出来,我会启动另一个Activity
以向玩家提问(发生在playTurn()
内),然后我会明显使用onActivityResult()
并返回玩家对主游戏Activity
的回答。我应该如何处理播放器答案的返回并允许代码继续在主playTurn()
循环内的playGame()
中运行,而不会破坏while循环流?我实际可以理解的唯一方法是在playTurn()
内使用while循环,它只是保持循环,而答案是0,但这似乎是非常浪费的。在此先感谢,任何帮助表示赞赏!
public void playGame() {
initialise();
boolean finished = false;
while (!finished) {
playTurn();
// Check if there is a winner after each turn is played
boolean winner = winner();
if (winner) {
finished = true;
}
}
}