python/ChatGPT Tic Tac Toe.py

52 lines
1.5 KiB
Python
Raw Normal View History

2024-03-11 20:05:37 -04:00
def print_board(board):
for row in board:
print("|".join(row))
print("-" * 5)
def check_win(board, player):
win_conditions = [
[board[0][0], board[0][1], board[0][2]],
[board[1][0], board[1][1], board[1][2]],
[board[2][0], board[2][1], board[2][2]],
[board[0][0], board[1][0], board[2][0]],
[board[0][1], board[1][1], board[2][1]],
[board[0][2], board[1][2], board[2][2]],
[board[0][0], board[1][1], board[2][2]],
[board[2][0], board[1][1], board[0][2]]
]
return [player, player, player] in win_conditions
def get_player_move(player):
while True:
try:
move = int(input(f"Player {player}, enter your move (1-9): ")) - 1
if move < 0 or move > 8:
raise ValueError
if board[move // 3][move % 3] != " ":
print("This space is already taken.")
continue
return move
except ValueError:
print("Invalid input. Please enter a number between 1 and 9.")
def play_game():
for turn in range(9):
player = "X" if turn % 2 == 0 else "O"
print_board(board)
move = get_player_move(player)
board[move // 3][move % 3] = player
if check_win(board, player):
print_board(board)
print(f"Player {player} wins!")
return
print_board(board)
print("It's a tie!")
# Initialize the game board
board = [[" " for _ in range(3)] for _ in range(3)]
# Start the game
play_game()