2021-02-20 14:35:23 +00:00
|
|
|
import { playAudio, useStore } from "../store";
|
|
|
|
import sleep from "../utils/sleep";
|
2021-02-18 18:01:16 +00:00
|
|
|
|
|
|
|
type Mutation = {
|
2021-02-19 17:57:02 +00:00
|
|
|
mutation: Object;
|
2021-02-20 14:35:23 +00:00
|
|
|
delay?: number;
|
2021-02-18 18:01:16 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
type EventAudio = {
|
|
|
|
sfx: HTMLAudioElement[];
|
2021-02-20 14:35:23 +00:00
|
|
|
delay?: number;
|
2021-02-18 18:01:16 +00:00
|
|
|
};
|
|
|
|
|
2021-02-20 14:35:23 +00:00
|
|
|
export type GameEvent = {
|
|
|
|
state?: Mutation[];
|
2021-02-18 18:01:16 +00:00
|
|
|
audio?: EventAudio[];
|
|
|
|
effects?: (() => void)[];
|
|
|
|
};
|
|
|
|
|
|
|
|
// the async/await here might be misleading for some, it functions as a setTimeout that fires
|
|
|
|
// multiple async calls without stopping the execution, which is what we want.
|
2021-02-20 14:35:23 +00:00
|
|
|
const handleEvent = (event: GameEvent) => {
|
2021-02-18 18:01:16 +00:00
|
|
|
const setState = useStore.setState;
|
|
|
|
|
2021-02-20 14:35:23 +00:00
|
|
|
const { state, effects, audio } = event;
|
2021-02-18 18:01:16 +00:00
|
|
|
|
2021-02-20 14:35:23 +00:00
|
|
|
if (state)
|
|
|
|
state.forEach(async (mutationData) => {
|
|
|
|
const { delay, mutation } = mutationData;
|
|
|
|
if (delay) await sleep(delay);
|
|
|
|
setState(mutation);
|
|
|
|
});
|
2021-02-18 18:01:16 +00:00
|
|
|
|
|
|
|
if (effects) effects.forEach((effect) => effect());
|
|
|
|
|
2021-02-20 14:35:23 +00:00
|
|
|
if (audio)
|
2021-02-18 18:01:16 +00:00
|
|
|
audio.forEach(async (audio) => {
|
|
|
|
const { delay, sfx } = audio;
|
|
|
|
if (delay) await sleep(delay);
|
|
|
|
sfx.forEach((soundEffect) => playAudio(soundEffect));
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
|
|
|
export default handleEvent;
|