Skip to content

Instantly share code, notes, and snippets.

@ruby0x1
Created March 27, 2012 14:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ruby0x1/2216585 to your computer and use it in GitHub Desktop.
Save ruby0x1/2216585 to your computer and use it in GitHub Desktop.
Multi-player games in HTML5 : Server Side Session Class
var Session = Class.extend({
init : function( socket ) {
this.socket = socket;
this.serverid = UUID();
this.initListeners();
},
initListeners : function() {
//socket.io specific listeners
this.socket.on('error', this.onError.bind(this));
this.socket.on('disconnect', this.onDisconnect.bind(this));
//custom handlers
//Called when first connecting, this is to check if a game can be found
this.socket.on('onConnected', this.onConnected.bind(this));
//This connection can send us onClientInput
this.socket.on('onClientInput', this.onClientInput.bind(this));
},
//if an error happens
onError : function( e ) {
console.log('\t :: Server :: Session has an error id : ' + this.serverid);
console.log( e );
},
//when the client receives their key, the ping back with their information.
//effectively registering themselves as available to play a game or not.
onConnected : function( e ){
console.log('\t :: Server :: ok, a client is asking to play ! ' + this.serverid );
var indexofplayer = -1;
//search for the next available player to play against
for( var i = 0; i < server.connections.length; ++i ) {
//Check all players on the server for one that isn't in a game.
//This person is waiting for someone to join them.
if( !server.connections[i].ingame && server.connections[i].id != this.id) {
indexofplayer = i;
break;
} //if !me and not in game already
} //for each connection
//If we found a player
if(indexofplayer != -1) {
//Fetch the player socket, as we are now classed as an opponent
var player = server.connections[ indexofplayer ];
//Debug!
console.log('\t :: Server :: found a player to play against !!' + otherplayer.serverid);
//create a new server instance for this game
var game = new Game( player, this );
//create the game information states, and tell players
game.create();
//add to the list of games that are active
server.games.push( game );
} else {
//Debug
console.log('\t :: Server :: found nobody to play against! I\'ll wait! ' + this.serverid);
//Ok, so no players.. Wait around for one
this.socket.emit('waitForPlayer', {});
}
},
//when a client leaves
onDisconnect : function(e){
console.log('\t :: Server :: A player has disconnected ' + this.serverid );
//Remove the player from the list of server connections
server.connections.erase(this);
console.log('\t :: Server :: There are now ' + server.connections.length + ' players online');
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment