Simple HTML Ping Pong Game - Play Now!
<html>
<head>
<title> Ping Pong Game </title>
</head>
<body>
<h1> Ping Pong Game </h1>
<div>
<div id='player1' style='padding-left: 20px; float: left; width:20px; height:100px; background: #00f;'></div>
<div id='player2' style='padding-right: 20px; float: right; width:20px; height:100px; background: #f00;'></div>
<div style='clear: both;'></div>
<div id='ball' style='position: absolute; left: 50%; top: 50%; width:20px; height:20px; background: #000;'></div>
</div>
<script>
var player1 = document.getElementById('player1');
var player2 = document.getElementById('player2');
var ball = document.getElementById('ball');
var speedX = 1;
var speedY = 1;
var score1 = 0;
var score2 = 0;
var maxScore = 10;
document.body.addEventListener('keydown', function(e) {
if (e.keyCode == 38) {
player1.style.top = parseInt(player1.style.top) - 5 + 'px';
}
if (e.keyCode == 40) {
player1.style.top = parseInt(player1.style.top) + 5 + 'px';
}
if (e.keyCode == 87) {
player2.style.top = parseInt(player2.style.top) - 5 + 'px';
}
if (e.keyCode == 83) {
player2.style.top = parseInt(player2.style.top) + 5 + 'px';
}
});
function gameLoop() {
// move the ball
ball.style.left = parseInt(ball.style.left) + speedX + 'px';
ball.style.top = parseInt(ball.style.top) + speedY + 'px';
// check if the ball is colliding with a player
if (collision(ball, player1) || collision(ball, player2)) {
speedX = -speedX;
}
// check if the ball is out of bounds
if (parseInt(ball.style.top) < 0) {
speedY = -speedY;
}
if (parseInt(ball.style.top) > document.body.clientHeight - 20) {
speedY = -speedY;
}
// check if the ball is out of bounds
if (parseInt(ball.style.left) < 0) {
score2++;
ball.style.left = '50%';
ball.style.top = '50%';
}
if (parseInt(ball.style.left) > document.body.clientWidth - 20) {
score1++;
ball.style.left = '50%';
ball.style.top = '50%';
}
// check if anyone has reached the max score
if (score1 == maxScore || score2 == maxScore) {
alert('Game Over!');
score1 = 0;
score2 = 0;
}
}
setInterval(gameLoop, 10);
// helper function to check collisions
function collision(a, b) {
return !(
((a.offsetTop + a.clientHeight) < (b.offsetTop)) ||
(a.offsetTop > (b.offsetTop + b.clientHeight)) ||
((a.offsetLeft + a.clientWidth) < b.offsetLeft) ||
(a.offsetLeft > (b.offsetLeft + b.clientWidth))
);
}
</script>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/lnin 著作权归作者所有。请勿转载和采集!