連絡先を編集
CoddyのGDScriptジャーニー「ロジックとフロー」セクションの一部。レッスン 27/78。
チャレンジ
簡単選択肢 3 を処理して、連絡先を編集します。前の手順で書いたものはすべて残してください。
edit_contact(contact_book: Dictionary) を書きます。この関数は名前を読み取ります。
- 名前が
contact_bookにない場合は、Contact not found!を出力し、それ以外は何も読み取りません。 - それ以外の場合は、新しい電話番号、新しいメールアドレス、新しい住所の順に3行を読み取ります。空行は「keep the current value」を意味します。空でないフィールドを更新し、その後
Contact updated successfully!を出力します。
たとえば、連絡先帳に Alice がいて、選択肢 3 の後の入力が次のとおりの場合:
Alice
987-654-3210
456 Elm StAlice の電話番号は 987-654-3210、住所は 456 Elm St になり、メールアドレスはそのままです。
ループ内に、"3" に対して edit_contact(contact_book) を呼び出す elif 分岐を追加します。
自分で試してみよう
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 == "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!")
ロジックとフローのすべてのレッスン
自分で練習してみよう: GDScriptオンラインコンパイラ