How to detect keywords in a LineEdit input

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By TobeQGamings

Bit of a beginner question here! I’m making a text adventure game where the player inputs their actions with a little LineEdit box, and I want to have the game be able to parse language a little more naturally. How can I make the engine detect when keywords are in the input rather than only picking up on the exact wording? I.e, if the player needs to speak to Jane Doe, rather than only detecting “Speak to Jane Doe” it will detect “Speak with Jane Doe,” “I want to speak to Jane Doe,” “Speak to Jane,” and so forth - it will emit a certain signal and trigger the response anytime someone types in an input with “Speak” and “Jane” in it? Thanks so much!

:bust_in_silhouette: Reply From: jgodfrey

This can get quite complex, depending on the vocabulary and sentence structure you expect to support. There might even be some useful assets to assist here, but I haven’t looked. That said, here is a very naive example I knocked up to give you some ideas…

func _ready():
	var instructions = ["speak to jane", "kill tom", "jane says hi", "please hit tom"]
	for instruction in instructions:
		var valid = is_valid_instruction(instruction)
		print("Valid? %s - %s" % [valid, instruction])
	
func is_valid_instruction(text):
	var actors = ["jane", "tom", "sarah"]
	var actions = ["speak", "take", "hit"]
	var has_actor = false
	var has_action = false
	for actor in actors:
		if actor in text.to_lower():
			has_actor = true
			break
	for action in actions:
		if action in text.to_lower():
			has_action = true
			break
	return has_actor and has_action