1

这是我的代码

direction = 0

while direction != ("quit"):
    direction = input("> ")
    if direction[0:4] != "quit" and direction != "go north" and direction != "go south" and direction != "go east" and direction != "go west" and direction != "go up" and direction != "go down" and direction[0:4] != "look":
        if direction[0:2] == "go" and direction[3:] == (""):
            print("please tell me more")
        else:
            print("huh?")

    elif direction[0:1] == "go" and direction != "north" and direction != "south" and direction != "east" and direction != "west" and direction != "up" and direction != "down":
        print ("please tell me more")

    elif direction[0:4] == "quit":
        print ("OK ... but a small part of you may never leave until you have personally saved Muirfieland from the clutches of evil .. Bwahahahahahah (sinister laugh).")

    elif direction[0:4] == "look":
        print ("You see nothing but endless void stretching off in all directions ...")

    else:
        print ("You wander of in the direction of " + direction)

如果第一个单词被识别但第二个单词没有被识别,我试图将其添加到我的代码中,它会响应:“对不起,我害怕我不能这样做”我只是在我的代码中遇到了麻烦,任何帮助都会不胜感激谢谢。

4

4 回答 4

2

如此快速的分析......您正在制作文本解析器,其工作方式如下:

  • 获取“命令”的第一个单词,如果我们不知道单词用户使用了无效输入 -> 通知并重新启动
  • 如果用户使用了已知的“命令”,则解析其参数(如:、、)并让“嵌套”函数处理参数go northgo south

请注意,“主要解析函数”不需要知道参数go()是否有效,它只是将验证责任委托给go().

所以我认为你应该像这样构建代码(类)

class Game:

    # Initialize internal variables, method automatically called on g = Game()
    def __init__(self):
        self._exit = False

        # Array of known commands, used in run, basically maps commands
            # to function and it says: if will get 'go' execute self._go
        self._commands = {
            'go': self._go,
            'quit': self._quit
        }

        # Array of go sub commands, used by _go
        self._commands_go = {
            'north': self._go_north
            # ...
        }

    # Mathod for parsing command, if it gets "comamnd" returns ("command",None)
    # if "command arg1 arg2" returns ("command", "arg1 arg2")
    @staticmethod
    def parse_command(string):
        string = str(string)
        index = string.find(' ')
        if index < 0:
            return (string, None)

        return (string[:index], string[index+1:])

    # This is main method; the only one which should be called from outside
    # It will just read data from input in never ending loop and parse commands
    def run(self):
        while not self._exit:
            src = input('> ')
            (command,args) = Game.parse_command( src)

            # Do we have this command, execute it
            if command in self._commands:
                self._commands[command](args)
            else:
                print( 'I\'m sorry I don\'t known command {}, try one of these:'.format(command))
                print( '\n'.join( self._commands.keys()))

    #######################################################
    # All game commands go here
    #######################################################
    def _quit(self,args):
        self._exit = True
        print( 'Bye bye')

    # Movement handling, will get executed when user types 'go ...' nad '...' will be in arg
    def _go(self,args):
        # No argument
        if args is None:
            print( 'Go excepts one of these:', '; '.join( self._commands_go.keys()))
            return False

        # Split sub command anr arguments
        (command,args) = Game.parse_command(args)
        if command not in self._commands_go:
            print( 'Go excepts one of these:', '; '.join( self._commands_go.keys()))
            return False

        if args is not None:
            print( 'Too many arguments for go')
            return False

        self._commands_go[command](args)
        return True

    # Go north
    def _go_north(self, args):
        print( 'Going north')


game = Game()
game.run()

这将允许您:

  • 构建复杂的嵌套命令
  • 构建漂亮且可读的命令层次结构(inventory item 123 update use potion 345)而不是难读的复杂条件集
  • 构建函数别名go north可以gn通过添加'gn': self._go_north_commands
  • 构建可重用的参数解析(item_id, action, args) = self._parse_item_action(args)
  • 利用面向对象编程的优势(没有全局变量,一切都将是类属性,降低意外变量覆盖的风险)

如果你需要解析goasdfgo你可以简单地:

for i in self._commands:
    if input.startswirh( i):
        return self._commands[i](...)
print('Invalid command')
return False

注意:我没有测试过代码,这只是我的想法。

于 2013-04-14T12:19:47.293 回答
0

您的代码对我来说看起来很混乱,这只是您的代码的一个更简单的版本:

flag = 0
count = 0

direction = 0

while direction != ("quit"):
    direction = input("> ")
    count += 1
    if recognised and count == 1: # word is recognised
       flag = 1
       print "whatever you want..."
    elif (not recognised) and count == 2 and flag == 1:
       flag = 0
       print "sorry, im afraid i cant do that"
    else:
       flag = 1
       print "second is recognised or whatever you want..."

在我的代码中,如果第一次猜测被识别并增加计数,我已经设置了一个标志。第二次猜测,我只是检查标志和计数的值。

于 2013-04-14T12:21:49.593 回答
0

与您的代码不是很相关,但是,当您可以获取用户输入时,将其拆分为一个列表并比较第一个单词,然后比较第二个单词,因此可能类似于

    user = user_input("> ")
    user = user.split()

    if user[0] == "look"
        if user[1] == "left"
            do something
        if user[1] == "right"
            do something
        else
            print ("sorry, im afraid i cant do that") 

不知道这是否是你要找的东西

于 2013-04-14T12:23:24.397 回答
0

简单地说,我认为你需要学习更多的代码来让你自己在这里变得更容易,尽管类可能有点多,我并不是以一种侮辱的方式。

作为一个简单的开始,我建议使用 in 关键字而不是 ==。

例如:

if "north" in direction:
    do something

如果输入是北、北、向北、请向北等,这将“做某事”。

因此,为了解决您的问题,您的代码可以使用如下内容:

input = ("> ")
if "go" in input and not ("north" in input and "south" in input...):
    print "That is not a direction you can go in."

等等。“而不是(...)”部分可以重写得更整洁,但我按原样写它是为了更容易地显示正在发生的事情。

truthcase = None
directions = ["north", "south", ...]

for i in directions:
     if i not in input:
         continue
     else:
         truthcase = True
     truthcase = False 

if "go" in input and not truthcase:
    print something

希望这会有所帮助。

于 2013-04-14T16:29:26.553 回答