Author Archives: Aditya Ravi Shankar

Six Pack Abs and a Toned Body – You don’t really want it

Do you want to be extremely fit and healthy? Maybe have a toned body with a six-pack instead of a growing belly with flabby arms? Is getting fit and healthy a priority in your life?

Over the last year, while focusing on fitness and nutrition, I dropped nearly 14 Kgs (31 lbs) and 6 inches off my waist. I’ve now reached the point where people automatically stereotype me as “the fitness guy”, or “the bodybuilder”.

Since then, more and more people have reached out to me for fitness, nutrition and weight loss advice. Everyone wants to know exactly what I did, and how easy or difficult it would be for them to replicate.

I usually go out of the way to try and help friends when they ask for advice, since fitness is still a very big part of my life, and I’m always happy to help others on the same path. I freely share information about my diet/nutrition, exercise routines, and how I keep myself motivated.

It’s a pleasure to see the excitement in their eyes when they see how simple it can be to get into great shape; when they realize that their “stretch goal”, is in fact realistically possible in just two or three months.

However I’ve come to a bitter realization over the last year of trying to help people get fit.

Most people don’t really want to get fit and healthy. Most people don’t want to look like the models they see in magazines. In fact, they don’t even want to get half-way to that point to look “not unhealthy”.

All most people really want to do is talk about how much they want it, while continuing to remain in their current unhealthy state, or worse getting even more unfit.

Every time someone takes home one of the workout programs I recommend, I get hopeful that maybe this one person will stick with it and achieve great results. Often they message me after a few days about how amazing it feels and share the initial results they are getting, which gets me optimistic since unlike ninety percent of their peers, they actually started and committed to it.

And then, even though they see the results they have already got in just a few days, even though they know that this program works, without fail, they stop.

They abruptly stop messaging updates, and just as abruptly stop talking about fitness.

When I make the effort to reach out and check up, out come the excuses – no time, too tired, suddenly very busy.

Almost consistently and without fail, each of them usually says that they haven’t quit, they have just stopped for a little while and they plan to start again when they “have the time”. I still don’t know of one person among dozens of friends who started again or managed to find time.

I had someone tell me once, “exercise is a priority for me, however I just don’t get the time“.

My response? “No. It isn’t. Your priority is eating and drinking with your friends, watching movies, or relaxing and watching tv. If exercise was your priority over these things you would first exercise, and then say you didn’t have time to watch movies or hang out with friends. The fact that exercise doesn’t come before these things clearly means, by definition, that fitness isn’t the priority in your life.

So now let me ask again – Do you want to be fit and healthy? Is being healthy a priority in your life?

Answer honestly, and if the answer is no, then learn to accept it. Start admitting to people that you find it easier to be fat and unhealthy and prefer making excuses to getting fit and healthy. That you don’t want to be the best that you can be.

Don’t lie to yourself. At least this way you won’t feel guilty about missing out on exercise or eating unhealthy.

And when you truly decide to make fitness your priority, you can commit fully and achieve results.

Thank you – Expressing your feelings so others can feel them too

I was still in school. I think it was 7th grade.

I was just another shy school kid who brought his teacher a card for teacher’s day. I didn’t really put much effort into the card. She wasn’t even my favorite teacher. But she was a good teacher who loved her job and taught like it meant a lot to her. I just gave her the card because lots of other students were giving cards in class and I thought even I should.

When I gave her the card, she looked me in the eyes and said “Thank you”. Nothing more.

But that moment changed my life in a way that I can never really explain. Because what really shocked me, was the fact that I didn’t just hear that Thank you. I felt it !!!

Maybe it was the way she looked at me like I was the only person in the room. Maybe it was the way her eyes were glistening, almost with tears, when she said it. The way that she seemed to really, really mean it.

I knew she meant it, and I knew she was trying to convey what she was feeling. At that moment she was sharing everything that she felt – the joy, the gratitude, everything. And as I looked at her, I felt every bit of it, almost radiating from her.

And all she had said were the two words – “Thank you”.

Until that day, in my mind, “Thank You” was just something you automatically said when people gave you something, whether you cared about it or not. It was something you said because your parents taught you that you were supposed to say it.

It was never said like this!!! Words weren’t supposed to have so much feeling and emotion in them. Words were just words. How was she doing this?

But that day she changed my life. Because from that day, I kept wondering how someone could say something with so much emotion. Wondering what I had been missing because I didn’t even know it was possible.

It was the day I realized that I too wanted to be able to say and express what I felt. To be able to communicate not just with words, but with emotions and feelings. And I wanted to be around more people who could talk to me the same way. People who could connect with more than just words.

That day, as much as any other, has made me who I am today. And for that I am truly grateful.

HTML5 Game Development: Using sprite sheets for better performance (and protecting your server)

When I started developing the HTML5 version of Command and Conquer, I never expected more than a few close friends to look at the game. (Based on the experience with my last game, Breakout).

Command and Conquer Javascript ScreenshotSo while I spent a lot of time making the game look as close to the original Command and Conquer as possible, I never spent much time optimizing the code. Most of my development and testing was on my own Macbook, and I didn’t pay attention to the image loading time or network traffic.

Unfortunately, this game uses a lot of images.

Each unit can face 32 different directions. This means at least 32 different images for each unit (more if there are animations like ‘harvesting’).

Buildings need a whole set of images for each state – under construction, regular – with different sets of images for healthy and damaged buildings, and for any additional states (like ‘unloading a harvester’). The Construction Yard for example needs 82 different images for it’s animations.

As a result, when the game loaded, it made nearly 1,000 HTTP requests to load all the assets (including images and sounds).

Since most browsers only make a few simultaneous requests at time, downloading all these images took a lot of time, with an overload of HTTP requests.

While this wasn’t a problem when I was testing the code locally, it was a bit of a pain when the code went onto the server. My patient friends ended up waiting for the game to load for 5-10 minutes (sometimes longer) before they could actually start playing. - Traffic Screen ShotThe problem came when my game hit the front page of Hacker News and on the same night, resulting in a slight spike in traffic :). It then got worse when the game got 1,000+ tweets and 1,000+ FB likes in just a few hours. The last time I checked, searching for my game gave over 5,000 google results.

What this meant was my shared hosting server was getting close to 14,000,000 HTTP requests in one day from just my domain.

I don’t think too many shared hosts are designed to take this kind of load, which resulted in my account being disabled with this interesting email from my provider.


Your account on the server was recently found to be causing high load that resulted in slowness/outages of various system services. In order to ensure quality of service to the other clients on this server we regret to inform you that the account had to be disabled to prevent any further interruption of service to our other clients.

If nothing can be done to lower the resource usage you may need to look into purchasing a dedicated server or cloud server which you can find more information about at Please contact us as soon as possible to resolve this issue.

I was able to find temporary hosting on another server but the biggest priority was to optimize the way I stored images, which of course brings us to sprite sheets.

Hand of Nod Sprite SheetSprite sheets store all the sprites for an object in a single large image file.

When displaying the images, we calculate the offset of the sprite we want to show and use the ability of the drawImage() method to draw only a part of an image.

Creating these sprite sheets is incredibly simple using ImageMagick’s montage command line tool. This single command will convert a folder full of images into a single row sprite sheet.

After comparing PNG and GIF, I found that PNGs tend to compress the sprite sheets a lot more.

The advantages of using Sprite Sheets?

  1. Fewer HTTP requests – The Command Center went from 81 requests to a SINGLE HTTP request
  2. Better Compression – An advantage of storing the images in a single file is that the header information doesn’t repeat and the combined file’s size is much smaller than the sum of the individual files. The command center went from 496KB in 81 files to only 37KB in a single file. (Less than 8% of the original size, which is incredible)
  3. Easier Manipulation – With all the sprites in a single image file, it became easier to do RGB color manipulations, and I was able to optimize the drawing code for performance.

From almost a 1,000 requests to 120 requests in one simple code rewrite. And the total download size went from a few MBs to around 200KB.

Game load time went from 10+ minutes to under a minute. The bandwidth usage dropped to a tenth of the original. The number of requests dropped to a tenth of the original. And now my shared hosting can survive a very decent amount of traffic.

Moral of the story? When developing a large game that is image heavy, track your network usage and when possible use sprite sheets πŸ™‚

Command and Conquer – Programming an RTS game in HTML5 and Javascript

After writing my first HTML5 game I decided to take on a more challenging project.

Command and Conquer Javascript ScreenshotMy latest project is a recreation of the original Command and Conquer entirely in HTML5 and Javascript.

Command and Conquer is the grand-daddy of all Real Time Strategy games and is probably the game that made the genre popular. My friends and I spent countless hours playing the original as well as subsequent sequels (Tiberian Sun, Red Alert).

Check out the demo video.

You can play the actual game here. Command and Conquer – HTML5 version

This project was a lot more challenging than my previous game, Breakout. In hindsight, I might have wanted to take smaller steps and make a tower defense game instead of jumping directly into an RTS.

Creating even this simple version of the game covered a lot of things.

  1. Using images to recreate the sidebar and game interface.
  2. Using mouse input for unit selection, panning, attacking and user input
  3. Using images as sprites for unit and building animation, and using sprite sheets for better performance
  4. A lot more sounds for units and buildings
  5. Using a finite state machine for handling unit commands, movement, attacking etc.
  6. Using path finding (A*) to navigate around obstructions like buildings, mountains and trees
  7. Using hidden canvas’s for things like fog of war and image manipulation

Obviously because of the size of the project, trying to do the whole thing in under a month all by myself wasn’t the smartest idea. I ended up spending lots of 18 hour work days during this time.

I used to switch between playing the original Tiberian Dawn in a Wine window on my Mac and my JS version on the browser to make sure my version looked EXACTLY like the original. I spent a LOT of time going through C&C forums to understand how to reverse engineer the Tiberium Dawn files to extract the building/unit sprites and audio and reading up on unit specs to figure out how to make the units behave exactly like the original.

Every little thing took time – things like selecting single units, multiple units, being able to select by drawing the box from left to right or from right to left; making sure the panning was smooth; Figuring out a decent fog of war implementation; Allowing for building construction, dependencies (Power Plant needed for Refinery, which is needed for Factory), building placement (buildings cannot be constructed on top of other buildings); Depth sorting when drawing so units could move behind buildings and trees.

The next big headache was smooth unit movement. I wanted to do better than the original game, and spent a lot of time going through Starcraft 2 videos to see if I could get a smoother movement closer to the way SC2 handles it. Pathfinding using A* can do some of the work, but gives a clunky movement and causes units to take behave badly/take longer routes when going through bottle necks. I decided to mix A* with a repelling force/steering behavior to improve it. It still has some bugs I need to work out.

I had to fine tune the way units behaved (during patrolling, guarding, attacking). Even the fact that a MCV couldn’t attack and turned into buildings.

Harvesting was a whole different pain in the ass since my collision detection and steering code meant my harvester was initially afraid to return to the refinery :).

While a lot of people have been giving me props for just getting this project out, one of the things that I am proud of is that I completed the first version in around 3 and a half weeks, all by myself.

For people who have been criticizing this project, I’ll say this – “I did this, entirely on my own, unpaid, in three and a half weeks – including one week where I had a fever. Give me a break. It isn’t that bad :)”.

The current iteration of the project contains several levels from both GDI and NOD campaigns. I am also currently testing multiplayer using Node.js, which should be coming soon.

Check out the video demo of the new version of this game that I am working on.

This game has got a lot of attention from online media and FB/Twitter/Google+. The extra traffic brought my server down on its knees and got my account temporarily suspended. This forced me to optimize the game using sprite sheets so it could handle requests more efficiently. You can read more about the whole story here – HTML5 Game Development: Using sprite sheets for better performance (and protecting your server)

Real Time Strategy Game - Pathfinding, Collision Detection & Steering Demo - ScreenshotAfter lots of feedback, I’ve specifically researched and worked on improving the pathfinding of the game. Check out the Pathfinding, Collision Detection & Steering Demo. This is a demonstration of the improved unit pathfinding and movement/steering strategies used in RTS games. Units use A* to plot a path and avoid collision using a ‘soft collision’ radius. They also ask static units to move aside.

Here is a video demonstrating all the features of the new pathfinding code.

Check out the demo here. Switch on “DEBUG MODE” to see how it works. This is still a work in progress. Any comments or feedback (including bugs), is appreciated.

Check out some of theΒ HTML5 games I have written.Β If you are just starting out with game programming, check out my earlier tutorial on developing a simple Breakout game in HTML5.


ANNOUNCEMENT: My Book, Pro HTML5 Games is out!!!

Pro HTML5 Games - Aditya Ravi ShankarA lot of people have been asking me for details on how I built the HTML5 version of Command and Conquer.

Based on my experience developing this game, I have just written a book showing readers how to build a complete RTS game in HTML5.

My book, Pro HTML5 Games takes readers through the process of building two complete games – a Box2D Engine based Angry Birds clone and a realtime strategy (RTS) game with multiplayer support.

This book is now available for purchase at Amazon (Pro HTML5 Games on Amazon), Barnes & Nobles (Pro HTML5 Games on Barnes & Noble) as well as the Apress Site (Pro HTML5 Games on Apress).

If you are interested in building professional looking HTML5 games, you should check the book out.

If you know anyone who would be interested in this book, please do share this book URL (// with them.

Read more details about Pro HTML5 Games here.

HTML5 Game Development Tutorial: Breakout Part III – Collisions, Scoring and Sound

Breakout v0.6 ScreenshotThis is the third in a series of tutorials on developing a full featured version of Breakout.

In the second tutorial, we used setInterval() to add some animation and capture keydown and keyup events to respond to user input.

In this tutorial, we will bring back the bricks we drew before, handle the ball colliding with these bricks, and finally increase the score when a brick gets destroyed. We will also add some sound effects to make the game more fun.

We will use the code from the last tutorial as our starting point.

Lets get started.

First we add back two lines at the beginning of the animate() function to draw the scoreboard and the bricks.

Right now the ball will move over the bricks without bouncing off them.

We need the ball to reverse X direction if it hits the sides of the bricks, reverse Y direction if it hits the top or bottom of the bricks and damage the bricks every time it touches them.

Lets create functions to check whether the ball is colliding with a brick along the X or Y direction, and to damage the brick if it collides.

The collisionXWithBricks() and collisionYWithBricks() functions return true when they bounce against a brick and automatically call explodeBrick() to weaken the brick and update the score. To start using these functions, we modify the collision checking conditions in moveBall() slightly.

At this point, the ball bounces off the bricks as expected and weakens the brick when it hits them. Once the brick is completely destroyed, it disappears and gives the player an extra points.

Not bad. The game works fine, however there is still something missing.

A little sound tends to give players a much more immersive experience and will make the game more fun. With HTML5 Audio, implementing sound is surprisingly easy.

To play sounds, we load files using the Audio() object and play them using its play() method. Browsers are still a little inconsistent about which formats they support. The OGG file format is an open format supported by both Chrome and Firefox (my favorites), which is why we will stick with them for now.

To create the sound we place the two files at the same location as the HTML file and load them by creating new Audio() objects and storing them in variables. The OGG sound files used here are included with the source code.

To play these sounds, all we need to do is invoke the play() method.

We can play the breaking sound whenever a brick is completely destroyed (inside the explodeBrick() function).

And the bounce sound anytime we change X or Y direction for the ball (inside the moveBall() function)

That’s really all there is to it. We have a game with sound effects, animation, keyboard control and increasing scores written entirely in HTML and Javascript.

To make the game more fun, we can add more interesting brick types, sounds and game mechanics.

In my version of the game, the bricks start falling down, we have Cash bricks to give money, Bomb bricks that explode everything nearby, Laser Ammo bricks that let us shoot laser from the paddle and Spider bricks that shriek and start crawling down at the user. Check out the game to see what you think. Leave a comment if you enjoy the game.

I don’t see much point showing people how to implement the exact same features in a game, because at this point it is fairly simple to do. However if you have an interesting idea that you would like to add to the game, leave me a comment below. If we get a few interesting ideas, we can have one more tutorial where we implement the ideas and create our own new version of the game.

If not, stay tuned to learn how to implement a Real Time Strategy game engine entirely in HTML5 and Javascript. Check out Command and Conquer – Programming an RTS game in HTML5 and Javascript.

You can download the finished source code for this tutorial below.

HTML5 Game Development Tutorial: Breakout Part II – Animation and Keyboard Input

Breakout v0.6 ScreenshotThis is the second in a series of tutorials on developing a full featured version of Breakout.

In the first tutorial we covered drawing primitive objects on the screen using the Canvas element and developing the basic game screen.

In this tutorial, we will use setInterval() to add some animation and capture keydown and keyup events to respond to user input (so we can move the paddle).

We will use the code from the last tutorial as our starting point.

Lets get started.

To animate objects in the game, we need to draw them, move them a little, and then redraw them. To do this, we create an animate() function and place our calls to the drawing functions inside it. For now, lets focus on only the paddle and the ball.

Now we need to figure out a way to call animate() repeatedly at regular intervals. Luckily, Javascript has a function called setInterval() which keeps calling a given function repeatedly at fixed time intervals until the clearInterval() function is called.

We create two functions called startGame() and endGame() to begin the animation and end it. We can also use startGame() to do any pre-game initialization of variables.

Now that the game loop is setup, we need to start moving the elements during the loop.
We start by creating a moveBall() function and calling it from within animate().

The moveBall() function adjusts the ball coordinates by adding the ball speed. We initalize balldeltaX and ballDeltaY when the game starts.

Now that everything is in place, the ball should start moving.
However when we open the file in a browser, we see something weird.

Instead of a moving ball, we have a long black line. The ball keeps moving, however the old balls stay behind, leaving a long trail along the path. We need to clear the earlier objects before drawing new ones.

To do this, we can use the clearRect() method.

This line clears the entire canvas at the beginning of the animation loop. When we run the code now, it looks like a moving ball instead of a long snake.

The next problem is that our ball doesn’t bounce off the walls. It keeps moving past the edge of the canvas and disappears. To fix that, lets add some conditions to check when the ball is moving outside the boundary.

Great! Now the ball is bouncing off the walls properly and when it touches the ground the game ends.

Now lets animate the paddle. To move the paddle, we need to first track the left and right keys and keep track of where the paddle should move during the next animate(). We do this by using the keydown() and keyup() jQuery methods to assign event handlers for these events.

The event handlers check if the key pressed or key released is Left (key code 39) or Right (key code 37) and stores this in a paddleMove variable. We will check this variable every time we animate to see where the paddle needs to move next.

The next thing we need to do is define another movePaddle() function that is called just like moveBall().

We now call this new movePaddle() function from animate() as well.

Great! Now the paddle moves to the left and right when we use the cursor keys.

The last thing we need to do is make the ball bounce if it hits the paddle. We just need to add a condition to the other collision checks in moveBall().

And thats it! The paddle moves perfectly, the ball bounces off the wall and the paddle, and if the ball hits the ground, the game ends.

We have come a long way from an empty rectangle on the browser. Of course, this game is still a little boring with just a ball and paddle.

In the next tutorial, we will bring back the bricks that we drew before, handle the ball colliding with these bricks, and finally increase the score when a brick gets destroyed.

You can download the finished source code for this tutorial below.

Continue to part 3 of this series. HTML5 Game Development Tutorial: Breakout Part III – Collisions, Scoring and Sound

HTML5 Game Development Tutorial: Breakout Part I – Introduction to Canvas

Breakout v0.6 ScreenshotThis is the first in a series of tutorials on developing a full featured version of Breakout. This tutorial will cover drawing primitive objects on the screen using the Canvas element and developing the basic game screen.

Before we get started, check out the finished Breakout game demo. With flying bats, falling spiders, laser turrets and exploding bricks, its probably a little different from the typical breakout game. We will be recreating this game over the series.

All of our development will be for HTML5 capable browsers that properly support the HTML5 Canvas and Audio tags (Chrome, Safari, Firefox, Opera and maybe Internet Explorer 9). Make sure you have one of these browsers.

Now let’s get started.

First we create a simple HTML file with a canvas inside it.

We also include jQuery to make cross browser development easier.

To start using the Canvas we need to get its 2d context which then gives us access to all the drawing methods we need.

With this context object, we now have access to the methods that we will need for our game like fillRect(), clearRect() and drawImage().

Now that we can draw, lets start with creating the paddle.

Note that we store all the parameters in variables so that we can easily modify and reuse them later. Drawing the paddle is as simple as using the fillRect() method.

Now lets draw the ball.

Drawing the ball requires the arc() method to draw a circular shape and the fill() method to fill the shape we just created. While drawing the arc, the starting angle is 0 and the ending angle is 2xPI radians (or 360 degrees) which makes a full circle.

Now lets draw the bricks on top.

First we store the bricks layout in an Array making it easier to visualize and modify. Feel free to try adding a few more rows, or changing the numbers to modify the layout.

We then iterate over each row and column and call the drawBrick() method to place the brick correctly. Within drawBrick(), we use a switch statement to set different fill colors for different types of bricks. This function can be extended to add more brick types.

Finally, lets create a simple scoreboard or status bar below.

This uses the fillText() method to write text at the bottom of the canvas.

We can check the output of the code so far by calling each of the functions that we wrote.

Breakout - Tutorial 1 - ScreenshotThis is the final result. We have a complete game screen with all the elements drawn on it programmatically – the bricks, the paddle, the ball and the scoreboard.

It doesn’t seem like much yet. Everything is static. However, because we stored the parameters in variables, all we need to do to move objects around is change the parameter values and call the same functions again. Thats when things start getting interesting.

In part II of this series, we will use setInterval() to add some animation and capture keydown and keyup events to respond to user input.

You can download the finished source code for this tutorial below.

Continue to part 2 of this series. HTML5 Game Development Tutorial: Breakout Part II – Animation and Keyboard Input

Javascript Game Development with HTML5 Canvas – Breakout released

Breakout v0.6 ScreenshotI started working on my version of the Breakout game as a simple exercise to learn Javascript game programming, using HTML5 Canvas for animation.

The way I see it, Breakout is the “Hello World” of Game development. Pretty much everyone does it when they want to learn the basics. It is probably one of the simplest games to develop though you can choose to make this exercise as easy or as challenging as you like.

In the process of building even the simplest versions of this game you learn most of the essential fundamentals for building any Javascript game, namely –

  1. Drawing primitive objects on the screen using the Canvas element and its Context. (See Introduction to Canvas Tutorial)
  2. Moving objects by using clearRect() and redrawing the object. (See Animation and Keyboard Input Tutorial)
  3. Using setInterval() and setTimeout() to animate objects and run a game loop. (See Animation and Keyboard Input Tutorial)
  4. Capturing keypress, keydown and keyup events and responding to user input. (See Animation and Keyboard Input Tutorial)
  5. And finally rudimentary collision detection. (See Collisions, Scoring and Sound Tutorial)
Β If you then decide to put in a little more effort, you also learn –
  1. Using HTML5 Audio for sound effects. (See Collisions, Scoring and Sound Tutorial)
  2. Using bitmaps with drawImage() for better looking graphics.
  3. Animating arrays of objects simultaneously, each with their own life cycle (like bullets)

I expected this game to be a quick learning experience with limited playable value. I never expected the game to be as much fun as it is. Once I decided to put the game up on my website, the positive feedback that I got was Β very heartening.

Based on feedback, I have decided to continue adding features and developing the game. If you are interested in game development and the making of this game, you can check out the tutorial series on developing Breakout.

The latest version of the game is available at the Breakout Game page. Please check it out and let me know whether you like it.Β I would appreciate any suggestions or constructive criticism (as a player or as a developer) – Any bugs or any playability issues that you find.

If you like the game, please do let me know, and do share it with all your friends. You can use the comments form on the game page.


NowJS and Node.js Tutorial – Creating a multi room chat client

NOTE: This is a really old tutorial. The library used in this example (NowJS) has pretty much been abandoned by the developers for several years. You might still be able to find the NowJS library code at the NowJS Github Page.

However if you are trying to create a HTML5 Websocket/Node.js chat client, I’d recommend using Websocket-Node or Socket.IO instead of NowJS.


Node.js is a server side environment for Javascript. NowJS is a framework built on top of Node.js that connects the client side and server side Javascript effortlessly.

The core of NowJS functionality lies in the now object.The now object is special because it exists on the server and the client.

This means variables you set in the now object are automatically synced between client and server. Also server functions can be directly called on the client and client functions can be called directly from the server.

All in realtime.

You can have a working HTTP server up and running in Node.JS with just a few lines of code. For example –

This little snippet of code will create an HTTP server, listen on port 8080, and send back “Hello World” for every request. That’s it. Nothing more needed.

Using NowJS, communication between the client and server side is just as simple.

Client Side:

In this code snippet, the client side sets a variable to ‘someValue’ and calls serverSideFunction(), which is declared only on the server.

Server Side:

The server side is then able to access clientSideVariable, which is declared only on the client.

All the details such as establishing connections and communicating change of data between the server and client are handed automagically by the framework.

In fact writing code using this framework is so simple, the NowJS hello world example is a working chat client and server written in under a dozen lines of code. Go check it out.

As a simple exercise to get comfortable with the NowJS API, we can modify the chat client example to support multiple chat rooms. Let’s take a look at how easy it is.

Server Side (multiroom_server.js)

1. The first thing we need to do is modify the distributeMessage() function to only send messages to users in the same chat room as the user.

We store the name of the server room on the client side ( When the client calls the distributeMessage() function we send the message to everyone in the same chat room by using getGroup() and using the object instead of the object. (everyone is just a group that contains all users connected to the server)

2. Next we need to handle the client changing chat rooms.

The getGroup() method fetches the group object if it exists andΒ creates a group if it doesn’t already exist. We use the groups addUser() and removeUser() methods to move the client from the old room to the new room.

Thats about it on the server side.

Client Side (multiroom.html)

3. First we add a drop down with the list of server rooms.

4. Next we call the server side changeRoom() function when the user first connects and whenever the drop down is changed.

5. For extra credit, we can allow the server to dynamically provide the list of rooms when the client connects.

The changes required would be –

Server Side:

Client Side:

That’s really all you need to do. We now have a multi room chat client/server with
i) A drop down on the client side with list of server rooms
ii) On connection with server, client auto populates server room list and enters the first room
iii) Changing drop down changes room
iv) Entering new room clears the screen for the user

