gpt4 book ai didi

javascript - 等待客户端响应来运行代码socket.io?

转载 作者:行者123 更新时间:2023-12-03 06:36:41 27 4
gpt4 key购买 nike

我有一些代码,仅在两个客户都输入答案后才尝试运行。这些是函数 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();
}
}

编辑:

包含的粘贴箱: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);
}

});

最佳答案

尝试创建自己的对象来存储用户及其套接字和答案。

以下是您的存储方式的示例:

var socketStorage = {
roomname : {

some-socketid : { // the socket id from socket.id

username : "username", // the username of the user
socket : socket, // the socket of the user
currQuestion : { // an object representing the current question
answered : false,
answer : false
},
allQuestionsAnswers : [ true, true, true ] // an array of answers

},

some-socketid : {
// the socket id from socket.id
username : "otherusername",
socket : socket,
currQuestion : {
answered : false,
answer : false
},
allQuestionsAnswers : [ true, true, false ]

},

}
};

以下是如何使用该对象:

var socketStorage = {};

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

var roomName = "gamelobby"; // ideally generate a unique room where 2 sockets would join


socketStorage[roomName] = {};

socketStorage[roomName][socket.id] = {
username : "username",
socket : socket,
currQuestion : {
answered : false,
answer : false
},
allQuestionsAnswers : []
};


})

理想情况下让用户向您发送他的信息(例如用户名),例如:

 socket.emit("setusername", {username:"my-awesome-username"});

并在服务器上以这种方式在存储中设置用户名:

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


socketStorage[roomName][socket.id].username = msg.usename;

})

这是一个简单的工作示例:

客户端:

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


})

服务器端:

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

}

关于javascript - 等待客户端响应来运行代码socket.io?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38168904/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com