简体   繁体   English

在socket.io中完成游戏后,从会议室中获得所有用户的分数

[英]Get a scores of all users from the room after game completes in socket.io

I'm working on a multiplayer game in which there will be four rooms and each room will have multiple clients in it who are playing the game. 我正在做一个多人游戏,其中将有四个房间,每个房间将有多个正在玩游戏的客户。 After completing the game i want to send the score of all users to the server, store it in the array, compare it and want to return the name of the winner. 完成游戏后,我想将所有用户的分数发送到服务器,将其存储在数组中,进行比较并返回赢家的名字。 So, how can i get the score of all the users from the room, after completing the game. 因此,完成游戏后,如何从会议室中获得所有用户的分数。

var delayInMilliseconds = 2000;
var hit = 0;

$('#hit').click(function() 
{
  hit++;
});

var modal = document.getElementById('myModal');
var btn = document.getElementsByClassName("common");
var span = document.getElementsByClassName("close")[0];

setTimeout(function() 
{
    var seconds_left = 15;
    var interval = setInterval(function() 
    {
        document.getElementById('timer').innerHTML = --seconds_left;
        if (seconds_left <= 0)
        {
            // document.getElementById('timer').innerHTML = "Time's up!";
            clearInterval(interval);
          console.log(hit);
          $('#hit').attr("disabled", true);
          $('#score').html(hit);
          modal.style.display = "block";

        }
    }, 1000);
}, delayInMilliseconds);

Above is the client side code for the game, game will be completed after 15 seconds, so my idea is i can send the data in if(seconds_left <= 0) , but how can i get the score of all the clients from the room. 上面是游戏的客户端代码,游戏将在15秒后完成,所以我的想法是我可以在if(seconds_left <= 0)发送数据,但是我如何从房间中获取所有客户端的分数。

First of all you have to somehow identify users. 首先,您必须以某种方式识别用户。 Let's save them to object called users with key userName and value score. 让我们将它们保存到具有关键userName和值得分的名为user的对象中。 Just like that: var users = { user1: 12, user2: 9 }; 就像这样: var users = { user1: 12, user2: 9 }; .
Than we have to send this data to server. 比我们必须将此数据发送到服务器。 We can do it like examle from official socket.io documentation 我们可以像socket.io官方文档中的示例那样进行操作

<script>
  var socket = io('http://localhost');
  socket.on('connection', function () {
    console.log('Socket connected');
  });

  // here is your code to handle users actions. 
  // When the game is finished, you do it like this
  socket.emit('game finished', users);
</script>

On the server side you can listen for game finished event with data you want to parse. 在服务器端,您可以使用要解析的数据监听game finished事件。

Also, you can make requests to server with ajax to process score data, you can read about jQuery implementation or native JS 另外,您可以使用ajax向服务器发出请求以处理分数数据,可以阅读有关jQuery 实现本机JS的信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM