I'm trying to make a life game in C ++ at the moment, this is my first C ++ exercise. I have one question: we need to make some game modes, for example, one of them is called "torus", when the cells leaving the board must re-enter it on the opposite side.
Now I'm checking the neighbors right now. But I hard code it with hell a lot if offers, because I tried some for-loops, but it didn’t work.
But is this really the only option? For hard coding of every possibility (cells on the left side, right side, upper side, lower side, etc.
This is the code snippet I have for this:
int countNeighboursTorus(int a, int b) {
int living = 0;
if (a == 0 && b == 0) {
if (board[a - 1][b] != DEAD) {
living++;
}
if (board[a + 1][b + 1] != DEAD) {
living++;
}
if (board[a][b + 1] != DEAD) {
living++;
}
if (board[HEIGHT - 1][b] != DEAD) {
living++;
}
if (board[HEIGHT - 1][b + 1] != DEAD) {
living++;
}
}
else if (a == 0 && b != 0) {
if (board[a - 1][b] != DEAD) {
living++;
}
if (board[a + 1][b + 1] != DEAD) {
living++;
}
if (board[a][b + 1] != DEAD) {
living++;
}
if (board[a + 1][b - 1] != DEAD) {
living++;
}
if (board[a][b - 1] != DEAD) {
living++;
}
if (board[HEIGHT - 1][b - 1] != DEAD) {
living++;
}
if (board[HEIGHT - 1][b] != DEAD) {
living++;
}
if (board[HEIGHT - 1][b + 1] != DEAD) {
living++;
}
}
return living;
}
for, , , : . , 3 , 2 . , , . - "+" - 5/6 , ( ).
else if (a != 0 && b != 0 && a < HEIGHT - 1 && b < WIDTH - 1) {
for (int c = -1; c < 2; c++) {
for (int d = -1; d < 2; d++) {
if (!(c == 0 && d == 0)) {
if (board[a + c][b + d] != DEAD) {
living++;
}
}
}
}
}
- , ? , , ? , ? . , . ++, Java , , ++. !