Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Xs and Os Champion solution in Uncategorized category for Xs and Os Champion by capback250
# migrated from python 2.7
from itertools import chain
def x_and_o(grid, mark):
mid = (1, 1),
corners = ((0, 0), (0, 2), (2, 0), (2, 2))
others = ((0,1), (1,0), (1,2), (2, 1))
if winDiagonals(grid, mark):
return winDiagonals(grid, mark)
if winHoriz(grid, mark):
return winHoriz(grid, mark)
closeThisASAP = list(filter(bool, enemyWin(grid, mark)))
if closeThisASAP:
return closeThisASAP[0]
for position in chain(mid, corners, others):
if grid[position[0]][position[1]] == '.':
return position
def winDiagonals(grid, mark):
d1 = [(grid[x][x], x, x) for x in range(3)]
d2 = [(grid[x][2 - x], x, 2 - x) for x in range(3)]
for diag in [d1, d2]:
if [x[0] for x in diag].count(mark) == 2 and '.' in [x[0] for x in diag]:
return filter(lambda x: x[0] == '.', diag)[0][1:]
return False
def winHoriz(grid, mark):
for i, x in enumerate(grid):
if x.count(mark) == 2 and '.' in x:
return i, x.index('.')
for i, x in enumerate(zip(*grid)):
if x.count(mark) == 2 and '.' in x:
return x.index('.'), i
return False
def enemyWin(grid, mark):
enemyWinPositions = []
enemyMark = 'X' if mark == 'O' else 'O'
enemyWinPositions.append(winDiagonals(grid, enemyMark))
enemyWinPositions.append(winHoriz(grid, enemyMark))
return enemyWinPositions
Feb. 9, 2016