This is obviously a fairly barebones version (like the original example), but it serves as a proof of concept of all the essential elements of NowJS communication.

The finished code has some extra comments and a few more features. You can download the complete source code below.

Learn how to play pool well in under 30 minutes

Ever wished you could “not suck” at playing pool? Not be considered the worst player in the group? Maybe even win when playing with your “pool player” friends and surprise everyone? Well, I am here to tell you that its not that hard.

It takes surprisingly little effort to beat the average pool player. Most players (outside of pool leagues) have no technique, no consistency and rely on luck or the inexperience of their opponents to win. All it takes to beat them are some basic drills and techniques to improve your consistency.

As someone who loves both to play pool and teach others, I came up with a series of drills that I use to teach complete beginners how to aim and shoot subconsciously. I taught a friend these basics a while ago and she made some amazing cut shots and ran two-three balls at a time during a game about fifteen minutes after going through the drills. Considering it was the second or third time in her life she had held a cue-stick, it was amazing improvement.

It is no substitute for years of practice, but these basics should give any beginner a jump start and have them playing very confidently in less than 30 minutes, easily beating most untrained or amateur players.

These are the essential basics that any beginner needs to go through to become a good intermediate level player

1. Learning to Stand and Hold the Cue Properly – The Stance, The Grip and The Bridge

Beginners tend to stand very awkwardly when they try to shoot pool. Most stand in a way where they have no balance and will fall over if pushed. Some can barely hold the cue steadily because their whole body is shaking from the strain of trying to maintain their weird posture.

Simple Advice? Get comfortable when you stand, hold the cue stick gently, and stay relaxed when you shoot. Check out this video for a quick explanation

When I am teaching, I first get students to learn a good stance and bridge and make sure their cue-ing is straight (using the bottle drill if a bottle if available).

They do not get to touch the cue ball or make a shot until they can maintain their balance in their stance and have a clean, straight stroke. Sometimes I even try to gently push them to test if they are in a stable stance. Ideally you should be so comfortable, you can stay in this position indefinitely.

2. Learning to hit the cue-ball straight and smooth – The Stroke

The next essential element after you learn to stand, is developing a good stroke. Bad stroke is the biggest reason for unpredictability in a persons game. Ever had days when you can make difficult shots, and other days when you can’t even make easy shots? Or find that the cue ball isn’t going where it should? Bad stroke is usually the culprit.

The bottle drill is probably the easiest way to fix a person’s stroke and can teach a beginner in minutes what some players with years of experience don’t realize.

This includes not moving their head during the shot, holding the cue stick gently, and a good clean follow through with no jerkiness in the cue action.

For a detailed explanation, you can read my article on the essential elements of of a good billiards stroke where I go over each of these elements in detail.

Simple Advice? Hold the cue softly. Don’t move any part of the body other than the forearm while shooting. Follow through. And get up only after the cue ball has stopped moving. Check out this video for a quick explanation

When I am teaching, I have the student practice hitting a cue ball from one side of the table into the opposite corner pocket to improve their confidence. If you can hit the cue ball into the opposite corner consistently (the longest possible shot on the table), then your stroke is steady enough.

3. Learning where to hit the cue ball – An Aiming System

Most beginners don’t realize that learning to hit straight in step two is the hardest part of learning pool. If you have learned to accurately hit where you aim, then all you need is someone to show you where to aim the cue ball.

Ever had a friend place a finger on the table to show you the point to aim and you found that by aiming there you made the shot easily? Well, the ghost ball system is a simple little trick to find that point without needing someone else.

You can read my article on the ghost ball system for a detailed explanation of how it works. For longer distance cut shots, I recommend using the parallel line aiming system.

Simple Advice? Imagine a ghost ball pushing the target ball into the pocket from the opposite side and aim at the center of the ghost ball. Check out this video for a quick explanation.

When I am teaching students to aim, I start by giving them progressively increasing cut shots. I start with a straight shot, then an easy cut shot, then a tougher one until they are comfortable with most cut shots.

