Tic Tac Toe Python Code
def print_board(board):
for row in board:
print(" | ".join(row))
print("-" * 9)
def check_win(board, player):
for row in board:
if all([cell == player for cell in row]):
return True
for col in range(3):
if all([board[row][col] == player for row in range(3)]):
return True
if all([board[i][i] == player for i in range(3)]) or all([board[i][2 - i] == player for i in range(3)]):
return True
return False
def is_board_full(board):
return all([cell != " " for row in board for cell in row])
def tic_tac_toe():
board = [[" " for _ in range(3)] for _ in range(3)]
players = ["X", "O"]
player_index = 0
print("Welcome to Tic Tac Toe!")
print_board(board)
while True:
current_player = players[player_index]
row = int(input(f"Player {current_player}, enter row (0-2): "))
col = int(input(f"Player {current_player}, enter column (0-2): "))
if board[row][col] == " ":
board[row][col] = current_player
print_board(board)
if check_win(board, current_player):
print(f"Congratulations, Player {current_player} wins!")
break
if is_board_full(board):
print("It's a draw!")
break
player_index = 1 - player_index
else:
print("That cell is already occupied. Try again!")
if __name__ == "__main__":
tic_tac_toe()
0 Comments