factor_za factor_za - 5 months ago 16
jQuery Question

Socket.io event that waits for both players to have chosen answers

I am busy learning socket.io and trying to figure out how to make a bit of JS only fire off once both users have clicked their answers.

The code in question I am wanting to fire off is:



// Random number function
function randomIntFromInterval(min,max){
return Math.floor(Math.random()*(max-min+1)+min);
}

// Check if correct + send to server
function correctAnswer() {
var correct = true;
socket.emit('playerCorrect', {answer: correct});
console.log(correct);
buttonRemover();

}
// Check if wrong + send to server
function incorrectAnswer () {
var wrong = false;
socket.emit('playerWrong', {answer: wrong});
buttonRemover();
}

socket.on ('updatePlayer', function (data) {
if (data.answer === true) {
console.log ('Player got it right! ' + data.answer);
}else if (data.answer === false) {
console.log ('Player got it wrong! ' + data.answer);
}

});




What those functions are sending data to the server to let the server know if the answer was correct or not.



socket.on('playerCorrect', function (data) {
io.sockets.emit('updatePlayer', data);
dataRequest();
});

socket.on('playerWrong', function (data) {
io.sockets.emit('updatePlayer', data);
dataRequest();
});




However I am only wanting this stuff to happen when both clients have clicked an option. Is there a way to track this?

Answer

For a single set of users, it would suffice to do:

// Global variables for maintaining game states
// TODO: Clear this when a new game is started
var nrecieved = 0;
var responses = {}; // Socket id to response


function finish(/* todo: maybe also pass in a game_id or one of the user ids to know which game is being played */){
   // Loop through users in game and send them their responses
   for(var id in responses){
        if(responses.hasOwnProperty(id)){
             // Send the response
             io.to(id).emit('updatePlayer', responses[id]);
        }
   }
}

socket.on('playerCorrect', function (data) {
    responses[socket.id] = data;
    nrecieved++;

    if(nrecieved == 2){
        finish();
        dataRequest();
    }
});    

socket.on('playerWrong', function (data) {
    responses[socket.id] = data;
    nrecieved++;

    // Only respond if both responses received
    if(nrecieved == 2){
       finish();
       dataRequest();
    }
});

socket.id is a unique identifier assigned to each socket which may be useful. For multi-game performance, you will probably need to have more logic to maintain a list of which sockets/players belong to which games and then use that to direct messages to the correct pairs of users.