0

I have tried to search the forum and google but do not really know what to ask for so apologies if this have been answered before.

var currentLevel = 2;

var Level = function(layout, ColRow) {
  this.layout = layout;
  this.ColRow = ColRow;};

var level1 = new Level ([   1, 2, 1, 2, 2,
                            1, 1, 3, 1, 1,
                            1, 1, 1, 1, 1,
                            1, 1, 1, 1, 1],
                           [5, 4]);

var level2 = new Level ([   1, 2, 1, 2, 2,
                            1, 1, 3, 1, 1,
                            1, 1, 1, 1, 1,
                            1, 1, 1, 1, 1],
                           [2, 2]);                         


var drawTrack = function () {
id = 0;
for (var col = 0; col < level1.ColRow[0]; col ++) {
    tile[col] = [];
    for (var row = 0; row < level1.ColRow[1]; row++) {
        id = col + row*level1.ColRow[0];
        tile[col][row] = {x:0, y:0, type:"asphalt"};
        image (tiles[level1.layout[id]], col * 256, row * 256);
    }
}
};

In the example above I would like to change level1 in the code at the bottom to something like level(currentLevel).ColRow[0]. Is that possible or is there any other best practice to do this?

*edit The array solution solved my problem, thanks! The suggested link I did find before but could not see how it could change the variable within the code? Maybe I missed something.

1 Answers1

2

How about creating an array of levels?

var levels = [

    new Level ([1, 2, 1, 2, 2,
    1, 1, 3, 1, 1,
    1, 1, 1, 1, 1,
    1, 1, 1, 1, 1],
    [5, 4]),

    new Level ([1, 2, 1, 2, 2,
    1, 1, 3, 1, 1,
    1, 1, 1, 1, 1,
    1, 1, 1, 1, 1],
    [2, 2])

];

Then to access:

levels[currentLevel].ColRow;
shennan
  • 10,798
  • 5
  • 44
  • 79
  • Much better than using variable variables. One minor change I'd make is `var levels = []` then `levels.push(new Level...` as many times as needed, so if/when more levels are added the `levels` initialiser isn't ever growing – James Thorpe Dec 09 '15 at 10:51
  • @JamesThorpe Fair comment. But this is essentially hardcoded bootstrapping data; it has to be defined somewhere, whether it's in a `push` or straight into an `Array`. Either way, the concept is the same. :-) – shennan Dec 09 '15 at 10:54