Example output
def print_board(board):
for row in board:
print(" | ".join(row))
print("-" * 9)
def check_winner(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_draw(board):
for row in board:
if " " in row:
return False
return True
def play_game():
board = [[" " for _ in range(3)] for _ in range(3)]
current_player = "X"
winner = None
print("Welcome to Tic-Tac-Toe!")
print_board(board)
while True:
try:
row = int(input(f"Player {current_player}, enter the row (0, 1, or 2): "))
col = int(input(f"Player {current_player}, enter the column (0, 1, or 2): "))
if board[row][col] != " ":
print("That position is already taken. Try again.")
continue
board[row][col] = current_player
except (ValueError, IndexError):
print("Invalid input. Please enter valid row and column values.")
continue
print_board(board)
if check_winner(board, current_player):
winner = current_player
break
if is_draw(board):
break
current_player = "O" if current_player == "X" else "X"
if winner:
print(f"Player {winner} wins! Congratulations!")
else:
print("It's a draw! Good game!")
if __name__ == "__main__":
play_game()