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
Below is a Python code that checks the status of a Tic-Tac-Toe game. This code defines a function
check_game_statuswhich takes the current state of the board as input and returns the status of the game. The board is represented as a 3x3 list of lists, where 'X' and 'O' represent the players' marks, and '-' represents an empty space.pythondef check_game_status(board): """ Checks the status of a Tic-Tac-Toe game. Args: - board (list of lists): A 3x3 representation of the Tic-Tac-Toe board. 'X' and 'O' are players, '-' represents an empty space. Returns: - status (str): 'Finished' if the game is over, 'Ongoing' otherwise. - winner (str): 'X' if X wins, 'O' if O wins, 'Tie' if it's a tie, None if the game is not finished. - next_turn (str): 'X' or 'O' indicating whose turn it is next, None if the game is finished. """ # Validate the input board if not isinstance(board, list) or len(board) != 3: raise ValueError("Invalid board: Board must be a 3x3 list of lists.") for row in board: if not isinstance(row, list) or len(row) != 3: raise ValueError("Invalid board: Each row must be a list of 3 elements.") for cell in row: if cell not in ['X', 'O', '-']: raise ValueError("Invalid board: Cell values must be 'X', 'O', or '-'.") # Check rows and columns for a winner for i in range(3): if board[i][0] == board[i][1] == board[i][2] and board[i][0] in ['X', 'O']: return 'Finished', board[i][0], None if board[0][i] == board[1][i] == board[2][i] and board[0][i] in ['X', 'O']: return 'Finished', board[0][i], None # Check diagonals for a winner if board[0][0] == board[1][1] == board[2][2] and board[0][0] in ['X', 'O']: return 'Finished', board[0][0], None if board[0][2] == board[1][1] == board[2][0] and board[0][2] in ['X', 'O']: return 'Finished', board[0][2], None # Check for a tie if all(cell in ['X', 'O'] for row in board for cell in row): return 'Finished', 'Tie', None # Determine whose turn it is next x_moves = sum(row.count('X') for row in board) o_moves = sum(row.count('O') for row in board) next_turn = 'X' if x_moves <= o_moves else 'O' return 'Ongoing', None, next_turn # Example usage: if __name__ == "__main__": # Example board where X is about to win board = [ ['X', 'O', 'X'], ['O', 'X', 'O'], ['O', '-', 'X'] ] try: status, winner, next_turn = check_game_status(board) print(f"Game Status: {status}") if winner: if winner == 'Tie': print("It's a tie!") else: print(f"{winner} wins!") else: print(f"Next Turn: {next_turn}") except ValueError as e: print(f"Error: {e}")
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.