Repeating an image with a for loop and switch statement

Hello !

I’ve started recently diving into SDL 2 and programming as a whole and I’m following a tutorial online
I want to repeat an image over the whole screen
my question is the following:
is there a better way(probably yes) to repeat an image half the surface size of the screen 4 times other than this:

for (int i = 0; i < 4; i++) {
	switch (i) {
		case 0:
			SDL_Rect stretchRect0;
			stretchRect0.x = 0;
			stretchRect0.y = 0;
			stretchRect0.w = SCREEN_WIDTH/2;
			stretchRect0.h = SCREEN_HEIGHT/2;
			SDL_BlitScaled( gStretchedSurface, NULL, gScreenSurface, &stretchRect0 );
		case 1:
			SDL_Rect stretchRect1;
			stretchRect1.x = SCREEN_WIDTH/2;
			stretchRect1.y = 0;
			stretchRect1.w = SCREEN_WIDTH/2;
			stretchRect1.h = SCREEN_HEIGHT/2;
			SDL_BlitScaled( gStretchedSurface, NULL, gScreenSurface, &stretchRect1 );
		case 2:
			SDL_Rect stretchRect2;
			stretchRect2.x = 0;
			stretchRect2.y = SCREEN_HEIGHT/2;
			stretchRect2.w = SCREEN_WIDTH/2;
			stretchRect2.h = SCREEN_HEIGHT/2;
			SDL_BlitScaled( gStretchedSurface, NULL, gScreenSurface, &stretchRect2 );
		case 3:
			SDL_Rect stretchRect3;
			stretchRect3.x = SCREEN_WIDTH/2;
			stretchRect3.y = SCREEN_HEIGHT/2;
			stretchRect3.w = SCREEN_WIDTH/2;
			stretchRect3.h = SCREEN_HEIGHT/2;
			SDL_BlitScaled( gStretchedSurface, NULL, gScreenSurface, &stretchRect3 );
						
	}
}

You could use a nested loop to go through each row and column and use them to calculate the position of the rects.

Something like:

const int cols = 2;
const int rows = 2;

SDL_Rect stretchRect;
stretchRect.w = SCREEN_WIDTH / cols;
stretchRect.h = SCREEN_HEIGHT / rows;

for (int row = 0; row < rows; ++row) {
	for (int col = 0; col < cols; ++col) {
		stretchRect.x = stretchRect.w * col;
		stretchRect.y = stretchRect.h * row;
		SDL_BlitScaled(gStretchedSurface, NULL, gScreenSurface, &stretchRect);
	}
}
2 Likes

You could initialize your rectangles before the game loop, and if you intend to always draw them in each corner then there’s no need for the nested loop and switch statement.

// Before your game loop, AKA initialization code
SDL_Rect topLeft = {0, 0, SCREEN_WIDTH/2, SCREEN_HEIGHT/2};
SDL_Rect topRight = {SCREEN_WIDTH/2, 0, SCREEN_WIDTH/2, SCREEN_HEIGHT/2};
SDL_Rect bottomLeft = {0, SCREEN_HEIGHT/2, SCREEN_WIDTH/2, SCREEN_HEIGHT/2};
SDL_Rect bottomRight = {SCREEN_WIDTH/2, SCREEN_HEIGHT/2, SCREEN_WIDTH/2, SCREEN_HEIGHT/2};

// Later, inside of your game loop in the drawing code section. 
// Just blit the images.
SDL_BlitScaled( gStretchedSurface, NULL, gScreenSurface, &topLeft );
SDL_BlitScaled( gStretchedSurface, NULL, gScreenSurface, &topRight );
SDL_BlitScaled( gStretchedSurface, NULL, gScreenSurface, &bottomLeft );
SDL_BlitScaled( gStretchedSurface, NULL, gScreenSurface, &bottomRight );
1 Like

Thank you very much !

this was roughly what I was going for.

tgol