我正在忙着学习socket.io并试图弄清楚如果用户点击了他们的答案后,只会激活一些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();
});
的
但是,当两个客户都点击了一个选项时,我只想要这个东西发生。有没有办法跟踪这个?
答案 0 :(得分:1)
对于一组用户,只需执行以下操作:
// 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
是分配给每个套接字的唯一标识符,可能很有用。对于多游戏性能,您可能需要更多逻辑来维护哪些套接字/播放器属于哪些游戏,然后使用它来将消息定向到正确的用户对。