diff --git a/TIC_TAC_TOE/index.py b/TIC_TAC_TOE/index.py index 7e494d0e700..95245d34fe5 100644 --- a/TIC_TAC_TOE/index.py +++ b/TIC_TAC_TOE/index.py @@ -15,6 +15,17 @@ def check_winner(board, player): def is_full(board): return all(cell != " " for row in board for cell in row) +# A function that validates user input +def get_valid_input(prompt): + while True: + try: + value = int(input(prompt)) + if 0 <= value < 3: # Check if the value is within the valid range + return value + else: + print("Invalid input: Enter a number between 0 and 2.") + except ValueError: + print("Invalid input: Please enter an integer.") def main(): board = [[" " for _ in range(3)] for _ in range(3)] @@ -22,10 +33,13 @@ def main(): while True: print_board(board) - row = int(input(f"Player {player}, enter the row (0, 1, 2): ")) - col = int(input(f"Player {player}, enter the column (0, 1, 2): ")) + print(f"Player {player}'s turn:") + + # Get validated inputs + row = get_valid_input("Enter the row (0, 1, 2): ") + col = get_valid_input("Enter the column (0, 1, 2): ") - if 0 <= row < 3 and 0 <= col < 3 and board[row][col] == " ": + if board[row][col] == " ": board[row][col] = player if check_winner(board, player): @@ -40,7 +54,7 @@ def main(): player = "O" if player == "X" else "X" else: - print("Invalid move. Try again.") + print("Invalid move: That spot is already taken. Try again.") if __name__ == "__main__": main()