python - 在 Python 中递归生成每个井字游戏
问题描述
我正在开发一个项目,在该项目中我生成所有可能的井字游戏数组。作为概念证明,我正在编写代码以用 9 个子数组填充数组。每个子数组将有两个值,第一个是 0 或 1(分别代表 x 和 o),第二个是从 1 到 9(表示放置时间)。我想退出的数组示例如下所示:
[[0, 0], [1, 1], [0, 2], [1, 3], [0, 4], [1, 5], [0, 6], [1, 7], [0, 8]]
我已经编写了代码,使用了 9 个 for 循环,每个循环都嵌套在上面的循环中,这给了我想要的结果(每个可能的数组,每个都是唯一的)。但我正在尝试编写代码,使用递归,并避免编写大量嵌套循环。
当我运行下面的代码时,它只能生成上面的数组,不能创建其他组合。我的代码如下:
print("running...")
allGames = []
checkCurrentGame = [5, 5, 5, 5, 5, 5, 5, 5, 5]
stepsDown = 0
def cleanGame(move, currentGame):
for j in range(9):
if (currentGame[j][1] >= move):
currentGame[j] = [5, 0]
def completeMove(moveNumber, currentGame):
global stepsDown
stepsDown = stepsDown + 1
for i in range(9):
cleanGame(moveNumber, currentGame)
if (currentGame[i][0] == 5):
currentGame[i][0] = i % 2
currentGame[i][1] = moveNumber
allGames.append(currentGame)
break
if (stepsDown < 9):
generateGame(currentGame)
def generateGame(currentGame):
for i in range(9):
completeMove(i, currentGame)
generateGame([[5, 0], [5, 0], [5, 0], [5, 0], [5, 0], [5, 0], [5, 0], [5, 0], [5, 0]])
for x in range(len(allGames)):
print(allGames[x])
解决方案
如果我正确理解了您的问题,这应该可以,但是这不是递归-
import itertools
[zip(p, range(0, 9)) for p in itertools.product([0, 1], repeat=9)]
代码首先生成一个板(9 个 0 或 1) -
itertools.product([0, 1], repeat=9)
然后将索引数据添加到其中。
我建议看看itertools
推荐阅读
- .htaccess - 从旧网址重定向到新网址赞助人
- latex - 如何自定义乳胶上连续方程之间的空格?
- c++ - 在以下情况下会出现什么问题?
- ios - 如何使用 Swift 在 JKCalendar 事件列表中创建具有当前时间线显示的正确时间格式?
- java - Android 10 中的 Sql 语法错误,在其他版本中可以正常工作
- canvas - 在 webgl 中,透视相机被添加到画布或 3D 模型本身?
- google-cloud-platform - 为 GCP Bucket 中所有未来上传的对象设置默认元数据
- android - 无法同步 Gradle 项目并显示消息“读取超时”
- rxjs - 无法将 Observable 转换为 ConnectableObservable
- php - wp_query wordpress