Skip to content

Instantly share code, notes, and snippets.

@ToeJamson
Last active December 27, 2015 19:09
Show Gist options
  • Select an option

  • Save ToeJamson/7375145 to your computer and use it in GitHub Desktop.

Select an option

Save ToeJamson/7375145 to your computer and use it in GitHub Desktop.
Tutorial: How To Build HTML5 Multiplayer Game Foundation
// 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.
}
});
<-- 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>
/*
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);
}
request(
'/click',
{ click : 1 },
function(response){
// The "response" var contains information
// from the applicatoin server.
console.log(response);
}
);
/*
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.
*/
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) + ')')
t123456({"message":"You lost a gear and a few bolts","credits":-10})
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;
} );
// 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;
}
// 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
}
});
}
// 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'
}
});
// 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);
}
});
<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>
// 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 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 );
// SEND A MESSAGE with Python
pubnub = Pubnub( 'publish_key', 'subscribe_key' )
pubnub.publish({
'channel' : 'my-game-channel',
'message' : { 'total_purchases' : '$1,200.00' }
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment