8 Commits

Author SHA1 Message Date
9ceb21c04f colisions bala-enemic 2025-12-02 13:22:26 +01:00
76a91b4736 restaurada funcionalitat de disparar 2025-12-02 13:09:34 +01:00
df744338f1 enemics ja no ixen del area de joc 2025-12-02 10:01:31 +01:00
8803fc3806 afegit vsync toggle 2025-12-02 09:44:58 +01:00
c26a4774a1 afegit comptador de frames per segon 2025-12-02 09:09:22 +01:00
20538af4c6 LOGO explota 2025-12-02 08:50:38 +01:00
73f222fcb7 afegit debris_manager 2025-12-02 08:30:32 +01:00
67681e0f37 el marcador fake ja es pinta correctament 2025-12-01 23:47:42 +01:00
25 changed files with 2091 additions and 1303 deletions

21
.clang-format Normal file
View File

@@ -0,0 +1,21 @@
BasedOnStyle: Google
IndentWidth: 4
IndentAccessModifiers: true
ColumnLimit: 0 # Sin límite de longitud de línea
BreakBeforeBraces: Attach # Llaves en la misma línea
AllowShortIfStatementsOnASingleLine: true
AllowShortBlocksOnASingleLine: true
AllowShortFunctionsOnASingleLine: All
AlignOperands: DontAlign
AlignAfterOpenBracket: DontAlign
BinPackArguments: false
BinPackParameters: false
ContinuationIndentWidth: 4
ConstructorInitializerIndentWidth: 4
IndentWrappedFunctionNames: false
Cpp11BracedListStyle: true
BreakConstructorInitializers: BeforeColon
AllowAllConstructorInitializersOnNextLine: false
PackConstructorInitializers: Never
AllowAllArgumentsOnNextLine: false
AllowAllParametersOfDeclarationOnNextLine: false

View File

@@ -1,7 +1,7 @@
# CMakeLists.txt # CMakeLists.txt
cmake_minimum_required(VERSION 3.10) cmake_minimum_required(VERSION 3.10)
project(orni VERSION 0.1.0) project(orni VERSION 0.2.0)
# Info del proyecto # Info del proyecto
set(PROJECT_LONG_NAME "Orni Attack") set(PROJECT_LONG_NAME "Orni Attack")
@@ -51,6 +51,7 @@ set(APP_SOURCES
source/game/entities/nau.cpp source/game/entities/nau.cpp
source/game/entities/bala.cpp source/game/entities/bala.cpp
source/game/entities/enemic.cpp source/game/entities/enemic.cpp
source/game/effects/debris_manager.cpp
) )
# Configuración de SDL3 # Configuración de SDL3

View File

@@ -50,7 +50,8 @@ APP_SOURCES := \
source/game/escenes/escena_joc.cpp \ source/game/escenes/escena_joc.cpp \
source/game/entities/nau.cpp \ source/game/entities/nau.cpp \
source/game/entities/bala.cpp \ source/game/entities/bala.cpp \
source/game/entities/enemic.cpp source/game/entities/enemic.cpp \
source/game/effects/debris_manager.cpp
# ============================================================================== # ==============================================================================
# INCLUDES # INCLUDES

View File

@@ -2,19 +2,27 @@
// © 2025 Port a C++20 amb SDL3 // © 2025 Port a C++20 amb SDL3
#include "sdl_manager.hpp" #include "sdl_manager.hpp"
#include "core/defaults.hpp"
#include "core/rendering/line_renderer.hpp"
#include "game/options.hpp"
#include "project.h"
#include <algorithm> #include <algorithm>
#include <format> #include <format>
#include <iostream> #include <iostream>
#include "core/defaults.hpp"
#include "core/rendering/line_renderer.hpp"
#include "game/options.hpp"
#include "project.h"
SDLManager::SDLManager() SDLManager::SDLManager()
: finestra_(nullptr), renderer_(nullptr), : finestra_(nullptr),
renderer_(nullptr),
fps_accumulator_(0.0f),
fps_frame_count_(0),
fps_display_(0),
current_width_(Defaults::Window::WIDTH), current_width_(Defaults::Window::WIDTH),
current_height_(Defaults::Window::HEIGHT), is_fullscreen_(false), current_height_(Defaults::Window::HEIGHT),
max_width_(1920), max_height_(1080) { is_fullscreen_(false),
max_width_(1920),
max_height_(1080) {
// Inicialitzar SDL3 // Inicialitzar SDL3
if (!SDL_Init(SDL_INIT_VIDEO)) { if (!SDL_Init(SDL_INIT_VIDEO)) {
std::cerr << "Error inicialitzant SDL3: " << SDL_GetError() << std::endl; std::cerr << "Error inicialitzant SDL3: " << SDL_GetError() << std::endl;
@@ -24,9 +32,8 @@ SDLManager::SDLManager()
// Calcular mida màxima des del display // Calcular mida màxima des del display
calculateMaxWindowSize(); calculateMaxWindowSize();
// Construir títol dinàmic igual que en pollo // Construir títol dinàmic
std::string window_title = std::format("{} v{} ({})", Project::LONG_NAME, std::string window_title = std::format("{} v{} ({})", Project::LONG_NAME, Project::VERSION, Project::COPYRIGHT);
Project::VERSION, Project::COPYRIGHT);
// Crear finestra CENTRADA (SDL ho fa automàticament amb CENTERED) // Crear finestra CENTRADA (SDL ho fa automàticament amb CENTERED)
finestra_ = finestra_ =
@@ -41,8 +48,7 @@ SDLManager::SDLManager()
} }
// IMPORTANT: Centrar explícitament la finestra // IMPORTANT: Centrar explícitament la finestra
SDL_SetWindowPosition(finestra_, SDL_WINDOWPOS_CENTERED, SDL_SetWindowPosition(finestra_, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED);
SDL_WINDOWPOS_CENTERED);
// Crear renderer amb acceleració // Crear renderer amb acceleració
renderer_ = SDL_CreateRenderer(finestra_, nullptr); renderer_ = SDL_CreateRenderer(finestra_, nullptr);
@@ -54,6 +60,9 @@ SDLManager::SDLManager()
return; return;
} }
// Aplicar configuració de V-Sync
SDL_SetRenderVSync(renderer_, Options::rendering.vsync);
// CRÍTIC: Configurar viewport scaling // CRÍTIC: Configurar viewport scaling
updateLogicalPresentation(); updateLogicalPresentation();
@@ -64,8 +73,15 @@ SDLManager::SDLManager()
// Constructor amb configuració // Constructor amb configuració
SDLManager::SDLManager(int width, int height, bool fullscreen) SDLManager::SDLManager(int width, int height, bool fullscreen)
: finestra_(nullptr), renderer_(nullptr), current_width_(width), : finestra_(nullptr),
current_height_(height), is_fullscreen_(fullscreen), max_width_(1920), renderer_(nullptr),
fps_accumulator_(0.0f),
fps_frame_count_(0),
fps_display_(0),
current_width_(width),
current_height_(height),
is_fullscreen_(fullscreen),
max_width_(1920),
max_height_(1080) { max_height_(1080) {
// Inicialitzar SDL3 // Inicialitzar SDL3
if (!SDL_Init(SDL_INIT_VIDEO)) { if (!SDL_Init(SDL_INIT_VIDEO)) {
@@ -77,8 +93,7 @@ SDLManager::SDLManager(int width, int height, bool fullscreen)
calculateMaxWindowSize(); calculateMaxWindowSize();
// Construir títol dinàmic // Construir títol dinàmic
std::string window_title = std::format("{} v{} ({})", Project::LONG_NAME, std::string window_title = std::format("{} v{} ({})", Project::LONG_NAME, Project::VERSION, Project::COPYRIGHT);
Project::VERSION, Project::COPYRIGHT);
// Configurar flags de la finestra // Configurar flags de la finestra
SDL_WindowFlags flags = SDL_WINDOW_RESIZABLE; SDL_WindowFlags flags = SDL_WINDOW_RESIZABLE;
@@ -87,8 +102,7 @@ SDLManager::SDLManager(int width, int height, bool fullscreen)
} }
// Crear finestra // Crear finestra
finestra_ = SDL_CreateWindow(window_title.c_str(), current_width_, finestra_ = SDL_CreateWindow(window_title.c_str(), current_width_, current_height_, flags);
current_height_, flags);
if (!finestra_) { if (!finestra_) {
std::cerr << "Error creant finestra: " << SDL_GetError() << std::endl; std::cerr << "Error creant finestra: " << SDL_GetError() << std::endl;
@@ -98,8 +112,7 @@ SDLManager::SDLManager(int width, int height, bool fullscreen)
// Centrar explícitament la finestra (si no és fullscreen) // Centrar explícitament la finestra (si no és fullscreen)
if (!is_fullscreen_) { if (!is_fullscreen_) {
SDL_SetWindowPosition(finestra_, SDL_WINDOWPOS_CENTERED, SDL_SetWindowPosition(finestra_, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED);
SDL_WINDOWPOS_CENTERED);
} }
// Crear renderer amb acceleració // Crear renderer amb acceleració
@@ -112,6 +125,9 @@ SDLManager::SDLManager(int width, int height, bool fullscreen)
return; return;
} }
// Aplicar configuració de V-Sync
SDL_SetRenderVSync(renderer_, Options::rendering.vsync);
// Configurar viewport scaling // Configurar viewport scaling
updateLogicalPresentation(); updateLogicalPresentation();
@@ -141,7 +157,7 @@ SDLManager::~SDLManager() {
void SDLManager::calculateMaxWindowSize() { void SDLManager::calculateMaxWindowSize() {
SDL_DisplayID display = SDL_GetPrimaryDisplay(); SDL_DisplayID display = SDL_GetPrimaryDisplay();
const SDL_DisplayMode *mode = SDL_GetCurrentDisplayMode(display); const SDL_DisplayMode* mode = SDL_GetCurrentDisplayMode(display);
if (mode) { if (mode) {
// Deixar marge de 100px per a decoracions de l'OS // Deixar marge de 100px per a decoracions de l'OS
@@ -262,7 +278,7 @@ void SDLManager::toggleFullscreen() {
// En sortir, restaura la mida anterior // En sortir, restaura la mida anterior
} }
bool SDLManager::handleWindowEvent(const SDL_Event &event) { bool SDLManager::handleWindowEvent(const SDL_Event& event) {
if (event.type == SDL_EVENT_WINDOW_RESIZED) { if (event.type == SDL_EVENT_WINDOW_RESIZED) {
// Usuari ha redimensionat manualment (arrossegar vora) // Usuari ha redimensionat manualment (arrossegar vora)
// Actualitzar el nostre tracking // Actualitzar el nostre tracking
@@ -301,3 +317,49 @@ void SDLManager::updateColors(float delta_time) {
// Actualitzar color global de línies // Actualitzar color global de línies
Rendering::setLineColor(color_oscillator_.getCurrentLineColor()); Rendering::setLineColor(color_oscillator_.getCurrentLineColor());
} }
// [NUEVO] Actualitzar comptador de FPS
void SDLManager::updateFPS(float delta_time) {
// Acumular temps i frames
fps_accumulator_ += delta_time;
fps_frame_count_++;
// Actualitzar display cada 0.5 segons
if (fps_accumulator_ >= 0.5f) {
fps_display_ = static_cast<int>(fps_frame_count_ / fps_accumulator_);
fps_frame_count_ = 0;
fps_accumulator_ = 0.0f;
// Actualitzar títol de la finestra
std::string title = std::format("{} v{} ({}) - {} FPS",
Project::LONG_NAME,
Project::VERSION,
Project::COPYRIGHT,
fps_display_);
if (finestra_) {
SDL_SetWindowTitle(finestra_, title.c_str());
}
}
}
// [NUEVO] Actualitzar títol de la finestra
void SDLManager::setWindowTitle(const std::string& title) {
if (finestra_) {
SDL_SetWindowTitle(finestra_, title.c_str());
}
}
// [NUEVO] Toggle V-Sync (F4)
void SDLManager::toggleVSync() {
// Toggle: 1 → 0 → 1
Options::rendering.vsync = (Options::rendering.vsync == 1) ? 0 : 1;
// Aplicar a SDL
if (renderer_) {
SDL_SetRenderVSync(renderer_, Options::rendering.vsync);
}
// Guardar configuració
Options::saveToFile();
}

View File

@@ -5,26 +5,30 @@
#define SDL_MANAGER_HPP #define SDL_MANAGER_HPP
#include <SDL3/SDL.h> #include <SDL3/SDL.h>
#include <cstdint> #include <cstdint>
#include <string>
#include "core/rendering/color_oscillator.hpp" #include "core/rendering/color_oscillator.hpp"
class SDLManager { class SDLManager {
public: public:
SDLManager(); // Constructor per defecte (usa Defaults::) SDLManager(); // Constructor per defecte (usa Defaults::)
SDLManager(int width, int height, SDLManager(int width, int height,
bool fullscreen); // Constructor amb configuració bool fullscreen); // Constructor amb configuració
~SDLManager(); ~SDLManager();
// No permetre còpia ni assignació // No permetre còpia ni assignació
SDLManager(const SDLManager &) = delete; SDLManager(const SDLManager&) = delete;
SDLManager &operator=(const SDLManager &) = delete; SDLManager& operator=(const SDLManager&) = delete;
// [NUEVO] Gestió de finestra dinàmica // [NUEVO] Gestió de finestra dinàmica
void increaseWindowSize(); // F2: +100px void increaseWindowSize(); // F2: +100px
void decreaseWindowSize(); // F1: -100px void decreaseWindowSize(); // F1: -100px
void toggleFullscreen(); // F3 void toggleFullscreen(); // F3
void toggleVSync(); // F4
bool bool
handleWindowEvent(const SDL_Event &event); // Per a SDL_EVENT_WINDOW_RESIZED handleWindowEvent(const SDL_Event& event); // Per a SDL_EVENT_WINDOW_RESIZED
// Funcions principals (renderitzat) // Funcions principals (renderitzat)
void neteja(uint8_t r = 0, uint8_t g = 0, uint8_t b = 0); void neteja(uint8_t r = 0, uint8_t g = 0, uint8_t b = 0);
@@ -33,12 +37,23 @@ public:
// [NUEVO] Actualització de colors (oscil·lació) // [NUEVO] Actualització de colors (oscil·lació)
void updateColors(float delta_time); void updateColors(float delta_time);
// Getters // [NUEVO] Actualitzar comptador de FPS
SDL_Renderer *obte_renderer() { return renderer_; } void updateFPS(float delta_time);
private: // Getters
SDL_Window *finestra_; SDL_Renderer* obte_renderer() { return renderer_; }
SDL_Renderer *renderer_;
// [NUEVO] Actualitzar títol de la finestra
void setWindowTitle(const std::string& title);
private:
SDL_Window* finestra_;
SDL_Renderer* renderer_;
// [NUEVO] Variables FPS
float fps_accumulator_;
int fps_frame_count_;
int fps_display_;
// [NUEVO] Estat de la finestra // [NUEVO] Estat de la finestra
int current_width_; // Mida física actual int current_width_; // Mida física actual

2
source/external/.clang-format vendored Normal file
View File

@@ -0,0 +1,2 @@
DisableFormat: true
SortIncludes: Never

View File

@@ -7,10 +7,12 @@
namespace Constants { namespace Constants {
// Marges de l'àrea de joc (derivats de Defaults::Zones::GAME) // Marges de l'àrea de joc (derivats de Defaults::Zones::GAME)
constexpr int MARGE_ESQ = static_cast<int>(Defaults::Zones::GAME.x); constexpr int MARGE_ESQ = static_cast<int>(Defaults::Zones::PLAYAREA.x);
constexpr int MARGE_DRET = static_cast<int>(Defaults::Zones::GAME.x + Defaults::Zones::GAME.w); constexpr int MARGE_DRET =
constexpr int MARGE_DALT = static_cast<int>(Defaults::Zones::GAME.y); static_cast<int>(Defaults::Zones::PLAYAREA.x + Defaults::Zones::PLAYAREA.w);
constexpr int MARGE_BAIX = static_cast<int>(Defaults::Zones::GAME.y + Defaults::Zones::GAME.h); constexpr int MARGE_DALT = static_cast<int>(Defaults::Zones::PLAYAREA.y);
constexpr int MARGE_BAIX =
static_cast<int>(Defaults::Zones::PLAYAREA.y + Defaults::Zones::PLAYAREA.h);
// Límits de polígons i objectes // Límits de polígons i objectes
constexpr int MAX_IPUNTS = Defaults::Entities::MAX_IPUNTS; constexpr int MAX_IPUNTS = Defaults::Entities::MAX_IPUNTS;
@@ -27,14 +29,33 @@ constexpr float PI = Defaults::Math::PI;
// Helpers per comprovar límits de zona // Helpers per comprovar límits de zona
inline bool dins_zona_joc(float x, float y) { inline bool dins_zona_joc(float x, float y) {
const SDL_FPoint punt = {x, y}; const SDL_FPoint punt = {x, y};
return SDL_PointInRectFloat(&punt, &Defaults::Zones::GAME); return SDL_PointInRectFloat(&punt, &Defaults::Zones::PLAYAREA);
} }
inline void obtenir_limits_zona(float& min_x, float& max_x, float& min_y, float& max_y) { inline void obtenir_limits_zona(float& min_x, float& max_x, float& min_y, float& max_y) {
const auto& zona = Defaults::Zones::GAME; const auto& zona = Defaults::Zones::PLAYAREA;
min_x = zona.x; min_x = zona.x;
max_x = zona.x + zona.w; max_x = zona.x + zona.w;
min_y = zona.y; min_y = zona.y;
max_y = zona.y + zona.h; max_y = zona.y + zona.h;
} }
// Obtenir límits segurs (compensant radi de l'entitat)
inline void obtenir_limits_zona_segurs(float radi, float& min_x, float& max_x,
float& min_y, float& max_y) {
const auto& zona = Defaults::Zones::PLAYAREA;
constexpr float MARGE_SEGURETAT = 10.0f; // Safety margin
min_x = zona.x + radi + MARGE_SEGURETAT;
max_x = zona.x + zona.w - radi - MARGE_SEGURETAT;
min_y = zona.y + radi + MARGE_SEGURETAT;
max_y = zona.y + zona.h - radi - MARGE_SEGURETAT;
}
// Obtenir centre de l'àrea de joc
inline void obtenir_centre_zona(float& centre_x, float& centre_y) {
const auto& zona = Defaults::Zones::PLAYAREA;
centre_x = zona.x + zona.w / 2.0f;
centre_y = zona.y + zona.h / 2.0f;
}
} // namespace Constants } // namespace Constants

View File

@@ -0,0 +1,33 @@
// debris.hpp - Fragment de línia volant (explosió de formes)
// © 2025 Port a C++20 amb SDL3
#pragma once
#include "core/types.hpp"
namespace Effects {
// Debris: un segment de línia que vola perpendicular a sí mateix
// Representa un fragment d'una forma destruïda (nau, enemic, bala)
struct Debris {
// Geometria del segment (2 punts en coordenades mundials)
Punt p1; // Punt inicial del segment
Punt p2; // Punt final del segment
// Física
Punt velocitat; // Velocitat en px/s (components x, y)
float acceleracio; // Acceleració negativa (fricció) en px/s²
// Rotació
float angle_rotacio; // Angle de rotació acumulat (radians)
float velocitat_rot; // Velocitat de rotació en rad/s
// Estat de vida
float temps_vida; // Temps transcorregut (segons)
float temps_max; // Temps de vida màxim (segons)
bool actiu; // Està actiu?
// Shrinking (reducció de distància entre punts)
float factor_shrink; // Factor de reducció per segon (0.0-1.0)
};
} // namespace Effects

View File

@@ -0,0 +1,276 @@
// debris_manager.cpp - Implementació del gestor de fragments
// © 2025 Port a C++20 amb SDL3
#include "debris_manager.hpp"
#include <cmath>
#include <cstdlib>
#include <iostream>
#include "core/defaults.hpp"
#include "core/rendering/line_renderer.hpp"
namespace Effects {
// Helper: transformar punt amb rotació, escala i trasllació
// (Copiat de shape_renderer.cpp:12-34)
static Punt transform_point(const Punt& point, const Punt& shape_centre, const Punt& posicio, float angle, float escala) {
// 1. Centrar el punt respecte al centre de la forma
float centered_x = point.x - shape_centre.x;
float centered_y = point.y - shape_centre.y;
// 2. Aplicar escala al punt centrat
float scaled_x = centered_x * escala;
float scaled_y = centered_y * escala;
// 3. Aplicar rotació
float cos_a = std::cos(angle);
float sin_a = std::sin(angle);
float rotated_x = scaled_x * cos_a - scaled_y * sin_a;
float rotated_y = scaled_x * sin_a + scaled_y * cos_a;
// 4. Aplicar trasllació a posició mundial
return {rotated_x + posicio.x, rotated_y + posicio.y};
}
DebrisManager::DebrisManager(SDL_Renderer* renderer)
: renderer_(renderer) {
// Inicialitzar tots els debris com inactius
for (auto& debris : debris_pool_) {
debris.actiu = false;
}
}
void DebrisManager::explotar(const std::shared_ptr<Graphics::Shape>& shape,
const Punt& centre,
float angle,
float escala,
float velocitat_base) {
if (!shape || !shape->es_valida()) {
return;
}
// Obtenir centre de la forma per a transformacions
const Punt& shape_centre = shape->get_centre();
// Iterar sobre totes les primitives de la forma
for (const auto& primitive : shape->get_primitives()) {
// Processar cada segment de línia
std::vector<std::pair<Punt, Punt>> segments;
if (primitive.type == Graphics::PrimitiveType::POLYLINE) {
// Polyline: extreure segments consecutius
for (size_t i = 0; i < primitive.points.size() - 1; i++) {
segments.push_back({primitive.points[i], primitive.points[i + 1]});
}
} else { // PrimitiveType::LINE
// Line: un únic segment
if (primitive.points.size() >= 2) {
segments.push_back({primitive.points[0], primitive.points[1]});
}
}
// Crear debris per a cada segment
for (const auto& [local_p1, local_p2] : segments) {
// 1. Transformar punts locals → coordenades mundials
Punt world_p1 =
transform_point(local_p1, shape_centre, centre, angle, escala);
Punt world_p2 =
transform_point(local_p2, shape_centre, centre, angle, escala);
// 2. Trobar slot lliure
Debris* debris = trobar_slot_lliure();
if (!debris) {
std::cerr << "[DebrisManager] Warning: no debris slots disponibles\n";
return; // Pool ple
}
// 3. Inicialitzar geometria
debris->p1 = world_p1;
debris->p2 = world_p2;
// 4. Calcular direcció perpendicular
Punt direccio = calcular_direccio_perpendicular(world_p1, world_p2);
// 5. Velocitat inicial (base ± variació aleatòria)
float speed =
velocitat_base +
((std::rand() / static_cast<float>(RAND_MAX)) * 2.0f - 1.0f) *
Defaults::Physics::Debris::VARIACIO_VELOCITAT;
debris->velocitat.x = direccio.x * speed;
debris->velocitat.y = direccio.y * speed;
debris->acceleracio = Defaults::Physics::Debris::ACCELERACIO;
// 6. Rotació lenta aleatòria
debris->velocitat_rot =
Defaults::Physics::Debris::ROTACIO_MIN +
(std::rand() / static_cast<float>(RAND_MAX)) *
(Defaults::Physics::Debris::ROTACIO_MAX -
Defaults::Physics::Debris::ROTACIO_MIN);
// 50% probabilitat de rotació en sentit contrari
if (std::rand() % 2 == 0) {
debris->velocitat_rot = -debris->velocitat_rot;
}
debris->angle_rotacio = 0.0f;
// 7. Configurar vida i shrinking
debris->temps_vida = 0.0f;
debris->temps_max = Defaults::Physics::Debris::TEMPS_VIDA;
debris->factor_shrink = Defaults::Physics::Debris::SHRINK_RATE;
// 8. Activar
debris->actiu = true;
}
}
}
void DebrisManager::actualitzar(float delta_time) {
for (auto& debris : debris_pool_) {
if (!debris.actiu)
continue;
// 1. Actualitzar temps de vida
debris.temps_vida += delta_time;
// Desactivar si ha superat temps màxim
if (debris.temps_vida >= debris.temps_max) {
debris.actiu = false;
continue;
}
// 2. Actualitzar velocitat (desacceleració)
// Aplicar fricció en la direcció del moviment
float speed = std::sqrt(debris.velocitat.x * debris.velocitat.x +
debris.velocitat.y * debris.velocitat.y);
if (speed > 1.0f) {
// Calcular direcció normalitzada
float dir_x = debris.velocitat.x / speed;
float dir_y = debris.velocitat.y / speed;
// Aplicar acceleració negativa (fricció)
float nova_speed = speed + debris.acceleracio * delta_time;
if (nova_speed < 0.0f)
nova_speed = 0.0f;
debris.velocitat.x = dir_x * nova_speed;
debris.velocitat.y = dir_y * nova_speed;
} else {
// Velocitat molt baixa, aturar
debris.velocitat.x = 0.0f;
debris.velocitat.y = 0.0f;
}
// 3. Calcular centre del segment
Punt centre = {(debris.p1.x + debris.p2.x) / 2.0f,
(debris.p1.y + debris.p2.y) / 2.0f};
// 4. Actualitzar posició del centre
centre.x += debris.velocitat.x * delta_time;
centre.y += debris.velocitat.y * delta_time;
// 5. Actualitzar rotació
debris.angle_rotacio += debris.velocitat_rot * delta_time;
// 6. Aplicar shrinking (reducció de distància entre punts)
float shrink_factor =
1.0f - (debris.factor_shrink * debris.temps_vida / debris.temps_max);
shrink_factor = std::max(0.0f, shrink_factor); // No negatiu
// Calcular distància original entre punts
float dx = debris.p2.x - debris.p1.x;
float dy = debris.p2.y - debris.p1.y;
// 7. Reconstruir segment amb nova mida i rotació
float half_length = std::sqrt(dx * dx + dy * dy) * shrink_factor / 2.0f;
float original_angle = std::atan2(dy, dx);
float new_angle = original_angle + debris.angle_rotacio;
debris.p1.x = centre.x - half_length * std::cos(new_angle);
debris.p1.y = centre.y - half_length * std::sin(new_angle);
debris.p2.x = centre.x + half_length * std::cos(new_angle);
debris.p2.y = centre.y + half_length * std::sin(new_angle);
}
}
void DebrisManager::dibuixar() const {
for (const auto& debris : debris_pool_) {
if (!debris.actiu)
continue;
// Dibuixar segment de línia
Rendering::linea(renderer_, static_cast<int>(debris.p1.x), static_cast<int>(debris.p1.y), static_cast<int>(debris.p2.x), static_cast<int>(debris.p2.y), true);
}
}
Debris* DebrisManager::trobar_slot_lliure() {
for (auto& debris : debris_pool_) {
if (!debris.actiu) {
return &debris;
}
}
return nullptr; // Pool ple
}
Punt DebrisManager::calcular_direccio_perpendicular(const Punt& p1,
const Punt& p2) const {
// 1. Calcular vector de la línia (p1 → p2)
float dx = p2.x - p1.x;
float dy = p2.y - p1.y;
// 2. Normalitzar (obtenir vector unitari)
float length = std::sqrt(dx * dx + dy * dy);
if (length < 0.001f) {
// Línia degenerada, retornar direcció aleatòria
float angle_rand =
(std::rand() / static_cast<float>(RAND_MAX)) * 2.0f * Defaults::Math::PI;
return {std::cos(angle_rand), std::sin(angle_rand)};
}
dx /= length;
dy /= length;
// 3. Rotar 90° (perpendicular)
// Rotació 90° sentit antihorari: (x,y) → (-y, x)
float perp_x = -dy;
float perp_y = dx;
// 4. Afegir variació aleatòria petita (±15°)
float angle_variacio =
((std::rand() % 30) - 15) * Defaults::Math::PI / 180.0f;
float cos_v = std::cos(angle_variacio);
float sin_v = std::sin(angle_variacio);
float final_x = perp_x * cos_v - perp_y * sin_v;
float final_y = perp_x * sin_v + perp_y * cos_v;
// 5. Afegir ± direcció aleatòria (50% probabilitat d'invertir)
if (std::rand() % 2 == 0) {
final_x = -final_x;
final_y = -final_y;
}
return {final_x, final_y};
}
void DebrisManager::reiniciar() {
for (auto& debris : debris_pool_) {
debris.actiu = false;
}
}
int DebrisManager::get_num_actius() const {
int count = 0;
for (const auto& debris : debris_pool_) {
if (debris.actiu)
count++;
}
return count;
}
} // namespace Effects

View File

@@ -0,0 +1,63 @@
// debris_manager.hpp - Gestor de fragments d'explosions
// © 2025 Port a C++20 amb SDL3
#pragma once
#include <SDL3/SDL.h>
#include <array>
#include <memory>
#include "core/graphics/shape.hpp"
#include "core/types.hpp"
#include "debris.hpp"
namespace Effects {
// Gestor de fragments d'explosions
// Manté un pool d'objectes Debris i gestiona el seu cicle de vida
class DebrisManager {
public:
explicit DebrisManager(SDL_Renderer* renderer);
// Crear explosió a partir d'una forma
// - shape: forma vectorial a explotar
// - centre: posició del centre de l'objecte
// - angle: orientació de l'objecte (radians)
// - escala: escala de l'objecte (1.0 = normal)
// - velocitat_base: velocitat inicial dels fragments (px/s)
void explotar(const std::shared_ptr<Graphics::Shape>& shape,
const Punt& centre,
float angle,
float escala,
float velocitat_base);
// Actualitzar tots els fragments actius
void actualitzar(float delta_time);
// Dibuixar tots els fragments actius
void dibuixar() const;
// Reiniciar tots els fragments (neteja)
void reiniciar();
// Obtenir número de fragments actius
int get_num_actius() const;
private:
SDL_Renderer* renderer_;
// Pool de fragments (màxim concurrent)
// Un pentàgon té 5 línies, 15 enemics = 75 línies
// + nau (3 línies) + bales (5 línies * 3) = 93 línies màxim
// Arrodonit a 100 per seguretat
static constexpr int MAX_DEBRIS = 100;
std::array<Debris, MAX_DEBRIS> debris_pool_;
// Trobar primer slot inactiu
Debris* trobar_slot_lliure();
// Calcular direcció perpendicular a un segment
Punt calcular_direccio_perpendicular(const Punt& p1, const Punt& p2) const;
};
} // namespace Effects

View File

@@ -3,16 +3,20 @@
// © 2025 Port a C++20 amb SDL3 // © 2025 Port a C++20 amb SDL3
#include "game/entities/bala.hpp" #include "game/entities/bala.hpp"
#include "core/graphics/shape_loader.hpp"
#include "core/rendering/shape_renderer.hpp"
#include "game/constants.hpp"
#include <cmath> #include <cmath>
#include <iostream> #include <iostream>
Bala::Bala(SDL_Renderer *renderer) #include "core/graphics/shape_loader.hpp"
: renderer_(renderer), centre_({0.0f, 0.0f}), angle_(0.0f), #include "core/rendering/shape_renderer.hpp"
velocitat_(0.0f), esta_(false) { #include "game/constants.hpp"
Bala::Bala(SDL_Renderer* renderer)
: renderer_(renderer),
centre_({0.0f, 0.0f}),
angle_(0.0f),
velocitat_(0.0f),
esta_(false) {
// [NUEVO] Carregar forma compartida des de fitxer // [NUEVO] Carregar forma compartida des de fitxer
forma_ = Graphics::ShapeLoader::load("bullet.shp"); forma_ = Graphics::ShapeLoader::load("bullet.shp");
@@ -29,7 +33,7 @@ void Bala::inicialitzar() {
velocitat_ = 0.0f; velocitat_ = 0.0f;
} }
void Bala::disparar(const Punt &posicio, float angle) { void Bala::disparar(const Punt& posicio, float angle) {
// Activar bala i posicionar-la a la nau // Activar bala i posicionar-la a la nau
// Basat en joc_asteroides.cpp línies 188-200 // Basat en joc_asteroides.cpp línies 188-200
@@ -80,7 +84,13 @@ void Bala::mou(float delta_time) {
centre_.x += dx; centre_.x += dx;
// Desactivar si surt de la zona de joc (no rebota com els ORNIs) // Desactivar si surt de la zona de joc (no rebota com els ORNIs)
if (!Constants::dins_zona_joc(centre_.x, centre_.y)) { // CORRECCIÓ: Usar límits segurs amb radi de la bala
float min_x, max_x, min_y, max_y;
Constants::obtenir_limits_zona_segurs(Defaults::Entities::BULLET_RADIUS,
min_x, max_x, min_y, max_y);
if (centre_.x < min_x || centre_.x > max_x ||
centre_.y < min_y || centre_.y > max_y) {
esta_ = false; esta_ = false;
} }
} }

View File

@@ -3,28 +3,31 @@
// © 2025 Port a C++20 amb SDL3 // © 2025 Port a C++20 amb SDL3
#pragma once #pragma once
#include "core/graphics/shape.hpp"
#include "core/types.hpp"
#include <SDL3/SDL.h> #include <SDL3/SDL.h>
#include <memory> #include <memory>
#include "core/graphics/shape.hpp"
#include "core/types.hpp"
class Bala { class Bala {
public: public:
Bala() : renderer_(nullptr) {} Bala()
Bala(SDL_Renderer *renderer); : renderer_(nullptr) {}
Bala(SDL_Renderer* renderer);
void inicialitzar(); void inicialitzar();
void disparar(const Punt &posicio, float angle); void disparar(const Punt& posicio, float angle);
void actualitzar(float delta_time); void actualitzar(float delta_time);
void dibuixar() const; void dibuixar() const;
// Getters (API pública sense canvis) // Getters (API pública sense canvis)
bool esta_activa() const { return esta_; } bool esta_activa() const { return esta_; }
const Punt &get_centre() const { return centre_; } const Punt& get_centre() const { return centre_; }
void desactivar() { esta_ = false; } void desactivar() { esta_ = false; }
private: private:
SDL_Renderer *renderer_; SDL_Renderer* renderer_;
// [NUEVO] Forma vectorial (compartida entre totes les bales) // [NUEVO] Forma vectorial (compartida entre totes les bales)
std::shared_ptr<Graphics::Shape> forma_; std::shared_ptr<Graphics::Shape> forma_;

View File

@@ -3,17 +3,23 @@
// © 2025 Port a C++20 amb SDL3 // © 2025 Port a C++20 amb SDL3
#include "game/entities/enemic.hpp" #include "game/entities/enemic.hpp"
#include "core/graphics/shape_loader.hpp"
#include "core/rendering/shape_renderer.hpp"
#include "game/constants.hpp"
#include <cmath> #include <cmath>
#include <cstdlib> #include <cstdlib>
#include <iostream> #include <iostream>
Enemic::Enemic(SDL_Renderer *renderer) #include "core/graphics/shape_loader.hpp"
: renderer_(renderer), centre_({0.0f, 0.0f}), angle_(0.0f), #include "core/rendering/shape_renderer.hpp"
velocitat_(0.0f), drotacio_(0.0f), rotacio_(0.0f), esta_(false) { #include "game/constants.hpp"
Enemic::Enemic(SDL_Renderer* renderer)
: renderer_(renderer),
centre_({0.0f, 0.0f}),
angle_(0.0f),
velocitat_(0.0f),
drotacio_(0.0f),
rotacio_(0.0f),
esta_(false) {
// [NUEVO] Carregar forma compartida des de fitxer // [NUEVO] Carregar forma compartida des de fitxer
forma_ = Graphics::ShapeLoader::load("enemy_pentagon.shp"); forma_ = Graphics::ShapeLoader::load("enemy_pentagon.shp");
@@ -27,12 +33,20 @@ void Enemic::inicialitzar() {
// Inicialitzar enemic (pentàgon) // Inicialitzar enemic (pentàgon)
// Copiat de joc_asteroides.cpp línies 41-54 // Copiat de joc_asteroides.cpp línies 41-54
// [NUEVO] Ja no cal crear_poligon_regular - la geometria es carrega del fitxer // [NUEVO] Ja no cal crear_poligon_regular - la geometria es carrega del
// Només inicialitzem l'estat de la instància // fitxer Només inicialitzem l'estat de la instància
// Posició aleatòria dins de l'àrea de joc // Posició aleatòria dins de l'àrea de joc
centre_.x = static_cast<float>((std::rand() % 580) + 30); // 30-610 // Calcular rangs segurs amb radi de l'enemic
centre_.y = static_cast<float>((std::rand() % 420) + 30); // 30-450 float min_x, max_x, min_y, max_y;
Constants::obtenir_limits_zona_segurs(Defaults::Entities::ENEMY_RADIUS,
min_x, max_x, min_y, max_y);
// Spawn aleatori dins dels límits segurs
int range_x = static_cast<int>(max_x - min_x);
int range_y = static_cast<int>(max_y - min_y);
centre_.x = static_cast<float>((std::rand() % range_x) + static_cast<int>(min_x));
centre_.y = static_cast<float>((std::rand() % range_y) + static_cast<int>(min_y));
// Angle aleatori de moviment // Angle aleatori de moviment
angle_ = (std::rand() % 360) * Constants::PI / 180.0f; angle_ = (std::rand() % 360) * Constants::PI / 180.0f;
@@ -85,14 +99,16 @@ void Enemic::mou(float delta_time) {
float new_y = centre_.y + dy; float new_y = centre_.y + dy;
float new_x = centre_.x + dx; float new_x = centre_.x + dx;
// Obtenir límits de la zona de joc // Obtenir límits segurs compensant el radi de l'enemic
float min_x, max_x, min_y, max_y; float min_x, max_x, min_y, max_y;
Constants::obtenir_limits_zona(min_x, max_x, min_y, max_y); Constants::obtenir_limits_zona_segurs(Defaults::Entities::ENEMY_RADIUS,
min_x, max_x, min_y, max_y);
// Lògica Pascal: Actualitza Y si dins, sinó ajusta angle aleatòriament // Lògica Pascal: Actualitza Y si dins, sinó ajusta angle aleatòriament
// if (dy>marge_dalt) and (dy<marge_baix) then orni.centre.y:=round(Dy) // if (dy>marge_dalt) and (dy<marge_baix) then orni.centre.y:=round(Dy)
// else orni.angle:=orni.angle+(random(256)/512)*(random(3)-1); // else orni.angle:=orni.angle+(random(256)/512)*(random(3)-1);
if (new_y > min_y && new_y < max_y) { // CORRECCIÓ: Usar inequalitats inclusives (>= i <=) per evitar fugides
if (new_y >= min_y && new_y <= max_y) {
centre_.y = new_y; centre_.y = new_y;
} else { } else {
// Pequeño ajuste aleatorio: (random(256)/512)*(random(3)-1) // Pequeño ajuste aleatorio: (random(256)/512)*(random(3)-1)
@@ -107,7 +123,8 @@ void Enemic::mou(float delta_time) {
// Lògica Pascal: Actualitza X si dins, sinó ajusta angle aleatòriament // Lògica Pascal: Actualitza X si dins, sinó ajusta angle aleatòriament
// if (dx>marge_esq) and (dx<marge_dret) then orni.centre.x:=round(Dx) // if (dx>marge_esq) and (dx<marge_dret) then orni.centre.x:=round(Dx)
// else orni.angle:=orni.angle+(random(256)/512)*(random(3)-1); // else orni.angle:=orni.angle+(random(256)/512)*(random(3)-1);
if (new_x > min_x && new_x < max_x) { // CORRECCIÓ: Usar inequalitats inclusives (>= i <=) per evitar fugides
if (new_x >= min_x && new_x <= max_x) {
centre_.x = new_x; centre_.x = new_x;
} else { } else {
float rand1 = (static_cast<float>(std::rand() % 256) / 512.0f); float rand1 = (static_cast<float>(std::rand() % 256) / 512.0f);

View File

@@ -3,15 +3,18 @@
// © 2025 Port a C++20 amb SDL3 // © 2025 Port a C++20 amb SDL3
#pragma once #pragma once
#include "core/graphics/shape.hpp"
#include "core/types.hpp"
#include <SDL3/SDL.h> #include <SDL3/SDL.h>
#include <memory> #include <memory>
#include "core/graphics/shape.hpp"
#include "core/types.hpp"
class Enemic { class Enemic {
public: public:
Enemic() : renderer_(nullptr) {} Enemic()
Enemic(SDL_Renderer *renderer); : renderer_(nullptr) {}
Enemic(SDL_Renderer* renderer);
void inicialitzar(); void inicialitzar();
void actualitzar(float delta_time); void actualitzar(float delta_time);
@@ -19,11 +22,12 @@ public:
// Getters (API pública sense canvis) // Getters (API pública sense canvis)
bool esta_actiu() const { return esta_; } bool esta_actiu() const { return esta_; }
const Punt &get_centre() const { return centre_; } const Punt& get_centre() const { return centre_; }
const std::shared_ptr<Graphics::Shape>& get_forma() const { return forma_; }
void destruir() { esta_ = false; } void destruir() { esta_ = false; }
private: private:
SDL_Renderer *renderer_; SDL_Renderer* renderer_;
// [NUEVO] Forma vectorial (compartida entre tots els enemics) // [NUEVO] Forma vectorial (compartida entre tots els enemics)
std::shared_ptr<Graphics::Shape> forma_; std::shared_ptr<Graphics::Shape> forma_;

View File

@@ -3,18 +3,23 @@
// © 2025 Port a C++20 amb SDL3 // © 2025 Port a C++20 amb SDL3
#include "game/entities/nau.hpp" #include "game/entities/nau.hpp"
#include <SDL3/SDL.h>
#include <cmath>
#include <iostream>
#include "core/defaults.hpp" #include "core/defaults.hpp"
#include "core/graphics/shape_loader.hpp" #include "core/graphics/shape_loader.hpp"
#include "core/rendering/shape_renderer.hpp" #include "core/rendering/shape_renderer.hpp"
#include "game/constants.hpp" #include "game/constants.hpp"
#include <SDL3/SDL.h>
#include <cmath>
#include <iostream>
Nau::Nau(SDL_Renderer *renderer)
: renderer_(renderer), centre_({0.0f, 0.0f}), angle_(0.0f),
velocitat_(0.0f), esta_tocada_(false) {
Nau::Nau(SDL_Renderer* renderer)
: renderer_(renderer),
centre_({0.0f, 0.0f}),
angle_(0.0f),
velocitat_(0.0f),
esta_tocada_(false) {
// [NUEVO] Carregar forma compartida des de fitxer // [NUEVO] Carregar forma compartida des de fitxer
forma_ = Graphics::ShapeLoader::load("ship.shp"); forma_ = Graphics::ShapeLoader::load("ship.shp");
@@ -28,12 +33,14 @@ void Nau::inicialitzar() {
// Basat en el codi Pascal original: lines 380-384 // Basat en el codi Pascal original: lines 380-384
// Copiat de joc_asteroides.cpp línies 30-44 // Copiat de joc_asteroides.cpp línies 30-44
// [NUEVO] Ja no cal configurar punts polars - la geometria es carrega del fitxer // [NUEVO] Ja no cal configurar punts polars - la geometria es carrega del
// Només inicialitzem l'estat de la instància // fitxer Només inicialitzem l'estat de la instància
// Posició inicial al centre de la pantalla // Posició inicial al centre de l'àrea de joc
centre_.x = 320.0f; float centre_x, centre_y;
centre_.y = 240.0f; Constants::obtenir_centre_zona(centre_x, centre_y);
centre_.x = centre_x; // 320
centre_.y = centre_y; // 213 (not 240!)
// Estat inicial // Estat inicial
angle_ = 0.0f; angle_ = 0.0f;
@@ -49,7 +56,7 @@ void Nau::processar_input(float delta_time) {
return; return;
// Obtenir estat actual del teclat (no events, sinó estat continu) // Obtenir estat actual del teclat (no events, sinó estat continu)
const bool *keyboard_state = SDL_GetKeyboardState(nullptr); const bool* keyboard_state = SDL_GetKeyboardState(nullptr);
// Rotació // Rotació
if (keyboard_state[SDL_SCANCODE_RIGHT]) { if (keyboard_state[SDL_SCANCODE_RIGHT]) {
@@ -116,16 +123,18 @@ void Nau::aplicar_fisica(float delta_time) {
(velocitat_ * delta_time) * std::cos(angle_ - Constants::PI / 2.0f) + (velocitat_ * delta_time) * std::cos(angle_ - Constants::PI / 2.0f) +
centre_.x; centre_.x;
// Boundary checking - només actualitzar si dins de la zona de joc // Boundary checking amb radi de la nau
// Acumulació directa amb precisió subpíxel // CORRECCIÓ: Usar límits segurs i inequalitats inclusives
float min_x, max_x, min_y, max_y; float min_x, max_x, min_y, max_y;
Constants::obtenir_limits_zona(min_x, max_x, min_y, max_y); Constants::obtenir_limits_zona_segurs(Defaults::Entities::SHIP_RADIUS,
min_x, max_x, min_y, max_y);
if (dy > min_y && dy < max_y) { // Inequalitats inclusives (>= i <=)
if (dy >= min_y && dy <= max_y) {
centre_.y = dy; centre_.y = dy;
} }
if (dx > min_x && dx < max_x) { if (dx >= min_x && dx <= max_x) {
centre_.x = dx; centre_.x = dx;
} }

View File

@@ -3,15 +3,18 @@
// © 2025 Port a C++20 amb SDL3 // © 2025 Port a C++20 amb SDL3
#pragma once #pragma once
#include "core/graphics/shape.hpp"
#include "core/types.hpp"
#include <SDL3/SDL.h> #include <SDL3/SDL.h>
#include <memory> #include <memory>
#include "core/graphics/shape.hpp"
#include "core/types.hpp"
class Nau { class Nau {
public: public:
Nau() : renderer_(nullptr) {} Nau()
Nau(SDL_Renderer *renderer); : renderer_(nullptr) {}
Nau(SDL_Renderer* renderer);
void inicialitzar(); void inicialitzar();
void processar_input(float delta_time); void processar_input(float delta_time);
@@ -19,17 +22,18 @@ public:
void dibuixar() const; void dibuixar() const;
// Getters (API pública sense canvis) // Getters (API pública sense canvis)
const Punt &get_centre() const { return centre_; } const Punt& get_centre() const { return centre_; }
float get_angle() const { return angle_; } float get_angle() const { return angle_; }
bool esta_viva() const { return !esta_tocada_; } bool esta_viva() const { return !esta_tocada_; }
// Col·lisions (Fase 10) // Col·lisions (Fase 10)
void marcar_tocada() { esta_tocada_ = true; } void marcar_tocada() { esta_tocada_ = true; }
private: private:
SDL_Renderer *renderer_; SDL_Renderer* renderer_;
// [NUEVO] Forma vectorial (compartida, només 1 instància de Nau però preparat per reutilització) // [NUEVO] Forma vectorial (compartida, només 1 instància de Nau però preparat
// per reutilització)
std::shared_ptr<Graphics::Shape> forma_; std::shared_ptr<Graphics::Shape> forma_;
// [NUEVO] Estat de la instància (separat de la geometria) // [NUEVO] Estat de la instància (separat de la geometria)

View File

@@ -3,23 +3,30 @@
// © 2025 Port a C++20 amb SDL3 // © 2025 Port a C++20 amb SDL3
#include "escena_joc.hpp" #include "escena_joc.hpp"
#include "../../core/rendering/line_renderer.hpp"
#include "../../core/system/gestor_escenes.hpp"
#include "../../core/system/global_events.hpp"
#include <cmath> #include <cmath>
#include <cstdlib> #include <cstdlib>
#include <ctime> #include <ctime>
#include <iostream> #include <iostream>
#include <vector>
#include "../../core/rendering/line_renderer.hpp"
#include "../../core/system/gestor_escenes.hpp"
#include "../../core/system/global_events.hpp"
EscenaJoc::EscenaJoc(SDLManager& sdl) EscenaJoc::EscenaJoc(SDLManager& sdl)
: sdl_(sdl), nau_(sdl.obte_renderer()), itocado_(0), text_(sdl.obte_renderer()) { : sdl_(sdl),
debris_manager_(sdl.obte_renderer()),
nau_(sdl.obte_renderer()),
itocado_(0),
text_(sdl.obte_renderer()) {
// Inicialitzar bales amb renderer // Inicialitzar bales amb renderer
for (auto &bala : bales_) { for (auto& bala : bales_) {
bala = Bala(sdl.obte_renderer()); bala = Bala(sdl.obte_renderer());
} }
// Inicialitzar enemics amb renderer // Inicialitzar enemics amb renderer
for (auto &enemy : orni_) { for (auto& enemy : orni_) {
enemy = Enemic(sdl.obte_renderer()); enemy = Enemic(sdl.obte_renderer());
} }
} }
@@ -44,6 +51,9 @@ void EscenaJoc::executar() {
delta_time = 0.05f; delta_time = 0.05f;
} }
// Actualitzar comptador de FPS
sdl_.updateFPS(delta_time);
// Processar events SDL // Processar events SDL
while (SDL_PollEvent(&event)) { while (SDL_PollEvent(&event)) {
// Manejo de finestra // Manejo de finestra
@@ -91,12 +101,12 @@ void EscenaJoc::inicialitzar() {
nau_.inicialitzar(); nau_.inicialitzar();
// Inicialitzar enemics (ORNIs) // Inicialitzar enemics (ORNIs)
for (auto &enemy : orni_) { for (auto& enemy : orni_) {
enemy.inicialitzar(); enemy.inicialitzar();
} }
// Inicialitzar bales // Inicialitzar bales
for (auto &bala : bales_) { for (auto& bala : bales_) {
bala.inicialitzar(); bala.inicialitzar();
} }
} }
@@ -107,14 +117,20 @@ void EscenaJoc::actualitzar(float delta_time) {
nau_.actualitzar(delta_time); nau_.actualitzar(delta_time);
// Actualitzar moviment i rotació dels enemics (ORNIs) // Actualitzar moviment i rotació dels enemics (ORNIs)
for (auto &enemy : orni_) { for (auto& enemy : orni_) {
enemy.actualitzar(delta_time); enemy.actualitzar(delta_time);
} }
// Actualitzar moviment de bales (Fase 9) // Actualitzar moviment de bales (Fase 9)
for (auto &bala : bales_) { for (auto& bala : bales_) {
bala.actualitzar(delta_time); bala.actualitzar(delta_time);
} }
// Detectar col·lisions bala-enemic (Fase 10)
detectar_col·lisions_bales_enemics();
// Actualitzar fragments d'explosions
debris_manager_.actualitzar(delta_time);
} }
void EscenaJoc::dibuixar() { void EscenaJoc::dibuixar() {
@@ -125,39 +141,63 @@ void EscenaJoc::dibuixar() {
nau_.dibuixar(); nau_.dibuixar();
// Dibuixar ORNIs (enemics) // Dibuixar ORNIs (enemics)
for (const auto &enemy : orni_) { for (const auto& enemy : orni_) {
enemy.dibuixar(); enemy.dibuixar();
} }
// Dibuixar bales (Fase 9) // Dibuixar bales (Fase 9)
for (const auto &bala : bales_) { for (const auto& bala : bales_) {
bala.dibuixar(); bala.dibuixar();
} }
// Dibuixar fragments d'explosions (després d'altres objectes)
debris_manager_.dibuixar();
// Dibuixar marcador // Dibuixar marcador
dibuixar_marcador(); dibuixar_marcador();
} }
void EscenaJoc::processar_input(const SDL_Event &event) { void EscenaJoc::processar_input(const SDL_Event& event) {
// Processament d'input per events puntuals (no continus) // Processament d'input per events puntuals (no continus)
// L'input continu (fletxes) es processa en actualitzar() amb // L'input continu (fletxes) es processa en actualitzar() amb
// SDL_GetKeyboardState() // SDL_GetKeyboardState()
if (event.type == SDL_EVENT_KEY_DOWN) { if (event.type == SDL_EVENT_KEY_DOWN) {
switch (event.key.key) { switch (event.key.key) {
case SDLK_SPACE: case SDLK_SPACE: {
// Disparar (Fase 9) // No disparar si la nau està morta
// Basat en el codi Pascal original: crear bala en posició de la nau if (!nau_.esta_viva()) {
// El joc original només permetia 1 bala activa alhora break;
}
// Buscar primera bala inactiva // Disparar bala des del front de la nau
for (auto &bala : bales_) { // El ship.shp té el front a (0, -12) en coordenades locals
// 1. Calcular posició del front de la nau
constexpr float LOCAL_TIP_X = 0.0f;
constexpr float LOCAL_TIP_Y = -12.0f;
const Punt& ship_centre = nau_.get_centre();
float ship_angle = nau_.get_angle();
// Aplicar transformació: rotació + trasllació
float cos_a = std::cos(ship_angle);
float sin_a = std::sin(ship_angle);
float tip_x = LOCAL_TIP_X * cos_a - LOCAL_TIP_Y * sin_a + ship_centre.x;
float tip_y = LOCAL_TIP_X * sin_a + LOCAL_TIP_Y * cos_a + ship_centre.y;
Punt posicio_dispar = {tip_x, tip_y};
// 2. Buscar primera bala inactiva i disparar
for (auto& bala : bales_) {
if (!bala.esta_activa()) { if (!bala.esta_activa()) {
bala.disparar(nau_.get_centre(), nau_.get_angle()); bala.disparar(posicio_dispar, ship_angle);
break; break; // Només una bala per polsació
} }
} }
break; break;
}
default: default:
break; break;
@@ -171,7 +211,7 @@ void EscenaJoc::tocado() {
void EscenaJoc::dibuixar_marges() const { void EscenaJoc::dibuixar_marges() const {
// Dibuixar rectangle de la zona de joc // Dibuixar rectangle de la zona de joc
const SDL_FRect& zona = Defaults::Zones::GAME; const SDL_FRect& zona = Defaults::Zones::PLAYAREA;
// Coordenades dels cantons // Coordenades dels cantons
int x1 = static_cast<int>(zona.x); int x1 = static_cast<int>(zona.x);
@@ -188,26 +228,80 @@ void EscenaJoc::dibuixar_marges() const {
void EscenaJoc::dibuixar_marcador() { void EscenaJoc::dibuixar_marcador() {
// Text estàtic (hardcoded) // Text estàtic (hardcoded)
const std::string text = "SCORE: 00000 LIFE: 3 LEVEL: 01"; const std::string text = "SCORE: 01000 LIFE: 3 LEVEL: 01";
// Escala ajustada per cabre en 640px d'amplada // Paràmetres de renderització
// Zona marcador: width = 640 px, height = 64 px const float escala = 0.85f;
// Text: 34 caràcters → necessitem ~487 px amb escala 1.2 const float spacing = 0.0f;
// Altura caràcter: 20 * 1.2 = 24 px (37.5% de 64px)
const float escala = 1.2f;
const float spacing = 2.0f;
// Calcular amplada total del text // Calcular dimensions del text
float text_width = text_.get_text_width(text, escala, spacing); float text_width = text_.get_text_width(text, escala, spacing);
float text_height = text_.get_text_height(escala);
// Centrat horitzontal // Centrat horitzontal dins de la zona del marcador
float x = (Defaults::Zones::SCOREBOARD.w - text_width) / 2.0f; float x = (Defaults::Zones::SCOREBOARD.w - text_width) / 2.0f;
// Centrat vertical // Centrat vertical dins de la zona del marcador
// Altura del caràcter escalat: 20 * 1.2 = 24 px float y = Defaults::Zones::SCOREBOARD.y +
// Marge superior: (64 - 24) / 2 = 20 px (Defaults::Zones::SCOREBOARD.h - text_height) / 2.0f;
float y = Defaults::Zones::SCOREBOARD.y + 20.0f;
// Renderitzar // Renderitzar
text_.render(text, {x, y}, escala, spacing); text_.render(text, {x, y}, escala, spacing);
} }
void EscenaJoc::detectar_col·lisions_bales_enemics() {
// Constants amplificades per hitbox més generós (115%)
constexpr float RADI_BALA = Defaults::Entities::BULLET_RADIUS;
constexpr float RADI_ENEMIC = Defaults::Entities::ENEMY_RADIUS;
constexpr float SUMA_RADIS = (RADI_BALA + RADI_ENEMIC) * 1.15f; // 28.75 px
constexpr float SUMA_RADIS_QUADRAT = SUMA_RADIS * SUMA_RADIS; // 826.56
// Velocitat d'explosió reduïda per efecte suau
constexpr float VELOCITAT_EXPLOSIO = 50.0f; // px/s (en lloc de 80.0f per defecte)
// Iterar per totes les bales actives
for (auto& bala : bales_) {
if (!bala.esta_activa()) {
continue;
}
const Punt& pos_bala = bala.get_centre();
// Comprovar col·lisió amb tots els enemics actius
for (auto& enemic : orni_) {
if (!enemic.esta_actiu()) {
continue;
}
const Punt& pos_enemic = enemic.get_centre();
// Calcular distància quadrada (evita sqrt)
float dx = pos_bala.x - pos_enemic.x;
float dy = pos_bala.y - pos_enemic.y;
float distancia_quadrada = dx * dx + dy * dy;
// Comprovar col·lisió
if (distancia_quadrada <= SUMA_RADIS_QUADRAT) {
// *** COL·LISIÓ DETECTADA ***
// 1. Destruir enemic (marca com inactiu)
enemic.destruir();
// 2. Crear explosió de fragments
debris_manager_.explotar(
enemic.get_forma(), // Forma vectorial del pentàgon
pos_enemic, // Posició central
0.0f, // Angle (enemic té rotació interna)
1.0f, // Escala normal
VELOCITAT_EXPLOSIO // 50 px/s (explosió suau)
);
// 3. Desactivar bala
bala.desactivar();
// 4. Eixir del bucle intern (bala només destrueix 1 enemic)
break;
}
}
}
}

View File

@@ -5,20 +5,23 @@
#ifndef ESCENA_JOC_HPP #ifndef ESCENA_JOC_HPP
#define ESCENA_JOC_HPP #define ESCENA_JOC_HPP
#include <SDL3/SDL.h>
#include <array>
#include <cstdint>
#include "../../core/graphics/vector_text.hpp" #include "../../core/graphics/vector_text.hpp"
#include "../../core/rendering/sdl_manager.hpp" #include "../../core/rendering/sdl_manager.hpp"
#include "../../core/types.hpp" #include "../../core/types.hpp"
#include "../constants.hpp" #include "../constants.hpp"
#include "../effects/debris_manager.hpp"
#include "../entities/bala.hpp" #include "../entities/bala.hpp"
#include "../entities/enemic.hpp" #include "../entities/enemic.hpp"
#include "../entities/nau.hpp" #include "../entities/nau.hpp"
#include <SDL3/SDL.h>
#include <array>
#include <cstdint>
// Classe principal del joc (escena) // Classe principal del joc (escena)
class EscenaJoc { class EscenaJoc {
public: public:
explicit EscenaJoc(SDLManager& sdl); explicit EscenaJoc(SDLManager& sdl);
~EscenaJoc() = default; ~EscenaJoc() = default;
@@ -26,11 +29,14 @@ public:
void inicialitzar(); void inicialitzar();
void actualitzar(float delta_time); void actualitzar(float delta_time);
void dibuixar(); void dibuixar();
void processar_input(const SDL_Event &event); void processar_input(const SDL_Event& event);
private: private:
SDLManager& sdl_; SDLManager& sdl_;
// Efectes visuals
Effects::DebrisManager debris_manager_;
// Estat del joc // Estat del joc
Nau nau_; Nau nau_;
std::array<Enemic, Constants::MAX_ORNIS> orni_; std::array<Enemic, Constants::MAX_ORNIS> orni_;
@@ -43,6 +49,7 @@ private:
// Funcions privades // Funcions privades
void tocado(); void tocado();
void detectar_col·lisions_bales_enemics(); // Col·lisions bala-enemic
void dibuixar_marges() const; // Dibuixar vores de la zona de joc void dibuixar_marges() const; // Dibuixar vores de la zona de joc
void dibuixar_marcador(); // Dibuixar marcador de puntuació void dibuixar_marcador(); // Dibuixar marcador de puntuació
}; };

View File

@@ -2,20 +2,19 @@
// © 2025 Port a C++20 // © 2025 Port a C++20
#include "escena_logo.hpp" #include "escena_logo.hpp"
#include "../../core/system/gestor_escenes.hpp"
#include "../../core/system/global_events.hpp" #include <algorithm>
#include <cfloat>
#include <iostream>
#include "../../core/graphics/shape_loader.hpp" #include "../../core/graphics/shape_loader.hpp"
#include "../../core/rendering/shape_renderer.hpp" #include "../../core/rendering/shape_renderer.hpp"
#include <iostream> #include "../../core/system/gestor_escenes.hpp"
#include <cfloat> #include "../../core/system/global_events.hpp"
#include <algorithm>
// Helper: calcular el progrés individual d'una lletra // Helper: calcular el progrés individual d'una lletra
// en funció del progrés global (efecte seqüencial) // en funció del progrés global (efecte seqüencial)
static float calcular_progress_letra(size_t letra_index, static float calcular_progress_letra(size_t letra_index, size_t num_letras, float global_progress, float threshold) {
size_t num_letras,
float global_progress,
float threshold) {
if (num_letras == 0) if (num_letras == 0)
return 1.0f; return 1.0f;
@@ -38,7 +37,10 @@ static float calcular_progress_letra(size_t letra_index,
EscenaLogo::EscenaLogo(SDLManager& sdl) EscenaLogo::EscenaLogo(SDLManager& sdl)
: sdl_(sdl), : sdl_(sdl),
estat_actual_(EstatAnimacio::PRE_ANIMATION), estat_actual_(EstatAnimacio::PRE_ANIMATION),
temps_estat_actual_(0.0f) { temps_estat_actual_(0.0f),
debris_manager_(std::make_unique<Effects::DebrisManager>(sdl.obte_renderer())),
lletra_explosio_index_(0),
temps_des_ultima_explosio_(0.0f) {
std::cout << "Escena Logo: Inicialitzant...\n"; std::cout << "Escena Logo: Inicialitzant...\n";
inicialitzar_lletres(); inicialitzar_lletres();
} }
@@ -58,6 +60,9 @@ void EscenaLogo::executar() {
delta_time = 0.05f; delta_time = 0.05f;
} }
// Actualitzar comptador de FPS
sdl_.updateFPS(delta_time);
// Processar events SDL // Processar events SDL
while (SDL_PollEvent(&event)) { while (SDL_PollEvent(&event)) {
// Manejo de finestra // Manejo de finestra
@@ -92,9 +97,15 @@ void EscenaLogo::inicialitzar_lletres() {
// Llista de fitxers .shp (A repetida per a les dues A's) // Llista de fitxers .shp (A repetida per a les dues A's)
std::vector<std::string> fitxers = { std::vector<std::string> fitxers = {
"logo/letra_j.shp", "logo/letra_a.shp", "logo/letra_i.shp", "logo/letra_l.shp", "logo/letra_j.shp",
"logo/letra_g.shp", "logo/letra_a.shp", "logo/letra_m.shp", "logo/letra_e.shp", "logo/letra_s.shp" "logo/letra_a.shp",
}; "logo/letra_i.shp",
"logo/letra_l.shp",
"logo/letra_g.shp",
"logo/letra_a.shp",
"logo/letra_m.shp",
"logo/letra_e.shp",
"logo/letra_s.shp"};
// Pas 1: Carregar totes les formes i calcular amplades // Pas 1: Carregar totes les formes i calcular amplades
float ancho_total = 0.0f; float ancho_total = 0.0f;
@@ -124,12 +135,10 @@ void EscenaLogo::inicialitzar_lletres() {
float ancho = ancho_sin_escalar * ESCALA_FINAL; float ancho = ancho_sin_escalar * ESCALA_FINAL;
float offset_centre = (forma->get_centre().x - min_x) * ESCALA_FINAL; float offset_centre = (forma->get_centre().x - min_x) * ESCALA_FINAL;
lletres_.push_back({ lletres_.push_back({forma,
forma,
{0.0f, 0.0f}, // Posició es calcularà després {0.0f, 0.0f}, // Posició es calcularà després
ancho, ancho,
offset_centre offset_centre});
});
ancho_total += ancho; ancho_total += ancho;
} }
@@ -165,7 +174,15 @@ void EscenaLogo::inicialitzar_lletres() {
void EscenaLogo::canviar_estat(EstatAnimacio nou_estat) { void EscenaLogo::canviar_estat(EstatAnimacio nou_estat) {
estat_actual_ = nou_estat; estat_actual_ = nou_estat;
temps_estat_actual_ = 0.0f; // Reset temps temps_estat_actual_ = 0.0f; // Reset temps
std::cout << "[EscenaLogo] Canvi a estat: " << static_cast<int>(nou_estat) << "\n";
// Inicialitzar estat d'explosió
if (nou_estat == EstatAnimacio::EXPLOSION) {
lletra_explosio_index_ = 0;
temps_des_ultima_explosio_ = 0.0f;
}
std::cout << "[EscenaLogo] Canvi a estat: " << static_cast<int>(nou_estat)
<< "\n";
} }
bool EscenaLogo::totes_lletres_completes() const { bool EscenaLogo::totes_lletres_completes() const {
@@ -173,6 +190,35 @@ bool EscenaLogo::totes_lletres_completes() const {
return temps_estat_actual_ >= DURACIO_ZOOM; return temps_estat_actual_ >= DURACIO_ZOOM;
} }
void EscenaLogo::actualitzar_explosions(float delta_time) {
temps_des_ultima_explosio_ += delta_time;
// Comprovar si és el moment d'explotar la següent lletra
if (temps_des_ultima_explosio_ >= DELAY_ENTRE_EXPLOSIONS) {
if (lletra_explosio_index_ < lletres_.size()) {
// Explotar lletra actual
const auto& lletra = lletres_[lletra_explosio_index_];
debris_manager_->explotar(
lletra.forma, // Forma a explotar
lletra.posicio, // Posició
0.0f, // Angle (sense rotació)
ESCALA_FINAL, // Escala (lletres a escala final)
VELOCITAT_EXPLOSIO // Velocitat base
);
std::cout << "[EscenaLogo] Explota lletra " << lletra_explosio_index_ << "\n";
// Passar a la següent lletra
lletra_explosio_index_++;
temps_des_ultima_explosio_ = 0.0f;
} else {
// Totes les lletres han explotat, transició a POST_EXPLOSION
canviar_estat(EstatAnimacio::POST_EXPLOSION);
}
}
}
void EscenaLogo::actualitzar(float delta_time) { void EscenaLogo::actualitzar(float delta_time) {
temps_estat_actual_ += delta_time; temps_estat_actual_ += delta_time;
@@ -190,11 +236,24 @@ void EscenaLogo::actualitzar(float delta_time) {
break; break;
case EstatAnimacio::POST_ANIMATION: case EstatAnimacio::POST_ANIMATION:
if (temps_estat_actual_ >= DURACIO_POST) { if (temps_estat_actual_ >= DURACIO_POST_ANIMATION) {
canviar_estat(EstatAnimacio::EXPLOSION);
}
break;
case EstatAnimacio::EXPLOSION:
actualitzar_explosions(delta_time);
break;
case EstatAnimacio::POST_EXPLOSION:
if (temps_estat_actual_ >= DURACIO_POST_EXPLOSION) {
GestorEscenes::actual = GestorEscenes::Escena::JOC; GestorEscenes::actual = GestorEscenes::Escena::JOC;
} }
break; break;
} }
// Actualitzar animacions de debris
debris_manager_->actualitzar(delta_time);
} }
void EscenaLogo::dibuixar() { void EscenaLogo::dibuixar() {
@@ -207,49 +266,71 @@ void EscenaLogo::dibuixar() {
return; // No renderitzar lletres return; // No renderitzar lletres
} }
// ANIMATION o POST_ANIMATION: Calcular progrés // ANIMATION o POST_ANIMATION: Dibuixar lletres amb animació
float global_progress = (estat_actual_ == EstatAnimacio::ANIMATION) if (estat_actual_ == EstatAnimacio::ANIMATION ||
estat_actual_ == EstatAnimacio::POST_ANIMATION) {
float global_progress =
(estat_actual_ == EstatAnimacio::ANIMATION)
? std::min(temps_estat_actual_ / DURACIO_ZOOM, 1.0f) ? std::min(temps_estat_actual_ / DURACIO_ZOOM, 1.0f)
: 1.0f; // POST: mantenir al 100% : 1.0f; // POST: mantenir al 100%
// Punt inicial del zoom (configurable amb ORIGEN_ZOOM_X/Y)
const Punt ORIGEN_ZOOM = {ORIGEN_ZOOM_X, ORIGEN_ZOOM_Y}; const Punt ORIGEN_ZOOM = {ORIGEN_ZOOM_X, ORIGEN_ZOOM_Y};
// Dibuixar cada lletra amb animació seqüencial
for (size_t i = 0; i < lletres_.size(); i++) { for (size_t i = 0; i < lletres_.size(); i++) {
const auto& lletra = lletres_[i]; const auto& lletra = lletres_[i];
// Calcular progrés individual d'aquesta lletra (0.0 → 1.0) float letra_progress = calcular_progress_letra(
float letra_progress = calcular_progress_letra(i, lletres_.size(), global_progress, THRESHOLD_LETRA); i,
lletres_.size(),
global_progress,
THRESHOLD_LETRA);
// Si la lletra encara no ha començat, saltar-la
if (letra_progress <= 0.0f) { if (letra_progress <= 0.0f) {
continue; continue;
} }
// Interpolar posició: des del origen zoom cap a posició final
Punt pos_actual; Punt pos_actual;
pos_actual.x = ORIGEN_ZOOM.x + (lletra.posicio.x - ORIGEN_ZOOM.x) * letra_progress; pos_actual.x =
pos_actual.y = ORIGEN_ZOOM.y + (lletra.posicio.y - ORIGEN_ZOOM.y) * letra_progress; ORIGEN_ZOOM.x + (lletra.posicio.x - ORIGEN_ZOOM.x) * letra_progress;
pos_actual.y =
ORIGEN_ZOOM.y + (lletra.posicio.y - ORIGEN_ZOOM.y) * letra_progress;
// Aplicar ease-out quadràtic per suavitat
float t = letra_progress; float t = letra_progress;
float ease_factor = 1.0f - (1.0f - t) * (1.0f - t); float ease_factor = 1.0f - (1.0f - t) * (1.0f - t);
float escala_actual =
ESCALA_INICIAL + (ESCALA_FINAL - ESCALA_INICIAL) * ease_factor;
// Interpolar escala amb ease-out: des de ESCALA_INICIAL cap a ESCALA_FINAL
float escala_actual = ESCALA_INICIAL + (ESCALA_FINAL - ESCALA_INICIAL) * ease_factor;
// Renderitzar la lletra
Rendering::render_shape( Rendering::render_shape(
sdl_.obte_renderer(), sdl_.obte_renderer(),
lletra.forma, lletra.forma,
pos_actual, // Posició interpolada pos_actual,
0.0f, // Sense rotació 0.0f,
escala_actual, // Escala interpolada amb ease-out escala_actual,
true, // Dibuixar true,
1.0f // Progress = 1.0 (lletra completa, sense animació de primitives) 1.0f);
);
} }
}
// EXPLOSION: Dibuixar només lletres que encara no han explotat
if (estat_actual_ == EstatAnimacio::EXPLOSION) {
for (size_t i = lletra_explosio_index_; i < lletres_.size(); i++) {
const auto& lletra = lletres_[i];
Rendering::render_shape(
sdl_.obte_renderer(),
lletra.forma,
lletra.posicio,
0.0f,
ESCALA_FINAL,
true,
1.0f);
}
}
// POST_EXPLOSION: No dibuixar lletres, només debris (a baix)
// Sempre dibuixar debris (si n'hi ha d'actius)
debris_manager_->dibuixar();
sdl_.presenta(); sdl_.presenta();
} }

View File

@@ -4,29 +4,43 @@
#pragma once #pragma once
#include "../../core/rendering/sdl_manager.hpp"
#include "../../core/graphics/shape.hpp"
#include "../../core/types.hpp"
#include <SDL3/SDL.h> #include <SDL3/SDL.h>
#include <vector>
#include <memory> #include <memory>
#include <vector>
#include "../../core/graphics/shape.hpp"
#include "../../core/rendering/sdl_manager.hpp"
#include "../../core/types.hpp"
#include "../effects/debris_manager.hpp"
#include "core/defaults.hpp"
class EscenaLogo { class EscenaLogo {
public: public:
explicit EscenaLogo(SDLManager& sdl); explicit EscenaLogo(SDLManager& sdl);
void executar(); // Bucle principal de l'escena void executar(); // Bucle principal de l'escena
private: private:
// Màquina d'estats per l'animació // Màquina d'estats per l'animació
enum class EstatAnimacio { enum class EstatAnimacio {
PRE_ANIMATION, // Pantalla negra inicial PRE_ANIMATION, // Pantalla negra inicial
ANIMATION, // Animació de zoom de lletres ANIMATION, // Animació de zoom de lletres
POST_ANIMATION // Logo complet visible POST_ANIMATION, // Logo complet visible
EXPLOSION, // Explosió seqüencial de lletres
POST_EXPLOSION // Espera després de l'última explosió
}; };
SDLManager& sdl_; SDLManager& sdl_;
EstatAnimacio estat_actual_; // Estat actual de la màquina EstatAnimacio estat_actual_; // Estat actual de la màquina
float temps_estat_actual_; // Temps en l'estat actual (reset en cada transició) float
temps_estat_actual_; // Temps en l'estat actual (reset en cada transició)
// Gestor de fragments d'explosions
std::unique_ptr<Effects::DebrisManager> debris_manager_;
// Seguiment d'explosions seqüencials
size_t lletra_explosio_index_; // Índex de la següent lletra a explotar
float temps_des_ultima_explosio_; // Temps des de l'última explosió
// Estructura per a cada lletra del logo // Estructura per a cada lletra del logo
struct LetraLogo { struct LetraLogo {
@@ -41,19 +55,23 @@ private:
// Constants d'animació // Constants d'animació
static constexpr float DURACIO_PRE = 1.5f; // Duració PRE_ANIMATION (pantalla negra) static constexpr float DURACIO_PRE = 1.5f; // Duració PRE_ANIMATION (pantalla negra)
static constexpr float DURACIO_ZOOM = 4.0f; // Duració del zoom (segons) static constexpr float DURACIO_ZOOM = 4.0f; // Duració del zoom (segons)
static constexpr float DURACIO_POST = 4.0f; // Duració POST_ANIMATION (logo complet) static constexpr float DURACIO_POST_ANIMATION = 3.0f; // Duració POST_ANIMATION (logo complet)
static constexpr float DURACIO_POST_EXPLOSION = 3.0f; // Duració POST_EXPLOSION (espera final)
static constexpr float DELAY_ENTRE_EXPLOSIONS = 0.15f; // Temps entre explosions de lletres
static constexpr float VELOCITAT_EXPLOSIO = 80.0f; // Velocitat base fragments (px/s)
static constexpr float ESCALA_INICIAL = 0.1f; // Escala inicial (10%) static constexpr float ESCALA_INICIAL = 0.1f; // Escala inicial (10%)
static constexpr float ESCALA_FINAL = 0.8f; // Escala final (80%) static constexpr float ESCALA_FINAL = 0.8f; // Escala final (80%)
static constexpr float ESPAI_ENTRE_LLETRES = 10.0f; // Espaiat entre lletres static constexpr float ESPAI_ENTRE_LLETRES = 10.0f; // Espaiat entre lletres
// Constants d'animació seqüencial // Constants d'animació seqüencial
static constexpr float THRESHOLD_LETRA = 0.6f; // Umbral per activar següent lletra (0.0-1.0) static constexpr float THRESHOLD_LETRA = 0.6f; // Umbral per activar següent lletra (0.0-1.0)
static constexpr float ORIGEN_ZOOM_X = 640.0f / 2.0f; // Punt inicial X del zoom (320) static constexpr float ORIGEN_ZOOM_X = Defaults::Game::WIDTH * 0.5f; // Punt inicial X del zoom
static constexpr float ORIGEN_ZOOM_Y = 480.0f * 0.4f; // Punt inicial Y del zoom (240) static constexpr float ORIGEN_ZOOM_Y = Defaults::Game::HEIGHT * 0.4f; // Punt inicial Y del zoom
// Mètodes privats // Mètodes privats
void inicialitzar_lletres(); void inicialitzar_lletres();
void actualitzar(float delta_time); void actualitzar(float delta_time);
void actualitzar_explosions(float delta_time);
void dibuixar(); void dibuixar();
void processar_events(const SDL_Event& event); void processar_events(const SDL_Event& event);

View File

@@ -1,12 +1,13 @@
#include "options.hpp" #include "options.hpp"
#include "../core/defaults.hpp"
#include "../external/fkyaml_node.hpp"
#include "project.h"
#include <fstream> #include <fstream>
#include <iostream> #include <iostream>
#include <string> #include <string>
#include "../core/defaults.hpp"
#include "../external/fkyaml_node.hpp"
#include "project.h"
namespace Options { namespace Options {
// Inicialitzar opcions amb valors per defecte de Defaults:: // Inicialitzar opcions amb valors per defecte de Defaults::
@@ -35,18 +36,21 @@ void init() {
gameplay.max_enemies = Defaults::Entities::MAX_ORNIS; gameplay.max_enemies = Defaults::Entities::MAX_ORNIS;
gameplay.max_bullets = Defaults::Entities::MAX_BALES; gameplay.max_bullets = Defaults::Entities::MAX_BALES;
// Rendering
rendering.vsync = Defaults::Rendering::VSYNC_DEFAULT;
// Version // Version
version = std::string(Project::VERSION); version = std::string(Project::VERSION);
} }
// Establir la ruta del fitxer de configuració // Establir la ruta del fitxer de configuració
void setConfigFile(const std::string &path) { config_file_path = path; } void setConfigFile(const std::string& path) { config_file_path = path; }
// Funcions auxiliars per carregar seccions del YAML // Funcions auxiliars per carregar seccions del YAML
static void loadWindowConfigFromYaml(const fkyaml::node &yaml) { static void loadWindowConfigFromYaml(const fkyaml::node& yaml) {
if (yaml.contains("window")) { if (yaml.contains("window")) {
const auto &win = yaml["window"]; const auto& win = yaml["window"];
if (win.contains("width")) { if (win.contains("width")) {
try { try {
@@ -90,9 +94,9 @@ static void loadWindowConfigFromYaml(const fkyaml::node &yaml) {
} }
} }
static void loadPhysicsConfigFromYaml(const fkyaml::node &yaml) { static void loadPhysicsConfigFromYaml(const fkyaml::node& yaml) {
if (yaml.contains("physics")) { if (yaml.contains("physics")) {
const auto &phys = yaml["physics"]; const auto& phys = yaml["physics"];
if (phys.contains("rotation_speed")) { if (phys.contains("rotation_speed")) {
try { try {
@@ -154,9 +158,9 @@ static void loadPhysicsConfigFromYaml(const fkyaml::node &yaml) {
} }
} }
static void loadGameplayConfigFromYaml(const fkyaml::node &yaml) { static void loadGameplayConfigFromYaml(const fkyaml::node& yaml) {
if (yaml.contains("gameplay")) { if (yaml.contains("gameplay")) {
const auto &game = yaml["gameplay"]; const auto& game = yaml["gameplay"];
if (game.contains("max_enemies")) { if (game.contains("max_enemies")) {
try { try {
@@ -180,6 +184,22 @@ static void loadGameplayConfigFromYaml(const fkyaml::node &yaml) {
} }
} }
static void loadRenderingConfigFromYaml(const fkyaml::node& yaml) {
if (yaml.contains("rendering")) {
const auto& rend = yaml["rendering"];
if (rend.contains("vsync")) {
try {
int val = rend["vsync"].get_value<int>();
// Validar: només 0 o 1
rendering.vsync = (val == 0 || val == 1) ? val : Defaults::Rendering::VSYNC_DEFAULT;
} catch (...) {
rendering.vsync = Defaults::Rendering::VSYNC_DEFAULT;
}
}
}
}
// Carregar configuració des del fitxer YAML // Carregar configuració des del fitxer YAML
auto loadFromFile() -> bool { auto loadFromFile() -> bool {
const std::string CONFIG_VERSION = std::string(Project::VERSION); const std::string CONFIG_VERSION = std::string(Project::VERSION);
@@ -225,6 +245,7 @@ auto loadFromFile() -> bool {
loadWindowConfigFromYaml(yaml); loadWindowConfigFromYaml(yaml);
loadPhysicsConfigFromYaml(yaml); loadPhysicsConfigFromYaml(yaml);
loadGameplayConfigFromYaml(yaml); loadGameplayConfigFromYaml(yaml);
loadRenderingConfigFromYaml(yaml);
if (console) { if (console) {
std::cout << "Config carregada correctament des de: " << config_file_path std::cout << "Config carregada correctament des de: " << config_file_path
@@ -233,7 +254,7 @@ auto loadFromFile() -> bool {
return true; return true;
} catch (const fkyaml::exception &e) { } catch (const fkyaml::exception& e) {
// Error de parsejat YAML → regenerar config // Error de parsejat YAML → regenerar config
if (console) { if (console) {
std::cerr << "Error parsejant YAML: " << e.what() << '\n'; std::cerr << "Error parsejant YAML: " << e.what() << '\n';
@@ -284,7 +305,11 @@ auto saveToFile() -> bool {
file << "# GAMEPLAY\n"; file << "# GAMEPLAY\n";
file << "gameplay:\n"; file << "gameplay:\n";
file << " max_enemies: " << gameplay.max_enemies << "\n"; file << " max_enemies: " << gameplay.max_enemies << "\n";
file << " max_bullets: " << gameplay.max_bullets << "\n"; file << " max_bullets: " << gameplay.max_bullets << "\n\n";
file << "# RENDERITZACIÓ\n";
file << "rendering:\n";
file << " vsync: " << rendering.vsync << " # 0=disabled, 1=enabled\n";
file.close(); file.close();

View File

@@ -27,6 +27,10 @@ struct Gameplay {
int max_bullets{3}; int max_bullets{3};
}; };
struct Rendering {
int vsync{1}; // 0=disabled, 1=enabled
};
// Variables globals (inline per evitar ODR violations) // Variables globals (inline per evitar ODR violations)
inline std::string version{}; // Versió del config per validació inline std::string version{}; // Versió del config per validació
@@ -34,6 +38,7 @@ inline bool console{false}; // Eixida de debug
inline Window window{}; inline Window window{};
inline Physics physics{}; inline Physics physics{};
inline Gameplay gameplay{}; inline Gameplay gameplay{};
inline Rendering rendering{};
inline std::string config_file_path{}; // Establert per setConfigFile() inline std::string config_file_path{}; // Establert per setConfigFile()
@@ -41,7 +46,7 @@ inline std::string config_file_path{}; // Establert per setConfigFile()
void init(); // Inicialitzar amb valors per defecte void init(); // Inicialitzar amb valors per defecte
void setConfigFile( void setConfigFile(
const std::string &path); // Establir ruta del fitxer de config const std::string& path); // Establir ruta del fitxer de config
auto loadFromFile() -> bool; // Carregar config YAML auto loadFromFile() -> bool; // Carregar config YAML
auto saveToFile() -> bool; // Guardar config YAML auto saveToFile() -> bool; // Guardar config YAML

View File

@@ -1,4 +1,5 @@
#include <SDL2/SDL.h> #include <SDL2/SDL.h>
#include <string> #include <string>
#include <vector> #include <vector>
@@ -32,7 +33,7 @@ struct triangle {
typedef std::vector<ipunt> ivector(); typedef std::vector<ipunt> ivector();
struct poligon { struct poligon {
ivector *ipunts; ivector* ipunts;
ivector ipuntx; ivector ipuntx;
punt centre; punt centre;
float angl; float angl;

View File

@@ -2,11 +2,12 @@
// © 1999 Visente i Sergi (versió Pascal) // © 1999 Visente i Sergi (versió Pascal)
// © 2025 Port a C++20 amb SDL3 // © 2025 Port a C++20 amb SDL3
#include "core/system/director.hpp"
#include <string> #include <string>
#include <vector> #include <vector>
int main(int argc, char *argv[]) { #include "core/system/director.hpp"
int main(int argc, char* argv[]) {
// Convertir arguments a std::vector<std::string> // Convertir arguments a std::vector<std::string>
std::vector<std::string> args(argv, argv + argc); std::vector<std::string> args(argv, argv + argc);

14
todo.txt Normal file
View File

@@ -0,0 +1,14 @@
ORNI TODO:
- Crear escena titulo: muestra el logo, el copyright, el texto de insert coin o press start y quizas un starfield de fondo
- Revisar contador de frames: hace cosas raras, hacer que se actualice cada segundo
- Añadir clase audio -> añadir ruidos a logo, title y game
- Añadir resource.pack
- Crear estados en GAME: GET_READY -> GAME -> GAME_OVER -> CONTINUE
-> STAGE_COMPLETED -> GET_READY (next stage)
- Añadir nuevos enemigos: cuadrado, ... otras formas (revisar Geometry Wars). Darles fiferente personalidad
- La bala ha de salir de la punta de la nave, con forma cuadrada, va rotando
- Pensar si todas las entidades deberian tener dos radios de colision: uno pequeño para colision con bordes o jugador, uno mas grande para colision con balas
- Revisar que los debris salgan realmente en direccion contraria al centro de la figura
- Crear progresion: fichero con enemigos para ese nivel. cuando se acaba la lista de niveles -> loop con dificultad aumentada. Pensar si jefe final. Juego no tiene fin
- Menu de servicio? numero de vidas, numero de continues o free play, controles de audio, controles de video, colores, activar parpadeo o cambiar frecuencia
- Cuando se destruye un enemigo, salen dos mas pequeños