Compare commits

9 Commits

31 changed files with 817 additions and 872 deletions

Binary file not shown.

Before

Width:  |  Height:  |  Size: 935 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 337 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 376 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 364 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 487 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 580 B

View File

@@ -281,7 +281,7 @@ MODE FORA DE LINEA
TAULER DE PUNTS
## 94 - NOTIFICACIONES
Torna a polsar per eixir ...
Torna a polsar per eixir
## 95 - DEFINE BUTTONS
Disparar cap a l'esquerra
@@ -344,4 +344,7 @@ Eixir
Per favor
## 115 - MARCADOR
espere
espere
## 116 - NOTIFICACIONES
Torna a polsar per apagar el sistema

View File

@@ -344,4 +344,7 @@ Exit
Please
## 115 - MARCADOR
wait
wait
## 116 - NOTIFICACIONES
Press again to shutdown system

View File

@@ -344,4 +344,7 @@ Salir
Por favor
## 115 - MARCADOR
espere
espere
## 94 - NOTIFICACIONES
Pulsa otra vez para apagar el sistema

View File

@@ -8,6 +8,7 @@
#include <SDL2/SDL_scancode.h> // for SDL_SCANCODE_0, SDL_SCANCODE_DOWN
#include <SDL2/SDL_stdinc.h> // for SDL_bool, Uint32
#include <SDL2/SDL_timer.h> // for SDL_GetTicks
#include <cstdlib> // for system
#include <errno.h> // for errno, EEXIST, EACCES, ENAMETOO...
#include <stdio.h> // for printf, perror
#include <string.h> // for strcmp
@@ -29,6 +30,7 @@
#include "lang.h" // for Code, loadFromFile
#include "logo.h" // for Logo
#include "manage_hiscore_table.h" // for ManageHiScoreTable
#include "notifier.h" // for Notifier
#include "on_screen_help.h" // for OnScreenHelp
#include "options.h" // for options, loadOptionsFile, saveO...
#include "param.h" // for param, loadParamsFromFile
@@ -101,6 +103,8 @@ Director::Director(int argc, const char *argv[])
Screen::init(window_, renderer_);
Notifier::init(renderer_, std::string(), Asset::get()->get("8bithud.png"), Asset::get()->get("8bithud.txt"), Asset::get()->get("notify.wav"));
OnScreenHelp::init();
// Carga los sonidos del juego
@@ -119,6 +123,7 @@ Director::~Director()
Asset::destroy();
Input::destroy();
Screen::destroy();
Notifier::destroy();
OnScreenHelp::destroy();
sounds_.clear();
@@ -411,7 +416,12 @@ bool Director::setFileList()
Asset::get()->add(prefix + "/data/gfx/game/game_grass.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/game/game_power_meter.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/game/game_sky_colors.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/game/game_text.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/game_text/game_text_1000_points.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/game_text/game_text_2500_points.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/game_text/game_text_5000_points.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/game_text/game_text_powerup.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/game_text/game_text_one_hit.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/intro/intro.png", AssetType::BITMAP);
@@ -692,6 +702,12 @@ int Director::run()
}
}
#ifdef ARCADE
// Comprueba si ha de apagar el sistema
if (section::options == section::Options::QUIT_SHUTDOWN)
shutdownSystem();
#endif
const int return_code = section::options == section::Options::QUIT_NORMAL ? 0 : 1;
return return_code;
}
@@ -718,4 +734,22 @@ std::string Director::getLangFile(lang::Code code)
}
return Asset::get()->get("en_UK.txt");
}
// Apaga el sistema
void Director::shutdownSystem()
{
#ifdef _WIN32
// Apaga el sistema en Windows
system("shutdown /s /t 0");
#elif __APPLE__
// Apaga el sistema en macOS
system("sudo shutdown -h now");
#elif __linux__
// Apaga el sistema en Linux
system("shutdown -h now");
#else
// Sistema operativo no compatible
#error "Sistema operativo no soportado"
#endif
}

View File

@@ -76,6 +76,9 @@ private:
// Obtiene una fichero a partir de un lang::Code
std::string getLangFile(lang::Code code);
// Apaga el sistema
void shutdownSystem();
public:
// Constructor
Director(int argc, const char *argv[]);

View File

@@ -15,7 +15,7 @@ void EnterName::init()
// Inicia la lista de caracteres permitidos
character_list_ = " ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.-+-*/=?¿<>!\"#$%&/()";
pos_ = 0;
position_ = 0;
num_characters_ = (int)character_list_.size();
// Pone la lista de indices para que refleje el nombre
@@ -26,26 +26,27 @@ void EnterName::init()
}
// Incrementa la posición
void EnterName::incPos()
void EnterName::incPosition()
{
pos_++;
pos_ = std::min(pos_, NAME_LENGHT - 1);
position_++;
position_ = std::min(position_, NAME_LENGHT - 1);
checkIfPositionHasBeenUsed();
}
// Decrementa la posición
void EnterName::decPos()
void EnterName::decPosition()
{
pos_--;
pos_ = std::max(pos_, 0);
position_--;
position_ = std::max(position_, 0);
}
// Incrementa el índice
void EnterName::incIndex()
{
++character_index_[pos_];
if (character_index_[pos_] >= num_characters_)
++character_index_[position_];
if (character_index_[position_] >= num_characters_)
{
character_index_[pos_] = 0;
character_index_[position_] = 0;
}
updateName();
}
@@ -53,15 +54,15 @@ void EnterName::incIndex()
// Decrementa el índice
void EnterName::decIndex()
{
--character_index_[pos_];
if (character_index_[pos_] < 0)
--character_index_[position_];
if (character_index_[position_] < 0)
{
character_index_[pos_] = num_characters_ - 1;
character_index_[position_] = num_characters_ - 1;
}
updateName();
}
// Actualiza la variable
// Actualiza el nombre a partir de la lista de índices
void EnterName::updateName()
{
name_.clear();
@@ -74,16 +75,18 @@ void EnterName::updateName()
// Actualiza la variable
void EnterName::updateCharacterIndex()
{
// Rellena de espacios
// Rellena de espacios y marca como no usados
for (int i = 0; i < NAME_LENGHT; ++i)
{
character_index_[i] = 0;
position_has_been_used_[i] = false;
}
// Coloca los índices en funcion de los caracteres que forman el nombre
for (int i = 0; i < (int)name_.size(); ++i)
{
character_index_[i] = findIndex(name_.at(i));
position_has_been_used_[i] = true;
}
}
@@ -107,7 +110,21 @@ std::string EnterName::getName() const
}
// Obtiene la posición que se está editando
int EnterName::getPos() const
int EnterName::getPosition() const
{
return pos_;
return position_;
}
// Comprueba la posición y copia el caracter si es necesario
void EnterName::checkIfPositionHasBeenUsed()
{
auto used = position_has_been_used_[position_];
if (!used && position_ > 0)
{
character_index_[position_] = character_index_[position_ - 1];
}
position_has_been_used_[position_] = true;
updateName();
}

View File

@@ -16,13 +16,14 @@ constexpr int NAME_LENGHT = 8;
class EnterName
{
private:
std::string character_list_; // Lista de todos los caracteres permitidos
std::string name_; // Nombre introducido
int pos_; // Posición a editar del nombre
int num_characters_; // Cantidad de caracteres de la lista de caracteres
int character_index_[NAME_LENGHT]; // Indice de la lista para cada uno de los caracteres que forman el nombre
std::string character_list_; // Lista de todos los caracteres permitidos
std::string name_; // Nombre introducido
int position_; // Posición a editar del nombre
int num_characters_; // Cantidad de caracteres de la lista de caracteres
int character_index_[NAME_LENGHT]; // Indice de la lista para cada uno de los caracteres que forman el nombre
bool position_has_been_used_[NAME_LENGHT]; // Indica si en esa posición se ha puesto ya alguna letra. Se utiliza para replicar la letra anterior la primera vez
// Actualiza la variable
// Actualiza el nombre a partir de la lista de índices
void updateName();
// Actualiza la variable
@@ -31,6 +32,9 @@ private:
// Encuentra el indice de un caracter en "characterList"
int findIndex(char character);
// Comprueba la posición y copia el caracter si es necesario
void checkIfPositionHasBeenUsed();
public:
// Constructor
EnterName();
@@ -42,10 +46,10 @@ public:
void init();
// Incrementa la posición
void incPos();
void incPosition();
// Decrementa la posición
void decPos();
void decPosition();
// Incrementa el índice
void incIndex();
@@ -57,5 +61,5 @@ public:
std::string getName() const;
// Obtiene la posición que se está editando
int getPos() const;
int getPosition() const;
};

View File

