trijoco
trijoco

Reputation: 31

How to match a string to an element in a list/array - python

I'm trying to make a text adventure game, and my current approach involves lists/arrays that have valid commands:

#action verbs
act_verb = ['take', 'pick up', 'remove', 'shift', 'position', 'reposition', 'lift', 'kick', 'move']
#fight verbs
fight_verb = ['hit', 'kill', 'wack', 'dismember', 'destroy', 'obliterate']
#movement verbs
mov_verb = ['move', 'crawl', 'go', 'travel', 'walk', 'slither', 'go to', 'go to the', 'run']
#just-in-case adjectives
jic_adj = ['adjective']
#room nouns (ie directions, doors)
room_noun = ['north', 'n', 'south', 's', 'west', 'w', 'east', 'e', 'up', 'u', 'down', 'd']
#thing/object nouns
thing_noun = ['sword', 'troll', 'rug', 'door']

What I would like to do is be able to match two of those strings when a command is input, in a vein similar to this (but working, obviously):

command = raw_input('>')
if command == act_verb + thing_noun
    print "output"

I've tried regular expressions, but can't seem to make them work, as I am not sure what the second argument required would be:

matchaverb = re.match(act_verb, )
matchtnoun = re.match(thing_noun, )

If anyone could provide some guidance or advice on how to continue, it would be greatly appreciated.

Upvotes: 0

Views: 205

Answers (2)

Andrew_Lvov
Andrew_Lvov

Reputation: 4668

It would be easier if your tokens would be without spaces, e.g. 'pick_up', 'go_to'. Then you can split the input this way:

tokens = command.split()
# get actions from command tokens:
actions = set(act_verbs) & set(tokens)
# process actions
if 'take' in actions:
   ....

Upvotes: 0

jnd
jnd

Reputation: 754

You would need to split on whitespace (command.split() without an argument does this) and then get the two commands. Then you can check:

if firstWord in act_verb and secondWord in thing_noun

Upvotes: 1

Related Questions