File size: 1,056 Bytes
89682f8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
44
45
import { Dice1, Dice2, Dice3, Dice4, Dice5, Dice6 } from "lucide-react";
import { FC, useState } from "react";

const dices = [
  <Dice1 key="dice-1" />,
  <Dice2 key="dice-2" />,
  <Dice3 key="dice-3" />,
  <Dice4 key="dice-4" />,
  <Dice5 key="dice-5" />,
  <Dice6 key="dice-6" />,
];

export const Dice: FC = () => {
  const [click, setClick] = useState(false);
  const [currentNumber, setCurrentNumber] = useState(3);
  const rollDice = () => {
    let rollingTime = 0;
    setClick(true);

    const rollInterval = setInterval(
      () => {
        setCurrentNumber(Math.floor(Math.random() * 6));
        rollingTime += 100;
        // Slow down the rolling
        if (rollingTime >= 1200) {
          clearInterval(rollInterval);
          setClick(false);
        }
      },
      100 - rollingTime / 20,
    );
  };
  return (
    <div
      className={click ? "animate-[shake_1.2s_ease-in-out]" : ""}
      onClick={(event) => {
        event.preventDefault();
        rollDice();
      }}
    >
      {dices[currentNumber]}
    </div>
  );
};