-
Notifications
You must be signed in to change notification settings - Fork 99
Expand file tree
/
Copy pathuseGameSound.ts
More file actions
43 lines (35 loc) · 1.27 KB
/
useGameSound.ts
File metadata and controls
43 lines (35 loc) · 1.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import { Chess } from "chess.js";
import { PrimitiveAtom, useAtomValue } from "jotai";
import { useEffect, useRef } from "react";
import { soundThemeAtom } from "@/sections/play/states";
export const useGameSound = (gameAtom: PrimitiveAtom<Chess>) => {
const game = useAtomValue(gameAtom);
const soundTheme = useAtomValue(soundThemeAtom);
const previousMoveCount = useRef(game.history().length);
useEffect(() => {
const history = game.history({ verbose: true });
const currentMoveCount = history.length;
if (currentMoveCount === previousMoveCount.current) {
return;
}
previousMoveCount.current = currentMoveCount;
const lastMove = history.at(-1);
if (!lastMove) return;
let soundFile = "Move.mp3";
if (game.isGameOver()) {
if (game.isCheckmate()) {
soundFile = "Checkmate.mp3";
} else if (game.isDraw()) {
soundFile = "Draw.mp3";
} else {
soundFile = "Error.mp3";
}
} else if (game.inCheck()) {
soundFile = "Check.mp3";
} else if (lastMove.captured || lastMove.promotion) {
soundFile = "Capture.mp3";
}
const audio = new Audio(`/sound/${soundTheme}/${soundFile}`);
audio.play().catch((e) => console.error("Error playing sound:", e));
}, [game, soundTheme]);
};