Ping Pong
by Gereltod Gotsbayar
HTML
<div id="scoreboard">
<div class="score">Тоглогч A : <span id="scoreA">0</span> (AI)</div>
<div class="score">Тоглогч B : <span id="scoreB">0</span></div>
</div>
<div id="game">
<div id="playground">
<div id="paddleA" class="paddle"></div>
<div id="paddleB" class="paddle"></div>
<div id="ball"></div>
</div>
</div>
CSS
#playground{
background: #e0ffe0;
width: 400px;
height: 200px;
position: relative;
overflow: hidden;
}
#ball {
background: #fbb;
position: absolute;
width: 20px;
height: 20px;
left: 150px;
top: 100px;
border-radius: 10px;
}
.paddle {
background: #bbf;
left: 50px;
top: 70px;
position: absolute;
width: 30px;
height: 70px;
}
#paddleB {
left: 320px;
}
#scoreboard {
font-size: 11px;
}
JavaScript
$("#paddleB").css("top", "20px");
$("#paddleA").css("top", "60px");
var KEY = {
UP: 38,
DOWN: 40
};
var pingpong = {
scoreA: 0,
scoreB: 0
}
pingpong.pressedKeys = [];
pingpong.ball = {
speed: 5,
x: 150,
y: 100,
directionX: 1,
directionY: 1
}
$(function() {
pingpong.timer = setInterval(gameloop, 30);
$(document).keydown(function(e) {
pingpong.pressedKeys[e.which] = true;
});
$(document).keyup(function(e) {
pingpong.pressedKeys[e.which] = false;
});
});
function gameloop() {
moveAI();
moveBall();
movePaddles();
}
function movePaddles() {
if (pingpong.pressedKeys[KEY.UP]) {
var top = parseInt($("#paddleB").css("top"));
$("#paddleB").css("top", top - 5);
}
if (pingpong.pressedKeys[KEY.DOWN]) {
var top = parseInt($("#paddleB").css("top"));
$("#paddleB").css("top", top + 5);
}
if (pingpong.pressedKeys[KEY.W]) {
var top = parseInt($("#paddleA").css("top"));
$("#paddleA").css("top", top - 5);
}
if (pingpong.pressedKeys[KEY.S]) {
var top = parseInt($("#paddleA").css("top"));
$("#paddleA").css("top", top + 5);
}
}
function moveBall() {
var playgroundHeight = parseInt($("#playground").height());
var playgroundWidth = parseInt($("#playground").width());
var ball = pingpong.ball;
if (ball.y + ball.speed * ball.directionY > playgroundHeight) {
ball.directionY = -1;
}
if (ball.y + ball.speed * ball.directionY < 0) {
ball.directionY = 1;
}
if (ball.x + ball.speed * ball.directionX > playgroundWidth) {
ball.directionX = -1;
}
if (ball.x + ball.speed * ball.directionX < 0) {
ball.directionX = 1;
}
ball.x += ball.speed * ball.directionX;
ball.y += ball.speed * ball.directionY;
var paddleAX = parseInt($("#paddleA").css("left")) + parseInt($("#paddleA").css("width"));
var paddleAYBottom =...