More node.js game action

This small game idea felt like fun – there is a man walking at the bottom of your browser window. Adjust the size of the browser window to make the man walk into the green area, i.e. live on.

manmanbg

Try the game here: http://nodelab.earthpeople.se:1112

The man walks faster and faster and more green doors appear. To this you could add extra lives and power packs to catch along the ride. Also control the game in other ways by tampering with your browser, like jump if you scroll down rubber band style.

Anyway, someone said “what about multi-player?” So time for more node.js. When the man exits he simply walks over at the next persons screen, and walks from screen to screen. We made this a player vs. player game, but it could also be a collab. Keep the man alive for as long as possible, and keep track on how far he’s been walking and what part of the world he is in right now.

What we are doing is simply saving the player ids in an array, and walking through the array round robin style.

node.js server code example:


io.sockets.on('connection', function(socket) {
   clients[socket.id] = socket;
   ids.push(socket.id);
   socket.on('manLeaving',function(data){
      nextUser();
   });

   socket.on('join',function(data){
      io.sockets.emit('newUser', {});
      if (ids.length == 1){
         clients[ids[0]].emit('manComes', {});
      }
   });

   socket.on('failed', function(){
      remove(socket.id);
      nextUser();
   });

   socket.on('disconnect', function() {
      remove(socket.id);
   });

   function remove(user){
      delete clients[user];
      var i = ids.indexOf(user);
      if (i > -1) {
         ids.splice(i, 1);
      }
   }

   function nextUser(){
      if (userInTurn = ids.shift()){
         clients[userInTurn].emit('manComes', {});
         ids.push(userInTurn);
      }
   }
});