复习:自定义列表
本课属于 Coddy GDScript 学习旅程的“面向对象编程”单元。第 34 课,共 65 课。
挑战
中等在 custom_list.gd 中编写 CustomList,这是一个封装私有数组 _items 的类,并通过方法和虚方法提供列表所需的功能:
_init(items = [])会保存items的副本,因此之后对传入数组所做的更改不会影响列表。append(item)会在末尾添加一项。pop_back()会移除并返回最后一项;如果列表为空,则返回null。get_at(index)会返回对应项;如果索引超出0到size() - 1的范围,则返回null。set_at(index, value)会替换对应项并返回true;如果索引超出列表范围,则返回false。size()、has(item)和clear()的功能与名称相同的数组方法一致。concat(other)用来代替+运算符:它会返回一个新的CustomList,其中先是此列表的各项,接着是other中的各项,并且不会更改任何一个列表。_to_string()会按数组打印内容的方式返回各项,例如[3, 1, 4]。_iter_init()、_iter_next()和_iter_get()让for循环可以遍历各项。
提供的代码会读取起始数字(单独一行,以空格分隔,也可以为空),创建列表,将 99 添加到传入的数组中,然后打印列表。接着,它会读取命令数量,并逐行执行一条命令:append N、pop、get I、set I N、has N、size、sum(对列表进行 for 循环)、clear 和 concat N N ...。对于以下输入:
3 1 4
8
append 1
get 2
get 9
set 0 5
has 4
sum
pop
concat 9 2程序会打印:
[3, 1, 4]
[3, 1, 4, 1]
Item 2: 4
No item at 9
[5, 1, 4, 1]
Has 4: true
Sum: 11
Popped 1
[5, 1, 4] + [9, 2] = [5, 1, 4, 9, 2]将你的代码写在 custom_list.gd 中。main.gd 包含提供的输入/输出代码,不能修改。
亲手试试
extends Node
func _ready():
# 提供的输入输出代码:保持原样
var numbers := to_numbers(OS.read_string_from_stdin().split(" ", false))
var list := CustomList.new(numbers)
# 列表必须保留自己的副本
numbers.append(99)
print(list)
var count := int(OS.read_string_from_stdin())
for i in count:
var parts := OS.read_string_from_stdin().split(" ", false)
match parts[0]:
"append":
list.append(int(parts[1]))
print(list)
"pop":
var item = list.pop_back()
print("Empty" if item == null else "Popped %d" % item)
"get":
var item = list.get_at(int(parts[1]))
print(("No item at " + parts[1]) if item == null else "Item %s: %d" % [parts[1], item])
"set":
if list.set_at(int(parts[1]), int(parts[2])):
print(list)
else:
print("No item at " + parts[1])
"has":
print("Has %s: %s" % [parts[1], list.has(int(parts[1]))])
"size":
print("Size: %d" % list.size())
"sum":
var total := 0
for item in list:
total += item
print("Sum: %d" % total)
"clear":
list.clear()
print(list)
"concat":
var other := CustomList.new(to_numbers(parts.slice(1)))
print("%s + %s = %s" % [list, other, list.concat(other)])
func to_numbers(words: PackedStringArray) -> Array:
var result := []
for word in words:
result.append(int(word))
return result
面向对象编程中的所有课
自己练习: GDScript 在线编译器