gpt4 book ai didi

javascript - Socket.io,从客户端获得两个响应然后运行代码?

转载 作者:行者123 更新时间:2023-11-28 05:49:48 25 4
gpt4 key购买 nike

我想让答案验证仅在从客户端收到两个唯一响应后才触发。

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

问题是我不能真正使用 nrecieved++;在这些套接字事件中,否则它将无法正确计数。如果玩游戏的客户端必须选择他们的答案,有没有办法触发计数器,这会触发套接字事件,然后++?

最佳答案

var nPlayers = 2; // Total number of players to process at a time
var responses = {}; // Socket id to response

var finish = function(){
// 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]);
}
}
}

var answerValidation = function() {
// number of players reached
if(Object.keys(responses).length === nPlayers){
finish();
dataRequest();
}
// reset responses
responses = {};
}

var registerAnswer = function(id, data) {
// check for existing response from this player
// disallows overwriting answers until processed
if(!responses.hasOwnProperty(id) {
responses[id] = data;
answerValidation();
}
};

socket.on('playerCorrect', function (data) {
registerAnswer(socket.id, data);
});

socket.on('playerWrong', function (data) {
registerAnswer(socket.id, data);
});

关于javascript - Socket.io,从客户端获得两个响应然后运行代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38165857/

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