【发布时间】:2016-07-03 10:14:59
【问题描述】:
我有一些代码,只有在两个客户都输入答案后才尝试运行。这些是函数finish 和datarequest();。
目前我有它,它可以正确等待两个响应,并且不会在一个客户回答后立即发出。问题在于它没有到达我的 if 语句。
有没有办法 ++ nrecieved++;根据客户给出的答案类型。 IE。两个错误答案,两个正确答案还是一个?基本上是让它运行nrecieved++;同时基于两个客户的响应?
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();
}
}
编辑:
包含的 pastebin:http://pastebin.com/y6akQ6Sh
客户端:
// 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);
}
});
【问题讨论】:
标签: javascript jquery socket.io