簡體   English   中英

如何從 txt 文件加載命令,python

[英]How to load commands from txt file, python

我有一個如下的文本文件:

Run
Jump
Jump
Swim
Run

我有 3 種方法,跑步、跳躍和游泳,當每一行被讀取時,我如何運行這些函數,所以它會先運行“運行”,然后運行 function,然后運行“跳轉”function兩次等,我被困了 2 天,並認為提示將不勝感激,謝謝! ^-^

這就是我要做的:

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]()

我們使用字典來存儲文本文件中的命令與需要執行的函數之間的關系。

with 語句及其他語句打開文本文件,讀取命令,刪除任何空格,然后通過從字典中提取 function 來執行它。

我認為您應該只擁有一本包含命令+功能的字典:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM