Created
June 19, 2023 21:38
-
-
Save AnimXhafa97/fac5b62e47e136b954bdd8223d3cbb9c to your computer and use it in GitHub Desktop.
2 player Tic Tac Toe in Python
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
#2-player tic tac toe | |
# Create the board as a list of empty spaces | |
board = [" " for i in range(9)] | |
# print board in terminal | |
def print_board(): | |
print("_____________") | |
print("|", board[0], "|", board[1], "|", board[2], "|") | |
print("-------------") | |
print("|", board[3], "|", board[4], "|", board[5], "|") | |
print("-------------") | |
print("|", board[6], "|", board[7], "|", board[8], "|") | |
print("-------------") | |
# Function to check for winner | |
def check_winner(): | |
# Check rows | |
for i in range(0, 9, 3): | |
if board[i] == board[i + 1] == board[i + 2] != " ": | |
return board[i] | |
# Check columns | |
for i in range(3): | |
if board[i] == board[i + 3] == board[i + 6] != " ": | |
return board[i] | |
# Check diagonals | |
if board[0] == board[4] == board[8] != " ": | |
return board[0] | |
if board[2] == board[4] == board[6] != " ": | |
return board[2] | |
# No winner | |
return None | |
# Checks if board is full so we can stop on a tie | |
def is_board_full(): | |
return " " not in board | |
# Gameplay loop | |
def play_game(): | |
player = "X" | |
while True: | |
print_board() | |
print("Player", player, "turn. Choose a position (1-9):") | |
position = input() | |
position = int(position) - 1 | |
if board[position] != " ": | |
print("Invalid move. Try again.") | |
continue | |
board[position] = player | |
winner = check_winner() | |
if winner: | |
print_board() | |
print("Player", winner, "wins!") | |
break | |
if is_board_full(): | |
print_board() | |
print("It's a tie!") | |
break | |
player = "O" if player == "X" else "X" | |
# Start the game | |
play_game() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment