Reputation: 63
I'm creating an app in Godot where the user inputs text in a LineEdit node. The code checks what they have typed, and responds differently depending on the words that were entered.
So far I have it working so that it recognizes the first word that was entered:
func process_command(_input: String) -> String:
var words = _input.split(" ", false)
if words.size() == 0:
return "Error: no words were parsed."
var first_word = words[0].to_lower()
match first_word:
"hello":
return hello()
"help":
return help()
_:
return "I don't understand."
func hello() -> String:
return "Hello. How are you?"
func help() -> String:
return "Press ESC for help."
However, I'd like to get it working so that it not only recognizes "hello" or "help" if they are the first words, but also recognizes those words if they are the second, third, or tenth word in a sentence. Basically, I want it to recognize a word no matter where it is in a sentence.
I've messed around with the code, but I can't seem to figure out how to go about it. It keeps coming up with errors. I'm hoping it's a simple solution. I'm very new to Godot and GDScript.
Upvotes: 1
Views: 1031
Reputation: 40305
You already have an Array
of words:
var words = _input.split(" ", false)
Let us be explicit with the type for illustration:
var words:Array = _input.split(" ", false)
Then we can check if that Array
has a value you want, something like this:
var words:Array = _input.split(" ", false)
if words.has("hello"):
print("has hello")
I notice that you convert to lower case before comparing. You can do that before splitting, as converting to lower case does not affect spaces:
var words:Array = _input.to_lower().split(" ", false)
if words.has("hello"):
print("has hello")
And we can put our checks in bool
s if that is more convenient:
var words:Array = _input.to_lower().split(" ", false)
var has_hello:bool = words.has("hello")
var has_help:bool = words.has("help")
Then you can have whatever logic you want.
I don't know what the code should do when it has both words. But you can check that:
if has_hello and has_help:
print("something happens?")
Alright, what if we have an Array
of words we want to check?
var keys:Array = ["hello", "help", "water", "platypus"]
var words:Array = _input.to_lower().split(" ", false)
We could make a dictionary!
var keys:Array = ["hello", "help", "water", "platypus"]
var words:Array = _input.to_lower().split(" ", false)
var check:Dictionary = {}
for key in keys:
check[key] = words.has(key)
And now you can check if they asking the platypus for help, or perhaps that is asking for help to find the platypus? I don't know, remember this does not preserve order. Anyway, you would check like this:
if check["help"] and check["platypus"]:
print("do-be-do-be-do-bah")
Upvotes: 1