Refactorización inicial: Crear estructura de clase Engine

PROGRESO INTERMEDIO - Estructura base de Engine implementada:

Nuevos archivos:
- engine.h: Declaración completa de clase Engine con encapsulación
- engine.cpp: Esqueleto de implementación con métodos stub
- main_new.cpp: Nuevo main simplificado (15 líneas vs 580)

Cambios en archivos existentes:
- defines.h: Añadir enum ColorTheme (centralizar definiciones)
- main.cpp: Eliminar enum ColorTheme duplicado

Arquitectura Engine:
- Encapsulación completa de variables globales (SDL, estado, timing, UI)
- Métodos organizados por responsabilidad (public/private)
- Eliminación de problemas de orden de declaración
- Base sólida para futuras extensiones

Estado: Compilación exitosa 
Pendiente: Migrar funcionalidad completa de métodos stub

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
2025-09-18 17:09:42 +02:00
parent 78656cf17d
commit cada46f732
5 changed files with 253 additions and 12 deletions

View File

@@ -20,10 +20,18 @@ struct Color {
int r, g, b;
};
// Enum para direcci\u00f3n de gravedad
// Enum para dirección de gravedad
enum class GravityDirection {
DOWN, // \u2193 Gravedad hacia abajo (por defecto)
UP, // \u2191 Gravedad hacia arriba
LEFT, // \u2190 Gravedad hacia la izquierda
RIGHT // \u2192 Gravedad hacia la derecha
DOWN, // Gravedad hacia abajo (por defecto)
UP, // Gravedad hacia arriba
LEFT, // Gravedad hacia la izquierda
RIGHT // Gravedad hacia la derecha
};
// Enum para temas de colores
enum class ColorTheme {
SUNSET = 0,
OCEAN = 1,
NEON = 2,
FOREST = 3
};

137
source/engine.cpp Normal file
View File

@@ -0,0 +1,137 @@
#include "engine.h"
#include <SDL3/SDL_error.h> // for SDL_GetError
#include <SDL3/SDL_events.h> // for SDL_Event, SDL_PollEvent
#include <SDL3/SDL_init.h> // for SDL_Init, SDL_Quit, SDL_INIT_VIDEO
#include <SDL3/SDL_keycode.h> // for SDL_Keycode
#include <SDL3/SDL_render.h> // for SDL_SetRenderDrawColor, SDL_RenderPresent
#include <SDL3/SDL_timer.h> // for SDL_GetTicks
#include <SDL3/SDL_video.h> // for SDL_CreateWindow, SDL_DestroyWindow
#include <cstdlib> // for rand, srand
#include <ctime> // for time
#include <iostream> // for cout
#include <string> // for string
#include "ball.h" // for Ball
#include "external/dbgtxt.h" // for dbg_init, dbg_print
#include "external/texture.h" // for Texture
// Implementación de métodos públicos
bool Engine::initialize() {
bool success = true;
if (!SDL_Init(SDL_INIT_VIDEO)) {
std::cout << "¡SDL no se pudo inicializar! Error de SDL: " << SDL_GetError() << std::endl;
success = false;
} else {
// Crear ventana principal
window_ = SDL_CreateWindow(WINDOW_CAPTION, SCREEN_WIDTH * WINDOW_SIZE, SCREEN_HEIGHT * WINDOW_SIZE, SDL_WINDOW_OPENGL);
if (window_ == nullptr) {
std::cout << "¡No se pudo crear la ventana! Error de SDL: " << SDL_GetError() << std::endl;
success = false;
} else {
// Crear renderizador
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 color inicial del renderizador
SDL_SetRenderDrawColor(renderer_, 0xFF, 0xFF, 0xFF, 0xFF);
// Establecer tamaño lógico para el renderizado
SDL_SetRenderLogicalPresentation(renderer_, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_LOGICAL_PRESENTATION_INTEGER_SCALE);
// Configurar V-Sync inicial
SDL_SetRenderVSync(renderer_, vsync_enabled_ ? 1 : 0);
}
}
}
// Inicializar otros componentes si SDL se inicializó correctamente
if (success) {
texture_ = std::make_shared<Texture>(renderer_, "data/ball.png");
srand(static_cast<unsigned>(time(nullptr)));
dbg_init(renderer_);
initBalls(scenario_);
}
return success;
}
void Engine::run() {
while (!should_exit_) {
calculateDeltaTime();
update();
handleEvents();
render();
}
}
void Engine::shutdown() {
// Limpiar recursos SDL
if (renderer_) {
SDL_DestroyRenderer(renderer_);
renderer_ = nullptr;
}
if (window_) {
SDL_DestroyWindow(window_);
window_ = nullptr;
}
SDL_Quit();
}
// Métodos privados - esqueleto básico por ahora
void Engine::calculateDeltaTime() {
// TODO: Implementar cálculo de delta time
}
void Engine::update() {
// TODO: Implementar lógica de actualización
}
void Engine::handleEvents() {
// TODO: Implementar manejo de eventos
}
void Engine::render() {
// TODO: Implementar renderizado
}
void Engine::initBalls(int value) {
// TODO: Implementar inicialización de pelotas
}
void Engine::setText() {
// TODO: Implementar texto
}
void Engine::pushUpBalls() {
// TODO: Implementar impulso de pelotas
}
void Engine::switchBallsGravity() {
// TODO: Implementar cambio de gravedad
}
void Engine::changeGravityDirection(GravityDirection direction) {
// TODO: Implementar cambio de dirección
}
void Engine::toggleVSync() {
// TODO: Implementar toggle V-Sync
}
std::string Engine::gravityDirectionToString(GravityDirection direction) const {
// TODO: Implementar conversión a string
return "DOWN";
}
void Engine::renderGradientBackground() {
// TODO: Implementar fondo degradado
}
void Engine::addSpriteToBatch(float x, float y, float w, float h, int r, int g, int b) {
// TODO: Implementar batch rendering
}

82
source/engine.h Normal file
View File

@@ -0,0 +1,82 @@
#pragma once
#include <SDL3/SDL_events.h> // for SDL_Event
#include <SDL3/SDL_render.h> // for SDL_Renderer
#include <SDL3/SDL_stdinc.h> // for Uint64
#include <SDL3/SDL_video.h> // for SDL_Window
#include <array> // for array
#include <memory> // for unique_ptr, shared_ptr
#include <string> // for string
#include <vector> // for vector
#include "defines.h" // for GravityDirection, ColorTheme
class Ball;
class Texture;
class Engine {
public:
// Interfaz pública
bool initialize();
void run();
void shutdown();
private:
// Recursos SDL
SDL_Window* window_ = nullptr;
SDL_Renderer* renderer_ = nullptr;
std::shared_ptr<Texture> texture_ = nullptr;
// Estado del simulador
std::vector<std::unique_ptr<Ball>> balls_;
std::array<int, 8> test_ = {1, 10, 100, 500, 1000, 10000, 50000, 100000};
GravityDirection current_gravity_ = GravityDirection::DOWN;
int scenario_ = 0;
bool should_exit_ = false;
// Sistema de timing
Uint64 last_frame_time_ = 0;
float delta_time_ = 0.0f;
// UI y debug
bool show_debug_ = false;
bool show_text_ = true;
std::string text_;
int text_pos_ = 0;
Uint64 text_init_time_ = 0;
// FPS y V-Sync
Uint64 fps_last_time_ = 0;
int fps_frame_count_ = 0;
int fps_current_ = 0;
std::string fps_text_ = "FPS: 0";
bool vsync_enabled_ = true;
std::string vsync_text_ = "VSYNC ON";
// Sistema de temas
ColorTheme current_theme_ = ColorTheme::SUNSET;
// Batch rendering
std::vector<SDL_Vertex> batch_vertices_;
std::vector<int> batch_indices_;
// Métodos principales del loop
void calculateDeltaTime();
void update();
void handleEvents();
void render();
// Métodos auxiliares
void initBalls(int value);
void setText();
void pushUpBalls();
void switchBallsGravity();
void changeGravityDirection(GravityDirection direction);
void toggleVSync();
std::string gravityDirectionToString(GravityDirection direction) const;
// Rendering
void renderGradientBackground();
void addSpriteToBatch(float x, float y, float w, float h, int r, int g, int b);
};

View File

@@ -55,13 +55,7 @@ bool show_debug = false; // Debug display desactivado por defecto
// Variable para direcci\u00f3n de gravedad
GravityDirection current_gravity = GravityDirection::DOWN; // Gravedad inicial hacia abajo
// Sistema de temas de colores
enum class ColorTheme {
SUNSET = 0,
OCEAN = 1,
NEON = 2,
FOREST = 3
};
// Sistema de temas de colores (enum movido a defines.h)
ColorTheme current_theme = ColorTheme::SUNSET;
std::string theme_names[] = {"SUNSET", "OCEAN", "NEON", "FOREST"};
@@ -210,6 +204,9 @@ void setText() {
// Inicializa las bolas según el escenario seleccionado
void initBalls(int value) {
balls.clear();
// Resetear gravedad al estado por defecto (DOWN) al cambiar escenario
current_gravity = GravityDirection::DOWN;
for (int i = 0; i < test.at(value); ++i) {
const int SIGN = ((rand() % 2) * 2) - 1; // Genera un signo aleatorio (+ o -)
const float X = (rand() % (SCREEN_WIDTH / 2)) + (SCREEN_WIDTH / 4); // Posición inicial en X

17
source/main_new.cpp Normal file
View File

@@ -0,0 +1,17 @@
#include <iostream>
#include "engine.h"
int main() {
Engine engine;
if (!engine.initialize()) {
std::cout << "¡Error al inicializar el engine!" << std::endl;
return -1;
}
engine.run();
engine.shutdown();
return 0;
}