Created
October 14, 2021 13:00
-
-
Save hugooliveirad/80489773b1debe271fa1637e185fa06b 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 { createMachine, assign } from "xstate"; | |
type MachineContext = { | |
lives: number; | |
}; | |
type MachineEvent = | |
| { type: "IDLE" } | |
| { type: "WALK" } | |
| { type: "RUN" } | |
| { type: "JUMP" } | |
| { type: "DIE" }; | |
export const FinalDinoMachine = createMachine<MachineContext, MachineEvent>({ | |
id: "DINO_FINAL_MACHINE", | |
initial: "Idle", | |
context: { | |
lives: 3, | |
}, | |
states: { | |
Idle: { | |
on: { WALK: "Walking" }, | |
}, | |
Walking: { | |
on: { | |
IDLE: "Idle", | |
RUN: "Running", | |
}, | |
}, | |
Running: { | |
on: { | |
WALK: "Walking", | |
DIE: "Dead", | |
JUMP: "Jumping", | |
}, | |
}, | |
Jumping: { | |
after: { 1000: { target: "Running" } }, | |
}, | |
Dead: { | |
on: { | |
IDLE: { | |
target: "Idle", | |
cond: (context) => { | |
const hasLivesLeft = context.lives > 0; | |
if (!hasLivesLeft) { | |
alert("You ran out of lives... Refresh the page to play again"); | |
} | |
return hasLivesLeft; | |
}, | |
}, | |
}, | |
invoke: { | |
src: () => Promise.resolve(), | |
onDone: { | |
actions: assign({ | |
lives: (context) => context.lives - 1, | |
}), | |
}, | |
}, | |
}, | |
}, | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment