You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
def display_board(board):
"""Display Tic-Tac-Toe board."""
for row in board:
print("|".join(row))
print("-----")
def check_winner(board):
"""Check if there is a winner."""
# Check rows
for row in board:
if row[0] == row[1] == row[2] != ' ':
return row[0]
# Check columns
for col in range(3):
if board[0][col] == board[1][col] == board[2][col] != ' ':
return board[0][col]
# Check diagonals
if board[0][0] == board[1][1] == board[2][2] != ' ':
return board[0][0]
if board[0][2] == board[1][1] == board[2][0] != ' ':
return board[0][2]
return None
def check_tie(board):
"""Check if the game is a tie."""
for row in board:
for cell in row:
if cell == ' ':
return False
return True
def get_player_move(board, player):
"""Get valid player move."""
while True:
try:
move = input(f"Player {player}, enter your move (row[0-2] column[0-2]): ")
row, col = map(int, move.split())
if board[row][col] == ' ':
return row, col
else:
print("That position is already taken. Try again.")
except ValueError:
print("Invalid input. Please enter row and column as numbers.")
def play_game():
"""Run Tic-Tac-Toe game."""
board = [[' ']*3 for _ in range(3)]
current_player = 'X'
while True:
display_board(board)
row, col = get_player_move(board, current_player)
board[row][col] = current_player
if check_winner(board):
display_board(board)
print(f"Player {current_player} wins!")
break
elif check_tie(board):
display_board(board)
print("It's a tie!")
break
current_player = 'O' if current_player == 'X' else 'X'
if name == "main":
play_game()
The text was updated successfully, but these errors were encountered:
def display_board(board):
"""Display Tic-Tac-Toe board."""
for row in board:
print("|".join(row))
print("-----")
def check_winner(board):
"""Check if there is a winner."""
# Check rows
for row in board:
if row[0] == row[1] == row[2] != ' ':
return row[0]
def check_tie(board):
"""Check if the game is a tie."""
for row in board:
for cell in row:
if cell == ' ':
return False
return True
def get_player_move(board, player):
"""Get valid player move."""
while True:
try:
move = input(f"Player {player}, enter your move (row[0-2] column[0-2]): ")
row, col = map(int, move.split())
if board[row][col] == ' ':
return row, col
else:
print("That position is already taken. Try again.")
except ValueError:
print("Invalid input. Please enter row and column as numbers.")
def play_game():
"""Run Tic-Tac-Toe game."""
board = [[' ']*3 for _ in range(3)]
current_player = 'X'
if name == "main":
play_game()
The text was updated successfully, but these errors were encountered: