2013-01-03 79 views
2

我對Java中的Game of Life應用程序有以下邏輯代碼。我有這樣的問題,規則不會像默認的Conway的生命遊戲規則那樣行事。我已經在Wikipedia上看過他們,他們是以下的;遊戲中的生活規則無法正常工作

  • 任何少於兩個活鄰居的活細胞都會死亡,好像是由於人口不足造成的。
  • 任何有兩個或三個活着的鄰居的活細胞都活在下一代。
  • 任何有三個以上活着的鄰居的活細胞都會死亡,好像過度擁擠一樣。
  • 任何具有三個活的鄰居的死細胞就像是通過繁殖一樣成爲活細胞。

我試圖在下面的代碼中複製這些規則,但它的行爲不像普通的康威'生命遊戲;

int surroundingLife = 0; 
if (lifeMap[cX+1][cY]) { //Right 
    surroundingLife++; 
} 
if (lifeMap[cX-1][cY]) { // Left 
    surroundingLife++; 
} 
if (lifeMap[cX][cY+1]) { // Above 
    surroundingLife++; 
} 
if (lifeMap[cX][cY-1]) { // Below 
    surroundingLife++; 
} 
if (lifeMap[cX-1][cY-1]) { // Bottom left 
    surroundingLife++; 
} 
if (lifeMap[cX+1][cY+1]) { // Top Right 
    surroundingLife++; 
} 
if (lifeMap[cX-1][cY+1]) { // Some other corner (I don't know which one) 
    surroundingLife++; 
} 
if (lifeMap[cX+1][cY-1]) { // Yet another corner (I don't know which one) 
    surroundingLife++; 
} 
if (running) { 
    // Logic for life 
    if (surroundingLife < 2 && lifeMap[cX][cY]) {// Rule 1. Any live cell with fewer than two live neighbours dies, as if caused by under-population. 
     lifeMap[cX][cY] = false; 
    } else if (surroundingLife == 2 && lifeMap[cX][cY]) { // Rule 2. Any live cell with two or three live neighbours lives on to the next generation. 
     lifeMap[cX][cY] = true; 
    } else if (surroundingLife == 3 && lifeMap[cX][cY]) { // Rule 3. Same as above 
     lifeMap[cX][cY] = true; 
    } else if (surroundingLife > 3 && lifeMap[cX][cY]) { // Rule 4. Any live cell with more than three live neighbours dies, as if by overcrowding. 
     lifeMap[cX][cY] = false; 
    } else if (surroundingLife == 3 && !lifeMap[cX][cY]) { // Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction. 
     lifeMap[cX][cY] = true; 
    } 
} 

這是運行幾代後的樣子;

GameOfBugs, or BugsOfLife.

這讓我想起了 '迷宮' 規則集,這是奇怪的我。

我不認爲我周圍的生活計算器有問題,因爲當實體有8個人圍繞他們時,它返回8。由於我循環Y和X而導致問題出現?

+0

[生命遊戲(康威的遊戲) - 如何檢查細胞鄰居]的可能重複(http://stackoverflow.com/questions/8364301/the-game-of-lifeconways-game-how-to-檢查單元格鄰居) –

回答

8

問題在於,您正在修改網格,因爲您正在評估需要更改的內容。每次更換一個單元格時,都會在與該單元格邊界相同的通道中影響所有未來測試的結果。

您需要製作一個副本的網格。始終從該副本中進行測試(讀取),並將更改(寫入)應用於原件。

+1

那麼有2個網格,並且在生成完成後同步它們? –

+3

我希望每次看到這個錯誤都會有鎳幣;我可能第一次自己做了。 –

+0

你可以這樣做,或者你可以使用我建議的方法。只需在每次傳遞開始時創建一個數組副本,並將該數組用於所有測試。將實際更改應用於原始數組。 – cdhowie

相關問題