Menu
CoddyTech

复习:命令解析器

本课属于 Coddy GDScript 学习旅程的“逻辑与流程”单元。第 11 课,共 78 课。

challenge icon

挑战

简单

编写一个文字冒险游戏的命令解析器。程序每行读取一条命令,直到读到命令 quit。先清理每一行:去掉两端的空格,转换为小写,再按空格拆分成单词,并去掉空片段。

使用 match 匹配单词数组,每条命令输出一行:

  • 没有单词: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 在线编译器