1

I'm making a noughts and crosses AI using negamax and to do this I must run through all the possible moves you could make from any board state. I'm attempting to do this by appending each possible version of the board to a list however it will only append the final state to the list.

Here is my code:

def allPossibleMoves(board, turn):
    l = []
    for i in range(0,3):
        for x in range(0,3):
            if board[i][x] == ' ':
                board[i][x] = turn
                print(board)
                l.append(board)
                board[i][x] = ' '
    return l
2
  • 1
    Could you provide an input and its expected output? Commented Mar 13, 2021 at 13:51
  • 1
    You only have a single mutable board in your code -- make copies of it before appending. Also -- your question would be better if it included a minimal reproducible example. In this case, the issue seems clear enough, but whenever code in a question depends upon code defined elsewhere, it is hard to know for certain what is going on. Commented Mar 13, 2021 at 13:55

2 Answers 2

2

The reason is because no matter how many times you append board to the list, the board variable will point at the same object.

Use the deepcopy() method from the built-in copy module in the for loop to make copies of the object:

Sign up to request clarification or add additional context in comments.

Comments

1

Your trying to append the same variable over over.

If you know for sure that board is a bidimensional array, you can append a list comprehension, like this:

l.append([array[:] for array in board])

If you don't know the shape of board, I suggest you use the same method as per Ann Zen's answer.

3 Comments

Nice. But the inner arrays of board will still be the same instances of each others.
Oof, you are right, they'll all be the same copy of the latest updated board. Thanks for letting me know!
Good idea. You can implement your first suggestion into this answer: [array[:] for array in board].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.