Skip to content

Instantly share code, notes, and snippets.

@uroybd
Last active October 7, 2016 17:41
Show Gist options
  • Save uroybd/0da0d2346ee8654ab87c0172f02a79c4 to your computer and use it in GitHub Desktop.
Save uroybd/0da0d2346ee8654ab87c0172f02a79c4 to your computer and use it in GitHub Desktop.
Tic Tac Toe in python
import pandas as pd
def check_equal(lst):
if lst[0] != " ":
return lst[1:] == lst[:-1]
else:
return False
def if_win(board):
for i in range(3):
if check_equal(list(board[i])) is True:
return board[i][0]
elif check_equal(list(board.loc[i])) is True:
return board.loc[0]
if check_equal([board[0][0], board[1][1], board[2][2]]) is True or check_equal([board[0][2], board[1][1], board[2][1]]) is True:
return board[1][1]
else:
return False
def print_board(board):
print("|".join(board.loc[0]))
print("-+-+-")
print("|".join(board.loc[1]))
print("-+-+-")
print("|".join(board.loc[2]))
def main():
board = pd.DataFrame([[" " for i in range(3)] for i in range(3)])
user1 = None
while user1 is None:
choice = input("User 1, what symbol you would like to pick? 'X' or 'Y'?\n: ")
if choice == "X":
user1, user2 = "X", "Y"
elif choice == "Y":
user1, user2 = "Y", "X"
user = None
while user is None:
turn = input("User 1, you want to play first or User 2 will?\n'yes' or 'no'.\n: ")
if turn == "yes":
user = user1
elif turn == "no":
user = user2
print_board(board)
moves = 9
while moves > 0:
print("Turn for user {}".format(user))
move = None
while move is None:
try:
move = [int(n) for n in input("Pick a positon. Input coordinate with space between as sepertator.\n: ").split(" ")]
except:
print("Invalid Move.")
if board[move[0]][move[1]] == " " and move[0] < 3 and move[1] < 3:
board[move[0]][move[1]] = user
print_board(board)
any_winner = if_win(board)
user = user2 if user == user1 else user1
moves = moves - 1
if any_winner is not False:
print("{} wins!".format(any_winner))
print("Game Over.")
break
else:
pass
else:
print("Invalid Move.")
if moves == 0:
print("No winner, game over!")
again = input("Wanna play again? 'yes' or 'no'.\n: ")
if again == 'yes':
main()
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment