Pong

download Pong

If you can't read please download the document

description

code

Transcript of Pong

// RequestAnimFrame: a browser API for getting smooth animationswindow.requestAnimFrame = (function(){return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function( callback ){return window.setTimeout(callback, 1000 / 60);};})();window.cancelRequestAnimFrame = ( function() {return window.cancelAnimationFrame ||window.webkitCancelRequestAnimationFrame ||window.mozCancelRequestAnimationFrame ||window.oCancelRequestAnimationFrame ||window.msCancelRequestAnimationFrame ||clearTimeout} )();// Initialize canvas and required variablesvar canvas = document.getElementById("canvas"),ctx = canvas.getContext("2d"), // Create canvas contextW = window.innerWidth, // Window's widthH = window.innerHeight, // Window's heightparticles = [], // Array containing particlesball = {}, // Ball objectpaddles = [2], // Array containing two paddlesmouse = {}, // Mouse object to store it's current positionpoints = 0, // Varialbe to store pointsfps = 60, // Max FPS (frames per second)particlesCount = 20, // Number of sparks when ball strikes the paddleflag = 0, // Flag variable which is changed on collisionparticlePos = {}, // Object to contain the position of collision multipler = 1, // Varialbe to control the direction of sparksstartBtn = {}, // Start button objectrestartBtn = {}, // Restart button objectover = 0, // flag varialbe, cahnged when the game is overinit, // variable to initialize animationpaddleHit;// Add mousemove and mousedown events to the canvascanvas.addEventListener("mousemove", trackPosition, true);canvas.addEventListener("mousedown", btnClick, true);// Initialise the collision soundcollision = document.getElementById("collide");// Set the canvas's height and width to full screencanvas.width = W;canvas.height = H;// Function to paint canvasfunction paintCanvas() {ctx.fillStyle = "black";ctx.fillRect(0, 0, W, H);}// Function for creating paddlesfunction Paddle(pos) {// Height and widththis.h = 5;this.w = 150;// Paddle's positionthis.x = W/2 - this.w/2;this.y = (pos == "top") ? 0 : H - this.h;}// Push two new paddles into the paddles[] arraypaddles.push(new Paddle("bottom"));paddles.push(new Paddle("top"));// Ball objectball = {x: 50,y: 50, r: 5,c: "white",vx: 4,vy: 8,// Function for drawing ball on canvasdraw: function() {ctx.beginPath();ctx.fillStyle = this.c;ctx.arc(this.x, this.y, this.r, 0, Math.PI*2, false);ctx.fill();}};// Start Button objectstartBtn = {w: 100,h: 50,x: W/2 - 50,y: H/2 - 25,draw: function() {ctx.strokeStyle = "white";ctx.lineWidth = "2";ctx.strokeRect(this.x, this.y, this.w, this.h);ctx.font = "18px Arial, sans-serif";ctx.textAlign = "center";ctx.textBaseline = "middle";ctx.fillStlye = "white";ctx.fillText("Start", W/2, H/2 );}};// Restart Button objectrestartBtn = {w: 100,h: 50,x: W/2 - 50,y: H/2 - 50,draw: function() {ctx.strokeStyle = "white";ctx.lineWidth = "2";ctx.strokeRect(this.x, this.y, this.w, this.h);ctx.font = "18px Arial, sans-serif";ctx.textAlign = "center";ctx.textBaseline = "middle";ctx.fillStlye = "white";ctx.fillText("Restart", W/2, H/2 - 25 );}};// Function for creating particles objectfunction createParticles(x, y, m) {this.x = x || 0;this.y = y || 0;this.radius = 1.2;this.vx = -1.5 + Math.random()*3;this.vy = m * Math.random()*1.5;}// Draw everything on canvasfunction draw() {paintCanvas();for(var i = 0; i < paddles.length; i++) {p = paddles[i];ctx.fillStyle = "white";ctx.fillRect(p.x, p.y, p.w, p.h);}ball.draw();update();}// Function to increase speed after every 5 pointsfunction increaseSpd() {if(points % 4 == 0) {if(Math.abs(ball.vx) < 15) {ball.vx += (ball.vx < 0) ? -1 : 1;ball.vy += (ball.vy < 0) ? -2 : 2;}}}// Track the position of mouse cursorfunction trackPosition(e) {mouse.x = e.pageX;mouse.y = e.pageY;}// Function to update positions, score and everything.// Basically, the main game logic is defined herefunction update() {// Update scoresupdateScore(); // Move the paddles on mouse moveif(mouse.x && mouse.y) {for(var i = 1; i < paddles.length; i++) {p = paddles[i];p.x = mouse.x - p.w/2;}}// Move the ballball.x += ball.vx;ball.y += ball.vy;// Collision with paddlesp1 = paddles[1];p2 = paddles[2];// If the ball strikes with paddles,// invert the y-velocity vector of ball,// increment the points, play the collision sound,// save collision's position so that sparks can be// emitted from that position, set the flag variable,// and change the multiplierif(collides(ball, p1)) {collideAction(ball, p1);}else if(collides(ball, p2)) {collideAction(ball, p2);} else {// Collide with walls, If the ball hits the top/bottom,// walls, run gameOver() functionif(ball.y + ball.r > H) {ball.y = H - ball.r;gameOver();} else if(ball.y < 0) {ball.y = ball.r;gameOver();}// If ball strikes the vertical walls, invert the // x-velocity vector of ballif(ball.x + ball.r > W) {ball.vx = -ball.vx;ball.x = W - ball.r;}else if(ball.x -ball.r < 0) {ball.vx = -ball.vx;ball.x = ball.r;}}// If flag is set, push the particlesif(flag == 1) { for(var k = 0; k < particlesCount; k++) {particles.push(new createParticles(particlePos.x, particlePos.y, multiplier));}}// Emit particles/sparksemitParticles();// reset flagflag = 0;}//Function to check collision between ball and one of//the paddlesfunction collides(b, p) {if(b.x + ball.r >= p.x && b.x - ball.r = (p.y - p.h) && p.y > 0){paddleHit = 1;return true;}else if(b.y 0) collision.pause();collision.currentTime = 0;collision.play();}particlePos.x = ball.x;flag = 1;}// Function for emitting particlesfunction emitParticles() { for(var j = 0; j < particles.length; j++) {par = particles[j];ctx.beginPath(); ctx.fillStyle = "white";if (par.radius > 0) {ctx.arc(par.x, par.y, par.radius, 0, Math.PI*2, false);}ctx.fill(); par.x += par.vx; par.y += par.vy; // Reduce radius so that the particles die after a few secondspar.radius = Math.max(par.radius - 0.05, 0.0); } }// Function for updating scorefunction updateScore() {ctx.fillStlye = "white";ctx.font = "16px Arial, sans-serif";ctx.textAlign = "left";ctx.textBaseline = "top";ctx.fillText("Score: " + points, 20, 20 );}// Function to run when the game oversfunction gameOver() {ctx.fillStlye = "white";ctx.font = "20px Arial, sans-serif";ctx.textAlign = "center";ctx.textBaseline = "middle";ctx.fillText("Game Over - You scored "+points+" points!", W/2, H/2 + 25 );// Stop the AnimationcancelRequestAnimFrame(init);// Set the over flagover = 1;// Show the restart buttonrestartBtn.draw();}// Function for running the whole animationfunction animloop() {init = requestAnimFrame(animloop);draw();}// Function to execute at startupfunction startScreen() {draw();startBtn.draw();}// On button click (Restart and start)function btnClick(e) {// Variables for storing mouse position on clickvar mx = e.pageX,my = e.pageY;// Click start buttonif(mx >= startBtn.x && mx = restartBtn.x && mx