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

标签 c++ sdl sdl-2

我想渲染一个带正方形的 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;
}

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

我做错了什么?

最佳答案

您的 newSDL_Rect 函数不返回任何内容。

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++)

enter image description here

关于c++ - 在 SDL 中渲染带正方形的二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28052670/

相关文章:

C++:按引用传递和 const 关键字

c++ - 将 URL 编码转换为可打印字符

c++ - 在没有线程支持的程序加载的共享库中使用 C++11 多线程

c - gcc 无法识别标志 SDL_HWPALETTE

c++ - 用作基类接口(interface)的一部分的 header 是否应该包含在派生类中

c++ - SDL OpenGL 窗口立即关闭

c++ - SDL event.window.windowID 与 GetWindowID()

opengl - Go Lang OpenGL 简单形状 - 空白屏幕

c++ - 使用 SDL2 从 C++11 线程可移植地退出 readline

c - 初始化丢弃限定符... sdl 警告