Writing a Pong game in JavaScript




In this episode I write a Pong game in JavaScript from scratch.

Some key technologies we will look at are
* Object Oriented Programming
* ES6 class with getter and setter
* Canvas
* requestAnimationFrame()
* Handling user input

Since we are writing ES6 this code might not run on all browsers yet. I was running Chrome 52 when I wrote this and if you wish to follow I recommend you do too.

The initial HTML file can be found here:
https://github.com/meth-meth-method/pong/blob/5e20bf1512e1579f16d794d7ce2e49ad32f57b37/src/index.html

Try it:
https://meth-meth-method.github.io/pong/

Source code:
https://github.com/meth-meth-method/pong

Music:
Demoscene Time Machine
http://demoscenetimemachine.com

Original source


32 responses to “Writing a Pong game in JavaScript”

  1. Hey guys, is observable from the video that ball don't touch left and upper corner. In order to fix this use: get left(){ return this.position.x; } and get top(){return this.position.y; } . Happy Coding! 🙂

  2. I know you probably do this later in the video, but I went ahead and added this after you made the 2nd paddle AI, to keep paddles within the screen:
    this.players.forEach(player => {
    if (player.pos.y – player.size.y / 2 < 0) {
    player.pos.y = player.size.y / 2;
    } else if (player.pos.y + player.size.y / 2 > this._canvas.height) {
    player.pos.y = this._canvas.height – player.size.y / 2;
    }
    });

Leave a Reply