@@ -21,10 +21,11 @@
#include "fade.h" // for Fade, FadeType
#include "global_inputs.h" // for check
#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, ItemType::COFFEE_MACHINE, ItemType::CLOCK
#include "jail_audio.h" // for JA_PlaySound, JA_DeleteSound, JA_L...
#include "lang.h" // for getText
#include "manage_hiscore_table.h" // for ManageHiScoreTable
#include "notifier.h" // for Notifier
#include "options.h" // for options
#include "param.h" // for param
#include "player.h" // for Player, PlayerStatus
@@ -39,7 +40,8 @@ struct JA_Sound_t; // lines 36-36
// Constructor
Game::Game(int player_id, int current_stage, bool demo, JA_Music_t *music)
: music_(music), current_stage_(current_stage)
: music_(music),
current_stage_(current_stage)
{
// Copia los punteros
asset_ = Asset::get();
@@ -75,9 +77,11 @@ Game::Game(int player_id, int current_stage, bool demo, JA_Music_t *music)
background_->setPos(param.game.play_area.rect);
p1000_sprite_ = std::make_shared<SmartSprite>(game_text_texture_);
p2500_sprite_ = std::make_shared<SmartSprite>(game_text_texture_);
p5000_sprite_ = std::make_shared<SmartSprite>(game_text_texture_);
// game_text_sprites_.emplace_back(std::make_shared<SmartSprite>(game_text_textures_.at(0)));
// game_text_sprites_.emplace_back(std::make_shared<SmartSprite>(game_text_textures_.at(1)));
// game_text_sprites_.emplace_back(std::make_shared<SmartSprite>(game_text_textures_.at(2)));
// game_text_sprites_.emplace_back(std::make_shared<SmartSprite>(game_text_textures_.at(3)));
// game_text_sprites_.emplace_back(std::make_shared<SmartSprite>(game_text_textures_.at(4)));
explosions_->addTexture(1, explosions_textures_[0], explosions_animations_[0]);
explosions_->addTexture(2, explosions_textures_[1], explosions_animations_[1]);
@@ -295,54 +299,8 @@ void Game::init(int player_id)
// Con los globos creados, calcula el nivel de amenaza
evaluateAndSetMenace();
// Inicializa el bitmap de 1000 puntos
constexpr auto height = 15;
constexpr auto sprite1_width = 35;
constexpr auto sprite2_width = 38;
constexpr auto sprite3_width = 39;
p1000_sprite_->setPosX(0);
p1000_sprite_->setPosY(0);
p1000_sprite_->setWidth(sprite1_width);
p1000_sprite_->setHeight(height);
p1000_sprite_->setVelX(0.0f);
p1000_sprite_->setVelY(-0.5f);
p1000_sprite_->setAccelX(0.0f);
p1000_sprite_->setAccelY(-0.1f);
p1000_sprite_->setSpriteClip(0, 0, sprite1_width, height);
p1000_sprite_->setEnabled(false);
p1000_sprite_->setFinishedCounter(0);
p1000_sprite_->setDestX(0);
p1000_sprite_->setDestY(0);
// Inicializa el bitmap de 2500 puntos
p2500_sprite_->setPosX(0);
p2500_sprite_->setPosY(0);
p2500_sprite_->setWidth(sprite2_width);
p2500_sprite_->setHeight(height);
p2500_sprite_->setVelX(0.0f);
p2500_sprite_->setVelY(-0.5f);
p2500_sprite_->setAccelX(0.0f);
p2500_sprite_->setAccelY(-0.1f);
p2500_sprite_->setSpriteClip(sprite1_width, 0, sprite2_width, height);
p2500_sprite_->setEnabled(false);
p2500_sprite_->setFinishedCounter(0);
p2500_sprite_->setDestX(0);
p2500_sprite_->setDestY(0);
// Inicializa el bitmap de 5000 puntos
p5000_sprite_->setPosX(0);
p5000_sprite_->setPosY(0);
p5000_sprite_->setWidth(sprite3_width);
p5000_sprite_->setHeight(height);
p5000_sprite_->setVelX(0.0f);
p5000_sprite_->setVelY(-0.5f);
p5000_sprite_->setAccelX(0.0f);
p5000_sprite_->setAccelY(-0.1f);
p5000_sprite_->setSpriteClip(sprite1_width + sprite2_width, 0, sprite3_width, height);
p5000_sprite_->setEnabled(false);
p5000_sprite_->setFinishedCounter(0);
p5000_sprite_->setDestX(0);
p5000_sprite_->setDestY(0);
// Inicializa los sprites con los textos que aparecen al coger items
smart_sprites_.clear();
}
// Carga los recursos necesarios para la sección 'Game'
@@ -362,93 +320,73 @@ void Game::loadMedia()
item_textures_.clear();
balloon_textures_.clear();
explosions_textures_.clear();
game_text_textures_.clear();
}
// Texturas
{
bullet_texture_ = std::make_shared<Texture>(renderer_, asset_->get("bullet.png"));
game_text_texture_ = std::make_shared<Texture>(renderer_, asset_->get("game_text.png"));
}
// Texturas - Game_text
{
game_text_textures_.emplace_back(std::make_shared<Texture>(renderer_, asset_->get("game_text_1000_points.png")));
game_text_textures_.emplace_back(std::make_shared<Texture>(renderer_, asset_->get("game_text_2500_points.png")));
game_text_textures_.emplace_back(std::make_shared<Texture>(renderer_, asset_->get("game_text_5000_points.png")));
game_text_textures_.emplace_back(std::make_shared<Texture>(renderer_, asset_->get("game_text_powerup.png")));
game_text_textures_.emplace_back(std::make_shared<Texture>(renderer_, asset_->get("game_text_one_hit.png")));
}
// Texturas - Globos
{
auto balloon1_texture = std::make_shared<Texture>(renderer_, asset_->get("balloon1.png"));
balloon_textures_.push_back(balloon1_texture);
balloon_textures_.emplace_back(std::make_shared<Texture>(renderer_, asset_->get("balloon1.png")));
balloon_textures_.emplace_back(std::make_shared<Texture>(renderer_, asset_->get("balloon2.png")));
balloon_textures_.emplace_back(std::make_shared<Texture>(renderer_, asset_->get("balloon3.png")));
balloon_textures_.emplace_back(std::make_shared<Texture>(renderer_, asset_->get("balloon4.png")));
balloon_textures_.emplace_back(std::make_shared<Texture>(renderer_, asset_->get("powerball.png")));
}
auto balloon2_texture = std::make_shared<Texture>(renderer_, asset_->get("balloon2.png"));
balloon_textures_.push_back(balloon2_texture);
auto balloon3_texture = std::make_shared<Texture>(renderer_, asset_->get("balloon3.png"));
balloon_textures_.push_back(balloon3_texture);
auto balloon4_texture = std::make_shared<Texture>(renderer_, asset_->get("balloon4.png"));
balloon_textures_.push_back(balloon4_texture);
auto balloon5_texture = std::make_shared<Texture>(renderer_, asset_->get("powerball.png"));
balloon_textures_.push_back(balloon5_texture);
// Texturas - Explosiones
auto explosion1_texture = std::make_shared<Texture>(renderer_, asset_->get("explosion1.png"));
explosions_textures_.push_back(explosion1_texture);
auto explosion2_texture = std::make_shared<Texture>(renderer_, asset_->get("explosion2.png"));
explosions_textures_.push_back(explosion2_texture);
auto explosion3_texture = std::make_shared<Texture>(renderer_, asset_->get("explosion3.png"));
explosions_textures_.push_back(explosion3_texture);
auto explosion4_texture = std::make_shared<Texture>(renderer_, asset_->get("explosion4.png"));
explosions_textures_.push_back(explosion4_texture);
// Texturas - Explosiones
{
explosions_textures_.emplace_back(std::make_shared<Texture>(renderer_, asset_->get("explosion1.png")));
explosions_textures_.emplace_back(std::make_shared<Texture>(renderer_, asset_->get("explosion2.png")));
explosions_textures_.emplace_back(std::make_shared<Texture>(renderer_, asset_->get("explosion3.png")));
explosions_textures_.emplace_back(std::make_shared<Texture>(renderer_, asset_->get("explosion4.png")));
}
// Texturas - Items
{
auto item1 = std::make_shared<Texture>(renderer_, asset_->get("item_points1_disk.png"));
item_textures_.push_back(item1);
auto item2 = std::make_shared<Texture>(renderer_, asset_->get("item_points2_gavina.png"));
item_textures_.push_back(item2);
auto item3 = std::make_shared<Texture>(renderer_, asset_->get("item_points3_pacmar.png"));
item_textures_.push_back(item3);
auto item4 = std::make_shared<Texture>(renderer_, asset_->get("item_clock.png"));
item_textures_.push_back(item4);
auto item5 = std::make_shared<Texture>(renderer_, asset_->get("item_coffee.png"));
item_textures_.push_back(item5);
auto item6 = std::make_shared<Texture>(renderer_, asset_->get("item_coffee_machine.png"));
item_textures_.push_back(item6);
item_textures_.emplace_back(std::make_shared<Texture>(renderer_, asset_->get("item_points1_disk.png")));
item_textures_.emplace_back(std::make_shared<Texture>(renderer_, asset_->get("item_points2_gavina.png")));
item_textures_.emplace_back(std::make_shared<Texture>(renderer_, asset_->get("item_points3_pacmar.png")));
item_textures_.emplace_back(std::make_shared<Texture>(renderer_, asset_->get("item_clock.png")));
item_textures_.emplace_back(std::make_shared<Texture>(renderer_, asset_->get("item_coffee.png")));
item_textures_.emplace_back(std::make_shared<Texture>(renderer_, asset_->get("item_coffee_machine.png")));
}
// Texturas - Player1
{
auto player1_texture = std::make_shared<Texture>(renderer_, asset_->get("player1.gif"));
player1_texture->addPalette(asset_->get("player1_pal1.gif"));
player1_texture->addPalette(asset_->get("player1_pal2.gif"));
player1_texture->addPalette(asset_->get("player1_pal3.gif"));
player1_textures_.push_back(player1_texture);
player1_textures_.emplace_back(std::make_shared<Texture>(renderer_, asset_->get("player1.gif")));
player1_textures_.back()->addPalette(asset_->get("player1_pal1.gif"));
player1_textures_.back()->addPalette(asset_->get("player1_pal2.gif"));
player1_textures_.back()->addPalette(asset_->get("player1_pal3.gif"));
auto player1_power_texture = std::make_shared<Texture>(renderer_, asset_->get("player_power.gif"));
player1_power_texture->addPalette(asset_->get("player_power_pal.gif"));
player1_textures_.push_back(player1_power_texture);
player1_textures_.emplace_back(std::make_shared<Texture>(renderer_, asset_->get("player_power.gif")));
player1_textures_.back()->addPalette(asset_->get("player_power_pal.gif"));
player_textures_.push_back(player1_textures_);
}
// Texturas - Player2
{
auto player2_texture = std::make_shared<Texture>(renderer_, asset_->get("player2.gif"));
player2_texture->addPalette(asset_->get("player2_pal1.gif"));
player2_texture->addPalette(asset_->get("player2_pal2.gif"));
player2_texture->addPalette(asset_->get("player2_pal3.gif"));
player2_textures_.push_back(player2_texture);
player2_textures_.emplace_back(std::make_shared<Texture>(renderer_, asset_->get("player2.gif")));
player2_textures_.back()->addPalette(asset_->get("player2_pal1.gif"));
player2_textures_.back()->addPalette(asset_->get("player2_pal2.gif"));
player2_textures_.back()->addPalette(asset_->get("player2_pal3.gif"));
auto player2_power_texture = std::make_shared<Texture>(renderer_, asset_->get("player_power.gif"));
player2_power_texture->addPalette(asset_->get("player_power_pal.gif"));
player2_power_texture->setPalette(1);
player2_textures_.push_back(player2_power_texture);
player2_textures_.emplace_back(std::make_shared<Texture>(renderer_, asset_->get("player_power.gif")));
player2_textures_.back()->addPalette(asset_->get("player_power_pal.gif"));
player2_textures_.back()->setPalette(1);
player_textures_.push_back(player2_textures_);
}
@@ -1192,50 +1130,55 @@ void Game::checkPlayerItemCollision(std::shared_ptr<Player> &player)
{
if (checkCollision(player->getCollider(), item->getCollider()))
{
switch (item->getClass())
switch (item->getType())
{
case ITEM_POINTS_1_DISK:
case ItemType::DISK:
{
player->addScore(1000);
createItemScoreSprite(item->getPosX() + (item->getWidth() / 2) - (p1000_sprite_->getWidth() / 2), player->getPosY(), p1000_sprite_);
createItemScoreSprite(item->getPosX() + (item->getWidth() / 2) - (game_text_textures_[0]->getWidth() / 2), player->getPosY(), game_text_textures_[0]);
break;
}
case ITEM_POINTS_2_GAVINA:
case ItemType::GAVINA:
{
player->addScore(2500);
createItemScoreSprite(item->getPosX() + (item->getWidth() / 2) - (p2500_sprite_->getWidth() / 2), player->getPosY(), p2500_sprite_);
createItemScoreSprite(item->getPosX() + (item->getWidth() / 2) - (game_text_textures_[1]->getWidth() / 2), player->getPosY(), game_text_textures_[1]);
break;
}
case ITEM_POINTS_3_PACMAR:
case ItemType::PACMAR:
{
player->addScore(5000);
createItemScoreSprite(item->getPosX() + (item->getWidth() / 2) - (p5000_sprite_->getWidth() / 2), player->getPosY(), p5000_sprite_);
createItemScoreSprite(item->getPosX() + (item->getWidth() / 2) - (game_text_textures_[2]->getWidth() / 2), player->getPosY(), game_text_textures_[2]);
break;
}
case ITEM_CLOCK:
case ItemType::CLOCK:
{
enableTimeStopItem();
break;
}
case ITEM_COFFEE:
case ItemType::COFFEE:
{
if (player->getCoffees() == 2)
{
player->addScore(5000);
createItemScoreSprite(item->getPosX() + (item->getWidth() / 2) - (p5000_sprite_->getWidth() / 2), player->getPosY(), p5000_sprite_);
createItemScoreSprite(item->getPosX() + (item->getWidth() / 2) - (game_text_textures_[2]->getWidth() / 2), player->getPosY(), game_text_textures_[2]);
}
else
{
player->giveExtraHit();
createItemScoreSprite(item->getPosX() + (item->getWidth() / 2) - (game_text_textures_[4]->getWidth() / 2), player->getPosY(), game_text_textures_[4]);
}
player->giveExtraHit();
break;
}
case ITEM_COFFEE_MACHINE:
case ItemType::COFFEE_MACHINE:
{
player->setPowerUp();
coffee_machine_enabled_ = false;
createItemScoreSprite(item->getPosX() + (item->getWidth() / 2) - (game_text_textures_[3]->getWidth() / 2), player->getPosY(), game_text_textures_[3]);
break;
}
@@ -1274,9 +1217,9 @@ void Game::checkBulletBalloonCollision()
// Suelta el item si se da el caso
const auto droppeditem = dropItem();
if (droppeditem != ITEM_NULL && !demo_.recording)
if (droppeditem != ItemType::NONE && !demo_.recording)
{
if (droppeditem != ITEM_COFFEE_MACHINE)
if (droppeditem != ItemType::COFFEE_MACHINE)
{
createItem(droppeditem, balloon->getPosX(), balloon->getPosY());
JA_PlaySound(item_drop_sound_);
@@ -1380,7 +1323,7 @@ void Game::renderItems()
}
// Devuelve un item al azar y luego segun sus probabilidades
int Game::dropItem()
ItemType Game::dropItem()
{
const auto lucky_number = rand() % 100;
const auto item = rand() % 6;
@@ -1390,28 +1333,28 @@ int Game::dropItem()
case 0:
if (lucky_number < helper_.item_disk_odds)
{
return ITEM_POINTS_1_DISK;
return ItemType::DISK;
}
break;
case 1:
if (lucky_number < helper_.item_gavina_odds)
{
return ITEM_POINTS_2_GAVINA;
return ItemType::GAVINA;
}
break;
case 2:
if (lucky_number < helper_.item_pacmar_odds)
{
return ITEM_POINTS_3_PACMAR;
return ItemType::GAVINA;
}
break;
case 3:
if (lucky_number < helper_.item_clock_odds)
{
return ITEM_CLOCK;
return ItemType::CLOCK;
}
break;
@@ -1419,7 +1362,7 @@ int Game::dropItem()
if (lucky_number < helper_.item_coffee_odds)
{
helper_.item_coffee_odds = ITEM_COFFEE_ODDS;
return ITEM_COFFEE;
return ItemType::COFFEE;
}
else
{
@@ -1436,7 +1379,7 @@ int Game::dropItem()
helper_.item_coffee_machine_odds = ITEM_COFFEE_MACHINE_ODDS;
if (!coffee_machine_enabled_ && helper_.need_coffee_machine)
{
return ITEM_COFFEE_MACHINE;
return ItemType::COFFEE_MACHINE;
}
}
else
@@ -1452,14 +1395,13 @@ int Game::dropItem()
break;
}
return ITEM_NULL;
return ItemType::NONE;
}
// Crea un objeto item
void Game::createItem(int kind, float x, float y)
void Game::createItem(ItemType type, float x, float y)
{
auto item = std::make_unique<Item>(kind, x, y, &(param.game.play_area.rect), item_textures_[kind - 1], item_animations_[kind - 1]);
items_.push_back(std::move(item));
items_.emplace_back(std::make_unique<Item>(type, x, y, &(param.game.play_area.rect), item_textures_[static_cast<int>(type) - 1], item_animations_[static_cast<int>(type) - 1]));
}
// Vacia el vector de items
@@ -1478,19 +1420,21 @@ void Game::freeItems()
}
// Crea un objeto SmartSprite para mostrar la puntuación al coger un objeto
void Game::createItemScoreSprite(int x, int y, std::shared_ptr<SmartSprite> sprite)
void Game::createItemScoreSprite(int x, int y, std::shared_ptr<Texture> texture)
{
auto ss = new SmartSprite(nullptr);
smart_sprites_.push_back(ss);
smart_sprites_.emplace_back(std::make_unique<SmartSprite>(texture));
// Crea una copia del objeto
*ss = *sprite;
ss->setPosX(x);
ss->setPosY(y);
ss->setDestX(x);
ss->setDestY(y - 25);
ss->setEnabled(true);
ss->setFinishedCounter(100);
// Inicializa
smart_sprites_.back()->setPos({0, 0, texture->getWidth(), texture->getHeight()});
smart_sprites_.back()->setSpriteClip(smart_sprites_.back()->getPos());
smart_sprites_.back()->setPosX(x);
smart_sprites_.back()->setPosY(y);
smart_sprites_.back()->setDestX(x);
smart_sprites_.back()->setDestY(y - 25);
smart_sprites_.back()->setVelY(-0.5f);
smart_sprites_.back()->setAccelY(-0.1f);
smart_sprites_.back()->setEnabled(true);
smart_sprites_.back()->setFinishedCounter(100);
}
// Vacia el vector de smartsprites
@@ -1511,31 +1455,30 @@ void Game::freeSmartSprites()
// Crea un SmartSprite para arrojar el item café al recibir un impacto
void Game::throwCoffee(int x, int y)
{
auto ss = new SmartSprite(item_textures_[4]);
smart_sprites_.push_back(ss);
smart_sprites_.emplace_back(std::make_unique<SmartSprite>(item_textures_[4]));
ss->setPosX(x - 8);
ss->setPosY(y - 8);
ss->setWidth(param.game.item_size);
ss->setHeight(param.game.item_size);
ss->setVelX(-1.0f + ((rand() % 5) * 0.5f));
ss->setVelY(-4.0f);
ss->setAccelX(0.0f);
ss->setAccelY(0.2f);
ss->setDestX(x + (ss->getVelX() * 50));
ss->setDestY(param.game.height + 1);
ss->setEnabled(true);
ss->setFinishedCounter(1);
ss->setSpriteClip(0, param.game.item_size, param.game.item_size, param.game.item_size);
ss->setRotate(true);
ss->setRotateSpeed(10);
ss->setRotateAmount(90.0);
smart_sprites_.back()->setPosX(x - 8);
smart_sprites_.back()->setPosY(y - 8);
smart_sprites_.back()->setWidth(param.game.item_size);
smart_sprites_.back()->setHeight(param.game.item_size);
smart_sprites_.back()->setVelX(-1.0f + ((rand() % 5) * 0.5f));
smart_sprites_.back()->setVelY(-4.0f);
smart_sprites_.back()->setAccelX(0.0f);
smart_sprites_.back()->setAccelY(0.2f);
smart_sprites_.back()->setDestX(x + (smart_sprites_.back()->getVelX() * 50));
smart_sprites_.back()->setDestY(param.game.height + 1);
smart_sprites_.back()->setEnabled(true);
smart_sprites_.back()->setFinishedCounter(1);
smart_sprites_.back()->setSpriteClip(0, param.game.item_size, param.game.item_size, param.game.item_size);
smart_sprites_.back()->setRotate(true);
smart_sprites_.back()->setRotateSpeed(10);
smart_sprites_.back()->setRotateAmount(90.0);
}
// Actualiza los SmartSprites
void Game::updateSmartSprites()
{
for (auto ss : smart_sprites_)
for (auto &ss : smart_sprites_)
{
ss->update();
}
@@ -1544,7 +1487,7 @@ void Game::updateSmartSprites()
// Pinta los SmartSprites activos
void Game::renderSmartSprites()
{
for (auto ss : smart_sprites_)
for (auto &ss : smart_sprites_)
{
ss->render();
}
@@ -2462,7 +2405,7 @@ void Game::checkEvents()
case SDLK_3:
{
auto_pop_balloons_ = !auto_pop_balloons_;
screen_->showNotification("auto_pop_balloons_ " + boolToString(auto_pop_balloons_));
Notifier::get()->showText("auto_pop_balloons_ " + boolToString(auto_pop_balloons_));
break;
}
@@ -2541,8 +2484,12 @@ void Game::reloadTextures()
texture->reLoad();
}
for (auto &texture : game_text_textures_)
{
texture->reLoad();
}
bullet_texture_->reLoad();
game_text_texture_->reLoad();
background_->reloadTextures();
}

View File

@@ -24,6 +24,7 @@ class Texture;
enum class BulletType; // lines 26-26
struct JA_Music_t; // lines 27-27
struct JA_Sound_t; // lines 28-28
enum class ItemType;
// Modo demo
constexpr bool GAME_MODE_DEMO_OFF = false;
@@ -118,11 +119,11 @@ private:
SDL_Texture *canvas_; // Textura para dibujar la zona de juego
std::vector<std::shared_ptr<Player>> players_; // Vector con los jugadores
std::vector<std::shared_ptr<Balloon>> balloons_; // Vector con los globos
std::vector<std::unique_ptr<Bullet>> bullets_; // Vector con las balas
std::vector<std::unique_ptr<Item>> items_; // Vector con los items
std::vector<SmartSprite *> smart_sprites_; // Vector con los smartsprites
std::vector<std::shared_ptr<Player>> players_; // Vector con los jugadores
std::vector<std::shared_ptr<Balloon>> balloons_; // Vector con los globos
std::vector<std::unique_ptr<Bullet>> bullets_; // Vector con las balas
std::vector<std::unique_ptr<Item>> items_; // Vector con los items
std::vector<std::unique_ptr<SmartSprite>> smart_sprites_; // Vector con los smartsprites
std::shared_ptr<Texture> bullet_texture_; // Textura para las balas
std::vector<std::shared_ptr<Texture>> item_textures_; // Vector con las texturas de los items
@@ -132,7 +133,8 @@ private:
std::vector<std::shared_ptr<Texture>> player2_textures_; // Vector con las texturas del jugador
std::vector<std::vector<std::shared_ptr<Texture>>> player_textures_; // Vector con todas las texturas de los jugadores;
std::shared_ptr<Texture> game_text_texture_; // Textura para los sprites con textos
std::vector<std::shared_ptr<Texture>> game_text_textures_; // Vector con las texturas para los sprites con textos
//std::vector<std::shared_ptr<SmartSprite>> game_text_sprites_; // Sprite con el textos que aparecen al coger items
std::vector<std::vector<std::string> *> item_animations_; // Vector con las animaciones de los items
std::vector<std::vector<std::string> *> player_animations_; // Vector con las animaciones del jugador
@@ -146,10 +148,6 @@ private:
std::unique_ptr<Fade> fade_; // Objeto para renderizar fades
std::shared_ptr<SmartSprite> p1000_sprite_; // Sprite con el texto 1.000
std::shared_ptr<SmartSprite> p2500_sprite_; // Sprite con el texto 2.500
std::shared_ptr<SmartSprite> p5000_sprite_; // Sprite con el texto 5.000
JA_Sound_t *balloon_sound_; // Sonido para la explosión del globo
JA_Sound_t *bullet_sound_; // Sonido para los disparos
JA_Sound_t *player_collision_sound_; // Sonido para la colisión del jugador con un enemigo
@@ -315,16 +313,16 @@ private:
void renderItems();
// Devuelve un item en función del azar
int dropItem();
ItemType dropItem();
// Crea un objeto item
void createItem(int kind, float x, float y);
void createItem(ItemType type, float x, float y);
// Vacia el vector de items
void freeItems();
// Crea un objeto SmartSprite
void createItemScoreSprite(int x, int y, std::shared_ptr<SmartSprite> sprite);
void createItemScoreSprite(int x, int y, std::shared_ptr<Texture> texture);
// Vacia el vector de smartsprites
void freeSmartSprites();

View File

@@ -3,6 +3,7 @@
#include "input.h" // for Input, inputs_e, INPUT_DO_NOT_ALLOW_REPEAT
#include "jail_audio.h" // for JA_EnableMusic, JA_EnableSound
#include "lang.h" // for getText
#include "notifier.h" // for Notifier
#include "options.h" // for options
#include "on_screen_help.h"
#include "screen.h" // for Screen
@@ -28,14 +29,21 @@ namespace globalInputs
// Termina
void quit(section::Options code)
{
if (Screen::get()->notificationsAreActive())
const std::string exit_code = "QUIT";
auto code_found = stringInVector(Notifier::get()->getCodes(), exit_code);
if (code_found)
{
section::name = section::Name::QUIT;
section::options = code;
}
else
{
Screen::get()->showNotification(lang::getText(94));
#ifdef ARCADE
const int index = code == section::Options::QUIT_NORMAL ? 94 : 116;
Notifier::get()->showText(lang::getText(index), std::string(), -1, exit_code);
#else
Notifier::get()->showText(lang::getText(94), std::string(), -1, exit_code);
#endif
}
}
@@ -43,7 +51,7 @@ namespace globalInputs
void reset()
{
section::name = section::Name::INIT;
Screen::get()->showNotification("Reset");
Notifier::get()->showText("Reset");
}
// Activa o desactiva el audio
@@ -52,7 +60,7 @@ namespace globalInputs
options.audio.sound.enabled = options.audio.music.enabled = !options.audio.music.enabled;
JA_EnableMusic(options.audio.music.enabled);
JA_EnableSound(options.audio.sound.enabled);
Screen::get()->showNotification("Audio " + boolToOnOff(options.audio.music.enabled));
Notifier::get()->showText("Audio " + boolToOnOff(options.audio.music.enabled));
}
// Comprueba los inputs que se pueden introducir en cualquier sección del juego

View File

@@ -5,16 +5,16 @@
class Texture;
// Constructor
Item::Item(int kind, float x, float y, SDL_Rect *play_area, std::shared_ptr<Texture> texture, std::vector<std::string> *animation)
Item::Item(ItemType type, float x, float y, SDL_Rect *play_area, std::shared_ptr<Texture> texture, std::vector<std::string> *animation)
: sprite_(std::make_unique<AnimatedSprite>(texture, "", animation)),
accel_x_(0.0f),
floor_collision_(false),
kind_(kind),
type_(type),
enabled_(true),
play_area_(play_area),
time_to_live_(600)
{
if (kind == ITEM_COFFEE_MACHINE)
if (type == ItemType::COFFEE_MACHINE)
{
width_ = 28;
height_ = 37;
@@ -104,7 +104,7 @@ void Item::move()
}
// Si se sale por arriba rebota (excepto la maquina de café)
if ((pos_y_ < param.game.play_area.rect.y) && !(kind_ == ITEM_COFFEE_MACHINE))
if ((pos_y_ < param.game.play_area.rect.y) && !(type_ == ItemType::COFFEE_MACHINE))
{
// Corrige
pos_y_ = param.game.play_area.rect.y;
@@ -122,7 +122,7 @@ void Item::move()
accel_x_ = 0;
accel_y_ = 0;
pos_y_ = play_area_->h - height_;
if (kind_ == ITEM_COFFEE_MACHINE)
if (type_ == ItemType::COFFEE_MACHINE)
{
floor_collision_ = true;
}
@@ -190,9 +190,9 @@ int Item::getHeight()
}
// Obtiene del valor de la variable
int Item::getClass()
ItemType Item::getType()
{
return kind_;
return type_;
}
// Obtiene el valor de la variable

View File

@@ -1,22 +1,25 @@
#pragma once
#include <SDL2/SDL_rect.h> // for SDL_Rect
#include <SDL2/SDL_stdinc.h> // for Uint16
#include <memory> // for shared_ptr, unique_ptr
#include <string> // for string
#include <vector> // for vector
#include "animated_sprite.h" // for AnimatedSprite
#include "utils.h" // for Circle
#include <SDL2/SDL_rect.h> // for SDL_Rect
#include <SDL2/SDL_stdinc.h> // for Uint16
#include <memory> // for shared_ptr, unique_ptr
#include <string> // for string
#include <vector> // for vector
#include "animated_sprite.h" // for AnimatedSprite
#include "utils.h" // for Circle
class Texture;
// Tipos de objetos
constexpr int ITEM_POINTS_1_DISK = 1;
constexpr int ITEM_POINTS_2_GAVINA = 2;
constexpr int ITEM_POINTS_3_PACMAR = 3;
constexpr int ITEM_CLOCK = 4;
constexpr int ITEM_COFFEE = 5;
constexpr int ITEM_COFFEE_MACHINE = 6;
constexpr int ITEM_NULL = 7;
enum class ItemType : int
{
DISK = 1,
GAVINA = 2,
PACMAR = 3,
CLOCK = 4,
COFFEE = 5,
COFFEE_MACHINE = 6,
NONE = 7,
};
// Clase Item
class Item
@@ -35,7 +38,7 @@ private:
float accel_x_; // Aceleración en el eje X
float accel_y_; // Aceleración en el eje Y
bool floor_collision_; // Indica si el objeto colisiona con el suelo
int kind_; // Especifica el tipo de objeto que es
ItemType type_; // Especifica el tipo de objeto que es
bool enabled_; // Especifica si el objeto está habilitado
Circle collider_; // Circulo de colisión del objeto
SDL_Rect *play_area_; // Rectangulo con la zona de juego
@@ -55,7 +58,7 @@ private:
public:
// Constructor
Item(int kind, float x, float y, SDL_Rect *play_area, std::shared_ptr<Texture> texture, std::vector<std::string> *animation);
Item(ItemType type, float x, float y, SDL_Rect *play_area, std::shared_ptr<Texture> texture, std::vector<std::string> *animation);
// Destructor
~Item() = default;
@@ -85,7 +88,7 @@ public:
int getHeight();
// Obtiene del valor de la variable
int getClass();
ItemType getType();
// Obtiene el valor de la variable
bool isEnabled();

View File

@@ -1,166 +0,0 @@
#ifdef JA_USESDLMIXER
#include "jail_audio.h"
#include <SDL2/SDL.h>
#include <SDL2/SDL_mixer.h>
#include <stdio.h>
struct JA_Sound_t {}; // Dummy structs
struct JA_Music_t {};
int JA_freq {48000};
SDL_AudioFormat JA_format {AUDIO_S16};
Uint8 JA_channels {2};
int JA_musicVolume = 128;
int JA_soundVolume = 64;
bool JA_musicEnabled = true;
bool JA_soundEnabled = true;
void JA_Init(const int freq, const SDL_AudioFormat format, const int channels) {
JA_freq = freq;
JA_format = format;
JA_channels = channels;
Mix_OpenAudio(JA_freq, JA_format, JA_channels, 1024);
}
void JA_Quit() {
Mix_CloseAudio();
}
JA_Music_t *JA_LoadMusic(const char* filename) {
return (JA_Music_t*)Mix_LoadMUS(filename);
}
void JA_PlayMusic(JA_Music_t *music, const int loop)
{
if (!JA_musicEnabled) return;
Mix_PlayMusic((Mix_Music*)music, loop);
Mix_VolumeMusic(JA_musicVolume);
}
void JA_PauseMusic()
{
if (!JA_musicEnabled) return;
Mix_PauseMusic();
}
void JA_ResumeMusic()
{
if (!JA_musicEnabled) return;
Mix_ResumeMusic();
}
void JA_StopMusic()
{
if (!JA_musicEnabled) return;
Mix_HaltMusic();
}
JA_Music_state JA_GetMusicState()
{
if (!JA_musicEnabled) return JA_MUSIC_DISABLED;
if (Mix_PausedMusic()) {
return JA_MUSIC_PAUSED;
} else if (Mix_PlayingMusic()) {
return JA_MUSIC_PLAYING;
} else {
return JA_MUSIC_STOPPED;
}
}
void JA_DeleteMusic(JA_Music_t *music)
{
Mix_FreeMusic((Mix_Music*)music);
}
int JA_SetMusicVolume(int volume)
{
JA_musicVolume = volume;
Mix_VolumeMusic(JA_musicVolume);
return JA_musicVolume;
}
void JA_EnableMusic(const bool value)
{
if (Mix_PlayingMusic()) Mix_HaltMusic();
JA_musicEnabled = value;
}
JA_Sound_t *JA_NewSound(Uint8* buffer, Uint32 length)
{
return NULL;
}
JA_Sound_t *JA_LoadSound(const char* filename) {
JA_Sound_t *sound = (JA_Sound_t*)Mix_LoadWAV(filename);
return sound;
}
int JA_PlaySound(JA_Sound_t *sound, const int loop) {
if (!JA_soundEnabled) return -1;
const int channel = Mix_PlayChannel(-1, (Mix_Chunk*)sound, loop);
Mix_Volume(-1, JA_soundVolume);
return channel;
}
void JA_DeleteSound(JA_Sound_t *sound)
{
Mix_FreeChunk((Mix_Chunk*)sound);
}
void JA_PauseChannel(const int channel)
{
if (!JA_soundEnabled) return;
Mix_Pause(channel);
}
void JA_ResumeChannel(const int channel)
{
if (!JA_soundEnabled) return;
Mix_Resume(channel);
}
void JA_StopChannel(const int channel)
{
if (!JA_soundEnabled) return;
Mix_HaltChannel(channel);
}
JA_Channel_state JA_GetChannelState(const int channel)
{
if (!JA_soundEnabled) return JA_SOUND_DISABLED;
if (Mix_Paused(channel)) {
return JA_CHANNEL_PAUSED;
} else if (Mix_Playing(channel)) {
return JA_CHANNEL_PLAYING;
} else {
return JA_CHANNEL_FREE;
}
}
int JA_SetSoundVolume(int volume)
{
JA_musicVolume = volume;
Mix_Volume(-1, JA_musicVolume);
return JA_musicVolume;
}
void JA_EnableSound(const bool value)
{
Mix_HaltChannel(-1);
JA_soundEnabled = value;
}
int JA_SetVolume(int volume)
{
JA_SetSoundVolume(volume);
return JA_SetMusicVolume(volume);
}
#endif

341
source/notifier.cpp Normal file
View File

@@ -0,0 +1,341 @@
#include "notifier.h"
#include <SDL2/SDL_blendmode.h> // for SDL_BLENDMODE_BLEND
#include <SDL2/SDL_pixels.h> // for SDL_PIXELFORMAT_RGBA8888
#include <string> // for string
#include "jail_audio.h" // for JA_DeleteSound, JA_LoadSound, JA_Pla...
#include "param.h" // for param
#include "sprite.h" // for Sprite
#include "text.h" // for Text
#include "texture.h" // for Texture
// [SINGLETON] Hay que definir las variables estáticas, desde el .h sólo la hemos declarado
Notifier *Notifier::notifier_ = nullptr;
// [SINGLETON] Crearemos el objeto screen con esta función estática
void Notifier::init(SDL_Renderer *renderer, std::string icon_file, std::string bitmap_file, std::string text_file, const std::string &sound_file)
{
Notifier::notifier_ = new Notifier(renderer, icon_file, bitmap_file, text_file, sound_file);
}
// [SINGLETON] Destruiremos el objeto screen con esta función estática
void Notifier::destroy()
{
delete Notifier::notifier_;
}
// [SINGLETON] Con este método obtenemos el objeto screen y podemos trabajar con él
Notifier *Notifier::get()
{
return Notifier::notifier_;
}
// Constructor
Notifier::Notifier(SDL_Renderer *renderer, std::string icon_file, std::string bitmap_file, std::string text_file, const std::string &sound_file)
: renderer_(renderer),
text_(std::make_unique<Text>(bitmap_file, text_file, renderer)),
bg_color_(param.notification.color),
wait_time_(150),
stack_(false),
sound_(JA_LoadSound(sound_file.c_str()))
{
// Inicializa variables
has_icons_ = !icon_file.empty();
// Crea objetos
icon_texture_ = has_icons_ ? std::make_unique<Texture>(renderer, icon_file) : nullptr;
}
// Destructor
Notifier::~Notifier()
{
// Libera la memoria de los objetos
JA_DeleteSound(sound_);
notifications_.clear();
}
// Dibuja las notificaciones por pantalla
void Notifier::render()
{
for (int i = (int)notifications_.size() - 1; i >= 0; --i)
{
notifications_[i].sprite->render();
}
}
// Actualiza el estado de las notificaiones
void Notifier::update()
{
for (int i = 0; i < (int)notifications_.size(); ++i)
{
// Si la notificación anterior está "saliendo", no hagas nada
if (i > 0)
{
if (notifications_[i - 1].status == NotificationStatus::RISING)
{
break;
}
}
notifications_[i].counter++;
// Hace sonar la notificación en el primer frame
if (notifications_[i].counter == 1)
{
if (param.notification.sound)
{
if (notifications_[i].status == NotificationStatus::RISING)
{ // Reproduce el sonido de la notificación
JA_PlaySound(sound_);
}
}
}
// Comprueba los estados
if (notifications_[i].status == NotificationStatus::RISING)
{
const float step = ((float)notifications_[i].counter / notifications_[i].travel_dist);
const int alpha = 255 * step;
if (param.notification.pos_v == NotifyPosition::TOP)
{
notifications_[i].rect.y++;
}
else
{
notifications_[i].rect.y--;
}
notifications_[i].texture->setAlpha(alpha);
if (notifications_[i].rect.y == notifications_[i].y)
{
notifications_[i].status = NotificationStatus::STAY;
notifications_[i].texture->setAlpha(255);
notifications_[i].counter = 0;
}
}
else if (notifications_[i].status == NotificationStatus::STAY)
{
if (notifications_[i].counter == wait_time_)
{
notifications_[i].status = NotificationStatus::VANISHING;
notifications_[i].counter = 0;
}
}
else if (notifications_[i].status == NotificationStatus::VANISHING)
{
const float step = (notifications_[i].counter / (float)notifications_[i].travel_dist);
const int alpha = 255 * (1 - step);
if (param.notification.pos_v == NotifyPosition::TOP)
{
notifications_[i].rect.y--;
}
else
{
notifications_[i].rect.y++;
}
notifications_[i].texture->setAlpha(alpha);
if (notifications_[i].rect.y == notifications_[i].y - notifications_[i].travel_dist)
{
notifications_[i].status = NotificationStatus::FINISHED;
}
}
notifications_[i].sprite->setPos(notifications_[i].rect);
}
clearFinishedNotifications();
}
// Elimina las notificaciones finalizadas
void Notifier::clearFinishedNotifications()
{
for (int i = (int)notifications_.size() - 1; i >= 0; --i)
{
if (notifications_[i].status == NotificationStatus::FINISHED)
{
notifications_.erase(notifications_.begin() + i);
}
}
}
void Notifier::showText(std::string text1, std::string text2, int icon, std::string code)
{
// Cuenta el número de textos a mostrar
const int num_texts = !text1.empty() + !text2.empty();
// Si no hay texto, acaba
if (num_texts == 0)
{
return;
}
// Si solo hay un texto, lo coloca en la primera variable
if (num_texts == 1)
{
text1 += text2;
text2.clear();
}
// Si las notificaciones no se apilan, elimina las anteriores
if (!stack_)
{
clearNotifications();
}
// Inicializa variables
constexpr auto icon_size = 16;
constexpr auto padding_out = 1;
const auto padding_in = text_->getCharacterSize() / 2;
const auto icon_space = icon >= 0 ? icon_size + padding_in : 0;
const std::string txt = text1.length() > text2.length() ? text1 : text2;
const auto width = text_->lenght(txt) + (padding_in * 2) + icon_space;
const auto height = (text_->getCharacterSize() * num_texts) + (padding_in * 2);
const auto shape = NotificationShape::SQUARED;
// Posición horizontal
auto desp_h = 0;
if (param.notification.pos_h == NotifyPosition::LEFT)
{
desp_h = padding_out;
}
else if (param.notification.pos_h == NotifyPosition::MIDDLE)
{
desp_h = ((param.game.width / 2) - (width / 2));
}
else
{
desp_h = param.game.width - width - padding_out;
}
// Posición vertical
const int desp_v = (param.notification.pos_v == NotifyPosition::TOP) ? padding_out : (param.game.height - height - padding_out);
// Offset
const auto travel_dist = height + padding_out;
auto offset = 0;
if (param.notification.pos_v == NotifyPosition::TOP)
{
offset = (int)notifications_.size() > 0 ? notifications_.back().y + travel_dist : desp_v;
}
else
{
offset = (int)notifications_.size() > 0 ? notifications_.back().y - travel_dist : desp_v;
}
// Crea la notificacion
Notification n;
// Inicializa variables
n.code = code;
n.y = offset;
n.travel_dist = travel_dist;
n.counter = 0;
n.status = NotificationStatus::RISING;
n.text1 = text1;
n.text2 = text2;
n.shape = shape;
auto y_pos = offset + (param.notification.pos_v == NotifyPosition::TOP ? -travel_dist : travel_dist);
n.rect = {desp_h, y_pos, width, height};
// Crea la textura
n.texture = std::make_shared<Texture>(renderer_);
n.texture->createBlank(width, height, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET);
n.texture->setBlendMode(SDL_BLENDMODE_BLEND);
// Prepara para dibujar en la textura
n.texture->setAsRenderTarget(renderer_);
// Dibuja el fondo de la notificación
SDL_SetRenderDrawColor(renderer_, bg_color_.r, bg_color_.g, bg_color_.b, 255);
SDL_Rect rect;
if (shape == NotificationShape::ROUNDED)
{
rect = {4, 0, width - (4 * 2), height};
SDL_RenderFillRect(renderer_, &rect);
rect = {4 / 2, 1, width - 4, height - 2};
SDL_RenderFillRect(renderer_, &rect);
rect = {1, 4 / 2, width - 2, height - 4};
SDL_RenderFillRect(renderer_, &rect);
rect = {0, 4, width, height - (4 * 2)};
SDL_RenderFillRect(renderer_, &rect);
}
else if (shape == NotificationShape::SQUARED)
{
SDL_RenderClear(renderer_);
}
// Dibuja el icono de la notificación
if (has_icons_ && icon >= 0 && num_texts == 2)
{
auto sp = std::make_unique<Sprite>((SDL_Rect){0, 0, icon_size, icon_size}, icon_texture_);
sp->setPos({padding_in, padding_in, icon_size, icon_size});
sp->setSpriteClip({icon_size * (icon % 10), icon_size * (icon / 10), icon_size, icon_size});
sp->render();
}
// Escribe el texto de la notificación
Color color = {255, 255, 255};
if (num_texts == 2)
{ // Dos lineas de texto
text_->writeColored(padding_in + icon_space, padding_in, text1, color);
text_->writeColored(padding_in + icon_space, padding_in + text_->getCharacterSize() + 1, text2, color);
}
else
{ // Una linea de texto
text_->writeColored(padding_in + icon_space, padding_in, text1, color);
}
// Deja de dibujar en la textura
SDL_SetRenderTarget(renderer_, nullptr);
// Crea el sprite de la notificación
n.sprite = std::make_shared<Sprite>(n.rect, n.texture);
// Deja la notificación invisible
n.texture->setAlpha(0);
// Añade la notificación a la lista
notifications_.push_back(n);
}
// Indica si hay notificaciones activas
bool Notifier::isActive()
{
if ((int)notifications_.size() > 0)
{
return true;
}
return false;
}
// Finaliza y elimnina todas las notificaciones activas
void Notifier::clearNotifications()
{
for (int i = 0; i < (int)notifications_.size(); ++i)
{
notifications_[i].status = NotificationStatus::FINISHED;
}
clearFinishedNotifications();
}
// Obtiene los códigos de las notificaciones
std::vector<std::string> Notifier::getCodes()
{
std::vector<std::string> codes;
for (int i = 0; i < (int)notifications_.size(); ++i)
{
codes.push_back(notifications_[i].code);
}
return codes;
}

121
source/notifier.h Normal file
View File

@@ -0,0 +1,121 @@
#pragma once
#include <SDL2/SDL_rect.h> // for SDL_Rect
#include <SDL2/SDL_render.h> // for SDL_Renderer
#include <memory> // for shared_ptr, unique_ptr
#include <string> // for string, basic_string
#include <vector> // for vector
#include "utils.h" // for Color
class Sprite;
class Text;
class Texture;
struct JA_Sound_t; // lines 12-12
class Notifier
{
private:
// [SINGLETON] Objeto notifier privado para Don Melitón
static Notifier *notifier_;
enum class NotificationStatus
{
RISING,
STAY,
VANISHING,
FINISHED,
};
enum class NotificationPosition
{
UPPER_LEFT,
UPPER_CENTER,
UPPER_RIGHT,
MIDDLE_LEFT,
MIDDLE_RIGHT,
BOTTOM_LEFT,
BOTTOM_CENTER,
BOTTOM_RIGHT,
};
enum class NotificationShape
{
ROUNDED,
SQUARED,
};
struct Notification
{
std::shared_ptr<Texture> texture;
std::shared_ptr<Sprite> sprite;
std::string text1;
std::string text2;
int counter;
NotificationStatus status;
NotificationPosition position;
NotificationShape shape;
SDL_Rect rect;
int y;
int travel_dist;
std::string code; // Permite asignar un código a la notificación
};
// Objetos y punteros
SDL_Renderer *renderer_; // El renderizador de la ventana
std::shared_ptr<Texture> icon_texture_; // Textura para los iconos de las notificaciones
std::unique_ptr<Text> text_; // Objeto para dibujar texto
// Variables
Color bg_color_; // Color de fondo de las notificaciones
int wait_time_; // Tiempo que se ve la notificación
std::vector<Notification> notifications_; // La lista de notificaciones activas
bool stack_; // Indica si las notificaciones se apilan
bool has_icons_; // Indica si el notificador tiene textura para iconos
JA_Sound_t *sound_; // Sonido a reproducir cuando suena la notificación
// Elimina las notificaciones finalizadas
void clearFinishedNotifications();
// Finaliza y elimnina todas las notificaciones activas
void clearNotifications();
// [SINGLETON] Ahora el constructor y el destructor son privados, para no poder crear objetos notifier desde fuera
// Constructor
Notifier(SDL_Renderer *renderer, std::string icon_file, std::string bitmap_file, std::string text_file, const std::string &sound_file);
// Destructor
~Notifier();
public:
// [SINGLETON] Crearemos el objeto notifier con esta función estática
static void init(SDL_Renderer *renderer, std::string icon_file, std::string bitmap_file, std::string text_file, const std::string &sound_file);
// [SINGLETON] Destruiremos el objeto notifier con esta función estática
static void destroy();
// [SINGLETON] Con este método obtenemos el objeto notifier y podemos trabajar con él
static Notifier *get();
// Dibuja las notificaciones por pantalla
void render();
// Actualiza el estado de las notificaiones
void update();
/**
* @brief Muestra una notificación de texto por pantalla.
*
* @param text1 Primer texto opcional para mostrar (valor predeterminado: cadena vacía).
* @param text2 Segundo texto opcional para mostrar (valor predeterminado: cadena vacía).
* @param icon Icono opcional para mostrar (valor predeterminado: -1).
* @param code Permite asignar un código a la notificación (valor predeterminado: cadena vacía).
*/
void showText(std::string text1 = std::string(), std::string text2 = std::string(), int icon = -1, std::string code = std::string());
// Indica si hay notificaciones activas
bool isActive();
// Obtiene los códigos de las notificaciones
std::vector<std::string> getCodes();
};

View File

@@ -1,309 +0,0 @@
#include "notify.h"
#include <SDL2/SDL_blendmode.h> // for SDL_BLENDMODE_BLEND
#include <SDL2/SDL_pixels.h> // for SDL_PIXELFORMAT_RGBA8888
#include <string> // for string
#include "jail_audio.h" // for JA_DeleteSound, JA_LoadSound, JA_Pla...
#include "param.h" // for param
#include "sprite.h" // for Sprite
#include "text.h" // for Text
#include "texture.h" // for Texture
// Constructor
Notify::Notify(SDL_Renderer *renderer, std::string iconFile, std::string bitmapFile, std::string textFile, const std::string &soundFile)
: renderer(renderer),
text(std::make_unique<Text>(bitmapFile, textFile, renderer)),
bgColor(param.notification.color),
waitTime(150),
stack(false),
sound(JA_LoadSound(soundFile.c_str()))
{
// Inicializa variables
hasIcons = !iconFile.empty();
// Crea objetos
iconTexture = hasIcons ? std::make_unique<Texture>(renderer, iconFile) : nullptr;
}
// Destructor
Notify::~Notify()
{
// Libera la memoria de los objetos
JA_DeleteSound(sound);
notifications.clear();
}
// Dibuja las notificaciones por pantalla
void Notify::render()
{
for (int i = (int)notifications.size() - 1; i >= 0; --i)
{
notifications[i].sprite->render();
}
}
// Actualiza el estado de las notificaiones
void Notify::update()
{
for (int i = 0; i < (int)notifications.size(); ++i)
{
// Si la notificación anterior está "saliendo", no hagas nada
if (i > 0)
{
if (notifications[i - 1].status == NotificationStatus::RISING)
{
break;
}
}
notifications[i].counter++;
// Hace sonar la notificación en el primer frame
if (notifications[i].counter == 1)
{
if (param.notification.sound)
{
if (notifications[i].status == NotificationStatus::RISING)
{ // Reproduce el sonido de la notificación
JA_PlaySound(sound);
}
}
}
// Comprueba los estados
if (notifications[i].status == NotificationStatus::RISING)
{
const float step = ((float)notifications[i].counter / notifications[i].travelDist);
const int alpha = 255 * step;
if (param.notification.pos_v == NotifyPosition::TOP)
{
notifications[i].rect.y++;
}
else
{
notifications[i].rect.y--;
}
notifications[i].texture->setAlpha(alpha);
if (notifications[i].rect.y == notifications[i].y)
{
notifications[i].status = NotificationStatus::STAY;
notifications[i].texture->setAlpha(255);
notifications[i].counter = 0;
}
}
else if (notifications[i].status == NotificationStatus::STAY)
{
if (notifications[i].counter == waitTime)
{
notifications[i].status = NotificationStatus::VANISHING;
notifications[i].counter = 0;
}
}
else if (notifications[i].status == NotificationStatus::VANISHING)
{
const float step = (notifications[i].counter / (float)notifications[i].travelDist);
const int alpha = 255 * (1 - step);
if (param.notification.pos_v == NotifyPosition::TOP)
{
notifications[i].rect.y--;
}
else
{
notifications[i].rect.y++;
}
notifications[i].texture->setAlpha(alpha);
if (notifications[i].rect.y == notifications[i].y - notifications[i].travelDist)
{
notifications[i].status = NotificationStatus::FINISHED;
}
}
notifications[i].sprite->setPos(notifications[i].rect);
}
clearFinishedNotifications();
}
// Elimina las notificaciones finalizadas
void Notify::clearFinishedNotifications()
{
for (int i = (int)notifications.size() - 1; i >= 0; --i)
{
if (notifications[i].status == NotificationStatus::FINISHED)
{
notifications.erase(notifications.begin() + i);
}
}
}
// Muestra una notificación de texto por pantalla;
void Notify::showText(std::string text1, std::string text2, int icon)
{
// Cuenta el número de textos a mostrar
const int numTexts = !text1.empty() + !text2.empty();
// Si no hay texto, acaba
if (numTexts == 0)
{
return;
}
// Si solo hay un texto, lo coloca en la primera variable
if (numTexts == 1)
{
text1 += text2;
text2.clear();
}
// Si las notificaciones no se apilan, elimina las anteriores
if (!stack)
{
clearNotifications();
}
// Inicializa variables
constexpr auto iconSize = 16;
constexpr auto paddingOut = 1;
const auto paddingIn = text->getCharacterSize() / 2;
const auto iconSpace = icon >= 0 ? iconSize + paddingIn : 0;
const std::string txt = text1.length() > text2.length() ? text1 : text2;
const auto width = text->lenght(txt) + (paddingIn * 2) + iconSpace;
const auto height = (text->getCharacterSize() * numTexts) + (paddingIn * 2);
const auto shape = NotificationShape::SQUARED;
// Posición horizontal
auto despH = 0;
if (param.notification.pos_h == NotifyPosition::LEFT)
{
despH = paddingOut;
}
else if (param.notification.pos_h == NotifyPosition::MIDDLE)
{
despH = ((param.game.width / 2) - (width / 2));
}
else
{
despH = param.game.width - width - paddingOut;
}
// Posición vertical
const int despV = (param.notification.pos_v == NotifyPosition::TOP) ? paddingOut : (param.game.height - height - paddingOut);
// Offset
const auto travelDist = height + paddingOut;
auto offset = 0;
if (param.notification.pos_v == NotifyPosition::TOP)
{
offset = (int)notifications.size() > 0 ? notifications.back().y + travelDist : despV;
}
else
{
offset = (int)notifications.size() > 0 ? notifications.back().y - travelDist : despV;
}
// Crea la notificacion
Notification n;
// Inicializa variables
n.y = offset;
n.travelDist = travelDist;
n.counter = 0;
n.status = NotificationStatus::RISING;
n.text1 = text1;
n.text2 = text2;
n.shape = shape;
auto yPos = offset + (param.notification.pos_v == NotifyPosition::TOP ? -travelDist : travelDist);
n.rect = {despH, yPos, width, height};
// Crea la textura
n.texture = std::make_shared<Texture>(renderer);
n.texture->createBlank(width, height, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET);
n.texture->setBlendMode(SDL_BLENDMODE_BLEND);
// Prepara para dibujar en la textura
n.texture->setAsRenderTarget(renderer);
// Dibuja el fondo de la notificación
SDL_SetRenderDrawColor(renderer, bgColor.r, bgColor.g, bgColor.b, 255);
SDL_Rect rect;
if (shape == NotificationShape::ROUNDED)
{
rect = {4, 0, width - (4 * 2), height};
SDL_RenderFillRect(renderer, &rect);
rect = {4 / 2, 1, width - 4, height - 2};
SDL_RenderFillRect(renderer, &rect);
rect = {1, 4 / 2, width - 2, height - 4};
SDL_RenderFillRect(renderer, &rect);
rect = {0, 4, width, height - (4 * 2)};
SDL_RenderFillRect(renderer, &rect);
}
else if (shape == NotificationShape::SQUARED)
{
SDL_RenderClear(renderer);
}
// Dibuja el icono de la notificación
if (hasIcons && icon >= 0 && numTexts == 2)
{
auto sp = std::make_unique<Sprite>((SDL_Rect){0, 0, iconSize, iconSize}, iconTexture);
sp->setPos({paddingIn, paddingIn, iconSize, iconSize});
sp->setSpriteClip({iconSize * (icon % 10), iconSize * (icon / 10), iconSize, iconSize});
sp->render();
}
// Escribe el texto de la notificación
Color color = {255, 255, 255};
if (numTexts == 2)
{ // Dos lineas de texto
text->writeColored(paddingIn + iconSpace, paddingIn, text1, color);
text->writeColored(paddingIn + iconSpace, paddingIn + text->getCharacterSize() + 1, text2, color);
}
else
{ // Una linea de texto
text->writeColored(paddingIn + iconSpace, paddingIn, text1, color);
}
// Deja de dibujar en la textura
SDL_SetRenderTarget(renderer, nullptr);
// Crea el sprite de la notificación
n.sprite = std::make_shared<Sprite>(n.rect, n.texture);
// Deja la notificación invisible
n.texture->setAlpha(0);
// Añade la notificación a la lista
notifications.push_back(n);
}
// Indica si hay notificaciones activas
bool Notify::active()
{
if ((int)notifications.size() > 0)
{
return true;
}
return false;
}
// Finaliza y elimnina todas las notificaciones activas
void Notify::clearNotifications()
{
for (int i = 0; i < (int)notifications.size(); ++i)
{
notifications[i].status = NotificationStatus::FINISHED;
}
clearFinishedNotifications();
}

View File

@@ -1,96 +0,0 @@
#pragma once
#include <SDL2/SDL_rect.h> // for SDL_Rect
#include <SDL2/SDL_render.h> // for SDL_Renderer
#include <memory> // for shared_ptr, unique_ptr
#include <string> // for string, basic_string
#include <vector> // for vector
#include "utils.h" // for Color
class Sprite;
class Text;
class Texture;
struct JA_Sound_t; // lines 12-12
class Notify
{
private:
enum class NotificationStatus
{
RISING,
STAY,
VANISHING,
FINISHED,
};
enum class NotificationPosition
{
UPPER_LEFT,
UPPER_CENTER,
UPPER_RIGHT,
MIDDLE_LEFT,
MIDDLE_RIGHT,
BOTTOM_LEFT,
BOTTOM_CENTER,
BOTTOM_RIGHT,
};
enum class NotificationShape
{
ROUNDED,
SQUARED,
};
struct Notification
{
std::shared_ptr<Texture> texture;
std::shared_ptr<Sprite> sprite;
std::string text1;
std::string text2;
int counter;
NotificationStatus status;
NotificationPosition position;
NotificationShape shape;
SDL_Rect rect;
int y;
int travelDist;
};
// Objetos y punteros
SDL_Renderer *renderer; // El renderizador de la ventana
std::shared_ptr<Texture> iconTexture; // Textura para los iconos de las notificaciones
std::unique_ptr<Text> text; // Objeto para dibujar texto
// Variables
Color bgColor; // Color de fondo de las notificaciones
int waitTime; // Tiempo que se ve la notificación
std::vector<Notification> notifications; // La lista de notificaciones activas
bool stack; // Indica si las notificaciones se apilan
bool hasIcons; // Indica si el notificador tiene textura para iconos
JA_Sound_t *sound; // Sonido a reproducir cuando suena la notificación
// Elimina las notificaciones finalizadas
void clearFinishedNotifications();
// Finaliza y elimnina todas las notificaciones activas
void clearNotifications();
public:
// Constructor
Notify(SDL_Renderer *renderer, std::string iconFile, std::string bitmapFile, std::string textFile, const std::string &soundFile);
// Destructor
~Notify();
// Dibuja las notificaciones por pantalla
void render();
// Actualiza el estado de las notificaiones
void update();
// Muestra una notificación de texto por pantalla;
void showText(std::string text1 = std::string(), std::string text2 = std::string(), int icon = -1);
// Indica si hay notificaciones activas
bool active();
};

View File

@@ -149,11 +149,11 @@ void Player::setInputEnteringName(InputType input)
switch (input)
{
case InputType::LEFT:
enter_name_->decPos();
enter_name_->decPosition();
break;
case InputType::RIGHT:
enter_name_->incPos();
enter_name_->incPosition();
break;
case InputType::UP:
@@ -763,7 +763,7 @@ int Player::getRecordNamePos() const
{
if (enter_name_)
{
return enter_name_->getPos();
return enter_name_->getPosition();
}
return 0;

View File

@@ -12,7 +12,7 @@
#include "dbgtxt.h" // for dbg_print
#include "global_inputs.h" // for servicePressedCounter
#include "input.h" // for Input, inputs_e, INPUT_DO_NOT_ALLOW_REPEAT
#include "notify.h" // for Notify
#include "notifier.h" // for Notify
#include "on_screen_help.h" // for OnScreenHelp
#include "options.h" // for options
#include "param.h" // for param
@@ -47,7 +47,6 @@ Screen::Screen(SDL_Window *window, SDL_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)),
@@ -127,7 +126,7 @@ void Screen::blit()
displayInfo();
// Muestra las notificaciones
notify_->render();
Notifier::get()->render();
#ifdef NO_SHADERS
// Vuelve a dejar el renderizador en modo normal
@@ -200,8 +199,9 @@ void Screen::setVideoMode(ScreenVideoMode videoMode)
SDL_ShowCursor(SDL_ENABLE);
#endif
// Modifica el tamaño de la ventana
SDL_Point pos = getNewPosition();
SDL_SetWindowSize(window_, param.game.width * options.video.window.size, param.game.height * options.video.window.size);
SDL_SetWindowPosition(window_, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED);
SDL_SetWindowPosition(window_, pos.x, pos.y);
break;
}
@@ -280,7 +280,7 @@ void Screen::setBlendMode(SDL_BlendMode blendMode)
void Screen::update()
{
updateShakeEffect();
notify_->update();
Notifier::get()->update();
updateFPS();
OnScreenHelp::get()->update();
}
@@ -294,7 +294,7 @@ void Screen::checkInput()
{
switchVideoMode();
const std::string mode = options.video.mode == ScreenVideoMode::WINDOW ? "Window" : "Fullscreen";
showNotification(mode + " mode");
Notifier::get()->showText(mode + " mode");
return;
}
@@ -303,7 +303,7 @@ void Screen::checkInput()
{
decWindowSize();
const std::string size = std::to_string(options.video.window.size);
showNotification("Window size x" + size);
Notifier::get()->showText("Window size x" + size);
return;
}
@@ -312,7 +312,7 @@ void Screen::checkInput()
{
incWindowSize();
const std::string size = std::to_string(options.video.window.size);
showNotification("Window size x" + size);
Notifier::get()->showText("Window size x" + size);
return;
}
#endif
@@ -442,7 +442,7 @@ void Screen::switchShaders()
options.video.shaders = !options.video.shaders;
setVideoMode(options.video.mode);
const std::string value = options.video.shaders ? "on" : "off";
showNotification("Shaders " + value);
Notifier::get()->showText("Shaders " + value);
}
// Atenua la pantalla
@@ -451,12 +451,6 @@ void Screen::attenuate(bool value)
attenuate_effect_ = value;
}
// Muestra una notificación de texto por pantalla;
void Screen::showNotification(const std::string &text1, const std::string &text2, int icon)
{
notify_->showText(text1, text2, icon);
}
// Obtiene el puntero al renderizador
SDL_Renderer *Screen::getRenderer()
{
@@ -490,8 +484,38 @@ void Screen::displayInfo()
}
}
// Indica si hay alguna notificación activa en pantalla
bool Screen::notificationsAreActive() const
// Calcula la nueva posición de la ventana a partir de la antigua al cambiarla de tamaño
SDL_Point Screen::getNewPosition()
{
return notify_->active();
// Obtiene la posición actual de la ventana
SDL_Point current_position;
SDL_GetWindowPosition(window_, &current_position.x, &current_position.y);
// Obtiene las dimensiones actuales de la ventana
int current_width, current_height;
SDL_GetWindowSize(window_, &current_width, &current_height);
// Obtiene las dimesiones que tendrá la ventana
const int new_width = param.game.width * options.video.window.size;
const int new_height = param.game.height * options.video.window.size;
// Obtiene el centro de la ventana actual
SDL_Point center;
center.x = current_position.x + current_width / 2;
center.y = current_position.y + current_height / 2;
// Calcula la nueva posición a partir del centro y las nuevas diemsiones
SDL_Point new_pos;
new_pos.x = center.x - new_width / 2;
new_pos.y = center.y - new_height / 2;
// Obtiene las dimensiones del escritorio
SDL_DisplayMode DM;
SDL_GetCurrentDisplayMode(0, &DM);
// Evita que la ventana quede fuera del escritorio
new_pos.x = std::clamp(new_pos.x, 30, DM.w - new_width);
new_pos.y = std::clamp(new_pos.y, 30, DM.h - new_height);
return new_pos;
}

