简体   繁体   中英

How to load commands from txt file, python

I have a text file that follows:

Run
Jump
Jump
Swim
Run

And I have 3 methods, run, jump and swim, how do I run those functions when each of those lines gets read, so it would run "Run" first and that would run the run function then it would run the "Jump" function twice ect, ive been stuck for 2 days and thought a hint would be much appreciated, thanks! ^-^

This is what I would do:

def run():
    print('Running')
def jump():
    print('Jump')
def swim():
    print('Swim')

commands_table = {'Run':run, 'Jump':jump, 'Swim':swim}

with open('commands.txt', 'r') as command_file:
     for cmd in command_file:
         cmd = cmd.strip()
         commands_table[cmd]()

We use a dictionary to store the relationship between the commands in the text file and the functions that need to be executed.

The with statement and beyond opens the text file, reads the commands in, removes any whitespace and then executes the function by extracting it from the dictionary.

I think you should just have a dictionary that holds commands+functions:

def jump():
   player.y += 10 
    ...

commands = {"jump":jump,"Run":run,"Swim":swim}
for cmd in command_file.split("\n"):
    commands.get(cmd.strip())()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM