add move sound

This commit is contained in:
Neko-Life 2023-07-23 09:49:07 +07:00
parent 9e7092a0f6
commit 8b130113ee
4 changed files with 65 additions and 1 deletions

View file

@ -0,0 +1,32 @@
export default class GameAudio {
track: HTMLAudioElement | undefined | null;
canPlay: boolean = false;
constructor(url?: string) {
if (url?.length) this.track = new Audio(url);
}
setCanPlay(state: boolean) {
this.canPlay = state;
}
onCanPlay(ev: Event) {
this.setCanPlay(true);
}
offCanPlay() {
this.setCanPlay(false);
}
onMount() {
if (!this.track) return;
this.track.addEventListener('canplay', this.onCanPlay.bind(this));
return () => {
if (!this.track) return;
this.track.removeEventListener('canplay', this.onCanPlay.bind(this));
this.offCanPlay();
};
}
}

Binary file not shown.

View file

@ -5,6 +5,9 @@
import Move from "./move.svelte";
import { DEFAULT_TRANSITION_DURATION } from "./config";
import BackButton from "./backButton.svelte";
import GameAudio from "./GameAudio";
import sndMove1 from "./assets/fx/jump.wav";
import sndMove2 from "./assets/fx/accomplished.wav";
export var self: 1 | 2 = 1;
export var twoPlayer: boolean = false;
@ -72,6 +75,7 @@
if(overallState) return;
moves.push({ p: currentPlayer, i, j });
moves = moves;
playMoveSound();
dispatch("move", { i, j, p: currentPlayer });
@ -177,12 +181,40 @@
const duration = DEFAULT_TRANSITION_DURATION;
var moveDelayMultiplier = 1;
const moveSounds = [sndMove1, sndMove2].map(src => new GameAudio(src));
function playMoveSound() {
const track = moveSounds[currentPlayer - 1];
if (track.track && track.canPlay)
track.track.play();
}
function playRandomMoveSound() {
const playableTracks: GameAudio[] = [];
for (const ga of moveSounds)
if (ga.canPlay) playableTracks.push(ga);
if (!playableTracks.length) return;
const rand = Math.floor(Math.random() * playableTracks.length);
const track = playableTracks[rand];
if (track.track) track.track.play();
}
onMount(() => {
let i = setTimeout(() => {
moveDelayMultiplier = 0;
}, duration * moveDelayMultiplier);
return () => clearTimeout(i);
const cleanupFns = moveSounds.map(ga => ga.onMount());
return () => {
clearTimeout(i);
cleanupFns.every(fn => fn ? fn() : null);
};
});
let innerWidth = typeof window !== "undefined" ? window.innerWidth : 0;