Menu
CoddyTech

振り返り - コマンドパーサー

CoddyのGDScriptジャーニー「ロジックとフロー」セクションの一部。レッスン 11/78。

challenge icon

チャレンジ

簡単

テキストアドベンチャーのコマンドパーサーを書きましょう。プログラムは、コマンドが quit になるまで、1行につき1つのコマンドを読み取ります。各行をまず整えます。両端の空白を取り除き、小文字に変換してから、空の要素を除外しつつ、空白で単語に分割します。

単語の配列に対して match を使い、各コマンドに1行で応答します。

  • 単語がない場合: Type a command.
  • help: Commands: go, take, inventory, quit
  • go と 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オンラインコンパイラ