224 lines
6.1 KiB
GDScript
224 lines
6.1 KiB
GDScript
extends Node
|
|
# Este script se encarga de comunicarse con la API
|
|
|
|
# Señales para saber cuando se recibe los datos
|
|
signal users_received(users)
|
|
signal residents_received(residents)
|
|
signal games_received(games)
|
|
|
|
var all_users = []
|
|
var all_residents = []
|
|
var all_games = []
|
|
|
|
var resident_playing = -1
|
|
var level_game = -1
|
|
var partidas_activas: Array = []
|
|
var partidas_completadas: Array = []
|
|
var id_user = -1
|
|
|
|
### Método para iniciar partida
|
|
func start_game(resident, level, ejercicio_name):
|
|
var partida = {
|
|
"idUsuario": id_user,
|
|
"idResidente": resident,
|
|
"start_time": Time.get_unix_time_from_system(),
|
|
"ejercicio": ejercicio_name,
|
|
"nivel": level
|
|
}
|
|
partidas_activas.append(partida)
|
|
|
|
### Método para finalizar partida
|
|
func end_game(ejercicio: String):
|
|
var now = Time.get_unix_time_from_system()
|
|
|
|
var games = await get_games_loaded()
|
|
var game_id = 0
|
|
for game in games:
|
|
if game.nombre == "Gimnasio":
|
|
game_id = game.id
|
|
|
|
if game_id == 0:
|
|
print("No se encontro el juego en la base de datos")
|
|
|
|
# Crea una nueva lista porque no puedes borrar mientras iteras
|
|
var partidas_a_borrar := []
|
|
|
|
for partida in partidas_activas:
|
|
if partida.ejercicio == ejercicio:
|
|
var tiempo_total = now - partida["start_time"]
|
|
|
|
# Calcular duración acumulada de ejercicios anteriores de este mismo residente
|
|
var tiempo_previo := 0
|
|
for p in partidas_completadas:
|
|
if p["idResidente"] == partida["idResidente"]:
|
|
tiempo_previo += p["duracion"]
|
|
|
|
var duracion_real = max(tiempo_total - tiempo_previo, 0)
|
|
|
|
var data = {
|
|
"idJuego": game_id,
|
|
"idResidente": partida["idResidente"],
|
|
"idUsuario": partida["idUsuario"],
|
|
"fallos": 0,
|
|
"duracion": duracion_real,
|
|
"dificultad": partida["nivel"]
|
|
}
|
|
|
|
send_game_data(data)
|
|
|
|
partida["duracion"] = duracion_real
|
|
partidas_completadas.append(partida)
|
|
partidas_a_borrar.append(partida)
|
|
|
|
# Borra después para evitar errores de iteración
|
|
for p in partidas_a_borrar:
|
|
partidas_activas.erase(p)
|
|
|
|
|
|
func clear_active_games():
|
|
partidas_activas.clear()
|
|
partidas_completadas.clear()
|
|
|
|
### Método para calcular la duración entre el inicio y el final de la partida (ya no necesario, pero mantenido)
|
|
func get_duration() -> int:
|
|
return 0 # ya no se usa esta duración global
|
|
|
|
# ------------------------ GET USERS ------------------------
|
|
|
|
func get_users():
|
|
var http_request = HTTPRequest.new()
|
|
get_tree().root.add_child(http_request)
|
|
|
|
var status = http_request.connect(
|
|
"request_completed",
|
|
Callable(self, "_on_request_get_users").bind(http_request)
|
|
)
|
|
|
|
var url = "http://localhost:8080/resi/users"
|
|
var headers = ["User-Agent: Godot"]
|
|
var error = http_request.request(url, headers)
|
|
|
|
if error != OK:
|
|
print("Error al hacer GET:", error)
|
|
|
|
func _on_request_get_users(result, response_code, headers, body, request_node):
|
|
print("Código de respuesta:", response_code)
|
|
|
|
if response_code == 200:
|
|
var response_text = body.get_string_from_utf8()
|
|
var parsed = JSON.parse_string(response_text)
|
|
|
|
if parsed != null:
|
|
all_users = parsed
|
|
print("Users obtenidos:", all_users)
|
|
emit_signal("users_received", all_users)
|
|
else:
|
|
print("Error al parsear JSON")
|
|
else:
|
|
print("Error del servidor o conexión:", response_code)
|
|
|
|
request_node.queue_free()
|
|
|
|
func get_users_loaded() -> Array:
|
|
get_users()
|
|
var result = await self.users_received
|
|
return result
|
|
|
|
# ------------------------ GET RESIDENTES ------------------------
|
|
|
|
func get_residents():
|
|
var http_request = HTTPRequest.new()
|
|
get_tree().root.add_child(http_request)
|
|
|
|
var status = http_request.connect(
|
|
"request_completed",
|
|
Callable(self, "_on_request_get_residents").bind(http_request)
|
|
)
|
|
|
|
var url = "http://localhost:8080/resi/residents"
|
|
var headers = ["User-Agent: Godot"]
|
|
var error = http_request.request(url, headers)
|
|
|
|
if error != OK:
|
|
print("Error al hacer GET:", error)
|
|
|
|
func _on_request_get_residents(result, response_code, headers, body, request_node):
|
|
print("Código de respuesta:", response_code)
|
|
|
|
if response_code == 200:
|
|
var response_text = body.get_string_from_utf8()
|
|
var parsed = JSON.parse_string(response_text)
|
|
|
|
if parsed != null:
|
|
all_residents = parsed
|
|
print("Residentes obtenidos:", all_residents)
|
|
emit_signal("residents_received", all_residents)
|
|
else:
|
|
print("Error al parsear JSON")
|
|
else:
|
|
print("Error del servidor o conexión:", response_code)
|
|
|
|
request_node.queue_free()
|
|
|
|
func get_residents_loaded() -> Array:
|
|
get_residents()
|
|
var result = await self.residents_received
|
|
return result
|
|
|
|
# ------------------------ GET JUEGOS ------------------------
|
|
|
|
func get_games():
|
|
var http_request = HTTPRequest.new()
|
|
get_tree().root.add_child(http_request)
|
|
|
|
var status = http_request.connect(
|
|
"request_completed",
|
|
Callable(self, "_on_request_get_games").bind(http_request)
|
|
)
|
|
|
|
var url = "http://localhost:8080/resi/juegos"
|
|
var headers = ["User-Agent: Godot"]
|
|
var error = http_request.request(url, headers)
|
|
|
|
if error != OK:
|
|
print("Error al hacer GET en juegos:", error)
|
|
|
|
func _on_request_get_games(result, response_code, headers, body, request_node):
|
|
print("Código de respuesta en juegos:", response_code)
|
|
|
|
if response_code == 200:
|
|
var response_text = body.get_string_from_utf8()
|
|
var parsed = JSON.parse_string(response_text)
|
|
|
|
if parsed != null:
|
|
all_games = parsed
|
|
print("Juegos obtenidos:", all_games)
|
|
emit_signal("games_received", all_games)
|
|
else:
|
|
print("Error al parsear JSON de juegos")
|
|
else:
|
|
print("Error del servidor o conexión en juegos:", response_code)
|
|
|
|
request_node.queue_free()
|
|
|
|
func get_games_loaded() -> Array:
|
|
get_games()
|
|
var result = await self.games_received
|
|
return result
|
|
|
|
# ------------------------ POST PARTIDA ------------------------
|
|
|
|
func send_game_data(data: Dictionary):
|
|
var http_request = HTTPRequest.new()
|
|
get_tree().root.add_child(http_request)
|
|
|
|
var json_body = JSON.stringify(data)
|
|
var headers = ["Content-Type: application/json"]
|
|
var url = "http://localhost:8080/resi/juegos/stats/add"
|
|
|
|
http_request.connect("request_completed", Callable(self, "_on_game_data_sent").bind(http_request))
|
|
var error = http_request.request(url, headers, HTTPClient.METHOD_POST, json_body)
|
|
|
|
if error != OK:
|
|
print("Error al enviar los datos:", error)
|