Pong
Just.. Pong.
HTML
<div class="container" id="game">
<span id="ball" class="ball"></span>
<span id="paddle1" class="paddle"></span>
<span id="score" class="score">0</span>
<span id="highscore" class="score">Best: 0</span>
</div>
CSS
.ball {
background-color:red;
display:block;
width:15px;
height:15px;
border-radius:100px;
position:absolute;
}
.paddle {
display:block;
background-color:blue;
height:100px;
width:10px;
border-radius:10px;
position:absolute;
}
.score {
display:block;
text-align:center;
width:100%;
background-color:black;
color:white;
font-size:20px;
}
.container {
width:500px;
display:absolute;
top:0px;
margin:0px;
padding:0px;
left:0px;
height:500px;
border: solid white 1px;
}
JavaScript
document.body.style = "background-color:black;";
document.documentElement.style.overflow = "hidden";
document.body.scroll = "no";
var score = 0;
best = 0;
var container = document.getElementById("game");
function Ball(name) {
this.paddle = null;
var x = game.clientWidth / 2;
var y = game.clientHeight / 2;
var xv = -1.5;
var yv = 0;
window.setInterval(function() {
var ball = document.getElementById(name);
x += xv;
y += yv;
if (x < 0) {
if (score > best) {
document.getElementById("highscore").innerHTML = "Best: " + score;
best = score;
}
score = 0;
document.getElementById("score").innerHTML = score;
x = game.clientWidth / 2;
y = game.clientHeight / 2;
xv = -1.5;
yv = 0;
}
if (y + ball.clientHeight >= game.clientHeight + game.getBoundingClientRect().top || y <= game.getBoundingClientRect().top) {
yv *= -1;
}
document.getElementById(name).style = "left:" + x + "px;" + "top:" + y + "px;";
if (paddle != null) {
var py = document.getElementById(paddle.name).offsetTop;
var px = document.getElementById(paddle.name).offsetLeft;
if (Math.abs(py - y + 50) - 7 <= 50 && Math.abs(px - x) <= 10) {
xv = Math.abs(xv);
x += 5;
if (Math.abs(xv) < 6) {
xv *= 1.1;
}
if (yv == 0) {
yv += (Math.random() - 0.5) * 2;
} else {
var random = Math.random() - 0.5;
if (random > 0) {
yv *= -1;
}
if (Math.abs(yv) < 6) {
yv *= 1.2;
yv += Math.random() - 0.5;
} else {
yv -= Math.random() * 2;
}
}
score++;
document.getElementById("score").innerHTML = score;
}
}
if (x + 15 > game.clientWidth + game.getBoundingClientRect().left) {
xv *= -1;
}
}, 10);
}
ball = new Ball("ball");
function Paddle(name, ai) {
var y = 0;
this.name = name;
if (!ai) {
...