创建一个数组Javascript突破游戏

时间:2016-06-15 20:22:44

标签: javascript arrays html5-canvas

我正在使用HTML5 Canvas创建一个简单的分组克隆并遇到了loadHitGrid()函数,但我很难理解它的作用。

它看起来像是在hitgrid数组中创建数组 然后填写1&#39>

有人可以帮忙或者说出来吗?

function loadHitGrid() {
  for (var i = 0; i < NUM_ROWS; i++) {
    hitGrid[i] = new Array;

    for (var j = 0; j < NUM_COLS; j++) {
      hitGrid[i][j] = 1;
    }
  }

}


//Can i replace hitGrid with the following?


hitGrid = [
  1, 1, 1, 1, 1, // is this the same as the above????
  1, 1, 1, 1, 1,
  1, 1, 1, 1, 1,
  1, 1, 1, 1, 1,
  1, 1, 1, 1, 1
]





function drawblocks() {
    for (var i = 0; i < NUM_ROWS; i++) { // loops  trough number of rows
      for (var j = 0; j < NUM_COLS; j++) { // loops thgrough number of cols
        if (hitGrid[i][j] == 1) { // for each row / col check for 1
          ctx.beginPath(); // Satrts a new path used when drawing!
          ctx.fillStyle = colours[i];
          ctx.fillRect(j * (blockW + SPACING) + SPACING, 
                       i * (blockH + SPACING) + SPACING, blockW, blockH);
        }
      }
    }

2 个答案:

答案 0 :(得分:0)

这将是:

hitGrid = [[1, 1, 1, 1, 1], // is this the same as the above????
           [1, 1, 1, 1, 1], 
           [1, 1, 1, 1, 1],
           [1, 1, 1, 1, 1], 
           [1, 1, 1, 1, 1]];

当然这意味着NUM_ROWS和NUM_COLUMNS是5 :)

答案 1 :(得分:0)

查看我对以下代码的评论:

     function loadHitGrid () {     
          for(var i = 0 ; i < NUM_ROWS ; i ++) {
              hitGrid[i] = new Array; //Creating an empty array NUM_ROWS amount of times

              for(var j = 0; j < NUM_COLS; j ++) {
                   hitGrid[i][j] = 1 ; //Populating each newly created empty array with NUM_COLS amount of ones.
              }
          }
      }

所以在NUM_ROWS和NUM_COLS都等于5并假设hitGrid是一个空数组,输出看起来更像:

[[1,1,1,1,1],
 [1,1,1,1,1],
 [1,1,1,1,1],
 [1,1,1,1,1]]