Skip to content

Instantly share code, notes, and snippets.

@jconst
Created March 12, 2015 23:04
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save jconst/657b5f6bf1f5c755baec to your computer and use it in GitHub Desktop.
tictactoe.py
X = 'X'
O = 'O'
theBoard = [[None for _ in range(3)] for _ in range(3)]
def owner(line):
return reduce(lambda acc,cur: acc if acc == cur else None, line, line[0])
def diags(board):
return [[x[i] for i, x in enumerate(board)],
[x[i] for i, x in enumerate(reversed(board))]]
def rows(board):
return board
def cols(board):
return zip(*board)
def anyNonNull(list):
return reduce(lambda acc,cur: cur if acc == None else acc, list)
def winner(board):
return anyNonNull([owner(row) for row in rows(board)]) \
or anyNonNull([owner(col) for col in cols(board)]) \
or anyNonNull([owner(diag) for diag in diags(board)]) \
or None
def printBoard(board):
print '\n'
for arr in board:
print arr
print '\n'
def playerMove():
return [int(s) for s in raw_input("Make a move:").split()]
def computerMove(board):
# Computer moves coming soon ;)
return [int(s) for s in raw_input("Make a move:").split()]
def play():
turns = [X,O,X,O,X,O,X,O,X]
for turn in turns:
x, y = playerMove() if turn == X else computerMove(theBoard)
theBoard[y][x] = turn
printBoard(theBoard)
theWinner = winner(theBoard)
if theWinner != None:
print theWinner + " WINS!!!\n"
return
print "CATS!"
play()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment