func is_quest_inside(quest: CogitoQuest) -> bool:
return quest in quests
func get_quest_from_id(id: int) -> CogitoQuest:
for quest in quests:
if quest.id == id:
return quest
return null
func get_ids_from_quests() -> Array[int]:
var ids: Array[int] = []
for quest in quests:
ids.append(quest.id)
return ids
func clear_group():
quests.clear()
Assistant
Your GDScript code defines a class called CogitoQuestGroup, which manages a collection of quests. This class is useful for grouping and organizing quests in a game or application. Below is a brief overview of the methods and their functions:
Class: CogitoQuestGroup
Variables:
quests: An array that holds instances of CogitoQuest.
Methods:
_init(pool_name: String):
Constructor that initializes the CogitoQuestGroup with a specific name.
add_quest(quest: CogitoQuest) -> CogitoQuest:
Adds a CogitoQuest instance to the quests array and returns it.
Asserts that the quest is not null to ensure validity.
remove_quest(quest: CogitoQuest) -> CogitoQuest:
Removes a specified CogitoQuest from the quests array and returns it.
Asserts that the quest is not null to ensure validity.
is_quest_inside(quest: CogitoQuest) -> bool:
Checks if the given CogitoQuest is present in the quests array and returns a boolean value.
get_quest_from_id(id: int) -> CogitoQuest:
Searches for a CogitoQuest by its id and returns the corresponding quest if found; otherwise returns null.
get_ids_from_quests() -> Array[int]:
Collects and returns an array of ids for all quests in the quests array.
clear_group():
Clears the quests array, removing all quests from the group.
Considerations:
Error Handling: The current implementation uses assertions. Consider handling errors gracefully if a quest isn't found or if an operation fails.
Quest Class: Ensure that the CogitoQuest class has an id property as it is used in several methods.
Performance: If quest management scales, consider the efficiency of searching for quests by id and other operations.
Documentation: Adding comments or documentation strings to the methods would improve code readability and maintainability.
Overall, the CogitoQuestGroup class is well-structured for managing groups of quests. If you have specific questions or need enhancements, feel free to ask!
func update_quest(quest_id: int) -> void:
var quest: CogitoQuest = get_quest_from_id(quest_id)
code
quest.update()
Assistant
Your implementation of the ActiveQuestsGroup class, which extends CogitoQuestGroup, allows for managing and updating quests within that group. Below, I'll review your code and suggest improvements and potential extensions.
Class: ActiveQuestsGroup
Inherits from: CogitoQuestGroup, allowing it to use all its methods and properties.
Method: update_quest(quest_id: int) -> void
This method aims to update a quest given its ID.
It retrieves the CogitoQuest associated with the quest_id using the inherited method get_quest_from_id().
Once the quest is retrieved, it calls the update() method on the quest.
Suggested Improvements:
Null Check: It's essential to check if the quest was found before calling update(). If the quest is not found, calling an update on null will result in an error. Here’s how you could add that check:
gd
func update_quest(quest_id: int) -> void:
var quest: CogitoQuest = get_quest_from_id(quest_id)
if quest:
quest.update()
else:
print("Quest with ID", quest_id, "not found.")
Error Handling: Instead of just printing an error message, you might want to consider how you would like to handle the failure to find a quest. This might involve logging, triggering an event, or managing game state.
User Feedback: Depending on your application, it might be beneficial to provide feedback to the user if they attempt to update a non-existent quest, especially in a game or UI context.
Extending Functionality: If you foresee needing additional functionality related to active quests (such as marking them as complete, failed, or tracking their states), you might consider adding those capabilities directly in this class or another class that manages game state.
Final Code with Improvements
Here’s the updated version of your ActiveQuestsGroup class with the suggested improvements:
gdscript
User
extends Node
signal quest_activated(quest: CogitoQuest) #Emitted when a quest gets added to the active quests group
signal quest_updated(quest: CogitoQuest) #Emitted when a quests gets updated (used for the quest counter)
signal quest_completed(quest: CogitoQuest) #Emitted when a quest gets completed / moved to the completed quests group.
signal quest_failed(quest: CogitoQuest) #Emitted when a quest gets moved to the failed quests group.
var available: AvailableQuests = AvailableQuests.new("Available")
var active: ActiveQuests = ActiveQuests.new("Active")
var completed: CompletedQuests = CompletedQuests.new("Completed")
var failed: FailedQuests = FailedQuests.new("Failed")
var quest_audio_volume_db : float = -9
Assistant
Your provided code sets up a quest management system using various quest groups in Godot. It includes signals to handle events related to quest activation, updating, completion, and failure while initializing the respective quest groups. Here's an overview and some suggestions for enhancements.
Overview of the Code
Signals:
You have defined several signals (quest_activated, quest_updated, quest_completed, quest_failed). These will allow you to notify other parts of your game or application when certain quest events occur.
Quest Groups:
You preload four quest groups: AvailableQuests, ActiveQuests, CompletedQuests, and FailedQuests. Since you are calling new() on them, these likely inherit from CogitoQuestGroup or a similar structure.
Audio References:
You have preloaded audio files for specific quest-related events (completion, failure, and starting a quest). This allows for immediate access at runtime without loading them each time.
Variables:
The variables available, active, completed, and failed are instances of the preloaded quest groups.
The volume for quest audio is set to -9 dB, which can be adjusted based on your audio mixing preferences.
Suggested Enhancements
Initialization in _ready():
Consider moving the initialization of your quest groups to the _ready() function, which is the standard place for setting up your nodes in Godot.
gdscript
func _ready():
available = AvailableQuests.new("Available")
active = ActiveQuests.new("Active")
completed = CompletedQuests.new("Completed")
failed = FailedQuests.new("Failed")
Connecting Signals:
You could connect the signals to methods that will handle these events. For example, you may want to play audio when a quest is completed or just log a message.
Your code snippet defines methods for managing quests in your game, specifically focusing on starting and completing quests. Below is a more detailed overview, some potential improvements, and best practices for your QuestManager class.
Overview of Methods
_init():
This method initializes the quest manager by adding the quest groups to the current node. You ensure that all necessary quest groups (available, active, completed, and failed) are part of the scene tree.
start_quest(quest: CogitoQuest) -> CogitoQuest:
This method is responsible for starting a quest. It first checks to ensure that the quest is not already active, completed, or failed.
If the quest is valid to start, it moves it from the available group to the active group, activates the quest, and emits a signal indicating that a quest has been activated.
It also plays an audio clip indicating that a quest has started.
This method is meant to complete a quest. It checks if the quest is currently active and whether it has already been marked as completed.
If the conditions are met, it marks the quest as complete, removes it from the active group, and adds it to the completed group. Then, it emits a signal indicating that the quest is completed and plays the appropriate audio.
Suggested Improvements
Null Checks for quest:
In both the start_quest and complete_quest methods, it is good practice to assert that the quest is not null. You can also consider adding specific checks or logging if quest isn't valid.
gdscript
assert(quest != null, "Attempted to start/complete a null quest.")
Quest Status Validation:
The complete_quest method checks if quest.quest_completed is false before proceeding. Consider renaming or making sure that the condition logically corresponds to whether the quest can be marked as completed. You might want to clarify the logic here.
User
Moves a quest to the completed group. Quest needs to be active to be completed.
func fail_quest(quest: CogitoQuest) -> CogitoQuest:
if not active.is_quest_inside(quest):
return quest
Gets a quest that's neither in the active, completed or failed groups
func is_quest_available(quest: CogitoQuest) -> bool:
if not (active.is_quest_inside(quest) or completed.is_quest_inside(quest) or failed.is_quest_inside(quest)):
return true
return false
Checks if a quest is currently in the active group.
Your additional code provides essential functionality for managing the state and completion of quests in your game. Below is an overview of each method you've implemented, along with suggestions for improvement and enhancements where necessary.
Overview of Methods
fail_quest(quest: CogitoQuest) -> CogitoQuest:
This method moves a quest from the active group to the failed group. It checks if the quest is currently active, marks it as failed, removes it from the active group, adds it to the failed group, and emits a signal indicating that the quest has failed. It also plays failure audio.
This method changes the current value of a quest's counter. It checks if the quest is active, applies the value change, emits an updated signal, checks if the counter goal is reached, and, if so, completes the quest.
get_available_quests() -> Array[CogitoQuest]:
Returns an array of quests currently in the available group.
get_active_quests() -> Array[CogitoQuest]:
Returns an array of quests currently in the active group.
get_completed_quests() -> Array[CogitoQuest]:
Returns an array of quests currently in the completed group.
get_failed_quests() -> Array[CogitoQuest]:
Returns an array of quests currently in the failed group.
is_quest_available(quest: CogitoQuest) -> bool:
Checks if a quest is neither in the active, completed, nor failed groups and returns a boolean based on that check.
is_quest_active(quest: CogitoQuest) -> bool:
Checks if a quest is currently in the active group and returns a boolean value.
Suggested Improvements
Null Checks for quest:
Similar to your previous functions, it is good practice to assert that each quest parameter is not null at the beginning of methods that require it. This prevents potential runtime errors.
User
Checks if a quest is currently in the completed group.
Checks if a quest is in a given group. Given group name string needs to match child node name (as added in _ready)
func is_quest_in_group(quest: CogitoQuest, group_name: String) -> bool:
if group_name.is_empty():
for group in get_children():
if group.is_quest_inside(quest): return true
return false
code
var group := get_node(group_name)
if group.is_quest_inside(quest): return true
return false
# Find the quest if present
for pools in get_children():
if pools.get_quest_from_id(quest_id) != null:
quest = pools.get_quest_from_id(quest_id)
break
# Make sure we've got the quest
if quest == null: return
if quest.has_method(method):
quest.callv(method, args)
Assistant
Your additional methods for managing quests are a solid extension to the system. They provide functionality to check if a quest is completed, if it belongs to a specified group, and invoke methods on a quest by its ID. Below is a detailed overview of each method and some suggestions for improvements.
Overview of Methods
is_quest_completed(quest: CogitoQuest) -> bool:
This method checks whether a specified quest is in the completed group and returns a boolean value.
# Find the quest
for groups in get_children():
if groups.get_quest_from_id(quest_id) != null:
quest = groups.get_quest_from_id(quest_id)
if quest == null: return
# Now check if the quest has the property
# First if the property is null -> we return
if property == null: return
var was_property_found: bool = false
# Then we check if the property is present
for p in quest.get_property_list():
if p.name == property:
was_property_found = true
break
# Return if the property was not found
if not was_property_found: return
# Finally we set the value
quest.set(property, value)
var old_group_instance: CogitoQuestGroup = get_node_or_null(old_group)
var new_group_instance: CogitoQuestGroup = get_node_or_null(new_group)
assert(old_group_instance != null or new_group_instance != null)
old_group_instance.quests.erase(quest)
new_group_instance.quests.append(quest)
return quest
Assistant
Your newly provided methods for managing quest properties and moving quests between groups enhance the capabilities of the quest management system. Let's break down each method, review the functionality, and provide suggestions for improvements.
This method moves a quest from one group to another specified group.
It checks if the old and new group names are different and ensures both groups are valid before performing the move.
Suggested Improvements
Null Checks for quest:
In set_quest_property, ensure that you assert that the quest is not null after attempting to find it. This helps catch any issues if the quest is not found.
gdscript
if quest == null:
CogitoGlobals.debug_log(true, "QuestManager.gd", "Quest with ID " + str(quest_id) + " not found.")
return
Property Name Check:
Instead of checking if property is null, you might want to check if it is an empty string as well to keep it consistent.
gdscript
if property.is_empty():
return
Consolidate Property Check:
You can streamline the property existence check by using has_method or get_property_list more effectively without a separate loop:
gdscript
if not quest.has_method("set") or !quest.has_property(property):
return
Error Logging:
User
Clears a group. Given group name string needs to match child node name (as added in _ready)
func reset_group(group_name: String) -> void:
if group_name.is_empty():
for group in get_children():
group.reset()
return
code
var group := get_node(group_name)
group.clear_group()
return
Extra QuestManager methods that are currently not really needed.
#for group in get_children():
#quest_dict[group.name.to_lower()] = group.get_ids_from_quests()
code
#return quest_dict
#func dict_to_quests(dict: Dictionary, quests: Array[CogitoQuest]) -> void:
#for group in get_children():
code
## Make sure to iterate only for available pools
#if !dict.has(group.name.to_lower()): continue
code
## Match quest with their ids and insert them into the quest pool
#var quest_with_id: Dictionary = {}
#var group_ids: Array[int]
#group_ids.append_array(dict[group.name.to_lower()])
#for quest in quests:
#if quest.id in group_ids:
#group.add_quest(quest)
#quests.erase(quest)
Your new method reset_group provides functionality to reset a specific quest group in your quest management system. Additionally, you have commented-out methods for manipulating quest data structures. Let’s summarize the functionality of the provided methods, provide best practices, and suggest improvements.
Overview of Methods
reset_group(group_name: String) -> void:
This method clears a specified quest group. If the group_name is empty, it resets all groups by calling reset() on each.
It retrieves the group node by name and calls clear_group() on it.
Suggested Improvements for reset_group
Null Check for Group:
Before calling clear_group() on the found group, it is good practice to check if group is null, as it may fail if the specified group does not exist.
gdscript
var group := get_node(group_name)
if group == null:
CogitoGlobals.debug_log(true, "QuestManager.gd", "Group " + group_name + " not found.")
return
Error Logging:
If reset() or clear_group() implementations have side effects, consider logging messages for confirmation or issues to improve usability.
Streamlined Logic:
You can tighten the logic in your resets. If you plan to expand functionality, consider implementing a more robust “reset” method that reflects the different states (active, completed, etc.) for each group.
Commented-Out Methods
The extra methods are not currently in use but suggest interesting functionality. Here are brief descriptions and suggestions for them:
quests_as_dict() -> Dictionary:
Converts the ID of quests in each group into a dictionary form. This could enhance the overview of quests in a user-readable format. Make sure to ensure that the dictionary collects quests smartly, perhaps by filtering in a way that excludes any quest that might not be relevant (like non-active quests).
gdscript
User
extends Node3D
@onready var neutral_position : Vector3 = global_position
Define the axis the object will rotate.
@export var hover_amplitude: Vector3 = Vector3(0,.5,0)
Time it takes to reach the return position.
@export var hover_speed : float = 1
Activates/deactivates hover tweens.
@export var is_hovering : bool
var hover_tween : Tween
Called when the node enters the scene tree for the first time.
Your provided code snippet defines a simple hovering behavior for a 3D object in Godot using GDScript. The script sets up a hover_tween that moves the object along a specified amplitude, creating an illusion of hovering. Below, I’ll walk through the code, point out any potential improvements, and suggest ways you might enhance or extend the functionality.
Overview of the Code
Variables:
neutral_position: Captures the initial position of the object when it enters the scene.
hover_amplitude: This defines how far above and below the neutral position the object will hover.
hover_speed: This sets how quickly the object will reach the hovering positions.
is_hovering: A flag that can be used to toggle hovering (though it isn't utilized in your current code).
hover_tween: An instance of a Tween, which manages the animation for the hovering effect.
_ready() Function:
This method initializes the hover_tween, setting up a tween that will make the object oscillate vertically within the defined amplitude at the specified speed.
It performs two tween operations: one to move to the top position and the other to move to the bottom position, using a cubic transition.
Suggested Improvements and Enhancements
Enable/Disable Hovering:
Your is_hovering variable is defined but not utilized. You may want to add logic to enable or disable hovering based on this flag.
gdscript
func _ready() -> void:
if is_hovering:
_start_hovering()
And create a new function _start_hovering() to encapsulate the hovering logic:
func _set_interactable(value) -> void:
_interactable = value
if _interactable == null:
interactable_unseen.emit()
else:
interactable_seen.emit(_interactable)
func _update_interactable() -> void:
if !is_colliding():
return
var collider = get_collider(0)
code
# Handle freed objects.
# is_instance_valid() will be false for null and for freed objects, but only
# null will return 0 for typeof()
if not is_instance_valid(_interactable):
if typeof(_interactable) != 0:
_interactable = null
return
# Handle all colliders that aren't in the interactable group as null.
if collider != null and not collider.is_in_group("interactable"):
collider = null
if collider == _interactable:
return
# HACK: Turns out a null from the collider is/can be an object.
# This changes it to an actual null, so the freed object handling
# won't trigger on it.
if collider == null and typeof(collider) != 0:
collider = null
_interactable = collider
Assistant
Your InteractionShapeCast class builds upon Godot's ShapeCast3D to detect and interact with objects in the 3D environment. This class emits signals when an interactable object is seen or unseen, providing a way to manage interactions more easily in-game. Let's break down the functionality and then look at potential improvements and extensions.
Overview of the Code
Signals:
interactable_seen(interactable): Emitted when an interactable object comes into range.
interactable_unseen(): Emitted when the interactable object is no longer detectable.
Variable:
_interactable: Holds a reference to the currently interactable object. It's actively managed by using a setter function _set_interactable().
Methods:
_ready(): Placeholder function called when the object enters the scene. Currently does not contain any logic.
_process(_delta: float): Calls the _update_interactable() method every frame to check for changes in the interactable.
_set_interactable(value): This is the setter for the _interactable variable. It emits the appropriate signal depending on whether an interactable has been assigned or removed.
_update_interactable(): This method checks for collisions and updates the _interactable variable as necessary. It verifies whether the collider is valid and checks if it's part of the "interactable" group.
Suggested Improvements and Enhancements
Variable Naming:
Consider using descriptive names for variables and functions to maintain clarity. Instead of _interactable, you could use _current_interactable. This helps differentiate it from the type of object it holds.
Improve Null Checks:
In _update_interactable(), streamline your null and validity checks. Godot provides useful methods, such as is_instance_valid(), which can simplify checks against freed instances.
gdscript
Not yet included in a published release.
extends CogitoQuestGroup
class_name ActiveQuestsGroup
func update_quest(quest_id: int) -> void:
var quest: CogitoQuest = get_quest_from_id(quest_id)
if quest:
quest.update()
else:
print("Quest with ID", quest_id, "not found.")
Conclusion
The ActiveQuestsGroup class seems to be a solid addition to your quest management system. By adding checks to ensure reliability, you can improve the robustness of your code while maintaining clarity. If you have any other features or functionalities in mind that you wish to implement, feel free to ask!
gdscript
func _ready():
available = AvailableQuests.new("Available")
active = ActiveQuests.new("Active")
completed = CompletedQuests.new("Completed")
failed = FailedQuests.new("Failed")
# Connect signals from active quests
active.connect("quest_completed", self, "_on_quest_completed")
active.connect("quest_failed", self, "_on_quest_failed")
func _on_quest_completed(quest: CogitoQuest):
print("Quest completed:", quest.name)
# Play completion audio
AudioStreamPlayer.play(COGITO_QUEST_COMPLETE)
func _on_quest_failed(quest: CogitoQuest):
print("Quest failed:", quest.name)
# Play failed audio
AudioStreamPlayer.play(COGITO_QUEST_FAILED)
Managing Audio:
Ensure you have an AudioStreamPlayer node in your scene to play the audio clips.
Dynamic Volume Control:
You might want to implement a method to adjust the volume dynamically if your game has options for audio settings. For example:
gdscript
func set_audio_volume(volume_db: float):
quest_audio_volume_db = volume_db
# Assuming you have an AudioStreamPlayer for quest audio
audio_player.volume_db = quest_audio_volume_db
Handling Quest Activations:
You might also want to handle activations inside your available quest group to notify the system when a quest is started.
Final Notes
Your setup provides a solid foundation for a quest management system in Godot. It handles various states of quests and provides a way to respond to events through signals. With the above enhancements and considerations, you can increase the robustness and usability of your system. If you have specific features in mind or need assistance with particular functionality, feel free to ask!
Decoupling Audio Logic:
Instead of directly manipulating audio playback in your quest management methods, consider creating a separate method or a class to handle audio playback. This promotes separation of concerns.
Utilizing CogitoGlobals.debug_log is a good practice for debugging. Ensure to include relevant details in your logs, and consider toggling debug logging based on a global debug flag for ease in production builds.
Return Type Consistency:
Ensure that all your functions have consistent return types. The complete_quest method has a condition where it may return the quest even when the completion isn't executed. You might want to clarify the return type or the conditions for successfully completing a quest.
Final Code Example with Improvements
Here's how the QuestManager might look with some of the improvements mentioned:
gdscript
extends Node
signal quest_activated(quest: CogitoQuest)
signal quest_updated(quest: CogitoQuest)
signal quest_completed(quest: CogitoQuest)
signal quest_failed(quest: CogitoQuest)
const AvailableQuests = preload("./QuestGroups/available_quests_group.gd")
const ActiveQuests = preload("./QuestGroups/active_quests_group.gd")
const CompletedQuests = preload("./QuestGroups/completed_quests_group.gd")
const FailedQuests = preload("./QuestGroups/failed_quests_group.gd")
const COGITO_QUEST_COMPLETE = preload("../Assets/Audio/Phazorknight/Cogito_QuestComplete.wav")
const COGITO_QUEST_FAILED = preload("../Assets/Audio/Phazorknight/Cogito_QuestFailed.wav")
const COGITO_QUEST_START = preload("../Assets/Audio/Phazorknight/Cogito_QuestStart.wav")
var quest_audio_volume_db : float = -9
var available: AvailableQuests
var active: ActiveQuests
var completed: CompletedQuests
var failed: FailedQuests
func _init() -> void:
available = AvailableQuests.new("Available")
active = ActiveQuests.new("Active")
completed = CompletedQuests.new("Completed")
failed = FailedQuests.new("Failed")
add_child(available)
add_child(active)
add_child(completed)
add_child(failed)
func start_quest(quest: CogitoQuest) -> CogitoQuest:
assert(quest != null, "Attempted to start a null quest.")
if active.is_quest_inside(quest):
CogitoGlobals.debug_log(true, "QuestManager.gd", quest.quest_name + " is already active.")
return quest
if completed.is_quest_inside(quest):
CogitoGlobals.debug_log(true, "QuestManager.gd", quest.quest_name + " is already completed.")
return quest
if failed.is_quest_inside(quest):
CogitoGlobals.debug_log(true, "QuestManager.gd", quest.quest_name + " was already failed.")
return quest
available.remove_quest(quest)
active.add_quest(quest)
quest_activated.emit(quest)
quest.start()
play_quest_audio("start") # separated audio logic
CogitoGlobals.debug_log(true, "QuestManager.gd", "Quest " + quest.quest_name + " has been started.")
return quest
func complete_quest(quest: CogitoQuest) -> CogitoQuest:
assert(quest != null, "Attempted to complete a null quest.")
if not active.is_quest_inside(quest):
CogitoGlobals.debug_log(true, "QuestManager.gd", quest.quest_name + " is not currently active.")
return quest
if quest.quest_completed:
CogitoGlobals.debug_log(true, "QuestManager.gd", quest.quest_name + " has already been completed.")
return quest
quest.complete()
active.remove_quest(quest)
completed.add_quest(quest)
quest_completed.emit(quest)
play_quest_audio("complete") # separated audio logic
return quest
Conclusion
The changes enhance the robustness, readability, and maintainability of your quest management code. By incorporating checks and separating logic into clear, single-purpose methods, you can ensure a more organized codebase. If you have further questions or need help with additional features, feel free to ask!
gdscript
assert(quest != null, "Attempted to fail/change/complete a null quest.")
Logging and Feedback:
Adding debug logs can help with tracing issues, especially in fail_quest and change_quest_counter. Logging what happens during these changes can be invaluable.
You can simplify the boolean checks for the is_quest_available and is_quest_active methods:
gdscript
func is_quest_available(quest: CogitoQuest) -> bool:
return not (active.is_quest_inside(quest) or completed.is_quest_inside(quest) or failed.is_quest_inside(quest))
func is_quest_active(quest: CogitoQuest) -> bool:
return active.is_quest_inside(quest)
Handling Quest Counter Goals:
In change_quest_counter, consider introducing constraints if there are upper and lower limits to the quest counter to ensure that the counter stays valid throughout the tracking process.
Encapsulation:
For managing quests, consider creating a separate QuestManager class instance which is responsible for all quest-related signals and logic. This decouples quest management from quest logic itself and promotes cleaner design.
Final Code Example with Improvements
Here is your updated code with suggested improvements:
gdscript
## Moves a quest to the completed group. Quest needs to be active to be completed.
func fail_quest(quest: CogitoQuest) -> CogitoQuest:
assert(quest != null, "Attempted to fail a null quest.")
if not active.is_quest_inside(quest):
CogitoGlobals.debug_log(true, "QuestManager.gd", quest.quest_name + " is not in active.")
return quest
quest.failed()
active.remove_quest(quest)
failed.add_quest(quest)
quest_failed.emit(quest)
Audio.play_sound(COGITO_QUEST_FAILED).volume_db = quest_audio_volume_db
CogitoGlobals.debug_log(true, "QuestManager.gd", "Quest failed: " + quest.quest_name)
return quest
## Changes quest counter value. Quest needs to be active.
func change_quest_counter(quest: CogitoQuest, value_change: int) -> CogitoQuest:
assert(quest != null, "Attempted to change a null quest counter.")
if not active.is_quest_inside(quest):
CogitoGlobals.debug_log(true, "QuestManager.gd", quest.quest_name + " is not currently active.")
return quest
quest.quest_counter_current += value_change
quest_updated.emit(quest)
# Checks if counter goal is reached:
if quest.quest_counter_current >= quest.quest_counter_goal:
CogitoGlobals.debug_log(true, "QuestManager.gd", quest.quest_name + ": Quest goal reached!")
quest.update()
complete_quest(quest)
return quest
## Functions to get a list of quests from each group
func get_available_quests() -> Array[CogitoQuest]:
return available.quests
func get_active_quests() -> Array[CogitoQuest]:
return active.quests
func get_completed_quests() -> Array[CogitoQuest]:
return completed.quests
func get_failed_quests() -> Array[CogitoQuest]:
return failed.quests
## Gets a quest that's neither in the active, completed, or failed groups
func is_quest_available(quest: CogitoQuest) -> bool:
assert(quest != null, "Attempted to check a null quest.")
return not (active.is_quest_inside(quest) or completed.is_quest_inside(quest) or failed.is_quest_inside(quest))
## Checks if a quest is currently in the active group.
func is_quest_active(quest: CogitoQuest) -> bool:
assert(quest != null, "Attempted to check a null quest.")
return active.is_quest_inside(quest)
Conclusion
With these adjustments, your code becomes more robust and maintainable. The checks for null values ensure safety, while logging can help you trace the flow of quest state changes, which is vital for debugging and maintaining the game. If you need further modifications or have any specific questions, feel free to ask!
Validity Check for group_name:
In your is_quest_in_group method, consider validating group_name with additional checks, such as checking if the group exists.
gdscript
if not has_node(group_name):
CogitoGlobals.debug_log(true, "QuestManager.gd", "Group with name " + group_name + " does not exist.")
return false
Method Calling Safety:
In call_quest_method, ensure that the method being called is safe to invoke, especially if it might modify the quest state.
Final Code Example with Improvements
Here's your updated code with suggested improvements:
gdscript
## Checks if a quest is currently in the completed group.
func is_quest_completed(quest: CogitoQuest) -> bool:
assert(quest != null, "Attempted to check a null quest.")
return completed.is_quest_inside(quest)
## Checks if a quest is in a given group. Given group name string needs to match child node name (as added in _ready)
func is_quest_in_group(quest: CogitoQuest, group_name: String) -> bool:
assert(quest != null, "Attempted to check if a null quest is in a group.")
if group_name.is_empty():
for group in get_children():
if group.is_quest_inside(quest):
return true
return false
if not has_node(group_name):
CogitoGlobals.debug_log(true, "QuestManager.gd", "Group with name " + group_name + " does not exist.")
return false
var group := get_node(group_name)
return group.is_quest_inside(quest)
func call_quest_method(quest_id: int, method: String, args: Array) -> void:
var quest: CogitoQuest = null
# Find the quest if present
for pools in get_children():
quest = pools.get_quest_from_id(quest_id)
if quest != null:
break
# Make sure we've got the quest
if quest == null:
CogitoGlobals.debug_log(true, "QuestManager.gd", "Quest with ID " + str(quest_id) + " not found.")
return
if quest.has_method(method):
quest.callv(method, args)
else:
CogitoGlobals.debug_log(true, "QuestManager.gd", "Method " + method + " not found on quest: " + quest.quest_name)
Conclusion
These enhancements help improve the reliability and maintainability of your quest management system. By checking for null values, logging errors, and simplifying methods, you ensure that your code is easier to debug and understand. If you have any further questions or would like additional features, feel free to ask!
For better traceability, log messages after every return that indicates an operation didn’t execute as expected, like if the property was not found or if the move failed.
Assertions:
In move_quest_to_group, improve the assertion to check both groups simultaneously instead of just one.
Final Code Example with Improvements
Here's your updated code with the suggested enhancements:
gdscript
func set_quest_property(quest_id: int, property: String, value: Variant) -> void:
var quest: CogitoQuest = null
# Find the quest
for groups in get_children():
quest = groups.get_quest_from_id(quest_id)
if quest != null:
break
if quest == null:
CogitoGlobals.debug_log(true, "QuestManager.gd", "Quest with ID " + str(quest_id) + " not found.")
return
# Check if the property is an empty string
if property.is_empty():
return
# Check if the property is available
if not quest.has_property(property):
CogitoGlobals.debug_log(true, "QuestManager.gd", "Property " + property + " not found in quest: " + quest.quest_name)
return
# Finally, set the value
quest.set(property, value)
## Force moves a quest to a group.
func move_quest_to_group(quest: CogitoQuest, old_group: String, new_group: String) -> CogitoQuest:
if old_group == new_group:
return
var old_group_instance: CogitoQuestGroup = get_node_or_null(old_group)
var new_group_instance: CogitoQuestGroup = get_node_or_null(new_group)
assert(old_group_instance != null, "Old group does not exist.")
assert(new_group_instance != null, "New group does not exist.")
old_group_instance.remove_quest(quest) # Consider using defined method for removal
new_group_instance.add_quest(quest) # Consider using defined method for addition
CogitoGlobals.debug_log(true, "QuestManager.gd", "Moved quest: " + quest.quest_name + " from " + old_group + " to " + new_group)
return quest
Conclusion
By implementing these improvements, you enhance the robustness and usability of your quest management system. The focus on null checks, clearer logic, and better error handling will help ensure that your system is more maintainable and easier to debug. If you have any more features to discuss or any questions, feel free to ask!
func quests_as_dict() -> Dictionary:
var quest_dict: Dictionary = {}
for group in get_children():
quest_dict[group.name.to_lower()] = group.get_ids_from_quests()
return quest_dict
Converts a dictionary back into quest instances, reassigning them to the right groups. This may be useful for serialization or loading saved states.
gdscript
func dict_to_quests(dict: Dictionary, quests: Array[CogitoQuest]) -> void:
for group in get_children():
if !dict.has(group.name.to_lower()): continue
var group_ids: Array[int] = dict[group.name.to_lower()]
for quest in quests:
if quest.id in group_ids:
group.add_quest(quest)
quests.erase(quest)
serialize_quests(group: String) -> Dictionary:
Serializes quest data into a dictionary for saving purposes. This is quite useful for saving the game state or exporting quests for other purposes.
gdscript
func serialize_quests(group: String) -> Dictionary:
var group_node: CogitoQuestGroup = get_node_or_null(group)
if group_node == null: return {}
var quest_dictionary: Dictionary = {}
for quest in group_node.quests:
var quest_data: Dictionary = {}
for property_info in quest.get_script().get_script_property_list():
if property_info.usage & PROPERTY_USAGE_STORAGE or property_info.usage & PROPERTY_USAGE_SCRIPT_VARIABLE:
quest_data[property_info.name] = quest.get(property_info.name)
quest_data.erase("id")
quest_dictionary[quest.id] = quest_data
return quest_dictionary
Suggestions for Commented-Out Methods
Given the utility of these methods, consider implementing the following best practices:
Documentation:
Add docstrings to the commented-out methods that explain their purpose clearly, expected input, and output for better maintainability.
Testing Utility:
Before integrating these methods back into active usage, create simple unit tests to ensure they handle edge cases appropriately (e.g., empty lists, missing nodes).
Consistent Naming:
Make sure method names follow consistent naming conventions, and clarify their purpose through clear naming.
Error Handling:
Just as with the other methods, ensure that logging is consistent, especially for methods that might manipulate the state, as tracking state mutation is important in debugging.
Final Code Example for reset_group
Here’s your updated reset_group method, including suggested improvements:
gdscript
## Clears a group. Given group name string needs to match child node name (as added in _ready)
func reset_group(group_name: String) -> void:
if group_name.is_empty():
for group in get_children():
group.reset()
return
var group := get_node_or_null(group_name)
if group == null:
CogitoGlobals.debug_log(true, "QuestManager.gd", "Group " + group_name + " not found.")
return
group.clear_group()
CogitoGlobals.debug_log(true, "QuestManager.gd", "Cleared group: " + group_name)
Conclusion
Your quest management system is evolving well, with lots of useful functionality. The suggestions above aim to enhance robustness and maintainability. If you have more features you want to discuss or questions regarding implementation, feel free to ask!
Stopping the Hovering:
Implement a method to stop the hovering when needed. You can call this method when is_hovering is set to false.
gdscript
func _stop_hovering() -> void:
if hover_tween:
hover_tween.stop_all() # Stops all tweens attached to this node
Dynamic Position and Speed Changes:
Consider adding functions that allow for dynamic changes to hover_amplitude and hover_speed while the object is hovering. This would enable you to create more complex animations based on game events.
If you want to trigger the hover effect from another script or node, consider using Godot's signal system to manage interactions.
Alternative Hovering:
You might want to explore alternative methods of implementing hovering. For instance, rather than using tweens, you could calculate the position in _process() to create a more fluid, real-time effect.
Final Example of an Enhanced Hover Script
Here's how the final version of your hovering code might look after integrating some of the suggestions:
Your original code lays a solid foundation for a hover effect in a Godot 3D environment, and with just a few enhancements, it can become much more flexible and responsive to game dynamics. By implementing the suggestions above, you can improve the usability and versatility of your hovering effect. If you have further questions or need assistance with additional features, feel free to ask!
if collider == null or not is_instance_valid(collider):
collider = null
_set_interactable(null)
return
Signals Handling:
You may consider emitting a signal when a new object is detected instead of only when it changes. This can be useful in cases where multiple interactable objects are present simultaneously.
gdscript
if _interactable != collider:
_set_interactable(collider)
Documentation:
Adding comments or documentation strings explaining the purpose of methods and variables can enhance code readability and maintainability, especially when shared among developers.
Collision Filtering:
If you have specific types of interactables or want to filter based on additional criteria, consider extending the logic in _update_interactable().
Optimization:
If the interaction check does not need to run every frame, consider using Godot's built-in physics signals (like body_entered for Area3D nodes) to minimize unnecessary computations.
Final Code Example with Enhancements
Here’s an updated version with the suggested changes:
gdscript
class_name InteractionShapeCast
extends ShapeCast3D
signal interactable_seen(interactable)
signal interactable_unseen()
var current_interactable : Node3D set = _set_interactable
func _ready() -> void:
pass
func _process(_delta: float) -> void:
_update_interactable()
func _set_interactable(value: Node3D) -> void:
current_interactable = value
if current_interactable == null:
interactable_unseen.emit()
else:
interactable_seen.emit(current_interactable)
func _update_interactable() -> void:
if not is_colliding():
_set_interactable(null)
return
var collider = get_collider(0)
# Verify validity of the collider
if collider == null or not is_instance_valid(collider):
_set_interactable(null)
return
# Check if the collider is part of the "interactable" group
if not collider.is_in_group("interactable"):
_set_interactable(null)
return
# Update the interactable if it's changed
if current_interactable != collider:
_set_interactable(collider)
Conclusion
This enhanced version of your InteractionShapeCast class improves clarity, efficiency, and functionality. The suggestions aim to make your code cleaner and easier to maintain. If you have any additional features in mind or further questions about this implementation, feel free to ask!