Simple HTML Ping Pong Game: No Instructions Needed
<html>
<head>
<title>Ping Pong</title>
<style>
#paddle1 {
width: 10px;
height: 50px;
position: absolute;
left: 0px;
top: 0px;
background: lightgreen;
}
#paddle2 {
width: 10px;
height: 50px;
position: absolute;
right: 0px;
top: 0px;
background: lightblue;
}
#ball {
width: 10px;
height: 10px;
position: absolute;
left: 50px;
top: 50px;
background: red;
}
#game {
background-color: #ccc;
width: 500px;
height: 300px;
position: relative;
margin: auto;
border: 1px solid black;
}
</style>
</head>
<body>
<div id='game'>
<div id='paddle1'></div>
<div id='paddle2'></div>
<div id='ball'></div>
</div>
<script>
var p1y = 0;
var p2y = 0;
var ballX = 250;
var ballY = 150;
var ballSpeedX = -3;
var ballSpeedY = 3;
<pre><code> function MovePaddles(){
//Get user input
if(Key.isDown(Key.UP)){
p1y-=5;
}
else if(Key.isDown(Key.DOWN)){
p1y+=5;
}
if(Key.isDown(Key.W)){
p2y-=5;
}
else if(Key.isDown(Key.S)){
p2y+=5;
}
//Keep paddles in bounds
if(p1y < 0){
p1y = 0;
}
if(p1y > 250){
p1y = 250;
}
if(p2y < 0){
p2y = 0;
}
if(p2y > 250){
p2y = 250;
}
//Move paddles
Paddle1.style.top = p1y + 'px';
Paddle2.style.top = p2y + 'px';
}
function MoveBall(){
//Move ball
ballX+=ballSpeedX;
ballY+=ballSpeedY;
//Check for boundaries
if(ballX < 0){
ballSpeedX *= -1;
}
if(ballX > 490){
ballSpeedX *= -1;
}
if(ballY < 0){
ballSpeedY *= -1;
}
if(ballY > 290){
ballSpeedY *= -1;
}
//Check for paddle collisions
if(ballX <= 25 && ballY >= p1y && ballY <= p1y+50){
ballSpeedX *= -1;
}
if(ballX >= 475 && ballY >= p2y && ballY <= p2y+50){
ballSpeedX *= -1;
}
//Move ball
Ball.style.left = ballX + 'px';
Ball.style.top = ballY + 'px';
}
function GameLoop(){
MovePaddles();
MoveBall();
}
function Init(){
//Get references to objects
Paddle1 = document.getElementById('paddle1');
Paddle2 = document.getElementById('paddle2');
Ball = document.getElementById('ball');
//Init mouse
Key.init();
//Start game loop
setInterval(GameLoop, 10);
}
window.onload = Init;
</script>
</code></pre>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/lnip 著作权归作者所有。请勿转载和采集!