Merge pull request #19 from Neko-Life/feat/move-sound

Feat/move sound
This commit is contained in:
Daniel Bulant 2023-08-04 17:12:55 +02:00 committed by GitHub
commit d7ffafc9d4
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 67 additions and 1 deletions

View file

@ -0,0 +1,34 @@
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;
const handleTrackCanPlay = this.onCanPlay.bind(this);
this.track.addEventListener('canplay', handleTrackCanPlay);
return () => {
if (!this.track) return;
this.track.removeEventListener('canplay', handleTrackCanPlay);
this.offCanPlay();
};
}
}

Binary file not shown.

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 sndLocalMove from "./assets/fx/localMove.wav";
import sndRemoteMove from "./assets/fx/remoteMove.mp3";
export var self: 1 | 2 = 1;
export var twoPlayer: boolean = false;
@ -80,6 +83,7 @@
if(overallState) return;
moves.push({ p: currentPlayer, i, j });
moves = moves;
playMoveSound();
dispatch("move", { i, j, p: currentPlayer });
@ -188,12 +192,40 @@
const duration = DEFAULT_TRANSITION_DURATION;
var moveDelayMultiplier = 1;
const moveSounds = [sndLocalMove, sndRemoteMove].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 winnerWidth = typeof window !== "undefined" ? window.innerWidth : 0;

Binary file not shown.