HTML Basketball Click Game: Fun and Simple
<!DOCTYPE html>
<html>
<head>
<title>Click the Basketball Game</title>
<style>
body {
background-color: #F6DDB2;
font-family: Arial, sans-serif;
}
h1 {
color: #FF5733;
text-align: center;
}
#score {
color: #FFC300;
font-size: 24px;
text-align: center;
margin-top: 20px;
}
#gameboard {
width: 500px;
height: 500px;
margin: 0 auto;
position: relative;
background-image: url('https://cdn.pixabay.com/photo/2018/09/24/04/52/background-3697843_960_720.jpg');
background-size: cover;
border: 2px solid #FFC300;
border-radius: 10px;
overflow: hidden;
}
#target {
position: absolute;
width: 50px;
height: 50px;
background-image: url('https://cdn.pixabay.com/photo/2016/03/31/20/51/basketball-1295012_960_720.png');
background-size: contain;
top: 0;
left: 0;
cursor: pointer;
}
</style>
</head>
<body>
<h1>Click the basketballs!</h1>
<div id='score'>Score: 0</div>
<div id='gameboard'>
<div id='target'></div>
</div>
<pre><code><script>
let score = 0;
const scoreBoard = document.querySelector('#score');
const target = document.querySelector('#target');
// function to generate random position for target
function randomPosition() {
const boardWidth = document.querySelector('#gameboard').clientWidth;
const boardHeight = document.querySelector('#gameboard').clientHeight;
const targetWidth = target.clientWidth;
const targetHeight = target.clientHeight;
const maxX = boardWidth - targetWidth;
const maxY = boardHeight - targetHeight;
const randomX = Math.floor(Math.random() * maxX);
const randomY = Math.floor(Math.random() * maxY);
target.style.top = `${randomY}px`;
target.style.left = `${randomX}px`;
}
// function to handle click on target
function handleClick() {
score++;
scoreBoard.textContent = 'Score: ' + score;
randomPosition();
}
// add event listener to target
target.addEventListener('click', handleClick);
// generate random position for target on page load
randomPosition();
</script>
</code></pre>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/ls7f 著作权归作者所有。请勿转载和采集!