Code Refactoring: Part 2

Hopefully final refactoring, offloaded ui scripts to its own global .gd to prevent repetition.
This commit is contained in:
Patrick_Pluto 2024-06-19 18:27:40 +02:00
parent 1f13b9d7b2
commit 6b2159b840
10 changed files with 182 additions and 187 deletions

View file

@ -20,6 +20,7 @@ config/icon="res://icon.svg"
Load="*res://scripts/load.gd"
Save="*res://scripts/save.gd"
Content="*res://scripts/content.gd"
Ui="*res://scripts/ui.gd"
[display]

View file

@ -37,12 +37,20 @@ text = "Creator"
[node name="Label" type="Label" parent="."]
layout_mode = 0
offset_left = 488.0
offset_left = 456.0
offset_top = 432.0
offset_right = 592.0
offset_right = 571.0
offset_bottom = 455.0
scale = Vector2(3, 3)
text = "Version: 0.0.4"
text = "Milestone 1 b5"
[node name="Label2" type="Label" parent="."]
layout_mode = 0
offset_left = 544.0
offset_right = 629.0
offset_bottom = 23.0
scale = Vector2(3, 3)
text = "FreeTTRPG"
[connection signal="pressed" from="Button" to="." method="_on_button_pressed"]
[connection signal="pressed" from="Button2" to="." method="_on_button_2_pressed"]

View file

@ -6,7 +6,7 @@ var loadPath
# Variable to store the loaded JSON data
var data
# Called when the node is added to the scene
# Currently placeholder function, to be deprecated once custom content loading is enabled.
func _ready():
loadPath = "res://content/stats.json" # Set the path to load JSON data from
data = Load.loadJSON(loadPath) # Load JSON data from the specified path
loadPath = "res://content/stats.json"
data = Load.loadJSON(loadPath)

View file

@ -1,42 +1,31 @@
extends Node
# Reference to the inputOutput.tscn scene
var field = preload("res://scenes/menu/inputOutput.tscn")
# Variable to store loaded JSON data
var data
var amount
# Called when the node is added to the scene
# Get all needed things for Ui.placeFields and save amount from it.
func _ready():
# Load JSON data from stats.json
data = Load.loadJSON("res://content/stats.json")
# Instantiate input fields based on 'amount' from data
for i in range(int(data.get("amount"))):
var fieldInstance = field.instance()
$"ScrollContainer/VBoxContainer".add_child(fieldInstance)
# Set position, placeholder text, and minimum size for each field
$"ScrollContainer/VBoxContainer".get_child(i).position = Vector2(16, (16 + i * 88))
$"ScrollContainer/VBoxContainer".get_child(i).placeholder_text = data.get(str(i))
$"ScrollContainer/VBoxContainer".get_child(i).custom_minimum_size.y = 40
data = Content.data
var container = $"ScrollContainer/VBoxContainer"
Ui.placeFields(data, container, true)
amount = data.get("amount")
# Handler for when a button is pressed
# Upon pressing the "Send" button
func _on_button_pressed():
# Construct save path based on user input
var savePath = "user://player_data" + $"ScrollContainer/VBoxContainer".get_child(0).text + ".json"
# Prepare data to save
var saveData = {}
for i in range(int(data.get("amount"))):
if i > 0:
saveData[data.get(str(i))] = $"ScrollContainer/VBoxContainer".get_child(i).text
# Save data to JSON file
Save.saveJSON(savePath, saveData)
# Create the save path based on which ID was entered
var savePath = "user://player_" + $"ScrollContainer/VBoxContainer".get_child(0).text + ".json"
# Get data from the fields to save, except the first one, which is the ID and should be used in the filename.
var saveData = {}
for i in range(int(data.get("amount"))):
if i > 0:
saveData[data.get(str(i))] = $"ScrollContainer/VBoxContainer".get_child(i).text
# Call the global save function
Save.saveJSON(savePath, saveData)
# Process function called every frame
# Only for the Main Menu "shortcut"
func _process(delta):
# Check if the Escape key is pressed to change scene to main.tscn
if Input.is_action_pressed("escape"):
get_tree().change_scene_to_file("res://scenes/menu/main.tscn")
if Input.is_action_pressed("escape"):
get_tree().change_scene_to_file("res://scenes/menu/main.tscn")

