This is more of a general game programming than an SFML question, but I still thought you might have some insight:
Say, I was going to implement "
The Game of Life". As you probably know this game consists of an infinite two dimensional grid of square "cells" that live under very simple rules. Each iteration of the game, each cell can be "born", can "continue living" or can "die". This only depends on the number of adjacent cells that are alive.
Something like this:
class Cell : public bool
{
public.
void update(int numberOfLiveNeighbors)
{
*this = numberOfLiveNeighbours == 3 || (numberOfLiveNeighbours == 2 && *this);
}
};
Now, if I was to follow the standard implementation recommended by most game tutorials, my naive game loop would look something like this:
for (int x = 0; x < width; x++)
for (int y = 0; y < height; y++)
{
int n = countLiveNeighbors(x, y);
cells[x * height + y].update(n);
}
That is, update each cell after the other. Obviously, that won't work, because each cell needs the data about the last generation, and some of the neighbors have already updated when they are counted.
Variant a) One solution would be to have a game state: store a copy of the "board", compute next generation based on that copy, replace, rinse & repeat. This is the standard board game approach, but means a lot of copy operations. Which is bad, if the board is large. (it's supposed to be infinite after all)
Variant b)Another option would be to do something similar, but on the cell level:
class Cell : public bool
{
public:
void preUpdate(int numberOfLiveNeighbors)
{
inescapableFate = numberOfLiveNeighbours == 3 || (numberOfLiveNeighbours == 2 && *this);
}
void update(int numberOfLiveNeighbors)
{
*this = inescapableFate;
}
private:
bool inescapableFate;
};
Then, run the loop twice: Once to "precompute", once to actually update. That works, but is also terrible: you still are copying a lot of data (the same amount in this case), and increase the complexity of your code by counter-intuitively breaking a method in two. The advantage is, you don't have to copy stuff that doesn't change.
Of course, I am not really coding this "game", but the problem I am facing is basically the same. What would you do in this case?