Files
demo4_sprites/source/main.cpp

154 lines
2.5 KiB
C++

#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include "texture.h"
#include "ball.h"
#include "defines.h"
#include <iostream>
SDL_Window *window = NULL;
SDL_Renderer *renderer = NULL;
SDL_Event *event;
Texture *texture = nullptr;
Ball *ball[NUM_BALLS];
bool shouldExit = false;
Uint32 ticks = 0;
bool init()
{
// Initialization flag
bool success = true;
// Initialize SDL
if (SDL_Init(SDL_INIT_VIDEO) < 0)
{
printf("SDL could not initialize! SDL Error: %s\n", SDL_GetError());
success = false;
}
else
{
// Create window
window = SDL_CreateWindow("SDL Tutorial", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH * 2, SCREEN_HEIGHT * 2, SDL_WINDOW_SHOWN);
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, -1, SDL_RENDERER_ACCELERATED);
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_RenderSetLogicalSize(renderer, SCREEN_WIDTH, SCREEN_HEIGHT);
}
}
}
event = new SDL_Event();
texture = new Texture(renderer, "resources/pelota.png");
for (int i = 0; i < NUM_BALLS; ++i)
{
ball[i] = new Ball(rand() % SCREEN_WIDTH, rand() % SCREEN_HEIGHT, 24, 24, 1, 1, texture);
}
ticks = SDL_GetTicks();
return success;
}
void close()
{
// Destroy window
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
window = NULL;
renderer = NULL;
if (event)
{
delete event;
}
if (texture)
{
delete texture;
}
for (int i = 0; i < NUM_BALLS; ++i)
{
if (ball[i])
{
delete ball[i];
}
}
// Quit SDL subsystems
IMG_Quit();
SDL_Quit();
}
void checkEvents()
{
// Comprueba los eventos que hay en la cola
while (SDL_PollEvent(event) != 0)
{
// Evento de salida de la aplicación
if (event->type == SDL_QUIT)
{
shouldExit = true;
break;
}
}
}
void update()
{
if (SDL_GetTicks() - ticks > 15)
{
ticks = SDL_GetTicks();
for (int i = 0; i < NUM_BALLS; ++i)
{
ball[i]->update();
}
}
}
void render()
{
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 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 (!shouldExit)
{
update();
checkEvents();
render();
}
close();
return 0;
}