SlideShare a Scribd company logo
1 of 14
Download to read offline
DESCRIPCIÓN DE CODIGO Y INTERFAZ
   Ventana principal




   Esta es la ventana principal de nuestro programa, el escenario donde actuará el agente está
   dividido en celadas 9 horizontales y 9 verticales, botones para dibujar la partida, llegada,
   camino u obstáculo. También una ruta por defecto al presionar usar predeterminado.
   Para empezar a ejecutar se debe presionar primero listo en caso de que escogimos dibujar, el
   botón nuevo nos permitirá dibujar una nueva ruta.


   A continuación describiremos las clases utilizadas




Dentro del codigo del form1 se encuentra todo lo que se refiere a heuristica, ordenar
nodos, presentacion de resultados, expansion de nodos, asignacion de varioables, etc. A
continuación colocamos el codigo:
using   System.Collections.Generic;
using   System.ComponentModel;
using   System.Data;
using   System.Drawing;
using   System.Text;
using   System.Windows.Forms;

namespace IGU
{
    public partial class frmMain : Form
    {
        String casilla_tipo;
        PictureBox casilla_partida;
        PictureBox casilla_llegada;
        PictureBox casilla_camino;
        Nodo miPartida;
        Nodo miLlegada;
        Nodo mejor;
        Nodo alternativa;
        ArrayList arbol;
        ArrayList ruta;

         public frmMain()
         {
             InitializeComponent();
         }

         private void frmMain_Load(object sender, EventArgs e)
         {
             this.Inicializar();
         }

         private void btnSalir_Click(object sender, EventArgs e)
         {
             Application.Exit();
         }

        private void pictureBox_Click(object sender, EventArgs e)
        {
            PictureBox pbx = ((PictureBox)sender);
            if (this.casilla_partida != null || this.casilla_llegada
!= null)
            {
                if (this.casilla_tipo=="camino" ||
this.casilla_tipo=="obstaculo"){
                    if (pbx==this.casilla_partida)
                    {
                        this.casilla_partida = null;
                    }
                    if (pbx == this.casilla_llegada)
                    {
                        this.casilla_llegada = null;
                    }
                }
            }
            pbx.Tag = this.casilla_tipo;
            switch (pbx.Tag.ToString())
            {
                case "camino":
                    pbx.BackgroundImage = this.imageList.Images[0];
                    break;
case "obstaculo":
                    pbx.BackgroundImage = this.imageList.Images[1];
                    break;
                case "partida":
                    if (this.casilla_partida!=null)
                    {
                        foreach (Control c in
this.panEntorno.Controls)
                        {
                            PictureBox auxpbx = ((PictureBox)c);
                            if (auxpbx == this.casilla_partida)
                            {
                                auxpbx.Tag = "camino";
                                auxpbx.BackgroundImage =
this.imageList.Images[0];
                            }
                        }
                    }
                    this.casilla_partida = ((PictureBox)sender);
                    pbx.BackgroundImage = this.imageList.Images[2];
                    break;
                case "llegada":
                    if (this.casilla_llegada != null)
                    {
                        foreach (Control c in
this.panEntorno.Controls)
                        {
                            PictureBox auxpbx = ((PictureBox)c);
                            if (auxpbx == this.casilla_llegada)
                            {
                                auxpbx.Tag = "camino";
                                auxpbx.BackgroundImage =
this.imageList.Images[0];
                            }
                        }
                    }
                    this.casilla_llegada = ((PictureBox)sender);
                    pbx.BackgroundImage = this.imageList.Images[3];
                    break;
            }
        }

       private void pbObstaculo_Click(object sender, EventArgs e)
       {
           this.casilla_tipo = "obstaculo";
           this.pbPartida.BorderStyle = BorderStyle.None;
           this.labPartida.ForeColor = Color.Black;
           this.pbLlegada.BorderStyle = BorderStyle.None;
           this.labLlegada.ForeColor = Color.Black;
           this.pbCamino.BorderStyle = BorderStyle.None;
           this.labCamino.ForeColor = Color.Black;
           this.pbObstaculo.BorderStyle = BorderStyle.FixedSingle;
           this.labObstaculo.ForeColor = Color.Red;
       }

       private void pbCamino_Click(object sender, EventArgs e)
       {
           this.casilla_tipo = "camino";
           this.pbPartida.BorderStyle = BorderStyle.None;
           this.labPartida.ForeColor = Color.Black;
           this.pbLlegada.BorderStyle = BorderStyle.None;
this.labLlegada.ForeColor = Color.Black;
         this.pbCamino.BorderStyle = BorderStyle.FixedSingle;
         this.labCamino.ForeColor = Color.Red;
         this.pbObstaculo.BorderStyle = BorderStyle.None;
         this.labObstaculo.ForeColor = Color.Black;
     }

     private void btnDibujar_Click(object sender, EventArgs e)
     {
         this.panEntorno.Enabled = true;
         this.btnDibujar.Enabled = false;
         this.btnPredeterminado.Enabled = true;
         this.pbPartida.Visible = true;
         this.pbLlegada.Visible = true;
         this.pbCamino.Visible = true;
         this.pbObstaculo.Visible = true;
         this.labPartida.Visible = true;
         this.labLlegada.Visible = true;
         this.labCamino.Visible = true;
         this.labObstaculo.Visible = true;
         this.pbPartida.BorderStyle = BorderStyle.FixedSingle;
         this.labPartida.ForeColor = Color.Red;
         this.btnListo.Visible = true;
         this.btnEjecutar.Enabled = false;
         this.casilla_tipo = "partida";
     }

     private void btnPredeterminado_Click(object sender, EventArgs
e)
     {
         this.panEntorno.Enabled = false;
         this.btnDibujar.Enabled = true;
         this.btnPredeterminado.Enabled = false;
         this.pbPartida.Visible = false;
         this.pbLlegada.Visible = false;
         this.pbCamino.Visible = false;
         this.pbObstaculo.Visible = false;
         this.labPartida.Visible = false;
         this.labLlegada.Visible = false;
         this.labCamino.Visible = false;
         this.labObstaculo.Visible = false;
         this.btnListo.Visible = false;
         this.btnEjecutar.Enabled = true;

         //laberinto 1
         this.casilla40.Tag = "partida";
         this.casilla40.BackgroundImage = this.imageList.Images[2];
         this.casilla_partida = this.casilla40;
         this.casilla49.Tag = "llegada";
         this.casilla49.BackgroundImage = this.imageList.Images[3];
         this.casilla_llegada = this.casilla49;
         this.casilla30.Tag = "obstaculo";
         this.casilla30.BackgroundImage = this.imageList.Images[1];
         this.casilla31.Tag = "obstaculo";
         this.casilla31.BackgroundImage = this.imageList.Images[1];
         this.casilla32.Tag = "obstaculo";
         this.casilla32.BackgroundImage = this.imageList.Images[1];
         this.casilla33.Tag = "obstaculo";
         this.casilla33.BackgroundImage = this.imageList.Images[1];
         this.casilla23.Tag = "obstaculo";
         this.casilla23.BackgroundImage = this.imageList.Images[1];
this.casilla13.Tag = "obstaculo";
this.casilla13.BackgroundImage = this.imageList.Images[1];
this.casilla14.Tag = "obstaculo";
this.casilla14.BackgroundImage = this.imageList.Images[1];
this.casilla15.Tag = "obstaculo";
this.casilla15.BackgroundImage = this.imageList.Images[1];
this.casilla25.Tag = "obstaculo";
this.casilla25.BackgroundImage = this.imageList.Images[1];
this.casilla35.Tag = "obstaculo";
this.casilla35.BackgroundImage = this.imageList.Images[1];
this.casilla45.Tag = "obstaculo";
this.casilla45.BackgroundImage = this.imageList.Images[1];
this.casilla55.Tag = "obstaculo";
this.casilla55.BackgroundImage = this.imageList.Images[1];
this.casilla56.Tag = "obstaculo";
this.casilla56.BackgroundImage = this.imageList.Images[1];
this.casilla57.Tag = "obstaculo";
this.casilla57.BackgroundImage = this.imageList.Images[1];
this.casilla47.Tag = "obstaculo";
this.casilla47.BackgroundImage = this.imageList.Images[1];
this.casilla37.Tag = "obstaculo";
this.casilla37.BackgroundImage = this.imageList.Images[1];
this.casilla38.Tag = "obstaculo";
this.casilla38.BackgroundImage = this.imageList.Images[1];
this.casilla39.Tag = "obstaculo";
this.casilla39.BackgroundImage = this.imageList.Images[1];
this.casilla51.Tag = "obstaculo";
this.casilla51.BackgroundImage = this.imageList.Images[1];
this.casilla52.Tag = "obstaculo";
this.casilla52.BackgroundImage = this.imageList.Images[1];
this.casilla53.Tag = "obstaculo";
this.casilla53.BackgroundImage = this.imageList.Images[1];
this.casilla60.Tag = "obstaculo";
this.casilla60.BackgroundImage = this.imageList.Images[1];
this.casilla61.Tag = "obstaculo";
this.casilla61.BackgroundImage = this.imageList.Images[1];
this.casilla70.Tag = "obstaculo";
this.casilla70.BackgroundImage = this.imageList.Images[1];
this.casilla71.Tag = "obstaculo";
this.casilla71.BackgroundImage = this.imageList.Images[1];
this.casilla72.Tag = "obstaculo";
this.casilla72.BackgroundImage = this.imageList.Images[1];
this.casilla73.Tag = "obstaculo";
this.casilla73.BackgroundImage = this.imageList.Images[1];
this.casilla83.Tag = "obstaculo";
this.casilla83.BackgroundImage = this.imageList.Images[1];
this.casilla93.Tag = "obstaculo";
this.casilla93.BackgroundImage = this.imageList.Images[1];
this.casilla94.Tag = "obstaculo";
this.casilla94.BackgroundImage = this.imageList.Images[1];
this.casilla95.Tag = "obstaculo";
this.casilla95.BackgroundImage = this.imageList.Images[1];
this.casilla85.Tag = "obstaculo";
this.casilla85.BackgroundImage = this.imageList.Images[1];
this.casilla75.Tag = "obstaculo";
this.casilla75.BackgroundImage = this.imageList.Images[1];
this.casilla76.Tag = "obstaculo";
this.casilla76.BackgroundImage = this.imageList.Images[1];
this.casilla77.Tag = "obstaculo";
this.casilla77.BackgroundImage = this.imageList.Images[1];
this.casilla87.Tag = "obstaculo";
this.casilla87.BackgroundImage = this.imageList.Images[1];
           this.casilla88.Tag = "obstaculo";
           this.casilla88.BackgroundImage = this.imageList.Images[1];
           this.casilla89.Tag = "obstaculo";
           this.casilla89.BackgroundImage = this.imageList.Images[1];
           this.casilla79.Tag = "obstaculo";
           this.casilla79.BackgroundImage = this.imageList.Images[1];
           this.casilla69.Tag = "obstaculo";
           this.casilla69.BackgroundImage = this.imageList.Images[1];
           this.casilla59.Tag = "obstaculo";
           this.casilla59.BackgroundImage = this.imageList.Images[1];
       }

        private void btnEjecutar_Click(object sender, EventArgs e)
        {
            this.miPartida = new Nodo("partida",
this.casilla_partida.Name);
            this.miLlegada = new Nodo("llegada",
this.casilla_llegada.Name);
            this.miPartida.funcion =
this.CalcularHeuristica(this.miPartida);
            this.arbol = new ArrayList();
            this.ruta = new ArrayList();
            this.BLO();
            this.PresentarRuta();
            this.btnDibujar.Enabled = false;
            this.btnPredeterminado.Enabled = false;
            this.btnEjecutar.Enabled = false;
            this.btnNuevo.Enabled = true;
        }

       private void pbPartida_Click(object sender, EventArgs e)
       {
           this.casilla_tipo = "partida";
           this.pbPartida.BorderStyle = BorderStyle.FixedSingle;
           this.labPartida.ForeColor = Color.Red;
           this.pbLlegada.BorderStyle = BorderStyle.None;
           this.labLlegada.ForeColor = Color.Black;
           this.pbCamino.BorderStyle = BorderStyle.None;
           this.labCamino.ForeColor = Color.Black;
           this.pbObstaculo.BorderStyle = BorderStyle.None;
           this.labObstaculo.ForeColor = Color.Black;
       }

       private void pbLlegada_Click(object sender, EventArgs e)
       {
           this.casilla_tipo = "llegada";
           this.pbPartida.BorderStyle = BorderStyle.None;
           this.labPartida.ForeColor = Color.Black;
           this.pbLlegada.BorderStyle = BorderStyle.FixedSingle;
           this.labLlegada.ForeColor = Color.Red;
           this.pbCamino.BorderStyle = BorderStyle.None;
           this.labCamino.ForeColor = Color.Black;
           this.pbObstaculo.BorderStyle = BorderStyle.None;
           this.labObstaculo.ForeColor = Color.Black;
       }

       int BLO()
       {
           return BLO1(this.miPartida, double.MaxValue);
       }
int BLO1(Nodo nodo, double limite)
{
    Nodo[] sucesores;
    if (!nodo.visitado)
    {
        if (nodo.tipo == "llegada")
        {
            return 0;
        }
        sucesores = this.ExpandirNodo(nodo);
        if (sucesores.Length == 0)
        {
            return 1;
        }
        foreach (Nodo n in sucesores)
        {
            n.funcion = nodo.funcion;
            if ((n.costo + n.heuristica) > nodo.funcion)
            {
                n.funcion = n.costo + n.heuristica;
            }
        }
    }
    else
    {
        ArrayList aux_sucesores = new ArrayList();
        foreach (Object o in arbol)
        {
            Nodo n = ((Nodo)o);
            if (n.padre == nodo)
            {
                aux_sucesores.Add(n);
            }
        }

       sucesores = new Nodo[aux_sucesores.Count];
       for (int i=0; i<aux_sucesores.Count;i++)
       {
           sucesores[i] = ((Nodo)aux_sucesores[i]);
       }
   }
   Nodo[] sucesoresOrdenados = OrdenarMayorAMenor(sucesores);
   nodo.visitado = true;
   mejor = sucesoresOrdenados[0];
   if (mejor.funcion > limite)
   {
       nodo.funcion = mejor.funcion;
       this.ruta.RemoveAt(this.ruta.Count - 1);
       BLO1(nodo.padre, mejor.funcion);
   }
   if (sucesores.Length == 1)
   {
       alternativa = mejor;
   }
   else
   {
       alternativa = sucesoresOrdenados[1];
   }
   double min = alternativa.funcion;
   if (limite < min)
{
               min = limite;
           }
           if (this.ruta.Count<2)
           {
               this.ruta.Add(mejor);
           }else
           {
               if (mejor != this.ruta[this.ruta.Count - 1])
               {
                   this.ruta.Add(mejor);
               }
           }
           this.BLO1(mejor, min);
           return 0;
       }

        //Este metodo expande los sucesores de un nodo recibido
        Nodo[] ExpandirNodo(Nodo nodo)
        {
            Nodo[] sucesores = new Nodo[4];
            string mnombre = "casilla";
            int i = 0;
            int mnivel = nodo.nivel_casilla_arriba;
            int mpasillo = nodo.pasillo_casilla_arriba;
            if ((mnivel > -1) && (mpasillo > -1))
            {
                mnombre = mnombre + mnivel.ToString() +
mpasillo.ToString();
                if ((this.panEntorno.Controls[mnombre].Tag.ToString()
== "camino") || (this.panEntorno.Controls[mnombre].Tag.ToString() ==
"llegada"))
                {
                    if (nodo.padre == null)
                    {
                        Nodo nodo_arriba = new
Nodo(this.panEntorno.Controls[mnombre].Tag.ToString(), mnombre);
                        this.AgregarNodo(nodo, nodo_arriba);
                        sucesores[i] = nodo_arriba;
                        i++;
                    }
                    else
                    {
                        if (!((mnivel == nodo.padre.nivel) &&
(mpasillo == nodo.padre.pasillo)))
                        {
                            Nodo nodo_arriba = new
Nodo(this.panEntorno.Controls[mnombre].Tag.ToString(), mnombre);
                            this.AgregarNodo(nodo, nodo_arriba);
                            sucesores[i] = nodo_arriba;
                            i++;
                        }
                    }
                }
            }
            mnombre = "casilla";
            mnivel = nodo.nivel_casilla_abajo;
            mpasillo = nodo.pasillo_casilla_abajo;
            if ((mnivel > -1) && (mpasillo > -1))
            {
mnombre = mnombre + mnivel.ToString() +
mpasillo.ToString();
                if ((this.panEntorno.Controls[mnombre].Tag.ToString()
== "camino") || (this.panEntorno.Controls[mnombre].Tag.ToString() ==
"llegada"))
                {
                    if (nodo.padre == null)
                    {
                        Nodo nodo_abajo = new
Nodo(this.panEntorno.Controls[mnombre].Tag.ToString(), mnombre);
                        this.AgregarNodo(nodo, nodo_abajo);
                        sucesores[i] = nodo_abajo;
                        i++;
                    }
                    else
                    {
                        if (!((mnivel == nodo.padre.nivel) &&
(mpasillo == nodo.padre.pasillo)))
                        {
                            Nodo nodo_abajo = new
Nodo(this.panEntorno.Controls[mnombre].Tag.ToString(), mnombre);
                            this.AgregarNodo(nodo, nodo_abajo);
                            sucesores[i] = nodo_abajo;
                            i++;
                        }
                    }
                }
            }
            mnombre = "casilla";
            mnivel = nodo.nivel_casilla_izquierda;
            mpasillo = nodo.pasillo_casilla_izquierda;
            if ((mnivel > -1) && (mpasillo > -1))
            {
                mnombre = mnombre + mnivel.ToString() +
mpasillo.ToString();
                if ((this.panEntorno.Controls[mnombre].Tag.ToString()
== "camino") || (this.panEntorno.Controls[mnombre].Tag.ToString() ==
"llegada"))
                {
                    if (nodo.padre == null)
                    {
                        Nodo nodo_izquierda = new
Nodo(this.panEntorno.Controls[mnombre].Tag.ToString(), mnombre);
                        this.AgregarNodo(nodo, nodo_izquierda);
                        sucesores[i] = nodo_izquierda;
                        i++;
                    }
                    else
                    {
                        if (!((mnivel == nodo.padre.nivel) &&
(mpasillo == nodo.padre.pasillo)))
                        {
                            Nodo nodo_izquierda = new
Nodo(this.panEntorno.Controls[mnombre].Tag.ToString(), mnombre);
                            this.AgregarNodo(nodo, nodo_izquierda);
                            sucesores[i] = nodo_izquierda;
                            i++;
                        }
                    }
                }
            }
mnombre = "casilla";
            mnivel = nodo.nivel_casilla_derecha;
            mpasillo = nodo.pasillo_casilla_derecha;
            if ((mnivel > -1) && (mpasillo > -1))
            {
                mnombre = mnombre + mnivel.ToString() +
mpasillo.ToString();
                if ((this.panEntorno.Controls[mnombre].Tag.ToString()
== "camino") || (this.panEntorno.Controls[mnombre].Tag.ToString() ==
"llegada"))
                {
                    if (nodo.padre == null)
                    {
                        Nodo nodo_derecha = new
Nodo(this.panEntorno.Controls[mnombre].Tag.ToString(), mnombre);
                        this.AgregarNodo(nodo, nodo_derecha);
                        sucesores[i] = nodo_derecha;
                        i++;
                    }
                    else
                    {
                        if (!((mnivel == nodo.padre.nivel) &&
(mpasillo == nodo.padre.pasillo)))
                        {
                            Nodo nodo_derecha = new
Nodo(this.panEntorno.Controls[mnombre].Tag.ToString(), mnombre);
                            this.AgregarNodo(nodo, nodo_derecha);
                            sucesores[i] = nodo_derecha;
                            i++;
                        }
                    }
                }
            }
            int len = 0;
            foreach (object o in sucesores)
            {
                if (o != null)
                {
                    len++;
                }
            }
            Nodo[] aux_sucesores = new Nodo[len];
            for (int j = 0; j < len; j++)
            {
                aux_sucesores[j] = sucesores[j];
            }
            return aux_sucesores;
        }

        void AgregarNodo(Nodo padre, Nodo nodo)
        {
            this.AgregarNodo(padre, nodo, CalcularCosto(padre),
CalcularHeuristica(nodo));
        }

        void AgregarNodo(Nodo padre, Nodo nodo, int costo, double
heuristica)
        {
            nodo.padre=padre;
            nodo.costo=costo;
            nodo.heuristica=heuristica;
this.arbol.Add(nodo);
       }

       int CalcularCosto(Nodo nodoPadre)
       {
           return nodoPadre.costo + 1;
       }

       double CalcularHeuristica(Nodo nodo)
       {
           int a = nodo.nivel - this.miLlegada.nivel;
           int b = nodo.pasillo - this.miLlegada.pasillo;
           return Math.Sqrt(Math.Pow(a, 2) + Math.Pow(b, 2));
       }

        Nodo[] OrdenarMayorAMenor(Nodo[] sucesores)
        {
            for (int j = 1; j <= sucesores.Length; j++)
            {
                for (int i = 0; i < sucesores.Length - 1; i++)
                {
                    if (sucesores[i].funcion > sucesores[i +
1].funcion)
                    {
                        Nodo temp = sucesores[i];
                        sucesores[i] = sucesores[i + 1];
                        sucesores[i + 1] = temp;
                    }
                }
            }
            return sucesores;
        }

       void PresentarRuta()
       {
           //for (int i = 0; i < (this.ruta.Count-1); i++)
           //{
           //    for (int j=i+1;j<this.ruta.Count;j++)
           //    {
           //        if (this.ruta[i] == this.ruta[j])
           //        {
           //            this.ruta.RemoveAt(j);
           //            j--;
           //        }
           //    }
           //}
           this.timer.Start();
       }

        int indRuta;
        private void timer_Tick(object sender, EventArgs e)
        {
            Nodo n = ((Nodo)this.ruta[this.indRuta]);
            string mnombre =
"casilla"+n.nivel.ToString()+n.pasillo.ToString();
            this.panEntorno.Controls[mnombre].BackgroundImage =
this.imageList.Images[2];
            if (this.indRuta == 0)
            {
                n = this.miPartida;
            }
else
            {
                n = ((Nodo)this.ruta[this.indRuta - 1]);
            }
            mnombre = "casilla" + n.nivel.ToString() +
n.pasillo.ToString();
            this.panEntorno.Controls[mnombre].BackgroundImage =
this.imageList.Images[0];
            this.indRuta++;
            if (indRuta == this.ruta.Count)
            {
                this.timer.Stop();
                string miruta = string.Empty;
                Nodo minodo=null;
                for (int i = 0; i < this.ruta.Count; i++)
                {
                    minodo = ((Nodo)this.ruta[i]);
                    miruta = miruta + minodo.nivel.ToString() + ", " +
minodo.pasillo.ToString() + "n";
                }
                if (minodo.tipo == "llegada")
                {
                    MessageBox.Show(miruta,this.Text + " -
Resultados");
                }
                else
                {
                    MessageBox.Show("Sin SALIDA", this.Text + " -
Resultados");
                }
            }
        }

       private void btnListo_Click(object sender, EventArgs e)
       {
           this.panEntorno.Enabled = false;
           this.btnDibujar.Enabled = true;
           this.btnPredeterminado.Enabled = true;
           this.pbPartida.Visible = false;
           this.pbLlegada.Visible = false;
           this.pbCamino.Visible = false;
           this.pbObstaculo.Visible = false;
           this.labPartida.Visible = false;
           this.labLlegada.Visible = false;
           this.labCamino.Visible = false;
           this.labObstaculo.Visible = false;
           this.btnListo.Visible = false;
           this.btnEjecutar.Enabled = true;
       }

       private void btnNuevo_Click(object sender, EventArgs e)
       {
           this.Inicializar();
           this.btnDibujar.Enabled = true;
           this.btnPredeterminado.Enabled = true;
           this.btnNuevo.Enabled = false;
       }

       void Inicializar()
       {
           this.btnPredeterminado.Enabled = true;
this.pbCamino.Enabled = true;
               this.pbObstaculo.Enabled = true;
               this.pbPartida.Enabled = true;
               this.pbLlegada.Enabled = true;
               this.panEntorno.Enabled = true;
               PictureBox img = new PictureBox();
               foreach (Control c in this.panEntorno.Controls)
               {
                   img = ((PictureBox)c);
                   if (c.Size.Height == 25)
                   {
                       img.Tag = "camino";
                       img.BackgroundImage = this.imageList.Images[0];
                       img.BackgroundImageLayout = ImageLayout.Stretch;
                   }
               }
               this.casilla_camino = this.casilla00;
               this.pbCamino.Image = this.imageList.Images[0];
               this.pbObstaculo.Image = this.imageList.Images[1];
               this.pbPartida.Image = this.imageList.Images[2];
               this.pbLlegada.Image = this.imageList.Images[3];
               indRuta = 0;
           }
      }
  }


  Dentro de la clase Nodo.cs calculamos la la posición delnodo en donde se encuentra
  el agente y de los vecinos o nodos sucesores.
  A continuación el codigo la clase Nodo.cs
using     System;
using     System.Collections.Generic;
using     System.Text;
using     System.Windows.Forms;


namespace IGU
{
    class Nodo
    {
        public    Nodo padre;
        public    string tipo;
        public    int nivel;
        public    int pasillo;
        public    double funcion;
        public    int costo;
        public    double heuristica;
        public    bool visitado = false;
        public    int nivel_casilla_arriba = -1;
        public    int nivel_casilla_abajo = -1;
        public    int nivel_casilla_izquierda = -1;
        public    int nivel_casilla_derecha = -1;
        public    int pasillo_casilla_arriba = -1;
        public    int pasillo_casilla_abajo = -1;
        public    int pasillo_casilla_izquierda = -1;
        public    int pasillo_casilla_derecha = -1;

           public Nodo(string mtipo, string mnombre)
           {
this.tipo = mtipo;
            this.CalcularUbicacion(mnombre);
            this.DefinirVecinos(this.nivel, this.pasillo);
        }

        void CalcularUbicacion(string mnombre)
        {
            string mnivel = mnombre.Substring(7, 1);
            string mpasillo = mnombre.Substring(8, 1);
            this.nivel = int.Parse(mnivel);
            this.pasillo = int.Parse(mpasillo);
        }

        void DefinirVecinos(int mnivel, int mpasillo)
        {
            //casilla arriba
            if (mnivel > 0)
            {
                this.nivel_casilla_arriba = mnivel - 1;
                this.pasillo_casilla_arriba = mpasillo;
            }
            //casilla abajo
            if (mnivel < 9)
            {
                this.nivel_casilla_abajo = mnivel + 1;
                this.pasillo_casilla_abajo = mpasillo;
            }
            //casilla izquierda
            if (mpasillo > 0)
            {
                this.nivel_casilla_izquierda = mnivel;
                this.pasillo_casilla_izquierda = mpasillo - 1;
            }
            //casilla derecha
            if (mpasillo < 9)
            {
                this.nivel_casilla_derecha = mnivel;
                this.pasillo_casilla_derecha = mpasillo + 1;
            }
        }

