振り返り - コマンドパーサー
CoddyのGDScriptジャーニー「ロジックとフロー」セクションの一部。レッスン 11/78。
チャレンジ
簡単テキストアドベンチャーのコマンドパーサーを書きましょう。プログラムは、コマンドが quit になるまで、1行につき1つのコマンドを読み取ります。各行をまず整えます。両端の空白を取り除き、小文字に変換してから、空の要素を除外しつつ、空白で単語に分割します。
単語の配列に対して match を使い、各コマンドに1行で応答します。
- 単語がない場合:
Type a command. help:Commands: go, take, inventory, quitgoとDIRECTIONSに含まれる方向:You go DIRECTION.goとその他の単語:You can't go WORD.takeと、すでにinventoryにあるアイテム:You already have the ITEM.takeとその他のアイテム:inventoryに追加し、You take the ITEM.を出力します。inventory:Inventory:の後に、アイテムをカンマと空白で区切って出力するか、Inventory: emptyを出力します。quit:Goodbye!を出力し、プログラムは読み取りを停止します。- その他すべて:
Unknown command.
次の入力に対して
help
Go North
go up
take lamp
inventory
quit出力は次のとおりです。
Commands: go, take, inventory, quit
You go north.
You can't go up.
You take the lamp.
Inventory: lamp
Goodbye!自分で試してみよう
extends Node
func _ready():
const DIRECTIONS = ["north", "south", "east", "west"]
var inventory: Array[String] = []
# プレイヤーが quit と入力するまでコマンドを読み取り、応答する
ロジックとフローのすべてのレッスン
自分で練習してみよう: GDScriptオンラインコンパイラ