整合所有功能
本课属于 Coddy GDScript 学习旅程的“逻辑与流程”单元。第 30 课,共 78 课。
挑战
简单最后一步会整理循环,并处理错误的选择。保留你在前面步骤中写的所有内容。
- 将循环中的
if/elif链替换为match choice:语句,并为从"1"到"6"的每个选择设置一个模式。在模式中使用break仍会退出while循环。 - 添加通配模式
_:,用于处理其他所有选择。它会输出:
Invalid choice. Please try again.显示这条消息后,循环会像之前一样显示菜单并读取下一个选择。
亲手试试
extends Node
func _ready():
var contact_book := {}
while true:
display_menu()
var choice := OS.read_string_from_stdin()
if choice == "1":
add_contact(contact_book)
elif choice == "2":
view_contact(contact_book)
elif choice == "3":
edit_contact(contact_book)
elif choice == "4":
delete_contact(contact_book)
elif choice == "5":
list_all_contacts(contact_book)
elif choice == "6":
break
func display_menu() -> void:
print("Contact Book Menu:")
print("1. Add Contact")
print("2. View Contact")
print("3. Edit Contact")
print("4. Delete Contact")
print("5. List All Contacts")
print("6. Exit")
func add_contact(contact_book: Dictionary) -> void:
var contact_name := OS.read_string_from_stdin()
if contact_book.has(contact_name):
print("Contact already exists!")
return
var phone := OS.read_string_from_stdin()
var email := OS.read_string_from_stdin()
var address := OS.read_string_from_stdin()
contact_book[contact_name] = {"phone": phone, "email": email, "address": address}
print("Contact added successfully!")
func view_contact(contact_book: Dictionary) -> void:
var contact_name := OS.read_string_from_stdin()
if contact_book.has(contact_name):
var contact: Dictionary = contact_book[contact_name]
print("Name: ", contact_name)
print("Phone: ", contact["phone"])
print("Email: ", contact["email"])
print("Address: ", contact["address"])
else:
print("Contact not found!")
func edit_contact(contact_book: Dictionary) -> void:
var contact_name := OS.read_string_from_stdin()
if contact_book.has(contact_name):
var contact: Dictionary = contact_book[contact_name]
var phone := OS.read_string_from_stdin()
var email := OS.read_string_from_stdin()
var address := OS.read_string_from_stdin()
if phone != "":
contact["phone"] = phone
if email != "":
contact["email"] = email
if address != "":
contact["address"] = address
print("Contact updated successfully!")
else:
print("Contact not found!")
func delete_contact(contact_book: Dictionary) -> void:
var contact_name := OS.read_string_from_stdin()
if contact_book.has(contact_name):
contact_book.erase(contact_name)
print("Contact deleted successfully!")
else:
print("Contact not found!")
func list_all_contacts(contact_book: Dictionary) -> void:
if contact_book.is_empty():
print("No contacts available.")
else:
for contact_name in contact_book:
var contact: Dictionary = contact_book[contact_name]
print("Name: ", contact_name)
print("Phone: ", contact["phone"])
print("Email: ", contact["email"])
print("Address: ", contact["address"])
print()
逻辑与流程中的所有课
自己练习: GDScript 在线编译器