Search code examples
c++sdlsdl-2

Rendering a bidimensional array with squares in SDL


I want to render a table with squares (like on tabletop games, chess for example). Here is my code:

#include <SDL.h>
#include <stdio.h>
SDL_Rect newSDL_Rect(int xs, int ys, int widths, int heights)
{
    SDL_Rect rectangular;
    rectangular.x = xs;
    rectangular.y = ys;
    rectangular.w = widths;
    rectangular.h = heights;
    return rectangular;
}
int main(int argc, char* args[])
{
    SDL_Window* window = NULL;
    SDL_Surface* surface = NULL;
    SDL_Rect rects[15][13];
    if (SDL_Init(SDL_INIT_VIDEO) < 0) //Init the video driver
    {
        printf("SDL_Error: %s\n", SDL_GetError());
    }
    else
    {
        window = SDL_CreateWindow("SDL 2", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, SDL_WINDOW_SHOWN); //Creates the window
    if (window == NULL)
    {
        printf("SDL_Error: %s\n", SDL_GetError());
    }
    else
    {
        SDL_Renderer* renderer = NULL;
        renderer = SDL_CreateRenderer(window, 0, SDL_RENDERER_ACCELERATED); //renderer used to color rects

        SDL_SetRenderDrawColor(renderer, 51, 102, 153, 255);
        SDL_RenderClear(renderer);

        for (int i = 0; i < 14; i++)
            for (int j = 0; j < 12; j++)
            {
                rects[i][j] = newSDL_Rect(20 + i*42, 20 + j*42, 40, 40);
                SDL_SetRenderDrawColor(renderer, 255, 102, 0, 255);
                SDL_RenderFillRect(renderer, &rects[i][j]);
            }

        SDL_UpdateWindowSurface(window);
        SDL_Delay(5000);
    }
}
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}

But when i execute my code entirely, the window that is created is blank (all white) for 5 seconds (as the SDL_Delay is running). I don't know how to debug SDL, because i am new to it.

What am i doing wrong?


Solution

  • your newSDL_Rect function does not return anything.

    SDL_Rect newSDL_Rect(int xs, int ys, int widths, int heights) {
    SDL_Rect rectangular;
    rectangular.x = xs;
    rectangular.y = ys;
    rectangular.w = widths;
    rectangular.h = heights;
    }
    

    It should be:

    SDL_Rect newSDL_Rect(int xs, int ys, int widths, int heights) {
    SDL_Rect rectangular;
    rectangular.x = xs;
    rectangular.y = ys;
    rectangular.w = widths;
    rectangular.h = heights;
    return rectangular;
    }
    

    And:

    for ( i = 0; i < 14; i++)
    for ( j = 0; j < 12; j++)
    

    enter image description here