brandon-barker
9/2/2013 - 7:56 PM

socket.io event listeners

socket.io event listeners

io.sockets.on('connection', function (socket) {
    socket.on('addPlayer', function(player) {
        players[socket.id] = player;
        players[socket.id].id = socket.id;
        console.log("Player " + player.userName + " with id: " + socket.id + " has joined.");
        for (var key in players) {
            console.log("Players: " + key + " : " + players[key].userName);
        }
        if (Object.size(players) == 2) {
            io.sockets.emit('ready', true);
        }

        socket.emit('playerId', socket.id);
    });

    socket.on('logPoints', function(player) {
        if (players[socket.id] != null) {
            players[socket.id].score = player.score;
            console.log(players[socket.id].userName + ' score: ' + players[socket.id].score);
        }
    });

    socket.on('answerQuestion', function (roundNumber) {
        round = roundNumber;
        var imdbRound = getRound(roundNumber);
        imdbRound.answers++;

        if (imdbRound.answers >= 2) {
            if (round < 8) {
                // Move on to the next round
                io.sockets.emit('nextRound', true);
            } else {
                // Game over!
                console.log('Game over!');
                console.log(players);
                io.sockets.emit('gameOver', players);
            }
        }
    });

    socket.on('disconnect', function() {
        if (players[socket.id] != null) {
            start = false;
            imdb.clearRounds();
            round = 1;
            console.log("Player " + players[socket.id].userName + " with id: " + socket.id + " has left.");
            io.sockets.emit('playerLeft', players[socket.id]);
            delete players[socket.id];

            for (var key in players) {
                console.log("Remaining players: " + key + " : " + players[key].userName);
            }
            if (Object.size(players) < 2) {
                io.sockets.emit('ready', false);
            }
        }
    });
});