I'm trying to make a 'smart' opponent in my Tic Tac Toe program. To do this I've created a 'possible win' function which will decide if there is a possible win in the next turn. My problem when running this code is that on every iteration of the for loop the variable board seems to be changed.
I want to reset potential board to the original board at the start of every iteration which is why I included potential_board = board[:] at the start of the loop. I then edit potential_board but every time the loop repeats this variable is not reset, and board is in fact changed as well. Why is this?
Many thanks!
import random,copy
board = [['o','o',' '],[' ',' ',' '],[' ',' ',' ']]
cols = [['o',' ',' '],['o','',''],['o','','']]
def possible_win(board,player):
""" This function should predict whether a winning move is possible in
the next turn. This could be done by simulating every possible next move
and running check_win() on those positions.
:param board,player: checks a win for the specified player
:return:
"""
spaces = empty_spaces(board)
print('Spaces',spaces)
winning_moves = []
for space in spaces:
potential_board = board[:]
print('PBoard',potential_board)
print(space[0],space[1])
potential_board[space[0]][space[1]] = 'o'
if check_win(potential_board,'o'):
winning_moves.append(space)
return winning_moves
def choose_space(board):
a = True
while a:
col = int(input('Choose your column of 1,2,3: ')) - 1
row = int(input('Choose your row of 1,2,3: ')) - 1
if board[row][col] == ' ':
board[row][col] = 'o'
a = False
else: print('Sorry, try again')
return board
def empty_spaces(board):
empty_spaces = []
ind = 0
for row in board:
ind1 = 0
for space in row:
if space == ' ':
empty_spaces.append((ind, ind1))
ind1 += 1
ind += 1
return empty_spaces
def comp_choose_space(board):
choice = random.choice(empty_spaces(board))
board[choice[0]][choice[1]] = 'x'
return board
def check_win(board,player):
rows = board
columns = construct_cols(board)
for row in board:
# if player fills row win = True
a = ind = 0
for space in row:
if rows[board.index(row)][ind] != player: break
else: a += 1
ind += 1
if a == 3:
return True
for col in columns:
a = ind = 0
for space in col:
if rows[columns.index(col)][ind] != player:
break
else:
a += 1
ind += 1
if a == 3:
return True
if rows[0][0] == player and rows[1][1] == player and rows[2][2] == player \
or rows[0][2] == player and rows[1][1] == player and rows[2][0] == player:
return True
return False
def construct_cols(board):
cols = [['','',''],['','',''],['','','']]
for row in range(len(board)):
for col in range(row):
cols[col][row] = board[row][col] # sounds like this should work
return cols
def print_board(board):
for row in board:
print('| {} {} {} |'.format(row[0],row[1],row[2]))
def main():
turns = 0
board = [[' ',' ',' '],[' ',' ',' '],[' ',' ',' ']]
print_board(board)
win = False
while win == False and turns < 9:
turns += 1
board = choose_space(board)
if check_win(board,'o'): win,winner = True,'won'
board = comp_choose_space(board)
if check_win(board,'x'): win,winner = True,'lost'
print_board(board)
if turns == 9: print('You drew!')
else:
print('{}, you {}'.format('Congratulations' if winner == 'won' else 'Sorry',winner))
print(possible_win(board,'o'))
# print(empty_spaces(board))
# print(check_win(board,'o'))
# print_board(board)
# print(comp_choose_space(board))
# main()
# Future project - make the computer smarter than just randomly choosing a space
# ie seeing how close i am to winning
EDIT: By using copy.deepcopy() I managed to fix this, but I dont understand why this works and copy.copy() and board[:] did not work? Could somebody explain this?
This is what copy.deepcopy
is for. It will traverse the structure, creating copies of each mutable object within. Using a slice [:]
or shallow copy
duplicated only the top level, leaving the list for each row shared.
Basically, if we start out with a list:
l = [a, b, c]
shallow = l[:]
shallow2 = copy(l)
deep = deepcopy(l)
The two shallow
copies have operated only on l
, not on a
, b
or c
. They both have the value [a, b, c]
but are distinct lists. All of them refer to the same a
, b
and c
objects (the only change from their perspective is that there are more references).
The deep
copy has gone deeper and copied each element; it is a new list with the shape [deepcopy(a), deepcopy(b), deepcopy(c)]
, whatever those values turned into.