I've been trying to code a tic-tac-toe game but I'm facing a problem. For example if I put a cross on one of the corners, the bot should mark "O" in the centre but that doesn't happen. Instead, it marks it on adjacent to the cross. The bot is not choosing the right value on the matrix. Any help would be appreciated. PS: The first player is always human while the second player is the bot. Here's the code:
import re
current_board = [" ", " ", " ", " ", " ", " ", " ", " ", " "]
current_game = list(" | | \n_|_|_\n | | \n_|_|_\n | | \n | | \n")
def draw1():
for i in range(9):
if(i<3 and i>=0):
current_game[2*i]=current_board[i]
elif(i<6 and i>=3):
current_game[2*(i-3)+12]=current_board[i]
elif(i<9 and i>=6):
current_game[2*(i-6)+24]=current_board[i]
print "".join(current_game)
def win(board, depth):
board="".join(board)
regex1 = [r"XXX......", r"...XXX...", r"......XXX", r"X..X..X..", r".X..X..X.", r"..X..X..X", r"X...X...X", r"..X.X.X.."]
for i in regex1:
if bool(re.search(i, board)):
return -10+depth
regex2 = [r"OOO......", r"...OOO...", r"......OOO", r"O..O..O..", r".O..O..O.", r"..O..O..O", r"O...O...O", r"..O.O.O.."]
for i in regex2:
if bool(re.search(i, board)):
return 10-depth
def draw(board):
for i in board:
if i==" ":
return False
return True
def assigning_values_to_a_move(board, isOplaying, depth):
scorelist=[]
if win(board, depth)==10-depth:
return 10-depth
elif win(board, depth)==-10+depth:
return -10+depth
elif draw(board):
return 0
else:
if(isOplaying):
for i in range(len(board)):
if board[i]==" ":
board[i]="O"
scorelist.append(assigning_values_to_a_move(board, not isOplaying, depth+1))
board[i]=" "
return max(scorelist)
else:
for i in range(len(board)):
if board[i]==" ":
board[i]="X"
scorelist.append(assigning_values_to_a_move(board, isOplaying, depth+1))
board[i]=" "
return min(scorelist)
def choosing_the_move(board, depth):
current_value=-1000
best_value=-1000
best_index=-1
for i in range(9):
if board[i]==" ":
board[i]="O"
current_value=assigning_values_to_a_move(board, False, depth)
if(current_value>best_value):
best_value=current_value
best_index=i
board[i]=" "
return best_index
for i in range(9):
if i%2==0:
y=int(raw_input())
current_board[y]="X"
draw1()
else:
current_board[choosing_the_move(current_board,i+1)]="O"
draw1()