View File

@@ -8,7 +8,6 @@
#include <string> // for basic_string, string
#include "utils.h" // for Color
#include <memory>
class Notify;
enum class ScreenFilter : int
{
@@ -29,11 +28,10 @@ private:
static Screen *screen_;
// Objetos y punteros
SDL_Window *window_; // Ventana de la aplicación
SDL_Renderer *renderer_; // El renderizador de la ventana
std::unique_ptr<Notify> notify_; // Pinta notificaciones en pantalla
SDL_Texture *game_canvas_; // Textura donde se dibuja todo antes de volcarse al renderizador
SDL_Texture *shader_canvas_; // Textura para pasarle al shader desde gameCanvas
SDL_Window *window_; // Ventana de la aplicación
SDL_Renderer *renderer_; // El renderizador de la ventana
SDL_Texture *game_canvas_; // Textura donde se dibuja todo antes de volcarse al renderizador
SDL_Texture *shader_canvas_; // Textura para pasarle al shader desde gameCanvas
// Variables
SDL_Rect src_rect_; // Coordenadas de donde va a pillar la textura del juego para dibujarla
@@ -85,6 +83,9 @@ private:
// Muestra información por pantalla
void displayInfo();
// Calcula la nueva posición de la ventana a partir de la antigua al cambiarla de tamaño
SDL_Point getNewPosition();
// [SINGLETON] Ahora el constructor y el destructor son privados, para no poder crear objetos screen desde fuera
// Constructor
@@ -151,12 +152,6 @@ public:
// Atenua la pantalla
void attenuate(bool value);
// Muestra una notificación de texto por pantalla;
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
bool notificationsAreActive() const;
// Obtiene el puntero al renderizador
SDL_Renderer *getRenderer();
};

View File

@@ -127,7 +127,7 @@ void SmartSprite::checkMove()
void SmartSprite::checkFinished()
{
// Comprueba si ha llegado a su destino
on_destination_ = (getPosX() == dest_x_ && getPosY() == dest_y_) ? true : false;
on_destination_ = (getPosX() == dest_x_ && getPosY() == dest_y_);
if (on_destination_)
{

View File

@@ -12,7 +12,9 @@ Sprite::Sprite(SDL_Rect rect, std::shared_ptr<Texture> texture)
sprite_clip_((SDL_Rect){0, 0, pos_.w, pos_.h}) {}
Sprite::Sprite(std::shared_ptr<Texture> texture)
: texture_(texture) {}
: texture_(texture),
pos_({0, 0, texture_->getWidth(), texture_->getHeight()}),
sprite_clip_(pos_) {}
// Muestra el sprite por pantalla
void Sprite::render()

View File

@@ -1,24 +1,25 @@
#include "title.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
#include <SDL2/SDL_rect.h> // for SDL_Rect
#include <SDL2/SDL_render.h> // for SDL_Renderer
#include <SDL2/SDL_timer.h> // for SDL_GetTicks
#include <string> // for char_traits, operator+, to_string, bas...
#include <utility> // for move
#include <vector> // for vector
#include "asset.h" // for Asset
#include "global_inputs.h" // for check
#include "input.h" // for Input, InputType, INPUT_DO_NOT_ALLOW_R...
#include "jail_audio.h" // for JA_GetMusicState, JA_Music_state, JA_P...
#include "lang.h" // for getText
#include "options.h" // for options
#include "param.h" // for param
#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
#include <SDL2/SDL_events.h> // for SDL_PollEvent, SDL_Event, SDL_KEYDOWN
#include <SDL2/SDL_keycode.h> // for SDLK_1, SDLK_2, SDLK_3
#include <SDL2/SDL_rect.h> // for SDL_Rect
#include <SDL2/SDL_render.h> // for SDL_Renderer
#include <SDL2/SDL_timer.h> // for SDL_GetTicks
#include <string> // for char_traits, operator+, to_string, bas...
#include <utility> // for move
#include <vector> // for vector
#include "asset.h" // for Asset
#include "global_inputs.h" // for check
#include "input.h" // for Input, InputType, INPUT_DO_NOT_ALLOW_R...
#include "jail_audio.h" // for JA_GetMusicState, JA_Music_state, JA_P...
#include "lang.h" // for getText
#include "notifier.h" // for Notifier
#include "options.h" // for options
#include "param.h" // for param
#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
Title::Title(JA_Music_t *music)
@@ -354,7 +355,7 @@ void Title::swapControllers()
}
}
screen_->showNotification(text[0], text[1]);
Notifier::get()->showText(text[0], text[1]);
resetCounter();
}

View File

@@ -213,4 +213,10 @@ double easeOutQuint(double t)
double easeInOutSine(double t)
{
return -0.5 * (std::cos(M_PI * t) - 1);
}
}
// Comprueba si una vector contiene una cadena
bool stringInVector(const std::vector<std::string> &vec, const std::string &str)
{
return std::find(vec.begin(), vec.end(), str) != vec.end();
}

View File

@@ -282,6 +282,9 @@ double easeOutQuint(double t);
// Función de suavizado
double easeInOutSine(double t);
// Comprueba si una vector contiene una cadena
bool stringInVector(const std::vector<std::string> &vec, const std::string &str);
// Colores
extern const Color bg_color;
extern const Color no_color;