Imagine yourself as a game developer on Godot 4. Your goal is to create a quest system. Each quest has an id, a name, a type, a description, and a condition for completion. Each quest is a resource that is loaded from a folder.
Assistant
Creating a robust quest system in Godot 4 involves several steps, including defining a Quest resource, organizing your quest assets, loading quests dynamically from a folder, and managing quest conditions and completion logic. Below is a comprehensive guide to help you implement such a system using GDScript in Godot 4.
1. Define the Quest Resource
First, you'll want to create a custom resource that represents a quest. This resource will hold all the necessary data for each quest, such as id, name, type, description, and completion_condition.
Creating the Quest Resource Script
Create a new script named Quest.gd in your project, preferably within a res://scripts/ directory.
gdscript
# res://scripts/Quest.gd
extends Resource
class_name Quest
# Define export variables for the quest properties
@export var id: String
@export var name: String
@export var type: String
@export var description: String
@export var completion_condition: String # Could be a reference to another script or a condition identifier
# Optionally, you can add signals for quest events
signal quest_completed(quest_id)
Set the resource type by ensuring the script extends Resource and uses the class_name keyword for easy instantiation.
Creating Quest Resource Files
For each quest, you'll create a .tres file (or .res if you prefer) which uses the Quest resource.
Create a folder for your quests, e.g., res://quests/.
Create individual quest resources:
Right-click on the quests folder in the FileSystem panel.
Select New Resource.
Choose Quest as the resource type.
Fill in the properties (id, name, type, description, completion_condition).
Save each quest with a unique name, e.g., FindTheSword.tres, DefeatTheDragon.tres, etc.
2. Organize Quest Assets
Ensure all your quest .tres files are organized within a specific folder, such as res://quests/. This organization allows for easy loading and management.
A QuestManager will handle loading quests, tracking active quests, and checking for completion.
Creating the QuestManager Script
Create a new script named QuestManager.gd in your scripts directory.
gdscript
# res://scripts/QuestManager.gd
extends Node
class_name QuestManager
# Dictionary to store all quests loaded, keyed by quest id
var all_quests: Dictionary = {}
# Array to store active quest ids
var active_quests: Array = []
# Array to store completed quest ids
var completed_quests: Array = []
# Signal for quest events
signal quest_added(quest_id)
signal quest_completed(quest_id)
func _ready():
load_all_quests("res://quests/")
# Function to load all quest resources from a directory
func load_all_quests(directory_path: String):
var dir := Directory.new()
if dir.open(directory_path) == OK:
dir.list_dir_begin(true, true) # skip hidden files and lowercase
while true:
var file_name := dir.get_next()
if file_name == "":
break
if file_name.ends_with(".tres") or file_name.ends_with(".res"):
var quest_resource = load(directory_path + "/" + file_name)
if quest_resource and quest_resource is Quest:
all_quests[quest_resource.id] = quest_resource
dir.list_dir_end()
else:
push_error("Failed to open quests directory: " + directory_path)
# Function to add a quest to active quests
func add_quest(quest_id: String) -> bool:
if quest_id in all_quests and not (quest_id in active_quests or quest_id in completed_quests):
active_quests.append(quest_id)
emit_signal("quest_added", quest_id)
return true
return false
# Function to mark a quest as completed
func complete_quest(quest_id: String):
if quest_id in active_quests:
active_quests.erase(quest_id)
completed_quests.append(quest_id)
emit_signal("quest_completed", quest_id)
else:
push_warning("Attempted to complete a quest that's not active: " + quest_id)
# Function to check if a quest is completed based on its condition
func check_quest_completion(quest_id: String) -> bool:
var quest = all_quests.get(quest_id)
if quest:
# Implement condition checking logic here
# For simplicity, let's assume completion_condition is a string key that we can handle
match quest.completion_condition:
"defeat_dragon":
return GlobalState.defeated_dragons >= 1
"find_sword":
return GlobalState.found_sword == true
"rescue_villager":
return GlobalState.rescued_villagers > 0
_:
push_warning("Unknown completion condition: " + quest.completion_condition)
return false
return false
# Function to update all active quests and check for completion
func update_quests():
var quests_to_complete: Array = []
for quest_id in active_quests:
if check_quest_completion(quest_id):
quests_to_complete.append(quest_id)
for quest_id in quests_to_complete:
complete_quest(quest_id)
Explanation:
all_quests: Stores all available quests loaded from the quests directory, keyed by their id.
active_quests: Holds the IDs of quests currently active for the player.
completed_quests: Holds the IDs of quests that have been completed.
load_all_quests: Loads all .tres or .res files from the specified directory and populates all_quests.
add_quest: Adds a quest to the active quests if it's not already active or completed.
complete_quest: Moves a quest from active to completed quests and emits a signal.
check_quest_completion: Checks if the quest's completion condition is met. Here, it's simplified to match strings, but you can expand this to a more robust system.
update_quests: Iterates through active quests and completes any that meet their conditions.
Integrate the QuestManager in Your Game
Add the QuestManager to the scene tree, preferably as a singleton (autoload) so that it's accessible from anywhere.
Go to Project > Project Settings > Autoload.
Add a new autoload:
Path: res://scripts/QuestManager.gd
Name: QuestManager
Click Add.
GlobalState Example: The check_quest_completion function references a hypothetical GlobalState. You need to manage global game states that quests can query to check their conditions.
gdscript
# res://scripts/GlobalState.gd
extends Node
class_name GlobalState
var defeated_dragons: int = 0
var found_sword: bool = false
var rescued_villagers: int = 0
# Singleton setup similar to QuestManager
Add GlobalState as an autoload following the same steps as QuestManager.
4. Managing Quest Conditions
The completion_condition in the Quest resource can be implemented in various ways. Here are a few approaches:
Simple String-Based Conditions
As shown in the check_quest_completion function, you can use string identifiers for conditions and handle them with a match statement or if conditions.
Using Signals for More Complex Conditions
For more dynamic quests, you can emit signals when certain events occur (e.g., defeating a boss, collecting an item) and have the QuestManager listen to these signals to update quest statuses.
Example:
Define Signals in GlobalState:
gdscript
# res://scripts/GlobalState.gd
extends Node
class_name GlobalState
signal defeated_dragon()
signal found_sword()
signal rescued_villager()
var defeated_dragons: int = 0
var found_sword: bool = false
var rescued_villagers: int = 0
func defeat_dragon():
defeated_dragons += 1
emit_signal("defeated_dragon")
func obtain_sword():
found_sword = true
emit_signal("found_sword")
func rescue_villager():
rescued_villagers += 1
emit_signal("rescued_villager")
Here's how you might add and complete quests within your game.
Adding a Quest
gdscript
# Somewhere in your game logic, e.g., when talking to an NPC
func offer_quest():
var success = QuestManager.add_quest("find_sword")
if success:
print("Quest 'Find the Sword' added!")
else:
print("Quest could not be added.")
Completing a Quest
When the player meets the condition (managed by GlobalState or other systems), the QuestManager automatically checks and completes the quest. Ensure that events such as finding a sword, defeating a dragon, etc., are properly hooked into the GlobalState methods.
gdscript
# Example: Player finds the sword
func on_player_finds_sword():
GlobalState.obtain_sword()
# QuestManager will automatically check and complete the quest if conditions are met
7. Extending the System
You can extend this basic quest system in numerous ways:
Quest Dependencies: Implement prerequisites where certain quests become available only after others are completed.
Reward System: Add rewards to quests, such as experience points, items, or currency.
Dynamic Conditions: Allow completion_condition to reference scripts or lambda functions for more complex logic.
Serialization: Save and load the state of active and completed quests using Godot's File API or ConfigFile.
Recurring/Repeatable Quests: Allow certain quests to be repeated after completion.
Example: Adding Rewards to Quest
Modify the Quest resource to include rewards.
gdscript
# res://scripts/Quest.gd
extends Resource
class_name Quest
enum QuestType { MAIN, SIDE, DAILY, REPEATABLE }
@export var id: String
@export var name: String
@export var type: QuestType
@export var description: String
@export var completion_condition: String
@export var reward_experience: int = 0
@export var reward_items: Array = []
Update the complete_quest function in QuestManager.gd to grant rewards.
gdscript
func complete_quest(quest_id: String):
if quest_id in active_quests:
active_quests.erase(quest_id)
completed_quests.append(quest_id)
var quest = all_quests.get(quest_id)
if quest:
grant_rewards(quest)
emit_signal("quest_completed", quest_id)
func grant_rewards(quest: Quest):
# Implement your reward logic here
if quest.reward_experience > 0:
PlayerStats.add_experience(quest.reward_experience)
for item in quest.reward_items:
Inventory.add_item(item)
print("Granted rewards for quest: ", quest.name)
8. Conclusion
This guide provides a foundational quest system in Godot 4 using GDScript. By defining a Quest resource, organizing quests, managing them with a QuestManager, and integrating with your game's UI and global state, you can create a flexible and scalable system for handling quests in your game. Depending on your game's complexity, you can further expand this system with additional features such as quest chains, varied objectives, dynamic storytelling, and more.
Feel free to tailor and extend this system to fit the specific needs and mechanics of your game!