Вы находитесь на странице: 1из 23

FACULTAD DE INGENIERIA DE

PRODUCCION Y SERVICIOS

INGENIERIA INDUSTRIAL
Curso:

SISTEMA DE INFORMACIÓN

Trabajo:
INFORMES DE LAS PRACTICAS DE LABORATORIO
Docente:
ING. IZMAEL VELIZ VILCA
Integrantes:

 Apaza Rodriguez Eddy Felix; CUI: 20150378; eapazar@unsa.edu.pe

 Choquehuanca Apaza Alexander; CUI:

20153622;achoquehuanca@unsa.edu.pe

 Diaz Condori, Lizbeth Karla; CUI: 20171931; ldiazcon@unsa.edu.pe

 Torres Anco, John Edward; CUI:20150382; jtorresanc@unsa.edu.pe

Año:
4to – GRUPO “B”

AREQUIPA-2020
}

INDICE
INFORMES DE LAS PRACTICAS DE LABORATORIO........................................................................2
PRACTICA 1...............................................................................................................................2
OBJETIVO..............................................................................................................................2
DESCRIPCION DEL PROCESO.................................................................................................2
CODIGOS DEL FORMULARIO.................................................................................................3
EXPLICACIÓN........................................................................................................................8
TRABAJO FINAL.....................................................................................................................9
PRACTICA 2: EVENTOS DEL MOUSE Y TECLADO.......................................................................9
OBJETIVO:.............................................................................................................................9
DESCRIPCION DEL PROCESO...............................................................................................10
CODIGO DEL FORMULARIO................................................................................................10
EXPLICACIÓN......................................................................................................................12
TRABAJO FINAL...................................................................................................................13
PRACTICA 4.............................................................................................................................13
PRACTICA 5: AGENTE VIAJERO...............................................................................................15
Objetivo del programa.......................................................................................................16
Métodos utilizados.............................................................................................................16
Interfaz...............................................................................................................................16
Funcionamiento.................................................................................................................16
Restricciones......................................................................................................................18
Código interfaz...................................................................................................................18
Código Crear Ruta..............................................................................................................19
Código Método Held Karp..................................................................................................19
Códido Método Vecino más cercano..................................................................................20
Código Pintor:.....................................................................................................................20
BIBLIOGRAFIA.............................................................................................................................21

1
INFORMES DE LAS PRACTICAS DE LABORATORIO

PRACTICA 1

En esta práctica número 1, hemos desarrollado un juego en Visual Basic 2010 haciendo

simulaciones de juego muy conocido en los años 90 que es “THE SNAKE” a partir de

un formulario Visual Form. En este juego se implemento 4 niveles donde su dificultad

van aumentando progresivamente.

En este juego se usó varios controles y operando del Visual Basic 2010, lo cual nos

permite aprender más sobre como programar, estos son:

 Timer

 Keycode

 Resources

 Como importar imágenes

 Funciones Matrices

OBJETIVO

Presentar un tema libre con uso de control multimedia a partir de las direccionales

encontradas en el teclado.

DESCRIPCION DEL PROCESO

1. Crear una aplicación en Microsoft Visual Estudio llamada SNAKE.

2. Crear un Windows Form para desarrollar nuestro juego SNAKE.

3. En el diseñador de Formularios arrastrar: 1 Timer, 4 Button, 1TextBox, 1 label ,

luego configurar las propiedades para sincronizar varios aspectos como la

2
distribución de imágenes de nuestro juego, importación de imágenes y

form_keyup

CODIGOS DEL FORMULARIO

Public Class Form1


Private cx(500), cy(500) As Integer 'coordenadas de la serpiente
Private movi As Byte 'movimiento de la se´rpiente
Private moviANT As Byte 'movimiento anterior
Private lon As Short 'Longitud de la serpiente
Private anillos(499) As Label 'Array de anillos de los serpientes
Private Lineam(21) As String 'Lineas de mapa, representa el dibujo
Private bloque As PictureBox ' Codigode los bloques graficos
Private mapa(29, 21) As Char 'mapa para presentar los bloques
graficos(matrices)

