Example #1
0
    function sendPlayers () {
        var clients = io.sockets.clients();
        console.log(clients.length);

        for (var client in clients) {
            var newPlayer = graphics.Texture( {
                    center : { x : 640, y : 350 },
                    width : 100, height : 100,
                    rotation : 0,
                    moveRate : 100,         // pixels per second
                    rotateRate : 3.14159    // Radians per second
                });
            
            newPlayer.id = client.id;
            newPlayer.setLives(3);
            

            //register the handler
            newPlayer.myKeyboard.registerCommand(input.KeyEvent.DOM_VK_W, newPlayer.forwardThruster);
            newPlayer.myKeyboard.registerCommand(input.KeyEvent.DOM_VK_A, newPlayer.rotateLeft);
            newPlayer.myKeyboard.registerCommand(input.KeyEvent.DOM_VK_D, newPlayer.rotateRight);
            newPlayer.myKeyboard.registerCommand(input.KeyEvent.DOM_VK_SPACE, newPlayer.shoot);
            newPlayer.myKeyboard.registerCommand(input.KeyEvent.DOM_VK_S, newPlayer.warp);

            io.sockets.emit("new player",
            {
                id: newPlayer.id,
                x: newPlayer.getX(),
                y: newPlayer.getY(),
                rot: newPlayer.getRot()
            });
            remotePlayers.push(newPlayer);
        }
    }
Example #2
0
setInterval(function() {
	if(typeof puck != 'undefined') {
		puck = puck.add(dir);
		io.sockets.emit('puck', JSON.stringify(puck));

		if(--lastBounced <= 0) {
			var p = 2 * io.sockets.clients().length,
			index = (Math.floor(puck.getAngle(center) / a) + p)%p,
			p1 = (new paper.Point(Math.cos(a * index), Math.sin(a * index))).multiply(100).add(center),
			p2 = (new paper.Point(Math.cos(a * (index+1)), Math.sin(a * (index+1)))).multiply(100).add(center),
			d = p2.subtract(p1).normalize(),
			n = new paper.Point(-d.y, d.x),
			i = p2.subtract(puck),
			dist = Math.abs(i.dot(n));
			if(dist < 5) {
				if(index%2 == 0) {
					var l = p2.subtract(p1).getLength() / 8,
					paddle = positions[index / 2];
					if(Math.abs(puck.subtract(paddle).dot(d)) > l) {
						return false;
					}
				}
				dir = d.multiply(2 * d.dot(dir)).subtract(dir);
				lastBounced = 3;
			}
		}
	}

	io.sockets.emit('position', JSON.stringify(positions));
}, 16);
Example #3
0
                        chan.get_results(function(results) {
                            if (results.length == 0) { // no votes
                                console.log(('voting ended [no votes]: '+chan.name).red);
                                io.sockets.in(chan.name).emit('gameEnded', {});
                                console.log(('game halted').red);
                                
                                chan.end();
                                io.sockets.clients(chan.name).forEach(function(socket) {
                                    socket.leave(chan.name);
                                });
                                
                            } else {
                                io.sockets.in(chan.name).emit('votingEnded', { responses: results });
                                console.log(('voting ended: '+chan.name).red);
                                setTimeout(function() {
                                    if (haltGame) {
                                        io.sockets.in(chan.name).emit('gameEnded', {});
                                        console.log(('game halted').red);
                                        
                                        chan.end();
                                        io.sockets.clients(chan.name).forEach(function(socket) {
                                            socket.leave(chan.name);
                                        });

                                    } else {
                                        chan.next_round(function() {});
                                        console.log('next round: '+chan.name.red);                              
                                    }
                                }, config.rules.roundEnd_time);
                            }
                        });
Example #4
0
io.sockets.on('connection', function(socket) {
	positions = {};
	var clients = io.sockets.clients(),
	pool = {size: clients.length};
	for(var i=0; i<clients.length; i++) {
		pool.player = i;
		clients[i].send(JSON.stringify(pool));
	}
	a = Math.PI / pool.size;
	puck = center.clone();
	dir = new paper.Point(Math.cos(dir = Math.random()*2*Math.PI), Math.sin(dir));

	socket.on('disconnect', function() {
		positions = {};
		var clients = io.sockets.clients(),
		index = clients.indexOf(socket),
		pool = {size: clients.length - 1};
		for(var i=0; i<clients.length; i++) {
			if(i != index) {
				pool.player = i > index ? i-1 : i;
				clients[i].send(JSON.stringify(pool));
			}
		}
		puck = center.clone();
		dir = new paper.Point(Math.cos(dir = Math.random()*2*Math.PI), Math.sin(dir));
	})
	.on('position', function(position) {
		positions[(position = JSON.parse(position)).player] = position.point;
	});
});
Example #5
0
            chan.get_answers(function(answers) {
                if (answers.length == 0) {
                    console.log(('no answers: '+chan.name).red);
                    io.sockets.in(chan.name).emit('gameEnded', {});
                    console.log(('game halted').red);

                    chan.end();                    
                    io.sockets.clients(chan.name).forEach(function(socket) {
                        socket.leave(chan.name);
                    });
                    
                } else {
                    var answersLong = [];
                    answers.map(function(a) {
                        answersLong.push({ response: a, responseID: a });
                    });
                    answersLong = game.shuffle(answersLong);
                    io.sockets.in(chan.name).emit('roundEnded', {});
                    io.sockets.in(chan.name).emit('votingStarted', {responses: answersLong});
                    console.log(('voting started: '+chan.name).red);
                    
                    setTimeout(function() {
                        
                        chan.get_results(function(results) {
                            if (results.length == 0) { // no votes
                                console.log(('voting ended [no votes]: '+chan.name).red);
                                io.sockets.in(chan.name).emit('gameEnded', {});
                                console.log(('game halted').red);
                                
                                chan.end();
                                io.sockets.clients(chan.name).forEach(function(socket) {
                                    socket.leave(chan.name);
                                });
                                
                            } else {
                                io.sockets.in(chan.name).emit('votingEnded', { responses: results });
                                console.log(('voting ended: '+chan.name).red);
                                setTimeout(function() {
                                    if (haltGame) {
                                        io.sockets.in(chan.name).emit('gameEnded', {});
                                        console.log(('game halted').red);
                                        
                                        chan.end();
                                        io.sockets.clients(chan.name).forEach(function(socket) {
                                            socket.leave(chan.name);
                                        });

                                    } else {
                                        chan.next_round(function() {});
                                        console.log('next round: '+chan.name.red);                              
                                    }
                                }, config.rules.roundEnd_time);
                            }
                        });
                        
                        
                    }, config.rules.vote_time);
                }
            });
Example #6
0
 chan.on('round reset', function(scores) {
     console.log(('round reset: '+chan.name).red);
     io.sockets.in(chan.name).emit('gameEnded', { scores: scores });
     
     io.sockets.clients(chan.name).forEach(function(socket) {
         socket.leave(chan.name);
     });
 });
Example #7
0
world.start(function(worldState) {
	io.sockets.clients().forEach(function(socket) {
		if(worldState.id != socket.id) {
			delete worldState.handData
		}
		socket.emit('update', worldState);
	});
});
Example #8
0
process.on('SIGINT', function() {
    global.log.error("app: gracefully shutting down from SIGINT (Ctrl+C)");

	var clients = io.sockets.clients();

	for (i in clients) {
		clients[i].disconnect();			
	}

});
Example #9
0
		socket.on('getClientUserIds', function(roomName, callback){
		 	var userIds = new Array();
		 	var roomSockets = io.sockets.clients(roomName);
		 	for (var i = roomSockets.length - 1; i >= 0; i--) {
		 		io.sockets.socket(roomSockets[i].id).get('user_id', function(err, userId){
		 			userIds.push(userId);
		 		});
		 	};
		 	callback(userIds);
		});
Example #10
0
io.sockets.on('connection', function (socket) {
  
  console.log("user connected","connections:",io.sockets.clients().length)

  io.sockets.emit('open', { status: 'connected'});
  
  socket.on('disconnect', function () {
    console.log("user disconnected","connections:",io.sockets.clients().length)
    io.sockets.emit('user disconnected');
  });

});
Example #11
0
	socket.on('disconnect', function() {
		positions = {};
		var clients = io.sockets.clients(),
		index = clients.indexOf(socket),
		pool = {size: clients.length - 1};
		for(var i=0; i<clients.length; i++) {
			if(i != index) {
				pool.player = i > index ? i-1 : i;
				clients[i].send(JSON.stringify(pool));
			}
		}
		puck = center.clone();
		dir = new tools.Point(Math.cos(dir = Math.random()*2*Math.PI), Math.sin(dir));
	})
