简体   繁体   中英

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.

First of all you have to somehow identify users. Let's save them to object called users with key userName and value score. Just like that: 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

<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.

Also, you can make requests to server with ajax to process score data, you can read about jQuery implementation or native JS

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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