Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Speedy category for Xs and Os Champion by zcjsword
def x_and_o(grid, your_mark):
def checkWin(grid, mark):
"""
:a subroutine to check a imminent victory condition
"""
#horizontal
for iR, row in enumerate(grid):
if sorted(row) == ['.', mark, mark]: return iR, row.index('.')
#vertical
for iC, col in enumerate(zip(*grid)):
if sorted(col) == ['.', mark, mark]: return col.index('.'), iC
#back slash
r = [grid[x][x] for x in range(3)]
if sorted(r) == ['.', mark, mark]: return r.index('.'), r.index('.')
#slash
r = [grid[2-x][x] for x in range(3)]
if sorted(r) == ['.', mark, mark]: return 2-r.index('.'), r.index('.')
#no imminent victory to take care
return None
#if I have a win, then go for it
ret = checkWin(grid, your_mark)
if ret: return ret
#if AI has a win, then sabotage it
ret = checkWin(grid, "X" if your_mark=="O" else "O")
if ret: return ret
#if the center is not occupied, then go for it
if grid[1][1] == '.': return 1,1
#if any corner is not occupied, then go for it
for i in [0,2]:
for j in [0,2]:
if grid [i][j] == '.': return i, j
#fill the rest 4
for iR, row in enumerate(grid):
for iC, c in enumerate(row):
if c=='.': return iR, iC
Jan. 6, 2016
Comments: