71 Commits

Author SHA1 Message Date
3d52c45f5c Actualizado Makefile 2022-10-14 10:55:27 +02:00
3276027044 Subido el numero de versión 2022-10-14 10:46:18 +02:00
8041595976 Añadido contador al quitar el menu de pausa del juego 2022-10-14 10:44:50 +02:00
fa53c1b01a Merge branch 'master' of https://gitea.sustancia.synology.me/JailDesigner/coffee_crisis 2022-10-14 09:56:22 +02:00
20b362160e Arreglado el fallo en el sprite de muerte del arounder, tenia pantalón corto 2022-10-14 09:56:04 +02:00
5cabbfc487 Eliminar 'data/config/config.bin' 2022-10-14 09:53:38 +02:00
9f5e001c70 Eliminar 'data/config/score.bin' 2022-10-14 09:53:27 +02:00
112c3afc76 Solucionado el problema de no cerrar el juego durante la demo o las instrucciones 2022-10-14 09:52:15 +02:00
f4215384fe Actualizado Makefile 2022-10-13 10:46:40 +02:00
7796cee51a Actualizado Makefile 2022-10-13 10:41:22 +02:00
f83154c062 Listo para lanzamiento 2022-10-09 14:23:45 +02:00
9e73f7f97d Eliminado todo.txt 2022-10-09 13:02:18 +02:00
742ca02573 Revisados varios pequeños bugs 2022-10-09 12:58:23 +02:00
d77757853d Quitadas las cabezas rojas de powerup y acelerada la animación 2022-10-09 12:01:28 +02:00
ca7ae7418e Arreglado el modo 2P 2022-10-09 11:46:11 +02:00
f880bb7d74 Modificado el ritmo de las numbes i el cambio de color del cielo 2022-10-08 00:14:14 +02:00
9784b5517a Trabajando el menu de game over y el player_fire 2022-10-07 22:44:57 +02:00
88041eba23 Merge branch 'master' of https://gitea.sustancia.synology.me/JailDesigner/coffee_crisis 2022-10-07 18:30:44 +02:00
698721ae03 Trabajando en la pantalla de game over 2022-10-07 18:30:41 +02:00
c7109a46cd Pequeños ajustes y detalles 2022-10-07 13:56:51 +02:00
bb20522172 Arreglados dos fallos del menu 2022-10-06 19:06:39 +02:00
bebc016f3c Las instrucciones ya usan las nuevas texturas de objetos 2022-10-06 13:46:41 +02:00
56c1a1d7f3 Arreglada la animacion de morir. Ya no se usan smartsprites 2022-10-06 13:13:27 +02:00
50d2a5d1c7 Ya va pasando del titulo a las instrucciones, a la demo, etc.. 2022-10-06 10:31:48 +02:00
83103ddfea Arreglados los cambios de lenguaje 2022-10-06 09:39:39 +02:00
f4f7bb52b3 Actualizado makefile 2022-10-06 08:01:23 +02:00
b861f33867 Actualizado Makefile 2022-10-06 07:16:58 +02:00
2576d62002 Optimizados algunos png 2022-10-05 22:37:37 +02:00
02312e1342 Ya precarga todos los recursos del juego 2022-10-05 20:48:55 +02:00
83a34d61bf Trabajando en tener todos los recursos cargados previamente 2022-10-05 19:17:45 +02:00
8076d8a765 Trabajando en la cache de los recursos de los items 2022-10-05 14:02:50 +02:00
901757b9b2 Actualizado .gitignore 2022-10-05 13:02:57 +02:00
f5ba15a4af Renombradas las variables de game.cpp 2022-10-05 12:30:45 +02:00
6eda55cdae Redistribución de los graficos de fondo en varios png 2022-10-05 10:22:38 +02:00
18c36ad3fb Ya se puede continuar al morir 2022-10-04 21:40:33 +02:00
a5adf1ba01 La maquina de cafe no toca el suelo 2022-10-04 19:11:31 +02:00
d5ab7cbe2a Renombradas las variablesde balloon.cpp 2022-10-04 18:27:49 +02:00
adad58ccfa Renombradas las variables de bullet.cpp 2022-10-04 18:11:42 +02:00
33b7c6082e Añadido todo.txt 2022-10-04 17:56:38 +02:00
5fd1ffa865 Retocado el borde de la powerball y quitados los efectos de rebote 2022-10-04 16:58:10 +02:00
9f93de1d06 Resuelto un bug en la colision de balas con globos 2022-10-04 14:16:22 +02:00
c3fd348a61 Optimizada la carga de las animaciones de los globos. Cacheada 2022-10-04 12:13:47 +02:00
ddb70c8c85 Fallo parcial en la carga de animaciones desde streams 2022-10-04 07:09:28 +02:00
95d6396dfa Resueltos los dos últimos problemas 2022-10-03 17:14:33 +02:00
99b61c4b2d Los items ya parecen funcionar. revisar power ball y los puntos al coger items 2022-10-03 14:11:13 +02:00
91b868572e trabajando los items 2022-10-03 11:45:09 +02:00
9c35fadd55 Trabajando en los globos 2022-10-03 04:15:04 +02:00
80ca04fd64 Balas funcionales 2022-10-03 03:02:46 +02:00
4ac7496eff Trabajando en la sección de juego y el jugador 2022-10-02 20:23:06 +02:00
b6225d2d2f Trabajando en el jugador 2022-09-29 20:15:41 +02:00
a148c38ef8 Modificados ficheros .ani del jugador 2022-09-29 19:07:39 +02:00
902d901698 Trabajando en el jugador 2022-09-29 18:17:30 +02:00
a1bdb6add3 Merge branch 'master' of https://gitea.sustancia.synology.me/JailDesigner/coffee_crisis 2022-09-29 18:07:58 +02:00
0063a2ede5 Optimizado TITLE, aun queda por hacer 2022-09-29 17:49:43 +02:00
e46a346d20 Trabajando con las animaciones del jugador 2022-09-29 14:02:13 +02:00
15b73f1d2c TITULO bastante avanzado, se deja para el final ya que falta ver elmodo demo y demas 2022-09-29 11:22:29 +02:00
fd90a3c66c Corregido el bug de la asignacion de items del menu de la intro 2022-09-28 22:23:26 +02:00
3d75fae393 Error raro en el constructor del menu 2022-09-28 21:12:26 +02:00
6df5d484bc No se pq no funciona al cargar los items del menu 2022-09-28 20:26:35 +02:00
e2298dc2b2 Ya empieza a funcionar la INTRO 2022-09-28 19:41:12 +02:00
c213124193 Trabajando en la INTRO 2022-09-28 18:52:19 +02:00
2209ed5f97 Trabajando en el TITULO 2022-09-28 14:03:45 +02:00
1552f6385c INTRO optimizada y revisada 2022-09-28 11:48:01 +02:00
072a488de6 Ya funciona la INTRO 2022-09-28 09:48:55 +02:00
8b2459dc35 Trabajando en la INTRO 2022-09-27 22:39:27 +02:00
10882780e5 Revisada la clase DIRECTOR 2022-09-27 19:34:13 +02:00
96ee1fdbe5 Eliminado el fichero coffeedrop 2022-09-27 19:04:25 +02:00
50e31a3db3 LOGO funcional 2022-09-27 19:03:24 +02:00
740e495ad0 Ya compila 2022-09-27 14:02:16 +02:00
2528969801 He quitado todos lo errores. No va a funcionar 2022-09-27 13:35:39 +02:00
8d56912765 Actualizando el código 2022-09-27 13:06:04 +02:00
119 changed files with 6780 additions and 5526 deletions

5
.gitignore vendored
View File

@@ -1,5 +1,6 @@
.vscode
*.DS_Store
bin
data/config.bin
data/score.bin
data/config/config.txt
data/config/config.bin
data/config/score.bin

View File

