我目前正在制作一个简单的游戏,用户首先连接输入用户名,然后将其存储起来。
所以问题是我有一个多维数组。但是,当第二个玩家连接时,它怎么知道呢?我需要创建其中两个吗?如果是这样,它如何知道将其推到哪里?
因为我需要找到 .length,以便我可以看到有两个用户。
var socketStorage = {};
// ===============================================
// GAME LOGIC
// ===============================================
socketStorage[socket.id] = {};
socketStorage[socket.id] = {
username : "username",
socket : socket,
currQuestion : {
answered : false,
answer : false
},
allQuestionsAnswers : []
};
socket.on("setusername", function(msg){
socketStorage[socket.id].username = msg.username;
console.log(socketStorage[socket.id].username);
});
最佳答案
您的示例中没有多维数组。你也没有在游戏中解释——大家是同时玩的,还是有不同的游戏可以各自包含自己的玩家,彼此隔离?
这里有一个处理这个问题的示例方法:我有一段时间没有使用套接字了,所以我使用你的代码和我对其处理方式的粗略内存 - 根据需要纠正任何错误。
var games = []
var socketStorage = {};
// ===============================================
// GAME LOGIC
// ===============================================
// socketStorage[socket.id] = {}; // <- this line is unnecessary.
socketStorage[socket.id] = {
username : "username",
socket : socket,
currQuestion : {
answered : false,
answer : false
},
allQuestionsAnswers : []
};
socket.on("setusername", function(msg){
socketStorage[socket.id].username = msg.username;
console.log(socketStorage[socket.id].username);
});
socket.on("newgame", function(msg){
newGameId = games.length;
games.push([]);
games[gameId].push(socketStorage[socket.id]);
socket.emit("newgamecreated", { gameId: newGameId });
});
socket.on("joingame", function(msg){
var gameId = msg.gameNumber;
games[gameId].push(socketStorage[socket.id]);
});
socket.on("getgames", function(msg){
gamesToUsers = {};
games.forEach(function(game, index) {
gamesToUsers[index] = game.map(function(socket) {
return socket.username
});
});
socket.emit("currentgames", gamesToUsers);
});
这是不完整的,而且非常基础,并且可能有几个错误,但应该足以让您理解如何进行此操作的概念。每当有人在游戏中执行某些操作时,您只需使用循环将新信息 socket.emit
发送给同一游戏中的每个人。所以,
socket.on("somethinghappenedingame", function(msg){
game = msg.gameNumber;
update = msg.update;
games[game].forEach(function(socketObj){
socketObj.socket.emit("gameUpdate", update);
});
});
希望有帮助。
关于javascript - Socket.io 和多维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38172707/