Untitled

 avatar
unknown
plain_text
a year ago
1.7 kB
5
Indexable
def print_board(board):
    for row in board:
        print(" | ".join(row))
        print("-" * 5)

def check_winner(board, player):
    for row in board:
        if all([spot == player for spot 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_board_full(board):
    return all(board[row][col] != " " for row in range(3) for col in range(3))

def get_move(player, board):
    while True:
        try:
            move = input(f"Player {player}, enter your move as 'row,col': ")
            row, col = map(int, move.split(","))
            if board[row][col] == " ":
                return row, col
            else:
                print("This spot is taken. Choose another.")
        except (ValueError, IndexError):
            print("Invalid input. Enter the row and column as numbers separated by a comma.")

def play_game():
    board = [[" " for _ in range(3)] for _ in range(3)]
    current_player = "X"
    while True:
        print_board(board)
        row, col = get_move(current_player, board)
        board[row][col] = current_player
        if check_winner(board, current_player):
            print_board(board)
            print(f"Player {current_player} wins!")
            break
        if is_board_full(board):
            print_board(board)
            print("The game ends in a tie.")
            break
        current_player = "O" if current_player == "X" else "X"

if __name__ == "__main__":
    play_game()
Editor is loading...
Leave a Comment