Compare commits

20 Commits

Author SHA1 Message Date
c66cc965f1 define_buttons ja acaba be de definir els buttons 2024-11-01 18:39:10 +01:00
0757f63b73 Eliminat checkModInput 2024-11-01 18:20:18 +01:00
80a110e1d7 Abans de llevar checkInputMod 2024-11-01 16:48:03 +01:00
cd68c5ffea Al redefinir botons, ja no pots repetir botó. Util per als qui tenim la ma tremolosa i apretem dos voltes sense voler 2024-11-01 14:32:27 +01:00
f786cb7776 Implementat el final del joc 2024-11-01 13:05:11 +01:00
2e0d27a95c Modificats parámetres 2024-11-01 12:56:09 +01:00
861a9411d3 Nous textos 2024-11-01 12:55:37 +01:00
da27fde366 Millores en la gestió del "mute" en el joc 2024-11-01 07:55:37 +01:00
c6e2368e82 Noves animacions per a deixar de disparar 2024-10-31 23:32:11 +01:00
30dfa4c545 Treballant en el final del joc 2024-10-31 11:58:01 +01:00
7e2691e33e Finalitzat el Attract Mode 2024-10-30 21:29:23 +01:00
7e918e99f7 Arreglat un include 2024-10-30 13:15:30 +01:00
2aa3f827cb Arreglada la animació de morir, que s'updatava dos voltes per frame 2024-10-30 10:15:53 +01:00
06899d95a8 Arreglat el efecte de flash. Estava passant-li un valor massa xicotet 2024-10-30 09:45:57 +01:00
20c51d0796 Acabat el nou motor per a textos en pantalla 2024-10-30 09:25:28 +01:00
b43782786a Modificades les linux_utils 2024-10-30 09:25:12 +01:00
15554c449f Nuevos textos para el game_text 2024-10-30 08:19:32 +01:00
ba05eab79e Reduida la dependencia de PathSprite a Sprite
Treballant en els missatges de text que ixen durant la partida
2024-10-29 20:05:05 +01:00
d83c05bad4 El game_text dels items ja son textures generades i precarregades 2024-10-29 16:04:14 +01:00
e2abf835f9 Afegida nova tipografia 04b_25
Eliminades tipografies que no s'utilitzaven
La classe Text ara pot tornar una textura amb el text
2024-10-29 15:22:19 +01:00
60 changed files with 1619 additions and 2256 deletions

View File

@@ -6,7 +6,7 @@ game.play_area.rect.x 0 # Rectangulo con la posición de la zona de juego
game.play_area.rect.y 0 # Rectangulo con la posición de la zona de juego
game.play_area.rect.w 320 # Rectangulo con la posición de la zona de juego
game.play_area.rect.h 200 # Rectangulo con la posición de la zona de juego
game.enter_name_seconds 30 # Duración en segundos para introducir el nombre al finalizar la partida
game.enter_name_seconds 60 # Duración en segundos para introducir el nombre al finalizar la partida
## FADE
fade.num_squares_width 160

View File

@@ -6,8 +6,7 @@ game.play_area.rect.x 0 # Rectangulo con la posición de la zona de juego
game.play_area.rect.y 0 # Rectangulo con la posición de la zona de juego
game.play_area.rect.w 320 # Rectangulo con la posición de la zona de juego
game.play_area.rect.h 216 # Rectangulo con la posición de la zona de juego
game.enter_name_seconds 30 # Duración en segundos para introducir el nombre al finalizar la partida
game.game_text.dest_y
game.enter_name_seconds 60 # Duración en segundos para introducir el nombre al finalizar la partida
## FADE
fade.num_squares_width 160

BIN
data/font/04b_25.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.2 KiB

View File

@@ -1,194 +1,194 @@
# box width
10
14
# box height
10
14
# 32 espacio ( )
5
8
# 33 !
4
5
# 34 "
5
# 35 #
7
8
# 35
10
# 36 $
7
10
# 37 %
8
9
# 38 &
8
11
# 39 '
3
5
# 40 (
5
7
# 41 )
5
7
# 42 *
7
7
# 43 +
7
9
# 44 ,
4
5
# 45 -
6
9
# 46 .
4
5
# 47 /
5
12
# 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
# 49 1
6
# 50 2
8
# 51 3
8
# 52 4
8
# 53 5
8
# 54 6
8
# 55 7
8
# 56 8
8
# 57 9
8
# 58 :
5
# 59 ;
5
# 60 <
8
# 61 =
8
# 62 >
8
# 63 ?
8
# 64 @
11
# 65 A
8
# 66 B
8
# 67 C
8
# 68 D
8
# 69 E
8
# 70 F
8
# 71 G
8
# 72 H
8
# 73 I
5
# 74 J
8
# 75 K
8
# 76 L
6
8
# 77 M
9
11
# 78 N
8
# 79 O
8
# 80 P
7
8
# 81 Q
8
# 82 R
7
# 83 S
6
# 84 T
8
# 83 S
8
# 84 T
9
# 85 U
7
8
# 86 V
8
# 87 W
9
11
# 88 X
8
# 89 Y
8
# 90 Z
7
# 91 [
4
# 92 \
5
# 93 ]
4
# 94 ^
5
# 95 _
8
# 91 [
7
# 92 \
11
# 93 ]
7
# 94 ^
6
# 95 _
7
# 96 `
4
6
# 97 a
7
8
# 98 b
7
8
# 99 c
6
8
# 100 d
7
8
# 101 e
7
8
# 102 f
5
8
# 103 g
7
8
# 104 h
7
8
# 105 i
4
5
# 106 j
5
8
# 107 k
7
8
# 108 l
4
8
# 109 m
10
11
# 110 n
7
8
# 111 o
7
8
# 112 p
7
8
# 113 q
7
8
# 114 r
6
8
# 115 s
6
8
# 116 t
5
# 117 u
7
# 118 v
7
# 119 w
9
# 117 u
8
# 118 v
8
# 119 w
11
# 120 x
7
8
# 121 y
7
8
# 122 z
7
# 123 { -> ñ
7
# 124 | -> ç
7
8
# 123 {
1
# 124 |
1
# 125 }
0
1
# 126 ~
0
1

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 KiB

After

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.1 KiB

View File

@@ -1,194 +0,0 @@
# box width
20
# box height
20
# 32 espacio ( )
8
# 33 !
8
# 34 "
10
# 35 #
14
# 36 $
14
# 37 %
16
# 38 &
16
# 39 '
6
# 40 (
10
# 41 )
10
# 42 *
14
# 43 +
14
# 44 ,
8
# 45 -
12
# 46 .
8
# 47 /
10
# 48 0
14
# 49 1
10
# 50 2
14
# 51 6
14
# 52 8
14
# 53 10
14
# 54 12
14
# 55 14
14
# 56 16
14
# 57 18
14
# 58 :
8
# 59 ;
8
# 60 <
12
# 61 =
12
# 62 >
12
# 63 ?
14
# 64 @
16
# 65 A
14
# 66 B
14
# 67 C
14
# 68 D
14
# 69 E
14
# 70 F
14
# 71 G
14
# 72 H
14
# 73 I
8
# 74 J
12
# 75 K
16
# 76 L
12
# 77 M
18
# 78 N
16
# 79 O
16
# 80 P
14
# 81 Q
16
# 82 R
14
# 83 S
12
# 84 T
16
# 85 U
14
# 86 V
16
# 87 W
18
# 88 X
16
# 89 Y
16
# 90 Z
14
# 91 [
8
# 92 \
10
# 93 ]
8
# 94 ^
10
# 95 _
16
# 96 `
8
# 97 a
14
# 98 b
14
# 99 c
12
# 100 d
14
# 101 e
14
# 102 f
10
# 103 g
14
# 104 h
14
# 105 i
8
# 106 j
10
# 107 k
14
# 108 l
8
# 109 m
20
# 110 n
14
# 111 o
14
# 112 p
14
# 113 q
14
# 114 r
12
# 115 s
12
# 116 t
10
# 117 u
14
# 118 v
14
# 119 w
18
# 120 x
14
# 121 y
14
# 122 z
14
# 123 { -> ñ
14
# 124 | -> ç
14
# 125 }
0
# 126 ~
0

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.2 KiB

View File

@@ -1,194 +0,0 @@
# box width
16
# box height
16
# 32 espacio ( )
16
# 33 !
16
# 34 "
16
# 35 #
16
# 36 $
16
# 37 %
16
# 38 &
16
# 39 '
16
# 40 (
16
# 41 )
16
# 42 *
16
# 43 +
16
# 44 ,
16
# 45 -
16
# 46 .
16
# 47 /
16
# 48 0
16
# 49 1
16
# 50 2
16
# 51 3
16
# 52 4
16
# 53 5
16
# 54 6
16
# 55 7
16
# 56 8
16
# 57 9
16
# 58 :
16
# 59 ;
16
# 60 <
16
# 61 =
16
# 62 >
16
# 63 ?
16
# 64 @
16
# 65 A
16
# 66 B
16
# 67 C
16
# 68 D
16
# 69 E
16
# 70 F
16
# 71 G
16
# 72 H
16
# 73 I
16
# 74 J
16
# 75 K
16
# 76 L
16
# 77 M
16
# 78 N
16
# 79 O
16
# 80 P
16
# 81 Q
16
# 82 R
16
# 83 S
16
# 84 T
16
# 85 U
16
# 86 V
16
# 87 W
16
# 88 X
16
# 89 Y
16
# 90 Z
16
# 91 [
16
# 92 \
16
# 93 ]
16
# 94 ^
16
# 95 _
16
# 96 `
16
# 97 a
16
# 98 b
16
# 99 c
16
# 100 d
16
# 101 e
16
# 102 f
16
# 103 g
16
# 104 h
16
# 105 i
16
# 106 j
16
# 107 k
16
# 108 l
16
# 109 m
16
# 110 n
16
# 111 o
16
# 112 p
16
# 113 q
16
# 114 r
16
# 115 s
16
# 116 t
16
# 117 u
16
# 118 v
16
# 119 w
16
# 120 x
16
# 121 y
16
# 122 z
16
# 123 {
16
# 124 |
16
# 125 }
16
# 126 ~
16

Binary file not shown.

Before

Width:  |  Height:  |  Size: 295 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 371 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 332 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 399 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 453 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 392 B

View File

@@ -23,29 +23,64 @@ frames=8,9,10,11
[/animation]
[animation]
name=stand-sideshoot
name=walk-sideshoot-cooldown
speed=5
loop=0
frames=12,13,14,15
[/animation]
[animation]
name=walk-centershoot
name=stand-sideshoot
speed=5
loop=0
frames=16,17,18,19
[/animation]
[animation]
name=stand-centershoot
name=stand-sideshoot-cooldown
speed=5
loop=0
frames=15
[/animation]
[animation]
name=walk-centershoot
speed=5
loop=0
frames=20,21,22,23
[/animation]
[animation]
name=death
speed=15
name=walk-centershoot-cooldown
speed=5
loop=0
frames=24,25,26,27
[/animation]
[animation]
name=stand-centershoot
speed=5
loop=0
frames=28,29,30,31
[/animation]
[animation]
name=stand-centershoot-cooldown
speed=5
loop=0
frames=27
[/animation]
[animation]
name=death
speed=10
loop=0
frames=32,33,34,35
[/animation]
[animation]
name=celebration
speed=10
loop=-1
frames=36,36,36,36,36,36,37,38,39,40,40,40,40,40,40,39,39,39,40,40,40,39,39,39,38,37,36,36,36
[/animation]

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.7 KiB

After

Width:  |  Height:  |  Size: 8.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.5 KiB

After

Width:  |  Height:  |  Size: 7.8 KiB

View File

@@ -347,4 +347,16 @@ Per favor
espere
## 116 - NOTIFICACIONES
Torna a polsar per apagar el sistema
Torna a polsar per apagar el sistema
## 117 - GAME TEXT
SuperPoder!
## 118 - GAME TEXT
+1 Colp
## 119 - GAME TEXT
Temps!
## 120 - SCOREBOARD
Puntuacio

View File

@@ -347,4 +347,16 @@ Please
wait
## 116 - NOTIFICACIONES
Press again to shutdown system
Press again to shutdown system
## 117 - GAME TEXT
PowerUp
## 118 - GAME TEXT
+1 Hit
## 119 - GAME TEXT
Stop!
## 120 - SCOREBOARD
Score

View File

@@ -347,4 +347,16 @@ Por favor
espere
## 94 - NOTIFICACIONES
Pulsa otra vez para apagar el sistema
Pulsa otra vez para apagar el sistema
## 117 - GAME TEXT
Potenciador
## 118 - GAME TEXT
+1 Golpe
## 119 - GAME TEXT
Tiempo!
## 120 - SCOREBOARD
Puntuacion

View File

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

View File

@@ -0,0 +1,53 @@
#!/bin/bash
# Función para mostrar el uso del script
mostrar_uso() {
echo "Uso: $0 [-o opción]"
echo "Opciones:"
echo " w Ejecutar cppcheck con warning, style, performance"
echo " a Ejecutar cppcheck con todas las opciones habilitadas"
echo " u Ejecutar cppcheck para unusedFunction"
}
# Inicializar las variables
opcion=""
# Procesar las opciones
while getopts "o:" opt; do
case $opt in
o)
opcion=$OPTARG
;;
*)
mostrar_uso
exit 1
;;
esac
done
# Ejecutar según la opción seleccionada
case $opcion in
w)
cppcheck --force --enable=warning,style,performance --std=c++20 \
--suppressions-list=./cppcheck_suppressions \
../source/ \
2>./cppcheck-result-warning-style-performance.txt
;;
a)
cppcheck --force --enable=all -I /usr/include --std=c++20 \
--suppress=missingIncludeSystem \
--suppressions-list=./cppcheck_suppressions \
../source/ \
2>./cppcheck-result-all.txt
;;
u)
cppcheck --enable=style --std=c++20 \
--suppressions-list=./cppcheck_suppressions \
../source/ \
2>./cppcheck-result-unusedFunction.txt
;;
*)
mostrar_uso
exit 1
;;
esac

View File

@@ -28,13 +28,13 @@ Balloon::Balloon(float x, float y, BalloonType type, BalloonSize size, float vel
vy_ = 0;
max_vy_ = 3.0f;
const int size = static_cast<int>(size_);
gravity_ = param.balloon.at(size).grav;
default_vy_ = param.balloon.at(size).vel;
h_ = w_ = BALLOON_SIZE[size];
power_ = BALLOON_POWER[size];
menace_ = BALLOON_MENACE[size];
score_ = BALLOON_SCORE[size];
const int index = static_cast<int>(size_);
gravity_ = param.balloon.at(index).grav;
default_vy_ = param.balloon.at(index).vel;
h_ = w_ = BALLOON_SIZE[index];
power_ = BALLOON_POWER[index];
menace_ = BALLOON_MENACE[index];
score_ = BALLOON_SCORE[index];
break;
}
@@ -44,25 +44,25 @@ Balloon::Balloon(float x, float y, BalloonType type, BalloonSize size, float vel
default_vy_ = max_vy_ = vy_ = fabs(vx_ * 2.0f);
gravity_ = 0.00f;
const int size = static_cast<int>(size_);
h_ = w_ = BALLOON_SIZE[size];
power_ = BALLOON_POWER[size];
menace_ = BALLOON_MENACE[size];
score_ = BALLOON_SCORE[size];
const int index = static_cast<int>(size_);
h_ = w_ = BALLOON_SIZE[index];
power_ = BALLOON_POWER[index];
menace_ = BALLOON_MENACE[index];
score_ = BALLOON_SCORE[index];
break;
}
case BalloonType::POWERBALL:
{
const int size = 3;
h_ = w_ = BALLOON_SIZE[size];
const int index = 3;
h_ = w_ = BALLOON_SIZE[index];
power_ = score_ = menace_ = 0;
vy_ = 0;
max_vy_ = 3.0f;
gravity_ = param.balloon.at(size).grav;
default_vy_ = param.balloon.at(size).vel;
gravity_ = param.balloon.at(index).grav;
default_vy_ = param.balloon.at(index).vel;
sprite_->disableRotate();
sprite_->setRotateSpeed(0);
@@ -200,17 +200,11 @@ void Balloon::move()
}
}
// Deshabilita el globo y pone a cero todos los valores
void Balloon::disable()
{
enabled_ = false;
}
// Deshabilita el globo
void Balloon::disable() { enabled_ = false; }
// Explosiona el globo
void Balloon::pop()
{
disable();
}
void Balloon::pop() { disable(); }
// Actualiza al globo a su posicion, animación y controla los contadores
void Balloon::update()
@@ -296,60 +290,6 @@ void Balloon::setAnimation()
sprite_->setCurrentAnimation(isBeingCreated() ? creating_animation : normal_animation);
}
// Comprueba si el globo está habilitado
bool Balloon::isEnabled() const
{
return enabled_;
}
// Obtiene del valor de la variable
float Balloon::getPosX() const
{
return x_;
}
// Obtiene del valor de la variable
float Balloon::getPosY() const
{
return y_;
}
// Obtiene del valor de la variable
int Balloon::getWidth() const
{
return w_;
}
// Obtiene del valor de la variable
int Balloon::getHeight() const
{
return h_;
}
// Establece el valor de la variable
void Balloon::setVelY(float vel_y)
{
vy_ = vel_y;
}
// Establece el valor de la variable
void Balloon::setSpeed(float speed)
{
speed_ = speed;
}
// Obtiene el tamaño del globo
BalloonSize Balloon::getSize() const
{
return size_;
}
// Obtiene el tipo de globo
BalloonType Balloon::getType() const
{
return type_;
}
// Detiene el globo
void Balloon::stop()
{
@@ -366,42 +306,6 @@ void Balloon::start()
sprite_->enableRotate();
}
// Obtiene del valor de la variable
bool Balloon::isStopped() const
{
return stopped_;
}
// Establece el valor de la variable
void Balloon::setInvulnerable(bool value)
{
invulnerable_ = value;
}
// Obtiene del valor de la variable
bool Balloon::isInvulnerable() const
{
return invulnerable_;
}
// Obtiene del valor de la variable
bool Balloon::isBeingCreated() const
{
return being_created_;
}
// Obtiene del valor de la variable
Uint16 Balloon::getScore() const
{
return score_;
}
// Obtiene el circulo de colisión
Circle &Balloon::getCollider()
{
return collider_;
}
// Alinea el circulo de colisión con la posición del objeto globo
void Balloon::shiftColliders()
{
@@ -423,18 +327,6 @@ void Balloon::zoomSprite()
sprite_->setZoomH(bouncing_.zoomH);
}
// Obtiene le valor de la variable
Uint8 Balloon::getMenace() const
{
return isEnabled() ? menace_ : 0;
}
// Obtiene le valor de la variable
Uint8 Balloon::getPower() const
{
return power_;
}
// Activa el efecto
void Balloon::enableBounce()
{
@@ -471,18 +363,6 @@ void Balloon::updateBounce()
}
}
// Indica si el globo se puede explotar
bool Balloon::canBePopped() const
{
return isEnabled() && !isBeingCreated();
}
// Indica si el globo se puede destruir
bool Balloon::canBeDestroyed() const
{
return isEnabled();
}
// Pone el color alternativo en el globo
void Balloon::useReverseColor()
{
@@ -500,8 +380,25 @@ void Balloon::useNormalColor()
setAnimation();
}
// Indica si está usando el color alternativo
bool Balloon::isUsingReversedColor()
{
return use_reversed_colors_;
}
// Getters
float Balloon::getPosX() const { return x_; }
float Balloon::getPosY() const { return y_; }
int Balloon::getWidth() const { return w_; }
int Balloon::getHeight() const { return h_; }
BalloonSize Balloon::getSize() const { return size_; }
BalloonType Balloon::getType() const { return type_; }
Uint16 Balloon::getScore() const { return score_; }
Circle &Balloon::getCollider() { return collider_; }
Uint8 Balloon::getMenace() const { return isEnabled() ? menace_ : 0; }
Uint8 Balloon::getPower() const { return power_; }
bool Balloon::isStopped() const { return stopped_; }
bool Balloon::isInvulnerable() const { return invulnerable_; }
bool Balloon::isBeingCreated() const { return being_created_; }
bool Balloon::isEnabled() const { return enabled_; }
bool Balloon::isUsingReversedColor() { return use_reversed_colors_; }
bool Balloon::canBePopped() const { return !isBeingCreated(); }
// Setters
void Balloon::setVelY(float vel_y) { vy_ = vel_y; }
void Balloon::setSpeed(float speed) { speed_ = speed; }
void Balloon::setInvulnerable(bool value) { invulnerable_ = value; }

View File

@@ -161,75 +161,38 @@ public:
// Actualiza al globo a su posicion, animación y controla los contadores
void update();
// Comprueba si el globo está habilitado
bool isEnabled() const;
// Obtiene del valor de la variable
float getPosX() const;
// Obtiene del valor de la variable
float getPosY() const;
// Obtiene del valor de la variable
int getWidth() const;
// Obtiene del valor de la variable
int getHeight() const;
// Establece el valor de la variable
void setVelY(float vel_y);
// Establece el valor de la variable
void setSpeed(float speed);
// Obtiene el tamaño del globo
BalloonSize getSize() const;
// Obtiene el tipo de globo
BalloonType getType() const;
// Detiene el globo
void stop();
// Pone el globo en movimiento
void start();
// Obtiene del valor de la variable
bool isStopped() const;
// Establece el valor de la variable
void setInvulnerable(bool value);
// Obtiene del valor de la variable
bool isInvulnerable() const;
// Obtiene del valor de la variable
bool isBeingCreated() const;
// Obtiene del valor de la variable
Uint16 getScore() const;
// Obtiene el circulo de colisión
Circle &getCollider();
// Obtiene le valor de la variable
Uint8 getMenace() const;
// Obtiene le valor de la variable
Uint8 getPower() const;
// Indica si el globo se puede explotar
bool canBePopped() const;
// Indica si el globo se puede destruir
bool canBeDestroyed() const;
// Pone el color alternativo en el globo
void useReverseColor();
// Pone el color normal en el globo
void useNormalColor();
// Indica si está usando el color alternativo
// Getters
float getPosX() const;
float getPosY() const;
int getWidth() const;
int getHeight() const;
BalloonSize getSize() const;
BalloonType getType() const;
Uint16 getScore() const;
Circle &getCollider();
Uint8 getMenace() const;
Uint8 getPower() const;
bool isStopped() const;
bool isInvulnerable() const;
bool isBeingCreated() const;
bool isEnabled() const;
bool isUsingReversedColor();
bool canBePopped() const;
// Setters
void setVelY(float vel_y);
void setSpeed(float speed);
void setInvulnerable(bool value);
};

View File

@@ -16,11 +16,11 @@ DefineButtons::DefineButtons(std::unique_ptr<Text> text_)
x_ = param.game.width / 2;
y_ = param.title.press_start_position;
buttons_.emplace_back(lang::getText(95), InputType::FIRE_LEFT, SDL_CONTROLLER_BUTTON_X);
buttons_.emplace_back(lang::getText(96), InputType::FIRE_CENTER, SDL_CONTROLLER_BUTTON_Y);
buttons_.emplace_back(lang::getText(97), InputType::FIRE_RIGHT, SDL_CONTROLLER_BUTTON_RIGHTSHOULDER);
buttons_.emplace_back(lang::getText(98), InputType::START, SDL_CONTROLLER_BUTTON_START);
buttons_.emplace_back(lang::getText(99), InputType::EXIT, SDL_CONTROLLER_BUTTON_BACK);
buttons_.emplace_back(lang::getText(95), InputType::FIRE_LEFT, SDL_CONTROLLER_BUTTON_INVALID);
buttons_.emplace_back(lang::getText(96), InputType::FIRE_CENTER, SDL_CONTROLLER_BUTTON_INVALID);
buttons_.emplace_back(lang::getText(97), InputType::FIRE_RIGHT, SDL_CONTROLLER_BUTTON_INVALID);
buttons_.emplace_back(lang::getText(98), InputType::START, SDL_CONTROLLER_BUTTON_INVALID);
buttons_.emplace_back(lang::getText(99), InputType::SERVICE, SDL_CONTROLLER_BUTTON_INVALID);
for (int i = 0; i < input_->getNumControllers(); ++i)
{
@@ -33,38 +33,40 @@ void DefineButtons::render()
{
if (enabled_)
{
text_->writeCentered(x_, y_ - 10, lang::getText(100) + std::to_string(options.controller[index_controller_].player_id));
text_->writeCentered(x_, y_, controller_names_[index_controller_]);
text_->writeCentered(x_, y_ + 10, buttons_[index_button_].label);
text_->writeCentered(x_, y_ - 10, lang::getText(100) + std::to_string(options.controller.at(index_controller_).player_id));
text_->writeCentered(x_, y_, controller_names_.at(index_controller_));
text_->writeCentered(x_, y_ + 10, buttons_.at(index_button_).label);
}
}
// Comprueba el botón que se ha pulsado
void DefineButtons::doControllerButtonDown(SDL_ControllerButtonEvent *event)
void DefineButtons::doControllerButtonDown(SDL_ControllerButtonEvent &event)
{
int i = input_->getJoyIndex(event->which);
// Solo pillamos botones del mando que toca
if (i != index_controller_)
// Solo pilla botones del mando que toca
if (input_->getJoyIndex(event.which) != static_cast<int>(index_controller_))
{
return;
}
buttons_[index_button_].button = (SDL_GameControllerButton)event->button;
incIndexButton();
const auto button = static_cast<SDL_GameControllerButton>(event.button);
if (checkButtonNotInUse(button))
{
buttons_.at(index_button_).button = button;
incIndexButton();
}
}
// Asigna los botones definidos al input_
void DefineButtons::bindButtons()
{
for (int i = 0; i < (int)buttons_.size(); ++i)
for (const auto &button : buttons_)
{
input_->bindGameControllerButton(index_controller_, buttons_[i].input, buttons_[i].button);
input_->bindGameControllerButton(index_controller_, button.input, button.button);
}
}
// Comprueba las entradas
void DefineButtons::checkInput()
// Comprueba los eventos
void DefineButtons::checkEvents()
{
if (enabled_)
{
@@ -81,13 +83,11 @@ void DefineButtons::checkInput()
section::options = section::Options::QUIT_WITH_KEYBOARD;
break;
}
case SDL_CONTROLLERBUTTONDOWN:
{
doControllerButtonDown(&event.cbutton);
doControllerButtonDown(event.cbutton);
break;
}
default:
break;
}
@@ -110,18 +110,15 @@ bool DefineButtons::enable(int index)
}
// Comprueba si está habilitado
bool DefineButtons::isEnabled()
{
return enabled_;
}
bool DefineButtons::isEnabled() { return enabled_; }
// Incrementa el indice de los botones
void DefineButtons::incIndexButton()
{
index_button_++;
++index_button_;
// Comprueba si ha finalizado
if (index_button_ == (int)buttons_.size())
if (index_button_ == buttons_.size())
{
// Asigna los botones definidos al input_
bindButtons();
@@ -129,8 +126,6 @@ void DefineButtons::incIndexButton()
// Guarda los cambios en las opciones
saveBindingsToOptions();
// input_->allActive(index_controller_);
// Reinicia variables
index_button_ = 0;
index_controller_ = 0;
@@ -142,17 +137,29 @@ void DefineButtons::incIndexButton()
void DefineButtons::saveBindingsToOptions()
{
// Modifica las opciones para colocar los valores asignados
options.controller[index_controller_].name = input_->getControllerName(index_controller_);
for (int j = 0; j < (int)options.controller[index_controller_].inputs.size(); ++j)
auto &controller = options.controller.at(index_controller_);
controller.name = input_->getControllerName(index_controller_);
for (size_t j = 0; j < controller.inputs.size(); ++j)
{
options.controller[index_controller_].buttons[j] = input_->getControllerBinding(index_controller_, options.controller[index_controller_].inputs[j]);
controller.buttons.at(j) = input_->getControllerBinding(index_controller_, controller.inputs.at(j));
}
}
// Intercambia los jugadores asignados a los dos primeros mandos
void DefineButtons::swapControllers()
{
const int temp = options.controller[0].player_id;
options.controller[0].player_id = options.controller[1].player_id;
options.controller[1].player_id = temp;
}
std::swap(options.controller[0].player_id, options.controller[1].player_id);
}
// Comprueba que un botón no esté ya asignado
bool DefineButtons::checkButtonNotInUse(SDL_GameControllerButton button)
{
for (const auto &b : buttons_)
{
if (b.button == button)
{
return false;
}
}
return true;
}

View File

@@ -33,15 +33,15 @@ private:
int x_; // Posición donde dibujar el texto
int y_; // Posición donde dibujar el texto
std::vector<DefineButtonsButton> buttons_; // Vector con las nuevas definiciones de botones/acciones
int index_controller_ = 0; // Indice del controlador a reasignar
int index_button_ = 0; // Indice para saber qué bot´çon se está definiendo
size_t index_controller_ = 0; // Indice del controlador a reasignar
size_t index_button_ = 0; // Indice para saber qué botón se está definiendo
std::vector<std::string> controller_names_; // Nombres de los mandos
// Incrementa el indice de los botones
void incIndexButton();
// Comprueba el botón que se ha pulsado
void doControllerButtonDown(SDL_ControllerButtonEvent *event);
void doControllerButtonDown(SDL_ControllerButtonEvent &event);
// Asigna los botones definidos al input
void bindButtons();
@@ -49,6 +49,9 @@ private:
// Guarda los cambios en las opciones
void saveBindingsToOptions();
// Comprueba que un botón no esté ya asignado
bool checkButtonNotInUse(SDL_GameControllerButton button);
public:
// Constructor
explicit DefineButtons(std::unique_ptr<Text> text);
@@ -59,8 +62,8 @@ public:
// Dibuja el objeto en pantalla
void render();
// Comprueba las entradas
void checkInput();
// Comprueba los eventos
void checkEvents();
// Habilita el objeto
bool enable(int index);

View File

@@ -41,11 +41,19 @@
#include "text.h" // Para Text
#include "title.h" // Para Title
#include "utils.h" // Para Overrides, overrides
#include <chrono>
#ifndef _WIN32
#include <pwd.h> // para getpwuid, passwd
#endif
// Inicia la semilla aleatoria
void initRand()
{
unsigned int seed = static_cast<unsigned int>(std::chrono::system_clock::now().time_since_epoch().count());
std::srand(seed);
}
// Constructor
Director::Director(int argc, const char *argv[])
{
@@ -56,6 +64,7 @@ Director::Director(int argc, const char *argv[])
section::name = section::Name::LOGO;
#else
section::name = section::Name::LOGO;
section::attract_mode = section::AttractMode::TITLE_TO_DEMO;
#endif
#ifndef VERBOSE
@@ -66,6 +75,8 @@ Director::Director(int argc, const char *argv[])
std::cout << "Game start" << std::endl;
initRand();
// Comprueba los parametros del programa
checkProgramArguments(argc, argv);
@@ -88,19 +99,15 @@ Director::Director(int argc, const char *argv[])
#else
const std::string paramFilePath = overrides.param_file == "--320x240" ? Asset::get()->get("param_320x240.txt") : Asset::get()->get("param_320x256.txt");
#endif
loadParams(paramFilePath);
loadParamsFromFile(paramFilePath);
// Carga el fichero de puntuaciones
{
auto manager = std::make_unique<ManageHiScoreTable>(options.game.hi_score_table);
if (overrides.clear_hi_score_table)
{
manager->clear();
}
else
{
manager->loadFromFile(Asset::get()->get("score.bin"));
}
}
// Inicializa SDL
@@ -194,14 +201,6 @@ void Director::bindInputs()
// Mando - Control del programa
Input::get()->bindGameControllerButton(i, InputType::SERVICE, SDL_CONTROLLER_BUTTON_BACK);
Input::get()->bindGameControllerButton(i, InputType::EXIT, InputType::START);
Input::get()->bindGameControllerButton(i, InputType::PAUSE, InputType::FIRE_RIGHT);
Input::get()->bindGameControllerButton(i, InputType::VIDEO_SHADERS, InputType::FIRE_LEFT);
Input::get()->bindGameControllerButton(i, InputType::MUTE, InputType::LEFT);
Input::get()->bindGameControllerButton(i, InputType::SHOWINFO, InputType::RIGHT);
Input::get()->bindGameControllerButton(i, InputType::RESET, InputType::FIRE_CENTER);
Input::get()->bindGameControllerButton(i, InputType::CONFIG, InputType::DOWN);
Input::get()->bindGameControllerButton(i, InputType::SWAP_CONTROLLERS, InputType::UP);
}
// Mapea las asignaciones a los botones desde el archivo de configuración, si se da el caso
@@ -232,10 +231,10 @@ void Director::bindInputs()
// Guarda las asignaciones de botones en las opciones
for (int i = 0; i < num_gamepads; ++i)
{
options.controller[i].name = Input::get()->getControllerName(i);
for (int j = 0; j < (int)options.controller[i].inputs.size(); ++j)
options.controller.at(i).name = Input::get()->getControllerName(i);
for (size_t j = 0; j < options.controller.at(i).inputs.size(); ++j)
{
options.controller[i].buttons[j] = Input::get()->getControllerBinding(i, options.controller[i].inputs[j]);
options.controller.at(i).buttons.at(j) = Input::get()->getControllerBinding(i, options.controller.at(i).inputs.at(j));
}
}
}
@@ -244,10 +243,16 @@ void Director::bindInputs()
void Director::initJailAudio()
{
JA_Init(48000, AUDIO_S16, 2);
JA_EnableMusic(options.audio.music.enabled);
JA_EnableSound(options.audio.sound.enabled);
JA_SetMusicVolume(options.audio.music.volume);
JA_SetSoundVolume(options.audio.sound.volume);
if (options.audio.enabled)
{
JA_SetMusicVolume(to_JA_volume(options.audio.music.volume));
JA_SetSoundVolume(to_JA_volume(options.audio.sound.volume));
}
else
{
JA_SetMusicVolume(0);
JA_SetSoundVolume(0);
}
}
// Arranca SDL y crea la ventana
@@ -264,35 +269,36 @@ bool Director::initSDL()
}
else
{
// Inicia el generador de numeros aleatorios
std::srand(static_cast<unsigned int>(SDL_GetTicks()));
/*
// Muestra información de la pantalla
/*std::cout << "\nDisplay modes list:" << std::endl;
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 << " - " + std::to_string(DM.w) + "x" + std::to_string(DM.h) + " @ " + std::to_string(DM.refresh_rate) + "Hz" << std::endl;
}*/
std::cout << " - " << DM.w << "x" << DM.h << " @ " << DM.refresh_rate << "Hz" << std::endl;
}
*/
SDL_DisplayMode DM;
SDL_GetCurrentDisplayMode(0, &DM);
std::cout << "\nCurrent display mode: " + std::to_string(DM.w) + "x" + std::to_string(DM.h) + " @ " + std::to_string(DM.refresh_rate) + "Hz" << std::endl;
std::cout << "Window resolution : " + std::to_string(param.game.width) + "x" + std::to_string(param.game.height) + " x" + std::to_string(options.video.window.size) << std::endl;
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;
// 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()))
{
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 // NO_SHADERS
// Crea la ventana
#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);
if (!window_)
{
@@ -307,10 +313,12 @@ 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);
if (!renderer_)
@@ -320,14 +328,9 @@ bool Director::initSDL()
}
else
{
// Inicializa el color de renderizado
SDL_SetRenderDrawColor(renderer_, 0x00, 0x00, 0x00, 0xFF);
// Establece el tamaño del buffer de renderizado
SDL_RenderSetLogicalSize(renderer_, param.game.width, param.game.height);
SDL_RenderSetIntegerScale(renderer_, static_cast<SDL_bool>(options.video.integer_scale));
// Establece el modo de mezcla
SDL_SetRenderDrawBlendMode(renderer_, SDL_BLENDMODE_BLEND);
}
}
@@ -427,15 +430,6 @@ void Director::setFileList()
Asset::get()->add(prefix + "/data/gfx/game/game_sky_colors.png", AssetType::BITMAP);
}
{ // Game Text
Asset::get()->add(prefix + "/data/gfx/game_text/game_text_1000_points.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/game_text/game_text_2500_points.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/game_text/game_text_5000_points.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/game_text/game_text_powerup.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/game_text/game_text_one_hit.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/game_text/game_text_stop.png", AssetType::BITMAP);
}
{ // Intro
Asset::get()->add(prefix + "/data/gfx/intro/intro.png", AssetType::BITMAP);
}
@@ -495,16 +489,12 @@ void Director::setFileList()
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_big2.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/font/nokia.txt", AssetType::FONT);
Asset::get()->add(prefix + "/data/font/nokia2.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/font/nokia2.txt", AssetType::FONT);
Asset::get()->add(prefix + "/data/font/nokia_big2.txt", AssetType::FONT);
Asset::get()->add(prefix + "/data/font/smb2_big.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/font/smb2_big.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);
Asset::get()->add(prefix + "/data/font/04b_25.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/font/04b_25.txt", AssetType::FONT);
// Textos
Asset::get()->add(prefix + "/data/lang/es_ES.txt", AssetType::LANG);
@@ -516,16 +506,10 @@ void Director::setFileList()
throw std::runtime_error("Falta algun fichero");
}
// Carga los parametros para configurar el juego
void Director::loadParams(const std::string &file_path)
{
loadParamsFromFile(file_path);
}
// Comprueba los parametros del programa
void Director::checkProgramArguments(int argc, const char *argv[])
{
const std::vector<std::string> argument_list = {"--h", "--320x240", "--clear_score"};
const std::vector<std::string> argument_list = {"--320x240", "--clear_score"};
// Establece la ruta del programa
executable_path_ = argv[0];
@@ -533,23 +517,13 @@ void Director::checkProgramArguments(int argc, const char *argv[])
// Comprueba el resto de parámetros
for (int i = 1; i < argc; ++i)
{
if (strcmp(argv[i], "--h") == 0)
{
for (const auto &argument : argument_list)
{
std::cout << argument << std::endl;
}
// std::exit(EXIT_SUCCESS);
section::name = section::Name::QUIT;
section::options = section::Options::QUIT_FROM_EVENT;
}
std::string arg = argv[i];
if (strcmp(argv[i], "--320x240") == 0)
if (arg == "--320x240")
{
overrides.param_file = argv[i];
overrides.param_file = arg;
}
if (strcmp(argv[i], "--clear_score") == 0)
else if (arg == "--clear_score")
{
overrides.clear_hi_score_table = true;
}
@@ -641,7 +615,11 @@ void Director::runTitle()
void Director::runGame()
{
const auto player_id = section::options == section::Options::GAME_PLAY_1P ? 1 : 2;
#ifdef DEBUG
constexpr auto current_stage = 9;
#else
constexpr auto current_stage = 0;
#endif
auto game = std::make_unique<Game>(player_id, current_stage, GAME_MODE_DEMO_OFF);
game->run();
}
@@ -679,54 +657,57 @@ int Director::run()
case section::Name::INIT:
section::name = section::Name::LOGO;
break;
case section::Name::LOGO:
runLogo();
break;
case section::Name::INTRO:
runIntro();
break;
case section::Name::TITLE:
runTitle();
break;
case section::Name::GAME:
runGame();
break;
case section::Name::HI_SCORE_TABLE:
runHiScoreTable();
break;
case section::Name::GAME_DEMO:
runDemoGame();
break;
case section::Name::INSTRUCTIONS:
runInstructions();
break;
default:
break;
}
}
#ifdef ARCADE
// Comprueba si ha de apagar el sistema
if (section::options == section::Options::QUIT_WITH_CONTROLLER)
shutdownSystem();
#endif
std::string return_code;
switch (section::options)
{
case section::Options::QUIT_WITH_KEYBOARD:
return_code = "with keyboard";
break;
case section::Options::QUIT_WITH_CONTROLLER:
return_code = "with controller";
break;
default:
return_code = "from event";
break;
}
const auto return_code = (section::options == section::Options::QUIT_WITH_KEYBOARD) ? "with keyboard" : (section::options == section::Options::QUIT_WITH_CONTROLLER) ? "with controller"
: "from event";
std::cout << "\nGame end " << return_code << std::endl;
#ifndef VERBOSE
// 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;
}
@@ -739,15 +720,12 @@ std::string Director::getLangFile(lang::Code code)
case lang::Code::ba_BA:
return Asset::get()->get("ba_BA.txt");
break;
case lang::Code::es_ES:
return Asset::get()->get("es_ES.txt");
break;
case lang::Code::en_UK:
return Asset::get()->get("en_UK.txt");
break;
default:
break;
}
@@ -773,4 +751,4 @@ void Director::shutdownSystem()
#error "Sistema operativo no soportado"
#endif
}
#endif // ARCADE
#endif // ARCADE

View File

@@ -34,9 +34,6 @@ private:
// Asigna los botones y teclas al objeto Input
void bindInputs();
// Carga los parametros para configurar el juego
void loadParams(const std::string &file_path);
// Crea el indice de ficheros
void setFileList();

File diff suppressed because it is too large Load Diff

View File

@@ -1,31 +1,31 @@
#pragma once
#include <SDL2/SDL_render.h> // Para SDL_Renderer, SDL_Texture
#include <SDL2/SDL_stdinc.h> // Para Uint32, Uint8
#include <memory> // Para shared_ptr, unique_ptr
#include <string> // Para string
#include <vector> // Para vector
#include "balloon.h" // Para Balloon
#include "manage_hiscore_table.h" // Para HiScoreEntry
#include "options.h" // Para Options, OptionsGame, options
#include "player.h" // Para Player
#include "utils.h" // Para Demo
class Asset; // lines 12-12
class Background; // lines 13-13
class BalloonFormations; // lines 14-14
class Bullet; // lines 15-15
class Explosions; // lines 16-16
class Fade; // lines 17-17
class Input; // lines 18-18
class Item; // lines 19-19
class PathSprite; // lines 20-20
class Scoreboard; // lines 21-21
class Screen; // lines 22-22
class SmartSprite; // lines 23-23
class Text; // lines 24-24
class Texture; // lines 25-25
enum class BulletType : Uint8; // lines 26-26
enum class ItemType; // lines 27-27
#include <SDL2/SDL_render.h> // for SDL_Renderer, SDL_Texture
#include <SDL2/SDL_stdinc.h> // for Uint32, Uint8
#include <memory> // for shared_ptr, unique_ptr
#include <string> // for string
#include <vector> // for vector
#include "balloon.h" // for Balloon
#include "manage_hiscore_table.h" // for HiScoreEntry
#include "options.h" // for Options, OptionsGame, options
#include "player.h" // for Player
#include "utils.h" // for Demo
class Asset; // lines 14-14
class Background; // lines 15-15
class BalloonFormations; // lines 16-16
class Bullet; // lines 17-17
class Explosions; // lines 18-18
class Fade; // lines 19-19
class Input; // lines 20-20
class Item; // lines 21-21
class PathSprite; // lines 22-22
class Scoreboard; // lines 23-23
class Screen; // lines 24-24
class SmartSprite; // lines 25-25
class Texture; // lines 27-27
enum class BulletType : Uint8; // lines 28-28
enum class ItemType; // lines 29-29
struct Path;
// Modo demo
constexpr bool GAME_MODE_DEMO_OFF = false;
@@ -64,10 +64,15 @@ constexpr int TOTAL_SCORE_DATA = 3;
class Game
{
private:
// Constantes
// Enum
enum class GameState
{
PLAYING,
COMPLETED,
GAME_OVER,
};
// Contadores
static constexpr int STAGE_COUNTER_ = 200;
static constexpr int HELP_COUNTER_ = 1000;
static constexpr int GAME_COMPLETED_START_FADE_ = 500;
static constexpr int GAME_COMPLETED_END_ = 700;
@@ -144,12 +149,8 @@ private:
std::vector<std::vector<std::string>> balloon_animations_; // Vector con las animaciones de los globos
std::vector<std::vector<std::string>> explosions_animations_; // Vector con las animaciones de las explosiones
std::unique_ptr<Text> text_; // Fuente para los textos del juego
std::unique_ptr<Text> text_big_; // Fuente de texto grande
std::unique_ptr<Text> text_nokia2_; // Otra fuente de texto para mensajes
std::unique_ptr<Text> text_nokia2_big_; // Y la versión en grande
std::unique_ptr<Fade> fade_; // Objeto para renderizar fades
std::vector<Path> paths_; // Vector con los recorridos precalculados almacenados
// Variables
HiScoreEntry hi_score_ = HiScoreEntry(
@@ -157,21 +158,17 @@ private:
options.game.hi_score_table[0].score); // Máxima puntuación y nombre de quien la ostenta
int current_stage_; // Indica la fase actual
int last_stage_reached_; // Contiene el número de la última pantalla que se ha alcanzado
Demo demo_; // Variable con todas las variables relacionadas con el modo demo
GameDifficulty difficulty_ = options.game.difficulty; // Dificultad del juego
Helper helper_; // Variable para gestionar las ayudas
Uint32 ticks_ = 0; // Contador de ticks para ajustar la velocidad del programa
bool coffee_machine_enabled_ = false; // Indica si hay una máquina de café en el terreno de juego
bool game_completed_ = false; // Indica si se ha completado la partida, llegando al final de la ultima pantalla
bool hi_score_achieved_ = false; // Indica si se ha superado la puntuación máxima
bool paused_ = false; // Indica si el juego está pausado (no se deberia de poder utilizar en el modo arcade)
bool power_ball_enabled_ = false; // Indica si hay una powerball ya activa
float balloon_speed_; // Velocidad a la que se mueven los enemigos
float default_balloon_speed_; // Velocidad base de los enemigos, sin incrementar
float difficulty_score_multiplier_; // Multiplicador de puntos en función de la dificultad
float get_ready_bitmap_path_[STAGE_COUNTER_]; // Vector con los puntos X por donde se desplaza el texto
int stage_bitmap_path_[STAGE_COUNTER_]; // Vector con los puntos Y por donde se desplaza el texto
int balloon_deploy_counter_ = 0; // Cuando se lanza una formación, se le da un valor y no sale otra hasta que llegue a cero
int balloons_popped_ = 0; // Lleva la cuenta de los globos explotados
int counter_ = 0; // Contador para el juego
@@ -182,9 +179,9 @@ private:
int menace_current_ = 0; // Nivel de amenaza actual
int menace_threshold_ = 0; // Umbral del nivel de amenaza. Si el nivel de amenaza cae por debajo del umbral, se generan más globos. Si el umbral aumenta, aumenta el número de globos
int power_ball_counter_ = 0; // Contador de formaciones enemigas entre la aparicion de una PowerBall y otra
int stage_bitmap_counter_ = STAGE_COUNTER_; // Contador para el tiempo visible del texto de Stage
int time_stopped_counter_ = 0; // Temporizador para llevar la cuenta del tiempo detenido
int total_power_to_complete_game_; // La suma del poder necesario para completar todas las fases
GameState state_ = GameState::PLAYING; // Estado
#ifdef DEBUG
bool auto_pop_balloons_ = false; // Si es true, incrementa automaticamente los globos explotados
#endif
@@ -220,7 +217,7 @@ private:
void updateStage();
// Actualiza el estado de fin de la partida
void updateGameOver();
void updateGameOverState();
// Actualiza los globos
void updateBalloons();
@@ -241,7 +238,7 @@ private:
void setBalloonSpeed(float speed);
// Actualiza la velocidad de los globos en funcion del poder acumulado de la fase
void updateBalloonSpeed();
void checkAndUpdateBalloonSpeed();
// Explosiona un globo. Lo destruye y crea otros dos si es el caso
void popBalloon(std::shared_ptr<Balloon> balloon);
@@ -252,6 +249,9 @@ private:
// Destruye todos los globos
void destroyAllBalloons();
// Destruye todos los items
void destroyAllItems();
// Detiene todos los globos
void stopAllBalloons();
@@ -304,7 +304,10 @@ private:
void freeItems();
// Crea un objeto PathSprite
void createPathSprite(int x, std::shared_ptr<Texture> texture);
void createItemText(int x, std::shared_ptr<Texture> texture);
// Crea un objeto PathSprite
void createMessage(const std::vector<Path> &paths, std::shared_ptr<Texture> texture);
// Vacia el vector de smartsprites
void freeSmartSprites();
@@ -348,9 +351,6 @@ private:
// Inicializa las variables que contienen puntos de ruta para mover objetos
void initPaths();
// Pinta diferentes mensajes en la pantalla
void renderMessages();
// Habilita el efecto del item de detener el tiempo
void enableTimeStopItem();
@@ -363,9 +363,6 @@ private:
// Calcula el poder actual de los globos en pantalla
int calculateScreenPower();
// Actualiza el tramo final de juego, una vez completado
void updateGameCompleted();
// Actualiza las variables de ayuda
void updateHelper();
@@ -465,6 +462,27 @@ private:
// Detiene la música
void stopMusic();
// Actualiza las variables durante el modo demo
void updateDemo();
#ifdef RECORDING
// Actualiza las variables durante el modo de grabación
void updateRecording();
#endif
// Actualiza las variables durante el transcurso normal del juego
void updateGame();
// Actualiza las variables durante el transcurso del final del juego
void updateCompletedGame();
// Gestiona eventos para el estado del final del juego
void updateCompletedState();
// Comprueba el estado del juego
void checkState();
// Vacía los vectores de elementos deshabilitados
void cleanVectors();
public:
// Constructor
Game(int playerID, int current_stage, bool demo);

View File

@@ -100,9 +100,7 @@ void GameLogo::render()
crisis_sprite_->render();
if (status_ == Status::FINISHED)
{
arcade_edition_sprite_->render();
}
// Dibuja el polvillo del logo
dust_right_sprite_->render();

View File

@@ -56,10 +56,18 @@ namespace globalInputs
// Activa o desactiva el audio
void switchAudio()
{
options.audio.sound.enabled = options.audio.music.enabled = !options.audio.music.enabled;
JA_EnableMusic(options.audio.music.enabled);
JA_EnableSound(options.audio.sound.enabled);
Notifier::get()->showText("Audio " + boolToOnOff(options.audio.music.enabled));
options.audio.enabled = !options.audio.enabled;
if (options.audio.enabled)
{
JA_SetMusicVolume(to_JA_volume(options.audio.music.volume));
JA_SetSoundVolume(to_JA_volume(options.audio.sound.volume));
}
else
{
JA_SetMusicVolume(0);
JA_SetSoundVolume(0);
}
Notifier::get()->showText("Audio " + boolToOnOff(options.audio.enabled));
}
// Comprueba los inputs que se pueden introducir en cualquier sección del juego
@@ -73,19 +81,19 @@ namespace globalInputs
}
// Comprueba si se va a resetear el juego
else if (Input::get()->checkInput(InputType::RESET, INPUT_DO_NOT_ALLOW_REPEAT, INPUT_USE_KEYBOARD))
if (Input::get()->checkInput(InputType::RESET, INPUT_DO_NOT_ALLOW_REPEAT, INPUT_USE_KEYBOARD))
{
reset();
return;
}
else if (Input::get()->checkInput(InputType::MUTE, INPUT_DO_NOT_ALLOW_REPEAT, INPUT_USE_KEYBOARD))
if (Input::get()->checkInput(InputType::MUTE, INPUT_DO_NOT_ALLOW_REPEAT, INPUT_USE_KEYBOARD))
{
switchAudio();
return;
}
else if (Input::get()->checkInput(InputType::SERVICE, INPUT_ALLOW_REPEAT, INPUT_USE_KEYBOARD))
if (Input::get()->checkInput(InputType::SERVICE, INPUT_ALLOW_REPEAT, INPUT_USE_KEYBOARD))
{
service_pressed_counter[0]++;
@@ -96,29 +104,30 @@ namespace globalInputs
}
return;
}
else
{
service_pressed_counter[0] = 0;
}
service_pressed_counter[0] = 0;
for (int i = 0; i < Input::get()->getNumControllers(); ++i)
{
// Comprueba si se sale con el mando
if (Input::get()->checkModInput(InputType::SERVICE, InputType::EXIT, INPUT_DO_NOT_ALLOW_REPEAT, INPUT_USE_GAMECONTROLLER, i))
if (Input::get()->checkInput(InputType::SERVICE, INPUT_ALLOW_REPEAT, INPUT_USE_GAMECONTROLLER, i) &&
Input::get()->checkInput(InputType::EXIT, INPUT_DO_NOT_ALLOW_REPEAT, INPUT_USE_GAMECONTROLLER, i))
{
quit(section::Options::QUIT_WITH_CONTROLLER);
return;
}
// Comprueba si se va a resetear el juego
else if (Input::get()->checkModInput(InputType::SERVICE, InputType::RESET, INPUT_DO_NOT_ALLOW_REPEAT, INPUT_USE_GAMECONTROLLER, i))
if (Input::get()->checkInput(InputType::SERVICE, INPUT_ALLOW_REPEAT, INPUT_USE_GAMECONTROLLER, i) &&
Input::get()->checkInput(InputType::RESET, INPUT_DO_NOT_ALLOW_REPEAT, INPUT_USE_GAMECONTROLLER, i))
{
reset();
return;
}
// Comprueba si se va a activar o desactivar el audio
else if (Input::get()->checkModInput(InputType::SERVICE, InputType::MUTE, INPUT_DO_NOT_ALLOW_REPEAT, INPUT_USE_GAMECONTROLLER, i))
if (Input::get()->checkInput(InputType::SERVICE, INPUT_ALLOW_REPEAT, INPUT_USE_GAMECONTROLLER, i) &&
Input::get()->checkInput(InputType::MUTE, INPUT_DO_NOT_ALLOW_REPEAT, INPUT_USE_GAMECONTROLLER, i))
{
switchAudio();
return;
@@ -135,10 +144,8 @@ namespace globalInputs
}
return;
}
else
{
service_pressed_counter[i + 1] = 0;
}
service_pressed_counter[i + 1] = 0;
}
}
}

View File

@@ -4,6 +4,8 @@
#include <SDL2/SDL_events.h> // para SDL_ENABLE
#include <SDL2/SDL_keyboard.h> // para SDL_GetKeyboardState
#include <iostream> // para basic_ostream, operator<<, cout, basi...
#include <unordered_map>
#include <algorithm>
// [SINGLETON] Hay que definir las variables estáticas, desde el .h sólo la hemos declarado
Input *Input::input_ = nullptr;
@@ -28,49 +30,23 @@ Input *Input::get()
// Constructor
Input::Input(const std::string &game_controller_db_path)
: game_controller_db_path_(game_controller_db_path),
enabled_(true)
: game_controller_db_path_(game_controller_db_path)
{
// Busca si hay mandos conectados
discoverGameControllers();
// Inicializa las vectores
KeyBindings kb;
kb.scancode = 0;
kb.active = false;
key_bindings_.resize(static_cast<int>(InputType::NUMBER_OF_INPUTS), kb);
ControllerBindings gcb;
gcb.button = SDL_CONTROLLER_BUTTON_INVALID;
gcb.active = false;
controller_bindings_.resize(num_gamepads_);
for (int i = 0; i < num_gamepads_; ++i)
{
controller_bindings_[i].resize(static_cast<int>(InputType::NUMBER_OF_INPUTS), gcb);
}
// Listado de los inputs usados para jugar, excluyendo botones para la interfaz
game_inputs_.clear();
game_inputs_.push_back(InputType::FIRE_LEFT);
game_inputs_.push_back(InputType::FIRE_CENTER);
game_inputs_.push_back(InputType::FIRE_RIGHT);
game_inputs_.push_back(InputType::UP);
game_inputs_.push_back(InputType::DOWN);
game_inputs_.push_back(InputType::LEFT);
game_inputs_.push_back(InputType::RIGHT);
// Inicializa los vectores
key_bindings_.resize(static_cast<int>(InputType::NUMBER_OF_INPUTS), KeyBindings());
controller_bindings_.resize(num_gamepads_, std::vector<ControllerBindings>(static_cast<int>(InputType::NUMBER_OF_INPUTS), ControllerBindings()));
// Listado de los inputs para jugar que utilizan botones, ni palancas ni crucetas
button_inputs_.clear();
button_inputs_.push_back(InputType::FIRE_LEFT);
button_inputs_.push_back(InputType::FIRE_CENTER);
button_inputs_.push_back(InputType::FIRE_RIGHT);
button_inputs_.push_back(InputType::START);
button_inputs_ = {InputType::FIRE_LEFT, InputType::FIRE_CENTER, InputType::FIRE_RIGHT, InputType::START};
}
// Asigna inputs a teclas
void Input::bindKey(InputType input, SDL_Scancode code)
{
key_bindings_[static_cast<int>(input)].scancode = code;
key_bindings_.at(static_cast<int>(input)).scancode = code;
}
// Asigna inputs a botones del mando
@@ -78,7 +54,7 @@ void Input::bindGameControllerButton(int controller_index, InputType input, SDL_
{
if (controller_index < num_gamepads_)
{
controller_bindings_[controller_index][static_cast<int>(input)].button = button;
controller_bindings_.at(controller_index).at(static_cast<int>(input)).button = button;
}
}
@@ -87,129 +63,13 @@ void Input::bindGameControllerButton(int controller_index, InputType input_targe
{
if (controller_index < num_gamepads_)
{
controller_bindings_[controller_index][static_cast<int>(input_target)].button = controller_bindings_[controller_index][static_cast<int>(input_source)].button;
controller_bindings_.at(controller_index).at(static_cast<int>(input_target)).button = controller_bindings_.at(controller_index).at(static_cast<int>(input_source)).button;
}
}
// Comprueba si un input esta activo
bool Input::checkInput(InputType input, bool repeat, int device, int controller_index)
{
if (!enabled_)
{
return false;
}
bool success_keyboard = false;
bool success_controller = false;
const int input_index = static_cast<int>(input);
if (device == INPUT_USE_ANY)
{
controller_index = 0;
}
if (device == INPUT_USE_KEYBOARD || device == INPUT_USE_ANY)
{
const Uint8 *keyStates = SDL_GetKeyboardState(nullptr);
if (repeat)
{
if (keyStates[key_bindings_[input_index].scancode] != 0)
{
success_keyboard = true;
}
else
{
success_keyboard = false;
}
}
else
{
if (!key_bindings_[input_index].active)
{
if (keyStates[key_bindings_[input_index].scancode] != 0)
{
key_bindings_[input_index].active = true;
success_keyboard = true;
}
else
{
success_keyboard = false;
}
}
else
{
if (keyStates[key_bindings_[input_index].scancode] == 0)
{
key_bindings_[input_index].active = false;
success_keyboard = false;
}
else
{
success_keyboard = false;
}
}
}
}
if (gameControllerFound() && controller_index < num_gamepads_)
if ((device == INPUT_USE_GAMECONTROLLER) || (device == INPUT_USE_ANY))
{
success_controller = checkAxisInput(input, controller_index);
if (!success_controller)
{
if (repeat)
{
if (SDL_GameControllerGetButton(connected_controllers_[controller_index], controller_bindings_[controller_index][input_index].button) != 0)
{
success_controller = true;
}
else
{
success_controller = false;
}
}
else
{
if (!controller_bindings_[controller_index][input_index].active)
{
if (SDL_GameControllerGetButton(connected_controllers_[controller_index], controller_bindings_[controller_index][input_index].button) != 0)
{
controller_bindings_[controller_index][input_index].active = true;
success_controller = true;
}
else
{
success_controller = false;
}
}
else
{
if (SDL_GameControllerGetButton(connected_controllers_[controller_index], controller_bindings_[controller_index][input_index].button) == 0)
{
controller_bindings_[controller_index][input_index].active = false;
success_controller = false;
}
else
{
success_controller = false;
}
}
}
}
}
return (success_keyboard || success_controller);
}
// Comprueba si un input con modificador esta activo
bool Input::checkModInput(InputType input_mod, InputType input, bool repeat, int device, int controller_index)
{
if (!enabled_ || controller_index >= num_gamepads_ || !checkInput(input_mod, INPUT_ALLOW_REPEAT, device, controller_index))
{
return false;
}
bool success_keyboard = false;
bool success_controller = false;
const int input_index = static_cast<int>(input);
@@ -396,9 +256,7 @@ bool Input::discoverGameControllers()
if (SDL_GameControllerAddMappingsFromFile(game_controller_db_path_.c_str()) < 0)
{
{
std::cout << "Error, could not load " << game_controller_db_path_.c_str() << " file: " << SDL_GetError() << std::endl;
}
std::cout << "Error, could not load " << game_controller_db_path_.c_str() << " file: " << SDL_GetError() << std::endl;
}
num_joysticks_ = SDL_NumJoysticks();
@@ -408,7 +266,7 @@ bool Input::discoverGameControllers()
joysticks_.clear();
for (int i = 0; i < num_joysticks_; ++i)
{
SDL_Joystick *joy = SDL_JoystickOpen(i);
auto joy = SDL_JoystickOpen(i);
joysticks_.push_back(joy);
if (SDL_IsGameController(i))
{
@@ -417,7 +275,6 @@ bool Input::discoverGameControllers()
}
std::cout << "\n** LOOKING FOR GAME CONTROLLERS" << std::endl;
// std::cout << " " << num_joysticks_ << " joysticks found" << std::endl;
std::cout << "Gamepads found: " << num_gamepads_ << std::endl;
if (num_gamepads_ > 0)
@@ -432,16 +289,12 @@ bool Input::discoverGameControllers()
{
connected_controllers_.push_back(pad);
const std::string name = SDL_GameControllerNameForIndex(i);
{
std::cout << "#" << i << ": " << name << std::endl;
}
std::cout << "#" << i << ": " << name << std::endl;
controller_names_.push_back(name);
}
else
{
{
std::cout << "SDL_GetError() = " << SDL_GetError() << std::endl;
}
std::cout << "SDL_GetError() = " << SDL_GetError() << std::endl;
}
}
@@ -449,27 +302,17 @@ bool Input::discoverGameControllers()
}
std::cout << "\n** FINISHED LOOKING FOR GAME CONTROLLERS" << std::endl;
return found;
}
// Comprueba si hay algun mando conectado
bool Input::gameControllerFound()
{
return num_gamepads_ > 0 ? true : false;
}
bool Input::gameControllerFound() { return num_gamepads_ > 0 ? true : false; }
// Obten el nombre de un mando de juego
std::string Input::getControllerName(int controller_index) const
{
return num_gamepads_ > 0 ? controller_names_[controller_index] : "";
}
std::string Input::getControllerName(int controller_index) const { return num_gamepads_ > 0 ? controller_names_.at(controller_index) : std::string(); }
// Obten el número de mandos conectados
int Input::getNumControllers() const
{
return num_gamepads_;
}
int Input::getNumControllers() const { return num_gamepads_; }
// Obtiene el indice del controlador a partir de un event.id
int Input::getJoyIndex(int id) const
@@ -500,13 +343,12 @@ void Input::printBindings(int device, int controller_index) const
}
// Muestra el nombre del mando
std::cout << "\n"
<< controller_names_[controller_index] << std::endl;
std::cout << "\n" + controller_names_.at(controller_index) << std::endl;
// Muestra los botones asignados
for (auto bi : button_inputs_)
{
std::cout << to_string(bi) << " : " << controller_bindings_[controller_index][static_cast<int>(bi)].button << std::endl;
std::cout << to_string(bi) << " : " << controller_bindings_.at(controller_index).at(static_cast<int>(bi)).button << std::endl;
}
}
}
@@ -520,116 +362,58 @@ SDL_GameControllerButton Input::getControllerBinding(int controller_index, Input
// Obtiene el indice a partir del nombre del mando
int Input::getIndexByName(const std::string &name) const
{
for (int i = 0; i < num_gamepads_; ++i)
{
if (controller_names_[i] == name)
{
return i;
}
}
return -1;
auto it = std::find(controller_names_.begin(), controller_names_.end(), name);
return it != controller_names_.end() ? std::distance(controller_names_.begin(), it) : -1;
}
// Convierte un InputType a std::string
std::string Input::to_string(InputType input) const
{
if (input == InputType::FIRE_LEFT)
switch (input)
{
case InputType::FIRE_LEFT:
return "input_fire_left";
}
if (input == InputType::FIRE_CENTER)
{
case InputType::FIRE_CENTER:
return "input_fire_center";
}
if (input == InputType::FIRE_RIGHT)
{
case InputType::FIRE_RIGHT:
return "input_fire_right";
}
if (input == InputType::START)
{
case InputType::START:
return "input_start";
}
if (input == InputType::SERVICE)
{
case InputType::SERVICE:
return "input_service";
default:
return "";
}
return "";
}
// Convierte un std::string a InputType
InputType Input::to_inputs_e(const std::string &name) const
{
if (name == "input_fire_left")
{
return InputType::FIRE_LEFT;
}
static const std::unordered_map<std::string, InputType> inputMap = {
{"input_fire_left", InputType::FIRE_LEFT},
{"input_fire_center", InputType::FIRE_CENTER},
{"input_fire_right", InputType::FIRE_RIGHT},
{"input_start", InputType::START},
{"input_service", InputType::SERVICE}};
if (name == "input_fire_center")
{
return InputType::FIRE_CENTER;
}
if (name == "input_fire_right")
{
return InputType::FIRE_RIGHT;
}
if (name == "input_start")
{
return InputType::START;
}
if (name == "input_service")
{
return InputType::SERVICE;
}
return InputType::NONE;
auto it = inputMap.find(name);
return it != inputMap.end() ? it->second : InputType::NONE;
}
// Comprueba el eje del mando
bool Input::checkAxisInput(InputType input, int controller_index) const
{
bool success = false;
switch (input)
{
case InputType::LEFT:
if (SDL_GameControllerGetAxis(connected_controllers_[controller_index], SDL_CONTROLLER_AXIS_LEFTX) < -30000)
{
success = true;
}
break;
return SDL_GameControllerGetAxis(connected_controllers_[controller_index], SDL_CONTROLLER_AXIS_LEFTX) < -30000;
case InputType::RIGHT:
if (SDL_GameControllerGetAxis(connected_controllers_[controller_index], SDL_CONTROLLER_AXIS_LEFTX) > 30000)
{
success = true;
}
break;
return SDL_GameControllerGetAxis(connected_controllers_[controller_index], SDL_CONTROLLER_AXIS_LEFTX) > 30000;
case InputType::UP:
if (SDL_GameControllerGetAxis(connected_controllers_[controller_index], SDL_CONTROLLER_AXIS_LEFTY) < -30000)
{
success = true;
}
break;
return SDL_GameControllerGetAxis(connected_controllers_[controller_index], SDL_CONTROLLER_AXIS_LEFTY) < -30000;
case InputType::DOWN:
if (SDL_GameControllerGetAxis(connected_controllers_[controller_index], SDL_CONTROLLER_AXIS_LEFTY) > 30000)
{
success = true;
}
break;
return SDL_GameControllerGetAxis(connected_controllers_[controller_index], SDL_CONTROLLER_AXIS_LEFTY) > 30000;
default:
break;
return false;
}
return success;
}

View File

@@ -66,12 +66,20 @@ private:
{
Uint8 scancode; // Scancode asociado
bool active; // Indica si está activo
// Constructor
explicit KeyBindings(Uint8 sc = 0, bool act = false)
: scancode(sc), active(act) {}
};
struct ControllerBindings
{
SDL_GameControllerButton button; // GameControllerButton asociado
bool active; // Indica si está activo
// Constructor
explicit ControllerBindings(SDL_GameControllerButton btn = SDL_CONTROLLER_BUTTON_INVALID, bool act = false)
: button(btn), active(act) {}
};
// Variables
@@ -80,12 +88,10 @@ private:
std::vector<KeyBindings> key_bindings_; // Vector con las teclas asociadas a los inputs predefinidos
std::vector<std::vector<ControllerBindings>> controller_bindings_; // Vector con los botones asociadas a los inputs predefinidos para cada mando
std::vector<std::string> controller_names_; // Vector con los nombres de los mandos
std::vector<InputType> game_inputs_; // Inputs usados para jugar, normalmente direcciones y botones
std::vector<InputType> button_inputs_; // Inputs asignados al jugador y a botones, excluyendo direcciones
int num_joysticks_; // Número de joysticks conectados
int num_gamepads_; // Número de mandos conectados
int num_joysticks_ = 0; // Número de joysticks conectados
int num_gamepads_ = 0; // Número de mandos conectados
std::string game_controller_db_path_; // Ruta al archivo gamecontrollerdb.txt
bool enabled_; // Indica si está habilitado
// Comprueba el eje del mando
bool checkAxisInput(InputType input, int controller_index = 0) const;
@@ -116,9 +122,6 @@ public:
// Comprueba si un input esta activo
bool checkInput(InputType input, bool repeat = true, int device = INPUT_USE_ANY, int controller_index = 0);
// Comprueba si un input con modificador esta activo
bool checkModInput(InputType input_mod, InputType input, bool repeat = true, int device = INPUT_USE_ANY, int controller_index = 0);
// Comprueba si hay almenos un input activo
bool checkAnyInput(int device = INPUT_USE_ANY, int controller_index = 0);

View File

@@ -139,9 +139,7 @@ Intro::Intro()
texts_[8]->setSpeed(16);
for (auto &text : texts_)
{
text->center(param.game.game_area.center_x);
}
}
// Recarga todas las texturas
@@ -171,9 +169,7 @@ void Intro::checkEvents()
case SDL_WINDOWEVENT:
{
if (event.window.event == SDL_WINDOWEVENT_SIZE_CHANGED)
{
reloadTextures();
}
break;
}

View File

@@ -53,6 +53,13 @@ Logo::Logo()
color_.push_back(Color(0xFF, 0xFF, 0xFF)); // Bright white
}
// Destructor
Logo::~Logo()
{
jail_texture_->setColor(255, 255, 255);
since_texture_->setColor(255, 255, 255);
}
// Recarga todas las texturas
void Logo::reloadTextures()
{

View File

@@ -65,7 +65,7 @@ public:
Logo();
// Destructor
~Logo() = default;
~Logo();
// Bucle principal
void run();

View File

@@ -32,10 +32,12 @@ void initOptions()
options.video.shaders = true;
// Opciones de audio
options.audio.enabled = true;
options.audio.volume = 100;
options.audio.music.enabled = true;
options.audio.music.volume = 128;
options.audio.music.volume = 100;
options.audio.sound.enabled = true;
options.audio.sound.volume = 64;
options.audio.sound.volume = 50;
// Opciones de juego
options.game.difficulty = GameDifficulty::NORMAL;
@@ -178,9 +180,11 @@ bool saveOptionsFile(std::string file_path)
// Opciones de audio
file << "\n\n## AUDIO\n";
file << "## volume [0 .. 128]\n";
file << "## volume [0 .. 100]\n";
file << "\n";
file << "audio.enabled=" + boolToString(options.audio.enabled) + "\n";
file << "audio.volume=" + std::to_string(options.audio.volume) + "\n";
file << "audio.music.enabled=" + boolToString(options.audio.music.enabled) + "\n";
file << "audio.music.volume=" + std::to_string(options.audio.music.volume) + "\n";
file << "audio.sound.enabled=" + boolToString(options.audio.sound.enabled) + "\n";
@@ -269,6 +273,15 @@ bool setOptions(const std::string &var, const std::string &value)
}
// Opciones de audio
else if (var == "audio.enabled")
{
options.audio.enabled = stringToBool(value);
}
else if (var == "audio.volume")
{
options.audio.volume = std::stoi(value);
}
else if (var == "audio.music.enabled")
{
options.audio.music.enabled = stringToBool(value);
@@ -387,4 +400,11 @@ bool setOptions(const std::string &var, const std::string &value)
}
return success;
}
// Convierte valores de 0 a 100 en valores de 0 a 128
int to_JA_volume(int vol)
{
vol = vol * 1.28f;
return std::clamp(vol, 0, 128);
}

View File

@@ -57,6 +57,8 @@ struct OptionsAudio
{
OptionsMusic music; // Opciones para la música
OptionsSound sound; // Opciones para los efectos de sonido
bool enabled; // Indica si el audio está activo o no
int volume; // Volumen al que suenan el audio
};
// Estructura para las opciones del juego
@@ -96,4 +98,7 @@ extern Options options;
bool loadOptionsFile(std::string file_path);
// Guarda el fichero de configuración
bool saveOptionsFile(std::string file_path);
bool saveOptionsFile(std::string file_path);
// Convierte valores de 0 a 100 en valores de 0 a 128
int to_JA_volume(int vol);

View File

@@ -23,6 +23,7 @@ void initParam()
param.game.item_size = 20;
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;
precalculateZones();
// SCOREBOARD

View File

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

View File

@@ -1,40 +1,11 @@
#include "path_sprite.h"
#include <bits/std_abs.h> // Para abs
#include <stdlib.h> // Para abs
#include <utility> // Para move
#include "moving_sprite.h" // Para MovingSprite
#include "utils.h" // Para easeOutQuint
#include <functional>
class Texture; // lines 3-3
// Constructor
PathSprite::PathSprite(std::shared_ptr<Texture> texture)
: AnimatedSprite(texture) {}
// Actualiza la posición y comprueba si ha llegado a su destino
void PathSprite::update()
{
if (enabled_)
{
moveThroughCurrentPath();
goToNextPathOrDie();
}
}
// Añade un recorrido
void PathSprite::addPath(int start, int end, PathType type, int fixed_pos, int steps, const std::function<double(double)> &easingFunction, int waiting_counter)
{
paths_.emplace_back(createPath(start, end, type, fixed_pos, steps, easingFunction), waiting_counter);
}
// Añade un recorrido
void PathSprite::addPath(std::vector<SDL_Point> spots, int waiting_counter)
{
paths_.emplace_back(std::move(spots), waiting_counter);
}
#include <cmath> // for abs
#include <stdlib.h> // for abs
#include <functional> // for function
#include <utility> // for move
// Devuelve un vector con los puntos que conforman la ruta
std::vector<SDL_Point> PathSprite::createPath(int start, int end, PathType type, int fixed_pos, int steps, const std::function<double(double)> &easingFunction)
std::vector<SDL_Point> createPath(int start, int end, PathType type, int fixed_pos, int steps, const std::function<double(double)> &easingFunction)
{
std::vector<SDL_Point> v;
v.reserve(steps);
@@ -69,6 +40,59 @@ std::vector<SDL_Point> PathSprite::createPath(int start, int end, PathType type,
return v;
}
// Actualiza la posición y comprueba si ha llegado a su destino
void PathSprite::update()
{
if (enabled_)
{
moveThroughCurrentPath();
goToNextPathOrDie();
}
}
// Añade un recorrido
void PathSprite::addPath(Path path, bool centered)
{
PathCentered path_centered = PathCentered::NONE;
if (centered)
path_centered = (path.spots.back().x == path.spots.front().x) ? PathCentered::ON_X : PathCentered::ON_Y;
switch (path_centered)
{
case PathCentered::ON_X:
{
const int x = path.spots.back().x - pos_.w / 2;
for (auto &spot : path.spots)
spot.x = x;
paths_.emplace_back(path);
break;
}
case PathCentered::ON_Y:
{
const int y = path.spots.back().y - pos_.h / 2;
for (auto &spot : path.spots)
spot.y = y;
paths_.emplace_back(path);
break;
}
default:
paths_.emplace_back(path);
break;
}
}
// Añade un recorrido
void PathSprite::addPath(int start, int end, PathType type, int fixed_pos, int steps, const std::function<double(double)> &easingFunction, int waiting_counter)
{
paths_.emplace_back(createPath(start, end, type, fixed_pos, steps, easingFunction), waiting_counter);
}
// Añade un recorrido
void PathSprite::addPath(std::vector<SDL_Point> spots, int waiting_counter)
{
paths_.emplace_back(std::move(spots), waiting_counter);
}
// Habilita el objeto
void PathSprite::enable()
{
@@ -82,7 +106,7 @@ void PathSprite::moveThroughCurrentPath()
// Establece la posición
const auto &p = path.spots.at(path.counter);
MovingSprite::setPos(p.x, p.y);
setPosition(p);
// Comprobar si ha terminado el recorrido
if (!path.on_destination)
@@ -101,7 +125,7 @@ void PathSprite::moveThroughCurrentPath()
if (path.waiting_counter == 0)
path.finished = true;
else
--path.waiting_counter;
--path.waiting_counter;
}
}

View File

@@ -1,11 +1,11 @@
#pragma once
#include <SDL2/SDL_rect.h> // Para SDL_Point
#include <memory> // Para shared_ptr
#include <functional>
#include <vector> // Para vector
#include "animated_sprite.h" // Para AnimatedSprite
class Texture; // lines 5-5
#include <SDL2/SDL_rect.h> // for SDL_Point
#include <functional> // for function
#include <memory> // for shared_ptr
#include <vector> // for vector
#include "sprite.h" // for Sprite
class Texture; // lines 8-8
enum class PathType
{
@@ -13,26 +13,35 @@ enum class PathType
HORIZONTAL,
};
enum class PathCentered
{
ON_X,
ON_Y,
NONE,
};
// Estructuras
struct Path
{
std::vector<SDL_Point> spots; // Puntos por los que se desplazará el sprite
int waiting_counter; // Tiempo de espera una vez en el destino
bool on_destination = false; // Indica si ha llegado al destino
bool finished = false; // Indica si ha terminado de esperarse
int counter = 0; // Contador interno
// Constructor
Path(const std::vector<SDL_Point> &spots_init, int waiting_counter_init)
: spots(spots_init), waiting_counter(waiting_counter_init) {}
};
// Devuelve un vector con los puntos que conforman la ruta
std::vector<SDL_Point> createPath(int start, int end, PathType type, int fixed_pos, int steps, const std::function<double(double)> &easingFunction);
// Clase PathSprite
class PathSprite : public AnimatedSprite
class PathSprite : public Sprite
{
private:
// Estructuras
struct Path
{
std::vector<SDL_Point> spots; // Puntos por los que se desplazará el sprite
int waiting_counter; // Tiempo de espera una vez en el destino
bool on_destination = false; // Indica si ha llegado al destino
bool finished = false; // Indica si ha terminado de esperarse
int counter = 0; // Contador interno
// Constructor
Path(const std::vector<SDL_Point> &spots_init, int waiting_counter_init)
: spots(spots_init), waiting_counter(waiting_counter_init) {}
};
// Variables
bool finished_ = false; // Indica si ya ha terminado
bool enabled_ = false; // Indica si el objeto está habilitado
int current_path_ = 0; // Path que se está recorriendo actualmente
std::vector<Path> paths_; // Caminos a recorrer por el sprite
@@ -45,21 +54,20 @@ private:
public:
// Constructor
explicit PathSprite(std::shared_ptr<Texture> texture);
explicit PathSprite(std::shared_ptr<Texture> texture)
: Sprite(texture) {}
// Destructor
~PathSprite() = default;
// Actualiza la posición del sprite
void update() override;
void update();
// 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);
// Devuelve un vector con los puntos que conforman la ruta
std::vector<SDL_Point> createPath(int start, int end, PathType type, int fixed_pos, int steps, const std::function<double(double)> &easingFunction);
// Habilita el objeto
void enable();

View File

@@ -39,9 +39,9 @@ void Player::init()
// Inicializa variables de estado
pos_x_ = default_pos_x_;
pos_y_ = default_pos_y_;
status_walking_ = PlayerStatus::WALKING_STOP;
status_firing_ = PlayerStatus::FIRING_NONE;
status_playing_ = PlayerStatus::WAITING;
walking_state_ = PlayerState::WALKING_STOP;
firing_state_ = PlayerState::FIRING_NONE;
playing_state_ = PlayerState::WAITING;
invulnerable_ = true;
invulnerable_counter_ = INVULNERABLE_COUNTER_;
power_up_ = false;
@@ -61,8 +61,7 @@ void Player::init()
// Establece la posición del sprite
player_sprite_->clear();
player_sprite_->setPosX(pos_x_);
player_sprite_->setPosY(pos_y_);
shiftSprite();
// Selecciona un frame para pintar
player_sprite_->setCurrentAnimation("stand");
@@ -71,20 +70,19 @@ void Player::init()
// Actua en consecuencia de la entrada recibida
void Player::setInput(InputType input)
{
switch (status_playing_)
switch (playing_state_)
{
case PlayerStatus::PLAYING:
case PlayerState::PLAYING:
{
setInputPlaying(input);
break;
}
case PlayerStatus::ENTERING_NAME:
case PlayerState::ENTERING_NAME:
case PlayerState::ENTERING_NAME_GAME_COMPLETED:
{
setInputEnteringName(input);
break;
}
default:
break;
}
@@ -98,39 +96,34 @@ void Player::setInputPlaying(InputType input)
case InputType::LEFT:
{
vel_x_ = -BASE_SPEED_;
setWalkingStatus(PlayerStatus::WALKING_LEFT);
setWalkingState(PlayerState::WALKING_LEFT);
break;
}
case InputType::RIGHT:
{
vel_x_ = BASE_SPEED_;
setWalkingStatus(PlayerStatus::WALKING_RIGHT);
setWalkingState(PlayerState::WALKING_RIGHT);
break;
}
case InputType::FIRE_CENTER:
{
setFiringStatus(PlayerStatus::FIRING_UP);
setFiringState(PlayerState::FIRING_UP);
break;
}
case InputType::FIRE_LEFT:
{
setFiringStatus(PlayerStatus::FIRING_LEFT);
setFiringState(PlayerState::FIRING_LEFT);
break;
}
case InputType::FIRE_RIGHT:
{
setFiringStatus(PlayerStatus::FIRING_RIGHT);
setFiringState(PlayerState::FIRING_RIGHT);
break;
}
default:
{
vel_x_ = 0;
setWalkingStatus(PlayerStatus::WALKING_STOP);
setWalkingState(PlayerState::WALKING_STOP);
break;
}
}
@@ -144,23 +137,18 @@ void Player::setInputEnteringName(InputType input)
case InputType::LEFT:
enter_name_->decPosition();
break;
case InputType::RIGHT:
enter_name_->incPosition();
break;
case InputType::UP:
enter_name_->incIndex();
break;
case InputType::DOWN:
enter_name_->decIndex();
break;
case InputType::START:
setRecordName(enter_name_->getName());
break;
default:
break;
}
@@ -170,44 +158,57 @@ void Player::setInputEnteringName(InputType input)
// Mueve el jugador a la posición y animación que le corresponde
void Player::move()
{
if (isPlaying())
switch (playing_state_)
{
case PlayerState::PLAYING:
{
// Mueve el jugador a derecha o izquierda
pos_x_ += vel_x_;
// Si el jugador abandona el area de juego por los laterales
if ((pos_x_ < param.game.play_area.rect.x - 5) || (pos_x_ + WIDTH_ > play_area_.w + 5))
{
// Restaura su posición
pos_x_ -= vel_x_;
}
// Si el jugador abandona el area de juego por los laterales, restaura su posición
const float min_x = param.game.play_area.rect.x - 5;
const float max_x = play_area_.w + 5 - WIDTH_;
pos_x_ = std::clamp(pos_x_, min_x, max_x);
// Actualiza la posición del sprite
player_sprite_->setPosX(getPosX());
player_sprite_->setPosY(pos_y_);
power_sprite_->setPosX(getPosX() - power_up_desp_x_);
shiftSprite();
break;
}
else if (isDying())
case PlayerState::DYING:
{
player_sprite_->update();
// Si el cadaver abandona el area de juego por los laterales
// Si el cadaver abandona el area de juego por los laterales lo hace rebotar
if ((player_sprite_->getPosX() < param.game.play_area.rect.x) || (player_sprite_->getPosX() + WIDTH_ > play_area_.w))
{
// Restaura su posición
const float vx = player_sprite_->getVelX();
player_sprite_->setPosX(player_sprite_->getPosX() - vx);
// Rebota
player_sprite_->setVelX(-vx);
}
player_sprite_->setVelX(-player_sprite_->getVelX());
// Si el cadaver abandona el area de juego por abajo
if (player_sprite_->getPosY() > param.game.play_area.rect.h)
setPlayingState(PlayerState::DIED);
break;
}
case PlayerState::GAME_COMPLETED:
{
switch (id_)
{
setStatusPlaying(PlayerStatus::DIED);
case 1:
setInputPlaying(InputType::LEFT);
break;
case 2:
setInputPlaying(InputType::RIGHT);
break;
default:
break;
}
pos_x_ += vel_x_;
const float min_x = -WIDTH_;
const float max_x = play_area_.w;
pos_x_ = std::clamp(pos_x_, min_x, max_x);
shiftSprite();
if (pos_x_ == min_x || pos_x_ == max_x)
setPlayingState(PlayerState::GAME_OVER);
break;
}
default:
break;
}
}
@@ -215,118 +216,95 @@ void Player::move()
void Player::render()
{
if (power_up_ && isPlaying())
{
if (power_up_counter_ > (POWERUP_COUNTER_ / 4) || power_up_counter_ % 20 > 4)
{
power_sprite_->render();
}
}
if (isRenderable())
player_sprite_->render();
}
// Establece el estado del jugador cuando camina
void Player::setWalkingStatus(PlayerStatus status)
{
status_walking_ = status;
}
// Establece el estado del jugador cuando dispara
void Player::setFiringStatus(PlayerStatus status)
{
status_firing_ = status;
}
// Establece la animación correspondiente al estado
void Player::setAnimation()
{
// Crea cadenas de texto para componer el nombre de la animación
const std::string a_walking = status_walking_ == PlayerStatus::WALKING_STOP ? "stand" : "walk";
const std::string a_firing = status_firing_ == PlayerStatus::FIRING_UP ? "centershoot" : "sideshoot";
const std::string a_walking = walking_state_ == PlayerState::WALKING_STOP ? "stand" : "walk";
const std::string a_firing = firing_state_ == PlayerState::FIRING_UP ? "centershoot" : "sideshoot";
const std::string a_cooling = firing_state_ == PlayerState::COOLING_UP ? "centershoot" : "sideshoot";
const SDL_RendererFlip flip_walk = status_walking_ == PlayerStatus::WALKING_RIGHT ? SDL_FLIP_HORIZONTAL : SDL_FLIP_NONE;
const SDL_RendererFlip flip_fire = status_firing_ == PlayerStatus::FIRING_RIGHT ? SDL_FLIP_HORIZONTAL : SDL_FLIP_NONE;
const SDL_RendererFlip flip_walk = walking_state_ == PlayerState::WALKING_RIGHT ? SDL_FLIP_HORIZONTAL : SDL_FLIP_NONE;
const SDL_RendererFlip flip_fire = firing_state_ == PlayerState::FIRING_RIGHT ? SDL_FLIP_HORIZONTAL : SDL_FLIP_NONE;
const SDL_RendererFlip flip_cooling = firing_state_ == PlayerState::COOLING_RIGHT ? SDL_FLIP_HORIZONTAL : SDL_FLIP_NONE;
// Establece la animación a partir de las cadenas
if (isPlaying())
if (isPlaying() || isEnteringNameGameCompleted() || isGameCompleted())
{
if (status_firing_ == PlayerStatus::FIRING_NONE)
if (firing_state_ == PlayerState::FIRING_NONE)
{ // No esta disparando
player_sprite_->setCurrentAnimation(a_walking);
player_sprite_->setFlip(flip_walk);
}
else if (isCooling())
{ // Acaba de disparar
player_sprite_->setCurrentAnimation(a_walking + "-" + a_cooling + "-cooldown");
player_sprite_->setFlip(flip_cooling);
}
else
{ // 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
a_firing == "centershoot" ? player_sprite_->setFlip(flip_walk) : player_sprite_->setFlip(flip_fire);
player_sprite_->setFlip(a_firing == "centershoot" ? flip_walk : flip_fire);
}
}
else
else if (isDying() || hasDied())
{
player_sprite_->setCurrentAnimation("death");
}
else if (isCelebrating())
{
player_sprite_->setCurrentAnimation("celebration");
}
// Actualiza las animaciones de los sprites
player_sprite_->update();
// powerSprite->setFlip(flip_walk);
player_sprite_->update(); // Hace avanzar las animaciones y mueve el cadaver del jugador
power_sprite_->update();
}
// Obtiene el valor de la variable
int Player::getPosX() const
{
return int(pos_x_);
}
// Obtiene el valor de la variable
int Player::getPosY() const
{
return pos_y_;
}
// Obtiene el valor de la variable
int Player::getWidth() const
{
return WIDTH_;
}
// Obtiene el valor de la variable
int Player::getHeight() const
{
return HEIGHT_;
}
// Indica si el jugador puede disparar
bool Player::canFire() const
{
// Si el contador a llegado a cero, podemos disparar. En caso contrario decrementamos el contador
return cooldown_ > 0 ? false : true;
}
// Establece el valor de la variable
void Player::setFireCooldown(int time)
{
cooldown_ = time;
}
// Actualiza el valor de la variable
void Player::updateCooldown()
{
if (cooldown_ > 0)
{
cooldown_--;
if (power_up_)
{
cooldown_--;
}
cooldown_ -= power_up_ ? 2 : 1;
}
else
{
setFiringStatus(PlayerStatus::FIRING_NONE);
if (!isCooling())
{
cooling_status_counter_ = 40;
switch (firing_state_)
{
case PlayerState::FIRING_LEFT:
firing_state_ = PlayerState::COOLING_LEFT;
break;
case PlayerState::FIRING_RIGHT:
firing_state_ = PlayerState::COOLING_RIGHT;
break;
case PlayerState::FIRING_UP:
firing_state_ = PlayerState::COOLING_UP;
break;
default:
break;
}
}
else if (cooling_status_counter_ > 0)
{
--cooling_status_counter_;
}
else
{
setFiringState(PlayerState::FIRING_NONE);
}
}
}
@@ -344,18 +322,6 @@ void Player::update()
updateScoreboard();
}
// Obtiene la puntuación del jugador
int Player::getScore() const
{
return score_;
}
// Asigna un valor a la puntuación del jugador
void Player::setScore(int score)
{
score_ = score;
}
// Incrementa la puntuación del jugador
void Player::addScore(int score)
{
@@ -365,67 +331,23 @@ void Player::addScore(int score)
}
}
// Indica si el jugador está jugando
bool Player::isPlaying() const
{
return status_playing_ == PlayerStatus::PLAYING;
}
// Indica si el jugador está continuando
bool Player::isContinue() const
{
return status_playing_ == PlayerStatus::CONTINUE;
}
// Indica si el jugador está esperando
bool Player::isWaiting() const
{
return status_playing_ == PlayerStatus::WAITING;
}
// Indica si el jugador está introduciendo su nombre
bool Player::isEnteringName() const
{
return status_playing_ == PlayerStatus::ENTERING_NAME;
}
// Indica si el jugador está muriendose
bool Player::isDying() const
{
return status_playing_ == PlayerStatus::DYING;
}
// Indica si el jugador ha terminado de morir
bool Player::hasDied() const
{
return status_playing_ == PlayerStatus::DIED;
}
// Indica si el jugador ya ha terminado de jugar
bool Player::isGameOver() const
{
return status_playing_ == PlayerStatus::GAME_OVER;
}
// Actualiza el panel del marcador
void Player::updateScoreboard()
{
switch (status_playing_)
switch (playing_state_)
{
case PlayerStatus::CONTINUE:
case PlayerState::CONTINUE:
{
Scoreboard::get()->setContinue(getScoreBoardPanel(), getContinueCounter());
break;
}
case PlayerStatus::ENTERING_NAME:
case PlayerState::ENTERING_NAME:
case PlayerState::ENTERING_NAME_GAME_COMPLETED:
{
Scoreboard::get()->setRecordName(getScoreBoardPanel(), getRecordName());
Scoreboard::get()->setSelectorPos(getScoreBoardPanel(), getRecordNamePos());
break;
}
default:
break;
}
@@ -441,21 +363,20 @@ void Player::setScoreboardMode(ScoreboardMode mode)
}
// Establece el estado del jugador en el juego
void Player::setStatusPlaying(PlayerStatus value)
void Player::setPlayingState(PlayerState state)
{
status_playing_ = value;
playing_state_ = state;
switch (status_playing_)
switch (playing_state_)
{
case PlayerStatus::PLAYING:
case PlayerState::PLAYING:
{
init();
status_playing_ = PlayerStatus::PLAYING;
playing_state_ = PlayerState::PLAYING;
setScoreboardMode(ScoreboardMode::SCORE);
break;
}
case PlayerStatus::CONTINUE:
case PlayerState::CONTINUE:
{
// Inicializa el contador de continuar
continue_ticks_ = SDL_GetTicks();
@@ -464,20 +385,17 @@ void Player::setStatusPlaying(PlayerStatus value)
setScoreboardMode(ScoreboardMode::CONTINUE);
break;
}
case PlayerStatus::WAITING:
case PlayerState::WAITING:
{
setScoreboardMode(ScoreboardMode::WAITING);
break;
}
case PlayerStatus::ENTERING_NAME:
case PlayerState::ENTERING_NAME:
{
setScoreboardMode(ScoreboardMode::ENTER_NAME);
break;
}
case PlayerStatus::DYING:
case PlayerState::DYING:
{
// Activa la animación de morir
player_sprite_->setAccelY(0.2f);
@@ -485,43 +403,39 @@ void Player::setStatusPlaying(PlayerStatus value)
rand() % 2 == 0 ? player_sprite_->setVelX(3.3f) : player_sprite_->setVelX(-3.3f);
break;
}
case PlayerStatus::DIED:
case PlayerState::DIED:
{
const auto nextPlayerStatus = IsEligibleForHighScore() ? PlayerStatus::ENTERING_NAME : PlayerStatus::CONTINUE;
demo_ ? setStatusPlaying(PlayerStatus::WAITING) : setStatusPlaying(nextPlayerStatus);
const auto nextPlayerStatus = IsEligibleForHighScore() ? PlayerState::ENTERING_NAME : PlayerState::CONTINUE;
demo_ ? setPlayingState(PlayerState::WAITING) : setPlayingState(nextPlayerStatus);
break;
}
case PlayerStatus::GAME_OVER:
case PlayerState::GAME_OVER:
{
setScoreboardMode(ScoreboardMode::GAME_OVER);
break;
}
case PlayerState::CELEBRATING:
{
setScoreboardMode(ScoreboardMode::SCORE);
break;
}
case PlayerState::ENTERING_NAME_GAME_COMPLETED:
{
setWalkingState(PlayerState::WALKING_STOP);
setFiringState(PlayerState::FIRING_NONE);
setScoreboardMode(ScoreboardMode::ENTER_NAME);
break;
}
case PlayerState::GAME_COMPLETED:
{
setScoreboardMode(ScoreboardMode::GAME_COMPLETED);
break;
}
default:
break;
}
}
// Obtiene el estado del jugador en el juego
PlayerStatus Player::getStatusPlaying() const
{
return status_playing_;
}
// Obtiene el valor de la variable
float Player::getScoreMultiplier() const
{
return score_multiplier_;
}
// Establece el valor de la variable
void Player::setScoreMultiplier(float value)
{
score_multiplier_ = value;
}
// Aumenta el valor de la variable hasta un máximo
void Player::incScoreMultiplier()
{
@@ -536,12 +450,6 @@ void Player::decScoreMultiplier()
score_multiplier_ = std::max(score_multiplier_, 1.0f);
}
// Obtiene el valor de la variable
bool Player::isInvulnerable() const
{
return invulnerable_;
}
// Establece el valor del estado
void Player::setInvulnerable(bool value)
{
@@ -549,18 +457,6 @@ void Player::setInvulnerable(bool value)
invulnerable_counter_ = invulnerable_ ? INVULNERABLE_COUNTER_ : 0;
}
// Obtiene el valor de la variable
int Player::getInvulnerableCounter() const
{
return invulnerable_counter_;
}
// Establece el valor de la variable
void Player::setInvulnerableCounter(int value)
{
invulnerable_counter_ = value;
}
// Monitoriza el estado
void Player::updateInvulnerable()
{
@@ -579,12 +475,6 @@ void Player::updateInvulnerable()
}
}
// Obtiene el valor de la variable
bool Player::isPowerUp() const
{
return power_up_;
}
// Establece el valor de la variable
void Player::setPowerUp()
{
@@ -592,18 +482,6 @@ void Player::setPowerUp()
power_up_counter_ = POWERUP_COUNTER_;
}
// Obtiene el valor de la variable
int Player::getPowerUpCounter() const
{
return power_up_counter_;
}
// Establece el valor de la variable
void Player::setPowerUpCounter(int value)
{
power_up_counter_ = value;
}
// Actualiza el valor de la variable
void Player::updatePowerUp()
{
@@ -614,12 +492,6 @@ void Player::updatePowerUp()
}
}
// Obtiene el valor de la variable
bool Player::hasExtraHit() const
{
return extra_hit_;
}
// Concede un toque extra al jugador
void Player::giveExtraHit()
{
@@ -644,18 +516,6 @@ void Player::removeExtraHit()
extra_hit_ = coffees_ == 0 ? false : true;
}
// Devuelve el número de cafes actuales
int Player::getCoffees() const
{
return coffees_;
}
// Obtiene el circulo de colisión
Circle &Player::getCollider()
{
return collider_;
}
// Actualiza el circulo de colisión a la posición del jugador
void Player::shiftColliders()
{
@@ -670,16 +530,10 @@ void Player::setPlayerTextures(const std::vector<std::shared_ptr<Texture>> &text
power_sprite_->setTexture(texture[1]);
}
// Obtiene el valor de la variable
int Player::getContinueCounter() const
{
return continue_counter_;
}
// Actualiza el contador de continue
void Player::updateContinueCounter()
{
if (status_playing_ == PlayerStatus::CONTINUE)
if (playing_state_ == PlayerState::CONTINUE)
{
constexpr int TICKS_SPEED = 1000;
if (SDL_GetTicks() - continue_ticks_ > TICKS_SPEED)
@@ -692,7 +546,7 @@ void Player::updateContinueCounter()
// Actualiza el contador de entrar nombre
void Player::updateEnterNameCounter()
{
if (status_playing_ == PlayerStatus::ENTERING_NAME)
if (playing_state_ == PlayerState::ENTERING_NAME || playing_state_ == PlayerState::ENTERING_NAME_GAME_COMPLETED)
{
constexpr int TICKS_SPEED = 1000;
if (SDL_GetTicks() - enter_name_ticks_ > TICKS_SPEED)
@@ -702,18 +556,6 @@ void Player::updateEnterNameCounter()
}
}
// Le asigna un panel en el marcador al jugador
void Player::setScoreBoardPanel(int panel)
{
scoreboard_panel_ = panel;
}
// Obtiene el valor de la variable
int Player::getScoreBoardPanel() const
{
return scoreboard_panel_;
}
// Decrementa el contador de continuar
void Player::decContinueCounter()
{
@@ -721,7 +563,7 @@ void Player::decContinueCounter()
--continue_counter_;
if (continue_counter_ < 0)
{
setStatusPlaying(PlayerStatus::GAME_OVER);
setPlayingState(PlayerState::GAME_OVER);
}
}
@@ -733,71 +575,72 @@ void Player::decEnterNameCounter()
if (enter_name_counter_ < 0)
{
enter_name_counter_ = param.game.enter_name_seconds;
setStatusPlaying(PlayerStatus::CONTINUE);
if (playing_state_ == PlayerState::ENTERING_NAME)
setPlayingState(PlayerState::CONTINUE);
else
setPlayingState(PlayerState::GAME_COMPLETED);
}
}
// Establece el nombre del jugador
void Player::setName(const std::string &name)
{
name_ = name;
}
// Establece el nombre del jugador para la tabla de mejores puntuaciones
void Player::setRecordName(const std::string &record_name)
{
record_name_ = record_name.substr(0, 8);
}
// Obtiene el nombre del jugador
std::string Player::getName() const
{
return name_;
}
// Obtiene el nombre del jugador para la tabla de mejores puntuaciones
std::string Player::getRecordName() const
{
return record_name_;
}
// Obtiene la posici´´on que se está editando del nombre del jugador para la tabla de mejores puntuaciones
// Obtiene la posición que se está editando del nombre del jugador para la tabla de mejores puntuaciones
int Player::getRecordNamePos() const
{
if (enter_name_)
{
return enter_name_->getPosition();
}
return 0;
}
// Establece el mando que usará para ser controlado
void Player::setController(int index)
// Recoloca los sprites
void Player::shiftSprite()
{
controller_index_ = index;
player_sprite_->setPosX(pos_x_);
player_sprite_->setPosY(pos_y_);
power_sprite_->setPosX(getPosX() - power_up_desp_x_);
}
// Obtiene el mando que usa para ser controlado
int Player::getController() const
{
return controller_index_;
}
// Obtiene el "id" del jugador
int Player::getId() const
{
return id_;
}
// Indica si el jugador se puede dibujar
bool Player::isRenderable() const
{
return isPlaying() || isDying();
}
// Comprueba si la puntuación entra en la tabla de mejores puntuaciones
bool Player::IsEligibleForHighScore()
{
return score_ > options.game.hi_score_table.back().score;
}
int Player::getScore() const { return score_; }
void Player::setScore(int score) { score_ = score; }
PlayerState Player::getPlayingState() const { return playing_state_; }
float Player::getScoreMultiplier() const { return score_multiplier_; }
void Player::setScoreMultiplier(float value) { score_multiplier_ = value; }
bool Player::isInvulnerable() const { return invulnerable_; }
int Player::getInvulnerableCounter() const { return invulnerable_counter_; }
void Player::setInvulnerableCounter(int value) { invulnerable_counter_ = value; }
bool Player::isPowerUp() const { return power_up_; }
int Player::getPowerUpCounter() const { return power_up_counter_; }
void Player::setPowerUpCounter(int value) { power_up_counter_ = value; }
bool Player::hasExtraHit() const { return extra_hit_; }
void Player::setScoreBoardPanel(int panel) { scoreboard_panel_ = panel; }
int Player::getScoreBoardPanel() const { return scoreboard_panel_; }
int Player::getCoffees() const { return coffees_; }
Circle &Player::getCollider() { return collider_; }
int Player::getContinueCounter() const { return continue_counter_; }
void Player::setName(const std::string &name) { name_ = name; }
void Player::setRecordName(const std::string &record_name) { record_name_ = record_name.substr(0, 8); }
std::string Player::getName() const { return name_; }
std::string Player::getRecordName() const { return record_name_; }
void Player::setController(int index) { controller_index_ = index; }
int Player::getController() const { return controller_index_; }
int Player::getId() const { return id_; }
bool Player::isRenderable() const { return isPlaying() || isDying() || isCelebrating() || isEnteringNameGameCompleted() || isGameCompleted(); }
bool Player::IsEligibleForHighScore() { return score_ > options.game.hi_score_table.back().score; }
bool Player::isCooling() { return firing_state_ == PlayerState::COOLING_LEFT || firing_state_ == PlayerState::COOLING_UP || firing_state_ == PlayerState::COOLING_RIGHT; }
int Player::getPosX() const { return static_cast<int>(pos_x_); }
int Player::getPosY() const { return pos_y_; }
int Player::getWidth() const { return WIDTH_; }
int Player::getHeight() const { return HEIGHT_; }
bool Player::canFire() const { return cooldown_ > 0 ? false : true; }
void Player::setFireCooldown(int time) { cooldown_ = time; }
void Player::setWalkingState(PlayerState state) { walking_state_ = state; }
void Player::setFiringState(PlayerState state) { firing_state_ = state; }
bool Player::isPlaying() const { return playing_state_ == PlayerState::PLAYING; }
bool Player::isContinue() const { return playing_state_ == PlayerState::CONTINUE; }
bool Player::isWaiting() const { return playing_state_ == PlayerState::WAITING; }
bool Player::isEnteringName() const { return playing_state_ == PlayerState::ENTERING_NAME; }
bool Player::isDying() const { return playing_state_ == PlayerState::DYING; }
bool Player::hasDied() const { return playing_state_ == PlayerState::DIED; }
bool Player::isGameOver() const { return playing_state_ == PlayerState::GAME_OVER; }
bool Player::isEnteringNameGameCompleted() const { return playing_state_ == PlayerState::ENTERING_NAME_GAME_COMPLETED; }
bool Player::isGameCompleted() const { return playing_state_ == PlayerState::GAME_COMPLETED; }
bool Player::isCelebrating() const { return playing_state_ == PlayerState::CELEBRATING; }

View File

@@ -1,19 +1,20 @@
#pragma once
#include "animated_sprite.h" // Para AnimatedSprite
#include "enter_name.h" // Para EnterName
#include "utils.h" // Para Circle
#include <SDL2/SDL_rect.h> // Para SDL_Rect
#include <SDL2/SDL_stdinc.h> // Para Uint32
#include <memory> // Para unique_ptr, shared_ptr
#include <string> // Para string
#include <vector> // Para vector
#include "animated_sprite.h" // Para AnimatedSprite
#include "enter_name.h" // Para EnterName
#include "utils.h" // Para Circle
class Texture; // lines 12-12
enum class InputType : int; // lines 13-13
enum class ScoreboardMode; // lines 14-14
class Texture; // lines 12-12
enum class InputType : int; // lines 13-13
enum class ScoreboardMode; // lines 14-14
// Estados del jugador
enum class PlayerStatus
enum class PlayerState
{
WALKING_LEFT,
WALKING_RIGHT,
@@ -24,16 +25,21 @@ enum class PlayerStatus
FIRING_RIGHT,
FIRING_NONE,
PLAYING,
CONTINUE,
WAITING,
ENTERING_NAME,
DYING,
DIED,
GAME_OVER,
};
COOLING_UP,
COOLING_LEFT,
COOLING_RIGHT,
// Variables del jugador
PLAYING, // Está jugando
CONTINUE, // Está con la cuenta atras para continuar
WAITING, // No está jugando pero puede entrar a jugar
ENTERING_NAME, // Introduciendo nombre
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
CELEBRATING, // Poniendo pose de victoria
ENTERING_NAME_GAME_COMPLETED, // Poniendo nombre en el tramo final del juego
GAME_COMPLETED, // Moviendose fuera de la pantalla
};
// Clase Player
class Player
@@ -52,41 +58,45 @@ private:
std::unique_ptr<EnterName> enter_name_; // Clase utilizada para introducir el nombre
// Variables
int id_; // Numero de identificación para el jugador. Player1 = 1, Player2 = 2
SDL_Rect play_area_; // Rectangulo con la zona de juego
float pos_x_ = 0.0f; // Posicion en el eje X
int pos_y_ = 0; // Posicion en el eje Y
float default_pos_x_; // Posición inicial para el jugador
int default_pos_y_; // Posición inicial para el jugador
float vel_x_ = 0.0f; // Cantidad de pixeles a desplazarse en el eje X
int vel_y_ = 0.0f; // Cantidad de pixeles a desplazarse en el eje Y
int cooldown_ = 10; // Contador durante el cual no puede disparar
int score_ = 0; // Puntos del jugador
float score_multiplier_ = 1.0f; // Multiplicador de puntos
PlayerStatus status_walking_ = PlayerStatus::WALKING_STOP; // Estado del jugador al moverse
PlayerStatus status_firing_ = PlayerStatus::FIRING_NONE; // Estado del jugador al disparar
PlayerStatus status_playing_ = PlayerStatus::WAITING; // Estado del jugador en el juego
bool invulnerable_ = true; // Indica si el jugador es invulnerable
int invulnerable_counter_ = INVULNERABLE_COUNTER_; // Contador para la invulnerabilidad
bool extra_hit_ = false; // Indica si el jugador tiene un toque extra
int coffees_ = 0; // Indica cuantos cafes lleva acumulados
bool power_up_ = false; // Indica si el jugador tiene activo el modo PowerUp
int power_up_counter_ = POWERUP_COUNTER_; // Temporizador para el modo PowerUp
int power_up_desp_x_ = 0; // Desplazamiento del sprite de PowerUp respecto al sprite del jugador
Circle collider_ = Circle(0, 0, 9); // Circulo de colisión del jugador
int continue_counter_ = 10; // Contador para poder continuar
Uint32 continue_ticks_ = 0; // Variable para poder cambiar el contador de continue en función del tiempo
int scoreboard_panel_ = 0; // Panel del marcador asociado al jugador
std::string name_; // Nombre del jugador
std::string record_name_; // Nombre del jugador para la tabla de mejores puntuaciones
int controller_index_ = 0; // Indice del array de mandos que utilizará para moverse
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
int id_; // Numero de identificación para el jugador. Player1 = 1, Player2 = 2
SDL_Rect play_area_; // Rectangulo con la zona de juego
float pos_x_ = 0.0f; // Posicion en el eje X
int pos_y_ = 0; // Posicion en el eje Y
float default_pos_x_; // Posición inicial para el jugador
int default_pos_y_; // Posición inicial para el jugador
float vel_x_ = 0.0f; // Cantidad de pixeles a desplazarse en el eje X
int vel_y_ = 0.0f; // Cantidad de pixeles a desplazarse en el eje Y
int cooldown_ = 0; // Contador durante el cual no puede disparar
int cooling_status_counter_ = 0; // Contador para la animación del estado cooling
int score_ = 0; // Puntos del jugador
float score_multiplier_ = 1.0f; // Multiplicador de puntos
PlayerState walking_state_ = PlayerState::WALKING_STOP; // Estado del jugador al moverse
PlayerState firing_state_ = PlayerState::FIRING_NONE; // Estado del jugador al disparar
PlayerState playing_state_ = PlayerState::WAITING; // Estado del jugador en el juego
bool invulnerable_ = true; // Indica si el jugador es invulnerable
int invulnerable_counter_ = INVULNERABLE_COUNTER_; // Contador para la invulnerabilidad
bool extra_hit_ = false; // Indica si el jugador tiene un toque extra
int coffees_ = 0; // Indica cuantos cafes lleva acumulados
bool power_up_ = false; // Indica si el jugador tiene activo el modo PowerUp
int power_up_counter_ = POWERUP_COUNTER_; // Temporizador para el modo PowerUp
int power_up_desp_x_ = 0; // Desplazamiento del sprite de PowerUp respecto al sprite del jugador
Circle collider_ = Circle(0, 0, 9); // Circulo de colisión del jugador
int continue_counter_ = 10; // Contador para poder continuar
Uint32 continue_ticks_ = 0; // Variable para poder cambiar el contador de continue en función del tiempo
int scoreboard_panel_ = 0; // Panel del marcador asociado al jugador
std::string name_; // Nombre del jugador
std::string record_name_; // Nombre del jugador para la tabla de mejores puntuaciones
int controller_index_ = 0; // Indice del array de mandos que utilizará para moverse
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
// Actualiza el circulo de colisión a la posición del jugador
void shiftColliders();
// Recoloca el sprite
void shiftSprite();
// Monitoriza el estado
void updateInvulnerable();
@@ -105,12 +115,12 @@ private:
// Actualiza el panel del marcador
void updateScoreboard();
// Comprueba si la puntuación entra en la tabla de mejores puntuaciones
bool IsEligibleForHighScore();
// Cambia el modo del marcador
void setScoreboardMode(ScoreboardMode mode);
// Se encuentra en alguno de los estados "COOLING"
bool isCooling();
public:
// Constructor
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);
@@ -143,10 +153,10 @@ public:
void move();
// Establece el estado del jugador
void setWalkingStatus(PlayerStatus status);
void setWalkingState(PlayerState state);
// Establece el estado del jugador
void setFiringStatus(PlayerStatus status);
void setFiringState(PlayerState state);
// Establece la animación correspondiente al estado
void setAnimation();
@@ -181,32 +191,23 @@ public:
// Incrementa la puntuación del jugador
void addScore(int score);
// Indica si el jugador está jugando
// Indica si el jugador se encuentra en ese estado
bool isPlaying() const;
// Indica si el jugador está continuando
bool isContinue() const;
// Indica si el jugador está esperando
bool isWaiting() const;
// Indica si el jugador está introduciendo su nombre
bool isEnteringName() const;
// Indica si el jugador está muriendose
bool isDying() const;
// Indica si el jugador ha terminado de morir
bool hasDied() const;
// Indica si el jugador ya ha terminado de jugar
bool isGameOver() const;
bool isEnteringNameGameCompleted() const;
bool isGameCompleted() const;
bool isCelebrating() const;
// Establece el estado del jugador en el juego
void setStatusPlaying(PlayerStatus value);
void setPlayingState(PlayerState state);
// Obtiene el estado del jugador en el juego
PlayerStatus getStatusPlaying() const;
PlayerState getPlayingState() const;
// Obtiene el valor de la variable
float getScoreMultiplier() const;
@@ -286,7 +287,7 @@ public:
// Obtiene el nombre del jugador para la tabla de mejores puntuaciones
std::string getRecordName() const;
// Obtiene la posici´´on que se está editando del nombre del jugador para la tabla de mejores puntuaciones
// Obtiene la posición que se está editando del nombre del jugador para la tabla de mejores puntuaciones
int getRecordNamePos() const;
// Establece el mando que usará para ser controlado
@@ -297,4 +298,7 @@ public:
// Obtiene el "id" del jugador
int getId() const;
// Comprueba si la puntuación entra en la tabla de mejores puntuaciones
bool IsEligibleForHighScore();
};

View File

@@ -3,8 +3,10 @@
#include <iostream> // Para basic_ostream, operator<<, endl, cout, cerr
#include <stdexcept> // Para runtime_error
#include "asset.h" // Para Asset, AssetType
#include "lang.h" // Para lang
#include "jail_audio.h" // Para JA_LoadMusic, JA_LoadSound
#include "screen.h" // Para Screen
#include "text.h" // Para Text
struct JA_Music_t;
struct JA_Sound_t;
@@ -40,19 +42,10 @@ Resource::Resource()
loadAnimations();
loadDemoData();
addPalettes();
createTextures();
std::cout << "\n** RESOURCES LOADED" << std::endl;
}
// Destructor
Resource::~Resource()
{
sounds_.clear();
musics_.clear();
textures_.clear();
text_files_.clear();
animations_.clear();
}
// Obtiene el sonido a partir de un nombre
JA_Sound_t *Resource::getSound(const std::string &name)
{
@@ -230,4 +223,50 @@ void Resource::addPalettes()
// Fuentes
getTexture("smb2.gif")->addPaletteFromFile(Asset::get()->get("smb2_palette1.pal"));
}
}
// Crea texturas
void Resource::createTextures()
{
struct NameAndText
{
std::string name;
std::string text;
// Constructor
NameAndText(const std::string &name_init, const std::string &text_init)
: name(name_init), text(text_init) {}
};
std::cout << "\n>> CREATING TEXTURES" << std::endl;
auto text = std::make_unique<Text>(getTexture("04b_25.png"), getTextFile("04b_25.txt"));
// Tamaño normal
std::vector<NameAndText> strings = {
NameAndText("game_text_1000_points", "1.000"),
NameAndText("game_text_2500_points", "2.500"),
NameAndText("game_text_5000_points", "5.000"),
NameAndText("game_text_powerup", lang::getText(117)),
NameAndText("game_text_one_hit", lang::getText(118)),
NameAndText("game_text_stop", lang::getText(119)),
NameAndText("1000000_points", lang::getText(76))};
for (const auto &s : strings)
{
textures_.emplace_back(ResourceTexture(s.name, text->writeToTexture(s.text, 1, -2)));
printWithDots("Texture : ", s.name, "[ DONE ]");
}
// Tamaño doble
std::vector<NameAndText> strings2X = {
NameAndText("get_ready", lang::getText(75)),
NameAndText("last_stage", lang::getText(79)),
NameAndText("congratulations", lang::getText(50)),
NameAndText("game_over", "Game Over")};
for (const auto &s : strings2X)
{
textures_.emplace_back(ResourceTexture(s.name, text->writeToTexture(s.text, 2, -2)));
printWithDots("Texture : ", s.name, "[ DONE ]");
}
}

View File

@@ -99,13 +99,16 @@ private:
// Añade paletas a las texturas
void addPalettes();
// Crea texturas
void createTextures();
// [SINGLETON] Ahora el constructor y el destructor son privados, para no poder crear objetos resource desde fuera
// Constructor
Resource();
// Destructor
~Resource();
~Resource() = default;
public:
// [SINGLETON] Crearemos el objeto resource con esta función estática

View File

@@ -118,77 +118,28 @@ void Scoreboard::render()
SDL_RenderCopy(renderer_, background_, nullptr, &rect_);
}
// Establece el valor de la variable
void Scoreboard::setName(int panel_, const std::string &name_)
{
this->name_[panel_] = name_;
}
void Scoreboard::setName(int panel, const std::string &name) { name_[panel] = name; }
void Scoreboard::setRecordName(int panel, const std::string &record_name) { record_name_[panel] = record_name; }
void Scoreboard::setSelectorPos(int panel, int pos) { selector_pos_[panel] = pos; }
void Scoreboard::setScore(int panel, int score) { score_[panel] = score; }
void Scoreboard::setMult(int panel, float mult) { mult_[panel] = mult; }
void Scoreboard::setContinue(int panel, int continue_counter) { continue_counter_[panel] = continue_counter; }
void Scoreboard::setStage(int stage) { stage_ = stage; }
void Scoreboard::setHiScore(int hi_score) { hi_score_ = hi_score; }
void Scoreboard::setPower(float power) { power_ = power; }
void Scoreboard::setHiScoreName(const std::string &name) { hi_score_name_ = name; }
// Establece el valor de la variable
void Scoreboard::setRecordName(int panel_, const std::string &record_name_)
void Scoreboard::setColor(Color color)
{
this->record_name_[panel_] = record_name_;
}
// Establece el valor de la variable
void Scoreboard::setSelectorPos(int panel_, int pos)
{
selector_pos_[panel_] = pos;
}
// Establece el valor de la variable
void Scoreboard::setScore(int panel_, int score_)
{
this->score_[panel_] = score_;
}
// Establece el valor de la variable
void Scoreboard::setMult(int panel_, float mult_)
{
this->mult_[panel_] = mult_;
}
// Establece el valor de la variable
void Scoreboard::setContinue(int panel_, int value)
{
continue_counter_[panel_] = value;
}
// Establece el valor de la variable
void Scoreboard::setStage(int stage_)
{
this->stage_ = stage_;
}
// Establece el valor de la variable
void Scoreboard::setHiScore(int hi_score_)
{
this->hi_score_ = hi_score_;
}
// Establece el valor de la variable
void Scoreboard::setPower(float power_)
{
this->power_ = power_;
}
// Establece el valor de la variable
void Scoreboard::setHiScoreName(const std::string &name_)
{
hi_score_name_ = name_;
}
// Establece el valor de la variable
void Scoreboard::setColor(Color color_)
{
this->color_ = color_;
color_ = color;
fillBackgroundTexture();
}
// Establece el valor de la variable
void Scoreboard::setPos(SDL_Rect rect_)
void Scoreboard::setPos(SDL_Rect rect)
{
this->rect_ = rect_;
rect_ = rect;
// Recalcula las anclas de los elementos
recalculateAnchors();
@@ -207,10 +158,10 @@ void Scoreboard::setPos(SDL_Rect rect_)
void Scoreboard::fillPanelTextures()
{
// Guarda a donde apunta actualmente el renderizador
SDL_Texture *temp = SDL_GetRenderTarget(renderer_);
auto temp = SDL_GetRenderTarget(renderer_);
// Genera el contenidoi de cada panel_
for (int i = 0; i < SCOREBOARD_MAX_PANELS; ++i)
for (size_t i = 0; i < SCOREBOARD_MAX_PANELS; ++i)
{
// Cambia el destino del renderizador
SDL_SetRenderTarget(renderer_, panel_texture_[i]);
@@ -314,8 +265,9 @@ void Scoreboard::fillPanelTextures()
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 (int j = 0; j < (int)record_name_[i].size(); ++j)
for (size_t j = 0; j < record_name_[i].size(); ++j)
{
/*
if (j == selector_pos_[i])
{ // La letra seleccionada se pinta de forma intermitente
if (counter_ % 3 > 0)
@@ -329,11 +281,28 @@ void Scoreboard::fillPanelTextures()
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));
}
*/
if (j != selector_pos_[i] || counter_ % 3 == 0)
{
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));
}
rect.x += 7;
}
break;
}
case ScoreboardMode::GAME_COMPLETED:
{
// GAME OVER
text_scoreboard_->writeCentered(slot4_1_.x, slot4_1_.y + 4, lang::getText(102));
// SCORE
if (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]));
}
}
default:
break;
}
@@ -416,10 +385,7 @@ void Scoreboard::recalculateAnchors()
}
// Establece el modo del marcador
void Scoreboard::setMode(int index, ScoreboardMode mode)
{
panel_[index].mode = mode;
}
void Scoreboard::setMode(int index, ScoreboardMode mode) { panel_[index].mode = mode; }
// Crea la textura de fondo
void Scoreboard::createBackgroundTexture()

View File

@@ -28,6 +28,7 @@ enum class ScoreboardMode : int
GAME_OVER,
DEMO,
ENTER_NAME,
GAME_COMPLETED,
NUM_MODES,
};
@@ -58,7 +59,7 @@ private:
// Variables
std::string name_[SCOREBOARD_MAX_PANELS] = {}; // Nom de cada jugador
std::string record_name_[SCOREBOARD_MAX_PANELS] = {}; // Nombre introducido para la tabla de records
int selector_pos_[SCOREBOARD_MAX_PANELS] = {}; // Posición del selector de letra para introducir el nombre
size_t selector_pos_[SCOREBOARD_MAX_PANELS] = {}; // Posición del selector de letra para introducir el nombre
int score_[SCOREBOARD_MAX_PANELS] = {}; // Puntuación de los jugadores
float mult_[SCOREBOARD_MAX_PANELS] = {}; // Multiplicador de los jugadores
int continue_counter_[SCOREBOARD_MAX_PANELS] = {}; // Tiempo para continuar de los jugadores

View File

@@ -141,7 +141,7 @@ void Screen::blit()
// Copia la textura de juego en el renderizador en la posición adecuada
if (shake_effect_.enabled)
SDL_RenderCopy(renderer_, game_canvas_, nullptr, nullptr);
SDL_RenderCopy(renderer_, game_canvas_, nullptr, nullptr); // Esta copia es para evitar que se vea negro por los laterales
SDL_RenderCopy(renderer_, game_canvas_, &src_rect_, &dst_rect_);
// Muestra por pantalla el renderizador
@@ -311,14 +311,16 @@ void Screen::checkInput()
for (int i = 0; i < Input::get()->getNumControllers(); ++i)
{
// Comprueba los mandos para activar o desactivar los shaders
if (Input::get()->checkModInput(InputType::SERVICE, InputType::VIDEO_SHADERS, INPUT_DO_NOT_ALLOW_REPEAT, INPUT_USE_GAMECONTROLLER, i))
if (Input::get()->checkInput(InputType::SERVICE, INPUT_ALLOW_REPEAT, INPUT_USE_GAMECONTROLLER, i) &&
Input::get()->checkInput(InputType::VIDEO_SHADERS, INPUT_DO_NOT_ALLOW_REPEAT, INPUT_USE_GAMECONTROLLER, i))
{
switchShaders();
return;
}
// Comprueba los mandos para mostrar la información de debug
if (Input::get()->checkModInput(InputType::SERVICE, InputType::SHOWINFO, INPUT_DO_NOT_ALLOW_REPEAT, INPUT_USE_GAMECONTROLLER, i))
if (Input::get()->checkInput(InputType::SERVICE, INPUT_ALLOW_REPEAT, INPUT_USE_GAMECONTROLLER, i) &&
Input::get()->checkInput(InputType::SHOWINFO, INPUT_DO_NOT_ALLOW_REPEAT, INPUT_USE_GAMECONTROLLER, i))
{
show_info_ = !show_info_;
return;
@@ -375,10 +377,7 @@ void Screen::updateShakeEffect()
// Pone la pantalla de color
void Screen::flash(Color color, int lenght)
{
flash_effect_.enabled = true;
flash_effect_.counter = 0;
flash_effect_.lenght = lenght;
flash_effect_.color = color;
flash_effect_ = FlashEffect(true, lenght, color);
}
// Actualiza y dibuja el efecto de flash en la pantalla
@@ -387,14 +386,11 @@ void Screen::doFlash()
if (flash_effect_.enabled)
{
// Dibuja el color del flash en la textura
SDL_Texture *temp = SDL_GetRenderTarget(renderer_);
SDL_SetRenderTarget(renderer_, game_canvas_);
SDL_SetRenderDrawColor(renderer_, flash_effect_.color.r, flash_effect_.color.g, flash_effect_.color.b, 0xFF);
SDL_RenderClear(renderer_);
SDL_SetRenderTarget(renderer_, temp);
// Actualiza la lógica del efecto
flash_effect_.counter < flash_effect_.lenght ? flash_effect_.counter++ : flash_effect_.enabled = false;
flash_effect_.counter > 0 ? flash_effect_.counter-- : flash_effect_.enabled = false;
}
}
@@ -403,11 +399,8 @@ void Screen::doAttenuate()
{
if (attenuate_effect_)
{
SDL_Texture *temp = SDL_GetRenderTarget(renderer_);
SDL_SetRenderTarget(renderer_, game_canvas_);
SDL_SetRenderDrawColor(renderer_, 0, 0, 0, 64);
SDL_RenderFillRect(renderer_, nullptr);
SDL_SetRenderTarget(renderer_, temp);
}
}

View File

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

View File

@@ -4,4 +4,5 @@ namespace section
{
Name name;
Options options;
AttractMode attract_mode;
}

View File

@@ -29,6 +29,14 @@ namespace section
NONE = 7,
};
// Variables para el Attract Mode
enum class AttractMode
{
TITLE_TO_DEMO,
TITLE_TO_LOGO,
};
extern Name name;
extern Options options;
extern AttractMode attract_mode;
}

View File

@@ -1,11 +1,16 @@
#include "text.h"
#include <SDL2/SDL_rect.h> // Para SDL_Rect
#include <fstream> // Para basic_ifstream, basic_istream, basic_ostream
#include <iostream> // Para cerr
#include <stdexcept> // Para runtime_error
#include "sprite.h" // Para Sprite
#include "texture.h" // Para Texture
#include "utils.h" // Para Color, getFileName, printWithDots
#include <SDL2/SDL_blendmode.h> // for SDL_BLENDMODE_BLEND
#include <SDL2/SDL_pixels.h> // for SDL_PIXELFORMAT_RGBA8888
#include <SDL2/SDL_rect.h> // for SDL_Rect
#include <SDL2/SDL_render.h> // for SDL_TEXTUREACCESS_TARGET
#include <stddef.h> // for size_t
#include <fstream> // for basic_ifstream, basic_istream, basic...
#include <iostream> // for cerr
#include <stdexcept> // for runtime_error
#include "screen.h" // for Screen
#include "sprite.h" // for Sprite
#include "texture.h" // for Texture
#include "utils.h" // for Color, getFileName, printWithDots
// Llena una estructuta TextFile desde un fichero
std::shared_ptr<TextFile> loadTextFile(const std::string &file_path)
@@ -45,9 +50,7 @@ std::shared_ptr<TextFile> loadTextFile(const std::string &file_path)
{
// Almacena solo las lineas impares
if (line_read % 2 == 1)
{
tf->offset[index++].w = std::stoi(buffer);
}
// Limpia el buffer
buffer.clear();
@@ -122,26 +125,50 @@ Text::Text(std::shared_ptr<Texture> texture, std::shared_ptr<TextFile> text_file
// Escribe texto en pantalla
void Text::write(int x, int y, const std::string &text, int kerning, int lenght)
{
auto shift = 0;
int shift = 0;
if (lenght == -1)
{
lenght = text.length();
}
sprite_->setY(y);
const auto width = sprite_->getWidth();
const auto height = sprite_->getHeight();
for (int i = 0; i < lenght; ++i)
{
const auto index = static_cast<int>(text[i]);
sprite_->setSpriteClip(offset_[index].x, offset_[index].y, width, height);
auto index = static_cast<int>(text[i]);
sprite_->setSpriteClip(offset_[index].x, offset_[index].y, box_width_, box_height_);
sprite_->setX(x + shift);
sprite_->render();
shift += fixed_width_ ? box_width_ : (offset_[int(text[i])].w + kerning);
shift += offset_[static_cast<int>(text[i])].w + kerning;
}
}
// Escribe texto en pantalla
void Text::write2X(int x, int y, const std::string &text, int kerning)
{
int shift = 0;
for (size_t i = 0; i < text.length(); ++i)
{
auto index = static_cast<size_t>(text[i]);
SDL_Rect rect = {offset_[index].x, offset_[index].y, box_width_, box_height_};
sprite_->getTexture()->render(x + shift, y, &rect, 2.0f, 2.0f);
shift += (offset_[index].w + kerning) * 2;
}
}
// Escribe el texto en una textura
std::shared_ptr<Texture> Text::writeToTexture(const std::string &text, int zoom, int kerning)
{
auto renderer = Screen::get()->getRenderer();
auto texture = std::make_shared<Texture>(renderer);
auto width = lenght(text, kerning) * zoom;
auto height = box_height_ * zoom;
texture->createBlank(width, height, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET);
texture->setBlendMode(SDL_BLENDMODE_BLEND);
texture->setAsRenderTarget(renderer);
zoom == 1 ? write(0, 0, text, kerning) : write2X(0, 0, text, kerning);
return texture;
}
// Escribe el texto con colores
void Text::writeColored(int x, int y, const std::string &text, Color color, int kerning, int lenght)
{
@@ -211,12 +238,9 @@ void Text::writeDX(Uint8 flags, int x, int y, const std::string &text, int kerni
// Obtiene la longitud en pixels de una cadena
int Text::lenght(const std::string &text, int kerning) const
{
auto shift = 0;
for (int i = 0; i < (int)text.length(); ++i)
{
shift += (offset_[int(text[i])].w + kerning);
}
int shift = 0;
for (size_t i = 0; i < text.length(); ++i)
shift += (offset_[static_cast<int>(text[i])].w + kerning);
// Descuenta el kerning del último caracter
return shift - kerning;

View File

@@ -50,6 +50,10 @@ public:
// Escribe el texto en pantalla
void write(int x, int y, const std::string &text, int kerning = 1, int lenght = -1);
void write2X(int x, int y, const std::string &text, int kerning = 1);
// 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 colores
void writeColored(int x, int y, const std::string &text, Color color, int kerning = 1, int lenght = -1);

View File

@@ -60,6 +60,9 @@ Texture::~Texture()
// Carga una imagen desde un fichero
bool Texture::loadFromFile(const std::string &file_path)
{
if (file_path.empty())
return false;
int req_format = STBI_rgb_alpha;
int width, height, orig_format;
unsigned char *data = stbi_load(file_path.c_str(), &width, &height, &orig_format, req_format);

View File

@@ -46,6 +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;
}
// Destructor
@@ -172,7 +175,6 @@ void Title::checkEvents()
if (!define_buttons_->isEnabled())
{
SDL_Event event;
// Comprueba los eventos que hay en la cola
while (SDL_PollEvent(&event))
{
// Evento de salida de la aplicación
@@ -213,6 +215,12 @@ void Title::checkEvents()
break;
}
case SDLK_4:
{
showControllers();
break;
}
default:
break;
}
@@ -241,14 +249,16 @@ void Title::checkInput()
for (int i = 0; i < Input::get()->getNumControllers(); ++i)
{
// Comprueba si se va a intercambiar la asignación de mandos a jugadores
if (Input::get()->checkModInput(InputType::SERVICE, InputType::SWAP_CONTROLLERS, INPUT_DO_NOT_ALLOW_REPEAT, INPUT_USE_GAMECONTROLLER, i))
if (Input::get()->checkInput(InputType::SERVICE, INPUT_ALLOW_REPEAT, INPUT_USE_GAMECONTROLLER, i) &&
Input::get()->checkInput(InputType::SWAP_CONTROLLERS, INPUT_DO_NOT_ALLOW_REPEAT, INPUT_USE_GAMECONTROLLER, i))
{
swapControllers();
return;
}
// Comprueba si algun mando quiere ser configurado
if (Input::get()->checkModInput(InputType::SERVICE, InputType::CONFIG, INPUT_DO_NOT_ALLOW_REPEAT, INPUT_USE_GAMECONTROLLER, i))
if (Input::get()->checkInput(InputType::SERVICE, INPUT_ALLOW_REPEAT, INPUT_USE_GAMECONTROLLER, i) &&
Input::get()->checkInput(InputType::CONFIG, INPUT_DO_NOT_ALLOW_REPEAT, INPUT_USE_GAMECONTROLLER, i))
{
define_buttons_->enable(i);
return;
@@ -273,7 +283,7 @@ void Title::checkInput()
// Comprueba el input para el resto de objetos
Screen::get()->checkInput();
define_buttons_->checkInput();
define_buttons_->checkEvents();
// Comprueba los inputs que se pueden introducir en cualquier sección del juego
globalInputs::check();
@@ -299,23 +309,21 @@ void Title::reLoadTextures()
}
// Reinicia el contador interno
void Title::resetCounter()
{
counter_ = 0;
}
void Title::resetCounter() { counter_ = 0; }
// Intercambia la asignación de mandos a los jugadores
void Title::swapControllers()
{
const auto num_controllers = Input::get()->getNumControllers();
if (num_controllers == 0)
{
if (Input::get()->getNumControllers() == 0)
return;
}
define_buttons_->swapControllers();
showControllers();
}
// Muestra información sobre los controles y los jugadores
void Title::showControllers()
{
// Crea cadenas de texto vacias para un numero máximo de mandos
constexpr int MAX_CONTROLLERS = 2;
std::string text[MAX_CONTROLLERS];
@@ -338,11 +346,10 @@ void Title::swapControllers()
const int index = playerControllerIndex[i];
if (options.controller[index].plugged)
{
text[i] = lang::getText(101) + std::to_string(i + 1) + ": " + options.controller[index].name;
text[i] = lang::getText(100) + std::to_string(i + 1) + ": " + options.controller[index].name;
}
}
Notifier::get()->showText(text[0], text[1]);
resetCounter();
}

View File

@@ -47,11 +47,11 @@ private:
std::unique_ptr<DefineButtons> define_buttons_; // Objeto para definir los botones del joystic
// Variable
int counter_ = 0; // Temporizador para la pantalla de titulo
Uint32 ticks_ = 0; // Contador de ticks para ajustar la velocidad del programa
section::Name next_section_ = section::Name::GAME_DEMO; // Indica cual es la siguiente sección a cargar cuando termine el contador del titulo
int post_fade_ = 0; // Opción a realizar cuando termina el fundido
int num_controllers_; // Número de mandos conectados
int counter_ = 0; // Temporizador para la pantalla de titulo
Uint32 ticks_ = 0; // Contador de ticks para ajustar la velocidad del programa
section::Name next_section_; // Indica cual es la siguiente sección a cargar cuando termine el contador del titulo
int post_fade_ = 0; // Opción a realizar cuando termina el fundido
int num_controllers_; // Número de mandos conectados
// Actualiza las variables del objeto
void update();
@@ -74,6 +74,9 @@ private:
// Intercambia la asignación de mandos a los jugadores
void swapControllers();
// Muestra información sobre los controles y los jugadores
void showControllers();
public:
// Constructor
Title();