Check out the NEW! Corona Multiplayer Networking SDK to build Real-time Games on Mobile Phones iPhone.
This is an HTML5 Multiplayer Game Tutorial.
This page is the foundation for creating your own Monetizable
HTML5 games and applications with Live Data Streaming.
You will learn how to create a game and earn money from
internet game players.
Use
Check out the new Corona Multiplayer Networking SDK to build Real-time Games on Mobile Phones iPhone.
If you are here to learn how to make a Multiplayer Game, continue reading! If you are here to play the HTML5 Multiplayer Game to Earn Credits and Increase Your Customer Level, then go play the game! The information below explains how to create your own HTML5 Multiplayer Games and earn money from players.
The HTML5 Multiplayer Game 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.
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.
The HTML5 Multiplayer Game above is tied to your
So how does it work?
When a player clicks the Play Button, a message is sent to the
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 Real-time Analytics.
// RECEIVE MESSAGES PUBNUB.subscribe({ channel : 'my-game-channel', callback : function(message) { // A message is received here and it contains // the information from the original publish. // With this hook, you update the Player UI. // The message in this case contains information that // a new purchase has been placed. // You take this advantage to update // the HTML interface with the new balance. } });
Get your PUBNUB JavaScript Include Here.
The code above demonstrates the simplicity of the
// SEND A MESSAGE with JavaScript PUBNUB.publish({ channel : 'my-game-channel', message : { // You broadcast the total purchase dollar amount. // Everyone will receive this message via PUBNUB.subscribe() total_purchases : '$1,200.00' } });Data Streaming is easy with
// SEND A MESSAGE with Lua Corona SDK
multiplayer:publish({
channel = "lua-corona-demo-channel",
message = { "1234", 2, 3, 4 }
})
// SEND A MESSAGE with Objective-C
Pubnub *pubnub = [[Pubnub alloc]
publishKey: @"publish_key"
subscribeKey: @"subscribe_key"
secretKey: @"secret_key"
sslOn: NO
origin: @"pubsub.pubnub.com"
];
[pubnub
publish: @"my-game-channel"
message: [NSDictionary
dictionaryWithObjectsAndKeys:
@"total_purchases", @"$1,200.00",
nil]
deligate: [Response alloc]
];
// SEND A MESSAGE with RUBY
pubnub = Pubnub.new( 'publish_key', 'subscribe_key' )
pubnub.publish({
'channel' => 'my-game-channel',
'message' => { 'total_purchases' => '$1,200.00' }
})
// SEND A MESSAGE with PHP
$pubnub = new Pubnub( 'publish_key', 'subscribe_key' );
$pubnub->publish(array(
'channel' => 'my-game-channel',
'message' => array( 'total_purchases' => '$1,200.00' )
));
// SEND A MESSAGE with Python
pubnub = Pubnub( 'publish_key', 'subscribe_key' )
pubnub.publish({
'channel' : 'my-game-channel',
'message' : { 'total_purchases' : '$1,200.00' }
})
// SEND A MESSAGE with Perl
my $pubnub = Pubnub->new( 'publish_key', 'subscribe_key' );
$p->publish( {
channel => 'my-game-channel',
message => { 'total_purchases' => '$1,200.00' }
}),
// SEND A MESSAGE with .NET C#
Pubnub pubnub = new Pubnub( "publish_key", "subscribe_key" );
Dictionary<string,string> message = new Dictionary<string,string>();
message.Add( "total_purchases", "$1,200.00" );
pubnub.publish( channel, message );
// SEND A MESSAGE with Java
Pubnub pubnub = new Pubnub( "publish_key", "subscribe_key" );
JSONObject message = new JSONObject();
try { message.put( "total_purchases", "$1,200.00" ); }
catch (org.json.JSONException jsonError) {}
JSONArray info = pubnub.publish( 'my-game-channel', message );
If you have trouble getting started, visit the
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
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:
<-- STEP 1 of 4: CSS3 --> <style> #my-element-div { cursor: pointer; background: #f90; color: #fff; /* Specify that this element will animate for 0.8 seconds if changes are made via JavaScript. */ transition: all 0.8s; -o-transition: all 0.8s; -moz-transition: all 0.8s; -webkit-transition: all 0.8s; } </style> <-- STEP 2 of 4: HTML Div Element --> <div id=my-element-div>CLICK THIS TEXT!!!</div> <-- STEP 3 of 4: PUBNUB JavaScript --> <div> pub-key="demo" sub-key="demo" ssl="off" origin="pubsub.pubnub.com" id="pubnub" </div> <script src="http://cdn.pubnub.com/pubnub-3.1.min.js"></script> <-- STEP 4 of 4: Applicatoin Logic --> <script>(function(){ var my_element_div = PUBNUB.$('my-element-div'); PUBNUB.bind( 'mousedown,touchstart', my_element_div, function() { if (PUBNUB.attr( my_element_div, 'clicked' ) != 'yup!') { PUBNUB.attr( my_element_div, 'clicked', 'yup!' ); PUBNUB.css( my_element_div, { color : '#f90', backgroundColor : '#fff' } ); } else { PUBNUB.attr( my_element_div, 'clicked', ' ' ); PUBNUB.css( my_element_div, { color : '#fff', backgroundColor : '#f90' } ); } } ); })();</script>
Get your PUBNUB JavaScript Include Here.
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:
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 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:
/*
USAGE EXAMPLE:
request(
'/player-status', // URL
{ 'key' : 'val' }, // JSON PARAMATERS
function(response){ ... } // CALLBACK FUNCTION
);
*/
var NOW = 1;
function request( url, data, callback ) {
var jsonp = PUBNUB.create('script')
, uni = 't'+(NOW++)+(+new Date);
window[uni] = callback || function(){};
data['callback'] = uni;
jsonp.src = url + '?data=' + escape(JSON.stringify(data));
PUBNUB.search('body')[0].appendChild(jsonp);
}
The
request(
'/click',
{ click : 1 },
function(response){
// The "response" var contains information
// from the applicatoin server.
console.log(response);
}
);
The code above is called when you click the "Play!" button.
When this happens the request() function issues a request
to the following URL:
/*
Request:
/click?data={"click":1,"callback":"t123456"}
Encoded Request:
/click?data=%7B%22click%22%3A1%2C%22callback%22%3A%22t123456%22%7D
The request must be encoded.
Calling the request(...) function does this for you.
*/
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:
def jsonp_response( web, response ):
## Get the Data URL Varaible
request = json.loads(urllib.unquote(web.request.get( 'data', '' )))
## Extract the Callback
callback = request['callback']
## Set Appropriate Header for JSONP
web.response.headers["Content-Type"] = 'text/javascript'
web.response.headers["Cache-Control"] = 'no-cache'
## Respond with Padded JSON
web.response.out.write(callback + '(' + json.dumps(response) + ')')
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:
t123456({"message":"You lost a gear and a few bolts","credits":-10})
This can be done with every web server.
Python is used here for simplicity.
Important details for the server are:
Exceed the expectations of your players by offering
PUBNUB.bind( 'keydown', chat_input, function(e) {
// Did the user press the ENTER KEY?
if (e.keyCode == 13) return new_chat_line();
// Send Message
// (What you typed so far)
send_keystroke();
// Very Important to Return True
// This allows the keyup event to fire.
return true;
} );
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
// Create an Updater Function // This provides a rate limited interface // to Events; such as the KeyDown Event. var send_keystroke = updater( function() { // You add a Timeout to allow the DOM // to update every keystroke // before the message is published. setTimeout( function() { // Publish The Message, even // if the message is incomplete. publish_comment(); }, 10 ); }, 150 );
// Here is the updater() function.
function updater( fun, rate ) {
var timeout
, now = function(){return+new Date}
, last = 0
, runnit = function() {
var right_now = now();
if (last + rate > right_now) {
clearTimeout(timeout);
timeout = setTimeout( runnit, rate );
}
else {
last = now();
fun();
}
return true;
};
return runnit;
}
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.
// Trim White Space var trim_rx = /^\s*|\s*$/g // Chat Message ID , chat_box_count = +new Date() // Prevent Displaying Bad Characters and Scripts , safe_rx = /[\r\n<>]/g; // Post Comment function publish_comment() { // Prevent Publishing Empty Messages if (!chat_input.value.replace( trim_rx, '' )) return; // If the player isn't ready, don't send. // We need the Player's name for example. if (!player.ready) return; // Send a network Broadcast using PubNub. PUBNUB.publish({ channel : 'my-game-channel', message : { action : 'chat', // Player Details (name, public_id, etc) player : player, // Only allow 200 Character Messages. // Truncate anything longer. text : chat_input.value.slice(-200).replace( safe_rx, '' ), // Each player will have multiple // chat lines during gameplay. // When you press the Enter Key, a new // chat line is generated and the next // ChatBox is displayed on a new line. // This allows you to send updates // to the current line of text. box_id : player.info.uuid + '-' + chat_box_count, // This is a very important concept // with real-time messaging. // Messages in the cloud are // not always delivered in order // due its asynchronous nature. // Therefore you must associate a // timeline to track // message order. last : ++chat_publishes } }); }
// Setup the Subscribe Callback PUBNUB.subscribe({ channel : 'my-game-channel', callback : function(message) { // Capture UUID (the Public ID of a Player) var uuid = 'uuid' in message && message.uuid || 'player' in message && message.player.info.uuid; // Is this a new Player? if (!players.get(uuid)) { players.add(uuid); } // Render the Message on Screen receive_comment(message); } });These are the important parts when you create a Real-time 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.
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
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:
<div
pub-key="PUBLISH_KEY" REMOVE THIS LINE
sub-key="demo"
ssl="off"
origin="pubsub.pubnub.com"
id="pubnub"></div>
<script src="http://cdn.pubnub.com/pubnub-3.1.min.js"></script>
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.
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 Social Gold 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
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 love developers. Here are resources for you, the developer, to allow you to build amazing HTML5 Multiplayer Games and Applications: