PongR part 3: client side


Heads up!

The blog has moved!
If you are interested in reading new posts, the new URL to bookmark is http://blog.valeriogheri.com/


In part 1 of “PongR – my first experience with HTML5 multiplayer gaming” , I talked about the spirit of this project, the system architecture, technologies used and the design of the game (remember the server authoritative model?)

In part 2 I talked about the server side code and the server loops

This is part 3 and I will talk about the client side code, the client loops and how we draw basic (no sprites, only basic shapes) images on a canvas.

Code and Demo

As always, the code is fully published on github [https://github.com/vgheri/PongR] and a (boring!) demo is available at http://pongr-1.apphb.com . If you don’t have anyone to play with, just open two tabs and enjoy!

Project structure and technologies used

As a quick recap, this project has been realised using Asp.Net MVC, HTML5 (Canvas), Javascript, C#, SignalR for client/server real-time communication and qUnit for javascript unit testing.

PongR is a multiplayer HTML5 game, and this means that the client itself is doing a good amount of work.
The engine is replicated both on the server and on the client, as we have seen in the first part of this article when I talked about the server authoritative model + client side prediction that force us to add logic onto the client.
In the server this logic is built into a class named “Engine” and later on we will go into more details.
In the client this logic is built into a javascript module named PongR.

Javascript  code structure and unit testing

Most of the Javascript client side code is contained into a folder called Js, whose structure is shown below:

the module PongR is inside the file PongR.js. This module exports a public prototype with two public functions needed to setup an instance of the game and to connect to the server.

pongR.PublicPrototype.createInstance = function (width, height, username) { … }
pongR.PublicPrototype.connect = function () { … }

Furthermore the public prototype exports also a set of functions that have been unit tested using qUnit [www.qunitjs.com].
qUnit is very easy to use and the way I set it up is very neat: you can find all the details in this awesome article http://freshbrewedcode.com/jonathancreamer/2011/12/08/qunit-layout-for-javascript-testing-in-asp-net-mvc3/
Basically what you get is an easy way to share certain pieces of the tests layout in an ASP.net MVC3 application, with the possibility to have all the links to start your different tests grouped into one HTML page, being able to start them with just one click.
The downside of doing things this way is that the functions we want to unit test need to be visible from outside the module. In order not to pollute the public prototype too much, the module exports a UnitTestPrototype object, which will contain the references to the functions that I want to unit test.

var pongR = {
    PublicPrototype: { UnitTestPrototype: {} }

All the unit tests are contained into PongR_test.js.
A quick example:

And when runned, this is what you get:

Finally, I’m going to talk about RequestAnimationFrameShim.js later in the article, when I’ll focus on the Canvas element.


Other than what we already saw, this module defines several View Model, related to objects that needs to be simulated. Below we can see a basic diagram of the objects and their connections:

The main object here is clearly Game, as it contains the whole state of a match.
Settings is another interesting enough object, it holds a few configuration variables that are mostly used for client prediction and interpolation (I will cover this topic later on in the post).
These models are widely used by the client logic: for example the physics update loop directly modifies these models at every simulation step.
And this leads us to discuss about the client side update loops.

Client side update loops

Let’s restart the flow and let’s see more in detail what is happening:
when a client enters its username and posts the form, the system redirects the client to the page where the actual game will be displayed. This page will load all the necessary javascript libraries and modules, as well as PongR, and will then perform this piece of code on the document onready event:

createInstance sets up the basic configuration of the game and creates the variable that will host the SignalR object, pongR.pongRHub, and all related callbacks.
Once the SignalR object has been correctly populated, we can invoke the .connect() function on PongR, that will start the SignalR connection and on success we invoke the joined() function, which will be where the server will process the client.
We need to have something after start() because in the server side handler the round trip state is not yet available.
When 2 players are connected and waiting, the server sends an init message to both clients that is handled by the client by the following callback:


This code initiliases a new Game, the canvas on which the game will be drawn on, an empty list of server updates that will be received throughout the game and the default delta time set to 0.015 ms that corresponds to 66 fps, a keyboard object, which is a slightly modified version of the THREEx keyboard library that I edited to serve my purposes here, and draws the initial scene (the field, the players and the ball).
After completing initialisation, we can perform a 3 seconds countdown so that the match doesn’t start all of a sudden and the players are not yet ready.
At the end of the countdown the startGame function is invoked.
This function is very important because it starts the two client loops responsible of handling the game inputs and rendering.

function startGame() {

Client side loops

Client physics update loop

Exactly as the server was running a physics update loop, the client is also running a similar loop.
This loops interacts with and modifies directly the View Models that I described earlier.

function startPhysicsLoop() {
    physicsLoopId = window.setInterval(updatePhysics, 15);

This loop runs every 15msec and is responsible for

  • updating at each round the delta time, used to compute the movements of the players
  • updating the position of the client
  • updating the position of the ball
  • checking for possible collisions between the ball and the objects of the game, players and ball. If a collision is detected, than the position and the direction of the ball are updated as well.


Despite the fact that the source I used to create this project puts the collision-checking code into the client update loop, I moved it inside the physics update loop for simplicity. This is obviously not an ideal solution if you want to play sounds on collisions, for example, given that the sound should be played by the update loop.

Client update loop

This loop, unlike the physics loop, is scheduled using a function recently introduced into modern browsers, RequestAnimationFrame.

function startAnimation() {
    requestAnimationFrameRequestId = window.requestAnimationFrame(startUpdateLoop);

You can read in detail about this function here  and more here  .
Basically instead of using setTimeout or setInterval, we tell the browser that we wish to perform an animation and requests that the browser schedule a repaint of the window for the next animation frame. Reasons why RequestAnimationFrame is better than old style setTimeout and setInterval for drawing purposes are clearly stated in the above link, but I think it’s important to quote them here:

The browser can optimize concurrent animations together into a single reflow and repaint cycle, leading to higher fidelity animation. For example, JS-based animations synchronized with CSS transitions or SVG SMIL. Plus, if you’re running the animation loop in a tab that’s not visible, the browser won’t keep it running, which means less CPU, GPU, and memory usage, leading to much longer battery life.

Because this function has been recently introuced, it may happen that some browser still don’t support it and that’s the reason of that RequestAnimationFrameShim.js file that we saw at the beginning. It’s a piece of code found on Paul Irish’s blog aticle mentioned above, so credits go to him.
Let’s see the code:

Initially I check that we are not in a post-goal condition, because after a goal a 3 seconds countdown will be performed and we don’t want to update any of our internal data structures during this time.
If we are not, then we can simulate a new step of the game

At every step the canvas must be redrawn, therefore I can safely clear it.
As this game is fairly simple it won’t impact our performances, otherwise it could have been better to have multiple specialised overlapping canvas, where for example we could use one to draw the background that never changes, and therefore needs not to be cleared & redrawn at each step, and so forth…
Furthermore, I need to process client inputs (if any) and accordingly update a meta-structure that contains a list of commands (“up”/”down”). This meta-structure will then be used by the client physics loop and converted in movements.
Every input processed at each loop is stored in a list of commands (pongR.me.inputs) and assigned a sequence number that will be used when the server will acknowledge already processed inputs. For example, if the server acknowledges input 15, then we can safely remove from the buffer all inputs with sequence number equal to or lower than 15, and reapply all non yet acknowledged inputs (remember the client side prediction model?).
Every input is packed and immediately sent to the server to be processed.

if (!pongR.settings.naive_approach) {

function interpolateClientMovements is a bit tricky and you can read the code by yourself for a better understanding (or even better you can check the blog article where I took this from), but basically it is trying to interpolate the different positions of the opponent in time so that at each redraw its movements will result more continuous and natural to the eyes of the player.
Imagine that the opponent is currently at position (50,50) and then finally we receive its new position at (50,100), if we naively assign this new position to the opponent, what we will see on the screen is a big leap from last frame and it’s obviously something we don’t want.
I have to say that my implementation is not working that well at the moment, but the idea is there.
Finally, after having handled all inputs, I can draw the new frame by drawing each object on the screen.

Server authoritative model in practice

Each time the server runs its own update loop, the clients receive an update packet.
Each client is then responsible for processing it and updating its internal structures so that the next time the update loops will run, they will see an updated snapshot of the game as dictated by the server.
The function responsible to handle all of this is the SignalR callback updateGame.
Let’s see it in detail:

As I mentioned in part 1 of this blog article, it’s the server responsibility to simulate game state changing events, and a goal event is one of this kind!
This should clarify the meaning of the first lines of code: the client only knows that a goal happened because the score changed!
Then, based on this condition, we need to perform two different tasks:

  1. If one of the two players scored, we need to update the scores (both internally and on the screen), reset the positions of all the objects drawn on the screen, reset the state of the keyboard object (we don’t care of all the keystroke pressed after a goal!) and finally perform a countdown that will start the match once again.
  2. Otherwise
    1. We need to apply client side prediction to update our client position, re-processing all those inputs which have not been acked by the server yet
    2. If we are not using a naive approach we do not directly update the other player position, but we simply update some of its internal properties and then we push the just received update packet into the updates buffer, so that it will be used in the update loop for interpolation
    3. We update the information related to the ball  object

It is interesting to note that the updates buffer is not infinite and we limit it to cover 1 seconds of server updates.

Final considerations and next step

This was my first attempt at creating a game and adding multiplayer didn’t make the task easier for sure!
The graphic is really basic, the game itself is not that entartaining, the network lag is clearly affecting the user experience mostly due to a not optimised networking code and to the impossibility of using WebSockets (AppHarbor doesn’t support them yet), but nevertheless it was very funny and I learned plenty of stuff while working on this project.
I have to say that offering the clients a seamless game over the wire has probably been the hardest part of it, and I’m sure there are things which are not working like they should in my code.
Also I think that Asp.Net MVC doesn’t offer the best in class experience to realise this sort of web app (as expected), whereas I see much more fitting Node.Js because of its event-driven nature: if you think about it, almost everything happening in a game can be seen as an event.
Last but not least, using a single codebase and a single language can greatly help to speed up the process.
I couldn’t cover everything I wanted to in these three posts, they are already monster size, so I encourage you to clone the repository and dig into the code to find everything out (like for example delta-time implementation and time synchronisation).
In the near future I would like to rewrite this project entirely in Javascript using Node.Js and, enhancing the user experience ameliorating the graphics using sprites, making the game funnier (e.g. possibility to use bonuses), adding sounds, upgrading SignalR to 1.0 etc…


That’s all about PongR, I hope this can help someone


2 thoughts on “PongR part 3: client side

    • Hello,

      well I think that Node.js is a better fit for stuff like multiplayer games, yes, but SignalR remains a solid solution for all real-time additions to classic web applications that you can build with Asp.Net MVC.
      That being said, Node.js is certainly worth your time :=)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s