mole.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. const cursor = document.querySelector('.cursor');
  2. const holes = [...document.querySelectorAll('.hole')];
  3. const scoreEl = document.querySelector('.score span');
  4. let score = 0;
  5. const sound = new Audio('./img/assets_smash.mp3');
  6. function run() {
  7. const i = Math.floor(Math.random() * holes.length);
  8. const hole = holes[i];
  9. let timer = null;
  10. const img = document.createElement('img');
  11. img.classList.add('mole');
  12. img.src = './img/mole.png';
  13. img.addEventListener('click', () => {
  14. score += 10;
  15. sound.play();
  16. scoreEl.textContent = score;
  17. img.src = './img/mole-whacked.png';
  18. clearTimeout(timer);
  19. setTimeout(() => {
  20. hole.removeChild(img);
  21. run();
  22. }, 500);
  23. });
  24. hole.appendChild(img);
  25. timer = setTimeout(() => {
  26. hole.removeChild(img);
  27. run();
  28. }, 1100);
  29. }
  30. run();
  31. window.addEventListener('mousemove', (e) => {
  32. cursor.style.top = e.pageY + 'px';
  33. cursor.style.left = e.pageX + 'px';
  34. });
  35. window.addEventListener('mousedown', () => {
  36. cursor.classList.add('active');
  37. });
  38. window.addEventListener('mouseup', () => {
  39. cursor.classList.remove('active');
  40. });