在 SDL 中渲染带正方形的二维数组

Rendering a bidimensional array with squares in SDL

我想用正方形渲染 table(例如 table顶级游戏,例如国际象棋)。 这是我的代码:

#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;
}

但是当我完全执行我的代码时,创建的 window 是空白的(全白)5 秒(因为 SDL_Delay 是 运行)。我不知道如何调试 SDL,因为我是新手。

我做错了什么?

你的数组有

SDL_Rect rects[14][12];

但是您正在恭敬地迭代到第 15 个和第 13 个元素。这比数组有的多。修正你的循环最大值。

另一个错误是您发布的代码在 newSDL_Rect 中没有 return(但有问题的代码有)。

您的 newSDL_Rect 函数没有 return 任何东西。

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;
}

应该是:

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;
}

并且:

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

SDL_UpdateWindowSurface(window);

添加 -> SDL_RenderPresent(renderer);

SDL_Delay(5000);