|
| 1 | +const screens = document.querySelectorAll(".screen"); |
| 2 | +const chooseInsectButtons = document.querySelectorAll(".choose-insect-btn"); |
| 3 | +const startButton = document.getElementById("start-btn"); |
| 4 | +const gameContainer = document.getElementById("game-container"); |
| 5 | +const timeElement = document.getElementById("time"); |
| 6 | +const scoreElement = document.getElementById("score"); |
| 7 | +const message = document.getElementById("message"); |
| 8 | +let seconds = 0; |
| 9 | +let score = 0; |
| 10 | +let selectedInsect = {}; |
| 11 | + |
| 12 | +startButton.addEventListener("click", () => screens[0].classList.add("up")); |
| 13 | + |
| 14 | +const increaseScore = () => { |
| 15 | + score++; |
| 16 | + if (score > 19) message.classList.add("visible"); |
| 17 | + scoreElement.innerHTML = `Score: ${score}`; |
| 18 | +}; |
| 19 | + |
| 20 | +const addInsects = () => { |
| 21 | + setTimeout(createInsect, 1000); |
| 22 | + setTimeout(createInsect, 1500); |
| 23 | +}; |
| 24 | + |
| 25 | +const catchInsect = function () { |
| 26 | + increaseScore(); |
| 27 | + this.classList.add("caught"); |
| 28 | + setTimeout(() => this.remove, 2000); |
| 29 | + addInsects(); |
| 30 | +}; |
| 31 | + |
| 32 | +const getRandomLocation = () => { |
| 33 | + const width = window.innerWidth; |
| 34 | + const height = window.innerHeight; |
| 35 | + const x = Math.random() * (width - 200) + 100; |
| 36 | + const y = Math.random() * (height - 200) + 100; |
| 37 | + return { x, y }; |
| 38 | +}; |
| 39 | + |
| 40 | +const createInsect = () => { |
| 41 | + const insect = document.createElement("div"); |
| 42 | + insect.classList.add("insect"); |
| 43 | + const { x, y } = getRandomLocation(); |
| 44 | + insect.style.top = `${y}px`; |
| 45 | + insect.style.left = `${x}px`; |
| 46 | + insect.innerHTML = `<img src="${selectedInsect.src}" |
| 47 | + alt="${selectedInsect.alt}" |
| 48 | + style="transform: rotate(${Math.random() * 360}deg)" />`; |
| 49 | + insect.addEventListener("click", catchInsect); |
| 50 | + gameContainer.appendChild(insect); |
| 51 | +}; |
| 52 | + |
| 53 | +const increaseTime = () => { |
| 54 | + let m = Math.floor(seconds / 60); |
| 55 | + let s = seconds % 60; |
| 56 | + m = m < 10 ? `0${m}` : m; |
| 57 | + s = s < 10 ? `0${s}` : s; |
| 58 | + timeElement.innerHTML = `Time: ${m}:${s}`; |
| 59 | + seconds++; |
| 60 | +}; |
| 61 | + |
| 62 | +const startGame = () => setInterval(increaseTime, 1000); |
| 63 | + |
| 64 | +chooseInsectButtons.forEach((button) => { |
| 65 | + button.addEventListener("click", () => { |
| 66 | + const image = button.querySelector("img"); |
| 67 | + const src = image.getAttribute("src"); |
| 68 | + const alt = image.getAttribute("alt"); |
| 69 | + selectedInsect = { src, alt }; |
| 70 | + screens[1].classList.add("up"); |
| 71 | + setTimeout(createInsect, 1000); |
| 72 | + startGame(); |
| 73 | + }); |
| 74 | +}); |
0 commit comments