View file

@ -1,53 +1,37 @@
extends Node
# Reference to the inputOutput.tscn scene
var field = preload("res://scenes/menu/inputOutput.tscn")
# Variables to store data and amount
# Variable to store loaded JSON data
var data
var amount
# Called when the node is added to the scene
# Get all needed things for Ui.placeFields and save amount from it.
func _ready():
# Get data from Content singleton
data = Content.data
# Instantiate input fields based on 'amount' from data
for i in range(int(data.get("amount"))):
var fieldInstance = field.instance()
$"ScrollContainer/VBoxContainer".add_child(fieldInstance)
# Set placeholder text and minimum size for each field
$"ScrollContainer/VBoxContainer".get_child(i).placeholder_text = data.get(str(i))
$"ScrollContainer/VBoxContainer".get_child(i).custom_minimum_size.y = 40
# Make fields editable except the first one
if i > 0:
$"ScrollContainer/VBoxContainer".get_child(i).editable = false
amount = data.get("amount") # Store the amount of fields
data = Content.data
var container = $"ScrollContainer/VBoxContainer"
Ui.placeFields(data, container, false)
amount = data.get("amount")
# Handler for when a button is pressed
# Upon pressing the "Get" button, also called in game
func _on_button_pressed():
# Construct save path based on user input
var savePath = "user://player_data" + $"ScrollContainer/VBoxContainer".get_child(0).text + ".json"
# Load JSON data from the constructed save path
data = Load.loadJSON(savePath)
# Check if data is successfully loaded (type 27 corresponds to Dictionary in Godot)
if typeof(data) == 27:
# Populate fields with loaded data
for i in range(int(amount) - 1):
$"ScrollContainer/VBoxContainer".get_child(i + 1).text = data.get(str($"ScrollContainer/VBoxContainer".get_child(i + 1).placeholder_text))
# Construct save path based on user input
var savePath = "user://player_" + $"ScrollContainer/VBoxContainer".get_child(0).text + ".json"
# Load JSON data from the constructed save path
data = Load.loadJSON(savePath)
# Check if data is successfully loaded (type 27 corresponds to Dictionary in Godot, although the wiki says it's 18...)
if typeof(data) == 27:
# Populate fields with loaded data
for i in range(int(amount) - 1):
$"ScrollContainer/VBoxContainer".get_child(i + 1).text = data.get(str($"ScrollContainer/VBoxContainer".get_child(i + 1).placeholder_text))
# Process function called every frame
# Only for the Main Menu "shortcut"
func _process(_delta):
# Check if the Escape key is pressed to change scene to main.tscn
if Input.is_action_pressed("escape"):
get_tree().change_scene_to_file("res://scenes/menu/main.tscn")
# Check if the Escape key is pressed to change scene to main.tscn
if Input.is_action_pressed("escape"):
get_tree().change_scene_to_file("res://scenes/menu/main.tscn")
# Function to hide the 'get' button
func hideGet():
$button.visible = false
$button.disabled = true
$button.visible = false
$button.disabled = true

View file

@ -1,30 +1,26 @@
extends Node
# Function to load JSON data from a file
func loadJSON(savePath):
var data # Variable to store loaded data
# Check if the file exists
if not FileAccess.file_exists(savePath):
return 1 # Return error code 1 if file does not exist
# Open the file for reading
var fileAccess = FileAccess.open(savePath, FileAccess.READ)
# Read the entire JSON string from the file
var jsonString = fileAccess.get_line()
fileAccess.close() # Close the file
# Create a new JSON instance
var json = JSON.new()
# Parse the JSON string into a JSON object
var error = json.parse(jsonString)
if error:
return 1 # Return error code 1 if there was an error parsing JSON
data = json.data # Extract data from the parsed JSON
return data # Return the loaded data
func loadJSON(savePath):
# Check if the file exists
if not FileAccess.file_exists(savePath):
return 1 # Return error code 1 if file does not exist
# Open the file for reading
var fileAccess = FileAccess.open(savePath, FileAccess.READ)
# Read the entire JSON string from the file
var jsonString = fileAccess.get_line()
fileAccess.close() # Close the file
# Create a new JSON instance
var json = JSON.new()
# Parse the JSON string into a JSON object
var error = json.parse(jsonString)
if error:
return 1 # Return error code 1 if there was an error parsing JSON
return json.data # Return the loaded data

View file

@ -7,50 +7,52 @@ var playerIndex = 0
# Variable to hold the current player's object name
var objectName
# Called when the node is added to the scene
# Kick the game off
func _ready():
# Hide character viewer GUI initially
$"../characterViewer".hideGet()
# Start cycling through players
next()
# Hide character viewer GUI initially
$"../characterViewer".hideGet()
# Start cycling through players
next()
# Function to switch to the next player
func next():
if playerIndex >= playerAmount:
playerIndex = 0
# Construct object name based on player index
objectName = "player%d" % playerIndex
print(objectName) # Print current player's object name (for debugging)
# Start the current player's activity
get_node(objectName).start()
playerIndex += 1 # Move to the next player index
if playerIndex >= playerAmount:
playerIndex = 0
# Construct object name based on player index
objectName = "player%d" % playerIndex
print(objectName) # Print current player's object name (for debugging)
# Start the current player's activity
get_node(objectName).start()
playerIndex += 1 # Move to the next player index
# Function to display statistics
# Function to display statistics, lots of relative links, may change eventually
func stats():
visible = false # Hide current node (assuming this node should hide itself)
$"../characterViewer".visible = true # Show character viewer GUI
get_node(objectName).stop() # Stop current player's activity
$"../back".disabled = false # Enable back button
$"../back".visible = true # Make back button visible
# Update player index display in character viewer
$"../characterViewer/ScrollContainer/VBoxContainer".get_child(0).text = str(playerIndex - 1)
$"../characterViewer/ScrollContainer/VBoxContainer".get_child(0).editable = false
# Simulate button press in character viewer (assuming this triggers further actions)
$"../characterViewer"._on_button_pressed()
visible = false # Hide game area
$"../characterViewer".visible = true
get_node(objectName).stop()
# Activate back button
$"../back".disabled = false
$"../back".visible = true
# Update player index display in character viewer
$"../characterViewer/ScrollContainer/VBoxContainer".get_child(0).text = str(playerIndex - 1)
$"../characterViewer/ScrollContainer/VBoxContainer".get_child(0).editable = false
# Simulate button press in character viewer (assuming this triggers further actions)
$"../characterViewer"._on_button_pressed()
# Function to restart the node's state
func restart():
visible = true # Show current node
$"../characterViewer".visible = false # Hide character viewer GUI
get_node(objectName).start() # Start current player's activity
$"../back".disabled = true # Disable back button
$"../back".visible = false # Hide back button
visible = true # Show game area
$"../characterViewer".visible = false
get_node(objectName).start()
# Activate back button
$"../back".disabled = true
$"../back".visible = false
# Handler for when the back button is pressed
func _on_back_pressed():
restart() # Restart the node's state
restart() # Gives control back to the current player character

View file

@ -1,16 +1,13 @@
extends Node
# Function called when button 1 is pressed
# Function called when "Play" is pressed
func _on_button_pressed():
get_tree().change_scene_to_file("res://scenes/map/map.tscn")
# Change the scene to the map scene ("map.tscn")
get_tree().change_scene_to_file("res://scenes/map/map.tscn")
# Function called when button 2 is pressed
# Function called when "View" is pressed
func _on_button_2_pressed():
get_tree().change_scene_to_file("res://scenes/menu/view.tscn")
# Change the scene to the view menu scene ("view.tscn")
get_tree().change_scene_to_file("res://scenes/menu/view.tscn")
# Function called when button 3 is pressed
# Function called when "Create" is pressed
func _on_button_3_pressed():
get_tree().change_scene_to_file("res://scenes/menu/create.tscn")
# Change the scene to the create menu scene ("create.tscn")
get_tree().change_scene_to_file("res://scenes/menu/create.tscn")

View file

@ -1,58 +1,55 @@
extends CharacterBody2D
# Exported variable for movement speed
@export var speed = 200
# Distance traveled accumulator
var distanceTo = 0
# Flag to indicate if the character is active
# Flag to indicate if the character is currently the active player.
var active = false
# Function to handle user input
func get_input():
# Change scene if Escape key is pressed
if Input.is_action_pressed("escape"):
get_tree().change_scene_to_file("res://scenes/menu/main.tscn")
# Get directional input and set velocity accordingly
var input_direction = Input.get_vector("left", "right", "up", "down")
velocity = input_direction * speed
# Main Menu "shortcut"
if Input.is_action_pressed("escape"):
get_tree().change_scene_to_file("res://scenes/menu/main.tscn")
# Get directional input and set velocity accordingly
var input_direction = Input.get_vector("left", "right", "up", "down")
velocity = input_direction * speed
# Physics process function called every frame
func _physics_process(delta):
# Store current position for distance calculation
var toCalculate = position
# Process input if the character is active
if active:
get_input()
move_and_slide(velocity) # Move the character based on current velocity
# Accumulate distance traveled
distanceTo += position.distance_to(toCalculate)
print(distanceTo) # Print distance traveled (for debugging)
# Store current position for distance calculation
var toCalculate = position
# Process input if the character is active
if active:
get_input()
move_and_slide()
# Accumulate distance traveled
distanceTo += position.distance_to(toCalculate)
# Check if distance threshold is exceeded and the character is active
if distanceTo > 500 and active:
stop() # Stop character movement and reset distance traveled
distanceTo = 0
get_parent().next() # Trigger next action in parent node
# Check if distance threshold is exceeded and the character is active
if distanceTo > 500 and active:
stop()
distanceTo = 0
get_parent().next() # Go to the next player
# Function to start the character's activity
# Set main character as active
func start():
$camera.enabled = true # Enable camera
active = true # Set character to active state
$stats.disabled = false # Enable stats UI node
$stats.visible = true # Make stats UI node visible
$camera.enabled = true
active = true
$stats.disabled = false
$stats.visible = true
# Function to stop the character's activity
# Set main character as inactive
func stop():
$camera.enabled = false # Disable camera
active = false # Set character to inactive state
$stats.disabled = true # Disable stats UI node
$stats.visible = false # Hide stats UI node
$camera.enabled = false
active = false
$stats.disabled = true
$stats.visible = false
# Handler for when the stats button is pressed
func _on_stats_pressed():
get_parent().stats() # Call stats function in the parent node
get_parent().stats() # Open up the stats menu for the current player

21
scripts/ui.gd Normal file
View file

@ -0,0 +1,21 @@
extends Node
# Loading the stat field
var field = preload("res://scenes/menu/inputOutput.tscn")
# Creating all necessary stat fields
func placeFields(data, container, isWriteable):
# Load which stats should be displayed
# Create the fields one-by-one
for i in range(int(data.get("amount"))):
var fieldInstance = field.instantiate()
container.add_child(fieldInstance)
# Changes their placeholder based on what should be entered or seen in that field
container.get_child(i).placeholder_text = data.get(str(i))
container.get_child(i).custom_minimum_size.y = 40
# Every field except ID (if not isWriteable)
if i > 0 and !isWriteable:
container.get_child(i).editable = false