I am trying to implement a State Machine
into my Android game (note that it is not a game that needs to be constantly redrawn with a UI as it just works using standard Android Activity
structure). I have found this example below of how you can implement a State Machine
with a switch
statement:
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.
}
}
Whilst transitioning my game from the loop below to the State Machine
, I am having issues. If say from this main game Activity
, I launch another Activity
in order to ask the player a question (happens inside playTurn()
), I will then obviously utilise onActivityResult()
and return the player's answer to the main game Activity
. How should I handle the return of the player's answer and allow the code to then continue running in playTurn()
, inside the main playGame()
loop, without breaking the while loop flow? The only way I actually can figure out is by utilising a while loop inside playTurn()
that simply keeps looping whilst the answer is 0 but that seems horrifically wasteful. Thanks in advance, any help is appreciated!
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;
}
}
}