我正在尝试制作一个游戏,其中每2个socket.io连接都放到一个“游戏” /房间中。我设法将两个连接放到一个房间里,但我也想为这两个连接放一个游戏对象。但是我的代码基本上为每个连接创建两个。
//My Class
class Game {
constructor() {
this.players = [];
this.nextPlayer = [];
}
//...My Methods go here
}
这是给我带来麻烦的部分。
io.on('connection', function (socket) {
//Puts every 2 connections into 1 room together
if (io.nsps['/'].adapter.rooms["room-" + roomno] && io.nsps['/'].adapter.rooms["room-" + roomno].length > 1) roomno++;
socket.join("room-" + roomno);
io.sockets.in("room-"+roomno).emit('connectedToRoom', "You are in room no. "+roomno);
if (io.nsps["/"].adapter.rooms["room-1"].length === 2) {
//I think the problem is here it creates a new Game() for every connection
//I would like to have only one game object for every 2 connections
let game = new Game();
game.players = Object.keys(io.nsps["/"].adapter.rooms["room-1"].sockets);
game.nextPlayer = Object.keys(io.nsps["/"].adapter.rooms["room-1"].sockets)[0];
socket.on("fieldMarked", (data) => {
//This is different based on which client sent the "fieldMarked"
console.log(game.nextPlayer);
})
}
});