我一直在尋找這一段時間,迄今爲止重寫了三次代碼,這是我有什麼,我不明白。生活的遊戲,C檢查生活狀況
我有一種方法,通過各種打印線和我的跑步通過它檢查鄰域,這個工程。
int getLiveCellCount(Generation *currentGeneration, int i, int j)
{
int liveCellCount = 0;
// check top row
if(i > 0)
{
if(j > 0 && currentGeneration->generation[i-1][j-1] == 'X')
{
liveCellCount++;
}
if(currentGeneration->generation[i-1][j] == 'X')
{
liveCellCount++;
}
if(j < currentCols && currentGeneration->generation[i-1][j+1] == 'X')
{
liveCellCount++;
}
}
// check mid row
if(j > 0 && currentGeneration->generation[i][j-1] == 'X')
{
liveCellCount++;
}
if(j < currentCols && currentGeneration->generation[i][j+1] == 'X')
{
liveCellCount++;
}
// check bottom row
if(i < currentRows)
{
if(j > 0 && universe[i+1][j-1] == 'X')
{
liveCellCount++;
}
if(currentGeneration->generation[i+1][j] == 'X')
{
liveCellCount++;
}
if(j < currentCols && currentGeneration->generation[i+1][j+1] == 'X')
{
liveCellCount++;
}
}
return liveCellCount;
}
我在其中的細胞生命或死亡,活細胞含有X和死細胞是空白的具體條件。
If the cell is alive:
it dies if it has 0, 1, 4 or more living neighbours (starvation), or
it lives if it has 2 or 3 living neighbours (balance).
If the cell is dead:
it springs to life if it has exactly 3 neighbours (procreation).
我實現的代碼如下:
for(i=0; i<currentRows; i++)
{
for(j=0; j<currentCols; j++)
{
int livingCells = 0;
livingCells = getLiveCellCount(currentGeneration, i,j);
if(universe[i][j] == 'X')
{
if(livingCells == 2 || livingCells == 3)
{
universe[i][j] = 'X';
}
else
{
universe[i][j] = ' ';
}
}
else
{
if(livingCells == 3)
{
universe[i][j] = 'X';
}
}
}
}
要知道,universe[][]
是一個文件範圍的變量,我這種想法的代碼讀取在初始狀態爲universe
,這個工程。我將這個數組複製到一個結構數組中(稍後存儲並且當前註釋掉)。我掃描universe
並檢查每個單元格是否存在於其鄰域中的活動單元格,其依據的是上述規則,並以逐個元素爲基礎編輯universe
。 我在這裏遺漏了什麼?某處某個條件未被我正確讀取,我看不到它。
我想感謝大家給我的幫助!就像你提到的許多我看過的小細節,宇宙中的每個單元必須同時更新!正如我所提到的,我將Universe的當前狀態複製到結構中的二維數組中,並將其存儲在數組中以供將來使用,使用Universe的當前快照對單元計數進行計數,然後編輯完美的Universe!非常感謝!
你應該包括一個小例子來說明你看到的問題。你應該考慮到你掃描桌子的方式會影響你的遊戲狀態。你同時殺死和復活細胞,所以一個細胞可能在x,y位置死亡,這會影響x + 1,j + 1是否存活或死亡,因爲當你到達第二個細胞時已經更新了x,y。它有一種單轉級聯效應。也許這就是你想要的。 –
在'getLiveCellCount'中,你不能防止超出上限。 – ooga
'getLiveCellCount'只能在我的for循環中調用,那些應該覆蓋上限? –