248 lines
7.1 KiB
GDScript3
248 lines
7.1 KiB
GDScript3
|
|
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 end_time: int = 0
|
||
|
|
var level_game = -1
|
||
|
|
|
||
|
|
var partidas_activas: Array = []
|
||
|
|
var partidas_completadas: Array = []
|
||
|
|
var id_user = -1
|
||
|
|
|
||
|
|
### Metodo para inicar partida
|
||
|
|
func start_game(resident, level, shape_name):
|
||
|
|
var partida = {
|
||
|
|
"idUsuario": id_user,
|
||
|
|
"idResidente": resident,
|
||
|
|
"start_time": Time.get_unix_time_from_system(),
|
||
|
|
"shape": shape_name,
|
||
|
|
"nivel": level,
|
||
|
|
"fallos": 0
|
||
|
|
}
|
||
|
|
partidas_activas.append(partida)
|
||
|
|
|
||
|
|
### Metodo para finalizar partida
|
||
|
|
func end_game(shape: 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 == "Seguir la linea":
|
||
|
|
game_id = game.id
|
||
|
|
|
||
|
|
if game_id == 0:
|
||
|
|
print("No se encontro el juego en la base de datos")
|
||
|
|
|
||
|
|
for partida in partidas_activas:
|
||
|
|
if partida.shape == shape:
|
||
|
|
# Calcular cuánto tiempo ha pasado desde que se empezó la forma
|
||
|
|
var tiempo_total = now - partida["start_time"]
|
||
|
|
|
||
|
|
# Restar duración de partidas anteriores
|
||
|
|
var tiempo_previo := 0
|
||
|
|
for p in partidas_completadas:
|
||
|
|
tiempo_previo += p["duracion"]
|
||
|
|
|
||
|
|
var duracion_real = tiempo_total - tiempo_previo
|
||
|
|
duracion_real = max(duracion_real, 0) # por seguridad
|
||
|
|
|
||
|
|
var data = {
|
||
|
|
"idJuego": game_id,
|
||
|
|
"idResidente": partida["idResidente"],
|
||
|
|
"idUsuario": partida["idUsuario"],
|
||
|
|
"fallos": partida["fallos"],
|
||
|
|
"duracion": duracion_real,
|
||
|
|
"dificultad": partida["nivel"]
|
||
|
|
}
|
||
|
|
|
||
|
|
send_game_data(data)
|
||
|
|
|
||
|
|
# Guardar la duración usada en esta forma, para futuros cálculos
|
||
|
|
partida["duracion"] = duracion_real
|
||
|
|
partidas_completadas.append(partida)
|
||
|
|
partidas_activas.erase(partida)
|
||
|
|
break
|
||
|
|
|
||
|
|
|
||
|
|
func clear_active_games():
|
||
|
|
partidas_activas.clear()
|
||
|
|
|
||
|
|
func remove_active_game(name: String):
|
||
|
|
if name in partidas_activas:
|
||
|
|
partidas_activas.erase(name)
|
||
|
|
|
||
|
|
|
||
|
|
func add_failure_to_shape(shape_name: String):
|
||
|
|
for partida in partidas_activas:
|
||
|
|
if partida.shape == shape_name:
|
||
|
|
partida["fallos"] += 1
|
||
|
|
break
|
||
|
|
|
||
|
|
#-------------------------------------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)
|
||
|
|
|
||
|
|
### Metodo para parsear json de residentes y que emite una señal cuando lo tenga
|
||
|
|
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)
|
||
|
|
|
||
|
|
# Emitir la señal para notificar a quien esté conectado
|
||
|
|
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() # Liberar para evitar error 31
|
||
|
|
|
||
|
|
### Metodo que espera a la señal de que se han obtenido y parseado los residentes y los devuelve.
|
||
|
|
func get_users_loaded() -> Array:
|
||
|
|
print("Hola")
|
||
|
|
get_users()
|
||
|
|
var result = await self.users_received
|
||
|
|
return result
|
||
|
|
|
||
|
|
#--------------------------------------GET RESIDENTES-----------------------------------------------
|
||
|
|
|
||
|
|
### Metodo para hacer un get a la api de todos los 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)
|
||
|
|
|
||
|
|
### Metodo para parsear json de residentes y que emite una señal cuando lo tenga
|
||
|
|
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)
|
||
|
|
|
||
|
|
# Emitir la señal para notificar a quien esté conectado
|
||
|
|
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() # Liberar para evitar error 31
|
||
|
|
|
||
|
|
### Metodo que espera a la señal de que se han obtenido y parseado los residentes y los devuelve.
|
||
|
|
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)
|
||
|
|
|
||
|
|
### Metodo para parsear json de residentes y que emite una señal cuando lo tenga
|
||
|
|
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)
|
||
|
|
|
||
|
|
# Emitir la señal para notificar a quien esté conectado
|
||
|
|
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() # Liberar para evitar error 31
|
||
|
|
|
||
|
|
### Metodo que espera a la señal de que se han obtenido y parseado los residentes y los devuelve.
|
||
|
|
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)
|
||
|
|
|
||
|
|
|