As a project, I created a game of multiplayer pong, as a way to really get to grips with Node. I’ve used it before but only as a web server which didn’t really suit my needs. So this was my chance to use it properly.

I’m a massive fan of AngularJS — I’ve used it for a few years on various projects and thought it would be suitable given the constraints:

  • The server must have a model of the game, which it uses to continually update clients on.
  • The clients must make sure the UI reflects the game model at all times — there is no point the server thinking the ball is in one place when the UI displays it in another.
  • The communication must be fast.

Given this, I chose Socket.io for communication between the Nodeserver and the client. This will allow easy communication which is fast and without complications. To ensure the UI reflects the game model I used AngularJS, a front end Javascript framework. This is because it is perfectly suited to tying the front-end DOM to a data model; as the model changes, it automatically makes the front-end change.

The game works by waiting for two players to join the game, at which point the game starts. When a user visits the webpage, they can choose a left bat or right bat. When one bat is chosen, the option of choosing that bat disappears from all other clients. This is a demonstration of the beauty of the stack — as the user makes an action, it notifies and updates the server, thus updating the model on all clients. This is incredibly elegant solution, as no client can ever get “left behind”.

Once a game is started, the users can move the bats by using their arrow keys. This is easy to do in Javascript, as each key sends a data event that contains the key code for each key pressed — we just listen for up, down and space (new game).

Scores are kept, the first to three wins. The UI highlights the players side, and this then lights up on the winners side.

As anyone who has used jQuery for large applications will know, things soon become messy. UI elements that shouldn’t be showing start showing, and errors start cropping up, ending up in the user needing to refresh the page. With AngularJS that never happens.

The model for the game is a JSON object. This works well with all technologies, and provides an easy to understand model. The ball has a position as well as two properties used to animate the movement of the ball: dx and dy which is the difference in x and y position for each “tick” of the game. A speed property is also there however I’ve since integrated this as part of the dx and dy numbers.

If you want to see the code I wrote, I put it up on GitHub: https://github.com/conorriches/NodeAngularSocketPong

This is the first of many projects I have written that I’ve put on GitHub — I usually don’t do this, as I don’t feel my code is at the level that I’d like to publicly share, but for this I think it’s a good start.

 

Categories: Uncategorized