68 lines
2.6 KiB
C
68 lines
2.6 KiB
C
#include "ui.h"
|
|
#include <stdbool.h>
|
|
#include <SDL2/SDL.h>
|
|
|
|
bool isPointInsideRect(int x, int y, SDL_Rect rect) {
|
|
return (x >= rect.x && x <= rect.x + rect.w && y >= rect.y && y <= rect.y + rect.h);
|
|
}
|
|
|
|
void handleButtonClick(SDL_Event *event, Button *button) {
|
|
int mouseX, mouseY;
|
|
SDL_GetMouseState(&mouseX, &mouseY);
|
|
|
|
if (event->type == SDL_MOUSEBUTTONDOWN && event->button.button == SDL_BUTTON_LEFT) {
|
|
// Check if the mouse click is inside the button
|
|
if (isPointInsideRect(mouseX, mouseY, (SDL_Rect){button->x, button->y, button->w, button->h})) {
|
|
button->clicked = true;
|
|
}
|
|
} else if (event->type == SDL_MOUSEBUTTONUP && event->button.button == SDL_BUTTON_LEFT) {
|
|
if (isPointInsideRect(mouseX, mouseY, (SDL_Rect){button->x, button->y, button->w, button->h})) {
|
|
if (button->clicked && button->onClick != NULL) {
|
|
button->onClick(); // Call the associated function
|
|
}
|
|
}
|
|
button->clicked = false;
|
|
}
|
|
}
|
|
|
|
void handleButtonEvents(SDL_Event *event, Button buttons[], int numButtons) {
|
|
for (int i = 0; i < numButtons; i++) {
|
|
handleButtonClick(event, &buttons[i]);
|
|
}
|
|
}
|
|
|
|
void drawButtons(SDL_Renderer *renderer, Button buttons[], int numButtons, TTF_Font *font) {
|
|
SDL_Color textColor = {255, 255, 255}; // White color for text
|
|
|
|
// Clear the renderer
|
|
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
|
|
SDL_RenderClear(renderer);
|
|
|
|
// Loop through each button and draw it
|
|
for (int i = 0; i < numButtons; ++i) {
|
|
SDL_Rect rect = {buttons[i].x, buttons[i].y, buttons[i].w, buttons[i].h};
|
|
|
|
// Set button color based on whether it's clicked or not
|
|
if (buttons[i].clicked) {
|
|
SDL_SetRenderDrawColor(renderer, 0, 255, 0, 255); // Green if clicked
|
|
} else {
|
|
SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255); // Red if not clicked
|
|
}
|
|
SDL_RenderFillRect(renderer, &rect);
|
|
|
|
// Render button text
|
|
SDL_Surface* surfaceMessage = TTF_RenderText_Solid(font, buttons[i].text, textColor);
|
|
SDL_Texture* message = SDL_CreateTextureFromSurface(renderer, surfaceMessage);
|
|
int text_width, text_height;
|
|
SDL_QueryTexture(message, NULL, NULL, &text_width, &text_height);
|
|
SDL_Rect textRect = {buttons[i].x + (buttons[i].w - text_width) / 2, buttons[i].y + (buttons[i].h - text_height) / 2, text_width, text_height};
|
|
SDL_RenderCopy(renderer, message, NULL, &textRect);
|
|
|
|
SDL_FreeSurface(surfaceMessage);
|
|
SDL_DestroyTexture(message);
|
|
}
|
|
|
|
// Present renderer
|
|
SDL_RenderPresent(renderer);
|
|
}
|