Compare commits

5 Commits

Author SHA1 Message Date
9825c7fb9b Pasaeta de include-what-you-use 2024-10-13 21:58:36 +02:00
d0a6e4c572 Afegits destructors virtuals en les classes Sprite 2024-10-13 21:23:15 +02:00
7c876e1d4d Acabat amb cppcheck
Arreglades les herencies de les classes Sprite
2024-10-13 21:00:33 +02:00
809c10048e Commit pa poder tornar a passar el cppcheck 2024-10-13 19:39:43 +02:00
babf02226c Mes recomanacions de cppcheck 2024-10-13 19:26:27 +02:00
58 changed files with 741 additions and 833 deletions

View File

@@ -1,6 +1,8 @@
#include "animated_sprite.h" #include "animated_sprite.h"
#include <algorithm> // for copy
#include <fstream> // for basic_ostream, operator<<, basic_istream, basic... #include <fstream> // for basic_ostream, operator<<, basic_istream, basic...
#include <iostream> // for cout #include <iostream> // for cout
#include <iterator> // for back_insert_iterator, back_inserter
#include <sstream> // for basic_stringstream #include <sstream> // for basic_stringstream
#include "texture.h" // for Texture #include "texture.h" // for Texture

View File

@@ -2,11 +2,11 @@
#include <SDL2/SDL_rect.h> // for SDL_Rect #include <SDL2/SDL_rect.h> // for SDL_Rect
#include <SDL2/SDL_stdinc.h> // for Uint8 #include <SDL2/SDL_stdinc.h> // for Uint8
#include <string> // for string, basic_string #include <memory> // for shared_ptr
#include <string> // for string
#include <vector> // for vector #include <vector> // for vector
#include "moving_sprite.h" // for MovingSprite #include "moving_sprite.h" // for MovingSprite
#include "texture.h" class Texture;
#include <memory>
struct Animation struct Animation
{ {
@@ -37,11 +37,11 @@ protected:
public: public:
// Constructor // Constructor
explicit AnimatedSprite(std::shared_ptr<Texture> texture = nullptr, const std::string &file = std::string(), std::vector<std::string>* buffer = nullptr); explicit AnimatedSprite(std::shared_ptr<Texture> texture = nullptr, const std::string &file = std::string(), std::vector<std::string> *buffer = nullptr);
explicit AnimatedSprite(const AnimatedFile *animation); explicit AnimatedSprite(const AnimatedFile *animation);
// Destructor // Destructor
~AnimatedSprite(); virtual ~AnimatedSprite();
// Calcula el frame correspondiente a la animación actual // Calcula el frame correspondiente a la animación actual
void animate(); void animate();

View File

@@ -1,10 +1,12 @@
#include "background.h" #include "background.h"
#include <SDL2/SDL_blendmode.h> // for SDL_BLENDMODE_BLEND #include <SDL2/SDL_blendmode.h> // for SDL_BLENDMODE_BLEND
#include <SDL2/SDL_pixels.h> // for SDL_PIXELFORMAT_RGBA8888 #include <SDL2/SDL_pixels.h> // for SDL_PIXELFORMAT_RGBA8888
#include <algorithm> // for max, min #include <algorithm> // for clamp, max
#include <string> // for basic_string #include "asset.h" // for Asset
#include "asset.h" // for Asset #include "moving_sprite.h" // for MovingSprite
#include "param.h" // for param #include "param.h" // for param
#include "sprite.h" // for Sprite
#include "texture.h" // for Texture
// Constructor // Constructor
Background::Background(SDL_Renderer *renderer) Background::Background(SDL_Renderer *renderer)
@@ -103,18 +105,19 @@ void Background::update()
// Incrementa el contador // Incrementa el contador
counter_++; counter_++;
// Compone todos los elementos del fondo en la textura
fillCanvas(); fillCanvas();
} }
// Dibuja el gradiente de fondo // Dibuja el gradiente de fondo
void Background::renderGradient() void Background::renderGradient()
{ {
// Dibuja el gradiente 2 // Dibuja el gradiente de detras
gradients_texture_->setAlpha(255); gradients_texture_->setAlpha(255);
gradient_sprite_->setSpriteClip(gradient_rect_[(gradient_number_ + 1) % 4]); gradient_sprite_->setSpriteClip(gradient_rect_[(gradient_number_ + 1) % 4]);
gradient_sprite_->render(); gradient_sprite_->render();
// Dibuja el gradiente 1 con una opacidad cada vez menor // Dibuja el gradiente de delante con una opacidad cada vez menor
gradients_texture_->setAlpha(alpha_); gradients_texture_->setAlpha(alpha_);
gradient_sprite_->setSpriteClip(gradient_rect_[gradient_number_]); gradient_sprite_->setSpriteClip(gradient_rect_[gradient_number_]);
gradient_sprite_->render(); gradient_sprite_->render();
@@ -123,36 +126,36 @@ void Background::renderGradient()
// Dibuja las nubes de arriba // Dibuja las nubes de arriba
void Background::renderTopClouds() void Background::renderTopClouds()
{ {
// Dibuja el primer conjunto de nubes // Dibuja el primer conjunto de nubes, las de detras
top_clouds_texture_->setAlpha(255); top_clouds_texture_->setAlpha(255);
top_clouds_sprite_a_->setSpriteClip(top_clouds_rect_[(gradient_number_ + 1) % 4]); top_clouds_sprite_a_->setSpriteClip(top_clouds_rect_[(gradient_number_ + 1) % 4]);
top_clouds_sprite_a_->render();
top_clouds_sprite_b_->setSpriteClip(top_clouds_rect_[(gradient_number_ + 1) % 4]); top_clouds_sprite_b_->setSpriteClip(top_clouds_rect_[(gradient_number_ + 1) % 4]);
top_clouds_sprite_a_->render();
top_clouds_sprite_b_->render(); top_clouds_sprite_b_->render();
// Dibuja el segundo conjunto de nubes // Dibuja el segundo conjunto de nubes, las de delante
top_clouds_texture_->setAlpha(alpha_); top_clouds_texture_->setAlpha(alpha_);
top_clouds_sprite_a_->setSpriteClip(top_clouds_rect_[gradient_number_]); top_clouds_sprite_a_->setSpriteClip(top_clouds_rect_[gradient_number_]);
top_clouds_sprite_a_->render();
top_clouds_sprite_b_->setSpriteClip(top_clouds_rect_[gradient_number_]); top_clouds_sprite_b_->setSpriteClip(top_clouds_rect_[gradient_number_]);
top_clouds_sprite_a_->render();
top_clouds_sprite_b_->render(); top_clouds_sprite_b_->render();
} }
// Dibuja las nubes de abajo // Dibuja las nubes de abajo
void Background::renderBottomClouds() void Background::renderBottomClouds()
{ {
// Dibuja el primer conjunto de nubes // Dibuja el primer conjunto de nubes, las de detras
bottom_clouds_texture_->setAlpha(255); bottom_clouds_texture_->setAlpha(255);
bottom_clouds_sprite_a_->setSpriteClip(bottom_clouds_rect_[(gradient_number_ + 1) % 4]); bottom_clouds_sprite_a_->setSpriteClip(bottom_clouds_rect_[(gradient_number_ + 1) % 4]);
bottom_clouds_sprite_a_->render();
bottom_clouds_sprite_b_->setSpriteClip(bottom_clouds_rect_[(gradient_number_ + 1) % 4]); bottom_clouds_sprite_b_->setSpriteClip(bottom_clouds_rect_[(gradient_number_ + 1) % 4]);
bottom_clouds_sprite_a_->render();
bottom_clouds_sprite_b_->render(); bottom_clouds_sprite_b_->render();
// Dibuja el segundo conjunto de nubes // Dibuja el segundo conjunto de nubes, las de delante
bottom_clouds_texture_->setAlpha(alpha_); bottom_clouds_texture_->setAlpha(alpha_);
bottom_clouds_sprite_a_->setSpriteClip(bottom_clouds_rect_[gradient_number_]); bottom_clouds_sprite_a_->setSpriteClip(bottom_clouds_rect_[gradient_number_]);
bottom_clouds_sprite_a_->render();
bottom_clouds_sprite_b_->setSpriteClip(bottom_clouds_rect_[gradient_number_]); bottom_clouds_sprite_b_->setSpriteClip(bottom_clouds_rect_[gradient_number_]);
bottom_clouds_sprite_a_->render();
bottom_clouds_sprite_b_->render(); bottom_clouds_sprite_b_->render();
} }
@@ -217,9 +220,7 @@ void Background::setGradientNumber(int value)
// Ajusta el valor de la variable // Ajusta el valor de la variable
void Background::setTransition(float value) void Background::setTransition(float value)
{ {
value = std::min(value, 1.0f); transition_ = std::clamp(value, 0.0f, 1.0f);
value = std::max(value, 0.0f);
transition_ = value;
} }
// Establece la posición del objeto // Establece la posición del objeto
@@ -265,13 +266,10 @@ void Background::setColor(Color color)
void Background::setAlpha(int alpha) void Background::setAlpha(int alpha)
{ {
// Evita que se asignen valores fuera de rango // Evita que se asignen valores fuera de rango
alpha_ = std::min(alpha, 255); alpha_ = std::clamp(alpha, 0, 255);
alpha_ = std::max(alpha, 0);
// Guarda el valor actual // Guarda el valor actual y establece el nuevo valor
alpha_color_text_temp_ = alpha_color_text_; alpha_color_text_temp_ = alpha_color_text_;
// Establece el nuevo valor
alpha_color_text_ = alpha_; alpha_color_text_ = alpha_;
} }

View File

@@ -1,12 +1,12 @@
#pragma once #pragma once
#include <SDL2/SDL_rect.h> // for SDL_Rect #include <SDL2/SDL_rect.h> // for SDL_Rect
#include <SDL2/SDL_render.h> // for SDL_Renderer, SDL_Texture #include <SDL2/SDL_render.h> // for SDL_Renderer, SDL_Texture
#include "utils.h" // for Color #include <memory> // for unique_ptr, shared_ptr
#include "moving_sprite.h" #include "utils.h" // for Color
#include "sprite.h" class MovingSprite;
#include "texture.h" class Sprite;
#include <memory> class Texture;
/* /*
Esta clase es la encargada de dibujar el fondo que aparece durante la sección Esta clase es la encargada de dibujar el fondo que aparece durante la sección

View File

@@ -1,5 +1,5 @@
#include "balloon.h" #include "balloon.h"
#include <math.h> // for abs #include <cmath> // for abs
#include "animated_sprite.h" // for AnimatedSprite #include "animated_sprite.h" // for AnimatedSprite
#include "moving_sprite.h" // for MovingSprite #include "moving_sprite.h" // for MovingSprite
#include "param.h" // for param #include "param.h" // for param

View File

@@ -1,12 +1,12 @@
#pragma once #pragma once
#include <SDL2/SDL_stdinc.h> // for Uint8, Uint16, Uint32 #include <SDL2/SDL_stdinc.h> // for Uint8, Uint16, Uint32
#include <memory> // for shared_ptr, unique_ptr
#include <string> // for string #include <string> // for string
#include <vector> // for vector #include <vector> // for vector
#include <memory> #include "animated_sprite.h" // for AnimatedSprite
#include "utils.h" // for Circle #include "utils.h" // for Circle
#include "animated_sprite.h" class Texture;
#include "texture.h"
// Cantidad de elementos del vector con los valores de la deformación del globo al rebotar // Cantidad de elementos del vector con los valores de la deformación del globo al rebotar
constexpr int MAX_BOUNCE = 10; constexpr int MAX_BOUNCE = 10;

View File

@@ -428,7 +428,6 @@ void BalloonFormations::initBalloonFormations()
// #24 - Treinta enemigos BALLOON1. Del centro hacia los extremos. Juntos. Simetricos // #24 - Treinta enemigos BALLOON1. Del centro hacia los extremos. Juntos. Simetricos
j = 24; j = 24;
balloon_formation_[j].number_of_balloons = 30; balloon_formation_[j].number_of_balloons = 30;
inc_x = 0;
inc_time = 5; inc_time = 5;
for (int i = 0; i < balloon_formation_[j].number_of_balloons; i++) for (int i = 0; i < balloon_formation_[j].number_of_balloons; i++)
{ {

View File

@@ -1,9 +1,9 @@
#include "bullet.h" #include "bullet.h"
#include "param.h" // for param #include <memory> // for unique_ptr, make_unique, shared_ptr
#include "sprite.h" // for Sprite #include "param.h" // for param
#include <memory> // for std::unique_ptr #include "sprite.h" // for Sprite
class Texture;
// Constantes evaluables en tiempo de compilación
constexpr int BULLET_WIDTH = 12; constexpr int BULLET_WIDTH = 12;
constexpr int BULLET_HEIGHT = 12; constexpr int BULLET_HEIGHT = 12;
constexpr int BULLET_VELY = -3; constexpr int BULLET_VELY = -3;
@@ -23,10 +23,9 @@ Bullet::Bullet(int x, int y, BulletType kind, bool powered_up, int owner, SDL_Re
owner_(owner), owner_(owner),
play_area_(play_area) play_area_(play_area)
{ {
vel_x_ = (kind_ == BulletType::LEFT) ? BULLET_VELX_LEFT vel_x_ = (kind_ == BulletType::LEFT) ? BULLET_VELX_LEFT : (kind_ == BulletType::RIGHT) ? BULLET_VELX_RIGHT
: (kind_ == BulletType::RIGHT) ? BULLET_VELX_RIGHT : 0;
: 0;
auto sprite_offset = powered_up ? 3 : 0; auto sprite_offset = powered_up ? 3 : 0;
auto kind_index = static_cast<int>(kind); auto kind_index = static_cast<int>(kind);
sprite_->setSpriteClip((kind_index + sprite_offset) * width_, 0, sprite_->getWidth(), sprite_->getHeight()); sprite_->setSpriteClip((kind_index + sprite_offset) * width_, 0, sprite_->getWidth(), sprite_->getHeight());
@@ -67,12 +66,12 @@ BulletMoveStatus Bullet::move()
bool Bullet::isEnabled() const bool Bullet::isEnabled() const
{ {
return kind_ != BulletType::NULL_TYPE; return kind_ != BulletType::NONE;
} }
void Bullet::disable() void Bullet::disable()
{ {
kind_ = BulletType::NULL_TYPE; kind_ = BulletType::NONE;
} }
int Bullet::getPosX() const int Bullet::getPosX() const

View File

@@ -1,11 +1,11 @@
#pragma once #pragma once
#include <SDL2/SDL_rect.h> // for SDL_Rect #include <SDL2/SDL_rect.h> // for SDL_Rect
#include <SDL2/SDL_stdinc.h> // for Uint8 #include <SDL2/SDL_stdinc.h> // for Uint8
#include <memory> // for unique_ptr #include <memory> // for shared_ptr, unique_ptr
#include "sprite.h" // for Sprite #include "sprite.h" // for Sprite
#include "utils.h" // for Circle #include "utils.h" // for Circle
#include "texture.h" // lines 9-9 class Texture;
// Enumeración para los diferentes tipos de balas // Enumeración para los diferentes tipos de balas
enum class BulletType enum class BulletType
@@ -13,7 +13,7 @@ enum class BulletType
UP, UP,
LEFT, LEFT,
RIGHT, RIGHT,
NULL_TYPE NONE
}; };
// Enumeración para los resultados del movimiento de la bala // Enumeración para los resultados del movimiento de la bala

View File

@@ -1,10 +1,12 @@
#include "define_buttons.h" #include "define_buttons.h"
#include "lang.h" // for getText #include <utility> // for move
#include "options.h" // for options #include "input.h" // for Input, InputType
#include "param.h" // for param #include "lang.h" // for getText
#include "section.h" // for name, SectionName, options, SectionOptions #include "options.h" // for options
#include "text.h" // for Text #include "param.h" // for param
#include "utils.h" // for OptionsController, Options, Param, ParamGame #include "section.h" // for Name, Options, name, options
#include "text.h" // for Text
#include "utils.h" // for OptionsController, Options, Param, ParamGame
// Constructor // Constructor
DefineButtons::DefineButtons(std::unique_ptr<Text> text_) DefineButtons::DefineButtons(std::unique_ptr<Text> text_)

View File

@@ -1,12 +1,13 @@
#pragma once #pragma once
#include <SDL2/SDL_events.h> // for SDL_ControllerButtonEvent #include <SDL2/SDL_events.h> // for SDL_ControllerButtonEvent
#include <SDL2/SDL_gamecontroller.h> // for SDL_GameControllerButton #include <SDL2/SDL_gamecontroller.h> // for SDL_GameControllerButton
#include <string> // for string, basic_string #include <memory> // for shared_ptr, unique_ptr
#include <vector> // for vector #include <string> // for string
#include "input.h" // for inputs_e #include <vector> // for vector
#include "text.h" class Input;
#include <memory> class Text;
enum class InputType : int;
struct DefineButtonsButton struct DefineButtonsButton
{ {

View File

@@ -5,43 +5,44 @@
#include <SDL2/SDL_error.h> // for SDL_GetError #include <SDL2/SDL_error.h> // for SDL_GetError
#include <SDL2/SDL_gamecontroller.h> // for SDL_CONTROLLER_BUTTON_B, SDL_CO... #include <SDL2/SDL_gamecontroller.h> // for SDL_CONTROLLER_BUTTON_B, SDL_CO...
#include <SDL2/SDL_hints.h> // for SDL_SetHint, SDL_HINT_RENDER_DR... #include <SDL2/SDL_hints.h> // for SDL_SetHint, SDL_HINT_RENDER_DR...
#include <SDL2/SDL_scancode.h> // for SDL_SCANCODE_DOWN, SDL_SCANCODE_E #include <SDL2/SDL_scancode.h> // for SDL_SCANCODE_0, SDL_SCANCODE_DOWN
#include <SDL2/SDL_stdinc.h> // for Uint32 #include <SDL2/SDL_stdinc.h> // for SDL_bool, Uint32
#include <SDL2/SDL_timer.h> // for SDL_GetTicks #include <SDL2/SDL_timer.h> // for SDL_GetTicks
#include <errno.h> // for errno, EACCES, EEXIST, ENAMETOO... #include <errno.h> // for errno, EEXIST, EACCES, ENAMETOO...
#include <stdio.h> // for printf, perror, size_t #include <stdio.h> // for printf, perror
#include <string.h> // for strcmp #include <string.h> // for strcmp
#include <sys/stat.h> // for stat, mkdir, S_IRWXU #include <sys/stat.h> // for mkdir, stat, S_IRWXU
#include <unistd.h> // for getuid #include <unistd.h> // for getuid
#include <cstdlib> // for exit, EXIT_FAILURE, rand, srand #include <cstdlib> // for exit, EXIT_FAILURE, rand, srand
#include <iostream> // for basic_ostream, operator<<, cout #include <iostream> // for basic_ostream, operator<<, cout
#include <string> // for basic_string, operator+, allocator #include <memory> // for make_unique, unique_ptr
#include "asset.h" // for Asset, assetType #include <string> // for operator+, allocator, char_traits
#include "asset.h" // for Asset, AssetType
#include "dbgtxt.h" // for dbg_init #include "dbgtxt.h" // for dbg_init
#include "game.h" // for Game, GAME_MODE_DEMO_OFF, GAME_... #include "game.h" // for Game, GAME_MODE_DEMO_OFF, GAME_...
#include "global_inputs.h" #include "global_inputs.h" // for init
#include "hiscore_table.h" // for HiScoreTable #include "hiscore_table.h" // for HiScoreTable
#include "input.h" // for inputs_e, Input #include "input.h" // for Input, InputType
#include "instructions.h" // for Instructions #include "instructions.h" // for Instructions
#include "intro.h" // for Intro #include "intro.h" // for Intro
#include "jail_audio.h" // for JA_DeleteMusic, JA_DeleteSound #include "jail_audio.h" // for JA_LoadMusic, JA_LoadSound, JA_...
#include "logo.h" // for Logo #include "lang.h" // for Code, loadFromFile
#include "manage_hiscore_table.h" // for ManageHiScoreTable #include "logo.h" // for Logo
#include "on_screen_help.h" // for OnScreenHelp #include "manage_hiscore_table.h" // for ManageHiScoreTable
#include "options.h" // for options, loadOptionsFile, saveO... #include "on_screen_help.h" // for OnScreenHelp
#include "param.h" // for param, loadParamsFromFile #include "options.h" // for options, loadOptionsFile, saveO...
#include "screen.h" // for Screen #include "param.h" // for param, loadParamsFromFile
#include "section.h" // for SectionName, name, options, SectionOptions #include "screen.h" // for Screen
#include "title.h" // for Title #include "section.h" // for Name, name, Options, options
#include "utils.h" // for MusicFile, SoundFile, opt... #include "title.h" // for Title
#include <memory> #include "utils.h" // for MusicFile, SoundFile, Options
#ifndef _WIN32 #ifndef _WIN32
#include <pwd.h> // for getpwuid, passwd #include <pwd.h> // for getpwuid, passwd
#endif #endif
// Constructor // Constructor
Director::Director(int argc, char *argv[]) Director::Director(int argc, const char *argv[])
{ {
#ifdef RECORDING #ifdef RECORDING
section::name = section::Name::GAME; section::name = section::Name::GAME;
@@ -160,8 +161,8 @@ void Director::initInput()
Input::get()->bindKey(InputType::RESET, SDL_SCANCODE_F10); Input::get()->bindKey(InputType::RESET, SDL_SCANCODE_F10);
// Asigna botones a inputs // Asigna botones a inputs
const int numGamePads = Input::get()->getNumControllers(); const int num_gamepads = Input::get()->getNumControllers();
for (int i = 0; i < numGamePads; ++i) for (int i = 0; i < num_gamepads; ++i)
{ {
// Mando - Movimiento del jugador // Mando - Movimiento del jugador
Input::get()->bindGameControllerButton(i, InputType::UP, SDL_CONTROLLER_BUTTON_DPAD_UP); Input::get()->bindGameControllerButton(i, InputType::UP, SDL_CONTROLLER_BUTTON_DPAD_UP);
@@ -188,7 +189,7 @@ void Director::initInput()
} }
// Mapea las asignaciones a los botones desde el archivo de configuración, si se da el caso // Mapea las asignaciones a los botones desde el archivo de configuración, si se da el caso
for (int i = 0; i < numGamePads; ++i) for (int i = 0; i < num_gamepads; ++i)
for (int index = 0; index < (int)options.controller.size(); ++index) for (int index = 0; index < (int)options.controller.size(); ++index)
if (Input::get()->getControllerName(i) == options.controller[index].name) if (Input::get()->getControllerName(i) == options.controller[index].name)
{ {
@@ -200,7 +201,7 @@ void Director::initInput()
} }
// Asigna botones a inputs desde otros inputs // Asigna botones a inputs desde otros inputs
for (int i = 0; i < numGamePads; ++i) for (int i = 0; i < num_gamepads; ++i)
{ {
Input::get()->bindGameControllerButton(i, InputType::EXIT, InputType::START); Input::get()->bindGameControllerButton(i, InputType::EXIT, InputType::START);
Input::get()->bindGameControllerButton(i, InputType::RESET, InputType::FIRE_CENTER); Input::get()->bindGameControllerButton(i, InputType::RESET, InputType::FIRE_CENTER);
@@ -213,7 +214,7 @@ void Director::initInput()
} }
// Guarda las asignaciones de botones en las opciones // Guarda las asignaciones de botones en las opciones
for (int i = 0; i < numGamePads; ++i) for (int i = 0; i < num_gamepads; ++i)
{ {
options.controller[i].name = Input::get()->getControllerName(i); options.controller[i].name = Input::get()->getControllerName(i);
for (int j = 0; j < (int)options.controller[i].inputs.size(); ++j) for (int j = 0; j < (int)options.controller[i].inputs.size(); ++j)
@@ -484,7 +485,7 @@ void Director::loadParams(const std::string &file_path)
} }
// Comprueba los parametros del programa // Comprueba los parametros del programa
void Director::checkProgramArguments(int argc, char *argv[]) void Director::checkProgramArguments(int argc, const char *argv[])
{ {
// Establece la ruta del programa // Establece la ruta del programa
executable_path_ = argv[0]; executable_path_ = argv[0];
@@ -492,7 +493,7 @@ void Director::checkProgramArguments(int argc, char *argv[])
// Valores por defecto // Valores por defecto
param_file_argument_.clear(); param_file_argument_.clear();
// Comprueba el resto de parametros // Comprueba el resto de parámetros
for (int i = 1; i < argc; ++i) for (int i = 1; i < argc; ++i)
{ {
if (strcmp(argv[i], "--320x240") == 0) if (strcmp(argv[i], "--320x240") == 0)
@@ -566,17 +567,15 @@ void Director::createSystemFolder(const std::string &folder)
void Director::loadSounds() void Director::loadSounds()
{ {
// Obtiene la lista con las rutas a los ficheros de sonidos // Obtiene la lista con las rutas a los ficheros de sonidos
std::vector<std::string> list = Asset::get()->getListByType(AssetType::SOUND); auto list = Asset::get()->getListByType(AssetType::SOUND);
sounds_.clear(); sounds_.clear();
for (const auto &l : list) for (const auto &l : list)
{ {
const size_t lastIndex = l.find_last_of("/") + 1; auto last_index = l.find_last_of('/') + 1;
const std::string name = l.substr(lastIndex, std::string::npos); auto name = l.substr(last_index);
SoundFile temp;
temp.name = name; // Añade el nombre del fichero sounds_.emplace_back(SoundFile{name, JA_LoadSound(l.c_str())});
temp.file = JA_LoadSound(l.c_str()); // Carga el fichero de audio
sounds_.push_back(temp);
} }
} }
@@ -584,78 +583,69 @@ void Director::loadSounds()
void Director::loadMusics() void Director::loadMusics()
{ {
// Obtiene la lista con las rutas a los ficheros musicales // Obtiene la lista con las rutas a los ficheros musicales
std::vector<std::string> list = Asset::get()->getListByType(AssetType::MUSIC); auto list = Asset::get()->getListByType(AssetType::MUSIC);
musics_.clear(); musics_.clear();
for (const auto &l : list) for (const auto &l : list)
{ {
const size_t lastIndex = l.find_last_of("/") + 1; auto last_index = l.find_last_of('/') + 1;
const std::string name = l.substr(lastIndex, std::string::npos); auto name = l.substr(last_index);
MusicFile temp;
temp.name = name; // Añade el nombre del fichero musics_.emplace_back(MusicFile{name, JA_LoadMusic(l.c_str())});
temp.file = JA_LoadMusic(l.c_str()); // Carga el fichero de audio
musics_.push_back(temp);
} }
} }
// Ejecuta la sección con el logo // Ejecuta la sección con el logo
void Director::runLogo() void Director::runLogo()
{ {
auto logo = new Logo(); auto logo = std::make_unique<Logo>();
logo->run(); logo->run();
delete logo;
} }
// Ejecuta la sección con la secuencia de introducción // Ejecuta la sección con la secuencia de introducción
void Director::runIntro() void Director::runIntro()
{ {
auto intro = new Intro(getMusic(musics_, "intro.ogg")); auto intro = std::make_unique<Intro>(getMusic(musics_, "intro.ogg"));
intro->run(); intro->run();
delete intro;
} }
// Ejecuta la sección con el titulo del juego // Ejecuta la sección con el título del juego
void Director::runTitle() void Director::runTitle()
{ {
auto title = new Title(getMusic(musics_, "title.ogg")); auto title = std::make_unique<Title>(getMusic(musics_, "title.ogg"));
title->run(); title->run();
delete title;
} }
// Ejecuta la sección donde se juega al juego // Ejecuta la sección donde se juega al juego
void Director::runGame() void Director::runGame()
{ {
const auto playerID = section::options == section::Options::GAME_PLAY_1P ? 1 : 2; const auto player_id = section::options == section::Options::GAME_PLAY_1P ? 1 : 2;
constexpr auto currentStage = 0; constexpr auto current_stage = 0;
auto game = new Game(playerID, currentStage, GAME_MODE_DEMO_OFF, getMusic(musics_, "playing.ogg")); auto game = std::make_unique<Game>(player_id, current_stage, GAME_MODE_DEMO_OFF, getMusic(musics_, "playing.ogg"));
game->run(); game->run();
delete game;
} }
// Ejecuta la sección donde se muestran las instrucciones // Ejecuta la sección donde se muestran las instrucciones
void Director::runInstructions() void Director::runInstructions()
{ {
auto instructions = new Instructions(getMusic(musics_, "title.ogg")); auto instructions = std::make_unique<Instructions>(getMusic(musics_, "title.ogg"));
instructions->run(); instructions->run();
delete instructions;
} }
// Ejecuta la sección donde se muestra la tabla de puntuaciones // Ejecuta la sección donde se muestra la tabla de puntuaciones
void Director::runHiScoreTable() void Director::runHiScoreTable()
{ {
auto hiScoreTable = new HiScoreTable(getMusic(musics_, "title.ogg")); auto hi_score_table = std::make_unique<HiScoreTable>(getMusic(musics_, "title.ogg"));
hiScoreTable->run(); hi_score_table->run();
delete hiScoreTable;
} }
// Ejecuta el juego en modo demo // Ejecuta el juego en modo demo
void Director::runDemoGame() void Director::runDemoGame()
{ {
const auto playerID = (rand() % 2) + 1; const auto player_id = (rand() % 2) + 1;
constexpr auto currentStage = 0; constexpr auto current_stage = 0;
auto game = new Game(playerID, currentStage, GAME_MODE_DEMO_ON, nullptr); auto game = std::make_unique<Game>(player_id, current_stage, GAME_MODE_DEMO_ON, nullptr);
game->run(); game->run();
delete game;
} }
int Director::run() int Director::run()
@@ -702,8 +692,8 @@ int Director::run()
} }
} }
const int returnCode = section::options == section::Options::QUIT_NORMAL ? 0 : 1; const int return_code = section::options == section::Options::QUIT_NORMAL ? 0 : 1;
return returnCode; return return_code;
} }
// Obtiene una fichero a partir de un lang::Code // Obtiene una fichero a partir de un lang::Code

View File

@@ -1,11 +1,12 @@
#pragma once #pragma once
#include <SDL2/SDL_render.h> // for SDL_Renderer #include <SDL2/SDL_render.h> // for SDL_Renderer
#include <SDL2/SDL_video.h> // for SDL_Window #include <SDL2/SDL_video.h> // for SDL_Window
#include <string> // for string, basic_string #include <string> // for string
#include <vector> // for vector #include <vector> // for vector
#include "lang.h" // for lang_e namespace lang { enum class Code : int; }
#include "utils.h" // for MusicFile, SoundFile struct MusicFile;
struct SoundFile;
// Textos // Textos
constexpr char WINDOW_CAPTION[] = "Coffee Crisis Arcade Edition"; constexpr char WINDOW_CAPTION[] = "Coffee Crisis Arcade Edition";
@@ -46,7 +47,7 @@ private:
void loadMusics(); void loadMusics();
// Comprueba los parametros del programa // Comprueba los parametros del programa
void checkProgramArguments(int argc, char *argv[]); void checkProgramArguments(int argc, const char *argv[]);
// Crea la carpeta del sistema donde guardar datos // Crea la carpeta del sistema donde guardar datos
void createSystemFolder(const std::string &folder); void createSystemFolder(const std::string &folder);
@@ -77,7 +78,7 @@ private:
public: public:
// Constructor // Constructor
Director(int argc, char *argv[]); Director(int argc, const char *argv[]);
// Destructor // Destructor
~Director(); ~Director();

View File

@@ -1,6 +1,7 @@
#include "explosions.h" #include "explosions.h"
#include <utility> // for move
#include "animated_sprite.h" // for AnimatedSprite #include "animated_sprite.h" // for AnimatedSprite
class Texture; class Texture; // lines 3-3
// Constructor // Constructor
Explosions::Explosions() Explosions::Explosions()

View File

@@ -1,10 +1,10 @@
#pragma once #pragma once
#include <string> // for string #include <memory> // for shared_ptr, unique_ptr
#include <vector> // for vector #include <string> // for string
#include "animated_sprite.h" #include <vector> // for vector
#include <memory> class AnimatedSprite;
#include "texture.h" class Texture;
struct ExplosionTexture struct ExplosionTexture
{ {

View File

@@ -1,38 +1,41 @@
#include "game.h" #include "game.h"
#include <SDL2/SDL_blendmode.h> // for SDL_BLENDMODE_BLEND #include <SDL2/SDL_blendmode.h> // for SDL_BLENDMODE_BLEND
#include <SDL2/SDL_keycode.h> // for SDLK_1, SDLK_2, SDLK_3, SDLK_h #include <SDL2/SDL_events.h> // for SDL_PollEvent, SDL_Event, SDL_KEYDOWN
#include <SDL2/SDL_keycode.h> // for SDLK_1, SDLK_2, SDLK_3, SDLK_4
#include <SDL2/SDL_pixels.h> // for SDL_PIXELFORMAT_RGBA8888 #include <SDL2/SDL_pixels.h> // for SDL_PIXELFORMAT_RGBA8888
#include <SDL2/SDL_rwops.h> // for SDL_RWFromFile, SDL_RWclose, SDL_R... #include <SDL2/SDL_rwops.h> // for SDL_RWFromFile, SDL_RWclose, SDL_R...
#include <SDL2/SDL_timer.h> // for SDL_GetTicks #include <SDL2/SDL_timer.h> // for SDL_GetTicks
#include <SDL2/SDL_video.h> // for SDL_WINDOWEVENT_FOCUS_GAINED, SDL_... #include <SDL2/SDL_video.h> // for SDL_WINDOWEVENT_FOCUS_GAINED, SDL_...
#include <stdlib.h> // for rand #include <stdlib.h> // for rand
#include <algorithm> // for min #include <algorithm> // for min, remove_if
#include <fstream> // for basic_ifstream #include <fstream> // for basic_ostream, operator<<, basic_i...
#include <iostream> // for char_traits, basic_istream, ifstream #include <iostream> // for cout
#include <numeric> // for accumulate
#include <utility> // for move
#include "asset.h" // for Asset #include "asset.h" // for Asset
#include "background.h" // for Background #include "background.h" // for Background
#include "balloon.h" // for Balloon, BALLOON_SPEED_1, BALLOON_... #include "balloon.h" // for Balloon, BALLOON_SCORE_1, BALLOON_...
#include "bullet.h" // for Bullet, BulletType::LEFT, BulletType::RIGHT #include "balloon_formations.h" // for Stage, BalloonFormationParams, Bal...
#include "balloon_formations.h" // for Stage, EnemyFormations, enemyIni... #include "bullet.h" // for Bullet, BulletType, BulletMoveStatus
#include "explosions.h" // for Explosions #include "explosions.h" // for Explosions
#include "fade.h" // for Fade, FadeType::RANDOM_SQUARE, FADE_VEN... #include "fade.h" // for Fade, FadeType
#include "global_inputs.h" // for globalInputs::check #include "global_inputs.h" // for check
#include "input.h" // for inputs_e, Input, INPUT_DO_NOT_ALLO... #include "input.h" // for InputType, Input, INPUT_DO_NOT_ALL...
#include "item.h" // for Item, ITEM_COFFEE_MACHINE, ITEM_CLOCK #include "item.h" // for Item, ITEM_COFFEE_MACHINE, ITEM_CLOCK
#include "jail_audio.h" // for JA_PlaySound, JA_DeleteSound, JA_L... #include "jail_audio.h" // for JA_PlaySound, JA_DeleteSound, JA_L...
#include "lang.h" // for getText #include "lang.h" // for getText
#include "manage_hiscore_table.h" // for ManageHiScoreTable #include "manage_hiscore_table.h" // for ManageHiScoreTable
#include "options.h" // for options #include "options.h" // for options
#include "param.h" // for param #include "param.h" // for param
#include "player.h" // for Player, PlayerStatus::PLAYING, PLA... #include "player.h" // for Player, PlayerStatus
#include "scoreboard.h" // for Scoreboard, scoreboard_modes_e #include "scoreboard.h" // for Scoreboard, ScoreboardMode, SCOREB...
#include "screen.h" // for Screen #include "screen.h" // for Screen
#include "section.h" // for Name, name, Options, options
#include "smart_sprite.h" // for SmartSprite #include "smart_sprite.h" // for SmartSprite
#include "text.h" // for Text, TEXT_CENTER #include "text.h" // for Text, TEXT_CENTER
#include "texture.h" // for Texture #include "texture.h" // for Texture
#include "dbgtxt.h" struct JA_Music_t; // lines 35-35
struct JA_Music_t; struct JA_Sound_t; // lines 36-36
struct JA_Sound_t;
// Constructor // Constructor
Game::Game(int player_id, int current_stage, bool demo, JA_Music_t *music) Game::Game(int player_id, int current_stage, bool demo, JA_Music_t *music)
@@ -133,13 +136,13 @@ void Game::init(int player_id)
players_.push_back(std::move(player2)); players_.push_back(std::move(player2));
// Obtiene mediante "playerID" el jugador que va a empezar jugar // Obtiene mediante "playerID" el jugador que va a empezar jugar
auto player = getPlayer(player_id); auto main_player = getPlayer(player_id);
// Cambia el estado del jugador seleccionado // Cambia el estado del jugador seleccionado
player->setStatusPlaying(PlayerStatus::PLAYING); main_player->setStatusPlaying(PlayerStatus::PLAYING);
// Como es el principio del juego, empieza sin inmunidad // Como es el principio del juego, empieza sin inmunidad
player->setInvulnerable(false); main_player->setInvulnerable(false);
// Variables relacionadas con la dificultad // Variables relacionadas con la dificultad
switch (difficulty_) switch (difficulty_)
@@ -243,9 +246,9 @@ void Game::init(int player_id)
// Activa o no al otro jugador // Activa o no al otro jugador
if (rand() % 2 == 0) if (rand() % 2 == 0)
{ {
const auto otherPlayer = player_id == 1 ? 2 : 1; const auto other_player_id = player_id == 1 ? 2 : 1;
auto player = getPlayer(otherPlayer); auto other_player = getPlayer(other_player_id);
player->setStatusPlaying(PlayerStatus::PLAYING); other_player->setStatusPlaying(PlayerStatus::PLAYING);
} }
for (auto &player : players_) for (auto &player : players_)
@@ -707,7 +710,7 @@ bool Game::saveDemoFile(const std::string &file_path)
#endif // RECORDING #endif // RECORDING
// Crea una formación de enemigos // Crea una formación de enemigos
void Game::deployEnemyFormation() void Game::deployBalloonFormation()
{ {
// Solo despliega una formación enemiga si ha pasado cierto tiempo desde la última // Solo despliega una formación enemiga si ha pasado cierto tiempo desde la última
if (balloon_deploy_counter_ == 0) if (balloon_deploy_counter_ == 0)
@@ -1587,14 +1590,8 @@ void Game::killPlayer(std::shared_ptr<Player> &player)
// Calcula y establece el valor de amenaza en funcion de los globos activos // Calcula y establece el valor de amenaza en funcion de los globos activos
void Game::evaluateAndSetMenace() void Game::evaluateAndSetMenace()
{ {
menace_current_ = 0; menace_current_ = std::accumulate(balloons_.begin(), balloons_.end(), 0, [](int sum, const auto &balloon)
for (auto &balloon : balloons_) { return sum + (balloon->isEnabled() ? balloon->getMenace() : 0); });
{
if (balloon->isEnabled())
{
menace_current_ += balloon->getMenace();
}
}
} }
// Obtiene el valor de la variable // Obtiene el valor de la variable
@@ -1645,11 +1642,11 @@ void Game::updateTimeStoppedCounter()
} }
// Actualiza la variable enemyDeployCounter // Actualiza la variable enemyDeployCounter
void Game::updateEnemyDeployCounter() void Game::updateBalloonDeployCounter()
{ {
if (balloon_deploy_counter_ > 0) if (balloon_deploy_counter_ > 0)
{ {
balloon_deploy_counter_--; --balloon_deploy_counter_;
} }
} }
@@ -1750,7 +1747,7 @@ void Game::update()
// Actualiza los contadores de estado y efectos // Actualiza los contadores de estado y efectos
updateTimeStoppedCounter(); updateTimeStoppedCounter();
updateEnemyDeployCounter(); updateBalloonDeployCounter();
// Actualiza el ayudante // Actualiza el ayudante
updateHelper(); updateHelper();
@@ -1872,7 +1869,7 @@ void Game::updateMenace()
if (menace_current_ < menace_threshold_) if (menace_current_ < menace_threshold_)
{ {
// Crea una formación de enemigos // Crea una formación de enemigos
deployEnemyFormation(); deployBalloonFormation();
// Recalcula el nivel de amenaza con el nuevo globo // Recalcula el nivel de amenaza con el nuevo globo
evaluateAndSetMenace(); evaluateAndSetMenace();
@@ -2248,28 +2245,14 @@ void Game::run()
// Indica si se puede crear una powerball // Indica si se puede crear una powerball
bool Game::canPowerBallBeCreated() bool Game::canPowerBallBeCreated()
{ {
if ((!power_ball_enabled_) && (calculateScreenPower() > POWERBALL_SCREENPOWER_MINIMUM) && (power_ball_counter_ == 0)) return (!power_ball_enabled_) && (calculateScreenPower() > POWERBALL_SCREENPOWER_MINIMUM) && (power_ball_counter_ == 0);
{
return true;
}
return false;
} }
// Calcula el poder actual de los globos en pantalla // Calcula el poder actual de los globos en pantalla
int Game::calculateScreenPower() int Game::calculateScreenPower()
{ {
auto power = 0; return std::accumulate(balloons_.begin(), balloons_.end(), 0, [](int sum, const auto &balloon)
{ return sum + (balloon->isEnabled() ? balloon->getPower() : 0); });
for (auto &balloon : balloons_)
{
if (balloon->isEnabled())
{
power += balloon->getPower();
}
}
return power;
} }
// Inicializa las variables que contienen puntos de ruta para mover objetos // Inicializa las variables que contienen puntos de ruta para mover objetos
@@ -2354,7 +2337,7 @@ void Game::updateHelper()
// Solo ofrece ayuda cuando la amenaza es elevada // Solo ofrece ayuda cuando la amenaza es elevada
if (menace_current_ > 15) if (menace_current_ > 15)
{ {
for (auto &player : players_) for (const auto &player : players_)
{ {
helper_.need_coffee = (player->getCoffees() == 0); helper_.need_coffee = (player->getCoffees() == 0);
helper_.need_coffee_machine = (!player->isPowerUp()); helper_.need_coffee_machine = (!player->isPowerUp());
@@ -2370,7 +2353,7 @@ void Game::updateHelper()
bool Game::allPlayersAreWaitingOrGameOver() bool Game::allPlayersAreWaitingOrGameOver()
{ {
auto success = true; auto success = true;
for (auto &player : players_) for (const auto &player : players_)
{ {
success &= player->isWaiting() || player->isGameOver(); success &= player->isWaiting() || player->isGameOver();
} }
@@ -2382,7 +2365,7 @@ bool Game::allPlayersAreWaitingOrGameOver()
bool Game::allPlayersAreGameOver() bool Game::allPlayersAreGameOver()
{ {
auto success = true; auto success = true;
for (auto &player : players_) for (const auto &player : players_)
{ {
success &= player->isGameOver(); success &= player->isGameOver();
} }
@@ -2394,7 +2377,7 @@ bool Game::allPlayersAreGameOver()
bool Game::allPlayersAreNotPlaying() bool Game::allPlayersAreNotPlaying()
{ {
auto success = true; auto success = true;
for (auto &player : players_) for (const auto &player : players_)
{ {
success &= !player->isPlaying(); success &= !player->isPlaying();
} }
@@ -2566,7 +2549,7 @@ void Game::reloadTextures()
// Actualiza el marcador // Actualiza el marcador
void Game::updateScoreboard() void Game::updateScoreboard()
{ {
for (auto &player : players_) for (const auto &player : players_)
{ {
scoreboard_->setScore(player->getScoreBoardPanel(), player->getScore()); scoreboard_->setScore(player->getScoreBoardPanel(), player->getScore());
scoreboard_->setMult(player->getScoreBoardPanel(), player->getScoreMultiplier()); scoreboard_->setMult(player->getScoreBoardPanel(), player->getScoreMultiplier());
@@ -2590,7 +2573,7 @@ void Game::pause(bool value)
} }
// Añade una puntuación a la tabla de records // Añade una puntuación a la tabla de records
void Game::addScoreToScoreBoard(std::string name, int score) void Game::addScoreToScoreBoard(const std::string &name, int score)
{ {
const auto entry = (HiScoreEntry){trim(name), score}; const auto entry = (HiScoreEntry){trim(name), score};
auto manager = std::make_unique<ManageHiScoreTable>(&options.game.hi_score_table); auto manager = std::make_unique<ManageHiScoreTable>(&options.game.hi_score_table);
@@ -2635,7 +2618,7 @@ void Game::checkPlayersStatusPlaying()
// Obtiene un jugador a partir de su "id" // Obtiene un jugador a partir de su "id"
std::shared_ptr<Player> Game::getPlayer(int id) std::shared_ptr<Player> Game::getPlayer(int id)
{ {
for (auto &player : players_) for (const auto &player : players_)
{ {
if (player->getId() == id) if (player->getId() == id)
{ {

View File

@@ -1,31 +1,29 @@
#pragma once #pragma once
#include <SDL2/SDL_events.h> // for SDL_Event
#include <SDL2/SDL_render.h> // for SDL_Renderer, SDL_Texture #include <SDL2/SDL_render.h> // for SDL_Renderer, SDL_Texture
#include <SDL2/SDL_stdinc.h> // for Uint32 #include <SDL2/SDL_stdinc.h> // for Uint32
#include <memory> // for shared_ptr, unique_ptr
#include <string> // for string #include <string> // for string
#include <vector> // for vector #include <vector> // for vector
#include "section.h" // for SectionOptions #include "balloon.h" // for Balloon
#include "player.h" // for Player
#include "utils.h" // for DemoKeys, Color, HiScoreEntry #include "utils.h" // for DemoKeys, Color, HiScoreEntry
#include <memory> class Asset;
#include "asset.h" // lines 11-11 class Background;
#include "background.h" // lines 12-12 class BalloonFormations;
#include "balloon.h" // lines 13-13 class Bullet;
#include "bullet.h" // lines 14-14 class Explosions;
#include "balloon_formations.h" // lines 15-15 class Fade;
#include "explosions.h" // lines 16-16 class Input;
#include "fade.h" // lines 17-17 class Item;
#include "input.h" // lines 18-18 class Scoreboard;
#include "item.h" // lines 19-19 class Screen;
#include "player.h" // lines 20-20 class SmartSprite;
#include "scoreboard.h" // lines 21-21 class Text;
#include "screen.h" // lines 22-22 class Texture;
#include "smart_sprite.h" // lines 23-23 enum class BulletType; // lines 26-26
#include "text.h" // lines 24-24 struct JA_Music_t; // lines 27-27
#include "texture.h" // lines 24-24 struct JA_Sound_t; // lines 28-28
enum class BulletType;
struct JA_Music_t; // lines 26-26
struct JA_Sound_t; // lines 27-27
// Modo demo // Modo demo
constexpr bool GAME_MODE_DEMO_OFF = false; constexpr bool GAME_MODE_DEMO_OFF = false;
@@ -233,7 +231,7 @@ private:
bool saveDemoFile(const std::string &file_path); bool saveDemoFile(const std::string &file_path);
#endif #endif
// Crea una formación de enemigos // Crea una formación de enemigos
void deployEnemyFormation(); void deployBalloonFormation();
// Aumenta el poder de la fase // Aumenta el poder de la fase
void increaseStageCurrentPower(int power); void increaseStageCurrentPower(int power);
@@ -362,7 +360,7 @@ private:
void incTimeStoppedCounter(int value); void incTimeStoppedCounter(int value);
// Actualiza la variable EnemyDeployCounter // Actualiza la variable EnemyDeployCounter
void updateEnemyDeployCounter(); void updateBalloonDeployCounter();
// Actualiza y comprueba el valor de la variable // Actualiza y comprueba el valor de la variable
void updateTimeStoppedCounter(); void updateTimeStoppedCounter();
@@ -431,7 +429,7 @@ private:
void checkMusicStatus(); void checkMusicStatus();
// Añade una puntuación a la tabla de records // Añade una puntuación a la tabla de records
void addScoreToScoreBoard(std::string name, int score); void addScoreToScoreBoard(const std::string &name, int score);
// Saca del estado de GAME OVER al jugador si el otro está activo // Saca del estado de GAME OVER al jugador si el otro está activo
void checkAndUpdatePlayerStatus(int active_player_index, int inactive_player_index); void checkAndUpdatePlayerStatus(int active_player_index, int inactive_player_index);

View File

@@ -1,6 +1,6 @@
#include "game_logo.h" #include "game_logo.h"
#include <SDL2/SDL_render.h> // for SDL_FLIP_HORIZONTAL
#include <algorithm> // for max #include <algorithm> // for max
#include <string> // for basic_string
#include "animated_sprite.h" // for AnimatedSprite #include "animated_sprite.h" // for AnimatedSprite
#include "asset.h" // for Asset #include "asset.h" // for Asset
#include "jail_audio.h" // for JA_DeleteSound, JA_LoadSound, JA_PlaySound #include "jail_audio.h" // for JA_DeleteSound, JA_LoadSound, JA_PlaySound
@@ -17,17 +17,17 @@ GameLogo::GameLogo(int x, int y)
coffee_texture_(std::make_shared<Texture>(Screen::get()->getRenderer(), Asset::get()->get("title_coffee.png"))), coffee_texture_(std::make_shared<Texture>(Screen::get()->getRenderer(), Asset::get()->get("title_coffee.png"))),
crisis_texture_(std::make_shared<Texture>(Screen::get()->getRenderer(), Asset::get()->get("title_crisis.png"))), crisis_texture_(std::make_shared<Texture>(Screen::get()->getRenderer(), Asset::get()->get("title_crisis.png"))),
arcade_edition_texture_(std::make_shared<Texture>(Screen::get()->getRenderer(), Asset::get()->get("title_arcade_edition.png"))), arcade_edition_texture_(std::make_shared<Texture>(Screen::get()->getRenderer(), Asset::get()->get("title_arcade_edition.png"))),
dust_left_sprite_(std::make_unique<AnimatedSprite>(dust_texture_, Asset::get()->get("title_dust.ani"))), dust_left_sprite_(std::make_unique<AnimatedSprite>(dust_texture_, Asset::get()->get("title_dust.ani"))),
dust_right_sprite_(std::make_unique<AnimatedSprite>(dust_texture_, Asset::get()->get("title_dust.ani"))), dust_right_sprite_(std::make_unique<AnimatedSprite>(dust_texture_, Asset::get()->get("title_dust.ani"))),
coffee_sprite_(std::make_unique<SmartSprite>(coffee_texture_)), coffee_sprite_(std::make_unique<SmartSprite>(coffee_texture_)),
crisis_sprite_(std::make_unique<SmartSprite>(crisis_texture_)), crisis_sprite_(std::make_unique<SmartSprite>(crisis_texture_)),
arcade_edition_sprite_(std::make_unique<Sprite>((param.game.width - arcade_edition_texture_->getWidth()) / 2, param.title.arcade_edition_position, arcade_edition_texture_->getWidth(), arcade_edition_texture_->getHeight(), arcade_edition_texture_)), arcade_edition_sprite_(std::make_unique<Sprite>((param.game.width - arcade_edition_texture_->getWidth()) / 2, param.title.arcade_edition_position, arcade_edition_texture_->getWidth(), arcade_edition_texture_->getHeight(), arcade_edition_texture_)),
crash_sound_(JA_LoadSound(Asset::get()->get("title.wav").c_str())), crash_sound_(JA_LoadSound(Asset::get()->get("title.wav").c_str())),
x_(x), x_(x),
y_(y) y_(y)
{ {

View File

@@ -1,13 +1,11 @@
#pragma once #pragma once
#include <SDL2/SDL_render.h> // for SDL_Renderer #include <memory> // for unique_ptr, shared_ptr
#include <memory> class AnimatedSprite;
#include "texture.h" class SmartSprite;
#include "animated_sprite.h" class Sprite;
#include "smart_sprite.h" class Texture;
#include "sprite.h" struct JA_Sound_t; // lines 10-10
struct JA_Sound_t;
// Clase GameLogo // Clase GameLogo
class GameLogo class GameLogo

View File

@@ -1,5 +1,6 @@
#include "hiscore_table.h" #include "hiscore_table.h"
#include <SDL2/SDL_blendmode.h> // for SDL_BLENDMODE_BLEND #include <SDL2/SDL_blendmode.h> // for SDL_BLENDMODE_BLEND
#include <SDL2/SDL_events.h> // for SDL_PollEvent, SDL_Event, SDL_QUIT
#include <SDL2/SDL_pixels.h> // for SDL_PIXELFORMAT_RGBA8888 #include <SDL2/SDL_pixels.h> // for SDL_PIXELFORMAT_RGBA8888
#include <SDL2/SDL_timer.h> // for SDL_GetTicks #include <SDL2/SDL_timer.h> // for SDL_GetTicks
#include <SDL2/SDL_video.h> // for SDL_WINDOWEVENT_SIZE_CHANGED #include <SDL2/SDL_video.h> // for SDL_WINDOWEVENT_SIZE_CHANGED
@@ -7,15 +8,17 @@
#include <vector> // for vector #include <vector> // for vector
#include "asset.h" // for Asset #include "asset.h" // for Asset
#include "background.h" // for Background #include "background.h" // for Background
#include "global_inputs.h" // for globalInputs::check #include "fade.h" // for Fade, FadeMode, FadeType
#include "global_inputs.h" // for check
#include "input.h" // for Input #include "input.h" // for Input
#include "jail_audio.h" // for JA_GetMusicState, JA_Music_state #include "jail_audio.h" // for JA_GetMusicState, JA_Music_state
#include "lang.h" // for getText #include "lang.h" // for getText
#include "options.h" // for options #include "options.h" // for options
#include "param.h" // for param #include "param.h" // for param
#include "screen.h" // for Screen #include "screen.h" // for Screen
#include "text.h" // for Text, TEXT_CENTER, TEXT_SHADOW, TEXT_COLOR #include "section.h" // for Name, name, Options, options
#include "utils.h" // for Param, ParamGame, HiScoreEntry #include "text.h" // for Text, TEXT_CENTER, TEXT_SHADOW, TEXT...
#include "utils.h" // for Param, ParamGame, Color, HiScoreEntry
// Constructor // Constructor
HiScoreTable::HiScoreTable(JA_Music_t *music) HiScoreTable::HiScoreTable(JA_Music_t *music)

View File

@@ -1,17 +1,15 @@
#pragma once #pragma once
#include <SDL2/SDL_events.h> // for SDL_Event
#include <SDL2/SDL_rect.h> // for SDL_Rect #include <SDL2/SDL_rect.h> // for SDL_Rect
#include <SDL2/SDL_render.h> // for SDL_Renderer, SDL_Texture #include <SDL2/SDL_render.h> // for SDL_Renderer, SDL_Texture
#include <SDL2/SDL_stdinc.h> // for Uint16, Uint32 #include <SDL2/SDL_stdinc.h> // for Uint16, Uint32, Uint8
#include <memory> #include <memory> // for unique_ptr
#include <string> // for string #include <string> // for string
#include "fade.h" class Background; // lines 8-8
#include "section.h" // for SectionOptions class Fade; // lines 9-9
#include "background.h" class Text; // lines 10-10
#include "text.h" enum class FadeMode : Uint8; // lines 11-11
struct JA_Music_t; // lines 12-12
struct JA_Music_t;
/* /*
Esta clase gestiona un estado del programa. Se encarga de mostrar la tabla con las puntuaciones Esta clase gestiona un estado del programa. Se encarga de mostrar la tabla con las puntuaciones

View File

@@ -1,25 +1,26 @@
#include "instructions.h" #include "instructions.h"
#include <SDL2/SDL_blendmode.h> // for SDL_BLENDMODE_BLEND #include <SDL2/SDL_blendmode.h> // for SDL_BLENDMODE_BLEND
#include <SDL2/SDL_events.h> // for SDL_PollEvent, SDL_Event, SDL_QUIT
#include <SDL2/SDL_pixels.h> // for SDL_PIXELFORMAT_RGBA8888 #include <SDL2/SDL_pixels.h> // for SDL_PIXELFORMAT_RGBA8888
#include <SDL2/SDL_timer.h> // for SDL_GetTicks #include <SDL2/SDL_timer.h> // for SDL_GetTicks
#include <SDL2/SDL_video.h> // for SDL_WINDOWEVENT_SIZE_CHANGED #include <SDL2/SDL_video.h> // for SDL_WINDOWEVENT_SIZE_CHANGED
#include <algorithm> // for max #include <algorithm> // for max
#include <string> // for basic_string #include <utility> // for move
#include "asset.h" // for Asset #include "asset.h" // for Asset
#include "fade.h" // for Fade, FadeType::FULLSCREEN, FadeMode::IN #include "fade.h" // for Fade, FadeMode, FadeType
#include "global_inputs.h" // for globalInputs::check #include "global_inputs.h" // for check
#include "input.h" // for Input #include "input.h" // for Input
#include "jail_audio.h" // for JA_GetMusicState, JA_Music_state #include "jail_audio.h" // for JA_GetMusicState, JA_Music_state
#include "lang.h" // for getText #include "lang.h" // for getText
#include "param.h" // for param #include "param.h" // for param
#include "screen.h" // for Screen #include "screen.h" // for Screen
#include "section.h" // for name, SectionName, options, SectionOptions #include "section.h" // for Name, name, Options, options
#include "sprite.h" // for Sprite #include "sprite.h" // for Sprite
#include "text.h" // for Text, TEXT_CENTER, TEXT_COLOR, TEXT_SHADOW #include "text.h" // for Text, TEXT_CENTER, TEXT_COLOR, TEXT_...
#include "texture.h" // for Texture #include "texture.h" // for Texture
#include "tiled_bg.h" // for Tiledbg, TILED_MODE_STATIC #include "tiled_bg.h" // for Tiledbg, TILED_MODE_STATIC
#include "utils.h" // for Param, ParamGame, Color, shdwT... #include "utils.h" // for Param, ParamGame, Color, shdw_txt_color
struct JA_Music_t; struct JA_Music_t; // lines 22-22
// Constructor // Constructor
Instructions::Instructions(JA_Music_t *music) Instructions::Instructions(JA_Music_t *music)

View File

@@ -1,17 +1,16 @@
#pragma once #pragma once
#include <SDL2/SDL_events.h> // for SDL_Event #include <SDL2/SDL_rect.h> // for SDL_Point, SDL_Rect
#include <SDL2/SDL_rect.h> // for SDL_Point, SDL_Rect #include <SDL2/SDL_render.h> // for SDL_Texture, SDL_Renderer
#include <SDL2/SDL_render.h> // for SDL_Texture, SDL_Renderer #include <SDL2/SDL_stdinc.h> // for Uint32
#include <SDL2/SDL_stdinc.h> // for Uint32 #include <memory> // for unique_ptr, shared_ptr
#include <vector> // for vector #include <vector> // for vector
#include <memory> class Fade;
#include "fade.h" class Sprite;
#include "sprite.h" class Text;
#include "text.h" class Texture;
#include "texture.h" class Tiledbg;
#include "tiled_bg.h" struct JA_Music_t; // lines 14-14
struct JA_Music_t;
/* /*
Esta clase gestiona un estado del programa. Se encarga de poner en pantalla Esta clase gestiona un estado del programa. Se encarga de poner en pantalla

View File

@@ -1,22 +1,22 @@
#include "intro.h" #include "intro.h"
#include <SDL2/SDL_render.h> // for SDL_Renderer #include <SDL2/SDL_events.h> // for SDL_PollEvent, SDL_Event, SDL_QUIT, SDL...
#include <SDL2/SDL_timer.h> // for SDL_GetTicks #include <SDL2/SDL_timer.h> // for SDL_GetTicks
#include <SDL2/SDL_video.h> // for SDL_WINDOWEVENT_SIZE_CHANGED #include <SDL2/SDL_video.h> // for SDL_WINDOWEVENT_SIZE_CHANGED
#include <string> // for basic_string #include <utility> // for move
#include "asset.h" // for Asset #include "asset.h" // for Asset
#include "global_inputs.h" // for globalInputs::check #include "global_inputs.h" // for check
#include "input.h" // for Input #include "input.h" // for Input
#include "jail_audio.h" // for JA_StopMusic, JA_PlayMusic #include "jail_audio.h" // for JA_StopMusic, JA_PlayMusic
#include "lang.h" // for getText #include "lang.h" // for getText
#include "param.h" // for param #include "param.h" // for param
#include "screen.h" // for Screen #include "screen.h" // for Screen
#include "section.h" // for name, SectionName, options, SectionOptions #include "section.h" // for Name, name, Options, options
#include "smart_sprite.h" // for SmartSprite #include "smart_sprite.h" // for SmartSprite
#include "text.h" // for Text #include "text.h" // for Text
#include "texture.h" // for Texture #include "texture.h" // for Texture
#include "utils.h" // for ParamGame, Param, Zone, BLOCK #include "utils.h" // for Param, ParamGame, Zone, BLOCK, Color
#include "writer.h" // for Writer #include "writer.h" // for Writer
struct JA_Music_t; struct JA_Music_t; // lines 19-19
// Constructor // Constructor
Intro::Intro(JA_Music_t *music) Intro::Intro(JA_Music_t *music)

View File

@@ -1,14 +1,13 @@
#pragma once #pragma once
#include <SDL2/SDL_events.h> // for SDL_Event #include <SDL2/SDL_stdinc.h> // for Uint32, Uint8
#include <SDL2/SDL_stdinc.h> // for Uint32, Uint8 #include <memory> // for unique_ptr, shared_ptr
#include <vector> // for vector #include <vector> // for vector
#include <memory> #include "smart_sprite.h" // for SmartSprite
#include "smart_sprite.h" #include "writer.h" // for Writer
#include "texture.h" class Text;
#include "text.h" class Texture;
#include "writer.h" struct JA_Music_t; // lines 11-11
struct JA_Music_t;
/* /*
Esta clase gestiona un estado del programa. Se encarga de mostrar la secuencia Esta clase gestiona un estado del programa. Se encarga de mostrar la secuencia

View File

@@ -1,13 +1,13 @@
#pragma once #pragma once
#include <SDL2/SDL_rect.h> // for SDL_Rect #include <SDL2/SDL_rect.h> // for SDL_Rect
#include <SDL2/SDL_stdinc.h> // for Uint16 #include <SDL2/SDL_stdinc.h> // for Uint16
#include <string> // for string #include <memory> // for shared_ptr, unique_ptr
#include <vector> // for vector #include <string> // for string
#include <memory> #include <vector> // for vector
#include "utils.h" // for Circle #include "animated_sprite.h" // for AnimatedSprite
#include "animated_sprite.h" #include "utils.h" // for Circle
#include "texture.h" class Texture;
// Tipos de objetos // Tipos de objetos
constexpr int ITEM_POINTS_1_DISK = 1; constexpr int ITEM_POINTS_1_DISK = 1;

View File

@@ -1,17 +1,18 @@
#include "logo.h" #include "logo.h"
#include <SDL2/SDL_render.h> // for SDL_Renderer #include <SDL2/SDL_events.h> // for SDL_PollEvent, SDL_Event, SDL_QUIT, SDL...
#include <SDL2/SDL_timer.h> // for SDL_GetTicks #include <SDL2/SDL_render.h> // for SDL_Renderer
#include <SDL2/SDL_video.h> // for SDL_WINDOWEVENT_SIZE_CHANGED #include <SDL2/SDL_timer.h> // for SDL_GetTicks
#include <string> // for basic_string #include <SDL2/SDL_video.h> // for SDL_WINDOWEVENT_SIZE_CHANGED
#include "asset.h" // for Asset #include <utility> // for move
#include "global_inputs.h" // for globalInputs::check #include "asset.h" // for Asset
#include "input.h" // for Input #include "global_inputs.h" // for check
#include "jail_audio.h" // for JA_StopMusic #include "input.h" // for Input
#include "param.h" // for param #include "jail_audio.h" // for JA_StopMusic
#include "screen.h" // for Screen #include "param.h" // for param
#include "section.h" // for name, SectionName, options, SectionOptions #include "screen.h" // for Screen
#include "sprite.h" // for Sprite #include "section.h" // for Name, name, Options, options
#include "texture.h" // for Texture #include "sprite.h" // for Sprite
#include "texture.h" // for Texture
// Constructor // Constructor
Logo::Logo() Logo::Logo()
@@ -114,12 +115,12 @@ void Logo::updateJAILGAMES()
{ {
for (int i = 0; i < (int)jail_sprite_.size(); ++i) for (int i = 0; i < (int)jail_sprite_.size(); ++i)
{ {
if (jail_sprite_[i]->getPosX() != dest_.x) if (jail_sprite_[i]->getIntPosX() != dest_.x)
{ {
if (i % 2 == 0) if (i % 2 == 0)
{ {
jail_sprite_[i]->incPosX(-SPEED); jail_sprite_[i]->incPosX(-SPEED);
if (jail_sprite_[i]->getPosX() < dest_.x) if (jail_sprite_[i]->getIntPosX() < dest_.x)
{ {
jail_sprite_[i]->setPosX(dest_.x); jail_sprite_[i]->setPosX(dest_.x);
} }
@@ -127,7 +128,7 @@ void Logo::updateJAILGAMES()
else else
{ {
jail_sprite_[i]->incPosX(SPEED); jail_sprite_[i]->incPosX(SPEED);
if (jail_sprite_[i]->getPosX() > dest_.x) if (jail_sprite_[i]->getIntPosX() > dest_.x)
{ {
jail_sprite_[i]->setPosX(dest_.x); jail_sprite_[i]->setPosX(dest_.x);
} }

View File

@@ -1,13 +1,12 @@
#pragma once #pragma once
#include <SDL2/SDL_events.h> // for SDL_Event #include <SDL2/SDL_rect.h> // for SDL_Point
#include <SDL2/SDL_rect.h> // for SDL_Point #include <SDL2/SDL_stdinc.h> // for Uint32
#include <SDL2/SDL_stdinc.h> // for Uint32 #include <memory> // for unique_ptr, shared_ptr
#include <vector> // for vector #include <vector> // for vector
#include <memory> #include "sprite.h" // for Sprite
#include "utils.h" // for Color #include "utils.h" // for Color
#include "sprite.h" class Texture;
#include "texture.h"
/* /*
Esta clase gestiona un estado del programa. Se encarga de dibujar por pantalla el Esta clase gestiona un estado del programa. Se encarga de dibujar por pantalla el

View File

@@ -7,25 +7,22 @@ Actualizando a la versión "Arcade Edition" en 08/05/2024
*/ */
#include <iostream> // for basic_ostream, char_traits, operator<<, cout #include <iostream> // for char_traits, basic_ostream, operator<<, cout
#include <string> // for basic_string, operator<<, string #include <memory> // for make_unique, unique_ptr
#include "director.h" // for Director #include "director.h" // for Director
int main(int argc, char *argv[]) int main(int argc, char *argv[])
{ {
std::cout << "Game start" << std::endl; std::cout << "Game start" << std::endl;
// Crea el objeto Director // Crea el objeto Director
Director *director = new Director(argc, argv); auto director = std::make_unique<Director>(argc, const_cast<const char **>(argv));
// Bucle principal // Bucle principal
const auto exit = director->run(); const auto exit = director->run();
// Destruye el objeto Director const auto endType = exit == 0 ? "keyboard" : "controller";
delete director; std::cout << "\nGame end with " << endType << std::endl;
const auto endType = exit == 0 ? "keyboard" : "controller"; return exit;
std::cout << "\nGame end with " << endType << std::endl;
return exit;
} }

View File

@@ -50,7 +50,7 @@ void ManageHiScoreTable::sort()
{ {
struct struct
{ {
bool operator()(HiScoreEntry &a, HiScoreEntry &b) const { return a.score > b.score; } bool operator()(const HiScoreEntry &a, const HiScoreEntry &b) const { return a.score > b.score; }
} custom_less; } custom_less;
std::sort(table_->begin(), table_->end(), custom_less); std::sort(table_->begin(), table_->end(), custom_less);

View File

@@ -1,11 +1,11 @@
#pragma once #pragma once
#include <SDL2/SDL_rect.h> // for SDL_Rect, SDL_Point #include <SDL2/SDL_rect.h> // for SDL_Rect, SDL_Point
#include <SDL2/SDL_render.h> // for SDL_RendererFlip #include <SDL2/SDL_render.h> // for SDL_RendererFlip
#include <SDL2/SDL_stdinc.h> // for Uint16 #include <SDL2/SDL_stdinc.h> // for Uint16
#include <memory> #include <memory> // for shared_ptr
#include "sprite.h" // for Sprite #include "sprite.h" // for Sprite
#include "texture.h" class Texture;
// Clase MovingSprite. Añade posicion y velocidad en punto flotante // Clase MovingSprite. Añade posicion y velocidad en punto flotante
class MovingSprite : public Sprite class MovingSprite : public Sprite
@@ -41,6 +41,9 @@ public:
explicit MovingSprite(float x = 0, float y = 0, int w = 0, int h = 0, float velx = 0, float vely = 0, float accelx = 0, float accely = 0, std::shared_ptr<Texture> texture = nullptr); explicit MovingSprite(float x = 0, float y = 0, int w = 0, int h = 0, float velx = 0, float vely = 0, float accelx = 0, float accely = 0, std::shared_ptr<Texture> texture = nullptr);
explicit MovingSprite(std::shared_ptr<Texture> texture = nullptr); explicit MovingSprite(std::shared_ptr<Texture> texture = nullptr);
// Destructor
virtual ~MovingSprite() = default;
// Mueve el sprite // Mueve el sprite
void move(); void move();

View File

@@ -1,16 +1,15 @@
#include "notify.h" #include "notify.h"
#include <SDL2/SDL_blendmode.h> // for SDL_BLENDMODE_BLEND #include <SDL2/SDL_blendmode.h> // for SDL_BLENDMODE_BLEND
#include <SDL2/SDL_pixels.h> // for SDL_PIXELFORMAT_RGBA8888 #include <SDL2/SDL_pixels.h> // for SDL_PIXELFORMAT_RGBA8888
#include <string> // for basic_string, char_traits, string #include <string> // for string
#include "jail_audio.h" // for JA_DeleteSound, JA_LoadSound, JA_Pla... #include "jail_audio.h" // for JA_DeleteSound, JA_LoadSound, JA_Pla...
#include "options.h" // for options #include "param.h" // for param
#include "param.h" #include "sprite.h" // for Sprite
#include "sprite.h" // for Sprite #include "text.h" // for Text
#include "text.h" // for Text #include "texture.h" // for Texture
#include "texture.h" // for Texture
// Constructor // Constructor
Notify::Notify(SDL_Renderer *renderer, std::string iconFile, std::string bitmapFile, std::string textFile, std::string soundFile) Notify::Notify(SDL_Renderer *renderer, std::string iconFile, std::string bitmapFile, std::string textFile, const std::string &soundFile)
: renderer(renderer), : renderer(renderer),
text(std::make_unique<Text>(bitmapFile, textFile, renderer)), text(std::make_unique<Text>(bitmapFile, textFile, renderer)),
bgColor(param.notification.color), bgColor(param.notification.color),

View File

@@ -1,15 +1,15 @@
#pragma once #pragma once
#include <SDL2/SDL_rect.h> // for SDL_Rect #include <SDL2/SDL_rect.h> // for SDL_Rect
#include <SDL2/SDL_render.h> // for SDL_Renderer #include <SDL2/SDL_render.h> // for SDL_Renderer
#include <string> // for basic_string, string #include <memory> // for shared_ptr, unique_ptr
#include <vector> // for vector #include <string> // for string, basic_string
#include <memory> #include <vector> // for vector
#include "utils.h" // for Color #include "utils.h" // for Color
#include "text.h" class Sprite;
#include "texture.h" class Text;
#include "sprite.h" class Texture;
struct JA_Sound_t; struct JA_Sound_t; // lines 12-12
class Notify class Notify
{ {
@@ -77,7 +77,7 @@ private:
public: public:
// Constructor // Constructor
Notify(SDL_Renderer *renderer, std::string iconFile, std::string bitmapFile, std::string textFile, std::string soundFile); Notify(SDL_Renderer *renderer, std::string iconFile, std::string bitmapFile, std::string textFile, const std::string &soundFile);
// Destructor // Destructor
~Notify(); ~Notify();

View File

@@ -1,16 +1,15 @@
#include "on_screen_help.h" #include "on_screen_help.h"
#include <SDL2/SDL_blendmode.h> // for SDL_BLENDMODE_BLEND #include <SDL2/SDL_blendmode.h> // for SDL_BLENDMODE_BLEND
#include <SDL2/SDL_pixels.h> // for SDL_PIXELFORMAT_RGBA8888 #include <SDL2/SDL_pixels.h> // for SDL_PIXELFORMAT_RGBA8888
#include <memory> // for make_unique, unique_ptr #include <memory> // for make_unique, make_shared, unique_ptr
#include <string> // for basic_string #include "asset.h" // for Asset
#include "asset.h" // for Asset #include "lang.h" // for getText
#include "lang.h" // for getText #include "param.h" // for param
#include "param.h" // for param #include "screen.h" // for Screen
#include "screen.h" // for Screen #include "sprite.h" // for Sprite
#include "sprite.h" // for Sprite #include "text.h" // for Text
#include "text.h" // for Text #include "texture.h" // for Texture
#include "texture.h" // for Texture #include "utils.h" // for easeInOutSine, Param, ParamGame
#include "utils.h" // for easeInOutSine, ParamGame, Param
// [SINGLETON] Hay que definir las variables estáticas, desde el .h sólo la hemos declarado // [SINGLETON] Hay que definir las variables estáticas, desde el .h sólo la hemos declarado
OnScreenHelp *OnScreenHelp::onScreenHelp = nullptr; OnScreenHelp *OnScreenHelp::onScreenHelp = nullptr;

View File

@@ -1,11 +1,10 @@
#pragma once #pragma once
#include <SDL2/SDL_rect.h> // for SDL_Rect #include <SDL2/SDL_rect.h> // for SDL_Rect
#include <SDL2/SDL_render.h> // for SDL_Texture #include <SDL2/SDL_render.h> // for SDL_Texture
#include <vector> // for vector #include <vector> // for vector
#include <memory> class Sprite;
#include "sprite.h" // lines 10-10 class Text;
#include "text.h"
enum class OnScreenHelpStatus enum class OnScreenHelpStatus
{ {

View File

@@ -13,7 +13,7 @@
Options options; Options options;
// Declaraciones // Declaraciones
bool setOptions(std::string var, const std::string &value); bool setOptions(const std::string &var, const std::string &value);
// Inicializa las opciones del programa // Inicializa las opciones del programa
void initOptions() void initOptions()
@@ -244,7 +244,7 @@ bool saveOptionsFile(std::string file_path)
} }
// Asigna variables a partir de dos cadenas // Asigna variables a partir de dos cadenas
bool setOptions(std::string var, const std::string &value) bool setOptions(const std::string &var, const std::string &value)
{ {
// Indicador de éxito en la asignación // Indicador de éxito en la asignación
auto success = true; auto success = true;

View File

@@ -1,7 +1,10 @@
#include "param.h" #include "param.h"
#include <fstream> // for char_traits, basic_ostream, basic_ifstream, basi... #include <fstream> // for char_traits, basic_ostream, basic_ifstream, basi...
#include <iostream> // for cout #include <iostream> // for cout
#include "utils.h" // for Param, ParamGame, Zone, ParamBalloon #include <sstream>
#include <string>
#include <stdexcept>
#include "utils.h" // for Param, ParamGame, Zone, ParamBalloon
Param param; Param param;
@@ -40,7 +43,7 @@ void initParam()
param.title.title_c_c_position = 11; param.title.title_c_c_position = 11;
// BACKGROUND // BACKGROUND
param.background.attenuate_color = {255, 255, 255}; param.background.attenuate_color = (Color){255, 255, 255};
param.background.attenuate_alpha = 32; param.background.attenuate_alpha = 32;
// BALLOONS // BALLOONS
@@ -52,10 +55,18 @@ void initParam()
param.balloon_3.grav = 0.10f; param.balloon_3.grav = 0.10f;
param.balloon_4.vel = 4.95f; param.balloon_4.vel = 4.95f;
param.balloon_4.grav = 0.10f; param.balloon_4.grav = 0.10f;
// NOTIFICATION
param.notification.pos_v = NotifyPosition::TOP;
param.notification.pos_h = NotifyPosition::LEFT;
param.notification.sound = false;
param.notification.color.r = 48;
param.notification.color.g = 48;
param.notification.color.b = 48;
} }
// Establece valores para los parametros a partir de un fichero de texto // Establece valores para los parametros a partir de un fichero de texto
void loadParamsFromFile(std::string file_path) /*void loadParamsFromFile(std::string file_path)
{ {
// Pone valores por defecto a las variables // Pone valores por defecto a las variables
initParam(); initParam();
@@ -80,8 +91,15 @@ void loadParamsFromFile(std::string file_path)
param1.clear(); param1.clear();
param2.clear(); param2.clear();
// Elimina los comentarios // Elimina los comentarios al final de una linea
line = line.substr(0, line.find("#")); {
// line = line.substr(0, line.find("#"));
auto pos = line.find("#");
if (pos != std::string::npos)
{
line.resize(pos);
}
}
// Ignora los espacios en blanco // Ignora los espacios en blanco
int pos = 0; int pos = 0;
@@ -148,6 +166,50 @@ void loadParamsFromFile(std::string file_path)
std::cout << "Failed to load file: " << file_path << std::endl; std::cout << "Failed to load file: " << file_path << std::endl;
#endif #endif
precalculateZones();
}*/
void loadParamsFromFile(const std::string &file_path)
{
// Inicializa los parámetros con valores por defecto
initParam();
// Abre el archivo
std::ifstream file(file_path);
if (!file.is_open())
{
#ifdef VERBOSE
std::cerr << "Error: No se pudo abrir el archivo " << file_path << std::endl;
#endif
throw std::runtime_error("No se pudo abrir el archivo: " + file_path);
}
#ifdef VERBOSE
const std::string file_name = file_path.substr(file_path.find_last_of("\\/") + 1);
std::cout << "Reading file: " << file_name << std::endl;
#endif
std::string line, param1, param2;
while (std::getline(file, line))
{
// Elimina comentarios
auto comment_pos = line.find('#');
if (comment_pos != std::string::npos)
{
line.resize(comment_pos);
}
// Usa un stream para separar palabras
std::istringstream iss(line);
if (iss >> param1 >> param2)
{
setParams(param1, param2);
}
}
// Cierra el archivo
file.close();
// Realiza cálculos adicionales después de cargar los parámetros
precalculateZones(); precalculateZones();
} }

View File

@@ -6,4 +6,4 @@ struct Param;
extern Param param; extern Param param;
// Establece valores para los parametros a partir de un fichero de texto // Establece valores para los parametros a partir de un fichero de texto
void loadParamsFromFile(std::string file_path); void loadParamsFromFile(const std::string &file_path);

View File

@@ -12,30 +12,29 @@
// Constructor // Constructor
Player::Player(int id, float x, int y, bool demo, SDL_Rect *play_area, std::vector<std::shared_ptr<Texture>> texture, std::vector<std::vector<std::string> *> animations) Player::Player(int id, float x, int y, bool demo, SDL_Rect *play_area, std::vector<std::shared_ptr<Texture>> texture, std::vector<std::vector<std::string> *> animations)
: player_sprite_(std::make_unique<AnimatedSprite>(texture[0], "", animations[0])),
power_sprite_(std::make_unique<AnimatedSprite>(texture[1], "", animations[1])),
enter_name_(std::make_unique<EnterName>()),
play_area_(play_area),
id_(id),
pos_x_(x),
pos_y_(y),
default_pos_x_(x),
default_pos_y_(y),
status_playing_(PlayerStatus::WAITING),
scoreboard_panel_(0),
name_(std::string()),
controller_index_(0),
demo_(demo)
{ {
// Reserva memoria para los objetos // Reserva memoria para los objetos
player_sprite_ = std::make_unique<AnimatedSprite>(texture[0], "", animations[0]);
power_sprite_ = std::make_unique<AnimatedSprite>(texture[1], "", animations[1]);
power_sprite_->getTexture()->setAlpha(224); power_sprite_->getTexture()->setAlpha(224);
enter_name_ = std::make_unique<EnterName>();
// Rectangulo con la zona de juego
play_area_ = play_area;
// Establece la posición inicial del jugador
default_pos_x_ = pos_x_ = x;
default_pos_y_ = pos_y_ = y;
// Establece los offsets para el sprite de PowerUp // Establece los offsets para el sprite de PowerUp
power_up_desp_x_ = (power_sprite_->getWidth() - player_sprite_->getWidth()) / 2; power_up_desp_x_ = (power_sprite_->getWidth() - player_sprite_->getWidth()) / 2;
power_sprite_->setPosY(y - (power_sprite_->getHeight() - player_sprite_->getHeight())); power_sprite_->setPosY(y - (power_sprite_->getHeight() - player_sprite_->getHeight()));
// Inicializa variables // Inicializa variables
id_ = id;
demo_ = demo;
status_playing_ = PlayerStatus::WAITING;
scoreboard_panel_ = 0;
name_.clear();
setRecordName(enter_name_->getName()); setRecordName(enter_name_->getName());
init(); init();
} }
@@ -237,21 +236,13 @@ void Player::render()
// Establece el estado del jugador cuando camina // Establece el estado del jugador cuando camina
void Player::setWalkingStatus(PlayerStatus status) void Player::setWalkingStatus(PlayerStatus status)
{ {
// Si cambiamos de estado, reiniciamos la animación status_walking_ = status;
if (status_walking_ != status)
{
status_walking_ = status;
}
} }
// Establece el estado del jugador cuando dispara // Establece el estado del jugador cuando dispara
void Player::setFiringStatus(PlayerStatus status) void Player::setFiringStatus(PlayerStatus status)
{ {
// Si cambiamos de estado, reiniciamos la animación status_firing_ = status;
if (status_firing_ != status)
{
status_firing_ = status;
}
} }
// Establece la animación correspondiente al estado // Establece la animación correspondiente al estado
@@ -694,7 +685,7 @@ void Player::shiftColliders()
} }
// Pone las texturas del jugador // Pone las texturas del jugador
void Player::setPlayerTextures(std::vector<std::shared_ptr<Texture>> texture) void Player::setPlayerTextures(const std::vector<std::shared_ptr<Texture>> &texture)
{ {
player_sprite_->setTexture(texture[0]); player_sprite_->setTexture(texture[0]);
power_sprite_->setTexture(texture[1]); power_sprite_->setTexture(texture[1]);
@@ -736,7 +727,7 @@ int Player::getScoreBoardPanel() const
void Player::decContinueCounter() void Player::decContinueCounter()
{ {
continue_ticks_ = SDL_GetTicks(); continue_ticks_ = SDL_GetTicks();
continue_counter_--; --continue_counter_;
if (continue_counter_ < 0) if (continue_counter_ < 0)
{ {
setStatusPlaying(PlayerStatus::GAME_OVER); setStatusPlaying(PlayerStatus::GAME_OVER);
@@ -744,13 +735,13 @@ void Player::decContinueCounter()
} }
// Establece el nombre del jugador // Establece el nombre del jugador
void Player::setName(std::string name) void Player::setName(const std::string &name)
{ {
name_ = name; name_ = name;
} }
// Establece el nombre del jugador para la tabla de mejores puntuaciones // Establece el nombre del jugador para la tabla de mejores puntuaciones
void Player::setRecordName(std::string record_name) void Player::setRecordName(const std::string &record_name)
{ {
record_name_ = record_name.substr(0, 8); record_name_ = record_name.substr(0, 8);
} }

View File

@@ -1,15 +1,16 @@
#pragma once #pragma once
#include <SDL2/SDL_rect.h> // for SDL_Rect #include <SDL2/SDL_rect.h> // for SDL_Rect
#include <SDL2/SDL_stdinc.h> // for Uint32 #include <SDL2/SDL_stdinc.h> // for Uint32
#include <memory> // for unique_ptr #include <memory> // for unique_ptr, shared_ptr
#include <string> // for string, basic_string #include <string> // for string
#include <vector> // for vector #include <vector> // for vector
#include "animated_sprite.h" // for AnimatedSprite #include "animated_sprite.h" // for AnimatedSprite
#include "enter_name.h" // for EnterName #include "enter_name.h" // for EnterName
#include "utils.h" // for Circle #include "utils.h" // for Circle
#include "texture.h" // lines 12-12 class Texture;
enum class ScoreboardMode; enum class InputType : int;
enum class ScoreboardMode; // lines 12-12
// Estados del jugador // Estados del jugador
enum class PlayerStatus enum class PlayerStatus
@@ -118,7 +119,7 @@ public:
void render(); void render();
// Pone las texturas del jugador // Pone las texturas del jugador
void setPlayerTextures(std::vector<std::shared_ptr<Texture>> texture); void setPlayerTextures(const std::vector<std::shared_ptr<Texture>> &texture);
// Actua en consecuencia de la entrada recibida // Actua en consecuencia de la entrada recibida
void setInput(InputType input); void setInput(InputType input);
@@ -271,10 +272,10 @@ public:
void decContinueCounter(); void decContinueCounter();
// Establece el nombre del jugador // Establece el nombre del jugador
void setName(std::string name); void setName(const std::string &name);
// Establece el nombre del jugador para la tabla de mejores puntuaciones // Establece el nombre del jugador para la tabla de mejores puntuaciones
void setRecordName(std::string record_name); void setRecordName(const std::string &record_name);
// Obtiene el nombre del jugador // Obtiene el nombre del jugador
std::string getName() const; std::string getName() const;

View File

@@ -34,13 +34,21 @@ Scoreboard *Scoreboard::get()
// Constructor // Constructor
Scoreboard::Scoreboard(SDL_Renderer *renderer) Scoreboard::Scoreboard(SDL_Renderer *renderer)
: renderer_(renderer) : renderer_(renderer),
game_power_meter_texture_(std::make_shared<Texture>(renderer, Asset::get()->get("game_power_meter.png"))),
power_meter_sprite_(std::make_unique<Sprite>(game_power_meter_texture_)),
text_scoreboard_(std::make_unique<Text>(Asset::get()->get("8bithud.png"), Asset::get()->get("8bithud.txt"), renderer)),
stage_(1),
hi_score_(0),
power_(0),
hi_score_name_(std::string()),
color_({0, 0, 0}),
rect_({0, 0, 320, 40}),
ticks_(SDL_GetTicks()),
counter_(0)
{ {
// Inicializa punteros
game_power_meter_texture_ = nullptr;
power_meter_sprite_ = nullptr;
text_scoreboard_ = nullptr;
// Inicializa variables // Inicializa variables
for (int i = 0; i < SCOREBOARD_MAX_PANELS; ++i) for (int i = 0; i < SCOREBOARD_MAX_PANELS; ++i)
{ {
@@ -51,25 +59,14 @@ Scoreboard::Scoreboard(SDL_Renderer *renderer)
mult_[i] = 0; mult_[i] = 0;
continue_counter_[i] = 0; continue_counter_[i] = 0;
} }
stage_ = 1;
hi_score_ = 0;
power_ = 0;
hi_score_name_.clear();
color_ = {0, 0, 0};
rect_ = {0, 0, 320, 40};
panel_[SCOREBOARD_LEFT_PANEL].mode = ScoreboardMode::SCORE; panel_[SCOREBOARD_LEFT_PANEL].mode = ScoreboardMode::SCORE;
panel_[SCOREBOARD_RIGHT_PANEL].mode = ScoreboardMode::SCORE; panel_[SCOREBOARD_RIGHT_PANEL].mode = ScoreboardMode::SCORE;
panel_[SCOREBOARD_CENTER_PANEL].mode = ScoreboardMode::STAGE_INFO; panel_[SCOREBOARD_CENTER_PANEL].mode = ScoreboardMode::STAGE_INFO;
ticks_ = SDL_GetTicks();
counter_ = 0;
// Recalcula las anclas de los elementos // Recalcula las anclas de los elementos
recalculateAnchors(); recalculateAnchors();
power_meter_sprite_->setPos({slot4_2_.x - 20, slot4_2_.y, 40, 7});
// Crea objetos
game_power_meter_texture_ = std::make_shared<Texture>(renderer_, Asset::get()->get("game_power_meter.png"));
power_meter_sprite_ = std::make_unique<Sprite>(slot4_2_.x - 20, slot4_2_.y, 40, 7, game_power_meter_texture_);
text_scoreboard_ = std::make_unique<Text>(Asset::get()->get("8bithud.png"), Asset::get()->get("8bithud.txt"), renderer_);
// Crea la textura de fondo // Crea la textura de fondo
background_ = nullptr; background_ = nullptr;
@@ -130,13 +127,13 @@ void Scoreboard::render()
} }
// Establece el valor de la variable // Establece el valor de la variable
void Scoreboard::setName(int panel_, std::string name_) void Scoreboard::setName(int panel_, const std::string &name_)
{ {
this->name_[panel_] = name_; this->name_[panel_] = name_;
} }
// Establece el valor de la variable // Establece el valor de la variable
void Scoreboard::setRecordName(int panel_, std::string record_name_) void Scoreboard::setRecordName(int panel_, const std::string &record_name_)
{ {
this->record_name_[panel_] = record_name_; this->record_name_[panel_] = record_name_;
} }
@@ -184,7 +181,7 @@ void Scoreboard::setPower(float power_)
} }
// Establece el valor de la variable // Establece el valor de la variable
void Scoreboard::setHiScoreName(std::string name_) void Scoreboard::setHiScoreName(const std::string &name_)
{ {
hi_score_name_ = name_; hi_score_name_ = name_;
} }
@@ -323,7 +320,7 @@ void Scoreboard::fillPanelTextures()
// ENTER NAME // ENTER NAME
text_scoreboard_->writeCentered(slot4_3_.x, slot4_3_.y, lang::getText(106)); text_scoreboard_->writeCentered(slot4_3_.x, slot4_3_.y, lang::getText(106));
SDL_Rect rect_ = {enter_name_pos_.x, enter_name_pos_.y, 5, 7}; SDL_Rect rect = {enter_name_pos_.x, enter_name_pos_.y, 5, 7};
SDL_SetRenderDrawColor(renderer_, 0xFF, 0xFF, 0xEB, 255); SDL_SetRenderDrawColor(renderer_, 0xFF, 0xFF, 0xEB, 255);
for (int j = 0; j < (int)record_name_[i].size(); ++j) for (int j = 0; j < (int)record_name_[i].size(); ++j)
{ {
@@ -331,16 +328,16 @@ void Scoreboard::fillPanelTextures()
{ // La letra seleccionada se pinta de forma intermitente { // La letra seleccionada se pinta de forma intermitente
if (counter_ % 3 > 0) if (counter_ % 3 > 0)
{ {
SDL_RenderDrawLine(renderer_, rect_.x, rect_.y + rect_.h, rect_.x + rect_.w, rect_.y + rect_.h); SDL_RenderDrawLine(renderer_, rect.x, rect.y + rect.h, rect.x + rect.w, rect.y + rect.h);
text_scoreboard_->write(rect_.x, rect_.y, record_name_[i].substr(j, 1)); text_scoreboard_->write(rect.x, rect.y, record_name_[i].substr(j, 1));
} }
} }
else else
{ {
SDL_RenderDrawLine(renderer_, rect_.x, rect_.y + rect_.h, rect_.x + rect_.w, rect_.y + rect_.h); SDL_RenderDrawLine(renderer_, rect.x, rect.y + rect.h, rect.x + rect.w, rect.y + rect.h);
text_scoreboard_->write(rect_.x, rect_.y, record_name_[i].substr(j, 1)); text_scoreboard_->write(rect.x, rect.y, record_name_[i].substr(j, 1));
} }
rect_.x += 7; rect.x += 7;
} }
break; break;
} }

View File

@@ -1,15 +1,15 @@
#pragma once #pragma once
#include <SDL2/SDL_rect.h> // for SDL_Point, SDL_Rect #include <SDL2/SDL_rect.h> // for SDL_Point, SDL_Rect
#include <SDL2/SDL_render.h> // for SDL_Renderer, SDL_Texture #include <SDL2/SDL_render.h> // for SDL_Renderer, SDL_Texture
#include <SDL2/SDL_stdinc.h> // for Uint32 #include <SDL2/SDL_stdinc.h> // for Uint32
#include <memory> // for unique_ptr #include <memory> // for unique_ptr, shared_ptr
#include <string> // for string, basic_string #include <string> // for string
#include <vector> // for vector #include <vector> // for vector
#include "utils.h" // for Color #include "utils.h" // for Color
#include "sprite.h" // lines 11-11 class Sprite;
#include "text.h" // lines 12-12 class Text;
#include "texture.h" // lines 13-13 class Texture;
// Defines // Defines
constexpr int SCOREBOARD_LEFT_PANEL = 0; constexpr int SCOREBOARD_LEFT_PANEL = 0;
@@ -50,9 +50,9 @@ private:
std::shared_ptr<Texture> game_power_meter_texture_; // Textura con el marcador de poder de la fase std::shared_ptr<Texture> game_power_meter_texture_; // Textura con el marcador de poder de la fase
std::unique_ptr<Sprite> power_meter_sprite_; // Sprite para el medidor de poder de la fase std::unique_ptr<Sprite> power_meter_sprite_; // Sprite para el medidor de poder de la fase
std::unique_ptr<Text> text_scoreboard_; // Fuente para el marcador del juego std::unique_ptr<Text> text_scoreboard_; // Fuente para el marcador del juego
SDL_Texture *background_; // Textura para dibujar el marcador SDL_Texture *background_; // Textura para dibujar el marcador
std::vector<SDL_Texture *> panel_texture_; // Texturas para dibujar cada panel std::vector<SDL_Texture *> panel_texture_; // Texturas para dibujar cada panel
// Variables // Variables
@@ -103,7 +103,7 @@ private:
// [SINGLETON] Ahora el constructor y el destructor son privados // [SINGLETON] Ahora el constructor y el destructor son privados
// Constructor // Constructor
Scoreboard(SDL_Renderer *renderer); explicit Scoreboard(SDL_Renderer *renderer);
// Destructor // Destructor
~Scoreboard(); ~Scoreboard();
@@ -125,10 +125,10 @@ public:
void render(); void render();
// Establece el valor de la variable // Establece el valor de la variable
void setName(int panel, std::string name); void setName(int panel, const std::string &name);
// Establece el valor de la variable // Establece el valor de la variable
void setRecordName(int panel, std::string record_name); void setRecordName(int panel, const std::string &record_name);
// Establece el valor de la variable // Establece el valor de la variable
void setSelectorPos(int panel, int pos); void setSelectorPos(int panel, int pos);
@@ -152,7 +152,7 @@ public:
void setPower(float power); void setPower(float power);
// Establece el valor de la variable // Establece el valor de la variable
void setHiScoreName(std::string name); void setHiScoreName(const std::string &name);
// Establece el valor de la variable // Establece el valor de la variable
void setColor(Color color); void setColor(Color color);

View File

@@ -44,12 +44,27 @@ Screen *Screen::get()
// Constructor // Constructor
Screen::Screen(SDL_Window *window, SDL_Renderer *renderer) Screen::Screen(SDL_Window *window, SDL_Renderer *renderer)
: window_(window), renderer_(renderer) : window_(window),
renderer_(renderer),
notify_(std::make_unique<Notify>(renderer_, std::string(), Asset::get()->get("8bithud.png"), Asset::get()->get("8bithud.txt"), Asset::get()->get("notify.wav"))),
game_canvas_(SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, param.game.width, param.game.height)),
shader_canvas_(SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, param.game.width, param.game.height)),
src_rect_({0, 0, param.game.width, param.game.height}),
dst_rect_({0, 0, param.game.width, param.game.height}),
border_color_({0x00, 0x00, 0x00}),
attenuate_effect_(false),
fps_ticks_(0),
fps_counter_(0),
fps_(0),
#ifdef DEBUG
show_info_(true)
#else
show_info_(false)
#endif
{ {
// Inicializa variables // Inicializa variables
src_rect_ = {0, 0, param.game.width, param.game.height};
dst_rect_ = {0, 0, param.game.width, param.game.height};
border_color_ = {0, 0, 0};
flash_effect_.enabled = false; flash_effect_.enabled = false;
flash_effect_.counter = 0; flash_effect_.counter = 0;
flash_effect_.lenght = 0; flash_effect_.lenght = 0;
@@ -62,29 +77,10 @@ Screen::Screen(SDL_Window *window, SDL_Renderer *renderer)
shake_effect_.remaining = 0; shake_effect_.remaining = 0;
shake_effect_.originalPos = 0; shake_effect_.originalPos = 0;
shake_effect_.originalWidth = param.game.width; shake_effect_.originalWidth = param.game.width;
attenuate_effect_ = false;
fps_ticks_ = 0;
fps_counter_ = 0;
fps_ = 0;
#ifdef DEBUG
show_info_ = true;
#else
show_info_ = false;
#endif
SDL_DisplayMode DM; SDL_DisplayMode DM;
SDL_GetCurrentDisplayMode(0, &DM); SDL_GetCurrentDisplayMode(0, &DM);
info_resolution_ = std::to_string(DM.w) + " X " + std::to_string(DM.h) + " AT " + std::to_string(DM.refresh_rate) + " HZ"; info_resolution_ = std::to_string(DM.w) + " X " + std::to_string(DM.h) + " AT " + std::to_string(DM.refresh_rate) + " HZ";
// Crea los objetos
notify_ = std::make_unique<Notify>(renderer_, "", Asset::get()->get("8bithud.png"), Asset::get()->get("8bithud.txt"), Asset::get()->get("notify.wav"));
// Define el color del borde para el modo de pantalla completa
border_color_ = {0x00, 0x00, 0x00};
// Crea las textura donde se dibujan los graficos del juego
game_canvas_ = SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, param.game.width, param.game.height);
shader_canvas_ = SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, param.game.width, param.game.height);
// Establece el modo de video // Establece el modo de video
setVideoMode(options.video.mode); setVideoMode(options.video.mode);
@@ -183,9 +179,10 @@ void Screen::blit()
// Establece el modo de video // Establece el modo de video
void Screen::setVideoMode(ScreenVideoMode videoMode) void Screen::setVideoMode(ScreenVideoMode videoMode)
{ {
options.video.mode = videoMode;
#ifdef ARCADE #ifdef ARCADE
options.video.mode = ScreenVideoMode::WINDOW; options.video.mode = ScreenVideoMode::WINDOW;
#else
options.video.mode = videoMode;
#endif #endif
switch (options.video.mode) switch (options.video.mode)
@@ -455,7 +452,7 @@ void Screen::attenuate(bool value)
} }
// Muestra una notificación de texto por pantalla; // Muestra una notificación de texto por pantalla;
void Screen::showNotification(std::string text1, std::string text2, int icon) void Screen::showNotification(const std::string &text1, const std::string &text2, int icon)
{ {
notify_->showText(text1, text2, icon); notify_->showText(text1, text2, icon);
} }

