我能够较早地引用数组时无法

我能够较早地引用数组时无法

我正在使用node.js作为服务器来创建在线游戏。我有一些要在用户登录时分配给他们的播放器名称。播放器名称是从JSON文件加载的,加载它们时我可以记录播放器名称,但是当用户登录时我登录播放器时却显示未定义。我的代码如下。



var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var fs = require("fs");

var playersRequired = 3;
var playersHad = 0;
var playerNames = [];
var players =[];
var gameStart = false;
var gameRunning = false;

class Player {...}

fs.readFile(__dirname+"/Gamedata/characters.json",function(err,data){
  console.log("Loading Characters");
  playerNames = JSON.parse(data);
  console.log(playerNames);
  for(var i = 0; i<Object.keys(playerNames).length;i++){
    console.log(i);
    players[i] = new Player(playerNames[i].name,playerNames[i].description);
    //this works and logs the players:
    console.log("yet another player "+players[i].name+"\n\n\n\n\n\n\n\n");
  }
  //console.log('Creating player objects: '+JSON.stringify(players,0,2))
});

server.listen(3000, function(){
  console.log("listening");
});

console.log('starting');

app.get('/', function (req, res) {
  console.log('get / request');
  res.sendFile(__dirname + '/public/index.html');
});

io.on('connection', function (socket) {
  socket.on('disconnect',function(){
    console.log('a player disconnected');
    playersHad--;
    if(playersHad <0){
      playersHad = 0;
    }
  });
  socket.on('login',function(data){
    console.log("Player logged in");
    playersHad++;
    console.log(playersHad+" players have logged in");
    //this does not work and returns undefined:
    console.log("This user is: " + players[playersHad]);
    socket.emit("Name",players[playersHad]);
    if(playersHad == playersRequired){
      if(!gameRunning){
        gameRunninng = true;
        game();
      }
    }
  });
  socket.on('disconnect',function(){
    players--;
  });
});

function game(){...}

最佳答案

您似乎已离开1。您正在更新playersHad,然后再从玩家登录。播放器的索引为0,并且您使用1,2,3等来跟踪长度。

您的代码应为

socket.on('login',function(data){
 console.log("Player logged in");
 playersHad++;
 console.log(playersHad+" players have logged in");
 //this does not work and returns undefined:
 console.log("This user is: " + players[playersHad - 1]);
 socket.emit("Name",players[playersHad - 1]);
 if(playersHad == playersRequired){
   if(!gameRunning){
     gameRunninng = true;
     game();
   }
 }
});


让我知道这是否有帮助!

关于javascript - 我能够较早地引用数组时无法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47078566/

10-11 20:45