Dynamic puzzle in java artificial intelligence

Technology

Dynamic puzzle in java artificial intelligence

dynamic puzzle in java with artificial intelligence solves the puzzle automatically with path in depth

Dynamic puzzle in java artificial intelligence
Dynamic puzzle in java artificial intelligence

dynamic puzzle in java with artificial intelligence solves the riddle automatically with path in depth, is a project that I had to do while studying my career in computer engineering and systems at the University of Harvard in the field of data structures where I had to perform the game with artificial intelligence and when solving it it had to show the route in depth and the binary tree.



the condition that he asked us was to read an entry pad where the main configuration was to assemble the puzzle (1,2,3,4,5,6) and then solve the exit to the end with the armed tree and the route.


The first thing we must do is create a package or folder called puzzle and another called images, as we see in the following image:


Dynamic puzzle in java artificial intelligence code structure
inside the puzzle folder, we create a class called Arbol inside this class we place the following code:







package Puzzle;

import imagenes.Puzzle;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.XMLOutputter;

public class Arbol implements Cloneable,Runnable {

    // Lista de tipo nodo creada para obtener el camino de la busqueda
    public ArrayList camino;
    // Se declara una lista de tipo nodo la cual contendr� los nodos abiertos
    // es decir los nodos que aun no se han recorrido
    ArrayList abiertos;
    // Se declara una lista de tipo nodo la cual contendrq
    // los nodos que han sido recorridos
    // es decir, los nodos a los cuales se les han revisado los sucesores
    ArrayList cerrados;
    // Se declara una lista de tipo nodo que contendr�
    // los sucesores obtenidos en cada busqueda
    ArrayList sucesores;
    //Se declara una lista de tipo element que contendra 
    // los elementos para forma el archivo xml
    LinkedList datos = new LinkedList();
    //variable de tipo int que contendra la secuencia de los nodos
    int secuencia=0;

    public Arbol() {
    }

    /**
     * M�todo que realiza la b�squeda por anchura
     *
     * @author https://www.mbajava.com/
     * @author mbajava.com
     *
     * @param inicial estado inicial del nodo
     *
     */
    public Node busquedaAnchura(Node inicial) {
        System.out.println("/***********Busqueda por anchura***********/\n");

        // Se declara una variable q de tipo Cola
        Queue q = new LinkedList();

        // Se inicializan las listas de abiertos y
        // cerrados para asegurar que sean unicas
        // dentro de la b�squeda
        abiertos = new ArrayList();
        cerrados = new ArrayList();

        // Variable booleana que indica si ya se lleg� a la soluci�n o no
        boolean esSolucion = false;

        // Se adiciona a la Cola el estado inicial del nodo
        q.add(inicial);

        // Se adiciona a abiertos el estado inicial del nodo,
        // es decir el nodo con el cual se
        // comenzar� la iteracion
        abiertos.add(inicial);

        // Se llama el metodo printNode para imprimir el nodo,
        // en este caso se pasa el nodo inicial
        // y el padre nulo por ser el nodo Raiz
        printNode(inicial, null);

        // Se realiza un bucle mientras la Cola no est� vacia y
        // la variable esSolucion no sea verdadera
        while (!q.isEmpty() && esSolucion != true) {

            // Se declara una variable de tipo nodo, se le asigna el primir
            // objeto
            // de la Cola y al mismo tiempo
            // este elemento de la cola es eliminado
            Node n = (Node) q.remove();

            // Se inicializa la lista sucesores para asegurar que sea
            // unica en el metodo de busqueda
            sucesores = new ArrayList();

            // Se obtiene los sucesores del nodo n
            sucesores = n.sucesoresNodos(n);
            // Se realiza un foreach para recorrer los sucesores
            for (Node s : sucesores) {
                // Se verifica que el sucesor s no se encuentre en
                // las listas de abiertos y cerrados
                if (s != null) {
                    if (!abiertos.contains(s) && !cerrados.contains(s)) {

                        // Si la validacion se cumple se adiciona el nodo s
                        // a la lista de abiertos
                        // evitando asi crear sucesores que realicen el mismo
                        // movimiento
                        abiertos.add(s);

                        // Se llama al metodo que imprime el nodo s
                        // con su respectivo nodo padre
                        printNode(s, s.papa);

                        // Se valida si el nodo s es una posible solucion
                        if (s.esEstadoFinal(s.getL1())) {

                            // Si s es solucion el estado de la
                            // variable esSolucion a verdadero
                            esSolucion = true;

                            // Se llama al metodo camino y se envia por parametros
                            // el nodo s

                            return s;
                            // camino(s);

                            // Se realiza un break para salirse del forEach

                        }
                        // Se adiciona el nodo s a la Cola
                        q.add(s);
                    }

                }

            }
            // Se adiciona a la lista de cerrados el nodo que se
            // encuentra en la posicion 0 de la lista de abiertos
            // porque ya ha sido recorrido
            cerrados.add(abiertos.get(0));

            // Se remueve el nodo en la posicion 0 de dicha lista porque
            // ha pasado a la lista de cerrados
            // es decir, ya ha sido recorrido
            abiertos.remove(0);
        }
        System.out.println("Numero de movimientos totales c: " + cerrados.size());
        System.out.println("Numero de movimientos totales a: " + abiertos.size());
        System.out.println("\n------Termina la b�squeda------\n");

        return null;
    }

    /**
     * M�todo que realiza la b�squeda por profundidad
     *
     * @author https://www.mbajava.com/
     * @author https://www.mbajava.com/
     *
     * @param inicial estado inicial del nodo
     */
    public Node busquedaProfundidad(Node inicial) {
        System.out.println("/***********Busqueda por profundidad***********/\n");

        // Se declara una variable s de tipo Pila y se inicializa
        Stack s = new Stack();

        // Se inicializan las listas de abiertos y cerrados
        // para asegurar que sean unicas
        // dentro de la b�squeda
        abiertos = new ArrayList();
        cerrados = new ArrayList();

        // Se adiciona a abiertos el nodo inicial,
        // es decir el nodo con el cual se
        // comenzar� la iteracion
        abiertos.add(inicial);

        // Se adiciona a la Pila el nodo inicial
        s.push(inicial);

        // Se llama el metodo printNode para imprimir el nodo,
        // en este caso se pasa el nodo inicial
        // y el padre nulo por ser el nodo Raiz
        printNode(inicial, null);

        // Se declara una variable nodo n y se le asigna
        // el primer elemento de la Pila, en este caso
        // el estado inicial
        Node n = (Node) s.peek();

        // Se realiza un bucle mientras la Pila no este vacia y
        // mientras n no sea un estado final (para esto se llama el
        // metodo esEstadoFinal enviando por parametros las dos listas del nodo)
        while (!s.isEmpty() && !n.esEstadoFinal(n.getL1())) {

            // Se declara una variable hijo de tipo nodo y se inicializa en null
            Node hijo = null;

            // Se verifica que el nodo n no se encuentre nulo
            if (n != null) {
                // si se cumple la validacion anterior se realiza un
                // forEach para recorrer los sucesores de n
                for (Node a : n.sucesoresNodos(n)) {
                    if (a != null) {
                        // Se valida que el sucesor a no se encuentre
                        // en la lista de abiertos y cerrados
                        if (!abiertos.contains(a) && !cerrados.contains(a)) {

                            // Si se cumple la condicion anterior se asigna el valor
                            // a a la variable hijo
                            hijo = a;

                            // Se adiciona el nodo a a la lista de abiertos
                            abiertos.add(a);

                            // Se realiza un break para que solo evalue el primer
                            // sucesor del nodo n y realice
                            // la busqueda por profundidad
                            break;
                        }
                    }
                }
                // Se verifica que la variable hijo no sea nula
                if (hijo != null) {

                    // Si se cumple la condicion anterior se llama al metodo
                    // printNode para que imprima el nodo hijo
                    // con su respectivo nodo padre
                    printNode(hijo, hijo.papa);

                    // Se adiciona el nodo hijo a la pila
                    s.push(hijo);
                } else {
                    // Si la condicion if no se cumple se elimina el primer
                    // elemento de la pila
                    s.pop();
                }

                // Se verifica que la lista de abiertos no este vacia, esta
                // validacion es necesaria
                // ya que al llegar al ultimo elemento abiertos va a estar vacio
                // y generaria una excepcion de desbordamiento
                if (!abiertos.isEmpty()) {

                    // Se adiciona a la lista de cerrados el primer nodo de la
                    // lista de abiertos indicando que este elemto
                    // ya fue recorrido
                    cerrados.add(abiertos.get(0));

                    // Se elimina el primer elemento de la lista de abiertos
                    // porque ya fue recorrido
                    abiertos.remove(0);
                }
                // Se verifica que la pila no se encuentre vacia, esta
                // validacion es necesaria porque en pasos anteriores
                // se esta eliminando de la pila y si llega vacia generaria una
                // excepcion
                if (!s.isEmpty()) {
                    // Si se cumple la validacion anterior se asigna el primer
                    // elemento de la pila a la variable n
                    n = (Node) s.peek();
                }
            }
        }
        // Se llama al metodo camino y se envia por parametros el nodo s
        System.out.println("Numero de movimientos totales: " + abiertos.size() + cerrados.size());
        System.out.println("\n------Termina la b�squeda------\n");
    
        return n;

    }
 public Node busquedaAEstrella2(Node inicial) throws IOException {
        // Se inicializan las listas de abiertos y cerrados
        // para asegurar que sean unicas
        // dentro de la b�squeda
        Puzzle pu= new Puzzle();
        abiertos = new ArrayList();
        cerrados = new ArrayList();

        Node x = inicial;
      //  System.out.println("padre");
        
     datos=  pu.printNode(x, null,4);
     printNode(x, null);
        for (Node sucesor : x.sucesoresNodos(x)) {
            if (sucesor != null) {
                x.listaSucesores.add(sucesor);
            }
        }
        abiertos.add(x);
        boolean fallo = false;

        while (!x.esEstadoFinal(x.getL1()) && fallo != true) {
            if (abiertos.isEmpty()) {
                fallo = true;
                System.out.println("ERROR: La lista de abiertos est� vacia");
            } else {
                Node m = x;
                if (m.esEstadoFinal(m.getL1())) {
                    camino(m);
                    break;
                } else {
                    boolean b = false;
                    for (Node nprima : m.sucesoresNodos(m)) {
                        // Bandera implementacion codigo del cuaderno
                        if (nprima != null) {
                            for (int i = 0; i < abiertos.size(); i++) {
                                if (abiertos.get(i).getL1().equals(nprima.getL1())) {
                                    b = true;
                                    if ((Integer) nprima.getL2().get(0) < (Integer) abiertos.get(i).getL2().get(0)) {
                                        Node copia = abiertos.get(i);
                                         //    printNode(copia,    copia.papa);
                                        copia.papa = m;
                                        copia.getL2().set(0, nprima.getL2().get(0));
                                        copia.getL2().set(2, ((Integer) nprima.getL2().get(0) + (Integer) copia.getL2().get(1)));
                                        abiertos.remove(abiertos.get(i));
                                        abiertos.add(copia);
                                        break;
                                    }
                                }
                            }
                            if (b != true) {
                                ArrayList temp = (ArrayList) cerrados.clone();
                                for (int i = 0; i < temp.size(); i++) {
                                    Node copia = temp.get(i);
                                    if (copia.getL1().equals(nprima.getL1())) {
                                        b = true;
                                        if ((Integer) nprima.getL2().get(0) < (Integer) copia.getL2().get(0)) {
                                            cerrados.remove(copia);
                                            nprima.listaSucesores = copia.listaSucesores;
                                            cerrados.add(nprima);
                                            recursionCambioGDeN(nprima);
                                        }
                                        break;
                                    }
                                }
                            }
                            if (b != true) {
                                for (Node hijo : nprima.sucesoresNodos(nprima)) {
                                    if (hijo != null) {
                                        nprima.listaSucesores.add(hijo);
                                    }
                                }
                                abiertos.add(nprima);
                            }
                            b = false;
                            m.listaSucesores.add(nprima);
                        }
                    }
                }
                //Se movieron de la linea donde se asigna x
                abiertos.remove(x);
                cerrados.add(m);
            }
            calcularMenorF(abiertos);
            if (!abiertos.isEmpty()) {

                x = abiertos.get(0);
                //printNode(x, x.papa);
            } else {
                fallo = true;
            }
        }
        System.out.println("N�mero de movimientos entre cerrados: " + cerrados.size());
        System.out.println("N�mero de movimientos entre abiertos: " + abiertos.size());
   //  camino(x);
     return x;
    }
    public void busquedaAEstrella(Node inicial) throws IOException {
        // Se inicializan las listas de abiertos y cerrados
        // para asegurar que sean unicas
        // dentro de la b�squeda
        Puzzle pu= new Puzzle();
        abiertos = new ArrayList();
        cerrados = new ArrayList();

        Node x = inicial;
      //  System.out.println("padre");
        
     datos=  pu.printNode(x, null,4);
     //printNode(x, null);
        for (Node sucesor : x.sucesoresNodos(x)) {
            if (sucesor != null) {
                x.listaSucesores.add(sucesor);
            }
        }
        abiertos.add(x);
        boolean fallo = false;

        while (!x.esEstadoFinal(x.getL1()) && fallo != true) {
            if (abiertos.isEmpty()) {
                fallo = true;
                System.out.println("ERROR: La lista de abiertos est� vacia");
            } else {
                Node m = x;
                if (m.esEstadoFinal(m.getL1())) {
                    camino(m);
                    break;
                } else {
                    boolean b = false;
                    for (Node nprima : m.sucesoresNodos(m)) {
                        // Bandera implementacion codigo del cuaderno
                        if (nprima != null) {
                            for (int i = 0; i < abiertos.size(); i++) {
                                if (abiertos.get(i).getL1().equals(nprima.getL1())) {
                                    b = true;
                                    if ((Integer) nprima.getL2().get(0) < (Integer) abiertos.get(i).getL2().get(0)) {
                                        Node copia = abiertos.get(i);
                                         //    printNode(copia,    copia.papa);
                                        copia.papa = m;
                                        copia.getL2().set(0, nprima.getL2().get(0));
                                        copia.getL2().set(2, ((Integer) nprima.getL2().get(0) + (Integer) copia.getL2().get(1)));
                                        abiertos.remove(abiertos.get(i));
                                        abiertos.add(copia);
                                        break;
                                    }
                                }
                            }
                            if (b != true) {
                                ArrayList temp = (ArrayList) cerrados.clone();
                                for (int i = 0; i < temp.size(); i++) {
                                    Node copia = temp.get(i);
                                    if (copia.getL1().equals(nprima.getL1())) {
                                        b = true;
                                        if ((Integer) nprima.getL2().get(0) < (Integer) copia.getL2().get(0)) {
                                            cerrados.remove(copia);
                                            nprima.listaSucesores = copia.listaSucesores;
                                            cerrados.add(nprima);
                                            recursionCambioGDeN(nprima);
                                        }
                                        break;
                                    }
                                }
                            }
                            if (b != true) {
                                for (Node hijo : nprima.sucesoresNodos(nprima)) {
                                    if (hijo != null) {
                                        nprima.listaSucesores.add(hijo);
                                    }
                                }
                                abiertos.add(nprima);
                            }
                            b = false;
                            m.listaSucesores.add(nprima);
                        }
                    }
                }
                //Se movieron de la linea donde se asigna x
                abiertos.remove(x);
                cerrados.add(m);
            }
            calcularMenorF(abiertos);
            if (!abiertos.isEmpty()) {

                x = abiertos.get(0);
                //printNode(x, x.papa);
            } else {
                fallo = true;
            }
        }
        System.out.println("Numero de movimientos entre cerrados: " + cerrados.size());
        System.out.println("Numero de movimientos entre abiertos: " + abiertos.size());
     camino(x);
    }

    
    // LLamar metodo que es recursivo
    public ArrayList calcularMenorF(ArrayList listaAbiertos) {

        Collections.sort(listaAbiertos);
        return listaAbiertos;
    }

    public void recursionCambioGDeN(Node node) {
        if (node.listaSucesores.size() == 0 && !node.listaSucesores.isEmpty()) {
            for (int i = 0; i < node.listaSucesores.size(); i++) {
                Node suc = node.listaSucesores.get(i);
                if (abiertos.remove(suc)) {
                    int pesoMov = (Integer) suc.getL2().get(0) - (Integer) suc.papa.getL2().get(1);
                    suc.getL2().set(0, (Integer) node.getL2().get(0) + pesoMov);
                    suc.getL2().set(2, (Integer) suc.getL2().get(0) + (Integer) suc.getL2().get(1));
                    suc.papa = node;
                    abiertos.add(suc);
                } else if (cerrados.remove(suc)) {
                    int pesoMov = (Integer) suc.getL2().get(0) - (Integer) suc.papa.getL2().get(1);
                    suc.getL2().set(0, (Integer) node.getL2().get(0) + pesoMov);
                    suc.getL2().set(2, (Integer) suc.getL2().get(0) + (Integer) suc.getL2().get(1));
                    suc.papa = node;
                    cerrados.add(suc);
                    recursionCambioGDeN(suc);
                }
            }
        }
    }

    /**
     * Metodo que imprime el camino de acuerdo a la busqueda que lo invoque
     *
     * @author https://www.mbajava.com/
     * @author https://www.mbajava.com/
     *
     * @param nodoFinal recibe el nodo objetivo o el nodo respectivo al estado
     * final
     */
    public void camino(Node nodoFinal) throws IOException {
        datos.clear();

        // Se verifica que la variable nodoFinal no sea nula
        if (nodoFinal != null) {

            // Si la validacion anterior se cumple, se declara la variable
            // nodoEvaluado de tipo nodo
            // y se le asigna el valor de nodoFinal
            Node nodoEvaluado = nodoFinal;

            // Se inicializa la variable camino
            camino = new ArrayList();
            System.out.println("\nEl mejor camino es:\n ");

            // Se realiza un bucle mientras el padre del nodo evaluado no sea
            // nulo
            while (nodoEvaluado.papa != null) {
                // Si la validacion anterior se cumple se adiciona el nodo
                // evaluado a la lista camino
                camino.add(nodoEvaluado);

                // Se reasigna el valor de nodoEvaluado por el padre de dicho
                // nodo
                nodoEvaluado = nodoEvaluado.papa;
            }
            // Se verifica que el nodo padre del nodo evaluado es igual a null
            // para indicar que es el nodo raiz
            if (nodoEvaluado.papa == null) {

                // Se adiciona el nodoEvaluado a la lista camino
                camino.add(nodoEvaluado);
            }
            // Se llama al metodo impimir camino enviando como parametro la
            // lista de nodos camino
            imprimirCamino(camino);
        }
    }

    /**
     * Metodo que imprime el nodo enviado por parametros,su nodo padre y su
     * respectivo movimiento
     *
     * @author https://www.mbajava.com/
     * @author https://www.mbajava.com/
     *
     * @param n : es el nodo evaluado
     * @param papa : es el padre del nodo evaluado
     */
    private void printNode(Node n, Node papa) {
        int temp0=0;
            int temp1=0;
            int temp2=0;
                int temp3=0;
                int dato1=0;
                   int dato2=0;
                    
        // se crea el elemento inicial del grafo
        Element root1 = new Element("Grafo");
        // se adiciona el elemento a la lista de datos para ir formando el archivo xml 
        datos.add(root1);
        // Se verificaque el nodo padre sea diferente de nulo
        if (papa != null) {
            if (!papa.getL2().isEmpty() && papa.getL2().size() > 3 && papa.getL2().get(3) != null) {
                Object[][] matriz = (Object[][]) papa.getL2().get(3);
                Object[][] matrizHijo = (Object[][]) n.getL2().get(3);
                System.out.println("Papa");
                
                for (int i = 0; i < matriz.length; i++) {
                    for (int j = 0; j < matriz[0].length; j++) {
                        System.out.print(matriz[i][j]);
                    }
                    System.out.println();
                }
       
            
                   System.out.println("Hijo");
boolean estado= true;
                for (int i = 0; i < matrizHijo.length; i++) {
                    for (int j = 0; j < matrizHijo[0].length; j++) {
                      
                  System.out.print(matrizHijo[i][j]);
                       
                        if (matrizHijo[i][j] != matriz[i][j]) {
                            if(estado){
                          //  System.out.println("boton " + i + j);
                            temp0=i;
                              temp1=j;
                             estado= false;
                            }else
                            {
                                // System.out.println("boton " + i + j);
                           temp2=i;
                            temp3=j;
                             estado= true;
                            }
                        }
                    }
                    System.out.println();
                }
             //   Juego ju =new Juego();
                System.out.println("temporales "+temp0+temp1 +temp2+temp3);
               if(temp0==0 && temp1==0)
                        dato1=1;
               if(temp0==0 && temp1==1)
                        dato1=2;
                 if(temp0==0 && temp1==2)
                        dato1=3;
                  if(temp0==1 && temp1==0)
                        dato1=4;
                   if(temp0==1 && temp1==1)
                        dato1=5;
                    if(temp0==1 && temp1==2)
                        dato1=6;
                        if(temp0==2 && temp1==0)
                        dato1=7;
                          if(temp0==2 && temp1==1)
                        dato1=8;
                            if(temp0==2 && temp1==2)
                        dato1=9;
                          
                                
                             
               
                              
                              
                              
                          if(temp2==0 && temp3==0)
                        dato2=1;
               if(temp2==0 && temp3==1)
                        dato2=2;
                 if(temp2==0 && temp3==2)
                        dato2=3;
                  if(temp2==1 && temp3==0)
                        dato2=4;
                   if(temp2==1 && temp3==1)
                        dato2=5;
                    if(temp2==1 && temp3==2)
                        dato2=6;
                        if(temp2==2 && temp3==0)
                        dato2=7;
                          if(temp2==2 && temp3==1)
                        dato2=8;
                            if(temp2==2 && temp3==2)
                        dato2=9;
//               tre               if(matrizHijo[temp0][temp1]==0){
//                                 ju.cambiar2(temp0,temp1);  
//                              }
//                              else{
//                                  ju.cambiar2(temp1,temp0);  
//                              }
                        
                                           
                System.out.println();
            } else {
                System.out.println("Papa " + papa.getL1() + " con movimiento --> "
                        + n.getMovimiento() + " llega al hijo " + n.getL1() + " g,h,f" + n.getL2());
                conectarNodos(n, papa);
            }
        } else {
            // Si no se cumple la verificacion del if est� indicando que es el
            // nodo raiz
            System.out.println("Raiz del grafo" + n.getL1() + " g,h,f " + n.getL2().get(3));
            // Se crea el elemento raiz con el atributo movimiento
            //y el texto correspondiente
            Element item1 = new Element("Nodo_raiz");
            item1.setText("" + n.getL1());
            datos.add(item1);
        }

    }

   //metodo que se encarga de conectar los nodos que forman el archivo XML
    public void conectarNodos(Node n, Node padre) {
        Element item2 = null;
        secuencia++;
        for (int i = 1; i < datos.size(); i++) {
            if (datos.get(i).getText().equals("" + padre.getL1())) {
                item2 = new Element("Nodo");
                item2.setAttribute("movimiento", "" + n.getMovimiento());
                 item2.setAttribute("secuencia", "" + secuencia);
                item2.setText("" + n.getL1());
            }
            if (item2 != null) {
                if (!datos.get(i).getText().equals("" + item2.getText())) {
                    datos.get(i).addContent(item2);
                    datos.add(item2);
                    item2 = null;
                }
            }
        }
    }

    public void generarXML(String url) {
        datos.get(0).addContent(datos.get(1));
        /*
         * for (int i = 1; i < datos.size(); i++) {
         * datos.get(0).addContent(datos.get(i)); }
         */
        XMLOutputter outputter = new XMLOutputter();

        try {
            outputter.output(new Document(datos.get(0)), new FileOutputStream(url));
        } catch (Exception e) {
            System.out.print(e.getMessage());

        }

    }

    /**
     * Metodo que imprime el camino desde el nodo raiz hasta el nodo objetivo y
     * sus respectivos movimientos
     *
     * @author https://www.mbajava.com/
     * @author https://www.mbajava.com/
     *
     * @param camino : lista que contiene los nodos desde el nodo objetivo o
     * nodo final hasta el nodo raiz
     */
    public void imprimirCamino(ArrayList camino) throws IOException {

        // Se realiza un bucle que recorra la lista descendentemente para
        // imprimir los nodos desde la raiz
        // hasta el nodo final o nodo objetivo
  
  Puzzle pu = new Puzzle( );
        int tamano = camino.size();
          
        for (int i = tamano - 1; i >= 0; i--) {
            pu.printNode(camino.get(i), camino.get(i).papa,i);
        }
        System.out.println();
         pu.setVisible(true);
        System.out.println("Numero de movimientos del camino: " + camino.size());
        for (int j = 0; j < pu.lista.size(); j++) {
            System.out.println(pu.lista.get(j));
        }
 
       pu.cambiar3(pu.lista);
         
       
            pu.setVisible(true);
       
    }
    
    
    
        /***
     *este metodo genera una archivo xml de la estructura del grafo actual 
     *@author Juan Carlos Vargas 
     * @param url url del archivo XML
     */
    public void generateXML(String url) {
        XMLGenerator xml = new XMLGenerator();

        for (Node node : cerrados) {            
            xml.addNodeAndCreateArc(node);
        }

        for (Node node : abiertos) {            
            xml.addNodeAndCreateArc(node);
        }

        xml.addRoad(this.camino);

        XMLGenerator.createFile(url, xml);

    }

    @Override
    public void run() {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}




then in the same folder we created another class called juego:





/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Puzzle;

import java.awt.Label;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

/**
 *
 * @author mbajava.com
 */
public class Juego implements Runnable {

    public LinkedList lista = new LinkedList();
    public int[] cartas;
    int j = -1;
    int[] dato33;
    int contador;
    String[] dato23;
    public JButton jb = new JButton();
    public JButton m = new JButton();
    public JButton uno;
    public JButton dos;
    public JButton tres;
    public JButton cuatro;
    public JButton cinco;
    public JButton seis;
    public JButton siete;
    public JButton ocho;
    public JButton nueve;
    public JButton diez;
    public JButton once;
    public JButton doce;
    public JButton trece;
    public JButton catorce;
    public JButton quince;
    public JButton vacio;
    public JLabel label = new JLabel();

    public Juego() {
    }

    public Juego(JButton uno1, JButton dos2, JButton tres3, JButton cuatro4, JButton cinco5, JButton seis6, JButton siete7, JButton ocho8, JButton nueve9, JButton diez10, JButton once11, JButton doce12, JButton trece13, JButton catorce14, JButton quince15, JButton vacio1, int[] dato11) throws FileNotFoundException, IOException {
        BufferedReader reader = new BufferedReader(new FileReader("entrada.txt"));
        jb = vacio1;
        uno = uno1;
        dos = dos2;
        tres = tres3;
        cuatro = cuatro4;
        cinco = cinco5;
        seis = seis6;
        siete = siete7;
        ocho = ocho8;
        nueve = nueve9;
        diez = diez10;
        once = once11;
        doce= doce12;
        trece = trece13;
        catorce = catorce14;
        quince = quince15;
        vacio = vacio1;

        System.out.println("listo " + dato11[0]);
        int pos = 0;
        int n = 0;
        contador = 0;
        label.setText("" + contador);
        boolean p;

        String linea = reader.readLine();

        dato23 = linea.split(",");
        int tamaño = dato23.length;

        dato33 = new int[tamaño];
        for (int i = 0; i < dato23.length; i++) {
            dato33[i] = Integer.parseInt(dato23[i]);

        }
        this.cartas = dato33;
//          cartas= new int [8];
////           String dato = JOptionPane.showInputDialog("Ingrese las letras separadas por ,");
////      int [] dato33=new int [8];
////      1,2,3,4,5,6,8,7has

////        dato23 = dato.split(",");
////        for (int i = 0; i < dato23.length; i++) {
////      dato33[i]=Integer.parseInt(dato23[i]);
////          cartas[i]=dato33[i];
////            System.out.println("descompuesto " + dato23[i]);
////        }2,3,1,4,6,7,5,8
//          b,c,a,d,f,g,e,
//            cartas[0]=  dato11[0];
//
//            cartas[1]=dato11[1];
//           
//            cartas[2]=dato11[2];
//            
//           cartas[3]=dato11[3];
//           
//            cartas[4]=dato11[4];
//           
//            cartas[5]=dato11[5];
//           
//            cartas[6]=dato11[6];
//               cartas[7]=dato11[7];

//        for (int x = 0; x < 8; x++) {
//            do {
//                n = (int) (Math.random() * 8 + 1);
//                p = true;
//                for (int y = 0; y < 8; y++) {
//                    if (cartas[y] == n) {
//                        p = false;
//                        break;
//                    }
//                }
//
//            } while (p == false);
//            do {
//                pos = (int) (Math.random() * 8 + 0);
//                p = true;
//                if (cartas[pos] != 0) {
//                    p = false;
//                }
//            } while (p == false);
//            cartas[pos] = n;
//        }
//        for (int x = 0; x < 8; x++) {
//            System.out.println(cartas[x]);
//        }
if(tamaño<=8){
        uno.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen" + cartas[0] + ".jpg")));
        uno.setMnemonic(cartas[0]);
        uno.setToolTipText(Integer.toString(cartas[0]));

        dos.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen" + cartas[1] + ".jpg")));
        dos.setMnemonic(cartas[1]);
        dos.setToolTipText(Integer.toString(cartas[1]));

        tres.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen" + cartas[2] + ".jpg")));
        tres.setMnemonic(cartas[2]);
        tres.setToolTipText(Integer.toString(cartas[2]));

        cuatro.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen" + cartas[3] + ".jpg")));
        cuatro.setMnemonic(cartas[3]);
        cuatro.setToolTipText(Integer.toString(cartas[3]));

        cinco.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen" + cartas[4] + ".jpg")));
        cinco.setMnemonic(cartas[4]);
        cinco.setToolTipText(Integer.toString(cartas[4]));

        seis.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen" + cartas[5] + ".jpg")));
        seis.setMnemonic(cartas[5]);
        seis.setToolTipText(Integer.toString(cartas[5]));

        siete.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen" + cartas[6] + ".jpg")));
        siete.setMnemonic(cartas[6]);
        siete.setToolTipText(Integer.toString(cartas[6]));

        ocho.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen" + cartas[7] + ".jpg")));
        ocho.setMnemonic(cartas[7]);
        ocho.setToolTipText(Integer.toString(cartas[7]));
     nueve.setVisible(false);
     diez.setVisible(false);
     once.setVisible(false);
     doce.setVisible(false);
     trece.setVisible(false);
     catorce.setVisible(false);
     quince.setVisible(false);
     
     
    }
        
          
        else
{
         uno.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen" + cartas[0] + ".jpg")));
        uno.setMnemonic(cartas[0]);
        uno.setToolTipText(Integer.toString(cartas[0]));

        dos.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen" + cartas[1] + ".jpg")));
        dos.setMnemonic(cartas[1]);
        dos.setToolTipText(Integer.toString(cartas[1]));

        tres.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen" + cartas[2] + ".jpg")));
        tres.setMnemonic(cartas[2]);
        tres.setToolTipText(Integer.toString(cartas[2]));

        cuatro.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen" + cartas[3] + ".jpg")));
        cuatro.setMnemonic(cartas[3]);
        cuatro.setToolTipText(Integer.toString(cartas[3]));

        cinco.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen" + cartas[4] + ".jpg")));
        cinco.setMnemonic(cartas[4]);
        cinco.setToolTipText(Integer.toString(cartas[4]));

        seis.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen" + cartas[5] + ".jpg")));
        seis.setMnemonic(cartas[5]);
        seis.setToolTipText(Integer.toString(cartas[5]));

        siete.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen" + cartas[6] + ".jpg")));
        siete.setMnemonic(cartas[6]);
        siete.setToolTipText(Integer.toString(cartas[6]));

        ocho.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen" + cartas[7] + ".jpg")));
        ocho.setMnemonic(cartas[7]);
        ocho.setToolTipText(Integer.toString(cartas[7]));
             nueve.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen" + cartas[8] + ".jpg")));
        nueve.setMnemonic(cartas[8]);
        nueve.setToolTipText(Integer.toString(cartas[8]));
        
           diez.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen" + cartas[9] + ".jpg")));
        diez.setMnemonic(cartas[8]);
        diez.setToolTipText(Integer.toString(cartas[9]));
        

         once.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen" + cartas[10] + ".jpg")));
        once.setMnemonic(cartas[10]);
        once.setToolTipText(Integer.toString(cartas[10]));
        

        
         doce.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen" + cartas[11] + ".jpg")));
        doce.setMnemonic(cartas[11]);
        doce.setToolTipText(Integer.toString(cartas[11]));
        

        
        
        
         trece.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen" + cartas[12] + ".jpg")));
        trece.setMnemonic(cartas[12]);
        trece.setToolTipText(Integer.toString(cartas[12]));
        
        catorce.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen" + cartas[13] + ".jpg")));
        catorce.setMnemonic(cartas[13]);
        catorce.setToolTipText(Integer.toString(cartas[13]));
        
        
         quince.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen" + cartas[14] + ".jpg")));
        quince.setMnemonic(cartas[14]);
        quince.setToolTipText(Integer.toString(cartas[14]));
        
        }
        vacio.setMnemonic(9);

    }

    public void cambiar(JButton a, JButton b) {
        JButton tem = new JButton();
        tem.setIcon(a.getIcon());
        a.setIcon(b.getIcon());
        b.setIcon(tem.getIcon());

        tem.setMnemonic(a.getMnemonic());
        a.setMnemonic(b.getMnemonic());
        b.setMnemonic(tem.getMnemonic());

        tem.setToolTipText(a.getToolTipText());
        a.setToolTipText(b.getToolTipText());
        b.setToolTipText(tem.getToolTipText());
    }

    public synchronized void cambiar2(int j, int i) {

        JButton tem = new JButton();
        JButton a = new JButton();
//              Thread t= new Thread("Puzzle");
//              t.sleep(1000);
        JButton b = new JButton();
        //   
//                if(i==1)
//                 a=this.uno;
//               if(i==2)
//                 a=this.dos;
//                 if(i==3)
//                 a=this.tres;
//                   if(i==4)
//                 a=this.cuatro;
//                    if(i==5)
//                 a=this.cinco;
//                     if(i==6)
//                 a=this.seis;
//                      if(i==7)
//                 a=this.siete;
//                       if(i==8)
//                 a=this.ocho;
//                      if(i==0)
        a = this.vacio;
        //                 
        //                if(j==0)
        //          b=this.vacio;     
        if (j == 1) {
            b = this.uno;
        }
        if (j == 2) {
            b = this.dos;
        }
        if (j == 3) {
            b = this.tres;
        }
        if (j == 4) {
            b = this.cuatro;
        }
        if (j == 5) {
            b = this.cinco;
        }
        if (j == 6) {
            b = this.seis;
        }
        if (j == 7) {
            b = this.siete;
        }
        if (j == 8) {
            b = this.ocho;
        }
        System.out.println("movio el " + j + "con el " + i);
        tem.setIcon(a.getIcon());
        a.setIcon(b.getIcon());
        b.setIcon(tem.getIcon());

        tem.setMnemonic(a.getMnemonic());
        a.setMnemonic(b.getMnemonic());
        b.setMnemonic(tem.getMnemonic());

        tem.setToolTipText(a.getToolTipText());
        a.setToolTipText(b.getToolTipText());
        b.setToolTipText(tem.getToolTipText());

    }

    public void recibe(LinkedList hola) {
        for (int i = 0; i < hola.size(); i++) {
            this.lista.add(hola.get(i));
        }
    }

    public void cambiar3(LinkedList hola) {
        System.out.println("lista terminada");
        for (int i = 0; i < hola.size(); i++) {
            try {

                i++;

                JButton tem = new JButton();
                JButton a = new JButton();
                Thread t = new Thread("Puzzle");
                t.sleep(1000);
                JButton b = new JButton();
                //   
                //                if(i==1)
                //                 a=this.uno;
                //               if(i==2)
                //                 a=this.dos;
                //                 if(i==3)
                //                 a=this.tres;
                //                   if(i==4)
                //                 a=this.cuatro;
                //                    if(i==5)
                //                 a=this.cinco;
                //                     if(i==6)
                //                 a=this.seis;
                //                      if(i==7)
                //                 a=this.siete;
                //                       if(i==8)
                //                 a=this.ocho;
                //                      if(i==0)
                a = this.vacio;
                //                 
                //                if(j==0)
                //          b=this.vacio;     
                if (lista.get(i) == 1) {
                    b = this.uno;
                }
                if (lista.get(i) == 2) {
                    b = this.dos;
                }
                if (lista.get(i) == 3) {
                    b = this.tres;
                }
                if (lista.get(i) == 4) {
                    b = this.cuatro;
                }
                if (lista.get(i) == 5) {
                    b = this.cinco;
                }
                if (lista.get(i) == 6) {
                    b = this.seis;
                }
                if (lista.get(i) == 7) {
                    b = this.siete;
                }
                if (lista.get(i) == 8) {
                    b = this.ocho;
                }
                System.out.println("movio el " + lista.get(i - 1) + "con el " + lista.get(i));

                tem.setIcon(a.getIcon());
                a.setIcon(b.getIcon());
                b.setIcon(tem.getIcon());

                tem.setMnemonic(a.getMnemonic());
                a.setMnemonic(b.getMnemonic());
                b.setMnemonic(tem.getMnemonic());

                tem.setToolTipText(a.getToolTipText());
                a.setToolTipText(b.getToolTipText());
                b.setToolTipText(tem.getToolTipText());
            } catch (InterruptedException ex) {
                Logger.getLogger(Juego.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public JLabel botonUno() {

        if (dos.getIcon() == null) {
            cambiar(uno, dos);
            contador++;
            label.setText("" + contador);
            System.out.println("vacio boton 2");

        } else if (cuatro.getIcon() == null) {
            cambiar(uno, cuatro);
            contador++;
            label.setText("" + contador);
            System.out.println("vacio boton 4");
        }
        return label;


    }

    public JLabel botonDos() {

        if (tres.getIcon() == null) {
            cambiar(dos, tres);
            contador++;
            label.setText("" + contador);
            System.out.println("vacio boton 3");
        } else if (cinco.getIcon() == null) {
            cambiar(dos, cinco);
            contador++;
            label.setText("" + contador);
            System.out.println("vacio boton 5");
        } else if (uno.getIcon() == null) {
            cambiar(dos, uno);
            contador++;
            label.setText("" + contador);
            System.out.println("vacio boton 1");
        }

        return label;

    }

    public JLabel botonTres() {


        if (seis.getIcon() == null) {
            cambiar(tres, seis);
            contador++;
            label.setText("" + contador);
            System.out.println("vacio boton 6");
        } else if (dos.getIcon() == null) {
            cambiar(tres, dos);
            contador++;
            label.setText("" + contador);
            System.out.println("vacio boton 2");
        }
        return label;


    }

    public JLabel botonCuatro() {

        if (siete.getIcon() == null) {
            cambiar(cuatro, siete);
            contador++;
            label.setText("" + contador);
            System.out.println("vacio boton 7");
        } else if (cinco.getIcon() == null) {
            cambiar(cuatro, cinco);
            contador++;
            label.setText("" + contador);
            System.out.println("vacio boton 5");
        } else if (uno.getIcon() == null) {
            cambiar(cuatro, uno);
            contador++;
            label.setText("" + contador);
            System.out.println("vacio boton 1");
        }

        return label;

    }

    public JLabel botonCinco() {

        if (seis.getIcon() == null) {

            cambiar(cinco, seis);
            contador++;
            label.setText("" + contador);

            System.out.println("vacio boton 6");
        }
        if (dos.getIcon() == null) {
            cambiar(cinco, dos);
            contador++;
            label.setText("" + contador);
            System.out.println("vacio boton 2");
        } else if (cuatro.getIcon() == null) {
            cambiar(cinco, cuatro);
            contador++;
            label.setText("" + contador);
            System.out.println("vacio boton 4");
        } else if (ocho.getIcon() == null) {
            cambiar(cinco, ocho);
            contador++;
            label.setText("" + contador);
            System.out.println("vacio boton 8");
        }

        return label;

    }

    public JLabel botonSeis() {
        if (tres.getIcon() == null) {
            cambiar(seis, tres);
            contador++;
            label.setText("" + contador);
            System.out.println("vacio boton 3");
        } else if (cinco.getIcon() == null) {
            cambiar(seis, cinco);
            contador++;
            label.setText("" + contador);
            System.out.println("vacio boton 5");
        } else if (vacio.getIcon() == null) {
            cambiar(seis, vacio);
            contador++;
            label.setText("" + contador);
            System.out.println("vacio boton 9");
        }
        return label;
    }

    public JLabel botonSiete() {
        if (cuatro.getIcon() == null) {
            cambiar(siete, cuatro);
            contador++;
            label.setText("" + contador);
            System.out.println("vacio boton 4");
        } else if (ocho.getIcon() == null) {
            cambiar(siete, ocho);
            contador++;
            label.setText("" + contador);
            System.out.println("vacio boton 8");
        }
        return label;

    }

    public JLabel botonOcho() {

        if (siete.getIcon() == null) {
            cambiar(ocho, siete);
            contador++;
            label.setText("" + contador);
            System.out.println("vacio boton 7");
        } else if (cinco.getIcon() == null) {
            cambiar(ocho, cinco);
            contador++;
            label.setText("" + contador);
            System.out.println("vacio boton 5");
        } else if (vacio.getIcon() == null) {
            cambiar(ocho, vacio);
            contador++;
            label.setText("" + contador);
            System.out.println("vacio boton 9");
        }
        return label;
    }
    
    public JLabel botonNueve() {

        if (siete.getIcon() == null) {
            cambiar(nueve, siete);
            contador++;
            label.setText("" + contador);
            System.out.println("vacio boton 7");
        } else if (cinco.getIcon() == null) {
            cambiar(nueve, cinco);
            contador++;
            label.setText("" + contador);
            System.out.println("vacio boton 5");
        } else if (vacio.getIcon() == null) {
            cambiar(nueve, vacio);
            contador++;
            label.setText("" + contador);
            System.out.println("vacio boton 9");
        }
        return label;
    }

    public JLabel botonVacio() {

        if (seis.getIcon() == null) {
            cambiar(vacio, seis);
            contador++;
            label.setText("" + contador);
            System.out.println("vacio boton 6");
        } else if (ocho.getIcon() == null) {
            cambiar(vacio, ocho);
            contador++;
            label.setText("" + contador);
            System.out.println("vacio boton 8");
        }
        if (uno.getMnemonic() == 1 & cuatro.getMnemonic() == 4 & siete.getMnemonic() == 7 & dos.getMnemonic() == 2 & cinco.getMnemonic() == 5 & ocho.getMnemonic() == 8 & tres.getMnemonic() == 3 & seis.getMnemonic() == 6 & vacio.getMnemonic() == 9) {
            JOptionPane.showMessageDialog(null, "Numero de Nodos  " + contador);
            //         vacio.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen.jpg")));
            // JOptionPane.showMessageDialog(null, "Has Ganado"+"puntos "+contador);
            //System.exit(0);

        }
        return label;

    }

    @Override
    public void run() {
    }
}


then in the same folder we created another class called Node:






then in the same folder we created another class called PuzzleModelo



then in the same folder we created another class called Vertices:


package Puzzle;

/**
 *
 * @author https://www.mbajava.com/
 */
public class Vertices {

    private int x;          //posiciòn en x del vertice
    private int y;          //posicion en y del vertice
    private String txt;     // texto que va en la posiciòn X y Y
    private Object padre;   //el padre del vertice actual

    /**
     * Constructor
     * @param x posiciòn en x del vertice
     * @param y posicion en y del vertice
     * @param txt texto que va en la posiciòn X y Y
     * @param padre el padre del vertice actual
     */
    public Vertices(int x, int y, String txt, Object padre) {
        this.x = x;
        this.y = y;
        this.txt = txt;
        this.padre = padre;


    }

    /**
     * @return retorna la posición en x
     */
    public int getX() {
        return x;
    }

    /**
     * @param valor de la posicion en x
     */
    public void setX(int x) {
        this.x = x;
    }

    /**
     * @return retorna la posicion en y
     */
    public int getY() {
        return y;
    }

    /**
     * @param valor de la posicion en y
     */
    public void setY(int y) {
        this.y = y;
    }

    /**
     * @return retorna el texto que va en la posiciòn X y Y
     */
    public String getTxt() {
        return txt;
    }

    /**
     * @param establece el texto que va en la posiciòn X y Y
     */
    public void setTxt(String txt) {
        this.txt = txt;
    }

    /**
     * @return retorna el padre del vertice actual
     */
    public Object getPadre() {
        return padre;
    }

    /**
     * @param padre establece el padre del vertice actual
     */
    public void setPadre(Object padre) {
        this.padre = padre;
    }
}



then in the same folder we create another class called XMLGenerator:

package Puzzle;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;


/**
 *
 * @author https://www.mbajava.com/
 * @see es una representacion de la clase LibreriaBusquedas.Graph en un XML
 * se pueden agregar nodos y arcos o un nodo con referencia a su padre y la clase
 * ira constuyendo su estructura XML interna 
 */
public class XMLGenerator {

    private Element states;
    private Element nodes;
    private Element arcs;
    private Element road;

    public XMLGenerator() {
        this.states = new Element("graph");
        this.nodes = new Element("nodes");
        this.arcs = new Element("arcs");
        this.road = new Element("road");

        this.states.addContent(nodes);
        this.states.addContent(arcs);
        this.states.addContent(road);
    }

    /**
     * este metodo crea la estructura xml del grafo a partir de un nodo 
     * asignado nombre y conexiones con otros nodos 
     * 
     * su estructura final de nodo se representa de la sigueinte manera:
     * entrada:
     * 
     * Nodo:{
     *    my_id:1,
     *    l1<0>,
     *    l2
     *    parent:
     *      Nodo:{
     *          my_id:3,
     *          l1<0>,
     *          l2,
     *          movimiento:"LLenar jarra 3"
     *      }
     *  }
     * 
     * creara una estructura como la siguente:
     * 
     * 
     *     
     *       
     *     
     *     
     *       LLenar jarra 3
     *     
     *     
     *   
     * @author Juan Carlos Vargas 
     * @param node nodo de entrada con la estrucura correspondiente
     * @see LibreriaBusquedas.Graph
     * @see LibreriaBusquedas.Node
     */
    public void addNodeAndCreateArc(Node node) {
        Element xml_node = new Element("node");
        xml_node.setAttribute("id", node.getMy_id() + "");

        this.nodes.addContent(xml_node);
        
        
        String state="";
        for (Object stm : node.getL1()) {
            Element xml_state = new Element("state");
            state+=stm+",";  
 
        }
       

        for (Object stm : node.getL2()) {
            Element xml_state = new Element("state");
            state+=stm+",";  
        }
        
     
        
        state=(state.lastIndexOf(",")== state.length()-1)?state.substring(0,state.lastIndexOf(",")):state;
        
       
        xml_node.setAttribute("state",state);
        

        if (node.getPapa() != null) {
            Element xml_arc = new Element("arc");
            xml_arc.setAttribute("from", node.getPapa().getMy_id() + "");
            xml_arc.setAttribute("to", node.getMy_id() + "");
            xml_arc.setText(node.getMovimiento());
            this.arcs.addContent(xml_arc);
        }
        
      
    }
    
    

    /**
     * crea el elemento road en el xml haciendo referencia a el camino solucion 
     * @author Juan Carlos Vargas 
     * @param lst lista de nodos con el cmaino solucion 
     * @return una variable string con los id de los nodos visitados en el camino separados por 
     * @see LibreriaBusquedas.Node
     * un coma ','
     */
    public void addRoad(ArrayList lst) {
        String res = "";
        for (Node node : lst) {
            res += node.getMy_id() + ",";
        }

        res=(res.lastIndexOf(",")== res.length()-1)?res.substring(0,res.lastIndexOf(",")):res;
        
        this.road.setAttribute("nodes", res);

    }

    
    //XML
    
    /***
     * @author Juan Carlos Vargas 
     * 
     */
    public static void createFile(String url,XMLGenerator xml_g) {
        Element xml=xml_g.getRoot();
        XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
        try {
            outputter.output(new Document(xml), new FileOutputStream(url));
        } catch (Exception e) {
            e.getMessage();
        }
    }

    public static Document openFile(String url) {
        SAXBuilder builder = new SAXBuilder(false);
        Document res = null;
        try {
            res = builder.build(url);
        } catch (JDOMException ex) {
            Logger.getLogger(XMLGenerator.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(XMLGenerator.class.getName()).log(Level.SEVERE, null, ex);
        }

        return res;

    }
    
    public Element getRoot(){
        return this.states;
    }
}


then in the same folder we create another NewJFrame class called FrmVisor:


package Puzzle;

import com.mxgraph.swing.mxGraphComponent;
import com.mxgraph.view.mxGraph;
import java.awt.*;
import java.io.*;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;

/**
 *
 * @author https://www.mbajava.com/
 */
public class FrmVisor extends javax.swing.JDialog {
 LinkedList datos = new LinkedList();
    mxGraph graph;                      //se declara el elemento principal para dibujar el grafo
    mxGraphComponent graphComponent;    //se declara el panel sobre el cual sera dibujado el grafo
    LinkedList vertices;      //se declara la lista de vertices creados
    String nom;                         //se declara el nombre del archivo XML a cargar
    double numZoom = 1;
    int numero;
  BufferedReader reader = new BufferedReader(new FileReader("salida.txt"));
    /**
     *
     * @param parent propietario del frame. si es null quiere decir que no tiene dueño
     * @param modal especifica si se muestra o no el frame
     * @param nom nombre del archivo XML a cargar
     * @param zoom valor en double que incrementa o disminuye el tamano de vista de los nodos
     * @throws JDOMException se lanza cuando ocurre error al leer o escribir datos del xml
     * @throws IOException Excepción que se produce cuando se produce un error de E/S
     */
    public FrmVisor(java.awt.Frame parent, boolean modal, String nom, double zoom) throws JDOMException, IOException {
        super(parent, nom);
        initComponents();
        getContentPane().setBackground(new Color(204, 204, 255));
        getContentPane().setLayout(new BorderLayout());
        vertices = new LinkedList();
        this.nom = "jarraBusquedaProfundida";
        Zoom.setOrientation(JSlider.HORIZONTAL);
        Zoom.setMajorTickSpacing(20);
        Zoom.setMinorTickSpacing(1);
        Zoom.setPaintTicks(true);
        Zoom.setPaintLabels(true);
        Zoom.setMinimum(-50);
        Zoom.setMaximum(50);
        Zoom.setValue(0);
        Zoom.setMajorTickSpacing(10);
        Zoom.setMinorTickSpacing(2);
        Zoom.addChangeListener(new SliderListener());
        jPanelZoom.setVisible(false);
        initGUI(zoom);
        
    }

    /**
     * Metodo en el que se encarga de inicializar y cargar todos los elementos
     * de la interfaz Grafica
     * @param num valor que es aplicado al tamaño de los elementos graficados. entre 0.01 y 0.99 aleja el foco y >1.0 acerca
     * @throws JDOMException se lanza cuando ocurre error al leer o escribir datos del xml
     * @throws IOException Excepción que se produce cuando se produce un error de E/S
     */
    private void initGUI(double num) throws JDOMException, IOException {

        setSize(800, 750);              // se le asigna el tamaño al Frame
        setLocationRelativeTo(null);    // centramos en la pantalla el Frame
        graph = new mxGraph();          //instanciamos el graph para dibujar el grafo
        graphComponent = new mxGraphComponent(graph);   //se enlaza el panel grafico con el graph
        graphComponent.setPreferredSize(new Dimension(800, 750));
        graphComponent.zoomTo(num, graphComponent.isCenterZoom());  //metodo que permite aplicar zoom a los elementos graficados
        getContentPane().add(graphComponent);       // conectamos el Frame con el panel en el que se grafica
      //  cargar();       //llama al metodo encargado de de cargar el archivo XML que se deseea dibujar
     String linea = reader.readLine();
     
       dibujarNodos(linea, this.getWidth() / 2, 60, null); //metodo que se encarga de dibujar los elementos hijos del nodo raiz
    }

    
    
    
    class SliderListener implements ChangeListener {

        public void stateChanged(ChangeEvent e) {
            JSlider source = (JSlider) e.getSource();
            numZoom = source.getValue();
        }
    }

    /**
     * Metodo que se encarga de cargar el XML y obtener el elemento principal
     * para dibujar los nodos del grafo
     * @throws JDOMException
     * @throws IOException
     */
    
    public void cargar() throws JDOMException, IOException {
        SAXBuilder builder = new SAXBuilder();
        // variable Document en la cual se carga todos los datos del archivo XML especificado
        Document doc = builder.build(new FileInputStream("src\\Xml\\" + nom + "" + ".xml" + ""));
        Element root = doc.getRootElement();            //se obtiene el elemento raiz el XML
        List elementos = root.getChildren();   //Lista en la cual se cargan los elementos Hijos del elemento raiz
    //    dibujarNodos(elementos, this.getWidth() / 2, 90, null); //metodo que se encarga de dibujar los elementos hijos del nodo raiz
    }

    /**
     * Metodo que se encarga de Graficar los nodos
     * @param elementos lista de elementos hijos
     * @param x posicion en x donde se desea dibujar el nodo
     * @param y posicion en y donde se desea dibujar el nodo
     * @param padre elemento padre
     */
    public void dibujarNodos(String linea, int x, int y, Object padre) throws FileNotFoundException, IOException {

if (linea != null)
{
   // lineapadre=reader.readLine();
    
   // Aquí lo que tengamos que hacer con la línea puede ser esto
                int d = posicion(padre);

                    //se verifica si se ha asignado una nueva posicion
                    if (d != 0) {
                        // si se cumple con la condiciòn anterior se le asigna a x el nuevo valor calculado
                        x = d;
                    }

                    // se valida si la posicion X y Y no se encuentra ocupada
                    x = validarPosicion(x, y);

                    // se actualiza el elemento proncipal para dibujar
                    graph.getModel().beginUpdate();
                    Object parent = graph.getDefaultParent();

                    int tamañoTexto = (linea.length()) * 6;

                    //Se crea el vertice con el contenido del texto del hijo
                    Object v1 = graph.insertVertex(parent, null, linea, x, y, tamañoTexto, 40, "shape=ellipse;perimeter=ellipsePerimeter;strokeColor=#871F78;fillColor=#EAEAAE");

                    
                    
                    
                    //Se adiciona el nuevo vertice a la lista de vertices 
                    vertices.add(new Vertices(x, y, linea, padre));

                    
                    //Se verifica si el elemento es diferente al nodo raiz
                    if (padre != null) {
                        // se crea el arco entre el vertice padre y el vertice hijo la cual tiene la secuencia y el movimiento
                        graph.insertEdge(null, null, linea, padre, v1, "strokeColor=#871F78");

                    }
                  
                    // se finaliza la actualizaciòn
                    graph.getModel().endUpdate();

                    //se verifica si la posiciòn en X es la mitad de frame es decir el nodo raiz
                    if (x == this.getWidth() / 2) {
                        // Se modifica la posicion en x 
                        x = 50;
                    }
                 //   y=y+10;
    numero++;
                    //se hace un llamado recursivo con los hijos del nodo actual para graficarlos
                  dibujarNodos(reader.readLine(), x, (y + 50), v1);   
  
                 //  padre= linea;
   //linea = reader.readLine();
}






//        for (Element hijo : elementos) {
//
//                se verifica que el elemento sea difente al ultimo elemento del archivo XML
//                 debido a que este no se grafica
//                if (!hijo.getName().equals("Total")) {
//
//                     si se cumple la validacion anterior se verifica que en la posicion indicada
//                     no se encuentre ningun nodo graficado, si es el caso se asigna una posiciòn
//                    int d = posicion(padre);
//
//                    se verifica si se ha asignado una nueva posicion
//                    if (d != 0) {
//                         si se cumple con la condiciòn anterior se le asigna a x el nuevo valor calculado
//                        x = d;
//                    }
//
//                     se valida si la posicion X y Y no se encuentra ocupada
//                    x = validarPosicion(x, y);
//
//                     se actualiza el elemento proncipal para dibujar
//                    graph.getModel().beginUpdate();
//                    Object parent = graph.getDefaultParent();
//
//                    int tamañoTexto = (hijo.getText().length() - 1) * 6;
//
//                    Se crea el vertice con el contenido del texto del hijo
//                    Object v1 = graph.insertVertex(parent, null, hijo.getText(), x, y, tamañoTexto, 40, "shape=ellipse;perimeter=ellipsePerimeter;strokeColor=#871F78;fillColor=#EAEAAE");
//
//                    Se adiciona el nuevo vertice a la lista de vertices 
//                    vertices.add(new Vertices(x, y, hijo.getText(), padre));
//
//                    Se verifica si el elemento es diferente al nodo raiz
//                    if (padre != null) {
//                         se crea el arco entre el vertice padre y el vertice hijo la cual tiene la secuencia y el movimiento
//                        graph.insertEdge(null, null, hijo.getAttribute("secuencia").getValue() + "---" + hijo.getAttribute("movimiento").getValue()+"--"+hijo.getAttribute("ghf").getValue(), padre, v1, "strokeColor=#871F78");
//
//                    }
//                     se finaliza la actualizaciòn
//                    graph.getModel().endUpdate();
//
//                    se verifica si la posiciòn en X es la mitad de frame es decir el nodo raiz
//                    if (x == this.getWidth() / 2) {
//                         Se modifica la posicion en x 
//                        x = 100;
//                    }
//
//                    se hace un llamado recursivo con los hijos del nodo actual para graficarlos
//                    dibujarNodos(hijo.getChildren(), x, (y + 100), v1);
//                }
//            }
//        }
    }
    
    /**
     * Metodo que se encarga de calcular la nueva posiciòn de un nodo si ya
     * existe uno en esta posiciòn
     * @param x posiciòn en x de un nodo
     * @param y posiciòn en y de un nodo
     * @return x es el nuevo valor de x .
     */
    public int validarPosicion(int x, int y) {
        //se recorre la lista de vertices
        for (Vertices v : vertices) {
            //se verifica si ya existe un nodo en esta posiciòn
            if (v.getX() == x && v.getY() == y) {
                // si se cumple con la condiciòn anterior  se a signa una nueva posiciòn a x
                int newP = x + 400;
                // retorna la nueva posicion de x
                return newP;
            }
        }
        //devuelve el valor original de x si no hay ningun nodo en esa posiciòn
        return x;
    }

    /**
     * Metodo que se encarga de asignar la posicion a un nodo dependiendo de su
     * nodo hermano
     * @param padre elemento padre
     * @return xHermano es el nuevo valor de x calculado con respecto a la
     * posicion de su ultimo hermano
     */
    public int posicion(Object padre) {
        //se declara  una variable que contendra la posicion en x de un nodo
        int xHermano = 0;

        //se verifica si tiene padre
        if (padre != null) {
            //si cumple la condiciòn anterior se verifica 
            //si existen vertices en la lista de vertices
            if (vertices.size() != 0) {
                //si se cumple la condiciòn anterior se recorre la lista de vertices
                for (Vertices v : vertices) {
                    //se verifica si el  vertice actual tiene padre
                    if (v.getPadre() != null) {
                        //si se cumple la condiciòn anterior se verifica si el padre del 
                        //vertice actual es igual al padre ingresado 
                        if (v.getPadre().equals(padre)) {
                            //si se cumple la condiciòn anterior se le asigana a Xhermano
                            //la posicion en x del vertice  mas 200
                            xHermano = v.getX() + 200;
                        }
                    }
                }
                //devuelve el valor de xHermano cuando se termina la lista
                return xHermano;
            }
        }
        //devuelve 0 en caso de que no tenga padre
        return 0;

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    //                           
    private void initComponents() {

        jPanelZoom = new javax.swing.JPanel();
        Zoom = new javax.swing.JSlider();
        jButton1 = new javax.swing.JButton();
        btnZoom = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        addMouseWheelListener(new java.awt.event.MouseWheelListener() {
            public void mouseWheelMoved(java.awt.event.MouseWheelEvent evt) {
                formMouseWheelMoved(evt);
            }
        });
        addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
            public void mouseMoved(java.awt.event.MouseEvent evt) {
                formMouseMoved(evt);
            }
        });

        jPanelZoom.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jButton1.setFont(new java.awt.Font("Century", 1, 12)); // NOI18N
        jButton1.setForeground(new java.awt.Color(102, 102, 102));
        jButton1.setText("Aplicar Zoom");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanelZoomLayout = new javax.swing.GroupLayout(jPanelZoom);
        jPanelZoom.setLayout(jPanelZoomLayout);
        jPanelZoomLayout.setHorizontalGroup(
            jPanelZoomLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelZoomLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jButton1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(Zoom, javax.swing.GroupLayout.DEFAULT_SIZE, 569, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanelZoomLayout.setVerticalGroup(
            jPanelZoomLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelZoomLayout.createSequentialGroup()
                .addContainerGap(25, Short.MAX_VALUE)
                .addGroup(jPanelZoomLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(Zoom, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1)))
        );

        btnZoom.setFont(new java.awt.Font("Century", 1, 12)); // NOI18N
        btnZoom.setForeground(new java.awt.Color(102, 102, 102));
        btnZoom.setText("Zoom");
        btnZoom.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnZoomActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(0, 6, Short.MAX_VALUE)
                .addComponent(btnZoom)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanelZoom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanelZoom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(20, 20, 20)
                        .addComponent(btnZoom)))
                .addGap(0, 682, Short.MAX_VALUE))
        );

        pack();
    }//                         

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        jPanelZoom.setVisible(false);
        btnZoom.setVisible(true);
        double tam = 1 + (0.01 * numZoom);
        try {
            FrmVisor visor = new FrmVisor(new javax.swing.JFrame(), true, nom, tam);
            visor.setVisible(true);
            this.setVisible(false);
        } catch (JDOMException ex) {
            Logger.getLogger(FrmVisor.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(FrmVisor.class.getName()).log(Level.SEVERE, null, ex);
        }

    }                                        

    private void formMouseMoved(java.awt.event.MouseEvent evt) {                                
    }                               

    private void formMouseWheelMoved(java.awt.event.MouseWheelEvent evt) {                                     
        // TODO add your handling code here:
    }                                    

    private void btnZoomActionPerformed(java.awt.event.ActionEvent evt) {                                        
        jPanelZoom.setVisible(true);
        btnZoom.setVisible(false);
    }                                       

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(FrmVisor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FrmVisor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FrmVisor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FrmVisor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //

        /*
         * Create and display the dialog
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                FrmVisor dialog = null;
                try {
                    dialog = new FrmVisor(new javax.swing.JFrame(), true, "", 1);
                } catch (JDOMException ex) {
                    Logger.getLogger(FrmVisor.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IOException ex) {
                    Logger.getLogger(FrmVisor.class.getName()).log(Level.SEVERE, null, ex);
                }
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify                     
    private javax.swing.JSlider Zoom;
    private javax.swing.JButton btnZoom;
    private javax.swing.JButton jButton1;
    private javax.swing.JPanel jPanelZoom;
    // End of variables declaration                   
}

then we have formed the classes where we form the route and the trees as the puzzle, proceed to create a new package called images where we will place the images of the puzzle and the main class, we create within this folder the main class that is a derivative of NewJFrame called Puzzle:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package imagenes;

import Puzzle.*;
import java.io.*;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.XMLOutputter;

/**
 *
 * @author https://www.mbajava.com/
 */
public class Puzzle extends javax.swing.JFrame implements Runnable {
        Element root1 = new Element("Grafo");
    LinkedList datos = new LinkedList();
    Juego juego;
      BufferedReader reader = new BufferedReader(new FileReader("entrada.txt"));
    int[] dato33 = null;
    public LinkedList lista = new LinkedList();
    public JButton uno1;
    public JButton dos1;
    public JButton tres1;
    public JButton cuatro1;
    public JButton cinco1;
    public JButton seis1;
    public JButton siete1;
    public JButton ocho1;
    public JButton vacio1;
    public JButton nueve1;
    public JButton diez1;
    public JButton once1;
    public JButton doce1;
    public JButton trece1;
    public JButton catorce1;
    public JButton quince1;
    
 
   String[] dato23;
    public ArrayList camino;
    // Se declara una lista de tipo nodo la cual contendr� los nodos abiertos
    // es decir los nodos que aun no se han recorrido
    ArrayList abiertos;
    // Se declara una lista de tipo nodo la cual contendrq
    // los nodos que han sido recorridos
    
    
    // es decir, los nodos a los cuales se les han revisado los sucesores
    ArrayList cerrados;
    // Se declara una lista de tipo nodo que contendr�
    // los sucesores obtenidos en cada busqueda
    ArrayList sucesores;
    int secuencia = 0;

    public Puzzle() throws FileNotFoundException, IOException {
        initComponents();

//          String dato = JOptionPane.showInputDialog("Ingrese las letras separadas por ,");


//      1,2,3,4,5,6,8,7
//        dato23 = dato.split(",");
//        for (int i = 0; i < dato23.length; i++) {
//      dato33[i]=Integer.parseInt(dato23[i]);
//            System.out.println("descompuesto " + dato23[i]);
//        }
        //   juego.cartas=dato33;
       
       
 String linea =reader.readLine();

                dato23 = linea.split(",");
                
               
                  int tamaño= dato23.length;
                 System.out.println(tamaño);
       dato33 = new int[tamaño];
                  for (int i = 0; i < dato23.length; i++) {
                   dato33[i]=Integer.parseInt(dato23[i]);
        
        }
     //  linea = reader.readLine();
                 
//         
//         String dato = JOptionPane.showInputDialog("Ingrese las letras separadas por ,");

//        //  1,2,3,4,5,6,8,7
//        String[] dato23 = dato.split(",");
//        for (int i = 0; i < dato23.length; i++) {
//            dato33[i] = Integer.parseInt(dato23[i]);
//            //     cartas[i]=dato33[i];
//https://www.mbajava.com/
//            System.out.println("descompuesto " + dato23[i]);
//        }


        juego = new Juego(btnUno, btndos, btntres, btncuatro, btncinco, btnseis, btnsiete, btnocho,btnNueve,btnDiez,btnOnce,btnDoce,btnTrece,btnCatorce,btnQuince, btnvacio, dato33);


        // this.cambiar2(, 8);
//                  lista.add(6);
//                            lista.add(9);
//                                      lista.add(5);
//                                                lista.add(6);
//                                                this.cambiar3(lista);
         uno1 = this.btnUno;
         dos1 = this.btndos;
         tres1 = this.btntres;
         cuatro1 = this.btncuatro;
         cinco1 = this.btncinco;
         seis1 = this.btnseis;
         siete1 = this.btnsiete;
         ocho1 = this.btnocho;
         vacio1 = this.btnvacio;
         nueve1 = this.btnNueve;
         diez1= this.btnDiez;
         once1= this.btnOnce;
         doce1=this.btnTrece;
         trece1= this.btnTrece;
         catorce1= this.btnCatorce;
         quince1=this.btnQuince;
         
         
        
        //juego = new Juego(btnUno, btndos, btntres, btncuatro, btncinco, btnseis, btnsiete, btnocho, btnvacio);
//        this.setVisible(true);
//    juego.lista.add(9);
//      juego.lista.add(6);
//      
//    juego.lista.add(6);
//     juego.lista.add(3);
//    juego.cambiar3();

    }

    public  LinkedList printNode(Node n, Node papa, int xx) throws IOException {
     File f;

BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

File file = new File("salida.txt");

if (!file.exists()) {

if (file.createNewFile()) {
System.out.println("El fichero se ha creado correctamente");
} else {

System.out.println("No ha podido ser creado el fichero");
}
}


BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true), "UTF8"));



//PrintWriter wr = new PrintWriter(bw);  
Element item3= new Element("Nodo_raiz");
        JButton tem = new JButton();
        JButton a = new JButton();
  Element item1 = new Element("Nodo");
        JButton b = new JButton();
        int temp0 = 0;
        int temp1 = 0;
        int temp2 = 0;
        int temp3 = 0;
        int dato1 = 0;
        int dato2 = 0;

        // se crea el elemento inicial del grafo

        // se adiciona el elemento a la lista de datos para ir formando el archivo xml 
        datos.add(root1);
        // Se verificaque el nodo padre sea diferente de nulo
        if (papa != null) {
            if (!papa.getL2().isEmpty() && papa.getL2().size() > 3 && papa.getL2().get(3) != null) {

                Object[][] matriz = (Object[][]) papa.getL2().get(3);
                Object[][] matrizHijo = (Object[][]) n.getL2().get(3);
                System.out.println("Papa");



                System.out.println("Hijo");
                boolean estado = true;
                String dato11="";
                for (int i = 0; i < matrizHijo.length; i++) {
                    for (int j = 0; j < matrizHijo[0].length; j++) {
    dato11=dato11+matrizHijo[i][j]+"";
            item1.setText("" + matrizHijo[i][j]);
            datos.add(item1);
                        System.out.println(matrizHijo[i][j]);
                        if (matrizHijo[i][j] != matriz[i][j]) {
                            if (estado) {
                                //  System.out.println("boton " + i + j);

                                temp0 = i;
                                temp1 = j;
                                estado = false;
                            } else {

                                // System.out.println("boton " + i + j);

                                temp2 = i;
                                temp3 = j;
                                estado = true;
                                // System.out.println("temporales "+temp0+temp1 +temp2+temp3);
                                if (temp0 == 0 && temp1 == 0) {
                                    dato1 = 1;
                                }
                                if (temp0 == 0 && temp1 == 1) {
                                    dato1 = 2;
                                }
                                if (temp0 == 0 && temp1 == 2) {
                                    dato1 = 3;
                                }
                                if (temp0 == 1 && temp1 == 0) {
                                    dato1 = 4;
                                }
                                if (temp0 == 1 && temp1 == 1) {
                                    dato1 = 5;
                                }
                                if (temp0 == 1 && temp1 == 2) {
                                    dato1 = 6;
                                }
                                if (temp0 == 2 && temp1 == 0) {
                                    dato1 = 7;
                                }
                                if (temp0 == 2 && temp1 == 1) {
                                    dato1 = 8;
                                }
                                if (temp0 == 2 && temp1 == 2) {
                                    dato1 = 9;
                                }







                                if (temp2 == 0 && temp3 == 0) {
                                    dato2 = 1;
                                }
                                if (temp2 == 0 && temp3 == 1) {
                                    dato2 = 2;
                                }
                                if (temp2 == 0 && temp3 == 2) {
                                    dato2 = 3;
                                }
                                if (temp2 == 1 && temp3 == 0) {
                                    dato2 = 4;
                                }
                                if (temp2 == 1 && temp3 == 1) {
                                    dato2 = 5;
                                }
                                if (temp2 == 1 && temp3 == 2) {
                                    dato2 = 6;
                                }
                                if (temp2 == 2 && temp3 == 0) {
                                    dato2 = 7;
                                }
                                if (temp2 == 2 && temp3 == 1) {
                                    dato2 = 8;
                                }
                                if (temp2 == 2 && temp3 == 2) {
                                    dato2 = 9;
                                }


                                if ((Integer)matrizHijo[temp0][temp1] != 0) {


                                    lista.add(dato2);

                                } else {
                                    lista.add(dato1);

                                }



                            }
                        }
                    }
                    System.out.println();
                }



                
                
      
                
                
                
//wr.write(dato11);//escribimos en el archivo
//BufferedReader reader = new BufferedReader(new FileReader("nombreArchivo"));
//String linea = reader.readLine();
//while (linea != null)
//{
                
//   // Aquí lo que tengamos que hacer con la línea puede ser esto
//   wr.append(linea);
//   
//   linea = reader.readLine();
//}
                System.out.println("escribe "+dato11);
out.write(dato11+"|");
out.write("\n");
out.close();
        //ahora cerramos los flujos de canales de datos, al cerrarlos el archivo quedará guardado con información escrita

        //de no hacerlo no se escribirá nada en el archivo


 


                System.out.println();

            } else {
                System.out.println("Papa " + papa.getL1() + " con movimiento --> "
                        + n.getMovimiento() + " llega al hijo " + n.getL1() + " g,h,f" + n.getL2());
               // conectarNodos(n, papa);
            }
        } else {
            // Si no se cumple la verificacion del if est� indicando que es el
            // nodo raiz
            System.out.println("Raiz del grafo" + n.getL1() + " g,h,f " + n.getL2().get(3));
            // Se crea el elemento raiz con el atributo movimiento
            //y el texto correspondiente
            
            item3.setText("" + n.getL1());
            datos.add(item3);

        }
//  if(xx==0){
//             juego.cambiar3();  

        //  juego = new Juego(btnUno, btndos, btntres, btncuatro, btncinco, btnseis, btnsiete, btnocho, btnvacio);





        return  datos;
    }

