Node.js + Socket.io:玩家从一个房间转移到另一个房间

时间:2017-12-22 20:20:27

标签: javascript node.js sockets

我正在使用node.js + socket.io创建一个多人游戏。玩家被分为几个房间,每个房间最多有3个玩家。该算法用于跟踪房间数量,并检查最新房间中的玩家数量(按房间号码)。如果最近房间中的玩家数量超过3,则程序增加房间号,并且下一个要加入的套接字/玩家将加入新房间(“房间”+房间号码)。我遇到的问题是,即使程序正确地让玩家加入新房间,而前一个房间有3个玩家,之前的玩家正被转移到新房间。我没有看到我的代码的哪一部分会导致这种情况发生。

var players = [];
var player;
var playerUsernames = [];

var express = require("express");
var socket = require("socket.io");

var app = express();
var server = app.listen(3000);

app.use(express.static("public"));

function Player(username) {
    this.username = username;
}

var io = socket(server);
var roomNumber = 1;

setInterval(distributor, 33);

function distributor() {
    io.sockets.in("room" + roomNumber).emit("distributor", players);
}

io.sockets.on("connection", transmitter);

function transmitter(socket) {
    io.of('/').in("room" + roomNumber).clients(function(error,clients){
        var numClients = clients.length;
        if (numClients > 3) {
            roomNumber++;
        }
    });

    io.of('/').in("room" + roomNumber).clients((error, clients) => {
        console.log(clients); // Problem: Displays that players in room 2 include all of the players in room 1
    });

    socket.join("room"+roomNumber);
    socket.on("player", playerMsg);

    function playerMsg(data) {
        player = new Player(data.username);

        if (playerUsernames.indexOf(data.username) == -1 && data.hp == 100) {
            players.push(player);
            playerUsernames.push(data.username);
        }
        else {
            var index = playerUsernames.indexOf(data.username);
            players[index] = player;
        }
    }

    socket.on("players", setPlayers);

    function setPlayers(sentPlayers) {
        players = sentPlayers;
        playerUsernames = [];

        for (var i = 0; i < players.length; i++) {
            playerUsernames.push(players[i].username);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

我相信这是因为namespace.clients是异步的,而socket.join连接到一个旧房间

因此,您最好更新代码以跟踪已加入的ppl,到最后一个房间:

var roomNumber = 0;
var lastRoomCount = 0;
var maxRoomCount = 3;

function transmitter(cSocket) { // better name it other name than global "var socket"
...
  lastRoomCount=(lastRoomCount+1)%maxRoomCount;
  if (!lastRoomCount) roomNumber++;
  cSocket.join("room" + roomNumber);
...