我正在努力寫康威的生命遊戲。遊戲生活C++,檢查鄰居
不幸的是,當我去檢查一個塊的鄰居時,我總是會在我的數組中的某些元素上收到錯誤。具體來說,在grid[0][11]
它給了我一個鄰居,但是,我已經設置好了,只有當它周圍的塊不是空格,或者我的代碼中有' '
時,我纔會將值添加到名爲neighbors的變量中。
我相信,if語句中的條件也是這樣,它不會超出數組範圍。
整個陣列充滿了' '
,儘管如此,我仍然對鄰居有價值。
我一直在這個小時,並沒有找到解決辦法。我的代碼仍然充滿了試圖進行測試,並且我對它缺乏整潔感到抱歉。預先感謝您提供解決問題的任何幫助。當你想進行檢查指數
int _tmain(int argc, _TCHAR* argv[])
{
bool infloop = true;
//Create the playing grid.
char grid[HEIGHT][WIDTH];
//Comment out later. Used for testing.
for(int i=0; i<75; i++)
for(int j=0; j<22; j++)
grid[i][j] = ' ';
//Create initial seed here. grid [x coordinate] [y coordinate].
//grid [1][1] = '+'; grid [2][1] = '+'; grid [3][1] = '+';
//Key. * is going to live. + is alive currently.
//- is going to die, and negative space is dead.
//As Conway's Game of Life runs infinitely, create an infinite loop.
while (infloop)
generation(grid);
cout << endl;
system("pause");
return 0;
}
void generation(char grid[][WIDTH]) {
int neighbors;
/*Check each point on the grid for alive or dead. If it is, check the
surrounding neighbors and apply the game's rules.*/
for(int x=0; x<75; x++) {
for(int y=0; y<22; y++)
{
neighbors = 0;
/*check all eight neighbors except for when outside of the
array.*/
if((grid[x+1][y] != ' ') && (grid[x+1][y] < grid[HEIGHT][y])){
neighbors++; cout << "A";
}
if((grid[x-1][y] != ' ') && (grid[x-1][y] > grid[-1][y])){
neighbors++; cout << "E";
}
if((grid[x][y+1] != ' ') && (grid[x][y+1] < grid[x][WIDTH])){
neighbors++; cout << "C";
}
if((grid[x][y-1] != ' ') && (grid[x][y-1] > grid[x][-1])){
neighbors++; cout << "G";
}
if((grid[x+1][y+1] != ' ') && (grid[x+1][y+1] < grid[HEIGHT][WIDTH])){
neighbors++; cout << "B";
}
grid[0][11] = ' '; grid[11][0] = ' ';
if((grid[x-1][y-1] != ' ') && (grid[x-1][y-1] > grid[-1][-1])){
neighbors++; cout << "F";
}
if((grid[x+1][y-1] != ' ') && (grid[x+1][y] < grid[HEIGHT][y]) &&
(grid[x][y-1] > grid[x][-1])){
neighbors++; cout << "H";
}
if((grid[x-1][y+1] != ' ') && (grid[x-1][y] > grid[-1][y])
&& (grid[x][y+1] < grid[x][WIDTH])){
neighbors++; cout << "D";
}
system("pause");
cout << neighbors;
//Set a marker for each point according to neighbor amounts and key.
if(grid[x][y] == '+' && neighbors < 2)
grid[x][y] = '-';
if(grid[x][y] == '+' && (neighbors == 2 || neighbors == 3))
grid[x][y] = '*';
if(grid[x][y] == '+' && neighbors > 3)
grid[x][y] = '-';
if(grid[x][y] == ' ' && (neighbors == 3))
grid[x][y] = '*';
}
}
for(int x=0; x<75; x++){
for(int y=0; y<22; y++)
{
if(grid[x][y] == '*')
grid[x][y] = '+';
if(grid[x][y] == '-')
grid[x][y] = ' ';
}
}
system("pause");
display(grid);
}