Я пытаюсь расширить уже существующий проект JavaScript, который я кодировал, добавив счетчик очков в простую игру, где вы управляете GIF-изображением с помощью клавиш со стрелками и собираете монету, которая случайно появляется на странице. Мои попытки пока не увенчались успехом.
HTML код:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Coin Game Starter</title>
<link rel="stylesheet" href="app.css">
</head>
<body>
<h1 id= "scoreboard">0</h1>
<img id="player" src="https://media.tenor.com/images/0791eb3858075aca85eed5ecfe08c778/tenor.gif" alt="">
<img id="coin" src="coin.gif" alt="">
<script src="app.js"></script>
</body>
</html>
JS код:
function isTouching(a, b) {
const aRect = a.getBoundingClientRect();
const bRect = b.getBoundingClientRect();
return !(
aRect.top + aRect.height < bRect.top ||
aRect.top > bRect.top + bRect.height ||
aRect.left + aRect.width < bRect.left ||
aRect.left > bRect.left + bRect.width
);
}
const avatar = document.querySelector('#player')
const coin = document.querySelector('#coin')
window.addEventListener('keyup', function(e){
if(e.key === 'ArrowDown') {
const currTop = extractPos (avatar.style.top)
avatar.style.top = `${currTop + 50}px`
}
else if (e.key === 'ArrowUp'){
const currTop = extractPos (avatar.style.top)
avatar.style.top = `${currTop - 50}px`
}
else if (e.key === 'ArrowRight'){
const currLeft = extractPos (avatar.style.left)
avatar.style.left = `${currLeft + 50}px`
avatar.style.transform = 'scale(1,1)'
}
else if (e.key === 'ArrowLeft'){
const currLeft = extractPos (avatar.style.left)
avatar.style.left = `${currLeft - 50}px`
avatar.style.transform = 'scale(-1,1)'
}
if(isTouching(avatar, coin)) moveCoin ()
});
const moveCoin = () => {
const x = Math.floor(Math.random() * window.innerWidth);
const y = Math.floor(Math.random() * window.innerHeight);
coin.style.top = `${y}px`;
coin.style.left = `${x}px`;
}
const extractPos = (pos) => {
if(!pos) return 0
return parseInt(pos.slice(0,-2))
}
const score = document.getElementById('scoreboard')
const coinScore = score
function scoreUp () {
if (isTouching){
score ++
}
score.textContent = score
}
В нижней части страницы js показано, где я пытался написать функцию, которая заставляет счет увеличиваться при захвате монеты игроком