HTML and CSS Reference
In-Depth Information
socket.on('move',function(data) {
socket.get('partner',function(err,partner) {
if(partner) {
partner.volatile.emit('move',data);
}
});
});
socket.on('ball',function(data) {
socket.get('partner',function(err,partner) {
if(partner) {
partner.volatile.emit('ball',data);
}
});
});
socket.on('disconnect',function() {
socket.get('partner',function(err,partner) {
if(partner) {
partner.emit('end');
partner.set("partner",null);
}
});
socket.get('game',function(err,game) {
var idx = games[game].indexOf(socket);
if(idx!=-1) games[game].splice(idx, 1);
});
});
});
Now run npm install from the command line in that directory to grab the dependencies.
On new connections the server finds the first entry in the games array that has less than two entries. This
array keeps sets of players who are playing together paired. If it can't find an entry that has fewer than two
players, it adds a new entry to the array for the new game. In both cases it keeps the index in the games array to
keep track of the game a socket is associated with.
The game uses Socket.io's capability to associate extra data with a socket via socket.set and sock-
et.get .
If after adding the socket to the current game there are two players for the current game, the server sets one
to be the master (the client that controls the canonical simulation of the ball) and one to be the slave. It also adds
an item of data called partner to each socket that maps to its paired socket.
If you were to take this example to a more complete lobby-style game, you could create an object for each
game that keeps a list of players in that game and makes it easy to send messages to all players in that game.
Search WWH ::




Custom Search