1. JSON查看与编辑(主要逻辑)
步骤1:创建Godot项目
首先,我们创建一个新的Godot项目。在项目设置中,我们选择使用GDScript作为主要编程语言。
Godot版本:4.2稳定版
步骤2:设计用户界面
我们使用Godot的UI控件来创建界面。主要包括:
– Labal用于显示文件路径
– Tree控件用于显示JSON数据
– Button用于文件选择和保存操作
步骤3:实现文件选择功能
我们创建一个FileDialog节点来处理文件选择。以下是相关代码:
func _ready(): # 连接按钮信号到相应的函数 file_button.pressed.connect(self._on_file_button_pressed) save_button.pressed.connect(self._on_save_button_pressed) # 创建并配置文件对话框 file_dialog = FileDialog.new() file_dialog.access = FileDialog.ACCESS_FILESYSTEM # 允许访问文件系统 file_dialog.file_mode = FileDialog.FILE_MODE_OPEN_FILE # 设置为打开文件模式 file_dialog.add_filter("*.json", "JSON files") # 只显示JSON文件 file_dialog.file_selected.connect(self._on_file_selected) # 连接文件选择信号 add_child(file_dialog) # 将文件对话框添加为子节点 # 配置树形视图 tree.columns = 2 # 设置为两列(键和值) tree.set_column_title(0, "Key") # 设置第一列标题 tree.set_column_title(1, "Value") # 设置第二列标题 tree.set_column_expand(0, true) # 允许第一列展开 tree.set_column_expand(1, true) # 允许第二列展开 tree.set_column_custom_minimum_width(0, 150) # 设置第一列最小宽度 tree.set_column_custom_minimum_width(1, 150) # 设置第二列最小宽度 tree.item_edited.connect(self._on_item_edited) # 连接项目编辑信号 # 当文件选择按钮被按下时调用 func _on_file_button_pressed(): file_dialog.popup_centered(Vector2(800, 600)) # 显示文件选择对话框 # 当文件被选中时调用 func _on_file_selected(path): current_file_path = path # 保存当前文件路径 file_path_label.text = path # 更新文件路径标签 load_json_file(path) # 加载选中的JSON文件
步骤4:JSON文件加载和解析
我们使用Godot的FileAccess类来读取文件,并使用JSON类来解析内容:
# 加载JSON文件 func load_json_file(path): var file = FileAccess.open(path, FileAccess.READ) # 打开文件 if not file: print("无法打开文件") return var content = file.get_as_text() # 读取文件内容 file.close() # 关闭文件 var json = JSON.new() var error = json.parse(content) # 解析JSON内容 if error == OK: json_data = json.get_data() # 获取解析后的数据 display_json_data(json_data) # 显示数据 else: print("JSON解析错误: ", json.get_error_message(), " at line ", json.get_error_line())
步骤5:在Tree控件中显示JSON数据
我们递归地遍历JSON数据,将其显示在Tree控件中:
# 在树形视图中显示JSON数据 func display_json_data(data): tree.clear() # 清除现有内容 var root = tree.create_item() # 创建根项 tree.hide_root = true # 隐藏根项 if data is Array: for i in range(data.size()): add_item(root, str(i), data[i]) # 添加数组项 elif data is Dictionary: for key in data.keys(): add_item(root, str(key), data[key]) # 添加字典项 # 向树形视图添加项目 func add_item(parent, key, value): var item = tree.create_item(parent) # 创建新项 item.set_text(0, str(key)) # 设置键 item.set_editable(0, true) # 允许编辑键 if value is Array or value is Dictionary: item.set_text(1, get_value_string(value)) # 设置值的描述 if value is Array: for i in range(value.size()): add_item(item, str(i), value[i]) # 递归添加数组项 elif value is Dictionary: for sub_key in value.keys(): add_item(item, str(sub_key), value[sub_key]) # 递归添加字典项 else: item.set_text(1, str(value)) # 设置值 item.set_editable(1, true) # 允许编辑值 # 获取值的字符串表示 func get_value_string(value): if value is Array: return "Array[" + str(value.size()) + "]" elif value is Dictionary: return "Object" else: return str(value)
步骤6:实现JSON编辑功能
我们允许用户直接在Tree控件中编辑值,并更新内部的JSON数据结构:
# 当树形视图中的项被编辑时调用 func _on_item_edited(): var edited_item = tree.get_edited() # 获取被编辑的项 var parent = edited_item.get_parent() # 获取父项 var key = edited_item.get_text(0) # 获取键 var value = edited_item.get_text(1) # 获取值 update_json_data(parent, key, value) # 更新JSON数据 # 更新JSON数据 func update_json_data(parent, key, value): var current = json_data var path = [] # 构建从根到当前项的路径 while parent and parent != tree.get_root(): path.push_front(parent.get_text(0)) parent = parent.get_parent() # 遍历路径到达正确的位置 for p in path: if current is Array: current = current[int(p)] elif current is Dictionary: current = current[p] # 更新值 if current is Array: current[int(key)] = parse_value(value) elif current is Dictionary: current[key] = parse_value(value) #确保转化的类型一一对应 func parse_value(value: String) -> Variant: if value.is_valid_int(): return value.to_int() elif value.is_valid_float(): return value.to_float() elif value.to_lower() == "true": return true elif value.to_lower() == "false": return false else: return value
步骤7:实现保存功能
最后,我们实现了将编辑后的JSON数据保存回文件的功能:
#保存逻辑 func _on_save_button_pressed(): if current_file_path.is_empty(): print("没有打开的文件") return var file = FileAccess.open(current_file_path, FileAccess.WRITE) if not file: print("无法打开文件进行写入") return var json_string = JSON.stringify(json_data, " ") file.store_string(json_string) file.close() print("文件已保存")
2. TXT到JSON的简单转换(主要逻辑)
步骤1:创建新场景
我们使用Godot的UI控件来创建界面。主要包括:
– Labal用于显示文件路径
– Button用于文件加载,输出和转化操作
步骤2:实现文件选择功能
我们为输入和输出文件分别创建一个简单窗口FileDialog,并显示输入输出路径:
func _ready(): # 连接按钮信号 input_button.pressed.connect(self._on_input_button_pressed) output_button.pressed.connect(self._on_output_button_pressed) convert_button.pressed.connect(self._on_convert_button_pressed) # 创建文件对话框 file_dialog = FileDialog.new() file_dialog.access = FileDialog.ACCESS_FILESYSTEM file_dialog.file_selected.connect(self._on_file_selected) add_child(file_dialog) #创建一个窗口来输入TXT文件 func _on_input_button_pressed(): file_dialog.file_mode = FileDialog.FILE_MODE_OPEN_FILE file_dialog.current_path = "res://" file_dialog.filters = ["*.txt ; Text files"] file_dialog.popup_centered(Vector2(800, 600)) #再次创建一个窗口来输出JSON文件 func _on_output_button_pressed(): file_dialog.file_mode = FileDialog.FILE_MODE_SAVE_FILE file_dialog.current_path = "res://" file_dialog.filters = ["*.json ; JSON files"] file_dialog.popup_centered(Vector2(800, 600)) #分别显示输入和输出的文件路径 func _on_file_selected(path): if file_dialog.file_mode == FileDialog.FILE_MODE_OPEN_FILE: input_path = path input_path_label.text = path else: output_path = path output_path_label.text = path
步骤3:实现转换功能
这是转换的核心功能,我们逐行读取TXT文件,将内容转换为JSON格式:
#文件转换的核心逻辑,将一个TXT文件内容转换为JSON文件 func _on_convert_button_pressed(): if input_path.is_empty() or output_path.is_empty(): print("请选择输入和输出文件") return # 读取输入文件 var input_file = FileAccess.open(input_path, FileAccess.READ) if not input_file: print("无法打开输入文件") return var content = input_file.get_as_text() input_file.close() # 将内容转换为JSON var json_data = [] var lines = content.split("\n") var current_user = {} for line in lines: if line.strip_edges().is_empty(): continue var parts = line.split(":", false, 1) if parts.size() == 2: var key = parts[0].strip_edges().to_lower() var value = parts[1].strip_edges() match key: "用户": if not current_user.is_empty(): json_data.append(current_user) current_user = {"用户名": value} "年龄": current_user["年龄"] = value.to_int() "职业": current_user["职业"] = value "爱好": current_user["爱好"] = value.split(",") # 添加最后一个用户 if not current_user.is_empty(): json_data.append(current_user) # 将JSON数据写入输出文件 var output_file = FileAccess.open(output_path, FileAccess.WRITE) if not output_file: print("无法创建输出文件") return output_file.store_string(JSON.stringify(json_data, " ")) output_file.close() print("转换完成")
——此内容由Claude3.5生成并加以修改完成
结语:第一次尝试用Claude3.5编写Godot程序和编写博客文章,总的来讲还是挺满意的,虽然有时候出现乱讲,乱改的毛病,但给他说明错误后还是能立即改正(主要是能改对),只要你耐心不断试错,还是能得到点效果
程序源码:首页文件下载页面Godot专栏
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END
暂无评论内容