2人组合游戏

时间:2019-01-21 15:04:05

标签: python

有一个游戏我需要编写一个python代码。我不知道游戏的名称,所以无法正确搜索到它。 该函数获取目标号码(“ n”)和move_options(正数列表,其中必须包含1)。 游戏规则:每个棋手可以将move_options中存在的任何数字从“ n”减少。所选号码在下一轮仍然可用(列表保持不变)。 将“ n”更改为0的玩家获胜(n不能为负)。 该函数返回一个布尔值-如果在给定的n和move_options中当前玩家可以获胜,则返回True;否则,则返回False。

我知道这是一个递归问题,但我不知道如何考虑其他玩家的举动。

谢谢

2 个答案:

答案 0 :(得分:1)

我将通过考虑一些基本情况来开始这个问题:

def current_player_win(dest, move_options):
    if dest in move_options:
        return True

这是显而易见的“如果我离获胜仅一步之遥,我就赢了!案。为完整起见,我还要添加以下内容:

def current_player_win(dest, move_options):
    if dest in move_options:
        return True
    if dest == 0:
        # Other player must have moved to 0. They won.
        return False

现在,正如您所说,问题的实质是:如何处理另一位玩家的回合。

好吧,现在您需要考虑所有可能的举动:

def current_player_win(dest, move_options):
    if dest in move_options:
        return True
    if dest == 0:
        # Other player must have moved to 0. They won.
        return False
    for my_move in move_options:
        if my_move < dest:
            other_wins_if_i_do_this = current_player_win(dest - my_move, move_options)
            # Now do something with other_wins_if_i_do_this

因此,通过递归调用该函数,如果在当前玩家移动True other 玩家获胜,那么您现在有了一个my_move变量,它是{ {1}},如果其他玩家在当前玩家做出False之后输了。

那你该怎么办?显然,如果my_move的每一步都赋予相同的值,那么您将返回相反的值。但是,如果对于某些值,other_wins_if_i_do_thisother_wins_if_i_do_this,而对于其他值,True会怎样?您想让播放器做什么?

答案 1 :(得分:0)

在特定情况下,此功能有效,但我认为它始终无法正常工作。你觉得呢?

def current_player_win(dest, move_options):
    if num<0: return False
    if num in move_options:
        return True
    for move in move_options:
        if current_player_win(num-move, move_options) == True:
            return False
            break
    return True
相关问题