Skip to content

Instantly share code, notes, and snippets.

@jmelloy
Created July 19, 2013 18:03
Show Gist options
  • Save jmelloy/6041106 to your computer and use it in GitHub Desktop.
Save jmelloy/6041106 to your computer and use it in GitHub Desktop.
"""Given a tic-tac-toe board, determine if the game is won.
- Allow the user to select a choice, and error appropriately if the choice is invalid
- Have the computer play, randomly picking a valid choice
Test input:
x-x-oox-- # No winner
o-xo-xo-- # O wins
xxxo-o-o- # X wins
xooox-x-x # X wins
xooox-o-x # X wins
xxx---ooo # Invalid board
"""
import sys
def board_check(board):
for row in board:
print "|".join(row)
print "-" * (len(row) + len(row) - 1)
# Horizontal
winner = []
for row in board:
test = row[0]
valid = True and test != "-"
for i, val in enumerate(row):
if val != test:
valid = False
break
if valid:
winner.append(test)
# Vertical
for i in range(len(board)):
test = board[0][i]
valid = True and test != "-"
for j in range(len(board)):
if board[j][i] != test:
valid = False
break
if valid:
winner.append(test)
# Diagonal
test = board[0][0]
valid = True and test != "-"
for i in range(len(board)):
if board[i][i] != test:
valid = False
break
if valid:
winner.append(test)
test = board[0][len(board) - 1]
(x,y) = (0, len(board) - 1)
valid = True and test != "-"
for i in range(len(board)):
if board[x + i][y - i] != test:
valid = False
break
if valid:
winner.append(test)
print winner
if len(winner) == 0:
return "No winner"
elif len(winner) == 1:
return "Winner is %s" % winner.pop()
else:
return "Board is invalid"
board = []
row = []
for i, l in enumerate(sys.argv[1]):
if i % 3 == 0 and i <> 0:
board.append(row)
row = []
row.append(l)
board.append(row)
print board
print board_check(board)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment