Compare commits
68 Commits
2025-08-21
...
c79a846b29
| Author | SHA1 | Date | |
|---|---|---|---|
| c79a846b29 | |||
| ad39d55e79 | |||
| 853ef426f0 | |||
| cadf7de3d8 | |||
| ec65ff9acb | |||
| d077374883 | |||
| 40a2b2cc00 | |||
| b3f3f151da | |||
| 3fdd61655a | |||
| 504727b95f | |||
| ff5446fcdf | |||
| 545eb70082 | |||
| 232a23a5dd | |||
| c9a29e26dd | |||
| 2977869ab5 | |||
| 6a223b68ba | |||
| 3fafff026b | |||
| 159528adc9 | |||
| 6c8f231b34 | |||
| c5d6d77ebf | |||
| 5e73327b2f | |||
| 720d286dcf | |||
| dd13a2bd7c | |||
| 1a6ef79466 | |||
| 8f83a1d13e | |||
| 9edfe6877f | |||
| 91b26631c6 | |||
| 331a690b78 | |||
| 5e3946e28b | |||
| d4a0189dc8 | |||
| 568b941990 | |||
| 49a3989ecf | |||
| af7cb01ead | |||
| 5c82916650 | |||
| 0c0518adac | |||
| cb7b290818 | |||
| ae30c9b34f | |||
| 9acd9aa631 | |||
| 577510ff8c | |||
| 66566913f6 | |||
| 3e6cc9dfab | |||
| a15e29344f | |||
| a96a17e11b | |||
| e0f6a424a9 | |||
| 49e30f947a | |||
| 470a07d28c | |||
| 65716fce20 | |||
| dfa66b0e95 | |||
| 3d9ffe356e | |||
| 19768cb72b | |||
| 26e0fd7247 | |||
| e2fd470ad3 | |||
| a72ae0a5fc | |||
| 7579594c22 | |||
| 6c702e7e23 | |||
| fb9c78eb49 | |||
| 62f65cbd5a | |||
| 057d3dcfee | |||
| c85336a4d0 | |||
| e4702e4e24 | |||
| 928335576c | |||
| fe950e6f17 | |||
| 6e81b6e60c | |||
| 74f6fe3501 | |||
| dfdb679054 | |||
| 26ed479306 | |||
| 32e9da55ef | |||
| 610083578e |
@@ -14,6 +14,8 @@ ContinuationIndentWidth: 4
|
|||||||
ConstructorInitializerIndentWidth: 4
|
ConstructorInitializerIndentWidth: 4
|
||||||
IndentWrappedFunctionNames: false
|
IndentWrappedFunctionNames: false
|
||||||
Cpp11BracedListStyle: true
|
Cpp11BracedListStyle: true
|
||||||
BreakConstructorInitializers: BeforeComma
|
BreakConstructorInitializers: BeforeColon
|
||||||
|
AllowAllConstructorInitializersOnNextLine: false
|
||||||
|
PackConstructorInitializers: Never
|
||||||
AllowAllArgumentsOnNextLine: false
|
AllowAllArgumentsOnNextLine: false
|
||||||
AllowAllParametersOfDeclarationOnNextLine: false
|
AllowAllParametersOfDeclarationOnNextLine: false
|
||||||
|
|||||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -1,4 +1,5 @@
|
|||||||
.vscode
|
.vscode
|
||||||
|
.claude
|
||||||
build/
|
build/
|
||||||
data/config/config.txt
|
data/config/config.txt
|
||||||
*.DS_Store
|
*.DS_Store
|
||||||
|
|||||||
@@ -52,6 +52,7 @@ SOUND|${PREFIX}/data/sound/notify.wav
|
|||||||
SOUND|${PREFIX}/data/sound/player_collision.wav
|
SOUND|${PREFIX}/data/sound/player_collision.wav
|
||||||
SOUND|${PREFIX}/data/sound/power_ball_explosion.wav
|
SOUND|${PREFIX}/data/sound/power_ball_explosion.wav
|
||||||
SOUND|${PREFIX}/data/sound/service_menu_adjust.wav
|
SOUND|${PREFIX}/data/sound/service_menu_adjust.wav
|
||||||
|
SOUND|${PREFIX}/data/sound/service_menu_back.wav
|
||||||
SOUND|${PREFIX}/data/sound/service_menu_move.wav
|
SOUND|${PREFIX}/data/sound/service_menu_move.wav
|
||||||
SOUND|${PREFIX}/data/sound/service_menu_select.wav
|
SOUND|${PREFIX}/data/sound/service_menu_select.wav
|
||||||
SOUND|${PREFIX}/data/sound/stage_change.wav
|
SOUND|${PREFIX}/data/sound/stage_change.wav
|
||||||
@@ -174,6 +175,7 @@ BITMAP|${PREFIX}/data/gfx/player/hit.png
|
|||||||
|
|
||||||
# Fuentes de texto
|
# Fuentes de texto
|
||||||
BITMAP|${PREFIX}/data/font/04b_25_2x.png
|
BITMAP|${PREFIX}/data/font/04b_25_2x.png
|
||||||
|
BITMAP|${PREFIX}/data/font/04b_25_2x_white.png
|
||||||
BITMAP|${PREFIX}/data/font/04b_25_flat_2x.png
|
BITMAP|${PREFIX}/data/font/04b_25_flat_2x.png
|
||||||
BITMAP|${PREFIX}/data/font/04b_25_flat.png
|
BITMAP|${PREFIX}/data/font/04b_25_flat.png
|
||||||
BITMAP|${PREFIX}/data/font/04b_25_grey.png
|
BITMAP|${PREFIX}/data/font/04b_25_grey.png
|
||||||
|
|||||||
@@ -8,270 +8,270 @@
|
|||||||
|
|
||||||
formation: 0
|
formation: 0
|
||||||
# Dos enemigos BALLOON3 uno a cada extremo
|
# Dos enemigos BALLOON3 uno a cada extremo
|
||||||
X3_0, 0, DEFAULT_POS_Y, RIGHT, BALLOON, EXTRALARGE, 0
|
X3_0, 0, DEFAULT_POS_Y, RIGHT, BALLOON, EXTRALARGE, 0.0000
|
||||||
X3_100, 0, DEFAULT_POS_Y, LEFT, BALLOON, EXTRALARGE, 0
|
X3_100, 0, DEFAULT_POS_Y, LEFT, BALLOON, EXTRALARGE, 0.0000
|
||||||
|
|
||||||
formation: 1
|
formation: 1
|
||||||
# Dos enemigos BALLOON3 uno a cada cuarto. Ambos van hacia el centro
|
# Dos enemigos BALLOON3 uno a cada cuarto. Ambos van hacia el centro
|
||||||
X3_25, 0, DEFAULT_POS_Y, RIGHT, BALLOON, EXTRALARGE, 0
|
X3_25, 0, DEFAULT_POS_Y, RIGHT, BALLOON, EXTRALARGE, 0.0000
|
||||||
X3_75, 0, DEFAULT_POS_Y, LEFT, BALLOON, EXTRALARGE, 0
|
X3_75, 0, DEFAULT_POS_Y, LEFT, BALLOON, EXTRALARGE, 0.0000
|
||||||
|
|
||||||
formation: 2
|
formation: 2
|
||||||
# Cuatro enemigos BALLOON1 uno detrás del otro. A la izquierda y hacia el centro
|
# Cuatro enemigos BALLOON1 uno detrás del otro. A la izquierda y hacia el centro
|
||||||
X1_0, 0, DEFAULT_POS_Y, RIGHT, BALLOON, MEDIUM, 30
|
X1_0, 0, DEFAULT_POS_Y, RIGHT, BALLOON, MEDIUM, 0.5000
|
||||||
X1_0, 1, DEFAULT_POS_Y, RIGHT, BALLOON, MEDIUM, 20
|
X1_0, 1, DEFAULT_POS_Y, RIGHT, BALLOON, MEDIUM, 0.3333
|
||||||
X1_0, 2, DEFAULT_POS_Y, RIGHT, BALLOON, MEDIUM, 10
|
X1_0, 2, DEFAULT_POS_Y, RIGHT, BALLOON, MEDIUM, 0.1667
|
||||||
X1_0, 3, DEFAULT_POS_Y, RIGHT, BALLOON, MEDIUM, 0
|
X1_0, 3, DEFAULT_POS_Y, RIGHT, BALLOON, MEDIUM, 0.0000
|
||||||
|
|
||||||
formation: 3
|
formation: 3
|
||||||
# Cuatro enemigos BALLOON1 uno detrás del otro. A la derecha y hacia el centro
|
# Cuatro enemigos BALLOON1 uno detrás del otro. A la derecha y hacia el centro
|
||||||
X1_100, 0, DEFAULT_POS_Y, LEFT, BALLOON, MEDIUM, 30
|
X1_100, 0, DEFAULT_POS_Y, LEFT, BALLOON, MEDIUM, 0.5000
|
||||||
X1_100, -1, DEFAULT_POS_Y, LEFT, BALLOON, MEDIUM, 20
|
X1_100, -1, DEFAULT_POS_Y, LEFT, BALLOON, MEDIUM, 0.3333
|
||||||
X1_100, -2, DEFAULT_POS_Y, LEFT, BALLOON, MEDIUM, 10
|
X1_100, -2, DEFAULT_POS_Y, LEFT, BALLOON, MEDIUM, 0.1667
|
||||||
X1_100, -3, DEFAULT_POS_Y, LEFT, BALLOON, MEDIUM, 0
|
X1_100, -3, DEFAULT_POS_Y, LEFT, BALLOON, MEDIUM, 0.0000
|
||||||
|
|
||||||
formation: 4
|
formation: 4
|
||||||
# Tres enemigos BALLOON2. 0, 25, 50. Hacia la derecha
|
# Tres enemigos BALLOON2. 0, 25, 50. Hacia la derecha
|
||||||
X2_0, 0, DEFAULT_POS_Y, RIGHT, BALLOON, LARGE, 20
|
X2_0, 0, DEFAULT_POS_Y, RIGHT, BALLOON, LARGE, 0.3333
|
||||||
X2_0, 2, DEFAULT_POS_Y, RIGHT, BALLOON, LARGE, 10
|
X2_0, 2, DEFAULT_POS_Y, RIGHT, BALLOON, LARGE, 0.1667
|
||||||
X2_0, 4, DEFAULT_POS_Y, RIGHT, BALLOON, LARGE, 0
|
X2_0, 4, DEFAULT_POS_Y, RIGHT, BALLOON, LARGE, 0.0000
|
||||||
|
|
||||||
formation: 5
|
formation: 5
|
||||||
# Tres enemigos BALLOON2. 50, 75, 100. Hacia la izquierda
|
# Tres enemigos BALLOON2. 50, 75, 100. Hacia la izquierda
|
||||||
X2_100, 0, DEFAULT_POS_Y, LEFT, BALLOON, LARGE, 20
|
X2_100, 0, DEFAULT_POS_Y, LEFT, BALLOON, LARGE, 0.3333
|
||||||
X2_100, -2, DEFAULT_POS_Y, LEFT, BALLOON, LARGE, 10
|
X2_100, -2, DEFAULT_POS_Y, LEFT, BALLOON, LARGE, 0.1667
|
||||||
X2_100, -4, DEFAULT_POS_Y, LEFT, BALLOON, LARGE, 0
|
X2_100, -4, DEFAULT_POS_Y, LEFT, BALLOON, LARGE, 0.0000
|
||||||
|
|
||||||
formation: 6
|
formation: 6
|
||||||
# Tres enemigos BALLOON2. 0, 0, 0. Hacia la derecha
|
# Tres enemigos BALLOON2. 0, 0, 0. Hacia la derecha
|
||||||
X2_0, 0, DEFAULT_POS_Y, RIGHT, BALLOON, LARGE, 20
|
X2_0, 0, DEFAULT_POS_Y, RIGHT, BALLOON, LARGE, 0.3333
|
||||||
X2_0, 1, DEFAULT_POS_Y, RIGHT, BALLOON, LARGE, 10
|
X2_0, 1, DEFAULT_POS_Y, RIGHT, BALLOON, LARGE, 0.1667
|
||||||
X2_0, 2, DEFAULT_POS_Y, RIGHT, BALLOON, LARGE, 0
|
X2_0, 2, DEFAULT_POS_Y, RIGHT, BALLOON, LARGE, 0.0000
|
||||||
|
|
||||||
formation: 7
|
formation: 7
|
||||||
# Tres enemigos BALLOON2. 100, 100, 100. Hacia la izquierda
|
# Tres enemigos BALLOON2. 100, 100, 100. Hacia la izquierda
|
||||||
X2_100, 0, DEFAULT_POS_Y, LEFT, BALLOON, LARGE, 20
|
X2_100, 0, DEFAULT_POS_Y, LEFT, BALLOON, LARGE, 0.3333
|
||||||
X2_100, -1, DEFAULT_POS_Y, LEFT, BALLOON, LARGE, 10
|
X2_100, -1, DEFAULT_POS_Y, LEFT, BALLOON, LARGE, 0.1667
|
||||||
X2_100, -2, DEFAULT_POS_Y, LEFT, BALLOON, LARGE, 0
|
X2_100, -2, DEFAULT_POS_Y, LEFT, BALLOON, LARGE, 0.0000
|
||||||
|
|
||||||
formation: 8
|
formation: 8
|
||||||
# Seis enemigos BALLOON0. 0, 0, 0, 0, 0, 0. Hacia la derecha
|
# Seis enemigos BALLOON0. 0, 0, 0, 0, 0, 0. Hacia la derecha
|
||||||
X0_0, 0, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 50
|
X0_0, 0, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 0.8333
|
||||||
X0_0, 1, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 40
|
X0_0, 1, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 0.6667
|
||||||
X0_0, 2, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 30
|
X0_0, 2, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 0.5000
|
||||||
X0_0, 3, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 20
|
X0_0, 3, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 0.3333
|
||||||
X0_0, 4, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 10
|
X0_0, 4, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 0.1667
|
||||||
X0_0, 5, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 0
|
X0_0, 5, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 0.0000
|
||||||
|
|
||||||
formation: 9
|
formation: 9
|
||||||
# Seis enemigos BALLOON0. 100, 100, 100, 100, 100, 100. Hacia la izquierda
|
# Seis enemigos BALLOON0. 100, 100, 100, 100, 100, 100. Hacia la izquierda
|
||||||
X0_100, 0, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 50
|
X0_100, 0, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 0.8333
|
||||||
X0_100, -1, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 40
|
X0_100, -1, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 0.6667
|
||||||
X0_100, -2, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 30
|
X0_100, -2, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 0.5000
|
||||||
X0_100, -3, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 20
|
X0_100, -3, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 0.3333
|
||||||
X0_100, -4, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 10
|
X0_100, -4, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 0.1667
|
||||||
X0_100, -5, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 0
|
X0_100, -5, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 0.0000
|
||||||
|
|
||||||
formation: 10
|
formation: 10
|
||||||
# Tres enemigos BALLOON3 seguidos desde la izquierda. Hacia la derecha
|
# Tres enemigos BALLOON3 seguidos desde la izquierda. Hacia la derecha
|
||||||
X3_0, 0, DEFAULT_POS_Y, RIGHT, BALLOON, EXTRALARGE, 30
|
X3_0, 0, DEFAULT_POS_Y, RIGHT, BALLOON, EXTRALARGE, 0.5000
|
||||||
X3_0, 1, DEFAULT_POS_Y, RIGHT, BALLOON, EXTRALARGE, 15
|
X3_0, 1, DEFAULT_POS_Y, RIGHT, BALLOON, EXTRALARGE, 0.2500
|
||||||
X3_0, 2, DEFAULT_POS_Y, RIGHT, BALLOON, EXTRALARGE, 0
|
X3_0, 2, DEFAULT_POS_Y, RIGHT, BALLOON, EXTRALARGE, 0.0000
|
||||||
|
|
||||||
formation: 11
|
formation: 11
|
||||||
# Tres enemigos BALLOON3 seguidos desde la derecha. Hacia la izquierda
|
# Tres enemigos BALLOON3 seguidos desde la derecha. Hacia la izquierda
|
||||||
X3_100, 0, DEFAULT_POS_Y, LEFT, BALLOON, EXTRALARGE, 30
|
X3_100, 0, DEFAULT_POS_Y, LEFT, BALLOON, EXTRALARGE, 0.5000
|
||||||
X3_100, -1, DEFAULT_POS_Y, LEFT, BALLOON, EXTRALARGE, 15
|
X3_100, -1, DEFAULT_POS_Y, LEFT, BALLOON, EXTRALARGE, 0.2500
|
||||||
X3_100, -2, DEFAULT_POS_Y, LEFT, BALLOON, EXTRALARGE, 0
|
X3_100, -2, DEFAULT_POS_Y, LEFT, BALLOON, EXTRALARGE, 0.0000
|
||||||
|
|
||||||
formation: 12
|
formation: 12
|
||||||
# Seis enemigos BALLOON1 uno detrás del otro. A la izquierda y hacia el centro
|
# Seis enemigos BALLOON1 uno detrás del otro. A la izquierda y hacia el centro
|
||||||
X1_0, 0, DEFAULT_POS_Y, RIGHT, BALLOON, MEDIUM, 50
|
X1_0, 0, DEFAULT_POS_Y, RIGHT, BALLOON, MEDIUM, 0.8333
|
||||||
X1_0, 1, DEFAULT_POS_Y, RIGHT, BALLOON, MEDIUM, 40
|
X1_0, 1, DEFAULT_POS_Y, RIGHT, BALLOON, MEDIUM, 0.6667
|
||||||
X1_0, 2, DEFAULT_POS_Y, RIGHT, BALLOON, MEDIUM, 30
|
X1_0, 2, DEFAULT_POS_Y, RIGHT, BALLOON, MEDIUM, 0.5000
|
||||||
X1_0, 3, DEFAULT_POS_Y, RIGHT, BALLOON, MEDIUM, 20
|
X1_0, 3, DEFAULT_POS_Y, RIGHT, BALLOON, MEDIUM, 0.3333
|
||||||
X1_0, 4, DEFAULT_POS_Y, RIGHT, BALLOON, MEDIUM, 10
|
X1_0, 4, DEFAULT_POS_Y, RIGHT, BALLOON, MEDIUM, 0.1667
|
||||||
X1_0, 5, DEFAULT_POS_Y, RIGHT, BALLOON, MEDIUM, 0
|
X1_0, 5, DEFAULT_POS_Y, RIGHT, BALLOON, MEDIUM, 0.0000
|
||||||
|
|
||||||
formation: 13
|
formation: 13
|
||||||
# Seis enemigos BALLOON1 uno detrás del otro. A la derecha y hacia el centro
|
# Seis enemigos BALLOON1 uno detrás del otro. A la derecha y hacia el centro
|
||||||
X1_100, 0, DEFAULT_POS_Y, LEFT, BALLOON, MEDIUM, 50
|
X1_100, 0, DEFAULT_POS_Y, LEFT, BALLOON, MEDIUM, 0.8333
|
||||||
X1_100, -1, DEFAULT_POS_Y, LEFT, BALLOON, MEDIUM, 40
|
X1_100, -1, DEFAULT_POS_Y, LEFT, BALLOON, MEDIUM, 0.6667
|
||||||
X1_100, -2, DEFAULT_POS_Y, LEFT, BALLOON, MEDIUM, 30
|
X1_100, -2, DEFAULT_POS_Y, LEFT, BALLOON, MEDIUM, 0.5000
|
||||||
X1_100, -3, DEFAULT_POS_Y, LEFT, BALLOON, MEDIUM, 20
|
X1_100, -3, DEFAULT_POS_Y, LEFT, BALLOON, MEDIUM, 0.3333
|
||||||
X1_100, -4, DEFAULT_POS_Y, LEFT, BALLOON, MEDIUM, 10
|
X1_100, -4, DEFAULT_POS_Y, LEFT, BALLOON, MEDIUM, 0.1667
|
||||||
X1_100, -5, DEFAULT_POS_Y, LEFT, BALLOON, MEDIUM, 0
|
X1_100, -5, DEFAULT_POS_Y, LEFT, BALLOON, MEDIUM, 0.0000
|
||||||
|
|
||||||
formation: 14
|
formation: 14
|
||||||
# Cinco enemigos BALLOON2. Hacia la derecha. Separados
|
# Cinco enemigos BALLOON2. Hacia la derecha. Separados
|
||||||
X2_0, 0, DEFAULT_POS_Y, RIGHT, BALLOON, LARGE, 40
|
X2_0, 0, DEFAULT_POS_Y, RIGHT, BALLOON, LARGE, 0.6667
|
||||||
X2_0, 2, DEFAULT_POS_Y, RIGHT, BALLOON, LARGE, 30
|
X2_0, 2, DEFAULT_POS_Y, RIGHT, BALLOON, LARGE, 0.5000
|
||||||
X2_0, 4, DEFAULT_POS_Y, RIGHT, BALLOON, LARGE, 20
|
X2_0, 4, DEFAULT_POS_Y, RIGHT, BALLOON, LARGE, 0.3333
|
||||||
X2_0, 6, DEFAULT_POS_Y, RIGHT, BALLOON, LARGE, 10
|
X2_0, 6, DEFAULT_POS_Y, RIGHT, BALLOON, LARGE, 0.1667
|
||||||
X2_0, 8, DEFAULT_POS_Y, RIGHT, BALLOON, LARGE, 0
|
X2_0, 8, DEFAULT_POS_Y, RIGHT, BALLOON, LARGE, 0.0000
|
||||||
|
|
||||||
formation: 15
|
formation: 15
|
||||||
# Cinco enemigos BALLOON2. Hacia la izquierda. Separados
|
# Cinco enemigos BALLOON2. Hacia la izquierda. Separados
|
||||||
X2_100, 0, DEFAULT_POS_Y, LEFT, BALLOON, LARGE, 40
|
X2_100, 0, DEFAULT_POS_Y, LEFT, BALLOON, LARGE, 0.6667
|
||||||
X2_100, -2, DEFAULT_POS_Y, LEFT, BALLOON, LARGE, 30
|
X2_100, -2, DEFAULT_POS_Y, LEFT, BALLOON, LARGE, 0.5000
|
||||||
X2_100, -4, DEFAULT_POS_Y, LEFT, BALLOON, LARGE, 20
|
X2_100, -4, DEFAULT_POS_Y, LEFT, BALLOON, LARGE, 0.3333
|
||||||
X2_100, -6, DEFAULT_POS_Y, LEFT, BALLOON, LARGE, 10
|
X2_100, -6, DEFAULT_POS_Y, LEFT, BALLOON, LARGE, 0.1667
|
||||||
X2_100, -8, DEFAULT_POS_Y, LEFT, BALLOON, LARGE, 0
|
X2_100, -8, DEFAULT_POS_Y, LEFT, BALLOON, LARGE, 0.0000
|
||||||
|
|
||||||
formation: 16
|
formation: 16
|
||||||
# Cinco enemigos BALLOON2. Hacia la derecha. Juntos
|
# Cinco enemigos BALLOON2. Hacia la derecha. Juntos
|
||||||
X2_0, 0, DEFAULT_POS_Y, RIGHT, BALLOON, LARGE, 40
|
X2_0, 0, DEFAULT_POS_Y, RIGHT, BALLOON, LARGE, 0.6667
|
||||||
X2_0, 1, DEFAULT_POS_Y, RIGHT, BALLOON, LARGE, 30
|
X2_0, 1, DEFAULT_POS_Y, RIGHT, BALLOON, LARGE, 0.5000
|
||||||
X2_0, 2, DEFAULT_POS_Y, RIGHT, BALLOON, LARGE, 20
|
X2_0, 2, DEFAULT_POS_Y, RIGHT, BALLOON, LARGE, 0.3333
|
||||||
X2_0, 3, DEFAULT_POS_Y, RIGHT, BALLOON, LARGE, 10
|
X2_0, 3, DEFAULT_POS_Y, RIGHT, BALLOON, LARGE, 0.1667
|
||||||
X2_0, 4, DEFAULT_POS_Y, RIGHT, BALLOON, LARGE, 0
|
X2_0, 4, DEFAULT_POS_Y, RIGHT, BALLOON, LARGE, 0.0000
|
||||||
|
|
||||||
formation: 17
|
formation: 17
|
||||||
# Cinco enemigos BALLOON2. Hacia la izquierda. Juntos
|
# Cinco enemigos BALLOON2. Hacia la izquierda. Juntos
|
||||||
X2_100, 0, DEFAULT_POS_Y, LEFT, BALLOON, LARGE, 40
|
X2_100, 0, DEFAULT_POS_Y, LEFT, BALLOON, LARGE, 0.6667
|
||||||
X2_100, -1, DEFAULT_POS_Y, LEFT, BALLOON, LARGE, 30
|
X2_100, -1, DEFAULT_POS_Y, LEFT, BALLOON, LARGE, 0.5000
|
||||||
X2_100, -2, DEFAULT_POS_Y, LEFT, BALLOON, LARGE, 20
|
X2_100, -2, DEFAULT_POS_Y, LEFT, BALLOON, LARGE, 0.3333
|
||||||
X2_100, -3, DEFAULT_POS_Y, LEFT, BALLOON, LARGE, 10
|
X2_100, -3, DEFAULT_POS_Y, LEFT, BALLOON, LARGE, 0.1667
|
||||||
X2_100, -4, DEFAULT_POS_Y, LEFT, BALLOON, LARGE, 0
|
X2_100, -4, DEFAULT_POS_Y, LEFT, BALLOON, LARGE, 0.0000
|
||||||
|
|
||||||
formation: 18
|
formation: 18
|
||||||
# Doce enemigos BALLOON0. Hacia la derecha. Juntos
|
# Doce enemigos BALLOON0. Hacia la derecha. Juntos
|
||||||
X0_0, 0, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 110
|
X0_0, 0, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 1.8333
|
||||||
X0_0, 1, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 100
|
X0_0, 1, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 1.6667
|
||||||
X0_0, 2, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 90
|
X0_0, 2, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 1.5000
|
||||||
X0_0, 3, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 80
|
X0_0, 3, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 1.3333
|
||||||
X0_0, 4, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 70
|
X0_0, 4, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 1.1667
|
||||||
X0_0, 5, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 60
|
X0_0, 5, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 1.0000
|
||||||
X0_0, 6, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 50
|
X0_0, 6, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 0.8333
|
||||||
X0_0, 7, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 40
|
X0_0, 7, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 0.6667
|
||||||
X0_0, 8, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 30
|
X0_0, 8, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 0.5000
|
||||||
X0_0, 9, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 20
|
X0_0, 9, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 0.3333
|
||||||
X0_0, 10, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 10
|
X0_0, 10, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 0.1667
|
||||||
X0_0, 11, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 0
|
X0_0, 11, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 0.0000
|
||||||
|
|
||||||
formation: 19
|
formation: 19
|
||||||
# Doce enemigos BALLOON0. Hacia la izquierda. Juntos
|
# Doce enemigos BALLOON0. Hacia la izquierda. Juntos
|
||||||
X0_100, 0, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 110
|
X0_100, 0, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 1.8333
|
||||||
X0_100, -1, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 100
|
X0_100, -1, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 1.6667
|
||||||
X0_100, -2, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 90
|
X0_100, -2, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 1.5000
|
||||||
X0_100, -3, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 80
|
X0_100, -3, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 1.3333
|
||||||
X0_100, -4, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 70
|
X0_100, -4, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 1.1667
|
||||||
X0_100, -5, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 60
|
X0_100, -5, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 1.0000
|
||||||
X0_100, -6, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 50
|
X0_100, -6, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 0.8333
|
||||||
X0_100, -7, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 40
|
X0_100, -7, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 0.6667
|
||||||
X0_100, -8, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 30
|
X0_100, -8, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 0.5000
|
||||||
X0_100, -9, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 20
|
X0_100, -9, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 0.3333
|
||||||
X0_100, -10, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 10
|
X0_100, -10, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 0.1667
|
||||||
X0_100, -11, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 0
|
X0_100, -11, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 0.0000
|
||||||
|
|
||||||
formation: 20
|
formation: 20
|
||||||
# Cuatro enemigos BALLOON3 seguidos desde la izquierda/derecha. Simétricos
|
# Cuatro enemigos BALLOON3 seguidos desde la izquierda/derecha. Simétricos
|
||||||
X3_0, 0, DEFAULT_POS_Y, RIGHT, BALLOON, EXTRALARGE, 0
|
X3_0, 0, DEFAULT_POS_Y, RIGHT, BALLOON, EXTRALARGE, 0.0000
|
||||||
X3_0, 1, DEFAULT_POS_Y, RIGHT, BALLOON, EXTRALARGE, 0
|
X3_0, 1, DEFAULT_POS_Y, RIGHT, BALLOON, EXTRALARGE, 0.0000
|
||||||
X3_100, 0, DEFAULT_POS_Y, LEFT, BALLOON, EXTRALARGE, 0
|
X3_100, 0, DEFAULT_POS_Y, LEFT, BALLOON, EXTRALARGE, 0.0000
|
||||||
X3_100, -1, DEFAULT_POS_Y, LEFT, BALLOON, EXTRALARGE, 0
|
X3_100, -1, DEFAULT_POS_Y, LEFT, BALLOON, EXTRALARGE, 0.0000
|
||||||
|
|
||||||
formation: 21
|
formation: 21
|
||||||
# Diez enemigos BALLOON1 uno detrás del otro. Izquierda/derecha. Simétricos
|
# Diez enemigos BALLOON1 uno detrás del otro. Izquierda/derecha. Simétricos
|
||||||
X1_0, 0, DEFAULT_POS_Y, RIGHT, BALLOON, MEDIUM, 12
|
X1_0, 0, DEFAULT_POS_Y, RIGHT, BALLOON, MEDIUM, 0.2000
|
||||||
X1_0, 1, DEFAULT_POS_Y, RIGHT, BALLOON, MEDIUM, 9
|
X1_0, 1, DEFAULT_POS_Y, RIGHT, BALLOON, MEDIUM, 0.1500
|
||||||
X1_0, 2, DEFAULT_POS_Y, RIGHT, BALLOON, MEDIUM, 6
|
X1_0, 2, DEFAULT_POS_Y, RIGHT, BALLOON, MEDIUM, 0.1000
|
||||||
X1_0, 3, DEFAULT_POS_Y, RIGHT, BALLOON, MEDIUM, 3
|
X1_0, 3, DEFAULT_POS_Y, RIGHT, BALLOON, MEDIUM, 0.0500
|
||||||
X1_0, 4, DEFAULT_POS_Y, RIGHT, BALLOON, MEDIUM, 0
|
X1_0, 4, DEFAULT_POS_Y, RIGHT, BALLOON, MEDIUM, 0.0000
|
||||||
X1_100, 0, DEFAULT_POS_Y, LEFT, BALLOON, MEDIUM, 12
|
X1_100, 0, DEFAULT_POS_Y, LEFT, BALLOON, MEDIUM, 0.2000
|
||||||
X1_100, -1, DEFAULT_POS_Y, LEFT, BALLOON, MEDIUM, 9
|
X1_100, -1, DEFAULT_POS_Y, LEFT, BALLOON, MEDIUM, 0.1500
|
||||||
X1_100, -2, DEFAULT_POS_Y, LEFT, BALLOON, MEDIUM, 6
|
X1_100, -2, DEFAULT_POS_Y, LEFT, BALLOON, MEDIUM, 0.1000
|
||||||
X1_100, -3, DEFAULT_POS_Y, LEFT, BALLOON, MEDIUM, 3
|
X1_100, -3, DEFAULT_POS_Y, LEFT, BALLOON, MEDIUM, 0.0500
|
||||||
X1_100, -4, DEFAULT_POS_Y, LEFT, BALLOON, MEDIUM, 0
|
X1_100, -4, DEFAULT_POS_Y, LEFT, BALLOON, MEDIUM, 0.0000
|
||||||
|
|
||||||
formation: 22
|
formation: 22
|
||||||
# Diez enemigos BALLOON2. Hacia la derecha/izquierda. Separados. Simétricos
|
# Diez enemigos BALLOON2. Hacia la derecha/izquierda. Separados. Simétricos
|
||||||
X2_0, 0, DEFAULT_POS_Y, RIGHT, BALLOON, LARGE, 40
|
X2_0, 0, DEFAULT_POS_Y, RIGHT, BALLOON, LARGE, 0.6667
|
||||||
X2_0, 2, DEFAULT_POS_Y, RIGHT, BALLOON, LARGE, 30
|
X2_0, 2, DEFAULT_POS_Y, RIGHT, BALLOON, LARGE, 0.5000
|
||||||
X2_0, 4, DEFAULT_POS_Y, RIGHT, BALLOON, LARGE, 20
|
X2_0, 4, DEFAULT_POS_Y, RIGHT, BALLOON, LARGE, 0.3333
|
||||||
X2_0, 6, DEFAULT_POS_Y, RIGHT, BALLOON, LARGE, 10
|
X2_0, 6, DEFAULT_POS_Y, RIGHT, BALLOON, LARGE, 0.1667
|
||||||
X2_0, 8, DEFAULT_POS_Y, RIGHT, BALLOON, LARGE, 0
|
X2_0, 8, DEFAULT_POS_Y, RIGHT, BALLOON, LARGE, 0.0000
|
||||||
X2_100, 0, DEFAULT_POS_Y, LEFT, BALLOON, LARGE, 40
|
X2_100, 0, DEFAULT_POS_Y, LEFT, BALLOON, LARGE, 0.6667
|
||||||
X2_100, -2, DEFAULT_POS_Y, LEFT, BALLOON, LARGE, 30
|
X2_100, -2, DEFAULT_POS_Y, LEFT, BALLOON, LARGE, 0.5000
|
||||||
X2_100, -4, DEFAULT_POS_Y, LEFT, BALLOON, LARGE, 20
|
X2_100, -4, DEFAULT_POS_Y, LEFT, BALLOON, LARGE, 0.3333
|
||||||
X2_100, -6, DEFAULT_POS_Y, LEFT, BALLOON, LARGE, 10
|
X2_100, -6, DEFAULT_POS_Y, LEFT, BALLOON, LARGE, 0.1667
|
||||||
X2_100, -8, DEFAULT_POS_Y, LEFT, BALLOON, LARGE, 0
|
X2_100, -8, DEFAULT_POS_Y, LEFT, BALLOON, LARGE, 0.0000
|
||||||
|
|
||||||
formation: 23
|
formation: 23
|
||||||
# Diez enemigos BALLOON2. Hacia la derecha. Juntos. Simétricos
|
# Diez enemigos BALLOON2. Hacia la derecha. Juntos. Simétricos
|
||||||
X2_0, 0, DEFAULT_POS_Y, RIGHT, BALLOON, LARGE, 40
|
X2_0, 0, DEFAULT_POS_Y, RIGHT, BALLOON, LARGE, 0.6667
|
||||||
X2_0, 1, DEFAULT_POS_Y, RIGHT, BALLOON, LARGE, 30
|
X2_0, 1, DEFAULT_POS_Y, RIGHT, BALLOON, LARGE, 0.5000
|
||||||
X2_0, 2, DEFAULT_POS_Y, RIGHT, BALLOON, LARGE, 20
|
X2_0, 2, DEFAULT_POS_Y, RIGHT, BALLOON, LARGE, 0.3333
|
||||||
X2_0, 3, DEFAULT_POS_Y, RIGHT, BALLOON, LARGE, 10
|
X2_0, 3, DEFAULT_POS_Y, RIGHT, BALLOON, LARGE, 0.1667
|
||||||
X2_0, 4, DEFAULT_POS_Y, RIGHT, BALLOON, LARGE, 0
|
X2_0, 4, DEFAULT_POS_Y, RIGHT, BALLOON, LARGE, 0.0000
|
||||||
X2_100, 0, DEFAULT_POS_Y, LEFT, BALLOON, LARGE, 40
|
X2_100, 0, DEFAULT_POS_Y, LEFT, BALLOON, LARGE, 0.6667
|
||||||
X2_100, -1, DEFAULT_POS_Y, LEFT, BALLOON, LARGE, 30
|
X2_100, -1, DEFAULT_POS_Y, LEFT, BALLOON, LARGE, 0.5000
|
||||||
X2_100, -2, DEFAULT_POS_Y, LEFT, BALLOON, LARGE, 20
|
X2_100, -2, DEFAULT_POS_Y, LEFT, BALLOON, LARGE, 0.3333
|
||||||
X2_100, -3, DEFAULT_POS_Y, LEFT, BALLOON, LARGE, 10
|
X2_100, -3, DEFAULT_POS_Y, LEFT, BALLOON, LARGE, 0.1667
|
||||||
X2_100, -4, DEFAULT_POS_Y, LEFT, BALLOON, LARGE, 0
|
X2_100, -4, DEFAULT_POS_Y, LEFT, BALLOON, LARGE, 0.0000
|
||||||
|
|
||||||
formation: 24
|
formation: 24
|
||||||
# Treinta enemigos BALLOON0. Del centro hacia los extremos. Juntos. Simétricos
|
# Treinta enemigos BALLOON0. Del centro hacia los extremos. Juntos. Simétricos
|
||||||
X0_50, 0, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 0
|
X0_50, 0, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 0.0000
|
||||||
X0_50, 0, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 5
|
X0_50, 0, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 0.0833
|
||||||
X0_50, 0, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 10
|
X0_50, 0, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 0.1667
|
||||||
X0_50, 0, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 15
|
X0_50, 0, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 0.2500
|
||||||
X0_50, 0, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 20
|
X0_50, 0, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 0.3333
|
||||||
X0_50, 0, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 25
|
X0_50, 0, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 0.4167
|
||||||
X0_50, 0, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 30
|
X0_50, 0, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 0.5000
|
||||||
X0_50, 0, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 35
|
X0_50, 0, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 0.5833
|
||||||
X0_50, 0, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 40
|
X0_50, 0, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 0.6667
|
||||||
X0_50, 0, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 45
|
X0_50, 0, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 0.7500
|
||||||
X0_50, 0, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 50
|
X0_50, 0, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 0.8333
|
||||||
X0_50, 0, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 55
|
X0_50, 0, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 0.9167
|
||||||
X0_50, 0, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 60
|
X0_50, 0, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 1.0000
|
||||||
X0_50, 0, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 65
|
X0_50, 0, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 1.0833
|
||||||
X0_50, 0, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 70
|
X0_50, 0, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 1.1667
|
||||||
X0_50, 0, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 0
|
X0_50, 0, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 0.0000
|
||||||
X0_50, 0, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 5
|
X0_50, 0, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 0.0833
|
||||||
X0_50, 0, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 10
|
X0_50, 0, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 0.1667
|
||||||
X0_50, 0, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 15
|
X0_50, 0, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 0.2500
|
||||||
X0_50, 0, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 20
|
X0_50, 0, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 0.3333
|
||||||
X0_50, 0, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 25
|
X0_50, 0, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 0.4167
|
||||||
X0_50, 0, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 30
|
X0_50, 0, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 0.5000
|
||||||
X0_50, 0, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 35
|
X0_50, 0, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 0.5833
|
||||||
X0_50, 0, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 40
|
X0_50, 0, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 0.6667
|
||||||
X0_50, 0, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 45
|
X0_50, 0, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 0.7500
|
||||||
X0_50, 0, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 50
|
X0_50, 0, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 0.8333
|
||||||
X0_50, 0, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 55
|
X0_50, 0, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 0.9167
|
||||||
X0_50, 0, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 60
|
X0_50, 0, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 1.0000
|
||||||
X0_50, 0, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 65
|
X0_50, 0, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 1.0833
|
||||||
X0_50, 0, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 70
|
X0_50, 0, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 1.1667
|
||||||
|
|
||||||
formation: 25
|
formation: 25
|
||||||
# Treinta enemigos BALLOON0. Del centro hacia adentro. Juntos. Simétricos
|
# Treinta enemigos BALLOON0. Del centro hacia adentro. Juntos. Simétricos
|
||||||
X0_50 + 20, 0, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 70
|
X0_50 + 20, 0, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 1.1667
|
||||||
X0_50 + 20, 0, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 65
|
X0_50 + 20, 0, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 1.0833
|
||||||
X0_50 + 20, 0, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 60
|
X0_50 + 20, 0, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 1.0000
|
||||||
X0_50 + 20, 0, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 55
|
X0_50 + 20, 0, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 0.9167
|
||||||
X0_50 + 20, 0, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 50
|
X0_50 + 20, 0, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 0.8333
|
||||||
X0_50 + 20, 0, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 45
|
X0_50 + 20, 0, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 0.7500
|
||||||
X0_50 + 20, 0, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 40
|
X0_50 + 20, 0, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 0.6667
|
||||||
X0_50 + 20, 0, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 35
|
X0_50 + 20, 0, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 0.5833
|
||||||
X0_50 + 20, 0, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 30
|
X0_50 + 20, 0, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 0.5000
|
||||||
X0_50 + 20, 0, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 25
|
X0_50 + 20, 0, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 0.4167
|
||||||
X0_50 + 20, 0, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 20
|
X0_50 + 20, 0, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 0.3333
|
||||||
X0_50 + 20, 0, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 15
|
X0_50 + 20, 0, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 0.2500
|
||||||
X0_50 + 20, 0, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 10
|
X0_50 + 20, 0, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 0.1667
|
||||||
X0_50 + 20, 0, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 5
|
X0_50 + 20, 0, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 0.0833
|
||||||
X0_50 + 20, 0, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 0
|
X0_50 + 20, 0, DEFAULT_POS_Y, LEFT, BALLOON, SMALL, 0.0000
|
||||||
X0_50 - 20, 0, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 70
|
X0_50 - 20, 0, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 1.1667
|
||||||
X0_50 - 20, 0, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 65
|
X0_50 - 20, 0, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 1.0833
|
||||||
X0_50 - 20, 0, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 60
|
X0_50 - 20, 0, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 1.0000
|
||||||
X0_50 - 20, 0, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 55
|
X0_50 - 20, 0, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 0.9167
|
||||||
X0_50 - 20, 0, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 50
|
X0_50 - 20, 0, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 0.8333
|
||||||
X0_50 - 20, 0, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 45
|
X0_50 - 20, 0, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 0.7500
|
||||||
X0_50 - 20, 0, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 40
|
X0_50 - 20, 0, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 0.6667
|
||||||
X0_50 - 20, 0, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 35
|
X0_50 - 20, 0, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 0.5833
|
||||||
X0_50 - 20, 0, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 30
|
X0_50 - 20, 0, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 0.5000
|
||||||
X0_50 - 20, 0, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 25
|
X0_50 - 20, 0, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 0.4167
|
||||||
X0_50 - 20, 0, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 20
|
X0_50 - 20, 0, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 0.3333
|
||||||
X0_50 - 20, 0, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 15
|
X0_50 - 20, 0, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 0.2500
|
||||||
X0_50 - 20, 0, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 10
|
X0_50 - 20, 0, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 0.1667
|
||||||
X0_50 - 20, 0, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 5
|
X0_50 - 20, 0, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 0.0833
|
||||||
X0_50 - 20, 0, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 0
|
X0_50 - 20, 0, DEFAULT_POS_Y, RIGHT, BALLOON, SMALL, 0.0000
|
||||||
@@ -39,24 +39,24 @@ scoreboard.text_color2 FFFFFF # Color secundario del texto del marca
|
|||||||
scoreboard.skip_countdown_value 8 # Valor para saltar la cuenta atrás (segundos)
|
scoreboard.skip_countdown_value 8 # Valor para saltar la cuenta atrás (segundos)
|
||||||
|
|
||||||
# --- TITLE ---
|
# --- TITLE ---
|
||||||
title.press_start_position 180 # Posición Y del texto "Press Start"
|
title.press_start_position 180 # Posición Y del texto "Press Start"
|
||||||
title.title_duration 800 # Duración de la pantalla de título (frames)
|
title.title_duration 14 # Duración de la pantalla de título (segundos)
|
||||||
title.arcade_edition_position 123 # Posición Y del subtítulo "Arcade Edition"
|
title.arcade_edition_position 123 # Posición Y del subtítulo "Arcade Edition"
|
||||||
title.title_c_c_position 80 # Posición Y del título principal
|
title.title_c_c_position 80 # Posición Y del título principal
|
||||||
title.bg_color 41526F # Color de fondo en la sección titulo
|
title.bg_color 41526F # Color de fondo en la sección titulo
|
||||||
|
|
||||||
# --- BACKGROUND ---
|
# --- BACKGROUND ---
|
||||||
background.attenuate_color FFFFFF00 # Color de atenuación del fondo (RGBA hexadecimal)
|
background.attenuate_color FFFFFF00 # Color de atenuación del fondo (RGBA hexadecimal)
|
||||||
|
|
||||||
# --- BALLOONS ---
|
# --- BALLOONS --- (deltaTime en segundos: vel en pixels/s, grav en pixels/s²)
|
||||||
balloon.settings[0].vel 2.75f # Velocidad inicial del globo 1
|
balloon.settings[0].vel 165.0f # Velocidad inicial del globo 1 (pixels/s)
|
||||||
balloon.settings[0].grav 0.09f # Gravedad aplicada al globo 1
|
balloon.settings[0].grav 320.0f # Gravedad aplicada al globo 1 (pixels/s²)
|
||||||
balloon.settings[1].vel 3.70f # Velocidad inicial del globo 2
|
balloon.settings[1].vel 222.0f # Velocidad inicial del globo 2 (pixels/s)
|
||||||
balloon.settings[1].grav 0.10f # Gravedad aplicada al globo 2
|
balloon.settings[1].grav 360.0f # Gravedad aplicada al globo 2 (pixels/s²)
|
||||||
balloon.settings[2].vel 4.70f # Velocidad inicial del globo 3
|
balloon.settings[2].vel 282.0f # Velocidad inicial del globo 3 (pixels/s)
|
||||||
balloon.settings[2].grav 0.10f # Gravedad aplicada al globo 3
|
balloon.settings[2].grav 360.0f # Gravedad aplicada al globo 3 (pixels/s²)
|
||||||
balloon.settings[3].vel 5.45f # Velocidad inicial del globo 4
|
balloon.settings[3].vel 327.0f # Velocidad inicial del globo 4 (pixels/s)
|
||||||
balloon.settings[3].grav 0.10f # Gravedad aplicada al globo 4
|
balloon.settings[3].grav 360.0f # Gravedad aplicada al globo 4 (pixels/s²)
|
||||||
|
|
||||||
balloon.color[0] blue # Color de creación del globo normal
|
balloon.color[0] blue # Color de creación del globo normal
|
||||||
balloon.color[1] orange # Color del globo normal
|
balloon.color[1] orange # Color del globo normal
|
||||||
|
|||||||
@@ -39,24 +39,24 @@ scoreboard.text_color2 FFFFFF # Color secundario del texto del marca
|
|||||||
scoreboard.skip_countdown_value 8 # Valor para saltar la cuenta atrás (segundos)
|
scoreboard.skip_countdown_value 8 # Valor para saltar la cuenta atrás (segundos)
|
||||||
|
|
||||||
# --- TITLE ---
|
# --- TITLE ---
|
||||||
title.press_start_position 180 # Posición Y del texto "Press Start"
|
title.press_start_position 180 # Posición Y del texto "Press Start"
|
||||||
title.title_duration 800 # Duración de la pantalla de título (frames)
|
title.title_duration 14 # Duración de la pantalla de título (segundos)
|
||||||
title.arcade_edition_position 123 # Posición Y del subtítulo "Arcade Edition"
|
title.arcade_edition_position 123 # Posición Y del subtítulo "Arcade Edition"
|
||||||
title.title_c_c_position 80 # Posición Y del título principal
|
title.title_c_c_position 80 # Posición Y del título principal
|
||||||
title.bg_color 41526F # Color de fondo en la sección titulo
|
title.bg_color 41526F # Color de fondo en la sección titulo
|
||||||
|
|
||||||
# --- BACKGROUND ---
|
# --- BACKGROUND ---
|
||||||
background.attenuate_color FFFFFF00 # Color de atenuación del fondo (RGBA hexadecimal)
|
background.attenuate_color FFFFFF00 # Color de atenuación del fondo (RGBA hexadecimal)
|
||||||
|
|
||||||
# --- BALLOONS ---
|
# --- BALLOONS --- (deltaTime en segundos: vel en pixels/s, grav en pixels/s²)
|
||||||
balloon.settings[0].vel 2.75f # Velocidad inicial del globo 1
|
balloon.settings[0].vel 165.0f # Velocidad inicial del globo 1 (pixels/s)
|
||||||
balloon.settings[0].grav 0.09f # Gravedad aplicada al globo 1
|
balloon.settings[0].grav 320.0f # Gravedad aplicada al globo 1 (pixels/s²)
|
||||||
balloon.settings[1].vel 3.70f # Velocidad inicial del globo 2
|
balloon.settings[1].vel 222.0f # Velocidad inicial del globo 2 (pixels/s)
|
||||||
balloon.settings[1].grav 0.10f # Gravedad aplicada al globo 2
|
balloon.settings[1].grav 360.0f # Gravedad aplicada al globo 2 (pixels/s²)
|
||||||
balloon.settings[2].vel 4.70f # Velocidad inicial del globo 3
|
balloon.settings[2].vel 282.0f # Velocidad inicial del globo 3 (pixels/s)
|
||||||
balloon.settings[2].grav 0.10f # Gravedad aplicada al globo 3
|
balloon.settings[2].grav 360.0f # Gravedad aplicada al globo 3 (pixels/s²)
|
||||||
balloon.settings[3].vel 5.45f # Velocidad inicial del globo 4
|
balloon.settings[3].vel 327.0f # Velocidad inicial del globo 4 (pixels/s)
|
||||||
balloon.settings[3].grav 0.10f # Gravedad aplicada al globo 4
|
balloon.settings[3].grav 360.0f # Gravedad aplicada al globo 4 (pixels/s²)
|
||||||
|
|
||||||
balloon.color[0] blue # Color de creación del globo normal
|
balloon.color[0] blue # Color de creación del globo normal
|
||||||
balloon.color[1] orange # Color del globo normal
|
balloon.color[1] orange # Color del globo normal
|
||||||
|
|||||||
BIN
data/font/04b_25_2x_white.png
Normal file
BIN
data/font/04b_25_2x_white.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 4.2 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 872 B After Width: | Height: | Size: 882 B |
@@ -3,28 +3,28 @@ frame_height=10
|
|||||||
|
|
||||||
[animation]
|
[animation]
|
||||||
name=orange
|
name=orange
|
||||||
speed=10
|
speed=0.1667
|
||||||
loop=0
|
loop=0
|
||||||
frames=0,1,2,3,4,5,6,7,8,9
|
frames=0,1,2,3,4,5,6,7,8,9
|
||||||
[/animation]
|
[/animation]
|
||||||
|
|
||||||
[animation]
|
[animation]
|
||||||
name=blue
|
name=blue
|
||||||
speed=20
|
speed=0.3333
|
||||||
loop=0
|
loop=0
|
||||||
frames=10,11,12,13,14,15,16,17,18,19
|
frames=10,11,12,13,14,15,16,17,18,19
|
||||||
[/animation]
|
[/animation]
|
||||||
|
|
||||||
[animation]
|
[animation]
|
||||||
name=green
|
name=green
|
||||||
speed=10
|
speed=0.1667
|
||||||
loop=0
|
loop=0
|
||||||
frames=20,21,22,23,24,25,26,27,28,29
|
frames=20,21,22,23,24,25,26,27,28,29
|
||||||
[/animation]
|
[/animation]
|
||||||
|
|
||||||
[animation]
|
[animation]
|
||||||
name=red
|
name=red
|
||||||
speed=20
|
speed=0.3333
|
||||||
loop=0
|
loop=0
|
||||||
frames=30,31,32,33,34,35,36,37,38,39
|
frames=30,31,32,33,34,35,36,37,38,39
|
||||||
[/animation]
|
[/animation]
|
||||||
@@ -3,28 +3,28 @@ frame_height=16
|
|||||||
|
|
||||||
[animation]
|
[animation]
|
||||||
name=orange
|
name=orange
|
||||||
speed=10
|
speed=0.1667
|
||||||
loop=0
|
loop=0
|
||||||
frames=0,1,2,3,4,5,6,7,8,9
|
frames=0,1,2,3,4,5,6,7,8,9
|
||||||
[/animation]
|
[/animation]
|
||||||
|
|
||||||
[animation]
|
[animation]
|
||||||
name=blue
|
name=blue
|
||||||
speed=20
|
speed=0.3333
|
||||||
loop=0
|
loop=0
|
||||||
frames=10,11,12,13,14,15,16,17,18,19
|
frames=10,11,12,13,14,15,16,17,18,19
|
||||||
[/animation]
|
[/animation]
|
||||||
|
|
||||||
[animation]
|
[animation]
|
||||||
name=green
|
name=green
|
||||||
speed=10
|
speed=0.1667
|
||||||
loop=0
|
loop=0
|
||||||
frames=20,21,22,23,24,25,26,27,28,29
|
frames=20,21,22,23,24,25,26,27,28,29
|
||||||
[/animation]
|
[/animation]
|
||||||
|
|
||||||
[animation]
|
[animation]
|
||||||
name=red
|
name=red
|
||||||
speed=20
|
speed=0.3333
|
||||||
loop=0
|
loop=0
|
||||||
frames=30,31,32,33,34,35,36,37,38,39
|
frames=30,31,32,33,34,35,36,37,38,39
|
||||||
[/animation]
|
[/animation]
|
||||||
@@ -3,28 +3,28 @@ frame_height=26
|
|||||||
|
|
||||||
[animation]
|
[animation]
|
||||||
name=orange
|
name=orange
|
||||||
speed=10
|
speed=0.1667
|
||||||
loop=0
|
loop=0
|
||||||
frames=0,1,2,3,4,5,6,7,8,9
|
frames=0,1,2,3,4,5,6,7,8,9
|
||||||
[/animation]
|
[/animation]
|
||||||
|
|
||||||
[animation]
|
[animation]
|
||||||
name=blue
|
name=blue
|
||||||
speed=20
|
speed=0.3333
|
||||||
loop=0
|
loop=0
|
||||||
frames=10,11,12,13,14,15,16,17,18,19
|
frames=10,11,12,13,14,15,16,17,18,19
|
||||||
[/animation]
|
[/animation]
|
||||||
|
|
||||||
[animation]
|
[animation]
|
||||||
name=green
|
name=green
|
||||||
speed=10
|
speed=0.1667
|
||||||
loop=0
|
loop=0
|
||||||
frames=20,21,22,23,24,25,26,27,28,29
|
frames=20,21,22,23,24,25,26,27,28,29
|
||||||
[/animation]
|
[/animation]
|
||||||
|
|
||||||
[animation]
|
[animation]
|
||||||
name=red
|
name=red
|
||||||
speed=20
|
speed=0.3333
|
||||||
loop=0
|
loop=0
|
||||||
frames=30,31,32,33,34,35,36,37,38,39
|
frames=30,31,32,33,34,35,36,37,38,39
|
||||||
[/animation]
|
[/animation]
|
||||||
@@ -3,28 +3,28 @@ frame_height=48
|
|||||||
|
|
||||||
[animation]
|
[animation]
|
||||||
name=orange
|
name=orange
|
||||||
speed=10
|
speed=0.1667
|
||||||
loop=0
|
loop=0
|
||||||
frames=0,1,2,3,4,5,6,7,8,9
|
frames=0,1,2,3,4,5,6,7,8,9
|
||||||
[/animation]
|
[/animation]
|
||||||
|
|
||||||
[animation]
|
[animation]
|
||||||
name=blue
|
name=blue
|
||||||
speed=20
|
speed=0.3333
|
||||||
loop=0
|
loop=0
|
||||||
frames=10,11,12,13,14,15,16,17,18,19
|
frames=10,11,12,13,14,15,16,17,18,19
|
||||||
[/animation]
|
[/animation]
|
||||||
|
|
||||||
[animation]
|
[animation]
|
||||||
name=green
|
name=green
|
||||||
speed=10
|
speed=0.1667
|
||||||
loop=0
|
loop=0
|
||||||
frames=20,21,22,23,24,25,26,27,28,29
|
frames=20,21,22,23,24,25,26,27,28,29
|
||||||
[/animation]
|
[/animation]
|
||||||
|
|
||||||
[animation]
|
[animation]
|
||||||
name=red
|
name=red
|
||||||
speed=20
|
speed=0.3333
|
||||||
loop=0
|
loop=0
|
||||||
frames=30,31,32,33,34,35,36,37,38,39
|
frames=30,31,32,33,34,35,36,37,38,39
|
||||||
[/animation]
|
[/animation]
|
||||||
@@ -3,7 +3,7 @@ frame_height=10
|
|||||||
|
|
||||||
[animation]
|
[animation]
|
||||||
name=default
|
name=default
|
||||||
speed=5
|
speed=0.0833
|
||||||
loop=-1
|
loop=-1
|
||||||
frames=0,1,2,3,4,5,6,7,8,9
|
frames=0,1,2,3,4,5,6,7,8,9
|
||||||
[/animation]
|
[/animation]
|
||||||
@@ -3,7 +3,7 @@ frame_height=16
|
|||||||
|
|
||||||
[animation]
|
[animation]
|
||||||
name=default
|
name=default
|
||||||
speed=5
|
speed=0.0833
|
||||||
loop=-1
|
loop=-1
|
||||||
frames=0,1,2,3,4,5,6,7,8,9
|
frames=0,1,2,3,4,5,6,7,8,9
|
||||||
[/animation]
|
[/animation]
|
||||||
@@ -3,7 +3,7 @@ frame_height=26
|
|||||||
|
|
||||||
[animation]
|
[animation]
|
||||||
name=default
|
name=default
|
||||||
speed=5
|
speed=0.0833
|
||||||
loop=-1
|
loop=-1
|
||||||
frames=0,1,2,3,4,5,6,7,8,9
|
frames=0,1,2,3,4,5,6,7,8,9
|
||||||
[/animation]
|
[/animation]
|
||||||
@@ -3,7 +3,7 @@ frame_height=48
|
|||||||
|
|
||||||
[animation]
|
[animation]
|
||||||
name=default
|
name=default
|
||||||
speed=5
|
speed=0.0833
|
||||||
loop=-1
|
loop=-1
|
||||||
frames=0,1,2,3,4,5,6,7,8,9
|
frames=0,1,2,3,4,5,6,7,8,9
|
||||||
[/animation]
|
[/animation]
|
||||||
@@ -3,7 +3,7 @@ frame_height=49
|
|||||||
|
|
||||||
[animation]
|
[animation]
|
||||||
name=powerball
|
name=powerball
|
||||||
speed=10
|
speed=0.0167
|
||||||
loop=-1
|
loop=-1
|
||||||
frames=1
|
frames=1
|
||||||
[/animation]
|
[/animation]
|
||||||
@@ -3,42 +3,42 @@ frame_height=12
|
|||||||
|
|
||||||
[animation]
|
[animation]
|
||||||
name=normal_up
|
name=normal_up
|
||||||
speed=5
|
speed=0.0833
|
||||||
loop=0
|
loop=0
|
||||||
frames=0,1,2
|
frames=0,1,2
|
||||||
[/animation]
|
[/animation]
|
||||||
|
|
||||||
[animation]
|
[animation]
|
||||||
name=normal_left
|
name=normal_left
|
||||||
speed=5
|
speed=0.0833
|
||||||
loop=0
|
loop=0
|
||||||
frames=3,4,5,5,4,3
|
frames=3,4,5,5,4,3
|
||||||
[/animation]
|
[/animation]
|
||||||
|
|
||||||
[animation]
|
[animation]
|
||||||
name=normal_right
|
name=normal_right
|
||||||
speed=5
|
speed=0.0833
|
||||||
loop=0
|
loop=0
|
||||||
frames=6,7,8,8,7,6
|
frames=6,7,8,8,7,6
|
||||||
[/animation]
|
[/animation]
|
||||||
|
|
||||||
[animation]
|
[animation]
|
||||||
name=powered_up
|
name=powered_up
|
||||||
speed=5
|
speed=0.0833
|
||||||
loop=0
|
loop=0
|
||||||
frames=9,10,11,11,10,9
|
frames=9,10,11,11,10,9
|
||||||
[/animation]
|
[/animation]
|
||||||
|
|
||||||
[animation]
|
[animation]
|
||||||
name=powered_left
|
name=powered_left
|
||||||
speed=5
|
speed=0.0833
|
||||||
loop=0
|
loop=0
|
||||||
frames=12,13,14,14,13,12
|
frames=12,13,14,14,13,12
|
||||||
[/animation]
|
[/animation]
|
||||||
|
|
||||||
[animation]
|
[animation]
|
||||||
name=powered_right
|
name=powered_right
|
||||||
speed=5
|
speed=0.0833
|
||||||
loop=0
|
loop=0
|
||||||
frames=15,16,17,17,26,15
|
frames=15,16,17,17,26,15
|
||||||
[/animation]
|
[/animation]
|
||||||
@@ -3,7 +3,7 @@ frame_height=20
|
|||||||
|
|
||||||
[animation]
|
[animation]
|
||||||
name=default
|
name=default
|
||||||
speed=8
|
speed=0.1333
|
||||||
loop=0
|
loop=0
|
||||||
frames=0,0,1
|
frames=0,0,1
|
||||||
[/animation]
|
[/animation]
|
||||||
@@ -3,7 +3,7 @@ frame_height=20
|
|||||||
|
|
||||||
[animation]
|
[animation]
|
||||||
name=default
|
name=default
|
||||||
speed=8
|
speed=0.1333
|
||||||
loop=0
|
loop=0
|
||||||
frames=0,0,1
|
frames=0,0,1
|
||||||
[/animation]
|
[/animation]
|
||||||
@@ -3,7 +3,7 @@ frame_height=39
|
|||||||
|
|
||||||
[animation]
|
[animation]
|
||||||
name=default
|
name=default
|
||||||
speed=6
|
speed=0.1
|
||||||
loop=0
|
loop=0
|
||||||
frames=0,1,2,3,4,5,6,7,8
|
frames=0,1,2,3,4,5,6,7,8
|
||||||
[/animation]
|
[/animation]
|
||||||
@@ -3,7 +3,7 @@ frame_height=20
|
|||||||
|
|
||||||
[animation]
|
[animation]
|
||||||
name=default
|
name=default
|
||||||
speed=8
|
speed=0.1333
|
||||||
loop=0
|
loop=0
|
||||||
frames=0,0,1
|
frames=0,0,1
|
||||||
[/animation]
|
[/animation]
|
||||||
@@ -3,7 +3,7 @@ frame_height=20
|
|||||||
|
|
||||||
[animation]
|
[animation]
|
||||||
name=default
|
name=default
|
||||||
speed=8
|
speed=0.1333
|
||||||
loop=0
|
loop=0
|
||||||
frames=0,0,1
|
frames=0,0,1
|
||||||
[/animation]
|
[/animation]
|
||||||
@@ -3,7 +3,7 @@ frame_height=20
|
|||||||
|
|
||||||
[animation]
|
[animation]
|
||||||
name=default
|
name=default
|
||||||
speed=8
|
speed=0.1333
|
||||||
loop=0
|
loop=0
|
||||||
frames=0,0,1
|
frames=0,0,1
|
||||||
[/animation]
|
[/animation]
|
||||||
@@ -3,7 +3,7 @@ frame_height=20
|
|||||||
|
|
||||||
[animation]
|
[animation]
|
||||||
name=default
|
name=default
|
||||||
speed=8
|
speed=0.1333
|
||||||
loop=0
|
loop=0
|
||||||
frames=0,0,1
|
frames=0,0,1
|
||||||
[/animation]
|
[/animation]
|
||||||
@@ -3,133 +3,133 @@ frame_height=32
|
|||||||
|
|
||||||
[animation]
|
[animation]
|
||||||
name=walk
|
name=walk
|
||||||
speed=5
|
speed=0.0833
|
||||||
loop=0
|
loop=0
|
||||||
frames=0,1,2,3
|
frames=0,1,2,3
|
||||||
[/animation]
|
[/animation]
|
||||||
|
|
||||||
[animation]
|
[animation]
|
||||||
name=stand
|
name=stand
|
||||||
speed=10
|
speed=0.167
|
||||||
loop=0
|
loop=0
|
||||||
frames=4,5,6,7
|
frames=4,5,6,7
|
||||||
[/animation]
|
[/animation]
|
||||||
|
|
||||||
[animation]
|
[animation]
|
||||||
name=walk-fire-side
|
name=walk-fire-side
|
||||||
speed=5
|
speed=0.0833
|
||||||
loop=0
|
loop=0
|
||||||
frames=8,9,10,11
|
frames=8,9,10,11
|
||||||
[/animation]
|
[/animation]
|
||||||
|
|
||||||
[animation]
|
[animation]
|
||||||
name=walk-recoil-side
|
name=walk-recoil-side
|
||||||
speed=5
|
speed=0.0833
|
||||||
loop=0
|
loop=0
|
||||||
frames=12,13,14,15
|
frames=12,13,14,15
|
||||||
[/animation]
|
[/animation]
|
||||||
|
|
||||||
[animation]
|
[animation]
|
||||||
name=walk-cool-side
|
name=walk-cool-side
|
||||||
speed=5
|
speed=0.0833
|
||||||
loop=0
|
loop=0
|
||||||
frames=16,17,18,19
|
frames=16,17,18,19
|
||||||
[/animation]
|
[/animation]
|
||||||
|
|
||||||
[animation]
|
[animation]
|
||||||
name=stand-fire-side
|
name=stand-fire-side
|
||||||
speed=5
|
speed=0.0833
|
||||||
loop=0
|
loop=0
|
||||||
frames=20
|
frames=20
|
||||||
[/animation]
|
[/animation]
|
||||||
|
|
||||||
[animation]
|
[animation]
|
||||||
name=stand-recoil-side
|
name=stand-recoil-side
|
||||||
speed=5
|
speed=0.0833
|
||||||
loop=0
|
loop=0
|
||||||
frames=21
|
frames=21
|
||||||
[/animation]
|
[/animation]
|
||||||
|
|
||||||
[animation]
|
[animation]
|
||||||
name=stand-cool-side
|
name=stand-cool-side
|
||||||
speed=5
|
speed=0.0833
|
||||||
loop=0
|
loop=0
|
||||||
frames=22
|
frames=22
|
||||||
[/animation]
|
[/animation]
|
||||||
|
|
||||||
[animation]
|
[animation]
|
||||||
name=walk-fire-center
|
name=walk-fire-center
|
||||||
speed=5
|
speed=0.0833
|
||||||
loop=0
|
loop=0
|
||||||
frames=23,24,25,26
|
frames=23,24,25,26
|
||||||
[/animation]
|
[/animation]
|
||||||
|
|
||||||
[animation]
|
[animation]
|
||||||
name=walk-recoil-center
|
name=walk-recoil-center
|
||||||
speed=5
|
speed=0.0833
|
||||||
loop=0
|
loop=0
|
||||||
frames=27,28,29,30
|
frames=27,28,29,30
|
||||||
[/animation]
|
[/animation]
|
||||||
|
|
||||||
[animation]
|
[animation]
|
||||||
name=walk-cool-center
|
name=walk-cool-center
|
||||||
speed=5
|
speed=0.0833
|
||||||
loop=0
|
loop=0
|
||||||
frames=31,32,33,34
|
frames=31,32,33,34
|
||||||
[/animation]
|
[/animation]
|
||||||
|
|
||||||
[animation]
|
[animation]
|
||||||
name=stand-fire-center
|
name=stand-fire-center
|
||||||
speed=5
|
speed=0.0833
|
||||||
loop=0
|
loop=0
|
||||||
frames=35
|
frames=35
|
||||||
[/animation]
|
[/animation]
|
||||||
|
|
||||||
[animation]
|
[animation]
|
||||||
name=stand-recoil-center
|
name=stand-recoil-center
|
||||||
speed=5
|
speed=0.0833
|
||||||
loop=0
|
loop=0
|
||||||
frames=36
|
frames=36
|
||||||
[/animation]
|
[/animation]
|
||||||
|
|
||||||
[animation]
|
[animation]
|
||||||
name=stand-cool-center
|
name=stand-cool-center
|
||||||
speed=5
|
speed=0.0833
|
||||||
loop=0
|
loop=0
|
||||||
frames=37
|
frames=37
|
||||||
[/animation]
|
[/animation]
|
||||||
|
|
||||||
[animation]
|
[animation]
|
||||||
name=rolling
|
name=rolling
|
||||||
speed=10
|
speed=0.167
|
||||||
loop=0
|
loop=0
|
||||||
frames=38,39,40,41
|
frames=38,39,40,41
|
||||||
[/animation]
|
[/animation]
|
||||||
|
|
||||||
[animation]
|
[animation]
|
||||||
name=celebration
|
name=celebration
|
||||||
speed=10
|
speed=0.167
|
||||||
loop=-1
|
loop=-1
|
||||||
frames=42,42,42,42,42,42,43,44,45,46,46,46,46,46,46,45,45,45,46,46,46,45,45,45,44,43,42,42,42
|
frames=42,42,42,42,42,42,43,44,45,46,46,46,46,46,46,45,45,45,46,46,46,45,45,45,44,43,42,42,42
|
||||||
[/animation]
|
[/animation]
|
||||||
|
|
||||||
[animation]
|
[animation]
|
||||||
name=dizzy
|
name=dizzy
|
||||||
speed=5
|
speed=0.0833
|
||||||
loop=0
|
loop=0
|
||||||
frames=47,48,49,50,51,52,53
|
frames=47,48,49,50,51,52,53
|
||||||
[/animation]
|
[/animation]
|
||||||
|
|
||||||
[animation]
|
[animation]
|
||||||
name=recover
|
name=recover
|
||||||
speed=3
|
speed=0.05
|
||||||
loop=-1
|
loop=-1
|
||||||
frames=54,54,54,54,55,56,57,58,58,58,59,60,61,58,59,60,61,58,59,60,61,62,62,62,62
|
frames=54,54,54,54,55,56,57,58,58,58,59,60,61,58,59,60,61,58,59,60,61,62,62,62,62
|
||||||
[/animation]
|
[/animation]
|
||||||
|
|
||||||
[animation]
|
[animation]
|
||||||
name=hello
|
name=hello
|
||||||
speed=3
|
speed=0.05
|
||||||
loop=-1
|
loop=-1
|
||||||
frames=63,64,65,66,67,68,69,70,71,72,73,73,73,73,73,73,73,73,73,73,73,73,73,74,75,76,77,78,79,80,81,82,82,81,80,79,79,80,81,82,82,81,80,79,79,80,81,82,82,81,80,79,79,80,81,82,82,81,80,79,78,77,76,75,74,73,72,71,70,69,68,67,66,65,64,63
|
frames=63,64,65,66,67,68,69,70,71,72,73,73,73,73,73,73,73,73,73,73,73,73,73,74,75,76,77,78,79,80,81,82,82,81,80,79,79,80,81,82,82,81,80,79,79,80,81,82,82,81,80,79,79,80,81,82,82,81,80,79,78,77,76,75,74,73,72,71,70,69,68,67,66,65,64,63
|
||||||
[/animation]
|
[/animation]
|
||||||
@@ -3,7 +3,7 @@ frame_height=44
|
|||||||
|
|
||||||
[animation]
|
[animation]
|
||||||
name=default
|
name=default
|
||||||
speed=5
|
speed=0.0833
|
||||||
loop=0
|
loop=0
|
||||||
frames=0,1,2,3
|
frames=0,1,2,3
|
||||||
[/animation]
|
[/animation]
|
||||||
@@ -3,14 +3,14 @@ frame_height=32
|
|||||||
|
|
||||||
[animation]
|
[animation]
|
||||||
name=fly
|
name=fly
|
||||||
speed=2
|
speed=0.0333
|
||||||
loop=0
|
loop=0
|
||||||
frames=0,1
|
frames=0,1
|
||||||
[/animation]
|
[/animation]
|
||||||
|
|
||||||
[animation]
|
[animation]
|
||||||
name=hit
|
name=hit
|
||||||
speed=2
|
speed=0.0333
|
||||||
loop=0
|
loop=0
|
||||||
frames=2,3
|
frames=2,3
|
||||||
[/animation]
|
[/animation]
|
||||||
@@ -3,7 +3,7 @@ frame_height=16
|
|||||||
|
|
||||||
[animation]
|
[animation]
|
||||||
name=default
|
name=default
|
||||||
speed=8
|
speed=0.1333
|
||||||
loop=-1
|
loop=-1
|
||||||
frames=0,1,2,3,4,5,6
|
frames=0,1,2,3,4,5,6
|
||||||
[/animation]
|
[/animation]
|
||||||
BIN
data/sound/click-2.wav
Normal file
BIN
data/sound/click-2.wav
Normal file
Binary file not shown.
BIN
data/sound/click-3.wav
Normal file
BIN
data/sound/click-3.wav
Normal file
Binary file not shown.
BIN
data/sound/service_menu_back.wav
Normal file
BIN
data/sound/service_menu_back.wav
Normal file
Binary file not shown.
Binary file not shown.
43
development_guidelines.md
Normal file
43
development_guidelines.md
Normal file
@@ -0,0 +1,43 @@
|
|||||||
|
# Directrices de Desarrollo - Coffee Crisis Arcade Edition
|
||||||
|
|
||||||
|
## Directrices Principales Confirmadas
|
||||||
|
|
||||||
|
### 1. **Sistema Temporal**
|
||||||
|
- **TODO migrado de frame based a time based**
|
||||||
|
- **Delta time en segundos (float)**
|
||||||
|
- **Unidades de tiempo: SOLO segundos** (no frames, no milisegundos)
|
||||||
|
|
||||||
|
### 2. **Contadores y Timers**
|
||||||
|
- **CRECIENTES**: para sistemas con múltiples eventos temporales (timeline)
|
||||||
|
- Patrón: `elapsed_time += deltaTime; if (elapsed_time >= EVENT_TIME) { /* acción */ }`
|
||||||
|
- **DECRECIENTES**: para contadores con diferentes valores de inicialización
|
||||||
|
- Patrón: `timer -= deltaTime; if (timer <= 0.0f) { /* acción */ timer = DURATION; }`
|
||||||
|
|
||||||
|
### 3. **Números Mágicos**
|
||||||
|
- **Definidos en constantes**
|
||||||
|
- **Preferencia**: cabecera de la clase
|
||||||
|
- **Excepción**: si es algo local a un método específico
|
||||||
|
|
||||||
|
## Problemas Pendientes de Reparación (game.cpp)
|
||||||
|
|
||||||
|
### ❌ PENDIENTES
|
||||||
|
1. **param.fade.post_duration_ms verification** (líneas 89, 1671)
|
||||||
|
2. **setRotateSpeed verification** (línea 797)
|
||||||
|
3. **TOTAL_DEMO_DATA - 200 magic number** (línea 1669)
|
||||||
|
4. **Comprehensive magic number search** - Buscar 100, 150, 200, 250, 300, 400, 500, 1000
|
||||||
|
|
||||||
|
### 4. **Velocidades y Aceleraciones**
|
||||||
|
- **Velocidades**: pixels/segundo
|
||||||
|
- **Aceleraciones**: pixels/segundo²
|
||||||
|
|
||||||
|
### 5. **Documentación de Conversiones**
|
||||||
|
- **Comentarios explicativos** en cambios críticos de timing
|
||||||
|
- Documentar conversiones frame→tiempo en el código
|
||||||
|
|
||||||
|
### 6. **Patrón de Constantes**
|
||||||
|
- Crear constantes para valores repetidos (evitar duplicación)
|
||||||
|
- Nombres descriptivos para constantes de tiempo
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**Estado**: Directrices completas confirmadas
|
||||||
BIN
resources.pack
BIN
resources.pack
Binary file not shown.
@@ -9,9 +9,9 @@
|
|||||||
#include <stdexcept> // Para runtime_error
|
#include <stdexcept> // Para runtime_error
|
||||||
#include <utility> // Para pair
|
#include <utility> // Para pair
|
||||||
|
|
||||||
#include "texture.h" // Para Texture
|
|
||||||
#include "resource_helper.h" // Para ResourceHelper
|
#include "resource_helper.h" // Para ResourceHelper
|
||||||
#include "utils.h" // Para printWithDots
|
#include "texture.h" // Para Texture
|
||||||
|
#include "utils.h" // Para printWithDots
|
||||||
|
|
||||||
// Carga las animaciones en un vector(Animations) desde un fichero
|
// Carga las animaciones en un vector(Animations) desde un fichero
|
||||||
auto loadAnimationsFromFile(const std::string& file_path) -> AnimationsFileBuffer {
|
auto loadAnimationsFromFile(const std::string& file_path) -> AnimationsFileBuffer {
|
||||||
@@ -19,13 +19,13 @@ auto loadAnimationsFromFile(const std::string& file_path) -> AnimationsFileBuffe
|
|||||||
auto resource_data = ResourceHelper::loadFile(file_path);
|
auto resource_data = ResourceHelper::loadFile(file_path);
|
||||||
std::istringstream stream;
|
std::istringstream stream;
|
||||||
bool using_resource_data = false;
|
bool using_resource_data = false;
|
||||||
|
|
||||||
if (!resource_data.empty()) {
|
if (!resource_data.empty()) {
|
||||||
std::string content(resource_data.begin(), resource_data.end());
|
std::string content(resource_data.begin(), resource_data.end());
|
||||||
stream.str(content);
|
stream.str(content);
|
||||||
using_resource_data = true;
|
using_resource_data = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fallback a archivo directo
|
// Fallback a archivo directo
|
||||||
std::ifstream file;
|
std::ifstream file;
|
||||||
if (!using_resource_data) {
|
if (!using_resource_data) {
|
||||||
@@ -35,7 +35,7 @@ auto loadAnimationsFromFile(const std::string& file_path) -> AnimationsFileBuffe
|
|||||||
throw std::runtime_error("Fichero no encontrado: " + file_path);
|
throw std::runtime_error("Fichero no encontrado: " + file_path);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
std::istream& input_stream = using_resource_data ? stream : static_cast<std::istream&>(file);
|
std::istream& input_stream = using_resource_data ? stream : static_cast<std::istream&>(file);
|
||||||
|
|
||||||
printWithDots("Animation : ", file_path.substr(file_path.find_last_of("\\/") + 1), "[ LOADED ]");
|
printWithDots("Animation : ", file_path.substr(file_path.find_last_of("\\/") + 1), "[ LOADED ]");
|
||||||
@@ -43,6 +43,10 @@ auto loadAnimationsFromFile(const std::string& file_path) -> AnimationsFileBuffe
|
|||||||
std::vector<std::string> buffer;
|
std::vector<std::string> buffer;
|
||||||
std::string line;
|
std::string line;
|
||||||
while (std::getline(input_stream, line)) {
|
while (std::getline(input_stream, line)) {
|
||||||
|
// Eliminar caracteres de retorno de carro (\r) al final de la línea
|
||||||
|
if (!line.empty() && line.back() == '\r') {
|
||||||
|
line.pop_back();
|
||||||
|
}
|
||||||
if (!line.empty()) {
|
if (!line.empty()) {
|
||||||
buffer.push_back(line);
|
buffer.push_back(line);
|
||||||
}
|
}
|
||||||
@@ -82,33 +86,33 @@ auto AnimatedSprite::getAnimationIndex(const std::string& name) -> int {
|
|||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Calcula el frame correspondiente a la animación
|
// Calcula el frame correspondiente a la animación (time-based)
|
||||||
void AnimatedSprite::animate() {
|
void AnimatedSprite::animate(float deltaTime) {
|
||||||
if (animations_[current_animation_].speed == 0 || animations_[current_animation_].paused) {
|
if (animations_[current_animation_].speed == 0 || animations_[current_animation_].paused) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Calcula el frame actual a partir del contador
|
// Acumular tiempo transcurrido
|
||||||
animations_[current_animation_].current_frame = animations_[current_animation_].counter / animations_[current_animation_].speed;
|
animations_[current_animation_].time_accumulator += deltaTime;
|
||||||
|
|
||||||
// Si alcanza el final de la animación, reinicia el contador de la animación
|
// Verificar si es momento de cambiar frame
|
||||||
// en función de la variable loop y coloca el nuevo frame
|
if (animations_[current_animation_].time_accumulator >= animations_[current_animation_].speed) {
|
||||||
if (animations_[current_animation_].current_frame >= animations_[current_animation_].frames.size()) {
|
animations_[current_animation_].time_accumulator -= animations_[current_animation_].speed;
|
||||||
if (animations_[current_animation_].loop == -1) { // Si no hay loop, deja el último frame
|
animations_[current_animation_].current_frame++;
|
||||||
animations_[current_animation_].current_frame = animations_[current_animation_].frames.size();
|
|
||||||
animations_[current_animation_].completed = true;
|
// Si alcanza el final de la animación
|
||||||
} else { // Si hay loop, vuelve al frame indicado
|
if (animations_[current_animation_].current_frame >= animations_[current_animation_].frames.size()) {
|
||||||
animations_[current_animation_].counter = 0;
|
if (animations_[current_animation_].loop == -1) { // Si no hay loop, deja el último frame
|
||||||
animations_[current_animation_].current_frame = animations_[current_animation_].loop;
|
animations_[current_animation_].current_frame = animations_[current_animation_].frames.size() - 1;
|
||||||
|
animations_[current_animation_].completed = true;
|
||||||
|
} else { // Si hay loop, vuelve al frame indicado
|
||||||
|
animations_[current_animation_].time_accumulator = 0.0f;
|
||||||
|
animations_[current_animation_].current_frame = animations_[current_animation_].loop;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
// En caso contrario
|
// Actualizar el sprite clip
|
||||||
else {
|
|
||||||
// Escoge el frame correspondiente de la animación
|
|
||||||
updateSpriteClip();
|
updateSpriteClip();
|
||||||
|
|
||||||
// Incrementa el contador de la animacion
|
|
||||||
animations_[current_animation_].counter++;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -125,11 +129,11 @@ void AnimatedSprite::setCurrentAnimation(const std::string& name, bool reset) {
|
|||||||
current_animation_ = NEW_ANIMATION;
|
current_animation_ = NEW_ANIMATION;
|
||||||
if (reset) {
|
if (reset) {
|
||||||
animations_[current_animation_].current_frame = 0;
|
animations_[current_animation_].current_frame = 0;
|
||||||
animations_[current_animation_].counter = 0;
|
animations_[current_animation_].time_accumulator = 0.0f;
|
||||||
animations_[current_animation_].completed = false;
|
animations_[current_animation_].completed = false;
|
||||||
} else {
|
} else {
|
||||||
animations_[current_animation_].current_frame = std::min(animations_[OLD_ANIMATION].current_frame, animations_[current_animation_].frames.size() - 1);
|
animations_[current_animation_].current_frame = std::min(animations_[OLD_ANIMATION].current_frame, animations_[current_animation_].frames.size() - 1);
|
||||||
animations_[current_animation_].counter = animations_[OLD_ANIMATION].counter;
|
animations_[current_animation_].time_accumulator = animations_[OLD_ANIMATION].time_accumulator;
|
||||||
animations_[current_animation_].completed = animations_[OLD_ANIMATION].completed;
|
animations_[current_animation_].completed = animations_[OLD_ANIMATION].completed;
|
||||||
}
|
}
|
||||||
updateSpriteClip();
|
updateSpriteClip();
|
||||||
@@ -144,27 +148,27 @@ void AnimatedSprite::setCurrentAnimation(int index, bool reset) {
|
|||||||
current_animation_ = NEW_ANIMATION;
|
current_animation_ = NEW_ANIMATION;
|
||||||
if (reset) {
|
if (reset) {
|
||||||
animations_[current_animation_].current_frame = 0;
|
animations_[current_animation_].current_frame = 0;
|
||||||
animations_[current_animation_].counter = 0;
|
animations_[current_animation_].time_accumulator = 0.0f;
|
||||||
animations_[current_animation_].completed = false;
|
animations_[current_animation_].completed = false;
|
||||||
} else {
|
} else {
|
||||||
animations_[current_animation_].current_frame = std::min(animations_[OLD_ANIMATION].current_frame, animations_[current_animation_].frames.size());
|
animations_[current_animation_].current_frame = std::min(animations_[OLD_ANIMATION].current_frame, animations_[current_animation_].frames.size());
|
||||||
animations_[current_animation_].counter = animations_[OLD_ANIMATION].counter;
|
animations_[current_animation_].time_accumulator = animations_[OLD_ANIMATION].time_accumulator;
|
||||||
animations_[current_animation_].completed = animations_[OLD_ANIMATION].completed;
|
animations_[current_animation_].completed = animations_[OLD_ANIMATION].completed;
|
||||||
}
|
}
|
||||||
updateSpriteClip();
|
updateSpriteClip();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Actualiza las variables del objeto
|
// Actualiza las variables del objeto (time-based)
|
||||||
void AnimatedSprite::update() {
|
void AnimatedSprite::update(float deltaTime) {
|
||||||
animate();
|
animate(deltaTime);
|
||||||
MovingSprite::update();
|
MovingSprite::update(deltaTime);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Reinicia la animación
|
// Reinicia la animación
|
||||||
void AnimatedSprite::resetAnimation() {
|
void AnimatedSprite::resetAnimation() {
|
||||||
animations_[current_animation_].current_frame = 0;
|
animations_[current_animation_].current_frame = 0;
|
||||||
animations_[current_animation_].counter = 0;
|
animations_[current_animation_].time_accumulator = 0.0f;
|
||||||
animations_[current_animation_].completed = false;
|
animations_[current_animation_].completed = false;
|
||||||
animations_[current_animation_].paused = false;
|
animations_[current_animation_].paused = false;
|
||||||
updateSpriteClip();
|
updateSpriteClip();
|
||||||
@@ -190,6 +194,12 @@ void AnimatedSprite::loadFromAnimationsFileBuffer(const AnimationsFileBuffer& so
|
|||||||
// Pone un valor por defecto
|
// Pone un valor por defecto
|
||||||
setWidth(config.frame_width);
|
setWidth(config.frame_width);
|
||||||
setHeight(config.frame_height);
|
setHeight(config.frame_height);
|
||||||
|
|
||||||
|
// Establece el primer frame inmediatamente si hay animaciones
|
||||||
|
if (!animations_.empty()) {
|
||||||
|
current_animation_ = 0;
|
||||||
|
updateSpriteClip();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Procesa una línea de configuración
|
// Procesa una línea de configuración
|
||||||
@@ -259,7 +269,7 @@ void AnimatedSprite::processAnimationParameter(const std::string& line, Animatio
|
|||||||
if (key == "name") {
|
if (key == "name") {
|
||||||
animation.name = value;
|
animation.name = value;
|
||||||
} else if (key == "speed") {
|
} else if (key == "speed") {
|
||||||
animation.speed = std::stoi(value);
|
animation.speed = std::stof(value);
|
||||||
} else if (key == "loop") {
|
} else if (key == "loop") {
|
||||||
animation.loop = std::stoi(value);
|
animation.loop = std::stoi(value);
|
||||||
} else if (key == "frames") {
|
} else if (key == "frames") {
|
||||||
@@ -286,7 +296,7 @@ void AnimatedSprite::parseFramesParameter(const std::string& frames_str, Animati
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Establece la velocidad de la animación
|
// Establece la velocidad de la animación
|
||||||
void AnimatedSprite::setAnimationSpeed(size_t value) {
|
void AnimatedSprite::setAnimationSpeed(float value) {
|
||||||
animations_[current_animation_].speed = value;
|
animations_[current_animation_].speed = value;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -17,15 +17,15 @@ class Texture;
|
|||||||
|
|
||||||
// --- Estructuras ---
|
// --- Estructuras ---
|
||||||
struct Animation {
|
struct Animation {
|
||||||
static constexpr int DEFAULT_SPEED = 5;
|
static constexpr float DEFAULT_SPEED = 80.0F;
|
||||||
|
|
||||||
std::string name; // Nombre de la animación
|
std::string name; // Nombre de la animación
|
||||||
std::vector<SDL_FRect> frames; // Frames que componen la animación
|
std::vector<SDL_FRect> frames; // Frames que componen la animación
|
||||||
int speed{DEFAULT_SPEED}; // Velocidad de reproducción
|
float speed{DEFAULT_SPEED}; // Velocidad de reproducción (ms entre frames)
|
||||||
int loop{0}; // Frame de vuelta al terminar (-1 para no repetir)
|
int loop{0}; // Frame de vuelta al terminar (-1 para no repetir)
|
||||||
bool completed{false}; // Indica si la animación ha finalizado
|
bool completed{false}; // Indica si la animación ha finalizado
|
||||||
size_t current_frame{0}; // Frame actual en reproducción
|
size_t current_frame{0}; // Frame actual en reproducción
|
||||||
int counter{0}; // Contador para la animación
|
float time_accumulator{0.0f}; // Acumulador de tiempo para animaciones time-based
|
||||||
bool paused{false}; // La animación no avanza
|
bool paused{false}; // La animación no avanza
|
||||||
|
|
||||||
Animation() = default;
|
Animation() = default;
|
||||||
@@ -50,18 +50,19 @@ class AnimatedSprite : public MovingSprite {
|
|||||||
// --- Constructores y destructor ---
|
// --- Constructores y destructor ---
|
||||||
AnimatedSprite(std::shared_ptr<Texture> texture, const std::string& file_path);
|
AnimatedSprite(std::shared_ptr<Texture> texture, const std::string& file_path);
|
||||||
AnimatedSprite(std::shared_ptr<Texture> texture, const AnimationsFileBuffer& animations);
|
AnimatedSprite(std::shared_ptr<Texture> texture, const AnimationsFileBuffer& animations);
|
||||||
explicit AnimatedSprite(std::shared_ptr<Texture> texture) : MovingSprite(std::move(texture)) {}
|
explicit AnimatedSprite(std::shared_ptr<Texture> texture)
|
||||||
|
: MovingSprite(std::move(texture)) {}
|
||||||
~AnimatedSprite() override = default;
|
~AnimatedSprite() override = default;
|
||||||
|
|
||||||
// --- Métodos principales ---
|
// --- Métodos principales ---
|
||||||
void update() override; // Actualiza la animación
|
void update(float deltaTime); // Actualiza la animación (time-based)
|
||||||
|
|
||||||
// --- Control de animaciones ---
|
// --- Control de animaciones ---
|
||||||
void setCurrentAnimation(const std::string& name = "default", bool reset = true); // Establece la animación por nombre
|
void setCurrentAnimation(const std::string& name = "default", bool reset = true); // Establece la animación por nombre
|
||||||
void setCurrentAnimation(int index = 0, bool reset = true); // Establece la animación por índice
|
void setCurrentAnimation(int index = 0, bool reset = true); // Establece la animación por índice
|
||||||
void resetAnimation(); // Reinicia la animación actual
|
void resetAnimation(); // Reinicia la animación actual
|
||||||
void setAnimationSpeed(size_t value); // Establece la velocidad de la animación
|
void setAnimationSpeed(float value); // Establece la velocidad de la animación
|
||||||
auto getAnimationSpeed() const -> size_t { return animations_[current_animation_].speed; } // Obtiene la velocidad de la animación actual
|
auto getAnimationSpeed() const -> float { return animations_[current_animation_].speed; } // Obtiene la velocidad de la animación actual
|
||||||
void animtionPause() { animations_[current_animation_].paused = true; } // Detiene la animación
|
void animtionPause() { animations_[current_animation_].paused = true; } // Detiene la animación
|
||||||
void animationResume() { animations_[current_animation_].paused = false; } // Reanuda la animación
|
void animationResume() { animations_[current_animation_].paused = false; } // Reanuda la animación
|
||||||
auto getCurrentAnimationFrame() const -> size_t { return animations_[current_animation_].current_frame; } // Obtiene el numero de frame de la animación actual
|
auto getCurrentAnimationFrame() const -> size_t { return animations_[current_animation_].current_frame; } // Obtiene el numero de frame de la animación actual
|
||||||
@@ -77,7 +78,7 @@ class AnimatedSprite : public MovingSprite {
|
|||||||
int current_animation_ = 0; // Índice de la animación activa
|
int current_animation_ = 0; // Índice de la animación activa
|
||||||
|
|
||||||
// --- Métodos internos ---
|
// --- Métodos internos ---
|
||||||
void animate(); // Calcula el frame correspondiente a la animación
|
void animate(float deltaTime); // Calcula el frame correspondiente a la animación (time-based)
|
||||||
void loadFromAnimationsFileBuffer(const AnimationsFileBuffer& source); // Carga la animación desde un vector de cadenas
|
void loadFromAnimationsFileBuffer(const AnimationsFileBuffer& source); // Carga la animación desde un vector de cadenas
|
||||||
void processConfigLine(const std::string& line, AnimationConfig& config); // Procesa una línea de configuración
|
void processConfigLine(const std::string& line, AnimationConfig& config); // Procesa una línea de configuración
|
||||||
void updateFrameCalculations(AnimationConfig& config); // Actualiza los cálculos basados en las dimensiones del frame
|
void updateFrameCalculations(AnimationConfig& config); // Actualiza los cálculos basados en las dimensiones del frame
|
||||||
|
|||||||
@@ -8,8 +8,8 @@
|
|||||||
#include <sstream> // Para basic_istringstream
|
#include <sstream> // Para basic_istringstream
|
||||||
#include <stdexcept> // Para runtime_error
|
#include <stdexcept> // Para runtime_error
|
||||||
|
|
||||||
#include "utils.h" // Para getFileName
|
|
||||||
#include "resource_helper.h" // Para ResourceHelper
|
#include "resource_helper.h" // Para ResourceHelper
|
||||||
|
#include "utils.h" // Para getFileName
|
||||||
|
|
||||||
// Singleton
|
// Singleton
|
||||||
Asset *Asset::instance = nullptr;
|
Asset *Asset::instance = nullptr;
|
||||||
@@ -209,7 +209,7 @@ auto Asset::checkFile(const std::string &path) -> bool {
|
|||||||
// Intentar primero con ResourceHelper
|
// Intentar primero con ResourceHelper
|
||||||
auto data = ResourceHelper::loadFile(path);
|
auto data = ResourceHelper::loadFile(path);
|
||||||
bool success = !data.empty();
|
bool success = !data.empty();
|
||||||
|
|
||||||
// Si no se encuentra en el pack, intentar con filesystem directo
|
// Si no se encuentra en el pack, intentar con filesystem directo
|
||||||
if (!success) {
|
if (!success) {
|
||||||
std::ifstream file(path);
|
std::ifstream file(path);
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
|
#include <cstdint> // Para uint8_t
|
||||||
#include <string> // Para string
|
#include <string> // Para string
|
||||||
#include <unordered_map> // Para unordered_map
|
#include <unordered_map> // Para unordered_map
|
||||||
#include <utility> // Para move
|
#include <utility> // Para move
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
#include <cstdint> // Para uint8_t
|
|
||||||
|
|
||||||
// --- Clase Asset: gestor optimizado de recursos (singleton) ---
|
// --- Clase Asset: gestor optimizado de recursos (singleton) ---
|
||||||
class Asset {
|
class Asset {
|
||||||
@@ -34,7 +34,7 @@ class Asset {
|
|||||||
void add(const std::string &file_path, Type type, bool required = true, bool absolute = false);
|
void add(const std::string &file_path, Type type, bool required = true, bool absolute = false);
|
||||||
void loadFromFile(const std::string &config_file_path, const std::string &prefix = "", const std::string &system_folder = ""); // Con soporte para variables
|
void loadFromFile(const std::string &config_file_path, const std::string &prefix = "", const std::string &system_folder = ""); // Con soporte para variables
|
||||||
[[nodiscard]] auto get(const std::string &filename) const -> std::string; // Mantener nombre original
|
[[nodiscard]] auto get(const std::string &filename) const -> std::string; // Mantener nombre original
|
||||||
[[nodiscard]] auto loadData(const std::string &filename) const -> std::vector<uint8_t>; // Carga datos del archivo
|
[[nodiscard]] auto loadData(const std::string &filename) const -> std::vector<uint8_t>; // Carga datos del archivo
|
||||||
[[nodiscard]] auto check() const -> bool;
|
[[nodiscard]] auto check() const -> bool;
|
||||||
[[nodiscard]] auto getListByType(Type type) const -> std::vector<std::string>;
|
[[nodiscard]] auto getListByType(Type type) const -> std::vector<std::string>;
|
||||||
[[nodiscard]] auto exists(const std::string &filename) const -> bool; // Nueva función para verificar existencia
|
[[nodiscard]] auto exists(const std::string &filename) const -> bool; // Nueva función para verificar existencia
|
||||||
@@ -47,7 +47,9 @@ class Asset {
|
|||||||
bool required; // Indica si el archivo es obligatorio
|
bool required; // Indica si el archivo es obligatorio
|
||||||
|
|
||||||
Item(std::string path, Type asset_type, bool is_required)
|
Item(std::string path, Type asset_type, bool is_required)
|
||||||
: file(std::move(path)), type(asset_type), required(is_required) {}
|
: file(std::move(path)),
|
||||||
|
type(asset_type),
|
||||||
|
required(is_required) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
// --- Variables internas ---
|
// --- Variables internas ---
|
||||||
|
|||||||
@@ -1,17 +1,18 @@
|
|||||||
#include "asset_integrated.h"
|
#include "asset_integrated.h"
|
||||||
|
|
||||||
#include <filesystem>
|
#include <filesystem>
|
||||||
#include <iostream>
|
|
||||||
#include <fstream>
|
#include <fstream>
|
||||||
|
#include <iostream>
|
||||||
|
|
||||||
bool AssetIntegrated::resource_pack_enabled_ = false;
|
bool AssetIntegrated::resource_pack_enabled_ = false;
|
||||||
|
|
||||||
void AssetIntegrated::initWithResourcePack(const std::string &executable_path,
|
void AssetIntegrated::initWithResourcePack(const std::string &executable_path,
|
||||||
const std::string &resource_pack_path) {
|
const std::string &resource_pack_path) {
|
||||||
// Inicializar Asset normal
|
// Inicializar Asset normal
|
||||||
Asset::init(executable_path);
|
Asset::init(executable_path);
|
||||||
|
|
||||||
// Inicializar ResourceLoader
|
// Inicializar ResourceLoader
|
||||||
auto& loader = ResourceLoader::getInstance();
|
auto &loader = ResourceLoader::getInstance();
|
||||||
if (loader.initialize(resource_pack_path, true)) {
|
if (loader.initialize(resource_pack_path, true)) {
|
||||||
resource_pack_enabled_ = true;
|
resource_pack_enabled_ = true;
|
||||||
std::cout << "Asset system initialized with resource pack: " << resource_pack_path << std::endl;
|
std::cout << "Asset system initialized with resource pack: " << resource_pack_path << std::endl;
|
||||||
@@ -24,58 +25,58 @@ void AssetIntegrated::initWithResourcePack(const std::string &executable_path,
|
|||||||
std::vector<uint8_t> AssetIntegrated::loadFile(const std::string &filename) {
|
std::vector<uint8_t> AssetIntegrated::loadFile(const std::string &filename) {
|
||||||
if (shouldUseResourcePack(filename) && resource_pack_enabled_) {
|
if (shouldUseResourcePack(filename) && resource_pack_enabled_) {
|
||||||
// Intentar cargar del pack de recursos
|
// Intentar cargar del pack de recursos
|
||||||
auto& loader = ResourceLoader::getInstance();
|
auto &loader = ResourceLoader::getInstance();
|
||||||
|
|
||||||
// Convertir ruta completa a ruta relativa para el pack
|
// Convertir ruta completa a ruta relativa para el pack
|
||||||
std::string relativePath = filename;
|
std::string relativePath = filename;
|
||||||
|
|
||||||
// Si la ruta contiene "data/", extraer la parte relativa
|
// Si la ruta contiene "data/", extraer la parte relativa
|
||||||
size_t dataPos = filename.find("data/");
|
size_t dataPos = filename.find("data/");
|
||||||
if (dataPos != std::string::npos) {
|
if (dataPos != std::string::npos) {
|
||||||
relativePath = filename.substr(dataPos + 5); // +5 para saltar "data/"
|
relativePath = filename.substr(dataPos + 5); // +5 para saltar "data/"
|
||||||
}
|
}
|
||||||
|
|
||||||
auto data = loader.loadResource(relativePath);
|
auto data = loader.loadResource(relativePath);
|
||||||
if (!data.empty()) {
|
if (!data.empty()) {
|
||||||
return data;
|
return data;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fallback: cargar del filesystem
|
// Fallback: cargar del filesystem
|
||||||
std::ifstream file(filename, std::ios::binary | std::ios::ate);
|
std::ifstream file(filename, std::ios::binary | std::ios::ate);
|
||||||
if (!file) {
|
if (!file) {
|
||||||
std::cerr << "Error: Could not open file: " << filename << std::endl;
|
std::cerr << "Error: Could not open file: " << filename << std::endl;
|
||||||
return {};
|
return {};
|
||||||
}
|
}
|
||||||
|
|
||||||
std::streamsize fileSize = file.tellg();
|
std::streamsize fileSize = file.tellg();
|
||||||
file.seekg(0, std::ios::beg);
|
file.seekg(0, std::ios::beg);
|
||||||
|
|
||||||
std::vector<uint8_t> data(fileSize);
|
std::vector<uint8_t> data(fileSize);
|
||||||
if (!file.read(reinterpret_cast<char*>(data.data()), fileSize)) {
|
if (!file.read(reinterpret_cast<char *>(data.data()), fileSize)) {
|
||||||
std::cerr << "Error: Could not read file: " << filename << std::endl;
|
std::cerr << "Error: Could not read file: " << filename << std::endl;
|
||||||
return {};
|
return {};
|
||||||
}
|
}
|
||||||
|
|
||||||
return data;
|
return data;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool AssetIntegrated::fileExists(const std::string &filename) const {
|
bool AssetIntegrated::fileExists(const std::string &filename) const {
|
||||||
if (shouldUseResourcePack(filename) && resource_pack_enabled_) {
|
if (shouldUseResourcePack(filename) && resource_pack_enabled_) {
|
||||||
auto& loader = ResourceLoader::getInstance();
|
auto &loader = ResourceLoader::getInstance();
|
||||||
|
|
||||||
// Convertir ruta completa a ruta relativa para el pack
|
// Convertir ruta completa a ruta relativa para el pack
|
||||||
std::string relativePath = filename;
|
std::string relativePath = filename;
|
||||||
size_t dataPos = filename.find("data/");
|
size_t dataPos = filename.find("data/");
|
||||||
if (dataPos != std::string::npos) {
|
if (dataPos != std::string::npos) {
|
||||||
relativePath = filename.substr(dataPos + 5);
|
relativePath = filename.substr(dataPos + 5);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (loader.resourceExists(relativePath)) {
|
if (loader.resourceExists(relativePath)) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Verificar en filesystem
|
// Verificar en filesystem
|
||||||
return std::filesystem::exists(filename);
|
return std::filesystem::exists(filename);
|
||||||
}
|
}
|
||||||
@@ -90,16 +91,16 @@ bool AssetIntegrated::shouldUseResourcePack(const std::string &filepath) const {
|
|||||||
// - Archivos de config/ (ahora están fuera de data/)
|
// - Archivos de config/ (ahora están fuera de data/)
|
||||||
// - Archivos con absolute=true en assets.txt
|
// - Archivos con absolute=true en assets.txt
|
||||||
// - Archivos de sistema (${SYSTEM_FOLDER})
|
// - Archivos de sistema (${SYSTEM_FOLDER})
|
||||||
|
|
||||||
if (filepath.find("/config/") != std::string::npos ||
|
if (filepath.find("/config/") != std::string::npos ||
|
||||||
filepath.find("config/") == 0) {
|
filepath.find("config/") == 0) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (filepath.find("/data/") != std::string::npos ||
|
if (filepath.find("/data/") != std::string::npos ||
|
||||||
filepath.find("data/") == 0) {
|
filepath.find("data/") == 0) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -1,28 +1,29 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
|
#include <memory>
|
||||||
|
|
||||||
#include "asset.h"
|
#include "asset.h"
|
||||||
#include "resource_loader.h"
|
#include "resource_loader.h"
|
||||||
#include <memory>
|
|
||||||
|
|
||||||
// Extensión de Asset que integra ResourceLoader
|
// Extensión de Asset que integra ResourceLoader
|
||||||
class AssetIntegrated : public Asset {
|
class AssetIntegrated : public Asset {
|
||||||
public:
|
public:
|
||||||
// Inicializa Asset con ResourceLoader
|
// Inicializa Asset con ResourceLoader
|
||||||
static void initWithResourcePack(const std::string &executable_path,
|
static void initWithResourcePack(const std::string &executable_path,
|
||||||
const std::string &resource_pack_path = "resources.pack");
|
const std::string &resource_pack_path = "resources.pack");
|
||||||
|
|
||||||
// Carga un archivo usando ResourceLoader como primera opción
|
// Carga un archivo usando ResourceLoader como primera opción
|
||||||
std::vector<uint8_t> loadFile(const std::string &filename);
|
std::vector<uint8_t> loadFile(const std::string &filename);
|
||||||
|
|
||||||
// Verifica si un archivo existe (pack o filesystem)
|
// Verifica si un archivo existe (pack o filesystem)
|
||||||
bool fileExists(const std::string &filename) const;
|
bool fileExists(const std::string &filename) const;
|
||||||
|
|
||||||
// Obtiene la ruta completa para archivos del sistema/config
|
// Obtiene la ruta completa para archivos del sistema/config
|
||||||
std::string getSystemPath(const std::string &filename) const;
|
std::string getSystemPath(const std::string &filename) const;
|
||||||
|
|
||||||
private:
|
private:
|
||||||
static bool resource_pack_enabled_;
|
static bool resource_pack_enabled_;
|
||||||
|
|
||||||
// Determina si un archivo debe cargarse del pack o del filesystem
|
// Determina si un archivo debe cargarse del pack o del filesystem
|
||||||
bool shouldUseResourcePack(const std::string &filepath) const;
|
bool shouldUseResourcePack(const std::string &filepath) const;
|
||||||
};
|
};
|
||||||
@@ -100,7 +100,7 @@ void Audio::stopAllSounds() const {
|
|||||||
|
|
||||||
// Realiza un fundido de salida de la música
|
// Realiza un fundido de salida de la música
|
||||||
void Audio::fadeOutMusic(int milliseconds) const {
|
void Audio::fadeOutMusic(int milliseconds) const {
|
||||||
if (music_enabled_) {
|
if (music_enabled_ && music_.state == MusicState::PLAYING) {
|
||||||
#ifndef NO_AUDIO
|
#ifndef NO_AUDIO
|
||||||
JA_FadeOutMusic(milliseconds);
|
JA_FadeOutMusic(milliseconds);
|
||||||
#endif
|
#endif
|
||||||
|
|||||||
@@ -75,11 +75,15 @@ class Audio {
|
|||||||
bool loop; // Indica si la última pista de música se debe reproducir en bucle
|
bool loop; // Indica si la última pista de música se debe reproducir en bucle
|
||||||
|
|
||||||
// Constructor para inicializar la música con valores predeterminados
|
// Constructor para inicializar la música con valores predeterminados
|
||||||
Music() : state(MusicState::STOPPED), loop(false) {}
|
Music()
|
||||||
|
: state(MusicState::STOPPED),
|
||||||
|
loop(false) {}
|
||||||
|
|
||||||
// Constructor para inicializar con valores específicos
|
// Constructor para inicializar con valores específicos
|
||||||
Music(MusicState init_state, std::string init_name, bool init_loop)
|
Music(MusicState init_state, std::string init_name, bool init_loop)
|
||||||
: state(init_state), name(std::move(init_name)), loop(init_loop) {}
|
: state(init_state),
|
||||||
|
name(std::move(init_name)),
|
||||||
|
loop(init_loop) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
// --- Variables de estado ---
|
// --- Variables de estado ---
|
||||||
|
|||||||
@@ -126,7 +126,7 @@ void Background::initializeTextures() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Actualiza la lógica del objeto
|
// Actualiza la lógica del objeto
|
||||||
void Background::update() {
|
void Background::update(float delta_time) {
|
||||||
// Actualiza la progresión y calcula transiciones
|
// Actualiza la progresión y calcula transiciones
|
||||||
if (!manual_mode_) {
|
if (!manual_mode_) {
|
||||||
updateProgression();
|
updateProgression();
|
||||||
@@ -136,10 +136,14 @@ void Background::update() {
|
|||||||
updateAlphaColorTexture();
|
updateAlphaColorTexture();
|
||||||
|
|
||||||
// Actualiza las nubes
|
// Actualiza las nubes
|
||||||
updateClouds();
|
updateClouds(delta_time);
|
||||||
|
|
||||||
// Calcula el frame de la hierba
|
// Actualiza timer de hierba
|
||||||
grass_sprite_->setSpriteClip(0, (10 * (counter_ / 20 % 2)), 320, 10);
|
grass_timer_ += delta_time;
|
||||||
|
|
||||||
|
// Calcula el frame de la hierba (alterna cada GRASS_FRAME_DURATION ms)
|
||||||
|
int grass_frame = static_cast<int>(grass_timer_ / GRASS_FRAME_DURATION) % 2;
|
||||||
|
grass_sprite_->setSpriteClip(0, (10 * grass_frame), 320, 10);
|
||||||
|
|
||||||
// Calcula el valor de alpha
|
// Calcula el valor de alpha
|
||||||
alpha_ = std::max((255 - (int)(255 * transition_)), 0);
|
alpha_ = std::max((255 - (int)(255 * transition_)), 0);
|
||||||
@@ -148,9 +152,6 @@ void Background::update() {
|
|||||||
sun_sprite_->setPosition(sun_path_.at(sun_index_));
|
sun_sprite_->setPosition(sun_path_.at(sun_index_));
|
||||||
moon_sprite_->setPosition(moon_path_.at(moon_index_));
|
moon_sprite_->setPosition(moon_path_.at(moon_index_));
|
||||||
|
|
||||||
// Incrementa el contador
|
|
||||||
++counter_;
|
|
||||||
|
|
||||||
// Compone todos los elementos del fondo en la textura
|
// Compone todos los elementos del fondo en la textura
|
||||||
fillCanvas();
|
fillCanvas();
|
||||||
}
|
}
|
||||||
@@ -314,12 +315,12 @@ void Background::updateCloudsSpeed() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Actualiza las nubes
|
// Actualiza las nubes
|
||||||
void Background::updateClouds() {
|
void Background::updateClouds(float deltaTime) {
|
||||||
// Mueve las nubes
|
// Mueve las nubes
|
||||||
top_clouds_sprite_a_->update();
|
top_clouds_sprite_a_->update(deltaTime);
|
||||||
top_clouds_sprite_b_->update();
|
top_clouds_sprite_b_->update(deltaTime);
|
||||||
bottom_clouds_sprite_a_->update();
|
bottom_clouds_sprite_a_->update(deltaTime);
|
||||||
bottom_clouds_sprite_b_->update();
|
bottom_clouds_sprite_b_->update(deltaTime);
|
||||||
|
|
||||||
// Calcula el offset de las nubes
|
// Calcula el offset de las nubes
|
||||||
if (top_clouds_sprite_a_->getPosX() < -top_clouds_sprite_a_->getWidth()) {
|
if (top_clouds_sprite_a_->getPosX() < -top_clouds_sprite_a_->getWidth()) {
|
||||||
|
|||||||
@@ -31,7 +31,7 @@ class Background {
|
|||||||
~Background(); // Destructor
|
~Background(); // Destructor
|
||||||
|
|
||||||
// --- Métodos principales ---
|
// --- Métodos principales ---
|
||||||
void update(); // Actualiza la lógica del objeto
|
void update(float delta_time); // Actualiza la lógica del objeto
|
||||||
void render(); // Dibuja el objeto
|
void render(); // Dibuja el objeto
|
||||||
void reset(); // Reinicia la progresión
|
void reset(); // Reinicia la progresión
|
||||||
|
|
||||||
@@ -107,7 +107,8 @@ class Background {
|
|||||||
float clouds_speed_ = 0; // Velocidad de las nubes
|
float clouds_speed_ = 0; // Velocidad de las nubes
|
||||||
float transition_ = 0; // Porcentaje de transición
|
float transition_ = 0; // Porcentaje de transición
|
||||||
size_t gradient_number_ = 0; // Índice de fondo degradado
|
size_t gradient_number_ = 0; // Índice de fondo degradado
|
||||||
size_t counter_ = 0; // Contador interno
|
float grass_timer_ = 0.0f; // Timer para animación de hierba (ms)
|
||||||
|
static constexpr float GRASS_FRAME_DURATION = 333.34f; // Duración por frame de hierba (20 frames * 16.67ms)
|
||||||
size_t alpha_color_texture_ = 0; // Transparencia de atenuación
|
size_t alpha_color_texture_ = 0; // Transparencia de atenuación
|
||||||
size_t previous_alpha_color_texture_ = 0; // Transparencia anterior
|
size_t previous_alpha_color_texture_ = 0; // Transparencia anterior
|
||||||
size_t sun_index_ = 0; // Índice del recorrido del sol
|
size_t sun_index_ = 0; // Índice del recorrido del sol
|
||||||
@@ -129,7 +130,7 @@ class Background {
|
|||||||
void renderBottomClouds(); // Dibuja las nubes inferiores
|
void renderBottomClouds(); // Dibuja las nubes inferiores
|
||||||
void fillCanvas(); // Compone todos los elementos en la textura
|
void fillCanvas(); // Compone todos los elementos en la textura
|
||||||
void updateAlphaColorTexture(); // Actualiza el alpha de la textura de atenuación
|
void updateAlphaColorTexture(); // Actualiza el alpha de la textura de atenuación
|
||||||
void updateClouds(); // Actualiza el movimiento de las nubes
|
void updateClouds(float deltaTime); // Actualiza el movimiento de las nubes (time-based)
|
||||||
void createSunPath(); // Precalcula el recorrido del sol
|
void createSunPath(); // Precalcula el recorrido del sol
|
||||||
void createMoonPath(); // Precalcula el recorrido de la luna
|
void createMoonPath(); // Precalcula el recorrido de la luna
|
||||||
};
|
};
|
||||||
@@ -11,24 +11,25 @@
|
|||||||
#include "texture.h" // Para Texture
|
#include "texture.h" // Para Texture
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
Balloon::Balloon(float x, float y, Type type, Size size, float vel_x, float speed, Uint16 creation_timer, SDL_FRect play_area, const std::shared_ptr<Texture> &texture, const std::vector<std::string> &animation)
|
Balloon::Balloon(const Config& config)
|
||||||
: sprite_(std::make_unique<AnimatedSprite>(texture, animation)),
|
: sprite_(std::make_unique<AnimatedSprite>(config.texture, config.animation)),
|
||||||
x_(x),
|
x_(config.x),
|
||||||
y_(y),
|
y_(config.y),
|
||||||
vx_(vel_x),
|
vx_(config.vel_x),
|
||||||
being_created_(creation_timer > 0),
|
being_created_(config.creation_counter > 0),
|
||||||
invulnerable_(creation_timer > 0),
|
invulnerable_(config.creation_counter > 0),
|
||||||
stopped_(creation_timer > 0),
|
stopped_(config.creation_counter > 0),
|
||||||
creation_counter_(creation_timer),
|
creation_counter_(config.creation_counter),
|
||||||
creation_counter_ini_(creation_timer),
|
creation_counter_ini_(config.creation_counter),
|
||||||
type_(type),
|
type_(config.type),
|
||||||
size_(size),
|
size_(config.size),
|
||||||
speed_(speed),
|
game_tempo_(config.game_tempo),
|
||||||
play_area_(play_area) {
|
play_area_(config.play_area),
|
||||||
|
sound_(config.sound) {
|
||||||
switch (type_) {
|
switch (type_) {
|
||||||
case Type::BALLOON: {
|
case Type::BALLOON: {
|
||||||
vy_ = 0;
|
vy_ = 0;
|
||||||
max_vy_ = 3.0F;
|
max_vy_ = 3.0F * 60.0F; // Convert from frames to seconds (180 pixels/s)
|
||||||
|
|
||||||
const int INDEX = static_cast<int>(size_);
|
const int INDEX = static_cast<int>(size_);
|
||||||
gravity_ = param.balloon.settings.at(INDEX).grav;
|
gravity_ = param.balloon.settings.at(INDEX).grav;
|
||||||
@@ -37,9 +38,8 @@ Balloon::Balloon(float x, float y, Type type, Size size, float vel_x, float spee
|
|||||||
power_ = POWER.at(INDEX);
|
power_ = POWER.at(INDEX);
|
||||||
menace_ = MENACE.at(INDEX);
|
menace_ = MENACE.at(INDEX);
|
||||||
score_ = SCORE.at(INDEX);
|
score_ = SCORE.at(INDEX);
|
||||||
bouncing_sound_ = BOUNCING_SOUND.at(INDEX);
|
sound_.bouncing_file = BOUNCING_SOUND.at(INDEX);
|
||||||
popping_sound_ = POPPING_SOUND.at(INDEX);
|
sound_.popping_file = POPPING_SOUND.at(INDEX);
|
||||||
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -52,27 +52,25 @@ Balloon::Balloon(float x, float y, Type type, Size size, float vel_x, float spee
|
|||||||
power_ = POWER.at(INDEX);
|
power_ = POWER.at(INDEX);
|
||||||
menace_ = MENACE.at(INDEX);
|
menace_ = MENACE.at(INDEX);
|
||||||
score_ = SCORE.at(INDEX);
|
score_ = SCORE.at(INDEX);
|
||||||
bouncing_sound_ = BOUNCING_SOUND.at(INDEX);
|
sound_.bouncing_file = BOUNCING_SOUND.at(INDEX);
|
||||||
popping_sound_ = POPPING_SOUND.at(INDEX);
|
sound_.popping_file = POPPING_SOUND.at(INDEX);
|
||||||
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
case Type::POWERBALL: {
|
case Type::POWERBALL: {
|
||||||
constexpr int INDEX = 3;
|
constexpr int INDEX = 3;
|
||||||
h_ = w_ = WIDTH.at(4);
|
h_ = w_ = WIDTH.at(4);
|
||||||
bouncing_sound_ = BOUNCING_SOUND.at(3);
|
sound_.bouncing_file = BOUNCING_SOUND.at(3);
|
||||||
popping_sound_ = "power_ball_explosion.wav";
|
sound_.popping_file = "power_ball_explosion.wav";
|
||||||
power_ = score_ = menace_ = 0;
|
power_ = score_ = menace_ = 0;
|
||||||
|
|
||||||
vy_ = 0;
|
vy_ = 0;
|
||||||
max_vy_ = 3.0F;
|
max_vy_ = 3.0F * 60.0F; // Convert from frames to seconds (180 pixels/s)
|
||||||
gravity_ = param.balloon.settings.at(INDEX).grav;
|
gravity_ = param.balloon.settings.at(INDEX).grav;
|
||||||
default_vy_ = param.balloon.settings.at(INDEX).vel;
|
default_vy_ = param.balloon.settings.at(INDEX).vel;
|
||||||
|
|
||||||
sprite_->setRotate(creation_timer <= 0);
|
sprite_->setRotate(config.creation_counter <= 0);
|
||||||
sprite_->setRotateAmount(vx_ > 0.0F ? 2.0 : -2.0);
|
sprite_->setRotateAmount(vx_ > 0.0F ? 120.0 : -120.0); // Convert from 2 degrees/frame to 120 degrees/second
|
||||||
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -91,6 +89,12 @@ Balloon::Balloon(float x, float y, Type type, Size size, float vel_x, float spee
|
|||||||
|
|
||||||
// Establece la animación a usar
|
// Establece la animación a usar
|
||||||
setAnimation();
|
setAnimation();
|
||||||
|
|
||||||
|
// Si no se está creando (creation_counter = 0), asegurar estado activo
|
||||||
|
if (!being_created_) {
|
||||||
|
start();
|
||||||
|
setInvulnerable(false);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Centra el globo en la posición X
|
// Centra el globo en la posición X
|
||||||
@@ -137,19 +141,20 @@ void Balloon::render() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Actualiza la posición y estados del globo
|
// Actualiza la posición y estados del globo (time-based)
|
||||||
void Balloon::move() {
|
void Balloon::move(float deltaTime) {
|
||||||
if (isStopped()) {
|
if (isStopped()) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
handleHorizontalMovement();
|
handleHorizontalMovement(deltaTime);
|
||||||
handleVerticalMovement();
|
handleVerticalMovement(deltaTime);
|
||||||
applyGravity();
|
applyGravity(deltaTime);
|
||||||
}
|
}
|
||||||
|
|
||||||
void Balloon::handleHorizontalMovement() {
|
void Balloon::handleHorizontalMovement(float deltaTime) {
|
||||||
x_ += vx_ * speed_;
|
// DeltaTime en segundos: velocidad (pixels/s) * tempo * tiempo (s)
|
||||||
|
x_ += vx_ * game_tempo_ * deltaTime;
|
||||||
|
|
||||||
const int CLIP = 2;
|
const int CLIP = 2;
|
||||||
const float MIN_X = play_area_.x - CLIP;
|
const float MIN_X = play_area_.x - CLIP;
|
||||||
@@ -160,8 +165,9 @@ void Balloon::handleHorizontalMovement() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void Balloon::handleVerticalMovement() {
|
void Balloon::handleVerticalMovement(float deltaTime) {
|
||||||
y_ += vy_ * speed_;
|
// DeltaTime en segundos: velocidad (pixels/s) * tempo * tiempo (s)
|
||||||
|
y_ += vy_ * game_tempo_ * deltaTime;
|
||||||
|
|
||||||
if (shouldCheckTopCollision()) {
|
if (shouldCheckTopCollision()) {
|
||||||
handleTopCollision();
|
handleTopCollision();
|
||||||
@@ -216,41 +222,37 @@ void Balloon::handleBottomCollision() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void Balloon::applyGravity() {
|
void Balloon::applyGravity(float deltaTime) {
|
||||||
/*
|
// DeltaTime en segundos: aceleración (pixels/s²) * tempo * tiempo (s)
|
||||||
Para aplicar la gravedad, el diseño original la aplicaba en cada iteración del bucle
|
vy_ += gravity_ * game_tempo_ * deltaTime;
|
||||||
Al añadir el modificador de velocidad se reduce la distancia que recorre el objeto y por
|
|
||||||
tanto recibe mas gravedad. Para solucionarlo se va a aplicar la gravedad cuando se haya
|
|
||||||
recorrido una distancia igual a la velocidad en Y, que era el cálculo inicial
|
|
||||||
*/
|
|
||||||
|
|
||||||
travel_y_ += speed_;
|
|
||||||
|
|
||||||
if (travel_y_ >= 1.0F) {
|
|
||||||
travel_y_ -= 1.0F;
|
|
||||||
vy_ += gravity_;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void Balloon::playBouncingSound() {
|
void Balloon::playBouncingSound() {
|
||||||
if (bouncing_sound_enabled_) {
|
if (sound_.enabled && sound_.bouncing_enabled) {
|
||||||
playSound(bouncing_sound_);
|
Audio::get()->playSound(sound_.bouncing_file);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Actualiza al globo a su posicion, animación y controla los contadores
|
void Balloon::playPoppingSound() {
|
||||||
void Balloon::update() {
|
if (sound_.enabled && sound_.poping_enabled) {
|
||||||
move();
|
Audio::get()->playSound(sound_.popping_file);
|
||||||
updateState();
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Actualiza al globo a su posicion, animación y controla los contadores (time-based)
|
||||||
|
void Balloon::update(float deltaTime) {
|
||||||
|
move(deltaTime);
|
||||||
|
updateState(deltaTime);
|
||||||
updateBounceEffect();
|
updateBounceEffect();
|
||||||
shiftSprite();
|
shiftSprite();
|
||||||
shiftColliders();
|
shiftColliders();
|
||||||
sprite_->update();
|
sprite_->update(deltaTime);
|
||||||
++counter_;
|
// Contador interno con deltaTime en segundos
|
||||||
|
counter_ += deltaTime;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Actualiza los estados del globo
|
// Actualiza los estados del globo (time-based)
|
||||||
void Balloon::updateState() {
|
void Balloon::updateState(float deltaTime) {
|
||||||
// Si se está creando
|
// Si se está creando
|
||||||
if (isBeingCreated()) {
|
if (isBeingCreated()) {
|
||||||
// Actualiza el valor de las variables
|
// Actualiza el valor de las variables
|
||||||
@@ -259,9 +261,14 @@ void Balloon::updateState() {
|
|||||||
|
|
||||||
if (creation_counter_ > 0) {
|
if (creation_counter_ > 0) {
|
||||||
// Desplaza lentamente el globo hacia abajo y hacia un lado
|
// Desplaza lentamente el globo hacia abajo y hacia un lado
|
||||||
if (creation_counter_ % 10 == 0) {
|
// Cada 10/60 segundos (equivalente a 10 frames a 60fps)
|
||||||
|
movement_accumulator_ += deltaTime;
|
||||||
|
|
||||||
|
constexpr float MOVEMENT_INTERVAL_S = 10.0f / 60.0f; // 10 frames = ~0.167s
|
||||||
|
if (movement_accumulator_ >= MOVEMENT_INTERVAL_S) {
|
||||||
|
movement_accumulator_ -= MOVEMENT_INTERVAL_S;
|
||||||
y_++;
|
y_++;
|
||||||
x_ += vx_;
|
x_ += vx_ / 60.0f; // Convierte de pixels/segundo a pixels/frame para movimiento discreto
|
||||||
|
|
||||||
// Comprueba no se salga por los laterales
|
// Comprueba no se salga por los laterales
|
||||||
const int MIN_X = play_area_.x;
|
const int MIN_X = play_area_.x;
|
||||||
@@ -269,11 +276,12 @@ void Balloon::updateState() {
|
|||||||
|
|
||||||
if (x_ < MIN_X || x_ > MAX_X) {
|
if (x_ < MIN_X || x_ > MAX_X) {
|
||||||
// Corrige y cambia el sentido de la velocidad
|
// Corrige y cambia el sentido de la velocidad
|
||||||
x_ -= vx_;
|
x_ -= vx_ / 60.0f;
|
||||||
vx_ = -vx_;
|
vx_ = -vx_;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
--creation_counter_;
|
creation_counter_ -= deltaTime;
|
||||||
|
if (creation_counter_ < 0) creation_counter_ = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
else {
|
else {
|
||||||
@@ -307,11 +315,14 @@ void Balloon::setAnimation() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Establece el frame de animación
|
// Establece el frame de animación
|
||||||
|
std::string chosen_animation;
|
||||||
if (use_reversed_colors_) {
|
if (use_reversed_colors_) {
|
||||||
sprite_->setCurrentAnimation(creating_animation);
|
chosen_animation = creating_animation;
|
||||||
} else {
|
} else {
|
||||||
sprite_->setCurrentAnimation(isBeingCreated() ? creating_animation : normal_animation);
|
chosen_animation = isBeingCreated() ? creating_animation : normal_animation;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
sprite_->setCurrentAnimation(chosen_animation);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Detiene el globo
|
// Detiene el globo
|
||||||
@@ -368,23 +379,8 @@ void Balloon::useNormalColor() {
|
|||||||
setAnimation();
|
setAnimation();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Reproduce sonido
|
|
||||||
void Balloon::playSound(const std::string &name) const {
|
|
||||||
if (!sound_enabled_) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
static auto *audio_ = Audio::get();
|
|
||||||
audio_->playSound(name);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Explota el globo
|
// Explota el globo
|
||||||
void Balloon::pop(bool should_sound) {
|
void Balloon::pop(bool should_sound) {
|
||||||
if (should_sound) {
|
if (should_sound) { playPoppingSound(); }
|
||||||
if (poping_sound_enabled_) {
|
|
||||||
playSound(popping_sound_);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
enabled_ = false;
|
enabled_ = false;
|
||||||
}
|
}
|
||||||
168
source/balloon.h
168
source/balloon.h
@@ -25,15 +25,23 @@ class Balloon {
|
|||||||
static constexpr std::array<int, 5> WIDTH = {10, 16, 26, 48, 49};
|
static constexpr std::array<int, 5> WIDTH = {10, 16, 26, 48, 49};
|
||||||
|
|
||||||
static constexpr std::array<std::string_view, 4> BOUNCING_SOUND = {
|
static constexpr std::array<std::string_view, 4> BOUNCING_SOUND = {
|
||||||
"balloon_bounce0.wav", "balloon_bounce1.wav", "balloon_bounce2.wav", "balloon_bounce3.wav"};
|
"balloon_bounce0.wav",
|
||||||
|
"balloon_bounce1.wav",
|
||||||
|
"balloon_bounce2.wav",
|
||||||
|
"balloon_bounce3.wav"};
|
||||||
|
|
||||||
static constexpr std::array<std::string_view, 4> POPPING_SOUND = {
|
static constexpr std::array<std::string_view, 4> POPPING_SOUND = {
|
||||||
"balloon_pop0.wav", "balloon_pop1.wav", "balloon_pop2.wav", "balloon_pop3.wav"};
|
"balloon_pop0.wav",
|
||||||
|
"balloon_pop1.wav",
|
||||||
|
"balloon_pop2.wav",
|
||||||
|
"balloon_pop3.wav"};
|
||||||
|
|
||||||
static constexpr float VELX_POSITIVE = 0.7F;
|
// Velocidades horizontales en pixels/segundo (convertidas desde 0.7 pixels/frame a 60fps)
|
||||||
static constexpr float VELX_NEGATIVE = -0.7F;
|
static constexpr float VELX_POSITIVE = 0.7F * 60.0F; // 42 pixels/segundo
|
||||||
|
static constexpr float VELX_NEGATIVE = -0.7F * 60.0F; // -42 pixels/segundo
|
||||||
|
|
||||||
static constexpr std::array<float, 5> SPEED = {0.60F, 0.70F, 0.80F, 0.90F, 1.00F};
|
// Multiplicadores de tempo del juego (sin cambios, son puros multiplicadores)
|
||||||
|
static constexpr std::array<float, 5> GAME_TEMPO = {0.60F, 0.70F, 0.80F, 0.90F, 1.00F};
|
||||||
|
|
||||||
static constexpr int POWERBALL_SCREENPOWER_MINIMUM = 10;
|
static constexpr int POWERBALL_SCREENPOWER_MINIMUM = 10;
|
||||||
static constexpr int POWERBALL_COUNTER = 8;
|
static constexpr int POWERBALL_COUNTER = 8;
|
||||||
@@ -52,26 +60,40 @@ class Balloon {
|
|||||||
POWERBALL = 2, // Globo de poder
|
POWERBALL = 2, // Globo de poder
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// --- Estructura para manejo de sonido ---
|
||||||
|
struct Sound {
|
||||||
|
std::string bouncing_file; // Archivo de sonido al rebotar
|
||||||
|
std::string popping_file; // Archivo de sonido al explotar
|
||||||
|
bool bouncing_enabled = false; // Si debe sonar el globo al rebotar
|
||||||
|
bool poping_enabled = true; // Si debe sonar el globo al explotar
|
||||||
|
bool enabled = true; // Indica si los globos deben hacer algun sonido
|
||||||
|
};
|
||||||
|
|
||||||
|
// --- Estructura de configuración para inicialización ---
|
||||||
|
struct Config {
|
||||||
|
float x = 0.0F;
|
||||||
|
float y = 0.0F;
|
||||||
|
Type type = Type::BALLOON;
|
||||||
|
Size size = Size::EXTRALARGE;
|
||||||
|
float vel_x = VELX_POSITIVE;
|
||||||
|
float game_tempo = GAME_TEMPO.at(0);
|
||||||
|
float creation_counter = 0.0f;
|
||||||
|
SDL_FRect play_area = {.x = 0.0F, .y = 0.0F, .w = 0.0F, .h = 0.0F};
|
||||||
|
std::shared_ptr<Texture> texture = nullptr;
|
||||||
|
std::vector<std::string> animation;
|
||||||
|
Sound sound;
|
||||||
|
};
|
||||||
|
|
||||||
// --- Constructores y destructor ---
|
// --- Constructores y destructor ---
|
||||||
Balloon(
|
Balloon(const Config& config);
|
||||||
float x,
|
|
||||||
float y,
|
|
||||||
Type type,
|
|
||||||
Size size,
|
|
||||||
float vel_x,
|
|
||||||
float speed,
|
|
||||||
Uint16 creation_timer,
|
|
||||||
SDL_FRect play_area,
|
|
||||||
const std::shared_ptr<Texture>& texture,
|
|
||||||
const std::vector<std::string>& animation);
|
|
||||||
~Balloon() = default;
|
~Balloon() = default;
|
||||||
|
|
||||||
// --- Métodos principales ---
|
// --- Métodos principales ---
|
||||||
void alignTo(int x); // Centra el globo en la posición X
|
void alignTo(int x); // Centra el globo en la posición X
|
||||||
void render(); // Pinta el globo en la pantalla
|
void render(); // Pinta el globo en la pantalla
|
||||||
void move(); // Actualiza la posición y estados del globo
|
void move(float deltaTime); // Actualiza la posición y estados del globo (time-based)
|
||||||
void update(); // Actualiza el globo (posición, animación, contadores)
|
void update(float deltaTime); // Actualiza el globo (posición, animación, contadores) (time-based)
|
||||||
void stop(); // Detiene el globo
|
void stop(); // Detiene el globo
|
||||||
void start(); // Pone el globo en movimiento
|
void start(); // Pone el globo en movimiento
|
||||||
void pop(bool should_sound = false); // Explota el globo
|
void pop(bool should_sound = false); // Explota el globo
|
||||||
|
|
||||||
@@ -100,11 +122,11 @@ class Balloon {
|
|||||||
|
|
||||||
// --- Setters ---
|
// --- Setters ---
|
||||||
void setVelY(float vel_y) { vy_ = vel_y; }
|
void setVelY(float vel_y) { vy_ = vel_y; }
|
||||||
void setSpeed(float speed) { speed_ = speed; }
|
void setGameTempo(float tempo) { game_tempo_ = tempo; }
|
||||||
void setInvulnerable(bool value) { invulnerable_ = value; }
|
void setInvulnerable(bool value) { invulnerable_ = value; }
|
||||||
void setBouncingSound(bool value) { bouncing_sound_enabled_ = value; }
|
void setBouncingSound(bool value) { sound_.bouncing_enabled = value; }
|
||||||
void setPoppingSound(bool value) { poping_sound_enabled_ = value; }
|
void setPoppingSound(bool value) { sound_.poping_enabled = value; }
|
||||||
void setSound(bool value) { sound_enabled_ = value; }
|
void setSound(bool value) { sound_.enabled = value; }
|
||||||
|
|
||||||
private:
|
private:
|
||||||
// --- Estructura para el efecto de rebote ---
|
// --- Estructura para el efecto de rebote ---
|
||||||
@@ -114,10 +136,28 @@ class Balloon {
|
|||||||
|
|
||||||
// Tablas de valores predefinidos para el efecto de rebote
|
// Tablas de valores predefinidos para el efecto de rebote
|
||||||
static constexpr std::array<float, BOUNCE_FRAMES> HORIZONTAL_ZOOM_VALUES = {
|
static constexpr std::array<float, BOUNCE_FRAMES> HORIZONTAL_ZOOM_VALUES = {
|
||||||
1.10F, 1.05F, 1.00F, 0.95F, 0.90F, 0.95F, 1.00F, 1.02F, 1.05F, 1.02F};
|
1.10F,
|
||||||
|
1.05F,
|
||||||
|
1.00F,
|
||||||
|
0.95F,
|
||||||
|
0.90F,
|
||||||
|
0.95F,
|
||||||
|
1.00F,
|
||||||
|
1.02F,
|
||||||
|
1.05F,
|
||||||
|
1.02F};
|
||||||
|
|
||||||
static constexpr std::array<float, BOUNCE_FRAMES> VERTICAL_ZOOM_VALUES = {
|
static constexpr std::array<float, BOUNCE_FRAMES> VERTICAL_ZOOM_VALUES = {
|
||||||
0.90F, 0.95F, 1.00F, 1.05F, 1.10F, 1.05F, 1.00F, 0.98F, 0.95F, 0.98F};
|
0.90F,
|
||||||
|
0.95F,
|
||||||
|
1.00F,
|
||||||
|
1.05F,
|
||||||
|
1.10F,
|
||||||
|
1.05F,
|
||||||
|
1.00F,
|
||||||
|
0.98F,
|
||||||
|
0.95F,
|
||||||
|
0.98F};
|
||||||
|
|
||||||
// Estado del efecto
|
// Estado del efecto
|
||||||
bool enabled_ = false; // Si el efecto está activo
|
bool enabled_ = false; // Si el efecto está activo
|
||||||
@@ -203,52 +243,48 @@ class Balloon {
|
|||||||
std::unique_ptr<AnimatedSprite> sprite_; // Sprite del objeto globo
|
std::unique_ptr<AnimatedSprite> sprite_; // Sprite del objeto globo
|
||||||
|
|
||||||
// --- Variables de estado y físicas ---
|
// --- Variables de estado y físicas ---
|
||||||
float x_; // Posición X
|
float x_; // Posición X
|
||||||
float y_; // Posición Y
|
float y_; // Posición Y
|
||||||
float w_; // Ancho
|
float w_; // Ancho
|
||||||
float h_; // Alto
|
float h_; // Alto
|
||||||
float vx_; // Velocidad X
|
float vx_; // Velocidad X
|
||||||
float vy_; // Velocidad Y
|
float vy_; // Velocidad Y
|
||||||
float gravity_; // Aceleración en Y
|
float gravity_; // Aceleración en Y
|
||||||
float default_vy_; // Velocidad inicial al rebotar
|
float default_vy_; // Velocidad inicial al rebotar
|
||||||
float max_vy_; // Máxima velocidad en Y
|
float max_vy_; // Máxima velocidad en Y
|
||||||
bool being_created_; // Si el globo se está creando
|
bool being_created_; // Si el globo se está creando
|
||||||
bool enabled_ = true; // Si el globo está activo
|
bool enabled_ = true; // Si el globo está activo
|
||||||
bool invulnerable_; // Si el globo es invulnerable
|
bool invulnerable_; // Si el globo es invulnerable
|
||||||
bool stopped_; // Si el globo está parado
|
bool stopped_; // Si el globo está parado
|
||||||
bool use_reversed_colors_ = false; // Si se usa el color alternativo
|
bool use_reversed_colors_ = false; // Si se usa el color alternativo
|
||||||
Circle collider_; // Círculo de colisión
|
Circle collider_; // Círculo de colisión
|
||||||
Uint16 creation_counter_; // Temporizador de creación
|
float creation_counter_; // Temporizador de creación
|
||||||
Uint16 creation_counter_ini_; // Valor inicial del temporizador de creación
|
float creation_counter_ini_; // Valor inicial del temporizador de creación
|
||||||
Uint16 score_; // Puntos al destruir el globo
|
Uint16 score_; // Puntos al destruir el globo
|
||||||
Type type_; // Tipo de globo
|
Type type_; // Tipo de globo
|
||||||
Size size_; // Tamaño de globo
|
Size size_; // Tamaño de globo
|
||||||
Uint8 menace_; // Amenaza que genera el globo
|
Uint8 menace_; // Amenaza que genera el globo
|
||||||
Uint32 counter_ = 0; // Contador interno
|
Uint32 counter_ = 0; // Contador interno
|
||||||
float travel_y_ = 1.0F; // Distancia a recorrer en Y antes de aplicar gravedad
|
float game_tempo_; // Multiplicador de tempo del juego
|
||||||
float speed_; // Velocidad del globo
|
float movement_accumulator_ = 0.0f; // Acumulador para movimiento durante creación (deltaTime)
|
||||||
Uint8 power_; // Poder que alberga el globo
|
Uint8 power_; // Poder que alberga el globo
|
||||||
SDL_FRect play_area_; // Zona de movimiento del globo
|
SDL_FRect play_area_; // Zona de movimiento del globo
|
||||||
std::string bouncing_sound_; // Archivo de sonido al rebotar
|
Sound sound_; // Configuración de sonido del globo
|
||||||
std::string popping_sound_; // Archivo de sonido al explotar
|
BounceEffect bounce_effect_; // Efecto de rebote
|
||||||
bool bouncing_sound_enabled_ = false; // Si debe sonar el globo al rebotar
|
|
||||||
bool poping_sound_enabled_ = true; // Si debe sonar el globo al explotar
|
|
||||||
bool sound_enabled_ = true; // Indica si los globos deben hacer algun sonido
|
|
||||||
BounceEffect bounce_effect_; // Efecto de rebote
|
|
||||||
|
|
||||||
// --- Posicionamiento y transformación ---
|
// --- Posicionamiento y transformación ---
|
||||||
void shiftColliders(); // Alinea el círculo de colisión con el sprite
|
void shiftColliders(); // Alinea el círculo de colisión con el sprite
|
||||||
void shiftSprite(); // Alinea el sprite en pantalla
|
void shiftSprite(); // Alinea el sprite en pantalla
|
||||||
|
|
||||||
// --- Animación y sonido ---
|
// --- Animación y sonido ---
|
||||||
void setAnimation(); // Establece la animación correspondiente
|
void setAnimation(); // Establece la animación correspondiente
|
||||||
void playSound(const std::string& name) const; // Reproduce un sonido por nombre
|
void playBouncingSound(); // Reproduce el sonido de rebote
|
||||||
void playBouncingSound(); // Reproduce el sonido de rebote
|
void playPoppingSound(); // Reproduce el sonido de reventar
|
||||||
|
|
||||||
// --- Movimiento y física ---
|
// --- Movimiento y física ---
|
||||||
void handleHorizontalMovement(); // Maneja el movimiento horizontal
|
void handleHorizontalMovement(float deltaTime); // Maneja el movimiento horizontal (time-based)
|
||||||
void handleVerticalMovement(); // Maneja el movimiento vertical
|
void handleVerticalMovement(float deltaTime); // Maneja el movimiento vertical (time-based)
|
||||||
void applyGravity(); // Aplica la gravedad al objeto
|
void applyGravity(float deltaTime); // Aplica la gravedad al objeto (time-based)
|
||||||
|
|
||||||
// --- Rebote ---
|
// --- Rebote ---
|
||||||
void enableBounceEffect(); // Activa el efecto de rebote
|
void enableBounceEffect(); // Activa el efecto de rebote
|
||||||
@@ -263,5 +299,5 @@ class Balloon {
|
|||||||
void handleBottomCollision(); // Maneja la colisión inferior
|
void handleBottomCollision(); // Maneja la colisión inferior
|
||||||
|
|
||||||
// --- Lógica de estado ---
|
// --- Lógica de estado ---
|
||||||
void updateState(); // Actualiza los estados del globo
|
void updateState(float deltaTime); // Actualiza los estados del globo (time-based)
|
||||||
};
|
};
|
||||||
@@ -155,7 +155,7 @@ auto BalloonFormations::parseBalloonLine(const std::string& line, const std::map
|
|||||||
return std::nullopt;
|
return std::nullopt;
|
||||||
}
|
}
|
||||||
|
|
||||||
int creation_time = DEFAULT_CREATION_TIME + evaluateExpression(tokens.at(6), variables);
|
float creation_time = CREATION_TIME + evaluateExpression(tokens.at(6), variables); // Base time + offset from formations.txt
|
||||||
|
|
||||||
return SpawnParams(x + offset, y, vel_x, type, size, creation_time);
|
return SpawnParams(x + offset, y, vel_x, type, size, creation_time);
|
||||||
} catch (const std::exception&) {
|
} catch (const std::exception&) {
|
||||||
@@ -168,7 +168,7 @@ auto BalloonFormations::evaluateExpression(const std::string& expr, const std::m
|
|||||||
|
|
||||||
// Si es un número directo
|
// Si es un número directo
|
||||||
if ((std::isdigit(trimmed_expr.at(0)) != 0) || (trimmed_expr.at(0) == '-' && trimmed_expr.length() > 1)) {
|
if ((std::isdigit(trimmed_expr.at(0)) != 0) || (trimmed_expr.at(0) == '-' && trimmed_expr.length() > 1)) {
|
||||||
return std::stoi(trimmed_expr);
|
return std::stof(trimmed_expr);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Si es una variable simple
|
// Si es una variable simple
|
||||||
@@ -205,7 +205,7 @@ auto BalloonFormations::evaluateSimpleExpression(const std::string& expr, const
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Si no se encuentra operador, intentar como variable o número
|
// Si no se encuentra operador, intentar como variable o número
|
||||||
return variables.find(expr) != variables.end() ? variables.at(expr) : std::stoi(expr);
|
return variables.find(expr) != variables.end() ? variables.at(expr) : std::stof(expr);
|
||||||
}
|
}
|
||||||
|
|
||||||
auto BalloonFormations::trim(const std::string& str) -> std::string {
|
auto BalloonFormations::trim(const std::string& str) -> std::string {
|
||||||
@@ -235,10 +235,10 @@ void BalloonFormations::createFloaterVariants() {
|
|||||||
#ifdef _DEBUG
|
#ifdef _DEBUG
|
||||||
void BalloonFormations::addTestFormation() {
|
void BalloonFormations::addTestFormation() {
|
||||||
std::vector<SpawnParams> test_params = {
|
std::vector<SpawnParams> test_params = {
|
||||||
{10, -BLOCK, 0, Balloon::Type::FLOATER, Balloon::Size::SMALL, 200},
|
{10, -BLOCK, 0, Balloon::Type::FLOATER, Balloon::Size::SMALL, 3.334f}, // 200 frames ÷ 60fps = 3.334s
|
||||||
{50, -BLOCK, 0, Balloon::Type::FLOATER, Balloon::Size::MEDIUM, 200},
|
{50, -BLOCK, 0, Balloon::Type::FLOATER, Balloon::Size::MEDIUM, 3.334f}, // 200 frames ÷ 60fps = 3.334s
|
||||||
{90, -BLOCK, 0, Balloon::Type::FLOATER, Balloon::Size::LARGE, 200},
|
{90, -BLOCK, 0, Balloon::Type::FLOATER, Balloon::Size::LARGE, 3.334f}, // 200 frames ÷ 60fps = 3.334s
|
||||||
{140, -BLOCK, 0, Balloon::Type::FLOATER, Balloon::Size::EXTRALARGE, 200}};
|
{140, -BLOCK, 0, Balloon::Type::FLOATER, Balloon::Size::EXTRALARGE, 3.334f}}; // 200 frames ÷ 60fps = 3.334s
|
||||||
|
|
||||||
formations_.at(99) = Formation(test_params);
|
formations_.at(99) = Formation(test_params);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,19 +15,24 @@ class BalloonFormations {
|
|||||||
public:
|
public:
|
||||||
// --- Estructuras ---
|
// --- Estructuras ---
|
||||||
struct SpawnParams {
|
struct SpawnParams {
|
||||||
int x = 0; // Posición en el eje X donde crear el globo
|
float x = 0; // Posición en el eje X donde crear el globo
|
||||||
int y = 0; // Posición en el eje Y donde crear el globo
|
float y = 0; // Posición en el eje Y donde crear el globo
|
||||||
float vel_x = 0.0F; // Velocidad inicial en el eje X
|
float vel_x = 0.0F; // Velocidad inicial en el eje X
|
||||||
Balloon::Type type = Balloon::Type::BALLOON; // Tipo de globo
|
Balloon::Type type = Balloon::Type::BALLOON; // Tipo de globo
|
||||||
Balloon::Size size = Balloon::Size::SMALL; // Tamaño de globo
|
Balloon::Size size = Balloon::Size::SMALL; // Tamaño de globo
|
||||||
int creation_counter = 0; // Temporizador para la creación del globo
|
float creation_counter = 0.0f; // Temporizador para la creación del globo
|
||||||
|
|
||||||
// Constructor por defecto
|
// Constructor por defecto
|
||||||
SpawnParams() = default;
|
SpawnParams() = default;
|
||||||
|
|
||||||
// Constructor con parámetros
|
// Constructor con parámetros
|
||||||
SpawnParams(int x, int y, float vel_x, Balloon::Type type, Balloon::Size size, int creation_counter)
|
SpawnParams(float x, float y, float vel_x, Balloon::Type type, Balloon::Size size, float creation_counter)
|
||||||
: x(x), y(y), vel_x(vel_x), type(type), size(size), creation_counter(creation_counter) {}
|
: x(x),
|
||||||
|
y(y),
|
||||||
|
vel_x(vel_x),
|
||||||
|
type(type),
|
||||||
|
size(size),
|
||||||
|
creation_counter(creation_counter) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
struct Formation {
|
struct Formation {
|
||||||
@@ -77,7 +82,8 @@ class BalloonFormations {
|
|||||||
private:
|
private:
|
||||||
// --- Constantes ---
|
// --- Constantes ---
|
||||||
static constexpr int BALLOON_SPAWN_HEIGHT = 208; // Altura desde el suelo en la que aparecen los globos
|
static constexpr int BALLOON_SPAWN_HEIGHT = 208; // Altura desde el suelo en la que aparecen los globos
|
||||||
static constexpr int DEFAULT_CREATION_TIME = 200; // Tiempo base de creación de los globos para las formaciones
|
static constexpr float CREATION_TIME = 5.0f; // Tiempo base de creación de los globos en segundos (300 frames ÷ 60fps = 5.0s)
|
||||||
|
static constexpr float DEFAULT_CREATION_TIME = 3.334f; // Tiempo base de creación de los globos en segundos (200 frames ÷ 60fps = 3.334s)
|
||||||
|
|
||||||
// --- Variables ---
|
// --- Variables ---
|
||||||
std::vector<Formation> formations_; // Vector con todas las formaciones disponibles
|
std::vector<Formation> formations_; // Vector con todas las formaciones disponibles
|
||||||
|
|||||||
@@ -17,7 +17,9 @@
|
|||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
BalloonManager::BalloonManager(IStageInfo *stage_info)
|
BalloonManager::BalloonManager(IStageInfo *stage_info)
|
||||||
: explosions_(std::make_unique<Explosions>()), balloon_formations_(std::make_unique<BalloonFormations>()), stage_info_(stage_info) { init(); }
|
: explosions_(std::make_unique<Explosions>()),
|
||||||
|
balloon_formations_(std::make_unique<BalloonFormations>()),
|
||||||
|
stage_info_(stage_info) { init(); }
|
||||||
|
|
||||||
// Inicializa
|
// Inicializa
|
||||||
void BalloonManager::init() {
|
void BalloonManager::init() {
|
||||||
@@ -60,13 +62,13 @@ void BalloonManager::init() {
|
|||||||
explosions_->addTexture(3, explosions_textures_.at(3), explosions_animations_.at(3));
|
explosions_->addTexture(3, explosions_textures_.at(3), explosions_animations_.at(3));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Actualiza
|
// Actualiza (time-based)
|
||||||
void BalloonManager::update() {
|
void BalloonManager::update(float deltaTime) {
|
||||||
for (const auto &balloon : balloons_) {
|
for (const auto &balloon : balloons_) {
|
||||||
balloon->update();
|
balloon->update(deltaTime);
|
||||||
}
|
}
|
||||||
updateBalloonDeployCounter();
|
updateBalloonDeployCounter(deltaTime);
|
||||||
explosions_->update();
|
explosions_->update(deltaTime);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Renderiza los objetos
|
// Renderiza los objetos
|
||||||
@@ -79,12 +81,12 @@ void BalloonManager::render() {
|
|||||||
|
|
||||||
// Crea una formación de globos
|
// Crea una formación de globos
|
||||||
void BalloonManager::deployRandomFormation(int stage) {
|
void BalloonManager::deployRandomFormation(int stage) {
|
||||||
// Solo despliega una formación enemiga si ha pasado cierto tiempo desde la última
|
// Solo despliega una formación enemiga si el timer ha llegado a cero
|
||||||
if (balloon_deploy_counter_ == 0) {
|
if (balloon_deploy_counter_ <= 0.0f) {
|
||||||
// En este punto se decide entre crear una powerball o una formación enemiga
|
// En este punto se decide entre crear una powerball o una formación enemiga
|
||||||
if ((rand() % 100 < 15) && (canPowerBallBeCreated())) {
|
if ((rand() % 100 < 15) && (canPowerBallBeCreated())) {
|
||||||
createPowerBall(); // Crea una powerball
|
createPowerBall(); // Crea una powerball
|
||||||
balloon_deploy_counter_ = 10; // Da un poco de margen para que se creen mas globos
|
balloon_deploy_counter_ = POWERBALL_DEPLOY_DELAY; // Resetea con pequeño retraso
|
||||||
} else {
|
} else {
|
||||||
// Decrementa el contador de despliegues de globos necesarios para la siguiente PowerBall
|
// Decrementa el contador de despliegues de globos necesarios para la siguiente PowerBall
|
||||||
if (power_ball_counter_ > 0) {
|
if (power_ball_counter_ > 0) {
|
||||||
@@ -105,11 +107,19 @@ void BalloonManager::deployRandomFormation(int stage) {
|
|||||||
// Crea los globos de la formación
|
// Crea los globos de la formación
|
||||||
const auto BALLOONS = balloon_formations_->getFormationFromPool(stage, formation_id).balloons;
|
const auto BALLOONS = balloon_formations_->getFormationFromPool(stage, formation_id).balloons;
|
||||||
for (auto balloon : BALLOONS) {
|
for (auto balloon : BALLOONS) {
|
||||||
createBalloon(balloon.x, balloon.y, balloon.type, balloon.size, balloon.vel_x, balloon_speed_, (creation_time_enabled_) ? balloon.creation_counter : 0);
|
Balloon::Config config = {
|
||||||
|
.x = balloon.x,
|
||||||
|
.y = balloon.y,
|
||||||
|
.type = balloon.type,
|
||||||
|
.size = balloon.size,
|
||||||
|
.vel_x = balloon.vel_x,
|
||||||
|
.game_tempo = balloon_speed_,
|
||||||
|
.creation_counter = creation_time_enabled_ ? balloon.creation_counter : 0.0f};
|
||||||
|
createBalloon(config);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Reinicia el contador para el próximo despliegue
|
// Reinicia el timer para el próximo despliegue
|
||||||
balloon_deploy_counter_ = DEFAULT_BALLOON_DEPLOY_COUNTER;
|
balloon_deploy_counter_ = DEFAULT_BALLOON_DEPLOY_DELAY;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -118,15 +128,31 @@ void BalloonManager::deployRandomFormation(int stage) {
|
|||||||
void BalloonManager::deployFormation(int formation_id) {
|
void BalloonManager::deployFormation(int formation_id) {
|
||||||
const auto BALLOONS = balloon_formations_->getFormation(formation_id).balloons;
|
const auto BALLOONS = balloon_formations_->getFormation(formation_id).balloons;
|
||||||
for (auto balloon : BALLOONS) {
|
for (auto balloon : BALLOONS) {
|
||||||
createBalloon(balloon.x, balloon.y, balloon.type, balloon.size, balloon.vel_x, balloon_speed_, balloon.creation_counter);
|
Balloon::Config config = {
|
||||||
|
.x = balloon.x,
|
||||||
|
.y = balloon.y,
|
||||||
|
.type = balloon.type,
|
||||||
|
.size = balloon.size,
|
||||||
|
.vel_x = balloon.vel_x,
|
||||||
|
.game_tempo = balloon_speed_,
|
||||||
|
.creation_counter = balloon.creation_counter};
|
||||||
|
createBalloon(config);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Crea una formación de globos específica a una altura determinada
|
// Crea una formación de globos específica a una altura determinada
|
||||||
void BalloonManager::deployFormation(int formation_id, int y) {
|
void BalloonManager::deployFormation(int formation_id, float y) {
|
||||||
const auto BALLOONS = balloon_formations_->getFormation(formation_id).balloons;
|
const auto BALLOONS = balloon_formations_->getFormation(formation_id).balloons;
|
||||||
for (auto balloon : BALLOONS) {
|
for (auto balloon : BALLOONS) {
|
||||||
createBalloon(balloon.x, y, balloon.type, balloon.size, balloon.vel_x, balloon_speed_, balloon.creation_counter);
|
Balloon::Config config = {
|
||||||
|
.x = balloon.x,
|
||||||
|
.y = y,
|
||||||
|
.type = balloon.type,
|
||||||
|
.size = balloon.size,
|
||||||
|
.vel_x = balloon.vel_x,
|
||||||
|
.game_tempo = balloon_speed_,
|
||||||
|
.creation_counter = balloon.creation_counter};
|
||||||
|
createBalloon(config);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -136,11 +162,10 @@ void BalloonManager::freeBalloons() {
|
|||||||
balloons_.erase(result.begin(), balloons_.end());
|
balloons_.erase(result.begin(), balloons_.end());
|
||||||
}
|
}
|
||||||
|
|
||||||
// Actualiza la variable enemyDeployCounter
|
// Actualiza el timer de despliegue de globos (time-based)
|
||||||
void BalloonManager::updateBalloonDeployCounter() {
|
void BalloonManager::updateBalloonDeployCounter(float deltaTime) {
|
||||||
if (balloon_deploy_counter_ > 0) {
|
// DeltaTime en segundos - timer decrementa hasta llegar a cero
|
||||||
--balloon_deploy_counter_;
|
balloon_deploy_counter_ -= deltaTime;
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Indica si se puede crear una powerball
|
// Indica si se puede crear una powerball
|
||||||
@@ -152,13 +177,16 @@ auto BalloonManager::calculateScreenPower() -> int {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Crea un globo nuevo en el vector de globos
|
// Crea un globo nuevo en el vector de globos
|
||||||
auto BalloonManager::createBalloon(float x, int y, Balloon::Type type, Balloon::Size size, float velx, float speed, int creation_timer) -> std::shared_ptr<Balloon> {
|
auto BalloonManager::createBalloon(Balloon::Config config) -> std::shared_ptr<Balloon> {
|
||||||
if (can_deploy_balloons_) {
|
if (can_deploy_balloons_) {
|
||||||
const int INDEX = static_cast<int>(size);
|
const int INDEX = static_cast<int>(config.size);
|
||||||
balloons_.emplace_back(std::make_shared<Balloon>(x, y, type, size, velx, speed, creation_timer, play_area_, balloon_textures_.at(INDEX), balloon_animations_.at(INDEX)));
|
config.play_area = play_area_;
|
||||||
balloons_.back()->setSound(sound_enabled_);
|
config.texture = balloon_textures_.at(INDEX);
|
||||||
balloons_.back()->setBouncingSound(bouncing_sound_enabled_);
|
config.animation = balloon_animations_.at(INDEX);
|
||||||
balloons_.back()->setPoppingSound(poping_sound_enabled_);
|
config.sound.enabled = sound_enabled_;
|
||||||
|
config.sound.bouncing_enabled = bouncing_sound_enabled_;
|
||||||
|
config.sound.poping_enabled = poping_sound_enabled_;
|
||||||
|
balloons_.emplace_back(std::make_shared<Balloon>(config));
|
||||||
return balloons_.back();
|
return balloons_.back();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -169,22 +197,28 @@ auto BalloonManager::createBalloon(float x, int y, Balloon::Type type, Balloon::
|
|||||||
void BalloonManager::createChildBalloon(const std::shared_ptr<Balloon> &balloon, const std::string &direction) {
|
void BalloonManager::createChildBalloon(const std::shared_ptr<Balloon> &balloon, const std::string &direction) {
|
||||||
if (can_deploy_balloons_) {
|
if (can_deploy_balloons_) {
|
||||||
// Calcula parametros
|
// Calcula parametros
|
||||||
const float VX = direction == "LEFT" ? Balloon::VELX_NEGATIVE : Balloon::VELX_POSITIVE;
|
|
||||||
const auto SIZE = static_cast<Balloon::Size>(static_cast<int>(balloon->getSize()) - 1);
|
|
||||||
const int PARENT_HEIGHT = balloon->getHeight();
|
const int PARENT_HEIGHT = balloon->getHeight();
|
||||||
const int CHILD_HEIGHT = Balloon::WIDTH.at(static_cast<int>(balloon->getSize()) - 1);
|
const int CHILD_HEIGHT = Balloon::WIDTH.at(static_cast<int>(balloon->getSize()) - 1);
|
||||||
const int CHILD_WIDTH = CHILD_HEIGHT;
|
const int CHILD_WIDTH = CHILD_HEIGHT;
|
||||||
const float Y = balloon->getPosY() + ((PARENT_HEIGHT - CHILD_HEIGHT) / 2);
|
|
||||||
float x = direction == "LEFT" ? balloon->getPosX() + (balloon->getWidth() / 3) : balloon->getPosX() + (2 * (balloon->getWidth() / 3));
|
const float X = direction == "LEFT" ? balloon->getPosX() + (balloon->getWidth() / 3) : balloon->getPosX() + (2 * (balloon->getWidth() / 3));
|
||||||
const float MIN_X = play_area_.x;
|
const float MIN_X = play_area_.x;
|
||||||
const float MAX_X = play_area_.w - CHILD_WIDTH;
|
const float MAX_X = play_area_.w - CHILD_WIDTH;
|
||||||
x = std::clamp(x - (CHILD_WIDTH / 2), MIN_X, MAX_X);
|
|
||||||
|
Balloon::Config config = {
|
||||||
|
.x = std::clamp(X - (CHILD_WIDTH / 2), MIN_X, MAX_X),
|
||||||
|
.y = balloon->getPosY() + ((PARENT_HEIGHT - CHILD_HEIGHT) / 2),
|
||||||
|
.size = static_cast<Balloon::Size>(static_cast<int>(balloon->getSize()) - 1),
|
||||||
|
.vel_x = direction == "LEFT" ? Balloon::VELX_NEGATIVE : Balloon::VELX_POSITIVE,
|
||||||
|
.game_tempo = balloon_speed_,
|
||||||
|
.creation_counter = 0};
|
||||||
|
|
||||||
// Crea el globo
|
// Crea el globo
|
||||||
auto b = createBalloon(x, Y, balloon->getType(), SIZE, VX, balloon_speed_, 0);
|
auto b = createBalloon(config);
|
||||||
|
|
||||||
// Establece parametros
|
// Establece parametros (deltaTime en segundos - velocidades en pixels/segundo)
|
||||||
b->setVelY(b->getType() == Balloon::Type::BALLOON ? -2.50F : Balloon::VELX_NEGATIVE * 2.0F);
|
constexpr float VEL_Y_BALLOON_PER_S = -150.0F; // -2.50 pixels/frame convertido a pixels/segundo (-2.50 * 60 = -150)
|
||||||
|
b->setVelY(b->getType() == Balloon::Type::BALLOON ? VEL_Y_BALLOON_PER_S : Balloon::VELX_NEGATIVE * 2.0F);
|
||||||
|
|
||||||
// Herencia de estados
|
// Herencia de estados
|
||||||
if (balloon->isStopped()) { b->stop(); }
|
if (balloon->isStopped()) { b->stop(); }
|
||||||
@@ -196,18 +230,32 @@ void BalloonManager::createChildBalloon(const std::shared_ptr<Balloon> &balloon,
|
|||||||
void BalloonManager::createPowerBall() {
|
void BalloonManager::createPowerBall() {
|
||||||
if (can_deploy_balloons_) {
|
if (can_deploy_balloons_) {
|
||||||
constexpr int VALUES = 6;
|
constexpr int VALUES = 6;
|
||||||
constexpr float POS_Y = -Balloon::WIDTH.at(4);
|
const int LUCK = rand() % VALUES;
|
||||||
constexpr int CREATION_TIME = 0;
|
|
||||||
|
|
||||||
const float LEFT = param.game.play_area.rect.x;
|
const float LEFT = param.game.play_area.rect.x;
|
||||||
const float CENTER = param.game.play_area.center_x - (Balloon::WIDTH.at(4) / 2);
|
const float CENTER = param.game.play_area.center_x - (Balloon::WIDTH.at(4) / 2);
|
||||||
const float RIGHT = param.game.play_area.rect.w - Balloon::WIDTH.at(4);
|
const float RIGHT = param.game.play_area.rect.w - Balloon::WIDTH.at(4);
|
||||||
|
|
||||||
const int LUCK = rand() % VALUES;
|
|
||||||
const std::array<float, VALUES> POS_X = {LEFT, LEFT, CENTER, CENTER, RIGHT, RIGHT};
|
const std::array<float, VALUES> POS_X = {LEFT, LEFT, CENTER, CENTER, RIGHT, RIGHT};
|
||||||
const std::array<float, VALUES> VEL_X = {Balloon::VELX_POSITIVE, Balloon::VELX_POSITIVE, Balloon::VELX_POSITIVE, Balloon::VELX_NEGATIVE, Balloon::VELX_NEGATIVE, Balloon::VELX_NEGATIVE};
|
const std::array<float, VALUES> VEL_X = {Balloon::VELX_POSITIVE, Balloon::VELX_POSITIVE, Balloon::VELX_POSITIVE, Balloon::VELX_NEGATIVE, Balloon::VELX_NEGATIVE, Balloon::VELX_NEGATIVE};
|
||||||
|
|
||||||
balloons_.emplace_back(std::make_unique<Balloon>(POS_X[LUCK], POS_Y, Balloon::Type::POWERBALL, Balloon::Size::EXTRALARGE, VEL_X[LUCK], balloon_speed_, CREATION_TIME, play_area_, balloon_textures_[4], balloon_animations_[4]));
|
Balloon::Config config = {
|
||||||
|
.x = POS_X.at(LUCK),
|
||||||
|
.y = -Balloon::WIDTH.at(4),
|
||||||
|
.type = Balloon::Type::POWERBALL,
|
||||||
|
.size = Balloon::Size::EXTRALARGE,
|
||||||
|
.vel_x = VEL_X.at(LUCK),
|
||||||
|
.game_tempo = balloon_speed_,
|
||||||
|
.creation_counter = 0,
|
||||||
|
.play_area = play_area_,
|
||||||
|
.texture = balloon_textures_.at(4),
|
||||||
|
.animation = balloon_animations_.at(4),
|
||||||
|
.sound = {
|
||||||
|
.bouncing_enabled = bouncing_sound_enabled_,
|
||||||
|
.poping_enabled = poping_sound_enabled_,
|
||||||
|
.enabled = sound_enabled_}};
|
||||||
|
|
||||||
|
balloons_.emplace_back(std::make_unique<Balloon>(config));
|
||||||
balloons_.back()->setInvulnerable(true);
|
balloons_.back()->setInvulnerable(true);
|
||||||
|
|
||||||
power_ball_enabled_ = true;
|
power_ball_enabled_ = true;
|
||||||
@@ -219,7 +267,7 @@ void BalloonManager::createPowerBall() {
|
|||||||
void BalloonManager::setBalloonSpeed(float speed) {
|
void BalloonManager::setBalloonSpeed(float speed) {
|
||||||
balloon_speed_ = speed;
|
balloon_speed_ = speed;
|
||||||
for (auto &balloon : balloons_) {
|
for (auto &balloon : balloons_) {
|
||||||
balloon->setSpeed(speed);
|
balloon->setGameTempo(speed);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -232,7 +280,7 @@ auto BalloonManager::popBalloon(const std::shared_ptr<Balloon> &balloon) -> int
|
|||||||
balloon->pop(true);
|
balloon->pop(true);
|
||||||
score = destroyAllBalloons();
|
score = destroyAllBalloons();
|
||||||
power_ball_enabled_ = false;
|
power_ball_enabled_ = false;
|
||||||
balloon_deploy_counter_ = 20;
|
balloon_deploy_counter_ = BALLOON_POP_DELAY; // Resetea con retraso
|
||||||
} else {
|
} else {
|
||||||
score = balloon->getScore();
|
score = balloon->getScore();
|
||||||
if (balloon->getSize() != Balloon::Size::SMALL) {
|
if (balloon->getSize() != Balloon::Size::SMALL) {
|
||||||
@@ -288,8 +336,8 @@ auto BalloonManager::destroyAllBalloons() -> int {
|
|||||||
score += destroyBalloon(balloon);
|
score += destroyBalloon(balloon);
|
||||||
}
|
}
|
||||||
|
|
||||||
balloon_deploy_counter_ = 300;
|
balloon_deploy_counter_ = DEFAULT_BALLOON_DEPLOY_DELAY;
|
||||||
Screen::get()->flash(Colors::FLASH, 3);
|
Screen::get()->flash(Colors::FLASH, 0.05F);
|
||||||
Screen::get()->shake();
|
Screen::get()->shake();
|
||||||
|
|
||||||
return score;
|
return score;
|
||||||
@@ -298,7 +346,9 @@ auto BalloonManager::destroyAllBalloons() -> int {
|
|||||||
// Detiene todos los globos
|
// Detiene todos los globos
|
||||||
void BalloonManager::stopAllBalloons() {
|
void BalloonManager::stopAllBalloons() {
|
||||||
for (auto &balloon : balloons_) {
|
for (auto &balloon : balloons_) {
|
||||||
balloon->stop();
|
if (!balloon->isBeingCreated()) {
|
||||||
|
balloon->stop();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -332,19 +382,6 @@ void BalloonManager::createTwoBigBalloons() {
|
|||||||
deployFormation(1);
|
deployFormation(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Crea una disposición de globos aleatoria
|
|
||||||
void BalloonManager::createRandomBalloons() {
|
|
||||||
const int NUM_BALLOONS = 2 + (rand() % 4);
|
|
||||||
for (int i = 0; i < NUM_BALLOONS; ++i) {
|
|
||||||
const float X = param.game.game_area.rect.x + (rand() % static_cast<int>(param.game.game_area.rect.w)) - Balloon::WIDTH.at(3);
|
|
||||||
const int Y = param.game.game_area.rect.y + (rand() % 50);
|
|
||||||
const auto SIZE = static_cast<Balloon::Size>(rand() % 4);
|
|
||||||
const float VEL_X = (rand() % 2 == 0) ? Balloon::VELX_POSITIVE : Balloon::VELX_NEGATIVE;
|
|
||||||
const int CREATION_COUNTER = 0;
|
|
||||||
createBalloon(X, Y, Balloon::Type::BALLOON, SIZE, VEL_X, balloon_speed_, CREATION_COUNTER);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Obtiene el nivel de ameza actual generado por los globos
|
// Obtiene el nivel de ameza actual generado por los globos
|
||||||
auto BalloonManager::getMenace() -> int {
|
auto BalloonManager::getMenace() -> int {
|
||||||
return std::accumulate(balloons_.begin(), balloons_.end(), 0, [](int sum, const auto &balloon) { return sum + (balloon->isEnabled() ? balloon->getMenace() : 0); });
|
return std::accumulate(balloons_.begin(), balloons_.end(), 0, [](int sum, const auto &balloon) { return sum + (balloon->isEnabled() ? balloon->getMenace() : 0); });
|
||||||
|
|||||||
@@ -28,29 +28,28 @@ class BalloonManager {
|
|||||||
~BalloonManager() = default;
|
~BalloonManager() = default;
|
||||||
|
|
||||||
// --- Métodos principales ---
|
// --- Métodos principales ---
|
||||||
void update(); // Actualiza el estado de los globos
|
void update(float deltaTime); // Actualiza el estado de los globos (time-based)
|
||||||
void render(); // Renderiza los globos en pantalla
|
void render(); // Renderiza los globos en pantalla
|
||||||
|
|
||||||
// --- Gestión de globos ---
|
// --- Gestión de globos ---
|
||||||
void freeBalloons(); // Libera globos que ya no sirven
|
void freeBalloons(); // Libera globos que ya no sirven
|
||||||
|
|
||||||
// --- Creación de formaciones enemigas ---
|
// --- Creación de formaciones enemigas ---
|
||||||
void deployRandomFormation(int stage); // Crea una formación de globos aleatoria
|
void deployRandomFormation(int stage); // Crea una formación de globos aleatoria
|
||||||
void deployFormation(int formation_id); // Crea una formación específica
|
void deployFormation(int formation_id); // Crea una formación específica
|
||||||
void deployFormation(int formation_id, int y); // Crea una formación específica con coordenadas
|
void deployFormation(int formation_id, float y); // Crea una formación específica con coordenadas
|
||||||
|
|
||||||
// --- Creación de globos ---
|
// --- Creación de globos ---
|
||||||
auto createBalloon(float x, int y, Balloon::Type type, Balloon::Size size, float velx, float speed, int creation_timer) -> std::shared_ptr<Balloon>; // Crea un nuevo globo
|
auto createBalloon(Balloon::Config config) -> std::shared_ptr<Balloon>; // Crea un nuevo globo
|
||||||
void createChildBalloon(const std::shared_ptr<Balloon> &balloon, const std::string &direction); // Crea un globo a partir de otro
|
void createChildBalloon(const std::shared_ptr<Balloon> &balloon, const std::string &direction); // Crea un globo a partir de otro
|
||||||
void createPowerBall(); // Crea una PowerBall
|
void createPowerBall(); // Crea una PowerBall
|
||||||
void createTwoBigBalloons(); // Crea dos globos grandes
|
void createTwoBigBalloons(); // Crea dos globos grandes
|
||||||
void createRandomBalloons(); // Crea una disposición aleatoria de globos
|
|
||||||
|
|
||||||
// --- Control de velocidad y despliegue ---
|
// --- Control de velocidad y despliegue ---
|
||||||
void setBalloonSpeed(float speed); // Ajusta la velocidad de los globos
|
void setBalloonSpeed(float speed); // Ajusta la velocidad de los globos
|
||||||
void setDefaultBalloonSpeed(float speed) { default_balloon_speed_ = speed; }; // Establece la velocidad base
|
void setDefaultBalloonSpeed(float speed) { default_balloon_speed_ = speed; }; // Establece la velocidad base
|
||||||
void resetBalloonSpeed() { setBalloonSpeed(default_balloon_speed_); }; // Restablece la velocidad de los globos
|
void resetBalloonSpeed() { setBalloonSpeed(default_balloon_speed_); }; // Restablece la velocidad de los globos
|
||||||
void updateBalloonDeployCounter(); // Actualiza el contador de despliegue
|
void updateBalloonDeployCounter(float deltaTime); // Actualiza el contador de despliegue (time-based)
|
||||||
auto canPowerBallBeCreated() -> bool; // Indica si se puede crear una PowerBall
|
auto canPowerBallBeCreated() -> bool; // Indica si se puede crear una PowerBall
|
||||||
auto calculateScreenPower() -> int; // Calcula el poder de los globos en pantalla
|
auto calculateScreenPower() -> int; // Calcula el poder de los globos en pantalla
|
||||||
|
|
||||||
@@ -83,7 +82,9 @@ class BalloonManager {
|
|||||||
|
|
||||||
private:
|
private:
|
||||||
// --- Constantes ---
|
// --- Constantes ---
|
||||||
static const int DEFAULT_BALLOON_DEPLOY_COUNTER = 300;
|
static constexpr float DEFAULT_BALLOON_DEPLOY_DELAY = 5.0f; // 300 frames = 5 segundos
|
||||||
|
static constexpr float POWERBALL_DEPLOY_DELAY = 0.167f; // 10 frames = 0.167 segundos
|
||||||
|
static constexpr float BALLOON_POP_DELAY = 0.333f; // 20 frames = 0.333 segundos
|
||||||
|
|
||||||
// --- Objetos y punteros ---
|
// --- Objetos y punteros ---
|
||||||
Balloons balloons_; // Vector con los globos activos
|
Balloons balloons_; // Vector con los globos activos
|
||||||
@@ -97,9 +98,9 @@ class BalloonManager {
|
|||||||
|
|
||||||
// --- Variables de estado ---
|
// --- Variables de estado ---
|
||||||
SDL_FRect play_area_ = param.game.play_area.rect;
|
SDL_FRect play_area_ = param.game.play_area.rect;
|
||||||
float balloon_speed_ = Balloon::SPEED.at(0);
|
float balloon_speed_ = Balloon::GAME_TEMPO.at(0);
|
||||||
float default_balloon_speed_ = Balloon::SPEED.at(0);
|
float default_balloon_speed_ = Balloon::GAME_TEMPO.at(0);
|
||||||
int balloon_deploy_counter_ = 0;
|
float balloon_deploy_counter_ = 0;
|
||||||
int power_ball_counter_ = 0;
|
int power_ball_counter_ = 0;
|
||||||
int last_balloon_deploy_ = 0;
|
int last_balloon_deploy_ = 0;
|
||||||
bool power_ball_enabled_ = false;
|
bool power_ball_enabled_ = false;
|
||||||
|
|||||||
@@ -60,21 +60,22 @@ void Bullet::render() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Actualiza el estado del objeto
|
// Actualiza el estado del objeto (time-based)
|
||||||
auto Bullet::update() -> BulletMoveStatus {
|
auto Bullet::update(float deltaTime) -> BulletMoveStatus {
|
||||||
sprite_->update();
|
sprite_->update(deltaTime);
|
||||||
return move();
|
return move(deltaTime);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Implementación del movimiento usando BulletMoveStatus
|
// Implementación del movimiento usando BulletMoveStatus (time-based)
|
||||||
auto Bullet::move() -> BulletMoveStatus {
|
auto Bullet::move(float deltaTime) -> BulletMoveStatus {
|
||||||
pos_x_ += vel_x_;
|
// DeltaTime puro: velocidad (pixels/segundo) * tiempo (segundos)
|
||||||
|
pos_x_ += vel_x_ * deltaTime;
|
||||||
if (pos_x_ < param.game.play_area.rect.x - WIDTH || pos_x_ > param.game.play_area.rect.w) {
|
if (pos_x_ < param.game.play_area.rect.x - WIDTH || pos_x_ > param.game.play_area.rect.w) {
|
||||||
disable();
|
disable();
|
||||||
return BulletMoveStatus::OUT;
|
return BulletMoveStatus::OUT;
|
||||||
}
|
}
|
||||||
|
|
||||||
pos_y_ += VEL_Y;
|
pos_y_ += VEL_Y * deltaTime;
|
||||||
if (pos_y_ < param.game.play_area.rect.y - HEIGHT) {
|
if (pos_y_ < param.game.play_area.rect.y - HEIGHT) {
|
||||||
disable();
|
disable();
|
||||||
return BulletMoveStatus::OUT;
|
return BulletMoveStatus::OUT;
|
||||||
|
|||||||
@@ -34,9 +34,9 @@ class Bullet {
|
|||||||
~Bullet() = default; // Destructor
|
~Bullet() = default; // Destructor
|
||||||
|
|
||||||
// --- Métodos principales ---
|
// --- Métodos principales ---
|
||||||
void render(); // Dibuja la bala en pantalla
|
void render(); // Dibuja la bala en pantalla
|
||||||
auto update() -> BulletMoveStatus; // Actualiza el estado del objeto
|
auto update(float deltaTime) -> BulletMoveStatus; // Actualiza el estado del objeto (time-based)
|
||||||
void disable(); // Desactiva la bala
|
void disable(); // Desactiva la bala
|
||||||
|
|
||||||
// --- Getters ---
|
// --- Getters ---
|
||||||
[[nodiscard]] auto isEnabled() const -> bool; // Comprueba si está activa
|
[[nodiscard]] auto isEnabled() const -> bool; // Comprueba si está activa
|
||||||
@@ -45,10 +45,10 @@ class Bullet {
|
|||||||
|
|
||||||
private:
|
private:
|
||||||
// --- Constantes ---
|
// --- Constantes ---
|
||||||
static constexpr float VEL_Y = -3.0F; // Velocidad vertical
|
static constexpr float VEL_Y = -180.0F; // Velocidad vertical (pixels/segundo) - era -0.18F pixels/ms
|
||||||
static constexpr float VEL_X_LEFT = -2.0F; // Velocidad izquierda
|
static constexpr float VEL_X_LEFT = -120.0F; // Velocidad izquierda (pixels/segundo) - era -0.12F pixels/ms
|
||||||
static constexpr float VEL_X_RIGHT = 2.0F; // Velocidad derecha
|
static constexpr float VEL_X_RIGHT = 120.0F; // Velocidad derecha (pixels/segundo) - era 0.12F pixels/ms
|
||||||
static constexpr float VEL_X_CENTER = 0.0F; // Velocidad central
|
static constexpr float VEL_X_CENTER = 0.0F; // Velocidad central
|
||||||
|
|
||||||
// --- Objetos y punteros ---
|
// --- Objetos y punteros ---
|
||||||
std::unique_ptr<AnimatedSprite> sprite_; // Sprite con los gráficos
|
std::unique_ptr<AnimatedSprite> sprite_; // Sprite con los gráficos
|
||||||
@@ -64,7 +64,7 @@ class Bullet {
|
|||||||
// --- Métodos internos ---
|
// --- Métodos internos ---
|
||||||
void shiftColliders(); // Ajusta el círculo de colisión
|
void shiftColliders(); // Ajusta el círculo de colisión
|
||||||
void shiftSprite(); // Ajusta el sprite
|
void shiftSprite(); // Ajusta el sprite
|
||||||
auto move() -> BulletMoveStatus; // Mueve la bala y devuelve su estado
|
auto move(float deltaTime) -> BulletMoveStatus; // Mueve la bala y devuelve su estado (time-based)
|
||||||
static auto calculateVelocity(BulletType bullet_type) -> float; // Calcula la velocidad horizontal de la bala
|
static auto calculateVelocity(BulletType bullet_type) -> float; // Calcula la velocidad horizontal de la bala
|
||||||
static auto buildAnimationString(BulletType bullet_type, bool powered) -> std::string; // Construye el string de animación
|
static auto buildAnimationString(BulletType bullet_type, bool powered) -> std::string; // Construye el string de animación
|
||||||
};
|
};
|
||||||
|
|||||||
110
source/color.cpp
110
source/color.cpp
@@ -116,71 +116,71 @@ constexpr auto Color::hsvToRgb(HSV hsv) -> Color {
|
|||||||
|
|
||||||
// Implementaciones del namespace Colors
|
// Implementaciones del namespace Colors
|
||||||
namespace Colors {
|
namespace Colors {
|
||||||
// Obtiene un color del vector de colores imitando al Coche Fantástico
|
// Obtiene un color del vector de colores imitando al Coche Fantástico
|
||||||
auto getColorLikeKnightRider(const std::vector<Color> &colors, int counter) -> Color {
|
auto getColorLikeKnightRider(const std::vector<Color> &colors, int counter) -> Color {
|
||||||
int cycle_length = (colors.size() * 2) - 2;
|
int cycle_length = (colors.size() * 2) - 2;
|
||||||
size_t n = counter % cycle_length;
|
size_t n = counter % cycle_length;
|
||||||
|
|
||||||
size_t index;
|
size_t index;
|
||||||
if (n < colors.size()) {
|
if (n < colors.size()) {
|
||||||
index = n; // Avanza: 0,1,2,3
|
index = n; // Avanza: 0,1,2,3
|
||||||
} else {
|
} else {
|
||||||
index = 2 * (colors.size() - 1) - n; // Retrocede: 2,1
|
index = 2 * (colors.size() - 1) - n; // Retrocede: 2,1
|
||||||
}
|
|
||||||
|
|
||||||
return colors[index];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
auto generateMirroredCycle(Color base, ColorCycleStyle style) -> Cycle {
|
return colors[index];
|
||||||
Cycle result{};
|
}
|
||||||
HSV base_hsv = Color::rgbToHsv(base);
|
|
||||||
|
|
||||||
for (size_t i = 0; i < CYCLE_SIZE; ++i) {
|
auto generateMirroredCycle(Color base, ColorCycleStyle style) -> Cycle {
|
||||||
float t = static_cast<float>(i) / (CYCLE_SIZE - 1); // 0 → 1
|
Cycle result{};
|
||||||
float hue_shift = 0.0F;
|
HSV base_hsv = Color::rgbToHsv(base);
|
||||||
float sat_shift = 0.0F;
|
|
||||||
float val_shift = 0.0F;
|
|
||||||
|
|
||||||
switch (style) {
|
for (size_t i = 0; i < CYCLE_SIZE; ++i) {
|
||||||
case ColorCycleStyle::SUBTLE_PULSE:
|
float t = static_cast<float>(i) / (CYCLE_SIZE - 1); // 0 → 1
|
||||||
// Solo brillo suave
|
float hue_shift = 0.0F;
|
||||||
val_shift = 0.07F * sinf(t * M_PI);
|
float sat_shift = 0.0F;
|
||||||
break;
|
float val_shift = 0.0F;
|
||||||
|
|
||||||
case ColorCycleStyle::HUE_WAVE:
|
switch (style) {
|
||||||
// Oscilación leve de tono
|
case ColorCycleStyle::SUBTLE_PULSE:
|
||||||
hue_shift = 15.0F * (t - 0.5F) * 2.0F;
|
// Solo brillo suave
|
||||||
val_shift = 0.05F * sinf(t * M_PI);
|
val_shift = 0.07F * sinf(t * M_PI);
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case ColorCycleStyle::VIBRANT:
|
case ColorCycleStyle::HUE_WAVE:
|
||||||
// Cambios fuertes en tono y brillo
|
// Oscilación leve de tono
|
||||||
hue_shift = 35.0F * sinf(t * M_PI);
|
hue_shift = 15.0F * (t - 0.5F) * 2.0F;
|
||||||
val_shift = 0.2F * sinf(t * M_PI);
|
val_shift = 0.05F * sinf(t * M_PI);
|
||||||
sat_shift = -0.2F * sinf(t * M_PI);
|
break;
|
||||||
break;
|
|
||||||
|
|
||||||
case ColorCycleStyle::DARKEN_GLOW:
|
case ColorCycleStyle::VIBRANT:
|
||||||
// Se oscurece al centro
|
// Cambios fuertes en tono y brillo
|
||||||
val_shift = -0.15F * sinf(t * M_PI);
|
hue_shift = 35.0F * sinf(t * M_PI);
|
||||||
break;
|
val_shift = 0.2F * sinf(t * M_PI);
|
||||||
|
sat_shift = -0.2F * sinf(t * M_PI);
|
||||||
|
break;
|
||||||
|
|
||||||
case ColorCycleStyle::LIGHT_FLASH:
|
case ColorCycleStyle::DARKEN_GLOW:
|
||||||
// Se ilumina al centro
|
// Se oscurece al centro
|
||||||
val_shift = 0.25F * sinf(t * M_PI);
|
val_shift = -0.15F * sinf(t * M_PI);
|
||||||
break;
|
break;
|
||||||
}
|
|
||||||
|
|
||||||
HSV adjusted = {
|
case ColorCycleStyle::LIGHT_FLASH:
|
||||||
.h = fmodf(base_hsv.h + hue_shift + 360.0F, 360.0F),
|
// Se ilumina al centro
|
||||||
.s = fminf(1.0F, fmaxf(0.0F, base_hsv.s + sat_shift)),
|
val_shift = 0.25F * sinf(t * M_PI);
|
||||||
.v = fminf(1.0F, fmaxf(0.0F, base_hsv.v + val_shift))};
|
break;
|
||||||
|
|
||||||
Color c = Color::hsvToRgb(adjusted);
|
|
||||||
result[i] = c;
|
|
||||||
result[(2 * CYCLE_SIZE) - 1 - i] = c; // espejo
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return result;
|
HSV adjusted = {
|
||||||
|
.h = fmodf(base_hsv.h + hue_shift + 360.0F, 360.0F),
|
||||||
|
.s = fminf(1.0F, fmaxf(0.0F, base_hsv.s + sat_shift)),
|
||||||
|
.v = fminf(1.0F, fmaxf(0.0F, base_hsv.v + val_shift))};
|
||||||
|
|
||||||
|
Color c = Color::hsvToRgb(adjusted);
|
||||||
|
result[i] = c;
|
||||||
|
result[(2 * CYCLE_SIZE) - 1 - i] = c; // espejo
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
} // namespace Colors
|
||||||
@@ -36,10 +36,17 @@ struct Color {
|
|||||||
|
|
||||||
Uint8 r, g, b, a;
|
Uint8 r, g, b, a;
|
||||||
|
|
||||||
constexpr Color() : r(MIN_COLOR_VALUE), g(MIN_COLOR_VALUE), b(MIN_COLOR_VALUE), a(DEFAULT_ALPHA) {}
|
constexpr Color()
|
||||||
|
: r(MIN_COLOR_VALUE),
|
||||||
|
g(MIN_COLOR_VALUE),
|
||||||
|
b(MIN_COLOR_VALUE),
|
||||||
|
a(DEFAULT_ALPHA) {}
|
||||||
|
|
||||||
explicit constexpr Color(Uint8 red, Uint8 green, Uint8 blue, Uint8 alpha = DEFAULT_ALPHA)
|
explicit constexpr Color(Uint8 red, Uint8 green, Uint8 blue, Uint8 alpha = DEFAULT_ALPHA)
|
||||||
: r(red), g(green), b(blue), a(alpha) {}
|
: r(red),
|
||||||
|
g(green),
|
||||||
|
b(blue),
|
||||||
|
a(alpha) {}
|
||||||
|
|
||||||
[[nodiscard]] constexpr auto INVERSE() const -> Color {
|
[[nodiscard]] constexpr auto INVERSE() const -> Color {
|
||||||
return Color(MAX_COLOR_VALUE - r, MAX_COLOR_VALUE - g, MAX_COLOR_VALUE - b, a);
|
return Color(MAX_COLOR_VALUE - r, MAX_COLOR_VALUE - g, MAX_COLOR_VALUE - b, a);
|
||||||
@@ -108,25 +115,25 @@ enum class ColorCycleStyle {
|
|||||||
|
|
||||||
// --- Namespace Colors: constantes y utilidades de color ---
|
// --- Namespace Colors: constantes y utilidades de color ---
|
||||||
namespace Colors {
|
namespace Colors {
|
||||||
// --- Constantes ---
|
// --- Constantes ---
|
||||||
constexpr size_t CYCLE_SIZE = 6; // Mitad del ciclo espejado
|
constexpr size_t CYCLE_SIZE = 6; // Mitad del ciclo espejado
|
||||||
|
|
||||||
// --- Alias ---
|
// --- Alias ---
|
||||||
using Cycle = std::array<Color, 2 * CYCLE_SIZE>;
|
using Cycle = std::array<Color, 2 * CYCLE_SIZE>;
|
||||||
|
|
||||||
// --- Colores predefinidos ---
|
// --- Colores predefinidos ---
|
||||||
constexpr Color NO_COLOR_MOD = Color(0XFF, 0XFF, 0XFF);
|
constexpr Color NO_COLOR_MOD = Color(0XFF, 0XFF, 0XFF);
|
||||||
constexpr Color SHADOW_TEXT = Color(0X43, 0X43, 0X4F);
|
constexpr Color SHADOW_TEXT = Color(0X43, 0X43, 0X4F);
|
||||||
constexpr Color TITLE_SHADOW_TEXT = Color(0x14, 0x87, 0xc4);
|
constexpr Color TITLE_SHADOW_TEXT = Color(0x14, 0x87, 0xc4);
|
||||||
constexpr Color ORANGE_TEXT = Color(0XFF, 0X7A, 0X00);
|
constexpr Color ORANGE_TEXT = Color(0XFF, 0X7A, 0X00);
|
||||||
|
|
||||||
constexpr Color FLASH = Color(0XFF, 0XFF, 0XFF);
|
constexpr Color FLASH = Color(0XFF, 0XFF, 0XFF);
|
||||||
|
|
||||||
constexpr Color BLUE_SKY = Color(0X02, 0X88, 0XD1);
|
constexpr Color BLUE_SKY = Color(0X02, 0X88, 0XD1);
|
||||||
constexpr Color PINK_SKY = Color(0XFF, 0X6B, 0X97);
|
constexpr Color PINK_SKY = Color(0XFF, 0X6B, 0X97);
|
||||||
constexpr Color GREEN_SKY = Color(0X00, 0X79, 0X6B);
|
constexpr Color GREEN_SKY = Color(0X00, 0X79, 0X6B);
|
||||||
|
|
||||||
// --- Funciones ---
|
// --- Funciones ---
|
||||||
auto getColorLikeKnightRider(const std::vector<Color> &colors, int counter) -> Color;
|
auto getColorLikeKnightRider(const std::vector<Color> &colors, int counter) -> Color;
|
||||||
auto generateMirroredCycle(Color base, ColorCycleStyle style = ColorCycleStyle::SUBTLE_PULSE) -> Cycle;
|
auto generateMirroredCycle(Color base, ColorCycleStyle style = ColorCycleStyle::SUBTLE_PULSE) -> Cycle;
|
||||||
}
|
} // namespace Colors
|
||||||
@@ -15,8 +15,8 @@ namespace Game {
|
|||||||
constexpr float WIDTH = 320.0F;
|
constexpr float WIDTH = 320.0F;
|
||||||
constexpr float HEIGHT = 256.0F;
|
constexpr float HEIGHT = 256.0F;
|
||||||
constexpr float ITEM_SIZE = 20.0F;
|
constexpr float ITEM_SIZE = 20.0F;
|
||||||
constexpr int NAME_ENTRY_IDLE_TIME = 10;
|
constexpr int NAME_ENTRY_IDLE_TIME = 10;
|
||||||
constexpr int NAME_ENTRY_TOTAL_TIME = 60;
|
constexpr int NAME_ENTRY_TOTAL_TIME = 60;
|
||||||
constexpr bool HIT_STOP = false;
|
constexpr bool HIT_STOP = false;
|
||||||
constexpr int HIT_STOP_MS = 500;
|
constexpr int HIT_STOP_MS = 500;
|
||||||
constexpr const char* ITEM_TEXT_OUTLINE_COLOR = "FFFFFF00"; // 255, 255, 255, 0
|
constexpr const char* ITEM_TEXT_OUTLINE_COLOR = "FFFFFF00"; // 255, 255, 255, 0
|
||||||
@@ -58,7 +58,7 @@ constexpr int SKIP_COUNTDOWN_VALUE = 8;
|
|||||||
// --- TITLE ---
|
// --- TITLE ---
|
||||||
namespace Title {
|
namespace Title {
|
||||||
constexpr int PRESS_START_POSITION = 180;
|
constexpr int PRESS_START_POSITION = 180;
|
||||||
constexpr int DURATION = 800;
|
constexpr float DURATION_S = 14.0F;
|
||||||
constexpr int ARCADE_EDITION_POSITION = 123;
|
constexpr int ARCADE_EDITION_POSITION = 123;
|
||||||
constexpr int TITLE_C_C_POSITION = 80;
|
constexpr int TITLE_C_C_POSITION = 80;
|
||||||
constexpr const char* BG_COLOR = "41526F";
|
constexpr const char* BG_COLOR = "41526F";
|
||||||
@@ -76,14 +76,16 @@ struct BalloonSettings {
|
|||||||
float vel;
|
float vel;
|
||||||
float grav;
|
float grav;
|
||||||
constexpr BalloonSettings(float v, float g)
|
constexpr BalloonSettings(float v, float g)
|
||||||
: vel(v), grav(g) {}
|
: vel(v),
|
||||||
|
grav(g) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Valores para deltaTime en segundos: vel en pixels/s, grav en pixels/s² (aceleración)
|
||||||
constexpr std::array<BalloonSettings, 4> SETTINGS = {{
|
constexpr std::array<BalloonSettings, 4> SETTINGS = {{
|
||||||
BalloonSettings(2.75F, 0.09F), // Globo 0
|
BalloonSettings(165.0F, 320.0F), // Globo 0: vel=165 pixels/s, grav=320 pixels/s²
|
||||||
BalloonSettings(3.70F, 0.10F), // Globo 1
|
BalloonSettings(222.0F, 360.0F), // Globo 1: vel=222 pixels/s, grav=360 pixels/s²
|
||||||
BalloonSettings(4.70F, 0.10F), // Globo 2
|
BalloonSettings(282.0F, 360.0F), // Globo 2: vel=282 pixels/s, grav=360 pixels/s²
|
||||||
BalloonSettings(5.45F, 0.10F) // Globo 3
|
BalloonSettings(327.0F, 360.0F) // Globo 3: vel=327 pixels/s, grav=360 pixels/s²
|
||||||
}};
|
}};
|
||||||
|
|
||||||
constexpr std::array<const char*, 4> COLORS = {
|
constexpr std::array<const char*, 4> COLORS = {
|
||||||
|
|||||||
@@ -39,22 +39,22 @@ void DefineButtons::render() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void DefineButtons::update() {
|
void DefineButtons::update(float delta_time) {
|
||||||
if (!enabled_) {
|
if (!enabled_) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Actualizar la ventana siempre
|
// Actualizar la ventana siempre
|
||||||
if (window_message_) {
|
if (window_message_) {
|
||||||
window_message_->update();
|
window_message_->update(delta_time);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Manejar la secuencia de cierre si ya terminamos
|
// Manejar la secuencia de cierre si ya terminamos
|
||||||
if (finished_ && message_shown_) {
|
if (finished_ && message_shown_) {
|
||||||
message_timer_++;
|
message_timer_ += delta_time;
|
||||||
|
|
||||||
// Después del delay, iniciar animación de cierre (solo una vez)
|
// Después del delay, iniciar animación de cierre (solo una vez)
|
||||||
if (message_timer_ > MESSAGE_DISPLAY_FRAMES && !closing_) {
|
if (message_timer_ >= MESSAGE_DISPLAY_DURATION_S && !closing_) {
|
||||||
if (window_message_) {
|
if (window_message_) {
|
||||||
window_message_->hide(); // Iniciar animación de cierre
|
window_message_->hide(); // Iniciar animación de cierre
|
||||||
}
|
}
|
||||||
@@ -234,7 +234,7 @@ void DefineButtons::checkEnd() {
|
|||||||
|
|
||||||
// Solo marcar que ya mostramos el mensaje
|
// Solo marcar que ya mostramos el mensaje
|
||||||
message_shown_ = true;
|
message_shown_ = true;
|
||||||
message_timer_ = 0;
|
message_timer_ = 0.0f;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -25,7 +25,9 @@ class DefineButtons {
|
|||||||
int button;
|
int button;
|
||||||
|
|
||||||
Button(std::string label, Input::Action action, int button)
|
Button(std::string label, Input::Action action, int button)
|
||||||
: label(std::move(label)), action(action), button(button) {}
|
: label(std::move(label)),
|
||||||
|
action(action),
|
||||||
|
button(button) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
// --- Constructor y destructor ---
|
// --- Constructor y destructor ---
|
||||||
@@ -34,7 +36,7 @@ class DefineButtons {
|
|||||||
|
|
||||||
// --- Métodos principales ---
|
// --- Métodos principales ---
|
||||||
void render();
|
void render();
|
||||||
void update();
|
void update(float delta_time);
|
||||||
void handleEvents(const SDL_Event &event);
|
void handleEvents(const SDL_Event &event);
|
||||||
auto enable(Options::Gamepad *options_gamepad) -> bool;
|
auto enable(Options::Gamepad *options_gamepad) -> bool;
|
||||||
void disable();
|
void disable();
|
||||||
@@ -46,7 +48,7 @@ class DefineButtons {
|
|||||||
|
|
||||||
private:
|
private:
|
||||||
// --- Constantes ---
|
// --- Constantes ---
|
||||||
static constexpr size_t MESSAGE_DISPLAY_FRAMES = 120; // Cuánto tiempo mostrar el mensaje (en frames) ~2 segundos a 60fps
|
static constexpr float MESSAGE_DISPLAY_DURATION_S = 2.0f; // Cuánto tiempo mostrar el mensaje en segundos
|
||||||
|
|
||||||
// --- Objetos y punteros ---
|
// --- Objetos y punteros ---
|
||||||
Input *input_ = nullptr; // Entrada del usuario
|
Input *input_ = nullptr; // Entrada del usuario
|
||||||
@@ -57,7 +59,7 @@ class DefineButtons {
|
|||||||
std::vector<Button> buttons_; // Lista de botones
|
std::vector<Button> buttons_; // Lista de botones
|
||||||
std::vector<std::string> controller_names_; // Nombres de los controladores
|
std::vector<std::string> controller_names_; // Nombres de los controladores
|
||||||
size_t index_button_ = 0; // Índice del botón seleccionado
|
size_t index_button_ = 0; // Índice del botón seleccionado
|
||||||
size_t message_timer_ = 0; // Contador de frames para el mensaje
|
float message_timer_ = 0.0f; // Timer en segundos para el mensaje
|
||||||
bool enabled_ = false; // Flag para indicar si está activo
|
bool enabled_ = false; // Flag para indicar si está activo
|
||||||
bool finished_ = false; // Flag para indicar si ha terminado
|
bool finished_ = false; // Flag para indicar si ha terminado
|
||||||
bool closing_ = false; // Flag para indicar que está cerrando
|
bool closing_ = false; // Flag para indicar que está cerrando
|
||||||
|
|||||||
@@ -18,9 +18,9 @@
|
|||||||
#include "manage_hiscore_table.h" // Para ManageHiScoreTable
|
#include "manage_hiscore_table.h" // Para ManageHiScoreTable
|
||||||
#include "options.h" // Para loadFromFile, saveToFile, Settings, settings, setConfigFile, setControllersFile
|
#include "options.h" // Para loadFromFile, saveToFile, Settings, settings, setConfigFile, setControllersFile
|
||||||
#include "param.h" // Para loadParamsFromFile
|
#include "param.h" // Para loadParamsFromFile
|
||||||
#include "resource_helper.h" // Para ResourceHelper
|
|
||||||
#include "player.h" // Para Player
|
#include "player.h" // Para Player
|
||||||
#include "resource.h" // Para Resource
|
#include "resource.h" // Para Resource
|
||||||
|
#include "resource_helper.h" // Para ResourceHelper
|
||||||
#include "screen.h" // Para Screen
|
#include "screen.h" // Para Screen
|
||||||
#include "section.hpp" // Para Name, Options, name, options, AttractMode, attract_mode
|
#include "section.hpp" // Para Name, Options, name, options, AttractMode, attract_mode
|
||||||
#include "sections/credits.h" // Para Credits
|
#include "sections/credits.h" // Para Credits
|
||||||
@@ -42,7 +42,7 @@ Director::Director(int argc, std::span<char *> argv) {
|
|||||||
Section::name = Section::Name::GAME;
|
Section::name = Section::Name::GAME;
|
||||||
Section::options = Section::Options::GAME_PLAY_1P;
|
Section::options = Section::Options::GAME_PLAY_1P;
|
||||||
#elif _DEBUG
|
#elif _DEBUG
|
||||||
Section::name = Section::Name::GAME;
|
Section::name = Section::Name::TITLE;
|
||||||
Section::options = Section::Options::GAME_PLAY_1P;
|
Section::options = Section::Options::GAME_PLAY_1P;
|
||||||
#else // NORMAL GAME
|
#else // NORMAL GAME
|
||||||
Section::name = Section::Name::LOGO;
|
Section::name = Section::Name::LOGO;
|
||||||
@@ -77,8 +77,8 @@ Director::~Director() {
|
|||||||
// Inicializa todo
|
// Inicializa todo
|
||||||
void Director::init() {
|
void Director::init() {
|
||||||
// Configuración inicial de parametros
|
// Configuración inicial de parametros
|
||||||
Asset::init(executable_path_); // Inicializa el sistema de gestión de archivos
|
Asset::init(executable_path_); // Inicializa el sistema de gestión de archivos
|
||||||
|
|
||||||
#ifdef MACOS_BUNDLE
|
#ifdef MACOS_BUNDLE
|
||||||
ResourceHelper::initializeResourceSystem(executable_path_ + "/../Resources/resources.pack");
|
ResourceHelper::initializeResourceSystem(executable_path_ + "/../Resources/resources.pack");
|
||||||
#else
|
#else
|
||||||
|
|||||||
@@ -45,7 +45,10 @@ void EnterName::incPosition() {
|
|||||||
} else if (position_ > 0) // No es necesario verificar position_ < MAX_NAME_LENGTH
|
} else if (position_ > 0) // No es necesario verificar position_ < MAX_NAME_LENGTH
|
||||||
{
|
{
|
||||||
// Copiamos el índice del carácter anterior si es posible.
|
// Copiamos el índice del carácter anterior si es posible.
|
||||||
character_index_[position_] = character_index_[position_ - 1];
|
// character_index_[position_] = character_index_[position_ - 1];
|
||||||
|
|
||||||
|
// Ponemos el caracter "espacio"
|
||||||
|
character_index_[position_] = 0;
|
||||||
} else {
|
} else {
|
||||||
// Si position_ es 0, inicializamos el carácter actual.
|
// Si position_ es 0, inicializamos el carácter actual.
|
||||||
character_index_[position_] = 0;
|
character_index_[position_] = 0;
|
||||||
@@ -144,12 +147,19 @@ auto EnterName::findIndex(char character) const -> int {
|
|||||||
// Devuelve un nombre al azar
|
// Devuelve un nombre al azar
|
||||||
auto EnterName::getRandomName() -> std::string {
|
auto EnterName::getRandomName() -> std::string {
|
||||||
static constexpr std::array<std::string_view, 8> NAMES = {
|
static constexpr std::array<std::string_view, 8> NAMES = {
|
||||||
"BAL1", "TABE", "DOC", "MON", "SAM1", "JORDI", "JDES", "PEPE"};
|
"BAL1",
|
||||||
|
"TABE",
|
||||||
|
"DOC",
|
||||||
|
"MON",
|
||||||
|
"SAM1",
|
||||||
|
"JORDI",
|
||||||
|
"JDES",
|
||||||
|
"PEPE"};
|
||||||
return std::string(NAMES[rand() % NAMES.size()]);
|
return std::string(NAMES[rand() % NAMES.size()]);
|
||||||
}
|
}
|
||||||
// Obtiene el nombre final introducido
|
// Obtiene el nombre final introducido
|
||||||
auto EnterName::getFinalName() -> std::string {
|
auto EnterName::getFinalName() -> std::string {
|
||||||
auto name = trim(name_.substr(0, position_));
|
auto name = trim(name_.substr(0, position_ + 1)); // Devuelve el texto intruducido incluyendo el del selector
|
||||||
if (name.empty()) {
|
if (name.empty()) {
|
||||||
name = getRandomName();
|
name = getRandomName();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,10 +6,10 @@
|
|||||||
|
|
||||||
class Texture; // lines 4-4
|
class Texture; // lines 4-4
|
||||||
|
|
||||||
// Actualiza la lógica de la clase
|
// Actualiza la lógica de la clase (time-based)
|
||||||
void Explosions::update() {
|
void Explosions::update(float deltaTime) {
|
||||||
for (auto &explosion : explosions_) {
|
for (auto &explosion : explosions_) {
|
||||||
explosion->update();
|
explosion->update(deltaTime);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Vacia el vector de elementos finalizados
|
// Vacia el vector de elementos finalizados
|
||||||
|
|||||||
@@ -16,7 +16,9 @@ struct ExplosionTexture {
|
|||||||
std::vector<std::string> animation; // Animación para la textura
|
std::vector<std::string> animation; // Animación para la textura
|
||||||
|
|
||||||
ExplosionTexture(int sz, std::shared_ptr<Texture> tex, const std::vector<std::string> &anim)
|
ExplosionTexture(int sz, std::shared_ptr<Texture> tex, const std::vector<std::string> &anim)
|
||||||
: size(sz), texture(std::move(tex)), animation(anim) {}
|
: size(sz),
|
||||||
|
texture(std::move(tex)),
|
||||||
|
animation(anim) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
// --- Clase Explosions: gestor de explosiones ---
|
// --- Clase Explosions: gestor de explosiones ---
|
||||||
@@ -27,8 +29,8 @@ class Explosions {
|
|||||||
~Explosions() = default; // Destructor por defecto
|
~Explosions() = default; // Destructor por defecto
|
||||||
|
|
||||||
// --- Métodos principales ---
|
// --- Métodos principales ---
|
||||||
void update(); // Actualiza la lógica de la clase
|
void update(float deltaTime); // Actualiza la lógica de la clase (time-based)
|
||||||
void render(); // Dibuja el objeto en pantalla
|
void render(); // Dibuja el objeto en pantalla
|
||||||
|
|
||||||
// --- Configuración ---
|
// --- Configuración ---
|
||||||
void addTexture(int size, const std::shared_ptr<Texture> &texture, const std::vector<std::string> &animation); // Añade texturas al objeto
|
void addTexture(int size, const std::shared_ptr<Texture> &texture, const std::vector<std::string> &animation); // Añade texturas al objeto
|
||||||
|
|||||||
@@ -41,7 +41,7 @@ void Fade::init() {
|
|||||||
num_squares_width_ = param.fade.num_squares_width;
|
num_squares_width_ = param.fade.num_squares_width;
|
||||||
num_squares_height_ = param.fade.num_squares_height;
|
num_squares_height_ = param.fade.num_squares_height;
|
||||||
random_squares_duration_ = param.fade.random_squares_duration_ms; // Usar como duración en ms
|
random_squares_duration_ = param.fade.random_squares_duration_ms; // Usar como duración en ms
|
||||||
square_transition_duration_ = random_squares_duration_ / 4; // 25% del tiempo total para la transición individual
|
square_transition_duration_ = random_squares_duration_ / 4; // 25% del tiempo total para la transición individual
|
||||||
random_squares_start_time_ = 0;
|
random_squares_start_time_ = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -60,7 +60,7 @@ void Fade::render() {
|
|||||||
if (state_ == State::FINISHED && mode_ == Mode::IN) {
|
if (state_ == State::FINISHED && mode_ == Mode::IN) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
SDL_RenderTexture(renderer_, backbuffer_, nullptr, nullptr);
|
SDL_RenderTexture(renderer_, backbuffer_, nullptr, nullptr);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -82,10 +82,15 @@ void Fade::update() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Compatibilidad delta-time (ignora el parámetro ya que usa SDL_GetTicks)
|
||||||
|
void Fade::update(float delta_time) {
|
||||||
|
update(); // Llama al método original
|
||||||
|
}
|
||||||
|
|
||||||
void Fade::updatePreState() {
|
void Fade::updatePreState() {
|
||||||
// Sistema basado en tiempo únicamente
|
// Sistema basado en tiempo únicamente
|
||||||
Uint32 elapsed_time = SDL_GetTicks() - pre_start_time_;
|
Uint32 elapsed_time = SDL_GetTicks() - pre_start_time_;
|
||||||
|
|
||||||
if (elapsed_time >= static_cast<Uint32>(pre_duration_)) {
|
if (elapsed_time >= static_cast<Uint32>(pre_duration_)) {
|
||||||
state_ = State::FADING;
|
state_ = State::FADING;
|
||||||
// CRÍTICO: Reinicializar tiempo de inicio para tipos que usan random_squares_start_time_
|
// CRÍTICO: Reinicializar tiempo de inicio para tipos que usan random_squares_start_time_
|
||||||
@@ -129,17 +134,17 @@ void Fade::changeToPostState() {
|
|||||||
void Fade::updatePostState() {
|
void Fade::updatePostState() {
|
||||||
// Sistema basado en tiempo únicamente
|
// Sistema basado en tiempo únicamente
|
||||||
Uint32 elapsed_time = SDL_GetTicks() - post_start_time_;
|
Uint32 elapsed_time = SDL_GetTicks() - post_start_time_;
|
||||||
|
|
||||||
if (elapsed_time >= static_cast<Uint32>(post_duration_)) {
|
if (elapsed_time >= static_cast<Uint32>(post_duration_)) {
|
||||||
state_ = State::FINISHED;
|
state_ = State::FINISHED;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Mantener el alpha final correcto para cada tipo de fade
|
// Mantener el alpha final correcto para cada tipo de fade
|
||||||
Uint8 post_alpha = a_;
|
Uint8 post_alpha = a_;
|
||||||
if (type_ == Type::RANDOM_SQUARE2 || type_ == Type::DIAGONAL) {
|
if (type_ == Type::RANDOM_SQUARE2 || type_ == Type::DIAGONAL) {
|
||||||
post_alpha = (mode_ == Mode::OUT) ? 255 : 0;
|
post_alpha = (mode_ == Mode::OUT) ? 255 : 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
cleanBackbuffer(r_, g_, b_, post_alpha);
|
cleanBackbuffer(r_, g_, b_, post_alpha);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -204,16 +209,16 @@ void Fade::updateRandomSquareFade() {
|
|||||||
|
|
||||||
void Fade::updateRandomSquare2Fade() {
|
void Fade::updateRandomSquare2Fade() {
|
||||||
Uint32 elapsed_time = SDL_GetTicks() - random_squares_start_time_;
|
Uint32 elapsed_time = SDL_GetTicks() - random_squares_start_time_;
|
||||||
|
|
||||||
int total_squares = num_squares_width_ * num_squares_height_;
|
int total_squares = num_squares_width_ * num_squares_height_;
|
||||||
|
|
||||||
// Calcula el tiempo de activación: total - tiempo que necesitan los últimos cuadrados
|
// Calcula el tiempo de activación: total - tiempo que necesitan los últimos cuadrados
|
||||||
int activation_time = random_squares_duration_ - square_transition_duration_;
|
int activation_time = random_squares_duration_ - square_transition_duration_;
|
||||||
activation_time = std::max(activation_time, square_transition_duration_); // Mínimo igual a la duración de transición
|
activation_time = std::max(activation_time, square_transition_duration_); // Mínimo igual a la duración de transición
|
||||||
|
|
||||||
// Lógica diferente según el modo
|
// Lógica diferente según el modo
|
||||||
int squares_to_activate = 0;
|
int squares_to_activate = 0;
|
||||||
|
|
||||||
if (mode_ == Mode::OUT) {
|
if (mode_ == Mode::OUT) {
|
||||||
// OUT: Activa cuadrados gradualmente
|
// OUT: Activa cuadrados gradualmente
|
||||||
if (elapsed_time < static_cast<Uint32>(activation_time)) {
|
if (elapsed_time < static_cast<Uint32>(activation_time)) {
|
||||||
@@ -222,7 +227,7 @@ void Fade::updateRandomSquare2Fade() {
|
|||||||
} else {
|
} else {
|
||||||
squares_to_activate = total_squares; // Activar todos
|
squares_to_activate = total_squares; // Activar todos
|
||||||
}
|
}
|
||||||
|
|
||||||
// Activa nuevos cuadrados y guarda su tiempo de activación
|
// Activa nuevos cuadrados y guarda su tiempo de activación
|
||||||
for (int i = 0; i < squares_to_activate && i < total_squares; ++i) {
|
for (int i = 0; i < squares_to_activate && i < total_squares; ++i) {
|
||||||
if (square_age_[i] == -1) {
|
if (square_age_[i] == -1) {
|
||||||
@@ -232,22 +237,22 @@ void Fade::updateRandomSquare2Fade() {
|
|||||||
} else {
|
} else {
|
||||||
// IN: Todos los cuadrados empiezan activos desde el inicio
|
// IN: Todos los cuadrados empiezan activos desde el inicio
|
||||||
squares_to_activate = total_squares;
|
squares_to_activate = total_squares;
|
||||||
|
|
||||||
// Activa cuadrados gradualmente con tiempo de inicio escalonado
|
// Activa cuadrados gradualmente con tiempo de inicio escalonado
|
||||||
float activation_progress = static_cast<float>(elapsed_time) / activation_time;
|
float activation_progress = static_cast<float>(elapsed_time) / activation_time;
|
||||||
int squares_starting_transition = static_cast<int>(activation_progress * total_squares);
|
int squares_starting_transition = static_cast<int>(activation_progress * total_squares);
|
||||||
|
|
||||||
// Asegurar que al menos 1 cuadrado se active desde el primer frame
|
// Asegurar que al menos 1 cuadrado se active desde el primer frame
|
||||||
squares_starting_transition = std::max(squares_starting_transition, 1);
|
squares_starting_transition = std::max(squares_starting_transition, 1);
|
||||||
squares_starting_transition = std::min(squares_starting_transition, total_squares);
|
squares_starting_transition = std::min(squares_starting_transition, total_squares);
|
||||||
|
|
||||||
for (int i = 0; i < squares_starting_transition; ++i) {
|
for (int i = 0; i < squares_starting_transition; ++i) {
|
||||||
if (square_age_[i] == -1) {
|
if (square_age_[i] == -1) {
|
||||||
square_age_[i] = elapsed_time; // Empieza la transición a transparente
|
square_age_[i] = elapsed_time; // Empieza la transición a transparente
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
drawRandomSquares2();
|
drawRandomSquares2();
|
||||||
|
|
||||||
value_ = calculateValue(0, total_squares, squares_to_activate);
|
value_ = calculateValue(0, total_squares, squares_to_activate);
|
||||||
@@ -265,7 +270,7 @@ void Fade::updateRandomSquare2Fade() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (all_completed) {
|
if (all_completed) {
|
||||||
// Pintar textura final: OUT opaca, IN transparente
|
// Pintar textura final: OUT opaca, IN transparente
|
||||||
Uint8 final_alpha = (mode_ == Mode::OUT) ? 255 : 0;
|
Uint8 final_alpha = (mode_ == Mode::OUT) ? 255 : 0;
|
||||||
@@ -277,17 +282,17 @@ void Fade::updateRandomSquare2Fade() {
|
|||||||
|
|
||||||
void Fade::updateDiagonalFade() {
|
void Fade::updateDiagonalFade() {
|
||||||
Uint32 elapsed_time = SDL_GetTicks() - random_squares_start_time_;
|
Uint32 elapsed_time = SDL_GetTicks() - random_squares_start_time_;
|
||||||
|
|
||||||
int total_squares = num_squares_width_ * num_squares_height_;
|
int total_squares = num_squares_width_ * num_squares_height_;
|
||||||
|
|
||||||
// Calcula el tiempo de activación: total - tiempo que necesitan los últimos cuadrados
|
// Calcula el tiempo de activación: total - tiempo que necesitan los últimos cuadrados
|
||||||
int activation_time = random_squares_duration_ - square_transition_duration_;
|
int activation_time = random_squares_duration_ - square_transition_duration_;
|
||||||
activation_time = std::max(activation_time, square_transition_duration_);
|
activation_time = std::max(activation_time, square_transition_duration_);
|
||||||
|
|
||||||
// Calcula cuántas diagonales deberían estar activas
|
// Calcula cuántas diagonales deberían estar activas
|
||||||
int max_diagonal = num_squares_width_ + num_squares_height_ - 1; // Número total de diagonales
|
int max_diagonal = num_squares_width_ + num_squares_height_ - 1; // Número total de diagonales
|
||||||
int active_diagonals = 0;
|
int active_diagonals = 0;
|
||||||
|
|
||||||
if (mode_ == Mode::OUT) {
|
if (mode_ == Mode::OUT) {
|
||||||
// OUT: Activa diagonales gradualmente desde esquina superior izquierda
|
// OUT: Activa diagonales gradualmente desde esquina superior izquierda
|
||||||
if (elapsed_time < static_cast<Uint32>(activation_time)) {
|
if (elapsed_time < static_cast<Uint32>(activation_time)) {
|
||||||
@@ -296,7 +301,7 @@ void Fade::updateDiagonalFade() {
|
|||||||
} else {
|
} else {
|
||||||
active_diagonals = max_diagonal; // Activar todas
|
active_diagonals = max_diagonal; // Activar todas
|
||||||
}
|
}
|
||||||
|
|
||||||
// Activa cuadrados por diagonales
|
// Activa cuadrados por diagonales
|
||||||
for (int diagonal = 0; diagonal < active_diagonals; ++diagonal) {
|
for (int diagonal = 0; diagonal < active_diagonals; ++diagonal) {
|
||||||
activateDiagonal(diagonal, elapsed_time);
|
activateDiagonal(diagonal, elapsed_time);
|
||||||
@@ -304,12 +309,12 @@ void Fade::updateDiagonalFade() {
|
|||||||
} else {
|
} else {
|
||||||
// IN: Todas las diagonales empiezan activas, van desapareciendo
|
// IN: Todas las diagonales empiezan activas, van desapareciendo
|
||||||
active_diagonals = max_diagonal;
|
active_diagonals = max_diagonal;
|
||||||
|
|
||||||
// Activa diagonales gradualmente para transición
|
// Activa diagonales gradualmente para transición
|
||||||
if (elapsed_time < static_cast<Uint32>(activation_time)) {
|
if (elapsed_time < static_cast<Uint32>(activation_time)) {
|
||||||
float activation_progress = static_cast<float>(elapsed_time) / activation_time;
|
float activation_progress = static_cast<float>(elapsed_time) / activation_time;
|
||||||
int diagonals_starting_transition = static_cast<int>(activation_progress * max_diagonal);
|
int diagonals_starting_transition = static_cast<int>(activation_progress * max_diagonal);
|
||||||
|
|
||||||
for (int diagonal = 0; diagonal < diagonals_starting_transition; ++diagonal) {
|
for (int diagonal = 0; diagonal < diagonals_starting_transition; ++diagonal) {
|
||||||
activateDiagonal(diagonal, elapsed_time);
|
activateDiagonal(diagonal, elapsed_time);
|
||||||
}
|
}
|
||||||
@@ -320,7 +325,7 @@ void Fade::updateDiagonalFade() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
drawDiagonal();
|
drawDiagonal();
|
||||||
|
|
||||||
value_ = calculateValue(0, total_squares, active_diagonals * (total_squares / max_diagonal));
|
value_ = calculateValue(0, total_squares, active_diagonals * (total_squares / max_diagonal));
|
||||||
@@ -338,7 +343,7 @@ void Fade::updateDiagonalFade() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (all_completed) {
|
if (all_completed) {
|
||||||
// Pintar textura final: OUT opaca, IN transparente
|
// Pintar textura final: OUT opaca, IN transparente
|
||||||
Uint8 final_alpha = (mode_ == Mode::OUT) ? 255 : 0;
|
Uint8 final_alpha = (mode_ == Mode::OUT) ? 255 : 0;
|
||||||
@@ -354,15 +359,15 @@ void Fade::activateDiagonal(int diagonal_index, Uint32 current_time) {
|
|||||||
// Diagonal 1: (1,0), (0,1)
|
// Diagonal 1: (1,0), (0,1)
|
||||||
// Diagonal 2: (2,0), (1,1), (0,2)
|
// Diagonal 2: (2,0), (1,1), (0,2)
|
||||||
// etc.
|
// etc.
|
||||||
|
|
||||||
for (int x = 0; x < num_squares_width_; ++x) {
|
for (int x = 0; x < num_squares_width_; ++x) {
|
||||||
int y = diagonal_index - x;
|
int y = diagonal_index - x;
|
||||||
|
|
||||||
// Verificar que y está dentro de los límites
|
// Verificar que y está dentro de los límites
|
||||||
if (y >= 0 && y < num_squares_height_) {
|
if (y >= 0 && y < num_squares_height_) {
|
||||||
// Convertir coordenadas (x,y) a índice en el vector
|
// Convertir coordenadas (x,y) a índice en el vector
|
||||||
int index = y * num_squares_width_ + x;
|
int index = y * num_squares_width_ + x;
|
||||||
|
|
||||||
if (index >= 0 && index < static_cast<int>(square_age_.size())) {
|
if (index >= 0 && index < static_cast<int>(square_age_.size())) {
|
||||||
if (square_age_[index] == -1) {
|
if (square_age_[index] == -1) {
|
||||||
square_age_[index] = current_time; // Guarda el tiempo de activación
|
square_age_[index] = current_time; // Guarda el tiempo de activación
|
||||||
@@ -385,30 +390,30 @@ void Fade::drawDiagonal() {
|
|||||||
SDL_SetRenderDrawBlendMode(renderer_, SDL_BLENDMODE_BLEND); // Usar BLEND para alpha
|
SDL_SetRenderDrawBlendMode(renderer_, SDL_BLENDMODE_BLEND); // Usar BLEND para alpha
|
||||||
|
|
||||||
Uint32 current_time = SDL_GetTicks() - random_squares_start_time_;
|
Uint32 current_time = SDL_GetTicks() - random_squares_start_time_;
|
||||||
|
|
||||||
// Lógica unificada: sobre textura transparente, pintar cuadrados según su estado
|
// Lógica unificada: sobre textura transparente, pintar cuadrados según su estado
|
||||||
for (size_t i = 0; i < square_.size(); ++i) {
|
for (size_t i = 0; i < square_.size(); ++i) {
|
||||||
Uint8 current_alpha = 0;
|
Uint8 current_alpha = 0;
|
||||||
|
|
||||||
if (square_age_[i] == -1) {
|
if (square_age_[i] == -1) {
|
||||||
// Cuadrado no activado
|
// Cuadrado no activado
|
||||||
if (mode_ == Mode::OUT) {
|
if (mode_ == Mode::OUT) {
|
||||||
current_alpha = 0; // OUT: transparente si no activado
|
current_alpha = 0; // OUT: transparente si no activado
|
||||||
} else {
|
} else {
|
||||||
current_alpha = a_; // IN: opaco si no activado
|
current_alpha = a_; // IN: opaco si no activado
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// Cuadrado activado - calculamos progreso
|
// Cuadrado activado - calculamos progreso
|
||||||
Uint32 square_elapsed = current_time - square_age_[i];
|
Uint32 square_elapsed = current_time - square_age_[i];
|
||||||
float progress = std::min(static_cast<float>(square_elapsed) / square_transition_duration_, 1.0f);
|
float progress = std::min(static_cast<float>(square_elapsed) / square_transition_duration_, 1.0f);
|
||||||
|
|
||||||
if (mode_ == Mode::OUT) {
|
if (mode_ == Mode::OUT) {
|
||||||
current_alpha = static_cast<Uint8>(progress * a_); // 0 → 255
|
current_alpha = static_cast<Uint8>(progress * a_); // 0 → 255
|
||||||
} else {
|
} else {
|
||||||
current_alpha = static_cast<Uint8>((1.0f - progress) * a_); // 255 → 0
|
current_alpha = static_cast<Uint8>((1.0f - progress) * a_); // 255 → 0
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (current_alpha > 0) {
|
if (current_alpha > 0) {
|
||||||
SDL_SetRenderDrawColor(renderer_, r_, g_, b_, current_alpha);
|
SDL_SetRenderDrawColor(renderer_, r_, g_, b_, current_alpha);
|
||||||
SDL_RenderFillRect(renderer_, &square_[i]);
|
SDL_RenderFillRect(renderer_, &square_[i]);
|
||||||
@@ -450,30 +455,30 @@ void Fade::drawRandomSquares2() {
|
|||||||
SDL_SetRenderDrawBlendMode(renderer_, SDL_BLENDMODE_BLEND); // Usar BLEND para alpha
|
SDL_SetRenderDrawBlendMode(renderer_, SDL_BLENDMODE_BLEND); // Usar BLEND para alpha
|
||||||
|
|
||||||
Uint32 current_time = SDL_GetTicks() - random_squares_start_time_;
|
Uint32 current_time = SDL_GetTicks() - random_squares_start_time_;
|
||||||
|
|
||||||
// Lógica unificada: sobre textura transparente, pintar cuadrados según su estado
|
// Lógica unificada: sobre textura transparente, pintar cuadrados según su estado
|
||||||
for (size_t i = 0; i < square_.size(); ++i) {
|
for (size_t i = 0; i < square_.size(); ++i) {
|
||||||
Uint8 current_alpha = 0;
|
Uint8 current_alpha = 0;
|
||||||
|
|
||||||
if (square_age_[i] == -1) {
|
if (square_age_[i] == -1) {
|
||||||
// Cuadrado no activado
|
// Cuadrado no activado
|
||||||
if (mode_ == Mode::OUT) {
|
if (mode_ == Mode::OUT) {
|
||||||
current_alpha = 0; // OUT: transparente si no activado
|
current_alpha = 0; // OUT: transparente si no activado
|
||||||
} else {
|
} else {
|
||||||
current_alpha = a_; // IN: opaco si no activado
|
current_alpha = a_; // IN: opaco si no activado
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// Cuadrado activado - calculamos progreso
|
// Cuadrado activado - calculamos progreso
|
||||||
Uint32 square_elapsed = current_time - square_age_[i];
|
Uint32 square_elapsed = current_time - square_age_[i];
|
||||||
float progress = std::min(static_cast<float>(square_elapsed) / square_transition_duration_, 1.0f);
|
float progress = std::min(static_cast<float>(square_elapsed) / square_transition_duration_, 1.0f);
|
||||||
|
|
||||||
if (mode_ == Mode::OUT) {
|
if (mode_ == Mode::OUT) {
|
||||||
current_alpha = static_cast<Uint8>(progress * a_); // 0 → 255
|
current_alpha = static_cast<Uint8>(progress * a_); // 0 → 255
|
||||||
} else {
|
} else {
|
||||||
current_alpha = static_cast<Uint8>((1.0f - progress) * a_); // 255 → 0
|
current_alpha = static_cast<Uint8>((1.0f - progress) * a_); // 255 → 0
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (current_alpha > 0) {
|
if (current_alpha > 0) {
|
||||||
SDL_SetRenderDrawColor(renderer_, r_, g_, b_, current_alpha);
|
SDL_SetRenderDrawColor(renderer_, r_, g_, b_, current_alpha);
|
||||||
SDL_RenderFillRect(renderer_, &square_[i]);
|
SDL_RenderFillRect(renderer_, &square_[i]);
|
||||||
|
|||||||
@@ -11,12 +11,12 @@ class Fade {
|
|||||||
public:
|
public:
|
||||||
// --- Enums ---
|
// --- Enums ---
|
||||||
enum class Type : Uint8 {
|
enum class Type : Uint8 {
|
||||||
FULLSCREEN = 0, // Fundido de pantalla completa
|
FULLSCREEN = 0, // Fundido de pantalla completa
|
||||||
CENTER = 1, // Fundido desde el centro
|
CENTER = 1, // Fundido desde el centro
|
||||||
RANDOM_SQUARE = 2, // Fundido con cuadrados aleatorios
|
RANDOM_SQUARE = 2, // Fundido con cuadrados aleatorios
|
||||||
RANDOM_SQUARE2 = 3, // Fundido con cuadrados aleatorios (variante 2)
|
RANDOM_SQUARE2 = 3, // Fundido con cuadrados aleatorios (variante 2)
|
||||||
DIAGONAL = 4, // Fundido diagonal desde esquina superior izquierda
|
DIAGONAL = 4, // Fundido diagonal desde esquina superior izquierda
|
||||||
VENETIAN = 5, // Fundido tipo persiana veneciana
|
VENETIAN = 5, // Fundido tipo persiana veneciana
|
||||||
};
|
};
|
||||||
|
|
||||||
enum class Mode : Uint8 {
|
enum class Mode : Uint8 {
|
||||||
@@ -37,10 +37,11 @@ class Fade {
|
|||||||
~Fade();
|
~Fade();
|
||||||
|
|
||||||
// --- Métodos principales ---
|
// --- Métodos principales ---
|
||||||
void reset(); // Resetea variables para reutilizar el fade
|
void reset(); // Resetea variables para reutilizar el fade
|
||||||
void render(); // Dibuja la transición en pantalla
|
void render(); // Dibuja la transición en pantalla
|
||||||
void update(); // Actualiza el estado interno
|
void update(); // Actualiza el estado interno (ya usa tiempo real)
|
||||||
void activate(); // Activa el fade
|
void update(float delta_time); // Compatibilidad delta-time (ignora el parámetro)
|
||||||
|
void activate(); // Activa el fade
|
||||||
|
|
||||||
// --- Configuración ---
|
// --- Configuración ---
|
||||||
void setColor(Uint8 r, Uint8 g, Uint8 b); // Establece el color RGB del fade
|
void setColor(Uint8 r, Uint8 g, Uint8 b); // Establece el color RGB del fade
|
||||||
@@ -104,10 +105,10 @@ class Fade {
|
|||||||
void calculateVenetianProgress(); // Calcula el progreso del efecto veneciano
|
void calculateVenetianProgress(); // Calcula el progreso del efecto veneciano
|
||||||
|
|
||||||
// --- Dibujo de efectos visuales ---
|
// --- Dibujo de efectos visuales ---
|
||||||
void drawCenterFadeRectangles(); // Dibuja los rectángulos del fundido central
|
void drawCenterFadeRectangles(); // Dibuja los rectángulos del fundido central
|
||||||
void drawRandomSquares(int active_count = -1); // Dibuja los cuadrados aleatorios del fundido
|
void drawRandomSquares(int active_count = -1); // Dibuja los cuadrados aleatorios del fundido
|
||||||
void drawRandomSquares2(); // Dibuja los cuadrados con transición de color (RANDOM_SQUARE2)
|
void drawRandomSquares2(); // Dibuja los cuadrados con transición de color (RANDOM_SQUARE2)
|
||||||
void drawDiagonal(); // Dibuja los cuadrados con patrón diagonal
|
void drawDiagonal(); // Dibuja los cuadrados con patrón diagonal
|
||||||
void activateDiagonal(int diagonal_index, Uint32 current_time); // Activa una diagonal específica
|
void activateDiagonal(int diagonal_index, Uint32 current_time); // Activa una diagonal específica
|
||||||
void drawVenetianBlinds(); // Dibuja las persianas venecianas del fundido
|
void drawVenetianBlinds(); // Dibuja las persianas venecianas del fundido
|
||||||
};
|
};
|
||||||
@@ -15,8 +15,9 @@
|
|||||||
#include "texture.h" // Para Texture
|
#include "texture.h" // Para Texture
|
||||||
|
|
||||||
constexpr int ZOOM_FACTOR = 5;
|
constexpr int ZOOM_FACTOR = 5;
|
||||||
constexpr int FLASH_DELAY = 3;
|
constexpr float FLASH_DELAY_S = 0.05f; // 3 frames → 0.05s
|
||||||
constexpr int FLASH_LENGTH = FLASH_DELAY + 3;
|
constexpr float FLASH_DURATION_S = 0.1f; // 6 frames → 0.1s (3 + 3)
|
||||||
|
constexpr Color FLASH_COLOR = Color(0xFF, 0xFF, 0xFF); // Color blanco para el flash
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
GameLogo::GameLogo(int x, int y)
|
GameLogo::GameLogo(int x, int y)
|
||||||
@@ -45,6 +46,7 @@ void GameLogo::init() {
|
|||||||
arcade_edition_status_ = Status::DISABLED;
|
arcade_edition_status_ = Status::DISABLED;
|
||||||
shake_.init(1, 2, 8, XP);
|
shake_.init(1, 2, 8, XP);
|
||||||
zoom_ = 3.0F * ZOOM_FACTOR;
|
zoom_ = 3.0F * ZOOM_FACTOR;
|
||||||
|
post_finished_timer_ = 0.0f;
|
||||||
|
|
||||||
// Inicializa el bitmap de 'Coffee'
|
// Inicializa el bitmap de 'Coffee'
|
||||||
coffee_sprite_->setPosX(XP);
|
coffee_sprite_->setPosX(XP);
|
||||||
@@ -52,44 +54,44 @@ void GameLogo::init() {
|
|||||||
coffee_sprite_->setWidth(coffee_texture_->getWidth());
|
coffee_sprite_->setWidth(coffee_texture_->getWidth());
|
||||||
coffee_sprite_->setHeight(coffee_texture_->getHeight());
|
coffee_sprite_->setHeight(coffee_texture_->getHeight());
|
||||||
coffee_sprite_->setVelX(0.0F);
|
coffee_sprite_->setVelX(0.0F);
|
||||||
coffee_sprite_->setVelY(2.5F);
|
coffee_sprite_->setVelY(COFFEE_VEL_Y);
|
||||||
coffee_sprite_->setAccelX(0.0F);
|
coffee_sprite_->setAccelX(0.0F);
|
||||||
coffee_sprite_->setAccelY(0.1F);
|
coffee_sprite_->setAccelY(COFFEE_ACCEL_Y);
|
||||||
coffee_sprite_->setSpriteClip(0, 0, coffee_texture_->getWidth(), coffee_texture_->getHeight());
|
coffee_sprite_->setSpriteClip(0, 0, coffee_texture_->getWidth(), coffee_texture_->getHeight());
|
||||||
coffee_sprite_->setEnabled(true);
|
coffee_sprite_->setEnabled(true);
|
||||||
coffee_sprite_->setFinishedCounter(0);
|
coffee_sprite_->setFinishedDelay(0.0f);
|
||||||
coffee_sprite_->setDestX(XP);
|
coffee_sprite_->setDestX(XP);
|
||||||
coffee_sprite_->setDestY(y_ - coffee_texture_->getHeight());
|
coffee_sprite_->setDestY(y_ - coffee_texture_->getHeight());
|
||||||
|
|
||||||
// Inicializa el bitmap de 'Crisis'
|
// Inicializa el bitmap de 'Crisis'
|
||||||
crisis_sprite_->setPosX(XP + 15);
|
crisis_sprite_->setPosX(XP + CRISIS_OFFSET_X);
|
||||||
crisis_sprite_->setPosY(y_ + DESP);
|
crisis_sprite_->setPosY(y_ + DESP);
|
||||||
crisis_sprite_->setWidth(crisis_texture_->getWidth());
|
crisis_sprite_->setWidth(crisis_texture_->getWidth());
|
||||||
crisis_sprite_->setHeight(crisis_texture_->getHeight());
|
crisis_sprite_->setHeight(crisis_texture_->getHeight());
|
||||||
crisis_sprite_->setVelX(0.0F);
|
crisis_sprite_->setVelX(0.0F);
|
||||||
crisis_sprite_->setVelY(-2.5F);
|
crisis_sprite_->setVelY(CRISIS_VEL_Y);
|
||||||
crisis_sprite_->setAccelX(0.0F);
|
crisis_sprite_->setAccelX(0.0F);
|
||||||
crisis_sprite_->setAccelY(-0.1F);
|
crisis_sprite_->setAccelY(CRISIS_ACCEL_Y);
|
||||||
crisis_sprite_->setSpriteClip(0, 0, crisis_texture_->getWidth(), crisis_texture_->getHeight());
|
crisis_sprite_->setSpriteClip(0, 0, crisis_texture_->getWidth(), crisis_texture_->getHeight());
|
||||||
crisis_sprite_->setEnabled(true);
|
crisis_sprite_->setEnabled(true);
|
||||||
crisis_sprite_->setFinishedCounter(0);
|
crisis_sprite_->setFinishedDelay(0.0f);
|
||||||
crisis_sprite_->setDestX(XP + 15);
|
crisis_sprite_->setDestX(XP + CRISIS_OFFSET_X);
|
||||||
crisis_sprite_->setDestY(y_);
|
crisis_sprite_->setDestY(y_);
|
||||||
|
|
||||||
// Inicializa el bitmap de 'DustRight'
|
// Inicializa el bitmap de 'DustRight'
|
||||||
dust_right_sprite_->resetAnimation();
|
dust_right_sprite_->resetAnimation();
|
||||||
dust_right_sprite_->setPosX(coffee_sprite_->getPosX() + coffee_sprite_->getWidth());
|
dust_right_sprite_->setPosX(coffee_sprite_->getPosX() + coffee_sprite_->getWidth());
|
||||||
dust_right_sprite_->setPosY(y_);
|
dust_right_sprite_->setPosY(y_);
|
||||||
dust_right_sprite_->setWidth(16);
|
dust_right_sprite_->setWidth(DUST_SIZE);
|
||||||
dust_right_sprite_->setHeight(16);
|
dust_right_sprite_->setHeight(DUST_SIZE);
|
||||||
dust_right_sprite_->setFlip(SDL_FLIP_HORIZONTAL);
|
dust_right_sprite_->setFlip(SDL_FLIP_HORIZONTAL);
|
||||||
|
|
||||||
// Inicializa el bitmap de 'DustLeft'
|
// Inicializa el bitmap de 'DustLeft'
|
||||||
dust_left_sprite_->resetAnimation();
|
dust_left_sprite_->resetAnimation();
|
||||||
dust_left_sprite_->setPosX(coffee_sprite_->getPosX() - 16);
|
dust_left_sprite_->setPosX(coffee_sprite_->getPosX() - DUST_SIZE);
|
||||||
dust_left_sprite_->setPosY(y_);
|
dust_left_sprite_->setPosY(y_);
|
||||||
dust_left_sprite_->setWidth(16);
|
dust_left_sprite_->setWidth(DUST_SIZE);
|
||||||
dust_left_sprite_->setHeight(16);
|
dust_left_sprite_->setHeight(DUST_SIZE);
|
||||||
|
|
||||||
// Inicializa el bitmap de 'Arcade Edition'
|
// Inicializa el bitmap de 'Arcade Edition'
|
||||||
arcade_edition_sprite_->setZoom(zoom_);
|
arcade_edition_sprite_->setZoom(zoom_);
|
||||||
@@ -112,45 +114,45 @@ void GameLogo::render() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Actualiza la lógica de la clase
|
// Actualiza la lógica de la clase (time-based)
|
||||||
void GameLogo::update() {
|
void GameLogo::update(float deltaTime) {
|
||||||
updateCoffeeCrisis();
|
updateCoffeeCrisis(deltaTime);
|
||||||
updateArcadeEdition();
|
updateArcadeEdition(deltaTime);
|
||||||
updatePostFinishedCounter();
|
updatePostFinishedCounter(deltaTime);
|
||||||
}
|
}
|
||||||
|
|
||||||
void GameLogo::updateCoffeeCrisis() {
|
void GameLogo::updateCoffeeCrisis(float deltaTime) {
|
||||||
switch (coffee_crisis_status_) {
|
switch (coffee_crisis_status_) {
|
||||||
case Status::MOVING:
|
case Status::MOVING:
|
||||||
handleCoffeeCrisisMoving();
|
handleCoffeeCrisisMoving(deltaTime);
|
||||||
break;
|
break;
|
||||||
case Status::SHAKING:
|
case Status::SHAKING:
|
||||||
handleCoffeeCrisisShaking();
|
handleCoffeeCrisisShaking(deltaTime);
|
||||||
break;
|
break;
|
||||||
case Status::FINISHED:
|
case Status::FINISHED:
|
||||||
handleCoffeeCrisisFinished();
|
handleCoffeeCrisisFinished(deltaTime);
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void GameLogo::updateArcadeEdition() {
|
void GameLogo::updateArcadeEdition(float deltaTime) {
|
||||||
switch (arcade_edition_status_) {
|
switch (arcade_edition_status_) {
|
||||||
case Status::MOVING:
|
case Status::MOVING:
|
||||||
handleArcadeEditionMoving();
|
handleArcadeEditionMoving(deltaTime);
|
||||||
break;
|
break;
|
||||||
case Status::SHAKING:
|
case Status::SHAKING:
|
||||||
handleArcadeEditionShaking();
|
handleArcadeEditionShaking(deltaTime);
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void GameLogo::handleCoffeeCrisisMoving() {
|
void GameLogo::handleCoffeeCrisisMoving(float deltaTime) {
|
||||||
coffee_sprite_->update();
|
coffee_sprite_->update(deltaTime);
|
||||||
crisis_sprite_->update();
|
crisis_sprite_->update(deltaTime);
|
||||||
|
|
||||||
if (coffee_sprite_->hasFinished() && crisis_sprite_->hasFinished()) {
|
if (coffee_sprite_->hasFinished() && crisis_sprite_->hasFinished()) {
|
||||||
coffee_crisis_status_ = Status::SHAKING;
|
coffee_crisis_status_ = Status::SHAKING;
|
||||||
@@ -158,22 +160,23 @@ void GameLogo::handleCoffeeCrisisMoving() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void GameLogo::handleCoffeeCrisisShaking() {
|
void GameLogo::handleCoffeeCrisisShaking(float deltaTime) {
|
||||||
if (shake_.remaining > 0) {
|
if (shake_.remaining > 0) {
|
||||||
processShakeEffect(coffee_sprite_.get(), crisis_sprite_.get());
|
processShakeEffect(coffee_sprite_.get(), crisis_sprite_.get(), deltaTime);
|
||||||
} else {
|
} else {
|
||||||
finishCoffeeCrisisShaking();
|
finishCoffeeCrisisShaking();
|
||||||
}
|
}
|
||||||
|
|
||||||
updateDustSprites();
|
updateDustSprites(deltaTime);
|
||||||
}
|
}
|
||||||
|
|
||||||
void GameLogo::handleCoffeeCrisisFinished() {
|
void GameLogo::handleCoffeeCrisisFinished(float deltaTime) {
|
||||||
updateDustSprites();
|
updateDustSprites(deltaTime);
|
||||||
}
|
}
|
||||||
|
|
||||||
void GameLogo::handleArcadeEditionMoving() {
|
void GameLogo::handleArcadeEditionMoving(float deltaTime) {
|
||||||
zoom_ -= 0.1F * ZOOM_FACTOR;
|
// DeltaTime en segundos: decremento por segundo
|
||||||
|
zoom_ -= (ZOOM_DECREMENT_PER_S * ZOOM_FACTOR) * deltaTime;
|
||||||
arcade_edition_sprite_->setZoom(zoom_);
|
arcade_edition_sprite_->setZoom(zoom_);
|
||||||
|
|
||||||
if (zoom_ <= 1.0F) {
|
if (zoom_ <= 1.0F) {
|
||||||
@@ -181,34 +184,38 @@ void GameLogo::handleArcadeEditionMoving() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void GameLogo::handleArcadeEditionShaking() {
|
void GameLogo::handleArcadeEditionShaking(float deltaTime) {
|
||||||
if (shake_.remaining > 0) {
|
if (shake_.remaining > 0) {
|
||||||
processArcadeEditionShake();
|
processArcadeEditionShake(deltaTime);
|
||||||
} else {
|
} else {
|
||||||
arcade_edition_sprite_->setX(shake_.origin);
|
arcade_edition_sprite_->setX(shake_.origin);
|
||||||
arcade_edition_status_ = Status::FINISHED;
|
arcade_edition_status_ = Status::FINISHED;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void GameLogo::processShakeEffect(SmartSprite* primary_sprite, SmartSprite* secondary_sprite) {
|
|
||||||
if (shake_.counter > 0) {
|
void GameLogo::processShakeEffect(SmartSprite* primary_sprite, SmartSprite* secondary_sprite, float deltaTime) {
|
||||||
shake_.counter--;
|
shake_.time_accumulator += deltaTime;
|
||||||
} else {
|
|
||||||
shake_.counter = shake_.delay;
|
if (shake_.time_accumulator >= SHAKE_DELAY_S) {
|
||||||
|
shake_.time_accumulator -= SHAKE_DELAY_S;
|
||||||
const auto DISPLACEMENT = calculateShakeDisplacement();
|
const auto DISPLACEMENT = calculateShakeDisplacement();
|
||||||
primary_sprite->setPosX(shake_.origin + DISPLACEMENT);
|
primary_sprite->setPosX(shake_.origin + DISPLACEMENT);
|
||||||
if (secondary_sprite != nullptr) {
|
if (secondary_sprite != nullptr) {
|
||||||
secondary_sprite->setPosX(shake_.origin + DISPLACEMENT + 15);
|
secondary_sprite->setPosX(shake_.origin + DISPLACEMENT + CRISIS_OFFSET_X);
|
||||||
}
|
}
|
||||||
shake_.remaining--;
|
shake_.remaining--;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void GameLogo::processArcadeEditionShake() {
|
void GameLogo::processArcadeEditionShake(float deltaTime) {
|
||||||
if (shake_.counter > 0) {
|
// Delay fijo en segundos (shake_.delay era frames, ahora usamos constante)
|
||||||
shake_.counter--;
|
float delayTime = SHAKE_DELAY_S;
|
||||||
} else {
|
|
||||||
shake_.counter = shake_.delay;
|
shake_.time_accumulator += deltaTime;
|
||||||
|
|
||||||
|
if (shake_.time_accumulator >= delayTime) {
|
||||||
|
shake_.time_accumulator -= delayTime;
|
||||||
const auto DISPLACEMENT = calculateShakeDisplacement();
|
const auto DISPLACEMENT = calculateShakeDisplacement();
|
||||||
arcade_edition_sprite_->setX(shake_.origin + DISPLACEMENT);
|
arcade_edition_sprite_->setX(shake_.origin + DISPLACEMENT);
|
||||||
shake_.remaining--;
|
shake_.remaining--;
|
||||||
@@ -221,7 +228,7 @@ auto GameLogo::calculateShakeDisplacement() const -> int {
|
|||||||
|
|
||||||
void GameLogo::finishCoffeeCrisisShaking() {
|
void GameLogo::finishCoffeeCrisisShaking() {
|
||||||
coffee_sprite_->setPosX(shake_.origin);
|
coffee_sprite_->setPosX(shake_.origin);
|
||||||
crisis_sprite_->setPosX(shake_.origin + 15);
|
crisis_sprite_->setPosX(shake_.origin + CRISIS_OFFSET_X);
|
||||||
coffee_crisis_status_ = Status::FINISHED;
|
coffee_crisis_status_ = Status::FINISHED;
|
||||||
arcade_edition_status_ = Status::MOVING;
|
arcade_edition_status_ = Status::MOVING;
|
||||||
}
|
}
|
||||||
@@ -236,20 +243,20 @@ void GameLogo::finishArcadeEditionMoving() {
|
|||||||
|
|
||||||
void GameLogo::playTitleEffects() {
|
void GameLogo::playTitleEffects() {
|
||||||
Audio::get()->playSound("title.wav");
|
Audio::get()->playSound("title.wav");
|
||||||
Screen::get()->flash(Color(0xFF, 0xFF, 0xFF), FLASH_LENGTH, FLASH_DELAY);
|
Screen::get()->flash(FLASH_COLOR, FLASH_DURATION_S, FLASH_DELAY_S);
|
||||||
Screen::get()->shake();
|
Screen::get()->shake();
|
||||||
}
|
}
|
||||||
|
|
||||||
void GameLogo::updateDustSprites() {
|
void GameLogo::updateDustSprites(float deltaTime) {
|
||||||
dust_right_sprite_->update();
|
dust_right_sprite_->update(deltaTime);
|
||||||
dust_left_sprite_->update();
|
dust_left_sprite_->update(deltaTime);
|
||||||
}
|
}
|
||||||
|
|
||||||
void GameLogo::updatePostFinishedCounter() {
|
void GameLogo::updatePostFinishedCounter(float deltaTime) {
|
||||||
if (coffee_crisis_status_ == Status::FINISHED &&
|
if (coffee_crisis_status_ == Status::FINISHED &&
|
||||||
arcade_edition_status_ == Status::FINISHED &&
|
arcade_edition_status_ == Status::FINISHED) {
|
||||||
post_finished_counter_ > 0) {
|
|
||||||
--post_finished_counter_;
|
post_finished_timer_ += deltaTime;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -261,7 +268,7 @@ void GameLogo::enable() {
|
|||||||
|
|
||||||
// Indica si ha terminado la animación
|
// Indica si ha terminado la animación
|
||||||
auto GameLogo::hasFinished() const -> bool {
|
auto GameLogo::hasFinished() const -> bool {
|
||||||
return post_finished_counter_ == 0;
|
return post_finished_timer_ >= post_finished_delay_s_;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Calcula el desplazamiento vertical inicial
|
// Calcula el desplazamiento vertical inicial
|
||||||
|
|||||||
@@ -11,14 +11,25 @@ class Texture;
|
|||||||
// --- Clase GameLogo: gestor del logo del juego ---
|
// --- Clase GameLogo: gestor del logo del juego ---
|
||||||
class GameLogo {
|
class GameLogo {
|
||||||
public:
|
public:
|
||||||
|
// --- Constantes ---
|
||||||
|
static constexpr float COFFEE_VEL_Y = 0.15F * 1000.0F; // Velocidad Y de coffee sprite (pixels/s) - 0.15F * 1000 = 150 pixels/s
|
||||||
|
static constexpr float COFFEE_ACCEL_Y = 0.00036F * 1000000.0F; // Aceleración Y de coffee sprite (pixels/s²) - 0.00036F * 1000000 = 360 pixels/s²
|
||||||
|
static constexpr float CRISIS_VEL_Y = -0.15F * 1000.0F; // Velocidad Y de crisis sprite (pixels/s) - -0.15F * 1000 = -150 pixels/s
|
||||||
|
static constexpr float CRISIS_ACCEL_Y = -0.00036F * 1000000.0F; // Aceleración Y de crisis sprite (pixels/s²) - -0.00036F * 1000000 = -360 pixels/s²
|
||||||
|
static constexpr int CRISIS_OFFSET_X = 15; // Desplazamiento X de crisis sprite
|
||||||
|
static constexpr int DUST_SIZE = 16; // Tamaño de dust sprites
|
||||||
|
static constexpr float ZOOM_DECREMENT_PER_S = 0.006F * 1000.0F; // Decremento de zoom por segundo (0.006F * 1000 = 6.0F per second)
|
||||||
|
static constexpr float SHAKE_DELAY_S = 33.34F / 1000.0F; // Delay de shake en segundos (33.34ms / 1000 = 0.03334s)
|
||||||
|
static constexpr float POST_FINISHED_FRAME_TIME_S = 16.67F / 1000.0F; // Tiempo entre decrementos del counter (16.67ms / 1000 = 0.01667s)
|
||||||
|
|
||||||
// --- Constructores y destructor ---
|
// --- Constructores y destructor ---
|
||||||
GameLogo(int x, int y);
|
GameLogo(int x, int y);
|
||||||
~GameLogo() = default;
|
~GameLogo() = default;
|
||||||
|
|
||||||
// --- Métodos principales ---
|
// --- Métodos principales ---
|
||||||
void render(); // Pinta la clase en pantalla
|
void render(); // Pinta la clase en pantalla
|
||||||
void update(); // Actualiza la lógica de la clase
|
void update(float deltaTime); // Actualiza la lógica de la clase (time-based)
|
||||||
void enable(); // Activa la clase
|
void enable(); // Activa la clase
|
||||||
|
|
||||||
// --- Getters ---
|
// --- Getters ---
|
||||||
[[nodiscard]] auto hasFinished() const -> bool; // Indica si ha terminado la animación
|
[[nodiscard]] auto hasFinished() const -> bool; // Indica si ha terminado la animación
|
||||||
@@ -34,16 +45,22 @@ class GameLogo {
|
|||||||
|
|
||||||
// --- Estructuras privadas ---
|
// --- Estructuras privadas ---
|
||||||
struct Shake {
|
struct Shake {
|
||||||
int desp = 1; // Pixels de desplazamiento para agitar la pantalla en el eje x
|
int desp = 1; // Pixels de desplazamiento para agitar la pantalla en el eje x
|
||||||
int delay = 2; // Retraso entre cada desplazamiento de la pantalla al agitarse
|
int delay = 2; // Retraso entre cada desplazamiento de la pantalla al agitarse (frame-based)
|
||||||
int length = 8; // Cantidad de desplazamientos a realizar
|
int length = 8; // Cantidad de desplazamientos a realizar
|
||||||
int remaining = length; // Cantidad de desplazamientos pendientes a realizar
|
int remaining = length; // Cantidad de desplazamientos pendientes a realizar
|
||||||
int counter = delay; // Contador para el retraso
|
int counter = delay; // Contador para el retraso (frame-based)
|
||||||
int origin = 0; // Valor inicial de la pantalla para dejarla igual tras el desplazamiento
|
float time_accumulator = 0.0f; // Acumulador de tiempo para deltaTime
|
||||||
|
int origin = 0; // Valor inicial de la pantalla para dejarla igual tras el desplazamiento
|
||||||
|
|
||||||
Shake() = default;
|
Shake() = default;
|
||||||
Shake(int d, int de, int l, int o)
|
Shake(int d, int de, int l, int o)
|
||||||
: desp(d), delay(de), length(l), remaining(l), counter(de), origin(o) {}
|
: desp(d),
|
||||||
|
delay(de),
|
||||||
|
length(l),
|
||||||
|
remaining(l),
|
||||||
|
counter(de),
|
||||||
|
origin(o) {}
|
||||||
|
|
||||||
void init(int d, int de, int l, int o) {
|
void init(int d, int de, int l, int o) {
|
||||||
desp = d;
|
desp = d;
|
||||||
@@ -51,6 +68,7 @@ class GameLogo {
|
|||||||
length = l;
|
length = l;
|
||||||
remaining = l;
|
remaining = l;
|
||||||
counter = de;
|
counter = de;
|
||||||
|
time_accumulator = 0.0f;
|
||||||
origin = o;
|
origin = o;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -74,32 +92,34 @@ class GameLogo {
|
|||||||
float x_; // Posición X del logo
|
float x_; // Posición X del logo
|
||||||
float y_; // Posición Y del logo
|
float y_; // Posición Y del logo
|
||||||
float zoom_ = 1.0F; // Zoom aplicado al texto "ARCADE EDITION"
|
float zoom_ = 1.0F; // Zoom aplicado al texto "ARCADE EDITION"
|
||||||
int post_finished_counter_ = 1; // Contador final tras animaciones
|
float post_finished_delay_s_ = POST_FINISHED_FRAME_TIME_S; // Retraso final tras animaciones (s)
|
||||||
|
float post_finished_timer_ = 0.0f; // Timer acumulado para retraso final (s)
|
||||||
|
|
||||||
// --- Inicialización ---
|
// --- Inicialización ---
|
||||||
void init(); // Inicializa las variables
|
void init(); // Inicializa las variables
|
||||||
[[nodiscard]] auto getInitialVerticalDesp() const -> int; // Calcula el desplazamiento vertical inicial
|
[[nodiscard]] auto getInitialVerticalDesp() const -> int; // Calcula el desplazamiento vertical inicial
|
||||||
|
|
||||||
// --- Actualización de estados específicos ---
|
// --- Actualización de estados específicos ---
|
||||||
void updateCoffeeCrisis(); // Actualiza el estado de "Coffee Crisis"
|
void updateCoffeeCrisis(float deltaTime); // Actualiza el estado de "Coffee Crisis" (time-based)
|
||||||
void updateArcadeEdition(); // Actualiza el estado de "Arcade Edition"
|
void updateArcadeEdition(float deltaTime); // Actualiza el estado de "Arcade Edition" (time-based)
|
||||||
void updatePostFinishedCounter(); // Actualiza el contador tras finalizar una animación
|
void updatePostFinishedCounter(float deltaTime); // Actualiza el contador tras finalizar una animación (time-based)
|
||||||
|
|
||||||
// --- Efectos visuales: movimiento y sacudidas ---
|
// --- Efectos visuales: movimiento y sacudidas ---
|
||||||
void handleCoffeeCrisisMoving(); // Maneja el movimiento de "Coffee Crisis"
|
void handleCoffeeCrisisMoving(float deltaTime); // Maneja el movimiento de "Coffee Crisis" (time-based)
|
||||||
void handleCoffeeCrisisShaking(); // Maneja la sacudida de "Coffee Crisis"
|
void handleCoffeeCrisisShaking(float deltaTime); // Maneja la sacudida de "Coffee Crisis" (time-based)
|
||||||
void handleArcadeEditionMoving(); // Maneja el movimiento de "Arcade Edition"
|
void handleArcadeEditionMoving(float deltaTime); // Maneja el movimiento de "Arcade Edition" (time-based)
|
||||||
void handleArcadeEditionShaking(); // Maneja la sacudida de "Arcade Edition"
|
void handleArcadeEditionShaking(float deltaTime); // Maneja la sacudida de "Arcade Edition" (time-based)
|
||||||
void processShakeEffect(SmartSprite* primary_sprite, SmartSprite* secondary_sprite = nullptr); // Procesa el efecto de sacudida en sprites
|
void processShakeEffect(SmartSprite* primary_sprite, SmartSprite* secondary_sprite = nullptr); // Procesa el efecto de sacudida en sprites (frame-based)
|
||||||
void processArcadeEditionShake(); // Procesa la sacudida específica de "Arcade Edition"
|
void processShakeEffect(SmartSprite* primary_sprite, SmartSprite* secondary_sprite, float deltaTime); // Procesa el efecto de sacudida en sprites (time-based)
|
||||||
[[nodiscard]] auto calculateShakeDisplacement() const -> int; // Calcula el desplazamiento de la sacudida
|
void processArcadeEditionShake(float deltaTime); // Procesa la sacudida específica de "Arcade Edition" (time-based)
|
||||||
|
[[nodiscard]] auto calculateShakeDisplacement() const -> int; // Calcula el desplazamiento de la sacudida
|
||||||
|
|
||||||
// --- Gestión de finalización de efectos ---
|
// --- Gestión de finalización de efectos ---
|
||||||
void handleCoffeeCrisisFinished(); // Maneja el final de la animación "Coffee Crisis"
|
void handleCoffeeCrisisFinished(float deltaTime); // Maneja el final de la animación "Coffee Crisis" (time-based)
|
||||||
void finishCoffeeCrisisShaking(); // Finaliza la sacudida de "Coffee Crisis"
|
void finishCoffeeCrisisShaking(); // Finaliza la sacudida de "Coffee Crisis"
|
||||||
void finishArcadeEditionMoving(); // Finaliza el movimiento de "Arcade Edition"
|
void finishArcadeEditionMoving(); // Finaliza el movimiento de "Arcade Edition"
|
||||||
|
|
||||||
// --- Utilidades ---
|
// --- Utilidades ---
|
||||||
static void playTitleEffects(); // Reproduce efectos visuales/sonoros del título
|
static void playTitleEffects(); // Reproduce efectos visuales/sonoros del título
|
||||||
void updateDustSprites(); // Actualiza los sprites de polvo
|
void updateDustSprites(float deltaTime); // Actualiza los sprites de polvo (time-based)
|
||||||
};
|
};
|
||||||
@@ -32,7 +32,9 @@ class Input {
|
|||||||
bool just_pressed; // Se acaba de pulsar en este fotograma
|
bool just_pressed; // Se acaba de pulsar en este fotograma
|
||||||
|
|
||||||
KeyState(Uint8 scancode = 0, bool is_held = false, bool just_pressed = false)
|
KeyState(Uint8 scancode = 0, bool is_held = false, bool just_pressed = false)
|
||||||
: scancode(scancode), is_held(is_held), just_pressed(just_pressed) {}
|
: scancode(scancode),
|
||||||
|
is_held(is_held),
|
||||||
|
just_pressed(just_pressed) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
struct ButtonState {
|
struct ButtonState {
|
||||||
@@ -43,7 +45,10 @@ class Input {
|
|||||||
bool trigger_active{false}; // Estado del trigger como botón digital
|
bool trigger_active{false}; // Estado del trigger como botón digital
|
||||||
|
|
||||||
ButtonState(int btn = static_cast<int>(SDL_GAMEPAD_BUTTON_INVALID), bool is_held = false, bool just_pressed = false, bool axis_act = false)
|
ButtonState(int btn = static_cast<int>(SDL_GAMEPAD_BUTTON_INVALID), bool is_held = false, bool just_pressed = false, bool axis_act = false)
|
||||||
: button(btn), is_held(is_held), just_pressed(just_pressed), axis_active(axis_act) {}
|
: button(btn),
|
||||||
|
is_held(is_held),
|
||||||
|
just_pressed(just_pressed),
|
||||||
|
axis_active(axis_act) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
struct Keyboard {
|
struct Keyboard {
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
#include "item.h"
|
#include "item.h"
|
||||||
|
|
||||||
#include <algorithm> // Para clamp
|
#include <algorithm> // Para clamp
|
||||||
|
#include <cmath> // Para fmod
|
||||||
#include <cstdlib> // Para rand
|
#include <cstdlib> // Para rand
|
||||||
|
|
||||||
#include "animated_sprite.h" // Para AnimatedSprite
|
#include "animated_sprite.h" // Para AnimatedSprite
|
||||||
@@ -9,16 +10,18 @@
|
|||||||
class Texture; // lines 6-6
|
class Texture; // lines 6-6
|
||||||
|
|
||||||
Item::Item(ItemType type, float x, float y, SDL_FRect &play_area, const std::shared_ptr<Texture> &texture, const std::vector<std::string> &animation)
|
Item::Item(ItemType type, float x, float y, SDL_FRect &play_area, const std::shared_ptr<Texture> &texture, const std::vector<std::string> &animation)
|
||||||
: sprite_(std::make_unique<AnimatedSprite>(texture, animation)), play_area_(play_area), type_(type) {
|
: sprite_(std::make_unique<AnimatedSprite>(texture, animation)),
|
||||||
|
play_area_(play_area),
|
||||||
|
type_(type) {
|
||||||
switch (type) {
|
switch (type) {
|
||||||
case ItemType::COFFEE_MACHINE: {
|
case ItemType::COFFEE_MACHINE: {
|
||||||
width_ = COFFEE_MACHINE_WIDTH;
|
width_ = COFFEE_MACHINE_WIDTH;
|
||||||
height_ = COFFEE_MACHINE_HEIGHT;
|
height_ = COFFEE_MACHINE_HEIGHT;
|
||||||
pos_x_ = getCoffeeMachineSpawn(x, width_, play_area_.w);
|
pos_x_ = getCoffeeMachineSpawn(x, width_, play_area_.w);
|
||||||
pos_y_ = y;
|
pos_y_ = y;
|
||||||
vel_x_ = ((rand() % 3) - 1) * 0.5F;
|
vel_x_ = ((rand() % 3) - 1) * COFFEE_MACHINE_VEL_X_FACTOR;
|
||||||
vel_y_ = -0.1F;
|
vel_y_ = COFFEE_MACHINE_VEL_Y;
|
||||||
accel_y_ = 0.1F;
|
accel_y_ = COFFEE_MACHINE_ACCEL_Y;
|
||||||
collider_.r = 10;
|
collider_.r = 10;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
@@ -31,13 +34,13 @@ Item::Item(ItemType type, float x, float y, SDL_FRect &play_area, const std::sha
|
|||||||
const int direction = rand() % 6;
|
const int direction = rand() % 6;
|
||||||
if (direction < 3) {
|
if (direction < 3) {
|
||||||
// Velocidades negativas: -1.0, -0.66, -0.33
|
// Velocidades negativas: -1.0, -0.66, -0.33
|
||||||
vel_x_ = -1.0F + (direction * 0.33F);
|
vel_x_ = -ITEM_VEL_X_BASE + (direction * ITEM_VEL_X_STEP);
|
||||||
} else {
|
} else {
|
||||||
// Velocidades positivas: 0.33, 0.66, 1.0
|
// Velocidades positivas: 0.33, 0.66, 1.0
|
||||||
vel_x_ = 0.33F + ((direction - 3) * 0.33F);
|
vel_x_ = ITEM_VEL_X_STEP + ((direction - 3) * ITEM_VEL_X_STEP);
|
||||||
}
|
}
|
||||||
vel_y_ = -4.0F;
|
vel_y_ = ITEM_VEL_Y;
|
||||||
accel_y_ = 0.2F;
|
accel_y_ = ITEM_ACCEL_Y;
|
||||||
collider_.r = width_ / 2;
|
collider_.r = width_ / 2;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
@@ -64,24 +67,34 @@ void Item::alignTo(int x) {
|
|||||||
|
|
||||||
void Item::render() {
|
void Item::render() {
|
||||||
if (enabled_) {
|
if (enabled_) {
|
||||||
if (time_to_live_ > 200) {
|
// Muestra normalmente hasta los últimos ~3.3 segundos
|
||||||
sprite_->render();
|
constexpr float BLINK_START_S = LIFETIME_DURATION_S - 3.33f;
|
||||||
} else if (time_to_live_ % 20 > 10) {
|
|
||||||
|
if (lifetime_timer_ < BLINK_START_S) {
|
||||||
sprite_->render();
|
sprite_->render();
|
||||||
|
} else {
|
||||||
|
// Efecto de parpadeo en los últimos segundos (cada ~0.33 segundos)
|
||||||
|
constexpr float BLINK_INTERVAL_S = 0.33f;
|
||||||
|
const float phase = fmod(lifetime_timer_, BLINK_INTERVAL_S);
|
||||||
|
const float half_interval = BLINK_INTERVAL_S / 2.0f;
|
||||||
|
|
||||||
|
if (phase < half_interval) {
|
||||||
|
sprite_->render();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void Item::move() {
|
void Item::move(float deltaTime) {
|
||||||
floor_collision_ = false;
|
floor_collision_ = false;
|
||||||
|
|
||||||
// Calcula la nueva posición
|
// Calcula la nueva posición usando deltaTime (velocidad en pixels/segundo)
|
||||||
pos_x_ += vel_x_;
|
pos_x_ += vel_x_ * deltaTime;
|
||||||
pos_y_ += vel_y_;
|
pos_y_ += vel_y_ * deltaTime;
|
||||||
|
|
||||||
// Aplica las aceleraciones a la velocidad
|
// Aplica las aceleraciones a la velocidad usando deltaTime (aceleración en pixels/segundo²)
|
||||||
vel_x_ += accel_x_;
|
vel_x_ += accel_x_ * deltaTime;
|
||||||
vel_y_ += accel_y_;
|
vel_y_ += accel_y_ * deltaTime;
|
||||||
|
|
||||||
// Comprueba los laterales de la zona de juego
|
// Comprueba los laterales de la zona de juego
|
||||||
const float MIN_X = param.game.play_area.rect.x;
|
const float MIN_X = param.game.play_area.rect.x;
|
||||||
@@ -90,7 +103,7 @@ void Item::move() {
|
|||||||
|
|
||||||
// Si toca el borde lateral
|
// Si toca el borde lateral
|
||||||
if (pos_x_ == MIN_X || pos_x_ == MAX_X) {
|
if (pos_x_ == MIN_X || pos_x_ == MAX_X) {
|
||||||
vel_x_ = -vel_x_; // Invierte la velocidad horizontal
|
vel_x_ = -vel_x_; // Invierte la velocidad horizontal
|
||||||
}
|
}
|
||||||
|
|
||||||
// Si colisiona por arriba, rebota (excepto la máquina de café)
|
// Si colisiona por arriba, rebota (excepto la máquina de café)
|
||||||
@@ -111,24 +124,24 @@ void Item::move() {
|
|||||||
case ItemType::COFFEE_MACHINE:
|
case ItemType::COFFEE_MACHINE:
|
||||||
// La máquina de café es mas pesada y tiene una fisica diferente, ademas hace ruido
|
// La máquina de café es mas pesada y tiene una fisica diferente, ademas hace ruido
|
||||||
floor_collision_ = true;
|
floor_collision_ = true;
|
||||||
if (vel_y_ < 1.0F) {
|
if (std::abs(vel_y_) < BOUNCE_VEL_THRESHOLD) {
|
||||||
// Si la velocidad vertical es baja, detiene el objeto
|
// Si la velocidad vertical es baja, detiene el objeto
|
||||||
vel_y_ = vel_x_ = accel_x_ = accel_y_ = 0;
|
vel_y_ = vel_x_ = accel_x_ = accel_y_ = 0;
|
||||||
} else {
|
} else {
|
||||||
// Si la velocidad vertical es alta, el objeto rebota y pierde velocidad
|
// Si la velocidad vertical es alta, el objeto rebota y pierde velocidad
|
||||||
vel_y_ *= -0.20F;
|
vel_y_ *= COFFEE_BOUNCE_DAMPING;
|
||||||
vel_x_ *= 0.75F;
|
vel_x_ *= HORIZONTAL_DAMPING;
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
// Si no es una máquina de café
|
// Si no es una máquina de café
|
||||||
if (vel_y_ < 1.0F) {
|
if (std::abs(vel_y_) < BOUNCE_VEL_THRESHOLD) {
|
||||||
// Si la velocidad vertical es baja, detiene el objeto
|
// Si la velocidad vertical es baja, detiene el objeto
|
||||||
vel_y_ = vel_x_ = accel_x_ = accel_y_ = 0;
|
vel_y_ = vel_x_ = accel_x_ = accel_y_ = 0;
|
||||||
} else {
|
} else {
|
||||||
// Si la velocidad vertical es alta, el objeto rebota y pierde velocidad
|
// Si la velocidad vertical es alta, el objeto rebota y pierde velocidad
|
||||||
vel_y_ *= -0.5F;
|
vel_y_ *= ITEM_BOUNCE_DAMPING;
|
||||||
vel_x_ *= 0.75F;
|
vel_x_ *= HORIZONTAL_DAMPING;
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
@@ -141,16 +154,15 @@ void Item::move() {
|
|||||||
|
|
||||||
void Item::disable() { enabled_ = false; }
|
void Item::disable() { enabled_ = false; }
|
||||||
|
|
||||||
void Item::update() {
|
void Item::update(float deltaTime) {
|
||||||
move();
|
move(deltaTime);
|
||||||
sprite_->update();
|
sprite_->update(deltaTime);
|
||||||
updateTimeToLive();
|
updateTimeToLive(deltaTime);
|
||||||
}
|
}
|
||||||
|
|
||||||
void Item::updateTimeToLive() {
|
void Item::updateTimeToLive(float deltaTime) {
|
||||||
if (time_to_live_ > 0) {
|
lifetime_timer_ += deltaTime;
|
||||||
time_to_live_--;
|
if (lifetime_timer_ >= LIFETIME_DURATION_S) {
|
||||||
} else {
|
|
||||||
disable();
|
disable();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -29,16 +29,34 @@ class Item {
|
|||||||
// --- Constantes ---
|
// --- Constantes ---
|
||||||
static constexpr int COFFEE_MACHINE_WIDTH = 30; // Anchura de la máquina de café
|
static constexpr int COFFEE_MACHINE_WIDTH = 30; // Anchura de la máquina de café
|
||||||
static constexpr int COFFEE_MACHINE_HEIGHT = 39; // Altura de la máquina de café
|
static constexpr int COFFEE_MACHINE_HEIGHT = 39; // Altura de la máquina de café
|
||||||
|
static constexpr float LIFETIME_DURATION_S = 10.0f; // Duración de vida del ítem en segundos
|
||||||
|
|
||||||
|
// Velocidades base (pixels/segundo) - Coffee Machine
|
||||||
|
static constexpr float COFFEE_MACHINE_VEL_X_FACTOR = 30.0F; // Factor para velocidad X de máquina de café (0.5*60fps)
|
||||||
|
static constexpr float COFFEE_MACHINE_VEL_Y = -6.0F; // Velocidad Y inicial de máquina de café (-0.1*60fps)
|
||||||
|
static constexpr float COFFEE_MACHINE_ACCEL_Y = 360.0F; // Aceleración Y de máquina de café (0.1*60²fps = 360 pixels/segundo²)
|
||||||
|
|
||||||
|
// Velocidades base (pixels/segundo) - Items normales
|
||||||
|
static constexpr float ITEM_VEL_X_BASE = 60.0F; // Velocidad X base para items (1.0F*60fps)
|
||||||
|
static constexpr float ITEM_VEL_X_STEP = 20.0F; // Incremento de velocidad X (0.33F*60fps)
|
||||||
|
static constexpr float ITEM_VEL_Y = -240.0F; // Velocidad Y inicial de items (-4.0F*60fps)
|
||||||
|
static constexpr float ITEM_ACCEL_Y = 720.0F; // Aceleración Y de items (0.2*60²fps = 720 pixels/segundo²)
|
||||||
|
|
||||||
|
// Constantes de física de rebote
|
||||||
|
static constexpr float BOUNCE_VEL_THRESHOLD = 60.0F; // Umbral de velocidad para parar (1.0F*60fps)
|
||||||
|
static constexpr float COFFEE_BOUNCE_DAMPING = -0.20F; // Factor de rebote Y para máquina de café
|
||||||
|
static constexpr float ITEM_BOUNCE_DAMPING = -0.5F; // Factor de rebote Y para items normales
|
||||||
|
static constexpr float HORIZONTAL_DAMPING = 0.75F; // Factor de amortiguación horizontal
|
||||||
|
|
||||||
// --- Constructor y destructor ---
|
// --- Constructor y destructor ---
|
||||||
Item(ItemType type, float x, float y, SDL_FRect &play_area, const std::shared_ptr<Texture> &texture, const std::vector<std::string> &animation); // Constructor principal
|
Item(ItemType type, float x, float y, SDL_FRect &play_area, const std::shared_ptr<Texture> &texture, const std::vector<std::string> &animation); // Constructor principal
|
||||||
~Item() = default; // Destructor
|
~Item() = default; // Destructor
|
||||||
|
|
||||||
// --- Métodos principales ---
|
// --- Métodos principales ---
|
||||||
void alignTo(int x); // Centra el objeto en la posición X indicada
|
void alignTo(int x); // Centra el objeto en la posición X indicada
|
||||||
void render(); // Renderiza el objeto en pantalla
|
void render(); // Renderiza el objeto en pantalla
|
||||||
void disable(); // Desactiva el objeto
|
void disable(); // Desactiva el objeto
|
||||||
void update(); // Actualiza la posición, animación y contadores
|
void update(float deltaTime); // Actualiza la posición, animación y contadores (time-based)
|
||||||
|
|
||||||
// --- Getters ---
|
// --- Getters ---
|
||||||
[[nodiscard]] auto getPosX() const -> float { return pos_x_; } // Obtiene la posición X
|
[[nodiscard]] auto getPosX() const -> float { return pos_x_; } // Obtiene la posición X
|
||||||
@@ -66,14 +84,14 @@ class Item {
|
|||||||
float accel_y_; // Aceleración en el eje Y
|
float accel_y_; // Aceleración en el eje Y
|
||||||
int width_; // Ancho del objeto
|
int width_; // Ancho del objeto
|
||||||
int height_; // Alto del objeto
|
int height_; // Alto del objeto
|
||||||
Uint16 time_to_live_ = 600; // Tiempo que el objeto está presente
|
float lifetime_timer_ = 0.0f; // Acumulador de tiempo de vida del ítem (segundos)
|
||||||
bool floor_collision_ = false; // Indica si el objeto colisiona con el suelo
|
bool floor_collision_ = false; // Indica si el objeto colisiona con el suelo
|
||||||
bool enabled_ = true; // Indica si el objeto está habilitado
|
bool enabled_ = true; // Indica si el objeto está habilitado
|
||||||
|
|
||||||
// --- Métodos internos ---
|
// --- Métodos internos ---
|
||||||
void shiftColliders(); // Alinea el círculo de colisión con la posición del objeto
|
void shiftColliders(); // Alinea el círculo de colisión con la posición del objeto
|
||||||
void shiftSprite(); // Coloca el sprite en la posición del objeto
|
void shiftSprite(); // Coloca el sprite en la posición del objeto
|
||||||
void move(); // Actualiza la posición y estados del objeto
|
void move(float deltaTime); // Actualiza la posición y estados del objeto (time-based)
|
||||||
void updateTimeToLive(); // Actualiza el contador de tiempo de vida
|
void updateTimeToLive(float deltaTime); // Actualiza el contador de tiempo de vida (time-based)
|
||||||
static auto getCoffeeMachineSpawn(int player_x, int item_width, int area_width, int margin = 2) -> int; // Calcula la zona de aparición de la máquina de café
|
static auto getCoffeeMachineSpawn(int player_x, int item_width, int area_width, int margin = 2) -> int; // Calcula la zona de aparición de la máquina de café
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -30,10 +30,10 @@ auto loadFromFile(const std::string &file_path) -> bool {
|
|||||||
|
|
||||||
// Intentar cargar desde ResourceHelper primero
|
// Intentar cargar desde ResourceHelper primero
|
||||||
auto resource_data = ResourceHelper::loadFile(file_path);
|
auto resource_data = ResourceHelper::loadFile(file_path);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
json j;
|
json j;
|
||||||
|
|
||||||
if (!resource_data.empty()) {
|
if (!resource_data.empty()) {
|
||||||
// Cargar desde datos del pack
|
// Cargar desde datos del pack
|
||||||
std::string content(resource_data.begin(), resource_data.end());
|
std::string content(resource_data.begin(), resource_data.end());
|
||||||
|
|||||||
@@ -19,7 +19,9 @@ struct Language {
|
|||||||
std::string file_name; // Nombre del fichero con los textos
|
std::string file_name; // Nombre del fichero con los textos
|
||||||
|
|
||||||
Language(Code c, std::string n, std::string fn)
|
Language(Code c, std::string n, std::string fn)
|
||||||
: code(c), name(std::move(n)), file_name(std::move(fn)) {}
|
: code(c),
|
||||||
|
name(std::move(n)),
|
||||||
|
file_name(std::move(fn)) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
// --- Funciones ---
|
// --- Funciones ---
|
||||||
|
|||||||
@@ -10,8 +10,10 @@ struct HiScoreEntry {
|
|||||||
bool one_credit_complete; // Indica si se ha conseguido 1CC
|
bool one_credit_complete; // Indica si se ha conseguido 1CC
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
explicit HiScoreEntry(const std::string &n = "", int s = 0, bool occ = false)
|
explicit HiScoreEntry(const std::string &name = "", int score = 0, bool one_credit_complete = false)
|
||||||
: name(n.substr(0, 6)), score(s), one_credit_complete(occ) {}
|
: name(name.substr(0, 6)),
|
||||||
|
score(score),
|
||||||
|
one_credit_complete(one_credit_complete) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
// --- Tipos ---
|
// --- Tipos ---
|
||||||
|
|||||||
@@ -53,42 +53,41 @@ void MovingSprite::stop() {
|
|||||||
flip_ = SDL_FLIP_NONE; // Establece como se ha de voltear el sprite
|
flip_ = SDL_FLIP_NONE; // Establece como se ha de voltear el sprite
|
||||||
}
|
}
|
||||||
|
|
||||||
// Mueve el sprite
|
// Mueve el sprite (time-based)
|
||||||
void MovingSprite::move() {
|
void MovingSprite::move(float deltaTime) {
|
||||||
x_ += vx_;
|
// DeltaTime puro: velocidad (pixels/ms) * tiempo (ms)
|
||||||
y_ += vy_;
|
x_ += vx_ * deltaTime;
|
||||||
|
y_ += vy_ * deltaTime;
|
||||||
|
|
||||||
vx_ += ax_;
|
// Aceleración (pixels/ms²) * tiempo (ms)
|
||||||
vy_ += ay_;
|
vx_ += ax_ * deltaTime;
|
||||||
|
vy_ += ay_ * deltaTime;
|
||||||
|
|
||||||
pos_.x = static_cast<int>(x_);
|
pos_.x = static_cast<int>(x_);
|
||||||
pos_.y = static_cast<int>(y_);
|
pos_.y = static_cast<int>(y_);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Actualiza las variables internas del objeto
|
// Actualiza las variables internas del objeto (time-based)
|
||||||
void MovingSprite::update() {
|
void MovingSprite::update(float deltaTime) {
|
||||||
move();
|
move(deltaTime);
|
||||||
rotate();
|
rotate(deltaTime);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Muestra el sprite por pantalla
|
// Muestra el sprite por pantalla
|
||||||
void MovingSprite::render() { getTexture()->render(pos_.x, pos_.y, &sprite_clip_, horizontal_zoom_, vertical_zoom_, rotate_.angle, &rotate_.center, flip_); }
|
void MovingSprite::render() {
|
||||||
|
getTexture()->render(pos_.x, pos_.y, &sprite_clip_, horizontal_zoom_, vertical_zoom_, rotate_.angle, &rotate_.center, flip_);
|
||||||
|
}
|
||||||
|
|
||||||
// Establece la rotacion
|
// Establece la rotacion (time-based)
|
||||||
void MovingSprite::rotate() {
|
void MovingSprite::rotate(float deltaTime) {
|
||||||
if (rotate_.enabled) {
|
if (rotate_.enabled) {
|
||||||
++rotate_.counter;
|
rotate_.angle += rotate_.amount * deltaTime;
|
||||||
if (rotate_.counter % rotate_.speed == 0) {
|
|
||||||
updateAngle();
|
|
||||||
rotate_.counter = 0;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Activa o desactiva el efecto de rotación
|
// Activa o desactiva el efecto de rotación
|
||||||
void MovingSprite::setRotate(bool enable) {
|
void MovingSprite::setRotate(bool enable) {
|
||||||
rotate_.enabled = enable;
|
rotate_.enabled = enable;
|
||||||
rotate_.counter = 0;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Establece la posición y_ el tamaño del objeto
|
// Establece la posición y_ el tamaño del objeto
|
||||||
|
|||||||
@@ -15,7 +15,6 @@ class MovingSprite : public Sprite {
|
|||||||
// --- Estructuras ---
|
// --- Estructuras ---
|
||||||
struct Rotate {
|
struct Rotate {
|
||||||
bool enabled{false}; // Indica si ha de rotar
|
bool enabled{false}; // Indica si ha de rotar
|
||||||
int counter{0}; // Contador
|
|
||||||
int speed{1}; // Velocidad de giro
|
int speed{1}; // Velocidad de giro
|
||||||
double angle{0.0}; // Ángulo para dibujarlo
|
double angle{0.0}; // Ángulo para dibujarlo
|
||||||
float amount{0.0F}; // Cantidad de grados a girar en cada iteración
|
float amount{0.0F}; // Cantidad de grados a girar en cada iteración
|
||||||
@@ -29,10 +28,10 @@ class MovingSprite : public Sprite {
|
|||||||
~MovingSprite() override = default;
|
~MovingSprite() override = default;
|
||||||
|
|
||||||
// --- Métodos principales ---
|
// --- Métodos principales ---
|
||||||
virtual void update(); // Actualiza las variables internas del objeto
|
virtual void update(float deltaTime); // Actualiza las variables internas del objeto (time-based)
|
||||||
void clear() override; // Reinicia todas las variables a cero
|
void clear() override; // Reinicia todas las variables a cero
|
||||||
void stop(); // Elimina el movimiento del sprite
|
void stop(); // Elimina el movimiento del sprite
|
||||||
void render() override; // Muestra el sprite por pantalla
|
void render() override; // Muestra el sprite por pantalla
|
||||||
|
|
||||||
// --- Configuración ---
|
// --- Configuración ---
|
||||||
void setPos(SDL_FRect rect); // Establece la posición y el tamaño del objeto
|
void setPos(SDL_FRect rect); // Establece la posición y el tamaño del objeto
|
||||||
@@ -79,6 +78,6 @@ class MovingSprite : public Sprite {
|
|||||||
|
|
||||||
// --- Métodos internos ---
|
// --- Métodos internos ---
|
||||||
void updateAngle() { rotate_.angle += rotate_.amount; } // Incrementa el valor del ángulo
|
void updateAngle() { rotate_.angle += rotate_.amount; } // Incrementa el valor del ángulo
|
||||||
void move(); // Mueve el sprite según velocidad y aceleración
|
void move(float deltaTime); // Mueve el sprite según velocidad y aceleración (time-based)
|
||||||
void rotate(); // Rota el sprite según los parámetros de rotación
|
void rotate(float deltaTime); // Rota el sprite según los parámetros de rotación (time-based)
|
||||||
};
|
};
|
||||||
@@ -106,7 +106,6 @@ auto setParams(const std::string& var, const std::string& value) -> bool {
|
|||||||
{"scoreboard.rect.h", [](const std::string& v) { param.scoreboard.rect.h = std::stoi(v); }},
|
{"scoreboard.rect.h", [](const std::string& v) { param.scoreboard.rect.h = std::stoi(v); }},
|
||||||
{"scoreboard.skip_countdown_value", [](const std::string& v) { param.scoreboard.skip_countdown_value = std::stoi(v); }},
|
{"scoreboard.skip_countdown_value", [](const std::string& v) { param.scoreboard.skip_countdown_value = std::stoi(v); }},
|
||||||
{"title.press_start_position", [](const std::string& v) { param.title.press_start_position = std::stoi(v); }},
|
{"title.press_start_position", [](const std::string& v) { param.title.press_start_position = std::stoi(v); }},
|
||||||
{"title.title_duration", [](const std::string& v) { param.title.title_duration = std::stoi(v); }},
|
|
||||||
{"title.arcade_edition_position", [](const std::string& v) { param.title.arcade_edition_position = std::stoi(v); }},
|
{"title.arcade_edition_position", [](const std::string& v) { param.title.arcade_edition_position = std::stoi(v); }},
|
||||||
{"title.title_c_c_position", [](const std::string& v) { param.title.title_c_c_position = std::stoi(v); }},
|
{"title.title_c_c_position", [](const std::string& v) { param.title.title_c_c_position = std::stoi(v); }},
|
||||||
{"intro.text_distance_from_bottom", [](const std::string& v) { param.intro.text_distance_from_bottom = std::stoi(v); }}};
|
{"intro.text_distance_from_bottom", [](const std::string& v) { param.intro.text_distance_from_bottom = std::stoi(v); }}};
|
||||||
@@ -182,6 +181,7 @@ auto setParams(const std::string& var, const std::string& value) -> bool {
|
|||||||
{"balloon.settings[3].grav", [](const std::string& v) { param.balloon.settings.at(3).grav = std::stof(v); }},
|
{"balloon.settings[3].grav", [](const std::string& v) { param.balloon.settings.at(3).grav = std::stof(v); }},
|
||||||
{"tabe.min_spawn_time", [](const std::string& v) { param.tabe.min_spawn_time = std::stof(v); }},
|
{"tabe.min_spawn_time", [](const std::string& v) { param.tabe.min_spawn_time = std::stof(v); }},
|
||||||
{"tabe.max_spawn_time", [](const std::string& v) { param.tabe.max_spawn_time = std::stof(v); }},
|
{"tabe.max_spawn_time", [](const std::string& v) { param.tabe.max_spawn_time = std::stof(v); }},
|
||||||
|
{"title.title_duration", [](const std::string& v) { param.title.title_duration = std::stof(v); }},
|
||||||
{"service_menu.window_message.padding", [](const std::string& v) { param.service_menu.window_message.padding = std::stof(v); }},
|
{"service_menu.window_message.padding", [](const std::string& v) { param.service_menu.window_message.padding = std::stof(v); }},
|
||||||
{"service_menu.window_message.line_spacing", [](const std::string& v) { param.service_menu.window_message.line_spacing = std::stof(v); }},
|
{"service_menu.window_message.line_spacing", [](const std::string& v) { param.service_menu.window_message.line_spacing = std::stof(v); }},
|
||||||
{"service_menu.window_message.title_separator_spacing", [](const std::string& v) { param.service_menu.window_message.title_separator_spacing = std::stof(v); }},
|
{"service_menu.window_message.title_separator_spacing", [](const std::string& v) { param.service_menu.window_message.title_separator_spacing = std::stof(v); }},
|
||||||
@@ -196,46 +196,48 @@ auto setParams(const std::string& var, const std::string& value) -> bool {
|
|||||||
|
|
||||||
// Colores válidos para globos
|
// Colores válidos para globos
|
||||||
static const std::unordered_map<std::string, bool> VALID_BALLOON_COLORS = {
|
static const std::unordered_map<std::string, bool> VALID_BALLOON_COLORS = {
|
||||||
{"blue", true}, {"orange", true}, {"red", true}, {"green", true}
|
{"blue", true},
|
||||||
};
|
{"orange", true},
|
||||||
|
{"red", true},
|
||||||
|
{"green", true}};
|
||||||
|
|
||||||
auto validateBalloonColor = [](const std::string& color) -> bool {
|
auto validateBalloonColor = [](const std::string& color) -> bool {
|
||||||
return VALID_BALLOON_COLORS.find(color) != VALID_BALLOON_COLORS.end();
|
return VALID_BALLOON_COLORS.find(color) != VALID_BALLOON_COLORS.end();
|
||||||
};
|
};
|
||||||
|
|
||||||
static const std::unordered_map<std::string, std::function<void(const std::string&)>> STRING_PARAMS = {
|
static const std::unordered_map<std::string, std::function<void(const std::string&)>> STRING_PARAMS = {
|
||||||
{"balloon.color[0]", [validateBalloonColor](const std::string& v) {
|
{"balloon.color[0]", [validateBalloonColor](const std::string& v) {
|
||||||
if (!validateBalloonColor(v)) {
|
if (!validateBalloonColor(v)) {
|
||||||
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "Color de globo inválido '%s'. Usando 'blue' por defecto.", v.c_str());
|
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "Color de globo inválido '%s'. Usando 'blue' por defecto.", v.c_str());
|
||||||
param.balloon.color.at(0) = "blue";
|
param.balloon.color.at(0) = "blue";
|
||||||
} else {
|
} else {
|
||||||
param.balloon.color.at(0) = v;
|
param.balloon.color.at(0) = v;
|
||||||
}
|
}
|
||||||
}},
|
}},
|
||||||
{"balloon.color[1]", [validateBalloonColor](const std::string& v) {
|
{"balloon.color[1]", [validateBalloonColor](const std::string& v) {
|
||||||
if (!validateBalloonColor(v)) {
|
if (!validateBalloonColor(v)) {
|
||||||
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "Color de globo inválido '%s'. Usando 'orange' por defecto.", v.c_str());
|
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "Color de globo inválido '%s'. Usando 'orange' por defecto.", v.c_str());
|
||||||
param.balloon.color.at(1) = "orange";
|
param.balloon.color.at(1) = "orange";
|
||||||
} else {
|
} else {
|
||||||
param.balloon.color.at(1) = v;
|
param.balloon.color.at(1) = v;
|
||||||
}
|
}
|
||||||
}},
|
}},
|
||||||
{"balloon.color[2]", [validateBalloonColor](const std::string& v) {
|
{"balloon.color[2]", [validateBalloonColor](const std::string& v) {
|
||||||
if (!validateBalloonColor(v)) {
|
if (!validateBalloonColor(v)) {
|
||||||
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "Color de globo inválido '%s'. Usando 'red' por defecto.", v.c_str());
|
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "Color de globo inválido '%s'. Usando 'red' por defecto.", v.c_str());
|
||||||
param.balloon.color.at(2) = "red";
|
param.balloon.color.at(2) = "red";
|
||||||
} else {
|
} else {
|
||||||
param.balloon.color.at(2) = v;
|
param.balloon.color.at(2) = v;
|
||||||
}
|
}
|
||||||
}},
|
}},
|
||||||
{"balloon.color[3]", [validateBalloonColor](const std::string& v) {
|
{"balloon.color[3]", [validateBalloonColor](const std::string& v) {
|
||||||
if (!validateBalloonColor(v)) {
|
if (!validateBalloonColor(v)) {
|
||||||
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "Color de globo inválido '%s'. Usando 'green' por defecto.", v.c_str());
|
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "Color de globo inválido '%s'. Usando 'green' por defecto.", v.c_str());
|
||||||
param.balloon.color.at(3) = "green";
|
param.balloon.color.at(3) = "green";
|
||||||
} else {
|
} else {
|
||||||
param.balloon.color.at(3) = v;
|
param.balloon.color.at(3) = v;
|
||||||
}
|
}
|
||||||
}}};
|
}}};
|
||||||
|
|
||||||
// Lambda para intentar cada mapa de parámetros
|
// Lambda para intentar cada mapa de parámetros
|
||||||
auto try_map = [&](const auto& param_map) -> bool {
|
auto try_map = [&](const auto& param_map) -> bool {
|
||||||
|
|||||||
@@ -38,7 +38,7 @@ struct ParamFade {
|
|||||||
// --- Parámetros de la pantalla de título ---
|
// --- Parámetros de la pantalla de título ---
|
||||||
struct ParamTitle {
|
struct ParamTitle {
|
||||||
int press_start_position = GameDefaults::Title::PRESS_START_POSITION;
|
int press_start_position = GameDefaults::Title::PRESS_START_POSITION;
|
||||||
int title_duration = GameDefaults::Title::DURATION;
|
float title_duration = GameDefaults::Title::DURATION_S;
|
||||||
int arcade_edition_position = GameDefaults::Title::ARCADE_EDITION_POSITION;
|
int arcade_edition_position = GameDefaults::Title::ARCADE_EDITION_POSITION;
|
||||||
int title_c_c_position = GameDefaults::Title::TITLE_C_C_POSITION;
|
int title_c_c_position = GameDefaults::Title::TITLE_C_C_POSITION;
|
||||||
Color bg_color = Color::fromHex(GameDefaults::Title::BG_COLOR);
|
Color bg_color = Color::fromHex(GameDefaults::Title::BG_COLOR);
|
||||||
@@ -57,7 +57,8 @@ struct ParamBalloon {
|
|||||||
|
|
||||||
// Constructor por defecto
|
// Constructor por defecto
|
||||||
constexpr Settings(float grav_val = 0.0F, float vel_val = 0.0F)
|
constexpr Settings(float grav_val = 0.0F, float vel_val = 0.0F)
|
||||||
: grav(grav_val), vel(vel_val) {}
|
: grav(grav_val),
|
||||||
|
vel(vel_val) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Inicialización con los valores por defecto desde GameDefaults
|
// Inicialización con los valores por defecto desde GameDefaults
|
||||||
@@ -164,7 +165,10 @@ struct ParamPlayer {
|
|||||||
|
|
||||||
// Constructor con tonalidades específicas
|
// Constructor con tonalidades específicas
|
||||||
Shirt(const Color& darkest_tone, const Color& dark_tone, const Color& base_tone, const Color& light_tone)
|
Shirt(const Color& darkest_tone, const Color& dark_tone, const Color& base_tone, const Color& light_tone)
|
||||||
: darkest(darkest_tone), dark(dark_tone), base(base_tone), light(light_tone) {}
|
: darkest(darkest_tone),
|
||||||
|
dark(dark_tone),
|
||||||
|
base(base_tone),
|
||||||
|
light(light_tone) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Inicialización con valores por defecto
|
// Inicialización con valores por defecto
|
||||||
|
|||||||
@@ -4,6 +4,12 @@
|
|||||||
#include <functional> // Para function
|
#include <functional> // Para function
|
||||||
#include <utility> // Para move
|
#include <utility> // Para move
|
||||||
|
|
||||||
|
// Constructor para paths por puntos (convertido a segundos)
|
||||||
|
Path::Path(const std::vector<SDL_FPoint> &spots_init, float waiting_time_s_init)
|
||||||
|
: spots(spots_init), is_point_path(true) {
|
||||||
|
waiting_time_s = waiting_time_s_init;
|
||||||
|
}
|
||||||
|
|
||||||
// Devuelve un vector con los puntos que conforman la ruta
|
// Devuelve un vector con los puntos que conforman la ruta
|
||||||
auto createPath(float start, float end, PathType type, float fixed_pos, int steps, const std::function<double(double)> &easing_function) -> std::vector<SDL_FPoint> {
|
auto createPath(float start, float end, PathType type, float fixed_pos, int steps, const std::function<double(double)> &easing_function) -> std::vector<SDL_FPoint> {
|
||||||
std::vector<SDL_FPoint> v;
|
std::vector<SDL_FPoint> v;
|
||||||
@@ -33,9 +39,9 @@ auto createPath(float start, float end, PathType type, float fixed_pos, int step
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Actualiza la posición y comprueba si ha llegado a su destino
|
// Actualiza la posición y comprueba si ha llegado a su destino
|
||||||
void PathSprite::update() {
|
void PathSprite::update(float delta_time) {
|
||||||
if (enabled_ && !has_finished_) {
|
if (enabled_ && !has_finished_) {
|
||||||
moveThroughCurrentPath();
|
moveThroughCurrentPath(delta_time);
|
||||||
goToNextPathOrDie();
|
goToNextPathOrDie();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -77,14 +83,14 @@ void PathSprite::addPath(Path path, bool centered) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Añade un recorrido
|
// Añade un recorrido generado (en segundos)
|
||||||
void PathSprite::addPath(int start, int end, PathType type, int fixed_pos, int steps, const std::function<double(double)> &easing_function, int waiting_counter) {
|
void PathSprite::addPath(float start, float end, PathType type, float fixed_pos, float duration_s, const std::function<double(double)> &easing_function, float waiting_time_s) {
|
||||||
paths_.emplace_back(createPath(start, end, type, fixed_pos, steps, easing_function), waiting_counter);
|
paths_.emplace_back(start, end, type, fixed_pos, duration_s, waiting_time_s, easing_function);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Añade un recorrido
|
// Añade un recorrido por puntos (en segundos)
|
||||||
void PathSprite::addPath(const std::vector<SDL_FPoint> &spots, int waiting_counter) {
|
void PathSprite::addPath(const std::vector<SDL_FPoint> &spots, float waiting_time_s) {
|
||||||
paths_.emplace_back(spots, waiting_counter);
|
paths_.emplace_back(spots, waiting_time_s);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Habilita el objeto
|
// Habilita el objeto
|
||||||
@@ -95,35 +101,78 @@ void PathSprite::enable() {
|
|||||||
|
|
||||||
enabled_ = true;
|
enabled_ = true;
|
||||||
|
|
||||||
// Establece la posición
|
// Establece la posición inicial
|
||||||
auto &path = paths_.at(current_path_);
|
auto &path = paths_.at(current_path_);
|
||||||
const auto &p = path.spots.at(path.counter);
|
if (path.is_point_path) {
|
||||||
setPosition(p);
|
const auto &p = path.spots.at(path.counter);
|
||||||
|
setPosition(p);
|
||||||
|
} else {
|
||||||
|
// Para paths generados, establecer posición inicial
|
||||||
|
SDL_FPoint initial_pos;
|
||||||
|
if (path.type == PathType::HORIZONTAL) {
|
||||||
|
initial_pos = {path.start_pos, path.fixed_pos};
|
||||||
|
} else {
|
||||||
|
initial_pos = {path.fixed_pos, path.start_pos};
|
||||||
|
}
|
||||||
|
setPosition(initial_pos);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Coloca el sprite en los diferentes puntos del recorrido
|
// Coloca el sprite en los diferentes puntos del recorrido
|
||||||
void PathSprite::moveThroughCurrentPath() {
|
void PathSprite::moveThroughCurrentPath(float delta_time) {
|
||||||
auto &path = paths_.at(current_path_);
|
auto &path = paths_.at(current_path_);
|
||||||
|
|
||||||
// Establece la posición
|
if (path.is_point_path) {
|
||||||
const auto &p = path.spots.at(path.counter);
|
// Lógica para paths por puntos (compatibilidad)
|
||||||
setPosition(p);
|
const auto &p = path.spots.at(path.counter);
|
||||||
|
setPosition(p);
|
||||||
|
|
||||||
// Comprobar si ha terminado el recorrido
|
if (!path.on_destination) {
|
||||||
if (!path.on_destination) {
|
++path.counter;
|
||||||
++path.counter;
|
if (path.counter >= static_cast<int>(path.spots.size())) {
|
||||||
if (path.counter >= static_cast<int>(path.spots.size())) {
|
path.on_destination = true;
|
||||||
path.on_destination = true;
|
path.counter = static_cast<int>(path.spots.size()) - 1;
|
||||||
path.counter = static_cast<int>(path.spots.size()) - 1;
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
// Comprobar si ha terminado la espera
|
if (path.on_destination) {
|
||||||
if (path.on_destination) {
|
path.waiting_elapsed += delta_time;
|
||||||
if (path.waiting_counter == 0) {
|
if (path.waiting_elapsed >= path.waiting_time_s) {
|
||||||
path.finished = true;
|
path.finished = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Lógica para paths generados en tiempo real
|
||||||
|
if (!path.on_destination) {
|
||||||
|
path.elapsed_time += delta_time;
|
||||||
|
|
||||||
|
// Calcular progreso (0.0 a 1.0)
|
||||||
|
float progress = path.elapsed_time / path.duration_s;
|
||||||
|
if (progress >= 1.0f) {
|
||||||
|
progress = 1.0f;
|
||||||
|
path.on_destination = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Aplicar función de easing
|
||||||
|
double eased_progress = path.easing_function(progress);
|
||||||
|
|
||||||
|
// Calcular posición actual
|
||||||
|
float current_pos = path.start_pos + (path.end_pos - path.start_pos) * static_cast<float>(eased_progress);
|
||||||
|
|
||||||
|
// Establecer posición según el tipo
|
||||||
|
SDL_FPoint position;
|
||||||
|
if (path.type == PathType::HORIZONTAL) {
|
||||||
|
position = {current_pos, path.fixed_pos};
|
||||||
|
} else {
|
||||||
|
position = {path.fixed_pos, current_pos};
|
||||||
|
}
|
||||||
|
setPosition(position);
|
||||||
} else {
|
} else {
|
||||||
--path.waiting_counter;
|
// Esperar en destino
|
||||||
|
path.waiting_elapsed += delta_time;
|
||||||
|
if (path.waiting_elapsed >= path.waiting_time_s) {
|
||||||
|
path.finished = true;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,16 +24,31 @@ enum class PathCentered { // Centrado del recorrido
|
|||||||
};
|
};
|
||||||
|
|
||||||
// --- Estructuras ---
|
// --- Estructuras ---
|
||||||
struct Path { // Define un recorrido para el sprite
|
struct Path { // Define un recorrido para el sprite
|
||||||
std::vector<SDL_FPoint> spots; // Puntos por los que se desplazará el sprite
|
float start_pos; // Posición inicial
|
||||||
int waiting_counter; // Tiempo de espera una vez en el destino
|
float end_pos; // Posición final
|
||||||
bool on_destination = false; // Indica si ha llegado al destino
|
PathType type; // Tipo de movimiento (horizontal/vertical)
|
||||||
bool finished = false; // Indica si ha terminado de esperarse
|
float fixed_pos; // Posición fija en el eje contrario
|
||||||
int counter = 0; // Contador interno
|
float duration_s; // Duración de la animación en segundos
|
||||||
|
float waiting_time_s; // Tiempo de espera una vez en el destino
|
||||||
|
std::function<double(double)> easing_function; // Función de easing
|
||||||
|
float elapsed_time = 0.0f; // Tiempo transcurrido
|
||||||
|
float waiting_elapsed = 0.0f; // Tiempo de espera transcurrido
|
||||||
|
bool on_destination = false; // Indica si ha llegado al destino
|
||||||
|
bool finished = false; // Indica si ha terminado de esperarse
|
||||||
|
|
||||||
// Constructor
|
// Constructor para paths generados
|
||||||
Path(const std::vector<SDL_FPoint> &spots_init, int waiting_counter_init)
|
Path(float start, float end, PathType path_type, float fixed, float duration, float waiting, std::function<double(double)> easing)
|
||||||
: spots(spots_init), waiting_counter(waiting_counter_init) {}
|
: start_pos(start), end_pos(end), type(path_type), fixed_pos(fixed),
|
||||||
|
duration_s(duration), waiting_time_s(waiting), easing_function(std::move(easing)) {}
|
||||||
|
|
||||||
|
// Constructor para paths por puntos (convertido a segundos)
|
||||||
|
Path(const std::vector<SDL_FPoint> &spots_init, float waiting_time_s_init);
|
||||||
|
|
||||||
|
// Variables para paths por puntos
|
||||||
|
std::vector<SDL_FPoint> spots; // Solo para paths por puntos
|
||||||
|
int counter = 0; // Solo para paths por puntos
|
||||||
|
bool is_point_path = false; // Indica si es un path por puntos
|
||||||
};
|
};
|
||||||
|
|
||||||
// --- Funciones ---
|
// --- Funciones ---
|
||||||
@@ -48,13 +63,13 @@ class PathSprite : public Sprite {
|
|||||||
~PathSprite() override = default;
|
~PathSprite() override = default;
|
||||||
|
|
||||||
// --- Métodos principales ---
|
// --- Métodos principales ---
|
||||||
void update(); // Actualiza la posición del sprite según el recorrido
|
void update(float delta_time); // Actualiza la posición del sprite según el recorrido (delta_time en segundos)
|
||||||
void render() override; // Muestra el sprite por pantalla
|
void render() override; // Muestra el sprite por pantalla
|
||||||
|
|
||||||
// --- Gestión de recorridos ---
|
// --- Gestión de recorridos ---
|
||||||
void addPath(Path path, bool centered = false); // Añade un recorrido (Path)
|
void addPath(Path path, bool centered = false); // Añade un recorrido (Path)
|
||||||
void addPath(const std::vector<SDL_FPoint> &spots, int waiting_counter = 0); // Añade un recorrido a partir de puntos
|
void addPath(const std::vector<SDL_FPoint> &spots, float waiting_time_s = 0.0f); // Añade un recorrido a partir de puntos
|
||||||
void addPath(int start, int end, PathType type, int fixed_pos, int steps, const std::function<double(double)> &easing_function, int waiting_counter = 0); // Añade un recorrido generado
|
void addPath(float start, float end, PathType type, float fixed_pos, float duration_s, const std::function<double(double)> &easing_function, float waiting_time_s = 0.0f); // Añade un recorrido generado
|
||||||
|
|
||||||
// --- Estado y control ---
|
// --- Estado y control ---
|
||||||
void enable(); // Habilita el objeto
|
void enable(); // Habilita el objeto
|
||||||
@@ -71,6 +86,6 @@ class PathSprite : public Sprite {
|
|||||||
std::vector<Path> paths_; // Caminos a recorrer por el sprite
|
std::vector<Path> paths_; // Caminos a recorrer por el sprite
|
||||||
|
|
||||||
// --- Métodos internos ---
|
// --- Métodos internos ---
|
||||||
void moveThroughCurrentPath(); // Coloca el sprite en los diferentes puntos del recorrido
|
void moveThroughCurrentPath(float delta_time); // Coloca el sprite en los diferentes puntos del recorrido
|
||||||
void goToNextPathOrDie(); // Cambia de recorrido o finaliza
|
void goToNextPathOrDie(); // Cambia de recorrido o finaliza
|
||||||
};
|
};
|
||||||
@@ -3,6 +3,7 @@
|
|||||||
#include <SDL3/SDL.h> // Para SDL_GetTicks, SDL_FlipMode
|
#include <SDL3/SDL.h> // Para SDL_GetTicks, SDL_FlipMode
|
||||||
|
|
||||||
#include <algorithm> // Para clamp, max, min
|
#include <algorithm> // Para clamp, max, min
|
||||||
|
#include <cmath> // Para fmod
|
||||||
#include <cstdlib> // Para rand
|
#include <cstdlib> // Para rand
|
||||||
|
|
||||||
#include "animated_sprite.h" // Para AnimatedSprite
|
#include "animated_sprite.h" // Para AnimatedSprite
|
||||||
@@ -22,7 +23,17 @@
|
|||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
Player::Player(const Config &config)
|
Player::Player(const Config &config)
|
||||||
: player_sprite_(std::make_unique<AnimatedSprite>(config.texture.at(0), config.animations.at(0))), power_sprite_(std::make_unique<AnimatedSprite>(config.texture.at(4), config.animations.at(1))), enter_name_(std::make_unique<EnterName>()), hi_score_table_(config.hi_score_table), glowing_entry_(config.glowing_entry), stage_info_(config.stage_info), play_area_(*config.play_area), id_(config.id), default_pos_x_(config.x), default_pos_y_(config.y), demo_(config.demo) {
|
: player_sprite_(std::make_unique<AnimatedSprite>(config.texture.at(0), config.animations.at(0))),
|
||||||
|
power_sprite_(std::make_unique<AnimatedSprite>(config.texture.at(4), config.animations.at(1))),
|
||||||
|
enter_name_(std::make_unique<EnterName>()),
|
||||||
|
hi_score_table_(config.hi_score_table),
|
||||||
|
glowing_entry_(config.glowing_entry),
|
||||||
|
stage_info_(config.stage_info),
|
||||||
|
play_area_(*config.play_area),
|
||||||
|
id_(config.id),
|
||||||
|
default_pos_x_(config.x),
|
||||||
|
default_pos_y_(config.y),
|
||||||
|
demo_(config.demo) {
|
||||||
// Configura objetos
|
// Configura objetos
|
||||||
player_sprite_->addTexture(config.texture.at(1));
|
player_sprite_->addTexture(config.texture.at(1));
|
||||||
player_sprite_->addTexture(config.texture.at(2));
|
player_sprite_->addTexture(config.texture.at(2));
|
||||||
@@ -49,17 +60,14 @@ void Player::init() {
|
|||||||
power_up_counter_ = POWERUP_COUNTER;
|
power_up_counter_ = POWERUP_COUNTER;
|
||||||
extra_hit_ = false;
|
extra_hit_ = false;
|
||||||
coffees_ = 0;
|
coffees_ = 0;
|
||||||
continue_ticks_ = 0;
|
|
||||||
continue_counter_ = 10;
|
continue_counter_ = 10;
|
||||||
name_entry_ticks_ = 0;
|
name_entry_idle_time_accumulator_ = 0.0f;
|
||||||
name_entry_idle_counter_ = 0;
|
name_entry_total_time_accumulator_ = 0.0f;
|
||||||
name_entry_total_counter_ = 0;
|
|
||||||
shiftColliders();
|
shiftColliders();
|
||||||
vel_x_ = 0;
|
vel_x_ = 0;
|
||||||
vel_y_ = 0;
|
vel_y_ = 0;
|
||||||
score_ = 0;
|
score_ = 0;
|
||||||
score_multiplier_ = 1.0F;
|
score_multiplier_ = 1.0F;
|
||||||
cant_fire_counter_ = 10;
|
|
||||||
enter_name_->init(last_enter_name_);
|
enter_name_->init(last_enter_name_);
|
||||||
|
|
||||||
// Establece la posición del sprite
|
// Establece la posición del sprite
|
||||||
@@ -138,47 +146,50 @@ void Player::setInputEnteringName(Input::Action action) {
|
|||||||
default:
|
default:
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
name_entry_idle_counter_ = 0;
|
name_entry_idle_time_accumulator_ = 0.0f;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Mueve el jugador a la posición y animación que le corresponde
|
// Fase 1: Sistema de movimiento time-based
|
||||||
void Player::move() {
|
void Player::move(float deltaTime) {
|
||||||
switch (playing_state_) {
|
switch (playing_state_) {
|
||||||
case State::PLAYING:
|
case State::PLAYING:
|
||||||
handlePlayingMovement();
|
handlePlayingMovement(deltaTime);
|
||||||
break;
|
break;
|
||||||
case State::ROLLING:
|
case State::ROLLING:
|
||||||
handleRollingMovement();
|
handleRollingMovement();
|
||||||
break;
|
break;
|
||||||
case State::TITLE_ANIMATION:
|
case State::TITLE_ANIMATION:
|
||||||
handleTitleAnimation();
|
handleTitleAnimation(deltaTime);
|
||||||
break;
|
break;
|
||||||
case State::CONTINUE_TIME_OUT:
|
case State::CONTINUE_TIME_OUT:
|
||||||
handleContinueTimeOut();
|
handleContinueTimeOut();
|
||||||
break;
|
break;
|
||||||
case State::LEAVING_SCREEN:
|
case State::LEAVING_SCREEN:
|
||||||
handleLeavingScreen();
|
updateStepCounter(deltaTime);
|
||||||
|
handleLeavingScreen(deltaTime);
|
||||||
break;
|
break;
|
||||||
case State::ENTERING_SCREEN:
|
case State::ENTERING_SCREEN:
|
||||||
handleEnteringScreen();
|
updateStepCounter(deltaTime);
|
||||||
|
handleEnteringScreen(deltaTime);
|
||||||
break;
|
break;
|
||||||
case State::CREDITS:
|
case State::CREDITS:
|
||||||
handleCreditsMovement();
|
handleCreditsMovement(deltaTime);
|
||||||
break;
|
break;
|
||||||
case State::WAITING:
|
case State::WAITING:
|
||||||
handleWaitingMovement();
|
handleWaitingMovement(deltaTime);
|
||||||
break;
|
break;
|
||||||
case State::RECOVER:
|
case State::RECOVER:
|
||||||
handleRecoverMovement();
|
handleRecoverMovement();
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void Player::handlePlayingMovement() {
|
// Movimiento time-based durante el juego
|
||||||
// Mueve el jugador a derecha o izquierda
|
void Player::handlePlayingMovement(float deltaTime) {
|
||||||
pos_x_ += vel_x_;
|
// Mueve el jugador a derecha o izquierda (time-based en segundos)
|
||||||
|
pos_x_ += vel_x_ * deltaTime;
|
||||||
|
|
||||||
// Si el jugador abandona el area de juego por los laterales, restaura su posición
|
// Si el jugador abandona el area de juego por los laterales, restaura su posición
|
||||||
const float MIN_X = play_area_.x - 5;
|
const float MIN_X = play_area_.x - 5;
|
||||||
@@ -215,7 +226,7 @@ void Player::handleRollingGroundCollision() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (player_sprite_->getVelY() < 2.0F) {
|
if (player_sprite_->getVelY() < 120.0F) { // 2.0F * 60fps = 120.0F pixels/segundo
|
||||||
handleRollingStop();
|
handleRollingStop();
|
||||||
} else {
|
} else {
|
||||||
handleRollingBounce();
|
handleRollingBounce();
|
||||||
@@ -242,10 +253,10 @@ void Player::handleRollingBounce() {
|
|||||||
playSound("jump.wav");
|
playSound("jump.wav");
|
||||||
}
|
}
|
||||||
|
|
||||||
void Player::handleTitleAnimation() {
|
void Player::handleTitleAnimation(float deltaTime) {
|
||||||
setInputBasedOnPlayerId();
|
setInputBasedOnPlayerId();
|
||||||
|
|
||||||
pos_x_ += vel_x_ * 2.0F;
|
pos_x_ += (vel_x_ * 2.0F) * deltaTime;
|
||||||
const float MIN_X = -WIDTH;
|
const float MIN_X = -WIDTH;
|
||||||
const float MAX_X = play_area_.w;
|
const float MAX_X = play_area_.w;
|
||||||
pos_x_ = std::clamp(pos_x_, MIN_X, MAX_X);
|
pos_x_ = std::clamp(pos_x_, MIN_X, MAX_X);
|
||||||
@@ -264,11 +275,11 @@ void Player::handleContinueTimeOut() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void Player::handleLeavingScreen() {
|
void Player::handleLeavingScreen(float deltaTime) {
|
||||||
updateStepCounter();
|
// updateStepCounter se llama desde move() con deltaTime
|
||||||
setInputBasedOnPlayerId();
|
setInputBasedOnPlayerId();
|
||||||
|
|
||||||
pos_x_ += vel_x_;
|
pos_x_ += vel_x_ * deltaTime;
|
||||||
const float MIN_X = -WIDTH;
|
const float MIN_X = -WIDTH;
|
||||||
const float MAX_X = play_area_.w;
|
const float MAX_X = play_area_.w;
|
||||||
pos_x_ = std::clamp(pos_x_, MIN_X, MAX_X);
|
pos_x_ = std::clamp(pos_x_, MIN_X, MAX_X);
|
||||||
@@ -279,15 +290,15 @@ void Player::handleLeavingScreen() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void Player::handleEnteringScreen() {
|
void Player::handleEnteringScreen(float deltaTime) {
|
||||||
updateStepCounter();
|
// updateStepCounter se llama desde move() con deltaTime
|
||||||
|
|
||||||
switch (id_) {
|
switch (id_) {
|
||||||
case Id::PLAYER1:
|
case Id::PLAYER1:
|
||||||
handlePlayer1Entering();
|
handlePlayer1Entering(deltaTime);
|
||||||
break;
|
break;
|
||||||
case Id::PLAYER2:
|
case Id::PLAYER2:
|
||||||
handlePlayer2Entering();
|
handlePlayer2Entering(deltaTime);
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
break;
|
break;
|
||||||
@@ -296,26 +307,27 @@ void Player::handleEnteringScreen() {
|
|||||||
shiftSprite();
|
shiftSprite();
|
||||||
}
|
}
|
||||||
|
|
||||||
void Player::handlePlayer1Entering() {
|
void Player::handlePlayer1Entering(float deltaTime) {
|
||||||
setInputPlaying(Input::Action::RIGHT);
|
setInputPlaying(Input::Action::RIGHT);
|
||||||
pos_x_ += vel_x_;
|
pos_x_ += vel_x_ * deltaTime;
|
||||||
if (pos_x_ > default_pos_x_) {
|
if (pos_x_ > default_pos_x_) {
|
||||||
pos_x_ = default_pos_x_;
|
pos_x_ = default_pos_x_;
|
||||||
setPlayingState(State::PLAYING);
|
setPlayingState(State::PLAYING);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void Player::handlePlayer2Entering() {
|
void Player::handlePlayer2Entering(float deltaTime) {
|
||||||
setInputPlaying(Input::Action::LEFT);
|
setInputPlaying(Input::Action::LEFT);
|
||||||
pos_x_ += vel_x_;
|
pos_x_ += vel_x_ * deltaTime;
|
||||||
if (pos_x_ < default_pos_x_) {
|
if (pos_x_ < default_pos_x_) {
|
||||||
pos_x_ = default_pos_x_;
|
pos_x_ = default_pos_x_;
|
||||||
setPlayingState(State::PLAYING);
|
setPlayingState(State::PLAYING);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void Player::handleCreditsMovement() {
|
// Movimiento general en la pantalla de créditos (time-based)
|
||||||
pos_x_ += vel_x_ / 2.0F;
|
void Player::handleCreditsMovement(float deltaTime) {
|
||||||
|
pos_x_ += (vel_x_ / 2.0F) * deltaTime;
|
||||||
|
|
||||||
if (vel_x_ > 0) {
|
if (vel_x_ > 0) {
|
||||||
handleCreditsRightMovement();
|
handleCreditsRightMovement();
|
||||||
@@ -341,10 +353,12 @@ void Player::handleCreditsLeftMovement() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void Player::handleWaitingMovement() {
|
// Controla la animación del jugador saludando (time-based)
|
||||||
++waiting_counter_;
|
void Player::handleWaitingMovement(float deltaTime) {
|
||||||
if (waiting_counter_ == WAITING_COUNTER) {
|
waiting_time_accumulator_ += deltaTime;
|
||||||
waiting_counter_ = 0;
|
const float WAITING_DURATION_S = static_cast<float>(WAITING_COUNTER) / 60.0f; // Convert frames to seconds
|
||||||
|
if (waiting_time_accumulator_ >= WAITING_DURATION_S) {
|
||||||
|
waiting_time_accumulator_ = 0.0f;
|
||||||
player_sprite_->resetAnimation();
|
player_sprite_->resetAnimation();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -370,9 +384,12 @@ void Player::setInputBasedOnPlayerId() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void Player::updateStepCounter() {
|
// Incrementa o ajusta el contador de pasos (time-based)
|
||||||
++step_counter_;
|
void Player::updateStepCounter(float deltaTime) {
|
||||||
if (step_counter_ % 10 == 0) {
|
step_time_accumulator_ += deltaTime;
|
||||||
|
const float STEP_INTERVAL_S = 10.0f / 60.0f; // 10 frames converted to seconds
|
||||||
|
if (step_time_accumulator_ >= STEP_INTERVAL_S) {
|
||||||
|
step_time_accumulator_ = 0.0f;
|
||||||
playSound("walk.wav");
|
playSound("walk.wav");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -380,8 +397,22 @@ void Player::updateStepCounter() {
|
|||||||
// Pinta el jugador en pantalla
|
// Pinta el jugador en pantalla
|
||||||
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) {
|
// Convertir lógica de parpadeo a deltaTime en segundos
|
||||||
|
const float TOTAL_POWERUP_TIME_S = static_cast<float>(POWERUP_COUNTER) / 60.0f; // Total time in seconds
|
||||||
|
const float QUARTER_TIME_S = TOTAL_POWERUP_TIME_S / 4.0f; // 25% del tiempo total
|
||||||
|
|
||||||
|
if (power_up_time_accumulator_ > QUARTER_TIME_S) {
|
||||||
|
// En los primeros 75% del tiempo, siempre visible
|
||||||
power_sprite_->render();
|
power_sprite_->render();
|
||||||
|
} else {
|
||||||
|
// En el último 25%, parpadea cada 20 frames (≈0.333s)
|
||||||
|
constexpr float BLINK_PERIOD_S = 20.0f / 60.0f; // 20 frames in seconds
|
||||||
|
constexpr float VISIBLE_PROPORTION = 4.0f / 20.0f; // 4 frames visible de 20 total
|
||||||
|
|
||||||
|
float cycle_position = fmod(power_up_time_accumulator_, BLINK_PERIOD_S) / BLINK_PERIOD_S;
|
||||||
|
if (cycle_position >= VISIBLE_PROPORTION) {
|
||||||
|
power_sprite_->render();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -444,8 +475,8 @@ auto Player::computeAnimation() const -> std::pair<std::string, SDL_FlipMode> {
|
|||||||
return {anim_name, flip_mode};
|
return {anim_name, flip_mode};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Establece la animación correspondiente al estado
|
// Fase 1: Establece la animación correspondiente al estado (time-based)
|
||||||
void Player::setAnimation() {
|
void Player::setAnimation(float deltaTime) {
|
||||||
switch (playing_state_) {
|
switch (playing_state_) {
|
||||||
case State::PLAYING:
|
case State::PLAYING:
|
||||||
case State::ENTERING_NAME_GAME_COMPLETED:
|
case State::ENTERING_NAME_GAME_COMPLETED:
|
||||||
@@ -481,110 +512,33 @@ void Player::setAnimation() {
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
player_sprite_->update();
|
// La diferencia clave: usa deltaTime para las animaciones
|
||||||
power_sprite_->update();
|
player_sprite_->update(deltaTime);
|
||||||
|
power_sprite_->update(deltaTime);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Actualiza el valor de la variable
|
// Actualiza al jugador con deltaTime (time-based)
|
||||||
void Player::updateCooldown() {
|
void Player::update(float deltaTime) {
|
||||||
if (playing_state_ != State::PLAYING) {
|
move(deltaTime); // Sistema de movimiento time-based
|
||||||
return;
|
setAnimation(deltaTime); // Animaciones time-based
|
||||||
}
|
shiftColliders(); // Sin cambios (posicional)
|
||||||
|
updateFireSystem(deltaTime); // Sistema de disparo de dos líneas
|
||||||
|
updatePowerUp(deltaTime); // Sistema de power-up time-based
|
||||||
|
updateInvulnerable(deltaTime); // Sistema de invulnerabilidad time-based
|
||||||
|
updateScoreboard(); // Sin cambios (no temporal)
|
||||||
|
updateContinueCounter(deltaTime); // Sistema de continue time-based
|
||||||
|
updateEnterNameCounter(deltaTime); // Sistema de name entry time-based
|
||||||
|
updateShowingName(deltaTime); // Sistema de showing name time-based
|
||||||
|
}
|
||||||
|
|
||||||
if (cant_fire_counter_ > 0) {
|
void Player::passShowingName() {
|
||||||
handleFiringCooldown();
|
if (game_completed_) {
|
||||||
|
setPlayingState(State::LEAVING_SCREEN);
|
||||||
} else {
|
} else {
|
||||||
handleRecoilAndCooling();
|
setPlayingState(State::CONTINUE);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void Player::handleFiringCooldown() {
|
|
||||||
cooling_state_counter_ = COOLING_DURATION;
|
|
||||||
|
|
||||||
// Transition to recoiling state at halfway point
|
|
||||||
if (cant_fire_counter_ == recoiling_state_duration_ / 2) {
|
|
||||||
transitionToRecoiling();
|
|
||||||
}
|
|
||||||
|
|
||||||
--cant_fire_counter_;
|
|
||||||
if (cant_fire_counter_ == 0) {
|
|
||||||
recoiling_state_counter_ = recoiling_state_duration_;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void Player::handleRecoilAndCooling() {
|
|
||||||
if (recoiling_state_counter_ > 0) {
|
|
||||||
--recoiling_state_counter_;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
handleCoolingState();
|
|
||||||
}
|
|
||||||
|
|
||||||
void Player::handleCoolingState() {
|
|
||||||
if (cooling_state_counter_ > COOLING_COMPLETE) {
|
|
||||||
if (cooling_state_counter_ == COOLING_DURATION) {
|
|
||||||
transitionToCooling();
|
|
||||||
}
|
|
||||||
--cooling_state_counter_;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (cooling_state_counter_ == COOLING_COMPLETE) {
|
|
||||||
completeCooling();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void Player::transitionToRecoiling() {
|
|
||||||
switch (firing_state_) {
|
|
||||||
case State::FIRING_LEFT:
|
|
||||||
setFiringState(State::RECOILING_LEFT);
|
|
||||||
break;
|
|
||||||
case State::FIRING_RIGHT:
|
|
||||||
setFiringState(State::RECOILING_RIGHT);
|
|
||||||
break;
|
|
||||||
case State::FIRING_UP:
|
|
||||||
setFiringState(State::RECOILING_UP);
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void Player::transitionToCooling() {
|
|
||||||
switch (firing_state_) {
|
|
||||||
case State::RECOILING_LEFT:
|
|
||||||
setFiringState(State::COOLING_LEFT);
|
|
||||||
break;
|
|
||||||
case State::RECOILING_RIGHT:
|
|
||||||
setFiringState(State::COOLING_RIGHT);
|
|
||||||
break;
|
|
||||||
case State::RECOILING_UP:
|
|
||||||
setFiringState(State::COOLING_UP);
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void Player::completeCooling() {
|
|
||||||
setFiringState(State::FIRING_NONE);
|
|
||||||
cooling_state_counter_ = -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Actualiza al jugador a su posicion, animación y controla los contadores
|
|
||||||
void Player::update() {
|
|
||||||
move();
|
|
||||||
setAnimation();
|
|
||||||
shiftColliders();
|
|
||||||
updateCooldown();
|
|
||||||
updatePowerUp();
|
|
||||||
updateInvulnerable();
|
|
||||||
updateScoreboard();
|
|
||||||
updateContinueCounter();
|
|
||||||
updateEnterNameCounter();
|
|
||||||
updateShowingName();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Incrementa la puntuación del jugador
|
// Incrementa la puntuación del jugador
|
||||||
void Player::addScore(int score, int lowest_hi_score_entry) {
|
void Player::addScore(int score, int lowest_hi_score_entry) {
|
||||||
if (isPlaying()) {
|
if (isPlaying()) {
|
||||||
@@ -624,6 +578,9 @@ void Player::setPlayingState(State state) {
|
|||||||
|
|
||||||
switch (playing_state_) {
|
switch (playing_state_) {
|
||||||
case State::RECOVER: {
|
case State::RECOVER: {
|
||||||
|
score_ = 0; // Pon los puntos a cero para que no se vea en el marcador
|
||||||
|
score_multiplier_ = 1.0F;
|
||||||
|
setScoreboardMode(Scoreboard::Mode::SCORE);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case State::RESPAWNING: {
|
case State::RESPAWNING: {
|
||||||
@@ -641,8 +598,8 @@ void Player::setPlayingState(State state) {
|
|||||||
}
|
}
|
||||||
case State::CONTINUE: {
|
case State::CONTINUE: {
|
||||||
// Inicializa el contador de continuar
|
// Inicializa el contador de continuar
|
||||||
continue_ticks_ = SDL_GetTicks();
|
|
||||||
continue_counter_ = 9;
|
continue_counter_ = 9;
|
||||||
|
continue_time_accumulator_ = 0.0f; // Initialize time accumulator
|
||||||
playSound("continue_clock.wav");
|
playSound("continue_clock.wav");
|
||||||
setScoreboardMode(Scoreboard::Mode::CONTINUE);
|
setScoreboardMode(Scoreboard::Mode::CONTINUE);
|
||||||
break;
|
break;
|
||||||
@@ -661,6 +618,7 @@ void Player::setPlayingState(State state) {
|
|||||||
}
|
}
|
||||||
pos_y_ = default_pos_y_;
|
pos_y_ = default_pos_y_;
|
||||||
waiting_counter_ = 0;
|
waiting_counter_ = 0;
|
||||||
|
waiting_time_accumulator_ = 0.0f; // Initialize time accumulator
|
||||||
shiftSprite();
|
shiftSprite();
|
||||||
player_sprite_->setCurrentAnimation("hello");
|
player_sprite_->setCurrentAnimation("hello");
|
||||||
player_sprite_->animtionPause();
|
player_sprite_->animtionPause();
|
||||||
@@ -672,7 +630,7 @@ void Player::setPlayingState(State state) {
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case State::SHOWING_NAME: {
|
case State::SHOWING_NAME: {
|
||||||
showing_name_ticks_ = SDL_GetTicks();
|
showing_name_time_accumulator_ = 0.0f; // Inicializar acumulador time-based
|
||||||
setScoreboardMode(Scoreboard::Mode::SHOW_NAME);
|
setScoreboardMode(Scoreboard::Mode::SHOW_NAME);
|
||||||
Scoreboard::get()->setRecordName(scoreboard_panel_, last_enter_name_);
|
Scoreboard::get()->setRecordName(scoreboard_panel_, last_enter_name_);
|
||||||
addScoreToScoreBoard();
|
addScoreToScoreBoard();
|
||||||
@@ -681,15 +639,15 @@ void Player::setPlayingState(State state) {
|
|||||||
case State::ROLLING: {
|
case State::ROLLING: {
|
||||||
// Activa la animación de rodar dando botes
|
// Activa la animación de rodar dando botes
|
||||||
player_sprite_->setCurrentAnimation("rolling");
|
player_sprite_->setCurrentAnimation("rolling");
|
||||||
player_sprite_->setAnimationSpeed(4);
|
player_sprite_->setAnimationSpeed(4.0f / 60.0f); // 4 frames convertido a segundos
|
||||||
player_sprite_->setVelY(-6.6F); // Velocidad inicial
|
player_sprite_->setVelY(-396.0F); // Velocidad inicial (6.6 * 60 = 396 pixels/s)
|
||||||
player_sprite_->setAccelY(0.2F); // Gravedad
|
player_sprite_->setAccelY(720.0F); // Gravedad (0.2 * 60² = 720 pixels/s²)
|
||||||
player_sprite_->setPosY(pos_y_ - 2); // Para "sacarlo" del suelo, ya que está hundido un pixel para ocultar el outline de los pies
|
player_sprite_->setPosY(pos_y_ - 2); // Para "sacarlo" del suelo, ya que está hundido un pixel para ocultar el outline de los pies
|
||||||
(rand() % 2 == 0) ? player_sprite_->setVelX(3.3F) : player_sprite_->setVelX(-3.3F);
|
(rand() % 2 == 0) ? player_sprite_->setVelX(198.0F) : player_sprite_->setVelX(-198.0F); // 3.3 * 60 = 198 pixels/s
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case State::TITLE_ANIMATION: {
|
case State::TITLE_ANIMATION: {
|
||||||
// Activa la animación de rodar
|
// Activa la animación de caminar
|
||||||
player_sprite_->setCurrentAnimation("walk");
|
player_sprite_->setCurrentAnimation("walk");
|
||||||
playSound("voice_credit_thankyou.wav");
|
playSound("voice_credit_thankyou.wav");
|
||||||
break;
|
break;
|
||||||
@@ -701,11 +659,11 @@ void Player::setPlayingState(State state) {
|
|||||||
}
|
}
|
||||||
case State::CONTINUE_TIME_OUT: {
|
case State::CONTINUE_TIME_OUT: {
|
||||||
// Activa la animación de sacar al jugador de la zona de juego
|
// Activa la animación de sacar al jugador de la zona de juego
|
||||||
player_sprite_->setAccelY(0.2F);
|
player_sprite_->setAccelY(720.0F); // 0.2 * 60² = 720 pixels/s²
|
||||||
player_sprite_->setVelY(-4.0F);
|
player_sprite_->setVelY(-240.0F); // -4.0 * 60 = -240 pixels/s
|
||||||
player_sprite_->setVelX(0.0F);
|
player_sprite_->setVelX(0.0F);
|
||||||
player_sprite_->setCurrentAnimation("rolling");
|
player_sprite_->setCurrentAnimation("rolling");
|
||||||
player_sprite_->setAnimationSpeed(5);
|
player_sprite_->setAnimationSpeed(5.0f / 60.0f); // 5 frames convertido a segundos
|
||||||
setScoreboardMode(Scoreboard::Mode::GAME_OVER);
|
setScoreboardMode(Scoreboard::Mode::GAME_OVER);
|
||||||
playSound("voice_aw_aw_aw.wav");
|
playSound("voice_aw_aw_aw.wav");
|
||||||
playSound("jump.wav");
|
playSound("jump.wav");
|
||||||
@@ -728,12 +686,14 @@ void Player::setPlayingState(State state) {
|
|||||||
}
|
}
|
||||||
case State::LEAVING_SCREEN: {
|
case State::LEAVING_SCREEN: {
|
||||||
step_counter_ = 0;
|
step_counter_ = 0;
|
||||||
|
step_time_accumulator_ = 0.0f; // Initialize time accumulator
|
||||||
setScoreboardMode(Scoreboard::Mode::GAME_COMPLETED);
|
setScoreboardMode(Scoreboard::Mode::GAME_COMPLETED);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case State::ENTERING_SCREEN: {
|
case State::ENTERING_SCREEN: {
|
||||||
init();
|
init();
|
||||||
step_counter_ = 0;
|
step_counter_ = 0;
|
||||||
|
step_time_accumulator_ = 0.0f; // Initialize time accumulator
|
||||||
setScoreboardMode(Scoreboard::Mode::SCORE);
|
setScoreboardMode(Scoreboard::Mode::SCORE);
|
||||||
switch (id_) {
|
switch (id_) {
|
||||||
case Id::PLAYER1:
|
case Id::PLAYER1:
|
||||||
@@ -774,32 +734,35 @@ void Player::decScoreMultiplier() {
|
|||||||
void Player::setInvulnerable(bool value) {
|
void Player::setInvulnerable(bool value) {
|
||||||
invulnerable_ = value;
|
invulnerable_ = value;
|
||||||
invulnerable_counter_ = invulnerable_ ? INVULNERABLE_COUNTER : 0;
|
invulnerable_counter_ = invulnerable_ ? INVULNERABLE_COUNTER : 0;
|
||||||
|
invulnerable_time_accumulator_ = invulnerable_ ? static_cast<float>(INVULNERABLE_COUNTER) / 60.0f : 0.0f; // Convert frames to seconds
|
||||||
}
|
}
|
||||||
|
|
||||||
// Monitoriza el estado
|
// Monitoriza el estado (time-based)
|
||||||
void Player::updateInvulnerable() {
|
void Player::updateInvulnerable(float deltaTime) {
|
||||||
if (playing_state_ == State::PLAYING && invulnerable_) {
|
if (playing_state_ == State::PLAYING && invulnerable_) {
|
||||||
if (invulnerable_counter_ > 0) {
|
if (invulnerable_time_accumulator_ > 0) {
|
||||||
--invulnerable_counter_;
|
invulnerable_time_accumulator_ -= deltaTime;
|
||||||
|
|
||||||
// Frecuencia fija de parpadeo (como el original)
|
// Frecuencia fija de parpadeo adaptada a deltaTime (en segundos)
|
||||||
constexpr int blink_speed = 8;
|
constexpr float BLINK_PERIOD_S = 8.0f / 60.0f; // 8 frames convertidos a segundos
|
||||||
|
|
||||||
// Calcula proporción decreciente: menos textura blanca hacia el final
|
// Calcula proporción decreciente basada en tiempo restante
|
||||||
// Al inicio: 50-50, hacia el final: 70-30 (menos blanco)
|
const float TOTAL_INVULNERABLE_TIME_S = static_cast<float>(INVULNERABLE_COUNTER) / 60.0f;
|
||||||
float progress = 1.0f - (static_cast<float>(invulnerable_counter_) / INVULNERABLE_COUNTER);
|
float progress = 1.0f - (invulnerable_time_accumulator_ / TOTAL_INVULNERABLE_TIME_S);
|
||||||
int white_frames = static_cast<int>((0.5f - progress * 0.2f) * blink_speed);
|
float white_proportion = 0.5f - progress * 0.2f; // Menos blanco hacia el final
|
||||||
|
|
||||||
// Alterna entre texturas con proporción variable
|
// Calcula si debe mostrar textura de invulnerabilidad basado en el ciclo temporal
|
||||||
bool should_show_invulnerable = (invulnerable_counter_ % blink_speed) < white_frames;
|
float cycle_position = fmod(invulnerable_time_accumulator_, BLINK_PERIOD_S) / BLINK_PERIOD_S;
|
||||||
|
bool should_show_invulnerable = cycle_position < white_proportion;
|
||||||
size_t target_texture = should_show_invulnerable ? INVULNERABLE_TEXTURE : coffees_;
|
size_t target_texture = should_show_invulnerable ? INVULNERABLE_TEXTURE : coffees_;
|
||||||
|
|
||||||
// Solo cambia textura si es diferente (optimización)
|
// Solo cambia textura si es diferente (optimización)
|
||||||
if (player_sprite_->getActiveTexture() != target_texture) {
|
if (player_sprite_->getActiveTexture() != target_texture) {
|
||||||
player_sprite_->setActiveTexture(target_texture);
|
player_sprite_->setActiveTexture(target_texture);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// Fin de invulnerabilidad
|
// Fin de invulnerabilidad
|
||||||
|
invulnerable_time_accumulator_ = 0;
|
||||||
setInvulnerable(false);
|
setInvulnerable(false);
|
||||||
player_sprite_->setActiveTexture(coffees_);
|
player_sprite_->setActiveTexture(coffees_);
|
||||||
}
|
}
|
||||||
@@ -810,14 +773,18 @@ void Player::updateInvulnerable() {
|
|||||||
void Player::setPowerUp() {
|
void Player::setPowerUp() {
|
||||||
power_up_ = true;
|
power_up_ = true;
|
||||||
power_up_counter_ = POWERUP_COUNTER;
|
power_up_counter_ = POWERUP_COUNTER;
|
||||||
|
power_up_time_accumulator_ = static_cast<float>(POWERUP_COUNTER) / 60.0f; // Convert frames to seconds
|
||||||
}
|
}
|
||||||
|
|
||||||
// Actualiza el valor de la variable
|
// Actualiza el valor de la variable (time-based)
|
||||||
void Player::updatePowerUp() {
|
void Player::updatePowerUp(float deltaTime) {
|
||||||
if (playing_state_ == State::PLAYING) {
|
if (playing_state_ == State::PLAYING) {
|
||||||
if (power_up_) {
|
if (power_up_) {
|
||||||
--power_up_counter_;
|
power_up_time_accumulator_ -= deltaTime;
|
||||||
power_up_ = power_up_counter_ > 0;
|
power_up_ = power_up_time_accumulator_ > 0;
|
||||||
|
if (!power_up_) {
|
||||||
|
power_up_time_accumulator_ = 0;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -854,31 +821,36 @@ void Player::setPlayerTextures(const std::vector<std::shared_ptr<Texture>> &text
|
|||||||
power_sprite_->setTexture(texture[1]);
|
power_sprite_->setTexture(texture[1]);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Actualiza el contador de continue
|
// Actualiza el contador de continue (time-based)
|
||||||
void Player::updateContinueCounter() {
|
void Player::updateContinueCounter(float deltaTime) {
|
||||||
if (playing_state_ == State::CONTINUE) {
|
if (playing_state_ == State::CONTINUE) {
|
||||||
constexpr int TICKS_SPEED = 1000;
|
continue_time_accumulator_ += deltaTime;
|
||||||
if (SDL_GetTicks() - continue_ticks_ > TICKS_SPEED) {
|
constexpr float CONTINUE_INTERVAL_S = 1.0f; // 1 segundo
|
||||||
|
if (continue_time_accumulator_ >= CONTINUE_INTERVAL_S) {
|
||||||
|
continue_time_accumulator_ -= CONTINUE_INTERVAL_S;
|
||||||
decContinueCounter();
|
decContinueCounter();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Actualiza el contador de entrar nombre
|
// Actualiza el contador de entrar nombre (time-based)
|
||||||
void Player::updateEnterNameCounter() {
|
void Player::updateEnterNameCounter(float deltaTime) {
|
||||||
if (playing_state_ == State::ENTERING_NAME || playing_state_ == State::ENTERING_NAME_GAME_COMPLETED) {
|
if (playing_state_ == State::ENTERING_NAME || playing_state_ == State::ENTERING_NAME_GAME_COMPLETED) {
|
||||||
constexpr int TICKS_SPEED = 1000;
|
name_entry_time_accumulator_ += deltaTime;
|
||||||
if (SDL_GetTicks() - name_entry_ticks_ > TICKS_SPEED) {
|
constexpr float NAME_ENTRY_INTERVAL_S = 1.0f; // 1 segundo
|
||||||
|
if (name_entry_time_accumulator_ >= NAME_ENTRY_INTERVAL_S) {
|
||||||
|
name_entry_time_accumulator_ -= NAME_ENTRY_INTERVAL_S;
|
||||||
decNameEntryCounter();
|
decNameEntryCounter();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Actualiza el estado de SHOWING_NAME
|
// Actualiza el estado de SHOWING_NAME (time-based)
|
||||||
void Player::updateShowingName() {
|
void Player::updateShowingName(float deltaTime) {
|
||||||
if (playing_state_ == State::SHOWING_NAME) {
|
if (playing_state_ == State::SHOWING_NAME) {
|
||||||
constexpr int TICKS_SPEED = 5000;
|
showing_name_time_accumulator_ += deltaTime;
|
||||||
if (SDL_GetTicks() - name_entry_ticks_ > TICKS_SPEED) {
|
constexpr float SHOWING_NAME_DURATION_S = 5.0f; // 5 segundos
|
||||||
|
if (showing_name_time_accumulator_ >= SHOWING_NAME_DURATION_S) {
|
||||||
game_completed_ ? setPlayingState(State::LEAVING_SCREEN) : setPlayingState(State::CONTINUE);
|
game_completed_ ? setPlayingState(State::LEAVING_SCREEN) : setPlayingState(State::CONTINUE);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -886,7 +858,7 @@ void Player::updateShowingName() {
|
|||||||
|
|
||||||
// Decrementa el contador de continuar
|
// Decrementa el contador de continuar
|
||||||
void Player::decContinueCounter() {
|
void Player::decContinueCounter() {
|
||||||
continue_ticks_ = SDL_GetTicks();
|
continue_time_accumulator_ = 0.0f; // Reset time accumulator
|
||||||
--continue_counter_;
|
--continue_counter_;
|
||||||
if (continue_counter_ < 0) {
|
if (continue_counter_ < 0) {
|
||||||
setPlayingState(State::CONTINUE_TIME_OUT);
|
setPlayingState(State::CONTINUE_TIME_OUT);
|
||||||
@@ -897,17 +869,16 @@ void Player::decContinueCounter() {
|
|||||||
|
|
||||||
// Decrementa el contador de entrar nombre
|
// Decrementa el contador de entrar nombre
|
||||||
void Player::decNameEntryCounter() {
|
void Player::decNameEntryCounter() {
|
||||||
name_entry_ticks_ = SDL_GetTicks();
|
name_entry_time_accumulator_ = 0.0f; // Reset time accumulator
|
||||||
|
|
||||||
// Actualiza contadores
|
// Incrementa acumuladores de tiempo (1 segundo)
|
||||||
++name_entry_idle_counter_;
|
name_entry_idle_time_accumulator_ += 1.0f;
|
||||||
++name_entry_total_counter_;
|
name_entry_total_time_accumulator_ += 1.0f;
|
||||||
|
|
||||||
// Comprueba los contadores
|
if ((name_entry_total_time_accumulator_ >= param.game.name_entry_total_time) ||
|
||||||
if ((name_entry_total_counter_ >= param.game.name_entry_total_time) ||
|
(name_entry_idle_time_accumulator_ >= param.game.name_entry_idle_time)) {
|
||||||
(name_entry_idle_counter_ >= param.game.name_entry_idle_time)) {
|
name_entry_total_time_accumulator_ = 0.0f;
|
||||||
name_entry_total_counter_ = 0;
|
name_entry_idle_time_accumulator_ = 0.0f;
|
||||||
name_entry_idle_counter_ = 0;
|
|
||||||
if (playing_state_ == State::ENTERING_NAME) {
|
if (playing_state_ == State::ENTERING_NAME) {
|
||||||
last_enter_name_ = getRecordName();
|
last_enter_name_ = getRecordName();
|
||||||
setPlayingState(State::SHOWING_NAME);
|
setPlayingState(State::SHOWING_NAME);
|
||||||
@@ -967,4 +938,145 @@ void Player::addScoreToScoreBoard() const {
|
|||||||
void Player::addCredit() {
|
void Player::addCredit() {
|
||||||
++credits_used_;
|
++credits_used_;
|
||||||
playSound("credit.wav");
|
playSound("credit.wav");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========================================
|
||||||
|
// SISTEMA DE DISPARO DE DOS LÍNEAS
|
||||||
|
// ========================================
|
||||||
|
|
||||||
|
// Método principal del sistema de disparo
|
||||||
|
void Player::updateFireSystem(float deltaTime) {
|
||||||
|
updateFunctionalLine(deltaTime); // Línea 1: CanFire
|
||||||
|
updateVisualLine(deltaTime); // Línea 2: Animaciones
|
||||||
|
}
|
||||||
|
|
||||||
|
// LÍNEA 1: Sistema Funcional (CanFire)
|
||||||
|
void Player::updateFunctionalLine(float deltaTime) {
|
||||||
|
if (fire_cooldown_timer_ > 0) {
|
||||||
|
fire_cooldown_timer_ -= deltaTime;
|
||||||
|
can_fire_new_system_ = false;
|
||||||
|
} else {
|
||||||
|
fire_cooldown_timer_ = 0; // Evitar valores negativos
|
||||||
|
can_fire_new_system_ = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// LÍNEA 2: Sistema Visual (Animaciones)
|
||||||
|
void Player::updateVisualLine(float deltaTime) {
|
||||||
|
if (visual_fire_state_ == VisualFireState::NORMAL) {
|
||||||
|
return; // No hay temporizador activo en estado NORMAL
|
||||||
|
}
|
||||||
|
|
||||||
|
visual_state_timer_ -= deltaTime;
|
||||||
|
|
||||||
|
switch (visual_fire_state_) {
|
||||||
|
case VisualFireState::AIMING:
|
||||||
|
if (visual_state_timer_ <= 0) {
|
||||||
|
transitionToRecoilingNew();
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case VisualFireState::RECOILING:
|
||||||
|
if (visual_state_timer_ <= 0) {
|
||||||
|
transitionToThreatPose();
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case VisualFireState::THREAT_POSE:
|
||||||
|
if (visual_state_timer_ <= 0) {
|
||||||
|
transitionToNormalNew();
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case VisualFireState::NORMAL:
|
||||||
|
// Ya manejado arriba
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Inicia un disparo en ambas líneas
|
||||||
|
void Player::startFiringSystem(int cooldown_frames) {
|
||||||
|
// LÍNEA 1: Inicia cooldown funcional
|
||||||
|
fire_cooldown_timer_ = static_cast<float>(cooldown_frames) / 60.0f; // Convertir frames a segundos
|
||||||
|
can_fire_new_system_ = false;
|
||||||
|
|
||||||
|
// LÍNEA 2: Resetea completamente el estado visual
|
||||||
|
aiming_duration_ = fire_cooldown_timer_ * AIMING_DURATION_FACTOR; // 50% del cooldown
|
||||||
|
recoiling_duration_ = aiming_duration_ * RECOILING_DURATION_MULTIPLIER; // 4 veces la duración de aiming
|
||||||
|
|
||||||
|
visual_fire_state_ = VisualFireState::AIMING;
|
||||||
|
visual_state_timer_ = aiming_duration_;
|
||||||
|
|
||||||
|
updateFiringStateFromVisual(); // Sincroniza firing_state_ para animaciones
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sincroniza firing_state_ con visual_fire_state_
|
||||||
|
void Player::updateFiringStateFromVisual() {
|
||||||
|
// Mantener la dirección actual del disparo
|
||||||
|
State base_state = State::FIRING_NONE;
|
||||||
|
|
||||||
|
if (firing_state_ == State::FIRING_LEFT || firing_state_ == State::RECOILING_LEFT || firing_state_ == State::COOLING_LEFT) {
|
||||||
|
base_state = State::FIRING_LEFT;
|
||||||
|
} else if (firing_state_ == State::FIRING_RIGHT || firing_state_ == State::RECOILING_RIGHT || firing_state_ == State::COOLING_RIGHT) {
|
||||||
|
base_state = State::FIRING_RIGHT;
|
||||||
|
} else if (firing_state_ == State::FIRING_UP || firing_state_ == State::RECOILING_UP || firing_state_ == State::COOLING_UP) {
|
||||||
|
base_state = State::FIRING_UP;
|
||||||
|
}
|
||||||
|
|
||||||
|
switch (visual_fire_state_) {
|
||||||
|
case VisualFireState::NORMAL:
|
||||||
|
firing_state_ = State::FIRING_NONE;
|
||||||
|
break;
|
||||||
|
|
||||||
|
case VisualFireState::AIMING:
|
||||||
|
firing_state_ = base_state; // FIRING_LEFT/RIGHT/UP
|
||||||
|
break;
|
||||||
|
|
||||||
|
case VisualFireState::RECOILING:
|
||||||
|
switch (base_state) {
|
||||||
|
case State::FIRING_LEFT: firing_state_ = State::RECOILING_LEFT; break;
|
||||||
|
case State::FIRING_RIGHT: firing_state_ = State::RECOILING_RIGHT; break;
|
||||||
|
case State::FIRING_UP: firing_state_ = State::RECOILING_UP; break;
|
||||||
|
default: firing_state_ = State::RECOILING_UP; break;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case VisualFireState::THREAT_POSE:
|
||||||
|
switch (base_state) {
|
||||||
|
case State::FIRING_LEFT: firing_state_ = State::COOLING_LEFT; break;
|
||||||
|
case State::FIRING_RIGHT: firing_state_ = State::COOLING_RIGHT; break;
|
||||||
|
case State::FIRING_UP: firing_state_ = State::COOLING_UP; break;
|
||||||
|
default: firing_state_ = State::COOLING_UP; break;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Transiciones del sistema visual
|
||||||
|
void Player::transitionToRecoilingNew() {
|
||||||
|
visual_fire_state_ = VisualFireState::RECOILING;
|
||||||
|
visual_state_timer_ = recoiling_duration_;
|
||||||
|
updateFiringStateFromVisual();
|
||||||
|
}
|
||||||
|
|
||||||
|
void Player::transitionToThreatPose() {
|
||||||
|
visual_fire_state_ = VisualFireState::THREAT_POSE;
|
||||||
|
|
||||||
|
// Calcular threat_pose_duration ajustada:
|
||||||
|
// Duración original (833ms) menos el tiempo extra que ahora dura recoiling
|
||||||
|
float original_recoiling_duration = fire_cooldown_timer_; // Era 100% del cooldown
|
||||||
|
float new_recoiling_duration = aiming_duration_ * RECOILING_DURATION_MULTIPLIER; // Ahora es más del cooldown
|
||||||
|
float extra_recoiling_time = new_recoiling_duration - original_recoiling_duration;
|
||||||
|
float adjusted_threat_duration = THREAT_POSE_DURATION - extra_recoiling_time;
|
||||||
|
|
||||||
|
// Asegurar que no sea negativo
|
||||||
|
visual_state_timer_ = std::max(adjusted_threat_duration, MIN_THREAT_POSE_DURATION);
|
||||||
|
|
||||||
|
updateFiringStateFromVisual();
|
||||||
|
}
|
||||||
|
|
||||||
|
void Player::transitionToNormalNew() {
|
||||||
|
visual_fire_state_ = VisualFireState::NORMAL;
|
||||||
|
visual_state_timer_ = 0;
|
||||||
|
updateFiringStateFromVisual();
|
||||||
}
|
}
|
||||||
154
source/player.h
154
source/player.h
@@ -17,7 +17,21 @@
|
|||||||
|
|
||||||
class Texture;
|
class Texture;
|
||||||
|
|
||||||
// --- Clase Player ---
|
// --- Clase Player: jugador principal del juego ---
|
||||||
|
//
|
||||||
|
// Esta clase gestiona todos los aspectos de un jugador durante el juego,
|
||||||
|
// incluyendo movimiento, disparos, animaciones y estados especiales.
|
||||||
|
//
|
||||||
|
// Funcionalidades principales:
|
||||||
|
// • Sistema de disparo de dos líneas: funcional (cooldown) + visual (animaciones)
|
||||||
|
// • Estados de animación: normal → aiming → recoiling → threat_pose → normal
|
||||||
|
// • Movimiento time-based: compatibilidad con deltaTime para fluidez variable
|
||||||
|
// • Power-ups e invulnerabilidad: coffee machine, extra hits, parpadeos
|
||||||
|
// • Sistema de puntuación: multipliers, high scores, entrada de nombres
|
||||||
|
// • Estados de juego: playing, rolling, continue, entering_name, etc.
|
||||||
|
//
|
||||||
|
// El sistema de disparo utiliza duraciones configurables mediante constantes
|
||||||
|
// para facilitar el ajuste del gameplay y la sensación de disparo.
|
||||||
class Player {
|
class Player {
|
||||||
public:
|
public:
|
||||||
// --- Constantes ---
|
// --- Constantes ---
|
||||||
@@ -94,9 +108,9 @@ class Player {
|
|||||||
~Player() = default;
|
~Player() = default;
|
||||||
|
|
||||||
// --- Inicialización y ciclo de vida ---
|
// --- Inicialización y ciclo de vida ---
|
||||||
void init(); // Inicializa el jugador
|
void init(); // Inicializa el jugador
|
||||||
void update(); // Actualiza estado, animación y contadores
|
void update(float deltaTime); // Actualiza estado, animación y contadores (time-based)
|
||||||
void render(); // Dibuja el jugador en pantalla
|
void render(); // Dibuja el jugador en pantalla
|
||||||
|
|
||||||
// --- Entrada y control ---
|
// --- Entrada y control ---
|
||||||
void setInput(Input::Action action); // Procesa entrada general
|
void setInput(Input::Action action); // Procesa entrada general
|
||||||
@@ -104,14 +118,13 @@ class Player {
|
|||||||
void setInputEnteringName(Input::Action action); // Procesa entrada al introducir nombre
|
void setInputEnteringName(Input::Action action); // Procesa entrada al introducir nombre
|
||||||
|
|
||||||
// --- Movimiento y animación ---
|
// --- Movimiento y animación ---
|
||||||
void move(); // Mueve el jugador
|
void move(float deltaTime); // Mueve el jugador (time-based)
|
||||||
void setAnimation(); // Establece la animación según el estado
|
void setAnimation(float deltaTime); // Establece la animación según el estado (time-based)
|
||||||
|
|
||||||
// --- Texturas y animaciones ---
|
// --- Texturas y animaciones ---
|
||||||
void setPlayerTextures(const std::vector<std::shared_ptr<Texture>> &texture); // Cambia las texturas del jugador
|
void setPlayerTextures(const std::vector<std::shared_ptr<Texture>> &texture); // Cambia las texturas del jugador
|
||||||
|
|
||||||
// --- Estados y contadores ---
|
// --- Estados y contadores ---
|
||||||
void updateCooldown(); // Actualiza el cooldown de disparo
|
|
||||||
|
|
||||||
// --- Puntuación y marcador ---
|
// --- Puntuación y marcador ---
|
||||||
void addScore(int score, int lowest_hi_score_entry); // Añade puntos
|
void addScore(int score, int lowest_hi_score_entry); // Añade puntos
|
||||||
@@ -122,7 +135,7 @@ class Player {
|
|||||||
void setPlayingState(State state); // Cambia el estado de juego
|
void setPlayingState(State state); // Cambia el estado de juego
|
||||||
void setInvulnerable(bool value); // Establece el valor del estado de invulnerabilidad
|
void setInvulnerable(bool value); // Establece el valor del estado de invulnerabilidad
|
||||||
void setPowerUp(); // Activa el modo PowerUp
|
void setPowerUp(); // Activa el modo PowerUp
|
||||||
void updatePowerUp(); // Actualiza el valor de PowerUp
|
void updatePowerUp(float deltaTime); // Actualiza el valor de PowerUp (time-based)
|
||||||
void giveExtraHit(); // Concede un toque extra al jugador
|
void giveExtraHit(); // Concede un toque extra al jugador
|
||||||
void removeExtraHit(); // Quita el toque extra al jugador
|
void removeExtraHit(); // Quita el toque extra al jugador
|
||||||
void decContinueCounter(); // Decrementa el contador de continuar
|
void decContinueCounter(); // Decrementa el contador de continuar
|
||||||
@@ -145,7 +158,7 @@ class Player {
|
|||||||
[[nodiscard]] auto isTitleHidden() const -> bool { return playing_state_ == State::TITLE_HIDDEN; }
|
[[nodiscard]] auto isTitleHidden() const -> bool { return playing_state_ == State::TITLE_HIDDEN; }
|
||||||
|
|
||||||
// Getters
|
// Getters
|
||||||
[[nodiscard]] auto canFire() const -> bool { return cant_fire_counter_ <= 0; }
|
[[nodiscard]] auto canFire() const -> bool { return can_fire_new_system_; } // Usa nuevo sistema
|
||||||
[[nodiscard]] auto hasExtraHit() const -> bool { return extra_hit_; }
|
[[nodiscard]] auto hasExtraHit() const -> bool { return extra_hit_; }
|
||||||
[[nodiscard]] auto isCooling() const -> bool { return firing_state_ == State::COOLING_LEFT || firing_state_ == State::COOLING_UP || firing_state_ == State::COOLING_RIGHT; }
|
[[nodiscard]] auto isCooling() const -> bool { return firing_state_ == State::COOLING_LEFT || firing_state_ == State::COOLING_UP || firing_state_ == State::COOLING_RIGHT; }
|
||||||
[[nodiscard]] auto isRecoiling() const -> bool { return firing_state_ == State::RECOILING_LEFT || firing_state_ == State::RECOILING_UP || firing_state_ == State::RECOILING_RIGHT; }
|
[[nodiscard]] auto isRecoiling() const -> bool { return firing_state_ == State::RECOILING_LEFT || firing_state_ == State::RECOILING_UP || firing_state_ == State::RECOILING_RIGHT; }
|
||||||
@@ -170,12 +183,12 @@ class Player {
|
|||||||
[[nodiscard]] static auto getWidth() -> int { return WIDTH; }
|
[[nodiscard]] static auto getWidth() -> int { return WIDTH; }
|
||||||
[[nodiscard]] auto getPlayingState() const -> State { return playing_state_; }
|
[[nodiscard]] auto getPlayingState() const -> State { return playing_state_; }
|
||||||
[[nodiscard]] auto getName() const -> const std::string & { return name_; }
|
[[nodiscard]] auto getName() const -> const std::string & { return name_; }
|
||||||
[[nodiscard]] auto get1CC() const -> bool { return game_completed_ && credits_used_ == 1; }
|
[[nodiscard]] auto get1CC() const -> bool { return game_completed_ && credits_used_ <= 1; }
|
||||||
[[nodiscard]] auto getEnterNamePositionOverflow() const -> bool { return enter_name_ ? enter_name_->getPositionOverflow() : false; }
|
[[nodiscard]] auto getEnterNamePositionOverflow() const -> bool { return enter_name_ ? enter_name_->getPositionOverflow() : false; }
|
||||||
|
|
||||||
// Setters inline
|
// Setters inline
|
||||||
void setController(int index) { controller_index_ = index; }
|
void setController(int index) { controller_index_ = index; }
|
||||||
void setCantFireCounter(int counter) { recoiling_state_duration_ = cant_fire_counter_ = counter; }
|
void startFiringSystem(int cooldown_frames); // Método público para iniciar disparo
|
||||||
void setFiringState(State state) { firing_state_ = state; }
|
void setFiringState(State state) { firing_state_ = state; }
|
||||||
void setInvulnerableCounter(int value) { invulnerable_counter_ = value; }
|
void setInvulnerableCounter(int value) { invulnerable_counter_ = value; }
|
||||||
void setName(const std::string &name) { name_ = name; }
|
void setName(const std::string &name) { name_ = name; }
|
||||||
@@ -186,21 +199,34 @@ class Player {
|
|||||||
void setWalkingState(State state) { walking_state_ = state; }
|
void setWalkingState(State state) { walking_state_ = state; }
|
||||||
|
|
||||||
void addCredit();
|
void addCredit();
|
||||||
|
void passShowingName();
|
||||||
void setGamepad(std::shared_ptr<Input::Gamepad> gamepad) { gamepad_ = std::move(gamepad); }
|
void setGamepad(std::shared_ptr<Input::Gamepad> gamepad) { gamepad_ = std::move(gamepad); }
|
||||||
[[nodiscard]] auto getGamepad() const -> std::shared_ptr<Input::Gamepad> { return gamepad_; }
|
[[nodiscard]] auto getGamepad() const -> std::shared_ptr<Input::Gamepad> { return gamepad_; }
|
||||||
void setUsesKeyboard(bool value) { uses_keyboard_ = value; }
|
void setUsesKeyboard(bool value) { uses_keyboard_ = value; }
|
||||||
[[nodiscard]] auto getUsesKeyboard() const -> bool { return uses_keyboard_; }
|
[[nodiscard]] auto getUsesKeyboard() const -> bool { return uses_keyboard_; }
|
||||||
|
|
||||||
private:
|
private:
|
||||||
// --- Constantes ---
|
// --- Constantes de física y movimiento ---
|
||||||
static constexpr int POWERUP_COUNTER = 1500; // Duración del estado PowerUp
|
static constexpr float BASE_SPEED = 90.0f; // Velocidad base del jugador (pixels/segundo)
|
||||||
static constexpr int INVULNERABLE_COUNTER = 200; // Duración del estado invulnerable
|
|
||||||
|
// --- Constantes de power-ups y estados especiales ---
|
||||||
|
static constexpr int POWERUP_COUNTER = 1500; // Duración del estado PowerUp (frames)
|
||||||
|
static constexpr int INVULNERABLE_COUNTER = 200; // Duración del estado invulnerable (frames)
|
||||||
static constexpr size_t INVULNERABLE_TEXTURE = 3; // Textura usada durante invulnerabilidad
|
static constexpr size_t INVULNERABLE_TEXTURE = 3; // Textura usada durante invulnerabilidad
|
||||||
static constexpr float BASE_SPEED = 1.5F; // Velocidad base del jugador
|
|
||||||
|
// --- Constantes del sistema de disparo (obsoletas - usar nuevo sistema) ---
|
||||||
static constexpr int COOLING_DURATION = 50; // Duración del enfriamiento tras disparar
|
static constexpr int COOLING_DURATION = 50; // Duración del enfriamiento tras disparar
|
||||||
static constexpr int COOLING_COMPLETE = 0; // Valor que indica enfriamiento completado
|
static constexpr int COOLING_COMPLETE = 0; // Valor que indica enfriamiento completado
|
||||||
|
|
||||||
|
// --- Constantes de estados de espera ---
|
||||||
static constexpr int WAITING_COUNTER = 1000; // Tiempo de espera en estado de espera
|
static constexpr int WAITING_COUNTER = 1000; // Tiempo de espera en estado de espera
|
||||||
|
|
||||||
|
// --- Constantes del nuevo sistema de disparo de dos líneas ---
|
||||||
|
static constexpr float AIMING_DURATION_FACTOR = 0.5f; // 50% del cooldown funcional
|
||||||
|
static constexpr float RECOILING_DURATION_MULTIPLIER = 4.0f; // 4 veces la duración de aiming
|
||||||
|
static constexpr float THREAT_POSE_DURATION = 50.0f / 60.0f; // 50 frames = ~0.833s (duración base)
|
||||||
|
static constexpr float MIN_THREAT_POSE_DURATION = 6.0f / 60.0f; // 6 frames = ~0.1s (duración mínima)
|
||||||
|
|
||||||
// --- Objetos y punteros ---
|
// --- Objetos y punteros ---
|
||||||
std::unique_ptr<AnimatedSprite> player_sprite_; // Sprite para dibujar el jugador
|
std::unique_ptr<AnimatedSprite> player_sprite_; // Sprite para dibujar el jugador
|
||||||
std::unique_ptr<AnimatedSprite> power_sprite_; // Sprite para dibujar el aura del jugador con el poder a tope
|
std::unique_ptr<AnimatedSprite> power_sprite_; // Sprite para dibujar el aura del jugador con el poder a tope
|
||||||
@@ -221,9 +247,6 @@ class Player {
|
|||||||
State firing_state_ = State::FIRING_NONE; // Estado del jugador al disparar
|
State firing_state_ = State::FIRING_NONE; // Estado del jugador al disparar
|
||||||
State playing_state_ = State::WAITING; // Estado del jugador en el juego
|
State playing_state_ = State::WAITING; // Estado del jugador en el juego
|
||||||
|
|
||||||
Uint32 continue_ticks_ = 0; // Variable para poder cambiar el contador de continue en función del tiempo
|
|
||||||
Uint32 name_entry_ticks_ = 0; // Variable para poder cambiar el contador de poner nombre en función del tiempo
|
|
||||||
Uint32 showing_name_ticks_ = 0; // Tiempo en el que se entra al estado SHOWING_NAME
|
|
||||||
float pos_x_ = 0.0F; // Posición en el eje X
|
float pos_x_ = 0.0F; // Posición en el eje X
|
||||||
float default_pos_x_; // Posición inicial para el jugador
|
float default_pos_x_; // Posición inicial para el jugador
|
||||||
float vel_x_ = 0.0F; // Cantidad de píxeles a desplazarse en el eje X
|
float vel_x_ = 0.0F; // Cantidad de píxeles a desplazarse en el eje X
|
||||||
@@ -231,10 +254,36 @@ class Player {
|
|||||||
int pos_y_ = 0; // Posición en el eje Y
|
int pos_y_ = 0; // Posición en el eje Y
|
||||||
int default_pos_y_; // Posición inicial para el jugador
|
int default_pos_y_; // Posición inicial para el jugador
|
||||||
int vel_y_ = 0; // Cantidad de píxeles a desplazarse en el eje Y
|
int vel_y_ = 0; // Cantidad de píxeles a desplazarse en el eje Y
|
||||||
int cant_fire_counter_ = 0; // Contador durante el cual no puede disparar
|
float invulnerable_time_accumulator_ = 0.0f; // Acumulador de tiempo para invulnerabilidad (time-based)
|
||||||
int recoiling_state_counter_ = 0; // Contador para la animación del estado de retroceso
|
float power_up_time_accumulator_ = 0.0f; // Acumulador de tiempo para power-up (time-based)
|
||||||
int recoiling_state_duration_ = 0; // Número de frames que dura el estado de retroceso
|
float continue_time_accumulator_ = 0.0f; // Acumulador de tiempo para continue counter (time-based)
|
||||||
int cooling_state_counter_ = 0; // Contador para la animación del estado cooling
|
float name_entry_time_accumulator_ = 0.0f; // Acumulador de tiempo para name entry counter (time-based)
|
||||||
|
float showing_name_time_accumulator_ = 0.0f; // Acumulador de tiempo para showing name (time-based)
|
||||||
|
float waiting_time_accumulator_ = 0.0f; // Acumulador de tiempo para waiting movement (time-based)
|
||||||
|
float step_time_accumulator_ = 0.0f; // Acumulador de tiempo para step counter (time-based)
|
||||||
|
|
||||||
|
// ========================================
|
||||||
|
// NUEVO SISTEMA DE DISPARO DE DOS LÍNEAS
|
||||||
|
// ========================================
|
||||||
|
|
||||||
|
// LÍNEA 1: SISTEMA FUNCIONAL (CanFire)
|
||||||
|
float fire_cooldown_timer_ = 0.0f; // Tiempo restante hasta poder disparar otra vez
|
||||||
|
bool can_fire_new_system_ = true; // true si puede disparar ahora mismo
|
||||||
|
|
||||||
|
// LÍNEA 2: SISTEMA VISUAL (Animaciones)
|
||||||
|
enum class VisualFireState {
|
||||||
|
NORMAL, // Brazo en posición neutral
|
||||||
|
AIMING, // Brazo alzado (disparando)
|
||||||
|
RECOILING, // Brazo en retroceso
|
||||||
|
THREAT_POSE // Posición amenazante
|
||||||
|
};
|
||||||
|
|
||||||
|
VisualFireState visual_fire_state_ = VisualFireState::NORMAL;
|
||||||
|
float visual_state_timer_ = 0.0f; // Tiempo en el estado visual actual
|
||||||
|
float aiming_duration_ = 0.0f; // Duración del estado AIMING
|
||||||
|
float recoiling_duration_ = 0.0f; // Duración del estado RECOILING
|
||||||
|
|
||||||
|
|
||||||
int invulnerable_counter_ = INVULNERABLE_COUNTER; // Contador para la invulnerabilidad
|
int invulnerable_counter_ = INVULNERABLE_COUNTER; // Contador para la invulnerabilidad
|
||||||
int score_ = 0; // Puntos del jugador
|
int score_ = 0; // Puntos del jugador
|
||||||
int coffees_ = 0; // Indica cuántos cafés lleva acumulados
|
int coffees_ = 0; // Indica cuántos cafés lleva acumulados
|
||||||
@@ -242,8 +291,8 @@ class Player {
|
|||||||
int power_up_x_offset_ = 0; // Desplazamiento del sprite de PowerUp respecto al sprite del jugador
|
int power_up_x_offset_ = 0; // Desplazamiento del sprite de PowerUp respecto al sprite del jugador
|
||||||
int continue_counter_ = 10; // Contador para poder continuar
|
int continue_counter_ = 10; // Contador para poder continuar
|
||||||
int controller_index_ = 0; // Índice del array de mandos que utilizará para moverse
|
int controller_index_ = 0; // Índice del array de mandos que utilizará para moverse
|
||||||
int name_entry_idle_counter_ = 0; // Contador para poner nombre
|
float name_entry_idle_time_accumulator_ = 0.0f; // Tiempo idle acumulado para poner nombre (milisegundos)
|
||||||
int name_entry_total_counter_ = 0; // Segundos totales que lleva acumulados poniendo nombre
|
float name_entry_total_time_accumulator_ = 0.0f; // Tiempo total acumulado poniendo nombre (milisegundos)
|
||||||
int step_counter_ = 0; // Cuenta los pasos para los estados en los que camina automáticamente
|
int step_counter_ = 0; // Cuenta los pasos para los estados en los que camina automáticamente
|
||||||
int credits_used_ = 0; // Indica el número de veces que ha continuado
|
int credits_used_ = 0; // Indica el número de veces que ha continuado
|
||||||
int waiting_counter_ = 0; // Contador para el estado de espera
|
int waiting_counter_ = 0; // Contador para el estado de espera
|
||||||
@@ -258,41 +307,60 @@ class Player {
|
|||||||
// --- Métodos internos ---
|
// --- Métodos internos ---
|
||||||
void shiftColliders(); // Actualiza el círculo de colisión a la posición del jugador
|
void shiftColliders(); // Actualiza el círculo de colisión a la posición del jugador
|
||||||
void shiftSprite(); // Recoloca el sprite
|
void shiftSprite(); // Recoloca el sprite
|
||||||
void updateInvulnerable(); // Monitoriza el estado de invulnerabilidad
|
void updateInvulnerable(float deltaTime); // Monitoriza el estado de invulnerabilidad (time-based)
|
||||||
void updateContinueCounter(); // Actualiza el contador de continue
|
void updateContinueCounter(float deltaTime); // Actualiza el contador de continue (time-based)
|
||||||
void updateEnterNameCounter(); // Actualiza el contador de entrar nombre
|
void updateEnterNameCounter(float deltaTime); // Actualiza el contador de entrar nombre (time-based)
|
||||||
void updateShowingName(); // Actualiza el estado SHOWING_NAME
|
void updateShowingName(float deltaTime); // Actualiza el estado SHOWING_NAME (time-based)
|
||||||
void decNameEntryCounter(); // Decrementa el contador de entrar nombre
|
void decNameEntryCounter(); // Decrementa el contador de entrar nombre
|
||||||
void updateScoreboard(); // Actualiza el panel del marcador
|
void updateScoreboard(); // Actualiza el panel del marcador
|
||||||
void setScoreboardMode(Scoreboard::Mode mode) const; // Cambia el modo del marcador
|
void setScoreboardMode(Scoreboard::Mode mode) const; // Cambia el modo del marcador
|
||||||
void playSound(const std::string &name) const; // Hace sonar un sonido
|
void playSound(const std::string &name) const; // Hace sonar un sonido
|
||||||
[[nodiscard]] auto isRenderable() const -> bool; // Indica si se puede dibujar el objeto
|
[[nodiscard]] auto isRenderable() const -> bool; // Indica si se puede dibujar el objeto
|
||||||
void addScoreToScoreBoard() const; // Añade una puntuación a la tabla de records
|
void addScoreToScoreBoard() const; // Añade una puntuación a la tabla de records
|
||||||
void handleFiringCooldown(); // Gestiona el tiempo de espera después de disparar antes de permitir otro disparo
|
|
||||||
void handleRecoilAndCooling(); // Procesa simultáneamente el retroceso del arma y la transición al estado de enfriamiento si aplica
|
// --- Métodos del sistema de disparo de dos líneas ---
|
||||||
void handleCoolingState(); // Actualiza la lógica interna mientras el sistema está en estado de enfriamiento
|
void updateFireSystem(float deltaTime); // Método principal del nuevo sistema de disparo
|
||||||
void transitionToRecoiling(); // Cambia el estado actual al de retroceso después de disparar
|
void updateFunctionalLine(float deltaTime); // Actualiza la línea funcional (CanFire)
|
||||||
void transitionToCooling(); // Cambia el estado actual al de enfriamiento (por ejemplo, tras una ráfaga o sobrecalentamiento)
|
void updateVisualLine(float deltaTime); // Actualiza la línea visual (Animaciones)
|
||||||
void completeCooling(); // Finaliza el proceso de enfriamiento y restablece el estado listo para disparar
|
void startFiring(int cooldown_frames); // Inicia un nuevo disparo en ambas líneas
|
||||||
void handlePlayingMovement(); // Gestiona el movimiento del personaje u objeto durante el estado de juego activo
|
void updateFiringStateFromVisual(); // Sincroniza firing_state_ con visual_fire_state_
|
||||||
|
void transitionToRecoilingNew(); // Transición AIMING → RECOILING
|
||||||
|
void transitionToThreatPose(); // Transición RECOILING → THREAT_POSE
|
||||||
|
void transitionToNormalNew(); // Transición THREAT_POSE → NORMAL
|
||||||
|
|
||||||
|
// --- Métodos del sistema de disparo obsoleto ---
|
||||||
|
void handleFiringCooldown(); // Gestiona el tiempo de espera después de disparar (frame-based)
|
||||||
|
void handleFiringCooldown(float deltaTime); // Gestiona el tiempo de espera después de disparar (time-based)
|
||||||
|
void handleRecoilAndCooling(); // Procesa retroceso y enfriamiento (frame-based)
|
||||||
|
void handleRecoilAndCooling(float deltaTime); // Procesa retroceso y enfriamiento (time-based)
|
||||||
|
void handleCoolingState(); // Actualiza estado de enfriamiento (frame-based)
|
||||||
|
void handleCoolingState(float deltaTime); // Actualiza estado de enfriamiento (time-based)
|
||||||
|
void transitionToRecoiling(); // Transición a retroceso (sistema obsoleto)
|
||||||
|
void transitionToCooling(); // Transición a enfriamiento (sistema obsoleto)
|
||||||
|
void completeCooling(); // Finaliza enfriamiento (sistema obsoleto)
|
||||||
|
void handlePlayingMovement(); // Gestiona el movimiento del personaje u objeto durante el estado de juego activo (frame-based)
|
||||||
|
void handlePlayingMovement(float deltaTime); // Gestiona el movimiento del personaje u objeto durante el estado de juego activo (time-based)
|
||||||
void handleRecoverMovement(); // Comprueba si ha acabado la animación
|
void handleRecoverMovement(); // Comprueba si ha acabado la animación
|
||||||
void handleRollingMovement(); // Actualiza la lógica de movimiento de "rodar" (posiblemente tras impacto o acción especial)
|
void handleRollingMovement(); // Actualiza la lógica de movimiento de "rodar" (posiblemente tras impacto o acción especial)
|
||||||
void handleRollingBoundaryCollision(); // Detecta y maneja colisiones del objeto rodante con los límites de la pantalla
|
void handleRollingBoundaryCollision(); // Detecta y maneja colisiones del objeto rodante con los límites de la pantalla
|
||||||
void handleRollingGroundCollision(); // Gestiona la interacción del objeto rodante con el suelo (rebotes, frenado, etc.)
|
void handleRollingGroundCollision(); // Gestiona la interacción del objeto rodante con el suelo (rebotes, frenado, etc.)
|
||||||
void handleRollingStop(); // Detiene el movimiento del objeto rodante cuando se cumplen las condiciones necesarias
|
void handleRollingStop(); // Detiene el movimiento del objeto rodante cuando se cumplen las condiciones necesarias
|
||||||
void handleRollingBounce(); // Aplica una lógica de rebote al colisionar con superficies durante el rodamiento
|
void handleRollingBounce(); // Aplica una lógica de rebote al colisionar con superficies durante el rodamiento
|
||||||
void handleTitleAnimation(); // Ejecuta la animación del título en pantalla (ej. entrada, parpadeo o desplazamiento)
|
void handleTitleAnimation(float deltaTime); // Ejecuta la animación del título en pantalla (ej. entrada, parpadeo o desplazamiento)
|
||||||
void handleContinueTimeOut(); // Gestiona el tiempo de espera en la pantalla de "Continuar" y decide si pasar a otro estado
|
void handleContinueTimeOut(); // Gestiona el tiempo de espera en la pantalla de "Continuar" y decide si pasar a otro estado
|
||||||
void handleLeavingScreen(); // Lógica para salir de la pantalla actual (transición visual o cambio de escena)
|
void handleLeavingScreen(float deltaTime); // Lógica para salir de la pantalla actual (transición visual o cambio de escena)
|
||||||
void handleEnteringScreen(); // Lógica para entrar en una nueva pantalla, posiblemente con animación o retraso
|
void handleEnteringScreen(float deltaTime); // Lógica para entrar en una nueva pantalla, posiblemente con animación o retraso
|
||||||
void handlePlayer1Entering(); // Controla la animación o posición de entrada del Jugador 1 en pantalla
|
void handlePlayer1Entering(float deltaTime); // Controla la animación o posición de entrada del Jugador 1 en pantalla
|
||||||
void handlePlayer2Entering(); // Controla la animación o posición de entrada del Jugador 2 en pantalla
|
void handlePlayer2Entering(float deltaTime); // Controla la animación o posición de entrada del Jugador 2 en pantalla
|
||||||
void handleCreditsMovement(); // Movimiento general en la pantalla de créditos (desplazamiento vertical u horizontal)
|
void handleCreditsMovement(); // Movimiento general en la pantalla de créditos (frame-based)
|
||||||
|
void handleCreditsMovement(float deltaTime); // Movimiento general en la pantalla de créditos (time-based)
|
||||||
void handleCreditsRightMovement(); // Lógica específica para mover los créditos hacia la derecha
|
void handleCreditsRightMovement(); // Lógica específica para mover los créditos hacia la derecha
|
||||||
void handleCreditsLeftMovement(); // Lógica específica para mover los créditos hacia la izquierda
|
void handleCreditsLeftMovement(); // Lógica específica para mover los créditos hacia la izquierda
|
||||||
void handleWaitingMovement(); // Controla la animación del jugador saludando
|
void handleWaitingMovement(); // Controla la animación del jugador saludando (frame-based)
|
||||||
|
void handleWaitingMovement(float deltaTime); // Controla la animación del jugador saludando (time-based)
|
||||||
void updateWalkingStateForCredits(); // Actualiza el estado de caminata de algún personaje u elemento animado en los créditos
|
void updateWalkingStateForCredits(); // Actualiza el estado de caminata de algún personaje u elemento animado en los créditos
|
||||||
void setInputBasedOnPlayerId(); // Asocia las entradas de control en función del identificador del jugador (teclas, mando, etc.)
|
void setInputBasedOnPlayerId(); // Asocia las entradas de control en función del identificador del jugador (teclas, mando, etc.)
|
||||||
void updateStepCounter(); // Incrementa o ajusta el contador de pasos para animaciones o mecánicas relacionadas con movimiento
|
void updateStepCounter(); // Incrementa o ajusta el contador de pasos (frame-based)
|
||||||
|
void updateStepCounter(float deltaTime); // Incrementa o ajusta el contador de pasos (time-based)
|
||||||
[[nodiscard]] auto computeAnimation() const -> std::pair<std::string, SDL_FlipMode>; // Calcula la animacion de moverse y disparar del jugador
|
[[nodiscard]] auto computeAnimation() const -> std::pair<std::string, SDL_FlipMode>; // Calcula la animacion de moverse y disparar del jugador
|
||||||
};
|
};
|
||||||
@@ -2,57 +2,57 @@
|
|||||||
|
|
||||||
#include <SDL3/SDL.h> // Para SDL_LogInfo, SDL_LogCategory, SDL_LogError, SDL_SetRenderDrawColor, SDL_EventType, SDL_PollEvent, SDL_RenderFillRect, SDL_RenderRect, SDLK_ESCAPE, SDL_Event
|
#include <SDL3/SDL.h> // Para SDL_LogInfo, SDL_LogCategory, SDL_LogError, SDL_SetRenderDrawColor, SDL_EventType, SDL_PollEvent, SDL_RenderFillRect, SDL_RenderRect, SDLK_ESCAPE, SDL_Event
|
||||||
|
|
||||||
#include <algorithm> // Para find_if, max, find
|
#include <algorithm> // Para find_if, max, find
|
||||||
#include <array> // Para array
|
#include <array> // Para array
|
||||||
#include <cstdlib> // Para exit, getenv
|
#include <cstdlib> // Para exit, getenv
|
||||||
#include <filesystem> // Para filesystem::remove, filesystem::exists
|
#include <filesystem> // Para filesystem::remove, filesystem::exists
|
||||||
#include <fstream> // Para ofstream
|
#include <fstream> // Para ofstream
|
||||||
#include <stdexcept> // Para runtime_error
|
#include <stdexcept> // Para runtime_error
|
||||||
#include <utility> // Para move
|
#include <utility> // Para move
|
||||||
|
|
||||||
#include "asset.h" // Para Asset
|
#include "asset.h" // Para Asset
|
||||||
#include "color.h" // Para Color
|
#include "color.h" // Para Color
|
||||||
#ifndef NO_AUDIO
|
#ifndef NO_AUDIO
|
||||||
#include "external/jail_audio.h" // Para JA_LoadMusic, JA_LoadSound, JA_DeleteMusic, JA_DeleteSound
|
#include "external/jail_audio.h" // Para JA_LoadMusic, JA_LoadSound, JA_DeleteMusic, JA_DeleteSound
|
||||||
#endif
|
#endif
|
||||||
#include "lang.h" // Para getText
|
#include "lang.h" // Para getText
|
||||||
#include "param.h" // Para Param, param, ParamResource, ParamGame
|
#include "param.h" // Para Param, param, ParamResource, ParamGame
|
||||||
#include "screen.h" // Para Screen
|
|
||||||
#include "text.h" // Para Text
|
|
||||||
#include "resource_helper.h" // Para ResourceHelper
|
#include "resource_helper.h" // Para ResourceHelper
|
||||||
|
#include "screen.h" // Para Screen
|
||||||
|
#include "text.h" // Para Text
|
||||||
|
|
||||||
struct JA_Music_t; // lines 11-11
|
struct JA_Music_t; // lines 11-11
|
||||||
struct JA_Sound_t; // lines 12-12
|
struct JA_Sound_t; // lines 12-12
|
||||||
|
|
||||||
// Helper para cargar archivos de audio desde pack o filesystem
|
// Helper para cargar archivos de audio desde pack o filesystem
|
||||||
namespace {
|
namespace {
|
||||||
std::string createTempAudioFile(const std::string& file_path, std::vector<std::string>& temp_files_tracker) {
|
std::string createTempAudioFile(const std::string &file_path, std::vector<std::string> &temp_files_tracker) {
|
||||||
auto resource_data = ResourceHelper::loadFile(file_path);
|
auto resource_data = ResourceHelper::loadFile(file_path);
|
||||||
if (!resource_data.empty()) {
|
if (!resource_data.empty()) {
|
||||||
// Crear archivo temporal
|
// Crear archivo temporal
|
||||||
std::string temp_dir;
|
std::string temp_dir;
|
||||||
#ifdef _WIN32
|
#ifdef _WIN32
|
||||||
temp_dir = std::getenv("TEMP") ? std::getenv("TEMP") : "C:\\temp";
|
temp_dir = std::getenv("TEMP") ? std::getenv("TEMP") : "C:\\temp";
|
||||||
#else
|
#else
|
||||||
temp_dir = "/tmp";
|
temp_dir = "/tmp";
|
||||||
#endif
|
#endif
|
||||||
std::string temp_path = temp_dir + "/ccae_audio_" + std::to_string(std::hash<std::string>{}(file_path));
|
std::string temp_path = temp_dir + "/ccae_audio_" + std::to_string(std::hash<std::string>{}(file_path));
|
||||||
std::ofstream temp_file(temp_path, std::ios::binary);
|
std::ofstream temp_file(temp_path, std::ios::binary);
|
||||||
if (!temp_file) {
|
if (!temp_file) {
|
||||||
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Cannot create temp file %s", temp_path.c_str());
|
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Cannot create temp file %s", temp_path.c_str());
|
||||||
return file_path;
|
return file_path;
|
||||||
}
|
|
||||||
temp_file.write(reinterpret_cast<const char*>(resource_data.data()), resource_data.size());
|
|
||||||
temp_file.close();
|
|
||||||
|
|
||||||
// Agregar a la lista de archivos temporales para limpieza posterior
|
|
||||||
temp_files_tracker.push_back(temp_path);
|
|
||||||
|
|
||||||
return temp_path;
|
|
||||||
}
|
}
|
||||||
return file_path; // Usar ruta original si no está en pack
|
temp_file.write(reinterpret_cast<const char *>(resource_data.data()), resource_data.size());
|
||||||
|
temp_file.close();
|
||||||
|
|
||||||
|
// Agregar a la lista de archivos temporales para limpieza posterior
|
||||||
|
temp_files_tracker.push_back(temp_path);
|
||||||
|
|
||||||
|
return temp_path;
|
||||||
}
|
}
|
||||||
|
return file_path; // Usar ruta original si no está en pack
|
||||||
}
|
}
|
||||||
|
} // namespace
|
||||||
|
|
||||||
// Declaraciones de funciones que necesitas implementar en otros archivos
|
// Declaraciones de funciones que necesitas implementar en otros archivos
|
||||||
|
|
||||||
@@ -75,7 +75,8 @@ auto Resource::get() -> Resource * { return Resource::instance; }
|
|||||||
|
|
||||||
// Constructor con modo de carga
|
// Constructor con modo de carga
|
||||||
Resource::Resource(LoadingMode mode)
|
Resource::Resource(LoadingMode mode)
|
||||||
: loading_mode_(mode), loading_text_(nullptr) {
|
: loading_mode_(mode),
|
||||||
|
loading_text_(nullptr) {
|
||||||
if (loading_mode_ == LoadingMode::PRELOAD) {
|
if (loading_mode_ == LoadingMode::PRELOAD) {
|
||||||
loading_text_ = Screen::get()->getText();
|
loading_text_ = Screen::get()->getText();
|
||||||
load();
|
load();
|
||||||
@@ -649,7 +650,8 @@ void Resource::createTextTextures() {
|
|||||||
std::string text;
|
std::string text;
|
||||||
|
|
||||||
NameAndText(std::string name_init, std::string text_init)
|
NameAndText(std::string name_init, std::string text_init)
|
||||||
: name(std::move(name_init)), text(std::move(text_init)) {}
|
: name(std::move(name_init)),
|
||||||
|
text(std::move(text_init)) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n>> CREATING TEXTURES");
|
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n>> CREATING TEXTURES");
|
||||||
@@ -661,7 +663,8 @@ void Resource::createTextTextures() {
|
|||||||
{"game_text_5000_points", "5.000"},
|
{"game_text_5000_points", "5.000"},
|
||||||
{"game_text_powerup", Lang::getText("[GAME_TEXT] 4")},
|
{"game_text_powerup", Lang::getText("[GAME_TEXT] 4")},
|
||||||
{"game_text_one_hit", Lang::getText("[GAME_TEXT] 5")},
|
{"game_text_one_hit", Lang::getText("[GAME_TEXT] 5")},
|
||||||
{"game_text_stop", Lang::getText("[GAME_TEXT] 6")}};
|
{"game_text_stop", Lang::getText("[GAME_TEXT] 6")},
|
||||||
|
{"game_text_1000000_points", Lang::getText("[GAME_TEXT] 8")}};
|
||||||
|
|
||||||
auto text1 = getText("04b_25_enhanced");
|
auto text1 = getText("04b_25_enhanced");
|
||||||
for (const auto &s : strings1) {
|
for (const auto &s : strings1) {
|
||||||
@@ -669,27 +672,17 @@ void Resource::createTextTextures() {
|
|||||||
printWithDots("Texture : ", s.name, "[ DONE ]");
|
printWithDots("Texture : ", s.name, "[ DONE ]");
|
||||||
}
|
}
|
||||||
|
|
||||||
// Texturas de tamaño normal
|
|
||||||
std::vector<NameAndText> strings2 = {
|
|
||||||
{"game_text_1000000_points", Lang::getText("[GAME_TEXT] 8")}};
|
|
||||||
|
|
||||||
auto text2 = getText("04b_25");
|
|
||||||
for (const auto &s : strings2) {
|
|
||||||
textures_.emplace_back(s.name, text2->writeDXToTexture(Text::STROKE, s.text, -2, Colors::NO_COLOR_MOD, 1, param.game.item_text_outline_color));
|
|
||||||
printWithDots("Texture : ", s.name, "[ DONE ]");
|
|
||||||
}
|
|
||||||
|
|
||||||
// Texturas de tamaño doble
|
// Texturas de tamaño doble
|
||||||
std::vector<NameAndText> strings3 = {
|
std::vector<NameAndText> strings2 = {
|
||||||
{"game_text_100000_points", "100.000"},
|
{"game_text_100000_points", "100.000"},
|
||||||
{"game_text_get_ready", Lang::getText("[GAME_TEXT] 7")},
|
{"game_text_get_ready", Lang::getText("[GAME_TEXT] 7")},
|
||||||
{"game_text_last_stage", Lang::getText("[GAME_TEXT] 3")},
|
{"game_text_last_stage", Lang::getText("[GAME_TEXT] 3")},
|
||||||
{"game_text_congratulations", Lang::getText("[GAME_TEXT] 1")},
|
{"game_text_congratulations", Lang::getText("[GAME_TEXT] 1")},
|
||||||
{"game_text_game_over", "Game Over"}};
|
{"game_text_game_over", "Game Over"}};
|
||||||
|
|
||||||
auto text3 = getText("04b_25_2x");
|
auto text2 = getText("04b_25_2x_enhanced");
|
||||||
for (const auto &s : strings3) {
|
for (const auto &s : strings2) {
|
||||||
textures_.emplace_back(s.name, text3->writeToTexture(s.text, 1, -4));
|
textures_.emplace_back(s.name, text2->writeDXToTexture(Text::STROKE, s.text, -4, Colors::NO_COLOR_MOD, 1, param.game.item_text_outline_color));
|
||||||
printWithDots("Texture : ", s.name, "[ DONE ]");
|
printWithDots("Texture : ", s.name, "[ DONE ]");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -703,7 +696,10 @@ void Resource::createText() {
|
|||||||
std::string white_texture_file; // Textura blanca opcional
|
std::string white_texture_file; // Textura blanca opcional
|
||||||
|
|
||||||
ResourceInfo(std::string k, std::string t_file, std::string txt_file, std::string w_file = "")
|
ResourceInfo(std::string k, std::string t_file, std::string txt_file, std::string w_file = "")
|
||||||
: key(std::move(k)), texture_file(std::move(t_file)), text_file(std::move(txt_file)), white_texture_file(std::move(w_file)) {}
|
: key(std::move(k)),
|
||||||
|
texture_file(std::move(t_file)),
|
||||||
|
text_file(std::move(txt_file)),
|
||||||
|
white_texture_file(std::move(w_file)) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n>> CREATING TEXT OBJECTS");
|
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n>> CREATING TEXT OBJECTS");
|
||||||
@@ -713,6 +709,7 @@ void Resource::createText() {
|
|||||||
{"04b_25_enhanced", "04b_25.png", "04b_25.txt", "04b_25_white.png"}, // Nueva fuente con textura blanca
|
{"04b_25_enhanced", "04b_25.png", "04b_25.txt", "04b_25_white.png"}, // Nueva fuente con textura blanca
|
||||||
{"04b_25_white", "04b_25_white.png", "04b_25.txt"},
|
{"04b_25_white", "04b_25_white.png", "04b_25.txt"},
|
||||||
{"04b_25_2x", "04b_25_2x.png", "04b_25_2x.txt"},
|
{"04b_25_2x", "04b_25_2x.png", "04b_25_2x.txt"},
|
||||||
|
{"04b_25_2x_enhanced", "04b_25_2x.png", "04b_25_2x.txt", "04b_25_2x_white.png"}, // Nueva fuente con textura blanca
|
||||||
{"04b_25_metal", "04b_25_metal.png", "04b_25.txt"},
|
{"04b_25_metal", "04b_25_metal.png", "04b_25.txt"},
|
||||||
{"04b_25_grey", "04b_25_grey.png", "04b_25.txt"},
|
{"04b_25_grey", "04b_25_grey.png", "04b_25.txt"},
|
||||||
{"04b_25_flat", "04b_25_flat.png", "04b_25.txt"},
|
{"04b_25_flat", "04b_25_flat.png", "04b_25.txt"},
|
||||||
@@ -874,13 +871,13 @@ void Resource::updateProgressBar() {
|
|||||||
|
|
||||||
// Limpia archivos temporales de audio
|
// Limpia archivos temporales de audio
|
||||||
void Resource::cleanupTempAudioFiles() {
|
void Resource::cleanupTempAudioFiles() {
|
||||||
for (const auto& temp_path : temp_audio_files_) {
|
for (const auto &temp_path : temp_audio_files_) {
|
||||||
try {
|
try {
|
||||||
if (std::filesystem::exists(temp_path)) {
|
if (std::filesystem::exists(temp_path)) {
|
||||||
std::filesystem::remove(temp_path);
|
std::filesystem::remove(temp_path);
|
||||||
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Removed temp audio file: %s", temp_path.c_str());
|
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Removed temp audio file: %s", temp_path.c_str());
|
||||||
}
|
}
|
||||||
} catch (const std::exception& e) {
|
} catch (const std::exception &e) {
|
||||||
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to remove temp audio file %s: %s", temp_path.c_str(), e.what());
|
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to remove temp audio file %s: %s", temp_path.c_str(), e.what());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -52,7 +52,8 @@ class Resource {
|
|||||||
JA_Sound_t *sound; // Objeto con el sonido
|
JA_Sound_t *sound; // Objeto con el sonido
|
||||||
|
|
||||||
ResourceSound(std::string name, JA_Sound_t *sound = nullptr)
|
ResourceSound(std::string name, JA_Sound_t *sound = nullptr)
|
||||||
: name(std::move(name)), sound(sound) {}
|
: name(std::move(name)),
|
||||||
|
sound(sound) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
struct ResourceMusic {
|
struct ResourceMusic {
|
||||||
@@ -60,7 +61,8 @@ class Resource {
|
|||||||
JA_Music_t *music; // Objeto con la música
|
JA_Music_t *music; // Objeto con la música
|
||||||
|
|
||||||
ResourceMusic(std::string name, JA_Music_t *music = nullptr)
|
ResourceMusic(std::string name, JA_Music_t *music = nullptr)
|
||||||
: name(std::move(name)), music(music) {}
|
: name(std::move(name)),
|
||||||
|
music(music) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
struct ResourceTexture {
|
struct ResourceTexture {
|
||||||
@@ -68,7 +70,8 @@ class Resource {
|
|||||||
std::shared_ptr<Texture> texture; // Objeto con la textura
|
std::shared_ptr<Texture> texture; // Objeto con la textura
|
||||||
|
|
||||||
ResourceTexture(std::string name, std::shared_ptr<Texture> texture = nullptr)
|
ResourceTexture(std::string name, std::shared_ptr<Texture> texture = nullptr)
|
||||||
: name(std::move(name)), texture(std::move(texture)) {}
|
: name(std::move(name)),
|
||||||
|
texture(std::move(texture)) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
struct ResourceTextFile {
|
struct ResourceTextFile {
|
||||||
@@ -76,7 +79,8 @@ class Resource {
|
|||||||
std::shared_ptr<Text::File> text_file; // Objeto con los descriptores de la fuente de texto
|
std::shared_ptr<Text::File> text_file; // Objeto con los descriptores de la fuente de texto
|
||||||
|
|
||||||
ResourceTextFile(std::string name, std::shared_ptr<Text::File> text_file = nullptr)
|
ResourceTextFile(std::string name, std::shared_ptr<Text::File> text_file = nullptr)
|
||||||
: name(std::move(name)), text_file(std::move(text_file)) {}
|
: name(std::move(name)),
|
||||||
|
text_file(std::move(text_file)) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
struct ResourceText {
|
struct ResourceText {
|
||||||
@@ -84,7 +88,8 @@ class Resource {
|
|||||||
std::shared_ptr<Text> text; // Objeto de texto
|
std::shared_ptr<Text> text; // Objeto de texto
|
||||||
|
|
||||||
ResourceText(std::string name, std::shared_ptr<Text> text = nullptr)
|
ResourceText(std::string name, std::shared_ptr<Text> text = nullptr)
|
||||||
: name(std::move(name)), text(std::move(text)) {}
|
: name(std::move(name)),
|
||||||
|
text(std::move(text)) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
struct ResourceAnimation {
|
struct ResourceAnimation {
|
||||||
@@ -92,7 +97,8 @@ class Resource {
|
|||||||
AnimationsFileBuffer animation; // Objeto con las animaciones
|
AnimationsFileBuffer animation; // Objeto con las animaciones
|
||||||
|
|
||||||
ResourceAnimation(std::string name, AnimationsFileBuffer animation = {})
|
ResourceAnimation(std::string name, AnimationsFileBuffer animation = {})
|
||||||
: name(std::move(name)), animation(std::move(animation)) {}
|
: name(std::move(name)),
|
||||||
|
animation(std::move(animation)) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
// --- Estructura para el progreso de carga ---
|
// --- Estructura para el progreso de carga ---
|
||||||
@@ -100,8 +106,12 @@ class Resource {
|
|||||||
size_t total; // Número total de recursos
|
size_t total; // Número total de recursos
|
||||||
size_t loaded; // Número de recursos cargados
|
size_t loaded; // Número de recursos cargados
|
||||||
|
|
||||||
ResourceCount() : total(0), loaded(0) {}
|
ResourceCount()
|
||||||
ResourceCount(size_t total) : total(total), loaded(0) {}
|
: total(0),
|
||||||
|
loaded(0) {}
|
||||||
|
ResourceCount(size_t total)
|
||||||
|
: total(total),
|
||||||
|
loaded(0) {}
|
||||||
|
|
||||||
void add(size_t amount) { loaded += amount; }
|
void add(size_t amount) { loaded += amount; }
|
||||||
void increase() { loaded++; }
|
void increase() { loaded++; }
|
||||||
@@ -128,7 +138,7 @@ class Resource {
|
|||||||
std::string loading_resource_name_; // Nombre del recurso que se está cargando
|
std::string loading_resource_name_; // Nombre del recurso que se está cargando
|
||||||
SDL_FRect loading_wired_rect_;
|
SDL_FRect loading_wired_rect_;
|
||||||
SDL_FRect loading_full_rect_;
|
SDL_FRect loading_full_rect_;
|
||||||
|
|
||||||
// --- Archivos temporales ---
|
// --- Archivos temporales ---
|
||||||
std::vector<std::string> temp_audio_files_; // Rutas de archivos temporales de audio para limpieza
|
std::vector<std::string> temp_audio_files_; // Rutas de archivos temporales de audio para limpieza
|
||||||
|
|
||||||
|
|||||||
@@ -1,95 +1,96 @@
|
|||||||
#include "resource_helper.h"
|
#include "resource_helper.h"
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
#include <filesystem>
|
#include <filesystem>
|
||||||
#include <fstream>
|
#include <fstream>
|
||||||
#include <iostream>
|
#include <iostream>
|
||||||
#include <algorithm>
|
|
||||||
|
|
||||||
namespace ResourceHelper {
|
namespace ResourceHelper {
|
||||||
static bool resource_system_initialized = false;
|
static bool resource_system_initialized = false;
|
||||||
|
|
||||||
bool initializeResourceSystem(const std::string& pack_file) {
|
bool initializeResourceSystem(const std::string& pack_file) {
|
||||||
|
auto& loader = ResourceLoader::getInstance();
|
||||||
|
resource_system_initialized = loader.initialize(pack_file, true);
|
||||||
|
|
||||||
|
if (resource_system_initialized) {
|
||||||
|
std::cout << "Resource system initialized with pack: " << pack_file << std::endl;
|
||||||
|
} else {
|
||||||
|
std::cout << "Resource system using fallback mode (filesystem only)" << std::endl;
|
||||||
|
}
|
||||||
|
|
||||||
|
return true; // Always return true as fallback is acceptable
|
||||||
|
}
|
||||||
|
|
||||||
|
void shutdownResourceSystem() {
|
||||||
|
if (resource_system_initialized) {
|
||||||
|
ResourceLoader::getInstance().shutdown();
|
||||||
|
resource_system_initialized = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<uint8_t> loadFile(const std::string& filepath) {
|
||||||
|
if (resource_system_initialized && shouldUseResourcePack(filepath)) {
|
||||||
auto& loader = ResourceLoader::getInstance();
|
auto& loader = ResourceLoader::getInstance();
|
||||||
resource_system_initialized = loader.initialize(pack_file, true);
|
std::string pack_path = getPackPath(filepath);
|
||||||
|
|
||||||
if (resource_system_initialized) {
|
auto data = loader.loadResource(pack_path);
|
||||||
std::cout << "Resource system initialized with pack: " << pack_file << std::endl;
|
if (!data.empty()) {
|
||||||
} else {
|
return data;
|
||||||
std::cout << "Resource system using fallback mode (filesystem only)" << std::endl;
|
|
||||||
}
|
|
||||||
|
|
||||||
return true; // Always return true as fallback is acceptable
|
|
||||||
}
|
|
||||||
|
|
||||||
void shutdownResourceSystem() {
|
|
||||||
if (resource_system_initialized) {
|
|
||||||
ResourceLoader::getInstance().shutdown();
|
|
||||||
resource_system_initialized = false;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
std::vector<uint8_t> loadFile(const std::string& filepath) {
|
// Fallback a filesystem
|
||||||
if (resource_system_initialized && shouldUseResourcePack(filepath)) {
|
std::ifstream file(filepath, std::ios::binary | std::ios::ate);
|
||||||
auto& loader = ResourceLoader::getInstance();
|
if (!file) {
|
||||||
std::string pack_path = getPackPath(filepath);
|
return {};
|
||||||
|
|
||||||
auto data = loader.loadResource(pack_path);
|
|
||||||
if (!data.empty()) {
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fallback a filesystem
|
|
||||||
std::ifstream file(filepath, std::ios::binary | std::ios::ate);
|
|
||||||
if (!file) {
|
|
||||||
return {};
|
|
||||||
}
|
|
||||||
|
|
||||||
std::streamsize fileSize = file.tellg();
|
|
||||||
file.seekg(0, std::ios::beg);
|
|
||||||
|
|
||||||
std::vector<uint8_t> data(fileSize);
|
|
||||||
if (!file.read(reinterpret_cast<char*>(data.data()), fileSize)) {
|
|
||||||
return {};
|
|
||||||
}
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
bool shouldUseResourcePack(const std::string& filepath) {
|
std::streamsize fileSize = file.tellg();
|
||||||
// Archivos que NO van al pack:
|
file.seekg(0, std::ios::beg);
|
||||||
// - config/ (ahora está fuera de data/)
|
|
||||||
// - archivos absolutos del sistema
|
std::vector<uint8_t> data(fileSize);
|
||||||
|
if (!file.read(reinterpret_cast<char*>(data.data()), fileSize)) {
|
||||||
if (filepath.find("config/") != std::string::npos) {
|
return {};
|
||||||
return false;
|
}
|
||||||
}
|
|
||||||
|
return data;
|
||||||
// Si contiene "data/" es candidato para el pack
|
}
|
||||||
if (filepath.find("data/") != std::string::npos) {
|
|
||||||
return true;
|
bool shouldUseResourcePack(const std::string& filepath) {
|
||||||
}
|
// Archivos que NO van al pack:
|
||||||
|
// - config/ (ahora está fuera de data/)
|
||||||
|
// - archivos absolutos del sistema
|
||||||
|
|
||||||
|
if (filepath.find("config/") != std::string::npos) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
std::string getPackPath(const std::string& asset_path) {
|
// Si contiene "data/" es candidato para el pack
|
||||||
std::string pack_path = asset_path;
|
if (filepath.find("data/") != std::string::npos) {
|
||||||
|
return true;
|
||||||
// Normalizar separadores de path a '/'
|
|
||||||
std::replace(pack_path.begin(), pack_path.end(), '\\', '/');
|
|
||||||
|
|
||||||
// Remover prefijo "data/" si existe
|
|
||||||
size_t data_pos = pack_path.find("data/");
|
|
||||||
if (data_pos != std::string::npos) {
|
|
||||||
pack_path = pack_path.substr(data_pos + 5); // +5 para saltar "data/"
|
|
||||||
}
|
|
||||||
|
|
||||||
// Remover cualquier prefijo de path absoluto
|
|
||||||
size_t last_data = pack_path.rfind("data/");
|
|
||||||
if (last_data != std::string::npos) {
|
|
||||||
pack_path = pack_path.substr(last_data + 5);
|
|
||||||
}
|
|
||||||
|
|
||||||
return pack_path;
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string getPackPath(const std::string& asset_path) {
|
||||||
|
std::string pack_path = asset_path;
|
||||||
|
|
||||||
|
// Normalizar separadores de path a '/'
|
||||||
|
std::replace(pack_path.begin(), pack_path.end(), '\\', '/');
|
||||||
|
|
||||||
|
// Remover prefijo "data/" si existe
|
||||||
|
size_t data_pos = pack_path.find("data/");
|
||||||
|
if (data_pos != std::string::npos) {
|
||||||
|
pack_path = pack_path.substr(data_pos + 5); // +5 para saltar "data/"
|
||||||
|
}
|
||||||
|
|
||||||
|
// Remover cualquier prefijo de path absoluto
|
||||||
|
size_t last_data = pack_path.rfind("data/");
|
||||||
|
if (last_data != std::string::npos) {
|
||||||
|
pack_path = pack_path.substr(last_data + 5);
|
||||||
|
}
|
||||||
|
|
||||||
|
return pack_path;
|
||||||
|
}
|
||||||
|
} // namespace ResourceHelper
|
||||||
@@ -1,46 +1,47 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include "resource_loader.h"
|
|
||||||
#include <string>
|
|
||||||
#include <vector>
|
|
||||||
#include <memory>
|
|
||||||
#include <filesystem>
|
#include <filesystem>
|
||||||
#include <fstream>
|
#include <fstream>
|
||||||
|
#include <memory>
|
||||||
|
#include <string>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
#include "resource_loader.h"
|
||||||
|
|
||||||
// Helper functions para integrar ResourceLoader con el sistema existente
|
// Helper functions para integrar ResourceLoader con el sistema existente
|
||||||
namespace ResourceHelper {
|
namespace ResourceHelper {
|
||||||
// Inicializa ResourceLoader (llamar al inicio del programa)
|
// Inicializa ResourceLoader (llamar al inicio del programa)
|
||||||
bool initializeResourceSystem(const std::string& pack_file = "resources.pack");
|
bool initializeResourceSystem(const std::string& pack_file = "resources.pack");
|
||||||
|
|
||||||
// Cierra ResourceLoader
|
// Cierra ResourceLoader
|
||||||
void shutdownResourceSystem();
|
void shutdownResourceSystem();
|
||||||
|
|
||||||
// Carga un archivo usando ResourceLoader o fallback a filesystem
|
// Carga un archivo usando ResourceLoader o fallback a filesystem
|
||||||
std::vector<uint8_t> loadFile(const std::string& filepath);
|
std::vector<uint8_t> loadFile(const std::string& filepath);
|
||||||
|
|
||||||
// Verifica si un archivo debería cargarse del pack vs filesystem
|
// Verifica si un archivo debería cargarse del pack vs filesystem
|
||||||
bool shouldUseResourcePack(const std::string& filepath);
|
bool shouldUseResourcePack(const std::string& filepath);
|
||||||
|
|
||||||
// Convierte ruta Asset a ruta relativa para ResourceLoader
|
// Convierte ruta Asset a ruta relativa para ResourceLoader
|
||||||
std::string getPackPath(const std::string& asset_path);
|
std::string getPackPath(const std::string& asset_path);
|
||||||
|
|
||||||
// Wrappea la carga de archivos para mantener compatibilidad
|
// Wrappea la carga de archivos para mantener compatibilidad
|
||||||
template<typename T>
|
template <typename T>
|
||||||
T* loadResourceFile(const std::string& asset_path, T* (*loader_func)(const char*)) {
|
T* loadResourceFile(const std::string& asset_path, T* (*loader_func)(const char*)) {
|
||||||
auto data = loadFile(asset_path);
|
auto data = loadFile(asset_path);
|
||||||
if (data.empty()) {
|
if (data.empty()) {
|
||||||
return loader_func(asset_path.c_str());
|
return loader_func(asset_path.c_str());
|
||||||
}
|
|
||||||
|
|
||||||
// Crear archivo temporal para funciones que esperan path
|
|
||||||
std::string temp_path = "/tmp/ccae_" + std::to_string(std::hash<std::string>{}(asset_path));
|
|
||||||
std::ofstream temp_file(temp_path, std::ios::binary);
|
|
||||||
temp_file.write(reinterpret_cast<const char*>(data.data()), data.size());
|
|
||||||
temp_file.close();
|
|
||||||
|
|
||||||
T* result = loader_func(temp_path.c_str());
|
|
||||||
std::filesystem::remove(temp_path);
|
|
||||||
|
|
||||||
return result;
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
// Crear archivo temporal para funciones que esperan path
|
||||||
|
std::string temp_path = "/tmp/ccae_" + std::to_string(std::hash<std::string>{}(asset_path));
|
||||||
|
std::ofstream temp_file(temp_path, std::ios::binary);
|
||||||
|
temp_file.write(reinterpret_cast<const char*>(data.data()), data.size());
|
||||||
|
temp_file.close();
|
||||||
|
|
||||||
|
T* result = loader_func(temp_path.c_str());
|
||||||
|
std::filesystem::remove(temp_path);
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
} // namespace ResourceHelper
|
||||||
@@ -1,13 +1,15 @@
|
|||||||
#include "resource_loader.h"
|
#include "resource_loader.h"
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <filesystem>
|
||||||
#include <fstream>
|
#include <fstream>
|
||||||
#include <iostream>
|
#include <iostream>
|
||||||
#include <filesystem>
|
|
||||||
#include <algorithm>
|
|
||||||
|
|
||||||
std::unique_ptr<ResourceLoader> ResourceLoader::instance = nullptr;
|
std::unique_ptr<ResourceLoader> ResourceLoader::instance = nullptr;
|
||||||
|
|
||||||
ResourceLoader::ResourceLoader()
|
ResourceLoader::ResourceLoader()
|
||||||
: resourcePack(nullptr), fallbackToFiles(true) {}
|
: resourcePack(nullptr),
|
||||||
|
fallbackToFiles(true) {}
|
||||||
|
|
||||||
ResourceLoader& ResourceLoader::getInstance() {
|
ResourceLoader& ResourceLoader::getInstance() {
|
||||||
if (!instance) {
|
if (!instance) {
|
||||||
@@ -22,10 +24,10 @@ ResourceLoader::~ResourceLoader() {
|
|||||||
|
|
||||||
bool ResourceLoader::initialize(const std::string& packFile, bool enableFallback) {
|
bool ResourceLoader::initialize(const std::string& packFile, bool enableFallback) {
|
||||||
shutdown();
|
shutdown();
|
||||||
|
|
||||||
fallbackToFiles = enableFallback;
|
fallbackToFiles = enableFallback;
|
||||||
packPath = packFile;
|
packPath = packFile;
|
||||||
|
|
||||||
if (std::filesystem::exists(packFile)) {
|
if (std::filesystem::exists(packFile)) {
|
||||||
resourcePack = new ResourcePack();
|
resourcePack = new ResourcePack();
|
||||||
if (resourcePack->loadPack(packFile)) {
|
if (resourcePack->loadPack(packFile)) {
|
||||||
@@ -38,12 +40,12 @@ bool ResourceLoader::initialize(const std::string& packFile, bool enableFallback
|
|||||||
std::cerr << "Failed to load resource pack: " << packFile << std::endl;
|
std::cerr << "Failed to load resource pack: " << packFile << std::endl;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (fallbackToFiles) {
|
if (fallbackToFiles) {
|
||||||
std::cout << "Using fallback mode: loading resources from data/ directory" << std::endl;
|
std::cout << "Using fallback mode: loading resources from data/ directory" << std::endl;
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
std::cerr << "Resource pack not found and fallback disabled: " << packFile << std::endl;
|
std::cerr << "Resource pack not found and fallback disabled: " << packFile << std::endl;
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -59,11 +61,11 @@ std::vector<uint8_t> ResourceLoader::loadResource(const std::string& filename) {
|
|||||||
if (resourcePack && resourcePack->hasResource(filename)) {
|
if (resourcePack && resourcePack->hasResource(filename)) {
|
||||||
return resourcePack->getResource(filename);
|
return resourcePack->getResource(filename);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (fallbackToFiles) {
|
if (fallbackToFiles) {
|
||||||
return loadFromFile(filename);
|
return loadFromFile(filename);
|
||||||
}
|
}
|
||||||
|
|
||||||
std::cerr << "Resource not found: " << filename << std::endl;
|
std::cerr << "Resource not found: " << filename << std::endl;
|
||||||
return {};
|
return {};
|
||||||
}
|
}
|
||||||
@@ -72,33 +74,33 @@ bool ResourceLoader::resourceExists(const std::string& filename) {
|
|||||||
if (resourcePack && resourcePack->hasResource(filename)) {
|
if (resourcePack && resourcePack->hasResource(filename)) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (fallbackToFiles) {
|
if (fallbackToFiles) {
|
||||||
std::string fullPath = getDataPath(filename);
|
std::string fullPath = getDataPath(filename);
|
||||||
return std::filesystem::exists(fullPath);
|
return std::filesystem::exists(fullPath);
|
||||||
}
|
}
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
std::vector<uint8_t> ResourceLoader::loadFromFile(const std::string& filename) {
|
std::vector<uint8_t> ResourceLoader::loadFromFile(const std::string& filename) {
|
||||||
std::string fullPath = getDataPath(filename);
|
std::string fullPath = getDataPath(filename);
|
||||||
|
|
||||||
std::ifstream file(fullPath, std::ios::binary | std::ios::ate);
|
std::ifstream file(fullPath, std::ios::binary | std::ios::ate);
|
||||||
if (!file) {
|
if (!file) {
|
||||||
std::cerr << "Error: Could not open file: " << fullPath << std::endl;
|
std::cerr << "Error: Could not open file: " << fullPath << std::endl;
|
||||||
return {};
|
return {};
|
||||||
}
|
}
|
||||||
|
|
||||||
std::streamsize fileSize = file.tellg();
|
std::streamsize fileSize = file.tellg();
|
||||||
file.seekg(0, std::ios::beg);
|
file.seekg(0, std::ios::beg);
|
||||||
|
|
||||||
std::vector<uint8_t> data(fileSize);
|
std::vector<uint8_t> data(fileSize);
|
||||||
if (!file.read(reinterpret_cast<char*>(data.data()), fileSize)) {
|
if (!file.read(reinterpret_cast<char*>(data.data()), fileSize)) {
|
||||||
std::cerr << "Error: Could not read file: " << fullPath << std::endl;
|
std::cerr << "Error: Could not read file: " << fullPath << std::endl;
|
||||||
return {};
|
return {};
|
||||||
}
|
}
|
||||||
|
|
||||||
return data;
|
return data;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -117,7 +119,7 @@ std::vector<std::string> ResourceLoader::getAvailableResources() const {
|
|||||||
if (resourcePack) {
|
if (resourcePack) {
|
||||||
return resourcePack->getResourceList();
|
return resourcePack->getResourceList();
|
||||||
}
|
}
|
||||||
|
|
||||||
std::vector<std::string> result;
|
std::vector<std::string> result;
|
||||||
if (fallbackToFiles && std::filesystem::exists("data")) {
|
if (fallbackToFiles && std::filesystem::exists("data")) {
|
||||||
for (const auto& entry : std::filesystem::recursive_directory_iterator("data")) {
|
for (const auto& entry : std::filesystem::recursive_directory_iterator("data")) {
|
||||||
@@ -128,6 +130,6 @@ std::vector<std::string> ResourceLoader::getAvailableResources() const {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
@@ -1,37 +1,38 @@
|
|||||||
#ifndef RESOURCE_LOADER_H
|
#ifndef RESOURCE_LOADER_H
|
||||||
#define RESOURCE_LOADER_H
|
#define RESOURCE_LOADER_H
|
||||||
|
|
||||||
#include "resource_pack.h"
|
|
||||||
#include <memory>
|
#include <memory>
|
||||||
|
|
||||||
|
#include "resource_pack.h"
|
||||||
|
|
||||||
class ResourceLoader {
|
class ResourceLoader {
|
||||||
private:
|
private:
|
||||||
static std::unique_ptr<ResourceLoader> instance;
|
static std::unique_ptr<ResourceLoader> instance;
|
||||||
ResourcePack* resourcePack;
|
ResourcePack* resourcePack;
|
||||||
std::string packPath;
|
std::string packPath;
|
||||||
bool fallbackToFiles;
|
bool fallbackToFiles;
|
||||||
|
|
||||||
ResourceLoader();
|
ResourceLoader();
|
||||||
|
|
||||||
public:
|
public:
|
||||||
static ResourceLoader& getInstance();
|
static ResourceLoader& getInstance();
|
||||||
~ResourceLoader();
|
~ResourceLoader();
|
||||||
|
|
||||||
bool initialize(const std::string& packFile, bool enableFallback = true);
|
|
||||||
void shutdown();
|
|
||||||
|
|
||||||
std::vector<uint8_t> loadResource(const std::string& filename);
|
|
||||||
bool resourceExists(const std::string& filename);
|
|
||||||
|
|
||||||
void setFallbackToFiles(bool enable) { fallbackToFiles = enable; }
|
|
||||||
bool getFallbackToFiles() const { return fallbackToFiles; }
|
|
||||||
|
|
||||||
size_t getLoadedResourceCount() const;
|
|
||||||
std::vector<std::string> getAvailableResources() const;
|
|
||||||
|
|
||||||
private:
|
bool initialize(const std::string& packFile, bool enableFallback = true);
|
||||||
std::vector<uint8_t> loadFromFile(const std::string& filename);
|
void shutdown();
|
||||||
std::string getDataPath(const std::string& filename);
|
|
||||||
|
std::vector<uint8_t> loadResource(const std::string& filename);
|
||||||
|
bool resourceExists(const std::string& filename);
|
||||||
|
|
||||||
|
void setFallbackToFiles(bool enable) { fallbackToFiles = enable; }
|
||||||
|
bool getFallbackToFiles() const { return fallbackToFiles; }
|
||||||
|
|
||||||
|
size_t getLoadedResourceCount() const;
|
||||||
|
std::vector<std::string> getAvailableResources() const;
|
||||||
|
|
||||||
|
private:
|
||||||
|
std::vector<uint8_t> loadFromFile(const std::string& filename);
|
||||||
|
std::string getDataPath(const std::string& filename);
|
||||||
};
|
};
|
||||||
|
|
||||||
#endif
|
#endif
|
||||||
@@ -1,12 +1,14 @@
|
|||||||
#include "resource_pack.h"
|
#include "resource_pack.h"
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <filesystem>
|
||||||
#include <fstream>
|
#include <fstream>
|
||||||
#include <iostream>
|
#include <iostream>
|
||||||
#include <filesystem>
|
|
||||||
#include <algorithm>
|
|
||||||
|
|
||||||
const std::string ResourcePack::DEFAULT_ENCRYPT_KEY = "CCAE_RESOURCES_2024";
|
const std::string ResourcePack::DEFAULT_ENCRYPT_KEY = "CCAE_RESOURCES_2024";
|
||||||
|
|
||||||
ResourcePack::ResourcePack() : loaded(false) {}
|
ResourcePack::ResourcePack()
|
||||||
|
: loaded(false) {}
|
||||||
|
|
||||||
ResourcePack::~ResourcePack() {
|
ResourcePack::~ResourcePack() {
|
||||||
clear();
|
clear();
|
||||||
@@ -22,7 +24,7 @@ uint32_t ResourcePack::calculateChecksum(const std::vector<uint8_t>& data) {
|
|||||||
|
|
||||||
void ResourcePack::encryptData(std::vector<uint8_t>& data, const std::string& key) {
|
void ResourcePack::encryptData(std::vector<uint8_t>& data, const std::string& key) {
|
||||||
if (key.empty()) return;
|
if (key.empty()) return;
|
||||||
|
|
||||||
for (size_t i = 0; i < data.size(); ++i) {
|
for (size_t i = 0; i < data.size(); ++i) {
|
||||||
data[i] ^= key[i % key.length()];
|
data[i] ^= key[i % key.length()];
|
||||||
}
|
}
|
||||||
@@ -38,51 +40,51 @@ bool ResourcePack::loadPack(const std::string& packFile) {
|
|||||||
std::cerr << "Error: Could not open pack file: " << packFile << std::endl;
|
std::cerr << "Error: Could not open pack file: " << packFile << std::endl;
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
char header[4];
|
char header[4];
|
||||||
file.read(header, 4);
|
file.read(header, 4);
|
||||||
if (std::string(header, 4) != "CCAE") {
|
if (std::string(header, 4) != "CCAE") {
|
||||||
std::cerr << "Error: Invalid pack file format" << std::endl;
|
std::cerr << "Error: Invalid pack file format" << std::endl;
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
uint32_t version;
|
uint32_t version;
|
||||||
file.read(reinterpret_cast<char*>(&version), sizeof(version));
|
file.read(reinterpret_cast<char*>(&version), sizeof(version));
|
||||||
if (version != 1) {
|
if (version != 1) {
|
||||||
std::cerr << "Error: Unsupported pack version: " << version << std::endl;
|
std::cerr << "Error: Unsupported pack version: " << version << std::endl;
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
uint32_t resourceCount;
|
uint32_t resourceCount;
|
||||||
file.read(reinterpret_cast<char*>(&resourceCount), sizeof(resourceCount));
|
file.read(reinterpret_cast<char*>(&resourceCount), sizeof(resourceCount));
|
||||||
|
|
||||||
resources.clear();
|
resources.clear();
|
||||||
resources.reserve(resourceCount);
|
resources.reserve(resourceCount);
|
||||||
|
|
||||||
for (uint32_t i = 0; i < resourceCount; ++i) {
|
for (uint32_t i = 0; i < resourceCount; ++i) {
|
||||||
uint32_t filenameLength;
|
uint32_t filenameLength;
|
||||||
file.read(reinterpret_cast<char*>(&filenameLength), sizeof(filenameLength));
|
file.read(reinterpret_cast<char*>(&filenameLength), sizeof(filenameLength));
|
||||||
|
|
||||||
std::string filename(filenameLength, '\0');
|
std::string filename(filenameLength, '\0');
|
||||||
file.read(&filename[0], filenameLength);
|
file.read(&filename[0], filenameLength);
|
||||||
|
|
||||||
ResourceEntry entry;
|
ResourceEntry entry;
|
||||||
entry.filename = filename;
|
entry.filename = filename;
|
||||||
file.read(reinterpret_cast<char*>(&entry.offset), sizeof(entry.offset));
|
file.read(reinterpret_cast<char*>(&entry.offset), sizeof(entry.offset));
|
||||||
file.read(reinterpret_cast<char*>(&entry.size), sizeof(entry.size));
|
file.read(reinterpret_cast<char*>(&entry.size), sizeof(entry.size));
|
||||||
file.read(reinterpret_cast<char*>(&entry.checksum), sizeof(entry.checksum));
|
file.read(reinterpret_cast<char*>(&entry.checksum), sizeof(entry.checksum));
|
||||||
|
|
||||||
resources[filename] = entry;
|
resources[filename] = entry;
|
||||||
}
|
}
|
||||||
|
|
||||||
uint64_t dataSize;
|
uint64_t dataSize;
|
||||||
file.read(reinterpret_cast<char*>(&dataSize), sizeof(dataSize));
|
file.read(reinterpret_cast<char*>(&dataSize), sizeof(dataSize));
|
||||||
|
|
||||||
data.resize(dataSize);
|
data.resize(dataSize);
|
||||||
file.read(reinterpret_cast<char*>(data.data()), dataSize);
|
file.read(reinterpret_cast<char*>(data.data()), dataSize);
|
||||||
|
|
||||||
decryptData(data, DEFAULT_ENCRYPT_KEY);
|
decryptData(data, DEFAULT_ENCRYPT_KEY);
|
||||||
|
|
||||||
loaded = true;
|
loaded = true;
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@@ -93,32 +95,32 @@ bool ResourcePack::savePack(const std::string& packFile) {
|
|||||||
std::cerr << "Error: Could not create pack file: " << packFile << std::endl;
|
std::cerr << "Error: Could not create pack file: " << packFile << std::endl;
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
file.write("CCAE", 4);
|
file.write("CCAE", 4);
|
||||||
|
|
||||||
uint32_t version = 1;
|
uint32_t version = 1;
|
||||||
file.write(reinterpret_cast<const char*>(&version), sizeof(version));
|
file.write(reinterpret_cast<const char*>(&version), sizeof(version));
|
||||||
|
|
||||||
uint32_t resourceCount = static_cast<uint32_t>(resources.size());
|
uint32_t resourceCount = static_cast<uint32_t>(resources.size());
|
||||||
file.write(reinterpret_cast<const char*>(&resourceCount), sizeof(resourceCount));
|
file.write(reinterpret_cast<const char*>(&resourceCount), sizeof(resourceCount));
|
||||||
|
|
||||||
for (const auto& [filename, entry] : resources) {
|
for (const auto& [filename, entry] : resources) {
|
||||||
uint32_t filenameLength = static_cast<uint32_t>(filename.length());
|
uint32_t filenameLength = static_cast<uint32_t>(filename.length());
|
||||||
file.write(reinterpret_cast<const char*>(&filenameLength), sizeof(filenameLength));
|
file.write(reinterpret_cast<const char*>(&filenameLength), sizeof(filenameLength));
|
||||||
file.write(filename.c_str(), filenameLength);
|
file.write(filename.c_str(), filenameLength);
|
||||||
|
|
||||||
file.write(reinterpret_cast<const char*>(&entry.offset), sizeof(entry.offset));
|
file.write(reinterpret_cast<const char*>(&entry.offset), sizeof(entry.offset));
|
||||||
file.write(reinterpret_cast<const char*>(&entry.size), sizeof(entry.size));
|
file.write(reinterpret_cast<const char*>(&entry.size), sizeof(entry.size));
|
||||||
file.write(reinterpret_cast<const char*>(&entry.checksum), sizeof(entry.checksum));
|
file.write(reinterpret_cast<const char*>(&entry.checksum), sizeof(entry.checksum));
|
||||||
}
|
}
|
||||||
|
|
||||||
std::vector<uint8_t> encryptedData = data;
|
std::vector<uint8_t> encryptedData = data;
|
||||||
encryptData(encryptedData, DEFAULT_ENCRYPT_KEY);
|
encryptData(encryptedData, DEFAULT_ENCRYPT_KEY);
|
||||||
|
|
||||||
uint64_t dataSize = encryptedData.size();
|
uint64_t dataSize = encryptedData.size();
|
||||||
file.write(reinterpret_cast<const char*>(&dataSize), sizeof(dataSize));
|
file.write(reinterpret_cast<const char*>(&dataSize), sizeof(dataSize));
|
||||||
file.write(reinterpret_cast<const char*>(encryptedData.data()), dataSize);
|
file.write(reinterpret_cast<const char*>(encryptedData.data()), dataSize);
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -128,25 +130,25 @@ bool ResourcePack::addFile(const std::string& filename, const std::string& filep
|
|||||||
std::cerr << "Error: Could not open file: " << filepath << std::endl;
|
std::cerr << "Error: Could not open file: " << filepath << std::endl;
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
std::streamsize fileSize = file.tellg();
|
std::streamsize fileSize = file.tellg();
|
||||||
file.seekg(0, std::ios::beg);
|
file.seekg(0, std::ios::beg);
|
||||||
|
|
||||||
std::vector<uint8_t> fileData(fileSize);
|
std::vector<uint8_t> fileData(fileSize);
|
||||||
if (!file.read(reinterpret_cast<char*>(fileData.data()), fileSize)) {
|
if (!file.read(reinterpret_cast<char*>(fileData.data()), fileSize)) {
|
||||||
std::cerr << "Error: Could not read file: " << filepath << std::endl;
|
std::cerr << "Error: Could not read file: " << filepath << std::endl;
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
ResourceEntry entry;
|
ResourceEntry entry;
|
||||||
entry.filename = filename;
|
entry.filename = filename;
|
||||||
entry.offset = data.size();
|
entry.offset = data.size();
|
||||||
entry.size = fileData.size();
|
entry.size = fileData.size();
|
||||||
entry.checksum = calculateChecksum(fileData);
|
entry.checksum = calculateChecksum(fileData);
|
||||||
|
|
||||||
data.insert(data.end(), fileData.begin(), fileData.end());
|
data.insert(data.end(), fileData.begin(), fileData.end());
|
||||||
resources[filename] = entry;
|
resources[filename] = entry;
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -155,20 +157,20 @@ bool ResourcePack::addDirectory(const std::string& directory) {
|
|||||||
std::cerr << "Error: Directory does not exist: " << directory << std::endl;
|
std::cerr << "Error: Directory does not exist: " << directory << std::endl;
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
for (const auto& entry : std::filesystem::recursive_directory_iterator(directory)) {
|
for (const auto& entry : std::filesystem::recursive_directory_iterator(directory)) {
|
||||||
if (entry.is_regular_file()) {
|
if (entry.is_regular_file()) {
|
||||||
std::string filepath = entry.path().string();
|
std::string filepath = entry.path().string();
|
||||||
std::string filename = std::filesystem::relative(entry.path(), directory).string();
|
std::string filename = std::filesystem::relative(entry.path(), directory).string();
|
||||||
|
|
||||||
std::replace(filename.begin(), filename.end(), '\\', '/');
|
std::replace(filename.begin(), filename.end(), '\\', '/');
|
||||||
|
|
||||||
if (!addFile(filename, filepath)) {
|
if (!addFile(filename, filepath)) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -178,21 +180,21 @@ std::vector<uint8_t> ResourcePack::getResource(const std::string& filename) {
|
|||||||
std::cerr << "Error: Resource not found: " << filename << std::endl;
|
std::cerr << "Error: Resource not found: " << filename << std::endl;
|
||||||
return {};
|
return {};
|
||||||
}
|
}
|
||||||
|
|
||||||
const ResourceEntry& entry = it->second;
|
const ResourceEntry& entry = it->second;
|
||||||
if (entry.offset + entry.size > data.size()) {
|
if (entry.offset + entry.size > data.size()) {
|
||||||
std::cerr << "Error: Invalid resource data: " << filename << std::endl;
|
std::cerr << "Error: Invalid resource data: " << filename << std::endl;
|
||||||
return {};
|
return {};
|
||||||
}
|
}
|
||||||
|
|
||||||
std::vector<uint8_t> result(data.begin() + entry.offset,
|
std::vector<uint8_t> result(data.begin() + entry.offset,
|
||||||
data.begin() + entry.offset + entry.size);
|
data.begin() + entry.offset + entry.size);
|
||||||
|
|
||||||
uint32_t checksum = calculateChecksum(result);
|
uint32_t checksum = calculateChecksum(result);
|
||||||
if (checksum != entry.checksum) {
|
if (checksum != entry.checksum) {
|
||||||
std::cerr << "Warning: Checksum mismatch for resource: " << filename << std::endl;
|
std::cerr << "Warning: Checksum mismatch for resource: " << filename << std::endl;
|
||||||
}
|
}
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -213,10 +215,10 @@ size_t ResourcePack::getResourceCount() const {
|
|||||||
std::vector<std::string> ResourcePack::getResourceList() const {
|
std::vector<std::string> ResourcePack::getResourceList() const {
|
||||||
std::vector<std::string> result;
|
std::vector<std::string> result;
|
||||||
result.reserve(resources.size());
|
result.reserve(resources.size());
|
||||||
|
|
||||||
for (const auto& [filename, entry] : resources) {
|
for (const auto& [filename, entry] : resources) {
|
||||||
result.push_back(filename);
|
result.push_back(filename);
|
||||||
}
|
}
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
@@ -1,46 +1,46 @@
|
|||||||
#ifndef RESOURCE_PACK_H
|
#ifndef RESOURCE_PACK_H
|
||||||
#define RESOURCE_PACK_H
|
#define RESOURCE_PACK_H
|
||||||
|
|
||||||
|
#include <cstdint>
|
||||||
#include <string>
|
#include <string>
|
||||||
#include <unordered_map>
|
#include <unordered_map>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
#include <cstdint>
|
|
||||||
|
|
||||||
struct ResourceEntry {
|
struct ResourceEntry {
|
||||||
std::string filename;
|
std::string filename;
|
||||||
uint64_t offset;
|
uint64_t offset;
|
||||||
uint64_t size;
|
uint64_t size;
|
||||||
uint32_t checksum;
|
uint32_t checksum;
|
||||||
};
|
};
|
||||||
|
|
||||||
class ResourcePack {
|
class ResourcePack {
|
||||||
private:
|
private:
|
||||||
std::unordered_map<std::string, ResourceEntry> resources;
|
std::unordered_map<std::string, ResourceEntry> resources;
|
||||||
std::vector<uint8_t> data;
|
std::vector<uint8_t> data;
|
||||||
bool loaded;
|
bool loaded;
|
||||||
|
|
||||||
uint32_t calculateChecksum(const std::vector<uint8_t>& data);
|
|
||||||
void encryptData(std::vector<uint8_t>& data, const std::string& key);
|
|
||||||
void decryptData(std::vector<uint8_t>& data, const std::string& key);
|
|
||||||
|
|
||||||
public:
|
uint32_t calculateChecksum(const std::vector<uint8_t>& data);
|
||||||
ResourcePack();
|
void encryptData(std::vector<uint8_t>& data, const std::string& key);
|
||||||
~ResourcePack();
|
void decryptData(std::vector<uint8_t>& data, const std::string& key);
|
||||||
|
|
||||||
bool loadPack(const std::string& packFile);
|
public:
|
||||||
bool savePack(const std::string& packFile);
|
ResourcePack();
|
||||||
|
~ResourcePack();
|
||||||
bool addFile(const std::string& filename, const std::string& filepath);
|
|
||||||
bool addDirectory(const std::string& directory);
|
bool loadPack(const std::string& packFile);
|
||||||
|
bool savePack(const std::string& packFile);
|
||||||
std::vector<uint8_t> getResource(const std::string& filename);
|
|
||||||
bool hasResource(const std::string& filename) const;
|
bool addFile(const std::string& filename, const std::string& filepath);
|
||||||
|
bool addDirectory(const std::string& directory);
|
||||||
void clear();
|
|
||||||
size_t getResourceCount() const;
|
std::vector<uint8_t> getResource(const std::string& filename);
|
||||||
std::vector<std::string> getResourceList() const;
|
bool hasResource(const std::string& filename) const;
|
||||||
|
|
||||||
static const std::string DEFAULT_ENCRYPT_KEY;
|
void clear();
|
||||||
|
size_t getResourceCount() const;
|
||||||
|
std::vector<std::string> getResourceList() const;
|
||||||
|
|
||||||
|
static const std::string DEFAULT_ENCRYPT_KEY;
|
||||||
};
|
};
|
||||||
|
|
||||||
#endif
|
#endif
|
||||||
@@ -40,7 +40,8 @@ Scoreboard::Scoreboard()
|
|||||||
: renderer_(Screen::get()->getRenderer()),
|
: renderer_(Screen::get()->getRenderer()),
|
||||||
game_power_meter_texture_(Resource::get()->getTexture("game_power_meter.png")),
|
game_power_meter_texture_(Resource::get()->getTexture("game_power_meter.png")),
|
||||||
power_meter_sprite_(std::make_unique<Sprite>(game_power_meter_texture_)),
|
power_meter_sprite_(std::make_unique<Sprite>(game_power_meter_texture_)),
|
||||||
text_scoreboard_(Resource::get()->getText("8bithud")) {
|
text_(Resource::get()->getText("8bithud")),
|
||||||
|
enter_name_text_(Resource::get()->getText("smb2")) {
|
||||||
// Inicializa variables
|
// Inicializa variables
|
||||||
for (size_t i = 0; i < static_cast<size_t>(Id::SIZE); ++i) {
|
for (size_t i = 0; i < static_cast<size_t>(Id::SIZE); ++i) {
|
||||||
name_.at(i).clear();
|
name_.at(i).clear();
|
||||||
@@ -198,50 +199,50 @@ void Scoreboard::renderPanelContent(size_t panel_index) {
|
|||||||
|
|
||||||
void Scoreboard::renderScoreMode(size_t panel_index) {
|
void Scoreboard::renderScoreMode(size_t panel_index) {
|
||||||
// SCORE
|
// SCORE
|
||||||
text_scoreboard_->writeDX(Text::COLOR | Text::CENTER, slot4_1_.x, slot4_1_.y, name_.at(panel_index), 1, text_color1_);
|
text_->writeDX(Text::COLOR | Text::CENTER, slot4_1_.x, slot4_1_.y, name_.at(panel_index), 1, text_color1_);
|
||||||
text_scoreboard_->writeDX(Text::COLOR | Text::CENTER, slot4_2_.x, slot4_2_.y, updateScoreText(score_.at(panel_index)), 1, text_color2_);
|
text_->writeDX(Text::COLOR | Text::CENTER, slot4_2_.x, slot4_2_.y, updateScoreText(score_.at(panel_index)), 1, text_color2_);
|
||||||
|
|
||||||
// MULT
|
// MULT
|
||||||
text_scoreboard_->writeDX(Text::COLOR | Text::CENTER, slot4_3_.x, slot4_3_.y, Lang::getText("[SCOREBOARD] 3"), 1, text_color1_);
|
text_->writeDX(Text::COLOR | Text::CENTER, slot4_3_.x, slot4_3_.y, Lang::getText("[SCOREBOARD] 3"), 1, text_color1_);
|
||||||
text_scoreboard_->writeDX(Text::COLOR | Text::CENTER, slot4_4_.x, slot4_4_.y, "x" + std::to_string(mult_.at(panel_index)).substr(0, 3), 1, text_color2_);
|
text_->writeDX(Text::COLOR | Text::CENTER, slot4_4_.x, slot4_4_.y, "x" + std::to_string(mult_.at(panel_index)).substr(0, 3), 1, text_color2_);
|
||||||
}
|
}
|
||||||
|
|
||||||
void Scoreboard::renderDemoMode() {
|
void Scoreboard::renderDemoMode() {
|
||||||
// DEMO MODE
|
// DEMO MODE
|
||||||
text_scoreboard_->writeDX(Text::CENTER | Text::COLOR, slot4_1_.x, slot4_1_.y + 4, Lang::getText("[SCOREBOARD] 6"), 1, text_color1_);
|
text_->writeDX(Text::CENTER | Text::COLOR, slot4_1_.x, slot4_1_.y + 4, Lang::getText("[SCOREBOARD] 6"), 1, text_color1_);
|
||||||
|
|
||||||
// PRESS START TO PLAY
|
// PRESS START TO PLAY
|
||||||
if (time_counter_ % 10 < 8) {
|
if (time_counter_ % 10 < 8) {
|
||||||
text_scoreboard_->writeDX(Text::CENTER | Text::COLOR, slot4_3_.x, slot4_3_.y - 2, Lang::getText("[SCOREBOARD] 8"), 1, text_color1_);
|
text_->writeDX(Text::CENTER | Text::COLOR, slot4_3_.x, slot4_3_.y - 2, Lang::getText("[SCOREBOARD] 8"), 1, text_color1_);
|
||||||
text_scoreboard_->writeDX(Text::CENTER | Text::COLOR, slot4_4_.x, slot4_4_.y - 2, Lang::getText("[SCOREBOARD] 9"), 1, text_color1_);
|
text_->writeDX(Text::CENTER | Text::COLOR, slot4_4_.x, slot4_4_.y - 2, Lang::getText("[SCOREBOARD] 9"), 1, text_color1_);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void Scoreboard::renderWaitingMode() {
|
void Scoreboard::renderWaitingMode() {
|
||||||
// GAME OVER
|
// GAME OVER
|
||||||
text_scoreboard_->writeDX(Text::CENTER | Text::COLOR, slot4_1_.x, slot4_1_.y + 4, Lang::getText("[SCOREBOARD] 7"), 1, text_color1_);
|
text_->writeDX(Text::CENTER | Text::COLOR, slot4_1_.x, slot4_1_.y + 4, Lang::getText("[SCOREBOARD] 7"), 1, text_color1_);
|
||||||
|
|
||||||
// PRESS START TO PLAY
|
// PRESS START TO PLAY
|
||||||
if (time_counter_ % 10 < 8) {
|
if (time_counter_ % 10 < 8) {
|
||||||
text_scoreboard_->writeDX(Text::CENTER | Text::COLOR, slot4_3_.x, slot4_3_.y - 2, Lang::getText("[SCOREBOARD] 8"), 1, text_color1_);
|
text_->writeDX(Text::CENTER | Text::COLOR, slot4_3_.x, slot4_3_.y - 2, Lang::getText("[SCOREBOARD] 8"), 1, text_color1_);
|
||||||
text_scoreboard_->writeDX(Text::CENTER | Text::COLOR, slot4_4_.x, slot4_4_.y - 2, Lang::getText("[SCOREBOARD] 9"), 1, text_color1_);
|
text_->writeDX(Text::CENTER | Text::COLOR, slot4_4_.x, slot4_4_.y - 2, Lang::getText("[SCOREBOARD] 9"), 1, text_color1_);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void Scoreboard::renderGameOverMode() {
|
void Scoreboard::renderGameOverMode() {
|
||||||
// GAME OVER
|
// GAME OVER
|
||||||
text_scoreboard_->writeDX(Text::CENTER | Text::COLOR, slot4_1_.x, slot4_1_.y + 4, Lang::getText("[SCOREBOARD] 7"), 1, text_color1_);
|
text_->writeDX(Text::CENTER | Text::COLOR, slot4_1_.x, slot4_1_.y + 4, Lang::getText("[SCOREBOARD] 7"), 1, text_color1_);
|
||||||
|
|
||||||
// PLEASE WAIT
|
// PLEASE WAIT
|
||||||
if (time_counter_ % 10 < 8) {
|
if (time_counter_ % 10 < 8) {
|
||||||
text_scoreboard_->writeDX(Text::CENTER | Text::COLOR, slot4_3_.x, slot4_3_.y - 2, Lang::getText("[SCOREBOARD] 12"), 1, text_color1_);
|
text_->writeDX(Text::CENTER | Text::COLOR, slot4_3_.x, slot4_3_.y - 2, Lang::getText("[SCOREBOARD] 12"), 1, text_color1_);
|
||||||
text_scoreboard_->writeDX(Text::CENTER | Text::COLOR, slot4_4_.x, slot4_4_.y - 2, Lang::getText("[SCOREBOARD] 13"), 1, text_color1_);
|
text_->writeDX(Text::CENTER | Text::COLOR, slot4_4_.x, slot4_4_.y - 2, Lang::getText("[SCOREBOARD] 13"), 1, text_color1_);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void Scoreboard::renderStageInfoMode() {
|
void Scoreboard::renderStageInfoMode() {
|
||||||
// STAGE
|
// STAGE
|
||||||
text_scoreboard_->writeDX(Text::CENTER | Text::COLOR, slot4_1_.x, slot4_1_.y, Lang::getText("[SCOREBOARD] 5") + " " + std::to_string(stage_), 1, text_color1_);
|
text_->writeDX(Text::CENTER | Text::COLOR, slot4_1_.x, slot4_1_.y, Lang::getText("[SCOREBOARD] 5") + " " + std::to_string(stage_), 1, text_color1_);
|
||||||
|
|
||||||
// POWERMETER
|
// POWERMETER
|
||||||
power_meter_sprite_->setSpriteClip(0, 0, 40, 7);
|
power_meter_sprite_->setSpriteClip(0, 0, 40, 7);
|
||||||
@@ -250,76 +251,75 @@ void Scoreboard::renderStageInfoMode() {
|
|||||||
power_meter_sprite_->render();
|
power_meter_sprite_->render();
|
||||||
|
|
||||||
// HI-SCORE
|
// HI-SCORE
|
||||||
text_scoreboard_->writeDX(Text::CENTER | Text::COLOR, slot4_3_.x, slot4_3_.y, Lang::getText("[SCOREBOARD] 4"), 1, text_color1_);
|
text_->writeDX(Text::CENTER | Text::COLOR, slot4_3_.x, slot4_3_.y, Lang::getText("[SCOREBOARD] 4"), 1, text_color1_);
|
||||||
const std::string NAME = hi_score_name_.empty() ? "" : hi_score_name_ + " - ";
|
const std::string NAME = hi_score_name_.empty() ? "" : hi_score_name_ + " - ";
|
||||||
text_scoreboard_->writeDX(Text::CENTER | Text::COLOR, slot4_4_.x, slot4_4_.y, NAME + updateScoreText(hi_score_), 1, text_color2_);
|
text_->writeDX(Text::CENTER | Text::COLOR, slot4_4_.x, slot4_4_.y, NAME + updateScoreText(hi_score_), 1, text_color2_);
|
||||||
}
|
}
|
||||||
|
|
||||||
void Scoreboard::renderContinueMode(size_t panel_index) {
|
void Scoreboard::renderContinueMode(size_t panel_index) {
|
||||||
// SCORE
|
// SCORE
|
||||||
text_scoreboard_->writeDX(Text::CENTER | Text::COLOR, slot4_1_.x, slot4_1_.y, name_.at(panel_index), 1, text_color1_);
|
text_->writeDX(Text::CENTER | Text::COLOR, slot4_1_.x, slot4_1_.y, name_.at(panel_index), 1, text_color1_);
|
||||||
text_scoreboard_->writeDX(Text::CENTER | Text::COLOR, slot4_2_.x, slot4_2_.y, updateScoreText(score_.at(panel_index)), 1, text_color2_);
|
text_->writeDX(Text::CENTER | Text::COLOR, slot4_2_.x, slot4_2_.y, updateScoreText(score_.at(panel_index)), 1, text_color2_);
|
||||||
|
|
||||||
// CONTINUE
|
// CONTINUE
|
||||||
text_scoreboard_->writeDX(Text::CENTER | Text::COLOR, slot4_3_.x, slot4_3_.y, Lang::getText("[SCOREBOARD] 10"), 1, text_color1_);
|
text_->writeDX(Text::CENTER | Text::COLOR, slot4_3_.x, slot4_3_.y, Lang::getText("[SCOREBOARD] 10"), 1, text_color1_);
|
||||||
text_scoreboard_->writeDX(Text::CENTER | Text::COLOR, slot4_4_.x, slot4_4_.y, std::to_string(continue_counter_.at(panel_index)), 1, text_color2_);
|
text_->writeDX(Text::CENTER | Text::COLOR, slot4_4_.x, slot4_4_.y, std::to_string(continue_counter_.at(panel_index)), 1, text_color2_);
|
||||||
}
|
}
|
||||||
|
|
||||||
void Scoreboard::renderEnterNameMode(size_t panel_index) {
|
void Scoreboard::renderEnterNameMode(size_t panel_index) {
|
||||||
// SCORE
|
// SCORE
|
||||||
text_scoreboard_->writeDX(Text::CENTER | Text::COLOR, slot4_1_.x, slot4_1_.y, name_.at(panel_index), 1, text_color1_);
|
text_->writeDX(Text::CENTER | Text::COLOR, slot4_1_.x, slot4_1_.y, name_.at(panel_index), 1, text_color1_);
|
||||||
text_scoreboard_->writeDX(Text::CENTER | Text::COLOR, slot4_2_.x, slot4_2_.y, updateScoreText(score_.at(panel_index)), 1, text_color2_);
|
text_->writeDX(Text::CENTER | Text::COLOR, slot4_2_.x, slot4_2_.y, updateScoreText(score_.at(panel_index)), 1, text_color2_);
|
||||||
|
|
||||||
// ENTER NAME
|
// ENTER NAME
|
||||||
text_scoreboard_->writeDX(Text::CENTER | Text::COLOR, slot4_3_.x, slot4_3_.y, Lang::getText("[SCOREBOARD] 11"), 1, text_color1_);
|
text_->writeDX(Text::CENTER | Text::COLOR, slot4_3_.x, slot4_3_.y, Lang::getText("[SCOREBOARD] 11"), 1, text_color1_);
|
||||||
|
|
||||||
renderNameInputField(panel_index);
|
renderNameInputField(panel_index);
|
||||||
}
|
}
|
||||||
|
|
||||||
void Scoreboard::renderNameInputField(size_t panel_index) {
|
void Scoreboard::renderNameInputField(size_t panel_index) {
|
||||||
SDL_FRect rect = {enter_name_pos_.x, enter_name_pos_.y, 5.0F, 7.0F};
|
SDL_FRect rect = {
|
||||||
|
.x = enter_name_pos_.x,
|
||||||
|
.y = enter_name_pos_.y,
|
||||||
|
.w = static_cast<float>(enter_name_text_->getCharacterSize() - 2),
|
||||||
|
.h = static_cast<float>(enter_name_text_->getCharacterSize())};
|
||||||
|
|
||||||
// Recorre todos los slots de letras del nombre
|
// Recorre todos los slots de letras del nombre
|
||||||
for (size_t j = 0; j < NAME_SIZE; ++j) {
|
for (size_t j = 0; j < NAME_SIZE; ++j) {
|
||||||
// Selecciona el color
|
// Dibuja la linea. Si coincide con el selector solo se dibuja 2 de cada 4 veces
|
||||||
const Color COLOR = j < selector_pos_.at(panel_index) ? text_color2_ : text_color1_;
|
if (j != selector_pos_.at(panel_index) || time_counter_ % 4 >= 2) {
|
||||||
|
SDL_SetRenderDrawColor(renderer_, text_color1_.r, text_color1_.g, text_color1_.b, 255);
|
||||||
if (j != selector_pos_.at(panel_index) || time_counter_ % 3 == 0) {
|
SDL_RenderLine(renderer_, rect.x, rect.y + rect.h, rect.x + rect.w, rect.y + rect.h);
|
||||||
// Dibuja la linea
|
|
||||||
if (j >= selector_pos_.at(panel_index)) {
|
|
||||||
SDL_SetRenderDrawColor(renderer_, COLOR.r, COLOR.g, COLOR.b, 255);
|
|
||||||
SDL_RenderLine(renderer_, rect.x, rect.y + rect.h, rect.x + rect.w, rect.y + rect.h);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Dibuja la letra
|
|
||||||
if (j < record_name_.at(panel_index).size()) {
|
|
||||||
text_scoreboard_->writeColored(rect.x, rect.y, record_name_.at(panel_index).substr(j, 1), COLOR);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
rect.x += 7;
|
|
||||||
|
// Dibuja la letra
|
||||||
|
if (j < record_name_.at(panel_index).size()) {
|
||||||
|
enter_name_text_->writeColored(rect.x, rect.y, record_name_.at(panel_index).substr(j, 1), text_color2_);
|
||||||
|
}
|
||||||
|
rect.x += enter_name_text_->getCharacterSize();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void Scoreboard::renderShowNameMode(size_t panel_index) {
|
void Scoreboard::renderShowNameMode(size_t panel_index) {
|
||||||
// SCORE
|
// SCORE
|
||||||
text_scoreboard_->writeDX(Text::CENTER | Text::COLOR, slot4_1_.x, slot4_1_.y, name_.at(panel_index), 1, text_color1_);
|
text_->writeDX(Text::CENTER | Text::COLOR, slot4_1_.x, slot4_1_.y, name_.at(panel_index), 1, text_color1_);
|
||||||
text_scoreboard_->writeDX(Text::CENTER | Text::COLOR, slot4_2_.x, slot4_2_.y, updateScoreText(score_.at(panel_index)), 1, text_color2_);
|
text_->writeDX(Text::CENTER | Text::COLOR, slot4_2_.x, slot4_2_.y, updateScoreText(score_.at(panel_index)), 1, text_color2_);
|
||||||
|
|
||||||
// NAME
|
// NAME
|
||||||
text_scoreboard_->writeDX(Text::CENTER | Text::COLOR, slot4_3_.x, slot4_3_.y, Lang::getText("[SCOREBOARD] 11"), 1, text_color1_);
|
text_->writeDX(Text::CENTER | Text::COLOR, slot4_3_.x, slot4_3_.y, Lang::getText("[SCOREBOARD] 11"), 1, text_color1_);
|
||||||
|
|
||||||
/* TEXTO CENTRADO */
|
// NOMBRE INTRODUCIDO
|
||||||
text_scoreboard_->writeDX(Text::CENTER | Text::COLOR, slot4_4_.x, slot4_4_.y, record_name_.at(panel_index), 1, Colors::getColorLikeKnightRider(name_colors_, loop_counter_ / 5));
|
enter_name_text_->writeDX(Text::CENTER | Text::COLOR, slot4_4_.x, slot4_4_.y, record_name_.at(panel_index), 1, Colors::getColorLikeKnightRider(name_colors_, loop_counter_ / 5));
|
||||||
}
|
}
|
||||||
|
|
||||||
void Scoreboard::renderGameCompletedMode(size_t panel_index) {
|
void Scoreboard::renderGameCompletedMode(size_t panel_index) {
|
||||||
// GAME OVER
|
// GAME OVER
|
||||||
text_scoreboard_->writeDX(Text::CENTER | Text::COLOR, slot4_1_.x, slot4_1_.y + 4, Lang::getText("[SCOREBOARD] 7"), 1, text_color1_);
|
text_->writeDX(Text::CENTER | Text::COLOR, slot4_1_.x, slot4_1_.y + 4, Lang::getText("[SCOREBOARD] 7"), 1, text_color1_);
|
||||||
|
|
||||||
// SCORE
|
// SCORE
|
||||||
if (time_counter_ % 10 < 8) {
|
if (time_counter_ % 10 < 8) {
|
||||||
text_scoreboard_->writeDX(Text::CENTER | Text::COLOR, slot4_3_.x, slot4_3_.y - 2, Lang::getText("[SCOREBOARD] 14"), 1, text_color1_);
|
text_->writeDX(Text::CENTER | Text::COLOR, slot4_3_.x, slot4_3_.y - 2, Lang::getText("[SCOREBOARD] 14"), 1, text_color1_);
|
||||||
text_scoreboard_->writeDX(Text::CENTER | Text::COLOR, slot4_4_.x, slot4_4_.y - 2, updateScoreText(score_.at(panel_index)), 1, text_color2_);
|
text_->writeDX(Text::CENTER | Text::COLOR, slot4_4_.x, slot4_4_.y - 2, updateScoreText(score_.at(panel_index)), 1, text_color2_);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -379,7 +379,7 @@ void Scoreboard::recalculateAnchors() {
|
|||||||
slot4_4_ = {.x = COL, .y = ROW4};
|
slot4_4_ = {.x = COL, .y = ROW4};
|
||||||
|
|
||||||
// Primer cuadrado para poner el nombre de record
|
// Primer cuadrado para poner el nombre de record
|
||||||
const int ENTER_NAME_LENGTH = text_scoreboard_->length(std::string(NAME_SIZE, 'A'));
|
const int ENTER_NAME_LENGTH = enter_name_text_->length(std::string(NAME_SIZE, 'A'));
|
||||||
enter_name_pos_.x = COL - (ENTER_NAME_LENGTH / 2);
|
enter_name_pos_.x = COL - (ENTER_NAME_LENGTH / 2);
|
||||||
enter_name_pos_.y = ROW4;
|
enter_name_pos_.y = ROW4;
|
||||||
|
|
||||||
|
|||||||
@@ -73,7 +73,8 @@ class Scoreboard {
|
|||||||
SDL_Renderer *renderer_; // El renderizador de la ventana
|
SDL_Renderer *renderer_; // El renderizador de la ventana
|
||||||
std::shared_ptr<Texture> game_power_meter_texture_; // Textura con el marcador de poder de la fase
|
std::shared_ptr<Texture> game_power_meter_texture_; // Textura con el marcador de poder de la fase
|
||||||
std::unique_ptr<Sprite> power_meter_sprite_; // Sprite para el medidor de poder de la fase
|
std::unique_ptr<Sprite> power_meter_sprite_; // Sprite para el medidor de poder de la fase
|
||||||
std::shared_ptr<Text> text_scoreboard_; // Fuente para el marcador del juego
|
std::shared_ptr<Text> text_; // Fuente para el marcador del juego
|
||||||
|
std::shared_ptr<Text> enter_name_text_; // Fuente para la introducción de nombre del jugador
|
||||||
SDL_Texture *background_ = nullptr; // Textura para dibujar el marcador
|
SDL_Texture *background_ = nullptr; // Textura para dibujar el marcador
|
||||||
std::vector<SDL_Texture *> panel_texture_; // Texturas para dibujar cada panel
|
std::vector<SDL_Texture *> panel_texture_; // Texturas para dibujar cada panel
|
||||||
|
|
||||||
|
|||||||
@@ -155,16 +155,16 @@ auto Screen::incWindowSize() -> bool {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Actualiza la lógica de la clase
|
// Recibe deltaTime de las secciones y actualiza la lógica
|
||||||
void Screen::update() {
|
void Screen::update(float delta_time) {
|
||||||
fps_.calculate(SDL_GetTicks());
|
fps_.calculate(SDL_GetTicks());
|
||||||
shake_effect_.update(src_rect_, dst_rect_);
|
shake_effect_.update(src_rect_, dst_rect_, delta_time);
|
||||||
flash_effect_.update();
|
flash_effect_.update(delta_time);
|
||||||
if (service_menu_ != nullptr) {
|
if (service_menu_ != nullptr) {
|
||||||
service_menu_->update();
|
service_menu_->update(delta_time);
|
||||||
}
|
}
|
||||||
if (notifier_ != nullptr) {
|
if (notifier_ != nullptr) {
|
||||||
notifier_->update();
|
notifier_->update(delta_time);
|
||||||
}
|
}
|
||||||
Mouse::updateCursorVisibility();
|
Mouse::updateCursorVisibility();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ class Screen {
|
|||||||
static auto get() -> Screen *; // Obtiene el puntero al objeto Screen
|
static auto get() -> Screen *; // Obtiene el puntero al objeto Screen
|
||||||
|
|
||||||
// --- Métodos principales ---
|
// --- Métodos principales ---
|
||||||
void update(); // Actualiza la lógica de la clase
|
void update(float delta_time); // Recibe deltaTime de las secciones y actualiza la lógica
|
||||||
void coreUpdate(); // Actualiza los elementos mínimos
|
void coreUpdate(); // Actualiza los elementos mínimos
|
||||||
void clean(Color color = Color(0x00, 0x00, 0x00)); // Limpia la pantalla
|
void clean(Color color = Color(0x00, 0x00, 0x00)); // Limpia la pantalla
|
||||||
void start(); // Prepara para empezar a dibujar en la textura de juego
|
void start(); // Prepara para empezar a dibujar en la textura de juego
|
||||||
@@ -38,8 +38,8 @@ class Screen {
|
|||||||
void initShaders(); // Inicializa los shaders
|
void initShaders(); // Inicializa los shaders
|
||||||
|
|
||||||
// --- Efectos visuales ---
|
// --- Efectos visuales ---
|
||||||
void shake(int desp = 2, int delay = 3, int length = 8) { shake_effect_.enable(src_rect_, dst_rect_, desp, delay, length); } // Agita la pantalla
|
void shake(int desp = 2, float delay_s = 0.05f, float duration_s = 0.133f) { shake_effect_.enable(src_rect_, dst_rect_, desp, delay_s, duration_s); } // Agita la pantalla (tiempo en segundos)
|
||||||
void flash(Color color, int length = 10, int delay = 0) { flash_effect_ = FlashEffect(true, length, delay, color); } // Pone la pantalla de color
|
void flash(Color color, float duration_s = 0.167f, float delay_s = 0.0f) { flash_effect_ = FlashEffect(true, duration_s, delay_s, color); } // Pone la pantalla de color (tiempo en segundos)
|
||||||
void toggleShaders(); // Alterna entre activar y desactivar los shaders
|
void toggleShaders(); // Alterna entre activar y desactivar los shaders
|
||||||
void toggleIntegerScale(); // Alterna entre activar y desactivar el escalado entero
|
void toggleIntegerScale(); // Alterna entre activar y desactivar el escalado entero
|
||||||
void toggleVSync(); // Alterna entre activar y desactivar el V-Sync
|
void toggleVSync(); // Alterna entre activar y desactivar el V-Sync
|
||||||
@@ -82,37 +82,55 @@ class Screen {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Efecto de flash en pantalla: pinta la pantalla de un color durante unos frames
|
// Efecto de flash en pantalla: pinta la pantalla de un color durante un tiempo
|
||||||
struct FlashEffect {
|
struct FlashEffect {
|
||||||
bool enabled; // Indica si el efecto está activo
|
bool enabled; // Indica si el efecto está activo
|
||||||
int length; // Duración total del efecto en frames
|
float duration_s; // Duración total del efecto en segundos
|
||||||
int delay; // Retraso antes de mostrar el flash
|
float delay_s; // Retraso antes de mostrar el flash en segundos
|
||||||
int counter; // Contador de frames restantes
|
float timer_s; // Timer en segundos (contador decreciente)
|
||||||
Color color; // Color del flash
|
Color color; // Color del flash
|
||||||
|
|
||||||
explicit FlashEffect(bool enabled = false, int length = 0, int delay = 0, Color color = Color(0xFF, 0xFF, 0xFF))
|
explicit FlashEffect(bool enabled = false, float duration_s = 0.0f, float delay_s = 0.0f, Color color = Color(0xFF, 0xFF, 0xFF))
|
||||||
: enabled(enabled), length(length), delay(delay), counter(length), color(color) {}
|
: enabled(enabled),
|
||||||
|
duration_s(duration_s),
|
||||||
|
delay_s(delay_s),
|
||||||
|
timer_s(duration_s),
|
||||||
|
color(color) {}
|
||||||
|
|
||||||
void update() { (enabled && counter > 0) ? counter-- : static_cast<int>(enabled = false); }
|
void update(float delta_time) {
|
||||||
[[nodiscard]] auto isRendarable() const -> bool { return enabled && counter < length - delay; }
|
if (enabled && timer_s > 0.0f) {
|
||||||
|
timer_s -= delta_time;
|
||||||
|
if (timer_s <= 0.0f) {
|
||||||
|
enabled = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
[[nodiscard]] auto isRendarable() const -> bool { return enabled && timer_s < duration_s - delay_s; }
|
||||||
};
|
};
|
||||||
|
|
||||||
// Efecto de sacudida/agitación de pantalla: mueve la imagen para simular un temblor
|
// Efecto de sacudida/agitación de pantalla: mueve la imagen para simular un temblor
|
||||||
struct ShakeEffect {
|
struct ShakeEffect {
|
||||||
int desp; // Desplazamiento máximo de la sacudida (en píxeles)
|
int desp; // Desplazamiento máximo de la sacudida (en píxeles)
|
||||||
int delay; // Frames entre cada movimiento de sacudida
|
float delay_s; // Segundos entre cada movimiento de sacudida
|
||||||
int counter; // Contador de frames para el siguiente movimiento
|
float counter_s; // Timer para el siguiente movimiento (decreciente)
|
||||||
int length; // Duración total del efecto en frames
|
float duration_s; // Duración total del efecto en segundos
|
||||||
int remaining; // Frames restantes de sacudida
|
float remaining_s; // Tiempo restante de sacudida
|
||||||
int original_pos; // Posición original de la imagen (x)
|
int original_pos; // Posición original de la imagen (x)
|
||||||
int original_width; // Ancho original de la imagen
|
int original_width; // Ancho original de la imagen
|
||||||
bool enabled; // Indica si el efecto está activo
|
bool enabled; // Indica si el efecto está activo
|
||||||
|
|
||||||
explicit ShakeEffect(bool en = false, int dp = 2, int dl = 3, int cnt = 0, int len = 8, int rem = 0, int orig_pos = 0, int orig_width = 800)
|
explicit ShakeEffect(bool en = false, int dp = 2, float dl_s = 0.05f, float cnt_s = 0.0f, float len_s = 0.133f, float rem_s = 0.0f, int orig_pos = 0, int orig_width = 800)
|
||||||
: desp(dp), delay(dl), counter(cnt), length(len), remaining(rem), original_pos(orig_pos), original_width(orig_width), enabled(en) {}
|
: desp(dp),
|
||||||
|
delay_s(dl_s),
|
||||||
|
counter_s(cnt_s),
|
||||||
|
duration_s(len_s),
|
||||||
|
remaining_s(rem_s),
|
||||||
|
original_pos(orig_pos),
|
||||||
|
original_width(orig_width),
|
||||||
|
enabled(en) {}
|
||||||
|
|
||||||
// Activa el efecto de sacudida y guarda la posición y tamaño originales
|
// Activa el efecto de sacudida y guarda la posición y tamaño originales
|
||||||
void enable(SDL_FRect &src_rect, SDL_FRect &dst_rect, int new_desp = -1, int new_delay = -1, int new_length = -1) {
|
void enable(SDL_FRect &src_rect, SDL_FRect &dst_rect, int new_desp = -1, float new_delay_s = -1.0f, float new_duration_s = -1.0f) {
|
||||||
if (!enabled) {
|
if (!enabled) {
|
||||||
enabled = true;
|
enabled = true;
|
||||||
original_pos = src_rect.x;
|
original_pos = src_rect.x;
|
||||||
@@ -122,33 +140,35 @@ class Screen {
|
|||||||
if (new_desp != -1) {
|
if (new_desp != -1) {
|
||||||
desp = new_desp;
|
desp = new_desp;
|
||||||
}
|
}
|
||||||
if (new_delay != -1) {
|
if (new_delay_s >= 0.0f) {
|
||||||
delay = new_delay;
|
delay_s = new_delay_s;
|
||||||
}
|
}
|
||||||
if (new_length != -1) {
|
if (new_duration_s >= 0.0f) {
|
||||||
length = new_length;
|
duration_s = new_duration_s;
|
||||||
}
|
}
|
||||||
|
|
||||||
src_rect.w -= desp;
|
src_rect.w -= desp;
|
||||||
dst_rect.w = src_rect.w;
|
dst_rect.w = src_rect.w;
|
||||||
}
|
}
|
||||||
remaining = length;
|
remaining_s = duration_s;
|
||||||
counter = delay;
|
counter_s = delay_s;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Actualiza el estado del efecto de sacudida
|
// Actualiza el estado del efecto de sacudida
|
||||||
void update(SDL_FRect &src_rect, SDL_FRect &dst_rect) {
|
void update(SDL_FRect &src_rect, SDL_FRect &dst_rect, float delta_time) {
|
||||||
if (enabled) {
|
if (enabled) {
|
||||||
if (counter > 0) {
|
counter_s -= delta_time;
|
||||||
counter--;
|
if (counter_s <= 0.0f) {
|
||||||
} else {
|
counter_s = delay_s;
|
||||||
counter = delay;
|
// Alternar desplazamiento basado en tiempo restante
|
||||||
const auto SRC_DESP = (remaining % 2 == 0) ? 0 : desp;
|
const bool SHAKE_LEFT = static_cast<int>(remaining_s * 30.0f) % 2 == 0; // ~30 cambios por segundo
|
||||||
const auto DST_DESP = (remaining % 2 == 1) ? 0 : desp;
|
const auto SRC_DESP = SHAKE_LEFT ? 0 : desp;
|
||||||
|
const auto DST_DESP = SHAKE_LEFT ? desp : 0;
|
||||||
src_rect.x = original_pos + SRC_DESP;
|
src_rect.x = original_pos + SRC_DESP;
|
||||||
dst_rect.x = original_pos + DST_DESP;
|
dst_rect.x = original_pos + DST_DESP;
|
||||||
remaining--;
|
|
||||||
if (remaining == -1) {
|
remaining_s -= delay_s;
|
||||||
|
if (remaining_s <= 0.0f) {
|
||||||
enabled = false;
|
enabled = false;
|
||||||
src_rect.x = original_pos;
|
src_rect.x = original_pos;
|
||||||
src_rect.w = original_width;
|
src_rect.w = original_width;
|
||||||
|
|||||||
@@ -35,7 +35,12 @@ constexpr std::string_view TEXT_COPYRIGHT = "@2020,2025 JailDesigner";
|
|||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
Credits::Credits()
|
Credits::Credits()
|
||||||
: balloon_manager_(std::make_unique<BalloonManager>(nullptr)), tiled_bg_(std::make_unique<TiledBG>(param.game.game_area.rect, TiledBGMode::DIAGONAL)), fade_in_(std::make_unique<Fade>()), fade_out_(std::make_unique<Fade>()), text_texture_(SDL_CreateTexture(Screen::get()->getRenderer(), SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, static_cast<int>(param.game.width), static_cast<int>(param.game.height))), canvas_(SDL_CreateTexture(Screen::get()->getRenderer(), SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, static_cast<int>(param.game.width), static_cast<int>(param.game.height))) {
|
: balloon_manager_(std::make_unique<BalloonManager>(nullptr)),
|
||||||
|
tiled_bg_(std::make_unique<TiledBG>(param.game.game_area.rect, TiledBGMode::DIAGONAL)),
|
||||||
|
fade_in_(std::make_unique<Fade>()),
|
||||||
|
fade_out_(std::make_unique<Fade>()),
|
||||||
|
text_texture_(SDL_CreateTexture(Screen::get()->getRenderer(), SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, static_cast<int>(param.game.width), static_cast<int>(param.game.height))),
|
||||||
|
canvas_(SDL_CreateTexture(Screen::get()->getRenderer(), SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, static_cast<int>(param.game.width), static_cast<int>(param.game.height))) {
|
||||||
if (text_texture_ == nullptr) {
|
if (text_texture_ == nullptr) {
|
||||||
throw std::runtime_error("Failed to create SDL texture for text.");
|
throw std::runtime_error("Failed to create SDL texture for text.");
|
||||||
}
|
}
|
||||||
@@ -44,16 +49,17 @@ Credits::Credits()
|
|||||||
|
|
||||||
fade_in_->setColor(param.fade.color);
|
fade_in_->setColor(param.fade.color);
|
||||||
fade_in_->setType(Fade::Type::FULLSCREEN);
|
fade_in_->setType(Fade::Type::FULLSCREEN);
|
||||||
fade_in_->setPostDuration(50);
|
fade_in_->setPostDuration(static_cast<int>(50 * (1000.0f / 60.0f))); // 50 frames = ~833ms
|
||||||
fade_in_->setMode(Fade::Mode::IN);
|
fade_in_->setMode(Fade::Mode::IN);
|
||||||
fade_in_->activate();
|
fade_in_->activate();
|
||||||
|
|
||||||
fade_out_->setColor(0, 0, 0);
|
fade_out_->setColor(0, 0, 0);
|
||||||
fade_out_->setType(Fade::Type::FULLSCREEN);
|
fade_out_->setType(Fade::Type::FULLSCREEN);
|
||||||
fade_out_->setPostDuration(400);
|
fade_out_->setPostDuration(static_cast<int>(400 * (1000.0f / 60.0f))); // 400 frames = ~6667ms
|
||||||
|
|
||||||
updateRedRect();
|
updateRedRect();
|
||||||
tiled_bg_->setColor(Color(255, 96, 96));
|
tiled_bg_->setColor(Color(255, 96, 96));
|
||||||
|
tiled_bg_->setSpeed(60.0F);
|
||||||
|
|
||||||
initPlayers();
|
initPlayers();
|
||||||
SDL_SetTextureBlendMode(text_texture_, SDL_BLENDMODE_BLEND);
|
SDL_SetTextureBlendMode(text_texture_, SDL_BLENDMODE_BLEND);
|
||||||
@@ -73,37 +79,49 @@ Credits::~Credits() {
|
|||||||
Options::gamepad_manager.clearPlayers();
|
Options::gamepad_manager.clearPlayers();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Calcula el deltatime
|
||||||
|
auto Credits::calculateDeltaTime() -> float {
|
||||||
|
const Uint64 current_time = SDL_GetTicks();
|
||||||
|
const float delta_time = static_cast<float>(current_time - last_time_) / 1000.0f; // Convertir ms a segundos
|
||||||
|
last_time_ = current_time;
|
||||||
|
return delta_time;
|
||||||
|
}
|
||||||
|
|
||||||
// Bucle principal
|
// Bucle principal
|
||||||
void Credits::run() {
|
void Credits::run() {
|
||||||
|
last_time_ = SDL_GetTicks();
|
||||||
|
|
||||||
while (Section::name == Section::Name::CREDITS) {
|
while (Section::name == Section::Name::CREDITS) {
|
||||||
checkInput();
|
checkInput();
|
||||||
update();
|
const float delta_time = calculateDeltaTime();
|
||||||
|
update(delta_time);
|
||||||
checkEvents(); // Tiene que ir antes del render
|
checkEvents(); // Tiene que ir antes del render
|
||||||
render();
|
render();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Actualiza las variables
|
// Actualiza las variables (time-based)
|
||||||
void Credits::update() {
|
void Credits::update(float deltaTime) {
|
||||||
if (SDL_GetTicks() - ticks_ > param.game.speed) {
|
const float multiplier = want_to_pass_ ? 4.0f : 1.0f;
|
||||||
ticks_ = SDL_GetTicks();
|
const float adjusted_delta_time = deltaTime * multiplier;
|
||||||
const int REPEAT = want_to_pass_ ? 4 : 1;
|
|
||||||
for (int i = 0; i < REPEAT; ++i) {
|
|
||||||
tiled_bg_->update();
|
|
||||||
cycleColors();
|
|
||||||
balloon_manager_->update();
|
|
||||||
updateTextureDstRects();
|
|
||||||
throwBalloons();
|
|
||||||
updatePlayers();
|
|
||||||
updateAllFades();
|
|
||||||
++counter_;
|
|
||||||
}
|
|
||||||
|
|
||||||
Screen::get()->update();
|
static auto *const SCREEN = Screen::get();
|
||||||
|
SCREEN->update(deltaTime); // Actualiza el objeto screen
|
||||||
|
Audio::update(); // Actualiza el objeto audio
|
||||||
|
|
||||||
fillCanvas();
|
tiled_bg_->update(adjusted_delta_time);
|
||||||
}
|
cycleColors();
|
||||||
Audio::update();
|
balloon_manager_->update(adjusted_delta_time);
|
||||||
|
updateTextureDstRects(adjusted_delta_time);
|
||||||
|
throwBalloons(adjusted_delta_time);
|
||||||
|
updatePlayers(adjusted_delta_time);
|
||||||
|
updateAllFades(adjusted_delta_time);
|
||||||
|
|
||||||
|
// Convertir deltaTime a equivalente de frames (60fps)
|
||||||
|
const float frameFactor = adjusted_delta_time * 60.0f;
|
||||||
|
counter_ += frameFactor;
|
||||||
|
|
||||||
|
fillCanvas();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Dibuja Credits::en patalla
|
// Dibuja Credits::en patalla
|
||||||
@@ -272,9 +290,15 @@ void Credits::fillCanvas() {
|
|||||||
SDL_SetRenderTarget(Screen::get()->getRenderer(), temp);
|
SDL_SetRenderTarget(Screen::get()->getRenderer(), temp);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Actualiza el destino de los rectangulos de las texturas
|
// Actualiza el destino de los rectangulos de las texturas (time-based)
|
||||||
void Credits::updateTextureDstRects() {
|
void Credits::updateTextureDstRects(float deltaTime) {
|
||||||
if (counter_ % 10 == 0) {
|
constexpr float TEXTURE_UPDATE_INTERVAL_S = 10.0f / 60.0f; // ~0.167s (cada 10 frames)
|
||||||
|
static float texture_accumulator = 0.0f;
|
||||||
|
texture_accumulator += deltaTime;
|
||||||
|
|
||||||
|
if (texture_accumulator >= TEXTURE_UPDATE_INTERVAL_S) {
|
||||||
|
texture_accumulator -= TEXTURE_UPDATE_INTERVAL_S;
|
||||||
|
|
||||||
// Comprueba la posición de la textura con los titulos de credito
|
// Comprueba la posición de la textura con los titulos de credito
|
||||||
if (credits_rect_dst_.y + credits_rect_dst_.h > play_area_.y) {
|
if (credits_rect_dst_.y + credits_rect_dst_.h > play_area_.y) {
|
||||||
--credits_rect_dst_.y;
|
--credits_rect_dst_.y;
|
||||||
@@ -301,21 +325,31 @@ void Credits::updateTextureDstRects() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Tira globos al escenario
|
// Tira globos al escenario (time-based)
|
||||||
void Credits::throwBalloons() {
|
void Credits::throwBalloons(float deltaTime) {
|
||||||
constexpr int SPEED = 200;
|
constexpr int SPEED = 200;
|
||||||
const std::vector<int> SETS = {0, 63, 25, 67, 17, 75, 13, 50};
|
const std::vector<int> SETS = {0, 63, 25, 67, 17, 75, 13, 50};
|
||||||
|
constexpr float BALLOON_INTERVAL_S = SPEED / 60.0f; // ~3.33s (cada 200 frames)
|
||||||
|
constexpr float POWERBALL_INTERVAL_S = (SPEED * 4) / 60.0f; // ~13.33s (cada 800 frames)
|
||||||
|
|
||||||
if (counter_ > ((SETS.size() - 1) * SPEED) * 3) {
|
if (counter_ > ((SETS.size() - 1) * SPEED) * 3) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (counter_ % SPEED == 0) {
|
static float balloon_accumulator = 0.0f;
|
||||||
const int INDEX = (counter_ / SPEED) % SETS.size();
|
static float powerball_accumulator = 0.0f;
|
||||||
|
|
||||||
|
balloon_accumulator += deltaTime;
|
||||||
|
powerball_accumulator += deltaTime;
|
||||||
|
|
||||||
|
if (balloon_accumulator >= BALLOON_INTERVAL_S) {
|
||||||
|
balloon_accumulator -= BALLOON_INTERVAL_S;
|
||||||
|
const int INDEX = (static_cast<int>(counter_ / SPEED)) % SETS.size();
|
||||||
balloon_manager_->deployFormation(SETS.at(INDEX), -60);
|
balloon_manager_->deployFormation(SETS.at(INDEX), -60);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (counter_ % (SPEED * 4) == 0 && counter_ > 0) {
|
if (powerball_accumulator >= POWERBALL_INTERVAL_S && counter_ > 0) {
|
||||||
|
powerball_accumulator -= POWERBALL_INTERVAL_S;
|
||||||
balloon_manager_->createPowerBall();
|
balloon_manager_->createPowerBall();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -387,12 +421,18 @@ void Credits::initPlayers() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Actualiza los rectangulos negros
|
// Actualiza los rectangulos negros (time-based)
|
||||||
void Credits::updateBlackRects() {
|
void Credits::updateBlackRects(float deltaTime) {
|
||||||
static int current_step_ = steps_;
|
static float current_step_ = static_cast<float>(steps_);
|
||||||
|
constexpr float BLACK_RECT_INTERVAL_S = 4.0f / 60.0f; // ~0.067s (cada 4 frames)
|
||||||
|
static float black_rect_accumulator = 0.0f;
|
||||||
|
|
||||||
if (top_black_rect_.h != param.game.game_area.center_y - 1 && bottom_black_rect_.y != param.game.game_area.center_y + 1) {
|
if (top_black_rect_.h != param.game.game_area.center_y - 1 && bottom_black_rect_.y != param.game.game_area.center_y + 1) {
|
||||||
// Si los rectangulos superior e inferior no han llegado al centro
|
// Si los rectangulos superior e inferior no han llegado al centro
|
||||||
if (counter_ % 4 == 0) {
|
black_rect_accumulator += deltaTime;
|
||||||
|
if (black_rect_accumulator >= BLACK_RECT_INTERVAL_S) {
|
||||||
|
black_rect_accumulator -= BLACK_RECT_INTERVAL_S;
|
||||||
|
|
||||||
// Incrementa la altura del rectangulo superior
|
// Incrementa la altura del rectangulo superior
|
||||||
top_black_rect_.h = std::min(top_black_rect_.h + 1, param.game.game_area.center_y - 1);
|
top_black_rect_.h = std::min(top_black_rect_.h + 1, param.game.game_area.center_y - 1);
|
||||||
|
|
||||||
@@ -401,7 +441,7 @@ void Credits::updateBlackRects() {
|
|||||||
bottom_black_rect_.y = std::max(bottom_black_rect_.y - 1, param.game.game_area.center_y + 1);
|
bottom_black_rect_.y = std::max(bottom_black_rect_.y - 1, param.game.game_area.center_y + 1);
|
||||||
|
|
||||||
--current_step_;
|
--current_step_;
|
||||||
setVolume((initial_volume_ * current_step_ / steps_));
|
setVolume(static_cast<int>(initial_volume_ * current_step_ / steps_));
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// Si los rectangulos superior e inferior han llegado al centro
|
// Si los rectangulos superior e inferior han llegado al centro
|
||||||
@@ -416,7 +456,7 @@ void Credits::updateBlackRects() {
|
|||||||
right_black_rect_.x = std::max(right_black_rect_.x - SPEED, param.game.game_area.center_x);
|
right_black_rect_.x = std::max(right_black_rect_.x - SPEED, param.game.game_area.center_x);
|
||||||
|
|
||||||
--current_step_;
|
--current_step_;
|
||||||
setVolume((initial_volume_ * current_step_ / steps_));
|
setVolume(static_cast<int>(initial_volume_ * current_step_ / steps_));
|
||||||
} else {
|
} else {
|
||||||
// Si los rectangulos izquierdo y derecho han llegado al centro
|
// Si los rectangulos izquierdo y derecho han llegado al centro
|
||||||
setVolume(0);
|
setVolume(0);
|
||||||
@@ -424,7 +464,9 @@ void Credits::updateBlackRects() {
|
|||||||
if (counter_pre_fade_ == 400) {
|
if (counter_pre_fade_ == 400) {
|
||||||
fade_out_->activate();
|
fade_out_->activate();
|
||||||
} else {
|
} else {
|
||||||
++counter_pre_fade_;
|
// Convertir deltaTime a equivalente de frames
|
||||||
|
const float frameFactor = deltaTime * 60.0f;
|
||||||
|
counter_pre_fade_ += frameFactor;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -438,19 +480,19 @@ void Credits::updateRedRect() {
|
|||||||
border_rect_.h = bottom_black_rect_.y - border_rect_.y + 1;
|
border_rect_.h = bottom_black_rect_.y - border_rect_.y + 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Actualiza el estado de fade
|
// Actualiza el estado de fade (time-based)
|
||||||
void Credits::updateAllFades() {
|
void Credits::updateAllFades(float deltaTime) {
|
||||||
if (fading_) {
|
if (fading_) {
|
||||||
updateBlackRects();
|
updateBlackRects(deltaTime);
|
||||||
updateRedRect();
|
updateRedRect();
|
||||||
}
|
}
|
||||||
|
|
||||||
fade_in_->update();
|
fade_in_->update(); // Fade ya usa tiempo interno
|
||||||
if (fade_in_->hasEnded()) {
|
if (fade_in_->hasEnded()) {
|
||||||
Audio::get()->playMusic("credits.ogg");
|
Audio::get()->playMusic("credits.ogg");
|
||||||
}
|
}
|
||||||
|
|
||||||
fade_out_->update();
|
fade_out_->update(); // Fade ya usa tiempo interno
|
||||||
if (fade_out_->hasEnded()) {
|
if (fade_out_->hasEnded()) {
|
||||||
Section::name = Section::Name::HI_SCORE_TABLE;
|
Section::name = Section::Name::HI_SCORE_TABLE;
|
||||||
}
|
}
|
||||||
@@ -503,10 +545,10 @@ void Credits::cycleColors() {
|
|||||||
tiled_bg_->setColor(color_);
|
tiled_bg_->setColor(color_);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Actualza los jugadores
|
// Actualza los jugadores (time-based)
|
||||||
void Credits::updatePlayers() {
|
void Credits::updatePlayers(float deltaTime) {
|
||||||
for (auto &player : players_) {
|
for (auto &player : players_) {
|
||||||
player->update();
|
player->update(deltaTime);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -25,6 +25,11 @@ class Credits {
|
|||||||
// --- Bucle principal ---
|
// --- Bucle principal ---
|
||||||
void run();
|
void run();
|
||||||
|
|
||||||
|
private:
|
||||||
|
// --- Métodos del bucle principal ---
|
||||||
|
void update(float deltaTime); // Actualización principal de la lógica (time-based)
|
||||||
|
auto calculateDeltaTime() -> float; // Calcula el deltatime
|
||||||
|
|
||||||
private:
|
private:
|
||||||
// --- Constantes de clase ---
|
// --- Constantes de clase ---
|
||||||
static constexpr int PLAY_AREA_HEIGHT = 200;
|
static constexpr int PLAY_AREA_HEIGHT = 200;
|
||||||
@@ -41,10 +46,10 @@ class Credits {
|
|||||||
SDL_Texture *canvas_; // Textura donde se dibuja todo
|
SDL_Texture *canvas_; // Textura donde se dibuja todo
|
||||||
|
|
||||||
// --- Temporización y contadores ---
|
// --- Temporización y contadores ---
|
||||||
Uint64 ticks_ = 0; // Control de velocidad del programa
|
Uint64 last_time_ = 0; // Último tiempo registrado para deltaTime
|
||||||
Uint32 counter_ = 0; // Contador principal de lógica
|
float counter_ = 0; // Contador principal de lógica
|
||||||
Uint32 counter_pre_fade_ = 0; // Activación del fundido final
|
float counter_pre_fade_ = 0; // Activación del fundido final
|
||||||
Uint32 counter_prevent_endless_ = 0; // Prevención de bucle infinito
|
float counter_prevent_endless_ = 0; // Prevención de bucle infinito
|
||||||
|
|
||||||
// --- Variables de estado ---
|
// --- Variables de estado ---
|
||||||
bool fading_ = false; // Estado del fade final
|
bool fading_ = false; // Estado del fade final
|
||||||
@@ -101,8 +106,6 @@ class Credits {
|
|||||||
// Borde para la ventana
|
// Borde para la ventana
|
||||||
SDL_FRect border_rect_ = play_area_; // Delimitador de ventana
|
SDL_FRect border_rect_ = play_area_; // Delimitador de ventana
|
||||||
|
|
||||||
// --- Métodos del bucle principal ---
|
|
||||||
void update(); // Actualización principal de la lógica
|
|
||||||
void render(); // Renderizado de la escena
|
void render(); // Renderizado de la escena
|
||||||
static void checkEvents(); // Manejo de eventos
|
static void checkEvents(); // Manejo de eventos
|
||||||
void checkInput(); // Procesamiento de entrada
|
void checkInput(); // Procesamiento de entrada
|
||||||
@@ -110,19 +113,23 @@ class Credits {
|
|||||||
// --- Métodos de renderizado ---
|
// --- Métodos de renderizado ---
|
||||||
void fillTextTexture(); // Crear textura de texto de créditos
|
void fillTextTexture(); // Crear textura de texto de créditos
|
||||||
void fillCanvas(); // Renderizar todos los sprites y fondos
|
void fillCanvas(); // Renderizar todos los sprites y fondos
|
||||||
void updateTextureDstRects(); // Actualizar destinos de texturas
|
|
||||||
void renderPlayers(); // Renderiza los jugadores
|
void renderPlayers(); // Renderiza los jugadores
|
||||||
|
|
||||||
// --- Métodos de lógica del juego ---
|
// --- Métodos de lógica del juego ---
|
||||||
void throwBalloons(); // Lanzar globos al escenario
|
void throwBalloons(); // Lanzar globos al escenario (frame-based)
|
||||||
void initPlayers(); // Inicializar jugadores
|
void throwBalloons(float deltaTime); // Lanzar globos al escenario (time-based)
|
||||||
void updateAllFades(); // Actualizar estados de fade
|
void initPlayers(); // Inicializar jugadores
|
||||||
void cycleColors(); // Cambiar colores de fondo
|
void updateAllFades(); // Actualizar estados de fade (frame-based)
|
||||||
void updatePlayers(); // Actualza los jugadores
|
void updateAllFades(float deltaTime); // Actualizar estados de fade (time-based)
|
||||||
|
void cycleColors(); // Cambiar colores de fondo
|
||||||
|
void updatePlayers(float deltaTime); // Actualza los jugadores (time-based)
|
||||||
|
|
||||||
// --- Métodos de interfaz ---
|
// --- Métodos de interfaz ---
|
||||||
void updateBlackRects(); // Actualizar rectángulos negros (letterbox)
|
void updateBlackRects(); // Actualizar rectángulos negros (letterbox) (frame-based)
|
||||||
void updateRedRect(); // Actualizar rectángulo rojo (borde)
|
void updateBlackRects(float deltaTime); // Actualizar rectángulos negros (letterbox) (time-based)
|
||||||
|
void updateRedRect(); // Actualizar rectángulo rojo (borde)
|
||||||
|
void updateTextureDstRects(); // Actualizar destinos de texturas (frame-based)
|
||||||
|
void updateTextureDstRects(float deltaTime); // Actualizar destinos de texturas (time-based)
|
||||||
|
|
||||||
// --- Métodos de audio ---
|
// --- Métodos de audio ---
|
||||||
static void setVolume(int amount); // Establecer volumen
|
static void setVolume(int amount); // Establecer volumen
|
||||||
|
|||||||
@@ -49,7 +49,18 @@
|
|||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
Game::Game(Player::Id player_id, int current_stage, bool demo)
|
Game::Game(Player::Id player_id, int current_stage, bool demo)
|
||||||
: renderer_(Screen::get()->getRenderer()), screen_(Screen::get()), input_(Input::get()), canvas_(SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, param.game.play_area.rect.w, param.game.play_area.rect.h)), pause_manager_(std::make_unique<PauseManager>([this](bool is_paused) { onPauseStateChanged(is_paused); })), stage_manager_(std::make_unique<StageManager>()), balloon_manager_(std::make_unique<BalloonManager>(stage_manager_.get())), background_(std::make_unique<Background>(stage_manager_->getPowerNeededToReachStage(stage_manager_->getTotalStages() - 1))), fade_in_(std::make_unique<Fade>()), fade_out_(std::make_unique<Fade>()), tabe_(std::make_unique<Tabe>()), hit_(Hit(Resource::get()->getTexture("hit.png"))) {
|
: renderer_(Screen::get()->getRenderer()),
|
||||||
|
screen_(Screen::get()),
|
||||||
|
input_(Input::get()),
|
||||||
|
canvas_(SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, param.game.play_area.rect.w, param.game.play_area.rect.h)),
|
||||||
|
pause_manager_(std::make_unique<PauseManager>([this](bool is_paused) { onPauseStateChanged(is_paused); })),
|
||||||
|
stage_manager_(std::make_unique<StageManager>()),
|
||||||
|
balloon_manager_(std::make_unique<BalloonManager>(stage_manager_.get())),
|
||||||
|
background_(std::make_unique<Background>(stage_manager_->getPowerNeededToReachStage(stage_manager_->getTotalStages() - 1))),
|
||||||
|
fade_in_(std::make_unique<Fade>()),
|
||||||
|
fade_out_(std::make_unique<Fade>()),
|
||||||
|
tabe_(std::make_unique<Tabe>()),
|
||||||
|
hit_(Hit(Resource::get()->getTexture("hit.png"))) {
|
||||||
// Pasa variables
|
// Pasa variables
|
||||||
demo_.enabled = demo;
|
demo_.enabled = demo;
|
||||||
|
|
||||||
@@ -68,7 +79,7 @@ Game::Game(Player::Id player_id, int current_stage, bool demo)
|
|||||||
scoreboard_ = Scoreboard::get();
|
scoreboard_ = Scoreboard::get();
|
||||||
|
|
||||||
fade_in_->setColor(param.fade.color);
|
fade_in_->setColor(param.fade.color);
|
||||||
fade_in_->setPreDuration(demo_.enabled ? 500 : 0);
|
fade_in_->setPreDuration(demo_.enabled ? static_cast<int>(DEMO_FADE_PRE_DURATION_S * 1000) : 0);
|
||||||
fade_in_->setPostDuration(0);
|
fade_in_->setPostDuration(0);
|
||||||
fade_in_->setType(Fade::Type::RANDOM_SQUARE2);
|
fade_in_->setType(Fade::Type::RANDOM_SQUARE2);
|
||||||
fade_in_->setMode(Fade::Mode::IN);
|
fade_in_->setMode(Fade::Mode::IN);
|
||||||
@@ -200,9 +211,9 @@ void Game::updateHiScore() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Actualiza las variables del jugador
|
// Actualiza las variables del jugador
|
||||||
void Game::updatePlayers() {
|
void Game::updatePlayers(float deltaTime) {
|
||||||
for (auto &player : players_) {
|
for (auto &player : players_) {
|
||||||
player->update();
|
player->update(deltaTime);
|
||||||
|
|
||||||
if (player->isPlaying()) {
|
if (player->isPlaying()) {
|
||||||
// Comprueba la colisión entre el jugador y los globos
|
// Comprueba la colisión entre el jugador y los globos
|
||||||
@@ -211,7 +222,7 @@ void Game::updatePlayers() {
|
|||||||
// Si hay colisión
|
// Si hay colisión
|
||||||
if (balloon) {
|
if (balloon) {
|
||||||
// Si el globo está parado y el temporizador activo, lo explota
|
// Si el globo está parado y el temporizador activo, lo explota
|
||||||
if (balloon->isStopped() && time_stopped_counter_ > 0) {
|
if (balloon->isStopped() && time_stopped_timer_ > 0) {
|
||||||
balloon_manager_->popBalloon(balloon);
|
balloon_manager_->popBalloon(balloon);
|
||||||
}
|
}
|
||||||
// En caso contrario, el jugador ha sido golpeado por un globo activo
|
// En caso contrario, el jugador ha sido golpeado por un globo activo
|
||||||
@@ -271,7 +282,7 @@ void Game::updateStage() {
|
|||||||
// Efectos de cambio de fase
|
// Efectos de cambio de fase
|
||||||
playSound("stage_change.wav");
|
playSound("stage_change.wav");
|
||||||
balloon_manager_->resetBalloonSpeed();
|
balloon_manager_->resetBalloonSpeed();
|
||||||
screen_->flash(Colors::FLASH, 3);
|
screen_->flash(Colors::FLASH, 0.05F);
|
||||||
screen_->shake();
|
screen_->shake();
|
||||||
|
|
||||||
// Obtener datos de la nueva fase
|
// Obtener datos de la nueva fase
|
||||||
@@ -285,11 +296,11 @@ void Game::updateStage() {
|
|||||||
if (current_stage_index == total_stages - 1) { // Penúltima fase (será la última)
|
if (current_stage_index == total_stages - 1) { // Penúltima fase (será la última)
|
||||||
createMessage(paths, Resource::get()->getTexture("game_text_last_stage"));
|
createMessage(paths, Resource::get()->getTexture("game_text_last_stage"));
|
||||||
} else {
|
} else {
|
||||||
auto text = Resource::get()->getText("04b_25_2x");
|
auto text = Resource::get()->getText("04b_25_2x_enhanced");
|
||||||
const std::string CAPTION = Lang::getText("[GAME_TEXT] 2") +
|
const std::string CAPTION = Lang::getText("[GAME_TEXT] 2") +
|
||||||
std::to_string(total_stages - current_stage_index) +
|
std::to_string(total_stages - current_stage_index) +
|
||||||
Lang::getText("[GAME_TEXT] 2A");
|
Lang::getText("[GAME_TEXT] 2A");
|
||||||
createMessage(paths, text->writeToTexture(CAPTION, 1, -4));
|
createMessage(paths, text->writeDXToTexture(Text::STROKE, CAPTION, -4, Colors::NO_COLOR_MOD, 1, param.game.item_text_outline_color));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -301,31 +312,28 @@ void Game::updateStage() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Actualiza el estado de fin de la partida
|
// Actualiza el estado de fin de la partida
|
||||||
void Game::updateGameStateGameOver() {
|
void Game::updateGameStateGameOver(float deltaTime) {
|
||||||
fade_out_->update();
|
fade_out_->update();
|
||||||
updatePlayers();
|
updatePlayers(deltaTime);
|
||||||
updateScoreboard();
|
updateScoreboard();
|
||||||
updateBackground();
|
updateBackground(deltaTime);
|
||||||
balloon_manager_->update();
|
balloon_manager_->update(deltaTime);
|
||||||
tabe_->update();
|
tabe_->update(deltaTime);
|
||||||
updateBullets();
|
updateBullets(deltaTime);
|
||||||
updateItems();
|
updateItems(deltaTime);
|
||||||
updateSmartSprites();
|
updateSmartSprites(deltaTime);
|
||||||
updatePathSprites();
|
updatePathSprites(deltaTime);
|
||||||
updateTimeStopped();
|
updateTimeStopped(deltaTime);
|
||||||
checkBulletCollision();
|
checkBulletCollision();
|
||||||
cleanVectors();
|
cleanVectors();
|
||||||
|
|
||||||
if (game_over_counter_ > 0) {
|
if (game_over_timer_ < GAME_OVER_DURATION_S) {
|
||||||
if (game_over_counter_ == GAME_OVER_COUNTER) {
|
handleGameOverEvents(); // Maneja eventos al inicio
|
||||||
createMessage({paths_.at(2), paths_.at(3)}, Resource::get()->getTexture("game_text_game_over"));
|
|
||||||
Audio::get()->fadeOutMusic(1000);
|
|
||||||
balloon_manager_->setBouncingSounds(true);
|
|
||||||
}
|
|
||||||
|
|
||||||
game_over_counter_--;
|
game_over_timer_ += deltaTime; // Incremento time-based
|
||||||
|
|
||||||
if (game_over_counter_ == 150) {
|
constexpr float FADE_TRIGGER_S = GAME_OVER_DURATION_S - 2.5f; // 2.5 segundos antes del final
|
||||||
|
if (game_over_timer_ >= FADE_TRIGGER_S && !fade_out_->isEnabled()) {
|
||||||
fade_out_->activate();
|
fade_out_->activate();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -338,7 +346,7 @@ void Game::updateGameStateGameOver() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (fade_out_->hasEnded()) {
|
if (fade_out_->hasEnded()) {
|
||||||
if (game_completed_counter_ > 0) {
|
if (game_completed_timer_ > 0) {
|
||||||
Section::name = Section::Name::CREDITS; // Los jugadores han completado el juego
|
Section::name = Section::Name::CREDITS; // Los jugadores han completado el juego
|
||||||
} else {
|
} else {
|
||||||
Section::name = Section::Name::HI_SCORE_TABLE; // La partida ha terminado con la derrota de los jugadores
|
Section::name = Section::Name::HI_SCORE_TABLE; // La partida ha terminado con la derrota de los jugadores
|
||||||
@@ -352,64 +360,28 @@ void Game::updateGameStateGameOver() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Gestiona eventos para el estado del final del juego
|
// Gestiona eventos para el estado del final del juego
|
||||||
void Game::updateGameStateCompleted() {
|
void Game::updateGameStateCompleted(float deltaTime) {
|
||||||
constexpr int START_CELEBRATIONS = 400;
|
updatePlayers(deltaTime);
|
||||||
constexpr int END_CELEBRATIONS = START_CELEBRATIONS + 300;
|
|
||||||
|
|
||||||
updatePlayers();
|
|
||||||
updateScoreboard();
|
updateScoreboard();
|
||||||
updateBackground();
|
updateBackground(deltaTime);
|
||||||
balloon_manager_->update();
|
balloon_manager_->update(deltaTime);
|
||||||
tabe_->update();
|
tabe_->update(deltaTime);
|
||||||
updateBullets();
|
updateBullets(deltaTime);
|
||||||
updateItems();
|
updateItems(deltaTime);
|
||||||
updateSmartSprites();
|
updateSmartSprites(deltaTime);
|
||||||
updatePathSprites();
|
updatePathSprites(deltaTime);
|
||||||
cleanVectors();
|
cleanVectors();
|
||||||
|
|
||||||
// Para la música y elimina todos los globos e items
|
// Maneja eventos del juego completado
|
||||||
if (game_completed_counter_ == 0) {
|
handleGameCompletedEvents();
|
||||||
stopMusic(); // Detiene la música
|
|
||||||
balloon_manager_->destroyAllBalloons(); // Destruye a todos los globos
|
|
||||||
playSound("power_ball_explosion.wav"); // Sonido de destruir todos los globos
|
|
||||||
destroyAllItems(); // Destruye todos los items
|
|
||||||
background_->setAlpha(0); // Elimina el tono rojo de las últimas pantallas
|
|
||||||
}
|
|
||||||
|
|
||||||
// Comienza las celebraciones
|
|
||||||
// Muestra el mensaje de felicitación y da los puntos a los jugadores
|
|
||||||
if (game_completed_counter_ == START_CELEBRATIONS) {
|
|
||||||
createMessage({paths_.at(4), paths_.at(5)}, Resource::get()->getTexture("game_text_congratulations"));
|
|
||||||
createMessage({paths_.at(6), paths_.at(7)}, Resource::get()->getTexture("game_text_1000000_points"));
|
|
||||||
|
|
||||||
for (auto &player : players_) {
|
|
||||||
if (player->isPlaying()) {
|
|
||||||
player->addScore(1000000, Options::settings.hi_score_table.back().score);
|
|
||||||
player->setPlayingState(Player::State::CELEBRATING);
|
|
||||||
} else {
|
|
||||||
player->setPlayingState(Player::State::GAME_OVER);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
updateHiScore();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Termina las celebraciones
|
|
||||||
if (game_completed_counter_ == END_CELEBRATIONS) {
|
|
||||||
for (auto &player : players_) {
|
|
||||||
if (player->isCelebrating()) {
|
|
||||||
player->setPlayingState(player->qualifiesForHighScore() ? Player::State::ENTERING_NAME_GAME_COMPLETED : Player::State::LEAVING_SCREEN);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Si los jugadores ya no estan y no quedan mensajes en pantalla
|
// Si los jugadores ya no estan y no quedan mensajes en pantalla
|
||||||
if (allPlayersAreGameOver() && path_sprites_.empty()) {
|
if (allPlayersAreGameOver() && path_sprites_.empty()) {
|
||||||
setState(State::GAME_OVER);
|
setState(State::GAME_OVER);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Incrementa el contador al final
|
// Incrementa el acumulador al final
|
||||||
++game_completed_counter_;
|
game_completed_timer_ += deltaTime;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba el estado del juego
|
// Comprueba el estado del juego
|
||||||
@@ -606,6 +578,7 @@ void Game::handleItemDrop(const std::shared_ptr<Balloon> &balloon, const std::sh
|
|||||||
|
|
||||||
if (DROPPED_ITEM != ItemType::COFFEE_MACHINE) {
|
if (DROPPED_ITEM != ItemType::COFFEE_MACHINE) {
|
||||||
createItem(DROPPED_ITEM, balloon->getPosX(), balloon->getPosY());
|
createItem(DROPPED_ITEM, balloon->getPosX(), balloon->getPosY());
|
||||||
|
playSound("item_drop.wav");
|
||||||
} else {
|
} else {
|
||||||
createItem(DROPPED_ITEM, player->getPosX(), param.game.game_area.rect.y - Item::COFFEE_MACHINE_HEIGHT);
|
createItem(DROPPED_ITEM, player->getPosX(), param.game.game_area.rect.y - Item::COFFEE_MACHINE_HEIGHT);
|
||||||
coffee_machine_enabled_ = true;
|
coffee_machine_enabled_ = true;
|
||||||
@@ -624,9 +597,9 @@ void Game::handleBalloonDestruction(std::shared_ptr<Balloon> balloon, const std:
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Mueve las balas activas
|
// Mueve las balas activas
|
||||||
void Game::updateBullets() {
|
void Game::updateBullets(float deltaTime) {
|
||||||
for (auto &bullet : bullets_) {
|
for (auto &bullet : bullets_) {
|
||||||
if (bullet->update() == BulletMoveStatus::OUT) {
|
if (bullet->update(deltaTime) == BulletMoveStatus::OUT) {
|
||||||
getPlayer(bullet->getOwner())->decScoreMultiplier();
|
getPlayer(bullet->getOwner())->decScoreMultiplier();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -656,13 +629,13 @@ void Game::freeBullets() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Actualiza los items
|
// Actualiza los items
|
||||||
void Game::updateItems() {
|
void Game::updateItems(float deltaTime) {
|
||||||
for (auto &item : items_) {
|
for (auto &item : items_) {
|
||||||
if (item->isEnabled()) {
|
if (item->isEnabled()) {
|
||||||
item->update();
|
item->update(deltaTime);
|
||||||
if (item->isOnFloor()) {
|
if (item->isOnFloor()) {
|
||||||
playSound("title.wav");
|
playSound("title.wav");
|
||||||
screen_->shake(1, 2, 4);
|
screen_->shake(1, 0.033f, 0.067f); // desp=1, delay=0.033s, length=0.067s
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -733,7 +706,6 @@ auto Game::dropItem() -> ItemType {
|
|||||||
// Crea un objeto item
|
// Crea un objeto item
|
||||||
void Game::createItem(ItemType type, float x, float y) {
|
void Game::createItem(ItemType type, float x, float y) {
|
||||||
items_.emplace_back(std::make_unique<Item>(type, x, y, param.game.play_area.rect, item_textures_[static_cast<int>(type) - 1], item_animations_[static_cast<int>(type) - 1]));
|
items_.emplace_back(std::make_unique<Item>(type, x, y, param.game.play_area.rect, item_textures_[static_cast<int>(type) - 1], item_animations_[static_cast<int>(type) - 1]));
|
||||||
playSound("item_drop.wav");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Vacia el vector de items
|
// Vacia el vector de items
|
||||||
@@ -765,8 +737,8 @@ void Game::createItemText(int x, const std::shared_ptr<Texture> &texture) {
|
|||||||
path_sprites_.back()->setWidth(W);
|
path_sprites_.back()->setWidth(W);
|
||||||
path_sprites_.back()->setHeight(H);
|
path_sprites_.back()->setHeight(H);
|
||||||
path_sprites_.back()->setSpriteClip({0, 0, static_cast<float>(W), static_cast<float>(H)});
|
path_sprites_.back()->setSpriteClip({0, 0, static_cast<float>(W), static_cast<float>(H)});
|
||||||
path_sprites_.back()->addPath(Y0, Y1, PathType::VERTICAL, x, 100, easeOutQuint, 0);
|
path_sprites_.back()->addPath(Y0, Y1, PathType::VERTICAL, x, 1.667f, easeOutQuint, 0); // 100 frames → 1.667s
|
||||||
path_sprites_.back()->addPath(Y1, Y2, PathType::VERTICAL, x, 80, easeInQuint, 0);
|
path_sprites_.back()->addPath(Y1, Y2, PathType::VERTICAL, x, 1.333f, easeInQuint, 0); // 80 frames → 1.333s
|
||||||
path_sprites_.back()->enable();
|
path_sprites_.back()->enable();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -811,14 +783,14 @@ void Game::throwCoffee(int x, int y) {
|
|||||||
smart_sprites_.back()->setPosY(y - 8);
|
smart_sprites_.back()->setPosY(y - 8);
|
||||||
smart_sprites_.back()->setWidth(param.game.item_size);
|
smart_sprites_.back()->setWidth(param.game.item_size);
|
||||||
smart_sprites_.back()->setHeight(param.game.item_size);
|
smart_sprites_.back()->setHeight(param.game.item_size);
|
||||||
smart_sprites_.back()->setVelX(-1.0F + ((rand() % 5) * 0.5F));
|
smart_sprites_.back()->setVelX((-1.0F + ((rand() % 5) * 0.5F)) * 60.0f); // Convertir a pixels/segundo
|
||||||
smart_sprites_.back()->setVelY(-4.0F);
|
smart_sprites_.back()->setVelY(-4.0F * 60.0f); // Convertir a pixels/segundo
|
||||||
smart_sprites_.back()->setAccelX(0.0F);
|
smart_sprites_.back()->setAccelX(0.0F);
|
||||||
smart_sprites_.back()->setAccelY(0.2F);
|
smart_sprites_.back()->setAccelY(0.2F * 60.0f * 60.0f); // Convertir a pixels/segundo² (0.2 × 60²)
|
||||||
smart_sprites_.back()->setDestX(x + (smart_sprites_.back()->getVelX() * 50));
|
smart_sprites_.back()->setDestX(x + (smart_sprites_.back()->getVelX() * 50));
|
||||||
smart_sprites_.back()->setDestY(param.game.height + 1);
|
smart_sprites_.back()->setDestY(param.game.height + 1);
|
||||||
smart_sprites_.back()->setEnabled(true);
|
smart_sprites_.back()->setEnabled(true);
|
||||||
smart_sprites_.back()->setFinishedCounter(1);
|
smart_sprites_.back()->setFinishedDelay(0.0F);
|
||||||
smart_sprites_.back()->setSpriteClip(0, param.game.item_size, param.game.item_size, param.game.item_size);
|
smart_sprites_.back()->setSpriteClip(0, param.game.item_size, param.game.item_size, param.game.item_size);
|
||||||
smart_sprites_.back()->setRotatingCenter({param.game.item_size / 2, param.game.item_size / 2});
|
smart_sprites_.back()->setRotatingCenter({param.game.item_size / 2, param.game.item_size / 2});
|
||||||
smart_sprites_.back()->setRotate(true);
|
smart_sprites_.back()->setRotate(true);
|
||||||
@@ -827,9 +799,9 @@ void Game::throwCoffee(int x, int y) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Actualiza los SmartSprites
|
// Actualiza los SmartSprites
|
||||||
void Game::updateSmartSprites() {
|
void Game::updateSmartSprites(float deltaTime) {
|
||||||
for (auto &sprite : smart_sprites_) {
|
for (auto &sprite : smart_sprites_) {
|
||||||
sprite->update();
|
sprite->update(deltaTime);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -841,9 +813,9 @@ void Game::renderSmartSprites() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Actualiza los PathSprites
|
// Actualiza los PathSprites
|
||||||
void Game::updatePathSprites() {
|
void Game::updatePathSprites(float deltaTime) {
|
||||||
for (auto &sprite : path_sprites_) {
|
for (auto &sprite : path_sprites_) {
|
||||||
sprite->update();
|
sprite->update(deltaTime);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -885,42 +857,69 @@ void Game::handlePlayerCollision(std::shared_ptr<Player> &player, std::shared_pt
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Actualiza y comprueba el valor de la variable
|
// Actualiza el estado del tiempo detenido
|
||||||
void Game::updateTimeStopped() {
|
void Game::updateTimeStopped(float deltaTime) {
|
||||||
if (time_stopped_counter_ > 0) {
|
static constexpr float WARNING_THRESHOLD_S = 2.0f; // 120 frames a 60fps → segundos
|
||||||
time_stopped_counter_--;
|
static constexpr float CLOCK_SOUND_INTERVAL_S = 0.5f; // 30 frames a 60fps → segundos
|
||||||
if (time_stopped_counter_ > 120) {
|
static constexpr float COLOR_FLASH_INTERVAL_S = 0.25f; // 15 frames a 60fps → segundos
|
||||||
if (time_stopped_counter_ % 30 == 0) {
|
|
||||||
|
if (time_stopped_timer_ > 0) {
|
||||||
|
time_stopped_timer_ -= deltaTime;
|
||||||
|
|
||||||
|
// Fase de advertencia (últimos 2 segundos)
|
||||||
|
if (time_stopped_timer_ <= WARNING_THRESHOLD_S) {
|
||||||
|
static float last_sound_time = 0.0f;
|
||||||
|
static bool color_flash_sound_played = false;
|
||||||
|
static bool warning_phase_started = false;
|
||||||
|
|
||||||
|
// CLAC al entrar en fase de advertencia
|
||||||
|
if (!warning_phase_started) {
|
||||||
playSound("clock.wav");
|
playSound("clock.wav");
|
||||||
|
warning_phase_started = true;
|
||||||
|
last_sound_time = 0.0f; // Reset para empezar el ciclo rápido
|
||||||
}
|
}
|
||||||
} else {
|
|
||||||
if (time_stopped_counter_ % 30 == 0) {
|
last_sound_time += deltaTime;
|
||||||
|
|
||||||
|
if (last_sound_time >= CLOCK_SOUND_INTERVAL_S) {
|
||||||
balloon_manager_->normalColorsToAllBalloons();
|
balloon_manager_->normalColorsToAllBalloons();
|
||||||
playSound("clock.wav");
|
playSound("clock.wav");
|
||||||
} else if (time_stopped_counter_ % 30 == 15) {
|
last_sound_time = 0.0f;
|
||||||
|
color_flash_sound_played = false; // Reset flag para el próximo intervalo
|
||||||
|
} else if (last_sound_time >= COLOR_FLASH_INTERVAL_S && !color_flash_sound_played) {
|
||||||
balloon_manager_->reverseColorsToAllBalloons();
|
balloon_manager_->reverseColorsToAllBalloons();
|
||||||
playSound("clock.wav");
|
playSound("clock.wav");
|
||||||
|
color_flash_sound_played = true; // Evita que suene múltiples veces
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Fase normal - solo sonido ocasional
|
||||||
|
static float sound_timer = 0.0f;
|
||||||
|
sound_timer += deltaTime;
|
||||||
|
if (sound_timer >= CLOCK_SOUND_INTERVAL_S) {
|
||||||
|
playSound("clock.wav");
|
||||||
|
sound_timer = 0.0f;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
|
||||||
disableTimeStopItem();
|
// Si el timer llega a 0 o menos, desactivar
|
||||||
|
if (time_stopped_timer_ <= 0) {
|
||||||
|
playSound("clock.wav"); // CLAC final
|
||||||
|
disableTimeStopItem();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void Game::update() {
|
// Actualiza toda la lógica del juego
|
||||||
if (SDL_GetTicks() - ticks_ > param.game.speed) {
|
void Game::update(float deltaTime) {
|
||||||
ticks_ = SDL_GetTicks();
|
screen_->update(deltaTime); // Actualiza el objeto screen
|
||||||
screen_->update();
|
Audio::update(); // Actualiza el objeto audio
|
||||||
|
|
||||||
updateDemo();
|
updateDemo();
|
||||||
#ifdef RECORDING
|
#ifdef RECORDING
|
||||||
updateRecording();
|
updateRecording();
|
||||||
#endif
|
#endif
|
||||||
updateGameStates();
|
updateGameStates(deltaTime);
|
||||||
fillCanvas();
|
fillCanvas();
|
||||||
}
|
|
||||||
|
|
||||||
Audio::update();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Dibuja el juego
|
// Dibuja el juego
|
||||||
@@ -936,26 +935,26 @@ void Game::render() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Actualiza los estados del juego
|
// Actualiza los estados del juego
|
||||||
void Game::updateGameStates() {
|
void Game::updateGameStates(float deltaTime) {
|
||||||
if (!pause_manager_->isPaused()) {
|
if (!pause_manager_->isPaused()) {
|
||||||
switch (state_) {
|
switch (state_) {
|
||||||
case State::FADE_IN:
|
case State::FADE_IN:
|
||||||
updateGameStateFadeIn();
|
updateGameStateFadeIn(deltaTime);
|
||||||
break;
|
break;
|
||||||
case State::ENTERING_PLAYER:
|
case State::ENTERING_PLAYER:
|
||||||
updateGameStateEnteringPlayer();
|
updateGameStateEnteringPlayer(deltaTime);
|
||||||
break;
|
break;
|
||||||
case State::SHOWING_GET_READY_MESSAGE:
|
case State::SHOWING_GET_READY_MESSAGE:
|
||||||
updateGameStateShowingGetReadyMessage();
|
updateGameStateShowingGetReadyMessage(deltaTime);
|
||||||
break;
|
break;
|
||||||
case State::PLAYING:
|
case State::PLAYING:
|
||||||
updateGameStatePlaying();
|
updateGameStatePlaying(deltaTime);
|
||||||
break;
|
break;
|
||||||
case State::COMPLETED:
|
case State::COMPLETED:
|
||||||
updateGameStateCompleted();
|
updateGameStateCompleted(deltaTime);
|
||||||
break;
|
break;
|
||||||
case State::GAME_OVER:
|
case State::GAME_OVER:
|
||||||
updateGameStateGameOver();
|
updateGameStateGameOver(deltaTime);
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
break;
|
break;
|
||||||
@@ -964,8 +963,8 @@ void Game::updateGameStates() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Actualiza el fondo
|
// Actualiza el fondo
|
||||||
void Game::updateBackground() {
|
void Game::updateBackground(float deltaTime) {
|
||||||
background_->update();
|
background_->update(deltaTime);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Dibuja los elementos de la zona de juego en su textura
|
// Dibuja los elementos de la zona de juego en su textura
|
||||||
@@ -994,23 +993,34 @@ void Game::fillCanvas() {
|
|||||||
void Game::enableTimeStopItem() {
|
void Game::enableTimeStopItem() {
|
||||||
balloon_manager_->stopAllBalloons();
|
balloon_manager_->stopAllBalloons();
|
||||||
balloon_manager_->reverseColorsToAllBalloons();
|
balloon_manager_->reverseColorsToAllBalloons();
|
||||||
time_stopped_counter_ = TIME_STOPPED_COUNTER;
|
time_stopped_timer_ = TIME_STOPPED_DURATION_S;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Deshabilita el efecto del item de detener el tiempo
|
// Deshabilita el efecto del item de detener el tiempo
|
||||||
void Game::disableTimeStopItem() {
|
void Game::disableTimeStopItem() {
|
||||||
time_stopped_counter_ = 0;
|
time_stopped_timer_ = 0;
|
||||||
balloon_manager_->startAllBalloons();
|
balloon_manager_->startAllBalloons();
|
||||||
balloon_manager_->normalColorsToAllBalloons();
|
balloon_manager_->normalColorsToAllBalloons();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Calcula el deltatime en segundos
|
||||||
|
auto Game::calculateDeltaTime() -> float {
|
||||||
|
const Uint64 current_time = SDL_GetTicks();
|
||||||
|
const float delta_time_ms = static_cast<float>(current_time - last_time_);
|
||||||
|
last_time_ = current_time;
|
||||||
|
return delta_time_ms / 1000.0f; // Convertir de milisegundos a segundos
|
||||||
|
}
|
||||||
|
|
||||||
// Bucle para el juego
|
// Bucle para el juego
|
||||||
void Game::run() {
|
void Game::run() {
|
||||||
|
last_time_ = SDL_GetTicks();
|
||||||
|
|
||||||
while (Section::name == Section::Name::GAME) {
|
while (Section::name == Section::Name::GAME) {
|
||||||
#ifndef RECORDING
|
#ifndef RECORDING
|
||||||
checkInput();
|
checkInput();
|
||||||
#endif
|
#endif
|
||||||
update();
|
const float delta_time = calculateDeltaTime();
|
||||||
|
update(delta_time);
|
||||||
handleEvents(); // Tiene que ir antes del render
|
handleEvents(); // Tiene que ir antes del render
|
||||||
render();
|
render();
|
||||||
}
|
}
|
||||||
@@ -1026,7 +1036,7 @@ void Game::initPaths() {
|
|||||||
const int X1 = param.game.play_area.center_x - (W / 2);
|
const int X1 = param.game.play_area.center_x - (W / 2);
|
||||||
const int X2 = param.game.play_area.rect.w;
|
const int X2 = param.game.play_area.rect.w;
|
||||||
const int Y = param.game.play_area.center_y;
|
const int Y = param.game.play_area.center_y;
|
||||||
paths_.emplace_back(createPath(X0, X1, PathType::HORIZONTAL, Y, 80, easeOutQuint), 20);
|
paths_.emplace_back(createPath(X0, X1, PathType::HORIZONTAL, Y, 80, easeOutQuint), 0.33f); // 20 frames → segundos
|
||||||
paths_.emplace_back(createPath(X1, X2, PathType::HORIZONTAL, Y, 80, easeInQuint), 0);
|
paths_.emplace_back(createPath(X1, X2, PathType::HORIZONTAL, Y, 80, easeInQuint), 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1038,7 +1048,7 @@ void Game::initPaths() {
|
|||||||
const int Y1 = param.game.play_area.center_y - (H / 2);
|
const int Y1 = param.game.play_area.center_y - (H / 2);
|
||||||
const int Y2 = -H;
|
const int Y2 = -H;
|
||||||
const int X = param.game.play_area.center_x;
|
const int X = param.game.play_area.center_x;
|
||||||
paths_.emplace_back(createPath(Y0, Y1, PathType::VERTICAL, X, 80, easeOutQuint), 20);
|
paths_.emplace_back(createPath(Y0, Y1, PathType::VERTICAL, X, 80, easeOutQuint), 0.33f); // 20 frames → segundos
|
||||||
paths_.emplace_back(createPath(Y1, Y2, PathType::VERTICAL, X, 80, easeInQuint), 0);
|
paths_.emplace_back(createPath(Y1, Y2, PathType::VERTICAL, X, 80, easeInQuint), 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1051,7 +1061,7 @@ void Game::initPaths() {
|
|||||||
const int X1 = param.game.play_area.center_x - (W / 2);
|
const int X1 = param.game.play_area.center_x - (W / 2);
|
||||||
const int X2 = param.game.play_area.rect.w;
|
const int X2 = param.game.play_area.rect.w;
|
||||||
const int Y = param.game.play_area.center_y - (H / 2) - 20;
|
const int Y = param.game.play_area.center_y - (H / 2) - 20;
|
||||||
paths_.emplace_back(createPath(X0, X1, PathType::HORIZONTAL, Y, 80, easeOutQuint), 400);
|
paths_.emplace_back(createPath(X0, X1, PathType::HORIZONTAL, Y, 80, easeOutQuint), 6.67f); // 400 frames → segundos
|
||||||
paths_.emplace_back(createPath(X1, X2, PathType::HORIZONTAL, Y, 80, easeInQuint), 0);
|
paths_.emplace_back(createPath(X1, X2, PathType::HORIZONTAL, Y, 80, easeInQuint), 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1064,7 +1074,7 @@ void Game::initPaths() {
|
|||||||
const int X1 = param.game.play_area.center_x - (W / 2);
|
const int X1 = param.game.play_area.center_x - (W / 2);
|
||||||
const int X2 = -W;
|
const int X2 = -W;
|
||||||
const int Y = param.game.play_area.center_y + (H / 2) - 20;
|
const int Y = param.game.play_area.center_y + (H / 2) - 20;
|
||||||
paths_.emplace_back(createPath(X0, X1, PathType::HORIZONTAL, Y, 80, easeOutQuint), 400);
|
paths_.emplace_back(createPath(X0, X1, PathType::HORIZONTAL, Y, 80, easeOutQuint), 6.67f); // 400 frames → segundos
|
||||||
paths_.emplace_back(createPath(X1, X2, PathType::HORIZONTAL, Y, 80, easeInQuint), 0);
|
paths_.emplace_back(createPath(X1, X2, PathType::HORIZONTAL, Y, 80, easeInQuint), 0);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1327,7 +1337,7 @@ void Game::handleFireInput(const std::shared_ptr<Player> &player, BulletType bul
|
|||||||
cant_fire_counter = NORMAL_COOLDOWN;
|
cant_fire_counter = NORMAL_COOLDOWN;
|
||||||
}
|
}
|
||||||
|
|
||||||
player->setCantFireCounter(cant_fire_counter);
|
player->startFiringSystem(cant_fire_counter); // Sistema de disparo de dos líneas
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1371,17 +1381,27 @@ void Game::handleNormalPlayerInput(const std::shared_ptr<Player> &player) {
|
|||||||
|
|
||||||
// Procesa las entradas de disparo del jugador, permitiendo disparos automáticos si está habilitado.
|
// Procesa las entradas de disparo del jugador, permitiendo disparos automáticos si está habilitado.
|
||||||
void Game::handleFireInputs(const std::shared_ptr<Player> &player, bool autofire) {
|
void Game::handleFireInputs(const std::shared_ptr<Player> &player, bool autofire) {
|
||||||
|
if (!player) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (input_->checkAction(Input::Action::FIRE_CENTER, autofire, player->getUsesKeyboard(), player->getGamepad())) {
|
if (input_->checkAction(Input::Action::FIRE_CENTER, autofire, player->getUsesKeyboard(), player->getGamepad())) {
|
||||||
handleFireInput(player, BulletType::UP);
|
handleFireInput(player, BulletType::UP);
|
||||||
#ifdef RECORDING
|
#ifdef RECORDING
|
||||||
demo_.keys.fire = 1;
|
demo_.keys.fire = 1;
|
||||||
#endif
|
#endif
|
||||||
} else if (input_->checkAction(Input::Action::FIRE_LEFT, autofire, player->getUsesKeyboard(), player->getGamepad())) {
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (input_->checkAction(Input::Action::FIRE_LEFT, autofire, player->getUsesKeyboard(), player->getGamepad())) {
|
||||||
handleFireInput(player, BulletType::LEFT);
|
handleFireInput(player, BulletType::LEFT);
|
||||||
#ifdef RECORDING
|
#ifdef RECORDING
|
||||||
demo_.keys.fire_left = 1;
|
demo_.keys.fire_left = 1;
|
||||||
#endif
|
#endif
|
||||||
} else if (input_->checkAction(Input::Action::FIRE_RIGHT, autofire, player->getUsesKeyboard(), player->getGamepad())) {
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (input_->checkAction(Input::Action::FIRE_RIGHT, autofire, player->getUsesKeyboard(), player->getGamepad())) {
|
||||||
handleFireInput(player, BulletType::RIGHT);
|
handleFireInput(player, BulletType::RIGHT);
|
||||||
#ifdef RECORDING
|
#ifdef RECORDING
|
||||||
demo_.keys.fire_right = 1;
|
demo_.keys.fire_right = 1;
|
||||||
@@ -1395,6 +1415,7 @@ void Game::handlePlayerContinueInput(const std::shared_ptr<Player> &player) {
|
|||||||
player->setPlayingState(Player::State::RECOVER);
|
player->setPlayingState(Player::State::RECOVER);
|
||||||
player->addCredit();
|
player->addCredit();
|
||||||
sendPlayerToTheFront(player);
|
sendPlayerToTheFront(player);
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Disminuye el contador de continuación si se presiona cualquier botón de disparo.
|
// Disminuye el contador de continuación si se presiona cualquier botón de disparo.
|
||||||
@@ -1420,33 +1441,53 @@ void Game::handlePlayerWaitingInput(const std::shared_ptr<Player> &player) {
|
|||||||
void Game::handleNameInput(const std::shared_ptr<Player> &player) {
|
void Game::handleNameInput(const std::shared_ptr<Player> &player) {
|
||||||
if (input_->checkAction(Input::Action::FIRE_LEFT, Input::DO_NOT_ALLOW_REPEAT, player->getUsesKeyboard(), player->getGamepad())) {
|
if (input_->checkAction(Input::Action::FIRE_LEFT, Input::DO_NOT_ALLOW_REPEAT, player->getUsesKeyboard(), player->getGamepad())) {
|
||||||
if (player->isShowingName()) {
|
if (player->isShowingName()) {
|
||||||
player->setPlayingState(Player::State::CONTINUE);
|
player->passShowingName();
|
||||||
} else if (player->getEnterNamePositionOverflow()) {
|
return;
|
||||||
|
}
|
||||||
|
if (player->getEnterNamePositionOverflow()) {
|
||||||
player->setInput(Input::Action::START);
|
player->setInput(Input::Action::START);
|
||||||
player->setPlayingState(Player::State::SHOWING_NAME);
|
player->setPlayingState(Player::State::SHOWING_NAME);
|
||||||
|
playSound("service_menu_select.wav");
|
||||||
updateHiScoreName();
|
updateHiScoreName();
|
||||||
} else {
|
return;
|
||||||
player->setInput(Input::Action::RIGHT);
|
|
||||||
}
|
}
|
||||||
} else if (input_->checkAction(Input::Action::FIRE_CENTER, Input::DO_NOT_ALLOW_REPEAT, player->getUsesKeyboard(), player->getGamepad()) ||
|
player->setInput(Input::Action::RIGHT);
|
||||||
|
playSound("service_menu_select.wav");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (input_->checkAction(Input::Action::FIRE_CENTER, Input::DO_NOT_ALLOW_REPEAT, player->getUsesKeyboard(), player->getGamepad()) ||
|
||||||
input_->checkAction(Input::Action::FIRE_RIGHT, Input::DO_NOT_ALLOW_REPEAT, player->getUsesKeyboard(), player->getGamepad())) {
|
input_->checkAction(Input::Action::FIRE_RIGHT, Input::DO_NOT_ALLOW_REPEAT, player->getUsesKeyboard(), player->getGamepad())) {
|
||||||
if (player->isShowingName()) {
|
if (player->isShowingName()) {
|
||||||
player->setPlayingState(Player::State::CONTINUE);
|
player->passShowingName();
|
||||||
} else {
|
return;
|
||||||
player->setInput(Input::Action::LEFT);
|
|
||||||
}
|
}
|
||||||
} else if (input_->checkAction(Input::Action::UP, Input::DO_NOT_ALLOW_REPEAT, player->getUsesKeyboard(), player->getGamepad())) {
|
player->setInput(Input::Action::LEFT);
|
||||||
|
playSound("service_menu_back.wav");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (input_->checkAction(Input::Action::UP, Input::DO_NOT_ALLOW_REPEAT, player->getUsesKeyboard(), player->getGamepad())) {
|
||||||
player->setInput(Input::Action::UP);
|
player->setInput(Input::Action::UP);
|
||||||
} else if (input_->checkAction(Input::Action::DOWN, Input::DO_NOT_ALLOW_REPEAT, player->getUsesKeyboard(), player->getGamepad())) {
|
playSound("service_menu_move.wav");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (input_->checkAction(Input::Action::DOWN, Input::DO_NOT_ALLOW_REPEAT, player->getUsesKeyboard(), player->getGamepad())) {
|
||||||
player->setInput(Input::Action::DOWN);
|
player->setInput(Input::Action::DOWN);
|
||||||
} else if (input_->checkAction(Input::Action::START, Input::DO_NOT_ALLOW_REPEAT, player->getUsesKeyboard(), player->getGamepad())) {
|
playSound("service_menu_move.wav");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (input_->checkAction(Input::Action::START, Input::DO_NOT_ALLOW_REPEAT, player->getUsesKeyboard(), player->getGamepad())) {
|
||||||
if (player->isShowingName()) {
|
if (player->isShowingName()) {
|
||||||
player->setPlayingState(Player::State::CONTINUE);
|
player->passShowingName();
|
||||||
} else {
|
return;
|
||||||
player->setInput(Input::Action::START);
|
|
||||||
player->setPlayingState(Player::State::SHOWING_NAME);
|
|
||||||
updateHiScoreName();
|
|
||||||
}
|
}
|
||||||
|
player->setInput(Input::Action::START);
|
||||||
|
player->setPlayingState(Player::State::SHOWING_NAME);
|
||||||
|
playSound("service_menu_select.wav");
|
||||||
|
updateHiScoreName();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1457,20 +1498,16 @@ void Game::initDemo(Player::Id player_id) {
|
|||||||
setState(State::PLAYING);
|
setState(State::PLAYING);
|
||||||
|
|
||||||
// Aleatoriza la asignación del fichero con los datos del modo demostracion
|
// Aleatoriza la asignación del fichero con los datos del modo demostracion
|
||||||
{
|
const auto DEMO1 = rand() % 2;
|
||||||
const auto DEMO1 = rand() % 2;
|
const auto DEMO2 = (DEMO1 == 0) ? 1 : 0;
|
||||||
const auto DEMO2 = (DEMO1 == 0) ? 1 : 0;
|
demo_.data.emplace_back(Resource::get()->getDemoData(DEMO1));
|
||||||
demo_.data.emplace_back(Resource::get()->getDemoData(DEMO1));
|
demo_.data.emplace_back(Resource::get()->getDemoData(DEMO2));
|
||||||
demo_.data.emplace_back(Resource::get()->getDemoData(DEMO2));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Selecciona una pantalla al azar
|
// Selecciona una pantalla al azar
|
||||||
{
|
constexpr auto NUM_DEMOS = 3;
|
||||||
constexpr auto NUM_DEMOS = 3;
|
const auto DEMO = rand() % NUM_DEMOS;
|
||||||
const auto DEMO = rand() % NUM_DEMOS;
|
constexpr std::array<int, NUM_DEMOS> STAGES = {0, 3, 5};
|
||||||
constexpr std::array<int, NUM_DEMOS> STAGES = {0, 3, 5};
|
stage_manager_->jumpToStage(STAGES.at(DEMO));
|
||||||
stage_manager_->jumpToStage(STAGES.at(DEMO));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Activa o no al otro jugador
|
// Activa o no al otro jugador
|
||||||
if (rand() % 3 != 0) {
|
if (rand() % 3 != 0) {
|
||||||
@@ -1524,21 +1561,21 @@ void Game::initDifficultyVars() {
|
|||||||
// Variables relacionadas con la dificultad
|
// Variables relacionadas con la dificultad
|
||||||
switch (difficulty_) {
|
switch (difficulty_) {
|
||||||
case Difficulty::Code::EASY: {
|
case Difficulty::Code::EASY: {
|
||||||
balloon_manager_->setDefaultBalloonSpeed(Balloon::SPEED.at(0));
|
balloon_manager_->setDefaultBalloonSpeed(Balloon::GAME_TEMPO.at(0));
|
||||||
difficulty_score_multiplier_ = 0.5F;
|
difficulty_score_multiplier_ = 0.5F;
|
||||||
scoreboard_->setColor(param.scoreboard.easy_color);
|
scoreboard_->setColor(param.scoreboard.easy_color);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
case Difficulty::Code::NORMAL: {
|
case Difficulty::Code::NORMAL: {
|
||||||
balloon_manager_->setDefaultBalloonSpeed(Balloon::SPEED.at(0));
|
balloon_manager_->setDefaultBalloonSpeed(Balloon::GAME_TEMPO.at(0));
|
||||||
difficulty_score_multiplier_ = 1.0F;
|
difficulty_score_multiplier_ = 1.0F;
|
||||||
scoreboard_->setColor(param.scoreboard.normal_color);
|
scoreboard_->setColor(param.scoreboard.normal_color);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
case Difficulty::Code::HARD: {
|
case Difficulty::Code::HARD: {
|
||||||
balloon_manager_->setDefaultBalloonSpeed(Balloon::SPEED.at(4));
|
balloon_manager_->setDefaultBalloonSpeed(Balloon::GAME_TEMPO.at(4));
|
||||||
difficulty_score_multiplier_ = 1.5F;
|
difficulty_score_multiplier_ = 1.5F;
|
||||||
scoreboard_->setColor(param.scoreboard.hard_color);
|
scoreboard_->setColor(param.scoreboard.hard_color);
|
||||||
break;
|
break;
|
||||||
@@ -1554,60 +1591,51 @@ void Game::initDifficultyVars() {
|
|||||||
// Inicializa los jugadores
|
// Inicializa los jugadores
|
||||||
void Game::initPlayers(Player::Id player_id) {
|
void Game::initPlayers(Player::Id player_id) {
|
||||||
const int Y = param.game.play_area.rect.h - Player::HEIGHT + 1; // Se hunde un pixel para esconder el outline de los pies
|
const int Y = param.game.play_area.rect.h - Player::HEIGHT + 1; // Se hunde un pixel para esconder el outline de los pies
|
||||||
|
const Player::State STATE = demo_.enabled ? Player::State::PLAYING : Player::State::ENTERING_SCREEN;
|
||||||
|
|
||||||
// Crea al jugador uno y lo pone en modo espera
|
// Crea al jugador uno y lo pone en modo espera
|
||||||
Player::Config config_player1;
|
Player::Config config_player1{
|
||||||
config_player1.id = Player::Id::PLAYER1;
|
.id = Player::Id::PLAYER1,
|
||||||
config_player1.x = param.game.play_area.first_quarter_x - (Player::WIDTH / 2);
|
.x = param.game.play_area.first_quarter_x - (Player::WIDTH / 2),
|
||||||
config_player1.y = Y;
|
.y = Y,
|
||||||
config_player1.demo = demo_.enabled;
|
.demo = demo_.enabled,
|
||||||
config_player1.play_area = ¶m.game.play_area.rect;
|
.play_area = ¶m.game.play_area.rect,
|
||||||
config_player1.texture = player_textures_.at(0);
|
.texture = player_textures_.at(0),
|
||||||
config_player1.animations = player_animations_;
|
.animations = player_animations_,
|
||||||
config_player1.hi_score_table = &Options::settings.hi_score_table;
|
.hi_score_table = &Options::settings.hi_score_table,
|
||||||
config_player1.glowing_entry = &Options::settings.glowing_entries.at(static_cast<int>(Player::Id::PLAYER1) - 1);
|
.glowing_entry = &Options::settings.glowing_entries.at(static_cast<int>(Player::Id::PLAYER1) - 1),
|
||||||
config_player1.stage_info = stage_manager_.get();
|
.stage_info = stage_manager_.get()};
|
||||||
|
|
||||||
auto player1 = std::make_unique<Player>(config_player1);
|
auto player1 = std::make_unique<Player>(config_player1);
|
||||||
player1->setScoreBoardPanel(Scoreboard::Id::LEFT);
|
player1->setScoreBoardPanel(Scoreboard::Id::LEFT);
|
||||||
player1->setName(Lang::getText("[SCOREBOARD] 1"));
|
player1->setName(Lang::getText("[SCOREBOARD] 1"));
|
||||||
player1->setGamepad(Options::gamepad_manager.getGamepad(Player::Id::PLAYER1).instance);
|
player1->setGamepad(Options::gamepad_manager.getGamepad(Player::Id::PLAYER1).instance);
|
||||||
player1->setUsesKeyboard(Player::Id::PLAYER1 == Options::keyboard.player_id);
|
player1->setUsesKeyboard(Player::Id::PLAYER1 == Options::keyboard.player_id);
|
||||||
player1->setPlayingState(Player::State::WAITING);
|
player1->setPlayingState((player_id == Player::Id::BOTH_PLAYERS || player_id == Player::Id::PLAYER1) ? STATE : Player::State::WAITING);
|
||||||
players_.push_back(std::move(player1));
|
|
||||||
|
|
||||||
// Crea al jugador dos y lo pone en modo espera
|
// Crea al jugador dos y lo pone en modo espera
|
||||||
Player::Config config_player2;
|
Player::Config config_player2{
|
||||||
config_player2.id = Player::Id::PLAYER2;
|
.id = Player::Id::PLAYER2,
|
||||||
config_player2.x = param.game.play_area.third_quarter_x - (Player::WIDTH / 2);
|
.x = param.game.play_area.third_quarter_x - (Player::WIDTH / 2),
|
||||||
config_player2.y = Y;
|
.y = Y,
|
||||||
config_player2.demo = demo_.enabled;
|
.demo = demo_.enabled,
|
||||||
config_player2.play_area = ¶m.game.play_area.rect;
|
.play_area = ¶m.game.play_area.rect,
|
||||||
config_player2.texture = player_textures_.at(1);
|
.texture = player_textures_.at(1),
|
||||||
config_player2.animations = player_animations_;
|
.animations = player_animations_,
|
||||||
config_player2.hi_score_table = &Options::settings.hi_score_table;
|
.hi_score_table = &Options::settings.hi_score_table,
|
||||||
config_player2.glowing_entry = &Options::settings.glowing_entries.at(static_cast<int>(Player::Id::PLAYER2) - 1);
|
.glowing_entry = &Options::settings.glowing_entries.at(static_cast<int>(Player::Id::PLAYER2) - 1),
|
||||||
config_player2.stage_info = stage_manager_.get();
|
.stage_info = stage_manager_.get()};
|
||||||
|
|
||||||
auto player2 = std::make_unique<Player>(config_player2);
|
auto player2 = std::make_unique<Player>(config_player2);
|
||||||
player2->setScoreBoardPanel(Scoreboard::Id::RIGHT);
|
player2->setScoreBoardPanel(Scoreboard::Id::RIGHT);
|
||||||
player2->setName(Lang::getText("[SCOREBOARD] 2"));
|
player2->setName(Lang::getText("[SCOREBOARD] 2"));
|
||||||
player2->setGamepad(Options::gamepad_manager.getGamepad(Player::Id::PLAYER2).instance);
|
player2->setGamepad(Options::gamepad_manager.getGamepad(Player::Id::PLAYER2).instance);
|
||||||
player2->setUsesKeyboard(Player::Id::PLAYER2 == Options::keyboard.player_id);
|
player2->setUsesKeyboard(Player::Id::PLAYER2 == Options::keyboard.player_id);
|
||||||
player2->setPlayingState(Player::State::WAITING);
|
player2->setPlayingState((player_id == Player::Id::BOTH_PLAYERS || player_id == Player::Id::PLAYER2) ? STATE : Player::State::WAITING);
|
||||||
players_.push_back(std::move(player2));
|
|
||||||
|
|
||||||
// Activa el jugador que coincide con el "player_id" o ambos si es "0"
|
// Añade los jugadores al vector de forma que el jugador 1 se pinte por delante del jugador 2
|
||||||
if (player_id == Player::Id::BOTH_PLAYERS) {
|
players_.push_back(std::move(player2));
|
||||||
// Activa ambos jugadores
|
players_.push_back(std::move(player1));
|
||||||
getPlayer(Player::Id::PLAYER1)->setPlayingState(demo_.enabled ? Player::State::PLAYING : Player::State::ENTERING_SCREEN);
|
|
||||||
getPlayer(Player::Id::PLAYER2)->setPlayingState(demo_.enabled ? Player::State::PLAYING : Player::State::ENTERING_SCREEN);
|
|
||||||
} else {
|
|
||||||
// Activa el jugador elegido
|
|
||||||
auto player = getPlayer(player_id);
|
|
||||||
player->setPlayingState(demo_.enabled ? Player::State::PLAYING : Player::State::ENTERING_SCREEN);
|
|
||||||
sendPlayerToTheFront(player);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Registra los jugadores en Options
|
// Registra los jugadores en Options
|
||||||
for (const auto &player : players_) {
|
for (const auto &player : players_) {
|
||||||
@@ -1647,9 +1675,12 @@ void Game::updateDemo() {
|
|||||||
fade_in_->update();
|
fade_in_->update();
|
||||||
fade_out_->update();
|
fade_out_->update();
|
||||||
|
|
||||||
// Incrementa el contador de la demo
|
// Incrementa el contador de la demo cada 1/60 segundos (16.67ms)
|
||||||
if (demo_.counter < TOTAL_DEMO_DATA) {
|
static float demo_frame_timer = 0.0f;
|
||||||
|
demo_frame_timer += calculateDeltaTime();
|
||||||
|
if (demo_frame_timer >= 0.01667f && demo_.counter < TOTAL_DEMO_DATA) {
|
||||||
demo_.counter++;
|
demo_.counter++;
|
||||||
|
demo_frame_timer -= 0.01667f; // Mantener precisión acumulada
|
||||||
}
|
}
|
||||||
|
|
||||||
// Activa el fundido antes de acabar con los datos de la demo
|
// Activa el fundido antes de acabar con los datos de la demo
|
||||||
@@ -1673,9 +1704,13 @@ void Game::updateRecording() {
|
|||||||
// Solo mira y guarda el input en cada update
|
// Solo mira y guarda el input en cada update
|
||||||
checkInput();
|
checkInput();
|
||||||
|
|
||||||
// Incrementa el contador de la demo
|
// Incrementa el contador de la demo cada 1/60 segundos (16.67ms)
|
||||||
if (demo_.counter < TOTAL_DEMO_DATA)
|
static float recording_frame_timer = 0.0f;
|
||||||
|
recording_frame_timer += calculateDeltaTime();
|
||||||
|
if (recording_frame_timer >= 0.01667f && demo_.counter < TOTAL_DEMO_DATA) {
|
||||||
demo_.counter++;
|
demo_.counter++;
|
||||||
|
recording_frame_timer -= 0.01667f; // Mantener precisión acumulada
|
||||||
|
}
|
||||||
|
|
||||||
// Si se ha llenado el vector con datos, sale del programa
|
// Si se ha llenado el vector con datos, sale del programa
|
||||||
else {
|
else {
|
||||||
@@ -1686,10 +1721,10 @@ void Game::updateRecording() {
|
|||||||
#endif
|
#endif
|
||||||
|
|
||||||
// Actualiza las variables durante dicho estado
|
// Actualiza las variables durante dicho estado
|
||||||
void Game::updateGameStateFadeIn() {
|
void Game::updateGameStateFadeIn(float deltaTime) {
|
||||||
fade_in_->update();
|
fade_in_->update();
|
||||||
updateScoreboard();
|
updateScoreboard();
|
||||||
updateBackground();
|
updateBackground(deltaTime);
|
||||||
if (fade_in_->hasEnded()) {
|
if (fade_in_->hasEnded()) {
|
||||||
setState(State::ENTERING_PLAYER);
|
setState(State::ENTERING_PLAYER);
|
||||||
balloon_manager_->createTwoBigBalloons();
|
balloon_manager_->createTwoBigBalloons();
|
||||||
@@ -1698,11 +1733,11 @@ void Game::updateGameStateFadeIn() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Actualiza las variables durante dicho estado
|
// Actualiza las variables durante dicho estado
|
||||||
void Game::updateGameStateEnteringPlayer() {
|
void Game::updateGameStateEnteringPlayer(float deltaTime) {
|
||||||
balloon_manager_->update();
|
balloon_manager_->update(deltaTime);
|
||||||
updatePlayers();
|
updatePlayers(deltaTime);
|
||||||
updateScoreboard();
|
updateScoreboard();
|
||||||
updateBackground();
|
updateBackground(deltaTime);
|
||||||
for (const auto &player : players_) {
|
for (const auto &player : players_) {
|
||||||
if (player->isPlaying()) {
|
if (player->isPlaying()) {
|
||||||
setState(State::SHOWING_GET_READY_MESSAGE);
|
setState(State::SHOWING_GET_READY_MESSAGE);
|
||||||
@@ -1713,36 +1748,41 @@ void Game::updateGameStateEnteringPlayer() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Actualiza las variables durante dicho estado
|
// Actualiza las variables durante dicho estado
|
||||||
void Game::updateGameStateShowingGetReadyMessage() {
|
void Game::updateGameStateShowingGetReadyMessage(float deltaTime) {
|
||||||
updateGameStatePlaying();
|
updateGameStatePlaying(deltaTime);
|
||||||
if (path_sprites_.empty()) {
|
|
||||||
setState(State::PLAYING);
|
// Reproducir música después de ~1.67 segundos (100 frames a 60fps)
|
||||||
|
static bool music_started = false;
|
||||||
|
static float music_timer = 0.0f;
|
||||||
|
if (!music_started) {
|
||||||
|
music_timer += deltaTime;
|
||||||
|
if (music_timer >= 1.67f) {
|
||||||
|
playMusic();
|
||||||
|
music_started = true;
|
||||||
|
setState(State::PLAYING);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if (counter_ == 100) {
|
|
||||||
playMusic();
|
|
||||||
}
|
|
||||||
++counter_;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Actualiza las variables durante el transcurso normal del juego
|
// Actualiza las variables durante el transcurso normal del juego
|
||||||
void Game::updateGameStatePlaying() {
|
void Game::updateGameStatePlaying(float deltaTime) {
|
||||||
#ifdef _DEBUG
|
#ifdef _DEBUG
|
||||||
if (auto_pop_balloons_) {
|
if (auto_pop_balloons_) {
|
||||||
stage_manager_->addPower(5);
|
stage_manager_->addPower(1);
|
||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
updatePlayers();
|
updatePlayers(deltaTime);
|
||||||
checkPlayersStatusPlaying();
|
checkPlayersStatusPlaying();
|
||||||
updateScoreboard();
|
updateScoreboard();
|
||||||
updateBackground();
|
updateBackground(deltaTime);
|
||||||
balloon_manager_->update();
|
balloon_manager_->update(deltaTime);
|
||||||
tabe_->update();
|
tabe_->update(deltaTime);
|
||||||
updateBullets();
|
updateBullets(deltaTime);
|
||||||
updateItems();
|
updateItems(deltaTime);
|
||||||
updateStage();
|
updateStage();
|
||||||
updateSmartSprites();
|
updateSmartSprites(deltaTime);
|
||||||
updatePathSprites();
|
updatePathSprites(deltaTime);
|
||||||
updateTimeStopped();
|
updateTimeStopped(deltaTime);
|
||||||
updateHelper();
|
updateHelper();
|
||||||
checkBulletCollision();
|
checkBulletCollision();
|
||||||
updateMenace();
|
updateMenace();
|
||||||
@@ -1800,9 +1840,9 @@ void Game::checkAndUpdateBalloonSpeed() {
|
|||||||
|
|
||||||
for (size_t i = 0; i < std::size(THRESHOLDS); ++i) {
|
for (size_t i = 0; i < std::size(THRESHOLDS); ++i) {
|
||||||
// Si la velocidad actual del globo es la correspondiente al umbral "i" y el porcentaje de progreso ha superado ese umbral
|
// Si la velocidad actual del globo es la correspondiente al umbral "i" y el porcentaje de progreso ha superado ese umbral
|
||||||
if (balloon_manager_->getBalloonSpeed() == Balloon::SPEED.at(i) && PERCENT > THRESHOLDS.at(i)) {
|
if (balloon_manager_->getBalloonSpeed() == Balloon::GAME_TEMPO.at(i) && PERCENT > THRESHOLDS.at(i)) {
|
||||||
// Sube la velocidad al siguiente nivel (i + 1)
|
// Sube la velocidad al siguiente nivel (i + 1)
|
||||||
balloon_manager_->setBalloonSpeed(Balloon::SPEED.at(i + 1));
|
balloon_manager_->setBalloonSpeed(Balloon::GAME_TEMPO.at(i + 1));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1812,6 +1852,19 @@ void Game::checkAndUpdateBalloonSpeed() {
|
|||||||
void Game::setState(State state) {
|
void Game::setState(State state) {
|
||||||
state_ = state;
|
state_ = state;
|
||||||
counter_ = 0;
|
counter_ = 0;
|
||||||
|
|
||||||
|
switch (state) {
|
||||||
|
case State::COMPLETED: // Para la música y elimina todos los globos e items
|
||||||
|
stopMusic(); // Detiene la música
|
||||||
|
balloon_manager_->destroyAllBalloons(); // Destruye a todos los globos
|
||||||
|
playSound("power_ball_explosion.wav"); // Sonido de destruir todos los globos
|
||||||
|
destroyAllItems(); // Destruye todos los items
|
||||||
|
background_->setAlpha(0); // Elimina el tono rojo de las últimas pantallas
|
||||||
|
tabe_->disableSpawning(); // Deshabilita la creacion de Tabes
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void Game::playSound(const std::string &name) const {
|
void Game::playSound(const std::string &name) const {
|
||||||
@@ -1867,26 +1920,72 @@ void Game::onPauseStateChanged(bool is_paused) {
|
|||||||
tabe_->pauseTimer(is_paused);
|
tabe_->pauseTimer(is_paused);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Maneja eventos del juego completado usando flags para triggers únicos
|
||||||
|
void Game::handleGameCompletedEvents() {
|
||||||
|
constexpr float START_CELEBRATIONS_S = 6.667f; // 400 frames a 60fps → segundos
|
||||||
|
constexpr float END_CELEBRATIONS_S = 11.667f; // 700 frames a 60fps → segundos
|
||||||
|
|
||||||
|
// Inicio de celebraciones
|
||||||
|
static bool start_celebrations_triggered = false;
|
||||||
|
if (!start_celebrations_triggered && game_completed_timer_ >= START_CELEBRATIONS_S) {
|
||||||
|
createMessage({paths_.at(4), paths_.at(5)}, Resource::get()->getTexture("game_text_congratulations"));
|
||||||
|
createMessage({paths_.at(6), paths_.at(7)}, Resource::get()->getTexture("game_text_1000000_points"));
|
||||||
|
|
||||||
|
for (auto &player : players_) {
|
||||||
|
if (player->isPlaying()) {
|
||||||
|
player->addScore(1000000, Options::settings.hi_score_table.back().score);
|
||||||
|
player->setPlayingState(Player::State::CELEBRATING);
|
||||||
|
} else {
|
||||||
|
player->setPlayingState(Player::State::GAME_OVER);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
updateHiScore();
|
||||||
|
start_celebrations_triggered = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fin de celebraciones
|
||||||
|
static bool end_celebrations_triggered = false;
|
||||||
|
if (!end_celebrations_triggered && game_completed_timer_ >= END_CELEBRATIONS_S) {
|
||||||
|
for (auto &player : players_) {
|
||||||
|
if (player->isCelebrating()) {
|
||||||
|
player->setPlayingState(player->qualifiesForHighScore() ? Player::State::ENTERING_NAME_GAME_COMPLETED : Player::State::LEAVING_SCREEN);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fade_out_->activate();
|
||||||
|
end_celebrations_triggered = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Maneja eventos de game over usando flag para trigger único
|
||||||
|
void Game::handleGameOverEvents() {
|
||||||
|
static bool game_over_triggered = false;
|
||||||
|
if (!game_over_triggered && game_over_timer_ == 0.0f) {
|
||||||
|
createMessage({paths_.at(2), paths_.at(3)}, Resource::get()->getTexture("game_text_game_over"));
|
||||||
|
Audio::get()->fadeOutMusic(1000);
|
||||||
|
balloon_manager_->setBouncingSounds(true);
|
||||||
|
game_over_triggered = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#ifdef _DEBUG
|
#ifdef _DEBUG
|
||||||
// Comprueba los eventos en el modo DEBUG
|
// Comprueba los eventos en el modo DEBUG
|
||||||
void Game::handleDebugEvents(const SDL_Event &event) {
|
void Game::handleDebugEvents(const SDL_Event &event) {
|
||||||
static int formation_id_ = 0;
|
static int formation_id_ = 0;
|
||||||
if (event.type == SDL_EVENT_KEY_DOWN && static_cast<int>(event.key.repeat) == 0) {
|
if (event.type == SDL_EVENT_KEY_DOWN && static_cast<int>(event.key.repeat) == 0) {
|
||||||
switch (event.key.key) {
|
switch (event.key.key) {
|
||||||
case SDLK_1: // Crea una powerball
|
case SDLK_1: { // Crea una powerball
|
||||||
{
|
|
||||||
balloon_manager_->createPowerBall();
|
balloon_manager_->createPowerBall();
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case SDLK_2: // Activa o desactiva la aparición de globos
|
case SDLK_2: { // Activa o desactiva la aparición de globos
|
||||||
{
|
|
||||||
static bool deploy_balloons_ = true;
|
static bool deploy_balloons_ = true;
|
||||||
deploy_balloons_ = !deploy_balloons_;
|
deploy_balloons_ = !deploy_balloons_;
|
||||||
balloon_manager_->enableBalloonDeployment(deploy_balloons_);
|
balloon_manager_->enableBalloonDeployment(deploy_balloons_);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case SDLK_3: // Activa el modo para pasar el juego automaticamente
|
case SDLK_3: { // Activa el modo para pasar el juego automaticamente
|
||||||
{
|
|
||||||
auto_pop_balloons_ = !auto_pop_balloons_;
|
auto_pop_balloons_ = !auto_pop_balloons_;
|
||||||
Notifier::get()->show({"auto advance: " + boolToString(auto_pop_balloons_)});
|
Notifier::get()->show({"auto advance: " + boolToString(auto_pop_balloons_)});
|
||||||
if (auto_pop_balloons_) {
|
if (auto_pop_balloons_) {
|
||||||
@@ -1896,24 +1995,20 @@ void Game::handleDebugEvents(const SDL_Event &event) {
|
|||||||
balloon_manager_->enableBalloonDeployment(!auto_pop_balloons_);
|
balloon_manager_->enableBalloonDeployment(!auto_pop_balloons_);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case SDLK_4: // Suelta un item
|
case SDLK_4: { // Suelta un item
|
||||||
{
|
|
||||||
createItem(ItemType::CLOCK, players_.at(0)->getPosX(), players_.at(0)->getPosY() - 40);
|
createItem(ItemType::CLOCK, players_.at(0)->getPosX(), players_.at(0)->getPosY() - 40);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case SDLK_5: // 5.000
|
case SDLK_5: { // 5.000
|
||||||
{
|
|
||||||
const int X = players_.at(0)->getPosX() + ((Player::WIDTH - game_text_textures_[3]->getWidth()) / 2);
|
const int X = players_.at(0)->getPosX() + ((Player::WIDTH - game_text_textures_[3]->getWidth()) / 2);
|
||||||
createItemText(X, game_text_textures_.at(2));
|
createItemText(X, game_text_textures_.at(2));
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case SDLK_6: // Crea un mensaje
|
case SDLK_6: { // Crea un mensaje
|
||||||
{
|
|
||||||
createMessage({paths_.at(0), paths_.at(1)}, Resource::get()->getTexture("game_text_get_ready"));
|
createMessage({paths_.at(0), paths_.at(1)}, Resource::get()->getTexture("game_text_get_ready"));
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case SDLK_7: // 100.000
|
case SDLK_7: { // 100.000
|
||||||
{
|
|
||||||
const int X = players_.at(0)->getPosX() + ((Player::WIDTH - game_text_textures_[3]->getWidth()) / 2);
|
const int X = players_.at(0)->getPosX() + ((Player::WIDTH - game_text_textures_[3]->getWidth()) / 2);
|
||||||
createItemText(X, game_text_textures_.at(6));
|
createItemText(X, game_text_textures_.at(6));
|
||||||
break;
|
break;
|
||||||
|
|||||||
@@ -33,7 +33,22 @@ namespace Difficulty {
|
|||||||
enum class Code;
|
enum class Code;
|
||||||
} // namespace Difficulty
|
} // namespace Difficulty
|
||||||
|
|
||||||
// --- Clase Game: gestor principal del juego ---
|
// --- Clase Game: núcleo principal del gameplay ---
|
||||||
|
//
|
||||||
|
// Esta clase gestiona toda la lógica del juego durante las partidas activas,
|
||||||
|
// incluyendo mecánicas de juego, estados, objetos y sistemas de puntuación.
|
||||||
|
//
|
||||||
|
// Funcionalidades principales:
|
||||||
|
// • Gestión de jugadores: soporte para 1 o 2 jugadores simultáneos
|
||||||
|
// • Sistema de estados: fade-in, entrada, jugando, completado, game-over
|
||||||
|
// • Mecánicas de juego: globos, balas, ítems, power-ups y efectos especiales
|
||||||
|
// • Sistema de puntuación: scoreboard y tabla de récords
|
||||||
|
// • Efectos temporales: tiempo detenido, ayudas automáticas
|
||||||
|
// • Modo demo: reproducción automática para attract mode
|
||||||
|
// • Gestión de fases: progresión entre niveles y dificultad
|
||||||
|
//
|
||||||
|
// Utiliza un sistema de tiempo basado en milisegundos para garantizar
|
||||||
|
// comportamiento consistente independientemente del framerate.
|
||||||
class Game {
|
class Game {
|
||||||
public:
|
public:
|
||||||
// --- Constantes ---
|
// --- Constantes ---
|
||||||
@@ -58,12 +73,13 @@ class Game {
|
|||||||
GAME_OVER, // Fin del juego
|
GAME_OVER, // Fin del juego
|
||||||
};
|
};
|
||||||
|
|
||||||
// --- Constantes internas ---
|
// --- Constantes de tiempo (en segundos) ---
|
||||||
static constexpr int HELP_COUNTER = 1000;
|
static constexpr float HELP_COUNTER_S = 16.667f; // Contador de ayuda (1000 frames a 60fps → segundos)
|
||||||
static constexpr int GAME_COMPLETED_START_FADE = 500;
|
static constexpr float GAME_COMPLETED_START_FADE_S = 8.333f; // Inicio del fade al completar (500 frames → segundos)
|
||||||
static constexpr int GAME_COMPLETED_END = 700;
|
static constexpr float GAME_COMPLETED_END_S = 11.667f; // Fin del juego completado (700 frames → segundos)
|
||||||
static constexpr int GAME_OVER_COUNTER = 350;
|
static constexpr float GAME_OVER_DURATION_S = 5.833f; // Duración game over (350 frames → segundos)
|
||||||
static constexpr int TIME_STOPPED_COUNTER = 360;
|
static constexpr float TIME_STOPPED_DURATION_S = 6.0f; // Duración del tiempo detenido (360 frames → segundos)
|
||||||
|
static constexpr float DEMO_FADE_PRE_DURATION_S = 0.5f; // Pre-duración del fade en modo demo
|
||||||
static constexpr int ITEM_POINTS_1_DISK_ODDS = 10;
|
static constexpr int ITEM_POINTS_1_DISK_ODDS = 10;
|
||||||
static constexpr int ITEM_POINTS_2_GAVINA_ODDS = 6;
|
static constexpr int ITEM_POINTS_2_GAVINA_ODDS = 6;
|
||||||
static constexpr int ITEM_POINTS_3_PACMAR_ODDS = 3;
|
static constexpr int ITEM_POINTS_3_PACMAR_ODDS = 3;
|
||||||
@@ -77,7 +93,7 @@ class Game {
|
|||||||
bool need_coffee{false}; // Indica si se necesitan cafes
|
bool need_coffee{false}; // Indica si se necesitan cafes
|
||||||
bool need_coffee_machine{false}; // Indica si se necesita PowerUp
|
bool need_coffee_machine{false}; // Indica si se necesita PowerUp
|
||||||
bool need_power_ball{false}; // Indica si se necesita una PowerBall
|
bool need_power_ball{false}; // Indica si se necesita una PowerBall
|
||||||
int counter; // Contador para no dar ayudas consecutivas
|
float counter; // Contador para no dar ayudas consecutivas
|
||||||
int item_disk_odds; // Probabilidad de aparición del objeto
|
int item_disk_odds; // Probabilidad de aparición del objeto
|
||||||
int item_gavina_odds; // Probabilidad de aparición del objeto
|
int item_gavina_odds; // Probabilidad de aparición del objeto
|
||||||
int item_pacmar_odds; // Probabilidad de aparición del objeto
|
int item_pacmar_odds; // Probabilidad de aparición del objeto
|
||||||
@@ -86,7 +102,7 @@ class Game {
|
|||||||
int item_coffee_machine_odds; // Probabilidad de aparición del objeto
|
int item_coffee_machine_odds; // Probabilidad de aparición del objeto
|
||||||
|
|
||||||
Helper()
|
Helper()
|
||||||
: counter(HELP_COUNTER),
|
: counter(HELP_COUNTER_S * 1000), // Convertir a milisegundos para compatibilidad
|
||||||
item_disk_odds(ITEM_POINTS_1_DISK_ODDS),
|
item_disk_odds(ITEM_POINTS_1_DISK_ODDS),
|
||||||
item_gavina_odds(ITEM_POINTS_2_GAVINA_ODDS),
|
item_gavina_odds(ITEM_POINTS_2_GAVINA_ODDS),
|
||||||
item_pacmar_odds(ITEM_POINTS_3_PACMAR_ODDS),
|
item_pacmar_odds(ITEM_POINTS_3_PACMAR_ODDS),
|
||||||
@@ -134,14 +150,14 @@ class Game {
|
|||||||
Demo demo_; // Variable con todas las variables relacionadas con el modo demo
|
Demo demo_; // Variable con todas las variables relacionadas con el modo demo
|
||||||
Difficulty::Code difficulty_ = Options::settings.difficulty; // Dificultad del juego
|
Difficulty::Code difficulty_ = Options::settings.difficulty; // Dificultad del juego
|
||||||
Helper helper_; // Variable para gestionar las ayudas
|
Helper helper_; // Variable para gestionar las ayudas
|
||||||
Uint64 ticks_ = 0; // Contador de ticks para ajustar la velocidad del programa
|
Uint64 last_time_ = 0; // Último tiempo registrado para deltaTime
|
||||||
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 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
|
||||||
float difficulty_score_multiplier_; // Multiplicador de puntos en función de la dificultad
|
float difficulty_score_multiplier_ = 1.0f; // Multiplicador de puntos en función de la dificultad
|
||||||
int counter_ = 0; // Contador para el juego
|
float counter_ = 0.0f; // Contador para el juego
|
||||||
int game_completed_counter_ = 0; // Contador para el tramo final, cuando se ha completado la partida y ya no aparecen más globos
|
float game_completed_timer_ = 0.0f; // Acumulador de tiempo para el tramo final (milisegundos)
|
||||||
int game_over_counter_ = GAME_OVER_COUNTER; // Contador para el estado de fin de partida
|
float game_over_timer_ = 0.0f; // Timer para el estado de fin de partida (milisegundos)
|
||||||
int time_stopped_counter_ = 0; // Temporizador para llevar la cuenta del tiempo detenido
|
float time_stopped_timer_ = 0.0f; // Temporizador para llevar la cuenta del tiempo detenido
|
||||||
int menace_ = 0; // Nivel de amenaza actual
|
int menace_ = 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
|
||||||
State state_ = State::FADE_IN; // Estado
|
State state_ = State::FADE_IN; // Estado
|
||||||
@@ -154,25 +170,26 @@ class Game {
|
|||||||
#endif
|
#endif
|
||||||
|
|
||||||
// --- Ciclo principal del juego ---
|
// --- Ciclo principal del juego ---
|
||||||
void update(); // Actualiza la lógica principal del juego
|
void update(float deltaTime); // Actualiza la lógica principal del juego
|
||||||
void render(); // Renderiza todos los elementos del juego
|
auto calculateDeltaTime() -> float; // Calcula el deltatime
|
||||||
void handleEvents(); // Procesa los eventos del sistema en cola
|
void render(); // Renderiza todos los elementos del juego
|
||||||
void checkState(); // Verifica y actualiza el estado actual del juego
|
void handleEvents(); // Procesa los eventos del sistema en cola
|
||||||
void setState(State state); // Cambia el estado del juego
|
void checkState(); // Verifica y actualiza el estado actual del juego
|
||||||
void cleanVectors(); // Limpia vectores de elementos deshabilitados
|
void setState(State state); // Cambia el estado del juego
|
||||||
|
void cleanVectors(); // Limpia vectores de elementos deshabilitados
|
||||||
|
|
||||||
// --- Gestión de estados del juego ---
|
// --- Gestión de estados del juego ---
|
||||||
void updateGameStates(); // Actualiza todos los estados del juego
|
void updateGameStates(float deltaTime); // Actualiza todos los estados del juego
|
||||||
void updateGameStateFadeIn(); // Gestiona el estado de transición de entrada
|
void updateGameStateFadeIn(float deltaTime); // Gestiona el estado de transición de entrada (time-based)
|
||||||
void updateGameStateEnteringPlayer(); // Gestiona el estado de entrada de jugador
|
void updateGameStateEnteringPlayer(float deltaTime); // Gestiona el estado de entrada de jugador
|
||||||
void updateGameStateShowingGetReadyMessage(); // Gestiona el estado de mensaje "preparado"
|
void updateGameStateShowingGetReadyMessage(float deltaTime); // Gestiona el estado de mensaje "preparado"
|
||||||
void updateGameStatePlaying(); // Gestiona el estado de juego activo
|
void updateGameStatePlaying(float deltaTime); // Gestiona el estado de juego activo
|
||||||
void updateGameStateCompleted(); // Gestiona el estado de juego completado
|
void updateGameStateCompleted(float deltaTime); // Gestiona el estado de juego completado
|
||||||
void updateGameStateGameOver(); // Gestiona el estado de fin de partida
|
void updateGameStateGameOver(float deltaTime); // Gestiona el estado de fin de partida
|
||||||
|
|
||||||
// --- Gestión de jugadores ---
|
// --- Gestión de jugadores ---
|
||||||
void initPlayers(Player::Id player_id); // Inicializa los datos de los jugadores
|
void initPlayers(Player::Id player_id); // Inicializa los datos de los jugadores
|
||||||
void updatePlayers(); // Actualiza las variables y estados de los jugadores
|
void updatePlayers(float deltaTime); // Actualiza las variables y estados de los jugadores
|
||||||
void renderPlayers(); // Renderiza todos los jugadores en pantalla
|
void renderPlayers(); // Renderiza todos los jugadores en pantalla
|
||||||
void sortPlayersByZOrder(); // Reorganiza el orden de dibujado de jugadores
|
void sortPlayersByZOrder(); // Reorganiza el orden de dibujado de jugadores
|
||||||
auto getPlayer(Player::Id id) -> std::shared_ptr<Player>; // Obtiene un jugador por su identificador
|
auto getPlayer(Player::Id id) -> std::shared_ptr<Player>; // Obtiene un jugador por su identificador
|
||||||
@@ -209,7 +226,7 @@ class Game {
|
|||||||
void demoHandlePlayerInput(const std::shared_ptr<Player> &player, int index); // Procesa entrada de jugador en demo
|
void demoHandlePlayerInput(const std::shared_ptr<Player> &player, int index); // Procesa entrada de jugador en demo
|
||||||
|
|
||||||
// --- Sistema de balas y proyectiles ---
|
// --- Sistema de balas y proyectiles ---
|
||||||
void updateBullets(); // Actualiza posición y estado de todas las balas
|
void updateBullets(float deltaTime); // Actualiza posición y estado de todas las balas (time-based)
|
||||||
void renderBullets(); // Renderiza todas las balas activas
|
void renderBullets(); // Renderiza todas las balas activas
|
||||||
void createBullet(int x, int y, BulletType kind, bool powered_up, Player::Id owner); // Crea una nueva bala
|
void createBullet(int x, int y, BulletType kind, bool powered_up, Player::Id owner); // Crea una nueva bala
|
||||||
void checkBulletCollision(); // Verifica colisiones de todas las balas
|
void checkBulletCollision(); // Verifica colisiones de todas las balas
|
||||||
@@ -221,7 +238,7 @@ class Game {
|
|||||||
void processBalloonHit(const std::shared_ptr<Bullet> &bullet, const std::shared_ptr<Balloon> &balloon); // Procesa impacto en globo
|
void processBalloonHit(const std::shared_ptr<Bullet> &bullet, const std::shared_ptr<Balloon> &balloon); // Procesa impacto en globo
|
||||||
|
|
||||||
// --- Sistema de ítems y power-ups ---
|
// --- Sistema de ítems y power-ups ---
|
||||||
void updateItems(); // Actualiza posición y estado de todos los ítems
|
void updateItems(float deltaTime); // Actualiza posición y estado de todos los ítems
|
||||||
void renderItems(); // Renderiza todos los ítems activos
|
void renderItems(); // Renderiza todos los ítems activos
|
||||||
auto dropItem() -> ItemType; // Determina aleatoriamente qué ítem soltar
|
auto dropItem() -> ItemType; // Determina aleatoriamente qué ítem soltar
|
||||||
void createItem(ItemType type, float x, float y); // Crea un nuevo ítem en posición específica
|
void createItem(ItemType type, float x, float y); // Crea un nuevo ítem en posición específica
|
||||||
@@ -229,21 +246,23 @@ class Game {
|
|||||||
void destroyAllItems(); // Elimina todos los ítems activos de la pantalla
|
void destroyAllItems(); // Elimina todos los ítems activos de la pantalla
|
||||||
|
|
||||||
// --- ítems especiales ---
|
// --- ítems especiales ---
|
||||||
void enableTimeStopItem(); // Activa el efecto de detener el tiempo
|
void enableTimeStopItem(); // Activa el efecto de detener el tiempo
|
||||||
void disableTimeStopItem(); // Desactiva el efecto de detener el tiempo
|
void disableTimeStopItem(); // Desactiva el efecto de detener el tiempo
|
||||||
void updateTimeStopped(); // Actualiza el estado del tiempo detenido
|
void updateTimeStopped(float deltaTime); // Actualiza el estado del tiempo detenido
|
||||||
void throwCoffee(int x, int y); // Crea efecto de café arrojado al ser golpeado
|
void handleGameCompletedEvents(); // Maneja eventos del juego completado
|
||||||
|
void handleGameOverEvents(); // Maneja eventos de game over
|
||||||
|
void throwCoffee(int x, int y); // Crea efecto de café arrojado al ser golpeado
|
||||||
|
|
||||||
// --- Gestión de caída de ítems ---
|
// --- Gestión de caída de ítems ---
|
||||||
void handleItemDrop(const std::shared_ptr<Balloon> &balloon, const std::shared_ptr<Player> &player); // Gestiona caída de ítem desde globo
|
void handleItemDrop(const std::shared_ptr<Balloon> &balloon, const std::shared_ptr<Player> &player); // Gestiona caída de ítem desde globo
|
||||||
|
|
||||||
// --- Sprites inteligentes (smartsprites) ---
|
// --- Sprites inteligentes (smartsprites) ---
|
||||||
void updateSmartSprites(); // Actualiza todos los sprites con lógica propia
|
void updateSmartSprites(float deltaTime); // Actualiza todos los sprites con lógica propia (time-based)
|
||||||
void renderSmartSprites(); // Renderiza todos los sprites inteligentes
|
void renderSmartSprites(); // Renderiza todos los sprites inteligentes
|
||||||
void freeSmartSprites(); // Libera memoria de sprites inteligentes
|
void freeSmartSprites(); // Libera memoria de sprites inteligentes
|
||||||
|
|
||||||
// --- Sprites por ruta (pathsprites) ---
|
// --- Sprites por ruta (pathsprites) ---
|
||||||
void updatePathSprites(); // Actualiza sprites que siguen rutas predefinidas
|
void updatePathSprites(float deltaTime); // Actualiza sprites que siguen rutas predefinidas
|
||||||
void renderPathSprites(); // Renderiza sprites animados por ruta
|
void renderPathSprites(); // Renderiza sprites animados por ruta
|
||||||
void freePathSprites(); // Libera memoria de sprites por ruta
|
void freePathSprites(); // Libera memoria de sprites por ruta
|
||||||
void initPaths(); // Inicializa rutas predefinidas para animaciones
|
void initPaths(); // Inicializa rutas predefinidas para animaciones
|
||||||
@@ -254,8 +273,8 @@ class Game {
|
|||||||
|
|
||||||
// --- Sistema de globos y enemigos ---
|
// --- Sistema de globos y enemigos ---
|
||||||
void handleBalloonDestruction(std::shared_ptr<Balloon> balloon, const std::shared_ptr<Player> &player); // Procesa destrucción de globo
|
void handleBalloonDestruction(std::shared_ptr<Balloon> balloon, const std::shared_ptr<Player> &player); // Procesa destrucción de globo
|
||||||
void handleTabeHitEffects(); // Gestiona efectos al golpear a Tabe
|
void handleTabeHitEffects(); // Gestiona efectos al golpear a Tabe
|
||||||
void checkAndUpdateBalloonSpeed(); // Ajusta velocidad de globos según progreso
|
void checkAndUpdateBalloonSpeed(); // Ajusta velocidad de globos según progreso
|
||||||
|
|
||||||
// --- Gestión de fases y progresión ---
|
// --- Gestión de fases y progresión ---
|
||||||
void updateStage(); // Verifica y actualiza cambio de fase
|
void updateStage(); // Verifica y actualiza cambio de fase
|
||||||
@@ -277,7 +296,7 @@ class Game {
|
|||||||
|
|
||||||
// --- Recursos y renderizado ---
|
// --- Recursos y renderizado ---
|
||||||
void setResources(); // Asigna texturas y animaciones a los objetos
|
void setResources(); // Asigna texturas y animaciones a los objetos
|
||||||
void updateBackground(); // Actualiza elementos del fondo
|
void updateBackground(float deltaTime); // Actualiza elementos del fondo (time-based)
|
||||||
void fillCanvas(); // Renderiza elementos del área de juego en su textura
|
void fillCanvas(); // Renderiza elementos del área de juego en su textura
|
||||||
void updateHelper(); // Actualiza variables auxiliares de renderizado
|
void updateHelper(); // Actualiza variables auxiliares de renderizado
|
||||||
|
|
||||||
|
|||||||
@@ -29,7 +29,14 @@
|
|||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
HiScoreTable::HiScoreTable()
|
HiScoreTable::HiScoreTable()
|
||||||
: renderer_(Screen::get()->getRenderer()), backbuffer_(SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, param.game.width, param.game.height)), fade_(std::make_unique<Fade>()), background_(std::make_unique<Background>()), ticks_(0), view_area_(SDL_FRect{0, 0, param.game.width, param.game.height}), fade_mode_(Fade::Mode::IN), background_fade_color_(Color(0, 0, 0)) {
|
: renderer_(Screen::get()->getRenderer()),
|
||||||
|
backbuffer_(SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, param.game.width, param.game.height)),
|
||||||
|
fade_(std::make_unique<Fade>()),
|
||||||
|
background_(std::make_unique<Background>()),
|
||||||
|
last_time_(0),
|
||||||
|
view_area_(SDL_FRect{0, 0, param.game.width, param.game.height}),
|
||||||
|
fade_mode_(Fade::Mode::IN),
|
||||||
|
background_fade_color_(Color(0, 0, 0)) {
|
||||||
// Inicializa el resto
|
// Inicializa el resto
|
||||||
Section::name = Section::Name::HI_SCORE_TABLE;
|
Section::name = Section::Name::HI_SCORE_TABLE;
|
||||||
SDL_SetTextureBlendMode(backbuffer_, SDL_BLENDMODE_BLEND);
|
SDL_SetTextureBlendMode(backbuffer_, SDL_BLENDMODE_BLEND);
|
||||||
@@ -46,19 +53,18 @@ HiScoreTable::~HiScoreTable() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Actualiza las variables
|
// Actualiza las variables
|
||||||
void HiScoreTable::update() {
|
void HiScoreTable::update(float delta_time) {
|
||||||
if (SDL_GetTicks() - ticks_ > param.game.speed) {
|
elapsed_time_ += delta_time; // Incrementa el tiempo transcurrido
|
||||||
ticks_ = SDL_GetTicks(); // Actualiza el contador de ticks
|
|
||||||
Screen::get()->update(); // Actualiza el objeto screen
|
static auto *const SCREEN = Screen::get();
|
||||||
|
SCREEN->update(delta_time); // Actualiza el objeto screen
|
||||||
|
Audio::update(); // Actualiza el objeto audio
|
||||||
|
|
||||||
updateSprites(); // Actualiza las posiciones de los sprites de texto
|
updateSprites(delta_time); // Actualiza las posiciones de los sprites de texto
|
||||||
background_->update(); // Actualiza el fondo
|
background_->update(delta_time); // Actualiza el fondo
|
||||||
updateFade(); // Gestiona el fade
|
updateFade(delta_time); // Gestiona el fade
|
||||||
updateCounter(); // Gestiona el contador y sus eventos
|
updateCounter(); // Gestiona el contador y sus eventos
|
||||||
fillTexture(); // Dibuja los sprites en la textura
|
fillTexture(); // Dibuja los sprites en la textura
|
||||||
}
|
|
||||||
|
|
||||||
Audio::update();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Pinta en pantalla
|
// Pinta en pantalla
|
||||||
@@ -68,9 +74,10 @@ void HiScoreTable::render() {
|
|||||||
SCREEN->start(); // Prepara para empezar a dibujar en la textura de juego
|
SCREEN->start(); // Prepara para empezar a dibujar en la textura de juego
|
||||||
SCREEN->clean(); // Limpia la pantalla
|
SCREEN->clean(); // Limpia la pantalla
|
||||||
|
|
||||||
background_->render(); // Pinta el fondo
|
background_->render(); // Pinta el fondo
|
||||||
view_area_.y = std::max(0.0F, param.game.height - counter_ + 100); // Establece la ventana del backbuffer
|
float counter_equivalent = elapsed_time_ * 60.0f; // Convertir tiempo a equivalente frame para UI
|
||||||
SDL_RenderTexture(renderer_, backbuffer_, nullptr, &view_area_); // Copia el backbuffer al renderizador
|
view_area_.y = std::max(0.0F, param.game.height - counter_equivalent + 100); // Establece la ventana del backbuffer
|
||||||
|
SDL_RenderTexture(renderer_, backbuffer_, nullptr, &view_area_); // Copia el backbuffer al renderizador
|
||||||
fade_->render(); // Renderiza el fade
|
fade_->render(); // Renderiza el fade
|
||||||
|
|
||||||
SCREEN->render(); // Vuelca el contenido del renderizador en pantalla
|
SCREEN->render(); // Vuelca el contenido del renderizador en pantalla
|
||||||
@@ -110,20 +117,32 @@ void HiScoreTable::checkInput() {
|
|||||||
GlobalInputs::check();
|
GlobalInputs::check();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Calcula el tiempo transcurrido desde el último frame
|
||||||
|
float HiScoreTable::calculateDeltaTime() {
|
||||||
|
const Uint64 current_time = SDL_GetTicks();
|
||||||
|
const float delta_time = static_cast<float>(current_time - last_time_) / 1000.0f; // Convertir ms a segundos
|
||||||
|
last_time_ = current_time;
|
||||||
|
return delta_time;
|
||||||
|
}
|
||||||
|
|
||||||
// Bucle para la pantalla de instrucciones
|
// Bucle para la pantalla de instrucciones
|
||||||
void HiScoreTable::run() {
|
void HiScoreTable::run() {
|
||||||
|
last_time_ = SDL_GetTicks();
|
||||||
Audio::get()->playMusic("title.ogg");
|
Audio::get()->playMusic("title.ogg");
|
||||||
|
|
||||||
while (Section::name == Section::Name::HI_SCORE_TABLE) {
|
while (Section::name == Section::Name::HI_SCORE_TABLE) {
|
||||||
|
const float delta_time = calculateDeltaTime();
|
||||||
|
|
||||||
checkInput();
|
checkInput();
|
||||||
update();
|
update(delta_time);
|
||||||
checkEvents(); // Tiene que ir antes del render
|
checkEvents(); // Tiene que ir antes del render
|
||||||
render();
|
render();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Gestiona el fade
|
// Gestiona el fade
|
||||||
void HiScoreTable::updateFade() {
|
void HiScoreTable::updateFade(float delta_time) {
|
||||||
fade_->update();
|
fade_->update(delta_time);
|
||||||
|
|
||||||
if (fade_->hasEnded() && fade_mode_ == Fade::Mode::IN) {
|
if (fade_->hasEnded() && fade_mode_ == Fade::Mode::IN) {
|
||||||
fade_->reset();
|
fade_->reset();
|
||||||
@@ -201,15 +220,14 @@ void HiScoreTable::createSprites() {
|
|||||||
const int DEFAULT_POS_X = (backbuffer_width - ENTRY_WIDTH) / 2;
|
const int DEFAULT_POS_X = (backbuffer_width - ENTRY_WIDTH) / 2;
|
||||||
const int POS_X = (i < 9) ? DEFAULT_POS_X : DEFAULT_POS_X - entry_text->getCharacterSize();
|
const int POS_X = (i < 9) ? DEFAULT_POS_X : DEFAULT_POS_X - entry_text->getCharacterSize();
|
||||||
const int POS_Y = (i * SPACE_BETWEEN_LINES) + FIRST_LINE + SPACE_BETWEEN_HEADER;
|
const int POS_Y = (i * SPACE_BETWEEN_LINES) + FIRST_LINE + SPACE_BETWEEN_HEADER;
|
||||||
constexpr int STEPS = 80;
|
|
||||||
switch (ANIMATION) {
|
switch (ANIMATION) {
|
||||||
case 0: // Ambos lados alternativamente
|
case 0: // Ambos lados alternativamente
|
||||||
{
|
{
|
||||||
if (i % 2 == 0) {
|
if (i % 2 == 0) {
|
||||||
entry_names_.back()->addPath(-entry_names_.back()->getWidth(), POS_X, PathType::HORIZONTAL, POS_Y, STEPS, easeOutQuint);
|
entry_names_.back()->addPath(-entry_names_.back()->getWidth(), POS_X, PathType::HORIZONTAL, POS_Y, ANIM_DURATION_S, easeOutQuint);
|
||||||
entry_names_.back()->setPosition(-entry_names_.back()->getWidth(), 0);
|
entry_names_.back()->setPosition(-entry_names_.back()->getWidth(), 0);
|
||||||
} else {
|
} else {
|
||||||
entry_names_.back()->addPath(backbuffer_width, POS_X, PathType::HORIZONTAL, POS_Y, STEPS, easeOutQuint);
|
entry_names_.back()->addPath(backbuffer_width, POS_X, PathType::HORIZONTAL, POS_Y, ANIM_DURATION_S, easeOutQuint);
|
||||||
entry_names_.back()->setPosition(backbuffer_width, 0);
|
entry_names_.back()->setPosition(backbuffer_width, 0);
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
@@ -217,21 +235,21 @@ void HiScoreTable::createSprites() {
|
|||||||
|
|
||||||
case 1: // Entran por la izquierda
|
case 1: // Entran por la izquierda
|
||||||
{
|
{
|
||||||
entry_names_.back()->addPath(-entry_names_.back()->getWidth(), POS_X, PathType::HORIZONTAL, POS_Y, STEPS, easeOutQuint);
|
entry_names_.back()->addPath(-entry_names_.back()->getWidth(), POS_X, PathType::HORIZONTAL, POS_Y, ANIM_DURATION_S, easeOutQuint);
|
||||||
entry_names_.back()->setPosition(-entry_names_.back()->getWidth(), 0);
|
entry_names_.back()->setPosition(-entry_names_.back()->getWidth(), 0);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
case 2: // Entran por la derecha
|
case 2: // Entran por la derecha
|
||||||
{
|
{
|
||||||
entry_names_.back()->addPath(backbuffer_width, POS_X, PathType::HORIZONTAL, POS_Y, STEPS, easeOutQuint);
|
entry_names_.back()->addPath(backbuffer_width, POS_X, PathType::HORIZONTAL, POS_Y, ANIM_DURATION_S, easeOutQuint);
|
||||||
entry_names_.back()->setPosition(backbuffer_width, 0);
|
entry_names_.back()->setPosition(backbuffer_width, 0);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
case 3: // Entran desde la parte inferior
|
case 3: // Entran desde la parte inferior
|
||||||
{
|
{
|
||||||
entry_names_.back()->addPath(backbuffer_height, POS_Y, PathType::VERTICAL, POS_X, STEPS, easeOutQuint);
|
entry_names_.back()->addPath(backbuffer_height, POS_Y, PathType::VERTICAL, POS_X, ANIM_DURATION_S, easeOutQuint);
|
||||||
entry_names_.back()->setPosition(0, backbuffer_height);
|
entry_names_.back()->setPosition(0, backbuffer_height);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -242,20 +260,20 @@ void HiScoreTable::createSprites() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Actualiza las posiciones de los sprites de texto
|
// Actualiza las posiciones de los sprites de texto
|
||||||
void HiScoreTable::updateSprites() {
|
void HiScoreTable::updateSprites(float delta_time) {
|
||||||
constexpr int INIT_COUNTER = 190;
|
if (elapsed_time_ >= INIT_DELAY_S) {
|
||||||
const int COUNTER_BETWEEN_ENTRIES = 16;
|
const float elapsed_since_init = elapsed_time_ - INIT_DELAY_S;
|
||||||
if (counter_ >= INIT_COUNTER) {
|
int index = static_cast<int>(elapsed_since_init / ENTRY_DELAY_S);
|
||||||
const int COUNTER2 = counter_ - INIT_COUNTER;
|
if (index < static_cast<int>(entry_names_.size()) && index >= 0) {
|
||||||
if (COUNTER2 % COUNTER_BETWEEN_ENTRIES == 0) {
|
// Verificar si este índice debe activarse ahora
|
||||||
int index = COUNTER2 / COUNTER_BETWEEN_ENTRIES;
|
float expected_time = index * ENTRY_DELAY_S;
|
||||||
if (index < static_cast<int>(entry_names_.size())) {
|
if (elapsed_since_init >= expected_time && elapsed_since_init < expected_time + delta_time) {
|
||||||
entry_names_.at(index)->enable();
|
entry_names_.at(index)->enable();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for (auto const &entry : entry_names_) {
|
for (auto const &entry : entry_names_) {
|
||||||
entry->update();
|
entry->update(delta_time);
|
||||||
}
|
}
|
||||||
|
|
||||||
glowEntryNames();
|
glowEntryNames();
|
||||||
@@ -274,7 +292,7 @@ void HiScoreTable::initFade() {
|
|||||||
void HiScoreTable::initBackground() {
|
void HiScoreTable::initBackground() {
|
||||||
background_->setManualMode(true);
|
background_->setManualMode(true);
|
||||||
background_->setPos(param.game.game_area.rect);
|
background_->setPos(param.game.game_area.rect);
|
||||||
background_->setCloudsSpeed(-0.1F);
|
background_->setCloudsSpeed(CLOUDS_SPEED);
|
||||||
|
|
||||||
const int LUCKY = rand() % 3;
|
const int LUCKY = rand() % 3;
|
||||||
switch (LUCKY) {
|
switch (LUCKY) {
|
||||||
@@ -339,7 +357,8 @@ void HiScoreTable::iniEntryColors() {
|
|||||||
|
|
||||||
// Hace brillar los nombres de la tabla de records
|
// Hace brillar los nombres de la tabla de records
|
||||||
void HiScoreTable::glowEntryNames() {
|
void HiScoreTable::glowEntryNames() {
|
||||||
const Color ENTRY_COLOR = getEntryColor(counter_ / 5);
|
int color_counter = static_cast<int>(elapsed_time_ * 60.0f / 5.0f); // Convertir tiempo a equivalente frame
|
||||||
|
const Color ENTRY_COLOR = getEntryColor(color_counter);
|
||||||
for (const auto &entry_index : Options::settings.glowing_entries) {
|
for (const auto &entry_index : Options::settings.glowing_entries) {
|
||||||
if (entry_index != -1) {
|
if (entry_index != -1) {
|
||||||
entry_names_.at(entry_index)->getTexture()->setColor(ENTRY_COLOR);
|
entry_names_.at(entry_index)->getTexture()->setColor(ENTRY_COLOR);
|
||||||
@@ -349,14 +368,17 @@ void HiScoreTable::glowEntryNames() {
|
|||||||
|
|
||||||
// Gestiona el contador
|
// Gestiona el contador
|
||||||
void HiScoreTable::updateCounter() {
|
void HiScoreTable::updateCounter() {
|
||||||
++counter_;
|
static bool background_changed = false;
|
||||||
|
static bool fade_activated = false;
|
||||||
|
|
||||||
if (counter_ == 150) {
|
if (elapsed_time_ >= BACKGROUND_CHANGE_S && !background_changed) {
|
||||||
background_->setColor(background_fade_color_.DARKEN());
|
background_->setColor(background_fade_color_.DARKEN());
|
||||||
background_->setAlpha(96);
|
background_->setAlpha(96);
|
||||||
|
background_changed = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (counter_ == COUNTER_END) {
|
if (elapsed_time_ >= COUNTER_END_S && !fade_activated) {
|
||||||
fade_->activate();
|
fade_->activate();
|
||||||
|
fade_activated = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -30,8 +30,13 @@ class HiScoreTable {
|
|||||||
void run();
|
void run();
|
||||||
|
|
||||||
private:
|
private:
|
||||||
// --- Constantes ---
|
// --- Constantes (en segundos) ---
|
||||||
static constexpr Uint16 COUNTER_END = 800; // Valor final para el contador
|
static constexpr float COUNTER_END_S = 800.0f / 60.0f; // Tiempo final (≈13.33s)
|
||||||
|
static constexpr float INIT_DELAY_S = 190.0f / 60.0f; // Retraso inicial (≈3.17s)
|
||||||
|
static constexpr float ENTRY_DELAY_S = 16.0f / 60.0f; // Retraso entre entradas (≈0.27s)
|
||||||
|
static constexpr float BACKGROUND_CHANGE_S = 150.0f / 60.0f; // Tiempo cambio fondo (≈2.5s)
|
||||||
|
static constexpr float ANIM_DURATION_S = 80.0f / 60.0f; // Duración animación (≈1.33s)
|
||||||
|
static constexpr float CLOUDS_SPEED = -6.0f; // Velocidad nubes (pixels/s)
|
||||||
|
|
||||||
// --- Objetos y punteros ---
|
// --- Objetos y punteros ---
|
||||||
SDL_Renderer *renderer_; // El renderizador de la ventana
|
SDL_Renderer *renderer_; // El renderizador de la ventana
|
||||||
@@ -44,27 +49,28 @@ class HiScoreTable {
|
|||||||
std::vector<Path> paths_; // Vector con los recorridos precalculados
|
std::vector<Path> paths_; // Vector con los recorridos precalculados
|
||||||
|
|
||||||
// --- Variables ---
|
// --- Variables ---
|
||||||
Uint16 counter_ = 0; // Contador
|
float elapsed_time_ = 0.0f; // Tiempo transcurrido (segundos)
|
||||||
Uint64 ticks_; // Contador de ticks para ajustar la velocidad del programa
|
Uint64 last_time_ = 0; // Último timestamp para calcular delta-time
|
||||||
SDL_FRect view_area_; // Parte de la textura que se muestra en pantalla
|
SDL_FRect view_area_; // Parte de la textura que se muestra en pantalla
|
||||||
Fade::Mode fade_mode_; // Modo de fade a utilizar
|
Fade::Mode fade_mode_; // Modo de fade a utilizar
|
||||||
Color background_fade_color_; // Color de atenuación del fondo
|
Color background_fade_color_; // Color de atenuación del fondo
|
||||||
std::vector<Color> entry_colors_; // Colores para destacar las entradas en la tabla
|
std::vector<Color> entry_colors_; // Colores para destacar las entradas en la tabla
|
||||||
|
|
||||||
// --- Métodos internos ---
|
// --- Métodos internos ---
|
||||||
void update(); // Actualiza las variables
|
void update(float delta_time); // Actualiza las variables
|
||||||
void render(); // Pinta en pantalla
|
void render(); // Pinta en pantalla
|
||||||
static void checkEvents(); // Comprueba los eventos
|
static void checkEvents(); // Comprueba los eventos
|
||||||
static void checkInput(); // Comprueba las entradas
|
static void checkInput(); // Comprueba las entradas
|
||||||
static auto format(int number) -> std::string; // Convierte un entero a un string con separadores de miles
|
static auto format(int number) -> std::string; // Convierte un entero a un string con separadores de miles
|
||||||
void fillTexture(); // Dibuja los sprites en la textura
|
void fillTexture(); // Dibuja los sprites en la textura
|
||||||
void updateFade(); // Gestiona el fade
|
void updateFade(float delta_time); // Gestiona el fade
|
||||||
void createSprites(); // Crea los sprites con los textos
|
void createSprites(); // Crea los sprites con los textos
|
||||||
void updateSprites(); // Actualiza las posiciones de los sprites de texto
|
void updateSprites(float delta_time); // Actualiza las posiciones de los sprites de texto
|
||||||
void initFade(); // Inicializa el fade
|
void initFade(); // Inicializa el fade
|
||||||
void initBackground(); // Inicializa el fondo
|
void initBackground(); // Inicializa el fondo
|
||||||
auto getEntryColor(int counter) -> Color; // Obtiene un color del vector de colores de entradas
|
auto getEntryColor(int counter) -> Color; // Obtiene un color del vector de colores de entradas
|
||||||
void iniEntryColors(); // Inicializa los colores de las entradas
|
void iniEntryColors(); // Inicializa los colores de las entradas
|
||||||
void glowEntryNames(); // Hace brillar los nombres de la tabla de records
|
void glowEntryNames(); // Hace brillar los nombres de la tabla de records
|
||||||
void updateCounter(); // Gestiona el contador
|
void updateCounter(); // Gestiona el contador
|
||||||
|
float calculateDeltaTime(); // Calcula el tiempo transcurrido desde el último frame
|
||||||
};
|
};
|
||||||
@@ -26,7 +26,12 @@
|
|||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
Instructions::Instructions()
|
Instructions::Instructions()
|
||||||
: renderer_(Screen::get()->getRenderer()), texture_(SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, param.game.width, param.game.height)), backbuffer_(SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, param.game.width, param.game.height)), text_(Resource::get()->getText("smb2")), tiled_bg_(std::make_unique<TiledBG>(param.game.game_area.rect, TiledBGMode::STATIC)), fade_(std::make_unique<Fade>()) {
|
: renderer_(Screen::get()->getRenderer()),
|
||||||
|
texture_(SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, param.game.width, param.game.height)),
|
||||||
|
backbuffer_(SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, param.game.width, param.game.height)),
|
||||||
|
text_(Resource::get()->getText("smb2")),
|
||||||
|
tiled_bg_(std::make_unique<TiledBG>(param.game.game_area.rect, TiledBGMode::STATIC)),
|
||||||
|
fade_(std::make_unique<Fade>()) {
|
||||||
// Configura las texturas
|
// Configura las texturas
|
||||||
SDL_SetTextureBlendMode(backbuffer_, SDL_BLENDMODE_BLEND);
|
SDL_SetTextureBlendMode(backbuffer_, SDL_BLENDMODE_BLEND);
|
||||||
SDL_SetTextureBlendMode(texture_, SDL_BLENDMODE_BLEND);
|
SDL_SetTextureBlendMode(texture_, SDL_BLENDMODE_BLEND);
|
||||||
@@ -83,24 +88,24 @@ void Instructions::iniSprites() {
|
|||||||
void Instructions::updateSprites() {
|
void Instructions::updateSprites() {
|
||||||
SDL_FRect src_rect = {0, 0, param.game.item_size, param.game.item_size};
|
SDL_FRect src_rect = {0, 0, param.game.item_size, param.game.item_size};
|
||||||
|
|
||||||
// Disquito
|
// Disquito (desplazamiento 12/60 = 0.2s)
|
||||||
src_rect.y = param.game.item_size * (((counter_ + 12) / 36) % 2);
|
src_rect.y = param.game.item_size * (static_cast<int>((elapsed_time_ + 0.2f) / SPRITE_ANIMATION_CYCLE_S) % 2);
|
||||||
sprites_[0]->setSpriteClip(src_rect);
|
sprites_[0]->setSpriteClip(src_rect);
|
||||||
|
|
||||||
// Gavina
|
// Gavina (desplazamiento 9/60 = 0.15s)
|
||||||
src_rect.y = param.game.item_size * (((counter_ + 9) / 36) % 2);
|
src_rect.y = param.game.item_size * (static_cast<int>((elapsed_time_ + 0.15f) / SPRITE_ANIMATION_CYCLE_S) % 2);
|
||||||
sprites_[1]->setSpriteClip(src_rect);
|
sprites_[1]->setSpriteClip(src_rect);
|
||||||
|
|
||||||
// Pacmar
|
// Pacmar (desplazamiento 6/60 = 0.1s)
|
||||||
src_rect.y = param.game.item_size * (((counter_ + 6) / 36) % 2);
|
src_rect.y = param.game.item_size * (static_cast<int>((elapsed_time_ + 0.1f) / SPRITE_ANIMATION_CYCLE_S) % 2);
|
||||||
sprites_[2]->setSpriteClip(src_rect);
|
sprites_[2]->setSpriteClip(src_rect);
|
||||||
|
|
||||||
// Time Stopper
|
// Time Stopper (desplazamiento 3/60 = 0.05s)
|
||||||
src_rect.y = param.game.item_size * (((counter_ + 3) / 36) % 2);
|
src_rect.y = param.game.item_size * (static_cast<int>((elapsed_time_ + 0.05f) / SPRITE_ANIMATION_CYCLE_S) % 2);
|
||||||
sprites_[3]->setSpriteClip(src_rect);
|
sprites_[3]->setSpriteClip(src_rect);
|
||||||
|
|
||||||
// Coffee
|
// Coffee (sin desplazamiento)
|
||||||
src_rect.y = param.game.item_size * (((counter_ + 0) / 36) % 2);
|
src_rect.y = param.game.item_size * (static_cast<int>(elapsed_time_ / SPRITE_ANIMATION_CYCLE_S) % 2);
|
||||||
sprites_[4]->setSpriteClip(src_rect);
|
sprites_[4]->setSpriteClip(src_rect);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -199,20 +204,18 @@ void Instructions::fillBackbuffer() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Actualiza las variables
|
// Actualiza las variables
|
||||||
void Instructions::update() {
|
void Instructions::update(float delta_time) {
|
||||||
if (SDL_GetTicks() - ticks_ > param.game.speed) {
|
elapsed_time_ += delta_time; // Incrementa el tiempo transcurrido
|
||||||
ticks_ = SDL_GetTicks(); // Actualiza el contador de ticks
|
|
||||||
Screen::get()->update(); // Actualiza el objeto screen
|
|
||||||
|
|
||||||
counter_++; // Incrementa el contador
|
static auto *const SCREEN = Screen::get();
|
||||||
updateSprites(); // Actualiza los sprites
|
SCREEN->update(delta_time); // Actualiza el objeto screen
|
||||||
updateBackbuffer(); // Gestiona la textura con los graficos
|
Audio::update(); // Actualiza el objeto audio
|
||||||
tiled_bg_->update(); // Actualiza el mosaico de fondo
|
|
||||||
fade_->update(); // Actualiza el objeto "fade"
|
|
||||||
fillBackbuffer(); // Rellena el backbuffer
|
|
||||||
}
|
|
||||||
|
|
||||||
Audio::update();
|
updateSprites(); // Actualiza los sprites
|
||||||
|
updateBackbuffer(delta_time); // Gestiona la textura con los graficos
|
||||||
|
tiled_bg_->update(delta_time); // Actualiza el mosaico de fondo
|
||||||
|
fade_->update(delta_time); // Actualiza el objeto "fade"
|
||||||
|
fillBackbuffer(); // Rellena el backbuffer
|
||||||
}
|
}
|
||||||
|
|
||||||
// Pinta en pantalla
|
// Pinta en pantalla
|
||||||
@@ -250,12 +253,24 @@ void Instructions::checkInput() {
|
|||||||
GlobalInputs::check();
|
GlobalInputs::check();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Calcula el tiempo transcurrido desde el último frame
|
||||||
|
float Instructions::calculateDeltaTime() {
|
||||||
|
const Uint64 current_time = SDL_GetTicks();
|
||||||
|
const float delta_time = static_cast<float>(current_time - last_time_) / 1000.0f; // Convertir ms a segundos
|
||||||
|
last_time_ = current_time;
|
||||||
|
return delta_time;
|
||||||
|
}
|
||||||
|
|
||||||
// Bucle para la pantalla de instrucciones
|
// Bucle para la pantalla de instrucciones
|
||||||
void Instructions::run() {
|
void Instructions::run() {
|
||||||
|
last_time_ = SDL_GetTicks();
|
||||||
Audio::get()->playMusic("title.ogg");
|
Audio::get()->playMusic("title.ogg");
|
||||||
|
|
||||||
while (Section::name == Section::Name::INSTRUCTIONS) {
|
while (Section::name == Section::Name::INSTRUCTIONS) {
|
||||||
|
const float delta_time = calculateDeltaTime();
|
||||||
|
|
||||||
checkInput();
|
checkInput();
|
||||||
update();
|
update(delta_time);
|
||||||
checkEvents(); // Tiene que ir antes del render
|
checkEvents(); // Tiene que ir antes del render
|
||||||
render();
|
render();
|
||||||
}
|
}
|
||||||
@@ -310,23 +325,27 @@ void Instructions::renderLines(SDL_Renderer *renderer, SDL_Texture *texture, con
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Gestiona la textura con los graficos
|
// Gestiona la textura con los graficos
|
||||||
void Instructions::updateBackbuffer() {
|
void Instructions::updateBackbuffer(float delta_time) {
|
||||||
// Establece la ventana del backbuffer
|
// Establece la ventana del backbuffer (convertir elapsed_time_ a equivalente de counter)
|
||||||
view_.y = std::max(0.0F, param.game.height - counter_ + 100);
|
float counter_equivalent = elapsed_time_ * 60.0f; // Convertir segundos a equivalente frame para UI
|
||||||
|
view_.y = std::max(0.0F, param.game.height - counter_equivalent + 100);
|
||||||
|
|
||||||
// Verifica si view_.y == 0 y gestiona el temporizador
|
// Verifica si view_.y == 0 y gestiona el temporizador
|
||||||
if (view_.y == 0) {
|
if (view_.y == 0) {
|
||||||
if (!start_delay_triggered_) {
|
if (!start_delay_triggered_) {
|
||||||
// Activa el temporizador si no ha sido activado
|
// Activa el temporizador si no ha sido activado
|
||||||
start_delay_triggered_ = true;
|
start_delay_triggered_ = true;
|
||||||
start_delay_time_ = SDL_GetTicks();
|
start_delay_timer_ = 0.0f;
|
||||||
} else if (SDL_GetTicks() - start_delay_time_ >= 4000) {
|
} else {
|
||||||
// Han pasado tres segundos, mover líneas
|
start_delay_timer_ += delta_time;
|
||||||
all_lines_off_screen_ = moveLines(lines_, 320, 1.0F, 5);
|
if (start_delay_timer_ >= START_DELAY_S) {
|
||||||
|
// Han pasado los segundos de retraso, mover líneas
|
||||||
|
all_lines_off_screen_ = moveLines(lines_, 320, LINE_MOVE_DURATION_S, static_cast<Uint32>(LINE_START_DELAY_MS));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba si el contador ha llegado al final
|
// Comprueba si todas las líneas han terminado
|
||||||
if (all_lines_off_screen_) {
|
if (all_lines_off_screen_) {
|
||||||
Section::name = Section::Name::TITLE;
|
Section::name = Section::Name::TITLE;
|
||||||
Section::options = Section::Options::TITLE_1;
|
Section::options = Section::Options::TITLE_1;
|
||||||
|
|||||||
@@ -34,7 +34,9 @@ struct Line { // Almacena información de línea animada
|
|||||||
|
|
||||||
// Constructor de Line
|
// Constructor de Line
|
||||||
Line(int y, float x, int direction)
|
Line(int y, float x, int direction)
|
||||||
: y(y), x(x), direction(direction) {}
|
: y(y),
|
||||||
|
x(x),
|
||||||
|
direction(direction) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Clase Instructions
|
// Clase Instructions
|
||||||
@@ -48,6 +50,12 @@ class Instructions {
|
|||||||
void run();
|
void run();
|
||||||
|
|
||||||
private:
|
private:
|
||||||
|
// --- Constantes de tiempo (en segundos) ---
|
||||||
|
static constexpr float SPRITE_ANIMATION_CYCLE_S = 36.0f / 60.0f; // Ciclo de animación sprites (≈0.6s)
|
||||||
|
static constexpr float START_DELAY_S = 4.0f; // Retraso antes de mover líneas (4s)
|
||||||
|
static constexpr float LINE_MOVE_DURATION_S = 1.0f; // Duración movimiento líneas (1s)
|
||||||
|
static constexpr float LINE_START_DELAY_MS = 5.0f; // Retraso entre líneas (5ms)
|
||||||
|
|
||||||
// --- Objetos y punteros ---
|
// --- Objetos y punteros ---
|
||||||
SDL_Renderer *renderer_; // El renderizador de la ventana
|
SDL_Renderer *renderer_; // El renderizador de la ventana
|
||||||
SDL_Texture *texture_; // Textura fija con el texto
|
SDL_Texture *texture_; // Textura fija con el texto
|
||||||
@@ -60,18 +68,18 @@ class Instructions {
|
|||||||
std::unique_ptr<Fade> fade_; // Objeto para renderizar fades
|
std::unique_ptr<Fade> fade_; // Objeto para renderizar fades
|
||||||
|
|
||||||
// --- Variables ---
|
// --- Variables ---
|
||||||
int counter_ = 0; // Contador para manejar el progreso en la pantalla de instrucciones
|
float elapsed_time_ = 0.0f; // Tiempo transcurrido (segundos)
|
||||||
Uint64 ticks_ = 0; // Contador de ticks para ajustar la velocidad del programa
|
Uint64 last_time_ = 0; // Último timestamp para calcular delta-time
|
||||||
SDL_FRect view_; // Vista del backbuffer que se va a mostrar por pantalla
|
SDL_FRect view_; // Vista del backbuffer que se va a mostrar por pantalla
|
||||||
SDL_FPoint sprite_pos_ = {0, 0}; // Posición del primer sprite en la lista
|
SDL_FPoint sprite_pos_ = {0, 0}; // Posición del primer sprite en la lista
|
||||||
float item_space_ = 2.0; // Espacio entre los items en pantalla
|
float item_space_ = 2.0; // Espacio entre los items en pantalla
|
||||||
std::vector<Line> lines_; // Vector que contiene las líneas animadas en la pantalla
|
std::vector<Line> lines_; // Vector que contiene las líneas animadas en la pantalla
|
||||||
bool all_lines_off_screen_ = false; // Indica si todas las líneas han salido de la pantalla
|
bool all_lines_off_screen_ = false; // Indica si todas las líneas han salido de la pantalla
|
||||||
Uint32 start_delay_time_ = 0; // Tiempo de inicio del retraso para mover las líneas
|
float start_delay_timer_ = 0.0f; // Timer para retraso antes de mover líneas (segundos)
|
||||||
bool start_delay_triggered_ = false; // Bandera para determinar si el retraso ha comenzado
|
bool start_delay_triggered_ = false; // Bandera para determinar si el retraso ha comenzado
|
||||||
|
|
||||||
// --- Métodos internos ---
|
// --- Métodos internos ---
|
||||||
void update(); // Actualiza las variables
|
void update(float delta_time); // Actualiza las variables
|
||||||
void render(); // Pinta en pantalla
|
void render(); // Pinta en pantalla
|
||||||
static void checkEvents(); // Comprueba los eventos
|
static void checkEvents(); // Comprueba los eventos
|
||||||
static void checkInput(); // Comprueba las entradas
|
static void checkInput(); // Comprueba las entradas
|
||||||
@@ -80,7 +88,8 @@ class Instructions {
|
|||||||
void iniSprites(); // Inicializa los sprites de los items
|
void iniSprites(); // Inicializa los sprites de los items
|
||||||
void updateSprites(); // Actualiza los sprites
|
void updateSprites(); // Actualiza los sprites
|
||||||
static auto initializeLines(int height) -> std::vector<Line>; // Inicializa las líneas animadas
|
static auto initializeLines(int height) -> std::vector<Line>; // Inicializa las líneas animadas
|
||||||
static auto moveLines(std::vector<Line> &lines, int width, float duration, Uint32 start_delay) -> bool; // Mueve las líneas
|
static auto moveLines(std::vector<Line> &lines, int width, float duration, Uint32 start_delay) -> bool; // Mueve las líneas (ya usa tiempo real)
|
||||||
static void renderLines(SDL_Renderer *renderer, SDL_Texture *texture, const std::vector<Line> &lines); // Renderiza las líneas
|
static void renderLines(SDL_Renderer *renderer, SDL_Texture *texture, const std::vector<Line> &lines); // Renderiza las líneas
|
||||||
void updateBackbuffer(); // Gestiona la textura con los gráficos
|
void updateBackbuffer(float delta_time); // Gestiona la textura con los gráficos
|
||||||
|
float calculateDeltaTime(); // Calcula el tiempo transcurrido desde el último frame
|
||||||
};
|
};
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user