    public LinkedList conectarNodos(Node n, Node padre) {
        Element item2 = null;
        secuencia++;
        for (int i = 1; i < datos.size(); i++) {
            if (datos.get(i).getText().equals("" + padre.getL1())) {
                item2 = new Element("Nodo");
                item2.setAttribute("movimiento", "" + n.getMovimiento());
                item2.setAttribute("secuencia", "" + secuencia);
                item2.setText("" + n.getL1());
            }
            if (item2 != null) {
                if (!datos.get(i).getText().equals("" + item2.getText())) {
                    datos.get(i).addContent(item2);
                    datos.add(item2);
                    item2 = null;
                }
            }
        }
   
        return datos;
    }
    
  public void generateXML(String url) {
        XMLGenerator xml = new XMLGenerator();

        for (Node node : cerrados) {            
            xml.addNodeAndCreateArc(node);
        }

        for (Node node : abiertos) {            
            xml.addNodeAndCreateArc(node);
        }

        xml.addRoad(this.camino);

        XMLGenerator.createFile(url, xml);

    }
 public void generarXML(String url) {
   //  System.out.println("GENERANDO DATOS");
       /// datos.get(0).addContent(datos.get(1));
        /*
         * for (int i = 1; i < datos.size(); i++) {
         * datos.get(0).addContent(datos.get(i)); }
         */
        XMLOutputter outputter = new XMLOutputter();

        try {
            outputter.output(new Document(datos.get(0)), new FileOutputStream(url));
        } catch (Exception e) {
            System.out.print(e.getMessage());

        }

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    //                           
    private void initComponents() {

        btnUno = new javax.swing.JButton();
        btndos = new javax.swing.JButton();
        btntres = new javax.swing.JButton();
        btncuatro = new javax.swing.JButton();
        btncinco = new javax.swing.JButton();
        btnseis = new javax.swing.JButton();
        btnsiete = new javax.swing.JButton();
        btnocho = new javax.swing.JButton();
        btnvacio = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        btnDiez = new javax.swing.JButton();
        btnDoce = new javax.swing.JButton();
        btnOnce = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        btnQuince = new javax.swing.JButton();
        btnNueve = new javax.swing.JButton();
        btnCatorce = new javax.swing.JButton();
        btnTrece = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenuItem2 = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        btnUno.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen1.jpg"))); // NOI18N
        btnUno.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnUnoActionPerformed(evt);
            }
        });

        btndos.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen2.jpg"))); // NOI18N
        btndos.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btndosActionPerformed(evt);
            }
        });

        btntres.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen3.jpg"))); // NOI18N
        btntres.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btntresActionPerformed(evt);
            }
        });

        btncuatro.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen4.jpg"))); // NOI18N
        btncuatro.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btncuatroActionPerformed(evt);
            }
        });

        btncinco.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen5.jpg"))); // NOI18N
        btncinco.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btncincoActionPerformed(evt);
            }
        });

        btnseis.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen6.jpg"))); // NOI18N
        btnseis.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnseisActionPerformed(evt);
            }
        });

        btnsiete.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen7.jpg"))); // NOI18N
        btnsiete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnsieteActionPerformed(evt);
            }
        });

        btnocho.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen8.jpg"))); // NOI18N
        btnocho.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnochoActionPerformed(evt);
            }
        });

        btnvacio.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnvacioActionPerformed(evt);
            }
        });

        jLabel3.setFont(new java.awt.Font("Tempus Sans ITC", 1, 36)); // NOI18N
        jLabel3.setForeground(new java.awt.Color(204, 0, 102));

        btnDiez.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen1.jpg"))); // NOI18N
        btnDiez.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDiezActionPerformed(evt);
            }
        });

        btnDoce.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen3.jpg"))); // NOI18N
        btnDoce.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDoceActionPerformed(evt);
            }
        });

        btnOnce.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen2.jpg"))); // NOI18N
        btnOnce.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnOnceActionPerformed(evt);
            }
        });

        jLabel4.setFont(new java.awt.Font("Tempus Sans ITC", 1, 36)); // NOI18N
        jLabel4.setForeground(new java.awt.Color(204, 0, 102));

        btnQuince.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen7.jpg"))); // NOI18N
        btnQuince.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnQuinceActionPerformed(evt);
            }
        });

        btnNueve.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen1.jpg"))); // NOI18N
        btnNueve.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNueveActionPerformed(evt);
            }
        });

        btnCatorce.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen4.jpg"))); // NOI18N
        btnCatorce.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCatorceActionPerformed(evt);
            }
        });

        btnTrece.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen1.jpg"))); // NOI18N
        btnTrece.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnTreceActionPerformed(evt);
            }
        });

        jMenu1.setText("File");

        jMenuItem2.setText("Automatico");
        jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem2ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem2);

        jMenuBar1.add(jMenu1);

        jMenu2.setText("Edit");
        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(517, 517, 517)
                        .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(1, 1, 1)
                                .addComponent(btnNueve, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(btnQuince, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(btnCatorce, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(btnTrece, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(5, 5, 5)))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(btnDiez, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnOnce, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnDoce, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(btnsiete, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(btnocho, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(btnvacio, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(btncuatro, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(btnUno, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(btncinco, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(btndos, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(btntres, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(btnseis, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addComponent(btnOnce, 0, 0, Short.MAX_VALUE)
                                .addComponent(btnDoce, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(btnDiez, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(btnNueve, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addComponent(btndos, 0, 0, Short.MAX_VALUE)
                                .addComponent(btntres, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(btnUno, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(btncuatro, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(btncinco, javax.swing.GroupLayout.Alignment.TRAILING, 0, 0, Short.MAX_VALUE)
                                .addComponent(btnseis, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(btnsiete, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                            .addComponent(btnocho, 0, 0, Short.MAX_VALUE)
                            .addComponent(btnvacio, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addGap(388, 388, 388))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(226, 226, 226)
                                .addComponent(btnTrece, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnCatorce, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(btnQuince, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(0, 0, Short.MAX_VALUE)))))
                .addContainerGap())
        );

        pack();
    }//                         

    private void btnUnoActionPerformed(java.awt.event.ActionEvent evt) {                                       
        // TODO add your handling code here:


        jLabel3.setText(juego.botonUno().getText());

    }                                      

    private void btncincoActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:

        jLabel3.setText(juego.botonCinco().getText());
    }                                        

    private void btnvacioActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:

        jLabel3.setText(juego.botonVacio().getText());

    }                                        

    private void btncuatroActionPerformed(java.awt.event.ActionEvent evt) {                                          
        // TODO add your handling code here:

        jLabel3.setText(juego.botonCuatro().getText());
    }                                         

    private void btndosActionPerformed(java.awt.event.ActionEvent evt) {                                       
        // TODO add your handling code here:

        jLabel3.setText(juego.botonDos().getText());
    }                                      

    private void btntresActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // TODO add your handling code here:
        jLabel3.setText(juego.botonTres().getText());
    }                                       

    private void btnseisActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // TODO add your handling code here:

        jLabel3.setText(juego.botonSeis().getText());
    }                                       

    private void btnsieteActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        jLabel3.setText(juego.botonSiete().getText());

    }                                        

    private void btnochoActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // TODO add your handling code here:
        jLabel3.setText(juego.botonOcho().getText());

    }                                       

    private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {                                           

        PuzzleModelo pu = new PuzzleModelo(dato33);
        Thread t = new Thread(pu);
        t.start();
    }                                          

    private void btnDiezActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // TODO add your handling code here:
    }                                       

    private void btnDoceActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // TODO add your handling code here:
    }                                       

    private void btnOnceActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // TODO add your handling code here:
    }                                       

    private void btnQuinceActionPerformed(java.awt.event.ActionEvent evt) {                                          
        // TODO add your handling code here:
    }                                         

    private void btnNueveActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
    }                                        

    private void btnCatorceActionPerformed(java.awt.event.ActionEvent evt) {                                           
        // TODO add your handling code here:
    }                                          

    private void btnTreceActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
    }                                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Puzzle.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Puzzle.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Puzzle.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Puzzle.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                //  new Puzzle().setVisible(true);

                Thread t = null;
                try {
                    t = new Thread(new Puzzle());
                } catch (FileNotFoundException ex) {
                    Logger.getLogger(Puzzle.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IOException ex) {
                    Logger.getLogger(Puzzle.class.getName()).log(Level.SEVERE, null, ex);
                }
                t.start();




//        pu.archivoInicial("s");

            }
        });
    }
    // Variables declaration - do not modify                     
    private javax.swing.JButton btnCatorce;
    private javax.swing.JButton btnDiez;
    private javax.swing.JButton btnDoce;
    private javax.swing.JButton btnNueve;
    private javax.swing.JButton btnOnce;
    private javax.swing.JButton btnQuince;
    private javax.swing.JButton btnTrece;
    private javax.swing.JButton btnUno;
    private javax.swing.JButton btncinco;
    private javax.swing.JButton btncuatro;
    private javax.swing.JButton btndos;
    private javax.swing.JButton btnocho;
    private javax.swing.JButton btnseis;
    private javax.swing.JButton btnsiete;
    private javax.swing.JButton btntres;
    private javax.swing.JButton btnvacio;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem2;
    // End of variables declaration                   

    public void cambiar3(LinkedList hola) {
        System.out.println("lista terminada");
        for (int j = 0; j < hola.size(); j++) {
            try {
                Thread t = new Thread("Puzzle");
                t.sleep(1000);

                if (hola.get(j) == 1) {
                    juego.botonUno();
                }
                if (hola.get(j) == 2) {
                    juego.botonDos();
                }
                if (hola.get(j) == 3) {
                    juego.botonTres();
                }
                if (hola.get(j) == 4) {
                    juego.botonCuatro();
                }
                if (hola.get(j) == 5) {
                    juego.botonCinco();
                }
                if (hola.get(j) == 6) {
                    juego.botonSeis();
                }
                if (hola.get(j) == 7) {
                    juego.botonSiete();
                }
                if (hola.get(j) == 8) {
                    juego.botonOcho();
                }
                if (hola.get(j) == 9) {
                    juego.botonVacio();
                }


                System.out.println("llego el " + hola.get(j));
            } catch (InterruptedException ex) {
                Logger.getLogger(Puzzle.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public void cambiar2(int i) {
        try {

            Thread t = new Thread("Puzzle");
            t.sleep(1000);
            if (i == 1) {
                juego.botonUno();
            }
            if (i == 2) {
                juego.botonDos();
            }
            if (i == 3) {
                juego.botonTres();
            }
            if (i == 4) {
                juego.botonCuatro();
            }
            if (i == 5) {
                juego.botonCinco();
            }
            if (i == 6) {
                juego.botonSeis();
            }
            if (i == 7) {
                juego.botonSiete();
            }
            if (i == 8) {
                juego.botonOcho();
            }
            repaint();
        } catch (InterruptedException ex) {
            Logger.getLogger(Puzzle.class.getName()).log(Level.SEVERE, null, ex);
        }


    }

    @Override
    public void run() {

        Puzzle p = null;
        try {
            p = new Puzzle();
            //  juego = new Juego(btnUno, btndos, btntres, btncuatro, btncinco, btnseis, btnsiete, btnocho, btnvacio);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Puzzle.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Puzzle.class.getName()).log(Level.SEVERE, null, ex);
        }

        p.setVisible(true);
    }
}


and finally the images for the puzzle:

Dynamic puzzle in java artificial intelligence img1 CDynamic puzzle in java artificial intelligence img1 ADynamic puzzle in java artificial intelligence img1 B

Dynamic puzzle in java artificial intelligence img1 FDynamic puzzle in java artificial intelligence img1 DDynamic puzzle in java artificial intelligence img1 E




Dynamic puzzle in java artificial intelligence img1 JDynamic puzzle in java artificial intelligence img1 GDynamic puzzle in java artificial intelligence img1 H



Dynamic puzzle in java artificial intelligence img1 MDynamic puzzle in java artificial intelligence img1 KDynamic puzzle in java artificial intelligence img1 L


Dynamic puzzle in java artificial intelligence img1 ODynamic puzzle in java artificial intelligence img1 NDynamic puzzle in java artificial intelligence img1 Ñ






Dynamic puzzle in java artificial intelligence img1 puzzle




you can also download the project by mediafire executable java click here

Post a Comment

0 Comments