我正在开发一款涉及2名玩家的简单游戏。每个玩家都有两个计数器,他们可以通过选择它们来单独移动。玩家1有计数器1和1,而玩家2有计数器3和4.为了防止玩家移动他们的一个对手计数器,我写了以下递归函数。
如果没有人'欺骗',它就可以正常工作。
如果玩家作弊,该功能会让他们重新输入正确的计数器号码。这将按预期进行到最终的退货声明。
但是,此时不是返回正确的计数器,而是采取另一个步骤并将其更改为初始错误值。就好像代码已经记住了在递归过程中尝试过的变量计数器的所有值,并在返回结束之前循环遍历它们,然后返回第一个。
我错过了什么?
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
答案 0 :(得分: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
仅在输入正确的计数时返回;如果不正确的输入,它会继续循环(重新询问问题)。