在SDL中使用正方形渲染二维数组

时间:2015-01-20 18:32:13

标签: c++ sdl sdl-2

我想渲染一个带有正方形的表格(例如桌面游戏,国际象棋)。 这是我的代码:

#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,因为我是新手。

我做错了什么?

3 个答案:

答案 0 :(得分:1)

您的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

答案 1 :(得分:0)

你的阵列有

SDL_Rect rects[14][12];

但是你要恭敬地迭代到第15和第13个元素。这不仅仅是阵列了。修复你的循环最大值。

其他错误是您发布的代码在return中没有newSDL_Rect(但有问题的代码确实存在)。

答案 2 :(得分:-1)

<块引用>

SDL_UpdateWindowSurface(window);

添加 -> SDL_RenderPresent(renderer);

<块引用>

SDL_Delay(5000);