I am currently working on a multiplayer game in Javascript, and I seem to have a very peculiar problem with my PlayerList data-structure/object.
Here is the object:
var PlayerList = function(){
this.list = {};
}
The object has several methods that I added by doing...
PlayerList.prototype.method = function(){...}
The methods are: addPlayer, removePlayer, playerInList, findPlayer, jsonify and unjsonify. I am having a huge problem with unjsonify. Here is the code:
PlayerList.prototype.unjsonify = function(jsonList){
var object = JSON.parse(jsonList);
var li = new PlayerList();
console.log(li.list.x);
console.log(li.list.y);
console.log(li.list);
//insert the fake player objects from the fake list into the new list as real player objects
for(p in object.list){
var pObj = object.list[p];
//create real player object
var player = new Player(pObj.name, pObj.x, pObj.y, pObj.velX, pObj.velY);
li.addPlayer(player);
}
return li;
}
The reason for doing it this way is because if I just parse the jsonList object sent by the server, the resulting object has the correct structure, but none of the methods a PlayerList should have.
Here's the problem: I noticed later, when I go through the PlayerList.list and draw each player, I get this error:
Uncaught TypeError: Object NaN has no method 'getX'
As it turns out, for some reason when I created a new PlayerList in unjsonify it had two extra fields, x and y, both set to NaN. The problem occurs here:
PlayerList.prototype.unjsonify = function(jsonList){
var object = JSON.parse(jsonList);
var li = new PlayerList();
For some very odd reason, li is not a new empty PlayerList like it should be. It contains two extra variables, x and y, both set to NaN. Even weirder, not only is it not a new empty list, it contains all the players that are currently on the server - something that seems impossible to me because the first time the client gets the package containing the json player list it doesn't even have a past version of itself to go off of.
To top it off, if you look at the block of code for unjsonify, console.log(li.list.x) and console.log(li.list.y) both output undefined, but then console.log(li.list) outputs an Object that has (in addition to all players on the server) fields x and y set to NaN.
I am totally lost on how this could even happen. It seems like one of these bugs no one could solve because they just don't make any sense. But if someone has the slightest idea on how to help me that would be greatly appreciated!
I should note that before I had this PlayerList object, I simply used an object primitive without any methods and did everything manually (e.g. pList.username = player to add players, etc...) and everything worked (I could see other players move on my screen, etc.) But since this is getting pretty large at this point, I wanted to add some structure hence I created this PlayerList object that should make my code more structured and pretty but thus far has only caused more problems than anything else.