2017-07-22 36 views
0

我得到了這個奇怪的錯誤,這是不是100%可重複,像半個星期,仍然無法弄清楚。希望有人能給我一些指導。奇怪的兩次在JavaScript中的雙循環執行

所以我正在構建這個俄羅斯方塊遊戲。在這個實際上是二維陣列的井網中,每當tetromino下降到底部(它碰到另一個tetromino或井的邊界)時,我將包含四個方塊的那個網格轉移到井網中。通常它表現很好,但有時在比賽結束後,形狀看起來不再正確。

這裏是與評論的功能:

function transferTetroGridIntoWell({ grid, tetroGrid, tetroPosition, color }) { 
    let newGrid = [...grid] 
    let relativeX, relativeY 
    // the tetroGrid could be a 2d array like: 
    // [1,1,0] 
    // [1,1,0], in which 1 indicates a block, and 0 is none 

    for (let row = 0; row < tetroGrid.length; row++) { 
    for (let col = 0; col < tetroGrid[0].length; col++) { 
     if (!tetroGrid[row][col]) continue 
     // the index of the array relative to the well grid 
     relativeX = tetroPosition.x + col 
     relativeY = tetroPosition.y + row 

     // assign the color to the according square block in the well grid 
     newGrid[relativeY][relativeX] = color 
    } 
    } 
    return newGrid 
} 

現在的問題是:

由於每個四格拼板中只含有4見方的塊,在newGrid[relativeY][relativeX] = color應僅四次,執行這在調試器中看起來是如此。但有時它有時看起來像是這個賦值在被再次調用之前被執行了兩次。

這裏是調試截圖:

執行前:

enter image description here

第1次執行後:(這是奇怪的事情發生在哪裏,有兩個#f6d42b插入井,不僅格柵8,而且格7 enter image description here

執行後

第2次:(還是雙執行)執行後 enter image description here

第3次:執行後 enter image description here

第四次: enter image description here

四次執行插入6個方塊。這怎麼會發生?

完整的源代碼:https://github.com/thomasyimgit/Tetris

真的很感激了誰讀完這很長的帖子!

回答

0

原來,這完全是關於變更數據。

使用spread運算符來複制數組只是一個淺拷貝。因此,有可能兩行引用到網格的同一行。當你做這個任務時,兩行同時更新,這看起來像是雙重執行。

我修改了transferTetroGridIntoWell功能,這在第一線,它解決了這個問題:

let newGrid = grid.map(r => r.map(c => c))

變異是邪惡的。