2

I'm writing a script that will generate a square room within a larger map. The code looks like this:

var mapSize = 10;
var map = [];
for (var x = 0; x < mapSize; x++) {
    map[x] = [];
    for (var y = 0; y < mapSize; y++) {
        map[x][y] = 0
        };
    };
//Make square room within map
var roomSize = 3;
var roomType = "Kitchen"
var paintRoom = function(mapX, mapY) {
    for (var j = 0; j < roomSize; j++) {
      map[mapX + j][mapY] = roomType;
      map[mapX][mapY + j] = roomType;
    };
};
paintRoom(3, 4);
console.log(map);

The result that I want is this:

[
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 
  [0, 0, 0, 0, "Kitchen", "Kitchen", "Kitchen", 0, 0, 0], 
  [0, 0, 0, 0, "Kitchen", "Kitchen", "Kitchen", 0, 0, 0], 
  [0, 0, 0, 0, "Kitchen", "Kitchen", "Kitchen", 0, 0, 0], 
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
]

But instead I end up with this:

[
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 
  [0, 0, 0, 0, "Kitchen", "Kitchen", "Kitchen", 0, 0, 0], 
  [0, 0, 0, 0, "Kitchen", 0, 0, 0, 0, 0], 
  [0, 0, 0, 0, "Kitchen", 0, 0, 0, 0, 0], 
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
]

What am I missing here? I'm just starting out, and would like to figure out as much as possible on my own, so if anyone could give me a hint instead of answering outright, I would really appreciate it.

2 Answers2

2

It is doing what you've asked, if you follow the code carefully. It just needs an extra loop. Since what you're doing is 2 dimensional then you'll need 2 loops as well...

var paintRoom = function(mapX, mapY) {
    for (var x = 0; x < roomSize; x++) {
        for (var y = 0; y < roomSize; y++) {
            map[mapX + x][mapY + y] = roomType;
        }
    };
};
Reinstate Monica Cellio
  • 25,975
  • 6
  • 51
  • 67
0

you a missing 1 loop:

var mapSize = 10;
var map = [];
for (var x = 0; x < mapSize; x++) {
    map[x] = [];
    for (var y = 0; y < mapSize; y++) {
        map[x][y] = 0
        };
    };
//Make square room within map
var roomSize = 3;
var roomType = "Kitchen"
var paintRoom = function(mapX, mapY) {
    for (var j = 0; j < roomSize; j++) {
      for (var k = 0; k < roomSize; k++) {
         map[mapX + j][mapY + k] = roomType;
      }
    };
};
paintRoom(3, 4);
console.log(map);

https://jsfiddle.net/nfnpesmd/

Andrew Evt
  • 3,613
  • 1
  • 19
  • 35