-1

I'm experimenting with creating a tic-tac-toe AI, and one idea was to calculate all possible future board states given a position in order to get the statistically best move. I thought using recursion would be the best way to calculate this, but even before checking all winning positions i got this problem where the board would get changed despite passing a new object in the function.

import sys

def calc(board : list, turn : bool):
    game_over = True
    letter = "o" if turn else "x"

    for i in range(len(board)):
        for j in range(len(board)):
            if board[i][j] == "":
                t = list(board)
                t[i][j] = letter
                game_over = False
                calc(list(t), not turn)
    
    if game_over:
        print(board)

def main():
    sys.setrecursionlimit(50000)
    board = [["", "", ""],["", "", ""],["", "", ""]]
    calc(board, True)

if __name__ == '__main__':
    main()

How do I get board to not change so I can evaluate ALL possible moves?

khelwood
  • 55,782
  • 14
  • 81
  • 108
Andreas Sandberg
  • 241
  • 1
  • 3
  • 10

1 Answers1

0

That code represent all possible games in final state:

code:

import itertools
player = ['O', 'X']
itertools.product(player, repeat = 9)

list comprehension:

[[i[0:3],i[3:6],i[6:10]] for i in itertools.product(player, repeat = 9)]

more information:

Generate a list of all unique Tic Tac Toe boards


I suggest MiniMax Algorithm there

Piotr Żak
  • 2,046
  • 5
  • 18
  • 30