Simple HTML Ping Pong Game: No Instructions Needed
<html>
<title>Ping Pong</title>
<body>
<div style='width: 300px; height: 300px; background-color: black;'>
<div id='player1' style='width: 10px; height: 50px; background-color: red; position: absolute; top: 125px; left: 10px;'></div>
<div id='player2' style='width: 10px; height: 50px; background-color: blue; position: absolute; top: 125px; right: 10px;'></div>
<div id='ball' style='width: 10px; height: 10px; background-color: white; position: absolute; top: 50px; left: 145px;'></div>
</div>
<script>
document.onkeydown = checkKey;
let top1 = 125;
let top2 = 125;
let left = 145;
let top = 50;
let dir = 1;
<pre><code> function checkKey(e) {
e = e || window.event;
if (e.keyCode == '38') {
top2 -= 10;
if (top2 < 0) top2 = 0;
}
else if (e.keyCode == '40') {
top2 += 10;
if (top2 > 250) top2 = 250;
}
else if (e.keyCode == '87') {
top1 -= 10;
if (top1 < 0) top1 = 0;
}
else if (e.keyCode == '83') {
top1 += 10;
if (top1 > 250) top1 = 250;
}
document.getElementById('player1').style.top = top1 + 'px';
document.getElementById('player2').style.top = top2 + 'px';
left += 10 * dir;
if (left > 290) {
if (top2 < top + 10 && top2 > top - 50) {
dir = -1;
} else {
alert('Player 1 wins!');
document.location.reload();
}
}
if (left < 10) {
if (top1 < top + 10 && top1 > top - 50) {
dir = 1;
} else {
alert('Player 2 wins!');
document.location.reload();
}
}
top += Math.random() * 20 - 10;
if (top < 0) top = 0;
if (top > 290) top = 290;
document.getElementById('ball').style.left = left + 'px';
document.getElementById('ball').style.top = top + 'px';
}
</script>
</code></pre>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/lnh3 著作权归作者所有。请勿转载和采集!