90 Commits

Author SHA1 Message Date
d3f17bc93a Release 2.0 2021-09-03 19:21:26 +02:00
b7490ed1c1 Preparing release 2.0 2021-09-03 12:58:54 +02:00
836deb720d new logo.png 2021-09-03 12:47:16 +02:00
7e9a1cb049 bug fixes 2021-09-02 10:07:54 +02:00
f928195a05 bug fixes 2021-09-01 22:58:50 +02:00
84b09a4987 Bug fixes 2021-09-01 19:26:34 +02:00
f0b9a1d134 Fixed offset from render messages with nokia font 2021-09-01 19:10:00 +02:00
64369921ec bug fixes 2021-09-01 17:23:12 +02:00
70ae7f67a9 Merge branch 'master' of https://gitea.sustancia.synology.me/JailDesigner/coffee_crisis 2021-09-01 16:54:41 +02:00
2ea86ef39f added font nokia2 2021-09-01 16:54:19 +02:00
658bb71441 bug fixes 2021-09-01 14:04:34 +02:00
0b996ea321 Working on support for various controllers 2021-08-31 21:36:09 +02:00
cf072424c6 Working on support for various controllers 2021-08-31 21:30:55 +02:00
42c0f19c68 Working on support for various controllers 2021-08-31 21:05:04 +02:00
8d1cabb288 updated some pngs 2021-08-31 18:00:55 +02:00
87aeaab6b8 bug fixes 2021-08-31 17:09:30 +02:00
ad5fb0fc22 Working on support for various controllers 2021-08-31 13:56:03 +02:00
8e6d546b97 Start to work on support for various controllers 2021-08-31 10:18:13 +02:00
f916381a9b added gamecontrollersDB.txt 2021-08-31 07:23:27 +02:00
fd94aea99b added gamecontrollerdb.txt 2021-08-30 22:24:39 +02:00
cda4d3a566 added gamecontrollerdb.txt 2021-08-30 22:24:16 +02:00
22ca349171 Improved menu class 2021-08-30 20:58:57 +02:00
74c08884ae Improving menu class. Selector flickers when selecting 2021-08-30 17:16:53 +02:00
005eab5694 Reduced checkFileList function 2021-08-30 14:06:33 +02:00
56dd646dde Centered new/translated GetReady text 2021-08-30 13:37:28 +02:00
eb7f534b3b menu selector now resizes smooth 2021-08-30 12:39:11 +02:00
384cfa7156 Solved 1P death music. Some tweaks to bg.png 2021-08-29 22:55:19 +02:00
224b176108 Dual input for P1 done 2021-08-29 22:03:48 +02:00
02b528ea8c Start to work on dual input for P1 2021-08-29 19:54:18 +02:00
4de3d69bb8 Powerup face blinking 2021-08-29 16:22:19 +02:00
c373d10720 added nokia_big font 2021-08-29 13:42:26 +02:00
88e5303d28 options menu completed 2021-08-29 13:35:19 +02:00
697e5d796f menu class improved 2021-08-29 00:54:05 +02:00
0baf73b9ae working on options menu, almost done 2021-08-28 23:45:29 +02:00
0341a0fe9d working on options menu, almost done 2021-08-28 23:17:00 +02:00
e9fcacd7c6 working on options menu 2021-08-28 21:43:47 +02:00
502835453a added difficulty (speed and points) 2021-08-28 19:51:32 +02:00
914b9e4123 fixing bugs 2021-08-28 18:26:45 +02:00
946ab62c30 writer class completed 2021-08-28 13:21:10 +02:00
13be9df131 text2 class converted to writer class 2021-08-28 12:57:13 +02:00
a54d71c990 lang class 2021-08-28 12:23:04 +02:00
cc8ef6e927 working on text notifications 2021-08-28 00:55:27 +02:00
3f53ba333b working on text notifications 2021-08-27 22:40:48 +02:00
aac11d05aa updated title.png 2021-08-27 16:49:15 +02:00
acbdcf2fc1 Working on title cosmetics 2021-08-27 16:48:10 +02:00
c12a7dc885 updated title.png 2021-08-27 16:25:10 +02:00
ff0102256c enhancing title screen 2021-08-27 13:54:57 +02:00
75031038c8 working on CM collider 2021-08-27 12:44:02 +02:00
70324570c8 bug hunting coffee machine on windows 2021-08-27 12:32:34 +02:00
5d6047b642 bug hunting coffee machine on windows 2021-08-27 08:58:54 +02:00
97d5140ef9 bug hunting coffee machine on windows 2021-08-27 08:33:21 +02:00
dafba0648f bug fix 2021-08-26 22:44:19 +02:00
d240f8123c fixing some bugs 2021-08-26 20:49:49 +02:00
3cb822ee6c working on new text engine 2021-08-26 18:14:56 +02:00
6d2fd16ec2 working on new font engine 2021-08-26 13:59:46 +02:00
e93aba2522 working on new font engine 2021-08-26 13:59:25 +02:00
5768c1f7a2 renamed fonts.png 2021-08-26 07:39:27 +02:00
30c8a31a48 moved fonts.png to new folder 2021-08-26 07:31:31 +02:00
a2a6262ffe working on new font engine 2021-08-25 22:35:54 +02:00
dbd22fa719 new font added 2021-08-25 20:00:59 +02:00
5bb5022ebf fix bullet owner bug 2021-08-25 17:59:40 +02:00
3440dea0a5 working on game controller 2021-08-25 13:34:40 +02:00
36eaf1de4f working on game controller 2021-08-25 12:02:18 +02:00
c3d560a9b6 working on game controller input 2021-08-24 20:52:32 +02:00
09cee79122 working on game controller input 2021-08-24 20:28:27 +02:00
03cbc67cfb working on game controller input 2021-08-24 20:20:08 +02:00
23d9bb0e3d working on game controller input 2021-08-24 20:15:20 +02:00
f9d6917770 working on game controller input 2021-08-24 20:12:28 +02:00
bf45482c10 working on game controller input 2021-08-24 20:06:34 +02:00
39a59336e4 working on game controller input 2021-08-24 19:56:25 +02:00
7c0201f913 working on game controller input 2021-08-24 17:57:21 +02:00
b61fd84e22 working on 2p 2021-08-24 13:01:33 +02:00
52ea512eab working on 2p 2021-08-23 21:53:54 +02:00
Sergio Valor
26ac51b1be working on 2players 2021-08-23 13:44:05 +02:00
fb1ff3c97a working on 2players 2021-08-23 08:11:24 +02:00
943fb7bf27 working on 2players 2021-08-22 19:50:55 +02:00
2fd4334259 added poerup and helper 2021-08-22 16:15:10 +02:00
eb8f84a4b8 added player2 gfx 2021-08-22 09:41:38 +02:00
e793e08e85 added player2 gfx 2021-08-22 09:41:17 +02:00
837306f16e added power up on the player 2021-08-21 20:39:48 +02:00
182631b2b7 repository cleanup 2021-08-21 14:46:00 +02:00
5cc9b16d59 repository cleanup 2021-08-21 14:45:14 +02:00
6224ed2779 repository cleanup 2021-08-21 14:42:38 +02:00
fc3a4efc5f repositoty cleanup 2021-08-21 14:41:01 +02:00
2be1e566b2 repository cleanup 2021-08-21 14:40:37 +02:00
017f691841 update readme.md 2021-08-21 12:54:41 +02:00
43c5ddcd1e Update readme.md 2021-08-21 12:53:47 +02:00
ef9f855785 repository cleanup 2021-08-21 12:50:57 +02:00
a70402ab5e repository cleanup 2021-08-21 11:12:21 +02:00
91bed82fd2 repository cleanup 2021-08-21 11:11:48 +02:00
84 changed files with 5612 additions and 1926 deletions

12
.gitignore vendored
View File

@@ -1,14 +1,12 @@
.vscode
bin bin
data/config.bin
data/score.bin
dll dll
docs
icon icon
media_work
releases releases
resources resources
scripts scripts
.DS_Store
todo.txt
data/config.bin
data/score.bin
*.opk *.opk
coffee_crisis *.DS_Store
.vscode

View File

@@ -1,6 +1,6 @@
# Coffee Crisis # Coffee Crisis
Coffe Crisis es un juego arcade que pondrá a prueba tus reflejos. Realizado entre el verano de 2020 y el invierno de 2021. Intenta conseguir todos los puntos que puedas con una sola vida y ayuda a Bal1 a defender la UPV ante la invasión de la cafeína. Coffe Crisis es un juego arcade que pondrá a prueba tus reflejos. Empezado el verano de 2020 y terminado el verano de 2021. Intenta conseguir todos los puntos que puedas con una sola vida y ayuda a Bal1 a defender la UPV ante la invasión de la cafeína durante 10 estresantes oleadas.
## Compilar ## Compilar
@@ -8,10 +8,10 @@ Para compilar el código se necesitan tener las librerías SDL instaladas en el
En Linux: En Linux:
```bash ```bash
sudo apt install lib-SDL2 g++ sudo apt install libsdl2-dev g++
``` ```
En macos es más facil instalarlas con [brew](https://brew.sh): En macOS se pueden instalar fácilmente con [brew](https://brew.sh):
```bash ```bash
brew install sdl2 g++ brew install sdl2 g++
``` ```
@@ -23,21 +23,31 @@ En Linux:
make linux make linux
``` ```
En macos: En macOS:
```bash ```bash
make macos make macos
``` ```
## Como ejecutar ## Como ejecutar
Para ejecutar el juego hay que escribir en la terminal la orden que se muestra a continuación.
En Linux:
```bash ```bash
./bin/coffee_crisis bin/coffee_crisis_linux
``` ```
En macOS:
```bash
bin/coffee_crisis_macos
```
En macOS tambien puedes hacer doble click sobre el archivo coffee_crisis_macos que hay en la carpeta bin
## Agradecimientos ## Agradecimientos
A los jailers y a la jail. Y entre ellos, a JailDoctor por estar siempre ahí apoyándonos/obligándonos a sacar un Jailgame más. A los jailers y a la jail. Y entre ellos, a JailDoctor por estar siempre ahí apoyándonos/obligándonos a sacar un Jailgame más.
Y por supuesto a ti por estar aquí. Y por supuesto a ti por estar aquí.
## License ## Licencia
Buscar una licencia para que quiera haga con el código lo que le de la gana, menos sacar beneficio económico... que si lo hacen me expliquen como. Usa el código para lo que quieras: aprender, reirte, curiosear... excepto para sacar beneficio económico. Si lo consigues, por favor avísame y vamos a medias.

1144
data/gamecontrollerdb.txt Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -1,9 +0,0 @@
[Desktop Entry]
Version=1.0
Type=Application
Name=Coffee Crisis
Comment=Coffee Crisis
Icon=icon
Exec=bin/coffee_crisis
Categories=games;Game;SDL;
Terminal=false

View File

@@ -1,7 +0,0 @@
#!/usr/bin/bash
mkdir -p bin
cd source
/opt/gcw0-toolchain/usr/bin/mipsel-linux-g++ -g -D_GCWZERO -O2 -I/opt/gcw0-toolchain/usr/mipsel-gcw0-linux-uclibc/sysroot/usr/include/SDL2 -D_GNU_SOURCE=1 -D_REENTRANT -lSDL2 -lSDL2_mixer -std=c++11 *.cpp -o ../bin/coffee_crisis
cd ..
/opt/gcw0-toolchain/usr/bin/mksquashfs ./default.gcw0.desktop ./icon.png ./bin ./data ./media coffee_crisis.opk -all-root -noappend -no-exports -no-xattrs

BIN
icon.png

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.0 KiB

BIN
media/.DS_Store vendored

Binary file not shown.

BIN
media/font/8bithud.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

194
media/font/8bithud.txt Normal file
View File

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

View File

Before

Width:  |  Height:  |  Size: 2.0 KiB

After

Width:  |  Height:  |  Size: 2.0 KiB

194
media/font/nokia.txt Normal file
View File

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

BIN
media/font/nokia2.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

194
media/font/nokia2.txt Normal file
View File

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

BIN
media/font/nokia_big2.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.6 KiB

194
media/font/nokia_big2.txt Normal file
View File

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

View File

Before

Width:  |  Height:  |  Size: 1.3 KiB

After

Width:  |  Height:  |  Size: 1.3 KiB

194
media/font/smb2.txt Normal file
View File

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

View File

Before

Width:  |  Height:  |  Size: 2.2 KiB

After

Width:  |  Height:  |  Size: 2.2 KiB

194
media/font/smb2_big.txt Normal file
View File

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

BIN
media/gfx/.DS_Store vendored

Binary file not shown.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 348 B

After

Width:  |  Height:  |  Size: 644 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.8 KiB

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.1 KiB

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 146 B

BIN
media/gfx/player1_body.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.4 KiB

BIN
media/gfx/player1_death.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

BIN
media/gfx/player1_head.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.0 KiB

View File

Before

Width:  |  Height:  |  Size: 785 B

After

Width:  |  Height:  |  Size: 785 B

BIN
media/gfx/player2_body.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.5 KiB

BIN
media/gfx/player2_death.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

BIN
media/gfx/player2_head.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.6 KiB

BIN
media/gfx/player2_legs.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 654 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 672 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.6 KiB

After

Width:  |  Height:  |  Size: 71 KiB

158
media/lang/ba_BA.txt Normal file
View File

@@ -0,0 +1,158 @@
## 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
Pantalla
## 39 - MARCADOR
PUNTS
## 40 - MARCADOR
MAX.PUNT.
## 41 - MARCADOR
MULT
## 42 - MARCADOR
PANTALLA
## 43 - PANTALLA DE GAME OVER
FI DEL JOC
## 44 - PANTALLA DE GAME OVER
ELS TEUS PUNTS:
## 45 - PANTALLA DE GAME OVER
REINTENTAR?
## 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
pantalla
## 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 - MENU DE OPCIONES
TECLAT
## 65 - MENU DE OPCIONES
MANDO
## 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:

158
media/lang/en_UK.txt Normal file
View File

@@ -0,0 +1,158 @@
## 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
Stage
## 39 - MARCADOR
SCORE
## 40 - MARCADOR
HI-SCORE
## 41 - MARCADOR
MULT
## 42 - MARCADOR
STAGE
## 43 - PANTALLA DE GAME OVER
GAME OVER
## 44 - PANTALLA DE GAME OVER
YOUR SCORE:
## 45 - PANTALLA DE GAME OVER
RETRY?
## 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 - MENU DE OPCIONES
KEYBOARD
## 65 - MENU DE OPCIONES
GAME CONTROLLER
## 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:

158
media/lang/es_ES.txt Normal file
View File

@@ -0,0 +1,158 @@
## 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
Fase
## 39 - MARCADOR
PUNTOS
## 40 - MARCADOR
MAX.PUNT.
## 41 - MARCADOR
MULT
## 42 - MARCADOR
FASE
## 43 - PANTALLA DE GAME OVER
FIN DE JUEGO
## 44 - PANTALLA DE GAME OVER
TU PUNTUACION:
## 45 - PANTALLA DE GAME OVER
REINTENTAR?
## 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 - MENU DE OPCIONES
TECLADO
## 65 - MENU DE OPCIONES
MANDO
## 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:

BIN
media/music/.DS_Store vendored

Binary file not shown.

View File

@@ -1,10 +0,0 @@
playing.ogg
ARCADE GOBLINS
https://soundimage.org/chiptunes-3/
title.ogg
ARCADE STORIES
https://soundimage.org/chiptunes-3/
intro.ogg
JailDoctor

View File

@@ -1,65 +0,0 @@
bullet.wav
Gun11.wav
http://www.themotionmonkey.co.uk/free-resources/retro-arcade-sounds/
balloon.wav
Impact3.wav
http://www.themotionmonkey.co.uk/free-resources/retro-arcade-sounds/
player_collision.wav
Impact5.wav
http://www.themotionmonkey.co.uk/free-resources/retro-arcade-sounds/
title.wav
Explosion2.wav
http://www.themotionmonkey.co.uk/free-resources/retro-arcade-sounds/
menu_select.wav
kenney_digitalaudio/powerUp2.ogg
www.kenney.nl
menu_move.wav
kenney_uiaudio/switch11.ogg
www.kenney.nl
hiscore.wav
kenney_digitalaudio/powerUp1.ogg
www.kenney.nl
itemdrop.wav
kenney_digitalaudio/PowerUp10.ogg
www.kenney.nl
itempickup.wav
kenney_digitalaudio/PowerUp7.ogg
www.kenney.nl
coffeeout.wav
kenney_digitalaudio/lowDown.ogg
www.kenney.nl
stage_change.wav
JailDoctor
menu_cancel.wav
kenney_digitalaudio/pepSound1.ogg
www.kenney.nl
bubble1.wav
JailDoctor
bubble2.wav
JailDoctor
bubble3.wav
JailDoctor
bubble4.wav
JailDoctor
clock.wav
kenney_digitalaudio/switch2.ogg
www.kenney.nl
powerball.wav
JailDoctor

BIN
source/.DS_Store vendored

Binary file not shown.

View File

@@ -603,7 +603,8 @@ void Balloon::disable()
void Balloon::pop() void Balloon::pop()
{ {
setPopping(true); setPopping(true);
mSprite->setAnimationCounter(0); mSprite->setAnimationCounter(0);
mSprite->disableRotate();
setTimeToLive(120); setTimeToLive(120);
setStop(true); setStop(true);
setStoppedTimer(2000); setStoppedTimer(2000);

View File

@@ -50,7 +50,7 @@ private:
float zoomW; // Zoom aplicado a la anchura float zoomW; // Zoom aplicado a la anchura
float zoomH; // Zoom aplicado a la altura float zoomH; // Zoom aplicado a la altura
float despX; // Desplazamiento de pixeles en el eje X antes de pintar el objeto con zoom float despX; // Desplazamiento de pixeles en el eje X antes de pintar el objeto con zoom
float despY; // idem float despY; // Desplazamiento de pixeles en el eje Y antes de pintar el objeto con zoom
// Vector con los valores de zoom para el ancho y alto del globo // Vector con los valores de zoom para el ancho y alto del globo
float w[MAX_BOUNCE] = {1.10f, 1.05f, 1.00f, 0.95f, 0.90f, 0.95f, 1.00f, 1.02f, 1.05f, 1.02f}; float w[MAX_BOUNCE] = {1.10f, 1.05f, 1.00f, 0.95f, 0.90f, 0.95f, 1.00f, 1.02f, 1.05f, 1.02f};

View File

@@ -5,7 +5,6 @@
Bullet::Bullet() Bullet::Bullet()
{ {
mSprite = new Sprite(); mSprite = new Sprite();
//init(0, 0, NO_KIND, nullptr, nullptr);
mKind = NO_KIND; mKind = NO_KIND;
} }
@@ -18,7 +17,7 @@ Bullet::~Bullet()
} }
// Iniciador // Iniciador
void Bullet::init(int x, int y, int kind, LTexture *texture, SDL_Renderer *renderer) void Bullet::init(int x, int y, int kind, bool poweredUp, int owner, LTexture *texture, SDL_Renderer *renderer)
{ {
// Posición inicial del objeto // Posición inicial del objeto
mPosX = x; mPosX = x;
@@ -34,6 +33,9 @@ void Bullet::init(int x, int y, int kind, LTexture *texture, SDL_Renderer *rende
// Tipo de bala // Tipo de bala
mKind = kind; mKind = kind;
// Identificador del dueño del objeto
mOwner = owner;
// Textura con los gráficos del objeto // Textura con los gráficos del objeto
mSprite->setTexture(texture); mSprite->setTexture(texture);
@@ -56,7 +58,10 @@ void Bullet::init(int x, int y, int kind, LTexture *texture, SDL_Renderer *rende
mVelX = 0; mVelX = 0;
// Rectangulo con los gráficos del objeto // Rectangulo con los gráficos del objeto
mSprite->setSpriteClip(0 * mWidth, 0, mSprite->getWidth(), mSprite->getHeight()); if (!poweredUp)
mSprite->setSpriteClip(0 * mWidth, 0, mSprite->getWidth(), mSprite->getHeight());
else
mSprite->setSpriteClip((0 + 3) * mWidth, 0, mSprite->getWidth(), mSprite->getHeight());
break; break;
case BULLET_LEFT: case BULLET_LEFT:
@@ -64,7 +69,10 @@ void Bullet::init(int x, int y, int kind, LTexture *texture, SDL_Renderer *rende
mVelX = -2; mVelX = -2;
// Rectangulo con los gráficos del objeto // Rectangulo con los gráficos del objeto
mSprite->setSpriteClip(1 * mWidth, 0, mSprite->getWidth(), mSprite->getHeight()); if (!poweredUp)
mSprite->setSpriteClip(1 * mWidth, 0, mSprite->getWidth(), mSprite->getHeight());
else
mSprite->setSpriteClip((1 + 3) * mWidth, 0, mSprite->getWidth(), mSprite->getHeight());
break; break;
case BULLET_RIGHT: case BULLET_RIGHT:
@@ -72,7 +80,10 @@ void Bullet::init(int x, int y, int kind, LTexture *texture, SDL_Renderer *rende
mVelX = 2; mVelX = 2;
// Rectangulo con los gráficos del objeto // Rectangulo con los gráficos del objeto
mSprite->setSpriteClip(2 * mWidth, 0, mSprite->getWidth(), mSprite->getHeight()); if (!poweredUp)
mSprite->setSpriteClip(2 * mWidth, 0, mSprite->getWidth(), mSprite->getHeight());
else
mSprite->setSpriteClip((2 + 3) * mWidth, 0, mSprite->getWidth(), mSprite->getHeight());
break; break;
default: default:
@@ -149,7 +160,7 @@ void Bullet::testMove()
// Deshabilita el objeto // Deshabilita el objeto
void Bullet::erase() void Bullet::erase()
{ {
init(0, 0, 0, nullptr, nullptr); init(0, 0, 0, false, -1, nullptr, nullptr);
} }
// Comprueba si el objeto está activo // Comprueba si el objeto está activo
@@ -201,6 +212,12 @@ int Bullet::getKind()
return mKind; return mKind;
} }
// Obtiene el valor de la variable
int Bullet::getOwner()
{
return mOwner;
}
// Obtiene el circulo de colisión // Obtiene el circulo de colisión
circle_t &Bullet::getCollider() circle_t &Bullet::getCollider()
{ {

View File

@@ -8,6 +8,21 @@
// Clase bala // Clase bala
class Bullet 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
// Alinea el circulo de colisión con el objeto
void shiftColliders();
public: public:
// Constructor // Constructor
Bullet(); Bullet();
@@ -16,11 +31,11 @@ public:
~Bullet(); ~Bullet();
// Iniciador // Iniciador
void init(int x, int y, int kind, LTexture* texture, SDL_Renderer *renderer); void init(int x, int y, int kind, bool poweredUp, int owner, LTexture *texture, SDL_Renderer *renderer);
// Pinta el objeto en pantalla // Pinta el objeto en pantalla
void render(); void render();
// Actualiza la posición y estado del objeto // Actualiza la posición y estado del objeto
Uint8 move(); Uint8 move();
@@ -48,33 +63,11 @@ public:
// Obtiene el valor de la variable // Obtiene el valor de la variable
int getKind(); int getKind();
// Obtiene el valor de la variable
int getOwner();
// Obtiene el circulo de colisión // Obtiene el circulo de colisión
circle_t &getCollider(); circle_t &getCollider();
private:
// Posición X/Y del objeto
int mPosX;
int mPosY;
// Alto y ancho el objeto
Uint8 mWidth;
Uint8 mHeight;
// Velocidad del objeto
int mVelX;
int mVelY;
// Tipo de objeto
int mKind;
// Sprite con los graficos y métodos de pintado
Sprite *mSprite;
// Balloon's collision circle
circle_t mCollider;
// Alinea el circulo de colisión con el objeto
void shiftColliders();
}; };
#endif #endif

View File

@@ -9,7 +9,7 @@
// Textos // Textos
#define WINDOW_CAPTION "Coffee Crisis" #define WINDOW_CAPTION "Coffee Crisis"
#define TEXT_COPYRIGHT "@2020,2021 JAILDESIGNER (V1.5)" #define TEXT_COPYRIGHT "@2020,2021 JailDesigner (v2.0)"
// Recursos // Recursos
#define BINFILE_SCORE 0 #define BINFILE_SCORE 0
@@ -134,8 +134,16 @@ const int SCREEN_THIRD_QUARTER_Y = (SCREEN_HEIGHT / 4) * 3;
#define PLAYER_ANIMATION_BODY_WALKING_STOP 4 #define PLAYER_ANIMATION_BODY_WALKING_STOP 4
#define PLAYER_ANIMATION_BODY_FIRING_UP 5 #define PLAYER_ANIMATION_BODY_FIRING_UP 5
#define PLAYER_ANIMATION_HEAD_WALKING_LEFT 0
#define PLAYER_ANIMATION_HEAD_FIRING_LEFT 1
#define PLAYER_ANIMATION_HEAD_WALKING_RIGHT 2
#define PLAYER_ANIMATION_HEAD_FIRING_RIGHT 3
#define PLAYER_ANIMATION_HEAD_WALKING_STOP 4
#define PLAYER_ANIMATION_HEAD_FIRING_UP 5
// Variables del jugador // Variables del jugador
#define PLAYER_INVULNERABLE_COUNTER 200 #define PLAYER_INVULNERABLE_COUNTER 200
#define PLAYER_POWERUP_COUNTER 1500
// Secciones del programa // Secciones del programa
#define PROG_SECTION_LOGO 0 #define PROG_SECTION_LOGO 0
@@ -145,9 +153,10 @@ const int SCREEN_THIRD_QUARTER_Y = (SCREEN_HEIGHT / 4) * 3;
#define PROG_SECTION_QUIT 4 #define PROG_SECTION_QUIT 4
// Subsecciones // Subsecciones
#define GAME_SECTION_PLAY 0 #define GAME_SECTION_PLAY_1P 0
#define GAME_SECTION_PAUSE 1 #define GAME_SECTION_PLAY_2P 1
#define GAME_SECTION_GAMEOVER 2 #define GAME_SECTION_PAUSE 2
#define GAME_SECTION_GAMEOVER 3
#define TITLE_SECTION_1 3 #define TITLE_SECTION_1 3
#define TITLE_SECTION_2 4 #define TITLE_SECTION_2 4
#define TITLE_SECTION_3 5 #define TITLE_SECTION_3 5
@@ -260,6 +269,7 @@ const int MULTIPLIER_NUMBER_Y = SCREEN_HEIGHT - (2 * BLOCK) + 2;
// PowerBall // PowerBall
#define POWERBALL_SCREENPOWER_MINIMUM 10 #define POWERBALL_SCREENPOWER_MINIMUM 10
#define POWERBALL_COUNTER 8
// Tipos de bala // Tipos de bala
#define BULLET_UP 1 #define BULLET_UP 1
@@ -276,9 +286,19 @@ const int MULTIPLIER_NUMBER_Y = SCREEN_HEIGHT - (2 * BLOCK) + 2;
#define ITEM_CLOCK 4 #define ITEM_CLOCK 4
#define ITEM_COFFEE 5 #define ITEM_COFFEE 5
#define ITEM_POWER_BALL 6 #define ITEM_POWER_BALL 6
#define ITEM_COFFEE_MACHINE 7
// Porcentaje de aparición de los objetos
#define ITEM_POINTS_1_DISK_ODDS 10
#define ITEM_POINTS_2_GAVINA_ODDS 6
#define ITEM_POINTS_3_PACMAR_ODDS 3
#define ITEM_CLOCK_ODDS 5
#define ITEM_COFFEE_ODDS 5
#define ITEM_POWER_BALL_ODDS 0
#define ITEM_COFFEE_MACHINE_ODDS 4
// Cantidad de objetos simultaneos // Cantidad de objetos simultaneos
#define MAX_ITEMS 5 #define MAX_ITEMS 10
// Valores para las variables asociadas a los objetos // Valores para las variables asociadas a los objetos
#define REMAINING_EXPLOSIONS 3 #define REMAINING_EXPLOSIONS 3
@@ -315,6 +335,7 @@ const int MULTIPLIER_NUMBER_Y = SCREEN_HEIGHT - (2 * BLOCK) + 2;
#define INSTRUCTIONS_COUNTER 600 #define INSTRUCTIONS_COUNTER 600
#define DEATH_COUNTER 350 #define DEATH_COUNTER 350
#define SHAKE_COUNTER 10 #define SHAKE_COUNTER 10
#define HELP_COUNTER 1000
// Colores // Colores
const color_t bgColor = {0x27, 0x27, 0x36}; const color_t bgColor = {0x27, 0x27, 0x36};
@@ -325,5 +346,13 @@ const color_t shdwTxtColor = {0x43, 0x43, 0x4F};
#define NUMBER_OF_ENEMY_FORMATIONS 100 #define NUMBER_OF_ENEMY_FORMATIONS 100
#define MAX_NUMBER_OF_ENEMIES_IN_A_FORMATION 50 #define MAX_NUMBER_OF_ENEMIES_IN_A_FORMATION 50
// Dificultad del juego
#define DIFFICULTY_EASY 0
#define DIFFICULTY_NORMAL 1
#define DIFFICULTY_HARD 2
// Tipo de filtro
#define FILTER_NEAREST 0
#define FILTER_LINEAL 1
#endif #endif

View File

@@ -2,6 +2,7 @@
#include "utils.h" #include "utils.h"
#include "director.h" #include "director.h"
#include <iostream> #include <iostream>
#include <string>
#ifdef __MIPSEL__ #ifdef __MIPSEL__
#include <sys/stat.h> #include <sys/stat.h>
#include <dirent.h> #include <dirent.h>
@@ -10,14 +11,36 @@
// Constructor // Constructor
Director::Director(std::string path) Director::Director(std::string path)
{ {
// Crea los objetos // Inicializa la ruta
mInput = new Input();
mOptions = new options_t;
// Inicializa variables
setExecutablePath(path); setExecutablePath(path);
// Establece la lista de ficheros
setFileList(); setFileList();
checkFileList();
// Si falta algún fichero no inicies el programa
Uint8 section = PROG_SECTION_LOGO;
if (!checkFileList())
section = PROG_SECTION_QUIT;
// Inicializa el objeto de idioma
mLang = new Lang(mFileList);
// Crea el puntero a la estructura y carga el fichero de configuración
mOptions = new options_t;
if (!loadConfigFile())
{
mOptions->fullScreenMode = 0;
mOptions->windowSize = 3;
mOptions->language = en_UK;
mOptions->difficulty = DIFFICULTY_NORMAL;
mOptions->input[0].deviceType = INPUT_USE_KEYBOARD;
mOptions->input[1].deviceType = INPUT_USE_GAMECONTROLLER;
mOptions->filter = FILTER_NEAREST;
mOptions->vSync = true;
}
// Crea los objetos
mInput = new Input(mFileList[53]);
// Inicializa SDL // Inicializa SDL
initSDL(); initSDL();
@@ -25,6 +48,11 @@ Director::Director(std::string path)
// Inicializa JailAudio // Inicializa JailAudio
initJailAudio(); initJailAudio();
// Aplica las opciones
SDL_SetWindowFullscreen(mWindow, mOptions->fullScreenMode);
SDL_SetWindowSize(mWindow, SCREEN_WIDTH * mOptions->windowSize, SCREEN_HEIGHT * mOptions->windowSize);
mLang->setLang(mOptions->language);
#ifdef __MIPSEL__ #ifdef __MIPSEL__
DIR *dir = opendir("/media/data/local/home/.coffee_crisis"); DIR *dir = opendir("/media/data/local/home/.coffee_crisis");
if (dir) if (dir)
@@ -38,7 +66,7 @@ Director::Director(std::string path)
#endif #endif
// Inicializa el resto de variables // Inicializa el resto de variables
init(); init(section);
} }
Director::~Director() Director::~Director()
@@ -48,6 +76,9 @@ Director::~Director()
delete mInput; delete mInput;
mInput = nullptr; mInput = nullptr;
delete mLang;
mLang = nullptr;
delete mOptions; delete mOptions;
mOptions = nullptr; mOptions = nullptr;
@@ -60,24 +91,16 @@ Director::~Director()
} }
// Inicia las variables necesarias para arrancar el programa // Inicia las variables necesarias para arrancar el programa
void Director::init() void Director::init(Uint8 name)
{ {
// Carga el fichero de configuración
if (!loadConfigFile())
{
mOptions->fullScreenMode = 0;
mOptions->windowSize = 3;
mOptions->language = en_UK;
}
// Sección // Sección
mSection.name = PROG_SECTION_LOGO; mSection.name = name;
mSection.subsection = 0; mSection.subsection = 0;
// Textos // Textos
initTextStrings(mTextStrings, mOptions->language); mLang->setLang(mOptions->language);
// Teclado // Controles
mInput->bindKey(INPUT_UP, SDL_SCANCODE_UP); mInput->bindKey(INPUT_UP, SDL_SCANCODE_UP);
mInput->bindKey(INPUT_DOWN, SDL_SCANCODE_DOWN); mInput->bindKey(INPUT_DOWN, SDL_SCANCODE_DOWN);
mInput->bindKey(INPUT_LEFT, SDL_SCANCODE_LEFT); mInput->bindKey(INPUT_LEFT, SDL_SCANCODE_LEFT);
@@ -93,8 +116,20 @@ void Director::init()
mInput->bindKey(INPUT_BUTTON_2, SDL_SCANCODE_W); mInput->bindKey(INPUT_BUTTON_2, SDL_SCANCODE_W);
mInput->bindKey(INPUT_BUTTON_3, SDL_SCANCODE_E); mInput->bindKey(INPUT_BUTTON_3, SDL_SCANCODE_E);
#endif #endif
mInput->bindKey(INPUT_BUTTON_4, SDL_SCANCODE_ESCAPE); // PAUSE mInput->bindKey(INPUT_BUTTON_PAUSE, SDL_SCANCODE_ESCAPE); // PAUSE
mInput->bindKey(INPUT_BUTTON_5, SDL_SCANCODE_ESCAPE); // ESCAPE mInput->bindKey(INPUT_BUTTON_ESCAPE, SDL_SCANCODE_ESCAPE); // ESCAPE
mInput->bindGameControllerButton(INPUT_UP, SDL_CONTROLLER_BUTTON_DPAD_UP);
mInput->bindGameControllerButton(INPUT_DOWN, SDL_CONTROLLER_BUTTON_DPAD_DOWN);
mInput->bindGameControllerButton(INPUT_LEFT, SDL_CONTROLLER_BUTTON_DPAD_LEFT);
mInput->bindGameControllerButton(INPUT_RIGHT, SDL_CONTROLLER_BUTTON_DPAD_RIGHT);
mInput->bindGameControllerButton(INPUT_ACCEPT, SDL_CONTROLLER_BUTTON_B);
mInput->bindGameControllerButton(INPUT_CANCEL, SDL_CONTROLLER_BUTTON_A);
mInput->bindGameControllerButton(INPUT_BUTTON_1, SDL_CONTROLLER_BUTTON_X);
mInput->bindGameControllerButton(INPUT_BUTTON_2, SDL_CONTROLLER_BUTTON_Y);
mInput->bindGameControllerButton(INPUT_BUTTON_3, SDL_CONTROLLER_BUTTON_B);
mInput->bindGameControllerButton(INPUT_BUTTON_PAUSE, SDL_CONTROLLER_BUTTON_GUIDE); // PAUSE
mInput->bindGameControllerButton(INPUT_BUTTON_ESCAPE, SDL_CONTROLLER_BUTTON_GUIDE); // ESCAPE
} }
// Inicializa JailAudio // Inicializa JailAudio
@@ -106,19 +141,23 @@ void Director::initJailAudio()
// Arranca SDL y crea la ventana // Arranca SDL y crea la ventana
bool Director::initSDL() bool Director::initSDL()
{ {
// Indicador de inicialización // Indicador de éxito
bool success = true; bool success = true;
// Inicializa SDL // Inicializa SDL
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK | SDL_INIT_AUDIO | SDL_INIT_HAPTIC) < 0) //if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_GAMECONTROLLER | SDL_INIT_AUDIO) < 0)
if (SDL_Init(SDL_INIT_EVERYTHING) < 0)
{ {
printf("SDL could not initialize!\nSDL Error: %s\n", SDL_GetError()); printf("SDL could not initialize!\nSDL Error: %s\n", SDL_GetError());
success = false; success = false;
} }
else else
{ {
// Inicia el generador de numeros aleatorios
std::srand(static_cast<unsigned int>(SDL_GetTicks()));
// Establece el filtro de la textura a nearest // Establece el filtro de la textura a nearest
if (!SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "0")) if (!SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, std::to_string(mOptions->filter).c_str()))
{ {
printf("Warning: Nearest texture filtering not enabled!\n"); printf("Warning: Nearest texture filtering not enabled!\n");
} }
@@ -132,8 +171,12 @@ bool Director::initSDL()
} }
else else
{ {
// Crea un renderizador para la ventana con vsync // Crea un renderizador para la ventana. El vsync se activa en funcion de las opciones
mRenderer = SDL_CreateRenderer(mWindow, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if (mOptions->vSync)
mRenderer = SDL_CreateRenderer(mWindow, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
else
mRenderer = SDL_CreateRenderer(mWindow, -1, SDL_RENDERER_ACCELERATED);
if (mRenderer == NULL) if (mRenderer == NULL)
{ {
printf("Renderer could not be created!\nSDL Error: %s\n", SDL_GetError()); printf("Renderer could not be created!\nSDL Error: %s\n", SDL_GetError());
@@ -160,7 +203,11 @@ bool Director::initSDL()
// Crea el indice de ficheros // Crea el indice de ficheros
void Director::setFileList() void Director::setFileList()
{ {
// Ficheros binarios // Inicializa el vector
for (int i = 0; i < MAX_FILE_LIST; i++)
mFileList[i] = "";
// Ficheros binarios
#ifdef __MIPSEL__ #ifdef __MIPSEL__
mFileList[0] = "/media/data/local/home/.coffee_crisis/score.bin"; mFileList[0] = "/media/data/local/home/.coffee_crisis/score.bin";
mFileList[1] = "/media/data/local/home/.coffee_crisis/demo.bin"; mFileList[1] = "/media/data/local/home/.coffee_crisis/demo.bin";
@@ -199,93 +246,97 @@ void Director::setFileList()
// Texturas // Texturas
mFileList[24] = mExecutablePath + "/" + "../media/gfx/balloon.png"; mFileList[24] = mExecutablePath + "/" + "../media/gfx/balloon.png";
mFileList[25] = mExecutablePath + "/" + "../media/gfx/bullet.png"; mFileList[25] = mExecutablePath + "/" + "../media/gfx/bullet.png";
mFileList[26] = mExecutablePath + "/" + "../media/gfx/font_black_x2.png";
mFileList[27] = mExecutablePath + "/" + "../media/gfx/font_black.png";
mFileList[28] = mExecutablePath + "/" + "../media/gfx/font_nokia.png";
mFileList[29] = mExecutablePath + "/" + "../media/gfx/font_white_x2.png";
mFileList[30] = mExecutablePath + "/" + "../media/gfx/font_white.png";
mFileList[31] = mExecutablePath + "/" + "../media/gfx/game_bg.png"; mFileList[31] = mExecutablePath + "/" + "../media/gfx/game_bg.png";
mFileList[32] = mExecutablePath + "/" + "../media/gfx/game_text.png"; mFileList[32] = mExecutablePath + "/" + "../media/gfx/game_text.png";
mFileList[33] = mExecutablePath + "/" + "../media/gfx/intro.png"; mFileList[33] = mExecutablePath + "/" + "../media/gfx/intro.png";
mFileList[34] = mExecutablePath + "/" + "../media/gfx/items.png"; mFileList[34] = mExecutablePath + "/" + "../media/gfx/items.png";
mFileList[35] = mExecutablePath + "/" + "../media/gfx/logo.png"; mFileList[35] = mExecutablePath + "/" + "../media/gfx/logo.png";
mFileList[36] = mExecutablePath + "/" + "../media/gfx/menu.png"; mFileList[37] = mExecutablePath + "/" + "../media/gfx/player1_body.png";
mFileList[37] = mExecutablePath + "/" + "../media/gfx/player_body.png"; mFileList[38] = mExecutablePath + "/" + "../media/gfx/player1_death.png";
mFileList[38] = mExecutablePath + "/" + "../media/gfx/player_death.png"; mFileList[39] = mExecutablePath + "/" + "../media/gfx/player1_legs.png";
mFileList[39] = mExecutablePath + "/" + "../media/gfx/player_legs.png";
mFileList[40] = mExecutablePath + "/" + "../media/gfx/title.png"; mFileList[40] = mExecutablePath + "/" + "../media/gfx/title.png";
mFileList[41] = mExecutablePath + "/" + "../media/gfx/player1_head.png";
mFileList[42] = mExecutablePath + "/" + "../media/gfx/player2_body.png";
mFileList[43] = mExecutablePath + "/" + "../media/gfx/player2_death.png";
mFileList[44] = mExecutablePath + "/" + "../media/gfx/player2_legs.png";
mFileList[45] = mExecutablePath + "/" + "../media/gfx/player2_head.png";
// Fuentes
mFileList[27] = mExecutablePath + "/" + "../media/font/8bithud.png";
mFileList[46] = mExecutablePath + "/" + "../media/font/8bithud.txt";
mFileList[28] = mExecutablePath + "/" + "../media/font/nokia.png";
mFileList[54] = mExecutablePath + "/" + "../media/font/nokia_big2.png";
mFileList[52] = mExecutablePath + "/" + "../media/font/nokia.txt";
mFileList[56] = mExecutablePath + "/" + "../media/font/nokia2.png";
mFileList[57] = mExecutablePath + "/" + "../media/font/nokia2.txt";
mFileList[55] = mExecutablePath + "/" + "../media/font/nokia_big2.txt";
mFileList[29] = mExecutablePath + "/" + "../media/font/smb2_big.png";
mFileList[47] = mExecutablePath + "/" + "../media/font/smb2_big.txt";
mFileList[30] = mExecutablePath + "/" + "../media/font/smb2.png";
mFileList[48] = mExecutablePath + "/" + "../media/font/smb2.txt";
// Textos
mFileList[49] = mExecutablePath + "/" + "../media/lang/es_ES.txt";
mFileList[50] = mExecutablePath + "/" + "../media/lang/en_UK.txt";
mFileList[51] = mExecutablePath + "/" + "../media/lang/ba_BA.txt";
// DATA
mFileList[53] = mExecutablePath + "/" + "../data/gamecontrollerdb.txt";
}
// Comprueba los ficheros del vector de ficheros que coinciden con una ruta dada
bool Director::checkFolder(std::string name, std::string path)
{
bool success = true;
std::string p;
std::string filename;
SDL_RWops *file;
// Comprueba los ficheros de la carpeta
printf("\n>> %s FILES\n", name.c_str());
for (int i = 3; i < MAX_FILE_LIST; i++)
{
if (mFileList[i].find(path.c_str()) != std::string::npos)
{
p = mFileList[i].c_str();
filename = p.substr(p.find_last_of("\\/") + 1);
file = SDL_RWFromFile(p.c_str(), "r+b");
if (file != NULL)
{
printf("Checking file %-20s [OK]\n", filename.c_str());
}
else
{
printf("Checking file %-20s [ERROR]\n", filename.c_str());
success = false;
break;
}
SDL_RWclose(file);
}
}
return success;
} }
// Comprueba que todos los ficheros existen // Comprueba que todos los ficheros existen
bool Director::checkFileList() bool Director::checkFileList()
{ {
bool success = true; bool success = true;
/*std::string p; printf("Checking files...\n");
std::string filename;
SDL_RWops *file;
// Comprueba los ficheros de musica
printf("\n>> MUSIC FILES\n");
if (success) if (success)
for (int i = 0; i < TOTAL_MUSIC; i++) success &= checkFolder("MUSIC", "/media/music/");
{
p = mMusic[i].file.c_str();
filename = p.substr(p.find_last_of("\\/") + 1);
file = SDL_RWFromFile(p.c_str(), "r+b");
if (file != NULL)
{
printf("Checking file %-20s [OK]\n", filename.c_str());
}
else
{
printf("Checking file %-20s [ERROR]\n", filename.c_str());
success = false;
break;
}
SDL_RWclose(file);
}
// Comprueba los ficheros de sonidos
printf("\n>> SOUND FILES\n");
if (success) if (success)
for (int i = 0; i < TOTAL_SOUND; i++) success &= checkFolder("SOUND", "/media/sound/");
{
p = mSound[i].file.c_str();
filename = p.substr(p.find_last_of("\\/") + 1);
file = SDL_RWFromFile(p.c_str(), "r+b");
if (file != NULL)
{
printf("Checking file %-20s [OK]\n", filename.c_str());
}
else
{
printf("Checking file %-20s [ERROR]\n", filename.c_str());
success = false;
break;
}
SDL_RWclose(file);
}
// Comprueba los ficheros con texturas
printf("\n>> TEXTURE FILES\n");
if (success) if (success)
for (int i = 0; i < TOTAL_TEXTURE; i++) success &= checkFolder("BITMAP", "/media/gfx/");
{
p = mTexture[i].file.c_str(); if (success)
filename = p.substr(p.find_last_of("\\/") + 1); success &= checkFolder("FONT", "/media/font/");
file = SDL_RWFromFile(p.c_str(), "r+b");
if (file != NULL) if (success)
{ success &= checkFolder("LANG", "/media/lang/");
printf("Checking file %-20s [OK]\n", filename.c_str());
}
else
{
printf("Checking file %-20s [ERROR]\n", filename.c_str());
success = false;
break;
}
SDL_RWclose(file);
}
// Resultado // Resultado
if (success) if (success)
@@ -293,7 +344,6 @@ bool Director::checkFileList()
else else
printf("\n** A file is missing. Exiting.\n\n"); printf("\n** A file is missing. Exiting.\n\n");
*/
return success; return success;
} }
@@ -304,6 +354,11 @@ bool Director::loadConfigFile()
mOptions->fullScreenMode = 0; mOptions->fullScreenMode = 0;
mOptions->windowSize = 3; mOptions->windowSize = 3;
mOptions->language = en_UK; mOptions->language = en_UK;
mOptions->difficulty = DIFFICULTY_NORMAL;
mOptions->input[0].deviceType = INPUT_USE_KEYBOARD;
mOptions->input[1].deviceType = INPUT_USE_GAMECONTROLLER;
mOptions->filter = FILTER_NEAREST;
mOptions->vSync = true;
// Indicador de éxito en la carga // Indicador de éxito en la carga
bool success = true; bool success = true;
@@ -327,6 +382,11 @@ bool Director::loadConfigFile()
SDL_RWwrite(file, &mOptions->fullScreenMode, sizeof(mOptions->fullScreenMode), 1); SDL_RWwrite(file, &mOptions->fullScreenMode, sizeof(mOptions->fullScreenMode), 1);
SDL_RWwrite(file, &mOptions->windowSize, sizeof(mOptions->windowSize), 1); SDL_RWwrite(file, &mOptions->windowSize, sizeof(mOptions->windowSize), 1);
SDL_RWwrite(file, &mOptions->language, sizeof(mOptions->language), 1); SDL_RWwrite(file, &mOptions->language, sizeof(mOptions->language), 1);
SDL_RWwrite(file, &mOptions->difficulty, sizeof(mOptions->difficulty), 1);
SDL_RWwrite(file, &mOptions->input[0].deviceType, sizeof(mOptions->input[0].deviceType), 1);
SDL_RWwrite(file, &mOptions->input[1].deviceType, sizeof(mOptions->input[1].deviceType), 1);
SDL_RWwrite(file, &mOptions->filter, sizeof(mOptions->filter), 1);
SDL_RWwrite(file, &mOptions->vSync, sizeof(mOptions->vSync), 1);
// Cierra el fichero // Cierra el fichero
SDL_RWclose(file); SDL_RWclose(file);
@@ -345,6 +405,11 @@ bool Director::loadConfigFile()
SDL_RWread(file, &mOptions->fullScreenMode, sizeof(mOptions->fullScreenMode), 1); SDL_RWread(file, &mOptions->fullScreenMode, sizeof(mOptions->fullScreenMode), 1);
SDL_RWread(file, &mOptions->windowSize, sizeof(mOptions->windowSize), 1); SDL_RWread(file, &mOptions->windowSize, sizeof(mOptions->windowSize), 1);
SDL_RWread(file, &mOptions->language, sizeof(mOptions->language), 1); SDL_RWread(file, &mOptions->language, sizeof(mOptions->language), 1);
SDL_RWread(file, &mOptions->difficulty, sizeof(mOptions->difficulty), 1);
SDL_RWread(file, &mOptions->input[0].deviceType, sizeof(mOptions->input[0].deviceType), 1);
SDL_RWread(file, &mOptions->input[1].deviceType, sizeof(mOptions->input[1].deviceType), 1);
SDL_RWread(file, &mOptions->filter, sizeof(mOptions->filter), 1);
SDL_RWread(file, &mOptions->vSync, sizeof(mOptions->vSync), 1);
// Normaliza los valores // Normaliza los valores
if (!((mOptions->fullScreenMode == 0) || if (!((mOptions->fullScreenMode == 0) ||
@@ -356,11 +421,6 @@ bool Director::loadConfigFile()
if ((mOptions->language < 0) || (mOptions->language > MAX_LANGUAGES)) if ((mOptions->language < 0) || (mOptions->language > MAX_LANGUAGES))
mOptions->language = en_UK; mOptions->language = en_UK;
// Aplica las opciones
SDL_SetWindowFullscreen(mWindow, mOptions->fullScreenMode);
SDL_SetWindowSize(mWindow, SCREEN_WIDTH * mOptions->windowSize, SCREEN_HEIGHT * mOptions->windowSize);
initTextStrings(mTextStrings, mOptions->language);
// Cierra el fichero // Cierra el fichero
SDL_RWclose(file); SDL_RWclose(file);
} }
@@ -378,9 +438,14 @@ bool Director::saveConfigFile()
if (file != NULL) if (file != NULL)
{ {
// Guarda los datos // Guarda los datos
SDL_RWwrite(file, &mOptions->fullScreenMode, sizeof(Uint32), 1); SDL_RWwrite(file, &mOptions->fullScreenMode, sizeof(mOptions->fullScreenMode), 1);
SDL_RWwrite(file, &mOptions->windowSize, sizeof(Uint8), 1); SDL_RWwrite(file, &mOptions->windowSize, sizeof(mOptions->windowSize), 1);
SDL_RWwrite(file, &mOptions->language, sizeof(Uint8), 1); SDL_RWwrite(file, &mOptions->language, sizeof(mOptions->language), 1);
SDL_RWwrite(file, &mOptions->difficulty, sizeof(mOptions->difficulty), 1);
SDL_RWwrite(file, &mOptions->input[0].deviceType, sizeof(mOptions->input[0].deviceType), 1);
SDL_RWwrite(file, &mOptions->input[1].deviceType, sizeof(mOptions->input[1].deviceType), 1);
SDL_RWwrite(file, &mOptions->filter, sizeof(mOptions->filter), 1);
SDL_RWwrite(file, &mOptions->vSync, sizeof(mOptions->vSync), 1);
printf("Writing file %s\n", filename.c_str()); printf("Writing file %s\n", filename.c_str());
@@ -427,21 +492,24 @@ void Director::runLogo()
void Director::runIntro() void Director::runIntro()
{ {
mIntro = new Intro(mRenderer, mFileList, mTextStrings); mIntro = new Intro(mRenderer, mFileList, mLang);
setSection(mIntro->run()); setSection(mIntro->run());
delete mIntro; delete mIntro;
} }
void Director::runTitle() void Director::runTitle()
{ {
mTitle = new Title(mWindow, mRenderer, mInput, mFileList, mOptions, mTextStrings); mTitle = new Title(mWindow, mRenderer, mInput, mFileList, mOptions, mLang);
setSection(mTitle->run(mSection.subsection)); setSection(mTitle->run(mSection.subsection));
delete mTitle; delete mTitle;
} }
void Director::runGame() void Director::runGame()
{ {
mGame = new Game(mRenderer, mFileList, mTextStrings, mInput, false); if (mSection.subsection == GAME_SECTION_PLAY_1P)
mGame = new Game(1, mRenderer, mFileList, mLang, mInput, false, mOptions);
if (mSection.subsection == GAME_SECTION_PLAY_2P)
mGame = new Game(2, mRenderer, mFileList, mLang, mInput, false, mOptions);
setSection(mGame->run()); setSection(mGame->run());
delete mGame; delete mGame;
} }

View File

@@ -9,7 +9,7 @@
#include "coffeedrop.h" #include "coffeedrop.h"
#include "item.h" #include "item.h"
#include "text.h" #include "text.h"
#include "text2.h" #include "writer.h"
#include "menu.h" #include "menu.h"
#include "const.h" #include "const.h"
#include "jail_audio.h" #include "jail_audio.h"
@@ -20,11 +20,13 @@
#include "game.h" #include "game.h"
#include "input.h" #include "input.h"
#include "fade.h" #include "fade.h"
#include <math.h> //#include <math.h>
#ifndef DIRECTOR_H #ifndef DIRECTOR_H
#define DIRECTOR_H #define DIRECTOR_H
#define MAX_FILE_LIST 100
// Director // Director
class Director class Director
{ {
@@ -32,16 +34,15 @@ private:
SDL_Window *mWindow; // La ventana donde dibujamos SDL_Window *mWindow; // La ventana donde dibujamos
SDL_Renderer *mRenderer; // El renderizador de la ventana SDL_Renderer *mRenderer; // El renderizador de la ventana
Input *mInput;
Logo *mLogo; // Objeto para la sección del logo Logo *mLogo; // Objeto para la sección del logo
Intro *mIntro; // Objeto para la sección de la intro Intro *mIntro; // Objeto para la sección de la intro
Title *mTitle; // Objeto para la sección del titulo y el menu de opciones Title *mTitle; // Objeto para la sección del titulo y el menu de opciones
Game *mGame; // Objeto para la sección del juego Game *mGame; // Objeto para la sección del juego
Input *mInput; // Objeto Input para gestionar las entradas
Lang *mLang; // Objeto para gestionar los textos en diferentes idiomas
std::string mFileList[100]; // Vector con las rutas a los ficheros de recursos std::string mFileList[MAX_FILE_LIST]; // Vector con las rutas a los ficheros de recursos
struct options_t *mOptions; // Variable con todas las opciones del programa struct options_t *mOptions; // Variable con todas las opciones del programa
std::string mTextStrings[MAX_TEXT_STRINGS]; // Vector con los textos del juego
std::string mExecutablePath; // Path del ejecutable std::string mExecutablePath; // Path del ejecutable
section_t mSection; // Sección y subsección actual del programa; section_t mSection; // Sección y subsección actual del programa;
@@ -49,9 +50,6 @@ private:
// Inicializa jail_audio // Inicializa jail_audio
void initJailAudio(); void initJailAudio();
// Inicializa los textos del juego en el idioma seleccionado
//void initTextStrings(Uint8 lang);
// Arranca SDL y crea la ventana // Arranca SDL y crea la ventana
bool initSDL(); bool initSDL();
@@ -79,14 +77,21 @@ private:
// Establece el valor de la variable // Establece el valor de la variable
void setSection(section_t section); void setSection(section_t section);
// Ejecuta la seccion de juego con el logo
void runLogo(); void runLogo();
// Ejecuta la seccion de juego de la introducción
void runIntro(); void runIntro();
// Ejecuta la seccion de juego con el titulo y los menus
void runTitle(); void runTitle();
// Ejecuta la seccion de juego donde se juega
void runGame(); void runGame();
// Comprueba los ficheros del vector de ficheros que coinciden con una ruta dada
bool checkFolder(std::string name, std::string path);
public: public:
// Constructor // Constructor
Director(std::string path); Director(std::string path);
@@ -95,7 +100,7 @@ public:
~Director(); ~Director();
// Inicia las variables necesarias para arrancar el programa // Inicia las variables necesarias para arrancar el programa
void init(); void init(Uint8 name);
// Bucle principal // Bucle principal
void run(); void run();

View File

@@ -9,8 +9,6 @@ Fade::Fade(SDL_Renderer *renderer)
mBackbuffer = SDL_CreateTexture(mRenderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, SCREEN_WIDTH, SCREEN_HEIGHT); mBackbuffer = SDL_CreateTexture(mRenderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, SCREEN_WIDTH, SCREEN_HEIGHT);
if (mBackbuffer == NULL) if (mBackbuffer == NULL)
printf("Backbuffer could not be created!\nSDL Error: %s\n", SDL_GetError()); printf("Backbuffer could not be created!\nSDL Error: %s\n", SDL_GetError());
init();
} }
// Destructor // Destructor
@@ -21,15 +19,18 @@ Fade::~Fade()
} }
// Inicializa las variables // Inicializa las variables
void Fade::init() void Fade::init(Uint8 r, Uint8 g, Uint8 b)
{ {
mFadeType = FADE_CENTER; mFadeType = FADE_CENTER;
mEnabled = false; mEnabled = false;
mFinished = false; mFinished = false;
mCounter = 0; mCounter = 0;
mR = 0x27; //mR = 0x27;
mG = 0x27; //mG = 0x27;
mB = 0x36; //mB = 0x36;
mR = r;
mG = g;
mB = b;
} }
// Pinta una transición en pantalla // Pinta una transición en pantalla

View File

@@ -31,7 +31,7 @@ public:
~Fade(); ~Fade();
// Inicializa las variables // Inicializa las variables
void init(); void init(Uint8 r, Uint8 g, Uint8 b);
// Pinta una transición en pantalla // Pinta una transición en pantalla
void render(); void render();

File diff suppressed because it is too large Load Diff

View File

@@ -13,7 +13,7 @@
#include "item.h" #include "item.h"
#include "text.h" #include "text.h"
#include "text2.h" #include "writer.h"
#include "menu.h" #include "menu.h"
#include "input.h" #include "input.h"
#include "fade.h" #include "fade.h"
@@ -65,31 +65,57 @@ private:
Uint8 shakeCounter; // Contador para medir el tiempo que dura el efecto Uint8 shakeCounter; // Contador para medir el tiempo que dura el efecto
}; };
SDL_Renderer *mRenderer; // El renderizador de la ventana struct helper_t
std::string *mFileList; // Lista de ficheros con los recursos {
std::string *mTextStrings; // Vector con los textos del juego bool needCoffee; // Indica si se necesitan cafes
Input *mInput; // Manejador de entrada bool needCoffeeMachine; // Indica si se necesita PowerUp
bool needPowerBall; // Indica si se necesita una PowerBall
int counter; // Contador para no dar ayudas consecutivas
int itemPoints1Odds; // Probabilidad de aparición del objeto
int itemPoints2Odds; // Probabilidad de aparición del objeto
int itemPoints3Odds; // Probabilidad de aparición del objeto
int itemClockOdds; // Probabilidad de aparición del objeto
int itemCoffeeOdds; // Probabilidad de aparición del objeto
int itemCoffeeMachineOdds; // Probabilidad de aparición del objeto
};
Player *mPlayer; // El jugador SDL_Renderer *mRenderer; // El renderizador de la ventana
std::string *mFileList; // Lista de ficheros con los recursos
Lang *mLang; // Objeto para gestionar los textos en diferentes idiomas
int mNumPlayers; // Numero de jugadores
Player *mPlayer[2]; // Vector con los jugadores jugador
Input *mInput; // Manejador de entrada
Balloon *mBalloon[MAX_BALLOONS]; // Vector con los objetos globo Balloon *mBalloon[MAX_BALLOONS]; // Vector con los objetos globo
Bullet *mBullet[MAX_BULLETS]; // Vector con los objetos bala Bullet *mBullet[MAX_BULLETS]; // Vector con los objetos bala
Item *mItem[MAX_ITEMS]; // Vector con los objetos item Item *mItem[MAX_ITEMS]; // Vector con los objetos item
SmartSprite *mSmartSprite[MAX_SMART_SPRITES]; // Vector para almacenar y gestionar SmartSprites SmartSprite *mSmartSprite[MAX_SMART_SPRITES]; // Vector para almacenar y gestionar SmartSprites
LTexture *mTextureBalloon; // Textura para los enemigos LTexture *mTextureBalloon; // Textura para los enemigos
LTexture *mTextureBullet; // Textura para las balas LTexture *mTextureBullet; // Textura para las balas
LTexture *mTextureGameBG; // Textura para el fondo del juego LTexture *mTextureGameBG; // Textura para el fondo del juego
LTexture *mTextureGameText; // Textura para los sprites con textos LTexture *mTextureGameText; // Textura para los sprites con textos
LTexture *mTextureItems; // Textura para los items LTexture *mTextureItems; // Textura para los items
LTexture *mTexturePlayerBody; // Textura para el cuerpo del jugador LTexture *mTexturePlayer1Head; // Textura para la cabeza del jugador1
LTexture *mTexturePlayerDeath; // Textura para la animación de muerte del jugador LTexture *mTexturePlayer1Body; // Textura para el cuerpo del jugador1
LTexture *mTexturePlayerLegs; // Textura para las piernas del jugador LTexture *mTexturePlayer1Death; // Textura para la animación de muerte del jugador1
LTexture *mTextureText; // Textura para el texto LTexture *mTexturePlayer1Legs; // Textura para las piernas del jugador
LTexture *mTextureText2; // Textura para el texto 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 *mTextureText; // Textura para el texto del juego
LTexture *mTextureTextScoreBoard; // Textura para el texto del marcador
LTexture *mTextureTextBig; // Textura para el texto grande
LTexture *mTextureTextNokia2; // Textura para la fuente de texto Nokia
LTexture *mTextureTextNokiaBig2; // Textura para la fuente de texto Nokia grande
Text *mText; // Variable con todos los objetos de texto Text *mText; // Fuente para los textos del juego
Text *mTextX2; // Variable con todos los objetos de texto 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
Menu *mMenuGameOver; // Menú de la pantalla de game over Menu *mMenuGameOver; // Menú de la pantalla de game over
Menu *mMenuPause; // Menú de la pantalla de pausa Menu *mMenuPause; // Menú de la pantalla de pausa
@@ -125,13 +151,13 @@ private:
JA_Sound mSoundBubble4; // 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 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 mSoundPowerBall; // Sonido para cuando se explota una Power Ball
JA_Sound mSoundCollision; // Sonido para cuando la máquina de café toca el suelo
JA_Music mMusicPlaying; // Musica de fondo JA_Music mMusicPlaying; // Musica de fondo
Uint32 mTicks; // Contador de ticks para ajustar la velocidad del programa Uint32 mTicks; // Contador de ticks para ajustar la velocidad del programa
Uint8 mTicksSpeed; // Velocidad a la que se repiten los bucles del programa Uint8 mTicksSpeed; // Velocidad a la que se repiten los bucles del programa
Uint32 mScore; // Puntuación actual
Uint32 mHiScore; // Puntuación máxima Uint32 mHiScore; // Puntuación máxima
bool mHiScoreAchieved; // Indica si se ha superado la puntuación máxima bool mHiScoreAchieved; // Indica si se ha superado la puntuación máxima
section_t mSection; // Seccion actual dentro del juego section_t mSection; // Seccion actual dentro del juego
@@ -156,12 +182,20 @@ private:
Uint8 mLastEnemyDeploy; // Guarda cual ha sido la última formación desplegada para no repetir; Uint8 mLastEnemyDeploy; // Guarda cual ha sido la última formación desplegada para no repetir;
Uint8 mEnemyDeployCounter; // Cuando se lanza una formación, se le da un valor y no sale otra hasta que llegue a cero Uint8 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 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 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 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 Uint8 mPostFade; // Qué hacer al acabar el fade
float mSin[360]; // Vector con los valores del seno para 360 grados 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 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 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
struct demo_t struct demo_t
{ {
@@ -182,13 +216,6 @@ private:
}; };
debug_t mDebug; debug_t mDebug;
public:
// Constructor
Game(SDL_Renderer *renderer, std::string *filelist, std::string *textStrings, Input *input, bool demo);
// Destructor
~Game();
// Inicializa el vector con los valores del seno // Inicializa el vector con los valores del seno
void initSin(); void initSin();
@@ -225,9 +252,6 @@ public:
// Aumenta el poder de la fase // Aumenta el poder de la fase
void increaseStageCurrentPower(Uint8 power); void increaseStageCurrentPower(Uint8 power);
// Establece el valor de la variable
void setScore(Uint32 score);
// Establece el valor de la variable // Establece el valor de la variable
void setHiScore(Uint32 score); void setHiScore(Uint32 score);
@@ -304,10 +328,10 @@ public:
Uint8 countBalloons(); Uint8 countBalloons();
// Comprueba la colisión entre el jugador y los globos activos // Comprueba la colisión entre el jugador y los globos activos
bool checkPlayerBalloonCollision(); bool checkPlayerBalloonCollision(int index);
// Comprueba la colisión entre el jugador y los items // Comprueba la colisión entre el jugador y los items
void checkPlayerItemCollision(); void checkPlayerItemCollision(int index);
// Comprueba la colisión entre las balas y los globos // Comprueba la colisión entre las balas y los globos
void checkBulletBalloonCollision(); void checkBulletBalloonCollision();
@@ -325,7 +349,7 @@ public:
void resetBullets(); void resetBullets();
// Crea un objeto bala // Crea un objeto bala
void createBullet(int x, int y, Uint8 kind); void createBullet(int x, int y, Uint8 kind, bool poweredUp, int owner);
// Actualiza los items // Actualiza los items
void updateItems(); void updateItems();
@@ -358,7 +382,7 @@ public:
void throwCoffee(int x, int y); void throwCoffee(int x, int y);
// Crea un SmartSprite para arrojar al jugador al morir // Crea un SmartSprite para arrojar al jugador al morir
void throwPlayer(int x, int y); void throwPlayer(int x, int y, int index);
// Actualiza los SmartSprites // Actualiza los SmartSprites
void updateSmartSprites(); void updateSmartSprites();
@@ -373,7 +397,7 @@ public:
void resetSmartSprites(); void resetSmartSprites();
// Acciones a realizar cuando el jugador muere // Acciones a realizar cuando el jugador muere
void killPlayer(); void killPlayer(int index);
// Obtiene el valor de la variable // Obtiene el valor de la variable
Uint8 getSubsection(); Uint8 getSubsection();
@@ -447,9 +471,6 @@ public:
// Agita la pantalla // Agita la pantalla
void shakeScreen(); void shakeScreen();
// Bucle para el juego
section_t run();
// Bucle para el menu de pausa del juego // Bucle para el menu de pausa del juego
void runPausedGame(); void runPausedGame();
@@ -470,6 +491,22 @@ public:
// Actualiza el tramo final de juego, una vez completado // Actualiza el tramo final de juego, una vez completado
void updateGameCompleted(); void updateGameCompleted();
// Actualiza las variables de ayuda
void updateHelper();
// Comprueba si todos los jugadores han muerto
bool allPlayersAreDead();
public:
// Constructor
Game(int numPlayers, SDL_Renderer *renderer, std::string *filelist, Lang *lang, Input *input, bool demo, options_t *options);
// Destructor
~Game();
// Bucle para el juego
section_t run();
}; };
#endif #endif

View File

@@ -1,9 +1,9 @@
#ifdef _WIN64 #ifdef _WIN64
#include "C:\mingw_dev_lib\include\SDL2\SDL.h" #include "C:\Program Files\mingw-w64\x86_64-8.1.0-posix-seh-rt_v6-rev0\mingw64\lib\gcc\x86_64-w64-mingw32\8.1.0\include\c++\SDL2\SDL.h"
#endif #endif
#ifdef _WIN32 #ifdef _WIN32
#include "C:\mingw_dev_lib\include\SDL2\SDL.h" #include "C:\Program Files\mingw-w64\x86_64-8.1.0-posix-seh-rt_v6-rev0\mingw64\lib\gcc\x86_64-w64-mingw32\8.1.0\include\c++\SDL2\SDL.h"
#endif #endif
#ifdef __APPLE__ #ifdef __APPLE__

View File

@@ -1,163 +1,209 @@
#include "input.h" #include "input.h"
#include <iostream>
// Contestar cuantos joystics ha detectado
// Preguntarlepor los joystics que ha encontrado para ir poniendolos en la variable de opciones
// Constructor // Constructor
Input::Input() Input::Input(std::string file)
{ {
for (int i = 0; i < 15; i++) // Fichero gamecontrollerdb.txt
mDBpath = file;
// Inicializa las variables
for (int i = 0; i < 17; i++)
{ {
mInput[i].scancode = 0; mKeyBindings[i].scancode = 0;
mInput[i].active = false; mKeyBindings[i].active = false;
mGameControllerBindings[i].button = SDL_CONTROLLER_BUTTON_INVALID;
mGameControllerBindings[i].active = false;
} }
discoverGameController();
} }
// Destructor // Destructor
Input::~Input() Input::~Input()
{ {
for (int i = 0; i < mNumGamepads; i++)
mConnectedControllers[i] = nullptr;
} }
// Asigna uno de los posibles inputs a una tecla del teclado // Asigna uno de los posibles inputs a una tecla del teclado
void Input::bindKey(Uint8 input, SDL_Scancode code) void Input::bindKey(Uint8 input, SDL_Scancode code)
{ {
mInput[input].scancode = code; mKeyBindings[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;
} }
// Comprueba si un input esta activo // Comprueba si un input esta activo
bool Input::checkInput(Uint8 input, bool repeat) bool Input::checkInput(Uint8 input, bool repeat, int device, int index)
{ {
const Uint8 *mKeystates = SDL_GetKeyboardState(NULL); bool successKeyboard = false;
bool successGameController = false;
if (repeat) if (device == INPUT_USE_ANY)
index = 0;
if ((device == INPUT_USE_KEYBOARD) || (device == INPUT_USE_ANY))
{ {
if (mKeystates[mInput[input].scancode] != 0) const Uint8 *mKeystates = SDL_GetKeyboardState(NULL);
return true;
else if (repeat)
return false;
}
else
{
if (!mInput[input].active)
{ {
if (mKeystates[mInput[input].scancode] != 0) if (mKeystates[mKeyBindings[input].scancode] != 0)
{ successKeyboard = true;
mInput[input].active = true;
return true;
}
else else
{ successKeyboard = false;
return false;
}
} }
else else
{ {
if (mKeystates[mInput[input].scancode] == 0) if (!mKeyBindings[input].active)
{ {
mInput[input].active = false; if (mKeystates[mKeyBindings[input].scancode] != 0)
return false;
}
else
{
return false;
}
}
}
}
// Gestiona las entradas desde el mando de juego
bool Input::checkGameController(Uint8 state)
{
bool success = false;
// No hay mando. Siempre devuelve falso salvo NO_INPUT que siempre es cierto
/*if (!mGameControllerFound)
{
if (state == NO_INPUT)
return true;
else
return false;
}
switch (state)
{
case INPUT_NULL:
success = !checkGameController(INPUT_UP) && !checkGameController(INPUT_DOWN) && !checkGameController(INPUT_LEFT) && !checkGameController(INPUT_RIGHT) &&
!checkGameController(INPUT_ACCEPT) && !checkGameController(INPUT_CANCEL) && !checkGameController(INPUT_PAUSE) &&
!checkGameController(INPUT_FIRE_UP) && !checkGameController(INPUT_FIRE_LEFT) && !checkGameController(INPUT_FIRE_RIGHT);
break;
case INPUT_UP:
success = (SDL_JoystickGetAxis(mGameController, 1) < -JOYSTICK_DEAD_ZONE) || (SDL_JoystickGetButton(mGameController, SDL_CONTROLLER_BUTTON_DPAD_UP));
break;
case INPUT_DOWN:
success = (SDL_JoystickGetAxis(mGameController, 1) > JOYSTICK_DEAD_ZONE) || (SDL_JoystickGetButton(mGameController, SDL_CONTROLLER_BUTTON_DPAD_DOWN));
break;
case INPUT_LEFT:
success = (SDL_JoystickGetAxis(mGameController, 0) < -JOYSTICK_DEAD_ZONE) || (SDL_JoystickGetButton(mGameController, SDL_CONTROLLER_BUTTON_DPAD_LEFT));
break;
case INPUT_RIGHT:
success = (SDL_JoystickGetAxis(mGameController, 0) > JOYSTICK_DEAD_ZONE) || (SDL_JoystickGetButton(mGameController, SDL_CONTROLLER_BUTTON_DPAD_RIGHT));
break;
case INPUT_ACCEPT:
success = (SDL_JoystickGetButton(mGameController, SDL_CONTROLLER_BUTTON_B));
break;
case INPUT_CANCEL:
success = (SDL_JoystickGetButton(mGameController, SDL_CONTROLLER_BUTTON_A));
break;
case INPUT_PAUSE:
success = (SDL_JoystickGetButton(mGameController, SDL_CONTROLLER_BUTTON_START));
break;
case INPUT_FIRE_UP:
success = (SDL_JoystickGetButton(mGameController, SDL_CONTROLLER_BUTTON_Y));
break;
case INPUT_FIRE_LEFT:
success = (SDL_JoystickGetButton(mGameController, SDL_CONTROLLER_BUTTON_X));
break;
case INPUT_FIRE_RIGHT:
success = (SDL_JoystickGetButton(mGameController, SDL_CONTROLLER_BUTTON_B));
break;
default:
break;
}*/
return success;
}
// Comprueba si hay algun mando conectado
/*if (SDL_NumJoysticks() < 1)
{
printf("Warning: No joysticks connected!\n");
mGameControllerFound = false;
}
else
{
// Carga el mando
mGameController = SDL_JoystickOpen(0);
mGameControllerFound = true;
if (mGameController == NULL)
{
printf("Warning: Unable to open game controller!\nSDL Error: %s\n", SDL_GetError());
mGameControllerFound = false;
}
else
{
printf("%i joysticks were found.\n", SDL_NumJoysticks());
std::cout << SDL_JoystickNumButtons(mGameController) << " buttons\n";
// Obtiene el dispositivo de control háptico
mControllerHaptic = SDL_HapticOpenFromJoystick(mGameController);
if (mControllerHaptic == NULL)
{ {
printf("Warning: Controller does not support haptics!\nSDL Error: %s\n", SDL_GetError()); mKeyBindings[input].active = true;
successKeyboard = true;
} }
else else
{ {
printf("Haptics detected\n"); successKeyboard = false;
}
}
else
{
if (mKeystates[mKeyBindings[input].scancode] == 0)
{
mKeyBindings[input].active = false;
successKeyboard = false;
}
else
{
successKeyboard = false;
}
}
}
}
// Inicializa la vibración if (gameControllerFound())
if (SDL_HapticRumbleInit(mControllerHaptic) < 0) if ((device == INPUT_USE_GAMECONTROLLER) || (device == INPUT_USE_ANY))
{
if (repeat)
{
if (SDL_GameControllerGetButton(mConnectedControllers[index], mGameControllerBindings[input].button) != 0)
successGameController = true;
else
successGameController = false;
}
else
{
if (!mGameControllerBindings[input].active)
{
if (SDL_GameControllerGetButton(mConnectedControllers[index], mGameControllerBindings[input].button) != 0)
{ {
printf("Warning: Unable to initialize rumble!\nSDL Error: %s\n", SDL_GetError()); mGameControllerBindings[input].active = true;
successGameController = true;
}
else
{
successGameController = false;
}
}
else
{
if (SDL_GameControllerGetButton(mConnectedControllers[index], mGameControllerBindings[input].button) == 0)
{
mGameControllerBindings[input].active = false;
successGameController = false;
}
else
{
successGameController = false;
} }
} }
} }
}*/ }
return (successKeyboard || successGameController);
}
// Comprueba si hay un mando conectado
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());
int nJoysticks = SDL_NumJoysticks();
mNumGamepads = 0;
// Cuenta el numero de mandos
for (int i = 0; i < nJoysticks; i++)
if (SDL_IsGameController(i))
mNumGamepads++;
printf("\nChecking for game controllers...\n");
printf("%i joysticks found, %i are gamepads\n", nJoysticks, mNumGamepads);
if (mNumGamepads > 0)
{
found = true;
for (int i = 0; i < mNumGamepads; 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(" #");
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);
}
else
std::cout << "SDL_GetError() = " << SDL_GetError() << std::endl;
}
//mGameController = mConnectedControllers[0];
SDL_GameControllerEventState(SDL_ENABLE);
}
return found;
}
// Comprueba si hay algun mando conectado
bool Input::gameControllerFound()
{
if (mNumGamepads > 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];
else
return "";
}
// Obten el numero de mandos conectados
int Input::getNumControllers()
{
return mNumGamepads;
}

View File

@@ -1,5 +1,7 @@
#pragma once #pragma once
#include "ifdefs.h" #include "ifdefs.h"
#include <string>
#include <vector>
#ifndef INPUT_H #ifndef INPUT_H
#define INPUT_H #define INPUT_H
@@ -19,28 +21,46 @@
#define INPUT_BUTTON_6 12 #define INPUT_BUTTON_6 12
#define INPUT_BUTTON_7 13 #define INPUT_BUTTON_7 13
#define INPUT_BUTTON_8 14 #define INPUT_BUTTON_8 14
#define INPUT_BUTTON_PAUSE 15
#define INPUT_BUTTON_ESCAPE 16
#define REPEAT_TRUE true #define REPEAT_TRUE true
#define REPEAT_FALSE false #define REPEAT_FALSE false
#define INPUT_USE_KEYBOARD 0
#define INPUT_USE_GAMECONTROLLER 1
#define INPUT_USE_ANY 2
// Clase Input // Clase Input
class Input class Input
{ {
private: private:
struct input_t struct keyBindings_t
{ {
Uint8 scancode; // Scancode asociado Uint8 scancode; // Scancode asociado
bool active; // Indica si está activo bool active; // Indica si está activo
}; };
input_t mInput[15]; // Vector con las teclas asociadas a los inputs predefinidos keyBindings_t mKeyBindings[17]; // Vector con las teclas asociadas a los inputs predefinidos
//SDL_Joystick *mGameController; // Manejador para el mando 1 struct GameControllerBindings_t
//SDL_Haptic *mControllerHaptic; // Manejador para el mando con vibración {
//bool mGameControllerFound; // Variable para saber si hay un mando conectado SDL_GameControllerButton button; // GameControllerButton asociado
bool active; // Indica si está activo
};
GameControllerBindings_t mGameControllerBindings[17]; // Vector con las teclas asociadas a los inputs predefinidos
//SDL_GameController *mGameController; // Manejador para el mando
std::vector<SDL_GameController*> mConnectedControllers;
std::vector<std::string> mControllerNames;
int mNumGamepads;
std::string mDBpath; // Ruta al archivo gamecontrollerdb.txt
// Comprueba si hay un mando conectado
bool discoverGameController();
public: public:
// Constructor // Constructor
Input(); Input(std::string file);
// Destructor // Destructor
~Input(); ~Input();
@@ -48,11 +68,20 @@ public:
// Asigna uno de los posibles inputs a una tecla del teclado // Asigna uno de los posibles inputs a una tecla del teclado
void bindKey(Uint8 input, SDL_Scancode code); void bindKey(Uint8 input, SDL_Scancode code);
// Comprueba si un input esta activo // Asigna uno de los posibles inputs a un botón del mando
bool checkInput(Uint8 input, bool repeat); void bindGameControllerButton(Uint8 input, SDL_GameControllerButton button);
// Gestiona las entradas desde el mando de juego // Comprueba si un input esta activo
bool checkGameController(Uint8 state); bool checkInput(Uint8 input, bool repeat, int device=INPUT_USE_ANY, int index=0);
// Comprueba si hay algun mando conectado
bool gameControllerFound();
// Obten el numero de mandos conectados
int getNumControllers();
// Obten el nombre de un mando de juego
std::string getControllerName(int index);
}; };
#endif #endif

View File

@@ -7,19 +7,19 @@
const Uint8 SELF = 0; const Uint8 SELF = 0;
// Constructor // Constructor
Instructions::Instructions(SDL_Renderer *renderer, std::string *fileList, std::string *textStrings) Instructions::Instructions(SDL_Renderer *renderer, std::string *fileList, Lang *lang)
{ {
// Copia los punteros // Copia los punteros
mRenderer = renderer; mRenderer = renderer;
mFileList = fileList; mFileList = fileList;
mTextStrings = textStrings; mLang = lang;
// Reserva memoria para los punteros // Reserva memoria para los punteros
mEventHandler = new SDL_Event(); mEventHandler = new SDL_Event();
mItemTexture = new LTexture(); mItemTexture = new LTexture();
mTextTexture = new LTexture(); mTextTexture = new LTexture();
mSprite = new Sprite(); mSprite = new Sprite();
mText = new Text(mTextTexture, mRenderer); mText = new Text(mFileList[48], mTextTexture, mRenderer);
// Crea un backbuffer para el renderizador // Crea un backbuffer para el renderizador
mBackbuffer = SDL_CreateTexture(mRenderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, SCREEN_WIDTH, SCREEN_HEIGHT); mBackbuffer = SDL_CreateTexture(mRenderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, SCREEN_WIDTH, SCREEN_HEIGHT);
@@ -73,7 +73,6 @@ void Instructions::init()
mSprite->init(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, mItemTexture, mRenderer); mSprite->init(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, mItemTexture, mRenderer);
mTicks = 0; mTicks = 0;
mTicksSpeed = 15; mTicksSpeed = 15;
mText->init(TEXT_FIXED, BLOCK);
mManualQuit = false; mManualQuit = false;
mCounter = 0; mCounter = 0;
} }
@@ -156,21 +155,21 @@ void Instructions::run(Uint8 mode)
SDL_RenderClear(mRenderer); SDL_RenderClear(mRenderer);
// Escribe el texto // Escribe el texto
mText->writeDX(TXT_CENTER | TXT_COLOR | TXT_SHADOW, SCREEN_CENTER_X, 8, mTextStrings[11], 0, orangeColor, 1, shdwTxtColor); 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, mTextStrings[12], 0, noColor, 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, mTextStrings[13], 0, 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, mTextStrings[14], 0, 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, mTextStrings[15], 0, 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, mTextStrings[16], 0, orangeColor, 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, mTextStrings[17], shdwTxtColor); mText->writeShadowed(84, 92, mLang->getText(17), shdwTxtColor);
mText->writeShadowed(84, 108, mTextStrings[18], shdwTxtColor); mText->writeShadowed(84, 108, mLang->getText(18), shdwTxtColor);
mText->writeShadowed(84, 124, mTextStrings[19], shdwTxtColor); mText->writeShadowed(84, 124, mLang->getText(19), shdwTxtColor);
mText->writeShadowed(84, 140, mTextStrings[20], shdwTxtColor); mText->writeShadowed(84, 140, mLang->getText(20), shdwTxtColor);
mText->writeShadowed(84, 156, mTextStrings[21], shdwTxtColor); mText->writeShadowed(84, 156, mLang->getText(21), shdwTxtColor);
if ((mode == INSTRUCTIONS_MODE_MANUAL) && (mCounter % 50 > 14)) if ((mode == INSTRUCTIONS_MODE_MANUAL) && (mCounter % 50 > 14))
mText->writeDX(TXT_CENTER | TXT_COLOR | TXT_SHADOW, SCREEN_CENTER_X, SCREEN_HEIGHT - 12, mTextStrings[22], 0, orangeColor, 1, shdwTxtColor); mText->writeDX(TXT_CENTER | TXT_COLOR | TXT_SHADOW, SCREEN_CENTER_X, SCREEN_HEIGHT - 12, mLang->getText(22), 1, orangeColor, 1, shdwTxtColor);
// Disquito // Disquito
mSprite->init(destRect1, mItemTexture, mRenderer); mSprite->init(destRect1, mItemTexture, mRenderer);

View File

@@ -14,20 +14,20 @@
class Instructions class Instructions
{ {
private: private:
LTexture *mItemTexture; // Textura con los graficos LTexture *mItemTexture; // Textura con los graficos
LTexture *mTextTexture; // Textura con los graficos LTexture *mTextTexture; // Textura con los graficos
SDL_Event *mEventHandler; // Manejador de eventos SDL_Event *mEventHandler; // Manejador de eventos
SDL_Renderer *mRenderer; // El renderizador de la ventana SDL_Renderer *mRenderer; // El renderizador de la ventana
SDL_Texture *mBackbuffer; // Textura para usar como backbuffer SDL_Texture *mBackbuffer; // Textura para usar como backbuffer
Sprite *mSprite; // Sprite con la textura de las instrucciones Sprite *mSprite; // Sprite con la textura de las instrucciones
std::string *mFileList; // Lista de ficheros std::string *mFileList; // Lista de ficheros
std::string *mTextStrings; // Vector con los textos del juego Lang *mLang; // Objeto para gestionar los textos en diferentes idiomas
Text *mText; // Objeto para escribir texto Text *mText; // Objeto para escribir texto
Uint16 mCounter; // Contador Uint16 mCounter; // Contador
section_t mSection; // Estado del bucle principal para saber si continua o se sale 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 Uint32 mTicks; // Contador de ticks para ajustar la velocidad del programa
Uint8 mTicksSpeed; // Velocidad a la que se repiten los bucles del programa Uint8 mTicksSpeed; // Velocidad a la que se repiten los bucles del programa
bool mManualQuit; // Indica si se quiere salir del modo manual bool mManualQuit; // Indica si se quiere salir del modo manual
// Carga los recursos // Carga los recursos
bool loadMedia(); bool loadMedia();
@@ -43,7 +43,7 @@ private:
public: public:
// Constructor // Constructor
Instructions(SDL_Renderer *renderer, std::string *fileList, std::string *textStrings); Instructions(SDL_Renderer *renderer, std::string *fileList, Lang *lang);
// Destructor // Destructor
~Instructions(); ~Instructions();

View File

@@ -5,23 +5,24 @@
#endif #endif
// Constructor // Constructor
Intro::Intro(SDL_Renderer *renderer, std::string *fileList, std::string *textStrings) Intro::Intro(SDL_Renderer *renderer, std::string *fileList, Lang *lang)
{ {
// Copia los punteros // Copia los punteros
mRenderer = renderer; mRenderer = renderer;
mFileList = fileList; mFileList = fileList;
mTextStrings = textStrings; mLang = lang;
// Reserva memoria para los punteros // Reserva memoria para los punteros
mEventHandler = new SDL_Event(); mEventHandler = new SDL_Event();
mBitmapTexture = new LTexture(); mBitmapTexture = new LTexture();
mTextTexture = new LTexture(); mTextTexture = new LTexture();
mText = new Text(mFileList[52], mTextTexture, mRenderer);
for (int i = 0; i < INTRO_TOTAL_BITMAPS; i++) for (int i = 0; i < INTRO_TOTAL_BITMAPS; i++)
mBitmap[i] = new SmartSprite(); mBitmap[i] = new SmartSprite();
for (int i = 0; i < INTRO_TOTAL_TEXTS; i++) for (int i = 0; i < INTRO_TOTAL_TEXTS; i++)
mText[i] = new Text2(mTextTexture, mRenderer); mWriter[i] = new Writer(mText);
} }
// Destructor // Destructor
@@ -45,8 +46,8 @@ Intro::~Intro()
} }
for (int i = 0; i < INTRO_TOTAL_TEXTS; i++) for (int i = 0; i < INTRO_TOTAL_TEXTS; i++)
{ {
delete mText[i]; delete mWriter[i];
mText[i] = nullptr; mWriter[i] = nullptr;
} }
JA_DeleteMusic(mMusic); JA_DeleteMusic(mMusic);
@@ -133,55 +134,55 @@ void Intro::init()
// Inicializa los textos de la intro // Inicializa los textos de la intro
for (int i = 0; i < INTRO_TOTAL_TEXTS; i++) for (int i = 0; i < INTRO_TOTAL_TEXTS; i++)
{ {
mText[i]->init(TEXT_VARIABLE, 10); mWriter[i]->init();
mText[i]->setId(6 + i); mWriter[i]->setId(6 + i);
mText[i]->setIntroEvents(&mEvents[0]); mWriter[i]->setIntroEvents(&mEvents[0]);
mText[i]->setPosX(BLOCK * 0); mWriter[i]->setPosX(BLOCK * 0);
mText[i]->setPosY(SCREEN_HEIGHT - (BLOCK * 6)); mWriter[i]->setPosY(SCREEN_HEIGHT - (BLOCK * 6));
mText[i]->setKerning(-1); mWriter[i]->setKerning(-1);
mText[i]->setEnabled(false); mWriter[i]->setEnabled(false);
mText[i]->setEnabledTimer(180); mWriter[i]->setEnabledTimer(180);
} }
// Un dia qualsevol de l'any 2000 // Un dia qualsevol de l'any 2000
mText[0]->setCaption(mTextStrings[27]); mWriter[0]->setCaption(mLang->getText(27));
mText[0]->setWrittingSpeed(10); mWriter[0]->setSpeed(10);
// Tot esta tranquil a la UPV // Tot esta tranquil a la UPV
mText[1]->setCaption(mTextStrings[28]); mWriter[1]->setCaption(mLang->getText(28));
mText[1]->setWrittingSpeed(10); mWriter[1]->setSpeed(10);
// Fins que un desaprensiu... // Fins que un desaprensiu...
mText[2]->setCaption(mTextStrings[29]); mWriter[2]->setCaption(mLang->getText(29));
mText[2]->setWrittingSpeed(15); mWriter[2]->setSpeed(15);
// HEY! ME ANE A FERME UN CORTAET... // HEY! ME ANE A FERME UN CORTAET...
mText[3]->setCaption(mTextStrings[30]); mWriter[3]->setCaption(mLang->getText(30));
mText[3]->setWrittingSpeed(10); mWriter[3]->setSpeed(10);
// UAAAAAAAAAAAAA!!! // UAAAAAAAAAAAAA!!!
mText[4]->setCaption(mTextStrings[31]); mWriter[4]->setCaption(mLang->getText(31));
mText[4]->setWrittingSpeed(1); mWriter[4]->setSpeed(1);
// Espera un moment... // Espera un moment...
mText[5]->setCaption(mTextStrings[32]); mWriter[5]->setCaption(mLang->getText(32));
mText[5]->setWrittingSpeed(20); mWriter[5]->setSpeed(20);
// Si resulta que no tinc solt! // Si resulta que no tinc solt!
mText[6]->setCaption(mTextStrings[33]); mWriter[6]->setCaption(mLang->getText(33));
mText[6]->setWrittingSpeed(2); mWriter[6]->setSpeed(2);
// MERDA DE MAQUINA! // MERDA DE MAQUINA!
mText[7]->setCaption(mTextStrings[34]); mWriter[7]->setCaption(mLang->getText(34));
mText[7]->setWrittingSpeed(3); mWriter[7]->setSpeed(3);
// Blop... blop... blop... // Blop... blop... blop...
mText[8]->setCaption(mTextStrings[35]); mWriter[8]->setCaption(mLang->getText(35));
mText[8]->setWrittingSpeed(20); mWriter[8]->setSpeed(20);
for (int i = 0; i < INTRO_TOTAL_TEXTS; i++) for (int i = 0; i < INTRO_TOTAL_TEXTS; i++)
{ {
mText[i]->center(SCREEN_CENTER_X); mWriter[i]->center(SCREEN_CENTER_X);
} }
} }
@@ -240,7 +241,7 @@ section_t Intro::run()
for (int i = 0; i < INTRO_TOTAL_BITMAPS; i++) for (int i = 0; i < INTRO_TOTAL_BITMAPS; i++)
mBitmap[i]->update(); mBitmap[i]->update();
for (int i = 0; i < INTRO_TOTAL_TEXTS; i++) for (int i = 0; i < INTRO_TOTAL_TEXTS; i++)
mText[i]->update(); mWriter[i]->update();
// Guión de eventos // Guión de eventos
// Primera imagen - UPV // Primera imagen - UPV
@@ -253,23 +254,23 @@ section_t Intro::run()
// Primer texto de la primera imagen // Primer texto de la primera imagen
if ((mEvents[BITMAP0] == EVENT_COMPLETED) && (mEvents[TEXT0] == EVENT_WAITING)) if ((mEvents[BITMAP0] == EVENT_COMPLETED) && (mEvents[TEXT0] == EVENT_WAITING))
{ {
mText[0]->setEnabled(true); mWriter[0]->setEnabled(true);
mEvents[TEXT0] = EVENT_RUNNING; mEvents[TEXT0] = EVENT_RUNNING;
} }
// Segundo texto de la primera imagen // Segundo texto de la primera imagen
if ((mEvents[TEXT0] == EVENT_COMPLETED) && (mEvents[TEXT1] == EVENT_WAITING)) if ((mEvents[TEXT0] == EVENT_COMPLETED) && (mEvents[TEXT1] == EVENT_WAITING))
{ {
mText[0]->setEnabled(false); mWriter[0]->setEnabled(false);
mText[1]->setEnabled(true); mWriter[1]->setEnabled(true);
mEvents[TEXT1] = EVENT_RUNNING; mEvents[TEXT1] = EVENT_RUNNING;
} }
// Tercer texto de la primera imagen // Tercer texto de la primera imagen
if ((mEvents[TEXT1] == EVENT_COMPLETED) && (mEvents[TEXT2] == EVENT_WAITING)) if ((mEvents[TEXT1] == EVENT_COMPLETED) && (mEvents[TEXT2] == EVENT_WAITING))
{ {
mText[1]->setEnabled(false); mWriter[1]->setEnabled(false);
mText[2]->setEnabled(true); mWriter[2]->setEnabled(true);
mEvents[TEXT2] = EVENT_RUNNING; mEvents[TEXT2] = EVENT_RUNNING;
} }
@@ -277,7 +278,7 @@ section_t Intro::run()
if ((mEvents[TEXT2] == EVENT_COMPLETED) && (mEvents[BITMAP1] == EVENT_WAITING)) if ((mEvents[TEXT2] == EVENT_COMPLETED) && (mEvents[BITMAP1] == EVENT_WAITING))
{ {
mBitmap[0]->setEnabled(false); mBitmap[0]->setEnabled(false);
mText[2]->setEnabled(false); mWriter[2]->setEnabled(false);
mBitmap[1]->setEnabled(true); mBitmap[1]->setEnabled(true);
mEvents[BITMAP1] = EVENT_RUNNING; mEvents[BITMAP1] = EVENT_RUNNING;
} }
@@ -285,7 +286,7 @@ section_t Intro::run()
// Primer texto de la segunda imagen // Primer texto de la segunda imagen
if ((mEvents[BITMAP1] == EVENT_COMPLETED) && (mEvents[TEXT3] == EVENT_WAITING)) if ((mEvents[BITMAP1] == EVENT_COMPLETED) && (mEvents[TEXT3] == EVENT_WAITING))
{ {
mText[3]->setEnabled(true); mWriter[3]->setEnabled(true);
mEvents[TEXT3] = EVENT_RUNNING; mEvents[TEXT3] = EVENT_RUNNING;
} }
@@ -293,9 +294,9 @@ section_t Intro::run()
if ((mEvents[TEXT3] == EVENT_COMPLETED) && (mEvents[BITMAP2] == EVENT_WAITING) && (mEvents[TEXT4] == EVENT_WAITING)) if ((mEvents[TEXT3] == EVENT_COMPLETED) && (mEvents[BITMAP2] == EVENT_WAITING) && (mEvents[TEXT4] == EVENT_WAITING))
{ {
mBitmap[1]->setEnabled(false); mBitmap[1]->setEnabled(false);
mText[3]->setEnabled(false); mWriter[3]->setEnabled(false);
mBitmap[2]->setEnabled(true); mBitmap[2]->setEnabled(true);
mText[4]->setEnabled(true); mWriter[4]->setEnabled(true);
mEvents[BITMAP2] = EVENT_RUNNING; mEvents[BITMAP2] = EVENT_RUNNING;
mEvents[TEXT4] = EVENT_RUNNING; mEvents[TEXT4] = EVENT_RUNNING;
} }
@@ -304,9 +305,9 @@ section_t Intro::run()
if ((mEvents[TEXT4] == EVENT_COMPLETED) && (mEvents[BITMAP3] == EVENT_WAITING) && (mEvents[TEXT5] == EVENT_WAITING)) if ((mEvents[TEXT4] == EVENT_COMPLETED) && (mEvents[BITMAP3] == EVENT_WAITING) && (mEvents[TEXT5] == EVENT_WAITING))
{ {
mBitmap[2]->setEnabled(false); mBitmap[2]->setEnabled(false);
mText[4]->setEnabled(false); mWriter[4]->setEnabled(false);
mBitmap[3]->setEnabled(true); mBitmap[3]->setEnabled(true);
mText[5]->setEnabled(true); mWriter[5]->setEnabled(true);
mEvents[BITMAP3] = EVENT_RUNNING; mEvents[BITMAP3] = EVENT_RUNNING;
mEvents[TEXT5] = EVENT_RUNNING; mEvents[TEXT5] = EVENT_RUNNING;
} }
@@ -314,8 +315,8 @@ section_t Intro::run()
// Segundo texto de la cuarta imagen // Segundo texto de la cuarta imagen
if ((mEvents[TEXT5] == EVENT_COMPLETED) && (mEvents[TEXT6] == EVENT_WAITING)) if ((mEvents[TEXT5] == EVENT_COMPLETED) && (mEvents[TEXT6] == EVENT_WAITING))
{ {
mText[5]->setEnabled(false); mWriter[5]->setEnabled(false);
mText[6]->setEnabled(true); mWriter[6]->setEnabled(true);
mEvents[TEXT6] = EVENT_RUNNING; mEvents[TEXT6] = EVENT_RUNNING;
} }
@@ -323,7 +324,7 @@ section_t Intro::run()
if ((mEvents[TEXT6] == EVENT_COMPLETED) && (mEvents[BITMAP4] == EVENT_WAITING)) if ((mEvents[TEXT6] == EVENT_COMPLETED) && (mEvents[BITMAP4] == EVENT_WAITING))
{ {
mBitmap[3]->setEnabled(false); mBitmap[3]->setEnabled(false);
mText[6]->setEnabled(false); mWriter[6]->setEnabled(false);
mBitmap[4]->setEnabled(true); mBitmap[4]->setEnabled(true);
mEvents[BITMAP4] = EVENT_RUNNING; mEvents[BITMAP4] = EVENT_RUNNING;
} }
@@ -331,7 +332,7 @@ section_t Intro::run()
// Primer texto de la quinta imagen // Primer texto de la quinta imagen
if ((mEvents[BITMAP4] == EVENT_COMPLETED) && (mEvents[TEXT7] == EVENT_WAITING)) if ((mEvents[BITMAP4] == EVENT_COMPLETED) && (mEvents[TEXT7] == EVENT_WAITING))
{ {
mText[7]->setEnabled(true); mWriter[7]->setEnabled(true);
mEvents[TEXT7] = EVENT_RUNNING; mEvents[TEXT7] = EVENT_RUNNING;
} }
@@ -339,9 +340,9 @@ section_t Intro::run()
if ((mEvents[TEXT7] == EVENT_COMPLETED) && (mEvents[BITMAP5] == EVENT_WAITING) && (mEvents[TEXT8] == EVENT_WAITING)) if ((mEvents[TEXT7] == EVENT_COMPLETED) && (mEvents[BITMAP5] == EVENT_WAITING) && (mEvents[TEXT8] == EVENT_WAITING))
{ {
mBitmap[4]->setEnabled(false); mBitmap[4]->setEnabled(false);
mText[7]->setEnabled(false); mWriter[7]->setEnabled(false);
mBitmap[5]->setEnabled(true); mBitmap[5]->setEnabled(true);
mText[8]->setEnabled(true); mWriter[8]->setEnabled(true);
mEvents[BITMAP5] = EVENT_RUNNING; mEvents[BITMAP5] = EVENT_RUNNING;
mEvents[TEXT8] = EVENT_RUNNING; mEvents[TEXT8] = EVENT_RUNNING;
} }
@@ -349,7 +350,7 @@ section_t Intro::run()
// Acaba el último texto // Acaba el último texto
if (mEvents[TEXT8] == EVENT_COMPLETED) if (mEvents[TEXT8] == EVENT_COMPLETED)
{ {
mText[8]->setEnabled(false); mWriter[8]->setEnabled(false);
JA_StopMusic(); JA_StopMusic();
mSection = {PROG_SECTION_TITLE, TITLE_SECTION_1}; mSection = {PROG_SECTION_TITLE, TITLE_SECTION_1};
} }
@@ -363,7 +364,7 @@ section_t Intro::run()
for (int i = 0; i < INTRO_TOTAL_BITMAPS; i++) for (int i = 0; i < INTRO_TOTAL_BITMAPS; i++)
mBitmap[i]->render(); mBitmap[i]->render();
for (int i = 0; i < INTRO_TOTAL_TEXTS; i++) for (int i = 0; i < INTRO_TOTAL_TEXTS; i++)
mText[i]->render(); mWriter[i]->render();
// Actualiza la pantalla // Actualiza la pantalla
SDL_RenderPresent(mRenderer); SDL_RenderPresent(mRenderer);

View File

@@ -4,7 +4,7 @@
#include "utils.h" #include "utils.h"
#include "smartsprite.h" #include "smartsprite.h"
#include "text2.h" #include "writer.h"
#include "jail_audio.h" #include "jail_audio.h"
#ifndef INTRO_H #ifndef INTRO_H
@@ -19,18 +19,19 @@ private:
SDL_Event *mEventHandler; // Manejador de eventos SDL_Event *mEventHandler; // Manejador de eventos
SDL_Renderer *mRenderer; // El renderizador de la ventana SDL_Renderer *mRenderer; // El renderizador de la ventana
std::string *mFileList; // Lista de ficheros std::string *mFileList; // Lista de ficheros
std::string *mTextStrings; // Vector con los textos del juego Lang *mLang; // Objeto para gestionar los textos en diferentes idiomas
section_t mSection; // Estado del bucle principal para saber si continua o se sale 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 Uint32 mTicks; // Contador de ticks para ajustar la velocidad del programa
Uint8 mTicksSpeed; // Velocidad a la que se repiten los bucles 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 SmartSprite *mBitmap[INTRO_TOTAL_BITMAPS]; // Vector con los sprites inteligentes para los dibujos de la intro
Text2 *mText[INTRO_TOTAL_TEXTS]; // Textos 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 Uint8 mEvents[INTRO_TOTAL_EVENTS]; // Vector para coordinar los eventos de la intro
JA_Music mMusic; // Musica para la intro JA_Music mMusic; // Musica para la intro
public: public:
// Constructor // Constructor
Intro(SDL_Renderer *renderer, std::string *fileList, std::string *textStrings); Intro(SDL_Renderer *renderer, std::string *fileList, Lang *lang);
// Destructor // Destructor
~Intro(); ~Intro();

View File

@@ -1,18 +1,17 @@
#include "const.h" #include "const.h"
#include "item.h" #include "item.h"
#include <stdio.h>
// Constructor // Constructor
Item::Item() Item::Item()
{ {
mSprite = new AnimatedSprite(); mSprite = new AnimatedSprite();
//init(NO_KIND, 0, 0, nullptr, nullptr);
mClass = NO_KIND; mClass = NO_KIND;
} }
// Destructor // Destructor
Item::~Item() Item::~Item()
{ {
//init(NO_KIND, 0, 0, nullptr, nullptr);
delete mSprite; delete mSprite;
mSprite = nullptr; mSprite = nullptr;
} }
@@ -31,6 +30,7 @@ void Item::init(Uint8 value, float x, float y, LTexture *texture, SDL_Renderer *
mVelY = -4.0f; mVelY = -4.0f;
mAccelX = 0.0f; mAccelX = 0.0f;
mAccelY = 0.2f; mAccelY = 0.2f;
mFloorCollision = false;
mCollider.r = mWidth / 2; mCollider.r = mWidth / 2;
shiftColliders(); shiftColliders();
@@ -43,6 +43,8 @@ void Item::init(Uint8 value, float x, float y, LTexture *texture, SDL_Renderer *
mSprite->setAnimationSpeed(0, 10); mSprite->setAnimationSpeed(0, 10);
mSprite->setAnimationLoop(0, true); mSprite->setAnimationLoop(0, true);
mSprite->setSpriteClip(mSprite->getAnimationClip(0, 0)); mSprite->setSpriteClip(mSprite->getAnimationClip(0, 0));
mSprite->setPosX(mPosX);
mSprite->setPosY(mPosY);
switch (value) switch (value)
{ {
@@ -82,12 +84,31 @@ void Item::init(Uint8 value, float x, float y, LTexture *texture, SDL_Renderer *
mSprite->setAnimationFrames(0, 1, 16 * 5, 16 * 1, mWidth, mHeight); mSprite->setAnimationFrames(0, 1, 16 * 5, 16 * 1, mWidth, mHeight);
break; 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->setAnimationNumFrames(0, 4);
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: default:
break; break;
} }
} }
// Centra el globo en la posición X // Centra el objeto en la posición X
void Item::allignTo(int x) void Item::allignTo(int x)
{ {
mPosX = float(x - (mWidth / 2)); mPosX = float(x - (mWidth / 2));
@@ -109,7 +130,7 @@ void Item::allignTo(int x)
shiftColliders(); shiftColliders();
} }
// Pinta el globo en la pantalla // Pinta el objeto en la pantalla
void Item::render() void Item::render()
{ {
if (mEnabled) if (mEnabled)
@@ -125,9 +146,11 @@ void Item::render()
} }
} }
// Actualiza la posición y estados del globo // Actualiza la posición y estados del objeto
void Item::move() void Item::move()
{ {
mFloorCollision = false;
// Calcula la nueva posición // Calcula la nueva posición
mPosX += mVelX; mPosX += mVelX;
mPosY += mVelY; mPosY += mVelY;
@@ -146,8 +169,8 @@ void Item::move()
mVelX = -mVelX; mVelX = -mVelX;
} }
// Si se sale por arriba // Si se sale por arriba rebota (excepto la maquina de café)
if (mPosY < PLAY_AREA_TOP) if ((mPosY < PLAY_AREA_TOP) && !(mClass == ITEM_COFFEE_MACHINE))
{ {
// Corrige // Corrige
mPosY = PLAY_AREA_TOP; mPosY = PLAY_AREA_TOP;
@@ -168,6 +191,8 @@ void Item::move()
mAccelX = 0; mAccelX = 0;
mAccelY = 0; mAccelY = 0;
mPosY = PLAY_AREA_BOTTOM - mHeight; mPosY = PLAY_AREA_BOTTOM - mHeight;
if (mClass == ITEM_COFFEE_MACHINE)
mFloorCollision = true;
} }
// Actualiza la posición del sprite // Actualiza la posición del sprite
@@ -261,6 +286,14 @@ circle_t &Item::getCollider()
// Alinea el circulo de colisión con la posición del objeto // Alinea el circulo de colisión con la posición del objeto
void Item::shiftColliders() void Item::shiftColliders()
{ {
mCollider.x = Uint16(mPosX + mCollider.r); //mCollider.x = int(mPosX + mCollider.r);
mCollider.y = Uint16(mPosY + mCollider.r); //mCollider.y = int(mPosY + mCollider.r);
mCollider.x = int(mPosX + (mWidth / 2));
mCollider.y = int(mPosY + (mHeight / 2));
}
// Informa si el objeto ha colisionado con el suelo
bool Item::floorCollision()
{
return mFloorCollision;
} }

View File

@@ -9,6 +9,26 @@
// Clase AnimatedSprite // Clase AnimatedSprite
class 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
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
// Alinea el circulo de colisión con la posición del objeto
void shiftColliders();
public: public:
// Constructor // Constructor
Item(); Item();
@@ -17,7 +37,7 @@ public:
~Item(); ~Item();
// Iniciador // Iniciador
void init(Uint8 value, float x, float y, LTexture* texture, SDL_Renderer *renderer); void init(Uint8 value, float x, float y, LTexture *texture, SDL_Renderer *renderer);
// Centra el objeto en la posición X // Centra el objeto en la posición X
void allignTo(int x); void allignTo(int x);
@@ -64,40 +84,11 @@ public:
// Obtiene el circulo de colisión // Obtiene el circulo de colisión
circle_t &getCollider(); circle_t &getCollider();
// Temporizador con el tiempo que el objeto está presente // Temporizador con el tiempo que el objeto está presente
Uint16 mTimeToLive; Uint16 mTimeToLive;
private: // Informa si el objeto ha colisionado con el suelo
// Posición X,Y del objeto bool floorCollision();
float mPosX;
float mPosY;
// Alto y ancho del objeto
Uint8 mWidth;
Uint8 mHeight;
// Variables para controlar la velocidad del objeto
float mVelX;
float mVelY;
// Aceleración
float mAccelX;
float mAccelY;
// Sprite con los graficos del objeto
AnimatedSprite *mSprite;
// Especifica el tipo de objeto que es
Uint8 mClass;
// Especifica si está habilitado el objeto
bool mEnabled;
// Circulo de colisión del objeto
circle_t mCollider;
// Alinea el circulo de colisión con la posición del objeto
void shiftColliders();
}; };
#endif #endif

View File

@@ -1,10 +1,73 @@
#include "lang.h" #include "lang.h"
#include <iostream>
#include <fstream>
// Constructor
Lang::Lang(std::string *fileList)
{
mFileList = fileList;
}
// Destructor
Lang::~Lang()
{
}
// Inicializa los textos del juego en el idioma seleccionado // Inicializa los textos del juego en el idioma seleccionado
void initTextStrings(std::string *textStrings, Uint8 lang) bool Lang::setLang(Uint8 lang)
{ {
if ((lang < 0) || (lang > MAX_LANGUAGES)) std::string file;
lang = en_UK;
switch (lang)
{
case es_ES:
file = mFileList[49];
break;
case en_UK:
file = mFileList[50];
break;
case ba_BA:
file = mFileList[51];
break;
default:
file = mFileList[50];
break;
}
for (int i = 0; i < MAX_TEXT_STRINGS; i++) for (int i = 0; i < MAX_TEXT_STRINGS; i++)
textStrings[i] = gTextStrings[i][lang].c_str(); mTextStrings[i] = "";
bool success = false;
std::ifstream rfile(file);
if (rfile.is_open() && rfile.good())
{
success = true;
std::string buffer;
// lee el resto de datos del fichero
int index = 0;
int line_read = 0;
while (std::getline(rfile, buffer))
{
// Almacena solo las lineas impares
if (line_read % 2 == 1)
mTextStrings[index++] = buffer;
// Limpia el buffer
buffer.clear();
line_read++;
};
}
return success;
}
// Obtiene la cadena de texto del indice
std::string Lang::getText(int index)
{
return mTextStrings[index];
} }

View File

@@ -5,7 +5,7 @@
#ifndef LANG_H #ifndef LANG_H
#define LANG_H #define LANG_H
// iso codes // Lang codes
#define es_ES 0 #define es_ES 0
#define ba_BA 1 #define ba_BA 1
#define en_UK 2 #define en_UK 2
@@ -13,265 +13,25 @@
// Textos // Textos
#define MAX_TEXT_STRINGS 100 #define MAX_TEXT_STRINGS 100
const std::string gTextStrings[MAX_TEXT_STRINGS][3] =
{
// 0 - TITULO E INSTRUCCIONES
{"JUGAR",
"JUGAR",
"PLAY"},
// 1 // Clase Lang
{"OPCIONES", class Lang
"OPCIONS", {
"OPTIONS"}, private:
std::string *mFileList; // Lista de ficheros con los recursos
std::string mTextStrings[MAX_TEXT_STRINGS];
// 2 public:
{"INSTRUCCIONES", // Constructor
"INSTRUCCIONS", Lang(std::string *fileList);
"HOW TO PLAY"},
// 3 // Destructor
{"SALIR", ~Lang();
"EIXIR",
"QUIT"},
// 4 // Inicializa los textos del juego en el idioma seleccionado
{"VENTANA", bool setLang(Uint8 lang);
"FINESTRA",
"WINDOW"},
// 5
{"PANTALLA COMPLETA",
"PANTALLA COMPLETA",
"FULLSCREEN"},
// 6
{"PANTALLA COMPLETA FALSA",
"PANTALLA COMPLETA FALSA",
"FAKE FULLSCREEN"},
// 7
{"TAMA^O DE VENTANA",
"TAMANY DE FINESTRA",
"WINDOW SIZE"},
// 8
{"IDIOMA",
"IDIOMA",
"LANGUAGE"},
// 9
{"[ACEPTAR]",
"[ACEPTAR]",
"[ACCEPT]"},
// 10
{"[CANCELAR]",
"[CANCELAR]",
"[CANCEL]"},
// 11
{"OBJETIVO",
"OBJECTIU",
"OBJECTIVE"},
// 12
{"TIENES QUE EXPLOTAR",
"HAS D'EXPLOTAR",
"YOU HAVE TO POP AS MANY"},
// 13
{"TANTOS GLOBOS COMO PUEDAS",
"TANTS GLOBUS COM PUGUES",
"BALLOONS AS YOU CAN"},
// 14
{"LA DIFICULTAD SE INCREMENTA",
"LA DIFICULTAT AUGMENTA",
"DIFFICULTY WILL BE INCREASED"},
// 15
{"A MEDIDA QUE VAS PUNTUANDO",
"A MESURA QUE VAS PUNTUANT",
"AS YOU SCORE POINTS"},
// 16
{"OBJETOS",
"OBJECTES",
"ITEMS"},
// 17
{"1.000 PUNTOS",
"1.000 PUNTS",
"1.000 POINTS"},
// 18
{"2.500 PUNTOS",
"2.500 PUNTS",
"2.500 POINTS"},
// 19
{"5.000 PUNTOS",
"5.000 PUNTS",
"5.000 POINTS"},
// 20
{"DETIENE EL TIEMPO",
"PARA EL TEMPS",
"TIME STOPPER"},
// 21
{"VIDA EXTRA",
"VIDA EXTRA",
"EXTRA HIT"},
// 22
{"PULSA UNA TECLA PARA VOLVER",
"PREM UNA TECLA PER A TORNAR",
"PRESS ANY KEY TO RETURN"},
// 23
{"PULSA CUALQUIER TECLA",
"PREM QUALSEVOL TECLA",
"PRESS ANY KEY"},
// 24
{"ESPA^OL",
"ESPA^OL (ESPANYOL)",
"ESPA^OL (SPANISH)"},
// 25
{"BALOONCIA (VALENCIANO)",
"BALOONCIA",
"BALOONCIA (VALENCIAN)"},
// 26
{"ENGLISH (INGLES)",
"ENGLISH (ANGLES)",
"ENGLISH"},
// 27 - INTRO
{"Un dia cualquiera del a^o 2000",
"Un dia qualsevol de l'any 2000",
"Any day of the year 2000"},
// 28
{"Todo esta tranquilo en la UPV",
"Tot esta tranquil a la UPV",
"Everything is quiet at the UPV"},
// 29
{"Hasta que un desaprensivo...",
"Fins que un desaprensiu...",
"Until a bastard arrives..."},
// 30
{"HEY! VOY A SACARME UN TALLADET...",
"HEY! ME ANE A FERME UN CORTAET...",
" YO! GONNA TAKE A CAFELITO... "},
// 31
{"UAAAAAAAAAAAAA!!!",
"UAAAAAAAAAAAAA!!!",
"AAAAAAAARGHHHH!!!"},
// 32
{"Espera un momento...",
"Espera un moment...",
"Wait a moment..."},
// 33
{"Si no llevo suelto encima!",
"Si resulta que no tinc solt!",
" I don't have any loose! "},
// 34
{"MIERDA DE MAQUINA!",
"MERDA DE MAQUINA!",
"FUCKING MACHINE!"},
// 35
{"Blop... blop... blop...",
"Blop... blop... blop...",
"Blop... blop... blop..."},
// 36 - TEXTOS DEL JUEGO
{"Tiempo: ",
"Temps detes: ",
"Time Stopped: "},
// 37
{"D E M O",
"D E M O",
"D E M O"},
// 38
{"FASE ",
"PANTALLA ",
"STAGE "},
// 39 - MARCADOR
{"PUNTOS",
"PUNTS",
"SCORE"},
// 40
{"MAX.PUNT.",
"MAX.PUNT.",
"HI-SCORE"},
// 41
{"MULT",
"MULT",
"MULT"},
// 42
{"FASE ",
"PANTALLA ",
"STAGE "},
// 43 - PANTALLA DE GAME OVER
{"FIN DE JUEGO",
"FI DEL JOC",
"GAME OVER"},
// 44
{"TU PUNTUACION: ",
"ELS TEUS PUNTS: ",
"YOUR SCORE: "},
// 45
{"REINTENTAR?",
"REINTENTAR?",
"RETRY?"},
// 46 - MENU DE PAUSA
{"CONTINUAR",
"CONTINUAR",
"CONTINUE"},
// 47
{"SALIR DEL JUEGO ",
"EIXIR DEL JOC",
"LEAVE GAME"},
// 48 - MENU GAME OVER
{"SI",
"SI",
"YES"},
// 49
{"NO",
"NO",
"NO"},
// 50 - TEXTO DE COMPLETAR EL JUEGO
{"FELICIDADES!!",
"FELICITATS!!",
"CONGRATULATIONS!!"},
// Obtiene la cadena de texto del indice
std::string getText(int index);
}; };
void initTextStrings(std::string *textStrings, Uint8 lang);
#endif #endif

View File

