Compare commits
2 Commits
acdad8295a
...
8bf9da5fb6
| Author | SHA1 | Date | |
|---|---|---|---|
| 8bf9da5fb6 | |||
| cd836862c0 |
@@ -450,7 +450,7 @@ Game code
|
|||||||
|
|
||||||
**Variables:**
|
**Variables:**
|
||||||
- `snake_case` for member variables with `_` suffix: `x_`, `y_`, `sprite_`
|
- `snake_case` for member variables with `_` suffix: `x_`, `y_`, `sprite_`
|
||||||
- `UPPER_CASE` for constants: `BLOCK`, `MAX_VY_`, `WIDTH_`
|
- `UPPER_CASE` for constants: `BLOCK`, `MAX_VY`, `WIDTH`
|
||||||
- Private members: `private_member_`
|
- Private members: `private_member_`
|
||||||
|
|
||||||
**Structs for Data:**
|
**Structs for Data:**
|
||||||
|
|||||||
@@ -164,7 +164,7 @@ auto Resource::getTileMap(const std::string& name) -> std::vector<int>& {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Obtiene la habitación a partir de un nombre
|
// Obtiene la habitación a partir de un nombre
|
||||||
auto Resource::getRoom(const std::string& name) -> std::shared_ptr<RoomData> {
|
auto Resource::getRoom(const std::string& name) -> std::shared_ptr<Room::Data> {
|
||||||
auto it = std::ranges::find_if(rooms_, [&name](const auto& r) { return r.name == name; });
|
auto it = std::ranges::find_if(rooms_, [&name](const auto& r) { return r.name == name; });
|
||||||
|
|
||||||
if (it != rooms_.end()) {
|
if (it != rooms_.end()) {
|
||||||
@@ -278,7 +278,7 @@ void Resource::loadTileMaps() {
|
|||||||
|
|
||||||
for (const auto& l : list) {
|
for (const auto& l : list) {
|
||||||
auto name = getFileName(l);
|
auto name = getFileName(l);
|
||||||
tile_maps_.emplace_back(name, loadRoomTileFile(l));
|
tile_maps_.emplace_back(name, Room::loadRoomTileFile(l));
|
||||||
printWithDots("TileMap : ", name, "[ LOADED ]");
|
printWithDots("TileMap : ", name, "[ LOADED ]");
|
||||||
updateLoadingProgress();
|
updateLoadingProgress();
|
||||||
}
|
}
|
||||||
@@ -292,7 +292,7 @@ void Resource::loadRooms() {
|
|||||||
|
|
||||||
for (const auto& l : list) {
|
for (const auto& l : list) {
|
||||||
auto name = getFileName(l);
|
auto name = getFileName(l);
|
||||||
rooms_.emplace_back(name, std::make_shared<RoomData>(loadRoomFile(l)));
|
rooms_.emplace_back(name, std::make_shared<Room::Data>(Room::loadRoomFile(l)));
|
||||||
printWithDots("Room : ", name, "[ LOADED ]");
|
printWithDots("Room : ", name, "[ LOADED ]");
|
||||||
updateLoadingProgress();
|
updateLoadingProgress();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -103,10 +103,10 @@ struct ResourceTileMap {
|
|||||||
// Estructura para almacenar habitaciones y su nombre
|
// Estructura para almacenar habitaciones y su nombre
|
||||||
struct ResourceRoom {
|
struct ResourceRoom {
|
||||||
std::string name; // Nombre de la habitación
|
std::string name; // Nombre de la habitación
|
||||||
std::shared_ptr<RoomData> room; // Habitación
|
std::shared_ptr<Room::Data> room; // Habitación
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
ResourceRoom(std::string name, std::shared_ptr<RoomData> room)
|
ResourceRoom(std::string name, std::shared_ptr<Room::Data> room)
|
||||||
: name(std::move(name)),
|
: name(std::move(name)),
|
||||||
room(std::move(std::move(room))) {}
|
room(std::move(std::move(room))) {}
|
||||||
};
|
};
|
||||||
@@ -248,7 +248,7 @@ class Resource {
|
|||||||
auto getTileMap(const std::string& name) -> std::vector<int>&;
|
auto getTileMap(const std::string& name) -> std::vector<int>&;
|
||||||
|
|
||||||
// Obtiene la habitación a partir de un nombre
|
// Obtiene la habitación a partir de un nombre
|
||||||
auto getRoom(const std::string& name) -> std::shared_ptr<RoomData>;
|
auto getRoom(const std::string& name) -> std::shared_ptr<Room::Data>;
|
||||||
|
|
||||||
// Obtiene todas las habitaciones
|
// Obtiene todas las habitaciones
|
||||||
auto getRooms() -> std::vector<ResourceRoom>&;
|
auto getRooms() -> std::vector<ResourceRoom>&;
|
||||||
|
|||||||
@@ -9,7 +9,7 @@
|
|||||||
#include "utils/utils.hpp" // Para stringToColor
|
#include "utils/utils.hpp" // Para stringToColor
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
Enemy::Enemy(const EnemyData& enemy)
|
Enemy::Enemy(const Data& enemy)
|
||||||
: sprite_(std::make_shared<SurfaceAnimatedSprite>(Resource::get()->getSurface(enemy.surface_path), Resource::get()->getAnimations(enemy.animation_path))),
|
: sprite_(std::make_shared<SurfaceAnimatedSprite>(Resource::get()->getSurface(enemy.surface_path), Resource::get()->getAnimations(enemy.animation_path))),
|
||||||
color_string_(enemy.color),
|
color_string_(enemy.color),
|
||||||
x1_(enemy.x1),
|
x1_(enemy.x1),
|
||||||
|
|||||||
@@ -6,32 +6,46 @@
|
|||||||
#include <string> // Para string
|
#include <string> // Para string
|
||||||
class SurfaceAnimatedSprite; // lines 7-7
|
class SurfaceAnimatedSprite; // 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 {
|
class Enemy {
|
||||||
|
public:
|
||||||
|
// --- Estructuras ---
|
||||||
|
struct Data {
|
||||||
|
std::string surface_path{}; // Ruta al fichero con la textura
|
||||||
|
std::string animation_path{}; // Ruta al fichero con la animación
|
||||||
|
int w = 0; // Anchura del enemigo
|
||||||
|
int h = 0; // Altura del enemigo
|
||||||
|
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
|
||||||
|
|
||||||
|
// Constructor por defecto
|
||||||
|
Data() = default;
|
||||||
|
};
|
||||||
|
|
||||||
|
// --- Constructor y Destructor ---
|
||||||
|
explicit Enemy(const Data& enemy);
|
||||||
|
~Enemy() = default;
|
||||||
|
|
||||||
|
// --- Funciones ---
|
||||||
|
void render(); // Pinta el enemigo en pantalla
|
||||||
|
void update(float delta_time); // Actualiza las variables del objeto
|
||||||
|
auto getRect() -> SDL_FRect; // Devuelve el rectangulo que contiene al enemigo
|
||||||
|
auto getCollider() -> SDL_FRect&; // Obtiene el rectangulo de colision del enemigo
|
||||||
|
|
||||||
private:
|
private:
|
||||||
// Objetos y punteros
|
// --- Objetos y punteros ---
|
||||||
std::shared_ptr<SurfaceAnimatedSprite> sprite_; // Sprite del enemigo
|
std::shared_ptr<SurfaceAnimatedSprite> sprite_; // Sprite del enemigo
|
||||||
|
|
||||||
// Variables
|
// --- Variables ---
|
||||||
Uint8 color_; // Color del enemigo
|
Uint8 color_; // Color del enemigo
|
||||||
std::string color_string_; // Color del enemigo en formato texto
|
std::string color_string_; // Color del enemigo en formato texto
|
||||||
int x1_; // Limite izquierdo de la ruta en el eje X
|
int x1_; // Limite izquierdo de la ruta en el eje X
|
||||||
@@ -42,25 +56,6 @@ class Enemy {
|
|||||||
bool should_flip_; // Indica si el enemigo hace flip al terminar su ruta
|
bool should_flip_; // Indica si el enemigo hace flip al terminar su ruta
|
||||||
bool should_mirror_; // Indica si el enemigo se dibuja volteado verticalmente
|
bool should_mirror_; // Indica si el enemigo se dibuja volteado verticalmente
|
||||||
|
|
||||||
// Comprueba si ha llegado al limite del recorrido para darse media vuelta
|
// --- Comprueba si ha llegado al limite del recorrido para darse media vuelta ---
|
||||||
void checkPath();
|
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(float delta_time);
|
|
||||||
|
|
||||||
// Devuelve el rectangulo que contiene al enemigo
|
|
||||||
auto getRect() -> SDL_FRect;
|
|
||||||
|
|
||||||
// Obtiene el rectangulo de colision del enemigo
|
|
||||||
auto getCollider() -> SDL_FRect&;
|
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
#include "core/resources/resource.hpp" // Para Resource
|
#include "core/resources/resource.hpp" // Para Resource
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
Item::Item(const ItemData &item)
|
Item::Item(const Data& item)
|
||||||
: sprite_(std::make_shared<SurfaceSprite>(Resource::get()->getSurface(item.tile_set_file), item.x, item.y, ITEM_SIZE, ITEM_SIZE)),
|
: sprite_(std::make_shared<SurfaceSprite>(Resource::get()->getSurface(item.tile_set_file), item.x, item.y, ITEM_SIZE, ITEM_SIZE)),
|
||||||
time_accumulator_(static_cast<float>(item.counter) * COLOR_CHANGE_INTERVAL),
|
time_accumulator_(static_cast<float>(item.counter) * COLOR_CHANGE_INTERVAL),
|
||||||
is_paused_(false) {
|
is_paused_(false) {
|
||||||
|
|||||||
@@ -7,7 +7,10 @@
|
|||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
class SurfaceSprite;
|
class SurfaceSprite;
|
||||||
|
|
||||||
struct ItemData {
|
class Item {
|
||||||
|
public:
|
||||||
|
// --- Estructuras ---
|
||||||
|
struct Data {
|
||||||
std::string tile_set_file; // Ruta al fichero con los gráficos del item
|
std::string tile_set_file; // Ruta al fichero con los gráficos del item
|
||||||
float x{0}; // Posición del item en pantalla
|
float x{0}; // Posición del item en pantalla
|
||||||
float y{0}; // Posición del item en pantalla
|
float y{0}; // Posición del item en pantalla
|
||||||
@@ -17,46 +20,32 @@ struct ItemData {
|
|||||||
Uint8 color2{}; // 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
|
// Constructor
|
||||||
ItemData() = default;
|
Data() = default;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Constructor y Destructor
|
||||||
|
explicit Item(const Data& item);
|
||||||
|
~Item() = default;
|
||||||
|
|
||||||
|
// --- Funciones ---
|
||||||
|
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
|
||||||
|
|
||||||
class Item {
|
|
||||||
private:
|
private:
|
||||||
// Constantes
|
// --- Constantes ---
|
||||||
static constexpr float ITEM_SIZE = 8;
|
static constexpr float ITEM_SIZE = 8;
|
||||||
static constexpr float COLOR_CHANGE_INTERVAL = 0.06F; // Intervalo de cambio de color en segundos (4 frames a 66.67fps)
|
static constexpr float COLOR_CHANGE_INTERVAL = 0.06F; // Intervalo de cambio de color en segundos (4 frames a 66.67fps)
|
||||||
|
|
||||||
// Objetos y punteros
|
// --- Objetos y punteros ---
|
||||||
std::shared_ptr<SurfaceSprite> sprite_; // SSprite del objeto
|
std::shared_ptr<SurfaceSprite> sprite_; // SSprite del objeto
|
||||||
|
|
||||||
// Variables
|
// --- Variables ---
|
||||||
std::vector<Uint8> color_; // Vector con los colores del objeto
|
std::vector<Uint8> color_; // Vector con los colores del objeto
|
||||||
float time_accumulator_; // Acumulador de tiempo para cambio de color
|
float time_accumulator_; // Acumulador de tiempo para cambio de color
|
||||||
SDL_FRect collider_; // Rectangulo de colisión
|
SDL_FRect collider_; // Rectangulo de colisión
|
||||||
bool is_paused_; // Indica si el item está pausado
|
bool is_paused_; // Indica si el item está pausado
|
||||||
|
|
||||||
public:
|
|
||||||
// Constructor
|
|
||||||
explicit Item(const ItemData &item);
|
|
||||||
|
|
||||||
// Destructor
|
|
||||||
~Item() = default;
|
|
||||||
|
|
||||||
// Pinta el objeto en pantalla
|
|
||||||
void render() const;
|
|
||||||
|
|
||||||
// Actualiza las variables del objeto
|
|
||||||
void update(float delta_time);
|
|
||||||
|
|
||||||
// Pausa/despausa el item
|
|
||||||
void setPaused(bool paused) { is_paused_ = paused; }
|
|
||||||
|
|
||||||
// Obtiene el rectangulo de colision del objeto
|
|
||||||
auto getCollider() -> SDL_FRect& { return collider_; }
|
|
||||||
|
|
||||||
// Obtiene su ubicación
|
|
||||||
auto getPos() -> SDL_FPoint;
|
|
||||||
|
|
||||||
// Asigna los colores del objeto
|
|
||||||
void setColors(Uint8 col1, Uint8 col2);
|
|
||||||
};
|
};
|
||||||
@@ -15,12 +15,12 @@
|
|||||||
#include "utils/defines.hpp" // Para RoomBorder::BOTTOM, RoomBorder::LEFT, RoomBorder::RIGHT
|
#include "utils/defines.hpp" // Para RoomBorder::BOTTOM, RoomBorder::LEFT, RoomBorder::RIGHT
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
Player::Player(const PlayerData& player)
|
Player::Player(const Data& player)
|
||||||
: room_(player.room) {
|
: room_(player.room) {
|
||||||
// Inicializa algunas variables
|
// Inicializa algunas variables
|
||||||
initSprite(player.texture_path, player.animations_path);
|
initSprite(player.texture_path, player.animations_path);
|
||||||
setColor();
|
setColor();
|
||||||
applySpawnValues(player.spawn);
|
applySpawnValues(player.spawn_data);
|
||||||
placeSprite();
|
placeSprite();
|
||||||
initSounds();
|
initSounds();
|
||||||
|
|
||||||
@@ -65,7 +65,7 @@ void Player::checkInput(float delta_time) {
|
|||||||
(void)delta_time; // No usado en este método, pero mantenido para consistencia
|
(void)delta_time; // No usado en este método, pero mantenido para consistencia
|
||||||
|
|
||||||
// Solo comprueba las entradas de dirección cuando está sobre una superficie
|
// Solo comprueba las entradas de dirección cuando está sobre una superficie
|
||||||
if (state_ != PlayerState::STANDING) {
|
if (state_ != State::STANDING) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -106,7 +106,7 @@ void Player::checkInput(float delta_time) {
|
|||||||
// Ya que se coloca el estado s_standing al cambiar de pantalla
|
// Ya que se coloca el estado s_standing al cambiar de pantalla
|
||||||
|
|
||||||
if (isOnFloor() || isOnAutoSurface()) {
|
if (isOnFloor() || isOnAutoSurface()) {
|
||||||
setState(PlayerState::JUMPING);
|
setState(State::JUMPING);
|
||||||
vy_ = JUMP_VELOCITY;
|
vy_ = JUMP_VELOCITY;
|
||||||
jump_init_pos_ = y_;
|
jump_init_pos_ = y_;
|
||||||
jumping_time_ = 0.0F;
|
jumping_time_ = 0.0F;
|
||||||
@@ -117,22 +117,22 @@ void Player::checkInput(float delta_time) {
|
|||||||
// Comprueba si está situado en alguno de los cuatro bordes de la habitación
|
// Comprueba si está situado en alguno de los cuatro bordes de la habitación
|
||||||
void Player::checkBorders() {
|
void Player::checkBorders() {
|
||||||
if (x_ < PLAY_AREA_LEFT) {
|
if (x_ < PLAY_AREA_LEFT) {
|
||||||
border_ = RoomBorder::LEFT;
|
border_ = Room::Border::LEFT;
|
||||||
is_on_border_ = true;
|
is_on_border_ = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
else if (x_ + WIDTH > PLAY_AREA_RIGHT) {
|
else if (x_ + WIDTH > PLAY_AREA_RIGHT) {
|
||||||
border_ = RoomBorder::RIGHT;
|
border_ = Room::Border::RIGHT;
|
||||||
is_on_border_ = true;
|
is_on_border_ = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
else if (y_ < PLAY_AREA_TOP) {
|
else if (y_ < PLAY_AREA_TOP) {
|
||||||
border_ = RoomBorder::TOP;
|
border_ = Room::Border::TOP;
|
||||||
is_on_border_ = true;
|
is_on_border_ = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
else if (y_ + HEIGHT > PLAY_AREA_BOTTOM) {
|
else if (y_ + HEIGHT > PLAY_AREA_BOTTOM) {
|
||||||
border_ = RoomBorder::BOTTOM;
|
border_ = Room::Border::BOTTOM;
|
||||||
is_on_border_ = true;
|
is_on_border_ = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -144,24 +144,24 @@ void Player::checkBorders() {
|
|||||||
// Comprueba el estado del jugador
|
// Comprueba el estado del jugador
|
||||||
void Player::checkState(float delta_time) {
|
void Player::checkState(float delta_time) {
|
||||||
// Actualiza las variables en función del estado
|
// Actualiza las variables en función del estado
|
||||||
if (state_ == PlayerState::FALLING) {
|
if (state_ == State::FALLING) {
|
||||||
vx_ = 0.0F;
|
vx_ = 0.0F;
|
||||||
vy_ = MAX_VY;
|
vy_ = MAX_VY;
|
||||||
falling_time_ += delta_time;
|
falling_time_ += delta_time;
|
||||||
playFallSound();
|
playFallSound();
|
||||||
}
|
}
|
||||||
|
|
||||||
else if (state_ == PlayerState::STANDING) {
|
else if (state_ == State::STANDING) {
|
||||||
// Calcula la distancia de caída en pixels (velocidad * tiempo)
|
// Calcula la distancia de caída en pixels (velocidad * tiempo)
|
||||||
const float FALLING_DISTANCE = MAX_VY * falling_time_;
|
const float FALLING_DISTANCE = MAX_VY * falling_time_;
|
||||||
if (previous_state_ == PlayerState::FALLING && FALLING_DISTANCE > MAX_FALLING_HEIGHT) { // Si cae de muy alto, el jugador muere
|
if (previous_state_ == State::FALLING && FALLING_DISTANCE > MAX_FALLING_HEIGHT) { // Si cae de muy alto, el jugador muere
|
||||||
is_alive_ = false;
|
is_alive_ = false;
|
||||||
}
|
}
|
||||||
vy_ = 0.0F;
|
vy_ = 0.0F;
|
||||||
jumping_time_ = 0.0F;
|
jumping_time_ = 0.0F;
|
||||||
falling_time_ = 0.0F;
|
falling_time_ = 0.0F;
|
||||||
if (!isOnFloor() && !isOnAutoSurface() && !isOnDownSlope()) {
|
if (!isOnFloor() && !isOnAutoSurface() && !isOnDownSlope()) {
|
||||||
setState(PlayerState::FALLING);
|
setState(State::FALLING);
|
||||||
vx_ = 0.0F;
|
vx_ = 0.0F;
|
||||||
vy_ = MAX_VY;
|
vy_ = MAX_VY;
|
||||||
falling_time_ += delta_time;
|
falling_time_ += delta_time;
|
||||||
@@ -169,7 +169,7 @@ void Player::checkState(float delta_time) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
else if (state_ == PlayerState::JUMPING) {
|
else if (state_ == State::JUMPING) {
|
||||||
falling_time_ = 0.0F;
|
falling_time_ = 0.0F;
|
||||||
jumping_time_ += delta_time;
|
jumping_time_ += delta_time;
|
||||||
playJumpSound();
|
playJumpSound();
|
||||||
@@ -179,21 +179,21 @@ void Player::checkState(float delta_time) {
|
|||||||
// Cambia al jugador de un borde al opuesto. Util para el cambio de pantalla
|
// Cambia al jugador de un borde al opuesto. Util para el cambio de pantalla
|
||||||
void Player::switchBorders() {
|
void Player::switchBorders() {
|
||||||
switch (border_) {
|
switch (border_) {
|
||||||
case RoomBorder::TOP:
|
case Room::Border::TOP:
|
||||||
y_ = PLAY_AREA_BOTTOM - HEIGHT - BLOCK;
|
y_ = PLAY_AREA_BOTTOM - HEIGHT - BLOCK;
|
||||||
setState(PlayerState::STANDING);
|
setState(State::STANDING);
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case RoomBorder::BOTTOM:
|
case Room::Border::BOTTOM:
|
||||||
y_ = PLAY_AREA_TOP;
|
y_ = PLAY_AREA_TOP;
|
||||||
setState(PlayerState::STANDING);
|
setState(State::STANDING);
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case RoomBorder::RIGHT:
|
case Room::Border::RIGHT:
|
||||||
x_ = PLAY_AREA_LEFT;
|
x_ = PLAY_AREA_LEFT;
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case RoomBorder::LEFT:
|
case Room::Border::LEFT:
|
||||||
x_ = PLAY_AREA_RIGHT - WIDTH;
|
x_ = PLAY_AREA_RIGHT - WIDTH;
|
||||||
break;
|
break;
|
||||||
|
|
||||||
@@ -210,7 +210,7 @@ void Player::switchBorders() {
|
|||||||
void Player::applyGravity(float delta_time) {
|
void Player::applyGravity(float delta_time) {
|
||||||
// La gravedad solo se aplica cuando el jugador esta saltando
|
// La gravedad solo se aplica cuando el jugador esta saltando
|
||||||
// Nunca mientras cae o esta de pie
|
// Nunca mientras cae o esta de pie
|
||||||
if (state_ == PlayerState::JUMPING) {
|
if (state_ == State::JUMPING) {
|
||||||
vy_ += GRAVITY_FORCE * delta_time;
|
vy_ += GRAVITY_FORCE * delta_time;
|
||||||
vy_ = std::min(vy_, MAX_VY);
|
vy_ = std::min(vy_, MAX_VY);
|
||||||
}
|
}
|
||||||
@@ -243,7 +243,7 @@ void Player::moveHorizontalLeft(float delta_time) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Si ha tocado alguna rampa mientras camina (sin saltar), asciende
|
// Si ha tocado alguna rampa mientras camina (sin saltar), asciende
|
||||||
if (state_ != PlayerState::JUMPING) {
|
if (state_ != State::JUMPING) {
|
||||||
const LineVertical LEFT_SIDE = {.x = static_cast<int>(x_), .y1 = static_cast<int>(y_) + static_cast<int>(HEIGHT) - 2, .y2 = static_cast<int>(y_) + static_cast<int>(HEIGHT) - 1}; // Comprueba solo los dos pixels de abajo
|
const LineVertical LEFT_SIDE = {.x = static_cast<int>(x_), .y1 = static_cast<int>(y_) + static_cast<int>(HEIGHT) - 2, .y2 = static_cast<int>(y_) + static_cast<int>(HEIGHT) - 1}; // Comprueba solo los dos pixels de abajo
|
||||||
const int LY = room_->checkLeftSlopes(&LEFT_SIDE);
|
const int LY = room_->checkLeftSlopes(&LEFT_SIDE);
|
||||||
if (LY > -1) {
|
if (LY > -1) {
|
||||||
@@ -252,7 +252,7 @@ void Player::moveHorizontalLeft(float delta_time) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Si está bajando la rampa, recoloca al jugador
|
// Si está bajando la rampa, recoloca al jugador
|
||||||
if (isOnDownSlope() && state_ != PlayerState::JUMPING) {
|
if (isOnDownSlope() && state_ != State::JUMPING) {
|
||||||
y_ += 1;
|
y_ += 1;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -284,7 +284,7 @@ void Player::moveHorizontalRight(float delta_time) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Si ha tocado alguna rampa mientras camina (sin saltar), asciende
|
// Si ha tocado alguna rampa mientras camina (sin saltar), asciende
|
||||||
if (state_ != PlayerState::JUMPING) {
|
if (state_ != State::JUMPING) {
|
||||||
const LineVertical RIGHT_SIDE = {.x = static_cast<int>(x_) + static_cast<int>(WIDTH) - 1, .y1 = static_cast<int>(y_) + static_cast<int>(HEIGHT) - 2, .y2 = static_cast<int>(y_) + static_cast<int>(HEIGHT) - 1}; // Comprueba solo los dos pixels de abajo
|
const LineVertical RIGHT_SIDE = {.x = static_cast<int>(x_) + static_cast<int>(WIDTH) - 1, .y1 = static_cast<int>(y_) + static_cast<int>(HEIGHT) - 2, .y2 = static_cast<int>(y_) + static_cast<int>(HEIGHT) - 1}; // Comprueba solo los dos pixels de abajo
|
||||||
const int RY = room_->checkRightSlopes(&RIGHT_SIDE);
|
const int RY = room_->checkRightSlopes(&RIGHT_SIDE);
|
||||||
if (RY > -1) {
|
if (RY > -1) {
|
||||||
@@ -293,7 +293,7 @@ void Player::moveHorizontalRight(float delta_time) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Si está bajando la rampa, recoloca al jugador
|
// Si está bajando la rampa, recoloca al jugador
|
||||||
if (isOnDownSlope() && state_ != PlayerState::JUMPING) {
|
if (isOnDownSlope() && state_ != State::JUMPING) {
|
||||||
y_ += 1;
|
y_ += 1;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -322,7 +322,7 @@ void Player::moveVerticalUp(float delta_time) {
|
|||||||
} else {
|
} else {
|
||||||
// Si hay colisión lo mueve hasta donde no colisiona y entra en caída
|
// Si hay colisión lo mueve hasta donde no colisiona y entra en caída
|
||||||
y_ = POS + 1;
|
y_ = POS + 1;
|
||||||
setState(PlayerState::FALLING);
|
setState(State::FALLING);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -345,13 +345,13 @@ void Player::moveVerticalDown(float delta_time) {
|
|||||||
if (POS > -1) {
|
if (POS > -1) {
|
||||||
// Si hay colisión lo mueve hasta donde no colisiona y pasa a estar sobre la superficie
|
// Si hay colisión lo mueve hasta donde no colisiona y pasa a estar sobre la superficie
|
||||||
y_ = POS - HEIGHT;
|
y_ = POS - HEIGHT;
|
||||||
setState(PlayerState::STANDING);
|
setState(State::STANDING);
|
||||||
|
|
||||||
// Deja de estar enganchado a la superficie automatica
|
// Deja de estar enganchado a la superficie automatica
|
||||||
auto_movement_ = false;
|
auto_movement_ = false;
|
||||||
} else {
|
} else {
|
||||||
// Si no hay colisión con los muros, comprueba la colisión con las rampas
|
// 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
|
if (state_ != State::JUMPING) { // Las rampas no se miran si se está saltando
|
||||||
auto rect = toSDLRect(proj);
|
auto rect = toSDLRect(proj);
|
||||||
const LineVertical LEFT_SIDE = {.x = rect.x, .y1 = rect.y, .y2 = rect.y + rect.h - 1};
|
const LineVertical LEFT_SIDE = {.x = rect.x, .y1 = rect.y, .y2 = rect.y + rect.h - 1};
|
||||||
const LineVertical RIGHT_SIDE = {.x = rect.x + rect.w - 1, .y1 = rect.y, .y2 = rect.y + rect.h - 1};
|
const LineVertical RIGHT_SIDE = {.x = rect.x + rect.w - 1, .y1 = rect.y, .y2 = rect.y + rect.h - 1};
|
||||||
@@ -360,7 +360,7 @@ void Player::moveVerticalDown(float delta_time) {
|
|||||||
// No está saltando y hay colisión con una rampa
|
// No está saltando y hay colisión con una rampa
|
||||||
// Calcula la nueva posición
|
// Calcula la nueva posición
|
||||||
y_ = POINT - HEIGHT;
|
y_ = POINT - HEIGHT;
|
||||||
setState(PlayerState::STANDING);
|
setState(State::STANDING);
|
||||||
#ifdef _DEBUG
|
#ifdef _DEBUG
|
||||||
debug_color_ = static_cast<Uint8>(PaletteColor::YELLOW);
|
debug_color_ = static_cast<Uint8>(PaletteColor::YELLOW);
|
||||||
debug_point_ = {.x = x_ + (WIDTH / 2), .y = POINT};
|
debug_point_ = {.x = x_ + (WIDTH / 2), .y = POINT};
|
||||||
@@ -399,13 +399,13 @@ void Player::move(float delta_time) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Si ha salido del suelo, el jugador cae
|
// Si ha salido del suelo, el jugador cae
|
||||||
if (state_ == PlayerState::STANDING && !isOnFloor()) {
|
if (state_ == State::STANDING && !isOnFloor()) {
|
||||||
setState(PlayerState::FALLING);
|
setState(State::FALLING);
|
||||||
auto_movement_ = false;
|
auto_movement_ = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Si ha salido de una superficie automatica, detiene el movimiento automatico
|
// Si ha salido de una superficie automatica, detiene el movimiento automatico
|
||||||
if (state_ == PlayerState::STANDING && isOnFloor() && !isOnAutoSurface()) {
|
if (state_ == State::STANDING && isOnFloor() && !isOnAutoSurface()) {
|
||||||
auto_movement_ = false;
|
auto_movement_ = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -434,11 +434,11 @@ void Player::animate(float delta_time) {
|
|||||||
|
|
||||||
// Comprueba si ha finalizado el salto al alcanzar la altura de inicio
|
// Comprueba si ha finalizado el salto al alcanzar la altura de inicio
|
||||||
void Player::checkJumpEnd() {
|
void Player::checkJumpEnd() {
|
||||||
if (state_ == PlayerState::JUMPING) {
|
if (state_ == State::JUMPING) {
|
||||||
if (vy_ > 0) {
|
if (vy_ > 0) {
|
||||||
if (y_ >= jump_init_pos_) {
|
if (y_ >= jump_init_pos_) {
|
||||||
// Si alcanza la altura de salto inicial, pasa al estado de caída
|
// Si alcanza la altura de salto inicial, pasa al estado de caída
|
||||||
setState(PlayerState::FALLING);
|
setState(State::FALLING);
|
||||||
vy_ = MAX_VY;
|
vy_ = MAX_VY;
|
||||||
jumping_time_ = 0.0F;
|
jumping_time_ = 0.0F;
|
||||||
}
|
}
|
||||||
@@ -561,7 +561,7 @@ auto Player::checkKillingTiles() -> bool {
|
|||||||
|
|
||||||
// Comprueba si hay contacto con algún tile que mata
|
// Comprueba si hay contacto con algún tile que mata
|
||||||
if (std::ranges::any_of(collider_points_, [this](const auto& c) {
|
if (std::ranges::any_of(collider_points_, [this](const auto& c) {
|
||||||
return room_->getTile(c) == TileType::KILL;
|
return room_->getTile(c) == Room::Tile::KILL;
|
||||||
})) {
|
})) {
|
||||||
is_alive_ = false; // Mata al jugador inmediatamente
|
is_alive_ = false; // Mata al jugador inmediatamente
|
||||||
return true; // Retorna en cuanto se detecta una colisión
|
return true; // Retorna en cuanto se detecta una colisión
|
||||||
@@ -606,7 +606,7 @@ void Player::updateFeet() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Cambia el estado del jugador
|
// Cambia el estado del jugador
|
||||||
void Player::setState(PlayerState value) {
|
void Player::setState(State value) {
|
||||||
previous_state_ = state_;
|
previous_state_ = state_;
|
||||||
state_ = value;
|
state_ = value;
|
||||||
|
|
||||||
@@ -630,7 +630,7 @@ void Player::initSounds() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Aplica los valores de spawn al jugador
|
// Aplica los valores de spawn al jugador
|
||||||
void Player::applySpawnValues(const PlayerSpawn& spawn) {
|
void Player::applySpawnValues(const SpawnData& spawn) {
|
||||||
x_ = spawn.x;
|
x_ = spawn.x;
|
||||||
y_ = spawn.y;
|
y_ = spawn.y;
|
||||||
vx_ = spawn.vx;
|
vx_ = spawn.vx;
|
||||||
|
|||||||
@@ -13,33 +13,29 @@
|
|||||||
#include "utils/utils.hpp" // Para Color
|
#include "utils/utils.hpp" // Para Color
|
||||||
struct JA_Sound_t; // lines 13-13
|
struct JA_Sound_t; // lines 13-13
|
||||||
|
|
||||||
enum class PlayerState {
|
class Player {
|
||||||
|
public:
|
||||||
|
// --- Enums y Structs ---
|
||||||
|
enum class State {
|
||||||
STANDING,
|
STANDING,
|
||||||
JUMPING,
|
JUMPING,
|
||||||
FALLING,
|
FALLING,
|
||||||
};
|
};
|
||||||
|
|
||||||
struct PlayerSpawn {
|
struct SpawnData {
|
||||||
float x;
|
float x = 0;
|
||||||
float y;
|
float y = 0;
|
||||||
float vx;
|
float vx = 0;
|
||||||
float vy;
|
float vy = 0;
|
||||||
int jump_init_pos;
|
int jump_init_pos = 0;
|
||||||
PlayerState state;
|
State state = State::STANDING;
|
||||||
SDL_FlipMode flip;
|
SDL_FlipMode flip = SDL_FLIP_NONE;
|
||||||
|
|
||||||
// Constructor por defecto
|
// Constructor por defecto
|
||||||
PlayerSpawn()
|
SpawnData() = default;
|
||||||
: x(0),
|
|
||||||
y(0),
|
|
||||||
vx(0),
|
|
||||||
vy(0),
|
|
||||||
jump_init_pos(0),
|
|
||||||
state(PlayerState::STANDING),
|
|
||||||
flip(SDL_FLIP_NONE) {}
|
|
||||||
|
|
||||||
// Constructor
|
// Constructor con parámetros
|
||||||
PlayerSpawn(float x, float y, float vx, float vy, int jump_init_pos, PlayerState state, SDL_FlipMode flip)
|
SpawnData(float x, float y, float vx, float vy, int jump_init_pos, State state, SDL_FlipMode flip)
|
||||||
: x(x),
|
: x(x),
|
||||||
y(y),
|
y(y),
|
||||||
vx(vx),
|
vx(vx),
|
||||||
@@ -47,43 +43,63 @@ struct PlayerSpawn {
|
|||||||
jump_init_pos(jump_init_pos),
|
jump_init_pos(jump_init_pos),
|
||||||
state(state),
|
state(state),
|
||||||
flip(flip) {}
|
flip(flip) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
struct PlayerData {
|
struct Data {
|
||||||
PlayerSpawn spawn;
|
SpawnData spawn_data{};
|
||||||
std::string texture_path;
|
std::string texture_path{};
|
||||||
std::string animations_path;
|
std::string animations_path{};
|
||||||
std::shared_ptr<Room> room;
|
std::shared_ptr<Room> room = nullptr;
|
||||||
|
|
||||||
// Constructor
|
// Constructor por defecto
|
||||||
PlayerData(PlayerSpawn spawn, std::string texture_path, std::string animations_path, std::shared_ptr<Room> room)
|
Data() = default;
|
||||||
: spawn(spawn),
|
|
||||||
texture_path(std::move(std::move(texture_path))),
|
// Constructor con parámetros
|
||||||
animations_path(std::move(std::move(animations_path))),
|
Data(SpawnData spawn_data, std::string texture_path, std::string animations_path, std::shared_ptr<Room> room)
|
||||||
room(std::move(std::move(room))) {}
|
: spawn_data(std::move(spawn_data)),
|
||||||
};
|
texture_path(std::move(texture_path)),
|
||||||
|
animations_path(std::move(animations_path)),
|
||||||
|
room(std::move(room)) {}
|
||||||
|
};
|
||||||
|
|
||||||
|
// --- 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 getOnBorder() const -> bool { return is_on_border_; } // 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_, y_, WIDTH, 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_, y_, vx_, vy_, jump_init_pos_, state_, sprite_->getFlip()}; } // Obtiene el estado de reaparición del jugador
|
||||||
|
void setColor(); // Establece el color del jugador
|
||||||
|
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_; } // Comprueba si el jugador esta vivo
|
||||||
|
void setPaused(bool value) { is_paused_ = value; } // Pone el jugador en modo pausa
|
||||||
|
|
||||||
class Player {
|
|
||||||
private:
|
private:
|
||||||
// Constantes
|
// --- Constantes ---
|
||||||
static constexpr int WIDTH = 8; // Ancho del jugador
|
static constexpr int WIDTH = 8; // Ancho del jugador
|
||||||
static constexpr int HEIGHT = 16; // ALto del jugador
|
static constexpr int HEIGHT = 16; // ALto del jugador
|
||||||
static constexpr int MAX_FALLING_HEIGHT = BLOCK * 4; // Altura maxima permitida de caída en pixels
|
static constexpr int MAX_FALLING_HEIGHT = BLOCK * 4; // Altura maxima permitida de caída en pixels
|
||||||
|
|
||||||
// Constantes de física (per-second values)
|
// --- Constantes de física (per-second values) ---
|
||||||
static constexpr float HORIZONTAL_VELOCITY = 40.0F; // Velocidad horizontal en pixels/segundo (0.6 * 66.67fps)
|
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 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 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²)
|
static constexpr float GRAVITY_FORCE = 155.6F; // Fuerza de gravedad en pixels/segundo² (0.035 * 66.67²)
|
||||||
|
|
||||||
// Constantes de sonido
|
// --- Constantes de sonido ---
|
||||||
static constexpr float SOUND_INTERVAL = 0.06F; // Intervalo entre sonidos de salto/caída en segundos (4 frames a 66.67fps)
|
static constexpr float SOUND_INTERVAL = 0.06F; // Intervalo entre sonidos de salto/caída en segundos (4 frames a 66.67fps)
|
||||||
|
|
||||||
// Objetos y punteros
|
// --- --- Objetos y punteros --- ---
|
||||||
std::shared_ptr<Room> room_; // Objeto encargado de gestionar cada habitación del juego
|
std::shared_ptr<Room> room_; // Objeto encargado de gestionar cada habitación del juego
|
||||||
std::shared_ptr<SurfaceAnimatedSprite> sprite_; // Sprite del jugador
|
std::shared_ptr<SurfaceAnimatedSprite> sprite_; // Sprite del jugador
|
||||||
|
|
||||||
// Variables
|
// --- Variables ---
|
||||||
float x_; // Posición del jugador en el eje X
|
float x_; // Posición del jugador en el eje X
|
||||||
float y_; // Posición del jugador en el eje Y
|
float y_; // Posición del jugador en el eje Y
|
||||||
float vx_; // Velocidad/desplazamiento del jugador en el eje X
|
float vx_; // Velocidad/desplazamiento del jugador en el eje X
|
||||||
@@ -93,13 +109,13 @@ class Player {
|
|||||||
std::vector<SDL_FPoint> collider_points_; // Puntos de colisión con el mapa
|
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> 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
|
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
|
State 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
|
State 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_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_alive_ = true; // Indica si el jugador esta vivo o no
|
||||||
bool is_paused_ = false; // Indica si el jugador esta en modo pausa
|
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
|
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
|
Room::Border border_ = Room::Border::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
|
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
|
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*> jumping_sound_; // Vecor con todos los sonidos del salto
|
||||||
@@ -107,130 +123,40 @@ class Player {
|
|||||||
float jumping_time_ = 0.0F; // Tiempo acumulado de salto en segundos
|
float jumping_time_ = 0.0F; // Tiempo acumulado de salto en segundos
|
||||||
float falling_time_ = 0.0F; // Tiempo acumulado de caída en segundos
|
float falling_time_ = 0.0F; // Tiempo acumulado de caída en segundos
|
||||||
|
|
||||||
|
// --- Funciones ---
|
||||||
|
void checkInput(float delta_time); // Comprueba las entradas y modifica variables
|
||||||
|
void checkBorders(); // Comprueba si se halla en alguno de los cuatro bordes
|
||||||
|
void checkState(float delta_time); // Comprueba el estado del jugador
|
||||||
|
void applyGravity(float delta_time); // Aplica gravedad al jugador
|
||||||
|
void move(float delta_time); // Recalcula la posición del jugador y su animación
|
||||||
|
void moveHorizontalLeft(float delta_time); // Maneja el movimiento horizontal hacia la izquierda
|
||||||
|
void moveHorizontalRight(float delta_time); // Maneja el movimiento horizontal hacia la derecha
|
||||||
|
void moveVerticalUp(float delta_time); // Maneja el movimiento vertical hacia arriba
|
||||||
|
void moveVerticalDown(float delta_time); // Maneja el movimiento vertical hacia abajo
|
||||||
|
void animate(float delta_time); // Establece la animación del jugador
|
||||||
|
void checkJumpEnd(); // Comprueba si ha finalizado el salto al alcanzar la altura de inicio
|
||||||
|
void playJumpSound(); // Calcula y reproduce el sonido de salto
|
||||||
|
void playFallSound(); // Calcula y reproduce el sonido de caer
|
||||||
|
auto isOnFloor() -> bool; // Comprueba si el jugador tiene suelo debajo de los pies
|
||||||
|
auto isOnAutoSurface() -> bool; // Comprueba si el jugador esta sobre una superficie automática
|
||||||
|
auto isOnDownSlope() -> bool; // Comprueba si el jugador está sobre una rampa hacia abajo
|
||||||
|
auto checkKillingTiles() -> bool; // Comprueba que el jugador no toque ningun tile de los que matan
|
||||||
|
void updateColliderPoints(); // Actualiza los puntos de colisión
|
||||||
|
void updateFeet(); // Actualiza los puntos de los pies
|
||||||
|
void setState(State value); // Cambia el estado del jugador
|
||||||
|
void initSounds(); // Inicializa los sonidos de salto y caida
|
||||||
|
void placeSprite() { sprite_->setPos(x_, y_); } // Coloca el sprite en la posición del jugador
|
||||||
|
void applySpawnValues(const SpawnData& spawn); // Aplica los valores de spawn al jugador
|
||||||
|
void initSprite(const std::string& surface_path, const std::string& animations_path); // Inicializa el sprite del jugador
|
||||||
|
|
||||||
#ifdef _DEBUG
|
#ifdef _DEBUG
|
||||||
|
// --- Variables ---
|
||||||
SDL_FRect debug_rect_x_; // Rectangulo de desplazamiento para el modo 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
|
SDL_FRect debug_rect_y_; // Rectangulo de desplazamiento para el modo debug
|
||||||
Uint8 debug_color_; // Color del recuadro de debug del jugador
|
Uint8 debug_color_; // Color del recuadro de debug del jugador
|
||||||
SDL_FPoint debug_point_; // Punto para debug
|
SDL_FPoint debug_point_; // Punto para debug
|
||||||
|
|
||||||
|
// --- Funciones ---
|
||||||
|
void renderDebugInfo(); // Pinta la información de debug del jugador
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
// Comprueba las entradas y modifica variables
|
|
||||||
void checkInput(float delta_time);
|
|
||||||
|
|
||||||
// Comprueba si se halla en alguno de los cuatro bordes
|
|
||||||
void checkBorders();
|
|
||||||
|
|
||||||
// Comprueba el estado del jugador
|
|
||||||
void checkState(float delta_time);
|
|
||||||
|
|
||||||
// Aplica gravedad al jugador
|
|
||||||
void applyGravity(float delta_time);
|
|
||||||
|
|
||||||
// Recalcula la posición del jugador y su animación
|
|
||||||
void move(float delta_time);
|
|
||||||
|
|
||||||
// Maneja el movimiento horizontal hacia la izquierda
|
|
||||||
void moveHorizontalLeft(float delta_time);
|
|
||||||
|
|
||||||
// Maneja el movimiento horizontal hacia la derecha
|
|
||||||
void moveHorizontalRight(float delta_time);
|
|
||||||
|
|
||||||
// Maneja el movimiento vertical hacia arriba
|
|
||||||
void moveVerticalUp(float delta_time);
|
|
||||||
|
|
||||||
// Maneja el movimiento vertical hacia abajo
|
|
||||||
void moveVerticalDown(float delta_time);
|
|
||||||
|
|
||||||
// Establece la animación del jugador
|
|
||||||
void animate(float delta_time);
|
|
||||||
|
|
||||||
// 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
|
|
||||||
auto isOnFloor() -> bool;
|
|
||||||
|
|
||||||
// Comprueba si el jugador esta sobre una superficie automática
|
|
||||||
auto isOnAutoSurface() -> bool;
|
|
||||||
|
|
||||||
// Comprueba si el jugador está sobre una rampa hacia abajo
|
|
||||||
auto isOnDownSlope() -> bool;
|
|
||||||
|
|
||||||
// Comprueba que el jugador no toque ningun tile de los que matan
|
|
||||||
auto checkKillingTiles() -> bool;
|
|
||||||
|
|
||||||
// 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& surface_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(float delta_time);
|
|
||||||
|
|
||||||
// Indica si el jugador esta en uno de los cuatro bordes de la pantalla
|
|
||||||
[[nodiscard]] auto getOnBorder() const -> bool { return is_on_border_; }
|
|
||||||
|
|
||||||
// Indica en cual de los cuatro bordes se encuentra
|
|
||||||
[[nodiscard]] auto getBorder() const -> RoomBorder { 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
|
|
||||||
auto getRect() -> SDL_FRect { return {x_, y_, WIDTH, HEIGHT}; }
|
|
||||||
|
|
||||||
// Obtiene el rectangulo de colision del jugador
|
|
||||||
auto getCollider() -> SDL_FRect& { return collider_box_; }
|
|
||||||
|
|
||||||
// Obtiene el estado de reaparición del jugador
|
|
||||||
auto getSpawnParams() -> PlayerSpawn { 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_ = std::move(room); }
|
|
||||||
|
|
||||||
// Comprueba si el jugador esta vivo
|
|
||||||
[[nodiscard]] auto isAlive() const -> bool { return is_alive_; }
|
|
||||||
|
|
||||||
// Pone el jugador en modo pausa
|
|
||||||
void setPaused(bool value) { is_paused_ = value; }
|
|
||||||
};
|
};
|
||||||
@@ -19,275 +19,6 @@
|
|||||||
#include "utils/defines.hpp" // Para BLOCK, PLAY_AREA_HEIGHT, PLAY_AREA_WIDTH
|
#include "utils/defines.hpp" // Para BLOCK, PLAY_AREA_HEIGHT, PLAY_AREA_WIDTH
|
||||||
#include "utils/utils.hpp" // Para LineHorizontal, LineDiagonal, LineVertical
|
#include "utils/utils.hpp" // Para LineHorizontal, LineDiagonal, LineVertical
|
||||||
|
|
||||||
// Carga las variables y texturas desde un fichero de mapa de tiles
|
|
||||||
auto loadRoomTileFile(const std::string& file_path, bool verbose) -> std::vector<int> {
|
|
||||||
std::vector<int> tile_map_file;
|
|
||||||
const std::string FILENAME = file_path.substr(file_path.find_last_of("\\/") + 1);
|
|
||||||
std::ifstream file(file_path);
|
|
||||||
|
|
||||||
// El fichero se puede abrir
|
|
||||||
if (file.good()) {
|
|
||||||
std::string line;
|
|
||||||
// Procesa el fichero linea a linea
|
|
||||||
while (std::getline(file, line)) { // Lee el fichero linea a linea
|
|
||||||
if (line.find("data encoding") != std::string::npos) {
|
|
||||||
// Lee la primera linea
|
|
||||||
std::getline(file, line);
|
|
||||||
while (line != "</data>") { // Procesa lineas mientras haya
|
|
||||||
std::stringstream ss(line);
|
|
||||||
std::string tmp;
|
|
||||||
while (getline(ss, tmp, ',')) {
|
|
||||||
tile_map_file.push_back(std::stoi(tmp) - 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Lee la siguiente linea
|
|
||||||
std::getline(file, line);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Cierra el fichero
|
|
||||||
if (verbose) {
|
|
||||||
std::cout << "TileMap loaded: " << FILENAME.c_str() << '\n';
|
|
||||||
}
|
|
||||||
file.close();
|
|
||||||
}
|
|
||||||
|
|
||||||
else { // El fichero no se puede abrir
|
|
||||||
if (verbose) {
|
|
||||||
std::cout << "Warning: Unable to open " << FILENAME.c_str() << " file" << '\n';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return tile_map_file;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Parsea una línea en key y value separados por '='
|
|
||||||
auto parseKeyValue(const std::string& line) -> std::pair<std::string, std::string> {
|
|
||||||
int pos = line.find('=');
|
|
||||||
std::string key = line.substr(0, pos);
|
|
||||||
std::string value = line.substr(pos + 1, line.length());
|
|
||||||
return {key, value};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Muestra un warning de parámetro desconocido
|
|
||||||
void logUnknownParameter(const std::string& file_name, const std::string& key, bool verbose) {
|
|
||||||
if (verbose) {
|
|
||||||
std::cout << "Warning: file " << file_name.c_str() << "\n, unknown parameter \"" << key.c_str() << "\"" << '\n';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Carga un bloque [enemy]...[/enemy] desde un archivo
|
|
||||||
auto loadEnemyFromFile(std::ifstream& file, const std::string& file_name, bool verbose) -> EnemyData {
|
|
||||||
EnemyData enemy;
|
|
||||||
enemy.flip = false;
|
|
||||||
enemy.mirror = false;
|
|
||||||
enemy.frame = -1;
|
|
||||||
|
|
||||||
std::string line;
|
|
||||||
do {
|
|
||||||
std::getline(file, line);
|
|
||||||
auto [key, value] = parseKeyValue(line);
|
|
||||||
|
|
||||||
if (!setEnemy(&enemy, key, value)) {
|
|
||||||
logUnknownParameter(file_name, key, verbose);
|
|
||||||
}
|
|
||||||
} while (line != "[/enemy]");
|
|
||||||
|
|
||||||
return enemy;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Carga un bloque [item]...[/item] desde un archivo
|
|
||||||
auto loadItemFromFile(std::ifstream& file, const std::string& file_name, bool verbose) -> ItemData {
|
|
||||||
ItemData item;
|
|
||||||
item.counter = 0;
|
|
||||||
item.color1 = stringToColor("yellow");
|
|
||||||
item.color2 = stringToColor("magenta");
|
|
||||||
|
|
||||||
std::string line;
|
|
||||||
do {
|
|
||||||
std::getline(file, line);
|
|
||||||
auto [key, value] = parseKeyValue(line);
|
|
||||||
|
|
||||||
if (!setItem(&item, key, value)) {
|
|
||||||
logUnknownParameter(file_name, key, verbose);
|
|
||||||
}
|
|
||||||
} while (line != "[/item]");
|
|
||||||
|
|
||||||
return item;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Carga las variables desde un fichero de mapa
|
|
||||||
auto loadRoomFile(const std::string& file_path, bool verbose) -> RoomData {
|
|
||||||
RoomData room;
|
|
||||||
room.item_color1 = "yellow";
|
|
||||||
room.item_color2 = "magenta";
|
|
||||||
room.conveyor_belt_direction = 1;
|
|
||||||
|
|
||||||
const std::string FILE_NAME = file_path.substr(file_path.find_last_of("\\/") + 1);
|
|
||||||
room.number = FILE_NAME.substr(0, FILE_NAME.find_last_of('.'));
|
|
||||||
|
|
||||||
std::ifstream file(file_path);
|
|
||||||
|
|
||||||
// El fichero se puede abrir
|
|
||||||
if (file.good()) {
|
|
||||||
std::string line;
|
|
||||||
// Procesa el fichero linea a linea
|
|
||||||
while (std::getline(file, line)) {
|
|
||||||
// Si la linea contiene el texto [enemy] se realiza el proceso de carga de un enemigo
|
|
||||||
if (line == "[enemy]") {
|
|
||||||
room.enemies.push_back(loadEnemyFromFile(file, FILE_NAME, verbose));
|
|
||||||
}
|
|
||||||
// Si la linea contiene el texto [item] se realiza el proceso de carga de un item
|
|
||||||
else if (line == "[item]") {
|
|
||||||
room.items.push_back(loadItemFromFile(file, FILE_NAME, verbose));
|
|
||||||
}
|
|
||||||
// En caso contrario se parsea el fichero para buscar las variables y los valores
|
|
||||||
else {
|
|
||||||
auto [key, value] = parseKeyValue(line);
|
|
||||||
if (!setRoom(&room, key, value)) {
|
|
||||||
logUnknownParameter(FILE_NAME, key, verbose);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Cierra el fichero
|
|
||||||
if (verbose) {
|
|
||||||
std::cout << "Room loaded: " << FILE_NAME.c_str() << '\n';
|
|
||||||
}
|
|
||||||
file.close();
|
|
||||||
}
|
|
||||||
// El fichero no se puede abrir
|
|
||||||
else {
|
|
||||||
std::cout << "Warning: Unable to open " << FILE_NAME.c_str() << " file" << '\n';
|
|
||||||
}
|
|
||||||
|
|
||||||
return room;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Asigna variables a una estructura RoomData
|
|
||||||
auto setRoom(RoomData* room, const std::string& key, const std::string& value) -> bool {
|
|
||||||
// Indicador de éxito en la asignación
|
|
||||||
bool success = true;
|
|
||||||
|
|
||||||
try {
|
|
||||||
if (key == "tileMapFile") {
|
|
||||||
room->tile_map_file = value;
|
|
||||||
} else if (key == "name") {
|
|
||||||
room->name = value;
|
|
||||||
} else if (key == "bgColor") {
|
|
||||||
room->bg_color = value;
|
|
||||||
} else if (key == "border") {
|
|
||||||
room->border_color = value;
|
|
||||||
} else if (key == "itemColor1") {
|
|
||||||
room->item_color1 = value;
|
|
||||||
} else if (key == "itemColor2") {
|
|
||||||
room->item_color2 = value;
|
|
||||||
} else if (key == "tileSetFile") {
|
|
||||||
room->tile_set_file = value;
|
|
||||||
} else if (key == "roomUp") {
|
|
||||||
room->upper_room = value;
|
|
||||||
} else if (key == "roomDown") {
|
|
||||||
room->lower_room = value;
|
|
||||||
} else if (key == "roomLeft") {
|
|
||||||
room->left_room = value;
|
|
||||||
} else if (key == "roomRight") {
|
|
||||||
room->right_room = value;
|
|
||||||
} else if (key == "autoSurface") {
|
|
||||||
room->conveyor_belt_direction = (value == "right") ? 1 : -1;
|
|
||||||
} else if (key.empty() || key.substr(0, 1) == "#") {
|
|
||||||
// No se realiza ninguna acción para estas claves
|
|
||||||
} else {
|
|
||||||
success = false;
|
|
||||||
}
|
|
||||||
} catch (const std::exception& e) {
|
|
||||||
std::cerr << "Error al asignar la clave " << key << " con valor " << value << ": " << e.what() << '\n';
|
|
||||||
success = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
return success;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Asigna variables a una estructura EnemyData
|
|
||||||
auto setEnemy(EnemyData* enemy, const std::string& key, const std::string& value) -> bool {
|
|
||||||
// Indicador de éxito en la asignación
|
|
||||||
bool success = true;
|
|
||||||
|
|
||||||
try {
|
|
||||||
if (key == "tileSetFile") {
|
|
||||||
enemy->surface_path = value;
|
|
||||||
} else if (key == "animation") {
|
|
||||||
enemy->animation_path = value;
|
|
||||||
} else if (key == "width") {
|
|
||||||
enemy->w = std::stoi(value);
|
|
||||||
} else if (key == "height") {
|
|
||||||
enemy->h = std::stoi(value);
|
|
||||||
} else if (key == "x") {
|
|
||||||
enemy->x = std::stof(value) * BLOCK;
|
|
||||||
} else if (key == "y") {
|
|
||||||
enemy->y = std::stof(value) * BLOCK;
|
|
||||||
} else if (key == "vx") {
|
|
||||||
enemy->vx = std::stof(value);
|
|
||||||
} else if (key == "vy") {
|
|
||||||
enemy->vy = std::stof(value);
|
|
||||||
} else if (key == "x1") {
|
|
||||||
enemy->x1 = std::stoi(value) * BLOCK;
|
|
||||||
} else if (key == "x2") {
|
|
||||||
enemy->x2 = std::stoi(value) * BLOCK;
|
|
||||||
} else if (key == "y1") {
|
|
||||||
enemy->y1 = std::stoi(value) * BLOCK;
|
|
||||||
} else if (key == "y2") {
|
|
||||||
enemy->y2 = std::stoi(value) * BLOCK;
|
|
||||||
} else if (key == "flip") {
|
|
||||||
enemy->flip = stringToBool(value);
|
|
||||||
} else if (key == "mirror") {
|
|
||||||
enemy->mirror = stringToBool(value);
|
|
||||||
} else if (key == "color") {
|
|
||||||
enemy->color = value;
|
|
||||||
} else if (key == "frame") {
|
|
||||||
enemy->frame = std::stoi(value);
|
|
||||||
} else if (key == "[/enemy]" || key == "tileSetFile" || key.substr(0, 1) == "#") {
|
|
||||||
// No se realiza ninguna acción para estas claves
|
|
||||||
} else {
|
|
||||||
success = false;
|
|
||||||
}
|
|
||||||
} catch (const std::exception& e) {
|
|
||||||
std::cerr << "Error al asignar la clave " << key << " con valor " << value << ": " << e.what() << '\n';
|
|
||||||
success = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
return success;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Asigna variables a una estructura ItemData
|
|
||||||
auto setItem(ItemData* item, const std::string& key, const std::string& value) -> bool {
|
|
||||||
// Indicador de éxito en la asignación
|
|
||||||
bool success = true;
|
|
||||||
|
|
||||||
try {
|
|
||||||
if (key == "tileSetFile") {
|
|
||||||
item->tile_set_file = value;
|
|
||||||
} else if (key == "counter") {
|
|
||||||
item->counter = std::stoi(value);
|
|
||||||
} else if (key == "x") {
|
|
||||||
item->x = std::stof(value) * BLOCK;
|
|
||||||
} else if (key == "y") {
|
|
||||||
item->y = std::stof(value) * BLOCK;
|
|
||||||
} else if (key == "tile") {
|
|
||||||
item->tile = std::stof(value);
|
|
||||||
} else if (key == "[/item]") {
|
|
||||||
// No se realiza ninguna acción para esta clave
|
|
||||||
} else {
|
|
||||||
success = false;
|
|
||||||
}
|
|
||||||
} catch (const std::exception& e) {
|
|
||||||
std::cerr << "Error al asignar la clave " << key << " con valor " << value << ": " << e.what() << '\n';
|
|
||||||
success = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
return success;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
Room::Room(const std::string& room_path, std::shared_ptr<ScoreboardData> data)
|
Room::Room(const std::string& room_path, std::shared_ptr<ScoreboardData> data)
|
||||||
: data_(std::move(std::move(data))) {
|
: data_(std::move(std::move(data))) {
|
||||||
@@ -313,7 +44,7 @@ Room::Room(const std::string& room_path, std::shared_ptr<ScoreboardData> data)
|
|||||||
Screen::get()->setBorderColor(stringToColor(border_color_));
|
Screen::get()->setBorderColor(stringToColor(border_color_));
|
||||||
}
|
}
|
||||||
|
|
||||||
void Room::initializeRoom(const RoomData& room) {
|
void Room::initializeRoom(const Data& room) {
|
||||||
// Asignar valores a las variables miembro
|
// Asignar valores a las variables miembro
|
||||||
number_ = room.number;
|
number_ = room.number;
|
||||||
name_ = room.name;
|
name_ = room.name;
|
||||||
@@ -345,7 +76,7 @@ void Room::initializeRoom(const RoomData& room) {
|
|||||||
|
|
||||||
if (!ItemTracker::get()->hasBeenPicked(room.name, ITEM_POS)) {
|
if (!ItemTracker::get()->hasBeenPicked(room.name, ITEM_POS)) {
|
||||||
// Crear una copia local de los datos del item
|
// Crear una copia local de los datos del item
|
||||||
ItemData item_copy = item;
|
Item::Data item_copy = item;
|
||||||
item_copy.color1 = stringToColor(item_color1_);
|
item_copy.color1 = stringToColor(item_color1_);
|
||||||
item_copy.color2 = stringToColor(item_color2_);
|
item_copy.color2 = stringToColor(item_color2_);
|
||||||
|
|
||||||
@@ -495,21 +226,21 @@ void Room::update(float delta_time) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Devuelve la cadena del fichero de la habitación contigua segun el borde
|
// Devuelve la cadena del fichero de la habitación contigua segun el borde
|
||||||
auto Room::getRoom(RoomBorder border) -> std::string {
|
auto Room::getRoom(Border border) -> std::string {
|
||||||
switch (border) {
|
switch (border) {
|
||||||
case RoomBorder::TOP:
|
case Border::TOP:
|
||||||
return upper_room_;
|
return upper_room_;
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case RoomBorder::BOTTOM:
|
case Border::BOTTOM:
|
||||||
return lower_room_;
|
return lower_room_;
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case RoomBorder::RIGHT:
|
case Border::RIGHT:
|
||||||
return right_room_;
|
return right_room_;
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case RoomBorder::LEFT:
|
case Border::LEFT:
|
||||||
return left_room_;
|
return left_room_;
|
||||||
break;
|
break;
|
||||||
|
|
||||||
@@ -520,49 +251,49 @@ auto Room::getRoom(RoomBorder border) -> std::string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Devuelve el tipo de tile que hay en ese pixel
|
// Devuelve el tipo de tile que hay en ese pixel
|
||||||
auto Room::getTile(SDL_FPoint point) -> TileType {
|
auto Room::getTile(SDL_FPoint point) -> Tile {
|
||||||
const int POS = ((point.y / TILE_SIZE) * MAP_WIDTH) + (point.x / TILE_SIZE);
|
const int POS = ((point.y / TILE_SIZE) * MAP_WIDTH) + (point.x / TILE_SIZE);
|
||||||
return getTile(POS);
|
return getTile(POS);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Devuelve el tipo de tile que hay en ese indice
|
// Devuelve el tipo de tile que hay en ese indice
|
||||||
auto Room::getTile(int index) -> TileType {
|
auto Room::getTile(int index) -> Tile {
|
||||||
// const bool onRange = (index > -1) && (index < mapWidth * mapHeight);
|
// const bool onRange = (index > -1) && (index < mapWidth * mapHeight);
|
||||||
const bool ON_RANGE = (index > -1) && (index < (int)tile_map_.size());
|
const bool ON_RANGE = (index > -1) && (index < (int)tile_map_.size());
|
||||||
|
|
||||||
if (ON_RANGE) {
|
if (ON_RANGE) {
|
||||||
// Las filas 0-8 son de tiles t_wall
|
// Las filas 0-8 son de tiles t_wall
|
||||||
if ((tile_map_[index] >= 0) && (tile_map_[index] < 9 * tile_set_width_)) {
|
if ((tile_map_[index] >= 0) && (tile_map_[index] < 9 * tile_set_width_)) {
|
||||||
return TileType::WALL;
|
return Tile::WALL;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Las filas 9-17 son de tiles t_passable
|
// Las filas 9-17 son de tiles t_passable
|
||||||
if ((tile_map_[index] >= 9 * tile_set_width_) && (tile_map_[index] < 18 * tile_set_width_)) {
|
if ((tile_map_[index] >= 9 * tile_set_width_) && (tile_map_[index] < 18 * tile_set_width_)) {
|
||||||
return TileType::PASSABLE;
|
return Tile::PASSABLE;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Las filas 18-20 es de tiles t_animated
|
// Las filas 18-20 es de tiles t_animated
|
||||||
if ((tile_map_[index] >= 18 * tile_set_width_) && (tile_map_[index] < 21 * tile_set_width_)) {
|
if ((tile_map_[index] >= 18 * tile_set_width_) && (tile_map_[index] < 21 * tile_set_width_)) {
|
||||||
return TileType::ANIMATED;
|
return Tile::ANIMATED;
|
||||||
}
|
}
|
||||||
|
|
||||||
// La fila 21 es de tiles t_slope_r
|
// La fila 21 es de tiles t_slope_r
|
||||||
if ((tile_map_[index] >= 21 * tile_set_width_) && (tile_map_[index] < 22 * tile_set_width_)) {
|
if ((tile_map_[index] >= 21 * tile_set_width_) && (tile_map_[index] < 22 * tile_set_width_)) {
|
||||||
return TileType::SLOPE_R;
|
return Tile::SLOPE_R;
|
||||||
}
|
}
|
||||||
|
|
||||||
// La fila 22 es de tiles t_slope_l
|
// La fila 22 es de tiles t_slope_l
|
||||||
if ((tile_map_[index] >= 22 * tile_set_width_) && (tile_map_[index] < 23 * tile_set_width_)) {
|
if ((tile_map_[index] >= 22 * tile_set_width_) && (tile_map_[index] < 23 * tile_set_width_)) {
|
||||||
return TileType::SLOPE_L;
|
return Tile::SLOPE_L;
|
||||||
}
|
}
|
||||||
|
|
||||||
// La fila 23 es de tiles t_kill
|
// La fila 23 es de tiles t_kill
|
||||||
if ((tile_map_[index] >= 23 * tile_set_width_) && (tile_map_[index] < 24 * tile_set_width_)) {
|
if ((tile_map_[index] >= 23 * tile_set_width_) && (tile_map_[index] < 24 * tile_set_width_)) {
|
||||||
return TileType::KILL;
|
return Tile::KILL;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return TileType::EMPTY;
|
return Tile::EMPTY;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Indica si hay colision con un enemigo a partir de un rectangulo
|
// Indica si hay colision con un enemigo a partir de un rectangulo
|
||||||
@@ -589,7 +320,7 @@ auto Room::itemCollision(SDL_FRect& rect) -> bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Obten la coordenada de la cuesta a partir de un punto perteneciente a ese tile
|
// Obten la coordenada de la cuesta a partir de un punto perteneciente a ese tile
|
||||||
auto Room::getSlopeHeight(SDL_FPoint p, TileType slope) -> int {
|
auto Room::getSlopeHeight(SDL_FPoint p, Tile slope) -> int {
|
||||||
// Calcula la base del tile
|
// Calcula la base del tile
|
||||||
int base = ((p.y / TILE_SIZE) * TILE_SIZE) + TILE_SIZE;
|
int base = ((p.y / TILE_SIZE) * TILE_SIZE) + TILE_SIZE;
|
||||||
#ifdef _DEBUG
|
#ifdef _DEBUG
|
||||||
@@ -603,7 +334,7 @@ auto Room::getSlopeHeight(SDL_FPoint p, TileType slope) -> int {
|
|||||||
#endif
|
#endif
|
||||||
|
|
||||||
// Se resta a la base la cantidad de pixeles pos en funcion de la rampa
|
// Se resta a la base la cantidad de pixeles pos en funcion de la rampa
|
||||||
if (slope == TileType::SLOPE_R) {
|
if (slope == Tile::SLOPE_R) {
|
||||||
base -= POS + 1;
|
base -= POS + 1;
|
||||||
#ifdef _DEBUG
|
#ifdef _DEBUG
|
||||||
Debug::get()->add("BASE_R = " + std::to_string(base));
|
Debug::get()->add("BASE_R = " + std::to_string(base));
|
||||||
@@ -625,7 +356,7 @@ auto Room::collectBottomTiles() -> std::vector<int> {
|
|||||||
// Busca todos los tiles de tipo muro que no tengan debajo otro muro
|
// Busca todos los tiles de tipo muro que no tengan debajo otro muro
|
||||||
// Hay que recorrer la habitación por filas (excepto los de la última fila)
|
// Hay que recorrer la habitación por filas (excepto los de la última fila)
|
||||||
for (int i = 0; i < (int)tile_map_.size() - MAP_WIDTH; ++i) {
|
for (int i = 0; i < (int)tile_map_.size() - MAP_WIDTH; ++i) {
|
||||||
if (getTile(i) == TileType::WALL && getTile(i + MAP_WIDTH) != TileType::WALL) {
|
if (getTile(i) == Tile::WALL && getTile(i + MAP_WIDTH) != Tile::WALL) {
|
||||||
tile.push_back(i);
|
tile.push_back(i);
|
||||||
|
|
||||||
// Si llega al final de la fila, introduce un separador
|
// Si llega al final de la fila, introduce un separador
|
||||||
@@ -647,7 +378,7 @@ auto Room::collectTopTiles() -> std::vector<int> {
|
|||||||
// Busca todos los tiles de tipo muro o pasable que no tengan encima un muro
|
// Busca todos los tiles de tipo muro o pasable que no tengan encima un muro
|
||||||
// Hay que recorrer la habitación por filas (excepto los de la primera fila)
|
// Hay que recorrer la habitación por filas (excepto los de la primera fila)
|
||||||
for (int i = MAP_WIDTH; i < (int)tile_map_.size(); ++i) {
|
for (int i = MAP_WIDTH; i < (int)tile_map_.size(); ++i) {
|
||||||
if ((getTile(i) == TileType::WALL || getTile(i) == TileType::PASSABLE) && getTile(i - MAP_WIDTH) != TileType::WALL) {
|
if ((getTile(i) == Tile::WALL || getTile(i) == Tile::PASSABLE) && getTile(i - MAP_WIDTH) != Tile::WALL) {
|
||||||
tile.push_back(i);
|
tile.push_back(i);
|
||||||
|
|
||||||
// Si llega al final de la fila, introduce un separador
|
// Si llega al final de la fila, introduce un separador
|
||||||
@@ -725,7 +456,7 @@ void Room::setLeftSurfaces() {
|
|||||||
for (int i = 1; i < MAP_WIDTH; ++i) {
|
for (int i = 1; i < MAP_WIDTH; ++i) {
|
||||||
for (int j = 0; j < MAP_HEIGHT; ++j) {
|
for (int j = 0; j < MAP_HEIGHT; ++j) {
|
||||||
const int POS = ((j * MAP_WIDTH) + i);
|
const int POS = ((j * MAP_WIDTH) + i);
|
||||||
if (getTile(POS) == TileType::WALL && getTile(POS - 1) != TileType::WALL) {
|
if (getTile(POS) == Tile::WALL && getTile(POS - 1) != Tile::WALL) {
|
||||||
tile.push_back(POS);
|
tile.push_back(POS);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -765,7 +496,7 @@ void Room::setRightSurfaces() {
|
|||||||
for (int i = 0; i < MAP_WIDTH - 1; ++i) {
|
for (int i = 0; i < MAP_WIDTH - 1; ++i) {
|
||||||
for (int j = 0; j < MAP_HEIGHT; ++j) {
|
for (int j = 0; j < MAP_HEIGHT; ++j) {
|
||||||
const int POS = ((j * MAP_WIDTH) + i);
|
const int POS = ((j * MAP_WIDTH) + i);
|
||||||
if (getTile(POS) == TileType::WALL && getTile(POS + 1) != TileType::WALL) {
|
if (getTile(POS) == Tile::WALL && getTile(POS + 1) != Tile::WALL) {
|
||||||
tile.push_back(POS);
|
tile.push_back(POS);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -801,7 +532,7 @@ void Room::setLeftSlopes() {
|
|||||||
// Recorre la habitación entera por filas buscando tiles de tipo t_slope_l
|
// Recorre la habitación entera por filas buscando tiles de tipo t_slope_l
|
||||||
std::vector<int> found;
|
std::vector<int> found;
|
||||||
for (int i = 0; i < (int)tile_map_.size(); ++i) {
|
for (int i = 0; i < (int)tile_map_.size(); ++i) {
|
||||||
if (getTile(i) == TileType::SLOPE_L) {
|
if (getTile(i) == Tile::SLOPE_L) {
|
||||||
found.push_back(i);
|
found.push_back(i);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -836,7 +567,7 @@ void Room::setRightSlopes() {
|
|||||||
// Recorre la habitación entera por filas buscando tiles de tipo t_slope_r
|
// Recorre la habitación entera por filas buscando tiles de tipo t_slope_r
|
||||||
std::vector<int> found;
|
std::vector<int> found;
|
||||||
for (int i = 0; i < (int)tile_map_.size(); ++i) {
|
for (int i = 0; i < (int)tile_map_.size(); ++i) {
|
||||||
if (getTile(i) == TileType::SLOPE_R) {
|
if (getTile(i) == Tile::SLOPE_R) {
|
||||||
found.push_back(i);
|
found.push_back(i);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -874,7 +605,7 @@ auto Room::collectAnimatedTiles() -> std::vector<int> {
|
|||||||
// Busca todos los tiles de tipo animado
|
// Busca todos los tiles de tipo animado
|
||||||
// Hay que recorrer la habitación por filas (excepto los de la primera fila)
|
// Hay que recorrer la habitación por filas (excepto los de la primera fila)
|
||||||
for (int i = MAP_WIDTH; i < (int)tile_map_.size(); ++i) {
|
for (int i = MAP_WIDTH; i < (int)tile_map_.size(); ++i) {
|
||||||
if (getTile(i) == TileType::ANIMATED) {
|
if (getTile(i) == Tile::ANIMATED) {
|
||||||
tile.push_back(i);
|
tile.push_back(i);
|
||||||
|
|
||||||
// Si llega al final de la fila, introduce un separador
|
// Si llega al final de la fila, introduce un separador
|
||||||
@@ -901,7 +632,7 @@ void Room::setAutoSurfaces() {
|
|||||||
void Room::setAnimatedTiles() {
|
void Room::setAnimatedTiles() {
|
||||||
// Recorre la habitación entera por filas buscando tiles de tipo t_animated
|
// Recorre la habitación entera por filas buscando tiles de tipo t_animated
|
||||||
for (int i = 0; i < (int)tile_map_.size(); ++i) {
|
for (int i = 0; i < (int)tile_map_.size(); ++i) {
|
||||||
if (getTile(i) == TileType::ANIMATED) {
|
if (getTile(i) == Tile::ANIMATED) {
|
||||||
// La i es la ubicación
|
// La i es la ubicación
|
||||||
const int X = (i % MAP_WIDTH) * TILE_SIZE;
|
const int X = (i % MAP_WIDTH) * TILE_SIZE;
|
||||||
const int Y = (i / MAP_WIDTH) * TILE_SIZE;
|
const int Y = (i / MAP_WIDTH) * TILE_SIZE;
|
||||||
@@ -1080,3 +811,272 @@ void Room::initRoomSurfaces() {
|
|||||||
setRightSlopes();
|
setRightSlopes();
|
||||||
setAutoSurfaces();
|
setAutoSurfaces();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Asigna variables a una estructura RoomData
|
||||||
|
auto Room::setRoom(Data* room, const std::string& key, const std::string& value) -> bool {
|
||||||
|
// Indicador de éxito en la asignación
|
||||||
|
bool success = true;
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (key == "tileMapFile") {
|
||||||
|
room->tile_map_file = value;
|
||||||
|
} else if (key == "name") {
|
||||||
|
room->name = value;
|
||||||
|
} else if (key == "bgColor") {
|
||||||
|
room->bg_color = value;
|
||||||
|
} else if (key == "border") {
|
||||||
|
room->border_color = value;
|
||||||
|
} else if (key == "itemColor1") {
|
||||||
|
room->item_color1 = value;
|
||||||
|
} else if (key == "itemColor2") {
|
||||||
|
room->item_color2 = value;
|
||||||
|
} else if (key == "tileSetFile") {
|
||||||
|
room->tile_set_file = value;
|
||||||
|
} else if (key == "roomUp") {
|
||||||
|
room->upper_room = value;
|
||||||
|
} else if (key == "roomDown") {
|
||||||
|
room->lower_room = value;
|
||||||
|
} else if (key == "roomLeft") {
|
||||||
|
room->left_room = value;
|
||||||
|
} else if (key == "roomRight") {
|
||||||
|
room->right_room = value;
|
||||||
|
} else if (key == "autoSurface") {
|
||||||
|
room->conveyor_belt_direction = (value == "right") ? 1 : -1;
|
||||||
|
} else if (key.empty() || key.substr(0, 1) == "#") {
|
||||||
|
// No se realiza ninguna acción para estas claves
|
||||||
|
} else {
|
||||||
|
success = false;
|
||||||
|
}
|
||||||
|
} catch (const std::exception& e) {
|
||||||
|
std::cerr << "Error al asignar la clave " << key << " con valor " << value << ": " << e.what() << '\n';
|
||||||
|
success = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return success;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Asigna variables a una estructura EnemyData
|
||||||
|
auto Room::setEnemy(Enemy::Data* enemy, const std::string& key, const std::string& value) -> bool {
|
||||||
|
// Indicador de éxito en la asignación
|
||||||
|
bool success = true;
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (key == "tileSetFile") {
|
||||||
|
enemy->surface_path = value;
|
||||||
|
} else if (key == "animation") {
|
||||||
|
enemy->animation_path = value;
|
||||||
|
} else if (key == "width") {
|
||||||
|
enemy->w = std::stoi(value);
|
||||||
|
} else if (key == "height") {
|
||||||
|
enemy->h = std::stoi(value);
|
||||||
|
} else if (key == "x") {
|
||||||
|
enemy->x = std::stof(value) * BLOCK;
|
||||||
|
} else if (key == "y") {
|
||||||
|
enemy->y = std::stof(value) * BLOCK;
|
||||||
|
} else if (key == "vx") {
|
||||||
|
enemy->vx = std::stof(value);
|
||||||
|
} else if (key == "vy") {
|
||||||
|
enemy->vy = std::stof(value);
|
||||||
|
} else if (key == "x1") {
|
||||||
|
enemy->x1 = std::stoi(value) * BLOCK;
|
||||||
|
} else if (key == "x2") {
|
||||||
|
enemy->x2 = std::stoi(value) * BLOCK;
|
||||||
|
} else if (key == "y1") {
|
||||||
|
enemy->y1 = std::stoi(value) * BLOCK;
|
||||||
|
} else if (key == "y2") {
|
||||||
|
enemy->y2 = std::stoi(value) * BLOCK;
|
||||||
|
} else if (key == "flip") {
|
||||||
|
enemy->flip = stringToBool(value);
|
||||||
|
} else if (key == "mirror") {
|
||||||
|
enemy->mirror = stringToBool(value);
|
||||||
|
} else if (key == "color") {
|
||||||
|
enemy->color = value;
|
||||||
|
} else if (key == "frame") {
|
||||||
|
enemy->frame = std::stoi(value);
|
||||||
|
} else if (key == "[/enemy]" || key == "tileSetFile" || key.substr(0, 1) == "#") {
|
||||||
|
// No se realiza ninguna acción para estas claves
|
||||||
|
} else {
|
||||||
|
success = false;
|
||||||
|
}
|
||||||
|
} catch (const std::exception& e) {
|
||||||
|
std::cerr << "Error al asignar la clave " << key << " con valor " << value << ": " << e.what() << '\n';
|
||||||
|
success = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return success;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Asigna variables a una estructura ItemData
|
||||||
|
auto Room::setItem(Item::Data* item, const std::string& key, const std::string& value) -> bool {
|
||||||
|
// Indicador de éxito en la asignación
|
||||||
|
bool success = true;
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (key == "tileSetFile") {
|
||||||
|
item->tile_set_file = value;
|
||||||
|
} else if (key == "counter") {
|
||||||
|
item->counter = std::stoi(value);
|
||||||
|
} else if (key == "x") {
|
||||||
|
item->x = std::stof(value) * BLOCK;
|
||||||
|
} else if (key == "y") {
|
||||||
|
item->y = std::stof(value) * BLOCK;
|
||||||
|
} else if (key == "tile") {
|
||||||
|
item->tile = std::stof(value);
|
||||||
|
} else if (key == "[/item]") {
|
||||||
|
// No se realiza ninguna acción para esta clave
|
||||||
|
} else {
|
||||||
|
success = false;
|
||||||
|
}
|
||||||
|
} catch (const std::exception& e) {
|
||||||
|
std::cerr << "Error al asignar la clave " << key << " con valor " << value << ": " << e.what() << '\n';
|
||||||
|
success = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return success;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Carga las variables y texturas desde un fichero de mapa de tiles
|
||||||
|
auto Room::loadRoomTileFile(const std::string& file_path, bool verbose) -> std::vector<int> {
|
||||||
|
std::vector<int> tile_map_file;
|
||||||
|
const std::string FILENAME = file_path.substr(file_path.find_last_of("\\/") + 1);
|
||||||
|
std::ifstream file(file_path);
|
||||||
|
|
||||||
|
// El fichero se puede abrir
|
||||||
|
if (file.good()) {
|
||||||
|
std::string line;
|
||||||
|
// Procesa el fichero linea a linea
|
||||||
|
while (std::getline(file, line)) { // Lee el fichero linea a linea
|
||||||
|
if (line.find("data encoding") != std::string::npos) {
|
||||||
|
// Lee la primera linea
|
||||||
|
std::getline(file, line);
|
||||||
|
while (line != "</data>") { // Procesa lineas mientras haya
|
||||||
|
std::stringstream ss(line);
|
||||||
|
std::string tmp;
|
||||||
|
while (getline(ss, tmp, ',')) {
|
||||||
|
tile_map_file.push_back(std::stoi(tmp) - 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Lee la siguiente linea
|
||||||
|
std::getline(file, line);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Cierra el fichero
|
||||||
|
if (verbose) {
|
||||||
|
std::cout << "TileMap loaded: " << FILENAME.c_str() << '\n';
|
||||||
|
}
|
||||||
|
file.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
else { // El fichero no se puede abrir
|
||||||
|
if (verbose) {
|
||||||
|
std::cout << "Warning: Unable to open " << FILENAME.c_str() << " file" << '\n';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return tile_map_file;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Carga las variables desde un fichero de mapa
|
||||||
|
auto Room::loadRoomFile(const std::string& file_path, bool verbose) -> Data {
|
||||||
|
Data room;
|
||||||
|
room.item_color1 = "yellow";
|
||||||
|
room.item_color2 = "magenta";
|
||||||
|
room.conveyor_belt_direction = 1;
|
||||||
|
|
||||||
|
const std::string FILE_NAME = file_path.substr(file_path.find_last_of("\\/") + 1);
|
||||||
|
room.number = FILE_NAME.substr(0, FILE_NAME.find_last_of('.'));
|
||||||
|
|
||||||
|
std::ifstream file(file_path);
|
||||||
|
|
||||||
|
// El fichero se puede abrir
|
||||||
|
if (file.good()) {
|
||||||
|
std::string line;
|
||||||
|
// Procesa el fichero linea a linea
|
||||||
|
while (std::getline(file, line)) {
|
||||||
|
// Si la linea contiene el texto [enemy] se realiza el proceso de carga de un enemigo
|
||||||
|
if (line == "[enemy]") {
|
||||||
|
room.enemies.push_back(loadEnemyFromFile(file, FILE_NAME, verbose));
|
||||||
|
}
|
||||||
|
// Si la linea contiene el texto [item] se realiza el proceso de carga de un item
|
||||||
|
else if (line == "[item]") {
|
||||||
|
room.items.push_back(loadItemFromFile(file, FILE_NAME, verbose));
|
||||||
|
}
|
||||||
|
// En caso contrario se parsea el fichero para buscar las variables y los valores
|
||||||
|
else {
|
||||||
|
auto [key, value] = parseKeyValue(line);
|
||||||
|
if (!setRoom(&room, key, value)) {
|
||||||
|
logUnknownParameter(FILE_NAME, key, verbose);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Cierra el fichero
|
||||||
|
if (verbose) {
|
||||||
|
std::cout << "Room loaded: " << FILE_NAME.c_str() << '\n';
|
||||||
|
}
|
||||||
|
file.close();
|
||||||
|
}
|
||||||
|
// El fichero no se puede abrir
|
||||||
|
else {
|
||||||
|
std::cout << "Warning: Unable to open " << FILE_NAME.c_str() << " file" << '\n';
|
||||||
|
}
|
||||||
|
|
||||||
|
return room;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parsea una línea en key y value separados por '='
|
||||||
|
auto Room::parseKeyValue(const std::string& line) -> std::pair<std::string, std::string> {
|
||||||
|
int pos = line.find('=');
|
||||||
|
std::string key = line.substr(0, pos);
|
||||||
|
std::string value = line.substr(pos + 1, line.length());
|
||||||
|
return {key, value};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Muestra un warning de parámetro desconocido
|
||||||
|
void Room::logUnknownParameter(const std::string& file_name, const std::string& key, bool verbose) {
|
||||||
|
if (verbose) {
|
||||||
|
std::cout << "Warning: file " << file_name.c_str() << "\n, unknown parameter \"" << key.c_str() << "\"" << '\n';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Carga un bloque [enemy]...[/enemy] desde un archivo
|
||||||
|
auto Room::loadEnemyFromFile(std::ifstream& file, const std::string& file_name, bool verbose) -> Enemy::Data {
|
||||||
|
Enemy::Data enemy;
|
||||||
|
enemy.flip = false;
|
||||||
|
enemy.mirror = false;
|
||||||
|
enemy.frame = -1;
|
||||||
|
|
||||||
|
std::string line;
|
||||||
|
do {
|
||||||
|
std::getline(file, line);
|
||||||
|
auto [key, value] = parseKeyValue(line);
|
||||||
|
|
||||||
|
if (!setEnemy(&enemy, key, value)) {
|
||||||
|
logUnknownParameter(file_name, key, verbose);
|
||||||
|
}
|
||||||
|
} while (line != "[/enemy]");
|
||||||
|
|
||||||
|
return enemy;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Carga un bloque [item]...[/item] desde un archivo
|
||||||
|
auto Room::loadItemFromFile(std::ifstream& file, const std::string& file_name, bool verbose) -> Item::Data {
|
||||||
|
Item::Data item;
|
||||||
|
item.counter = 0;
|
||||||
|
item.color1 = stringToColor("yellow");
|
||||||
|
item.color2 = stringToColor("magenta");
|
||||||
|
|
||||||
|
std::string line;
|
||||||
|
do {
|
||||||
|
std::getline(file, line);
|
||||||
|
auto [key, value] = parseKeyValue(line);
|
||||||
|
|
||||||
|
if (!setItem(&item, key, value)) {
|
||||||
|
logUnknownParameter(file_name, key, verbose);
|
||||||
|
}
|
||||||
|
} while (line != "[/item]");
|
||||||
|
|
||||||
|
return item;
|
||||||
|
}
|
||||||
@@ -13,7 +13,17 @@ class SurfaceSprite; // lines 12-12
|
|||||||
class Surface; // lines 13-13
|
class Surface; // lines 13-13
|
||||||
struct ScoreboardData; // lines 15-15
|
struct ScoreboardData; // lines 15-15
|
||||||
|
|
||||||
enum class TileType {
|
class Room {
|
||||||
|
public:
|
||||||
|
// -- Enumeraciones y estructuras ---
|
||||||
|
enum class Border : int {
|
||||||
|
TOP = 0,
|
||||||
|
RIGHT = 1,
|
||||||
|
BOTTOM = 2,
|
||||||
|
LEFT = 3
|
||||||
|
};
|
||||||
|
|
||||||
|
enum class Tile {
|
||||||
EMPTY,
|
EMPTY,
|
||||||
WALL,
|
WALL,
|
||||||
PASSABLE,
|
PASSABLE,
|
||||||
@@ -21,233 +31,134 @@ enum class TileType {
|
|||||||
SLOPE_R,
|
SLOPE_R,
|
||||||
KILL,
|
KILL,
|
||||||
ANIMATED
|
ANIMATED
|
||||||
};
|
};
|
||||||
|
|
||||||
enum class RoomBorder : int {
|
struct AnimatedTile {
|
||||||
TOP = 0,
|
std::shared_ptr<SurfaceSprite> sprite{}; // SurfaceSprite para dibujar el tile
|
||||||
RIGHT = 1,
|
int x_orig = 0; // Posición X donde se encuentra el primer tile de la animación en la tilesheet
|
||||||
BOTTOM = 2,
|
};
|
||||||
LEFT = 3
|
|
||||||
};
|
|
||||||
|
|
||||||
struct AnimatedTile {
|
struct Data {
|
||||||
std::shared_ptr<SurfaceSprite> sprite; // SSprite para dibujar el tile
|
std::string number{}; // Numero de la habitación
|
||||||
int x_orig; // Poicion X donde se encuentra el primer tile de la animacion en la tilesheet
|
std::string name{}; // Nombre de la habitación
|
||||||
};
|
std::string bg_color{}; // Color de fondo de la habitación
|
||||||
|
std::string border_color{}; // Color del borde de la pantalla
|
||||||
|
std::string item_color1{}; // Color 1 para los items de la habitación
|
||||||
|
std::string item_color2{}; // Color 2 para los items de la habitación
|
||||||
|
std::string upper_room{}; // Identificador de la habitación que se encuentra arriba
|
||||||
|
std::string lower_room{}; // Identificador de la habitación que se encuentra abajo
|
||||||
|
std::string left_room{}; // Identificador de la habitación que se encuentra a la izquierda
|
||||||
|
std::string right_room{}; // Identificador de la habitación que se encuentra a la derecha
|
||||||
|
std::string tile_set_file{}; // Imagen con los gráficos para la habitación
|
||||||
|
std::string tile_map_file{}; // Fichero con el mapa de índices de tile
|
||||||
|
int conveyor_belt_direction = 0; // Sentido en el que arrastran las superficies automáticas de la habitación
|
||||||
|
std::vector<int> tile_map{}; // Índice de los tiles a dibujar en la habitación
|
||||||
|
std::vector<Enemy::Data> enemies{}; // Listado con los enemigos de la habitación
|
||||||
|
std::vector<Item::Data> items{}; // Listado con los items que hay en la habitación
|
||||||
|
|
||||||
struct RoomData {
|
// Constructor por defecto
|
||||||
std::string number; // Numero de la habitación
|
Data() = default;
|
||||||
std::string name; // Nombre de la habitación
|
};
|
||||||
std::string bg_color; // Color de fondo de la habitación
|
|
||||||
std::string border_color; // Color del borde de la pantalla
|
|
||||||
std::string item_color1; // Color 1 para los items de la habitación
|
|
||||||
std::string item_color2; // Color 2 para los items de la habitación
|
|
||||||
std::string upper_room; // Identificador de la habitación que se encuentra arriba
|
|
||||||
std::string lower_room; // Identificador de la habitación que se encuentra abajp
|
|
||||||
std::string left_room; // Identificador de la habitación que se encuentra a la izquierda
|
|
||||||
std::string right_room; // Identificador de la habitación que se encuentra a la derecha
|
|
||||||
std::string tile_set_file; // Imagen con los graficos para la habitación
|
|
||||||
std::string tile_map_file; // Fichero con el mapa de indices de tile
|
|
||||||
int conveyor_belt_direction; // Sentido en el que arrastran las superficies automáticas de la habitación
|
|
||||||
std::vector<int> tile_map; // Indice de los tiles a dibujar en la habitación
|
|
||||||
std::vector<EnemyData> enemies; // Listado con los enemigos de la habitación
|
|
||||||
std::vector<ItemData> items; // Listado con los items que hay en la habitación
|
|
||||||
};
|
|
||||||
|
|
||||||
// Carga las variables desde un fichero de mapa
|
// Constructor y destructor
|
||||||
auto loadRoomFile(const std::string& file_path, bool verbose = false) -> RoomData;
|
Room(const std::string& room_path, std::shared_ptr<ScoreboardData> data);
|
||||||
|
~Room() = default;
|
||||||
|
|
||||||
// Carga las variables y texturas desde un fichero de mapa de tiles
|
// --- Funciones ---
|
||||||
auto loadRoomTileFile(const std::string& file_path, bool verbose = false) -> std::vector<int>;
|
[[nodiscard]] auto getName() const -> const std::string& { return name_; } // Devuelve el nombre de la habitación
|
||||||
|
[[nodiscard]] auto getBGColor() const -> Uint8 { return stringToColor(bg_color_); } // Devuelve el color de la habitación
|
||||||
|
[[nodiscard]] auto getBorderColor() const -> Uint8 { return stringToColor(border_color_); } // Devuelve el color del borde
|
||||||
|
void renderMap(); // Dibuja el mapa en pantalla
|
||||||
|
void renderEnemies(); // Dibuja los enemigos en pantalla
|
||||||
|
void renderItems(); // Dibuja los objetos en pantalla
|
||||||
|
void update(float delta_time); // Actualiza las variables y objetos de la habitación
|
||||||
|
auto getRoom(Border border) -> std::string; // Devuelve la cadena del fichero de la habitación contigua segun el borde
|
||||||
|
auto getTile(SDL_FPoint point) -> Tile; // Devuelve el tipo de tile que hay en ese pixel
|
||||||
|
auto enemyCollision(SDL_FRect& rect) -> bool; // Indica si hay colision con un enemigo a partir de un rectangulo
|
||||||
|
auto itemCollision(SDL_FRect& rect) -> bool; // Indica si hay colision con un objeto a partir de un rectangulo
|
||||||
|
static auto getTileSize() -> int { return TILE_SIZE; } // Obten el tamaño del tile
|
||||||
|
static auto getSlopeHeight(SDL_FPoint p, Tile slope) -> int; // Obten la coordenada de la cuesta a partir de un punto perteneciente a ese tile
|
||||||
|
auto checkRightSurfaces(SDL_FRect* rect) -> int; // Comprueba las colisiones
|
||||||
|
auto checkLeftSurfaces(SDL_FRect* rect) -> int; // Comprueba las colisiones
|
||||||
|
auto checkTopSurfaces(SDL_FRect* rect) -> int; // Comprueba las colisiones
|
||||||
|
auto checkBottomSurfaces(SDL_FRect* rect) -> int; // Comprueba las colisiones
|
||||||
|
auto checkAutoSurfaces(SDL_FRect* rect) -> int; // Comprueba las colisiones
|
||||||
|
auto checkTopSurfaces(SDL_FPoint* p) -> bool; // Comprueba las colisiones
|
||||||
|
auto checkAutoSurfaces(SDL_FPoint* p) -> bool; // Comprueba las colisiones
|
||||||
|
auto checkLeftSlopes(const LineVertical* line) -> int; // Comprueba las colisiones
|
||||||
|
auto checkLeftSlopes(SDL_FPoint* p) -> bool; // Comprueba las colisiones
|
||||||
|
auto checkRightSlopes(const LineVertical* line) -> int; // Comprueba las colisiones
|
||||||
|
auto checkRightSlopes(SDL_FPoint* p) -> bool; // Comprueba las colisiones
|
||||||
|
void setPaused(bool value) { is_paused_ = value; }; // Pone el mapa en modo pausa
|
||||||
|
[[nodiscard]] auto getAutoSurfaceDirection() const -> int { return conveyor_belt_direction_; } // Obten la direccion de las superficies automaticas
|
||||||
|
static auto loadRoomFile(const std::string& file_path, bool verbose = false) -> Data; // Carga las variables desde un fichero de mapa
|
||||||
|
static auto loadRoomTileFile(const std::string& file_path, bool verbose = false) -> std::vector<int>; // Carga las variables y texturas desde un fichero de mapa de tiles
|
||||||
|
|
||||||
// Asigna variables a una estructura RoomData
|
|
||||||
auto setRoom(RoomData* room, const std::string& key, const std::string& value) -> bool;
|
|
||||||
|
|
||||||
// Asigna variables a una estructura EnemyData
|
|
||||||
auto setEnemy(EnemyData* enemy, const std::string& key, const std::string& value) -> bool;
|
|
||||||
|
|
||||||
// Asigna variables a una estructura ItemData
|
|
||||||
auto setItem(ItemData* item, const std::string& key, const std::string& value) -> bool;
|
|
||||||
|
|
||||||
class Room {
|
|
||||||
private:
|
private:
|
||||||
// Constantes
|
// --- Constantes ---
|
||||||
static constexpr int TILE_SIZE = 8; // Ancho del tile en pixels
|
static constexpr int TILE_SIZE = 8; // Ancho del tile en pixels
|
||||||
static constexpr int MAP_WIDTH = 32; // Ancho del mapa en tiles
|
static constexpr int MAP_WIDTH = 32; // Ancho del mapa en tiles
|
||||||
static constexpr int MAP_HEIGHT = 16; // Alto del mapa en tiles
|
static constexpr int MAP_HEIGHT = 16; // Alto del mapa en tiles
|
||||||
|
|
||||||
// Objetos y punteros
|
// --- Objetos y punteros ---
|
||||||
std::vector<std::shared_ptr<Enemy>> enemies_; // Listado con los enemigos de la habitación
|
std::vector<std::shared_ptr<Enemy>> enemies_; // Listado con los enemigos de la habitación
|
||||||
std::vector<std::shared_ptr<Item>> items_; // Listado con los items que hay en la habitación
|
std::vector<std::shared_ptr<Item>> items_; // Listado con los items que hay en la habitación
|
||||||
std::shared_ptr<Surface> surface_; // Textura con los graficos de la habitación
|
std::shared_ptr<Surface> surface_; // Textura con los graficos de la habitación
|
||||||
std::shared_ptr<Surface> map_surface_; // Textura para dibujar el mapa de la habitación
|
std::shared_ptr<Surface> map_surface_; // Textura para dibujar el mapa de la habitación
|
||||||
std::shared_ptr<ScoreboardData> data_; // Puntero a los datos del marcador
|
std::shared_ptr<ScoreboardData> data_; // Puntero a los datos del marcador
|
||||||
|
|
||||||
// Variables
|
// --- Variables ---
|
||||||
std::string number_; // Numero de la habitación
|
std::string number_{}; // Numero de la habitación
|
||||||
std::string name_; // Nombre de la habitación
|
std::string name_{}; // Nombre de la habitación
|
||||||
std::string bg_color_; // Color de fondo de la habitación
|
std::string bg_color_{}; // Color de fondo de la habitación
|
||||||
std::string border_color_; // Color del borde de la pantalla
|
std::string border_color_{}; // Color del borde de la pantalla
|
||||||
std::string item_color1_; // Color 1 para los items de la habitación
|
std::string item_color1_{}; // Color 1 para los items de la habitación
|
||||||
std::string item_color2_; // Color 2 para los items de la habitación
|
std::string item_color2_{}; // Color 2 para los items de la habitación
|
||||||
std::string upper_room_; // Identificador de la habitación que se encuentra arriba
|
std::string upper_room_{}; // Identificador de la habitación que se encuentra arriba
|
||||||
std::string lower_room_; // Identificador de la habitación que se encuentra abajp
|
std::string lower_room_{}; // Identificador de la habitación que se encuentra abajp
|
||||||
std::string left_room_; // Identificador de la habitación que se encuentra a la izquierda
|
std::string left_room_{}; // Identificador de la habitación que se encuentra a la izquierda
|
||||||
std::string right_room_; // Identificador de la habitación que se encuentra a la derecha
|
std::string right_room_{}; // Identificador de la habitación que se encuentra a la derecha
|
||||||
std::string tile_set_file_; // Imagen con los graficos para la habitación
|
std::string tile_set_file_{}; // Imagen con los graficos para la habitación
|
||||||
std::string tile_map_file_; // Fichero con el mapa de indices de tile
|
std::string tile_map_file_{}; // Fichero con el mapa de indices de tile
|
||||||
std::vector<int> tile_map_; // Indice de los tiles a dibujar en la habitación
|
std::vector<int> tile_map_{}; // Indice de los tiles a dibujar en la habitación
|
||||||
int conveyor_belt_direction_; // Sentido en el que arrastran las superficies automáticas de la habitación
|
int conveyor_belt_direction_ = 0; // Sentido en el que arrastran las superficies automáticas de la habitación
|
||||||
std::vector<LineHorizontal> bottom_floors_; // Lista con las superficies inferiores de la habitación
|
std::vector<LineHorizontal> bottom_floors_{}; // Lista con las superficies inferiores de la habitación
|
||||||
std::vector<LineHorizontal> top_floors_; // Lista con las superficies superiores de la habitación
|
std::vector<LineHorizontal> top_floors_{}; // Lista con las superficies superiores de la habitación
|
||||||
std::vector<LineVertical> left_walls_; // Lista con las superficies laterales de la parte izquierda de la habitación
|
std::vector<LineVertical> left_walls_{}; // Lista con las superficies laterales de la parte izquierda de la habitación
|
||||||
std::vector<LineVertical> right_walls_; // Lista con las superficies laterales de la parte derecha de la habitación
|
std::vector<LineVertical> right_walls_{}; // Lista con las superficies laterales de la parte derecha de la habitación
|
||||||
std::vector<LineDiagonal> left_slopes_; // Lista con todas las rampas que suben hacia la izquierda
|
std::vector<LineDiagonal> left_slopes_{}; // Lista con todas las rampas que suben hacia la izquierda
|
||||||
std::vector<LineDiagonal> right_slopes_; // Lista con todas las rampas que suben hacia la derecha
|
std::vector<LineDiagonal> right_slopes_{}; // Lista con todas las rampas que suben hacia la derecha
|
||||||
int counter_; // Contador para lo que haga falta
|
int counter_ = 0; // Contador para lo que haga falta
|
||||||
bool is_paused_; // Indica si el mapa esta en modo pausa
|
bool is_paused_ = false; // Indica si el mapa esta en modo pausa
|
||||||
std::vector<AnimatedTile> animated_tiles_; // Vector con los indices de tiles animados
|
std::vector<AnimatedTile> animated_tiles_{}; // Vector con los indices de tiles animados
|
||||||
std::vector<LineHorizontal> conveyor_belt_floors_; // Lista con las superficies automaticas de la habitación
|
std::vector<LineHorizontal> conveyor_belt_floors_{}; // Lista con las superficies automaticas de la habitación
|
||||||
int tile_set_width_; // Ancho del tileset en tiles
|
int tile_set_width_ = 0; // Ancho del tileset en tiles
|
||||||
|
|
||||||
void initializeRoom(const RoomData& room);
|
// --- Funciones ---
|
||||||
|
void initializeRoom(const Data& room); // Inicializa los valores
|
||||||
// Pinta el mapa de la habitación en la textura
|
void fillMapTexture(); // Pinta el mapa de la habitación en la textura
|
||||||
void fillMapTexture();
|
auto collectBottomTiles() -> std::vector<int>; // Helper para recopilar tiles inferiores
|
||||||
|
auto collectTopTiles() -> std::vector<int>; // Helper para recopilar tiles superiores
|
||||||
// Helper para recopilar tiles inferiores
|
auto collectAnimatedTiles() -> std::vector<int>; // Helper para recopilar tiles animados (para superficies automaticas)
|
||||||
auto collectBottomTiles() -> std::vector<int>;
|
static void buildHorizontalLines(const std::vector<int>& tiles, std::vector<LineHorizontal>& lines, bool is_bottom_surface); // Helper para construir lineas horizontales a partir de tiles consecutivos
|
||||||
|
void setBottomSurfaces(); // Calcula las superficies inferiores
|
||||||
// Helper para recopilar tiles superiores
|
void setTopSurfaces(); // Calcula las superficies superiores
|
||||||
auto collectTopTiles() -> std::vector<int>;
|
void setLeftSurfaces(); // Calcula las superficies laterales izquierdas
|
||||||
|
void setRightSurfaces(); // Calcula las superficies laterales derechas
|
||||||
// Helper para recopilar tiles animados (para superficies automaticas)
|
void setLeftSlopes(); // Encuentra todas las rampas que suben hacia la izquierda
|
||||||
auto collectAnimatedTiles() -> std::vector<int>;
|
void setRightSlopes(); // Encuentra todas las rampas que suben hacia la derecha
|
||||||
|
void setAutoSurfaces(); // Calcula las superficies automaticas
|
||||||
// Helper para construir lineas horizontales a partir de tiles consecutivos
|
void setAnimatedTiles(); // Localiza todos los tiles animados de la habitación
|
||||||
static void buildHorizontalLines(const std::vector<int>& tiles, std::vector<LineHorizontal>& lines, bool is_bottom_surface);
|
void updateAnimatedTiles(); // Actualiza los tiles animados
|
||||||
|
void renderAnimatedTiles(); // Pinta los tiles animados en pantalla
|
||||||
// Calcula las superficies inferiores
|
auto getTile(int index) -> Tile; // Devuelve el tipo de tile que hay en ese indice
|
||||||
void setBottomSurfaces();
|
void openTheJail(); // Abre la jail para poder entrar
|
||||||
|
void initRoomSurfaces(); // Inicializa las superficies de colision
|
||||||
// Calcula las superficies superiores
|
static auto setRoom(Data* room, const std::string& key, const std::string& value) -> bool; // Asigna variables a una estructura RoomData
|
||||||
void setTopSurfaces();
|
static auto setEnemy(Enemy::Data* enemy, const std::string& key, const std::string& value) -> bool; // Asigna variables a una estructura EnemyData
|
||||||
|
static auto setItem(Item::Data* item, const std::string& key, const std::string& value) -> bool; // Asigna variables a una estructura ItemData
|
||||||
// Calcula las superficies laterales izquierdas
|
static auto parseKeyValue(const std::string& line) -> std::pair<std::string, std::string>;
|
||||||
void setLeftSurfaces();
|
static void logUnknownParameter(const std::string& file_name, const std::string& key, bool verbose);
|
||||||
|
static auto loadEnemyFromFile(std::ifstream& file, const std::string& file_name, bool verbose) -> Enemy::Data;
|
||||||
// Calcula las superficies laterales derechas
|
static auto loadItemFromFile(std::ifstream& file, const std::string& file_name, bool verbose) -> Item::Data;
|
||||||
void setRightSurfaces();
|
|
||||||
|
|
||||||
// Encuentra todas las rampas que suben hacia la izquierda
|
|
||||||
void setLeftSlopes();
|
|
||||||
|
|
||||||
// Encuentra todas las rampas que suben hacia la derecha
|
|
||||||
void setRightSlopes();
|
|
||||||
|
|
||||||
// Calcula las superficies automaticas
|
|
||||||
void setAutoSurfaces();
|
|
||||||
|
|
||||||
// Localiza todos los tiles animados de la habitación
|
|
||||||
void setAnimatedTiles();
|
|
||||||
|
|
||||||
// Actualiza los tiles animados
|
|
||||||
void updateAnimatedTiles();
|
|
||||||
|
|
||||||
// Pinta los tiles animados en pantalla
|
|
||||||
void renderAnimatedTiles();
|
|
||||||
|
|
||||||
// Devuelve el tipo de tile que hay en ese indice
|
|
||||||
auto getTile(int index) -> TileType;
|
|
||||||
|
|
||||||
// Abre la jail para poder entrar
|
|
||||||
void openTheJail();
|
|
||||||
|
|
||||||
// Inicializa las superficies de colision
|
|
||||||
void initRoomSurfaces();
|
|
||||||
|
|
||||||
public:
|
|
||||||
// Constructor
|
|
||||||
Room(const std::string& room_path, std::shared_ptr<ScoreboardData> data);
|
|
||||||
|
|
||||||
// Destructor
|
|
||||||
~Room() = default;
|
|
||||||
|
|
||||||
// Devuelve el nombre de la habitación
|
|
||||||
[[nodiscard]] auto getName() const -> const std::string& { return name_; }
|
|
||||||
|
|
||||||
// Devuelve el color de la habitación
|
|
||||||
[[nodiscard]] auto getBGColor() const -> Uint8 { return stringToColor(bg_color_); }
|
|
||||||
|
|
||||||
// Devuelve el color del borde
|
|
||||||
[[nodiscard]] auto getBorderColor() const -> Uint8 { return stringToColor(border_color_); }
|
|
||||||
|
|
||||||
// Dibuja el mapa en pantalla
|
|
||||||
void renderMap();
|
|
||||||
|
|
||||||
// Dibuja los enemigos en pantalla
|
|
||||||
void renderEnemies();
|
|
||||||
|
|
||||||
// Dibuja los objetos en pantalla
|
|
||||||
void renderItems();
|
|
||||||
|
|
||||||
// Actualiza las variables y objetos de la habitación
|
|
||||||
void update(float delta_time);
|
|
||||||
|
|
||||||
// Devuelve la cadena del fichero de la habitación contigua segun el borde
|
|
||||||
auto getRoom(RoomBorder border) -> std::string;
|
|
||||||
|
|
||||||
// Devuelve el tipo de tile que hay en ese pixel
|
|
||||||
auto getTile(SDL_FPoint point) -> TileType;
|
|
||||||
|
|
||||||
// Indica si hay colision con un enemigo a partir de un rectangulo
|
|
||||||
auto enemyCollision(SDL_FRect& rect) -> bool;
|
|
||||||
|
|
||||||
// Indica si hay colision con un objeto a partir de un rectangulo
|
|
||||||
auto itemCollision(SDL_FRect& rect) -> bool;
|
|
||||||
|
|
||||||
// Obten el tamaño del tile
|
|
||||||
static auto getTileSize() -> int { return TILE_SIZE; }
|
|
||||||
|
|
||||||
// Obten la coordenada de la cuesta a partir de un punto perteneciente a ese tile
|
|
||||||
static auto getSlopeHeight(SDL_FPoint p, TileType slope) -> int;
|
|
||||||
|
|
||||||
// Comprueba las colisiones
|
|
||||||
auto checkRightSurfaces(SDL_FRect* rect) -> int;
|
|
||||||
|
|
||||||
// Comprueba las colisiones
|
|
||||||
auto checkLeftSurfaces(SDL_FRect* rect) -> int;
|
|
||||||
|
|
||||||
// Comprueba las colisiones
|
|
||||||
auto checkTopSurfaces(SDL_FRect* rect) -> int;
|
|
||||||
|
|
||||||
// Comprueba las colisiones
|
|
||||||
auto checkBottomSurfaces(SDL_FRect* rect) -> int;
|
|
||||||
|
|
||||||
// Comprueba las colisiones
|
|
||||||
auto checkAutoSurfaces(SDL_FRect* rect) -> int;
|
|
||||||
|
|
||||||
// Comprueba las colisiones
|
|
||||||
auto checkTopSurfaces(SDL_FPoint* p) -> bool;
|
|
||||||
|
|
||||||
// Comprueba las colisiones
|
|
||||||
auto checkAutoSurfaces(SDL_FPoint* p) -> bool;
|
|
||||||
|
|
||||||
// Comprueba las colisiones
|
|
||||||
auto checkLeftSlopes(const LineVertical* line) -> int;
|
|
||||||
|
|
||||||
// Comprueba las colisiones
|
|
||||||
auto checkLeftSlopes(SDL_FPoint* p) -> bool;
|
|
||||||
|
|
||||||
// Comprueba las colisiones
|
|
||||||
auto checkRightSlopes(const LineVertical* line) -> int;
|
|
||||||
|
|
||||||
// Comprueba las colisiones
|
|
||||||
auto checkRightSlopes(SDL_FPoint* p) -> bool;
|
|
||||||
|
|
||||||
// Pone el mapa en modo pausa
|
|
||||||
void setPaused(bool value) { is_paused_ = value; };
|
|
||||||
|
|
||||||
// Obten la direccion de las superficies automaticas
|
|
||||||
[[nodiscard]] auto getAutoSurfaceDirection() const -> int { return conveyor_belt_direction_; }
|
|
||||||
};
|
};
|
||||||
@@ -36,7 +36,7 @@ Game::Game(GameMode mode)
|
|||||||
mode_(mode),
|
mode_(mode),
|
||||||
#ifdef _DEBUG
|
#ifdef _DEBUG
|
||||||
current_room_("03.room"),
|
current_room_("03.room"),
|
||||||
spawn_point_(PlayerSpawn(25 * BLOCK, 13 * BLOCK, 0, 0, 0, PlayerState::STANDING, SDL_FLIP_HORIZONTAL))
|
spawn_data_(Player::SpawnData(25 * BLOCK, 13 * BLOCK, 0, 0, 0, Player::State::STANDING, SDL_FLIP_HORIZONTAL))
|
||||||
#else
|
#else
|
||||||
current_room_("03.room"),
|
current_room_("03.room"),
|
||||||
spawn_point_(PlayerSpawn(25 * BLOCK, 13 * BLOCK, 0, 0, 0, PlayerState::STANDING, SDL_FLIP_HORIZONTAL))
|
spawn_point_(PlayerSpawn(25 * BLOCK, 13 * BLOCK, 0, 0, 0, PlayerState::STANDING, SDL_FLIP_HORIZONTAL))
|
||||||
@@ -50,7 +50,7 @@ Game::Game(GameMode mode)
|
|||||||
ItemTracker::init();
|
ItemTracker::init();
|
||||||
demoInit();
|
demoInit();
|
||||||
room_ = std::make_shared<Room>(current_room_, board_);
|
room_ = std::make_shared<Room>(current_room_, board_);
|
||||||
initPlayer(spawn_point_, room_);
|
initPlayer(spawn_data_, room_);
|
||||||
initStats();
|
initStats();
|
||||||
total_items_ = getTotalItems();
|
total_items_ = getTotalItems();
|
||||||
|
|
||||||
@@ -178,9 +178,9 @@ void Game::render() {
|
|||||||
#ifdef _DEBUG
|
#ifdef _DEBUG
|
||||||
// Pasa la información de debug
|
// Pasa la información de debug
|
||||||
void Game::updateDebugInfo() {
|
void Game::updateDebugInfo() {
|
||||||
//Debug::get()->add("X = " + std::to_string(static_cast<int>(player_->x_)) + ", Y = " + std::to_string(static_cast<int>(player_->y_)));
|
// Debug::get()->add("X = " + std::to_string(static_cast<int>(player_->x_)) + ", Y = " + std::to_string(static_cast<int>(player_->y_)));
|
||||||
//Debug::get()->add("VX = " + std::to_string(player_->vx_).substr(0, 4) + ", VY = " + std::to_string(player_->vy_).substr(0, 4));
|
// Debug::get()->add("VX = " + std::to_string(player_->vx_).substr(0, 4) + ", VY = " + std::to_string(player_->vy_).substr(0, 4));
|
||||||
//Debug::get()->add("STATE = " + std::to_string(static_cast<int>(player_->state_)));
|
// Debug::get()->add("STATE = " + std::to_string(static_cast<int>(player_->state_)));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Pone la información de debug en pantalla
|
// Pone la información de debug en pantalla
|
||||||
@@ -228,19 +228,19 @@ void Game::checkDebugEvents(const SDL_Event& event) {
|
|||||||
break;
|
break;
|
||||||
|
|
||||||
case SDL_SCANCODE_W:
|
case SDL_SCANCODE_W:
|
||||||
changeRoom(room_->getRoom(RoomBorder::TOP));
|
changeRoom(room_->getRoom(Room::Border::TOP));
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case SDL_SCANCODE_A:
|
case SDL_SCANCODE_A:
|
||||||
changeRoom(room_->getRoom(RoomBorder::LEFT));
|
changeRoom(room_->getRoom(Room::Border::LEFT));
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case SDL_SCANCODE_S:
|
case SDL_SCANCODE_S:
|
||||||
changeRoom(room_->getRoom(RoomBorder::BOTTOM));
|
changeRoom(room_->getRoom(Room::Border::BOTTOM));
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case SDL_SCANCODE_D:
|
case SDL_SCANCODE_D:
|
||||||
changeRoom(room_->getRoom(RoomBorder::RIGHT));
|
changeRoom(room_->getRoom(Room::Border::RIGHT));
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case SDL_SCANCODE_7:
|
case SDL_SCANCODE_7:
|
||||||
@@ -305,7 +305,7 @@ void Game::checkPlayerIsOnBorder() {
|
|||||||
const std::string ROOM_NAME = room_->getRoom(player_->getBorder());
|
const std::string ROOM_NAME = room_->getRoom(player_->getBorder());
|
||||||
if (changeRoom(ROOM_NAME)) {
|
if (changeRoom(ROOM_NAME)) {
|
||||||
player_->switchBorders();
|
player_->switchBorders();
|
||||||
spawn_point_ = player_->getSpawnParams();
|
spawn_data_ = player_->getSpawnParams();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -363,7 +363,7 @@ void Game::killPlayer() {
|
|||||||
|
|
||||||
// Crea la nueva habitación y el nuevo jugador
|
// Crea la nueva habitación y el nuevo jugador
|
||||||
room_ = std::make_shared<Room>(current_room_, board_);
|
room_ = std::make_shared<Room>(current_room_, board_);
|
||||||
initPlayer(spawn_point_, room_);
|
initPlayer(spawn_data_, room_);
|
||||||
|
|
||||||
// Pone los objetos en pausa mientras esta la habitación en negro
|
// Pone los objetos en pausa mientras esta la habitación en negro
|
||||||
room_->setPaused(true);
|
room_->setPaused(true);
|
||||||
@@ -566,10 +566,10 @@ void Game::checkEndGameCheevos() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Inicializa al jugador
|
// Inicializa al jugador
|
||||||
void Game::initPlayer(const PlayerSpawn& spawn_point, std::shared_ptr<Room> room) {
|
void Game::initPlayer(const Player::SpawnData& spawn_point, std::shared_ptr<Room> room) {
|
||||||
std::string player_texture = Options::cheats.alternate_skin == Options::Cheat::State::ENABLED ? "player2.gif" : "player.gif";
|
std::string player_texture = Options::cheats.alternate_skin == Options::Cheat::State::ENABLED ? "player2.gif" : "player.gif";
|
||||||
std::string player_animations = Options::cheats.alternate_skin == Options::Cheat::State::ENABLED ? "player2.ani" : "player.ani";
|
std::string player_animations = Options::cheats.alternate_skin == Options::Cheat::State::ENABLED ? "player2.ani" : "player.ani";
|
||||||
const PlayerData PLAYER(spawn_point, player_texture, player_animations, std::move(room));
|
const Player::Data PLAYER(spawn_point, player_texture, player_animations, std::move(room));
|
||||||
player_ = std::make_shared<Player>(PLAYER);
|
player_ = std::make_shared<Player>(PLAYER);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -62,7 +62,7 @@ class Game {
|
|||||||
DemoData demo_; // Variables para el modo demo
|
DemoData demo_; // Variables para el modo demo
|
||||||
DeltaTimer delta_timer_; // Timer para calcular delta time
|
DeltaTimer delta_timer_; // Timer para calcular delta time
|
||||||
std::string current_room_; // Fichero de la habitación actual
|
std::string current_room_; // Fichero de la habitación actual
|
||||||
PlayerSpawn spawn_point_; // Lugar de la habitación donde aparece el jugador
|
Player::SpawnData spawn_data_; // Lugar de la habitación donde aparece el jugador
|
||||||
bool paused_ = false; // Indica si el juego se encuentra en pausa
|
bool paused_ = false; // Indica si el juego se encuentra en pausa
|
||||||
bool black_screen_ = false; // Indica si la pantalla está en negro. Se utiliza para la muerte del jugador
|
bool black_screen_ = false; // Indica si la pantalla está en negro. Se utiliza para la muerte del jugador
|
||||||
float black_screen_time_ = 0.0F; // Tiempo acumulado en pantalla negra en segundos
|
float black_screen_time_ = 0.0F; // Tiempo acumulado en pantalla negra en segundos
|
||||||
@@ -154,7 +154,7 @@ class Game {
|
|||||||
void checkEndGameCheevos();
|
void checkEndGameCheevos();
|
||||||
|
|
||||||
// Inicializa al jugador
|
// Inicializa al jugador
|
||||||
void initPlayer(const PlayerSpawn& spawn_point, std::shared_ptr<Room> room);
|
void initPlayer(const Player::SpawnData& spawn_point, std::shared_ptr<Room> room);
|
||||||
|
|
||||||
// Crea la textura para poner el nombre de la habitación
|
// Crea la textura para poner el nombre de la habitación
|
||||||
void createRoomNameTexture();
|
void createRoomNameTexture();
|
||||||
|
|||||||
Reference in New Issue
Block a user