how can i read the name of the player in de list?
let Players = []
let Player = {
sprite: 1,
coords: {M: 0, X: 0, Y: 0},
name: ""
}
function LoadPlayers(){
console.log("total players: " + Players.length)
let player1 = Player
player1.sprite = 0
player1.coords = {M: 0, X: 6, Y: 1};
player1.name = "jimpie"
Players.push([player1]);
let player2 = Player
player2.sprite = 0
player2.coords = {M: 0, X: 1, Y: 17};
player2.name = "kolien"
Players.push([player2]);
console.log("total players: " + Players.length)
console.log("Player 1 name: " + Players[1].name)
console.log("Player 2 name: " + Players[0].name)
}
I'm getting 'undefined' now and i want to read out the player details from a specific player in the list.
3 Answers 3
You have different errors.
First, you must use new Player() instead of just player.
Second, you should use this:
Players.push(player1);
instead of this:
Players.push([player1]);
The first one pushes player1 to the array of Players, the second one pushes a new array that only contains player1 to the array Players. You must also use this to add player2.
9 Comments
Players.push([player1]). However, to access the player, one would use Players[i][0] instead of Players[i].Player() needs a newIt's because you're not creating a Player correctly. Instead of using let player1 = Player, use let player1 = new Player(). Also, you need to create a Players array. Lastly, you'll need to make a Player class.
class Player {
constructor(sprite, coords, name) {
this.sprite = sprite;
this.coords = coords;
this.name = name;
}
}
var Players = []; // If you want to access this array
// from outside thefunction, keep it here.
// Otherwise, move it in the LoadPlayers function
function LoadPlayers() {
let player1 = new Player(0, {
M: 0,
X: 6,
Y: 1
}, "jimpie");
Players.push(player1);
let player2 = new Player(0, {
M: 0,
X: 1,
Y: 17
}, "kolien")
Players.push(player2);
console.log("total players: " + Players.length)
console.log("Player 1 name: " + Players[0].name)
console.log("Player 2 name: " + Players[1].name)
}
LoadPlayers();
6 Comments
Player class for this to work (if that's what you mean)Player class in the question?thanks @AlexH
function Player(sprite, coords, name){
this.sprite = sprite;
this.coords = coords;
this.name = name;
}
let Players = []
function LoadPlayers(){
console.log("total players: " + Players.length)
let player1 = new Player(1, [32, 15, 14], "jimpie")
Players.push(player1);
let player2 = new Player(1, (1, 1, 1), "kolien")
Players.push(player2);
console.log("total players: " + Players.length)
console.log("Player 1 name: " + Players[0].coords)
console.log("Player 2 name: " + Players[1].name)
var allcoords = Players[0].coords
var xcoord = allcoords[1]
var ycoord = allcoords[2]
var mapnum = allcoords[0]
console.log("map: " + mapnum + " x: " + xcoord + " y: " + ycoord);
}
this works fine!
news in yourlet _ = Playerlines, it seems.Playersarray (not in that code, at least)