JS: Pong
more at: http://www.senaeh.de/ein-altes-spiel-mit-neuen-technologien-pong/
by Daniel Hall
HTML
<p id="points">Ich: 0 | Computer: 0</p>
<canvas id="canvasPong" width="500" height="400">Dein Browser unterstĂĽtzt das Canvas-Element nicht.</canvas>
CSS
html,body{margin:0; padding:0}
p {display:none}
canvas {
display: block;
background: #123
}
JavaScript
var canvas;
var context;
var width;
var height;
var ball;
var player;
var computer;
var pointsPlayer = 0;
var pointsComputer = 0;
var up = false;
var down = false;
var speed = 3;
var computerSpeed = 40;
function init() {
// canvas
canvas = document.getElementById("canvasPong");
context = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
width = canvas.width;
height = canvas.height;
// create objects
createBall();
player = new Paddle(0, height / 2, height);
computer = new Paddle(width - 10, height / 2, height);
// loop
startLoop();
}
function startLoop() {
setInterval(updateLogic, 1000 / 33); // 33 milliseconds = ~ 30 frames per sec
}
Number.prototype.clamp = function (min, max) {
return Math.min(Math.max(this, min), max);
};
document.onmousemove = function (e) {
player.movePlayer(e.pageY)
};
function updateLogic() {
// move computer
if (GameMath.withinRange(ball.y, 0, computer.y + computer.height * 0.25)) computerSpeed = -speed;
else if (GameMath.withinRange(ball.y, computer.y + computer.height * 0.75, height)) computerSpeed = speed;
else computerSpeed *= 0.95;
computer.movePosition(computerSpeed);
// show points
document.getElementById("points").innerHTML = "Ich: " + pointsPlayer + " | Computer: " + pointsComputer;
// draw elements
context.clearRect(0, 0, width, height);
ball.update();
context.fillStyle = "#0ae";
context.beginPath();
context.arc(ball.x, ball.y, ball.radius, 0, Math.PI * 2, true);
context.closePath();
context.fillRect(player.x, player.y, player.width, player.height);
context.fillRect(computer.x, computer.y, computer.width, computer.height);
context.fillStyle = "#f0f";
context.fill();
// collision - ball with border
if (ball.x + ball.radius < 0) {
pointsComputer++;
createBall();
}
if (ball.x - ball.radius > width) {
...