Skip to content

Instantly share code, notes, and snippets.

@hugooliveirad
Created October 14, 2021 13:00
Show Gist options
  • Save hugooliveirad/80489773b1debe271fa1637e185fa06b to your computer and use it in GitHub Desktop.
Save hugooliveirad/80489773b1debe271fa1637e185fa06b to your computer and use it in GitHub Desktop.
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