factor_za factor_za - 5 months ago 39
Javascript Question

Wait on client responses to run code socket.io?

I have some code that I am only trying to run when both clients have put in their answers. These are the functions finish and datarequest();.

At the moment I have it where it waits for both responses correctly and doesn't emit just after one client answering. The problem comes in is that it is not reaching my if statement.

Is there a way to ++ nrecieved++; based on the type of answers the clients give. ie. Two wrong answers, two correct answers or one of each? Basically to get it to run nrecieved++; based on both client responses together?

var nrecieved = 0;
var responses = {}; // Socket id to response

function finish(){
// 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) {
nrecieved++;
responses[socket.id] = data;
answerValidation(nrecieved);
});

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

console.log(nrecieved);
function answerValidation(value) {
nrecieved = value + value;
console.log(value);
if(nrecieved == 2){
finish();
dataRequest();
}
}


EDIT:

Included pastebin: http://pastebin.com/y6akQ6Sh

Client Side:

// On click of a answer button check if it is the correct answer if it is tell the server
$(document).on('click', '.answerButton' , function(){

function answerChecker(element){
if(element == gaPosition) {
correctAnswer();
}
else {
console.log("Incorrect!");
incorrectAnswer();
}
}

var clickedButton = $(this).data('button');
console.log(clickedButton);
answerChecker(clickedButton);

});

function buttonRemover() {
$(".buttonContainer").removeClass("fadeInRightBig");
$(".buttonContainer").addClass("fadeOutRightBig");
setTimeout(function() {
$(".buttonContainer").remove();
}, 500);
}

// 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);
}

});

Answer

You should store the number of responses per client and count them.

Client side :

socket.on("connect",function(){

    // Joining the game
    socket.emit('joingame', {username:"foobar"});

    $(document).on('click', '.answerButton' , function(){

    function answerChecker(element){
      if(element == gaPosition) {
        correctAnswer();
      }
      else {
        console.log("Incorrect!");
        incorrectAnswer();
      }
    }

    var clickedButton = $(this).data('button');
    console.log(clickedButton);
    answerChecker(clickedButton);

   }); 

  function correctAnswer() {
    var correct = true;
    socket.emit('playercorrect', {answer: true});
    console.log(correct);
    buttonRemover();
  }

  // Check if wrong + send to server
  function incorrectAnswer () {
    var wrong   = false;
    socket.emit('playerwrong', {answer: false});
    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);
        }
    })

   socket.on("gamefinished", function(data){
      console.log(data.message);
   });


})

And the server side :

var users =  {}, validQuestions = [], validCurrQuestion = [];

io.sockets.on('connection', function(socket){

    socket.on("joingame", function(msg){

            console.log("joining game");

            users[socket.id] = {responses:[],currQuestion: {answered:false,answer:null}};

            socket.on("playercorrect",function(msg){

                users[socket.id].currQuestion.answered = true:
                users[socket.id].currQuestion.answer = true: 
                users[socket.id].responses.push(msg.answer);

                checkAnswers(socket);
            })

            socket.on("playerwrong",function(msg){

                users[socket.id].currQuestion.answered = true:
                users[socket.id].currQuestion.answer = false: 
                users[socket.id].responses.push(msg.answer);

                checkAnswers(socket);
            })


    })


})

io.sockets.on('disconnect', function(socket){
    delete users[socket.id];
})




function checkAnswers(socket){

      var connectedC = Object.keys(users).length;

       for (var clientK in users) {

           // check if current q has been answered

           if(users[clientK].currQuestion.answered) {
            validCurrQuestion.push({socket:socket,answer:users[clientK].currQuestion.answer});

              if (validCurrQuestion.length === connectedC) {
                  // curr question answered by both clients
                  // send result to both
                  sendCurrQresults();

              }

           }

           // if the 8 questions have been answered
           // push into array
           if (users[clientK].responses.length === 8) {
            validQuestions.push(socket.id);
           } 

           // if all users have answered all question send game results
           if (validQuestions.length === connectedC) {
            // finish the game
            getWinner()
           }

       }

}

function sendCurrQresults(){

  validCurrQuestion.forEach(function(question, index){
    question.socket.emit("updateplayer", {answer: question.answer});

    // reset curr question to go to next question
    validCurrQuestion.splice(index, 1);
    users[socket.id].currQuestion = { answered: false, answer: null};

  })

}

function getWinner(){

    // Check who has more true response and send by counting user.responses true vs false

}
Comments