Simple HTML Egg Catching Game: Play Now!
<html>
<head>
<title>The Egg Game</title>
<style>
body {
background-color: #f2f2f2;
font-family: sans-serif;
}
.egg {
width: 50px;
height: 50px;
background-image: url('https://image.flaticon.com/icons/svg/226/226745.svg');
background-repeat: no-repeat;
position: absolute;
}
</style>
</head>
<body>
<h1>The Egg Game</h1>
<pre><code><p>Your mission is to collect as many eggs as you can in one minute!</p>
<button id="startButton">Start the Game</button>
<script>
// Collect the eggs
let eggs = document.getElementsByClassName('egg');
let totalEggs = 0;
// Get a reference to the start button
let startButton = document.getElementById('startButton');
// Listen for the button to be clicked
startButton.addEventListener('click', startGame);
// Start the game on a timer
function startGame() {
let timer = setInterval(makeEggs, 1000);
let counter = 60;
// Count down from 60 seconds
function countDown() {
counter--;
// Make the text in the button equal to the current count
startButton.innerText = counter;
// When the count reaches 0, the game is over
if (counter === 0) {
clearInterval(timer);
alert("Time's up! You collected " + totalEggs + " eggs!");
startButton.innerText = "Play Again";
totalEggs = 0;
}
}
// Create an egg every second
function makeEggs() {
// Create a new egg
let egg = document.createElement('div');
egg.className = "egg";
document.body.appendChild(egg);
// Make the egg move
let xPos = Math.floor(Math.random() * window.innerWidth);
let yPos = Math.floor(Math.random() * window.innerHeight);
egg.style.left = xPos + "px";
egg.style.top = yPos + "px";
// Listen for the egg to be clicked
egg.addEventListener('click', eggClicked);
// Count the eggs
countDown();
}
// When the egg is clicked, remove it and increase the count
function eggClicked() {
this.remove();
totalEggs++;
}
}
</script>
</code></pre>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/lntT 著作权归作者所有。请勿转载和采集!