Created
September 7, 2018 21:58
-
-
Save michellemho/4cd4f5cbb3233f874325b49aabff64c1 to your computer and use it in GitHub Desktop.
let's play tic tac toe!
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 play_tic_tac_toe(): | |
print("""Let's play tictactoe! The board looks like | |
# 1 2 3 | |
# A A1 A2 A3 | |
# B B1 B2 B3 | |
# C C1 C2 C3""") | |
board = [('A', 1), ('A', 2), ('A', 3), | |
('B', 1), ('B', 2), ('B', 3), | |
('C', 1), ('C', 2), ('C', 3)] | |
moves = {1:[], 2:[]} | |
is_game_over = False | |
blank_board = """ | |
# 1 2 3 | |
# A {A1} {A2} {A3} | |
# B {B1} {B2} {B3} | |
# C {C1} {C2} {C3}""" | |
board_data = {'A1':'_','A2':'_','A3':'_','B1':'_','B2':'_','B3':'_','C1':'_','C2':'_','C3':'_'} | |
def end_game(winning_player): | |
print('Player {} wins!'.format(winning_player)) | |
return True | |
while not is_game_over: | |
for i in range(len(board)): # i keeps track of the order of the players, and the number of moves | |
valid_move = None | |
while not valid_move: | |
move = input('Player {x}, make a turn (ie. A1): '.format(x=i%2+1)) | |
player_move = move | |
if len(move) == 2: | |
move = (move[0], int(move[1])) | |
if move in board: | |
valid_move = True | |
break | |
elif move in [move for players in moves.values() for move in players]: | |
print('This move was already taken. Try again.') | |
else: | |
print('Hey! Not a valid move, choose again. Format answer as row letter and column number (ie. C2)') | |
# remove the move as a future option to play | |
board.remove(move) | |
board_data[player_move] = 'O' if i%2 else 'X' | |
print(blank_board.format(**board_data)) | |
# add the move to the list of player's moves | |
moves[i%2+1].append(move) | |
# all winning scenarios | |
winning_scenarios = [[('A',1), ('B',2), ('C',3)], | |
[('A',3), ('B',2), ('C',1)], | |
[('A',1), ('A',2), ('A',3)], | |
[('B',1), ('B',2), ('B',3)], | |
[('C',1), ('C',2), ('C',3)], | |
[('A',1), ('B',1), ('C',1)], | |
[('A',2), ('B',2), ('C',2)], | |
[('A',3), ('B',3), ('C',3)]] | |
# check for any winning moves | |
if moves[i%2+1]: | |
if any([set(win).issubset(set(moves[i%2+1])) for win in winning_scenarios]): | |
is_game_over = end_game(i%2+1) | |
break | |
if not is_game_over: | |
print('Draw!') | |
break |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment