Last active
March 12, 2021 13:18
-
-
Save janeadams/5111cd8f281d8883fbb346596840356e to your computer and use it in GitHub Desktop.
TicTacToe - Recurse Interview
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def printBoard(board, game): | |
print(f"Game #{game}. Board configuration:\n {' '.join([str(c) for c in board[:3]])}\n {' '.join([str(c) for c in board[3:6]])}\n {' '.join([str(c) for c in board[6:]])}\n") | |
def checkWin(board, game): | |
printBoard(board, game) | |
routes = [board[:3], board[3:6], board[6:]] # Rows of board | |
columns = [board[::3],board[1::3],board[2::3]] # Columns of board | |
routes.extend(columns) | |
diagonals = [[board[0],board[4],board[8]],[board[2],board[4],board[6]]] # Diagonals of board | |
routes.extend(diagonals) # Routes = all possible routes to a win-state | |
win = False | |
winner = None | |
for route in routes: | |
if len(list(set(route))) == 1: # If every item in the route is the same | |
print(f'Route set: {list(set(route))}') | |
win = True | |
winner = list(set(route))[0] # The winner is whichever player has filled every cell in the route | |
print(f'!WINNER! Player {winner}') | |
return win, winner | |
def checkStalemate(board): | |
stalemate = (True if (len(list(set(board))) == 2) else False) | |
if stalemate: print(f'!STALEMATE!') | |
return stalemate | |
def resetBoard(): | |
print("Clearing board...") | |
return [0,1,2,3,4,5,6,7,8] | |
def turn(player, board): | |
print(f'Hello player {player}!') | |
err = True | |
while err: | |
try: | |
square = int(input(f'Input a board square:')) | |
if 0 <= square <=8: | |
if isinstance(board[square], int): | |
err = False | |
board[square] = player | |
else: | |
print(f'Square #{square} already occupied by {board[square]}') | |
err = True | |
else: | |
print('Select a square in the range 0-8') | |
err = True | |
except: | |
err = True | |
player = 'X' if player=='O' else 'O' | |
print(f'Active player: {player}') | |
return player | |
def main(): | |
board = resetBoard() | |
game = 0 | |
win, winner = checkWin(board, game) | |
stalemate = checkStalemate(board) | |
keepPlaying = True | |
player = 'X' | |
while keepPlaying: | |
player = turn(player, board) | |
win, winner = checkWin(board, game) | |
stalemate = checkStalemate(board) | |
if (win or stalemate): | |
board = resetBoard() | |
playAgain = str(input(f'Play again? [Y/n]')) | |
if playAgain.lower() == 'n': | |
keepPlaying = False | |
else: game += 1 | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment