Tutorial: How To Build HTML5 Multiplayer Game Foundation

This is an HTML5 multiplayer game foundation tutorial. This page is the foundation for creating your own monetizable HTML5 games and applications with realtime data streaming. You will learn how to create a game and earn money from internet game players. Use PubNub to engage your players with your HTML5 multiplayer and flash games. The PubNub game below is a completed game demonstrating the power of PubNub HTML5 gaming and monetization.

Check out the new Corona Multiplayer Networking SDK to build realtime Games on Mobile Phones iPhone.

game foundation

If you are here to learn how to make a Multiplayer Game foundation, continue reading! The information below explains how to create your own HTML5 Multiplayer Games and earn money from players.

The HTML5 Multiplayer Game foundation is best played on Google Chrome, FireFox 4, Safari and Mobile Safari. Other browser will work, however CSS3 animations will not render. A simple User Interface will be displayed if you are not running an HTML5 browser.

Below is a screenshot of the finished product:

game foundation

PubNub Message Credits

Message Credits are won as you play the HTML5 Multiplayer Game. These are freebee credits which you normally pay for by enabling billing on your account. PubNub is a Cloud-Hosted Service for HTML5 Data Streaming, and much more. You are able to use your Message Credits for the PubNub Cloud-Hosted Service. Message Credits are used to stream data to your players.

The HTML5 Multiplayer Game above is tied to your PubNub Account. When you win credits in the game, you are incrementing your account balance! Use your credits towards the PubNub Cloud-Hosted Service for realtime data streaming powering the multiplayer games you build. To ensure your account is billable and stays active beyond the free quota and beyond the credits you won by playing the HTML5 Game, you must enable billing on your account.

So how does it work? When a player clicks the Play Button, a message is sent to the PubNub Cloud. This message is intended to be broadcast to everyone playing the HTML5 Multiplayer Game. PubNub provides this vital community connection. Learn more about the PubNub Cloud-Hosted Service for realtime Data Streaming and Broadcasting Here.

Payments Display Ticker

Enhance the sense of community by displaying the total dollar contribution provided by the player’s. This is demonstrated in the HTML5 Multiplayer Game above where the dollar amount is highlighted in green. Offering this information provides entertainment and engages players on an analytic level. You can think of these numbers as realtime Analytics.

PubNub provides Live Data Streaming which enables applications such as realtime Analytics. The first step in creating a Live Data Stream is to setup a PUBNUB.subscribe() channel on the mobile phone or web browser.’

Get your PUBNUB JavaScript Include Here.

The code above demonstrates the simplicity of the PubNub Data Streaming Cloud API. Calling PUBNUB.subscribe() is the first step of two. The Subscribe Function will wait and listing for a message to be sent accros the network. A message is sent by calling Publish function. The next step is calling PUBNUB.publish() to send messages to the subscribers.

Data Streaming is easy with PubNub. This engages your game players with Live, realtime Data provided by PubNub’s Mass Broadcasting Capabilities. Note that you may send a message from every location including Mobile Phones (iPhone, Android), Web Servers (Apache, Tomcat and NginX), Web Browsers (FireFox, Chrome, Internet Explorer), your laptop and more. The following is an example of publishing messages on multiple platforms and languages:

If you have trouble getting started, visit the PubNub forums at The GitHub Issue Center. Search for you answer first, if you don’t find it submit a new issue.

Payment Model

Virtual Currency provides a medium for extended playability for the player. This allows the player to engage the game longer and provide value to the online community. To broaden your target audience, make sure to offer game upgrades as an optional experience. Additional areas may be introduced offering extra gameplay. In the case of the PubNub HTML5 Multiplayer Game, the players are able to advance their account quickly, allowing faster credit accumulation. With a higher player level, higher scores are achievable.

CSS3 Animations with HTML5

Motion gameplay and good looking aesthetics are achievable with CSS3. If your web browser supports CSS3 Animations, then the HTML5 Multiplayer Game on this page will render them! CSS3 Animation is supremely simple to implement. Start by defining a normal CSS Selector followed by some JavaScript:

If your web browser does not support CSS3 Animations, then the div will toggle without a transition. However if you are running Chrome, Safari, Mobile Safari, FireFox 4 or Opera then you will see a smooth transition of colors. You must do the following to achieve CSS3 Transitions:

  1. Set up a style sheet defining your element and animation properties.
  2. Add the HTML <div> element.
  3. Include your PUBNUB JavaScript API.
  4. Add JavaScript to toggle display properties of the <div> element.

Animations indicates that happening is happening in the game and provides a moment of time for the player to react. Smooth animated motions are detectable and intriguing to the human eye. Use CSS3 animations to engage your users playing your games and using your application. Animations enhance every User Interface experience including Games, Analytics, Messaging and more.

JSONP Request Game Foundation

JSONP works everywhere. From this point on, use only JSONP. Drop AJAX XHR (XML HTTP Request). There are no limitations to JSONP and is therefore recommended as your data transport choice. JSONP is simple to implement and light weight with many invisible benefits which make application building great. The following code is the function to issue a JSONP request:

The PubNub HTML5 Multiplayer Game uses JSONP to call Google App Engine to communication player activity. JSONP is compatible with every application server including Apache, NginX, Tomcat and more. In the HTML5 Multiplayer Game, the JSONP request function is called when you click the “Play!” button.

The code above is called when you click the “Play!” button. When this happens the request() function issues a request to the following URL:

Note that the request data is encoded and must be decoded by the server in order to process the request. There is an additional detail needed on the server in order to respond with the correct information:

The code above is written in python using a common WSGI control pattern. The “data” URL variable is extracted, URL decoded and JSON decoded. The “callback” variable is extracted to provide the JSON Padding. The result of this request looks like this:

This can be done with every web server. Python is used here for simplicity. Important details for the server are:

  1. Receive request from Client and decode URL Variables including the “callback” wrapper “t123456″.
  2. Set the “Content-Type” and “Cache-Control” headers.
  3. Respond with JSON wrapped with the “callback” (“t123456″).

That’s it! You now have the recipe to create JSONP requests.

Streaming Keystroke Chat

Exceed the expectations of your players by offering PubNub Instant Keystroke Chat experience. Quickly deliver the experience to your players providing “Instant Gratification”. Since the “Play!” button has a timer associated with it, you need to keep your players active by offering a community chat interface.

PubNub makes streaming data easy and instant. Streaming Keystroke Chat hooks on the Keydown Event. When you press a key on your keyboard, an event is fired. A hook is placed into this keystroke event and used to publish a message of the typed text. To prevent data overload on the client stream, you must wrap the Keystroke Event in a Delayed Callback. This provides an improved usability experience for end users as the User Interface is redrawn with locking. The following code provides the foundation for creating a stream of data based on Keyboard Events (and Virtual Keyboard Events on Mobile Phones/Tablets).

To prevent User Interface Locking, you must rate limit keystroke publishes to 3 or 4 per second. Otherwise the interface will lock causing unpleasant typing experiences. Also you are recommended to rate limit the message delivery to prevent rapid PubNub Message Credit Drain.

Now you have a rate limited function which may be called thousands of times per second, yet only triggers the event 3 to 4 times per second. This triggers your function to send the must up-to-date message at a reasonable rate. Next let’s take a look inside the publish_comment() function to see what is happening.

These are the important parts when you create a realtime Keystroke Chat. Note there is a portion of UI logic left undiscussed as that is up to you to decide how this should look. The most important part is for you to rate limit the event bindings to provide a responsive user interface.

Security Implementation

Application security comes in several layers include: Client Logic, Server Logic, Transport Encoding, SSL Encryption, Message Signing and Access Levels. The HTML5 Multiplayer Game uses Client and Server Logic to provide a layer of security around data tracking for credits and tokens. For example, you are required to log in with your Google account to send authenticated requests; like the “Play!” button. These requests are for interaction related to tokens and credit currency.

Additionally, logic is implemented in the JavaScript to provide an improved user experience; preventing script injection. For example, if you change your player name during the game, you are limited by 10 to 20 characters maximum. This logic is implemented in the JavaScript on every client. This means if a hacker were to attempt to deliver a name longer than 20 characters, then truncation occurs on the client system. Therefore the hacker is not able to affect other players.

Further layers of Security are available with the PubNub Cloud-Hosted Service. SSL Encryption is an industry standard for keeping messages secret. Because of the High CPU cost, encrypted messages are more expensive, and totally optional. PubNub counts SSL Encrypted messages as double. Learn more about PubNub Pricing here.

Message Signing is a process of including a hashed value with the published message. The hashed value is calculated by the sum characters of the request string with the addition of your account’s Secrete Key. You can find your secret key here. Message Signing provides additional insurance confirming the origin of the message to be authentic.

The last security implementation is the most popular and most recommended. This process involves removing the Publish Key from your JavaScript. This prevents hackers from sending messages. You can accomplish this security method by deleting the reference to the Publish Key in your JavaScript Include. You can find your JavaScript Include here. Remove the line that looks like this:

By hiding the publish key, you prevent everyone from sending messages except yourself. This means the PUBNUB.publish() function will no longer work. Now you must use one of the Server APIs located here to send your messages securely.

Monetization

There are gracious consumers who will support your applications and games thru purchases. However you must offer them a way to give you money! You must setup an interface which accepts multiple payment options. This has been traditionally time consuming to setup. Not anymore! Use PlaySpan or Live Gamer to quickly setup your payment gateway. Offer every payment option to allow players to give you money. You must provide a way for your players to submit payments.

After players submit a payment, you may provide enhanced or continued gameplay. The PubNub HTML5 Multiplayer Game extends gameplay by reseting the game timer. This gives you the opportunity to continue playing and increase your Customer Level Quickly. You are a happy player!

HTML5 Game Compatibility

This page is totally compatible with every web browser, mobile phone and tablet device. iPhone, iPad, Android, Samsung Galaxy, Android, FireFox, Google Chrome, Internet Explorer, Safari, Mobile Safari and more!

We ♥ Developers

We love developers. Here are resources for you, the developer, to allow you to build amazing HTML5 Multiplayer Games and Applications:

Get Started
Sign up for free and use PubNub to power multiplayer gaming

Start Building Realtime Apps Now!

Loading...