我正在用 AI 创建一个井字游戏,有 3 个难度级别。为了玩(或观看计算机与计算机),您必须输入一个命令,该命令将以所需的 AI 级别开始游戏。这是我的主函数代码:
def main():
while True:
command = input('Input command: ')
if command == 'start user easy':
game = Easy()
game.easy_pvc()
elif command == 'start easy easy':
game = Easy()
game.easy_cvc()
elif command == 'start easy user':
game = Easy()
game.easy_cvp()
elif command == 'start user user':
game = Grid()
game.pvp()
elif command == 'start user medium':
game = Medium()
game.medium_pvc()
elif command == 'start medium user':
game = Medium()
game.medium_cvp()
elif command == 'start medium easy':
game = Medium()
game.medium_easy_cvc()
elif command == 'start easy medium':
game = Medium()
game.easy_medium_cvc()
elif command == 'start medium medium':
game = Medium()
game.medium_cvc()
elif command == 'exit':
exit()
else:
print('Bad parameters!')
我认为这是一团糟,可以简化,但我不知道该怎么做。我要加难度,所以输入这些命令的可能性会很大,代码量很大。
答案 0 :(得分:0)
您可以使用类似模块 cmd 的东西来添加自动完成功能,例如使用函数
import cmd
class input_shell(cmd.Cmd):
def __init__(self):
super(input_shell, self).__init__()
def do_start(self, line):
#Do something
pass
def complete_start(self, text, line, start_index, end_index):
start_wordlist = ["easy", "medium", "hard"]
if text:
return [
words for words in start_wordlist
if words.startswith(text)
]
else:
return start_wordlist
if __name__ == '__main__':
shell = input_shell()
shell.cmdloop()
如果熟悉 CMD 模块,这可以提供更好的用户体验和更清晰的阅读 在此处阅读有关 cmd 模块的更多信息https://docs.python.org/3/library/cmd.html
答案 1 :(得分:0)
使用 str.split
函数将响应拆分为列表。
player_types = ["user", "easy", "medium", "hard"]
def main():
while True:
command = input('Input command: ')
command_list = command.split()
if (len(command_list) == 3 and command_list[0] == "start" # checks if the response is an appropriate length, and whether it starts with a 'start' command
and all(i in player_types for i in command_list[1:])): # checks if the response uses valid player types
game = Game()
game.start(command_list[1], command_list[2])
else:
print("Invalid command")
我假设您可以在 Game 类中实现一个函数 game.start
,该函数采用对应于玩家类型的两个字符串,并使用这些类型的玩家初始化游戏。如果游戏界面必须像您描述的那样,那么没有比您更简单的解决方案了。