@@ -1,11 +1,16 @@
executable = coffee_crisis
windows:
@echo off
if not exist bin\ (mkdir bin)
g++ -std=c++11 -Wall -O2 source/*.cpp -lmingw32 -lSDL2main -lSDL2 -ffunction-sections -fdata-sections -Wl,--gc-sections -static-libstdc++ -o bin/$(executable).exe
strip -s -R .comment -R .gnu.version bin/$(executable).exe --strip-unneeded
macos:
mkdir -p bin
g++ -std=c++11 -Wall -O2 source/*.cpp -o bin/$(executable)_macos -lSDL2
g++ source/*.cpp -std=c++11 -Wall -O2 -lSDL2 -ffunction-sections -fdata-sections -o bin/$(executable)_macos
linux:
mkdir -p bin
g++ source/*.cpp -std=c++11 -Os -lSDL2 -ffunction-sections -fdata-sections -Wl,--gc-sections -o bin/$(executable)_linux
g++ source/*.cpp -std=c++11 -Wall -Os -lSDL2 -ffunction-sections -fdata-sections -Wl,--gc-sections -o bin/$(executable)_linux
strip -s -R .comment -R .gnu.version bin/$(executable)_linux --strip-unneeded
opendingux:
mkdir -p bin

Binary file not shown.

Binary file not shown.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 57 KiB

37
data/gfx/balloon1.ani Normal file
View File

@@ -0,0 +1,37 @@
frameWidth=8
frameHeight=8
[animation]
name=orange
speed=10
loop=0
frames=0,1,2,3,4,5,6,7,8,9
[/animation]
[animation]
name=blue
speed=20
loop=0
frames=12,13,14,15,16,17,18,19,20,21
[/animation]
[animation]
name=green
speed=10
loop=0
frames=24,25,26,27,28,29,30,31,32,33
[/animation]
[animation]
name=red
speed=20
loop=0
frames=36,37,38,39,40,41,42,43,44,45
[/animation]
[animation]
name=pop
speed=5
loop=-1
frames=48,49,50,51,52,53,54,55,56,57,58,59
[/animation]

BIN
data/gfx/balloon1.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

37
data/gfx/balloon2.ani Normal file
View File

@@ -0,0 +1,37 @@
frameWidth=13
frameHeight=13
[animation]
name=orange
speed=10
loop=0
frames=0,1,2,3,4,5,6,7,8,9
[/animation]
[animation]
name=blue
speed=20
loop=0
frames=12,13,14,15,16,17,18,19,20,21
[/animation]
[animation]
name=green
speed=10
loop=0
frames=24,25,26,27,28,29,30,31,32,33
[/animation]
[animation]
name=red
speed=20
loop=0
frames=36,37,38,39,40,41,42,43,44,45
[/animation]
[animation]
name=pop
speed=5
loop=-1
frames=48,49,50,51,52,53,54,55,56,57,58,59
[/animation]

BIN
data/gfx/balloon2.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.5 KiB

37
data/gfx/balloon3.ani Normal file
View File

@@ -0,0 +1,37 @@
frameWidth=21
frameHeight=21
[animation]
name=orange
speed=10
loop=0
frames=0,1,2,3,4,5,6,7,8,9
[/animation]
[animation]
name=blue
speed=20
loop=0
frames=12,13,14,15,16,17,18,19,20,21
[/animation]
[animation]
name=green
speed=10
loop=0
frames=24,25,26,27,28,29,30,31,32,33
[/animation]
[animation]
name=red
speed=20
loop=0
frames=36,37,38,39,40,41,42,43,44,45
[/animation]
[animation]
name=pop
speed=5
loop=-1
frames=48,49,50,51,52,53,54,55,56,57,58,59
[/animation]

BIN
data/gfx/balloon3.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.1 KiB

44
data/gfx/balloon4.ani Normal file
View File

@@ -0,0 +1,44 @@
frameWidth=37
frameHeight=37
[animation]
name=orange
speed=10
loop=0
frames=0,1,2,3,4,5,6,7,8,9
[/animation]
[animation]
name=blue
speed=20
loop=0
frames=12,13,14,15,16,17,18,19,20,21
[/animation]
[animation]
name=green
speed=10
loop=0
frames=24,25,26,27,28,29,30,31,32,33
[/animation]
[animation]
name=red
speed=20
loop=0
frames=36,37,38,39,40,41,42,43,44,45
[/animation]
[animation]
name=powerball
speed=10
loop=0
frames=10
[/animation]
[animation]
name=pop
speed=5
loop=-1
frames=48,49,50,51,52,53,54,55,56,57,58,59
[/animation]

BIN
data/gfx/balloon4.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

BIN
data/gfx/game_buildings.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.9 KiB

BIN
data/gfx/game_clouds.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 901 B

BIN
data/gfx/game_grass.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 468 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 270 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 795 B

After

Width:  |  Height:  |  Size: 438 B

9
data/gfx/item_clock.ani Normal file
View File

@@ -0,0 +1,9 @@
frameWidth=16
frameHeight=16
[animation]
name=default
speed=10
loop=0
frames=0,1
[/animation]

BIN
data/gfx/item_clock.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 334 B

9
data/gfx/item_coffee.ani Normal file
View File

@@ -0,0 +1,9 @@
frameWidth=16
frameHeight=16
[animation]
name=default
speed=10
loop=0
frames=0,1
[/animation]

BIN
data/gfx/item_coffee.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 462 B

View File

@@ -0,0 +1,9 @@
frameWidth=23
frameHeight=29
[animation]
name=default
speed=10
loop=0
frames=0,1,2,3
[/animation]

Binary file not shown.

After

Width:  |  Height:  |  Size: 553 B

View File

@@ -0,0 +1,9 @@
frameWidth=16
frameHeight=16
[animation]
name=default
speed=10
loop=0
frames=0,1
[/animation]

Binary file not shown.

After

Width:  |  Height:  |  Size: 263 B

View File

@@ -0,0 +1,9 @@
frameWidth=16
frameHeight=16
[animation]
name=default
speed=10
loop=0
frames=0,1
[/animation]

Binary file not shown.

After

Width:  |  Height:  |  Size: 422 B

View File

@@ -0,0 +1,9 @@
frameWidth=16
frameHeight=16
[animation]
name=default
speed=10
loop=0
frames=0,1
[/animation]

Binary file not shown.

After

Width:  |  Height:  |  Size: 388 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.0 KiB

After

Width:  |  Height:  |  Size: 2.5 KiB

BIN
data/gfx/menu_game_over.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 785 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 654 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 887 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 443 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 835 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 529 B

176
data/gfx/player_body.ani Normal file
View File

@@ -0,0 +1,176 @@
frameWidth=24
frameHeight=24
[animation]
name=walk
speed=5
loop=0
frames=0,1,2,3
[/animation]
[animation]
name=stand
speed=10
loop=0
frames=4,5,6,7
[/animation]
[animation]
name=walk_1C
speed=5
loop=0
frames=8,9,10,11
[/animation]
[animation]
name=stand_1C
speed=10
loop=0
frames=12,13,14,15
[/animation]
[animation]
name=walk_2C
speed=5
loop=0
frames=16,17,18,19
[/animation]
[animation]
name=stand_2C
speed=10
loop=0
frames=20,21,22,23
[/animation]
[animation]
name=sideshoot
speed=5
loop=0
frames=24,25,26,27
[/animation]
[animation]
name=centershoot
speed=5
loop=0
frames=28,29,30,31
[/animation]
[animation]
name=sideshoot_1C
speed=5
loop=0
frames=32,33,34,35
[/animation]
[animation]
name=centershoot_1C
speed=5
loop=0
frames=36,37,38,39
[/animation]
[animation]
name=sideshoot_2C
speed=5
loop=0
frames=40,41,42,43
[/animation]
[animation]
name=centershoot_2C
speed=5
loop=0
frames=44,45,46,47
[/animation]
[animation]
name=walk_pwr
speed=3
loop=0
frames=0,1,2,3
[/animation]
[animation]
name=stand_pwr
speed=5
loop=0
frames=4,5,6,7
[/animation]
[animation]
name=walk_1C_pwr
speed=3
loop=0
frames=8,9,10,11
[/animation]
[animation]
name=stand_1C_pwr
speed=5
loop=0
frames=12,13,14,15
[/animation]
[animation]
name=walk_2C_pwr
speed=3
loop=0
frames=16,17,18,19
[/animation]
[animation]
name=stand_2C_pwr
speed=5
loop=0
frames=20,21,22,23
[/animation]
[animation]
name=sideshoot_pwr
speed=2
loop=0
frames=24,25,26,27
[/animation]
[animation]
name=centershoot_pwr
speed=2
loop=0
frames=28,29,30,31
[/animation]
[animation]
name=sideshoot_1C_pwr
speed=2
loop=0
frames=32,33,34,35
[/animation]
[animation]
name=centershoot_1C_pwr
speed=2
loop=0
frames=36,37,38,39
[/animation]
[animation]
name=sideshoot_2C_pwr
speed=2
loop=0
frames=40,41,42,43
[/animation]
[animation]
name=centershoot_2C_pwr
speed=2
loop=0
frames=44,45,46,47
[/animation]

View File

@@ -0,0 +1,9 @@
frameWidth=24
frameHeight=24
[animation]
name=default
speed=5
loop=0
frames=0,1,2,3
[/animation]

9
data/gfx/player_fire.ani Normal file
View File

@@ -0,0 +1,9 @@
frameWidth=28
frameHeight=32
[animation]
name=default
speed=5
loop=0
frames=0,1,2,3
[/animation]

114
data/gfx/player_head.ani Normal file
View File

@@ -0,0 +1,114 @@
frameWidth=24
frameHeight=24
[animation]
name=walk
speed=5
loop=0
frames=0,1,2,3
[/animation]
[animation]
name=stand
speed=10
loop=0
frames=4,5,6,7
[/animation]
[animation]
name=walk_1C
speed=5
loop=0
frames=8,9,10,11
[/animation]
[animation]
name=stand_1C
speed=10
loop=0
frames=12,13,14,15
[/animation]
[animation]
name=walk_pwr
speed=5
loop=0
frames=16,17,18,19
[/animation]
[animation]
name=stand_pwr
speed=10
loop=0
frames=20,21,22,23
[/animation]
[animation]
name=walk_1C_pwr
speed=5
loop=0
frames=24,25,26,27
[/animation]
[animation]
name=stand_1C_pwr
speed=10
loop=0
frames=28,29,30,31
[/animation]
[animation]
name=sideshoot
speed=5
loop=0
frames=16,17,18,19
[/animation]
[animation]
name=centershoot
speed=5
loop=0
frames=20,21,22,23
[/animation]
[animation]
name=sideshoot_1C
speed=5
loop=0
frames=24,25,26,27
[/animation]
[animation]
name=centershoot_1C
speed=5
loop=0
frames=28,29,30,31
[/animation]
[animation]
name=sideshoot_pwr
speed=2
loop=0
frames=16,17,18,19
[/animation]
[animation]
name=centershoot_pwr
speed=2
loop=0
frames=20,21,22,23
[/animation]
[animation]
name=sideshoot_1C_pwr
speed=2
loop=0
frames=24,25,26,27
[/animation]
[animation]
name=centershoot_1C_pwr
speed=2
loop=0
frames=28,29,30,31
[/animation]

16
data/gfx/player_legs.ani Normal file
View File

@@ -0,0 +1,16 @@
frameWidth=24
frameHeight=24
[animation]
name=walk
speed=5
loop=0
frames=0,1,2,3
[/animation]
[animation]
name=stand
speed=10
loop=0
frames=4,5,6,7
[/animation]

Binary file not shown.

Before

Width:  |  Height:  |  Size: 71 KiB

BIN
data/gfx/title_bg_tile.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 899 B

BIN
data/gfx/title_coffee.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 KiB

BIN
data/gfx/title_crisis.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

9
data/gfx/title_dust.ani Normal file
View File

@@ -0,0 +1,9 @@
frameWidth=16
frameHeight=16
[animation]
name=default
speed=8
loop=-1
frames=0,1,2,3,4,5,6
[/animation]

BIN
data/gfx/title_dust.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 212 B

BIN
data/gfx/title_gradient.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 67 KiB

View File

@@ -1,160 +1,239 @@
## 0 - MENU DEL TITULO
JUGAR
## 1 - MENU DEL TITULO
OPCIONS
## 2 - MENU DEL TITULO
INSTRUCCIONS
## 3 - MENU DEL TITULO
EIXIR
## 4 - MENU DE OPCIONES
FINESTRA
## 5 - MENU DE OPCIONES
PANTALLA COMPLETA
## 6 - MENU DE OPCIONES
PANTALLA COMPLETA FALSA
## 7 - MENU DE OPCIONES
TAMANY DE FINESTRA
## 8 - MENU DE OPCIONES
IDIOMA
## 9 - MENU DE OPCIONES
[ ACEPTAR ]
## 10 - MENU DE OPCIONES
[ CANCELAR ]
## 11 - INSTRUCCIONES
OBJECTIU
## 12 - INSTRUCCIONES
HAS D'EXPLOTAR
## 13 - INSTRUCCIONES
TANTS GLOBUS COM PUGUES
## 14 - INSTRUCCIONES
LA DIFICULTAT AUGMENTA
## 15 - INSTRUCCIONES
A MESURA QUE VAS PUNTUANT
## 16 - INSTRUCCIONES
OBJECTES
## 17 - INSTRUCCIONES
1.000 PUNTS
## 18 - INSTRUCCIONES
2.500 PUNTS
## 19 - INSTRUCCIONES
5.000 PUNTS
## 20 - INSTRUCCIONES
PARA EL TEMPS
## 21 - INSTRUCCIONES
VIDA EXTRA
## 22 - INSTRUCCIONES
PREM UNA TECLA PER A TORNAR
## 23 - TITULO
PREM QUALSEVOL TECLA
## 24 - MENU SELECCION DE IDIOMA
ESPA{OL (ESPANYOL)
## 25 - MENU SELECCION DE IDIOMA
BALOONCIA
## 26 - MENU SELECCION DE IDIOMA
ENGLISH (ANGLES)
## 27 - INTRO
Un dia qualsevol de l'any 2000
## 28 - INTRO
Tot esta tranquil a la UPV
## 29 - INTRO
Fins que un desaprensiu...
## 30 - INTRO
HEY! ME ANE A FERME UN CORTAET...
## 31 - INTRO
UAAAAAAAAAAAAA!!!
## 32 - INTRO
Espera un moment...
## 33 - INTRO
Si resulta que no tinc solt!
## 34 - INTRO
MERDA DE MAQUINA!
## 35 - INTRO
Blop... blop... blop...
## 36 - TEXTOS DEL JUEGO
Temps detes:
## 37 - TEXTOS DEL JUEGO
D E M O
## 38 - TEXTOS DEL JUEGO
fases mes!
## 39 -
## 40 -
## 39 - MENU SELECCION DE JUGADOR
Selecciona personatge
## 41 -
## 40 - MENU SELECCION DE JUGADOR
Enrere
## 41 - MENU DE PAUSA
Menu de pausa
## 42 -
-
## 43 - PANTALLA DE GAME OVER
FI DEL JOC
## 44 - PANTALLA DE GAME OVER
ELS TEUS PUNTS:
## 45 - PANTALLA DE GAME OVER
CONTINUAR?
## 46 - MENU DE PAUSA
CONTINUAR
## 47 - MENU DE PAUSA
EIXIR DEL JOC
## 48 - MENU GAME OVER
SI
## 49 - MENU GAME OVER
NO
## 50 - TEXTO DE COMPLETAR EL JUEGO
Felicitats!!
## 51 - MENU DEL TITULO
1 JUGADOR
## 52 - MENU DEL TITULO
2 JUGADORS
## 53 MARCADOR
jugador 1
## 54 MARCADOR
jugador 2
## 55 MARCADOR
mult
## 56 MARCADOR
max. puntuacio
## 57 MARCADOR
fase
## 58 - MENU DE OPCIONES
MODE DE VISUALITZACIO
## 59 - MENU DE OPCIONES
DIFICULTAT
## 60 - MENU DE OPCIONES
FILTRE
## 61 - MENU DE OPCIONES
SINC. VERTICAL
## 62 - MENU DE OPCIONES
CONTROLS DEL JUGADOR 1
## 63 - MENU DE OPCIONES
CONTROLS DEL JUGADOR 2
## 64 -
-
## 65 -
-
## 66 - MENU DE OPCIONES
FACIL
## 67 - MENU DE OPCIONES
NORMAL
## 68 - MENU DE OPCIONES
DIFICIL
## 69 - MENU DE OPCIONES
TECLAT
## 70 - MENU DE OPCIONES
MANDO
## 71 - MENU DE OPCIONES
LINEAL
## 72 - MENU DE OPCIONES
NEAREST
## 73 - MENU DE OPCIONES
ACTIVADA
## 74 - MENU DE OPCIONES
DESACTIVADA
## 75 - JUEGO
Endavant!
## 76 - JUEGO
1.000.000 de punts!
## 77 - PANTALLA DE GAME OVER
PUNTS J1:
## 78 - PANTALLA DE GAME OVER
PUNTS J2:
## 79 - TEXTOS DEL JUEGO
Ultima fase!

View File

@@ -1,160 +1,239 @@
## 0 - MENU DEL TITULO
PLAY
## 1 - MENU DEL TITULO
OPTIONS
## 2 - MENU DEL TITULO
HOW TO PLAY
## 3 - MENU DEL TITULO
QUIT
## 4 - MENU DE OPCIONES
WINDOW
## 5 - MENU DE OPCIONES
FULLSCREEN
## 6 - MENU DE OPCIONES
FAKE FULLSCREEN
## 7 - MENU DE OPCIONES
WINDOW SIZE
## 8 - MENU DE OPCIONES
LANGUAGE
## 9 - MENU DE OPCIONES
[ ACCEPT ]
## 10 - MENU DE OPCIONES
[ CANCEL ]
## 11 - INSTRUCCIONES
OBJECTIVE
## 12 - INSTRUCCIONES
YOU HAVE TO POP AS MANY
## 13 - INSTRUCCIONES
BALLOONS AS YOU CAN
## 14 - INSTRUCCIONES
DIFFICULTY WILL BE INCREASED
## 15 - INSTRUCCIONES
AS YOU SCORE POINTS
## 16 - INSTRUCCIONES
ITEMS
## 17 - INSTRUCCIONES
1.000 POINTS
## 18 - INSTRUCCIONES
2.500 POINTS
## 19 - INSTRUCCIONES
5.000 POINTS
## 20 - INSTRUCCIONES
TIME STOPPER
## 21 - INSTRUCCIONES
EXTRA HIT
## 22 - INSTRUCCIONES
PRESS ANY KEY TO RETURN
## 23 - TITULO
PRESS ANY KEY
## 24 - MENU SELECCION DE IDIOMA
ESPA{OL (SPANISH)
## 25 - MENU SELECCION DE IDIOMA
BALOONCIA (VALENCIAN)
## 26 - MENU SELECCION DE IDIOMA
ENGLISH
## 27 - INTRO
Any day of the year 2000
## 28 - INTRO
Everything is quiet at the UPV
## 29 - INTRO
Until a bastard arrives...
## 30 - INTRO
YO! GONNA TAKE A CAFELITO...
## 31 - INTRO
AAAAAAAARGHHHH!!!
## 32 - INTRO
Wait a moment...
## 33 - INTRO
I don't have any loose!
## 34 - INTRO
FUCKING MACHINE!
## 35 - INTRO
Blop... blop... blop...
## 36 - TEXTOS DEL JUEGO
Time stopped:
## 37 - TEXTOS DEL JUEGO
D E M O
## 38 - TEXTOS DEL JUEGO
stages left!
## 39 -
## 40 -
## 39 - MENU SELECCION DE JUGADOR
Select Player
## 41 -
## 40 - MENU SELECCION DE JUGADOR
Back
## 41 - MENU DE PAUSA
Pause Menu
## 42 -
-
## 43 - PANTALLA DE GAME OVER
GAME OVER
## 44 - PANTALLA DE GAME OVER
YOUR SCORE:
## 45 - PANTALLA DE GAME OVER
CONTINUE?
## 46 - MENU DE PAUSA
CONTINUE
## 47 - MENU DE PAUSA
LEAVE GAME
## 48 - MENU GAME OVER
YES
## 49 - MENU GAME OVER
NO
## 50 - TEXTO DE COMPLETAR EL JUEGO
Congratulations!!
## 51 - MENU DEL TITULO
1 PLAYER
## 52 - MENU DEL TITULO
2 PLAYERS
## 53 - MARCADOR
player 1
## 54 - MARCADOR
player 2
## 55 - MARCADOR
mult
## 56 - MARCADOR
high score
## 57 - MARCADOR
stage
## 58 - MENU DE OPCIONES
DISPLAY MODE
## 59 - MENU DE OPCIONES
DIFFICULTY
## 60 - MENU DE OPCIONES
FILTER
## 61 - MENU DE OPCIONES
VSYNC
## 62 - MENU DE OPCIONES
PLAYER 1 CONTROLS
## 63 - MENU DE OPCIONES
PLAYER 2 CONTROLS
## 64 -
-
## 65 -
-
## 66 - MENU DE OPCIONES
EASY
## 67 - MENU DE OPCIONES
NORMAL
## 68 - MENU DE OPCIONES
HARD
## 69 - MENU DE OPCIONES
KEYBOARD
## 70 - MENU DE OPCIONES
GAME CONTROLLER
## 71 - MENU DE OPCIONES
LINEAL
## 72 - MENU DE OPCIONES
NEAREST
## 73 - MENU DE OPCIONES
ON
## 74 - MENU DE OPCIONES
OFF
## 75 - JUEGO
Get Ready!
## 76 - JUEGO
1.000.000 points!
## 77 - PANTALLA DE GAME OVER
PLAYER1 SCORE:
## 78 - PANTALLA DE GAME OVER
PLAYER2 SCORE:
## 79 - TEXTOS DEL JUEGO
Last stage!

View File

@@ -1,160 +1,239 @@
## 0 - MENU DEL TITULO
JUGAR
## 1 - MENU DEL TITULO
OPCIONES
## 2 - MENU DEL TITULO
INSTRUCCIONES
## 3 - MENU DEL TITULO
SALIR
## 4 - MENU DE OPCIONES
VENTANA
## 5 - MENU DE OPCIONES
PANTALLA COMPLETA
## 6 - MENU DE OPCIONES
PANTALLA COMPLETA FALSA
## 7 - MENU DE OPCIONES
TAMA{O DE VENTANA
## 8 - MENU DE OPCIONES
IDIOMA
## 9 - MENU DE OPCIONES
[ ACEPTAR ]
## 10 - MENU DE OPCIONES
[ CANCELAR ]
## 11 - INSTRUCCIONES
OBJETIVO
## 12 - INSTRUCCIONES
TIENES QUE EXPLOTAR
## 13 - INSTRUCCIONES
TANTOS GLOBOS COMO PUEDAS
## 14 - INSTRUCCIONES
LA DIFICULTAD SE INCREMENTA
## 15 - INSTRUCCIONES
A MEDIDA QUE VAS PUNTUANDO
## 16 - INSTRUCCIONES
OBJETOS
## 17 - INSTRUCCIONES
1.000 PUNTOS
## 18 - INSTRUCCIONES
2.500 PUNTOS
## 19 - INSTRUCCIONES
5.000 PUNTOS
## 20 - INSTRUCCIONES
DETIENE EL TIEMPO
## 21 - INSTRUCCIONES
VIDA EXTRA
## 22 - INSTRUCCIONES
PULSA UNA TECLA PARA VOLVER
## 23 - TITULO
PULSA CUALQUIER TECLA
## 24 - MENU SELECCION DE IDIOMA
ESPA{OL
## 25 - MENU SELECCION DE IDIOMA
BALOONCIA (VALENCIANO)
## 26 - MENU SELECCION DE IDIOMA
ENGLISH (INGLES)
## 27 - INTRO
Un dia cualquiera del a{o 2000
## 28 - INTRO
Todo esta tranquilo en la UPV
## 29 - INTRO
Hasta que un desaprensivo...
## 30 - INTRO
HEY! VOY A SACARME UN TALLADET...
## 31 - INTRO
UAAAAAAAAAAAAA!!!
## 32 - INTRO
Espera un momento...
## 33 - INTRO
Si no llevo suelto encima!
## 34 - INTRO
MIERDA DE MAQUINA!
## 35 - INTRO
Blop... blop... blop...
## 36 - TEXTOS DEL JUEGO
Tiempo:
## 37 - TEXTOS DEL JUEGO
D E M O
## 38 - TEXTOS DEL JUEGO
fases mas!
## 39 -
## 40 -
## 39 - MENU SELECCION DE JUGADOR
Selecciona jugador
## 41 -
## 40 - MENU SELECCION DE JUGADOR
Volver
## 41 - MENU DE PAUSA
Menu de pausa
## 42 -
-
## 43 - PANTALLA DE GAME OVER
FIN DE JUEGO
## 44 - PANTALLA DE GAME OVER
TU PUNTUACION:
## 45 - PANTALLA DE GAME OVER
CONTINUAR?
## 46 - MENU DE PAUSA
CONTINUAR
## 47 - MENU DE PAUSA
SALIR DEL JUEGO
## 48 - MENU GAME OVER
SI
## 49 - MENU GAME OVER
NO
## 50 - TEXTO DE COMPLETAR EL JUEGO
Felicidades!!
## 51 - MENU DEL TITULO
1 JUGADOR
## 52 - MENU DEL TITULO
2 JUGADORES
## 53 - MARCADOR
jugador 1
## 54 - MARCADOR
jugador 2
## 55 - MARCADOR
mult
## 56 - MARCADOR
max. puntuacion
## 57 - MARCADOR
FASE
## 58 - MENU DE OPCIONES
MODO DE VISUALIZACION
## 59 - MENU DE OPCIONES
DIFICULTAD
## 60 - MENU DE OPCIONES
FILTRO
## 61 - MENU DE OPCIONES
SINC. VERTICAL
## 62 - MENU DE OPCIONES
CONTROLES DEL JUGADOR 1
## 63 - MENU DE OPCIONES
CONTROLES DEL JUGADOR 2
## 64 -
-
## 65 -
-
## 66 - MENU DE OPCIONES
FACIL
## 67 - MENU DE OPCIONES
NORMAL
## 68 - MENU DE OPCIONES
DIFICIL
## 69 - MENU DE OPCIONES
TECLADO
## 70 - MENU DE OPCIONES
MANDO
## 71 - MENU DE OPCIONES
LINEAL
## 72 - MENU DE OPCIONES
NEAREST
## 73 - MENU DE OPCIONES
ACTIVADA
## 74 - MENU DE OPCIONES
DESACTIVADA
## 75 - JUEGO
Adelante!
## 76 - JUEGO
1.000.000 de puntos!
## 77 - PANTALLA DE GAME OVER
PUNTUACION J1:
## 78 - PANTALLA DE GAME OVER
PUNTUACION J2:
## 79 - TEXTOS DEL JUEGO
Ultima fase!

29
data/menu/gameover.men Normal file
View File

@@ -0,0 +1,29 @@
font_png=smb2.png
font_txt=smb2.txt
sound_move=menu_move.wav
sound_accept=menu_select.wav
name=GAME OVER
x=0
y=120
backgroundType=0
backgroundColor=128,64,0,0
areElementsCenteredOnX=true
isCenteredOnX=true
centerX=199
selector_color=255,122,0,255
selector_text_color=255,255,235
defaultActionWhenCancel=1
[item]
text=SI
hPaddingDown=2
[/item]
[item]
text=NO
[/item]

108
data/menu/options.men Normal file
View File

@@ -0,0 +1,108 @@
font_png=smb2.png
font_txt=smb2.txt
sound_move=menu_move.wav
sound_accept=menu_select.wav
name=OPTIONS
x=0
y=116
backgroundType=0
backgroundColor=48,48,64,192
areElementsCenteredOnX=true
isCenteredOnX=true
centerX=128
isCenteredOnY=true
centerY=96
selector_color=229,28,35,255
selector_text_color=255,241,118
defaultActionWhenCancel=13
[item]
text=DIFFICULTY
hPaddingDown=7
[/item]
[item]
text=PLAYER 1 CONTROLS
hPaddingDown=2
selectable=true
greyed=false
linkedDown=true
[/item]
[item]
text=KEYBOARD
hPaddingDown=7
selectable=false
greyed=false
[/item]
[item]
text=PLAYER 2 CONTROLS
hPaddingDown=2
selectable=true
greyed=false
linkedDown=true
[/item]
[item]
text=GAME CONTROLLER
hPaddingDown=7
selectable=false
greyed=false
[/item]
[item]
text=LANGUAGE
hPaddingDown=7
[/item]
[item]
text=DISPLAY MODE
hPaddingDown=2
selectable=true
greyed=false
linkedDown=true
[/item]
[item]
text=WINDOW
hPaddingDown=7
selectable=false
greyed=false
[/item]
[item]
text=WINDOW SIZE
hPaddingDown=2
[/item]
[item]
text=FILTER
hPaddingDown=2
[/item]
[item]
text=VSYNC
hPaddingDown=7
[/item]
[item]
text=HOW TO PLAY
hPaddingDown=7
[/item]
[item]
text=ACCEPT
hPaddingDown=2
[/item]
[item]
text=CANCEL
[/item]

35
data/menu/pause.men Normal file
View File

@@ -0,0 +1,35 @@
font_png=smb2.png
font_txt=smb2.txt
sound_move=menu_move.wav
sound_accept=menu_select.wav
name=PAUSE
x=0
y=80
backgroundType=1
backgroundColor=41,57,65,240
areElementsCenteredOnX=true
isCenteredOnX=true
centerX=128
selector_color=255,122,0,255
selector_text_color=255,255,255
defaultActionWhenCancel=1
[item]
text=PAUSE MENU
hPaddingDown=7
selectable=false
[/item]
[item]
text=CONTINUE
hPaddingDown=2
[/item]
[item]
text=LEAVE GAME
[/item]

View File

@@ -0,0 +1,40 @@
font_png=smb2.png
font_txt=smb2.txt
sound_move=menu_move.wav
sound_accept=menu_select.wav
name=PLAYER_SELECT
x=0
y=116
backgroundType=0
backgroundColor=48,48,64,192
areElementsCenteredOnX=true
isCenteredOnX=true
centerX=128
selector_color=229,28,35,0
selector_text_color=255,180,0
defaultActionWhenCancel=3
[item]
text=SELECT PLAYER
hPaddingDown=7
selectable=false
[/item]
[item]
text=BAL1
hPaddingDown=2
[/item]
[item]
text=AROUNDER
hPaddingDown=7
[/item]
[item]
text=BACK
[/item]

39
data/menu/title.men Normal file
View File

@@ -0,0 +1,39 @@
font_png=smb2.png
font_txt=smb2.txt
sound_move=menu_move.wav
sound_accept=menu_select.wav
name=TITLE
x=0
y=116
backgroundType=0
backgroundColor=48,48,64,192
areElementsCenteredOnX=true
isCenteredOnX=true
centerX=128
selector_color=229,28,35,0
selector_text_color=255,180,0
defaultActionWhenCancel=3
[item]
text=1 PLAYER
hPaddingDown=2
[/item]
[item]
text=2 PLAYERS
hPaddingDown=7
[/item]
[item]
text=OPTIONS
hPaddingDown=7
[/item]
[item]
text=QUIT
[/item]

Binary file not shown.

View File

@@ -1,15 +1,22 @@
#include "animatedsprite.h"
// Constructor
AnimatedSprite::AnimatedSprite(LTexture *texture, SDL_Renderer *renderer, std::string file)
AnimatedSprite::AnimatedSprite(LTexture *texture, SDL_Renderer *renderer, std::string file, std::vector<std::string> *buffer)
{
// Copia los punteros
setTexture(texture);
setRenderer(renderer);
// Carga las animaciones
load(file);
if (file != "")
{
loadFromFile(file);
}
else if (buffer)
{
loadFromVector(buffer);
}
// Inicializa variables
currentAnimation = 0;
@@ -47,37 +54,37 @@ int AnimatedSprite::getIndex(std::string name)
// Calcula el frame correspondiente a la animación
void AnimatedSprite::animate()
{
if (!enabled || animation[currentAnimation].speed == 0)
if (!enabled || animation.at(currentAnimation).speed == 0)
{
return;
}
// Calcula el frame actual a partir del contador
animation[currentAnimation].currentFrame = animation[currentAnimation].counter / animation[currentAnimation].speed;
animation.at(currentAnimation).currentFrame = animation.at(currentAnimation).counter / animation.at(currentAnimation).speed;
// Si alcanza el final de la animación, reinicia el contador de la animación
// en función de la variable loop y coloca el nuevo frame
if (animation[currentAnimation].currentFrame >= (int)animation[currentAnimation].frames.size())
if (animation.at(currentAnimation).currentFrame >= (int)animation.at(currentAnimation).frames.size())
{
if (animation[currentAnimation].loop == -1)
if (animation.at(currentAnimation).loop == -1)
{ // Si no hay loop, deja el último frame
animation[currentAnimation].currentFrame = animation[currentAnimation].frames.size();
animation[currentAnimation].completed = true;
animation.at(currentAnimation).currentFrame = animation.at(currentAnimation).frames.size();
animation.at(currentAnimation).completed = true;
}
else
{ // Si hay loop, vuelve al frame indicado
animation[currentAnimation].counter = 0;
animation[currentAnimation].currentFrame = animation[currentAnimation].loop;
animation.at(currentAnimation).counter = 0;
animation.at(currentAnimation).currentFrame = animation.at(currentAnimation).loop;
}
}
// En caso contrario
else
{
// Escoge el frame correspondiente de la animación
setSpriteClip(animation[currentAnimation].frames[animation[currentAnimation].currentFrame]);
setSpriteClip(animation.at(currentAnimation).frames.at(animation.at(currentAnimation).currentFrame));
// Incrementa el contador de la animacion
animation[currentAnimation].counter++;
animation.at(currentAnimation).counter++;
}
}
@@ -85,78 +92,85 @@ void AnimatedSprite::animate()
void AnimatedSprite::setCurrentFrame(int num)
{
// Descarta valores fuera de rango
if (num >= (int)animation[currentAnimation].frames.size())
if (num >= (int)animation.at(currentAnimation).frames.size())
{
num = 0;
}
// Cambia el valor de la variable
animation[currentAnimation].counter = animation[currentAnimation].speed * num;
animation.at(currentAnimation).counter = animation.at(currentAnimation).speed * num;
// Escoge el frame correspondiente de la animación
setSpriteClip(animation[currentAnimation].frames[animation[currentAnimation].currentFrame]);
setSpriteClip(animation.at(currentAnimation).frames.at(animation.at(currentAnimation).currentFrame));
}
// Establece el valor del contador
void AnimatedSprite::setAnimationCounter(std::string name, int num)
{
animation[getIndex(name)].counter = num;
animation.at(getIndex(name)).counter = num;
}
// Establece la velocidad de una animación
void AnimatedSprite::setAnimationSpeed(std::string name, int speed)
{
animation[getIndex(name)].counter = speed;
animation.at(getIndex(name)).counter = speed;
}
// Establece la velocidad de una animación
void AnimatedSprite::setAnimationSpeed(int index, int speed)
{
animation[index].counter = speed;
animation.at(index).counter = speed;
}
// Establece si la animación se reproduce en bucle
void AnimatedSprite::setAnimationLoop(std::string name, int loop)
{
animation[getIndex(name)].loop = loop;
animation.at(getIndex(name)).loop = loop;
}
// Establece si la animación se reproduce en bucle
void AnimatedSprite::setAnimationLoop(int index, int loop)
{
animation[index].loop = loop;
animation.at(index).loop = loop;
}
// Establece el valor de la variable
void AnimatedSprite::setAnimationCompleted(std::string name, bool value)
{
animation[getIndex(name)].completed = value;
animation.at(getIndex(name)).completed = value;
}
// OLD - Establece el valor de la variable
void AnimatedSprite::setAnimationCompleted(int index, bool value)
{
animation[index].completed = value;
animation.at(index).completed = value;
}
// Comprueba si ha terminado la animación
bool AnimatedSprite::animationIsCompleted()
{
return animation[currentAnimation].completed;
return animation.at(currentAnimation).completed;
}
// Devuelve el rectangulo de una animación y frame concreto
SDL_Rect AnimatedSprite::getAnimationClip(std::string name, Uint8 index)
{
return animation[getIndex(name)].frames[index];
return animation.at(getIndex(name)).frames.at(index);
}
// Devuelve el rectangulo de una animación y frame concreto
SDL_Rect AnimatedSprite::getAnimationClip(int indexA, Uint8 indexF)
{
return animation.at(indexA).frames.at(indexF);
}
// Carga la animación desde un fichero
bool AnimatedSprite::load(std::string filePath)
bool AnimatedSprite::loadFromFile(std::string filePath)
{
int frames_per_row = 0;
int frame_width = 0;
int frame_height = 0;
int framesPerRow = 0;
int frameWidth = 0;
int frameHeight = 0;
int maxTiles = 0;
// Indicador de éxito en la carga
bool success = true;
@@ -169,7 +183,7 @@ bool AnimatedSprite::load(std::string filePath)
if (file.good())
{
// Procesa el fichero linea a linea
printf("Reading file %s\n", filename.c_str());
std::cout << "Loading animation from file: " << filePath.c_str() << std::endl;
while (std::getline(file, line))
{
// Si la linea contiene el texto [animation] se realiza el proceso de carga de una animación
@@ -194,28 +208,33 @@ bool AnimatedSprite::load(std::string filePath)
{
buffer.name = line.substr(pos + 1, line.length());
}
else if (line.substr(0, pos) == "speed")
{
buffer.speed = std::stoi(line.substr(pos + 1, line.length()));
}
else if (line.substr(0, pos) == "loop")
{
buffer.loop = std::stoi(line.substr(pos + 1, line.length()));
}
else if (line.substr(0, pos) == "frames")
{
// Se introducen los valores separados por comas en un vector
std::stringstream ss(line.substr(pos + 1, line.length()));
std::string tmp;
SDL_Rect rect = {0, 0, frame_width, frame_height};
SDL_Rect rect = {0, 0, frameWidth, frameHeight};
while (getline(ss, tmp, ','))
{
int num_tile = std::stoi(tmp);
rect.x = (num_tile % frames_per_row) * frame_width;
rect.y = (num_tile / frames_per_row) * frame_height;
// Comprueba que el tile no sea mayor que el maximo indice permitido
const int numTile = std::stoi(tmp) > maxTiles ? 0 : std::stoi(tmp);
rect.x = (numTile % framesPerRow) * frameWidth;
rect.y = (numTile / framesPerRow) * frameHeight;
buffer.frames.push_back(rect);
}
}
else
{
printf("Warning: file %s, unknown parameter \"%s\"\n", filename.c_str(), line.substr(0, pos).c_str());
@@ -237,25 +256,19 @@ bool AnimatedSprite::load(std::string filePath)
// Procesa las dos subcadenas
if (pos != (int)line.npos)
{
if (line.substr(0, pos) == "frames_per_row")
if (line.substr(0, pos) == "framesPerRow")
{
frames_per_row = std::stoi(line.substr(pos + 1, line.length()));
framesPerRow = std::stoi(line.substr(pos + 1, line.length()));
}
else if (line.substr(0, pos) == "frame_width")
else if (line.substr(0, pos) == "frameWidth")
{
frame_width = std::stoi(line.substr(pos + 1, line.length()));
// Normaliza valores
if (frames_per_row == 0)
{
frames_per_row = texture->getWidth() / frame_width;
}
frameWidth = std::stoi(line.substr(pos + 1, line.length()));
}
else if (line.substr(0, pos) == "frame_height")
else if (line.substr(0, pos) == "frameHeight")
{
frame_height = std::stoi(line.substr(pos + 1, line.length()));
frameHeight = std::stoi(line.substr(pos + 1, line.length()));
}
else
@@ -263,12 +276,24 @@ bool AnimatedSprite::load(std::string filePath)
printf("Warning: file %s, unknown parameter \"%s\"\n", filename.c_str(), line.substr(0, pos).c_str());
success = false;
}
// Normaliza valores
if (framesPerRow == 0 && frameWidth > 0)
{
framesPerRow = texture->getWidth() / frameWidth;
}
if (maxTiles == 0 && frameWidth > 0 && frameHeight > 0)
{
const int w = texture->getWidth() / frameWidth;
const int h = texture->getHeight() / frameHeight;
maxTiles = w * h;
}
}
}
}
// Cierra el fichero
printf("Closing file %s\n\n", filename.c_str());
file.close();
}
// El fichero no se puede abrir
@@ -279,7 +304,145 @@ bool AnimatedSprite::load(std::string filePath)
}
// Pone un valor por defecto
setPos({0, 0, frame_width, frame_height});
setPos({0, 0, frameWidth, frameHeight});
return success;
}
// Carga la animación desde un vector
bool AnimatedSprite::loadFromVector(std::vector<std::string> *source)
{
// Inicializa variables
int framesPerRow = 0;
int frameWidth = 0;
int frameHeight = 0;
int maxTiles = 0;
// Indicador de éxito en el proceso
bool success = true;
std::string line;
// Recorre todo el vector
int index = 0;
while (index < (int)source->size())
{
// Lee desde el vector
line = source->at(index);
// Si la linea contiene el texto [animation] se realiza el proceso de carga de una animación
if (line == "[animation]")
{
t_animation buffer;
buffer.counter = 0;
buffer.currentFrame = 0;
buffer.completed = false;
do
{
// Aumenta el indice para leer la siguiente linea
index++;
line = source->at(index);
// Encuentra la posición del caracter '='
int pos = line.find("=");
// Procesa las dos subcadenas
if (pos != (int)line.npos)
{
if (line.substr(0, pos) == "name")
{
buffer.name = line.substr(pos + 1, line.length());
}
else if (line.substr(0, pos) == "speed")
{
buffer.speed = std::stoi(line.substr(pos + 1, line.length()));
}
else if (line.substr(0, pos) == "loop")
{
buffer.loop = std::stoi(line.substr(pos + 1, line.length()));
}
else if (line.substr(0, pos) == "frames")
{
// Se introducen los valores separados por comas en un vector
std::stringstream ss(line.substr(pos + 1, line.length()));
std::string tmp;
SDL_Rect rect = {0, 0, frameWidth, frameHeight};
while (getline(ss, tmp, ','))
{
// Comprueba que el tile no sea mayor que el maximo indice permitido
const int numTile = std::stoi(tmp) > maxTiles ? 0 : std::stoi(tmp);
rect.x = (numTile % framesPerRow) * frameWidth;
rect.y = (numTile / framesPerRow) * frameHeight;
buffer.frames.push_back(rect);
}
}
else
{
std::cout << "Warning: unknown parameter " << line.substr(0, pos).c_str() << std::endl;
success = false;
}
}
} while (line != "[/animation]");
// Añade la animación al vector de animaciones
animation.push_back(buffer);
}
// En caso contrario se parsea el fichero para buscar las variables y los valores
else
{
// Encuentra la posición del caracter '='
int pos = line.find("=");
// Procesa las dos subcadenas
if (pos != (int)line.npos)
{
if (line.substr(0, pos) == "framesPerRow")
{
framesPerRow = std::stoi(line.substr(pos + 1, line.length()));
}
else if (line.substr(0, pos) == "frameWidth")
{
frameWidth = std::stoi(line.substr(pos + 1, line.length()));
}
else if (line.substr(0, pos) == "frameHeight")
{
frameHeight = std::stoi(line.substr(pos + 1, line.length()));
}
else
{
std::cout << "Warning: unknown parameter " << line.substr(0, pos).c_str() << std::endl;
success = false;
}
// Normaliza valores
if (framesPerRow == 0 && frameWidth > 0)
{
framesPerRow = texture->getWidth() / frameWidth;
}
if (maxTiles == 0 && frameWidth > 0 && frameHeight > 0)
{
const int w = texture->getWidth() / frameWidth;
const int h = texture->getHeight() / frameHeight;
maxTiles = w * h;
}
}
}
// Una vez procesada la linea, aumenta el indice para pasar a la siguiente
index++;
}
// Pone un valor por defecto
setPos({0, 0, frameWidth, frameHeight});
return success;
}
@@ -291,9 +454,9 @@ void AnimatedSprite::setCurrentAnimation(std::string name)
if (currentAnimation != newAnimation)
{
currentAnimation = newAnimation;
animation[currentAnimation].currentFrame = 0;
animation[currentAnimation].counter = 0;
animation[currentAnimation].completed = false;
animation.at(currentAnimation).currentFrame = 0;
animation.at(currentAnimation).counter = 0;
animation.at(currentAnimation).completed = false;
}
}
@@ -304,9 +467,9 @@ void AnimatedSprite::setCurrentAnimation(int index)
if (currentAnimation != newAnimation)
{
currentAnimation = newAnimation;
animation[currentAnimation].currentFrame = 0;
animation[currentAnimation].counter = 0;
animation[currentAnimation].completed = false;
animation.at(currentAnimation).currentFrame = 0;
animation.at(currentAnimation).counter = 0;
animation.at(currentAnimation).completed = false;
}
}
@@ -320,14 +483,22 @@ void AnimatedSprite::update()
// Establece el rectangulo para un frame de una animación
void AnimatedSprite::setAnimationFrames(Uint8 index_animation, Uint8 index_frame, int x, int y, int w, int h)
{
animation[index_animation].frames.push_back({x, y, w, h});
animation.at(index_animation).frames.push_back({x, y, w, h});
}
// OLD - Establece el contador para todas las animaciones
void AnimatedSprite::setAnimationCounter(int value)
{
for (auto &a:animation)
for (auto &a : animation)
{
a.counter = value;
}
}
// Reinicia la animación
void AnimatedSprite::resetAnimation()
{
animation.at(currentAnimation).currentFrame = 0;
animation.at(currentAnimation).counter = 0;
animation.at(currentAnimation).completed = false;
}

View File

@@ -6,6 +6,7 @@
#include <string>
#include <sstream>
#include <fstream>
#include <iostream>
#ifndef ANIMATEDSPRITE_H
#define ANIMATEDSPRITE_H
@@ -29,7 +30,7 @@ private:
public:
// Constructor
AnimatedSprite(LTexture *texture = nullptr, SDL_Renderer *renderer = nullptr, std::string file = "");
AnimatedSprite(LTexture *texture = nullptr, SDL_Renderer *renderer = nullptr, std::string file = "", std::vector<std::string> *buffer = nullptr);
// Destructor
~AnimatedSprite();
@@ -60,12 +61,16 @@ public:
// Devuelve el rectangulo de una animación y frame concreto
SDL_Rect getAnimationClip(std::string name, Uint8 index);
SDL_Rect getAnimationClip(int indexA, Uint8 indexF);
// Obtiene el indice de la animación a partir del nombre
int getIndex(std::string name);
// Carga la animación desde un fichero
bool load(std::string filePath);
bool loadFromFile(std::string filePath);
// Carga la animación desde un vector
bool loadFromVector(std::vector<std::string> *source);
// Establece la animacion actual
void setCurrentAnimation(std::string name = "default");
@@ -79,6 +84,9 @@ public:
// OLD - Establece el contador para todas las animaciones
void setAnimationCounter(int value);
// Reinicia la animación
void resetAnimation();
};
#endif

File diff suppressed because it is too large Load Diff

View File

@@ -4,6 +4,7 @@
#include "utils.h"
#include "animatedsprite.h"
#include <vector>
#include <sstream>
#ifndef BALLOON_H
#define BALLOON_H
@@ -85,37 +86,39 @@ private:
std::vector<float> h; // Vector con los valores de zoom para el alto del globo
};
float mPosX; // Posición en el eje X
float mPosY; // Posición en el eje Y
Uint8 mWidth; // Ancho
Uint8 mHeight; // Alto
float mVelX; // Velocidad en el eje X. Cantidad de pixeles a desplazarse
float mVelY; // Velocidad en el eje Y. Cantidad de pixeles a desplazarse
float mGravity; // Aceleración en el eje Y. Modifica la velocidad
float mDefaultVelY; // Velocidad inicial que tienen al rebotar contra el suelo
float mMaxVelY; // Máxima velocidad que puede alcanzar el objeto en el eje Y
AnimatedSprite *mSprite; // Sprite del objeto globo
bool mBeingCreated; // Indica si el globo se está creando
bool mBlinking; // Indica si el globo está intermitente
bool mEnabled; // Indica si el globo esta activo
bool mInvulnerable; // Indica si el globo es invulnerable
bool mPopping; // Indica si el globo está explotando
bool mStopped; // Indica si el globo está parado
bool mVisible; // Indica si el globo es visible
circle_t mCollider; // Circulo de colisión del objeto
Uint16 mCreationCounter; // Temporizador para controlar el estado "creandose"
Uint16 mCreationCounterIni; // Valor inicial para el temporizador para controlar el estado "creandose"
Uint16 mScore; // Puntos que da el globo al ser destruido
Uint16 mStoppedCounter; // Contador para controlar el estado "parado"
Uint16 mTimeToLive; // Indica el tiempo de vida que le queda al globo
Uint8 mKind; // Tipo de globo
Uint8 mMenace; // Cantidad de amenaza que genera el globo
Uint32 mCounter; // Contador interno
float mTravelY; // Distancia que ha de recorrer el globo en el eje Y antes de que se le aplique la gravedad
float mSpeed; // Velocidad a la que se mueven los globos
Uint8 mSize; // Tamaño del globo
Uint8 mPower; // Cantidad de poder que alberga el globo
bouncing mBouncing; // Contiene las variables para el efecto de rebote
// Objetos
AnimatedSprite *sprite; // Sprite del objeto globo
// Variables
float posX; // Posición en el eje X
float posY; // Posición en el eje Y
Uint8 width; // Ancho
Uint8 height; // Alto
float velX; // Velocidad en el eje X. Cantidad de pixeles a desplazarse
float velY; // Velocidad en el eje Y. Cantidad de pixeles a desplazarse
float gravity; // Aceleración en el eje Y. Modifica la velocidad
float defaultVelY; // Velocidad inicial que tienen al rebotar contra el suelo
float maxVelY; // Máxima velocidad que puede alcanzar el objeto en el eje Y
bool beingCreated; // Indica si el globo se está creando
bool blinking; // Indica si el globo está intermitente
bool enabled; // Indica si el globo esta activo
bool invulnerable; // Indica si el globo es invulnerable
bool popping; // Indica si el globo está explotando
bool stopped; // Indica si el globo está parado
bool visible; // Indica si el globo es visible
circle_t collider; // Circulo de colisión del objeto
Uint16 creationCounter; // Temporizador para controlar el estado "creandose"
Uint16 creationCounterIni; // Valor inicial para el temporizador para controlar el estado "creandose"
Uint16 score; // Puntos que da el globo al ser destruido
Uint16 stoppedCounter; // Contador para controlar el estado "parado"
Uint8 kind; // Tipo de globo
Uint8 menace; // Cantidad de amenaza que genera el globo
Uint32 counter; // Contador interno
float travelY; // Distancia que ha de recorrer el globo en el eje Y antes de que se le aplique la gravedad
float speed; // Velocidad a la que se mueven los globos
Uint8 size; // Tamaño del globo
Uint8 power; // Cantidad de poder que alberga el globo
bouncing bouncing; // Contiene las variables para el efecto de rebote
// Alinea el circulo de colisión con la posición del objeto globo
void updateColliders();
@@ -136,17 +139,11 @@ private:
void updateAnimation();
// Establece el valor de la variable
void setBeingCreated(bool state);
// Establece el valor de la variable
void setTimeToLive(Uint16 time);
// Obtiene del valor de la variable
Uint16 getTimeToLive();
void setBeingCreated(bool value);
public:
// Constructor
Balloon(float x, float y, Uint8 kind, float velx, float speed, Uint16 creationtimer, LTexture *texture, SDL_Renderer *renderer);
Balloon(float x, float y, Uint8 kind, float velx, float speed, Uint16 creationtimer, LTexture *texture, std::vector<std::string> *animation, SDL_Renderer *renderer);
// Destructor
~Balloon();
@@ -203,25 +200,25 @@ public:
Uint8 getClass();
// Establece el valor de la variable
void setStop(bool state);
void setStop(bool value);
// Obtiene del valor de la variable
bool isStopped();
// Establece el valor de la variable
void setBlink(bool state);
void setBlink(bool value);
// Obtiene del valor de la variable
bool isBlinking();
// Establece el valor de la variable
void setVisible(bool state);
void setVisible(bool value);
// Obtiene del valor de la variable
bool isVisible();
// Establece el valor de la variable
void setInvulnerable(bool state);
void setInvulnerable(bool value);
// Obtiene del valor de la variable
bool isInvulnerable();
@@ -230,7 +227,7 @@ public:
bool isBeingCreated();
// Establece el valor de la variable
void setPopping(bool state);
void setPopping(bool value);
// Obtiene del valor de la variable
bool isPopping();

View File

@@ -2,87 +2,73 @@
#include "bullet.h"
// Constructor
Bullet::Bullet()
Bullet::Bullet(int x, int y, int kind, bool poweredUp, int owner, LTexture *texture, SDL_Renderer *renderer)
{
mSprite = new Sprite();
mKind = NO_KIND;
}
sprite = new Sprite({x, y, 10, 10}, texture, renderer);
// Destructor
Bullet::~Bullet()
{
delete mSprite;
mSprite = nullptr;
}
// Iniciador
void Bullet::init(int x, int y, int kind, bool poweredUp, int owner, LTexture *texture, SDL_Renderer *renderer)
{
// Posición inicial del objeto
mPosX = x;
mPosY = y;
posX = x;
posY = y;
// Alto y ancho del objeto
mWidth = 10;
mHeight = mWidth;
width = 10;
height = 10;
// Velocidad inicial en el eje Y
mVelY = -3;
velY = -3;
// Tipo de bala
mKind = kind;
this->kind = kind;
// Identificador del dueño del objeto
mOwner = owner;
// Textura con los gráficos del objeto
mSprite->setTexture(texture);
// Renderizador
mSprite->setRenderer(renderer);
// Alto y ancho del sprite
mSprite->setWidth(mWidth);
mSprite->setHeight(mHeight);
// Posición inicial del sprite
mSprite->setPosX(mPosX);
mSprite->setPosY(mPosY);
this->owner = owner;
// Valores especificos según el tipo
switch (kind)
{
case BULLET_UP:
// Establece la velocidad inicial
mVelX = 0;
velX = 0;
// Rectangulo con los gráficos del objeto
if (!poweredUp)
mSprite->setSpriteClip(0 * mWidth, 0, mSprite->getWidth(), mSprite->getHeight());
{
sprite->setSpriteClip(0 * width, 0, sprite->getWidth(), sprite->getHeight());
}
else
mSprite->setSpriteClip((0 + 3) * mWidth, 0, mSprite->getWidth(), mSprite->getHeight());
{
sprite->setSpriteClip((0 + 3) * width, 0, sprite->getWidth(), sprite->getHeight());
}
break;
case BULLET_LEFT:
// Establece la velocidad inicial
mVelX = -2;
velX = -2;
// Rectangulo con los gráficos del objeto
if (!poweredUp)
mSprite->setSpriteClip(1 * mWidth, 0, mSprite->getWidth(), mSprite->getHeight());
{
sprite->setSpriteClip(1 * width, 0, sprite->getWidth(), sprite->getHeight());
}
else
mSprite->setSpriteClip((1 + 3) * mWidth, 0, mSprite->getWidth(), mSprite->getHeight());
{
sprite->setSpriteClip((1 + 3) * width, 0, sprite->getWidth(), sprite->getHeight());
}
break;
case BULLET_RIGHT:
// Establece la velocidad inicial
mVelX = 2;
velX = 2;
// Rectangulo con los gráficos del objeto
if (!poweredUp)
mSprite->setSpriteClip(2 * mWidth, 0, mSprite->getWidth(), mSprite->getHeight());
{
sprite->setSpriteClip(2 * width, 0, sprite->getWidth(), sprite->getHeight());
}
else
mSprite->setSpriteClip((2 + 3) * mWidth, 0, mSprite->getWidth(), mSprite->getHeight());
{
sprite->setSpriteClip((2 + 3) * width, 0, sprite->getWidth(), sprite->getHeight());
}
break;
default:
@@ -90,16 +76,22 @@ void Bullet::init(int x, int y, int kind, bool poweredUp, int owner, LTexture *t
}
// Establece el tamaño del circulo de colisión
mCollider.r = mWidth / 2;
collider.r = width / 2;
// Alinea el circulo de colisión con el objeto
shiftColliders();
}
// Destructor
Bullet::~Bullet()
{
delete sprite;
}
// Pinta el objeto en pantalla
void Bullet::render()
{
mSprite->render();
sprite->render();
}
// Actualiza la posición y estado del objeto en horizontal
@@ -109,34 +101,34 @@ Uint8 Bullet::move()
Uint8 msg = BULLET_MOVE_OK;
// Mueve el objeto a su nueva posición
mPosX += mVelX;
posX += velX;
// Si el objeto se sale del area de juego por los laterales
if ((mPosX < PLAY_AREA_LEFT) || (mPosX + mWidth > PLAY_AREA_RIGHT))
if ((posX < PLAY_AREA_LEFT - width) || (posX > PLAY_AREA_RIGHT))
{
// Se deshabilita
mKind = NO_KIND;
kind = NO_KIND;
// Mensaje de salida
msg = BULLET_MOVE_OUT;
}
// Mueve el objeto a su nueva posición en vertical
mPosY += int(mVelY);
posY += int(velY);
// Si el objeto se sale del area de juego por la parte superior o inferior
if ((mPosY < PLAY_AREA_TOP) || (mPosY + mHeight > PLAY_AREA_BOTTOM))
// Si el objeto se sale del area de juego por la parte superior
if (posY < PLAY_AREA_TOP - height)
{
// Se deshabilita
mKind = NO_KIND;
kind = NO_KIND;
// Mensaje de salida
msg = BULLET_MOVE_OUT;
}
// Actualiza la posición del sprite
mSprite->setPosX(mPosX);
mSprite->setPosY(mPosY);
sprite->setPosX(posX);
sprite->setPosY(posY);
// Alinea el circulo de colisión con el objeto
shiftColliders();
@@ -144,72 +136,76 @@ Uint8 Bullet::move()
return msg;
}
// Deshabilita el objeto
void Bullet::erase()
// Comprueba si el objeto está habilitado
bool Bullet::isEnabled()
{
init(0, 0, 0, false, -1, nullptr, nullptr);
if (kind == NO_KIND)
{
return false;
}
else
{
return true;
}
}
// Comprueba si el objeto está activo
bool Bullet::isActive()
// Deshabilita el objeto
void Bullet::disable()
{
if (mKind == NO_KIND)
return false;
else
return true;
kind = NO_KIND;
}
// Obtiene el valor de la variable
int Bullet::getPosX()
{
return mPosX;
return posX;
}
// Obtiene el valor de la variable
int Bullet::getPosY()
{
return mPosY;
return posY;
}
// Establece el valor de la variable
void Bullet::setPosX(int x)
{
mPosX = x;
posX = x;
}
// Establece el valor de la variable
void Bullet::setPosY(int y)
{
mPosY = y;
posY = y;
}
// Obtiene el valor de la variable
int Bullet::getVelY()
{
return mVelY;
return velY;
}
// Obtiene el valor de la variable
int Bullet::getKind()
{
return mKind;
return kind;
}
// Obtiene el valor de la variable
int Bullet::getOwner()
{
return mOwner;
return owner;
}
// Obtiene el circulo de colisión
circle_t &Bullet::getCollider()
{
return mCollider;
return collider;
}
// Alinea el circulo de colisión con el objeto
void Bullet::shiftColliders()
{
mCollider.x = mPosX + mCollider.r;
mCollider.y = mPosY + mCollider.r;
collider.x = posX + collider.r;
collider.y = posY + collider.r;
}

View File

@@ -20,41 +20,41 @@
class Bullet
{
private:
int mPosX; // Posición en el eje X
int mPosY; // Posición en el eje Y
Uint8 mWidth; // Ancho del objeto
Uint8 mHeight; // Alto del objeto
int mVelX; // Velocidad en el eje X
int mVelY; // Velocidad en el eje Y
int mKind; // Tipo de objeto
int mOwner; // Identificador del dueño del objeto
Sprite *mSprite; // Sprite con los graficos y métodos de pintado
circle_t mCollider; // Circulo de colisión del objeto
// Objetos
Sprite *sprite; // Sprite con los graficos y métodos de pintado
// Variables
int posX; // Posición en el eje X
int posY; // Posición en el eje Y
Uint8 width; // Ancho del objeto
Uint8 height; // Alto del objeto
int velX; // Velocidad en el eje X
int velY; // Velocidad en el eje Y
int kind; // Tipo de objeto
int owner; // Identificador del dueño del objeto
circle_t collider; // Circulo de colisión del objeto
// Alinea el circulo de colisión con el objeto
void shiftColliders();
public:
// Constructor
Bullet();
Bullet(int x, int y, int kind, bool poweredUp, int owner, LTexture *texture, SDL_Renderer *renderer);
// Destructor
~Bullet();
// Iniciador
void init(int x, int y, int kind, bool poweredUp, int owner, LTexture *texture, SDL_Renderer *renderer);
// Pinta el objeto en pantalla
void render();
// Actualiza la posición y estado del objeto
Uint8 move();
// Deshabilita el objeto
void erase();
// Comprueba si el objeto está habilitado
bool isEnabled();
// Comprueba si el objeto está activo
bool isActive();
// Deshabilita el objeto
void disable();
// Obtiene el valor de la variable
int getPosX();

View File

@@ -1,89 +0,0 @@
#include "const.h"
#include "coffeedrop.h"
#ifndef UNUSED
// Constructor
CoffeeDrop::CoffeeDrop()
{
mPosX = 0;
mPosY = 0;
mWidth = 8;
mHeight = 8;
mVelX = 0;
mVelY = 0;
mGravity = 0.1f;
mFloor = 0;
mEnabled = false;
mSprite = new Sprite();
mAlpha = 128;
}
// Destructor
CoffeeDrop::~CoffeeDrop()
{
delete mSprite;
}
// Inicializador
void CoffeeDrop::init(LTexture *texture, SDL_Renderer *renderer, float x, float y, float velX, float velY, int floor)
{
mEnabled = true;
mPosX = x;
mPosY = y;
mVelX = velX;
mVelY = velY;
mFloor = floor;
mSprite->setRenderer(renderer);
mSprite->setTexture(texture);
mSprite->setSpriteClip(256, 97, mWidth, mHeight);
mSprite->setPosX(x);
mSprite->setPosY(y);
}
// Actualiza las variables del objeto
void CoffeeDrop::update()
{
if (mEnabled)
{
mVelY += mGravity;
mPosX += mVelX;
mPosY += mVelY;
mSprite->setPosX((int)mPosX);
mSprite->setPosY((int)mPosY);
if ((mPosY > mFloor) || (mPosX > PLAY_AREA_RIGHT) || ((mPosX - mWidth) < PLAY_AREA_LEFT))
mEnabled = false;
mAlpha -= 2;
if (mAlpha == 0)
mEnabled = false;
}
}
// Pinta el objeto
void CoffeeDrop::render()
{
if (mEnabled)
{
mSprite->getTexture()->setAlpha(mAlpha);
mSprite->render();
mSprite->getTexture()->setAlpha(255);
}
}
// Deshabilita el objeto
void CoffeeDrop::disable()
{
mEnabled = false;
}
// Comprueba si està habilitado
bool CoffeeDrop::isEnabled()
{
return mEnabled;
}
#endif

View File

@@ -1,52 +0,0 @@
#pragma once
#include <SDL2/SDL.h>
#include "sprite.h"
#ifndef COFFEEDROP_H
#define COFFEEDROP_H
#ifndef UNUSED
// Clase CoffeeDrop. Gotas de café que aparecen al explotar un globo
class CoffeeDrop
{
private:
float mPosX; // Posicion en el eje X del objeto
float mPosY; // Posicion en el eje Y del objeto
Uint8 mWidth; // Ancho del sprite
Uint8 mHeight; // Alto del sprite
float mVelX; // Velocidad en el eje X
float mVelY; // Velocidad en el eje Y
float mGravity; // Aceleración en el eje Y
int mFloor; // Punto donde se encuentra el suelo y desaparecen
bool mEnabled; // Si esta habilitado. Sirve para saber si se pinta, se actualiza o se puede usar
Sprite *mSprite; // Puntero al sprite con los graficos
Uint8 mAlpha;
public:
// Constructor
CoffeeDrop();
// Destructor
~CoffeeDrop();
// Inicializador
void init(LTexture *texture, SDL_Renderer *renderer, float x, float y, float velX, float velY, int floor);
// Actualiza las variables del objeto
void update();
// Pinta el objeto
void render();
// Deshabilita el objeto
void disable();
// Comprueba si està habilitado
bool isEnabled();
};
#endif
#endif

View File

@@ -54,11 +54,6 @@ const int SCREEN_THIRD_QUARTER_Y = (GAME_HEIGHT / 4) * 3;
#define TITLE_SECTION_3 5
#define TITLE_SECTION_INSTRUCTIONS 6
// Estados de cada elemento que pertenece a un evento
#define EVENT_WAITING 1
#define EVENT_RUNNING 2
#define EVENT_COMPLETED 3
// Ningun tipo
#define NO_KIND 0

View File

@@ -1,47 +1,42 @@
#include "const.h"
#include "utils.h"
#include "director.h"
#include "utils.h"
#include <iostream>
#include <string>
// Constructor
Director::Director(std::string path)
{
// Inicializa variables
section.name = PROG_SECTION_LOGO;
// Crea el objeto que controla los ficheros de recursos
asset = new Asset(path.substr(0, path.find_last_of("\\/")) + "../");
// Establece la lista de ficheros
Uint8 section = PROG_SECTION_LOGO;
if (!setFileList())
{// Si falta algún fichero no inicies el programa
section = PROG_SECTION_QUIT;
}
asset = new Asset(path.substr(0, path.find_last_of("\\/")) + "/../");
// Crea el objeto de idioma
lang = new Lang(asset);
// Establece la lista de ficheros
if (!setFileList())
{ // Si falta algún fichero no inicia el programa
section.name = PROG_SECTION_QUIT;
}
// Crea el puntero a la estructura y carga el fichero de configuración
options = new options_t;
loadConfigFile();
// Crea los objetos
input = new Input(asset->get("controllerdb.txt"));
// Inicializa SDL
initSDL();
// Crea el objeto para dibujar en pantalla (Requiere initSDL)
screen = new Screen(window, renderer, options, GAME_WIDTH, GAME_HEIGHT);
// Inicializa JailAudio
initJailAudio();
// Aplica las opciones
// Crea los objetos
lang = new Lang(asset);
lang->setLang(options->language);
// Inicializa el resto de variables
init(section);
input = new Input(asset->get("controllerdb.txt"));
initInput();
screen = new Screen(window, renderer, options, GAME_WIDTH, GAME_HEIGHT);
}
Director::~Director()
@@ -49,39 +44,21 @@ Director::~Director()
saveConfigFile();
delete asset;
asset = nullptr;
delete input;
input = nullptr;
delete screen;
screen = nullptr;
delete lang;
lang = nullptr;
delete options;
options = nullptr;
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
renderer = nullptr;
window = nullptr;
SDL_Quit();
}
// Inicia las variables necesarias para arrancar el programa
void Director::init(Uint8 name)
// Inicializa el objeto input
void Director::initInput()
{
// Sección
section.name = name;
section.subsection = 0;
// Textos
lang->setLang(options->language);
// Controles
// Teclado
input->bindKey(INPUT_UP, SDL_SCANCODE_UP);
input->bindKey(INPUT_DOWN, SDL_SCANCODE_DOWN);
input->bindKey(INPUT_LEFT, SDL_SCANCODE_LEFT);
@@ -94,6 +71,7 @@ void Director::init(Uint8 name)
input->bindKey(INPUT_BUTTON_PAUSE, SDL_SCANCODE_ESCAPE); // PAUSE
input->bindKey(INPUT_BUTTON_ESCAPE, SDL_SCANCODE_ESCAPE); // ESCAPE
// Mando
input->bindGameControllerButton(INPUT_UP, SDL_CONTROLLER_BUTTON_DPAD_UP);
input->bindGameControllerButton(INPUT_DOWN, SDL_CONTROLLER_BUTTON_DPAD_DOWN);
input->bindGameControllerButton(INPUT_LEFT, SDL_CONTROLLER_BUTTON_DPAD_LEFT);
@@ -103,7 +81,7 @@ void Director::init(Uint8 name)
input->bindGameControllerButton(INPUT_BUTTON_1, SDL_CONTROLLER_BUTTON_X);
input->bindGameControllerButton(INPUT_BUTTON_2, SDL_CONTROLLER_BUTTON_Y);
input->bindGameControllerButton(INPUT_BUTTON_3, SDL_CONTROLLER_BUTTON_B);
input->bindGameControllerButton(INPUT_BUTTON_PAUSE, SDL_CONTROLLER_BUTTON_GUIDE); // PAUSE
input->bindGameControllerButton(INPUT_BUTTON_PAUSE, SDL_CONTROLLER_BUTTON_GUIDE); // PAUSE
input->bindGameControllerButton(INPUT_BUTTON_ESCAPE, SDL_CONTROLLER_BUTTON_GUIDE); // ESCAPE
}
@@ -120,7 +98,8 @@ bool Director::initSDL()
bool success = true;
// Inicializa SDL
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_GAMECONTROLLER | SDL_INIT_AUDIO) < 0)
if (SDL_Init(SDL_INIT_EVERYTHING) < 0)
// if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_GAMECONTROLLER | SDL_INIT_AUDIO) < 0)
{
printf("SDL could not initialize!\nSDL Error: %s\n", SDL_GetError());
success = false;
@@ -147,9 +126,13 @@ bool Director::initSDL()
{
// Crea un renderizador para la ventana. El vsync se activa en funcion de las opciones
if (options->vSync)
{
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
}
else
{
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
}
if (renderer == nullptr)
{
@@ -199,7 +182,6 @@ bool Director::setFileList()
asset->add("data/sound/hiscore.wav", t_sound);
asset->add("data/sound/itemdrop.wav", t_sound);
asset->add("data/sound/itempickup.wav", t_sound);
asset->add("data/sound/menu_cancel.wav", t_sound);
asset->add("data/sound/menu_move.wav", t_sound);
asset->add("data/sound/menu_select.wav", t_sound);
asset->add("data/sound/player_collision.wav", t_sound);
@@ -209,22 +191,65 @@ bool Director::setFileList()
asset->add("data/sound/powerball.wav", t_sound);
// Texturas
asset->add("data/gfx/balloon.png", t_bitmap);
asset->add("data/gfx/balloon1.png", t_bitmap);
asset->add("data/gfx/balloon1.ani", t_data);
asset->add("data/gfx/balloon2.png", t_bitmap);
asset->add("data/gfx/balloon2.ani", t_data);
asset->add("data/gfx/balloon3.png", t_bitmap);
asset->add("data/gfx/balloon3.ani", t_data);
asset->add("data/gfx/balloon4.png", t_bitmap);
asset->add("data/gfx/balloon4.ani", t_data);
asset->add("data/gfx/bullet.png", t_bitmap);
asset->add("data/gfx/game_bg.png", t_bitmap);
asset->add("data/gfx/game_buildings.png", t_bitmap);
asset->add("data/gfx/game_clouds.png", t_bitmap);
asset->add("data/gfx/game_grass.png", t_bitmap);
asset->add("data/gfx/game_power_meter.png", t_bitmap);
asset->add("data/gfx/game_sky_colors.png", t_bitmap);
asset->add("data/gfx/game_text.png", t_bitmap);
asset->add("data/gfx/intro.png", t_bitmap);
asset->add("data/gfx/items.png", t_bitmap);
asset->add("data/gfx/logo.png", t_bitmap);
asset->add("data/gfx/player1_body.png", t_bitmap);
asset->add("data/gfx/player1_death.png", t_bitmap);
asset->add("data/gfx/player1_legs.png", t_bitmap);
asset->add("data/gfx/title.png", t_bitmap);
asset->add("data/gfx/player1_head.png", t_bitmap);
asset->add("data/gfx/player2_body.png", t_bitmap);
asset->add("data/gfx/player2_death.png", t_bitmap);
asset->add("data/gfx/player2_legs.png", t_bitmap);
asset->add("data/gfx/player2_head.png", t_bitmap);
asset->add("data/gfx/menu_game_over.png", t_bitmap);
asset->add("data/gfx/menu_game_over_end.png", t_bitmap);
asset->add("data/gfx/item_points1_disk.png", t_bitmap);
asset->add("data/gfx/item_points1_disk.ani", t_data);
asset->add("data/gfx/item_points2_gavina.png", t_bitmap);
asset->add("data/gfx/item_points2_gavina.ani", t_data);
asset->add("data/gfx/item_points3_pacmar.png", t_bitmap);
asset->add("data/gfx/item_points3_pacmar.ani", t_data);
asset->add("data/gfx/item_clock.png", t_bitmap);
asset->add("data/gfx/item_clock.ani", t_data);
asset->add("data/gfx/item_coffee.png", t_bitmap);
asset->add("data/gfx/item_coffee.ani", t_data);
asset->add("data/gfx/item_coffee_machine.png", t_bitmap);
asset->add("data/gfx/item_coffee_machine.ani", t_data);
asset->add("data/gfx/title_bg_tile.png", t_bitmap);
asset->add("data/gfx/title_coffee.png", t_bitmap);
asset->add("data/gfx/title_crisis.png", t_bitmap);
asset->add("data/gfx/title_dust.png", t_bitmap);
asset->add("data/gfx/title_dust.ani", t_data);
asset->add("data/gfx/title_gradient.png", t_bitmap);
asset->add("data/gfx/player_head.ani", t_data);
asset->add("data/gfx/player_body.ani", t_data);
asset->add("data/gfx/player_legs.ani", t_data);
asset->add("data/gfx/player_death.ani", t_data);
asset->add("data/gfx/player_fire.ani", t_data);
asset->add("data/gfx/player_bal1_head.png", t_bitmap);
asset->add("data/gfx/player_bal1_body.png", t_bitmap);
asset->add("data/gfx/player_bal1_legs.png", t_bitmap);
asset->add("data/gfx/player_bal1_death.png", t_bitmap);
asset->add("data/gfx/player_bal1_fire.png", t_bitmap);
asset->add("data/gfx/player_arounder_head.png", t_bitmap);
asset->add("data/gfx/player_arounder_body.png", t_bitmap);
asset->add("data/gfx/player_arounder_legs.png", t_bitmap);
asset->add("data/gfx/player_arounder_death.png", t_bitmap);
asset->add("data/gfx/player_arounder_fire.png", t_bitmap);
// Fuentes
asset->add("data/font/8bithud.png", t_font);
@@ -245,6 +270,13 @@ bool Director::setFileList()
asset->add("data/lang/en_UK.txt", t_lang);
asset->add("data/lang/ba_BA.txt", t_lang);
// Menus
asset->add("data/menu/title.men", t_data);
asset->add("data/menu/options.men", t_data);
asset->add("data/menu/pause.men", t_data);
asset->add("data/menu/gameover.men", t_data);
asset->add("data/menu/player_select.men", t_data);
return asset->check();
}
@@ -252,12 +284,24 @@ bool Director::setFileList()
bool Director::loadConfigFile()
{
// Pone unos valores por defecto
options->input.clear();
input_t inp;
inp.id = 0;
inp.name = "KEYBOARD";
inp.deviceType = INPUT_USE_KEYBOARD;
options->input.push_back(inp);
inp.id = 0;
inp.name = "GAME CONTROLLER";
inp.deviceType = INPUT_USE_GAMECONTROLLER;
options->input.push_back(inp);
options->fullScreenMode = 0;
options->windowSize = 3;
options->language = ba_BA;
options->difficulty = DIFFICULTY_NORMAL;
options->input[0].deviceType = INPUT_USE_KEYBOARD;
options->input[1].deviceType = INPUT_USE_GAMECONTROLLER;
options->playerSelected = 0;
options->filter = FILTER_NEAREST;
options->vSync = true;
options->screenWidth = GAME_WIDTH;
@@ -282,7 +326,7 @@ bool Director::loadConfigFile()
// Crea el fichero para escritura
file = SDL_RWFromFile(p.c_str(), "w+b");
if (file != nullptr)
{
{ // Ha podido crear el fichero
printf("New file (%s) created!\n", filename.c_str());
// Escribe los datos
@@ -290,8 +334,8 @@ bool Director::loadConfigFile()
SDL_RWwrite(file, &options->windowSize, sizeof(options->windowSize), 1);
SDL_RWwrite(file, &options->language, sizeof(options->language), 1);
SDL_RWwrite(file, &options->difficulty, sizeof(options->difficulty), 1);
SDL_RWwrite(file, &options->input[0].deviceType, sizeof(options->input[0].deviceType), 1);
SDL_RWwrite(file, &options->input[1].deviceType, sizeof(options->input[1].deviceType), 1);
SDL_RWwrite(file, &options->input.at(0).deviceType, sizeof(options->input.at(0).deviceType), 1);
SDL_RWwrite(file, &options->input.at(1).deviceType, sizeof(options->input.at(1).deviceType), 1);
SDL_RWwrite(file, &options->filter, sizeof(options->filter), 1);
SDL_RWwrite(file, &options->vSync, sizeof(options->vSync), 1);
SDL_RWwrite(file, &options->screenWidth, sizeof(options->screenWidth), 1);
@@ -303,7 +347,7 @@ bool Director::loadConfigFile()
SDL_RWclose(file);
}
else
{
{ // No ha podido crear el fichero
printf("Error: Unable to create file %s\n", filename.c_str());
success = false;
}
@@ -317,8 +361,8 @@ bool Director::loadConfigFile()
SDL_RWread(file, &options->windowSize, sizeof(options->windowSize), 1);
SDL_RWread(file, &options->language, sizeof(options->language), 1);
SDL_RWread(file, &options->difficulty, sizeof(options->difficulty), 1);
SDL_RWread(file, &options->input[0].deviceType, sizeof(options->input[0].deviceType), 1);
SDL_RWread(file, &options->input[1].deviceType, sizeof(options->input[1].deviceType), 1);
SDL_RWread(file, &options->input.at(0).deviceType, sizeof(options->input.at(0).deviceType), 1);
SDL_RWread(file, &options->input.at(1).deviceType, sizeof(options->input.at(1).deviceType), 1);
SDL_RWread(file, &options->filter, sizeof(options->filter), 1);
SDL_RWread(file, &options->vSync, sizeof(options->vSync), 1);
SDL_RWread(file, &options->screenWidth, sizeof(options->screenWidth), 1);
@@ -327,14 +371,23 @@ bool Director::loadConfigFile()
SDL_RWread(file, &options->keepAspect, sizeof(options->keepAspect), 1);
// Normaliza los valores
if (!((options->fullScreenMode == 0) ||
(options->fullScreenMode == SDL_WINDOW_FULLSCREEN) ||
(options->fullScreenMode == SDL_WINDOW_FULLSCREEN_DESKTOP)))
const bool a = options->fullScreenMode == 0;
const bool b = options->fullScreenMode == SDL_WINDOW_FULLSCREEN;
const bool c = options->fullScreenMode == SDL_WINDOW_FULLSCREEN_DESKTOP;
if (!(a || b || c))
{
options->fullScreenMode = 0;
if ((options->windowSize < 1) || (options->windowSize > 4))
}
if (options->windowSize < 1 || options->windowSize > 4)
{
options->windowSize = 3;
if ((options->language < 0) || (options->language > MAX_LANGUAGES))
}
if (options->language < 0 || options->language > MAX_LANGUAGES)
{
options->language = en_UK;
}
// Cierra el fichero
SDL_RWclose(file);
@@ -357,8 +410,8 @@ bool Director::saveConfigFile()
SDL_RWwrite(file, &options->windowSize, sizeof(options->windowSize), 1);
SDL_RWwrite(file, &options->language, sizeof(options->language), 1);
SDL_RWwrite(file, &options->difficulty, sizeof(options->difficulty), 1);
SDL_RWwrite(file, &options->input[0].deviceType, sizeof(options->input[0].deviceType), 1);
SDL_RWwrite(file, &options->input[1].deviceType, sizeof(options->input[1].deviceType), 1);
SDL_RWwrite(file, &options->input.at(0).deviceType, sizeof(options->input.at(0).deviceType), 1);
SDL_RWwrite(file, &options->input.at(1).deviceType, sizeof(options->input.at(1).deviceType), 1);
SDL_RWwrite(file, &options->filter, sizeof(options->filter), 1);
SDL_RWwrite(file, &options->vSync, sizeof(options->vSync), 1);
SDL_RWwrite(file, &options->screenWidth, sizeof(options->screenWidth), 1);
@@ -374,26 +427,16 @@ bool Director::saveConfigFile()
else
{
printf("Error: Unable to save %s file! %s\n", filename.c_str(), SDL_GetError());
success = false;
}
return success;
}
// Obtiene el valor de la variable
Uint8 Director::getSubsection()
{
return section.subsection;
}
// Obtiene el valor de la variable
Uint8 Director::getSection()
{
return section.name;
}
// Establece el valor de la variable
void Director::setSection(section_t section)
{
section = section;
this->section = section;
}
void Director::runLogo()
@@ -412,23 +455,15 @@ void Director::runIntro()
void Director::runTitle()
{
title = new Title(window, renderer, screen, input, asset, options, lang);
setSection(title->run(section.subsection));
title = new Title(renderer, screen, input, asset, options, lang, section);
setSection(title->run());
delete title;
}
void Director::runGame()
{
if (section.subsection == GAME_SECTION_PLAY_1P)
{
game = new Game(1, 0, renderer, screen, asset, lang, input, false, options);
}
else if (section.subsection == GAME_SECTION_PLAY_2P)
{
game = new Game(2, 0, renderer, screen, asset, lang, input, false, options);
}
const int numPlayers = section.subsection == GAME_SECTION_PLAY_1P ? 1 : 2;
game = new Game(numPlayers, 0, renderer, screen, asset, lang, input, false, options);
setSection(game->run());
delete game;
}
@@ -436,9 +471,9 @@ void Director::runGame()
void Director::run()
{
// Bucle principal
while (!(getSection() == PROG_SECTION_QUIT))
while (section.name != PROG_SECTION_QUIT)
{
switch (getSection())
switch (section.name)
{
case PROG_SECTION_LOGO:
runLogo();

View File

@@ -4,7 +4,6 @@
#include "asset.h"
#include "balloon.h"
#include "bullet.h"
#include "coffeedrop.h"
#include "const.h"
#include "fade.h"
#include "game.h"
@@ -34,6 +33,7 @@
class Director
{
private:
// Objetos
SDL_Window *window; // La ventana donde dibujamos
SDL_Renderer *renderer; // El renderizador de la ventana
Screen *screen; // Objeto encargado de dibujar en pantalla
@@ -44,6 +44,8 @@ private:
Input *input; // Objeto Input para gestionar las entradas
Lang *lang; // Objeto para gestionar los textos en diferentes idiomas
Asset *asset; // Objeto que gestiona todos los ficheros de recursos
// Variables
struct options_t *options; // Variable con todas las opciones del programa
section_t section; // Sección y subsección actual del programa;
@@ -53,6 +55,9 @@ private:
// Arranca SDL y crea la ventana
bool initSDL();
// Inicializa el objeto input
void initInput();
// Crea el indice de ficheros
bool setFileList();
@@ -62,12 +67,6 @@ private:
// Guarda el fichero de configuración
bool saveConfigFile();
// Obtiene el valor de la variable
Uint8 getSubsection();
// Obtiene el valor de la variable
Uint8 getSection();
// Establece el valor de la variable
void setSection(section_t section);
@@ -90,9 +89,6 @@ public:
// Destructor
~Director();
// Inicia las variables necesarias para arrancar el programa
void init(Uint8 name);
// Bucle principal
void run();
};

File diff suppressed because it is too large Load Diff

View File

@@ -18,6 +18,7 @@
#include "text.h"
#include "utils.h"
#include "writer.h"
#include <iostream>
#ifndef GAME_H
#define GAME_H
@@ -30,17 +31,13 @@
#define STAGE_COUNTER 200
#define SHAKE_COUNTER 10
#define HELP_COUNTER 1000
#define GAME_COMPLETED_START_FADE 500
#define GAME_COMPLETED_END 700
// Formaciones enemigas
#define NUMBER_OF_ENEMY_FORMATIONS 100
#define MAX_NUMBER_OF_ENEMIES_IN_A_FORMATION 50
// Cantidad de elementos del vector de SmartSprites
#define MAX_SMART_SPRITES 10
// Cantidad máxima posible de balas
#define MAX_BULLETS 50
// Porcentaje de aparición de los objetos
#define ITEM_POINTS_1_DISK_ODDS 10
#define ITEM_POINTS_2_GAVINA_ODDS 6
@@ -50,9 +47,6 @@
#define ITEM_POWER_BALL_ODDS 0
#define ITEM_COFFEE_MACHINE_ODDS 4
// Cantidad de objetos simultaneos
#define MAX_ITEMS 10
// Valores para las variables asociadas a los objetos
#define TIME_STOPPED_COUNTER 300
@@ -120,144 +114,144 @@ private:
demoKeys_t dataFile[TOTAL_DEMO_DATA]; // Datos del fichero con los movimientos para la demo
};
struct debug_t
{
bool enabled; // Indica si se va a mostrar la información de debug
Uint8 enemySet; // Escoge el set enemigo a generar
Uint8 gradR, gradG, gradB; // Colores RGB para modificar el color del gradiente de fondo
float hudW, hudH; // Multiplica el tamaño del hud de debug;
};
// Objetos
SDL_Renderer *renderer; // El renderizador de la ventana
Screen *screen; // Objeto encargado de dibujar en pantalla
Asset *asset; // Objeto que gestiona todos los ficheros de recursos
Lang *lang; // Objeto para gestionar los textos en diferentes idiomas
Input *input; // Manejador de entrada
SDL_Renderer *mRenderer; // El renderizador de la ventana
Screen *mScreen; // Objeto encargado de dibujar en pantalla
Asset *mAsset; // Objeto que gestiona todos los ficheros de recursos
Lang *mLang; // Objeto para gestionar los textos en diferentes idiomas
Input *mInput; // Manejador de entrada
// Player *mPlayer[2]; // Vector con los jugadores jugador
// Balloon *mBalloon[MAX_BALLOONS]; // Vector con los objetos globo
// Bullet *mBullet[MAX_BULLETS]; // Vector con los objetos bala
// Item *mItem[MAX_ITEMS]; // Vector con los objetos item
// SmartSprite *mSmartSprite[MAX_SMART_SPRITES]; // Vector para almacenar y gestionar SmartSprites
int mNumPlayers; // Numero de jugadores
std::vector<Player *> players; // Vector con los jugadores
std::vector<Balloon *> balloons; // Vector con los globos
std::vector<Balloon *> balloons; // Vector con los globos
std::vector<Bullet *> bullets; // Vector con las balas
std::vector<Item *> items; // Vector con los items
std::vector<SmartSprite *> smartSprites; // Vector con los smartsprites
LTexture *mTextureBalloon; // Textura para los enemigos
LTexture *mTextureBullet; // Textura para las balas
LTexture *mTextureGameBG; // Textura para el fondo del juego
LTexture *mTextureGameText; // Textura para los sprites con textos
LTexture *mTextureItems; // Textura para los items
LTexture *mTexturePlayer1Head; // Textura para la cabeza del jugador1
LTexture *mTexturePlayer1Body; // Textura para el cuerpo del jugador1
LTexture *mTexturePlayer1Death; // Textura para la animación de muerte del jugador1
LTexture *mTexturePlayer1Legs; // Textura para las piernas del jugador
LTexture *mTexturePlayer2Head; // Textura para la cabeza del jugador2
LTexture *mTexturePlayer2Body; // Textura para el cuerpo del jugador2
LTexture *mTexturePlayer2Death; // Textura para la animación de muerte del jugador2
LTexture *mTexturePlayer2Legs; // Textura para las piernas del jugador
LTexture *bulletTexture; // Textura para las balas
std::vector<LTexture *> itemTextures; // Vector con las texturas de los items
std::vector<LTexture *> balloonTextures; // Vector con las texturas de los globos
std::vector<LTexture *> player1Textures; // Vector con las texturas del jugador
std::vector<LTexture *> player2Textures; // Vector con las texturas del jugador
std::vector<std::vector<LTexture *>> playerTextures; // Vector con todas las texturas de los jugadores;
Text *mText; // Fuente para los textos del juego
Text *mTextBig; // Fuente de texto grande
Text *mTextScoreBoard; // Fuente para el marcador del juego
Text *mTextNokia2; // Otra fuente de texto para mesajes
Text *mTextNokiaBig2; // Y la versión en grande
LTexture *gameBuildingsTexture; // Textura con los edificios de fondo
LTexture *gameCloudsTexture; // Textura con las nubes de fondo
LTexture *gameGrassTexture; // Textura con la hierba del suelo
LTexture *gamePowerMeterTexture; // Textura con el marcador de poder de la fase
LTexture *gameSkyColorsTexture; // Textura con los diferentes colores de fondo del juego
LTexture *gameTextTexture; // Textura para los sprites con textos
LTexture *gameOverTexture; // Textura para la pantalla de game over
LTexture *gameOverEndTexture; // Textura para la pantalla de game over de acabar el juego
Menu *mMenuGameOver; // Menú de la pantalla de game over
Menu *mMenuPause; // Menú de la pantalla de pausa
std::vector<std::vector<std::string> *> itemAnimations; // Vector con las animaciones de los items
std::vector<std::vector<std::string> *> playerAnimations; // Vector con las animaciones del jugador
std::vector<std::vector<std::string> *> balloonAnimations; // Vector con las animaciones de los globos
Fade *mFade; // Objeto para renderizar fades
SDL_Event *mEventHandler; // Manejador de eventos
Text *text; // Fuente para los textos del juego
Text *textBig; // Fuente de texto grande
Text *textScoreBoard; // Fuente para el marcador del juego
Text *textNokia2; // Otra fuente de texto para mensajes
Text *textNokiaBig2; // Y la versión en grande
MovingSprite *mClouds1a; // Sprite para las nubes superiores
MovingSprite *mClouds1b; // Sprite para las nubes superiores
MovingSprite *mClouds2a; // Sprite para las nubes inferiores
MovingSprite *mClouds2b; // Sprite para las nubes inferiores
SmartSprite *m1000Bitmap; // Sprite con el texto 1.000
SmartSprite *m2500Bitmap; // Sprite con el texto 2.500
SmartSprite *m5000Bitmap; // Sprite con el texto 5.000
Sprite *mSpriteBackground; // Sprite con los graficos frontales del fondo
Sprite *mSpriteGetReady; // Sprite para el texto de GetReady del principio de la partida
Sprite *mSpriteGradient; // Sprite con los graficos del degradado de color de fondo
Sprite *mSpriteGrass; // Sprite para la hierba
Sprite *mSpritePowerMeter; // Sprite para el medidor de poder de la fase
Sprite *mSpriteScoreBoard; // Sprite para el fondo del marcador
Menu *gameOverMenu; // Menú de la pantalla de game over
Menu *pauseMenu; // Menú de la pantalla de pausa
JA_Sound mSoundBalloon; // Sonido para la explosión del globo
JA_Sound mSoundBullet; // Sonido para los disparos
JA_Sound mSoundPlayerCollision; // Sonido para la colisión del jugador con un enemigo
JA_Sound mSoundHiScore; // Sonido para cuando se alcanza la máxima puntuación
JA_Sound mSoundItemDrop; // Sonido para cuando se genera un item
JA_Sound mSoundItemPickup; // Sonido para cuando se recoge un item
JA_Sound mSoundCoffeeOut; // Sonido para cuando el jugador pierde el café al recibir un impacto
JA_Sound mSoundStageChange; // Sonido para cuando se cambia de fase
JA_Sound mSoundBubble1; // Sonido para cuando el jugador muere
JA_Sound mSoundBubble2; // Sonido para cuando el jugador muere
JA_Sound mSoundBubble3; // Sonido para cuando el jugador muere
JA_Sound mSoundBubble4; // Sonido para cuando el jugador muere
JA_Sound mSoundClock; // Sonido para cuando se detiene el tiempo con el item reloj
JA_Sound mSoundPowerBall; // Sonido para cuando se explota una Power Ball
JA_Sound mSoundCollision; // Sonido para cuando la máquina de café toca el suelo
Fade *fade; // Objeto para renderizar fades
SDL_Event *eventHandler; // Manejador de eventos
JA_Music mMusicPlaying; // Musica de fondo
MovingSprite *clouds1A; // Sprite para las nubes superiores
MovingSprite *clouds1B; // Sprite para las nubes superiores
MovingSprite *clouds2A; // Sprite para las nubes inferiores
MovingSprite *clouds2B; // Sprite para las nubes inferiores
SmartSprite *n1000Sprite; // Sprite con el texto 1.000
SmartSprite *n2500Sprite; // Sprite con el texto 2.500
SmartSprite *n5000Sprite; // Sprite con el texto 5.000
Uint32 mTicks; // Contador de ticks para ajustar la velocidad del programa
Uint8 mTicksSpeed; // Velocidad a la que se repiten los bucles del programa
Sprite *buildingsSprite; // Sprite con los edificios de fondo
Sprite *skyColorsSprite; // Sprite con los graficos del degradado de color de fondo
Sprite *grassSprite; // Sprite para la hierba
Sprite *powerMeterSprite; // Sprite para el medidor de poder de la fase
Sprite *gameOverSprite; // Sprite para dibujar los graficos del game over
Sprite *gameOverEndSprite; // Sprite para dibujar los graficos del game over de acabar el juego
Uint32 mHiScore; // Puntuación máxima
bool mHiScoreAchieved; // Indica si se ha superado la puntuación máxima
section_t mSection; // Seccion actual dentro del juego
stage_t mStage[10]; // Variable con los datos de cada pantalla
Uint8 mCurrentStage; // Indica la fase actual
Uint8 mStageBitmapCounter; // Contador para el tiempo visible del texto de Stage
float mStageBitmapPath[STAGE_COUNTER]; // Vector con los puntos Y por donde se desplaza el texto
float mGetReadyBitmapPath[STAGE_COUNTER]; // Vector con los puntos X por donde se desplaza el texto
Uint16 mDeathCounter; // Contador para la animación de muerte del jugador
Uint8 mDeathIndex; // Indice del vector de smartsprites que contiene el sprite del jugador
Uint8 mMenaceCurrent; // Nivel de amenaza actual
Uint8 mMenaceThreshold; // 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 numero de globos
bool mTimeStopped; // Indica si el tiempo está detenido
Uint16 mTimeStoppedCounter; // Temporizador para llevar la cuenta del tiempo detenido
Uint32 mCounter; // Contador para el juego
Uint32 mScoreDataFile[TOTAL_SCORE_DATA]; // Datos del fichero de puntos
SDL_Rect mGradientRect[4]; // Vector con las coordenadas de los 4 gradientes
Uint16 mBalloonsPopped; // Lleva la cuenta de los globos explotados
Uint8 mLastEnemyDeploy; // Guarda cual ha sido la última formación desplegada para no repetir;
int mEnemyDeployCounter; // Cuando se lanza una formación, se le da un valor y no sale otra hasta que llegue a cero
float mEnemySpeed; // Velocidad a la que se mueven los enemigos
float mDefaultEnemySpeed; // Velocidad base de los enemigos, sin incrementar
effect_t mEffect; // Variable para gestionar los efectos visuales
helper_t mHelper; // Variable para gestionar las ayudas
bool mPowerBallEnabled; // Indica si hay una powerball ya activa
Uint8 mPowerBallCounter; // Contador de formaciones enemigas entre la aparicion de una PowerBall y otra
bool mCoffeeMachineEnabled; // Indica si hay una máquina de café en el terreno de juego
Uint8 mPostFade; // Qué hacer al acabar el fade
float mSin[360]; // Vector con los valores del seno para 360 grados
bool mGameCompleted; // Indica si se ha completado la partida, llegando al final de la ultima pantalla
int mGameCompletedCounter; // Contador para el tramo final, cuando se ha completado la partida y ya no aparecen más enemigos
Uint8 mDifficulty; // Dificultad del juego
float mDifficultyScoreMultiplier; // Multiplicador de puntos en función de la dificultad
struct options_t *mOptions; // Variable con todas las variables de las opciones del programa
Uint8 mOnePlayerControl; // Variable para almacenar el valor de las opciones
enemyFormation_t mEnemyFormation[NUMBER_OF_ENEMY_FORMATIONS]; // Vector con todas las formaciones enemigas
enemyPool_t mEnemyPool[10]; // Variable con los diferentes conjuntos de formaciones enemigas
Uint8 mLastStageReached; // Contiene el numero de la última pantalla que se ha alcanzado
JA_Sound balloonSound; // Sonido para la explosión del globo
JA_Sound bulletSound; // Sonido para los disparos
JA_Sound playerCollisionSound; // Sonido para la colisión del jugador con un enemigo
JA_Sound hiScoreSound; // Sonido para cuando se alcanza la máxima puntuación
JA_Sound itemDropSound; // Sonido para cuando se genera un item
JA_Sound itemPickUpSound; // Sonido para cuando se recoge un item
JA_Sound coffeeOutSound; // Sonido para cuando el jugador pierde el café al recibir un impacto
JA_Sound stageChangeSound; // Sonido para cuando se cambia de fase
JA_Sound bubble1Sound; // Sonido para cuando el jugador muere
JA_Sound bubble2Sound; // Sonido para cuando el jugador muere
JA_Sound bubble3Sound; // Sonido para cuando el jugador muere
JA_Sound bubble4Sound; // Sonido para cuando el jugador muere
JA_Sound clockSound; // Sonido para cuando se detiene el tiempo con el item reloj
JA_Sound powerBallSound; // Sonido para cuando se explota una Power Ball
JA_Sound coffeeMachineSound; // Sonido para cuando la máquina de café toca el suelo
demo_t mDemo; // Variable con todas las variables relacionadas con el modo demo
debug_t mDebug; // Variable con las opciones de debug
JA_Music gameMusic; // Musica de fondo
// Inicializa el vector con los valores del seno
void initSin();
// Variables
int numPlayers; // Numero de jugadores
Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa
Uint8 ticksSpeed; // Velocidad a la que se repiten los bucles del programa
Uint32 hiScore; // Puntuación máxima
bool hiScoreAchieved; // Indica si se ha superado la puntuación máxima
section_t section; // Seccion actual dentro del juego
stage_t stage[10]; // Variable con los datos de cada pantalla
Uint8 currentStage; // Indica la fase actual
Uint8 stageBitmapCounter; // Contador para el tiempo visible del texto de Stage
float stageBitmapPath[STAGE_COUNTER]; // Vector con los puntos Y por donde se desplaza el texto
float getReadyBitmapPath[STAGE_COUNTER]; // Vector con los puntos X por donde se desplaza el texto
Uint16 deathCounter; // Contador para la animación de muerte del jugador
Uint8 menaceCurrent; // Nivel de amenaza actual
Uint8 menaceThreshold; // 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 numero de globos
bool timeStopped; // Indica si el tiempo está detenido
Uint16 timeStoppedCounter; // Temporizador para llevar la cuenta del tiempo detenido
Uint32 counter; // Contador para el juego
Uint32 scoreDataFile[TOTAL_SCORE_DATA]; // Datos del fichero de puntos
SDL_Rect skyColorsRect[4]; // Vector con las coordenadas de los 4 colores de cielo
Uint16 balloonsPopped; // Lleva la cuenta de los globos explotados
Uint8 lastEnemyDeploy; // Guarda cual ha sido la última formación desplegada para no repetir;
int enemyDeployCounter; // Cuando se lanza una formación, se le da un valor y no sale otra hasta que llegue a cero
float enemySpeed; // Velocidad a la que se mueven los enemigos
float defaultEnemySpeed; // Velocidad base de los enemigos, sin incrementar
effect_t effect; // Variable para gestionar los efectos visuales
helper_t helper; // Variable para gestionar las ayudas
bool powerBallEnabled; // Indica si hay una powerball ya activa
Uint8 powerBallCounter; // Contador de formaciones enemigas entre la aparicion de una PowerBall y otra
bool coffeeMachineEnabled; // Indica si hay una máquina de café en el terreno de juego
bool gameCompleted; // Indica si se ha completado la partida, llegando al final de la ultima pantalla
int gameCompletedCounter; // Contador para el tramo final, cuando se ha completado la partida y ya no aparecen más enemigos
Uint8 difficulty; // Dificultad del juego
float difficultyScoreMultiplier; // Multiplicador de puntos en función de la dificultad
color_t difficultyColor; // Color asociado a la dificultad
struct options_t *options; // Variable con todas las variables de las opciones del programa
Uint8 onePlayerControl; // Variable para almacenar el valor de las opciones
enemyFormation_t enemyFormation[NUMBER_OF_ENEMY_FORMATIONS]; // Vector con todas las formaciones enemigas
enemyPool_t enemyPool[10]; // Variable con los diferentes conjuntos de formaciones enemigas
Uint8 lastStageReached; // Contiene el numero de la última pantalla que se ha alcanzado
demo_t demo; // Variable con todas las variables relacionadas con el modo demo
int totalPowerToCompleteGame; // La suma del poder necesario para completar todas las fases
int cloudsSpeed; // Velocidad a la que se desplazan las nubes
int pauseCounter; // Contador para salir del menu de pausa y volver al juego
bool leavingPauseMenu; // Indica si esta saliendo del menu de pausa para volver al juego
// Actualiza el juego
void update();
// Dibuja el juego
void render();
// Comprueba los eventos que hay en cola
void checkEventHandler();
// Inicializa las variables necesarias para la sección 'Game'
void init();
// Carga los recursos necesarios para la sección 'Game'
bool loadMedia();
void loadMedia();
// Carga el fichero de puntos
bool loadScoreFile();
@@ -299,7 +293,10 @@ private:
void renderScoreBoard();
// Actualiza las variables del jugador
void updatePlayer();
void updatePlayers();
// Dibuja a los jugadores
void renderPlayers();
// Actualiza las variables de la fase
void updateStage();
@@ -317,14 +314,11 @@ private:
void renderBalloons();
// Crea un globo nuevo en el vector de globos
Uint8 createNewBalloon(float x, int y, Uint8 kind, float velx, float speed, Uint16 stoppedcounter, LTexture *texture);
Uint8 createBalloon(float x, int y, Uint8 kind, float velx, float speed, Uint16 stoppedcounter);
// Crea una PowerBall
void createPowerBall();
// Establece a cero todos los valores del vector de objetos globo
void resetBalloons();
// Establece la velocidad de los globos
void setBalloonSpeed(float speed);
@@ -358,6 +352,9 @@ private:
// Obtiene el numero de globos activos
Uint8 countBalloons();
// Vacia el vector de globos
void freeBalloons();
// Comprueba la colisión entre el jugador y los globos activos
bool checkPlayerBalloonCollision(Player *player);
@@ -373,30 +370,33 @@ private:
// Pinta las balas activas
void renderBullets();
// Establece a cero todos los valores del vector de objetos bala
void resetBullets();
// Crea un objeto bala
void createBullet(int x, int y, Uint8 kind, bool poweredUp, int owner);
// Vacia el vector de balas
void freeBullets();
// Actualiza los items
void updateItems();
// Pinta los items activos
void renderItems();
// Establece a cero todos los valores del vector de objetos item
void resetItems();
// Devuelve un item en función del azar
Uint8 dropItem();
// Crea un objeto item
void createItem(int x, int y, Uint8 kind);
void createItem(Uint8 kind, float x, float y);
// Vacia el vector de items
void freeItems();
// Crea un objeto SmartSprite
void createItemScoreSprite(int x, int y, SmartSprite *sprite);
// Vacia el vector de smartsprites
void freeSmartSprites();
// Dibuja el efecto de flash
void renderFlashEffect();
@@ -406,18 +406,12 @@ private:
// Crea un SmartSprite para arrojar el item café al recibir un impacto
void throwCoffee(int x, int y);
// Crea un SmartSprite para arrojar al jugador al morir
void throwPlayer(int x, int y, int index);
// Actualiza los SmartSprites
void updateSmartSprites();
// Pinta los SmartSprites activos
void renderSmartSprites();
// Establece a cero todos los valores del vector de objetos SmafrtSprite
void resetSmartSprites();
// Acciones a realizar cuando el jugador muere
void killPlayer(Player *player);
@@ -451,18 +445,12 @@ private:
// Gestiona el nivel de amenaza
void updateMenace();
// Actualiza el campo de juego
void updatePlayField();
// Actualiza el fondo
void updateBackground();
// Dibuja el fondo
void renderBackground();
// Dibuja el campo de juego
void renderPlayField();
// Gestiona la entrada durante el juego
void checkGameInput();
@@ -478,15 +466,24 @@ private:
// Agita la pantalla
void shakeScreen();
// Actualiza las variables del menu de pausa del juego
void updatePausedGame();
// Dibuja el menu de pausa del juego
void renderPausedGame();
// Bucle para el menu de pausa del juego
void runPausedGame();
// Actualiza los elementos de la pantalla de game over
void updateGameOverScreen();
// Dibuja los elementos de la pantalla de game over
void renderGameOverScreen();
// Bucle para la pantalla de game over
void runGameOverScreen();
// Dibuja la informacion de debug en pantalla
void renderDebugInfo();
// Indica si se puede crear una powerball
bool canPowerBallBeCreated();
@@ -505,9 +502,18 @@ private:
// Comprueba si todos los jugadores han muerto
bool allPlayersAreDead();
// Carga las animaciones
void loadAnimations(std::string filePath, std::vector<std::string> *buffer);
// Elimina todos los objetos contenidos en vectores
void deleteAllVectorObjects();
// Recarga las texturas
void reloadTextures();
public:
// Constructor
Game(int numPlayers, int currentStage, SDL_Renderer *renderer, Screen *screen, Asset *mAsset, Lang *lang, Input *input, bool demo, options_t *options);
Game(int numPlayers, int currentStage, SDL_Renderer *renderer, Screen *screen, Asset *asset, Lang *lang, Input *input, bool demo, options_t *options);
// Destructor
~Game();

View File

@@ -5,38 +5,38 @@
Input::Input(std::string file)
{
// Fichero gamecontrollerdb.txt
mDBpath = file;
dbPath = file;
// Inicializa las variables
for (int i = 0; i < 17; i++)
{
mKeyBindings[i].scancode = 0;
mKeyBindings[i].active = false;
keyBindings_t kb;
kb.scancode = 0;
kb.active = false;
keyBindings.resize(17, kb);
mGameControllerBindings[i].button = SDL_CONTROLLER_BUTTON_INVALID;
mGameControllerBindings[i].active = false;
}
GameControllerBindings_t gcb;
gcb.button = SDL_CONTROLLER_BUTTON_INVALID;
gcb.active = false;
gameControllerBindings.resize(17, gcb);
// Comprueba si hay un mando conectado
discoverGameController();
}
// Destructor
Input::~Input()
{
for (int i = 0; i < mNumGamepads; i++)
mConnectedControllers[i] = nullptr;
}
// Asigna uno de los posibles inputs a una tecla del teclado
void Input::bindKey(Uint8 input, SDL_Scancode code)
{
mKeyBindings[input].scancode = code;
keyBindings.at(input).scancode = code;
}
// Asigna uno de los posibles inputs a un botón del mando
void Input::bindGameControllerButton(Uint8 input, SDL_GameControllerButton button)
{
mGameControllerBindings[input].button = button;
gameControllerBindings.at(input).button = button;
}
// Comprueba si un input esta activo
@@ -48,24 +48,28 @@ bool Input::checkInput(Uint8 input, bool repeat, int device, int index)
if (device == INPUT_USE_ANY)
index = 0;
if ((device == INPUT_USE_KEYBOARD) || (device == INPUT_USE_ANY))
if (device == INPUT_USE_KEYBOARD || device == INPUT_USE_ANY)
{
const Uint8 *mKeystates = SDL_GetKeyboardState(nullptr);
const Uint8 *keyStates = SDL_GetKeyboardState(nullptr);
if (repeat)
{
if (mKeystates[mKeyBindings[input].scancode] != 0)
if (keyStates[keyBindings.at(input).scancode] != 0)
{
successKeyboard = true;
}
else
{
successKeyboard = false;
}
}
else
{
if (!mKeyBindings[input].active)
if (!keyBindings.at(input).active)
{
if (mKeystates[mKeyBindings[input].scancode] != 0)
if (keyStates[keyBindings.at(input).scancode] != 0)
{
mKeyBindings[input].active = true;
keyBindings.at(input).active = true;
successKeyboard = true;
}
else
@@ -75,9 +79,9 @@ bool Input::checkInput(Uint8 input, bool repeat, int device, int index)
}
else
{
if (mKeystates[mKeyBindings[input].scancode] == 0)
if (keyStates[keyBindings.at(input).scancode] == 0)
{
mKeyBindings[input].active = false;
keyBindings.at(input).active = false;
successKeyboard = false;
}
else
@@ -93,18 +97,22 @@ bool Input::checkInput(Uint8 input, bool repeat, int device, int index)
{
if (repeat)
{
if (SDL_GameControllerGetButton(mConnectedControllers[index], mGameControllerBindings[input].button) != 0)
if (SDL_GameControllerGetButton(connectedControllers.at(index), gameControllerBindings[input].button) != 0)
{
successGameController = true;
}
else
{
successGameController = false;
}
}
else
{
if (!mGameControllerBindings[input].active)
if (!gameControllerBindings[input].active)
{
if (SDL_GameControllerGetButton(mConnectedControllers[index], mGameControllerBindings[input].button) != 0)
if (SDL_GameControllerGetButton(connectedControllers.at(index), gameControllerBindings[input].button) != 0)
{
mGameControllerBindings[input].active = true;
gameControllerBindings[input].active = true;
successGameController = true;
}
else
@@ -114,9 +122,9 @@ bool Input::checkInput(Uint8 input, bool repeat, int device, int index)
}
else
{
if (SDL_GameControllerGetButton(mConnectedControllers[index], mGameControllerBindings[input].button) == 0)
if (SDL_GameControllerGetButton(connectedControllers.at(index), gameControllerBindings[input].button) == 0)
{
mGameControllerBindings[input].active = false;
gameControllerBindings[input].active = false;
successGameController = false;
}
else
@@ -136,45 +144,54 @@ bool Input::discoverGameController()
bool found = false;
if (SDL_WasInit(SDL_INIT_GAMECONTROLLER) != 1)
{
SDL_InitSubSystem(SDL_INIT_GAMECONTROLLER);
}
if (SDL_GameControllerAddMappingsFromFile(mDBpath.c_str()) < 0)
printf("Error, could not load %s file: %s\n", mDBpath.c_str(), SDL_GetError());
if (SDL_GameControllerAddMappingsFromFile(dbPath.c_str()) < 0)
{
printf("Error, could not load %s file: %s\n", dbPath.c_str(), SDL_GetError());
}
int nJoysticks = SDL_NumJoysticks();
mNumGamepads = 0;
const int nJoysticks = SDL_NumJoysticks();
numGamepads = 0;
// Cuenta el numero de mandos
for (int i = 0; i < nJoysticks; i++)
for (int i = 0; i < nJoysticks; ++i)
{
if (SDL_IsGameController(i))
mNumGamepads++;
{
numGamepads++;
}
}
printf("\nChecking for game controllers...\n");
printf("%i joysticks found, %i are gamepads\n", nJoysticks, mNumGamepads);
printf("%i joysticks found, %i are gamepads\n", nJoysticks, numGamepads);
if (mNumGamepads > 0)
if (numGamepads > 0)
{
found = true;
for (int i = 0; i < mNumGamepads; i++)
for (int i = 0; i < numGamepads; i++)
{
// Abre el mando y lo añade a la lista
SDL_GameController *pad = SDL_GameControllerOpen(i);
if (SDL_GameControllerGetAttached(pad) == 1)
{
mConnectedControllers.push_back(pad);
std::string separator(" #");
connectedControllers.push_back(pad);
const std::string separator(" #");
std::string name = SDL_GameControllerNameForIndex(i);
name.resize(25);
name = name + separator + std::to_string(i);
std::cout << name << std::endl;
mControllerNames.push_back(name);
controllerNames.push_back(name);
}
else
{
std::cout << "SDL_GetError() = " << SDL_GetError() << std::endl;
}
}
//mGameController = mConnectedControllers[0];
SDL_GameControllerEventState(SDL_ENABLE);
}
@@ -184,23 +201,31 @@ bool Input::discoverGameController()
// Comprueba si hay algun mando conectado
bool Input::gameControllerFound()
{
if (mNumGamepads > 0)
if (numGamepads > 0)
{
return true;
}
else
{
return false;
}
}
// Obten el nombre de un mando de juego
std::string Input::getControllerName(int index)
{
if (mNumGamepads > 0)
return mControllerNames[index];
if (numGamepads > 0)
{
return controllerNames.at(index);
}
else
{
return "";
}
}
// Obten el numero de mandos conectados
int Input::getNumControllers()
{
return mNumGamepads;
return numGamepads;
}

View File

@@ -41,19 +41,19 @@ private:
Uint8 scancode; // Scancode asociado
bool active; // Indica si está activo
};
keyBindings_t mKeyBindings[17]; // Vector con las teclas asociadas a los inputs predefinidos
struct GameControllerBindings_t
{
SDL_GameControllerButton button; // GameControllerButton asociado
bool active; // Indica si está activo
};
GameControllerBindings_t mGameControllerBindings[17]; // Vector con las teclas asociadas a los inputs predefinidos
std::vector<SDL_GameController *> mConnectedControllers; // Vector con todos los mandos conectados
std::vector<std::string> mControllerNames; // Vector con los nombres de los mandos
int mNumGamepads; // Numero de mandos conectados
std::string mDBpath; // Ruta al archivo gamecontrollerdb.txt
std::vector<keyBindings_t> keyBindings; // Vector con las teclas asociadas a los inputs predefinidos
std::vector<GameControllerBindings_t> gameControllerBindings; // Vector con las teclas asociadas a los inputs predefinidos
std::vector<SDL_GameController *> connectedControllers; // Vector con todos los mandos conectados
std::vector<std::string> controllerNames; // Vector con los nombres de los mandos
int numGamepads; // Numero de mandos conectados
std::string dbPath; // Ruta al archivo gamecontrollerdb.txt
// Comprueba si hay un mando conectado
bool discoverGameController();

View File

@@ -3,212 +3,248 @@
const Uint8 SELF = 0;
// Constructor
Instructions::Instructions(SDL_Renderer *renderer, Screen *screen, Asset *mAsset, Lang *lang)
Instructions::Instructions(SDL_Renderer *renderer, Screen *screen, Asset *asset, Lang *lang)
{
// Copia los punteros
mRenderer = renderer;
mScreen = screen;
this->mAsset = mAsset;
mLang = lang;
this->renderer = renderer;
this->screen = screen;
this->asset = asset;
this->lang = lang;
// Reserva memoria para los punteros
mEventHandler = new SDL_Event();
mItemTexture = new LTexture(mRenderer,mAsset->get("items.png"));
mSprite = new Sprite(0, 0, GAME_WIDTH, GAME_HEIGHT, mItemTexture, mRenderer);
mText = new Text(mAsset->get("smb2.png"), mAsset->get("smb2.txt"), mRenderer);
LTexture *item1 = new LTexture(renderer, asset->get("item_points1_disk.png"));
itemTextures.push_back(item1);
LTexture *item2 = new LTexture(renderer, asset->get("item_points2_gavina.png"));
itemTextures.push_back(item2);
LTexture *item3 = new LTexture(renderer, asset->get("item_points3_pacmar.png"));
itemTextures.push_back(item3);
LTexture *item4 = new LTexture(renderer, asset->get("item_clock.png"));
itemTextures.push_back(item4);
LTexture *item5 = new LTexture(renderer, asset->get("item_coffee.png"));
itemTextures.push_back(item5);
LTexture *item6 = new LTexture(renderer, asset->get("item_coffee_machine.png"));
itemTextures.push_back(item6);
eventHandler = new SDL_Event();
sprite = new Sprite(0, 0, 16, 16, itemTextures.at(0), renderer);
text = new Text(asset->get("smb2.png"), asset->get("smb2.txt"), renderer);
// Crea un backbuffer para el renderizador
mBackbuffer = SDL_CreateTexture(mRenderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, GAME_WIDTH, GAME_HEIGHT);
if (mBackbuffer == nullptr)
backbuffer = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, GAME_WIDTH, GAME_HEIGHT);
if (backbuffer == nullptr)
{
printf("Backbuffer could not be created!\nSDL Error: %s\n", SDL_GetError());
}
// Inicializa variables
section.name = SELF;
ticks = 0;
ticksSpeed = 15;
manualQuit = false;
counter = 0;
counterEnd = 600;
}
// Destructor
Instructions::~Instructions()
{
mRenderer = nullptr;
mScreen = nullptr;
mAsset = nullptr;
mLang = nullptr;
for (auto texture : itemTextures)
{
texture->unload();
delete texture;
}
itemTextures.clear();
mItemTexture->unload();
delete mItemTexture;
mItemTexture = nullptr;
delete sprite;
delete eventHandler;
delete text;
delete mSprite;
mSprite = nullptr;
delete mEventHandler;
mEventHandler = nullptr;
delete mText;
mText = nullptr;
SDL_DestroyTexture(mBackbuffer);
mBackbuffer = nullptr;
SDL_DestroyTexture(backbuffer);
}
// Inicializa las variables necesarias para la sección 'Instructions'
void Instructions::init()
// Actualiza las variables
void Instructions::update()
{
// Inicializa variables
mSection.name = SELF;
mTicks = 0;
mTicksSpeed = 15;
mManualQuit = false;
mCounter = 0;
// Comprueba los eventos
checkEventHandler();
// Actualiza las variables
if (SDL_GetTicks() - ticks > ticksSpeed)
{
// Actualiza el contador de ticks
ticks = SDL_GetTicks();
if (mode == m_auto)
{ // Modo automático
counter++;
if (counter == counterEnd)
{
section.name = PROG_SECTION_TITLE;
section.subsection = TITLE_SECTION_1;
}
}
else
{ // Modo manual
++counter %= 60000;
if (manualQuit)
{
section.name = PROG_SECTION_TITLE;
section.subsection = TITLE_SECTION_3;
}
}
}
}
// Pinta en pantalla
void Instructions::render()
{
// Pinta en pantalla
SDL_Rect window = {0, 0, GAME_WIDTH, GAME_HEIGHT};
SDL_Rect srcRect = {0, 0, 16, 16};
const color_t orangeColor = {0xFF, 0x7A, 0x00};
const SDL_Rect destRect1 = {60, 88 + (16 * 0), 16, 16}; // Disquito
const SDL_Rect destRect2 = {60, 88 + (16 * 1), 16, 16}; // Gavineixon
const SDL_Rect destRect3 = {60, 88 + (16 * 2), 16, 16}; // Pacmar
const SDL_Rect destRect4 = {60, 88 + (16 * 3), 16, 16}; // Time Stopper
const SDL_Rect destRect5 = {60, 88 + (16 * 4), 16, 16}; // Coffee
// Pinta en el backbuffer el texto y los sprites
SDL_SetRenderTarget(renderer, backbuffer);
SDL_SetRenderDrawColor(renderer, bgColor.r, bgColor.g, bgColor.b, 255);
SDL_RenderClear(renderer);
// Escribe el texto
text->writeDX(TXT_CENTER | TXT_COLOR | TXT_SHADOW, SCREEN_CENTER_X, 8, lang->getText(11), 1, orangeColor, 1, shdwTxtColor);
text->writeDX(TXT_CENTER | TXT_COLOR | TXT_SHADOW, SCREEN_CENTER_X, 24, lang->getText(12), 1, noColor, 1, shdwTxtColor);
text->writeDX(TXT_CENTER | TXT_COLOR | TXT_SHADOW, SCREEN_CENTER_X, 34, lang->getText(13), 1, noColor, 1, shdwTxtColor);
text->writeDX(TXT_CENTER | TXT_COLOR | TXT_SHADOW, SCREEN_CENTER_X, 48, lang->getText(14), 1, noColor, 1, shdwTxtColor);
text->writeDX(TXT_CENTER | TXT_COLOR | TXT_SHADOW, SCREEN_CENTER_X, 58, lang->getText(15), 1, noColor, 1, shdwTxtColor);
text->writeDX(TXT_CENTER | TXT_COLOR | TXT_SHADOW, SCREEN_CENTER_X, 75, lang->getText(16), 1, orangeColor, 1, shdwTxtColor);
text->writeShadowed(84, 92, lang->getText(17), shdwTxtColor);
text->writeShadowed(84, 108, lang->getText(18), shdwTxtColor);
text->writeShadowed(84, 124, lang->getText(19), shdwTxtColor);
text->writeShadowed(84, 140, lang->getText(20), shdwTxtColor);
text->writeShadowed(84, 156, lang->getText(21), shdwTxtColor);
if ((mode == m_manual) && (counter % 50 > 14))
{
text->writeDX(TXT_CENTER | TXT_COLOR | TXT_SHADOW, SCREEN_CENTER_X, GAME_HEIGHT - 12, lang->getText(22), 1, orangeColor, 1, shdwTxtColor);
}
// Disquito
sprite->setTexture(itemTextures.at(0));
sprite->setPos(destRect1);
srcRect.y = 16 * (((counter + 12) / 36) % 2);
sprite->setSpriteClip(srcRect);
sprite->render();
// Gavineixon
sprite->setTexture(itemTextures.at(1));
sprite->setPos(destRect2);
srcRect.y = 16 * (((counter + 9) / 36) % 2);
sprite->setSpriteClip(srcRect);
sprite->render();
// Pacmar
sprite->setTexture(itemTextures.at(2));
sprite->setPos(destRect3);
srcRect.y = 16 * (((counter + 6) / 36) % 2);
sprite->setSpriteClip(srcRect);
sprite->render();
// Time Stopper
sprite->setTexture(itemTextures.at(3));
sprite->setPos(destRect4);
srcRect.y = 16 * (((counter + 3) / 36) % 2);
sprite->setSpriteClip(srcRect);
sprite->render();
// Coffee
sprite->setTexture(itemTextures.at(4));
sprite->setPos(destRect5);
srcRect.y = 16 * (((counter + 0) / 36) % 2);
sprite->setSpriteClip(srcRect);
sprite->render();
// Cambia el destino de renderizado
SDL_SetRenderTarget(renderer, nullptr);
// Prepara para empezar a dibujar en la textura de juego
screen->start();
// Limpia la pantalla
screen->clean(bgColor);
// Establece la ventana del backbuffer
if (mode == m_auto)
{
window.y = std::max(8, GAME_HEIGHT - counter + 100);
}
else
{
window.y = 0;
}
// Copia el backbuffer al renderizador
SDL_RenderCopy(renderer, backbuffer, nullptr, &window);
// Vuelca el contenido del renderizador en pantalla
screen->blit();
}
// Comprueba los eventos
void Instructions::checkEventHandler()
{
// Comprueba los eventos que hay en la cola
while (SDL_PollEvent(eventHandler) != 0)
{
// Evento de salida de la aplicación
if (eventHandler->type == SDL_QUIT)
{
section.name = PROG_SECTION_QUIT;
break;
}
if ((eventHandler->type == SDL_KEYUP) || (eventHandler->type == SDL_JOYBUTTONUP))
{
if (mode == m_auto)
{
JA_StopMusic();
section.name = PROG_SECTION_TITLE;
section.subsection = TITLE_SECTION_1;
}
else
{
if (counter > 30)
{
manualQuit = true;
}
}
}
}
}
// Bucle para la pantalla de instrucciones
void Instructions::run(Uint8 mode)
section_t Instructions::run(mode_e mode)
{
init();
this->mode = mode;
while (mSection.name == SELF)
while (section.name == SELF)
{
// Comprueba los eventos que hay en la cola
while (SDL_PollEvent(mEventHandler) != 0)
{
// Evento de salida de la aplicación
if (mEventHandler->type == SDL_QUIT)
{
mSection.name = PROG_SECTION_QUIT;
break;
}
if ((mEventHandler->type == SDL_KEYDOWN) || (mEventHandler->type == SDL_JOYBUTTONDOWN))
{
if (mode == INSTRUCTIONS_MODE_AUTO)
{
JA_StopMusic();
mSection.name = PROG_SECTION_TITLE;
mSection.subsection = TITLE_SECTION_1;
}
else
mManualQuit = true;
}
}
// Actualiza las variables
if (SDL_GetTicks() - mTicks > mTicksSpeed)
{
// Actualiza el contador de ticks
mTicks = SDL_GetTicks();
// Modo automático
if (mode == INSTRUCTIONS_MODE_AUTO)
{
mCounter++;
if (mCounter == INSTRUCTIONS_COUNTER)
{
mSection.name = PROG_SECTION_TITLE;
mSection.subsection = TITLE_SECTION_1;
}
}
// Modo manual
else
{
++mCounter %= 60000;
if (mManualQuit)
{
mSection.name = PROG_SECTION_TITLE;
mSection.subsection = TITLE_SECTION_3;
}
}
}
// Pinta en pantalla
SDL_Rect window = {0, 0, GAME_WIDTH, GAME_HEIGHT};
SDL_Rect srcRect = {0, 0, 16, 16};
const color_t orangeColor = {0xFF, 0x7A, 0x00};
const SDL_Rect destRect1 = {60, 88 + (16 * 0), 16, 16}; // Disquito
const SDL_Rect destRect2 = {60, 88 + (16 * 1), 16, 16}; // Gavineixon
const SDL_Rect destRect3 = {60, 88 + (16 * 2), 16, 16}; // Pacmar
const SDL_Rect destRect4 = {60, 88 + (16 * 3), 16, 16}; // Time Stopper
const SDL_Rect destRect5 = {60, 88 + (16 * 4), 16, 16}; // Coffee
// Pinta en el backbuffer el texto y los sprites
SDL_SetRenderTarget(mRenderer, mBackbuffer);
SDL_SetRenderDrawColor(mRenderer, bgColor.r, bgColor.g, bgColor.b, 255);
SDL_RenderClear(mRenderer);
// Escribe el texto
mText->writeDX(TXT_CENTER | TXT_COLOR | TXT_SHADOW, SCREEN_CENTER_X, 8, mLang->getText(11), 1, orangeColor, 1, shdwTxtColor);
mText->writeDX(TXT_CENTER | TXT_COLOR | TXT_SHADOW, SCREEN_CENTER_X, 24, mLang->getText(12), 1, noColor, 1, shdwTxtColor);
mText->writeDX(TXT_CENTER | TXT_COLOR | TXT_SHADOW, SCREEN_CENTER_X, 34, mLang->getText(13), 1, noColor, 1, shdwTxtColor);
mText->writeDX(TXT_CENTER | TXT_COLOR | TXT_SHADOW, SCREEN_CENTER_X, 48, mLang->getText(14), 1, noColor, 1, shdwTxtColor);
mText->writeDX(TXT_CENTER | TXT_COLOR | TXT_SHADOW, SCREEN_CENTER_X, 58, mLang->getText(15), 1, noColor, 1, shdwTxtColor);
mText->writeDX(TXT_CENTER | TXT_COLOR | TXT_SHADOW, SCREEN_CENTER_X, 75, mLang->getText(16), 1, orangeColor, 1, shdwTxtColor);
mText->writeShadowed(84, 92, mLang->getText(17), shdwTxtColor);
mText->writeShadowed(84, 108, mLang->getText(18), shdwTxtColor);
mText->writeShadowed(84, 124, mLang->getText(19), shdwTxtColor);
mText->writeShadowed(84, 140, mLang->getText(20), shdwTxtColor);
mText->writeShadowed(84, 156, mLang->getText(21), shdwTxtColor);
if ((mode == INSTRUCTIONS_MODE_MANUAL) && (mCounter % 50 > 14))
mText->writeDX(TXT_CENTER | TXT_COLOR | TXT_SHADOW, SCREEN_CENTER_X, GAME_HEIGHT - 12, mLang->getText(22), 1, orangeColor, 1, shdwTxtColor);
// Disquito
mSprite->setPos(destRect1);
srcRect.x = 0;
srcRect.y = 16 * (((mCounter + 12) / 36) % 2);
mSprite->setSpriteClip(srcRect);
mSprite->render();
// Gavineixon
mSprite->setPos(destRect2);
srcRect.x += srcRect.w;
srcRect.y = 16 * (((mCounter + 9) / 36) % 2);
mSprite->setSpriteClip(srcRect);
mSprite->render();
// Pacmar
mSprite->setPos(destRect3);
srcRect.x += srcRect.w;
srcRect.y = 16 * (((mCounter + 6) / 36) % 2);
mSprite->setSpriteClip(srcRect);
mSprite->render();
// Time Stopper
mSprite->setPos(destRect4);
srcRect.x += srcRect.w;
srcRect.y = 16 * (((mCounter + 3) / 36) % 2);
mSprite->setSpriteClip(srcRect);
mSprite->render();
// Coffee
mSprite->setPos(destRect5);
srcRect.x += (srcRect.w * 2); // Se salta el icono del TNT
srcRect.y = 16 * (((mCounter + 0) / 36) % 2);
mSprite->setSpriteClip(srcRect);
mSprite->render();
// Cambia el destino de renderizado
SDL_SetRenderTarget(mRenderer, nullptr);
// Prepara para empezar a dibujar en la textura de juego
mScreen->start();
// Limpia la pantalla
mScreen->clean(bgColor);
// Establece la ventana del backbuffer
if (mode == INSTRUCTIONS_MODE_AUTO)
window.y = std::max(8, GAME_HEIGHT - mCounter + 100);
else
window.y = 0;
// Copia el backbuffer al renderizador
SDL_RenderCopy(mRenderer, mBackbuffer, nullptr, &window);
// Vuelca el contenido del renderizador en pantalla
mScreen->blit();
update();
render();
}
return section;
}

View File

@@ -12,31 +12,35 @@
#ifndef INSTRUCTIONS_H
#define INSTRUCTIONS_H
// Contadores
#define INSTRUCTIONS_COUNTER 600
// Modo para las instrucciones
#define INSTRUCTIONS_MODE_MANUAL 0
#define INSTRUCTIONS_MODE_AUTO 1
enum mode_e
{
m_manual,
m_auto
};
// Clase Instructions
class Instructions
{
private:
SDL_Renderer *mRenderer; // El renderizador de la ventana
Screen *mScreen; // Objeto encargado de dibujar en pantalla
LTexture *mItemTexture; // Textura con los graficos
SDL_Event *mEventHandler; // Manejador de eventos
SDL_Texture *mBackbuffer; // Textura para usar como backbuffer
Sprite *mSprite; // Sprite con la textura de las instrucciones
Asset *mAsset; // Objeto que gestiona todos los ficheros de recursos
Lang *mLang; // Objeto para gestionar los textos en diferentes idiomas
Text *mText; // Objeto para escribir texto
Uint16 mCounter; // Contador
section_t mSection; // Estado del bucle principal para saber si continua o se sale
Uint32 mTicks; // Contador de ticks para ajustar la velocidad del programa
Uint8 mTicksSpeed; // Velocidad a la que se repiten los bucles del programa
bool mManualQuit; // Indica si se quiere salir del modo manual
// Objetos
SDL_Renderer *renderer; // El renderizador de la ventana
Screen *screen; // Objeto encargado de dibujar en pantalla
std::vector<LTexture *> itemTextures; // Vector con las texturas de los items
SDL_Event *eventHandler; // Manejador de eventos
SDL_Texture *backbuffer; // Textura para usar como backbuffer
Sprite *sprite; // Sprite con la textura de las instrucciones
Asset *asset; // Objeto que gestiona todos los ficheros de recursos
Lang *lang; // Objeto para gestionar los textos en diferentes idiomas
Text *text; // Objeto para escribir texto
// Variables
Uint16 counter; // Contador
Uint16 counterEnd; // Valor final para el contador
section_t section; // Estado del bucle principal para saber si continua o se sale
Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa
Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles del programa
bool manualQuit; // Indica si se quiere salir del modo manual
mode_e mode; // Modo en el que se van a ejecutar las instrucciones
// Actualiza las variables
void update();
@@ -44,8 +48,8 @@ private:
// Pinta en pantalla
void render();
// Inicializa las variables
void init();
// Comprueba los eventos
void checkEventHandler();
public:
// Constructor
@@ -55,7 +59,7 @@ public:
~Instructions();
// Bucle principal
void run(Uint8 mode);
section_t run(mode_e mode);
};
#endif

View File

@@ -1,382 +1,446 @@
#include "intro.h"
// Constructor
Intro::Intro(SDL_Renderer *renderer, Screen *screen, Asset *mAsset, Lang *lang)
Intro::Intro(SDL_Renderer *renderer, Screen *screen, Asset *asset, Lang *lang)
{
// Copia los punteros
mRenderer = renderer;
mScreen = screen;
mLang = lang;
this->mAsset = mAsset;
this->renderer = renderer;
this->screen = screen;
this->lang = lang;
this->asset = asset;
// Reserva memoria para los punteros
mEventHandler = new SDL_Event();
mBitmapTexture = new LTexture(mRenderer,mAsset->get("intro.png"));
mText = new Text(mAsset->get("nokia.png"), mAsset->get("nokia.txt"), mRenderer);
// Reserva memoria para los objetos
eventHandler = new SDL_Event();
texture = new LTexture(renderer, asset->get("intro.png"));
text = new Text(asset->get("nokia.png"), asset->get("nokia.txt"), renderer);
for (int i = 0; i < INTRO_TOTAL_BITMAPS; i++)
// Carga los recursos
loadMedia();
// Inicializa variables
section.name = PROG_SECTION_INTRO;
section.subsection = 0;
ticks = 0;
ticksSpeed = 15;
scene = 1;
// Inicializa los bitmaps de la intro
const int totalBitmaps = 6;
for (int i = 0; i < totalBitmaps; ++i)
{
mBitmap[i] = new SmartSprite(mBitmapTexture, mRenderer);
SmartSprite *ss = new SmartSprite(texture, renderer);
ss->setWidth(128);
ss->setHeight(96);
ss->setEnabledCounter(20);
ss->setDestX(SCREEN_CENTER_X - 64);
ss->setDestY(SCREEN_FIRST_QUARTER_Y - 24);
bitmaps.push_back(ss);
}
for (int i = 0; i < INTRO_TOTAL_TEXTS; i++)
bitmaps.at(0)->setPosX(-128);
bitmaps.at(0)->setPosY(SCREEN_FIRST_QUARTER_Y - 24);
bitmaps.at(0)->setVelX(0.0f);
bitmaps.at(0)->setVelY(0.0f);
bitmaps.at(0)->setAccelX(0.6f);
bitmaps.at(0)->setAccelY(0.0f);
bitmaps.at(0)->setSpriteClip(0, 0, 128, 96);
bitmaps.at(1)->setPosX(GAME_WIDTH);
bitmaps.at(1)->setPosY(SCREEN_FIRST_QUARTER_Y - 24);
bitmaps.at(1)->setVelX(-1.0f);
bitmaps.at(1)->setVelY(0.0f);
bitmaps.at(1)->setAccelX(-0.3f);
bitmaps.at(1)->setAccelY(0.0f);
bitmaps.at(1)->setSpriteClip(128, 0, 128, 96);
bitmaps.at(2)->setPosX(SCREEN_CENTER_X - 64);
bitmaps.at(2)->setPosY(-96);
bitmaps.at(2)->setVelX(0.0f);
bitmaps.at(2)->setVelY(3.0f);
bitmaps.at(2)->setAccelX(0.1f);
bitmaps.at(2)->setAccelY(0.3f);
bitmaps.at(2)->setSpriteClip(0, 96, 128, 96);
bitmaps.at(2)->setEnabledCounter(250);
bitmaps.at(3)->setPosX(SCREEN_CENTER_X - 64);
bitmaps.at(3)->setPosY(GAME_HEIGHT);
bitmaps.at(3)->setVelX(0.0f);
bitmaps.at(3)->setVelY(-0.7f);
bitmaps.at(3)->setAccelX(0.0f);
bitmaps.at(3)->setAccelY(0.0f);
bitmaps.at(3)->setSpriteClip(128, 96, 128, 96);
bitmaps.at(4)->setPosX(SCREEN_CENTER_X - 64);
bitmaps.at(4)->setPosY(-96);
bitmaps.at(4)->setVelX(0.0f);
bitmaps.at(4)->setVelY(3.0f);
bitmaps.at(4)->setAccelX(0.1f);
bitmaps.at(4)->setAccelY(0.3f);
bitmaps.at(4)->setSpriteClip(0, 192, 128, 96);
bitmaps.at(5)->setPosX(GAME_WIDTH);
bitmaps.at(5)->setPosY(SCREEN_FIRST_QUARTER_Y - 24);
bitmaps.at(5)->setVelX(-0.7f);
bitmaps.at(5)->setVelY(0.0f);
bitmaps.at(5)->setAccelX(0.0f);
bitmaps.at(5)->setAccelY(0.0f);
bitmaps.at(5)->setSpriteClip(128, 192, 128, 96);
// Inicializa los textos de la intro
const int totalTexts = 9;
for (int i = 0; i < totalTexts; ++i)
{
mWriter[i] = new Writer(mText);
Writer *w = new Writer(text);
w->setPosX(BLOCK * 0);
w->setPosY(GAME_HEIGHT - (BLOCK * 6));
w->setKerning(-1);
w->setEnabled(false);
w->setEnabledCounter(180);
texts.push_back(w);
}
// Un dia qualsevol de l'any 2000
texts.at(0)->setCaption(lang->getText(27));
texts.at(0)->setSpeed(8);
// Tot esta tranquil a la UPV
texts.at(1)->setCaption(lang->getText(28));
texts.at(1)->setSpeed(8);
// Fins que un desaprensiu...
texts.at(2)->setCaption(lang->getText(29));
texts.at(2)->setSpeed(12);
// HEY! ME ANE A FERME UN CORTAET...
texts.at(3)->setCaption(lang->getText(30));
texts.at(3)->setSpeed(8);
// UAAAAAAAAAAAAA!!!
texts.at(4)->setCaption(lang->getText(31));
texts.at(4)->setSpeed(1);
// Espera un moment...
texts.at(5)->setCaption(lang->getText(32));
texts.at(5)->setSpeed(16);
// Si resulta que no tinc solt!
texts.at(6)->setCaption(lang->getText(33));
texts.at(6)->setSpeed(2);
// MERDA DE MAQUINA!
texts.at(7)->setCaption(lang->getText(34));
texts.at(7)->setSpeed(3);
// Blop... blop... blop...
texts.at(8)->setCaption(lang->getText(35));
texts.at(8)->setSpeed(16);
for (auto text : texts)
{
text->center(SCREEN_CENTER_X);
}
}
// Destructor
Intro::~Intro()
{
mRenderer = nullptr;
mScreen = nullptr;
mAsset = nullptr;
mLang = nullptr;
delete eventHandler;
delete mEventHandler;
mEventHandler = nullptr;
texture->unload();
delete texture;
mBitmapTexture->unload();
delete mBitmapTexture;
mBitmapTexture = nullptr;
for (int i = 0; i < INTRO_TOTAL_BITMAPS; i++)
for (auto bitmap : bitmaps)
{
delete mBitmap[i];
mBitmap[i] = nullptr;
delete bitmap;
}
for (int i = 0; i < INTRO_TOTAL_TEXTS; i++)
for (auto text : texts)
{
delete mWriter[i];
mWriter[i] = nullptr;
delete text;
}
JA_DeleteMusic(mMusic);
}
// Inicializa las variables
void Intro::init()
{
// Carga los recursos
loadMedia();
mSection = {PROG_SECTION_INTRO, 0};
mTicks = 0;
mTicksSpeed = 15;
// Inicializa el vector de eventos de la intro
for (int i = 0; i < INTRO_TOTAL_EVENTS; i++)
{
mEvents[i] = EVENT_WAITING;
}
// Inicializa los bitmaps de la intro
for (int i = 0; i < INTRO_TOTAL_BITMAPS; i++)
{
mBitmap[i]->init();
mBitmap[i]->setId(i);
mBitmap[i]->setIntroEvents(&mEvents[0]);
mBitmap[i]->setWidth(128);
mBitmap[i]->setHeight(96);
mBitmap[i]->setEnabled(false);
mBitmap[i]->setEnabledTimer(20);
mBitmap[i]->setDestX(SCREEN_CENTER_X - 64);
mBitmap[i]->setDestY(SCREEN_FIRST_QUARTER_Y - 24);
}
mBitmap[0]->setPosX(-128);
mBitmap[0]->setPosY(SCREEN_FIRST_QUARTER_Y - 24);
mBitmap[0]->setVelX(0.0f);
mBitmap[0]->setVelY(0.0f);
mBitmap[0]->setAccelX(0.6f);
mBitmap[0]->setAccelY(0.0f);
mBitmap[0]->setSpriteClip(0, 0, 128, 96);
mBitmap[1]->setPosX(GAME_WIDTH);
mBitmap[1]->setPosY(SCREEN_FIRST_QUARTER_Y - 24);
mBitmap[1]->setVelX(-1.0f);
mBitmap[1]->setVelY(0.0f);
mBitmap[1]->setAccelX(-0.3f);
mBitmap[1]->setAccelY(0.0f);
mBitmap[1]->setSpriteClip(128, 0, 128, 96);
mBitmap[2]->setPosX(SCREEN_CENTER_X - 64);
mBitmap[2]->setPosY(-96);
mBitmap[2]->setVelX(0.0f);
mBitmap[2]->setVelY(3.0f);
mBitmap[2]->setAccelX(0.1f);
mBitmap[2]->setAccelY(0.3f);
mBitmap[2]->setSpriteClip(0, 96, 128, 96);
mBitmap[2]->setEnabledTimer(250);
mBitmap[3]->setPosX(SCREEN_CENTER_X - 64);
mBitmap[3]->setPosY(GAME_HEIGHT);
mBitmap[3]->setVelX(0.0f);
mBitmap[3]->setVelY(-0.7f);
mBitmap[3]->setAccelX(0.0f);
mBitmap[3]->setAccelY(0.0f);
mBitmap[3]->setSpriteClip(128, 96, 128, 96);
mBitmap[4]->setPosX(SCREEN_CENTER_X - 64);
mBitmap[4]->setPosY(-96);
mBitmap[4]->setVelX(0.0f);
mBitmap[4]->setVelY(3.0f);
mBitmap[4]->setAccelX(0.1f);
mBitmap[4]->setAccelY(0.3f);
mBitmap[4]->setSpriteClip(0, 192, 128, 96);
mBitmap[5]->setPosX(GAME_WIDTH);
mBitmap[5]->setPosY(SCREEN_FIRST_QUARTER_Y - 24);
mBitmap[5]->setVelX(-0.7f);
mBitmap[5]->setVelY(0.0f);
mBitmap[5]->setAccelX(0.0f);
mBitmap[5]->setAccelY(0.0f);
mBitmap[5]->setSpriteClip(128, 192, 128, 96);
// Inicializa los textos de la intro
for (int i = 0; i < INTRO_TOTAL_TEXTS; i++)
{
mWriter[i]->init();
mWriter[i]->setId(6 + i);
mWriter[i]->setIntroEvents(&mEvents[0]);
mWriter[i]->setPosX(BLOCK * 0);
mWriter[i]->setPosY(GAME_HEIGHT - (BLOCK * 6));
mWriter[i]->setKerning(-1);
mWriter[i]->setEnabled(false);
mWriter[i]->setEnabledTimer(180);
}
// Un dia qualsevol de l'any 2000
mWriter[0]->setCaption(mLang->getText(27));
mWriter[0]->setSpeed(10);
// Tot esta tranquil a la UPV
mWriter[1]->setCaption(mLang->getText(28));
mWriter[1]->setSpeed(10);
// Fins que un desaprensiu...
mWriter[2]->setCaption(mLang->getText(29));
mWriter[2]->setSpeed(15);
// HEY! ME ANE A FERME UN CORTAET...
mWriter[3]->setCaption(mLang->getText(30));
mWriter[3]->setSpeed(10);
// UAAAAAAAAAAAAA!!!
mWriter[4]->setCaption(mLang->getText(31));
mWriter[4]->setSpeed(1);
// Espera un moment...
mWriter[5]->setCaption(mLang->getText(32));
mWriter[5]->setSpeed(20);
// Si resulta que no tinc solt!
mWriter[6]->setCaption(mLang->getText(33));
mWriter[6]->setSpeed(2);
// MERDA DE MAQUINA!
mWriter[7]->setCaption(mLang->getText(34));
mWriter[7]->setSpeed(3);
// Blop... blop... blop...
mWriter[8]->setCaption(mLang->getText(35));
mWriter[8]->setSpeed(20);
for (int i = 0; i < INTRO_TOTAL_TEXTS; i++)
mWriter[i]->center(SCREEN_CENTER_X);
JA_DeleteMusic(music);
}
// Carga los recursos
bool Intro::loadMedia()
{
bool success = true;
// Musicas
mMusic = JA_LoadMusic(mAsset->get("intro.ogg").c_str());
music = JA_LoadMusic(asset->get("intro.ogg").c_str());
return success;
return true;
}
// Comprueba los eventos
void Intro::checkEventHandler()
{
// Comprueba los eventos que hay en la cola
while (SDL_PollEvent(eventHandler) != 0)
{
// Evento de salida de la aplicación
if (eventHandler->type == SDL_QUIT)
{
section.name = PROG_SECTION_QUIT;
break;
}
// Cualquier tecla pulsada
if ((eventHandler->type == SDL_KEYDOWN) || (eventHandler->type == SDL_JOYBUTTONDOWN))
{
JA_StopMusic();
section.name = PROG_SECTION_TITLE;
section.subsection = TITLE_SECTION_1;
switch (eventHandler->key.keysym.scancode)
{
case SDL_SCANCODE_F:
screen->switchVideoMode();
texture->reLoad();
break;
case SDL_SCANCODE_F1:
screen->setWindowSize(1);
texture->reLoad();
break;
case SDL_SCANCODE_F2:
screen->setWindowSize(2);
texture->reLoad();
break;
case SDL_SCANCODE_F3:
screen->setWindowSize(3);
texture->reLoad();
break;
case SDL_SCANCODE_F4:
screen->setWindowSize(4);
texture->reLoad();
break;
default:
break;
}
}
}
}
// Actualiza las escenas de la intro
void Intro::updateScenes()
{
switch (scene)
{
case 1:
// Primera imagen - UPV
if (!bitmaps.at(0)->hasFinished())
{
bitmaps.at(0)->setEnabled(true);
}
// Primer texto de la primera imagen
if (bitmaps.at(0)->hasFinished() && !texts.at(0)->hasFinished())
{
texts.at(0)->setEnabled(true);
}
// Segundo texto de la primera imagen
if (texts.at(0)->hasFinished() && !texts.at(1)->hasFinished())
{
texts.at(0)->setEnabled(false);
texts.at(1)->setEnabled(true);
}
// Tercer texto de la primera imagen
if (texts.at(1)->hasFinished() && !texts.at(2)->hasFinished())
{
texts.at(1)->setEnabled(false);
texts.at(2)->setEnabled(true);
}
// Fin de la primera escena
if (texts.at(2)->hasFinished())
{
bitmaps.at(0)->setEnabled(false);
texts.at(2)->setEnabled(false);
scene++;
}
break;
case 2:
// Segunda imagen - Máquina
if (!bitmaps.at(1)->hasFinished())
{
bitmaps.at(1)->setEnabled(true);
}
// Primer texto de la segunda imagen
if (bitmaps.at(1)->hasFinished() && !texts.at(3)->hasFinished())
{
texts.at(3)->setEnabled(true);
}
// Fin de la segunda escena
if (texts.at(3)->hasFinished())
{
bitmaps.at(1)->setEnabled(false);
texts.at(3)->setEnabled(false);
scene++;
}
break;
case 3:
// Tercera imagen junto con primer texto - GRITO
if (!bitmaps.at(2)->hasFinished() && !texts.at(4)->hasFinished())
{
bitmaps.at(2)->setEnabled(true);
texts.at(4)->setEnabled(true);
}
// Fin de la tercera escena
if (bitmaps.at(2)->hasFinished() && texts.at(4)->hasFinished())
{
bitmaps.at(2)->setEnabled(false);
texts.at(4)->setEnabled(false);
scene++;
}
break;
case 4:
// Cuarta imagen junto con primer texto - Reflexión
if (!bitmaps.at(3)->hasFinished() && !texts.at(5)->hasFinished())
{
bitmaps.at(3)->setEnabled(true);
texts.at(5)->setEnabled(true);
}
// Segundo texto de la cuarta imagen
if (texts.at(5)->hasFinished() && !texts.at(6)->hasFinished())
{
texts.at(5)->setEnabled(false);
texts.at(6)->setEnabled(true);
}
// Fin de la cuarta escena
if (bitmaps.at(3)->hasFinished() && texts.at(6)->hasFinished())
{
bitmaps.at(3)->setEnabled(false);
texts.at(6)->setEnabled(false);
scene++;
}
break;
case 5:
// Quinta imagen - Patada
if (!bitmaps.at(4)->hasFinished())
{
bitmaps.at(4)->setEnabled(true);
}
// Primer texto de la quinta imagen
if (bitmaps.at(4)->hasFinished() && !texts.at(7)->hasFinished())
{
texts.at(7)->setEnabled(true);
}
// Fin de la quinta escena
if (bitmaps.at(4)->hasFinished() && texts.at(7)->hasFinished())
{
bitmaps.at(4)->setEnabled(false);
texts.at(7)->setEnabled(false);
scene++;
}
break;
case 6:
// Sexta imagen junto con texto - Globos de café
if (!bitmaps.at(5)->hasFinished() && !texts.at(8)->hasFinished())
{
bitmaps.at(5)->setEnabled(true);
texts.at(8)->setEnabled(true);
}
// Acaba el último texto
if (bitmaps.at(5)->hasFinished() && texts.at(8)->hasFinished())
{
bitmaps.at(5)->setEnabled(false);
texts.at(8)->setEnabled(false);
JA_StopMusic();
section.name = PROG_SECTION_TITLE;
section.subsection = TITLE_SECTION_1;
}
break;
default:
break;
}
}
// Actualiza las variables del objeto
void Intro::update()
{
checkEventHandler();
if (SDL_GetTicks() - ticks > ticksSpeed)
{
// Actualiza el contador de ticks
ticks = SDL_GetTicks();
// Actualiza los objetos
for (auto bitmap : bitmaps)
{
bitmap->update();
}
for (auto text : texts)
{
text->update();
}
// Actualiza las escenas de la intro
updateScenes();
}
}
// Dibuja el objeto en pantalla
void Intro::render()
{
// Prepara para empezar a dibujar en la textura de juego
screen->start();
// Limpia la pantalla
screen->clean(bgColor);
// Dibuja los objetos
for (auto bitmap : bitmaps)
{
bitmap->render();
}
for (auto text : texts)
{
text->render();
}
// Vuelca el contenido del renderizador en pantalla
screen->blit();
}
// Bucle principal
section_t Intro::run()
{
init();
JA_PlayMusic(music, 0);
// Si la música no está sonando la hace sonar
if ((JA_GetMusicState() == JA_MUSIC_INVALID) || (JA_GetMusicState() == JA_MUSIC_STOPPED))
while (section.name == PROG_SECTION_INTRO)
{
JA_PlayMusic(mMusic, 0);
update();
render();
}
while (mSection.name == PROG_SECTION_INTRO)
{
// Comprueba los eventos que hay en la cola
while (SDL_PollEvent(mEventHandler) != 0)
{
// Evento de salida de la aplicación
if (mEventHandler->type == SDL_QUIT)
{
mSection.name = PROG_SECTION_QUIT;
break;
}
if ((mEventHandler->type == SDL_KEYDOWN) || (mEventHandler->type == SDL_JOYBUTTONDOWN))
{
JA_StopMusic();
mSection = {PROG_SECTION_TITLE, TITLE_SECTION_1};
}
}
// Actualiza las variables
if (SDL_GetTicks() - mTicks > mTicksSpeed)
{
// Actualiza el contador de ticks
mTicks = SDL_GetTicks();
// Actualiza los objetos
for (int i = 0; i < INTRO_TOTAL_BITMAPS; i++)
{
mBitmap[i]->update();
}
for (int i = 0; i < INTRO_TOTAL_TEXTS; i++)
{
mWriter[i]->update();
}
// Guión de eventos
// Primera imagen - UPV
if (mEvents[BITMAP0] == EVENT_WAITING)
{
mBitmap[0]->setEnabled(true);
mEvents[BITMAP0] = EVENT_RUNNING;
}
// Primer texto de la primera imagen
if ((mEvents[BITMAP0] == EVENT_COMPLETED) && (mEvents[TEXT0] == EVENT_WAITING))
{
mWriter[0]->setEnabled(true);
mEvents[TEXT0] = EVENT_RUNNING;
}
// Segundo texto de la primera imagen
if ((mEvents[TEXT0] == EVENT_COMPLETED) && (mEvents[TEXT1] == EVENT_WAITING))
{
mWriter[0]->setEnabled(false);
mWriter[1]->setEnabled(true);
mEvents[TEXT1] = EVENT_RUNNING;
}
// Tercer texto de la primera imagen
if ((mEvents[TEXT1] == EVENT_COMPLETED) && (mEvents[TEXT2] == EVENT_WAITING))
{
mWriter[1]->setEnabled(false);
mWriter[2]->setEnabled(true);
mEvents[TEXT2] = EVENT_RUNNING;
}
// Segunda imagen - Máquina
if ((mEvents[TEXT2] == EVENT_COMPLETED) && (mEvents[BITMAP1] == EVENT_WAITING))
{
mBitmap[0]->setEnabled(false);
mWriter[2]->setEnabled(false);
mBitmap[1]->setEnabled(true);
mEvents[BITMAP1] = EVENT_RUNNING;
}
// Primer texto de la segunda imagen
if ((mEvents[BITMAP1] == EVENT_COMPLETED) && (mEvents[TEXT3] == EVENT_WAITING))
{
mWriter[3]->setEnabled(true);
mEvents[TEXT3] = EVENT_RUNNING;
}
// Tercera imagen junto con primer texto - GRITO
if ((mEvents[TEXT3] == EVENT_COMPLETED) && (mEvents[BITMAP2] == EVENT_WAITING) && (mEvents[TEXT4] == EVENT_WAITING))
{
mBitmap[1]->setEnabled(false);
mWriter[3]->setEnabled(false);
mBitmap[2]->setEnabled(true);
mWriter[4]->setEnabled(true);
mEvents[BITMAP2] = EVENT_RUNNING;
mEvents[TEXT4] = EVENT_RUNNING;
}
// Cuarta imagen junto con primer texto - Reflexión
if ((mEvents[TEXT4] == EVENT_COMPLETED) && (mEvents[BITMAP3] == EVENT_WAITING) && (mEvents[TEXT5] == EVENT_WAITING))
{
mBitmap[2]->setEnabled(false);
mWriter[4]->setEnabled(false);
mBitmap[3]->setEnabled(true);
mWriter[5]->setEnabled(true);
mEvents[BITMAP3] = EVENT_RUNNING;
mEvents[TEXT5] = EVENT_RUNNING;
}
// Segundo texto de la cuarta imagen
if ((mEvents[TEXT5] == EVENT_COMPLETED) && (mEvents[TEXT6] == EVENT_WAITING))
{
mWriter[5]->setEnabled(false);
mWriter[6]->setEnabled(true);
mEvents[TEXT6] = EVENT_RUNNING;
}
// Quinta imagen - Patada
if ((mEvents[TEXT6] == EVENT_COMPLETED) && (mEvents[BITMAP4] == EVENT_WAITING))
{
mBitmap[3]->setEnabled(false);
mWriter[6]->setEnabled(false);
mBitmap[4]->setEnabled(true);
mEvents[BITMAP4] = EVENT_RUNNING;
}
// Primer texto de la quinta imagen
if ((mEvents[BITMAP4] == EVENT_COMPLETED) && (mEvents[TEXT7] == EVENT_WAITING))
{
mWriter[7]->setEnabled(true);
mEvents[TEXT7] = EVENT_RUNNING;
}
// Sexta imagen junto con texto - Globos de café
if ((mEvents[TEXT7] == EVENT_COMPLETED) && (mEvents[BITMAP5] == EVENT_WAITING) && (mEvents[TEXT8] == EVENT_WAITING))
{
mBitmap[4]->setEnabled(false);
mWriter[7]->setEnabled(false);
mBitmap[5]->setEnabled(true);
mWriter[8]->setEnabled(true);
mEvents[BITMAP5] = EVENT_RUNNING;
mEvents[TEXT8] = EVENT_RUNNING;
}
// Acaba el último texto
if (mEvents[TEXT8] == EVENT_COMPLETED)
{
mWriter[8]->setEnabled(false);
JA_StopMusic();
mSection = {PROG_SECTION_TITLE, TITLE_SECTION_1};
}
}
// Prepara para empezar a dibujar en la textura de juego
mScreen->start();
// Limpia la pantalla
mScreen->clean(bgColor);
// Dibuja los objetos
for (int i = 0; i < INTRO_TOTAL_BITMAPS; ++i)
{
mBitmap[i]->render();
}
for (int i = 0; i < INTRO_TOTAL_TEXTS; ++i)
{
mWriter[i]->render();
}
// Vuelca el contenido del renderizador en pantalla
mScreen->blit();
}
return mSection;
return section;
}

View File

@@ -8,64 +8,55 @@
#include "smartsprite.h"
#include "utils.h"
#include "writer.h"
#include <vector>
#ifndef INTRO_H
#define INTRO_H
// Cantidad de eventos de la intro
#define INTRO_TOTAL_BITMAPS 6
#define INTRO_TOTAL_TEXTS 9
const int INTRO_TOTAL_EVENTS = INTRO_TOTAL_BITMAPS + INTRO_TOTAL_TEXTS;
// Relaciones de Id con nombres
#define BITMAP0 0
#define BITMAP1 1
#define BITMAP2 2
#define BITMAP3 3
#define BITMAP4 4
#define BITMAP5 5
#define TEXT0 6
#define TEXT1 7
#define TEXT2 8
#define TEXT3 9
#define TEXT4 10
#define TEXT5 11
#define TEXT6 12
#define TEXT7 13
#define TEXT8 14
// Clase Intro
class Intro
{
private:
SDL_Renderer *mRenderer; // El renderizador de la ventana
Screen *mScreen; // Objeto encargado de dibujar en pantalla
LTexture *mBitmapTexture; // Textura con los graficos
SDL_Event *mEventHandler; // Manejador de eventos
Asset *mAsset; // Objeto que gestiona todos los ficheros de recursos
Lang *mLang; // Objeto para gestionar los textos en diferentes idiomas
section_t mSection; // Estado del bucle principal para saber si continua o se sale
Uint32 mTicks; // Contador de ticks para ajustar la velocidad del programa
Uint8 mTicksSpeed; // Velocidad a la que se repiten los bucles del programa
SmartSprite *mBitmap[INTRO_TOTAL_BITMAPS]; // Vector con los sprites inteligentes para los dibujos de la intro
Writer *mWriter[INTRO_TOTAL_TEXTS]; // Textos de la intro
Text *mText; // Textos de la intro
Uint8 mEvents[INTRO_TOTAL_EVENTS]; // Vector para coordinar los eventos de la intro
JA_Music mMusic; // Musica para la intro
// Objetos
SDL_Renderer *renderer; // El renderizador de la ventana
Screen *screen; // Objeto encargado de dibujar en pantalla
LTexture *texture; // Textura con los graficos
SDL_Event *eventHandler; // Manejador de eventos
Asset *asset; // Objeto que gestiona todos los ficheros de recursos
Lang *lang; // Objeto para gestionar los textos en diferentes idiomas
std::vector<SmartSprite *> bitmaps; // Vector con los sprites inteligentes para los dibujos de la intro
std::vector<Writer *> texts; // Textos de la intro
Text *text; // Textos de la intro
// Variables
Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa
Uint8 ticksSpeed; // Velocidad a la que se repiten los bucles del programa
section_t section; // Estado del bucle principal para saber si continua o se sale
JA_Music music; // Musica para la intro
int scene; // Indica que escena está activa
// Actualiza las variables del objeto
void update();
// Dibuja el objeto en pantalla
void render();
// Carga los recursos
bool loadMedia();
// Comprueba los eventos
void checkEventHandler();
// Actualiza las escenas de la intro
void updateScenes();
public:
// Constructor
Intro(SDL_Renderer *renderer, Screen *screen, Asset *mAsset, Lang *lang);
Intro(SDL_Renderer *renderer, Screen *screen, Asset *asset, Lang *lang);
// Destructor
~Intro();
// Inicializa las variables
void init();
// Bucle principal
section_t run();
};

View File

@@ -2,125 +2,67 @@
#include "item.h"
// Constructor
Item::Item(LTexture *texture, SDL_Renderer *renderer)
Item::Item(Uint8 kind, float x, float y, LTexture *texture, std::vector<std::string> *animation, SDL_Renderer *renderer)
{
mSprite = new AnimatedSprite(texture, renderer);
init(NO_KIND, 0.0f, 0.0f);
sprite = new AnimatedSprite(texture, renderer, "", animation);
this->kind = kind;
enabled = true;
timeToLive = 600;
accelX = 0.0f;
floorCollision = false;
if (kind == ITEM_COFFEE_MACHINE)
{
width = 23;
height = 29;
posX = (((int)x + (PLAY_AREA_WIDTH / 2)) % (PLAY_AREA_WIDTH - width - 5)) + 2;
posY = PLAY_AREA_TOP - height;
velX = 0.0f;
velY = -0.1f;
accelY = 0.1f;
collider.r = 10;
}
else
{
width = 16;
height = 16;
posX = x;
posY = y;
velX = -1.0f + ((rand() % 5) * 0.5f);
velY = -4.0f;
accelY = 0.2f;
collider.r = width / 2;
}
sprite->setPosX(posX);
sprite->setPosY(posY);
shiftColliders();
}
// Destructor
Item::~Item()
{
delete mSprite;
mSprite = nullptr;
}
// Inicializador
void Item::init(Uint8 type, float x, float y)
{
mClass = type;
mEnabled = true;
mTimeToLive = 600;
mPosX = x;
mPosY = y;
mWidth = 16;
mHeight = 16;
mVelX = -1.0f + ((rand() % 5) * 0.5f);
mVelY = -4.0f;
mAccelX = 0.0f;
mAccelY = 0.2f;
mFloorCollision = false;
mCollider.r = mWidth / 2;
shiftColliders();
mSprite->setAnimationFrames(0, 0, 0, 48, mWidth, mHeight);
mSprite->setAnimationFrames(0, 1, 0, 64, mWidth, mHeight);
mSprite->setCurrentFrame(0);
mSprite->setAnimationCounter(0);
mSprite->setAnimationSpeed(0, 10);
mSprite->setAnimationLoop(0, true);
mSprite->setSpriteClip(mSprite->getAnimationClip(0, 0));
mSprite->setPosX(mPosX);
mSprite->setPosY(mPosY);
switch (type)
{
case NO_KIND:
mEnabled = false;
mTimeToLive = 0;
mPosX = 0;
mPosY = 0;
mWidth = 0;
mHeight = 0;
mVelX = 0;
mVelY = 0;
break;
case ITEM_POINTS_1_DISK:
mSprite->setAnimationFrames(0, 0, 16 * 0, 16 * 0, mWidth, mHeight);
mSprite->setAnimationFrames(0, 1, 16 * 0, 16 * 1, mWidth, mHeight);
break;
case ITEM_POINTS_2_GAVINA:
mSprite->setAnimationFrames(0, 0, 16 * 1, 16 * 0, mWidth, mHeight);
mSprite->setAnimationFrames(0, 1, 16 * 1, 16 * 1, mWidth, mHeight);
break;
case ITEM_POINTS_3_PACMAR:
mSprite->setAnimationFrames(0, 0, 16 * 2, 16 * 0, mWidth, mHeight);
mSprite->setAnimationFrames(0, 1, 16 * 2, 16 * 1, mWidth, mHeight);
break;
case ITEM_CLOCK:
mSprite->setAnimationFrames(0, 0, 16 * 3, 16 * 0, mWidth, mHeight);
mSprite->setAnimationFrames(0, 1, 16 * 3, 16 * 1, mWidth, mHeight);
break;
case ITEM_COFFEE:
mSprite->setAnimationFrames(0, 0, 16 * 5, 16 * 0, mWidth, mHeight);
mSprite->setAnimationFrames(0, 1, 16 * 5, 16 * 1, mWidth, mHeight);
break;
case ITEM_COFFEE_MACHINE:
mWidth = 32;
mHeight = 32;
mPosX = (((int)x + (PLAY_AREA_WIDTH / 2)) % (PLAY_AREA_WIDTH - mWidth - 5)) + 2;
mPosY = PLAY_AREA_TOP - mHeight;
mVelX = 0.0f;
mVelY = -0.1f;
mAccelY = 0.1f;
mSprite->setAnimationFrames(0, 0, 32 * 0, 16 * 2, mWidth, mHeight);
mSprite->setAnimationFrames(0, 1, 32 * 1, 16 * 2, mWidth, mHeight);
mSprite->setAnimationFrames(0, 2, 32 * 2, 16 * 2, mWidth, mHeight);
mSprite->setAnimationFrames(0, 3, 32 * 3, 16 * 2, mWidth, mHeight);
mSprite->setPosX(mPosX);
mSprite->setPosY(mPosY);
mCollider.r = 10;
shiftColliders();
break;
default:
break;
}
delete sprite;
}
// Centra el objeto en la posición X
void Item::allignTo(int x)
{
mPosX = float(x - (mWidth / 2));
posX = float(x - (width / 2));
if (mPosX < PLAY_AREA_LEFT)
if (posX < PLAY_AREA_LEFT)
{
mPosX = PLAY_AREA_LEFT + 1;
posX = PLAY_AREA_LEFT + 1;
}
else if ((mPosX + mWidth) > PLAY_AREA_RIGHT)
else if ((posX + width) > PLAY_AREA_RIGHT)
{
mPosX = float(PLAY_AREA_RIGHT - mWidth - 1);
posX = float(PLAY_AREA_RIGHT - width - 1);
}
// Posición X,Y del sprite
mSprite->setPosX(int(mPosX));
mSprite->setPosY(int(mPosY));
sprite->setPosX(int(posX));
sprite->setPosY(int(posY));
// Alinea el circulo de colisión con el objeto
shiftColliders();
@@ -129,15 +71,15 @@ void Item::allignTo(int x)
// Pinta el objeto en la pantalla
void Item::render()
{
if (mEnabled)
if (enabled)
{
if (mTimeToLive > 200)
if (timeToLive > 200)
{
mSprite->render();
sprite->render();
}
else if (mTimeToLive % 20 > 10)
else if (timeToLive % 20 > 10)
{
mSprite->render();
sprite->render();
}
}
}
@@ -145,149 +87,142 @@ void Item::render()
// Actualiza la posición y estados del objeto
void Item::move()
{
mFloorCollision = false;
floorCollision = false;
// Calcula la nueva posición
mPosX += mVelX;
mPosY += mVelY;
posX += velX;
posY += velY;
// Aplica las aceleraciones a la velocidad
mVelX += mAccelX;
mVelY += mAccelY;
velX += accelX;
velY += accelY;
// Si queda fuera de pantalla, corregimos su posición y cambiamos su sentido
if ((mPosX < PLAY_AREA_LEFT) || (mPosX + mWidth > PLAY_AREA_RIGHT))
if ((posX < PLAY_AREA_LEFT) || (posX + width > PLAY_AREA_RIGHT))
{
// Corregir posición
mPosX -= mVelX;
posX -= velX;
// Invertir sentido
mVelX = -mVelX;
velX = -velX;
}
// Si se sale por arriba rebota (excepto la maquina de café)
if ((mPosY < PLAY_AREA_TOP) && !(mClass == ITEM_COFFEE_MACHINE))
if ((posY < PLAY_AREA_TOP) && !(kind == ITEM_COFFEE_MACHINE))
{
// Corrige
mPosY = PLAY_AREA_TOP;
posY -= velY;
// Invierte el sentido
mVelY = -mVelY;
velY = -velY;
}
// Si el objeto se sale por la parte inferior
if (mPosY + mHeight > PLAY_AREA_BOTTOM)
if (posY + height > PLAY_AREA_BOTTOM)
{
// Corrige
mPosY -= mVelY;
posY -= velY;
// Detiene el objeto
mVelY = 0;
mVelX = 0;
mAccelX = 0;
mAccelY = 0;
mPosY = PLAY_AREA_BOTTOM - mHeight;
if (mClass == ITEM_COFFEE_MACHINE)
mFloorCollision = true;
velY = 0;
velX = 0;
accelX = 0;
accelY = 0;
posY = PLAY_AREA_BOTTOM - height;
if (kind == ITEM_COFFEE_MACHINE)
{
floorCollision = true;
}
}
// Actualiza la posición del sprite
mSprite->setPosX(int(mPosX));
mSprite->setPosY(int(mPosY));
sprite->setPosX(int(posX));
sprite->setPosY(int(posY));
shiftColliders();
}
// Pone a cero todos los valores del objeto
void Item::erase()
void Item::disable()
{
// init(NO_KIND, 0, 0, nullptr, nullptr);
enabled = false;
}
// Actualiza el objeto a su posicion, animación y controla los contadores
void Item::update()
{
if (mEnabled)
{
move();
shiftColliders();
mSprite->animate();
updateTimeToLive();
checkTimeToLive();
}
move();
sprite->animate();
updateTimeToLive();
checkTimeToLive();
}
// Actualiza el contador
void Item::updateTimeToLive()
{
if (mTimeToLive > 0)
if (timeToLive > 0)
{
mTimeToLive--;
timeToLive--;
}
}
// Comprueba si el objeto sigue vivo
void Item::checkTimeToLive()
{
if (mTimeToLive == 0)
erase();
if (timeToLive == 0)
disable();
}
// Obtiene del valor de la variable
float Item::getPosX()
{
return mPosX;
return posX;
}
// Obtiene del valor de la variable
float Item::getPosY()
{
return mPosY;
return posY;
}
// Obtiene del valor de la variable
int Item::getWidth()
{
return mWidth;
return width;
}
// Obtiene del valor de la variable
int Item::getHeight()
{
return mHeight;
return height;
}
// Obtiene del valor de la variable
int Item::getClass()
{
return mClass;
return kind;
}
// Obtiene el valor de la variable
bool Item::isEnabled()
{
return mEnabled;
}
// Establece el valor de la variable
void Item::setEnabled(bool value)
{
mEnabled = value;
return enabled;
}
// Obtiene el circulo de colisión
circle_t &Item::getCollider()
{
return mCollider;
return collider;
}
// Alinea el circulo de colisión con la posición del objeto
void Item::shiftColliders()
{
mCollider.x = int(mPosX + (mWidth / 2));
mCollider.y = int(mPosY + (mHeight / 2));
collider.x = int(posX + (width / 2));
collider.y = int(posY + (height / 2));
}
// Informa si el objeto ha colisionado con el suelo
bool Item::floorCollision()
bool Item::isOnFloor()
{
return mFloorCollision;
return floorCollision;
}

View File

@@ -8,60 +8,57 @@
#define ITEM_H
// Tipos de objetos
#define ITEM_POINTS_1_DISK 1
#define ITEM_POINTS_2_GAVINA 2
#define ITEM_POINTS_3_PACMAR 3
#define ITEM_CLOCK 4
#define ITEM_COFFEE 5
#define ITEM_POWER_BALL 6
#define ITEM_COFFEE_MACHINE 7
#define ITEM_POINTS_1_DISK 0
#define ITEM_POINTS_2_GAVINA 1
#define ITEM_POINTS_3_PACMAR 2
#define ITEM_CLOCK 3
#define ITEM_COFFEE 4
#define ITEM_COFFEE_MACHINE 5
// Clase Item
class Item
{
private:
float mPosX; // Posición X del objeto
float mPosY; // Posición Y del objeto
Uint8 mWidth; // Ancho del objeto
Uint8 mHeight; // Alto del objeto
float mVelX; // Velocidad en el eje X
float mVelY; // Velocidad en el eje Y
float mAccelX; // Aceleración en el eje X
float mAccelY; // Aceleración en el eje Y
bool mFloorCollision; // Indica si el objeto colisiona con el suelo
// Objetos
AnimatedSprite *sprite; // Sprite con los graficos del objeto
AnimatedSprite *mSprite; // Sprite con los graficos del objeto
Uint8 mClass; // Especifica el tipo de objeto que es
bool mEnabled; // Especifica si el objeto está habilitado
circle_t mCollider; // Circulo de colisión del objeto
// Variables
float posX; // Posición X del objeto
float posY; // Posición Y del objeto
Uint8 width; // Ancho del objeto
Uint8 height; // Alto del objeto
float velX; // Velocidad en el eje X
float velY; // Velocidad en el eje Y
float accelX; // Aceleración en el eje X
float accelY; // Aceleración en el eje Y
bool floorCollision; // Indica si el objeto colisiona con el suelo
Uint8 kind; // Especifica el tipo de objeto que es
bool enabled; // Especifica si el objeto está habilitado
circle_t collider; // Circulo de colisión del objeto
// Alinea el circulo de colisión con la posición del objeto
void shiftColliders();
// Actualiza la posición y estados del objeto
void move();
public:
Uint16 mTimeToLive; // Temporizador con el tiempo que el objeto está presente
Uint16 timeToLive; // Temporizador con el tiempo que el objeto está presente
// Constructor
Item(LTexture *texture, SDL_Renderer *renderer);
Item(Uint8 kind, float x, float y, LTexture *texture, std::vector<std::string> *animation, SDL_Renderer *renderer);
// Destructor
~Item();
// Inicializador
void init(Uint8 type, float x, float y);
// Centra el objeto en la posición X
void allignTo(int x);
// Pinta el objeto en la pantalla
void render();
// Actualiza la posición y estados del objeto
void move();
// Pone a cero todos los valores del objeto
void erase();
void disable();
// Actualiza al objeto a su posicion, animación y controla los contadores
void update();
@@ -90,14 +87,11 @@ public:
// Obtiene el valor de la variable
bool isEnabled();
// Establece el valor de la variable
void setEnabled(bool value);
// Obtiene el circulo de colisión
circle_t &getCollider();
// Informa si el objeto ha colisionado con el suelo
bool floorCollision();
bool isOnFloor();
};
#endif

View File

@@ -46,20 +46,20 @@ bool Lang::setLang(Uint8 lang)
if (rfile.is_open() && rfile.good())
{
success = true;
std::string buffer;
std::string line;
// lee el resto de datos del fichero
int index = 0;
int line_read = 0;
while (std::getline(rfile, buffer))
while (std::getline(rfile, line))
{
// Almacena solo las lineas impares
if (line_read % 2 == 1)
mTextStrings[index++] = buffer;
// Limpia el buffer
buffer.clear();
line_read++;
// Almacena solo las lineas que no empiezan por # o no esten vacias
const bool test1 = line.substr(0,1) != "#";
const bool test2 = !line.empty();
if (test1 && test2)
{
mTextStrings[index] = line;
index++;
}
};
}

View File

@@ -14,14 +14,7 @@ Logo::Logo(SDL_Renderer *renderer, Screen *screen, Asset *asset)
// Reserva memoria para los punteros
eventHandler = new SDL_Event();
texture = new LTexture(renderer, asset->get("logo.png"));
sprite = new Sprite(0, 0, GAME_WIDTH, GAME_HEIGHT, texture, renderer);
// Crea un backbuffer para el renderizador
backbuffer = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, GAME_WIDTH, GAME_HEIGHT);
if (backbuffer == nullptr)
{
printf("Backbuffer could not be created!\nSDL Error: %s\n", SDL_GetError());
}
sprite = new Sprite(14, 75, 226, 44, texture, renderer);
// Inicializa variables
counter = 0;
@@ -34,8 +27,6 @@ Logo::Logo(SDL_Renderer *renderer, Screen *screen, Asset *asset)
// Destructor
Logo::~Logo()
{
SDL_DestroyTexture(backbuffer);
texture->unload();
delete texture;
@@ -46,24 +37,11 @@ Logo::~Logo()
// Comprueba si ha terminado el logo
void Logo::checkLogoEnd()
{
if (counter == 0)
if (counter >= END_LOGO + 20)
{
if (JA_GetMusicState() == JA_MUSIC_PLAYING)
{
JA_StopMusic();
}
}
if (counter == END_LOGO + 20)
{
counter = 0;
section.name = PROG_SECTION_INTRO;
section.subsection = 0;
}
else
{
counter++;
}
}
// Comprueba los eventos
@@ -91,22 +69,13 @@ void Logo::checkEventHandler()
// Dibuja el fade
void Logo::renderFade()
{
const SDL_Rect rect = {0, 0, GAME_WIDTH, GAME_HEIGHT};
const int fadeLenght = END_LOGO - INIT_FADE;
// Dibuja el fade
if (counter >= INIT_FADE)
{
const Uint16 alpha = (255 * (counter - INIT_FADE)) / fadeLenght;
if (alpha < 256)
{
SDL_SetRenderDrawColor(renderer, bgColor.r, bgColor.g, bgColor.b, alpha);
}
else
{
SDL_SetRenderDrawColor(renderer, bgColor.r, bgColor.g, bgColor.b, 255);
}
SDL_RenderFillRect(renderer, &rect);
const float step = (float)(counter - INIT_FADE) / (float)(END_LOGO - INIT_FADE);
const int alpha = std::min((int)(255 * step), 255);
SDL_SetRenderDrawColor(renderer, bgColor.r, bgColor.g, bgColor.b, alpha);
SDL_RenderFillRect(renderer, nullptr);
}
}
@@ -120,6 +89,9 @@ void Logo::update()
// Actualiza el contador de ticks
ticks = SDL_GetTicks();
// Actualiza el contador
counter++;
// Comprueba si ha terminado el logo
checkLogoEnd();
}
@@ -132,7 +104,7 @@ void Logo::render()
screen->start();
// Limpia la pantalla
screen->clean(bgColor);
screen->clean({238, 238, 238});
// Dibuja los objetos
sprite->render();
@@ -147,6 +119,8 @@ void Logo::render()
// Bucle para el logo del juego
section_t Logo::run()
{
JA_StopMusic();
while (section.name == PROG_SECTION_LOGO)
{
update();

View File

@@ -15,17 +15,19 @@
class Logo
{
private:
// Objetos
SDL_Renderer *renderer; // El renderizador de la ventana
Screen *screen; // Objeto encargado de dibujar en pantalla
Asset *asset; // Objeto que gestiona todos los ficheros de recursos
LTexture *texture; // Textura con los graficos
SDL_Event *eventHandler; // Manejador de eventos
SDL_Texture *backbuffer; // Textura para usar como backbuffer
Sprite *sprite; // Sprite con la textura del logo
int counter; // Contador
section_t section; // Estado del bucle principal para saber si continua o se sale
// Variables
Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa
Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles del programa
section_t section; // Estado del bucle principal para saber si continua o se sale
int counter; // Contador
// Actualiza las variables del objeto
void update();

View File

@@ -32,6 +32,7 @@ LTexture::~LTexture()
// Carga una imagen desde un fichero
bool LTexture::loadFromFile(std::string path, SDL_Renderer *renderer)
{
const std::string filename = path.substr(path.find_last_of("\\/") + 1);
int req_format = STBI_rgb_alpha;
int width, height, orig_format;
unsigned char *data = stbi_load(path.c_str(), &width, &height, &orig_format, req_format);
@@ -40,6 +41,10 @@ bool LTexture::loadFromFile(std::string path, SDL_Renderer *renderer)
SDL_Log("Loading image failed: %s", stbi_failure_reason());
exit(1);
}
else
{
printf("Image loaded: %s\n", filename.c_str());
}
int depth, pitch;
Uint32 pixel_format;
@@ -144,7 +149,7 @@ void LTexture::setAlpha(Uint8 alpha)
// Renderiza la textura en un punto específico
void LTexture::render(SDL_Renderer *renderer, int x, int y, SDL_Rect *clip, float zoomW, float zoomH, double angle, SDL_Point *center, SDL_RendererFlip flip)
{
// Establece el destini de renderizado en la pantalla
// Establece el destino de renderizado en la pantalla
SDL_Rect renderQuad = {x, y, width, height};
// Obtiene las dimesiones del clip de renderizado

Some files were not shown because too many files have changed in this diff Show More