Simple HTML Game - Catch the Ball
<!DOCTYPE html>
<html>
<head>
<title>Simple HTML Game - Catch the Ball</title>
<style>
body {
text-align: center;
background-color: #3b3b3b;
}
<pre><code>#container {
width: 800px;
margin: 0 auto;
}
#game-area {
width: 600px;
height: 600px;
background-color: #fff;
border: 1px solid #000;
margin: 0 auto;
}
</code></pre>
</style>
</head>
<body>
<div id="container">
<h1>Catch the Ball</h1>
<div id="game-area"></div>
</div>
<script>
let gameArea = document.getElementById("game-area");
<pre><code>//Create a ball
let ball = document.createElement("div");
ball.style.width = "50px";
ball.style.height = "50px";
ball.style.backgroundColor = "#000";
ball.style.borderRadius = "25px";
ball.style.position = "absolute";
ball.style.left = "50%";
ball.style.top = "50%";
gameArea.appendChild(ball);
//Create a paddle
let paddle = document.createElement("div");
paddle.style.width = "100px";
paddle.style.height = "20px";
paddle.style.backgroundColor = "#000";
paddle.style.position = "absolute";
paddle.style.left = "50%";
paddle.style.bottom = "20px";
gameArea.appendChild(paddle);
//Create a wall
let wall = document.createElement("div");
wall.style.width = "50px";
wall.style.height = "400px";
wall.style.backgroundColor = "#000";
wall.style.position = "absolute";
wall.style.right = "20px";
wall.style.top = "50px";
gameArea.appendChild(wall);
//Create a score area
let scoreArea = document.createElement("div");
scoreArea.style.width = "200px";
scoreArea.style.height = "50px";
scoreArea.style.position = "absolute";
scoreArea.style.right = "20px";
scoreArea.style.bottom = "20px";
scoreArea.innerHTML = "Score: 0";
gameArea.appendChild(scoreArea);
//Initialise game variables
let score = 0;
let gameOver = false;
//Handle user input
document.addEventListener("keydown", function(e) {
if (e.keyCode == 37) {
//Left arrow
paddle.style.left = paddle.offsetLeft - 10 + "px";
} else if (e.keyCode == 39) {
//Right arrow
paddle.style.left = paddle.offsetLeft + 10 + "px";
}
});
//Game loop
let gameLoop = setInterval(function() {
//Move ball
ball.style.left = ball.offsetLeft + 5 + "px";
ball.style.top = ball.offsetTop + 5 + "px";
//Collision detection
//Wall
if (ball.offsetLeft >= wall.offsetLeft - 50 && ball.offsetTop <= wall.offsetTop + 400) {
gameOver = true;
}
//Paddle
if (ball.offsetLeft >= paddle.offsetLeft - 50 && ball.offsetTop >= paddle.offsetTop - 50) {
score++;
scoreArea.innerHTML = "Score: " + score;
}
//Game over
if (gameOver) {
alert("Game Over!");
clearInterval(gameLoop);
}
}, 20);
</code></pre>
</script>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/lmcp 著作权归作者所有。请勿转载和采集!