Whack a mole

DEMO

Score: 0

WhackAMole.jsx

const grid = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
];

const WhackAMole = () => {
  const [score, setScore] = useState(0);
  const [coordinates, setCoordinates] = useState([0, 0]);

  useEffect(() => {
    const intervalId = setInterval(() => {
      setCoordinates((coord) => {
        let newCoords = generateRand();
        // generate unique random coordinates
        while (newCoords[0] === coord[0] && newCoords[1] === coord[1]) 
          newCoords = generateRand();

        return newCoords;
      });
    }, 580);

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

  const handleWhack = (rowI, colI) => {
    // check if correct coordinates are hit
    console.log(rowI + ":" + colI);
    if (rowI === coordinates[0] && colI === coordinates[1]) {
      play();
      setScore((score) => score + 1);
    }
  };

  return (
    <>
      {grid.map((row, rowI) => (
        <GridCont key={row}>
          {row.map((col, colI) => (
            <Hole
              key={col}
              onMouseDown={() => handleWhack(rowI, colI)}
            >
              {rowI === coordinates[0] && colI === coordinates[1] && (
                <Mole key={row + "-" + col} />
              )}
            </Hole>
          ))}
        </GridCont>
      ))}
      <p>Score: {score}</p>
    </>
  );
};

export default WhackAMole;

const generateRand = () => {
  const randRow = Math.floor(Math.random() * 3);
  const randCol = Math.floor(Math.random() * 3);
  return [randRow, randCol];
};

Note: Code snippets do not include styling details unless they are the focus of the exercise.

Copyright © 2022 Explore React