OutputHandler.gd 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. # This code is borrowed from work by Joshua Moelans
  2. # https://github.com/JoshuaMoelans/Master-Thesis-Godot-exploration (accessed March 2025)
  3. # Originally developed for his master's thesis at the University of Antwerp
  4. extends Node
  5. class_name OutputHandler
  6. @export var write_buffered_game_data = false
  7. var gamesOutput = [] # list containing string output for games
  8. var gamesOutputFileNames = []
  9. # Called when the node enters the scene tree for the first time.
  10. func _ready():
  11. pass # Replace with function body.
  12. # Called every frame. 'delta' is the elapsed time since the previous frame.
  13. func _process(delta):
  14. pass
  15. func init(instance_count):
  16. for i in range(instance_count):
  17. var instance_file_name = "game_instance_" + str(i) # TODO also add timestamp identifier
  18. gamesOutputFileNames.append(instance_file_name)
  19. var file = FileAccess.open("user://logs/" + instance_file_name + ".txt", FileAccess.WRITE) # should create empty file
  20. gamesOutput.append("")
  21. # writes the given data to the given filename
  22. func write_to_file(filename, data, append=false):
  23. if not FileAccess.file_exists("user://logs/" + filename + ".txt"):
  24. var file = FileAccess.open("user://logs/" + filename + ".txt", FileAccess.WRITE) # should create empty file
  25. file.store_string(data)
  26. file.close()
  27. else:
  28. var access = FileAccess.WRITE
  29. if append:
  30. access = FileAccess.READ_WRITE
  31. var file = FileAccess.open("user://logs/" + filename + ".txt", access)
  32. if append:
  33. file.seek_end()
  34. file.store_string(data)
  35. file.close()
  36. # writes the given data to the given instance IDs file
  37. func write_to_instance_file(i:int, data:String):
  38. var instance_file_name = gamesOutputFileNames[i]
  39. var instance_file = FileAccess.open("user://logs/" + instance_file_name + ".txt", FileAccess.READ_WRITE)
  40. instance_file.seek_end()
  41. instance_file.store_string(data)
  42. instance_file.close()
  43. # writes the given data to the given instance file's buffer
  44. # gets flushed periodically to a file every 5s
  45. func write_to_instance_buffer(i:int, data):
  46. pass
  47. #gamesOutput[i] += "\n" + data
  48. # writes buffered data for each instance
  49. func write_buffered_data():
  50. for i in range(len(gamesOutputFileNames)):
  51. var data = gamesOutput[i]
  52. write_to_instance_file(i, data)
  53. gamesOutput[i] = "" # reset current instance buffer
  54. # periodically triggers a write of all buffered data
  55. func _on_write_timer_timeout():
  56. if write_buffered_game_data:
  57. write_buffered_data()