首页 > 解决方案 > 在 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])

标签: pythonarraysrecursion

解决方案


如果我正确理解了您的问题,这应该可以,但是这不是递归-

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


推荐阅读