Simple HTML Game: Bounce the Ball!

This tutorial shows you how to create a simple game using HTML, CSS, and JavaScript. The game involves a ball bouncing around the screen and a paddle that you control to keep the ball from falling.

Game Code

<!DOCTYPE html>
<html>
<head>
	<title>Simple HTML Game</title>
	<style>
	body {
		background-color: #f5f5f5;
	}
	
	#game {
		width: 500px;
		height: 500px;
		background-color: #fff;
		border: 1px solid #000;
		position: relative;
	}
	
	#ball {
		width: 50px;
		height: 50px;
		background-color: #000;
		border-radius: 50%;
		position: absolute;
		top: 225px;
		left: 225px;
	}
	
	#paddle {
		width: 100px;
		height: 10px;
		background-color: #000;
		position: absolute;
		bottom: 10px;
		left: 200px;
	}
	</style>
</head>
<body>
	<div id='game'>
		<div id='ball'></div>
		<div id='paddle'></div>
	</div>
	<script>
		var ball = document.getElementById('ball');
		var paddle = document.getElementById('paddle');
		
		var x = 225;
		var y = 225;
		var dx = 5;
		var dy = 5;
		
		function moveBall() {
			x += dx;
			y += dy;
			
			if (x + dx > 475 || x + dx < 25) {
				dx = -dx;
			}
			
			if (y + dy < 25) {
				dy = -dy;
			} else if (y + dy > 475) {
				if (x > parseInt(paddle.style.left) && x < parseInt(paddle.style.left) + 100) {
					dy = -dy;
				} else {
					alert('Game Over');
					clearInterval(interval);
				}
			}
			
			ball.style.left = x + 'px';
			ball.style.top = y + 'px';
		}
		
		function movePaddle(e) {
			if ((e.clientX - 50) > 0 && (e.clientX + 50) < 500) {
				paddle.style.left = (e.clientX - 50) + 'px';
			}
		}
		
		var interval = setInterval(moveBall, 50);
		
		document.addEventListener('mousemove', movePaddle, false);
	</script>
</body>
</html>

How to Play

  1. Move your mouse left and right to control the paddle at the bottom of the screen.
  2. Bounce the ball off the paddle to keep it from falling.
  3. Game Over: If the ball hits the bottom of the screen without hitting the paddle, the game ends.

Try It Out!

Copy and paste the code into an HTML file (e.g., game.html) and open it in your web browser. Enjoy!

Enhancements

Want to make the game more challenging or interesting? Consider adding some of these enhancements:

  • Multiple levels: Increase the ball's speed or add more obstacles as the game progresses.
  • Score keeping: Track how many times you successfully bounce the ball.
  • Sound effects: Add sounds for bounces and game over.
  • Graphics: Use images or animations to make the game more visually appealing.
Simple HTML Game: Bounce the Ball!

原文地址: https://www.cveoy.top/t/topic/lm9O 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录