gpt4 book ai didi

javascript - 当我能够更早地引用数组时无法引用数组

转载 作者:行者123 更新时间:2023-11-30 21:01:41 24 4
gpt4 key购买 nike

我正在创建一个在线游戏,服务器使用 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。 Players 的索引为 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com