Activity - Tic-Tac-Toe game Let's break into groups, and each of the groups completes…
- User
Activity - Tic-Tac-Toe game Let's break into groups, and each of the groups completes one of the following tasks: Create a function to check if there is a win in any of the rows Create a function to check if there is a win in any of the columns Create a function to check if there is a win in any of the diagonals Create a function to display and number the empty positions Create a loop to take user input for X or O depending on the turn, and check for a win after user selection
- Assistant
I will start with creating a function to check if there is a win in any of the rows.
def check_rows(board): for row in board: if row[0] == row[1] == row[2] and row[0] != " ": return True return FalseNext, I will create a function to check if there is a win in any of the columns.
def check_columns(board): for col in range(3): if board[0][col] == board[1][col] == board[2][col] and board[0][col] != " ": return True return FalseThen, I will create a function to check if there is a win in any of the diagonals.
def check_diagonals(board): if board[0][0] == board[1][1] == board[2][2] and board[0][0] != " ": return True if board[0][2] == board[1][1] == board[2][0] and board[0][2] != " ": return True return FalseNext, I will create a function to display and number the empty positions.
def display_board(board): print(" 1 2 3") print("1 {} | {} | {}".format(board[0][0], board[0][1], board[0][2])) print(" ---+---+---") print("2 {} | {} | {}".format(board[1][0], board[1][1], board[1][2])) print(" ---+---+---") print("3 {} | {} | {}".format(board[2][0], board[2][1], board[2][2])) def display_empty_positions(board): empty_positions = [] for row in range(3): for col in range(3): if board[row][col] == " ": empty_positions.append((row, col)) for i, position in enumerate(empty_positions): print("{}. row: {}, column: {}".format(i+1, position[0]+1, position[1]+1))Finally, I will create a loop to take user input for X or O depending on the turn, and check for a win after each user selection.
def play_tic_tac_toe(): board = [[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']] turn = "X" winner = None while not winner: display_board(board) display_empty_positions(board) row = int(input("Enter the row (1-3): ")) col = int(input("Enter the column (1-3): ")) if board[row-1][col-1] == " ": board[row-1][col-1] = turn if check_rows(board) or check_columns(board) or check_diagonals(board): winner = turn else: turn = "O" if turn == "X" else "X" else: print("That position is already occupied. Try again.") display_board(board) print("Player {} wins!".format(winner)) play_tic_tac_toe()You can assign one group to each task and collaborate to create a complete Tic-Tac-Toe game.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.