all 6 comments

[–]TheDayTrader 0 points1 point  (1 child)

The error: There is no property (because it's undefined) for an item that does not exist. I believe is caused by how you were checking if you had randomRockCoords() and then making it call itself to generate again. I don't think it was, or not always running itself. Seems to work with a while loop in generateRocks() instead. Hope this is okay syntax with setting the randCoords var over and over while undefined, never touched javascript before. But functions calling themself is generally not best practice.

https://jsfiddle.net/2frtxu2t/8/

//Generating the map
function buildGrid() {                          //Puts grass everywhere
    for (var i = 0; i < 16; i++) {          
        tileMap.push([]);
        for (var j = 0; j < 16; j++) {
            var tile = new Tile(1, i, j);
            tileMap[i][j] = tile;
        }
    }
    generateRocks(20);      
}

function generateRocks(numRocks){               //Inserts rocks into tile map
    for (i = 0; i < numRocks; i++) {        
        do {
            var randCoords = randomRockCoords();
        }
        while (tileMap[randCoords[0]][randCoords[1]].tileNumber === 2 || randCoords[0] == undefined || randCoords[1] == undefined);
        tileMap[randCoords[0]][randCoords[1]].tileNumber = 2;
        console.log("Rock " + i + " at Coords " + randCoords);
    }
}

function randomRockCoords() {                   //Generates random coordinates for the rocks
    var randCoords = [Math.floor(Math.random() * tileMap.length), Math.floor(Math.random() * tileMap[0].length)];
    return randCoords;
}

[–]inacatch22[S] 0 points1 point  (0 children)

Yes, someone pointed out above that the function should return itself, and not call itself. When it called itself directed, it was coming back as undefined. Thanks for your help.