2012-04-04 32 views
0

除了一步之外,我已經完成了所有功課。探索迷宮(使用python 2.7)

我以不同的方式做了,但它以某種方式提供了正確的答案。 無論如何,我必須探索一個maz,所以我完成了所有的工作,除了這個任務的一部分(Q COMMAND)之外,所有的東西都完全正確。

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

2.2.6頂級接口 interact()是如在引言中描述的denes文本基本用戶界面 頂層功能。 請注意,當用戶退出時或者在找到完成平方時 時,應該退出交互功能。

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

問題「爲什麼不退出?」?你期望發生什麼?爲什麼Python 2.7很重要?你能否在你沒有選擇解決最後一部分的方式上發表一些細節?你能發佈兩三行迷宮文件嗎? – octopusgrabbus 2012-04-04 13:03:02

回答

0

你的問題還不是特別清楚,但是我猜測,「問題」是,如果用戶回答「Y」代替「Y」當被問及是否確信他們要退出,然後循環將繼續。

如果是這樣的問題,您應該只是更換行:

if m == 'y': 
    break 

有:

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

因爲無論在用戶鍵入 「Y」 或 「Y」,循環仍然會被打破。

+0

但我不得不使用這個,因爲我的老師說: 在交互功能中的用戶輸入應該在請求用戶命令時轉換爲大寫。已經在字符串method.upper() 例如'asdf'.upper() - >'ASDF' 當退出交互時,[y]意味着退出是默認選項,所以基本上如果用戶鍵入'N',他們不應該退出,任何其他輸入應該退出。 例如。 「你確定要退出嗎? [y]或n:''N' - >不退出 '你確定要退出嗎? [y]或n:''Y' - >退出 '你確定要退出嗎? [y]或n:''asdf' - >退出 – Alzaeemah 2012-04-04 19:53:12