4044 游戏:点击消除球球!
<!DOCTYPE html>
<html>
<head>
<title>4044 游戏:点击消除球球!</title>
<style>
body {
margin: 0;
padding: 0;
font-family: sans-serif;
background: #F0F0F0;
}
#game-container {
width: 500px;
height: 500px;
position: relative;
margin: auto;
background: #FFF;
box-shadow: 0px 0px 20px 0px #999;
}
#score {
width: 500px;
height: 30px;
background: #DDD;
text-align: center;
line-height: 30px;
}
#board {
width: 500px;
height: 460px;
background: #999;
}
.ball {
width: 40px;
height: 40px;
position: absolute;
background: #F00;
border-radius: 50%;
}
</style>
</head>
<body>
<div id='game-container'>
<div id='score'></div>
<div id='board'></div>
</div>
<script>
// Game variables
var board = document.getElementById('board');
var score = document.getElementById('score');
var ballCount = 40;
var scoreCount = 0;
var ballArray = [];
<pre><code> // Create balls
for(var i = 0; i < ballCount; i++) {
var ball = document.createElement('div');
ball.className = 'ball';
// Generate random position
var x = Math.random() * (board.offsetWidth - ball.offsetWidth);
var y = Math.random() * (board.offsetHeight - ball.offsetHeight);
ball.style.left = x + 'px';
ball.style.top = y + 'px';
// Add to array and board
ballArray.push(ball);
board.appendChild(ball);
}
// Click event
board.addEventListener('click', function(e) {
// Get click position
var x = e.offsetX;
var y = e.offsetY;
// Check if click on a ball
for(var i = 0; i < ballArray.length; i++) {
var ball = ballArray[i];
// Check position
if (x > ball.offsetLeft &&
x < (ball.offsetLeft + ball.offsetWidth) &&
y > ball.offsetTop &&
y < (ball.offsetTop + ball.offsetHeight)) {
// Remove ball
board.removeChild(ball);
ballArray.splice(i, 1);
// Update score
scoreCount++;
score.innerHTML = 'Score: ' + scoreCount;
// Game over
if (ballArray.length == 0) {
alert('Game Over!');
}
}
}
});
</script>
</code></pre>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/lf3F 著作权归作者所有。请勿转载和采集!