Created
September 7, 2019 20:58
-
-
Save wcneill/6280e36746bcacfd639697ec1875b195 to your computer and use it in GitHub Desktop.
A game of 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
grid = [[0, 0, 0], | |
[0, 0, 0], | |
[0, 0, 0]] | |
print(grid) | |
win = False | |
turns = 0 | |
player = 1 | |
while not win: | |
if turns % 2 == 0: | |
player = 'X' | |
play = input("Player 1, please choose a square (format: 'row,col'): ").strip(" ") | |
else: | |
player = 'O' | |
play = input("Player 2, please choose a square (format: 'row,col'): ").strip(" ") | |
coord = [int(i) for i in play.split(',')] | |
if grid[coord[0] - 1][coord[1] - 1] == 0: | |
grid[coord[0] - 1][coord[1] - 1] = player | |
else: | |
print("That space is already taken!") | |
turns -= 1 | |
[print(i) for i in grid] | |
# check columns for wins | |
for i in range(3): | |
column = [row[i] for row in grid] | |
win = all(elem == column[0] and elem != 0 for elem in column) | |
if win: | |
print("Player", player, "wins by completing column", i + 1) | |
break | |
if win: break | |
# check rows for ins # | |
for j in range(3): | |
win = all(elem == grid[j][0] and elem != 0 for elem in grid[j]) | |
if win: | |
print('Player', player, 'wins by completing row', j + 1) | |
break | |
if win: break | |
# check diagonals for win | |
diag1 = [row[i] for i, row in zip(range(3), grid)] | |
win = all(elem == diag1[0] and elem != 0 for elem in diag1) | |
if win: | |
print('Player', player, 'wins by completing a diagonal!') | |
break | |
diag2 = [row[i] for i, row in zip(range(3)[::-1], grid)] | |
win = all(elem == diag2[0] and elem != 0 for elem in diag2) | |
if win: | |
print('Player', player, 'wins by completing a diagonal!') | |
break | |
turns +=1 | |
if turns == 9: | |
print("The game is a draw") | |
break | |
print('The game is over') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment