Finding a room in the worldMap

Example of navigating 2d arrays for the tile-based map game

by konijn_gmail_com

JavaScript

var room1 = [
    [1, 1, 1, 1, 1, 1, 1],
    [1, 1, 1, 1, 1, 1, 1],
    [1, 1, 1, 1, 1, 1, 1]
];

var room2 = [
    [2, 2, 2, 2, 2, 2, 2],
    [2, 2, 2, 2, 2, 2, 2],
    [2, 2, 2, 2, 2, 2, 2]
];

var room3 = [
    [3, 3, 3, 3, 3, 3, 3],
    [3, 3, 3, 3, 3, 3, 3],
    [3, 3, 3, 3, 3, 3, 3]
];

var room4 = [
    [4, 4, 4, 4, 4, 4, 4],
    [4, 4, 4, 4, 4, 4, 4],
    [4, 4, 4, 4, 4, 4, 4]
];

var worldMap = [
    [room1, room2],
    [room3, room4]
];

var outputA;
var outputB;
var currentMap = room2;

function indexOf2d(arrayParam, valueParam) {
    var index = [-1, -1];
    if (!Array.isArray(arrayParam)) {
        return index;
    }
    arrayParam.some(function (sub, posX) {
        if (!Array.isArray(sub)) {
            return false;
        }
        var posY = sub.indexOf(valueParam);
        if (posY !== -1) {
            index[0] = posX;
            index[1] = posY;
            outputA = index[0];
            outputB = index[1];
            return true;
        }
        return false;
    });
    return index;
}

function goToNextRoomDown(map, valueA, valueB) {
    var newValue = valueA + 1;
    var result = map[newValue][valueB];
    return result;
}

// show the existing currentMap
console.log('existing currentMap = ' + currentMap);

// get the index of the currentMap within the worldMap
console.log(indexOf2d(worldMap, currentMap));

// use the index value outputs to calculate the next room 'down' the worldMap array
console.log('next room down: ' + goToNextRoomDown(worldMap, outputA, outputB));

// assign the new room as the currentMap
currentMap = goToNextRoomDown(worldMap, outputA, outputB);
console.log('new currentMap = ' + currentMap);