        public double CalcularHeuristica(Nodo nodo)
        {
            return 0;
        }
    }
}

More Related Content

What's hot

What's hot (20)

Sincronizar Threads
Sincronizar ThreadsSincronizar Threads
Sincronizar Threads
 
1.2. kotlin (1)
1.2. kotlin (1)1.2. kotlin (1)
1.2. kotlin (1)
 
Java AWT Tres en Raya
Java AWT Tres en RayaJava AWT Tres en Raya
Java AWT Tres en Raya
 
Práctica Completa en Flash – ActionScript
Práctica Completa en Flash – ActionScriptPráctica Completa en Flash – ActionScript
Práctica Completa en Flash – ActionScript
 
Ejercisos condicionales 1
Ejercisos condicionales 1Ejercisos condicionales 1
Ejercisos condicionales 1
 
Programas en netbeans
Programas en netbeansProgramas en netbeans
Programas en netbeans
 
Problemas condicionales
Problemas condicionalesProblemas condicionales
Problemas condicionales
 
Python Tercera Sesion de Clases
Python Tercera Sesion de ClasesPython Tercera Sesion de Clases
Python Tercera Sesion de Clases
 
Ejercisos condicionales
Ejercisos condicionalesEjercisos condicionales
Ejercisos condicionales
 
Resumen java
Resumen javaResumen java
Resumen java
 
Problemas propuesto 1 al12
Problemas propuesto 1 al12Problemas propuesto 1 al12
Problemas propuesto 1 al12
 
Acmar trucos de visual basic(2)
Acmar   trucos de visual basic(2)Acmar   trucos de visual basic(2)
Acmar trucos de visual basic(2)
 
Problemas condicionales
Problemas condicionalesProblemas condicionales
Problemas condicionales
 
Poo 4 arraylist_implem
Poo 4 arraylist_implemPoo 4 arraylist_implem
Poo 4 arraylist_implem
 
Presentacion
PresentacionPresentacion
Presentacion
 
Ejercicio propuesto 2
Ejercicio propuesto 2Ejercicio propuesto 2
Ejercicio propuesto 2
 
Codigo ejercicios
Codigo ejerciciosCodigo ejercicios
Codigo ejercicios
 
Proyecto tres en_raya_f_inal_mathias_y_grupo
Proyecto tres en_raya_f_inal_mathias_y_grupoProyecto tres en_raya_f_inal_mathias_y_grupo
Proyecto tres en_raya_f_inal_mathias_y_grupo
 
Control jtable con base de datos
Control jtable con base de datosControl jtable con base de datos
Control jtable con base de datos
 
Control jtable con base de datos
Control jtable con base de datosControl jtable con base de datos
Control jtable con base de datos
 

More from luisfe

Reconocimiento de caracteres atravez de redes neuronales
Reconocimiento de caracteres atravez de redes neuronalesReconocimiento de caracteres atravez de redes neuronales
Reconocimiento de caracteres atravez de redes neuronalesluisfe
 
Descripcion de algoritmo
Descripcion de algoritmoDescripcion de algoritmo
Descripcion de algoritmoluisfe
 
Clustering
ClusteringClustering
Clusteringluisfe
 
Clustering
ClusteringClustering
Clusteringluisfe
 
Agente Inteligente Paper
Agente Inteligente PaperAgente Inteligente Paper
Agente Inteligente Paperluisfe
 
Agente Inteligente Ontologia y Tripletas
Agente Inteligente Ontologia y TripletasAgente Inteligente Ontologia y Tripletas
Agente Inteligente Ontologia y Tripletasluisfe
 
Agente Inteligente
Agente InteligenteAgente Inteligente
Agente Inteligenteluisfe
 
Open Innovation
Open InnovationOpen Innovation
Open Innovationluisfe
 
ReplicacióN Base De Datos
ReplicacióN  Base De DatosReplicacióN  Base De Datos
ReplicacióN Base De Datosluisfe
 
Ubuntu
UbuntuUbuntu
Ubuntuluisfe
 
Modelos De Carros
Modelos De CarrosModelos De Carros
Modelos De Carrosluisfe
 
Modelo Descrptivos Del Proceso Del Sofware
Modelo Descrptivos  Del  Proceso Del SofwareModelo Descrptivos  Del  Proceso Del Sofware
Modelo Descrptivos Del Proceso Del Sofwareluisfe
 
Mi Empresa
Mi EmpresaMi Empresa
Mi Empresaluisfe
 

More from luisfe (13)

Reconocimiento de caracteres atravez de redes neuronales
Reconocimiento de caracteres atravez de redes neuronalesReconocimiento de caracteres atravez de redes neuronales
Reconocimiento de caracteres atravez de redes neuronales
 
Descripcion de algoritmo
Descripcion de algoritmoDescripcion de algoritmo
Descripcion de algoritmo
 
Clustering
ClusteringClustering
Clustering
 
Clustering
ClusteringClustering
Clustering
 
Agente Inteligente Paper
Agente Inteligente PaperAgente Inteligente Paper
Agente Inteligente Paper
 
Agente Inteligente Ontologia y Tripletas
Agente Inteligente Ontologia y TripletasAgente Inteligente Ontologia y Tripletas
Agente Inteligente Ontologia y Tripletas
 
Agente Inteligente
Agente InteligenteAgente Inteligente
Agente Inteligente
 
Open Innovation
Open InnovationOpen Innovation
Open Innovation
 
ReplicacióN Base De Datos
ReplicacióN  Base De DatosReplicacióN  Base De Datos
ReplicacióN Base De Datos
 
Ubuntu
UbuntuUbuntu
Ubuntu
 
Modelos De Carros
Modelos De CarrosModelos De Carros
Modelos De Carros
 
Modelo Descrptivos Del Proceso Del Sofware
Modelo Descrptivos  Del  Proceso Del SofwareModelo Descrptivos  Del  Proceso Del Sofware
Modelo Descrptivos Del Proceso Del Sofware
 
Mi Empresa
Mi EmpresaMi Empresa
Mi Empresa
 

DescripcióN De Codigo Y Interfaz

