@@ -15,17 +15,31 @@ def check_winner(board, player):
1515
1616def is_full (board ):
1717 return all (cell != " " for row in board for cell in row )
18+ # A function that validates user input
19+ def get_valid_input (prompt ):
20+ while True :
21+ try :
22+ value = int (input (prompt ))
23+ if 0 <= value < 3 : # Check if the value is within the valid range
24+ return value
25+ else :
26+ print ("Invalid input: Enter a number between 0 and 2." )
27+ except ValueError :
28+ print ("Invalid input: Please enter an integer." )
1829
1930def main ():
2031 board = [[" " for _ in range (3 )] for _ in range (3 )]
2132 player = "X"
2233
2334 while True :
2435 print_board (board )
25- row = int (input (f"Player { player } , enter the row (0, 1, 2): " ))
26- col = int (input (f"Player { player } , enter the column (0, 1, 2): " ))
36+ print (f"Player { player } 's turn:" )
37+
38+ # Get validated inputs
39+ row = get_valid_input ("Enter the row (0, 1, 2): " )
40+ col = get_valid_input ("Enter the column (0, 1, 2): " )
2741
28- if 0 <= row < 3 and 0 <= col < 3 and board [row ][col ] == " " :
42+ if board [row ][col ] == " " :
2943 board [row ][col ] = player
3044
3145 if check_winner (board , player ):
@@ -40,7 +54,7 @@ def main():
4054
4155 player = "O" if player == "X" else "X"
4256 else :
43- print ("Invalid move. Try again." )
57+ print ("Invalid move: That spot is already taken . Try again." )
4458
4559if __name__ == "__main__" :
4660 main ()
0 commit comments