2021-02-20 14:35:23 +00:00
|
|
|
import { playAudio, useStore } from "../store";
|
|
|
|
import sleep from "../utils/sleep";
|
2021-02-22 15:03:43 +00:00
|
|
|
import { GameEvent } from "../types/types";
|
2021-02-18 18:01:16 +00:00
|
|
|
|
|
|
|
// 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;
|