  • 1. DESCRIPCIÓN DE CODIGO Y INTERFAZ Ventana principal Esta es la ventana principal de nuestro programa, el escenario donde actuará el agente está dividido en celadas 9 horizontales y 9 verticales, botones para dibujar la partida, llegada, camino u obstáculo. También una ruta por defecto al presionar usar predeterminado. Para empezar a ejecutar se debe presionar primero listo en caso de que escogimos dibujar, el botón nuevo nos permitirá dibujar una nueva ruta. A continuación describiremos las clases utilizadas Dentro del codigo del form1 se encuentra todo lo que se refiere a heuristica, ordenar nodos, presentacion de resultados, expansion de nodos, asignacion de varioables, etc. A continuación colocamos el codigo:
  • 2. using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace IGU { public partial class frmMain : Form { String casilla_tipo; PictureBox casilla_partida; PictureBox casilla_llegada; PictureBox casilla_camino; Nodo miPartida; Nodo miLlegada; Nodo mejor; Nodo alternativa; ArrayList arbol; ArrayList ruta; public frmMain() { InitializeComponent(); } private void frmMain_Load(object sender, EventArgs e) { this.Inicializar(); } private void btnSalir_Click(object sender, EventArgs e) { Application.Exit(); } private void pictureBox_Click(object sender, EventArgs e) { PictureBox pbx = ((PictureBox)sender); if (this.casilla_partida != null || this.casilla_llegada != null) { if (this.casilla_tipo=="camino" || this.casilla_tipo=="obstaculo"){ if (pbx==this.casilla_partida) { this.casilla_partida = null; } if (pbx == this.casilla_llegada) { this.casilla_llegada = null; } } } pbx.Tag = this.casilla_tipo; switch (pbx.Tag.ToString()) { case "camino": pbx.BackgroundImage = this.imageList.Images[0]; break;
  • 3. case "obstaculo": pbx.BackgroundImage = this.imageList.Images[1]; break; case "partida": if (this.casilla_partida!=null) { foreach (Control c in this.panEntorno.Controls) { PictureBox auxpbx = ((PictureBox)c); if (auxpbx == this.casilla_partida) { auxpbx.Tag = "camino"; auxpbx.BackgroundImage = this.imageList.Images[0]; } } } this.casilla_partida = ((PictureBox)sender); pbx.BackgroundImage = this.imageList.Images[2]; break; case "llegada": if (this.casilla_llegada != null) { foreach (Control c in this.panEntorno.Controls) { PictureBox auxpbx = ((PictureBox)c); if (auxpbx == this.casilla_llegada) { auxpbx.Tag = "camino"; auxpbx.BackgroundImage = this.imageList.Images[0]; } } } this.casilla_llegada = ((PictureBox)sender); pbx.BackgroundImage = this.imageList.Images[3]; break; } } private void pbObstaculo_Click(object sender, EventArgs e) { this.casilla_tipo = "obstaculo"; this.pbPartida.BorderStyle = BorderStyle.None; this.labPartida.ForeColor = Color.Black; this.pbLlegada.BorderStyle = BorderStyle.None; this.labLlegada.ForeColor = Color.Black; this.pbCamino.BorderStyle = BorderStyle.None; this.labCamino.ForeColor = Color.Black; this.pbObstaculo.BorderStyle = BorderStyle.FixedSingle; this.labObstaculo.ForeColor = Color.Red; } private void pbCamino_Click(object sender, EventArgs e) { this.casilla_tipo = "camino"; this.pbPartida.BorderStyle = BorderStyle.None; this.labPartida.ForeColor = Color.Black; this.pbLlegada.BorderStyle = BorderStyle.None;
  • 4. this.labLlegada.ForeColor = Color.Black; this.pbCamino.BorderStyle = BorderStyle.FixedSingle; this.labCamino.ForeColor = Color.Red; this.pbObstaculo.BorderStyle = BorderStyle.None; this.labObstaculo.ForeColor = Color.Black; } private void btnDibujar_Click(object sender, EventArgs e) { this.panEntorno.Enabled = true; this.btnDibujar.Enabled = false; this.btnPredeterminado.Enabled = true; this.pbPartida.Visible = true; this.pbLlegada.Visible = true; this.pbCamino.Visible = true; this.pbObstaculo.Visible = true; this.labPartida.Visible = true; this.labLlegada.Visible = true; this.labCamino.Visible = true; this.labObstaculo.Visible = true; this.pbPartida.BorderStyle = BorderStyle.FixedSingle; this.labPartida.ForeColor = Color.Red; this.btnListo.Visible = true; this.btnEjecutar.Enabled = false; this.casilla_tipo = "partida"; } private void btnPredeterminado_Click(object sender, EventArgs e) { this.panEntorno.Enabled = false; this.btnDibujar.Enabled = true; this.btnPredeterminado.Enabled = false; this.pbPartida.Visible = false; this.pbLlegada.Visible = false; this.pbCamino.Visible = false; this.pbObstaculo.Visible = false; this.labPartida.Visible = false; this.labLlegada.Visible = false; this.labCamino.Visible = false; this.labObstaculo.Visible = false; this.btnListo.Visible = false; this.btnEjecutar.Enabled = true; //laberinto 1 this.casilla40.Tag = "partida"; this.casilla40.BackgroundImage = this.imageList.Images[2]; this.casilla_partida = this.casilla40; this.casilla49.Tag = "llegada"; this.casilla49.BackgroundImage = this.imageList.Images[3]; this.casilla_llegada = this.casilla49; this.casilla30.Tag = "obstaculo"; this.casilla30.BackgroundImage = this.imageList.Images[1]; this.casilla31.Tag = "obstaculo"; this.casilla31.BackgroundImage = this.imageList.Images[1]; this.casilla32.Tag = "obstaculo"; this.casilla32.BackgroundImage = this.imageList.Images[1]; this.casilla33.Tag = "obstaculo"; this.casilla33.BackgroundImage = this.imageList.Images[1]; this.casilla23.Tag = "obstaculo"; this.casilla23.BackgroundImage = this.imageList.Images[1];
  • 5. this.casilla13.Tag = "obstaculo"; this.casilla13.BackgroundImage = this.imageList.Images[1]; this.casilla14.Tag = "obstaculo"; this.casilla14.BackgroundImage = this.imageList.Images[1]; this.casilla15.Tag = "obstaculo"; this.casilla15.BackgroundImage = this.imageList.Images[1]; this.casilla25.Tag = "obstaculo"; this.casilla25.BackgroundImage = this.imageList.Images[1]; this.casilla35.Tag = "obstaculo"; this.casilla35.BackgroundImage = this.imageList.Images[1]; this.casilla45.Tag = "obstaculo"; this.casilla45.BackgroundImage = this.imageList.Images[1]; this.casilla55.Tag = "obstaculo"; this.casilla55.BackgroundImage = this.imageList.Images[1]; this.casilla56.Tag = "obstaculo"; this.casilla56.BackgroundImage = this.imageList.Images[1]; this.casilla57.Tag = "obstaculo"; this.casilla57.BackgroundImage = this.imageList.Images[1]; this.casilla47.Tag = "obstaculo"; this.casilla47.BackgroundImage = this.imageList.Images[1]; this.casilla37.Tag = "obstaculo"; this.casilla37.BackgroundImage = this.imageList.Images[1]; this.casilla38.Tag = "obstaculo"; this.casilla38.BackgroundImage = this.imageList.Images[1]; this.casilla39.Tag = "obstaculo"; this.casilla39.BackgroundImage = this.imageList.Images[1]; this.casilla51.Tag = "obstaculo"; this.casilla51.BackgroundImage = this.imageList.Images[1]; this.casilla52.Tag = "obstaculo"; this.casilla52.BackgroundImage = this.imageList.Images[1]; this.casilla53.Tag = "obstaculo"; this.casilla53.BackgroundImage = this.imageList.Images[1]; this.casilla60.Tag = "obstaculo"; this.casilla60.BackgroundImage = this.imageList.Images[1]; this.casilla61.Tag = "obstaculo"; this.casilla61.BackgroundImage = this.imageList.Images[1]; this.casilla70.Tag = "obstaculo"; this.casilla70.BackgroundImage = this.imageList.Images[1]; this.casilla71.Tag = "obstaculo"; this.casilla71.BackgroundImage = this.imageList.Images[1]; this.casilla72.Tag = "obstaculo"; this.casilla72.BackgroundImage = this.imageList.Images[1]; this.casilla73.Tag = "obstaculo"; this.casilla73.BackgroundImage = this.imageList.Images[1]; this.casilla83.Tag = "obstaculo"; this.casilla83.BackgroundImage = this.imageList.Images[1]; this.casilla93.Tag = "obstaculo"; this.casilla93.BackgroundImage = this.imageList.Images[1]; this.casilla94.Tag = "obstaculo"; this.casilla94.BackgroundImage = this.imageList.Images[1]; this.casilla95.Tag = "obstaculo"; this.casilla95.BackgroundImage = this.imageList.Images[1]; this.casilla85.Tag = "obstaculo"; this.casilla85.BackgroundImage = this.imageList.Images[1]; this.casilla75.Tag = "obstaculo"; this.casilla75.BackgroundImage = this.imageList.Images[1]; this.casilla76.Tag = "obstaculo"; this.casilla76.BackgroundImage = this.imageList.Images[1]; this.casilla77.Tag = "obstaculo"; this.casilla77.BackgroundImage = this.imageList.Images[1]; this.casilla87.Tag = "obstaculo";
  • 6. this.casilla87.BackgroundImage = this.imageList.Images[1]; this.casilla88.Tag = "obstaculo"; this.casilla88.BackgroundImage = this.imageList.Images[1]; this.casilla89.Tag = "obstaculo"; this.casilla89.BackgroundImage = this.imageList.Images[1]; this.casilla79.Tag = "obstaculo"; this.casilla79.BackgroundImage = this.imageList.Images[1]; this.casilla69.Tag = "obstaculo"; this.casilla69.BackgroundImage = this.imageList.Images[1]; this.casilla59.Tag = "obstaculo"; this.casilla59.BackgroundImage = this.imageList.Images[1]; } private void btnEjecutar_Click(object sender, EventArgs e) { this.miPartida = new Nodo("partida", this.casilla_partida.Name); this.miLlegada = new Nodo("llegada", this.casilla_llegada.Name); this.miPartida.funcion = this.CalcularHeuristica(this.miPartida); this.arbol = new ArrayList(); this.ruta = new ArrayList(); this.BLO(); this.PresentarRuta(); this.btnDibujar.Enabled = false; this.btnPredeterminado.Enabled = false; this.btnEjecutar.Enabled = false; this.btnNuevo.Enabled = true; } private void pbPartida_Click(object sender, EventArgs e) { this.casilla_tipo = "partida"; this.pbPartida.BorderStyle = BorderStyle.FixedSingle; this.labPartida.ForeColor = Color.Red; this.pbLlegada.BorderStyle = BorderStyle.None; this.labLlegada.ForeColor = Color.Black; this.pbCamino.BorderStyle = BorderStyle.None; this.labCamino.ForeColor = Color.Black; this.pbObstaculo.BorderStyle = BorderStyle.None; this.labObstaculo.ForeColor = Color.Black; } private void pbLlegada_Click(object sender, EventArgs e) { this.casilla_tipo = "llegada"; this.pbPartida.BorderStyle = BorderStyle.None; this.labPartida.ForeColor = Color.Black; this.pbLlegada.BorderStyle = BorderStyle.FixedSingle; this.labLlegada.ForeColor = Color.Red; this.pbCamino.BorderStyle = BorderStyle.None; this.labCamino.ForeColor = Color.Black; this.pbObstaculo.BorderStyle = BorderStyle.None; this.labObstaculo.ForeColor = Color.Black; } int BLO() { return BLO1(this.miPartida, double.MaxValue); }
  • 7. int BLO1(Nodo nodo, double limite) { Nodo[] sucesores; if (!nodo.visitado) { if (nodo.tipo == "llegada") { return 0; } sucesores = this.ExpandirNodo(nodo); if (sucesores.Length == 0) { return 1; } foreach (Nodo n in sucesores) { n.funcion = nodo.funcion; if ((n.costo + n.heuristica) > nodo.funcion) { n.funcion = n.costo + n.heuristica; } } } else { ArrayList aux_sucesores = new ArrayList(); foreach (Object o in arbol) { Nodo n = ((Nodo)o); if (n.padre == nodo) { aux_sucesores.Add(n); } } sucesores = new Nodo[aux_sucesores.Count]; for (int i=0; i<aux_sucesores.Count;i++) { sucesores[i] = ((Nodo)aux_sucesores[i]); } } Nodo[] sucesoresOrdenados = OrdenarMayorAMenor(sucesores); nodo.visitado = true; mejor = sucesoresOrdenados[0]; if (mejor.funcion > limite) { nodo.funcion = mejor.funcion; this.ruta.RemoveAt(this.ruta.Count - 1); BLO1(nodo.padre, mejor.funcion); } if (sucesores.Length == 1) { alternativa = mejor; } else { alternativa = sucesoresOrdenados[1]; } double min = alternativa.funcion; if (limite < min)
  • 8. { min = limite; } if (this.ruta.Count<2) { this.ruta.Add(mejor); }else { if (mejor != this.ruta[this.ruta.Count - 1]) { this.ruta.Add(mejor); } } this.BLO1(mejor, min); return 0; } //Este metodo expande los sucesores de un nodo recibido Nodo[] ExpandirNodo(Nodo nodo) { Nodo[] sucesores = new Nodo[4]; string mnombre = "casilla"; int i = 0; int mnivel = nodo.nivel_casilla_arriba; int mpasillo = nodo.pasillo_casilla_arriba; if ((mnivel > -1) && (mpasillo > -1)) { mnombre = mnombre + mnivel.ToString() + mpasillo.ToString(); if ((this.panEntorno.Controls[mnombre].Tag.ToString() == "camino") || (this.panEntorno.Controls[mnombre].Tag.ToString() == "llegada")) { if (nodo.padre == null) { Nodo nodo_arriba = new Nodo(this.panEntorno.Controls[mnombre].Tag.ToString(), mnombre); this.AgregarNodo(nodo, nodo_arriba); sucesores[i] = nodo_arriba; i++; } else { if (!((mnivel == nodo.padre.nivel) && (mpasillo == nodo.padre.pasillo))) { Nodo nodo_arriba = new Nodo(this.panEntorno.Controls[mnombre].Tag.ToString(), mnombre); this.AgregarNodo(nodo, nodo_arriba); sucesores[i] = nodo_arriba; i++; } } } } mnombre = "casilla"; mnivel = nodo.nivel_casilla_abajo; mpasillo = nodo.pasillo_casilla_abajo; if ((mnivel > -1) && (mpasillo > -1)) {
  • 9. mnombre = mnombre + mnivel.ToString() + mpasillo.ToString(); if ((this.panEntorno.Controls[mnombre].Tag.ToString() == "camino") || (this.panEntorno.Controls[mnombre].Tag.ToString() == "llegada")) { if (nodo.padre == null) { Nodo nodo_abajo = new Nodo(this.panEntorno.Controls[mnombre].Tag.ToString(), mnombre); this.AgregarNodo(nodo, nodo_abajo); sucesores[i] = nodo_abajo; i++; } else { if (!((mnivel == nodo.padre.nivel) && (mpasillo == nodo.padre.pasillo))) { Nodo nodo_abajo = new Nodo(this.panEntorno.Controls[mnombre].Tag.ToString(), mnombre); this.AgregarNodo(nodo, nodo_abajo); sucesores[i] = nodo_abajo; i++; } } } } mnombre = "casilla"; mnivel = nodo.nivel_casilla_izquierda; mpasillo = nodo.pasillo_casilla_izquierda; if ((mnivel > -1) && (mpasillo > -1)) { mnombre = mnombre + mnivel.ToString() + mpasillo.ToString(); if ((this.panEntorno.Controls[mnombre].Tag.ToString() == "camino") || (this.panEntorno.Controls[mnombre].Tag.ToString() == "llegada")) { if (nodo.padre == null) { Nodo nodo_izquierda = new Nodo(this.panEntorno.Controls[mnombre].Tag.ToString(), mnombre); this.AgregarNodo(nodo, nodo_izquierda); sucesores[i] = nodo_izquierda; i++; } else { if (!((mnivel == nodo.padre.nivel) && (mpasillo == nodo.padre.pasillo))) { Nodo nodo_izquierda = new Nodo(this.panEntorno.Controls[mnombre].Tag.ToString(), mnombre); this.AgregarNodo(nodo, nodo_izquierda); sucesores[i] = nodo_izquierda; i++; } } } }
  • 10. mnombre = "casilla"; mnivel = nodo.nivel_casilla_derecha; mpasillo = nodo.pasillo_casilla_derecha; if ((mnivel > -1) && (mpasillo > -1)) { mnombre = mnombre + mnivel.ToString() + mpasillo.ToString(); if ((this.panEntorno.Controls[mnombre].Tag.ToString() == "camino") || (this.panEntorno.Controls[mnombre].Tag.ToString() == "llegada")) { if (nodo.padre == null) { Nodo nodo_derecha = new Nodo(this.panEntorno.Controls[mnombre].Tag.ToString(), mnombre); this.AgregarNodo(nodo, nodo_derecha); sucesores[i] = nodo_derecha; i++; } else { if (!((mnivel == nodo.padre.nivel) && (mpasillo == nodo.padre.pasillo))) { Nodo nodo_derecha = new Nodo(this.panEntorno.Controls[mnombre].Tag.ToString(), mnombre); this.AgregarNodo(nodo, nodo_derecha); sucesores[i] = nodo_derecha; i++; } } } } int len = 0; foreach (object o in sucesores) { if (o != null) { len++; } } Nodo[] aux_sucesores = new Nodo[len]; for (int j = 0; j < len; j++) { aux_sucesores[j] = sucesores[j]; } return aux_sucesores; } void AgregarNodo(Nodo padre, Nodo nodo) { this.AgregarNodo(padre, nodo, CalcularCosto(padre), CalcularHeuristica(nodo)); } void AgregarNodo(Nodo padre, Nodo nodo, int costo, double heuristica) { nodo.padre=padre; nodo.costo=costo; nodo.heuristica=heuristica;
  • 11. this.arbol.Add(nodo); } int CalcularCosto(Nodo nodoPadre) { return nodoPadre.costo + 1; } double CalcularHeuristica(Nodo nodo) { int a = nodo.nivel - this.miLlegada.nivel; int b = nodo.pasillo - this.miLlegada.pasillo; return Math.Sqrt(Math.Pow(a, 2) + Math.Pow(b, 2)); } Nodo[] OrdenarMayorAMenor(Nodo[] sucesores) { for (int j = 1; j <= sucesores.Length; j++) { for (int i = 0; i < sucesores.Length - 1; i++) { if (sucesores[i].funcion > sucesores[i + 1].funcion) { Nodo temp = sucesores[i]; sucesores[i] = sucesores[i + 1]; sucesores[i + 1] = temp; } } } return sucesores; } void PresentarRuta() { //for (int i = 0; i < (this.ruta.Count-1); i++) //{ // for (int j=i+1;j<this.ruta.Count;j++) // { // if (this.ruta[i] == this.ruta[j]) // { // this.ruta.RemoveAt(j); // j--; // } // } //} this.timer.Start(); } int indRuta; private void timer_Tick(object sender, EventArgs e) { Nodo n = ((Nodo)this.ruta[this.indRuta]); string mnombre = "casilla"+n.nivel.ToString()+n.pasillo.ToString(); this.panEntorno.Controls[mnombre].BackgroundImage = this.imageList.Images[2]; if (this.indRuta == 0) { n = this.miPartida; }
  • 12. else { n = ((Nodo)this.ruta[this.indRuta - 1]); } mnombre = "casilla" + n.nivel.ToString() + n.pasillo.ToString(); this.panEntorno.Controls[mnombre].BackgroundImage = this.imageList.Images[0]; this.indRuta++; if (indRuta == this.ruta.Count) { this.timer.Stop(); string miruta = string.Empty; Nodo minodo=null; for (int i = 0; i < this.ruta.Count; i++) { minodo = ((Nodo)this.ruta[i]); miruta = miruta + minodo.nivel.ToString() + ", " + minodo.pasillo.ToString() + "n"; } if (minodo.tipo == "llegada") { MessageBox.Show(miruta,this.Text + " - Resultados"); } else { MessageBox.Show("Sin SALIDA", this.Text + " - Resultados"); } } } private void btnListo_Click(object sender, EventArgs e) { this.panEntorno.Enabled = false; this.btnDibujar.Enabled = true; this.btnPredeterminado.Enabled = true; this.pbPartida.Visible = false; this.pbLlegada.Visible = false; this.pbCamino.Visible = false; this.pbObstaculo.Visible = false; this.labPartida.Visible = false; this.labLlegada.Visible = false; this.labCamino.Visible = false; this.labObstaculo.Visible = false; this.btnListo.Visible = false; this.btnEjecutar.Enabled = true; } private void btnNuevo_Click(object sender, EventArgs e) { this.Inicializar(); this.btnDibujar.Enabled = true; this.btnPredeterminado.Enabled = true; this.btnNuevo.Enabled = false; } void Inicializar() { this.btnPredeterminado.Enabled = true;
  • 13. this.pbCamino.Enabled = true; this.pbObstaculo.Enabled = true; this.pbPartida.Enabled = true; this.pbLlegada.Enabled = true; this.panEntorno.Enabled = true; PictureBox img = new PictureBox(); foreach (Control c in this.panEntorno.Controls) { img = ((PictureBox)c); if (c.Size.Height == 25) { img.Tag = "camino"; img.BackgroundImage = this.imageList.Images[0]; img.BackgroundImageLayout = ImageLayout.Stretch; } } this.casilla_camino = this.casilla00; this.pbCamino.Image = this.imageList.Images[0]; this.pbObstaculo.Image = this.imageList.Images[1]; this.pbPartida.Image = this.imageList.Images[2]; this.pbLlegada.Image = this.imageList.Images[3]; indRuta = 0; } } } Dentro de la clase Nodo.cs calculamos la la posición delnodo en donde se encuentra el agente y de los vecinos o nodos sucesores. A continuación el codigo la clase Nodo.cs using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; namespace IGU { class Nodo { public Nodo padre; public string tipo; public int nivel; public int pasillo; public double funcion; public int costo; public double heuristica; public bool visitado = false; public int nivel_casilla_arriba = -1; public int nivel_casilla_abajo = -1; public int nivel_casilla_izquierda = -1; public int nivel_casilla_derecha = -1; public int pasillo_casilla_arriba = -1; public int pasillo_casilla_abajo = -1; public int pasillo_casilla_izquierda = -1; public int pasillo_casilla_derecha = -1; public Nodo(string mtipo, string mnombre) {
  • 14. this.tipo = mtipo; this.CalcularUbicacion(mnombre); this.DefinirVecinos(this.nivel, this.pasillo); } void CalcularUbicacion(string mnombre) { string mnivel = mnombre.Substring(7, 1); string mpasillo = mnombre.Substring(8, 1); this.nivel = int.Parse(mnivel); this.pasillo = int.Parse(mpasillo); } void DefinirVecinos(int mnivel, int mpasillo) { //casilla arriba if (mnivel > 0) { this.nivel_casilla_arriba = mnivel - 1; this.pasillo_casilla_arriba = mpasillo; } //casilla abajo if (mnivel < 9) { this.nivel_casilla_abajo = mnivel + 1; this.pasillo_casilla_abajo = mpasillo; } //casilla izquierda if (mpasillo > 0) { this.nivel_casilla_izquierda = mnivel; this.pasillo_casilla_izquierda = mpasillo - 1; } //casilla derecha if (mpasillo < 9) { this.nivel_casilla_derecha = mnivel; this.pasillo_casilla_derecha = mpasillo + 1; } } public double CalcularHeuristica(Nodo nodo) { return 0; } } }