2014-05-08 59 views
1

我正在研究一個涉及2名玩家的簡單遊戲。每個球員有兩個計數器,他們可以通過選擇他們單獨移動。玩家1有計數器1和1,而玩家2有計數器3和4.爲了防止玩家移動他們的一個對手計數器,我寫了下面的遞歸函數。Python遞歸函數錯誤地執行return語句?

它工作正常,如果沒有人'作弊'。

如果玩家作弊,該功能讓他們重新輸入正確的計數器號碼。如預期的那樣,這將貫穿到最終的歸還聲明中。

但是,在這一點上不是返回一個正確的計數器號碼,它似乎要採取另一個步驟,並將其更改爲最初的錯誤值。就好像代碼已經記住了遞歸期間已經嘗試過的變量計數器的所有值,並在返回第一個元素之前循環遍歷它們。

我錯過了什麼?

def get_counter(current_player): 
    counter = int(input("Select which counter you want to move.")) 
    if counter != 1 and counter != 2 and current_player == 1: 
     print("This is not your counter") 
     print("Your counters are 1 or 2") 
     get_counter(current_player) 
    elif counter != 3 and counter != 4 and current_player == 2: 
     print("This is not your counter") 
     print("Your counters are 3 or 4") 
     get_counter(current_player) 
    return counter 

回答

2

您正在遞歸調用函數,但不返回遞歸結果。添加return聲明:

def get_counter(current_player): 
    counter = int(input("Select which counter you want to move.")) 
    if counter != 1 and counter != 2 and current_player == 1: 
     print("This is not your counter") 
     print("Your counters are 1 or 2") 
     return get_counter(current_player) 
    elif counter != 3 and counter != 4 and current_player == 2: 
     print("This is not your counter") 
     print("Your counters are 3 or 4") 
     return get_counter(current_player) 
    return counter 

沒有明確地返回遞歸調用get_counter()的結果,調用函數繼續在那裏,它已在調用之前離開,而是執行return counter聲明。本地counter變量不在遞歸函數調用之間共享,因此它是的第一個選項,最終從最外層調用中返回。

但是,不要低估你的用戶繼續嘗試和作弊的能力;你最終會跑到最大的遞歸深度。你不應該使用遞歸來處理用戶輸入;改爲使用循環:

def get_counter(current_player): 
    while True: 
     counter = int(input("Select which counter you want to move.")) 
     if current_player == 1 and counter not in (1, 2): 
      print("This is not your counter") 
      print("Your counters are 1 or 2") 
      continue 
     if current_player == 2 and counter not in (3, 4): 
      print("This is not your counter") 
      print("Your counters are 3 or 4") 
      continue 
     return counter 

僅當輸入了正確的計數時才返回;它繼續循環(重新考慮問題),如果不正確的條目被取而代之。

+0

這太清楚了!感謝您提高我的理解。 – user3616508