segon commit

This commit is contained in:
2026-04-05 21:34:38 +02:00
parent d168ed59f9
commit 20ad7d778f
502 changed files with 178145 additions and 0 deletions

View File

@@ -0,0 +1,117 @@
#include "game/entities/enemy.hpp"
#include <SDL3/SDL.h>
#include <cstdlib> // Para rand
#include "core/rendering/sprite/animated_sprite.hpp" // Para SAnimatedSprite
#include "core/resources/resource_cache.hpp" // Para Resource
#include "utils/utils.hpp" // Para stringToColor
// Constructor
Enemy::Enemy(const Data& enemy)
: sprite_(std::make_shared<AnimatedSprite>(Resource::Cache::get()->getAnimationData(enemy.animation_path))),
color_string_(enemy.color),
x1_(enemy.x1),
x2_(enemy.x2),
y1_(enemy.y1),
y2_(enemy.y2),
should_flip_(enemy.flip),
should_mirror_(enemy.mirror) {
// Obten el resto de valores
sprite_->setPosX(enemy.x);
sprite_->setPosY(enemy.y);
sprite_->setVelX(enemy.vx);
sprite_->setVelY(enemy.vy);
const int FLIP = (should_flip_ && enemy.vx < 0.0F) ? SDL_FLIP_HORIZONTAL : SDL_FLIP_NONE;
const int MIRROR = should_mirror_ ? SDL_FLIP_VERTICAL : SDL_FLIP_NONE;
sprite_->setFlip(static_cast<SDL_FlipMode>(FLIP | MIRROR)); // NOLINT(clang-analyzer-optin.core.EnumCastOutOfRange) SDL flags are designed for bitwise OR
collider_ = getRect();
color_ = stringToColor(color_string_);
// Coloca un frame al azar o el designado
sprite_->setCurrentAnimationFrame((enemy.frame == -1) ? (rand() % sprite_->getCurrentAnimationSize()) : enemy.frame);
}
// Pinta el enemigo en pantalla
void Enemy::render() {
sprite_->render(1, color_);
}
// Actualiza las variables del objeto
void Enemy::update(float delta_time) {
sprite_->update(delta_time);
checkPath();
collider_ = getRect();
}
#ifdef _DEBUG
// Solo actualiza la animación sin mover al enemigo
void Enemy::updateAnimation(float delta_time) {
sprite_->animate(delta_time);
}
// Resetea el enemigo a su posición inicial (para editor)
void Enemy::resetToInitialPosition(const Data& data) {
sprite_->setPosX(data.x);
sprite_->setPosY(data.y);
sprite_->setVelX(data.vx);
sprite_->setVelY(data.vy);
const int FLIP = (should_flip_ && data.vx < 0.0F) ? SDL_FLIP_HORIZONTAL : SDL_FLIP_NONE;
const int MIRROR = should_mirror_ ? SDL_FLIP_VERTICAL : SDL_FLIP_NONE;
sprite_->setFlip(static_cast<SDL_FlipMode>(FLIP | MIRROR)); // NOLINT(clang-analyzer-optin.core.EnumCastOutOfRange)
collider_ = getRect();
}
#endif
// Comprueba si ha llegado al limite del recorrido para darse media vuelta
void Enemy::checkPath() { // NOLINT(readability-make-member-function-const)
if (sprite_->getPosX() > x2_ || sprite_->getPosX() < x1_) {
// Recoloca
if (sprite_->getPosX() > x2_) {
sprite_->setPosX(x2_);
} else {
sprite_->setPosX(x1_);
}
// Cambia el sentido
sprite_->setVelX(sprite_->getVelX() * (-1));
// Invierte el sprite
if (should_flip_) {
sprite_->flip();
}
}
if (sprite_->getPosY() > y2_ || sprite_->getPosY() < y1_) {
// Recoloca
if (sprite_->getPosY() > y2_) {
sprite_->setPosY(y2_);
} else {
sprite_->setPosY(y1_);
}
// Cambia el sentido
sprite_->setVelY(sprite_->getVelY() * (-1));
// Invierte el sprite
if (should_flip_) {
sprite_->flip();
}
}
}
// Devuelve el rectangulo que contiene al enemigo
auto Enemy::getRect() -> SDL_FRect {
return sprite_->getRect();
}
// Obtiene el rectangulo de colision del enemigo
auto Enemy::getCollider() -> SDL_FRect& {
return collider_;
}

View File

@@ -0,0 +1,55 @@
#pragma once
#include <SDL3/SDL.h>
#include <memory> // Para shared_ptr
#include <string> // Para string
class AnimatedSprite; // lines 7-7
class Enemy {
public:
struct Data {
std::string animation_path; // Ruta al fichero con la animación
float x{0.0F}; // Posición inicial en el eje X
float y{0.0F}; // Posición inicial en el eje Y
float vx{0.0F}; // Velocidad en el eje X
float vy{0.0F}; // Velocidad en el eje Y
int x1{0}; // Límite izquierdo de la ruta en el eje X
int x2{0}; // Límite derecho de la ruta en el eje X
int y1{0}; // Límite superior de la ruta en el eje Y
int y2{0}; // Límite inferior de la ruta en el eje Y
bool flip{false}; // Indica si el enemigo hace flip al terminar su ruta
bool mirror{false}; // Indica si el enemigo está volteado verticalmente
int frame{0}; // Frame inicial para la animación del enemigo
std::string color; // Color del enemigo
};
explicit Enemy(const Data& enemy); // Constructor
~Enemy() = default; // Destructor
void render(); // Pinta el enemigo en pantalla
void update(float delta_time); // Actualiza las variables del objeto
#ifdef _DEBUG
void updateAnimation(float delta_time); // Solo actualiza la animación sin mover al enemigo
void resetToInitialPosition(const Data& data); // Resetea el enemigo a su posición inicial (para editor)
#endif
auto getRect() -> SDL_FRect; // Devuelve el rectangulo que contiene al enemigo
auto getCollider() -> SDL_FRect&; // Obtiene el rectangulo de colision del enemigo
private:
void checkPath(); // Comprueba si ha llegado al limite del recorrido para darse media vuelta
std::shared_ptr<AnimatedSprite> sprite_; // Sprite del enemigo
// Variables
Uint8 color_{0}; // Color del enemigo
std::string color_string_; // Color del enemigo en formato texto
int x1_{0}; // Limite izquierdo de la ruta en el eje X
int x2_{0}; // Limite derecho de la ruta en el eje X
int y1_{0}; // Limite superior de la ruta en el eje Y
int y2_{0}; // Limite inferior de la ruta en el eje Y
SDL_FRect collider_{}; // Caja de colisión
bool should_flip_{false}; // Indica si el enemigo hace flip al terminar su ruta
bool should_mirror_{false}; // Indica si el enemigo se dibuja volteado verticalmente
};

View File

@@ -0,0 +1,71 @@
#include "game/entities/item.hpp"
#include "core/rendering/sprite/sprite.hpp" // Para SSprite
#include "core/resources/resource_cache.hpp" // Para Resource
// Constructor
Item::Item(const Data& item)
: sprite_(std::make_shared<Sprite>(Resource::Cache::get()->getSurface(item.tile_set_file), item.x, item.y, ITEM_SIZE, ITEM_SIZE)),
time_accumulator_(static_cast<float>(item.counter) * COLOR_CHANGE_INTERVAL) {
// Inicia variables
sprite_->setClip((item.tile % 10) * ITEM_SIZE, (item.tile / 10) * ITEM_SIZE, ITEM_SIZE, ITEM_SIZE);
collider_ = sprite_->getRect();
// Inicializa los colores
color_.push_back(item.color1);
color_.push_back(item.color1);
color_.push_back(item.color2);
color_.push_back(item.color2);
}
// Actualiza las variables del objeto
void Item::update(float delta_time) {
if (is_paused_) {
return;
}
time_accumulator_ += delta_time;
}
// Pinta el objeto en pantalla
void Item::render() const { // NOLINT(readability-convert-member-functions-to-static)
// Calcula el índice de color basado en el tiempo acumulado
const int INDEX = static_cast<int>(time_accumulator_ / COLOR_CHANGE_INTERVAL) % static_cast<int>(color_.size());
sprite_->render(1, color_.at(INDEX));
}
// Obtiene su ubicación
auto Item::getPos() -> SDL_FPoint { // NOLINT(readability-convert-member-functions-to-static)
const SDL_FPoint P = {.x = sprite_->getX(), .y = sprite_->getY()};
return P;
}
#ifdef _DEBUG
// Establece la posición del item (para editor)
void Item::setPosition(float x, float y) {
sprite_->setPosition(x, y);
collider_ = sprite_->getRect();
}
#endif
#ifdef _DEBUG
// Cambia el tile del item (para editor)
void Item::setTile(int tile) {
sprite_->setClip((tile % 10) * ITEM_SIZE, (tile / 10) * ITEM_SIZE, ITEM_SIZE, ITEM_SIZE);
}
#endif
// Asigna los colores del objeto
void Item::setColors(Uint8 col1, Uint8 col2) {
// Reinicializa el vector de colores
color_.clear();
// Añade el primer color
color_.push_back(col1);
color_.push_back(col1);
// Añade el segundo color
color_.push_back(col2);
color_.push_back(col2);
}

View File

@@ -0,0 +1,48 @@
#pragma once
#include <SDL3/SDL.h>
#include <memory> // Para shared_ptr
#include <string> // Para string
#include <vector> // Para vector
class Sprite;
class Item {
public:
struct Data {
std::string tile_set_file; // Ruta al fichero con los gráficos del item
float x{0.0F}; // Posición del item en pantalla
float y{0.0F}; // Posición del item en pantalla
int tile{0}; // Número de tile dentro de la textura
int counter{0}; // Contador inicial. Es el que lo hace cambiar de color
Uint8 color1{0}; // Uno de los dos colores que se utiliza para el item
Uint8 color2{0}; // Uno de los dos colores que se utiliza para el item
};
explicit Item(const Data& item); // Constructor
~Item() = default; // Destructor
void render() const; // Pinta el objeto en pantalla
void update(float delta_time); // Actualiza las variables del objeto
void setPaused(bool paused) { is_paused_ = paused; } // Pausa/despausa el item
auto getCollider() -> SDL_FRect& { return collider_; } // Obtiene el rectangulo de colision del objeto
auto getPos() -> SDL_FPoint; // Obtiene su ubicación
void setColors(Uint8 col1, Uint8 col2); // Asigna los colores del objeto
#ifdef _DEBUG
void setPosition(float x, float y); // Establece la posición del item (para editor)
void setTile(int tile); // Cambia el tile del item (para editor)
#endif
private:
static constexpr float ITEM_SIZE = 8.0F; // Tamaño del item en pixels
static constexpr float COLOR_CHANGE_INTERVAL = 0.06F; // Intervalo de cambio de color en segundos (4 frames a 66.67fps)
std::shared_ptr<Sprite> sprite_; // SSprite del objeto
// Variables
std::vector<Uint8> color_; // Vector con los colores del objeto
float time_accumulator_{0.0F}; // Acumulador de tiempo para cambio de color
SDL_FRect collider_{}; // Rectangulo de colisión
bool is_paused_{false}; // Indica si el item está pausado
};

View File

@@ -0,0 +1,972 @@
// IWYU pragma: no_include <bits/std_abs.h>
#include "game/entities/player.hpp"
#include <algorithm> // Para max, min
#include <cmath> // Para ceil, abs
#include <iostream>
#include <ranges> // Para std::ranges::any_of
#include "core/audio/audio.hpp" // Para Audio
#include "core/input/input.hpp" // Para Input, InputAction
#include "core/rendering/sprite/animated_sprite.hpp" // Para SAnimatedSprite
#include "core/resources/resource_cache.hpp" // Para Resource
#include "game/gameplay/room.hpp" // Para Room, TileType
#include "game/options.hpp" // Para Cheat, Options, options
#include "utils/defines.hpp" // Para RoomBorder::BOTTOM, RoomBorder::LEFT, RoomBorder::RIGHT
#ifdef _DEBUG
#include "core/system/debug.hpp" // Para Debug
#endif
// Constructor
Player::Player(const Data& player)
: room_(player.room) {
initSprite(player.animations_path);
setColor();
applySpawnValues(player.spawn_data);
placeSprite();
initSounds();
previous_state_ = state_;
}
// Pinta el jugador en pantalla
void Player::render() {
sprite_->render(1, color_);
#ifdef _DEBUG
if (Debug::get()->isEnabled()) {
Screen::get()->getRendererSurface()->putPixel(under_right_foot_.x, under_right_foot_.y, static_cast<Uint8>(PaletteColor::GREEN));
Screen::get()->getRendererSurface()->putPixel(under_left_foot_.x, under_left_foot_.y, static_cast<Uint8>(PaletteColor::GREEN));
}
#endif
}
// Actualiza las variables del objeto
void Player::update(float delta_time) {
if (!is_paused_) {
handleInput();
updateState(delta_time);
move(delta_time);
handleKillingTiles(); // Los collider_points_ están actualizados por syncSpriteAndCollider() dentro de move()
animate(delta_time);
border_ = handleBorders();
}
}
// Comprueba las entradas y modifica variables
void Player::handleInput() {
if (ignore_input_) { return; }
if (Input::get()->checkAction(InputAction::LEFT)) {
wanna_go_ = Direction::LEFT;
} else if (Input::get()->checkAction(InputAction::RIGHT)) {
wanna_go_ = Direction::RIGHT;
} else {
wanna_go_ = Direction::NONE;
}
wanna_jump_ = Input::get()->checkAction(InputAction::JUMP);
}
// La lógica de movimiento está distribuida en move
void Player::move(float delta_time) {
switch (state_) {
case State::ON_GROUND:
moveOnGround(delta_time);
break;
case State::ON_SLOPE:
moveOnSlope(delta_time);
break;
case State::JUMPING:
moveJumping(delta_time);
break;
case State::FALLING:
moveFalling(delta_time);
break;
}
syncSpriteAndCollider(); // Actualiza la posición del sprite y las colisiones
#ifdef _DEBUG
Debug::get()->set("P.X", std::to_string(static_cast<int>(x_)));
Debug::get()->set("P.Y", std::to_string(static_cast<int>(y_)));
Debug::get()->set("P.LGP", std::to_string(last_grounded_position_));
switch (state_) {
case State::ON_GROUND:
Debug::get()->set("P.STATE", "ON_GROUND");
break;
case State::ON_SLOPE:
Debug::get()->set("P.STATE", "ON_SLOPE");
break;
case State::JUMPING:
Debug::get()->set("P.STATE", "JUMPING");
break;
case State::FALLING:
Debug::get()->set("P.STATE", "FALLING");
break;
}
#endif
}
void Player::handleConveyorBelts() {
if (!auto_movement_ and isOnConveyorBelt() and wanna_go_ == Direction::NONE) {
auto_movement_ = true;
}
if (auto_movement_ and !isOnConveyorBelt()) {
auto_movement_ = false;
}
}
void Player::handleShouldFall() {
if (!isOnFloor() and (state_ == State::ON_GROUND || state_ == State::ON_SLOPE)) {
transitionToState(State::FALLING);
}
}
void Player::transitionToState(State state) {
previous_state_ = state_;
state_ = state;
switch (state) {
case State::ON_GROUND:
vy_ = 0;
handleDeathByFalling();
resetSoundControllersOnLanding();
current_slope_ = nullptr;
break;
case State::ON_SLOPE:
vy_ = 0;
handleDeathByFalling();
resetSoundControllersOnLanding();
updateCurrentSlope();
if (current_slope_ == nullptr) {
// Los pies no coinciden con ninguna rampa: tratar como suelo plano
state_ = State::ON_GROUND;
}
break;
case State::JUMPING:
// Puede saltar desde ON_GROUND o ON_SLOPE
if (previous_state_ == State::ON_GROUND || previous_state_ == State::ON_SLOPE) {
vy_ = -MAX_VY;
last_grounded_position_ = y_;
updateVelocity();
jump_sound_ctrl_.start();
current_slope_ = nullptr;
}
break;
case State::FALLING:
fall_start_position_ = static_cast<int>(y_);
last_grounded_position_ = static_cast<int>(y_);
vy_ = MAX_VY;
vx_ = 0.0F;
jump_sound_ctrl_.reset();
fall_sound_ctrl_.start(y_);
current_slope_ = nullptr;
break;
}
}
void Player::updateState(float delta_time) {
switch (state_) {
case State::ON_GROUND:
updateOnGround(delta_time);
break;
case State::ON_SLOPE:
updateOnSlope(delta_time);
break;
case State::JUMPING:
updateJumping(delta_time);
break;
case State::FALLING:
updateFalling(delta_time);
break;
}
}
// Actualización lógica del estado ON_GROUND
void Player::updateOnGround(float delta_time) {
(void)delta_time; // No usado en este método, pero se mantiene por consistencia
handleConveyorBelts(); // Gestiona las cintas transportadoras
handleShouldFall(); // Verifica si debe caer (no tiene suelo)
// Verifica si el jugador quiere saltar
if (wanna_jump_) { transitionToState(State::JUMPING); }
}
// Actualización lógica del estado ON_SLOPE
void Player::updateOnSlope(float delta_time) {
(void)delta_time; // No usado en este método, pero se mantiene por consistencia
handleShouldFall();
// NOTA: No llamamos handleShouldFall() aquí porque moveOnSlope() ya maneja
// todas las condiciones de salida de la rampa (out of bounds, transición a superficie plana)
// Verifica si el jugador quiere saltar
if (wanna_jump_) { transitionToState(State::JUMPING); }
}
// Actualización lógica del estado JUMPING
void Player::updateJumping(float delta_time) {
auto_movement_ = false; // Desactiva el movimiento automático durante el salto
playJumpSound(delta_time); // Reproduce los sonidos de salto
handleJumpEnd(); // Verifica si el salto ha terminado (alcanzó la altura inicial)
}
// Actualización lógica del estado FALLING
void Player::updateFalling(float delta_time) {
auto_movement_ = false; // Desactiva el movimiento automático durante la caída
playFallSound(delta_time); // Reproduce los sonidos de caída
}
// Movimiento físico del estado ON_GROUND
void Player::moveOnGround(float delta_time) {
// Determinama cuál debe ser la velocidad a partir de automovement o de wanna_go_
updateVelocity();
if (vx_ == 0.0F) { return; }
// Movimiento horizontal y colision con muros
applyHorizontalMovement(delta_time);
// Comprueba colision con rampas, corrige y cambia estado
const int SIDE_X = vx_ < 0.0F ? static_cast<int>(x_) : static_cast<int>(x_) + WIDTH - 1;
const LineVertical SIDE = {
.x = SIDE_X,
.y1 = static_cast<int>(y_) + HEIGHT - 2,
.y2 = static_cast<int>(y_) + HEIGHT - 1};
// Comprueba la rampa correspondiente según la dirección
const int SLOPE_Y = vx_ < 0.0F ? room_->checkLeftSlopes(SIDE) : room_->checkRightSlopes(SIDE);
if (SLOPE_Y != Collision::NONE) {
// Hay rampa: sube al jugador para pegarlo a la rampa
y_ = SLOPE_Y - HEIGHT;
transitionToState(State::ON_SLOPE);
}
#ifdef _DEBUG
Debug::get()->set("sl.detect_y", SLOPE_Y != Collision::NONE ? std::to_string(SLOPE_Y) : "-");
#endif
// Comprueba si está sobre una rampa
if (isOnSlope()) { transitionToState(State::ON_SLOPE); }
}
// Movimiento físico del estado ON_SLOPE
void Player::moveOnSlope(float delta_time) {
// Determinama cuál debe ser la velocidad a partir de automovement o de wanna_go_
updateVelocity();
// Verificar rampa válida antes de comprobar velocidad: si no hay rampa siempre caer,
// independientemente de si hay o no input (evita bloqueo con vx_=0 y slope null)
if (current_slope_ == nullptr) {
transitionToState(State::FALLING);
return;
}
if (vx_ == 0.0F) { return; }
// Determinar el tipo de rampa
const bool IS_LEFT_SLOPE = isLeftSlope();
// Movimiento horizontal con colisión lateral
applyHorizontalMovement(delta_time);
// Seleccionar el pie apropiado según el tipo de rampa
// Left slopes (forma \) colisionan con el pie izquierdo
// Right slopes (forma /) colisionan con el pie derecho
const int X = IS_LEFT_SLOPE ? x_ : x_ + WIDTH - 1;
// Calcular la Y basada en la ecuación de la rampa (45 grados)
// Left slope (\): y aumenta con x -> y = y1 + (x - x1)
// Right slope (/): y disminuye con x -> y = y1 - (x - x1)
if (IS_LEFT_SLOPE) {
y_ = current_slope_->y1 + (X - current_slope_->x1) - HEIGHT;
} else {
y_ = current_slope_->y1 - (X - current_slope_->x1) - HEIGHT;
}
// Verificar si el pie ha salido de los límites horizontales de la rampa
// Usar min/max porque LEFT slopes tienen x1<x2 pero RIGHT slopes tienen x1>x2
const int MIN_X = std::min(current_slope_->x1, current_slope_->x2);
const int MAX_X = std::max(current_slope_->x1, current_slope_->x2);
const bool OUT_OF_BOUNDS = (X < MIN_X) || (X > MAX_X);
#ifdef _DEBUG
Debug::get()->set("sl.foot", std::to_string(X));
Debug::get()->set("sl.y_c", std::to_string(static_cast<int>(y_)));
Debug::get()->set("sl.oob", OUT_OF_BOUNDS ? "YES" : "ok");
#endif
if (OUT_OF_BOUNDS) {
// Determinar si estamos saliendo por arriba o por abajo de la rampa
const bool EXITING_DOWNWARD = (X > current_slope_->x2 && IS_LEFT_SLOPE) ||
(X < current_slope_->x1 && !IS_LEFT_SLOPE);
const bool EXITING_UPWARD = (X < current_slope_->x1 && IS_LEFT_SLOPE) ||
(X > current_slope_->x2 && !IS_LEFT_SLOPE);
#ifdef _DEBUG
Debug::get()->set("sl.oob", EXITING_DOWNWARD ? "DOWN" : "UP");
#endif
if (EXITING_DOWNWARD) {
// Salida por abajo: no hacer nada
// y_ += 1.0F;
}
if (EXITING_UPWARD) {
// Salida por arriba: bajar un pixel ya que ha subido 1 de mas al salirse de la recta
y_ += 1.0F;
}
// Verificar si hay soporte debajo (suelo plano o conveyor belt)
if (isOnTopSurface() || isOnConveyorBelt()) {
// Hay soporte: transición a ON_GROUND (podría ser superficie o conveyor belt)
transitionToState(State::ON_GROUND);
} else {
// Sin soporte: empezar a caer
transitionToState(State::FALLING);
}
return;
}
// Verificar transición a superficie plana
/*if (isOnTopSurface()) {
transitionToState(State::ON_GROUND);
return;
}*/
}
// Movimiento físico del estado JUMPING
void Player::moveJumping(float delta_time) {
// Movimiento horizontal
applyHorizontalMovement(delta_time);
// Movimiento vertical
applyGravity(delta_time);
const float DISPLACEMENT_Y = vy_ * delta_time;
// Movimiento vertical hacia arriba
if (vy_ < 0.0F) {
const SDL_FRect PROJECTION = getProjection(Direction::UP, DISPLACEMENT_Y);
// Comprueba la colisión
const int POS = room_->checkBottomSurfaces(PROJECTION);
// Calcula la nueva posición
if (POS == Collision::NONE) {
// Si no hay colisión
y_ += DISPLACEMENT_Y;
} else {
// Si hay colisión lo mueve hasta donde no colisiona -> FALLING
y_ = POS + 1;
transitionToState(State::FALLING);
}
}
// Movimiento vertical hacia abajo
else if (vy_ > 0.0F) {
// Crea el rectangulo de proyección en el eje Y para ver si colisiona
const SDL_FRect PROJECTION = getProjection(Direction::DOWN, DISPLACEMENT_Y);
// JUMPING colisiona con rampas solo si vx_ == 0
if (vx_ == 0.0F) {
handleLandingFromAir(DISPLACEMENT_Y, PROJECTION);
} else {
// Comprueba la colisión con las superficies y las cintas transportadoras (sin rampas)
// Extendemos 1px hacia arriba para detectar suelos traversados ligeramente al
// entrar horizontalmente (consecuencia del margen h=HEIGHT-1 en la proyección horizontal)
const SDL_FRect ADJ = {.x = PROJECTION.x, .y = PROJECTION.y - 1.0F, .w = PROJECTION.w, .h = PROJECTION.h + 1.0F};
const float POS = std::max(room_->checkTopSurfaces(ADJ), room_->checkAutoSurfaces(ADJ));
if (POS != Collision::NONE) {
// Si hay colisión lo mueve hasta donde no colisiona y pasa a estar sobre la superficie
y_ = POS - HEIGHT;
transitionToState(State::ON_GROUND);
} else {
// Esta saltando con movimiento horizontal y no hay colisión con los muros
// Calcula la nueva posición (atraviesa rampas)
y_ += DISPLACEMENT_Y;
}
}
}
}
// Movimiento físico del estado FALLING
void Player::moveFalling(float delta_time) {
// Crea el rectangulo de proyección en el eje Y para ver si colisiona
const float DISPLACEMENT = vy_ * delta_time;
const SDL_FRect PROJECTION = getProjection(Direction::DOWN, DISPLACEMENT);
// Comprueba aterrizaje en superficies y rampas
handleLandingFromAir(DISPLACEMENT, PROJECTION);
}
// Comprueba si está situado en alguno de los cuatro bordes de la habitación
auto Player::handleBorders() -> Room::Border {
if (x_ < PlayArea::LEFT) {
return Room::Border::LEFT;
}
if (x_ + WIDTH > PlayArea::RIGHT) {
return Room::Border::RIGHT;
}
if (y_ < PlayArea::TOP) {
return Room::Border::TOP;
}
if (y_ + HEIGHT > PlayArea::BOTTOM) {
// Si llega en estado terminal, muere y no cruza
const bool SHOULD_DIE = static_cast<int>(y_) - last_grounded_position_ > MAX_FALLING_HEIGHT;
if (SHOULD_DIE) { markAsDead(); }
return is_alive_ ? Room::Border::BOTTOM : Room::Border::NONE;
}
return Room::Border::NONE;
}
// Cambia al jugador de un borde al opuesto. Util para el cambio de pantalla
void Player::switchBorders() {
switch (border_) {
case Room::Border::TOP:
y_ = PlayArea::BOTTOM - HEIGHT - Tile::SIZE;
// CRÍTICO: Resetear last_grounded_position_ para evitar muerte falsa por diferencia de Y entre pantallas
last_grounded_position_ = static_cast<int>(y_);
transitionToState(State::ON_GROUND); // TODO: Detectar si debe ser ON_SLOPE
break;
case Room::Border::BOTTOM:
y_ = PlayArea::TOP;
// CRÍTICO: Resetear last_grounded_position_ para evitar muerte falsa por diferencia de Y entre pantallas
last_grounded_position_ = static_cast<int>(y_);
transitionToState(State::ON_GROUND); // TODO: Detectar si debe ser ON_SLOPE
break;
case Room::Border::RIGHT:
x_ = PlayArea::LEFT;
break;
case Room::Border::LEFT:
x_ = PlayArea::RIGHT - WIDTH;
break;
default:
break;
}
border_ = Room::Border::NONE;
syncSpriteAndCollider();
}
// Aplica gravedad al jugador
void Player::applyGravity(float delta_time) {
// La gravedad solo se aplica cuando el jugador esta saltando
// Nunca mientras cae o esta de pie
if (state_ == State::JUMPING) {
vy_ += GRAVITY_FORCE * delta_time;
vy_ = std::min(vy_, MAX_VY);
}
}
// Establece la animación del jugador
void Player::animate(float delta_time) { // NOLINT(readability-make-member-function-const)
if (vx_ != 0) {
sprite_->update(delta_time);
}
}
// Comprueba si ha finalizado el salto al alcanzar la altura de inicio
void Player::handleJumpEnd() {
// Si el jugador vuelve EXACTAMENTE a la altura inicial, debe CONTINUAR en JUMPING
// Solo cuando la SUPERA (desciende más allá) cambia a FALLING
if (state_ == State::JUMPING && vy_ > 0.0F && static_cast<int>(y_) > last_grounded_position_) {
transitionToState(State::FALLING);
}
}
// Calcula y reproduce el sonido de salto basado en tiempo transcurrido
void Player::playJumpSound(float delta_time) { // NOLINT(readability-convert-member-functions-to-static)
size_t sound_index;
if (jump_sound_ctrl_.shouldPlay(delta_time, sound_index)) {
if (sound_index < jumping_sound_.size()) {
Audio::get()->playSound(jumping_sound_[sound_index], Audio::Group::GAME);
}
}
}
// Calcula y reproduce el sonido de caída basado en distancia vertical recorrida
void Player::playFallSound(float delta_time) { // NOLINT(readability-convert-member-functions-to-static)
size_t sound_index;
if (fall_sound_ctrl_.shouldPlay(delta_time, y_, sound_index)) {
if (sound_index < falling_sound_.size()) {
Audio::get()->playSound(falling_sound_[sound_index], Audio::Group::GAME);
}
}
}
// Comprueba si el jugador tiene suelo debajo de los pies
auto Player::isOnFloor() -> bool {
bool on_top_surface = false;
bool on_conveyor_belt = false;
updateFeet();
// Comprueba las superficies
on_top_surface |= room_->checkTopSurfaces(under_left_foot_);
on_top_surface |= room_->checkTopSurfaces(under_right_foot_);
// Comprueba las cintas transportadoras
on_conveyor_belt |= room_->checkConveyorBelts(under_left_foot_);
on_conveyor_belt |= room_->checkConveyorBelts(under_right_foot_);
// Comprueba las rampas
auto on_slope_l = room_->checkLeftSlopes(under_left_foot_);
auto on_slope_r = room_->checkRightSlopes(under_right_foot_);
return on_top_surface || on_conveyor_belt || on_slope_l || on_slope_r;
}
// Comprueba si el jugador está sobre una superficie
auto Player::isOnTopSurface() -> bool {
bool on_top_surface = false;
updateFeet();
// Comprueba las superficies
on_top_surface |= room_->checkTopSurfaces(under_left_foot_);
on_top_surface |= room_->checkTopSurfaces(under_right_foot_);
return on_top_surface;
}
// Comprueba si el jugador esta sobre una cinta transportadora
auto Player::isOnConveyorBelt() -> bool {
bool on_conveyor_belt = false;
updateFeet();
// Comprueba las superficies
on_conveyor_belt |= room_->checkConveyorBelts(under_left_foot_);
on_conveyor_belt |= room_->checkConveyorBelts(under_right_foot_);
return on_conveyor_belt;
}
// Comprueba si el jugador está sobre una rampa
// Retorna true SOLO si un pie está en rampa Y el otro pie está volando (sin soporte)
auto Player::isOnSlope() -> bool {
updateFeet();
// Verificar qué pie está en qué tipo de rampa
const bool LEFT_FOOT_ON_LEFT_SLOPE = room_->checkLeftSlopes(under_left_foot_);
const bool RIGHT_FOOT_ON_RIGHT_SLOPE = room_->checkRightSlopes(under_right_foot_);
// Verificar si cada pie está "volando" (sin soporte: ni top surface ni conveyor belt)
const bool LEFT_FOOT_FLYING = !(room_->checkTopSurfaces(under_left_foot_) ||
room_->checkConveyorBelts(under_left_foot_));
const bool RIGHT_FOOT_FLYING = !(room_->checkTopSurfaces(under_right_foot_) ||
room_->checkConveyorBelts(under_right_foot_));
// Retornar true si UN pie en rampa Y el OTRO volando
return (LEFT_FOOT_ON_LEFT_SLOPE && RIGHT_FOOT_FLYING) ||
(RIGHT_FOOT_ON_RIGHT_SLOPE && LEFT_FOOT_FLYING);
}
// Comprueba si current_slope_ es una rampa izquierda (ascendente a la izquierda)
// Las rampas izquierdas tienen forma \ con x1 < x2 (x aumenta de izq a der)
auto Player::isLeftSlope() -> bool {
if (current_slope_ == nullptr) {
return false;
}
// Left slopes (\): x1 < x2 (x aumenta de izquierda a derecha)
// Right slopes (/): x1 > x2 (x decrece de izquierda a derecha)
return current_slope_->x1 < current_slope_->x2;
}
// Actualiza current_slope_ con la rampa correcta según el pie que toca
void Player::updateCurrentSlope() {
updateFeet();
// Left slopes (\) ascendentes a izquierda tocan el pie izquierdo
if (room_->checkLeftSlopes(under_left_foot_)) {
current_slope_ = room_->getSlopeAtPoint(under_left_foot_);
}
// Right slopes (/) ascendentes a derecha tocan el pie derecho
else if (room_->checkRightSlopes(under_right_foot_)) {
current_slope_ = room_->getSlopeAtPoint(under_right_foot_);
}
// Fallback para casos edge
else {
current_slope_ = room_->getSlopeAtPoint(under_left_foot_);
if (current_slope_ == nullptr) {
current_slope_ = room_->getSlopeAtPoint(under_right_foot_);
}
}
#ifdef _DEBUG
if (current_slope_ != nullptr) {
Debug::get()->set("sl.type", isLeftSlope() ? "L\\" : "R/");
Debug::get()->set("sl.p1", std::to_string(current_slope_->x1) + "," + std::to_string(current_slope_->y1));
Debug::get()->set("sl.p2", std::to_string(current_slope_->x2) + "," + std::to_string(current_slope_->y2));
} else {
Debug::get()->set("sl.type", "null");
Debug::get()->unset("sl.p1");
Debug::get()->unset("sl.p2");
}
#endif
}
// Comprueba que el jugador no toque ningun tile de los que matan
auto Player::handleKillingTiles() -> bool {
// Comprueba si hay contacto con algún tile que mata
if (std::ranges::any_of(collider_points_, [this](const auto& c) -> bool {
return room_->getTile(c) == Room::Tile::KILL;
})) {
markAsDead(); // Mata al jugador inmediatamente
return true; // Retorna en cuanto se detecta una colisión
}
return false; // No se encontró ninguna colisión
}
// Establece el color del jugador (0 = automático según options)
void Player::setColor(Uint8 color) {
if (color != 0) {
color_ = color;
return;
}
// Color personalizado desde opciones
if (Options::game.player_color >= 0) {
color_ = static_cast<Uint8>(Options::game.player_color);
} else {
color_ = static_cast<Uint8>(PaletteColor::WHITE);
}
// Si el color coincide con el fondo de la habitación, usar fallback
if (room_ != nullptr && color_ == room_->getBGColor()) {
color_ = (room_->getBGColor() != static_cast<Uint8>(PaletteColor::WHITE))
? static_cast<Uint8>(PaletteColor::WHITE)
: static_cast<Uint8>(PaletteColor::BRIGHT_BLACK);
}
}
// Actualiza los puntos de colisión
void Player::updateColliderPoints() {
const SDL_FRect RECT = getRect();
collider_points_[0] = {.x = RECT.x, .y = RECT.y};
collider_points_[1] = {.x = RECT.x + 7, .y = RECT.y};
collider_points_[2] = {.x = RECT.x + 7, .y = RECT.y + 7};
collider_points_[3] = {.x = RECT.x, .y = RECT.y + 7};
collider_points_[4] = {.x = RECT.x, .y = RECT.y + 8};
collider_points_[5] = {.x = RECT.x + 7, .y = RECT.y + 8};
collider_points_[6] = {.x = RECT.x + 7, .y = RECT.y + 15};
collider_points_[7] = {.x = RECT.x, .y = RECT.y + 15};
}
// Actualiza los puntos de los pies
void Player::updateFeet() {
under_left_foot_ = {
.x = x_,
.y = y_ + HEIGHT};
under_right_foot_ = {
.x = x_ + WIDTH - 1,
.y = y_ + HEIGHT};
}
// Inicializa los sonidos de salto y caida
void Player::initSounds() { // NOLINT(readability-convert-member-functions-to-static)
for (int i = 0; i < 24; ++i) {
std::string sound_file = "jump" + std::to_string(i + 1) + ".wav";
jumping_sound_[i] = Resource::Cache::get()->getSound(sound_file);
if (i >= 10) { // i+1 >= 11
falling_sound_[i - 10] = Resource::Cache::get()->getSound(sound_file);
}
}
}
// Implementación de JumpSoundController::start
void Player::JumpSoundController::start() {
current_index = 0;
elapsed_time = 0.0F;
active = true;
}
// Implementación de JumpSoundController::reset
void Player::JumpSoundController::reset() {
active = false;
current_index = 0;
elapsed_time = 0.0F;
}
// Implementación de JumpSoundController::shouldPlay
auto Player::JumpSoundController::shouldPlay(float delta_time, size_t& out_index) -> bool {
if (!active) {
return false;
}
// Acumula el tiempo transcurrido durante el salto
elapsed_time += delta_time;
// Calcula qué sonido debería estar sonando según el tiempo
size_t target_index = FIRST_SOUND + static_cast<size_t>((elapsed_time / SECONDS_PER_SOUND));
target_index = std::min(target_index, LAST_SOUND);
// Reproduce si hemos avanzado a un nuevo sonido
if (target_index > current_index) {
current_index = target_index;
out_index = current_index;
return true; // NOLINT(readability-simplify-boolean-expr)
}
return false;
}
// Implementación de FallSoundController::start
void Player::FallSoundController::start(float start_y) {
current_index = 0;
distance_traveled = 0.0F;
last_y = start_y;
active = true;
}
// Implementación de FallSoundController::reset
void Player::FallSoundController::reset() {
active = false;
current_index = 0;
distance_traveled = 0.0F;
}
// Implementación de FallSoundController::shouldPlay
auto Player::FallSoundController::shouldPlay(float delta_time, float current_y, size_t& out_index) -> bool {
(void)delta_time; // No usado actualmente, pero recibido por consistencia
if (!active) {
return false;
}
// Acumula la distancia recorrida (solo hacia abajo)
if (current_y > last_y) {
distance_traveled += (current_y - last_y);
}
last_y = current_y;
// Calcula qué sonido debería estar sonando según el intervalo
size_t target_index = FIRST_SOUND + static_cast<size_t>((distance_traveled / PIXELS_PER_SOUND));
// El sonido a reproducir se limita a LAST_SOUND (13), pero el índice interno sigue creciendo
size_t sound_to_play = std::min(target_index, LAST_SOUND);
// Reproduce si hemos avanzado a un nuevo índice (permite repetición de sonido 13)
if (target_index > current_index) {
current_index = target_index; // Guardamos el índice real (puede ser > LAST_SOUND)
out_index = sound_to_play; // Pero reproducimos LAST_SOUND cuando corresponde
return true;
}
return false;
}
// Aplica los valores de spawn al jugador
void Player::applySpawnValues(const SpawnData& spawn) {
x_ = spawn.x;
y_ = spawn.y;
y_prev_ = spawn.y; // Inicializar y_prev_ igual a y_ para evitar saltos en primer frame
vx_ = spawn.vx;
vy_ = spawn.vy;
last_grounded_position_ = spawn.last_grounded_position;
state_ = spawn.state;
sprite_->setFlip(spawn.flip);
}
// Resuelve nombre de skin a fichero de animación
auto Player::skinToAnimationPath(const std::string& skin_name) -> std::string {
if (skin_name == "default") {
return "player.yaml";
}
return skin_name + ".yaml";
}
// Cambia la skin del jugador en caliente preservando la orientación actual
void Player::setSkin(const std::string& skin_name) {
const auto FLIP = sprite_->getFlip();
initSprite(skinToAnimationPath(skin_name));
sprite_->setFlip(FLIP);
}
// Inicializa el sprite del jugador
void Player::initSprite(const std::string& animations_path) { // NOLINT(readability-convert-member-functions-to-static)
const auto& animation_data = Resource::Cache::get()->getAnimationData(animations_path);
sprite_ = std::make_unique<AnimatedSprite>(animation_data);
sprite_->setWidth(WIDTH);
sprite_->setHeight(HEIGHT);
sprite_->setCurrentAnimation("default");
}
// Actualiza la posición del sprite y las colisiones
void Player::syncSpriteAndCollider() {
placeSprite(); // Coloca el sprite en la posición del jugador
collider_box_ = getRect(); // Actualiza el rectangulo de colisión
updateColliderPoints(); // Actualiza los puntos de colisión
#ifdef _DEBUG
updateFeet();
#endif
}
// Coloca el sprite en la posición del jugador
void Player::placeSprite() {
sprite_->setPos(x_, y_);
}
// Gestiona la muerta al ccaer desde muy alto
void Player::handleDeathByFalling() {
const int FALL_DISTANCE = static_cast<int>(y_) - last_grounded_position_;
if (previous_state_ == State::FALLING && FALL_DISTANCE > MAX_FALLING_HEIGHT) {
markAsDead(); // Muere si cae más de 32 píxeles
}
}
// Calcula la velocidad en x
void Player::updateVelocity() {
if (auto_movement_) {
// La cinta transportadora tiene el control
vx_ = HORIZONTAL_VELOCITY * room_->getConveyorBeltDirection();
sprite_->setFlip(vx_ < 0.0F ? Flip::LEFT : Flip::RIGHT);
} else {
// El jugador tiene el control
switch (wanna_go_) {
case Direction::LEFT:
vx_ = -HORIZONTAL_VELOCITY;
sprite_->setFlip(Flip::LEFT);
break;
case Direction::RIGHT:
vx_ = HORIZONTAL_VELOCITY;
sprite_->setFlip(Flip::RIGHT);
break;
case Direction::NONE:
vx_ = 0.0F;
break;
default:
vx_ = 0.0F;
break;
}
}
}
// Aplica movimiento horizontal con colisión de muros
void Player::applyHorizontalMovement(float delta_time) {
if (vx_ == 0.0F) { return; }
const float DISPLACEMENT = vx_ * delta_time;
if (vx_ < 0.0F) {
const SDL_FRect PROJECTION = getProjection(Direction::LEFT, DISPLACEMENT);
const int POS = room_->checkRightSurfaces(PROJECTION);
if (POS == Collision::NONE) {
x_ += DISPLACEMENT;
} else {
x_ = POS + 1;
}
} else {
const SDL_FRect PROJECTION = getProjection(Direction::RIGHT, DISPLACEMENT);
const int POS = room_->checkLeftSurfaces(PROJECTION);
if (POS == Collision::NONE) {
x_ += DISPLACEMENT;
} else {
x_ = POS - WIDTH;
}
}
}
// Detecta aterrizaje en superficies y rampas
auto Player::handleLandingFromAir(float displacement, const SDL_FRect& projection) -> bool {
// Comprueba la colisión con las superficies y las cintas transportadoras
const float POS = std::max(room_->checkTopSurfaces(projection), room_->checkAutoSurfaces(projection));
if (POS != Collision::NONE) {
// Si hay colisión lo mueve hasta donde no colisiona y pasa a estar sobre la superficie
y_ = POS - HEIGHT;
transitionToState(State::ON_GROUND);
return true;
}
// Comprueba la colisión con las rampas
auto rect = toSDLRect(projection);
const LineVertical LEFT_SIDE = {.x = rect.x, .y1 = rect.y, .y2 = rect.y + rect.h};
const LineVertical RIGHT_SIDE = {.x = rect.x + rect.w - 1, .y1 = rect.y, .y2 = rect.y + rect.h};
const float POINT = std::max(room_->checkRightSlopes(RIGHT_SIDE), room_->checkLeftSlopes(LEFT_SIDE));
if (POINT != Collision::NONE) {
y_ = POINT - HEIGHT;
transitionToState(State::ON_SLOPE);
return true;
}
// No hay colisión
y_ += displacement;
#ifdef _DEBUG
// Guarda por si en debug el jugador se sale de la pantalla, para que no esté cayendo infinitamente
if (y_ > PlayArea::BOTTOM + HEIGHT) { y_ = PlayArea::TOP + 2; }
#endif
return false;
}
// Resetea los controladores de sonido al aterrizar
void Player::resetSoundControllersOnLanding() {
jump_sound_ctrl_.reset();
fall_sound_ctrl_.reset();
}
// Devuelve el rectangulo de proyeccion
auto Player::getProjection(Direction direction, float displacement) -> SDL_FRect { // NOLINT(readability-convert-member-functions-to-static)
switch (direction) {
case Direction::LEFT:
return {
.x = x_ + displacement,
.y = y_,
.w = std::ceil(std::fabs(displacement)), // Para evitar que tenga una anchura de 0 pixels
.h = HEIGHT - 1}; // -1 para dar ventana de 2px en aperturas de altura exacta
case Direction::RIGHT:
return {
.x = x_ + WIDTH,
.y = y_,
.w = std::ceil(displacement), // Para evitar que tenga una anchura de 0 pixels
.h = HEIGHT - 1}; // -1 para dar ventana de 2px en aperturas de altura exacta
case Direction::UP:
return {
.x = x_,
.y = y_ + displacement,
.w = WIDTH,
.h = std::ceil(std::fabs(displacement)) // Para evitar que tenga una altura de 0 pixels
};
case Direction::DOWN:
return {
.x = x_,
.y = y_ + HEIGHT,
.w = WIDTH,
.h = std::ceil(displacement) // Para evitar que tenga una altura de 0 pixels
};
default:
return {
.x = 0.0F,
.y = 0.0F,
.w = 0.0F,
.h = 0.0F};
}
}
// Marca al jugador como muerto
void Player::markAsDead() {
is_alive_ = (Options::cheats.invincible == Options::Cheat::State::ENABLED);
}
#ifdef _DEBUG
// Establece la posición del jugador directamente (debug)
void Player::setDebugPosition(float x, float y) {
x_ = x;
y_ = y;
syncSpriteAndCollider();
}
// Fija estado ON_GROUND, velocidades a 0, actualiza last_grounded_position_ (debug)
void Player::finalizeDebugTeleport() {
vx_ = 0.0F;
vy_ = 0.0F;
last_grounded_position_ = static_cast<int>(y_);
transitionToState(State::ON_GROUND);
syncSpriteAndCollider();
}
#endif

View File

@@ -0,0 +1,226 @@
#pragma once
#include <SDL3/SDL.h>
#include <array> // Para array
#include <limits> // Para numeric_limits
#include <memory> // Para shared_ptr, __shared_ptr_access
#include <string> // Para string
#include <utility>
#include "core/rendering/sprite/animated_sprite.hpp" // Para SAnimatedSprite
#include "game/gameplay/room.hpp"
#include "game/options.hpp" // Para Cheat, Options, options
#include "utils/defines.hpp" // Para BORDER_TOP, BLOCK
#include "utils/utils.hpp" // Para Color
struct JA_Sound_t; // lines 13-13
class Player {
public:
// --- Enums y Structs ---
enum class State {
ON_GROUND, // En suelo plano o conveyor belt
ON_SLOPE, // En rampa/pendiente
JUMPING,
FALLING,
};
enum class Direction {
LEFT,
RIGHT,
UP,
DOWN,
NONE
};
// --- Constantes de física (públicas para permitir cálculos en structs) ---
static constexpr float HORIZONTAL_VELOCITY = 40.0F; // Velocidad horizontal en pixels/segundo (0.6 * 66.67fps)
static constexpr float MAX_VY = 80.0F; // Velocidad vertical máxima en pixels/segundo (1.2 * 66.67fps)
static constexpr float JUMP_VELOCITY = -80.0F; // Velocidad inicial del salto en pixels/segundo
static constexpr float GRAVITY_FORCE = 155.6F; // Fuerza de gravedad en pixels/segundo² (0.035 * 66.67²)
struct SpawnData {
float x = 0;
float y = 0;
float vx = 0;
float vy = 0;
int last_grounded_position = 0;
State state = State::ON_GROUND;
SDL_FlipMode flip = SDL_FLIP_NONE;
};
struct Data {
SpawnData spawn_data;
std::string animations_path;
std::shared_ptr<Room> room = nullptr;
};
struct JumpSoundController {
// Duración del salto calculada automáticamente con física: t = 2 * v0 / g
static constexpr float JUMP_DURATION = (2.0F * MAX_VY) / GRAVITY_FORCE;
static constexpr size_t FIRST_SOUND = 1; // Primer sonido a reproducir (índice 1)
static constexpr size_t LAST_SOUND = 17; // Último sonido a reproducir (índice 17)
static constexpr float SECONDS_PER_SOUND = JUMP_DURATION / (LAST_SOUND - FIRST_SOUND + 1);
size_t current_index = 0; // Índice del sonido actual
float elapsed_time = 0.0F; // Tiempo transcurrido durante el salto
bool active = false; // Indica si el controlador está activo
void start(); // Inicia el controlador
void reset(); // Resetea el controlador
auto shouldPlay(float delta_time, size_t& out_index) -> bool; // Comprueba si debe reproducir un sonido
};
struct FallSoundController {
static constexpr float PIXELS_PER_SOUND = 5.0F; // Intervalo de píxeles por sonido (configurable)
static constexpr size_t FIRST_SOUND = 1; // Primer sonido a reproducir (índice 1)
static constexpr size_t LAST_SOUND = 13; // Último sonido a reproducir (índice 13)
size_t current_index = 0; // Índice del sonido actual
float distance_traveled = 0.0F; // Distancia acumulada durante la caída
float last_y = 0.0F; // Última posición Y registrada
bool active = false; // Indica si el controlador está activo
void start(float start_y); // Inicia el controlador
void reset(); // Resetea el controlador
auto shouldPlay(float delta_time, float current_y, size_t& out_index) -> bool; // Comprueba si debe reproducir un sonido
};
// --- Constructor y Destructor ---
explicit Player(const Data& player);
~Player() = default;
// --- Funciones ---
void render(); // Pinta el enemigo en pantalla
void update(float delta_time); // Actualiza las variables del objeto
[[nodiscard]] auto isOnBorder() const -> bool { return border_ != Room::Border::NONE; } // Indica si el jugador esta en uno de los cuatro bordes de la pantalla
[[nodiscard]] auto getBorder() const -> Room::Border { return border_; } // Indica en cual de los cuatro bordes se encuentra
void switchBorders(); // Cambia al jugador de un borde al opuesto. Util para el cambio de pantalla
auto getRect() -> SDL_FRect { return {.x = x_, .y = y_, .w = WIDTH, .h = HEIGHT}; } // Obtiene el rectangulo que delimita al jugador
auto getCollider() -> SDL_FRect& { return collider_box_; } // Obtiene el rectangulo de colision del jugador
auto getSpawnParams() -> SpawnData { return {.x = x_, .y = y_, .vx = vx_, .vy = vy_, .last_grounded_position = last_grounded_position_, .state = state_, .flip = sprite_->getFlip()}; } // Obtiene el estado de reaparición del jugador
void setColor(Uint8 color = 0); // Establece el color del jugador (0 = automático según cheats)
void setSkin(const std::string& skin_name); // Cambia la skin del jugador en caliente ("default" o nombre de enemigo)
static auto skinToAnimationPath(const std::string& skin_name) -> std::string; // Resuelve nombre de skin a fichero de animación
void setRoom(std::shared_ptr<Room> room) { room_ = std::move(room); } // Establece la habitación en la que se encuentra el jugador
//[[nodiscard]] auto isAlive() const -> bool { return is_alive_ || (Options::cheats.invincible == Options::Cheat::State::ENABLED); } // Comprueba si el jugador esta vivo
[[nodiscard]] auto isAlive() const -> bool { return is_alive_; } // Comprueba si el jugador esta vivo
void setPaused(bool value) { is_paused_ = value; } // Pone el jugador en modo pausa
void setIgnoreInput(bool value) { ignore_input_ = value; } // Ignora inputs del jugador (física sigue activa)
[[nodiscard]] auto getIgnoreInput() const -> bool { return ignore_input_; }
#ifdef _DEBUG
// --- Funciones de debug ---
void setDebugPosition(float x, float y); // Establece la posición del jugador directamente (debug)
void finalizeDebugTeleport(); // Fija estado ON_GROUND, velocidades a 0, actualiza last_grounded_position_ (debug)
#endif
private:
// --- Constantes ---
static constexpr int WIDTH = 8; // Ancho del jugador
static constexpr int HEIGHT = 16; // ALto del jugador
static constexpr int MAX_FALLING_HEIGHT = Tile::SIZE * 4; // Altura maxima permitida de caída en pixels
// --- Objetos y punteros ---
std::shared_ptr<Room> room_; // Objeto encargado de gestionar cada habitación del juego
std::unique_ptr<AnimatedSprite> sprite_; // Sprite del jugador
// --- Variables de posición y física ---
float x_ = 0.0F; // Posición del jugador en el eje X
float y_ = 0.0F; // Posición del jugador en el eje Y
float y_prev_ = 0.0F; // Posición Y del frame anterior (para detectar hitos de distancia en sonidos)
float vx_ = 0.0F; // Velocidad/desplazamiento del jugador en el eje X
float vy_ = 0.0F; // Velocidad/desplazamiento del jugador en el eje Y
Direction wanna_go_ = Direction::NONE;
bool wanna_jump_ = false;
// --- Variables de estado ---
State state_ = State::ON_GROUND; // Estado en el que se encuentra el jugador. Util apara saber si está saltando o cayendo
State previous_state_ = State::ON_GROUND; // Estado previo en el que se encontraba el jugador
// --- Variables de colisión ---
SDL_FRect collider_box_{}; // Caja de colisión con los enemigos u objetos
std::array<SDL_FPoint, 8> collider_points_{}; // Puntos de colisión con el mapa
SDL_FPoint under_left_foot_ = {.x = 0.0F, .y = 0.0F}; // El punto bajo la esquina inferior izquierda del jugador
SDL_FPoint under_right_foot_ = {.x = 0.0F, .y = 0.0F}; // El punto bajo la esquina inferior derecha del jugador
const LineDiagonal* current_slope_{nullptr}; // Rampa actual sobe la que está el jugador
// --- Variables de juego ---
bool is_alive_ = true; // Indica si el jugador esta vivo o no
bool is_paused_ = false; // Indica si el jugador esta en modo pausa
bool ignore_input_ = false; // Ignora inputs pero mantiene la física activa
bool auto_movement_ = false; // Indica si esta siendo arrastrado por una superficie automatica
Room::Border border_ = Room::Border::TOP; // Indica en cual de los cuatro bordes se encuentra
int last_grounded_position_ = 0; // Ultima posición en Y en la que se estaba en contacto con el suelo (hace doble función: tracking de caída + altura inicial del salto)
// --- Variables de renderizado y sonido ---
Uint8 color_ = 0; // Color del jugador
std::array<JA_Sound_t*, 24> jumping_sound_{}; // Array con todos los sonidos del salto
std::array<JA_Sound_t*, 14> falling_sound_{}; // Array con todos los sonidos de la caída
JumpSoundController jump_sound_ctrl_; // Controlador de sonidos de salto
FallSoundController fall_sound_ctrl_; // Controlador de sonidos de caída
int fall_start_position_ = 0; // Posición Y al iniciar la caída
void handleConveyorBelts();
void handleShouldFall();
void updateState(float delta_time);
// --- Métodos de actualización por estado ---
void updateOnGround(float delta_time); // Actualización lógica estado ON_GROUND
void updateOnSlope(float delta_time); // Actualización lógica estado ON_SLOPE
void updateJumping(float delta_time); // Actualización lógica estado JUMPING
void updateFalling(float delta_time); // Actualización lógica estado FALLING
// --- Métodos de movimiento por estado ---
void moveOnGround(float delta_time); // Movimiento físico estado ON_GROUND
void moveOnSlope(float delta_time); // Movimiento físico estado ON_SLOPE
void moveJumping(float delta_time); // Movimiento físico estado JUMPING
void moveFalling(float delta_time); // Movimiento físico estado FALLING
// --- Funciones de inicialización ---
void initSprite(const std::string& animations_path); // Inicializa el sprite del jugador
void initSounds(); // Inicializa los sonidos de salto y caida
void applySpawnValues(const SpawnData& spawn); // Aplica los valores de spawn al jugador
// --- Funciones de procesamiento de entrada ---
void handleInput(); // Comprueba las entradas y modifica variables
// --- Funciones de gestión de estado ---
void transitionToState(State state); // Cambia el estado del jugador
// --- Funciones de física ---
void applyGravity(float delta_time); // Aplica gravedad al jugador
// --- Funciones de movimiento y colisión ---
void move(float delta_time); // Orquesta el movimiento del jugador
auto getProjection(Direction direction, float displacement) -> SDL_FRect; // Devuelve el rectangulo de proyeccion
void applyHorizontalMovement(float delta_time); // Aplica movimiento horizontal con colisión de muros
auto handleLandingFromAir(float displacement, const SDL_FRect& projection) -> bool; // Detecta aterrizaje en superficies y rampas
void resetSoundControllersOnLanding(); // Resetea los controladores de sonido al aterrizar
// --- Funciones de detección de superficies ---
auto isOnFloor() -> bool; // Comprueba si el jugador tiene suelo debajo de los pies
auto isOnTopSurface() -> bool; // Comprueba si el jugador está sobre una superficie
auto isOnConveyorBelt() -> bool; // Comprueba si el jugador esta sobre una cinta transportadora
auto isOnSlope() -> bool; // Comprueba si el jugador está sobre una rampa
auto isLeftSlope() -> bool; // Comprueba si current_slope_ es una rampa izquierda (ascendente a la izquierda)
void updateCurrentSlope(); // Actualiza current_slope_ con la rampa correcta y muestra debug info
// --- Funciones de actualización de geometría ---
void syncSpriteAndCollider(); // Actualiza collider_box y collision points
void updateColliderPoints(); // Actualiza los puntos de colisión
void updateFeet(); // Actualiza los puntos de los pies
void placeSprite(); // Coloca el sprite en la posición del jugador
// --- Funciones de finalización ---
void animate(float delta_time); // Establece la animación del jugador
auto handleBorders() -> Room::Border; // Comprueba si se halla en alguno de los cuatro bordes
void handleJumpEnd(); // Comprueba si ha finalizado el salto al alcanzar la altura de inicio
auto handleKillingTiles() -> bool; // Comprueba que el jugador no toque ningun tile de los que matan
void playJumpSound(float delta_time); // Calcula y reproduce el sonido de salto
void playFallSound(float delta_time); // Calcula y reproduce el sonido de caer
void handleDeathByFalling(); // Gestiona la muerte al caer desde muy alto
void updateVelocity(); // Calcula la velocidad en x
void markAsDead(); // Marca al jugador como muerto
};