首页 > 解决方案 > 2人组合游戏

问题描述

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

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

谢谢

标签: python

解决方案


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

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玩家是否获胜,当前玩家下棋后其他玩家是否输了。my_moveFalsemy_move

那么你应该怎么做呢?显然,如果other_wins_if_i_do_this每一步都给出相同的值,你会返回相反的结果。但是,如果other_wins_if_i_do_thisTrue针对某些价值观,而False针对其他价值观呢?那你想让你的玩家做什么?


推荐阅读