Acabat el nou motor per a textos en pantalla

This commit is contained in:
2024-10-30 09:25:28 +01:00
parent b43782786a
commit 20c51d0796
11 changed files with 269 additions and 274 deletions

View File

@@ -1,20 +0,0 @@
#!/bin/bash
# warning,style,performance
#cppcheck --force --enable=warning,style,performance --std=c++20 \
# --suppressions-list=/home/sergio/gitea/coffee_crisis_arcade_edition/linux-utils/cppcheck_suppressions \
# /home/sergio/gitea/coffee_crisis_arcade_edition/source/ \
# 2>/home/sergio/cppcheck-result-warning-style-performance.txt
# all
#cppcheck --force --enable=all -I /usr/include --std=c++20 \
#--suppress=missingIncludeSystem \
#--suppressions-list=/home/sergio/gitea/coffee_crisis_arcade_edition/linux-utils/cppcheck_suppressions \
#/home/sergio/gitea/coffee_crisis_arcade_edition/source/ \
#2>/home/sergio/cppcheck-result-all.txt
# unusedFunction
cppcheck --enable=style --std=c++20 \
--suppressions-list=./cppcheck_suppressions \
../source/ \
2>/home/sergio/cppcheck-result-all.txt

View File

@@ -28,13 +28,13 @@ Balloon::Balloon(float x, float y, BalloonType type, BalloonSize size, float vel
vy_ = 0; vy_ = 0;
max_vy_ = 3.0f; max_vy_ = 3.0f;
const int size = static_cast<int>(size_); const int index = static_cast<int>(size_);
gravity_ = param.balloon.at(size).grav; gravity_ = param.balloon.at(index).grav;
default_vy_ = param.balloon.at(size).vel; default_vy_ = param.balloon.at(index).vel;
h_ = w_ = BALLOON_SIZE[size]; h_ = w_ = BALLOON_SIZE[index];
power_ = BALLOON_POWER[size]; power_ = BALLOON_POWER[index];
menace_ = BALLOON_MENACE[size]; menace_ = BALLOON_MENACE[index];
score_ = BALLOON_SCORE[size]; score_ = BALLOON_SCORE[index];
break; break;
} }
@@ -44,25 +44,25 @@ Balloon::Balloon(float x, float y, BalloonType type, BalloonSize size, float vel
default_vy_ = max_vy_ = vy_ = fabs(vx_ * 2.0f); default_vy_ = max_vy_ = vy_ = fabs(vx_ * 2.0f);
gravity_ = 0.00f; gravity_ = 0.00f;
const int size = static_cast<int>(size_); const int index = static_cast<int>(size_);
h_ = w_ = BALLOON_SIZE[size]; h_ = w_ = BALLOON_SIZE[index];
power_ = BALLOON_POWER[size]; power_ = BALLOON_POWER[index];
menace_ = BALLOON_MENACE[size]; menace_ = BALLOON_MENACE[index];
score_ = BALLOON_SCORE[size]; score_ = BALLOON_SCORE[index];
break; break;
} }
case BalloonType::POWERBALL: case BalloonType::POWERBALL:
{ {
const int size = 3; const int index = 3;
h_ = w_ = BALLOON_SIZE[size]; h_ = w_ = BALLOON_SIZE[index];
power_ = score_ = menace_ = 0; power_ = score_ = menace_ = 0;
vy_ = 0; vy_ = 0;
max_vy_ = 3.0f; max_vy_ = 3.0f;
gravity_ = param.balloon.at(size).grav; gravity_ = param.balloon.at(index).grav;
default_vy_ = param.balloon.at(size).vel; default_vy_ = param.balloon.at(index).vel;
sprite_->disableRotate(); sprite_->disableRotate();
sprite_->setRotateSpeed(0); sprite_->setRotateSpeed(0);

View File

@@ -1,39 +1,40 @@
#include "game.h" #include "game.h"
#include <SDL2/SDL_blendmode.h> // Para SDL_BLENDMODE_BLEND #include <SDL2/SDL_blendmode.h> // for SDL_BLENDMODE_BLEND
#include <SDL2/SDL_events.h> // Para SDL_PollEvent, SDL_Event, SDL_KEYDOWN #include <SDL2/SDL_events.h> // for SDL_PollEvent, SDL_Event, SDL_KEYDOWN
#include <SDL2/SDL_keycode.h> // Para SDLK_1, SDLK_2, SDLK_3, SDLK_4 #include <SDL2/SDL_keycode.h> // for SDLK_1, SDLK_2, SDLK_3, SDLK_4
#include <SDL2/SDL_pixels.h> // Para SDL_PIXELFORMAT_RGBA8888 #include <SDL2/SDL_pixels.h> // for SDL_PIXELFORMAT_RGBA8888
#include <SDL2/SDL_timer.h> // Para SDL_GetTicks #include <SDL2/SDL_timer.h> // for SDL_GetTicks
#include <SDL2/SDL_video.h> // Para SDL_WINDOWEVENT_FOCUS_GAINED, SDL_... #include <SDL2/SDL_video.h> // for SDL_WINDOWEVENT_FOCUS_GAINED, SDL_...
#include <stdlib.h> // Para rand, size_t #include <stdlib.h> // for rand, size_t
#include <algorithm> // Para find_if, clamp, min, remove_if #include <algorithm> // for find_if, clamp, min, remove_if
#include <iterator> // Para distance, size #include <functional> // for function
#include <numeric> // Para accumulate #include <iterator> // for distance, size
#include "asset.h" // Para Asset #include <numeric> // for accumulate
#include "background.h" // Para Background #include "asset.h" // for Asset
#include "balloon.h" // Para Balloon, BALLOON_SCORE, BALLOON_VE... #include "background.h" // for Background
#include "balloon_formations.h" // Para BalloonFormations, BalloonFormatio... #include "balloon.h" // for Balloon, BALLOON_SCORE, BALLOON_VE...
#include "bullet.h" // Para Bullet, BulletType, BulletMoveStatus #include "balloon_formations.h" // for BalloonFormations, BalloonFormatio...
#include "explosions.h" // Para Explosions #include "bullet.h" // for Bullet, BulletType, BulletMoveStatus
#include "fade.h" // Para Fade, FadeType #include "explosions.h" // for Explosions
#include "global_inputs.h" // Para check #include "fade.h" // for Fade, FadeType
#include "input.h" // Para InputType, Input, INPUT_DO_NOT_ALL... #include "global_inputs.h" // for check
#include "item.h" // Para Item, ItemType #include "input.h" // for InputType, Input, INPUT_DO_NOT_ALL...
#include "jail_audio.h" // Para JA_PlaySound, JA_GetMusicState #include "item.h" // for Item, ItemType
#include "lang.h" // Para getText #include "jail_audio.h" // for JA_PlaySound, JA_GetMusicState
#include "manage_hiscore_table.h" // Para ManageHiScoreTable #include "lang.h" // for getText
#include "notifier.h" // Para Notifier #include "manage_hiscore_table.h" // for ManageHiScoreTable, HiScoreEntry
#include "param.h" // Para Param, param, ParamGame, ParamFade #include "notifier.h" // for Notifier
#include "path_sprite.h" // Para PathSprite, PathType #include "param.h" // for Param, param, ParamGame, ParamFade
#include "player.h" // Para Player, PlayerStatus #include "path_sprite.h" // for Path, PathSprite, createPath, Path...
#include "resource.h" // Para Resource #include "player.h" // for Player, PlayerStatus
#include "scoreboard.h" // Para Scoreboard, ScoreboardMode, SCOREB... #include "resource.h" // for Resource
#include "screen.h" // Para Screen #include "scoreboard.h" // for Scoreboard, ScoreboardMode, SCOREB...
#include "section.h" // Para Name, name, Options, options #include "screen.h" // for Screen
#include "smart_sprite.h" // Para SmartSprite #include "section.h" // for Name, name, Options, options
#include "text.h" // Para Text, TEXT_CENTER #include "smart_sprite.h" // for SmartSprite
#include "texture.h" // Para Texture #include "text.h" // for Text
struct JA_Sound_t; // lines 40-40 #include "texture.h" // for Texture
struct JA_Sound_t; // lines 36-36
// Constructor // Constructor
Game::Game(int player_id, int current_stage, bool demo) Game::Game(int player_id, int current_stage, bool demo)
@@ -46,8 +47,7 @@ Game::Game(int player_id, int current_stage, bool demo)
balloon_formations_(std::make_unique<BalloonFormations>()), balloon_formations_(std::make_unique<BalloonFormations>()),
canvas_(SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, param.game.play_area.rect.w, param.game.play_area.rect.h)), canvas_(SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, param.game.play_area.rect.w, param.game.play_area.rect.h)),
fade_(std::make_unique<Fade>()), fade_(std::make_unique<Fade>()),
current_stage_(current_stage), current_stage_(current_stage)
last_stage_reached_(current_stage)
{ {
// Pasa variables // Pasa variables
demo_.enabled = demo; demo_.enabled = demo;
@@ -89,6 +89,7 @@ Game::Game(int player_id, int current_stage, bool demo)
{ {
createTwoBigBalloons(); createTwoBigBalloons();
evaluateAndSetMenace(); evaluateAndSetMenace();
createMessage({paths_.at(0), paths_.at(1)}, Resource::get()->getTexture("get_ready"));
} }
} }
@@ -325,46 +326,50 @@ void Game::updateStage()
if (current_power_ >= balloon_formations_->getStage(current_stage_).power_to_complete) if (current_power_ >= balloon_formations_->getStage(current_stage_).power_to_complete)
{ {
// Cambio de fase // Cambio de fase
current_stage_++; ++current_stage_;
current_power_ = 0; current_power_ = 0;
last_stage_reached_ = current_stage_;
// Ha llegado al final el juego
if (current_stage_ == 10) if (current_stage_ == 10)
{ // Ha llegado al final el juego {
game_completed_ = true; // Marca el juego como completado game_completed_ = true; // Marca el juego como completado
current_stage_ = 9; // Deja el valor dentro de los limites current_stage_ = 9; // Deja el valor dentro de los limites
destroyAllBalloons(); // Destruye a todos los enemigos destroyAllBalloons(); // Destruye a todos los enemigos
current_power_ = 0; // Vuelve a dejar el poder a cero, por lo que hubiera podido subir al destruir todos lo globos current_power_ = 0; // Vuelve a dejar el poder a cero, por lo que hubiera podido subir al destruir todos lo globos
menace_current_ = 255; // Sube el nivel de amenaza para que no cree mas globos menace_current_ = 255; // Sube el nivel de amenaza para que no cree mas globos
// Añade un millon de puntos a los jugadores que queden vivos
for (auto &player : players_) for (auto &player : players_)
{ // Añade un millon de puntos a los jugadores que queden vivos
if (player->isPlaying()) if (player->isPlaying())
{
player->addScore(1000000); player->addScore(1000000);
}
}
updateHiScore(); updateHiScore();
JA_StopMusic(); JA_StopMusic();
} }
JA_PlaySound(Resource::get()->getSound("stage_change.wav")); JA_PlaySound(Resource::get()->getSound("stage_change.wav"));
stage_bitmap_counter_ = 0;
balloon_speed_ = default_balloon_speed_; balloon_speed_ = default_balloon_speed_;
setBalloonSpeed(balloon_speed_); setBalloonSpeed(balloon_speed_);
screen_->flash(flash_color, 5); screen_->flash(flash_color, 10);
screen_->shake(); screen_->shake();
}
// Incrementa el contador del bitmap que aparece mostrando el cambio de fase // Escribe el texto por pantalla
if (stage_bitmap_counter_ < STAGE_COUNTER_) const auto stage_number = balloon_formations_->getStage(current_stage_).number;
{ if (!game_completed_)
stage_bitmap_counter_++;
}
// Si el juego se ha completado, el bitmap se detiene en el centro de la pantalla
if (game_completed_)
{
if (stage_bitmap_counter_ > 100)
{ {
stage_bitmap_counter_ = 100; std::vector<Path> paths = {paths_.at(2), paths_.at(3)};
if (stage_number == 10)
createMessage(paths, Resource::get()->getTexture("last_stage"));
else
{
auto text = std::make_unique<Text>(Resource::get()->getTexture("04b_25.png"), Resource::get()->getTextFile("04b_25.txt"));
const std::string caption = std::to_string(10 - current_stage_) + lang::getText(38);
createMessage(paths, text->writeToTexture(caption, 2, -2));
}
}
else
{
createMessage({paths_.at(4), paths_.at(5)}, Resource::get()->getTexture("congratulations"));
createMessage({paths_.at(6), paths_.at(7)}, Resource::get()->getTexture("1000000_points"));
} }
} }
} }
@@ -377,6 +382,9 @@ void Game::updateGameOver()
{ {
if (game_over_counter_ > 0) if (game_over_counter_ > 0)
{ {
if (game_over_counter_ == GAME_OVER_COUNTER_)
createMessage({paths_.at(2), paths_.at(3)}, Resource::get()->getTexture("game_over"));
game_over_counter_--; game_over_counter_--;
if ((game_over_counter_ == 250) || (game_over_counter_ == 200) || (game_over_counter_ == 180) || (game_over_counter_ == 120) || (game_over_counter_ == 60)) if ((game_over_counter_ == 250) || (game_over_counter_ == 200) || (game_over_counter_ == 180) || (game_over_counter_ == 120) || (game_over_counter_ == 60))
@@ -913,13 +921,13 @@ void Game::createItemText(int x, std::shared_ptr<Texture> texture)
} }
// Crea un objeto PathSprite // Crea un objeto PathSprite
void Game::createMessage(std::vector<Path> paths, std::shared_ptr<Texture> texture) void Game::createMessage(const std::vector<Path> &paths, std::shared_ptr<Texture> texture)
{ {
path_sprites_.emplace_back(std::make_unique<PathSprite>(texture)); path_sprites_.emplace_back(std::make_unique<PathSprite>(texture));
// Inicializa // Inicializa
for (const auto &path : paths) for (const auto &path : paths)
path_sprites_.back()->addPath(path); path_sprites_.back()->addPath(path, true);
path_sprites_.back()->enable(); path_sprites_.back()->enable();
} }
@@ -1205,15 +1213,15 @@ void Game::updateBackground()
balloons_popped_ = (balloons_popped_ > 400) ? (balloons_popped_ - 25) : 200; balloons_popped_ = (balloons_popped_ > 400) ? (balloons_popped_ - 25) : 200;
// Calcula la velocidad en función de los globos explotados y el total de globos a explotar para acabar el juego // Calcula la velocidad en función de los globos explotados y el total de globos a explotar para acabar el juego
constexpr auto clouds_initial_speed = 0.05f; constexpr float clouds_initial_speed = 0.05f;
constexpr auto clouds_final_speed = 2.00f - clouds_initial_speed; constexpr float clouds_final_speed = 2.00f - clouds_initial_speed;
const float cloudsSpeed = (-clouds_initial_speed) + (-clouds_final_speed * ((float)balloons_popped_ / (float)total_power_to_complete_game_)); const float cloudsSpeed = (-clouds_initial_speed) + (-clouds_final_speed * (static_cast<float>(balloons_popped_) / total_power_to_complete_game_));
background_->setCloudsSpeed(cloudsSpeed); background_->setCloudsSpeed(cloudsSpeed);
// Calcula la transición de los diferentes fondos // Calcula la transición de los diferentes fondos
const float gradient_number = std::min(((float)balloons_popped_ / 1250.0f), 3.0f); const float gradient_number = std::min(balloons_popped_ / 1250.0f, 3.0f);
const float percent = gradient_number - (int)gradient_number; const float percent = gradient_number - static_cast<int>(gradient_number);
background_->setGradientNumber((int)gradient_number); background_->setGradientNumber(static_cast<int>(gradient_number));
background_->setTransition(percent); background_->setTransition(percent);
// Actualiza el objeto // Actualiza el objeto
@@ -1231,11 +1239,10 @@ void Game::fillCanvas()
background_->render(); background_->render();
renderItems(); renderItems();
renderSmartSprites(); renderSmartSprites();
renderPathSprites();
explosions_->render(); explosions_->render();
renderBalloons(); renderBalloons();
renderBullets(); renderBullets();
renderMessages(); renderPathSprites();
renderPlayers(); renderPlayers();
// Deja el renderizador apuntando donde estaba // Deja el renderizador apuntando donde estaba
@@ -1251,6 +1258,12 @@ void Game::render()
// Copia la textura con la zona de juego a la pantalla // Copia la textura con la zona de juego a la pantalla
SDL_RenderCopy(renderer_, canvas_, nullptr, &param.game.play_area.rect); SDL_RenderCopy(renderer_, canvas_, nullptr, &param.game.play_area.rect);
// SDL_SetRenderDrawColor(Screen::get()->getRenderer(), 0, 0, 255, 255);
// const int y = param.game.play_area.center_y;
// SDL_RenderDrawLine(Screen::get()->getRenderer(), 0, y, param.game.play_area.rect.w, y);
// const int x = param.game.play_area.center_x;
// SDL_RenderDrawLine(Screen::get()->getRenderer(), x, 0, x, param.game.play_area.rect.h);
// Dibuja el marcador // Dibuja el marcador
scoreboard_->render(); scoreboard_->render();
@@ -1285,48 +1298,6 @@ void Game::updateMenace()
} }
} }
// Pinta diferentes mensajes en la pantalla
void Game::renderMessages()
{
// GetReady
if (counter_ == 10 && !demo_.enabled)
{ // text_04b_25_->write2X((int)get_ready_bitmap_path_[counter_], param.game.play_area.center_y - 8, lang::getText(75), -2);
std::vector<Path> paths = {paths_.at(0), paths_.at(1)};
createMessage(paths, Resource::get()->getTexture("get_ready"));
}
// STAGE NUMBER
if (stage_bitmap_counter_ < STAGE_COUNTER_)
{
const auto stage_number = balloon_formations_->getStage(current_stage_).number;
std::string text;
if (stage_number == 10)
{
// Ultima fase
text = lang::getText(79);
}
else
{
// X fases restantes
text = std::to_string(11 - stage_number) + lang::getText(38);
}
if (!game_completed_)
{
// Escribe el número de fases restantes
//text_04b_25_->write2X(param.game.play_area.center_x, stage_bitmap_path_[stage_bitmap_counter_], text, -2);
}
else
{
// Escribe el texto de juego completado
text = lang::getText(50);
//text_nokia2_big_->writeDX(TEXT_CENTER, param.game.play_area.center_x, stage_bitmap_path_[stage_bitmap_counter_], text, -2, no_color, 1, shdw_txt_color);
//text_nokia2_->writeDX(TEXT_CENTER, param.game.play_area.center_x, stage_bitmap_path_[stage_bitmap_counter_] + text_nokia2_big_->getCharacterSize() + 2, lang::getText(76), -1, no_color, 1, shdw_txt_color);
}
}
}
// Habilita el efecto del item de detener el tiempo // Habilita el efecto del item de detener el tiempo
void Game::enableTimeStopItem() void Game::enableTimeStopItem()
{ {
@@ -1385,42 +1356,54 @@ int Game::calculateScreenPower()
// Inicializa las variables que contienen puntos de ruta para mover objetos // Inicializa las variables que contienen puntos de ruta para mover objetos
void Game::initPaths() void Game::initPaths()
{ {
// Recorrido para el texto de "Get Ready!" // Recorrido para el texto de "Get Ready!" (0,1)
const auto &texture = Resource::get()->getTexture("get_ready");
const auto w = texture->getWidth();
const auto h = texture->getHeight();
const int x0 = -w;
const int x1 = param.game.play_area.center_x - w / 2;
const int x2 = param.game.play_area.rect.w;
const int y = param.game.play_area.center_y - h / 2;
paths_.emplace_back(Path(createPath(x0, x1, PathType::HORIZONTAL, y, 80, easeOutQuint), 10));
paths_.emplace_back(Path(createPath(x1, x2, PathType::HORIZONTAL, y, 80, easeInQuint), 0));
// Vector con los valores del seno para 360 grados
float sin[360];
for (int i = 0; i < 360; ++i)
sin[i] = SDL_sinf((float)i * 3.14f / 180.0f);
// Letrero de STAGE #
constexpr auto first_part = STAGE_COUNTER_ / 4; // 50
constexpr auto second_part = first_part * 3; // 150
const auto center_point = param.game.play_area.center_y - (BLOCK * 2);
const auto distance = (param.game.play_area.rect.h) - (param.game.play_area.center_y - 16);
for (int i = 0; i < first_part; ++i)
{ {
int index = static_cast<int>((i * 1.8f) + 90) % 360; const auto &texture = Resource::get()->getTexture("get_ready");
stage_bitmap_path_[i] = sin[index] * distance + center_point; const auto w = texture->getWidth();
const int x0 = -w;
const int x1 = param.game.play_area.center_x - w / 2;
const int x2 = param.game.play_area.rect.w;
const int y = param.game.play_area.center_y;
paths_.emplace_back(Path(createPath(x0, x1, PathType::HORIZONTAL, y, 80, easeOutQuint), 20));
paths_.emplace_back(Path(createPath(x1, x2, PathType::HORIZONTAL, y, 80, easeInQuint), 0));
} }
for (int i = first_part; i < second_part; ++i) // Recorrido para el texto de "Last Stage!" o de "X stages left" o "Game Over" (2,3)
stage_bitmap_path_[i] = center_point;
for (int i = second_part; i < STAGE_COUNTER_; ++i)
{ {
int index = static_cast<int>(((i - 149) * 1.8f) + 90) % 360; const auto &texture = Resource::get()->getTexture("last_stage");
stage_bitmap_path_[i] = sin[index] * (center_point + 17) - 17; const auto h = texture->getHeight();
const int y0 = param.game.play_area.rect.h - h;
const int y1 = param.game.play_area.center_y - h / 2;
const int y2 = -h;
const int x = param.game.play_area.center_x;
paths_.emplace_back(Path(createPath(y0, y1, PathType::VERTICAL, x, 80, easeOutQuint), 20));
paths_.emplace_back(Path(createPath(y1, y2, PathType::VERTICAL, x, 80, easeInQuint), 0));
}
// Recorrido para el texto de "Congratulations!!" (3,4)
{
const auto &texture = Resource::get()->getTexture("congratulations");
const auto w = texture->getWidth();
const auto h = texture->getHeight();
const int x0 = -w;
const int x1 = param.game.play_area.center_x - w / 2;
const int x2 = param.game.play_area.rect.w;
const int y = param.game.play_area.center_y - h / 2 - 20;
paths_.emplace_back(Path(createPath(x0, x1, PathType::HORIZONTAL, y, 80, easeOutQuint), 400));
paths_.emplace_back(Path(createPath(x1, x2, PathType::HORIZONTAL, y, 80, easeInQuint), 0));
}
// Recorrido para el texto de "1.000.000 points!" (5,6)
{
const auto &texture = Resource::get()->getTexture("1000000_points");
const auto w = texture->getWidth();
const auto h = texture->getHeight();
const int x0 = param.game.play_area.rect.w;
const int x1 = param.game.play_area.center_x - w / 2;
const int x2 = -w;
const int y = param.game.play_area.center_y + h / 2 - 20;
paths_.emplace_back(Path(createPath(x0, x1, PathType::HORIZONTAL, y, 80, easeOutQuint), 400));
paths_.emplace_back(Path(createPath(x1, x2, PathType::HORIZONTAL, y, 80, easeInQuint), 0));
} }
} }
@@ -1559,6 +1542,11 @@ void Game::checkEvents()
createItemText(x, game_text_textures_.at(3)); createItemText(x, game_text_textures_.at(3));
break; break;
} }
case SDLK_6: // Crea un mensaje
{
createMessage({paths_.at(4), paths_.at(5)}, Resource::get()->getTexture("congratulations"));
createMessage({paths_.at(6), paths_.at(7)}, Resource::get()->getTexture("1000000_points"));
}
default: default:
break; break;
} }
@@ -1610,9 +1598,7 @@ void Game::updateScoreboard()
void Game::pause(bool value) void Game::pause(bool value)
{ {
paused_ = value; paused_ = value;
#ifndef DEBUG
screen_->attenuate(paused_); screen_->attenuate(paused_);
#endif
} }
// Añade una puntuación a la tabla de records // Añade una puntuación a la tabla de records

View File

@@ -1,32 +1,31 @@
#pragma once #pragma once
#include <SDL2/SDL_render.h> // Para SDL_Renderer, SDL_Texture #include <SDL2/SDL_render.h> // for SDL_Renderer, SDL_Texture
#include <SDL2/SDL_stdinc.h> // Para Uint32, Uint8 #include <SDL2/SDL_stdinc.h> // for Uint32, Uint8
#include <memory> // Para shared_ptr, unique_ptr #include <memory> // for shared_ptr, unique_ptr
#include <string> // Para string #include <string> // for string
#include <vector> // Para vector #include <vector> // for vector
#include "balloon.h" // Para Balloon #include "balloon.h" // for Balloon
#include "manage_hiscore_table.h" // Para HiScoreEntry #include "manage_hiscore_table.h" // for HiScoreEntry
#include "options.h" // Para Options, OptionsGame, options #include "options.h" // for Options, OptionsGame, options
#include "player.h" // Para Player #include "player.h" // for Player
#include "utils.h" // Para Demo #include "utils.h" // for Demo
#include "path_sprite.h" class Asset; // lines 14-14
class Asset; // lines 12-12 class Background; // lines 15-15
class Background; // lines 13-13 class BalloonFormations; // lines 16-16
class BalloonFormations; // lines 14-14 class Bullet; // lines 17-17
class Bullet; // lines 15-15 class Explosions; // lines 18-18
class Explosions; // lines 16-16 class Fade; // lines 19-19
class Fade; // lines 17-17 class Input; // lines 20-20
class Input; // lines 18-18 class Item; // lines 21-21
class Item; // lines 19-19 class PathSprite; // lines 22-22
class PathSprite; // lines 20-20 class Scoreboard; // lines 23-23
class Scoreboard; // lines 21-21 class Screen; // lines 24-24
class Screen; // lines 22-22 class SmartSprite; // lines 25-25
class SmartSprite; // lines 23-23 class Texture; // lines 27-27
class Text; // lines 24-24 enum class BulletType : Uint8; // lines 28-28
class Texture; // lines 25-25 enum class ItemType; // lines 29-29
enum class BulletType : Uint8; // lines 26-26 struct Path;
enum class ItemType; // lines 27-27
// Modo demo // Modo demo
constexpr bool GAME_MODE_DEMO_OFF = false; constexpr bool GAME_MODE_DEMO_OFF = false;
@@ -68,7 +67,6 @@ private:
// Constantes // Constantes
// Contadores // Contadores
static constexpr int STAGE_COUNTER_ = 200;
static constexpr int HELP_COUNTER_ = 1000; static constexpr int HELP_COUNTER_ = 1000;
static constexpr int GAME_COMPLETED_START_FADE_ = 500; static constexpr int GAME_COMPLETED_START_FADE_ = 500;
static constexpr int GAME_COMPLETED_END_ = 700; static constexpr int GAME_COMPLETED_END_ = 700;
@@ -154,7 +152,6 @@ private:
options.game.hi_score_table[0].score); // Máxima puntuación y nombre de quien la ostenta options.game.hi_score_table[0].score); // Máxima puntuación y nombre de quien la ostenta
int current_stage_; // Indica la fase actual int current_stage_; // Indica la fase actual
int last_stage_reached_; // Contiene el número de la última pantalla que se ha alcanzado
Demo demo_; // Variable con todas las variables relacionadas con el modo demo Demo demo_; // Variable con todas las variables relacionadas con el modo demo
GameDifficulty difficulty_ = options.game.difficulty; // Dificultad del juego GameDifficulty difficulty_ = options.game.difficulty; // Dificultad del juego
Helper helper_; // Variable para gestionar las ayudas Helper helper_; // Variable para gestionar las ayudas
@@ -167,8 +164,6 @@ private:
float balloon_speed_; // Velocidad a la que se mueven los enemigos float balloon_speed_; // Velocidad a la que se mueven los enemigos
float default_balloon_speed_; // Velocidad base de los enemigos, sin incrementar float default_balloon_speed_; // Velocidad base de los enemigos, sin incrementar
float difficulty_score_multiplier_; // Multiplicador de puntos en función de la dificultad float difficulty_score_multiplier_; // Multiplicador de puntos en función de la dificultad
float get_ready_bitmap_path_[STAGE_COUNTER_]; // Vector con los puntos X por donde se desplaza el texto
int stage_bitmap_path_[STAGE_COUNTER_]; // Vector con los puntos Y por donde se desplaza el texto
int balloon_deploy_counter_ = 0; // Cuando se lanza una formación, se le da un valor y no sale otra hasta que llegue a cero int balloon_deploy_counter_ = 0; // Cuando se lanza una formación, se le da un valor y no sale otra hasta que llegue a cero
int balloons_popped_ = 0; // Lleva la cuenta de los globos explotados int balloons_popped_ = 0; // Lleva la cuenta de los globos explotados
int counter_ = 0; // Contador para el juego int counter_ = 0; // Contador para el juego
@@ -179,7 +174,6 @@ private:
int menace_current_ = 0; // Nivel de amenaza actual int menace_current_ = 0; // Nivel de amenaza actual
int menace_threshold_ = 0; // Umbral del nivel de amenaza. Si el nivel de amenaza cae por debajo del umbral, se generan más globos. Si el umbral aumenta, aumenta el número de globos int menace_threshold_ = 0; // Umbral del nivel de amenaza. Si el nivel de amenaza cae por debajo del umbral, se generan más globos. Si el umbral aumenta, aumenta el número de globos
int power_ball_counter_ = 0; // Contador de formaciones enemigas entre la aparicion de una PowerBall y otra int power_ball_counter_ = 0; // Contador de formaciones enemigas entre la aparicion de una PowerBall y otra
int stage_bitmap_counter_ = STAGE_COUNTER_; // Contador para el tiempo visible del texto de Stage
int time_stopped_counter_ = 0; // Temporizador para llevar la cuenta del tiempo detenido int time_stopped_counter_ = 0; // Temporizador para llevar la cuenta del tiempo detenido
int total_power_to_complete_game_; // La suma del poder necesario para completar todas las fases int total_power_to_complete_game_; // La suma del poder necesario para completar todas las fases
#ifdef DEBUG #ifdef DEBUG
@@ -304,7 +298,7 @@ private:
void createItemText(int x, std::shared_ptr<Texture> texture); void createItemText(int x, std::shared_ptr<Texture> texture);
// Crea un objeto PathSprite // Crea un objeto PathSprite
void createMessage(std::vector<Path> paths, std::shared_ptr<Texture> texture); void createMessage(const std::vector<Path> &paths, std::shared_ptr<Texture> texture);
// Vacia el vector de smartsprites // Vacia el vector de smartsprites
void freeSmartSprites(); void freeSmartSprites();

View File

@@ -63,19 +63,23 @@ struct ParamNotification
}; };
// Estructura para almacenar todos los parámetros del juego // Estructura para almacenar todos los parámetros del juego
struct Param struct Param {
{ ParamGame game;
ParamGame game; // Parametros relacionados con el juego ParamFade fade;
ParamFade fade; // Parametros para ajustar el fade SDL_Rect scoreboard;
SDL_Rect scoreboard; // Posición y tamaño del marcador ParamTitle title;
ParamTitle title; // Parametros con ajustes para la sección Title ParamBackground background;
ParamBackground background; // Parametros que afectan a la clase Background std::vector<ParamBalloon> balloon;
std::vector<ParamBalloon> balloon; // Parametros de velocidad y gravedad de cada tipo de globo ParamNotification notification;
ParamNotification notification; // Opciones para las notificaciones
Param() { balloon.reserve(4); } Param() : game(), fade(), scoreboard(), title(), background(), notification() {
balloon.reserve(4);
}
}; };
extern Param 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

View File

@@ -1,11 +1,8 @@
#include "path_sprite.h" #include "path_sprite.h"
#include <bits/std_abs.h> // Para abs #include <bits/std_abs.h> // for abs
#include <stdlib.h> // Para abs #include <stdlib.h> // for abs
#include <utility> // Para move #include <functional> // for function
#include "moving_sprite.h" // Para MovingSprite #include <utility> // for move
#include "utils.h" // Para easeOutQuint
#include <functional>
class Texture; // lines 3-3
// Devuelve un vector con los puntos que conforman la ruta // Devuelve un vector con los puntos que conforman la ruta
std::vector<SDL_Point> createPath(int start, int end, PathType type, int fixed_pos, int steps, const std::function<double(double)> &easingFunction) std::vector<SDL_Point> createPath(int start, int end, PathType type, int fixed_pos, int steps, const std::function<double(double)> &easingFunction)
@@ -54,9 +51,34 @@ void PathSprite::update()
} }
// Añade un recorrido // Añade un recorrido
void PathSprite::addPath(Path path) void PathSprite::addPath(Path path, bool centered)
{ {
paths_.emplace_back(path); PathCentered path_centered = PathCentered::NONE;
if (centered)
path_centered = (path.spots.back().x == path.spots.front().x) ? PathCentered::ON_X : PathCentered::ON_Y;
switch (path_centered)
{
case PathCentered::ON_X:
{
const int x = path.spots.back().x - pos_.w / 2;
for (auto &spot : path.spots)
spot.x = x;
paths_.emplace_back(path);
break;
}
case PathCentered::ON_Y:
{
const int y = path.spots.back().y - pos_.h / 2;
for (auto &spot : path.spots)
spot.y = y;
paths_.emplace_back(path);
break;
}
default:
paths_.emplace_back(path);
break;
}
} }
// Añade un recorrido // Añade un recorrido
@@ -103,7 +125,7 @@ void PathSprite::moveThroughCurrentPath()
if (path.waiting_counter == 0) if (path.waiting_counter == 0)
path.finished = true; path.finished = true;
else else
--path.waiting_counter; --path.waiting_counter;
} }
} }

View File

@@ -1,11 +1,11 @@
#pragma once #pragma once
#include <SDL2/SDL_rect.h> // Para SDL_Point #include <SDL2/SDL_rect.h> // for SDL_Point
#include <memory> // Para shared_ptr #include <functional> // for function
#include <functional> #include <memory> // for shared_ptr
#include <vector> // Para vector #include <vector> // for vector
#include "animated_sprite.h" // Para AnimatedSprite #include "sprite.h" // for Sprite
class Texture; // lines 5-5 class Texture; // lines 8-8
enum class PathType enum class PathType
{ {
@@ -13,6 +13,13 @@ enum class PathType
HORIZONTAL, HORIZONTAL,
}; };
enum class PathCentered
{
ON_X,
ON_Y,
NONE,
};
// Estructuras // Estructuras
struct Path struct Path
{ {
@@ -35,7 +42,6 @@ class PathSprite : public Sprite
{ {
private: private:
// Variables // Variables
bool finished_ = false; // Indica si ya ha terminado
bool enabled_ = false; // Indica si el objeto está habilitado bool enabled_ = false; // Indica si el objeto está habilitado
int current_path_ = 0; // Path que se está recorriendo actualmente int current_path_ = 0; // Path que se está recorriendo actualmente
std::vector<Path> paths_; // Caminos a recorrer por el sprite std::vector<Path> paths_; // Caminos a recorrer por el sprite
@@ -58,7 +64,7 @@ public:
void update(); void update();
// Añade un recorrido // Añade un recorrido
void addPath(Path path); void addPath(Path path, bool centered = false);
void addPath(std::vector<SDL_Point> spots, int waiting_counter); void addPath(std::vector<SDL_Point> spots, int waiting_counter);
void addPath(int start, int end, PathType type, int fixed_pos, int steps, const std::function<double(double)> &easingFunction, int waiting_counter); void addPath(int start, int end, PathType type, int fixed_pos, int steps, const std::function<double(double)> &easingFunction, int waiting_counter);

View File

@@ -238,26 +238,31 @@ void Resource::createTextures()
: name(name_init), text(text_init) {} : name(name_init), text(text_init) {}
}; };
std::cout << "\n>> CREATING TEXTURES" << std::endl;
auto text = std::make_unique<Text>(getTexture("04b_25.png"), getTextFile("04b_25.txt"));
// Tamaño normal
std::vector<NameAndText> strings = { std::vector<NameAndText> strings = {
NameAndText("game_text_1000_points", "1.000"), NameAndText("game_text_1000_points", "1.000"),
NameAndText("game_text_2500_points", "2.500"), NameAndText("game_text_2500_points", "2.500"),
NameAndText("game_text_5000_points", "5.000"), NameAndText("game_text_5000_points", "5.000"),
NameAndText("game_text_powerup", "PowerUp"), NameAndText("game_text_powerup", lang::getText(117)),
NameAndText("game_text_one_hit", "+1 Hit"), NameAndText("game_text_one_hit", lang::getText(118)),
NameAndText("game_text_stop", "Stop!")}; NameAndText("game_text_stop", lang::getText(119)),
NameAndText("1000000_points", lang::getText(76))};
auto text = std::make_unique<Text>(getTexture("04b_25.png"), getTextFile("04b_25.txt"));
std::cout << "\n>> CREATING TEXTURES" << std::endl;
for (const auto &s : strings) for (const auto &s : strings)
{ {
textures_.emplace_back(ResourceTexture(s.name, text->writeToTexture(s.text, 1, -2))); textures_.emplace_back(ResourceTexture(s.name, text->writeToTexture(s.text, 1, -2)));
printWithDots("Texture : ", s.name, "[ DONE ]"); printWithDots("Texture : ", s.name, "[ DONE ]");
} }
// Tamaño doble
std::vector<NameAndText> strings2X = { std::vector<NameAndText> strings2X = {
NameAndText("get_ready", lang::getText(75)), NameAndText("get_ready", lang::getText(75)),
NameAndText("stages_remaining", "9 " + lang::getText(38))}; NameAndText("last_stage", lang::getText(79)),
NameAndText("congratulations", lang::getText(50)),
NameAndText("game_over", "Game Over")};
for (const auto &s : strings2X) for (const auto &s : strings2X)
{ {

View File

@@ -141,7 +141,7 @@ void Screen::blit()
// Copia la textura de juego en el renderizador en la posición adecuada // Copia la textura de juego en el renderizador en la posición adecuada
if (shake_effect_.enabled) if (shake_effect_.enabled)
SDL_RenderCopy(renderer_, game_canvas_, nullptr, nullptr); SDL_RenderCopy(renderer_, game_canvas_, nullptr, nullptr); // Esta copia es para evitar que se vea negro por los laterales
SDL_RenderCopy(renderer_, game_canvas_, &src_rect_, &dst_rect_); SDL_RenderCopy(renderer_, game_canvas_, &src_rect_, &dst_rect_);
// Muestra por pantalla el renderizador // Muestra por pantalla el renderizador
@@ -375,10 +375,7 @@ void Screen::updateShakeEffect()
// Pone la pantalla de color // Pone la pantalla de color
void Screen::flash(Color color, int lenght) void Screen::flash(Color color, int lenght)
{ {
flash_effect_.enabled = true; flash_effect_ = FlashEffect(true, lenght, color);
flash_effect_.counter = 0;
flash_effect_.lenght = lenght;
flash_effect_.color = color;
} }
// Actualiza y dibuja el efecto de flash en la pantalla // Actualiza y dibuja el efecto de flash en la pantalla
@@ -387,14 +384,14 @@ void Screen::doFlash()
if (flash_effect_.enabled) if (flash_effect_.enabled)
{ {
// Dibuja el color del flash en la textura // Dibuja el color del flash en la textura
SDL_Texture *temp = SDL_GetRenderTarget(renderer_); //auto temp = SDL_GetRenderTarget(renderer_);
SDL_SetRenderTarget(renderer_, game_canvas_); //SDL_SetRenderTarget(renderer_, game_canvas_);
SDL_SetRenderDrawColor(renderer_, flash_effect_.color.r, flash_effect_.color.g, flash_effect_.color.b, 0xFF); SDL_SetRenderDrawColor(renderer_, flash_effect_.color.r, flash_effect_.color.g, flash_effect_.color.b, 0xFF);
SDL_RenderClear(renderer_); SDL_RenderClear(renderer_);
SDL_SetRenderTarget(renderer_, temp); //SDL_SetRenderTarget(renderer_, temp);
// Actualiza la lógica del efecto // Actualiza la lógica del efecto
flash_effect_.counter < flash_effect_.lenght ? flash_effect_.counter++ : flash_effect_.enabled = false; flash_effect_.counter > 0 ? flash_effect_.counter-- : flash_effect_.enabled = false;
} }
} }
@@ -403,11 +400,11 @@ void Screen::doAttenuate()
{ {
if (attenuate_effect_) if (attenuate_effect_)
{ {
SDL_Texture *temp = SDL_GetRenderTarget(renderer_); //auto temp = SDL_GetRenderTarget(renderer_);
SDL_SetRenderTarget(renderer_, game_canvas_); //SDL_SetRenderTarget(renderer_, game_canvas_);
SDL_SetRenderDrawColor(renderer_, 0, 0, 0, 64); SDL_SetRenderDrawColor(renderer_, 0, 0, 0, 64);
SDL_RenderFillRect(renderer_, nullptr); SDL_RenderFillRect(renderer_, nullptr);
SDL_SetRenderTarget(renderer_, temp); //SDL_SetRenderTarget(renderer_, temp);
} }
} }

View File

@@ -43,7 +43,7 @@ private:
int fps_ = 0; // Frames calculados en el último segundo int fps_ = 0; // Frames calculados en el último segundo
std::string info_resolution_; // Texto con la informacion de la pantalla std::string info_resolution_; // Texto con la informacion de la pantalla
#ifdef DEBUG #ifdef DEBUG
bool show_info_ = true; // Indica si ha de mostrar/ocultar la información de la pantalla bool show_info_ = false; // Indica si ha de mostrar/ocultar la información de la pantalla
#else #else
bool show_info_ = false; // Indica si ha de mostrar/ocultar la información de la pantalla bool show_info_ = false; // Indica si ha de mostrar/ocultar la información de la pantalla
#endif #endif
@@ -52,12 +52,11 @@ private:
{ {
bool enabled; // Indica si el efecto está activo bool enabled; // Indica si el efecto está activo
int counter; // Contador para el efecto int counter; // Contador para el efecto
int lenght; // Duración del efecto
Color color; // Color del efecto Color color; // Color del efecto
// Constructor // Constructor
explicit FlashEffect(bool en = false, int cnt = 0, int len = 0, Color col = Color(0xFF, 0xFF, 0xFF)) explicit FlashEffect(bool en = false, int cnt = 0, Color col = Color(0xFF, 0xFF, 0xFF))
: enabled(en), counter(cnt), lenght(len), color(col) {} : enabled(en), counter(cnt), color(col) {}
}; };
struct ShakeEffect struct ShakeEffect

View File

@@ -1,12 +1,16 @@
#include "text.h" #include "text.h"
#include <SDL2/SDL_rect.h> // Para SDL_Rect #include <SDL2/SDL_blendmode.h> // for SDL_BLENDMODE_BLEND
#include <fstream> // Para basic_ifstream, basic_istream, basic_ostream #include <SDL2/SDL_pixels.h> // for SDL_PIXELFORMAT_RGBA8888
#include <iostream> // Para cerr #include <SDL2/SDL_rect.h> // for SDL_Rect
#include <stdexcept> // Para runtime_error #include <SDL2/SDL_render.h> // for SDL_TEXTUREACCESS_TARGET
#include "sprite.h" // Para Sprite #include <stddef.h> // for size_t
#include "screen.h" // Para Screen #include <fstream> // for basic_ifstream, basic_istream, basic...
#include "texture.h" // Para Texture #include <iostream> // for cerr
#include "utils.h" // Para Color, getFileName, printWithDots #include <stdexcept> // for runtime_error
#include "screen.h" // for Screen
#include "sprite.h" // for Sprite
#include "texture.h" // for Texture
#include "utils.h" // for Color, getFileName, printWithDots
// Llena una estructuta TextFile desde un fichero // Llena una estructuta TextFile desde un fichero
std::shared_ptr<TextFile> loadTextFile(const std::string &file_path) std::shared_ptr<TextFile> loadTextFile(const std::string &file_path)
@@ -46,9 +50,7 @@ std::shared_ptr<TextFile> loadTextFile(const std::string &file_path)
{ {
// Almacena solo las lineas impares // Almacena solo las lineas impares
if (line_read % 2 == 1) if (line_read % 2 == 1)
{
tf->offset[index++].w = std::stoi(buffer); tf->offset[index++].w = std::stoi(buffer);
}
// Limpia el buffer // Limpia el buffer
buffer.clear(); buffer.clear();