Private Sub Form1_FormClosing(ByVal sender As System.Object, ByVal e As


System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
'liberar los recursos no administrativos
For A As Short = 0 To 499
anillos(A).Dispose()
anillos(A) = Nothing
Next A
liberar_bloque()
End Sub

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles MyBase.Load
Me.ClientSize = New Size(1037, 660)
crear_anillo() 'cargar los graficos de los anillos
mapa_bosque() 'carga el mapa inicial
asignar_matriz() 'asignar la matriz y dibujar los bloques
inicio_juego() 'cargamos los valores por defecto
End Sub

Private Sub Form1_KeyUp(ByVal sender As Object, ByVal e As


System.Windows.Forms.KeyEventArgs) Handles Me.KeyUp
If e.KeyCode = Keys.Right And moviANT <> 2 Then movi = 1 'Tecla derecha
If e.KeyCode = Keys.Left And moviANT <> 1 Then movi = 2 'Tecla izquierda
If e.KeyCode = Keys.Down And moviANT <> 4 Then movi = 3 'Tecla abajo
If e.KeyCode = Keys.Up And moviANT <> 3 Then movi = 4 'Tecla arriba
moviANT = movi 'Guarda movimiento de tecla
pulsada
End Sub

Private Sub tmrsnake_Tick(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles tmrsnake.Tick
'colocar todo el array de la serpiente
For A As Short = lon To 1 Step -1
cx(A) = cx(A - 1)
cy(A) = cy(A - 1)
anillos(A - 1).SetBounds(cx(A), cy(A), anillos(A - 1).Width,
anillos(A - 1).Height)
Next A
If movi = 1 Then cx(0) = cx(0) + 30 : lblsnake.Image = My.Resources.pacs
If movi = 2 Then cx(0) = cx(0) - 30 : lblsnake.Image =
My.Resources.pacsizquierda

3
If movi = 3 Then cy(0) = cy(0) + 30 : lblsnake.Image =
My.Resources.pacsabajo
If movi = 4 Then cy(0) = cy(0) - 30 : lblsnake.Image =
My.Resources.pacsarriba
'comprobamos si serpiente se cruza... game over
For A As Short = 1 To lon
If cx(0) = cx(A) And cy(0) = cy(A) Then
tmrsnake.Enabled = False 'se para el juego por
cruzarce a si mismo
MsgBox("GAME OVER", MsgBoxStyle.Critical)
inicio_juego()
Exit Sub
End If
Next A
'comprobamos si sierpente toca los bloques GAME OVER
If mapa(cx(0) / 30, cy(0) / 30) <> " " Then
tmrsnake.Enabled = False 'se para el juego por cruzarce
a si mismo
MsgBox("GAME OVER", MsgBoxStyle.Critical)
inicio_juego()
Exit Sub
End If
'colocar la comida
If lblnum.Visible = False Then colocar_numero()
'comprobar si la serpiente coge la comida
If cx(0) = lblnum.Location.X And cy(0) = lblnum.Location.Y Then
If Val(lblnum.Text + 1) = 100 Then
lblnum.Text = 1
Else
lblnum.Text = Val(lblnum.Text + 1)
End If
lon += 1
cx(lon) = cx(lon - 1)
cy(lon) = cy(lon - 1)
'dibujar ese anillo
anillos(lon - 1).SetBounds(cx(lon), cy(lon), anillos(lon - 1).Width,
anillos(lon - 1).Height)
anillos(lon - 1).Visible = True
lblnum.Visible = False
End If
'dibujando la serpiente
lblsnake.SetBounds(cx(0), cy(0), lblsnake.Width, lblsnake.Height)
End Sub

'**********PROCEDIMIENTOS DEL JUEGO*************


Private Sub inicio_juego()
For A As Short = 0 To lon
anillos(A).Visible = False 'La comida de la serpiente son
invisibles
Next A
lon = 0
cx(0) = 180 : cy(0) = 210
lblsnake.Location = New Point(cx(0), cy(0))
lblsnake.Image = My.Resources.pacs
lblnum.Visible = False
lblnum.Text = 1
movi = 0 : moviANT = 0
tmrsnake.Enabled = True 'Iniciación del timer
End Sub

Private Sub crear_anillo()


For A As Short = 0 To 499

4
anillos(A) = New Label
anillos(A).AutoSize = False
anillos(A).Size = New Size(30, 30)
anillos(A).Image = My.Resources.circulos
anillos(A).BackColor = Color.Transparent
Me.Controls.Add(anillos(A))
anillos(A).Visible = False
Next A
End Sub

Private Sub crear_bloque(ByVal col As Short, ByVal corX As Short, ByVal corY As
Short)
bloque = New PictureBox
bloque.Size = New Size(30, 30)
If col = 1 Then bloque.Image = My.Resources.pas
If col = 2 Then bloque.Image = My.Resources.pas
If col = 3 Then bloque.Image = My.Resources.pas
If col = 4 Then bloque.Image = My.Resources.pas
'-------------------------------- Para ingresar nuevas pantallas
bloque.BackColor = Color.Transparent
bloque.Location = New Point(corX, corY)
Me.Controls.Add(bloque)
End Sub
Private Sub asignar_matriz()
Dim x, y As Short
'leer los valores x,y de caracteres
For x = 0 To 29
For y = 0 To 21
mapa(x, y) = Mid(Lineam(y), x + 1, 1) 'lee una cadena de
carecteres(la linea q vamos a poner para el snake
Next y
Next x

'si hay bloque de color


For x = 0 To 29
For y = 0 To 21
mapa(x, y) = Mid(Lineam(y), x + 1, 1) 'lee una cadena de
carecteres(la linea q vamos a poner para el snake
If mapa(x, y) = "R" Then crear_bloque(1, x * 30, y * 30)
If mapa(x, y) = "Z" Then crear_bloque(2, x * 30, y * 30)
If mapa(x, y) = "A" Then crear_bloque(3, x * 30, y * 30)
If mapa(x, y) = "A" Then crear_bloque(4, x * 30, y * 30)
'---------------------------- si deseamos aca podemos agregar
nuevas pantallas
Next y
Next x
End Sub

Private Sub liberar_bloque()


'borrar la memoria todos los bloques
For B As Short = 1 To 10

For Each controles In Me.Controls


If TypeOf controles Is PictureBox Then
controles.dispose()
End If
Next controles
Next B
End Sub

Private Sub colocar_numero()


Randomize() 'reinicia los numeros aleatorios

5
Dim cnx, cny As Integer 'coordenadas del numero
Dim swpaso As Boolean = False 'switch para dar paso
Do
cnx = Int(30 * Rnd() + 0) 'numero aleatorio entre 0 y 29
cny = Int(22 * Rnd() + 0) 'numero aleatorio entre 0 y 21
If mapa(cnx, cny) = " " Then 'esta condicion es para evitar que no
se sobrepongan
swpaso = True
End If
'Comprobamos coordenadas numero si coincide anillos o cabeza
For A As Short = 0 To lon
If (cnx * 30) = cx(A) And (cny * 30) = cy(A) Then
swpaso = False
End If
Next A
Loop Until swpaso = True
lblnum.Location = New Point(cnx * 30, cny * 30)
lblnum.Visible = True 'visualizamos el numero
End Sub

Private Sub btnbosque_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnbosque.Click
'Cargar la pantalla del bosque
If movi = 0 Then
liberar_bloque()
mapa_bosque()
asignar_matriz()
inicio_juego()
End If
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles Button1.Click
If movi = 0 Then
liberar_bloque()
mapa_bosque1()
asignar_matriz()
inicio_juego()
End If
End Sub

Private Sub btnpacman_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnpacman.Click
If movi = 0 Then
liberar_bloque()
mapa_pacman()
asignar_matriz()
inicio_juego()
End If
End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles Button2.Click
If movi = 0 Then
liberar_bloque()
mapa_4()
asignar_matriz()
inicio_juego()
End If
End Sub
'********************** MAPAS DEL JUEGO *******************************

6
Private Sub mapa_bosque()
tmrsnake.Interval = 400
'Me.BackgroundImage = My.Resources.paisaje2
Lineam(0) = "RRRRRRRRRRRRRRRRRRRRRRRRRRRRRR"
Lineam(1) = "R R"
Lineam(2) = "R R"
Lineam(3) = "R R"
Lineam(4) = "R R"
Lineam(5) = "R R"
Lineam(6) = "R R"
Lineam(7) = "R R"
Lineam(8) = "R R"
Lineam(9) = "R RR R"
Lineam(10) = "R RR R"
Lineam(11) = "R RR R"
Lineam(12) = "R RR R"
Lineam(13) = "R R"
Lineam(14) = "R R"
Lineam(15) = "R R"
Lineam(16) = "R R"
Lineam(17) = "R R"
Lineam(18) = "R R"
Lineam(19) = "R R"
Lineam(20) = "R R"
Lineam(21) = "RRRRRRRRRRRRRRRRRRRRRRRRRRRRRR"
End Sub

Private Sub mapa_bosque1()


tmrsnake.Interval = 300
'Me.BackgroundImage = My.Resources.paisaje2
Lineam(0) = "ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ"
Lineam(1) = "Z Z"
Lineam(2) = "Z Z"
Lineam(3) = "Z ZZZZ Z"
Lineam(4) = "Z ZZZZZZ Z"
Lineam(5) = "Z Z Z"
Lineam(6) = "Z Z Z"
Lineam(7) = "Z ZZ Z"
Lineam(8) = "Z Z Z"
Lineam(9) = "Z ZZ Z"
Lineam(10) = "Z ZZ Z"
Lineam(11) = "Z ZZ Z"
Lineam(12) = "Z Z"
Lineam(13) = "Z ZZZZ Z"
Lineam(14) = "Z ZZZZZZZ Z"
Lineam(15) = "Z Z"
Lineam(16) = "Z Z"
Lineam(17) = "Z Z"
Lineam(18) = "Z ZZZZ Z"
Lineam(19) = "Z ZZZZ Z"
Lineam(20) = "Z Z"
Lineam(21) = "ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ"
End Sub

Private Sub mapa_pacman()


tmrsnake.Interval = 200
'Me.BackgroundImage = My.Resources.PAC
Lineam(0) = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
Lineam(1) = "A AAAAA AAAAAAA"
Lineam(2) = "A A"
Lineam(3) = "A AAAAAAA A"

7
Lineam(4) = "A AAAAAAAA A"
Lineam(5) = "A A"
Lineam(6) = "A A"
Lineam(7) = "A AAA A"
Lineam(8) = "A AAA A"
Lineam(9) = "A AAAAA A"
Lineam(10) = "A AAAAAAAAAAAAA A"
Lineam(11) = "A A"
Lineam(12) = "A AAAAAA A"
Lineam(13) = "A AAAAAAAA A"
Lineam(14) = "A AAAAAAAAAA A"
Lineam(15) = "A AAAAAAAAAA A"
Lineam(16) = "A AAAAAAAA A"
Lineam(17) = "A AAAAAAAAAAA A"
Lineam(18) = "A AAAAAAA A"
Lineam(19) = "AAAAAAAA A"
Lineam(20) = "AAAAAAAA A"
Lineam(21) = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
End Sub

Private Sub mapa_4()


tmrsnake.Interval = 100
'Me.BackgroundImage = My.Resources.PAC
Lineam(0) = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
Lineam(1) = "A AAAAA AAAAAAA"
Lineam(2) = "A A"
Lineam(3) = "AAAA AAAAAAA A"
Lineam(4) = "A AAA AAAAAAAA A"
Lineam(5) = "A AAAA A"
Lineam(6) = "A AAAAA AAA A"
Lineam(7) = "A AAA A"
Lineam(8) = "A AAA A"
Lineam(9) = "A AAAAA A"
Lineam(10) = "A AAAAAAAAAAAAA A"
Lineam(11) = "A A A"
Lineam(12) = "AAA A AAAAAAAAAAAA A"
Lineam(13) = "A AAAAAAAA A"
Lineam(14) = "A AAAAAAAAAA A"
Lineam(15) = "A AAAAAAAAAA A"
Lineam(16) = "A AAAAAAAA AA"
Lineam(17) = "A AAAAAAAAAAA AA"
Lineam(18) = "A AAAAAAA AA"
Lineam(19) = "AAAAAAAA AA"
Lineam(20) = "AAAAAAAA AAAA"
Lineam(21) = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
End Sub
End Class

EXPLICACIÓN

 En el presente ejercicio se usaron los eventos Key Press y la herramienta Timer

 Cuando el jugador presiona cualquier direccional de su teclado comenzara a

moverse la cabeza de la serpiente para a si ir tras su comida.

8
 La serpiente podrá moverse en cualquier dirección, pero si choca con el

laberinto o su propio cuerpo el juego acaba.

 Tendrá diferentes niveles, en cada uno cambia la dificultad del juego.

NIVEL 1: Lento

NIVEL 2: Normal

NIVEL 3: Rápido

NIVEL 4: Muy rápido

 Además, la serpiente se moverá más rápido en cada nivel gracias al control

Timer.

TRABAJO FINAL

9
PRACTICA 2: EVENTOS DEL MOUSE Y TECLADO

OBJETIVO: Aplicar los eventos del mouse y del teclado.

DESCRIPCION DEL PROCESO

4. Crear una aplicación en Microsoft Visual Estudio llamada Eventos del mouse y

teclado.

5. En el diseñador de Formularios arrastrar: 1 PictureBox, 4 Button, 1TextBox,

luego configurar las propiedades tal como se muestra.

OBJETO PROPIEDAD VALOR


PictureBox Name PictureBox1
Image Screenshot_20180903-171105
Button1 Name btnFoto
Text Cargar
Button2 Name btnManual
Text Manual
Button3 Name btnAuto
Text Automatico
Button4 Name btnDetener
Text Detener
TextBox Name txtMover

CODIGO DEL FORMULARIO

Imports System.Drawing

Public Class Form1


Dim Primeravez As Integer = 0
Dim DifX As Integer
Dim DifY As Integer
Dim x1 As Single, y1 As Single, x2 As Single, y2 As Single
Dim Paso As Integer = 10
Dim estirar As Integer = 0
Dim Movimiento1 As Boolean
Dim primovi1 As Boolean = False
Dim posicionX1 = 0
Dim posicionY1 = 0
Dim NombreArchivo As String

10
Private Sub PictureBox1_MouseMove(sender As Object, e As MouseEventArgs)
Handles PictureBox1.MouseMove
If Primeravez = 0 Then
Primeravez = 1
x1 = e.X
y1 = e.Y
Exit Sub
End If
x2 = e.X
y2 = e.Y
DifX = x2 - x1
DifY = y2 - y1
Me.Text = DifX
If e.X < PictureBox1.Width - Paso And e.X >= Paso And e.Y <=
PictureBox1.Height - Paso And e.Y >= Paso Then
PictureBox1.Cursor = Cursors.SizeAll
If (Movimiento1 = True) Then
If (primovi1 = False) Then
primovi1 = True
posicionX1 = e.X
posicionY1 = e.Y
End If
If e.X < PictureBox1.Width - Paso And e.X >= Paso And e.Y <=
PictureBox1.Height - Paso And e.Y >= Paso Then
PictureBox1.Location = New Point(e.X + PictureBox1.Location.X
- posicionX1, e.Y + PictureBox1.Location.Y - posicionY1)
End If
End If
Else
If e.X <= Paso Or e.X >= PictureBox1.Width - Paso Then
PictureBox1.Cursor = Cursors.SizeWE
If estirar = 1 And e.X <= Paso Then
PictureBox1.Width = PictureBox1.Width - DifX
PictureBox1.Left = PictureBox1.Left + DifX
End If
If estirar = 1 And e.X >= PictureBox1.Width - Paso Then
PictureBox1.Width = PictureBox1.Width + DifX
End If
End If
If e.Y <= Paso Or e.Y >= PictureBox1.Height - Paso Then
PictureBox1.Cursor = Cursors.SizeNS
If estirar = 1 And e.Y <= Paso Then
PictureBox1.Height = PictureBox1.Height - DifY
PictureBox1.Top = PictureBox1.Top + DifY
End If
If estirar = 1 And e.Y >= PictureBox1.Height - Paso Then
PictureBox1.Height = PictureBox1.Height + DifY
End If
End If
End If
x1 = x2
y1 = y2
End Sub
Private Sub PictureBox1_MouseDown(sender As Object, e As MouseEventArgs)
Handles PictureBox1.MouseDown
estirar = 1
Movimiento1 = True
PictureBox1.Cursor = Cursors.SizeAll
End Sub
Private Sub PictureBox1_MouseUp(sender As Object, e As MouseEventArgs)
Handles PictureBox1.MouseUp
estirar = 0

11
Movimiento1 = False
primovi1 = False
PictureBox1.Cursor = Cursors.Default
End Sub

Private Sub txtMover_KeyDown(sender As Object, e As KeyEventArgs) Handles


txtMover.KeyDown
If e.Shift = True Then
Select Case e.KeyCode
Case Keys.Left, Keys.X
PictureBox1.Width = PictureBox1.Width + Paso
Case Keys.Up, Keys.A
PictureBox1.Width = PictureBox1.Width - Paso
Case Keys.Right, Keys.Y
PictureBox1.Height = PictureBox1.Height + Paso
Case Keys.Down, Keys.B
PictureBox1.Height = PictureBox1.Height - Paso
End Select
Else
Select Case e.KeyCode
Case Keys.Left, Keys.X
PictureBox1.Left = PictureBox1.Left + Paso
Case Keys.Up, Keys.A
PictureBox1.Left = PictureBox1.Left - Paso
Case Keys.Right, Keys.Y
PictureBox1.Top = PictureBox1.Top + Paso
Case Keys.Down, Keys.B
PictureBox1.Top = PictureBox1.Top - Paso
End Select
End If
txtMover.Text = ""
End Sub
Private Sub btnFoto_Click(sender As Object, e As EventArgs) Handles
btnFoto.Click
OpenFileDialog1.ShowDialog()
PictureBox1.Load(OpenFileDialog1.FileName)
End Sub
Private Sub btnManual_Click(sender As Object, e As EventArgs) Handles
btnManual.Click
If PictureBox1.Left + Paso + PictureBox1.Width < Me.Width Then
PictureBox1.Left = PictureBox1.Left + Paso
Else
PictureBox1.Left = 10
End If
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
btnManual_Click(sender, e)
End Sub
Private Sub btnAuto_Click(sender As Object, e As EventArgs) Handles
btnAuto.Click
Timer1.Interval = 20
Timer1.Start()
End Sub
Private Sub btnDetener_Click(sender As Object, e As EventArgs) Handles
btnDetener.Click
Timer1.Stop()
End Sub

End Class

12
EXPLICACIÓN

 En el presente ejercicio se usaron los eventos mouse dow, mouse move, mouse

up y Key press.

 Cuando se hace clic en la imagen aparece el cursor de size all, si el ratón se

ubica en el borde se puede estirar o acortar la imagen.

 La imagen se pude mover con el uso mouse o con el teclado.

 La imagen se moverá mediante el teclado cuando se tenga el cursor en el

TextBox y se presione las teclas A, B, X, Y, las cuales realizaran los siguientes

movimientos:

A: arriba

B: abajo

X: izquierda

Y: derecha

 Además, la imagen se moverá automáticamente mediante el uso del control

Timer.

TRABAJO FINAL

13
PRACTICA 4

Aplicación de clases y objetos en modo consola y formulario donde se demuestran la


herencia-formulario.

14
Aplicación de clases y objetos

PRACTICA 5: AGENTE VIAJERO

El programa realizado se trata del “Travelling salesman problema”, un problema clásico


que hasta el día de hoy no tiene solución óptima eficiente para grandes cantidades de
ciudades.

15
Objetivo del programa: Determinar la ruta más corta para pasar por cada ciudad una
sola vez y terminar en la ciudad de inicio.
Métodos utilizados:
 Fuerza bruta o Held Karp: para cantidades de ciudades pequeñas (solución
óptima).
 Vecino más cercano o ruta más corta: para cantidades pequeñas y grandes
(solución aproximada).

Interfaz:
Se buscó diseñar una interfaz simple, de fácil comprensión y manejo.

Funcionamiento:

16
1. Ingresar coordenadas: El programa lee las coordenas ingresadas de n ciudades en un

archivo “ .txt” . Este archivo debe contener únicamente las coordenadas x-y en orden y

una coordenada por fila, como se muestra en la figura:

Se elige el archivo del cuadro de diálogo que aparece al dar click en el botón
INGRESAR COORDENADAS. Los datos se cargaran automáticamente en el list box
Ciudades y a la vez se calculará la matriz de distancias.

2. Se selecciona el método a utilizar dando click a uno de los botones. Se carga en el picture box
los puntos de cada ciudad y se traza la ruta más corta.

17
Restricciones:
 Se debe escalar las distancias de tal forma que resulten coordenadas iguales o menores que 10.
 Solo se pueden ingresar coordenadas enteras, caso contrario se redondearán las ingresadas.

Código interfaz:
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Pantalla = PictureBox1.CreateGraphics()
OpenFileDialog1.Filter = "Archivo de Texto |*.txt"
End Sub
Private Sub btnAbrir_Click(sender As Object, e As EventArgs) Handles
btnAbrir.Click
If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
btnAbrir.Text = OpenFileDialog1.SafeFileName

AbrirArchivo(OpenFileDialog1.FileName)
MostrarCiudades()

CalcularDistancias()
MostrarDistancias()
Desbloquear()
End If
End Sub
Sub Desbloquear()
btnCercano.Enabled = True
btnHP.Enabled = True
End Sub

Private Sub btnCercano_Click(sender As Object, e As EventArgs) Handles


btnCercano.Click

18
DibujarCiudades()

Dim Camino As List(Of Integer) = Cercano()


DibujarCamino(Camino)
End Sub

Private Sub btnHP_Click(sender As Object, e As EventArgs) Handles btnHP.Click


DibujarCiudades()
Dim Camino As List(Of Integer) = HeldKarp()
DibujarCamino(Camino)
End Sub

End Class

Código Crear Ruta


Module Algoritmos
Function CrearRuta() As List(Of Integer)
Dim Ruta As New List(Of Integer)
For A As Integer = 0 To Cantidad - 1
Ruta.Add(A)
Next
Return Ruta
End Function
Sub Permutar(ByRef Ruta As List(Of Integer), A As Integer, B As Integer)
Dim Cambio As Integer = Ruta(A)
Ruta(A) = Ruta(B)
Ruta(B) = Cambio
End Sub
End Module

Código Método Held Karp


Module AlgoritmoHeldKarp
Dim MejorRuta As List(Of Integer)
Dim MejorDistancia As Single = -1
Function HeldKarp() As List(Of Integer)
Dim RutaInicial As List(Of Integer) = CrearRuta()
RutaInicial.RemoveAt(0)

Dim Actual As New List(Of Integer) From {0}


CalcularRutas(Actual, RutaInicial)
Return MejorRuta
End Function
Public Sub CalcularRutas(Visitados As List(Of Integer), Restantes As List(Of
Integer))
If Restantes.Count = 1 Then
Dim Siguiente As Integer = Restantes(0)

Dim Final As List(Of Integer) = Visitados.ToList()


Final.Add(Siguiente)
Final.Add(0)

CompararRuta(Final)
Else
Dim Actual As Integer = Visitados(Visitados.Count - 1)
For A As Integer = 0 To Restantes.Count - 1
Dim Siguiente As Integer = Restantes(A)

Dim Resto As List(Of Integer) = Restantes.ToList()


Resto.RemoveAt(A)

Dim Visto As List(Of Integer) = Visitados.ToList()


Visto.Add(Siguiente)

19
CalcularRutas(Visto, Resto)
Next
End If
End Sub
Private Sub CompararRuta(Ruta As List(Of Integer))
Dim Distancia As Single = DistanciaTotal(Ruta)
If (Distancia < MejorDistancia) Or (MejorDistancia = -1) Then
MejorDistancia = Distancia
MejorRuta = Ruta
End If
End Sub
Private Function DistanciaTotal(Ruta As List(Of Integer)) As Single
Dim Total As Single = 0
For I As Integer = 0 To Cantidad - 1
Dim Anterior As Integer = Ruta(I)
Dim Actual As Integer = Ruta(I + 1)
Total += Distancias(Actual, Anterior)
Next
Return Total
End Function
End Module

Códido Método Vecino más cercano


Module AlgoritmoCercano
Dim Mejor As List(Of Integer)
Function Cercano() As List(Of Integer)
Mejor = CrearRuta()
For A As Integer = 0 To Cantidad - 2
Dim Partida As Integer = Mejor(A)

Dim MenorDistancia As Single


Dim MenorB As Integer
For B As Integer = (A + 1) To Cantidad - 1
Dim Llegada As Integer = Mejor(B)
Dim Distancia As Single = Distancias(Partida, Llegada)

If (B = (A + 1)) Or (Distancia < MenorDistancia) Then


MenorDistancia = Distancia
MenorB = B
End If
Next
Permutar(Mejor, A + 1, MenorB)
Next
Mejor.Add(0)
Return Mejor
End Function
End Module

Código Pintor:
Module Pintor
Public Pantalla As Graphics
Public Escala As Single = 28
Sub DibujarCiudades()
Pantalla.Clear(Color.White)
For A As Integer = 0 To Cantidad - 1
Dim X As Integer = UbicacionesX(A) * Escala
Dim Y As Integer = (300 - UbicacionesY(A) * Escala)

DibujarCiudad(X, Y, A + 1)
Next

20
End Sub
Sub DibujarCiudad(X As Integer, Y As Integer, Nombre As Integer)
Pantalla.FillEllipse(Brushes.Black, X - 2, Y - 2, 4, 4)
Pantalla.DrawString(Nombre, New Font("Times New Roman", 8),
Brushes.Black, X, Y)
End Sub
Sub DibujarCamino(Camino As List(Of Integer))
Dim X0, Y0 As Integer
For A As Integer = 0 To Cantidad
Dim I As Integer = Camino(A)
Dim X As Integer = UbicacionesX(I) * Escala
Dim Y As Integer = (300 - UbicacionesY(I) * Escala)

If A > 0 Then
Pantalla.DrawLine(Pens.Red, X0, Y0, X, Y)
End If
X0 = X
Y0 = Y
Next
End Sub
End Module

21
BIBLIOGRAFIA

 https://www.youtube.com/watch?v=OuhQgTS-XrY&t=547s
 https://www.youtube.com/watch?v=gFidtF5j5dk
 https://www.youtube.com/watch?v=jrFnKJW1XEI
 https://www.youtube.com/watch?v=NUCi9XjU-dQ
 https://www.youtube.com/watch?v=2S2nccRhqOQ

22

Вам также может понравиться