# Tic Tac Toe
def print_board(board):
print("\n")
print(f" {board[0]} | {board[1]} | {board[2]} ")
print("---+---+---")
print(f" {board[3]} | {board[4]} | {board[5]} ")
print("---+---+---")
print(f" {board[6]} | {board[7]} | {board[8]} ")
print("\n")
def check_winner(board, player):
win_conditions = [
(0, 1, 2), (3, 4, 5), (6, 7, 8), # rows
(0, 3, 6), (1, 4, 7), (2, 5, 8), # columns
(0, 4, 8), (2, 4, 6) # diagonals
]
return any(board[a] == board[b] == board[c] == player for a, b, c in win_conditions)
def is_full(board):
return all(space in ['X', 'O'] for space in board)
def tic_tac_toe():
board = [str(i + 1) for i in range(9)] # initial numbered board
current_player = 'X'
print("Welcome to Tic Tac Toe!")
print_board(board)
while True:
try:
move = int(input(f"Player {current_player}, choose a position (1–9): ")) - 1
if move < 0 or move > 8 or board[move] in ['X', 'O']:
print("Invalid move, try again.")
continue
except ValueError:
print("Please enter a valid number between 1 and 9.")
continue
board[move] = current_player
print_board(board)
if check_winner(board, current_player):
print(f"🎉 Player {current_player} wins! 🎉")
break
elif is_full(board):
print("It's a tie! 🤝")
break
current_player = 'O' if current_player == 'X' else 'X'
if __name__ == "__main__":
tic_tac_toe()