write a code in python that checks if a tic-tac-toe game is finished, if yes who won, if…
- User
write a code in python that checks if a tic-tac-toe game is finished, if yes who won, if no - whose turn now
- Assistant
3 1 2 3
| | | |
| | X | |
| | | O |
Here's a Python code that checks if a tic-tac-toe game is finished, determines the winner if there is one, or indicates whose turn it is:
pythondef check_winner(board): # Check rows for row in board: if row[0] == row[1] == row[2] != ' ': return row[0] # Check columns for col in range(3): if board[0][col] == board[1][col] == board[2][col] != ' ': return board[0][col] # Check diagonals if board[0][0] == board[1][1] == board[2][2] != ' ' or board[0][2] == board[1][1] == board[2][0] != ' ': return board[1][1] return None def print_board(board): print(" 1 2 3") print("-----------") for i, row in enumerate(board): print(f"{i+1}| {' | '.join(row)} |") print("-----------") def get_move(player): while True: try: row = int(input(f"Player {player}, enter row (1-3): ")) - 1 col = int(input(f"Player {player}, enter column (1-3): ")) - 1 if 0 <= row < 3 and 0 <= col < 3 and board[row][col] == ' ': return row, col else: print("Invalid move. Try again.") except ValueError: print("Invalid input. Please enter a number.") def tic_tac_toe(): board = [[' ' for _ in range(3)] for _ in range(3)] current_player = 'X' while True: print_board(board) row, col = get_move(current_player) board[row][col] = current_player winner = check_winner(board) if winner: print_board(board) print(f"Player {winner} wins!") break if ' ' not in [cell for row in board for cell in row]: print_board(board) print("It's a tie!") break current_player = 'O' if current_player == 'X' else 'X' if __name__ == "__main__": tic_tac_toe()
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.