Tennis Ball Game
by SonicBear35115 lines1.8 KB
<!DOCTYPE html>
<html>
<head>
<title>Tennis Ball Game</title>
<style>
body {
margin: 0;
background: #0b6623;
overflow: hidden;
}
canvas {
display: block;
margin: auto;
background: #2e7d32;
}
#score {
position: fixed;
top: 10px;
left: 10px;
color: white;
font-size: 20px;
font-family: Arial;
}
</style>
</head>
<body>
<div id="score">Score: 0</div>
<canvas id="game"></canvas>
<script>
const canvas = document.getElementById("game");
const ctx = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
let score = 0;
let ball = {
x: canvas.width / 2,
y: canvas.height / 2,
r: 15,
vx: 4,
vy: 4
};
let paddle = {
x: canvas.width / 2 - 60,
y: canvas.height - 50,
w: 120,
h: 15
};
document.addEventListener("mousemove", (e) => {
paddle.x = e.clientX - paddle.w / 2;
});
function drawBall() {
ctx.fillStyle = "yellow";
ctx.beginPath();
ctx.arc(ball.x, ball.y, ball.r, 0, Math.PI * 2);
ctx.fill();
}
function drawPaddle() {
ctx.fillStyle = "white";
ctx.fillRect(paddle.x, paddle.y, paddle.w, paddle.h);
}
function update() {
ball.x += ball.vx;
ball.y += ball.vy;
// wall bounce
if (ball.x < 0 || ball.x > canvas.width) ball.vx *= -1;
if (ball.y < 0) ball.vy *= -1;
// paddle hit
if (
ball.y + ball.r > paddle.y &&
ball.x > paddle.x &&
ball.x < paddle.x + paddle.w
) {
ball.vy *= -1;
score++;
document.getElementById("score").innerText = "Score: " + score;
}
// game over
if (ball.y > canvas.height) {
alert("Game Over! Score: " + score);
ball.x = canvas.width / 2;
ball.y = canvas.height / 2;
score = 0;
}
}
function loop() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBall();
drawPaddle();
update();
requestAnimationFrame(loop);
}
loop();
</script>
</body>
</html>Game Source: Tennis Ball Game
Creator: SonicBear35
Libraries: none
Complexity: moderate (115 lines, 1.8 KB)
The full source code is displayed above on this page.
Remix Instructions
To remix this game, copy the source code above and modify it. Add a ARCADELAB header at the top with "remix_of: tennis-ball-game-sonicbear35" to link back to the original. Then publish at arcadelab.ai/publish.