Skip to content

Instantly share code, notes, and snippets.

@mreinhardt
Last active December 30, 2016 11:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mreinhardt/cfdeeb3121ef1e6c00820d8a15677812 to your computer and use it in GitHub Desktop.
Save mreinhardt/cfdeeb3121ef1e6c00820d8a15677812 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
"""Tic Tac Toe game."""
PLAYER1 = True
BOARD = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
def show(board):
"""Print the current board state."""
print
for i, row in enumerate(board):
print ' {0} | {1} | {2} '.format(*row)
if i != len(board) - 1:
print '-' * 11
print
def check_win(board):
"""Return winning player mark or None."""
rotated_board = zip(*board) # matrix rotate rows to cols
# check rows and cols
for board_rotation in (board, rotated_board):
for row in board_rotation:
if (not isinstance(row[0], int) and
row.count(row[0]) == len(row)):
return row[0]
# check diags
if (not isinstance(board[1][1], int) and
(board[0][0] == board[1][1] == board[2][2] or
board[2][0] == board[1][1] == board[0][2])):
return board[1][1]
def board_full(board):
"""Return True if no moves left."""
for row in board:
if True in [isinstance(v, int) for v in row]:
return False
return True
if __name__ == '__main__':
print 'Welcome to a two-player Tic.Tac.Toe Game!'
print "Just pick a spot to put your mark!"
print 'Now, start!'
show(BOARD)
while check_win(BOARD) is None and not board_full(BOARD):
try:
move = int(input('Player {0}, select a spot (1-9): '.format(
1 if PLAYER1 else 2)))
row = (move - 1) / 3
col = (move - 1) % 3
spot = BOARD[row][col]
if isinstance(spot, int):
BOARD[row][col] = 'X' if PLAYER1 else 'O'
PLAYER1 = not PLAYER1
else:
print 'This spot is taken.'
except (ValueError, IndexError):
print 'Please enter a number from 1 to 9.'
show(BOARD)
winner = check_win(BOARD)
if winner:
print 'Player {0} won!'.format(1 if winner == 'X' else 2)
else:
print "It's a tie."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment