1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
|
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
SDL_Window* window = nullptr;
SDL_Renderer* renderer = nullptr;
struct user_input { int pointer_x = 0, pointer_y = 0; unsigned int mouse_state; bool made_selection_this_frame; };
[[nodiscard]] static bool constexpr within_aabb(int a, int b, int x, int y, int w, int h)
{ return (a > x && a < x + w) && (b > y && b < y + h); }
[[nodiscard]] static bool button(user_input ip, int x, int y, int w, int h)
{
bool clicked = false;
if (within_aabb(ip.pointer_x, ip.pointer_y, x, y, w, h))
{
if (ip.made_selection_this_frame) // clicked
clicked = true;
if (ip.mouse_state & SDL_BUTTON(SDL_BUTTON_LEFT)) // active
SDL_SetRenderDrawColor(renderer, 0x80, 0x80, 0x80, 0xff);
else //hovered
SDL_SetRenderDrawColor(renderer, 0xcc, 0xcc, 0xcc, 0xff);
}
else // inactive
SDL_SetRenderDrawColor(renderer, 0xff, 0xff, 0xff, 0xff);
SDL_Rect const button_rect{ x, y, w, h };
SDL_RenderFillRect(renderer, &button_rect);
return clicked;
}
// Main Function
int main()
{
SDL_Init(SDL_INIT_VIDEO);
window = SDL_CreateWindow("Dragon Hunt", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 800, 600, 0);
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
user_input ip;
for (SDL_Event e;;)
{
SDL_SetRenderDrawColor(renderer, 0x00, 0x00, 0x00, 0xff);
SDL_RenderClear(renderer);
ip.made_selection_this_frame = false;
// todo: check that it was the left mouse button that was released in this if statement
while (SDL_PollEvent(&e)) if (e.type == SDL_MOUSEBUTTONUP) ip.made_selection_this_frame = true;
ip.mouse_state = SDL_GetMouseState(&ip.pointer_x, &ip.pointer_y);
if (button(ip, 20, 20, 100, 40))
{
SDL_ShowSimpleMessageBox(0x00, "Button clicked", "You clicked the demo button.", window);
break;
}
SDL_RenderPresent(renderer);
}
return 0;
}
| |