我能够提前做到这一点时无法引用数组

时间:2017-11-02 15:08:18

标签: javascript arrays node.js server

我正在创建一个在线游戏,使用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 个答案:

答案 0 :(得分:1)

看起来你已经离开1.你在玩家登录之前更新了玩家。玩家是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();
   }
 }
});

请告诉我这是否有帮助!