32 Commits

Author SHA1 Message Date
8c293a6b7f Añadido coffee_crisis.icns 2022-11-11 21:38:09 +01:00
a3599d2d3d Actualizado Makefile para crear releases. Ejecutable pasa a estar en la raíz 2022-11-11 18:55:28 +01:00
7ab81eaf29 Actualizado animatedsprite.cpp 2022-10-20 09:18:18 +02:00
4f1a596e46 Arreglos y limpieza de código 2022-10-19 09:53:23 +02:00
b07baa4669 Movidos los archivos de clases comunes a la carpeta common 2022-10-19 09:38:38 +02:00
cf357560b2 Pequeños cambios en las librerias comunes 2022-10-17 19:53:19 +02:00
3d52c45f5c Actualizado Makefile 2022-10-14 10:55:27 +02:00
3276027044 Subido el numero de versión 2022-10-14 10:46:18 +02:00
8041595976 Añadido contador al quitar el menu de pausa del juego 2022-10-14 10:44:50 +02:00
fa53c1b01a Merge branch 'master' of https://gitea.sustancia.synology.me/JailDesigner/coffee_crisis 2022-10-14 09:56:22 +02:00
20b362160e Arreglado el fallo en el sprite de muerte del arounder, tenia pantalón corto 2022-10-14 09:56:04 +02:00
5cabbfc487 Eliminar 'data/config/config.bin' 2022-10-14 09:53:38 +02:00
9f5e001c70 Eliminar 'data/config/score.bin' 2022-10-14 09:53:27 +02:00
112c3afc76 Solucionado el problema de no cerrar el juego durante la demo o las instrucciones 2022-10-14 09:52:15 +02:00
f4215384fe Actualizado Makefile 2022-10-13 10:46:40 +02:00
7796cee51a Actualizado Makefile 2022-10-13 10:41:22 +02:00
f83154c062 Listo para lanzamiento 2022-10-09 14:23:45 +02:00
9e73f7f97d Eliminado todo.txt 2022-10-09 13:02:18 +02:00
742ca02573 Revisados varios pequeños bugs 2022-10-09 12:58:23 +02:00
d77757853d Quitadas las cabezas rojas de powerup y acelerada la animación 2022-10-09 12:01:28 +02:00
ca7ae7418e Arreglado el modo 2P 2022-10-09 11:46:11 +02:00
f880bb7d74 Modificado el ritmo de las numbes i el cambio de color del cielo 2022-10-08 00:14:14 +02:00
9784b5517a Trabajando el menu de game over y el player_fire 2022-10-07 22:44:57 +02:00
88041eba23 Merge branch 'master' of https://gitea.sustancia.synology.me/JailDesigner/coffee_crisis 2022-10-07 18:30:44 +02:00
698721ae03 Trabajando en la pantalla de game over 2022-10-07 18:30:41 +02:00
c7109a46cd Pequeños ajustes y detalles 2022-10-07 13:56:51 +02:00
bb20522172 Arreglados dos fallos del menu 2022-10-06 19:06:39 +02:00
bebc016f3c Las instrucciones ya usan las nuevas texturas de objetos 2022-10-06 13:46:41 +02:00
56c1a1d7f3 Arreglada la animacion de morir. Ya no se usan smartsprites 2022-10-06 13:13:27 +02:00
50d2a5d1c7 Ya va pasando del titulo a las instrucciones, a la demo, etc.. 2022-10-06 10:31:48 +02:00
83103ddfea Arreglados los cambios de lenguaje 2022-10-06 09:39:39 +02:00
f4f7bb52b3 Actualizado makefile 2022-10-06 08:01:23 +02:00
82 changed files with 3140 additions and 2065 deletions

15
.gitignore vendored
View File

@@ -1,6 +1,13 @@
.vscode
*config.txt
*.DS_Store
bin
data/config.txt
data/config.bin
data/score.bin
thumbs.db
*.exe
*_macos
*_linux
*.dmg
*.tar.gz
*.zip
*.app
*config.bin
*score.bin

124
Makefile
View File

@@ -1,16 +1,118 @@
executable = coffee_crisis
source = source/*.cpp source/common/*.cpp
appName = Coffee Crisis
releaseFolder = cc_release
version = v2.1b
windows:
mkdir bin
g++ -std=c++11 -Wall -O2 source/*.cpp -lmingw32 -lSDL2main -lSDL2 -o bin/coffee_crisis.exe
@echo off
powershell if (Test-Path data\config\config.bin) {Remove-Item data\config\config.bin -Recurse -Force}
powershell if (Test-Path data\config\score.bin) {Remove-Item data\config\score.bin -Recurse -Force}
g++ $(source) -std=c++11 -Wall -Os -lmingw32 -lSDL2main -lSDL2 -ffunction-sections -fdata-sections -Wl,--gc-sections -static-libstdc++ -Wl,-subsystem,windows -o $(executable).exe
strip -s -R .comment -R .gnu.version $(executable).exe --strip-unneeded
windows_release:
@echo off
# Remove data
powershell if (Test-Path data\config\config.bin) {Remove-Item data\config\config.bin -Recurse -Force}
powershell if (Test-Path data\config\score.bin) {Remove-Item data\config\score.bin -Recurse -Force}
powershell if (Test-Path $(releaseFolder)) {Remove-Item $(releaseFolder) -Recurse -Force}
# Create folders
powershell if (-not (Test-Path $(releaseFolder))) {New-Item $(releaseFolder) -ItemType Directory}
# Copy data
powershell Copy-Item -Path "data" -Destination "$(releaseFolder)" -recurse -Force
powershell Copy-Item "LICENSE" -Destination "$(releaseFolder)"
powershell Copy-Item "README.md" -Destination "$(releaseFolder)"
powershell Copy-Item "release/SDL2.dll" -Destination "$(releaseFolder)"
# Build
g++ $(source) -D RELEASE -std=c++11 -Wall -Os -lmingw32 -lSDL2main -lSDL2 -ffunction-sections -fdata-sections -Wl,--gc-sections -static-libstdc++ -Wl,-subsystem,windows -o "$(releaseFolder)/$(executable).exe"
strip -s -R .comment -R .gnu.version "$(releaseFolder)/$(executable).exe" --strip-unneeded
# Create ZIP
powershell if (Test-Path $(executable)_win_$(version).zip) {Remove-Item $(executable)_win_$(version).zip}
powershell Compress-Archive -Path "$(releaseFolder)"/* -DestinationPath $(executable)_win_$(version).zip
# Remove folder
powershell if (Test-Path $(releaseFolder)) {Remove-Item $(releaseFolder) -Recurse -Force}
macos:
mkdir -p bin
g++ -std=c++11 -Wall -O2 source/*.cpp -o bin/$(executable)_macos -lSDL2
rm -f data/config/config.bin
rm -f data/config/score.bin
clang++ $(source) -std=c++11 -Wall -Os -lSDL2 -ffunction-sections -fdata-sections -o $(executable)_macos -target arm64-apple-macos11
macos_release:
# Remove data
rm -f data/config/config.bin
rm -f data/config/score.bin
rm -rdf "$(releaseFolder)"
# Create folders
mkdir -p "$(releaseFolder)/$(appName).app/Contents/Frameworks"
mkdir -p "$(releaseFolder)/$(appName).app/Contents/MacOS"
mkdir -p "$(releaseFolder)/$(appName).app/Contents/Resources"
mkdir -p Frameworks
# Copy folders
cp -R data "$(releaseFolder)/$(appName).app/Contents/Resources"
cp -R /Library/Frameworks/SDL2.framework "$(releaseFolder)/$(appName).app/Contents/Frameworks"
cp -R /Library/Frameworks/SDL2.framework Frameworks
# Copy files
cp release/*.icns "$(releaseFolder)/$(appName).app/Contents/Resources"
cp release/Info.plist "$(releaseFolder)/$(appName).app/Contents"
# Build INTEL
clang++ $(source) -D RELEASE -D MACOS_BUNDLE -std=c++11 -Wall -Os -framework SDL2 -F ./Frameworks -ffunction-sections -fdata-sections -o "$(releaseFolder)/$(appName).app/Contents/MacOS/$(executable)" -rpath @executable_path/../Frameworks/ -target x86_64-apple-macos10.12
# Build INTEL DMG
rm -f "$(executable)_macos_intel_$(version).dmg"
hdiutil create tmp.dmg -ov -volname "$(appName)" -fs HFS+ -srcfolder "$(releaseFolder)"
hdiutil convert tmp.dmg -format UDZO -o "$(executable)_macos_intel_$(version).dmg"
rm tmp.dmg
# Build APPLE SILICON
clang++ $(source) -D RELEASE -D MACOS_BUNDLE -std=c++11 -Wall -Os -framework SDL2 -F ./Frameworks -ffunction-sections -fdata-sections -o "$(releaseFolder)/$(appName).app/Contents/MacOS/$(executable)" -rpath @executable_path/../Frameworks/ -target arm64-apple-macos11
# Build APPLE SILICON DMG
rm -f "$(executable)_macos_apple_silicon_$(version).dmg"
hdiutil create tmp.dmg -ov -volname "$(appName)" -fs HFS+ -srcfolder "$(releaseFolder)"
hdiutil convert tmp.dmg -format UDZO -o "$(executable)_macos_apple_silicon_$(version).dmg"
rm tmp.dmg
# Remove data
rm -rdf Frameworks
rm -rdf "$(releaseFolder)"
linux:
mkdir -p bin
g++ source/*.cpp -std=c++11 -Os -lSDL2 -ffunction-sections -fdata-sections -Wl,--gc-sections -o bin/$(executable)_linux
strip -s -R .comment -R .gnu.version bin/$(executable)_linux --strip-unneeded
opendingux:
mkdir -p bin
/opt/gcw0-toolchain/usr/bin/mipsel-linux-gcc -D GCWZERO -O2 -std=c++11 -I/opt/gcw0-toolchain/usr/mipsel-gcw0-linux-uclibc/sysroot/usr/include/SDL2 -D_GNU_SOURCE=1 -D_REENTRANT -lSDL2 -lSDL2_mixer -lstdc++ source/*.cpp -o bin/$(executable)_opendingux
/opt/gcw0-toolchain/usr/bin/mksquashfs ./default.gcw0.desktop ./icon.png ./bin ./data ./media coffee_crisis.opk -all-root -noappend -no-exports -no-xattrs
rm -f data/config/config.bin
rm -f data/config/score.bin
g++ $(source) -std=c++11 -Wall -Os -lSDL2 -ffunction-sections -fdata-sections -Wl,--gc-sections -o $(executable)_linux
strip -s -R .comment -R .gnu.version $(executable)_linux --strip-unneeded
linux_release:
# Remove data
rm -f data/config/config.bin
rm -f data/config/score.bin
rm -rdf $(releaseFolder)
# Create folders
mkdir -p $(releaseFolder)
# Copy data
cp -R data $(releaseFolder)
cp LICENSE $(releaseFolder)
cp README.md $(releaseFolder)
# Build
g++ $(source) -D RELEASE -std=c++11 -Wall -Os -lSDL2 -ffunction-sections -fdata-sections -Wl,--gc-sections -o $(releaseFolder)/$(executable)
strip -s -R .comment -R .gnu.version $(releaseFolder)/$(executable) --strip-unneeded
# Pack files
cd $(releaseFolder) && tar -czvf ../$(executable)_linux_$(version).tar.gz *
# Remove data
rm -rdf $(releaseFolder)

Binary file not shown.

Binary file not shown.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.8 KiB

BIN
data/gfx/menu_game_over.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.7 KiB

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 887 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.8 KiB

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.8 KiB

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 835 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.7 KiB

After

Width:  |  Height:  |  Size: 1.6 KiB

View File

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

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

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

View File

@@ -61,54 +61,54 @@ frames=28,29,30,31
name=sideshoot
speed=5
loop=0
frames=32,33,34,35
frames=16,17,18,19
[/animation]
[animation]
name=centershoot
speed=5
loop=0
frames=36,37,38,39
frames=20,21,22,23
[/animation]
[animation]
name=sideshoot_1C
speed=5
loop=0
frames=40,41,42,43
frames=24,25,26,27
[/animation]
[animation]
name=centershoot_1C
speed=5
loop=0
frames=44,45,46,47
frames=28,29,30,31
[/animation]
[animation]
name=sideshoot_pwr
speed=5
speed=2
loop=0
frames=48,49,50,51
frames=16,17,18,19
[/animation]
[animation]
name=centershoot_pwr
speed=5
speed=2
loop=0
frames=52,53,54,55
frames=20,21,22,23
[/animation]
[animation]
name=sideshoot_1C_pwr
speed=5
speed=2
loop=0
frames=56,57,58,59
frames=24,25,26,27
[/animation]
[animation]
name=centershoot_1C_pwr
speed=5
speed=2
loop=0
frames=60,61,62,63
frames=28,29,30,31
[/animation]

View File

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

View File

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

View File

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

View File

@@ -1,22 +1,21 @@
font_png=smb2.png
font_txt=smb2.txt
sound_cancel=menu_cancel.wav
sound_accept=menu_select.wav
sound_move=menu_move.wav
sound_accept=menu_select.wav
name=GAME OVER
x=0
y=112
y=120
backgroundType=0
backgroundColor=0,0,0,255
backgroundColor=128,64,0,0
areElementsCenteredOnX=true
isCenteredOnX=true
centerX=128
centerX=199
selector_color=84,110,122,0
selector_text_color=255,122,0
selector_color=255,122,0,255
selector_text_color=255,255,235
defaultActionWhenCancel=1

View File

@@ -1,9 +1,8 @@
font_png=smb2.png
font_txt=smb2.txt
sound_cancel=menu_cancel.wav
sound_accept=menu_select.wav
sound_move=menu_move.wav
sound_accept=menu_select.wav
name=OPTIONS
x=0
@@ -20,7 +19,7 @@ isCenteredOnY=true
centerY=96
selector_color=229,28,35,255
selector_text_color=255,180,0
selector_text_color=255,241,118
defaultActionWhenCancel=13

View File

@@ -1,13 +1,12 @@
font_png=smb2.png
font_txt=smb2.txt
sound_cancel=menu_cancel.wav
sound_accept=menu_select.wav
sound_move=menu_move.wav
sound_accept=menu_select.wav
name=PAUSE
x=0
y=96
y=80
backgroundType=1
backgroundColor=41,57,65,240
@@ -18,13 +17,19 @@ centerX=128
selector_color=255,122,0,255
selector_text_color=255,255,255
defaultActionWhenCancel=0
defaultActionWhenCancel=1
[item]
text=SI
text=PAUSE MENU
hPaddingDown=7
selectable=false
[/item]
[item]
text=CONTINUE
hPaddingDown=2
[/item]
[item]
text=NO
text=LEAVE GAME
[/item]

View File

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

View File

@@ -1,9 +1,8 @@
font_png=smb2.png
font_txt=smb2.txt
sound_cancel=menu_cancel.wav
sound_accept=menu_select.wav
sound_move=menu_move.wav
sound_accept=menu_select.wav
name=TITLE
x=0

Binary file not shown.

42
release/Info.plist Normal file
View File

@@ -0,0 +1,42 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>es</string>
<key>CFBundleDisplayName</key>
<string>coffee_crisis</string>
<key>CFBundleExecutable</key>
<string>coffee_crisis</string>
<key>CFBundleIconFile</key>
<string>coffee_crisis</string>
<key>CFBundleIconName</key>
<string>coffee_crisis</string>
<key>CFBundleIdentifier</key>
<string>org.jailgames.coffee_crisis</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>coffee_crisis</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1.0.0</string>
<key>CSResourcesFileMapped</key>
<true/>
<key>LSMinimumSystemVersion</key>
<string>10.12</string>
<key>NSHighResolutionCapable</key>
<true/>
<key>NSHumanReadableCopyright</key>
<string>Copyright 2022 JailDesigner</string>
<key>NSPrincipalClass</key>
<string>NSApplication</string>
<key>SUPublicDSAKeyFile</key>
<string>dsa_pub.pem</string>
</dict>
</plist>

BIN
release/SDL2.dll Executable file

Binary file not shown.

BIN
release/coffee_crisis.icns Normal file

Binary file not shown.

View File

@@ -2,7 +2,7 @@
#include "balloon.h"
// Constructor
Balloon::Balloon(float x, float y, Uint8 kind, float velx, float speed, Uint16 creationtimer, LTexture *texture, std::vector<std::string> *animation, SDL_Renderer *renderer)
Balloon::Balloon(float x, float y, Uint8 kind, float velx, float speed, Uint16 creationtimer, Texture *texture, std::vector<std::string> *animation, SDL_Renderer *renderer)
{
sprite = new AnimatedSprite(texture, renderer, "", animation);
disable();

View File

@@ -1,10 +1,10 @@
#pragma once
#include <SDL2/SDL.h>
#include "utils.h"
#include "animatedsprite.h"
#include <vector>
#include "common/animatedsprite.h"
#include "common/utils.h"
#include <sstream>
#include <vector>
#ifndef BALLOON_H
#define BALLOON_H
@@ -86,7 +86,7 @@ private:
std::vector<float> h; // Vector con los valores de zoom para el alto del globo
};
// Objetos
// Objetos y punteros
AnimatedSprite *sprite; // Sprite del objeto globo
// Variables
@@ -143,7 +143,7 @@ private:
public:
// Constructor
Balloon(float x, float y, Uint8 kind, float velx, float speed, Uint16 creationtimer, LTexture *texture, std::vector<std::string> *animation, SDL_Renderer *renderer);
Balloon(float x, float y, Uint8 kind, float velx, float speed, Uint16 creationtimer, Texture *texture, std::vector<std::string> *animation, SDL_Renderer *renderer);
// Destructor
~Balloon();

View File

@@ -2,7 +2,7 @@
#include "bullet.h"
// Constructor
Bullet::Bullet(int x, int y, int kind, bool poweredUp, int owner, LTexture *texture, SDL_Renderer *renderer)
Bullet::Bullet(int x, int y, int kind, bool poweredUp, int owner, Texture *texture, SDL_Renderer *renderer)
{
sprite = new Sprite({x, y, 10, 10}, texture, renderer);

View File

@@ -1,8 +1,8 @@
#pragma once
#include <SDL2/SDL.h>
#include "utils.h"
#include "sprite.h"
#include "common/sprite.h"
#include "common/utils.h"
#ifndef BULLET_H
#define BULLET_H
@@ -20,7 +20,7 @@
class Bullet
{
private:
// Objetos
// Objetos y punteros
Sprite *sprite; // Sprite con los graficos y métodos de pintado
// Variables
@@ -39,7 +39,7 @@ private:
public:
// Constructor
Bullet(int x, int y, int kind, bool poweredUp, int owner, LTexture *texture, SDL_Renderer *renderer);
Bullet(int x, int y, int kind, bool poweredUp, int owner, Texture *texture, SDL_Renderer *renderer);
// Destructor
~Bullet();

15
source/common/Makefile Normal file
View File

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

View File

@@ -1,7 +1,7 @@
#include "animatedsprite.h"
// Constructor
AnimatedSprite::AnimatedSprite(LTexture *texture, SDL_Renderer *renderer, std::string file, std::vector<std::string> *buffer)
AnimatedSprite::AnimatedSprite(Texture *texture, SDL_Renderer *renderer, std::string file, std::vector<std::string> *buffer)
{
// Copia los punteros
setTexture(texture);
@@ -88,6 +88,12 @@ void AnimatedSprite::animate()
}
}
// Obtiene el numero de frames de la animación actual
int AnimatedSprite::getNumFrames()
{
return (int)animation.at(currentAnimation).frames.size();
}
// Establece el frame actual de la animación
void AnimatedSprite::setCurrentFrame(int num)
{
@@ -304,7 +310,7 @@ bool AnimatedSprite::loadFromFile(std::string filePath)
}
// Pone un valor por defecto
setPos({0, 0, frameWidth, frameHeight});
setRect({0, 0, frameWidth, frameHeight});
return success;
}
@@ -442,7 +448,7 @@ bool AnimatedSprite::loadFromVector(std::vector<std::string> *source)
}
// Pone un valor por defecto
setPos({0, 0, frameWidth, frameHeight});
setRect({0, 0, frameWidth, frameHeight});
return success;
}
@@ -493,4 +499,12 @@ void AnimatedSprite::setAnimationCounter(int value)
{
a.counter = value;
}
}
// Reinicia la animación
void AnimatedSprite::resetAnimation()
{
animation.at(currentAnimation).currentFrame = 0;
animation.at(currentAnimation).counter = 0;
animation.at(currentAnimation).completed = false;
}

View File

@@ -1,90 +1,97 @@
#pragma once
#include <SDL2/SDL.h>
#include "movingsprite.h"
#include <vector>
#include <string>
#include <sstream>
#include <fstream>
#include <iostream>
#ifndef ANIMATEDSPRITE_H
#define ANIMATEDSPRITE_H
// Clase AnimatedSprite
class AnimatedSprite : public MovingSprite
{
private:
struct t_animation
{
std::string name; // Nombre de la animacion
std::vector<SDL_Rect> frames; // Cada uno de los frames que componen la animación
int speed; // Velocidad de la animación
int loop; // Indica a que frame vuelve la animación al terminar. -1 para que no vuelva
bool completed; // Indica si ha finalizado la animación
int currentFrame; // Frame actual
int counter; // Contador para las animaciones
};
std::vector<t_animation> animation; // Vector con las diferentes animaciones
int currentAnimation; // Animacion activa
public:
// Constructor
AnimatedSprite(LTexture *texture = nullptr, SDL_Renderer *renderer = nullptr, std::string file = "", std::vector<std::string> *buffer = nullptr);
// Destructor
~AnimatedSprite();
// Calcula el frame correspondiente a la animación actual
void animate();
// Establece el frame actual de la animación
void setCurrentFrame(int num);
// Establece el valor del contador
void setAnimationCounter(std::string name, int num);
// Establece la velocidad de una animación
void setAnimationSpeed(std::string name, int speed);
void setAnimationSpeed(int index, int speed);
// Establece el frame al que vuelve la animación al finalizar
void setAnimationLoop(std::string name, int loop);
void setAnimationLoop(int index, int loop);
// Establece el valor de la variable
void setAnimationCompleted(std::string name, bool value);
void setAnimationCompleted(int index, bool value);
// Comprueba si ha terminado la animación
bool animationIsCompleted();
// Devuelve el rectangulo de una animación y frame concreto
SDL_Rect getAnimationClip(std::string name, Uint8 index);
SDL_Rect getAnimationClip(int indexA, Uint8 indexF);
// Obtiene el indice de la animación a partir del nombre
int getIndex(std::string name);
// Carga la animación desde un fichero
bool loadFromFile(std::string filePath);
// Carga la animación desde un vector
bool loadFromVector(std::vector<std::string> *source);
// Establece la animacion actual
void setCurrentAnimation(std::string name = "default");
void setCurrentAnimation(int index = 0);
// Actualiza las variables del objeto
void update();
// OLD - Establece el rectangulo para un frame de una animación
void setAnimationFrames(Uint8 index_animation, Uint8 index_frame, int x, int y, int w, int h);
// OLD - Establece el contador para todas las animaciones
void setAnimationCounter(int value);
};
#pragma once
#include <SDL2/SDL.h>
#include "movingsprite.h"
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#ifndef ANIMATEDSPRITE_H
#define ANIMATEDSPRITE_H
// Clase AnimatedSprite
class AnimatedSprite : public MovingSprite
{
private:
struct t_animation
{
std::string name; // Nombre de la animacion
std::vector<SDL_Rect> frames; // Cada uno de los frames que componen la animación
int speed; // Velocidad de la animación
int loop; // Indica a que frame vuelve la animación al terminar. -1 para que no vuelva
bool completed; // Indica si ha finalizado la animación
int currentFrame; // Frame actual
int counter; // Contador para las animaciones
};
// Variables
std::vector<t_animation> animation; // Vector con las diferentes animaciones
int currentAnimation; // Animacion activa
public:
// Constructor
AnimatedSprite(Texture *texture = nullptr, SDL_Renderer *renderer = nullptr, std::string file = "", std::vector<std::string> *buffer = nullptr);
// Destructor
~AnimatedSprite();
// Calcula el frame correspondiente a la animación actual
void animate();
// Obtiene el numero de frames de la animación actual
int getNumFrames();
// Establece el frame actual de la animación
void setCurrentFrame(int num);
// Establece el valor del contador
void setAnimationCounter(std::string name, int num);
// Establece la velocidad de una animación
void setAnimationSpeed(std::string name, int speed);
void setAnimationSpeed(int index, int speed);
// Establece el frame al que vuelve la animación al finalizar
void setAnimationLoop(std::string name, int loop);
void setAnimationLoop(int index, int loop);
// Establece el valor de la variable
void setAnimationCompleted(std::string name, bool value);
void setAnimationCompleted(int index, bool value);
// Comprueba si ha terminado la animación
bool animationIsCompleted();
// Devuelve el rectangulo de una animación y frame concreto
SDL_Rect getAnimationClip(std::string name, Uint8 index);
SDL_Rect getAnimationClip(int indexA, Uint8 indexF);
// Obtiene el indice de la animación a partir del nombre
int getIndex(std::string name);
// Carga la animación desde un fichero
bool loadFromFile(std::string filePath);
// Carga la animación desde un vector
bool loadFromVector(std::vector<std::string> *source);
// Establece la animacion actual
void setCurrentAnimation(std::string name = "default");
void setCurrentAnimation(int index = 0);
// Actualiza las variables del objeto
void update();
// OLD - Establece el rectangulo para un frame de una animación
void setAnimationFrames(Uint8 index_animation, Uint8 index_frame, int x, int y, int w, int h);
// OLD - Establece el contador para todas las animaciones
void setAnimationCounter(int value);
// Reinicia la animación
void resetAnimation();
};
#endif

View File

@@ -1,10 +1,10 @@
#include "asset.h"
// Constructor
Asset::Asset(std::string path)
Asset::Asset(std::string executablePath)
{
executablePath = path;
longest_name = 0;
this->executablePath = executablePath.substr(0, executablePath.find_last_of("\\/"));
longestName = 0;
}
// Destructor
@@ -13,7 +13,7 @@ Asset::~Asset()
}
// Añade un elemento a la lista
void Asset::add(std::string file, enum assetType_e type, bool required)
void Asset::add(std::string file, enum assetType type, bool required)
{
item_t temp;
temp.file = executablePath + file;
@@ -22,7 +22,7 @@ void Asset::add(std::string file, enum assetType_e type, bool required)
fileList.push_back(temp);
const std::string filename = file.substr(file.find_last_of("\\/") + 1);
longest_name = SDL_max(longest_name, filename.size());
longestName = SDL_max(longestName, filename.size());
}
// Devuelve el fichero de un elemento de la lista a partir de una cadena
@@ -106,7 +106,7 @@ bool Asset::checkFile(std::string path)
SDL_RWclose(file);
}
const std::string s = "Checking file %-" + std::to_string(longest_name) + "s [" + result + "]\n";
const std::string s = "Checking file %-" + std::to_string(longestName) + "s [" + result + "]\n";
printf(s.c_str(), filename.c_str());
return success;

View File

@@ -7,7 +7,7 @@
#ifndef ASSET_H
#define ASSET_H
enum assetType_e
enum assetType
{
t_bitmap,
t_music,
@@ -29,11 +29,11 @@ private:
struct item_t
{
std::string file; // Ruta del fichero desde la raiz del directorio
enum assetType_e type; // Indica el tipo de recurso
enum assetType type; // Indica el tipo de recurso
bool required; // Indica si es un fichero que debe de existir
};
int longest_name; // Contiene la longitud del nombre de fichero mas largo
int longestName; // Contiene la longitud del nombre de fichero mas largo
std::vector<item_t> fileList;
std::string executablePath;
@@ -46,13 +46,13 @@ private:
public:
// Constructor
Asset(std::string path);
Asset(std::string executablePath);
// Destructor
~Asset();
// Añade un elemento a la lista
void add(std::string file, enum assetType_e type, bool required = true);
void add(std::string file, enum assetType type, bool required = true);
// Devuelve un elemento de la lista a partir de una cadena
std::string get(std::string text);

View File

@@ -97,7 +97,7 @@ bool Input::checkInput(Uint8 input, bool repeat, int device, int index)
{
if (repeat)
{
if (SDL_GameControllerGetButton(connectedControllers.at(index), gameControllerBindings[input].button) != 0)
if (SDL_GameControllerGetButton(connectedControllers.at(index), gameControllerBindings.at(input).button) != 0)
{
successGameController = true;
}
@@ -108,11 +108,11 @@ bool Input::checkInput(Uint8 input, bool repeat, int device, int index)
}
else
{
if (!gameControllerBindings[input].active)
if (!gameControllerBindings.at(input).active)
{
if (SDL_GameControllerGetButton(connectedControllers.at(index), gameControllerBindings[input].button) != 0)
if (SDL_GameControllerGetButton(connectedControllers.at(index), gameControllerBindings.at(input).button) != 0)
{
gameControllerBindings[input].active = true;
gameControllerBindings.at(input).active = true;
successGameController = true;
}
else
@@ -122,9 +122,9 @@ bool Input::checkInput(Uint8 input, bool repeat, int device, int index)
}
else
{
if (SDL_GameControllerGetButton(connectedControllers.at(index), gameControllerBindings[input].button) == 0)
if (SDL_GameControllerGetButton(connectedControllers.at(index), gameControllerBindings.at(input).button) == 0)
{
gameControllerBindings[input].active = false;
gameControllerBindings.at(input).active = false;
successGameController = false;
}
else
@@ -138,6 +138,44 @@ bool Input::checkInput(Uint8 input, bool repeat, int device, int index)
return (successKeyboard || successGameController);
}
// Comprueba si hay almenos un input activo
bool Input::checkAnyInput(int device, int index)
{
if (device == INPUT_USE_ANY)
{
index = 0;
}
if (device == INPUT_USE_KEYBOARD || device == INPUT_USE_ANY)
{
const Uint8 *mKeystates = SDL_GetKeyboardState(nullptr);
for (int i = 0; i < (int)keyBindings.size(); ++i)
{
if (mKeystates[keyBindings.at(i).scancode] != 0)
{
return true;
}
}
}
if (gameControllerFound())
{
if (device == INPUT_USE_GAMECONTROLLER || device == INPUT_USE_ANY)
{
for (int i = 0; i < (int)gameControllerBindings.size(); ++i)
{
if (SDL_GameControllerGetButton(connectedControllers.at(index), gameControllerBindings.at(i).button) != 0)
{
return true;
}
}
}
}
return false;
}
// Comprueba si hay un mando conectado
bool Input::discoverGameController()
{

View File

@@ -1,87 +1,90 @@
#pragma once
#include <SDL2/SDL.h>
#include <string>
#include <vector>
#ifndef INPUT_H
#define INPUT_H
#define INPUT_NULL 0
#define INPUT_UP 1
#define INPUT_DOWN 2
#define INPUT_LEFT 3
#define INPUT_RIGHT 4
#define INPUT_ACCEPT 5
#define INPUT_CANCEL 6
#define INPUT_BUTTON_1 7
#define INPUT_BUTTON_2 8
#define INPUT_BUTTON_3 9
#define INPUT_BUTTON_4 10
#define INPUT_BUTTON_5 11
#define INPUT_BUTTON_6 12
#define INPUT_BUTTON_7 13
#define INPUT_BUTTON_8 14
#define INPUT_BUTTON_PAUSE 15
#define INPUT_BUTTON_ESCAPE 16
#define REPEAT_TRUE true
#define REPEAT_FALSE false
#define INPUT_USE_KEYBOARD 0
#define INPUT_USE_GAMECONTROLLER 1
#define INPUT_USE_ANY 2
// Clase Input
class Input
{
private:
struct keyBindings_t
{
Uint8 scancode; // Scancode asociado
bool active; // Indica si está activo
};
struct GameControllerBindings_t
{
SDL_GameControllerButton button; // GameControllerButton asociado
bool active; // Indica si está activo
};
std::vector<keyBindings_t> keyBindings; // Vector con las teclas asociadas a los inputs predefinidos
std::vector<GameControllerBindings_t> gameControllerBindings; // Vector con las teclas asociadas a los inputs predefinidos
std::vector<SDL_GameController *> connectedControllers; // Vector con todos los mandos conectados
std::vector<std::string> controllerNames; // Vector con los nombres de los mandos
int numGamepads; // Numero de mandos conectados
std::string dbPath; // Ruta al archivo gamecontrollerdb.txt
// Comprueba si hay un mando conectado
bool discoverGameController();
public:
// Constructor
Input(std::string file);
// Destructor
~Input();
// Asigna uno de los posibles inputs a una tecla del teclado
void bindKey(Uint8 input, SDL_Scancode code);
// Asigna uno de los posibles inputs a un botón del mando
void bindGameControllerButton(Uint8 input, SDL_GameControllerButton button);
// Comprueba si un input esta activo
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
#pragma once
#include <SDL2/SDL.h>
#include <string>
#include <vector>
#ifndef INPUT_H
#define INPUT_H
#define INPUT_NULL 0
#define INPUT_UP 1
#define INPUT_DOWN 2
#define INPUT_LEFT 3
#define INPUT_RIGHT 4
#define INPUT_ACCEPT 5
#define INPUT_CANCEL 6
#define INPUT_BUTTON_1 7
#define INPUT_BUTTON_2 8
#define INPUT_BUTTON_3 9
#define INPUT_BUTTON_4 10
#define INPUT_BUTTON_5 11
#define INPUT_BUTTON_6 12
#define INPUT_BUTTON_7 13
#define INPUT_BUTTON_8 14
#define INPUT_BUTTON_PAUSE 15
#define INPUT_BUTTON_ESCAPE 16
#define REPEAT_TRUE true
#define REPEAT_FALSE false
#define INPUT_USE_KEYBOARD 0
#define INPUT_USE_GAMECONTROLLER 1
#define INPUT_USE_ANY 2
// Clase Input
class Input
{
private:
struct keyBindings_t
{
Uint8 scancode; // Scancode asociado
bool active; // Indica si está activo
};
struct GameControllerBindings_t
{
SDL_GameControllerButton button; // GameControllerButton asociado
bool active; // Indica si está activo
};
std::vector<keyBindings_t> keyBindings; // Vector con las teclas asociadas a los inputs predefinidos
std::vector<GameControllerBindings_t> gameControllerBindings; // Vector con las teclas asociadas a los inputs predefinidos
std::vector<SDL_GameController *> connectedControllers; // Vector con todos los mandos conectados
std::vector<std::string> controllerNames; // Vector con los nombres de los mandos
int numGamepads; // Numero de mandos conectados
std::string dbPath; // Ruta al archivo gamecontrollerdb.txt
// Comprueba si hay un mando conectado
bool discoverGameController();
public:
// Constructor
Input(std::string file);
// Destructor
~Input();
// Asigna uno de los posibles inputs a una tecla del teclado
void bindKey(Uint8 input, SDL_Scancode code);
// Asigna uno de los posibles inputs a un botón del mando
void bindGameControllerButton(Uint8 input, SDL_GameControllerButton button);
// Comprueba si un input esta activo
bool checkInput(Uint8 input, bool repeat, int device = INPUT_USE_ANY, int index = 0);
// Comprueba si hay almenos un input activo
bool checkAnyInput(int device, int index);
// 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

View File

@@ -1,4 +1,3 @@
#include "const.h"
#include "menu.h"
// Constructor
@@ -20,6 +19,7 @@ Menu::Menu(SDL_Renderer *renderer, Asset *asset, Input *input, std::string file)
itemSelected = MENU_NO_OPTION;
x = 0;
y = 0;
w = 0;
rectBG.rect = {0, 0, 0, 0};
rectBG.color = {0, 0, 0};
rectBG.a = 0;
@@ -57,6 +57,9 @@ Menu::Menu(SDL_Renderer *renderer, Asset *asset, Input *input, std::string file)
{
load(file);
}
// Deja el cursor en el primer elemento
reset();
}
Menu::~Menu()
@@ -167,9 +170,6 @@ bool Menu::load(std::string file_path)
success = false;
}
// Reorganiza el menu con los valores recien cargados
// reorganize();
return success;
}
@@ -207,6 +207,7 @@ bool Menu::setItem(item_t *item, std::string var, std::string value)
else if ((var == "") || (var == "[/item]"))
{
}
else
{
success = false;
@@ -351,11 +352,6 @@ bool Menu::setVars(std::string var, std::string value)
return success;
}
// Inicializa las variables
void Menu::init()
{
}
// Carga los ficheros de audio
void Menu::loadAudioFile(std::string file, int sound)
{
@@ -408,7 +404,8 @@ void Menu::updateSelector()
selector.moving = false;
}
}
if (selector.despY < 0) // Va hacia arriba
else if (selector.despY < 0) // Va hacia arriba
{
if (selector.y < selector.targetY) // Ha llegado al destino
{
@@ -436,7 +433,8 @@ void Menu::updateSelector()
selector.resizing = false;
}
}
if (selector.incH < 0) // Decrece
else if (selector.incH < 0) // Decrece
{
if (selector.h < selector.targetH) // Ha llegado al destino
{
@@ -459,7 +457,7 @@ void Menu::setSelectorPos(int index)
if (index < (int)item.size())
{
selector.index = index;
selector.rect.y = selector.y = selector.originY = selector.targetY = item[selector.index].rect.y;
selector.rect.y = selector.y = selector.originY = selector.targetY = item.at(selector.index).rect.y;
selector.rect.w = rectBG.rect.w;
selector.rect.x = rectBG.rect.x;
selector.originH = selector.targetH = selector.rect.h = getSelectorHeight(selector.index);
@@ -487,10 +485,17 @@ void Menu::reset()
{
itemSelected = MENU_NO_OPTION;
selector.index = 0;
selector.originY = selector.targetY = selector.y = item[0].rect.y;
selector.originH = selector.targetH = item[0].rect.h;
selector.originY = selector.targetY = selector.y = item.at(0).rect.y;
selector.originH = selector.targetH = item.at(0).rect.h;
selector.moving = false;
selector.resizing = false;
// Si el primer elemento no es seleccionable, incrementa el selector
if (!item.at(selector.index).selectable)
{
increaseSelectorIndex();
setSelectorPos(selector.index);
}
}
// Actualiza el menu para recolocarlo correctamente y establecer el tamaño
@@ -518,18 +523,18 @@ void Menu::reorganize()
bool Menu::increaseSelectorIndex()
{
// Obten las coordenadas del elemento actual
selector.y = selector.originY = item[selector.index].rect.y;
selector.y = selector.originY = item.at(selector.index).rect.y;
selector.h = selector.originH = getSelectorHeight(selector.index);
// Calcula cual es el siguiente elemento
++selector.index %= item.size();
while (!item[selector.index].selectable)
while (!item.at(selector.index).selectable)
{
++selector.index %= item.size();
}
// Establece las coordenadas y altura de destino
selector.targetY = item[selector.index].rect.y;
selector.targetY = item.at(selector.index).rect.y;
selector.despY = (selector.targetY - selector.originY) / selector.numJumps;
selector.targetH = getSelectorHeight(selector.index);
@@ -548,24 +553,24 @@ bool Menu::increaseSelectorIndex()
bool Menu::decreaseSelectorIndex()
{
// Obten las coordenadas del elemento actual
selector.y = selector.originY = item[selector.index].rect.y;
selector.y = selector.originY = item.at(selector.index).rect.y;
selector.h = selector.originH = getSelectorHeight(selector.index);
// Calcula cual es el siguiente elemento
if (selector.index == 0)
{
selector.index = item.size();
selector.index = item.size() - 1;
}
else
{
selector.index--;
}
while (!item[selector.index].selectable)
while (!item.at(selector.index).selectable)
{
if (selector.index == 0)
{
selector.index = item.size();
selector.index = item.size() - 1;
}
else
{
@@ -574,7 +579,7 @@ bool Menu::decreaseSelectorIndex()
}
// Establece las coordenadas y altura de destino
selector.targetY = item[selector.index].rect.y;
selector.targetY = item.at(selector.index).rect.y;
selector.despY = (selector.targetY - selector.originY) / selector.numJumps;
selector.targetH = getSelectorHeight(selector.index);
@@ -608,8 +613,6 @@ void Menu::render()
// Renderiza el rectangulo del selector
const SDL_Rect temp = {selector.rect.x, selector.rect.y - 1, selector.rect.w, selector.rect.h + 1};
// temp.y--;
// temp.h++;
SDL_SetRenderDrawColor(renderer, selector.color.r, selector.color.g, selector.color.b, selector.a);
SDL_RenderFillRect(renderer, &temp);
@@ -626,40 +629,74 @@ void Menu::render()
if (i == selector.index)
{
const color_t color = {selector.itemColor.r, selector.itemColor.g, selector.itemColor.b};
text->writeColored(item[i].rect.x, item[i].rect.y, item[i].label, color);
text->writeColored(item.at(i).rect.x, item.at(i).rect.y, item.at(i).label, color);
}
else if (item[i].selectable)
else if (item.at(i).selectable)
{
text->write(item[i].rect.x, item[i].rect.y, item[i].label);
text->write(item.at(i).rect.x, item.at(i).rect.y, item.at(i).label);
}
else if (item[i].greyed)
else if (item.at(i).greyed)
{
text->writeColored(item[i].rect.x, item[i].rect.y, item[i].label, colorGreyed);
text->writeColored(item.at(i).rect.x, item.at(i).rect.y, item.at(i).label, colorGreyed);
}
else
// No seleccionable
{
if ((item[i].linkedUp) && (i == selector.index + 1))
{ // No seleccionable
if ((item.at(i).linkedUp) && (i == selector.index + 1))
{
const color_t color = {selector.itemColor.r, selector.itemColor.g, selector.itemColor.b};
text->writeColored(item[i].rect.x, item[i].rect.y, item[i].label, color);
text->writeColored(item.at(i).rect.x, item.at(i).rect.y, item.at(i).label, color);
}
else // No enlazado con el de arriba
{
text->write(item[i].rect.x, item[i].rect.y, item[i].label);
text->write(item.at(i).rect.x, item.at(i).rect.y, item.at(i).label);
}
}
}
}
// Establece el rectangulo de fondo del menu y el selector
void Menu::setRectSize()
void Menu::setRectSize(int w, int h)
{
rectBG.rect.w = findWidth() + text->getCharacterSize();
rectBG.rect.h = findHeight() + text->getCharacterSize();
// Establece el ancho
if (w == 0)
{ // Si no se pasa un valor, se busca si hay uno prefijado
if (this->w == 0)
{ // Si no hay prefijado, coge el item mas ancho
rectBG.rect.w = findWidth() + text->getCharacterSize();
}
else
{ // Si hay prefijado, coge ese
rectBG.rect.w = this->w;
}
}
else
{ // Si se pasa un valor, se usa y se prefija
rectBG.rect.w = w;
this->w = w;
}
// Establece el alto
if (h == 0)
{ // Si no se pasa un valor, se busca de manera automatica
rectBG.rect.h = findHeight() + text->getCharacterSize();
}
else
{ // Si se pasa un valor, se aplica
rectBG.rect.h = h;
}
// La posición X es la del menú menos medio caracter
rectBG.rect.x = x - (text->getCharacterSize() / 2);
if (this->w != 0)
{ // Si el ancho esta prefijado, la x coinccide
rectBG.rect.x = x;
}
else
{ // Si el ancho es automatico, se le da un poco de margen
rectBG.rect.x = x - (text->getCharacterSize() / 2);
}
// La posición Y es la del menu menos la altura de medio caracter
rectBG.rect.y = y - (text->getCharacterSize() / 2);
@@ -692,10 +729,28 @@ void Menu::setSelectorTextColor(color_t color)
void Menu::centerMenuOnX(int value)
{
isCenteredOnX = true;
centerX = value;
if (value != 0)
{
centerX = value;
}
else if (centerX == 0)
{
return;
}
// Establece la nueva posición centrada en funcion del elemento más ancho
x = (value) - (findWidth() / 2);
// Establece la nueva posición centrada en funcion del elemento más ancho o del ancho fijo del menu
if (w != 0)
{ // Si se ha definido un ancho fijo
x = (centerX) - (w / 2);
}
else
{ // Si se actua en función del elemento más ancho
x = (centerX) - (findWidth() / 2);
}
// Actualiza el rectangulo de fondo y del selector
rectBG.rect.x = x;
selector.rect.x = x;
// Reposiciona los elementos del menu
for (auto &i : item)
@@ -705,6 +760,12 @@ void Menu::centerMenuOnX(int value)
// Recalcula el rectangulo de fondo
setRectSize();
// Vuelve a centrar los elementos si fuera el caso
if (areElementsCenteredOnX)
{
centerMenuElementsOnX();
}
}
// Centra el menu respecto un punto en el eje Y
@@ -738,13 +799,13 @@ void Menu::centerMenuElementsOnX()
void Menu::addItem(std::string text, int hPaddingDown, bool selectable, bool greyed, bool linkedDown)
{
item_t temp;
if (item.empty())
{// Si es el primer item coge la posición en el eje Y del propio menu
{ // Si es el primer item coge la posición en el eje Y del propio menu
temp.rect.y = y;
}
else
{// En caso contrario, coge la posición en el eje Y a partir del último elemento
{ // En caso contrario, coge la posición en el eje Y a partir del último elemento
temp.rect.y = item.back().rect.y + item.back().rect.h + item.back().hPaddingDown;
}
@@ -755,7 +816,7 @@ void Menu::addItem(std::string text, int hPaddingDown, bool selectable, bool gre
temp.linkedDown = linkedDown;
item.push_back(temp);
setItemCaption(item.size() - 1, text);
if (item.size() > 1)
@@ -777,9 +838,6 @@ void Menu::setItemCaption(int index, std::string text)
item.at(index).rect.w = this->text->lenght(item.at(index).label);
item.at(index).rect.h = this->text->getCharacterSize();
reorganize();
const std::string t = item.at(index).label + ":" + std::to_string(item.at(index).rect.w);
printf("Adding menu item -> %s\n", t.c_str());
}
// Establece el indice del itemm que se usará por defecto al cancelar el menu
@@ -855,42 +913,42 @@ int Menu::findHeight()
// Recoloca los elementos del menu en el eje Y
void Menu::replaceElementsOnY()
{
item[0].rect.y = y;
item.at(0).rect.y = y;
for (int i = 1; i < (int)item.size(); i++)
{
item[i].rect.y = item[i - 1].rect.y + item[i - 1].rect.h + item[i - 1].hPaddingDown;
item.at(i).rect.y = item.at(i - 1).rect.y + item.at(i - 1).rect.h + item.at(i - 1).hPaddingDown;
}
}
// Establece el estado seleccionable de un item
void Menu::setSelectable(int index, bool value)
{
item[index].selectable = value;
item.at(index).selectable = value;
}
// Establece el estado agrisado de un item
void Menu::setGreyed(int index, bool value)
{
item[index].greyed = value;
item.at(index).greyed = value;
}
// Establece el estado de enlace de un item
void Menu::setLinkedDown(int index, bool value)
{
item[index].linkedDown = value;
item.at(index).linkedDown = value;
}
// Calcula la altura del selector
int Menu::getSelectorHeight(int value)
{
if (item[value].linkedDown)
if (item.at(value).linkedDown)
{
return item[value].rect.h + item[value].hPaddingDown + item[value + 1].rect.h;
return item.at(value).rect.h + item.at(value).hPaddingDown + item.at(value + 1).rect.h;
}
else
{
return item[value].rect.h;
return item.at(value).rect.h;
}
}

View File

@@ -1,15 +1,15 @@
#pragma once
#include <SDL2/SDL.h>
#include <vector>
#include "sprite.h"
#include "text.h"
#include "asset.h"
#include "input.h"
#include "utils.h"
#include "jail_audio.h"
#include <sstream>
#include "sprite.h"
#include "text.h"
#include "utils.h"
#include <fstream>
#include <sstream>
#include <vector>
#ifndef MENU_H
#define MENU_H
@@ -68,6 +68,13 @@ private:
int a; // Cantidad de transparencia para el rectangulo del selector
};
// Objetos y punteros
SDL_Renderer *renderer; // Puntero al renderizador de la ventana
Text *text; // Texto para poder escribir los items del menu
Input *input; // Gestor de eventos de entrada de teclado o gamepad
Asset *asset; // Objeto para gestionar los ficheros de recursos
// Variables
std::string name; // Nombre del menu
int x; // Posición en el eje X de la primera letra del primer elemento
int y; // Posición en el eje Y de la primera letra del primer elemento
@@ -85,10 +92,6 @@ private:
JA_Sound soundAccept; // Sonido al aceptar o elegir una opción del menu
JA_Sound soundCancel; // Sonido al cancelar el menu
JA_Sound soundMove; // Sonido al mover el selector
SDL_Renderer *renderer; // Puntero al renderizador de la ventana
Text *text; // Texto para poder escribir los items del menu
Input *input; // Gestor de eventos de entrada de teclado o gamepad
Asset *asset; // Objeto para gestionar los ficheros de recursos
color_t colorGreyed; // Color para los elementos agrisados
rectangle_t rectBG; // Rectangulo de fondo del menu
std::vector<item_t> item; // Estructura para cada elemento del menu
@@ -105,12 +108,6 @@ private:
// Asigna variables a partir de dos cadenas
bool setItem(item_t *item, std::string var, std::string value);
// Inicializa las variables
void init();
// Establece el rectangulo de fondo del menu
void setRectSize();
// Actualiza el menu para recolocarlo correctamente y establecer el tamaño
void reorganize();
@@ -143,7 +140,7 @@ private:
public:
// Constructor
Menu(SDL_Renderer *renderer, Asset *asset, Input *input, std::string file="");
Menu(SDL_Renderer *renderer, Asset *asset, Input *input, std::string file = "");
// Destructor
~Menu();
@@ -179,7 +176,7 @@ public:
void setSelectorTextColor(color_t color);
// Centra el menu respecto a un punto en el eje X
void centerMenuOnX(int value);
void centerMenuOnX(int value = 0);
// Centra el menu respecto a un punto en el eje Y
void centerMenuOnY(int value);
@@ -219,6 +216,9 @@ public:
// Establece la fuente de texto que se utilizará
void setText(std::string font_png, std::string font_txt);
// Establece el rectangulo de fondo del menu
void setRectSize(int w = 0, int h = 0);
};
#endif

View File

@@ -1,8 +1,7 @@
#include "const.h"
#include "movingsprite.h"
// Constructor
MovingSprite::MovingSprite(float x, float y, int w, int h, float velx, float vely, float accelx, float accely, LTexture *texture, SDL_Renderer *renderer)
MovingSprite::MovingSprite(float x, float y, int w, int h, float velx, float vely, float accelx, float accely, Texture *texture, SDL_Renderer *renderer)
{
// Copia los punteros
this->texture = texture;
@@ -51,11 +50,6 @@ MovingSprite::MovingSprite(float x, float y, int w, int h, float velx, float vel
currentFlip = SDL_FLIP_NONE;
};
// Destructor
MovingSprite::~MovingSprite()
{
}
// Reinicia todas las variables
void MovingSprite::clear()
{
@@ -160,11 +154,13 @@ double MovingSprite::getAngle()
return angle;
}
// Establece la posición del objeto
void MovingSprite::setPos(SDL_Rect rect)
// Establece la posición y el tamaño del objeto
void MovingSprite::setRect(SDL_Rect rect)
{
x = (float)rect.x;
y = (float)rect.y;
w = rect.w;
h = rect.h;
}
// Establece el valor de la variable
@@ -333,15 +329,6 @@ SDL_Rect MovingSprite::getRect()
return rect;
}
// Establece los valores de posición y tamaño del sprite
void MovingSprite::setRect(SDL_Rect rect)
{
x = (float)rect.x;
y = (float)rect.y;
w = rect.w;
h = rect.h;
}
// Deshace el último movimiento
void MovingSprite::undoMove()
{

View File

@@ -1,173 +1,167 @@
#pragma once
#include <SDL2/SDL.h>
#include "sprite.h"
#ifndef MOVINGSPRITE_H
#define MOVINGSPRITE_H
// Clase MovingSprite. Añade posicion y velocidad en punto flotante
class MovingSprite : public Sprite
{
protected:
float x; // Posición en el eje X
float y; // Posición en el eje Y
float xPrev; // Posición anterior en el eje X
float yPrev; // Posición anterior en el eje Y
float vx; // Velocidad en el eje X. Cantidad de pixeles a desplazarse
float vy; // Velocidad en el eje Y. Cantidad de pixeles a desplazarse
float ax; // Aceleración en el eje X. Variación de la velocidad
float ay; // Aceleración en el eje Y. Variación de la velocidad
float zoomW; // Zoom aplicado a la anchura
float zoomH; // Zoom aplicado a la altura
double angle; // Angulo para dibujarlo
bool rotateEnabled; // Indica si ha de rotar
int rotateSpeed; // Velocidad de giro
double rotateAmount; // Cantidad de grados a girar en cada iteración
int counter; // Contador interno
SDL_Point *center; // Centro de rotación
SDL_RendererFlip currentFlip; // Indica como se voltea el sprite
public:
// Constructor
MovingSprite(float x = 0, float y = 0, int w = 0, int h = 0, float velx = 0, float vely = 0, float accelx = 0, float accely = 0, LTexture *texture = nullptr, SDL_Renderer *renderer = nullptr);
// Destructor
~MovingSprite();
// Mueve el sprite
void move();
// Rota el sprite
void rotate();
// Actualiza las variables internas del objeto
void update();
// Reinicia todas las variables
void clear();
// Muestra el sprite por pantalla
void render();
// Obten el valor de la variable
float getPosX();
// Obten el valor de la variable
float getPosY();
// Obten el valor de la variable
float getVelX();
// Obten el valor de la variable
float getVelY();
// Obten el valor de la variable
float getAccelX();
// Obten el valor de la variable
float getAccelY();
// Obten el valor de la variable
float getZoomW();
// Obten el valor de la variable
float getZoomH();
// Obten el valor de la variable
double getAngle();
// Obtiene el valor de la variable
bool getRotate();
// Obtiene el valor de la variable
Uint16 getRotateSpeed();
// Establece la posición del objeto
void setPos(SDL_Rect rect);
// Establece el valor de la variable
void setPosX(float value);
// Establece el valor de la variable
void setPosY(float value);
// Establece el valor de la variable
void setVelX(float value);
// Establece el valor de la variable
void setVelY(float value);
// Establece el valor de la variable
void setAccelX(float value);
// Establece el valor de la variable
void setAccelY(float value);
// Establece el valor de la variable
void setZoomW(float value);
// Establece el valor de la variable
void setZoomH(float value);
// Establece el valor de la variable
void setAngle(double vaue);
// Incrementa el valor de la variable
void incAngle(double value);
// Decrementa el valor de la variable
void decAngle(double value);
// Establece el valor de la variable
void setRotate(bool value);
// Establece el valor de la variable
void setRotateSpeed(int value);
// Establece el valor de la variable
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
void switchRotate();
// Establece el valor de la variable
void setFlip(SDL_RendererFlip flip);
// Gira el sprite horizontalmente
void flip();
// Obtiene el valor de la variable
SDL_RendererFlip getFlip();
// Devuelve el rectangulo donde está el sprite
SDL_Rect getRect();
// Establece los valores de posición y tamaño del sprite
void setRect(SDL_Rect rect);
// Deshace el último movimiento
void undoMove();
// Deshace el último movimiento en el eje X
void undoMoveX();
// Deshace el último movimiento en el eje Y
void undoMoveY();
// Pone a cero las velocidades de desplacamiento
void clearVel();
// Devuelve el incremento en el eje X en pixels
int getIncX();
};
#endif
#pragma once
#include <SDL2/SDL.h>
#include "sprite.h"
#ifndef MOVINGSPRITE_H
#define MOVINGSPRITE_H
// Clase MovingSprite. Añade posicion y velocidad en punto flotante
class MovingSprite : public Sprite
{
protected:
float x; // Posición en el eje X
float y; // Posición en el eje Y
float xPrev; // Posición anterior en el eje X
float yPrev; // Posición anterior en el eje Y
float vx; // Velocidad en el eje X. Cantidad de pixeles a desplazarse
float vy; // Velocidad en el eje Y. Cantidad de pixeles a desplazarse
float ax; // Aceleración en el eje X. Variación de la velocidad
float ay; // Aceleración en el eje Y. Variación de la velocidad
float zoomW; // Zoom aplicado a la anchura
float zoomH; // Zoom aplicado a la altura
double angle; // Angulo para dibujarlo
bool rotateEnabled; // Indica si ha de rotar
int rotateSpeed; // Velocidad de giro
double rotateAmount; // Cantidad de grados a girar en cada iteración
int counter; // Contador interno
SDL_Point *center; // Centro de rotación
SDL_RendererFlip currentFlip; // Indica como se voltea el sprite
public:
// Constructor
MovingSprite(float x = 0, float y = 0, int w = 0, int h = 0, float velx = 0, float vely = 0, float accelx = 0, float accely = 0, Texture *texture = nullptr, SDL_Renderer *renderer = nullptr);
// Mueve el sprite
void move();
// Rota el sprite
void rotate();
// Actualiza las variables internas del objeto
void update();
// Reinicia todas las variables
void clear();
// Muestra el sprite por pantalla
void render();
// Obten el valor de la variable
float getPosX();
// Obten el valor de la variable
float getPosY();
// Obten el valor de la variable
float getVelX();
// Obten el valor de la variable
float getVelY();
// Obten el valor de la variable
float getAccelX();
// Obten el valor de la variable
float getAccelY();
// Obten el valor de la variable
float getZoomW();
// Obten el valor de la variable
float getZoomH();
// Obten el valor de la variable
double getAngle();
// Obtiene el valor de la variable
bool getRotate();
// Obtiene el valor de la variable
Uint16 getRotateSpeed();
// Establece la posición y el tamaño del objeto
void setRect(SDL_Rect rect);
// Establece el valor de la variable
void setPosX(float value);
// Establece el valor de la variable
void setPosY(float value);
// Establece el valor de la variable
void setVelX(float value);
// Establece el valor de la variable
void setVelY(float value);
// Establece el valor de la variable
void setAccelX(float value);
// Establece el valor de la variable
void setAccelY(float value);
// Establece el valor de la variable
void setZoomW(float value);
// Establece el valor de la variable
void setZoomH(float value);
// Establece el valor de la variable
void setAngle(double vaue);
// Incrementa el valor de la variable
void incAngle(double value);
// Decrementa el valor de la variable
void decAngle(double value);
// Establece el valor de la variable
void setRotate(bool value);
// Establece el valor de la variable
void setRotateSpeed(int value);
// Establece el valor de la variable
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
void switchRotate();
// Establece el valor de la variable
void setFlip(SDL_RendererFlip flip);
// Gira el sprite horizontalmente
void flip();
// Obtiene el valor de la variable
SDL_RendererFlip getFlip();
// Devuelve el rectangulo donde está el sprite
SDL_Rect getRect();
// Deshace el último movimiento
void undoMove();
// Deshace el último movimiento en el eje X
void undoMoveX();
// Deshace el último movimiento en el eje Y
void undoMoveY();
// Pone a cero las velocidades de desplacamiento
void clearVel();
// Devuelve el incremento en el eje X en pixels
int getIncX();
};
#endif

View File

@@ -21,8 +21,10 @@ Screen::Screen(SDL_Window *window, SDL_Renderer *renderer, options_t *options, i
// Crea la textura donde se dibujan los graficos del juego
gameCanvas = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, gameCanvasWidth, gameCanvasHeight);
if (gameCanvas == NULL)
if (gameCanvas == nullptr)
{
printf("TitleSurface could not be created!\nSDL Error: %s\n", SDL_GetError());
}
// Establece el modo de video
setVideoMode(options->fullScreenMode);
@@ -59,14 +61,14 @@ void Screen::start()
void Screen::blit()
{
// Vuelve a dejar el renderizador en modo normal
SDL_SetRenderTarget(renderer, NULL);
SDL_SetRenderTarget(renderer, nullptr);
// Borra el contenido previo
SDL_SetRenderDrawColor(renderer, borderColor.r, borderColor.g, borderColor.b, 0xFF);
SDL_RenderClear(renderer);
// Copia la textura de juego en el renderizador en la posición adecuada
SDL_RenderCopy(renderer, gameCanvas, NULL, &dest);
SDL_RenderCopy(renderer, gameCanvas, nullptr, &dest);
// Muestra por pantalla el renderizador
SDL_RenderPresent(renderer);

View File

@@ -1,14 +1,19 @@
#include "const.h"
#include "smartsprite.h"
// Constructor
SmartSprite::SmartSprite(LTexture *texture, SDL_Renderer *renderer)
SmartSprite::SmartSprite(Texture *texture, SDL_Renderer *renderer)
{
// Copia punteros
setTexture(texture);
setRenderer(renderer);
// Inicializa variables
// Inicializa el objeto
init();
}
// Inicializa el objeto
void SmartSprite::init()
{
enabled = false;
enabledCounter = 0;
onDestination = false;
@@ -18,11 +23,6 @@ SmartSprite::SmartSprite(LTexture *texture, SDL_Renderer *renderer)
finished = false;
}
// Destructor
SmartSprite::~SmartSprite()
{
}
// Actualiza la posición y comprueba si ha llegado a su destino
void SmartSprite::update()
{

View File

@@ -1,73 +1,73 @@
#pragma once
#include <SDL2/SDL.h>
#include "animatedsprite.h"
#include "utils.h"
#include <vector>
#ifndef SMARTSPRITE_H
#define SMARTSPRITE_H
// Clase SmartSprite
class SmartSprite : public AnimatedSprite
{
private:
// VAriables
bool enabled; // Indica si esta habilitado
bool onDestination; // Indica si está en el destino
int destX; // Posicion de destino en el eje X
int destY; // Posicion de destino en el eje Y
int enabledCounter; // Contador para deshabilitarlo
bool finished; // Indica si ya ha terminado
// Comprueba el movimiento
void checkMove();
// Comprueba si ha terminado
void checkFinished();
public:
// Constructor
SmartSprite(LTexture *texture, SDL_Renderer *renderer);
// Destructor
~SmartSprite();
// Actualiza la posición y comprueba si ha llegado a su destino
void update();
// Pinta el objeto en pantalla
void render();
// Obtiene el valor de la variable
bool isEnabled();
// Establece el valor de la variable
void setEnabled(bool enabled);
// Obtiene el valor de la variable
int getEnabledCounter();
// Establece el valor de la variable
void setEnabledCounter(int value);
// Establece el valor de la variable
void setDestX(int x);
// Establece el valor de la variable
void setDestY(int y);
// Obtiene el valor de la variable
int getDestX();
// Obtiene el valor de la variable
int getDestY();
// Obtiene el valor de la variable
bool isOnDestination();
// Obtiene el valor de la variable
bool hasFinished();
};
#endif
#pragma once
#include <SDL2/SDL.h>
#include "animatedsprite.h"
#include "utils.h"
#include <vector>
#ifndef SMARTSPRITE_H
#define SMARTSPRITE_H
// Clase SmartSprite
class SmartSprite : public AnimatedSprite
{
private:
// Variables
bool enabled; // Indica si esta habilitado
bool onDestination; // Indica si está en el destino
int destX; // Posicion de destino en el eje X
int destY; // Posicion de destino en el eje Y
int enabledCounter; // Contador para deshabilitarlo
bool finished; // Indica si ya ha terminado
// Comprueba el movimiento
void checkMove();
// Comprueba si ha terminado
void checkFinished();
public:
// Constructor
SmartSprite(Texture *texture, SDL_Renderer *renderer);
// Inicializa el objeto
void init();
// Actualiza la posición y comprueba si ha llegado a su destino
void update();
// Pinta el objeto en pantalla
void render();
// Obtiene el valor de la variable
bool isEnabled();
// Establece el valor de la variable
void setEnabled(bool enabled);
// Obtiene el valor de la variable
int getEnabledCounter();
// Establece el valor de la variable
void setEnabledCounter(int value);
// Establece el valor de la variable
void setDestX(int x);
// Establece el valor de la variable
void setDestY(int y);
// Obtiene el valor de la variable
int getDestX();
// Obtiene el valor de la variable
int getDestY();
// Obtiene el valor de la variable
bool isOnDestination();
// Obtiene el valor de la variable
bool hasFinished();
};
#endif

View File

@@ -1,7 +1,7 @@
#include "sprite.h"
// Constructor
Sprite::Sprite(int x, int y, int w, int h, LTexture *texture, SDL_Renderer *renderer)
Sprite::Sprite(int x, int y, int w, int h, Texture *texture, SDL_Renderer *renderer)
{
// Establece la posición X,Y del sprite
this->x = x;
@@ -24,7 +24,7 @@ Sprite::Sprite(int x, int y, int w, int h, LTexture *texture, SDL_Renderer *rend
enabled = true;
}
Sprite::Sprite(SDL_Rect rect, LTexture *texture, SDL_Renderer *renderer)
Sprite::Sprite(SDL_Rect rect, Texture *texture, SDL_Renderer *renderer)
{
// Establece la posición X,Y del sprite
x = rect.x;
@@ -137,13 +137,13 @@ void Sprite::setSpriteClip(int x, int y, int w, int h)
}
// Obten el valor de la variable
LTexture *Sprite::getTexture()
Texture *Sprite::getTexture()
{
return texture;
}
// Establece el valor de la variable
void Sprite::setTexture(LTexture *texture)
void Sprite::setTexture(Texture *texture)
{
this->texture = texture;
}

View File

@@ -1,96 +1,96 @@
#pragma once
#include <SDL2/SDL.h>
#include "ltexture.h"
#ifndef SPRITE_H
#define SPRITE_H
// Clase sprite
class Sprite
{
protected:
int x; // Posición en el eje X donde dibujar el sprite
int y; // Posición en el eje Y donde dibujar el sprite
int w; // Ancho del sprite
int h; // Alto del sprite
SDL_Renderer *renderer; // Puntero al renderizador de la ventana
LTexture *texture; // Textura donde estan todos los dibujos del sprite
SDL_Rect spriteClip; // Rectangulo de origen de la textura que se dibujará en pantalla
bool enabled; // Indica si el sprite esta habilitado
public:
// Constructor
Sprite(int x = 0, int y = 0, int w = 0, int h = 0, LTexture *texture = nullptr, SDL_Renderer *renderer = nullptr);
Sprite(SDL_Rect rect, LTexture *texture, SDL_Renderer *renderer);
// Destructor
~Sprite();
// Muestra el sprite por pantalla
void render();
// Obten el valor de la variable
int getPosX();
// Obten el valor de la variable
int getPosY();
// Obten el valor de la variable
int getWidth();
// Obten el valor de la variable
int getHeight();
// Establece la posición del objeto
void setPos(SDL_Rect rect);
// Establece el valor de la variable
void setPosX(int x);
// Establece el valor de la variable
void setPosY(int y);
// Establece el valor de la variable
void setWidth(int w);
// Establece el valor de la variable
void setHeight(int h);
// Obten el valor de la variable
SDL_Rect getSpriteClip();
// Establece el valor de la variable
void setSpriteClip(SDL_Rect rect);
// Establece el valor de la variable
void setSpriteClip(int x, int y, int w, int h);
// Obten el valor de la variable
LTexture *getTexture();
// Establece el valor de la variable
void setTexture(LTexture *texture);
// Obten el valor de la variable
SDL_Renderer *getRenderer();
// Establece el valor de la variable
void setRenderer(SDL_Renderer *renderer);
// Establece el valor de la variable
void setEnabled(bool value);
// Comprueba si el objeto está habilitado
bool isEnabled();
// Devuelve el rectangulo donde está el sprite
SDL_Rect getRect();
// Establece los valores de posición y tamaño del sprite
void setRect(SDL_Rect rect);
};
#endif
#pragma once
#include <SDL2/SDL.h>
#include "texture.h"
#ifndef SPRITE_H
#define SPRITE_H
// Clase sprite
class Sprite
{
protected:
int x; // Posición en el eje X donde dibujar el sprite
int y; // Posición en el eje Y donde dibujar el sprite
int w; // Ancho del sprite
int h; // Alto del sprite
SDL_Renderer *renderer; // Puntero al renderizador de la ventana
Texture *texture; // Textura donde estan todos los dibujos del sprite
SDL_Rect spriteClip; // Rectangulo de origen de la textura que se dibujará en pantalla
bool enabled; // Indica si el sprite esta habilitado
public:
// Constructor
Sprite(int x = 0, int y = 0, int w = 0, int h = 0, Texture *texture = nullptr, SDL_Renderer *renderer = nullptr);
Sprite(SDL_Rect rect, Texture *texture, SDL_Renderer *renderer);
// Destructor
~Sprite();
// Muestra el sprite por pantalla
void render();
// Obten el valor de la variable
int getPosX();
// Obten el valor de la variable
int getPosY();
// Obten el valor de la variable
int getWidth();
// Obten el valor de la variable
int getHeight();
// Establece la posición del objeto
void setPos(SDL_Rect rect);
// Establece el valor de la variable
void setPosX(int x);
// Establece el valor de la variable
void setPosY(int y);
// Establece el valor de la variable
void setWidth(int w);
// Establece el valor de la variable
void setHeight(int h);
// Obten el valor de la variable
SDL_Rect getSpriteClip();
// Establece el valor de la variable
void setSpriteClip(SDL_Rect rect);
// Establece el valor de la variable
void setSpriteClip(int x, int y, int w, int h);
// Obten el valor de la variable
Texture *getTexture();
// Establece el valor de la variable
void setTexture(Texture *texture);
// Obten el valor de la variable
SDL_Renderer *getRenderer();
// Establece el valor de la variable
void setRenderer(SDL_Renderer *renderer);
// Establece el valor de la variable
void setEnabled(bool value);
// Comprueba si el objeto está habilitado
bool isEnabled();
// Devuelve el rectangulo donde está el sprite
SDL_Rect getRect();
// Establece los valores de posición y tamaño del sprite
void setRect(SDL_Rect rect);
};
#endif

View File

@@ -10,7 +10,7 @@ Text::Text(std::string bitmapFile, std::string textFile, SDL_Renderer *renderer)
initOffsetFromFile(textFile);
// Crea los objetos
texture = new LTexture(renderer, bitmapFile);
texture = new Texture(renderer, bitmapFile);
sprite = new Sprite({0, 0, boxWidth, boxHeight}, texture, renderer);
}
@@ -143,7 +143,9 @@ void Text::initOffsetFromFile(std::string file)
{
// Almacena solo las lineas impares
if (line_read % 2 == 1)
{
offset[index++].w = std::stoi(buffer);
}
// Limpia el buffer
buffer.clear();

View File

@@ -1,69 +1,69 @@
#pragma once
#include "sprite.h"
#include "utils.h"
#ifndef TEXT_H
#define TEXT_H
#define TXT_COLOR 1
#define TXT_SHADOW 2
#define TXT_CENTER 4
#define TXT_STROKE 8
// Clase texto. Pinta texto en pantalla a partir de un bitmap
class Text
{
private:
struct offset_t
{
int x;
int y;
int w;
};
// Objetos
Sprite *sprite; // Objeto con los graficos para el texto
LTexture *texture; // Textura con los bitmaps del texto
// Variables
int boxWidth; // Anchura de la caja de cada caracter en el png
int boxHeight; // Altura de la caja de cada caracter en el png
offset_t offset[128]; // Vector con las posiciones y ancho de cada letra
// Inicializa el vector de offsets desde un fichero
void initOffsetFromFile(std::string file);
public:
// Constructor
Text(std::string bitmapFile, std::string textFile, SDL_Renderer *renderer);
// Destructor
~Text();
// Escribe el texto en pantalla
void write(int x, int y, std::string text, int kerning = 1, int lenght = -1);
// Escribe el texto con colores
void writeColored(int x, int y, std::string text, color_t color, int kerning = 1, int lenght = -1);
// Escribe el texto con sombra
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
void writeCentered(int x, int y, std::string text, int kerning = 1, int lenght = -1);
// Escribe texto con extras
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
int lenght(std::string text, int kerning = 1);
// Devuelve el valor de la variable
int getCharacterSize();
// Recarga la textura
void reLoadTexture();
};
#endif
#pragma once
#include "sprite.h"
#include "utils.h"
#ifndef TEXT_H
#define TEXT_H
#define TXT_COLOR 1
#define TXT_SHADOW 2
#define TXT_CENTER 4
#define TXT_STROKE 8
// Clase texto. Pinta texto en pantalla a partir de un bitmap
class Text
{
private:
struct offset_t
{
int x;
int y;
int w;
};
// Objetos y punteros
Sprite *sprite; // Objeto con los graficos para el texto
Texture *texture; // Textura con los bitmaps del texto
// Variables
int boxWidth; // Anchura de la caja de cada caracter en el png
int boxHeight; // Altura de la caja de cada caracter en el png
offset_t offset[128]; // Vector con las posiciones y ancho de cada letra
// Inicializa el vector de offsets desde un fichero
void initOffsetFromFile(std::string file);
public:
// Constructor
Text(std::string bitmapFile, std::string textFile, SDL_Renderer *renderer);
// Destructor
~Text();
// Escribe el texto en pantalla
void write(int x, int y, std::string text, int kerning = 1, int lenght = -1);
// Escribe el texto con colores
void writeColored(int x, int y, std::string text, color_t color, int kerning = 1, int lenght = -1);
// Escribe el texto con sombra
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
void writeCentered(int x, int y, std::string text, int kerning = 1, int lenght = -1);
// Escribe texto con extras
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
int lenght(std::string text, int kerning = 1);
// Devuelve el valor de la variable
int getCharacterSize();
// Recarga la textura
void reLoadTexture();
};
#endif

View File

@@ -1,191 +1,191 @@
#include "ltexture.h"
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
// Constructor
LTexture::LTexture(SDL_Renderer *renderer, std::string path)
{
// Copia punteros
this->renderer = renderer;
this->path = path;
// Inicializa
texture = nullptr;
width = 0;
height = 0;
// Carga el fichero en la textura
if (path != "")
{
loadFromFile(path, renderer);
}
}
// Destructor
LTexture::~LTexture()
{
// Libera memoria
unload();
}
// Carga una imagen desde un fichero
bool LTexture::loadFromFile(std::string path, SDL_Renderer *renderer)
{
const std::string filename = path.substr(path.find_last_of("\\/") + 1);
int req_format = STBI_rgb_alpha;
int width, height, orig_format;
unsigned char *data = stbi_load(path.c_str(), &width, &height, &orig_format, req_format);
if (data == nullptr)
{
SDL_Log("Loading image failed: %s", stbi_failure_reason());
exit(1);
}
else
{
printf("Image loaded: %s\n", filename.c_str());
}
int depth, pitch;
Uint32 pixel_format;
if (req_format == STBI_rgb)
{
depth = 24;
pitch = 3 * width; // 3 bytes por pixel * pixels per linea
pixel_format = SDL_PIXELFORMAT_RGB24;
}
else
{ // STBI_rgb_alpha (RGBA)
depth = 32;
pitch = 4 * width;
pixel_format = SDL_PIXELFORMAT_RGBA32;
}
// Limpia
unload();
// La textura final
SDL_Texture *newTexture = nullptr;
// Carga la imagen desde una ruta específica
SDL_Surface *loadedSurface = SDL_CreateRGBSurfaceWithFormatFrom((void *)data, width, height, depth, pitch, pixel_format);
if (loadedSurface == nullptr)
{
printf("Unable to load image %s!\n", path.c_str());
}
else
{
// Crea la textura desde los pixels de la surface
newTexture = SDL_CreateTextureFromSurface(renderer, loadedSurface);
if (newTexture == nullptr)
{
printf("Unable to create texture from %s! SDL Error: %s\n", path.c_str(), SDL_GetError());
}
else
{
// Obtiene las dimensiones de la imagen
this->width = loadedSurface->w;
this->height = loadedSurface->h;
}
// Elimina la textura cargada
SDL_FreeSurface(loadedSurface);
}
// Return success
texture = newTexture;
return texture != nullptr;
}
// Crea una textura en blanco
bool LTexture::createBlank(SDL_Renderer *renderer, int width, int height, SDL_TextureAccess access)
{
// Crea una textura sin inicializar
texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, access, width, height);
if (texture == nullptr)
{
printf("Unable to create blank texture! SDL Error: %s\n", SDL_GetError());
}
else
{
this->width = width;
this->height = height;
}
return texture != nullptr;
}
// Libera la memoria de la textura
void LTexture::unload()
{
// Libera la textura si existe
if (texture != nullptr)
{
SDL_DestroyTexture(texture);
texture = nullptr;
width = 0;
height = 0;
}
}
// Establece el color para la modulacion
void LTexture::setColor(Uint8 red, Uint8 green, Uint8 blue)
{
SDL_SetTextureColorMod(texture, red, green, blue);
}
// Establece el blending
void LTexture::setBlendMode(SDL_BlendMode blending)
{
SDL_SetTextureBlendMode(texture, blending);
}
// Establece el alpha para la modulación
void LTexture::setAlpha(Uint8 alpha)
{
SDL_SetTextureAlphaMod(texture, alpha);
}
// Renderiza la textura en un punto específico
void LTexture::render(SDL_Renderer *renderer, int x, int y, SDL_Rect *clip, float zoomW, float zoomH, double angle, SDL_Point *center, SDL_RendererFlip flip)
{
// Establece el destino de renderizado en la pantalla
SDL_Rect renderQuad = {x, y, width, height};
// Obtiene las dimesiones del clip de renderizado
if (clip != nullptr)
{
renderQuad.w = clip->w;
renderQuad.h = clip->h;
}
renderQuad.w = renderQuad.w * zoomW;
renderQuad.h = renderQuad.h * zoomH;
// Renderiza a pantalla
SDL_RenderCopyEx(renderer, texture, clip, &renderQuad, angle, center, flip);
}
// Establece la textura como objetivo de renderizado
void LTexture::setAsRenderTarget(SDL_Renderer *renderer)
{
SDL_SetRenderTarget(renderer, texture);
}
// Obtiene el ancho de la imagen
int LTexture::getWidth()
{
return width;
}
// Obtiene el alto de la imagen
int LTexture::getHeight()
{
return height;
}
// Recarga la textura
bool LTexture::reLoad()
{
return loadFromFile(path, renderer);
#include "texture.h"
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
// Constructor
Texture::Texture(SDL_Renderer *renderer, std::string path)
{
// Copia punteros
this->renderer = renderer;
this->path = path;
// Inicializa
texture = nullptr;
width = 0;
height = 0;
// Carga el fichero en la textura
if (path != "")
{
loadFromFile(path, renderer);
}
}
// Destructor
Texture::~Texture()
{
// Libera memoria
unload();
}
// Carga una imagen desde un fichero
bool Texture::loadFromFile(std::string path, SDL_Renderer *renderer)
{
const std::string filename = path.substr(path.find_last_of("\\/") + 1);
int req_format = STBI_rgb_alpha;
int width, height, orig_format;
unsigned char *data = stbi_load(path.c_str(), &width, &height, &orig_format, req_format);
if (data == nullptr)
{
SDL_Log("Loading image failed: %s", stbi_failure_reason());
exit(1);
}
else
{
printf("Image loaded: %s\n", filename.c_str());
}
int depth, pitch;
Uint32 pixel_format;
if (req_format == STBI_rgb)
{
depth = 24;
pitch = 3 * width; // 3 bytes por pixel * pixels per linea
pixel_format = SDL_PIXELFORMAT_RGB24;
}
else
{ // STBI_rgb_alpha (RGBA)
depth = 32;
pitch = 4 * width;
pixel_format = SDL_PIXELFORMAT_RGBA32;
}
// Limpia
unload();
// La textura final
SDL_Texture *newTexture = nullptr;
// Carga la imagen desde una ruta específica
SDL_Surface *loadedSurface = SDL_CreateRGBSurfaceWithFormatFrom((void *)data, width, height, depth, pitch, pixel_format);
if (loadedSurface == nullptr)
{
printf("Unable to load image %s!\n", path.c_str());
}
else
{
// Crea la textura desde los pixels de la surface
newTexture = SDL_CreateTextureFromSurface(renderer, loadedSurface);
if (newTexture == nullptr)
{
printf("Unable to create texture from %s! SDL Error: %s\n", path.c_str(), SDL_GetError());
}
else
{
// Obtiene las dimensiones de la imagen
this->width = loadedSurface->w;
this->height = loadedSurface->h;
}
// Elimina la textura cargada
SDL_FreeSurface(loadedSurface);
}
// Return success
texture = newTexture;
return texture != nullptr;
}
// Crea una textura en blanco
bool Texture::createBlank(SDL_Renderer *renderer, int width, int height, SDL_TextureAccess access)
{
// Crea una textura sin inicializar
texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, access, width, height);
if (texture == nullptr)
{
printf("Unable to create blank texture! SDL Error: %s\n", SDL_GetError());
}
else
{
this->width = width;
this->height = height;
}
return texture != nullptr;
}
// Libera la memoria de la textura
void Texture::unload()
{
// Libera la textura si existe
if (texture != nullptr)
{
SDL_DestroyTexture(texture);
texture = nullptr;
width = 0;
height = 0;
}
}
// Establece el color para la modulacion
void Texture::setColor(Uint8 red, Uint8 green, Uint8 blue)
{
SDL_SetTextureColorMod(texture, red, green, blue);
}
// Establece el blending
void Texture::setBlendMode(SDL_BlendMode blending)
{
SDL_SetTextureBlendMode(texture, blending);
}
// Establece el alpha para la modulación
void Texture::setAlpha(Uint8 alpha)
{
SDL_SetTextureAlphaMod(texture, alpha);
}
// Renderiza la textura en un punto específico
void Texture::render(SDL_Renderer *renderer, int x, int y, SDL_Rect *clip, float zoomW, float zoomH, double angle, SDL_Point *center, SDL_RendererFlip flip)
{
// Establece el destino de renderizado en la pantalla
SDL_Rect renderQuad = {x, y, width, height};
// Obtiene las dimesiones del clip de renderizado
if (clip != nullptr)
{
renderQuad.w = clip->w;
renderQuad.h = clip->h;
}
renderQuad.w = renderQuad.w * zoomW;
renderQuad.h = renderQuad.h * zoomH;
// Renderiza a pantalla
SDL_RenderCopyEx(renderer, texture, clip, &renderQuad, angle, center, flip);
}
// Establece la textura como objetivo de renderizado
void Texture::setAsRenderTarget(SDL_Renderer *renderer)
{
SDL_SetRenderTarget(renderer, texture);
}
// Obtiene el ancho de la imagen
int Texture::getWidth()
{
return width;
}
// Obtiene el alto de la imagen
int Texture::getHeight()
{
return height;
}
// Recarga la textura
bool Texture::reLoad()
{
return loadFromFile(path, renderer);
}

View File

@@ -1,61 +1,63 @@
#pragma once
#include <SDL2/SDL.h>
#include <stdio.h>
#include <string>
#ifndef LTEXTURE_H
#define LTEXTURE_H
// Clase LTexture
class LTexture
{
private:
SDL_Texture *texture; // La textura
SDL_Renderer *renderer; // Renderizador donde dibujar la textura
int width; // Ancho de la imagen
int height; // Alto de la imagen
std::string path; // Ruta de la imagen de la textura
public:
// Constructor
LTexture(SDL_Renderer *renderer, std::string path = "");
// Destructor
~LTexture();
// Carga una imagen desde un fichero
bool loadFromFile(std::string path, SDL_Renderer *renderer);
// Crea una textura en blanco
bool createBlank(SDL_Renderer *renderer, int width, int height, SDL_TextureAccess = SDL_TEXTUREACCESS_STREAMING);
// Libera la memoria de la textura
void unload();
// Establece el color para la modulacion
void setColor(Uint8 red, Uint8 green, Uint8 blue);
// Establece el blending
void setBlendMode(SDL_BlendMode blending);
// Establece el alpha para la modulación
void setAlpha(Uint8 alpha);
// Renderiza la textura en un punto específico
void render(SDL_Renderer *renderer, int x, int y, SDL_Rect *clip = nullptr, float zoomW = 1, float zoomH = 1, double angle = 0.0, SDL_Point *center = nullptr, SDL_RendererFlip flip = SDL_FLIP_NONE);
// Establece la textura como objetivo de renderizado
void setAsRenderTarget(SDL_Renderer *renderer);
// Obtiene el ancho de la imagen
int getWidth();
// Obtiene el alto de la imagen
int getHeight();
// Recarga la textura
bool reLoad();
};
#endif
#pragma once
#include <SDL2/SDL.h>
#include <stdio.h>
#include <string>
#ifndef TEXTURE_H
#define TEXTURE_H
class Texture
{
private:
// Objetos y punteros
SDL_Texture *texture; // La textura
SDL_Renderer *renderer; // Renderizador donde dibujar la textura
// Variables
int width; // Ancho de la imagen
int height; // Alto de la imagen
std::string path; // Ruta de la imagen de la textura
public:
// Constructor
Texture(SDL_Renderer *renderer, std::string path = "");
// Destructor
~Texture();
// Carga una imagen desde un fichero
bool loadFromFile(std::string path, SDL_Renderer *renderer);
// Crea una textura en blanco
bool createBlank(SDL_Renderer *renderer, int width, int height, SDL_TextureAccess = SDL_TEXTUREACCESS_STREAMING);
// Libera la memoria de la textura
void unload();
// Establece el color para la modulacion
void setColor(Uint8 red, Uint8 green, Uint8 blue);
// Establece el blending
void setBlendMode(SDL_BlendMode blending);
// Establece el alpha para la modulación
void setAlpha(Uint8 alpha);
// Renderiza la textura en un punto específico
void render(SDL_Renderer *renderer, int x, int y, SDL_Rect *clip = nullptr, float zoomW = 1, float zoomH = 1, double angle = 0.0, SDL_Point *center = nullptr, SDL_RendererFlip flip = SDL_FLIP_NONE);
// Establece la textura como objetivo de renderizado
void setAsRenderTarget(SDL_Renderer *renderer);
// Obtiene el ancho de la imagen
int getWidth();
// Obtiene el alto de la imagen
int getHeight();
// Recarga la textura
bool reLoad();
};
#endif

View File

@@ -1,7 +1,7 @@
#pragma once
#include <SDL2/SDL.h>
#include "ltexture.h"
#include "texture.h"
#include <string>
#include <vector>
@@ -87,6 +87,7 @@ struct input_t
struct options_t
{
Uint8 difficulty; // Dificultad del juego
Uint8 playerSelected; // Jugador seleccionado para el modo 1P
std::vector<input_t> input; // Modo de control (teclado o mando)
Uint8 language; // Idioma usado en el juego
Uint32 fullScreenMode; // Contiene el valor del modo de pantalla completa

View File

@@ -1,4 +1,3 @@
#include "const.h"
#include "writer.h"
// Constructor
@@ -22,11 +21,6 @@ Writer::Writer(Text *text)
finished = false;
}
// Destructor
Writer::~Writer()
{
}
// Actualiza el objeto
void Writer::update()
{

View File

@@ -11,7 +11,7 @@
class Writer
{
private:
// Objetos
// Objetos y punteros
Text *text; // Objeto encargado de escribir el texto
// Variables
@@ -32,9 +32,6 @@ public:
// Constructor
Writer(Text *text);
// Destructor
~Writer();
// Actualiza el objeto
void update();

View File

@@ -1,7 +1,7 @@
#pragma once
#include <SDL2/SDL.h>
#include "utils.h"
#include "common/utils.h"
#include "lang.h"
#ifndef CONST_H

View File

@@ -1,22 +1,17 @@
#include "const.h"
#include "director.h"
#include "utils.h"
#include "common/utils.h"
#include <iostream>
#include <string>
// Constructor
Director::Director(std::string path)
{
// Inicializa variables
section.name = PROG_SECTION_GAME;
section.subsection = GAME_SECTION_PLAY_1P;
section.name = PROG_SECTION_LOGO;
section.subsection = 0;
// Crea el objeto que controla los ficheros de recursos
asset = new Asset(path.substr(0, path.find_last_of("\\/")) + "/../");
asset = new Asset(path);
// Establece la lista de ficheros
if (!setFileList())
@@ -103,7 +98,8 @@ bool Director::initSDL()
bool success = true;
// Inicializa SDL
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_GAMECONTROLLER | SDL_INIT_AUDIO) < 0)
if (SDL_Init(SDL_INIT_EVERYTHING) < 0)
// if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_GAMECONTROLLER | SDL_INIT_AUDIO) < 0)
{
printf("SDL could not initialize!\nSDL Error: %s\n", SDL_GetError());
success = false;
@@ -130,9 +126,13 @@ bool Director::initSDL()
{
// Crea un renderizador para la ventana. El vsync se activa en funcion de las opciones
if (options->vSync)
{
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
}
else
{
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
}
if (renderer == nullptr)
{
@@ -160,118 +160,128 @@ bool Director::initSDL()
// Crea el indice de ficheros
bool Director::setFileList()
{
#ifdef MACOS_BUNDLE
const std::string prefix = "/../Resources";
#else
const std::string prefix = "";
#endif
// Ficheros de configuración
asset->add("data/config/score.bin", t_data, false);
asset->add("data/config/demo.bin", t_data);
asset->add("data/config/config.bin", t_data, false);
asset->add("data/config/gamecontrollerdb.txt", t_data);
asset->add(prefix + "/data/config/score.bin", t_data, false);
asset->add(prefix + "/data/config/demo.bin", t_data);
asset->add(prefix + "/data/config/config.bin", t_data, false);
asset->add(prefix + "/data/config/gamecontrollerdb.txt", t_data);
// Musicas
asset->add("data/music/intro.ogg", t_music);
asset->add("data/music/playing.ogg", t_music);
asset->add("data/music/title.ogg", t_music);
asset->add(prefix + "/data/music/intro.ogg", t_music);
asset->add(prefix + "/data/music/playing.ogg", t_music);
asset->add(prefix + "/data/music/title.ogg", t_music);
// Sonidos
asset->add("data/sound/balloon.wav", t_sound);
asset->add("data/sound/bubble1.wav", t_sound);
asset->add("data/sound/bubble2.wav", t_sound);
asset->add("data/sound/bubble3.wav", t_sound);
asset->add("data/sound/bubble4.wav", t_sound);
asset->add("data/sound/bullet.wav", t_sound);
asset->add("data/sound/coffeeout.wav", t_sound);
asset->add("data/sound/hiscore.wav", t_sound);
asset->add("data/sound/itemdrop.wav", t_sound);
asset->add("data/sound/itempickup.wav", t_sound);
asset->add("data/sound/menu_cancel.wav", t_sound);
asset->add("data/sound/menu_move.wav", t_sound);
asset->add("data/sound/menu_select.wav", t_sound);
asset->add("data/sound/player_collision.wav", t_sound);
asset->add("data/sound/stage_change.wav", t_sound);
asset->add("data/sound/title.wav", t_sound);
asset->add("data/sound/clock.wav", t_sound);
asset->add("data/sound/powerball.wav", t_sound);
asset->add(prefix + "/data/sound/balloon.wav", t_sound);
asset->add(prefix + "/data/sound/bubble1.wav", t_sound);
asset->add(prefix + "/data/sound/bubble2.wav", t_sound);
asset->add(prefix + "/data/sound/bubble3.wav", t_sound);
asset->add(prefix + "/data/sound/bubble4.wav", t_sound);
asset->add(prefix + "/data/sound/bullet.wav", t_sound);
asset->add(prefix + "/data/sound/coffeeout.wav", t_sound);
asset->add(prefix + "/data/sound/hiscore.wav", t_sound);
asset->add(prefix + "/data/sound/itemdrop.wav", t_sound);
asset->add(prefix + "/data/sound/itempickup.wav", t_sound);
asset->add(prefix + "/data/sound/menu_move.wav", t_sound);
asset->add(prefix + "/data/sound/menu_select.wav", t_sound);
asset->add(prefix + "/data/sound/player_collision.wav", t_sound);
asset->add(prefix + "/data/sound/stage_change.wav", t_sound);
asset->add(prefix + "/data/sound/title.wav", t_sound);
asset->add(prefix + "/data/sound/clock.wav", t_sound);
asset->add(prefix + "/data/sound/powerball.wav", t_sound);
// Texturas
asset->add("data/gfx/balloon1.png", t_bitmap);
asset->add("data/gfx/balloon1.ani", t_data);
asset->add("data/gfx/balloon2.png", t_bitmap);
asset->add("data/gfx/balloon2.ani", t_data);
asset->add("data/gfx/balloon3.png", t_bitmap);
asset->add("data/gfx/balloon3.ani", t_data);
asset->add("data/gfx/balloon4.png", t_bitmap);
asset->add("data/gfx/balloon4.ani", t_data);
asset->add("data/gfx/bullet.png", t_bitmap);
asset->add(prefix + "/data/gfx/balloon1.png", t_bitmap);
asset->add(prefix + "/data/gfx/balloon1.ani", t_data);
asset->add(prefix + "/data/gfx/balloon2.png", t_bitmap);
asset->add(prefix + "/data/gfx/balloon2.ani", t_data);
asset->add(prefix + "/data/gfx/balloon3.png", t_bitmap);
asset->add(prefix + "/data/gfx/balloon3.ani", t_data);
asset->add(prefix + "/data/gfx/balloon4.png", t_bitmap);
asset->add(prefix + "/data/gfx/balloon4.ani", t_data);
asset->add(prefix + "/data/gfx/bullet.png", t_bitmap);
asset->add("data/gfx/game_buildings.png", t_bitmap);
asset->add("data/gfx/game_clouds.png", t_bitmap);
asset->add("data/gfx/game_grass.png", t_bitmap);
asset->add("data/gfx/game_power_meter.png", t_bitmap);
asset->add("data/gfx/game_sky_colors.png", t_bitmap);
asset->add("data/gfx/game_text.png", t_bitmap);
asset->add(prefix + "/data/gfx/game_buildings.png", t_bitmap);
asset->add(prefix + "/data/gfx/game_clouds.png", t_bitmap);
asset->add(prefix + "/data/gfx/game_grass.png", t_bitmap);
asset->add(prefix + "/data/gfx/game_power_meter.png", t_bitmap);
asset->add(prefix + "/data/gfx/game_sky_colors.png", t_bitmap);
asset->add(prefix + "/data/gfx/game_text.png", t_bitmap);
asset->add("data/gfx/intro.png", t_bitmap);
asset->add("data/gfx/logo.png", t_bitmap);
asset->add("data/gfx/items.png", t_bitmap);
asset->add("data/gfx/item_points1_disk.png", t_bitmap);
asset->add("data/gfx/item_points1_disk.ani", t_data);
asset->add("data/gfx/item_points2_gavina.png", t_bitmap);
asset->add("data/gfx/item_points2_gavina.ani", t_data);
asset->add("data/gfx/item_points3_pacmar.png", t_bitmap);
asset->add("data/gfx/item_points3_pacmar.ani", t_data);
asset->add("data/gfx/item_clock.png", t_bitmap);
asset->add("data/gfx/item_clock.ani", t_data);
asset->add("data/gfx/item_coffee.png", t_bitmap);
asset->add("data/gfx/item_coffee.ani", t_data);
asset->add("data/gfx/item_coffee_machine.png", t_bitmap);
asset->add("data/gfx/item_coffee_machine.ani", t_data);
asset->add(prefix + "/data/gfx/intro.png", t_bitmap);
asset->add(prefix + "/data/gfx/logo.png", t_bitmap);
asset->add(prefix + "/data/gfx/menu_game_over.png", t_bitmap);
asset->add(prefix + "/data/gfx/menu_game_over_end.png", t_bitmap);
asset->add("data/gfx/title_bg_tile.png", t_bitmap);
asset->add("data/gfx/title_coffee.png", t_bitmap);
asset->add("data/gfx/title_crisis.png", t_bitmap);
asset->add("data/gfx/title_dust.png", t_bitmap);
asset->add("data/gfx/title_dust.ani", t_data);
asset->add("data/gfx/title_gradient.png", t_bitmap);
asset->add(prefix + "/data/gfx/item_points1_disk.png", t_bitmap);
asset->add(prefix + "/data/gfx/item_points1_disk.ani", t_data);
asset->add(prefix + "/data/gfx/item_points2_gavina.png", t_bitmap);
asset->add(prefix + "/data/gfx/item_points2_gavina.ani", t_data);
asset->add(prefix + "/data/gfx/item_points3_pacmar.png", t_bitmap);
asset->add(prefix + "/data/gfx/item_points3_pacmar.ani", t_data);
asset->add(prefix + "/data/gfx/item_clock.png", t_bitmap);
asset->add(prefix + "/data/gfx/item_clock.ani", t_data);
asset->add(prefix + "/data/gfx/item_coffee.png", t_bitmap);
asset->add(prefix + "/data/gfx/item_coffee.ani", t_data);
asset->add(prefix + "/data/gfx/item_coffee_machine.png", t_bitmap);
asset->add(prefix + "/data/gfx/item_coffee_machine.ani", t_data);
asset->add("data/gfx/player_head.ani", t_data);
asset->add("data/gfx/player_body.ani", t_data);
asset->add("data/gfx/player_legs.ani", t_data);
asset->add("data/gfx/player_death.ani", t_data);
asset->add(prefix + "/data/gfx/title_bg_tile.png", t_bitmap);
asset->add(prefix + "/data/gfx/title_coffee.png", t_bitmap);
asset->add(prefix + "/data/gfx/title_crisis.png", t_bitmap);
asset->add(prefix + "/data/gfx/title_dust.png", t_bitmap);
asset->add(prefix + "/data/gfx/title_dust.ani", t_data);
asset->add(prefix + "/data/gfx/title_gradient.png", t_bitmap);
asset->add("data/gfx/player_bal1_head.png", t_bitmap);
asset->add("data/gfx/player_bal1_body.png", t_bitmap);
asset->add("data/gfx/player_bal1_legs.png", t_bitmap);
asset->add("data/gfx/player_bal1_death.png", t_bitmap);
asset->add(prefix + "/data/gfx/player_head.ani", t_data);
asset->add(prefix + "/data/gfx/player_body.ani", t_data);
asset->add(prefix + "/data/gfx/player_legs.ani", t_data);
asset->add(prefix + "/data/gfx/player_death.ani", t_data);
asset->add(prefix + "/data/gfx/player_fire.ani", t_data);
asset->add("data/gfx/player_arounder_head.png", t_bitmap);
asset->add("data/gfx/player_arounder_body.png", t_bitmap);
asset->add("data/gfx/player_arounder_legs.png", t_bitmap);
asset->add("data/gfx/player_arounder_death.png", t_bitmap);
asset->add(prefix + "/data/gfx/player_bal1_head.png", t_bitmap);
asset->add(prefix + "/data/gfx/player_bal1_body.png", t_bitmap);
asset->add(prefix + "/data/gfx/player_bal1_legs.png", t_bitmap);
asset->add(prefix + "/data/gfx/player_bal1_death.png", t_bitmap);
asset->add(prefix + "/data/gfx/player_bal1_fire.png", t_bitmap);
asset->add(prefix + "/data/gfx/player_arounder_head.png", t_bitmap);
asset->add(prefix + "/data/gfx/player_arounder_body.png", t_bitmap);
asset->add(prefix + "/data/gfx/player_arounder_legs.png", t_bitmap);
asset->add(prefix + "/data/gfx/player_arounder_death.png", t_bitmap);
asset->add(prefix + "/data/gfx/player_arounder_fire.png", t_bitmap);
// Fuentes
asset->add("data/font/8bithud.png", t_font);
asset->add("data/font/8bithud.txt", t_font);
asset->add("data/font/nokia.png", t_font);
asset->add("data/font/nokia_big2.png", t_font);
asset->add("data/font/nokia.txt", t_font);
asset->add("data/font/nokia2.png", t_font);
asset->add("data/font/nokia2.txt", t_font);
asset->add("data/font/nokia_big2.txt", t_font);
asset->add("data/font/smb2_big.png", t_font);
asset->add("data/font/smb2_big.txt", t_font);
asset->add("data/font/smb2.png", t_font);
asset->add("data/font/smb2.txt", t_font);
asset->add(prefix + "/data/font/8bithud.png", t_font);
asset->add(prefix + "/data/font/8bithud.txt", t_font);
asset->add(prefix + "/data/font/nokia.png", t_font);
asset->add(prefix + "/data/font/nokia_big2.png", t_font);
asset->add(prefix + "/data/font/nokia.txt", t_font);
asset->add(prefix + "/data/font/nokia2.png", t_font);
asset->add(prefix + "/data/font/nokia2.txt", t_font);
asset->add(prefix + "/data/font/nokia_big2.txt", t_font);
asset->add(prefix + "/data/font/smb2_big.png", t_font);
asset->add(prefix + "/data/font/smb2_big.txt", t_font);
asset->add(prefix + "/data/font/smb2.png", t_font);
asset->add(prefix + "/data/font/smb2.txt", t_font);
// Textos
asset->add("data/lang/es_ES.txt", t_lang);
asset->add("data/lang/en_UK.txt", t_lang);
asset->add("data/lang/ba_BA.txt", t_lang);
asset->add(prefix + "/data/lang/es_ES.txt", t_lang);
asset->add(prefix + "/data/lang/en_UK.txt", t_lang);
asset->add(prefix + "/data/lang/ba_BA.txt", t_lang);
// Menus
asset->add("data/menu/title.men", t_data);
asset->add("data/menu/options.men", t_data);
asset->add("data/menu/pause.men", t_data);
asset->add("data/menu/gameover.men", t_data);
asset->add(prefix + "/data/menu/title.men", t_data);
asset->add(prefix + "/data/menu/options.men", t_data);
asset->add(prefix + "/data/menu/pause.men", t_data);
asset->add(prefix + "/data/menu/gameover.men", t_data);
asset->add(prefix + "/data/menu/player_select.men", t_data);
return asset->check();
}
@@ -297,6 +307,7 @@ bool Director::loadConfigFile()
options->windowSize = 3;
options->language = ba_BA;
options->difficulty = DIFFICULTY_NORMAL;
options->playerSelected = 0;
options->filter = FILTER_NEAREST;
options->vSync = true;
options->screenWidth = GAME_WIDTH;

View File

@@ -1,27 +1,27 @@
#pragma once
#include <SDL2/SDL.h>
#include "asset.h"
#include "balloon.h"
#include "bullet.h"
#include "common/asset.h"
#include "common/input.h"
#include "common/jail_audio.h"
#include "common/menu.h"
#include "common/movingsprite.h"
#include "common/screen.h"
#include "common/smartsprite.h"
#include "common/sprite.h"
#include "common/text.h"
#include "common/utils.h"
#include "common/writer.h"
#include "const.h"
#include "fade.h"
#include "game.h"
#include "input.h"
#include "intro.h"
#include "item.h"
#include "jail_audio.h"
#include "logo.h"
#include "menu.h"
#include "movingsprite.h"
#include "player.h"
#include "screen.h"
#include "smartsprite.h"
#include "sprite.h"
#include "text.h"
#include "title.h"
#include "utils.h"
#include "writer.h"
#ifndef DIRECTOR_H
#define DIRECTOR_H
@@ -29,11 +29,10 @@
// Textos
#define WINDOW_CAPTION "Coffee Crisis"
// Clase Director
class Director
{
private:
// Objetos
// Objetos y punteros
SDL_Window *window; // La ventana donde dibujamos
SDL_Renderer *renderer; // El renderizador de la ventana
Screen *screen; // Objeto encargado de dibujar en pantalla

View File

@@ -1,7 +1,7 @@
#pragma once
#include <SDL2/SDL.h>
#include "ltexture.h"
#include "common/texture.h"
#ifndef FADE_H
#define FADE_H

File diff suppressed because it is too large Load Diff

View File

@@ -1,23 +1,23 @@
#pragma once
#include <SDL2/SDL.h>
#include "asset.h"
#include "balloon.h"
#include "bullet.h"
#include "common/asset.h"
#include "common/input.h"
#include "common/jail_audio.h"
#include "common/menu.h"
#include "common/movingsprite.h"
#include "common/screen.h"
#include "common/smartsprite.h"
#include "common/sprite.h"
#include "common/text.h"
#include "common/utils.h"
#include "common/writer.h"
#include "const.h"
#include "fade.h"
#include "input.h"
#include "item.h"
#include "jail_audio.h"
#include "menu.h"
#include "movingsprite.h"
#include "player.h"
#include "screen.h"
#include "smartsprite.h"
#include "sprite.h"
#include "text.h"
#include "utils.h"
#include "writer.h"
#include <iostream>
#ifndef GAME_H
@@ -31,6 +31,8 @@
#define STAGE_COUNTER 200
#define SHAKE_COUNTER 10
#define HELP_COUNTER 1000
#define GAME_COMPLETED_START_FADE 500
#define GAME_COMPLETED_END 700
// Formaciones enemigas
#define NUMBER_OF_ENEMY_FORMATIONS 100
@@ -112,7 +114,7 @@ private:
demoKeys_t dataFile[TOTAL_DEMO_DATA]; // Datos del fichero con los movimientos para la demo
};
// Objetos
// Objetos y punteros
SDL_Renderer *renderer; // El renderizador de la ventana
Screen *screen; // Objeto encargado de dibujar en pantalla
Asset *asset; // Objeto que gestiona todos los ficheros de recursos
@@ -125,20 +127,21 @@ private:
std::vector<Item *> items; // Vector con los items
std::vector<SmartSprite *> smartSprites; // Vector con los smartsprites
LTexture *bulletTexture; // Textura para las balas
std::vector<LTexture *> itemTextures; // Vector con las texturas de los items
std::vector<LTexture *> balloonTextures; // Vector con las texturas de los globos
std::vector<LTexture *> player1Textures; // Vector con las texturas del jugador
std::vector<LTexture *> player2Textures; // Vector con las texturas del jugador
Texture *bulletTexture; // Textura para las balas
std::vector<Texture *> itemTextures; // Vector con las texturas de los items
std::vector<Texture *> balloonTextures; // Vector con las texturas de los globos
std::vector<Texture *> player1Textures; // Vector con las texturas del jugador
std::vector<Texture *> player2Textures; // Vector con las texturas del jugador
std::vector<std::vector<Texture *>> playerTextures; // Vector con todas las texturas de los jugadores;
LTexture *gameBuildingsTexture; // Textura con los edificios de fondo
LTexture *gameCloudsTexture; // Textura con las nubes de fondo
LTexture *gameGrassTexture; // Textura con la hierba del suelo
LTexture *gamePowerMeterTexture; // Textura con el marcador de poder de la fase
LTexture *gameSkyColorsTexture; // Textura con los diferentes colores de fondo del juego
LTexture *gameTextTexture; // Textura para los sprites con textos
LTexture *itemTexture; // Textura para los items
Texture *gameBuildingsTexture; // Textura con los edificios de fondo
Texture *gameCloudsTexture; // Textura con las nubes de fondo
Texture *gameGrassTexture; // Textura con la hierba del suelo
Texture *gamePowerMeterTexture; // Textura con el marcador de poder de la fase
Texture *gameSkyColorsTexture; // Textura con los diferentes colores de fondo del juego
Texture *gameTextTexture; // Textura para los sprites con textos
Texture *gameOverTexture; // Textura para la pantalla de game over
Texture *gameOverEndTexture; // Textura para la pantalla de game over de acabar el juego
std::vector<std::vector<std::string> *> itemAnimations; // Vector con las animaciones de los items
std::vector<std::vector<std::string> *> playerAnimations; // Vector con las animaciones del jugador
@@ -164,10 +167,12 @@ private:
SmartSprite *n2500Sprite; // Sprite con el texto 2.500
SmartSprite *n5000Sprite; // Sprite con el texto 5.000
Sprite *buildingsSprite; // Sprite con los edificios de fondo
Sprite *skyColorsSprite; // Sprite con los graficos del degradado de color de fondo
Sprite *grassSprite; // Sprite para la hierba
Sprite *powerMeterSprite; // Sprite para el medidor de poder de la fase
Sprite *buildingsSprite; // Sprite con los edificios de fondo
Sprite *skyColorsSprite; // Sprite con los graficos del degradado de color de fondo
Sprite *grassSprite; // Sprite para la hierba
Sprite *powerMeterSprite; // Sprite para el medidor de poder de la fase
Sprite *gameOverSprite; // Sprite para dibujar los graficos del game over
Sprite *gameOverEndSprite; // Sprite para dibujar los graficos del game over de acabar el juego
JA_Sound balloonSound; // Sonido para la explosión del globo
JA_Sound bulletSound; // Sonido para los disparos
@@ -188,10 +193,9 @@ private:
JA_Music gameMusic; // Musica de fondo
// Variables
int numPlayers; // Numero de jugadores
Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa
Uint8 ticksSpeed; // Velocidad a la que se repiten los bucles del programa
int numPlayers; // Numero de jugadores
Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa
Uint8 ticksSpeed; // Velocidad a la que se repiten los bucles del programa
Uint32 hiScore; // Puntuación máxima
bool hiScoreAchieved; // Indica si se ha superado la puntuación máxima
section_t section; // Seccion actual dentro del juego
@@ -201,7 +205,6 @@ private:
float stageBitmapPath[STAGE_COUNTER]; // Vector con los puntos Y por donde se desplaza el texto
float getReadyBitmapPath[STAGE_COUNTER]; // Vector con los puntos X por donde se desplaza el texto
Uint16 deathCounter; // Contador para la animación de muerte del jugador
Uint8 deathIndex; // Indice del vector de smartsprites que contiene el sprite del jugador
Uint8 menaceCurrent; // Nivel de amenaza actual
Uint8 menaceThreshold; // Umbral del nivel de amenaza. Si el nivel de amenaza cae por debajo del umbral, se generan más globos. Si el umbral aumenta, aumenta el numero de globos
bool timeStopped; // Indica si el tiempo está detenido
@@ -223,13 +226,17 @@ private:
int gameCompletedCounter; // Contador para el tramo final, cuando se ha completado la partida y ya no aparecen más enemigos
Uint8 difficulty; // Dificultad del juego
float difficultyScoreMultiplier; // Multiplicador de puntos en función de la dificultad
color_t difficultyColor; // Color asociado a la dificultad
struct options_t *options; // Variable con todas las variables de las opciones del programa
Uint8 onePlayerControl; // Variable para almacenar el valor de las opciones
enemyFormation_t enemyFormation[NUMBER_OF_ENEMY_FORMATIONS]; // Vector con todas las formaciones enemigas
enemyPool_t enemyPool[10]; // Variable con los diferentes conjuntos de formaciones enemigas
Uint8 lastStageReached; // Contiene el numero de la última pantalla que se ha alcanzado
demo_t demo; // Variable con todas las variables relacionadas con el modo demo
demo_t demo; // Variable con todas las variables relacionadas con el modo demo
int totalPowerToCompleteGame; // La suma del poder necesario para completar todas las fases
int cloudsSpeed; // Velocidad a la que se desplazan las nubes
int pauseCounter; // Contador para salir del menu de pausa y volver al juego
bool leavingPauseMenu; // Indica si esta saliendo del menu de pausa para volver al juego
// Actualiza el juego
void update();
@@ -399,9 +406,6 @@ private:
// Crea un SmartSprite para arrojar el item café al recibir un impacto
void throwCoffee(int x, int y);
// Crea un SmartSprite para arrojar al jugador al morir
void throwPlayer(int x, int y, Player *player);
// Actualiza los SmartSprites
void updateSmartSprites();
@@ -462,9 +466,21 @@ private:
// Agita la pantalla
void shakeScreen();
// Actualiza las variables del menu de pausa del juego
void updatePausedGame();
// Dibuja el menu de pausa del juego
void renderPausedGame();
// Bucle para el menu de pausa del juego
void runPausedGame();
// Actualiza los elementos de la pantalla de game over
void updateGameOverScreen();
// Dibuja los elementos de la pantalla de game over
void renderGameOverScreen();
// Bucle para la pantalla de game over
void runGameOverScreen();
@@ -492,6 +508,9 @@ private:
// Elimina todos los objetos contenidos en vectores
void deleteAllVectorObjects();
// Recarga las texturas
void reloadTextures();
public:
// Constructor
Game(int numPlayers, int currentStage, SDL_Renderer *renderer, Screen *screen, Asset *asset, Lang *lang, Input *input, bool demo, options_t *options);

View File

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

View File

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

View File

@@ -11,7 +11,7 @@ Intro::Intro(SDL_Renderer *renderer, Screen *screen, Asset *asset, Lang *lang)
// Reserva memoria para los objetos
eventHandler = new SDL_Event();
texture = new LTexture(renderer, asset->get("intro.png"));
texture = new Texture(renderer, asset->get("intro.png"));
text = new Text(asset->get("nokia.png"), asset->get("nokia.txt"), renderer);
// Carga los recursos
@@ -101,19 +101,19 @@ Intro::Intro(SDL_Renderer *renderer, Screen *screen, Asset *asset, Lang *lang)
// Un dia qualsevol de l'any 2000
texts.at(0)->setCaption(lang->getText(27));
texts.at(0)->setSpeed(10);
texts.at(0)->setSpeed(8);
// Tot esta tranquil a la UPV
texts.at(1)->setCaption(lang->getText(28));
texts.at(1)->setSpeed(10);
texts.at(1)->setSpeed(8);
// Fins que un desaprensiu...
texts.at(2)->setCaption(lang->getText(29));
texts.at(2)->setSpeed(15);
texts.at(2)->setSpeed(12);
// HEY! ME ANE A FERME UN CORTAET...
texts.at(3)->setCaption(lang->getText(30));
texts.at(3)->setSpeed(10);
texts.at(3)->setSpeed(8);
// UAAAAAAAAAAAAA!!!
texts.at(4)->setCaption(lang->getText(31));
@@ -121,7 +121,7 @@ Intro::Intro(SDL_Renderer *renderer, Screen *screen, Asset *asset, Lang *lang)
// Espera un moment...
texts.at(5)->setCaption(lang->getText(32));
texts.at(5)->setSpeed(20);
texts.at(5)->setSpeed(16);
// Si resulta que no tinc solt!
texts.at(6)->setCaption(lang->getText(33));
@@ -133,7 +133,7 @@ Intro::Intro(SDL_Renderer *renderer, Screen *screen, Asset *asset, Lang *lang)
// Blop... blop... blop...
texts.at(8)->setCaption(lang->getText(35));
texts.at(8)->setSpeed(20);
texts.at(8)->setSpeed(16);
for (auto text : texts)
{
@@ -190,6 +190,37 @@ void Intro::checkEventHandler()
JA_StopMusic();
section.name = PROG_SECTION_TITLE;
section.subsection = TITLE_SECTION_1;
switch (eventHandler->key.keysym.scancode)
{
case SDL_SCANCODE_F:
screen->switchVideoMode();
texture->reLoad();
break;
case SDL_SCANCODE_F1:
screen->setWindowSize(1);
texture->reLoad();
break;
case SDL_SCANCODE_F2:
screen->setWindowSize(2);
texture->reLoad();
break;
case SDL_SCANCODE_F3:
screen->setWindowSize(3);
texture->reLoad();
break;
case SDL_SCANCODE_F4:
screen->setWindowSize(4);
texture->reLoad();
break;
default:
break;
}
}
}
}

View File

@@ -1,13 +1,13 @@
#pragma once
#include <SDL2/SDL.h>
#include "asset.h"
#include "common/asset.h"
#include "common/jail_audio.h"
#include "common/screen.h"
#include "common/smartsprite.h"
#include "common/utils.h"
#include "common/writer.h"
#include "const.h"
#include "jail_audio.h"
#include "screen.h"
#include "smartsprite.h"
#include "utils.h"
#include "writer.h"
#include <vector>
#ifndef INTRO_H
@@ -17,10 +17,10 @@
class Intro
{
private:
// Objetos
// Objetos y punteros
SDL_Renderer *renderer; // El renderizador de la ventana
Screen *screen; // Objeto encargado de dibujar en pantalla
LTexture *texture; // Textura con los graficos
Texture *texture; // Textura con los graficos
SDL_Event *eventHandler; // Manejador de eventos
Asset *asset; // Objeto que gestiona todos los ficheros de recursos
Lang *lang; // Objeto para gestionar los textos en diferentes idiomas

View File

@@ -2,7 +2,7 @@
#include "item.h"
// Constructor
Item::Item(Uint8 kind, float x, float y, LTexture *texture, std::vector<std::string> *animation, SDL_Renderer *renderer)
Item::Item(Uint8 kind, float x, float y, Texture *texture, std::vector<std::string> *animation, SDL_Renderer *renderer)
{
sprite = new AnimatedSprite(texture, renderer, "", animation);

View File

@@ -1,8 +1,8 @@
#pragma once
#include <SDL2/SDL.h>
#include "animatedsprite.h"
#include "utils.h"
#include "common/animatedsprite.h"
#include "common/utils.h"
#ifndef ITEM_H
#define ITEM_H
@@ -19,7 +19,7 @@
class Item
{
private:
// Objetos
// Objetos y punteros
AnimatedSprite *sprite; // Sprite con los graficos del objeto
// Variables
@@ -45,7 +45,7 @@ public:
Uint16 timeToLive; // Temporizador con el tiempo que el objeto está presente
// Constructor
Item(Uint8 kind, float x, float y, LTexture *texture, std::vector<std::string> *animation, SDL_Renderer *renderer);
Item(Uint8 kind, float x, float y, Texture *texture, std::vector<std::string> *animation, SDL_Renderer *renderer);
// Destructor
~Item();

View File

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

View File

@@ -1,7 +1,7 @@
#pragma once
#include <SDL2/SDL.h>
#include "asset.h"
#include "common/asset.h"
#include <string>
#ifndef LANG_H

View File

@@ -13,7 +13,7 @@ Logo::Logo(SDL_Renderer *renderer, Screen *screen, Asset *asset)
// Reserva memoria para los punteros
eventHandler = new SDL_Event();
texture = new LTexture(renderer, asset->get("logo.png"));
texture = new Texture(renderer, asset->get("logo.png"));
sprite = new Sprite(14, 75, 226, 44, texture, renderer);
// Inicializa variables

View File

@@ -1,12 +1,12 @@
#pragma once
#include <SDL2/SDL.h>
#include "asset.h"
#include "common/asset.h"
#include "common/jail_audio.h"
#include "common/screen.h"
#include "common/sprite.h"
#include "common/utils.h"
#include "const.h"
#include "jail_audio.h"
#include "screen.h"
#include "sprite.h"
#include "utils.h"
#ifndef LOGO_H
#define LOGO_H
@@ -15,11 +15,11 @@
class Logo
{
private:
// Objetos
// Objetos y punteros
SDL_Renderer *renderer; // El renderizador de la ventana
Screen *screen; // Objeto encargado de dibujar en pantalla
Asset *asset; // Objeto que gestiona todos los ficheros de recursos
LTexture *texture; // Textura con los graficos
Texture *texture; // Textura con los graficos
SDL_Event *eventHandler; // Manejador de eventos
Sprite *sprite; // Sprite con la textura del logo

View File

@@ -2,7 +2,7 @@
#include "player.h"
// Constructor
Player::Player(float x, int y, SDL_Renderer *renderer, std::vector<LTexture *> texture, std::vector<std::vector<std::string>*> animations)
Player::Player(float x, int y, SDL_Renderer *renderer, std::vector<Texture *> texture, std::vector<std::vector<std::string> *> animations)
{
// Copia los punteros
this->renderer = renderer;
@@ -12,6 +12,8 @@ Player::Player(float x, int y, SDL_Renderer *renderer, std::vector<LTexture *> t
bodySprite = new AnimatedSprite(texture.at(1), renderer, "", animations.at(1));
legsSprite = new AnimatedSprite(texture.at(2), renderer, "", animations.at(2));
deathSprite = new AnimatedSprite(texture.at(3), renderer, "", animations.at(3));
fireSprite = new AnimatedSprite(texture.at(4), renderer, "", animations.at(4));
fireSprite->getTexture()->setAlpha(224);
// Establece la posición inicial del jugador
posX = x;
@@ -27,6 +29,7 @@ Player::~Player()
delete bodySprite;
delete legsSprite;
delete deathSprite;
delete fireSprite;
}
// Iniciador
@@ -131,7 +134,9 @@ void Player::move()
// Si el jugador abandona el area de juego por los laterales
if ((posX < PLAY_AREA_LEFT - 5) || (posX + width > PLAY_AREA_RIGHT + 5))
posX -= velX; // Restaura su posición
{ // Restaura su posición
posX -= velX;
}
// Actualiza la posición del sprite
legsSprite->setPosX(getPosX());
@@ -142,6 +147,23 @@ void Player::move()
headSprite->setPosX(getPosX());
headSprite->setPosY(posY);
fireSprite->setPosX(getPosX() - 2);
fireSprite->setPosY(posY - 8);
}
else
{
deathSprite->update();
// Si el cadaver abandona el area de juego por los laterales
if ((deathSprite->getPosX() < PLAY_AREA_LEFT) || (deathSprite->getPosX() + width > PLAY_AREA_RIGHT))
{ // Restaura su posición
const float vx = deathSprite->getVelX();
deathSprite->setPosX(deathSprite->getPosX() - vx);
// Rebota
deathSprite->setVelX(-vx);
}
}
}
@@ -154,6 +176,10 @@ void Player::render()
{
if ((invulnerableCounter % 10) > 4)
{
if (powerUp)
{
fireSprite->render();
}
legsSprite->render();
bodySprite->render();
headSprite->render();
@@ -161,11 +187,19 @@ void Player::render()
}
else
{
if (powerUp)
{
fireSprite->render();
}
legsSprite->render();
bodySprite->render();
headSprite->render();
}
}
else
{
deathSprite->render();
}
}
// Establece el estado del jugador cuando camina
@@ -186,8 +220,6 @@ void Player::setFiringStatus(Uint8 status)
if (statusFiring != status)
{
statusFiring = status;
// bodySprite->setCurrentFrame(0);
// headSprite->setCurrentFrame(0);
}
}
@@ -215,14 +247,14 @@ void Player::setAnimation()
legsSprite->setFlip(flipWalk);
if (statusFiring == PLAYER_STATUS_FIRING_NO)
{ // No esta disparando
bodySprite->setCurrentAnimation(aWalking + aBodyCoffees);
bodySprite->setCurrentAnimation(aWalking + aBodyCoffees + aPowerUp);
bodySprite->setFlip(flipWalk);
headSprite->setCurrentAnimation(aWalking + aHeadCoffees+ aPowerUp);
headSprite->setCurrentAnimation(aWalking + aHeadCoffees + aPowerUp);
headSprite->setFlip(flipWalk);
}
else
{ // Está disparando
bodySprite->setCurrentAnimation(aFiring + aBodyCoffees);
bodySprite->setCurrentAnimation(aFiring + aBodyCoffees + aPowerUp);
bodySprite->setFlip(flipFire);
headSprite->setCurrentAnimation(aFiring + aHeadCoffees + aPowerUp);
headSprite->setFlip(flipFire);
@@ -232,6 +264,9 @@ void Player::setAnimation()
legsSprite->animate();
bodySprite->animate();
headSprite->animate();
fireSprite->animate();
fireSprite->setFlip(flipWalk);
}
// Obtiene el valor de la variable
@@ -336,6 +371,18 @@ bool Player::isAlive()
void Player::setAlive(bool value)
{
alive = value;
if (!value)
{
deathSprite->setPos(headSprite->getRect());
deathSprite->setAccelY(0.2f);
deathSprite->setVelY(-6.6f);
deathSprite->setVelX(3.3f);
if (rand() % 2 == 0)
{
deathSprite->setVelX(-3.3f);
}
}
}
// Obtiene el valor de la variable
@@ -531,9 +578,10 @@ void Player::shiftColliders()
}
// Obtiene el puntero a la textura con los gráficos de la animación de morir
LTexture *Player::getDeadTexture()
Texture *Player::getDeadTexture()
{
return deathSprite->getTexture();;
return deathSprite->getTexture();
;
}
// Obtiene el valor de la variable
@@ -547,21 +595,33 @@ void Player::updatePowerUpHeadOffset()
{
if (!powerUp)
{
//powerUpHeadOffset = 0;
// powerUpHeadOffset = 0;
}
else
{
//powerUpHeadOffset = 96;
// powerUpHeadOffset = 96;
if (powerUpCounter < 300)
{
if (powerUpCounter % 10 > 4)
{
//powerUpHeadOffset = 96;
// powerUpHeadOffset = 96;
fireSprite->setEnabled(false);
}
else
{
//powerUpHeadOffset = 0;
// powerUpHeadOffset = 0;
fireSprite->setEnabled(true);
}
}
}
}
// Pone las texturas del jugador
void Player::setPlayerTextures(std::vector<Texture *> texture)
{
headSprite->setTexture(texture.at(0));
bodySprite->setTexture(texture.at(1));
legsSprite->setTexture(texture.at(2));
deathSprite->setTexture(texture.at(3));
fireSprite->setTexture(texture.at(4));
}

View File

@@ -1,11 +1,11 @@
#pragma once
#include <SDL2/SDL.h>
#include "utils.h"
#include "input.h"
#include "asset.h"
#include "ltexture.h"
#include "animatedsprite.h"
#include "common/animatedsprite.h"
#include "common/asset.h"
#include "common/input.h"
#include "common/texture.h"
#include "common/utils.h"
#ifndef PLAYER_H
#define PLAYER_H
@@ -23,24 +23,6 @@
#define PLAYER_STATUS_FIRING_RIGHT 2
#define PLAYER_STATUS_FIRING_NO 3
#define PLAYER_ANIMATION_LEGS_WALKING_LEFT 0
#define PLAYER_ANIMATION_LEGS_WALKING_RIGHT 1
#define PLAYER_ANIMATION_LEGS_WALKING_STOP 2
#define PLAYER_ANIMATION_BODY_WALKING_LEFT 0
#define PLAYER_ANIMATION_BODY_FIRING_LEFT 1
#define PLAYER_ANIMATION_BODY_WALKING_RIGHT 2
#define PLAYER_ANIMATION_BODY_FIRING_RIGHT 3
#define PLAYER_ANIMATION_BODY_WALKING_STOP 4
#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
#define PLAYER_INVULNERABLE_COUNTER 200
#define PLAYER_POWERUP_COUNTER 1500
@@ -49,12 +31,13 @@
class Player
{
private:
// Objetos
// Objetos y punteros
SDL_Renderer *renderer; // El renderizador de la ventana
AnimatedSprite *headSprite; // Sprite para dibujar la cabeza
AnimatedSprite *bodySprite; // Sprite para dibujar el cuerpo
AnimatedSprite *legsSprite; // Sprite para dibujar las piernas
AnimatedSprite *deathSprite; // Sprite para dibujar el jugador derrotado
AnimatedSprite *fireSprite; // Sprite para dibujar el aura del jugador con el poder a tope
// Variables
float posX; // Posicion en el eje X
@@ -100,7 +83,7 @@ private:
public:
// Constructor
Player(float x, int y, SDL_Renderer *renderer, std::vector<LTexture *> texture, std::vector<std::vector<std::string> *> animations);
Player(float x, int y, SDL_Renderer *renderer, std::vector<Texture *> texture, std::vector<std::vector<std::string> *> animations);
// Destructor
~Player();
@@ -114,6 +97,9 @@ public:
// Pinta el jugador en pantalla
void render();
// Pone las texturas del jugador
void setPlayerTextures(std::vector<Texture *> texture);
// Actua en consecuencia de la entrada recibida
void setInput(Uint8 input);
@@ -226,7 +212,7 @@ public:
circle_t &getCollider();
// Obtiene el puntero a la textura con los gráficos de la animación de morir
LTexture *getDeadTexture();
Texture *getDeadTexture();
// Obtiene el valor de la variable
Uint16 getDeathCounter();

View File

@@ -11,14 +11,16 @@ Title::Title(SDL_Renderer *renderer, Screen *screen, Input *input, Asset *asset,
this->options = options;
this->lang = lang;
// Reserva memoria para los punteros propios
this->section = section;
// Reserva memoria para los punteros
eventHandler = new SDL_Event();
fade = new Fade(renderer);
dustTexture = new LTexture(renderer, asset->get("title_dust.png"));
coffeeTexture = new LTexture(renderer, asset->get("title_coffee.png"));
crisisTexture = new LTexture(renderer, asset->get("title_crisis.png"));
gradientTexture = new LTexture(renderer, asset->get("title_gradient.png"));
dustTexture = new Texture(renderer, asset->get("title_dust.png"));
coffeeTexture = new Texture(renderer, asset->get("title_coffee.png"));
crisisTexture = new Texture(renderer, asset->get("title_crisis.png"));
gradientTexture = new Texture(renderer, asset->get("title_gradient.png"));
coffeeBitmap = new SmartSprite(coffeeTexture, renderer);
crisisBitmap = new SmartSprite(crisisTexture, renderer);
@@ -31,6 +33,7 @@ Title::Title(SDL_Renderer *renderer, Screen *screen, Input *input, Asset *asset,
menu.title = new Menu(renderer, asset, input, asset->get("title.men"));
menu.options = new Menu(renderer, asset, input, asset->get("options.men"));
menu.playerSelect = new Menu(renderer, asset, input, asset->get("player_select.men"));
// Sonidos
crashSound = JA_LoadSound(asset->get("title.wav").c_str());
@@ -38,8 +41,52 @@ Title::Title(SDL_Renderer *renderer, Screen *screen, Input *input, Asset *asset,
// Musicas
titleMusic = JA_LoadMusic(asset->get("title.ogg").c_str());
// Inicializa los valores
init();
}
// Destructor
Title::~Title()
{
delete eventHandler;
delete fade;
dustTexture->unload();
delete dustTexture;
coffeeTexture->unload();
delete coffeeTexture;
crisisTexture->unload();
delete crisisTexture;
gradientTexture->unload();
delete gradientTexture;
delete coffeeBitmap;
delete crisisBitmap;
delete dustBitmapL;
delete dustBitmapR;
delete gradient;
delete text1;
delete text2;
delete menu.title;
delete menu.options;
delete menu.playerSelect;
JA_DeleteSound(crashSound);
JA_DeleteMusic(titleMusic);
SDL_DestroyTexture(background);
}
// Inicializa los valores
void Title::init()
{
// Inicializa variables
this->section = section;
section.subsection = TITLE_SECTION_1;
counter = TITLE_COUNTER;
backgroundCounter = 0;
backgroundMode = rand() % 2;
@@ -50,7 +97,7 @@ Title::Title(SDL_Renderer *renderer, Screen *screen, Input *input, Asset *asset,
ticks = 0;
ticksSpeed = 15;
fade->init(0x17, 0x17, 0x26);
demo = false;
demo = true;
// Pone valores por defecto a las opciones de control
options->input.clear();
@@ -83,6 +130,7 @@ Title::Title(SDL_Renderer *renderer, Screen *screen, Input *input, Asset *asset,
}
// Inicializa el bitmap de Coffee
coffeeBitmap->init();
coffeeBitmap->setPosX(45);
coffeeBitmap->setPosY(11 - 200);
coffeeBitmap->setWidth(167);
@@ -98,6 +146,7 @@ Title::Title(SDL_Renderer *renderer, Screen *screen, Input *input, Asset *asset,
coffeeBitmap->setDestY(11);
// Inicializa el bitmap de Crisis
crisisBitmap->init();
crisisBitmap->setPosX(60);
crisisBitmap->setPosY(57 + 200);
crisisBitmap->setWidth(137);
@@ -113,6 +162,7 @@ Title::Title(SDL_Renderer *renderer, Screen *screen, Input *input, Asset *asset,
crisisBitmap->setDestY(57);
// Inicializa el bitmap de DustRight
dustBitmapR->resetAnimation();
dustBitmapR->setPosX(218);
dustBitmapR->setPosY(47);
dustBitmapR->setWidth(16);
@@ -120,6 +170,7 @@ Title::Title(SDL_Renderer *renderer, Screen *screen, Input *input, Asset *asset,
dustBitmapR->setFlip(SDL_FLIP_HORIZONTAL);
// Inicializa el bitmap de DustLeft
dustBitmapL->resetAnimation();
dustBitmapL->setPosX(33);
dustBitmapL->setPosY(47);
dustBitmapL->setWidth(16);
@@ -144,43 +195,7 @@ Title::Title(SDL_Renderer *renderer, Screen *screen, Input *input, Asset *asset,
}
// Actualiza los textos de los menus
// updateMenuLabels();
}
// Destructor
Title::~Title()
{
delete eventHandler;
delete fade;
dustTexture->unload();
delete dustTexture;
coffeeTexture->unload();
delete coffeeTexture;
crisisTexture->unload();
delete crisisTexture;
gradientTexture->unload();
delete gradientTexture;
delete coffeeBitmap;
delete crisisBitmap;
delete dustBitmapL;
delete dustBitmapR;
delete gradient;
delete text1;
delete text2;
delete menu.title;
delete menu.options;
JA_DeleteSound(crashSound);
JA_DeleteMusic(titleMusic);
SDL_DestroyTexture(background);
updateMenuLabels();
}
// Actualiza las variables del objeto
@@ -235,7 +250,7 @@ void Title::update()
dustBitmapL->update();
step++;
if (step == 33)
{
section.subsection = TITLE_SECTION_3;
@@ -246,181 +261,251 @@ void Title::update()
// Sección 3 - La pantalla de titulo con el menú y la música
case TITLE_SECTION_3:
{
// Reproduce la música
if ((JA_GetMusicState() == JA_MUSIC_INVALID) || (JA_GetMusicState() == JA_MUSIC_STOPPED))
{
JA_PlayMusic(titleMusic);
}
// Actualiza el contador de ticks
ticks = SDL_GetTicks();
dustBitmapR->update();
dustBitmapL->update();
// Actualiza la lógica del titulo
menu.active->update();
fade->update();
if (fade->hasEnded())
{
switch (postFade)
if (counter > 0)
{ // Reproduce la música
if ((JA_GetMusicState() == JA_MUSIC_INVALID) || (JA_GetMusicState() == JA_MUSIC_STOPPED))
{
case 0: // 1 PLAYER
section.name = PROG_SECTION_GAME;
section.subsection = GAME_SECTION_PLAY_1P;
JA_StopMusic();
break;
JA_PlayMusic(titleMusic);
}
case 1: // 2 PLAYERS
section.name = PROG_SECTION_GAME;
section.subsection = GAME_SECTION_PLAY_2P;
JA_StopMusic();
break;
dustBitmapR->update();
dustBitmapL->update();
case 2: // QUIT
section.name = PROG_SECTION_QUIT;
JA_StopMusic();
break;
// Actualiza la lógica del titulo
fade->update();
case 3: // TIME OUT
if (fade->hasEnded())
{
switch (postFade)
{
case 0: // 1 PLAYER
section.name = PROG_SECTION_GAME;
section.subsection = GAME_SECTION_PLAY_1P;
JA_StopMusic();
break;
case 1: // 2 PLAYERS
section.name = PROG_SECTION_GAME;
section.subsection = GAME_SECTION_PLAY_2P;
JA_StopMusic();
break;
case 2: // QUIT
section.name = PROG_SECTION_QUIT;
JA_StopMusic();
break;
case 3: // TIME OUT
counter = TITLE_COUNTER;
menu.active->reset();
if (demo)
{
runDemoGame();
if (section.name != PROG_SECTION_QUIT)
{
runInstructions(m_auto);
}
}
else
section.name = PROG_SECTION_LOGO;
break;
default:
break;
}
}
// Actualiza el tileado de fondo
updateBG();
// Comprueba las entradas para el menu
if (menuVisible == true)
{
menu.active->update();
}
// Comprueba si se ha seleccionado algún item del menú de titulo
if (menu.active->getName() == "TITLE")
{
switch (menu.active->getItemSelected())
{
case 0: // 1 PLAYER -> Cambia al manu de selección de jugador
menu.active = menu.playerSelect;
break;
case 1: // 2 PLAYERS
postFade = 1;
fade->activateFade();
break;
case 2: // OPTIONS
menu.active = menu.options;
optionsPrevious = *options;
break;
case 3: // QUIT
postFade = 2;
fade->activateFade();
break;
default:
break;
}
}
// Comprueba si se ha seleccionado algún item del menú de selección de jugador
if (menu.active->getName() == "PLAYER_SELECT")
{
switch (menu.active->getItemSelected())
{
case 0:
// Este item no se puede seleccionar y actua de titulo
break;
case 1: // BAL1
postFade = 0;
options->playerSelected = 0;
fade->activateFade();
break;
case 2: // AROUNDER
postFade = 0;
options->playerSelected = 1;
fade->activateFade();
break;
case 3: // BACK
menu.active = menu.title;
menu.playerSelect->reset();
break;
default:
break;
}
}
// Comprueba si se ha seleccionado algún item de opciones
if (menu.active->getName() == "OPTIONS")
{
switch (menu.active->getItemSelected())
{
case 0: // Difficulty
if (options->difficulty == DIFFICULTY_EASY)
options->difficulty = DIFFICULTY_NORMAL;
else if (options->difficulty == DIFFICULTY_NORMAL)
options->difficulty = DIFFICULTY_HARD;
else
options->difficulty = DIFFICULTY_EASY;
updateMenuLabels();
break;
case 1: // PLAYER 1 CONTROLS
updatePlayerInputs(0);
updateMenuLabels();
break;
case 3: // PLAYER 2 CONTROLS
updatePlayerInputs(1);
updateMenuLabels();
break;
case 5: // Language
options->language++;
if (options->language == 3)
options->language = 0;
updateMenuLabels();
break;
case 6: // Display mode
switchFullScreenModeVar();
if (options->fullScreenMode != 0)
{
menu.options->setSelectable(8, false);
menu.options->setGreyed(8, true);
}
else
{
menu.options->setSelectable(8, true);
menu.options->setGreyed(8, false);
}
updateMenuLabels();
break;
case 8: // Windows size
options->windowSize++;
if (options->windowSize == 5)
options->windowSize = 1;
updateMenuLabels();
break;
case 9: // FILTER
if (options->filter == FILTER_LINEAL)
options->filter = FILTER_NEAREST;
else
options->filter = FILTER_LINEAL;
updateMenuLabels();
break;
case 10: // VSYNC
if (options->vSync)
options->vSync = false;
else
options->vSync = true;
updateMenuLabels();
break;
case 11: // HOW TO PLAY
runInstructions(m_manual);
break;
case 12: // ACCEPT
applyOptions();
menu.active->reset();
menu.active = menu.title;
break;
case 13: // CANCEL
options = &optionsPrevious;
updateMenuLabels();
menu.active->reset();
menu.active = menu.title;
break;
default:
break;
}
}
if (menu.active->getName() == "TITLE")
{
counter--;
}
}
else if (counter == 0)
{
if (demo)
{
runDemoGame();
if (section.name != PROG_SECTION_QUIT)
{
runInstructions(m_auto);
}
init();
demo = false;
counter = TITLE_COUNTER;
menu.active->reset();
if (demo)
{
runDemoGame();
runInstructions(INSTRUCTIONS_MODE_AUTO);
}
else
section.name = PROG_SECTION_LOGO;
break;
default:
break;
}
}
// Actualiza el tileado de fondo
updateBG();
// Comprueba las entradas para el menu
if (menuVisible == true)
{
menu.active->checkInput();
}
// Comprueba si se ha seleccionado algún item del menú
if (menu.active->getName() == "TITLE")
{
switch (menu.active->getItemSelected())
else
{
case 0: // 1 PLAYER
postFade = 0;
fade->activateFade();
break;
case 1: // 2 PLAYERS
postFade = 1;
fade->activateFade();
break;
case 2: // OPTIONS
menu.active = menu.options;
optionsPrevious = *options;
break;
case 3: // QUIT
postFade = 2;
fade->activateFade();
break;
default:
break;
section.name = PROG_SECTION_LOGO;
}
}
// Comprueba si se ha seleccionado algún item de opciones
if (menu.active->getName() == "OPTIONS")
// Sección Instrucciones
if (section.subsection == TITLE_SECTION_INSTRUCTIONS)
{
switch (menu.active->getItemSelected())
{
case 0: // Difficulty
if (options->difficulty == DIFFICULTY_EASY)
options->difficulty = DIFFICULTY_NORMAL;
else if (options->difficulty == DIFFICULTY_NORMAL)
options->difficulty = DIFFICULTY_HARD;
else
options->difficulty = DIFFICULTY_EASY;
updateMenuLabels();
break;
case 1: // PLAYER 1 CONTROLS
updatePlayerInputs(0);
updateMenuLabels();
break;
case 3: // PLAYER 2 CONTROLS
updatePlayerInputs(1);
updateMenuLabels();
break;
case 5: // Language
options->language++;
if (options->language == 3)
options->language = 0;
updateMenuLabels();
break;
case 6: // Display mode
switchFullScreenModeVar();
if (options->fullScreenMode != 0)
{
menu.options->setSelectable(8, false);
menu.options->setGreyed(8, true);
}
else
{
menu.options->setSelectable(8, true);
menu.options->setGreyed(8, false);
}
updateMenuLabels();
break;
case 8: // Windows size
options->windowSize++;
if (options->windowSize == 5)
options->windowSize = 1;
updateMenuLabels();
break;
case 9: // FILTER
if (options->filter == FILTER_LINEAL)
options->filter = FILTER_NEAREST;
else
options->filter = FILTER_LINEAL;
updateMenuLabels();
break;
case 10: // VSYNC
if (options->vSync)
options->vSync = false;
else
options->vSync = true;
updateMenuLabels();
break;
case 11: // HOW TO PLAY
runInstructions(INSTRUCTIONS_MODE_MANUAL);
break;
case 12: // ACCEPT
applyOptions();
menu.active->reset();
menu.active = menu.title;
break;
case 13: // CANCEL
options = &optionsPrevious;
updateMenuLabels();
menu.active->reset();
menu.active = menu.title;
break;
default:
break;
}
}
if (menu.active->getName() == "TITLE")
{
counter--;
runInstructions(m_auto);
counter = TITLE_COUNTER;
demo = true;
}
}
@@ -569,6 +654,40 @@ void Title::checkEventHandler()
break;
}
else if (eventHandler->type == SDL_KEYDOWN && eventHandler->key.repeat == 0)
{
switch (eventHandler->key.keysym.scancode)
{
case SDL_SCANCODE_F:
screen->switchVideoMode();
reloadTextures();
break;
case SDL_SCANCODE_F1:
screen->setWindowSize(1);
reloadTextures();
break;
case SDL_SCANCODE_F2:
screen->setWindowSize(2);
reloadTextures();
break;
case SDL_SCANCODE_F3:
screen->setWindowSize(3);
reloadTextures();
break;
case SDL_SCANCODE_F4:
screen->setWindowSize(4);
reloadTextures();
break;
default:
break;
}
}
if (section.subsection == TITLE_SECTION_3)
{ // Si se pulsa alguna tecla durante la tercera sección del titulo
if ((eventHandler->type == SDL_KEYUP) || (eventHandler->type == SDL_JOYBUTTONUP))
@@ -792,6 +911,14 @@ void Title::updateMenuLabels()
// Recoloca el menu de titulo
menu.title->centerMenuOnX(SCREEN_CENTER_X);
menu.title->centerMenuElementsOnX();
// Establece las etiquetas del menu de seleccion de jugador
menu.playerSelect->setItemCaption(0, lang->getText(39)); // SELECT PLAYER
menu.playerSelect->setItemCaption(3, lang->getText(40)); // BACK
// Recoloca el menu de selección de jugador
menu.playerSelect->centerMenuOnX(SCREEN_CENTER_X);
menu.playerSelect->centerMenuElementsOnX();
}
// Aplica las opciones de menu seleccionadas
@@ -812,32 +939,29 @@ section_t Title::run()
{
update();
render();
// Sección 3 - La pantalla de titulo con el menú y la música
// Sección Instrucciones
// if (section.subsection == TITLE_SECTION_INSTRUCTIONS)
//{
// runInstructions(INSTRUCTIONS_MODE_AUTO);
//}
}
return section;
}
// Ejecuta la parte donde se muestran las instrucciones
void Title::runInstructions(Uint8 mode)
section_t Title::runInstructions(mode_e mode)
{
instructions = new Instructions(renderer, screen, asset, lang);
instructions->run(mode);
section = instructions->run(mode);
delete instructions;
return section;
}
// Ejecuta el juego en modo demo
void Title::runDemoGame()
section_t Title::runDemoGame()
{
demoGame = new Game(1, 0, renderer, screen, asset, lang, input, true, options);
demoGame->run();
section = demoGame->run();
delete demoGame;
return section;
}
// Modifica las opciones para los controles de los jugadores
@@ -906,7 +1030,7 @@ void Title::createTiledBackground()
}
// Crea los objetos para pintar en la textura de fondo
LTexture *bgTileTexture = new LTexture(renderer, asset->get("title_bg_tile.png"));
Texture *bgTileTexture = new Texture(renderer, asset->get("title_bg_tile.png"));
Sprite *tile = new Sprite({0, 0, 64, 64}, bgTileTexture, renderer);
// Prepara para dibujar sobre la textura
@@ -960,4 +1084,14 @@ void Title::checkInputDevices()
temp.deviceType = INPUT_USE_KEYBOARD;
availableInputDevices.push_back(temp);
printf("Device %i:\t%s\n\n", (int)availableInputDevices.size(), temp.name.c_str());
}
// Recarga las texturas
void Title::reloadTextures()
{
dustTexture->reLoad();
coffeeTexture->reLoad();
crisisTexture->reLoad();
gradientTexture->reLoad();
createTiledBackground();
}

View File

@@ -1,27 +1,27 @@
#pragma once
#include <SDL2/SDL.h>
#include "asset.h"
#include "common/asset.h"
#include "common/input.h"
#include "common/jail_audio.h"
#include "common/menu.h"
#include "common/movingsprite.h"
#include "common/screen.h"
#include "common/smartsprite.h"
#include "common/sprite.h"
#include "common/text.h"
#include "common/utils.h"
#include "const.h"
#include "fade.h"
#include "game.h"
#include "input.h"
#include "instructions.h"
#include "item.h"
#include "jail_audio.h"
#include "menu.h"
#include "movingsprite.h"
#include "screen.h"
#include "smartsprite.h"
#include "sprite.h"
#include "text.h"
#include "utils.h"
#ifndef TITLE_H
#define TITLE_H
// Textos
#define TEXT_COPYRIGHT "@2020,2022 JailDesigner (v2.1)"
#define TEXT_COPYRIGHT "@2020,2022 JailDesigner (v2.1b)"
// Contadores
#define TITLE_COUNTER 800
@@ -29,19 +29,19 @@
// Cantidad de eventos de la pantalla de titulo
#define TITLE_TOTAL_EVENTS 2
// Clase Title
class Title
{
private:
struct menu_t
{
Menu *title; // Menu de la pantalla de título
Menu *options; // Menú de la pantalla de opciones
Menu *active; // Menu activo (de momento para la pantalla del titulo)
bool keyPressed; // Variable para evitar la repetición de teclas en los menus
Menu *title; // Menu de la pantalla de título
Menu *options; // Menú de la pantalla de opciones
Menu *playerSelect; // Menu para elegir jugador
Menu *active; // Menu activo (de momento para la pantalla del titulo)
bool keyPressed; // Variable para evitar la repetición de teclas en los menus
};
// Objetos
// Objetos y punteros
SDL_Renderer *renderer; // El renderizador de la ventana
Screen *screen; // Objeto encargado de dibujar en pantalla
Asset *asset; // Objeto que gestiona todos los ficheros de recursos
@@ -51,10 +51,10 @@ private:
Game *demoGame; // Objeto para lanzar la demo del juego
SDL_Event *eventHandler; // Manejador de eventos
LTexture *dustTexture; // Textura con los graficos del polvo
LTexture *coffeeTexture; // Textura con los graficos de la palabra coffee
LTexture *crisisTexture; // Textura con los graficos de la plabra crisis
LTexture *gradientTexture; // Textura con los graficos para el degradado del fondo del titulo
Texture *dustTexture; // Textura con los graficos del polvo
Texture *coffeeTexture; // Textura con los graficos de la palabra coffee
Texture *crisisTexture; // Textura con los graficos de la plabra crisis
Texture *gradientTexture; // Textura con los graficos para el degradado del fondo del titulo
SDL_Rect backgroundWindow; // Ventana visible para la textura de fondo del titulo
SDL_Texture *background; // Textura dibujar el fondo del titulo
@@ -91,6 +91,9 @@ private:
std::vector<input_t> availableInputDevices; // Vector con todos los metodos de control disponibles
std::vector<int> deviceIndex; // Indice para el jugador [i] del vector de dispositivos de entrada disponibles
// Inicializa los valores
void init();
// Actualiza las variables del objeto
void update();
@@ -113,10 +116,10 @@ private:
void applyOptions();
// Ejecuta la parte donde se muestran las instrucciones
void runInstructions(Uint8 mode);
section_t runInstructions(mode_e mode);
// Ejecuta el juego en modo demo
void runDemoGame();
section_t runDemoGame();
// Modifica las opciones para los controles de los jugadores
bool updatePlayerInputs(int numPlayer);
@@ -127,6 +130,9 @@ private:
// Comprueba cuantos mandos hay conectados para gestionar el menu de opciones
void checkInputDevices();
// Recarga las texturas
void reloadTextures();
public:
// Constructor
Title(SDL_Renderer *renderer, Screen *screen, Input *input, Asset *asset, options_t *options, Lang *lang, section_t section);

View File

@@ -1,23 +0,0 @@
x los items se quedan pegados en el techo (comprobar si sigue pasando, he cambiado la coreción al chocar arriba. Si sigue fallando se quita la comprobación superior)
x la maquina de cafe no toca el suelo
x las bolas verdes nacen naranja al explotarlas
falta el aura de superguerrero al pillar la maquina de cafe
x la powerball deja la mascara al explotarlas
los menus de pausa y game over falta poner bien los textos
x cuando continuas la partida sigues muerto
poder elegir el personaje para jugar
arreglar los smart sprites de muerte y de perder el cafe
arreglar los items de las instrucciones
que cicle la musica en el titulo, demo, instrucciones
que guarde el progreso del juego
que aumente la velocidad de las nubes conforme avanzas
retocar un poco la distancia entre los cambios de color del cielo, se llega al oscuro muy pronto
x las balas deberian llegar a salir de la pantalla
x hacer desaparecer los accesos a disco en el juego. cargar todos los recursos previamente y pasarlos por punteros
x la powerball se para con el reloj y sigue rodando
x acelerar la animacion de disparar recto
x no pone la animacion corecta al no disparar con el powerup
que grite "yiiijaa!" o algo parecido al coger la maquina de cafe
o que diga DIMONIS! en un globo de texto que se evapore
podrian salir comentarios aleatoriamente o con ciertos eventos (falta ver si no estorbará)
que se vea el nivel de dificultad