Menu
CoddyTech

组合对象

Coddy 面向 Dart 开发者的 GDScript 课程的第 29 课,共 48 课。

Dart 对象字段和 GDScript 对象字段可以保留共享的协作者。Dart 中的 final 会阻止重新绑定字段,但不会冻结协作者,也不会克隆协作者。其他所有者之后进行的修改仍可能可见。组合表示一种“拥有”关系,而不是必须继承。Dart 的追踪式垃圾回收与 Godot 的 RefCounted 在处理不可达的强引用循环时有所不同。

完整的 Dart 程序,适用时拆分为多个文件:

Dart 文件 note.dart:

class Note { String text="a"; }

Dart 文件 envelope.dart:

import "note.dart";
class Envelope { final Note note; Envelope(this.note); }

Dart 文件 main.dart:

import "note.dart";
import "envelope.dart";
void main() { final n=Note(),e=Envelope(n); n.text="b"; print(e.note.text); }

Dart 输出:

b

GDScript 示例文件 demo_note.gd:

class_name DemoNote
extends RefCounted
var text: String = "a"

GDScript 示例文件 demo_envelope.gd:

class_name DemoEnvelope
extends RefCounted
var note: DemoNote
func _init(value: DemoNote) -> void:
	note = value

GDScript 示例文件 main.gd:

extends Node

func _ready() -> void:
	var note: DemoNote = DemoNote.new()
	var envelope: DemoEnvelope = DemoEnvelope.new(note)
	note.text = "b"
	print(envelope.note.text)

GDScript 输出:

b
challenge icon

挑战

简单

实现 RateRule(cents:int),并提供 cost(units:int)。BillBox(rule:RateRule) 会存储传入的规则,total(units:int) 会委托该规则处理。之后更改 rule.cents 必须影响账单。solve 使用 [rate,units]。

标准输入中有一个 JSON 数组。锁定的 main 会解析它,调用公共 API,并打印 result=,后面跟着返回的文本和一个换行符。任何辅助函数都不应打印内容。输入用例之前,独立的固定探测会验证所需的 API 行为,但不会限制实现风格。

你的代码应写在 rate_rule.gd、bill_box.gd 和 exercise.gd 中。main.gd 包含提供的输入/输出代码,不能编辑。每个 class_name 类型都要放在以其名称命名的文件中。

亲手试试

extends Node

func contract_ok(data: Array) -> bool:
	var rule: RateRule = RateRule.new(2)
	var bill: BillBox = BillBox.new(rule)
	rule.cents = 7
	if rule.cost(3) != 21 or bill.total(3) != 21: return false
	return true

func _ready() -> void:
	var data: Array = JSON.parse_string(OS.read_string_from_stdin())
	if not contract_ok(data):
		print("API_CONTRACT_FAILED")
		return
	print("result=" + Exercise.solve(data))
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向 Dart 开发者的 GDScript中的所有课

自己练习: GDScript 在线编译器