Python Tkinter 四子棋游戏(5)

这就是我们如何设置的机器版本,大家有提升的方法请在评论区里评论。

def computer_move(self):
        # Improved Computer AI: Tries to place O near the player's last move
        available_squares = [(row, col) for row in range(10) for col in range(10) if self.board[row][col] == " "]
        if available_squares:
            last_move_row, last_move_col = 0, 0  # Initialize with defaults
            for row in range(10):
                for col in range(10):
                    if self.board[row][col] == self.current_player:
                        last_move_row, last_move_col = row, col
            
            nearby_squares = []

            # Check squares around the last move
            for row in range(last_move_row - 1, last_move_row + 2):
                for col in range(last_move_col - 1, last_move_col + 2):
                    if 0 <= row < 10 and 0 <= col < 10 and (row, col) in available_squares:
                        nearby_squares.append((row, col))

            # Choose a random square from nearby squares or from all available squares
            if nearby_squares:
                row, col = random.choice(nearby_squares)
            else:
                row, col = random.choice(available_squares)

            self.on_click(row, col)
            self.root.update_idletasks()  # Update the UI after the computer move

你可能感兴趣的:(Python,Tkinter,四子棋游戏,python,游戏,开发语言)