2人组合游戏

2024-09-25 00:32:42 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

谢谢


Tags: 函数代码游戏列表move选项玩家数字
2条回答

我将首先考虑一些基本情况:

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_move,那么这个变量就是False,如果当前玩家移动后另一个玩家输了my_move。你知道吗

那你该怎么办呢?显然,如果other_wins_if_i_do_this对每个移动都给出相同的值,则返回相反的值。但是如果other_wins_if_i_do_this对于某些值是True,但是对于其他值是False,那会怎样呢?你希望你的球员做什么?你知道吗

对于特定的情况,这一个是有效的,但我相信它并不总是有效的。你怎么认为?你知道吗

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

相关问题 更多 >