Skip to content

Commit

Permalink
Add robust input validation for row and column inputs
Browse files Browse the repository at this point in the history
  • Loading branch information
ZerubbabelT authored Dec 21, 2024
1 parent c7bc89b commit 3c4beaf
Showing 1 changed file with 18 additions and 4 deletions.
22 changes: 18 additions & 4 deletions TIC_TAC_TOE/index.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,17 +15,31 @@ 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)]
player = "X"

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):
Expand All @@ -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()

0 comments on commit 3c4beaf

Please sign in to comment.