How to create a window and renderer and draw random points on a rectangle using SDL3 in Win32 C++

1 Answer

0 votes
#include <SDL3/SDL.h>

#if _WIN32 // PLATFORM_WINDOWS 

#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
#include <windows.h>

int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
    _In_opt_ HINSTANCE hPrevInstance,
    _In_ LPWSTR lpCmdLine,
    _In_ int nCmdShow) {

    if (!SDL_Init(SDL_INIT_VIDEO)) {
        //SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s", SDL_GetError());
        MessageBoxA(0, SDL_GetError(), "Couldn't initialize SDL", MB_OK);
        return 3;
    }

    SDL_Window* window;
    SDL_Renderer* renderer;
    if (!SDL_CreateWindowAndRenderer("SDL3 Draw random points on a rectangle", 640, 480, SDL_WINDOW_RESIZABLE, &window, &renderer)) {
        //SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create window and renderer: %s", SDL_GetError());
        MessageBoxA(0, SDL_GetError(), "Couldn't create window and renderer", MB_OK);
        return 3;
    }

    SDL_Event event;
    static SDL_FPoint points[550];

    for (int i = 0; i < SDL_arraysize(points); i++) {
        points[i].x = (SDL_randf() * 470.0f) + 100.0f;
        points[i].y = (SDL_randf() * 300.0f) + 100.0f;
    }

    while (1) {
        SDL_PollEvent(&event);
        if (event.type == SDL_EVENT_QUIT) {
            break;
        }

        // backround color
        SDL_SetRenderDrawColor(renderer, 33, 33, 33, SDL_ALPHA_OPAQUE); // dark gray
        SDL_RenderClear(renderer);  // start with a blank dark gray canvas

        SDL_FRect rect;

        // draw a filled rectangle
        SDL_SetRenderDrawColor(renderer, 13, 98, 76, SDL_ALPHA_OPAQUE); // mix color - towards green
        rect.x = rect.y = 100;
        rect.w = 470;
        rect.h = 300;
        SDL_RenderFillRect(renderer, &rect);

        // draw points across the rectangle
        SDL_SetRenderDrawColor(renderer, 255, 255, 0, SDL_ALPHA_OPAQUE); // yellow
        SDL_RenderPoints(renderer, points, SDL_arraysize(points));

        SDL_RenderPresent(renderer);  // put all on the screen
    }

    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);

    SDL_Quit();

    return 0;
}

#endif

 



answered Dec 29, 2024 by avibootz
edited Jan 1, 2025 by avibootz
...