I've been reading a couple of books on Javascript and searching a lot on the net (most good answer seem to be here at stackoverflow) and I'm still uncertain how to proceed.
What I am after is to setup 2-4 players in a Javascript/HTML app so that it knows the player's real name, assigns an alias (later an avatar, but not now), starting points, and turns.
In a book by John Duckett, Javascript & JQuery, I learned that I can use either an Array or an Object. These are similar but work slightly differently.
For an array I might have something like this:
var players= {
Timmy = {alias: "Spike", turns:0}
(and so on)
}
For an object I can apparently do something like this:
var players= {
Timmy = {alias: "Spike", turns:0}
/* and so on */
}
I'm not actually sure which is best, but I'm leaning toward the array. Where I'm stuck is that I am having a difficult time figuring out how to establish each player as such and create and populate the array with values, some of which will be selected randomly from a list (this part I can handle).
So I'm trying to start with a basic experiment (which as yet isn't working) that is less interactive than the rest of the thing I'm building, and populates the array with paired elements. Starting small with values for name and turns (all start at 0), I have this:
var p1="Billy";
var p2="Mikey";
var p3="Sammy";
var p4="";
var playerList=[];
createPList();
function pListConstructor(name, alias, turns) {
this.name=name;
this.alias=alias;
this.turns=turns;
}
function aliasChooser() {
return alias
}
function createPList() {
if(p1!=="") {
playerList.push({pName: p1});
}
if(p2!=="") {
playerList.push({pName: p2});
}
if(p3!=="") {
playerList.push({pName: p3});
}
if(p4!=="") {
playerList.push({pName: p4});;
}
document.getElementById("player1Disp").innerHTML=playerList[0].name;
document.getElementById("player2Disp").innerHTML=playerList[1].name;
document.getElementById("player3Disp").innerHTML=playerList[2].name;
document.getElementById("player4Disp").innerHTML=playerList[3].name;
}
My thinking based on recent learning in JS and some decent experience a few years ago in Actionscript is that I should be able to use the push() method to add to the array with paired values, but so far I'm not having success.
Any hints or nudges are great! Thanks.
Aucun commentaire:
Enregistrer un commentaire