Last active
May 27, 2016 16:05
-
-
Save gwengrid/6f9d6248c30ec969e47764451d62ecbd to your computer and use it in GitHub Desktop.
3x3 Tic Tac Toe
This file contains hidden or 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
#! python | |
import random | |
def print_board(board, size): | |
for j in range(0, size): | |
marker = "" | |
for i in range(0, size): | |
saved = board.get((i, j)) | |
if saved: | |
marker += saved + " " | |
else: | |
marker += "_" + " " | |
print marker | |
def valid_input(input, board): | |
try: | |
for i in input: | |
i = int(i) | |
if i < 0 or i > 2: | |
print "\tInvalid input. Move outside bounds" | |
return False | |
except ValueError: | |
print "\tInvalid input. Please use the form x, y" | |
return False | |
return True | |
def clean_input(input): | |
input = [int(i) for i in input] | |
return tuple(input) | |
def find_winning_chain(move, board, size): | |
x = move[0] | |
y = move[1] | |
winning = [ | |
[(0,0), (1,0), (2,0)], | |
[(0,1), (1,1), (2,1)], | |
[(0,2), (1,2), (2,2)], | |
[(0,0), (0,1), (0,2)], | |
[(1,0), (1,1), (1,2)], | |
[(2,0), (2,1), (2,2)], | |
[(0,0), (1,1), (2,2)], | |
[(2,0), (1,1), (0,2)] | |
] | |
for win in winning: | |
if move in win and board.get(win[0]) == board.get(win[1]) == board.get(win[2]): | |
return True | |
return False | |
if __name__ == "__main__": | |
game_on = True | |
current_player = "X" | |
other_player = "O" | |
computer_player = "O" | |
board = {} | |
board_size = 3 | |
untaken_moves = set() | |
for i in range(0, board_size): | |
for j in range(0, board_size): | |
untaken_moves.add((j, i)) | |
while game_on: | |
print_board(board, board_size) | |
turn_message = "Player " + str(current_player) + "'s turn. Make your move: " | |
if current_player == computer_player: | |
move = random.sample(untaken_moves, 1)[0] | |
else: | |
move = raw_input(turn_message).split(',') | |
if not valid_input(move, board): | |
continue | |
move = clean_input(move) | |
if move not in untaken_moves: | |
print "\tMove already taken!" | |
continue | |
untaken_moves.remove(move) | |
board[move] = current_player | |
if find_winning_chain(move, board, board_size): | |
game_on = False | |
print "Tic tac toe! Congrats Player " + current_player + "!" | |
continue | |
if len(board.keys()) == board_size*board_size: | |
game_on = False | |
print "It's a tie!" | |
continue | |
temp = other_player | |
other_player = current_player | |
current_player = temp |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment