creada carpeta source2

This commit is contained in:
2025-10-26 12:31:49 +01:00
parent 545d471654
commit 9676e5bc2f
85 changed files with 30192 additions and 0 deletions

View File

@@ -0,0 +1,97 @@
#include "enemy.h"
#include <SDL3/SDL.h>
#include <stdlib.h> // Para rand
#include "resource.h" // Para Resource
#include "sprite/surface_animated_sprite.h" // Para SAnimatedSprite
#include "utils.h" // Para stringToColor
// Constructor
Enemy::Enemy(const EnemyData& enemy)
: sprite_(std::make_shared<SAnimatedSprite>(Resource::get()->getSurface(enemy.surface_path), Resource::get()->getAnimations(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);
sprite_->setWidth(enemy.w);
sprite_->setHeight(enemy.h);
const SDL_FlipMode FLIP = (should_flip_ && enemy.vx < 0.0f) ? SDL_FLIP_HORIZONTAL : SDL_FLIP_NONE;
const SDL_FlipMode MIRROR = should_mirror_ ? SDL_FLIP_VERTICAL : SDL_FLIP_NONE;
sprite_->setFlip(static_cast<SDL_FlipMode>(FLIP | MIRROR));
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() {
sprite_->update();
checkPath();
collider_ = getRect();
}
// Comprueba si ha llegado al limite del recorrido para darse media vuelta
void Enemy::checkPath() {
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
SDL_FRect Enemy::getRect() {
return sprite_->getRect();
}
// Obtiene el rectangulo de colision del enemigo
SDL_FRect& Enemy::getCollider() {
return collider_;
}

View File

@@ -0,0 +1,66 @@
#pragma once
#include <SDL3/SDL.h>
#include <memory> // Para shared_ptr
#include <string> // Para string
class SAnimatedSprite; // lines 7-7
// Estructura para pasar los datos de un enemigo
struct EnemyData {
std::string surface_path; // Ruta al fichero con la textura
std::string animation_path; // Ruta al fichero con la animación
int w; // Anchura del enemigo
int h; // Altura del enemigo
float x; // Posición inicial en el eje X
float y; // Posición inicial en el eje Y
float vx; // Velocidad en el eje X
float vy; // Velocidad en el eje Y
int x1; // Limite izquierdo de la ruta en el eje X
int x2; // Limite derecho de la ruta en el eje X
int y1; // Limite superior de la ruta en el eje Y
int y2; // Limite inferior de la ruta en el eje Y
bool flip; // Indica si el enemigo hace flip al terminar su ruta
bool mirror; // Indica si el enemigo está volteado verticalmente
int frame; // Frame inicial para la animación del enemigo
std::string color; // Color del enemigo
};
class Enemy {
private:
// Objetos y punteros
std::shared_ptr<SAnimatedSprite> sprite_; // Sprite del enemigo
// Variables
Uint8 color_; // Color del enemigo
std::string color_string_; // Color del enemigo en formato texto
int x1_; // Limite izquierdo de la ruta en el eje X
int x2_; // Limite derecho de la ruta en el eje X
int y1_; // Limite superior de la ruta en el eje Y
int y2_; // Limite inferior de la ruta en el eje Y
SDL_FRect collider_; // Caja de colisión
bool should_flip_; // Indica si el enemigo hace flip al terminar su ruta
bool should_mirror_; // Indica si el enemigo se dibuja volteado verticalmente
// Comprueba si ha llegado al limite del recorrido para darse media vuelta
void checkPath();
public:
// Constructor
explicit Enemy(const EnemyData& enemy);
// Destructor
~Enemy() = default;
// Pinta el enemigo en pantalla
void render();
// Actualiza las variables del objeto
void update();
// Devuelve el rectangulo que contiene al enemigo
SDL_FRect getRect();
// Obtiene el rectangulo de colision del enemigo
SDL_FRect& getCollider();
};

View File

@@ -0,0 +1,47 @@
#include "item.h"
#include "resource.h" // Para Resource
#include "sprite/surface_sprite.h" // Para SSprite
// Constructor
Item::Item(ItemData item)
: sprite_(std::make_shared<SSprite>(Resource::get()->getSurface(item.tile_set_file), item.x, item.y, ITEM_SIZE_, ITEM_SIZE_)),
change_color_speed(4) {
// Inicia variables
sprite_->setClip((item.tile % 10) * ITEM_SIZE_, (item.tile / 10) * ITEM_SIZE_, ITEM_SIZE_, ITEM_SIZE_);
collider_ = sprite_->getRect();
counter_ = item.counter * change_color_speed;
// Inicializa los colores
color_.push_back(item.color1);
color_.push_back(item.color1);
color_.push_back(item.color2);
color_.push_back(item.color2);
}
// Pinta el objeto en pantalla
void Item::render() {
const int INDEX = (counter_ / change_color_speed) % color_.size();
sprite_->render(1, color_.at(INDEX));
}
// Obtiene su ubicación
SDL_FPoint Item::getPos() {
const SDL_FPoint p = {sprite_->getX(), sprite_->getY()};
return p;
}
// 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,64 @@
#pragma once
#include <SDL3/SDL.h>
#include <memory> // Para shared_ptr
#include <string> // Para string
#include <vector> // Para vector
class SSprite;
struct ItemData {
std::string tile_set_file; // Ruta al fichero con los gráficos del item
float x; // Posición del item en pantalla
float y; // Posición del item en pantalla
int tile; // Número de tile dentro de la textura
int counter; // Contador inicial. Es el que lo hace cambiar de color
Uint8 color1; // Uno de los dos colores que se utiliza para el item
Uint8 color2; // Uno de los dos colores que se utiliza para el item
// Constructor
ItemData()
: x(0),
y(0),
tile(0),
counter(0),
color1(),
color2() {}
};
class Item {
private:
// Constantes
static constexpr float ITEM_SIZE_ = 8;
// Objetos y punteros
std::shared_ptr<SSprite> sprite_; // SSprite del objeto
// Variables
std::vector<Uint8> color_; // Vector con los colores del objeto
int counter_; // Contador interno
SDL_FRect collider_; // Rectangulo de colisión
int change_color_speed; // Cuanto mas alto, mas tarda en cambiar de color
public:
// Constructor
explicit Item(ItemData item);
// Destructor
~Item() = default;
// Pinta el objeto en pantalla
void render();
// Actualiza las variables del objeto
void update() { counter_++; }
// Obtiene el rectangulo de colision del objeto
SDL_FRect& getCollider() { return collider_; }
// Obtiene su ubicación
SDL_FPoint getPos();
// Asigna los colores del objeto
void setColors(Uint8 col1, Uint8 col2);
};

View File

@@ -0,0 +1,656 @@
// IWYU pragma: no_include <bits/std_abs.h>
#include "player.h"
#include <algorithm> // Para max, min
#include <cmath> // Para ceil, abs
#include "debug.h" // Para Debug
#include "defines.h" // Para RoomBorder::BOTTOM, RoomBorder::LEFT, RoomBorder::RIGHT
#include "external/jail_audio.h" // Para JA_PlaySound
#include "input.h" // Para Input, InputAction
#include "options.h" // Para Cheat, Options, options
#include "resource.h" // Para Resource
#include "room.h" // Para Room, TileType
#include "sprite/surface_animated_sprite.h" // Para SAnimatedSprite
// Constructor
Player::Player(const PlayerData& player)
: room_(player.room) {
// Inicializa algunas variables
initSprite(player.texture_path, player.animations_path);
setColor();
applySpawnValues(player.spawn);
placeSprite();
initSounds();
previous_state_ = state_;
last_position_ = getRect();
collider_box_ = getRect();
collider_points_.resize(collider_points_.size() + 8, {0, 0});
under_feet_.resize(under_feet_.size() + 2, {0, 0});
feet_.resize(feet_.size() + 2, {0, 0});
#ifdef DEBUG
debug_rect_x_ = {0, 0, 0, 0};
debug_rect_y_ = {0, 0, 0, 0};
debug_color_ = static_cast<Uint8>(PaletteColor::GREEN);
debug_point_ = {0, 0};
#endif
}
// Pinta el jugador en pantalla
void Player::render() {
sprite_->render(1, color_);
#ifdef DEBUG
renderDebugInfo();
#endif
}
// Actualiza las variables del objeto
void Player::update() {
if (!is_paused_) {
checkInput(); // Comprueba las entradas y modifica variables
move(); // Recalcula la posición del jugador
animate(); // Establece la animación del jugador
checkBorders(); // Comprueba si está situado en alguno de los cuatro bordes de la habitación
checkJumpEnd(); // Comprueba si ha finalizado el salto al alcanzar la altura de inicio
checkKillingTiles(); // Comprueba que el jugador no toque ningun tile de los que matan}
}
}
// Comprueba las entradas y modifica variables
void Player::checkInput() {
// Solo comprueba las entradas de dirección cuando está sobre una superficie
if (state_ != PlayerState::STANDING) {
return;
}
if (!auto_movement_) {
// Comprueba las entradas de desplazamiento lateral solo en el caso de no estar enganchado a una superficie automatica
if (Input::get()->checkInput(InputAction::LEFT)) {
vx_ = -0.6f;
sprite_->setFlip(SDL_FLIP_HORIZONTAL);
}
else if (Input::get()->checkInput(InputAction::RIGHT)) {
vx_ = 0.6f;
sprite_->setFlip(SDL_FLIP_NONE);
}
else {
// No se pulsa ninguna dirección
vx_ = 0.0f;
if (isOnAutoSurface()) {
// Si deja de moverse sobre una superficie se engancha
auto_movement_ = true;
}
}
} else { // El movimiento lo proporciona la superficie
vx_ = 0.6f * room_->getAutoSurfaceDirection();
if (vx_ > 0.0f) {
sprite_->setFlip(SDL_FLIP_NONE);
} else {
sprite_->setFlip(SDL_FLIP_HORIZONTAL);
}
}
if (Input::get()->checkInput(InputAction::JUMP)) {
// Solo puede saltar si ademas de estar (state == s_standing)
// Esta sobre el suelo, rampa o suelo que se mueve
// Esto es para evitar el salto desde el vacio al cambiar de pantalla verticalmente
// Ya que se coloca el estado s_standing al cambiar de pantalla
if (isOnFloor() || isOnAutoSurface()) {
setState(PlayerState::JUMPING);
vy_ = -MAX_VY_;
jump_init_pos_ = y_;
jumping_counter_ = 0;
}
}
}
// Comprueba si está situado en alguno de los cuatro bordes de la habitación
void Player::checkBorders() {
if (x_ < PLAY_AREA_LEFT) {
border_ = RoomBorder::LEFT;
is_on_border_ = true;
}
else if (x_ + WIDTH_ > PLAY_AREA_RIGHT) {
border_ = RoomBorder::RIGHT;
is_on_border_ = true;
}
else if (y_ < PLAY_AREA_TOP) {
border_ = RoomBorder::TOP;
is_on_border_ = true;
}
else if (y_ + HEIGHT_ > PLAY_AREA_BOTTOM) {
border_ = RoomBorder::BOTTOM;
is_on_border_ = true;
}
else {
is_on_border_ = false;
}
}
// Comprueba el estado del jugador
void Player::checkState() {
// Actualiza las variables en función del estado
if (state_ == PlayerState::FALLING) {
vx_ = 0.0f;
vy_ = MAX_VY_;
falling_counter_++;
playFallSound();
}
else if (state_ == PlayerState::STANDING) {
if (previous_state_ == PlayerState::FALLING && falling_counter_ > MAX_FALLING_HEIGHT_) { // Si cae de muy alto, el jugador muere
is_alive_ = false;
}
vy_ = 0.0f;
jumping_counter_ = 0;
falling_counter_ = 0;
if (!isOnFloor() && !isOnAutoSurface() && !isOnDownSlope()) {
setState(PlayerState::FALLING);
vx_ = 0.0f;
vy_ = MAX_VY_;
falling_counter_++;
playFallSound();
}
}
else if (state_ == PlayerState::JUMPING) {
falling_counter_ = 0;
jumping_counter_++;
playJumpSound();
}
}
// Cambia al jugador de un borde al opuesto. Util para el cambio de pantalla
void Player::switchBorders() {
switch (border_) {
case RoomBorder::TOP:
y_ = PLAY_AREA_BOTTOM - HEIGHT_ - BLOCK;
setState(PlayerState::STANDING);
break;
case RoomBorder::BOTTOM:
y_ = PLAY_AREA_TOP;
setState(PlayerState::STANDING);
break;
case RoomBorder::RIGHT:
x_ = PLAY_AREA_LEFT;
break;
case RoomBorder::LEFT:
x_ = PLAY_AREA_RIGHT - WIDTH_;
break;
default:
break;
}
is_on_border_ = false;
placeSprite();
collider_box_ = getRect();
}
// Aplica gravedad al jugador
void Player::applyGravity() {
constexpr float GRAVITY_FORCE = 0.035f;
// La gravedad solo se aplica cuando el jugador esta saltando
// Nunca mientras cae o esta de pie
if (state_ == PlayerState::JUMPING) {
vy_ += GRAVITY_FORCE;
if (vy_ > MAX_VY_) {
vy_ = MAX_VY_;
}
}
}
// Recalcula la posición del jugador y su animación
void Player::move() {
last_position_ = {x_, y_}; // Guarda la posicion actual antes de modificarla
applyGravity(); // Aplica gravedad al jugador
checkState(); // Comprueba el estado del jugador
#ifdef DEBUG
debug_color_ = static_cast<Uint8>(PaletteColor::GREEN);
#endif
// Se mueve hacia la izquierda
if (vx_ < 0.0f) {
// Crea el rectangulo de proyección en el eje X para ver si colisiona
SDL_FRect proj;
proj.x = static_cast<int>(x_ + vx_);
proj.y = static_cast<int>(y_);
proj.h = HEIGHT_;
proj.w = static_cast<int>(std::ceil(std::fabs(vx_))); // Para evitar que tenga un ancho de 0 pixels
#ifdef DEBUG
debug_rect_x_ = proj;
#endif
// Comprueba la colisión con las superficies
const int POS = room_->checkRightSurfaces(&proj);
// Calcula la nueva posición
if (POS == -1) {
// Si no hay colisión
x_ += vx_;
} else {
// Si hay colisión lo mueve hasta donde no colisiona
x_ = POS + 1;
}
// Si ha tocado alguna rampa mientras camina (sin saltar), asciende
if (state_ != PlayerState::JUMPING) {
const LineVertical LEFT_SIDE = {static_cast<int>(x_), static_cast<int>(y_) + static_cast<int>(HEIGHT_) - 2, static_cast<int>(y_) + static_cast<int>(HEIGHT_) - 1}; // Comprueba solo los dos pixels de abajo
const int LY = room_->checkLeftSlopes(&LEFT_SIDE);
if (LY > -1) {
y_ = LY - HEIGHT_;
}
}
// Si está bajando la rampa, recoloca al jugador
if (isOnDownSlope() && state_ != PlayerState::JUMPING) {
y_ += 1;
}
}
// Se mueve hacia la derecha
else if (vx_ > 0.0f) {
// Crea el rectangulo de proyección en el eje X para ver si colisiona
SDL_FRect proj;
proj.x = x_ + WIDTH_;
proj.y = y_;
proj.h = HEIGHT_;
proj.w = ceil(vx_); // Para evitar que tenga un ancho de 0 pixels
#ifdef DEBUG
debug_rect_x_ = proj;
#endif
// Comprueba la colisión
const int POS = room_->checkLeftSurfaces(&proj);
// Calcula la nueva posición
if (POS == -1) {
// Si no hay colisión
x_ += vx_;
} else {
// Si hay colisión lo mueve hasta donde no colisiona
x_ = POS - WIDTH_;
}
// Si ha tocado alguna rampa mientras camina (sin saltar), asciende
if (state_ != PlayerState::JUMPING) {
const LineVertical RIGHT_SIDE = {static_cast<int>(x_) + static_cast<int>(WIDTH_) - 1, static_cast<int>(y_) + static_cast<int>(HEIGHT_) - 2, static_cast<int>(y_) + static_cast<int>(HEIGHT_) - 1}; // Comprueba solo los dos pixels de abajo
const int RY = room_->checkRightSlopes(&RIGHT_SIDE);
if (RY > -1) {
y_ = RY - HEIGHT_;
}
}
// Si está bajando la rampa, recoloca al jugador
if (isOnDownSlope() && state_ != PlayerState::JUMPING) {
y_ += 1;
}
}
// Si ha salido del suelo, el jugador cae
if (state_ == PlayerState::STANDING && !isOnFloor()) {
setState(PlayerState::FALLING);
// Deja de estar enganchado a la superficie automatica
auto_movement_ = false;
}
// Si ha salido de una superficie automatica, detiene el movimiento automatico
if (state_ == PlayerState::STANDING && isOnFloor() && !isOnAutoSurface()) {
// Deja de estar enganchado a la superficie automatica
auto_movement_ = false;
}
// Se mueve hacia arriba
if (vy_ < 0.0f) {
// Crea el rectangulo de proyección en el eje Y para ver si colisiona
SDL_FRect proj;
proj.x = static_cast<int>(x_);
proj.y = static_cast<int>(y_ + vy_);
proj.h = static_cast<int>(std::ceil(std::fabs(vy_))); // Para evitar que tenga una altura de 0 pixels
proj.w = WIDTH_;
#ifdef DEBUG
debug_rect_y_ = proj;
#endif
// Comprueba la colisión
const int POS = room_->checkBottomSurfaces(&proj);
// Calcula la nueva posición
if (POS == -1) {
// Si no hay colisión
y_ += vy_;
} else {
// Si hay colisión lo mueve hasta donde no colisiona y entra en caída
y_ = POS + 1;
setState(PlayerState::FALLING);
}
}
// Se mueve hacia abajo
else if (vy_ > 0.0f) {
// Crea el rectangulo de proyección en el eje Y para ver si colisiona
SDL_FRect proj;
proj.x = x_;
proj.y = y_ + HEIGHT_;
proj.h = ceil(vy_); // Para evitar que tenga una altura de 0 pixels
proj.w = WIDTH_;
#ifdef DEBUG
debug_rect_y_ = proj;
#endif
// Comprueba la colisión con las superficies normales y las automáticas
const float POS = std::max(room_->checkTopSurfaces(&proj), room_->checkAutoSurfaces(&proj));
if (POS > -1) {
// Si hay colisión lo mueve hasta donde no colisiona y pasa a estar sobre la superficie
y_ = POS - HEIGHT_;
setState(PlayerState::STANDING);
// Deja de estar enganchado a la superficie automatica
auto_movement_ = false;
} else {
// Si no hay colisión con los muros, comprueba la colisión con las rampas
if (state_ != PlayerState::JUMPING) { // Las rampas no se miran si se está saltando
auto rect = toSDLRect(proj);
const LineVertical LEFT_SIDE = {rect.x, rect.y, rect.y + rect.h - 1};
const LineVertical RIGHT_SIDE = {rect.x + rect.w - 1, rect.y, rect.y + rect.h - 1};
const float POINT = std::max(room_->checkRightSlopes(&RIGHT_SIDE), room_->checkLeftSlopes(&LEFT_SIDE));
if (POINT > -1) {
// No está saltando y hay colisión con una rampa
// Calcula la nueva posición
y_ = POINT - HEIGHT_;
setState(PlayerState::STANDING);
#ifdef DEBUG
debug_color_ = static_cast<Uint8>(PaletteColor::YELLOW);
debug_point_ = {x_ + (WIDTH_ / 2), POINT};
#endif
} else {
// No está saltando y no hay colisón con una rampa
// Calcula la nueva posición
y_ += vy_;
#ifdef DEBUG
debug_color_ = static_cast<Uint8>(PaletteColor::RED);
#endif
}
} else {
// Esta saltando y no hay colisión con los muros
// Calcula la nueva posición
y_ += vy_;
}
}
}
placeSprite(); // Coloca el sprite en la nueva posición
collider_box_ = getRect(); // Actualiza el rectangulo de colisión
#ifdef DEBUG
Debug::get()->add("RECT_X: " + std::to_string(debug_rect_x_.x) + "," + std::to_string(debug_rect_x_.y) + "," + std::to_string(debug_rect_x_.w) + "," + std::to_string(debug_rect_x_.h));
Debug::get()->add("RECT_Y: " + std::to_string(debug_rect_y_.x) + "," + std::to_string(debug_rect_y_.y) + "," + std::to_string(debug_rect_y_.w) + "," + std::to_string(debug_rect_y_.h));
#endif
}
// Establece la animación del jugador
void Player::animate() {
if (vx_ != 0) {
sprite_->update();
}
}
// Comprueba si ha finalizado el salto al alcanzar la altura de inicio
void Player::checkJumpEnd() {
if (state_ == PlayerState::JUMPING) {
if (vy_ > 0) {
if (y_ >= jump_init_pos_) {
// Si alcanza la altura de salto inicial, pasa al estado de caída
setState(PlayerState::FALLING);
vy_ = MAX_VY_;
jumping_counter_ = 0;
}
}
}
}
// Calcula y reproduce el sonido de salto
void Player::playJumpSound() {
if (jumping_counter_ % 4 == 0) {
JA_PlaySound(jumping_sound_[jumping_counter_ / 4]);
}
#ifdef DEBUG
Debug::get()->add("JUMP: " + std::to_string(jumping_counter_ / 4));
#endif
}
// Calcula y reproduce el sonido de caer
void Player::playFallSound() {
if (falling_counter_ % 4 == 0) {
JA_PlaySound(falling_sound_[std::min((falling_counter_ / 4), (int)falling_sound_.size() - 1)]);
}
#ifdef DEBUG
Debug::get()->add("FALL: " + std::to_string(falling_counter_ / 4));
#endif
}
// Comprueba si el jugador tiene suelo debajo de los pies
bool Player::isOnFloor() {
bool on_floor = false;
bool on_slope_l = false;
bool on_slope_r = false;
updateFeet();
// Comprueba las superficies
for (auto f : under_feet_) {
on_floor |= room_->checkTopSurfaces(&f);
on_floor |= room_->checkAutoSurfaces(&f);
}
// Comprueba las rampas
on_slope_l = room_->checkLeftSlopes(&under_feet_[0]);
on_slope_r = room_->checkRightSlopes(&under_feet_[1]);
#ifdef DEBUG
if (on_floor) {
Debug::get()->add("ON_FLOOR");
}
if (on_slope_l) {
Debug::get()->add("ON_SLOPE_L: " + std::to_string(under_feet_[0].x) + "," + std::to_string(under_feet_[0].y));
}
if (on_slope_r) {
Debug::get()->add("ON_SLOPE_R: " + std::to_string(under_feet_[1].x) + "," + std::to_string(under_feet_[1].y));
}
#endif
return on_floor || on_slope_l || on_slope_r;
}
// Comprueba si el jugador esta sobre una superficie automática
bool Player::isOnAutoSurface() {
bool on_auto_surface = false;
updateFeet();
// Comprueba las superficies
for (auto f : under_feet_) {
on_auto_surface |= room_->checkAutoSurfaces(&f);
}
#ifdef DEBUG
if (on_auto_surface) {
Debug::get()->add("ON_AUTO_SURFACE");
}
#endif
return on_auto_surface;
}
// Comprueba si el jugador está sobre una rampa hacia abajo
bool Player::isOnDownSlope() {
bool on_slope = false;
updateFeet();
// Cuando el jugador baja una escalera, se queda volando
// Hay que mirar otro pixel más por debajo
under_feet_[0].y += 1;
under_feet_[1].y += 1;
// Comprueba las rampas
on_slope |= room_->checkLeftSlopes(&under_feet_[0]);
on_slope |= room_->checkRightSlopes(&under_feet_[1]);
#ifdef DEBUG
if (on_slope) {
Debug::get()->add("ON_DOWN_SLOPE");
}
#endif
return on_slope;
}
// Comprueba que el jugador no toque ningun tile de los que matan
bool Player::checkKillingTiles() {
// Actualiza los puntos de colisión
updateColliderPoints();
// Comprueba si hay contacto y retorna en cuanto se encuentra colisión
for (const auto& c : collider_points_) {
if (room_->getTile(c) == TileType::KILL) {
is_alive_ = false; // 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
void Player::setColor() {
if (options.cheats.invincible == Cheat::CheatState::ENABLED) {
color_ = static_cast<Uint8>(PaletteColor::CYAN);
} else if (options.cheats.infinite_lives == Cheat::CheatState::ENABLED) {
color_ = static_cast<Uint8>(PaletteColor::YELLOW);
} else {
color_ = static_cast<Uint8>(PaletteColor::WHITE);
}
}
// Actualiza los puntos de colisión
void Player::updateColliderPoints() {
const SDL_FRect rect = getRect();
collider_points_[0] = {rect.x, rect.y};
collider_points_[1] = {rect.x + 7, rect.y};
collider_points_[2] = {rect.x + 7, rect.y + 7};
collider_points_[3] = {rect.x, rect.y + 7};
collider_points_[4] = {rect.x, rect.y + 8};
collider_points_[5] = {rect.x + 7, rect.y + 8};
collider_points_[6] = {rect.x + 7, rect.y + 15};
collider_points_[7] = {rect.x, rect.y + 15};
}
// Actualiza los puntos de los pies
void Player::updateFeet() {
const SDL_FPoint p = {x_, y_};
under_feet_[0] = {p.x, p.y + HEIGHT_};
under_feet_[1] = {p.x + 7, p.y + HEIGHT_};
feet_[0] = {p.x, p.y + HEIGHT_ - 1};
feet_[1] = {p.x + 7, p.y + HEIGHT_ - 1};
}
// Cambia el estado del jugador
void Player::setState(PlayerState value) {
previous_state_ = state_;
state_ = value;
checkState();
}
// Inicializa los sonidos de salto y caida
void Player::initSounds() {
jumping_sound_.clear();
falling_sound_.clear();
for (int i = 1; i <= 24; ++i) {
std::string soundFile = "jump" + std::to_string(i) + ".wav";
jumping_sound_.push_back(Resource::get()->getSound(soundFile));
if (i >= 11) {
falling_sound_.push_back(Resource::get()->getSound(soundFile));
}
}
}
// Aplica los valores de spawn al jugador
void Player::applySpawnValues(const PlayerSpawn& spawn) {
x_ = spawn.x;
y_ = spawn.y;
vx_ = spawn.vx;
vy_ = spawn.vy;
jump_init_pos_ = spawn.jump_init_pos;
state_ = spawn.state;
sprite_->setFlip(spawn.flip);
}
// Inicializa el sprite del jugador
void Player::initSprite(const std::string& surface_path, const std::string& animations_path) {
auto surface = Resource::get()->getSurface(surface_path);
auto animations = Resource::get()->getAnimations(animations_path);
sprite_ = std::make_shared<SAnimatedSprite>(surface, animations);
sprite_->setWidth(WIDTH_);
sprite_->setHeight(HEIGHT_);
sprite_->setCurrentAnimation("walk");
}
#ifdef DEBUG
// Pinta la información de debug del jugador
void Player::renderDebugInfo() {
if (Debug::get()->getEnabled()) {
auto surface = Screen::get()->getRendererSurface();
// Pinta los underfeet
surface->putPixel(under_feet_[0].x, under_feet_[0].y, static_cast<Uint8>(PaletteColor::BRIGHT_MAGENTA));
surface->putPixel(under_feet_[1].x, under_feet_[1].y, static_cast<Uint8>(PaletteColor::BRIGHT_MAGENTA));
// Pinta rectangulo del jugador
SDL_FRect rect = getRect();
surface->drawRectBorder(&rect, static_cast<Uint8>(PaletteColor::BRIGHT_CYAN));
// Pinta el rectangulo de movimiento
if (vx_ != 0.0f) {
surface->fillRect(&debug_rect_x_, static_cast<Uint8>(PaletteColor::BRIGHT_RED));
}
if (vy_ != 0.0f) {
surface->fillRect(&debug_rect_y_, static_cast<Uint8>(PaletteColor::BRIGHT_RED));
}
// Pinta el punto de debug
surface->putPixel(debug_point_.x, debug_point_.y, rand() % 16);
}
}
#endif // DEBUG

View File

@@ -0,0 +1,215 @@
#pragma once
#include <SDL3/SDL.h>
#include <memory> // Para shared_ptr, __shared_ptr_access
#include <string> // Para string
#include <vector> // Para vector
#include "defines.h" // Para BORDER_TOP, BLOCK
#include "room.h"
#include "sprite/surface_animated_sprite.h" // Para SAnimatedSprite
#include "utils.h" // Para Color
struct JA_Sound_t; // lines 13-13
enum class PlayerState {
STANDING,
JUMPING,
FALLING,
};
struct PlayerSpawn {
float x;
float y;
float vx;
float vy;
int jump_init_pos;
PlayerState state;
SDL_FlipMode flip;
// Constructor por defecto
PlayerSpawn()
: x(0),
y(0),
vx(0),
vy(0),
jump_init_pos(0),
state(PlayerState::STANDING),
flip(SDL_FLIP_NONE) {}
// Constructor
PlayerSpawn(float x, float y, float vx, float vy, int jump_init_pos, PlayerState state, SDL_FlipMode flip)
: x(x),
y(y),
vx(vx),
vy(vy),
jump_init_pos(jump_init_pos),
state(state),
flip(flip) {}
};
struct PlayerData {
PlayerSpawn spawn;
std::string texture_path;
std::string animations_path;
std::shared_ptr<Room> room;
// Constructor
PlayerData(PlayerSpawn spawn, std::string texture_path, std::string animations_path, std::shared_ptr<Room> room)
: spawn(spawn),
texture_path(texture_path),
animations_path(animations_path),
room(room) {}
};
class Player {
public:
// Constantes
static constexpr int WIDTH_ = 8; // Ancho del jugador
static constexpr int HEIGHT_ = 16; // ALto del jugador
static constexpr int MAX_FALLING_HEIGHT_ = BLOCK * 4; // Altura maxima permitida de caída.
static constexpr float MAX_VY_ = 1.2f; // Velocidad máxima que puede alcanzar al desplazarse en vertical
// Objetos y punteros
std::shared_ptr<Room> room_; // Objeto encargado de gestionar cada habitación del juego
std::shared_ptr<SAnimatedSprite> sprite_; // Sprite del jugador
// Variables
float x_; // Posición del jugador en el eje X
float y_; // Posición del jugador en el eje Y
float vx_; // Velocidad/desplazamiento del jugador en el eje X
float vy_; // Velocidad/desplazamiento del jugador en el eje Y
Uint8 color_; // Color del jugador
SDL_FRect collider_box_; // Caja de colisión con los enemigos u objetos
std::vector<SDL_FPoint> collider_points_; // Puntos de colisión con el mapa
std::vector<SDL_FPoint> under_feet_; // Contiene los puntos que hay bajo cada pie del jugador
std::vector<SDL_FPoint> feet_; // Contiene los puntos que hay en el pie del jugador
PlayerState state_; // Estado en el que se encuentra el jugador. Util apara saber si está saltando o cayendo
PlayerState previous_state_; // Estado previo en el que se encontraba el jugador
bool is_on_border_ = false; // Indica si el jugador esta en uno de los cuatro bordes de la pantalla
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 auto_movement_ = false; // Indica si esta siendo arrastrado por una superficie automatica
RoomBorder border_ = RoomBorder::TOP; // Indica en cual de los cuatro bordes se encuentra
SDL_FRect last_position_; // Contiene la ultima posición del jugador, por si hay que deshacer algun movimiento
int jump_init_pos_; // Valor del eje Y en el que se inicia el salto
std::vector<JA_Sound_t*> jumping_sound_; // Vecor con todos los sonidos del salto
std::vector<JA_Sound_t*> falling_sound_; // Vecor con todos los sonidos de la caída
int jumping_counter_ = 0; // Cuenta el tiempo de salto
int falling_counter_ = 0; // Cuenta el tiempo de caida
#ifdef DEBUG
SDL_FRect debug_rect_x_; // Rectangulo de desplazamiento para el modo debug
SDL_FRect debug_rect_y_; // Rectangulo de desplazamiento para el modo debug
Uint8 debug_color_; // Color del recuadro de debug del jugador
SDL_FPoint debug_point_; // Punto para debug
#endif
// Comprueba las entradas y modifica variables
void checkInput();
// Comprueba si se halla en alguno de los cuatro bordes
void checkBorders();
// Comprueba el estado del jugador
void checkState();
// Aplica gravedad al jugador
void applyGravity();
// Recalcula la posición del jugador y su animación
void move();
// Establece la animación del jugador
void animate();
// Comprueba si ha finalizado el salto al alcanzar la altura de inicio
void checkJumpEnd();
// Calcula y reproduce el sonido de salto
void playJumpSound();
// Calcula y reproduce el sonido de caer
void playFallSound();
// Comprueba si el jugador tiene suelo debajo de los pies
bool isOnFloor();
// Comprueba si el jugador esta sobre una superficie automática
bool isOnAutoSurface();
// Comprueba si el jugador está sobre una rampa hacia abajo
bool isOnDownSlope();
// Comprueba que el jugador no toque ningun tile de los que matan
bool checkKillingTiles();
// Actualiza los puntos de colisión
void updateColliderPoints();
// Actualiza los puntos de los pies
void updateFeet();
// Cambia el estado del jugador
void setState(PlayerState value);
// Inicializa los sonidos de salto y caida
void initSounds();
// Coloca el sprite en la posición del jugador
void placeSprite() { sprite_->setPos(x_, y_); }
// Aplica los valores de spawn al jugador
void applySpawnValues(const PlayerSpawn& spawn);
// Inicializa el sprite del jugador
void initSprite(const std::string& texture_path, const std::string& animations_path);
#ifdef DEBUG
// Pinta la información de debug del jugador
void renderDebugInfo();
#endif
public:
// Constructor
explicit Player(const PlayerData& player);
// Destructor
~Player() = default;
// Pinta el enemigo en pantalla
void render();
// Actualiza las variables del objeto
void update();
// Indica si el jugador esta en uno de los cuatro bordes de la pantalla
bool getOnBorder() { return is_on_border_; }
// Indica en cual de los cuatro bordes se encuentra
RoomBorder getBorder() { return border_; }
// Cambia al jugador de un borde al opuesto. Util para el cambio de pantalla
void switchBorders();
// Obtiene el rectangulo que delimita al jugador
SDL_FRect getRect() { return {x_, y_, WIDTH_, HEIGHT_}; }
// Obtiene el rectangulo de colision del jugador
SDL_FRect& getCollider() { return collider_box_; }
// Obtiene el estado de reaparición del jugador
PlayerSpawn getSpawnParams() { return {x_, y_, vx_, vy_, jump_init_pos_, state_, sprite_->getFlip()}; }
// Establece el color del jugador
void setColor();
// Establece la habitación en la que se encuentra el jugador
void setRoom(std::shared_ptr<Room> room) { room_ = room; }
// Comprueba si el jugador esta vivo
bool isAlive() { return is_alive_; }
// Pone el jugador en modo pausa
void setPaused(bool value) { is_paused_ = value; }
};