Skip to content

Instantly share code, notes, and snippets.

@jodischneider
Created May 4, 2019 21:23
Show Gist options
  • Save jodischneider/6dbe5a36b3f3e9a3054d351d6ca88579 to your computer and use it in GitHub Desktop.
Save jodischneider/6dbe5a36b3f3e9a3054d351d6ca88579 to your computer and use it in GitHub Desktop.
# Before your interview, write a program that lets two humans play a game
# of Tic Tac Toe in a terminal. The program should let the players take
# turns to input their moves. The program should report the outcome of
# the game.
#
# During your interview, you will pair on adding support for a computer
# player to your game. You can start with random moves and make the AI
# smarter if you have time.
def printBoard(board):
print("", board[1], "|" , board[2], "|" , board[3])
print("---|---|---")
print("", board[4], "|" , board[5], "|" , board[6])
print("---|---|---")
print("", board[7], "|" , board[8], "|" , board[9])
print()
return
def getMove(board,playersymbol):
print("Player", playersymbol, "your turn!")
while True:
move = input("Enter the number of the square you want: ")
try:
index = int(move.strip())
if isValidMove(board, index):
board[int(move.strip())] = playersymbol
print("")
break
else:
print ("Sorry, that's not a valid move.")
except ValueError:
print("Sorry, I didn't understand that.")
return
def isValidMove(board, move):
if 1 <= move <= 9:
return(board[move] == str(move))
else:
return False
def swapPlayer(p):
if p == "x":
p = "o"
else:
p = "x"
return(p)
def checkWon(board,winningstates):
for state in winningstates:
if board[state[0]]==board[state[1]]==board[state[2]]:
return (True)
break
return(False)
############SET UP############
board = ['notused', '1', '2','3','4', '5', '6','7','8','9'] #avoid 0, looks like the letter 'o'
playersymbol = "o"
winningstates = [[1,2,3],[4,5,6],[7,8,9],[1,4,7],[2,5,8],[3,6,9],[1,5,9],[3,5,7]]
won = False
turns = 0
printBoard(board)
############CONGATS TO WINNER############
while ((won == False) & (turns < 9)):
playersymbol = swapPlayer(playersymbol)
getMove(board,playersymbol)
won = checkWon(board,winningstates)
printBoard(board)
turns += 1
############CONGATS TO WINNER############
if won:
print("Congratulations, player", playersymbol+"!")
else:
print("It's a tie!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment