demo.cpp a fer la mar

This commit is contained in:
2025-03-02 10:41:38 +01:00
parent 82f0992116
commit cdf0b0a694
6 changed files with 158 additions and 344 deletions

View File

@@ -1,195 +0,0 @@
#include "demo.h"
#include <SDL2/SDL_events.h> // for SDL_PollEvent, SDL_Event
#include <SDL2/SDL_rect.h> // for SDL_Rect
#include <SDL2/SDL_render.h> // for SDL_RenderFillRect, SDL_SetRenderDrawColor
#include <SDL2/SDL_timer.h> // for SDL_GetTicks
#include "asset.h" // for Asset
#include "defines.h" // for BLOCK, PLAY_AREA_WIDTH, GAMECANVAS_CENT...
#include "global_events.h" // for check
#include "global_inputs.h" // for check
#include "item_tracker.h" // for ItemTracker
#include "options.h" // for Options, options, OptionsVideo, Section...
#include "resource.h" // for Resource
#include "room.h" // for Room
#include "scoreboard.h" // for ScoreboardData, Scoreboard
#include "screen.h" // for Screen
#include "text.h" // for TEXT_CENTER, TEXT_COLOR, Text
#include "utils.h" // for Color, stringToColor, colorAreEqual
// Constructor
Demo::Demo()
: board_(std::make_shared<ScoreboardData>())
{
// Inicia algunas variables
board_->ini_clock = SDL_GetTicks();
rooms_.push_back("04.room");
rooms_.push_back("54.room");
rooms_.push_back("20.room");
rooms_.push_back("09.room");
rooms_.push_back("05.room");
rooms_.push_back("11.room");
rooms_.push_back("31.room");
rooms_.push_back("44.room");
room_index_ = 0;
current_room_ = rooms_[room_index_];
// Crea los objetos
ItemTracker::init();
scoreboard_ = std::make_shared<Scoreboard>(board_);
room_ = std::make_shared<Room>(current_room_, board_);
// Inicializa el resto de variables
counter_ = 0;
room_time_ = 400;
ticks_ = 0;
board_->lives = 9;
board_->items = 0;
board_->rooms = 1;
board_->jail_is_open = false;
board_->music = true;
setScoreBoardColor();
options.section.section = Section::DEMO;
options.section.subsection = Subsection::NONE;
}
// Destructor
Demo::~Demo()
{
ItemTracker::destroy();
}
// Comprueba los eventos de la cola
void Demo::checkEvents()
{
SDL_Event event;
while (SDL_PollEvent(&event))
{
globalEvents::check(event);
}
}
// Comprueba las entradas
void Demo::checkInput()
{
globalInputs::check();
}
// Bucle para el juego
void Demo::run()
{
while (options.section.section == Section::DEMO)
{
update();
checkEvents();
render();
}
}
// Actualiza el juego, las variables, comprueba la entrada, etc.
void Demo::update()
{
// Comprueba que la diferencia de ticks sea mayor a la velocidad del juego
if (SDL_GetTicks() - ticks_ > GAME_SPEED)
{
// Actualiza el contador de ticks
ticks_ = SDL_GetTicks();
// Comprueba las entradas
checkInput();
// Actualiza los objetos
room_->update();
scoreboard_->update();
checkRoomChange();
Screen::get()->update();
}
}
// Pinta los objetos en pantalla
void Demo::render()
{
// Prepara para dibujar el frame
Screen::get()->start();
// Dibuja los elementos del juego en orden
room_->renderMap();
room_->renderEnemies();
room_->renderItems();
renderRoomName();
scoreboard_->render();
// Actualiza la pantalla
Screen::get()->render();
}
// Escribe el nombre de la pantalla
void Demo::renderRoomName()
{
// Texto en el centro de la pantalla
SDL_Rect rect = {0, 16 * BLOCK, PLAY_AREA_WIDTH, BLOCK * 2};
Color color = stringToColor(options.video.palette, "white");
SDL_SetRenderDrawColor(Screen::get()->getRenderer(), color.r, color.g, color.b, 0xFF);
SDL_RenderFillRect(Screen::get()->getRenderer(), &rect);
Resource::get()->getText("smb2")->writeDX(TEXT_CENTER | TEXT_COLOR, GAMECANVAS_CENTER_X, 16 * 8 + 4, room_->getName(), 1, room_->getBGColor());
}
// Cambia de habitación
bool Demo::changeRoom(const std::string &room_path)
{
// En las habitaciones los limites tienen la cadena del fichero o un 0 en caso de no limitar con nada
if (room_path != "0")
{
// Verifica que exista el fichero que se va a cargar
if (Asset::get()->get(room_path) != "")
{
// Crea un objeto habitación a partir del fichero
room_ = std::make_shared<Room>(room_path, board_);
// Pone el color del marcador en función del color del borde de la habitación
setScoreBoardColor();
return true;
}
}
return false;
}
// Comprueba si se ha de cambiar de habitación
void Demo::checkRoomChange()
{
counter_++;
if (counter_ == room_time_)
{
counter_ = 0;
room_index_++;
if (room_index_ == (int)rooms_.size())
{
options.section.section = Section::LOGO;
options.section.subsection = Subsection::LOGO_TO_TITLE;
}
else
{
changeRoom(rooms_[room_index_]);
}
}
}
// Pone el color del marcador en función del color del borde de la habitación
void Demo::setScoreBoardColor()
{
// Obtiene el color del borde
const Color color = room_->getBorderColor();
// Si el color es negro lo cambia a blanco
const Color black_color = stringToColor(options.video.palette, "black");
board_->color = colorAreEqual(color, black_color) ? stringToColor(options.video.palette, "white") : color;
// Si el color es negro brillante lo cambia a blanco
const Color bright_blac_color = stringToColor(options.video.palette, "bright_black");
board_->color = colorAreEqual(color, bright_blac_color) ? stringToColor(options.video.palette, "white") : color;
}

View File

@@ -1,60 +0,0 @@
#pragma once
#include <SDL2/SDL_stdinc.h> // for Uint32
#include <memory> // for shared_ptr
#include <string> // for string
#include <vector> // for vector
class Room; // lines 14-14
class Scoreboard;
struct ScoreboardData;
class Demo
{
private:
// Objetos y punteros
std::shared_ptr<Room> room_; // Objeto encargado de gestionar cada habitación del juego
std::shared_ptr<Scoreboard> scoreboard_; // Objeto encargado de gestionar el marcador
// Variables
Uint32 ticks_; // Contador de ticks para ajustar la velocidad del programa
std::string current_room_; // Fichero de la habitación actual
std::shared_ptr<ScoreboardData> board_; // Estructura con los datos del marcador
int counter_; // Contador para el modo demo
int room_time_; // Tiempo que se muestra cada habitacion
int room_index_; // Indice para el vector de habitaciones
std::vector<std::string> rooms_; // Listado con los mapas de la demo
// Actualiza el juego, las variables, comprueba la entrada, etc.
void update();
// Pinta los objetos en pantalla
void render();
// Comprueba los eventos de la cola
void checkEvents();
// Comprueba las entradas
void checkInput();
// Escribe el nombre de la pantalla
void renderRoomName();
// Cambia de habitación
bool changeRoom(const std::string &file);
// Comprueba si se ha de cambiar de habitación
void checkRoomChange();
// Pone el color del marcador en función del color del borde de la habitación
void setScoreBoardColor();
public:
// Constructor
Demo();
// Destructor
~Demo();
// Bucle para el juego
void run();
};

View File

@@ -22,7 +22,6 @@
#include "credits.h" // for Credits
#include "debug.h" // for Debug
#include "defines.h" // for WINDOW_CAPTION, borderColor
#include "demo.h" // for Demo
#include "ending.h" // for Ending
#include "ending2.h" // for Ending2
#include "game.h" // for Game
@@ -110,41 +109,37 @@ Director::~Director()
// Comprueba los parametros del programa
std::string Director::checkProgramArguments(int argc, const char *argv[])
{
// Comprueba los parametros
// Iterar sobre los argumentos del programa
for (int i = 1; i < argc; ++i)
{
if (strcmp(argv[i], "--console") == 0)
std::string argument(argv[i]);
if (argument == "--console")
{
options.console = true;
}
else if (strcmp(argv[i], "--infiniteLives") == 0)
else if (argument == "--infiniteLives")
{
options.cheats.infinite_lives = Cheat::CheatState::ENABLED;
}
else if (strcmp(argv[i], "--invincible") == 0)
else if (argument == "--invincible")
{
options.cheats.invincible = Cheat::CheatState::ENABLED;
;
}
else if (strcmp(argv[i], "--jailEnabled") == 0)
else if (argument == "--jailEnabled")
{
options.cheats.jail_is_open = Cheat::CheatState::ENABLED;
;
}
else if (strcmp(argv[i], "--altSkin") == 0)
else if (argument == "--altSkin")
{
options.cheats.alternate_skin = Cheat::CheatState::ENABLED;
;
}
}
return argv[0];
}
// Crea la carpeta del sistema donde guardar datos
void Director::createSystemFolder(const std::string &folder)
{
@@ -774,8 +769,8 @@ void Director::runCredits()
// Ejecuta la seccion de la demo, donde se ven pantallas del juego
void Director::runDemo()
{
auto demo = std::make_unique<Demo>();
demo->run();
auto game = std::make_unique<Game>(GameMode::DEMO);
game->run();
}
// Ejecuta la seccion del final del juego
@@ -803,7 +798,7 @@ void Director::runGameOver()
void Director::runGame()
{
JA_StopMusic();
auto game = std::make_unique<Game>();
auto game = std::make_unique<Game>(GameMode::GAME);
game->run();
}

View File

@@ -27,11 +27,12 @@
#include "utils.h" // for Color, stringToColor, colorAreEqual
// Constructor
Game::Game()
Game::Game(GameMode mode)
: board_(std::make_shared<ScoreboardData>(0, 9, 0, true, Color(0, 0, 0), SDL_GetTicks(), options.cheats.jail_is_open == Cheat::CheatState::ENABLED)),
scoreboard_(std::make_shared<Scoreboard>(board_)),
room_tracker_(std::make_shared<RoomTracker>()),
stats_(std::make_shared<Stats>(Asset::get()->get("stats.csv"), Asset::get()->get("stats_buffer.csv"))),
mode_(mode),
#ifdef DEBUG
current_room_("03.room"),
spawn_point_(PlayerSpawn(25 * BLOCK, 13 * BLOCK, 0, 0, 0, PlayerState::STANDING, SDL_FLIP_HORIZONTAL))
@@ -46,6 +47,7 @@ Game::Game()
// Crea objetos e inicializa variables
ItemTracker::init();
DEMO_init();
room_ = std::make_shared<Room>(current_room_, board_);
initPlayer(spawn_point_, room_);
initStats();
@@ -57,7 +59,7 @@ Game::Game()
Cheevos::get()->enable(!options.cheats.enabled()); // Deshabilita los logros si hay trucos activados
Cheevos::get()->clearUnobtainableState();
options.section.section = Section::GAME;
options.section.section = (mode_ == GameMode::GAME) ? Section::GAME : Section::DEMO;
options.section.subsection = Subsection::NONE;
}
@@ -108,7 +110,7 @@ void Game::run()
JA_PauseMusic();
}
while (options.section.section == Section::GAME)
while (options.section.section == Section::GAME || options.section.section == Section::DEMO)
{
update();
checkEvents();
@@ -136,6 +138,8 @@ void Game::update()
// Actualiza los objetos
room_->update();
if (mode_ == GameMode::GAME)
{
player_->update();
checkPlayerOnBorder();
checkPlayerAndItems();
@@ -145,6 +149,8 @@ void Game::update()
checkEndGame();
checkRestoringJail();
checkSomeCheevos();
}
DEMO_checkRoomChange();
scoreboard_->update();
updateBlackScreen();
@@ -162,13 +168,15 @@ void Game::render()
{
// Prepara para dibujar el frame
Screen::get()->start();
// test_surface_->render(0, 0, 10, 10, 64, 64);
// Dibuja los elementos del juego en orden
room_->renderMap();
room_->renderEnemies();
room_->renderItems();
if (mode_ == GameMode::GAME)
{
player_->render();
}
renderRoomName();
scoreboard_->render();
renderBlackScreen();
@@ -670,3 +678,37 @@ void Game::createRoomNameTexture()
// Establece el destino de la textura
room_name_rect_ = {0, PLAY_AREA_HEIGHT, GAMECANVAS_WIDTH, text->getCharacterSize() * 2};
}
// DEMO MODE: Inicializa las variables para el modo demo
void Game::DEMO_init()
{
if (mode_ == GameMode::DEMO)
{
demo_ = DemoData(0, 400, 0, {"04.room", "54.room", "20.room", "09.room", "05.room", "11.room", "31.room", "44.room"});
current_room_ = demo_.rooms.front();
}
}
// DEMO MODE: Comprueba si se ha de cambiar de habitación
void Game::DEMO_checkRoomChange()
{
if (mode_ == GameMode::DEMO)
{
demo_.counter++;
if (demo_.counter == demo_.room_time)
{
demo_.counter = 0;
demo_.room_index++;
if (demo_.room_index == (int)demo_.rooms.size())
{
options.section.section = Section::LOGO;
options.section.subsection = Subsection::LOGO_TO_TITLE;
}
else
{
changeRoom(demo_.rooms[demo_.room_index]);
}
}
}
}

View File

@@ -6,16 +6,40 @@
#include <SDL2/SDL_stdinc.h> // for Uint32
#include <memory> // for shared_ptr
#include <string> // for string
#include <vector> // for vector
#include "player.h" // for PlayerSpawn
class Room; // lines 17-17
class RoomTracker; // lines 18-18
class Scoreboard;
class Stats; // lines 20-20
struct ScoreboardData;
class Room; // lines 10-10
class RoomTracker; // lines 11-11
class Scoreboard; // lines 12-12
class Stats; // lines 13-13
struct ScoreboardData; // lines 14-14
enum class GameMode
{
DEMO,
GAME
};
class Game
{
private:
// Estructuras
struct DemoData
{
int counter; // Contador para el modo demo
int room_time; // Tiempo que se muestra cada habitación
int room_index; // Índice para el vector de habitaciones
std::vector<std::string> rooms; // Listado con los mapas de la demo
// Constructor por defecto
DemoData()
: counter(0), room_time(0), room_index(0), rooms({}) {}
// Constructor parametrizado
DemoData(int counter, int room_time, int room_index, const std::vector<std::string> &rooms)
: counter(counter), room_time(room_time), room_index(room_index), rooms(rooms) {}
};
// Objetos y punteros
std::shared_ptr<ScoreboardData> board_; // Estructura con los datos del marcador
std::shared_ptr<Scoreboard> scoreboard_; // Objeto encargado de gestionar el marcador
@@ -26,6 +50,8 @@ private:
SDL_Texture *room_name_texture_; // Textura para escribir el nombre de la habitación
// Variables
GameMode mode_; // Modo del juego
DemoData demo_; // Variables para el modo demo
Uint32 ticks_ = 0; // Contador de ticks para ajustar la velocidad del programa
std::string current_room_; // Fichero de la habitación actual
PlayerSpawn spawn_point_; // Lugar de la habitación donde aparece el jugador
@@ -124,9 +150,15 @@ private:
// Crea la textura para poner el nombre de la habitación
void createRoomNameTexture();
// DEMO MODE: Inicializa las variables para el modo demo
void DEMO_init();
// DEMO MODE: Comprueba si se ha de cambiar de habitación
void DEMO_checkRoomChange();
public:
// Constructor
Game();
Game(GameMode mode);
// Destructor
~Game();

View File

@@ -21,7 +21,7 @@ void initOptions()
options = Options();
#ifdef DEBUG
options.section = SectionState(Section::TITLE, Subsection::NONE);
options.section = SectionState(Section::DEMO, Subsection::NONE);
options.console = true;
#else
options.section = SectionState(Section::LOGO, Subsection::LOGO_TO_INTRO);