@@ -4,6 +4,9 @@
#include <dirent.h> #include <dirent.h>
#endif #endif
# define INIT_FADE 100
# define END_LOGO 200
// Constructor // Constructor
Logo::Logo(SDL_Renderer *renderer, std::string *fileList) Logo::Logo(SDL_Renderer *renderer, std::string *fileList)
{ {
@@ -71,6 +74,7 @@ section_t Logo::run()
{ {
init(); init();
const SDL_Rect rect = {0, 0, SCREEN_WIDTH, SCREEN_HEIGHT}; const SDL_Rect rect = {0, 0, SCREEN_WIDTH, SCREEN_HEIGHT};
const int fadeLenght = END_LOGO - INIT_FADE;
while (mSection.name == PROG_SECTION_LOGO) while (mSection.name == PROG_SECTION_LOGO)
{ {
@@ -92,9 +96,6 @@ section_t Logo::run()
} }
} }
// Cambia el destino donde se pinta todo
//SDL_SetRenderTarget(mRenderer, mBackbuffer);
// Limpia el destino // Limpia el destino
SDL_SetRenderDrawColor(mRenderer, bgColor.r, bgColor.g, bgColor.b, 255); SDL_SetRenderDrawColor(mRenderer, bgColor.r, bgColor.g, bgColor.b, 255);
SDL_RenderClear(mRenderer); SDL_RenderClear(mRenderer);
@@ -103,22 +104,16 @@ section_t Logo::run()
mSprite->render(); mSprite->render();
// Dibuja el fade // Dibuja el fade
if (mCounter >= 200) if (mCounter >= INIT_FADE)
{ {
Uint16 alpha = mCounter - 200; Uint16 alpha = (255 * (mCounter - INIT_FADE)) / fadeLenght;
if (alpha < 256) if (alpha < 256)
SDL_SetRenderDrawColor(mRenderer, bgColor.r, bgColor.g, bgColor.b, alpha); SDL_SetRenderDrawColor(mRenderer, bgColor.r, bgColor.g, bgColor.b, alpha);
else else
SDL_SetRenderDrawColor(mRenderer, bgColor.r, bgColor.g, bgColor.b, 255); // alpha - 0 trans, 255 opaco SDL_SetRenderDrawColor(mRenderer, bgColor.r, bgColor.g, bgColor.b, 255);
SDL_RenderFillRect(mRenderer, &rect); SDL_RenderFillRect(mRenderer, &rect);
} }
// Vuelve a usar el renderizador como destino
//SDL_SetRenderTarget(mRenderer, NULL);
// Copia el backbufer al renderizador
//SDL_RenderCopy(mRenderer, mBackbuffer, NULL, NULL);
// Actualiza la pantalla // Actualiza la pantalla
SDL_RenderPresent(mRenderer); SDL_RenderPresent(mRenderer);
@@ -134,7 +129,7 @@ section_t Logo::run()
JA_StopMusic(); JA_StopMusic();
} }
if (mCounter == 500) // minimo 200 + 255 if (mCounter == END_LOGO + 20)
{ {
mCounter = 0; mCounter = 0;
mSection.name = PROG_SECTION_INTRO; mSection.name = PROG_SECTION_INTRO;

View File

@@ -1,9 +1,7 @@
/* /*
This source code copyrighted by JailDesigner (2020) Código fuente creado por JailDesigner (2020)
started on Castalla 15-07-2020. Empezado en Castalla el 15/07/2020.
*/
/*
Descripción del enfoque utilizado para crear el juego. Descripción del enfoque utilizado para crear el juego.
El programa contine una serie de clases/objetos básicos: la clase sprite El programa contine una serie de clases/objetos básicos: la clase sprite
@@ -38,24 +36,22 @@ un tipo asociado diferente a NO_KIND
#include "director.h" #include "director.h"
#include <stdio.h> #include <stdio.h>
#include <string>
int main(int argc, char *args[]) int main(int argc, char *args[])
{ {
// Inicia el generador de numeros aleatorios
srand(time(nullptr));
// Crea el objeto mDirector
Director *mDirector = new Director(args[0]);
printf("Starting the game...\n\n"); printf("Starting the game...\n\n");
// Crea el objeto Director
Director *mDirector = new Director(args[0]);
// Bucle principal // Bucle principal
mDirector->run(); mDirector->run();
// Libera todos los recursos y cierra SDL // Destruye el objeto Director
delete mDirector; delete mDirector;
mDirector = nullptr; mDirector = nullptr;
printf("Shutting down the game...\n");
printf("\nShutting down the game...\n");
return 0; return 0;
} }

View File

@@ -28,7 +28,6 @@ void Menu::init(std::string name, int x, int y, int backgroundType)
mSelector.index = 0; mSelector.index = 0;
mTotalItems = 0; mTotalItems = 0;
mItemSelected = MENU_NO_OPTION; mItemSelected = MENU_NO_OPTION;
mVerticalPadding = 1;
mPosX = x; mPosX = x;
mPosY = y; mPosY = y;
mRectBG.rect.x = 0; mRectBG.rect.x = 0;
@@ -38,51 +37,44 @@ void Menu::init(std::string name, int x, int y, int backgroundType)
mRectBG.r = 0; mRectBG.r = 0;
mRectBG.g = 0; mRectBG.g = 0;
mRectBG.b = 0; mRectBG.b = 0;
mSelector.rect.x = 0; mBackgroundType = backgroundType;
mSelector.rect.y = 0; mIsCenteredOnX = false;
mSelector.rect.w = 0; mIsCenteredOnY = false;
mSelector.rect.h = 0; mAreElementsCenteredOnX = false;
mCenterX = 0;
mCenterY = 0;
mWidestItem = 0;
mColorGreyed = {128, 128, 128};
// Selector
mSelector.originY = 0;
mSelector.targetY = 0;
mSelector.despY = 0;
mSelector.originH = 0;
mSelector.targetH = 0;
mSelector.incH = 0;
mSelector.y = 0.0f;
mSelector.h = 0.0f;
mSelector.numJumps = 8;
mSelector.moving = false;
mSelector.resizing = false;
mSelector.rect = {0, 0, 0, 0};
mSelector.r = 0; mSelector.r = 0;
mSelector.g = 0; mSelector.g = 0;
mSelector.b = 0; mSelector.b = 0;
mSelector.a = 255; mSelector.a = 255;
mBackgroundType = backgroundType;
mIsCentered = false;
mAreElementsCentered = false;
mCenter = x + ((SCREEN_WIDTH - x) / 2);
mWidestItem = 0;
// Selector
mSelector.origin = 0;
mSelector.target = 0;
mSelector.y = 0;
mSelector.numJumps = 4;
mSelector.despY = 0;
mSelector.moving = false;
// Sprite con los graficos del selector
//mSelectorSprite.setWidth(8);
//mSelectorSprite.setHeight(8);
//mSelectorSprite.setPosX(0);
//mSelectorSprite.setPosY(0);
//mSelectorSprite.setTexture(texture);
//mSelectorSprite.setRenderer(renderer);
//mSelectorSprite.setSpriteClip(0, 0, mSelectorSprite.getWidth(), mSelectorSprite.getHeight());
// Elementos del menu // Elementos del menu
for (int i = 0; i < 10; i++) for (int i = 0; i < MENU_MAX_ITEMS; i++)
{ {
mItem[i].label = ""; mItem[i].label = "";
mItem[i].w = 0; mItem[i].rect = {0, 0, 0, 0};
mItem[i].h = 0;
mItem[i].x = 0;
mItem[i].y = 0;
mItem[i].hPaddingUp = 0;
mItem[i].hPaddingDown = 0; mItem[i].hPaddingDown = 0;
mItem[i].selectable = false;
mItem[i].greyed = false;
mItem[i].linkedDown = false;
mItem[i].linkedUp = false;
} }
// Mueve el grafico del selector al elemento seleccionado
//moveSelectorSprite(mSelector.index);
} }
// Carga los recursos necesarios para la sección 'Title' // Carga los recursos necesarios para la sección 'Title'
@@ -108,57 +100,70 @@ std::string Menu::getName()
// Obtiene el valor de la variable // Obtiene el valor de la variable
Uint8 Menu::getItemSelected() Uint8 Menu::getItemSelected()
{ {
// Al llamar a esta funcion, se obtiene el valor y se borra
const int temp = mItemSelected; const int temp = mItemSelected;
mItemSelected = MENU_NO_OPTION; mItemSelected = MENU_NO_OPTION;
return temp; return temp;
} }
// Mueve el grafico del selector al elemento seleccionado
/*void Menu::moveSelectorSprite(int pos)
{
mSelector.rect.y = mItem[pos].y - 1;
}*/
// Actualiza la posicion y el estado del selector // Actualiza la posicion y el estado del selector
void Menu::updateSelector() void Menu::updateSelector()
{ {
if (mSelector.moving) if (mSelector.moving)
{ {
// Calcula el desplazamiento en Y
mSelector.y += mSelector.despY; mSelector.y += mSelector.despY;
if (mSelector.despY > 0) // Va hacia abajo if (mSelector.despY > 0) // Va hacia abajo
{ {
if (mSelector.y > mSelector.target) // Ha llegado al destino if (mSelector.y > mSelector.targetY) // Ha llegado al destino
{ {
mSelector.origin = mSelector.y = mSelector.target; mSelector.originY = mSelector.y = mSelector.targetY;
mSelector.moving = false; mSelector.moving = false;
} }
} }
if (mSelector.despY < 0) // Va hacia abajo if (mSelector.despY < 0) // Va hacia arriba
{ {
if (mSelector.y < mSelector.target) // Ha llegado al destino if (mSelector.y < mSelector.targetY) // Ha llegado al destino
{ {
mSelector.origin = mSelector.y = mSelector.target; mSelector.originY = mSelector.y = mSelector.targetY;
mSelector.moving = false; mSelector.moving = false;
} }
} }
mSelector.rect.y = int(mSelector.y) - 1; mSelector.rect.y = int(mSelector.y);
} }
else else
{ {
mSelector.rect.y = int(mSelector.y) - 1; mSelector.rect.y = int(mSelector.y);
} }
}
// Establece el origen del selector if (mSelector.resizing)
void Menu::setSelectorOrigin(int value) {
{ // Calcula el incremento en H
mSelector.origin = value; mSelector.h += mSelector.incH;
} if (mSelector.incH > 0) // Crece
{
// Establece el destino del selector if (mSelector.h > mSelector.targetH) // Ha llegado al destino
void Menu::setSelectorTarget(int value) {
{ //mSelector.originH = mSelector.targetH = mSelector.rect.h = getSelectorHeight(mSelector.index);
mSelector.target = value; mSelector.originH = mSelector.h = mSelector.targetH;
mSelector.resizing = false;
}
}
if (mSelector.incH < 0) // Decrece
{
if (mSelector.h < mSelector.targetH) // Ha llegado al destino
{
//mSelector.originH = mSelector.targetH = mSelector.rect.h = getSelectorHeight(mSelector.index);
mSelector.originH = mSelector.h = mSelector.targetH;
mSelector.resizing = false;
}
}
mSelector.rect.h = int(mSelector.h);
}
else
{
mSelector.rect.h = getSelectorHeight(mSelector.index);
}
} }
// Coloca el selector en una posición específica // Coloca el selector en una posición específica
@@ -167,8 +172,12 @@ void Menu::setSelectorPos(Uint8 index)
if (index < mTotalItems) if (index < mTotalItems)
{ {
mSelector.index = index; mSelector.index = index;
mSelector.y = mSelector.origin = mSelector.target = mItem[mSelector.index].y; mSelector.rect.y = mSelector.y = mSelector.originY = mSelector.targetY = mItem[mSelector.index].rect.y;
mSelector.rect.w = mRectBG.rect.w;
mSelector.rect.x = mRectBG.rect.x;
mSelector.originH = mSelector.targetH = mSelector.rect.h = getSelectorHeight(mSelector.index);
mSelector.moving = false; mSelector.moving = false;
mSelector.resizing = false;
} }
} }
@@ -179,12 +188,8 @@ Uint16 Menu::getWidestItem()
// Obtenemos la anchura del item mas ancho // Obtenemos la anchura del item mas ancho
for (int i = 0; i < mTotalItems; i++) for (int i = 0; i < mTotalItems; i++)
{ if (mItem[i].rect.w > result)
if (mItem[i].w > result) result = mItem[i].rect.w;
{
result = mItem[i].w;
}
}
return result; return result;
} }
@@ -194,42 +199,55 @@ void Menu::reset()
{ {
mItemSelected = MENU_NO_OPTION; mItemSelected = MENU_NO_OPTION;
mSelector.index = 0; mSelector.index = 0;
//moveSelectorSprite(mSelector.index); mSelector.originY = mSelector.targetY = mSelector.y = mItem[0].rect.y;
mSelector.origin = mSelector.target = mSelector.y = mItem[0].y; mSelector.originH = mSelector.targetH = mItem[0].rect.h;
mSelector.moving = false; mSelector.moving = false;
} mSelector.resizing = false;
// Deja el menu sin elemento seleccionado
void Menu::deselectItem()
{
mItemSelected = MENU_NO_OPTION;
} }
// Actualiza el menu para recolocarlo correctamente y establecer el tamaño // Actualiza el menu para recolocarlo correctamente y establecer el tamaño
void Menu::reorganize() void Menu::reorganize()
{ {
setRectSize(); setRectSize();
if (mIsCentered) if (mIsCenteredOnX)
centerMenu(mCenter); centerMenuOnX(mCenterX);
if (mAreElementsCentered) if (mIsCenteredOnY)
centerMenuElements(); centerMenuOnY(mCenterY);
if (mAreElementsCenteredOnX)
centerMenuElementsOnX();
} }
// Deja el menu apuntando al siguiente elemento // Deja el menu apuntando al siguiente elemento
bool Menu::increaseSelectorIndex() bool Menu::increaseSelectorIndex()
{ {
bool success = false; bool success = false;
mSelector.y = mSelector.origin = mItem[mSelector.index].y;
// Obten las coordenadas del elemento actual
mSelector.y = mSelector.originY = mItem[mSelector.index].rect.y;
mSelector.h = mSelector.originH = getSelectorHeight(mSelector.index);
// Calcula cual es el siguiente elemento
if (mSelector.index < (mTotalItems - 1)) if (mSelector.index < (mTotalItems - 1))
{ {
mSelector.index++; mSelector.index++;
while ((!mItem[mSelector.index].selectable) && (mSelector.index < (mTotalItems - 1)))
mSelector.index++;
success = true; success = true;
} }
mSelector.target = mItem[mSelector.index].y; if (success)
mSelector.despY = (mSelector.target - mSelector.origin) / mSelector.numJumps; { // Establece las coordenadas y altura de destino
mSelector.moving = true; mSelector.targetY = mItem[mSelector.index].rect.y;
mSelector.despY = (mSelector.targetY - mSelector.originY) / mSelector.numJumps;
mSelector.targetH = getSelectorHeight(mSelector.index);
mSelector.incH = (mSelector.targetH - mSelector.originH) / mSelector.numJumps;
mSelector.moving = true;
if (mSelector.incH != 0)
mSelector.resizing = true;
}
return success; return success;
} }
@@ -237,17 +255,33 @@ bool Menu::increaseSelectorIndex()
bool Menu::decreaseSelectorIndex() bool Menu::decreaseSelectorIndex()
{ {
bool success = false; bool success = false;
mSelector.y = mSelector.origin = mItem[mSelector.index].y;
// Obten las coordenadas del elemento actual
mSelector.y = mSelector.originY = mItem[mSelector.index].rect.y;
mSelector.h = mSelector.originH = getSelectorHeight(mSelector.index);
// Calcula cual es el siguiente elemento
if (mSelector.index > 0) if (mSelector.index > 0)
{ {
mSelector.index--; mSelector.index--;
while ((!mItem[mSelector.index].selectable) && (mSelector.index > 0))
mSelector.index--;
success = true; success = true;
} }
mSelector.target = mItem[mSelector.index].y; if (success)
mSelector.despY = (mSelector.target - mSelector.origin) / mSelector.numJumps; { // Establece las coordenadas y altura de destino
mSelector.moving = true; mSelector.targetY = mItem[mSelector.index].rect.y;
mSelector.despY = (mSelector.targetY - mSelector.originY) / mSelector.numJumps;
mSelector.targetH = getSelectorHeight(mSelector.index);
mSelector.incH = (mSelector.targetH - mSelector.originH) / mSelector.numJumps;
mSelector.moving = true;
if (mSelector.incH != 0)
mSelector.resizing = true;
}
return success; return success;
} }
@@ -268,8 +302,11 @@ void Menu::render()
} }
// Renderiza el rectangulo del selector // Renderiza el rectangulo del selector
SDL_Rect temp = mSelector.rect;
temp.y--;
temp.h++;
SDL_SetRenderDrawColor(mRenderer, mSelector.r, mSelector.g, mSelector.b, mSelector.a); SDL_SetRenderDrawColor(mRenderer, mSelector.r, mSelector.g, mSelector.b, mSelector.a);
SDL_RenderFillRect(mRenderer, &mSelector.rect); SDL_RenderFillRect(mRenderer, &temp);
// Renderiza el borde del fondo // Renderiza el borde del fondo
if (mBackgroundType == MENU_BACKGROUND_SOLID) if (mBackgroundType == MENU_BACKGROUND_SOLID)
@@ -278,65 +315,63 @@ void Menu::render()
SDL_RenderDrawRect(mRenderer, &mRectBG.rect); SDL_RenderDrawRect(mRenderer, &mRectBG.rect);
} }
// Renderiza el sprite del selector // Renderitza el texto
//mSelectorSprite.render();
// Renderitza el text
for (int i = 0; i < mTotalItems; i++) for (int i = 0; i < mTotalItems; i++)
{ {
if (i == mSelector.index) if (i == mSelector.index)
{ {
const color_t color = {mSelector.itemR, mSelector.itemG, mSelector.itemB}; const color_t color = {mSelector.itemR, mSelector.itemG, mSelector.itemB};
mText->writeColored(mItem[i].x, mItem[i].y, mItem[i].label, color); mText->writeColored(mItem[i].rect.x, mItem[i].rect.y, mItem[i].label, color);
} }
else else if (mItem[i].selectable)
{ {
mText->write(mItem[i].x, mItem[i].y, mItem[i].label, 0); mText->write(mItem[i].rect.x, mItem[i].rect.y, mItem[i].label);
} }
else if (mItem[i].greyed)
{
mText->writeColored(mItem[i].rect.x, mItem[i].rect.y, mItem[i].label, mColorGreyed);
}
else // No seleccionable
{
if ((mItem[i].linkedUp) && (i == mSelector.index + 1))
{
const color_t color = {mSelector.itemR, mSelector.itemG, mSelector.itemB};
mText->writeColored(mItem[i].rect.x, mItem[i].rect.y, mItem[i].label, color);
}
else // No enlazado con el de arriba
{
mText->write(mItem[i].rect.x, mItem[i].rect.y, mItem[i].label);
}
}
//borrar
//mText->write(0, 0, std::to_string(mSelector.h) + " " + std::to_string(mSelector.incH) + " " + std::to_string(mSelector.resizing));
//mText->write(0, 8, std::to_string(mSelector.y) + " " + std::to_string(mSelector.despY) + " " + std::to_string(mSelector.moving));
} }
} }
// Establece el rectangulo de fondo del menu y el selector // Establece el rectangulo de fondo del menu y el selector
void Menu::setRectSize() void Menu::setRectSize()
{ {
Uint8 i = 0; mRectBG.rect.w = findWidth() + mText->getCharacterWidth();
mRectBG.rect.w = 0; mRectBG.rect.h = findHeight() + mText->getCharacterWidth();
mRectBG.rect.h = 0;
mSelector.rect.w = 0;
mSelector.rect.h = 0;
// Obtenemos la anchura del item mas ancho y la altura de la suma de alturas de los items // La posición X es la del menú menos medio caracter
for (i = 0; i < mTotalItems; i++) mRectBG.rect.x = mPosX - (mText->getCharacterWidth() / 2);
{
if (mItem[i].w > mRectBG.rect.w)
{
mRectBG.rect.w = mItem[i].w;
}
mRectBG.rect.h += mItem[i].h + mItem[i].hPaddingDown;
}
// La anchura de la cadena más larga, mas un caracter, mas la anchura del sprite del selector // La posición Y es la del menu menos la altura de medio caracter
mRectBG.rect.w += (mText->getSize() * 1); // + mSelectorSprite.getWidth(); mRectBG.rect.y = mPosY - (mText->getCharacterWidth() / 2);
// La altura de la suma de los items mas un caracter y menos un pixel (porque el texto en realidad es de 7 pixeles)
mRectBG.rect.h += (mText->getSize() * 1) - 1;
// La posición X es la del menú menos la anchura del sprite del selector y menos medio caracter
mRectBG.rect.x = mPosX - (mText->getSize() / 2); // - mSelectorSprite.getWidth();
// La posición Y es la del menu menos la altura de medio caracter i el padding
mRectBG.rect.y = mPosY - (mText->getSize() / 2) - mVerticalPadding;
// Establecemos los valores del rectangulo del selector a partir de los valores del rectangulo de fondo // Establecemos los valores del rectangulo del selector a partir de los valores del rectangulo de fondo
mSelector.rect.h = (mText->getSize() * 1) + 1; setSelectorPos(mSelector.index);
mSelector.rect.w = mRectBG.rect.w;
mSelector.rect.x = mRectBG.rect.x;
} }
// Establece el valor de la variable // Establece el valor de la variable
void Menu::setTotalItems(int num) void Menu::setTotalItems(int num)
{ {
mTotalItems = num; mTotalItems = num;
if (mTotalItems > MENU_MAX_ITEMS)
mTotalItems = MENU_MAX_ITEMS;
} }
// Establece el color del rectangulo de fondo // Establece el color del rectangulo de fondo
@@ -365,89 +400,86 @@ void Menu::setSelectorTextColor(int r, int g, int b)
mSelector.itemB = b; mSelector.itemB = b;
} }
// Centra el menu respecto un punto // Centra el menu respecto un punto en el eje X
void Menu::centerMenu(int value) void Menu::centerMenuOnX(int value)
{ {
mIsCentered = true; mIsCenteredOnX = true;
mCenter = value; mCenterX = value;
// Actualiza el rectangulo de fondo para recalcular las dimensiones // Actualiza el rectangulo de fondo para recalcular las dimensiones
setRectSize(); //setRectSize();
// Obten el acho del menu
mWidestItem = getWidestItem();
// Establece la nueva posición centrada en funcion del elemento más ancho // Establece la nueva posición centrada en funcion del elemento más ancho
mPosX = (value) - (mWidestItem / 2); mPosX = (value) - (findWidth() / 2);
// Reposiciona los elementos del menu // Reposiciona los elementos del menu
for (int i = 0; i < 10; i++) for (int i = 0; i < MENU_MAX_ITEMS; i++)
{ mItem[i].rect.x = mPosX;
mItem[i].x = mPosX;
}
// Recalcula el rectangulo de fondo // Recalcula el rectangulo de fondo
setRectSize(); setRectSize();
// Recoloca el selector
mSelector.origin = mSelector.target = mSelector.y = mItem[mSelector.index].y;
mSelector.moving = false;
//moveSelectorSprite(mSelector.index);
} }
// Centra los elementos del menu // Centra el menu respecto un punto en el eje Y
void Menu::centerMenuElements() void Menu::centerMenuOnY(int value)
{ {
mAreElementsCentered = true; mIsCenteredOnY = true;
mCenterY = value;
// Actualiza el rectangulo de fondo para recalcular las dimensiones
//setRectSize();
// Establece la nueva posición centrada en funcion del elemento más ancho
mPosY = (value) - (findHeight() / 2);
// Reposiciona los elementos del menu
replaceElementsOnY();
// Recalcula el rectangulo de fondo
setRectSize();
}
// Centra los elementos del menu en el eje X
void Menu::centerMenuElementsOnX()
{
mAreElementsCenteredOnX = true;
for (int i = 0; i < mTotalItems; i++) for (int i = 0; i < mTotalItems; i++)
{ mItem[i].rect.x = (mCenterX - (mItem[i].rect.w / 2));
//mItem[i].x = (mCenter - ((mText->lenght(mItem[i].label, 0)) / 2));
mItem[i].x = (mCenter - (mItem[i].w / 2));
}
// Mueve el grafico del selector al elemento seleccionado
//moveSelectorSprite(mSelector.index);
} }
// Añade un item al menu // Añade un item al menu
void Menu::addItem(std::string text, const Uint8 hPaddingUp, const Uint8 hPaddingDown) void Menu::addItem(std::string text, Uint8 hPaddingDown, bool selectable, bool greyed, bool linkedDown)
{ {
// Si es el primer item coge la posición y del propio menu // Si es el primer item coge la posición en el eje Y del propio menu
if (mTotalItems == 0) if (mTotalItems == 0)
{ mItem[mTotalItems].rect.y = mPosY;
mItem[mTotalItems].label = text;
mItem[mTotalItems].w = mText->lenght(mItem[mTotalItems].label, 0);
mItem[mTotalItems].h = mText->getSize() + (mVerticalPadding * 2);
mItem[mTotalItems].x = mPosX;
mItem[mTotalItems].y = mPosY;
mItem[mTotalItems].hPaddingUp = hPaddingUp;
mItem[mTotalItems].hPaddingDown = hPaddingDown;
}
else else
{ // En caso contrario, coge la posición en el eje Y a partir del elemento anterior
// En caso contrario, coge la posición y a partir del elemento anterior mItem[mTotalItems].rect.y = mItem[mTotalItems - 1].rect.y + mItem[mTotalItems - 1].rect.h + mItem[mTotalItems - 1].hPaddingDown;
if (mTotalItems < 10)
{ setItemCaption(mTotalItems, text);
mItem[mTotalItems].label = text; mItem[mTotalItems].rect.x = mPosX;
mItem[mTotalItems].w = mText->lenght(mItem[mTotalItems].label, 0); mItem[mTotalItems].hPaddingDown = hPaddingDown;
mItem[mTotalItems].h = mText->getSize() + (mVerticalPadding * 2); mItem[mTotalItems].selectable = selectable;
mItem[mTotalItems].x = mPosX; mItem[mTotalItems].greyed = greyed;
mItem[mTotalItems].y = mItem[mTotalItems - 1].y + mItem[mTotalItems - 1].h + mItem[mTotalItems - 1].hPaddingDown; mItem[mTotalItems].linkedDown = linkedDown;
mItem[mTotalItems].hPaddingUp = hPaddingUp; if (mTotalItems > 0)
mItem[mTotalItems].hPaddingDown = hPaddingDown; if (mItem[mTotalItems - 1].linkedDown)
} mItem[mTotalItems].linkedUp = true;
}
setTotalItems(mTotalItems + 1); setTotalItems(mTotalItems + 1);
mCenterX = mPosX + (findWidth() / 2);
//setSelectorPos(0);
reorganize(); reorganize();
setSelectorPos(0);
} }
// Cambia el texto de un item // Cambia el texto de un item
void Menu::setItemCaption(Uint8 index, std::string text) void Menu::setItemCaption(Uint8 index, std::string text)
{ {
mItem[index].label = text; mItem[index].label = text;
mItem[index].w = mText->lenght(mItem[index].label, 0); mItem[index].rect.w = mText->lenght(mItem[index].label);
mItem[index].rect.h = mText->getCharacterWidth();
reorganize(); reorganize();
} }
@@ -483,4 +515,58 @@ void Menu::checkInput()
mItemSelected = mDefaultActionWhenCancel; mItemSelected = mDefaultActionWhenCancel;
JA_PlaySound(mSoundCancel); JA_PlaySound(mSoundCancel);
} }
}
// Calcula el ancho del menu
Uint16 Menu::findWidth()
{
return getWidestItem();
}
// Calcula el alto del menu
Uint16 Menu::findHeight()
{
Uint16 height = 0;
// Obtenemos la altura de la suma de alturas de los items
for (int i = 0; i < mTotalItems; i++)
height += mItem[i].rect.h + mItem[i].hPaddingDown;
return height - mItem[mTotalItems - 1].hPaddingDown;
}
// Recoloca los elementos del menu en el eje Y
void Menu::replaceElementsOnY()
{
mItem[0].rect.y = mPosY;
for (int i = 1; i < mTotalItems; i++)
mItem[i].rect.y = mItem[i - 1].rect.y + mItem[i - 1].rect.h + mItem[i - 1].hPaddingDown;
}
// Establece el estado seleccionable de un item
void Menu::setSelectable(Uint8 index, bool value)
{
mItem[index].selectable = value;
}
// Establece el estado agrisado de un item
void Menu::setGreyed(Uint8 index, bool value)
{
mItem[index].greyed = value;
}
// Establece el estado de enlace de un item
void Menu::setLinkedDown(Uint8 index, bool value)
{
mItem[index].linkedDown = value;
}
// Calcula la altura del selector
int Menu::getSelectorHeight(int value)
{
if (mItem[value].linkedDown)
return mItem[value].rect.h + mItem[value].hPaddingDown + mItem[value + 1].rect.h;
else
return mItem[value].rect.h;
} }

View File

@@ -8,30 +8,35 @@
#ifndef MENU_H #ifndef MENU_H
#define MENU_H #define MENU_H
#define MENU_MAX_ITEMS 50
// Clase menu // Clase menu
class Menu class Menu
{ {
private: private:
std::string mName; // Nombre del menu
int mPosX; // Posición en el eje X de la primera letra del primer elemento int mPosX; // Posición en el eje X de la primera letra del primer elemento
int mPosY; // Posición en el eje Y de la primera letra del primer elemento int mPosY; // Posición en el eje Y de la primera letra del primer elemento
std::string mName; // Nombre del menu Uint16 mHeight; // Altura del menu
Uint16 mWidth; // Anchura del menu
Uint8 mTotalItems; // Numero total de items del menu Uint8 mTotalItems; // Numero total de items del menu
int mItemSelected; // Índice del item del menu que ha sido seleccionado int mItemSelected; // Índice del item del menu que ha sido seleccionado
Uint8 mDefaultActionWhenCancel; // Indice del item del menu que se selecciona cuando se cancela el menu Uint8 mDefaultActionWhenCancel; // Indice del item del menu que se selecciona cuando se cancela el menu
Uint8 mVerticalPadding; // Espacio de separacion entre items
Uint8 mBackgroundType; // Tipo de fondo para el menu Uint8 mBackgroundType; // Tipo de fondo para el menu
Sprite *mSelectorSprite; // Sprite con los graficos del selector bool mIsCenteredOnX; // Variable para saber si el menu debe estar centrado respecto a un punto en el eje X
Text *mText; // Texto para poder escribir los items del menu bool mIsCenteredOnY; // Variable para saber si el menu debe estar centrado respecto a un punto en el eje Y
SDL_Renderer *mRenderer; // Puntero al renderizador de la ventana int mCenterX; // Centro del menu en el eje X
std::string *mFileList; // Lista de ficheros int mCenterY; // Centro del menu en el eje Y
bool mIsCentered; // Variable para saber si el menu debe estar centrado respecto a un punto bool mAreElementsCenteredOnX; // Variable para saber si los elementos van centrados en el eje X
int mCenter; // Centro del menu
bool mAreElementsCentered; // Variable para saber si los elementos van centrados
Uint16 mWidestItem; // Anchura del elemento más ancho Uint16 mWidestItem; // Anchura del elemento más ancho
JA_Sound mSoundAccept; // Sonido al aceptar o elegir una opción del menu JA_Sound mSoundAccept; // Sonido al aceptar o elegir una opción del menu
JA_Sound mSoundCancel; // Sonido al cancelar el menu JA_Sound mSoundCancel; // Sonido al cancelar el menu
JA_Sound mSoundMove; // Sonido al mover el selector JA_Sound mSoundMove; // Sonido al mover el selector
SDL_Renderer *mRenderer; // Puntero al renderizador de la ventana
std::string *mFileList; // Lista de ficheros
Text *mText; // Texto para poder escribir los items del menu
Input *mInput; // Gestor de eventos de entrada de teclado o gamepad Input *mInput; // Gestor de eventos de entrada de teclado o gamepad
color_t mColorGreyed; // Color para los elementos agrisados
struct rectangle struct rectangle
{ {
@@ -46,23 +51,28 @@ private:
struct item struct item
{ {
std::string label; // Texto std::string label; // Texto
int x; // Posición en el eje X de la primera letra del elemento SDL_Rect rect; // Rectangulo que delimita el elemento
int y; // Posición en el eje Y de la primera letra del elemento
Uint8 w; // Ancho del elemento
Uint8 h; // Alto del elemento
Uint8 hPaddingUp; // Espaciado sobre el elemento
Uint8 hPaddingDown; // Espaciado bajo el elemento Uint8 hPaddingDown; // Espaciado bajo el elemento
bool selectable; // Indica si se puede seleccionar
bool greyed; // Indica si ha de aparecer con otro color mas oscuro
bool linkedDown; // Indica si el elemento actual y el siguiente se tratan como uno solo. Afecta al selector
bool linkedUp; // Indica si el elemento actual y el anterior se tratan como uno solo. Afecta al selector
}; };
item mItem[10]; // Estructura para cada elemento del menu item mItem[MENU_MAX_ITEMS]; // Estructura para cada elemento del menu
struct selector struct selector
{ {
double origin; // Coordenada de origen float originY; // Coordenada de origen
double target; // Coordenada de destino float targetY; // Coordenada de destino
double y; // Coordenada actual float despY; // Cantidad de pixeles que se desplaza el selector en cada salto: (target - origin) / numJumps
Uint8 numJumps; // Numero de pasos preestablecido para llegar al destino
double despY; // Cantidad de pixeles que se desplaza el selector en cada salto: (target - origin) / numJumps
bool moving; // Indica si el selector está avanzando hacia el destino bool moving; // Indica si el selector está avanzando hacia el destino
float originH; // Altura de origen
float targetH; // Altura de destino
float incH; // Cantidad de pixels que debe incrementar o decrementar el selector en cada salto
bool resizing; // Indica si el selector está cambiando de tamaño
float y; // Coordenada actual, usado para el desplazamiento
float h; // Altura actual, usado para el cambio de tamaño
Uint8 numJumps; // Numero de pasos preestablecido para llegar al destino
Uint8 index; // Elemento del menu que tiene el foco Uint8 index; // Elemento del menu que tiene el foco
SDL_Rect rect; // Rectangulo del selector SDL_Rect rect; // Rectangulo del selector
Uint8 r; // Cantidad de color rojo para el rectangulo del selector Uint8 r; // Cantidad de color rojo para el rectangulo del selector
@@ -93,24 +103,27 @@ private:
// Deja el menu apuntando al elemento anterior // Deja el menu apuntando al elemento anterior
bool decreaseSelectorIndex(); bool decreaseSelectorIndex();
// Mueve el grafico del selector al elemento seleccionado
//void moveSelectorSprite(int pos);
// Actualiza la posicion y el estado del selector // Actualiza la posicion y el estado del selector
void updateSelector(); void updateSelector();
// Establece el origen del selector
void setSelectorOrigin(int value);
// Establece el destino del selector
void setSelectorTarget(int value);
// Obtiene la anchura del elemento más ancho del menu // Obtiene la anchura del elemento más ancho del menu
Uint16 getWidestItem(); Uint16 getWidestItem();
// Gestiona la entrada de teclado y mando durante el menu // Gestiona la entrada de teclado y mando durante el menu
void checkMenuInput(Menu *menu); void checkMenuInput(Menu *menu);
// Calcula el ancho del menu
Uint16 findWidth();
// Calcula el alto del menu
Uint16 findHeight();
// Recoloca los elementos del menu en el eje Y
void replaceElementsOnY();
// Calcula la altura del selector
int getSelectorHeight(int value);
public: public:
// Constructor // Constructor
Menu(SDL_Renderer *renderer, Text *text, Input *input, std::string *fileList); Menu(SDL_Renderer *renderer, Text *text, Input *input, std::string *fileList);
@@ -130,9 +143,6 @@ public:
// Deja el menu apuntando al primer elemento // Deja el menu apuntando al primer elemento
void reset(); void reset();
// Deja el menu sin elemento seleccionado
void deselectItem();
// Gestiona la entrada de teclado y mando durante el menu // Gestiona la entrada de teclado y mando durante el menu
void checkInput(); void checkInput();
@@ -151,14 +161,17 @@ public:
// Establece el color del texto del selector // Establece el color del texto del selector
void setSelectorTextColor(int r, int g, int b); void setSelectorTextColor(int r, int g, int b);
// Centra el menu respecto a un punto // Centra el menu respecto a un punto en el eje X
void centerMenu(int value); void centerMenuOnX(int value);
// Centra los elementos del menu // Centra el menu respecto a un punto en el eje Y
void centerMenuElements(); void centerMenuOnY(int value);
// Centra los elementos del menu en el eje X
void centerMenuElementsOnX();
// Añade un item al menu // Añade un item al menu
void addItem(std::string text, const Uint8 hPaddingUp = 0, const Uint8 hPaddingDown = 0); void addItem(std::string text, Uint8 hPaddingDown = 1, bool selectable = true, bool greyed = false, bool linkedDown = false);
// Cambia el texto de un item // Cambia el texto de un item
void setItemCaption(Uint8 index, std::string text); void setItemCaption(Uint8 index, std::string text);
@@ -168,6 +181,15 @@ public:
// Coloca el selector en una posición específica // Coloca el selector en una posición específica
void setSelectorPos(Uint8 index); void setSelectorPos(Uint8 index);
// Establece el estado seleccionable de un item
void setSelectable(Uint8 index, bool value);
// Establece el estado agrisado de un item
void setGreyed(Uint8 index, bool value);
// Establece el estado de enlace de un item
void setLinkedDown(Uint8 index, bool value);
}; };
#endif #endif

View File

@@ -262,6 +262,13 @@ void MovingSprite::setRotateAmount(double value)
mRotateAmount = value; mRotateAmount = value;
} }
// Establece el valor de la variable
void MovingSprite::disableRotate()
{
mRotate = false;
mAngle = 0;
}
// Actualiza las variables internas del objeto // Actualiza las variables internas del objeto
void MovingSprite::update() void MovingSprite::update()
{ {

View File

@@ -127,6 +127,9 @@ public:
// Establece el valor de la variable // Establece el valor de la variable
void setRotateAmount(double value); void setRotateAmount(double value);
// Quita el efecto de rotación y deja el sprite en su angulo inicial.
void disableRotate();
// Cambia el sentido de la rotación // Cambia el sentido de la rotación
void switchRotate(); void switchRotate();
}; };

View File

@@ -14,23 +14,31 @@ Player::~Player()
{ {
delete mSpriteLegs; delete mSpriteLegs;
mSpriteLegs = nullptr; mSpriteLegs = nullptr;
delete mSpriteBody; delete mSpriteBody;
mSpriteBody = nullptr; mSpriteBody = nullptr;
delete mSpriteHead; delete mSpriteHead;
mSpriteHead = nullptr; mSpriteHead = nullptr;
} }
// Iniciador // Iniciador
void Player::init(float x, int y, LTexture *textureLegs, LTexture *textureBody, SDL_Renderer *renderer) void Player::init(float x, int y, LTexture *textureLegs, LTexture *textureBody, LTexture *textureHead, LTexture *textureDead, SDL_Renderer *renderer)
{ {
// Copia punteros
mPlayerDeadTexture = textureDead;
// Inicializa variables de estado // Inicializa variables de estado
mAlive = true; mAlive = true;
mDeathCounter = DEATH_COUNTER;
mDeathIndex = 0;
mStatusWalking = PLAYER_STATUS_WALKING_STOP; mStatusWalking = PLAYER_STATUS_WALKING_STOP;
mStatusFiring = PLAYER_STATUS_FIRING_NO; mStatusFiring = PLAYER_STATUS_FIRING_NO;
mInvulnerable = false; mInvulnerable = false;
mInvulnerableCounter = PLAYER_INVULNERABLE_COUNTER; mInvulnerableCounter = PLAYER_INVULNERABLE_COUNTER;
mPowerUp = false;
mPowerUpCounter = PLAYER_POWERUP_COUNTER;
mPowerUpHeadOffset = 0;
mExtraHit = false; mExtraHit = false;
mCoffees = 0; mCoffees = 0;
mInput = true; mInput = true;
@@ -68,6 +76,7 @@ void Player::init(float x, int y, LTexture *textureLegs, LTexture *textureBody,
// Inicia el sprite // Inicia el sprite
mSpriteLegs->init(textureLegs, renderer); mSpriteLegs->init(textureLegs, renderer);
mSpriteBody->init(textureBody, renderer); mSpriteBody->init(textureBody, renderer);
mSpriteHead->init(textureHead, renderer);
// Establece el alto y ancho del sprite // Establece el alto y ancho del sprite
mSpriteLegs->setWidth(mWidth); mSpriteLegs->setWidth(mWidth);
@@ -76,6 +85,9 @@ void Player::init(float x, int y, LTexture *textureLegs, LTexture *textureBody,
mSpriteBody->setWidth(mWidth); mSpriteBody->setWidth(mWidth);
mSpriteBody->setHeight(mHeight); mSpriteBody->setHeight(mHeight);
mSpriteHead->setWidth(mWidth);
mSpriteHead->setHeight(mHeight);
// Establece la posición del sprite // Establece la posición del sprite
mSpriteLegs->setPosX(int(mPosX)); mSpriteLegs->setPosX(int(mPosX));
mSpriteLegs->setPosY(mPosY); mSpriteLegs->setPosY(mPosY);
@@ -83,6 +95,9 @@ void Player::init(float x, int y, LTexture *textureLegs, LTexture *textureBody,
mSpriteBody->setPosX(int(mPosX)); mSpriteBody->setPosX(int(mPosX));
mSpriteBody->setPosY(mPosY); mSpriteBody->setPosY(mPosY);
mSpriteHead->setPosX(int(mPosX));
mSpriteHead->setPosY(mPosY);
// Inicializa las variables para la animación // Inicializa las variables para la animación
mSpriteLegs->setCurrentFrame(0); mSpriteLegs->setCurrentFrame(0);
mSpriteLegs->setAnimationCounter(0); mSpriteLegs->setAnimationCounter(0);
@@ -90,6 +105,9 @@ void Player::init(float x, int y, LTexture *textureLegs, LTexture *textureBody,
mSpriteBody->setCurrentFrame(0); mSpriteBody->setCurrentFrame(0);
mSpriteBody->setAnimationCounter(0); mSpriteBody->setAnimationCounter(0);
mSpriteHead->setCurrentFrame(0);
mSpriteHead->setAnimationCounter(0);
// Establece el numero de frames de cada animacion // Establece el numero de frames de cada animacion
mSpriteLegs->setAnimationNumFrames(PLAYER_ANIMATION_LEGS_WALKING_STOP, 4); mSpriteLegs->setAnimationNumFrames(PLAYER_ANIMATION_LEGS_WALKING_STOP, 4);
mSpriteLegs->setAnimationNumFrames(PLAYER_ANIMATION_LEGS_WALKING_LEFT, 4); mSpriteLegs->setAnimationNumFrames(PLAYER_ANIMATION_LEGS_WALKING_LEFT, 4);
@@ -102,6 +120,13 @@ void Player::init(float x, int y, LTexture *textureLegs, LTexture *textureBody,
mSpriteBody->setAnimationNumFrames(PLAYER_ANIMATION_BODY_WALKING_STOP, 4); mSpriteBody->setAnimationNumFrames(PLAYER_ANIMATION_BODY_WALKING_STOP, 4);
mSpriteBody->setAnimationNumFrames(PLAYER_ANIMATION_BODY_FIRING_UP, 4); mSpriteBody->setAnimationNumFrames(PLAYER_ANIMATION_BODY_FIRING_UP, 4);
mSpriteHead->setAnimationNumFrames(PLAYER_ANIMATION_HEAD_WALKING_LEFT, 4);
mSpriteHead->setAnimationNumFrames(PLAYER_ANIMATION_HEAD_FIRING_LEFT, 4);
mSpriteHead->setAnimationNumFrames(PLAYER_ANIMATION_HEAD_WALKING_RIGHT, 4);
mSpriteHead->setAnimationNumFrames(PLAYER_ANIMATION_HEAD_FIRING_RIGHT, 4);
mSpriteHead->setAnimationNumFrames(PLAYER_ANIMATION_HEAD_WALKING_STOP, 4);
mSpriteHead->setAnimationNumFrames(PLAYER_ANIMATION_HEAD_FIRING_UP, 4);
// Establece la velocidad de cada animación // Establece la velocidad de cada animación
mSpriteLegs->setAnimationSpeed(PLAYER_ANIMATION_LEGS_WALKING_STOP, 10); mSpriteLegs->setAnimationSpeed(PLAYER_ANIMATION_LEGS_WALKING_STOP, 10);
mSpriteLegs->setAnimationSpeed(PLAYER_ANIMATION_LEGS_WALKING_LEFT, 5); mSpriteLegs->setAnimationSpeed(PLAYER_ANIMATION_LEGS_WALKING_LEFT, 5);
@@ -114,6 +139,13 @@ void Player::init(float x, int y, LTexture *textureLegs, LTexture *textureBody,
mSpriteBody->setAnimationSpeed(PLAYER_ANIMATION_BODY_WALKING_STOP, 10); mSpriteBody->setAnimationSpeed(PLAYER_ANIMATION_BODY_WALKING_STOP, 10);
mSpriteBody->setAnimationSpeed(PLAYER_ANIMATION_BODY_FIRING_UP, 5); mSpriteBody->setAnimationSpeed(PLAYER_ANIMATION_BODY_FIRING_UP, 5);
mSpriteHead->setAnimationSpeed(PLAYER_ANIMATION_HEAD_WALKING_LEFT, 5);
mSpriteHead->setAnimationSpeed(PLAYER_ANIMATION_HEAD_FIRING_LEFT, 5);
mSpriteHead->setAnimationSpeed(PLAYER_ANIMATION_HEAD_WALKING_RIGHT, 5);
mSpriteHead->setAnimationSpeed(PLAYER_ANIMATION_HEAD_FIRING_RIGHT, 5);
mSpriteHead->setAnimationSpeed(PLAYER_ANIMATION_HEAD_WALKING_STOP, 10);
mSpriteHead->setAnimationSpeed(PLAYER_ANIMATION_HEAD_FIRING_UP, 5);
// Establece si la animación se reproduce en bucle // Establece si la animación se reproduce en bucle
mSpriteLegs->setAnimationLoop(PLAYER_ANIMATION_LEGS_WALKING_STOP, true); mSpriteLegs->setAnimationLoop(PLAYER_ANIMATION_LEGS_WALKING_STOP, true);
mSpriteLegs->setAnimationLoop(PLAYER_ANIMATION_LEGS_WALKING_LEFT, true); mSpriteLegs->setAnimationLoop(PLAYER_ANIMATION_LEGS_WALKING_LEFT, true);
@@ -126,6 +158,13 @@ void Player::init(float x, int y, LTexture *textureLegs, LTexture *textureBody,
mSpriteBody->setAnimationLoop(PLAYER_ANIMATION_BODY_WALKING_STOP, true); mSpriteBody->setAnimationLoop(PLAYER_ANIMATION_BODY_WALKING_STOP, true);
mSpriteBody->setAnimationLoop(PLAYER_ANIMATION_BODY_FIRING_UP, true); mSpriteBody->setAnimationLoop(PLAYER_ANIMATION_BODY_FIRING_UP, true);
mSpriteHead->setAnimationLoop(PLAYER_ANIMATION_HEAD_WALKING_LEFT, true);
mSpriteHead->setAnimationLoop(PLAYER_ANIMATION_HEAD_FIRING_LEFT, true);
mSpriteHead->setAnimationLoop(PLAYER_ANIMATION_HEAD_WALKING_RIGHT, true);
mSpriteHead->setAnimationLoop(PLAYER_ANIMATION_HEAD_FIRING_RIGHT, true);
mSpriteHead->setAnimationLoop(PLAYER_ANIMATION_HEAD_WALKING_STOP, true);
mSpriteHead->setAnimationLoop(PLAYER_ANIMATION_HEAD_FIRING_UP, true);
// Establece los frames de cada animación // Establece los frames de cada animación
mSpriteLegs->setAnimationFrames(PLAYER_ANIMATION_LEGS_WALKING_LEFT, 0, mWidth * 0, mHeight * 0, mWidth, mHeight); mSpriteLegs->setAnimationFrames(PLAYER_ANIMATION_LEGS_WALKING_LEFT, 0, mWidth * 0, mHeight * 0, mWidth, mHeight);
mSpriteLegs->setAnimationFrames(PLAYER_ANIMATION_LEGS_WALKING_LEFT, 1, mWidth * 1, mHeight * 0, mWidth, mHeight); mSpriteLegs->setAnimationFrames(PLAYER_ANIMATION_LEGS_WALKING_LEFT, 1, mWidth * 1, mHeight * 0, mWidth, mHeight);
@@ -172,9 +211,40 @@ void Player::init(float x, int y, LTexture *textureLegs, LTexture *textureBody,
mSpriteBody->setAnimationFrames(PLAYER_ANIMATION_BODY_FIRING_UP, 2, mWidth * 2, mHeight * 5, mWidth, mHeight); mSpriteBody->setAnimationFrames(PLAYER_ANIMATION_BODY_FIRING_UP, 2, mWidth * 2, mHeight * 5, mWidth, mHeight);
mSpriteBody->setAnimationFrames(PLAYER_ANIMATION_BODY_FIRING_UP, 3, mWidth * 3, mHeight * 5, mWidth, mHeight); mSpriteBody->setAnimationFrames(PLAYER_ANIMATION_BODY_FIRING_UP, 3, mWidth * 3, mHeight * 5, mWidth, mHeight);
mSpriteHead->setAnimationFrames(PLAYER_ANIMATION_HEAD_WALKING_LEFT, 0, mWidth * 0, mHeight * 0, mWidth, mHeight);
mSpriteHead->setAnimationFrames(PLAYER_ANIMATION_HEAD_WALKING_LEFT, 1, mWidth * 1, mHeight * 0, mWidth, mHeight);
mSpriteHead->setAnimationFrames(PLAYER_ANIMATION_HEAD_WALKING_LEFT, 2, mWidth * 2, mHeight * 0, mWidth, mHeight);
mSpriteHead->setAnimationFrames(PLAYER_ANIMATION_HEAD_WALKING_LEFT, 3, mWidth * 3, mHeight * 0, mWidth, mHeight);
mSpriteHead->setAnimationFrames(PLAYER_ANIMATION_HEAD_FIRING_LEFT, 0, mWidth * 0, mHeight * 1, mWidth, mHeight);
mSpriteHead->setAnimationFrames(PLAYER_ANIMATION_HEAD_FIRING_LEFT, 1, mWidth * 1, mHeight * 1, mWidth, mHeight);
mSpriteHead->setAnimationFrames(PLAYER_ANIMATION_HEAD_FIRING_LEFT, 2, mWidth * 2, mHeight * 1, mWidth, mHeight);
mSpriteHead->setAnimationFrames(PLAYER_ANIMATION_HEAD_FIRING_LEFT, 3, mWidth * 3, mHeight * 1, mWidth, mHeight);
mSpriteHead->setAnimationFrames(PLAYER_ANIMATION_HEAD_WALKING_RIGHT, 0, mWidth * 0, mHeight * 2, mWidth, mHeight);
mSpriteHead->setAnimationFrames(PLAYER_ANIMATION_HEAD_WALKING_RIGHT, 1, mWidth * 1, mHeight * 2, mWidth, mHeight);
mSpriteHead->setAnimationFrames(PLAYER_ANIMATION_HEAD_WALKING_RIGHT, 2, mWidth * 2, mHeight * 2, mWidth, mHeight);
mSpriteHead->setAnimationFrames(PLAYER_ANIMATION_HEAD_WALKING_RIGHT, 3, mWidth * 3, mHeight * 2, mWidth, mHeight);
mSpriteHead->setAnimationFrames(PLAYER_ANIMATION_HEAD_FIRING_RIGHT, 0, mWidth * 0, mHeight * 3, mWidth, mHeight);
mSpriteHead->setAnimationFrames(PLAYER_ANIMATION_HEAD_FIRING_RIGHT, 1, mWidth * 1, mHeight * 3, mWidth, mHeight);
mSpriteHead->setAnimationFrames(PLAYER_ANIMATION_HEAD_FIRING_RIGHT, 2, mWidth * 2, mHeight * 3, mWidth, mHeight);
mSpriteHead->setAnimationFrames(PLAYER_ANIMATION_HEAD_FIRING_RIGHT, 3, mWidth * 3, mHeight * 3, mWidth, mHeight);
mSpriteHead->setAnimationFrames(PLAYER_ANIMATION_HEAD_WALKING_STOP, 0, mWidth * 0, mHeight * 4, mWidth, mHeight);
mSpriteHead->setAnimationFrames(PLAYER_ANIMATION_HEAD_WALKING_STOP, 1, mWidth * 1, mHeight * 4, mWidth, mHeight);
mSpriteHead->setAnimationFrames(PLAYER_ANIMATION_HEAD_WALKING_STOP, 2, mWidth * 2, mHeight * 4, mWidth, mHeight);
mSpriteHead->setAnimationFrames(PLAYER_ANIMATION_HEAD_WALKING_STOP, 3, mWidth * 3, mHeight * 4, mWidth, mHeight);
mSpriteHead->setAnimationFrames(PLAYER_ANIMATION_HEAD_FIRING_UP, 0, mWidth * 0, mHeight * 5, mWidth, mHeight);
mSpriteHead->setAnimationFrames(PLAYER_ANIMATION_HEAD_FIRING_UP, 1, mWidth * 1, mHeight * 5, mWidth, mHeight);
mSpriteHead->setAnimationFrames(PLAYER_ANIMATION_HEAD_FIRING_UP, 2, mWidth * 2, mHeight * 5, mWidth, mHeight);
mSpriteHead->setAnimationFrames(PLAYER_ANIMATION_HEAD_FIRING_UP, 3, mWidth * 3, mHeight * 5, mWidth, mHeight);
// Selecciona un frame para pintar // Selecciona un frame para pintar
mSpriteLegs->setSpriteClip(mSpriteLegs->getAnimationClip(PLAYER_ANIMATION_LEGS_WALKING_STOP, 0)); mSpriteLegs->setSpriteClip(mSpriteLegs->getAnimationClip(PLAYER_ANIMATION_LEGS_WALKING_STOP, 0));
mSpriteBody->setSpriteClip(mSpriteBody->getAnimationClip(PLAYER_ANIMATION_BODY_WALKING_STOP, 0)); mSpriteBody->setSpriteClip(mSpriteBody->getAnimationClip(PLAYER_ANIMATION_BODY_WALKING_STOP, 0));
mSpriteHead->setSpriteClip(mSpriteHead->getAnimationClip(PLAYER_ANIMATION_HEAD_WALKING_STOP, 0));
} }
// Actua en consecuencia de la entrada recibida // Actua en consecuencia de la entrada recibida
@@ -232,6 +302,9 @@ void Player::move()
mSpriteBody->setPosX(getPosX()); mSpriteBody->setPosX(getPosX());
mSpriteBody->setPosY(mPosY); mSpriteBody->setPosY(mPosY);
mSpriteHead->setPosX(getPosX());
mSpriteHead->setPosY(mPosY);
} }
} }
@@ -246,12 +319,14 @@ void Player::render()
{ {
mSpriteLegs->render(); mSpriteLegs->render();
mSpriteBody->render(); mSpriteBody->render();
mSpriteHead->render();
} }
} }
else else
{ {
mSpriteLegs->render(); mSpriteLegs->render();
mSpriteBody->render(); mSpriteBody->render();
mSpriteHead->render();
} }
} }
} }
@@ -275,6 +350,7 @@ void Player::setFiringStatus(Uint8 status)
{ {
mStatusFiring = status; mStatusFiring = status;
mSpriteBody->setCurrentFrame(0); mSpriteBody->setCurrentFrame(0);
mSpriteHead->setCurrentFrame(0);
} }
} }
@@ -292,6 +368,17 @@ void Player::setAnimation()
mSpriteBody->setAnimationFrames(PLAYER_ANIMATION_BODY_FIRING_UP, i, mWidth * i, mHeight * (5 + (6 * mCoffees)), mWidth, mHeight); mSpriteBody->setAnimationFrames(PLAYER_ANIMATION_BODY_FIRING_UP, i, mWidth * i, mHeight * (5 + (6 * mCoffees)), mWidth, mHeight);
} }
// Actualiza los frames de la animación en función de si se tiene el PowerUp
for (int i = 0; i < 4; i++)
{
mSpriteHead->setAnimationFrames(PLAYER_ANIMATION_HEAD_WALKING_LEFT, i, (mWidth * i) + mPowerUpHeadOffset, mHeight * (0 + (6 * mCoffees)), mWidth, mHeight);
mSpriteHead->setAnimationFrames(PLAYER_ANIMATION_HEAD_FIRING_LEFT, i, (mWidth * i) + mPowerUpHeadOffset, mHeight * (1 + (6 * mCoffees)), mWidth, mHeight);
mSpriteHead->setAnimationFrames(PLAYER_ANIMATION_HEAD_WALKING_RIGHT, i, (mWidth * i) + mPowerUpHeadOffset, mHeight * (2 + (6 * mCoffees)), mWidth, mHeight);
mSpriteHead->setAnimationFrames(PLAYER_ANIMATION_HEAD_FIRING_RIGHT, i, (mWidth * i) + mPowerUpHeadOffset, mHeight * (3 + (6 * mCoffees)), mWidth, mHeight);
mSpriteHead->setAnimationFrames(PLAYER_ANIMATION_HEAD_WALKING_STOP, i, (mWidth * i) + mPowerUpHeadOffset, mHeight * (4 + (6 * mCoffees)), mWidth, mHeight);
mSpriteHead->setAnimationFrames(PLAYER_ANIMATION_HEAD_FIRING_UP, i, (mWidth * i) + mPowerUpHeadOffset, mHeight * (5 + (6 * mCoffees)), mWidth, mHeight);
}
switch (mStatusWalking) switch (mStatusWalking)
{ {
case PLAYER_STATUS_WALKING_LEFT: case PLAYER_STATUS_WALKING_LEFT:
@@ -300,22 +387,27 @@ void Player::setAnimation()
{ {
case PLAYER_STATUS_FIRING_UP: case PLAYER_STATUS_FIRING_UP:
mSpriteBody->animate(PLAYER_ANIMATION_BODY_FIRING_UP); mSpriteBody->animate(PLAYER_ANIMATION_BODY_FIRING_UP);
mSpriteHead->animate(PLAYER_ANIMATION_HEAD_FIRING_UP);
break; break;
case PLAYER_STATUS_FIRING_LEFT: case PLAYER_STATUS_FIRING_LEFT:
mSpriteBody->animate(PLAYER_ANIMATION_BODY_FIRING_LEFT); mSpriteBody->animate(PLAYER_ANIMATION_BODY_FIRING_LEFT);
mSpriteHead->animate(PLAYER_ANIMATION_HEAD_FIRING_LEFT);
break; break;
case PLAYER_STATUS_FIRING_RIGHT: case PLAYER_STATUS_FIRING_RIGHT:
mSpriteBody->animate(PLAYER_ANIMATION_BODY_FIRING_RIGHT); mSpriteBody->animate(PLAYER_ANIMATION_BODY_FIRING_RIGHT);
mSpriteHead->animate(PLAYER_ANIMATION_HEAD_FIRING_RIGHT);
break; break;
case PLAYER_STATUS_FIRING_NO: case PLAYER_STATUS_FIRING_NO:
mSpriteBody->animate(PLAYER_ANIMATION_BODY_WALKING_LEFT); mSpriteBody->animate(PLAYER_ANIMATION_BODY_WALKING_LEFT);
mSpriteHead->animate(PLAYER_ANIMATION_HEAD_WALKING_LEFT);
break; break;
default: default:
mSpriteBody->animate(PLAYER_ANIMATION_BODY_WALKING_STOP); mSpriteBody->animate(PLAYER_ANIMATION_BODY_WALKING_STOP);
mSpriteHead->animate(PLAYER_ANIMATION_HEAD_WALKING_STOP);
break; break;
} }
break; break;
@@ -326,22 +418,27 @@ void Player::setAnimation()
{ {
case PLAYER_STATUS_FIRING_UP: case PLAYER_STATUS_FIRING_UP:
mSpriteBody->animate(PLAYER_ANIMATION_BODY_FIRING_UP); mSpriteBody->animate(PLAYER_ANIMATION_BODY_FIRING_UP);
mSpriteHead->animate(PLAYER_ANIMATION_HEAD_FIRING_UP);
break; break;
case PLAYER_STATUS_FIRING_LEFT: case PLAYER_STATUS_FIRING_LEFT:
mSpriteBody->animate(PLAYER_ANIMATION_BODY_FIRING_LEFT); mSpriteBody->animate(PLAYER_ANIMATION_BODY_FIRING_LEFT);
mSpriteHead->animate(PLAYER_ANIMATION_HEAD_FIRING_LEFT);
break; break;
case PLAYER_STATUS_FIRING_RIGHT: case PLAYER_STATUS_FIRING_RIGHT:
mSpriteBody->animate(PLAYER_ANIMATION_BODY_FIRING_RIGHT); mSpriteBody->animate(PLAYER_ANIMATION_BODY_FIRING_RIGHT);
mSpriteHead->animate(PLAYER_ANIMATION_HEAD_FIRING_RIGHT);
break; break;
case PLAYER_STATUS_FIRING_NO: case PLAYER_STATUS_FIRING_NO:
mSpriteBody->animate(PLAYER_ANIMATION_BODY_WALKING_RIGHT); mSpriteBody->animate(PLAYER_ANIMATION_BODY_WALKING_RIGHT);
mSpriteHead->animate(PLAYER_ANIMATION_HEAD_WALKING_RIGHT);
break; break;
default: default:
mSpriteBody->animate(PLAYER_ANIMATION_BODY_WALKING_STOP); mSpriteBody->animate(PLAYER_ANIMATION_BODY_WALKING_STOP);
mSpriteHead->animate(PLAYER_ANIMATION_HEAD_WALKING_STOP);
break; break;
} }
break; break;
@@ -352,22 +449,27 @@ void Player::setAnimation()
{ {
case PLAYER_STATUS_FIRING_UP: case PLAYER_STATUS_FIRING_UP:
mSpriteBody->animate(PLAYER_ANIMATION_BODY_FIRING_UP); mSpriteBody->animate(PLAYER_ANIMATION_BODY_FIRING_UP);
mSpriteHead->animate(PLAYER_ANIMATION_HEAD_FIRING_UP);
break; break;
case PLAYER_STATUS_FIRING_LEFT: case PLAYER_STATUS_FIRING_LEFT:
mSpriteBody->animate(PLAYER_ANIMATION_BODY_FIRING_LEFT); mSpriteBody->animate(PLAYER_ANIMATION_BODY_FIRING_LEFT);
mSpriteHead->animate(PLAYER_ANIMATION_HEAD_FIRING_LEFT);
break; break;
case PLAYER_STATUS_FIRING_RIGHT: case PLAYER_STATUS_FIRING_RIGHT:
mSpriteBody->animate(PLAYER_ANIMATION_BODY_FIRING_RIGHT); mSpriteBody->animate(PLAYER_ANIMATION_BODY_FIRING_RIGHT);
mSpriteHead->animate(PLAYER_ANIMATION_HEAD_FIRING_RIGHT);
break; break;
case PLAYER_STATUS_FIRING_NO: case PLAYER_STATUS_FIRING_NO:
mSpriteBody->animate(PLAYER_ANIMATION_BODY_WALKING_STOP); mSpriteBody->animate(PLAYER_ANIMATION_BODY_WALKING_STOP);
mSpriteHead->animate(PLAYER_ANIMATION_HEAD_WALKING_STOP);
break; break;
default: default:
mSpriteBody->animate(PLAYER_ANIMATION_BODY_WALKING_STOP); mSpriteBody->animate(PLAYER_ANIMATION_BODY_WALKING_STOP);
mSpriteHead->animate(PLAYER_ANIMATION_HEAD_WALKING_STOP);
break; break;
} }
break; break;
@@ -427,7 +529,9 @@ void Player::updateCooldown()
{ {
if (mCooldown > 0) if (mCooldown > 0)
{ {
--mCooldown; mCooldown--;
if (mPowerUp)
mCooldown--;
} }
else else
{ {
@@ -442,23 +546,26 @@ void Player::update()
setAnimation(); setAnimation();
shiftColliders(); shiftColliders();
updateCooldown(); updateCooldown();
updatePowerUpCounter();
updateInvulnerableCounter(); updateInvulnerableCounter();
updateDeathCounter();
updatePowerUpHeadOffset();
} }
// Obtiene la puntuación del jugador // Obtiene la puntuación del jugador
int Player::getScore() Uint32 Player::getScore()
{ {
return mScore; return mScore;
} }
// Asigna un valor a la puntuación del jugador // Asigna un valor a la puntuación del jugador
void Player::setScore(int score) void Player::setScore(Uint32 score)
{ {
mScore = score; mScore = score;
} }
// Incrementa la puntuación del jugador // Incrementa la puntuación del jugador
void Player::addScore(int score) void Player::addScore(Uint32 score)
{ {
mScore += score; mScore += score;
} }
@@ -491,18 +598,18 @@ void Player::setScoreMultiplier(float value)
void Player::incScoreMultiplier() void Player::incScoreMultiplier()
{ {
if (mScoreMultiplier < 5.0f) if (mScoreMultiplier < 5.0f)
{
mScoreMultiplier += 0.1f; mScoreMultiplier += 0.1f;
} else
mScoreMultiplier = 5.0f;
} }
// Decrementa el valor de la variable hasta un mínimo // Decrementa el valor de la variable hasta un mínimo
void Player::decScoreMultiplier() void Player::decScoreMultiplier()
{ {
if (mScoreMultiplier > 1.0f) if (mScoreMultiplier > 1.0f)
{
mScoreMultiplier -= 0.1f; mScoreMultiplier -= 0.1f;
} else
mScoreMultiplier = 1.0f;
} }
// Obtiene el valor de la variable // Obtiene el valor de la variable
@@ -532,14 +639,63 @@ void Player::setInvulnerableCounter(Uint16 value)
// Actualiza el valor de la variable // Actualiza el valor de la variable
void Player::updateInvulnerableCounter() void Player::updateInvulnerableCounter()
{ {
if (mInvulnerableCounter > 0) if (mInvulnerable)
{ {
--mInvulnerableCounter; if (mInvulnerableCounter > 0)
{
mInvulnerableCounter--;
}
else
{
mInvulnerable = false;
mInvulnerableCounter = PLAYER_INVULNERABLE_COUNTER;
}
}
}
// Actualiza el valor de la variable
void Player::updateDeathCounter()
{
if (!mAlive)
if (mDeathCounter > 0)
mDeathCounter--;
}
// Obtiene el valor de la variable
bool Player::isPowerUp()
{
return mPowerUp;
}
// Establece el valor de la variable
void Player::setPowerUp(bool value)
{
mPowerUp = value;
}
// Obtiene el valor de la variable
Uint16 Player::getPowerUpCounter()
{
return mPowerUpCounter;
}
// Establece el valor de la variable
void Player::setPowerUpCounter(Uint16 value)
{
mPowerUpCounter = value;
}
// Actualiza el valor de la variable
void Player::updatePowerUpCounter()
{
if ((mPowerUpCounter > 0) && (mPowerUp))
{
mPowerUpCounter--;
} }
else else
{ {
mInvulnerable = false; mPowerUp = false;
mInvulnerableCounter = PLAYER_INVULNERABLE_COUNTER; mPowerUpCounter = PLAYER_POWERUP_COUNTER;
} }
} }
@@ -596,6 +752,36 @@ circle_t &Player::getCollider()
// Actualiza el circulo de colisión a la posición del jugador // Actualiza el circulo de colisión a la posición del jugador
void Player::shiftColliders() void Player::shiftColliders()
{ {
mCollider.x = Uint16(mPosX + (mWidth / 2)); mCollider.x = int(mPosX + (mWidth / 2));
mCollider.y = mPosY + (mHeight / 2); mCollider.y = int(mPosY + (mHeight / 2));
}
// Obtiene el puntero a la textura con los gráficos de la animación de morir
LTexture *Player::getDeadTexture()
{
return mPlayerDeadTexture;
}
// Obtiene el valor de la variable
Uint16 Player::getDeathCounter()
{
return mDeathCounter;
}
// Actualiza el valor de la variable
void Player::updatePowerUpHeadOffset()
{
if (!mPowerUp)
mPowerUpHeadOffset = 0;
else
{
mPowerUpHeadOffset = 96;
if (mPowerUpCounter < 300)
{
if (mPowerUpCounter % 10 > 4)
mPowerUpHeadOffset = 96;
else
mPowerUpHeadOffset = 0;
}
}
} }

View File

@@ -29,20 +29,36 @@ private:
Uint8 mStatusFiring; // Estado del jugador Uint8 mStatusFiring; // Estado del jugador
bool mAlive; // Indica si el jugador está vivo bool mAlive; // Indica si el jugador está vivo
Uint16 mDeathCounter; // Contador para la animación de morirse
bool mInvulnerable; // Indica si el jugador es invulnerable bool mInvulnerable; // Indica si el jugador es invulnerable
Uint16 mInvulnerableCounter; // Temporizador para la invulnerabilidad Uint16 mInvulnerableCounter; // Contador para la invulnerabilidad
bool mExtraHit; // Indica si el jugador tiene un toque extra bool mExtraHit; // Indica si el jugador tiene un toque extra
Uint8 mCoffees; // Indica cuantos cafes lleva acumulados Uint8 mCoffees; // Indica cuantos cafes lleva acumulados
bool mPowerUp; // Indica si el jugador tiene activo el modo PowerUp
Uint8 mPowerUpHeadOffset; // Variable para dibujar la cabeza normal o la del powerup
bool mInput; // Indica si puede recibir ordenes de entrada bool mInput; // Indica si puede recibir ordenes de entrada
AnimatedSprite *mSpriteLegs; // Sprite para dibujar las piernas AnimatedSprite *mSpriteLegs; // Sprite para dibujar las piernas
AnimatedSprite *mSpriteBody; // Sprite para dibujar el cuerpo AnimatedSprite *mSpriteBody; // Sprite para dibujar el cuerpo
AnimatedSprite *mSpriteHead; // Sprite para dibujar la cabeza AnimatedSprite *mSpriteHead; // Sprite para dibujar la cabeza
LTexture *mPlayerDeadTexture; // Textura con los gráficos para la animación de muerte
circle_t mCollider; // Circulo de colisión del jugador circle_t mCollider; // Circulo de colisión del jugador
void shiftColliders(); // Actualiza el circulo de colisión a la posición del jugador void shiftColliders(); // Actualiza el circulo de colisión a la posición del jugador
// Actualiza el valor de la variable
void updateInvulnerableCounter();
// Actualiza el valor de la variable
void updateDeathCounter();
// Actualiza el valor de la variable
void updatePowerUpHeadOffset();
public: public:
Uint8 mDeathIndex; // Apaño rapidito. Indice de SmartSprite donde esta ubicado el sprite de morirse
Uint16 mPowerUpCounter; // Temporizador para el modo PowerUp
// Constructor // Constructor
Player(); Player();
@@ -50,7 +66,7 @@ public:
~Player(); ~Player();
// Iniciador // Iniciador
void init(float x, int y, LTexture *textureLegs, LTexture *textureBody, SDL_Renderer *renderer); void init(float x, int y, LTexture *textureLegs, LTexture *textureBody, LTexture *textureHead, LTexture *textureDead, SDL_Renderer *renderer);
// Actua en consecuencia de la entrada recibida // Actua en consecuencia de la entrada recibida
void setInput(Uint8 input); void setInput(Uint8 input);
@@ -63,6 +79,8 @@ public:
// Establece el estado del jugador // Establece el estado del jugador
void setWalkingStatus(Uint8 status); void setWalkingStatus(Uint8 status);
// Establece el estado del jugador
void setFiringStatus(Uint8 status); void setFiringStatus(Uint8 status);
// Establece la animación correspondiente al estado // Establece la animación correspondiente al estado
@@ -93,13 +111,13 @@ public:
void update(); void update();
// Obtiene la puntuación del jugador // Obtiene la puntuación del jugador
int getScore(); Uint32 getScore();
// Asigna un valor a la puntuación del jugador // Asigna un valor a la puntuación del jugador
void setScore(int score); void setScore(Uint32 score);
// Incrementa la puntuación del jugador // Incrementa la puntuación del jugador
void addScore(int score); void addScore(Uint32 score);
// Obtiene el valor de la variable // Obtiene el valor de la variable
bool isAlive(); bool isAlive();
@@ -131,8 +149,20 @@ public:
// Establece el valor de la variable // Establece el valor de la variable
void setInvulnerableCounter(Uint16 value); void setInvulnerableCounter(Uint16 value);
// Obtiene el valor de la variable
bool isPowerUp();
// Establece el valor de la variable
void setPowerUp(bool value);
// Obtiene el valor de la variable
Uint16 getPowerUpCounter();
// Establece el valor de la variable
void setPowerUpCounter(Uint16 value);
// Actualiza el valor de la variable // Actualiza el valor de la variable
void updateInvulnerableCounter(); void updatePowerUpCounter();
// Obtiene el valor de la variable // Obtiene el valor de la variable
bool hasExtraHit(); bool hasExtraHit();
@@ -154,6 +184,12 @@ public:
// Obtiene el circulo de colisión // Obtiene el circulo de colisión
circle_t &getCollider(); circle_t &getCollider();
// Obtiene el puntero a la textura con los gráficos de la animación de morir
LTexture *getDeadTexture();
// Obtiene el valor de la variable
Uint16 getDeathCounter();
}; };
#endif #endif

View File

@@ -1,12 +1,17 @@
#include "const.h" #include "const.h"
#include "text.h" #include "text.h"
#include <iostream>
#include <fstream>
// Constructor // Constructor
Text::Text(LTexture *texture, SDL_Renderer *renderer) Text::Text(std::string file, LTexture *texture, SDL_Renderer *renderer)
{ {
mSprite = new Sprite(); mSprite = new Sprite();
mSprite->setTexture(texture); mSprite->setTexture(texture);
mSprite->setRenderer(renderer); mSprite->setRenderer(renderer);
mFile = file;
init();
} }
// Destructor // Destructor
@@ -17,22 +22,8 @@ Text::~Text()
} }
// Inicializador // Inicializador
void Text::init(Uint8 type, Uint8 size) void Text::init()
{ {
// Inicializa variables
mType = type;
mSize = size;
// Inicia los valores del sprite que dibuja las letras
mSprite->setWidth(size);
mSprite->setHeight(size);
mSprite->setPosX(0);
mSprite->setPosY(0);
mSprite->setSpriteClip(0, 0, mSprite->getWidth(), mSprite->getHeight());
// Cadena con los caracteres ascii que se van a inicializar
const std::string text = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ{\\[]]^_`abcdefghijklmnopqrstuvwxyz";
// Inicializa a cero el vector con las coordenadas // Inicializa a cero el vector con las coordenadas
for (int i = 0; i < 128; i++) for (int i = 0; i < 128; i++)
{ {
@@ -41,106 +32,21 @@ void Text::init(Uint8 type, Uint8 size)
mOffset[i].w = 0; mOffset[i].w = 0;
} }
// Carga los offsets desde el fichero
initOffsetFromFile();
// Inicia los valores del sprite que dibuja las letras
mSprite->setWidth(mBoxWidth);
mSprite->setHeight(mBoxHeight);
mSprite->setPosX(0);
mSprite->setPosY(0);
mSprite->setSpriteClip(0, 0, mSprite->getWidth(), mSprite->getHeight());
// Establece las coordenadas para cada caracter ascii de la cadena y su ancho // Establece las coordenadas para cada caracter ascii de la cadena y su ancho
for (int i = 0; i < text.length(); ++i) for (int i = 32; i < 128; i++)
{ {
mOffset[int(text[i])].x = ((int(text[i]) - 32) % 15) * mSprite->getWidth(); mOffset[i].x = ((i - 32) % 15) * mBoxWidth;
mOffset[int(text[i])].y = ((int(text[i]) - 32) / 15) * mSprite->getHeight(); mOffset[i].y = ((i - 32) / 15) * mBoxHeight;
if (type == TEXT_FIXED)
mOffset[int(text[i])].w = size;
}
// Establece las coordenadas de forma manual para la ñ y la ç
mOffset[int('^')].x = mOffset[int('z')].x + size;
mOffset[int('^')].y = mOffset[int('z')].y;
mOffset[int('^')].w = size;
mOffset[int('~')].x = mOffset[int('z')].x + size * 2;
mOffset[int('~')].y = mOffset[int('z')].y;
mOffset[int('~')].w = size;
// Establece el ancho de cada caracter
if (type == TEXT_VARIABLE)
{
mOffset[int(' ')].w = 7;
mOffset[int('-')].w = 6;
mOffset[int('/')].w = 5;
mOffset[int('(')].w = 5;
mOffset[int(')')].w = 5;
mOffset[int('.')].w = 4;
mOffset[int(':')].w = 4;
mOffset[int('#')].w = 7;
mOffset[int('!')].w = 7;
mOffset[int('\'')].w = 3;
mOffset[int('0')].w = 7;
mOffset[int('1')].w = 5;
mOffset[int('2')].w = 7;
mOffset[int('3')].w = 7;
mOffset[int('4')].w = 7;
mOffset[int('5')].w = 7;
mOffset[int('6')].w = 7;
mOffset[int('7')].w = 7;
mOffset[int('8')].w = 7;
mOffset[int('9')].w = 7;
mOffset[int('A')].w = 7;
mOffset[int('B')].w = 7;
mOffset[int('C')].w = 7;
mOffset[int('D')].w = 7;
mOffset[int('E')].w = 7;
mOffset[int('F')].w = 7;
mOffset[int('G')].w = 7;
mOffset[int('H')].w = 7;
mOffset[int('I')].w = 4;
mOffset[int('J')].w = 6;
mOffset[int('K')].w = 8;
mOffset[int('L')].w = 6;
mOffset[int('M')].w = 9;
mOffset[int('N')].w = 8;
mOffset[int('O')].w = 8;
mOffset[int('P')].w = 7;
mOffset[int('Q')].w = 8;
mOffset[int('R')].w = 7;
mOffset[int('S')].w = 6;
mOffset[int('T')].w = 8;
mOffset[int('U')].w = 7;
mOffset[int('V')].w = 8;
mOffset[int('W')].w = 9;
mOffset[int('X')].w = 8;
mOffset[int('Y')].w = 8;
mOffset[int('Z')].w = 7;
mOffset[int('^')].w = 7;
mOffset[int('~')].w = 7;
mOffset[int('a')].w = 7;
mOffset[int('b')].w = 7;
mOffset[int('c')].w = 6;
mOffset[int('d')].w = 7;
mOffset[int('e')].w = 7;
mOffset[int('f')].w = 5;
mOffset[int('g')].w = 7;
mOffset[int('h')].w = 7;
mOffset[int('i')].w = 4;
mOffset[int('j')].w = 5;
mOffset[int('k')].w = 7;
mOffset[int('l')].w = 4;
mOffset[int('m')].w = 10;
mOffset[int('n')].w = 7;
mOffset[int('o')].w = 7;
mOffset[int('p')].w = 7;
mOffset[int('q')].w = 7;
mOffset[int('r')].w = 6;
mOffset[int('s')].w = 6;
mOffset[int('t')].w = 5;
mOffset[int('u')].w = 7;
mOffset[int('v')].w = 7;
mOffset[int('w')].w = 9;
mOffset[int('x')].w = 7;
mOffset[int('y')].w = 7;
mOffset[int('z')].w = 7;
} }
} }
@@ -192,6 +98,7 @@ void Text::writeDX(Uint8 flags, int x, int y, std::string text, int kerning, col
const bool centered = ((flags & TXT_CENTER) == TXT_CENTER); const bool centered = ((flags & TXT_CENTER) == TXT_CENTER);
const bool shadowed = ((flags & TXT_SHADOW) == TXT_SHADOW); const bool shadowed = ((flags & TXT_SHADOW) == TXT_SHADOW);
const bool colored = ((flags & TXT_COLOR) == TXT_COLOR); const bool colored = ((flags & TXT_COLOR) == TXT_COLOR);
const bool stroked = ((flags & TXT_STROKE) == TXT_STROKE);
if (centered) if (centered)
x -= (Text::lenght(text, kerning) / 2); x -= (Text::lenght(text, kerning) / 2);
@@ -199,6 +106,19 @@ void Text::writeDX(Uint8 flags, int x, int y, std::string text, int kerning, col
if (shadowed) if (shadowed)
writeColored(x + shadowDistance, y + shadowDistance, text, shadowColor, kerning, lenght); writeColored(x + shadowDistance, y + shadowDistance, text, shadowColor, kerning, lenght);
if (stroked)
{
writeColored(x + shadowDistance, y + shadowDistance, text, shadowColor, kerning, lenght);
writeColored(x - shadowDistance, y + shadowDistance, text, shadowColor, kerning, lenght);
writeColored(x + shadowDistance, y - shadowDistance, text, shadowColor, kerning, lenght);
writeColored(x - shadowDistance, y - shadowDistance, text, shadowColor, kerning, lenght);
writeColored(x, y + shadowDistance, text, shadowColor, kerning, lenght);
writeColored(x, y - shadowDistance, text, shadowColor, kerning, lenght);
writeColored(x + shadowDistance, y, text, shadowColor, kerning, lenght);
writeColored(x - shadowDistance, y, text, shadowColor, kerning, lenght);
}
if (colored) if (colored)
writeColored(x, y, text, textColor, kerning, lenght); writeColored(x, y, text, textColor, kerning, lenght);
else else
@@ -216,26 +136,42 @@ Uint16 Text::lenght(std::string text, int kerning)
return shift; return shift;
} }
// Obtiene el valor de la variable // Inicializa el vector de offsets desde un fichero
Uint8 Text::getType() void Text::initOffsetFromFile()
{ {
return mType; std::ifstream rfile(mFile);
if (rfile.is_open() && rfile.good())
{
std::string buffer;
//printf("Reading %s file\n", mFile.c_str());
// Lee los dos primeros valores del fichero
std::getline(rfile, buffer);
std::getline(rfile, buffer);
mBoxWidth = std::stoi(buffer);
std::getline(rfile, buffer);
std::getline(rfile, buffer);
mBoxHeight = std::stoi(buffer);
// lee el resto de datos del fichero
int index = 32;
int line_read = 0;
while (std::getline(rfile, buffer))
{
// Almacena solo las lineas impares
if (line_read % 2 == 1)
mOffset[index++].w = std::stoi(buffer);
// Limpia el buffer
buffer.clear();
line_read++;
};
}
} }
// Establece el valor de la variable // Devuelve el valor de la variable
void Text::setType(Uint8 type) Uint8 Text::getCharacterWidth()
{ {
mType = type; return mBoxWidth;
}
// Obtiene el valor de la variable
Uint8 Text::getSize()
{
return mSize;
}
// Establece el valor de la variable
void Text::setSize(Uint8 size)
{
mSize = size;
} }

View File

@@ -8,6 +8,7 @@
#define TXT_COLOR 1 #define TXT_COLOR 1
#define TXT_SHADOW 2 #define TXT_SHADOW 2
#define TXT_CENTER 4 #define TXT_CENTER 4
#define TXT_STROKE 8
// Clase texto. Pinta texto en pantalla a partir de un bitmap // Clase texto. Pinta texto en pantalla a partir de un bitmap
class Text class Text
@@ -21,50 +22,45 @@ private:
int y; int y;
Uint8 w; Uint8 w;
}; };
Offset mOffset[255]; // Vector con las posiciones y ancho de cada letra Offset mOffset[128]; // Vector con las posiciones y ancho de cada letra
Uint8 mType; // Indica si el texto es de anchura fija o variable Uint8 mBoxWidth; // Anchura de la caja de cada caracter en el png
Uint8 mSize; // Altura del texto Uint8 mBoxHeight; // Altura de la caja de cada caracter en el png
std::string mFile; // Fichero con los descriptores de la fuente
// Inicializa el vector de offsets desde un fichero
void initOffsetFromFile();
public: public:
// Constructor // Constructor
Text(LTexture *texture, SDL_Renderer *renderer); Text(std::string file, LTexture *texture, SDL_Renderer *renderer);
// Destructor // Destructor
~Text(); ~Text();
// Inicializador // Inicializador
void init(Uint8 type, Uint8 size); void init();
// Escribe el texto en pantalla // Escribe el texto en pantalla
void write(int x, int y, std::string text, int kerning = 0, int lenght = -1); void write(int x, int y, std::string text, int kerning = 1, int lenght = -1);
// Escribe el texto con colores // Escribe el texto con colores
void writeColored(int x, int y, std::string text, color_t color, int kerning = 0, int lenght = -1); void writeColored(int x, int y, std::string text, color_t color, int kerning = 1, int lenght = -1);
// Escribe el texto con sombra // Escribe el texto con sombra
void writeShadowed(int x, int y, std::string text, color_t color, Uint8 shadowDistance = 1, int kerning = 0, int lenght = -1); void writeShadowed(int x, int y, std::string text, color_t color, Uint8 shadowDistance = 1, int kerning = 1, int lenght = -1);
// Escribe el texto centrado en un punto x y con kerning // Escribe el texto centrado en un punto x y con kerning
void writeCentered(int x, int y, std::string text, int kerning = 0, int lenght = -1); void writeCentered(int x, int y, std::string text, int kerning = 1, int lenght = -1);
// Escribe texto con extras // Escribe texto con extras
void writeDX(Uint8 flags, int x, int y, std::string text, int kerning = 0, color_t textColor = {255, 255, 255}, Uint8 shadowDistance = 1, color_t shadowColor = {0, 0, 0}, int lenght = -1); void writeDX(Uint8 flags, int x, int y, std::string text, int kerning = 1, color_t textColor = {255, 255, 255}, Uint8 shadowDistance = 1, color_t shadowColor = {0, 0, 0}, int lenght = -1);
// Obtiene la longitud en pixels de una cadena // Obtiene la longitud en pixels de una cadena
Uint16 lenght(std::string text, int kerning); Uint16 lenght(std::string text, int kerning = 1);
// Obtiene el valor de la variable // Devuelve el valor de la variable
Uint8 getType(); Uint8 getCharacterWidth();
// Establece el valor de la variable
void setType(Uint8 type);
// Obtiene el valor de la variable
Uint8 getSize();
// Establece el valor de la variable
void setSize(Uint8 size);
}; };
#endif #endif

View File

@@ -5,7 +5,7 @@
#endif #endif
// Constructor // Constructor
Title::Title(SDL_Window *window, SDL_Renderer *renderer, Input *input, std::string *fileList, options_t *options, std::string *textStrings) Title::Title(SDL_Window *window, SDL_Renderer *renderer, Input *input, std::string *fileList, options_t *options, Lang *lang)
{ {
// Copia las direcciones de los punteros // Copia las direcciones de los punteros
mWindow = window; mWindow = window;
@@ -13,7 +13,7 @@ Title::Title(SDL_Window *window, SDL_Renderer *renderer, Input *input, std::stri
mInput = input; mInput = input;
mFileList = fileList; mFileList = fileList;
mOptions = options; mOptions = options;
mTextStrings = textStrings; mLang = lang;
// Reserva memoria para los punteros propios // Reserva memoria para los punteros propios
mEventHandler = new SDL_Event(); mEventHandler = new SDL_Event();
@@ -21,12 +21,15 @@ Title::Title(SDL_Window *window, SDL_Renderer *renderer, Input *input, std::stri
mTitleTexture = new LTexture(); mTitleTexture = new LTexture();
mItemsTexture = new LTexture(); mItemsTexture = new LTexture();
mTextTexture = new LTexture(); mTextTexture = new LTexture();
mTextTexture2 = new LTexture();
mCoffeeBitmap = new SmartSprite(); mCoffeeBitmap = new SmartSprite();
mCrisisBitmap = new SmartSprite(); mCrisisBitmap = new SmartSprite();
mDustBitmapL = new AnimatedSprite(); mDustBitmapL = new AnimatedSprite();
mDustBitmapR = new AnimatedSprite(); mDustBitmapR = new AnimatedSprite();
mTile = new Sprite(); mTile = new Sprite();
mText = new Text(mTextTexture, mRenderer); mGradient = new Sprite();
mText = new Text(mFileList[48], mTextTexture, mRenderer);
mText2 = new Text(mFileList[46], mTextTexture2, mRenderer);
mMenu.title = new Menu(mRenderer, mText, mInput, mFileList); mMenu.title = new Menu(mRenderer, mText, mInput, mFileList);
mMenu.options = new Menu(mRenderer, mText, mInput, mFileList); mMenu.options = new Menu(mRenderer, mText, mInput, mFileList);
@@ -38,12 +41,22 @@ Title::Title(SDL_Window *window, SDL_Renderer *renderer, Input *input, std::stri
// Destructor // Destructor
Title::~Title() Title::~Title()
{ {
mWindow = nullptr;
mRenderer = nullptr;
mInput = nullptr;
mFileList = nullptr;
mOptions = nullptr;
mLang = nullptr;
delete mEventHandler; delete mEventHandler;
mEventHandler = nullptr; mEventHandler = nullptr;
delete mText; delete mText;
mText = nullptr; mText = nullptr;
delete mText2;
mText2 = nullptr;
delete mFade; delete mFade;
mFade = nullptr; mFade = nullptr;
@@ -59,6 +72,10 @@ Title::~Title()
delete mTextTexture; delete mTextTexture;
mTextTexture = nullptr; mTextTexture = nullptr;
mTextTexture2->unload();
delete mTextTexture2;
mTextTexture2 = nullptr;
delete mCoffeeBitmap; delete mCoffeeBitmap;
mCoffeeBitmap = nullptr; mCoffeeBitmap = nullptr;
@@ -74,6 +91,9 @@ Title::~Title()
delete mTile; delete mTile;
mTile = nullptr; mTile = nullptr;
delete mGradient;
mGradient = nullptr;
delete mMenu.title; delete mMenu.title;
mMenu.title = nullptr; mMenu.title = nullptr;
@@ -113,10 +133,32 @@ void Title::init(bool demo, Uint8 subsection)
mPostFade = 0; mPostFade = 0;
mTicks = 0; mTicks = 0;
mTicksSpeed = 15; mTicksSpeed = 15;
mText->init(TEXT_FIXED, BLOCK); mFade->init(0x17, 0x17, 0x26);
mFade->init();
mDemo = demo; mDemo = demo;
//if (!mInput->gameControllerFound())
{
mOptions->input[0].id = 0;
mOptions->input[0].name = "KEYBOARD";
mOptions->input[0].deviceType = INPUT_USE_KEYBOARD;
mOptions->input[1].id = 0;
mOptions->input[1].name = "GAME CONTROLLER";
mOptions->input[1].deviceType = INPUT_USE_GAMECONTROLLER;
}
checkInputDevices();
mDeviceIndex[0] = mAvailableInputDevices.size() - 1;
mDeviceIndex[1] = 0;
if (mInput->gameControllerFound())
{
mOptions->input[1].id = mAvailableInputDevices[mDeviceIndex[1]].id;
mOptions->input[1].name = mAvailableInputDevices[mDeviceIndex[1]].name;
mOptions->input[1].deviceType = mAvailableInputDevices[mDeviceIndex[1]].deviceType;
}
// Inicializa el bitmap de Coffee // Inicializa el bitmap de Coffee
mCoffeeBitmap->init(mTitleTexture, mRenderer); mCoffeeBitmap->init(mTitleTexture, mRenderer);
mCoffeeBitmap->setId(0); mCoffeeBitmap->setId(0);
@@ -191,63 +233,62 @@ void Title::init(bool demo, Uint8 subsection)
mDustBitmapL->setAnimationFrames(0, 5, 160 + (mDustBitmapL->getWidth() * 5), 66, mDustBitmapL->getWidth(), mDustBitmapL->getHeight()); mDustBitmapL->setAnimationFrames(0, 5, 160 + (mDustBitmapL->getWidth() * 5), 66, mDustBitmapL->getWidth(), mDustBitmapL->getHeight());
mDustBitmapL->setAnimationFrames(0, 6, 160 + (mDustBitmapL->getWidth() * 6), 66, mDustBitmapL->getWidth(), mDustBitmapL->getHeight()); mDustBitmapL->setAnimationFrames(0, 6, 160 + (mDustBitmapL->getWidth() * 6), 66, mDustBitmapL->getWidth(), mDustBitmapL->getHeight());
// Inicializa el sprite con el degradado
mGradient->init(0, 0, 256, 192, mTitleTexture, mRenderer);
mGradient->setSpriteClip(0, 96, 256, 192);
// Inicializa el vector de eventos de la pantalla de titulo // Inicializa el vector de eventos de la pantalla de titulo
for (int i = 0; i < TITLE_TOTAL_EVENTS; i++) for (int i = 0; i < TITLE_TOTAL_EVENTS; i++)
mEvents[i] = EVENT_WAITING; mEvents[i] = EVENT_WAITING;
// Crea el mosaico de fondo del titulo // Crea el mosaico de fondo del titulo
SDL_SetRenderTarget(mRenderer, mBackground); createTiledBackground();
SDL_SetRenderDrawColor(mRenderer, 0x43, 0x43, 0x4F, 0xFF);
SDL_RenderClear(mRenderer);
mTile->init(0, 0, 64, 64, mTitleTexture, mRenderer); mBackgroundWindow.x = 128;
mTile->setSpriteClip(192, 0, 64, 64); mBackgroundWindow.y = 96;
for (int i = 0; i < 8; i++)
for (int j = 0; j < 6; j++)
{
mTile->setPosX(i * 64);
mTile->setPosY(j * 64);
mTile->render();
}
SDL_SetRenderTarget(mRenderer, nullptr);
mBackgroundWindow.x = 0;
mBackgroundWindow.y = 0;
mBackgroundWindow.w = SCREEN_WIDTH; mBackgroundWindow.w = SCREEN_WIDTH;
mBackgroundWindow.h = SCREEN_HEIGHT; mBackgroundWindow.h = SCREEN_HEIGHT;
// Inicializa los valores del vector con los valores del seno // Inicializa los valores del vector con los valores del seno
for (int i = 0; i < 360; i++) for (int i = 0; i < 360; i++)
{ {
mSin[i] = sin((float)i * 3.14f / 180.0f); mSin[i] = SDL_sinf((float)i * 3.14f / 180.0f);
} }
// Inicializa los objetos de menu // Inicializa los objetos de menu
mMenu.title->init("TITLE", 0, 15 * BLOCK, MENU_BACKGROUND_SOLID); mMenu.title->init("TITLE", 0, (14 * BLOCK) + 4, MENU_BACKGROUND_TRANSPARENT);
mMenu.title->addItem(mTextStrings[0]); // PLAY mMenu.title->addItem(mLang->getText(51), 2); // 1 PLAYER
mMenu.title->addItem(mTextStrings[1]); // OPTIONS mMenu.title->addItem(mLang->getText(52), 7); // 2 PLAYERS
mMenu.title->addItem(mTextStrings[2], 0, 5); // HOW TO PLAY mMenu.title->addItem(mLang->getText(1), 7); // OPTIONS
mMenu.title->addItem(mTextStrings[3]); // QUIT mMenu.title->addItem(mLang->getText(3)); // QUIT
mMenu.title->setDefaultActionWhenCancel(3); mMenu.title->setDefaultActionWhenCancel(3);
mMenu.title->setBackgroundColor(0x30, 0x30, 0x40, 192); mMenu.title->setBackgroundColor(0x30, 0x30, 0x40, 192);
mMenu.title->setSelectorColor(0xe5, 0x1c, 0x23, 255); mMenu.title->setSelectorColor(0xe5, 0x1c, 0x23, 0);
mMenu.title->setSelectorTextColor(0xFF, 0xF1, 0x76); mMenu.title->setSelectorTextColor(0xFF, 0xB4, 0x00);
mMenu.title->centerMenu(SCREEN_CENTER_X); mMenu.title->centerMenuOnX(SCREEN_CENTER_X);
mMenu.title->centerMenuElements(); mMenu.title->centerMenuElementsOnX();
mMenu.options->init("OPTIONS", 0, 14 * BLOCK, MENU_BACKGROUND_SOLID); mMenu.options->init("OPTIONS", 0, BLOCK, MENU_BACKGROUND_TRANSPARENT);
mMenu.options->addItem(mTextStrings[4]); mMenu.options->addItem(mLang->getText(59), 7); // (0) DIFFICULTY
mMenu.options->addItem(mTextStrings[7]); mMenu.options->addItem(mLang->getText(62), 2, true, false, true); // (1) PLAYER 1 CONTROLS
mMenu.options->addItem(mTextStrings[8], 0, 5); mMenu.options->addItem(mLang->getText(69), 7, false, false); // (2) KEYBOARD
mMenu.options->addItem(mTextStrings[9]); mMenu.options->addItem(mLang->getText(63), 2, true, false, true); // (3) PLAYER 2 CONTROLS
mMenu.options->addItem(mTextStrings[10]); mMenu.options->addItem(mLang->getText(70), 7, false, false); // (4) GAME CONTROLLER
mMenu.options->setDefaultActionWhenCancel(4); mMenu.options->addItem(mLang->getText(8), 7); // (5) LANGUAGE
mMenu.options->addItem(mLang->getText(58), 2, true, false, true); // (6) DISPLAY MODE
mMenu.options->addItem(mLang->getText(4), 7, false, false); // (7) WINDOW
mMenu.options->addItem(mLang->getText(7), 2); // (8) WINDOW SIZE
mMenu.options->addItem(mLang->getText(60), 2); // (9) FILTER
mMenu.options->addItem(mLang->getText(61), 7); // (10) VSYNC
mMenu.options->addItem(mLang->getText(2), 7); // (11) HOW TO PLAY
mMenu.options->addItem(mLang->getText(9), 2); // (12) ACCEPT
mMenu.options->addItem(mLang->getText(10)); // (13) CANCEL
mMenu.options->setDefaultActionWhenCancel(13);
mMenu.options->setBackgroundColor(0x30, 0x30, 0x40, 192); mMenu.options->setBackgroundColor(0x30, 0x30, 0x40, 192);
mMenu.options->setSelectorColor(0xe5, 0x1c, 0x23, 255); mMenu.options->setSelectorColor(0xe5, 0x1c, 0x23, 255);
mMenu.options->setSelectorTextColor(0xFF, 0xF1, 0x76); mMenu.options->setSelectorTextColor(0xFF, 0xF1, 0x76);
mMenu.options->centerMenu(SCREEN_CENTER_X); mMenu.options->centerMenuOnX(SCREEN_CENTER_X);
mMenu.options->centerMenuElements(); mMenu.options->centerMenuOnY(SCREEN_CENTER_Y);
// Actualiza los textos de los menus // Actualiza los textos de los menus
updateMenuLabels(); updateMenuLabels();
@@ -263,6 +304,7 @@ bool Title::loadMedia()
success &= loadTextureFromFile(mTitleTexture, mFileList[40], mRenderer); success &= loadTextureFromFile(mTitleTexture, mFileList[40], mRenderer);
success &= loadTextureFromFile(mItemsTexture, mFileList[34], mRenderer); success &= loadTextureFromFile(mItemsTexture, mFileList[34], mRenderer);
success &= loadTextureFromFile(mTextTexture, mFileList[30], mRenderer); success &= loadTextureFromFile(mTextTexture, mFileList[30], mRenderer);
success &= loadTextureFromFile(mTextTexture2, mFileList[27], mRenderer);
// Sonidos // Sonidos
mSound = JA_LoadSound(mFileList[21].c_str()); mSound = JA_LoadSound(mFileList[21].c_str());
@@ -297,51 +339,174 @@ void Title::switchFullScreenModeVar()
// Actualiza los elementos de los menus // Actualiza los elementos de los menus
void Title::updateMenuLabels() void Title::updateMenuLabels()
{ {
switch (mOptions->fullScreenMode) int i = 0;
// DIFFICULTY
switch (mOptions->difficulty)
{ {
case 0: case DIFFICULTY_EASY:
mMenu.options->setItemCaption(0, mTextStrings[4]); // WINDOW mMenu.options->setItemCaption(i, mLang->getText(59) + ": " + mLang->getText(66)); // EASY
break; break;
case SDL_WINDOW_FULLSCREEN:
mMenu.options->setItemCaption(0, mTextStrings[5]); // FULLSCREEN case DIFFICULTY_NORMAL:
mMenu.options->setItemCaption(i, mLang->getText(59) + ": " + mLang->getText(67)); // NORMAL
break; break;
case SDL_WINDOW_FULLSCREEN_DESKTOP:
mMenu.options->setItemCaption(0, mTextStrings[6]); // FAKE FULLSCREEN case DIFFICULTY_HARD:
mMenu.options->setItemCaption(i, mLang->getText(59) + ": " + mLang->getText(68)); // HARD
break; break;
default: default:
mMenu.options->setItemCaption(0, mTextStrings[4]); // WINDOW mMenu.options->setItemCaption(i, mLang->getText(59) + ": " + mLang->getText(67)); // NORMAL
break; break;
} }
mMenu.options->setItemCaption(1, mTextStrings[7] + " x" + std::to_string(mOptions->windowSize)); // WINDOW SIZE i++;
// PLAYER 1 CONTROLS
mMenu.options->setItemCaption(i, mLang->getText(62));
i++;
// PLAYER 1 CONTROLS - OPTIONS
switch (mOptions->input[0].deviceType)
{
case INPUT_USE_KEYBOARD:
mMenu.options->setItemCaption(i, mLang->getText(69)); // KEYBOARD
mMenu.options->setGreyed(i, false);
break;
case INPUT_USE_GAMECONTROLLER:
mMenu.options->setItemCaption(i, mLang->getText(70)); // GAME CONTROLLER
if (!mInput->gameControllerFound())
mMenu.options->setGreyed(i, true);
else
{
mMenu.options->setGreyed(i, false);
//mMenu.options->setItemCaption(i, mInput->getControllerName(0));
mMenu.options->setItemCaption(i, mOptions->input[0].name);
}
break;
default:
mMenu.options->setItemCaption(i, mLang->getText(69)); // KEYBOARD
break;
}
i++;
// PLAYER 2 CONTROLS
mMenu.options->setItemCaption(i, mLang->getText(63));
i++;
// PLAYER 2 CONTROLS - OPTIONS
switch (mOptions->input[1].deviceType)
{
case INPUT_USE_KEYBOARD:
mMenu.options->setItemCaption(i, mLang->getText(69)); // KEYBOARD
mMenu.options->setGreyed(i, false);
break;
case INPUT_USE_GAMECONTROLLER:
mMenu.options->setItemCaption(i, mLang->getText(70)); // GAME CONTROLLER
if (!mInput->gameControllerFound())
mMenu.options->setGreyed(i, true);
else
{
mMenu.options->setGreyed(i, false);
//mMenu.options->setItemCaption(i, mInput->getControllerName(0));
mMenu.options->setItemCaption(i, mOptions->input[1].name);
}
break;
default:
mMenu.options->setItemCaption(i, mLang->getText(69)); // KEYBOARD
break;
}
i++;
// LANGUAGE
switch (mOptions->language) switch (mOptions->language)
{ {
case es_ES: case es_ES:
mMenu.options->setItemCaption(2, mTextStrings[8] + " " + mTextStrings[24]); mMenu.options->setItemCaption(i, mLang->getText(8) + ": " + mLang->getText(24)); // SPANISH
break; break;
case ba_BA: case ba_BA:
mMenu.options->setItemCaption(2, mTextStrings[8] + " " + mTextStrings[25]); mMenu.options->setItemCaption(i, mLang->getText(8) + ": " + mLang->getText(25)); // VALENCIAN
break; break;
case en_UK: case en_UK:
mMenu.options->setItemCaption(2, mTextStrings[8] + " " + mTextStrings[26]); mMenu.options->setItemCaption(i, mLang->getText(8) + ": " + mLang->getText(26)); // ENGLISH
break;
default:
mMenu.options->setItemCaption(i, mLang->getText(8) + ": " + mLang->getText(26)); // ENGLISH
break; break;
} }
mMenu.options->setItemCaption(3, mTextStrings[9]); i++;
mMenu.options->setItemCaption(4, mTextStrings[10]); // DISPLAY MODE
mMenu.options->setItemCaption(i, mLang->getText(58));
mMenu.options->centerMenu(SCREEN_CENTER_X); i++;
mMenu.options->centerMenuElements(); // DISPLAY MODE - OPTIONS
switch (mOptions->fullScreenMode)
{
case 0:
mMenu.options->setItemCaption(i, mLang->getText(4)); // WINDOW
break;
mMenu.title->setItemCaption(0, mTextStrings[0]); case SDL_WINDOW_FULLSCREEN:
mMenu.title->setItemCaption(1, mTextStrings[1]); mMenu.options->setItemCaption(i, mLang->getText(5)); // FULLSCREEN
mMenu.title->setItemCaption(2, mTextStrings[2]); break;
mMenu.title->setItemCaption(3, mTextStrings[3]);
mMenu.title->centerMenu(SCREEN_CENTER_X); case SDL_WINDOW_FULLSCREEN_DESKTOP:
mMenu.title->centerMenuElements(); mMenu.options->setItemCaption(i, mLang->getText(6)); // FAKE FULLSCREEN
break;
default:
mMenu.options->setItemCaption(i, mLang->getText(4)); // WINDOW
break;
}
i++;
// WINDOW SIZE
mMenu.options->setItemCaption(i, mLang->getText(7) + " x" + std::to_string(mOptions->windowSize)); // WINDOW SIZE
i++;
// FILTER
if (mOptions->filter == FILTER_LINEAL)
mMenu.options->setItemCaption(i, mLang->getText(60) + ": " + mLang->getText(71)); // BILINEAL
else
mMenu.options->setItemCaption(i, mLang->getText(60) + ": " + mLang->getText(72)); // LINEAL
i++;
// VSYNC
if (mOptions->vSync)
mMenu.options->setItemCaption(i, mLang->getText(61) + ": " + mLang->getText(73)); // ON
else
mMenu.options->setItemCaption(i, mLang->getText(61) + ": " + mLang->getText(74)); // OFF
i++;
// HOW TO PLAY
mMenu.options->setItemCaption(i, mLang->getText(2));
i++;
// ACCEPT
mMenu.options->setItemCaption(i, mLang->getText(9)); // ACCEPT
i++;
// CANCEL
mMenu.options->setItemCaption(i, mLang->getText(10)); // CANCEL
mMenu.options->centerMenuOnX(SCREEN_CENTER_X);
mMenu.options->centerMenuOnY(SCREEN_CENTER_Y);
mMenu.options->centerMenuElementsOnX();
mMenu.title->setItemCaption(0, mLang->getText(51)); // 1 PLAYER
mMenu.title->setItemCaption(1, mLang->getText(52)); // 2 PLAYERS
mMenu.title->setItemCaption(2, mLang->getText(1)); // OPTIONS
mMenu.title->setItemCaption(3, mLang->getText(3)); // QUIT
mMenu.title->centerMenuOnX(SCREEN_CENTER_X);
mMenu.title->centerMenuElementsOnX();
} }
// Aplica las opciones de menu seleccionadas // Aplica las opciones de menu seleccionadas
@@ -349,8 +514,10 @@ void Title::applyOptions()
{ {
SDL_SetWindowFullscreen(mWindow, mOptions->fullScreenMode); SDL_SetWindowFullscreen(mWindow, mOptions->fullScreenMode);
SDL_SetWindowSize(mWindow, SCREEN_WIDTH * mOptions->windowSize, SCREEN_HEIGHT * mOptions->windowSize); SDL_SetWindowSize(mWindow, SCREEN_WIDTH * mOptions->windowSize, SCREEN_HEIGHT * mOptions->windowSize);
initTextStrings(mTextStrings, mOptions->language); mLang->setLang(mOptions->language);
updateMenuLabels(); updateMenuLabels();
createTiledBackground();
} }
// Bucle para el titulo del juego // Bucle para el titulo del juego
@@ -389,6 +556,12 @@ section_t Title::run(Uint8 subsection)
SDL_SetRenderDrawColor(mRenderer, bgColor.r, bgColor.g, bgColor.b, 255); SDL_SetRenderDrawColor(mRenderer, bgColor.r, bgColor.g, bgColor.b, 255);
SDL_RenderClear(mRenderer); SDL_RenderClear(mRenderer);
// Dibuja el tileado de fondo
SDL_RenderCopy(mRenderer, mBackground, &mBackgroundWindow, NULL);
// Dibuja el degradado
mGradient->render();
// Dibuja los objetos // Dibuja los objetos
mCoffeeBitmap->render(); mCoffeeBitmap->render();
mCrisisBitmap->render(); mCrisisBitmap->render();
@@ -435,6 +608,12 @@ section_t Title::run(Uint8 subsection)
SDL_SetRenderDrawColor(mRenderer, bgColor.r, bgColor.g, bgColor.b, 255); SDL_SetRenderDrawColor(mRenderer, bgColor.r, bgColor.g, bgColor.b, 255);
SDL_RenderClear(mRenderer); SDL_RenderClear(mRenderer);
// Dibuja el tileado de fondo
SDL_RenderCopy(mRenderer, mBackground, &mBackgroundWindow, NULL);
// Dibuja el degradado
mGradient->render();
// Dibuja los objetos // Dibuja los objetos
mCoffeeBitmap->setPosX(a + v[n / 3]); mCoffeeBitmap->setPosX(a + v[n / 3]);
mCrisisBitmap->setPosX(b + v[n / 3]); mCrisisBitmap->setPosX(b + v[n / 3]);
@@ -494,17 +673,24 @@ section_t Title::run(Uint8 subsection)
{ {
switch (mPostFade) switch (mPostFade)
{ {
case 0: // PLAY case 0: // 1 PLAYER
mSection.name = PROG_SECTION_GAME; mSection.name = PROG_SECTION_GAME;
mSection.subsection = GAME_SECTION_PLAY_1P;
JA_StopMusic(); JA_StopMusic();
break; break;
case 1: // QUIT case 1: // 2 PLAYERS
mSection.name = PROG_SECTION_GAME;
mSection.subsection = GAME_SECTION_PLAY_2P;
JA_StopMusic();
break;
case 2: // QUIT
mSection.name = PROG_SECTION_QUIT; mSection.name = PROG_SECTION_QUIT;
JA_StopMusic(); JA_StopMusic();
break; break;
case 2: // TIME OUT case 3: // TIME OUT
mCounter = TITLE_COUNTER; mCounter = TITLE_COUNTER;
mMenu.active->reset(); mMenu.active->reset();
if (mDemo) if (mDemo)
@@ -522,6 +708,26 @@ section_t Title::run(Uint8 subsection)
} }
} }
// Actualiza el tileado de fondo
switch (mBackgroundMode)
{
case 0: // El tileado de fondo se desplaza en diagonal
mBackgroundWindow.x++;
mBackgroundWindow.x %= 64;
mBackgroundWindow.y++;
mBackgroundWindow.y %= 64;
break;
case 1: // El tileado de fondo se desplaza en circulo
++mBackgroundCounter %= 360;
mBackgroundWindow.x = 128 + (int(mSin[(mBackgroundCounter + 270) % 360] * 128));
mBackgroundWindow.y = 96 + (int(mSin[(360 - mBackgroundCounter) % 360] * 96));
break;
default:
break;
}
// Comprueba las entradas para el menu // Comprueba las entradas para el menu
if (mMenuVisible == true) if (mMenuVisible == true)
mMenu.active->checkInput(); mMenu.active->checkInput();
@@ -531,21 +737,20 @@ section_t Title::run(Uint8 subsection)
{ {
switch (mMenu.active->getItemSelected()) switch (mMenu.active->getItemSelected())
{ {
case 0: // PLAY case 0: // 1 PLAYER
mPostFade = 0; mPostFade = 0;
mFade->activateFade(); mFade->activateFade();
break; break;
case 1: // OPTIONS case 1: // 2 PLAYERS
mMenu.active = mMenu.options; mPostFade = 1;
mOptions->fullScreenModePrevious = mOptions->fullScreenMode; mFade->activateFade();
mOptions->windowSizePrevious = mOptions->windowSize;
mOptions->languagePrevious = mOptions->language;
break; break;
case 2: // HOW TO PLAY case 2: // OPTIONS
runInstructions(INSTRUCTIONS_MODE_MANUAL); mMenu.active = mMenu.options;
mOptionsPrevious = *mOptions;
break; break;
case 3: // QUIT case 3: // QUIT
mPostFade = 1; mPostFade = 2;
mFade->activateFade(); mFade->activateFade();
break; break;
@@ -559,31 +764,73 @@ section_t Title::run(Uint8 subsection)
{ {
switch (mMenu.active->getItemSelected()) switch (mMenu.active->getItemSelected())
{ {
case 0: // Fullscreen mode case 0: // Difficulty
switchFullScreenModeVar(); if (mOptions->difficulty == DIFFICULTY_EASY)
mOptions->difficulty = DIFFICULTY_NORMAL;
else if (mOptions->difficulty == DIFFICULTY_NORMAL)
mOptions->difficulty = DIFFICULTY_HARD;
else
mOptions->difficulty = DIFFICULTY_EASY;
updateMenuLabels(); updateMenuLabels();
break; break;
case 1: // Windows size case 1: // PLAYER 1 CONTROLS
mOptions->windowSize++; updatePlayerInputs(0);
if (mOptions->windowSize == 5)
mOptions->windowSize = 1;
updateMenuLabels(); updateMenuLabels();
break; break;
case 2: // Language case 3: // PLAYER 2 CONTROLS
updatePlayerInputs(1);
updateMenuLabels();
break;
case 5: // Language
mOptions->language++; mOptions->language++;
if (mOptions->language == 3) if (mOptions->language == 3)
mOptions->language = 0; mOptions->language = 0;
updateMenuLabels(); updateMenuLabels();
break; break;
case 3: // OK case 6: // Display mode
switchFullScreenModeVar();
if (mOptions->fullScreenMode != 0)
{
mMenu.options->setSelectable(8, false);
mMenu.options->setGreyed(8, true);
}
else
{
mMenu.options->setSelectable(8, true);
mMenu.options->setGreyed(8, false);
}
updateMenuLabels();
break;
case 8: // Windows size
mOptions->windowSize++;
if (mOptions->windowSize == 5)
mOptions->windowSize = 1;
updateMenuLabels();
break;
case 9: // FILTER
if (mOptions->filter == FILTER_LINEAL)
mOptions->filter = FILTER_NEAREST;
else
mOptions->filter = FILTER_LINEAL;
updateMenuLabels();
break;
case 10: // VSYNC
if (mOptions->vSync)
mOptions->vSync = false;
else
mOptions->vSync = true;
updateMenuLabels();
break;
case 11: // HOW TO PLAY
runInstructions(INSTRUCTIONS_MODE_MANUAL);
break;
case 12: // ACCEPT
applyOptions(); applyOptions();
mMenu.active->reset(); mMenu.active->reset();
mMenu.active = mMenu.title; mMenu.active = mMenu.title;
break; break;
case 4: // CANCEL case 13: // CANCEL
mOptions->fullScreenMode = mOptions->fullScreenModePrevious; mOptions = &mOptionsPrevious;
mOptions->windowSize = mOptions->windowSizePrevious;
mOptions->language = mOptions->languagePrevious;
updateMenuLabels(); updateMenuLabels();
mMenu.active->reset(); mMenu.active->reset();
mMenu.active = mMenu.title; mMenu.active = mMenu.title;
@@ -604,33 +851,26 @@ section_t Title::run(Uint8 subsection)
SDL_SetRenderDrawColor(mRenderer, bgColor.r, bgColor.g, bgColor.b, 255); SDL_SetRenderDrawColor(mRenderer, bgColor.r, bgColor.g, bgColor.b, 255);
SDL_RenderClear(mRenderer); SDL_RenderClear(mRenderer);
// Pinta el tileado de fondo // Dibuja el tileado de fondo
switch (mBackgroundMode)
{
case 0: // El tileado de fondo se desplaza en diagonal
mBackgroundWindow.x++;
mBackgroundWindow.x %= 64;
mBackgroundWindow.y++;
mBackgroundWindow.y %= 64;
break;
case 1: // El tileado de fondo se desplaza en circulo
++mBackgroundCounter %= 360;
mBackgroundWindow.x = 128 + (int(mSin[(mBackgroundCounter + 270) % 360] * 128));
mBackgroundWindow.y = 96 + (int(mSin[(360 - mBackgroundCounter) % 360] * 96));
break;
default:
break;
}
SDL_RenderCopy(mRenderer, mBackground, &mBackgroundWindow, NULL); SDL_RenderCopy(mRenderer, mBackground, &mBackgroundWindow, NULL);
// Dibuja el degradado
mGradient->render();
// Dibuja los objetos // Dibuja los objetos
mCoffeeBitmap->render(); if (mMenu.active->getName() != "OPTIONS")
mCrisisBitmap->render(); {
// Bitmaps con el logo/titulo del juego
mCoffeeBitmap->render();
mCrisisBitmap->render();
// Texto con el copyright y versión
mText2->writeDX(TXT_CENTER | TXT_SHADOW, SCREEN_CENTER_X, SCREEN_HEIGHT - (BLOCK * 2), TEXT_COPYRIGHT, 1, noColor, 1, shdwTxtColor);
}
if (mMenuVisible == true) if (mMenuVisible == true)
mMenu.active->render(); mMenu.active->render();
mDustBitmapR->animate(0); mDustBitmapR->animate(0);
mDustBitmapL->animate(0); mDustBitmapL->animate(0);
mDustBitmapR->render(); mDustBitmapR->render();
@@ -638,10 +878,7 @@ section_t Title::run(Uint8 subsection)
// PRESS ANY KEY! // PRESS ANY KEY!
if ((mCounter % 50 > 14) && (mMenuVisible == false)) if ((mCounter % 50 > 14) && (mMenuVisible == false))
mText->writeDX(TXT_CENTER | TXT_SHADOW, SCREEN_CENTER_X, PLAY_AREA_THIRD_QUARTER_Y + BLOCK, mTextStrings[23], 0, noColor, 1, shdwTxtColor); mText->writeDX(TXT_CENTER | TXT_SHADOW, SCREEN_CENTER_X, PLAY_AREA_THIRD_QUARTER_Y + BLOCK, mLang->getText(23), 1, noColor, 1, shdwTxtColor);
// Texto con el copyright y versión
mText->writeDX(TXT_CENTER | TXT_SHADOW, SCREEN_CENTER_X, SCREEN_HEIGHT - (BLOCK * 2), TEXT_COPYRIGHT, 0, noColor, 1, shdwTxtColor);
// Fade // Fade
mFade->render(); mFade->render();
@@ -676,7 +913,7 @@ section_t Title::run(Uint8 subsection)
// Ejecuta la parte donde se muestran las instrucciones // Ejecuta la parte donde se muestran las instrucciones
void Title::runInstructions(Uint8 mode) void Title::runInstructions(Uint8 mode)
{ {
mInstructions = new Instructions(mRenderer, mFileList, mTextStrings); mInstructions = new Instructions(mRenderer, mFileList, mLang);
mInstructions->run(mode); mInstructions->run(mode);
delete mInstructions; delete mInstructions;
} }
@@ -684,7 +921,110 @@ void Title::runInstructions(Uint8 mode)
// Ejecuta el juego en modo demo // Ejecuta el juego en modo demo
void Title::runDemoGame() void Title::runDemoGame()
{ {
mDemoGame = new Game(mRenderer, mFileList, mTextStrings, mInput, true); mDemoGame = new Game(1, mRenderer, mFileList, mLang, mInput, true, mOptions);
mDemoGame->run(); mDemoGame->run();
delete mDemoGame; delete mDemoGame;
}
// Modifica las opciones para los controles de los jugadores
bool Title::updatePlayerInputs(int numPlayer)
{
const int numDevices = mAvailableInputDevices.size();
// Si no hay mandos se deja todo de manera prefijada
if (!mInput->gameControllerFound())
{
mDeviceIndex[0] = 0;
mDeviceIndex[1] = 0;
mOptions->input[0].id = -1;
mOptions->input[0].name = "KEYBOARD";
mOptions->input[0].deviceType = INPUT_USE_KEYBOARD;
mOptions->input[1].id = 0;
mOptions->input[1].name = "GAME CONTROLLER";
mOptions->input[1].deviceType = INPUT_USE_GAMECONTROLLER;
return true;
}
else // Si hay mas de un dispositivo, se recorre el vector
{
printf("numplayer:%i\n",numPlayer);
printf("deviceindex:%i\n",mDeviceIndex[numPlayer]);
// Incrementa el indice
if (mDeviceIndex[numPlayer] < numDevices - 1)
mDeviceIndex[numPlayer]++;
else
mDeviceIndex[numPlayer] = 0;
printf("deviceindex:%i\n",mDeviceIndex[numPlayer]);
// Si coincide con el del otro jugador, se lo intercambian
if (mDeviceIndex[0] == mDeviceIndex[1])
{
printf("%i:%i\n",mDeviceIndex[0],mDeviceIndex[1]);
//const int temp = mDeviceIndex[0];
//mDeviceIndex[0] = mDeviceIndex[1];
//mDeviceIndex[1] = temp;
const int theOtherPlayer = (numPlayer + 1) % 2;
mDeviceIndex[theOtherPlayer]--;
if (mDeviceIndex[theOtherPlayer] < 0)
mDeviceIndex[theOtherPlayer]=numDevices-1;
printf("%i:%i\n",mDeviceIndex[0],mDeviceIndex[1]);
}
// Copia el dispositivo marcado por el indice a la variable de opciones de cada jugador
mOptions->input[0] = mAvailableInputDevices[mDeviceIndex[0]];
mOptions->input[1] = mAvailableInputDevices[mDeviceIndex[1]];
return true;
}
}
// Crea el mosaico de fondo del titulo
void Title::createTiledBackground()
{
SDL_SetRenderTarget(mRenderer, mBackground);
SDL_SetRenderDrawColor(mRenderer, 0x43, 0x43, 0x4F, 0xFF);
SDL_RenderClear(mRenderer);
mTile->init(0, 0, 64, 64, mTitleTexture, mRenderer);
mTile->setSpriteClip(192, 0, 64, 64);
for (int i = 0; i < 8; i++)
for (int j = 0; j < 6; j++)
{
mTile->setPosX(i * 64);
mTile->setPosY(j * 64);
mTile->render();
}
SDL_SetRenderTarget(mRenderer, nullptr);
}
// Comprueba cuantos mandos hay conectados para gestionar el menu de opciones
void Title::checkInputDevices()
{
printf("Filling devices for options menu...\n");
int numControllers = mInput->getNumControllers();
mAvailableInputDevices.clear();
input_t temp;
// Añade todos los mandos
if (numControllers > 0)
for (int i = 0; i < numControllers; i++)
{
temp.id = i;
temp.name = mInput->getControllerName(i);
temp.deviceType = INPUT_USE_GAMECONTROLLER;
mAvailableInputDevices.push_back(temp);
printf("Device %i:\t%s\n", (int)mAvailableInputDevices.size(), temp.name.c_str());
}
// Añade el teclado al final
temp.id = -1;
temp.name = "KEYBOARD";
temp.deviceType = INPUT_USE_KEYBOARD;
mAvailableInputDevices.push_back(temp);
printf("Device %i:\t%s\n\n", (int)mAvailableInputDevices.size(), temp.name.c_str());
} }

View File

@@ -33,16 +33,17 @@ private:
LTexture *mItemsTexture; // Textura con los gráficos de los items para las instrucciones LTexture *mItemsTexture; // Textura con los gráficos de los items para las instrucciones
LTexture *mTitleTexture; // Textura con los graficos para el titulo LTexture *mTitleTexture; // Textura con los graficos para el titulo
LTexture *mTextTexture; // Textura con los gráficos para el texto LTexture *mTextTexture; // Textura con los gráficos para el texto
LTexture *mTextTexture2; // Textura con los gráficos para el texto
SDL_Event *mEventHandler; // Manejador de eventos SDL_Event *mEventHandler; // Manejador de eventos
SDL_Rect mBackgroundWindow; // Ventana visible para la textura de fondo del titulo SDL_Rect mBackgroundWindow; // Ventana visible para la textura de fondo del titulo
SDL_Renderer *mRenderer; // El renderizador de la ventana SDL_Renderer *mRenderer; // El renderizador de la ventana
//SDL_Texture *mBackbuffer; // Textura para usar como backbuffer
SDL_Texture *mBackground; // Textura dibujar el fondo del titulo SDL_Texture *mBackground; // Textura dibujar el fondo del titulo
SmartSprite *mCoffeeBitmap; // Sprite con la palabra COFFEE para la pantalla de titulo SmartSprite *mCoffeeBitmap; // Sprite con la palabra COFFEE para la pantalla de titulo
SmartSprite *mCrisisBitmap; // Sprite con la palabra CRISIS para la pantalla de titulo SmartSprite *mCrisisBitmap; // Sprite con la palabra CRISIS para la pantalla de titulo
Sprite *mTile; // Sprite para dibujar el fondo de pantalla del título Sprite *mTile; // Sprite para dibujar el fondo de pantalla del título
Sprite *mGradient; // Sprite para dibujar el degradado del titulo
std::string *mFileList; // Lista de ficheros std::string *mFileList; // Lista de ficheros
std::string *mTextStrings; // Vector con los textos del juego Lang *mLang; // Objeto para gestionar los textos en diferentes idiomas
Uint16 mBackgroundCounter; // Temporizador para el fondo de tiles de la pantalla de titulo Uint16 mBackgroundCounter; // Temporizador para el fondo de tiles de la pantalla de titulo
Uint16 mCounter; // Temporizador para la pantalla de titulo Uint16 mCounter; // Temporizador para la pantalla de titulo
Uint32 mTicks; // Contador de ticks para ajustar la velocidad del programa Uint32 mTicks; // Contador de ticks para ajustar la velocidad del programa
@@ -53,6 +54,7 @@ private:
section_t mNextSection; // Indica cual es la siguiente sección a cargar cuando termine el contador del titulo section_t mNextSection; // Indica cual es la siguiente sección a cargar cuando termine el contador del titulo
Uint8 mTicksSpeed; // Velocidad a la que se repiten los bucles del programa Uint8 mTicksSpeed; // Velocidad a la que se repiten los bucles del programa
Text *mText; // Objeto de texto para poder escribir textos en pantalla Text *mText; // Objeto de texto para poder escribir textos en pantalla
Text *mText2; // Objeto de texto para poder escribir textos en pantalla
Fade *mFade; // Objeto para realizar fundidos en pantalla Fade *mFade; // Objeto para realizar fundidos en pantalla
Uint8 mPostFade; // Opción a realizar cuando termina el fundido Uint8 mPostFade; // Opción a realizar cuando termina el fundido
Input *mInput; // Objeto para leer las entradas de teclado o mando Input *mInput; // Objeto para leer las entradas de teclado o mando
@@ -69,6 +71,9 @@ private:
menu_t mMenu; // Variable con todos los objetos menus y sus variables menu_t mMenu; // Variable con todos los objetos menus y sus variables
struct options_t *mOptions; // Variable con todas las variables de las opciones del programa struct options_t *mOptions; // Variable con todas las variables de las opciones del programa
options_t mOptionsPrevious; // Variable de respaldo para las opciones
std::vector<input_t> mAvailableInputDevices; // Vector con todos los metodos de control disponibles
int mDeviceIndex[2]; // Indice para el jugador [i] del vector de dispositivos de entrada disponibles
// Carga los recursos necesarios para la sección 'Title' // Carga los recursos necesarios para la sección 'Title'
bool loadMedia(); bool loadMedia();
@@ -88,9 +93,18 @@ private:
// Ejecuta el juego en modo demo // Ejecuta el juego en modo demo
void runDemoGame(); void runDemoGame();
// Modifica las opciones para los controles de los jugadores
bool updatePlayerInputs(int numPlayer);
// Crea el mosaico de fondo del titulo
void createTiledBackground();
// Comprueba cuantos mandos hay conectados para gestionar el menu de opciones
void checkInputDevices();
public: public:
// Constructor // Constructor
Title(SDL_Window *window, SDL_Renderer *renderer, Input *input, std::string *fileList, options_t *options, std::string *textStrings); Title(SDL_Window *window, SDL_Renderer *renderer, Input *input, std::string *fileList, options_t *options, Lang *lang);
// Destructor // Destructor
~Title(); ~Title();

View File

@@ -1,6 +1,7 @@
#pragma once #pragma once
#include "ifdefs.h" #include "ifdefs.h"
#include "ltexture.h" #include "ltexture.h"
#include <string>
#ifndef UTILS_H #ifndef UTILS_H
#define UTILS_H #define UTILS_H
@@ -8,9 +9,9 @@
// Estructura para definir un circulo // Estructura para definir un circulo
struct circle_t struct circle_t
{ {
Uint16 x; int x;
Uint16 y; int y;
Uint8 r; int r;
}; };
// Estructura para definir un color // Estructura para definir un color
@@ -39,15 +40,24 @@ struct demoKeys_t
Uint8 fireRight; Uint8 fireRight;
}; };
// Estructura para albergar métodos de control
struct input_t
{
int id; // Identificador en el vector de mandos
std::string name; // Nombre del dispositivo
Uint8 deviceType; // Tipo de dispositivo (teclado o mando)
};
// Estructura con todas las opciones de configuración del programa // Estructura con todas las opciones de configuración del programa
struct options_t struct options_t
{ {
Uint32 fullScreenMode; // Contiene el valor del modo de pantalla completa Uint8 difficulty; // Dificultad del juego
Uint32 fullScreenModePrevious; // Usado por si se cancelan los cambios en el menu de opciones input_t input[2]; // Modo de control (teclado o mando)
Uint8 windowSize; // Contiene el valor del tamaño de la ventana Uint8 language; // Idioma usado en el juego
Uint8 windowSizePrevious; // Usado por si se cancelan los cambios en el menu de opciones Uint32 fullScreenMode; // Contiene el valor del modo de pantalla completa
Uint8 language; // Idioma usado en el juego Uint8 windowSize; // Contiene el valor del tamaño de la ventana
Uint8 languagePrevious; // Usado por si se cancelan los cambios en el menu de opciones Uint32 filter; // Filtro usado para el escalado de la imagen
bool vSync; // Indica si se quiere usar vsync o no
}; };
// Calcula el cuadrado de la distancia entre dos puntos // Calcula el cuadrado de la distancia entre dos puntos

View File

@@ -1,29 +1,31 @@
#include "const.h" #include "const.h"
#include "text2.h" #include "writer.h"
// Constructor // Constructor
Text2::Text2(LTexture *texture, SDL_Renderer *renderer) : Text(texture, renderer) Writer::Writer(Text *text)
{ {
mText = text;
init();
} }
// Destructor // Destructor
Text2::~Text2() Writer::~Writer()
{ {
mText = nullptr;
} }
// Inicializador // Inicializador
void Text2::init(Uint8 type, Uint8 size) void Writer::init()
{ {
Text::init(type, size);
mPosX = 0; mPosX = 0;
mPosY = 0; mPosY = 0;
mKerning = 0; mKerning = 0;
mCaption = ""; mCaption = "";
mWrittingSpeed = 0; mSpeed = 0;
mWrittingTimer = 0; mTimer = 0;
mIndex = 0; mIndex = 0;
mLenght = 0; mLenght = 0;
mWrittingCompleted = false; mCompleted = false;
mEnabled = false; mEnabled = false;
mEnabledTimer = 0; mEnabledTimer = 0;
mId = -1; mId = -1;
@@ -31,87 +33,87 @@ void Text2::init(Uint8 type, Uint8 size)
} }
// Establece el valor de la variable // Establece el valor de la variable
void Text2::setPosX(int value) void Writer::setPosX(int value)
{ {
mPosX = value; mPosX = value;
} }
// Establece el valor de la variable // Establece el valor de la variable
void Text2::setPosY(int value) void Writer::setPosY(int value)
{ {
mPosY = value; mPosY = value;
} }
// Establece el valor de la variable // Establece el valor de la variable
void Text2::setKerning(int value) void Writer::setKerning(int value)
{ {
mKerning = value; mKerning = value;
} }
// Establece el valor de la variable // Establece el valor de la variable
void Text2::setCaption(std::string text) void Writer::setCaption(std::string text)
{ {
mCaption = text; mCaption = text;
mLenght = text.length(); mLenght = text.length();
} }
// Establece el valor de la variable // Establece el valor de la variable
void Text2::setWrittingSpeed(Uint16 value) void Writer::setSpeed(Uint16 value)
{ {
mWrittingSpeed = value; mSpeed = value;
mWrittingTimer = value; mTimer = value;
} }
// Establece el valor de la variable // Establece el valor de la variable
void Text2::setEnabled(bool value) void Writer::setEnabled(bool value)
{ {
mEnabled = value; mEnabled = value;
} }
// Obtiene el valor de la variable // Obtiene el valor de la variable
bool Text2::IsEnabled() bool Writer::IsEnabled()
{ {
return mEnabled; return mEnabled;
} }
// Establece el valor de la variable // Establece el valor de la variable
void Text2::setEnabledTimer(Uint16 value) void Writer::setEnabledTimer(Uint16 value)
{ {
mEnabledTimer = value; mEnabledTimer = value;
} }
// Obtiene el valor de la variable // Obtiene el valor de la variable
Uint16 Text2::getEnabledTimer() Uint16 Writer::getEnabledTimer()
{ {
return mEnabledTimer; return mEnabledTimer;
} }
// Actualiza el objeto // Actualiza el objeto
void Text2::update() void Writer::update()
{ {
if (mEnabled) if (mEnabled)
{ {
if (mWrittingCompleted == false) if (mCompleted == false)
{ {
if (mWrittingTimer > 0) if (mTimer > 0)
{ {
--mWrittingTimer; mTimer--;
} }
if (mWrittingTimer == 0) if (mTimer == 0)
{ {
++mIndex; mIndex++;
mWrittingTimer = mWrittingSpeed; mTimer = mSpeed;
} }
if (mIndex == mLenght) if (mIndex == mLenght)
{ {
mWrittingCompleted = true; mCompleted = true;
} }
} }
if (mWrittingCompleted) if (mCompleted)
{ {
if (mEnabledTimer > 0) if (mEnabledTimer > 0)
{ {
--mEnabledTimer; mEnabledTimer--;
} }
else if (mEnabledTimer == 0) else if (mEnabledTimer == 0)
{ {
@@ -129,28 +131,28 @@ void Text2::update()
} }
// Dibuja el objeto en pantalla // Dibuja el objeto en pantalla
void Text2::render() void Writer::render()
{ {
if (mEnabled) if (mEnabled)
{ {
Text::write(mPosX, mPosY, mCaption, mKerning, mIndex); mText->write(mPosX, mPosY, mCaption, mKerning, mIndex);
} }
} }
// Centra la cadena de texto a un punto X // Centra la cadena de texto a un punto X
void Text2::center(int x) void Writer::center(int x)
{ {
setPosX(x - (lenght(mCaption, mKerning) / 2)); setPosX(x - (mText->lenght(mCaption, mKerning) / 2));
} }
// Establece el valor de la variable // Establece el valor de la variable
void Text2::setId(int id) void Writer::setId(int id)
{ {
mId = id; mId = id;
} }
// Establece el valor de la variable // Establece el valor de la variable
void Text2::setIntroEvents(Uint8 *value) void Writer::setIntroEvents(Uint8 *value)
{ {
mIntroEvents = value; mIntroEvents = value;
} }

View File

@@ -1,102 +1,80 @@
#pragma once #pragma once
#include "sprite.h" #include "sprite.h"
#include "text.h" #include "text.h"
#ifndef TEXT2_H #ifndef WRITER_H
#define TEXT2_H #define WRITER_H
// Clase texto. Pinta texto en pantalla a partir de un bitmap // Clase texto. Pinta texto en pantalla a partir de un bitmap
class Text2 : public Text class Writer
{ {
public: private:
// Constructor int mPosX; // Posicion en el eje X donde empezar a escribir el texto
Text2(LTexture *texture, SDL_Renderer *renderer); int mPosY; // Posicion en el eje Y donde empezar a escribir el texto
int mKerning; // Kerning del texto, es decir, espaciado entre caracteres
// Destructor std::string mCaption; // El texto para escribir
~Text2(); Uint16 mSpeed; // Velocidad de escritura
Uint16 mTimer; // Temporizador de escritura para cada caracter
// Inicializador Uint16 mIndex; // Posición del texto que se está escribiendo
void init(Uint8 type, Uint8 size); Uint16 mLenght; // Longitud de la cadena a escribir
bool mCompleted; // Indica si se ha escrito todo el texto
// Establece el valor de la variable bool mEnabled; // Indica si el objeto está habilitado
void setPosX(int value); Uint16 mEnabledTimer; // Temporizador para deshabilitar el objeto
int mId; // Temporizador para deshabilitar el objeto
// Establece el valor de la variable Uint8 *mIntroEvents; // Dirección del array de eventos donde notificar el estado
void setPosY(int value); Text *mText; // Objeto encargado de escribir el texto
// Establece el valor de la variable public:
void setKerning(int value); // Constructor
Writer(Text *text);
// Establece el valor de la variable
void setCaption(std::string text); // Destructor
~Writer();
// Establece el valor de la variable
void setWrittingSpeed(Uint16 value); // Inicializador
void init();
// Establece el valor de la variable
void setEnabled(bool value); // Establece el valor de la variable
void setPosX(int value);
// Obtiene el valor de la variable
bool IsEnabled(); // Establece el valor de la variable
void setPosY(int value);
// Establece el valor de la variable
void setEnabledTimer(Uint16 value); // Establece el valor de la variable
void setKerning(int value);
// Obtiene el valor de la variable
Uint16 getEnabledTimer(); // Establece el valor de la variable
void setCaption(std::string text);
// Actualiza el objeto
void update(); // Establece el valor de la variable
void setSpeed(Uint16 value);
// Dibuja el objeto en pantalla
void render(); // Establece el valor de la variable
void setEnabled(bool value);
// Centra la cadena de texto a un punto X
void center(int x); // Obtiene el valor de la variable
bool IsEnabled();
// Establece el valor de la variable
void setId(int id); // Establece el valor de la variable
void setEnabledTimer(Uint16 value);
// Establece el valor de la variable
void setIntroEvents(Uint8 *value); // Obtiene el valor de la variable
Uint16 getEnabledTimer();
private:
// Posicion X/Y donde empezar a escribir el texto // Actualiza el objeto
int mPosX; void update();
int mPosY;
// Dibuja el objeto en pantalla
// Kerning del texto void render();
int mKerning;
// Centra la cadena de texto a un punto X
// Texto para escribir void center(int x);
std::string mCaption;
// Establece el valor de la variable
// Velocidad de escritura void setId(int id);
Uint16 mWrittingSpeed;
// Establece el valor de la variable
// Temporizador de escritura para cada caracter void setIntroEvents(Uint8 *value);
Uint16 mWrittingTimer; };
// Posición del texto que se está escribiendo #endif
Uint16 mIndex;
// Longitud de la cadena a escribir
Uint16 mLenght;
// Indica si se ha escrito todo el texto
bool mWrittingCompleted;
// Indica si el objeto está habilitado
bool mEnabled;
// Temporizador para deshabilitar el objeto
Uint16 mEnabledTimer;
// Identificador
int mId;
// Dirección del array de eventos donde notificar el estado
Uint8 *mIntroEvents;
};
#endif

36
sync.sh
View File

@@ -1,36 +0,0 @@
#!/bin/bash
readonly PROJECT=coffee_crisis
readonly USAGE="
USAGE:
$(basename "$0") [UPLOAD or DOWNLOAD]"
function help_message() {
echo "$USAGE"
}
PARAMETERS="UPLOAD DOWNLOAD upload download"
# check if there are all the parameters
if [ "$#" -ne 1 ]; then
help_message
exit 0
fi
# check if the systems parameter is valid
if ! echo "$PARAMETERS" | grep -w "$1" >/dev/null; then
help_message
exit 0
fi
# UPLOAD
if [ "$1" = upload ] || [ "$1" = UPLOAD ]; then
printf "\n%s\n" "uploading $PROJECT"
rsync -avzmPu --delete -e 'ssh -p 4545' . sergio@sustancia.synology.me:/home/sergio/backup/code/$PROJECT/
rsync -avzmPu -e 'ssh -p 4545' . sergio@sustancia.synology.me:/home/sergio/backup/code/$PROJECT.all/
fi
if [ "$1" = download ] || [ "$1" = DOWNLOAD ]; then
printf "%s\n" "downloading $PROJECT"
rsync -avzmP --delete -e 'ssh -p 4545' sergio@sustancia.synology.me:/home/sergio/backup/code/$PROJECT/* .
fi