Compare commits
12 Commits
b1785cf5f1
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 0a3fcd91d7 | |||
| 38f23c83c3 | |||
| 857a0c05f1 | |||
| a7c0b7d8c6 | |||
| 45b763791a | |||
| 57db69d2a4 | |||
| 1eab622ba2 | |||
| 22ddfcd153 | |||
| 9d4625c4eb | |||
| f9fab6e53b | |||
| 17b1e6a491 | |||
| da0aa04f2d |
107
.gitignore
vendored
107
.gitignore
vendored
@@ -1,2 +1,107 @@
|
|||||||
|
demo4_sprites
|
||||||
|
build/
|
||||||
|
|
||||||
|
# ---> C++
|
||||||
|
# Prerequisites
|
||||||
|
*.d
|
||||||
|
|
||||||
|
# Compiled Object files
|
||||||
|
*.slo
|
||||||
|
*.lo
|
||||||
|
*.o
|
||||||
|
*.obj
|
||||||
|
|
||||||
|
# Precompiled Headers
|
||||||
|
*.gch
|
||||||
|
*.pch
|
||||||
|
|
||||||
|
# Compiled Dynamic libraries
|
||||||
|
*.so
|
||||||
|
*.dylib
|
||||||
|
*.dll
|
||||||
|
|
||||||
|
# Fortran module files
|
||||||
|
*.mod
|
||||||
|
*.smod
|
||||||
|
|
||||||
|
# Compiled Static libraries
|
||||||
|
*.lai
|
||||||
|
*.la
|
||||||
|
*.a
|
||||||
|
*.lib
|
||||||
|
|
||||||
|
# Executables
|
||||||
*.exe
|
*.exe
|
||||||
*.dll
|
*.out
|
||||||
|
*.app
|
||||||
|
|
||||||
|
# ---> macOS
|
||||||
|
# General
|
||||||
|
.DS_Store
|
||||||
|
.AppleDouble
|
||||||
|
.LSOverride
|
||||||
|
|
||||||
|
# Icon must end with two \r
|
||||||
|
Icon
|
||||||
|
|
||||||
|
|
||||||
|
# Thumbnails
|
||||||
|
._*
|
||||||
|
|
||||||
|
# Files that might appear in the root of a volume
|
||||||
|
.DocumentRevisions-V100
|
||||||
|
.fseventsd
|
||||||
|
.Spotlight-V100
|
||||||
|
.TemporaryItems
|
||||||
|
.Trashes
|
||||||
|
.VolumeIcon.icns
|
||||||
|
.com.apple.timemachine.donotpresent
|
||||||
|
|
||||||
|
# Directories potentially created on remote AFP share
|
||||||
|
.AppleDB
|
||||||
|
.AppleDesktop
|
||||||
|
Network Trash Folder
|
||||||
|
Temporary Items
|
||||||
|
.apdisk
|
||||||
|
|
||||||
|
# ---> Windows
|
||||||
|
# Windows thumbnail cache files
|
||||||
|
Thumbs.db
|
||||||
|
Thumbs.db:encryptable
|
||||||
|
ehthumbs.db
|
||||||
|
ehthumbs_vista.db
|
||||||
|
|
||||||
|
# Dump file
|
||||||
|
*.stackdump
|
||||||
|
|
||||||
|
# Folder config file
|
||||||
|
[Dd]esktop.ini
|
||||||
|
|
||||||
|
# Recycle Bin used on file shares
|
||||||
|
$RECYCLE.BIN/
|
||||||
|
|
||||||
|
# Windows Installer files
|
||||||
|
*.cab
|
||||||
|
*.msi
|
||||||
|
*.msix
|
||||||
|
*.msm
|
||||||
|
*.msp
|
||||||
|
|
||||||
|
# Windows shortcuts
|
||||||
|
*.lnk
|
||||||
|
|
||||||
|
# ---> Linux
|
||||||
|
*~
|
||||||
|
|
||||||
|
# temporary files which can be created if a process still has a handle open of a deleted file
|
||||||
|
.fuse_hidden*
|
||||||
|
|
||||||
|
# KDE directory preferences
|
||||||
|
.directory
|
||||||
|
|
||||||
|
# Linux trash folder which might appear on any partition or disk
|
||||||
|
.Trash-*
|
||||||
|
|
||||||
|
# .nfs files are created when an open file is removed but is still being accessed
|
||||||
|
.nfs*
|
||||||
|
|
||||||
|
|||||||
49
CMakeLists.txt
Normal file
49
CMakeLists.txt
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
cmake_minimum_required(VERSION 3.20)
|
||||||
|
project(demo4_sprites)
|
||||||
|
|
||||||
|
# Establecer el estándar de C++
|
||||||
|
set(CMAKE_CXX_STANDARD 20)
|
||||||
|
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||||
|
|
||||||
|
# Opciones comunes de compilación
|
||||||
|
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Os -ffunction-sections -fdata-sections")
|
||||||
|
|
||||||
|
# Buscar SDL3 automáticamente
|
||||||
|
find_package(SDL3 REQUIRED)
|
||||||
|
|
||||||
|
# Si no se encuentra SDL3, generar un error
|
||||||
|
if (NOT SDL3_FOUND)
|
||||||
|
message(FATAL_ERROR "SDL3 no encontrado. Por favor, verifica su instalación.")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
# Archivos fuente
|
||||||
|
file(GLOB SOURCE_FILES source/*.cpp)
|
||||||
|
|
||||||
|
# Comprobar si se encontraron archivos fuente
|
||||||
|
if(NOT SOURCE_FILES)
|
||||||
|
message(FATAL_ERROR "No se encontraron archivos fuente en el directorio 'source/'. Verifica la ruta.")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
# Detectar la plataforma y configuraciones específicas
|
||||||
|
if(WIN32)
|
||||||
|
set(PLATFORM windows)
|
||||||
|
set(LINK_LIBS ${SDL3_LIBRARIES} mingw32 ws2_32)
|
||||||
|
elseif(UNIX AND NOT APPLE)
|
||||||
|
set(PLATFORM linux)
|
||||||
|
set(LINK_LIBS ${SDL3_LIBRARIES})
|
||||||
|
elseif(APPLE)
|
||||||
|
set(PLATFORM macos)
|
||||||
|
set(LINK_LIBS ${SDL3_LIBRARIES})
|
||||||
|
endif()
|
||||||
|
|
||||||
|
# Incluir directorios de SDL3
|
||||||
|
include_directories(${SDL3_INCLUDE_DIRS})
|
||||||
|
|
||||||
|
# Añadir el ejecutable reutilizando el nombre del proyecto
|
||||||
|
add_executable(${PROJECT_NAME} ${SOURCE_FILES})
|
||||||
|
|
||||||
|
# Especificar la ubicación del ejecutable (en la raíz del proyecto)
|
||||||
|
set_target_properties(${PROJECT_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR})
|
||||||
|
|
||||||
|
# Enlazar las bibliotecas necesarias
|
||||||
|
target_link_libraries(${PROJECT_NAME} ${LINK_LIBS})
|
||||||
23
Makefile
23
Makefile
@@ -1,5 +1,20 @@
|
|||||||
source := source/*.cpp
|
# Variables comunes
|
||||||
executable_name := pelota
|
SOURCE := source/*.cpp
|
||||||
|
EXECUTABLE_NAME := demo4_sprites
|
||||||
|
CXXFLAGS := -std=c++20 -Wall -Os -ffunction-sections -fdata-sections # Opciones comunes de compilación
|
||||||
|
LDFLAGS := -lSDL3 # Flags de enlace comunes
|
||||||
|
OUTPUT_EXT :=
|
||||||
|
|
||||||
windows:
|
# Detectar plataforma y configurar
|
||||||
g++ $(source) -lmingw32 -lws2_32 -lSDL2main -lSDL2 -lSDL2_image -o $(executable_name).exe
|
ifeq ($(OS),Windows_NT)
|
||||||
|
LDFLAGS += -lmingw32 -lws2_32
|
||||||
|
OUTPUT_EXT := .exe
|
||||||
|
endif
|
||||||
|
|
||||||
|
# Regla principal: compilar el ejecutable
|
||||||
|
all:
|
||||||
|
$(CXX) $(SOURCE) $(CXXFLAGS) $(LDFLAGS) -o $(EXECUTABLE_NAME)$(OUTPUT_EXT)
|
||||||
|
|
||||||
|
# Regla para limpiar archivos generados
|
||||||
|
clean:
|
||||||
|
rm -f $(EXECUTABLE_NAME)$(OUTPUT_EXT)
|
||||||
Binary file not shown.
|
Before Width: | Height: | Size: 542 B |
BIN
resources/soccer_ball.aseprite
Normal file
BIN
resources/soccer_ball.aseprite
Normal file
Binary file not shown.
BIN
resources/soccer_ball.png
Normal file
BIN
resources/soccer_ball.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 1.2 KiB |
@@ -1,5 +1,4 @@
|
|||||||
#include "ball.h"
|
#include "ball.h"
|
||||||
#include "defines.h"
|
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
Ball::Ball(int x, int y, int w, int h, int vx, int vy, Texture *texture)
|
Ball::Ball(int x, int y, int w, int h, int vx, int vy, Texture *texture)
|
||||||
@@ -13,8 +12,8 @@ Ball::Ball(int x, int y, int w, int h, int vx, int vy, Texture *texture)
|
|||||||
sprite = new Sprite(texture);
|
sprite = new Sprite(texture);
|
||||||
sprite->setPos({x, y});
|
sprite->setPos({x, y});
|
||||||
sprite->setSize(w, h);
|
sprite->setSize(w, h);
|
||||||
sprite->setClip({0, 0, 24, 24});
|
sprite->setClip({0, 0, static_cast<float>(w), static_cast<float>(h)});
|
||||||
color = {255, 255, 255};
|
color = {(rand() % 192) + 32, (rand() % 192) + 32, (rand() % 192) + 32};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Destructor
|
// Destructor
|
||||||
@@ -46,9 +45,9 @@ void Ball::update()
|
|||||||
collision = true;
|
collision = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (x + w > SCREEN_WIDTH)
|
if (x + w > DEMO_WIDTH)
|
||||||
{
|
{
|
||||||
x = SCREEN_WIDTH - w;
|
x = DEMO_WIDTH - w;
|
||||||
vx = -luckyX;
|
vx = -luckyX;
|
||||||
collision = true;
|
collision = true;
|
||||||
}
|
}
|
||||||
@@ -60,16 +59,16 @@ void Ball::update()
|
|||||||
collision = true;
|
collision = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (y + h > SCREEN_HEIGHT)
|
if (y + h > DEMO_HEIGHT)
|
||||||
{
|
{
|
||||||
y = SCREEN_HEIGHT - h;
|
y = DEMO_HEIGHT - h;
|
||||||
vy = -luckyY;
|
vy = -luckyY;
|
||||||
collision = true;
|
collision = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (collision)
|
if (collision)
|
||||||
{
|
{
|
||||||
color = {rand() % 255, rand() % 255, rand() % 255};
|
sprite->setAnimationSpeed((rand() % 15) + 5);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Actualiza la posición del sprite
|
// Actualiza la posición del sprite
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ private:
|
|||||||
int w; // Ancho
|
int w; // Ancho
|
||||||
int h; // Alto
|
int h; // Alto
|
||||||
int vx, vy; // Velocidad
|
int vx, vy; // Velocidad
|
||||||
color_t color; // Color de la pelota
|
Color color; // Color de la pelota
|
||||||
|
|
||||||
public:
|
public:
|
||||||
// Constructor
|
// Constructor
|
||||||
|
|||||||
@@ -1,10 +1,21 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#define SCREEN_WIDTH 320
|
constexpr Uint64 DEMO_SPEED = 1000/60;
|
||||||
#define SCREEN_HEIGHT 240
|
|
||||||
#define NUM_BALLS 100
|
|
||||||
|
|
||||||
struct color_t
|
constexpr int DEMO_WIDTH = 480;
|
||||||
|
constexpr int DEMO_HEIGHT = 360;
|
||||||
|
constexpr int WINDOW_ZOOM = 2;
|
||||||
|
constexpr int NUM_BALLS = 100;
|
||||||
|
constexpr int BALL_SIZE = 36;
|
||||||
|
constexpr int NUM_FRAMES = 4;
|
||||||
|
|
||||||
|
constexpr int BG_R = 96;
|
||||||
|
constexpr int BG_G = 96;
|
||||||
|
constexpr int BG_B = 96;
|
||||||
|
|
||||||
|
constexpr char TEXTURE_FILE[] = "resources/soccer_ball.png";
|
||||||
|
|
||||||
|
struct Color
|
||||||
{
|
{
|
||||||
int r,g,b;
|
int r, g, b;
|
||||||
};
|
};
|
||||||
266
source/main.cpp
266
source/main.cpp
@@ -1,168 +1,188 @@
|
|||||||
#include <SDL2/SDL.h>
|
|
||||||
#include <SDL2/SDL_image.h>
|
|
||||||
#include "texture.h"
|
#include "texture.h"
|
||||||
#include "ball.h"
|
#include "ball.h"
|
||||||
#include "defines.h"
|
#include "defines.h"
|
||||||
#include <iostream>
|
#include <iostream>
|
||||||
|
#include <SDL3/SDL.h>
|
||||||
|
|
||||||
SDL_Window *window = NULL;
|
// Ventana principal y renderizador
|
||||||
SDL_Renderer *renderer = NULL;
|
SDL_Window *window = nullptr;
|
||||||
SDL_Event *event;
|
SDL_Renderer *renderer = nullptr;
|
||||||
|
|
||||||
|
// Textura y bolas
|
||||||
Texture *texture = nullptr;
|
Texture *texture = nullptr;
|
||||||
Ball *ball[NUM_BALLS];
|
Ball *ball[NUM_BALLS];
|
||||||
|
|
||||||
bool shouldExit = false;
|
// Control de la aplicación
|
||||||
Uint32 ticks = 0;
|
bool should_exit = false;
|
||||||
|
Uint64 ticks = 0;
|
||||||
|
|
||||||
|
// Inicializa SDL, la ventana, el renderizador y los elementos del juego
|
||||||
bool init()
|
bool init()
|
||||||
{
|
{
|
||||||
// Initialization flag
|
// Indicador de inicialización exitosa
|
||||||
bool success = true;
|
bool success = true;
|
||||||
|
|
||||||
// Initialize SDL
|
// Inicializar SDL
|
||||||
if (SDL_Init(SDL_INIT_VIDEO) < 0)
|
if (!SDL_Init(SDL_INIT_VIDEO))
|
||||||
{
|
{
|
||||||
printf("SDL could not initialize! SDL Error: %s\n", SDL_GetError());
|
std::cout << "¡SDL no pudo inicializarse! Error de SDL: " << SDL_GetError() << std::endl;
|
||||||
success = false;
|
success = false;
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
// Set texture filtering to linear
|
// Crear ventana
|
||||||
if (!SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "1"))
|
window = SDL_CreateWindow("demo_pelotas1", DEMO_WIDTH * WINDOW_ZOOM, DEMO_HEIGHT * WINDOW_ZOOM, SDL_WINDOW_OPENGL);
|
||||||
{
|
if (window == nullptr)
|
||||||
printf("Warning: Linear texture filtering not enabled!");
|
{
|
||||||
}
|
std::cout << "¡No se pudo crear la ventana! Error de SDL: " << SDL_GetError() << std::endl;
|
||||||
|
success = false;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
// Crear renderizador para la ventana
|
||||||
|
renderer = SDL_CreateRenderer(window, nullptr);
|
||||||
|
if (renderer == nullptr)
|
||||||
|
{
|
||||||
|
std::cout << "¡No se pudo crear el renderizador! Error de SDL: " << SDL_GetError() << std::endl;
|
||||||
|
success = false;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
// Establecer el color inicial del renderizador
|
||||||
|
SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF);
|
||||||
|
|
||||||
// Create window
|
// Configurar el renderizador para usar una presentación lógica
|
||||||
window = SDL_CreateWindow("SDL Tutorial", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH * 2, SCREEN_HEIGHT * 2, SDL_WINDOW_SHOWN);
|
SDL_SetRenderLogicalPresentation(renderer, DEMO_WIDTH, DEMO_HEIGHT, SDL_LOGICAL_PRESENTATION_INTEGER_SCALE);
|
||||||
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);
|
|
||||||
|
|
||||||
// Initialize PNG loading
|
// Crear textura y bolas
|
||||||
int imgFlags = IMG_INIT_PNG;
|
texture = new Texture(renderer, TEXTURE_FILE);
|
||||||
if (!(IMG_Init(imgFlags) & imgFlags))
|
for (int i = 0; i < NUM_BALLS; ++i)
|
||||||
{
|
{
|
||||||
printf("SDL_image could not initialize! SDL_image Error: %s\n", IMG_GetError());
|
const int VX = rand() % 2 == 0 ? 1 : -1;
|
||||||
success = false;
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
SDL_RenderSetLogicalSize(renderer, SCREEN_WIDTH, SCREEN_HEIGHT);
|
// Configuración inicial de tiempos
|
||||||
}
|
ticks = SDL_GetTicks();
|
||||||
}
|
srand(time(nullptr));
|
||||||
}
|
|
||||||
|
|
||||||
event = new SDL_Event();
|
return success;
|
||||||
|
|
||||||
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;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Limpia y libera todos los recursos
|
||||||
void close()
|
void close()
|
||||||
{
|
{
|
||||||
// Destroy window
|
// Destruir el renderizador y la ventana
|
||||||
SDL_DestroyRenderer(renderer);
|
SDL_DestroyRenderer(renderer);
|
||||||
SDL_DestroyWindow(window);
|
SDL_DestroyWindow(window);
|
||||||
window = NULL;
|
|
||||||
renderer = NULL;
|
|
||||||
|
|
||||||
if (event)
|
// Eliminar la textura
|
||||||
{
|
if (texture)
|
||||||
delete event;
|
{
|
||||||
}
|
delete texture;
|
||||||
|
}
|
||||||
|
|
||||||
if (texture)
|
// Eliminar todas las bolas
|
||||||
{
|
for (int i = 0; i < NUM_BALLS; ++i)
|
||||||
delete texture;
|
{
|
||||||
}
|
if (ball[i])
|
||||||
|
{
|
||||||
|
delete ball[i];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
for (int i = 0; i < NUM_BALLS; ++i)
|
// Finalizar SDL
|
||||||
{
|
SDL_Quit();
|
||||||
if (ball[i])
|
|
||||||
{
|
|
||||||
delete ball[i];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Quit SDL subsystems
|
|
||||||
IMG_Quit();
|
|
||||||
SDL_Quit();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Gestiona los eventos del usuario
|
||||||
void checkEvents()
|
void checkEvents()
|
||||||
{
|
{
|
||||||
// Comprueba los eventos que hay en la cola
|
SDL_Event event;
|
||||||
while (SDL_PollEvent(event) != 0)
|
|
||||||
{
|
// Procesar todos los eventos en la cola
|
||||||
// Evento de salida de la aplicación
|
while (SDL_PollEvent(&event) != 0)
|
||||||
if (event->type == SDL_QUIT)
|
{
|
||||||
{
|
// Detectar si el usuario quiere cerrar la aplicación
|
||||||
shouldExit = true;
|
if (event.type == SDL_EVENT_QUIT)
|
||||||
break;
|
{
|
||||||
}
|
should_exit = true;
|
||||||
}
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Manejar eventos de teclado
|
||||||
|
if (event.type == SDL_EVENT_KEY_DOWN && event.key.repeat == 0)
|
||||||
|
{
|
||||||
|
switch (event.key.key)
|
||||||
|
{
|
||||||
|
case SDLK_ESCAPE: // Salir de la aplicación
|
||||||
|
should_exit = true;
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Actualiza el estado de las bolas
|
||||||
void update()
|
void update()
|
||||||
{
|
{
|
||||||
if (SDL_GetTicks() - ticks > 15)
|
if (SDL_GetTicks() - ticks > DEMO_SPEED)
|
||||||
{
|
{
|
||||||
ticks = SDL_GetTicks();
|
ticks = SDL_GetTicks();
|
||||||
|
|
||||||
for (int i = 0; i < NUM_BALLS; ++i)
|
// Actualizar la posición de cada bola
|
||||||
{
|
for (int i = 0; i < NUM_BALLS; ++i)
|
||||||
ball[i]->update();
|
{
|
||||||
}
|
ball[i]->update();
|
||||||
}
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Dibuja el estado actual en la pantalla
|
||||||
void render()
|
void render()
|
||||||
{
|
{
|
||||||
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
|
// Limpiar la pantalla con el color de fondo
|
||||||
SDL_RenderClear(renderer);
|
SDL_SetRenderDrawColor(renderer, BG_R, BG_G, BG_B, 255);
|
||||||
|
SDL_RenderClear(renderer);
|
||||||
|
|
||||||
for (int i = 0; i < NUM_BALLS; ++i)
|
// Dibujar todas las bolas
|
||||||
{
|
for (int i = 0; i < NUM_BALLS; ++i)
|
||||||
ball[i]->render();
|
{
|
||||||
}
|
ball[i]->render();
|
||||||
|
}
|
||||||
|
|
||||||
SDL_RenderPresent(renderer);
|
// Presentar el renderizador
|
||||||
|
SDL_RenderPresent(renderer);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Función principal
|
||||||
int main(int argc, char *args[])
|
int main(int argc, char *args[])
|
||||||
{
|
{
|
||||||
init();
|
if (!init())
|
||||||
|
{
|
||||||
|
return -1; // Salir si la inicialización falla
|
||||||
|
}
|
||||||
|
|
||||||
while (!shouldExit)
|
// Bucle principal del juego
|
||||||
{
|
while (!should_exit)
|
||||||
update();
|
{
|
||||||
checkEvents();
|
update();
|
||||||
render();
|
checkEvents();
|
||||||
}
|
render();
|
||||||
|
}
|
||||||
|
|
||||||
close();
|
// Limpiar y cerrar la aplicación
|
||||||
|
close();
|
||||||
|
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,65 +3,67 @@
|
|||||||
// Constructor
|
// Constructor
|
||||||
Sprite::Sprite(Texture *texture)
|
Sprite::Sprite(Texture *texture)
|
||||||
{
|
{
|
||||||
this->texture = texture;
|
texture_ = texture;
|
||||||
pos = {0, 0, 0, 0};
|
pos_ = {0, 0, 0, 0};
|
||||||
clip = {0, 0, 0, 0};
|
clip_ = {0, 0, 0, 0};
|
||||||
frame = 0;
|
frame_ = 0;
|
||||||
numFrames = 3;
|
num_frames_ = NUM_FRAMES;
|
||||||
animationSpeed = 20;
|
animation_speed_ = 20;
|
||||||
animationCounter = 0;
|
animation_counter_ = 0;
|
||||||
}
|
|
||||||
|
|
||||||
// Destructor
|
|
||||||
Sprite::~Sprite()
|
|
||||||
{
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Establece la posición del sprite
|
// Establece la posición del sprite
|
||||||
void Sprite::setPos(SDL_Point pos)
|
void Sprite::setPos(SDL_Point pos)
|
||||||
{
|
{
|
||||||
this->pos.x = pos.x;
|
pos_.x = pos.x;
|
||||||
this->pos.y = pos.y;
|
pos_.y = pos.y;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Pinta el sprite
|
// Pinta el sprite
|
||||||
void Sprite::render()
|
void Sprite::render()
|
||||||
{
|
{
|
||||||
texture->render(&clip, &pos);
|
texture_->render(&clip_, &pos_);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Actualiza la lógica de la clase
|
// Actualiza la lógica de la clase
|
||||||
void Sprite::update()
|
void Sprite::update()
|
||||||
{
|
{
|
||||||
animationCounter++;
|
animation_counter_++;
|
||||||
if (animationCounter % animationSpeed == 0)
|
if (animation_counter_ % animation_speed_ == 0)
|
||||||
{
|
{
|
||||||
animate();
|
animate();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Establece el rectangulo de la textura que se va a pintar
|
// Establece el rectangulo de la textura que se va a pintar
|
||||||
void Sprite::setClip(SDL_Rect clip)
|
void Sprite::setClip(SDL_FRect clip)
|
||||||
{
|
{
|
||||||
this->clip = clip;
|
clip_ = clip;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Establece el tamaño del sprite
|
// Establece el tamaño del sprite
|
||||||
void Sprite::setSize(int w, int h)
|
void Sprite::setSize(int w, int h)
|
||||||
{
|
{
|
||||||
this->pos.w = w;
|
pos_.w = w;
|
||||||
this->pos.h = h;
|
pos_.h = h;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Anima el sprite
|
// Anima el sprite
|
||||||
void Sprite::animate()
|
void Sprite::animate()
|
||||||
{
|
{
|
||||||
frame = (frame + 1) % numFrames;
|
frame_ = (frame_ + 1) % num_frames_;
|
||||||
clip.x = frame * pos.w;
|
clip_.x = frame_ * pos_.w;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Modulación de color
|
// Modulación de color
|
||||||
void Sprite::setColor(int r, int g, int b)
|
void Sprite::setColor(int r, int g, int b)
|
||||||
{
|
{
|
||||||
texture->setColor(r, g, b);
|
texture_->setColor(r, g, b);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Cambia la velocidad de la animación
|
||||||
|
void Sprite::setAnimationSpeed(int value)
|
||||||
|
{
|
||||||
|
animation_speed_ = value;
|
||||||
|
animation_counter_ = 0;
|
||||||
}
|
}
|
||||||
@@ -1,28 +1,28 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <SDL2/SDL.h>
|
|
||||||
#include "texture.h"
|
#include "texture.h"
|
||||||
|
#include "defines.h"
|
||||||
|
|
||||||
class Sprite
|
class Sprite
|
||||||
{
|
{
|
||||||
private:
|
private:
|
||||||
Texture *texture; // Textura con los gráficos del sprite
|
Texture *texture_; // Textura con los gráficos del sprite
|
||||||
SDL_Rect pos; // Posición y tamaño del sprite
|
SDL_FRect pos_; // Posición y tamaño del sprite
|
||||||
SDL_Rect clip; // Parte de la textura que se va a dibujar
|
SDL_FRect clip_; // Parte de la textura que se va a dibujar
|
||||||
int frame; // Frame a dibujar de la textura definido en clip
|
int frame_; // Frame a dibujar de la textura definido en clip
|
||||||
int numFrames; // Numero total de frames
|
int num_frames_; // Numero total de frames
|
||||||
int animationSpeed; // Velocidad de animación
|
int animation_speed_; // Velocidad de animación
|
||||||
int animationCounter; // Contador para la animación
|
int animation_counter_; // Contador para la animación
|
||||||
|
|
||||||
// Anima el sprite
|
// Anima el sprite
|
||||||
void animate();
|
void animate();
|
||||||
|
|
||||||
public:
|
public:
|
||||||
// Constructor
|
// Constructor
|
||||||
Sprite(Texture *texture);
|
explicit Sprite(Texture *texture);
|
||||||
|
|
||||||
// Destructor
|
// Destructor
|
||||||
~Sprite();
|
~Sprite() = default;
|
||||||
|
|
||||||
// Establece la posición del sprite
|
// Establece la posición del sprite
|
||||||
void setPos(SDL_Point pos);
|
void setPos(SDL_Point pos);
|
||||||
@@ -34,11 +34,14 @@ public:
|
|||||||
void update();
|
void update();
|
||||||
|
|
||||||
// Establece el rectangulo de la textura que se va a pintar
|
// Establece el rectangulo de la textura que se va a pintar
|
||||||
void setClip(SDL_Rect clip);
|
void setClip(SDL_FRect clip);
|
||||||
|
|
||||||
// Establece el tamaño del sprite
|
// Establece el tamaño del sprite
|
||||||
void setSize(int w, int h);
|
void setSize(int w, int h);
|
||||||
|
|
||||||
// Modulación de color
|
// Modulación de color
|
||||||
void setColor(int r, int g, int b);
|
void setColor(int r, int g, int b);
|
||||||
|
|
||||||
|
// Cambia la velocidad de la animación
|
||||||
|
void setAnimationSpeed(int value);
|
||||||
};
|
};
|
||||||
7897
source/stb_image.h
Normal file
7897
source/stb_image.h
Normal file
File diff suppressed because it is too large
Load Diff
@@ -1,23 +1,16 @@
|
|||||||
#include <SDL2/SDL_image.h>
|
#define STB_IMAGE_IMPLEMENTATION
|
||||||
|
#include "stb_image.h"
|
||||||
#include <stdio.h>
|
#include <stdio.h>
|
||||||
#include <string>
|
#include <string>
|
||||||
#include "texture.h"
|
#include "texture.h"
|
||||||
|
|
||||||
Texture::Texture(SDL_Renderer *renderer)
|
Texture::Texture(SDL_Renderer *renderer)
|
||||||
{
|
: renderer_(renderer), texture_(nullptr), width_(0), height_(0) {}
|
||||||
this->renderer = renderer;
|
|
||||||
texture = NULL;
|
|
||||||
width = 0;
|
|
||||||
height = 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
Texture::Texture(SDL_Renderer *renderer, std::string filepath)
|
Texture::Texture(SDL_Renderer *renderer, std::string file_path)
|
||||||
|
: renderer_(renderer), texture_(nullptr), width_(0), height_(0)
|
||||||
{
|
{
|
||||||
this->renderer = renderer;
|
loadFromFile(file_path);
|
||||||
texture = NULL;
|
|
||||||
width = 0;
|
|
||||||
height = 0;
|
|
||||||
loadFromFile(filepath);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Texture::~Texture()
|
Texture::~Texture()
|
||||||
@@ -25,77 +18,102 @@ Texture::~Texture()
|
|||||||
free();
|
free();
|
||||||
}
|
}
|
||||||
|
|
||||||
bool Texture::loadFromFile(std::string path)
|
bool Texture::loadFromFile(std::string file_path)
|
||||||
{
|
{
|
||||||
// Get rid of preexisting texture
|
const std::string filename = file_path.substr(file_path.find_last_of("\\/") + 1);
|
||||||
free();
|
int req_format = STBI_rgb_alpha;
|
||||||
|
int width, height, orig_format;
|
||||||
// The final texture
|
unsigned char *data = stbi_load(file_path.c_str(), &width, &height, &orig_format, req_format);
|
||||||
SDL_Texture *newTexture = NULL;
|
if (data == nullptr)
|
||||||
|
|
||||||
// Load image at specified path
|
|
||||||
SDL_Surface *loadedSurface = IMG_Load(path.c_str());
|
|
||||||
if (loadedSurface == NULL)
|
|
||||||
{
|
{
|
||||||
printf("Unable to load image %s! SDL_image Error: %s\n", path.c_str(), IMG_GetError());
|
SDL_Log("Loading image failed: %s", stbi_failure_reason());
|
||||||
|
exit(1);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
// Color key image
|
std::cout << "Image loaded: " << filename.c_str() << std::endl;
|
||||||
SDL_SetColorKey(loadedSurface, SDL_TRUE, SDL_MapRGB(loadedSurface->format, 0, 0xFF, 0xFF));
|
}
|
||||||
|
|
||||||
// Create texture from surface pixels
|
int pitch;
|
||||||
newTexture = SDL_CreateTextureFromSurface(renderer, loadedSurface);
|
SDL_PixelFormat pixel_format;
|
||||||
if (newTexture == NULL)
|
if (req_format == STBI_rgb)
|
||||||
|
{
|
||||||
|
pitch = 3 * width; // 3 bytes por pixel * pixels por linea
|
||||||
|
pixel_format = SDL_PIXELFORMAT_RGB24;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{ // STBI_rgb_alpha (RGBA)
|
||||||
|
pitch = 4 * width;
|
||||||
|
pixel_format = SDL_PIXELFORMAT_RGBA32;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Limpia
|
||||||
|
free();
|
||||||
|
|
||||||
|
// La textura final
|
||||||
|
SDL_Texture *new_texture = nullptr;
|
||||||
|
|
||||||
|
// Carga la imagen desde una ruta específica
|
||||||
|
SDL_Surface *loaded_surface = SDL_CreateSurfaceFrom(width, height, pixel_format, (void *)data, pitch);
|
||||||
|
if (loaded_surface == nullptr)
|
||||||
|
{
|
||||||
|
std::cout << "Unable to load image " << file_path << std::endl;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
// Crea la textura desde los pixels de la surface
|
||||||
|
new_texture = SDL_CreateTextureFromSurface(renderer_, loaded_surface);
|
||||||
|
if (new_texture == nullptr)
|
||||||
{
|
{
|
||||||
printf("Unable to create texture from %s! SDL Error: %s\n", path.c_str(), SDL_GetError());
|
std::cout << "Unable to create texture from " << file_path << "! SDL Error: " << SDL_GetError() << std::endl;
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
// Get image dimensions
|
// Obtiene las dimensiones de la imagen
|
||||||
width = loadedSurface->w;
|
width_ = loaded_surface->w;
|
||||||
height = loadedSurface->h;
|
height_ = loaded_surface->h;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get rid of old loaded surface
|
// Elimina la textura cargada
|
||||||
SDL_FreeSurface(loadedSurface);
|
SDL_DestroySurface(loaded_surface);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Return success
|
// Return success
|
||||||
texture = newTexture;
|
stbi_image_free(data);
|
||||||
return texture != NULL;
|
texture_ = new_texture;
|
||||||
|
return texture_ != nullptr;
|
||||||
}
|
}
|
||||||
|
|
||||||
void Texture::free()
|
void Texture::free()
|
||||||
{
|
{
|
||||||
// Free texture if it exists
|
// Free texture if it exists
|
||||||
if (texture != NULL)
|
if (texture_ != NULL)
|
||||||
{
|
{
|
||||||
SDL_DestroyTexture(texture);
|
SDL_DestroyTexture(texture_);
|
||||||
texture = NULL;
|
texture_ = NULL;
|
||||||
width = 0;
|
width_ = 0;
|
||||||
height = 0;
|
height_ = 0;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void Texture::render(SDL_Rect *src, SDL_Rect *dst)
|
void Texture::render(SDL_FRect *src, SDL_FRect *dst)
|
||||||
{
|
{
|
||||||
// Render to screen
|
// Render to screen
|
||||||
SDL_RenderCopy(renderer, texture, src, dst);
|
SDL_RenderTexture(renderer_, texture_, src, dst);
|
||||||
}
|
}
|
||||||
|
|
||||||
int Texture::getWidth()
|
int Texture::getWidth()
|
||||||
{
|
{
|
||||||
return width;
|
return width_;
|
||||||
}
|
}
|
||||||
|
|
||||||
int Texture::getHeight()
|
int Texture::getHeight()
|
||||||
{
|
{
|
||||||
return height;
|
return height_;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Modulación de color
|
// Modulación de color
|
||||||
void Texture::setColor(int r, int g, int b)
|
void Texture::setColor(int r, int g, int b)
|
||||||
{
|
{
|
||||||
SDL_SetTextureColorMod(texture, r, g, b);
|
SDL_SetTextureColorMod(texture_, r, g, b);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,23 +1,23 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <SDL2/SDL.h>
|
#include <SDL3/SDL.h>
|
||||||
#include <iostream>
|
#include <iostream>
|
||||||
|
|
||||||
// Texture wrapper class
|
// Texture wrapper class
|
||||||
class Texture
|
class Texture
|
||||||
{
|
{
|
||||||
private:
|
private:
|
||||||
SDL_Renderer *renderer;
|
SDL_Renderer *renderer_;
|
||||||
SDL_Texture *texture;
|
SDL_Texture *texture_;
|
||||||
|
|
||||||
// Image dimensions
|
// Image dimensions
|
||||||
int width;
|
int width_;
|
||||||
int height;
|
int height_;
|
||||||
|
|
||||||
public:
|
public:
|
||||||
// Initializes variables
|
// Initializes variables
|
||||||
Texture(SDL_Renderer *renderer);
|
Texture(SDL_Renderer *renderer);
|
||||||
Texture(SDL_Renderer *renderer, std::string filepath);
|
Texture(SDL_Renderer *renderer, std::string file_path);
|
||||||
|
|
||||||
// Deallocates memory
|
// Deallocates memory
|
||||||
~Texture();
|
~Texture();
|
||||||
@@ -29,7 +29,7 @@ public:
|
|||||||
void free();
|
void free();
|
||||||
|
|
||||||
// Renders texture at given point
|
// Renders texture at given point
|
||||||
void render(SDL_Rect *src = nullptr, SDL_Rect *dst = nullptr);
|
void render(SDL_FRect *src = nullptr, SDL_FRect *dst = nullptr);
|
||||||
|
|
||||||
// Gets image dimensions
|
// Gets image dimensions
|
||||||
int getWidth();
|
int getWidth();
|
||||||
|
|||||||
Reference in New Issue
Block a user