When I initialize Allegro, I draw a 2D table that its cells will change white/black during the program
//Global variables
int** board;
//Draw 2D board
for (int i = 0; i < SCREEN_H ; i++) {
for (int j = 0; j < SCREEN_W; j++) {
al_draw_rectangle((j) * CELL_SIZE, (i) * CELL_SIZE, (j + 1) * CELL_SIZE, (i + 1) * CELL_SIZE, BLACK, 1.0);
}
}
al_flip_display();
Before the while loop it initialize the 2D dynamically pointer board, with random values between 0 and 1.
Inside while loop I change cell's color
//changes the values of board based on the rules of the Conway's Game of Life
generate();
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < columns; ++j) {
//Redrawing the table
al_draw_rectangle((j) * CELL_SIZE, (i) * CELL_SIZE, (j + 1) * CELL_SIZE, (i + 1) * CELL_SIZE, BLACK, 1.0);
if(board[i][j] == 1){
al_draw_filled_rectangle((j) * CELL_SIZE, (i) * CELL_SIZE, (j + 1) * CELL_SIZE, (i + 1) * CELL_SIZE, BLACK);
}else{
al_draw_filled_rectangle((j) * CELL_SIZE, (i) * CELL_SIZE, (j + 1) * CELL_SIZE, (i + 1) * CELL_SIZE, WHITE);
}
}
}
But inside for loop I need to redraw the table again.
How can I avoid that Allegro redraws the static background when I'm drawing single cells?
I don't believe there's an easy way to to this, and in any case it is simpler to just redraw the background before your cells, every frame.
If you're background doesn't change much or at all, you could store it in a texture and draw that. This is called Painter's algorithm, it's simple to do and reason about at first.
If you really don't want to redraw the background, what you could do is when you change the value of a cell that hides the background, you should store that piece of background, and when that cell "dies", draw back again. Older games used to that a lot, is still probably used a lot today, I don't know.
If most of your frame is changing a lot, redrawing everything seems just about the simplest thing to do. (And my intuition is that it would be the most efficient, but I could be wrong).
There's a a question over on gamedev network that goes deeper into what you're asking..