Introducing pong.js

There are times in life when you are really bored but instantly, in just few seconds, you realize that you are a developer. Boom. Why I love to be a developer? Because you have the tools to create everything is bouncing in your mind, everytime, everywhere.

What bounced in my mind some weeks ago was the retrĂ² game Pong, one of the first videogame ever made in the history, produced by Atari in the seventies. I love that game, it's simple, it's fun and it's fu**ing viiiiintage!

So, after some reading and documentation about the principle behind a pong game (I want to thank Matt Mongeau for this beautiful post/tutorial that show the base code for a pong clone), I started to write the project, a javascript module that let you integrate a full customizable pong game in web pages. Let me introduce pong.js.


demo download on GitHub


Some basics

Pong.js is a simple JavaScript library to let you add a custom pong game on your web applications. Just set up some basic option and let the library do the job.

A <canvas> tag moved by requestAnimationFrame will be append on our document and the game will begin. To move the paddle we can use the keybord arrows, to start the game just press ENTER and to pause the game push the space bar. We can start a new game or change the level game (difficult) using the menu. That's all!

What happened under the hood is really simple: everytime the RAF call the render function, the canvas is updated with new positions for paddles, ball and much more. To create a solid structure was needed and object oriented approach: we have some basic class like "Paddle" or "Ball", everyone of those has its own update methods. There are also a "Player" and a "Computer" objects: they are the real players.

Finally, I have included the possibility to customize the size, the colors and the difficult of the game. A set of retrĂ² aspect style is also included: do you prefer a dark (default) theme, a light one or the classics matrix colors?


Setup the game and let the js do the job

Everything you need to do to create a pong instance using the library it's the initial setup to set your preferences and call the init() method. Really...that's all. Let's check out a simple example.

// setting up a a new pong.js instance
var pongGame = new PongGame({  
    level: 2,
    width: 600,
    height: 600,
    theme: 'matrix',
    onInit: function(){ console.log('game is initialized'); },
    onPlay: function(){ console.log('game is playing'); },
    onPause: function(){ console.log('game is paused'); },
});

// let's start it
pongGame.init();  

Hope you enjoy my latest project. It's work in progress...there's still much to do but I think that it's in a good spot now. For any question or integration, drop a comment below. Cheers!



Daniele Petrarolo

Daniele Petrarolo

http://www.danielepetrarolo.com

In love with #JavaScript, #PHP and #Python / Web Developer / There's no place like 127.0.0.1.

View Comments