Example #12
0
io.sockets.on('connection', function (socket) {
  clients = io.sockets.clients();
    socket.on('connect', function (message) {
        console.log("Got message: " + message);
        io.sockets.emit(message.nodo, { 'nolike': message.nolike, 'like': message.like, 'comment': message.comment, 'time': message.time, 'avatar': message.avatar, 'name': message.name, 'idusuario': message.idusuario, 'id': message.id, 'parent': message.parent, 'baneo': message.baneo, 'ncomments': message.ncomments, 'nodo': message.nodo});
    });

    socket.on('disconnect', function () {
        clients = io.sockets.clients();
        console.log("Socket disconnected");
        io.sockets.emit('pageview', { 'connections': Object.keys(io.connected).length});
        console.log(clients.length + " clients are connected");
    });
  console.log(clients.length + " clients are connected");
});
Example #13
0
                                setTimeout(function() {
                                    if (haltGame) {
                                        io.sockets.in(chan.name).emit('gameEnded', {});
                                        console.log(('game halted').red);
                                        
                                        chan.end();
                                        io.sockets.clients(chan.name).forEach(function(socket) {
                                            socket.leave(chan.name);
                                        });

                                    } else {
                                        chan.next_round(function() {});
                                        console.log('next round: '+chan.name.red);                              
                                    }
                                }, config.rules.roundEnd_time);
Example #14
0
 client.on('create', function (name, cb) {
   if (arguments.length == 2) {
       cb = (typeof cb == 'function') ? cb : function () {};
       name = name || uuid();
   } else {
       cb = name;
       name = uuid();
   }
   // check if exists
   if (io.sockets.clients(name).length) {
       safeCb(cb)('taken');
   } else {
       join(name);
       safeCb(cb)(null, name);
   }
 });
Example #15
0
                            clientSocket.get('duration', function (derr, duration) {

                                // Game and Duration must be the same so players are playing same game and duration
                                if (parseInt(game) === parseInt(data.game) && parseInt(duration) === parseInt(data.duration)) {

                                    // Join the client to the room with a waiting client playing the same game and duration
                                    socket.join(room.slice(1));
                                    socket.set('room', room.slice(1));
                                    socket.set('game', data.game);
                                    socket.set('duration', data.duration);
                                    socket.emit('in_room', {gameRoom:room.slice(1)});
                                    inRoom = true;

                                    //var clientSocketId = clients[0];
                                    socket.set('playerName', data.playerName);

                                    // go through all the clients
                                    _.each(io.sockets.clients(), function (clientSocket) {

                                        if (clientSocket.id === socket.id) {
                                            // clientSocket.get('playerName', function (err, playerName) {
                                            socket.broadcast.emit('opponent_name', {name:data.playerName});
                                            //});
                                        }
                                        else {
                                            clientSocket.get('playerName', function (err, playerName) {
                                                clientSocket.broadcast.emit('opponent_name', {name:playerName});
                                            });
                                        }
                                    });

                                    gameModel.getQuestions(data.game, function (result) {
                                        io.sockets.in(room.slice(1)).emit('start',
                                            {
                                                // send the first random question
                                                question:result[Math.floor(Math.random() * result.length) + 1],

                                                // and the number of questions
                                                questionCount:result.length,
                                            });
                                    });

                                }
                            });
Example #16
0
app.all("/stoot/triggerEvent", function (req, res) {
    var channel = req.param('channel');
    var event = req.param('event');
    var data = req.param('data') || {};
    var apiKey = req.param('apiKey');
    console.log("Received params: " + [apiKey, channel, event, data]);
    if (!apiKey) {
        res.status(500).send({error:'Missing API key', success:false})
    } else if (!channel) {
        res.status(500).send({error:'Missing channel name', success:false})
    } else if (!event) {
        res.status(500).send({error:'Missing event name', success:false})
    } else {
        console.log(io.sockets.clients(apiKey + "/" + channel));
        console.log("Sending message", data, "to", apiKey + "/" + channel);
        io.sockets.in(apiKey + "/" + channel).emit(event, data);
        res.status(200).send({message:'Event triggered', success:true})
    }
});
Example #17
0
function handleSendMessage(socket, data) {
	console.log('recv send_message');
	console.log('sockets in room ' + data.groupid);
	console.log(io.sockets.clients(data.groupid).length);
	redis.client.hget('rooms', 'room:' + data.groupid, function(err, room) {
		if (err) throw err;
		room = JSON.parse(room);

		Users.get(data.uid).then(function(user) {
			var newMessage = {
				user: {
					uid: user.id,
					username: user.username
				},
				message: validator.escape(data.message)
			};

			room.attributes.messages.push(newMessage);

			redis.client.hset('rooms', 'room:' + data.groupid, JSON.stringify(room), function() { });
			io.sockets.in(data.groupid).emit('new_message', newMessage);
		});
	});
}
Example #18
0
 socket.on('disconnect', function () {
     clients = io.sockets.clients();
     console.log("Socket disconnected");
     io.sockets.emit('pageview', { 'connections': Object.keys(io.connected).length});
     console.log(clients.length + " clients are connected");
 });
Example #19
0
    var twoPlayerGame = function (socket, data) {
        // look through all the rooms to find one with only one player
        var inRoom = false;
        var rooms = io.sockets.manager.rooms;

        for (var room in rooms) {
            var clients = rooms[room];

            // If the room has one player in it and it is not the default room
            if (room !== '' && clients.length === 1) {

                var clientSocketId = clients[0];

                // go through all the clients
                _.each(io.sockets.clients(), function (clientSocket) {

                    if (clientSocket.id === clientSocketId) {

                        // get the game data on the client already in the room for comparison with the newly joining client
                        clientSocket.get('game', function (err, game) {

                            // get the duration data of the client already in the room
                            clientSocket.get('duration', function (derr, duration) {

                                // Game and Duration must be the same so players are playing same game and duration
                                if (parseInt(game) === parseInt(data.game) && parseInt(duration) === parseInt(data.duration)) {

                                    // Join the client to the room with a waiting client playing the same game and duration
                                    socket.join(room.slice(1));
                                    socket.set('room', room.slice(1));
                                    socket.set('game', data.game);
                                    socket.set('duration', data.duration);
                                    socket.emit('in_room', {gameRoom:room.slice(1)});
                                    inRoom = true;

                                    //var clientSocketId = clients[0];
                                    socket.set('playerName', data.playerName);

                                    // go through all the clients
                                    _.each(io.sockets.clients(), function (clientSocket) {

                                        if (clientSocket.id === socket.id) {
                                            // clientSocket.get('playerName', function (err, playerName) {
                                            socket.broadcast.emit('opponent_name', {name:data.playerName});
                                            //});
                                        }
                                        else {
                                            clientSocket.get('playerName', function (err, playerName) {
                                                clientSocket.broadcast.emit('opponent_name', {name:playerName});
                                            });
                                        }
                                    });

                                    gameModel.getQuestions(data.game, function (result) {
                                        io.sockets.in(room.slice(1)).emit('start',
                                            {
                                                // send the first random question
                                                question:result[Math.floor(Math.random() * result.length) + 1],

                                                // and the number of questions
                                                questionCount:result.length,
                                            });
                                    });

                                }
                            });
                        });
                    }
                });

            }

        }

        // There are no rooms to join the create a new room for the client
        if (!inRoom) {
            var room = uuid.v4();
            socket.join(room);
            socket.set('room', room);
            socket.set('game', data.game);
            socket.set('duration', data.duration);
            socket.emit('in_room', {gameRoom:room});
            socket.set('playerName', data.playerName);

        }
    };
Example #20
0
 socket.on('disconnect', function () {
   console.log("user disconnected","connections:",io.sockets.clients().length)
   io.sockets.emit('user disconnected');
 });
exports.getAllSockets = function(){
	if(!initialized){
		return;
	}
	return socketIO.sockets.clients();
};
Example #22
0
 socket.on("disconnect", function () {
     if (autoClose && io.sockets.clients().length === 0) {
         server.close();
     }
 });