python - 2人组合游戏
问题描述
有一个游戏我需要编写一个 python 代码。我不知道游戏的名称,所以我无法正确搜索它。该函数获取目标编号(“n”)和 move_options(正数列表,其中必须包含 1)。游戏规则:每个玩家在他的移动中可以从“n”减少 move_options 中存在的任何数字。所选号码在下一回合仍然可用(列表保持不变)。将“n”更改为 0 的玩家获胜(n 不能为负数)。该函数返回一个布尔值 - 如果在给定的 n 和 move_options 当前玩家可以获胜,则返回 True,否则返回 False。
我知道这是一个递归问题,但我不明白如何考虑其他玩家的举动。
谢谢
解决方案
我将通过考虑一些基本情况来开始这个问题:
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
针对其他价值观呢?那你想让你的玩家做什么?
推荐阅读
- c++ - CV_WINDOW_AUTOSIZE 常量和 cvCreatTrackbar 方法未定义
- sql-server - 从给定的事务 id 中选择许多事务中的 1 个
- php - 如何使用 PHP 和 fopen 打开 CSV-fil
- android - 使用 retofit 和 Moshi 解析 api 响应不完全“json”
- php - 为什么我的 SQL 查询导致 PHP 数组缺少一半的结果?
- r - 直方图中不同的 bin 宽度与 ggplot2, r
- ssis - SSIS 在查询名称中使用变量
- if-statement - VHDL 编码错误“不支持检查时钟后的其他子句”
- r - R广义矩回归估计方法与仪器
- java - 如何计算具有加权顶点的图的最短路径?