View File

@@ -152,7 +152,7 @@ public:
void attenuate(bool value); void attenuate(bool value);
// Muestra una notificación de texto por pantalla; // Muestra una notificación de texto por pantalla;
void showNotification(std::string text1 = std::string(), std::string text2 = std::string(), int icon = -1); void showNotification(const std::string &text1 = std::string(), const std::string &text2 = std::string(), int icon = -1);
// Indica si hay alguna notificación activa en pantalla // Indica si hay alguna notificación activa en pantalla
bool notificationsAreActive() const; bool notificationsAreActive() const;

View File

@@ -1,8 +1,8 @@
#pragma once #pragma once
#include "animated_sprite.h" // for AnimatedSprite #include <memory> // for shared_ptr
#include "texture.h" #include "animated_sprite.h" // for AnimatedSprite
#include <memory> class Texture;
// Clase SmartSprite // Clase SmartSprite
class SmartSprite : public AnimatedSprite class SmartSprite : public AnimatedSprite

View File

@@ -21,13 +21,13 @@ void Sprite::render()
} }
// Obten el valor de la variable // Obten el valor de la variable
int Sprite::getPosX() const int Sprite::getIntPosX() const
{ {
return pos_.x; return pos_.x;
} }
// Obten el valor de la variable // Obten el valor de la variable
int Sprite::getPosY() const int Sprite::getIntPosY() const
{ {
return pos_.y; return pos_.y;
} }

View File

@@ -20,14 +20,14 @@ public:
explicit Sprite(std::shared_ptr<Texture> texture = nullptr); explicit Sprite(std::shared_ptr<Texture> texture = nullptr);
// Destructor // Destructor
~Sprite() = default; virtual ~Sprite() = default;
// Muestra el sprite por pantalla // Muestra el sprite por pantalla
virtual void render(); virtual void render();
// Obten el valor de la variable // Obten el valor de la variable
int getPosX() const; int getIntPosX() const;
int getPosY() const; int getIntPosY() const;
int getWidth() const; int getWidth() const;
int getHeight() const; int getHeight() const;

View File

@@ -1,9 +1,10 @@
#include "text.h" #include "text.h"
#include <fstream> // for char_traits, basic_ostream, basic_ifstream, ope... #include <SDL2/SDL_rect.h> // for SDL_Rect
#include <iostream> // for cout #include <fstream> // for basic_ostream, basic_ifstream, basic_istream
#include "sprite.h" // for Sprite #include <iostream> // for cout
#include "texture.h" // for Texture #include "sprite.h" // for Sprite
#include "utils.h" // for Color #include "texture.h" // for Texture
#include "utils.h" // for Color
// Llena una estructuta TextFile desde un fichero // Llena una estructuta TextFile desde un fichero
TextFile LoadTextFile(std::string file_path) TextFile LoadTextFile(std::string file_path)
@@ -21,7 +22,9 @@ TextFile LoadTextFile(std::string file_path)
} }
// Abre el fichero para leer los valores // Abre el fichero para leer los valores
#ifdef VERBOSE
const std::string file_name = file_path.substr(file_path.find_last_of("\\/") + 1).c_str(); const std::string file_name = file_path.substr(file_path.find_last_of("\\/") + 1).c_str();
#endif
std::ifstream file(file_path); std::ifstream file(file_path);
if (file.is_open() && file.good()) if (file.is_open() && file.good())
@@ -55,7 +58,7 @@ TextFile LoadTextFile(std::string file_path)
// Cierra el fichero // Cierra el fichero
#ifdef VERBOSE #ifdef VERBOSE
std::cout << "Text loaded: " << file_name.c_str() << std::endl; std::cout << "Text loaded: " << file_name << std::endl;
#endif #endif
file.close(); file.close();
} }
@@ -64,7 +67,7 @@ TextFile LoadTextFile(std::string file_path)
else else
{ {
#ifdef VERBOSE #ifdef VERBOSE
std::cout << "Warning: Unable to open " << file_name.c_str() << " file" << std::endl; std::cout << "Warning: Unable to open " << file_name << " file" << std::endl;
#endif #endif
} }
@@ -79,7 +82,7 @@ TextFile LoadTextFile(std::string file_path)
} }
// Constructor // Constructor
Text::Text(std::string bitmap_file, std::string text_file, SDL_Renderer *renderer) Text::Text(const std::string &bitmap_file, const std::string &text_file, SDL_Renderer *renderer)
{ {
// Carga los offsets desde el fichero // Carga los offsets desde el fichero
auto tf = LoadTextFile(text_file); auto tf = LoadTextFile(text_file);
@@ -103,7 +106,7 @@ Text::Text(std::string bitmap_file, std::string text_file, SDL_Renderer *rendere
} }
// Constructor // Constructor
Text::Text(std::string text_file, std::shared_ptr<Texture> texture) Text::Text(const std::string &text_file, std::shared_ptr<Texture> texture)
{ {
// Carga los offsets desde el fichero // Carga los offsets desde el fichero
auto tf = LoadTextFile(text_file); auto tf = LoadTextFile(text_file);
@@ -146,7 +149,7 @@ Text::Text(TextFile *text_file, std::shared_ptr<Texture> texture)
} }
// Escribe texto en pantalla // Escribe texto en pantalla
void Text::write(int x, int y, std::string text, int kerning, int lenght) void Text::write(int x, int y, const std::string &text, int kerning, int lenght)
{ {
auto shift = 0; auto shift = 0;
@@ -169,7 +172,7 @@ void Text::write(int x, int y, std::string text, int kerning, int lenght)
} }
// Escribe el texto con colores // Escribe el texto con colores
void Text::writeColored(int x, int y, std::string text, Color color, int kerning, int lenght) void Text::writeColored(int x, int y, const std::string &text, Color color, int kerning, int lenght)
{ {
sprite_->getTexture()->setColor(color.r, color.g, color.b); sprite_->getTexture()->setColor(color.r, color.g, color.b);
write(x, y, text, kerning, lenght); write(x, y, text, kerning, lenght);
@@ -177,7 +180,7 @@ void Text::writeColored(int x, int y, std::string text, Color color, int kerning
} }
// Escribe el texto con sombra // Escribe el texto con sombra
void Text::writeShadowed(int x, int y, std::string text, Color color, Uint8 shadow_distance, int kerning, int lenght) void Text::writeShadowed(int x, int y, const std::string &text, Color color, Uint8 shadow_distance, int kerning, int lenght)
{ {
sprite_->getTexture()->setColor(color.r, color.g, color.b); sprite_->getTexture()->setColor(color.r, color.g, color.b);
write(x + shadow_distance, y + shadow_distance, text, kerning, lenght); write(x + shadow_distance, y + shadow_distance, text, kerning, lenght);
@@ -186,14 +189,14 @@ void Text::writeShadowed(int x, int y, std::string text, Color color, Uint8 shad
} }
// Escribe el texto centrado en un punto x // Escribe el texto centrado en un punto x
void Text::writeCentered(int x, int y, std::string text, int kerning, int lenght) void Text::writeCentered(int x, int y, const std::string &text, int kerning, int lenght)
{ {
x -= (Text::lenght(text, kerning) / 2); x -= (Text::lenght(text, kerning) / 2);
write(x, y, text, kerning, lenght); write(x, y, text, kerning, lenght);
} }
// Escribe texto con extras // Escribe texto con extras
void Text::writeDX(Uint8 flags, int x, int y, std::string text, int kerning, Color textColor, Uint8 shadow_distance, Color shadow_color, int lenght) void Text::writeDX(Uint8 flags, int x, int y, const std::string &text, int kerning, Color textColor, Uint8 shadow_distance, Color shadow_color, int lenght)
{ {
const auto centered = ((flags & TEXT_CENTER) == TEXT_CENTER); const auto centered = ((flags & TEXT_CENTER) == TEXT_CENTER);
const auto shadowed = ((flags & TEXT_SHADOW) == TEXT_SHADOW); const auto shadowed = ((flags & TEXT_SHADOW) == TEXT_SHADOW);
@@ -235,7 +238,7 @@ void Text::writeDX(Uint8 flags, int x, int y, std::string text, int kerning, Col
} }
// Obtiene la longitud en pixels de una cadena // Obtiene la longitud en pixels de una cadena
int Text::lenght(std::string text, int kerning) const int Text::lenght(const std::string &text, int kerning) const
{ {
auto shift = 0; auto shift = 0;
@@ -267,7 +270,7 @@ void Text::setFixedWidth(bool value)
} }
// Carga una paleta de colores para el texto // Carga una paleta de colores para el texto
void Text::addPalette(std::string path) void Text::addPalette(const std::string &path)
{ {
texture_->addPalette(path); texture_->addPalette(path);
} }

View File

@@ -2,11 +2,11 @@
#include <SDL2/SDL_render.h> // for SDL_Renderer #include <SDL2/SDL_render.h> // for SDL_Renderer
#include <SDL2/SDL_stdinc.h> // for Uint8 #include <SDL2/SDL_stdinc.h> // for Uint8
#include <memory> // for shared_ptr, unique_ptr
#include <string> // for string #include <string> // for string
#include <memory> #include "sprite.h" // for Sprite
#include "utils.h" #include "utils.h" // for Color
#include "sprite.h" class Texture;
#include "texture.h"
constexpr int TEXT_COLOR = 1; constexpr int TEXT_COLOR = 1;
constexpr int TEXT_SHADOW = 2; constexpr int TEXT_SHADOW = 2;
@@ -33,41 +33,41 @@ class Text
{ {
private: private:
// Objetos y punteros // Objetos y punteros
std::unique_ptr<Sprite> sprite_; // Objeto con los graficos para el texto std::unique_ptr<Sprite> sprite_; // Objeto con los graficos para el texto
std::shared_ptr<Texture> texture_; // Textura con los bitmaps del texto std::shared_ptr<Texture> texture_; // Textura con los bitmaps del texto
// Variables // Variables
int box_width_; // Anchura de la caja de cada caracter en el png int box_width_; // Anchura de la caja de cada caracter en el png
int box_height_; // Altura de la caja de cada caracter en el png int box_height_; // Altura de la caja de cada caracter en el png
bool fixed_width_; // Indica si el texto se ha de escribir con longitud fija en todas las letras bool fixed_width_; // Indica si el texto se ha de escribir con longitud fija en todas las letras
TextOffset offset_[128]; // Vector con las posiciones y ancho de cada letra TextOffset offset_[128]; // Vector con las posiciones y ancho de cada letra
public: public:
// Constructor // Constructor
Text(std::string bitmap_file, std::string text_file, SDL_Renderer *renderer); Text(const std::string &bitmap_file, const std::string &text_file, SDL_Renderer *renderer);
Text(std::string text_file, std::shared_ptr<Texture> texture); Text(const std::string &text_file, std::shared_ptr<Texture> texture);
Text(TextFile *text_file, std::shared_ptr<Texture> texture); Text(TextFile *text_file, std::shared_ptr<Texture> texture);
// Destructor // Destructor
~Text() = default; ~Text() = default;
// Escribe el texto en pantalla // Escribe el texto en pantalla
void write(int x, int y, std::string text, int kerning = 1, int lenght = -1); void write(int x, int y, const std::string &text, int kerning = 1, int lenght = -1);
// Escribe el texto con colores // Escribe el texto con colores
void writeColored(int x, int y, std::string text, Color color, int kerning = 1, int lenght = -1); void writeColored(int x, int y, const std::string &text, Color color, int kerning = 1, int lenght = -1);
// Escribe el texto con sombra // Escribe el texto con sombra
void writeShadowed(int x, int y, std::string text, Color color, Uint8 shadow_distance = 1, int kerning = 1, int lenght = -1); void writeShadowed(int x, int y, const std::string &text, Color color, Uint8 shadow_distance = 1, int kerning = 1, int lenght = -1);
// Escribe el texto centrado en un punto x // Escribe el texto centrado en un punto x
void writeCentered(int x, int y, std::string text, int kerning = 1, int lenght = -1); void writeCentered(int x, int y, const std::string &text, int kerning = 1, int lenght = -1);
// Escribe texto con extras // Escribe texto con extras
void writeDX(Uint8 flags, int x, int y, std::string text, int kerning = 1, Color textColor = {255, 255, 255}, Uint8 shadow_distance = 1, Color shadow_color = {0, 0, 0}, int lenght = -1); void writeDX(Uint8 flags, int x, int y, const std::string &text, int kerning = 1, Color textColor = Color(), Uint8 shadow_distance = 1, Color shadow_color = Color(), int lenght = -1);
// Obtiene la longitud en pixels de una cadena // Obtiene la longitud en pixels de una cadena
int lenght(std::string text, int kerning = 1) const; int lenght(const std::string &text, int kerning = 1) const;
// Devuelve el valor de la variable // Devuelve el valor de la variable
int getCharacterSize() const; int getCharacterSize() const;
@@ -79,7 +79,7 @@ public:
void setFixedWidth(bool value); void setFixedWidth(bool value);
// Carga una paleta de colores para el texto // Carga una paleta de colores para el texto
void addPalette(std::string path); void addPalette(const std::string &path);
// Establece una paleta de colores para el texto // Establece una paleta de colores para el texto
void setPalette(int index); void setPalette(int index);

View File

@@ -11,7 +11,7 @@
#include "stb_image.h" // for stbi_failure_reason, stbi_image_free #include "stb_image.h" // for stbi_failure_reason, stbi_image_free
// Constructor // Constructor
Texture::Texture(SDL_Renderer *renderer, std::string path) Texture::Texture(SDL_Renderer *renderer, const std::string &path)
: renderer_(renderer), path_(path) : renderer_(renderer), path_(path)
{ {
// Inicializa // Inicializa
@@ -37,8 +37,8 @@ Texture::Texture(SDL_Renderer *renderer, std::string path)
// .gif // .gif
else if (extension == "gif") else if (extension == "gif")
{ {
surface_ = loadSurface(path_.c_str()); surface_ = loadSurface(path_);
addPalette(path_.c_str()); addPalette(path_);
setPaletteColor(0, 0, 0x00000000); setPaletteColor(0, 0, 0x00000000);
createBlank(width_, height_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_STREAMING); createBlank(width_, height_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_STREAMING);
SDL_SetTextureBlendMode(texture_, SDL_BLENDMODE_BLEND); SDL_SetTextureBlendMode(texture_, SDL_BLENDMODE_BLEND);
@@ -54,13 +54,12 @@ Texture::~Texture()
} }
// Carga una imagen desde un fichero // Carga una imagen desde un fichero
bool Texture::loadFromFile(std::string path) bool Texture::loadFromFile(const std::string &path)
{ {
const std::string file_name = path.substr(path.find_last_of("\\/") + 1);
int req_format = STBI_rgb_alpha; int req_format = STBI_rgb_alpha;
int width, height, orig_format; int width, height, orig_format;
unsigned char *data = stbi_load(path.c_str(), &width, &height, &orig_format, req_format); unsigned char *data = stbi_load(path.c_str(), &width, &height, &orig_format, req_format);
if (data == nullptr) if (!data)
{ {
#ifdef VERBOSE #ifdef VERBOSE
std::cout << "Loading image failed: " << stbi_failure_reason() << std::endl; std::cout << "Loading image failed: " << stbi_failure_reason() << std::endl;
@@ -70,19 +69,20 @@ bool Texture::loadFromFile(std::string path)
else else
{ {
#ifdef VERBOSE #ifdef VERBOSE
std::cout << "Image loaded: " << file_name.c_str() << std::endl; const std::string file_name = path.substr(path.find_last_of("\\/") + 1);
std::cout << "Image loaded: " << file_name << std::endl;
#endif #endif
} }
int depth, pitch; int depth, pitch;
Uint32 pixel_format; Uint32 pixel_format;
if (req_format == STBI_rgb) /*if (req_format == STBI_rgb)
{ {
depth = 24; depth = 24;
pitch = 3 * width; // 3 bytes por pixel * pixels por linea pitch = 3 * width; // 3 bytes por pixel * pixels por linea
pixel_format = SDL_PIXELFORMAT_RGB24; pixel_format = SDL_PIXELFORMAT_RGB24;
} }
else else*/
{ // STBI_rgb_alpha (RGBA) { // STBI_rgb_alpha (RGBA)
depth = 32; depth = 32;
pitch = 4 * width; pitch = 4 * width;
@@ -96,11 +96,11 @@ bool Texture::loadFromFile(std::string path)
SDL_Texture *newTexture = nullptr; SDL_Texture *newTexture = nullptr;
// Carga la imagen desde una ruta específica // Carga la imagen desde una ruta específica
SDL_Surface *loadedSurface = SDL_CreateRGBSurfaceWithFormatFrom((void *)data, width, height, depth, pitch, pixel_format); auto loadedSurface = SDL_CreateRGBSurfaceWithFormatFrom(static_cast<void *>(data), width, height, depth, pitch, pixel_format);
if (loadedSurface == nullptr) if (loadedSurface == nullptr)
{ {
#ifdef VERBOSE #ifdef VERBOSE
std::cout << "Unable to load image " << path.c_str() << std::endl; std::cout << "Unable to load image " << path << std::endl;
#endif #endif
} }
else else
@@ -110,7 +110,7 @@ bool Texture::loadFromFile(std::string path)
if (newTexture == nullptr) if (newTexture == nullptr)
{ {
#ifdef VERBOSE #ifdef VERBOSE
std::cout << "Unable to create texture from " << path.c_str() << "! SDL Error: " << SDL_GetError() << std::endl; std::cout << "Unable to create texture from " << path << "! SDL Error: " << SDL_GetError() << std::endl;
#endif #endif
} }
else else
@@ -137,9 +137,9 @@ bool Texture::createBlank(int width, int height, SDL_PixelFormatEnum format, SDL
texture_ = SDL_CreateTexture(renderer_, format, access, width, height); texture_ = SDL_CreateTexture(renderer_, format, access, width, height);
if (!texture_) if (!texture_)
{ {
#ifdef VERBOSE #ifdef VERBOSE
std::cout << "Unable to create blank texture! SDL Error: " << SDL_GetError() << std::endl; std::cout << "Unable to create blank texture! SDL Error: " << SDL_GetError() << std::endl;
#endif #endif
} }
else else
{ {
@@ -239,14 +239,14 @@ SDL_Texture *Texture::getSDLTexture()
} }
// Crea una nueva surface // Crea una nueva surface
Surface Texture::newSurface(int w, int h) /*Surface Texture::newSurface(int w, int h)
{ {
Surface surf = (Surface)malloc(sizeof(surface_s)); Surface surf = static_cast<Surface>(malloc(sizeof(surface_s)));
surf->w = w; surf->w = w;
surf->h = h; surf->h = h;
surf->data = (Uint8 *)malloc(w * h); surf->data = static_cast<Uint8 *>(malloc(w * h));
return surf; return surf;
} }*/
// Elimina una surface // Elimina una surface
void Texture::deleteSurface(Surface surface) void Texture::deleteSurface(Surface surface)
@@ -265,29 +265,29 @@ void Texture::deleteSurface(Surface surface)
} }
// Crea una surface desde un fichero .gif // Crea una surface desde un fichero .gif
Surface Texture::loadSurface(const char *file_name) Surface Texture::loadSurface(const std::string &file_name)
{ {
FILE *f = fopen(file_name, "rb"); FILE *f = fopen(file_name.c_str(), "rb");
if (!f) if (!f)
{ {
return NULL; return nullptr;
} }
fseek(f, 0, SEEK_END); fseek(f, 0, SEEK_END);
long size = ftell(f); long size = ftell(f);
fseek(f, 0, SEEK_SET); fseek(f, 0, SEEK_SET);
Uint8 *buffer = (Uint8 *)malloc(size); Uint8 *buffer = static_cast<Uint8 *>(malloc(size));
fread(buffer, size, 1, f); fread(buffer, size, 1, f);
fclose(f); fclose(f);
Uint16 w, h; Uint16 w, h;
Uint8 *pixels = LoadGif(buffer, &w, &h); Uint8 *pixels = LoadGif(buffer, &w, &h);
if (pixels == NULL) if (pixels == nullptr)
{ {
return NULL; return nullptr;
} }
Surface surface = (Surface)malloc(sizeof(surface_s)); Surface surface = static_cast<Surface>(malloc(sizeof(surface_s)));
surface->w = w; surface->w = w;
surface->h = h; surface->h = h;
surface->data = pixels; surface->data = pixels;
@@ -312,7 +312,7 @@ void Texture::flipSurface()
// Vuelca los datos // Vuelca los datos
Uint32 *pixels; Uint32 *pixels;
int pitch; int pitch;
SDL_LockTexture(texture_, nullptr, (void **)&pixels, &pitch); SDL_LockTexture(texture_, nullptr, reinterpret_cast<void **>(&pixels), &pitch);
for (int i = 0; i < width_ * height_; ++i) for (int i = 0; i < width_ * height_; ++i)
{ {
pixels[i] = palettes_[paletteIndex_][surface_->data[i]]; pixels[i] = palettes_[paletteIndex_][surface_->data[i]];
@@ -327,11 +327,11 @@ void Texture::setPaletteColor(int palette, int index, Uint32 color)
} }
// Carga una paleta desde un fichero // Carga una paleta desde un fichero
std::vector<Uint32> Texture::loadPal(const char *file_name) std::vector<Uint32> Texture::loadPal(const std::string &file_name)
{ {
std::vector<Uint32> palette; std::vector<Uint32> palette;
FILE *f = fopen(file_name, "rb"); FILE *f = fopen(file_name.c_str(), "rb");
if (!f) if (!f)
{ {
return palette; return palette;
@@ -340,12 +340,12 @@ std::vector<Uint32> Texture::loadPal(const char *file_name)
fseek(f, 0, SEEK_END); fseek(f, 0, SEEK_END);
long size = ftell(f); long size = ftell(f);
fseek(f, 0, SEEK_SET); fseek(f, 0, SEEK_SET);
Uint8 *buffer = (Uint8 *)malloc(size); Uint8 *buffer = static_cast<Uint8 *>(malloc(size));
fread(buffer, size, 1, f); fread(buffer, size, 1, f);
fclose(f); fclose(f);
Uint32 *pal = LoadPalette(buffer); const auto *pal = LoadPalette(buffer);
if (pal == nullptr) if (!pal)
{ {
return palette; return palette;
} }
@@ -361,9 +361,9 @@ std::vector<Uint32> Texture::loadPal(const char *file_name)
} }
// Añade una paleta a la lista // Añade una paleta a la lista
void Texture::addPalette(std::string path) void Texture::addPalette(const std::string &path)
{ {
palettes_.push_back(loadPal(path.c_str())); palettes_.push_back(loadPal(path));
setPaletteColor((int)palettes_.size() - 1, 0, 0x00000000); setPaletteColor((int)palettes_.size() - 1, 0, 0x00000000);
} }

View File

@@ -33,29 +33,29 @@ private:
int paletteIndex_; // Indice de la paleta en uso int paletteIndex_; // Indice de la paleta en uso
// Crea una nueva surface // Crea una nueva surface
Surface newSurface(int w, int h); //Surface newSurface(int w, int h);
// Elimina una surface // Elimina una surface
void deleteSurface(Surface surface); void deleteSurface(Surface surface);
// Crea una surface desde un fichero .gif // Crea una surface desde un fichero .gif
Surface loadSurface(const char *file_name); Surface loadSurface(const std::string &file_name);
// Vuelca la surface en la textura // Vuelca la surface en la textura
void flipSurface(); void flipSurface();
// Carga una paleta desde un fichero // Carga una paleta desde un fichero
std::vector<Uint32> loadPal(const char *file_name); std::vector<Uint32> loadPal(const std::string &file_name);
public: public:
// Constructor // Constructor
explicit Texture(SDL_Renderer *renderer, std::string path = std::string()); explicit Texture(SDL_Renderer *renderer, const std::string &path = std::string());
// Destructor // Destructor
~Texture(); ~Texture();
// Carga una imagen desde un fichero // Carga una imagen desde un fichero
bool loadFromFile(std::string path); bool loadFromFile(const std::string &path);
// Crea una textura en blanco // Crea una textura en blanco
bool createBlank(int width, int height, SDL_PixelFormatEnum format = SDL_PIXELFORMAT_RGBA8888, SDL_TextureAccess = SDL_TEXTUREACCESS_STREAMING); bool createBlank(int width, int height, SDL_PixelFormatEnum format = SDL_PIXELFORMAT_RGBA8888, SDL_TextureAccess = SDL_TEXTUREACCESS_STREAMING);
@@ -91,7 +91,7 @@ public:
SDL_Texture *getSDLTexture(); SDL_Texture *getSDLTexture();
// Añade una paleta a la lista // Añade una paleta a la lista
void addPalette(std::string path); void addPalette(const std::string &path);
// Establece un color de la paleta // Establece un color de la paleta
void setPaletteColor(int palette, int index, Uint32 color); void setPaletteColor(int palette, int index, Uint32 color);

View File

@@ -1,10 +1,11 @@
#include "tiled_bg.h" #include "tiled_bg.h"
#include <SDL2/SDL_pixels.h> // for SDL_PIXELFORMAT_RGBA8888 #include <SDL2/SDL_pixels.h> // for SDL_PIXELFORMAT_RGBA8888
#include <SDL2/SDL_stdinc.h> // for SDL_sinf #include <SDL2/SDL_stdinc.h> // for SDL_sinf
#include <stdlib.h> // for rand #include <stdlib.h> // for rand
#include "screen.h" // for Screen #include <memory> // for unique_ptr, make_shared, make_unique
#include "sprite.h" // for Sprite #include "screen.h" // for Screen
#include "texture.h" // for Texture #include "sprite.h" // for Sprite
#include "texture.h" // for Texture
// Constructor // Constructor
Tiledbg::Tiledbg(std::string texture_path, SDL_Rect pos, int mode) Tiledbg::Tiledbg(std::string texture_path, SDL_Rect pos, int mode)

View File

@@ -1,20 +1,24 @@
#include "title.h" #include "title.h"
#include <SDL2/SDL_keycode.h> // for SDLK_1, SDLK_2, SDLK_3 #include <SDL2/SDL_events.h> // for SDL_PollEvent, SDL_Event, SDL_KEYDOWN
#include <SDL2/SDL_render.h> // for SDL_Renderer #include <SDL2/SDL_keycode.h> // for SDLK_1, SDLK_2, SDLK_3
#include <SDL2/SDL_timer.h> // for SDL_GetTicks #include <SDL2/SDL_rect.h> // for SDL_Rect
#include <string> // for allocator, basic_string, char_traits #include <SDL2/SDL_render.h> // for SDL_Renderer
#include <vector> // for vector #include <SDL2/SDL_timer.h> // for SDL_GetTicks
#include "asset.h" // for Asset #include <string> // for char_traits, operator+, to_string, bas...
#include "global_inputs.h" // for globalInputs::check #include <utility> // for move
#include "input.h" // for Input, inputs_e, INPUT_DO_NOT_ALLOW_RE... #include <vector> // for vector
#include "jail_audio.h" // for JA_GetMusicState, JA_Music_state, JA_P... #include "asset.h" // for Asset
#include "lang.h" // for getText #include "global_inputs.h" // for check
#include "options.h" // for options #include "input.h" // for Input, InputType, INPUT_DO_NOT_ALLOW_R...
#include "param.h" // for param #include "jail_audio.h" // for JA_GetMusicState, JA_Music_state, JA_P...
#include "screen.h" // for Screen #include "lang.h" // for getText
#include "section.h" // for SectionOptions, options, SectionName, name #include "options.h" // for options
#include "param.h" // for param
struct JA_Music_t; #include "screen.h" // for Screen
#include "section.h" // for Options, options, Name, name
#include "texture.h" // for Texture
#include "utils.h" // for Param, OptionsController, Color, Param...
struct JA_Music_t; // lines 17-17
// Constructor // Constructor
Title::Title(JA_Music_t *music) Title::Title(JA_Music_t *music)
@@ -315,9 +319,9 @@ void Title::resetCounter()
// Intercambia la asignación de mandos a los jugadores // Intercambia la asignación de mandos a los jugadores
void Title::swapControllers() void Title::swapControllers()
{ {
const int num_controllers_ = input_->getNumControllers(); const auto num_controllers = input_->getNumControllers();
if (num_controllers_ == 0) if (num_controllers == 0)
{ {
return; return;
} }

View File

@@ -1,24 +1,18 @@
#pragma once #pragma once
#include <SDL2/SDL_events.h> // for SDL_Event #include <SDL2/SDL_stdinc.h> // for Uint32
#include <SDL2/SDL_stdinc.h> // for Uint32 #include <memory> // for unique_ptr, shared_ptr
#include <memory> #include "define_buttons.h" // for DefineButtons
#include "define_buttons.h" #include "fade.h" // for Fade
#include "fade.h" #include "game_logo.h" // for GameLogo
#include "game_logo.h" #include "sprite.h" // for Sprite
#include "text.h" #include "text.h" // for Text
#include "tiled_bg.h" #include "tiled_bg.h" // for Tiledbg
#include "utils.h" // for Section class Input; // lines 17-17
#include "sprite.h" class Screen; // lines 18-18
#include "texture.h" class Texture; // lines 20-20
#include "section.h" namespace section { enum class Name; }
struct JA_Music_t; // lines 21-21
class Asset;
class Input;
class Screen;
class Sprite;
class Texture;
struct JA_Music_t;
// Textos // Textos
constexpr const char TEXT_COPYRIGHT[] = "@2020,2024 JailDesigner"; constexpr const char TEXT_COPYRIGHT[] = "@2020,2024 JailDesigner";

View File

@@ -1,11 +1,10 @@
#include "utils.h" #include "utils.h"
#include <stdlib.h> // for free, malloc #include <algorithm> // for min, clamp, find_if_not, transform
#include <algorithm> // for max, min #include <cctype> // for tolower, isspace
#include <cctype> // for isspace #include <cmath> // for cos, pow, M_PI
#include <iterator> // for distance #include <compare> // for operator<
#include <cmath> struct JA_Music_t; // lines 7-7
struct JA_Music_t; // lines 3-3 struct JA_Sound_t; // lines 8-8
struct JA_Sound_t; // lines 4-4
// Colores // Colores
const Color bg_color = {0x27, 0x27, 0x36}; const Color bg_color = {0x27, 0x27, 0x36};
@@ -29,210 +28,112 @@ double distanceSquared(int x1, int y1, int x2, int y2)
} }
// Detector de colisiones entre dos circulos // Detector de colisiones entre dos circulos
bool checkCollision(Circle &a, Circle &b) bool checkCollision(const Circle &a, const Circle &b)
{ {
// Calcula el radio total al cuadrado // Calcula el radio total al cuadrado
int total_radius_squared = a.r + b.r; int total_radius_squared = (a.r + b.r) * (a.r + b.r);
total_radius_squared = total_radius_squared * total_radius_squared;
// Si la distancia entre el centro de los circulos es inferior a la suma de sus radios // Comprueba si la distancia entre los centros de los círculos es inferior a la suma de sus radios
if (distanceSquared(a.x, a.y, b.x, b.y) < (total_radius_squared)) return distanceSquared(a.x, a.y, b.x, b.y) < total_radius_squared;
{
// Los circulos han colisionado
return true;
}
// En caso contrario
return false;
} }
// Detector de colisiones entre un circulo y un rectangulo // Detector de colisiones entre un circulo y un rectangulo
bool checkCollision(Circle &a, SDL_Rect &b) bool checkCollision(const Circle &a, const SDL_Rect &b)
{ {
// Closest point on collision box // Encuentra el punto más cercano en el rectángulo
int cX, cY; int cX = std::clamp(a.x, b.x, b.x + b.w);
int cY = std::clamp(a.y, b.y, b.y + b.h);
// Find closest x offset // Si el punto más cercano está dentro del círculo
if (a.x < b.x) return distanceSquared(a.x, a.y, cX, cY) < a.r * a.r;
{
cX = b.x;
}
else if (a.x > b.x + b.w)
{
cX = b.x + b.w;
}
else
{
cX = a.x;
}
// Find closest y offset
if (a.y < b.y)
{
cY = b.y;
}
else if (a.y > b.y + b.h)
{
cY = b.y + b.h;
}
else
{
cY = a.y;
}
// If the closest point is inside the Circle
if (distanceSquared(a.x, a.y, cX, cY) < a.r * a.r)
{
// This box and the Circle have collided
return true;
}
// If the shapes have not collided
return false;
} }
// Detector de colisiones entre dos rectangulos // Detector de colisiones entre dos rectangulos
bool checkCollision(SDL_Rect &a, SDL_Rect &b) bool checkCollision(const SDL_Rect &a, const SDL_Rect &b)
{ {
// Calcula las caras del rectangulo a const int leftA = a.x, rightA = a.x + a.w, topA = a.y, bottomA = a.y + a.h;
const int leftA = a.x; const int leftB = b.x, rightB = b.x + b.w, topB = b.y, bottomB = b.y + b.h;
const int rightA = a.x + a.w;
const int topA = a.y;
const int bottomA = a.y + a.h;
// Calcula las caras del rectangulo b
const int leftB = b.x;
const int rightB = b.x + b.w;
const int topB = b.y;
const int bottomB = b.y + b.h;
// Si cualquiera de las caras de a está fuera de b
if (bottomA <= topB) if (bottomA <= topB)
{
return false; return false;
}
if (topA >= bottomB) if (topA >= bottomB)
{
return false; return false;
}
if (rightA <= leftB) if (rightA <= leftB)
{
return false; return false;
}
if (leftA >= rightB) if (leftA >= rightB)
{
return false; return false;
}
// Si ninguna de las caras está fuera de b
return true; return true;
} }
// Detector de colisiones entre un punto y un rectangulo // Detector de colisiones entre un punto y un rectangulo
bool checkCollision(SDL_Point &p, SDL_Rect &r) bool checkCollision(const SDL_Point &p, const SDL_Rect &r)
{ {
// Comprueba si el punto está a la izquierda del rectangulo if (p.x < r.x || p.x > r.x + r.w)
if (p.x < r.x)
{
return false; return false;
} if (p.y < r.y || p.y > r.y + r.h)
// Comprueba si el punto está a la derecha del rectangulo
if (p.x > r.x + r.w)
{
return false; return false;
}
// Comprueba si el punto está por encima del rectangulo
if (p.y < r.y)
{
return false;
}
// Comprueba si el punto está por debajo del rectangulo
if (p.y > r.y + r.h)
{
return false;
}
// Si no está fuera, es que está dentro
return true; return true;
} }
// Convierte una cadena en un valor booleano // Convierte una cadena en un valor booleano
bool stringToBool(std::string str) bool stringToBool(const std::string &str)
{ {
return str == "true" ? true : false; return str == "true";
} }
// Convierte un valor booleano en una cadena // Convierte un valor booleano en una cadena
std::string boolToString(bool value) std::string boolToString(bool value)
{ {
return value == true ? "true" : "false"; return value ? "true" : "false";
} }
// Convierte un valor booleano en una cadena "on" o "off" // Convierte un valor booleano en una cadena "on" o "off"
std::string boolToOnOff(bool value) std::string boolToOnOff(bool value)
{ {
return value == true ? "on" : "off"; return value ? "on" : "off";
} }
// Convierte una cadena a minusculas // Convierte una cadena a minusculas
std::string toLower(std::string str) std::string toLower(const std::string &str)
{ {
const char *original = str.c_str(); std::string result = str;
char *lower = (char *)malloc(str.size() + 1); std::transform(result.begin(), result.end(), result.begin(),
for (int i = 0; i < (int)str.size(); ++i) [](unsigned char c)
{ { return std::tolower(c); });
char c = original[i]; return result;
lower[i] = (c >= 65 && c <= 90) ? c + 32 : c;
}
lower[str.size()] = 0;
std::string nova(lower);
free(lower);
return nova;
} }
// Obtiene el fichero de sonido a partir de un nombre // Obtiene el fichero de sonido a partir de un nombre
JA_Sound_t *getSound(std::vector<SoundFile> sounds, std::string name) JA_Sound_t *getSound(const std::vector<SoundFile> &sounds, const std::string &name)
{ {
for (auto s : sounds) for (const auto &s : sounds)
{ {
if (s.name == name) if (s.name == name)
{ {
return s.file; return s.file;
} }
} }
return nullptr; return nullptr;
} }
// Obtiene el fichero de música a partir de un nombre // Obtiene el fichero de música a partir de un nombre
JA_Music_t *getMusic(std::vector<MusicFile> music, std::string name) JA_Music_t *getMusic(const std::vector<MusicFile> &music, const std::string &name)
{ {
for (auto m : music) for (const auto &m : music)
{ {
if (m.name == name) if (m.name == name)
{ {
return m.file; return m.file;
} }
} }
return nullptr; return nullptr;
} }
// Ordena las entradas de la tabla de records // Ordena las entradas de la tabla de records
HiScoreEntry sortHiScoreTable(HiScoreEntry entry1, HiScoreEntry entry2) HiScoreEntry sortHiScoreTable(const HiScoreEntry &entry1, const HiScoreEntry &entry2)
{ {
if (entry1.score > entry2.score) return (entry1.score > entry2.score) ? entry1 : entry2;
{
return entry1;
}
return entry2;
} }
// Dibuja un circulo // Dibuja un circulo
@@ -275,41 +176,31 @@ void DrawCircle(SDL_Renderer *renderer, int32_t centerX, int32_t centerY, int32_
} }
// Aclara el color // Aclara el color
Color lightenColor(Color color, int amount) Color lightenColor(const Color &color, int amount)
{ {
Color newColor; Color newColor;
newColor.r = std::min(255, (int)color.r + amount); newColor.r = std::min(255, color.r + amount);
newColor.g = std::min(255, (int)color.g + amount); newColor.g = std::min(255, color.g + amount);
newColor.b = std::min(255, (int)color.b + amount); newColor.b = std::min(255, color.b + amount);
return newColor; return newColor;
} }
// Oscurece el color // Oscurece el color
Color DarkenColor(Color color, int amount) Color DarkenColor(const Color &color, int amount)
{ {
Color newColor; Color newColor;
newColor.r = std::max(0, (int)color.r - amount); newColor.r = std::min(255, color.r - +amount);
newColor.g = std::max(0, (int)color.g - amount); newColor.g = std::min(255, color.g - +amount);
newColor.b = std::max(0, (int)color.b - amount); newColor.b = std::min(255, color.b - +amount);
return newColor; return newColor;
} }
// Quita los espacioes en un string // Quita los espacioes en un string
std::string trim(const std::string &str) std::string trim(const std::string &str)
{ {
auto start = str.begin(); auto start = std::find_if_not(str.begin(), str.end(), ::isspace);
while (start != str.end() && std::isspace(*start)) auto end = std::find_if_not(str.rbegin(), str.rend(), ::isspace).base();
{ return (start < end ? std::string(start, end) : std::string());
start++;
}
auto end = str.end();
do
{
end--;
} while (std::distance(start, end) > 0 && std::isspace(*end));
return std::string(start, end + 1);
} }
// Función de suavizado // Función de suavizado

View File

@@ -3,16 +3,19 @@
#include <SDL2/SDL_gamecontroller.h> // for SDL_GameControllerButton #include <SDL2/SDL_gamecontroller.h> // for SDL_GameControllerButton
#include <SDL2/SDL_rect.h> // for SDL_Rect, SDL_Point #include <SDL2/SDL_rect.h> // for SDL_Rect, SDL_Point
#include <SDL2/SDL_render.h> // for SDL_Renderer #include <SDL2/SDL_render.h> // for SDL_Renderer
#include <SDL2/SDL_stdinc.h> // for Uint8, Uint32 #include <SDL2/SDL_stdinc.h> // for Uint8
#include <stdint.h> // for int32_t #include <stdint.h> // for int32_t
#include <string> // for string, basic_string #include <string> // for string
#include <vector> // for vector #include <vector> // for vector
#include "input.h" // for inputs_e enum class InputType : int;
#include "lang.h" enum class ScreenFilter; // lines 14-14
struct JA_Music_t; enum class ScreenVideoMode; // lines 15-15
struct JA_Sound_t; namespace lang
enum class ScreenFilter; {
enum class ScreenVideoMode; enum class Code : int;
}
struct JA_Music_t; // lines 12-12
struct JA_Sound_t; // lines 13-13
// Dificultad del juego // Dificultad del juego
enum class GameDifficulty enum class GameDifficulty
@@ -35,6 +38,7 @@ struct Circle
struct Color struct Color
{ {
Uint8 r, g, b; Uint8 r, g, b;
constexpr Color(int red = 255, int green = 255, int blue = 255) : r(red), g(green), b(blue) {}
}; };
// Posiciones de las notificaciones // Posiciones de las notificaciones
@@ -47,13 +51,6 @@ enum class NotifyPosition
RIGHT, RIGHT,
}; };
// Estructura para saber la seccion y subseccion del programa
/*struct Section
{
section::Name name;
section::Options options;
};*/
// Estructura para las entradas de la tabla de recirds // Estructura para las entradas de la tabla de recirds
struct HiScoreEntry struct HiScoreEntry
{ {
@@ -114,7 +111,7 @@ struct OptionsAudio
struct OptionsGame struct OptionsGame
{ {
GameDifficulty difficulty; // Dificultad del juego GameDifficulty difficulty; // Dificultad del juego
lang::Code language; // Idioma usado en el juego lang::Code language; // Idioma usado en el juego
bool autofire; // Indica si el jugador ha de pulsar repetidamente para disparar o basta con mantener pulsado bool autofire; // Indica si el jugador ha de pulsar repetidamente para disparar o basta con mantener pulsado
std::vector<HiScoreEntry> hi_score_table; // Tabla con las mejores puntuaciones std::vector<HiScoreEntry> hi_score_table; // Tabla con las mejores puntuaciones
}; };
@@ -235,19 +232,19 @@ struct MusicFile
double distanceSquared(int x1, int y1, int x2, int y2); double distanceSquared(int x1, int y1, int x2, int y2);
// Detector de colisiones entre dos circulos // Detector de colisiones entre dos circulos
bool checkCollision(Circle &a, Circle &b); bool checkCollision(const Circle &a, const Circle &b);
// Detector de colisiones entre un circulo y un rectangulo // Detector de colisiones entre un circulo y un rectangulo
bool checkCollision(Circle &a, SDL_Rect &b); bool checkCollision(const Circle &a, const SDL_Rect &b);
// Detector de colisiones entre un dos rectangulos // Detector de colisiones entre un dos rectangulos
bool checkCollision(SDL_Rect &a, SDL_Rect &b); bool checkCollision(const SDL_Rect &a, const SDL_Rect &b);
// Detector de colisiones entre un punto y un rectangulo // Detector de colisiones entre un punto y un rectangulo
bool checkCollision(SDL_Point &p, SDL_Rect &r); bool checkCollision(const SDL_Point &p, const SDL_Rect &r);
// Convierte una cadena en un valor booleano // Convierte una cadena en un valor booleano
bool stringToBool(std::string str); bool stringToBool(const std::string &str);
// Convierte un valor booleano en una cadena // Convierte un valor booleano en una cadena
std::string boolToString(bool value); std::string boolToString(bool value);
@@ -256,25 +253,25 @@ std::string boolToString(bool value);
std::string boolToOnOff(bool value); std::string boolToOnOff(bool value);
// Convierte una cadena a minusculas // Convierte una cadena a minusculas
std::string toLower(std::string str); std::string toLower(const std::string &str);
// Obtiene el fichero de sonido a partir de un nombre // Obtiene el fichero de sonido a partir de un nombre
JA_Sound_t *getSound(std::vector<SoundFile> sounds, std::string name); JA_Sound_t *getSound(const std::vector<SoundFile> &sounds, const std::string &name);
// Obtiene el fichero de música a partir de un nombre // Obtiene el fichero de música a partir de un nombre
JA_Music_t *getMusic(std::vector<MusicFile> music, std::string name); JA_Music_t *getMusic(const std::vector<MusicFile> &music, const std::string &name);
// Ordena las entradas de la tabla de records // Ordena las entradas de la tabla de records
HiScoreEntry sortHiScoreTable(HiScoreEntry entry1, HiScoreEntry entry2); HiScoreEntry sortHiScoreTable(const HiScoreEntry &entry1, const HiScoreEntry &entry2);
// Dibuja un circulo // Dibuja un circulo
void DrawCircle(SDL_Renderer *renderer, int32_t centerX, int32_t centerY, int32_t radius); void DrawCircle(SDL_Renderer *renderer, int32_t centerX, int32_t centerY, int32_t radius);
// Aclara el color // Aclara el color
Color lightenColor(Color color, int amount); Color lightenColor(const Color &color, int amount);
// Oscurece el color // Oscurece el color
Color DarkenColor(Color color, int amount); Color DarkenColor(const Color &color, int amount);
// Quita los espacioes en un string // Quita los espacioes en un string
std::string trim(const std::string &str); std::string trim(const std::string &str);

View File

@@ -1,4 +1,5 @@
#include "writer.h" #include "writer.h"
#include "text.h" // for Text
// Constructor // Constructor
Writer::Writer(std::shared_ptr<Text> text) Writer::Writer(std::shared_ptr<Text> text)
@@ -79,7 +80,7 @@ void Writer::setKerning(int value)
} }
// Establece el valor de la variable // Establece el valor de la variable
void Writer::setCaption(std::string text) void Writer::setCaption(const std::string &text)
{ {
caption_ = text; caption_ = text;
lenght_ = text.length(); lenght_ = text.length();

View File

@@ -1,10 +1,10 @@
#pragma once #pragma once
#include <string> // for string, basic_string #include <memory> // for shared_ptr
#include <memory> #include <string> // for string
#include "text.h" class Text;
// Clase Writer. Pinta texto en pantalla letra a letra a partir de una cadena y un bitmap // Clase Writer. Pinta texto en pantalla letra a letra a partir de una cadena y un objeto Text
class Writer class Writer
{ {
private: private:
@@ -48,7 +48,7 @@ public:
void setKerning(int value); void setKerning(int value);
// Establece el valor de la variable // Establece el valor de la variable
void setCaption(std::string text); void setCaption(const std::string &text);
// Establece el valor de la variable // Establece el valor de la variable
void setSpeed(int value); void setSpeed(int value);