Untitled
unknown
plain_text
10 months ago
2.7 kB
11
Indexable
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Catch the Falling Object</title>
<style>
body {
text-align: center;
background-color: lightblue;
}
#gameArea {
width: 400px;
height: 500px;
background: white;
border: 2px solid black;
position: relative;
margin: auto;
overflow: hidden;
}
.basket {
width: 60px;
height: 30px;
background: brown;
position: absolute;
bottom: 10px;
left: 170px;
}
.apple {
width: 20px;
height: 20px;
background: red;
border-radius: 50%;
position: absolute;
}
</style>
</head>
<body>
<h1>Catch the Falling Apples!</h1>
<p>Move the basket with the left and right arrow keys.</p>
<div id="gameArea">
<div class="basket" id="basket"></div>
</div>
<script>
const basket = document.getElementById("basket");
const gameArea = document.getElementById("gameArea");
let score = 0;
document.addEventListener("keydown", (e) => {
let left = parseInt(window.getComputedStyle(basket).getPropertyValue("left"));
if (e.key === "ArrowLeft" && left > 0) {
basket.style.left = left - 20 + "px";
}
if (e.key === "ArrowRight" && left < 340) {
basket.style.left = left + 20 + "px";
}
});
function createApple() {
let apple = document.createElement("div");
apple.classList.add("apple");
apple.style.left = Math.random() * 380 + "px";
gameArea.appendChild(apple);
let fall = setInterval(() => {
let appleTop = parseInt(window.getComputedStyle(apple).getPropertyValue("top") || "0");
let basketLeft = parseInt(window.getComputedStyle(basket).getPropertyValue("left"));
if (appleTop > 470 && appleTop < 500 && Math.abs(basketLeft - parseInt(apple.style.left)) < 40) {
score++;
apple.remove();
clearInterval(fall);
} else if (appleTop > 480) {
apple.remove();
clearInterval(fall);
} else {
apple.style.top = appleTop + 5 + "px";
}
}, 50);
}
setInterval(createApple, 1000);
</script>
</body>
</html>
Editor is loading...
Leave a Comment