Page 1 of 2 12 LastLast
Results 1 to 10 of 18

Thread: Array/hash tag help

  1. #1
    Join Date
    Dec 2011
    Posts
    34
    Thanks
    8
    Thanked 0 Times in 0 Posts

    Default Array/hash tag help

    Code:
    var lootedItem;
    
    var loot = {
    "silver": 3,
    "bronze": 3,
    "copper": 3,
    "platinum": 1,
    "iron": 5,
    "stone": 5
    };
    var playerLoot = {
    "silver": 0,
    "bronze": 0,
    "copper": 0,
    "platinum": 0,
    "iron": 0,
    "stone": 0
    };
    Code:
    function mining() {
    //gold++;
    for(var v=0; v <loot.length; v++){
    lootedItem = loot[Math.floor(Math.random() * loot.length)];
    playerLoot[v]+= lootedItem[v];
    }
    console.log(lootedItem); //RETURNS 0 every time
    console.log(playerLoot); //returns the players array of 0's
    }
    The array "loot[]" is supposed to be a loot table with a corresponding value. When the function mining() is called, it should randomly return 1 of the values from the array, with the corresponding value.

    So the first time it's called, maybe it randomly gives iron, it should give 5 iron to the player's iron variable.

    So if it randomly gives you the loot[5] entry as loot, it should increment the corresponding playerLoot[5].


    Anyone point me in the right direction? Been glued to the array documentation but not able to get it working....

    For right now if I could just get it to return a random entry I can figure out how to assign it to the corresponding entry in the other array...Any ideas how to get it to work right?

    Code:
    lootedItem = loot[Math.floor(Math.random() * loot.length)];
    returns 0 every time, I tried various combinations adding
    Code:
    lootedItem[v]= loot[Math.floor(Math.random() * loot.length)][0];
    and
    Code:
    lootedItem[v][0]= loot[Math.floor(Math.random() * loot.length)][0];
    lootedItem[0][0]= loot[Math.floor(Math.random() * loot.length)][0]; //etc various combinations...
    thinking that would return the first value from the random entry but it doesnt work either.
    Last edited by lmbarns; 12-16-2011 at 07:28 PM.

  2. #2
    Join Date
    Jul 2008
    Posts
    128
    Thanks
    0
    Thanked 17 Times in 16 Posts

    Default

    Quote Originally Posted by lmbarns View Post
    The array "loot[]"
    You don't have an array called loot, it is an object which has no length property and its properties cannot be addressed by a numeric index.

    You could use for-in to build an array of the properties, then select from it:

    Code:
    <script type="text/javascript">
    
    var loot = 
    {
    "silver": 3,
    "bronze": 3,
    "copper": 3,
    "platinum": 1,
    "iron": 5,
    "stone": 5
    };
    
    var propertyArray = [];
    
    for( var i in loot )
     propertyArray.push( i );
    
    alert( propertyArray[ Math.floor( Math.random() * propertyArray.length ) ] );
    
    </script>

  3. #3
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    Code:
    <!DOCTYPE html>
    <html>
    <head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <script type="text/javascript">
    var lootedItem;
    
    var loot = {
    	silver	: 3,
    	bronze	: 3,
    	copper	: 3,
    	platinum: 1,
    	iron	: 5,
    	stone	: 5
    };
    
    var playerLoot = {
    	silver	: 0,
    	bronze	: 0,
    	copper	: 0,
    	platinum: 0,
    	iron	: 0,
    	stone	: 0
    };
    
    var lootArray = [];
    
    for (var p in loot){
    	if(loot.hasOwnProperty(p)){
    		lootArray.push(p);
    	}
    }
    
    function addLoot(){
    	lootedItem = lootArray[Math.floor(Math.random() * lootArray.length)];
    	playerLoot[lootedItem] += loot[lootedItem];
    }
    
    function queryLoot(){
    	alert('item : ' + lootedItem + '\nplayer\'s value : ' + playerLoot[lootedItem]);
    }
    
    function allLoot(){
    	var r = ['Player Loot\n'];
    	for(var i = 0; i < lootArray.length; ++i){
    		r.push(lootArray[i] + ' : ' + playerLoot[lootArray[i]]);
    	}
    	alert(r.join('\n'));
    }
    
    </script>
    </head>
    <body>
    <input type="button" value="add" onclick="addLoot();"><br>
    <input type="button" value="query" onclick="queryLoot();"><br>
    <input type="button" value="all" onclick="allLoot();">
    </body>
    </html>
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  4. The Following User Says Thank You to jscheuer1 For This Useful Post:

    lmbarns (12-17-2011)

  5. #4
    Join Date
    Dec 2011
    Posts
    34
    Thanks
    8
    Thanked 0 Times in 0 Posts

    Default

    Thank you so much guys. I realized I was confused, initially I thought I was using arrays, then after endless reading through searches it was apparent that hash tables != arrays....


    Before seeing this ^^ above from John I had ended up just randomly generating a random number of all of the different ores, with the rarest one only having a chance of randomly giving 0-1 and the commonest ones range between 0-10 but this will clean it up a lot and I want the functionality for a lot of other things, to randomly spit out something different as achievements.....

  6. #5
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    A little more on the subject, hopefully it will help in your understanding.

    The technical term in javascript for loot and playerLoot is Object. In general programming parlance the concept is also known as an associative array. That is an array consisting of keys and values. It's different than a javascript array, which is known as an indexed array and can contain only values, which are indexed via the order in which they appear in the array.

    In some languages an array can behave partly, and in some completely as both, having keys and indexes, but not in javascript. In javascript there is no crossover between the two. But as you see we can approximate aspects of it (a crossover) to suit our purposes.

    In javascript an Array is made with the new Array() constructor or by the preferred method - literally placing values in the square brackets. A javascript Object is made either with the new Object() constructor, or as in our example, and the preferred method - literally placing key: value pairs inside the curly brackets.
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  7. The Following User Says Thank You to jscheuer1 For This Useful Post:

    lmbarns (12-17-2011)

  8. #6
    Join Date
    Dec 2011
    Posts
    34
    Thanks
    8
    Thanked 0 Times in 0 Posts

    Default

    Are the individual "properties" objects as well? Reason I ask is because
    Code:
    function test() {
    localStorage.setItem('lootIndex0', playerLoot[lootArray[0]]);
    
    localStorage.getItem('lootIndex0'); // returns null
    
    console.log(localStorage.lootIndex0); //DOES return correct amount from playerLoot[lootArray[0]]
    }
    Will output the correct amount of ore currently in playerLoot[lootArray[2]] in the console making me think it's saving it to localStorage, but the second I try to retrieve it, or compare it to the current playerLoot[lootArray[2]] (after dying and resetting) I get null or undefined.

    But if I reset it and just do console.log(localStorage.lootIndex0) on it's own without setItem it returns null so I guess it's not saving but just returning it into the console because it's in the same function?

    So I guess I should try json stringify?

    I was trying to do this and it returns null as well:
    Code:
    if(localStorage.lootIndex0 < playerInventory[lootArray[0]]) {
    	localStorage.setItem('lootIndex0',playerInventory[lootArray[0]])
    }

    Edit:: I'm trying with json and it's the same deal. It'll log the right numbers in the console but when I replay the game the previous localStorage values are null....
    Code:
    localStorage.setItem('index0', JSON.stringify(playerLoot[lootArray[0]]));
    
    var index0 = localStorage.getItem('index0');
    console.log('retrievedIndex0: ', JSON.parse(index0)); //returns the correct number
    but
    Code:
    var index0 = localStorage.getItem('index0');
    if(index0 > JSON.stringify(playerLoot[lootArray[0]])){
    localStorage.setItem('index0', JSON.stringify(playerLoot[lootArray[0]]));
    }
    returns null. I'm trying to compare the current amount to the amount in storage and if the current one is higher then write it to the relevant storage.
    Last edited by lmbarns; 12-20-2011 at 02:12 AM.

  9. #7
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    No, the individual values are numbers and can easily type convert to and from strings in the operations you're doing there.

    Now, localStorage only works if the page is live. Assuming you have the syntax right, are you doing this live or on your own computer. If the page isn't live, that could be the problem. Or, you may be expecting the functions to do something they're not set up for. For example, this 'works' live:

    Code:
    function test() {
    localStorage.setItem('lootIndex0', playerLoot[lootArray[0]]);
    
    alert(localStorage.getItem('lootIndex0')); // alerts correct value
    }
    But where you have:

    Code:
    function test() {
    localStorage.setItem('lootIndex0', playerLoot[lootArray[0]]);
    
    localStorage.getItem('lootIndex0'); // returns null
    
    console.log(localStorage.lootIndex0); //DOES return correct amount from playerLoot[lootArray[0]]
    }
    What makes you think the highlighted line returns null? You're not doing anything with the value, at least not so far as I can see. How would you know?
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  10. #8
    Join Date
    Dec 2011
    Posts
    34
    Thanks
    8
    Thanked 0 Times in 0 Posts

    Default

    Sorry it was
    var retrievedIndex0 = localStorage.getItem('index0');
    console.log('retrieved0: '+retrievedIndex0 ); //retrieved0: null is result
    Closest thing I've gotten towards working is this:

    Code:
    if(localStorage.getItem('index0') <  playerLoot[lootArray[0]]){ console.log('bingo! ');
    }
    That actually now throws 'bingo!' when I get a higher amount of ore this round than before.......but
    Code:
    if(localStorage.getItem('index0') <  playerLoot[lootArray[0]]){ console.log('bingo! '); 
    localStorage.setItem('index0', JSON.stringify(playerLoot[lootArray[0]])); }
    the bold never triggers which I assume should overwrite the original entry??

    I threw out a few other variables just to see what they returned
    Code:
    var addThis = playerLoot[lootArray[0]]+localStorage.getItem('index0');
    returns nn where n is the number, 0 if I don't get any ore, otherwise it's the number twice

    I commented out anywhere else that was writing it to localStorage to make sure it wasn't clearing things out and just added a line where "bingo" triggers thinking if it triggers it should then write to localStorage because it's the higher value.

    At this point I wouldn't even mind just += adding the new ores gathered during this game to some global amount that I retrieve when the game is loaded.

    I just tried it in IE and it throws an error in the console
    SCRIPT5007: Unable to get value of the property 'index0': object is null or undefined

  11. #9
    Join Date
    Jul 2008
    Posts
    128
    Thanks
    0
    Thanked 17 Times in 16 Posts

    Default

    Try
    Code:
    playerLoot[ "lootArray" ][ 0 ];

  12. #10
    Join Date
    Dec 2011
    Posts
    34
    Thanks
    8
    Thanked 0 Times in 0 Posts

    Default

    Quote Originally Posted by clueful View Post
    Try
    Code:
    playerLoot[ "lootArray" ][ 0 ];
    That gave a new error
    Permission denied for <http://view.atdmt.com> to call method Location.toString
    I don't have a clue what that url is to ^^ atdmt.com has nothing to do with anything I'm writing...must be from the json library? I downloaded the json2 file off google code.

    This is a screenshot of my console:

    I'm not sure what the difference is between the "null"'s are, if you notice there are 2 different types, 2 are bolder while the rest are italicized and lighter in color....

    This is the code that triggers those console logs..
    Code:
    var retrievedIndex0 = localStorage.getItem('index0');
    console.log('retrieved0000:'+retrievedIndex0 );
    var addThis = playerLoot[lootArray[0]]+localStorage.getItem('index0');
    var thisIndex0 = playerLoot[lootArray[0]];
    console.log('retrievedIndex0:', JSON.parse(retrievedIndex0));
    console.log('playInv: '+playerLoot[lootArray[0]]);
    console.log('addThis: '+addThis);
    
    if(localStorage.getItem('index0') <  playerLoot[lootArray[0]]){ console.log('bingo! '); 
    localStorage.setItem('index0', JSON.stringify(playerLoot['lootArray'][0])); }
    
    console.log('newshit: '+localStorage.index0);
    I've tried the bolded both ways, the new way and the original way...new way gives new error, old way just doesn't do anything though it outputs "bingo!" only when I have a new high score.............


    Elsewhere in my code where I implemented John's amazing array above ^^ I access the array objects as:
    Code:
    function incOres() {
    addLoot();
    var goDiv = document.getElementById("gold");
        goDiv.innerHTML = "<span class='indent'>Gold: "+playerLoot[lootArray[6]]+"</span>";
    }
    Which adjusts a div on my screen to accurately show the amount of ores in playerLoot[lootArray[6]] so I figured I could just go to my gameOver() function and write all these entries to localStorage....

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •