38 Commits

Author SHA1 Message Date
4a2d27dc59 Eliminados todos los std:: del código 2023-09-16 12:44:40 +02:00
71be364141 Acabada la primera versión de la lista de logros 2023-09-16 12:29:52 +02:00
16cc725cb3 Terminado el desplazamiento por la lista de logros 2023-09-16 11:02:56 +02:00
a05dbc7581 Ya es posible desplazarse de forma prematura por la lista de logros 2023-09-15 23:02:42 +02:00
2db0b43d23 Mejoras en la presentación de la lista de logros 2023-09-15 22:33:59 +02:00
d6c100379e La pantalla de titulo ya no acaba cuando termina la marquesina si la lista de logros está activa 2023-09-15 22:00:52 +02:00
22e8579337 Ya muestra la lista de logros de forma preliminar 2023-09-15 21:31:23 +02:00
d0c0715640 Añadido: la clase cheevos devuelve una lista de los logros 2023-09-15 17:05:00 +02:00
38e0573a0e Fix: Guarda los logros también cuando se desbloquean 2023-09-15 17:00:32 +02:00
f259fbb3a5 Actualizado gitignore 2023-09-15 16:27:47 +02:00
663e1ed32e Añadida barra de información en el titulo 2023-09-15 11:44:51 +02:00
b1887fe6da Fix: No se limpiaba la pantalla tras entrar el JailerID 2023-09-15 07:45:21 +02:00
3fcf3b23e0 Actualizado .gitignore 2023-05-06 18:52:54 +02:00
284f7d5bad Cambiada la carpeta common a jail_engine 2023-05-06 18:06:29 +02:00
adab0b420c - Modificada la carpeta de guardar datos al estandar de jailgames 2023-02-12 18:05:53 +01:00
4f9d8bec42 - Cambiados los textos de los creditos/instrucciones para reflejar las nuevas teclas
- Cambiados los textos de los creditos/instrucciones para la versión de consola
2023-02-12 17:44:00 +01:00
31e657d138 - Cambiadas las teclas de cambiar el tamaño de ventana para adecuarse al estandar de jailgames 2023-02-12 17:28:48 +01:00
8b3d257baf - La ventana ya no se destruye al cambiar de tamaño de ventana
- La ventana aparece centrada al cambiar de tamaño
2023-02-12 17:05:16 +01:00
d1143b9dfe - Trabajando en la creación y destrucción de la ventana
- FIX: la clase screen no liberaba la textura gameCanvas al finalizar
2023-02-10 22:55:36 +01:00
68ebff722e - FIX: cambiado el boton de guía por el de select (o back)
- Añadido flag para intercambiar los botones de start y select en consola
- Añadido botón para activar o desactivar el borde con el mando (botón X)
2023-02-10 20:31:37 +01:00
3be9d4459c - Ya se puede usar el mando en todas las secciones del juego
- Definido flag para compilar para consola de juegos (GAME_CONSOLE)
2023-02-10 20:08:06 +01:00
76e928e21d Commit para seguir programando en WSL 2023-02-10 19:07:19 +01:00
9c6924d7bb - La clase input ya admite inputs personalizados
- El juego ya utiliza el objeto input para comprobar las teclas de cambio de tamaño de ventana, pausa, etc.
2023-02-10 18:28:53 +01:00
5007bea835 Se había quedado una linea comentada 2023-01-09 09:21:22 +01:00
5e7be1c2fb Ya se guardan los logros en un fichero 2023-01-02 09:46:09 +01:00
faf2e69b63 Creando iconos para las notificaciones 2022-12-30 13:18:43 +01:00
4c3c844ccf Fix: En la secuencia del final, al pulsar ESC se cerraba el juego. Ahora vuelve al logo 2022-12-29 15:26:02 +01:00
48b8ae049a Testeados todos los logros. Los logros no funcionan con los trucos activados 2022-12-29 14:59:48 +01:00
c0d4eddde7 Colocados los disparadores de los logros en su sitio 2022-12-29 14:08:42 +01:00
f590101047 Definidos los logros 2022-12-29 13:03:10 +01:00
c7fcbd0258 Añadidos nuevos iconos para las notificaciones. Rediseñada la notificación de login. Arreglado bug: No se podia elegir un icono para las notificaciones que no fuera de la primera fila 2022-12-29 11:58:32 +01:00
b2061c86d2 Cambiado el tamaño de las notificaciones. Posibilidad de añadir un icono 2022-12-29 11:36:44 +01:00
510a6ca718 Añadido bisel a las notificaciones 2022-12-29 11:00:26 +01:00
ec8209265a Añadidos iconos a las notificaciones 2022-12-29 10:19:11 +01:00
e963251fd9 Modificadas las notificaciones a dos lineas de texto 2022-12-29 09:42:57 +01:00
a2f1efd2a6 Empezando a trabajar con los logros 2022-12-29 09:09:36 +01:00
8959b7bcce Arreglado el cambio de paleta durante la pantalla de carga optimizada 2022-12-16 11:15:13 +01:00
4d8bb46a52 Cambiada la variable section por un puntero 2022-12-16 09:32:33 +01:00
79 changed files with 2150 additions and 1391 deletions

4
.gitignore vendored
View File

@@ -10,4 +10,6 @@ thumbs.db
*.tar.gz
*.zip
*.app
*_debug*
*_debug*
sync_jail_engine.sh
jaildoctors_dilemma*

View File

@@ -1,8 +1,8 @@
executable = jaildoctors_dilemma
source = source/*.cpp source/common/*.cpp
source = source/*.cpp source/jail_engine/*.cpp
appName = JailDoctor's Dilemma
releaseFolder = jdd_release
version = v1.07
version = v1.08
# Release names
windowsRelease = $(executable)-$(version)-win32-x64.zip

View File

@@ -1,4 +1,4 @@
# JailDoctor's Dilemma (v1.07)
# JailDoctor's Dilemma (v1.08)
JailDoc es un Jailer. A los Jailers les gusta empezar proyectos. A nadie le gusta terminarlos. Los Jailers viven en la Jail. A la Jail va uno a empezar proyectos. A la Jail va uno a enseñar sus proyectos. A la Jail va uno a aprender como empezar nuevos proyectos. A la Jail va uno a ayudar a sus compañeros a que empiecen nuevos proyectos.

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

View File

@@ -23,11 +23,11 @@
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0.7</string>
<string>1.0.8</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1.0.7</string>
<string>1.0.8</string>
<key>CSResourcesFileMapped</key>
<true/>
<key>LSMinimumSystemVersion</key>

View File

@@ -1,13 +1,267 @@
#include "cheevos.h"
#include <iostream>
// Constructor
Cheevos::Cheevos(options_t *options)
Cheevos::Cheevos(Screen *screen, options_t *options, string file)
{
// Copia la dirección de los objetos
this->options = options;
this->screen = screen;
this->file = file;
// Inicializa los logros
init();
// Inicializa variables
enabled = true;
// Carga el estado de los logros desde un fichero
loadFromFile();
}
// Destructor
Cheevos::~Cheevos()
{
// Guarda el estado de los logros en un fichero
saveToFile();
cheevos.clear();
}
// Inicializa los logros
void Cheevos::init()
{
cheevos_t c;
c.completed = false;
c.valid = true;
c.icon = 2;
c.id = 1;
c.caption = "SHINY THINGS";
c.description = "Get 25\% of the items";
cheevos.push_back(c);
c.id = 2;
c.caption = "HALF THE WORK";
c.description = "Get 50\% of the items";
cheevos.push_back(c);
c.id = 3;
c.caption = "GETTING THERE";
c.description = "Get 75\% of the items";
cheevos.push_back(c);
c.id = 4;
c.caption = "THE COLLECTOR";
c.description = "Get 100\% of the items";
cheevos.push_back(c);
c.id = 5;
c.caption = "WANDERING AROUND";
c.description = "Visit 20 rooms";
cheevos.push_back(c);
c.id = 6;
c.caption = "I GOT LOST";
c.description = "Visit 40 rooms";
cheevos.push_back(c);
c.id = 7;
c.caption = "I LIKE TO EXPLORE";
c.description = "Visit all rooms";
cheevos.push_back(c);
c.id = 8;
c.caption = "FINISH THE GAME";
c.description = "Complete the game";
cheevos.push_back(c);
c.id = 9;
c.caption = "I WAS SUCKED BY A HOLE";
c.description = "Complete the game without entering the jail";
cheevos.push_back(c);
c.id = 10;
c.caption = "MY LITTLE PROJECTS";
c.description = "Complete the game with all items";
cheevos.push_back(c);
c.id = 11;
c.caption = "I LIKE MY MULTICOLOURED FRIENDS";
c.description = "Complete the game without dying";
cheevos.push_back(c);
c.id = 12;
c.caption = "SHIT PROJECTS DONE FAST";
c.description = "Complete the game in under 30 minutes";
cheevos.push_back(c);
}
// Busca un logro por id y devuelve el indice
int Cheevos::find(int id)
{
for (int i = 0; i < (int)cheevos.size(); ++i)
{
if (cheevos[i].id == id)
{
return i;
}
}
return -1;
}
// Desbloquea un logro
void Cheevos::unlock(int id)
{
const int index = find(id);
if (index == -1)
{
return;
}
if (!cheevos[index].valid)
{
return;
}
if (cheevos[index].completed)
{
return;
}
if (!enabled)
{
return;
}
cheevos[index].completed = true;
screen->showNotification("ACHIEVEMENT UNLOCKED!", cheevos[index].caption, cheevos[index].icon);
saveToFile();
}
// Invalida un logro
void Cheevos::invalidate(int id)
{
const int index = find(id);
if (index == -1)
{
return;
}
cheevos[index].valid = false;
}
// Habilita o deshabilita los logros
void Cheevos::enable(bool value)
{
enabled = value;
}
// Carga el estado de los logros desde un fichero
void Cheevos::loadFromFile()
{
// Open file for reading in binary
SDL_RWops *file = SDL_RWFromFile(this->file.c_str(), "r+b");
// El fichero no existe
if (file == NULL)
{
if (options->console)
{
cout << "Warning: Unable to open file! SDL Error: " << SDL_GetError() << endl;
}
// Crea el fichero en modo escritura
file = SDL_RWFromFile(this->file.c_str(), "w+b");
if (file != NULL)
{
if (options->console)
{
cout << "New file created!" << endl;
}
// Guarda la información
for (int i = 0; i < (int)cheevos.size(); ++i)
{
SDL_RWwrite(file, &cheevos[i].completed, sizeof(bool), 1);
}
// Cierra el fichero
SDL_RWclose(file);
}
else
{
if (options->console)
{
cout << "Error: Unable to create file! SDL Error: " << SDL_GetError() << endl;
}
}
}
// El fichero existe
else
{
// Carga los datos
if (options->console)
{
cout << "Reading file...!" << endl;
}
for (int i = 0; i < (int)cheevos.size(); ++i)
{
SDL_RWread(file, &cheevos[i].completed, sizeof(bool), 1);
}
// Cierra el fichero
SDL_RWclose(file);
}
}
// Guarda el estado de los logros en un fichero
void Cheevos::saveToFile()
{
// Abre el fichero en modo escritura
SDL_RWops *file = SDL_RWFromFile(this->file.c_str(), "w+b");
if (file != NULL)
{
// Guarda la información
for (int i = 0; i < (int)cheevos.size(); ++i)
{
SDL_RWwrite(file, &cheevos[i].completed, sizeof(bool), 1);
}
// Cierra el fichero
SDL_RWclose(file);
}
else
{
if (options->console)
{
cout << "Error: Unable to save file! " << SDL_GetError() << endl;
}
}
}
// Lista los logros
vector<cheevos_t> Cheevos::list()
{
return cheevos;
}
// Devuelve el número total de logros desbloqueados
int Cheevos::unlocked()
{
int count = 0;
for (auto cheevo : cheevos)
{
if (cheevo.completed)
count++;
}
return count;
}
// Devuelve el número total de logros
int Cheevos::count()
{
return cheevos.size();
}

View File

@@ -1,27 +1,73 @@
#pragma once
#include <SDL2/SDL.h>
#include "common/utils.h"
#include "jail_engine/screen.h"
#include "jail_engine/utils.h"
#include <string>
#include <vector>
#ifndef CHEEVOS_H
#define CHEEVOS_H
using namespace std;
struct cheevos_t
{
int id; // Identificador del logro
string caption; // Texto con el nombre del logro
string description; // Texto que describe el logro
int icon; // Indice del icono a utilizar en la notificación
bool completed; // Indica si se ha obtenido el logro
bool valid; // Indica si se puede obtener el logro
};
class Cheevos
{
private:
// Punteros y objetos
options_t *options;
Screen *screen; // Objeto encargado de dibujar en pantalla
options_t *options; // Puntero a las opciones del juego
// Variables
vector<cheevos_t> cheevos; // Listado de logros
bool enabled; // Indica si los logros se pueden obtener
string file; // Fichero done leer/almacenar el estado de los logros
// Inicializa los logros
void init();
// Busca un logro por id y devuelve el indice
int find(int id);
// Carga el estado de los logros desde un fichero
void loadFromFile();
// Guarda el estado de los logros en un fichero
void saveToFile();
public:
// Constructor
Cheevos(options_t *options);
Cheevos(Screen *screen, options_t *options, string file);
// Destructor
~Cheevos();
// Desbloquea un logro
void unlock(int id);
// Invalida un logro
void invalidate(int id);
// Habilita o deshabilita los logros
void enable(bool value);
// Lista los logros
vector<cheevos_t> list();
// Devuelve el número total de logros desbloqueados
int unlocked();
// Devuelve el número total de logros
int count();
};
#endif

View File

@@ -2,7 +2,7 @@
#include <SDL2/SDL.h>
#include <string>
#include "common/utils.h"
#include "jail_engine/utils.h"
#ifndef CONST_H
#define CONST_H

View File

@@ -2,14 +2,16 @@
#include <iostream>
// Constructor
Credits::Credits(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *asset, options_t *options)
Credits::Credits(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *asset, Input *input, options_t *options, section_t *section)
{
// Copia la dirección de los objetos
this->resource = resource;
this->renderer = renderer;
this->screen = screen;
this->resource = resource;
this->asset = asset;
this->input = input;
this->options = options;
this->section = section;
// Reserva memoria para los punteros
eventHandler = new SDL_Event();
@@ -20,8 +22,8 @@ Credits::Credits(SDL_Renderer *renderer, Screen *screen, Resource *resource, Ass
counter = 0;
counterEnabled = true;
subCounter = 0;
section.name = SECTION_PROG_CREDITS;
section.subsection = 0;
section->name = SECTION_PROG_CREDITS;
section->subsection = 0;
ticks = 0;
ticksSpeed = 15;
sprite->setRect({194, 174, 8, 8});
@@ -35,7 +37,7 @@ Credits::Credits(SDL_Renderer *renderer, Screen *screen, Resource *resource, Ass
{
if (options->console)
{
std::cout << "Error: textTexture could not be created!\nSDL Error: " << SDL_GetError() << std::endl;
cout << "Error: textTexture could not be created!\nSDL Error: " << SDL_GetError() << endl;
}
}
SDL_SetTextureBlendMode(textTexture, SDL_BLENDMODE_BLEND);
@@ -46,7 +48,7 @@ Credits::Credits(SDL_Renderer *renderer, Screen *screen, Resource *resource, Ass
{
if (options->console)
{
std::cout << "Error: textTexture could not be created!\nSDL Error: " << SDL_GetError() << std::endl;
cout << "Error: textTexture could not be created!\nSDL Error: " << SDL_GetError() << endl;
}
}
SDL_SetTextureBlendMode(coverTexture, SDL_BLENDMODE_BLEND);
@@ -74,66 +76,57 @@ void Credits::checkEventHandler()
// Evento de salida de la aplicación
if (eventHandler->type == SDL_QUIT)
{
section.name = SECTION_PROG_QUIT;
section->name = SECTION_PROG_QUIT;
break;
}
}
}
// Comprueba las teclas que se han pulsado
if ((eventHandler->type == SDL_KEYDOWN && eventHandler->key.repeat == 0) || (eventHandler->type == SDL_JOYBUTTONDOWN))
{
switch (eventHandler->key.keysym.scancode)
{
case SDL_SCANCODE_ESCAPE:
section.name = SECTION_PROG_QUIT;
break;
// Comprueba las entradas
void Credits::checkInput()
{
case SDL_SCANCODE_B:
screen->switchBorder();
resource->reLoadTextures();
break;
if (input->checkInput(input_exit, REPEAT_FALSE))
{
section->name = SECTION_PROG_QUIT;
}
case SDL_SCANCODE_F:
screen->switchVideoMode();
resource->reLoadTextures();
break;
else if (input->checkInput(input_toggle_border, REPEAT_FALSE))
{
screen->switchBorder();
}
case SDL_SCANCODE_F1:
screen->setWindowSize(1);
resource->reLoadTextures();
break;
else if (input->checkInput(input_window_fullscreen, REPEAT_FALSE))
{
screen->switchVideoMode();
}
case SDL_SCANCODE_F2:
screen->setWindowSize(2);
resource->reLoadTextures();
break;
else if (input->checkInput(input_window_dec_size, REPEAT_FALSE))
{
screen->decWindowSize();
}
case SDL_SCANCODE_F3:
screen->setWindowSize(3);
resource->reLoadTextures();
break;
else if (input->checkInput(input_window_inc_size, REPEAT_FALSE))
{
screen->incWindowSize();
}
case SDL_SCANCODE_F4:
screen->setWindowSize(4);
resource->reLoadTextures();
break;
else if (input->checkInput(input_swap_palette, REPEAT_FALSE))
{
switchPalette();
}
case SDL_SCANCODE_F5:
switchPalette();
break;
default:
section.name = SECTION_PROG_TITLE;
section.subsection = 0;
break;
}
}
else if (input->checkInput(input_pause, REPEAT_FALSE) || input->checkInput(input_accept, REPEAT_FALSE) || input->checkInput(input_jump, REPEAT_FALSE))
{
section->name = SECTION_PROG_TITLE;
section->subsection = 0;
}
}
// Inicializa los textos
void Credits::iniTexts()
{
std::string keys = "";
string keys = "";
if (options->keys == ctrl_cursor)
{
keys = "CURSORS";
@@ -147,6 +140,7 @@ void Credits::iniTexts()
keys = "A,D AND W";
}
#ifndef GAME_CONSOLE
texts.clear();
texts.push_back({"", stringToColor(options->palette, "white")});
texts.push_back({"INSTRUCTIONS:", stringToColor(options->palette, "yellow")});
@@ -160,11 +154,11 @@ void Credits::iniTexts()
texts.push_back({"KEYS:", stringToColor(options->palette, "yellow")});
texts.push_back({"", stringToColor(options->palette, "white")});
texts.push_back({keys + " TO MOVE AND JUMP", stringToColor(options->palette, "white")});
texts.push_back({"M TO TURN ON/OFF THE MUSIC", stringToColor(options->palette, "white")});
texts.push_back({"H TO HOLD/PAUSE THE GAME", stringToColor(options->palette, "white")});
texts.push_back({"F1-F4 TO CHANGE WINDOWS SIZE", stringToColor(options->palette, "white")});
texts.push_back({"F TO SWITCH TO FULLSCREEN", stringToColor(options->palette, "white")});
texts.push_back({"B TO SWITCH THE BORDER SCREEN", stringToColor(options->palette, "white")});
texts.push_back({"M TO SWITCH THE MUSIC", stringToColor(options->palette, "white")});
texts.push_back({"H TO PAUSE THE GAME", stringToColor(options->palette, "white")});
texts.push_back({"F1-F2 TO CHANGE WINDOWS SIZE", stringToColor(options->palette, "white")});
texts.push_back({"F3 TO SWITCH TO FULLSCREEN", stringToColor(options->palette, "white")});
texts.push_back({"B TO TOOGLE THE BORDER SCREEN", stringToColor(options->palette, "white")});
texts.push_back({"", stringToColor(options->palette, "white")});
texts.push_back({"", stringToColor(options->palette, "white")});
@@ -175,6 +169,36 @@ void Credits::iniTexts()
texts.push_back({"I LOVE JAILGAMES! ", stringToColor(options->palette, "white")});
texts.push_back({"", stringToColor(options->palette, "white")});
#else
texts.clear();
texts.push_back({"", stringToColor(options->palette, "white")});
texts.push_back({"INSTRUCTIONS:", stringToColor(options->palette, "yellow")});
texts.push_back({"", stringToColor(options->palette, "white")});
texts.push_back({"HELP JAILDOC TO GET BACK ALL", stringToColor(options->palette, "white")});
texts.push_back({"HIS PROJECTS AND GO TO THE", stringToColor(options->palette, "white")});
texts.push_back({"JAIL TO FINISH THEM", stringToColor(options->palette, "white")});
texts.push_back({"", stringToColor(options->palette, "white")});
texts.push_back({"", stringToColor(options->palette, "white")});
texts.push_back({"KEYS:", stringToColor(options->palette, "yellow")});
texts.push_back({"", stringToColor(options->palette, "white")});
texts.push_back({"B TO JUMP", stringToColor(options->palette, "white")});
texts.push_back({"R TO SWITCH THE MUSIC", stringToColor(options->palette, "white")});
texts.push_back({"L TO SWAP THE COLOR PALETTE", stringToColor(options->palette, "white")});
texts.push_back({"START TO PAUSE", stringToColor(options->palette, "white")});
texts.push_back({"SELECT TO EXIT", stringToColor(options->palette, "white")});
texts.push_back({"", stringToColor(options->palette, "white")});
texts.push_back({"", stringToColor(options->palette, "white")});
texts.push_back({"", stringToColor(options->palette, "white")});
texts.push_back({"A GAME BY JAILDESIGNER", stringToColor(options->palette, "yellow")});
texts.push_back({"MADE ON SUMMER/FALL 2022", stringToColor(options->palette, "yellow")});
texts.push_back({"", stringToColor(options->palette, "white")});
texts.push_back({"", stringToColor(options->palette, "white")});
texts.push_back({"I LOVE JAILGAMES! ", stringToColor(options->palette, "white")});
texts.push_back({"", stringToColor(options->palette, "white")});
#endif
}
// Escribe el texto en la textura
@@ -259,21 +283,24 @@ void Credits::updateCounter()
// Comprueba si ha terminado la sección
if (counter > 1200)
{
section.name = SECTION_PROG_DEMO;
section->name = SECTION_PROG_DEMO;
}
}
// Actualiza las variables
void Credits::update()
{
// Comprueba el manejador de eventos
checkEventHandler();
// Comprueba que la diferencia de ticks sea mayor a la velocidad del juego
if (SDL_GetTicks() - ticks > ticksSpeed)
{
// Actualiza el contador de ticks
ticks = SDL_GetTicks();
// Comprueba el manejador de eventos
checkEventHandler();
// Comprueba las entradas
checkInput();
// Actualiza el contador
updateCounter();
@@ -304,7 +331,7 @@ void Credits::render()
SDL_RenderCopy(renderer, textTexture, nullptr, nullptr);
// Dibuja la textura que cubre el texto
const int offset = std::min(counter / 8, 192 / 2);
const int offset = min(counter / 8, 192 / 2);
SDL_Rect srcRect = {0, 0, 256, 192 - (offset * 2)};
SDL_Rect dstRect = {0, offset * 2, 256, 192 - (offset * 2)};
SDL_RenderCopy(renderer, coverTexture, &srcRect, &dstRect);
@@ -318,15 +345,13 @@ void Credits::render()
}
// Bucle para el logo del juego
section_t Credits::run()
void Credits::run()
{
while (section.name == SECTION_PROG_CREDITS)
while (section->name == SECTION_PROG_CREDITS)
{
update();
render();
}
return section;
}
// Cambia la paleta

View File

@@ -1,28 +1,31 @@
#pragma once
#include <SDL2/SDL.h>
#include "common/animatedsprite.h"
#include "common/asset.h"
#include "common/jail_audio.h"
#include "common/resource.h"
#include "common/screen.h"
#include "common/sprite.h"
#include "common/text.h"
#include "common/texture.h"
#include "common/utils.h"
#include "jail_engine/animatedsprite.h"
#include "jail_engine/asset.h"
#include "jail_engine/input.h"
#include "jail_engine/jail_audio.h"
#include "jail_engine/resource.h"
#include "jail_engine/screen.h"
#include "jail_engine/sprite.h"
#include "jail_engine/text.h"
#include "jail_engine/texture.h"
#include "jail_engine/utils.h"
#include "const.h"
#include <vector>
#ifndef CREDITS_H
#define CREDITS_H
using namespace std;
class Credits
{
private:
struct captions_t
{
std::string label; // Texto a escribir
color_t color; // Color del texto
string label; // Texto a escribir
color_t color; // Color del texto
};
// Objetos y punteros
@@ -30,21 +33,22 @@ private:
Screen *screen; // Objeto encargado de dibujar en pantalla
Resource *resource; // Objeto con los recursos
Asset *asset; // Objeto con los ficheros de recursos
Input *input; // Objeto pata gestionar la entrada
SDL_Event *eventHandler; // Manejador de eventos
Text *text; // Objeto para escribir texto en pantalla
SDL_Texture *textTexture; // Textura para dibujar el texto
SDL_Texture *coverTexture; // Textura para cubrir el texto
AnimatedSprite *sprite; // Sprite para el brillo del corazón
options_t *options; // Puntero a las opciones del juego
section_t *section; // Estado del bucle principal para saber si continua o se sale
// Variables
int counter; // Contador
bool counterEnabled; // Indica si esta activo el contador
int subCounter; // Contador secundario
section_t section; // Estado del bucle principal para saber si continua o se sale
Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa
Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles del programa
std::vector<captions_t> texts; // Vector con los textos
int counter; // Contador
bool counterEnabled; // Indica si esta activo el contador
int subCounter; // Contador secundario
Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa
Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles del programa
vector<captions_t> texts; // Vector con los textos
// Actualiza las variables
void update();
@@ -55,6 +59,9 @@ private:
// Comprueba el manejador de eventos
void checkEventHandler();
// Comprueba las entradas
void checkInput();
// Actualiza el contador
void updateCounter();
@@ -69,13 +76,13 @@ private:
public:
// Constructor
Credits(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *asset, options_t *options);
Credits(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *asset, Input *input, options_t *options, section_t *section);
// Destructor
~Credits();
// Bucle principal
section_t run();
void run();
};
#endif

View File

@@ -1,7 +1,7 @@
#include "demo.h"
// Constructor
Demo::Demo(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *asset, options_t *options, Debug *debug)
Demo::Demo(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *asset, Input *input, options_t *options, section_t *section, Debug *debug)
{
// Inicia algunas variables
board.iniClock = SDL_GetTicks();
@@ -18,12 +18,14 @@ Demo::Demo(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *as
currentRoom = rooms[roomIndex];
// Copia los punteros
this->resource = resource;
this->renderer = renderer;
this->asset = asset;
this->screen = screen;
this->debug = debug;
this->resource = resource;
this->asset = asset;
this->input = input;
this->options = options;
this->section = section;
this->debug = debug;
// Crea los objetos
itemTracker = new ItemTracker();
@@ -44,8 +46,8 @@ Demo::Demo(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *as
board.music = true;
setScoreBoardColor();
section.name = SECTION_PROG_DEMO;
section.subsection = 0;
section->name = SECTION_PROG_DEMO;
section->subsection = 0;
}
Demo::~Demo()
@@ -67,86 +69,82 @@ void Demo::checkEventHandler()
// Evento de salida de la aplicación
if (eventHandler->type == SDL_QUIT)
{
section.name = SECTION_PROG_QUIT;
section->name = SECTION_PROG_QUIT;
screen->setBorderColor(stringToColor(options->palette, "black"));
break;
}
// Comprueba las teclas que se han pulsado
if ((eventHandler->type == SDL_KEYDOWN && eventHandler->key.repeat == 0) || (eventHandler->type == SDL_JOYBUTTONDOWN))
{
switch (eventHandler->key.keysym.scancode)
{
case SDL_SCANCODE_ESCAPE:
section.name = SECTION_PROG_QUIT;
break;
case SDL_SCANCODE_B:
screen->switchBorder();
reLoadTextures();
break;
case SDL_SCANCODE_F:
screen->switchVideoMode();
reLoadTextures();
break;
case SDL_SCANCODE_F1:
screen->setWindowSize(1);
reLoadTextures();
break;
case SDL_SCANCODE_F2:
screen->setWindowSize(2);
reLoadTextures();
break;
case SDL_SCANCODE_F3:
screen->setWindowSize(3);
reLoadTextures();
break;
case SDL_SCANCODE_F4:
screen->setWindowSize(4);
reLoadTextures();
break;
case SDL_SCANCODE_F5:
switchPalette();
break;
default:
section.name = SECTION_PROG_TITLE;
section.subsection = 0;
break;
}
}
}
}
// Bucle para el juego
section_t Demo::run()
// Comprueba las entradas
void Demo::checkInput()
{
while (section.name == SECTION_PROG_DEMO)
if (input->checkInput(input_exit, REPEAT_FALSE))
{
section->name = SECTION_PROG_QUIT;
}
else if (input->checkInput(input_toggle_border, REPEAT_FALSE))
{
screen->switchBorder();
reLoadTextures();
}
else if (input->checkInput(input_window_fullscreen, REPEAT_FALSE))
{
screen->switchVideoMode();
reLoadTextures();
}
else if (input->checkInput(input_window_dec_size, REPEAT_FALSE))
{
screen->decWindowSize();
reLoadTextures();
}
else if (input->checkInput(input_window_inc_size, REPEAT_FALSE))
{
screen->incWindowSize();
reLoadTextures();
}
else if (input->checkInput(input_swap_palette, REPEAT_FALSE))
{
switchPalette();
}
else if (input->checkInput(input_pause, REPEAT_FALSE) || input->checkInput(input_accept, REPEAT_FALSE) || input->checkInput(input_jump, REPEAT_FALSE))
{
section->name = SECTION_PROG_TITLE;
section->subsection = 0;
}
}
// Bucle para el juego
void Demo::run()
{
while (section->name == SECTION_PROG_DEMO)
{
update();
render();
}
return section;
}
// Actualiza el juego, las variables, comprueba la entrada, etc.
void Demo::update()
{
// Comprueba los eventos de la cola
checkEventHandler();
// Comprueba que la diferencia de ticks sea mayor a la velocidad del juego
if (SDL_GetTicks() - ticks > ticksSpeed)
{
// Actualiza el contador de ticks
ticks = SDL_GetTicks();
// Comprueba los eventos de la cola
checkEventHandler();
// Comprueba las entradas
checkInput();
// Actualiza los objetos
room->update();
@@ -194,7 +192,7 @@ void Demo::reLoadTextures()
{
if (options->console)
{
std::cout << "** RELOAD REQUESTED" << std::endl;
cout << "** RELOAD REQUESTED" << endl;
}
room->reLoadTexture();
scoreboard->reLoadTexture();
@@ -222,7 +220,7 @@ void Demo::switchPalette()
}
// Cambia de habitación
bool Demo::changeRoom(std::string file)
bool Demo::changeRoom(string file)
{
// En las habitaciones los limites tienen la cadena del fichero o un 0 en caso de no limitar con nada
if (file != "0")
@@ -255,8 +253,8 @@ void Demo::checkRoomChange()
roomIndex++;
if (roomIndex == (int)rooms.size())
{
section.name = SECTION_PROG_LOGO;
section.subsection = SUBSECTION_LOGO_TO_TITLE;
section->name = SECTION_PROG_LOGO;
section->subsection = SUBSECTION_LOGO_TO_TITLE;
}
else
{

View File

@@ -1,15 +1,16 @@
#pragma once
#include <SDL2/SDL.h>
#include "common/animatedsprite.h"
#include "common/asset.h"
#include "common/debug.h"
#include "common/input.h"
#include "common/resource.h"
#include "common/screen.h"
#include "common/sprite.h"
#include "common/text.h"
#include "common/utils.h"
#include "jail_engine/animatedsprite.h"
#include "jail_engine/asset.h"
#include "jail_engine/input.h"
#include "jail_engine/debug.h"
#include "jail_engine/input.h"
#include "jail_engine/resource.h"
#include "jail_engine/screen.h"
#include "jail_engine/sprite.h"
#include "jail_engine/text.h"
#include "jail_engine/utils.h"
#include "const.h"
#include "item_tracker.h"
#include "room_tracker.h"
@@ -19,6 +20,8 @@
#ifndef DEMO_H
#define DEMO_H
using namespace std;
class Demo
{
private:
@@ -29,22 +32,23 @@ private:
Room *room; // Objeto encargado de gestionar cada habitación del juego
Resource *resource; // Objeto con los recursos
Asset *asset; // Objeto con la ruta a todos los ficheros de recursos
Input *input; // Objeto pata gestionar la entrada
Text *text; // Objeto para los textos del juego
ScoreBoard *scoreboard; // Objeto encargado de gestionar el marcador
ItemTracker *itemTracker; // Lleva el control de los objetos recogidos
Debug *debug; // Objeto para gestionar la información de debug
options_t *options; // Puntero a las opciones del juego
section_t *section; // Seccion actual dentro del juego
// Variables
Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa
Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles del programa
section_t section; // Seccion actual dentro del juego
std::string currentRoom; // Fichero de la habitación actual
board_t board; // Estructura con los datos del marcador
int counter; // Contador para el modo demo
int roomTime; // Tiempo que se muestra cada habitacion
int roomIndex; // Indice para el vector de habitaciones
std::vector<std::string> rooms; // Listado con los mapas de la demo
Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa
Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles del programa
string currentRoom; // Fichero de la habitación actual
board_t board; // Estructura con los datos del marcador
int counter; // Contador para el modo demo
int roomTime; // Tiempo que se muestra cada habitacion
int roomIndex; // Indice para el vector de habitaciones
vector<string> rooms; // Listado con los mapas de la demo
// Actualiza el juego, las variables, comprueba la entrada, etc.
void update();
@@ -55,6 +59,9 @@ private:
// Comprueba los eventos de la cola
void checkEventHandler();
// Comprueba las entradas
void checkInput();
// Escribe el nombre de la pantalla
void renderRoomName();
@@ -65,7 +72,7 @@ private:
void switchPalette();
// Cambia de habitación
bool changeRoom(std::string file);
bool changeRoom(string file);
// Comprueba si se ha de cambiar de habitación
void checkRoomChange();
@@ -75,13 +82,13 @@ private:
public:
// Constructor
Demo(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *asset, options_t *options, Debug *debug);
Demo(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *asset, Input *input, options_t *options, section_t *section, Debug *debug);
// Destructor
~Demo();
// Bucle para el juego
section_t run();
void run();
};
#endif

View File

@@ -1,5 +1,5 @@
#include "common/jscore.h"
#include "common/utils.h"
#include "jail_engine/jscore.h"
#include "jail_engine/utils.h"
#include "director.h"
#include <errno.h>
#include <iostream>
@@ -14,11 +14,12 @@
// Constructor
Director::Director(int argc, char *argv[])
{
section.name = SECTION_PROG_LOGO;
section.subsection = SUBSECTION_LOGO_TO_INTRO;
section = new section_t();
section->name = SECTION_PROG_LOGO;
section->subsection = SUBSECTION_LOGO_TO_INTRO;
#ifdef DEBUG
section.name = SECTION_PROG_LOGO;
section->name = SECTION_PROG_INTRO;
#endif
// Crea e inicializa las opciones del programa
@@ -28,7 +29,12 @@ Director::Director(int argc, char *argv[])
checkProgramArguments(argc, argv);
// Crea la carpeta del sistema donde guardar datos
createSystemFolder();
createSystemFolder("jailgames");
#ifndef DEBUG
createSystemFolder("jailgames/jaildoctors_dilemma");
#else
createSystemFolder("jailgames/jaildoctors_dilemma_debug");
#endif
// Crea el objeto que controla los ficheros de recursos
asset = new Asset(executablePath);
@@ -65,6 +71,7 @@ Director::~Director()
saveConfig();
// Libera la memoria
delete section;
delete options;
delete asset;
delete input;
@@ -93,11 +100,11 @@ void Director::initOnline()
{ // Establece el servidor y el puerto
jscore::init(options->online.server, options->online.port);
const std::string caption = options->online.jailerID + " IS LOGGED IN";
const string caption = options->online.jailerID + " IS LOGGED IN";
screen->showNotification(caption);
if (options->console)
{
std::cout << caption << std::endl;
cout << caption << endl;
}
}
}
@@ -135,6 +142,9 @@ void Director::initOptions()
// Estos valores no se guardan en el fichero de configuraci´ón
options->console = false;
#ifdef DEBUG
options->console = true;
#endif
options->cheat.infiniteLives = false;
options->cheat.invincible = false;
options->cheat.jailEnabled = false;
@@ -148,7 +158,7 @@ void Director::initOptions()
options->online.server = "jaildoctor.duckdns.org";
options->online.port = 9911;
#ifdef DEBUG
options->online.gameID = "jaildoctors_dilemma_test";
options->online.gameID = "jaildoctors_dilemma_debug";
#else
options->online.gameID = "jaildoctors_dilemma";
#endif
@@ -158,7 +168,7 @@ void Director::initOptions()
options->notifications.posV = pos_top;
options->notifications.posH = pos_left;
options->notifications.sound = true;
options->notifications.color = {64, 64, 64};
options->notifications.color = {48, 48, 48};
}
// Comprueba los parametros del programa
@@ -204,12 +214,12 @@ bool Director::loadConfig()
bool success = true;
// Versión actual del fichero
const std::string configVersion = options->configVersion;
const string configVersion = options->configVersion;
options->configVersion = "";
// Variables para manejar el fichero
std::string line;
std::ifstream file(asset->get("config.txt"));
string line;
ifstream file(asset->get("config.txt"));
// Si el fichero se puede abrir
if (file.good())
@@ -217,9 +227,9 @@ bool Director::loadConfig()
// Procesa el fichero linea a linea
if (options->console)
{
std::cout << "Reading file config.txt\n";
cout << "Reading file config.txt\n";
}
while (std::getline(file, line))
while (getline(file, line))
{
// Comprueba que la linea no sea un comentario
if (line.substr(0, 1) != "#")
@@ -231,8 +241,8 @@ bool Director::loadConfig()
{
if (options->console)
{
std::cout << "Warning: file config.txt\n";
std::cout << "unknown parameter " << line.substr(0, pos).c_str() << std::endl;
cout << "Warning: file config.txt\n";
cout << "unknown parameter " << line.substr(0, pos).c_str() << endl;
}
success = false;
}
@@ -242,7 +252,7 @@ bool Director::loadConfig()
// Cierra el fichero
if (options->console)
{
std::cout << "Closing file config.txt\n\n";
cout << "Closing file config.txt\n\n";
}
file.close();
}
@@ -297,20 +307,20 @@ bool Director::saveConfig()
bool success = true;
// Crea y abre el fichero de texto
std::ofstream file(asset->get("config.txt"));
ofstream file(asset->get("config.txt"));
if (file.good())
{
if (options->console)
{
std::cout << asset->get("config.txt") << " open for writing" << std::endl;
cout << asset->get("config.txt") << " open for writing" << endl;
}
}
else
{
if (options->console)
{
std::cout << asset->get("config.txt") << " can't be opened" << std::endl;
cout << asset->get("config.txt") << " can't be opened" << endl;
}
}
@@ -349,7 +359,7 @@ bool Director::saveConfig()
file << "videoMode=SDL_WINDOW_FULLSCREEN_DESKTOP\n";
}
file << "windowSize=" + std::to_string(options->windowSize) + "\n";
file << "windowSize=" + to_string(options->windowSize) + "\n";
if (options->filter == FILTER_NEAREST)
{
@@ -364,14 +374,14 @@ bool Director::saveConfig()
file << "integerScale=" + boolToString(options->integerScale) + "\n";
file << "keepAspect=" + boolToString(options->keepAspect) + "\n";
file << "borderEnabled=" + boolToString(options->borderEnabled) + "\n";
file << "borderWidth=" + std::to_string(options->borderWidth) + "\n";
file << "borderHeight=" + std::to_string(options->borderHeight) + "\n";
file << "palette=" + std::to_string(options->palette) + "\n";
file << "borderWidth=" + to_string(options->borderWidth) + "\n";
file << "borderHeight=" + to_string(options->borderHeight) + "\n";
file << "palette=" + to_string(options->palette) + "\n";
file << "\n## ONLINE OPTIONS\n";
file << "enabled=" + boolToString(options->online.enabled) + "\n";
file << "server=" + options->online.server + "\n";
file << "port=" + std::to_string(options->online.port) + "\n";
file << "port=" + to_string(options->online.port) + "\n";
file << "jailerID=" + options->online.jailerID + "\n";
file << "\n## NOTIFICATION OPTIONS\n";
@@ -408,24 +418,18 @@ bool Director::saveConfig()
}
// Crea la carpeta del sistema donde guardar datos
void Director::createSystemFolder()
void Director::createSystemFolder(string folder)
{
#ifdef DEBUG
const std::string folderName = "jaildoctors_dilemma_debug";
#else
const std::string folderName = "jaildoctors_dilemma";
#endif
#ifdef _WIN32
systemFolder = std::string(getenv("APPDATA")) + "/" + folderName;
systemFolder = string(getenv("APPDATA")) + "/" + folder;
#elif __APPLE__
struct passwd *pw = getpwuid(getuid());
const char *homedir = pw->pw_dir;
systemFolder = std::string(homedir) + "/Library/Application Support/" + folderName;
systemFolder = string(homedir) + "/Library/Application Support" + "/" + folder;
#elif __linux__
struct passwd *pw = getpwuid(getuid());
const char *homedir = pw->pw_dir;
systemFolder = std::string(homedir) + "/." + folderName;
systemFolder = string(homedir) + "/." + folder;
#endif
struct stat st = {0};
@@ -463,25 +467,25 @@ void Director::createSystemFolder()
}
// Carga los recursos
void Director::loadResources(section_t section)
void Director::loadResources(section_t *section)
{
if (options->console)
{
std::cout << "** LOAD RESOURCES" << std::endl;
cout << "** LOAD RESOURCES" << endl;
}
if (section.name == SECTION_PROG_LOGO)
if (section->name == SECTION_PROG_LOGO)
{
std::vector<std::string> textureList;
vector<string> textureList;
textureList.push_back("jailgames.png");
textureList.push_back("since_1998.png");
resource->loadTextures(textureList);
}
else if (section.name == SECTION_PROG_INTRO)
else if (section->name == SECTION_PROG_INTRO)
{
std::vector<std::string> textureList;
vector<string> textureList;
textureList.push_back("loading_screen_bn.png");
textureList.push_back("loading_screen_color.png");
textureList.push_back("loading_screen_bn_zxarne.png");
@@ -490,48 +494,51 @@ void Director::loadResources(section_t section)
resource->loadTextures(textureList);
}
else if (section.name == SECTION_PROG_TITLE)
else if (section->name == SECTION_PROG_TITLE)
{
std::vector<std::string> textureList;
vector<string> textureList;
textureList.push_back("loading_screen_color.png");
textureList.push_back("loading_screen_color_zxarne.png");
textureList.push_back("smb2.png");
textureList.push_back("debug.png");
textureList.push_back("notify.png");
resource->loadTextures(textureList);
// Offsets
std::vector<std::string> offsetsList;
vector<string> offsetsList;
offsetsList.push_back("smb2.txt");
offsetsList.push_back("debug.txt");
resource->loadOffsets(offsetsList);
}
else if (section.name == SECTION_PROG_CREDITS)
else if (section->name == SECTION_PROG_CREDITS)
{
// Texturas
std::vector<std::string> textureList;
vector<string> textureList;
textureList.push_back("shine.png");
textureList.push_back("smb2.png");
resource->loadTextures(textureList);
// Animaciones
std::vector<std::string> animationList;
vector<string> animationList;
animationList.push_back("shine.ani");
resource->loadAnimations(animationList);
// Offsets
std::vector<std::string> offsetsList;
vector<string> offsetsList;
offsetsList.push_back("smb2.txt");
resource->loadOffsets(offsetsList);
}
else if (section.name == SECTION_PROG_ENDING)
else if (section->name == SECTION_PROG_ENDING)
{
// Texturas
std::vector<std::string> textureList;
vector<string> textureList;
textureList.push_back("ending1.png");
textureList.push_back("ending1_zxarne.png");
textureList.push_back("ending2.png");
@@ -547,16 +554,16 @@ void Director::loadResources(section_t section)
resource->loadTextures(textureList);
// Offsets
std::vector<std::string> offsetsList;
vector<string> offsetsList;
offsetsList.push_back("smb2.txt");
resource->loadOffsets(offsetsList);
}
else if (section.name == SECTION_PROG_ENDING2)
else if (section->name == SECTION_PROG_ENDING2)
{
// Texturas
std::vector<std::string> textureList;
vector<string> textureList;
// Texto
textureList.push_back("smb2.png");
@@ -622,7 +629,7 @@ void Director::loadResources(section_t section)
resource->loadTextures(textureList);
// Animaciones
std::vector<std::string> animationList;
vector<string> animationList;
// Enemigos
animationList.push_back("abad.ani");
@@ -685,16 +692,16 @@ void Director::loadResources(section_t section)
resource->loadAnimations(animationList);
// Offsets
std::vector<std::string> offsetsList;
vector<string> offsetsList;
offsetsList.push_back("smb2.txt");
resource->loadOffsets(offsetsList);
}
else if (section.name == SECTION_PROG_GAME_OVER)
else if (section->name == SECTION_PROG_GAME_OVER)
{
// Texturas
std::vector<std::string> textureList;
vector<string> textureList;
textureList.push_back("smb2.png");
textureList.push_back("player_game_over.png");
textureList.push_back("tv.png");
@@ -702,23 +709,23 @@ void Director::loadResources(section_t section)
resource->loadTextures(textureList);
// Animaciones
std::vector<std::string> animationList;
vector<string> animationList;
animationList.push_back("player_game_over.ani");
animationList.push_back("tv.ani");
resource->loadAnimations(animationList);
// Offsets
std::vector<std::string> offsetsList;
vector<string> offsetsList;
offsetsList.push_back("smb2.txt");
resource->loadOffsets(offsetsList);
}
else if (section.name == SECTION_PROG_GAME || section.name == SECTION_PROG_DEMO)
else if (section->name == SECTION_PROG_GAME || section->name == SECTION_PROG_DEMO)
{
// Texturas
std::vector<std::string> textureList;
vector<string> textureList;
// Jugador
if (options->cheat.altSkin)
@@ -803,7 +810,7 @@ void Director::loadResources(section_t section)
resource->loadTextures(textureList);
// Animaciones
std::vector<std::string> animationList;
vector<string> animationList;
// Jugador
if (options->cheat.altSkin)
@@ -877,14 +884,14 @@ void Director::loadResources(section_t section)
resource->loadAnimations(animationList);
// Offsets
std::vector<std::string> offsetsList;
vector<string> offsetsList;
offsetsList.push_back("smb2.txt");
offsetsList.push_back("debug.txt");
resource->loadOffsets(offsetsList);
// TileMaps
std::vector<std::string> tileMapList;
vector<string> tileMapList;
tileMapList.push_back("01.tmx");
tileMapList.push_back("02.tmx");
tileMapList.push_back("03.tmx");
@@ -949,7 +956,7 @@ void Director::loadResources(section_t section)
resource->loadTileMaps(tileMapList);
// Habitaciones
std::vector<std::string> roomList;
vector<string> roomList;
roomList.push_back("01.room");
roomList.push_back("02.room");
roomList.push_back("03.room");
@@ -1016,12 +1023,12 @@ void Director::loadResources(section_t section)
if (options->console)
{
std::cout << "** RESOURCES LOADED" << std::endl;
cout << "** RESOURCES LOADED" << endl;
}
}
// Asigna variables a partir de dos cadenas
bool Director::setOptions(options_t *options, std::string var, std::string value)
bool Director::setOptions(options_t *options, string var, string value)
{
// Indicador de éxito en la asignación
bool success = true;
@@ -1065,7 +1072,7 @@ bool Director::setOptions(options_t *options, std::string var, std::string value
else if (var == "windowSize")
{
options->windowSize = std::stoi(value);
options->windowSize = stoi(value);
if ((options->windowSize < 1) || (options->windowSize > 4))
{
options->windowSize = 3;
@@ -1106,17 +1113,17 @@ bool Director::setOptions(options_t *options, std::string var, std::string value
else if (var == "borderWidth")
{
options->borderWidth = std::stoi(value);
options->borderWidth = stoi(value);
}
else if (var == "borderHeight")
{
options->borderHeight = std::stoi(value);
options->borderHeight = stoi(value);
}
else if (var == "palette")
{
const int pal = std::stoi(value);
const int pal = stoi(value);
if (pal == 0)
{
@@ -1145,7 +1152,7 @@ bool Director::setOptions(options_t *options, std::string var, std::string value
{
value = "0";
}
options->online.port = std::stoi(value);
options->online.port = stoi(value);
}
else if (var == "jailerID")
@@ -1207,43 +1214,62 @@ void Director::initInput()
// Busca si hay un mando conectado
input->discoverGameController();
// Asigna inputs a teclas
// Teclado - Movimiento
if (options->keys == ctrl_cursor)
{
input->bindKey(INPUT_UP, SDL_SCANCODE_UP);
input->bindKey(INPUT_LEFT, SDL_SCANCODE_LEFT);
input->bindKey(INPUT_RIGHT, SDL_SCANCODE_RIGHT);
input->bindKey(input_jump, SDL_SCANCODE_UP);
input->bindKey(input_left, SDL_SCANCODE_LEFT);
input->bindKey(input_right, SDL_SCANCODE_RIGHT);
input->bindKey(input_up, SDL_SCANCODE_UP);
input->bindKey(input_down, SDL_SCANCODE_DOWN);
}
else if (options->keys == ctrl_opqa)
{
input->bindKey(INPUT_UP, SDL_SCANCODE_Q);
input->bindKey(INPUT_LEFT, SDL_SCANCODE_O);
input->bindKey(INPUT_RIGHT, SDL_SCANCODE_P);
input->bindKey(input_jump, SDL_SCANCODE_Q);
input->bindKey(input_left, SDL_SCANCODE_O);
input->bindKey(input_right, SDL_SCANCODE_P);
input->bindKey(input_up, SDL_SCANCODE_Q);
input->bindKey(input_down, SDL_SCANCODE_A);
}
else if (options->keys == ctrl_wasd)
{
input->bindKey(INPUT_UP, SDL_SCANCODE_W);
input->bindKey(INPUT_LEFT, SDL_SCANCODE_A);
input->bindKey(INPUT_RIGHT, SDL_SCANCODE_D);
input->bindKey(input_jump, SDL_SCANCODE_W);
input->bindKey(input_left, SDL_SCANCODE_A);
input->bindKey(input_right, SDL_SCANCODE_D);
input->bindKey(input_up, SDL_SCANCODE_W);
input->bindKey(input_down, SDL_SCANCODE_S);
}
input->bindKey(INPUT_DOWN, SDL_SCANCODE_DOWN);
input->bindKey(INPUT_ACCEPT, SDL_SCANCODE_RETURN);
input->bindKey(INPUT_CANCEL, SDL_SCANCODE_ESCAPE);
input->bindKey(INPUT_BUTTON_1, SDL_SCANCODE_SPACE);
input->bindKey(INPUT_BUTTON_2, SDL_SCANCODE_D);
input->bindKey(INPUT_BUTTON_PAUSE, SDL_SCANCODE_ESCAPE);
input->bindKey(INPUT_BUTTON_ESCAPE, SDL_SCANCODE_ESCAPE);
// Teclado - Otros
input->bindKey(input_accept, SDL_SCANCODE_RETURN);
input->bindKey(input_cancel, SDL_SCANCODE_ESCAPE);
input->bindKey(input_pause, SDL_SCANCODE_H);
input->bindKey(input_exit, SDL_SCANCODE_ESCAPE);
input->bindKey(input_window_dec_size, SDL_SCANCODE_F1);
input->bindKey(input_window_inc_size, SDL_SCANCODE_F2);
input->bindKey(input_window_fullscreen, SDL_SCANCODE_F3);
input->bindKey(input_swap_palette, SDL_SCANCODE_F5);
input->bindKey(input_switch_music, SDL_SCANCODE_M);
input->bindKey(input_toggle_border, SDL_SCANCODE_B);
input->bindGameControllerButton(INPUT_UP, SDL_CONTROLLER_BUTTON_B);
input->bindGameControllerButton(INPUT_DOWN, SDL_CONTROLLER_BUTTON_DPAD_DOWN);
input->bindGameControllerButton(INPUT_LEFT, SDL_CONTROLLER_BUTTON_DPAD_LEFT);
input->bindGameControllerButton(INPUT_RIGHT, SDL_CONTROLLER_BUTTON_DPAD_RIGHT);
input->bindGameControllerButton(INPUT_ACCEPT, SDL_CONTROLLER_BUTTON_B);
input->bindGameControllerButton(INPUT_CANCEL, SDL_CONTROLLER_BUTTON_A);
input->bindGameControllerButton(INPUT_BUTTON_1, SDL_CONTROLLER_BUTTON_B);
input->bindGameControllerButton(INPUT_BUTTON_PAUSE, SDL_CONTROLLER_BUTTON_START);
input->bindGameControllerButton(INPUT_BUTTON_ESCAPE, SDL_CONTROLLER_BUTTON_GUIDE);
// Mando - Movimiento
input->bindGameControllerButton(input_jump, SDL_CONTROLLER_BUTTON_B);
input->bindGameControllerButton(input_left, SDL_CONTROLLER_BUTTON_DPAD_LEFT);
input->bindGameControllerButton(input_right, SDL_CONTROLLER_BUTTON_DPAD_RIGHT);
// Mando - Otros
input->bindGameControllerButton(input_accept, SDL_CONTROLLER_BUTTON_B);
input->bindGameControllerButton(input_cancel, SDL_CONTROLLER_BUTTON_A);
#ifdef GAME_CONSOLE
input->bindGameControllerButton(input_pause, SDL_CONTROLLER_BUTTON_BACK);
input->bindGameControllerButton(input_exit, SDL_CONTROLLER_BUTTON_START);
#else
input->bindGameControllerButton(input_pause, SDL_CONTROLLER_BUTTON_START);
input->bindGameControllerButton(input_exit, SDL_CONTROLLER_BUTTON_BACK);
#endif
input->bindGameControllerButton(input_swap_palette, SDL_CONTROLLER_BUTTON_LEFTSHOULDER);
input->bindGameControllerButton(input_switch_music, SDL_CONTROLLER_BUTTON_RIGHTSHOULDER);
input->bindGameControllerButton(input_toggle_border, SDL_CONTROLLER_BUTTON_X);
}
// Inicializa JailAudio
@@ -1263,21 +1289,21 @@ bool Director::initSDL()
{
if (options->console)
{
std::cout << "SDL could not initialize!\nSDL Error: " << SDL_GetError() << std::endl;
cout << "SDL could not initialize!\nSDL Error: " << SDL_GetError() << endl;
}
success = false;
}
else
{
// Inicia el generador de numeros aleatorios
std::srand(static_cast<unsigned int>(SDL_GetTicks()));
srand(static_cast<unsigned int>(SDL_GetTicks()));
// Establece el filtro de la textura a nearest
if (!SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, std::to_string(options->filter).c_str()))
if (!SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, to_string(options->filter).c_str()))
{
if (options->console)
{
std::cout << "Warning: Nearest texture filtering not enabled!\n";
cout << "Warning: Nearest texture filtering not enabled!\n";
}
}
@@ -1295,7 +1321,7 @@ bool Director::initSDL()
{
if (options->console)
{
std::cout << "Window could not be created!\nSDL Error: " << SDL_GetError() << std::endl;
cout << "Window could not be created!\nSDL Error: " << SDL_GetError() << endl;
}
success = false;
}
@@ -1315,7 +1341,7 @@ bool Director::initSDL()
{
if (options->console)
{
std::cout << "Renderer could not be created!\nSDL Error: " << SDL_GetError() << std::endl;
cout << "Renderer could not be created!\nSDL Error: " << SDL_GetError() << endl;
}
success = false;
}
@@ -1335,7 +1361,7 @@ bool Director::initSDL()
if (options->console)
{
std::cout << std::endl;
cout << endl;
}
return success;
}
@@ -1344,9 +1370,9 @@ bool Director::initSDL()
bool Director::setFileList()
{
#ifdef MACOS_BUNDLE
const std::string prefix = "/../Resources";
const string prefix = "/../Resources";
#else
const std::string prefix = "";
const string prefix = "";
#endif
// Texto
@@ -1362,6 +1388,10 @@ bool Director::setFileList()
asset->add(systemFolder + "/config.txt", t_data, false, true);
asset->add(systemFolder + "/stats_buffer.csv", t_data, false, true);
asset->add(systemFolder + "/stats.csv", t_data, false, true);
asset->add(systemFolder + "/cheevos.bin", t_data, false, true);
// Notificaciones
asset->add(prefix + "/data/notifications/notify.png", t_bitmap);
// Habitaciones
asset->add(prefix + "/data/room/01.room", t_room);
@@ -1686,34 +1716,16 @@ bool Director::setFileList()
return asset->check();
}
// Obtiene el valor de la variable
Uint8 Director::getSubsection()
{
return section.subsection;
}
// Obtiene el valor de la variable
Uint8 Director::getSection()
{
return section.name;
}
// Establece el valor de la variable
void Director::setSection(section_t section)
{
this->section = section;
}
// Ejecuta la seccion de juego con el logo
void Director::runLogo()
{
if (options->console)
{
std::cout << "\n* SECTION: LOGO" << std::endl;
cout << "\n* SECTION: LOGO" << endl;
}
loadResources(section);
logo = new Logo(renderer, screen, resource, asset, options, section.subsection);
setSection(logo->run());
logo = new Logo(renderer, screen, resource, asset, input, options, section);
logo->run();
delete logo;
resource->free();
}
@@ -1723,11 +1735,11 @@ void Director::runIntro()
{
if (options->console)
{
std::cout << "\n* SECTION: INTRO" << std::endl;
cout << "\n* SECTION: INTRO" << endl;
}
loadResources(section);
intro = new Intro(renderer, screen, resource, asset, options);
setSection(intro->run());
intro = new Intro(renderer, screen, resource, asset, input, options, section);
intro->run();
delete intro;
resource->free();
}
@@ -1737,15 +1749,15 @@ void Director::runTitle()
{
if (options->console)
{
std::cout << "\n* SECTION: TITLE" << std::endl;
cout << "\n* SECTION: TITLE" << endl;
}
if ((JA_GetMusicState() == JA_MUSIC_INVALID) || (JA_GetMusicState() == JA_MUSIC_STOPPED))
{
JA_PlayMusic(music);
}
loadResources(section);
title = new Title(renderer, screen, resource, asset, options);
setSection(title->run());
title = new Title(renderer, screen, resource, asset, input, options, section);
title->run();
delete title;
resource->free();
}
@@ -1755,11 +1767,11 @@ void Director::runCredits()
{
if (options->console)
{
std::cout << "\n* SECTION: CREDITS" << std::endl;
cout << "\n* SECTION: CREDITS" << endl;
}
loadResources(section);
credits = new Credits(renderer, screen, resource, asset, options);
setSection(credits->run());
credits = new Credits(renderer, screen, resource, asset, input, options, section);
credits->run();
delete credits;
resource->free();
}
@@ -1769,11 +1781,11 @@ void Director::runDemo()
{
if (options->console)
{
std::cout << "\n* SECTION: DEMO" << std::endl;
cout << "\n* SECTION: DEMO" << endl;
}
loadResources(section);
demo = new Demo(renderer, screen, resource, asset, options, debug);
setSection(demo->run());
demo = new Demo(renderer, screen, resource, asset, input, options, section, debug);
demo->run();
delete demo;
resource->free();
}
@@ -1783,11 +1795,11 @@ void Director::runEnterID()
{
if (options->console)
{
std::cout << "\n* SECTION: ENTER_ID" << std::endl;
cout << "\n* SECTION: ENTER_ID" << endl;
}
// loadResources(section);
enterID = new EnterID(renderer, screen, asset, options, section);
setSection(enterID->run());
enterID->run();
delete enterID;
resource->free();
}
@@ -1797,11 +1809,11 @@ void Director::runEnding()
{
if (options->console)
{
std::cout << "\n* SECTION: ENDING" << std::endl;
cout << "\n* SECTION: ENDING" << endl;
}
loadResources(section);
ending = new Ending(renderer, screen, resource, asset, options);
setSection(ending->run());
ending = new Ending(renderer, screen, resource, asset, input, options, section);
ending->run();
delete ending;
resource->free();
}
@@ -1811,11 +1823,11 @@ void Director::runEnding2()
{
if (options->console)
{
std::cout << "\n* SECTION: ENDING2" << std::endl;
cout << "\n* SECTION: ENDING2" << endl;
}
loadResources(section);
ending2 = new Ending2(renderer, screen, resource, asset, options);
setSection(ending2->run());
ending2 = new Ending2(renderer, screen, resource, asset, input, options, section);
ending2->run();
delete ending2;
resource->free();
}
@@ -1825,11 +1837,11 @@ void Director::runGameOver()
{
if (options->console)
{
std::cout << "\n* SECTION: GAME OVER" << std::endl;
cout << "\n* SECTION: GAME OVER" << endl;
}
loadResources(section);
gameOver = new GameOver(renderer, screen, resource, asset, options);
setSection(gameOver->run());
gameOver = new GameOver(renderer, screen, resource, asset, input, options, section);
gameOver->run();
delete gameOver;
resource->free();
}
@@ -1839,12 +1851,12 @@ void Director::runGame()
{
if (options->console)
{
std::cout << "\n* SECTION: GAME" << std::endl;
cout << "\n* SECTION: GAME" << endl;
}
JA_StopMusic();
loadResources(section);
game = new Game(renderer, screen, resource, asset, options, input, debug);
setSection(game->run());
game = new Game(renderer, screen, resource, asset, options, input, section, debug);
game->run();
delete game;
resource->free();
}
@@ -1852,9 +1864,9 @@ void Director::runGame()
void Director::run()
{
// Bucle principal
while (getSection() != SECTION_PROG_QUIT)
while (section->name != SECTION_PROG_QUIT)
{
switch (getSection())
switch (section->name)
{
case SECTION_PROG_LOGO:
runLogo();

View File

@@ -1,14 +1,14 @@
#pragma once
#include <SDL2/SDL.h>
#include "common/asset.h"
#include "common/debug.h"
#include "common/input.h"
#include "common/jail_audio.h"
#include "common/movingsprite.h"
#include "common/resource.h"
#include "common/sprite.h"
#include "common/text.h"
#include "common/utils.h"
#include "jail_engine/asset.h"
#include "jail_engine/debug.h"
#include "jail_engine/input.h"
#include "jail_engine/jail_audio.h"
#include "jail_engine/movingsprite.h"
#include "jail_engine/resource.h"
#include "jail_engine/sprite.h"
#include "jail_engine/text.h"
#include "jail_engine/utils.h"
#include "const.h"
#include "credits.h"
#include "demo.h"
@@ -24,6 +24,8 @@
#ifndef DIRECTOR_H
#define DIRECTOR_H
using namespace std;
class Director
{
private:
@@ -46,12 +48,12 @@ private:
GameOver *gameOver; // Objeto para gestionar el final de la partida
Debug *debug; // Objeto para getsionar la información de debug
struct options_t *options; // Variable con todas las opciones del programa
section_t *section; // Sección y subsección actual del programa;
// Variables
section_t section; // Sección y subsección actual del programa;
JA_Music_t* music; // Musica del titulo
std::string executablePath; // Path del ejecutable
std::string systemFolder; // Carpeta del sistema donde guardar datos
JA_Music_t *music; // Musica del titulo
string executablePath; // Path del ejecutable
string systemFolder; // Carpeta del sistema donde guardar datos
// Crea e inicializa las opciones del programa
void initOptions();
@@ -69,13 +71,13 @@ private:
bool saveConfig();
// Crea la carpeta del sistema donde guardar datos
void createSystemFolder();
void createSystemFolder(string folder);
// Carga los recursos
void loadResources(section_t section);
void loadResources(section_t *section);
// Asigna variables a partir de dos cadenas
bool setOptions(options_t *options, std::string var, std::string value);
bool setOptions(options_t *options, string var, string value);
// Inicializa jail_audio
void initJailAudio();
@@ -89,15 +91,6 @@ private:
// Crea el indice de ficheros
bool setFileList();
// Obtiene el valor de la variable
Uint8 getSubsection();
// Obtiene el valor de la variable
Uint8 getSection();
// Establece el valor de la variable
void setSection(section_t section);
// Ejecuta la seccion de juego con el logo
void runLogo();

View File

@@ -1,14 +1,16 @@
#include "ending.h"
// Constructor
Ending::Ending(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *asset, options_t *options)
Ending::Ending(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *asset, Input *input, options_t *options, section_t *section)
{
// Copia los punteros
this->renderer = renderer;
this->screen = screen;
this->resource = resource;
this->asset = asset;
this->input = input;
this->options = options;
this->section = section;
// Reserva memoria para los punteros a objetos
eventHandler = new SDL_Event();
@@ -19,8 +21,8 @@ Ending::Ending(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset
counter = -1;
preCounter = 0;
coverCounter = 0;
section.name = SECTION_PROG_ENDING;
section.subsection = 0;
section->name = SECTION_PROG_ENDING;
section->subsection = 0;
ticks = 0;
ticksSpeed = 15;
scene = 0;
@@ -43,7 +45,7 @@ Ending::Ending(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset
{
if (options->console)
{
std::cout << "Error: canvasTexture could not be created!\nSDL Error: " << SDL_GetError() << std::endl;
cout << "Error: canvasTexture could not be created!\nSDL Error: " << SDL_GetError() << endl;
}
}
SDL_SetTextureBlendMode(coverTexture, SDL_BLENDMODE_BLEND);
@@ -83,14 +85,17 @@ Ending::~Ending()
// Actualiza el objeto
void Ending::update()
{
// Comprueba el manejador de eventos
checkEventHandler();
// Comprueba que la diferencia de ticks sea mayor a la velocidad del juego
if (SDL_GetTicks() - ticks > ticksSpeed)
{
// Actualiza el contador de ticks
ticks = SDL_GetTicks();
// Comprueba el manejador de eventos
checkEventHandler();
// Comprueba las entradas
checkInput();
// Actualiza el contador
updateCounters();
@@ -135,7 +140,7 @@ void Ending::render()
// Dibuja la cortinilla de cambio de escena
renderCoverTexture();
// text->write(0, 0, std::to_string(counter));
// text->write(0, 0, to_string(counter));
// Vuelca el contenido del renderizador en pantalla
screen->blit();
@@ -150,57 +155,45 @@ void Ending::checkEventHandler()
// Evento de salida de la aplicación
if (eventHandler->type == SDL_QUIT)
{
section.name = SECTION_PROG_QUIT;
section->name = SECTION_PROG_QUIT;
break;
}
}
}
// Comprueba las teclas que se han pulsado
if ((eventHandler->type == SDL_KEYDOWN && eventHandler->key.repeat == 0) || (eventHandler->type == SDL_JOYBUTTONDOWN))
{
switch (eventHandler->key.keysym.scancode)
{
case SDL_SCANCODE_ESCAPE:
section.name = SECTION_PROG_QUIT;
break;
// Comprueba las entradas
void Ending::checkInput()
{
case SDL_SCANCODE_B:
screen->switchBorder();
resource->reLoadTextures();
break;
if (input->checkInput(input_exit, REPEAT_FALSE))
{
section->name = SECTION_PROG_LOGO;
section->subsection = SUBSECTION_LOGO_TO_INTRO;
}
case SDL_SCANCODE_F:
screen->switchVideoMode();
resource->reLoadTextures();
break;
else if (input->checkInput(input_toggle_border, REPEAT_FALSE))
{
screen->switchBorder();
}
case SDL_SCANCODE_F1:
screen->setWindowSize(1);
resource->reLoadTextures();
break;
else if (input->checkInput(input_window_fullscreen, REPEAT_FALSE))
{
screen->switchVideoMode();
}
case SDL_SCANCODE_F2:
screen->setWindowSize(2);
resource->reLoadTextures();
break;
else if (input->checkInput(input_window_dec_size, REPEAT_FALSE))
{
screen->decWindowSize();
}
case SDL_SCANCODE_F3:
screen->setWindowSize(3);
resource->reLoadTextures();
break;
else if (input->checkInput(input_window_inc_size, REPEAT_FALSE))
{
screen->incWindowSize();
}
case SDL_SCANCODE_F4:
screen->setWindowSize(4);
resource->reLoadTextures();
break;
case SDL_SCANCODE_F5:
switchPalette();
break;
default:
break;
}
}
else if (input->checkInput(input_swap_palette, REPEAT_FALSE))
{
switchPalette();
}
}
@@ -208,7 +201,7 @@ void Ending::checkEventHandler()
void Ending::iniTexts()
{
// Vector con los textos
std::vector<textAndPos_t> texts;
vector<textAndPos_t> texts;
// Escena #0
texts.push_back({"HE FINALLY MANAGED", 32});
@@ -314,7 +307,7 @@ void Ending::iniTexts()
void Ending::iniPics()
{
// Vector con las rutas y la posición
std::vector<textAndPos_t> pics;
vector<textAndPos_t> pics;
if (options->palette == p_zxspectrum)
{
@@ -482,11 +475,11 @@ void Ending::iniScenes()
}
// Bucle principal
section_t Ending::run()
void Ending::run()
{
JA_PlayMusic(music);
while (section.name == SECTION_PROG_ENDING)
while (section->name == SECTION_PROG_ENDING)
{
update();
render();
@@ -494,8 +487,6 @@ section_t Ending::run()
JA_StopMusic();
JA_SetVolume(128);
return section;
}
// Actualiza los contadores
@@ -571,7 +562,7 @@ void Ending::checkChangeScene()
if (scene == 5)
{
// Termina el bucle
section.name = SECTION_PROG_ENDING2;
section->name = SECTION_PROG_ENDING2;
// Mantiene los valores anteriores
scene = 4;
@@ -614,7 +605,7 @@ void Ending::renderCoverTexture()
{
if (coverCounter > 0)
{ // Dibuja la textura que cubre el texto
const int offset = std::min(coverCounter, 100);
const int offset = min(coverCounter, 100);
SDL_Rect srcRect = {0, 200 - (coverCounter * 2), 256, offset * 2};
SDL_Rect dstRect = {0, 0, 256, offset * 2};
SDL_RenderCopy(renderer, coverTexture, &srcRect, &dstRect);

View File

@@ -1,14 +1,15 @@
#pragma once
#include <SDL2/SDL.h>
#include "common/asset.h"
#include "common/jail_audio.h"
#include "common/resource.h"
#include "common/screen.h"
#include "common/sprite.h"
#include "common/sprite.h"
#include "common/text.h"
#include "common/texture.h"
#include "common/utils.h"
#include "jail_engine/asset.h"
#include "jail_engine/input.h"
#include "jail_engine/jail_audio.h"
#include "jail_engine/resource.h"
#include "jail_engine/screen.h"
#include "jail_engine/sprite.h"
#include "jail_engine/sprite.h"
#include "jail_engine/text.h"
#include "jail_engine/texture.h"
#include "jail_engine/utils.h"
#include "const.h"
#include <string>
#include <vector>
@@ -16,6 +17,8 @@
#ifndef ENDING_H
#define ENDING_H
using namespace std;
class Ending
{
private:
@@ -32,8 +35,8 @@ private:
struct textAndPos_t // Estructura con un texto y su posición en el eje Y
{
std::string caption; // Texto
int pos; // Posición
string caption; // Texto
int pos; // Posición
};
struct asdhk
@@ -44,9 +47,9 @@ private:
struct scene_t // Estructura para crear cada una de las escenas del final
{
std::vector<asdhk> textIndex; // Indices del vector de textos a mostrar y su disparador
int pictureIndex; // Indice del vector de imagenes a mostrar
int counterEnd; // Valor del contador en el que finaliza la escena
vector<asdhk> textIndex; // Indices del vector de textos a mostrar y su disparador
int pictureIndex; // Indice del vector de imagenes a mostrar
int counterEnd; // Valor del contador en el que finaliza la escena
};
// Objetos y punteros
@@ -54,23 +57,24 @@ private:
Screen *screen; // Objeto encargado de dibujar en pantalla
Resource *resource; // Objeto con los recursos
Asset *asset; // Objeto con los ficheros de recursos
Input *input; // Objeto pata gestionar la entrada
options_t *options; // Puntero a las opciones del juego
SDL_Event *eventHandler; // Manejador de eventos
Text *text; // Objeto para escribir texto en pantalla
SDL_Texture *coverTexture; // Textura para cubrir el texto
section_t *section; // Estado del bucle principal para saber si continua o se sale
// Variables
int counter; // Contador
int preCounter; // Contador previo
int coverCounter; // Contador para la cortinilla
section_t section; // Estado del bucle principal para saber si continua o se sale
Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa
Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles del programa
std::vector<endingTexture_t> spriteTexts; // Vector con los sprites de texto con su cortinilla
std::vector<endingTexture_t> spritePics; // Vector con los sprites de texto con su cortinilla
int scene; // Escena actual
std::vector<scene_t> scenes; // Vector con los textos e imagenes de cada escena
JA_Music_t* music; // Musica que suena durante el final
int counter; // Contador
int preCounter; // Contador previo
int coverCounter; // Contador para la cortinilla
Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa
Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles del programa
vector<endingTexture_t> spriteTexts; // Vector con los sprites de texto con su cortinilla
vector<endingTexture_t> spritePics; // Vector con los sprites de texto con su cortinilla
int scene; // Escena actual
vector<scene_t> scenes; // Vector con los textos e imagenes de cada escena
JA_Music_t *music; // Musica que suena durante el final
// Actualiza el objeto
void update();
@@ -81,6 +85,9 @@ private:
// Comprueba el manejador de eventos
void checkEventHandler();
// Comprueba las entradas
void checkInput();
// Inicializa los textos
void iniTexts();
@@ -113,13 +120,13 @@ private:
public:
// Constructor
Ending(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *asset, options_t *options);
Ending(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *asset, Input *input, options_t *options, section_t *section);
// Destructor
~Ending();
// Bucle principal
section_t run();
void run();
};
#endif

View File

@@ -2,14 +2,16 @@
#include <algorithm>
// Constructor
Ending2::Ending2(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *asset, options_t *options)
Ending2::Ending2(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *asset, Input *input, options_t *options, section_t *section)
{
// Copia los punteros
this->renderer = renderer;
this->screen = screen;
this->resource = resource;
this->asset = asset;
this->input = input;
this->options = options;
this->section = section;
// Reserva memoria para los punteros a objetos
eventHandler = new SDL_Event();
@@ -21,8 +23,8 @@ Ending2::Ending2(SDL_Renderer *renderer, Screen *screen, Resource *resource, Ass
preCounter = 0;
postCounter = 0;
postCounterEnabled = false;
section.name = SECTION_PROG_ENDING2;
section.subsection = 0;
section->name = SECTION_PROG_ENDING2;
section->subsection = 0;
ticks = 0;
ticksSpeed = 15;
distSpriteText = 8;
@@ -32,7 +34,7 @@ Ending2::Ending2(SDL_Renderer *renderer, Screen *screen, Resource *resource, Ass
secondCol = GAMECANVAS_THIRD_QUARTER_X - (GAMECANVAS_WIDTH / 16);
// Inicializa el vector de colores
const std::vector<std::string> colorList = {"white", "yellow", "cyan", "green", "magenta", "red", "blue", "black"};
const vector<string> colorList = {"white", "yellow", "cyan", "green", "magenta", "red", "blue", "black"};
for (auto cl : colorList)
{
colors.push_back(stringToColor(options->palette, cl));
@@ -73,14 +75,17 @@ Ending2::~Ending2()
// Actualiza el objeto
void Ending2::update()
{
// Comprueba el manejador de eventos
checkEventHandler();
// Comprueba que la diferencia de ticks sea mayor a la velocidad del juego
if (SDL_GetTicks() - ticks > ticksSpeed)
{
// Actualiza el contador de ticks
ticks = SDL_GetTicks();
// Comprueba el manejador de eventos
checkEventHandler();
// Comprueba las entradas
checkInput();
// Actualiza los contadores
updateCounters();
@@ -126,7 +131,7 @@ void Ending2::render()
// Dibuja los sprites con el texto del final
renderTexts();
const std::string txt = std::to_string(postCounter);
const string txt = to_string(postCounter);
// text->write(0, 192 - 8, txt);
// Dibuja la cuadricula
@@ -184,66 +189,54 @@ void Ending2::checkEventHandler()
// Evento de salida de la aplicación
if (eventHandler->type == SDL_QUIT)
{
section.name = SECTION_PROG_QUIT;
section->name = SECTION_PROG_QUIT;
break;
}
// Comprueba las teclas que se han pulsado
if ((eventHandler->type == SDL_KEYDOWN && eventHandler->key.repeat == 0) || (eventHandler->type == SDL_JOYBUTTONDOWN))
{
switch (eventHandler->key.keysym.scancode)
{
case SDL_SCANCODE_ESCAPE:
section.name = SECTION_PROG_QUIT;
break;
case SDL_SCANCODE_B:
screen->switchBorder();
resource->reLoadTextures();
break;
case SDL_SCANCODE_F:
screen->switchVideoMode();
resource->reLoadTextures();
break;
case SDL_SCANCODE_F1:
screen->setWindowSize(1);
resource->reLoadTextures();
break;
case SDL_SCANCODE_F2:
screen->setWindowSize(2);
resource->reLoadTextures();
break;
case SDL_SCANCODE_F3:
screen->setWindowSize(3);
resource->reLoadTextures();
break;
case SDL_SCANCODE_F4:
screen->setWindowSize(4);
resource->reLoadTextures();
break;
case SDL_SCANCODE_F5:
switchPalette();
break;
default:
break;
}
}
}
}
// Comprueba las entradas
void Ending2::checkInput()
{
if (input->checkInput(input_exit, REPEAT_FALSE))
{
section->name = SECTION_PROG_LOGO;
section->subsection = SUBSECTION_LOGO_TO_INTRO;
}
else if (input->checkInput(input_toggle_border, REPEAT_FALSE))
{
screen->switchBorder();
}
else if (input->checkInput(input_window_fullscreen, REPEAT_FALSE))
{
screen->switchVideoMode();
}
else if (input->checkInput(input_window_dec_size, REPEAT_FALSE))
{
screen->decWindowSize();
}
else if (input->checkInput(input_window_inc_size, REPEAT_FALSE))
{
screen->incWindowSize();
}
else if (input->checkInput(input_swap_palette, REPEAT_FALSE))
{
switchPalette();
}
}
// Bucle principal
section_t Ending2::run()
void Ending2::run()
{
JA_PlayMusic(music);
while (section.name == SECTION_PROG_ENDING2)
while (section->name == SECTION_PROG_ENDING2)
{
update();
render();
@@ -251,8 +244,6 @@ section_t Ending2::run()
JA_StopMusic();
JA_SetVolume(128);
return section;
}
// Actualiza los contadores
@@ -275,8 +266,8 @@ void Ending2::updateCounters()
if (postCounter > 600)
{
section.name = SECTION_PROG_LOGO;
section.subsection = SUBSECTION_LOGO_TO_INTRO;
section->name = SECTION_PROG_LOGO;
section->subsection = SUBSECTION_LOGO_TO_INTRO;
}
}
@@ -372,8 +363,8 @@ void Ending2::loadSprites()
for (auto sl : spriteList)
{
sprites.push_back(new AnimatedSprite(renderer, resource->getAnimation(sl + ".ani")));
maxSpriteWidth = std::max(sprites.back()->getAnimationClip(0, 0).w, maxSpriteWidth);
maxSpriteHeight = std::max(sprites.back()->getAnimationClip(0, 0).h, maxSpriteHeight);
maxSpriteWidth = max(sprites.back()->getAnimationClip(0, 0).w, maxSpriteWidth);
maxSpriteHeight = max(sprites.back()->getAnimationClip(0, 0).h, maxSpriteHeight);
}
}
@@ -497,8 +488,8 @@ void Ending2::createSpriteTexts()
for (int i = 0; i < (int)spriteList.size(); ++i)
{
// Calcula constantes
std::string txt = spriteList[i];
std::replace(txt.begin(), txt.end(), '_', ' ');
string txt = spriteList[i];
replace(txt.begin(), txt.end(), '_', ' ');
txt = txt == "player" ? "JAILDOCTOR" : txt; // Reemplaza el texto
const int w = text->lenght(txt, 1);
const int h = text->getCharacterSize();
@@ -529,7 +520,7 @@ void Ending2::createTexts()
deleteTexts();
// Crea los primeros textos
std::vector<std::string> list;
vector<string> list;
list.push_back("STARRING");
// Crea los sprites de texto a partir de la lista
@@ -619,7 +610,7 @@ void Ending2::deleteTexts()
void Ending2::updateFinalFade()
{
// La variable step va de 0 a 40 en el tramo de postCounter que va de 500 a 540. Al dividirlo por 40, va de 0.0f a 1.0f
const float step = std::min(std::max(postCounter, 500) - 500, 40) / 40.0f;
const float step = min(max(postCounter, 500) - 500, 40) / 40.0f;
const int index = (colors.size() - 1) * step;
for (auto t : texts)

View File

@@ -1,14 +1,15 @@
#pragma once
#include <SDL2/SDL.h>
#include "common/animatedsprite.h"
#include "common/asset.h"
#include "common/jail_audio.h"
#include "common/resource.h"
#include "common/screen.h"
#include "common/sprite.h"
#include "common/text.h"
#include "common/texture.h"
#include "common/utils.h"
#include "jail_engine/animatedsprite.h"
#include "jail_engine/asset.h"
#include "jail_engine/input.h"
#include "jail_engine/jail_audio.h"
#include "jail_engine/resource.h"
#include "jail_engine/screen.h"
#include "jail_engine/sprite.h"
#include "jail_engine/text.h"
#include "jail_engine/texture.h"
#include "jail_engine/utils.h"
#include "const.h"
#include <vector>
#include <string>
@@ -16,39 +17,42 @@
#ifndef ENDING2_H
#define ENDING2_H
using namespace std;
class Ending2
{
private:
// Objetos y punteros
Asset *asset; // Objeto con los ficheros de recursos
Resource *resource; // Objeto con los recursos
Screen *screen; // Objeto encargado de dibujar en pantalla
SDL_Event *eventHandler; // Manejador de eventos
SDL_Renderer *renderer; // El renderizador de la ventana
Text *text; // Objeto para escribir texto en pantalla
options_t *options; // Puntero a las opciones del juego
std::vector<AnimatedSprite *> sprites; // Vector con todos los sprites a dibujar
std::vector<MovingSprite *> spriteTexts; // Vector con los sprites de texto de los sprites
std::vector<MovingSprite *> texts; // Vector con los sprites de texto
Asset *asset; // Objeto con los ficheros de recursos
Resource *resource; // Objeto con los recursos
Screen *screen; // Objeto encargado de dibujar en pantalla
SDL_Event *eventHandler; // Manejador de eventos
SDL_Renderer *renderer; // El renderizador de la ventana
Input *input; // Objeto pata gestionar la entrada
Text *text; // Objeto para escribir texto en pantalla
options_t *options; // Puntero a las opciones del juego
vector<AnimatedSprite *> sprites; // Vector con todos los sprites a dibujar
vector<MovingSprite *> spriteTexts; // Vector con los sprites de texto de los sprites
vector<MovingSprite *> texts; // Vector con los sprites de texto
section_t *section; // Estado del bucle principal para saber si continua o se sale
// Variables
bool counterEnabled; // Indica si está el contador habilitado
int preCounter; // Contador previo
int postCounter; // Contador posterior
bool postCounterEnabled; // Indica si está habilitado el contador
section_t section; // Estado del bucle principal para saber si continua o se sale
Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa
Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles del programa
JA_Music_t* music; // Musica que suena durante el final
std::vector<std::string> spriteList; // Lista con todos los sprites a dibujar
std::vector<color_t> colors; // Vector con los colores para el fade
int maxSpriteWidth; // El valor de ancho del sprite mas ancho
int maxSpriteHeight; // El valor de alto del sprite mas alto
int distSpriteText; // Distancia entre el sprite y el texto que lo acompaña
int distSpriteSprite; // Distancia entre dos sprites de la misma columna
float despSpeed; // Velocidad de desplazamiento de los sprites
int firstCol; // Primera columna por donde desfilan los sprites
int secondCol; // Segunda columna por donde desfilan los sprites
bool counterEnabled; // Indica si está el contador habilitado
int preCounter; // Contador previo
int postCounter; // Contador posterior
bool postCounterEnabled; // Indica si está habilitado el contador
Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa
Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles del programa
JA_Music_t *music; // Musica que suena durante el final
vector<string> spriteList; // Lista con todos los sprites a dibujar
vector<color_t> colors; // Vector con los colores para el fade
int maxSpriteWidth; // El valor de ancho del sprite mas ancho
int maxSpriteHeight; // El valor de alto del sprite mas alto
int distSpriteText; // Distancia entre el sprite y el texto que lo acompaña
int distSpriteSprite; // Distancia entre dos sprites de la misma columna
float despSpeed; // Velocidad de desplazamiento de los sprites
int firstCol; // Primera columna por donde desfilan los sprites
int secondCol; // Segunda columna por donde desfilan los sprites
// Actualiza el objeto
void update();
@@ -59,6 +63,9 @@ private:
// Comprueba el manejador de eventos
void checkEventHandler();
// Comprueba las entradas
void checkInput();
// Actualiza los contadores
void updateCounters();
@@ -115,13 +122,13 @@ private:
public:
// Constructor
Ending2(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *asset, options_t *options);
Ending2(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *asset, Input *input, options_t *options, section_t *section);
// Destructor
~Ending2();
// Bucle principal
section_t run();
void run();
};
#endif

View File

@@ -40,7 +40,7 @@ Enemy::Enemy(enemy_t enemy)
}
else
{
sprite->setCurrentFrame(std::min(enemy.frame, sprite->getNumFrames() - 1));
sprite->setCurrentFrame(min(enemy.frame, sprite->getNumFrames() - 1));
}
}

View File

@@ -1,20 +1,22 @@
#pragma once
#include <SDL2/SDL.h>
#include "common/animatedsprite.h"
#include "common/asset.h"
#include "common/utils.h"
#include "jail_engine/animatedsprite.h"
#include "jail_engine/asset.h"
#include "jail_engine/utils.h"
#include <string>
#ifndef ENEMY_H
#define ENEMY_H
using namespace std;
// Estructura para pasar los datos de un enemigo
struct enemy_t
{
SDL_Renderer *renderer; // El renderizador de la ventana
animatedSprite_t *animation; // Puntero a las animaciones del enemigo
std::string animationString; // Ruta al fichero con la animación
string animationString; // Ruta al fichero con la animación
int w; // Anchura del enemigo
int h; // Altura del enemigo
float x; // Posición inicial en el eje X
@@ -28,7 +30,7 @@ struct enemy_t
bool flip; // Indica si el enemigo hace flip al terminar su ruta
bool mirror; // Indica si el enemigo está volteado verticalmente
int frame; // Frame inicial para la animación del enemigo
std::string color; // Color del enemigo
string color; // Color del enemigo
palette_e palette; // Paleta de colores
};
@@ -39,16 +41,16 @@ private:
AnimatedSprite *sprite; // Sprite del enemigo
// Variables
color_t color; // Color del enemigo
std::string colorString; // Color del enemigo en formato texto
palette_e palette; // Paleta de colores
int x1; // Limite izquierdo de la ruta en el eje X
int x2; // Limite derecho de la ruta en el eje X
int y1; // Limite superior de la ruta en el eje Y
int y2; // Limite inferior de la ruta en el eje Y
SDL_Rect collider; // Caja de colisión
bool doFlip; // Indica si el enemigo hace flip al terminar su ruta
bool mirror; // Indica si el enemigo se dibuja volteado verticalmente
color_t color; // Color del enemigo
string colorString; // Color del enemigo en formato texto
palette_e palette; // Paleta de colores
int x1; // Limite izquierdo de la ruta en el eje X
int x2; // Limite derecho de la ruta en el eje X
int y1; // Limite superior de la ruta en el eje Y
int y2; // Limite inferior de la ruta en el eje Y
SDL_Rect collider; // Caja de colisión
bool doFlip; // Indica si el enemigo hace flip al terminar su ruta
bool mirror; // Indica si el enemigo se dibuja volteado verticalmente
// Comprueba si ha llegado al limite del recorrido para darse media vuelta
void checkPath();

View File

@@ -1,17 +1,18 @@
#include "common/jail_audio.h"
#include "common/jscore.h"
#include "jail_engine/jail_audio.h"
#include "jail_engine/jscore.h"
#include "const.h"
#include "enter_id.h"
#include <iostream>
// Constructor
EnterID::EnterID(SDL_Renderer *renderer, Screen *screen, Asset *asset, options_t *options, section_t section)
EnterID::EnterID(SDL_Renderer *renderer, Screen *screen, Asset *asset, options_t *options, section_t *section)
{
// Copia la dirección de los objetos
this->renderer = renderer;
this->screen = screen;
this->asset = asset;
this->options = options;
this->section = section;
// Reserva memoria para los punteros
eventHandler = new SDL_Event();
@@ -24,7 +25,7 @@ EnterID::EnterID(SDL_Renderer *renderer, Screen *screen, Asset *asset, options_t
{
if (options->console)
{
std::cout << "Error: textTexture could not be created!\nSDL Error: " << SDL_GetError() << std::endl;
cout << "Error: textTexture could not be created!\nSDL Error: " << SDL_GetError() << endl;
}
}
SDL_SetTextureBlendMode(textTexture, SDL_BLENDMODE_BLEND);
@@ -36,11 +37,10 @@ EnterID::EnterID(SDL_Renderer *renderer, Screen *screen, Asset *asset, options_t
pos = 0;
name[pos] = 0;
maxLenght = 15;
this->section.subsection = section.subsection;
if (options->online.enabled && options->online.jailerID == "")
{
this->section.name = SECTION_PROG_ENTER_ID;
this->section->name = SECTION_PROG_ENTER_ID;
}
else
{
@@ -60,18 +60,16 @@ EnterID::~EnterID()
}
// Bucle para el logo del juego
section_t EnterID::run()
void EnterID::run()
{
// Detiene la música
JA_StopMusic();
while (section.name == SECTION_PROG_ENTER_ID)
while (section->name == SECTION_PROG_ENTER_ID)
{
update();
render();
}
return section;
}
// Comprueba el manejador de eventos
@@ -83,7 +81,7 @@ void EnterID::checkEventHandler()
// Evento de salida de la aplicación
if (eventHandler->type == SDL_QUIT)
{
section.name = SECTION_PROG_QUIT;
section->name = SECTION_PROG_QUIT;
break;
}
@@ -92,7 +90,7 @@ void EnterID::checkEventHandler()
{
if (eventHandler->key.keysym.scancode == SDL_SCANCODE_RETURN)
{
options->online.jailerID = (std::string)name;
options->online.jailerID = (string)name;
endSection();
break;
}
@@ -138,7 +136,7 @@ void EnterID::checkEventHandler()
else if (eventHandler->key.keysym.scancode == SDL_SCANCODE_ESCAPE)
{
section.name = SECTION_PROG_QUIT;
section->name = SECTION_PROG_QUIT;
break;
}
@@ -208,7 +206,7 @@ void EnterID::render()
SDL_RenderCopy(renderer, textTexture, nullptr, nullptr);
// Escribe el jailerID
const std::string jailerID = (std::string)name + cursor;
const string jailerID = (string)name + cursor;
const color_t color = stringToColor(options->palette, "white");
text->writeDX(TXT_CENTER | TXT_COLOR, GAMECANVAS_CENTER_X, (16 * 8 + 1), jailerID, 1, color);
@@ -298,14 +296,14 @@ void EnterID::initOnline()
jscore::init(options->online.server, options->online.port);
#ifdef DEBUG
const std::string caption = options->online.jailerID + " IS LOGGED IN (DEBUG)";
const string caption = "IS LOGGED IN (DEBUG)";
#else
const std::string caption = options->online.jailerID + " IS LOGGED IN";
const string caption = "IS LOGGED IN";
#endif
screen->showNotification(caption);
screen->showNotification(options->online.jailerID, caption, 12);
if (options->console)
{
std::cout << caption << std::endl;
cout << caption << endl;
}
}
}
@@ -314,6 +312,6 @@ void EnterID::initOnline()
void EnterID::endSection()
{
initOnline();
section.name = (section.subsection == SUBSECTION_LOGO_TO_INTRO) ? SECTION_PROG_INTRO : SECTION_PROG_TITLE;
section.subsection = 0;
section->name = (section->subsection == SUBSECTION_LOGO_TO_INTRO) ? SECTION_PROG_INTRO : SECTION_PROG_TITLE;
section->subsection = 0;
}

View File

@@ -1,23 +1,25 @@
#pragma once
#include <SDL2/SDL.h>
#include "common/asset.h"
#include "common/screen.h"
#include "common/utils.h"
#include "common/text.h"
#include "common/texture.h"
#include "jail_engine/asset.h"
#include "jail_engine/screen.h"
#include "jail_engine/utils.h"
#include "jail_engine/text.h"
#include "jail_engine/texture.h"
#include <string>
#include <vector>
#ifndef ENTER_ID_H
#define ASK_ME_H
#define ENTER_ID_H
using namespace std;
class EnterID
{
private:
struct captions_t
{
std::string label; // Texto a escribir
color_t color; // Color del texto
string label; // Texto a escribir
color_t color; // Color del texto
};
// Punteros y objetos
@@ -29,14 +31,14 @@ private:
SDL_Texture *textTexture; // Textura para dibujar el texto
Text *text; // Objeto para escribir texto en pantalla
Texture *texture; // Textura para la fuente para el texto
section_t *section; // Estado del bucle principal para saber si continua o se sale
// Variables
int counter; // Contador
section_t section; // Estado del bucle principal para saber si continua o se sale
Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa
Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles del programa
std::vector<captions_t> texts; // Vector con los textos
std::string cursor; // Contiene el caracter que se muestra como cursor
int counter; // Contador
Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa
Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles del programa
vector<captions_t> texts; // Vector con los textos
string cursor; // Contiene el caracter que se muestra como cursor
char name[15];
int pos;
@@ -68,13 +70,13 @@ private:
public:
// Constructor
EnterID(SDL_Renderer *renderer, Screen *screen, Asset *asset, options_t *options, section_t section);
EnterID(SDL_Renderer *renderer, Screen *screen, Asset *asset, options_t *options, section_t *section);
// Destructor
~EnterID();
// Bucle principal
section_t run();
void run();
};
#endif

View File

@@ -2,15 +2,8 @@
#include <iostream>
// Constructor
Game::Game(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *asset, options_t *options, Input *input, Debug *debug)
Game::Game(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *asset, options_t *options, Input *input, section_t *section, Debug *debug)
{
// Inicia algunas variables
board.iniClock = SDL_GetTicks();
currentRoom = "03.room";
const int x = 25;
const int y = 13;
spawnPoint = {x * 8, y * 8, 0, 0, 0, s_standing, SDL_FLIP_HORIZONTAL};
// Copia los punteros
this->resource = resource;
this->renderer = renderer;
@@ -19,21 +12,31 @@ Game::Game(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *as
this->input = input;
this->debug = debug;
this->options = options;
this->section = section;
// Inicia algunas variables
board.iniClock = SDL_GetTicks();
#ifdef DEBUG
currentRoom = "01.room";
const int x1 = 25;
const int y1 = 13;
spawnPoint = {x1 * 8, y1 * 8, 0, 0, 0, s_standing, SDL_FLIP_HORIZONTAL};
currentRoom = "03.room";
const int x = 25;
const int y = 13;
spawnPoint = {x * 8, y * 8, 0, 0, 0, s_standing, SDL_FLIP_HORIZONTAL};
debug->setEnabled(false);
#else
currentRoom = "03.room";
const int x = 25;
const int y = 13;
spawnPoint = {x * 8, y * 8, 0, 0, 0, s_standing, SDL_FLIP_HORIZONTAL};
#endif
// Crea los objetos
cheevos = new Cheevos(screen, options, asset->get("cheevos.bin"));
scoreboard = new ScoreBoard(renderer, resource, asset, options, &board);
itemTracker = new ItemTracker();
roomTracker = new RoomTracker();
room = new Room(resource->getRoom(currentRoom), renderer, screen, asset, options, itemTracker, &board.items, false, debug);
const std::string playerPNG = options->cheat.altSkin ? "player2.png" : "player.png";
const std::string playerANI = options->cheat.altSkin ? "player2.ani" : "player.ani";
const string playerPNG = options->cheat.altSkin ? "player2.png" : "player.png";
const string playerANI = options->cheat.altSkin ? "player2.ani" : "player.ani";
const player_t player = {spawnPoint, playerPNG, playerANI, renderer, resource, asset, options, input, room, debug};
this->player = new Player(player);
eventHandler = new SDL_Event();
@@ -48,7 +51,7 @@ Game::Game(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *as
{
if (options->console)
{
std::cout << "Error: roomNameTexture could not be created!\nSDL Error: " << SDL_GetError() << std::endl;
cout << "Error: roomNameTexture could not be created!\nSDL Error: " << SDL_GetError() << endl;
}
}
@@ -80,14 +83,17 @@ Game::Game(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *as
totalItems = getTotalItems();
initStats();
stats->addVisit(room->getName());
const bool cheats = options->cheat.infiniteLives || options->cheat.invincible || options->cheat.jailEnabled;
cheevos->enable(!cheats); // Deshabilita los logros si hay trucos activados
section.name = SECTION_PROG_GAME;
section.subsection = 0;
section->name = SECTION_PROG_GAME;
section->subsection = 0;
}
Game::~Game()
{
// Libera la memoria de los objetos
delete cheevos;
delete scoreboard;
delete itemTracker;
delete roomTracker;
@@ -112,7 +118,7 @@ void Game::checkEventHandler()
// Evento de salida de la aplicación
if (eventHandler->type == SDL_QUIT)
{
section.name = SECTION_PROG_QUIT;
section->name = SECTION_PROG_QUIT;
screen->setBorderColor(stringToColor(options->palette, "black"));
break;
}
@@ -122,13 +128,10 @@ void Game::checkEventHandler()
reLoadTextures();
}
if ((eventHandler->type == SDL_KEYDOWN) and (eventHandler->key.repeat == 0))
if (eventHandler->type == SDL_KEYDOWN && eventHandler->key.repeat == 0)
{
switch (eventHandler->key.keysym.scancode)
{
case SDL_SCANCODE_ESCAPE:
section.name = SECTION_PROG_TITLE;
break;
#ifdef DEBUG
case SDL_SCANCODE_G:
debug->switchEnabled();
@@ -158,53 +161,21 @@ void Game::checkEventHandler()
break;
case SDL_SCANCODE_F6:
screen->showNotification("MAMA MIRA! SIN MANOS!");
screen->showNotification("ACHIEVEMENT UNLOCKED!", "I LIKE MY MULTICOLOURED FRIENDS", 2);
break;
case SDL_SCANCODE_F7:
screen->showNotification("ACHIEVEMENT UNLOCKED!", "I LIKE MY MULTICOLOURED FRIENDS", 3);
break;
case SDL_SCANCODE_F8:
screen->showNotification("JAILDESIGNER IS LOGGED IN", "", 4);
break;
case SDL_SCANCODE_F9:
screen->showNotification("JAILDESIGNER IS LOGGED IN", "", 5);
break;
#endif
case SDL_SCANCODE_M:
board.music = !board.music;
board.music ? JA_ResumeMusic() : JA_PauseMusic();
break;
case SDL_SCANCODE_H:
switchPause();
break;
case SDL_SCANCODE_B:
screen->switchBorder();
reLoadTextures();
break;
case SDL_SCANCODE_F:
screen->switchVideoMode();
reLoadTextures();
break;
case SDL_SCANCODE_F1:
screen->setWindowSize(1);
reLoadTextures();
break;
case SDL_SCANCODE_F2:
screen->setWindowSize(2);
reLoadTextures();
break;
case SDL_SCANCODE_F3:
screen->setWindowSize(3);
reLoadTextures();
break;
case SDL_SCANCODE_F4:
screen->setWindowSize(4);
reLoadTextures();
break;
case SDL_SCANCODE_F5:
switchPalette();
break;
default:
break;
}
@@ -212,8 +183,57 @@ void Game::checkEventHandler()
}
}
// Comprueba el teclado
void Game::checkInput()
{
if (input->checkInput(input_exit, REPEAT_FALSE))
{
section->name = SECTION_PROG_TITLE;
}
else if (input->checkInput(input_switch_music, REPEAT_FALSE))
{
board.music = !board.music;
board.music ? JA_ResumeMusic() : JA_PauseMusic();
}
else if (input->checkInput(input_pause, REPEAT_FALSE))
{
switchPause();
}
else if (input->checkInput(input_toggle_border, REPEAT_FALSE))
{
screen->switchBorder();
reLoadTextures();
}
else if (input->checkInput(input_window_fullscreen, REPEAT_FALSE))
{
screen->switchVideoMode();
reLoadTextures();
}
else if (input->checkInput(input_window_dec_size, REPEAT_FALSE))
{
screen->decWindowSize();
reLoadTextures();
}
else if (input->checkInput(input_window_inc_size, REPEAT_FALSE))
{
screen->incWindowSize();
reLoadTextures();
}
else if (input->checkInput(input_swap_palette, REPEAT_FALSE))
{
switchPalette();
}
}
// Bucle para el juego
section_t Game::run()
void Game::run()
{
JA_PlayMusic(music);
if (!board.music)
@@ -221,28 +241,29 @@ section_t Game::run()
JA_PauseMusic();
}
while (section.name == SECTION_PROG_GAME)
while (section->name == SECTION_PROG_GAME)
{
update();
render();
}
JA_StopMusic();
return section;
}
// Actualiza el juego, las variables, comprueba la entrada, etc.
void Game::update()
{
// Comprueba los eventos de la cola
checkEventHandler();
// Comprueba que la diferencia de ticks sea mayor a la velocidad del juego
if (SDL_GetTicks() - ticks > ticksSpeed)
{
// Actualiza el contador de ticks
ticks = SDL_GetTicks();
// Comprueba los eventos de la cola
checkEventHandler();
// Comprueba el teclado
checkInput();
#ifdef DEBUG
debug->clear();
@@ -258,6 +279,7 @@ void Game::update()
checkGameOver();
checkEndGame();
checkRestoringJail();
checkSomeCheevos();
scoreboard->update();
input->update();
@@ -300,9 +322,9 @@ void Game::render()
// Pasa la información de debug
void Game::updateDebugInfo()
{
debug->add("X = " + std::to_string((int)player->x) + ", Y = " + std::to_string((int)player->y));
debug->add("VX = " + std::to_string(player->vx).substr(0, 4) + ", VY = " + std::to_string(player->vy).substr(0, 4));
debug->add("STATE = " + std::to_string(player->state));
debug->add("X = " + to_string((int)player->x) + ", Y = " + to_string((int)player->y));
debug->add("VX = " + to_string(player->vx).substr(0, 4) + ", VY = " + to_string(player->vy).substr(0, 4));
debug->add("STATE = " + to_string(player->state));
}
// Pone la información de debug en pantalla
@@ -343,7 +365,7 @@ void Game::renderRoomName()
}
// Cambia de habitación
bool Game::changeRoom(std::string file)
bool Game::changeRoom(string file)
{
// En las habitaciones los limites tienen la cadena del fichero o un 0 en caso de no limitar con nada
if (file == "0")
@@ -391,7 +413,7 @@ void Game::checkPlayerOnBorder()
{
if (player->getOnBorder())
{
const std::string roomName = room->getRoom(player->getBorder());
const string roomName = room->getRoom(player->getBorder());
if (changeRoom(roomName))
{
player->switchBorders();
@@ -432,7 +454,7 @@ void Game::checkGameOver()
{
if (board.lives < 0 && blackScreenCounter > 17)
{
section.name = SECTION_PROG_GAME_OVER;
section->name = SECTION_PROG_GAME_OVER;
}
}
@@ -453,6 +475,9 @@ void Game::killPlayer()
// Actualiza las estadisticas
stats->addDeath(room->getName());
// Invalida el logro de pasarse el juego sin morir
cheevos->invalidate(11);
// Destruye la habitacion y el jugador
delete room;
delete this->player;
@@ -465,8 +490,8 @@ void Game::killPlayer()
// Crea la nueva habitación y el nuevo jugador
room = new Room(resource->getRoom(currentRoom), renderer, screen, asset, options, itemTracker, &board.items, board.jailEnabled, debug);
const std::string playerPNG = options->cheat.altSkin ? "player2.png" : "player.png";
const std::string playerANI = options->cheat.altSkin ? "player2.ani" : "player.ani";
const string playerPNG = options->cheat.altSkin ? "player2.png" : "player.png";
const string playerANI = options->cheat.altSkin ? "player2.ani" : "player.ani";
const player_t player = {spawnPoint, playerPNG, playerANI, renderer, resource, asset, options, input, room, debug};
this->player = new Player(player);
@@ -480,7 +505,7 @@ void Game::reLoadTextures()
{
if (options->console)
{
std::cout << "** RELOAD REQUESTED" << std::endl;
cout << "** RELOAD REQUESTED" << endl;
}
player->reLoadTexture();
room->reLoadTexture();
@@ -493,7 +518,7 @@ void Game::switchPalette()
{
if (options->console)
{
std::cout << "** PALETTE SWITCH REQUESTED" << std::endl;
cout << "** PALETTE SWITCH REQUESTED" << endl;
}
// Modifica la variable
@@ -569,7 +594,10 @@ bool Game::checkEndGame()
if (haveTheItems && isOnTheRoom && isOnTheDoor)
{
section.name = SECTION_PROG_ENDING;
// Comprueba los logros de completar el juego
checkEndGameCheevos();
section->name = SECTION_PROG_ENDING;
return true;
}
@@ -580,7 +608,7 @@ bool Game::checkEndGame()
int Game::getTotalItems()
{
int items = 0;
std::vector<res_room_t> *rooms = new std::vector<res_room_t>;
vector<res_room_t> *rooms = new vector<res_room_t>;
rooms = resource->getAllRooms();
for (auto room : *rooms)
@@ -594,7 +622,7 @@ int Game::getTotalItems()
// Va a la habitación designada
void Game::goToRoom(int border)
{
const std::string roomName = room->getRoom(border);
const string roomName = room->getRoom(border);
if (changeRoom(roomName))
{
currentRoom = roomName;
@@ -635,18 +663,26 @@ void Game::checkRestoringJail()
counter++;
}
// Incrementa el numero de vidas
if (counter == 100)
{
counter = 0;
board.lives++;
JA_PlaySound(deathSound);
// Invalida el logro de completar el juego sin entrar a la jail
const bool haveTheItems = board.items >= int(totalItems * 0.9f);
if (!haveTheItems)
{
cheevos->invalidate(9);
}
}
}
// Inicializa el diccionario de las estadísticas
void Game::initStats()
{
std::vector<res_room_t> *rooms = new std::vector<res_room_t>;
vector<res_room_t> *rooms = new vector<res_room_t>;
rooms = resource->getAllRooms();
for (auto room : *rooms)
@@ -673,4 +709,74 @@ void Game::fillRoomNameTexture()
// Deja el renderizador por defecto
SDL_SetRenderTarget(renderer, nullptr);
}
// Comprueba algunos logros
void Game::checkSomeCheevos()
{
// Logros sobre la cantidad de items
if (board.items == totalItems)
{
cheevos->unlock(4);
cheevos->unlock(3);
cheevos->unlock(2);
cheevos->unlock(1);
}
else if (board.items >= totalItems * 0.75f)
{
cheevos->unlock(3);
cheevos->unlock(2);
cheevos->unlock(1);
}
else if (board.items >= totalItems * 0.5f)
{
cheevos->unlock(2);
cheevos->unlock(1);
}
else if (board.items >= totalItems * 0.25f)
{
cheevos->unlock(1);
}
// Logros sobre las habitaciones visitadas
if (board.rooms >= 60)
{
cheevos->unlock(7);
cheevos->unlock(6);
cheevos->unlock(5);
}
else if (board.rooms >= 40)
{
cheevos->unlock(6);
cheevos->unlock(5);
}
else if (board.rooms >= 20)
{
cheevos->unlock(5);
}
}
// Comprueba los logros de completar el juego
void Game::checkEndGameCheevos()
{
// "Complete the game"
cheevos->unlock(8);
// "Complete the game without entering the jail"
cheevos->unlock(9);
// "Complete the game with all items"
if (board.items == totalItems)
{
cheevos->unlock(10);
}
// "Complete the game without dying"
cheevos->unlock(11);
// "Complete the game in under 30 minutes"
if (scoreboard->getMinutes() < 30)
{
cheevos->unlock(12);
}
}

View File

@@ -1,16 +1,17 @@
#pragma once
#include <SDL2/SDL.h>
#include "common/animatedsprite.h"
#include "common/asset.h"
#include "common/debug.h"
#include "common/input.h"
#include "common/jail_audio.h"
#include "common/resource.h"
#include "common/screen.h"
#include "common/sprite.h"
#include "common/text.h"
#include "common/utils.h"
#include "cheevos.h"
#include "jail_engine/animatedsprite.h"
#include "jail_engine/asset.h"
#include "jail_engine/debug.h"
#include "jail_engine/input.h"
#include "jail_engine/jail_audio.h"
#include "jail_engine/resource.h"
#include "jail_engine/screen.h"
#include "jail_engine/sprite.h"
#include "jail_engine/text.h"
#include "jail_engine/utils.h"
#include "const.h"
#include "item_tracker.h"
#include "player.h"
@@ -22,6 +23,8 @@
#ifndef GAME_H
#define GAME_H
using namespace std;
class Game
{
private:
@@ -37,18 +40,19 @@ private:
Input *input; // Objeto pata gestionar la entrada
Text *text; // Objeto para los textos del juego
ScoreBoard *scoreboard; // Objeto encargado de gestionar el marcador
Cheevos *cheevos; // Objeto encargado de gestionar los logros del juego
Resource *resource; // Objeto con los recursos
Debug *debug; // Objeto para gestionar la información de debug
options_t *options; // Puntero a las opciones del juego
Stats *stats; // Objeto encargado de gestionar las estadísticas
SDL_Texture *roomNameTexture; // Textura para escribir el nombre de la habitación
section_t *section; // Seccion actual dentro del juego
// Variables
JA_Music_t *music; // Musica que suena durante el juego
Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa
Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles del programa
section_t section; // Seccion actual dentro del juego
std::string currentRoom; // Fichero de la habitación actual
string currentRoom; // Fichero de la habitación actual
playerSpawn_t spawnPoint; // Lugar de la habitación donde aparece el jugador
JA_Sound_t *deathSound; // Sonido a reproducir cuando muere el jugador
board_t board; // Estructura con los datos del marcador
@@ -79,7 +83,10 @@ private:
void renderRoomName();
// Cambia de habitación
bool changeRoom(std::string file);
bool changeRoom(string file);
// Comprueba el teclado
void checkInput();
// Comprueba si el jugador esta en el borde de la pantalla y actua
void checkPlayerOnBorder();
@@ -138,15 +145,21 @@ private:
// Pone el nombre de la habitación en la textura
void fillRoomNameTexture();
// Comprueba algunos logros
void checkSomeCheevos();
// Comprueba los logros de completar el juego
void checkEndGameCheevos();
public:
// Constructor
Game(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *asset, options_t *options, Input *input, Debug *debug);
Game(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *asset, options_t *options, Input *input, section_t *section, Debug *debug);
// Destructor
~Game();
// Bucle para el juego
section_t run();
void run();
};
#endif

View File

@@ -1,14 +1,16 @@
#include "game_over.h"
// Constructor
GameOver::GameOver(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *asset, options_t *options)
GameOver::GameOver(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *asset, Input *input, options_t *options, section_t *section)
{
// Copia los punteros
this->renderer = renderer;
this->screen = screen;
this->resource = resource;
this->asset = asset;
this->input = input;
this->options = options;
this->section = section;
// Reserva memoria para los punteros a objetos
eventHandler = new SDL_Event();
@@ -20,8 +22,8 @@ GameOver::GameOver(SDL_Renderer *renderer, Screen *screen, Resource *resource, A
// Inicializa variables
preCounter = 0;
counter = 0;
section.name = SECTION_PROG_GAME_OVER;
section.subsection = 0;
section->name = SECTION_PROG_GAME_OVER;
section->subsection = 0;
ticks = 0;
ticksSpeed = 15;
endSection = 400;
@@ -33,7 +35,7 @@ GameOver::GameOver(SDL_Renderer *renderer, Screen *screen, Resource *resource, A
tvSprite->setPosY(30);
// Inicializa el vector de colores
const std::vector<std::string> colorList = {"white", "yellow", "cyan", "green", "magenta", "red", "blue", "black"};
const vector<string> colorList = {"white", "yellow", "cyan", "green", "magenta", "red", "blue", "black"};
for (auto cl : colorList)
{
colors.push_back(stringToColor(options->palette, cl));
@@ -55,14 +57,17 @@ GameOver::~GameOver()
// Actualiza el objeto
void GameOver::update()
{
// Comprueba el manejador de eventos
checkEventHandler();
// Comprueba que la diferencia de ticks sea mayor a la velocidad del juego
if (SDL_GetTicks() - ticks > ticksSpeed)
{
// Actualiza el contador de ticks
ticks = SDL_GetTicks();
// Comprueba el manejador de eventos
checkEventHandler();
// Comprueba las entradas
checkInput();
// Actualiza el color usado para renderizar los textos e imagenes
updateColor();
@@ -83,7 +88,7 @@ void GameOver::update()
void GameOver::render()
{
const int y = 32;
// Prepara para empezar a dibujar en la textura de juego
screen->start();
@@ -99,8 +104,8 @@ void GameOver::render()
renderSprites();
// Escribe el texto con las habitaciones y los items
const std::string itemsTxt = std::to_string(options->stats.items / 100) + std::to_string((options->stats.items % 100) / 10) + std::to_string(options->stats.items % 10);
const std::string roomsTxt = std::to_string(options->stats.rooms / 100) + std::to_string((options->stats.rooms % 100) / 10) + std::to_string(options->stats.rooms % 10);
const string itemsTxt = to_string(options->stats.items / 100) + to_string((options->stats.items % 100) / 10) + to_string(options->stats.items % 10);
const string roomsTxt = to_string(options->stats.rooms / 100) + to_string((options->stats.rooms % 100) / 10) + to_string(options->stats.rooms % 10);
text->writeDX(TXT_CENTER | TXT_COLOR, GAMECANVAS_CENTER_X, y + 80, "ITEMS: " + itemsTxt, 1, color);
text->writeDX(TXT_CENTER | TXT_COLOR, GAMECANVAS_CENTER_X, y + 90, "ROOMS: " + roomsTxt, 1, color);
@@ -121,71 +126,56 @@ void GameOver::checkEventHandler()
// Evento de salida de la aplicación
if (eventHandler->type == SDL_QUIT)
{
section.name = SECTION_PROG_QUIT;
section.subsection = 0;
section->name = SECTION_PROG_QUIT;
section->subsection = 0;
break;
}
// Comprueba las teclas que se han pulsado
if ((eventHandler->type == SDL_KEYDOWN && eventHandler->key.repeat == 0) || (eventHandler->type == SDL_JOYBUTTONDOWN))
{
switch (eventHandler->key.keysym.scancode)
{
case SDL_SCANCODE_ESCAPE:
section.name = SECTION_PROG_QUIT;
break;
case SDL_SCANCODE_B:
screen->switchBorder();
resource->reLoadTextures();
break;
case SDL_SCANCODE_F:
screen->switchVideoMode();
resource->reLoadTextures();
break;
case SDL_SCANCODE_F1:
screen->setWindowSize(1);
resource->reLoadTextures();
break;
case SDL_SCANCODE_F2:
screen->setWindowSize(2);
resource->reLoadTextures();
break;
case SDL_SCANCODE_F3:
screen->setWindowSize(3);
resource->reLoadTextures();
break;
case SDL_SCANCODE_F4:
screen->setWindowSize(4);
resource->reLoadTextures();
break;
case SDL_SCANCODE_F5:
switchPalette();
break;
default:
break;
}
}
}
}
// Bucle principal
section_t GameOver::run()
// Comprueba las entradas
void GameOver::checkInput()
{
while (section.name == SECTION_PROG_GAME_OVER)
if (input->checkInput(input_exit, REPEAT_FALSE))
{
section->name = SECTION_PROG_QUIT;
}
else if (input->checkInput(input_toggle_border, REPEAT_FALSE))
{
screen->switchBorder();
}
else if (input->checkInput(input_window_fullscreen, REPEAT_FALSE))
{
screen->switchVideoMode();
}
else if (input->checkInput(input_window_dec_size, REPEAT_FALSE))
{
screen->decWindowSize();
}
else if (input->checkInput(input_window_inc_size, REPEAT_FALSE))
{
screen->incWindowSize();
}
else if (input->checkInput(input_swap_palette, REPEAT_FALSE))
{
switchPalette();
}
}
// Bucle principal
void GameOver::run()
{
while (section->name == SECTION_PROG_GAME_OVER)
{
update();
render();
}
return section;
}
// Actualiza el color usado para renderizar los textos e imagenes
@@ -195,14 +185,13 @@ void GameOver::updateColor()
if (counter < half)
{
// const float step = std::min(std::max(counter, iniFade) - iniFade, fadeLenght) / (float)fadeLenght;
const float step = std::min(counter, fadeLenght) / (float)fadeLenght;
const float step = min(counter, fadeLenght) / (float)fadeLenght;
const int index = (colors.size() - 1) - int((colors.size() - 1) * step);
color = colors[index];
}
else
{
const float step = std::min(std::max(counter, iniFade) - iniFade, fadeLenght) / (float)fadeLenght;
const float step = min(max(counter, iniFade) - iniFade, fadeLenght) / (float)fadeLenght;
const int index = (colors.size() - 1) * step;
color = colors[index];
}
@@ -240,8 +229,8 @@ void GameOver::updateCounters()
// Comprueba si ha terminado la sección
else if (counter == endSection)
{
section.name = SECTION_PROG_LOGO;
section.subsection = SUBSECTION_LOGO_TO_TITLE;
section->name = SECTION_PROG_LOGO;
section->subsection = SUBSECTION_LOGO_TO_TITLE;
}
}

View File

@@ -1,20 +1,23 @@
#pragma once
#include <SDL2/SDL.h>
#include "common/animatedsprite.h"
#include "common/asset.h"
#include "common/jail_audio.h"
#include "common/resource.h"
#include "common/screen.h"
#include "common/sprite.h"
#include "common/text.h"
#include "common/texture.h"
#include "common/utils.h"
#include "jail_engine/animatedsprite.h"
#include "jail_engine/asset.h"
#include "jail_engine/input.h"
#include "jail_engine/jail_audio.h"
#include "jail_engine/resource.h"
#include "jail_engine/screen.h"
#include "jail_engine/sprite.h"
#include "jail_engine/text.h"
#include "jail_engine/texture.h"
#include "jail_engine/utils.h"
#include "const.h"
#include <vector>
#ifndef GAME_OVER_H
#define GAME_OVER_H
using namespace std;
class GameOver
{
private:
@@ -23,24 +26,25 @@ private:
Screen *screen; // Objeto encargado de dibujar en pantalla
Resource *resource; // Objeto con los recursos
Asset *asset; // Objeto con los ficheros de recursos
Input *input; // Objeto pata gestionar la entrada
options_t *options; // Puntero a las opciones del juego
SDL_Event *eventHandler; // Manejador de eventos
Text *text; // Objeto para escribir texto en pantalla
AnimatedSprite *playerSprite; // Sprite con el jugador
AnimatedSprite *tvSprite; // Sprite con el televisor
section_t *section; // Estado del bucle principal para saber si continua o se sale
// Variables
int preCounter; // Contador previo
int counter; // Contador
section_t section; // Estado del bucle principal para saber si continua o se sale
Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa
Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles del programa
std::vector<color_t> colors; // Vector con los colores para el fade
color_t color; // Color usado para el texto y los sprites
int endSection; // Contador: cuando acaba la sección
int iniFade; // Contador: cuando emiepza el fade
int fadeLenght; // Contador: duración del fade
JA_Music_t* music; // Musica que suena durante el juego
int preCounter; // Contador previo
int counter; // Contador
Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa
Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles del programa
vector<color_t> colors; // Vector con los colores para el fade
color_t color; // Color usado para el texto y los sprites
int endSection; // Contador: cuando acaba la sección
int iniFade; // Contador: cuando emiepza el fade
int fadeLenght; // Contador: duración del fade
JA_Music_t *music; // Musica que suena durante el juego
// Actualiza el objeto
void update();
@@ -51,6 +55,9 @@ private:
// Comprueba el manejador de eventos
void checkEventHandler();
// Comprueba las entradas
void checkInput();
// Actualiza el color usado para renderizar los textos e imagenes
void updateColor();
@@ -65,13 +72,13 @@ private:
public:
// Constructor
GameOver(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *asset, options_t *options);
GameOver(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *asset, Input *input, options_t *options, section_t *section);
// Destructor
~GameOver();
// Bucle principal
section_t run();
void run();
};
#endif

View File

@@ -1,14 +1,16 @@
#include "intro.h"
// Constructor
Intro::Intro(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *asset, options_t *options)
Intro::Intro(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *asset, Input *input, options_t *options, section_t *section)
{
// Copia la dirección de los objetos
this->resource = resource;
this->renderer = renderer;
this->screen = screen;
this->asset = asset;
this->input = input;
this->options = options;
this->section = section;
// Reserva memoria para los punteros
eventHandler = new SDL_Event();
@@ -31,8 +33,8 @@ Intro::Intro(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *
// Inicializa variables
preCounter = 0;
counter = 0;
section.name = SECTION_PROG_INTRO;
section.subsection = 0;
section->name = SECTION_PROG_INTRO;
section->subsection = 0;
ticks = 0;
ticksSpeed = 15;
loadCounter = 0;
@@ -82,66 +84,57 @@ void Intro::checkEventHandler()
// Evento de salida de la aplicación
if (eventHandler->type == SDL_QUIT)
{
section.name = SECTION_PROG_QUIT;
section->name = SECTION_PROG_QUIT;
break;
}
}
}
// Comprueba las teclas que se han pulsado
if ((eventHandler->type == SDL_KEYDOWN && eventHandler->key.repeat == 0) || (eventHandler->type == SDL_JOYBUTTONDOWN))
{
switch (eventHandler->key.keysym.scancode)
{
case SDL_SCANCODE_ESCAPE:
section.name = SECTION_PROG_QUIT;
break;
// Comprueba las entradas
void Intro::checkInput()
{
case SDL_SCANCODE_B:
screen->switchBorder();
resource->reLoadTextures();
break;
if (input->checkInput(input_exit, REPEAT_FALSE))
{
section->name = SECTION_PROG_QUIT;
}
case SDL_SCANCODE_F:
screen->switchVideoMode();
resource->reLoadTextures();
break;
else if (input->checkInput(input_toggle_border, REPEAT_FALSE))
{
screen->switchBorder();
}
case SDL_SCANCODE_F1:
screen->setWindowSize(1);
resource->reLoadTextures();
break;
else if (input->checkInput(input_window_fullscreen, REPEAT_FALSE))
{
screen->switchVideoMode();
}
case SDL_SCANCODE_F2:
screen->setWindowSize(2);
resource->reLoadTextures();
break;
else if (input->checkInput(input_window_dec_size, REPEAT_FALSE))
{
screen->decWindowSize();
}
case SDL_SCANCODE_F3:
screen->setWindowSize(3);
resource->reLoadTextures();
break;
else if (input->checkInput(input_window_inc_size, REPEAT_FALSE))
{
screen->incWindowSize();
}
case SDL_SCANCODE_F4:
screen->setWindowSize(4);
resource->reLoadTextures();
break;
else if (input->checkInput(input_swap_palette, REPEAT_FALSE))
{
switchPalette();
}
case SDL_SCANCODE_F5:
//switchPalette();
break;
default:
section.name = SECTION_PROG_TITLE;
section.subsection = 0;
break;
}
}
else if (input->checkInput(input_pause, REPEAT_FALSE) || input->checkInput(input_accept, REPEAT_FALSE) || input->checkInput(input_jump, REPEAT_FALSE))
{
section->name = SECTION_PROG_TITLE;
section->subsection = 0;
}
}
// Gestiona el contador de carga
void Intro::updateLoad()
{
// Primera parte de la carga, la parte en blanco ynegro
// Primera parte de la carga, la parte en blanco y negro
if (loadingFirstPart)
{
// Cada 5 pasos el loadCounter se incrementa en uno
@@ -179,8 +172,8 @@ void Intro::updateLoad()
// Comprueba si ha terminado la intro
if (loadCounter >= 768)
{
section.name = SECTION_PROG_TITLE;
section.subsection = 0;
section->name = SECTION_PROG_TITLE;
section->subsection = 0;
JA_StopMusic();
}
}
@@ -206,14 +199,17 @@ void Intro::renderLoad()
// Actualiza las variables
void Intro::update()
{
// Comprueba el manejador de eventos
checkEventHandler();
// Comprueba que la diferencia de ticks sea mayor a la velocidad del juego
if (SDL_GetTicks() - ticks > ticksSpeed)
{
// Actualiza el contador de ticks
ticks = SDL_GetTicks();
// Comprueba el manejador de eventos
checkEventHandler();
// Comprueba las entradas
checkInput();
// Gestiona el contador interno
updateCounter();
@@ -240,20 +236,24 @@ void Intro::render()
}
// Bucle para el logo del juego
section_t Intro::run()
void Intro::run()
{
// Inicia el sonido de carga
JA_SetVolume(64);
JA_PlayMusic(loadingSound1);
while (section.name == SECTION_PROG_INTRO)
// Limpia la pantalla
screen->start();
screen->clean();
screen->blit();
while (section->name == SECTION_PROG_INTRO)
{
update();
render();
}
JA_SetVolume(128);
return section;
}
// Cambia la paleta
@@ -271,4 +271,45 @@ void Intro::switchPalette()
sprite1->setTexture(resource->getTexture("loading_screen_bn.png"));
sprite2->setTexture(resource->getTexture("loading_screen_color.png"));
}
recreateLoadingScreen();
}
// Reconstruye la pantalla de carga
void Intro::recreateLoadingScreen()
{
// Prepara para empezar a dibujar en la textura de juego
screen->start();
// Primera parte de la carga, la parte en blanco y negro
if (loadingFirstPart)
{
const int numSteps = 5;
const int step = 51;
for (int i = 0; i <= counter; i++)
{
loadCounter = i / numSteps;
loadRect.x = step * (i % numSteps);
loadRect.y = lineIndex[loadCounter];
sprite1->setSpriteClip(loadRect);
sprite1->setRect(loadRect);
sprite1->render();
}
}
// Segunda parte de la carga, la parte de los bloques en color
else
{
for (int i = 0; i <= loadCounter; i++)
{
loadRect.x = (i * 8) % 256;
loadRect.y = (i / 32) * 8;
sprite2->setSpriteClip(loadRect);
sprite2->setRect(loadRect);
sprite2->render();
}
}
// Vuelca el contenido del renderizador en pantalla
screen->blit();
}

View File

@@ -1,17 +1,18 @@
#pragma once
#include <SDL2/SDL.h>
#include "common/asset.h"
#include "common/jail_audio.h"
#include "common/resource.h"
#include "common/screen.h"
#include "common/sprite.h"
#include "common/utils.h"
#include "jail_engine/asset.h"
#include "jail_engine/input.h"
#include "jail_engine/jail_audio.h"
#include "jail_engine/resource.h"
#include "jail_engine/screen.h"
#include "jail_engine/sprite.h"
#include "jail_engine/utils.h"
#include "const.h"
#include <vector>
#include <string>
#include "common/text.h"
#include "jail_engine/text.h"
#ifndef INTRO_H
#define INTRO_H
@@ -24,26 +25,27 @@ private:
Screen *screen; // Objeto encargado de dibujar en pantalla
Resource *resource; // Objeto con los recursos
Asset *asset; // Objeto con los ficheros de recursos
Input *input; // Objeto pata gestionar la entrada
Texture *loadingScreenTexture1; // Textura con la pantalla de carga en blanco y negro
Texture *loadingScreenTexture2; // Textura con la pantalla de carga en color
SDL_Event *eventHandler; // Manejador de eventos
Sprite *sprite1; // Sprite para manejar la textura loadingScreenTexture1
Sprite *sprite2; // Sprite para manejar la textura loadingScreenTexture2
options_t *options; // Puntero a las opciones del juego
section_t *section; // Estado del bucle principal para saber si continua o se sale
// Variables
int preCounter; // Contador previo para realizar una pausa inicial
int counter; // Contador
section_t section; // Estado del bucle principal para saber si continua o se sale
Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa
Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles del programa
int loadCounter; // Contador para controlar las cargas
bool loadingFirstPart; // Para saber en que parte de la carga se encuentra
JA_Music_t* loadingSound1; // Sonidos para imitar la carga tipo spectrum
JA_Music_t* loadingSound2; // Sonidos para imitar la carga tipo spectrum
JA_Music_t* loadingSound3; // Sonidos para imitar la carga tipo spectrum
int lineIndex[192]; // El orden en el que se procesan las 192 lineas de la pantalla de carga
SDL_Rect loadRect; // Rectangulo para dibujar la pantalla de carga
int preCounter; // Contador previo para realizar una pausa inicial
int counter; // Contador
Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa
Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles del programa
int loadCounter; // Contador para controlar las cargas
bool loadingFirstPart; // Para saber en que parte de la carga se encuentra
JA_Music_t *loadingSound1; // Sonidos para imitar la carga tipo spectrum
JA_Music_t *loadingSound2; // Sonidos para imitar la carga tipo spectrum
JA_Music_t *loadingSound3; // Sonidos para imitar la carga tipo spectrum
int lineIndex[192]; // El orden en el que se procesan las 192 lineas de la pantalla de carga
SDL_Rect loadRect; // Rectangulo para dibujar la pantalla de carga
// Actualiza las variables
void update();
@@ -54,6 +56,9 @@ private:
// Comprueba el manejador de eventos
void checkEventHandler();
// Comprueba las entradas
void checkInput();
// Gestiona el contador interno
void updateCounter();
@@ -66,15 +71,18 @@ private:
// Cambia la paleta
void switchPalette();
// Reconstruye la pantalla de carga
void recreateLoadingScreen();
public:
// Constructor
Intro(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *asset, options_t *options);
Intro(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *asset, Input *input, options_t *options, section_t *section);
// Destructor
~Intro();
// Bucle principal
section_t run();
void run();
};
#endif

View File

@@ -1,25 +1,27 @@
#pragma once
#include <SDL2/SDL.h>
#include "common/asset.h"
#include "common/sprite.h"
#include "common/utils.h"
#include "jail_engine/asset.h"
#include "jail_engine/sprite.h"
#include "jail_engine/utils.h"
#include <string>
#ifndef ITEM_H
#define ITEM_H
using namespace std;
struct item_t
{
SDL_Renderer *renderer; // El renderizador de la ventana
Texture *texture; // Textura con los graficos del item
std::string tileSetFile; // Ruta al fichero con los graficos del item
int x; // Posicion del item en pantalla
int y; // Posicion del item en pantalla
int tile; // Numero de tile dentro de la textura
int counter; // Contador inicial. Es el que lo hace cambiar de color
color_t color1; // Uno de los dos colores que se utiliza para el item
color_t color2; // Uno de los dos colores que se utiliza para el item
SDL_Renderer *renderer; // El renderizador de la ventana
Texture *texture; // Textura con los graficos del item
string tileSetFile; // Ruta al fichero con los graficos del item
int x; // Posicion del item en pantalla
int y; // Posicion del item en pantalla
int tile; // Numero de tile dentro de la textura
int counter; // Contador inicial. Es el que lo hace cambiar de color
color_t color1; // Uno de los dos colores que se utiliza para el item
color_t color2; // Uno de los dos colores que se utiliza para el item
};
class Item
@@ -29,10 +31,10 @@ private:
Sprite *sprite; // Sprite del objeto
// Variables
std::vector<color_t> color; // Vector con los colores del objeto
int counter; // Contador interno
SDL_Rect collider; // Rectangulo de colisión
int colorChangeSpeed; // Cuanto mas alto, mas tarda en cambiar de color
vector<color_t> color; // Vector con los colores del objeto
int counter; // Contador interno
SDL_Rect collider; // Rectangulo de colisión
int colorChangeSpeed; // Cuanto mas alto, mas tarda en cambiar de color
public:
// Constructor

View File

@@ -7,7 +7,7 @@ ItemTracker::~ItemTracker()
}
// Comprueba si el objeto ya ha sido cogido
bool ItemTracker::hasBeenPicked(std::string name, SDL_Point pos)
bool ItemTracker::hasBeenPicked(string name, SDL_Point pos)
{
bool success = false;
@@ -26,7 +26,7 @@ bool ItemTracker::hasBeenPicked(std::string name, SDL_Point pos)
}
// Añade el objeto a la lista de objetos cogidos
void ItemTracker::addItem(std::string name, SDL_Point pos)
void ItemTracker::addItem(string name, SDL_Point pos)
{
// Comprueba si el objeto no ha sido recogido con anterioridad
if (!hasBeenPicked(name, pos))
@@ -50,7 +50,7 @@ void ItemTracker::addItem(std::string name, SDL_Point pos)
}
// Busca una entrada en la lista por nombre
int ItemTracker::findByName(std::string name)
int ItemTracker::findByName(string name)
{
int i = 0;
@@ -71,7 +71,7 @@ int ItemTracker::findByPos(int index, SDL_Point pos)
{
int i = 0;
for (auto l:list[index].pos)
for (auto l : list[index].pos)
{
if ((l.x == pos.x) && (l.y == pos.y))
{

View File

@@ -1,26 +1,28 @@
#pragma once
#include <SDL2/SDL.h>
#include "common/utils.h"
#include "jail_engine/utils.h"
#include <string>
#include <vector>
#ifndef ITEM_TRACKER_H
#define ITEM_TRACKER_H
using namespace std;
struct item_tracker_t
{
std::string name; // Nombre de la habitación donde se encuentra el objeto
std::vector<SDL_Point> pos; // Lista de objetos cogidos de la habitación
string name; // Nombre de la habitación donde se encuentra el objeto
vector<SDL_Point> pos; // Lista de objetos cogidos de la habitación
};
class ItemTracker
{
private:
// Variables
std::vector<item_tracker_t> list; // Lista con todos los objetos recogidos
vector<item_tracker_t> list; // Lista con todos los objetos recogidos
// Busca una entrada en la lista por nombre
int findByName(std::string name);
int findByName(string name);
// Busca una entrada en la lista por posición
int findByPos(int index, SDL_Point pos);
@@ -30,10 +32,10 @@ public:
~ItemTracker();
// Comprueba si el objeto ya ha sido cogido
bool hasBeenPicked(std::string name, SDL_Point pos);
bool hasBeenPicked(string name, SDL_Point pos);
// Añade el objeto a la lista de objetos cogidos
void addItem(std::string name, SDL_Point pos);
void addItem(string name, SDL_Point pos);
};
#endif

View File

@@ -11,12 +11,12 @@ Input::Input(std::string file)
keyBindings_t kb;
kb.scancode = 0;
kb.active = false;
keyBindings.resize(17, kb);
keyBindings.resize(input_number_of_inputs, kb);
GameControllerBindings_t gcb;
gcb.button = SDL_CONTROLLER_BUTTON_INVALID;
gcb.active = false;
gameControllerBindings.resize(17, gcb);
gameControllerBindings.resize(input_number_of_inputs, gcb);
verbose = true;
enabled = true;

View File

@@ -7,23 +7,31 @@
#ifndef INPUT_H
#define INPUT_H
#define INPUT_NULL 0
#define INPUT_UP 1
#define INPUT_DOWN 2
#define INPUT_LEFT 3
#define INPUT_RIGHT 4
#define INPUT_ACCEPT 5
#define INPUT_CANCEL 6
#define INPUT_BUTTON_1 7
#define INPUT_BUTTON_2 8
#define INPUT_BUTTON_3 9
#define INPUT_BUTTON_4 10
#define INPUT_BUTTON_5 11
#define INPUT_BUTTON_6 12
#define INPUT_BUTTON_7 13
#define INPUT_BUTTON_8 14
#define INPUT_BUTTON_PAUSE 15
#define INPUT_BUTTON_ESCAPE 16
enum inputs_e
{
// Inputs obligatorios
input_null,
input_up,
input_down,
input_left,
input_right,
input_pause,
input_exit,
input_accept,
input_cancel,
// Inputs personalizados
input_jump,
input_window_fullscreen,
input_window_inc_size,
input_window_dec_size,
input_toggle_border,
input_switch_music,
input_swap_palette,
// Input obligatorio
input_number_of_inputs
};
#define REPEAT_TRUE true
#define REPEAT_FALSE false
@@ -81,7 +89,7 @@ public:
void bindGameControllerButton(Uint8 input, SDL_GameControllerButton button);
// Comprueba si un input esta activo
bool checkInput(Uint8 input, bool repeat, int device = INPUT_USE_ANY, int index = 0);
bool checkInput(Uint8 input, bool repeat = true, int device = INPUT_USE_ANY, int index = 0);
// Comprueba si hay almenos un input activo
bool checkAnyInput(int device = INPUT_USE_ANY, int index = 0);

View File

@@ -850,7 +850,7 @@ void Menu::setDefaultActionWhenCancel(int item)
// Gestiona la entrada de teclado y mando durante el menu
void Menu::checkInput()
{
if (input->checkInput(INPUT_UP, REPEAT_FALSE))
if (input->checkInput(input_up, REPEAT_FALSE))
{
if (decreaseSelectorIndex())
{
@@ -861,7 +861,7 @@ void Menu::checkInput()
}
}
if (input->checkInput(INPUT_DOWN, REPEAT_FALSE))
if (input->checkInput(input_down, REPEAT_FALSE))
{
if (increaseSelectorIndex())
{
@@ -872,7 +872,7 @@ void Menu::checkInput()
}
}
if (input->checkInput(INPUT_ACCEPT, REPEAT_FALSE))
if (input->checkInput(input_accept, REPEAT_FALSE))
{
itemSelected = selector.index;
if (soundAccept)
@@ -881,7 +881,7 @@ void Menu::checkInput()
}
}
if (input->checkInput(INPUT_CANCEL, REPEAT_FALSE))
if (input->checkInput(input_cancel, REPEAT_FALSE))
{
itemSelected = defaultActionWhenCancel;
if (soundCancel)

View File

@@ -4,7 +4,7 @@
#include <iostream>
// Constructor
Notify::Notify(SDL_Renderer *renderer, std::string bitmapFile, std::string textFile, std::string soundFile, options_t *options)
Notify::Notify(SDL_Renderer *renderer, std::string iconFile, std::string bitmapFile, std::string textFile, std::string soundFile, options_t *options)
{
// Inicializa variables
this->renderer = renderer;
@@ -13,8 +13,9 @@ Notify::Notify(SDL_Renderer *renderer, std::string bitmapFile, std::string textF
waitTime = 300;
// Crea objetos
texture = new Texture(renderer, bitmapFile);
text = new Text(textFile, texture, renderer);
iconTexture = new Texture(renderer, iconFile);
textTexture = new Texture(renderer, bitmapFile);
text = new Text(textFile, textTexture, renderer);
sound = JA_LoadSound(soundFile.c_str());
}
@@ -22,7 +23,8 @@ Notify::Notify(SDL_Renderer *renderer, std::string bitmapFile, std::string textF
Notify::~Notify()
{
// Libera la memoria de los objetos
delete texture;
delete textTexture;
delete iconTexture;
delete text;
JA_DeleteSound(sound);
@@ -124,12 +126,15 @@ void Notify::clearFinishedNotifications()
}
// Muestra una notificación de texto por pantalla;
void Notify::showText(std::string text)
void Notify::showText(std::string text1, std::string text2, int icon)
{
// Inicializa variables
const int width = this->text->lenght(text) + (this->text->getCharacterSize() * 2);
const int height = this->text->getCharacterSize() * 2;
const int padding = (this->text->getCharacterSize() / 2);
const int iconSize = 16;
const int padding = text->getCharacterSize();
const int iconSpace = icon >= 0 ? iconSize + padding : 0;
const std::string txt = text1.length() > text2.length() ? text1 : text2;
const int width = text->lenght(txt) + (padding * 2) + iconSpace;
const int height = (text->getCharacterSize() * 2) + (padding * 2);
// Posición horizontal
int despH = 0;
@@ -178,7 +183,8 @@ void Notify::showText(std::string text)
n.travelDist = travelDist;
n.counter = 0;
n.state = ns_rising;
n.text = text;
n.text1 = text1;
n.text2 = text2;
if (options->notifications.posV == pos_top)
{
n.rect = {despH, offset - travelDist, width, height};
@@ -191,14 +197,52 @@ void Notify::showText(std::string text)
// Crea la textura
n.texture = new Texture(renderer);
n.texture->createBlank(renderer, width, height, SDL_TEXTUREACCESS_TARGET);
n.texture->setAsRenderTarget(renderer);
SDL_SetRenderDrawColor(renderer, bgColor.r, bgColor.g, bgColor.b, 255);
SDL_RenderClear(renderer);
n.texture->setBlendMode(SDL_BLENDMODE_BLEND);
this->text->writeDX(TXT_CENTER | TXT_STROKE, width / 2, padding, text, 1, {255, 255, 255}, 1, {0, 0, 0});
// 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;
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);
// Dibuja el icono de la notificación
if (icon >= 0)
{
Sprite *sp = new Sprite({0, 0, iconSize, iconSize}, iconTexture, renderer);
sp->setPos({padding, padding, iconSize, iconSize});
sp->setSpriteClip({iconSize * (icon % 10), iconSize * (icon / 10), iconSize, iconSize});
sp->render();
delete sp;
}
// Escribe el texto de la notificación
color_t color = {255, 255, 255};
if (text2 != "")
{ // Dos lineas de texto
text->writeColored(padding + iconSpace, padding, text1, color);
text->writeColored(padding + iconSpace, padding + text->getCharacterSize() + 1, text2, color);
}
else
{ // Una linea de texto
text->writeColored(padding + iconSpace, (height / 2) - (text->getCharacterSize() / 2), text1, color);
}
// Deja de dibujar en la textura
SDL_SetRenderTarget(renderer, nullptr);
// Crea el sprite
// Crea el sprite de la notificación
n.sprite = new Sprite(n.rect, n.texture, renderer);
// Añade la notificación a la lista

View File

@@ -36,7 +36,8 @@ private:
struct notification_t
{
std::string text;
std::string text1;
std::string text2;
int counter;
notification_state_e state;
notification_position_e position;
@@ -49,7 +50,8 @@ private:
// Objetos y punteros
SDL_Renderer *renderer; // El renderizador de la ventana
Texture *texture; // Textura para la fuente de las notificaciones
Texture *textTexture; // Textura para la fuente de las notificaciones
Texture *iconTexture; // Textura para los iconos de las notificaciones
Text *text; // Objeto para dibujar texto
options_t *options; // Variable con todas las opciones del programa
@@ -57,7 +59,7 @@ private:
color_t bgColor; // Color de fondo de las notificaciones
int waitTime; // Tiempo que se ve la notificación
std::vector<notification_t> notifications; // La lista de notificaciones activas
JA_Sound_t* sound; // Sonido a reproducir cuando suena la notificación
JA_Sound_t *sound; // Sonido a reproducir cuando suena la notificación
// Elimina las notificaciones finalizadas
void clearFinishedNotifications();
@@ -70,13 +72,13 @@ public:
void update();
// Constructor
Notify(SDL_Renderer *renderer, std::string bitmapFile, std::string textFile, std::string soundFile, options_t *options);
Notify(SDL_Renderer *renderer, std::string iconFile, std::string bitmapFile, std::string textFile, std::string soundFile, options_t *options);
// Destructor
~Notify();
// Muestra una notificación de texto por pantalla;
void showText(std::string text);
void showText(std::string text1 = "", std::string text2 = "", int icon = -1);
// Indica si hay notificaciones activas
bool active();

View File

@@ -12,7 +12,7 @@ Screen::Screen(SDL_Window *window, SDL_Renderer *renderer, Asset *asset, options
this->asset = asset;
// Crea los objetos
notify = new Notify(renderer, asset->get("smb2.png"), asset->get("smb2.txt"), asset->get("notify.wav"), options);
notify = new Notify(renderer, asset->get("notify.png"), asset->get("smb2.png"), asset->get("smb2.txt"), asset->get("notify.wav"), options);
gameCanvasWidth = options->gameWidth;
gameCanvasHeight = options->gameHeight;
@@ -48,6 +48,7 @@ Screen::Screen(SDL_Window *window, SDL_Renderer *renderer, Asset *asset, options
Screen::~Screen()
{
delete notify;
SDL_DestroyTexture(gameCanvas);
}
// Limpia la pantalla
@@ -86,15 +87,18 @@ void Screen::blit()
// Establece el modo de video
void Screen::setVideoMode(int videoMode)
{
// Muestra el puntero
SDL_ShowCursor(SDL_ENABLE);
// Aplica el modo de video
SDL_SetWindowFullscreen(window, videoMode);
// Si está activo el modo ventana quita el borde
if (videoMode == 0)
{
// Muestra el puntero
SDL_ShowCursor(SDL_ENABLE);
// Esconde la ventana
//SDL_HideWindow(window);
if (options->borderEnabled)
{
windowWidth = gameCanvasWidth + borderWidth;
@@ -109,9 +113,12 @@ void Screen::setVideoMode(int videoMode)
dest = {0, 0, gameCanvasWidth, gameCanvasHeight};
}
// Modifica el tamaño del renderizador y de la ventana
SDL_RenderSetLogicalSize(renderer, windowWidth, windowHeight);
// Modifica el tamaño de la ventana
SDL_SetWindowSize(window, windowWidth * options->windowSize, windowHeight * options->windowSize);
SDL_SetWindowPosition(window, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED);
// Muestra la ventana
//SDL_ShowWindow(window);
}
// Si está activo el modo de pantalla completa añade el borde
@@ -162,11 +169,11 @@ void Screen::setVideoMode(int videoMode)
dest.h = windowHeight;
dest.x = dest.y = 0;
}
// Modifica el tamaño del renderizador
SDL_RenderSetLogicalSize(renderer, windowWidth, windowHeight);
}
// Modifica el tamaño del renderizador
SDL_RenderSetLogicalSize(renderer, windowWidth, windowHeight);
// Actualiza las opciones
options->videoMode = videoMode;
options->screen.windowWidth = windowWidth;
@@ -190,6 +197,22 @@ void Screen::setWindowSize(int size)
setVideoMode(0);
}
// Reduce el tamaño de la ventana
void Screen::decWindowSize()
{
--options->windowSize;
options->windowSize = std::max(options->windowSize, 1);
setVideoMode(0);
}
// Aumenta el tamaño de la ventana
void Screen::incWindowSize()
{
++options->windowSize;
options->windowSize = std::min(options->windowSize, 4);
setVideoMode(0);
}
// Cambia el color del borde
void Screen::setBorderColor(color_t color)
{
@@ -370,9 +393,9 @@ void Screen::updateNotifier()
}
// Muestra una notificación de texto por pantalla;
void Screen::showNotification(std::string text)
void Screen::showNotification(std::string text1, std::string text2, int icon)
{
notify->showText(text);
notify->showText(text1, text2, icon);
}
// Dibuja las notificaciones
@@ -383,9 +406,9 @@ void Screen::renderNotifications()
return;
}
//SDL_RenderSetLogicalSize(renderer, notificationLogicalWidth, notificationLogicalHeight);
SDL_RenderSetLogicalSize(renderer, notificationLogicalWidth, notificationLogicalHeight);
notify->render();
//SDL_RenderSetLogicalSize(renderer, windowWidth, windowHeight);
SDL_RenderSetLogicalSize(renderer, windowWidth, windowHeight);
}
// Establece el tamaño de las notificaciones

View File

@@ -4,6 +4,7 @@
#include "asset.h"
#include "notify.h"
#include "utils.h"
#include "../const.h"
#include <vector>
#ifndef SCREEN_H
@@ -94,6 +95,12 @@ public:
// Cambia el tamaño de la ventana
void setWindowSize(int size);
// Reduce el tamaño de la ventana
void decWindowSize();
// Aumenta el tamaño de la ventana
void incWindowSize();
// Cambia el color del borde
void setBorderColor(color_t color);
@@ -132,7 +139,7 @@ public:
void updateNotifier();
// Muestra una notificación de texto por pantalla;
void showNotification(std::string text);
void showNotification(std::string text1 = "", std::string text2 = "", int icon = -1);
};
#endif

View File

@@ -2,14 +2,16 @@
#include <iostream>
// Constructor
Logo::Logo(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *asset, options_t *options, int subsection)
Logo::Logo(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *asset, Input *input, options_t *options, section_t *section)
{
// Copia la dirección de los objetos
this->resource = resource;
this->renderer = renderer;
this->screen = screen;
this->asset = asset;
this->input = input;
this->options = options;
this->section = section;
// Reserva memoria para los punteros
eventHandler = new SDL_Event();
@@ -37,8 +39,7 @@ Logo::Logo(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *as
// Inicializa variables
counter = 0;
section.name = SECTION_PROG_LOGO;
section.subsection = subsection;
section->name = SECTION_PROG_LOGO;
ticks = 0;
ticksSpeed = 15;
initFade = 300;
@@ -46,7 +47,7 @@ Logo::Logo(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *as
postLogo = 20;
// Inicializa el vector de colores
const std::vector<std::string> vColors = {"black", "blue", "red", "magenta", "green", "cyan", "yellow", "bright_white"};
const vector<string> vColors = {"black", "blue", "red", "magenta", "green", "cyan", "yellow", "bright_white"};
for (auto v : vColors)
{
color.push_back(stringToColor(options->palette, v));
@@ -77,59 +78,49 @@ void Logo::checkEventHandler()
// Evento de salida de la aplicación
if (eventHandler->type == SDL_QUIT)
{
section.name = SECTION_PROG_QUIT;
section->name = SECTION_PROG_QUIT;
break;
}
}
}
// Comprueba las teclas que se han pulsado
if ((eventHandler->type == SDL_KEYUP && eventHandler->key.repeat == 0) || (eventHandler->type == SDL_JOYBUTTONUP))
{
switch (eventHandler->key.keysym.scancode)
{
case SDL_SCANCODE_ESCAPE:
section.name = SECTION_PROG_QUIT;
break;
// Comprueba las entradas
void Logo::checkInput()
{
if (input->checkInput(input_exit, REPEAT_FALSE))
{
section->name = SECTION_PROG_TITLE;
}
case SDL_SCANCODE_B:
screen->switchBorder();
resource->reLoadTextures();
break;
else if (input->checkInput(input_toggle_border, REPEAT_FALSE))
{
screen->switchBorder();
}
case SDL_SCANCODE_F:
screen->switchVideoMode();
resource->reLoadTextures();
break;
else if (input->checkInput(input_window_fullscreen, REPEAT_FALSE))
{
screen->switchVideoMode();
}
case SDL_SCANCODE_F1:
screen->setWindowSize(1);
resource->reLoadTextures();
break;
else if (input->checkInput(input_window_dec_size, REPEAT_FALSE))
{
screen->decWindowSize();
}
case SDL_SCANCODE_F2:
screen->setWindowSize(2);
resource->reLoadTextures();
break;
else if (input->checkInput(input_window_inc_size, REPEAT_FALSE))
{
screen->incWindowSize();
}
case SDL_SCANCODE_F3:
screen->setWindowSize(3);
resource->reLoadTextures();
break;
else if (input->checkInput(input_swap_palette, REPEAT_FALSE))
{
switchPalette();
}
case SDL_SCANCODE_F4:
screen->setWindowSize(4);
resource->reLoadTextures();
break;
case SDL_SCANCODE_F5:
switchPalette();
break;
default:
section.subsection = SUBSECTION_LOGO_TO_TITLE;
endSection();
break;
}
}
else if (input->checkInput(input_pause, REPEAT_FALSE) || input->checkInput(input_accept, REPEAT_FALSE) || input->checkInput(input_jump, REPEAT_FALSE))
{
section->subsection = SUBSECTION_LOGO_TO_TITLE;
endSection();
}
}
@@ -175,26 +166,32 @@ void Logo::updateTextureColors()
{
texture2->setColor(color[0].r, color[0].g, color[0].b);
}
else if (counter == ini + inc * 1)
{
texture2->setColor(color[1].r, color[1].g, color[1].b);
}
else if (counter == ini + inc * 2)
{
texture2->setColor(color[2].r, color[2].g, color[2].b);
}
else if (counter == ini + inc * 3)
{
texture2->setColor(color[3].r, color[3].g, color[3].b);
}
else if (counter == ini + inc * 4)
{
texture2->setColor(color[4].r, color[4].g, color[4].b);
}
else if (counter == ini + inc * 5)
{
texture2->setColor(color[5].r, color[5].g, color[5].b);
}
else if (counter == ini + inc * 6)
{
texture2->setColor(color[6].r, color[6].g, color[6].b);
@@ -210,31 +207,37 @@ void Logo::updateTextureColors()
texture->setColor(color[6].r, color[6].g, color[6].b);
texture2->setColor(color[6].r, color[6].g, color[6].b);
}
else if (counter == initFade + inc * 1)
{
texture->setColor(color[5].r, color[5].g, color[5].b);
texture2->setColor(color[5].r, color[5].g, color[5].b);
}
else if (counter == initFade + inc * 2)
{
texture->setColor(color[4].r, color[4].g, color[4].b);
texture2->setColor(color[4].r, color[4].g, color[4].b);
}
else if (counter == initFade + inc * 3)
{
texture->setColor(color[3].r, color[3].g, color[3].b);
texture2->setColor(color[3].r, color[3].g, color[3].b);
}
else if (counter == initFade + inc * 4)
{
texture->setColor(color[2].r, color[2].g, color[2].b);
texture2->setColor(color[2].r, color[2].g, color[2].b);
}
else if (counter == initFade + inc * 5)
{
texture->setColor(color[1].r, color[1].g, color[1].b);
texture2->setColor(color[1].r, color[1].g, color[1].b);
}
else if (counter == initFade + inc * 6)
{
texture->setColor(color[0].r, color[0].g, color[0].b);
@@ -254,6 +257,9 @@ void Logo::update()
// Comprueba el manejador de eventos
checkEventHandler();
// Comprueba las entradas
checkInput();
// Incrementa el contador
counter++;
@@ -295,18 +301,16 @@ void Logo::render()
}
// Bucle para el logo del juego
section_t Logo::run()
void Logo::run()
{
// Detiene la música
JA_StopMusic();
while (section.name == SECTION_PROG_LOGO)
while (section->name == SECTION_PROG_LOGO)
{
update();
render();
}
return section;
}
// Cambia la paleta
@@ -318,5 +322,5 @@ void Logo::switchPalette()
// Termina la sección
void Logo::endSection()
{
section.name = SECTION_PROG_ENTER_ID;
section->name = SECTION_PROG_ENTER_ID;
}

View File

@@ -1,42 +1,46 @@
#pragma once
#include <SDL2/SDL.h>
#include "common/asset.h"
#include "common/jail_audio.h"
#include "common/resource.h"
#include "common/screen.h"
#include "common/sprite.h"
#include "common/utils.h"
#include "jail_engine/asset.h"
#include "jail_engine/input.h"
#include "jail_engine/jail_audio.h"
#include "jail_engine/resource.h"
#include "jail_engine/screen.h"
#include "jail_engine/sprite.h"
#include "jail_engine/utils.h"
#include "const.h"
#include <vector>
#ifndef LOGO_H
#define LOGO_H
using namespace std;
class Logo
{
private:
// Objetos y punteros
SDL_Renderer *renderer; // El renderizador de la ventana
Screen *screen; // Objeto encargado de dibujar en pantalla
Resource *resource; // Objeto con los recursos
Asset *asset; // Objeto con los ficheros de recursos
Texture *texture; // Textura con los graficos "JAILGAMES"
Texture *texture2; // Textura con los graficos "Since 1998"
SDL_Event *eventHandler; // Manejador de eventos
std::vector<Sprite *> sprite; // Vector con los sprites de cada linea que forman el bitmap JAILGAMES
Sprite *sprite2; // Sprite para manejar la textura2
options_t *options; // Puntero a las opciones del juego
SDL_Renderer *renderer; // El renderizador de la ventana
Screen *screen; // Objeto encargado de dibujar en pantalla
Resource *resource; // Objeto con los recursos
Asset *asset; // Objeto con los ficheros de recursos
Input *input; // Objeto pata gestionar la entrada
Texture *texture; // Textura con los graficos "JAILGAMES"
Texture *texture2; // Textura con los graficos "Since 1998"
SDL_Event *eventHandler; // Manejador de eventos
vector<Sprite *> sprite; // Vector con los sprites de cada linea que forman el bitmap JAILGAMES
Sprite *sprite2; // Sprite para manejar la textura2
options_t *options; // Puntero a las opciones del juego
section_t *section; // Estado del bucle principal para saber si continua o se sale
// Variables
std::vector<color_t> color; // Vector con los colores para el fade
int counter; // Contador
section_t section; // Estado del bucle principal para saber si continua o se sale
Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa
Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles del programa
int initFade; // Tiempo del contador cuando inicia el fade a negro
int endLogo; // Tiempo del contador para terminar el logo
int postLogo; // Tiempo que dura el logo con el fade al maximo
vector<color_t> color; // Vector con los colores para el fade
int counter; // Contador
Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa
Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles del programa
int initFade; // Tiempo del contador cuando inicia el fade a negro
int endLogo; // Tiempo del contador para terminar el logo
int postLogo; // Tiempo que dura el logo con el fade al maximo
// Actualiza las variables
void update();
@@ -47,6 +51,9 @@ private:
// Comprueba el manejador de eventos
void checkEventHandler();
// Comprueba las entradas
void checkInput();
// Gestiona el logo de JAILGAME
void updateJAILGAMES();
@@ -61,13 +68,13 @@ private:
public:
// Constructor
Logo(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *asset, options_t *options, int subsection);
Logo(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *asset, Input *input, options_t *options, section_t *section);
// Destructor
~Logo();
// Bucle principal
section_t run();
void run();
};
#endif

View File

@@ -8,9 +8,11 @@ Empezado en Castalla el 01/07/2022.
#include "director.h"
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
std::cout << "Starting the game...\n\n";
cout << "Starting the game..." << endl;
// Crea el objeto Director
Director *director = new Director(argc, argv);
@@ -22,7 +24,7 @@ int main(int argc, char *argv[])
delete director;
director = nullptr;
std::cout << "\nShutting down the game..." << std::endl;
cout << "\nShutting down the game..." << endl;
return 0;
}

View File

@@ -181,13 +181,13 @@ void Player::checkInput()
if (!autoMovement)
{ // Comprueba las entradas de desplazamiento lateral solo en el caso de no estar enganchado a una superficie automatica
if (input->checkInput(INPUT_LEFT, REPEAT_TRUE))
if (input->checkInput(input_left))
{
vx = -0.6f;
sprite->setFlipH(true);
}
else if (input->checkInput(INPUT_RIGHT, REPEAT_TRUE))
else if (input->checkInput(input_right))
{
vx = 0.6f;
sprite->setFlipH(false);
@@ -216,7 +216,7 @@ void Player::checkInput()
}
}
if (input->checkInput(INPUT_UP, REPEAT_TRUE))
if (input->checkInput(input_jump))
{
// Solo puede saltar si ademas de estar (state == s_standing)
// Esta sobre el suelo, rampa o suelo que se mueve
@@ -533,7 +533,7 @@ void Player::move()
#endif
// Comprueba la colisión con las superficies normales y las automáticas
const int pos = std::max(room->checkTopSurfaces(&proj), room->checkAutoSurfaces(&proj));
const int pos = max(room->checkTopSurfaces(&proj), room->checkAutoSurfaces(&proj));
if (pos > -1)
{ // Si hay colisión lo mueve hasta donde no colisiona y pasa a estar sobre la superficie
y = pos - h;
@@ -548,7 +548,7 @@ void Player::move()
{ // Las rampas no se miran si se está saltando
v_line_t leftSide = {proj.x, proj.y, proj.y + proj.h - 1};
v_line_t rightSide = {proj.x + proj.w - 1, proj.y, proj.y + proj.h - 1};
const int p = std::max(room->checkRightSlopes(&rightSide), room->checkLeftSlopes(&leftSide));
const int p = max(room->checkRightSlopes(&rightSide), room->checkLeftSlopes(&leftSide));
if (p > -1)
{ // No está saltando y hay colisión con una rampa
// Calcula la nueva posición
@@ -581,8 +581,8 @@ void Player::move()
sprite->setPosY(y);
#ifdef DEBUG
debug->add("RECT_X: " + std::to_string(rx.x) + "," + std::to_string(rx.y) + "," + std::to_string(rx.w) + "," + std::to_string(rx.h));
debug->add("RECT_Y: " + std::to_string(ry.x) + "," + std::to_string(ry.y) + "," + std::to_string(ry.w) + "," + std::to_string(ry.h));
debug->add("RECT_X: " + to_string(rx.x) + "," + to_string(rx.y) + "," + to_string(rx.w) + "," + to_string(rx.h));
debug->add("RECT_Y: " + to_string(ry.x) + "," + to_string(ry.y) + "," + to_string(ry.w) + "," + to_string(ry.h));
#endif
}
@@ -621,7 +621,7 @@ void Player::playJumpSound()
}
#ifdef DEBUG
debug->add("JUMP: " + std::to_string(jumpCounter / 4));
debug->add("JUMP: " + to_string(jumpCounter / 4));
#endif
}
@@ -630,11 +630,11 @@ void Player::playFallSound()
{
if (fallCounter % 4 == 0)
{
JA_PlaySound(fallSound[std::min((fallCounter / 4), (int)fallSound.size() - 1)]);
JA_PlaySound(fallSound[min((fallCounter / 4), (int)fallSound.size() - 1)]);
}
#ifdef DEBUG
debug->add("FALL: " + std::to_string(fallCounter / 4));
debug->add("FALL: " + to_string(fallCounter / 4));
#endif
}
@@ -666,12 +666,12 @@ bool Player::isOnFloor()
if (onSlopeL)
{
debug->add("ON_SLOPE_L: " + std::to_string(underFeet[0].x) + "," + std::to_string(underFeet[0].y));
debug->add("ON_SLOPE_L: " + to_string(underFeet[0].x) + "," + to_string(underFeet[0].y));
}
if (onSlopeR)
{
debug->add("ON_SLOPE_R: " + std::to_string(underFeet[1].x) + "," + std::to_string(underFeet[1].y));
debug->add("ON_SLOPE_R: " + to_string(underFeet[1].x) + "," + to_string(underFeet[1].y));
}
#endif

View File

@@ -1,12 +1,12 @@
#pragma once
#include <SDL2/SDL.h>
#include "common/animatedsprite.h"
#include "common/asset.h"
#include "common/debug.h"
#include "common/input.h"
#include "common/resource.h"
#include "common/utils.h"
#include "jail_engine/animatedsprite.h"
#include "jail_engine/asset.h"
#include "jail_engine/debug.h"
#include "jail_engine/input.h"
#include "jail_engine/resource.h"
#include "jail_engine/utils.h"
#include "const.h"
#include "room.h"
#include <string>
@@ -15,6 +15,8 @@
#ifndef PLAYER_H
#define PLAYER_H
using namespace std;
enum state_e
{
s_standing,
@@ -36,8 +38,8 @@ struct playerSpawn_t
struct player_t
{
playerSpawn_t spawn;
std::string png;
std::string animation;
string png;
string animation;
SDL_Renderer *renderer;
Resource *resource;
Asset *asset;
@@ -61,32 +63,32 @@ public:
options_t *options; // Puntero a las opciones del juego
// Variables
float x; // Posición del jugador en el eje X
float y; // Posición del jugador en el eje Y
float vx; // Velocidad/desplazamiento del jugador en el eje X
float vy; // Velocidad/desplazamiento del jugador en el eje Y
int w; // Ancho del jugador
int h; // ALto del jugador
color_t color; // Color del jugador
SDL_Rect colliderBox; // Caja de colisión con los enemigos u objetos
std::vector<SDL_Point> colliderPoints; // Puntos de colisión con el mapa
std::vector<SDL_Point> underFeet; // Contiene los puntos que hay bajo cada pie del jugador
std::vector<SDL_Point> feet; // Contiene los puntos que hay en el pie del jugador
state_e state; // Estado en el que se encuentra el jugador. Util apara saber si está saltando o cayendo
state_e prevState; // Estado previo en el que se encontraba el jugador
bool onBorder; // Indica si el jugador esta en uno de los cuatro bordes de la pantalla
int border; // Indica en cual de los cuatro bordes se encuentra
bool autoMovement; // Indica si esta siendo arrastrado por una superficie automatica
bool paused; // Indica si el jugador esta en modo pausa
SDL_Rect lastPosition; // Contiene la ultima posición del jugador, por si hay que deshacer algun movimiento
int jumpIni; // Valor del eje Y en el que se inicia el salto
float maxVY; // Velocidad máxima que puede alcanzar al desplazarse en vertical
std::vector<JA_Sound_t*> jumpSound; // Vecor con todos los sonidos del salto
std::vector<JA_Sound_t*> fallSound; // Vecor con todos los sonidos de la caída
int jumpCounter; // Cuenta el tiempo de salto
int fallCounter; // Cuenta el tiempo de caida
bool alive; // Indica si el jugador esta vivo o no
int maxFallHeight; // Altura maxima permitida de caída.
float x; // Posición del jugador en el eje X
float y; // Posición del jugador en el eje Y
float vx; // Velocidad/desplazamiento del jugador en el eje X
float vy; // Velocidad/desplazamiento del jugador en el eje Y
int w; // Ancho del jugador
int h; // ALto del jugador
color_t color; // Color del jugador
SDL_Rect colliderBox; // Caja de colisión con los enemigos u objetos
vector<SDL_Point> colliderPoints; // Puntos de colisión con el mapa
vector<SDL_Point> underFeet; // Contiene los puntos que hay bajo cada pie del jugador
vector<SDL_Point> feet; // Contiene los puntos que hay en el pie del jugador
state_e state; // Estado en el que se encuentra el jugador. Util apara saber si está saltando o cayendo
state_e prevState; // Estado previo en el que se encontraba el jugador
bool onBorder; // Indica si el jugador esta en uno de los cuatro bordes de la pantalla
int border; // Indica en cual de los cuatro bordes se encuentra
bool autoMovement; // Indica si esta siendo arrastrado por una superficie automatica
bool paused; // Indica si el jugador esta en modo pausa
SDL_Rect lastPosition; // Contiene la ultima posición del jugador, por si hay que deshacer algun movimiento
int jumpIni; // Valor del eje Y en el que se inicia el salto
float maxVY; // Velocidad máxima que puede alcanzar al desplazarse en vertical
vector<JA_Sound_t *> jumpSound; // Vecor con todos los sonidos del salto
vector<JA_Sound_t *> fallSound; // Vecor con todos los sonidos de la caída
int jumpCounter; // Cuenta el tiempo de salto
int fallCounter; // Cuenta el tiempo de caida
bool alive; // Indica si el jugador esta vivo o no
int maxFallHeight; // Altura maxima permitida de caída.
#ifdef DEBUG
SDL_Rect rx; // Rectangulo de desplazamiento para el modo debug

View File

@@ -4,34 +4,34 @@
#include <sstream>
// Carga las variables y texturas desde un fichero de mapa de tiles
std::vector<int> loadRoomTileFile(std::string file_path, bool verbose)
vector<int> loadRoomTileFile(string file_path, bool verbose)
{
std::vector<int> tileMapFile;
const std::string filename = file_path.substr(file_path.find_last_of("\\/") + 1);
std::string line;
std::ifstream file(file_path);
vector<int> tileMapFile;
const string filename = file_path.substr(file_path.find_last_of("\\/") + 1);
string line;
ifstream file(file_path);
// El fichero se puede abrir
if (file.good())
{
// Procesa el fichero linea a linea
while (std::getline(file, line))
while (getline(file, line))
{ // Lee el fichero linea a linea
if (line.find("data encoding") != std::string::npos)
if (line.find("data encoding") != string::npos)
{
// Lee la primera linea
std::getline(file, line);
getline(file, line);
while (line != "</data>")
{ // Procesa lineas mientras haya
std::stringstream ss(line);
std::string tmp;
stringstream ss(line);
string tmp;
while (getline(ss, tmp, ','))
{
tileMapFile.push_back(std::stoi(tmp) - 1);
tileMapFile.push_back(stoi(tmp) - 1);
}
// Lee la siguiente linea
std::getline(file, line);
getline(file, line);
}
}
}
@@ -39,7 +39,7 @@ std::vector<int> loadRoomTileFile(std::string file_path, bool verbose)
// Cierra el fichero
if (verbose)
{
std::cout << "TileMap loaded: " << filename.c_str() << std::endl;
cout << "TileMap loaded: " << filename.c_str() << endl;
}
file.close();
}
@@ -48,7 +48,7 @@ std::vector<int> loadRoomTileFile(std::string file_path, bool verbose)
{ // El fichero no se puede abrir
if (verbose)
{
std::cout << "Warning: Unable to open " << filename.c_str() << " file" << std::endl;
cout << "Warning: Unable to open " << filename.c_str() << " file" << endl;
}
}
@@ -56,24 +56,24 @@ std::vector<int> loadRoomTileFile(std::string file_path, bool verbose)
}
// Carga las variables desde un fichero de mapa
room_t loadRoomFile(std::string file_path, bool verbose)
room_t loadRoomFile(string file_path, bool verbose)
{
room_t room;
room.itemColor1 = "yellow";
room.itemColor2 = "magenta";
room.autoSurfaceDirection = 1;
const std::string fileName = file_path.substr(file_path.find_last_of("\\/") + 1);
const string fileName = file_path.substr(file_path.find_last_of("\\/") + 1);
room.number = fileName.substr(0, fileName.find_last_of("."));
std::string line;
std::ifstream file(file_path);
string line;
ifstream file(file_path);
// El fichero se puede abrir
if (file.good())
{
// Procesa el fichero linea a linea
while (std::getline(file, line))
while (getline(file, line))
{
// Si la linea contiene el texto [enemy] se realiza el proceso de carga de un enemigo
if (line == "[enemy]")
@@ -86,7 +86,7 @@ room_t loadRoomFile(std::string file_path, bool verbose)
do
{
std::getline(file, line);
getline(file, line);
// Encuentra la posición del caracter '='
int pos = line.find("=");
@@ -96,7 +96,7 @@ room_t loadRoomFile(std::string file_path, bool verbose)
{
if (verbose)
{
std::cout << "Warning: file " << fileName.c_str() << "\n, unknown parameter \"" << line.substr(0, pos).c_str() << "\"" << std::endl;
cout << "Warning: file " << fileName.c_str() << "\n, unknown parameter \"" << line.substr(0, pos).c_str() << "\"" << endl;
}
}
} while (line != "[/enemy]");
@@ -115,7 +115,7 @@ room_t loadRoomFile(std::string file_path, bool verbose)
do
{
std::getline(file, line);
getline(file, line);
// Encuentra la posición del caracter '='
int pos = line.find("=");
@@ -125,7 +125,7 @@ room_t loadRoomFile(std::string file_path, bool verbose)
{
if (verbose)
{
std::cout << "Warning: file " << fileName.c_str() << "\n, unknown parameter \"" << line.substr(0, pos).c_str() << "\"" << std::endl;
cout << "Warning: file " << fileName.c_str() << "\n, unknown parameter \"" << line.substr(0, pos).c_str() << "\"" << endl;
}
}
@@ -145,7 +145,7 @@ room_t loadRoomFile(std::string file_path, bool verbose)
{
if (verbose)
{
std::cout << "Warning: file " << fileName.c_str() << "\n, unknown parameter \"" << line.substr(0, pos).c_str() << "\"" << std::endl;
cout << "Warning: file " << fileName.c_str() << "\n, unknown parameter \"" << line.substr(0, pos).c_str() << "\"" << endl;
}
}
}
@@ -154,7 +154,7 @@ room_t loadRoomFile(std::string file_path, bool verbose)
// Cierra el fichero
if (verbose)
{
std::cout << "Room loaded: " << fileName.c_str() << std::endl;
cout << "Room loaded: " << fileName.c_str() << endl;
}
file.close();
}
@@ -162,7 +162,7 @@ room_t loadRoomFile(std::string file_path, bool verbose)
else
{
{
std::cout << "Warning: Unable to open " << fileName.c_str() << " file" << std::endl;
cout << "Warning: Unable to open " << fileName.c_str() << " file" << endl;
}
}
@@ -170,7 +170,7 @@ room_t loadRoomFile(std::string file_path, bool verbose)
}
// Asigna variables a partir de dos cadenas
bool setVars(room_t *room, std::string var, std::string value)
bool setVars(room_t *room, string var, string value)
{
// Indicador de éxito en la asignación
bool success = true;
@@ -255,7 +255,7 @@ bool setVars(room_t *room, std::string var, std::string value)
}
// Asigna variables a una estructura enemy_t
bool setEnemy(enemy_t *enemy, std::string var, std::string value)
bool setEnemy(enemy_t *enemy, string var, string value)
{
// Indicador de éxito en la asignación
bool success = true;
@@ -267,52 +267,52 @@ bool setEnemy(enemy_t *enemy, std::string var, std::string value)
else if (var == "width")
{
enemy->w = std::stof(value);
enemy->w = stof(value);
}
else if (var == "height")
{
enemy->h = std::stof(value);
enemy->h = stof(value);
}
else if (var == "x")
{
enemy->x = std::stof(value) * BLOCK;
enemy->x = stof(value) * BLOCK;
}
else if (var == "y")
{
enemy->y = std::stof(value) * BLOCK;
enemy->y = stof(value) * BLOCK;
}
else if (var == "vx")
{
enemy->vx = std::stof(value);
enemy->vx = stof(value);
}
else if (var == "vy")
{
enemy->vy = std::stof(value);
enemy->vy = stof(value);
}
else if (var == "x1")
{
enemy->x1 = std::stoi(value) * BLOCK;
enemy->x1 = stoi(value) * BLOCK;
}
else if (var == "x2")
{
enemy->x2 = std::stoi(value) * BLOCK;
enemy->x2 = stoi(value) * BLOCK;
}
else if (var == "y1")
{
enemy->y1 = std::stoi(value) * BLOCK;
enemy->y1 = stoi(value) * BLOCK;
}
else if (var == "y2")
{
enemy->y2 = std::stoi(value) * BLOCK;
enemy->y2 = stoi(value) * BLOCK;
}
else if (var == "flip")
@@ -332,7 +332,7 @@ bool setEnemy(enemy_t *enemy, std::string var, std::string value)
else if (var == "frame")
{
enemy->frame = std::stoi(value);
enemy->frame = stoi(value);
}
else if (var == "[/enemy]" || var == "tileSetFile" || var.substr(0, 1) == "#")
@@ -348,7 +348,7 @@ bool setEnemy(enemy_t *enemy, std::string var, std::string value)
}
// Asigna variables a una estructura item_t
bool setItem(item_t *item, std::string var, std::string value)
bool setItem(item_t *item, string var, string value)
{
// Indicador de éxito en la asignación
bool success = true;
@@ -360,22 +360,22 @@ bool setItem(item_t *item, std::string var, std::string value)
else if (var == "counter")
{
item->counter = std::stoi(value);
item->counter = stoi(value);
}
else if (var == "x")
{
item->x = std::stof(value) * BLOCK;
item->x = stof(value) * BLOCK;
}
else if (var == "y")
{
item->y = std::stof(value) * BLOCK;
item->y = stof(value) * BLOCK;
}
else if (var == "tile")
{
item->tile = std::stof(value);
item->tile = stof(value);
}
else if (var == "[/item]")
@@ -478,7 +478,7 @@ Room::Room(room_t *room, SDL_Renderer *renderer, Screen *screen, Asset *asset, o
{
if (options->console)
{
std::cout << "Error: mapTexture could not be created!\nSDL Error: " << SDL_GetError() << std::endl;
cout << "Error: mapTexture could not be created!\nSDL Error: " << SDL_GetError() << endl;
}
}
SDL_SetTextureBlendMode(mapTexture, SDL_BLENDMODE_BLEND);
@@ -514,7 +514,7 @@ Room::~Room()
}
// Devuelve el nombre de la habitación
std::string Room::getName()
string Room::getName()
{
return name;
}
@@ -723,7 +723,7 @@ void Room::update()
}
// Devuelve la cadena del fichero de la habitación contigua segun el borde
std::string Room::getRoom(int border)
string Room::getRoom(int border)
{
switch (border)
{
@@ -897,13 +897,13 @@ int Room::getSlopeHeight(SDL_Point p, tile_e slope)
// Calcula la base del tile
int base = ((p.y / tileSize) * tileSize) + tileSize;
#ifdef DEBUG
debug->add("BASE = " + std::to_string(base));
debug->add("BASE = " + to_string(base));
#endif
// Calcula cuanto se ha entrado en el tile horizontalmente
const int pos = (p.x % tileSize); // Esto da un valor entre 0 y 7
#ifdef DEBUG
debug->add("POS = " + std::to_string(pos));
debug->add("POS = " + to_string(pos));
#endif
// Se resta a la base la cantidad de pixeles pos en funcion de la rampa
@@ -911,14 +911,14 @@ int Room::getSlopeHeight(SDL_Point p, tile_e slope)
{
base -= pos + 1;
#ifdef DEBUG
debug->add("BASE_R = " + std::to_string(base));
debug->add("BASE_R = " + to_string(base));
#endif
}
else
{
base -= (tileSize - pos);
#ifdef DEBUG
debug->add("BASE_L = " + std::to_string(base));
debug->add("BASE_L = " + to_string(base));
#endif
}
@@ -928,7 +928,7 @@ int Room::getSlopeHeight(SDL_Point p, tile_e slope)
// Calcula las superficies inferiores
void Room::setBottomSurfaces()
{
std::vector<int> tile;
vector<int> tile;
// Busca todos los tiles de tipo muro que no tengan debajo otro muro
// Hay que recorrer la habitación por filas (excepto los de la última fila)
@@ -991,7 +991,7 @@ void Room::setBottomSurfaces()
// Calcula las superficies superiores
void Room::setTopSurfaces()
{
std::vector<int> tile;
vector<int> tile;
// Busca todos los tiles de tipo muro o pasable que no tengan encima un muro
// Hay que recorrer la habitación por filas (excepto los de la primera fila)
@@ -1054,7 +1054,7 @@ void Room::setTopSurfaces()
// Calcula las superficies laterales izquierdas
void Room::setLeftSurfaces()
{
std::vector<int> tile;
vector<int> tile;
// Busca todos los tiles de tipo muro que no tienen a su izquierda un tile de tipo muro
// Hay que recorrer la habitación por columnas (excepto los de la primera columna)
@@ -1102,7 +1102,7 @@ void Room::setLeftSurfaces()
// Calcula las superficies laterales derechas
void Room::setRightSurfaces()
{
std::vector<int> tile;
vector<int> tile;
// Busca todos los tiles de tipo muro que no tienen a su derecha un tile de tipo muro
// Hay que recorrer la habitación por columnas (excepto los de la última columna)
@@ -1151,7 +1151,7 @@ void Room::setRightSurfaces()
void Room::setLeftSlopes()
{
// Recorre la habitación entera por filas buscando tiles de tipo t_slope_l
std::vector<int> found;
vector<int> found;
for (int i = 0; i < (int)tileMap.size(); ++i)
{
if (getTile(i) == t_slope_l)
@@ -1192,7 +1192,7 @@ void Room::setLeftSlopes()
void Room::setRightSlopes()
{
// Recorre la habitación entera por filas buscando tiles de tipo t_slope_r
std::vector<int> found;
vector<int> found;
for (int i = 0; i < (int)tileMap.size(); ++i)
{
if (getTile(i) == t_slope_r)
@@ -1232,7 +1232,7 @@ void Room::setRightSlopes()
// Calcula las superficies automaticas
void Room::setAutoSurfaces()
{
std::vector<int> tile;
vector<int> tile;
// Busca todos los tiles de tipo animado
// Hay que recorrer la habitación por filas (excepto los de la primera fila)

View File

@@ -1,12 +1,12 @@
#pragma once
#include <SDL2/SDL.h>
#include "common/asset.h"
#include "common/debug.h"
#include "common/jail_audio.h"
#include "common/screen.h"
#include "common/sprite.h"
#include "common/utils.h"
#include "jail_engine/asset.h"
#include "jail_engine/debug.h"
#include "jail_engine/jail_audio.h"
#include "jail_engine/screen.h"
#include "jail_engine/sprite.h"
#include "jail_engine/utils.h"
#include "const.h"
#include "enemy.h"
#include "item_tracker.h"
@@ -17,6 +17,8 @@
#ifndef ROOM_H
#define ROOM_H
using namespace std;
enum tile_e
{
t_empty,
@@ -36,90 +38,90 @@ struct aTile_t
struct room_t
{
std::string number; // Numero de la habitación
std::string name; // Nombre de la habitación
std::string bgColor; // Color de fondo de la habitación
std::string borderColor; // Color del borde de la pantalla
std::string itemColor1; // Color 1 para los items de la habitación
std::string itemColor2; // Color 2 para los items de la habitación
std::string roomUp; // Identificador de la habitación que se encuentra arriba
std::string roomDown; // Identificador de la habitación que se encuentra abajp
std::string roomLeft; // Identificador de la habitación que se encuentra a la izquierda
std::string roomRight; // Identificador de la habitación que se encuentra a la derecha
std::string tileSetFile; // Imagen con los graficos para la habitación
std::string tileMapFile; // Fichero con el mapa de indices de tile
std::vector<int> *tileMap; // Indice de los tiles a dibujar en la habitación
int autoSurfaceDirection; // Sentido en el que arrastran las superficies automáticas de la habitación
std::vector<enemy_t> enemies; // Listado con los enemigos de la habitación
std::vector<item_t> items; // Listado con los items que hay en la habitación
Texture *textureA; // Textura con los graficos de la habitación
Texture *textureB; // Textura con los graficos de la habitación
string number; // Numero de la habitación
string name; // Nombre de la habitación
string bgColor; // Color de fondo de la habitación
string borderColor; // Color del borde de la pantalla
string itemColor1; // Color 1 para los items de la habitación
string itemColor2; // Color 2 para los items de la habitación
string roomUp; // Identificador de la habitación que se encuentra arriba
string roomDown; // Identificador de la habitación que se encuentra abajp
string roomLeft; // Identificador de la habitación que se encuentra a la izquierda
string roomRight; // Identificador de la habitación que se encuentra a la derecha
string tileSetFile; // Imagen con los graficos para la habitación
string tileMapFile; // Fichero con el mapa de indices de tile
vector<int> *tileMap; // Indice de los tiles a dibujar en la habitación
int autoSurfaceDirection; // Sentido en el que arrastran las superficies automáticas de la habitación
vector<enemy_t> enemies; // Listado con los enemigos de la habitación
vector<item_t> items; // Listado con los items que hay en la habitación
Texture *textureA; // Textura con los graficos de la habitación
Texture *textureB; // Textura con los graficos de la habitación
};
// Carga las variables desde un fichero de mapa
room_t loadRoomFile(std::string file, bool verbose = false);
room_t loadRoomFile(string file, bool verbose = false);
// Carga las variables y texturas desde un fichero de mapa de tiles
std::vector<int> loadRoomTileFile(std::string file_path, bool verbose = false);
vector<int> loadRoomTileFile(string file_path, bool verbose = false);
// Asigna variables a partir de dos cadenas
bool setVars(room_t *room, std::string var, std::string value);
bool setVars(room_t *room, string var, string value);
// Asigna variables a una estructura enemy_t
bool setEnemy(enemy_t *enemy, std::string var, std::string value);
bool setEnemy(enemy_t *enemy, string var, string value);
// Asigna variables a una estructura item_t
bool setItem(item_t *item, std::string var, std::string value);
bool setItem(item_t *item, string var, string value);
class Room
{
private:
// Objetos y punteros
std::vector<Enemy *> enemies; // Listado con los enemigos de la habitación
std::vector<Item *> items; // Listado con los items que hay en la habitación
Texture *texture; // Textura con los graficos de la habitación
Texture *textureA; // Textura con los graficos de la habitación
Texture *textureB; // Textura con los graficos de la habitación
Asset *asset; // Objeto con la ruta a todos los ficheros de recursos
Screen *screen; // Objeto encargado de dibujar en pantalla
ItemTracker *itemTracker; // Lleva el control de los objetos recogidos
SDL_Renderer *renderer; // El renderizador de la ventana
SDL_Texture *mapTexture; // Textura para dibujar el mapa de la habitación
int *itemsPicked; // Puntero a la cantidad de items recogidos que lleva el juego
Debug *debug; // Objeto para gestionar la información de debug
options_t *options; // Puntero a las opciones del juego
vector<Enemy *> enemies; // Listado con los enemigos de la habitación
vector<Item *> items; // Listado con los items que hay en la habitación
Texture *texture; // Textura con los graficos de la habitación
Texture *textureA; // Textura con los graficos de la habitación
Texture *textureB; // Textura con los graficos de la habitación
Asset *asset; // Objeto con la ruta a todos los ficheros de recursos
Screen *screen; // Objeto encargado de dibujar en pantalla
ItemTracker *itemTracker; // Lleva el control de los objetos recogidos
SDL_Renderer *renderer; // El renderizador de la ventana
SDL_Texture *mapTexture; // Textura para dibujar el mapa de la habitación
int *itemsPicked; // Puntero a la cantidad de items recogidos que lleva el juego
Debug *debug; // Objeto para gestionar la información de debug
options_t *options; // Puntero a las opciones del juego
// Variables
std::string number; // Numero de la habitación
std::string name; // Nombre de la habitación
std::string bgColor; // Color de fondo de la habitación
std::string borderColor; // Color del borde de la pantalla
std::string itemColor1; // Color 1 para los items de la habitación
std::string itemColor2; // Color 2 para los items de la habitación
std::string roomUp; // Identificador de la habitación que se encuentra arriba
std::string roomDown; // Identificador de la habitación que se encuentra abajp
std::string roomLeft; // Identificador de la habitación que se encuentra a la izquierda
std::string roomRight; // Identificador de la habitación que se encuentra a la derecha
std::string tileSetFile; // Imagen con los graficos para la habitación
std::string tileMapFile; // Fichero con el mapa de indices de tile
std::vector<int> tileMap; // Indice de los tiles a dibujar en la habitación
int autoSurfaceDirection; // Sentido en el que arrastran las superficies automáticas de la habitación
JA_Sound_t *itemSound; // Sonido producido al coger un objeto
std::vector<h_line_t> bottomSurfaces; // Lista con las superficies inferiores de la habitación
std::vector<h_line_t> topSurfaces; // Lista con las superficies superiores de la habitación
std::vector<v_line_t> leftSurfaces; // Lista con las superficies laterales de la parte izquierda de la habitación
std::vector<v_line_t> rightSurfaces; // Lista con las superficies laterales de la parte derecha de la habitación
std::vector<d_line_t> leftSlopes; // Lista con todas las rampas que suben hacia la izquierda
std::vector<d_line_t> rightSlopes; // Lista con todas las rampas que suben hacia la derecha
int counter; // Contador para lo que haga falta
bool paused; // Indica si el mapa esta en modo pausa
std::vector<aTile_t> aTile; // Vector con los indices de tiles animados
std::vector<h_line_t> autoSurfaces; // Lista con las superficies automaticas de la habitación
int tileSize; // Ancho del tile en pixels
int mapWidth; // Ancho del mapa en tiles
int mapHeight; // Alto del mapa en tiles
int tileSetWidth; // Ancho del tileset en tiles
bool jailEnabled; // Indica si hay acceso a la Jail
string number; // Numero de la habitación
string name; // Nombre de la habitación
string bgColor; // Color de fondo de la habitación
string borderColor; // Color del borde de la pantalla
string itemColor1; // Color 1 para los items de la habitación
string itemColor2; // Color 2 para los items de la habitación
string roomUp; // Identificador de la habitación que se encuentra arriba
string roomDown; // Identificador de la habitación que se encuentra abajp
string roomLeft; // Identificador de la habitación que se encuentra a la izquierda
string roomRight; // Identificador de la habitación que se encuentra a la derecha
string tileSetFile; // Imagen con los graficos para la habitación
string tileMapFile; // Fichero con el mapa de indices de tile
vector<int> tileMap; // Indice de los tiles a dibujar en la habitación
int autoSurfaceDirection; // Sentido en el que arrastran las superficies automáticas de la habitación
JA_Sound_t *itemSound; // Sonido producido al coger un objeto
vector<h_line_t> bottomSurfaces; // Lista con las superficies inferiores de la habitación
vector<h_line_t> topSurfaces; // Lista con las superficies superiores de la habitación
vector<v_line_t> leftSurfaces; // Lista con las superficies laterales de la parte izquierda de la habitación
vector<v_line_t> rightSurfaces; // Lista con las superficies laterales de la parte derecha de la habitación
vector<d_line_t> leftSlopes; // Lista con todas las rampas que suben hacia la izquierda
vector<d_line_t> rightSlopes; // Lista con todas las rampas que suben hacia la derecha
int counter; // Contador para lo que haga falta
bool paused; // Indica si el mapa esta en modo pausa
vector<aTile_t> aTile; // Vector con los indices de tiles animados
vector<h_line_t> autoSurfaces; // Lista con las superficies automaticas de la habitación
int tileSize; // Ancho del tile en pixels
int mapWidth; // Ancho del mapa en tiles
int mapHeight; // Alto del mapa en tiles
int tileSetWidth; // Ancho del tileset en tiles
bool jailEnabled; // Indica si hay acceso a la Jail
// Pinta el mapa de la habitación en la textura
void fillMapTexture();
@@ -168,7 +170,7 @@ public:
~Room();
// Devuelve el nombre de la habitación
std::string getName();
string getName();
// Devuelve el color de la habitación
color_t getBGColor();
@@ -189,7 +191,7 @@ public:
void update();
// Devuelve la cadena del fichero de la habitación contigua segun el borde
std::string getRoom(int border);
string getRoom(int border);
// Devuelve el tipo de tile que hay en ese pixel
tile_e getTile(SDL_Point point);

View File

@@ -12,7 +12,7 @@ RoomTracker::~RoomTracker()
}
// Comprueba si la habitación ya ha sido visitada
bool RoomTracker::hasBeenVisited(std::string name)
bool RoomTracker::hasBeenVisited(string name)
{
for (auto l : list)
{
@@ -26,7 +26,7 @@ bool RoomTracker::hasBeenVisited(std::string name)
}
// Añade la habitación a la lista
bool RoomTracker::addRoom(std::string name)
bool RoomTracker::addRoom(string name)
{
// Comprueba si la habitación ya ha sido visitada
if (!hasBeenVisited(name))

View File

@@ -1,21 +1,23 @@
#pragma once
#include <SDL2/SDL.h>
#include "common/utils.h"
#include "jail_engine/utils.h"
#include <string>
#include <vector>
#ifndef ROOM_TRACKER_H
#define ROOM_TRACKER_H
using namespace std;
class RoomTracker
{
private:
// Variables
std::vector<std::string> list; // Lista con las habitaciones visitadas
vector<string> list; // Lista con las habitaciones visitadas
// Comprueba si la habitación ya ha sido visitada
bool hasBeenVisited(std::string name);
bool hasBeenVisited(string name);
public:
// Constructor
@@ -25,7 +27,7 @@ public:
~RoomTracker();
// Añade la habitación a la lista
bool addRoom(std::string name);
bool addRoom(string name);
};
#endif

View File

@@ -6,15 +6,15 @@
ScoreBoard::ScoreBoard(SDL_Renderer *renderer, Resource *resource, Asset *asset, options_t *options, board_t *board)
{
// Obten punteros a objetos
this->renderer = renderer;
this->resource = resource;
this->asset = asset;
this->renderer = renderer;
this->board = board;
this->options = options;
this->board = board;
// Reserva memoria para los objetos
itemTexture = resource->getTexture("items.png");
const std::string playerANI = options->cheat.altSkin ? "player2.ani" : "player.ani";
const string playerANI = options->cheat.altSkin ? "player2.ani" : "player.ani";
sprite = new AnimatedSprite(renderer, resource->getAnimation(playerANI));
sprite->setCurrentAnimation("walk_menu");
text = new Text(resource->getOffset("smb2.txt"), resource->getTexture("smb2.png"), renderer);
@@ -28,7 +28,7 @@ ScoreBoard::ScoreBoard(SDL_Renderer *renderer, Resource *resource, Asset *asset,
itemsColor = stringToColor(options->palette, "white");
// Inicializa el vector de colores
const std::vector<std::string> vColors = {"blue", "magenta", "green", "cyan", "yellow", "white", "bright_blue", "bright_magenta", "bright_green", "bright_cyan", "bright_yellow", "bright_white"};
const vector<string> vColors = {"blue", "magenta", "green", "cyan", "yellow", "white", "bright_blue", "bright_magenta", "bright_green", "bright_cyan", "bright_yellow", "bright_white"};
for (auto v : vColors)
{
color.push_back(stringToColor(options->palette, v));
@@ -77,14 +77,14 @@ void ScoreBoard::render()
}
// Escribe los textos
const std::string timeTxt = std::to_string((clock.minutes % 100) / 10) + std::to_string(clock.minutes % 10) + clock.separator + std::to_string((clock.seconds % 60) / 10) + std::to_string(clock.seconds % 10);
const std::string itemsTxt = std::to_string(board->items / 100) + std::to_string((board->items % 100) / 10) + std::to_string(board->items % 10);
const string timeTxt = to_string((clock.minutes % 100) / 10) + to_string(clock.minutes % 10) + clock.separator + to_string((clock.seconds % 60) / 10) + to_string(clock.seconds % 10);
const string itemsTxt = to_string(board->items / 100) + to_string((board->items % 100) / 10) + to_string(board->items % 10);
this->text->writeColored(BLOCK, line1, "Items collected ", board->color);
this->text->writeColored(17 * BLOCK, line1, itemsTxt, itemsColor);
this->text->writeColored(20 * BLOCK, line1, " Time ", board->color);
this->text->writeColored(26 * BLOCK, line1, timeTxt, stringToColor(options->palette, "white"));
const std::string roomsTxt = std::to_string(board->rooms / 100) + std::to_string((board->rooms % 100) / 10) + std::to_string(board->rooms % 10);
const string roomsTxt = to_string(board->rooms / 100) + to_string((board->rooms % 100) / 10) + to_string(board->rooms % 10);
this->text->writeColored(22 * BLOCK, line2, "Rooms", stringToColor(options->palette, "white"));
this->text->writeColored(28 * BLOCK, line2, roomsTxt, stringToColor(options->palette, "white"));
}
@@ -131,7 +131,7 @@ void ScoreBoard::reLoadTexture()
void ScoreBoard::reLoadPalette()
{
// Reinicia el vector de colores
const std::vector<std::string> vColors = {"blue", "magenta", "green", "cyan", "yellow", "white", "bright_blue", "bright_magenta", "bright_green", "bright_cyan", "bright_yellow", "bright_white"};
const vector<string> vColors = {"blue", "magenta", "green", "cyan", "yellow", "white", "bright_blue", "bright_magenta", "bright_green", "bright_cyan", "bright_yellow", "bright_white"};
color.clear();
for (auto v : vColors)
{
@@ -169,4 +169,10 @@ void ScoreBoard::updateItemsColor()
{
itemsColor = stringToColor(options->palette, "magenta");
}
}
// Devuelve la cantidad de minutos de juego transcurridos
int ScoreBoard::getMinutes()
{
return getTime().minutes;
}

View File

@@ -1,17 +1,19 @@
#pragma once
#include <SDL2/SDL.h>
#include "common/animatedsprite.h"
#include "common/asset.h"
#include "common/resource.h"
#include "common/text.h"
#include "common/utils.h"
#include "jail_engine/animatedsprite.h"
#include "jail_engine/asset.h"
#include "jail_engine/resource.h"
#include "jail_engine/text.h"
#include "jail_engine/utils.h"
#include "const.h"
#include <string>
#ifndef SCOREBOARD_H
#define SCOREBOARD_H
using namespace std;
struct board_t
{
int items; // Lleva la cuenta de los objetos recogidos
@@ -31,7 +33,7 @@ private:
int hours;
int minutes;
int seconds;
std::string separator;
string separator;
};
// Objetos y punteros
@@ -45,14 +47,14 @@ private:
options_t *options; // Puntero a las opciones del juego
// Variables
std::vector<color_t> color; // Vector con los colores del objeto
int counter; // Contador interno
int colorChangeSpeed; // Cuanto mas alto, mas tarda en cambiar de color
bool paused; // Indica si el marcador esta en modo pausa
Uint32 timePaused; // Milisegundos que ha estado el marcador en pausa
Uint32 totalTimePaused; // Tiempo acumulado en pausa
clock_t clock; // Contiene las horas, minutos y segundos transcurridos desde el inicio de la partida
color_t itemsColor; // Color de la cantidad de items recogidos
vector<color_t> color; // Vector con los colores del objeto
int counter; // Contador interno
int colorChangeSpeed; // Cuanto mas alto, mas tarda en cambiar de color
bool paused; // Indica si el marcador esta en modo pausa
Uint32 timePaused; // Milisegundos que ha estado el marcador en pausa
Uint32 totalTimePaused; // Tiempo acumulado en pausa
clock_t clock; // Contiene las horas, minutos y segundos transcurridos desde el inicio de la partida
color_t itemsColor; // Color de la cantidad de items recogidos
// Obtiene el tiempo transcurrido de partida
clock_t getTime();
@@ -84,6 +86,9 @@ public:
// Quita el modo pausa del marcador
void resume();
// Devuelve la cantidad de minutos de juego transcurridos
int getMinutes();
};
#endif

View File

@@ -1,4 +1,4 @@
#include "common/jscore.h"
#include "jail_engine/jscore.h"
#include "stats.h"
#include <algorithm>
#include <fstream>
@@ -6,7 +6,7 @@
#include <sstream>
// Constructor
Stats::Stats(std::string file, std::string buffer, options_t *options)
Stats::Stats(string file, string buffer, options_t *options)
{
this->options = options;
bufferPath = buffer;
@@ -51,10 +51,10 @@ void Stats::init()
}
// Añade una muerte a las estadisticas
void Stats::addDeath(std::string name)
void Stats::addDeath(string name)
{
// Normaliza el nombre
// std::replace(name.begin(), name.end(), ' ', '_');
// replace(name.begin(), name.end(), ' ', '_');
// Primero busca si ya hay una entrada con ese nombre
const int index = findByName(name, bufferList);
@@ -75,10 +75,10 @@ void Stats::addDeath(std::string name)
}
// Añade una visita a las estadisticas
void Stats::addVisit(std::string name)
void Stats::addVisit(string name)
{
// Normaliza el nombre
// std::replace(name.begin(), name.end(), ' ', '_');
// replace(name.begin(), name.end(), ' ', '_');
// Primero busca si ya hay una entrada con ese nombre
const int index = findByName(name, bufferList);
@@ -99,7 +99,7 @@ void Stats::addVisit(std::string name)
}
// Busca una entrada en la lista por nombre
int Stats::findByName(std::string name, std::vector<stats_t> &list)
int Stats::findByName(string name, vector<stats_t> &list)
{
int i = 0;
@@ -116,7 +116,7 @@ int Stats::findByName(std::string name, std::vector<stats_t> &list)
}
// Carga las estadisticas desde un fichero
bool Stats::loadFromFile(std::string filePath, std::vector<stats_t> &list)
bool Stats::loadFromFile(string filePath, vector<stats_t> &list)
{
list.clear();
@@ -124,21 +124,21 @@ bool Stats::loadFromFile(std::string filePath, std::vector<stats_t> &list)
bool success = true;
// Variables para manejar el fichero
std::string line;
std::ifstream file(filePath);
string line;
ifstream file(filePath);
// Si el fichero se puede abrir
if (file.good())
{
// Procesa el fichero linea a linea
while (std::getline(file, line))
while (getline(file, line))
{
// Comprueba que la linea no sea un comentario
if (line.substr(0, 1) != "#")
{
stats_t stat;
std::stringstream ss(line);
std::string tmp;
stringstream ss(line);
string tmp;
// Obtiene el nombre
getline(ss, tmp, ';');
@@ -146,11 +146,11 @@ bool Stats::loadFromFile(std::string filePath, std::vector<stats_t> &list)
// Obtiene las visitas
getline(ss, tmp, ';');
stat.visited = std::stoi(tmp);
stat.visited = stoi(tmp);
// Obtiene las muertes
getline(ss, tmp, ';');
stat.died = std::stoi(tmp);
stat.died = stoi(tmp);
list.push_back(stat);
}
@@ -177,14 +177,14 @@ void Stats::loadFromServer()
list.clear();
std::string data;
string data;
if (options->online.enabled)
{
data = jscore::getUserData(options->online.gameID, options->online.jailerID);
}
std::stringstream ss(data);
std::string tmp;
stringstream ss(data);
string tmp;
int count = 0;
@@ -206,11 +206,11 @@ void Stats::loadFromServer()
// Obtiene las visitas
getline(ss, tmp, ';');
stat.visited = std::stoi(tmp);
stat.visited = stoi(tmp);
// Obtiene las muertes
getline(ss, tmp, ';');
stat.died = std::stoi(tmp);
stat.died = stoi(tmp);
list.push_back(stat);
count = count - 3;
@@ -218,16 +218,16 @@ void Stats::loadFromServer()
}
// Guarda las estadisticas en un fichero
void Stats::saveToFile(std::string filePath, std::vector<stats_t> &list)
void Stats::saveToFile(string filePath, vector<stats_t> &list)
{
// Crea y abre el fichero de texto
std::ofstream file(filePath);
ofstream file(filePath);
// Escribe en el fichero
file << "# ROOM NAME;VISITS;DEATHS" << std::endl;
file << "# ROOM NAME;VISITS;DEATHS" << endl;
for (auto item : list)
{
file << item.name << ";" << item.visited << ";" << item.died << std::endl;
file << item.name << ";" << item.visited << ";" << item.died << endl;
}
// Cierra el fichero
@@ -237,12 +237,12 @@ void Stats::saveToFile(std::string filePath, std::vector<stats_t> &list)
// Guarda las estadisticas en un servidor
void Stats::saveToServer()
{
std::string data = "";
string data = "";
if (options->online.enabled)
{
for (auto item : list)
{
data = data + nameToNumber(item.name) + ";" + std::to_string(item.visited) + ";" + std::to_string(item.died) + ";";
data = data + nameToNumber(item.name) + ";" + to_string(item.visited) + ";" + to_string(item.died) + ";";
}
jscore::setUserData(options->online.gameID, options->online.jailerID, data);
}
@@ -263,13 +263,13 @@ void Stats::checkWorstNightmare()
}
// Añade una entrada al diccionario
void Stats::addDictionary(std::string number, std::string name)
void Stats::addDictionary(string number, string name)
{
dictionary.push_back({number, name});
}
// Obtiene el nombre de una habitación a partir del número
std::string Stats::numberToName(std::string number)
string Stats::numberToName(string number)
{
for (auto l : dictionary)
{
@@ -282,7 +282,7 @@ std::string Stats::numberToName(std::string number)
}
// Obtiene el número de una habitación a partir del nombre
std::string Stats::nameToNumber(std::string name)
string Stats::nameToNumber(string name)
{
for (auto l : dictionary)
{

View File

@@ -1,49 +1,51 @@
#pragma once
#include <SDL2/SDL.h>
#include "common/utils.h"
#include "jail_engine/utils.h"
#include <string>
#include <vector>
#ifndef STATS_H
#define STATS_H
using namespace std;
class Stats
{
private:
struct stats_t
{
std::string name; // Nombre de la habitación
int visited; // Cuenta las veces que se ha visitado una habitación
int died; // Cuenta las veces que se ha muerto en una habitación
string name; // Nombre de la habitación
int visited; // Cuenta las veces que se ha visitado una habitación
int died; // Cuenta las veces que se ha muerto en una habitación
};
struct stats_dictionary_t
{
std::string number; // Numero de la habitación
std::string name; // Nombre de la habitación
string number; // Numero de la habitación
string name; // Nombre de la habitación
};
// Punteros y objetos
options_t *options;
// Variables
std::vector<stats_dictionary_t> dictionary; // Lista con la equivalencia nombre-numero de habitacion
std::vector<stats_t> bufferList; // Lista con las estadisticas temporales por habitación
std::vector<stats_t> list; // Lista con las estadisticas completas por habitación
std::string bufferPath; // Fichero con las estadísticas temporales
std::string filePath; // Fichero con las estadísticas completas
vector<stats_dictionary_t> dictionary; // Lista con la equivalencia nombre-numero de habitacion
vector<stats_t> bufferList; // Lista con las estadisticas temporales por habitación
vector<stats_t> list; // Lista con las estadisticas completas por habitación
string bufferPath; // Fichero con las estadísticas temporales
string filePath; // Fichero con las estadísticas completas
// Busca una entrada en la lista por nombre
int findByName(std::string name, std::vector<stats_t> &list);
int findByName(string name, vector<stats_t> &list);
// Carga las estadisticas desde un fichero
bool loadFromFile(std::string filePath, std::vector<stats_t> &list);
bool loadFromFile(string filePath, vector<stats_t> &list);
// Carga las estadisticas desde un servidor
void loadFromServer();
// Guarda las estadisticas en un fichero
void saveToFile(std::string filePath, std::vector<stats_t> &list);
void saveToFile(string filePath, vector<stats_t> &list);
// Guarda las estadisticas en un servidor
void saveToServer();
@@ -52,10 +54,10 @@ private:
void checkWorstNightmare();
// Obtiene el nombre de una habitación a partir del número
std::string numberToName(std::string number);
string numberToName(string number);
// Obtiene el número de una habitación a partir del nombre
std::string nameToNumber(std::string name);
string nameToNumber(string name);
// Vuelca los datos del buffer en la lista de estadisticas
void updateListFromBuffer();
@@ -65,7 +67,7 @@ private:
public:
// Constructor
Stats(std::string file, std::string buffer, options_t *options);
Stats(string file, string buffer, options_t *options);
// Destructor
~Stats();
@@ -75,13 +77,13 @@ public:
void init();
// Añade una muerte a las estadisticas
void addDeath(std::string name);
void addDeath(string name);
// Añade una visita a las estadisticas
void addVisit(std::string name);
void addVisit(string name);
// Añade una entrada al diccionario
void addDictionary(std::string number, std::string name);
void addDictionary(string number, string name);
};
#endif

View File

@@ -1,17 +1,20 @@
#include "title.h"
// Constructor
Title::Title(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *asset, options_t *options)
Title::Title(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *asset, Input *input, options_t *options, section_t *section)
{
// Copia la dirección de los objetos
this->resource = resource;
this->renderer = renderer;
this->screen = screen;
this->asset = asset;
this->input = input;
this->options = options;
this->section = section;
// Reserva memoria para los punteros
eventHandler = new SDL_Event();
cheevos = new Cheevos(screen, options, asset->get("cheevos.bin"));
if (options->palette == p_zxspectrum)
{
texture = resource->getTexture("loading_screen_color.png");
@@ -22,27 +25,23 @@ Title::Title(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *
}
sprite = new Sprite(0, 0, texture->getWidth(), texture->getHeight(), texture, renderer);
text = new Text(resource->getOffset("smb2.txt"), resource->getTexture("smb2.png"), renderer);
infoText = new Text(resource->getOffset("debug.txt"), resource->getTexture("debug.png"), renderer);
// Inicializa variables
counter = 0;
section.name = SECTION_PROG_TITLE;
section.subsection = 0;
section->name = SECTION_PROG_TITLE;
section->subsection = 0;
ticks = 0;
ticksSpeed = 15;
longText = "HEY JAILERS!! IT'S 2022 AND WE'RE STILL ROCKING LIKE IT'S 1998!!! HAVE YOU HEARD IT? JAILGAMES ARE BACK!! YEEESSS BACK!! MORE THAN 10 TITLES ON JAILDOC'S KITCHEN!! THATS A LOOOOOOT OF JAILGAMES, BUT WHICH ONE WILL STRIKE FIRST? THERE IS ALSO A NEW DEVICE TO COME THAT WILL BLOW YOUR MIND WITH JAILGAMES ON THE GO: P.A.C.O. BUT WAIT! WHAT'S THAT BEAUTY I'M SEEING RIGHT OVER THERE?? OOOH THAT TINY MINIASCII IS PURE LOVE!! I WANT TO LICK EVERY BYTE OF IT!! OH SHIT! AND DON'T FORGET TO BRING BACK THOSE OLD AND FAT MS-DOS JAILGAMES TO GITHUB TO KEEP THEM ALIVE!! WHAT WILL BE THE NEXT JAILDOC RELEASE? WHAT WILL BE THE NEXT PROJECT TO COME ALIVE?? OH BABY WE DON'T KNOW BUT HERE YOU CAN FIND THE ANSWER, YOU JUST HAVE TO COMPLETE JAILDOCTOR'S DILEMMA ... COULD YOU?";
for (int i = 0; i < (int)longText.length(); ++i)
{
letter_t l;
l.letter = longText.substr(i, 1);
l.x = 256;
l.enabled = false;
letters.push_back(l);
}
letters[0].enabled = true;
marqueeSpeed = 3;
initMarquee();
// Crea el cartel de PRESS ENTER
const std::string caption = "PRESS ENTER TO PLAY";
#ifdef GAME_CONSOLE
const string caption = "PRESS START TO PLAY";
#else
const string caption = "PRESS ENTER TO PLAY";
#endif
const color_t textColor = stringToColor(options->palette, "white");
const color_t strokeColor = stringToColor(options->palette, "bright_blue");
@@ -56,6 +55,49 @@ Title::Title(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *
// Crea el sprite
pressEnterSprite = new Sprite(128 - (pressEnterTexture->getWidth() / 2), 192 / 5 * 4, pressEnterTexture->getWidth(), pressEnterTexture->getHeight(), pressEnterTexture, renderer);
// Crea la textura con el listado de logros
const vector<cheevos_t> cheevosList = cheevos->list();
const int iconSize = 16; // Altura del icono que representa a cada logro
const int cheevoHeight = iconSize + 2; // EL espacio que ocupa cada logro es igual a la altura del icono mas dos pixeles de separación
const int cheevosTextureWidth = 200;
const int cheevosTextureViewHeight = GAMECANVAS_HEIGHT - 32;
cheevosTexture = new Texture(renderer);
cheevosTexture->createBlank(renderer, cheevosTextureWidth, cheevoHeight * cheevosList.size(), SDL_TEXTUREACCESS_TARGET);
cheevosTexture->setAsRenderTarget(renderer);
cheevosTexture->setBlendMode(SDL_BLENDMODE_BLEND);
const color_t cheevosBGColor = stringToColor(options->palette, "blue");
SDL_SetRenderDrawColor(renderer, cheevosBGColor.r, cheevosBGColor.g, cheevosBGColor.b, 0xFF);
SDL_RenderClear(renderer);
const std::string cheevosListCaption = "ACHIEVEMENTS (" + std::to_string(cheevos->unlocked()) + " / " + std::to_string(cheevos->count()) + ")";
infoText->writeDX(TXT_CENTER | TXT_COLOR, cheevosTexture->getWidth() / 2, 2, cheevosListCaption, 1, stringToColor(options->palette, "bright_white"));
int pos = 9;
const color_t cheevoLockedColor = stringToColor(options->palette, "white");
const color_t cheevoUnlockedColor = stringToColor(options->palette, "bright_white");
color_t cheevoColor;
Texture *iconTexture = new Texture(renderer, asset->get("notify.png"));
Sprite *sp = new Sprite({0, 0, iconSize, iconSize}, iconTexture, renderer);
for (auto cheevo : cheevosList)
{
cheevoColor = cheevo.completed ? cheevoUnlockedColor : cheevoLockedColor;
sp->setPos({2, pos, iconSize, iconSize});
sp->setSpriteClip({iconSize * 2, 0, iconSize, iconSize});
sp->getTexture()->setColor(cheevoColor.r, cheevoColor.g, cheevoColor.b);
sp->render();
pos += 2;
infoText->writeColored(2 + iconSize + 2, pos, cheevo.caption, cheevoColor);
pos += 6;
infoText->writeColored(2 + iconSize + 2, pos, cheevo.description, cheevoColor);
pos += 9;
}
delete sp;
delete iconTexture;
// Crea el sprite para el listado de logros
cheevosSprite = new Sprite((GAMECANVAS_WIDTH - cheevosTexture->getWidth()) / 2, (GAMECANVAS_HEIGHT - cheevosTextureViewHeight) / 2, cheevosTexture->getWidth(), cheevosTexture->getHeight(), cheevosTexture, renderer);
cheevosTextureView = {0, 0, cheevosTexture->getWidth(), cheevosTextureViewHeight};
cheevosSprite->setSpriteClip(cheevosTextureView);
// Cambia el color del borde
screen->setBorderColor(stringToColor(options->palette, "bright_blue"));
}
@@ -63,11 +105,31 @@ Title::Title(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *
// Destructor
Title::~Title()
{
delete cheevos;
delete eventHandler;
delete sprite;
delete pressEnterSprite;
delete pressEnterTexture;
delete cheevosSprite;
delete cheevosTexture;
delete text;
delete infoText;
}
// Inicializa la marquesina
void Title::initMarquee()
{
letters.clear();
longText = "HEY JAILERS!! IT'S 2022 AND WE'RE STILL ROCKING LIKE IT'S 1998!!! HAVE YOU HEARD IT? JAILGAMES ARE BACK!! YEEESSS BACK!! MORE THAN 10 TITLES ON JAILDOC'S KITCHEN!! THATS A LOOOOOOT OF JAILGAMES, BUT WHICH ONE WILL STRIKE FIRST? THERE IS ALSO A NEW DEVICE TO COME THAT WILL BLOW YOUR MIND WITH JAILGAMES ON THE GO: P.A.C.O. BUT WAIT! WHAT'S THAT BEAUTY I'M SEEING RIGHT OVER THERE?? OOOH THAT TINY MINIASCII IS PURE LOVE!! I WANT TO LICK EVERY BYTE OF IT!! OH SHIT! AND DON'T FORGET TO BRING BACK THOSE OLD AND FAT MS-DOS JAILGAMES TO GITHUB TO KEEP THEM ALIVE!! WHAT WILL BE THE NEXT JAILDOC RELEASE? WHAT WILL BE THE NEXT PROJECT TO COME ALIVE?? OH BABY WE DON'T KNOW BUT HERE YOU CAN FIND THE ANSWER, YOU JUST HAVE TO COMPLETE JAILDOCTOR'S DILEMMA ... COULD YOU?";
for (int i = 0; i < (int)longText.length(); ++i)
{
letter_t l;
l.letter = longText.substr(i, 1);
l.x = 256;
l.enabled = false;
letters.push_back(l);
}
letters[0].enabled = true;
}
// Comprueba el manejador de eventos
@@ -79,70 +141,21 @@ void Title::checkEventHandler()
// Evento de salida de la aplicación
if (eventHandler->type == SDL_QUIT)
{
section.name = SECTION_PROG_QUIT;
section->name = SECTION_PROG_QUIT;
break;
}
// Comprueba las teclas que se han pulsado
if ((eventHandler->type == SDL_KEYDOWN && eventHandler->key.repeat == 0) || (eventHandler->type == SDL_JOYBUTTONDOWN))
if (eventHandler->type == SDL_KEYDOWN)
{
if (eventHandler->type == SDL_JOYBUTTONDOWN)
{
section.name = SECTION_PROG_GAME;
section.subsection = 0;
}
switch (eventHandler->key.keysym.scancode)
{
case SDL_SCANCODE_ESCAPE:
section.name = SECTION_PROG_QUIT;
case SDL_SCANCODE_A:
showCheevos = !showCheevos;
break;
case SDL_SCANCODE_RETURN:
section.name = SECTION_PROG_GAME;
section.subsection = 0;
case SDL_SCANCODE_Z:
initMarquee();
break;
case SDL_SCANCODE_B:
screen->switchBorder();
resource->reLoadTextures();
break;
case SDL_SCANCODE_F:
screen->switchVideoMode();
resource->reLoadTextures();
break;
case SDL_SCANCODE_F1:
screen->setWindowSize(1);
resource->reLoadTextures();
break;
case SDL_SCANCODE_F2:
screen->setWindowSize(2);
resource->reLoadTextures();
break;
case SDL_SCANCODE_F3:
screen->setWindowSize(3);
resource->reLoadTextures();
break;
case SDL_SCANCODE_F4:
screen->setWindowSize(4);
resource->reLoadTextures();
break;
case SDL_SCANCODE_F5:
switchPalette();
break;
#ifdef DEBUG
case SDL_SCANCODE_F6:
screen->showNotification("MAMA MIRA! SIN MANOS!");
break;
#endif
default:
break;
}
@@ -150,6 +163,62 @@ void Title::checkEventHandler()
}
}
// Comprueba las entradas
void Title::checkInput()
{
if (showCheevos)
{
if (input->checkInput(input_down, REPEAT_TRUE))
{
moveCheevosList(1);
}
else if (input->checkInput(input_up, REPEAT_TRUE))
{
moveCheevosList(0);
}
}
if (input->checkInput(input_exit, REPEAT_FALSE))
{
section->name = SECTION_PROG_QUIT;
}
else if (input->checkInput(input_toggle_border, REPEAT_FALSE))
{
screen->switchBorder();
resource->reLoadTextures();
}
else if (input->checkInput(input_window_fullscreen, REPEAT_FALSE))
{
screen->switchVideoMode();
resource->reLoadTextures();
}
else if (input->checkInput(input_window_dec_size, REPEAT_FALSE))
{
screen->decWindowSize();
resource->reLoadTextures();
}
else if (input->checkInput(input_window_inc_size, REPEAT_FALSE))
{
screen->incWindowSize();
resource->reLoadTextures();
}
else if (input->checkInput(input_swap_palette, REPEAT_FALSE))
{
switchPalette();
}
else if (input->checkInput(input_accept, REPEAT_FALSE) || input->checkInput(input_pause, REPEAT_FALSE))
{
section->name = SECTION_PROG_GAME;
section->subsection = 0;
}
}
// Actualiza la marquesina
void Title::updateMarquee()
{
@@ -186,17 +255,29 @@ void Title::renderMarquee()
}
}
// Dibuja la linea de información inferior
void Title::renderInfo()
{
const string loginText = options->online.enabled ? "OnLine: " + options->online.jailerID : "OnLine: OFF";
infoText->writeDX(TXT_CENTER | TXT_COLOR, GAMECANVAS_FIRST_QUARTER_X, 1, loginText, 1, stringToColor(options->palette, "white"));
infoText->writeDX(TXT_CENTER | TXT_COLOR, GAMECANVAS_CENTER_X, 1, "H: Help", 1, stringToColor(options->palette, "white"));
infoText->writeDX(TXT_CENTER | TXT_COLOR, GAMECANVAS_THIRD_QUARTER_X, 1, "A: Achievements", 1, stringToColor(options->palette, "white"));
}
// Actualiza las variables
void Title::update()
{
// Comprueba el manejador de eventos
checkEventHandler();
// Comprueba que la diferencia de ticks sea mayor a la velocidad del juego
if (SDL_GetTicks() - ticks > ticksSpeed)
{
// Actualiza el contador de ticks
ticks = SDL_GetTicks();
// Comprueba el manejador de eventos
checkEventHandler();
// Comprueba las entradas
checkInput();
// Incrementa el contador
counter++;
@@ -210,8 +291,16 @@ void Title::update()
// Comprueba si ha terminado la marquesina y acaba con el titulo
if (letters[letters.size() - 1].x < -10)
{
section.name = SECTION_PROG_CREDITS;
section.subsection = 0;
if (!showCheevos)
{
section->name = SECTION_PROG_CREDITS;
section->subsection = 0;
}
else
{
// Inicializa la marquesina
initMarquee();
}
}
}
}
@@ -234,20 +323,27 @@ void Title::render()
// Dibuja la marquesina
renderMarquee();
// Dibuja la linea de información inferior
renderInfo();
// Dibuja la información de logros
if (showCheevos)
{
cheevosSprite->render();
}
// Vuelca el contenido del renderizador en pantalla
screen->blit();
}
// Bucle para el logo del juego
section_t Title::run()
void Title::run()
{
while (section.name == SECTION_PROG_TITLE)
while (section->name == SECTION_PROG_TITLE)
{
update();
render();
}
return section;
}
// Recarga las texturas
@@ -284,4 +380,18 @@ void Title::switchPalette()
// Cambia el color del borde
screen->setBorderColor(stringToColor(options->palette, "bright_blue"));
}
// Desplaza la lista de logros
void Title::moveCheevosList(int direction)
{
cheevosTextureView.y = direction == 0 ? cheevosTextureView.y - 1 : cheevosTextureView.y + 1;
const int bottom = cheevosTexture->getHeight() - cheevosTextureView.h;
if (cheevosTextureView.y < 0)
cheevosTextureView.y = 0;
else if (cheevosTextureView.y > bottom)
cheevosTextureView.y = bottom;
cheevosSprite->setSpriteClip(cheevosTextureView);
}

View File

@@ -1,27 +1,31 @@
#pragma once
#include <SDL2/SDL.h>
#include "common/asset.h"
#include "common/jail_audio.h"
#include "common/resource.h"
#include "common/screen.h"
#include "common/sprite.h"
#include "common/text.h"
#include "common/utils.h"
#include "cheevos.h"
#include "jail_engine/asset.h"
#include "jail_engine/input.h"
#include "jail_engine/jail_audio.h"
#include "jail_engine/resource.h"
#include "jail_engine/screen.h"
#include "jail_engine/sprite.h"
#include "jail_engine/text.h"
#include "jail_engine/utils.h"
#include "const.h"
#include <vector>
#ifndef TITLE_H
#define TITLE_H
using namespace std;
class Title
{
private:
struct letter_t
{
std::string letter; // Letra a escribir
int x; // Posición en el eje x
bool enabled; // Solo se escriben y mueven si estan habilitadas
string letter; // Letra a escribir
int x; // Posición en el eje x
bool enabled; // Solo se escriben y mueven si estan habilitadas
};
// Objetos y punteros
@@ -29,22 +33,29 @@ private:
Screen *screen; // Objeto encargado de dibujar en pantalla
Resource *resource; // Objeto con los recursos
Asset *asset; // Objeto con los ficheros de recursos
Input *input; // Objeto pata gestionar la entrada
SDL_Event *eventHandler; // Manejador de eventos
Texture *texture; // Textura con los graficos
Sprite *sprite; // Sprite para manejar la textura
Text *text; // Objeto para escribir texto en pantalla
Text *infoText; // Objeto para escribir texto en pantalla
options_t *options; // Puntero a las opciones del juego
Texture *pressEnterTexture; // Textura con los graficos de PRESS ENTER
Sprite *pressEnterSprite; // Sprite para manejar la textura de PRESS ENTER
Texture *cheevosTexture; // Textura con lo lista de logros
Sprite *cheevosSprite; // Sprite para manejar la textura con la lista de logros
Cheevos *cheevos; // Objeto encargado de gestionar los logros del juego
section_t *section; // Estado del bucle principal para saber si continua o se sale
// Variables
int counter; // Contador
section_t section; // Estado del bucle principal para saber si continua o se sale
std::string longText; // Texto que aparece en la parte inferior del titulo
Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa
Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles del programa
std::vector<letter_t> letters; // Vector con las letras de la marquesina
int marqueeSpeed; // Velocidad de desplazamiento de la marquesina
int counter; // Contador
string longText; // Texto que aparece en la parte inferior del titulo
Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa
Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles del programa
vector<letter_t> letters; // Vector con las letras de la marquesina
int marqueeSpeed; // Velocidad de desplazamiento de la marquesina
bool showCheevos; // Indica si se muestra por pantalla el listado de logros
SDL_Rect cheevosTextureView; // Zona visible de la textura con el listado de logros
// Actualiza las variables
void update();
@@ -55,27 +66,39 @@ private:
// Comprueba el manejador de eventos
void checkEventHandler();
// Comprueba las entradas
void checkInput();
// Inicializa la marquesina
void initMarquee();
// Actualiza la marquesina
void updateMarquee();
// Dibuja la marquesina
void renderMarquee();
// Dibuja la linea de información inferior
void renderInfo();
// Recarga las texturas
void reLoadTextures();
// Cambia la paleta
void switchPalette();
// Desplaza la lista de logros
void moveCheevosList(int direction);
public:
// Constructor
Title(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *asset, options_t *options);
Title(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *asset, Input *input, options_t *options, section_t *section);
// Destructor
~Title();
// Bucle principal
section_t run();
void run();
};
#endif