When aiming, I usually place a second object ball as a ghost ball and ask them to use it to line up. Once they do so, and are down on the shot, I remove the ghost ball and let them shoot. After doing this enough number of times, I make them repeat the shot without a ghost ball. In case they start missing, I bring back the ghost ball and let them shoot a few more shots.

I then try to give them the gist of the aiming without aiming concept of just getting down on the shot and trusting their subconscious mind. Surprisingly, complete beginners are able to pick up the system a lot faster than people who have been shooting for a while.

4. Learning to control the cue ball for the next shot – Position Play

Ever seen a professional player playing? He not only makes the shot, but the cue ball then rolls around the table right next to the next shot. To be able to do this, you need to understand the elements of positioning the ball and shot selection. If you would like to learn position control, check out my new article series on learning cue ball position control.

i) Controlling the Ball – Obviously, for a quick crash course, I ignore the basic elements of position play. For people who have the time, or come back for a second lesson, we go over the stop shot, the follow shot and the draw shot. Check out this video for a quick explanation of follow, draw and stop shots.

ii) Positioning the Ball – Once you can control the cue ball, you need to start using the 90 and 30 degree rule and apply them for simple position play. Then comes learning to use follow, draw and side english to control where the cue ball goes after each shot. I have a separate workout to explain position play. If your are at the stage where you are able to make shots reasonably well, you might want to read my article series on cue ball control and position play, which should give your positioning ability a significant boost.

iii) Shot Selection – The last piece of the puzzle is learning to choose which ball to aim at so you are left with another shot after making the current ball. This is how you can make/run more than one ball at a time. After going over position play, I usually just play while I discuss and illustrate shot selection while using position play.

Thats it!!!

Mastering these fundamentals takes any person from barely able to hold the cue to playing at an APA 2-3 level in under an hour. What separates an APA 2-3 from an APA 4-5 is, more accuracy, consistency, and learning to control the cue ball for position play. And what separates a 4-5 from a 6-7, is inner game, emotional control, and even more consistency.

Of course, There is a LOT more to pool than just aiming or running tables. The fact is, even after learning to aim well, there is still so much to learn and do. Better cue ball control, better position play, better safety play, better kick shots, better bank shots, learning break-out shots. Once you have mastered the basics, I recommend more advanced warmup drills to fine tune your stroke and position play.

At the professional level, its no longer about just shooting skill, but also the mental game of billiards. Once you get good at aiming, bigger things start mattering – such as controlling your own emotions, playing against more experienced players with defensive play or learning to face new experiences and situations that you haven’t faced before.

How far you decide to go and where you decide to stop learning depends entirely on your own journey and motivation behind playing pool.

If you enjoyed this article, you might also enjoy two of my most popular article series – Aiming without Aiming – How to shoot pool like a pro and Cue Ball Position Control Essentials.

If you have any questions or are interested in more details about these steps, please leave a comment below.