Compare commits
61 Commits
2025-01-05
...
3670bad36a
| Author | SHA1 | Date | |
|---|---|---|---|
| 3670bad36a | |||
| 919e2b9ca7 | |||
| 6c7cfaae59 | |||
| 3ee47ba906 | |||
| ff4e356013 | |||
| c757886430 | |||
| f11cb32ac0 | |||
| 9692d01b42 | |||
| d1db4f253e | |||
| 5a6b96f7ab | |||
| a3d4b13f3b | |||
| 215ce999c2 | |||
| 5ccd7eebcd | |||
| 90313da3ce | |||
| 9251d2cf42 | |||
| 059a9c863a | |||
| be857cc8c8 | |||
| 482dc3de54 | |||
| 9d98d3ea6a | |||
| 9c1b3c45b0 | |||
| 79b2917112 | |||
| c88a277cba | |||
| e0c10f83d6 | |||
| 72cb39da78 | |||
| 9f8d1fbcd7 | |||
| e523692e99 | |||
| 83bdd67cee | |||
| 66e5105c84 | |||
| f8449ea6d1 | |||
| f43d18e6f0 | |||
| a42141ebd7 | |||
| 29c85fecad | |||
| 04ff428aa0 | |||
| 84595da13a | |||
| 01591175ef | |||
| 29bc4a64fd | |||
| 559210652f | |||
| 44e4ca490d | |||
| 3cebee2ae4 | |||
| 270d7d1848 | |||
| ccf005dce1 | |||
| 5755947ff7 | |||
| 6f594b9a1f | |||
| 7e2021da70 | |||
| 0a9a92d4b7 | |||
| b01763b749 | |||
| 59b9f61d69 | |||
| b9f194a2b1 | |||
| 59936f13eb | |||
| bad0a10328 | |||
| 52a0c2b91f | |||
| f12a456017 | |||
| f39e65afaf | |||
| d3183237df | |||
| 60302004f4 | |||
| e60938cb19 | |||
| 2b3cc719ba | |||
| d01c91ebde | |||
| 7130f2298a | |||
| 380cc17861 | |||
| a5388873e3 |
@@ -3,6 +3,9 @@
|
||||
cmake_minimum_required(VERSION 3.10)
|
||||
project(coffee_crisis_arcade_edition VERSION 0.01)
|
||||
|
||||
# Establece las políticas
|
||||
cmake_policy(SET CMP0072 NEW)
|
||||
|
||||
# Configuración de compilador para MinGW en Windows, si es necesario
|
||||
if(WIN32 AND NOT CMAKE_CXX_COMPILER_ID MATCHES "MSVC")
|
||||
set(CMAKE_CXX_COMPILER "g++")
|
||||
|
||||
2
Makefile
@@ -11,7 +11,7 @@ APP_NAME := Coffee Crisis Arcade Edition
|
||||
RELEASE_FOLDER := ccae_release
|
||||
RELEASE_FILE := $(RELEASE_FOLDER)/$(TARGET_NAME)
|
||||
RESOURCE_FILE := release/coffee.res
|
||||
VERSION := 2025-01-05
|
||||
VERSION := 2025-02-07
|
||||
|
||||
# Nombres para los ficheros de lanzamiento
|
||||
WINDOWS_RELEASE := $(TARGET_NAME)-$(VERSION)-win32-x64.zip
|
||||
|
||||
21
README.md
@@ -11,7 +11,7 @@ Coffee Crisis Arcade Edition és una versió ampliada i millorada del aclamat Co
|
||||
Defensa el teu cafè contra les bambolles gegants en aquest trepidant joc d'arcade! 🍵
|
||||
|
||||
<p align="center">
|
||||
<img src="https://php.sustancia.synology.me/images/ccae_title.png" alt="Títol" />
|
||||
<img src="https://php.sustancia.synology.me/images/ccae/ccae_title.png" alt="Títol" width="60%" />
|
||||
</p>
|
||||
|
||||
## Controls
|
||||
@@ -25,25 +25,28 @@ El joc està optimitzat per a ser jugat amb un mando de jocs, encara que un dels
|
||||
> Nota: El joc suporta nomes un jugador amb teclat.
|
||||
|
||||
<p align="center">
|
||||
<img src="https://php.sustancia.synology.me/images/ccae1.png" alt="Joc" />
|
||||
<img src="https://php.sustancia.synology.me/images/ccae/ccae1.png" alt="Joc" width="45%" />
|
||||
<img src="https://php.sustancia.synology.me/images/ccae/ccae3.png" alt="Joc" width="45%" />
|
||||
</p>
|
||||
|
||||
## Altres tecles
|
||||
|
||||
| Tecla | Funció |
|
||||
|-------------|----------------------------------------------|
|
||||
|:-----------:|----------------------------------------------------|
|
||||
| **ESC** | Tancar el joc |
|
||||
| **P** | Pausar el joc |
|
||||
| **F1** | Fa la finestra més xicoteta |
|
||||
| **F2** | Fa la finestra més gran |
|
||||
| **F3** | Alterna entre mode de pantalla completa i finestra |
|
||||
| **F4** | Activa o desactiva els shaders |
|
||||
| **F5** | Activa o desactiva l'àudio |
|
||||
| **F6** | Activa o desactiva el dispar automàtic |
|
||||
| **F7** | Canvia l'idioma del joc i reinicia |
|
||||
| **F10** | Reset del joc |
|
||||
| **F4** | Activa o desactiva el filtre de pantalla |
|
||||
| **F5** | Activa o desactiva el mode d'escalat sencer |
|
||||
| **F6** | Activa o desactiva l'àudio |
|
||||
| **F7** | Activa o desactiva el dispar automàtic |
|
||||
| **F8** | Canvia l'idioma del joc (Provoca el reinici) |
|
||||
| **F10** | Reinicia el joc |
|
||||
|
||||
<p align="center">
|
||||
<img src="https://php.sustancia.synology.me/images/ccae2.png" alt="Joc" />
|
||||
<img src="https://php.sustancia.synology.me/images/ccae/ccae2.png" alt="Joc" width="50%" />
|
||||
</p>
|
||||
|
||||
## Com instal·lar i jugar
|
||||
|
||||
BIN
data/font/04b_25_grey.png
Normal file
|
After Width: | Height: | Size: 3.1 KiB |
BIN
data/font/04b_25_metal.png
Normal file
|
After Width: | Height: | Size: 3.2 KiB |
|
Before Width: | Height: | Size: 2.4 KiB |
@@ -1,194 +0,0 @@
|
||||
# box width
|
||||
10
|
||||
# box height
|
||||
10
|
||||
# 32 espacio ( )
|
||||
5
|
||||
# 33 !
|
||||
4
|
||||
# 34 "
|
||||
5
|
||||
# 35 #
|
||||
7
|
||||
# 36 $
|
||||
7
|
||||
# 37 %
|
||||
8
|
||||
# 38 &
|
||||
8
|
||||
# 39 '
|
||||
3
|
||||
# 40 (
|
||||
5
|
||||
# 41 )
|
||||
5
|
||||
# 42 *
|
||||
7
|
||||
# 43 +
|
||||
7
|
||||
# 44 ,
|
||||
4
|
||||
# 45 -
|
||||
6
|
||||
# 46 .
|
||||
4
|
||||
# 47 /
|
||||
5
|
||||
# 48 0
|
||||
7
|
||||
# 49 1
|
||||
5
|
||||
# 50 2
|
||||
7
|
||||
# 51 3
|
||||
7
|
||||
# 52 4
|
||||
7
|
||||
# 53 5
|
||||
7
|
||||
# 54 6
|
||||
7
|
||||
# 55 7
|
||||
7
|
||||
# 56 8
|
||||
7
|
||||
# 57 9
|
||||
7
|
||||
# 58 :
|
||||
4
|
||||
# 59 ;
|
||||
4
|
||||
# 60 <
|
||||
6
|
||||
# 61 =
|
||||
6
|
||||
# 62 >
|
||||
6
|
||||
# 63 ?
|
||||
7
|
||||
# 64 @
|
||||
8
|
||||
# 65 A
|
||||
7
|
||||
# 66 B
|
||||
7
|
||||
# 67 C
|
||||
7
|
||||
# 68 D
|
||||
7
|
||||
# 69 E
|
||||
7
|
||||
# 70 F
|
||||
7
|
||||
# 71 G
|
||||
7
|
||||
# 72 H
|
||||
7
|
||||
# 73 I
|
||||
4
|
||||
# 74 J
|
||||
6
|
||||
# 75 K
|
||||
8
|
||||
# 76 L
|
||||
6
|
||||
# 77 M
|
||||
9
|
||||
# 78 N
|
||||
8
|
||||
# 79 O
|
||||
8
|
||||
# 80 P
|
||||
7
|
||||
# 81 Q
|
||||
8
|
||||
# 82 R
|
||||
7
|
||||
# 83 S
|
||||
6
|
||||
# 84 T
|
||||
8
|
||||
# 85 U
|
||||
7
|
||||
# 86 V
|
||||
8
|
||||
# 87 W
|
||||
9
|
||||
# 88 X
|
||||
8
|
||||
# 89 Y
|
||||
8
|
||||
# 90 Z
|
||||
7
|
||||
# 91 [
|
||||
4
|
||||
# 92 \
|
||||
5
|
||||
# 93 ]
|
||||
4
|
||||
# 94 ^
|
||||
5
|
||||
# 95 _
|
||||
8
|
||||
# 96 `
|
||||
4
|
||||
# 97 a
|
||||
7
|
||||
# 98 b
|
||||
7
|
||||
# 99 c
|
||||
6
|
||||
# 100 d
|
||||
7
|
||||
# 101 e
|
||||
7
|
||||
# 102 f
|
||||
5
|
||||
# 103 g
|
||||
7
|
||||
# 104 h
|
||||
7
|
||||
# 105 i
|
||||
4
|
||||
# 106 j
|
||||
5
|
||||
# 107 k
|
||||
7
|
||||
# 108 l
|
||||
4
|
||||
# 109 m
|
||||
10
|
||||
# 110 n
|
||||
7
|
||||
# 111 o
|
||||
7
|
||||
# 112 p
|
||||
7
|
||||
# 113 q
|
||||
7
|
||||
# 114 r
|
||||
6
|
||||
# 115 s
|
||||
6
|
||||
# 116 t
|
||||
5
|
||||
# 117 u
|
||||
7
|
||||
# 118 v
|
||||
7
|
||||
# 119 w
|
||||
9
|
||||
# 120 x
|
||||
7
|
||||
# 121 y
|
||||
7
|
||||
# 122 z
|
||||
7
|
||||
# 123 { -> ñ
|
||||
7
|
||||
# 124 | -> ç
|
||||
7
|
||||
# 125 }
|
||||
0
|
||||
# 126 ~
|
||||
0
|
||||
|
Before Width: | Height: | Size: 1.1 KiB After Width: | Height: | Size: 1.1 KiB |
|
Before Width: | Height: | Size: 13 KiB |
BIN
data/gfx/intro/intro1.png
Normal file
|
After Width: | Height: | Size: 52 KiB |
BIN
data/gfx/intro/intro2.png
Normal file
|
After Width: | Height: | Size: 4.8 KiB |
BIN
data/gfx/intro/intro3.png
Normal file
|
After Width: | Height: | Size: 3.3 KiB |
BIN
data/gfx/intro/intro4.png
Normal file
|
After Width: | Height: | Size: 1.8 KiB |
BIN
data/gfx/intro/intro5.png
Normal file
|
After Width: | Height: | Size: 5.7 KiB |
BIN
data/gfx/intro/intro6.png
Normal file
|
After Width: | Height: | Size: 4.4 KiB |
9
data/gfx/item/item_debian.ani
Normal file
@@ -0,0 +1,9 @@
|
||||
frame_width=20
|
||||
frame_height=20
|
||||
|
||||
[animation]
|
||||
name=default
|
||||
speed=10
|
||||
loop=0
|
||||
frames=0,1
|
||||
[/animation]
|
||||
BIN
data/gfx/item/item_debian.png
Normal file
|
After Width: | Height: | Size: 565 B |
@@ -2,8 +2,15 @@ frame_width=32
|
||||
frame_height=32
|
||||
|
||||
[animation]
|
||||
name=default
|
||||
name=fly
|
||||
speed=2
|
||||
loop=0
|
||||
frames=0,1
|
||||
[/animation]
|
||||
|
||||
[animation]
|
||||
name=hit
|
||||
speed=2
|
||||
loop=0
|
||||
frames=2,3
|
||||
[/animation]
|
||||
|
Before Width: | Height: | Size: 1.8 KiB After Width: | Height: | Size: 2.6 KiB |
@@ -32,7 +32,7 @@ IDIOMA
|
||||
[ CANCELAR ]
|
||||
|
||||
## 11 - INSTRUCCIONES
|
||||
OBJECTIU
|
||||
Objectiu
|
||||
|
||||
## 12 - INSTRUCCIONES
|
||||
HAS D'EXPLOTAR
|
||||
@@ -47,7 +47,7 @@ LA DIFICULTAT AUGMENTA
|
||||
A MESURA QUE VAS PUNTUANT
|
||||
|
||||
## 16 - INSTRUCCIONES
|
||||
OBJECTES
|
||||
Objectes
|
||||
|
||||
## 17 - INSTRUCCIONES
|
||||
1.000 PUNTS
|
||||
@@ -101,10 +101,10 @@ Espera un moment...
|
||||
Si resulta que no tinc solt!
|
||||
|
||||
## 34 - INTRO
|
||||
MERDA DE MAQUINA!
|
||||
VAJA BIRRIA DE MAQUINA !!!
|
||||
|
||||
## 35 - INTRO
|
||||
Blop... blop... blop...
|
||||
blop... blop... blop...
|
||||
|
||||
## 36 - TEXTOS DEL JUEGO
|
||||
Temps detes:
|
||||
@@ -372,3 +372,36 @@ MUSICA COMPOSADA PER
|
||||
|
||||
## 124 - CREDITS
|
||||
EFECTES DE SO
|
||||
|
||||
## 125 - NOTIFICACIONES
|
||||
Torna a polsar per reiniciar
|
||||
|
||||
## 126 - NOTIFICACIONES
|
||||
Torna a polsar per canviar el idioma a
|
||||
|
||||
## 127 - NOTIFICACIONES
|
||||
Idioma canviat a
|
||||
|
||||
## 128 - VARIOS
|
||||
activat
|
||||
|
||||
## 129 - VARIOS
|
||||
desactivat
|
||||
|
||||
## 130 - VARIOS
|
||||
Dispar automatic
|
||||
|
||||
## 131 - VARIOS
|
||||
Zoom de finestra
|
||||
|
||||
## 132 - VARIOS
|
||||
Mode finestra
|
||||
|
||||
## 133 - VARIOS
|
||||
Mode pantalla completa
|
||||
|
||||
## 134 - VARIOS
|
||||
Mode d'escalat sencer
|
||||
|
||||
## 135 - VARIOS
|
||||
Filtre
|
||||
@@ -372,3 +372,36 @@ MUSIC COMPOSED BY
|
||||
|
||||
## 124 - CREDITS
|
||||
SOUND EFFECTS
|
||||
|
||||
## 125 - NOTIFICACIONES
|
||||
Press again to reset
|
||||
|
||||
## 126 - NOTIFICACIONES
|
||||
Press again to change languaje to
|
||||
|
||||
## 127 - NOTIFICACIONES
|
||||
Language set to
|
||||
|
||||
## 128 - VARIOS
|
||||
on
|
||||
|
||||
## 129 - VARIOS
|
||||
off
|
||||
|
||||
## 130 - VARIOS
|
||||
Autofire
|
||||
|
||||
## 131 - VARIOS
|
||||
Window zoom
|
||||
|
||||
## 132 - VARIOS
|
||||
Window mode
|
||||
|
||||
## 133 - VARIOS
|
||||
Fullscreen mode
|
||||
|
||||
## 134 - VARIOS
|
||||
Integer scale
|
||||
|
||||
## 135 - VARIOS
|
||||
Filter
|
||||
@@ -372,3 +372,36 @@ MUSICA COMPUESTA POR
|
||||
|
||||
## 124 - CREDITS
|
||||
EFECTOS DE SONIDO
|
||||
|
||||
## 125 - NOTIFICACIONES
|
||||
Vuelve a pulsar para reiniciar
|
||||
|
||||
## 126 - NOTIFICACIONES
|
||||
Vuelve a pulsar para cambiar el idioma a
|
||||
|
||||
## 127 - NOTIFICACIONES
|
||||
Idioma cambiado a
|
||||
|
||||
## 128 - VARIOS
|
||||
activado
|
||||
|
||||
## 129 - VARIOS
|
||||
desactivado
|
||||
|
||||
## 130 - VARIOS
|
||||
Disparo automático
|
||||
|
||||
## 131 - VARIOS
|
||||
Zoom de ventana
|
||||
|
||||
## 132 - VARIOS
|
||||
Modo ventana
|
||||
|
||||
## 133 - VARIOS
|
||||
Modo pantalla completa
|
||||
|
||||
## 134 - VARIOS
|
||||
Modo de escalado entero
|
||||
|
||||
## 135 - VARIOS
|
||||
Filtro
|
||||
BIN
data/sound/debian_drop.wav
Normal file
BIN
data/sound/debian_pickup.wav
Normal file
BIN
data/sound/tabe_hit.wav
Normal file
@@ -56,13 +56,13 @@ private:
|
||||
~Asset() = default;
|
||||
|
||||
public:
|
||||
// [SINGLETON] Crearemos el objeto screen con esta función estática
|
||||
// [SINGLETON] Crearemos el objeto con esta función estática
|
||||
static void init(const std::string &executable_path);
|
||||
|
||||
// [SINGLETON] Destruiremos el objeto screen con esta función estática
|
||||
// [SINGLETON] Destruiremos el objeto con esta función estática
|
||||
static void destroy();
|
||||
|
||||
// [SINGLETON] Con este método obtenemos el objeto screen y podemos trabajar con él
|
||||
// [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él
|
||||
static Asset *get();
|
||||
|
||||
// Añade un elemento a la lista
|
||||
|
||||
@@ -226,16 +226,6 @@ void Background::render()
|
||||
SDL_RenderCopy(renderer_, color_texture_, &src_rect_, &dst_rect_);
|
||||
}
|
||||
|
||||
// Vuelve a cargar las texturas
|
||||
void Background::reloadTextures()
|
||||
{
|
||||
buildings_texture_->reLoad();
|
||||
top_clouds_texture_->reLoad();
|
||||
bottom_clouds_texture_->reLoad();
|
||||
grass_texture_->reLoad();
|
||||
gradients_texture_->reLoad();
|
||||
}
|
||||
|
||||
// Ajusta el valor de la variable
|
||||
void Background::setCloudsSpeed(float value)
|
||||
{
|
||||
|
||||
@@ -131,9 +131,6 @@ public:
|
||||
// Establece la posición del objeto
|
||||
void setPos(SDL_Rect pos);
|
||||
|
||||
// Vuelve a cargar las texturas
|
||||
void reloadTextures();
|
||||
|
||||
// Ajusta el valor de la variable
|
||||
void setCloudsSpeed(float value);
|
||||
|
||||
|
||||
@@ -9,9 +9,8 @@
|
||||
#include "param.h" // Para Param, ParamGame, param
|
||||
#include "resource.h" // Para Resource
|
||||
#include "screen.h" // Para Screen
|
||||
#include "stage.h" // Para power
|
||||
#include "texture.h" // Para Texture
|
||||
#include "utils.h" // Para Zone, BLOCK, Color, flash_color
|
||||
#include "stage.h" // Para addPower
|
||||
#include "utils.h" // Para Zone, Color, flash_color
|
||||
|
||||
// Constructor
|
||||
BalloonManager::BalloonManager()
|
||||
@@ -321,7 +320,7 @@ int BalloonManager::destroyAllBalloons()
|
||||
}
|
||||
|
||||
balloon_deploy_counter_ = 300;
|
||||
JA_PlaySound(Resource::get()->getSound("powerball.wav"));
|
||||
JA_PlaySound(Resource::get()->getSound("power_ball_explosion.wav"));
|
||||
Screen::get()->flash(flash_color, 3);
|
||||
Screen::get()->shake();
|
||||
|
||||
@@ -370,15 +369,6 @@ void BalloonManager::normalColorsToAllBalloons()
|
||||
}
|
||||
}
|
||||
|
||||
// Recarga las texturas
|
||||
void BalloonManager::reLoad()
|
||||
{
|
||||
for (auto &texture : balloon_textures_)
|
||||
{
|
||||
texture->reLoad();
|
||||
}
|
||||
}
|
||||
|
||||
// Crea dos globos gordos
|
||||
void BalloonManager::createTwoBigBalloons()
|
||||
{
|
||||
|
||||
@@ -104,9 +104,6 @@ public:
|
||||
// Cambia el color de todos los globos
|
||||
void normalColorsToAllBalloons();
|
||||
|
||||
// Recarga las texturas
|
||||
void reLoad();
|
||||
|
||||
// Crea dos globos gordos
|
||||
void createTwoBigBalloons();
|
||||
|
||||
|
||||
@@ -9,13 +9,14 @@
|
||||
#include <stdexcept> // Para runtime_error
|
||||
#include <string> // Para basic_string, string
|
||||
#include <vector> // Para vector
|
||||
#include <array> // Para vector
|
||||
#include "balloon_manager.h" // Para BalloonManager
|
||||
#include "fade.h" // Para Fade, FadeType, FadeMode
|
||||
#include "global_inputs.h" // Para check, update
|
||||
#include "input.h" // Para Input
|
||||
#include "jail_audio.h" // Para JA_GetMusicState, JA_SetMusicVolume
|
||||
#include "lang.h" // Para getText
|
||||
#include "mouse.h" // Para handleEvent
|
||||
#include "global_events.h" // Para handleEvent
|
||||
#include "param.h" // Para Param, ParamGame, param
|
||||
#include "player.h" // Para Player, PlayerState
|
||||
#include "resource.h" // Para Resource
|
||||
@@ -68,6 +69,7 @@ Credits::~Credits()
|
||||
SDL_DestroyTexture(text_texture_);
|
||||
SDL_DestroyTexture(canvas_);
|
||||
resetVolume();
|
||||
JA_StopMusic();
|
||||
}
|
||||
|
||||
// Bucle principal
|
||||
@@ -85,13 +87,11 @@ void Credits::run()
|
||||
// Actualiza las variables
|
||||
void Credits::update()
|
||||
{
|
||||
constexpr Uint32 TICKS_SPEED_ = 15;
|
||||
|
||||
if (SDL_GetTicks() - ticks_ > TICKS_SPEED_)
|
||||
if (SDL_GetTicks() - ticks_ > param.game.speed)
|
||||
{
|
||||
ticks_ = SDL_GetTicks();
|
||||
const int repeat = want_to_pass_ ? 4 : 1;
|
||||
for (int i = 0; i < repeat; ++i)
|
||||
const int REPEAT = want_to_pass_ ? 4 : 1;
|
||||
for (int i = 0; i < REPEAT; ++i)
|
||||
{
|
||||
tiled_bg_->update();
|
||||
balloon_manager_->update();
|
||||
@@ -104,6 +104,7 @@ void Credits::update()
|
||||
updateAllFades();
|
||||
++counter_;
|
||||
}
|
||||
|
||||
Screen::get()->update();
|
||||
globalInputs::update();
|
||||
|
||||
@@ -128,20 +129,9 @@ void Credits::render()
|
||||
void Credits::checkEvents()
|
||||
{
|
||||
SDL_Event event;
|
||||
|
||||
// Comprueba los eventos que hay en la cola
|
||||
while (SDL_PollEvent(&event))
|
||||
{
|
||||
// Evento de salida de la aplicación
|
||||
if (event.type == SDL_QUIT)
|
||||
{
|
||||
section::name = section::Name::QUIT;
|
||||
section::options = section::Options::QUIT_FROM_EVENT;
|
||||
break;
|
||||
}
|
||||
|
||||
// Comprueba el cursor
|
||||
Mouse::handleEvent(event);
|
||||
globalEvents::check(event);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -176,7 +166,7 @@ void Credits::fillTextTexture()
|
||||
SDL_SetRenderDrawColor(Screen::get()->getRenderer(), 0, 0, 0, 0);
|
||||
SDL_RenderClear(Screen::get()->getRenderer());
|
||||
|
||||
std::vector<std::string> texts = {
|
||||
const std::array<std::string, 10> TEXTS = {
|
||||
lang::getText(121),
|
||||
lang::getText(122),
|
||||
lang::getText(123),
|
||||
@@ -188,50 +178,50 @@ void Credits::fillTextTexture()
|
||||
"WWW.KENNEY.NL",
|
||||
"JAILDOCTOR"};
|
||||
|
||||
const int space_post_title = 3 + text->getCharacterSize();
|
||||
const int space_pre_title = text->getCharacterSize() * 4;
|
||||
const int texts_height = 1 * text->getCharacterSize() + 7 * space_post_title + 3 * space_pre_title;
|
||||
credits_rect_dst_.h = credits_rect_src_.h = texts_height;
|
||||
const int SPACE_POST_TITLE = 3 + text->getCharacterSize();
|
||||
const int SPACE_PRE_TITLE = text->getCharacterSize() * 4;
|
||||
const int TEXTS_HEIGHT = 1 * text->getCharacterSize() + 7 * SPACE_POST_TITLE + 3 * SPACE_PRE_TITLE;
|
||||
credits_rect_dst_.h = credits_rect_src_.h = TEXTS_HEIGHT;
|
||||
|
||||
int y = (param.game.height - texts_height) / 2;
|
||||
int y = (param.game.height - TEXTS_HEIGHT) / 2;
|
||||
y = 0;
|
||||
text->setPalette(1);
|
||||
text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, texts.at(0), 1, no_color, 1, shdw_txt_color);
|
||||
text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, TEXTS.at(0), 1, no_color, 1, shdw_txt_color);
|
||||
|
||||
text->setPalette(0);
|
||||
y += space_post_title;
|
||||
text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, texts.at(4), 1, no_color, 1, shdw_txt_color);
|
||||
y += SPACE_POST_TITLE;
|
||||
text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, TEXTS.at(4), 1, no_color, 1, shdw_txt_color);
|
||||
|
||||
y += space_pre_title;
|
||||
y += SPACE_PRE_TITLE;
|
||||
text->setPalette(1);
|
||||
text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, texts.at(1), 1, no_color, 1, shdw_txt_color);
|
||||
text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, TEXTS.at(1), 1, no_color, 1, shdw_txt_color);
|
||||
text->setPalette(0);
|
||||
y += space_post_title;
|
||||
text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, texts.at(4), 1, no_color, 1, shdw_txt_color);
|
||||
y += SPACE_POST_TITLE;
|
||||
text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, TEXTS.at(4), 1, no_color, 1, shdw_txt_color);
|
||||
|
||||
y += space_pre_title;
|
||||
y += SPACE_PRE_TITLE;
|
||||
text->setPalette(1);
|
||||
text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, texts.at(2), 1, no_color, 1, shdw_txt_color);
|
||||
text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, TEXTS.at(2), 1, no_color, 1, shdw_txt_color);
|
||||
text->setPalette(0);
|
||||
|
||||
y += space_post_title;
|
||||
text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, texts.at(5), 1, no_color, 1, shdw_txt_color);
|
||||
y += space_post_title;
|
||||
text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, texts.at(6), 1, no_color, 1, shdw_txt_color);
|
||||
y += SPACE_POST_TITLE;
|
||||
text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, TEXTS.at(5), 1, no_color, 1, shdw_txt_color);
|
||||
y += SPACE_POST_TITLE;
|
||||
text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, TEXTS.at(6), 1, no_color, 1, shdw_txt_color);
|
||||
|
||||
y += space_pre_title;
|
||||
y += SPACE_PRE_TITLE;
|
||||
text->setPalette(1);
|
||||
text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, texts.at(3), 1, no_color, 1, shdw_txt_color);
|
||||
text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, TEXTS.at(3), 1, no_color, 1, shdw_txt_color);
|
||||
text->setPalette(0);
|
||||
y += space_post_title;
|
||||
text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, texts.at(7), 1, no_color, 1, shdw_txt_color);
|
||||
y += space_post_title;
|
||||
text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, texts.at(8), 1, no_color, 1, shdw_txt_color);
|
||||
y += space_post_title;
|
||||
text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, texts.at(9), 1, no_color, 1, shdw_txt_color);
|
||||
y += SPACE_POST_TITLE;
|
||||
text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, TEXTS.at(7), 1, no_color, 1, shdw_txt_color);
|
||||
y += SPACE_POST_TITLE;
|
||||
text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, TEXTS.at(8), 1, no_color, 1, shdw_txt_color);
|
||||
y += SPACE_POST_TITLE;
|
||||
text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, TEXTS.at(9), 1, no_color, 1, shdw_txt_color);
|
||||
|
||||
// Mini logo
|
||||
y += space_pre_title;
|
||||
y += SPACE_PRE_TITLE;
|
||||
mini_logo_rect_src_.y = y;
|
||||
auto mini_logo_sprite = std::make_unique<Sprite>(Resource::get()->getTexture("logo_jailgames_mini.png"));
|
||||
mini_logo_sprite->setPosition(1 + param.game.game_area.center_x - mini_logo_sprite->getWidth() / 2, 1 + y);
|
||||
@@ -477,7 +467,7 @@ void Credits::updateAllFades()
|
||||
fade_out_->update();
|
||||
if (fade_out_->hasEnded())
|
||||
{
|
||||
section::name = section::Name::LOGO;
|
||||
section::name = section::Name::HI_SCORE_TABLE;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -4,7 +4,6 @@
|
||||
#include "options.h" // Para OptionsController, Options, options
|
||||
#include "param.h" // Para Param, param, ParamGame, ParamTitle
|
||||
#include "resource.h" // Para Resource
|
||||
#include "section.h" // Para Name, Options, name, options
|
||||
#include "text.h" // Para Text
|
||||
|
||||
// Constructor
|
||||
@@ -62,32 +61,11 @@ void DefineButtons::bindButtons()
|
||||
}
|
||||
|
||||
// Comprueba los eventos
|
||||
void DefineButtons::checkEvents()
|
||||
void DefineButtons::checkEvents(const SDL_Event &event)
|
||||
{
|
||||
if (enabled_)
|
||||
{
|
||||
SDL_Event event;
|
||||
|
||||
// Comprueba los eventos que hay en la cola
|
||||
while (SDL_PollEvent(&event))
|
||||
{
|
||||
switch (event.type)
|
||||
{
|
||||
case SDL_QUIT:
|
||||
{
|
||||
section::name = section::Name::QUIT;
|
||||
section::options = section::Options::QUIT_WITH_KEYBOARD;
|
||||
break;
|
||||
}
|
||||
case SDL_CONTROLLERBUTTONDOWN:
|
||||
if (enabled_ && event.type == SDL_CONTROLLERBUTTONDOWN)
|
||||
{
|
||||
doControllerButtonDown(event.cbutton);
|
||||
break;
|
||||
}
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -67,7 +67,7 @@ public:
|
||||
void render();
|
||||
|
||||
// Comprueba los eventos
|
||||
void checkEvents();
|
||||
void checkEvents(const SDL_Event &event);
|
||||
|
||||
// Habilita el objeto
|
||||
bool enable(int index);
|
||||
|
||||
@@ -4,14 +4,13 @@
|
||||
#include <SDL2/SDL_audio.h> // Para AUDIO_S16
|
||||
#include <SDL2/SDL_blendmode.h> // Para SDL_BLENDMODE_BLEND
|
||||
#include <SDL2/SDL_error.h> // Para SDL_GetError
|
||||
#include <SDL2/SDL_events.h> // Para SDL_DISABLE
|
||||
#include <SDL2/SDL_gamecontroller.h> // Para SDL_CONTROLLER_BUTTON_B, SDL_CO...
|
||||
#include <SDL2/SDL_hints.h> // Para SDL_SetHint, SDL_HINT_RENDER_DR...
|
||||
#include <SDL2/SDL_mouse.h> // Para SDL_ShowCursor
|
||||
#include <SDL2/SDL_scancode.h> // Para SDL_SCANCODE_0, SDL_SCANCODE_DOWN
|
||||
#include <SDL2/SDL_stdinc.h> // Para SDL_bool, Uint32
|
||||
#include <SDL2/SDL_stdinc.h> // Para Uint32, SDL_bool
|
||||
#include <errno.h> // Para errno, EEXIST, EACCES, ENAMETOO...
|
||||
#ifndef _WIN32
|
||||
#include <pwd.h> // Para getpwuid, passwd
|
||||
#endif
|
||||
#include <stdio.h> // Para printf, perror
|
||||
#include <sys/stat.h> // Para mkdir, stat, S_IRWXU
|
||||
#include <unistd.h> // Para getuid
|
||||
@@ -45,6 +44,10 @@
|
||||
#include "title.h" // Para Title
|
||||
#include "utils.h" // Para Overrides, overrides
|
||||
|
||||
#ifndef _WIN32
|
||||
#include <pwd.h> // Para getpwuid, passwd
|
||||
#endif
|
||||
|
||||
// Constructor
|
||||
Director::Director(int argc, const char *argv[])
|
||||
{
|
||||
@@ -55,6 +58,7 @@ Director::Director(int argc, const char *argv[])
|
||||
section::name = section::Name::LOGO;
|
||||
#else // NORMAL GAME
|
||||
section::name = section::Name::LOGO;
|
||||
section::options = section::Options::NONE;
|
||||
section::attract_mode = section::AttractMode::TITLE_TO_DEMO;
|
||||
#endif
|
||||
|
||||
@@ -97,6 +101,7 @@ void Director::init()
|
||||
|
||||
// Inicializa y crea el resto de objetos
|
||||
initSDL();
|
||||
SDL_ShowCursor(SDL_DISABLE);
|
||||
initJailAudio();
|
||||
dbg_init(renderer_);
|
||||
lang::loadFromFile(getLangFile(static_cast<lang::Code>(options.game.language)));
|
||||
@@ -126,6 +131,10 @@ void Director::close()
|
||||
SDL_DestroyWindow(window_);
|
||||
|
||||
SDL_Quit();
|
||||
|
||||
#ifdef ARCADE
|
||||
shutdownSystem(section::options == section::Options::QUIT_WITH_CONTROLLER);
|
||||
#endif
|
||||
}
|
||||
|
||||
// Carga los parametros
|
||||
@@ -173,16 +182,21 @@ void Director::bindInputs()
|
||||
Input::get()->bindKey(InputType::SERVICE, SDL_SCANCODE_0);
|
||||
Input::get()->bindKey(InputType::EXIT, SDL_SCANCODE_ESCAPE);
|
||||
Input::get()->bindKey(InputType::PAUSE, SDL_SCANCODE_P);
|
||||
|
||||
Input::get()->bindKey(InputType::WINDOW_DEC_SIZE, SDL_SCANCODE_F1);
|
||||
Input::get()->bindKey(InputType::WINDOW_INC_SIZE, SDL_SCANCODE_F2);
|
||||
Input::get()->bindKey(InputType::WINDOW_FULLSCREEN, SDL_SCANCODE_F3);
|
||||
Input::get()->bindKey(InputType::VIDEO_SHADERS, SDL_SCANCODE_F4);
|
||||
Input::get()->bindKey(InputType::MUTE, SDL_SCANCODE_F5);
|
||||
Input::get()->bindKey(InputType::AUTO_FIRE, SDL_SCANCODE_F6);
|
||||
Input::get()->bindKey(InputType::CHANGE_LANG, SDL_SCANCODE_F7);
|
||||
Input::get()->bindKey(InputType::SHOWINFO, SDL_SCANCODE_F8);
|
||||
Input::get()->bindKey(InputType::VIDEO_INTEGER_SCALE, SDL_SCANCODE_F5);
|
||||
|
||||
Input::get()->bindKey(InputType::MUTE, SDL_SCANCODE_F6);
|
||||
Input::get()->bindKey(InputType::AUTO_FIRE, SDL_SCANCODE_F7);
|
||||
Input::get()->bindKey(InputType::CHANGE_LANG, SDL_SCANCODE_F8);
|
||||
|
||||
Input::get()->bindKey(InputType::RESET, SDL_SCANCODE_F10);
|
||||
|
||||
Input::get()->bindKey(InputType::SHOWINFO, SDL_SCANCODE_F12);
|
||||
|
||||
// Asigna botones a inputs
|
||||
const int num_gamepads = Input::get()->getNumControllers();
|
||||
for (int i = 0; i < num_gamepads; ++i)
|
||||
@@ -283,28 +297,17 @@ bool Director::initSDL()
|
||||
}
|
||||
else
|
||||
{
|
||||
/*
|
||||
// Muestra información de la pantalla
|
||||
std::cout << "\nDisplay modes list:" << std::endl;
|
||||
for (int i = 0; i < SDL_GetNumDisplayModes(0); ++i)
|
||||
{
|
||||
SDL_DisplayMode DM;
|
||||
SDL_GetDisplayMode(0,i,&DM);
|
||||
std::cout << " - " << DM.w << "x" << DM.h << " @ " << DM.refresh_rate << "Hz" << std::endl;
|
||||
}
|
||||
*/
|
||||
|
||||
// Obtiene información sobre la pantalla
|
||||
SDL_DisplayMode DM;
|
||||
SDL_GetCurrentDisplayMode(0, &DM);
|
||||
|
||||
// Calcula el máximo factor de zoom que se puede aplicar a la pantalla
|
||||
options.video.window.max_size = std::min(DM.w / param.game.width, DM.h / param.game.height);
|
||||
options.video.window.size = std::min(options.video.window.size, options.video.window.max_size);
|
||||
options.video.window.max_zoom = std::min(DM.w / param.game.width, DM.h / param.game.height);
|
||||
options.video.window.zoom = std::min(options.video.window.zoom, options.video.window.max_zoom);
|
||||
|
||||
// Muestra información sobre el tamaño de la pantalla y de la ventana de juego
|
||||
std::cout << "\nCurrent display mode: " << DM.w << "x" << DM.h << " @ " << DM.refresh_rate << "Hz" << std::endl;
|
||||
std::cout << "Window resolution : " << param.game.width << "x" << param.game.height << " x" << options.video.window.size << std::endl;
|
||||
std::cout << "Window resolution : " << param.game.width << "x" << param.game.height << " x" << options.video.window.zoom << std::endl;
|
||||
|
||||
// Establece el filtro de la textura
|
||||
if (!SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, std::to_string(static_cast<int>(options.video.filter)).c_str()))
|
||||
@@ -312,15 +315,13 @@ bool Director::initSDL()
|
||||
std::cout << "Warning: texture filtering not enabled!\n";
|
||||
}
|
||||
|
||||
#ifndef NO_SHADERS
|
||||
if (!SDL_SetHint(SDL_HINT_RENDER_DRIVER, "opengl"))
|
||||
{
|
||||
std::cout << "Warning: opengl not enabled!\n";
|
||||
}
|
||||
#endif
|
||||
|
||||
// Crea la ventana
|
||||
window_ = SDL_CreateWindow(WINDOW_CAPTION, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, param.game.width * options.video.window.size, param.game.height * options.video.window.size, SDL_WINDOW_HIDDEN);
|
||||
window_ = SDL_CreateWindow(WINDOW_CAPTION, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, param.game.width * options.video.window.zoom, param.game.height * options.video.window.zoom, SDL_WINDOW_HIDDEN);
|
||||
if (!window_)
|
||||
{
|
||||
std::cout << "Window could not be created!\nSDL Error: " << SDL_GetError() << std::endl;
|
||||
@@ -335,10 +336,8 @@ bool Director::initSDL()
|
||||
flags = SDL_RENDERER_PRESENTVSYNC;
|
||||
}
|
||||
|
||||
#ifndef NO_SHADERS
|
||||
// La aceleración se activa según el define
|
||||
flags = flags | SDL_RENDERER_ACCELERATED | SDL_RENDERER_TARGETTEXTURE;
|
||||
#endif
|
||||
|
||||
renderer_ = SDL_CreateRenderer(window_, -1, flags);
|
||||
|
||||
@@ -352,6 +351,7 @@ bool Director::initSDL()
|
||||
SDL_SetRenderDrawColor(renderer_, 0x00, 0x00, 0x00, 0xFF);
|
||||
SDL_RenderSetLogicalSize(renderer_, param.game.width, param.game.height);
|
||||
SDL_RenderSetIntegerScale(renderer_, static_cast<SDL_bool>(options.video.integer_scale));
|
||||
SDL_SetWindowFullscreen(window_, static_cast<Uint32>(options.video.mode));
|
||||
SDL_SetRenderDrawBlendMode(renderer_, SDL_BLENDMODE_BLEND);
|
||||
}
|
||||
}
|
||||
@@ -393,16 +393,16 @@ void Director::setFileList()
|
||||
Asset::get()->add(prefix + "/data/sound/bubble4.wav", AssetType::SOUND);
|
||||
Asset::get()->add(prefix + "/data/sound/bullet.wav", AssetType::SOUND);
|
||||
Asset::get()->add(prefix + "/data/sound/clock.wav", AssetType::SOUND);
|
||||
Asset::get()->add(prefix + "/data/sound/coffeeout.wav", AssetType::SOUND);
|
||||
Asset::get()->add(prefix + "/data/sound/coffee_out.wav", AssetType::SOUND);
|
||||
Asset::get()->add(prefix + "/data/sound/continue_clock.wav", AssetType::SOUND);
|
||||
Asset::get()->add(prefix + "/data/sound/game_start.wav", AssetType::SOUND);
|
||||
Asset::get()->add(prefix + "/data/sound/hiscore.wav", AssetType::SOUND);
|
||||
Asset::get()->add(prefix + "/data/sound/itemdrop.wav", AssetType::SOUND);
|
||||
Asset::get()->add(prefix + "/data/sound/itempickup.wav", AssetType::SOUND);
|
||||
Asset::get()->add(prefix + "/data/sound/hi_score_achieved.wav", AssetType::SOUND);
|
||||
Asset::get()->add(prefix + "/data/sound/item_drop.wav", AssetType::SOUND);
|
||||
Asset::get()->add(prefix + "/data/sound/item_pickup.wav", AssetType::SOUND);
|
||||
Asset::get()->add(prefix + "/data/sound/logo.wav", AssetType::SOUND);
|
||||
Asset::get()->add(prefix + "/data/sound/notify.wav", AssetType::SOUND);
|
||||
Asset::get()->add(prefix + "/data/sound/player_collision.wav", AssetType::SOUND);
|
||||
Asset::get()->add(prefix + "/data/sound/powerball.wav", AssetType::SOUND);
|
||||
Asset::get()->add(prefix + "/data/sound/power_ball_explosion.wav", AssetType::SOUND);
|
||||
Asset::get()->add(prefix + "/data/sound/stage_change.wav", AssetType::SOUND);
|
||||
Asset::get()->add(prefix + "/data/sound/tabe.wav", AssetType::SOUND);
|
||||
Asset::get()->add(prefix + "/data/sound/title.wav", AssetType::SOUND);
|
||||
@@ -411,6 +411,9 @@ void Director::setFileList()
|
||||
Asset::get()->add(prefix + "/data/sound/voice_no.wav", AssetType::SOUND);
|
||||
Asset::get()->add(prefix + "/data/sound/voice_power_up.wav", AssetType::SOUND);
|
||||
Asset::get()->add(prefix + "/data/sound/walk.wav", AssetType::SOUND);
|
||||
Asset::get()->add(prefix + "/data/sound/debian_drop.wav", AssetType::SOUND);
|
||||
Asset::get()->add(prefix + "/data/sound/debian_pickup.wav", AssetType::SOUND);
|
||||
Asset::get()->add(prefix + "/data/sound/tabe_hit.wav", AssetType::SOUND);
|
||||
|
||||
// Shaders
|
||||
Asset::get()->add(prefix + "/data/shaders/crtpi_256.glsl", AssetType::DATA);
|
||||
@@ -470,7 +473,12 @@ void Director::setFileList()
|
||||
}
|
||||
|
||||
{ // Intro
|
||||
Asset::get()->add(prefix + "/data/gfx/intro/intro.png", AssetType::BITMAP);
|
||||
Asset::get()->add(prefix + "/data/gfx/intro/intro1.png", AssetType::BITMAP);
|
||||
Asset::get()->add(prefix + "/data/gfx/intro/intro2.png", AssetType::BITMAP);
|
||||
Asset::get()->add(prefix + "/data/gfx/intro/intro3.png", AssetType::BITMAP);
|
||||
Asset::get()->add(prefix + "/data/gfx/intro/intro4.png", AssetType::BITMAP);
|
||||
Asset::get()->add(prefix + "/data/gfx/intro/intro5.png", AssetType::BITMAP);
|
||||
Asset::get()->add(prefix + "/data/gfx/intro/intro6.png", AssetType::BITMAP);
|
||||
}
|
||||
|
||||
{ // Logo
|
||||
@@ -490,6 +498,8 @@ void Director::setFileList()
|
||||
Asset::get()->add(prefix + "/data/gfx/item/item_clock.ani", AssetType::ANIMATION);
|
||||
Asset::get()->add(prefix + "/data/gfx/item/item_coffee.png", AssetType::BITMAP);
|
||||
Asset::get()->add(prefix + "/data/gfx/item/item_coffee.ani", AssetType::ANIMATION);
|
||||
Asset::get()->add(prefix + "/data/gfx/item/item_debian.png", AssetType::BITMAP);
|
||||
Asset::get()->add(prefix + "/data/gfx/item/item_debian.ani", AssetType::ANIMATION);
|
||||
Asset::get()->add(prefix + "/data/gfx/item/item_coffee_machine.png", AssetType::BITMAP);
|
||||
Asset::get()->add(prefix + "/data/gfx/item/item_coffee_machine.ani", AssetType::ANIMATION);
|
||||
}
|
||||
@@ -527,8 +537,6 @@ void Director::setFileList()
|
||||
// Fuentes de texto
|
||||
Asset::get()->add(prefix + "/data/font/8bithud.png", AssetType::BITMAP);
|
||||
Asset::get()->add(prefix + "/data/font/8bithud.txt", AssetType::FONT);
|
||||
Asset::get()->add(prefix + "/data/font/nokia.png", AssetType::BITMAP);
|
||||
Asset::get()->add(prefix + "/data/font/nokia.txt", AssetType::FONT);
|
||||
Asset::get()->add(prefix + "/data/font/smb2.gif", AssetType::BITMAP);
|
||||
Asset::get()->add(prefix + "/data/font/smb2_palette1.pal", AssetType::PALETTE);
|
||||
Asset::get()->add(prefix + "/data/font/smb2.txt", AssetType::FONT);
|
||||
@@ -536,6 +544,8 @@ void Director::setFileList()
|
||||
Asset::get()->add(prefix + "/data/font/04b_25.txt", AssetType::FONT);
|
||||
Asset::get()->add(prefix + "/data/font/04b_25_2x.png", AssetType::BITMAP);
|
||||
Asset::get()->add(prefix + "/data/font/04b_25_2x.txt", AssetType::FONT);
|
||||
Asset::get()->add(prefix + "/data/font/04b_25_metal.png", AssetType::BITMAP);
|
||||
Asset::get()->add(prefix + "/data/font/04b_25_grey.png", AssetType::BITMAP);
|
||||
|
||||
// Textos
|
||||
Asset::get()->add(prefix + "/data/lang/es_ES.txt", AssetType::LANG);
|
||||
@@ -544,8 +554,10 @@ void Director::setFileList()
|
||||
|
||||
// Si falta algun fichero, sale del programa
|
||||
if (!Asset::get()->check())
|
||||
{
|
||||
throw std::runtime_error("Falta algun fichero");
|
||||
}
|
||||
}
|
||||
|
||||
// Comprueba los parametros del programa
|
||||
void Director::checkProgramArguments(int argc, const char *argv[])
|
||||
@@ -762,11 +774,6 @@ int Director::run()
|
||||
// Habilita de nuevo los std::cout
|
||||
std::cout.rdbuf(orig_buf);
|
||||
#endif
|
||||
#ifdef ARCADE
|
||||
// Comprueba si ha de apagar el sistema
|
||||
if (section::options == section::Options::QUIT_WITH_CONTROLLER)
|
||||
shutdownSystem();
|
||||
#endif
|
||||
|
||||
return (section::options == section::Options::QUIT_WITH_CONTROLLER) ? 1 : 0;
|
||||
}
|
||||
@@ -794,20 +801,23 @@ std::string Director::getLangFile(lang::Code code)
|
||||
|
||||
#ifdef ARCADE
|
||||
// Apaga el sistema
|
||||
void Director::shutdownSystem()
|
||||
void Director::shutdownSystem(bool shouldShutdown)
|
||||
{
|
||||
if (shouldShutdown)
|
||||
{
|
||||
#ifdef _WIN32
|
||||
// Apaga el sistema en Windows
|
||||
system("shutdown /s /t 0");
|
||||
system("shutdown /s /t 5");
|
||||
#elif __APPLE__
|
||||
// Apaga el sistema en macOS
|
||||
system("sudo shutdown -h now");
|
||||
system("sudo shutdown -h +0.1");
|
||||
#elif __linux__
|
||||
// Apaga el sistema en Linux
|
||||
system("shutdown -h now");
|
||||
system("sleep 5; shutdown -h now");
|
||||
#else
|
||||
// Sistema operativo no compatible
|
||||
#error "Sistema operativo no soportado"
|
||||
#endif
|
||||
}
|
||||
}
|
||||
#endif // ARCADE
|
||||
|
||||
@@ -74,7 +74,7 @@ private:
|
||||
std::string getLangFile(lang::Code code);
|
||||
#ifdef ARCADE
|
||||
// Apaga el sistema
|
||||
void shutdownSystem();
|
||||
void shutdownSystem(bool shouldShutdown);
|
||||
#endif
|
||||
|
||||
// Inicializa todo
|
||||
|
||||
@@ -1,93 +1,160 @@
|
||||
#include "enter_name.h"
|
||||
#include <stddef.h> // Para size_t
|
||||
#include <algorithm> // Para max, min
|
||||
#include "utils.h" // Para trim
|
||||
|
||||
// Constructor
|
||||
EnterName::EnterName()
|
||||
{
|
||||
init();
|
||||
}
|
||||
: character_list_(" ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.-+-*/=?¿<>!\"#$%&/()") {}
|
||||
|
||||
// Inicializa el objeto
|
||||
void EnterName::init()
|
||||
void EnterName::init(const std::string &name)
|
||||
{
|
||||
// No se pasa ningún nombre
|
||||
if (name.empty())
|
||||
{
|
||||
// Obtiene el puntero al nombre
|
||||
name_ = "A";
|
||||
|
||||
// Inicia la lista de caracteres permitidos
|
||||
character_list_ = " ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.-+-*/=?¿<>!\"#$%&/()";
|
||||
position_ = 0;
|
||||
num_characters_ = static_cast<int>(character_list_.size());
|
||||
position_overflow_ = false;
|
||||
}
|
||||
// Se pasa un nombre
|
||||
else
|
||||
{
|
||||
name_ = name;
|
||||
position_ = name_.length();
|
||||
position_overflow_ = position_ >= MAX_NAME_LENGHT ? true : false;
|
||||
}
|
||||
|
||||
// Pone la lista de indices para que refleje el nombre
|
||||
updateCharacterIndex();
|
||||
|
||||
// Actualiza el nombre para que ocupe 8 espacios
|
||||
updateName();
|
||||
// Inicializa el vector de indices con el nombre y espacios
|
||||
initCharacterIndex(name_);
|
||||
}
|
||||
|
||||
// Incrementa la posición
|
||||
void EnterName::incPosition()
|
||||
{
|
||||
position_++;
|
||||
position_ = std::min(position_, NAME_LENGHT - 1);
|
||||
checkIfPositionHasBeenUsed();
|
||||
if (position_overflow_)
|
||||
{
|
||||
// Si ya estamos en overflow, no incrementamos más.
|
||||
return;
|
||||
}
|
||||
|
||||
++position_;
|
||||
|
||||
if (position_ >= MAX_NAME_LENGHT)
|
||||
{
|
||||
position_ = MAX_NAME_LENGHT; // Mantenemos en el índice máximo válido.
|
||||
position_overflow_ = true; // Activamos el flag de overflow.
|
||||
}
|
||||
else
|
||||
{
|
||||
// Copiamos el índice del carácter anterior si es posible.
|
||||
if (position_ > 0 && position_ < MAX_NAME_LENGHT)
|
||||
{
|
||||
character_index_[position_] = character_index_[position_ - 1];
|
||||
}
|
||||
else
|
||||
{
|
||||
// Si position_ es 0, inicializamos el carácter actual.
|
||||
character_index_[position_] = 0;
|
||||
}
|
||||
}
|
||||
|
||||
updateNameFromCharacterIndex();
|
||||
}
|
||||
|
||||
// Decrementa la posición
|
||||
void EnterName::decPosition()
|
||||
{
|
||||
if (position_overflow_)
|
||||
{
|
||||
// Si estaba en overflow, lo desactivamos y mantenemos position_ en el máximo.
|
||||
position_overflow_ = false;
|
||||
position_ = MAX_NAME_LENGHT - 1;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (position_ > 0)
|
||||
{
|
||||
--position_;
|
||||
position_ = std::max(position_, 0);
|
||||
|
||||
// Limpiamos el carácter siguiente si el índice es válido.
|
||||
if (position_ + 1 < MAX_NAME_LENGHT)
|
||||
{
|
||||
character_index_[position_ + 1] = 0;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// Si position_ es 0, aseguramos que no vaya a ser negativo y limpiamos el carácter actual.
|
||||
position_ = 0;
|
||||
character_index_[position_] = 0;
|
||||
}
|
||||
|
||||
// Si position_ es menor que NAME_LENGHT, aseguramos que el overflow esté desactivado.
|
||||
if (position_ < MAX_NAME_LENGHT)
|
||||
{
|
||||
position_overflow_ = false;
|
||||
}
|
||||
}
|
||||
|
||||
updateNameFromCharacterIndex();
|
||||
}
|
||||
|
||||
// Incrementa el índice
|
||||
void EnterName::incIndex()
|
||||
{
|
||||
if (position_overflow_)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
++character_index_[position_];
|
||||
if (character_index_[position_] >= num_characters_)
|
||||
if (character_index_[position_] >= static_cast<int>(character_list_.size()))
|
||||
{
|
||||
character_index_[position_] = 0;
|
||||
}
|
||||
updateName();
|
||||
updateNameFromCharacterIndex();
|
||||
}
|
||||
|
||||
// Decrementa el índice
|
||||
void EnterName::decIndex()
|
||||
{
|
||||
if (position_overflow_)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
--character_index_[position_];
|
||||
if (character_index_[position_] < 0)
|
||||
{
|
||||
character_index_[position_] = num_characters_ - 1;
|
||||
character_index_[position_] = character_list_.size() - 1;
|
||||
}
|
||||
updateName();
|
||||
updateNameFromCharacterIndex();
|
||||
}
|
||||
|
||||
// Actualiza el nombre a partir de la lista de índices
|
||||
void EnterName::updateName()
|
||||
void EnterName::updateNameFromCharacterIndex()
|
||||
{
|
||||
name_.clear();
|
||||
for (int i = 0; i < NAME_LENGHT; ++i)
|
||||
for (int i = 0; i < MAX_NAME_LENGHT; ++i)
|
||||
{
|
||||
name_.push_back(character_list_[character_index_[i]]);
|
||||
}
|
||||
name_ = trim(name_);
|
||||
}
|
||||
|
||||
// Actualiza la variable
|
||||
void EnterName::updateCharacterIndex()
|
||||
void EnterName::initCharacterIndex(const std::string &name)
|
||||
{
|
||||
// Rellena de espacios y marca como no usados
|
||||
for (size_t i = 0; i < NAME_LENGHT; ++i)
|
||||
// Rellena de espacios
|
||||
for (size_t i = 0; i < MAX_NAME_LENGHT; ++i)
|
||||
{
|
||||
character_index_[i] = 0;
|
||||
position_has_been_used_[i] = false;
|
||||
}
|
||||
|
||||
// Coloca los índices en función de los caracteres que forman el nombre
|
||||
for (size_t i = 0; i < name_.size(); ++i)
|
||||
for (size_t i = 0; i < name.substr(0, MAX_NAME_LENGHT).size(); ++i)
|
||||
{
|
||||
character_index_[i] = findIndex(name_.at(i));
|
||||
position_has_been_used_[i] = true;
|
||||
character_index_[i] = findIndex(name.at(i));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -95,31 +162,11 @@ void EnterName::updateCharacterIndex()
|
||||
int EnterName::findIndex(char character) const
|
||||
{
|
||||
for (size_t i = 0; i < character_list_.size(); ++i)
|
||||
{
|
||||
if (character == character_list_.at(i))
|
||||
{
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Obtiene el nombre
|
||||
std::string EnterName::getName() const
|
||||
{
|
||||
return name_;
|
||||
}
|
||||
|
||||
// Obtiene la posición que se está editando
|
||||
int EnterName::getPosition() const
|
||||
{
|
||||
return position_;
|
||||
}
|
||||
|
||||
// Comprueba la posición y copia el caracter si es necesario
|
||||
void EnterName::checkIfPositionHasBeenUsed()
|
||||
{
|
||||
auto used = position_has_been_used_[position_];
|
||||
|
||||
if (!used && position_ > 0)
|
||||
character_index_[position_] = character_index_[position_ - 1];
|
||||
|
||||
position_has_been_used_[position_] = true;
|
||||
updateName();
|
||||
}
|
||||
@@ -1,8 +1,9 @@
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
#include "utils.h"
|
||||
|
||||
constexpr int NAME_LENGHT = 6;
|
||||
constexpr int MAX_NAME_LENGHT = 6;
|
||||
|
||||
/*
|
||||
Un array, "characterList", contiene la lista de caracteres
|
||||
@@ -18,23 +19,19 @@ class EnterName
|
||||
private:
|
||||
std::string character_list_; // Lista de todos los caracteres permitidos
|
||||
std::string name_; // Nombre introducido
|
||||
int position_; // Posición a editar del nombre
|
||||
int num_characters_; // Cantidad de caracteres de la lista de caracteres
|
||||
int character_index_[NAME_LENGHT]; // Indice de la lista para cada uno de los caracteres que forman el nombre
|
||||
bool position_has_been_used_[NAME_LENGHT]; // Indica si en esa posición se ha puesto ya alguna letra. Se utiliza para replicar la letra anterior la primera vez
|
||||
int position_ = 0; // Posición a editar del nombre
|
||||
bool position_overflow_ = false; // Indica si hemos incrementado la posición más allá del límite
|
||||
int character_index_[MAX_NAME_LENGHT]; // Indice de la lista para cada uno de los caracteres que forman el nombre
|
||||
|
||||
// Actualiza el nombre a partir de la lista de índices
|
||||
void updateName();
|
||||
void updateNameFromCharacterIndex();
|
||||
|
||||
// Actualiza la variable
|
||||
void updateCharacterIndex();
|
||||
void initCharacterIndex(const std::string &name);
|
||||
|
||||
// Encuentra el indice de un caracter en "characterList"
|
||||
int findIndex(char character) const;
|
||||
|
||||
// Comprueba la posición y copia el caracter si es necesario
|
||||
void checkIfPositionHasBeenUsed();
|
||||
|
||||
public:
|
||||
// Constructor
|
||||
EnterName();
|
||||
@@ -43,7 +40,7 @@ public:
|
||||
~EnterName() = default;
|
||||
|
||||
// Inicializa el objeto
|
||||
void init();
|
||||
void init(const std::string &name = "");
|
||||
|
||||
// Incrementa la posición
|
||||
void incPosition();
|
||||
@@ -57,9 +54,9 @@ public:
|
||||
// Decrementa el índice
|
||||
void decIndex();
|
||||
|
||||
// Obtiene el nombre
|
||||
std::string getName() const;
|
||||
|
||||
// Obtiene la posición que se está editando
|
||||
int getPosition() const;
|
||||
// Getters
|
||||
std::string getFinalName() const { return trim(name_.substr(0, position_)); }
|
||||
std::string getCurrentName() const { return trim(name_); }
|
||||
int getPosition() const { return position_; }
|
||||
bool getPositionOverflow() const { return position_overflow_; }
|
||||
};
|
||||
348
source/game.cpp
@@ -1,6 +1,6 @@
|
||||
#include "game.h"
|
||||
#include <SDL2/SDL_blendmode.h> // Para SDL_BLENDMODE_BLEND
|
||||
#include <SDL2/SDL_events.h> // Para SDL_PollEvent, SDL_Event, SDL_KEYDOWN
|
||||
#include <SDL2/SDL_events.h> // Para SDL_Event, SDL_PollEvent, SDL_KEYDOWN
|
||||
#include <SDL2/SDL_keycode.h> // Para SDLK_1, SDLK_2, SDLK_3, SDLK_4
|
||||
#include <SDL2/SDL_pixels.h> // Para SDL_PIXELFORMAT_RGBA8888
|
||||
#include <SDL2/SDL_timer.h> // Para SDL_GetTicks
|
||||
@@ -14,15 +14,14 @@
|
||||
#include "balloon.h" // Para Balloon, BALLOON_SPEED
|
||||
#include "balloon_manager.h" // Para BalloonManager
|
||||
#include "bullet.h" // Para Bullet, BulletType, BulletMoveStatus
|
||||
#include "enter_name.h" // Para NAME_LENGHT
|
||||
#include "fade.h" // Para Fade, FadeType, FadeMode
|
||||
#include "global_events.h" // Para check
|
||||
#include "global_inputs.h" // Para check, update
|
||||
#include "input.h" // Para InputType, Input, INPUT_DO_NOT_ALL...
|
||||
#include "item.h" // Para Item, ItemType
|
||||
#include "jail_audio.h" // Para JA_PlaySound, JA_GetMusicState
|
||||
#include "lang.h" // Para getText
|
||||
#include "manage_hiscore_table.h" // Para ManageHiScoreTable, HiScoreEntry
|
||||
#include "mouse.h" // Para handleEvent
|
||||
#include "notifier.h" // Para Notifier
|
||||
#include "param.h" // Para Param, param, ParamGame, ParamFade
|
||||
#include "path_sprite.h" // Para Path, PathSprite, createPath, Path...
|
||||
@@ -30,10 +29,10 @@
|
||||
#include "resource.h" // Para Resource
|
||||
#include "scoreboard.h" // Para Scoreboard, ScoreboardMode, SCOREB...
|
||||
#include "screen.h" // Para Screen
|
||||
#include "section.h" // Para Name, name, AttractMode, Options
|
||||
#include "section.h" // Para Name, name, AttractMode, attract_mode
|
||||
#include "smart_sprite.h" // Para SmartSprite
|
||||
#include "stage.h" // Para number, get, Stage, total_power
|
||||
#include "tabe.h" // Para Tabe
|
||||
#include "tabe.h" // Para Tabe, TabeState
|
||||
#include "text.h" // Para Text
|
||||
#include "texture.h" // Para Texture
|
||||
|
||||
@@ -140,6 +139,7 @@ void Game::setResources()
|
||||
game_text_textures_.emplace_back(Resource::get()->getTexture("game_text_powerup"));
|
||||
game_text_textures_.emplace_back(Resource::get()->getTexture("game_text_one_hit"));
|
||||
game_text_textures_.emplace_back(Resource::get()->getTexture("game_text_stop"));
|
||||
game_text_textures_.emplace_back(Resource::get()->getTexture("game_text_100000_points"));
|
||||
}
|
||||
|
||||
// Texturas - Items
|
||||
@@ -149,6 +149,7 @@ void Game::setResources()
|
||||
item_textures_.emplace_back(Resource::get()->getTexture("item_points3_pacmar.png"));
|
||||
item_textures_.emplace_back(Resource::get()->getTexture("item_clock.png"));
|
||||
item_textures_.emplace_back(Resource::get()->getTexture("item_coffee.png"));
|
||||
item_textures_.emplace_back(Resource::get()->getTexture("item_debian.png"));
|
||||
item_textures_.emplace_back(Resource::get()->getTexture("item_coffee_machine.png"));
|
||||
}
|
||||
|
||||
@@ -181,6 +182,7 @@ void Game::setResources()
|
||||
item_animations_.emplace_back(Resource::get()->getAnimation("item_points3_pacmar.ani"));
|
||||
item_animations_.emplace_back(Resource::get()->getAnimation("item_clock.ani"));
|
||||
item_animations_.emplace_back(Resource::get()->getAnimation("item_coffee.ani"));
|
||||
item_animations_.emplace_back(Resource::get()->getAnimation("item_debian.ani"));
|
||||
item_animations_.emplace_back(Resource::get()->getAnimation("item_coffee_machine.ani"));
|
||||
}
|
||||
}
|
||||
@@ -202,7 +204,7 @@ void Game::updateHiScore()
|
||||
if (hi_score_achieved_ == false)
|
||||
{
|
||||
hi_score_achieved_ = true;
|
||||
JA_PlaySound(Resource::get()->getSound("hiscore.wav"));
|
||||
JA_PlaySound(Resource::get()->getSound("hi_score_achieved.wav"));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -280,6 +282,13 @@ void Game::updateStage()
|
||||
createMessage(paths, text->writeToTexture(caption, 1, -4));
|
||||
}
|
||||
}
|
||||
|
||||
// Modifica el color de fondo al llegar a la Fase 10
|
||||
if (Stage::number == 9)
|
||||
{
|
||||
background_->setColor(Color(0xdd, 0x19, 0x1d).darken());
|
||||
background_->setAlpha(96);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -297,7 +306,7 @@ void Game::updateGameStateGameOver()
|
||||
updateSmartSprites();
|
||||
updatePathSprites();
|
||||
updateTimeStopped();
|
||||
checkBulletBalloonCollision();
|
||||
checkBulletCollision();
|
||||
cleanVectors();
|
||||
|
||||
if (game_over_counter_ > 0)
|
||||
@@ -362,6 +371,7 @@ void Game::updateGameStateCompleted()
|
||||
balloon_manager_->destroyAllBalloons(); // Destruye a todos los globos
|
||||
destroyAllItems(); // Destruye todos los items
|
||||
Stage::power = 0; // Vuelve a dejar el poder a cero, por lo que hubiera podido subir al destruir todos los globos
|
||||
background_->setAlpha(0); // Elimina el tono rojo de las últimas pantallas
|
||||
}
|
||||
|
||||
// Comienza las celebraciones
|
||||
@@ -462,37 +472,41 @@ void Game::checkPlayerItemCollision(std::shared_ptr<Player> &player)
|
||||
case ItemType::DISK:
|
||||
{
|
||||
player->addScore(1000);
|
||||
const auto x =
|
||||
item->getPosX() +
|
||||
(item->getWidth() - game_text_textures_[0]->getWidth()) / 2;
|
||||
createItemText(x, game_text_textures_[0]);
|
||||
const auto x = item->getPosX() + (item->getWidth() - game_text_textures_.at(0)->getWidth()) / 2;
|
||||
createItemText(x, game_text_textures_.at(0));
|
||||
JA_PlaySound(Resource::get()->getSound("item_pickup.wav"));
|
||||
break;
|
||||
}
|
||||
case ItemType::GAVINA:
|
||||
{
|
||||
player->addScore(2500);
|
||||
const auto x =
|
||||
item->getPosX() +
|
||||
(item->getWidth() - game_text_textures_[1]->getWidth()) / 2;
|
||||
createItemText(x, game_text_textures_[1]);
|
||||
const auto x = item->getPosX() + (item->getWidth() - game_text_textures_.at(1)->getWidth()) / 2;
|
||||
createItemText(x, game_text_textures_.at(1));
|
||||
JA_PlaySound(Resource::get()->getSound("item_pickup.wav"));
|
||||
break;
|
||||
}
|
||||
case ItemType::PACMAR:
|
||||
{
|
||||
player->addScore(5000);
|
||||
const auto x =
|
||||
item->getPosX() +
|
||||
(item->getWidth() - game_text_textures_[2]->getWidth()) / 2;
|
||||
createItemText(x, game_text_textures_[2]);
|
||||
const auto x = item->getPosX() + (item->getWidth() - game_text_textures_.at(2)->getWidth()) / 2;
|
||||
createItemText(x, game_text_textures_.at(2));
|
||||
JA_PlaySound(Resource::get()->getSound("item_pickup.wav"));
|
||||
break;
|
||||
}
|
||||
case ItemType::DEBIAN:
|
||||
{
|
||||
player->addScore(100000);
|
||||
const auto x = item->getPosX() + (item->getWidth() - game_text_textures_.at(6)->getWidth()) / 2;
|
||||
createItemText(x, game_text_textures_.at(6));
|
||||
JA_PlaySound(Resource::get()->getSound("debian_pickup.wav"));
|
||||
break;
|
||||
}
|
||||
case ItemType::CLOCK:
|
||||
{
|
||||
enableTimeStopItem();
|
||||
const auto x =
|
||||
item->getPosX() +
|
||||
(item->getWidth() - game_text_textures_[5]->getWidth()) / 2;
|
||||
createItemText(x, game_text_textures_[5]);
|
||||
const auto x = item->getPosX() + (item->getWidth() - game_text_textures_.at(5)->getWidth()) / 2;
|
||||
createItemText(x, game_text_textures_.at(5));
|
||||
JA_PlaySound(Resource::get()->getSound("item_pickup.wav"));
|
||||
break;
|
||||
}
|
||||
case ItemType::COFFEE:
|
||||
@@ -500,18 +514,14 @@ void Game::checkPlayerItemCollision(std::shared_ptr<Player> &player)
|
||||
if (player->getCoffees() == 2)
|
||||
{
|
||||
player->addScore(5000);
|
||||
const auto x =
|
||||
item->getPosX() +
|
||||
(item->getWidth() - game_text_textures_[2]->getWidth()) / 2;
|
||||
createItemText(x, game_text_textures_[2]);
|
||||
const auto x = item->getPosX() + (item->getWidth() - game_text_textures_.at(2)->getWidth()) / 2;
|
||||
createItemText(x, game_text_textures_.at(2));
|
||||
}
|
||||
else
|
||||
{
|
||||
player->giveExtraHit();
|
||||
const auto x =
|
||||
item->getPosX() +
|
||||
(item->getWidth() - game_text_textures_[4]->getWidth()) / 2;
|
||||
createItemText(x, game_text_textures_[4]);
|
||||
const auto x = item->getPosX() + (item->getWidth() - game_text_textures_.at(4)->getWidth()) / 2;
|
||||
createItemText(x, game_text_textures_.at(4));
|
||||
}
|
||||
JA_PlaySound(Resource::get()->getSound("voice_coffee.wav"));
|
||||
break;
|
||||
@@ -520,10 +530,8 @@ void Game::checkPlayerItemCollision(std::shared_ptr<Player> &player)
|
||||
{
|
||||
player->setPowerUp();
|
||||
coffee_machine_enabled_ = false;
|
||||
const auto x =
|
||||
item->getPosX() +
|
||||
(item->getWidth() - game_text_textures_[3]->getWidth()) / 2;
|
||||
createItemText(x, game_text_textures_[3]);
|
||||
const auto x = item->getPosX() + (item->getWidth() - game_text_textures_.at(3)->getWidth()) / 2;
|
||||
createItemText(x, game_text_textures_.at(3));
|
||||
JA_PlaySound(Resource::get()->getSound("voice_power_up.wav"));
|
||||
break;
|
||||
}
|
||||
@@ -532,18 +540,46 @@ void Game::checkPlayerItemCollision(std::shared_ptr<Player> &player)
|
||||
}
|
||||
|
||||
updateHiScore();
|
||||
JA_PlaySound(Resource::get()->getSound("itempickup.wav"));
|
||||
item->disable();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Comprueba y procesa la colisión entre las balas y los globos
|
||||
void Game::checkBulletBalloonCollision()
|
||||
// Comprueba y procesa la colisión de las balas
|
||||
void Game::checkBulletCollision()
|
||||
{
|
||||
for (auto &bullet : bullets_)
|
||||
{
|
||||
// Comprueba la colisión con el Tabe
|
||||
if (bullet->isEnabled() && tabe_->isEnabled())
|
||||
if (checkCollision(bullet->getCollider(), tabe_->getCollider()))
|
||||
{
|
||||
tabe_->setState(TabeState::HIT);
|
||||
bullet->disable();
|
||||
auto pos = tabe_->getCollider();
|
||||
if (tabe_->tryToGetBonus())
|
||||
{
|
||||
createItem(ItemType::DEBIAN, pos.x, pos.y);
|
||||
JA_PlaySound(Resource::get()->getSound("debian_drop.wav"));
|
||||
}
|
||||
else
|
||||
{
|
||||
if (rand() % 3 == 0)
|
||||
{
|
||||
createItem(ItemType::COFFEE, pos.x, pos.y);
|
||||
// JA_PlaySound(Resource::get()->getSound("item_drop.wav"));
|
||||
}
|
||||
else
|
||||
{
|
||||
// JA_PlaySound(Resource::get()->getSound("tabe_hit.wav"));
|
||||
}
|
||||
JA_PlaySound(Resource::get()->getSound("tabe_hit.wav"));
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
// Comprueba la colisión con los globos
|
||||
for (auto &balloon : balloon_manager_->getBalloons())
|
||||
{
|
||||
if (balloon->isEnabled() && (!balloon->isInvulnerable()) && bullet->isEnabled())
|
||||
@@ -560,7 +596,7 @@ void Game::checkBulletBalloonCollision()
|
||||
if (dropped_item != ItemType::COFFEE_MACHINE)
|
||||
{
|
||||
createItem(dropped_item, balloon->getPosX(), balloon->getPosY());
|
||||
JA_PlaySound(Resource::get()->getSound("itemdrop.wav"));
|
||||
JA_PlaySound(Resource::get()->getSound("item_drop.wav"));
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -745,7 +781,7 @@ void Game::createItemText(int x, std::shared_ptr<Texture> texture)
|
||||
const auto h = texture->getHeight();
|
||||
|
||||
const int y0 = param.game.play_area.rect.h - h;
|
||||
const int y1 = 155;
|
||||
const int y1 = 160 - (h / 2);
|
||||
const int y2 = -h;
|
||||
|
||||
// Ajusta para que no se dibuje fuera de pantalla
|
||||
@@ -865,7 +901,7 @@ void Game::killPlayer(std::shared_ptr<Player> &player)
|
||||
// Lo pierde
|
||||
player->removeExtraHit();
|
||||
throwCoffee(player->getPosX() + (player->getWidth() / 2), player->getPosY() + (player->getHeight() / 2));
|
||||
JA_PlaySound(Resource::get()->getSound("coffeeout.wav"));
|
||||
JA_PlaySound(Resource::get()->getSound("coffee_out.wav"));
|
||||
screen_->shake();
|
||||
}
|
||||
else
|
||||
@@ -893,28 +929,34 @@ void Game::updateTimeStopped()
|
||||
if (time_stopped_counter_ > 120)
|
||||
{
|
||||
if (time_stopped_counter_ % 30 == 0)
|
||||
{
|
||||
JA_PlaySound(Resource::get()->getSound("clock.wav"));
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (time_stopped_counter_ % 15 == 0)
|
||||
JA_PlaySound(Resource::get()->getSound("clock.wav"));
|
||||
if (time_stopped_counter_ % 30 == 0)
|
||||
{
|
||||
balloon_manager_->normalColorsToAllBalloons();
|
||||
if (time_stopped_counter_ % 30 == 15)
|
||||
JA_PlaySound(Resource::get()->getSound("clock.wav"));
|
||||
}
|
||||
else if (time_stopped_counter_ % 30 == 15)
|
||||
{
|
||||
balloon_manager_->reverseColorsToAllBalloons();
|
||||
JA_PlaySound(Resource::get()->getSound("clock.wav"));
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
disableTimeStopItem();
|
||||
}
|
||||
}
|
||||
|
||||
// Actualiza el juego
|
||||
void Game::update()
|
||||
{
|
||||
constexpr int TICKS_SPEED = 15;
|
||||
|
||||
if (SDL_GetTicks() - ticks_ > TICKS_SPEED)
|
||||
if (SDL_GetTicks() - ticks_ > param.game.speed)
|
||||
{
|
||||
ticks_ = SDL_GetTicks();
|
||||
|
||||
@@ -1173,15 +1215,7 @@ void Game::checkEvents()
|
||||
SDL_Event event;
|
||||
while (SDL_PollEvent(&event))
|
||||
{
|
||||
// Evento de salida de la aplicación
|
||||
if (event.type == SDL_QUIT)
|
||||
{
|
||||
section::name = section::Name::QUIT;
|
||||
section::options = section::Options::QUIT_FROM_EVENT;
|
||||
break;
|
||||
}
|
||||
|
||||
else if (event.type == SDL_WINDOWEVENT)
|
||||
if (event.type == SDL_WINDOWEVENT)
|
||||
{
|
||||
switch (event.window.event)
|
||||
{
|
||||
@@ -1195,104 +1229,19 @@ void Game::checkEvents()
|
||||
pause(false);
|
||||
break;
|
||||
}
|
||||
case SDL_WINDOWEVENT_SIZE_CHANGED:
|
||||
{
|
||||
reloadTextures();
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
#ifdef DEBUG
|
||||
else if (event.type == SDL_KEYDOWN && event.key.repeat == 0)
|
||||
{
|
||||
switch (event.key.keysym.sym)
|
||||
{
|
||||
case SDLK_1: // Crea una powerball
|
||||
{
|
||||
balloon_manager_->createPowerBall();
|
||||
break;
|
||||
}
|
||||
case SDLK_2: // Crea dos globos gordos
|
||||
{
|
||||
balloon_manager_->createTwoBigBalloons();
|
||||
}
|
||||
break;
|
||||
case SDLK_3: // Activa el modo para pasar el juego automaticamente
|
||||
{
|
||||
auto_pop_balloons_ = !auto_pop_balloons_;
|
||||
Notifier::get()->showText({"auto advance: " + boolToString(auto_pop_balloons_)});
|
||||
balloon_manager_->destroyAllBalloons();
|
||||
balloon_manager_->setDeployBalloons(!auto_pop_balloons_);
|
||||
break;
|
||||
}
|
||||
case SDLK_4: // Suelta un item
|
||||
{
|
||||
createItem(ItemType::CLOCK, players_.at(0)->getPosX(), players_.at(0)->getPosY() - 40);
|
||||
break;
|
||||
}
|
||||
case SDLK_5: // Crea un PathSprite
|
||||
{
|
||||
const int x = players_.at(0)->getPosX() + (players_.at(0)->getWidth() - game_text_textures_[3]->getWidth()) / 2;
|
||||
createItemText(x, game_text_textures_.at(3));
|
||||
break;
|
||||
}
|
||||
case SDLK_6: // Crea un mensaje
|
||||
{
|
||||
createMessage({paths_.at(0), paths_.at(1)}, Resource::get()->getTexture("game_text_get_ready"));
|
||||
break;
|
||||
}
|
||||
case SDLK_7: // Flash
|
||||
{
|
||||
screen_->flash(flash_color, 3);
|
||||
break;
|
||||
}
|
||||
case SDLK_8:
|
||||
{
|
||||
for (auto player : players_)
|
||||
{
|
||||
if (player->isPlaying())
|
||||
{
|
||||
createItem(ItemType::COFFEE_MACHINE, player->getPosX(), param.game.game_area.rect.y - param.game.coffee_machine_h);
|
||||
break;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
case SDLK_9:
|
||||
{
|
||||
tabe_->enable();
|
||||
break;
|
||||
}
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
checkDebugEvents(event);
|
||||
#endif
|
||||
// Comprueba el cursor
|
||||
Mouse::handleEvent(event);
|
||||
globalEvents::check(event);
|
||||
}
|
||||
}
|
||||
|
||||
// Recarga las texturas
|
||||
void Game::reloadTextures()
|
||||
{
|
||||
for (auto &texture : item_textures_)
|
||||
texture->reLoad();
|
||||
|
||||
for (auto &textures : player_textures_)
|
||||
for (auto &texture : textures)
|
||||
texture->reLoad();
|
||||
|
||||
for (auto &texture : game_text_textures_)
|
||||
texture->reLoad();
|
||||
|
||||
bullet_texture_->reLoad();
|
||||
background_->reloadTextures();
|
||||
}
|
||||
|
||||
// Actualiza el marcador
|
||||
void Game::updateScoreboard()
|
||||
{
|
||||
@@ -1320,11 +1269,11 @@ void Game::pause(bool value)
|
||||
}
|
||||
|
||||
// Añade una puntuación a la tabla de records
|
||||
void Game::addScoreToScoreBoard(const std::string &name, int score)
|
||||
void Game::addScoreToScoreBoard(const std::shared_ptr<Player> &player)
|
||||
{
|
||||
const auto entry = HiScoreEntry(trim(name), score);
|
||||
const auto entry = HiScoreEntry(trim(player->getRecordName()), player->getScore(), player->get1CC());
|
||||
auto manager = std::make_unique<ManageHiScoreTable>(options.game.hi_score_table);
|
||||
manager->add(entry);
|
||||
options.game.last_hi_score_entry.at(player->getId() - 1) = manager->add(entry);
|
||||
manager->saveToFile(asset_->get("score.bin"));
|
||||
hi_score_.name = options.game.hi_score_table.front().name;
|
||||
}
|
||||
@@ -1405,12 +1354,14 @@ void Game::checkPauseInput()
|
||||
{
|
||||
// Comprueba los mandos
|
||||
for (int i = 0; i < input_->getNumControllers(); ++i)
|
||||
{
|
||||
if (input_->checkInput(InputType::SERVICE, INPUT_ALLOW_REPEAT, InputDeviceToUse::CONTROLLER, i) &&
|
||||
input_->checkInput(InputType::PAUSE, INPUT_DO_NOT_ALLOW_REPEAT, InputDeviceToUse::CONTROLLER, i))
|
||||
{
|
||||
pause(!paused_);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Comprueba el teclado
|
||||
if (input_->checkInput(InputType::PAUSE, INPUT_DO_NOT_ALLOW_REPEAT, InputDeviceToUse::KEYBOARD))
|
||||
@@ -1427,7 +1378,8 @@ void Game::handleDemoMode()
|
||||
for (const auto &player : players_)
|
||||
{
|
||||
if (player->isPlaying())
|
||||
{ // Maneja el input específico del jugador en modo demo.
|
||||
{
|
||||
// Maneja el input específico del jugador en modo demo.
|
||||
handleDemoPlayerInput(player, index);
|
||||
}
|
||||
|
||||
@@ -1505,7 +1457,7 @@ void Game::handlePlayersInput()
|
||||
// Gestiona la continuación del jugador.
|
||||
handlePlayerContinue(player);
|
||||
}
|
||||
else if (player->isEnteringName() || player->isEnteringNameGameCompleted())
|
||||
else if (player->isEnteringName() || player->isEnteringNameGameCompleted() || player->isShowingName())
|
||||
{
|
||||
// Gestiona la introducción del nombre del jugador.
|
||||
handleNameInput(player);
|
||||
@@ -1577,16 +1529,20 @@ void Game::handlePlayerContinue(const std::shared_ptr<Player> &player)
|
||||
if (input_->checkInput(InputType::START, INPUT_DO_NOT_ALLOW_REPEAT, options.controllers[controllerIndex].type, options.controllers[controllerIndex].index))
|
||||
{
|
||||
player->setPlayingState(PlayerState::PLAYING);
|
||||
player->addCredit();
|
||||
}
|
||||
|
||||
// Disminuye el contador de continuación si se presiona cualquier botón de disparo.
|
||||
if (input_->checkInput(InputType::FIRE_LEFT, INPUT_DO_NOT_ALLOW_REPEAT, options.controllers[controllerIndex].type, options.controllers[controllerIndex].index) ||
|
||||
input_->checkInput(InputType::FIRE_CENTER, INPUT_DO_NOT_ALLOW_REPEAT, options.controllers[controllerIndex].type, options.controllers[controllerIndex].index) ||
|
||||
input_->checkInput(InputType::FIRE_RIGHT, INPUT_DO_NOT_ALLOW_REPEAT, options.controllers[controllerIndex].type, options.controllers[controllerIndex].index))
|
||||
{
|
||||
if (player->getContinueCounter() < 7)
|
||||
{
|
||||
player->decContinueCounter();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Procesa las entradas para la introducción del nombre del jugador.
|
||||
void Game::handleNameInput(const std::shared_ptr<Player> &player)
|
||||
@@ -1596,12 +1552,15 @@ void Game::handleNameInput(const std::shared_ptr<Player> &player)
|
||||
input_->checkInput(InputType::FIRE_CENTER, INPUT_DO_NOT_ALLOW_REPEAT, options.controllers[controllerIndex].type, options.controllers[controllerIndex].index) ||
|
||||
input_->checkInput(InputType::FIRE_RIGHT, INPUT_DO_NOT_ALLOW_REPEAT, options.controllers[controllerIndex].type, options.controllers[controllerIndex].index))
|
||||
{
|
||||
if (player->getRecordNamePos() == NAME_LENGHT - 1)
|
||||
if (player->isShowingName())
|
||||
{
|
||||
player->setPlayingState(PlayerState::CONTINUE);
|
||||
}
|
||||
else if (player->getEnterNamePositionOverflow())
|
||||
{
|
||||
player->setInput(InputType::START);
|
||||
addScoreToScoreBoard(player->getRecordName(), player->getScore());
|
||||
const auto state = player->getPlayingState();
|
||||
player->setPlayingState(state == PlayerState::ENTERING_NAME ? PlayerState::CONTINUE : PlayerState::LEAVING_SCREEN);
|
||||
addScoreToScoreBoard(player);
|
||||
player->setPlayingState(PlayerState::SHOWING_NAME);
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -1623,9 +1582,8 @@ void Game::handleNameInput(const std::shared_ptr<Player> &player)
|
||||
else if (input_->checkInput(InputType::START, INPUT_DO_NOT_ALLOW_REPEAT, options.controllers[controllerIndex].type, options.controllers[controllerIndex].index))
|
||||
{
|
||||
player->setInput(InputType::START);
|
||||
addScoreToScoreBoard(player->getRecordName(), player->getScore());
|
||||
const auto state = player->getPlayingState();
|
||||
player->setPlayingState(state == PlayerState::ENTERING_NAME ? PlayerState::CONTINUE : PlayerState::LEAVING_SCREEN);
|
||||
addScoreToScoreBoard(player);
|
||||
player->setPlayingState(PlayerState::SHOWING_NAME);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1941,7 +1899,7 @@ void Game::updateGameStatePlaying()
|
||||
updatePathSprites();
|
||||
updateTimeStopped();
|
||||
updateHelper();
|
||||
checkBulletBalloonCollision();
|
||||
checkBulletCollision();
|
||||
updateMenace();
|
||||
checkAndUpdateBalloonSpeed();
|
||||
checkState();
|
||||
@@ -2014,3 +1972,79 @@ void Game::setState(GameState state)
|
||||
state_ = state;
|
||||
counter_ = 0;
|
||||
}
|
||||
|
||||
#ifdef DEBUG
|
||||
// Comprueba los eventos en el modo DEBUG
|
||||
void Game::checkDebugEvents(const SDL_Event &event)
|
||||
{
|
||||
if (event.type == SDL_KEYDOWN && event.key.repeat == 0)
|
||||
{
|
||||
switch (event.key.keysym.sym)
|
||||
{
|
||||
case SDLK_1: // Crea una powerball
|
||||
{
|
||||
balloon_manager_->createPowerBall();
|
||||
break;
|
||||
}
|
||||
case SDLK_2: // Crea dos globos gordos
|
||||
{
|
||||
balloon_manager_->createTwoBigBalloons();
|
||||
break;
|
||||
}
|
||||
case SDLK_3: // Activa el modo para pasar el juego automaticamente
|
||||
{
|
||||
auto_pop_balloons_ = !auto_pop_balloons_;
|
||||
Notifier::get()->show({"auto advance: " + boolToString(auto_pop_balloons_)});
|
||||
if (auto_pop_balloons_)
|
||||
{
|
||||
balloon_manager_->destroyAllBalloons();
|
||||
}
|
||||
balloon_manager_->setDeployBalloons(!auto_pop_balloons_);
|
||||
break;
|
||||
}
|
||||
case SDLK_4: // Suelta un item
|
||||
{
|
||||
createItem(ItemType::CLOCK, players_.at(0)->getPosX(), players_.at(0)->getPosY() - 40);
|
||||
break;
|
||||
}
|
||||
case SDLK_5: // 5.000
|
||||
{
|
||||
const int X = players_.at(0)->getPosX() + (players_.at(0)->getWidth() - game_text_textures_[3]->getWidth()) / 2;
|
||||
createItemText(X, game_text_textures_.at(2));
|
||||
break;
|
||||
}
|
||||
case SDLK_6: // Crea un mensaje
|
||||
{
|
||||
createMessage({paths_.at(0), paths_.at(1)}, Resource::get()->getTexture("game_text_get_ready"));
|
||||
break;
|
||||
}
|
||||
case SDLK_7: // 100.000
|
||||
{
|
||||
const int X = players_.at(0)->getPosX() + (players_.at(0)->getWidth() - game_text_textures_[3]->getWidth()) / 2;
|
||||
createItemText(X, game_text_textures_.at(6));
|
||||
break;
|
||||
break;
|
||||
}
|
||||
case SDLK_8:
|
||||
{
|
||||
for (auto player : players_)
|
||||
{
|
||||
if (player->isPlaying())
|
||||
{
|
||||
createItem(ItemType::COFFEE_MACHINE, player->getPosX(), param.game.game_area.rect.y - param.game.coffee_machine_h);
|
||||
break;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
case SDLK_9:
|
||||
{
|
||||
tabe_->enable();
|
||||
break;
|
||||
}
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
#include <SDL2/SDL_render.h> // Para SDL_Renderer, SDL_Texture
|
||||
#include <SDL2/SDL_stdinc.h> // Para Uint32, Uint8
|
||||
#include <SDL2/SDL_events.h> // Para SDL_PollEvent, SDL_Event, SDL_KEYDOWN
|
||||
#include <memory> // Para shared_ptr, unique_ptr
|
||||
#include <string> // Para string
|
||||
#include <vector> // Para vector
|
||||
@@ -173,6 +174,9 @@ private:
|
||||
GameState state_ = GameState::FADE_IN; // Estado
|
||||
#ifdef DEBUG
|
||||
bool auto_pop_balloons_ = false; // Si es true, incrementa automaticamente los globos explotados
|
||||
|
||||
// Comprueba los eventos en el modo DEBUG
|
||||
void checkDebugEvents(const SDL_Event &event);
|
||||
#endif
|
||||
|
||||
// Actualiza el juego
|
||||
@@ -211,8 +215,8 @@ private:
|
||||
// Comprueba la colisión entre el jugador y los items
|
||||
void checkPlayerItemCollision(std::shared_ptr<Player> &player);
|
||||
|
||||
// Comprueba la colisión entre las balas y los globos
|
||||
void checkBulletBalloonCollision();
|
||||
// Comprueba y procesa la colisión de las balas
|
||||
void checkBulletCollision();
|
||||
|
||||
// Mueve las balas activas
|
||||
void updateBullets();
|
||||
@@ -298,9 +302,6 @@ private:
|
||||
// Comprueba si todos los jugadores han terminado de jugar
|
||||
bool allPlayersAreNotPlaying();
|
||||
|
||||
// Recarga las texturas
|
||||
void reloadTextures();
|
||||
|
||||
// Actualiza el marcador
|
||||
void updateScoreboard();
|
||||
|
||||
@@ -311,7 +312,7 @@ private:
|
||||
void pause(bool value);
|
||||
|
||||
// Añade una puntuación a la tabla de records
|
||||
void addScoreToScoreBoard(const std::string &name, int score);
|
||||
void addScoreToScoreBoard(const std::shared_ptr<Player> &player);
|
||||
|
||||
// Saca del estado de GAME OVER al jugador si el otro está activo
|
||||
void checkAndUpdatePlayerStatus(int active_player_index, int inactive_player_index);
|
||||
|
||||
@@ -244,15 +244,6 @@ bool GameLogo::hasFinished() const
|
||||
return post_finished_counter_ == 0;
|
||||
}
|
||||
|
||||
// Recarga las texturas
|
||||
void GameLogo::reLoad()
|
||||
{
|
||||
dust_texture_->reLoad();
|
||||
coffee_texture_->reLoad();
|
||||
crisis_texture_->reLoad();
|
||||
arcade_edition_texture_->reLoad();
|
||||
}
|
||||
|
||||
// Calcula el desplazamiento vertical inicial
|
||||
int GameLogo::getInitialVerticalDesp()
|
||||
{
|
||||
|
||||
@@ -94,7 +94,4 @@ public:
|
||||
|
||||
// Indica si ha terminado la animación
|
||||
bool hasFinished() const;
|
||||
|
||||
// Recarga las texturas
|
||||
void reLoad();
|
||||
};
|
||||
479
source/gif.c
@@ -1,479 +0,0 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <fcntl.h>
|
||||
|
||||
#define EXTENSION_INTRODUCER 0x21
|
||||
#define IMAGE_DESCRIPTOR 0x2C
|
||||
#define TRAILER 0x3B
|
||||
|
||||
#define GRAPHIC_CONTROL 0xF9
|
||||
#define APPLICATION_EXTENSION 0xFF
|
||||
#define COMMENT_EXTENSION 0xFE
|
||||
#define PLAINTEXT_EXTENSION 0x01
|
||||
|
||||
#define READ(dst, size) memcpy(dst, buffer, size); buffer += size
|
||||
|
||||
typedef struct
|
||||
{
|
||||
unsigned short width;
|
||||
unsigned short height;
|
||||
unsigned char fields;
|
||||
unsigned char background_color_index;
|
||||
unsigned char pixel_aspect_ratio;
|
||||
}
|
||||
screen_descriptor_t;
|
||||
|
||||
typedef struct
|
||||
{
|
||||
unsigned char r;
|
||||
unsigned char g;
|
||||
unsigned char b;
|
||||
}
|
||||
rgb;
|
||||
|
||||
typedef struct
|
||||
{
|
||||
unsigned short image_left_position;
|
||||
unsigned short image_top_position;
|
||||
unsigned short image_width;
|
||||
unsigned short image_height;
|
||||
unsigned char fields;
|
||||
}
|
||||
image_descriptor_t;
|
||||
|
||||
typedef struct
|
||||
{
|
||||
unsigned char byte;
|
||||
int prev;
|
||||
int len;
|
||||
}
|
||||
dictionary_entry_t;
|
||||
|
||||
typedef struct
|
||||
{
|
||||
unsigned char extension_code;
|
||||
unsigned char block_size;
|
||||
}
|
||||
extension_t;
|
||||
|
||||
typedef struct
|
||||
{
|
||||
unsigned char fields;
|
||||
unsigned short delay_time;
|
||||
unsigned char transparent_color_index;
|
||||
}
|
||||
graphic_control_extension_t;
|
||||
|
||||
typedef struct
|
||||
{
|
||||
unsigned char application_id[ 8 ];
|
||||
unsigned char version[ 3 ];
|
||||
}
|
||||
application_extension_t;
|
||||
|
||||
typedef struct
|
||||
{
|
||||
unsigned short left;
|
||||
unsigned short top;
|
||||
unsigned short width;
|
||||
unsigned short height;
|
||||
unsigned char cell_width;
|
||||
unsigned char cell_height;
|
||||
unsigned char foreground_color;
|
||||
unsigned char background_color;
|
||||
}
|
||||
plaintext_extension_t;
|
||||
|
||||
//static unsigned short width = 0;
|
||||
//static unsigned short height = 0;
|
||||
//static unsigned char* uncompressed_data = NULL;
|
||||
|
||||
void uncompress( int code_length,
|
||||
const unsigned char *input,
|
||||
int input_length,
|
||||
unsigned char *out )
|
||||
{
|
||||
//int maxbits;
|
||||
int i, bit;
|
||||
int code, prev = -1;
|
||||
dictionary_entry_t *dictionary;
|
||||
int dictionary_ind;
|
||||
unsigned int mask = 0x01;
|
||||
int reset_code_length;
|
||||
int clear_code; // This varies depending on code_length
|
||||
int stop_code; // one more than clear code
|
||||
int match_len;
|
||||
|
||||
|
||||
clear_code = 1 << ( code_length );
|
||||
stop_code = clear_code + 1;
|
||||
// To handle clear codes
|
||||
reset_code_length = code_length;
|
||||
|
||||
// Create a dictionary large enough to hold "code_length" entries.
|
||||
// Once the dictionary overflows, code_length increases
|
||||
dictionary = ( dictionary_entry_t * )
|
||||
malloc( sizeof( dictionary_entry_t ) * ( 1 << ( code_length + 1 ) ) );
|
||||
|
||||
// Initialize the first 2^code_len entries of the dictionary with their
|
||||
// indices. The rest of the entries will be built up dynamically.
|
||||
|
||||
// Technically, it shouldn't be necessary to initialize the
|
||||
// dictionary. The spec says that the encoder "should output a
|
||||
// clear code as the first code in the image data stream". It doesn't
|
||||
// say must, though...
|
||||
for ( dictionary_ind = 0;
|
||||
dictionary_ind < ( 1 << code_length );
|
||||
dictionary_ind++ )
|
||||
{
|
||||
dictionary[ dictionary_ind ].byte = dictionary_ind;
|
||||
// XXX this only works because prev is a 32-bit int (> 12 bits)
|
||||
dictionary[ dictionary_ind ].prev = -1;
|
||||
dictionary[ dictionary_ind ].len = 1;
|
||||
}
|
||||
|
||||
// 2^code_len + 1 is the special "end" code; don't give it an entry here
|
||||
dictionary_ind++;
|
||||
dictionary_ind++;
|
||||
|
||||
// TODO verify that the very last byte is clear_code + 1
|
||||
while ( input_length )
|
||||
{
|
||||
code = 0x0;
|
||||
// Always read one more bit than the code length
|
||||
for ( i = 0; i < ( code_length + 1 ); ++i )
|
||||
{
|
||||
// This is different than in the file read example; that
|
||||
// was a call to "next_bit"
|
||||
bit = ( *input & mask ) ? 1 : 0;
|
||||
mask <<= 1;
|
||||
|
||||
if ( mask == 0x100 )
|
||||
{
|
||||
mask = 0x01;
|
||||
input++;
|
||||
input_length--;
|
||||
}
|
||||
|
||||
code = code | ( bit << i );
|
||||
}
|
||||
|
||||
if ( code == clear_code )
|
||||
{
|
||||
code_length = reset_code_length;
|
||||
dictionary = ( dictionary_entry_t * ) realloc( dictionary,
|
||||
sizeof( dictionary_entry_t ) * ( 1 << ( code_length + 1 ) ) );
|
||||
|
||||
for ( dictionary_ind = 0;
|
||||
dictionary_ind < ( 1 << code_length );
|
||||
dictionary_ind++ )
|
||||
{
|
||||
dictionary[ dictionary_ind ].byte = dictionary_ind;
|
||||
// XXX this only works because prev is a 32-bit int (> 12 bits)
|
||||
dictionary[ dictionary_ind ].prev = -1;
|
||||
dictionary[ dictionary_ind ].len = 1;
|
||||
}
|
||||
dictionary_ind++;
|
||||
dictionary_ind++;
|
||||
prev = -1;
|
||||
continue;
|
||||
}
|
||||
else if ( code == stop_code )
|
||||
{
|
||||
/*if ( input_length > 1 )
|
||||
{
|
||||
fprintf( stderr, "Malformed GIF (early stop code)\n" );
|
||||
exit( 0 );
|
||||
}*/
|
||||
break;
|
||||
}
|
||||
|
||||
// Update the dictionary with this character plus the _entry_
|
||||
// (character or string) that came before it
|
||||
if ( ( prev > -1 ) && ( code_length < 12 ) )
|
||||
{
|
||||
if ( code > dictionary_ind )
|
||||
{
|
||||
fprintf( stderr, "code = %.02x, but dictionary_ind = %.02x\n",
|
||||
code, dictionary_ind );
|
||||
exit( 0 );
|
||||
}
|
||||
|
||||
// Special handling for KwKwK
|
||||
if ( code == dictionary_ind )
|
||||
{
|
||||
int ptr = prev;
|
||||
|
||||
while ( dictionary[ ptr ].prev != -1 )
|
||||
{
|
||||
ptr = dictionary[ ptr ].prev;
|
||||
}
|
||||
dictionary[ dictionary_ind ].byte = dictionary[ ptr ].byte;
|
||||
}
|
||||
else
|
||||
{
|
||||
int ptr = code;
|
||||
while ( dictionary[ ptr ].prev != -1 )
|
||||
{
|
||||
ptr = dictionary[ ptr ].prev;
|
||||
}
|
||||
dictionary[ dictionary_ind ].byte = dictionary[ ptr ].byte;
|
||||
}
|
||||
|
||||
dictionary[ dictionary_ind ].prev = prev;
|
||||
|
||||
dictionary[ dictionary_ind ].len = dictionary[ prev ].len + 1;
|
||||
|
||||
dictionary_ind++;
|
||||
|
||||
// GIF89a mandates that this stops at 12 bits
|
||||
if ( ( dictionary_ind == ( 1 << ( code_length + 1 ) ) ) &&
|
||||
( code_length < 11 ) )
|
||||
{
|
||||
code_length++;
|
||||
|
||||
dictionary = ( dictionary_entry_t * ) realloc( dictionary,
|
||||
sizeof( dictionary_entry_t ) * ( 1 << ( code_length + 1 ) ) );
|
||||
}
|
||||
}
|
||||
|
||||
prev = code;
|
||||
|
||||
// Now copy the dictionary entry backwards into "out"
|
||||
match_len = dictionary[ code ].len;
|
||||
while ( code != -1 )
|
||||
{
|
||||
out[ dictionary[ code ].len - 1 ] = dictionary[ code ].byte;
|
||||
if ( dictionary[ code ].prev == code )
|
||||
{
|
||||
fprintf( stderr, "Internal error; self-reference." );
|
||||
exit( 0 );
|
||||
}
|
||||
code = dictionary[ code ].prev;
|
||||
}
|
||||
|
||||
out += match_len;
|
||||
}
|
||||
}
|
||||
|
||||
static int read_sub_blocks( unsigned char* buffer, unsigned char **data )
|
||||
{
|
||||
int data_length;
|
||||
int index;
|
||||
unsigned char block_size;
|
||||
|
||||
// Everything following are data sub-blocks, until a 0-sized block is
|
||||
// encountered.
|
||||
data_length = 0;
|
||||
*data = NULL;
|
||||
index = 0;
|
||||
|
||||
while ( 1 )
|
||||
{
|
||||
READ(&block_size, 1);
|
||||
|
||||
if ( block_size == 0 ) // end of sub-blocks
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
data_length += block_size;
|
||||
*data = (unsigned char*)realloc( *data, data_length );
|
||||
|
||||
// TODO this could be split across block size boundaries
|
||||
READ(*data + index, block_size);
|
||||
|
||||
index += block_size;
|
||||
}
|
||||
|
||||
return data_length;
|
||||
}
|
||||
|
||||
unsigned char* process_image_descriptor( unsigned char* buffer,
|
||||
rgb *gct,
|
||||
int gct_size,
|
||||
int resolution_bits )
|
||||
{
|
||||
image_descriptor_t image_descriptor;
|
||||
int compressed_data_length;
|
||||
unsigned char *compressed_data = NULL;
|
||||
unsigned char lzw_code_size;
|
||||
int uncompressed_data_length = 0;
|
||||
unsigned char *uncompressed_data = NULL;
|
||||
|
||||
// TODO there could actually be lots of these
|
||||
READ(&image_descriptor, 9);
|
||||
|
||||
// TODO if LCT = true, read the LCT
|
||||
|
||||
READ(&lzw_code_size, 1);
|
||||
|
||||
compressed_data_length = read_sub_blocks( buffer, &compressed_data );
|
||||
|
||||
// width = image_descriptor.image_width;
|
||||
// height = image_descriptor.image_height;
|
||||
uncompressed_data_length = image_descriptor.image_width *
|
||||
image_descriptor.image_height;
|
||||
uncompressed_data = (unsigned char*)malloc( uncompressed_data_length );
|
||||
|
||||
uncompress( lzw_code_size, compressed_data, compressed_data_length,
|
||||
uncompressed_data );
|
||||
|
||||
if ( compressed_data ) free( compressed_data );
|
||||
|
||||
//if ( uncompressed_data )
|
||||
// free( uncompressed_data );
|
||||
|
||||
return uncompressed_data;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param gif_file the file descriptor of a file containing a
|
||||
* GIF-encoded file. This should point to the first byte in
|
||||
* the file when invoked.
|
||||
*/
|
||||
#define rb (*(buffer++))
|
||||
|
||||
uint32_t* LoadPalette(unsigned char *buffer) {
|
||||
unsigned char header[7];
|
||||
screen_descriptor_t screen_descriptor;
|
||||
//int color_resolution_bits;
|
||||
|
||||
int global_color_table_size = 0; // number of entries in global_color_table
|
||||
uint32_t *global_color_table = NULL;
|
||||
|
||||
READ(header, 6);
|
||||
READ(&screen_descriptor, 7);
|
||||
|
||||
//color_resolution_bits = ((screen_descriptor.fields & 0x70) >> 4) + 1;
|
||||
global_color_table = (uint32_t *)calloc(1, 1024);
|
||||
|
||||
if (screen_descriptor.fields & 0x80) {
|
||||
global_color_table_size = 1 << (((screen_descriptor.fields & 0x07) + 1));
|
||||
|
||||
//global_color_table = (rgb *)malloc(3 * global_color_table_size);
|
||||
//READ(global_color_table, 3 * global_color_table_size);
|
||||
for (int i=0; i<global_color_table_size;++i) {
|
||||
global_color_table[i] = (buffer[0]<<16) + (buffer[1]<<8) + buffer[2];
|
||||
buffer+=3;
|
||||
}
|
||||
}
|
||||
return global_color_table;
|
||||
}
|
||||
|
||||
static unsigned char* process_gif_stream(unsigned char *buffer, unsigned short* w, unsigned short* h)
|
||||
{
|
||||
unsigned char header[ 7 ];
|
||||
screen_descriptor_t screen_descriptor;
|
||||
int color_resolution_bits;
|
||||
|
||||
int global_color_table_size =0; // number of entries in global_color_table
|
||||
rgb *global_color_table = NULL;
|
||||
|
||||
unsigned char block_type = 0x0;
|
||||
|
||||
// A GIF file starts with a Header (section 17)
|
||||
READ(header, 6);
|
||||
header[ 6 ] = 0x0;
|
||||
|
||||
// XXX there's another format, GIF87a, that you may still find
|
||||
// floating around.
|
||||
/*if ( strcmp( "GIF89a", (char*)header ) )
|
||||
{
|
||||
fprintf( stderr,
|
||||
"Invalid GIF file (header is '%s', should be 'GIF89a')\n",
|
||||
header );
|
||||
return NULL;
|
||||
}*/
|
||||
|
||||
// Followed by a logical screen descriptor
|
||||
// Note that this works because GIFs specify little-endian order; on a
|
||||
// big-endian machine, the height & width would need to be reversed.
|
||||
|
||||
// Can't use sizeof here since GCC does byte alignment;
|
||||
// sizeof( screen_descriptor_t ) = 8!
|
||||
READ(&screen_descriptor, 7);
|
||||
*w = screen_descriptor.width;
|
||||
*h = screen_descriptor.height;
|
||||
|
||||
color_resolution_bits = ( ( screen_descriptor.fields & 0x70 ) >> 4 ) + 1;
|
||||
|
||||
if ( screen_descriptor.fields & 0x80 )
|
||||
{
|
||||
//int i;
|
||||
// If bit 7 is set, the next block is a global color table; read it
|
||||
global_color_table_size = 1 <<
|
||||
( ( ( screen_descriptor.fields & 0x07 ) + 1 ) );
|
||||
|
||||
global_color_table = ( rgb * ) malloc( 3 * global_color_table_size );
|
||||
|
||||
// XXX this could conceivably return a short count...
|
||||
READ(global_color_table, 3 * global_color_table_size);
|
||||
}
|
||||
|
||||
while ( block_type != TRAILER )
|
||||
{
|
||||
READ(&block_type, 1);
|
||||
|
||||
unsigned char size;
|
||||
switch ( block_type )
|
||||
{
|
||||
case IMAGE_DESCRIPTOR:
|
||||
return process_image_descriptor(buffer,
|
||||
global_color_table,
|
||||
global_color_table_size,
|
||||
color_resolution_bits);
|
||||
break;
|
||||
case EXTENSION_INTRODUCER:
|
||||
buffer++;
|
||||
size = *(buffer++);
|
||||
buffer += size;
|
||||
do {
|
||||
size = *(buffer++);
|
||||
buffer += size;
|
||||
} while (size != 0);
|
||||
|
||||
/*if ( !process_extension( buffer ) )
|
||||
{
|
||||
return NULL;
|
||||
}*/
|
||||
break;
|
||||
case TRAILER:
|
||||
break;
|
||||
default:
|
||||
fprintf( stderr, "Bailing on unrecognized block type %.02x\n",
|
||||
block_type );
|
||||
return NULL;
|
||||
}
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
|
||||
unsigned char* LoadGif(unsigned char *buffer, unsigned short* w, unsigned short* h) {
|
||||
return process_gif_stream(buffer, w, h);
|
||||
}
|
||||
|
||||
/*int main( int argc, char *argv[] )
|
||||
{
|
||||
FILE* gif_file;
|
||||
|
||||
if ( argc < 2 )
|
||||
{
|
||||
fprintf( stderr, "Usage: %s <path-to-gif-file>\n", argv[ 0 ] );
|
||||
exit( 0 );
|
||||
}
|
||||
|
||||
gif_file = fopen( argv[ 1 ], "rb" );
|
||||
|
||||
if ( gif_file == NULL )
|
||||
{
|
||||
fprintf( stderr, "Unable to open file '%s'", argv[ 1 ] );
|
||||
perror( ": " );
|
||||
}
|
||||
|
||||
process_gif_stream( gif_file );
|
||||
|
||||
fclose( gif_file );
|
||||
}*/
|
||||
395
source/gif.cpp
Normal file
@@ -0,0 +1,395 @@
|
||||
#include "gif.h"
|
||||
#include <stdio.h> // Para NULL, fprintf, stderr
|
||||
#include <stdlib.h> // Para malloc, realloc, exit, calloc, free
|
||||
|
||||
void uncompress(int code_length,
|
||||
const unsigned char *input,
|
||||
int input_length,
|
||||
unsigned char *out)
|
||||
{
|
||||
// int maxbits;
|
||||
int i, bit;
|
||||
int code, prev = -1;
|
||||
dictionary_entry_t *dictionary;
|
||||
int dictionary_ind;
|
||||
unsigned int mask = 0x01;
|
||||
int reset_code_length;
|
||||
int clear_code; // This varies depending on code_length
|
||||
int stop_code; // one more than clear code
|
||||
int match_len;
|
||||
|
||||
clear_code = 1 << (code_length);
|
||||
stop_code = clear_code + 1;
|
||||
// To handle clear codes
|
||||
reset_code_length = code_length;
|
||||
|
||||
// Create a dictionary large enough to hold "code_length" entries.
|
||||
// Once the dictionary overflows, code_length increases
|
||||
dictionary = (dictionary_entry_t *)
|
||||
malloc(sizeof(dictionary_entry_t) * (1 << (code_length + 1)));
|
||||
|
||||
// Initialize the first 2^code_len entries of the dictionary with their
|
||||
// indices. The rest of the entries will be built up dynamically.
|
||||
|
||||
// Technically, it shouldn't be necessary to initialize the
|
||||
// dictionary. The spec says that the encoder "should output a
|
||||
// clear code as the first code in the image data stream". It doesn't
|
||||
// say must, though...
|
||||
for (dictionary_ind = 0;
|
||||
dictionary_ind < (1 << code_length);
|
||||
dictionary_ind++)
|
||||
{
|
||||
dictionary[dictionary_ind].byte = dictionary_ind;
|
||||
// XXX this only works because prev is a 32-bit int (> 12 bits)
|
||||
dictionary[dictionary_ind].prev = -1;
|
||||
dictionary[dictionary_ind].len = 1;
|
||||
}
|
||||
|
||||
// 2^code_len + 1 is the special "end" code; don't give it an entry here
|
||||
dictionary_ind++;
|
||||
dictionary_ind++;
|
||||
|
||||
// TODO verify that the very last byte is clear_code + 1
|
||||
while (input_length)
|
||||
{
|
||||
code = 0x0;
|
||||
// Always read one more bit than the code length
|
||||
for (i = 0; i < (code_length + 1); i++)
|
||||
{
|
||||
// This is different than in the file read example; that
|
||||
// was a call to "next_bit"
|
||||
bit = (*input & mask) ? 1 : 0;
|
||||
mask <<= 1;
|
||||
|
||||
if (mask == 0x100)
|
||||
{
|
||||
mask = 0x01;
|
||||
input++;
|
||||
input_length--;
|
||||
}
|
||||
|
||||
code = code | (bit << i);
|
||||
}
|
||||
|
||||
if (code == clear_code)
|
||||
{
|
||||
code_length = reset_code_length;
|
||||
dictionary = (dictionary_entry_t *)realloc(dictionary,
|
||||
sizeof(dictionary_entry_t) * (1 << (code_length + 1)));
|
||||
|
||||
for (dictionary_ind = 0;
|
||||
dictionary_ind < (1 << code_length);
|
||||
dictionary_ind++)
|
||||
{
|
||||
dictionary[dictionary_ind].byte = dictionary_ind;
|
||||
// XXX this only works because prev is a 32-bit int (> 12 bits)
|
||||
dictionary[dictionary_ind].prev = -1;
|
||||
dictionary[dictionary_ind].len = 1;
|
||||
}
|
||||
dictionary_ind++;
|
||||
dictionary_ind++;
|
||||
prev = -1;
|
||||
continue;
|
||||
}
|
||||
else if (code == stop_code)
|
||||
{
|
||||
/*if ( input_length > 1 )
|
||||
{
|
||||
fprintf( stderr, "Malformed GIF (early stop code)\n" );
|
||||
exit( 0 );
|
||||
}*/
|
||||
break;
|
||||
}
|
||||
|
||||
// Update the dictionary with this character plus the _entry_
|
||||
// (character or string) that came before it
|
||||
if ((prev > -1) && (code_length < 12))
|
||||
{
|
||||
if (code > dictionary_ind)
|
||||
{
|
||||
fprintf(stderr, "code = %.02x, but dictionary_ind = %.02x\n",
|
||||
code, dictionary_ind);
|
||||
exit(0);
|
||||
}
|
||||
|
||||
// Special handling for KwKwK
|
||||
if (code == dictionary_ind)
|
||||
{
|
||||
int ptr = prev;
|
||||
|
||||
while (dictionary[ptr].prev != -1)
|
||||
{
|
||||
ptr = dictionary[ptr].prev;
|
||||
}
|
||||
dictionary[dictionary_ind].byte = dictionary[ptr].byte;
|
||||
}
|
||||
else
|
||||
{
|
||||
int ptr = code;
|
||||
while (dictionary[ptr].prev != -1)
|
||||
{
|
||||
ptr = dictionary[ptr].prev;
|
||||
}
|
||||
dictionary[dictionary_ind].byte = dictionary[ptr].byte;
|
||||
}
|
||||
|
||||
dictionary[dictionary_ind].prev = prev;
|
||||
|
||||
dictionary[dictionary_ind].len = dictionary[prev].len + 1;
|
||||
|
||||
dictionary_ind++;
|
||||
|
||||
// GIF89a mandates that this stops at 12 bits
|
||||
if ((dictionary_ind == (1 << (code_length + 1))) &&
|
||||
(code_length < 11))
|
||||
{
|
||||
code_length++;
|
||||
|
||||
dictionary = (dictionary_entry_t *)realloc(dictionary,
|
||||
sizeof(dictionary_entry_t) * (1 << (code_length + 1)));
|
||||
}
|
||||
}
|
||||
|
||||
prev = code;
|
||||
|
||||
// Now copy the dictionary entry backwards into "out"
|
||||
match_len = dictionary[code].len;
|
||||
while (code != -1)
|
||||
{
|
||||
out[dictionary[code].len - 1] = dictionary[code].byte;
|
||||
if (dictionary[code].prev == code)
|
||||
{
|
||||
fprintf(stderr, "Internal error; self-reference.");
|
||||
exit(0);
|
||||
}
|
||||
code = dictionary[code].prev;
|
||||
}
|
||||
|
||||
out += match_len;
|
||||
}
|
||||
}
|
||||
|
||||
static int read_sub_blocks(unsigned char *buffer, unsigned char **data)
|
||||
{
|
||||
int data_length;
|
||||
int index;
|
||||
unsigned char block_size;
|
||||
|
||||
// Everything following are data sub-blocks, until a 0-sized block is
|
||||
// encountered.
|
||||
data_length = 0;
|
||||
*data = NULL;
|
||||
index = 0;
|
||||
|
||||
while (1)
|
||||
{
|
||||
READ(&block_size, 1);
|
||||
|
||||
if (block_size == 0) // end of sub-blocks
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
data_length += block_size;
|
||||
*data = (unsigned char *)realloc(*data, data_length);
|
||||
|
||||
// TODO this could be split across block size boundaries
|
||||
READ(*data + index, block_size);
|
||||
|
||||
index += block_size;
|
||||
}
|
||||
|
||||
return data_length;
|
||||
}
|
||||
|
||||
unsigned char *process_image_descriptor(unsigned char *buffer,
|
||||
rgb *gct,
|
||||
int gct_size,
|
||||
int resolution_bits)
|
||||
{
|
||||
image_descriptor_t image_descriptor;
|
||||
int compressed_data_length;
|
||||
unsigned char *compressed_data = NULL;
|
||||
unsigned char lzw_code_size;
|
||||
int uncompressed_data_length = 0;
|
||||
unsigned char *uncompressed_data = NULL;
|
||||
|
||||
// TODO there could actually be lots of these
|
||||
READ(&image_descriptor, 9);
|
||||
|
||||
// TODO if LCT = true, read the LCT
|
||||
|
||||
READ(&lzw_code_size, 1);
|
||||
|
||||
compressed_data_length = read_sub_blocks(buffer, &compressed_data);
|
||||
|
||||
// width = image_descriptor.image_width;
|
||||
// height = image_descriptor.image_height;
|
||||
uncompressed_data_length = image_descriptor.image_width *
|
||||
image_descriptor.image_height;
|
||||
uncompressed_data = (unsigned char *)malloc(uncompressed_data_length);
|
||||
|
||||
uncompress(lzw_code_size, compressed_data, compressed_data_length,
|
||||
uncompressed_data);
|
||||
|
||||
if (compressed_data)
|
||||
free(compressed_data);
|
||||
|
||||
// if ( uncompressed_data )
|
||||
// free( uncompressed_data );
|
||||
|
||||
return uncompressed_data;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param gif_file the file descriptor of a file containing a
|
||||
* GIF-encoded file. This should point to the first byte in
|
||||
* the file when invoked.
|
||||
*/
|
||||
#define rb (*(buffer++))
|
||||
|
||||
uint32_t *LoadPalette(unsigned char *buffer)
|
||||
{
|
||||
unsigned char header[7];
|
||||
screen_descriptor_t screen_descriptor;
|
||||
// int color_resolution_bits;
|
||||
|
||||
int global_color_table_size = 0; // number of entries in global_color_table
|
||||
uint32_t *global_color_table = NULL;
|
||||
|
||||
READ(header, 6);
|
||||
READ(&screen_descriptor, 7);
|
||||
|
||||
// color_resolution_bits = ((screen_descriptor.fields & 0x70) >> 4) + 1;
|
||||
global_color_table = (uint32_t *)calloc(1, 1024);
|
||||
|
||||
if (screen_descriptor.fields & 0x80)
|
||||
{
|
||||
global_color_table_size = 1 << (((screen_descriptor.fields & 0x07) + 1));
|
||||
|
||||
// global_color_table = (rgb *)malloc(3 * global_color_table_size);
|
||||
// READ(global_color_table, 3 * global_color_table_size);
|
||||
for (int i = 0; i < global_color_table_size; ++i)
|
||||
{
|
||||
global_color_table[i] = (buffer[0] << 16) + (buffer[1] << 8) + buffer[2];
|
||||
buffer += 3;
|
||||
}
|
||||
}
|
||||
return global_color_table;
|
||||
}
|
||||
|
||||
static unsigned char *process_gif_stream(unsigned char *buffer, unsigned short *w, unsigned short *h)
|
||||
{
|
||||
unsigned char header[7];
|
||||
screen_descriptor_t screen_descriptor;
|
||||
int color_resolution_bits;
|
||||
|
||||
int global_color_table_size = 0; // number of entries in global_color_table
|
||||
rgb *global_color_table = NULL;
|
||||
|
||||
unsigned char block_type = 0x0;
|
||||
|
||||
// A GIF file starts with a Header (section 17)
|
||||
READ(header, 6);
|
||||
header[6] = 0x0;
|
||||
|
||||
// XXX there's another format, GIF87a, that you may still find
|
||||
// floating around.
|
||||
/*if ( strcmp( "GIF89a", (char*)header ) )
|
||||
{
|
||||
fprintf( stderr,
|
||||
"Invalid GIF file (header is '%s', should be 'GIF89a')\n",
|
||||
header );
|
||||
return NULL;
|
||||
}*/
|
||||
|
||||
// Followed by a logical screen descriptor
|
||||
// Note that this works because GIFs specify little-endian order; on a
|
||||
// big-endian machine, the height & width would need to be reversed.
|
||||
|
||||
// Can't use sizeof here since GCC does byte alignment;
|
||||
// sizeof( screen_descriptor_t ) = 8!
|
||||
READ(&screen_descriptor, 7);
|
||||
*w = screen_descriptor.width;
|
||||
*h = screen_descriptor.height;
|
||||
|
||||
color_resolution_bits = ((screen_descriptor.fields & 0x70) >> 4) + 1;
|
||||
|
||||
if (screen_descriptor.fields & 0x80)
|
||||
{
|
||||
// int i;
|
||||
// If bit 7 is set, the next block is a global color table; read it
|
||||
global_color_table_size = 1 << (((screen_descriptor.fields & 0x07) + 1));
|
||||
|
||||
global_color_table = (rgb *)malloc(3 * global_color_table_size);
|
||||
|
||||
// XXX this could conceivably return a short count...
|
||||
READ(global_color_table, 3 * global_color_table_size);
|
||||
}
|
||||
|
||||
while (block_type != TRAILER)
|
||||
{
|
||||
READ(&block_type, 1);
|
||||
|
||||
unsigned char size;
|
||||
switch (block_type)
|
||||
{
|
||||
case IMAGE_DESCRIPTOR:
|
||||
return process_image_descriptor(buffer,
|
||||
global_color_table,
|
||||
global_color_table_size,
|
||||
color_resolution_bits);
|
||||
break;
|
||||
case EXTENSION_INTRODUCER:
|
||||
buffer++;
|
||||
size = *(buffer++);
|
||||
buffer += size;
|
||||
do
|
||||
{
|
||||
size = *(buffer++);
|
||||
buffer += size;
|
||||
} while (size != 0);
|
||||
|
||||
/*if ( !process_extension( buffer ) )
|
||||
{
|
||||
return NULL;
|
||||
}*/
|
||||
break;
|
||||
case TRAILER:
|
||||
break;
|
||||
default:
|
||||
fprintf(stderr, "Bailing on unrecognized block type %.02x\n",
|
||||
block_type);
|
||||
return NULL;
|
||||
}
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
unsigned char *LoadGif(unsigned char *buffer, unsigned short *w, unsigned short *h)
|
||||
{
|
||||
return process_gif_stream(buffer, w, h);
|
||||
}
|
||||
|
||||
/*int main( int argc, char *argv[] )
|
||||
{
|
||||
FILE* gif_file;
|
||||
|
||||
if ( argc < 2 )
|
||||
{
|
||||
fprintf( stderr, "Usage: %s <path-to-gif-file>\n", argv[ 0 ] );
|
||||
exit( 0 );
|
||||
}
|
||||
|
||||
gif_file = fopen( argv[ 1 ], "rb" );
|
||||
|
||||
if ( gif_file == NULL )
|
||||
{
|
||||
fprintf( stderr, "Unable to open file '%s'", argv[ 1 ] );
|
||||
perror( ": " );
|
||||
}
|
||||
|
||||
process_gif_stream( gif_file );
|
||||
|
||||
fclose( gif_file );
|
||||
}*/
|
||||
76
source/gif.h
Normal file
@@ -0,0 +1,76 @@
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h> // Para uint32_t
|
||||
#include <string.h> // Para memcpy
|
||||
|
||||
#define EXTENSION_INTRODUCER 0x21
|
||||
#define IMAGE_DESCRIPTOR 0x2C
|
||||
#define TRAILER 0x3B
|
||||
#define GRAPHIC_CONTROL 0xF9
|
||||
#define APPLICATION_EXTENSION 0xFF
|
||||
#define COMMENT_EXTENSION 0xFE
|
||||
#define PLAINTEXT_EXTENSION 0x01
|
||||
|
||||
#define READ(dst, size) \
|
||||
memcpy(dst, buffer, size); \
|
||||
buffer += size
|
||||
|
||||
typedef struct
|
||||
{
|
||||
unsigned short width;
|
||||
unsigned short height;
|
||||
unsigned char fields;
|
||||
unsigned char background_color_index;
|
||||
unsigned char pixel_aspect_ratio;
|
||||
} screen_descriptor_t;
|
||||
|
||||
typedef struct
|
||||
{
|
||||
unsigned char r, g, b;
|
||||
} rgb;
|
||||
|
||||
typedef struct
|
||||
{
|
||||
unsigned short image_left_position;
|
||||
unsigned short image_top_position;
|
||||
unsigned short image_width;
|
||||
unsigned short image_height;
|
||||
unsigned char fields;
|
||||
} image_descriptor_t;
|
||||
|
||||
typedef struct
|
||||
{
|
||||
unsigned char byte;
|
||||
int prev;
|
||||
int len;
|
||||
} dictionary_entry_t;
|
||||
|
||||
typedef struct
|
||||
{
|
||||
unsigned char extension_code;
|
||||
unsigned char block_size;
|
||||
} extension_t;
|
||||
|
||||
typedef struct
|
||||
{
|
||||
unsigned char fields;
|
||||
unsigned short delay_time;
|
||||
unsigned char transparent_color_index;
|
||||
} graphic_control_extension_t;
|
||||
|
||||
typedef struct
|
||||
{
|
||||
unsigned char application_id[8];
|
||||
unsigned char version[3];
|
||||
} application_extension_t;
|
||||
|
||||
typedef struct
|
||||
{
|
||||
unsigned short left, top, width, height;
|
||||
unsigned char cell_width, cell_height;
|
||||
unsigned char foreground_color, background_color;
|
||||
} plaintext_extension_t;
|
||||
|
||||
void uncompress(int code_length, const unsigned char *input, int input_length, unsigned char *out);
|
||||
uint32_t *LoadPalette(unsigned char *buffer);
|
||||
unsigned char *LoadGif(unsigned char *buffer, unsigned short *w, unsigned short *h);
|
||||
33
source/global_events.cpp
Normal file
@@ -0,0 +1,33 @@
|
||||
#include "global_events.h"
|
||||
#include <SDL2/SDL_video.h> // Para SDL_WINDOWEVENT_SIZE_CHANGED
|
||||
#include <iostream> // Para char_traits, basic_ostream, operator<<
|
||||
#include "mouse.h" // Para handleEvent
|
||||
#include "section.h" // Para Name, Options, name, options
|
||||
|
||||
namespace globalEvents
|
||||
{
|
||||
// Comprueba los eventos que se pueden producir en cualquier sección del juego
|
||||
void check(const SDL_Event &event)
|
||||
{
|
||||
switch (event.type)
|
||||
{
|
||||
case SDL_QUIT: // Evento de salida de la aplicación
|
||||
section::name = section::Name::QUIT;
|
||||
section::options = section::Options::QUIT_FROM_EVENT;
|
||||
return;
|
||||
case SDL_RENDER_DEVICE_RESET:
|
||||
case SDL_RENDER_TARGETS_RESET:
|
||||
std::cout << "SDL_RENDER_TARGETS_RESET" << std::endl;
|
||||
break;
|
||||
case SDL_WINDOWEVENT:
|
||||
if (event.window.event == SDL_WINDOWEVENT_SIZE_CHANGED)
|
||||
{
|
||||
std::cout << "SDL_WINDOWEVENT_SIZE_CHANGED" << std::endl;
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
Mouse::handleEvent(event);
|
||||
}
|
||||
}
|
||||
9
source/global_events.h
Normal file
@@ -0,0 +1,9 @@
|
||||
#pragma once
|
||||
|
||||
#include <SDL2/SDL_events.h>
|
||||
|
||||
namespace globalEvents
|
||||
{
|
||||
// Comprueba los eventos que se pueden producir en cualquier sección del juego
|
||||
void check(const SDL_Event &event);
|
||||
}
|
||||
@@ -1,16 +1,18 @@
|
||||
#include "global_inputs.h"
|
||||
#include <SDL2/SDL_render.h> // Para SDL_RenderSetIntegerScale
|
||||
#include <SDL2/SDL_stdinc.h> // Para SDL_FALSE, SDL_TRUE
|
||||
#include <string> // Para operator+, string, to_string, basic_string
|
||||
#include <vector> // Para vector
|
||||
#include "asset.h" // Para Asset
|
||||
#include "input.h" // Para Input, InputDeviceToUse, InputType, INPU...
|
||||
#include "input.h" // Para Input, InputDeviceToUse, InputType, INP...
|
||||
#include "jail_audio.h" // Para JA_SetMusicVolume, JA_SetSoundVolume
|
||||
#include "lang.h" // Para Code, getText, change, loadFromFile
|
||||
#include "lang.h" // Para getText, Code, getNextLangCode, loadFro...
|
||||
#include "notifier.h" // Para Notifier
|
||||
#include "on_screen_help.h" // Para OnScreenHelp
|
||||
#include "options.h" // Para Options, options, OptionsGame, OptionsAudio
|
||||
#include "options.h" // Para Options, options, OptionsGame, OptionsV...
|
||||
#include "screen.h" // Para Screen, ScreenVideoMode
|
||||
#include "section.h" // Para Name, Options, name, options
|
||||
#include "utils.h" // Para boolToOnOff, stringInVector
|
||||
#include "section.h" // Para Name, name, Options, options, AttractMode
|
||||
#include "utils.h" // Para boolToOnOff
|
||||
|
||||
namespace globalInputs
|
||||
{
|
||||
@@ -21,9 +23,8 @@ namespace globalInputs
|
||||
// Termina
|
||||
void quit(section::Options code)
|
||||
{
|
||||
const std::string exit_code = "QUIT";
|
||||
auto code_found = stringInVector(Notifier::get()->getCodes(), exit_code);
|
||||
if (code_found)
|
||||
const std::string CODE = "QUIT";
|
||||
if (Notifier::get()->checkCode(CODE))
|
||||
{
|
||||
// Si la notificación de salir está activa, cambia de sección
|
||||
section::name = section::Name::QUIT;
|
||||
@@ -33,19 +34,27 @@ namespace globalInputs
|
||||
{
|
||||
// Si la notificación de salir no está activa, muestra la notificación
|
||||
#ifdef ARCADE
|
||||
const int index = code == section::Options::QUIT_WITH_CONTROLLER ? 116 : 94;
|
||||
Notifier::get()->showText({lang::getText(index), std::string()}, -1, exit_code);
|
||||
const int INDEX = code == section::Options::QUIT_WITH_CONTROLLER ? 116 : 94;
|
||||
Notifier::get()->show({lang::getText(INDEX), std::string()}, -1, CODE);
|
||||
#else
|
||||
Notifier::get()->showText({lang::getText(94), std::string()}, -1, exit_code);
|
||||
Notifier::get()->show({lang::getText(94), std::string()}, -1, CODE);
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
// Reinicia
|
||||
void reset()
|
||||
{
|
||||
const std::string CODE = "RESET";
|
||||
if (Notifier::get()->checkCode(CODE))
|
||||
{
|
||||
section::name = section::Name::INIT;
|
||||
Notifier::get()->showText({"Reset"});
|
||||
Notifier::get()->show({lang::getText(111)});
|
||||
}
|
||||
else
|
||||
{
|
||||
Notifier::get()->show({lang::getText(125), std::string()}, -1, CODE);
|
||||
}
|
||||
}
|
||||
|
||||
// Activa o desactiva el audio
|
||||
@@ -62,7 +71,23 @@ namespace globalInputs
|
||||
JA_SetMusicVolume(0);
|
||||
JA_SetSoundVolume(0);
|
||||
}
|
||||
Notifier::get()->showText({"Audio " + boolToOnOff(options.audio.enabled)});
|
||||
Notifier::get()->show({"Audio " + boolToOnOff(options.audio.enabled)});
|
||||
}
|
||||
|
||||
// Cambia el modo de escalado entero
|
||||
void toggleintegerScale()
|
||||
{
|
||||
options.video.integer_scale = !options.video.integer_scale;
|
||||
SDL_RenderSetIntegerScale(Screen::get()->getRenderer(), options.video.integer_scale ? SDL_TRUE : SDL_FALSE);
|
||||
Screen::get()->setVideoMode();
|
||||
Notifier::get()->show({lang::getText(134) + " " + boolToOnOff(options.video.integer_scale)});
|
||||
}
|
||||
|
||||
// Activa o desactiva los shaders
|
||||
void toggleShaders()
|
||||
{
|
||||
Screen::get()->toggleShaders();
|
||||
Notifier::get()->show({lang::getText(135) + " " + boolToOnOff(options.video.shaders)});
|
||||
}
|
||||
|
||||
// Obtiene una fichero a partir de un lang::Code
|
||||
@@ -88,13 +113,13 @@ namespace globalInputs
|
||||
switch (code)
|
||||
{
|
||||
case lang::Code::ba_BA:
|
||||
return "ba_BA";
|
||||
return " \"ba_BA\"";
|
||||
break;
|
||||
case lang::Code::es_ES:
|
||||
return "es_ES";
|
||||
return " \"es_ES\"";
|
||||
break;
|
||||
default:
|
||||
return "en_UK";
|
||||
return " \"en_UK\"";
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -102,18 +127,49 @@ namespace globalInputs
|
||||
// Cambia el idioma
|
||||
void changeLang()
|
||||
{
|
||||
options.game.language = lang::change(options.game.language);
|
||||
const std::string CODE = "LANG";
|
||||
if (Notifier::get()->checkCode(CODE))
|
||||
{
|
||||
options.game.language = lang::getNextLangCode(options.game.language);
|
||||
lang::loadFromFile(getLangFile(static_cast<lang::Code>(options.game.language)));
|
||||
section::name = section::Name::INIT;
|
||||
section::options = section::Options::RELOAD;
|
||||
Notifier::get()->showText({getLangName(options.game.language)});
|
||||
Notifier::get()->show({lang::getText(127) + getLangName(options.game.language)});
|
||||
}
|
||||
else
|
||||
{
|
||||
const auto NEXT = lang::getNextLangCode(options.game.language);
|
||||
Notifier::get()->show({lang::getText(126) + getLangName(NEXT), std::string()}, -1, CODE);
|
||||
}
|
||||
}
|
||||
|
||||
// Cambia el modo de disparo
|
||||
void toggleFireMode()
|
||||
{
|
||||
options.game.autofire = !options.game.autofire;
|
||||
Notifier::get()->showText({"Autofire " + boolToOnOff(options.game.autofire)});
|
||||
Notifier::get()->show({lang::getText(130) + " " + boolToOnOff(options.game.autofire)});
|
||||
}
|
||||
|
||||
// Salta una sección del juego
|
||||
void skip_section()
|
||||
{
|
||||
switch (section::name)
|
||||
{
|
||||
case section::Name::INTRO:
|
||||
JA_StopMusic();
|
||||
/* Continua en el case de abajo */
|
||||
case section::Name::LOGO:
|
||||
case section::Name::HI_SCORE_TABLE:
|
||||
case section::Name::INSTRUCTIONS:
|
||||
{
|
||||
section::name = section::Name::TITLE;
|
||||
section::options = section::Options::TITLE_1;
|
||||
section::attract_mode = section::AttractMode::TITLE_TO_DEMO;
|
||||
break;
|
||||
}
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Comprueba los inputs que se pueden introducir en cualquier sección del juego
|
||||
@@ -121,34 +177,35 @@ namespace globalInputs
|
||||
{
|
||||
// Teclado
|
||||
{
|
||||
#ifndef ARCADE
|
||||
// Comprueba el teclado para cambiar entre pantalla completa y ventana
|
||||
if (Input::get()->checkInput(InputType::WINDOW_FULLSCREEN, INPUT_DO_NOT_ALLOW_REPEAT, InputDeviceToUse::KEYBOARD))
|
||||
{
|
||||
Screen::get()->toggleVideoMode();
|
||||
const std::string mode = options.video.mode == ScreenVideoMode::WINDOW ? "Window" : "Fullscreen";
|
||||
Notifier::get()->showText({mode + " mode"});
|
||||
const std::string mode = options.video.mode == ScreenVideoMode::WINDOW ? lang::getText(132) : lang::getText(133);
|
||||
Notifier::get()->show({mode});
|
||||
return;
|
||||
}
|
||||
|
||||
// Comprueba el teclado para decrementar el tamaño de la ventana
|
||||
if (Input::get()->checkInput(InputType::WINDOW_DEC_SIZE, INPUT_DO_NOT_ALLOW_REPEAT, InputDeviceToUse::KEYBOARD))
|
||||
{
|
||||
Screen::get()->decWindowSize();
|
||||
const std::string size = std::to_string(options.video.window.size);
|
||||
Notifier::get()->showText({"Window size x" + size});
|
||||
if (Screen::get()->decWindowZoom())
|
||||
{
|
||||
Notifier::get()->show({lang::getText(131) + " x" + std::to_string(options.video.window.zoom)});
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Comprueba el teclado para incrementar el tamaño de la ventana
|
||||
if (Input::get()->checkInput(InputType::WINDOW_INC_SIZE, INPUT_DO_NOT_ALLOW_REPEAT, InputDeviceToUse::KEYBOARD))
|
||||
{
|
||||
Screen::get()->incWindowSize();
|
||||
const std::string size = std::to_string(options.video.window.size);
|
||||
Notifier::get()->showText({"Window size x" + size});
|
||||
if (Screen::get()->incWindowZoom())
|
||||
{
|
||||
Notifier::get()->show({lang::getText(131) + " x" + std::to_string(options.video.window.zoom)});
|
||||
}
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
|
||||
// Salir
|
||||
if (Input::get()->checkInput(InputType::EXIT, INPUT_DO_NOT_ALLOW_REPEAT, InputDeviceToUse::KEYBOARD))
|
||||
{
|
||||
@@ -156,6 +213,13 @@ namespace globalInputs
|
||||
return;
|
||||
}
|
||||
|
||||
// Saltar sección
|
||||
if (Input::get()->checkAnyButtonPressed())
|
||||
{
|
||||
skip_section();
|
||||
return;
|
||||
}
|
||||
|
||||
// Reset
|
||||
if (Input::get()->checkInput(InputType::RESET, INPUT_DO_NOT_ALLOW_REPEAT, InputDeviceToUse::KEYBOARD))
|
||||
{
|
||||
@@ -187,7 +251,13 @@ namespace globalInputs
|
||||
// Shaders
|
||||
if (Input::get()->checkInput(InputType::VIDEO_SHADERS, INPUT_DO_NOT_ALLOW_REPEAT, InputDeviceToUse::KEYBOARD))
|
||||
{
|
||||
Screen::get()->toggleShaders();
|
||||
toggleShaders();
|
||||
return;
|
||||
}
|
||||
|
||||
if (Input::get()->checkInput(InputType::VIDEO_INTEGER_SCALE, INPUT_DO_NOT_ALLOW_REPEAT, InputDeviceToUse::KEYBOARD))
|
||||
{
|
||||
toggleintegerScale();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -239,7 +309,7 @@ namespace globalInputs
|
||||
if (Input::get()->checkInput(InputType::SERVICE, INPUT_ALLOW_REPEAT, InputDeviceToUse::CONTROLLER, i) &&
|
||||
Input::get()->checkInput(InputType::VIDEO_SHADERS, INPUT_DO_NOT_ALLOW_REPEAT, InputDeviceToUse::CONTROLLER, i))
|
||||
{
|
||||
Screen::get()->toggleShaders();
|
||||
toggleShaders();
|
||||
return;
|
||||
}
|
||||
#ifdef DEBUG
|
||||
|
||||
@@ -1,26 +1,29 @@
|
||||
#include "hiscore_table.h"
|
||||
#include <SDL2/SDL_blendmode.h> // Para SDL_BLENDMODE_BLEND
|
||||
#include <SDL2/SDL_events.h> // Para SDL_PollEvent, SDL_Event, SDL_QUIT
|
||||
#include <SDL2/SDL_events.h> // Para SDL_PollEvent, SDL_Event
|
||||
#include <SDL2/SDL_pixels.h> // Para SDL_PIXELFORMAT_RGBA8888
|
||||
#include <SDL2/SDL_timer.h> // Para SDL_GetTicks
|
||||
#include <SDL2/SDL_video.h> // Para SDL_WINDOWEVENT_SIZE_CHANGED
|
||||
#include <stdlib.h> // Para rand, size_t
|
||||
#include <algorithm> // Para max
|
||||
#include <functional> // Para function
|
||||
#include <vector> // Para vector
|
||||
#include "background.h" // Para Background
|
||||
#include "fade.h" // Para Fade, FadeMode, FadeType
|
||||
#include "global_inputs.h" // Para check
|
||||
#include "input.h" // Para Input
|
||||
#include "global_events.h" // Para check
|
||||
#include "global_inputs.h" // Para check, update
|
||||
#include "jail_audio.h" // Para JA_GetMusicState, JA_Music_state
|
||||
#include "lang.h" // Para getText
|
||||
#include "manage_hiscore_table.h" // Para HiScoreEntry
|
||||
#include "options.h" // Para Options, OptionsGame, options
|
||||
#include "param.h" // Para Param, param, ParamGame, ParamFade
|
||||
#include "path_sprite.h" // Para PathSprite, Path, PathType
|
||||
#include "resource.h" // Para Resource
|
||||
#include "screen.h" // Para Screen
|
||||
#include "section.h" // Para Name, name, Options, options
|
||||
#include "text.h" // Para Text, TEXT_CENTER, TEXT_SHADOW
|
||||
#include "utils.h" // Para Color, Zone, fade_color, orange_color
|
||||
#include "mouse.h"
|
||||
#include "section.h" // Para Name, name
|
||||
#include "sprite.h" // Para Sprite
|
||||
#include "text.h" // Para Text, TEXT_SHADOW, TEXT_COLOR
|
||||
#include "texture.h" // Para Texture
|
||||
#include "utils.h" // Para Color, easeOutQuint, fade_color, Zone
|
||||
|
||||
// Constructor
|
||||
HiScoreTable::HiScoreTable()
|
||||
@@ -28,60 +31,41 @@ HiScoreTable::HiScoreTable()
|
||||
backbuffer_(SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, param.game.width, param.game.height)),
|
||||
fade_(std::make_unique<Fade>()),
|
||||
background_(std::make_unique<Background>()),
|
||||
text_(Resource::get()->getText("smb2")),
|
||||
counter_(0),
|
||||
ticks_(0),
|
||||
view_area_({0, 0, param.game.width, param.game.height}),
|
||||
fade_mode_(FadeMode::IN)
|
||||
fade_mode_(FadeMode::IN),
|
||||
background_fade_color_(Color(0, 0, 0))
|
||||
{
|
||||
// Inicializa el resto de variables
|
||||
// Inicializa el resto
|
||||
section::name = section::Name::HI_SCORE_TABLE;
|
||||
|
||||
// Inicializa objetos
|
||||
SDL_SetTextureBlendMode(backbuffer_, SDL_BLENDMODE_BLEND);
|
||||
background_->setPos(param.game.game_area.rect);
|
||||
background_->setCloudsSpeed(-0.1f);
|
||||
background_->setGradientNumber(1);
|
||||
background_->setTransition(0.8f);
|
||||
background_->setSunProgression(1.0f);
|
||||
background_->setMoonProgression(0.6f);
|
||||
fade_->setColor(fade_color.r, fade_color.g, fade_color.b);
|
||||
fade_->setType(FadeType::RANDOM_SQUARE);
|
||||
fade_->setPostDuration(param.fade.post_duration);
|
||||
fade_->setMode(fade_mode_);
|
||||
fade_->activate();
|
||||
|
||||
// Crea el contenido de la textura con la lista de puntuaciones
|
||||
fillTexture();
|
||||
initFade();
|
||||
initBackground();
|
||||
iniEntryColors();
|
||||
createSprites();
|
||||
}
|
||||
|
||||
// Destructor
|
||||
HiScoreTable::~HiScoreTable()
|
||||
{
|
||||
SDL_DestroyTexture(backbuffer_);
|
||||
options.game.clear_last_hi_score_entries();
|
||||
}
|
||||
|
||||
// Actualiza las variables
|
||||
void HiScoreTable::update()
|
||||
{
|
||||
constexpr int TICKS_SPEED = 15;
|
||||
|
||||
if (SDL_GetTicks() - ticks_ > TICKS_SPEED)
|
||||
if (SDL_GetTicks() - ticks_ > param.game.speed)
|
||||
{
|
||||
// Actualiza el contador de ticks
|
||||
ticks_ = SDL_GetTicks();
|
||||
|
||||
// Mantiene la música sonando
|
||||
if ((JA_GetMusicState() == JA_MUSIC_INVALID) || (JA_GetMusicState() == JA_MUSIC_STOPPED))
|
||||
{
|
||||
JA_PlayMusic(Resource::get()->getMusic("title.ogg"));
|
||||
}
|
||||
updateMusic();
|
||||
|
||||
// Actualiza el objeto screen
|
||||
Screen::get()->update();
|
||||
|
||||
// Actualiza las variables de globalInputs
|
||||
globalInputs::update();
|
||||
// Actualiza las posiciones de los sprites de texto
|
||||
updateSprites();
|
||||
|
||||
// Actualiza el fondo
|
||||
background_->update();
|
||||
@@ -90,31 +74,22 @@ void HiScoreTable::update()
|
||||
updateFade();
|
||||
|
||||
// Gestiona el contador y sus eventos
|
||||
counter_++;
|
||||
updateCounter();
|
||||
|
||||
if (counter_ == 150)
|
||||
{
|
||||
background_->setColor(Color(0, 0, 0));
|
||||
background_->setAlpha(96);
|
||||
}
|
||||
// Dibuja los sprites en la textura
|
||||
fillTexture();
|
||||
|
||||
if (counter_ == COUNTER_END_)
|
||||
{
|
||||
fade_->activate();
|
||||
}
|
||||
// Actualiza el objeto screen
|
||||
Screen::get()->update();
|
||||
|
||||
// Actualiza las variables de globalInputs
|
||||
globalInputs::update();
|
||||
}
|
||||
}
|
||||
|
||||
// Crea el contenido de la textura con la lista de puntuaciones
|
||||
// Dibuja los sprites en la textura
|
||||
void HiScoreTable::fillTexture()
|
||||
{
|
||||
// hay 27 letras - 7 de puntos quedan 20 caracteres 20 - name_lenght 0 num_dots
|
||||
constexpr auto max_names = 10;
|
||||
constexpr auto space_between_header = 32;
|
||||
const auto space_between_lines = text_->getCharacterSize() * 2.0f;
|
||||
const auto size = space_between_header + space_between_lines * (max_names - 1) + text_->getCharacterSize();
|
||||
const auto first_line = (param.game.height - size) / 2;
|
||||
|
||||
// Pinta en el backbuffer el texto y los sprites
|
||||
auto temp = SDL_GetRenderTarget(renderer_);
|
||||
SDL_SetRenderTarget(renderer_, backbuffer_);
|
||||
@@ -122,22 +97,12 @@ void HiScoreTable::fillTexture()
|
||||
SDL_RenderClear(renderer_);
|
||||
|
||||
// Escribe el texto: Mejores puntuaciones
|
||||
text_->writeDX(TEXT_CENTER | TEXT_COLOR | TEXT_SHADOW, param.game.game_area.center_x, first_line, lang::getText(42), 1, orange_color, 1, shdw_txt_color);
|
||||
header_->render();
|
||||
|
||||
// Escribe los nombres de la tabla de puntuaciones
|
||||
for (int i = 0; i < max_names; ++i)
|
||||
for (auto const &entry : entry_names_)
|
||||
{
|
||||
const auto name_lenght = options.game.hi_score_table[i].name.length();
|
||||
const auto score = format(options.game.hi_score_table[i].score);
|
||||
const auto score_lenght = score.size();
|
||||
const auto num_dots = 25 - name_lenght - score_lenght;
|
||||
std::string dots;
|
||||
for (int j = 0; j < (int)num_dots; ++j)
|
||||
{
|
||||
dots = dots + ".";
|
||||
}
|
||||
const auto line = options.game.hi_score_table[i].name + dots + score;
|
||||
text_->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, (i * space_between_lines) + first_line + space_between_header, line, 1, orange_color, 1, shdw_txt_color);
|
||||
entry->render();
|
||||
}
|
||||
|
||||
// Cambia el destino de renderizado
|
||||
@@ -169,56 +134,19 @@ void HiScoreTable::render()
|
||||
Screen::get()->render();
|
||||
}
|
||||
|
||||
// Recarga todas las texturas
|
||||
void HiScoreTable::reloadTextures()
|
||||
{
|
||||
text_->reLoadTexture();
|
||||
fillTexture();
|
||||
}
|
||||
|
||||
// Comprueba los eventos
|
||||
void HiScoreTable::checkEvents()
|
||||
{
|
||||
// Comprueba los eventos que hay en la cola
|
||||
SDL_Event event;
|
||||
while (SDL_PollEvent(&event))
|
||||
{
|
||||
// Evento de salida de la aplicación
|
||||
if (event.type == SDL_QUIT)
|
||||
{
|
||||
section::name = section::Name::QUIT;
|
||||
section::options = section::Options::QUIT_FROM_EVENT;
|
||||
break;
|
||||
}
|
||||
|
||||
// Comprueba si se ha cambiado el tamaño de la ventana
|
||||
else if (event.type == SDL_WINDOWEVENT)
|
||||
{
|
||||
if (event.window.event == SDL_WINDOWEVENT_SIZE_CHANGED)
|
||||
{
|
||||
reloadTextures();
|
||||
}
|
||||
}
|
||||
|
||||
// Comprueba el cursor
|
||||
Mouse::handleEvent(event);
|
||||
globalEvents::check(event);
|
||||
}
|
||||
}
|
||||
|
||||
// Comprueba las entradas
|
||||
void HiScoreTable::checkInput()
|
||||
{
|
||||
// Comprueba si se ha pulsado cualquier botón (de los usados para jugar)
|
||||
if (Input::get()->checkAnyButtonPressed())
|
||||
{
|
||||
// JA_StopMusic();
|
||||
section::name = section::Name::TITLE;
|
||||
section::options = section::Options::TITLE_1;
|
||||
section::attract_mode = section::AttractMode::TITLE_TO_DEMO;
|
||||
return;
|
||||
}
|
||||
|
||||
// Comprueba los inputs que se pueden introducir en cualquier sección del juego
|
||||
globalInputs::check();
|
||||
}
|
||||
|
||||
@@ -275,3 +203,238 @@ std::string HiScoreTable::format(int number)
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// Crea los sprites con los textos
|
||||
void HiScoreTable::createSprites()
|
||||
{
|
||||
auto header_text = Resource::get()->getText("04b_25_grey");
|
||||
auto entry_text = Resource::get()->getText("smb2");
|
||||
|
||||
// Obtiene el tamaño de la textura
|
||||
int backbuffer_width;
|
||||
int backbuffer_height;
|
||||
SDL_QueryTexture(backbuffer_, nullptr, nullptr, &backbuffer_width, &backbuffer_height);
|
||||
|
||||
constexpr int entry_lenght = 22;
|
||||
constexpr int max_names = 10;
|
||||
const int space_between_header = entry_text->getCharacterSize() * 4;
|
||||
const int space_between_lines = entry_text->getCharacterSize() * 2;
|
||||
const int size = space_between_header + space_between_lines * (max_names - 1) + entry_text->getCharacterSize();
|
||||
const int first_line = (param.game.height - size) / 2;
|
||||
|
||||
// Crea el sprite para el texto de cabecera
|
||||
header_ = std::make_unique<Sprite>(header_text->writeDXToTexture(TEXT_COLOR, lang::getText(42), -2, background_fade_color_.getInverse().lighten(25)));
|
||||
header_->setPosition(param.game.game_area.center_x - (header_->getWidth() / 2), first_line);
|
||||
|
||||
// Crea los sprites para las entradas en la tabla de puntuaciones
|
||||
const int animation = rand() % 4;
|
||||
const std::string sample_line(entry_lenght + 3, ' ');
|
||||
auto sample_entry = std::make_unique<Sprite>(entry_text->writeDXToTexture(TEXT_SHADOW, sample_line, 1, orange_color, 1, shdw_txt_color));
|
||||
const auto entry_width = sample_entry->getWidth();
|
||||
for (int i = 0; i < max_names; ++i)
|
||||
{
|
||||
const auto table_position = format(i + 1) + ". ";
|
||||
const auto score = format(options.game.hi_score_table.at(i).score);
|
||||
const auto num_dots = entry_lenght - options.game.hi_score_table.at(i).name.size() - score.size();
|
||||
const auto one_cc = options.game.hi_score_table.at(i).one_credit_complete ? " }" : "";
|
||||
std::string dots;
|
||||
for (int j = 0; j < (int)num_dots; ++j)
|
||||
{
|
||||
dots = dots + ".";
|
||||
}
|
||||
const auto line = table_position + options.game.hi_score_table.at(i).name + dots + score + one_cc;
|
||||
|
||||
entry_names_.emplace_back(std::make_shared<PathSprite>(entry_text->writeDXToTexture(TEXT_SHADOW, line, 1, orange_color, 1, shdw_txt_color)));
|
||||
const int default_pos_x = (backbuffer_width - entry_width) / 2;
|
||||
const int pos_x = (i < 9) ? default_pos_x : default_pos_x - entry_text->getCharacterSize();
|
||||
const int pos_y = (i * space_between_lines) + first_line + space_between_header;
|
||||
constexpr int steps = 80;
|
||||
switch (animation)
|
||||
{
|
||||
case 0: // Ambos lados alternativamente
|
||||
{
|
||||
if (i % 2 == 0)
|
||||
{
|
||||
entry_names_.back()->addPath(-entry_names_.back()->getWidth(), pos_x, PathType::HORIZONTAL, pos_y, steps, easeOutQuint);
|
||||
entry_names_.back()->setPosition(-entry_names_.back()->getWidth(), 0);
|
||||
}
|
||||
else
|
||||
{
|
||||
entry_names_.back()->addPath(backbuffer_width, pos_x, PathType::HORIZONTAL, pos_y, steps, easeOutQuint);
|
||||
entry_names_.back()->setPosition(backbuffer_width, 0);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case 1: // Entran por la izquierda
|
||||
{
|
||||
entry_names_.back()->addPath(-entry_names_.back()->getWidth(), pos_x, PathType::HORIZONTAL, pos_y, steps, easeOutQuint);
|
||||
entry_names_.back()->setPosition(-entry_names_.back()->getWidth(), 0);
|
||||
break;
|
||||
}
|
||||
|
||||
case 2: // Entran por la derecha
|
||||
{
|
||||
entry_names_.back()->addPath(backbuffer_width, pos_x, PathType::HORIZONTAL, pos_y, steps, easeOutQuint);
|
||||
entry_names_.back()->setPosition(backbuffer_width, 0);
|
||||
break;
|
||||
}
|
||||
|
||||
case 3: // Entran desde la parte inferior
|
||||
{
|
||||
entry_names_.back()->addPath(backbuffer_height, pos_y, PathType::VERTICAL, pos_x, steps, easeOutQuint);
|
||||
entry_names_.back()->setPosition(0, backbuffer_height);
|
||||
}
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Actualiza las posiciones de los sprites de texto
|
||||
void HiScoreTable::updateSprites()
|
||||
{
|
||||
constexpr int init_counter = 190;
|
||||
const int counter_between_entries = 16;
|
||||
if (counter_ >= init_counter)
|
||||
{
|
||||
const int counter2 = counter_ - init_counter;
|
||||
if (counter2 % counter_between_entries == 0)
|
||||
{
|
||||
int index = counter2 / counter_between_entries;
|
||||
if (index < static_cast<int>(entry_names_.size()))
|
||||
{
|
||||
entry_names_.at(index)->enable();
|
||||
}
|
||||
}
|
||||
}
|
||||
for (auto const &entry : entry_names_)
|
||||
{
|
||||
entry->update();
|
||||
}
|
||||
|
||||
glowEntryNames();
|
||||
}
|
||||
|
||||
// Inicializa el fade
|
||||
void HiScoreTable::initFade()
|
||||
{
|
||||
fade_->setColor(fade_color.r, fade_color.g, fade_color.b);
|
||||
fade_->setType(FadeType::RANDOM_SQUARE);
|
||||
fade_->setPostDuration(param.fade.post_duration);
|
||||
fade_->setMode(fade_mode_);
|
||||
fade_->activate();
|
||||
}
|
||||
|
||||
// Inicializa el fondo
|
||||
void HiScoreTable::initBackground()
|
||||
{
|
||||
background_->setPos(param.game.game_area.rect);
|
||||
background_->setCloudsSpeed(-0.1f);
|
||||
|
||||
const int lucky = rand() % 3;
|
||||
switch (lucky)
|
||||
{
|
||||
case 0: // Fondo verde
|
||||
{
|
||||
background_->setGradientNumber(2);
|
||||
background_->setTransition(0.0f);
|
||||
background_->setSunProgression(1.0f);
|
||||
background_->setMoonProgression(0.0f);
|
||||
background_fade_color_ = green_sky_color;
|
||||
break;
|
||||
}
|
||||
|
||||
case 1: // Fondo naranja
|
||||
{
|
||||
background_->setGradientNumber(1);
|
||||
background_->setTransition(0.0f);
|
||||
background_->setSunProgression(0.65f);
|
||||
background_->setMoonProgression(0.0f);
|
||||
background_fade_color_ = pink_sky_color;
|
||||
break;
|
||||
}
|
||||
|
||||
case 2: // Fondo azul
|
||||
{
|
||||
background_->setGradientNumber(0);
|
||||
background_->setTransition(0.0f);
|
||||
background_->setSunProgression(0.0f);
|
||||
background_->setMoonProgression(0.0f);
|
||||
background_fade_color_ = blue_sky_color;
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Obtiene un color del vector de colores de entradas
|
||||
Color HiScoreTable::getEntryColor(int counter_)
|
||||
{
|
||||
int cycle_length = entry_colors_.size() * 2 - 2;
|
||||
size_t n = counter_ % cycle_length;
|
||||
|
||||
size_t index;
|
||||
if (n < entry_colors_.size())
|
||||
{
|
||||
index = n; // Avanza: 0,1,2,3
|
||||
}
|
||||
else
|
||||
{
|
||||
index = 2 * (entry_colors_.size() - 1) - n; // Retrocede: 2,1
|
||||
}
|
||||
|
||||
return entry_colors_[index];
|
||||
}
|
||||
|
||||
// Inicializa los colores de las entradas
|
||||
void HiScoreTable::iniEntryColors()
|
||||
{
|
||||
entry_colors_.clear();
|
||||
entry_colors_.emplace_back(background_fade_color_.getInverse().lighten(75));
|
||||
entry_colors_.emplace_back(background_fade_color_.getInverse().lighten(50));
|
||||
entry_colors_.emplace_back(background_fade_color_.getInverse().lighten(25));
|
||||
entry_colors_.emplace_back(background_fade_color_.getInverse());
|
||||
}
|
||||
|
||||
// Hace brillar los nombres de la tabla de records
|
||||
void HiScoreTable::glowEntryNames()
|
||||
{
|
||||
const Color entry_color = getEntryColor(counter_ / 5);
|
||||
for (const auto &entry_index : options.game.last_hi_score_entry)
|
||||
{
|
||||
if (entry_index != -1)
|
||||
{
|
||||
entry_names_.at(entry_index)->getTexture()->setColor(entry_color);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Gestiona la musica
|
||||
void HiScoreTable::updateMusic()
|
||||
{
|
||||
if ((JA_GetMusicState() == JA_MUSIC_INVALID) || (JA_GetMusicState() == JA_MUSIC_STOPPED))
|
||||
{
|
||||
JA_PlayMusic(Resource::get()->getMusic("title.ogg"));
|
||||
}
|
||||
}
|
||||
|
||||
// Gestiona el contador
|
||||
void HiScoreTable::updateCounter()
|
||||
{
|
||||
counter_++;
|
||||
|
||||
if (counter_ == 150)
|
||||
{
|
||||
background_->setColor(background_fade_color_.darken());
|
||||
background_->setAlpha(96);
|
||||
}
|
||||
|
||||
if (counter_ == COUNTER_END_)
|
||||
{
|
||||
fade_->activate();
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,18 @@
|
||||
#pragma once
|
||||
|
||||
#include <SDL2/SDL_rect.h> // para SDL_Rect
|
||||
#include <SDL2/SDL_render.h> // para SDL_Renderer, SDL_Texture
|
||||
#include <SDL2/SDL_stdinc.h> // para Uint16, Uint32, Uint8
|
||||
#include <memory> // para unique_ptr
|
||||
#include <string> // para string
|
||||
class Background; // lines 8-8
|
||||
class Fade; // lines 9-9
|
||||
class Text; // lines 10-10
|
||||
enum class FadeMode : Uint8; // lines 11-11
|
||||
#include <SDL2/SDL_rect.h> // Para SDL_Rect
|
||||
#include <SDL2/SDL_render.h> // Para SDL_Renderer, SDL_Texture
|
||||
#include <SDL2/SDL_stdinc.h> // Para Uint16, Uint32, Uint8
|
||||
#include <memory> // Para unique_ptr, shared_ptr
|
||||
#include <string> // Para string
|
||||
#include <vector> // Para vector
|
||||
#include "utils.h"
|
||||
class Background; // lines 10-10
|
||||
class Fade; // lines 11-11
|
||||
class PathSprite;
|
||||
class Sprite;
|
||||
enum class FadeMode : Uint8; // lines 13-13
|
||||
struct Path;
|
||||
|
||||
/*
|
||||
Esta clase gestiona un estado del programa. Se encarga de mostrar la tabla con las puntuaciones
|
||||
@@ -33,13 +37,17 @@ private:
|
||||
|
||||
std::unique_ptr<Fade> fade_; // Objeto para renderizar fades
|
||||
std::unique_ptr<Background> background_; // Objeto para dibujar el fondo del juego
|
||||
std::shared_ptr<Text> text_; // Objeto para escribir texto
|
||||
std::unique_ptr<Sprite> header_; // Sprite con la cabecera del texto
|
||||
std::vector<std::shared_ptr<PathSprite>> entry_names_; // Lista con los spritres de cada uno de los nombres de la tabla de records
|
||||
std::vector<Path> paths_; // Vector con los recorridos precalculados
|
||||
|
||||
// Variables
|
||||
Uint16 counter_; // Contador
|
||||
Uint16 counter_ = 0; // Contador
|
||||
Uint32 ticks_; // Contador de ticks para ajustar la velocidad del programa
|
||||
SDL_Rect view_area_; // Parte de la textura que se muestra en pantalla
|
||||
FadeMode fade_mode_; // Modo de fade a utilizar
|
||||
Color background_fade_color_; // Color de atenuación del fondo
|
||||
std::vector<Color> entry_colors_; // Colores para destacar las entradas en la tabla
|
||||
|
||||
// Actualiza las variables
|
||||
void update();
|
||||
@@ -56,15 +64,39 @@ private:
|
||||
// Convierte un entero a un string con separadores de miles
|
||||
std::string format(int number);
|
||||
|
||||
// Crea el contenido de la textura con la lista de puntuaciones
|
||||
// Dibuja los sprites en la textura
|
||||
void fillTexture();
|
||||
|
||||
// Recarga todas las texturas
|
||||
void reloadTextures();
|
||||
|
||||
// Gestiona el fade
|
||||
void updateFade();
|
||||
|
||||
// Crea los sprites con los textos
|
||||
void createSprites();
|
||||
|
||||
// Actualiza las posiciones de los sprites de texto
|
||||
void updateSprites();
|
||||
|
||||
// Inicializa el fade
|
||||
void initFade();
|
||||
|
||||
// Inicializa el fondo
|
||||
void initBackground();
|
||||
|
||||
// Obtiene un color del vector de colores de entradas
|
||||
Color getEntryColor(int counter_);
|
||||
|
||||
// Inicializa los colores de las entradas
|
||||
void iniEntryColors();
|
||||
|
||||
// Hace brillar los nombres de la tabla de records
|
||||
void glowEntryNames();
|
||||
|
||||
// Gestiona la musica
|
||||
void updateMusic();
|
||||
|
||||
// Gestiona el contador
|
||||
void updateCounter();
|
||||
|
||||
public:
|
||||
// Constructor
|
||||
HiScoreTable();
|
||||
|
||||
@@ -9,22 +9,22 @@
|
||||
#include <unordered_map> // Para unordered_map, operator==, _Node_cons...
|
||||
#include <utility> // Para pair
|
||||
|
||||
// [SINGLETON] Hay que definir las variables estáticas, desde el .h sólo la hemos declarado
|
||||
// [SINGLETON]
|
||||
Input *Input::input_ = nullptr;
|
||||
|
||||
// [SINGLETON] Crearemos el objeto input con esta función estática
|
||||
// [SINGLETON] Crearemos el objeto con esta función estática
|
||||
void Input::init(const std::string &game_controller_db_path)
|
||||
{
|
||||
Input::input_ = new Input(game_controller_db_path);
|
||||
}
|
||||
|
||||
// [SINGLETON] Destruiremos el objeto input con esta función estática
|
||||
// [SINGLETON] Destruiremos el objeto con esta función estática
|
||||
void Input::destroy()
|
||||
{
|
||||
delete Input::input_;
|
||||
}
|
||||
|
||||
// [SINGLETON] Con este método obtenemos el objeto input y podemos trabajar con él
|
||||
// [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él
|
||||
Input *Input::get()
|
||||
{
|
||||
return Input::input_;
|
||||
@@ -110,9 +110,11 @@ bool Input::checkInput(InputType input, bool repeat, InputDeviceToUse device, in
|
||||
}
|
||||
|
||||
if (gameControllerFound() && controller_index >= 0 && controller_index < num_gamepads_)
|
||||
{
|
||||
if ((device == InputDeviceToUse::CONTROLLER) || (device == InputDeviceToUse::ANY))
|
||||
{
|
||||
success_controller = checkAxisInput(input, controller_index);
|
||||
success_controller = checkAxisInput(input, controller_index, repeat);
|
||||
|
||||
if (!success_controller)
|
||||
{
|
||||
if (repeat)
|
||||
@@ -144,6 +146,7 @@ bool Input::checkInput(InputType input, bool repeat, InputDeviceToUse device, in
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return (success_keyboard || success_controller);
|
||||
}
|
||||
@@ -379,19 +382,53 @@ InputType Input::to_inputs_e(const std::string &name) const
|
||||
}
|
||||
|
||||
// Comprueba el eje del mando
|
||||
bool Input::checkAxisInput(InputType input, int controller_index) const
|
||||
bool Input::checkAxisInput(InputType input, int controller_index, bool repeat)
|
||||
{
|
||||
// Umbral para considerar el eje como activo
|
||||
const Sint16 threshold = 30000;
|
||||
bool axis_active_now = false;
|
||||
|
||||
switch (input)
|
||||
{
|
||||
case InputType::LEFT:
|
||||
return SDL_GameControllerGetAxis(connected_controllers_[controller_index], SDL_CONTROLLER_AXIS_LEFTX) < -30000;
|
||||
axis_active_now = SDL_GameControllerGetAxis(connected_controllers_[controller_index], SDL_CONTROLLER_AXIS_LEFTX) < -threshold;
|
||||
break;
|
||||
case InputType::RIGHT:
|
||||
return SDL_GameControllerGetAxis(connected_controllers_[controller_index], SDL_CONTROLLER_AXIS_LEFTX) > 30000;
|
||||
axis_active_now = SDL_GameControllerGetAxis(connected_controllers_[controller_index], SDL_CONTROLLER_AXIS_LEFTX) > threshold;
|
||||
break;
|
||||
case InputType::UP:
|
||||
return SDL_GameControllerGetAxis(connected_controllers_[controller_index], SDL_CONTROLLER_AXIS_LEFTY) < -30000;
|
||||
axis_active_now = SDL_GameControllerGetAxis(connected_controllers_[controller_index], SDL_CONTROLLER_AXIS_LEFTY) < -threshold;
|
||||
break;
|
||||
case InputType::DOWN:
|
||||
return SDL_GameControllerGetAxis(connected_controllers_[controller_index], SDL_CONTROLLER_AXIS_LEFTY) > 30000;
|
||||
axis_active_now = SDL_GameControllerGetAxis(connected_controllers_[controller_index], SDL_CONTROLLER_AXIS_LEFTY) > threshold;
|
||||
break;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
|
||||
// Referencia al binding correspondiente
|
||||
auto &binding = controller_bindings_.at(controller_index).at(static_cast<int>(input));
|
||||
|
||||
if (repeat)
|
||||
{
|
||||
// Si se permite repetir, simplemente devolvemos el estado actual
|
||||
return axis_active_now;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Si no se permite repetir, aplicamos la lógica de transición
|
||||
if (axis_active_now && !binding.axis_active)
|
||||
{
|
||||
// Transición de inactivo a activo
|
||||
binding.axis_active = true;
|
||||
return true;
|
||||
}
|
||||
else if (!axis_active_now && binding.axis_active)
|
||||
{
|
||||
// Transición de activo a inactivo
|
||||
binding.axis_active = false;
|
||||
}
|
||||
// Mantener el estado actual
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -38,6 +38,7 @@ enum class InputType : int
|
||||
WINDOW_INC_SIZE,
|
||||
WINDOW_DEC_SIZE,
|
||||
VIDEO_SHADERS,
|
||||
VIDEO_INTEGER_SCALE,
|
||||
RESET,
|
||||
MUTE,
|
||||
CHANGE_LANG,
|
||||
@@ -64,7 +65,7 @@ enum class InputDeviceToUse : int
|
||||
class Input
|
||||
{
|
||||
private:
|
||||
// [SINGLETON] Objeto screen privado para Don Melitón
|
||||
// [SINGLETON] Objeto privado
|
||||
static Input *input_;
|
||||
|
||||
struct KeyBindings
|
||||
@@ -81,10 +82,11 @@ private:
|
||||
{
|
||||
SDL_GameControllerButton button; // GameControllerButton asociado
|
||||
bool active; // Indica si está activo
|
||||
bool axis_active; // Estado del eje
|
||||
|
||||
// Constructor
|
||||
explicit ControllerBindings(SDL_GameControllerButton btn = SDL_CONTROLLER_BUTTON_INVALID, bool act = false)
|
||||
: button(btn), active(act) {}
|
||||
explicit ControllerBindings(SDL_GameControllerButton btn = SDL_CONTROLLER_BUTTON_INVALID, bool act = false, bool axis_act = false)
|
||||
: button(btn), active(act), axis_active(axis_act) {}
|
||||
};
|
||||
|
||||
// Variables
|
||||
@@ -99,7 +101,7 @@ private:
|
||||
std::string game_controller_db_path_; // Ruta al archivo gamecontrollerdb.txt
|
||||
|
||||
// Comprueba el eje del mando
|
||||
bool checkAxisInput(InputType input, int controller_index = 0) const;
|
||||
bool checkAxisInput(InputType input, int controller_index, bool repeat);
|
||||
|
||||
// Constructor
|
||||
explicit Input(const std::string &game_controller_db_path);
|
||||
@@ -108,13 +110,13 @@ private:
|
||||
~Input() = default;
|
||||
|
||||
public:
|
||||
// [SINGLETON] Crearemos el objeto screen con esta función estática
|
||||
// [SINGLETON] Crearemos el objeto con esta función estática
|
||||
static void init(const std::string &game_controller_db_path);
|
||||
|
||||
// [SINGLETON] Destruiremos el objeto screen con esta función estática
|
||||
// [SINGLETON] Destruiremos el objeto con esta función estática
|
||||
static void destroy();
|
||||
|
||||
// [SINGLETON] Con este método obtenemos el objeto screen y podemos trabajar con él
|
||||
// [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él
|
||||
static Input *get();
|
||||
|
||||
// Asigna inputs a teclas
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
#include "instructions.h"
|
||||
#include <SDL2/SDL_blendmode.h> // Para SDL_BLENDMODE_BLEND
|
||||
#include <SDL2/SDL_events.h> // Para SDL_PollEvent, SDL_Event, SDL_QUIT
|
||||
#include <SDL2/SDL_events.h> // Para SDL_PollEvent, SDL_Event
|
||||
#include <SDL2/SDL_pixels.h> // Para SDL_PIXELFORMAT_RGBA8888
|
||||
#include <SDL2/SDL_timer.h> // Para SDL_GetTicks
|
||||
#include <SDL2/SDL_video.h> // Para SDL_WINDOWEVENT_SIZE_CHANGED
|
||||
#include <algorithm> // Para max
|
||||
#include <utility> // Para move
|
||||
#include <vector> // Para vector
|
||||
#include "fade.h" // Para Fade, FadeMode, FadeType
|
||||
#include "global_inputs.h" // Para check
|
||||
#include "input.h" // Para Input
|
||||
#include "global_events.h" // Para check
|
||||
#include "global_inputs.h" // Para check, update
|
||||
#include "jail_audio.h" // Para JA_GetMusicState, JA_Music_state
|
||||
#include "lang.h" // Para getText
|
||||
#include "param.h" // Para Param, param, ParamGame, ParamFade
|
||||
@@ -17,10 +17,8 @@
|
||||
#include "section.h" // Para Name, name, Options, options
|
||||
#include "sprite.h" // Para Sprite
|
||||
#include "text.h" // Para Text, TEXT_CENTER, TEXT_COLOR, TEXT_...
|
||||
#include "texture.h" // Para Texture
|
||||
#include "tiled_bg.h" // Para TiledBG, TiledBGMode
|
||||
#include "utils.h" // Para Color, shdw_txt_color, Zone, no_color
|
||||
#include "mouse.h"
|
||||
|
||||
// Constructor
|
||||
Instructions::Instructions()
|
||||
@@ -46,6 +44,9 @@ Instructions::Instructions()
|
||||
fade_->setMode(FadeMode::IN);
|
||||
fade_->activate();
|
||||
|
||||
// Inicializa las líneas con un retraso progresivo de 50 ms
|
||||
lines_ = initializeLines(256);
|
||||
|
||||
// Rellena la textura de texto
|
||||
fillTexture();
|
||||
|
||||
@@ -159,7 +160,6 @@ void Instructions::fillTexture()
|
||||
text_->writeDX(TEXT_CENTER | TEXT_COLOR | TEXT_SHADOW, param.game.game_area.center_x, anchor2, lang::getText(16), 1, orange_color, 1, shdw_txt_color);
|
||||
|
||||
const int anchor3 = anchor2 + space_post_header;
|
||||
// const int anchor4 = anchor3 + ((param.game.item_size + text->getCharacterSize()) / 2);
|
||||
text_->writeShadowed(anchor_item + desp_x, anchor3 + space_between_item_lines * 0, lang::getText(17), shdw_txt_color);
|
||||
text_->writeShadowed(anchor_item + desp_x, anchor3 + space_between_item_lines * 1, lang::getText(18), shdw_txt_color);
|
||||
text_->writeShadowed(anchor_item + desp_x, anchor3 + space_between_item_lines * 2, lang::getText(19), shdw_txt_color);
|
||||
@@ -201,18 +201,13 @@ void Instructions::fillBackbuffer()
|
||||
// Actualiza las variables
|
||||
void Instructions::update()
|
||||
{
|
||||
constexpr int TICKS_SPEED = 15;
|
||||
|
||||
if (SDL_GetTicks() - ticks_ > TICKS_SPEED)
|
||||
if (SDL_GetTicks() - ticks_ > param.game.speed)
|
||||
{
|
||||
// Actualiza el contador de ticks
|
||||
ticks_ = SDL_GetTicks();
|
||||
|
||||
// Mantiene la música sonando
|
||||
if ((JA_GetMusicState() == JA_MUSIC_INVALID) || (JA_GetMusicState() == JA_MUSIC_STOPPED))
|
||||
{
|
||||
JA_PlayMusic(Resource::get()->getMusic("title.ogg"));
|
||||
}
|
||||
updateMusic();
|
||||
|
||||
// Actualiza el objeto screen
|
||||
Screen::get()->update();
|
||||
@@ -226,27 +221,23 @@ void Instructions::update()
|
||||
// Actualiza los sprites
|
||||
updateSprites();
|
||||
|
||||
// Gestiona la textura con los graficos
|
||||
updateBackbuffer();
|
||||
|
||||
// Actualiza el mosaico de fondo
|
||||
tiled_bg_->update();
|
||||
|
||||
// Actualiza el objeto "fade"
|
||||
fade_->update();
|
||||
|
||||
// Comprueba si el contador ha llegado al final
|
||||
if (counter_ == counter_end_)
|
||||
{
|
||||
section::name = section::Name::TITLE;
|
||||
section::options = section::Options::TITLE_1;
|
||||
}
|
||||
// Rellena el backbuffer
|
||||
fillBackbuffer();
|
||||
}
|
||||
}
|
||||
|
||||
// Pinta en pantalla
|
||||
void Instructions::render()
|
||||
{
|
||||
// Rellena el backbuffer
|
||||
fillBackbuffer();
|
||||
|
||||
// Prepara para empezar a dibujar en la textura de juego
|
||||
Screen::get()->start();
|
||||
|
||||
@@ -256,10 +247,10 @@ void Instructions::render()
|
||||
// Dibuja el mosacico de fondo
|
||||
tiled_bg_->render();
|
||||
|
||||
// Establece la ventana del backbuffer
|
||||
view_.y = std::max(0, param.game.height - counter_ + 100);
|
||||
|
||||
// Copia la textura y el backbuffer al renderizador
|
||||
if (view_.y == 0)
|
||||
renderLines(renderer_, backbuffer_, lines_);
|
||||
else
|
||||
SDL_RenderCopy(renderer_, backbuffer_, nullptr, &view_);
|
||||
|
||||
fade_->render();
|
||||
@@ -268,60 +259,19 @@ void Instructions::render()
|
||||
Screen::get()->render();
|
||||
}
|
||||
|
||||
// Recarga todas las texturas
|
||||
void Instructions::reloadTextures()
|
||||
{
|
||||
for (auto &texture : item_textures_)
|
||||
{
|
||||
texture->reLoad();
|
||||
}
|
||||
text_->reLoadTexture();
|
||||
fillTexture();
|
||||
}
|
||||
|
||||
// Comprueba los eventos
|
||||
void Instructions::checkEvents()
|
||||
{
|
||||
// Comprueba los eventos que hay en la cola
|
||||
SDL_Event event;
|
||||
while (SDL_PollEvent(&event))
|
||||
{
|
||||
// Evento de salida de la aplicación
|
||||
if (event.type == SDL_QUIT)
|
||||
{
|
||||
section::name = section::Name::QUIT;
|
||||
section::options = section::Options::QUIT_FROM_EVENT;
|
||||
break;
|
||||
}
|
||||
|
||||
// Comprueba si se ha cambiado el tamaño de la ventana
|
||||
else if (event.type == SDL_WINDOWEVENT)
|
||||
{
|
||||
if (event.window.event == SDL_WINDOWEVENT_SIZE_CHANGED)
|
||||
{
|
||||
reloadTextures();
|
||||
}
|
||||
}
|
||||
|
||||
// Comprueba el cursor
|
||||
Mouse::handleEvent(event);
|
||||
globalEvents::check(event);
|
||||
}
|
||||
}
|
||||
|
||||
// Comprueba las entradas
|
||||
void Instructions::checkInput()
|
||||
{
|
||||
// Comprueba si se ha pulsado cualquier botón (de los usados para jugar)
|
||||
if (Input::get()->checkAnyButtonPressed())
|
||||
{
|
||||
// JA_StopMusic();
|
||||
section::name = section::Name::TITLE;
|
||||
section::options = section::Options::TITLE_1;
|
||||
section::attract_mode = section::AttractMode::TITLE_TO_DEMO;
|
||||
return;
|
||||
}
|
||||
|
||||
// Comprueba los inputs que se pueden introducir en cualquier sección del juego
|
||||
globalInputs::check();
|
||||
}
|
||||
|
||||
@@ -336,3 +286,99 @@ void Instructions::run()
|
||||
render();
|
||||
}
|
||||
}
|
||||
|
||||
// Método para inicializar las líneas
|
||||
std::vector<Line> Instructions::initializeLines(int height)
|
||||
{
|
||||
std::vector<Line> lines;
|
||||
for (int y = 0; y < height; y++)
|
||||
{
|
||||
int direction = (y % 2 == 0) ? -1 : 1; // Pares a la izquierda, impares a la derecha
|
||||
lines.emplace_back(y, 0.0f, direction);
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
// Método para mover las líneas con suavizado
|
||||
bool Instructions::moveLines(std::vector<Line> &lines, int width, float duration, Uint32 startDelay)
|
||||
{
|
||||
Uint32 currentTime = SDL_GetTicks();
|
||||
bool allLinesOffScreen = true;
|
||||
|
||||
for (auto &line : lines)
|
||||
{
|
||||
// Establecer startTime en el primer cuadro de animación
|
||||
if (line.startTime == 0)
|
||||
{
|
||||
line.startTime = currentTime + line.y * startDelay;
|
||||
}
|
||||
|
||||
float elapsedTime = (currentTime - line.startTime) / 1000.0f; // Convertir a segundos
|
||||
if (elapsedTime < 0)
|
||||
{
|
||||
allLinesOffScreen = false; // Si aún no se debe mover esta línea, no están todas fuera de pantalla
|
||||
continue;
|
||||
}
|
||||
if (elapsedTime >= duration)
|
||||
{
|
||||
continue; // Si la línea ha salido de los límites, no la muevas más
|
||||
}
|
||||
|
||||
float t = elapsedTime / duration;
|
||||
float smoothFactor = easeInOutQuint(t);
|
||||
line.x = line.direction * smoothFactor * width;
|
||||
allLinesOffScreen = false; // Si alguna línea aún se está moviendo, no están todas fuera de pantalla
|
||||
}
|
||||
|
||||
return allLinesOffScreen;
|
||||
}
|
||||
|
||||
// Método para renderizar las líneas
|
||||
void Instructions::renderLines(SDL_Renderer *renderer, SDL_Texture *texture, const std::vector<Line> &lines)
|
||||
{
|
||||
for (const auto &line : lines)
|
||||
{
|
||||
SDL_Rect srcRect = {0, line.y, 320, 1};
|
||||
SDL_Rect dstRect = {static_cast<int>(line.x), line.y, 320, 1};
|
||||
SDL_RenderCopy(renderer, texture, &srcRect, &dstRect);
|
||||
}
|
||||
}
|
||||
|
||||
// Gestiona la musica
|
||||
void Instructions::updateMusic()
|
||||
{
|
||||
if ((JA_GetMusicState() == JA_MUSIC_INVALID) || (JA_GetMusicState() == JA_MUSIC_STOPPED))
|
||||
{
|
||||
JA_PlayMusic(Resource::get()->getMusic("title.ogg"));
|
||||
}
|
||||
}
|
||||
|
||||
// Gestiona la textura con los graficos
|
||||
void Instructions::updateBackbuffer()
|
||||
{
|
||||
// Establece la ventana del backbuffer
|
||||
view_.y = std::max(0, param.game.height - counter_ + 100);
|
||||
|
||||
// Verifica si view_.y == 0 y gestiona el temporizador
|
||||
if (view_.y == 0)
|
||||
{
|
||||
if (!start_delay_triggered_)
|
||||
{
|
||||
// Activa el temporizador si no ha sido activado
|
||||
start_delay_triggered_ = true;
|
||||
start_delay_time_ = SDL_GetTicks();
|
||||
}
|
||||
else if (SDL_GetTicks() - start_delay_time_ >= 4000)
|
||||
{
|
||||
// Han pasado tres segundos, mover líneas
|
||||
all_lines_off_screen_ = moveLines(lines_, 320, 1.0f, 5);
|
||||
}
|
||||
}
|
||||
|
||||
// Comprueba si el contador ha llegado al final
|
||||
if (all_lines_off_screen_)
|
||||
{
|
||||
section::name = section::Name::TITLE;
|
||||
section::options = section::Options::TITLE_1;
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,19 @@ class TiledBG; // lines 12-12
|
||||
por la pantalla sobre el mosaico de fondo (gestionado por el correspondiente objeto)
|
||||
*/
|
||||
|
||||
// Estructura para almacenar información de línea
|
||||
struct Line
|
||||
{
|
||||
int y; // Coordenada Y de la línea
|
||||
float x; // Coordenada X inicial (usamos float para mayor precisión en el suavizado)
|
||||
int direction; // Dirección de movimiento: -1 para izquierda, 1 para derecha
|
||||
Uint32 startTime; // Tiempo de inicio del movimiento
|
||||
|
||||
// Constructor de Line
|
||||
Line(int y, float x, int direction)
|
||||
: y(y), x(x), direction(direction), startTime(0) {}
|
||||
};
|
||||
|
||||
// Clase Instructions
|
||||
class Instructions
|
||||
{
|
||||
@@ -40,12 +53,15 @@ private:
|
||||
std::unique_ptr<Fade> fade_; // Objeto para renderizar fades
|
||||
|
||||
// Variables
|
||||
int counter_ = 0; // Contador
|
||||
int counter_end_ = 700; // Valor final para el contador
|
||||
int counter_ = 0; // Contador para manejar el progreso en la pantalla de instrucciones
|
||||
Uint32 ticks_ = 0; // Contador de ticks para ajustar la velocidad del programa
|
||||
SDL_Rect view_; // Vista del backbuffer que se va a mostrar por pantalla
|
||||
SDL_Point sprite_pos_ = {0, 0}; // Posición del primer sprite
|
||||
int item_space_ = 2; // Espacio entre los items
|
||||
SDL_Point sprite_pos_ = {0, 0}; // Posición del primer sprite en la lista
|
||||
int item_space_ = 2; // Espacio entre los items en pantalla
|
||||
std::vector<Line> lines_; // Vector que contiene las líneas animadas en la pantalla
|
||||
bool all_lines_off_screen_ = false; // Indica si todas las líneas han salido de la pantalla
|
||||
Uint32 start_delay_time_ = 0; // Tiempo de inicio del retraso para mover las líneas
|
||||
bool start_delay_triggered_ = false; // Bandera para determinar si el retraso ha comenzado
|
||||
|
||||
// Actualiza las variables
|
||||
void update();
|
||||
@@ -71,8 +87,20 @@ private:
|
||||
// Actualiza los sprites
|
||||
void updateSprites();
|
||||
|
||||
// Recarga todas las texturas
|
||||
void reloadTextures();
|
||||
// Método para inicializar las líneas
|
||||
std::vector<Line> initializeLines(int height);
|
||||
|
||||
// Método para mover las líneas
|
||||
bool moveLines(std::vector<Line> &lines, int width, float duration, Uint32 startDelay);
|
||||
|
||||
// Método para renderizar las líneas
|
||||
void renderLines(SDL_Renderer *renderer, SDL_Texture *texture, const std::vector<Line> &lines);
|
||||
|
||||
// Gestiona la musica
|
||||
void updateMusic();
|
||||
|
||||
// Gestiona la textura con los graficos
|
||||
void updateBackbuffer();
|
||||
|
||||
public:
|
||||
// Constructor
|
||||
|
||||
651
source/intro.cpp
@@ -1,243 +1,117 @@
|
||||
#include "intro.h"
|
||||
#include <SDL2/SDL_events.h> // Para SDL_PollEvent, SDL_Event, SDL_QUIT, SDL...
|
||||
#include <SDL2/SDL_blendmode.h> // Para SDL_BLENDMODE_BLEND, SDL_BLENDMODE_MOD
|
||||
#include <SDL2/SDL_events.h> // Para SDL_PollEvent, SDL_Event
|
||||
#include <SDL2/SDL_pixels.h> // Para SDL_PIXELFORMAT_RGBA8888
|
||||
#include <SDL2/SDL_rect.h> // Para SDL_Rect
|
||||
#include <SDL2/SDL_render.h> // Para SDL_SetTextureBlendMode, SDL_GetRend...
|
||||
#include <SDL2/SDL_timer.h> // Para SDL_GetTicks
|
||||
#include <SDL2/SDL_video.h> // Para SDL_WINDOWEVENT_SIZE_CHANGED
|
||||
#include <array> // Para array
|
||||
#include <functional> // Para function
|
||||
#include <string> // Para basic_string, string
|
||||
#include <utility> // Para move
|
||||
#include "global_inputs.h" // Para check
|
||||
#include "input.h" // Para Input
|
||||
#include "jail_audio.h" // Para JA_StopMusic, JA_PlayMusic
|
||||
#include "global_events.h" // Para check
|
||||
#include "global_inputs.h" // Para check, update
|
||||
#include "jail_audio.h" // Para JA_PlayMusic, JA_StopMusic
|
||||
#include "lang.h" // Para getText
|
||||
#include "param.h" // Para Param, ParamGame, param
|
||||
#include "path_sprite.h" // Para PathSprite, PathType
|
||||
#include "resource.h" // Para Resource
|
||||
#include "screen.h" // Para Screen
|
||||
#include "section.h" // Para Name, name, Options, options
|
||||
#include "smart_sprite.h" // Para SmartSprite
|
||||
#include "text.h" // Para Text
|
||||
#include "texture.h" // Para Texture
|
||||
#include "utils.h" // Para Zone, BLOCK, Color, bg_color
|
||||
#include "tiled_bg.h" // Para TiledBG, TiledBGMode
|
||||
#include "utils.h" // Para Color, Zone, easeOutQuint, BLOCK
|
||||
#include "writer.h" // Para Writer
|
||||
#include "mouse.h"
|
||||
|
||||
// Constructor
|
||||
Intro::Intro()
|
||||
: texture_(Resource::get()->getTexture("intro.png")),
|
||||
text_(Resource::get()->getText("nokia"))
|
||||
: tiled_bg_(std::make_unique<TiledBG>(param.game.game_area.rect, TiledBGMode::DIAGONAL))
|
||||
{
|
||||
|
||||
// Inicializa variables
|
||||
section::name = section::Name::INTRO;
|
||||
section::options = section::Options::NONE;
|
||||
|
||||
// Inicializa los bitmaps de la intro
|
||||
constexpr int totalBitmaps = 6;
|
||||
for (int i = 0; i < totalBitmaps; ++i)
|
||||
{
|
||||
auto ss = std::make_unique<SmartSprite>(texture_);
|
||||
ss->setWidth(128);
|
||||
ss->setHeight(96);
|
||||
ss->setFinishedCounter(20);
|
||||
ss->setDestX(param.game.game_area.center_x - 64);
|
||||
ss->setDestY(param.game.game_area.first_quarter_y - 24);
|
||||
bitmaps_.push_back(std::move(ss));
|
||||
}
|
||||
// Inicializa las imagens
|
||||
initSprites();
|
||||
|
||||
bitmaps_[0]->setPosX(-128);
|
||||
bitmaps_[0]->setPosY(param.game.game_area.first_quarter_y - 24);
|
||||
bitmaps_[0]->setVelX(0.0f);
|
||||
bitmaps_[0]->setVelY(0.0f);
|
||||
bitmaps_[0]->setAccelX(0.6f);
|
||||
bitmaps_[0]->setAccelY(0.0f);
|
||||
bitmaps_[0]->setSpriteClip(0, 0, 128, 96);
|
||||
// Inicializa los textos
|
||||
initTexts();
|
||||
|
||||
bitmaps_[1]->setPosX(param.game.width);
|
||||
bitmaps_[1]->setPosY(param.game.game_area.first_quarter_y - 24);
|
||||
bitmaps_[1]->setVelX(-1.0f);
|
||||
bitmaps_[1]->setVelY(0.0f);
|
||||
bitmaps_[1]->setAccelX(-0.3f);
|
||||
bitmaps_[1]->setAccelY(0.0f);
|
||||
bitmaps_[1]->setSpriteClip(128, 0, 128, 96);
|
||||
|
||||
bitmaps_[2]->setPosX(param.game.game_area.center_x - 64);
|
||||
bitmaps_[2]->setPosY(-96);
|
||||
bitmaps_[2]->setVelX(0.0f);
|
||||
bitmaps_[2]->setVelY(3.0f);
|
||||
bitmaps_[2]->setAccelX(0.1f);
|
||||
bitmaps_[2]->setAccelY(0.3f);
|
||||
bitmaps_[2]->setSpriteClip(0, 96, 128, 96);
|
||||
bitmaps_[2]->setFinishedCounter(250);
|
||||
|
||||
bitmaps_[3]->setPosX(param.game.game_area.center_x - 64);
|
||||
bitmaps_[3]->setPosY(param.game.height);
|
||||
bitmaps_[3]->setVelX(0.0f);
|
||||
bitmaps_[3]->setVelY(-0.7f);
|
||||
bitmaps_[3]->setAccelX(0.0f);
|
||||
bitmaps_[3]->setAccelY(0.0f);
|
||||
bitmaps_[3]->setSpriteClip(128, 96, 128, 96);
|
||||
|
||||
bitmaps_[4]->setPosX(param.game.game_area.center_x - 64);
|
||||
bitmaps_[4]->setPosY(-96);
|
||||
bitmaps_[4]->setVelX(0.0f);
|
||||
bitmaps_[4]->setVelY(3.0f);
|
||||
bitmaps_[4]->setAccelX(0.1f);
|
||||
bitmaps_[4]->setAccelY(0.3f);
|
||||
bitmaps_[4]->setSpriteClip(0, 192, 128, 96);
|
||||
|
||||
bitmaps_[5]->setPosX(param.game.width);
|
||||
bitmaps_[5]->setPosY(param.game.game_area.first_quarter_y - 24);
|
||||
bitmaps_[5]->setVelX(-0.7f);
|
||||
bitmaps_[5]->setVelY(0.0f);
|
||||
bitmaps_[5]->setAccelX(0.0f);
|
||||
bitmaps_[5]->setAccelY(0.0f);
|
||||
bitmaps_[5]->setSpriteClip(128, 192, 128, 96);
|
||||
|
||||
// Inicializa los textos de la intro
|
||||
constexpr int totalTexts = 9;
|
||||
for (int i = 0; i < totalTexts; ++i)
|
||||
{
|
||||
auto w = std::make_unique<Writer>(text_);
|
||||
w->setPosX(BLOCK * 0);
|
||||
w->setPosY(param.game.height - (BLOCK * 6));
|
||||
w->setKerning(-1);
|
||||
w->setEnabled(false);
|
||||
w->setFinishedCounter(180);
|
||||
texts_.push_back(std::move(w));
|
||||
}
|
||||
|
||||
// Un dia qualsevol de l'any 2000
|
||||
texts_[0]->setCaption(lang::getText(27));
|
||||
texts_[0]->setSpeed(8);
|
||||
|
||||
// Tot esta tranquil a la UPV
|
||||
texts_[1]->setCaption(lang::getText(28));
|
||||
texts_[1]->setSpeed(8);
|
||||
|
||||
// Fins que un desaprensiu...
|
||||
texts_[2]->setCaption(lang::getText(29));
|
||||
texts_[2]->setSpeed(12);
|
||||
|
||||
// HEY! ME ANE A FERME UN CORTAET...
|
||||
texts_[3]->setCaption(lang::getText(30));
|
||||
texts_[3]->setSpeed(8);
|
||||
|
||||
// UAAAAAAAAAAAAA!!!
|
||||
texts_[4]->setCaption(lang::getText(31));
|
||||
texts_[4]->setSpeed(1);
|
||||
|
||||
// Espera un moment...
|
||||
texts_[5]->setCaption(lang::getText(32));
|
||||
texts_[5]->setSpeed(16);
|
||||
|
||||
// Si resulta que no tinc solt!
|
||||
texts_[6]->setCaption(lang::getText(33));
|
||||
texts_[6]->setSpeed(2);
|
||||
|
||||
// MERDA DE MAQUINA!
|
||||
texts_[7]->setCaption(lang::getText(34));
|
||||
texts_[7]->setSpeed(3);
|
||||
|
||||
// Blop... blop... blop...
|
||||
texts_[8]->setCaption(lang::getText(35));
|
||||
texts_[8]->setSpeed(16);
|
||||
|
||||
for (auto &text : texts_)
|
||||
text->center(param.game.game_area.center_x);
|
||||
}
|
||||
|
||||
// Recarga todas las texturas
|
||||
void Intro::reloadTextures()
|
||||
{
|
||||
texture_->reLoad();
|
||||
text_->reLoadTexture();
|
||||
// Configura el fondo
|
||||
tiled_bg_->setSpeed(0.3f);
|
||||
tiled_bg_->setColor(Color(bg_color_, bg_color_, bg_color_));
|
||||
}
|
||||
|
||||
// Comprueba los eventos
|
||||
void Intro::checkEvents()
|
||||
{
|
||||
SDL_Event event;
|
||||
|
||||
// Comprueba los eventos que hay en la cola
|
||||
while (SDL_PollEvent(&event))
|
||||
{
|
||||
switch (event.type)
|
||||
{
|
||||
case SDL_QUIT:
|
||||
{
|
||||
section::name = section::Name::QUIT;
|
||||
section::options = section::Options::QUIT_FROM_EVENT;
|
||||
break;
|
||||
}
|
||||
|
||||
case SDL_WINDOWEVENT:
|
||||
{
|
||||
if (event.window.event == SDL_WINDOWEVENT_SIZE_CHANGED)
|
||||
{
|
||||
reloadTextures();
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
// Comprueba el cursor
|
||||
Mouse::handleEvent(event);
|
||||
globalEvents::check(event);
|
||||
}
|
||||
}
|
||||
|
||||
// Comprueba las entradas
|
||||
void Intro::checkInput()
|
||||
{
|
||||
// Comprueba si se ha pulsado cualquier botón (de los usados para jugar)
|
||||
if (Input::get()->checkAnyButtonPressed())
|
||||
{
|
||||
JA_StopMusic();
|
||||
section::name = section::Name::TITLE;
|
||||
section::options = section::Options::TITLE_1;
|
||||
return;
|
||||
}
|
||||
|
||||
// Comprueba los inputs que se pueden introducir en cualquier sección del juego
|
||||
globalInputs::check();
|
||||
}
|
||||
void Intro::checkInput() { globalInputs::check(); }
|
||||
|
||||
// Actualiza las escenas de la intro
|
||||
void Intro::updateScenes()
|
||||
{
|
||||
switch (scene_)
|
||||
{
|
||||
case 1:
|
||||
{ // Primera imagen - UPV
|
||||
if (!bitmaps_[0]->hasFinished())
|
||||
case 0:
|
||||
{
|
||||
bitmaps_[0]->setEnabled(true);
|
||||
}
|
||||
// Primera imagen - UPV
|
||||
sprites_.at(0)->enable();
|
||||
shadow_sprites_.at(0)->enable();
|
||||
|
||||
// Primer texto de la primera imagen
|
||||
if (bitmaps_[0]->hasFinished() && !texts_[0]->hasFinished())
|
||||
if (sprites_.at(0)->hasFinished() && !texts_.at(0)->hasFinished())
|
||||
{
|
||||
texts_[0]->setEnabled(true);
|
||||
texts_.at(0)->setEnabled(true);
|
||||
}
|
||||
|
||||
// Segundo texto de la primera imagen
|
||||
if (texts_[0]->hasFinished() && !texts_[1]->hasFinished())
|
||||
if (texts_.at(0)->hasFinished() && !texts_.at(1)->hasFinished())
|
||||
{
|
||||
texts_[0]->setEnabled(false);
|
||||
texts_[1]->setEnabled(true);
|
||||
texts_.at(0)->setEnabled(false);
|
||||
texts_.at(1)->setEnabled(true);
|
||||
}
|
||||
|
||||
// Tercer texto de la primera imagen
|
||||
if (texts_[1]->hasFinished() && !texts_[2]->hasFinished())
|
||||
if (texts_.at(1)->hasFinished() && !texts_.at(2)->hasFinished())
|
||||
{
|
||||
texts_[1]->setEnabled(false);
|
||||
texts_[2]->setEnabled(true);
|
||||
texts_.at(1)->setEnabled(false);
|
||||
texts_.at(2)->setEnabled(true);
|
||||
}
|
||||
|
||||
// Fin de la primera escena
|
||||
if (texts_[2]->hasFinished())
|
||||
if (texts_.at(2)->hasFinished())
|
||||
{
|
||||
bitmaps_[0]->setEnabled(false);
|
||||
texts_[2]->setEnabled(false);
|
||||
texts_.at(2)->setEnabled(false);
|
||||
scene_++;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
case 1:
|
||||
{
|
||||
// Segunda imagen - Máquina
|
||||
sprites_.at(1)->enable();
|
||||
shadow_sprites_.at(1)->enable();
|
||||
|
||||
// Primer texto de la segunda imagen
|
||||
if (sprites_.at(1)->hasFinished() && !texts_.at(3)->hasFinished())
|
||||
{
|
||||
texts_.at(3)->setEnabled(true);
|
||||
}
|
||||
|
||||
// Fin de la segunda escena
|
||||
if (texts_.at(3)->hasFinished())
|
||||
{
|
||||
texts_.at(3)->setEnabled(false);
|
||||
scene_++;
|
||||
}
|
||||
|
||||
@@ -245,41 +119,48 @@ void Intro::updateScenes()
|
||||
}
|
||||
|
||||
case 2:
|
||||
{ // Segunda imagen - Máquina
|
||||
if (!bitmaps_[1]->hasFinished())
|
||||
{
|
||||
bitmaps_[1]->setEnabled(true);
|
||||
// Tercera imagen junto con primer texto - GRITO
|
||||
if (!texts_.at(4)->hasFinished())
|
||||
{
|
||||
sprites_.at(2)->enable();
|
||||
shadow_sprites_.at(2)->enable();
|
||||
|
||||
texts_.at(4)->setEnabled(true);
|
||||
}
|
||||
|
||||
// Primer texto de la segunda imagen
|
||||
if (bitmaps_[1]->hasFinished() && !texts_[3]->hasFinished())
|
||||
// Fin de la tercera escena
|
||||
if (sprites_.at(2)->hasFinished() && texts_.at(4)->hasFinished())
|
||||
{
|
||||
texts_[3]->setEnabled(true);
|
||||
}
|
||||
|
||||
// Fin de la segunda escena
|
||||
if (texts_[3]->hasFinished())
|
||||
{
|
||||
bitmaps_[1]->setEnabled(false);
|
||||
texts_[3]->setEnabled(false);
|
||||
texts_.at(4)->setEnabled(false);
|
||||
scene_++;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
case 3:
|
||||
{ // Tercera imagen junto con primer texto - GRITO
|
||||
if (!bitmaps_[2]->hasFinished() && !texts_[4]->hasFinished())
|
||||
{
|
||||
bitmaps_[2]->setEnabled(true);
|
||||
texts_[4]->setEnabled(true);
|
||||
// Cuarta imagen junto con primer texto - Reflexión
|
||||
sprites_.at(3)->enable();
|
||||
shadow_sprites_.at(3)->enable();
|
||||
|
||||
if (!texts_.at(5)->hasFinished())
|
||||
{
|
||||
texts_.at(5)->setEnabled(true);
|
||||
}
|
||||
|
||||
// Fin de la tercera escena
|
||||
if (bitmaps_[2]->hasFinished() && texts_[4]->hasFinished())
|
||||
// Segundo texto de la cuarta imagen
|
||||
if (texts_.at(5)->hasFinished() && !texts_.at(6)->hasFinished())
|
||||
{
|
||||
bitmaps_[2]->setEnabled(false);
|
||||
texts_[4]->setEnabled(false);
|
||||
texts_.at(5)->setEnabled(false);
|
||||
texts_.at(6)->setEnabled(true);
|
||||
}
|
||||
|
||||
// Fin de la cuarta escena
|
||||
if (sprites_.at(3)->hasFinished() && texts_.at(6)->hasFinished())
|
||||
{
|
||||
texts_.at(6)->setEnabled(false);
|
||||
scene_++;
|
||||
}
|
||||
|
||||
@@ -287,25 +168,21 @@ void Intro::updateScenes()
|
||||
}
|
||||
|
||||
case 4:
|
||||
{ // Cuarta imagen junto con primer texto - Reflexión
|
||||
if (!bitmaps_[3]->hasFinished() && !texts_[5]->hasFinished())
|
||||
{
|
||||
bitmaps_[3]->setEnabled(true);
|
||||
texts_[5]->setEnabled(true);
|
||||
// Quinta imagen - Patada
|
||||
sprites_.at(4)->enable();
|
||||
shadow_sprites_.at(4)->enable();
|
||||
|
||||
// Primer texto de la quinta imagen
|
||||
if (!texts_.at(7)->hasFinished())
|
||||
{
|
||||
texts_.at(7)->setEnabled(true);
|
||||
}
|
||||
|
||||
// Segundo texto de la cuarta imagen
|
||||
if (texts_[5]->hasFinished() && !texts_[6]->hasFinished())
|
||||
// Fin de la quinta escena
|
||||
if (sprites_.at(4)->hasFinished() && texts_.at(7)->hasFinished())
|
||||
{
|
||||
texts_[5]->setEnabled(false);
|
||||
texts_[6]->setEnabled(true);
|
||||
}
|
||||
|
||||
// Fin de la cuarta escena
|
||||
if (bitmaps_[3]->hasFinished() && texts_[6]->hasFinished())
|
||||
{
|
||||
bitmaps_[3]->setEnabled(false);
|
||||
texts_[6]->setEnabled(false);
|
||||
texts_.at(7)->setEnabled(false);
|
||||
scene_++;
|
||||
}
|
||||
|
||||
@@ -313,45 +190,27 @@ void Intro::updateScenes()
|
||||
}
|
||||
|
||||
case 5:
|
||||
{ // Quinta imagen - Patada
|
||||
if (!bitmaps_[4]->hasFinished())
|
||||
{
|
||||
bitmaps_[4]->setEnabled(true);
|
||||
}
|
||||
// Sexta imagen junto con texto - Globos de café
|
||||
sprites_.at(5)->enable();
|
||||
shadow_sprites_.at(5)->enable();
|
||||
|
||||
// Primer texto de la quinta imagen
|
||||
if (bitmaps_[4]->hasFinished() && !texts_[7]->hasFinished())
|
||||
if (!texts_.at(8)->hasFinished())
|
||||
{
|
||||
texts_[7]->setEnabled(true);
|
||||
}
|
||||
|
||||
// Fin de la quinta escena
|
||||
if (bitmaps_[4]->hasFinished() && texts_[7]->hasFinished())
|
||||
{
|
||||
bitmaps_[4]->setEnabled(false);
|
||||
texts_[7]->setEnabled(false);
|
||||
scene_++;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
case 6:
|
||||
{ // Sexta imagen junto con texto - Globos de café
|
||||
if (!bitmaps_[5]->hasFinished() && !texts_[8]->hasFinished())
|
||||
{
|
||||
bitmaps_[5]->setEnabled(true);
|
||||
texts_[8]->setEnabled(true);
|
||||
texts_.at(8)->setEnabled(true);
|
||||
}
|
||||
|
||||
// Acaba el último texto
|
||||
if (bitmaps_[5]->hasFinished() && texts_[8]->hasFinished())
|
||||
if (texts_.at(8)->hasFinished())
|
||||
{
|
||||
bitmaps_[5]->setEnabled(false);
|
||||
texts_[8]->setEnabled(false);
|
||||
JA_StopMusic();
|
||||
section::name = section::Name::TITLE;
|
||||
section::options = section::Options::TITLE_1;
|
||||
texts_.at(8)->setEnabled(false);
|
||||
}
|
||||
|
||||
// Acaba la ultima imagen
|
||||
if (sprites_.at(5)->hasFinished() && texts_.at(8)->hasFinished())
|
||||
{
|
||||
state_ = IntroState::POST;
|
||||
state_start_time_ = SDL_GetTicks();
|
||||
}
|
||||
|
||||
break;
|
||||
@@ -365,30 +224,30 @@ void Intro::updateScenes()
|
||||
// Actualiza las variables del objeto
|
||||
void Intro::update()
|
||||
{
|
||||
constexpr int TICKS_SPEED = 15;
|
||||
|
||||
if (SDL_GetTicks() - ticks_ > TICKS_SPEED)
|
||||
if (SDL_GetTicks() - ticks_ > param.game.speed)
|
||||
{
|
||||
// Actualiza el contador de ticks
|
||||
ticks_ = SDL_GetTicks();
|
||||
|
||||
// Actualiza el fondo
|
||||
tiled_bg_->update();
|
||||
|
||||
switch (state_)
|
||||
{
|
||||
case IntroState::SCENES:
|
||||
updateSprites();
|
||||
updateTexts();
|
||||
updateScenes();
|
||||
break;
|
||||
|
||||
case IntroState::POST:
|
||||
updatePostState();
|
||||
break;
|
||||
}
|
||||
|
||||
// Actualiza el objeto screen
|
||||
Screen::get()->update();
|
||||
|
||||
// Actualiza los objetos
|
||||
for (auto &bitmap : bitmaps_)
|
||||
{
|
||||
bitmap->update();
|
||||
}
|
||||
|
||||
for (auto &text : texts_)
|
||||
{
|
||||
text->update();
|
||||
}
|
||||
|
||||
// Actualiza las escenas de la intro
|
||||
updateScenes();
|
||||
|
||||
// Actualiza las variables de globalInputs
|
||||
globalInputs::update();
|
||||
}
|
||||
@@ -403,15 +262,19 @@ void Intro::render()
|
||||
// Limpia la pantalla
|
||||
Screen::get()->clean(bg_color);
|
||||
|
||||
// Dibuja los objetos
|
||||
for (const auto &bitmap : bitmaps_)
|
||||
{
|
||||
bitmap->render();
|
||||
}
|
||||
// Dibuja el fondo
|
||||
tiled_bg_->render();
|
||||
|
||||
for (const auto &text : texts_)
|
||||
switch (state_)
|
||||
{
|
||||
text->render();
|
||||
case IntroState::SCENES:
|
||||
{
|
||||
renderSprites();
|
||||
renderTexts();
|
||||
break;
|
||||
}
|
||||
case IntroState::POST:
|
||||
break;
|
||||
}
|
||||
|
||||
// Vuelca el contenido del renderizador en pantalla
|
||||
@@ -430,3 +293,235 @@ void Intro::run()
|
||||
render();
|
||||
}
|
||||
}
|
||||
|
||||
// Inicializa las imagens
|
||||
void Intro::initSprites()
|
||||
{
|
||||
// Listado de imagenes a usar
|
||||
const std::array<std::string, 6> TEXTURE_LIST = {
|
||||
"intro1.png",
|
||||
"intro2.png",
|
||||
"intro3.png",
|
||||
"intro4.png",
|
||||
"intro5.png",
|
||||
"intro6.png"};
|
||||
|
||||
// Constantes
|
||||
auto texture = Resource::get()->getTexture(TEXTURE_LIST.front());
|
||||
const int SPRITE_WIDTH = texture->getWidth();
|
||||
const int SPRITE_HEIGHT = texture->getHeight();
|
||||
const int X_DEST = param.game.game_area.center_x - SPRITE_WIDTH / 2;
|
||||
const int Y_DEST = param.game.game_area.first_quarter_y - (SPRITE_HEIGHT / 4);
|
||||
|
||||
// Inicializa los sprites de la intro
|
||||
constexpr int TOTAL_SPRITES = 6;
|
||||
for (int i = 0; i < TOTAL_SPRITES; ++i)
|
||||
{
|
||||
auto sprite = std::make_unique<PathSprite>(Resource::get()->getTexture(TEXTURE_LIST.at(i)));
|
||||
sprite->setWidth(SPRITE_WIDTH);
|
||||
sprite->setHeight(SPRITE_HEIGHT);
|
||||
sprite->setSpriteClip(0, 0, SPRITE_WIDTH, SPRITE_HEIGHT);
|
||||
sprites_.push_back(std::move(sprite));
|
||||
}
|
||||
|
||||
sprites_.at(0)->addPath(-SPRITE_WIDTH - 10, X_DEST, PathType::HORIZONTAL, Y_DEST, 100, easeInOutExpo, 0);
|
||||
sprites_.at(1)->addPath(param.game.width, X_DEST, PathType::HORIZONTAL, Y_DEST, 100, easeOutBounce, 0);
|
||||
sprites_.at(2)->addPath(-SPRITE_HEIGHT, Y_DEST, PathType::VERTICAL, X_DEST, 40, easeOutQuint, 0);
|
||||
sprites_.at(3)->addPath(param.game.height, Y_DEST, PathType::VERTICAL, X_DEST, 800, easeOutQuint, 0);
|
||||
sprites_.at(4)->addPath(-SPRITE_HEIGHT, Y_DEST, PathType::VERTICAL, X_DEST, 70, easeOutElastic, 0);
|
||||
sprites_.at(5)->addPath(param.game.width, X_DEST, PathType::HORIZONTAL, Y_DEST, 400, easeOutQuad, 300);
|
||||
sprites_.at(5)->addPath(X_DEST, -SPRITE_WIDTH, PathType::HORIZONTAL, Y_DEST, 80, easeInElastic, 0);
|
||||
|
||||
// Constantes
|
||||
const int BORDER = 4;
|
||||
const int SHADOW_SPRITE_WIDTH = SPRITE_WIDTH + BORDER;
|
||||
const int SHADOW_SPRITE_HEIGHT = SPRITE_HEIGHT + BORDER;
|
||||
const int S_X_DEST = X_DEST - BORDER / 2;
|
||||
const int S_Y_DEST = Y_DEST - BORDER / 2;
|
||||
;
|
||||
|
||||
// Crea las texturas para las sombras
|
||||
std::vector<std::shared_ptr<Texture>> shadow_textures;
|
||||
|
||||
for (int i = 0; i < TOTAL_SPRITES; ++i)
|
||||
{
|
||||
auto shadow_texture = std::make_shared<Texture>(Screen::get()->getRenderer());
|
||||
shadow_texture->createBlank(SHADOW_SPRITE_WIDTH, SHADOW_SPRITE_HEIGHT, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET);
|
||||
shadow_texture->setBlendMode(SDL_BLENDMODE_BLEND);
|
||||
|
||||
auto temp = SDL_GetRenderTarget(Screen::get()->getRenderer());
|
||||
shadow_texture->setAsRenderTarget(Screen::get()->getRenderer());
|
||||
|
||||
SDL_SetRenderDrawColor(Screen::get()->getRenderer(), 0xFF, 0x00, 0x00, 0xFF);
|
||||
SDL_RenderClear(Screen::get()->getRenderer());
|
||||
|
||||
SDL_Rect rect = {BORDER / 2, BORDER / 2, SPRITE_WIDTH, SPRITE_HEIGHT};
|
||||
auto texture = Resource::get()->getTexture(TEXTURE_LIST.at(i))->getSDLTexture();
|
||||
SDL_SetTextureBlendMode(texture, SDL_BLENDMODE_MOD);
|
||||
SDL_RenderCopy(Screen::get()->getRenderer(), texture, nullptr, &rect);
|
||||
SDL_SetTextureBlendMode(texture, SDL_BLENDMODE_NONE);
|
||||
|
||||
// shadow_texture->setAlpha(160);
|
||||
|
||||
SDL_SetRenderTarget(Screen::get()->getRenderer(), temp);
|
||||
shadow_textures.push_back(shadow_texture);
|
||||
}
|
||||
|
||||
// Inicializa los sprites para la sombra
|
||||
for (int i = 0; i < TOTAL_SPRITES; ++i)
|
||||
{
|
||||
auto sprite = std::make_unique<PathSprite>(shadow_textures.at(i));
|
||||
sprite->setWidth(SHADOW_SPRITE_WIDTH);
|
||||
sprite->setHeight(SHADOW_SPRITE_HEIGHT);
|
||||
sprite->setSpriteClip(0, 0, SHADOW_SPRITE_WIDTH, SHADOW_SPRITE_HEIGHT);
|
||||
shadow_sprites_.push_back(std::move(sprite));
|
||||
}
|
||||
|
||||
shadow_sprites_.at(0)->addPath(param.game.height + 10, S_Y_DEST, PathType::VERTICAL, S_X_DEST, 100, easeInOutExpo, 0);
|
||||
shadow_sprites_.at(1)->addPath(-SHADOW_SPRITE_HEIGHT, S_Y_DEST, PathType::VERTICAL, S_X_DEST, 100, easeOutBounce, 0);
|
||||
shadow_sprites_.at(2)->addPath(-SHADOW_SPRITE_WIDTH, S_X_DEST, PathType::HORIZONTAL, S_Y_DEST, 40, easeOutQuint, 0);
|
||||
shadow_sprites_.at(3)->addPath(param.game.width, S_X_DEST, PathType::HORIZONTAL, S_Y_DEST, 800, easeOutQuint, 0);
|
||||
shadow_sprites_.at(4)->addPath(param.game.height, S_Y_DEST, PathType::VERTICAL, S_X_DEST, 70, easeOutElastic, 0);
|
||||
shadow_sprites_.at(5)->addPath(-SHADOW_SPRITE_HEIGHT, S_Y_DEST, PathType::VERTICAL, S_X_DEST, 400, easeOutQuad, 300);
|
||||
shadow_sprites_.at(5)->addPath(S_X_DEST, param.game.width, PathType::HORIZONTAL, S_Y_DEST, 80, easeInElastic, 0);
|
||||
}
|
||||
|
||||
// Inicializa los textos
|
||||
void Intro::initTexts()
|
||||
{
|
||||
constexpr int TOTAL_TEXTS = 9;
|
||||
for (int i = 0; i < TOTAL_TEXTS; ++i)
|
||||
{
|
||||
auto w = std::make_unique<Writer>(Resource::get()->getText("04b_25_metal"));
|
||||
w->setPosX(BLOCK * 0);
|
||||
w->setPosY(param.game.height - (BLOCK * 6));
|
||||
w->setKerning(-2);
|
||||
w->setEnabled(false);
|
||||
w->setFinishedCounter(180);
|
||||
texts_.push_back(std::move(w));
|
||||
}
|
||||
|
||||
// Un dia qualsevol de l'any 2000
|
||||
texts_.at(0)->setCaption(lang::getText(27));
|
||||
texts_.at(0)->setSpeed(8);
|
||||
|
||||
// Tot esta tranquil a la UPV
|
||||
texts_.at(1)->setCaption(lang::getText(28));
|
||||
texts_.at(1)->setSpeed(8);
|
||||
|
||||
// Fins que un desaprensiu...
|
||||
texts_.at(2)->setCaption(lang::getText(29));
|
||||
texts_.at(2)->setSpeed(12);
|
||||
|
||||
// HEY! ME ANE A FERME UN CORTAET...
|
||||
texts_.at(3)->setCaption(lang::getText(30));
|
||||
texts_.at(3)->setSpeed(8);
|
||||
|
||||
// UAAAAAAAAAAAAA!!!
|
||||
texts_.at(4)->setCaption(lang::getText(31));
|
||||
texts_.at(4)->setSpeed(1);
|
||||
|
||||
// Espera un moment...
|
||||
texts_.at(5)->setCaption(lang::getText(32));
|
||||
texts_.at(5)->setSpeed(16);
|
||||
|
||||
// Si resulta que no tinc solt!
|
||||
texts_.at(6)->setCaption(lang::getText(33));
|
||||
texts_.at(6)->setSpeed(2);
|
||||
|
||||
// MERDA DE MAQUINA!
|
||||
texts_.at(7)->setCaption(lang::getText(34));
|
||||
texts_.at(7)->setSpeed(3);
|
||||
|
||||
// Blop... blop... blop...
|
||||
texts_.at(8)->setCaption(lang::getText(35));
|
||||
texts_.at(8)->setSpeed(16);
|
||||
|
||||
for (auto &text : texts_)
|
||||
{
|
||||
text->center(param.game.game_area.center_x);
|
||||
}
|
||||
}
|
||||
|
||||
// Actualiza los sprites
|
||||
void Intro::updateSprites()
|
||||
{
|
||||
for (auto &sprite : sprites_)
|
||||
{
|
||||
sprite->update();
|
||||
}
|
||||
|
||||
for (auto &sprite : shadow_sprites_)
|
||||
{
|
||||
sprite->update();
|
||||
}
|
||||
}
|
||||
|
||||
// Actualiza los textos
|
||||
void Intro::updateTexts()
|
||||
{
|
||||
for (auto &text : texts_)
|
||||
{
|
||||
text->update();
|
||||
}
|
||||
}
|
||||
|
||||
// Dibuja los sprites
|
||||
void Intro::renderSprites()
|
||||
{
|
||||
shadow_sprites_.at(scene_)->render();
|
||||
sprites_.at(scene_)->render();
|
||||
}
|
||||
|
||||
// Dibuja los textos
|
||||
void Intro::renderTexts()
|
||||
{
|
||||
for (const auto &text : texts_)
|
||||
{
|
||||
text->render();
|
||||
}
|
||||
}
|
||||
|
||||
// Actualiza el estado POST
|
||||
void Intro::updatePostState()
|
||||
{
|
||||
const Uint32 ELAPSED_TIME = SDL_GetTicks() - state_start_time_;
|
||||
|
||||
switch (post_state_)
|
||||
{
|
||||
case IntroPostState::STOP_BG:
|
||||
// EVENTO: Detiene el fondo después de 2 segundos
|
||||
if (ELAPSED_TIME >= 1000)
|
||||
{
|
||||
tiled_bg_->stopGracefully();
|
||||
|
||||
// Modifica el color del fondo hasta llegar a blanco
|
||||
if (bg_color_ < 255)
|
||||
{
|
||||
++bg_color_;
|
||||
tiled_bg_->setColor(Color(bg_color_, bg_color_, bg_color_));
|
||||
}
|
||||
}
|
||||
|
||||
// Cambia de estado si el fondo se ha detenido y recuperado el color
|
||||
if (tiled_bg_->isStopped() && bg_color_ == 255)
|
||||
{
|
||||
post_state_ = IntroPostState::END;
|
||||
state_start_time_ = SDL_GetTicks();
|
||||
}
|
||||
break;
|
||||
|
||||
case IntroPostState::END:
|
||||
// Finaliza la intro después de 3 segundos
|
||||
if (ELAPSED_TIME >= 2000)
|
||||
{
|
||||
JA_StopMusic();
|
||||
section::name = section::Name::TITLE;
|
||||
section::options = section::Options::TITLE_1;
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
#pragma once
|
||||
|
||||
#include <SDL2/SDL_stdinc.h> // Para Uint32
|
||||
#include <memory> // Para unique_ptr, shared_ptr
|
||||
#include <SDL2/SDL_stdinc.h> // Para Uint32, Uint8
|
||||
#include <memory> // Para unique_ptr
|
||||
#include <vector> // Para vector
|
||||
#include "smart_sprite.h" // Para SmartSprite
|
||||
#include "path_sprite.h" // Para PathSprite
|
||||
#include "tiled_bg.h" // Para TiledBG
|
||||
#include "writer.h" // Para Writer
|
||||
class Text; // lines 8-8
|
||||
class Texture; // lines 9-9
|
||||
|
||||
/*
|
||||
Esta clase gestiona un estado del programa. Se encarga de mostrar la secuencia
|
||||
@@ -17,16 +16,31 @@ class Texture; // lines 9-9
|
||||
class Intro
|
||||
{
|
||||
private:
|
||||
// Objetos
|
||||
std::shared_ptr<Texture> texture_; // Textura con los graficos
|
||||
std::shared_ptr<Text> text_; // Textos de la intro
|
||||
enum class IntroState
|
||||
{
|
||||
SCENES,
|
||||
POST,
|
||||
};
|
||||
|
||||
std::vector<std::unique_ptr<SmartSprite>> bitmaps_; // Vector con los sprites inteligentes para los dibujos de la intro
|
||||
enum class IntroPostState
|
||||
{
|
||||
STOP_BG,
|
||||
END,
|
||||
};
|
||||
|
||||
// Objetos
|
||||
std::vector<std::unique_ptr<PathSprite>> sprites_; // Vector con los sprites inteligentes para los dibujos de la intro
|
||||
std::vector<std::unique_ptr<PathSprite>> shadow_sprites_; // Vector con los sprites inteligentes para las sombras
|
||||
std::vector<std::unique_ptr<Writer>> texts_; // Textos de la intro
|
||||
std::unique_ptr<TiledBG> tiled_bg_;
|
||||
|
||||
// Variables
|
||||
Uint32 ticks_ = 0; // Contador de ticks para ajustar la velocidad del programa
|
||||
int scene_ = 1; // Indica que escena está activa
|
||||
int scene_ = 0; // Indica que escena está activa
|
||||
IntroState state_ = IntroState::SCENES; // Estado
|
||||
IntroPostState post_state_ = IntroPostState::STOP_BG; // Estado
|
||||
Uint32 state_start_time_;
|
||||
Uint8 bg_color_ = 96;
|
||||
|
||||
// Actualiza las variables del objeto
|
||||
void update();
|
||||
@@ -43,8 +57,26 @@ private:
|
||||
// Actualiza las escenas de la intro
|
||||
void updateScenes();
|
||||
|
||||
// Recarga todas las texturas
|
||||
void reloadTextures();
|
||||
// Inicializa las imagens
|
||||
void initSprites();
|
||||
|
||||
// Inicializa los textos
|
||||
void initTexts();
|
||||
|
||||
// Actualiza los sprites
|
||||
void updateSprites();
|
||||
|
||||
// Actualiza los textos
|
||||
void updateTexts();
|
||||
|
||||
// Dibuja los sprites
|
||||
void renderSprites();
|
||||
|
||||
// Dibuja los textos
|
||||
void renderTexts();
|
||||
|
||||
// Actualiza el estado POST
|
||||
void updatePostState();
|
||||
|
||||
public:
|
||||
// Constructor
|
||||
|
||||
@@ -22,8 +22,9 @@ enum class ItemType : int
|
||||
PACMAR = 3, /**< Pacman */
|
||||
CLOCK = 4, /**< Reloj */
|
||||
COFFEE = 5, /**< Café */
|
||||
COFFEE_MACHINE = 6,/**< Máquina de café */
|
||||
NONE = 7, /**< Ninguno */
|
||||
DEBIAN = 6, /**< Debian */
|
||||
COFFEE_MACHINE = 7,/**< Máquina de café */
|
||||
NONE = 8, /**< Ninguno */
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
#ifndef NO_SHADERS
|
||||
|
||||
#include "jail_shader.h"
|
||||
#include <SDL2/SDL_rect.h> // para SDL_Point
|
||||
#include <stdlib.h> // para NULL, free, malloc, exit
|
||||
@@ -248,4 +246,3 @@ namespace shader
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -1,5 +1,3 @@
|
||||
#ifndef NO_SHADERS
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <SDL2/SDL_render.h> // para SDL_Texture
|
||||
@@ -45,4 +43,3 @@ namespace shader
|
||||
|
||||
void render();
|
||||
}
|
||||
#endif
|
||||
@@ -41,10 +41,10 @@ namespace lang
|
||||
return texts.at(index);
|
||||
}
|
||||
|
||||
// Cambia el idioma seleccionado al siguiente idioma disponible
|
||||
Code change(Code current_lang)
|
||||
// Obtiene el codigo del idioma del siguiente idioma
|
||||
Code getNextLangCode(Code lang)
|
||||
{
|
||||
auto index = static_cast<int>(current_lang);
|
||||
auto index = static_cast<int>(lang);
|
||||
index = (index + 1) % 3;
|
||||
return static_cast<Code>(index);
|
||||
}
|
||||
|
||||
@@ -17,6 +17,6 @@ namespace lang
|
||||
// Obtiene la cadena de texto del indice
|
||||
std::string getText(int index);
|
||||
|
||||
// Cambia el idioma seleccionado al siguiente idioma disponible
|
||||
Code change(Code current_lang);
|
||||
// Obtiene el codigo del idioma del siguiente idioma
|
||||
Code getNextLangCode(Code lang);
|
||||
}
|
||||
112
source/logo.cpp
@@ -1,45 +1,41 @@
|
||||
#include "logo.h"
|
||||
#include <SDL2/SDL_events.h> // Para SDL_PollEvent, SDL_Event, SDL_QUIT, SDL...
|
||||
#include <SDL2/SDL_events.h> // Para SDL_PollEvent, SDL_Event
|
||||
#include <SDL2/SDL_timer.h> // Para SDL_GetTicks
|
||||
#include <SDL2/SDL_video.h> // Para SDL_WINDOWEVENT_SIZE_CHANGED
|
||||
#include <utility> // Para move
|
||||
#include "global_inputs.h" // Para check
|
||||
#include "input.h" // Para Input
|
||||
#include "jail_audio.h" // Para JA_StopMusic
|
||||
#include "global_events.h" // Para check
|
||||
#include "global_inputs.h" // Para check, update
|
||||
#include "jail_audio.h" // Para JA_FadeOutMusic, JA_PlaySound, JA_StopC...
|
||||
#include "param.h" // Para Param, ParamGame, param
|
||||
#include "resource.h" // Para Resource
|
||||
#include "screen.h" // Para Screen
|
||||
#include "section.h" // Para Name, name, Options, options
|
||||
#include "section.h" // Para Name, name
|
||||
#include "sprite.h" // Para Sprite
|
||||
#include "texture.h" // Para Texture
|
||||
#include "utils.h" // Para Color, Zone
|
||||
#include "mouse.h"
|
||||
|
||||
// Constructor
|
||||
Logo::Logo()
|
||||
: since_texture_(Resource::get()->getTexture("logo_since_1998.png")),
|
||||
since_sprite_(std::make_unique<Sprite>(since_texture_)),
|
||||
jail_texture_(Resource::get()->getTexture("logo_jailgames.png")),
|
||||
ticks_(0)
|
||||
jail_texture_(Resource::get()->getTexture("logo_jailgames.png"))
|
||||
{
|
||||
|
||||
// Inicializa variables
|
||||
counter_ = 0;
|
||||
section::name = section::Name::LOGO;
|
||||
dest_.x = param.game.game_area.center_x - jail_texture_->getWidth() / 2;
|
||||
dest_.y = param.game.game_area.center_y - jail_texture_->getHeight() / 2;
|
||||
since_sprite_->setPosition({(param.game.width - since_texture_->getWidth()) / 2, 83 + jail_texture_->getHeight() + 5, since_texture_->getWidth(), since_texture_->getHeight()});
|
||||
since_sprite_->setY(dest_.y + jail_texture_->getHeight() + 5);
|
||||
since_sprite_->setSpriteClip(0, 0, since_texture_->getWidth(), since_texture_->getHeight());
|
||||
since_texture_->setColor(0x00, 0x00, 0x00); // Esto en linux no hace nada ??
|
||||
since_texture_->setColor(0x00, 0x00, 0x00);
|
||||
|
||||
// Crea los sprites de cada linea
|
||||
for (int i = 0; i < jail_texture_->getHeight(); ++i)
|
||||
{
|
||||
auto temp = std::make_unique<Sprite>(jail_texture_, 0, i, jail_texture_->getWidth(), 1);
|
||||
temp->setSpriteClip(0, i, jail_texture_->getWidth(), 1);
|
||||
const int posX = (i % 2 == 0) ? param.game.width + (i * 3) : -jail_texture_->getWidth() - (i * 3);
|
||||
temp->setX(posX);
|
||||
const int POS_X = (i % 2 == 0) ? param.game.width + (i * 3) : -jail_texture_->getWidth() - (i * 3);
|
||||
temp->setX(POS_X);
|
||||
temp->setY(dest_.y + i);
|
||||
jail_sprite_.push_back(std::move(temp));
|
||||
}
|
||||
@@ -63,58 +59,23 @@ Logo::~Logo()
|
||||
JA_StopChannel(-1);
|
||||
}
|
||||
|
||||
// Recarga todas las texturas
|
||||
void Logo::reloadTextures()
|
||||
{
|
||||
jail_texture_->reLoad();
|
||||
since_texture_->reLoad();
|
||||
}
|
||||
|
||||
// Comprueba el manejador de eventos
|
||||
void Logo::checkEvents()
|
||||
{
|
||||
SDL_Event event;
|
||||
// Comprueba los eventos que hay en la cola
|
||||
while (SDL_PollEvent(&event))
|
||||
{
|
||||
// Evento de salida de la aplicación
|
||||
if (event.type == SDL_QUIT)
|
||||
{
|
||||
section::name = section::Name::QUIT;
|
||||
section::options = section::Options::QUIT_FROM_EVENT;
|
||||
break;
|
||||
}
|
||||
|
||||
// Comprueba si se ha cambiado el tamaño de la ventana
|
||||
else if (event.type == SDL_WINDOWEVENT)
|
||||
{
|
||||
if (event.window.event == SDL_WINDOWEVENT_SIZE_CHANGED)
|
||||
{
|
||||
reloadTextures();
|
||||
}
|
||||
}
|
||||
|
||||
// Comprueba el cursor
|
||||
Mouse::handleEvent(event);
|
||||
globalEvents::check(event);
|
||||
}
|
||||
}
|
||||
|
||||
// Comprueba las entradas
|
||||
void Logo::checkInput()
|
||||
{
|
||||
// Comprueba si se ha pulsado cualquier botón (de los usados para jugar)
|
||||
if (Input::get()->checkAnyButtonPressed())
|
||||
{
|
||||
section::name = section::Name::TITLE;
|
||||
section::options = section::Options::TITLE_1;
|
||||
return;
|
||||
}
|
||||
|
||||
// Comprueba los inputs que se pueden introducir en cualquier sección del juego
|
||||
globalInputs::check();
|
||||
}
|
||||
|
||||
// Gestiona el logo de JAILGAME
|
||||
// Gestiona el logo de JAILGAMES
|
||||
void Logo::updateJAILGAMES()
|
||||
{
|
||||
if (counter_ == 30)
|
||||
@@ -147,6 +108,12 @@ void Logo::updateJAILGAMES()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Comprueba si ha terminado el logo
|
||||
if (counter_ == END_LOGO_COUNTER_MARK + POST_LOGO_DURATION)
|
||||
{
|
||||
section::name = section::Name::INTRO;
|
||||
}
|
||||
}
|
||||
|
||||
// Gestiona el color de las texturas
|
||||
@@ -177,9 +144,7 @@ void Logo::updateTextureColors()
|
||||
// Actualiza las variables
|
||||
void Logo::update()
|
||||
{
|
||||
constexpr int TICKS_SPEED = 15;
|
||||
|
||||
if (SDL_GetTicks() - ticks_ > TICKS_SPEED)
|
||||
if (SDL_GetTicks() - ticks_ > param.game.speed)
|
||||
{
|
||||
// Actualiza el contador de ticks
|
||||
ticks_ = SDL_GetTicks();
|
||||
@@ -190,21 +155,12 @@ void Logo::update()
|
||||
// Comprueba las entradas
|
||||
checkInput();
|
||||
|
||||
// Gestiona el logo de JAILGAME
|
||||
updateJAILGAMES();
|
||||
|
||||
// Gestiona el color de las texturas
|
||||
updateTextureColors();
|
||||
|
||||
// Gestiona el contador y sus eventos
|
||||
// Gestiona el contador
|
||||
counter_++;
|
||||
|
||||
// Comprueba si ha terminado el logo
|
||||
if (counter_ == END_LOGO_COUNTER_MARK + POST_LOGO_DURATION)
|
||||
{
|
||||
section::name = section::Name::INTRO;
|
||||
}
|
||||
|
||||
// Actualiza las variables de globalInputs
|
||||
globalInputs::update();
|
||||
}
|
||||
@@ -213,24 +169,11 @@ void Logo::update()
|
||||
// Dibuja en pantalla
|
||||
void Logo::render()
|
||||
{
|
||||
// Prepara para empezar a dibujar en la textura de juego
|
||||
Screen::get()->start();
|
||||
|
||||
// Limpia la pantalla
|
||||
Screen::get()->clean();
|
||||
|
||||
// Dibuja los sprites
|
||||
for (auto &sprite : jail_sprite_)
|
||||
{
|
||||
sprite->render();
|
||||
}
|
||||
renderJAILGAMES();
|
||||
|
||||
if (counter_ >= SHOW_SINCE_SPRITE_COUNTER_MARK)
|
||||
{
|
||||
since_sprite_->render();
|
||||
}
|
||||
|
||||
// Vuelca el contenido del renderizador en pantalla
|
||||
Screen::get()->render();
|
||||
}
|
||||
|
||||
@@ -248,3 +191,18 @@ void Logo::run()
|
||||
render();
|
||||
}
|
||||
}
|
||||
|
||||
// Renderiza el logo de JAILGAMES
|
||||
void Logo::renderJAILGAMES()
|
||||
{
|
||||
// Dibuja los sprites
|
||||
for (auto &sprite : jail_sprite_)
|
||||
{
|
||||
sprite->render();
|
||||
}
|
||||
|
||||
if (counter_ >= SHOW_SINCE_SPRITE_COUNTER_MARK)
|
||||
{
|
||||
since_sprite_->render();
|
||||
}
|
||||
}
|
||||
@@ -4,9 +4,9 @@
|
||||
#include <SDL2/SDL_stdinc.h> // Para Uint32
|
||||
#include <memory> // Para shared_ptr, unique_ptr
|
||||
#include <vector> // Para vector
|
||||
class Sprite;
|
||||
class Sprite; // lines 8-8
|
||||
class Texture; // lines 9-9
|
||||
struct Color;
|
||||
struct Color; // lines 10-10
|
||||
|
||||
/*
|
||||
Esta clase gestiona un estado del programa. Se encarga de dibujar por pantalla el
|
||||
@@ -35,8 +35,8 @@ private:
|
||||
|
||||
// Variables
|
||||
std::vector<Color> color_; // Vector con los colores para el fade
|
||||
int counter_; // Contador
|
||||
Uint32 ticks_; // Contador de ticks para ajustar la velocidad del programa
|
||||
int counter_ = 0; // Contador
|
||||
Uint32 ticks_ = 0; // Contador de ticks para ajustar la velocidad del programa
|
||||
SDL_Point dest_; // Posición X donde dibujar el logo
|
||||
|
||||
// Actualiza las variables
|
||||
@@ -51,15 +51,15 @@ private:
|
||||
// Comprueba las entradas
|
||||
void checkInput();
|
||||
|
||||
// Gestiona el logo de JAILGAME
|
||||
// Gestiona el logo de JAILGAMES
|
||||
void updateJAILGAMES();
|
||||
|
||||
// Renderiza el logo de JAILGAMES
|
||||
void renderJAILGAMES();
|
||||
|
||||
// Gestiona el color de las texturas
|
||||
void updateTextureColors();
|
||||
|
||||
// Recarga todas las texturas
|
||||
void reloadTextures();
|
||||
|
||||
public:
|
||||
// Constructor
|
||||
Logo();
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
#include "manage_hiscore_table.h"
|
||||
#include <SDL2/SDL_error.h> // Para SDL_GetError
|
||||
#include <SDL2/SDL_rwops.h> // Para SDL_RWread, SDL_RWwrite, SDL_RWFromFile
|
||||
#include <algorithm> // Para sort
|
||||
#include <algorithm> // Para find_if, sort
|
||||
#include <iostream> // Para basic_ostream, operator<<, cout, endl
|
||||
#include "utils.h" // Para HiScoreEntry, getFileName
|
||||
#include <iterator> // Para distance
|
||||
#include "utils.h" // Para getFileName
|
||||
|
||||
// Resetea la tabla a los valores por defecto
|
||||
void ManageHiScoreTable::clear()
|
||||
@@ -27,7 +28,7 @@ void ManageHiScoreTable::clear()
|
||||
}
|
||||
|
||||
// Añade un elemento a la tabla
|
||||
void ManageHiScoreTable::add(HiScoreEntry entry)
|
||||
int ManageHiScoreTable::add(const HiScoreEntry &entry)
|
||||
{
|
||||
// Añade la entrada a la tabla
|
||||
table_.push_back(entry);
|
||||
@@ -35,8 +36,32 @@ void ManageHiScoreTable::add(HiScoreEntry entry)
|
||||
// Ordena la tabla
|
||||
sort();
|
||||
|
||||
// Encontrar la posición del nuevo elemento
|
||||
auto it = std::find_if(table_.begin(), table_.end(), [&](const HiScoreEntry &e)
|
||||
{ return e.name == entry.name &&
|
||||
e.score == entry.score &&
|
||||
e.one_credit_complete == entry.one_credit_complete; });
|
||||
|
||||
int position = -1;
|
||||
if (it != table_.end())
|
||||
{
|
||||
position = std::distance(table_.begin(), it);
|
||||
}
|
||||
|
||||
// Deja solo las 10 primeras entradas
|
||||
if (table_.size() > 10)
|
||||
{
|
||||
table_.resize(10);
|
||||
|
||||
// Si el nuevo elemento quedó fuera del top 10
|
||||
if (position >= 10)
|
||||
{
|
||||
position = -1; // No entró en el top 10
|
||||
}
|
||||
}
|
||||
|
||||
// Devuelve la posición
|
||||
return position;
|
||||
}
|
||||
|
||||
// Ordena la tabla
|
||||
@@ -50,52 +75,55 @@ void ManageHiScoreTable::sort()
|
||||
std::sort(table_.begin(), table_.end(), scoreDescendingComparator);
|
||||
}
|
||||
|
||||
// Carga la tabla con los datos de un fichero
|
||||
// Carga la tabla desde un fichero
|
||||
bool ManageHiScoreTable::loadFromFile(const std::string &file_path)
|
||||
{
|
||||
clear();
|
||||
auto success = true;
|
||||
auto file = SDL_RWFromFile(file_path.c_str(), "r+b");
|
||||
auto file = SDL_RWFromFile(file_path.c_str(), "rb");
|
||||
|
||||
if (file)
|
||||
{
|
||||
std::cout << "Reading file: " << getFileName(file_path) << std::endl;
|
||||
table_.clear(); // Limpia la tabla actual
|
||||
|
||||
for (auto &entry : table_)
|
||||
// Lee el número de entradas en la tabla
|
||||
int tableSize = 0;
|
||||
SDL_RWread(file, &tableSize, sizeof(int), 1);
|
||||
|
||||
// Lee los datos de cada entrada
|
||||
for (int i = 0; i < tableSize; ++i)
|
||||
{
|
||||
HiScoreEntry entry;
|
||||
|
||||
// Lee la puntuación
|
||||
SDL_RWread(file, &entry.score, sizeof(int), 1);
|
||||
|
||||
// Lee el tamaño del nombre y luego el nombre
|
||||
int nameSize = 0;
|
||||
|
||||
if (SDL_RWread(file, &entry.score, sizeof(int), 1) == 0)
|
||||
{
|
||||
success = false;
|
||||
break;
|
||||
}
|
||||
|
||||
if (SDL_RWread(file, &nameSize, sizeof(int), 1) == 0)
|
||||
{
|
||||
success = false;
|
||||
break;
|
||||
}
|
||||
SDL_RWread(file, &nameSize, sizeof(int), 1);
|
||||
|
||||
std::vector<char> nameBuffer(nameSize + 1);
|
||||
if (SDL_RWread(file, nameBuffer.data(), sizeof(char) * nameSize, 1) == 0)
|
||||
{
|
||||
success = false;
|
||||
break;
|
||||
}
|
||||
|
||||
nameBuffer[nameSize] = '\0';
|
||||
SDL_RWread(file, nameBuffer.data(), nameSize, 1);
|
||||
nameBuffer[nameSize] = '\0'; // Asegurar el fin de la cadena
|
||||
entry.name = std::string(nameBuffer.data());
|
||||
|
||||
// Lee el valor de one_credit_complete
|
||||
int occValue = 0;
|
||||
SDL_RWread(file, &occValue, sizeof(int), 1);
|
||||
entry.one_credit_complete = (occValue != 0);
|
||||
|
||||
// Añade la entrada a la tabla
|
||||
table_.push_back(entry);
|
||||
}
|
||||
|
||||
std::cout << "Reading file: " << getFileName(file_path) << std::endl;
|
||||
SDL_RWclose(file);
|
||||
}
|
||||
|
||||
if (!success)
|
||||
else
|
||||
{
|
||||
clear();
|
||||
std::cout << "Error: Unable to load " << getFileName(file_path) << " file! " << SDL_GetError() << std::endl;
|
||||
success = false;
|
||||
}
|
||||
|
||||
return success;
|
||||
}
|
||||
|
||||
@@ -107,21 +135,35 @@ bool ManageHiScoreTable::saveToFile(const std::string &file_path)
|
||||
|
||||
if (file)
|
||||
{
|
||||
// Guarda los datos
|
||||
for (int i = 0; i < (int)table_.size(); ++i)
|
||||
// Guarda el número de entradas en la tabla
|
||||
int tableSize = static_cast<int>(table_.size());
|
||||
SDL_RWwrite(file, &tableSize, sizeof(int), 1);
|
||||
|
||||
// Guarda los datos de cada entrada
|
||||
for (int i = 0; i < tableSize; ++i)
|
||||
{
|
||||
SDL_RWwrite(file, &table_.at(i).score, sizeof(int), 1);
|
||||
const int nameSize = (int)table_.at(i).name.size();
|
||||
const HiScoreEntry &entry = table_.at(i);
|
||||
|
||||
// Guarda la puntuación
|
||||
SDL_RWwrite(file, &entry.score, sizeof(int), 1);
|
||||
|
||||
// Guarda el tamaño del nombre y luego el nombre
|
||||
int nameSize = static_cast<int>(entry.name.size());
|
||||
SDL_RWwrite(file, &nameSize, sizeof(int), 1);
|
||||
SDL_RWwrite(file, table_.at(i).name.c_str(), nameSize, 1);
|
||||
SDL_RWwrite(file, entry.name.c_str(), nameSize, 1);
|
||||
|
||||
// Guarda el valor de one_credit_complete como un entero (0 o 1)
|
||||
int occValue = entry.one_credit_complete ? 1 : 0;
|
||||
SDL_RWwrite(file, &occValue, sizeof(int), 1);
|
||||
}
|
||||
|
||||
std::cout << "Writing file: " << getFileName(file_path).c_str() << std::endl;
|
||||
std::cout << "Writing file: " << getFileName(file_path) << std::endl;
|
||||
SDL_RWclose(file);
|
||||
}
|
||||
else
|
||||
{
|
||||
std::cout << "Error: Unable to save " << getFileName(file_path).c_str() << " file! " << SDL_GetError() << std::endl;
|
||||
std::cout << "Error: Unable to save " << getFileName(file_path) << " file! " << SDL_GetError() << std::endl;
|
||||
success = false;
|
||||
}
|
||||
return success;
|
||||
}
|
||||
@@ -16,10 +16,11 @@ struct HiScoreEntry
|
||||
{
|
||||
std::string name; // Nombre
|
||||
int score; // Puntuación
|
||||
bool one_credit_complete; // Indica si se ha conseguido 1CC
|
||||
|
||||
// Constructor
|
||||
explicit HiScoreEntry(const std::string &n = "", int s = 0)
|
||||
: name(n), score(s) {}
|
||||
explicit HiScoreEntry(const std::string &n = "", int s = 0, bool occ = false)
|
||||
: name(n.substr(0, 6)), score(s), one_credit_complete(occ) {}
|
||||
};
|
||||
|
||||
// Clase ManageHiScoreTable
|
||||
@@ -44,7 +45,7 @@ public:
|
||||
void clear();
|
||||
|
||||
// Añade un elemento a la tabla
|
||||
void add(HiScoreEntry entry);
|
||||
int add(const HiScoreEntry& entry);
|
||||
|
||||
// Carga la tabla con los datos de un fichero
|
||||
bool loadFromFile(const std::string &file_path);
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
#include "moving_sprite.h"
|
||||
#include <algorithm> // Para max
|
||||
#include "texture.h" // Para Texture
|
||||
|
||||
// Constructor
|
||||
@@ -73,46 +72,7 @@ void MovingSprite::update()
|
||||
}
|
||||
|
||||
// Muestra el sprite por pantalla
|
||||
void MovingSprite::render()
|
||||
{
|
||||
texture_->render(pos_.x, pos_.y, &sprite_clip_, zoom_w_, zoom_h_, rotate_.angle, rotate_.center, flip_);
|
||||
}
|
||||
|
||||
// Establece el valor de la variable
|
||||
void MovingSprite::setZoomW(float value)
|
||||
{
|
||||
zoom_w_ = value;
|
||||
}
|
||||
|
||||
// Establece el valor de la variable
|
||||
void MovingSprite::setZoomH(float value)
|
||||
{
|
||||
zoom_h_ = value;
|
||||
}
|
||||
|
||||
// Establece el valor de la variable
|
||||
void MovingSprite::setAngle(double value)
|
||||
{
|
||||
rotate_.angle = value;
|
||||
}
|
||||
|
||||
// Establece el valor de la variable
|
||||
void MovingSprite::setRotatingCenter(SDL_Point *point)
|
||||
{
|
||||
rotate_.center = point;
|
||||
}
|
||||
|
||||
// Incrementa el valor del ángulo
|
||||
void MovingSprite::updateAngle()
|
||||
{
|
||||
rotate_.angle += rotate_.amount;
|
||||
}
|
||||
|
||||
// Obtiene el valor de la variable
|
||||
bool MovingSprite::isRotating() const
|
||||
{
|
||||
return rotate_.enabled;
|
||||
}
|
||||
void MovingSprite::render() { texture_->render(pos_.x, pos_.y, &sprite_clip_, zoom_w_, zoom_h_, rotate_.angle, rotate_.center, flip_); }
|
||||
|
||||
// Establece la rotacion
|
||||
void MovingSprite::rotate()
|
||||
@@ -135,43 +95,6 @@ void MovingSprite::setRotate(bool enable)
|
||||
rotate_.counter = 0;
|
||||
}
|
||||
|
||||
// Establece el valor de la variable
|
||||
void MovingSprite::setRotateSpeed(int value)
|
||||
{
|
||||
rotate_.speed = std::max(1, value);
|
||||
}
|
||||
|
||||
// Establece el valor de la variable
|
||||
void MovingSprite::setRotateAmount(double value)
|
||||
{
|
||||
rotate_.amount = value;
|
||||
}
|
||||
|
||||
// Cambia el sentido de la rotación
|
||||
void MovingSprite::switchRotate()
|
||||
{
|
||||
rotate_.amount *= -1;
|
||||
}
|
||||
|
||||
// Establece el valor de la variable
|
||||
void MovingSprite::setFlip(SDL_RendererFlip flip)
|
||||
{
|
||||
flip_ = flip;
|
||||
}
|
||||
|
||||
// Gira el sprite horizontalmente
|
||||
void MovingSprite::flip()
|
||||
{
|
||||
flip_ = (flip_ == SDL_FLIP_HORIZONTAL) ? SDL_FLIP_NONE : SDL_FLIP_HORIZONTAL;
|
||||
}
|
||||
|
||||
// Obtiene el valor de la variable
|
||||
SDL_RendererFlip MovingSprite::getFlip()
|
||||
{
|
||||
return flip_;
|
||||
}
|
||||
|
||||
|
||||
// Establece la posición y_ el tamaño del objeto
|
||||
void MovingSprite::setPos(SDL_Rect rect)
|
||||
{
|
||||
@@ -204,27 +127,3 @@ void MovingSprite::setPosY(float value)
|
||||
y_ = value;
|
||||
pos_.y = static_cast<int>(y_);
|
||||
}
|
||||
|
||||
// Establece el valor de la variable
|
||||
void MovingSprite::setVelX(float value)
|
||||
{
|
||||
vx_ = value;
|
||||
}
|
||||
|
||||
// Establece el valor de la variable
|
||||
void MovingSprite::setVelY(float value)
|
||||
{
|
||||
vy_ = value;
|
||||
}
|
||||
|
||||
// Establece el valor de la variable
|
||||
void MovingSprite::setAccelX(float value)
|
||||
{
|
||||
ax_ = value;
|
||||
}
|
||||
|
||||
// Establece el valor de la variable
|
||||
void MovingSprite::setAccelY(float value)
|
||||
{
|
||||
ay_ = value;
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
#include <SDL2/SDL_rect.h> // Para SDL_Rect, SDL_Point
|
||||
#include <SDL2/SDL_render.h> // Para SDL_RendererFlip
|
||||
#include <memory> // Para shared_ptr
|
||||
#include <algorithm>
|
||||
#include "sprite.h" // Para Sprite
|
||||
class Texture; // lines 8-8
|
||||
|
||||
@@ -38,7 +39,7 @@ protected:
|
||||
SDL_RendererFlip flip_; // Indica como se voltea el sprite
|
||||
|
||||
// Incrementa el valor del ángulo
|
||||
void updateAngle();
|
||||
void updateAngle() { rotate_.angle += rotate_.amount; }
|
||||
|
||||
// Mueve el sprite
|
||||
void move();
|
||||
@@ -73,40 +74,40 @@ public:
|
||||
float getAccelY() const { return ay_; }
|
||||
|
||||
// Establece la variable
|
||||
void setVelX(float value);
|
||||
void setVelY(float value);
|
||||
void setAccelX(float value);
|
||||
void setAccelY(float value);
|
||||
void setVelX(float value) { vx_ = value; }
|
||||
void setVelY(float value) { vy_ = value; }
|
||||
void setAccelX(float value) { ax_ = value; }
|
||||
void setAccelY(float value) { ay_ = value; }
|
||||
|
||||
// Obten el valor de la variable
|
||||
bool isRotating() const;
|
||||
bool isRotating() const { return rotate_.enabled; }
|
||||
|
||||
// Establece el valor de la variable
|
||||
void setZoomW(float value);
|
||||
void setZoomH(float value);
|
||||
void setZoomW(float value) { zoom_w_ = value; }
|
||||
void setZoomH(float value) { zoom_h_ = value; }
|
||||
|
||||
// Establece el valor de la variable
|
||||
void setAngle(double vaue);
|
||||
void setRotatingCenter(SDL_Point *point);
|
||||
void setAngle(double value) { rotate_.angle = value; }
|
||||
void setRotatingCenter(SDL_Point *point) { rotate_.center = point; }
|
||||
|
||||
// Activa o desactiva el efecto de rotación
|
||||
void setRotate(bool enable);
|
||||
|
||||
// Establece el valor de la variable
|
||||
void setRotateSpeed(int value);
|
||||
void setRotateAmount(double value);
|
||||
void setRotateSpeed(int value) { rotate_.speed = std::max(1, value); }
|
||||
void setRotateAmount(double value) { rotate_.amount = value; }
|
||||
|
||||
// Cambia el sentido de la rotación
|
||||
void switchRotate();
|
||||
void switchRotate() { rotate_.amount *= -1; }
|
||||
|
||||
// Establece el valor de la variable
|
||||
void setFlip(SDL_RendererFlip flip);
|
||||
void setFlip(SDL_RendererFlip flip) { flip_ = flip; }
|
||||
|
||||
// Gira el sprite horizontalmente
|
||||
void flip();
|
||||
void flip() { flip_ = (flip_ == SDL_FLIP_HORIZONTAL) ? SDL_FLIP_NONE : SDL_FLIP_HORIZONTAL; }
|
||||
|
||||
// Obtiene el valor de la variable
|
||||
SDL_RendererFlip getFlip();
|
||||
SDL_RendererFlip getFlip() { return flip_; }
|
||||
|
||||
// Establece la posición y_ el tamaño del objeto
|
||||
void setPos(SDL_Rect rect);
|
||||
|
||||
@@ -12,22 +12,22 @@
|
||||
#include "texture.h" // Para Texture
|
||||
#include "resource.h"
|
||||
|
||||
// [SINGLETON] Hay que definir las variables estáticas, desde el .h sólo la hemos declarado
|
||||
// [SINGLETON]
|
||||
Notifier *Notifier::notifier_ = nullptr;
|
||||
|
||||
// [SINGLETON] Crearemos el objeto screen con esta función estática
|
||||
// [SINGLETON] Crearemos el objeto con esta función estática
|
||||
void Notifier::init(const std::string &icon_file, std::shared_ptr<Text> text)
|
||||
{
|
||||
Notifier::notifier_ = new Notifier(icon_file, text);
|
||||
}
|
||||
|
||||
// [SINGLETON] Destruiremos el objeto screen con esta función estática
|
||||
// [SINGLETON] Destruiremos el objeto con esta función estática
|
||||
void Notifier::destroy()
|
||||
{
|
||||
delete Notifier::notifier_;
|
||||
}
|
||||
|
||||
// [SINGLETON] Con este método obtenemos el objeto screen y podemos trabajar con él
|
||||
// [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él
|
||||
Notifier *Notifier::get()
|
||||
{
|
||||
return Notifier::notifier_;
|
||||
@@ -153,7 +153,7 @@ void Notifier::clearFinishedNotifications()
|
||||
}
|
||||
}
|
||||
|
||||
void Notifier::showText(std::vector<std::string> texts, int icon, const std::string &code)
|
||||
void Notifier::show(std::vector<std::string> texts, int icon, const std::string &code)
|
||||
{
|
||||
// Si no hay texto, acaba
|
||||
if (texts.empty())
|
||||
@@ -164,7 +164,7 @@ void Notifier::showText(std::vector<std::string> texts, int icon, const std::str
|
||||
// Si las notificaciones no se apilan, elimina las anteriores
|
||||
if (!stack_)
|
||||
{
|
||||
clearNotifications();
|
||||
clearAllNotifications();
|
||||
}
|
||||
|
||||
// Elimina las cadenas vacías
|
||||
@@ -298,7 +298,7 @@ void Notifier::showText(std::vector<std::string> texts, int icon, const std::str
|
||||
bool Notifier::isActive() { return !notifications_.empty(); }
|
||||
|
||||
// Finaliza y elimnina todas las notificaciones activas
|
||||
void Notifier::clearNotifications()
|
||||
void Notifier::clearAllNotifications()
|
||||
{
|
||||
for (auto ¬ification : notifications_)
|
||||
{
|
||||
@@ -318,3 +318,9 @@ std::vector<std::string> Notifier::getCodes()
|
||||
}
|
||||
return codes;
|
||||
}
|
||||
|
||||
// Comprueba si hay alguna notificacion con un código
|
||||
bool Notifier::checkCode(std::string code)
|
||||
{
|
||||
return stringInVector(getCodes(), code);
|
||||
}
|
||||
@@ -13,7 +13,7 @@ class Texture; // lines 11-11
|
||||
class Notifier
|
||||
{
|
||||
private:
|
||||
// [SINGLETON] Objeto notifier privado para Don Melitón
|
||||
// [SINGLETON] Objeto notifier
|
||||
static Notifier *notifier_;
|
||||
|
||||
enum class NotificationStatus
|
||||
@@ -66,7 +66,7 @@ private:
|
||||
void clearFinishedNotifications();
|
||||
|
||||
// Finaliza y elimnina todas las notificaciones activas
|
||||
void clearNotifications();
|
||||
void clearAllNotifications();
|
||||
|
||||
// [SINGLETON] Ahora el constructor y el destructor son privados, para no poder crear objetos notifier desde fuera
|
||||
|
||||
@@ -77,13 +77,13 @@ private:
|
||||
~Notifier() = default;
|
||||
|
||||
public:
|
||||
// [SINGLETON] Crearemos el objeto notifier con esta función estática
|
||||
// [SINGLETON] Crearemos el objeto con esta función estática
|
||||
static void init(const std::string &icon_file, std::shared_ptr<Text> text);
|
||||
|
||||
// [SINGLETON] Destruiremos el objeto notifier con esta función estática
|
||||
// [SINGLETON] Destruiremos el objeto con esta función estática
|
||||
static void destroy();
|
||||
|
||||
// [SINGLETON] Con este método obtenemos el objeto notifier y podemos trabajar con él
|
||||
// [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él
|
||||
static Notifier *get();
|
||||
|
||||
// Dibuja las notificaciones por pantalla
|
||||
@@ -93,11 +93,14 @@ public:
|
||||
void update();
|
||||
|
||||
// Muestra una notificación de texto por pantalla
|
||||
void showText(std::vector<std::string> texts, int icon = -1, const std::string &code = std::string());
|
||||
void show(std::vector<std::string> texts, int icon = -1, const std::string &code = std::string());
|
||||
|
||||
// Indica si hay notificaciones activas
|
||||
bool isActive();
|
||||
|
||||
// Obtiene los códigos de las notificaciones
|
||||
std::vector<std::string> getCodes();
|
||||
|
||||
// Comprueba si hay alguna notificacion con un código
|
||||
bool checkCode(std::string code);
|
||||
};
|
||||
|
||||
@@ -25,7 +25,7 @@ void initOptions()
|
||||
options.video.window.size = 3;
|
||||
#else
|
||||
options.video.mode = ScreenVideoMode::WINDOW;
|
||||
options.video.window.size = 2;
|
||||
options.video.window.zoom = 2;
|
||||
#endif
|
||||
options.video.filter = ScreenFilter::NEAREST;
|
||||
options.video.v_sync = true;
|
||||
@@ -44,6 +44,7 @@ void initOptions()
|
||||
options.game.difficulty = GameDifficulty::NORMAL;
|
||||
options.game.language = lang::Code::ba_BA;
|
||||
options.game.autofire = true;
|
||||
options.game.clear_last_hi_score_entries();
|
||||
|
||||
// Opciones de control
|
||||
options.controllers.clear();
|
||||
@@ -104,7 +105,7 @@ bool loadOptionsFile(std::string file_path)
|
||||
options.video.mode = ScreenVideoMode::WINDOW;
|
||||
}
|
||||
|
||||
options.video.window.size = std::clamp(options.video.window.size, 1, 4);
|
||||
options.video.window.zoom = std::clamp(options.video.window.zoom, 1, 4);
|
||||
|
||||
if (options.game.language != lang::Code::en_UK &&
|
||||
options.game.language != lang::Code::ba_BA &&
|
||||
@@ -136,7 +137,7 @@ bool saveOptionsFile(std::string file_path)
|
||||
file << "\n";
|
||||
|
||||
file << "video.mode=" << static_cast<int>(options.video.mode) << "\n";
|
||||
file << "video.window.size=" << options.video.window.size << "\n";
|
||||
file << "video.window.size=" << options.video.window.zoom << "\n";
|
||||
file << "video.filter=" << static_cast<int>(options.video.filter) << "\n";
|
||||
file << "video.v_sync=" << boolToString(options.video.v_sync) << "\n";
|
||||
file << "video.integer_scale=" << boolToString(options.video.integer_scale) << "\n";
|
||||
@@ -203,10 +204,10 @@ bool setOptions(const std::string &var, const std::string &value)
|
||||
}
|
||||
else if (var == "video.window.size")
|
||||
{
|
||||
options.video.window.size = std::stoi(value);
|
||||
if ((options.video.window.size < 1) || (options.video.window.size > 4))
|
||||
options.video.window.zoom = std::stoi(value);
|
||||
if ((options.video.window.zoom < 1) || (options.video.window.zoom > 4))
|
||||
{
|
||||
options.video.window.size = 3;
|
||||
options.video.window.zoom = 3;
|
||||
}
|
||||
}
|
||||
else if (var == "video.filter")
|
||||
|
||||
@@ -1,16 +1,17 @@
|
||||
#pragma once
|
||||
|
||||
#include <SDL2/SDL_gamecontroller.h> // Para SDL_CONTROLLER_BUTTON_B, SDL_CO...
|
||||
#include <SDL2/SDL_stdinc.h> // Para Uint32
|
||||
#include <string> // Para string
|
||||
#include <vector> // Para vector
|
||||
#include "input.h" // Para InputType, InputDeviceToUse
|
||||
#include "manage_hiscore_table.h" // Para HiScoreEntry
|
||||
enum class ScreenFilter : int; // lines 10-10
|
||||
enum class ScreenVideoMode : int; // lines 11-11
|
||||
enum class ScreenFilter : int; // lines 8-8
|
||||
enum class ScreenVideoMode : Uint32; // lines 9-9
|
||||
namespace lang
|
||||
{
|
||||
enum class Code : int;
|
||||
} // lines 14-14
|
||||
} // lines 12-12
|
||||
|
||||
// Dificultad del juego
|
||||
enum class GameDifficulty
|
||||
@@ -23,8 +24,8 @@ enum class GameDifficulty
|
||||
// Estructura para las opciones de la ventana
|
||||
struct OptionsWindow
|
||||
{
|
||||
int size = 1; // Contiene el valor por el que se multiplica el tamaño de la ventana
|
||||
int max_size = 1; // Tamaño máximo para que el tamaño de la ventana no sea mayor que el tamaño de la pantalla
|
||||
int zoom = 1; // Contiene el valor por el que se multiplica el tamaño de la ventana
|
||||
int max_zoom = 1; // Tamaño máximo para que el tamaño de la ventana no sea mayor que el tamaño de la pantalla
|
||||
};
|
||||
|
||||
// Estructura con opciones para el video
|
||||
@@ -66,8 +67,16 @@ struct OptionsGame
|
||||
{
|
||||
GameDifficulty difficulty; // Dificultad del juego
|
||||
lang::Code language; // Idioma usado en el juego
|
||||
bool autofire; // Indica si el jugador ha de pulsar repetidamente para disparar o basta con mantener pulsado
|
||||
std::vector<HiScoreEntry> hi_score_table; // Tabla con las mejores puntuaciones
|
||||
bool autofire; // Indicador de autofire
|
||||
std::vector<HiScoreEntry> hi_score_table; // Tabla de mejores puntuaciones
|
||||
std::vector<int> last_hi_score_entry = {-1, -1}; // Inicialización directa con dos elementos en -1
|
||||
|
||||
// Método para reiniciar las últimas entradas de puntuación
|
||||
void clear_last_hi_score_entries()
|
||||
{
|
||||
last_hi_score_entry[0] = -1;
|
||||
last_hi_score_entry[1] = -1;
|
||||
}
|
||||
};
|
||||
|
||||
// Estructura para los controles del juego
|
||||
|
||||
@@ -26,6 +26,7 @@ void initParam()
|
||||
param.game.game_area.rect = {0, 0, param.game.width, param.game.height};
|
||||
param.game.play_area.rect = {0, 0, param.game.width, 216};
|
||||
param.game.enter_name_seconds = 30;
|
||||
param.game.speed = 15;
|
||||
precalculateZones();
|
||||
|
||||
// SCOREBOARD
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include <SDL2/SDL_rect.h> // Para SDL_Rect
|
||||
#include <SDL2/SDL_stdinc.h> // Para Uint32
|
||||
#include <string> // Para string
|
||||
#include <vector> // Para vector
|
||||
#include "utils.h" // Para Color, Zone
|
||||
@@ -16,6 +17,7 @@ struct ParamGame
|
||||
Zone play_area; // Rectangulo con la posición de la zona de juego
|
||||
Zone game_area; // Rectangulo con las dimensiones del juego
|
||||
int enter_name_seconds; // Duración en segundos para introducir el nombre al finalizar la partida
|
||||
Uint32 speed; // Velocidad a la que transcurre el juego
|
||||
};
|
||||
|
||||
// param.fade
|
||||
@@ -83,7 +85,5 @@ struct Param
|
||||
|
||||
extern Param param;
|
||||
|
||||
extern Param param;
|
||||
|
||||
// Establece valores para los parametros a partir de un fichero de texto
|
||||
void loadParamsFromFile(const std::string &file_path);
|
||||
@@ -15,13 +15,9 @@ std::vector<SDL_Point> createPath(int start, int end, PathType type, int fixed_p
|
||||
double t = static_cast<double>(i) / (steps - 1);
|
||||
double value = start + (end - start) * easingFunction(t);
|
||||
|
||||
if (start > 0 && end < 0)
|
||||
if ((start > 0 && end < 0) || (start < 0 && end > 0))
|
||||
{
|
||||
value = start - std::abs(end - start) * easingFunction(t);
|
||||
}
|
||||
else if (start < 0 && end > 0)
|
||||
{
|
||||
value = start + std::abs(end - start) * easingFunction(t);
|
||||
value = start + (end > 0 ? 1 : -1) * std::abs(end - start) * easingFunction(t);
|
||||
}
|
||||
|
||||
switch (type)
|
||||
@@ -43,13 +39,22 @@ std::vector<SDL_Point> createPath(int start, int end, PathType type, int fixed_p
|
||||
// Actualiza la posición y comprueba si ha llegado a su destino
|
||||
void PathSprite::update()
|
||||
{
|
||||
if (enabled_)
|
||||
if (enabled_ && !has_finished_)
|
||||
{
|
||||
moveThroughCurrentPath();
|
||||
goToNextPathOrDie();
|
||||
}
|
||||
}
|
||||
|
||||
// Muestra el sprite por pantalla
|
||||
void PathSprite::render()
|
||||
{
|
||||
if (enabled_)
|
||||
{
|
||||
Sprite::render();
|
||||
}
|
||||
}
|
||||
|
||||
// Añade un recorrido
|
||||
void PathSprite::addPath(Path path, bool centered)
|
||||
{
|
||||
@@ -96,7 +101,7 @@ void PathSprite::addPath(std::vector<SDL_Point> spots, int waiting_counter)
|
||||
// Habilita el objeto
|
||||
void PathSprite::enable()
|
||||
{
|
||||
if (paths_.size() == 0)
|
||||
if (paths_.size() == 0 || enabled_)
|
||||
{
|
||||
return;
|
||||
}
|
||||
@@ -105,8 +110,8 @@ void PathSprite::enable()
|
||||
|
||||
// Establece la posición
|
||||
auto &path = paths_.at(current_path_);
|
||||
const auto &p = path.spots.at(path.counter);
|
||||
setPosition(p);
|
||||
const auto &P = path.spots.at(path.counter);
|
||||
setPosition(P);
|
||||
}
|
||||
|
||||
// Coloca el sprite en los diferentes puntos del recorrido
|
||||
@@ -133,26 +138,32 @@ void PathSprite::moveThroughCurrentPath()
|
||||
if (path.on_destination)
|
||||
{
|
||||
if (path.waiting_counter == 0)
|
||||
{
|
||||
path.finished = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
--path.waiting_counter;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Cambia de recorrido o finaliza
|
||||
void PathSprite::goToNextPathOrDie()
|
||||
{
|
||||
// Comprueba si ha terminado el recorrdo actual
|
||||
if (paths_.at(current_path_).finished)
|
||||
{
|
||||
++current_path_;
|
||||
}
|
||||
|
||||
// Comprueba si quedan mas recorridos
|
||||
if (current_path_ >= static_cast<int>(paths_.size()))
|
||||
enabled_ = false;
|
||||
{
|
||||
has_finished_ = true;
|
||||
current_path_ = 0;
|
||||
}
|
||||
}
|
||||
|
||||
// Indica si ha terminado todos los recorridos
|
||||
bool PathSprite::hasFinished()
|
||||
{
|
||||
return !enabled_;
|
||||
}
|
||||
bool PathSprite::hasFinished() { return has_finished_; }
|
||||
@@ -43,6 +43,7 @@ class PathSprite : public Sprite
|
||||
private:
|
||||
// Variables
|
||||
bool enabled_ = false; // Indica si el objeto está habilitado
|
||||
bool has_finished_ = false; // Indica si el objeto ha finalizado el recorrido
|
||||
int current_path_ = 0; // Path que se está recorriendo actualmente
|
||||
std::vector<Path> paths_; // Caminos a recorrer por el sprite
|
||||
|
||||
@@ -63,10 +64,13 @@ public:
|
||||
// Actualiza la posición del sprite
|
||||
void update();
|
||||
|
||||
// Muestra el sprite por pantalla
|
||||
void render() override;
|
||||
|
||||
// Añade un recorrido
|
||||
void addPath(Path path, bool centered = false);
|
||||
void addPath(std::vector<SDL_Point> spots, int waiting_counter);
|
||||
void addPath(int start, int end, PathType type, int fixed_pos, int steps, const std::function<double(double)> &easingFunction, int waiting_counter);
|
||||
void addPath(std::vector<SDL_Point> spots, int waiting_counter = 0);
|
||||
void addPath(int start, int end, PathType type, int fixed_pos, int steps, const std::function<double(double)> &easingFunction, int waiting_counter = 0);
|
||||
|
||||
// Habilita el objeto
|
||||
void enable();
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
#include "resource.h"
|
||||
#include "jail_audio.h"
|
||||
#include "stage.h"
|
||||
#include <array>
|
||||
|
||||
// Constructor
|
||||
Player::Player(int id, float x, int y, bool demo, SDL_Rect &play_area, std::vector<std::shared_ptr<Texture>> texture, const std::vector<std::vector<std::string>> &animations)
|
||||
@@ -58,7 +59,7 @@ void Player::init()
|
||||
score_ = 0;
|
||||
score_multiplier_ = 1.0f;
|
||||
cool_down_ = 10;
|
||||
enter_name_->init();
|
||||
enter_name_->init(last_enter_name_);
|
||||
|
||||
// Establece la posición del sprite
|
||||
player_sprite_->clear();
|
||||
@@ -148,6 +149,12 @@ void Player::setInputEnteringName(InputType input)
|
||||
enter_name_->decIndex();
|
||||
break;
|
||||
case InputType::START:
|
||||
last_enter_name_ = getRecordName();
|
||||
if (last_enter_name_.empty())
|
||||
{
|
||||
const std::array<std::string, 8> NAMES = {"BAL1", "TABE", "DOC", "MON", "SAM1", "JORDI", "JDES", "PEPE"};
|
||||
last_enter_name_ = NAMES.at(rand() % NAMES.size());
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
@@ -165,9 +172,9 @@ void Player::move()
|
||||
pos_x_ += vel_x_;
|
||||
|
||||
// Si el jugador abandona el area de juego por los laterales, restaura su posición
|
||||
const float min_x = play_area_.x - 5;
|
||||
const float max_x = play_area_.w + 5 - WIDTH_;
|
||||
pos_x_ = std::clamp(pos_x_, min_x, max_x);
|
||||
const float MIN_X = play_area_.x - 5;
|
||||
const float MAX_X = play_area_.w + 5 - WIDTH_;
|
||||
pos_x_ = std::clamp(pos_x_, MIN_X, MAX_X);
|
||||
|
||||
shiftSprite();
|
||||
break;
|
||||
@@ -175,12 +182,12 @@ void Player::move()
|
||||
case PlayerState::DYING:
|
||||
{
|
||||
// Si el cadaver abandona el area de juego por los laterales lo hace rebotar
|
||||
const int x = player_sprite_->getPosX();
|
||||
const int min_x = play_area_.x;
|
||||
const int max_x = play_area_.x + play_area_.w - WIDTH_;
|
||||
if ((x < min_x) || (x > max_x))
|
||||
const int X = player_sprite_->getPosX();
|
||||
const int MIN_X = play_area_.x;
|
||||
const int MAX_X = play_area_.x + play_area_.w - WIDTH_;
|
||||
if ((X < MIN_X) || (X > MAX_X))
|
||||
{
|
||||
player_sprite_->setPosX(std::clamp(x, min_x, max_x));
|
||||
player_sprite_->setPosX(std::clamp(X, MIN_X, MAX_X));
|
||||
player_sprite_->setVelX(-player_sprite_->getVelX());
|
||||
playRandomBubbleSound();
|
||||
}
|
||||
@@ -286,7 +293,6 @@ void Player::move()
|
||||
{
|
||||
pos_x_ = param.game.game_area.rect.w - WIDTH_;
|
||||
vel_x_ *= -1;
|
||||
// setInputPlaying(InputType::LEFT);
|
||||
}
|
||||
}
|
||||
else
|
||||
@@ -296,7 +302,6 @@ void Player::move()
|
||||
{
|
||||
pos_x_ = param.game.game_area.rect.x;
|
||||
vel_x_ *= -1;
|
||||
// setInputPlaying(InputType::RIGHT);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -355,17 +360,20 @@ void Player::setAnimation()
|
||||
|
||||
// Establece la animación a partir de las cadenas
|
||||
if (firing_state_ == PlayerState::FIRING_NONE)
|
||||
{ // No esta disparando
|
||||
{
|
||||
// No esta disparando
|
||||
player_sprite_->setCurrentAnimation(a_walking);
|
||||
player_sprite_->setFlip(flip_walk);
|
||||
}
|
||||
else if (isCooling())
|
||||
{ // Acaba de disparar
|
||||
{
|
||||
// Acaba de disparar
|
||||
player_sprite_->setCurrentAnimation(a_walking + "-" + a_cooling + "-cooldown");
|
||||
player_sprite_->setFlip(flip_cooling);
|
||||
}
|
||||
else
|
||||
{ // Está disparando
|
||||
{
|
||||
// Está disparando
|
||||
player_sprite_->setCurrentAnimation(a_walking + "-" + a_firing);
|
||||
// Si dispara de lado, invierte el sprite segun hacia donde dispara
|
||||
// Si dispara recto, invierte el sprite segun hacia donde camina
|
||||
@@ -449,6 +457,7 @@ void Player::update()
|
||||
updateInvulnerable();
|
||||
updateContinueCounter();
|
||||
updateEnterNameCounter();
|
||||
updateShowingName();
|
||||
updateScoreboard();
|
||||
}
|
||||
|
||||
@@ -474,7 +483,7 @@ void Player::updateScoreboard()
|
||||
case PlayerState::ENTERING_NAME:
|
||||
case PlayerState::ENTERING_NAME_GAME_COMPLETED:
|
||||
{
|
||||
Scoreboard::get()->setRecordName(getScoreBoardPanel(), enter_name_->getName());
|
||||
Scoreboard::get()->setRecordName(getScoreBoardPanel(), enter_name_->getCurrentName());
|
||||
Scoreboard::get()->setSelectorPos(getScoreBoardPanel(), getRecordNamePos());
|
||||
break;
|
||||
}
|
||||
@@ -525,12 +534,19 @@ void Player::setPlayingState(PlayerState state)
|
||||
setScoreboardMode(ScoreboardMode::ENTER_NAME);
|
||||
break;
|
||||
}
|
||||
case PlayerState::SHOWING_NAME:
|
||||
{
|
||||
showing_name_ticks_ = SDL_GetTicks();
|
||||
setScoreboardMode(ScoreboardMode::SHOW_NAME);
|
||||
Scoreboard::get()->setRecordName(scoreboard_panel_, last_enter_name_);
|
||||
break;
|
||||
}
|
||||
case PlayerState::DYING:
|
||||
{
|
||||
// Activa la animación de morir
|
||||
player_sprite_->setAccelY(0.2f);
|
||||
player_sprite_->setVelY(-6.6f);
|
||||
rand() % 2 == 0 ? player_sprite_->setVelX(3.3f) : player_sprite_->setVelX(-3.3f);
|
||||
(rand() % 2 == 0) ? player_sprite_->setVelX(3.3f) : player_sprite_->setVelX(-3.3f);
|
||||
break;
|
||||
}
|
||||
case PlayerState::DIED:
|
||||
@@ -546,6 +562,7 @@ void Player::setPlayingState(PlayerState state)
|
||||
}
|
||||
case PlayerState::CELEBRATING:
|
||||
{
|
||||
game_completed_ = true;
|
||||
setScoreboardMode(ScoreboardMode::SCORE);
|
||||
break;
|
||||
}
|
||||
@@ -711,6 +728,19 @@ void Player::updateEnterNameCounter()
|
||||
}
|
||||
}
|
||||
|
||||
// Actualiza el estado de SHOWING_NAME
|
||||
void Player::updateShowingName()
|
||||
{
|
||||
if (playing_state_ == PlayerState::SHOWING_NAME)
|
||||
{
|
||||
constexpr int TICKS_SPEED = 5000;
|
||||
if (SDL_GetTicks() - enter_name_ticks_ > TICKS_SPEED)
|
||||
{
|
||||
game_completed_ ? setPlayingState(PlayerState::LEAVING_SCREEN) : setPlayingState(PlayerState::CONTINUE);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Decrementa el contador de continuar
|
||||
void Player::decContinueCounter()
|
||||
{
|
||||
|
||||
@@ -34,6 +34,7 @@ enum class PlayerState
|
||||
CONTINUE, // Está con la cuenta atras para continuar
|
||||
WAITING, // No está jugando pero puede entrar a jugar
|
||||
ENTERING_NAME, // Introduciendo nombre
|
||||
SHOWING_NAME, // Mostrando el nombre introducido
|
||||
DYING, // El cadaver está volando por ahi
|
||||
DIED, // El cadaver ha desaparecido por el fondo
|
||||
GAME_OVER, // No está jugando y no puede entrar a jugar
|
||||
@@ -92,7 +93,11 @@ private:
|
||||
bool demo_; // Para que el jugador sepa si está en el modo demostración
|
||||
int enter_name_counter_; // Contador para poner nombre
|
||||
Uint32 enter_name_ticks_ = 0; // Variable para poder cambiar el contador de poner nombre en función del tiempo
|
||||
Uint32 showing_name_ticks_ = 0; // Tiempo en el que se entra al estado SHOWING_NAME
|
||||
int step_counter_ = 0; // Cuenta los pasos para los estados en los que camina automáticamente
|
||||
bool game_completed_ = false; // Indica si ha completado el juego
|
||||
int credits_used_ = 1; // Indica el numero de veces que ha continuado
|
||||
std::string last_enter_name_; // Ultimo nombre introducido en la tabla de puntuaciones
|
||||
|
||||
// Actualiza el circulo de colisión a la posición del jugador
|
||||
void shiftColliders();
|
||||
@@ -109,6 +114,9 @@ private:
|
||||
// Actualiza el contador de entrar nombre
|
||||
void updateEnterNameCounter();
|
||||
|
||||
// Actualiza el estado de SHOWING_NAME
|
||||
void updateShowingName();
|
||||
|
||||
// Decrementa el contador de entrar nombre
|
||||
void decEnterNameCounter();
|
||||
|
||||
@@ -200,6 +208,7 @@ public:
|
||||
bool isContinue() const { return playing_state_ == PlayerState::CONTINUE; }
|
||||
bool isDying() const { return playing_state_ == PlayerState::DYING; }
|
||||
bool isEnteringName() const { return playing_state_ == PlayerState::ENTERING_NAME; }
|
||||
bool isShowingName() const { return playing_state_ == PlayerState::SHOWING_NAME; }
|
||||
bool isEnteringNameGameCompleted() const { return playing_state_ == PlayerState::ENTERING_NAME_GAME_COMPLETED; }
|
||||
bool isLeavingScreen() const { return playing_state_ == PlayerState::LEAVING_SCREEN; }
|
||||
bool isGameOver() const { return playing_state_ == PlayerState::GAME_OVER; }
|
||||
@@ -224,12 +233,14 @@ public:
|
||||
int getPosX() const { return static_cast<int>(pos_x_); }
|
||||
int getPosY() const { return pos_y_; }
|
||||
int getPowerUpCounter() const { return power_up_counter_; }
|
||||
std::string getRecordName() const { return enter_name_->getName(); }
|
||||
std::string getRecordName() const { return enter_name_->getFinalName(); }
|
||||
int getScore() const { return score_; }
|
||||
int getScoreBoardPanel() const { return scoreboard_panel_; }
|
||||
int getWidth() const { return WIDTH_; }
|
||||
PlayerState getPlayingState() const { return playing_state_; }
|
||||
std::string getName() const { return name_; }
|
||||
bool get1CC() const { return game_completed_ && credits_used_ == 1; }
|
||||
bool getEnterNamePositionOverflow() const { return enter_name_->getPositionOverflow(); }
|
||||
|
||||
// Setters
|
||||
void setController(int index) { controller_index_ = index; }
|
||||
@@ -242,4 +253,5 @@ public:
|
||||
void setScoreBoardPanel(int panel) { scoreboard_panel_ = panel; }
|
||||
void setScoreMultiplier(float value) { score_multiplier_ = value; }
|
||||
void setWalkingState(PlayerState state) { walking_state_ = state; }
|
||||
void addCredit() { ++credits_used_; }
|
||||
};
|
||||
|
||||
@@ -2,14 +2,13 @@
|
||||
#include <algorithm> // Para find_if
|
||||
#include <iostream> // Para basic_ostream, operator<<, endl, cout, cerr
|
||||
#include <stdexcept> // Para runtime_error
|
||||
#include <utility> // Para pair
|
||||
#include "asset.h" // Para Asset, AssetType
|
||||
#include "jail_audio.h" // Para JA_LoadMusic, JA_LoadSound
|
||||
#include "jail_audio.h" // Para JA_DeleteMusic, JA_DeleteSound, JA_LoadMusic
|
||||
#include "lang.h" // Para getText
|
||||
#include "screen.h" // Para Screen
|
||||
#include "text.h" // Para Text, loadTextFile
|
||||
struct JA_Music_t; // lines 10-10
|
||||
struct JA_Sound_t; // lines 11-11
|
||||
struct JA_Music_t; // lines 11-11
|
||||
struct JA_Sound_t; // lines 12-12
|
||||
|
||||
// [SINGLETON] Hay que definir las variables estáticas, desde el .h sólo la hemos declarado
|
||||
Resource *Resource::resource_ = nullptr;
|
||||
@@ -73,6 +72,14 @@ void Resource::reload()
|
||||
load();
|
||||
}
|
||||
|
||||
// Recarga las texturas
|
||||
void Resource::reloadTextures()
|
||||
{
|
||||
loadTextures();
|
||||
addPalettes();
|
||||
createTextures();
|
||||
}
|
||||
|
||||
// Obtiene el sonido a partir de un nombre
|
||||
JA_Sound_t *Resource::getSound(const std::string &name)
|
||||
{
|
||||
@@ -301,6 +308,7 @@ void Resource::createTextures()
|
||||
|
||||
// Tamaño doble
|
||||
std::vector<NameAndText> strings2X = {
|
||||
NameAndText("game_text_100000_points", "100.000"),
|
||||
NameAndText("game_text_get_ready", lang::getText(75)),
|
||||
NameAndText("game_text_last_stage", lang::getText(79)),
|
||||
NameAndText("game_text_congratulations", lang::getText(50)),
|
||||
@@ -314,22 +322,35 @@ void Resource::createTextures()
|
||||
}
|
||||
}
|
||||
|
||||
// Crea los objetos de texto
|
||||
void Resource::createText()
|
||||
{
|
||||
struct ResourceInfo
|
||||
{
|
||||
std::string key; // Identificador del recurso
|
||||
std::string textureFile; // Nombre del archivo de textura
|
||||
std::string textFile; // Nombre del archivo de texto
|
||||
|
||||
// Constructor para facilitar la creación de objetos ResourceInfo
|
||||
ResourceInfo(const std::string &k, const std::string &tFile, const std::string &txtFile)
|
||||
: key(k), textureFile(tFile), textFile(txtFile) {}
|
||||
};
|
||||
|
||||
std::cout << "\n>> CREATING TEXT_OBJECTS" << std::endl;
|
||||
|
||||
std::vector<std::pair<std::string, std::string>> resources = {
|
||||
{"04b_25", "04b_25.png"},
|
||||
{"04b_25_2x", "04b_25_2x.png"},
|
||||
{"8bithud", "8bithud.png"},
|
||||
{"nokia", "nokia.png"},
|
||||
{"smb2", "smb2.gif"}};
|
||||
std::vector<ResourceInfo> resources = {
|
||||
{"04b_25", "04b_25.png", "04b_25.txt"},
|
||||
{"04b_25_2x", "04b_25_2x.png", "04b_25_2x.txt"},
|
||||
{"04b_25_metal", "04b_25_metal.png", "04b_25.txt"},
|
||||
{"04b_25_grey", "04b_25_grey.png", "04b_25.txt"},
|
||||
{"8bithud", "8bithud.png", "8bithud.txt"},
|
||||
{"smb2", "smb2.gif", "smb2.txt"}};
|
||||
|
||||
for (const auto &resource : resources)
|
||||
{
|
||||
texts_.emplace_back(ResourceText(resource.first, std::make_shared<Text>(getTexture(resource.second), getTextFile(resource.first + ".txt"))));
|
||||
printWithDots("Text : ", resource.first, "[ DONE ]");
|
||||
texts_.emplace_back(ResourceText(resource.key, std::make_shared<Text>(
|
||||
getTexture(resource.textureFile),
|
||||
getTextFile(resource.textFile))));
|
||||
printWithDots("Text : ", resource.key, "[ DONE ]");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -170,4 +170,7 @@ public:
|
||||
|
||||
// Recarga todos los recursos
|
||||
void reload();
|
||||
|
||||
// Recarga las texturas
|
||||
void reloadTextures();
|
||||
};
|
||||
@@ -5,12 +5,12 @@
|
||||
#include <math.h> // Para roundf
|
||||
#include <iomanip> // Para operator<<, setfill, setw
|
||||
#include <sstream> // Para basic_ostream, basic_ostringstream
|
||||
#include "enter_name.h" // Para MAX_NAME_LENGHT
|
||||
#include "lang.h" // Para getText
|
||||
#include "resource.h" // Para Resource
|
||||
#include "screen.h" // Para Screen
|
||||
#include "sprite.h" // Para Sprite
|
||||
#include "text.h" // Para Text
|
||||
#include "enter_name.h"
|
||||
#include "text.h" // Para Text, TEXT_CENTER, TEXT_COLOR
|
||||
|
||||
// [SINGLETON] Hay que definir las variables estáticas, desde el .h sólo la hemos declarado
|
||||
Scoreboard *Scoreboard::scoreboard_ = nullptr;
|
||||
@@ -68,6 +68,9 @@ Scoreboard::Scoreboard()
|
||||
|
||||
// Rellena la textura de fondo
|
||||
fillBackgroundTexture();
|
||||
|
||||
// Inicializa el vector de colores para el nombre
|
||||
iniNameColors();
|
||||
}
|
||||
|
||||
Scoreboard::~Scoreboard()
|
||||
@@ -86,23 +89,23 @@ Scoreboard::~Scoreboard()
|
||||
}
|
||||
}
|
||||
|
||||
// Transforma un valor numérico en una cadena de 6 cifras
|
||||
// Transforma un valor numérico en una cadena de 7 cifras
|
||||
std::string Scoreboard::updateScoreText(int num)
|
||||
{
|
||||
std::ostringstream oss;
|
||||
oss << std::setw(8) << std::setfill('0') << num;
|
||||
oss << std::setw(7) << std::setfill('0') << num;
|
||||
return oss.str();
|
||||
}
|
||||
|
||||
// Actualiza el contador
|
||||
void Scoreboard::updateCounter()
|
||||
void Scoreboard::updateTimeCounter()
|
||||
{
|
||||
constexpr int TICKS_SPEED = 100;
|
||||
|
||||
if (SDL_GetTicks() - ticks_ > TICKS_SPEED)
|
||||
{
|
||||
ticks_ = SDL_GetTicks();
|
||||
counter_++;
|
||||
++time_counter_;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -110,7 +113,8 @@ void Scoreboard::updateCounter()
|
||||
void Scoreboard::update()
|
||||
{
|
||||
fillBackgroundTexture();
|
||||
updateCounter();
|
||||
updateTimeCounter();
|
||||
++loop_counter_;
|
||||
}
|
||||
|
||||
// Pinta el marcador
|
||||
@@ -150,7 +154,7 @@ void Scoreboard::fillPanelTextures()
|
||||
// Guarda a donde apunta actualmente el renderizador
|
||||
auto temp = SDL_GetRenderTarget(renderer_);
|
||||
|
||||
// Genera el contenidoi de cada panel_
|
||||
// Genera el contenido de cada panel_
|
||||
for (size_t i = 0; i < SCOREBOARD_MAX_PANELS; ++i)
|
||||
{
|
||||
// Cambia el destino del renderizador
|
||||
@@ -180,7 +184,7 @@ void Scoreboard::fillPanelTextures()
|
||||
text_scoreboard_->writeCentered(slot4_1_.x, slot4_1_.y + 4, lang::getText(101));
|
||||
|
||||
// PRESS START TO PLAY
|
||||
if (counter_ % 10 < 8)
|
||||
if (time_counter_ % 10 < 8)
|
||||
{
|
||||
text_scoreboard_->writeCentered(slot4_3_.x, slot4_3_.y - 2, lang::getText(103));
|
||||
text_scoreboard_->writeCentered(slot4_4_.x, slot4_4_.y - 2, lang::getText(104));
|
||||
@@ -194,7 +198,7 @@ void Scoreboard::fillPanelTextures()
|
||||
text_scoreboard_->writeCentered(slot4_1_.x, slot4_1_.y + 4, lang::getText(102));
|
||||
|
||||
// PRESS START TO PLAY
|
||||
if (counter_ % 10 < 8)
|
||||
if (time_counter_ % 10 < 8)
|
||||
{
|
||||
text_scoreboard_->writeCentered(slot4_3_.x, slot4_3_.y - 2, lang::getText(103));
|
||||
text_scoreboard_->writeCentered(slot4_4_.x, slot4_4_.y - 2, lang::getText(104));
|
||||
@@ -208,7 +212,7 @@ void Scoreboard::fillPanelTextures()
|
||||
text_scoreboard_->writeCentered(slot4_1_.x, slot4_1_.y + 4, lang::getText(102));
|
||||
|
||||
// PLEASE WAIT
|
||||
if (counter_ % 10 < 8)
|
||||
if (time_counter_ % 10 < 8)
|
||||
{
|
||||
text_scoreboard_->writeCentered(slot4_3_.x, slot4_3_.y - 2, lang::getText(114));
|
||||
text_scoreboard_->writeCentered(slot4_4_.x, slot4_4_.y - 2, lang::getText(115));
|
||||
@@ -253,18 +257,46 @@ void Scoreboard::fillPanelTextures()
|
||||
text_scoreboard_->writeCentered(slot4_2_.x, slot4_2_.y, updateScoreText(score_[i]));
|
||||
|
||||
// ENTER NAME
|
||||
{
|
||||
text_scoreboard_->writeCentered(slot4_3_.x, slot4_3_.y, lang::getText(106));
|
||||
SDL_Rect rect = {enter_name_pos_.x, enter_name_pos_.y, 5, 7};
|
||||
SDL_SetRenderDrawColor(renderer_, 0xFF, 0xFF, 0xEB, 255);
|
||||
for (size_t j = 0; j < record_name_[i].size(); ++j)
|
||||
|
||||
// Recorre todos los slots de letras del nombre
|
||||
for (size_t j = 0; j < MAX_NAME_LENGHT; ++j)
|
||||
{
|
||||
if (j != selector_pos_[i] || counter_ % 3 == 0)
|
||||
// Selecciona el color
|
||||
const Color color = j < selector_pos_[i] ? orange_soft_color.lighten() : Color(0xFF, 0xFF, 0xEB);
|
||||
|
||||
if (j != selector_pos_[i] || time_counter_ % 3 == 0)
|
||||
{
|
||||
// Dibuja la linea
|
||||
if (j >= selector_pos_[i])
|
||||
{
|
||||
SDL_SetRenderDrawColor(renderer_, color.r, color.g, color.b, 255);
|
||||
SDL_RenderDrawLine(renderer_, rect.x, rect.y + rect.h, rect.x + rect.w, rect.y + rect.h);
|
||||
text_scoreboard_->write(rect.x, rect.y, record_name_[i].substr(j, 1));
|
||||
}
|
||||
|
||||
// Dibuja la letra
|
||||
if (j < record_name_->size())
|
||||
{
|
||||
text_scoreboard_->writeColored(rect.x, rect.y, record_name_[i].substr(j, 1), color);
|
||||
}
|
||||
}
|
||||
rect.x += 7;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
case ScoreboardMode::SHOW_NAME:
|
||||
{
|
||||
// SCORE
|
||||
text_scoreboard_->writeCentered(slot4_1_.x, slot4_1_.y, name_[i]);
|
||||
text_scoreboard_->writeCentered(slot4_2_.x, slot4_2_.y, updateScoreText(score_[i]));
|
||||
|
||||
// NAME
|
||||
text_scoreboard_->writeCentered(slot4_3_.x, slot4_3_.y, lang::getText(106));
|
||||
text_scoreboard_->writeDX(TEXT_CENTER | TEXT_COLOR, slot4_4_.x, slot4_4_.y, record_name_[i], 1, getColorLikeKnightRider(name_colors_, loop_counter_ / 5));
|
||||
// text_scoreboard_->writeColored(enter_name_pos_.x, enter_name_pos_.y, record_name_[i], getColorLikeKnightRider(name_colors_, loop_counter_ / 5));
|
||||
break;
|
||||
}
|
||||
case ScoreboardMode::GAME_COMPLETED:
|
||||
@@ -273,7 +305,7 @@ void Scoreboard::fillPanelTextures()
|
||||
text_scoreboard_->writeCentered(slot4_1_.x, slot4_1_.y + 4, lang::getText(102));
|
||||
|
||||
// SCORE
|
||||
if (counter_ % 10 < 8)
|
||||
if (time_counter_ % 10 < 8)
|
||||
{
|
||||
text_scoreboard_->writeCentered(slot4_3_.x, slot4_3_.y - 2, lang::getText(120));
|
||||
text_scoreboard_->writeCentered(slot4_4_.x, slot4_4_.y - 2, updateScoreText(score_[i]));
|
||||
@@ -319,27 +351,27 @@ void Scoreboard::fillBackgroundTexture()
|
||||
void Scoreboard::recalculateAnchors()
|
||||
{
|
||||
// Recalcula la posición y el tamaño de los paneles
|
||||
const float panelWidth = (float)rect_.w / (float)SCOREBOARD_MAX_PANELS;
|
||||
const float panel_width = (float)rect_.w / (float)SCOREBOARD_MAX_PANELS;
|
||||
for (int i = 0; i < SCOREBOARD_MAX_PANELS; ++i)
|
||||
{
|
||||
panel_[i].pos.x = roundf(panelWidth * i);
|
||||
panel_[i].pos.x = roundf(panel_width * i);
|
||||
panel_[i].pos.y = 0;
|
||||
panel_[i].pos.w = roundf(panelWidth * (i + 1)) - panel_[i].pos.x;
|
||||
panel_[i].pos.w = roundf(panel_width * (i + 1)) - panel_[i].pos.x;
|
||||
panel_[i].pos.h = rect_.h;
|
||||
}
|
||||
|
||||
// Constantes para definir las zonas del panel_: 4 filas y 1 columna
|
||||
const int rowSize = rect_.h / 4;
|
||||
const int textHeight = 7;
|
||||
const int row_size = rect_.h / 4;
|
||||
const int text_height = 7;
|
||||
|
||||
// Filas
|
||||
const int row1 = (rowSize * 0) + (textHeight / 2);
|
||||
const int row2 = (rowSize * 1) + (textHeight / 2) - 1;
|
||||
const int row3 = (rowSize * 2) + (textHeight / 2) - 2;
|
||||
const int row4 = (rowSize * 3) + (textHeight / 2) - 3;
|
||||
const int row1 = (row_size * 0) + (text_height / 2);
|
||||
const int row2 = (row_size * 1) + (text_height / 2) - 1;
|
||||
const int row3 = (row_size * 2) + (text_height / 2) - 2;
|
||||
const int row4 = (row_size * 3) + (text_height / 2) - 3;
|
||||
|
||||
// Columna
|
||||
const int col = panelWidth / 2;
|
||||
const int col = panel_width / 2;
|
||||
|
||||
// Slots de 4
|
||||
slot4_1_ = {col, row1};
|
||||
@@ -348,8 +380,8 @@ void Scoreboard::recalculateAnchors()
|
||||
slot4_4_ = {col, row4};
|
||||
|
||||
// Primer cuadrado para poner el nombre de record
|
||||
const int enterNameLenght = NAME_LENGHT * 7;
|
||||
enter_name_pos_.x = (panelWidth - enterNameLenght) / 2;
|
||||
const int enter_name_lenght = text_scoreboard_->lenght(std::string(MAX_NAME_LENGHT, 'A'));
|
||||
enter_name_pos_.x = col - (enter_name_lenght / 2);
|
||||
enter_name_pos_.y = row4;
|
||||
|
||||
// Recoloca los sprites
|
||||
@@ -403,3 +435,16 @@ void Scoreboard::renderSeparator()
|
||||
SDL_SetRenderDrawColor(renderer_, separator_color.r, separator_color.g, separator_color.b, 255);
|
||||
SDL_RenderDrawLine(renderer_, 0, 0, rect_.w, 0);
|
||||
}
|
||||
|
||||
// Inicializa el vector de colores para el nombre
|
||||
void Scoreboard::iniNameColors()
|
||||
{
|
||||
// Color color = orange_soft_color;
|
||||
Color color = green_color;
|
||||
|
||||
name_colors_.clear();
|
||||
name_colors_.emplace_back(color.lighten(50));
|
||||
name_colors_.emplace_back(color.lighten(25));
|
||||
name_colors_.emplace_back(color);
|
||||
name_colors_.emplace_back(color.darken(25));
|
||||
}
|
||||
@@ -29,6 +29,7 @@ enum class ScoreboardMode : int
|
||||
GAME_OVER,
|
||||
DEMO,
|
||||
ENTER_NAME,
|
||||
SHOW_NAME,
|
||||
GAME_COMPLETED,
|
||||
NUM_MODES,
|
||||
};
|
||||
@@ -72,7 +73,9 @@ private:
|
||||
Color color_ = Color(); // Color del marcador
|
||||
SDL_Rect rect_ = {0, 0, 320, 40}; // Posición y dimensiones del marcador
|
||||
Uint32 ticks_ = SDL_GetTicks(); // Variable donde almacenar el valor de SDL_GetTiks()
|
||||
int counter_ = 0; // Contador
|
||||
int time_counter_ = 0; // Contador de segundos
|
||||
int loop_counter_ = 0; // Contador de bucle
|
||||
std::vector<Color> name_colors_; // Colores para destacar el nombre una vez introducido
|
||||
|
||||
// Puntos predefinidos para colocar elementos en los paneles
|
||||
SDL_Point slot4_1_, slot4_2_, slot4_3_, slot4_4_;
|
||||
@@ -81,7 +84,7 @@ private:
|
||||
// Recalcula las anclas de los elementos
|
||||
void recalculateAnchors();
|
||||
|
||||
// Transforma un valor numérico en una cadena de 6 cifras
|
||||
// Transforma un valor numérico en una cadena de 7 cifras
|
||||
std::string updateScoreText(int num);
|
||||
|
||||
// Crea la textura de fondo
|
||||
@@ -97,11 +100,14 @@ private:
|
||||
void fillBackgroundTexture();
|
||||
|
||||
// Actualiza el contador
|
||||
void updateCounter();
|
||||
void updateTimeCounter();
|
||||
|
||||
// Dibuja la linea que separa la zona de juego del marcador
|
||||
void renderSeparator();
|
||||
|
||||
// Inicializa el vector de colores para el nombre
|
||||
void iniNameColors();
|
||||
|
||||
// [SINGLETON] Ahora el constructor y el destructor son privados
|
||||
|
||||
// Constructor
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
#include "screen.h"
|
||||
#include <SDL2/SDL_events.h> // Para SDL_DISABLE, SDL_ENABLE
|
||||
#include <SDL2/SDL_mouse.h> // Para SDL_ShowCursor
|
||||
#include <SDL2/SDL_pixels.h> // Para SDL_PIXELFORMAT_RGBA8888
|
||||
#include <SDL2/SDL_timer.h> // Para SDL_GetTicks
|
||||
#include <algorithm> // Para clamp, max, min
|
||||
#include <algorithm> // Para max, min
|
||||
#include <fstream> // Para basic_ifstream, ifstream
|
||||
#include <iterator> // Para istreambuf_iterator, operator==
|
||||
#include <string> // Para allocator, operator+, char_traits, to_s...
|
||||
@@ -11,35 +9,23 @@
|
||||
#include "asset.h" // Para Asset
|
||||
#include "dbgtxt.h" // Para dbg_print
|
||||
#include "global_inputs.h" // Para service_pressed_counter
|
||||
#include "jail_shader.h" // Para init, render
|
||||
#include "mouse.h" // Para updateCursorVisibility
|
||||
#include "notifier.h" // Para Notifier
|
||||
#include "on_screen_help.h" // Para OnScreenHelp
|
||||
#include "options.h" // Para Options, OptionsVideo, options, Options...
|
||||
#include "mouse.h"
|
||||
|
||||
#ifndef NO_SHADERS
|
||||
#include "jail_shader.h" // para init, render
|
||||
#endif
|
||||
|
||||
// [SINGLETON] Hay que definir las variables estáticas, desde el .h sólo la hemos declarado
|
||||
// [SINGLETON]
|
||||
Screen *Screen::screen_ = nullptr;
|
||||
|
||||
// [SINGLETON] Crearemos el objeto screen con esta función estática
|
||||
void Screen::init(SDL_Window *window, SDL_Renderer *renderer)
|
||||
{
|
||||
Screen::screen_ = new Screen(window, renderer);
|
||||
}
|
||||
// [SINGLETON] Crearemos el objeto con esta función estática
|
||||
void Screen::init(SDL_Window *window, SDL_Renderer *renderer) { Screen::screen_ = new Screen(window, renderer); }
|
||||
|
||||
// [SINGLETON] Destruiremos el objeto screen con esta función estática
|
||||
void Screen::destroy()
|
||||
{
|
||||
delete Screen::screen_;
|
||||
}
|
||||
// [SINGLETON] Destruiremos el objeto con esta función estática
|
||||
void Screen::destroy() { delete Screen::screen_; }
|
||||
|
||||
// [SINGLETON] Con este método obtenemos el objeto screen y podemos trabajar con él
|
||||
Screen *Screen::get()
|
||||
{
|
||||
return Screen::screen_;
|
||||
}
|
||||
// [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él
|
||||
Screen *Screen::get() { return Screen::screen_; }
|
||||
|
||||
// Constructor
|
||||
Screen::Screen(SDL_Window *window, SDL_Renderer *renderer)
|
||||
@@ -53,19 +39,17 @@ Screen::Screen(SDL_Window *window, SDL_Renderer *renderer)
|
||||
SDL_DisplayMode DM;
|
||||
SDL_GetCurrentDisplayMode(0, &DM);
|
||||
info_resolution_ = std::to_string(DM.w) + " X " + std::to_string(DM.h) + " AT " + std::to_string(DM.refresh_rate) + " HZ";
|
||||
adjustRenderLogicalSize();
|
||||
|
||||
// Establece el modo de video
|
||||
setVideoMode(options.video.mode);
|
||||
// Inicializa los shaders
|
||||
initShaders();
|
||||
|
||||
// Muestra la ventana
|
||||
SDL_ShowWindow(window_);
|
||||
show();
|
||||
}
|
||||
|
||||
// Destructor
|
||||
Screen::~Screen()
|
||||
{
|
||||
SDL_DestroyTexture(game_canvas_);
|
||||
}
|
||||
Screen::~Screen() { SDL_DestroyTexture(game_canvas_); }
|
||||
|
||||
// Limpia la pantalla
|
||||
void Screen::clean(Color color)
|
||||
@@ -75,152 +59,105 @@ void Screen::clean(Color color)
|
||||
}
|
||||
|
||||
// Prepara para empezar a dibujar en la textura de juego
|
||||
void Screen::start()
|
||||
{
|
||||
SDL_SetRenderTarget(renderer_, game_canvas_);
|
||||
}
|
||||
void Screen::start() { SDL_SetRenderTarget(renderer_, game_canvas_); }
|
||||
|
||||
// Vuelca el contenido del renderizador en pantalla
|
||||
void Screen::render()
|
||||
{
|
||||
// Actualiza el contador de FPS
|
||||
++fps_counter_;
|
||||
// Renderiza todos los overlays y efectos
|
||||
renderOverlays();
|
||||
|
||||
// Dibuja efectos y elementos sobre el game_canvas_
|
||||
renderFlash();
|
||||
renderAttenuate();
|
||||
OnScreenHelp::get()->render();
|
||||
renderInfo();
|
||||
Notifier::get()->render();
|
||||
|
||||
// Restablece el objetivo de renderizado al buffer de pantalla predeterminado
|
||||
SDL_SetRenderTarget(renderer_, nullptr);
|
||||
|
||||
// Renderiza el contenido del game_canvas_ o aplica shaders según configuración
|
||||
// Renderiza el contenido del game_canvas_
|
||||
renderScreen();
|
||||
}
|
||||
|
||||
// Selecciona y ejecuta el método de renderizado adecuado basado en la configuración de shaders
|
||||
// Renderiza el contenido del game_canvas_
|
||||
void Screen::renderScreen()
|
||||
{
|
||||
#ifdef NO_SHADERS
|
||||
// Actualiza la pantalla con el contenido del game_canvas_
|
||||
presentGameCanvas();
|
||||
#else
|
||||
SDL_SetRenderTarget(renderer_, nullptr);
|
||||
clean();
|
||||
|
||||
if (options.video.shaders)
|
||||
{
|
||||
// Aplica shaders y renderiza el contenido
|
||||
shader::render();
|
||||
}
|
||||
else
|
||||
{
|
||||
// Actualiza la pantalla con el contenido del game_canvas_
|
||||
presentGameCanvas();
|
||||
SDL_RenderCopy(renderer_, game_canvas_, nullptr, nullptr);
|
||||
SDL_RenderPresent(renderer_);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
// Establece el modo de video
|
||||
void Screen::setVideoMode(ScreenVideoMode videoMode)
|
||||
void Screen::setVideoMode(ScreenVideoMode video_mode)
|
||||
{
|
||||
#ifdef ARCADE
|
||||
options.video.mode = ScreenVideoMode::WINDOW;
|
||||
#else
|
||||
options.video.mode = videoMode;
|
||||
#endif
|
||||
// Actualiza las opciones
|
||||
options.video.mode = video_mode;
|
||||
|
||||
switch (options.video.mode)
|
||||
// Configura el modo de pantalla
|
||||
Uint32 flags = SDL_GetWindowFlags(window_);
|
||||
if (flags != static_cast<Uint32>(options.video.mode))
|
||||
{
|
||||
case ScreenVideoMode::WINDOW:
|
||||
{
|
||||
// Cambia a modo de ventana
|
||||
SDL_SetWindowFullscreen(window_, 0);
|
||||
|
||||
#ifdef ARCADE
|
||||
// Oculta el puntero
|
||||
SDL_ShowCursor(SDL_DISABLE);
|
||||
#else
|
||||
// Muestra el puntero
|
||||
SDL_ShowCursor(SDL_ENABLE);
|
||||
#endif
|
||||
// Modifica el tamaño de la ventana
|
||||
SDL_Point pos = getNewPosition();
|
||||
SDL_SetWindowSize(window_, param.game.width * options.video.window.size, param.game.height * options.video.window.size);
|
||||
SDL_SetWindowPosition(window_, pos.x, pos.y);
|
||||
|
||||
break;
|
||||
SDL_SetWindowFullscreen(window_, static_cast<Uint32>(options.video.mode));
|
||||
}
|
||||
|
||||
// Si está activo el modo de pantalla completa añade el borde
|
||||
case ScreenVideoMode::FULLSCREEN:
|
||||
{
|
||||
// Aplica el modo de video
|
||||
SDL_SetWindowFullscreen(window_, SDL_WINDOW_FULLSCREEN_DESKTOP);
|
||||
|
||||
// Oculta el puntero
|
||||
SDL_ShowCursor(SDL_DISABLE);
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
// Reinicia los shaders
|
||||
if (options.video.shaders)
|
||||
{
|
||||
#ifndef NO_SHADERS
|
||||
const std::string glsl_file = param.game.game_area.rect.h == 256 ? "crtpi_256.glsl" : "crtpi_240.glsl";
|
||||
std::ifstream f(Asset::get()->get(glsl_file).c_str());
|
||||
std::string source((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());
|
||||
|
||||
shader::init(window_, game_canvas_, source.c_str());
|
||||
#endif
|
||||
}
|
||||
initShaders();
|
||||
}
|
||||
|
||||
// Camibia entre pantalla completa y ventana
|
||||
void Screen::toggleVideoMode()
|
||||
{
|
||||
options.video.mode = options.video.mode == ScreenVideoMode::WINDOW ? ScreenVideoMode::FULLSCREEN : ScreenVideoMode::WINDOW;
|
||||
setVideoMode(options.video.mode);
|
||||
setVideoMode();
|
||||
}
|
||||
|
||||
// Cambia el tamaño de la ventana
|
||||
void Screen::setWindowSize(int size)
|
||||
void Screen::setWindowZoom(int zoom)
|
||||
{
|
||||
options.video.window.size = size;
|
||||
setVideoMode(ScreenVideoMode::WINDOW);
|
||||
options.video.window.zoom = zoom;
|
||||
adjustWindowSize();
|
||||
}
|
||||
|
||||
// Reduce el tamaño de la ventana
|
||||
void Screen::decWindowSize()
|
||||
bool Screen::decWindowZoom()
|
||||
{
|
||||
--options.video.window.size;
|
||||
options.video.window.size = std::max(options.video.window.size, 1);
|
||||
setVideoMode(ScreenVideoMode::WINDOW);
|
||||
if (options.video.mode == ScreenVideoMode::WINDOW)
|
||||
{
|
||||
const int PREVIOUS_ZOOM = options.video.window.zoom;
|
||||
--options.video.window.zoom;
|
||||
options.video.window.zoom = std::max(options.video.window.zoom, 1);
|
||||
|
||||
if (options.video.window.zoom != PREVIOUS_ZOOM)
|
||||
{
|
||||
adjustWindowSize();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
// Aumenta el tamaño de la ventana
|
||||
void Screen::incWindowSize()
|
||||
bool Screen::incWindowZoom()
|
||||
{
|
||||
++options.video.window.size;
|
||||
options.video.window.size = std::min(options.video.window.size, options.video.window.max_size);
|
||||
setVideoMode(ScreenVideoMode::WINDOW);
|
||||
if (options.video.mode == ScreenVideoMode::WINDOW)
|
||||
{
|
||||
const int PREVIOUS_ZOOM = options.video.window.zoom;
|
||||
++options.video.window.zoom;
|
||||
options.video.window.zoom = std::min(options.video.window.zoom, options.video.window.max_zoom);
|
||||
|
||||
if (options.video.window.zoom != PREVIOUS_ZOOM)
|
||||
{
|
||||
adjustWindowSize();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// Cambia el color del borde
|
||||
void Screen::setBorderColor(Color color)
|
||||
{
|
||||
border_color_ = color;
|
||||
return false;
|
||||
}
|
||||
|
||||
// Cambia el tipo de mezcla
|
||||
void Screen::setBlendMode(SDL_BlendMode blendMode)
|
||||
{
|
||||
SDL_SetRenderDrawBlendMode(renderer_, blendMode);
|
||||
}
|
||||
void Screen::setBlendMode(SDL_BlendMode blendMode) { SDL_SetRenderDrawBlendMode(renderer_, blendMode); }
|
||||
|
||||
// Actualiza la lógica de la clase
|
||||
void Screen::update()
|
||||
@@ -280,10 +217,7 @@ void Screen::updateShakeEffect()
|
||||
}
|
||||
|
||||
// Pone la pantalla de color
|
||||
void Screen::flash(Color color, int lenght, int delay)
|
||||
{
|
||||
flash_effect_ = FlashEffect(true, lenght, delay, color);
|
||||
}
|
||||
void Screen::flash(Color color, int lenght, int delay) { flash_effect_ = FlashEffect(true, lenght, delay, color); }
|
||||
|
||||
// Actualiza y dibuja el efecto de flash en la pantalla
|
||||
void Screen::renderFlash()
|
||||
@@ -296,10 +230,7 @@ void Screen::renderFlash()
|
||||
}
|
||||
|
||||
// Actualiza el efecto de flash
|
||||
void Screen::updateFlash()
|
||||
{
|
||||
flash_effect_.update();
|
||||
}
|
||||
void Screen::updateFlash() { flash_effect_.update(); }
|
||||
|
||||
// Atenua la pantalla
|
||||
void Screen::renderAttenuate()
|
||||
@@ -311,32 +242,44 @@ void Screen::renderAttenuate()
|
||||
}
|
||||
}
|
||||
|
||||
// Aplica el efecto de agitar la pantalla
|
||||
void Screen::renderShake()
|
||||
{
|
||||
if (shake_effect_.enabled)
|
||||
{
|
||||
// Guarda el renderizador actual para dejarlo despues como estaba
|
||||
auto current_target = SDL_GetRenderTarget(renderer_);
|
||||
|
||||
// Crea una textura temporal
|
||||
auto temp_texture = SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, param.game.width, param.game.height);
|
||||
|
||||
// Vuelca game_canvas_ a la textura temporal
|
||||
SDL_SetRenderTarget(renderer_, temp_texture);
|
||||
SDL_RenderCopy(renderer_, game_canvas_, nullptr, nullptr);
|
||||
|
||||
// Vuelca textura temporal a game_canvas_
|
||||
SDL_SetRenderTarget(renderer_, game_canvas_);
|
||||
SDL_RenderCopy(renderer_, temp_texture, &src_rect_, &dst_rect_);
|
||||
|
||||
// Elimina la textura temporal
|
||||
SDL_DestroyTexture(temp_texture);
|
||||
|
||||
// Restaura el renderizador de destino original
|
||||
SDL_SetRenderTarget(renderer_, current_target);
|
||||
}
|
||||
}
|
||||
|
||||
// Activa / desactiva los shaders
|
||||
void Screen::toggleShaders()
|
||||
{
|
||||
options.video.shaders = !options.video.shaders;
|
||||
setVideoMode(options.video.mode);
|
||||
const std::string value = options.video.shaders ? "on" : "off";
|
||||
Notifier::get()->showText({"Shaders " + value});
|
||||
}
|
||||
|
||||
// Activa / desactiva la información de debug
|
||||
void Screen::toggleDebugInfo()
|
||||
{
|
||||
show_info_ = !show_info_;
|
||||
}
|
||||
void Screen::toggleDebugInfo() { show_debug_info_ = !show_debug_info_; }
|
||||
|
||||
// Atenua la pantalla
|
||||
void Screen::attenuate(bool value)
|
||||
{
|
||||
attenuate_effect_ = value;
|
||||
}
|
||||
|
||||
// Obtiene el puntero al renderizador
|
||||
SDL_Renderer *Screen::getRenderer()
|
||||
{
|
||||
return renderer_;
|
||||
}
|
||||
void Screen::attenuate(bool value) { attenuate_effect_ = value; }
|
||||
|
||||
// Calcula los frames por segundo
|
||||
void Screen::updateFPS()
|
||||
@@ -352,7 +295,7 @@ void Screen::updateFPS()
|
||||
// Muestra información por pantalla
|
||||
void Screen::renderInfo()
|
||||
{
|
||||
if (show_info_)
|
||||
if (show_debug_info_)
|
||||
{
|
||||
// FPS
|
||||
const std::string fpstext = std::to_string(fps_) + " FPS";
|
||||
@@ -363,60 +306,90 @@ void Screen::renderInfo()
|
||||
|
||||
// Contador de service_pressed_counter
|
||||
if (const int counter = globalInputs::service_pressed_counter; counter > 0)
|
||||
dbg_print(0, 8, std::to_string(counter).c_str(), 255, 0, 255);
|
||||
|
||||
const std::string atten = attenuate_effect_ ? "ATTEN YES" : "ATTEN NO";
|
||||
dbg_print(0, 16, atten.c_str(), 255, 0, 0);
|
||||
}
|
||||
}
|
||||
|
||||
// Calcula la nueva posición de la ventana a partir de la antigua al cambiarla de tamaño
|
||||
SDL_Point Screen::getNewPosition()
|
||||
{
|
||||
// Obtiene la posición actual de la ventana
|
||||
SDL_Point current_position;
|
||||
SDL_GetWindowPosition(window_, ¤t_position.x, ¤t_position.y);
|
||||
dbg_print(0, 8, std::to_string(counter).c_str(), 255, 0, 255);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Obtiene las dimensiones actuales de la ventana
|
||||
int current_width, current_height;
|
||||
SDL_GetWindowSize(window_, ¤t_width, ¤t_height);
|
||||
// Carga el contenido del archivo GLSL
|
||||
void Screen::loadShaders()
|
||||
{
|
||||
const std::string GLSL_FILE = param.game.game_area.rect.h == 256 ? "crtpi_256.glsl" : "crtpi_240.glsl";
|
||||
std::ifstream f(Asset::get()->get(GLSL_FILE).c_str());
|
||||
shaderSource = std::string((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());
|
||||
}
|
||||
|
||||
// Obtiene las dimesiones que tendrá la ventana
|
||||
const int new_width = param.game.width * options.video.window.size;
|
||||
const int new_height = param.game.height * options.video.window.size;
|
||||
// Inicializa los shaders
|
||||
void Screen::initShaders()
|
||||
{
|
||||
if (shaderSource.empty())
|
||||
{
|
||||
loadShaders();
|
||||
}
|
||||
shader::init(window_, game_canvas_, shaderSource.c_str());
|
||||
}
|
||||
|
||||
// Obtiene el centro de la ventana actual
|
||||
SDL_Point center;
|
||||
center.x = current_position.x + current_width / 2;
|
||||
center.y = current_position.y + current_height / 2;
|
||||
// Calcula el tamaño de la ventana
|
||||
void Screen::adjustWindowSize()
|
||||
{
|
||||
options.video.window.max_zoom = getMaxZoom();
|
||||
|
||||
// Calcula la nueva posición a partir del centro y las nuevas diemsiones
|
||||
SDL_Point new_pos;
|
||||
new_pos.x = center.x - new_width / 2;
|
||||
new_pos.y = center.y - new_height / 2;
|
||||
// Establece el nuevo tamaño
|
||||
if (options.video.mode == ScreenVideoMode::WINDOW)
|
||||
{
|
||||
const int WIDTH = param.game.width * options.video.window.zoom;
|
||||
const int HEIGHT = param.game.height * options.video.window.zoom;
|
||||
|
||||
// Obtiene las dimensiones del escritorio
|
||||
int old_width, old_height;
|
||||
SDL_GetWindowSize(window_, &old_width, &old_height);
|
||||
|
||||
int old_pos_x, old_pos_y;
|
||||
SDL_GetWindowPosition(window_, &old_pos_x, &old_pos_y);
|
||||
|
||||
const int NEW_POS_X = old_pos_x + (old_width - WIDTH) / 2;
|
||||
const int NEW_POS_Y = old_pos_y + (old_height - HEIGHT) / 2;
|
||||
|
||||
SDL_Rect viewport = {0, 0, WIDTH, HEIGHT};
|
||||
SDL_RenderSetViewport(renderer_, &viewport);
|
||||
|
||||
SDL_SetWindowPosition(window_, std::max(NEW_POS_X, WINDOWS_DECORATIONS_), std::max(NEW_POS_Y, 0));
|
||||
SDL_SetWindowSize(window_, WIDTH, HEIGHT);
|
||||
|
||||
initShaders();
|
||||
}
|
||||
}
|
||||
|
||||
// Ajusta el tamaño lógico del renderizador
|
||||
void Screen::adjustRenderLogicalSize() { SDL_RenderSetLogicalSize(renderer_, param.game.width, param.game.height); }
|
||||
|
||||
// Obtiene el tamaño máximo de zoom posible para la ventana
|
||||
int Screen::getMaxZoom()
|
||||
{
|
||||
// Obtiene información sobre la pantalla
|
||||
SDL_DisplayMode DM;
|
||||
SDL_GetCurrentDisplayMode(0, &DM);
|
||||
|
||||
// Evita que la ventana quede fuera del escritorio
|
||||
new_pos.x = std::clamp(new_pos.x, 30, DM.w - new_width);
|
||||
new_pos.y = std::clamp(new_pos.y, 30, DM.h - new_height);
|
||||
// Calcula el máximo factor de zoom que se puede aplicar a la pantalla
|
||||
const int MAX_ZOOM = std::min(DM.w / param.game.width, (DM.h - WINDOWS_DECORATIONS_) / param.game.height);
|
||||
|
||||
return new_pos;
|
||||
// Normaliza los valores de zoom
|
||||
options.video.window.zoom = std::min(options.video.window.zoom, MAX_ZOOM);
|
||||
|
||||
return MAX_ZOOM;
|
||||
}
|
||||
|
||||
// Actualiza la pantalla con el contenido del game_canvas_
|
||||
void Screen::presentGameCanvas()
|
||||
// Renderiza todos los overlays y efectos
|
||||
void Screen::renderOverlays()
|
||||
{
|
||||
// Copia la textura de juego en el renderizador en la posición adecuada
|
||||
if (shake_effect_.enabled)
|
||||
{
|
||||
// Esta copia es para evitar que se vea negro por los laterales
|
||||
SDL_RenderCopy(renderer_, game_canvas_, nullptr, nullptr);
|
||||
}
|
||||
SDL_RenderCopy(renderer_, game_canvas_, &src_rect_, &dst_rect_);
|
||||
// Actualiza el contador de FPS
|
||||
++fps_counter_;
|
||||
|
||||
// Actualiza la pantalla con el contenido del buffer de renderizado
|
||||
SDL_RenderPresent(renderer_);
|
||||
// Dibuja efectos y elementos sobre el game_canvas_
|
||||
renderShake();
|
||||
renderFlash();
|
||||
renderAttenuate();
|
||||
OnScreenHelp::get()->render();
|
||||
renderInfo();
|
||||
Notifier::get()->render();
|
||||
}
|
||||
@@ -8,6 +8,7 @@
|
||||
#include <string> // Para string
|
||||
#include "param.h" // Para Param, ParamGame, param
|
||||
#include "utils.h" // Para Color
|
||||
#include "options.h"
|
||||
|
||||
enum class ScreenFilter : int
|
||||
{
|
||||
@@ -15,16 +16,19 @@ enum class ScreenFilter : int
|
||||
LINEAL = 1,
|
||||
};
|
||||
|
||||
enum class ScreenVideoMode : int
|
||||
enum class ScreenVideoMode : Uint32
|
||||
{
|
||||
WINDOW = 0,
|
||||
FULLSCREEN = 1,
|
||||
FULLSCREEN = SDL_WINDOW_FULLSCREEN_DESKTOP,
|
||||
};
|
||||
|
||||
class Screen
|
||||
{
|
||||
private:
|
||||
// [SINGLETON] Objeto screen privado para Don Melitón
|
||||
// Constantes
|
||||
static constexpr int WINDOWS_DECORATIONS_ = 35;
|
||||
|
||||
// [SINGLETON] Objeto privado
|
||||
static Screen *screen_;
|
||||
|
||||
// Objetos y punteros
|
||||
@@ -35,16 +39,17 @@ private:
|
||||
// Variables
|
||||
SDL_Rect src_rect_; // Coordenadas de donde va a pillar la textura del juego para dibujarla
|
||||
SDL_Rect dst_rect_; // Coordenadas donde se va a dibujar la textura del juego sobre la pantalla o ventana
|
||||
Color border_color_ = Color(); // Color del borde añadido a la textura de juego para rellenar la pantalla
|
||||
bool attenuate_effect_ = false; // Indica si la pantalla ha de estar atenuada
|
||||
Uint32 fps_ticks_ = 0; // Ticks para contar los frames por segundo
|
||||
int fps_counter_ = 0; // Contador de frames por segundo
|
||||
int fps_ = 0; // Frames calculados en el último segundo
|
||||
std::string info_resolution_; // Texto con la informacion de la pantalla
|
||||
std::string shaderSource; // Almacenar el contenido del archivo GLSL
|
||||
|
||||
#ifdef DEBUG
|
||||
bool show_info_ = false; // Indica si ha de mostrar/ocultar la información de la pantalla
|
||||
bool show_debug_info_ = false; // Indica si ha de mostrar/ocultar la información de la pantalla
|
||||
#else
|
||||
bool show_info_ = false; // Indica si ha de mostrar/ocultar la información de la pantalla
|
||||
bool show_debug_info_ = false; // Indica si ha de mostrar/ocultar la información de la pantalla
|
||||
#endif
|
||||
|
||||
struct FlashEffect
|
||||
@@ -98,22 +103,35 @@ private:
|
||||
// Atenua la pantalla
|
||||
void renderAttenuate();
|
||||
|
||||
// Aplica el efecto de agitar la pantalla
|
||||
void renderShake();
|
||||
|
||||
// Calcula los frames por segundo
|
||||
void updateFPS();
|
||||
|
||||
// Muestra información por pantalla
|
||||
void renderInfo();
|
||||
|
||||
// Calcula la nueva posición de la ventana a partir de la antigua al cambiarla de tamaño
|
||||
SDL_Point getNewPosition();
|
||||
|
||||
// Actualiza la pantalla con el contenido del game_canvas_
|
||||
void presentGameCanvas();
|
||||
|
||||
// Selecciona y ejecuta el método de renderizado adecuado basado en la configuración de shaders
|
||||
void renderScreen();
|
||||
|
||||
// [SINGLETON] Ahora el constructor y el destructor son privados, para no poder crear objetos screen desde fuera
|
||||
// Carga el contenido del archivo GLSL
|
||||
void loadShaders();
|
||||
|
||||
// Inicializa los shaders
|
||||
void initShaders();
|
||||
|
||||
// Calcula el tamaño de la ventana
|
||||
void adjustWindowSize();
|
||||
|
||||
// Ajusta el tamaño lógico del renderizador
|
||||
void adjustRenderLogicalSize();
|
||||
|
||||
// Obtiene el tamaño máximo de zoom posible para la ventana
|
||||
int getMaxZoom();
|
||||
|
||||
// Renderiza todos los overlays y efectos
|
||||
void renderOverlays();
|
||||
|
||||
// Constructor
|
||||
Screen(SDL_Window *window, SDL_Renderer *renderer);
|
||||
@@ -122,13 +140,13 @@ private:
|
||||
~Screen();
|
||||
|
||||
public:
|
||||
// [SINGLETON] Crearemos el objeto screen con esta función estática
|
||||
// [SINGLETON] Crearemos el objeto con esta función estática
|
||||
static void init(SDL_Window *window, SDL_Renderer *renderer);
|
||||
|
||||
// [SINGLETON] Destruiremos el objeto screen con esta función estática
|
||||
// [SINGLETON] Destruiremos el objeto con esta función estática
|
||||
static void destroy();
|
||||
|
||||
// [SINGLETON] Con este método obtenemos el objeto screen y podemos trabajar con él
|
||||
// [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él
|
||||
static Screen *get();
|
||||
|
||||
// Actualiza la lógica de la clase
|
||||
@@ -144,22 +162,19 @@ public:
|
||||
void render();
|
||||
|
||||
// Establece el modo de video
|
||||
void setVideoMode(ScreenVideoMode video_mode);
|
||||
void setVideoMode(ScreenVideoMode video_mode = options.video.mode);
|
||||
|
||||
// Cambia entre pantalla completa y ventana
|
||||
void toggleVideoMode();
|
||||
|
||||
// Cambia el tamaño de la ventana
|
||||
void setWindowSize(int size);
|
||||
void setWindowZoom(int size);
|
||||
|
||||
// Reduce el tamaño de la ventana
|
||||
void decWindowSize();
|
||||
bool decWindowZoom();
|
||||
|
||||
// Aumenta el tamaño de la ventana
|
||||
void incWindowSize();
|
||||
|
||||
// Cambia el color del borde
|
||||
void setBorderColor(Color color);
|
||||
bool incWindowZoom();
|
||||
|
||||
// Cambia el tipo de mezcla
|
||||
void setBlendMode(SDL_BlendMode blend_mode);
|
||||
@@ -179,6 +194,12 @@ public:
|
||||
// Atenua la pantalla
|
||||
void attenuate(bool value);
|
||||
|
||||
// Obtiene el puntero al renderizador
|
||||
SDL_Renderer *getRenderer();
|
||||
// Getters
|
||||
SDL_Renderer *getRenderer() { return renderer_; }
|
||||
|
||||
// Muestra la ventana
|
||||
void show() { SDL_ShowWindow(window_); }
|
||||
|
||||
// Oculta la ventana
|
||||
void hide() { SDL_HideWindow(window_); }
|
||||
};
|
||||
@@ -1,10 +1,5 @@
|
||||
#include "smart_sprite.h"
|
||||
#include "moving_sprite.h" // Para MovingSprite
|
||||
class Texture; // lines 2-2
|
||||
|
||||
// Constructor
|
||||
SmartSprite::SmartSprite(std::shared_ptr<Texture> texture)
|
||||
: AnimatedSprite(texture) {}
|
||||
|
||||
// Actualiza la posición y comprueba si ha llegado a su destino
|
||||
void SmartSprite::update()
|
||||
@@ -17,22 +12,13 @@ void SmartSprite::update()
|
||||
}
|
||||
}
|
||||
|
||||
// Establece el valor de la variable
|
||||
void SmartSprite::setFinishedCounter(int value)
|
||||
// Dibuja el sprite
|
||||
void SmartSprite::render()
|
||||
{
|
||||
finished_counter_ = value;
|
||||
if (enabled_)
|
||||
{
|
||||
MovingSprite::render();
|
||||
}
|
||||
|
||||
// Establece el valor de la variable
|
||||
void SmartSprite::setDestX(int x)
|
||||
{
|
||||
dest_x_ = x;
|
||||
}
|
||||
|
||||
// Establece el valor de la variable
|
||||
void SmartSprite::setDestY(int y)
|
||||
{
|
||||
dest_y_ = y;
|
||||
}
|
||||
|
||||
// Comprueba el movimiento
|
||||
@@ -115,21 +101,3 @@ void SmartSprite::checkFinished()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Obtiene el valor de la variable
|
||||
bool SmartSprite::isOnDestination() const
|
||||
{
|
||||
return on_destination_;
|
||||
}
|
||||
|
||||
// Obtiene el valor de la variable
|
||||
bool SmartSprite::hasFinished() const
|
||||
{
|
||||
return finished_;
|
||||
}
|
||||
|
||||
// Habilita el objeto
|
||||
void SmartSprite::setEnabled(bool value)
|
||||
{
|
||||
enabled_ = value;
|
||||
}
|
||||
@@ -24,7 +24,8 @@ private:
|
||||
|
||||
public:
|
||||
// Constructor
|
||||
explicit SmartSprite(std::shared_ptr<Texture> texture);
|
||||
explicit SmartSprite(std::shared_ptr<Texture> texture)
|
||||
: AnimatedSprite(texture) {}
|
||||
|
||||
// Destructor
|
||||
~SmartSprite() = default;
|
||||
@@ -32,27 +33,18 @@ public:
|
||||
// Actualiza la posición y comprueba si ha llegado a su destino
|
||||
void update() override;
|
||||
|
||||
// Establece el valor de la variable
|
||||
void setFinishedCounter(int value);
|
||||
// Dibuja el sprite
|
||||
void render() override;
|
||||
|
||||
// Establece el valor de la variable
|
||||
void setDestX(int x);
|
||||
// Getters
|
||||
int getDestX() const { return dest_x_; }
|
||||
int getDestY() const { return dest_y_; }
|
||||
bool isOnDestination() const { return on_destination_; }
|
||||
bool hasFinished() const { return finished_; }
|
||||
|
||||
// Establece el valor de la variable
|
||||
void setDestY(int y);
|
||||
|
||||
// Obtiene el valor de la variable
|
||||
int getDestX() const;
|
||||
|
||||
// Obtiene el valor de la variable
|
||||
int getDestY() const;
|
||||
|
||||
// Obtiene el valor de la variable
|
||||
bool isOnDestination() const;
|
||||
|
||||
// Obtiene el valor de la variable
|
||||
bool hasFinished() const;
|
||||
|
||||
// Habilita el objeto
|
||||
void setEnabled(bool value);
|
||||
// Setters
|
||||
void setFinishedCounter(int value) { finished_counter_ = value; }
|
||||
void setDestX(int x) { dest_x_ = x; }
|
||||
void setDestY(int y) { dest_y_ = y; }
|
||||
void setEnabled(bool value) { enabled_ = value; }
|
||||
};
|
||||
@@ -37,6 +37,7 @@ public:
|
||||
|
||||
// Devuelve el rectangulo donde está el sprite
|
||||
SDL_Rect getPosition() const { return pos_; }
|
||||
SDL_Rect &getRect() { return pos_; }
|
||||
|
||||
// Establece la posición y el tamaño
|
||||
void setX(int x) { pos_.x = x; }
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
#include "tabe.h"
|
||||
#include <SDL2/SDL_render.h> // Para SDL_FLIP_HORIZONTAL, SDL_FLIP_NONE
|
||||
#include <stdlib.h> // Para rand, abs
|
||||
#include <algorithm> // Para max
|
||||
#include "jail_audio.h" // Para JA_PlaySound
|
||||
#include "param.h" // Para Param, ParamGame, param
|
||||
#include "resource.h" // Para Resource
|
||||
@@ -9,7 +10,8 @@
|
||||
|
||||
// Constructor
|
||||
Tabe::Tabe()
|
||||
: sprite_(std::make_unique<AnimatedSprite>(Resource::get()->getTexture("tabe.png"), Resource::get()->getAnimation("tabe.ani"))) {}
|
||||
: sprite_(std::make_unique<AnimatedSprite>(Resource::get()->getTexture("tabe.png"), Resource::get()->getAnimation("tabe.ani"))),
|
||||
timer_(TabeTimer(2.5f, 4.0f)) {}
|
||||
|
||||
// Actualiza la lógica
|
||||
void Tabe::update()
|
||||
@@ -18,6 +20,12 @@ void Tabe::update()
|
||||
{
|
||||
sprite_->update();
|
||||
move();
|
||||
updateState();
|
||||
}
|
||||
timer_.update();
|
||||
if (timer_.should_spawn())
|
||||
{
|
||||
enable();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,7 +55,7 @@ void Tabe::move()
|
||||
{
|
||||
if (x_ < min_x)
|
||||
{
|
||||
enabled_ = false;
|
||||
disable();
|
||||
}
|
||||
if (x_ > param.game.game_area.rect.x + param.game.game_area.rect.w - WIDTH_ && direction_ == TabeDirection::TO_THE_RIGHT)
|
||||
{
|
||||
@@ -61,7 +69,7 @@ void Tabe::move()
|
||||
{
|
||||
if (x_ > max_x)
|
||||
{
|
||||
enabled_ = false;
|
||||
disable();
|
||||
}
|
||||
if (x_ < param.game.game_area.rect.x && direction_ == TabeDirection::TO_THE_LEFT)
|
||||
{
|
||||
@@ -100,7 +108,10 @@ void Tabe::enable()
|
||||
if (!enabled_)
|
||||
{
|
||||
enabled_ = true;
|
||||
y_ = 20.0f;
|
||||
has_bonus_ = true;
|
||||
hit_counter_ = 0;
|
||||
number_of_hits_ = 0;
|
||||
y_ = param.game.game_area.rect.y + 20.0f;
|
||||
|
||||
// Establece una dirección aleatoria
|
||||
destiny_ = direction_ = rand() % 2 == 0 ? TabeDirection::TO_THE_LEFT : TabeDirection::TO_THE_RIGHT;
|
||||
@@ -146,3 +157,67 @@ void Tabe::setRandomFlyPath(TabeDirection direction, int lenght)
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Establece el estado
|
||||
void Tabe::setState(TabeState state)
|
||||
{
|
||||
if (enabled_)
|
||||
{
|
||||
state_ = state;
|
||||
|
||||
switch (state)
|
||||
{
|
||||
case TabeState::FLY:
|
||||
sprite_->setCurrentAnimation("fly");
|
||||
break;
|
||||
|
||||
case TabeState::HIT:
|
||||
sprite_->setCurrentAnimation("hit");
|
||||
hit_counter_ = 5;
|
||||
++number_of_hits_;
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Actualiza el estado
|
||||
void Tabe::updateState()
|
||||
{
|
||||
if (state_ == TabeState::HIT)
|
||||
{
|
||||
--hit_counter_;
|
||||
if (hit_counter_ == 0)
|
||||
{
|
||||
setState(TabeState::FLY);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Intenta obtener el bonus
|
||||
bool Tabe::tryToGetBonus()
|
||||
{
|
||||
if (has_bonus_ && rand() % std::max(1, 15 - number_of_hits_) == 0)
|
||||
{
|
||||
has_bonus_ = false;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Actualiza el temporizador
|
||||
void Tabe::updateTimer()
|
||||
{
|
||||
timer_.current_time = SDL_GetTicks();
|
||||
timer_.delta_time = timer_.current_time - timer_.last_time;
|
||||
timer_.last_time = timer_.current_time;
|
||||
}
|
||||
|
||||
// Deshabilita el objeto
|
||||
void Tabe::disable()
|
||||
{
|
||||
enabled_ = false;
|
||||
timer_.reset();
|
||||
}
|
||||
@@ -1,7 +1,11 @@
|
||||
#pragma once
|
||||
|
||||
#include "animated_sprite.h"
|
||||
#include <memory>
|
||||
#include <SDL2/SDL_rect.h> // Para SDL_Rect
|
||||
#include <SDL2/SDL_stdinc.h> // Para Uint32
|
||||
#include <SDL2/SDL_timer.h> // Para SDL_GetTicks
|
||||
#include <stdlib.h> // Para rand
|
||||
#include <memory> // Para unique_ptr
|
||||
#include "animated_sprite.h" // Para AnimatedSprite
|
||||
|
||||
enum class TabeDirection : int
|
||||
{
|
||||
@@ -9,6 +13,61 @@ enum class TabeDirection : int
|
||||
TO_THE_RIGHT = 1,
|
||||
};
|
||||
|
||||
enum class TabeState : int
|
||||
{
|
||||
FLY = 0,
|
||||
HIT = 1,
|
||||
};
|
||||
|
||||
struct TabeTimer
|
||||
{
|
||||
Uint32 time_until_next_spawn; // Tiempo restante para la próxima aparición
|
||||
Uint32 min_spawn_time; // Tiempo mínimo entre apariciones
|
||||
Uint32 max_spawn_time; // Tiempo máximo entre apariciones
|
||||
Uint32 current_time; // Tiempo actual
|
||||
Uint32 delta_time; // Diferencia de tiempo desde la última actualización
|
||||
Uint32 last_time; // Tiempo de la última actualización
|
||||
|
||||
// Constructor
|
||||
TabeTimer(float minTime, float maxTime)
|
||||
: min_spawn_time(minTime * 60000), max_spawn_time(maxTime * 60000)
|
||||
{
|
||||
current_time = SDL_GetTicks();
|
||||
reset();
|
||||
}
|
||||
|
||||
// Restablece el temporizador con un nuevo tiempo hasta la próxima aparición
|
||||
void reset()
|
||||
{
|
||||
Uint32 range = max_spawn_time - min_spawn_time;
|
||||
time_until_next_spawn = min_spawn_time + rand() % (range + 1);
|
||||
last_time = SDL_GetTicks();
|
||||
}
|
||||
|
||||
// Actualiza el temporizador, decrementando el tiempo hasta la próxima aparición
|
||||
void update()
|
||||
{
|
||||
current_time = SDL_GetTicks();
|
||||
delta_time = current_time - last_time;
|
||||
last_time = current_time;
|
||||
|
||||
if (time_until_next_spawn > delta_time)
|
||||
{
|
||||
time_until_next_spawn -= delta_time;
|
||||
}
|
||||
else
|
||||
{
|
||||
time_until_next_spawn = 0;
|
||||
}
|
||||
}
|
||||
|
||||
// Indica si el temporizador ha finalizado
|
||||
bool should_spawn() const
|
||||
{
|
||||
return time_until_next_spawn == 0;
|
||||
}
|
||||
};
|
||||
|
||||
// Clase Tabe
|
||||
class Tabe
|
||||
{
|
||||
@@ -30,6 +89,11 @@ private:
|
||||
bool enabled_ = false; // Indica si el objeto está activo
|
||||
TabeDirection direction_; // Dirección del objeto
|
||||
TabeDirection destiny_; // Destino del objeto
|
||||
TabeState state_ = TabeState::FLY; // Estado
|
||||
int hit_counter_ = 0; // Contador para el estado HIT
|
||||
int number_of_hits_ = 0; // Cantidad de disparos que ha recibido
|
||||
bool has_bonus_ = true; // Indica si el Tabe aun tiene el bonus para soltar
|
||||
TabeTimer timer_; // Temporizador para gestionar la aparición del Tabe
|
||||
|
||||
// Mueve el objeto
|
||||
void move();
|
||||
@@ -40,6 +104,15 @@ private:
|
||||
// Establece un vuelo aleatorio
|
||||
void setRandomFlyPath(TabeDirection direction, int lenght);
|
||||
|
||||
// Actualiza el estado
|
||||
void updateState();
|
||||
|
||||
// Actualiza el temporizador
|
||||
void updateTimer();
|
||||
|
||||
// Deshabilita el objeto
|
||||
void disable();
|
||||
|
||||
public:
|
||||
// Constructor
|
||||
Tabe();
|
||||
@@ -55,4 +128,16 @@ public:
|
||||
|
||||
// Habilita el objeto
|
||||
void enable();
|
||||
|
||||
// Establece el estado
|
||||
void setState(TabeState state);
|
||||
|
||||
// Intenta obtener el bonus
|
||||
bool tryToGetBonus();
|
||||
|
||||
// Obtiene el area de colisión
|
||||
SDL_Rect &getCollider() { return sprite_->getRect(); }
|
||||
|
||||
// Getters
|
||||
bool isEnabled() const { return enabled_; }
|
||||
};
|
||||
@@ -173,6 +173,25 @@ std::shared_ptr<Texture> Text::writeToTexture(const std::string &text, int zoom,
|
||||
return texture;
|
||||
}
|
||||
|
||||
// Escribe el texto con extras en una textura
|
||||
std::shared_ptr<Texture> Text::writeDXToTexture(Uint8 flags, const std::string &text, int kerning, Color textColor, Uint8 shadow_distance, Color shadow_color, int lenght)
|
||||
{
|
||||
auto renderer = Screen::get()->getRenderer();
|
||||
auto texture = std::make_shared<Texture>(renderer);
|
||||
auto width = Text::lenght(text, kerning) + shadow_distance;
|
||||
auto height = box_height_ + shadow_distance;
|
||||
auto temp = SDL_GetRenderTarget(renderer);
|
||||
texture->createBlank(width, height, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET);
|
||||
texture->setBlendMode(SDL_BLENDMODE_BLEND);
|
||||
texture->setAsRenderTarget(renderer);
|
||||
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0);
|
||||
SDL_RenderClear(renderer);
|
||||
writeDX(flags, 0, 0, text, kerning, textColor, shadow_distance, shadow_color, lenght);
|
||||
SDL_SetRenderTarget(renderer, temp);
|
||||
|
||||
return texture;
|
||||
}
|
||||
|
||||
// Escribe el texto con colores
|
||||
void Text::writeColored(int x, int y, const std::string &text, Color color, int kerning, int lenght)
|
||||
{
|
||||
@@ -256,12 +275,6 @@ int Text::getCharacterSize() const
|
||||
return box_width_;
|
||||
}
|
||||
|
||||
// Recarga la textura
|
||||
void Text::reLoadTexture()
|
||||
{
|
||||
sprite_->getTexture()->reLoad();
|
||||
}
|
||||
|
||||
// Establece si se usa un tamaño fijo de letra
|
||||
void Text::setFixedWidth(bool value)
|
||||
{
|
||||
|
||||
@@ -55,6 +55,9 @@ public:
|
||||
// Escribe el texto en una textura
|
||||
std::shared_ptr<Texture> writeToTexture(const std::string &text, int zoom = 1, int kerning = 1);
|
||||
|
||||
// Escribe el texto con extras en una textura
|
||||
std::shared_ptr<Texture> writeDXToTexture(Uint8 flags, const std::string &text, int kerning = 1, Color textColor = Color(), Uint8 shadow_distance = 1, Color shadow_color = Color(), int lenght = -1);
|
||||
|
||||
// Escribe el texto con colores
|
||||
void writeColored(int x, int y, const std::string &text, Color color, int kerning = 1, int lenght = -1);
|
||||
|
||||
@@ -73,9 +76,6 @@ public:
|
||||
// Devuelve el valor de la variable
|
||||
int getCharacterSize() const;
|
||||
|
||||
// Recarga la textura
|
||||
void reLoadTexture();
|
||||
|
||||
// Establece si se usa un tamaño fijo de letra
|
||||
void setFixedWidth(bool value);
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
#include <stdexcept> // Para runtime_error
|
||||
#include <string> // Para char_traits, operator<<, operator+
|
||||
#include <vector> // Para vector
|
||||
#include "gif.c" // Para LoadGif, LoadPalette
|
||||
#include "gif.h" // Para LoadGif, LoadPalette
|
||||
#include "stb_image.h" // Para stbi_image_free, stbi_load, STBI_rgb_a...
|
||||
#include "utils.h" // Para getFileName, printWithDots
|
||||
|
||||
@@ -164,6 +164,10 @@ void Texture::setColor(Uint8 red, Uint8 green, Uint8 blue)
|
||||
{
|
||||
SDL_SetTextureColorMod(texture_, red, green, blue);
|
||||
}
|
||||
void Texture::setColor(Color color)
|
||||
{
|
||||
SDL_SetTextureColorMod(texture_, color.r, color.g, color.b);
|
||||
}
|
||||
|
||||
// Establece el blending
|
||||
void Texture::setBlendMode(SDL_BlendMode blending)
|
||||
@@ -376,7 +380,4 @@ void Texture::setPalette(int palette)
|
||||
}
|
||||
|
||||
// Obtiene el renderizador
|
||||
SDL_Renderer *Texture::getRenderer()
|
||||
{
|
||||
return renderer_;
|
||||
}
|
||||
SDL_Renderer *Texture::getRenderer(){ return renderer_;}
|
||||
@@ -1,13 +1,14 @@
|
||||
#pragma once
|
||||
|
||||
#include <SDL2/SDL_blendmode.h> // para SDL_BlendMode
|
||||
#include <SDL2/SDL_pixels.h> // para SDL_PIXELFORMAT_RGBA8888, SDL_PixelF...
|
||||
#include <SDL2/SDL_rect.h> // para SDL_Point, SDL_Rect
|
||||
#include <SDL2/SDL_render.h> // para SDL_Renderer, SDL_FLIP_NONE, SDL_TEX...
|
||||
#include <SDL2/SDL_stdinc.h> // para Uint8, Uint32, Uint16
|
||||
#include <string> // para string, basic_string
|
||||
#include <vector> // para vector
|
||||
#include <memory>
|
||||
#include <SDL2/SDL_blendmode.h> // Para SDL_BlendMode
|
||||
#include <SDL2/SDL_pixels.h> // Para SDL_PIXELFORMAT_RGBA8888, SDL_PixelF...
|
||||
#include <SDL2/SDL_rect.h> // Para SDL_Point, SDL_Rect
|
||||
#include <SDL2/SDL_render.h> // Para SDL_Renderer, SDL_FLIP_NONE, SDL_TEX...
|
||||
#include <SDL2/SDL_stdinc.h> // Para Uint8, Uint16, Uint32
|
||||
#include <memory> // Para shared_ptr
|
||||
#include <string> // Para string
|
||||
#include <vector> // Para vector
|
||||
struct Color;
|
||||
|
||||
// Definiciones de tipos
|
||||
struct Surface
|
||||
@@ -65,6 +66,7 @@ public:
|
||||
|
||||
// Establece el color para la modulacion
|
||||
void setColor(Uint8 red, Uint8 green, Uint8 blue);
|
||||
void setColor(Color color);
|
||||
|
||||
// Establece el blending
|
||||
void setBlendMode(SDL_BlendMode blending);
|
||||
|
||||
@@ -11,9 +11,6 @@
|
||||
TiledBG::TiledBG(SDL_Rect pos, TiledBGMode mode)
|
||||
: renderer_(Screen::get()->getRenderer()),
|
||||
pos_(pos),
|
||||
// Coloca la ventana que recorre el mosaico de fondo de manera que coincida
|
||||
// con el mosaico que hay pintado en el titulo al iniciar
|
||||
window_({128, 96, pos_.w, pos_.h}),
|
||||
mode_(mode == TiledBGMode::RANDOM ? static_cast<TiledBGMode>(rand() % 2) : mode)
|
||||
{
|
||||
// Crea la textura para el mosaico de fondo
|
||||
@@ -22,6 +19,25 @@ TiledBG::TiledBG(SDL_Rect pos, TiledBGMode mode)
|
||||
// Rellena la textura con el contenido
|
||||
fillTexture();
|
||||
|
||||
// Inicializa variables
|
||||
switch (mode_)
|
||||
{
|
||||
case TiledBGMode::STATIC:
|
||||
window_ = {0, 0, pos_.w, pos_.h};
|
||||
speed_ = 0.0f;
|
||||
break;
|
||||
case TiledBGMode::DIAGONAL:
|
||||
window_ = {0, 0, pos_.w, pos_.h};
|
||||
break;
|
||||
case TiledBGMode::CIRCLE:
|
||||
window_ = {128, 128, pos_.w, pos_.h};
|
||||
speed_ = 0.8f;
|
||||
break;
|
||||
default:
|
||||
window_ = {0, 0, pos_.w, pos_.h};
|
||||
break;
|
||||
}
|
||||
|
||||
// Inicializa los valores del vector con los valores del seno
|
||||
for (int i = 0; i < 360; ++i)
|
||||
{
|
||||
@@ -72,19 +88,26 @@ void TiledBG::render()
|
||||
// Actualiza la lógica de la clase
|
||||
void TiledBG::update()
|
||||
{
|
||||
updateDesp();
|
||||
updateStop();
|
||||
|
||||
switch (mode_)
|
||||
{
|
||||
case TiledBGMode::DIAGONAL:
|
||||
{ // El tileado de fondo se desplaza en diagonal
|
||||
++window_.x %= TILE_WIDTH_;
|
||||
++window_.y %= TILE_HEIGHT_;
|
||||
{
|
||||
// El tileado de fondo se desplaza en diagonal
|
||||
window_.x = static_cast<int>(desp_) % TILE_WIDTH_;
|
||||
window_.y = static_cast<int>(desp_) % TILE_HEIGHT_;
|
||||
|
||||
break;
|
||||
}
|
||||
case TiledBGMode::CIRCLE:
|
||||
{ // El tileado de fondo se desplaza en circulo
|
||||
++counter_ %= 360;
|
||||
window_.x = 128 + (int(sin_[(counter_ + 270) % 360] * 128));
|
||||
window_.y = 96 + (int(sin_[(360 - counter_) % 360] * 96));
|
||||
{
|
||||
// El tileado de fondo se desplaza en circulo
|
||||
const int INDEX = static_cast<int>(desp_) % 360;
|
||||
|
||||
window_.x = 128 + (static_cast<int>(sin_[(INDEX + 270) % 360] * 128));
|
||||
window_.y = 128 + (static_cast<int>(sin_[(360 - INDEX) % 360] * 96));
|
||||
break;
|
||||
}
|
||||
default:
|
||||
@@ -92,8 +115,30 @@ void TiledBG::update()
|
||||
}
|
||||
}
|
||||
|
||||
// Recarga las texturas
|
||||
void TiledBG::reLoad()
|
||||
// Detiene el desplazamiento de forma ordenada
|
||||
void TiledBG::updateStop()
|
||||
{
|
||||
fillTexture();
|
||||
if (stopping_)
|
||||
{
|
||||
const int UMBRAL = 20 * speed_; // Ajusta este valor según la precisión deseada
|
||||
|
||||
// Desacelerar si estamos cerca de completar el ciclo (ventana a punto de regresar a 0)
|
||||
if (window_.x >= TILE_WIDTH_ - UMBRAL)
|
||||
{
|
||||
speed_ /= 1.05f; // Reduce gradualmente la velocidad
|
||||
|
||||
// Asegura que no baje demasiado
|
||||
if (speed_ < 0.1f)
|
||||
{
|
||||
speed_ = 0.1f;
|
||||
}
|
||||
}
|
||||
|
||||
// Si estamos en 0, detener
|
||||
if (window_.x == 0)
|
||||
{
|
||||
speed_ = 0.0f;
|
||||
stopping_ = false; // Desactivamos el estado de "stopping"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
#include <SDL2/SDL_rect.h> // Para SDL_Rect
|
||||
#include <SDL2/SDL_render.h> // Para SDL_Renderer, SDL_Texture
|
||||
#include "utils.h"
|
||||
|
||||
// Modos de funcionamiento para el tileado de fondo
|
||||
enum class TiledBGMode : int
|
||||
@@ -36,10 +37,19 @@ private:
|
||||
int counter_ = 0; // Contador
|
||||
TiledBGMode mode_; // Tipo de movimiento del mosaico
|
||||
double sin_[360]; // Vector con los valores del seno precalculados
|
||||
float desp_ = 0.0f; // Desplazamiento aplicado
|
||||
float speed_ = 1.0f; // Incremento que se añade al desplazamiento a cada bucle
|
||||
bool stopping_ = false; // Indica si se está deteniendo
|
||||
|
||||
// Rellena la textura con el contenido
|
||||
void fillTexture();
|
||||
|
||||
// Actualiza el desplazamiento
|
||||
void updateDesp() { desp_ += speed_; }
|
||||
|
||||
// Detiene el desplazamiento de forma ordenada
|
||||
void updateStop();
|
||||
|
||||
public:
|
||||
// Constructor
|
||||
TiledBG(SDL_Rect pos, TiledBGMode mode);
|
||||
@@ -53,6 +63,15 @@ public:
|
||||
// Actualiza la lógica de la clase
|
||||
void update();
|
||||
|
||||
// Recarga las texturas
|
||||
void reLoad();
|
||||
// Establece la velocidad
|
||||
void setSpeed(float speed) { speed_ = speed; }
|
||||
|
||||
// Detiene el desplazamiento de forma ordenada
|
||||
void stopGracefully() { stopping_ = true; }
|
||||
|
||||
// Cambia el color de la textura
|
||||
void setColor(Color color) { SDL_SetTextureColorMod(canvas_, color.r, color.g, color.b); }
|
||||
|
||||
// Indica si está parado
|
||||
bool isStopped() const { return speed_ == 0.0f; }
|
||||
};
|
||||
252
source/title.cpp
@@ -12,7 +12,7 @@
|
||||
#include "input.h" // Para Input, InputType, INPUT_DO_NOT_ALLOW_R...
|
||||
#include "jail_audio.h" // Para JA_GetMusicState, JA_FadeOutMusic, JA_...
|
||||
#include "lang.h" // Para getText
|
||||
#include "mouse.h" // Para handleEvent
|
||||
#include "global_events.h" // Para handleEvent
|
||||
#include "notifier.h" // Para Notifier
|
||||
#include "options.h" // Para OptionsController, Options, options
|
||||
#include "param.h" // Para Param, param, ParamGame, ParamTitle
|
||||
@@ -46,9 +46,9 @@ Title::Title()
|
||||
|
||||
// Asigna valores a otras variables
|
||||
section::options = section::Options::TITLE_1;
|
||||
const bool is_title_to_demo = (section::attract_mode == section::AttractMode::TITLE_TO_DEMO);
|
||||
next_section_ = is_title_to_demo ? section::Name::GAME_DEMO : section::Name::LOGO;
|
||||
section::attract_mode = is_title_to_demo ? section::AttractMode::TITLE_TO_LOGO : section::AttractMode::TITLE_TO_DEMO;
|
||||
const bool IS_TITLE_TO_DEMO = (section::attract_mode == section::AttractMode::TITLE_TO_DEMO);
|
||||
next_section_ = IS_TITLE_TO_DEMO ? section::Name::GAME_DEMO : section::Name::LOGO;
|
||||
section::attract_mode = IS_TITLE_TO_DEMO ? section::AttractMode::TITLE_TO_LOGO : section::AttractMode::TITLE_TO_DEMO;
|
||||
}
|
||||
|
||||
// Destructor
|
||||
@@ -61,95 +61,22 @@ Title::~Title()
|
||||
// Actualiza las variables del objeto
|
||||
void Title::update()
|
||||
{
|
||||
constexpr int TICKS_SPEED = 15;
|
||||
|
||||
if (SDL_GetTicks() - ticks_ > TICKS_SPEED)
|
||||
if (SDL_GetTicks() - ticks_ > param.game.speed)
|
||||
{
|
||||
// Actualiza el contador de ticks_
|
||||
ticks_ = SDL_GetTicks();
|
||||
|
||||
// Actualiza el fade
|
||||
updateFade();
|
||||
|
||||
// Actualiza el estado
|
||||
updateState();
|
||||
|
||||
// Actualiza el objeto screen
|
||||
Screen::get()->update();
|
||||
|
||||
// Actualiza las variables de globalInputs
|
||||
globalInputs::update();
|
||||
|
||||
// Comprueba el fundido
|
||||
fade_->update();
|
||||
if (fade_->hasEnded())
|
||||
{
|
||||
if (selection_ == section::Options::TITLE_TIME_OUT)
|
||||
{
|
||||
// El menu ha hecho time out
|
||||
section::name = next_section_;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Se ha pulsado para jugar
|
||||
section::name = section::Name::GAME;
|
||||
section::options = selection_;
|
||||
JA_StopMusic();
|
||||
}
|
||||
}
|
||||
|
||||
// Establece la lógica según el estado
|
||||
switch (state_)
|
||||
{
|
||||
case TitleState::LOGO_ANIMATING:
|
||||
{
|
||||
game_logo_->update();
|
||||
if (game_logo_->hasFinished())
|
||||
{
|
||||
state_ = TitleState::LOGO_FINISHED;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case TitleState::LOGO_FINISHED:
|
||||
{
|
||||
// El contador solo sube si no estamos definiendo botones
|
||||
counter_ = define_buttons_->isEnabled() ? 0 : counter_ + 1;
|
||||
|
||||
// Reproduce la música
|
||||
if ((JA_GetMusicState() == JA_MUSIC_INVALID) || (JA_GetMusicState() == JA_MUSIC_STOPPED))
|
||||
{
|
||||
JA_PlayMusic(Resource::get()->getMusic("title.ogg"));
|
||||
}
|
||||
|
||||
// Actualiza el logo con el título del juego
|
||||
game_logo_->update();
|
||||
|
||||
// Actualiza el mosaico de fondo
|
||||
tiled_bg_->update();
|
||||
|
||||
if (counter_ == param.title.title_duration)
|
||||
{
|
||||
// El menu ha hecho time out
|
||||
fade_->setPostDuration(0);
|
||||
fade_->activate();
|
||||
selection_ = section::Options::TITLE_TIME_OUT;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
case TitleState::START_HAS_BEEN_PRESSED:
|
||||
{
|
||||
// Actualiza el logo con el título del juego
|
||||
game_logo_->update();
|
||||
|
||||
// Actualiza el mosaico de fondo
|
||||
tiled_bg_->update();
|
||||
|
||||
if (counter_ == 100)
|
||||
{
|
||||
fade_->activate();
|
||||
}
|
||||
++counter_;
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -212,72 +139,52 @@ void Title::render()
|
||||
|
||||
// Comprueba los eventos
|
||||
void Title::checkEvents()
|
||||
{
|
||||
// Comprueba el input para el resto de objetos
|
||||
define_buttons_->checkEvents();
|
||||
|
||||
// Si define_buttons_ está habilitado, es él quien gestiona los eventos
|
||||
if (!define_buttons_->isEnabled())
|
||||
{
|
||||
SDL_Event event;
|
||||
while (SDL_PollEvent(&event))
|
||||
{
|
||||
// Evento de salida de la aplicación
|
||||
if (event.type == SDL_QUIT)
|
||||
if (event.type == SDL_KEYDOWN && event.key.repeat == 0)
|
||||
{
|
||||
section::name = section::Name::QUIT;
|
||||
section::options = section::Options::QUIT_FROM_EVENT;
|
||||
break;
|
||||
}
|
||||
bool should_reset = false;
|
||||
|
||||
// Recarga las texturas
|
||||
else if (event.type == SDL_RENDER_DEVICE_RESET || event.type == SDL_RENDER_TARGETS_RESET)
|
||||
{
|
||||
reLoadTextures();
|
||||
}
|
||||
|
||||
else if (event.type == SDL_KEYDOWN && event.key.repeat == 0)
|
||||
{
|
||||
switch (event.key.keysym.sym)
|
||||
{
|
||||
case SDLK_1: // Redefine los botones del mando #0
|
||||
{
|
||||
if (define_buttons_->enable(0))
|
||||
resetCounter();
|
||||
should_reset = define_buttons_->enable(0);
|
||||
break;
|
||||
}
|
||||
|
||||
case SDLK_2: // Redefine los botones del mando #1
|
||||
{
|
||||
if (define_buttons_->enable(1))
|
||||
resetCounter();
|
||||
should_reset = define_buttons_->enable(1);
|
||||
break;
|
||||
}
|
||||
|
||||
case SDLK_3: // Intercambia los mandos entre los dos jugadores
|
||||
{
|
||||
swapControllers();
|
||||
resetCounter();
|
||||
should_reset = true;
|
||||
break;
|
||||
}
|
||||
|
||||
case SDLK_4: // Intercambia la asignación del teclado
|
||||
{
|
||||
swapKeyboard();
|
||||
resetCounter();
|
||||
should_reset = true;
|
||||
break;
|
||||
}
|
||||
case SDLK_5: // Muestra la asignacion de mandos y teclado
|
||||
{
|
||||
|
||||
case SDLK_5: // Muestra la asignación de mandos y teclado
|
||||
showControllers();
|
||||
resetCounter();
|
||||
should_reset = true;
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
// Resetear el contador si es necesario
|
||||
if (should_reset)
|
||||
{
|
||||
resetCounter();
|
||||
}
|
||||
}
|
||||
|
||||
// Comprueba el cursor
|
||||
Mouse::handleEvent(event);
|
||||
}
|
||||
globalEvents::check(event);
|
||||
define_buttons_->checkEvents(event);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -350,13 +257,6 @@ void Title::run()
|
||||
}
|
||||
}
|
||||
|
||||
// Recarga las texturas
|
||||
void Title::reLoadTextures()
|
||||
{
|
||||
game_logo_->reLoad();
|
||||
tiled_bg_->reLoad();
|
||||
}
|
||||
|
||||
// Reinicia el contador interno
|
||||
void Title::resetCounter() { counter_ = 0; }
|
||||
|
||||
@@ -375,7 +275,7 @@ void Title::swapKeyboard()
|
||||
{
|
||||
swapOptionsKeyboard();
|
||||
std::string text = lang::getText(100) + std::to_string(getPlayerWhoUsesKeyboard()) + ": " + lang::getText(69);
|
||||
Notifier::get()->showText({text});
|
||||
Notifier::get()->show({text});
|
||||
}
|
||||
|
||||
// Muestra información sobre los controles y los jugadores
|
||||
@@ -404,5 +304,89 @@ void Title::showControllers()
|
||||
}
|
||||
|
||||
// Muestra la notificación
|
||||
Notifier::get()->showText({text.at(0), text.at(1)});
|
||||
Notifier::get()->show({text.at(0), text.at(1)});
|
||||
}
|
||||
|
||||
// Actualiza el fade
|
||||
void Title::updateFade()
|
||||
{
|
||||
fade_->update();
|
||||
if (fade_->hasEnded())
|
||||
{
|
||||
if (selection_ == section::Options::TITLE_TIME_OUT)
|
||||
{
|
||||
// El menu ha hecho time out
|
||||
section::name = next_section_;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Se ha pulsado para jugar
|
||||
section::name = section::Name::GAME;
|
||||
section::options = selection_;
|
||||
JA_StopMusic();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Actualiza el estado
|
||||
void Title::updateState()
|
||||
{
|
||||
// Establece la lógica según el estado
|
||||
switch (state_)
|
||||
{
|
||||
case TitleState::LOGO_ANIMATING:
|
||||
{
|
||||
game_logo_->update();
|
||||
if (game_logo_->hasFinished())
|
||||
{
|
||||
state_ = TitleState::LOGO_FINISHED;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case TitleState::LOGO_FINISHED:
|
||||
{
|
||||
// El contador solo sube si no estamos definiendo botones
|
||||
counter_ = define_buttons_->isEnabled() ? 0 : counter_ + 1;
|
||||
|
||||
// Reproduce la música
|
||||
if ((JA_GetMusicState() == JA_MUSIC_INVALID) || (JA_GetMusicState() == JA_MUSIC_STOPPED))
|
||||
{
|
||||
JA_PlayMusic(Resource::get()->getMusic("title.ogg"));
|
||||
}
|
||||
|
||||
// Actualiza el logo con el título del juego
|
||||
game_logo_->update();
|
||||
|
||||
// Actualiza el mosaico de fondo
|
||||
tiled_bg_->update();
|
||||
|
||||
if (counter_ == param.title.title_duration)
|
||||
{
|
||||
// El menu ha hecho time out
|
||||
fade_->setPostDuration(0);
|
||||
fade_->activate();
|
||||
selection_ = section::Options::TITLE_TIME_OUT;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
case TitleState::START_HAS_BEEN_PRESSED:
|
||||
{
|
||||
// Actualiza el logo con el título del juego
|
||||
game_logo_->update();
|
||||
|
||||
// Actualiza el mosaico de fondo
|
||||
tiled_bg_->update();
|
||||
|
||||
if (counter_ == 100)
|
||||
{
|
||||
fade_->activate();
|
||||
}
|
||||
++counter_;
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||