Compare commits

13 Commits

Author SHA1 Message Date
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
50 changed files with 1249 additions and 1582 deletions

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 # box width
10 14
# box height # box height
10 14
# 32 espacio ( ) # 32 espacio ( )
5 8
# 33 ! # 33 !
4 5
# 34 " # 34 "
5 8
# 35 # # 35
7 10
# 36 $ # 36 $
7 10
# 37 % # 37 %
8 9
# 38 & # 38 &
8 11
# 39 ' # 39 '
3 5
# 40 ( # 40 (
5 7
# 41 ) # 41 )
5 7
# 42 * # 42 *
7 7
# 43 + # 43 +
7 9
# 44 , # 44 ,
4 5
# 45 - # 45 -
6 9
# 46 . # 46 .
4 5
# 47 / # 47 /
5 12
# 48 0 # 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 8
# 65 A # 49 1
7
# 66 B
7
# 67 C
7
# 68 D
7
# 69 E
7
# 70 F
7
# 71 G
7
# 72 H
7
# 73 I
4
# 74 J
6 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 # 75 K
8 8
# 76 L # 76 L
6 8
# 77 M # 77 M
9 11
# 78 N # 78 N
8 8
# 79 O # 79 O
8 8
# 80 P # 80 P
7 8
# 81 Q # 81 Q
8 8
# 82 R # 82 R
7
# 83 S
6
# 84 T
8 8
# 83 S
8
# 84 T
9
# 85 U # 85 U
7 8
# 86 V # 86 V
8 8
# 87 W # 87 W
9 11
# 88 X # 88 X
8 8
# 89 Y # 89 Y
8 8
# 90 Z # 90 Z
7
# 91 [
4
# 92 \
5
# 93 ]
4
# 94 ^
5
# 95 _
8 8
# 91 [
7
# 92 \
11
# 93 ]
7
# 94 ^
6
# 95 _
7
# 96 ` # 96 `
4 6
# 97 a # 97 a
7 8
# 98 b # 98 b
7 8
# 99 c # 99 c
6 8
# 100 d # 100 d
7 8
# 101 e # 101 e
7 8
# 102 f # 102 f
5 8
# 103 g # 103 g
7 8
# 104 h # 104 h
7 8
# 105 i # 105 i
4 5
# 106 j # 106 j
5 8
# 107 k # 107 k
7 8
# 108 l # 108 l
4 8
# 109 m # 109 m
10 11
# 110 n # 110 n
7 8
# 111 o # 111 o
7 8
# 112 p # 112 p
7 8
# 113 q # 113 q
7 8
# 114 r # 114 r
6 8
# 115 s # 115 s
6 8
# 116 t # 116 t
5
# 117 u
7
# 118 v
7
# 119 w
9 9
# 117 u
8
# 118 v
8
# 119 w
11
# 120 x # 120 x
7 8
# 121 y # 121 y
7 8
# 122 z # 122 z
7 8
# 123 { -> ñ # 123 {
7 1
# 124 | -> ç # 124 |
7 1
# 125 } # 125 }
0 1
# 126 ~ # 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]
[animation] [animation]
name=stand-sideshoot name=walk-sideshoot-cooldown
speed=5 speed=5
loop=0 loop=0
frames=12,13,14,15 frames=12,13,14,15
[/animation] [/animation]
[animation] [animation]
name=walk-centershoot name=stand-sideshoot
speed=5 speed=5
loop=0 loop=0
frames=16,17,18,19 frames=16,17,18,19
[/animation] [/animation]
[animation] [animation]
name=stand-centershoot name=stand-sideshoot-cooldown
speed=5
loop=0
frames=15
[/animation]
[animation]
name=walk-centershoot
speed=5 speed=5
loop=0 loop=0
frames=20,21,22,23 frames=20,21,22,23
[/animation] [/animation]
[animation] [animation]
name=death name=walk-centershoot-cooldown
speed=15 speed=5
loop=0 loop=0
frames=24,25,26,27 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=celeb
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] [/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,13 @@ Per favor
espere espere
## 116 - NOTIFICACIONES ## 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!

View File

@@ -347,4 +347,13 @@ Please
wait wait
## 116 - NOTIFICACIONES ## 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!

View File

@@ -347,4 +347,13 @@ Por favor
espere espere
## 94 - NOTIFICACIONES ## 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!

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; vy_ = 0;
max_vy_ = 3.0f; max_vy_ = 3.0f;
const int size = static_cast<int>(size_); const int index = static_cast<int>(size_);
gravity_ = param.balloon.at(size).grav; gravity_ = param.balloon.at(index).grav;
default_vy_ = param.balloon.at(size).vel; default_vy_ = param.balloon.at(index).vel;
h_ = w_ = BALLOON_SIZE[size]; h_ = w_ = BALLOON_SIZE[index];
power_ = BALLOON_POWER[size]; power_ = BALLOON_POWER[index];
menace_ = BALLOON_MENACE[size]; menace_ = BALLOON_MENACE[index];
score_ = BALLOON_SCORE[size]; score_ = BALLOON_SCORE[index];
break; break;
} }
@@ -44,25 +44,25 @@ Balloon::Balloon(float x, float y, BalloonType type, BalloonSize size, float vel
default_vy_ = max_vy_ = vy_ = fabs(vx_ * 2.0f); default_vy_ = max_vy_ = vy_ = fabs(vx_ * 2.0f);
gravity_ = 0.00f; gravity_ = 0.00f;
const int size = static_cast<int>(size_); const int index = static_cast<int>(size_);
h_ = w_ = BALLOON_SIZE[size]; h_ = w_ = BALLOON_SIZE[index];
power_ = BALLOON_POWER[size]; power_ = BALLOON_POWER[index];
menace_ = BALLOON_MENACE[size]; menace_ = BALLOON_MENACE[index];
score_ = BALLOON_SCORE[size]; score_ = BALLOON_SCORE[index];
break; break;
} }
case BalloonType::POWERBALL: case BalloonType::POWERBALL:
{ {
const int size = 3; const int index = 3;
h_ = w_ = BALLOON_SIZE[size]; h_ = w_ = BALLOON_SIZE[index];
power_ = score_ = menace_ = 0; power_ = score_ = menace_ = 0;
vy_ = 0; vy_ = 0;
max_vy_ = 3.0f; max_vy_ = 3.0f;
gravity_ = param.balloon.at(size).grav; gravity_ = param.balloon.at(index).grav;
default_vy_ = param.balloon.at(size).vel; default_vy_ = param.balloon.at(index).vel;
sprite_->disableRotate(); sprite_->disableRotate();
sprite_->setRotateSpeed(0); sprite_->setRotateSpeed(0);
@@ -200,17 +200,11 @@ void Balloon::move()
} }
} }
// Deshabilita el globo y pone a cero todos los valores // Deshabilita el globo
void Balloon::disable() void Balloon::disable() { enabled_ = false; }
{
enabled_ = false;
}
// Explosiona el globo // Explosiona el globo
void Balloon::pop() void Balloon::pop() { disable(); }
{
disable();
}
// Actualiza al globo a su posicion, animación y controla los contadores // Actualiza al globo a su posicion, animación y controla los contadores
void Balloon::update() void Balloon::update()
@@ -296,60 +290,6 @@ void Balloon::setAnimation()
sprite_->setCurrentAnimation(isBeingCreated() ? creating_animation : normal_animation); 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 // Detiene el globo
void Balloon::stop() void Balloon::stop()
{ {
@@ -366,42 +306,6 @@ void Balloon::start()
sprite_->enableRotate(); 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 // Alinea el circulo de colisión con la posición del objeto globo
void Balloon::shiftColliders() void Balloon::shiftColliders()
{ {
@@ -423,18 +327,6 @@ void Balloon::zoomSprite()
sprite_->setZoomH(bouncing_.zoomH); 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 // Activa el efecto
void Balloon::enableBounce() 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 // Pone el color alternativo en el globo
void Balloon::useReverseColor() void Balloon::useReverseColor()
{ {
@@ -500,8 +380,25 @@ void Balloon::useNormalColor()
setAnimation(); setAnimation();
} }
// Indica si está usando el color alternativo // Getters
bool Balloon::isUsingReversedColor() float Balloon::getPosX() const { return x_; }
{ float Balloon::getPosY() const { return y_; }
return use_reversed_colors_; 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 // Actualiza al globo a su posicion, animación y controla los contadores
void update(); 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 // Detiene el globo
void stop(); void stop();
// Pone el globo en movimiento // Pone el globo en movimiento
void start(); 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 // Pone el color alternativo en el globo
void useReverseColor(); void useReverseColor();
// Pone el color normal en el globo // Pone el color normal en el globo
void useNormalColor(); 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 isUsingReversedColor();
bool canBePopped() const;
// Setters
void setVelY(float vel_y);
void setSpeed(float speed);
void setInvulnerable(bool value);
}; };

View File

@@ -56,6 +56,7 @@ Director::Director(int argc, const char *argv[])
section::name = section::Name::LOGO; section::name = section::Name::LOGO;
#else #else
section::name = section::Name::LOGO; section::name = section::Name::LOGO;
section::attract_mode = section::AttractMode::TITLE_TO_DEMO;
#endif #endif
#ifndef VERBOSE #ifndef VERBOSE
@@ -94,13 +95,9 @@ Director::Director(int argc, const char *argv[])
{ {
auto manager = std::make_unique<ManageHiScoreTable>(options.game.hi_score_table); auto manager = std::make_unique<ManageHiScoreTable>(options.game.hi_score_table);
if (overrides.clear_hi_score_table) if (overrides.clear_hi_score_table)
{
manager->clear(); manager->clear();
}
else else
{
manager->loadFromFile(Asset::get()->get("score.bin")); manager->loadFromFile(Asset::get()->get("score.bin"));
}
} }
// Inicializa SDL // Inicializa SDL
@@ -244,10 +241,16 @@ void Director::bindInputs()
void Director::initJailAudio() void Director::initJailAudio()
{ {
JA_Init(48000, AUDIO_S16, 2); JA_Init(48000, AUDIO_S16, 2);
JA_EnableMusic(options.audio.music.enabled); if (options.audio.enabled)
JA_EnableSound(options.audio.sound.enabled); {
JA_SetMusicVolume(options.audio.music.volume); JA_SetMusicVolume(to_JA_volume(options.audio.music.volume));
JA_SetSoundVolume(options.audio.sound.volume); JA_SetSoundVolume(to_JA_volume(options.audio.sound.volume));
}
else
{
JA_SetMusicVolume(0);
JA_SetSoundVolume(0);
}
} }
// Arranca SDL y crea la ventana // Arranca SDL y crea la ventana
@@ -427,15 +430,6 @@ void Director::setFileList()
Asset::get()->add(prefix + "/data/gfx/game/game_sky_colors.png", AssetType::BITMAP); 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 { // Intro
Asset::get()->add(prefix + "/data/gfx/intro/intro.png", AssetType::BITMAP); 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.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/font/8bithud.txt", AssetType::FONT); 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.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/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.gif", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/font/smb2_palette1.pal", AssetType::PALETTE); 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/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 // Textos
Asset::get()->add(prefix + "/data/lang/es_ES.txt", AssetType::LANG); Asset::get()->add(prefix + "/data/lang/es_ES.txt", AssetType::LANG);
@@ -641,7 +631,11 @@ void Director::runTitle()
void Director::runGame() void Director::runGame()
{ {
const auto player_id = section::options == section::Options::GAME_PLAY_1P ? 1 : 2; 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; constexpr auto current_stage = 0;
#endif
auto game = std::make_unique<Game>(player_id, current_stage, GAME_MODE_DEMO_OFF); auto game = std::make_unique<Game>(player_id, current_stage, GAME_MODE_DEMO_OFF);
game->run(); game->run();
} }

File diff suppressed because it is too large Load Diff

View File

@@ -1,31 +1,31 @@
#pragma once #pragma once
#include <SDL2/SDL_render.h> // Para SDL_Renderer, SDL_Texture #include <SDL2/SDL_render.h> // for SDL_Renderer, SDL_Texture
#include <SDL2/SDL_stdinc.h> // Para Uint32, Uint8 #include <SDL2/SDL_stdinc.h> // for Uint32, Uint8
#include <memory> // Para shared_ptr, unique_ptr #include <memory> // for shared_ptr, unique_ptr
#include <string> // Para string #include <string> // for string
#include <vector> // Para vector #include <vector> // for vector
#include "balloon.h" // Para Balloon #include "balloon.h" // for Balloon
#include "manage_hiscore_table.h" // Para HiScoreEntry #include "manage_hiscore_table.h" // for HiScoreEntry
#include "options.h" // Para Options, OptionsGame, options #include "options.h" // for Options, OptionsGame, options
#include "player.h" // Para Player #include "player.h" // for Player
#include "utils.h" // Para Demo #include "utils.h" // for Demo
class Asset; // lines 12-12 class Asset; // lines 14-14
class Background; // lines 13-13 class Background; // lines 15-15
class BalloonFormations; // lines 14-14 class BalloonFormations; // lines 16-16
class Bullet; // lines 15-15 class Bullet; // lines 17-17
class Explosions; // lines 16-16 class Explosions; // lines 18-18
class Fade; // lines 17-17 class Fade; // lines 19-19
class Input; // lines 18-18 class Input; // lines 20-20
class Item; // lines 19-19 class Item; // lines 21-21
class PathSprite; // lines 20-20 class PathSprite; // lines 22-22
class Scoreboard; // lines 21-21 class Scoreboard; // lines 23-23
class Screen; // lines 22-22 class Screen; // lines 24-24
class SmartSprite; // lines 23-23 class SmartSprite; // lines 25-25
class Text; // lines 24-24 class Texture; // lines 27-27
class Texture; // lines 25-25 enum class BulletType : Uint8; // lines 28-28
enum class BulletType : Uint8; // lines 26-26 enum class ItemType; // lines 29-29
enum class ItemType; // lines 27-27 struct Path;
// Modo demo // Modo demo
constexpr bool GAME_MODE_DEMO_OFF = false; constexpr bool GAME_MODE_DEMO_OFF = false;
@@ -64,10 +64,14 @@ constexpr int TOTAL_SCORE_DATA = 3;
class Game class Game
{ {
private: private:
// Constantes // Enum
enum class GameStatus
{
PLAYING,
COMPLETED,
};
// Contadores // Contadores
static constexpr int STAGE_COUNTER_ = 200;
static constexpr int HELP_COUNTER_ = 1000; static constexpr int HELP_COUNTER_ = 1000;
static constexpr int GAME_COMPLETED_START_FADE_ = 500; static constexpr int GAME_COMPLETED_START_FADE_ = 500;
static constexpr int GAME_COMPLETED_END_ = 700; static constexpr int GAME_COMPLETED_END_ = 700;
@@ -144,12 +148,8 @@ private:
std::vector<std::vector<std::string>> balloon_animations_; // Vector con las animaciones de los globos 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::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::unique_ptr<Fade> fade_; // Objeto para renderizar fades
std::vector<Path> paths_; // Vector con los recorridos precalculados almacenados
// Variables // Variables
HiScoreEntry hi_score_ = HiScoreEntry( HiScoreEntry hi_score_ = HiScoreEntry(
@@ -157,21 +157,17 @@ private:
options.game.hi_score_table[0].score); // Máxima puntuación y nombre de quien la ostenta options.game.hi_score_table[0].score); // Máxima puntuación y nombre de quien la ostenta
int current_stage_; // Indica la fase actual int current_stage_; // Indica la fase actual
int last_stage_reached_; // Contiene el número de la última pantalla que se ha alcanzado
Demo demo_; // Variable con todas las variables relacionadas con el modo demo Demo demo_; // Variable con todas las variables relacionadas con el modo demo
GameDifficulty difficulty_ = options.game.difficulty; // Dificultad del juego GameDifficulty difficulty_ = options.game.difficulty; // Dificultad del juego
Helper helper_; // Variable para gestionar las ayudas Helper helper_; // Variable para gestionar las ayudas
Uint32 ticks_ = 0; // Contador de ticks para ajustar la velocidad del programa 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 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 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 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 bool power_ball_enabled_ = false; // Indica si hay una powerball ya activa
float balloon_speed_; // Velocidad a la que se mueven los enemigos float balloon_speed_; // Velocidad a la que se mueven los enemigos
float default_balloon_speed_; // Velocidad base de los enemigos, sin incrementar float default_balloon_speed_; // Velocidad base de los enemigos, sin incrementar
float difficulty_score_multiplier_; // Multiplicador de puntos en función de la dificultad float difficulty_score_multiplier_; // Multiplicador de puntos en función de la dificultad
float get_ready_bitmap_path_[STAGE_COUNTER_]; // Vector con los puntos X por donde se desplaza el texto
int stage_bitmap_path_[STAGE_COUNTER_]; // Vector con los puntos Y por donde se desplaza el texto
int balloon_deploy_counter_ = 0; // Cuando se lanza una formación, se le da un valor y no sale otra hasta que llegue a cero int balloon_deploy_counter_ = 0; // Cuando se lanza una formación, se le da un valor y no sale otra hasta que llegue a cero
int balloons_popped_ = 0; // Lleva la cuenta de los globos explotados int balloons_popped_ = 0; // Lleva la cuenta de los globos explotados
int counter_ = 0; // Contador para el juego int counter_ = 0; // Contador para el juego
@@ -182,9 +178,9 @@ private:
int menace_current_ = 0; // Nivel de amenaza actual int menace_current_ = 0; // Nivel de amenaza actual
int menace_threshold_ = 0; // Umbral del nivel de amenaza. Si el nivel de amenaza cae por debajo del umbral, se generan más globos. Si el umbral aumenta, aumenta el número de globos int menace_threshold_ = 0; // Umbral del nivel de amenaza. Si el nivel de amenaza cae por debajo del umbral, se generan más globos. Si el umbral aumenta, aumenta el número de globos
int power_ball_counter_ = 0; // Contador de formaciones enemigas entre la aparicion de una PowerBall y otra int power_ball_counter_ = 0; // Contador de formaciones enemigas entre la aparicion de una PowerBall y otra
int stage_bitmap_counter_ = STAGE_COUNTER_; // Contador para el tiempo visible del texto de Stage
int time_stopped_counter_ = 0; // Temporizador para llevar la cuenta del tiempo detenido int time_stopped_counter_ = 0; // Temporizador para llevar la cuenta del tiempo detenido
int total_power_to_complete_game_; // La suma del poder necesario para completar todas las fases int total_power_to_complete_game_; // La suma del poder necesario para completar todas las fases
GameStatus status_ = GameStatus::PLAYING; // Estado
#ifdef DEBUG #ifdef DEBUG
bool auto_pop_balloons_ = false; // Si es true, incrementa automaticamente los globos explotados bool auto_pop_balloons_ = false; // Si es true, incrementa automaticamente los globos explotados
#endif #endif
@@ -241,7 +237,7 @@ private:
void setBalloonSpeed(float speed); void setBalloonSpeed(float speed);
// Actualiza la velocidad de los globos en funcion del poder acumulado de la fase // 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 // Explosiona un globo. Lo destruye y crea otros dos si es el caso
void popBalloon(std::shared_ptr<Balloon> balloon); void popBalloon(std::shared_ptr<Balloon> balloon);
@@ -252,6 +248,9 @@ private:
// Destruye todos los globos // Destruye todos los globos
void destroyAllBalloons(); void destroyAllBalloons();
// Destruye todos los items
void destroyAllItems();
// Detiene todos los globos // Detiene todos los globos
void stopAllBalloons(); void stopAllBalloons();
@@ -304,7 +303,10 @@ private:
void freeItems(); void freeItems();
// Crea un objeto PathSprite // 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 // Vacia el vector de smartsprites
void freeSmartSprites(); void freeSmartSprites();
@@ -363,9 +365,6 @@ private:
// Calcula el poder actual de los globos en pantalla // Calcula el poder actual de los globos en pantalla
int calculateScreenPower(); int calculateScreenPower();
// Actualiza el tramo final de juego, una vez completado
void updateGameCompleted();
// Actualiza las variables de ayuda // Actualiza las variables de ayuda
void updateHelper(); void updateHelper();
@@ -465,6 +464,18 @@ private:
// Detiene la música // Detiene la música
void stopMusic(); 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 updateNormalGame();
// Actualiza las variables durante el transcurso del final del juego
void updateCompletedGame();
public: public:
// Constructor // Constructor
Game(int playerID, int current_stage, bool demo); Game(int playerID, int current_stage, bool demo);

View File

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

View File

@@ -56,10 +56,18 @@ namespace globalInputs
// Activa o desactiva el audio // Activa o desactiva el audio
void switchAudio() void switchAudio()
{ {
options.audio.sound.enabled = options.audio.music.enabled = !options.audio.music.enabled; options.audio.enabled = !options.audio.enabled;
JA_EnableMusic(options.audio.music.enabled); if (options.audio.enabled)
JA_EnableSound(options.audio.sound.enabled); {
Notifier::get()->showText("Audio " + boolToOnOff(options.audio.music.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 // Comprueba los inputs que se pueden introducir en cualquier sección del juego

View File

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

View File

@@ -53,6 +53,13 @@ Logo::Logo()
color_.push_back(Color(0xFF, 0xFF, 0xFF)); // Bright white 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 // Recarga todas las texturas
void Logo::reloadTextures() void Logo::reloadTextures()
{ {

View File

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

View File

@@ -32,10 +32,12 @@ void initOptions()
options.video.shaders = true; options.video.shaders = true;
// Opciones de audio // Opciones de audio
options.audio.enabled = true;
options.audio.volume = 100;
options.audio.music.enabled = true; options.audio.music.enabled = true;
options.audio.music.volume = 128; options.audio.music.volume = 100;
options.audio.sound.enabled = true; options.audio.sound.enabled = true;
options.audio.sound.volume = 64; options.audio.sound.volume = 50;
// Opciones de juego // Opciones de juego
options.game.difficulty = GameDifficulty::NORMAL; options.game.difficulty = GameDifficulty::NORMAL;
@@ -178,9 +180,11 @@ bool saveOptionsFile(std::string file_path)
// Opciones de audio // Opciones de audio
file << "\n\n## AUDIO\n"; file << "\n\n## AUDIO\n";
file << "## volume [0 .. 128]\n"; file << "## volume [0 .. 100]\n";
file << "\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.enabled=" + boolToString(options.audio.music.enabled) + "\n";
file << "audio.music.volume=" + std::to_string(options.audio.music.volume) + "\n"; file << "audio.music.volume=" + std::to_string(options.audio.music.volume) + "\n";
file << "audio.sound.enabled=" + boolToString(options.audio.sound.enabled) + "\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 // 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") else if (var == "audio.music.enabled")
{ {
options.audio.music.enabled = stringToBool(value); options.audio.music.enabled = stringToBool(value);
@@ -387,4 +400,11 @@ bool setOptions(const std::string &var, const std::string &value)
} }
return success; 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 OptionsMusic music; // Opciones para la música
OptionsSound sound; // Opciones para los efectos de sonido 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 // Estructura para las opciones del juego
@@ -96,4 +98,7 @@ extern Options options;
bool loadOptionsFile(std::string file_path); bool loadOptionsFile(std::string file_path);
// Guarda el fichero de configuración // 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

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

View File

@@ -1,40 +1,11 @@
#include "path_sprite.h" #include "path_sprite.h"
#include <bits/std_abs.h> // Para abs #include <cmath> // for abs
#include <stdlib.h> // Para abs #include <stdlib.h> // for abs
#include <utility> // Para move #include <functional> // for function
#include "moving_sprite.h" // Para MovingSprite #include <utility> // for move
#include "utils.h" // Para easeOutQuint
#include <functional>
class Texture; // lines 3-3
// 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);
}
// Devuelve un vector con los puntos que conforman la ruta // 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; std::vector<SDL_Point> v;
v.reserve(steps); v.reserve(steps);
@@ -69,6 +40,59 @@ std::vector<SDL_Point> PathSprite::createPath(int start, int end, PathType type,
return v; 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 // Habilita el objeto
void PathSprite::enable() void PathSprite::enable()
{ {
@@ -82,7 +106,7 @@ void PathSprite::moveThroughCurrentPath()
// Establece la posición // Establece la posición
const auto &p = path.spots.at(path.counter); const auto &p = path.spots.at(path.counter);
MovingSprite::setPos(p.x, p.y); setPosition(p);
// Comprobar si ha terminado el recorrido // Comprobar si ha terminado el recorrido
if (!path.on_destination) if (!path.on_destination)
@@ -101,7 +125,7 @@ void PathSprite::moveThroughCurrentPath()
if (path.waiting_counter == 0) if (path.waiting_counter == 0)
path.finished = true; path.finished = true;
else else
--path.waiting_counter; --path.waiting_counter;
} }
} }

View File

@@ -1,11 +1,11 @@
#pragma once #pragma once
#include <SDL2/SDL_rect.h> // Para SDL_Point #include <SDL2/SDL_rect.h> // for SDL_Point
#include <memory> // Para shared_ptr #include <functional> // for function
#include <functional> #include <memory> // for shared_ptr
#include <vector> // Para vector #include <vector> // for vector
#include "animated_sprite.h" // Para AnimatedSprite #include "sprite.h" // for Sprite
class Texture; // lines 5-5 class Texture; // lines 8-8
enum class PathType enum class PathType
{ {
@@ -13,26 +13,35 @@ enum class PathType
HORIZONTAL, 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 // Clase PathSprite
class PathSprite : public AnimatedSprite class PathSprite : public Sprite
{ {
private: 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 // Variables
bool finished_ = false; // Indica si ya ha terminado
bool enabled_ = false; // Indica si el objeto está habilitado bool enabled_ = false; // Indica si el objeto está habilitado
int current_path_ = 0; // Path que se está recorriendo actualmente int current_path_ = 0; // Path que se está recorriendo actualmente
std::vector<Path> paths_; // Caminos a recorrer por el sprite std::vector<Path> paths_; // Caminos a recorrer por el sprite
@@ -45,21 +54,20 @@ private:
public: public:
// Constructor // Constructor
explicit PathSprite(std::shared_ptr<Texture> texture); explicit PathSprite(std::shared_ptr<Texture> texture)
: Sprite(texture) {}
// Destructor // Destructor
~PathSprite() = default; ~PathSprite() = default;
// Actualiza la posición del sprite // Actualiza la posición del sprite
void update() override; void update();
// Añade un recorrido // Añade un recorrido
void addPath(Path path, bool centered = false);
void addPath(std::vector<SDL_Point> spots, int waiting_counter); void addPath(std::vector<SDL_Point> spots, int waiting_counter);
void addPath(int start, int end, PathType type, int fixed_pos, int steps, const std::function<double(double)> &easingFunction, int waiting_counter); void addPath(int start, int end, PathType type, int fixed_pos, int steps, const std::function<double(double)> &easingFunction, int waiting_counter);
// 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 // Habilita el objeto
void enable(); void enable();

View File

@@ -61,8 +61,7 @@ void Player::init()
// Establece la posición del sprite // Establece la posición del sprite
player_sprite_->clear(); player_sprite_->clear();
player_sprite_->setPosX(pos_x_); shiftSprite();
player_sprite_->setPosY(pos_y_);
// Selecciona un frame para pintar // Selecciona un frame para pintar
player_sprite_->setCurrentAnimation("stand"); player_sprite_->setCurrentAnimation("stand");
@@ -78,13 +77,16 @@ void Player::setInput(InputType input)
setInputPlaying(input); setInputPlaying(input);
break; break;
} }
case PlayerStatus::ENTERING_NAME: case PlayerStatus::ENTERING_NAME:
{ {
setInputEnteringName(input); setInputEnteringName(input);
break; break;
} }
case PlayerStatus::ENTERING_NAME_GAME_COMPLETED:
{
setInputEnteringName(input);
break;
}
default: default:
break; break;
} }
@@ -101,32 +103,27 @@ void Player::setInputPlaying(InputType input)
setWalkingStatus(PlayerStatus::WALKING_LEFT); setWalkingStatus(PlayerStatus::WALKING_LEFT);
break; break;
} }
case InputType::RIGHT: case InputType::RIGHT:
{ {
vel_x_ = BASE_SPEED_; vel_x_ = BASE_SPEED_;
setWalkingStatus(PlayerStatus::WALKING_RIGHT); setWalkingStatus(PlayerStatus::WALKING_RIGHT);
break; break;
} }
case InputType::FIRE_CENTER: case InputType::FIRE_CENTER:
{ {
setFiringStatus(PlayerStatus::FIRING_UP); setFiringStatus(PlayerStatus::FIRING_UP);
break; break;
} }
case InputType::FIRE_LEFT: case InputType::FIRE_LEFT:
{ {
setFiringStatus(PlayerStatus::FIRING_LEFT); setFiringStatus(PlayerStatus::FIRING_LEFT);
break; break;
} }
case InputType::FIRE_RIGHT: case InputType::FIRE_RIGHT:
{ {
setFiringStatus(PlayerStatus::FIRING_RIGHT); setFiringStatus(PlayerStatus::FIRING_RIGHT);
break; break;
} }
default: default:
{ {
vel_x_ = 0; vel_x_ = 0;
@@ -144,23 +141,18 @@ void Player::setInputEnteringName(InputType input)
case InputType::LEFT: case InputType::LEFT:
enter_name_->decPosition(); enter_name_->decPosition();
break; break;
case InputType::RIGHT: case InputType::RIGHT:
enter_name_->incPosition(); enter_name_->incPosition();
break; break;
case InputType::UP: case InputType::UP:
enter_name_->incIndex(); enter_name_->incIndex();
break; break;
case InputType::DOWN: case InputType::DOWN:
enter_name_->decIndex(); enter_name_->decIndex();
break; break;
case InputType::START: case InputType::START:
setRecordName(enter_name_->getName()); setRecordName(enter_name_->getName());
break; break;
default: default:
break; break;
} }
@@ -170,44 +162,57 @@ void Player::setInputEnteringName(InputType input)
// Mueve el jugador a la posición y animación que le corresponde // Mueve el jugador a la posición y animación que le corresponde
void Player::move() void Player::move()
{ {
if (isPlaying()) switch (status_playing_)
{
case PlayerStatus::PLAYING:
{ {
// Mueve el jugador a derecha o izquierda // Mueve el jugador a derecha o izquierda
pos_x_ += vel_x_; pos_x_ += vel_x_;
// Si el jugador abandona el area de juego por los laterales // Si el jugador abandona el area de juego por los laterales, restaura su posición
if ((pos_x_ < param.game.play_area.rect.x - 5) || (pos_x_ + WIDTH_ > play_area_.w + 5)) const float min_x = param.game.play_area.rect.x - 5;
{ const float max_x = play_area_.w + 5 - WIDTH_;
// Restaura su posición pos_x_ = std::clamp(pos_x_, min_x, max_x);
pos_x_ -= vel_x_;
}
// Actualiza la posición del sprite shiftSprite();
player_sprite_->setPosX(getPosX()); break;
player_sprite_->setPosY(pos_y_);
power_sprite_->setPosX(getPosX() - power_up_desp_x_);
} }
else if (isDying()) case PlayerStatus::DYING:
{ {
player_sprite_->update(); // Si el cadaver abandona el area de juego por los laterales lo hace rebotar
// Si el cadaver abandona el area de juego por los laterales
if ((player_sprite_->getPosX() < param.game.play_area.rect.x) || (player_sprite_->getPosX() + WIDTH_ > play_area_.w)) if ((player_sprite_->getPosX() < param.game.play_area.rect.x) || (player_sprite_->getPosX() + WIDTH_ > play_area_.w))
{ player_sprite_->setVelX(-player_sprite_->getVelX());
// Restaura su posición
const float vx = player_sprite_->getVelX();
player_sprite_->setPosX(player_sprite_->getPosX() - vx);
// Rebota
player_sprite_->setVelX(-vx);
}
// Si el cadaver abandona el area de juego por abajo // Si el cadaver abandona el area de juego por abajo
if (player_sprite_->getPosY() > param.game.play_area.rect.h) if (player_sprite_->getPosY() > param.game.play_area.rect.h)
{
setStatusPlaying(PlayerStatus::DIED); setStatusPlaying(PlayerStatus::DIED);
break;
}
case PlayerStatus::GAME_COMPLETED:
{
switch (id_)
{
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)
setStatusPlaying(PlayerStatus::GAME_OVER);
break;
}
default:
break;
} }
} }
@@ -215,28 +220,18 @@ void Player::move()
void Player::render() void Player::render()
{ {
if (power_up_ && isPlaying()) if (power_up_ && isPlaying())
{
if (power_up_counter_ > (POWERUP_COUNTER_ / 4) || power_up_counter_ % 20 > 4) if (power_up_counter_ > (POWERUP_COUNTER_ / 4) || power_up_counter_ % 20 > 4)
{
power_sprite_->render(); power_sprite_->render();
}
}
if (isRenderable()) if (isRenderable())
player_sprite_->render(); player_sprite_->render();
} }
// Establece el estado del jugador cuando camina // Establece el estado del jugador cuando camina
void Player::setWalkingStatus(PlayerStatus status) void Player::setWalkingStatus(PlayerStatus status) { status_walking_ = status; }
{
status_walking_ = status;
}
// Establece el estado del jugador cuando dispara // Establece el estado del jugador cuando dispara
void Player::setFiringStatus(PlayerStatus status) void Player::setFiringStatus(PlayerStatus status) { status_firing_ = status; }
{
status_firing_ = status;
}
// Establece la animación correspondiente al estado // Establece la animación correspondiente al estado
void Player::setAnimation() void Player::setAnimation()
@@ -244,24 +239,31 @@ void Player::setAnimation()
// Crea cadenas de texto para componer el nombre de la animación // 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_walking = status_walking_ == PlayerStatus::WALKING_STOP ? "stand" : "walk";
const std::string a_firing = status_firing_ == PlayerStatus::FIRING_UP ? "centershoot" : "sideshoot"; const std::string a_firing = status_firing_ == PlayerStatus::FIRING_UP ? "centershoot" : "sideshoot";
const std::string a_cooling = status_firing_ == PlayerStatus::COOLING_UP ? "centershoot" : "sideshoot";
const SDL_RendererFlip flip_walk = status_walking_ == PlayerStatus::WALKING_RIGHT ? SDL_FLIP_HORIZONTAL : SDL_FLIP_NONE; 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_fire = status_firing_ == PlayerStatus::FIRING_RIGHT ? SDL_FLIP_HORIZONTAL : SDL_FLIP_NONE;
const SDL_RendererFlip flip_cooling = status_firing_ == PlayerStatus::COOLING_RIGHT ? SDL_FLIP_HORIZONTAL : SDL_FLIP_NONE;
// Establece la animación a partir de las cadenas // Establece la animación a partir de las cadenas
if (isPlaying()) if (isPlaying() || isEnteringNameGameCompleted() || isGameCompleted())
{ {
if (status_firing_ == PlayerStatus::FIRING_NONE) if (status_firing_ == PlayerStatus::FIRING_NONE)
{ // No esta disparando { // No esta disparando
player_sprite_->setCurrentAnimation(a_walking); player_sprite_->setCurrentAnimation(a_walking);
player_sprite_->setFlip(flip_walk); 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 else
{ // Está disparando { // Está disparando
player_sprite_->setCurrentAnimation(a_walking + "-" + a_firing); player_sprite_->setCurrentAnimation(a_walking + "-" + a_firing);
// Si dispara de lado, invierte el sprite segun hacia donde dispara // Si dispara de lado, invierte el sprite segun hacia donde dispara
// Si dispara recto, invierte el sprite segun hacia donde camina // 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
@@ -270,63 +272,63 @@ void Player::setAnimation()
} }
// Actualiza las animaciones de los sprites // Actualiza las animaciones de los sprites
player_sprite_->update(); player_sprite_->update(); // Hace avanzar las animaciones y mueve el cadaver del jugador
// powerSprite->setFlip(flip_walk);
power_sprite_->update(); power_sprite_->update();
} }
// Obtiene el valor de la variable // Obtiene el valor de la variable
int Player::getPosX() const int Player::getPosX() const { return static_cast<int>(pos_x_); }
{
return int(pos_x_);
}
// Obtiene el valor de la variable // Obtiene el valor de la variable
int Player::getPosY() const int Player::getPosY() const { return pos_y_; }
{
return pos_y_;
}
// Obtiene el valor de la variable // Obtiene el valor de la variable
int Player::getWidth() const int Player::getWidth() const { return WIDTH_; }
{
return WIDTH_;
}
// Obtiene el valor de la variable // Obtiene el valor de la variable
int Player::getHeight() const int Player::getHeight() const { return HEIGHT_; }
{
return HEIGHT_;
}
// Indica si el jugador puede disparar // Indica si el jugador puede disparar
bool Player::canFire() const bool Player::canFire() const { return cooldown_ > 0 ? false : true; }
{
// 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 // Establece el valor de la variable
void Player::setFireCooldown(int time) void Player::setFireCooldown(int time) { cooldown_ = time; }
{
cooldown_ = time;
}
// Actualiza el valor de la variable // Actualiza el valor de la variable
void Player::updateCooldown() void Player::updateCooldown()
{ {
if (cooldown_ > 0) if (cooldown_ > 0)
{ {
cooldown_--; cooldown_ -= power_up_ ? 2 : 1;
if (power_up_)
{
cooldown_--;
}
} }
else else
{ {
setFiringStatus(PlayerStatus::FIRING_NONE); if (!isCooling())
{
cooling_status_counter_ = 40;
switch (status_firing_)
{
case PlayerStatus::FIRING_LEFT:
status_firing_ = PlayerStatus::COOLING_LEFT;
break;
case PlayerStatus::FIRING_RIGHT:
status_firing_ = PlayerStatus::COOLING_RIGHT;
break;
case PlayerStatus::FIRING_UP:
status_firing_ = PlayerStatus::COOLING_UP;
break;
default:
break;
}
}
else if (cooling_status_counter_ > 0)
{
--cooling_status_counter_;
}
else
{
setFiringStatus(PlayerStatus::FIRING_NONE);
}
} }
} }
@@ -345,16 +347,10 @@ void Player::update()
} }
// Obtiene la puntuación del jugador // Obtiene la puntuación del jugador
int Player::getScore() const int Player::getScore() const { return score_; }
{
return score_;
}
// Asigna un valor a la puntuación del jugador // Asigna un valor a la puntuación del jugador
void Player::setScore(int score) void Player::setScore(int score) { score_ = score; }
{
score_ = score;
}
// Incrementa la puntuación del jugador // Incrementa la puntuación del jugador
void Player::addScore(int score) void Player::addScore(int score)
@@ -366,66 +362,54 @@ void Player::addScore(int score)
} }
// Indica si el jugador está jugando // Indica si el jugador está jugando
bool Player::isPlaying() const bool Player::isPlaying() const { return status_playing_ == PlayerStatus::PLAYING; }
{
return status_playing_ == PlayerStatus::PLAYING;
}
// Indica si el jugador está continuando // Indica si el jugador está continuando
bool Player::isContinue() const bool Player::isContinue() const { return status_playing_ == PlayerStatus::CONTINUE; }
{
return status_playing_ == PlayerStatus::CONTINUE;
}
// Indica si el jugador está esperando // Indica si el jugador está esperando
bool Player::isWaiting() const bool Player::isWaiting() const { return status_playing_ == PlayerStatus::WAITING; }
{
return status_playing_ == PlayerStatus::WAITING;
}
// Indica si el jugador está introduciendo su nombre // Indica si el jugador está introduciendo su nombre
bool Player::isEnteringName() const bool Player::isEnteringName() const { return status_playing_ == PlayerStatus::ENTERING_NAME; }
{
return status_playing_ == PlayerStatus::ENTERING_NAME;
}
// Indica si el jugador está muriendose // Indica si el jugador está muriendose
bool Player::isDying() const bool Player::isDying() const { return status_playing_ == PlayerStatus::DYING; }
{
return status_playing_ == PlayerStatus::DYING;
}
// Indica si el jugador ha terminado de morir // Indica si el jugador ha terminado de morir
bool Player::hasDied() const bool Player::hasDied() const { return status_playing_ == PlayerStatus::DIED; }
{
return status_playing_ == PlayerStatus::DIED;
}
// Indica si el jugador ya ha terminado de jugar // Indica si el jugador ya ha terminado de jugar
bool Player::isGameOver() const bool Player::isGameOver() const { return status_playing_ == PlayerStatus::GAME_OVER; }
{
return status_playing_ == PlayerStatus::GAME_OVER; // Indica si el jugador está introduciendo su nombre una vez ha completado el juego
} bool Player::isEnteringNameGameCompleted() const { return status_playing_ == PlayerStatus::ENTERING_NAME_GAME_COMPLETED; }
// Indica si el jugador ha completado el juego
bool Player::isGameCompleted() const { return status_playing_ == PlayerStatus::GAME_COMPLETED; }
// Actualiza el panel del marcador // Actualiza el panel del marcador
void Player::updateScoreboard() void Player::updateScoreboard()
{ {
switch (status_playing_) switch (status_playing_)
{ {
case PlayerStatus::CONTINUE: case PlayerStatus::CONTINUE:
{ {
Scoreboard::get()->setContinue(getScoreBoardPanel(), getContinueCounter()); Scoreboard::get()->setContinue(getScoreBoardPanel(), getContinueCounter());
break; break;
} }
case PlayerStatus::ENTERING_NAME: case PlayerStatus::ENTERING_NAME:
{ {
Scoreboard::get()->setRecordName(getScoreBoardPanel(), getRecordName()); Scoreboard::get()->setRecordName(getScoreBoardPanel(), getRecordName());
Scoreboard::get()->setSelectorPos(getScoreBoardPanel(), getRecordNamePos()); Scoreboard::get()->setSelectorPos(getScoreBoardPanel(), getRecordNamePos());
break; break;
} }
case PlayerStatus::ENTERING_NAME_GAME_COMPLETED:
{
Scoreboard::get()->setRecordName(getScoreBoardPanel(), getRecordName());
Scoreboard::get()->setSelectorPos(getScoreBoardPanel(), getRecordNamePos());
break;
}
default: default:
break; break;
} }
@@ -454,7 +438,6 @@ void Player::setStatusPlaying(PlayerStatus value)
setScoreboardMode(ScoreboardMode::SCORE); setScoreboardMode(ScoreboardMode::SCORE);
break; break;
} }
case PlayerStatus::CONTINUE: case PlayerStatus::CONTINUE:
{ {
// Inicializa el contador de continuar // Inicializa el contador de continuar
@@ -464,19 +447,16 @@ void Player::setStatusPlaying(PlayerStatus value)
setScoreboardMode(ScoreboardMode::CONTINUE); setScoreboardMode(ScoreboardMode::CONTINUE);
break; break;
} }
case PlayerStatus::WAITING: case PlayerStatus::WAITING:
{ {
setScoreboardMode(ScoreboardMode::WAITING); setScoreboardMode(ScoreboardMode::WAITING);
break; break;
} }
case PlayerStatus::ENTERING_NAME: case PlayerStatus::ENTERING_NAME:
{ {
setScoreboardMode(ScoreboardMode::ENTER_NAME); setScoreboardMode(ScoreboardMode::ENTER_NAME);
break; break;
} }
case PlayerStatus::DYING: case PlayerStatus::DYING:
{ {
// Activa la animación de morir // Activa la animación de morir
@@ -485,42 +465,42 @@ void Player::setStatusPlaying(PlayerStatus value)
rand() % 2 == 0 ? player_sprite_->setVelX(3.3f) : player_sprite_->setVelX(-3.3f); rand() % 2 == 0 ? player_sprite_->setVelX(3.3f) : player_sprite_->setVelX(-3.3f);
break; break;
} }
case PlayerStatus::DIED: case PlayerStatus::DIED:
{ {
const auto nextPlayerStatus = IsEligibleForHighScore() ? PlayerStatus::ENTERING_NAME : PlayerStatus::CONTINUE; const auto nextPlayerStatus = IsEligibleForHighScore() ? PlayerStatus::ENTERING_NAME : PlayerStatus::CONTINUE;
demo_ ? setStatusPlaying(PlayerStatus::WAITING) : setStatusPlaying(nextPlayerStatus); demo_ ? setStatusPlaying(PlayerStatus::WAITING) : setStatusPlaying(nextPlayerStatus);
break; break;
} }
case PlayerStatus::GAME_OVER: case PlayerStatus::GAME_OVER:
{ {
setScoreboardMode(ScoreboardMode::GAME_OVER); setScoreboardMode(ScoreboardMode::GAME_OVER);
break; break;
} }
case PlayerStatus::ENTERING_NAME_GAME_COMPLETED:
{
setWalkingStatus(PlayerStatus::WALKING_STOP);
setFiringStatus(PlayerStatus::FIRING_NONE);
setScoreboardMode(ScoreboardMode::ENTER_NAME);
break;
}
case PlayerStatus::GAME_COMPLETED:
{
setScoreboardMode(ScoreboardMode::GAME_OVER);
break;
}
default: default:
break; break;
} }
} }
// Obtiene el estado del jugador en el juego // Obtiene el estado del jugador en el juego
PlayerStatus Player::getStatusPlaying() const PlayerStatus Player::getStatusPlaying() const { return status_playing_; }
{
return status_playing_;
}
// Obtiene el valor de la variable // Obtiene el valor de la variable
float Player::getScoreMultiplier() const float Player::getScoreMultiplier() const { return score_multiplier_; }
{
return score_multiplier_;
}
// Establece el valor de la variable // Establece el valor de la variable
void Player::setScoreMultiplier(float value) void Player::setScoreMultiplier(float value) { score_multiplier_ = value; }
{
score_multiplier_ = value;
}
// Aumenta el valor de la variable hasta un máximo // Aumenta el valor de la variable hasta un máximo
void Player::incScoreMultiplier() void Player::incScoreMultiplier()
@@ -537,10 +517,7 @@ void Player::decScoreMultiplier()
} }
// Obtiene el valor de la variable // Obtiene el valor de la variable
bool Player::isInvulnerable() const bool Player::isInvulnerable() const { return invulnerable_; }
{
return invulnerable_;
}
// Establece el valor del estado // Establece el valor del estado
void Player::setInvulnerable(bool value) void Player::setInvulnerable(bool value)
@@ -550,16 +527,10 @@ void Player::setInvulnerable(bool value)
} }
// Obtiene el valor de la variable // Obtiene el valor de la variable
int Player::getInvulnerableCounter() const int Player::getInvulnerableCounter() const { return invulnerable_counter_; }
{
return invulnerable_counter_;
}
// Establece el valor de la variable // Establece el valor de la variable
void Player::setInvulnerableCounter(int value) void Player::setInvulnerableCounter(int value) { invulnerable_counter_ = value; }
{
invulnerable_counter_ = value;
}
// Monitoriza el estado // Monitoriza el estado
void Player::updateInvulnerable() void Player::updateInvulnerable()
@@ -580,10 +551,7 @@ void Player::updateInvulnerable()
} }
// Obtiene el valor de la variable // Obtiene el valor de la variable
bool Player::isPowerUp() const bool Player::isPowerUp() const { return power_up_; }
{
return power_up_;
}
// Establece el valor de la variable // Establece el valor de la variable
void Player::setPowerUp() void Player::setPowerUp()
@@ -593,16 +561,10 @@ void Player::setPowerUp()
} }
// Obtiene el valor de la variable // Obtiene el valor de la variable
int Player::getPowerUpCounter() const int Player::getPowerUpCounter() const { return power_up_counter_; }
{
return power_up_counter_;
}
// Establece el valor de la variable // Establece el valor de la variable
void Player::setPowerUpCounter(int value) void Player::setPowerUpCounter(int value) { power_up_counter_ = value; }
{
power_up_counter_ = value;
}
// Actualiza el valor de la variable // Actualiza el valor de la variable
void Player::updatePowerUp() void Player::updatePowerUp()
@@ -615,10 +577,7 @@ void Player::updatePowerUp()
} }
// Obtiene el valor de la variable // Obtiene el valor de la variable
bool Player::hasExtraHit() const bool Player::hasExtraHit() const { return extra_hit_; }
{
return extra_hit_;
}
// Concede un toque extra al jugador // Concede un toque extra al jugador
void Player::giveExtraHit() void Player::giveExtraHit()
@@ -645,16 +604,10 @@ void Player::removeExtraHit()
} }
// Devuelve el número de cafes actuales // Devuelve el número de cafes actuales
int Player::getCoffees() const int Player::getCoffees() const { return coffees_; }
{
return coffees_;
}
// Obtiene el circulo de colisión // Obtiene el circulo de colisión
Circle &Player::getCollider() Circle &Player::getCollider() { return collider_; }
{
return collider_;
}
// Actualiza el circulo de colisión a la posición del jugador // Actualiza el circulo de colisión a la posición del jugador
void Player::shiftColliders() void Player::shiftColliders()
@@ -671,10 +624,7 @@ void Player::setPlayerTextures(const std::vector<std::shared_ptr<Texture>> &text
} }
// Obtiene el valor de la variable // Obtiene el valor de la variable
int Player::getContinueCounter() const int Player::getContinueCounter() const { return continue_counter_; }
{
return continue_counter_;
}
// Actualiza el contador de continue // Actualiza el contador de continue
void Player::updateContinueCounter() void Player::updateContinueCounter()
@@ -692,7 +642,7 @@ void Player::updateContinueCounter()
// Actualiza el contador de entrar nombre // Actualiza el contador de entrar nombre
void Player::updateEnterNameCounter() void Player::updateEnterNameCounter()
{ {
if (status_playing_ == PlayerStatus::ENTERING_NAME) if (status_playing_ == PlayerStatus::ENTERING_NAME || status_playing_ == PlayerStatus::ENTERING_NAME_GAME_COMPLETED)
{ {
constexpr int TICKS_SPEED = 1000; constexpr int TICKS_SPEED = 1000;
if (SDL_GetTicks() - enter_name_ticks_ > TICKS_SPEED) if (SDL_GetTicks() - enter_name_ticks_ > TICKS_SPEED)
@@ -703,16 +653,10 @@ void Player::updateEnterNameCounter()
} }
// Le asigna un panel en el marcador al jugador // Le asigna un panel en el marcador al jugador
void Player::setScoreBoardPanel(int panel) void Player::setScoreBoardPanel(int panel) { scoreboard_panel_ = panel; }
{
scoreboard_panel_ = panel;
}
// Obtiene el valor de la variable // Obtiene el valor de la variable
int Player::getScoreBoardPanel() const int Player::getScoreBoardPanel() const { return scoreboard_panel_; }
{
return scoreboard_panel_;
}
// Decrementa el contador de continuar // Decrementa el contador de continuar
void Player::decContinueCounter() void Player::decContinueCounter()
@@ -738,66 +682,47 @@ void Player::decEnterNameCounter()
} }
// Establece el nombre del jugador // Establece el nombre del jugador
void Player::setName(const std::string &name) void Player::setName(const std::string &name) { name_ = name; }
{
name_ = name;
}
// Establece el nombre del jugador para la tabla de mejores puntuaciones // Establece el nombre del jugador para la tabla de mejores puntuaciones
void Player::setRecordName(const std::string &record_name) void Player::setRecordName(const std::string &record_name) { record_name_ = record_name.substr(0, 8); }
{
record_name_ = record_name.substr(0, 8);
}
// Obtiene el nombre del jugador // Obtiene el nombre del jugador
std::string Player::getName() const std::string Player::getName() const { return name_; }
{
return name_;
}
// Obtiene el nombre del jugador para la tabla de mejores puntuaciones // Obtiene el nombre del jugador para la tabla de mejores puntuaciones
std::string Player::getRecordName() const std::string Player::getRecordName() const { return record_name_; }
{
return record_name_;
}
// Obtiene la posici´´on que se está editando del nombre del jugador para la tabla de mejores puntuaciones // Obtiene la posici´´on que se está editando del nombre del jugador para la tabla de mejores puntuaciones
int Player::getRecordNamePos() const int Player::getRecordNamePos() const
{ {
if (enter_name_) if (enter_name_)
{
return enter_name_->getPosition(); return enter_name_->getPosition();
}
return 0; return 0;
} }
// Establece el mando que usará para ser controlado // Establece el mando que usará para ser controlado
void Player::setController(int index) void Player::setController(int index) { controller_index_ = index; }
{
controller_index_ = index;
}
// Obtiene el mando que usa para ser controlado // Obtiene el mando que usa para ser controlado
int Player::getController() const int Player::getController() const { return controller_index_; }
{
return controller_index_;
}
// Obtiene el "id" del jugador // Obtiene el "id" del jugador
int Player::getId() const int Player::getId() const { return id_; }
{
return id_;
}
// Indica si el jugador se puede dibujar // Indica si el jugador se puede dibujar
bool Player::isRenderable() const bool Player::isRenderable() const { return isPlaying() || isDying() || isEnteringNameGameCompleted() || isGameCompleted(); }
{
return isPlaying() || isDying();
}
// Comprueba si la puntuación entra en la tabla de mejores puntuaciones // Comprueba si la puntuación entra en la tabla de mejores puntuaciones
bool Player::IsEligibleForHighScore() bool Player::IsEligibleForHighScore() { return score_ > options.game.hi_score_table.back().score; }
// Recoloca los sprites
void Player::shiftSprite()
{ {
return score_ > options.game.hi_score_table.back().score; player_sprite_->setPosX(pos_x_);
} player_sprite_->setPosY(pos_y_);
power_sprite_->setPosX(getPosX() - power_up_desp_x_);
}
bool Player::isCooling() { return status_firing_ == PlayerStatus::COOLING_LEFT || status_firing_ == PlayerStatus::COOLING_UP || status_firing_ == PlayerStatus::COOLING_RIGHT; }

View File

@@ -1,16 +1,17 @@
#pragma once #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_rect.h> // Para SDL_Rect
#include <SDL2/SDL_stdinc.h> // Para Uint32 #include <SDL2/SDL_stdinc.h> // Para Uint32
#include <memory> // Para unique_ptr, shared_ptr #include <memory> // Para unique_ptr, shared_ptr
#include <string> // Para string #include <string> // Para string
#include <vector> // Para vector #include <vector> // Para vector
#include "animated_sprite.h" // Para AnimatedSprite
#include "enter_name.h" // Para EnterName class Texture; // lines 12-12
#include "utils.h" // Para Circle enum class InputType : int; // lines 13-13
class Texture; // lines 12-12 enum class ScoreboardMode; // lines 14-14
enum class InputType : int; // lines 13-13
enum class ScoreboardMode; // lines 14-14
// Estados del jugador // Estados del jugador
enum class PlayerStatus enum class PlayerStatus
@@ -24,6 +25,10 @@ enum class PlayerStatus
FIRING_RIGHT, FIRING_RIGHT,
FIRING_NONE, FIRING_NONE,
COOLING_UP,
COOLING_LEFT,
COOLING_RIGHT,
PLAYING, PLAYING,
CONTINUE, CONTINUE,
WAITING, WAITING,
@@ -31,10 +36,10 @@ enum class PlayerStatus
DYING, DYING,
DIED, DIED,
GAME_OVER, GAME_OVER,
ENTERING_NAME_GAME_COMPLETED,
GAME_COMPLETED,
}; };
// Variables del jugador
// Clase Player // Clase Player
class Player class Player
{ {
@@ -60,7 +65,8 @@ private:
int default_pos_y_; // 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 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 vel_y_ = 0.0f; // Cantidad de pixeles a desplazarse en el eje Y
int cooldown_ = 10; // Contador durante el cual no puede disparar 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 int score_ = 0; // Puntos del jugador
float score_multiplier_ = 1.0f; // Multiplicador de puntos float score_multiplier_ = 1.0f; // Multiplicador de puntos
PlayerStatus status_walking_ = PlayerStatus::WALKING_STOP; // Estado del jugador al moverse PlayerStatus status_walking_ = PlayerStatus::WALKING_STOP; // Estado del jugador al moverse
@@ -87,6 +93,9 @@ private:
// Actualiza el circulo de colisión a la posición del jugador // Actualiza el circulo de colisión a la posición del jugador
void shiftColliders(); void shiftColliders();
// Recoloca el sprite
void shiftSprite();
// Monitoriza el estado // Monitoriza el estado
void updateInvulnerable(); void updateInvulnerable();
@@ -105,12 +114,11 @@ private:
// Actualiza el panel del marcador // Actualiza el panel del marcador
void updateScoreboard(); void updateScoreboard();
// Comprueba si la puntuación entra en la tabla de mejores puntuaciones
bool IsEligibleForHighScore();
// Cambia el modo del marcador // Cambia el modo del marcador
void setScoreboardMode(ScoreboardMode mode); void setScoreboardMode(ScoreboardMode mode);
bool isCooling();
public: public:
// Constructor // 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); 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);
@@ -202,6 +210,12 @@ public:
// Indica si el jugador ya ha terminado de jugar // Indica si el jugador ya ha terminado de jugar
bool isGameOver() const; bool isGameOver() const;
// Indica si el jugador está introduciendo su nombre una vez ha completado el juego
bool isEnteringNameGameCompleted() const;
// Indica si el jugador ha completado el juego
bool isGameCompleted() const;
// Establece el estado del jugador en el juego // Establece el estado del jugador en el juego
void setStatusPlaying(PlayerStatus value); void setStatusPlaying(PlayerStatus value);
@@ -286,7 +300,7 @@ public:
// Obtiene el nombre del jugador para la tabla de mejores puntuaciones // Obtiene el nombre del jugador para la tabla de mejores puntuaciones
std::string getRecordName() const; 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; int getRecordNamePos() const;
// Establece el mando que usará para ser controlado // Establece el mando que usará para ser controlado
@@ -297,4 +311,7 @@ public:
// Obtiene el "id" del jugador // Obtiene el "id" del jugador
int getId() const; 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 <iostream> // Para basic_ostream, operator<<, endl, cout, cerr
#include <stdexcept> // Para runtime_error #include <stdexcept> // Para runtime_error
#include "asset.h" // Para Asset, AssetType #include "asset.h" // Para Asset, AssetType
#include "lang.h" // Para lang
#include "jail_audio.h" // Para JA_LoadMusic, JA_LoadSound #include "jail_audio.h" // Para JA_LoadMusic, JA_LoadSound
#include "screen.h" // Para Screen #include "screen.h" // Para Screen
#include "text.h" // Para Text
struct JA_Music_t; struct JA_Music_t;
struct JA_Sound_t; struct JA_Sound_t;
@@ -40,19 +42,10 @@ Resource::Resource()
loadAnimations(); loadAnimations();
loadDemoData(); loadDemoData();
addPalettes(); addPalettes();
createTextures();
std::cout << "\n** RESOURCES LOADED" << std::endl; 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 // Obtiene el sonido a partir de un nombre
JA_Sound_t *Resource::getSound(const std::string &name) JA_Sound_t *Resource::getSound(const std::string &name)
{ {
@@ -230,4 +223,50 @@ void Resource::addPalettes()
// Fuentes // Fuentes
getTexture("smb2.gif")->addPaletteFromFile(Asset::get()->get("smb2_palette1.pal")); 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 // Añade paletas a las texturas
void addPalettes(); void addPalettes();
// Crea texturas
void createTextures();
// [SINGLETON] Ahora el constructor y el destructor son privados, para no poder crear objetos resource desde fuera // [SINGLETON] Ahora el constructor y el destructor son privados, para no poder crear objetos resource desde fuera
// Constructor // Constructor
Resource(); Resource();
// Destructor // Destructor
~Resource(); ~Resource() = default;
public: public:
// [SINGLETON] Crearemos el objeto resource con esta función estática // [SINGLETON] Crearemos el objeto resource con esta función estática

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -50,6 +50,10 @@ public:
// Escribe el texto en pantalla // Escribe el texto en pantalla
void write(int x, int y, const std::string &text, int kerning = 1, int lenght = -1); 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 // Escribe el texto con colores
void writeColored(int x, int y, const std::string &text, Color color, int kerning = 1, int lenght = -1); 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 // Carga una imagen desde un fichero
bool Texture::loadFromFile(const std::string &file_path) bool Texture::loadFromFile(const std::string &file_path)
{ {
if (file_path.empty())
return false;
int req_format = STBI_rgb_alpha; int req_format = STBI_rgb_alpha;
int width, height, orig_format; int width, height, orig_format;
unsigned char *data = stbi_load(file_path.c_str(), &width, &height, &orig_format, req_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 // Asigna valores a otras variables
section::options = section::Options::TITLE_1; 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 // Destructor

View File

@@ -47,11 +47,11 @@ private:
std::unique_ptr<DefineButtons> define_buttons_; // Objeto para definir los botones del joystic std::unique_ptr<DefineButtons> define_buttons_; // Objeto para definir los botones del joystic
// Variable // Variable
int counter_ = 0; // Temporizador para la pantalla de titulo int counter_ = 0; // Temporizador para la pantalla de titulo
Uint32 ticks_ = 0; // Contador de ticks para ajustar la velocidad del programa 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 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 post_fade_ = 0; // Opción a realizar cuando termina el fundido
int num_controllers_; // Número de mandos conectados int num_controllers_; // Número de mandos conectados
// Actualiza las variables del objeto // Actualiza las variables del objeto
void update(); void update();