Untitled
unknown
plain_text
a year ago
2.0 kB
3
Indexable
def print_board(board):
"""Prints the current state of the board."""
for row in board:
print(" | ".join(row))
print("-" * 9)
def check_winner(board):
"""Checks if there is a winner."""
# Check rows, columns, and diagonals for a win
for i in range(3):
if board[i][0] == board[i][1] == board[i][2] != ' ':
return board[i][0]
if board[0][i] == board[1][i] == board[2][i] != ' ':
return board[0][i]
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 is_board_full(board):
"""Checks if the board is full."""
return all(cell != ' ' for row in board for cell in row)
def tic_tac_toe():
"""Main function to play Tic Tac Toe."""
board = [[' ' for _ in range(3)] for _ in range(3)]
current_player = 'X'
while True:
print_board(board)
print(f"Player {current_player}'s turn.")
# Get valid input from the player
while True:
try:
row = int(input("Enter the row (0-2): "))
col = int(input("Enter the column (0-2): "))
if board[row][col] == ' ':
board[row][col] = current_player
break
else:
print("Cell already taken! Choose another.")
except (ValueError, IndexError):
print("Invalid input! Please enter numbers from 0 to 2.")
winner = check_winner(board)
if winner:
print_board(board)
print(f"Player {winner} wins!")
break
if is_board_full(board):
print_board(board)
print("It's a tie!")
break
# Switch players
current_player = 'O' if current_player == 'X' else 'X'
# Start the game
if __name__ == "__main__":
tic_tac_toe()Editor is loading...
Leave a Comment