Created
January 20, 2019 17:01
-
-
Save hugozap/ca2550f71178cddbcec1913f066087d8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as states from './enumMatchStates' | |
/** | |
* Simple State machine in charge of updating the | |
* current match state. | |
* This state machine is used to drive the UI | |
*/ | |
const transitions = { | |
START:'start', | |
NEXT_MOVE:'nextMove', | |
FINISH: 'finish' | |
} | |
/** | |
* Function that returns a new state machine | |
* with the game transition rules | |
*/ | |
function createMachine(initialState=states.CAPTURE_PLAYERS_INFO) { | |
return new StateMachine(initialState, { | |
[states.CAPTURE_PLAYERS_INFO]: { | |
[transitions.START]: states.WAITING_MOVE | |
}, | |
[states.WAITING_MOVE]: { | |
[transitions.NEXT_MOVE]: states.WAITING_MOVE, | |
[transitions.FINISH]: states.FINISHED | |
}, | |
[states.FINISHED]: { | |
[transitions.START]: states.CAPTURE_PLAYERS_INFO | |
} | |
}) | |
} | |
/** | |
* Simple state machine, transitions from one state to another using emit(transitionName) | |
* I started using the library nanostate, but it doesn't build properly with create-react-app | |
* so had to hack this | |
*/ | |
class StateMachine { | |
constructor(initialState, transitions) { | |
this.emit = this.emit.bind(this); | |
this.state = initialState; | |
this.transitions = transitions; | |
} | |
emit(transition) { | |
const stateTransitions = this.transitions[this.state]; | |
if(stateTransitions && stateTransitions[transition]) { | |
this.state = stateTransitions[transition]; | |
return this.state | |
} | |
else { | |
throw new Error('Invalid transition'); | |
} | |
} | |
} | |
export {createMachine, transitions} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment