Skip to content

Instantly share code, notes, and snippets.

@h2rashee
Last active August 29, 2015 14:02
Show Gist options
  • Save h2rashee/2e09c7cd23e86ed17fb9 to your computer and use it in GitHub Desktop.
Save h2rashee/2e09c7cd23e86ed17fb9 to your computer and use it in GitHub Desktop.
2-player Tic-Tac-Toe
#!/usr/bin/env/python
grid = [' '] * 9
curTurn = 'O'
#Print the X and O grid representing current game state
def displayBoard(board):
print "%s | %s | %s" % (board[0], board[1], board[2])
print "---------"
print "%s | %s | %s" % (board[3], board[4], board[5])
print "---------"
print "%s | %s | %s" % (board[6], board[7], board[8])
#Check if someone won through the last move
def isWin(board):
return ((board[0] == board[1] and board[1] == board[2] and board[0] != ' ') or # top row
(board[3] == board[4] and board[4] == board[5] and board[3] != ' ') or # middle row
(board[6] == board[7] and board[7] == board[8] and board[6] != ' ') or # bottom row
(board[0] == board[3] and board[3] == board[6] and board[0] != ' ') or # left column
(board[1] == board[4] and board[4] == board[7] and board[1] != ' ') or # middle column
(board[2] == board[5] and board[5] == board[8] and board[2] != ' ') or # right column
(board[0] == board[4] and board[4] == board[8] and board[0] != ' ') or # negative diagonal
(board[2] == board[4] and board[4] == board[6] and board[2] != ' ')) # positive diagonal
#Check if there are no longer any game moves to make and nobody has already won
#Game is declared a tie as a result then
def isTie(board):
if ' ' not in board:
return True
return False
#Turn changes hand
def flipTurn(curTurn):
if curTurn == 'X':
return 'O'
elif curTurn == 'O':
return 'X'
#Map a 2D given location to the 1D array storing Xs and Os
def computeLocation(row, col):
return (row * 3) + col
#
#Actual main part of the program
#
while not isWin(grid) and not isTie(grid):
displayBoard(grid)
curTurn = flipTurn(curTurn)
#Prompt for user's choice of spot
row = input("Please input row number: ")
col = input("Please input column number: ")
#Check if invalid grid table location is given
if row not in range(3) or col not in range(3):
print "INVALID spot: Appropriate range is 0-2"
#Counter-acts the change turn done at the beginning of the loop
curTurn = flipTurn(curTurn)
continue
spot = computeLocation(row, col)
#Check if location is illegal. If so, must re-input
if grid[spot] != ' ':
print "INVALID spot: Already filled. Please replay"
#Counter-acts the change turn done at the beginning of the loop
curTurn = flipTurn(curTurn)
continue
#Place user's move in appropriate spot
grid[spot] = curTurn
#Game is over by some means if it goes past this point
if isWin(grid):
displayBoard(grid)
print "%s wins the game!" % curTurn
if isTie(grid):
displayBoard(grid)
print "Nobody wins the game."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment