aboutsummaryrefslogtreecommitdiffhomepage
path: root/frontend/app/components/Gaming/Score.tsx
blob: ee23a6cc4f5ddde5fd68650ebf5e1f4bce11b764 (plain)
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
import { useEffect, useState } from "react";

type Props = {
	status: string | null;
	score: number | null;
};

export default function Score({ status, score }: Props) {
	const [randomScore, setRandomScore] = useState<number | null>(null);

	useEffect(() => {
		if (status !== "running") {
			return;
		}

		const intervalId = setInterval(() => {
			const maxValue = Math.pow(10, String(score ?? 100).length) - 1;
			const minValue = Math.pow(10, String(score ?? 100).length - 1);
			const randomValue =
				Math.floor(Math.random() * (maxValue - minValue + 1)) + minValue;
			setRandomScore(randomValue);
		}, 50);

		return () => {
			clearInterval(intervalId);
		};
	}, [status, score]);

	const displayScore = status === "running" ? randomScore : score;

	return (
		<span className={status === "running" ? "animate-pulse" : ""}>
			{displayScore}
		</span>
	);
}