#include "texture.h" #include "ball.h" #include "defines.h" #include #include SDL_Window *window = nullptr; SDL_Renderer *renderer = nullptr; Texture *texture = nullptr; Ball *ball[NUM_BALLS]; bool should_exit = false; Uint64 ticks = 0; bool init() { // Initialization flag bool success = true; // Initialize SDL if (SDL_Init(SDL_INIT_VIDEO)) { printf("SDL could not initialize! SDL Error: %s\n", SDL_GetError()); success = false; } else { // Create window window = SDL_CreateWindow("demo_pelotas1", DEMO_WIDTH * WINDOW_ZOOM, DEMO_HEIGHT * WINDOW_ZOOM, SDL_WINDOW_OPENGL); if (window == NULL) { printf("Window could not be created! SDL Error: %s\n", SDL_GetError()); success = false; } else { // Create renderer for window renderer = SDL_CreateRenderer(window, nullptr); if (renderer == NULL) { printf("Renderer could not be created! SDL Error: %s\n", SDL_GetError()); success = false; } else { // Initialize renderer color SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF); SDL_SetRenderLogicalPresentation(renderer, DEMO_WIDTH, DEMO_HEIGHT, SDL_LOGICAL_PRESENTATION_INTEGER_SCALE); } } } texture = new Texture(renderer, TEXTURE_FILE); for (int i = 0; i < NUM_BALLS; ++i) { const int VX = rand() % 2 == 0 ? 1 : -1; const int VY = rand() % 2 == 0 ? 1 : -1; const int X = rand() % DEMO_WIDTH; const int Y = rand() % DEMO_HEIGHT; constexpr int SIZE = BALL_SIZE; ball[i] = new Ball(X, Y, SIZE, SIZE, VX, VY, texture); } ticks = SDL_GetTicks(); srand(time(nullptr)); return success; } void close() { // Destroy window SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); if (texture) { delete texture; } for (int i = 0; i < NUM_BALLS; ++i) { if (ball[i]) { delete ball[i]; } } // Quit SDL subsystems SDL_Quit(); } void checkEvents() { SDL_Event event; // Comprueba los eventos que hay en la cola while (SDL_PollEvent(&event) != 0) { // Evento de salida de la aplicación if (event.type == SDL_EVENT_QUIT) { should_exit = true; break; } if (event.type == SDL_EVENT_KEY_DOWN && event.key.repeat == 0) { switch (event.key.key) { case SDLK_ESCAPE: should_exit = true; break; default: break; } } } } void update() { if (SDL_GetTicks() - ticks > DEMO_SPEED) { ticks = SDL_GetTicks(); for (int i = 0; i < NUM_BALLS; ++i) { ball[i]->update(); } } } void render() { SDL_SetRenderDrawColor(renderer, BG_R, BG_G, BG_B, 255); SDL_RenderClear(renderer); for (int i = 0; i < NUM_BALLS; ++i) { ball[i]->render(); } SDL_RenderPresent(renderer); } int main(int argc, char *args[]) { init(); while (!should_exit) { update(); checkEvents(); render(); } close(); return 0; }