探索迷宫(使用python 2.7)

时间:2012-04-04 12:59:15

标签: python

除了一步之外,我已完成了我的家庭作业。

我是以不同的方式做到的,但它给了某种正确答案。 无论如何,我必须探索一个maz,所以我一路走来,完全正确,除了这个任务的部分(Q COMMAND)。

我需要使用字符串方法.upper()

2.2.6顶级界面 interact()是定义基于文本的用户界面的顶级函数 如引言中所述。 请注意,当用户退出或时 找到完成方格后,交互功能应退出。

def interact():
    mazefile = raw_input('Maze File: ')
    maze = load_maze(mazefile)
    position = (1, 1)
    poshis = [position]

    while True:
        #print poshis, len(poshis)
        print 'You are at position', position
        command = raw_input('Command: ')
        #print command

        if command == '?':
            print HELP
        elif command == 'N' or command == 'E' or command == 'S'or command == 'W':
            mov = move(maze, position, command)
            if mov[0] == False: #invalid direction
                print "You can't go in that direction" 
            elif mov[1] == True:#finished
                print 'Congratulations - you made it!'
                break
            else: #can move, but not finished
                position = mov[2]
                poshis.append(position) 

        elif command == 'R': # reseting the maze to the first pos
            position = (1, 1)
            poshis = [position]
        elif command == 'B': # back one move
            if len(poshis) > 1:
                poshis.pop()
                position = poshis[-1]

        elif command == 'L': # listing all possible leg dir
            toggle = 0
            result = ''
            leg_list = get_legal_directions(maze, poshis[-1])
            for Legal in leg_list:
                if toggle:
                    result += ', '
                    result += Legal
                else:
                    result += Legal
                if not toggle:
                    toggle = 1
            print result

        elif command == 'Q': #quiting 
            m = raw_input('Are you sure you want to quit? [y] or n: ')
            if m == 'y':
                break

            #print 'Are you sure you want to quit? [y] or n: '
            #if raw_input == 'y':
              #  break

        else: #invalid input
            print 'Invalid Command:', command

1 个答案:

答案 0 :(得分:0)

你的问题不是特别清楚,但我猜测'问题'是如果用户在被问及是否确定要退出时回答“Y”而不是“y”,那么循环将继续。

如果这是问题,你应该只更换一行:

if m == 'y':
    break

使用:

if m.upper() == 'Y':
    break

因为无论用户输入“y”还是“Y”,循环仍然会被打破。