2016-09-06 84 views
0

我已經構建了Conways的生活遊戲,但算法運行不正常。我爲此使用了Js和Jquery的組合。我的程序所做的是逐個單元格遍歷整個棋盤,檢查單元格的鄰居,並通過檢查它的鄰居將遊戲規則應用於每個單元格。下面是該代碼:Conways遊戲人生算法不能正常工作

function checkSquares() { 
    generation++; 
    document.getElementById('gen').innerHTML=generation; 
    for (var i = 100; i <= 6220; i++) { 

     if (squareArray[i][1] === 1) { 
     var total = squareArray[i + 81][1] + squareArray[i + 80][1] + squareArray[i + 79][1] + squareArray[i - 81][1] + squareArray[i - 80][1] + squareArray[i - 79][1] + squareArray[i + 1][1] + squareArray[i - 1][1]; 

     switch (total) { 
      case 0: 
      case 1: 
      squareArray[i][1] = 0; 

      $('#square' + i).css("background-image", "url('http://www.fg-a.com/wallpapers/geo-shapes-black-1280.jpg')"); 
      break; 
      case 4: 
      case 5: 
      case 6: 
      case 7: 
      case 8: 
      squareArray[i][1] = 0; 
      $('#square' + i).css("background-image", "url('http://www.fg-a.com/wallpapers/geo-shapes-black-1280.jpg')"); 
      break; 
     } 
     }else{ 
     var total = squareArray[i + 81][1] + squareArray[i + 80][1] + squareArray[i + 79][1] + squareArray[i - 81][1] + squareArray[i - 80][1] + squareArray[i - 79][1] + squareArray[i + 1][1] + squareArray[i - 1][1]; 
     switch(total){ 
      case 3: 
      squareArray[i][1] = 1; 
      $('#square' + i).css("background-image", "url('https://c1.staticflickr.com/3/2942/15323841455_6c64757dbd_b.jpg')"); 
      break; 
     } 
     } 
    } 

    eliminate(); 
} 

總之什麼上面的代碼做的就是把一個正方形,檢查它的相鄰小區,並使用if-else語句來決定細胞存活或死亡是否。

現在我知道問題是什麼;例如以一個簡單的模式,如這樣的:

 cell here dies ----> [] 
     new cell born here --> [] <-- new cell born here 
     cell here dies ----> [] 

在我的代碼會發生什麼事是:

     checks this cell, only one neighbour so it dies ---> [] 
    When it comes to this cell it has only one neighbour because above -> [] 
    neighbour died. Therefore it dies. 
        No neighbours, so this dies -----------------------> [] 

那麼顯而易見的解決方案是以某種方式檢查整個圖案,然後決定該細胞是否是生活或死亡。但是我怎樣才能一次檢查幾個細胞?

另外,如果有幫助,這裏是codepen鏈接到完整的程序:

http://codepen.io/Phantom-Intruder/pen/BLaBPG/

回答

2

您需要保留舊板,併產生新的董事會(稱爲代)的規則。

然後跳過舊板使用新的。

只有一塊電路板Conway's Game of Life不起作用,因爲在與neibours交互時會破壞電路板的實際狀態。

初始模式構成系統的種子。第一代是通過將上述規則同時應用於種子中的每個細胞而產生的,並且死亡同時發生,並且發生這種情況的離散時刻有時被稱爲標記(換句話說,每一代都是純函數的前一個)。這些規則繼續被反覆應用以創造更多的世代。