套接字.等待两个玩家都选择了答案的IO事件

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

本文关键字:选择 答案 事件 IO 玩家 等待 两个 套接字      更新时间:2023-09-26

我在忙着学习socket。我试图弄清楚如何让JS只在两个用户都点击了他们的答案后才启动。

我想要触发的代码是:

<我>

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

这些函数向服务器发送数据以让服务器知道答案是否正确。

<我>

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

然而,我只希望这东西发生时,两个客户端都点击了一个选项。有办法追踪吗?

对于单个用户集,只需:

// 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是分配给每个套接字的唯一标识符,这可能有用。对于多游戏性能,您可能需要更多的逻辑来维护哪些套接字/玩家属于哪些游戏的列表,然后使用该列表将消息定向到正确的用户对。

相关文章: