375
Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -745- 11 APLICACIONES EN WINDOWS FORM Indice 11.1 EJEMPLO DE APLICACIÓN COMPLETA CON MENUS Y BARRA DE HERRAMIENTAS 773 11.2 TEMAS FRACTALES 786 11.3 MONTAÑA FRACTAL(corregir) 800 11.4 DIAGRAMAS DE VORONOI EN MODO GRAFICO 809 11.5 TRABAJO DE APLICACIÓN DE REDES DE OPTIMIZACION 813 11.6 SIMULACION DE POLITICAS DE INVENTARIOS DE CONTROL DE INVENTARIOS 826 11.7 TRIANGULACION DE DELAUNAY 830 1.8 PROGRAMA EDUCATIVO EL PUREK(para aprender operaciones matemáticas) 837 11.9 APLICACIÓN DE TRADUCTOR DE ARCHIVOS 843 11.10 BUSCADOR 846 11.11 PROBLEMA DE CRUCE 851 11.12 PROGRAMA DE LOCALIZACION DE LOTES 853 11.13 MODELADO 3D si tiene los siguientes puntos para un cubo realizar el modelado 3D 860 11.13 MODELADO 3D si tiene los siguientes puntos para un cubo realizar el modelado 3D 876 11.15 PROBLEMA DE CONDUCCION DE VEHICULOS 879 11.16 PROBLEMA DE CONDUCCION DE VEHICULOS USADO BITMAPS 885 11.18 MOVER UN ARCHIVO DE TEXTO Elaborar un programa que mueva un archivo de texto por la pantalla 895 11.19 VER UNA PARTE DE LA PANTALLA Modificar el programa para ver parte de una pantalla(corregir) 898 11.20 MADURACION DE UNA FRUTA (ejemplo platanos) 904 11.21 JUEGO DEL PACMAN (corregir) 911 11.22 APLICACIONES DE REDES NEURONALES PERCEPTRON 920 11.23 APLICACIONES DE LOGICA DIFUSA EN CONTROL DE TEMPERATURA 930 11.24 APLICACIÓN DEL MODELOS DEL SIMPLEX 935 11.25 APLICACIÓN DEL MODELOS DEL SIMPLEX METODO GRAFICO 949 11.26 GRAFICA DE FUNCIONES EN 2D Y 3D 959 11.26 GENERACION DE MONTAÑAS CON AUTOMATAS CELULARES(corregir) 968 12 28 Prender y Apagar un Foco con Arduino 978 11-30 PROCESAMIENTO DE IMAGNES EN VISUAL BASIC 2012 995 11.34 TRANSFORMACIONES CON BITMAPS 1031

Lp11 Aplicaciones Windows Form

Embed Size (px)

DESCRIPTION

visual studio

Citation preview

Page 1: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -745-

11 APLICACIONES EN WINDOWS FORMIndice

11.1 EJEMPLO DE APLICACIÓN COMPLETA CON MENUS Y BARRA DE HERRAMIENTAS 77311.2 TEMAS FRACTALES 78611.3 MONTAÑA FRACTAL(corregir) 80011.4 DIAGRAMAS DE VORONOI EN MODO GRAFICO 80911.5 TRABAJO DE APLICACIÓN DE REDES DE OPTIMIZACION 81311.6 SIMULACION DE POLITICAS DE INVENTARIOS DE CONTROL DE INVENTARIOS 82611.7 TRIANGULACION DE DELAUNAY 8301.8 PROGRAMA EDUCATIVO EL PUREK(para aprender operaciones matemáticas)83711.9 APLICACIÓN DE TRADUCTOR DE ARCHIVOS 84311.10 BUSCADOR 84611.11 PROBLEMA DE CRUCE 85111.12 PROGRAMA DE LOCALIZACION DE LOTES 85311.13 MODELADO 3D si tiene los siguientes puntos para un cubo realizar el modelado 3D 86011.13 MODELADO 3D si tiene los siguientes puntos para un cubo realizar el modelado 3D 87611.15 PROBLEMA DE CONDUCCION DE VEHICULOS 87911.16 PROBLEMA DE CONDUCCION DE VEHICULOS USADO BITMAPS 88511.18 MOVER UN ARCHIVO DE TEXTO Elaborar un programa que mueva un archivo de texto por la pantalla 89511.19 VER UNA PARTE DE LA PANTALLA Modificar el programa para ver parte de una pantalla(corregir) 89811.20 MADURACION DE UNA FRUTA (ejemplo platanos) 90411.21 JUEGO DEL PACMAN (corregir) 91111.22 APLICACIONES DE REDES NEURONALES PERCEPTRON 92011.23 APLICACIONES DE LOGICA DIFUSA EN CONTROL DE TEMPERATURA 93011.24 APLICACIÓN DEL MODELOS DEL SIMPLEX 93511.25 APLICACIÓN DEL MODELOS DEL SIMPLEX METODO GRAFICO 94911.26 GRAFICA DE FUNCIONES EN 2D Y 3D 95911.26 GENERACION DE MONTAÑAS CON AUTOMATAS CELULARES(corregir) 96812 28 Prender y Apagar un Foco con Arduino 978

11-30 PROCESAMIENTO DE IMAGNES EN VISUAL BASIC 2012 995

11.34 TRANSFORMACIONES CON BITMAPS 103111.34 JUEGO DE LA SERPIENTE O GUSANO 103511.35 TRABAJO CON BITMAPS 103911.35 PROBLEMA DEL BARQUITO EN MODO VISUAL 1044

11.1 EJEMPLO DE APLICACIÓN COMPLETA CON MENUS Y BARRA DE HERRAMIENTAS

1. TRABAJANDO CON INTERFACES DE MULTIPLES DOCUMENTOS

Page 2: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -746-

Cuando trabajamos con aplicaciones Windows, existen dos tipos de interfaces o formas de presentar la información en pantalla , éstas son:1. Interface de Simple Documentos (SDI): Presenta un documento en su propia

ventana, cada ventana es independiente. Por ejemplo se usan SDI, el bloc de notas, el Paint, el WordPad, Office 2000, etc.

2. Interface de Múltiples Documentos (MDI) : Presenta todos los documentos sobre una ventana principal (Formulario padre) sobre la cual se muestra cada documento en su ventana secundaria (Formulario hijo). Por ejemplo , se usan MDI: el Visual Estudio.NET, SQL Enterprise Manager, Office 97, etc.

El ejemplo trata sobre un Editor de documentos similar al Wordpad , pero con funciones básicas . Este ejemplo trabaja con dos formularios ; el primero es un formulario MDI padre que tiene un menú principal , barras de herramientas y barra de estado; el segundo formulario es la base para crear formularios MDI hijos que representan un documento donde pueda escribir textos enriquecidos. Formato rtf

1. Crear un Aplicación Windows en Visual Basic .NET llamado FormularioMDI2. En el Diseñador de formularios Windows, arrastrar 1 control MenuStrip1, 1

ToolStrip1,1 StatusStrip1, 1 OpenFileDialog, 1 SaveFileDialog, 1 ColorDialog, 1 FontDialog, 1 Timer , luego configurar las propiedades tal como se muestra en el siguiente cuadro:

Objeto Propiedad ValorForm1 isMdiContainer

TextTrueEditor de Documentos v 1.0

MenuStrip1 Name MenuStrip1OpenFileDialog1 Name OpenFileDialog1SaveFileDialog1 Name SaveFileDialog1ColorDialog1 Name ColorDialog1FontDialog1 Name FontDialog1Timer1 Name Timer1ToolStrip1 Name ToolStrip1

Page 3: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -747-

StatusStrip1 name StatusStrip1

3. Seleccione el control MenuStrip1 y en la parte superior donde dice “Escriba aqui”, Escriba directamente los textos del Menú y configure sus propiedades tal como se muestra en el siguiente cuadro:

Objeto Propiedad ValorMenuItem1 Name

TextmnuArchivo&Archivo

MenuItem11 NameShortCutText

mnuNuevoCtrlN&Nuevo

MenuItem12 NameShortCutText

mnuAbrirCtrlA&Abrir

MenuItem13 NameShortCutText

mnuGuardarCtrlG&Guardar

MenuItem14 NameText

mnuLinea1-

MenuItem15 NameShortCutText

mnuSalirCtrlS&Salir

MenuItem2 NameText

mnuEdición&Edición

MenuItem21 NameShortCutText

mnuCopiarCtrlC&Copiar

MenuItem22 NameShortCutText

mnuCortarCtrlXCo&rtar

MenuItem23 NameShortCutText

MnuPegarCtrlV&Pegar

MenuItem3 NameText

mnuFormato&Formato

MenuItem31 NameText

mnuFuenteFuente

MenuItem32 NameText

mnuFondoColor de Fondo

MenuItem4 NameText

mnuUtilitario&Utilitarios

MenuItem41 NameText

mnuWindowsWindows

MenuItem411 NameText

mnuCalculadoraCalculadora

MenuItem412 NameText

MnuBlocBloc de Notas

MenuItem413 NameText

mnuExploradorExplorador

MenuItem42 Name MnuOffice

Page 4: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -748-

Text OfficeMenuItem421 Name

TextMnuWordWord

MenuItem422 NameText

MnuExcelExcel

MenuItem423 NameText

mnuInternetInternet Explorer

MenuItem5 NameText

mnuVentana&Ventana

MenuItem51 NameTagText

Cascada0Cascada

MenuItem52 NameTagText

mnuMHorizontal1Mosaico Horizontal

MenuItem53 NameTagText

mnuMVertical2Mosaico Vertical

MenuItem54 NameTagrText

mnuOIcons3Organizar Iconos

MenuItem55 NameText

MnuLinea2-

MenuItem56 NameMdiListText

MnuListarTrueListar Ventanas

Para cambiar el nombre de cada menú hacer clic en menu strip y luego editar elementos

Aparece el siguiente cuadro

Page 5: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -749-

Elija DropDownItems

Hay podria cambiar los nombresTambien podria cambiar con el cuadro de propiedades

Page 6: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -750-

4. Seleccione el control ToolStrip1 y Clic al botón de abrir diálogo de la propiedad items, luego añadir nueve botones y configurar sus propiedades , tal como se meustran en el siguiente cuadro:

En image escoger

Page 7: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -751-

Objeto Propiedad ValorToolBarButton1 Name

ImageToolTipTextTag

tbbNuevo…\bitmaps\Tlbr_W95\New.bmpNuevoNuevo

ToolBarButton2 NameImageIndexToolTipTextTag

tbbAbrir\bitmaps\Tlbr_W95\Open.bmpAbrirAbrir

ToolBarButton3 NameImageIndexToolTipTextTag

tbbGuardarSave.bmpGuardarGuardar

ToolBarButton4 NameStyleTag

tbbSeparador1SeparatorSeparator1

ToolBarButton5 NameImageIndexToolTipTextTag

tbbCopiar…\bitmaps\Tlbr_W95\Copy.bmpCopiarCopiar

ToolBarButton6 NameImageIndexToolTipTextTag

tbbCortar…\bitmaps\Tlbr_W95\Copy.bmpCortarCortar

ToolBarButton7 NameImageIndexToolTipTextTag

tbbPegar…\bitmaps\Tlbr_W95\paste.bmpPegarPegar

ToolBarButton8 NameStyleTag

tbbSeparador2SeparatorSeparator2

ToolBarButton9 NameImageIndexToolTipTextTag

tbbSalir…\bitmaps\Tlbr_W95\redo.bmp6SalirSalir

Al final debe quedar así

Page 8: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -752-

5. Seleccione el control StatusStrip1 y Clic al botón de editar elementos luego añadir tres paneles y configurar sus propiedades , tal como se muestran en el siguiente cuadro:

Objeto Propiedad ValorStatusBarPanel1

NameIconWidth

sbpNombre…\Icons\Writing\Book01A.ico

StatusBarPanel2

NameText

sbpMayusculaCAPS

StatusBarPanel Name sbpFechaHora

Page 9: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -753-

3

6. Añadir un segundo formulario; del menú “Project” elegir “Add” Windows Form” , escribir como nombre frmDocumento y clic “Open”.

7. Seleccionar el formulario frmDocumento arrastrar un control ContextMenu y 1 RichTextBox, luego configurar sus propiedades, tal como se muestra en el siguiente cuadro.

Objeto Propiedad ValorForm2 Text DocumentoContextMenuStrip2 Name ContextMenuStrip2RichTextBox1 Name

ContextMenuDock

RichTextBox1ContextMenuStripFill

8. El diseño del formulario deberia quedar así

9. Regresar al formulario frmEditor y en la ventana explorador de soluciones dar click en el botón “View Code” copiar el siguiente código

Codigo de formulario

Imports System.IO 'Usar PathPublic Class Form1 Private intNumDoc As Integer Private Sub IniciarConfiguracion(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Clipboard.SetDataObject("") sbpFechaHora.Text = Now.ToLongTimeString sbpFechaHora.ToolTipText = Now.ToLongDateString End Sub

Page 10: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -754-

Private Sub NuevoDocumento(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuNuevo.Click intNumDoc = intNumDoc + 1 Dim X As New frmDocumento() X.MdiParent = Me X.Text = "Documento " & intNumDoc.ToString sbpNombre.Text = "Documento " & intNumDoc.ToString X.Show() End Sub

Private Sub AbrirDocumento(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuAbrir.Click With OpenFileDialog1 'Dialogo de Abrir .Title = "Abrir Documento rtf" .Filter = "Documento rtf|*.rtf" If .ShowDialog = DialogResult.OK Then If Me.MdiChildren.Length = 0 Then MnuNuevo.PerformClick() Dim rtb As RichTextBox = Me.ActiveMdiChild.Controls(0) rtb.LoadFile(.FileName, RichTextBoxStreamType.RichText) Me.ActiveMdiChild.Text = Path.GetFileName(.FileName) sbpNombre.Text = Path.GetFileName(.FileName) End If End With End Sub

Private Sub GuardarDocumento(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuGuardar.Click If Me.MdiChildren.Length > 0 Then With SaveFileDialog1 'Dialogo de Guardar .Title = "Guardar Documento rtf" .Filter = "Documento rtf|*.rtf" If .ShowDialog = DialogResult.OK Then Dim rtb As RichTextBox = Me.ActiveMdiChild.Controls(0) rtb.SaveFile(.FileName, RichTextBoxStreamType.RichText) Me.ActiveMdiChild.Text = Path.GetFileName(.FileName) sbpNombre.Text = Path.GetFileName(.FileName) End If End With End If End Sub Private Sub Salir(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuSalir.Click Me.Close() End Sub

Private Sub CopiarTexto(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuCopiar.Click If Me.MdiChildren.Length > 0 Then Dim rtb As RichTextBox = Me.ActiveMdiChild.Controls(0) If rtb.SelectedText <> "" Then Clipboard.SetDataObject(rtb.SelectedText) End If End Sub

Page 11: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -755-

Private Sub CortarTexto(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuCortar.Click If Me.MdiChildren.Length > 0 Then Dim rtb As RichTextBox = Me.ActiveMdiChild.Controls(0) If rtb.SelectedText <> "" Then Clipboard.SetDataObject(rtb.SelectedText) rtb.SelectedText = "" End If End If End Sub Private Sub PegarTexto(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuPegar.Click If Me.MdiChildren.Length > 0 Then Dim rtb As RichTextBox = Me.ActiveMdiChild.Controls(0) rtb.SelectedText = Clipboard.GetDataObject.GetData("Text") End If End Sub Private Sub CambiarFuente(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuFuente.Click If Me.MdiChildren.Length > 0 Then With FontDialog1 'Dialogo de Fuente .ShowColor = True If .ShowDialog() = DialogResult.OK Then Dim rtb As RichTextBox = Me.ActiveMdiChild.Controls(0) rtb.Font = .Font rtb.ForeColor = .Color End If End With End If End Sub

Private Sub CambiarColorFondo(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuFondo.Click If Me.MdiChildren.Length > 0 Then With ColorDialog1 'Dialogo de Colores If .ShowDialog = DialogResult.OK Then Dim rtb As RichTextBox = Me.ActiveMdiChild.Controls(0) rtb.BackColor = .Color End If End With End If End Sub Private Sub AbrirCalculadora(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuCalculadora.Click Process.Start("Calc.exe") End Sub Private Sub AbrirBlocNotas(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuBlocDeNotas.Click Process.Start("Notepad.exe") End Sub

Page 12: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -756-

Private Sub AbrirExplorador(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuExplorador.Click Process.Start("Explorer.exe") End Sub

Private Sub AbrirWord(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuWord.Click Process.Start("Winword.exe") End Sub Private Sub AbrirExcel(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuExcel.Click Process.Start("Excel.exe") End Sub Private Sub INTERNET(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuExcel.Click Process.Start("IEXPLORE.EXE") End Sub Private Sub AbrirInternet(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuInternet.Click Process.Start("IExplore.exe") End Sub Private Sub PresentarVentanas(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuCascada.Click, mnuMHorizontal.Click, mnuMVertical.Click, mnuOIconos.Click Me.LayoutMdi(sender.TAG) End Sub

Private Sub MostrarNombre(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.MdiChildActivate If Me.ActiveMdiChild Is Nothing Then sbpNombre.Text = "" Else sbpNombre.Text = Me.ActiveMdiChild.Text End If End Sub Private Sub VerHora(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick sbpFechaHora.Text = Now.ToLongTimeString End Sub Private Sub ToolStrip1_ItemClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.ToolStripItemClickedEventArgs) Handles ToolStrip1.ItemClicked Select Case e.ClickedItem.Tag Case "Nuevo" MnuNuevo.PerformClick() Case "Abrir" MnuAbrir.PerformClick() Case "Guardar" MnuGuardar.PerformClick() Case "Copiar" mnuCopiar.PerformClick() Case "Cortar"

Page 13: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -757-

mnuCortar.PerformClick() Case "Pegar" MnuPegar.PerformClick() Case "Salir" mnuSalir.PerformClick() End Select End Sub Private Sub ListarToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Listar.Click If Me.ActiveMdiChild Is Nothing Then sbpNombre.Text = "" Else sbpNombre.Text = Me.ActiveMdiChild.Text End If End SubEnd Class

Ejecute el programa . la aplicación debera quedar asi

Nota clic derecho en el menú strip y clic en insertar elementos estándar

Page 14: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -758-

Y automáticamente se inserta los elementos estándar

Lo mismo puede hacer con toolstrip y automáticamente adiciona los controles estándar

Al presionar editar elementos aparece el cuadro

Que nos permite editar los elementos

Page 15: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -759-

11.2 TEMAS FRACTALES

FRACTAL De Wikipedia, la enciclopedia libre

En la naturaleza también aparece la geometría fractal, como en esta romanescu.Un fractal es un objeto geométrico cuya estructura básica, fragmentada o irregular, se repite a diferentes escalas.1 El término fue propuesto por el matemático Benoît Mandelbrot en 1975 y deriva del Latín fractus, que significa quebrado o fracturado. Muchas estructuras naturales son de tipo fractal. La propiedad matemática clave de un objeto genuinamente fractal es que su dimensión métrica fractal es un número no entero.

Alfombra de Sierpinski De Wikipedia, la enciclopedia libre

La alfombra de Sierpiński es un conjunto fractal descrito por primera vez por Wacław Sierpiński en 1916.1 Constituye una generalización a dos dimensiones del conjunto de Cantor. Comparte con él muchas propiedades: también es un conjunto compacto, no numerable y de medida nula. Su dimensión de Hausdorff-Besicovitch es

Construcción La construcción de la alfombra de Sierpinski se define de forma recursiva:

1. Comenzamos con un cuadrado.2. El cuadrado se corta en 9 cuadrados congruentes, y eliminamos el cuadrado

central.3. El paso anterior vuelve a aplicarse recursivamente a cada uno de los 8

cuadrados restantes.La alfombra de Sierpinski es el límite de este proceso tras un número infinito de iteraciones.

Construcción de la alfombra de Sierpinski:

Paso 1 Paso 2 Paso 3 Paso 4 Paso 5

Código en Visual Basic

Page 16: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -760-

Option Explicit OnImports System.DrawingPublic Class Form1 Dim Grafico As Graphics Dim ancho As Integer = 500, alto As Integer = 500 Dim ancho1 As Integer Dim alto1 As Integer Dim Cx As Integer = 0, Cy As Integer = 0 Dim Cx1 As Integer, Cy1 As Integer Sub CuadroRecursivo(ByVal Cx As Integer, ByVal Cy As Integer, ByVal Ancho As Integer, ByVal Alto As Integer) Dim fila As Integer, col As Integer ancho1 = Ancho / 3 : alto1 = Alto / 3 Cy1 = Cy For fila = 1 To 3 Cx1 = Cx For col = 1 To 3 If fila = 2 And col = 2 Then Grafico.FillRectangle(Brushes.Blue, Cx1, Cy1, ancho1, alto1) Else ' Grafico.DrawRectangle(Pens.Green, Cx1, Cy1, ancho1, alto1) End If Cx1 = Cx1 + ancho1 Next Cy1 = Cy1 + alto1 Next fila If (Ancho > 10) Then For fila = 0 To 2 For col = 0 To 2 CuadroRecursivo(Cx + col * Ancho / 3, Cy + fila * Alto / 3, Ancho / 3, Alto / 3) Next Next End If End Sub Private Sub Button1_Click(ByVal sender As System.Object, _

Page 17: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -761-

ByVal e As System.EventArgs) Handles BtnFractal.Click Grafico = PictureBox1.CreateGraphics CuadroRecursivo(Cx, Cy, Ancho, Alto) End Sub

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load PictureBox1.Width = ancho + 1 PictureBox1.Height = alto + 1 End SubEnd Class

Triángulo de Sierpinski De Wikipedia, la enciclopedia libreEl triángulo de Sierpiński es un fractal que se puede construir a partir de cualquier triángulo.

Option Explicit OnImports System.DrawingPublic Class Form1 Dim Grafico As Graphics Function distancia(ByVal x1 As Single, ByVal y1 As Single, ByVal x2 As Single, ByVal y2 As Single) distancia = Math.Sqrt(Math.Pow(x2 - x1, 2) + Math.Pow(y2 - y1, 2)) End Function

Page 18: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -762-

Sub triangulo(ByVal px1 As Single, ByVal py1 As Single, ByVal px2 As Single, ByVal py2 As Single, _ByVal px3 As Single, ByVal py3 As Single) Dim px12 As Single, py12 As Single, px13 As Single, py13 As Single, px23 As Single, py23 As Single Grafico.DrawLine(Pens.Green, px1, py1, px2, py2) Grafico.DrawLine(Pens.Blue, px2, py2, px3, py3) Grafico.DrawLine(Pens.Red, px3, py3, px1, py1) If (distancia(px1, py1, px2, py2) > 5) Then px12 = (px1 + px2) / 2.0 px13 = (px1 + px3) / 2.0 px23 = (px2 + px3) / 2.0 py12 = (py1 + py2) / 2.0 py13 = (py1 + py3) / 2.0 py23 = (py2 + py3) / 2.0 ' triangulo(px12, py12, px23, py23, px13, py13) triangulo(px1, py1, px12, py12, px13, py13) triangulo(px2, py2, px12, py12, px23, py23) triangulo(px3, py3, px13, py13, px23, py23) End If End Sub Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles BtnFractal.Click Grafico = PictureBox1.CreateGraphics Dim Px1 As Integer = 300, py1 As Integer = 10, px2 As Integer = 500, py2 As Integer = 400 Dim px3 As Integer = 100, py3 As Integer = 400 triangulo(Px1, py1, px2, py2, px3, py3) End Sub Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load PictureBox1.Width = 510 PictureBox1.Height = 410 End SubEnd Class

Considerando los cuatros triangulos

Aleatorizando (modelizacion de terrenos )

Page 19: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -763-

Imports System.DrawingPublic Class Form1 Dim Grafico As Graphics Dim ColorFondo As Color = Color.FromArgb(255, 255, 255) Dim pen As Pen Dim valor As Integer = 10 Dim ancho = 600, alto = 400 Function distancia(ByVal x1 As Single, ByVal y1 As Single, ByVal x2 As Single, ByVal y2 As Single) distancia = Math.Sqrt(Math.Pow(x2 - x1, 2) + Math.Pow(y2 - y1, 2)) End Function Sub triangulo(ByVal px1 As Single, ByVal py1 As Single, ByVal px2 As Single, ByVal py2 As Single, ByVal px3 As Single, ByVal py3 As Single) Dim px12 As Single, py12 As Single, px13 As Single, py13 As Single Dim px23 As Single, py23 As Single

Grafico.DrawLine(pen, px1, py1, px2, py2) Grafico.DrawLine(pen, px2, py2, px3, py3) Grafico.DrawLine(pen, px3, py3, px1, py1) If (distancia(px1, py1, px2, py2) > 50) Then ' triangulo del punto1 pen.Color = ColorFondo Grafico.DrawLine(pen, px1, py1, px2, py2) Grafico.DrawLine(pen, px2, py2, px3, py3)

Page 20: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -764-

Grafico.DrawLine(pen, px3, py3, px1, py1) pen.Color = Color.Blue px12 = (px1 + px2) / 2.0 - valor + Int(Rnd(2 * valor)) px13 = (px1 + px3) / 2.0 - valor + Int(Rnd(2 * valor)) px23 = (px2 + px3) / 2.0 - valor + Int(Rnd(2 * valor)) py12 = (py1 + py2) / 2.0 - valor + Int(Rnd(2 * valor)) py13 = (py1 + py3) / 2.0 - valor + Int(Rnd(2 * valor)) py23 = (py2 + py3) / 2.0 - valor + Int(Rnd(2 * valor)) triangulo(px12, py12, px23, py23, px13, py13) triangulo(px1, py1, px12, py12, px13, py13) triangulo(px2, py2, px12, py12, px23, py23) triangulo(px3, py3, px13, py13, px23, py23) End If End Sub Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles BtnFractal.Click Grafico = PictureBox1.CreateGraphics Dim Px1 As Integer = 300, py1 As Integer = 10, px2 As Integer = 600, py2 As Integer = 400 Dim px3 As Integer = 10, py3 As Integer = 400 pen = New Pen(Color.Blue, 2) Grafico.Clear(ColorFondo) Randomize() triangulo(Px1, py1, px2, py2, px3, py3) End Sub Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load PictureBox1.Width = ancho + 10 PictureBox1.Height = alto + 10 PictureBox1.BackColor = ColorFondo End SubEnd Class

ARBOLES CON RECURSIVIDAD

Page 21: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -765-

Option Explicit OnImports System.DrawingPublic Class Form1 Dim Grafico As Graphics Dim pen As Pen Dim ancho As Integer = 500, alto As Integer = 320 Const dx As Single = 0.6 Sub Arbol(ByVal x As Single, ByVal y As Single, ByVal t As Single, ByVal teta As Single, ByVal w As Single, ByVal valor As Single) '// t=largo Dim x1 As Single, y1 As Single, t1 As Single If (t > 1) Then '//condición de paro ' If (valor >= 1) Then '//condición de paro pen.Width = valor x1 = x + t * Math.Cos(teta) y1 = y + t * Math.Sin(teta) Grafico.DrawLine(pen, x, y, x1, y1) t1 = t / 1.8 '1.7 ' Se llama recursivamente al sistema} Arbol(x1, y1, t1, teta - w, w, valor - dx) Arbol(x1, y1, t1, teta, w, valor - dx) Arbol(x1, y1, t1, teta + w, w, valor - dx) End If End Sub Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles BtnArbol.Click Grafico = PictureBox1.CreateGraphics pen = New Pen(Color.Green, 1) Arbol(150, 300, 120, 3 * Math.PI / 2.0, 0.5, 5) pen = New Pen(Color.FromArgb(0, 0, 255), 1) Arbol(350, 300, 100, 3 * Math.PI / 2.0, 0.4, 4) pen = New Pen(Color.Coral, 1) Arbol(420, 300, 50, 3 * Math.PI / 2.0, 0.3, 3) End Sub

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load PictureBox1.Width = ancho + 1 PictureBox1.Height = alto + 1 End SubEnd Class

Copo de nieve de Koch

El copo de nieve de Koch, también llamado estrella de Koch, es una curva cerrada continua pero no diferenciable en ningún punto descrita por el matemático sueco Helge von Koch en 1904 en un artículo titulado "Acerca de una curva continua que no posee tangentes y obtenida por los métodos de la geometría elemental". [1] [2]

En lenguaje actual, diríamos que es una curva fractal. Su construcción más simple se realiza mediante un proceso iterativo que se inicia partiendo en tres un segmento de

Page 22: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -766-

recta e insertando dos más en el tercero medio a manera de un triángulo equilátero, el proceso se repite infinidad de veces. La curva de Koch es un caso particular de curva de De Rham.

Código en Visual Basic

Option Explicit OnImports System.DrawingPublic Class Form1 Dim Grafico As Graphics Dim pen As Pen Const alfa As Single = 1.047 Dim Cx As Single = 200, Cy As Single = 200 Dim Colorfondo As Color = Color.FromArgb(255, 255, 255) Dim ancho As Integer = 500, alto As Integer = 400 Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long) Function distancia(ByVal x1 As Single, ByVal y1 As Single, ByVal x2 As Single, ByVal y2 As Single) As Single distancia = Math.Sqrt(Math.Pow(x2 - x1, 2) + Math.Pow(y2 - y1, 2)) End Function Sub Fractal(ByVal px1 As Single, ByVal py1 As Single, ByVal px2 As Single, ByVal py2 As Single) Dim ax As Single, ay As Single Dim x1 As Single, y1 As Single, x2 As Single, y2 As Single, x3 As Single, y3 As Single, rx As Single, ry As Single ax = (px2 - px1) / 3.0 ay = (py2 - py1) / 3.0 pen.Color = Color.Blue Grafico.DrawLine(pen, Cx + px1, Cy + py1, Cx + px2, Cy + py2) x1 = Cx + px1 + ax y1 = Cy + py1 + ay rx = ax * Math.Cos(alfa) - ay * Math.Sin(alfa) ry = ax * Math.Sin(alfa) + ay * Math.Cos(alfa) x2 = x1 + rx y2 = y1 + ry x3 = Cx + px1 + 2 * ax y3 = Cy + py1 + 2 * ay Grafico.DrawLine(pen, x1, y1, x2, y2) Grafico.DrawLine(pen, x2, y2, x3, y3) pen.Color = Colorfondo

Page 23: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -767-

Grafico.DrawLine(pen, x1, y1, x3, y3) Sleep(5) If distancia(px1, py1, px2, py2) > 10 Then Fractal(px1 + ax, py1 + ay, px1 + ax + rx, py1 + ay + ry) Fractal(px1 + ax + rx, py1 + ay + ry, px1 + 2 * ax, py1 + 2 * ay) Fractal(px1, py1, px1 + ax, py1 + ay) Fractal(px1 + 2 * ax, py1 + 2 * ay, px2, py2) End If End Sub Private Sub MostrarFractal(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles BtnFractal.Click Grafico = PictureBox1.CreateGraphics pen = New Pen(Color.Gold, 3) Grafico.DrawLine(pen, Cx, 0, Cx, alto) Grafico.DrawLine(pen, 0, Cy, ancho, Cy) Dim Px1 As Integer = 200, py1 As Integer = 0, px2 As Integer = 200, py2 As Integer = 0 Dim Px3 As Integer = 100, py3 As Integer = 0 px2 = Px1 * Math.Cos(2 * alfa) - py1 * Math.Sin(2 * alfa) py2 = Px1 * Math.Sin(2 * alfa) + py1 * Math.Cos(2 * alfa) Px3 = px2 * Math.Cos(2 * alfa) - py2 * Math.Sin(2 * alfa) py3 = px2 * Math.Sin(2 * alfa) + py2 * Math.Cos(2 * alfa) pen.Color = Color.Blue Grafico.DrawLine(pen, Cx + Px1, Cy + py1, Cx + px2, Cy + py2) Grafico.DrawLine(pen, Cx + px2, Cy + py2, Cx + Px3, Cy + py3) Grafico.DrawLine(pen, Cx + Px3, Cy + py3, Cx + Px1, Cy + py1) Fractal(Px1, py1, Px3, py3) Fractal(Px3, py3, px2, py2) Fractal(px2, py2, Px1, py1) End Sub Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load PictureBox1.Width = ancho + 10 PictureBox1.Height = alto + 10 PictureBox1.BackColor = Colorfondo End SubEnd Class

Page 24: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -768-

FRACTALES DE MALDEBROT

Option Explicit OnOption Strict OnModule Module1 Public brocha As SolidBrush Public Const limite As Integer = 200 Public Grafico As Graphics Public nc As Integer = 5 Public nf As Integer = 6 '6 Public Pen As Pen Public vel As Integer = 10 Public nx As Integer = 100 Public ny As Integer = 100 Public MaxIter As Integer = 10

'/* E s t a b l e c e el tamaño i n i c i a l de l a ventana de v i s u a l i z a c i ó n . */ 'Public winWidth As Integer = 500 'Public winHeight As Integer = 500 '// Establace los limites del area rectangular del plano complejo “ Public xComplexMin As Single = -2 ' -200 * 4 '-2.0 Public xComplexMax As Single = 0.5 ' 50 * 8 ' 0.5 Public yComplexMin As Single = -1.25 '-125 * 4 '-1.25 Public yComplexMax As Single = 1.25 '125 * 4 '1.25 Public complexWidth As Single = xComplexMax - xComplexMin Public complexHeight As Single = yComplexMax - yComplexMin Public Ex As Single = 100 Public Ey As Single = 100 Public Cx As Single = 300 Public cy As Single = 300 Public Structure Color1 Public r As Integer Public g As Integer Public b As Integer

Page 25: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -769-

End Structure Public Structure complexNum Public x As Single Public y As Single End Structure

'/* Calcula el cuadrado de un número c o m p l e j o . */ Function complexSquare(ByVal z As complexNum) As complexNum Dim zSquare As complexNum zSquare.x = z.x * z.x - z.y * z.y zSquare.y = 2 * z.x * z.y 'complexSquare = zSquare Return zSquare End Function

Function mandelSqTransf(ByVal z0 As complexNum, ByVal maxIter As Integer) As Integer Dim z As complexNum = z0 Dim count As Integer = 0 '/* Sale cuando z * z > 4 */ Dim valor As Single valor = z.x * z.x + z.y * z.y While (valor <= 8.0) And (count < maxIter) z = complexSquare(z) z.x += z0.x z.y += z0.y count += 1 valor = z.x * z.x + z.y * z.y End While Return count End FunctionEnd Module

CODIGO DE FORMULARIO

Option Explicit OnOption Strict OnImports System.DrawingImports System.Drawing.Drawing2DPublic Class Form1 Dim Pen As Pen Dim Grafico As Graphics Dim brocha As SolidBrush Sub plotPoint(ByVal zx As Single, ByVal zy As Single) Grafico.FillRectangle(brocha, Cx + zx * Ex, cy + zy * Ey, 4, 4) End Sub

Sub mandelbrot(ByVal nx As Integer, ByVal ny As Integer, ByVal maxIter As Integer) Dim zx As Single Dim zy As Single Dim z, zlncr As complexNum Dim ptColor As Color1

Page 26: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -770-

Dim iterCount As Integer zlncr.x = complexWidth / nx zlncr.y = complexHeight / ny For z.x = xComplexMin To xComplexMax Step zlncr.x For z.y = yComplexMin To yComplexMax Step zlncr.y iterCount = mandelSqTransf(z, maxIter) If (iterCount >= maxIter) Then '/* Establece el color de los p u n t o s en n e g r o . */ ptColor.r = 0 ptColor.g = 0 ptColor.b = 0 Else If (iterCount > (maxIter / 8)) Then '/* Establece el color de los puntos en naranja . */ ptColor.r = 255 ptColor.g = 125 ptColor.b = 0 Else If (iterCount > (maxIter / 10)) Then '/* E s t a b l e c e el c o l o r de l o s p u n t o s en r o j o . */ ptColor.r = 255 '1.0 ptColor.g = 0 ptColor.b = 0 Else If (iterCount > (maxIter / 20)) Then '/* E s t a b l e c e el c o l o r de l o s puntos en azul o s c u r o . */ ptColor.r = 128 ' 0.5 ptColor.r = 0 ptColor.g = 0 Else If (iterCount > (maxIter / 40)) Then '/* E s t a b l e c e el c o l o r de l o s puntos en a m a r i l l o . */ ptColor.r = 255 ptColor.g = 255 ptColor.b = 0 Else If (iterCount > (maxIter / 100)) Then '/* E s t a b l e c e el c o l o r de l o s puntos en * verde o s c u r o . */ ptColor.r = 0 ptColor.b = 0 ptColor.g = 80 ' 0.3 Else '/* E s t a b l e c e e l c o l o r de l os * puntos en c í a n . */ ptColor.r = 0 ptColor.g = 255 ptColor.b = 255 End If End If End If End If End If End If

Page 27: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -771-

brocha.Color = Drawing.Color.FromArgb(ptColor.r, ptColor.g, ptColor.b) zx = z.x zy = z.y plotPoint(zx, zy) Next Next End Sub

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Grafico = PictureBox1.CreateGraphics Pen = New Pen(Color.Red, 2) brocha = New SolidBrush(Color.FromArgb(0, 255, 0)) End Sub

Private Sub BtnFractal_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnFractal.Click btnIniciarTodo_Click(sender, e) mandelbrot(nx, ny, MaxIter) End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnIniciar.Click DataGridView1.ColumnCount = 2 DataGridView1.RowCount = 7 DataGridView1.Columns(1).Width = 70 For fila = 0 To DataGridView1.RowCount - 1 DataGridView1.Rows(fila).HeaderCell.Value = fila.ToString Next DataGridView1.Columns(0).HeaderText = "PARAMETROS" DataGridView1.Columns(1).HeaderText = "VALOR" DataGridView1.Rows(0).Cells(0).Value = "Nx" DataGridView1.Rows(0).Cells(1).Value = nx

DataGridView1.Rows(1).Cells(0).Value = "Ny" DataGridView1.Rows(1).Cells(1).Value = ny

DataGridView1.Rows(2).Cells(0).Value = "MaxIter" DataGridView1.Rows(2).Cells(1).Value = MaxIter

DataGridView1.Rows(3).Cells(0).Value = "Cx" DataGridView1.Rows(3).Cells(1).Value = Cx

DataGridView1.Rows(4).Cells(0).Value = "Cy" DataGridView1.Rows(4).Cells(1).Value = Cy DataGridView1.Rows(5).Cells(0).Value = "Ex" DataGridView1.Rows(5).Cells(1).Value = Ex

DataGridView1.Rows(6).Cells(0).Value = "Ey" DataGridView1.Rows(6).Cells(1).Value = Ey End Sub Private Sub btnIniciarTodo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnIniciarTodo.Click

Page 28: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -772-

nx = CInt(DataGridView1.Rows(0).Cells(1).Value) ny = CInt(DataGridView1.Rows(1).Cells(1).Value) MaxIter = CInt(DataGridView1.Rows(2).Cells(1).Value) Cx = CSng(DataGridView1.Rows(3).Cells(1).Value) cy = CSng(DataGridView1.Rows(4).Cells(1).Value) Ex = CSng(DataGridView1.Rows(5).Cells(1).Value) Ey = CSng(DataGridView1.Rows(6).Cells(1).Value) End Sub

Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnBorrar.Click Grafico.Clear(Color.White) End SubEnd Class

11.3 MONTAÑA FRACTAL(corregir)

Page 29: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -773-

Module Module1 Public Structure Puntos Public nro As Integer Public X As Single Public Y As Single Public Z As Single Public Rela As Integer End Structure Public Const maximo As Integer = 40000 Public P(maximo) As Puntos Public P1(maximo) As Puntos Public i As Integer Public k As Integer Sub CopiarVector(ByVal A() As Puntos, ByRef B() As Puntos, ByVal n As Integer) Dim fila As Integer For fila = 0 To n B(fila) = A(fila) Next End SubEnd Module

CODIGO DEL FORMULARIO

Option Explicit OnImports System.IOImports System.DrawingImports System.Drawing.Drawing2DPublic Class Form1 Dim Grafico As Graphics Dim ColorFondo As Color = Color.FromArgb(255, 255, 255) Dim pen As Pen Dim Brocha As SolidBrush Dim valor As Single Dim factor As Single = 0.5 Dim ancho = 700, alto = 500 Dim Ndivisiones As Integer Dim GradosX As Integer

Page 30: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -774-

Dim GradosY As Integer Dim GradosZ As Integer Dim Dx As Single Dim Dy As Single Dim Dz As Single Dim ContPuntos As Integer Dim MiFuente As New Font("Verdana", 24, FontStyle.Bold) Dim Tx As Single Dim Ty As Single Dim tz As Single Dim Ex As Single Dim Ey As Single Dim Ez As Single Dim CARAS(maximo, 4) As Integer Dim Normales(maximo, 4) As Single Dim D As Single = 1000 Dim contcaras As Integer Dim ver1 As Integer, ver2 As Integer, ver3 As Integer, ver4 As Integer Dim Modo As Integer

Sub ObtenerNormales() Dim Pe As Single, R As Single Dim AX As Single, Ay As Single, Az As Single, Bx As Single, By As Single, Bz As Single Dim NX As Single, Ny As Single, Nz As Single, Nx1 As Single, Ny1 As Single, Nz1 As Single Dim x1 As Single, y1 As Single, z1 As Single Dim x2 As Single, y2 As Single, z2 As Single Dim x3 As Single, y3 As Single, z3 As Single ListBox1.Items.Add("Normales") For fila = 0 To contcaras - 1 x1 = P1(CARAS(fila, 0)).X y1 = P1(CARAS(fila, 0)).Y z1 = P1(CARAS(fila, 0)).Z

x2 = P1(CARAS(fila, 1)).X y2 = P1(CARAS(fila, 1)).Y z2 = P1(CARAS(fila, 1)).Z x3 = P1(CARAS(fila, 2)).X y3 = P1(CARAS(fila, 2)).Y z3 = P1(CARAS(fila, 2)).Z

AX = x2 - x1 Ay = y2 - y1 Az = z2 - z1 Bx = x3 - x2 By = y3 - y2 Bz = z3 - z2 NX = Ay * Bz - Az * By Ny = AX * Bz - Az * Bx Nz = AX * By - Ay * Bx 'PRODUCTO(CRUZ)

Page 31: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -775-

R = Math.Sqrt(NX * NX + Ny * Ny + Nz * Nz) If R > 0 Then Nx1 = NX / R Else Nx1 = 1000 End If If R > 0 Then Ny1 = Ny / R Else Ny1 = 1000 End If If R > 0 Then Nz1 = Nz / R Else Nz1 = 1000 End If Pe = Nx1 * 0 + Ny1 * 0 + Nz1 * D Normales(fila, 0) = Nx1 Normales(fila, 1) = Ny1 Normales(fila, 2) = Nz1 Normales(fila, 3) = Pe ListBox1.Items.Add("normal" & Normales(fila, 2)) Next End Sub

Sub Rectangulo(ByVal px1 As Single, ByVal py1 As Single, ByVal pz1 As Single, _ ByVal px2 As Single, ByVal py2 As Single, ByVal pz2 As Single, _ ByVal px3 As Single, ByVal py3 As Single, ByVal pz3 As Single, _ ByVal px4 As Single, ByVal py4 As Single, ByVal pz4 As Single, _ ByVal ndivisiones As Integer, ByVal valor As Single, _ ByVal ver1 As Integer, ByVal ver2 As Integer, ByVal ver3 As Integer, ByVal ver4 As Integer)

Dim v1 As Integer, v2 As Integer, v3 As Integer, v4 As Integer Dim v12 As Integer, v23 As Integer, v34 As Integer, v14 As Integer Dim vmedio As Integer Dim px12 As Single, py12 As Single, pz12 As Single Dim px23 As Single, py23 As Single, pz23 As Single Dim px34 As Single, py34 As Single, pz34 As Single Dim px14 As Single, py14 As Single, pz14 As Single Dim xmed As Single, ymed As Single, zmed As Single Dim puntocentral As Integer If (ndivisiones > 1) Then xmed = (px1 + px2 + px3 + px4) / 4.0 ymed = (py1 + py2 + py3 + py4) / 4.0 'zmed = (pz1 + pz2 + pz3 + pz4) / 4.0 + Int(Rnd() * valor) zmed = (pz1 + pz2 + pz3 + pz4) / 4.0 - valor + Int(Rnd() * 2 * valor) ContPuntos = ContPuntos + 1 puntocentral = ContPuntos P(ContPuntos).nro = ContPuntos P(ContPuntos).X = xmed P(ContPuntos).Y = ymed

Page 32: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -776-

P(ContPuntos).Z = zmed P(ContPuntos).Rela = puntocentral vmedio = puntocentral px12 = (px1 + px2) / 2.0 px23 = (px2 + px3) / 2.0 px34 = (px3 + px4) / 2.0 px14 = (px1 + px4) / 2.0

py12 = (py1 + py2) / 2.0 py23 = (py2 + py3) / 2.0 py34 = (py3 + py4) / 2.0 py14 = (py1 + py4) / 2.0

pz12 = (pz1 + pz2) / 2.0 pz23 = (pz2 + pz3) / 2.0 pz34 = (pz3 + pz4) / 2.0 pz14 = (pz1 + pz4) / 2.0 ContPuntos = ContPuntos + 1 P(ContPuntos).nro = ContPuntos P(ContPuntos).X = px12 P(ContPuntos).Y = py12 P(ContPuntos).Z = pz12 P(ContPuntos).Rela = puntocentral v12 = ContPuntos ContPuntos = ContPuntos + 1 P(ContPuntos).nro = ContPuntos P(ContPuntos).X = px23 P(ContPuntos).Y = py23 P(ContPuntos).Z = pz23 P(ContPuntos).Rela = puntocentral v23 = ContPuntos

ContPuntos = ContPuntos + 1 P(ContPuntos).nro = ContPuntos P(ContPuntos).X = px34 P(ContPuntos).Y = py34 P(ContPuntos).Z = pz34 P(ContPuntos).Rela = puntocentral ' CARAS(ContCaras).P3 = P(ContPuntos).nro v34 = ContPuntos ContPuntos = ContPuntos + 1 P(ContPuntos).nro = ContPuntos P(ContPuntos).X = px14 P(ContPuntos).Y = py14 P(ContPuntos).Z = pz14 P(ContPuntos).Rela = puntocentral v14 = ContPuntos v1 = ver1 v2 = ver2 v3 = ver3 v4 = ver4

Page 33: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -777-

Rectangulo(px1, py1, pz1, px12, py12, pz12, xmed, ymed, zmed, px14, py14, pz14, ndivisiones - 1, valor * factor, v1, v12, vmedio, v14) Rectangulo(px12, py12, pz12, px2, py2, pz2, px23, py23, pz23, xmed, ymed, zmed, ndivisiones - 1, valor * factor, v12, v2, v23, vmedio) Rectangulo(xmed, ymed, zmed, px23, py23, pz23, px3, py3, pz3, px34, py34, pz34, ndivisiones - 1, valor * factor, vmedio, v23, v3, v34) Rectangulo(px14, py14, pz14, xmed, ymed, zmed, px34, py34, pz34, px4, py4, pz4, ndivisiones - 1, valor * factor, v14, vmedio, v34, v4) Else If ndivisiones = 1 Then CARAS(contcaras, 0) = ver1 CARAS(contcaras, 1) = ver2 CARAS(contcaras, 2) = ver3 CARAS(contcaras, 3) = ver4 contcaras = contcaras + 1 End If End If End Sub

Sub graficarCara(ByVal contcaras As Integer) Dim X1 As Single, y1 As Single, z1 As Single Dim X2 As Single, y2 As Single, z2 As Single Dim px1 As Single, py1 As Single Dim px2 As Single, py2 As Single Dim Figura(3) As Point Dim col As Integer Dim color1 As Integer For fila = 0 To contcaras - 1 For col = 0 To 2 X1 = P1(CARAS(fila, col)).X y1 = P1(CARAS(fila, col)).Y z1 = P1(CARAS(fila, col)).Z X2 = P1(CARAS(fila, col + 1)).X y2 = P1(CARAS(fila, col + 1)).Y z2 = P1(CARAS(fila, col + 1)).Z px1 = (X1 * D) / (D + z1) py1 = (y1 * D) / (D + z1) px2 = (X2 * D) / (D + z2) py2 = (y2 * D) / (D + z2) Figura(col).X = px1 Figura(col).Y = py1 Next Figura(3).X = px2 Figura(3).Y = py2 If Normales(fila, 2) > 0 Then 'solo dibuja si el normal es mayor que 0 If Modo = 0 Then ' si es modelo alambre Grafico.DrawPolygon(pen, Figura) Else color1 = Normales(fila, 2) * 255 Brocha.Color = Color.FromArgb(0, 255 - color1, 255 - color1) Grafico.FillPolygon(Brocha, Figura, FillMode.Alternate) End If

Page 34: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -778-

End If 'Grafico.DrawLine(pen, px1, py1, px2, py2) Next End Sub

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load PictureBox1.Width = ancho + 10 PictureBox1.Height = alto + 10 PictureBox1.BackColor = ColorFondo MiFuente = New Font("arial", 11, FontStyle.Bold) Brocha = New SolidBrush(Color.Red) Modo = 0 Ndivisiones = 7 End Sub

Private Sub MnuMontaña_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuMontaña.Click GradosX = 0 GradosY = 0 GradosZ = 0 Ex = 1 Ex = 1 Ex = 1 Tx = 0 Ty = 0 tz = 0 Randomize() 'Ndivisiones = 7 Grafico = PictureBox1.CreateGraphics valor = 200 Dim Px1 As Integer = 100, py1 As Integer = 100, pz1 As Integer = 10 Dim px2 As Integer = 600, py2 As Integer = 100, pz2 As Integer = 10 Dim px3 As Integer = 600, py3 As Integer = 400, pz3 As Integer = 10 Dim px4 As Integer = 100, py4 As Integer = 400, pz4 As Integer = 10 pen = New Pen(Color.Blue, 1) contcaras = 0 ver1 = 0 ver2 = 1 ver3 = 2 ver4 = 3 P(0).nro = 0 : P(0).X = Px1 : P(0).Y = py1 : P(0).Z = pz1 : P(0).Rela = 1 P(1).nro = 1 : P(1).X = px2 : P(1).Y = py2 : P(1).Z = pz2 : P(1).Rela = 2 P(2).nro = 2 : P(2).X = px3 : P(2).Y = py3 : P(2).Z = pz3 : P(2).Rela = 3 P(3).nro = 3 : P(3).X = px4 : P(3).Y = py4 : P(3).Z = pz4 : P(3).Rela = 0 ContPuntos = 3 ListBox1.Items.Clear() ListBox1.Items.Add("CANTIDAD de divisiones " & Ndivisiones) Randomize() Rectangulo(Px1, py1, pz1, px2, py2, pz2, px3, py3, pz3, px4, py4, pz4, Ndivisiones, valor, ver1, ver2, ver3, ver4) ListBox1.Items.Add("CANTIDAD DE Caras " & contcaras)

Page 35: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -779-

ListBox1.Items.Add("CANTIDAD DE puntos " & ContPuntos) For i = 0 To ContPuntos ListBox1.Items.Add("Punto Nro" & P(i).nro & " X " & P(i).X & " Y " & P(i).Y & " Z " & P(i).Z & "rela " & P(i).Rela) Next pen.Color = Color.Red Dim swEscritor As StreamWriter swEscritor = New StreamWriter("E:\DATOS\FRACTAL.txt") For i = 0 To ContPuntos swEscritor.WriteLine("{0}{1}{2}{3}{4}{5}{6}", P(i).nro, Chr(9), P(i).X, Chr(9), P(i).Y, Chr(9), P(i).Z) Next swEscritor.Close() CopiarVector(P, P1, ContPuntos) ObtenerNormales() graficarCara(contcaras) End Sub

Private Sub MnuEscalado_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuEscalado.Click Ex = TXTEX.Text Ey = txtEy.Text Ez = TxtEz.Text For fila = 0 To ContPuntos P1(fila).X = P1(fila).X * Ex P1(fila).Y = P1(fila).Y * Ey P1(fila).Z = P1(fila).Z * Ez Next End Sub

Private Sub MnuTraslacion_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuTraslacion.Click Tx = TxtTx.Text Ty = TxtTY.Text tz = TxtTz.Text For fila = 0 To ContPuntos P1(fila).X = P1(fila).X + Tx P1(fila).Y = P1(fila).Y + Ty P1(fila).Z = P1(fila).Z + tz Next End Sub

Private Sub MnGraficar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnGraficar.Click graficarCara(contcaras) End Sub

Private Sub MnuRotacion_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuRotacion.Click Dim x1 As Single, y1 As Single, z1 As Single Dim x2 As Single, y2 As Single, z2 As Single Dim fila As Integer = 0

Page 36: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -780-

' rotacion x GradosX = TXTRX.Text Dx = GradosX * Math.PI / 180 Dim ini As Integer For fila = 0 To ContPuntos ini = P(fila).nro 'error x1 = P1(ini).X y1 = P1(ini).Y z1 = P1(ini).Z x2 = x1 y2 = y1 * Math.Cos(Dx) - z1 * Math.Sin(Dx) z2 = y1 * Math.Sin(Dx) + z1 * Math.Cos(Dx) P1(ini).X = x2 P1(ini).Y = y2 P1(ini).Z = z2 Next ' rotacion y GradosY = TXTRY.Text Dy = GradosY * Math.PI / 180 For fila = 0 To ContPuntos ini = P(fila).nro 'error x1 = P1(ini).X y1 = P1(ini).Y z1 = P1(ini).Z x2 = x1 * Math.Cos(Dy) + z1 * Math.Sin(Dy) y2 = y1 z2 = -x1 * Math.Sin(Dy) + z1 * Math.Cos(Dy) P1(ini).X = x2 P1(ini).Y = y2 P1(ini).Z = z2 Next

' rotacion z GradosZ = TXTRZ.Text Dz = GradosZ * Math.PI / 180 For fila = 0 To ContPuntos ini = P1(fila).nro 'error x1 = P1(ini).X y1 = P1(ini).Y z1 = P1(ini).Z x2 = x1 * Math.Cos(Dz) - y1 * Math.Sin(Dz) y2 = x1 * Math.Sin(Dz) + y1 * Math.Cos(Dz) z2 = z1 P1(ini).X = x2 P1(ini).Y = y2 P1(ini).Z = z2 Next 'mnuBorrar_Click(sender, e) End Sub

Private Sub mnuBorrar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuBorrar.Click

Page 37: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -781-

Grafico.Clear(Color.White) End Sub

Private Sub MnuAlambre_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuAlambre.Click Modo = 0 End Sub

Private Sub MnuSolido_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuSolido.Click Modo = 1 End Sub Private Sub NroDivisiones_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NroDivisiones.Click Ndivisiones = InputBox("ingrese nro diviisones 1..7", 2) End Sub

11.4 DIAGRAMAS DE VORONOI EN MODO GRAFICO

Option Explicit OnImports System.DrawingPublic Class Form1 Dim fila As Integer Dim col As Integer Dim tam As Integer = 10 Dim Color As Color Dim Grafico As Graphics Dim BrochaSolida As SolidBrush Dim nombreArchivo As String Dim nombreColores As String Dim MColores(10, 3) As Integer

Sub MostrarMatrizEnPantalla(ByVal Cx As Integer, ByVal Cy As Integer, ByVal A(,) As Integer, ByVal nfilas As Integer, ByVal ncol As Integer) Dim indice As Integer

Page 38: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -782-

For fila = 0 To nfilas - 1 For col = 0 To ncol - 1 indice = A(fila, col) BrochaSolida.Color = Color.FromArgb(MColores(indice, 0), MColores(indice, 1), MColores(indice, 2)) Grafico.FillRectangle(BrochaSolida, col * tam + Cx, fila * tam + Cy, tam, tam) Next col Next fila End Sub

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load PictureBox1.Width = nc * tam + 1 PictureBox1.Height = nf * tam + 1 Grafico = PictureBox1.CreateGraphics BrochaSOLIDA = New SolidBrush(Color.Red) End Sub

Private Sub BtnPrincipal_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPrincipal.Click Dim MiFuente As New Font("Verdana", 16, FontStyle.Bold) Iniciar() recuperar(X, Y, np) IniciarPantalla(A, nf, nc) nombreArchivo = "e:\DATOS\PANTALLA70x24A.txt" nombreColores = "e:\DATOS\colores3x40.txt" RecuperarArchivo(A, nf, nc, nombreArchivo) RecuperarArchivo(MColores, 10, 3, nombreColores) MostrarMatrizEnPantalla(Cx, Cy, A, nf, nc) For k = 1 To 25 crecer(A, nf, nc, np) MostrarMatrizEnPantalla(Cx, Cy, A, nf, nc) Next BrochaSolida.Color = Color.White For k = 0 To np - 1 Grafico.DrawString(k + 1, MiFuente, BrochaSolida, X(k) * tam, Y(k) * tam) Next End Sub Private Sub btnBorrar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBorrar.Click Grafico.Clear(Color.White) End SubEnd Class

CODIGO DEL MODULO 1

Imports System.IOModule module1 '/*** declaraciones Public Const NFilas As Integer = 24, NCol As Integer = 70 Public Cx As Integer = 10, Cy As Integer = 10

Page 39: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -783-

Public srLector As StreamReader Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long) Public relleno(NCol) As Integer Public A(NFilas, NCol) As Integer Public B(NFilas, NCol) As Integer Public nf As Integer = NFilas, nc As Integer = NCol Public X(40) As Integer Public Y(40) As Integer Public np As Integer = 5, k As Integer Public vecinos As Integer

Public Sub RecuperarArchivo(ByVal A(,) As Integer, ByVal nf As Integer, ByVal nc As Integer, ByVal nombre As String) srLector = New StreamReader(nombre) Dim cadena As String Dim subcadena As String Dim pos As Integer = 0 Dim longitud As String Dim inicio As Integer = 1 Dim cont As Integer = 0 For fila = 0 To nf - 1 cadena = srLector.ReadLine() longitud = Len(cadena) inicio = 1 cont = 0 Do pos = InStr(inicio, cadena, Chr(9)) If pos > 0 Then subcadena = Mid(cadena, inicio, pos - inicio) A(fila, cont) = Val(subcadena) inicio = pos + 1 cont += 1 Else subcadena = Mid(cadena, inicio, longitud - inicio + 1) A(fila, cont) = Val(subcadena) cont += 1 Exit Do End If Loop While (inicio <= longitud) Next Console.WriteLine("Archivo leido satisfactoriamente") srLector.Close() End Sub Sub IniciarPantalla(ByVal A(,) As Integer, ByVal nf As Integer, ByVal nc As Integer) Dim fila As Integer, col As Integer For fila = 0 To nf - 1 For col = 0 To nc - 1 A(fila, col) = 0 Next Next End Sub

Page 40: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -784-

Sub recuperar(ByRef X() As Integer, ByRef Y() As Integer, ByVal ne As Integer) Dim srLector = New StreamReader("e:\DATOS\puntos5.txt") Dim cadena As String Dim subcadena As String Dim pos As Integer = 0 Dim longitud As String For fila = 0 To ne - 1 cadena = srLector.ReadLine() longitud = Len(cadena) pos = InStr(1, cadena, Chr(9)) ' pos tabulador If pos > 0 Then subcadena = Mid(cadena, 1, pos - 1) X(fila) = Val(subcadena) subcadena = Mid(cadena, pos + 1, longitud) Y(fila) = Val(subcadena) End If Next srLector.Close() End Sub Sub imprimir(ByVal X() As Integer, ByVal Y() As Integer, ByVal ne As Integer) Dim fila As Integer For fila = 0 To ne - 1 Console.WriteLine(" {0} {1} {2}", fila, X(fila), Y(fila)) Next End Sub Sub Iniciar() For fila = 0 To NFilas relleno(fila) = fila + 1 Next End Sub

Sub crecer(ByVal A(,) As Integer, ByVal nf As Integer, ByVal nc As Integer, ByVal np As Integer) Dim fila1 As Integer, col1 As Integer Dim k1 As Integer IniciarPantalla(B, nf, nc) For fila1 = 1 To nf - 1 For col1 = 1 To nc - 1 REM si hay espacio crece si no no crece y por lo menos debe haber un vecino For k1 = 0 To np - 1 vecinos = 0 If A(fila1, col1) = relleno(k1) Then vecinos = vecinos + 1 If A(fila1, col1 + 1) = relleno(k1) Then vecinos = vecinos + 1 If A(fila1 + 1, col1) = relleno(k1) Then vecinos = vecinos + 1 If A(fila1, col1 - 1) = relleno(k1) Then vecinos = vecinos + 1 If A(fila1 - 1, col1) = relleno(k1) Then vecinos = vecinos + 1 If vecinos > 0 And A(fila1, col1) = 0 Then B(fila1, col1) = relleno(k1) 'relleno(k1) Exit For Else B(fila1, col1) = A(fila1, col1) End If

Page 41: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -785-

Next k1 Next col1 Next fila1 IniciarPantalla(A, nf, nc) TransferirMatriz(B, A, nf, nc) End Sub Sub TransferirMatriz(ByVal A(,) As Integer, ByVal B(,) As Integer, ByVal nf As Integer, ByVal nc As Integer) For fila = 0 To nf - 1 For col = 0 To nc - 1 B(fila, col) = A(fila, col) Next Next End SubEnd Module

11.5 TRABAJO DE APLICACIÓN DE REDES DE OPTIMIZACION

Determinación de Trayectorias de transporte

Una empresa de transporte desea hacer el recorrido de mínima distancia entre la ubicación 1 y la 39 de la figura mostrada abajo que considera las alternativas de desplazamiento para las Urbanizaciones de Dolores y Amauta, donde los arcos muestran las distancias recorridas en metros.

Se tiene los siguientes puntos. -Se pide

Graficar arbol de expansion minima Graficar el recorrido minimo de un punto a otro Mostrar el flujo maximo de un punto a otro Mostrar el recorrido minimo que realiza un camion de un punto a otro Otros aportes

PUNTO X y R1 R2 R3

0 55 120 1 12 -11 130 100 0 11 22 190 70 1 3 103 320 40 2 4 64 360 30 3 5 -15 400 110 4 6 326 345 125 3 7 317 300 143 6 30 88 255 170 9 7 -19 260 183 8 10 -1

10 220 170 2 11 1411 175 188 1 10 1212 70 201 0 11 1313 82 266 12 16 1414 247 234 15 10 1315 269 299 14 16 3916 93 319 13 17 15

Page 42: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -786-

17 100 371 16 18 2118 217 371 17 20 1919 260 360 39 18 2420 220 410 18 21 2321 110 425 17 22 2022 110 480 21 23 -123 240 460 22 20 2424 310 450 23 25 1925 340 450 24 26 3726 340 400 27 25 3627 330 360 26 28 -128 350 320 39 27 2929 370 310 28 34 3030 350 260 31 7 2931 420 250 30 32 -132 450 230 33 5 -133 470 290 32 38 -134 410 300 29 33 -135 420 350 36 34 2736 450 380 37 35 -137 460 420 25 38 3638 500 410 37 33 -139 320 320 19 15 28

Page 43: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -787-

Page 44: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -788-

CODIGO DEL FORMULARIO

Option Explicit OnImports System.DrawingPublic Class Form1 Dim Grafico As Graphics Dim BrochaSólida As SolidBrush Dim pen As Pen Dim pen1 As Pen Dim penArbol As Pen Sub ObtenerRuta(ByVal i As Integer, ByVal j As Integer) Dim Sij As Integer Sij = S(i, j) If Sij = j Then Ruta(ner) = i ListBox1.Items.Add(" i " & i & " J " & j & " SIJ " & Sij) ner = ner + 1 Else ObtenerRuta(i, Sij) ObtenerRuta(Sij, j) End If End Sub Sub Graficar(ByVal X() As Single, ByVal Y() As Single, ByRef R(,) As Integer, _ ByVal nf As Integer, ByVal nc As Integer, ByVal ex As Single, ByVal ey As Single) Dim fila As Integer, col As Integer Dim x1 As Single, y1 As Single, x2 As Single, y2 As Single For fila = 0 To nf - 1 For col = 0 To nc - 1 If R(fila, col) = 1 Then

Page 45: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -789-

x1 = X(fila) * ex y1 = Y(fila) * ey x2 = X(col) * ex y2 = Y(col) * ey Grafico.DrawLine(pen, x1, y1, x2, y2) End If Next Next End Sub

Private Sub MnuIniciar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuIniciar.Click ex = Val(TxtEx.Text) ey = Val(TxtEy.Text) ListBox1.Items.Clear() ner = 0 iniciar() End Sub Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load pen = New Pen(Color.FromArgb(255, 0, 0), 5) Grafico = PictureBox1.CreateGraphics pen = New Pen(Color.FromArgb(255, 0, 0), 2) pen1 = New Pen(Color.FromArgb(0, 0, 255), 3) penArbol = New Pen(Color.FromArgb(0, 255, 0), 5) End Sub Private Sub MnuGraficarRuta_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuGraficarRuta.Click Dim fila As Integer Dim p1 As Integer, p2 As Integer For fila = 0 To ner - 2 p1 = Ruta(fila) p2 = Ruta(fila + 1) Grafico.DrawLine(pen1, X(p1) * ex, Y(p1) * ey, X(p2) * ex, Y(p2) * ey) Next End Sub

Private Sub MnuGraficarPuntos_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuGraficarPuntos.Click Dim k As Integer LeerArchivo(X, Y, np) Dim MiFuente As New Font("Verdana", 10, FontStyle.Bold) For k = 0 To np - 1 Grafico.DrawString(k, MiFuente, Brushes.Blue, X(k) * ex, Y(k) * ey) Grafico.DrawEllipse(Pens.Green, X(k) * ex, Y(k) * ey, ex, ey) Next End Sub

Private Sub MnuGraficarLineas_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuGraficarLineas.Click ex = Val(TxtEx.Text) ey = Val(TxtEy.Text)

Page 46: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -790-

Graficar(X, Y, Relaciones, np, np, ex, ey) End Sub Private Sub MnuBorrar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuBorrar.Click Grafico.Clear(Color.White) End Sub Private Sub MnuRecuperarPuntos_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuRecuperarPuntos.Click LeerArchivo(X, Y, np) End Sub Private Sub MnuRecuperarRelaciones_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuRecuperarRelaciones.Click RecuperarPuntosRelaciones(PuntosRelaciones, np, np - 1) End Sub Private Sub MnuProcesar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuProcesar.Click FormarRelaciones(PuntosRelaciones, Relaciones, np, np) ObtenerDistancias(X, Y, np, D, Relaciones) End Sub Private Sub MnuObtenerRecorridos_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuObtenerRecorridos.Click ObtenerRecorridos(S, np) End Sub Private Sub MnRecuperarDistancias_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnRecuperarDistancias.Click RecuperarDistancias(D, np, np) End Sub

Private Sub MnunGrabarDistancias_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnunGrabarDistancias.Click GrabarMatriz(D, np, np) End Sub Private Sub MnuGrabarRecorrido_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuGrabarRecorrido.Click GrabarMatrizRecorrido(S, np, np) End Sub Private Sub MnuFloyd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuFloyd.Click floyd(D, S, np) End Sub Private Sub MnuObteneRuta_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuObteneRuta.Click origen = Val(txtOrigen.Text) destino = Val(Txtdestino.Text) ner = 0 ObtenerRuta(origen, destino) Ruta(ner) = destino ner = ner + 1 End Sub Private Sub MnuProcesoGeneral_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuProcesoGeneral.Click MnuIniciar_Click(sender, e)

Page 47: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -791-

MnuRecuperarPuntos_Click(sender, e) MnuRecuperarRelaciones_Click(sender, e) MnuProcesar_Click(sender, e) MnuObtenerRecorridos_Click(sender, e) MnuGraficarPuntos_Click(sender, e) MnuGraficarLineas_Click(sender, e) MnuFloyd_Click(sender, e) MnunGrabarDistancias_Click(sender, e) MnuGrabarRecorrido_Click(sender, e) MnuObteneRuta_Click(sender, e) MnuGraficarRuta_Click(sender, e) End Sub

Private Sub MnuGraficarArbol_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuGraficarArbol.Click Dim x1 As Single, y1 As Single, x2 As Single, y2 As Single For fila = 0 To np - 1 x1 = X(CFila(fila)) * ex y1 = Y(CFila(fila)) * ey x2 = X(CCol(fila)) * ex y2 = Y(CCol(fila)) * ey Grafico.DrawLine(penArbol, x1, y1, x2, y2) Next End Sub Private Sub MnuIniciarArbol_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuIniciarArbol.Click ex = Val(TxtEx.Text) ey = Val(TxtEy.Text) InicioArbol() End Sub Private Sub MnuBorrararbol_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuBorrararbol.Click Grafico.Clear(Color.FloralWhite) End Sub Private Sub GraficarPuntosArbol_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuGraficarPuntosArbol.Click MnuGraficarPuntos_Click(sender, e) End Sub Private Sub MnuProcesoArbol_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuProcesoArbol.Click MnuIniciarArbol_Click(sender, e) MnuGraficarArbol_Click(sender, e) GraficarPuntosArbol_Click(sender, e) End Sub

Private Sub RecuperarGraficoToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuRecuperarGrafico.Click Dim nombre As String OpenFileDialog1.ShowDialog() nombre = OpenFileDialog1.FileName Me.Text = nombre PictureBox1.Load(nombre)

Page 48: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -792-

End Sub Private Sub MnuSalir_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuSalir.Click Me.Close() End SubEnd Class

CODIGO DEL MODULO

Module Module1 Sub InicioArbol() Dim contador As Integer = 0 Dim k As Integer Dim k1 As Integer Dim filamenor As Integer Dim menor As Single = 1000 LeerArchivo(X, Y, np) C(0) = 0 For k = 0 To nc1 - 1 C1(k) = k + 1 Next While nc1 > 0 menor = 1000 colMenor = 0 filamenor = 0 For k = 0 To nc - 1 p1 = C(k) For k1 = 0 To nc1 - 1 p2 = C1(k1) d1 = distancia(X(p1), Y(p1), X(p2), Y(p2)) If (d1 < menor) And d1 > 0 Then menor = d1 filamenor = C(k) colMenor = k1 End If Next Next CFila(contador) = filamenor CCol(contador) = C1(colMenor) contador = contador + 1 C(nc) = C1(colMenor) nc = nc + 1 nc1 = nc1 - 1 For k1 = colMenor To nc1 - 1 C1(k1) = C1(k1 + 1) Next End While ne = contador End Sub Function distanciaTotalArbol(ByVal CFila() As Integer, ByVal CCol() As Integer, ByVal np As Integer) Dim fila As Integer

Page 49: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -793-

Dim d1 As Single Dim dt As Single = 0 For fila = 0 To np - 1 d1 = distancia(X(CFila(fila)), Y(CFila(fila)), X(CCol(fila)), Y(CCol(fila))) dt = dt + d1 Next Return dt End FunctionEnd Module

MODULO 2

Option Explicit OnImports System.IOModule Module2 Public ne As Integer Public d1 As Single Public C(Npuntos) As Integer Public C1(Npuntos) As Integer Public CCol(Npuntos) As Integer Public CFila(Npuntos) As Integer Public colMenor As Integer Public Const Npuntos As Integer = 5 Public cont As Integer = 0 Public Cx As Integer = 1 Public Cy As Integer = 1 Public D(Npuntos, Npuntos) As Single Public destino As Integer = 4 Public ex As Single = 6 Public ey As Single = 2 Public nc As Integer = 1 Public nc1 As Integer = Npuntos - 1 Public ner As Integer = 0 Public np As Integer = Npuntos Public origen As Integer = 0 Public p1 As Integer Public p2 As Integer Public PuntosRelaciones(Npuntos, Npuntos) As Integer Public Relaciones(Npuntos, Npuntos) As Integer Public Ruta(Npuntos) As Integer Public S(Npuntos, Npuntos) As Integer Public srLector As StreamReader Public X(Npuntos) As Single Public Y(Npuntos) As Single Sub iniciar() IniciarPantalla(PuntosRelaciones, np, np) IniciarPantalla(Relaciones, np, np) IniciarPantalla(S, np, np) End Sub Sub LeerArchivo(ByVal X() As Single, ByVal Y() As Single, ByVal nf As Integer) srLector = New StreamReader("e:\DATOS\puntos2x5.txt") Dim cadena As String

Page 50: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -794-

Dim pos As Integer = 0 For fila = 0 To nf - 1 cadena = srLector.ReadLine() pos = InStr(1, cadena, Chr(9)) If pos > 0 Then X(fila) = Val(Mid(cadena, 1, pos - 1)) Y(fila) = Val(Mid(cadena, pos + 1, Len(cadena))) End If REM srLector.Close() Next End Sub

Public Sub RecuperarPuntosRelaciones(ByVal A(,) As Integer, ByVal nf As Integer, ByVal nc As Integer) srLector = New StreamReader("e:\DATOS\Relaciones4X5.txt") Dim cadena As String Dim subcadena As String Dim pos As Integer = 0 Dim longitud As String Dim inicio As Integer = 1 Dim cont As Integer = 0 For fila = 0 To nf - 1 cadena = srLector.ReadLine() longitud = Len(cadena) inicio = 1 cont = 0 Do pos = InStr(inicio, cadena, Chr(9)) If pos > 0 Then subcadena = Mid(cadena, inicio, pos - inicio) A(fila, cont) = Val(subcadena) inicio = pos + 1 cont += 1 Else subcadena = Mid(cadena, inicio, longitud - inicio + 1) A(fila, cont) = Val(subcadena) cont += 1 Exit Do End If Loop While (inicio <= longitud) Next srLector.Close() End Sub Public Sub RecuperarDistancias(ByVal A(,) As Single, ByVal nf As Integer, ByVal nc As Integer) srLector = New StreamReader("e:\DATOS\Dist8x8.txt") Dim cadena As String Dim subcadena As String Dim pos As Integer = 0 Dim longitud As String Dim inicio As Integer = 1 Dim cont As Integer = 0

Page 51: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -795-

For fila = 0 To nf - 1 cadena = srLector.ReadLine() longitud = Len(cadena) inicio = 1 cont = 0 Do pos = InStr(inicio, cadena, Chr(9)) If pos > 0 Then subcadena = Mid(cadena, inicio, pos - inicio) A(fila, cont) = Val(subcadena) inicio = pos + 1 cont += 1 Else subcadena = Mid(cadena, inicio, longitud - inicio + 1) A(fila, cont) = Val(subcadena) cont += 1 Exit Do End If Loop While (inicio <= longitud) Next srLector.Close() End Sub

Sub FormarRelaciones(ByVal A(,) As Integer, ByRef R(,) As Integer, ByVal nf As Integer, ByVal nc As Integer) Dim fila As Integer, col As Integer For fila = 0 To nf - 1 For col = 0 To nc - 1 If A(fila, col) >= 0 Then R(fila, A(fila, col)) = 1 End If Next Next End Sub Sub IniciarPantalla(ByVal A(,) As Integer, ByVal nf As Integer, ByVal nc As Integer) Dim fila As Integer, col As Integer For fila = 0 To nf - 1 For col = 0 To nc - 1 A(fila, col) = -1 Next Next End Sub Function distancia(ByVal x1 As Single, ByVal y1 As Single, ByVal x2 As Single, ByVal y2 As Single) As Single distancia = Math.Sqrt(Math.Pow(x2 - x1, 2) + Math.Pow(y2 - y1, 2)) End Function

Sub ObtenerDistancias(ByVal X() As Single, ByVal Y() As Single, ByVal np As Integer, ByVal D(,) As Single, ByVal Relaciones(,) As Integer) Dim fila As Integer, col As Integer Dim d1 As Single For fila = 0 To np - 1

Page 52: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -796-

For col = 0 To np - 1 d1 = distancia(X(fila), Y(fila), X(col), Y(col)) If Relaciones(fila, col) > 0 Then D(fila, col) = d1 Else If (fila <> col) Then D(fila, col) = 999 Else D(fila, col) = 0 End If End If Next Next End Sub Sub ObtenerRecorridos(ByRef S(,) As Integer, ByVal np As Integer) Dim fila As Integer, col As Integer For fila = 0 To np - 1 For col = 0 To np - 1 S(fila, col) = col Next Next End Sub Sub floyd(ByRef D(,) As Single, ByRef S(,) As Integer, ByVal np As Integer) Dim i As Integer, j As Integer, k As Integer = 0 For k = 0 To np - 1 For i = 0 To np - 1 For j = 0 To np - 1 If D(i, k) + D(k, j) < D(i, j) Then If (i <> j) And (j <> k) And (i <> k) Then D(i, j) = D(i, k) + D(k, j) S(i, j) = k End If End If Next Next Next End Sub

Sub GrabarMatriz(ByVal A(,) As Single, ByVal nf As Integer, ByVal nc As Integer) Dim swEscritor = New StreamWriter("e:\DATOS\D5x5.txt") Dim fila As Integer, col As Integer For fila = 0 To nf - 1 For col = 0 To nc - 1 swEscritor.Write("{0}{1} ", A(fila, col), Chr(9)) Next swEscritor.WriteLine() Next swEscritor.Close() End Sub Sub GrabarMatrizRecorrido(ByVal A(,) As Integer, ByVal nf As Integer, ByVal nc As Integer) Dim swEscritor = New StreamWriter("e:\DATOS\S5x5.txt")

Page 53: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -797-

Dim fila As Integer, col As Integer For fila = 0 To nf - 1 For col = 0 To nc - 1 swEscritor.Write("{0}{1} ", A(fila, col), Chr(9)) Next swEscritor.WriteLine() Next swEscritor.Close() End Sub

Function distanciaRuta(ByVal ruta() As Integer, ByVal X() As Single, ByVal Y() As Single, ByVal ner As Integer) As Single Dim fila As Integer Dim p1 As Integer, p2 As Integer Dim suma As Single, d As Single For fila = 0 To ner - 2 p1 = ruta(fila) p2 = ruta(fila + 1) d = distancia(X(p1), Y(p1), X(p2), Y(p2)) suma = suma + d Next Return suma End FunctionEnd Module

11.6 SIMULACION DE POLITICAS DE INVENTARIOS DE CONTROL DE INVENTARIOS

x P(x) acum L 21 5,00 5 Q 102 20,00 25 C1 0,13 40,00 65 C3 54 25,00 90 Z 105 10,00 100 z 4

SUMA 100

Page 54: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -798-

CODIGO DEL FORMULARIO

Imports System.DrawingPublic Class Form1 Dim Grafico As Graphics Dim ColorFondo As Color = Color.FromArgb(255, 255, 255) Dim pen As Pen Dim pen2 As Pen Dim pen3 As Pen Dim valor As Integer = 10 Dim ancho = 600, alto = 400 Dim BrochaSolida As SolidBrush Sub mostrar(ByVal vector() As Single, ByVal n As Integer) Dim i As Integer For i = 0 To n - 1 ListBox1.Items.Add(i & " " & vector(i)) Next End Sub Sub MostrarMatriz(ByRef A(,) As Single, ByVal nf As Integer, ByVal nc As Integer) Dim fila As Integer, col As Integer For col = 0 To nc - 1 DataGridView1.Columns(col).Width = 50 Next DataGridView1.ColumnCount = 10 For fila = 0 To nf - 1 For col = 0 To nc - 1 DataGridView1.Rows(fila).Cells(col).Value = A(fila, col) Next Console.WriteLine() Next End Sub

Private Sub BtnIniciar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnIniciar.Click ListBox1.Items.Clear() Iniciar() nfilas = Val(txtNper.Text) ex = Val(txtEx.Text) ey = Val(txtEy.Text) Z1 = Val(txtZ.Text) z2 = Val(txtz2.Text) demora = Val(txtL.Text) C1 = Val(txtC1.Text) C3 = Val(txtC3.Text) rellenar(vector, nro, p, nprob, nfilas) mostrar(vector, nfilas) RellenarMatriz(A, nro, vector, nfilas) DataGridView1.ColumnCount = 10 DataGridView1.RowCount = nfilas DataGridView1.Columns(0).HeaderText = "Per" DataGridView1.Columns(1).HeaderText = "I1"

Page 55: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -799-

DataGridView1.Columns(2).HeaderText = "R" DataGridView1.Columns(3).HeaderText = "I2" DataGridView1.Columns(4).HeaderText = "Ped" DataGridView1.Columns(5).HeaderText = "Llega" DataGridView1.Columns(6).HeaderText = "C1" DataGridView1.Columns(7).HeaderText = "C3" DataGridView1.Columns(8).HeaderText = "Ct" DataGridView1.Columns(9).HeaderText = "ctAc" MostrarMatriz(A, nfilas, ncol) GrabarMatriz(A, nfilas, ncol) Console.ReadLine() End Sub Private Sub BtnGraficar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnGraficar.Click Dim MiFuente = New Font("arial", 11, FontStyle.Bold) Dim x1 As Single, y1 As Single, x2 As Single, y2 As Single For fila = 0 To nfilas - 1 x1 = A(fila, 0) y1 = A(fila, 1) Grafico.DrawString(fila, MiFuente, BrochaSolida, Cx + x1 * ex, Cy) Next Grafico.DrawLine(pen, 0, Cy, ancho, Cy) Grafico.DrawLine(pen, cx, 0, cx, alto) For fila = 0 To nfilas - 1 x1 = A(fila, 0) y1 = A(fila, 1) Grafico.FillRectangle(Brushes.Blue, Cx + x1 * ex, Cy + y1 * ey, ex - ex / 10, A(fila, 1) * ey * -1) Next For fila = 1 To nfilas - 1 ' graficando el INVENTARIOl x1 = A(fila - 1, 0) y1 = A(fila - 1, 1) x2 = A(fila, 0) y2 = A(fila, 1) Grafico.DrawLine(pen2, Cx + x1 * ex, Cy + y1 * ey, Cx + x2 * ex, Cy + y2 * ey) ' graficando el costo total x1 = A(fila - 1, 0) y1 = A(fila - 1, 8) x2 = A(fila, 0) y2 = A(fila, 8) Grafico.DrawLine(pen3, Cx + x1 * ex, Cy + y1 * ey, Cx + x2 * ex, Cy + y2 * ey) Next txtCi.Text = CAcum End Sub Private Sub BtnBorrar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnBorrar.Click Grafico.Clear(Color.White) End Sub Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Grafico = PictureBox1.CreateGraphics

Page 56: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -800-

pen2 = New Pen(Color.Red, 1) pen3 = New Pen(Color.Green, 2) pen = New Pen(Color.FromArgb(255, 0, 0), 1) BrochaSolida = New SolidBrush(Color.Red) End SubEnd Class

CODIGO DEL MODULO 1

Imports System.IOModule Module1 Public Const maxfilas As Integer = 365 Public Const nprob As Integer = 10 Public ncol As Integer = 10 Public nfilas As Integer = maxfilas Public vector(maxfilas) As Single Public nro(nprob) As Single Public p(nprob) As Single Public A(nfilas, ncol) As Single Public C1 As Single = 0.1 Public C3 As Single = 5 Public Z1 As Single = 10 Public z2 As Single = 4 Public demora As Single = 2 'L Public hizopedido As Integer = 0 Public Cx As Single = 100 Public Cy As Single = 200 Public ex As Single = 10 Public ey As Single = -10 Public CAcum As Single = 0 Sub RellenarMatriz(ByRef A(,) As Single, ByVal nro() As Single, ByVal vector() As Single, ByVal np As Integer) Dim fila As Integer Dim I1 As Single = 8, I2 As Single, r As Integer Dim t As Single = 0 Dim pedido As Single Dim cmantenimiento As Single = 0, caprovisionamiento As Single = 0 Dim Ctotal As Single = 0 fila = 0 ' primero inicializamos A(fila, 0) = nro(fila) A(fila, 1) = Z1 A(fila, 2) = vector(fila) I2 = A(fila, 1) - vector(0) A(fila, 3) = I2 A(fila, 4) = pedido cmantenimiento = C1 * A(fila, 1) A(fila, 6) = cmantenimiento A(fila, 7) = caprovisionamiento Ctotal = cmantenimiento + caprovisionamiento A(fila, 8) = Ctotal CAcum = Ctotal

Page 57: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -801-

A(fila, 9) = Ctotal A(fila, 0) = fila For fila = 1 To nfilas - 1 r = vector(fila) A(fila, 0) = fila I1 = A(fila - 1, 3) A(fila, 5) = 0 If t >= demora Then ' llega el pedido I1 = I1 + pedido A(fila - 1, 5) = pedido t = 0 pedido = 0 hizopedido = 0 Else t = t + 1 End If A(fila, 1) = I1 A(fila, 2) = vector(fila) I2 = I1 - r A(fila, 3) = I2 A(fila, 4) = 0 If (I2 < z2) Then If hizopedido = 0 Then ' solo aumenta cuando no se hizo pedido pedido = Z1 - I2 A(fila, 4) = pedido t = 0 hizopedido = 1 End If End If ' calculo de costos A(fila, 6) = 0 A(fila, 7) = 0 If A(fila, 1) > 0 Then cmantenimiento = C1 * A(fila, 1) A(fila, 6) = cmantenimiento End If If A(fila, 4) > 0 Then caprovisionamiento = C3 Else caprovisionamiento = 0 End If A(fila, 7) = caprovisionamiento Ctotal = cmantenimiento + caprovisionamiento A(fila, 8) = Ctotal CAcum = CAcum + Ctotal A(fila, 9) = CAcum Next End Sub Sub GrabarMatriz(ByVal A(,) As Single, ByVal nf As Integer, ByVal nc As Integer) Dim swEscritor = New StreamWriter("E:\DATOS\Invent5x30.txt") Dim fila As Integer, col As Integer For fila = 0 To nf - 1

Page 58: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -802-

For col = 0 To nc - 1 swEscritor.Write("{0}{1} ", A(fila, col), Chr(9)) Next swEscritor.WriteLine() Next swEscritor.Close() End Sub Function generar(ByVal nro() As Single, ByVal p() As Single, ByVal n As Integer) As Integer Dim r As Integer, ng As Integer, i As Integer r = Int(Rnd() * 100) For i = 0 To n - 1 If (p(i) > r) Then ng = nro(i) Exit For End If Next Return ng End Function Sub rellenar(ByVal vector() As Single, ByVal nro() As Single, ByVal p() As Single, ByVal nprob As Integer, ByVal nper As Integer) Dim i As Integer Randomize() For i = 0 To nper - 1 vector(i) = generar(nro, p, nprob) Next End Sub Sub Iniciar() nro(0) = 1 : nro(1) = 2 : nro(2) = 3 : nro(3) = 4 : nro(4) = 5 p(0) = 5 p(1) = 25 p(2) = 65 p(3) = 90 : p(4) = 100 End SubEnd Module

11.7 TRIANGULACION DE DELAUNAY

Page 59: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -803-

CODIGO DEL FORMULARIO 1

Option Explicit OnImports System.DrawingPublic Class Form1 Dim MiFuente As New Font("Verdana", 12, FontStyle.Bold) Dim x1 As Integer Dim y1 As Integer Dim x2 As Integer Dim y2 As Integer Dim p1 As Integer Dim p2 As Integer Dim nsr As Integer = 0 Dim fila As Integer Sub imprimirVector(ByVal X() As Integer, ByVal ne As Integer) Dim fila As Integer For fila = 0 To ne - 1 ListBox1.Items.Add(" X " & X(fila)) Next End Sub

Sub imprimir(ByVal X() As Integer, ByVal Y() As Integer, ByVal ne As Integer) ListBox1.Items.Clear() Dim fila As Integer For fila = 0 To ne - 1 ListBox1.Items.Add(" X " & X(fila) & " Y " & Y(fila)) Next End Sub Sub graficarTriangulos()

Page 60: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -804-

For fila = 0 To Np - 1 p1 = MRel(fila, 0) x1 = X(p1) y1 = Y(p1) For col = 1 To Np - 1 p2 = MRel(fila, col) If MRel(fila, col) >= 0 Then x2 = X(p2) y2 = Y(p2) If x1 = x2 And y1 = y2 Then Else Grafico.DrawLine(pen, x1 * tam, y1 * tam, x2 * tam, y2 * tam) End If End If Next Next BrochaSolida.Color = Color.White For k = 0 To Np - 1 Grafico.DrawString(k + 1, MiFuente, BrochaSolida, X(k) * tam, Y(k) * tam) Next End Sub Sub MostrarMatriz(ByVal Cx As Integer, ByVal Cy As Integer, ByVal A(,) As Integer, ByVal nfilas As Integer, ByVal ncol As Integer) Dim indice As Integer For fila = 0 To nfilas - 1 For col = 0 To ncol - 1 indice = A(fila, col) BrochaSolida.Color = Color.FromArgb(MColores(indice, 0), MColores(indice, 1), MColores(indice, 2)) Grafico.FillRectangle(BrochaSolida, col * tam + Cx, fila * tam + Cy, tam, tam) Next col Next fila End Sub Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load pen = New Pen(Color.Yellow, 2) Grafico = PictureBox1.CreateGraphics BrochaSolida = New SolidBrush(Color.Red) End Sub Private Sub BtnPrincipal_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPrincipal.Click For fila = 0 To np - 1 relleno(fila) = fila + 1 Next recuperarPuntos(X, Y, Np) nombreColores = "E:\SI2014B\DATOSTXT\colores3x50.txt" RecuperarArchivo(MColores, 50, 3, nombreColores) IniciarMatriz(MRel, Np, Np, -1) IniciarMatriz(Matriz, nf, nc, 0) MostrarMatriz(cx, cy, matriz, nf, nc) imprimir(X, Y, Np) REM al crecer obtien cuales son sus vecinos

Page 61: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -805-

For r = 0 To 100 crecerCirculo(Matriz, X, Y, nf, nc, relleno, r, Np) Next MostrarMatriz(Cx, Cy, Matriz, nf, nc) For fila = 0 To nseres - 1 contavecinos(relleno(fila), vecinos, nvecinos) restar(vecinos, nvecinos) AsignarMatriz(MRel, vecinos, nvecinos, fila) ListBox1.Items.Add("ser " & relleno(fila)) imprimirVector(vecinos, nvecinos) Next graficarTriangulos() End Sub Private Sub btnBorrar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnBorrar.Click Grafico.Clear(Color.Black) End Sub

Private Sub btnMostrar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnMostrar.Click MostrarMatriz(Cx, Cy, Matriz, nf, nc) End Sub Private Sub btnCargar_Click(sender As Object, e As EventArgs) Handles btnCargar.Click End Sub Private Sub BtnTriangulos_Click(sender As Object, e As EventArgs) Handles BtnTriangulos.Click graficarTriangulos() End SubEnd Class

CODIGO DEL MODULO 1

Imports System.IOModule module1 Public tam As Integer = 1 Public Cx As Integer = 10, Cy As Integer = 10 Public npuntos As Integer Public Matriz(NFilas, NCol) As Integer Public Const NFilas As Integer = 500, NCol As Integer = 700, maximo = 100 Public Np As Integer = 40 Public relleno(NCol) As Integer Public X(Np) As Integer Public Y(Np) As Integer Public nf As Integer = NFilas, nc As Integer = NCol Public MRel(Np, Np) As Integer Public srLector As StreamReader Public nseres As Integer = 40 Public vecinos(maximo) As Integer Public nvecinos As Integer Public pen As Pen Public Color As Color

Page 62: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -806-

Public Grafico As Graphics Public BrochaSolida As SolidBrush Public nombreColores As String Public MColores(50, 3) As Integer Public Ex As Single = tam Public ey As Single = -tam

Sub contavecinos(ByRef ser As Integer, ByRef Vecinos() As Integer, ByRef nvecinos As Integer) Dim fila As Integer, col As Integer Dim cont = 0 Dim valor As Integer = 0 Vecinos(0) = ser cont = 1 For fila = 1 To nf - 2 For col = 1 To nc - 2 If (Matriz(fila, col) = ser) Then valor = 0 For k = 0 To cont - 1 If Matriz(fila, col + 1) = Vecinos(k) Then valor = 1 Exit For End If Next If valor = 0 Then Vecinos(cont) = Matriz(fila, col + 1) cont = cont + 1 End If valor = 0 For k = 0 To cont - 1 If Matriz(fila - 1, col) = Vecinos(k) Then valor = 1 Exit For End If Next If valor = 0 Then Vecinos(cont) = Matriz(fila - 1, col) cont = cont + 1 End If valor = 0 For k = 0 To cont - 1 If Matriz(fila, col - 1) = Vecinos(k) Then valor = 1 Exit For End If Next If valor = 0 Then Vecinos(cont) = Matriz(fila, col - 1) cont = cont + 1 End If valor = 0 For k = 0 To cont - 1

Page 63: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -807-

If Matriz(fila + 1, col) = Vecinos(k) Then valor = 1 Exit For End If Next If valor = 0 Then Vecinos(cont) = Matriz(fila + 1, col) cont = cont + 1 End If End If Next Next nvecinos = cont End Sub

Public Sub RecuperarArchivo(ByVal A(,) As Integer, ByVal nf As Integer, ByVal nc As Integer, ByVal nombre As String) srLector = New StreamReader(nombre) Dim cadena As String Dim subcadena As String Dim pos As Integer = 0 Dim longitud As String Dim inicio As Integer = 1 Dim cont As Integer = 0 For fila = 0 To nf - 1 cadena = srLector.ReadLine() longitud = Len(cadena) inicio = 1 cont = 0 Do pos = InStr(inicio, cadena, Chr(9)) If pos > 0 Then subcadena = Mid(cadena, inicio, pos - inicio) A(fila, cont) = Val(subcadena) inicio = pos + 1 cont += 1 Else subcadena = Mid(cadena, inicio, longitud - inicio + 1) A(fila, cont) = Val(subcadena) cont += 1 Exit Do End If Loop While (inicio <= longitud) Next Console.WriteLine("Archivo leido satisfactoriamente") srLector.Close() End Sub Sub crecerCirculo(ByVal A(,) As Integer, ByVal X() As Integer, ByVal Y() As Integer, ByVal nf As Integer, _ ByVal nc As Integer, ByVal relleno() As Integer, ByVal r As Single, ByVal np As Integer) Dim x1 As Integer, y1 As Integer, k As Integer

Page 64: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -808-

For k = 0 To np - 1 For y1 = Y(k) - r To Y(k) + r For x1 = X(k) - r To X(k) + r If (Math.Pow(x1 - X(k), 2) + Math.Pow(y1 - Y(k), 2) <= r * r) And (x1 > 0) And (x1 < NCol) And (y1 > 0) And (y1 < NFilas) Then If (A(y1, x1) = 0) Then A(y1, x1) = relleno(k) End If End If Next Next Next End Sub Sub IniciarMatriz(ByVal A(,) As Integer, ByVal nf As Integer, ByVal nc As Integer, ByVal nro As Integer) Dim fila As Integer, col As Integer For fila = 0 To nf - 1 For col = 0 To nc - 1 A(fila, col) = nro Next Next End Sub Sub recuperarPuntos(ByRef X() As Integer, ByRef Y() As Integer, ByVal ne As Integer) Dim srLector = New StreamReader("E:\SI2014B\DATOSTXT\puntos2x40.txt") Dim cadena As String Dim subcadena As String Dim pos As Integer = 0 Dim longitud As String For fila = 0 To ne - 1 cadena = srLector.ReadLine() longitud = Len(cadena) pos = InStr(1, cadena, Chr(9)) ' pos tabulador If pos > 0 Then subcadena = Mid(cadena, 1, pos - 1) X(fila) = Val(subcadena) subcadena = Mid(cadena, pos + 1, longitud) Y(fila) = Val(subcadena) End If Next srLector.Close() End Sub Sub AsignarMatriz(ByRef M(,) As Integer, ByVal V() As Integer, ByVal ne As Integer, ByVal nfila As Integer) Dim col As Integer For col = 0 To ne - 1 M(nfila, col) = V(col) Next End Sub Sub Iniciarvector(ByVal A() As Integer, ByVal ne As Integer) Dim fila As Integer For fila = 0 To nf - 1

Page 65: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -809-

A(fila) = -1 Next End Sub Sub restar(ByRef a() As Integer, ByVal ne As Integer) Dim fila As Integer For fila = 0 To ne - 1 a(fila) = a(fila) - 1 Next End SubEnd Module

1.8 PROGRAMA EDUCATIVO EL PUREK(para aprender operaciones matemáticas)

CODIGO DEL FORMULARIO

Option Explicit OnImports System.DrawingPublic Class Form1 Dim nro1 As Integer Dim nro2 As Integer Dim resultado As Integer Dim pen1 As Pen Dim pen2 As Pen Dim Color As Color Dim Grafico As Graphics Dim BrochaSolida As SolidBrush Dim Cx As Integer = 300, Cy As Integer = 300 Dim MiFuente As New Font("Verdana", 12, FontStyle.Bold) Dim ex As Integer = 1, ey As Integer = -1 Dim ancho As Integer = 600, alto As Integer = 600 Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long) Sub MostrarMatriz(ByVal Cx As Integer, ByVal Cy As Integer, ByVal A(,) As Integer, ByVal nfilas As Integer, ByVal ncol As Integer) Dim indice As Integer Dim factor As Single = 0.1 Dim tam1 As Integer = tam * (1 - factor)

Page 66: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -810-

For fila = 0 To nfilas - 1 For col = 0 To ncol - 1 indice = A(fila, col) BrochaSolida.Color = Color.FromArgb(MColores(indice, 0), MColores(indice, 1), MColores(indice, 2)) Grafico.FillRectangle(BrochaSolida, Cx + col * tam + tam * factor, Cy + fila * tam * ey - tam1 - factor, tam1, tam1) Next col Next fila End Sub Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load pen1 = New Pen(Color.Red, 2) pen2 = New Pen(Color.Green, 1) Grafico = PictureBox1.CreateGraphics BrochaSolida = New SolidBrush(Color.Blue) End Sub Private Sub BtnIniciar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnIniciar.Click IniciarMatriz(Matriz, nf, nc, 0) MostrarMatriz(Cx, Cy, Matriz, nf, nc) End Sub Private Sub btnTablero_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnTablero.Click BrochaSolida.Color = Color.Blue Grafico.DrawLine(pen1, 0, Cy, ancho, Cy) Grafico.DrawLine(pen1, Cx, 0, Cx, alto) For k = -NCol To NCol Grafico.DrawString(k, MiFuente, BrochaSolida, Cx + k * tam, Cy) Grafico.DrawLine(pen2, Cx + k * tam, 0, Cx + k * tam, alto) Next For k = -NFilas To NFilas Grafico.DrawString(k, MiFuente, BrochaSolida, Cx, Cy + k * tam * ey) Grafico.DrawLine(pen2, 0, Cy + k * tam, ancho, Cy + k * tam) Next End Sub

Private Sub BtnBorrar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnBorrar.Click Grafico.Clear(Color.White) End Sub

Private Sub BtnSumar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnSumar.Click Dim ex As Integer = 1 IniciarColores() Iniciarvector(VUnidades1, 0, 0, NCol - 1) Iniciarvector(VDecenas1, 0, 0, NCol - 1) Iniciarvector(VCentenas1, 0, 0, NCol - 1) Iniciarvector(VMillares1, 0, 0, NCol - 1) Dim contUnidades As Integer = 0 Dim contdecenas As Integer = 0

Page 67: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -811-

Dim ContCentenas As Integer = 0 Dim ContMillares As Integer = 0 Dim Valores1(5) As Integer Dim Valores2(5) As Integer Dim tope1 As Integer = 4 Dim tope2 As Integer = 4 Dim residuo As Integer Dim cociente As Integer nro1 = txtNro1.Text nro2 = txtNro2.Text Iniciarvector(Valores1, 0, 0, 5) Iniciarvector(Valores2, 0, 0, 5) Dim cont As Integer Dim numero As Integer cont = 0 numero = nro1 tope1 = 1000 tope2 = 1000 While numero > 0 cociente = numero \ tope1 residuo = numero - cociente * tope1 Valores1(cont) = cociente numero = residuo tope1 = tope1 \ 10 cont = cont + 1 End While numero = nro2 cont = 0 While numero > 0 cociente = numero \ tope2 residuo = numero - cociente * tope2 Valores2(cont) = cociente numero = residuo tope2 = tope2 \ 10 cont = cont + 1 End While resultado = nro1 + nro2 txtResultado.Text = resultado contUnidades = 0 contdecenas = 0 ContCentenas = 0 ContMillares = 0 ' sumando unidades Iniciarvector(VUnidades1, 1, 0, Valores1(3) - 1) contUnidades = Valores1(3) + Valores2(3) If contUnidades < 10 Then Iniciarvector(VUnidades1, 1, Valores1(3), Valores2(3) - 1) Else contdecenas = contdecenas + 1 Iniciarvector(VDecenas1, 0, 0, nc - 1) Iniciarvector(VDecenas1, 2, 0, contdecenas - 1) contUnidades = contUnidades - 10

Page 68: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -812-

Iniciarvector(VUnidades1, 0, 0, nc - 1) Iniciarvector(VUnidades1, 1, 0, contUnidades - 1) End If Sleep(140) ' sumando decenas Iniciarvector(VDecenas1, 2, 0, Valores1(2) - 1) contdecenas = contdecenas + Valores1(2) + Valores2(2) If contdecenas < 10 Then Iniciarvector(VDecenas1, 2, Valores1(2), Valores2(2) - 1) Else ContCentenas = ContCentenas + 1 Iniciarvector(VCentenas1, 0, 0, nc - 1) Iniciarvector(VCentenas1, 3, 0, ContCentenas - 1) contdecenas = contdecenas - 10 Iniciarvector(VDecenas1, 0, 0, nc - 1) Iniciarvector(VDecenas1, 2, 0, contdecenas - 1) End If Sleep(140)

' sumando centenas Iniciarvector(VCentenas1, 3, 0, Valores1(1) - 1) ContCentenas = ContCentenas + Valores1(1) + Valores2(1) If ContCentenas < 10 Then Iniciarvector(VCentenas1, 3, Valores1(1), Valores2(1) - 1) Else ContMillares = ContMillares + 1 Iniciarvector(VMillares1, 0, 0, nc - 1) Iniciarvector(VMillares1, 4, 0, ContMillares - 1) ContCentenas = ContCentenas - 10 Iniciarvector(VCentenas1, 0, 0, nc - 1) Iniciarvector(VCentenas1, 3, 0, ContCentenas - 1) End If MostrarVector(VUnidades1, NCol - 1, 0, ex) REM unidades es primera fila MostrarVector(VDecenas1, NCol - 1, 1, ex) REM decenas segunda fila} MostrarVector(VCentenas1, NCol - 1, 2, ex) REM centenas tercera fila MostrarVector(VMillares1, NCol - 1, 3, ex) REM decenas segunda fila End Sub

Sub MostrarVector(ByVal A() As Integer, ByVal nc As Integer, ByVal fila As Integer, ByVal ex As Integer) Dim col As Integer, indice As Integer Dim factor As Single = 0.1 Dim tam1 As Integer = tam * (1 - factor) For col = 0 To nc indice = A(col) Sleep(80) BrochaSolida.Color = Color.FromArgb(MColores(indice, 0), MColores(indice, 1), MColores(indice, 2)) Grafico.FillRectangle(BrochaSolida, Cx + col * tam * ex + tam * factor * ex, Cy + fila * tam * ey - tam1 - factor, tam1, tam1) Next End Sub

Page 69: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -813-

Private Sub btnRestar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRestar.Click Dim ex As Integer = 1 IniciarColores() Iniciarvector(VUnidades1, 0, 0, NCol - 1) Dim contUnidades As Integer = 0 Dim Valores1(5) As Integer Dim Valores2(5) As Integer Dim tope1 As Integer = 4 Dim tope2 As Integer = 4 Dim residuo As Integer Dim cociente As Integer Dim cadena1 As String Dim cadena2 As String nro1 = txtNro1.Text nro2 = txtNro2.Text Iniciarvector(Valores1, 0, 0, 5) Iniciarvector(Valores2, 0, 0, 5) Dim cont As Integer Dim numero As Integer cont = 0 numero = nro1 tope1 = 1000 tope2 = 1000 While numero > 0 cociente = numero \ tope1 residuo = numero - cociente * tope1 Valores1(cont) = cociente numero = residuo tope1 = tope1 \ 10 cont = cont + 1 End While numero = nro2 cont = 0 While numero > 0 cociente = numero \ tope2 residuo = numero - cociente * tope2 Valores2(cont) = cociente numero = residuo tope2 = tope2 \ 10 cont = cont + 1 End While resultado = nro1 - nro2 txtResultado.Text = resultado contUnidades = 0 ' RESTANDO UNIDADES Iniciarvector(VUnidades1, 0, 0, nc - 1) contUnidades = Valores1(3) - Valores2(3) Iniciarvector(VUnidades1, 1, 0, Math.Abs(contUnidades) - 1) If contUnidades < 10 Then If contUnidades < 0 Then

Page 70: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -814-

ex = -1 Else ex = 1 End If End If MostrarVector(VUnidades1, NCol - 1, 0, ex) REM unidades es primera fila End SubEnd Class

CODIGO DEL MODULO

Module Module1 Public Matriz(NFilas, NCol) As Integer Public Const NFilas As Integer = 10, NCol As Integer = 10, maximo = 5 Public relleno(maximo) As Integer Public tam As Integer = 30 Public nf As Integer = NFilas, nc As Integer = NCol Public VUnidades1(NCol) As Integer Public VDecenas1(NCol) As Integer Public VCentenas1(NCol) As Integer Public VMillares1(NCol) As Integer Public MColores(maximo, 3) As Integer Sub Iniciarvector(ByRef A() As Integer, ByVal nro As Integer, ByVal inicial As Integer, ByVal final As Integer) Dim fila As Integer For fila = inicial To inicial + final A(fila) = nro Next End Sub Sub IniciarColores() MColores(0, 0) = 255 MColores(0, 1) = 255 MColores(0, 2) = 255 MColores(1, 0) = 255 MColores(1, 1) = 0 MColores(1, 2) = 0 MColores(2, 0) = 0 MColores(2, 1) = 0 MColores(2, 2) = 255

MColores(3, 0) = 0 MColores(3, 1) = 255 MColores(3, 2) = 0 MColores(4, 0) = 255 MColores(4, 1) = 255 MColores(4, 2) = 0 End Sub

Sub IniciarMatriz(ByRef A(,) As Integer, ByVal nf As Integer, ByVal nc As Integer, ByVal nro As Integer) Dim fila As Integer, col As Integer For fila = 0 To nf - 1

Page 71: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -815-

For col = 0 To nc - 1 A(fila, col) = nro Next Next End SubEnd Module

11.9 APLICACIÓN DE TRADUCTOR DE ARCHIVOS

Imports System.IOModule Module1 Public srLector As StreamReader Public A(10) As String Public B(10) As StringEnd Module

Imports System.IOPublic Class Form1 Public srLector1 As StreamReader Public srLector2 As StreamReader Public swEscritor As StreamWriter Public A(200) As String Public B(200) As String Public nterminos As Integer = 0

Public Linea As String Public texto As String = ""

Page 72: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -816-

Public texto2 As String = "" Public ContadorLin As Integer = 1 Dim fila As Integer

Private Sub btnCargar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCargar.Click srLector1 = New StreamReader("e:\datos\datos1.txt") Linea = srLector1.ReadLine() Do While Not (Linea Is Nothing) ContadorLin += 1 texto = texto & Linea & vbCrLf Linea = srLector1.ReadLine() Loop TextBox1.Text = texto Me.Text = ContadorLin srLector1.Close() Console.ReadLine() End Sub

Private Sub btnCambiar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCambiar.Click Dim nombre1 As String Dim nombre2 As String texto2 = texto For fila = 0 To nterminos nombre1 = A(fila) nombre2 = B(fila) texto2 = Replace(texto2, nombre1, nombre2) Next TextBox1.Text = texto TextBox2.Text = texto2 End Sub

Private Sub btnTerminos_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnTerminos.Click srLector2 = New StreamReader("E:\datos\terminos1.txt") Dim cadena As String = "" Dim subcadena1 As String Dim subcadena2 As String Dim cont As Integer = 0 cadena = srLector2.ReadLine() Dim pos As Integer = 0 Do While Not (cadena Is Nothing) pos = InStr(1, cadena, Chr(9)) pos = InStr(1, cadena, Chr(9)) subcadena1 = Mid(cadena, 1, pos - 1) A(cont) = subcadena1 subcadena2 = Mid(cadena, pos + 1, Len(cadena) - pos) B(cont) = subcadena2 cadena = srLector2.ReadLine() cont += 1 Loop

Page 73: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -817-

Me.Text = "term" & cont srLector2.Close() ListBox1.Items.Clear() ListBox2.Items.Clear() nterminos = cont For i = 0 To nterminos - 1 ListBox1.Items.Add(A(i)) ListBox2.Items.Add(B(i)) Next End Sub

Private Sub BTNPRUEBA_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGrabar.Click swEscritor = New StreamWriter("e:\datos\datos2.txt") ' escribir líneas swEscritor.WriteLine(texto2) swEscritor.Close() End SubEnd Class

11.10 BUSCADOR

CODIGO DEL MODULO

Imports System.IOModule module1 '/*** declaraciones Public Const maxfilas As Integer = 20, maxcol As Integer = 30 Public Matriz(maxfilas, maxcol) As Integer Public Cx As Integer = 1, Cy As Integer = 1 Public dir As Integer = 0, valor As Integer = 0 Public final As Integer = 0, cont As Integer = 0

Page 74: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -818-

Public nfilasPantalla = 22, NcolPantalla = 32 Public srLector As StreamReader Public nf As Integer Public nc As Integer Public Objetos(maxfilas * maxcol) Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)

Public Sub RecuperarArchivo(ByVal A(,) As Integer, ByVal nf As Integer, ByVal nc As Integer) srLector = New StreamReader("e:\DATOS\Matriz30x20.txt") Dim cadena As String Dim subcadena As String Dim pos As Integer = 0 Dim longitud As String Dim inicio As Integer = 1 Dim cont As Integer = 0 For fila = 0 To nf - 1 cadena = srLector.ReadLine() longitud = Len(cadena) inicio = 1 cont = 0 Do pos = InStr(inicio, cadena, Chr(9)) If pos > 0 Then subcadena = Mid(cadena, inicio, pos - inicio) A(fila, cont) = Val(subcadena) inicio = pos + 1 cont += 1 Else subcadena = Mid(cadena, inicio, longitud - inicio + 1) A(fila, cont) = Val(subcadena) cont += 1 Exit Do End If Loop While (inicio <= longitud) Next Console.WriteLine("Archivo leido satisfactoriamente") srLector.Close() End SubEnd Module

CODIGO DEL FORMULARIO

Imports System.DrawingPublic Class Form1 Dim fila As Integer Dim col As Integer Dim tam As Integer = 20 Dim nf As Integer Dim nc As Integer Dim Color As Color Dim Grafico As Graphics

Page 75: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -819-

Dim BrochaSólida As SolidBrush Public Structure Buscador Public nro As Integer Public dir1 As Integer, dir2 As Integer, dir3 As Integer, dir4 As Integer ' declarar matrices de 4 Public Cx As Integer Public Cy As Integer Public np As Integer Public Valor As Integer, rojo As Integer, verde As Integer, azul As Integer, Direc As Integer End Structure Public Objeto1 As Buscador Sub InicializarObjeto(ByRef Objeto1 As Buscador) Objeto1.Cx = 14 Objeto1.Cy = 13 Objeto1.rojo = 255 Objeto1.verde = 0 Objeto1.azul = 0 Objeto1.Valor = 1 Objeto1.dir1 = 0 Objeto1.dir2 = 0 Objeto1.dir3 = 0 Objeto1.dir4 = 0 Objeto1.np = 0 Objeto1.nro = 0 End Sub

Function obtenerDir(ByVal d1 As Integer, ByVal d2 As Integer, ByVal d3 As Integer, ByVal d4 As Integer) As Integer If d1 = 1 Then obtenerDir = 1 : Exit Function If d2 = 1 Then obtenerDir = 2 : Exit Function If d3 = 1 Then obtenerDir = 3 : Exit Function If d4 = 1 Then obtenerDir = 4 : Exit Function obtenerDir = 0 End Function

Function evaluar(ByRef objeto1 As Buscador, ByVal Matriz(,) As Integer, ByVal camino As Integer, ByVal meta As Integer) As Integer Dim cont As Integer = 0, Cx As Integer, Cy As Integer, Direc As Integer = 0, i As Integer Dim resultado As Integer = 0 objeto1.dir1 = 0 objeto1.dir2 = 0 objeto1.dir3 = 0 objeto1.dir4 = 0 Cx = objeto1.Cx Cy = objeto1.Cy ' primero evalua si ya encontro la metas If Matriz(Cy, Cx + 1) = meta Then objeto1.dir1 = 1 cont = cont + 1 evaluar = 1

Page 76: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -820-

Exit Function End If If Matriz(Cy - 1, Cx) = meta Then objeto1.dir2 = 1 cont = cont + 1 evaluar = 1 Exit Function End If If Matriz(Cy, Cx - 1) = meta Then objeto1.dir3 = 1 cont = cont + 1 evaluar = 1 Exit Function End If If Matriz(Cy + 1, Cx) = meta Then objeto1.dir4 = 1 cont = cont + 1 evaluar = 1 Exit Function End If '// si no encuentra meta evalua si hay camino If Matriz(Cy, Cx + 1) = camino Then objeto1.dir1 = 1 cont = cont + 1 End If If Matriz(Cy - 1, Cx) = camino Then objeto1.dir2 = 1 cont = cont + 1 End If If Matriz(Cy, Cx - 1) = camino Then objeto1.dir3 = 1 cont = cont + 1 End If If Matriz(Cy + 1, Cx) = camino Then objeto1.dir4 = 1 cont = cont + 1 End If objeto1.np = cont Direc = obtenerDir(objeto1.dir1, objeto1.dir2, objeto1.dir3, objeto1.dir4) objeto1.Direc = Direc evaluar = 0 End Function Sub MostrarObjeto(ByVal figura As Buscador, ByVal Cx As Integer, ByVal Cy As Integer) Grafico.FillRectangle(Brushes.Red, figura.Cx * tam + Cx, figura.Cy * tam + Cy, tam, tam) End Sub

Sub MostrarPunto(ByVal Objeto1 As Buscador, ByVal Cx As Integer, ByVal Cy As Integer, ByVal valor As Integer) Select Case valor Case 0 : Color = Color.FromArgb(255, 255, 255)

Page 77: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -821-

Case 2 : Color = Color.FromArgb(0, 150, 0) Case 3 : Color = Color.FromArgb(0, 255, 0) Case 4 : Color = Color.FromArgb(255, 255, 0) Case 5 : Color = Color.FromArgb(0, 255, 255) Case 9 : Color = Color.FromArgb(0, 0, 255) End Select End Sub

Sub MostrarMatrizEnPantalla(ByVal Cx As Integer, ByVal Cy As Integer, ByVal A(,) As Integer, ByVal nfilas As Integer, ByVal ncol As Integer) For fila = 0 To nfilas - 1 For col = 0 To ncol - 1 Select Case Matriz(fila, col) Case 0 : Grafico.FillRectangle(Brushes.White, col * tam + Cx, fila * tam + Cy, tam, tam) Case 2 : Grafico.FillRectangle(Brushes.Gray, col * tam + Cx, fila * tam + Cy, tam, tam)Case 3 : Grafico.FillRectangle(Brushes.Green, col * tam + Cx, fila * tam + Cy, tam, tam)Case 4 : Grafico.FillRectangle(Brushes.Yellow, col * tam + Cx, fila * tam + Cy, tam, tam)Case 5 : Grafico.FillRectangle(Brushes.Gold, col * tam + Cx, fila * tam + Cy, tam, tam) Case 9 : Grafico.FillRectangle(Brushes.Blue, col * tam + Cx, fila * tam + Cy, tam, tam) End Select Next col Next fila End Sub Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load nf = 20 nc = 30 Objeto1 = New Buscador InicializarObjeto(Objeto1) PictureBox1.Width = nc * tam + 1 PictureBox1.Height = nf * tam + 1 Grafico = PictureBox1.CreateGraphics End Sub Private Sub BtnPrincipal_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnPrincipal.Click Dim Px2 As Integer = 0, Py2 As Integer = 0, valorbuscado As Integer = 2, huella As Integer = 4 Dim camino As Integer = 0, terminado As Integer = 0, retorno As Integer = 5 Dim meta As Integer = 9, resultado As Integer = 0, dir As Integer = 0 Dim valor As Integer = 0, final As Integer = 0, cont As Integer = 0, NroObjeto As Integer = 0 InicializarObjeto(Objeto1) RecuperarArchivo(Matriz, nf, nc) final = 0 Matriz(5, 7) = 9 ' para probar la metas MostrarMatrizEnPantalla(Cx, Cy, Matriz, nf, nc) MostrarObjeto(Objeto1, Cx, Cy) NroObjeto = 0 Objetos(NroObjeto) = Objeto1 Matriz(Objeto1.Cy, Objeto1.Cx) = huella PictureBox1.Refresh()

Page 78: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -822-

Do Do MostrarMatrizEnPantalla(Cx, Cy, Matriz, nf, nc) MostrarObjeto(Objeto1, Cx, Cy) resultado = evaluar(Objeto1, Matriz, camino, meta) If resultado = 1 Then GoTo fin dir = Objeto1.Direc Select Case dir Case 1 : Objeto1.Cx = Objeto1.Cx + 1 Case 2 : Objeto1.Cy = Objeto1.Cy - 1 Case 3 : Objeto1.Cx = Objeto1.Cx - 1 Case 4 : Objeto1.Cy = Objeto1.Cy + 1 Case Else : terminado = 1 End Select Matriz(Objeto1.Cy, Objeto1.Cx) = huella MostrarPunto(Objeto1, Cx, Cy, huella) NroObjeto = NroObjeto + 1 cont = cont + 1 Objeto1.nro = NroObjeto Objetos(NroObjeto) = Objeto1 Loop While terminado = 0 terminado = 0 Do Objeto1 = Objetos(NroObjeto) MostrarMatrizEnPantalla(Cx, Cy, Matriz, nf, nc) MostrarObjeto(Objeto1, Cx, Cy) resultado = evaluar(Objeto1, Matriz, camino, meta) dir = Objeto1.Direc If (NroObjeto < 0) Then GoTo fin If dir > 0 Then terminado = 1 Else Matriz(Objeto1.Cy, Objeto1.Cx) = retorno MostrarPunto(Objeto1, Cx, Cy, retorno) NroObjeto = NroObjeto - 1 If (NroObjeto < 0) Then GoTo fin cont = cont + 1 'Sleep(10) End If Loop While terminado = 0 If NroObjeto < 0 Then final = 1 Loop While final = 0 MostrarObjeto(Objeto1, Cx, Cy)fin: If NroObjeto > 0 Then MsgBox(" X= " & Objetos(NroObjeto).cx & " Y = " & Objetos(NroObjeto).cy & " Mov =" & cont) Else MsgBox(" no se encontro la meta y se hizo " & cont & " Movimientos ") End If End Sub

Page 79: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -823-

Private Sub btnBorrar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBorrar.Click Grafico.Clear(Color.White) End SubEnd Class

11.11 PROBLEMA DE CRUCE

Se ingresas 4 puntos ( puntos inicial y final de dos rectas) determiner si esos puntos se Cruzan o no se Cruzan

Module Module1 Sub Main() Dim resultado1 As Integer = 0 ' " 0 no hay cruce 1 hay cruce RecuperarPuntos(X, Y, np) Console.WriteLine(" vector X") Imprimir(X, np) Console.WriteLine(" vector Y") Imprimir(Y, np) resultado1 = Interseccion(X, Y) Console.WriteLine() If resultado1 = 1 Then Console.WriteLine(" EL valor es =={0} HAY CRUCE ", resultado1) Else Console.WriteLine(" EL valor es =={0} no hay cruce ", resultado1) End If Console.ReadLine() End SubEnd Module

CODIGO DEL MODULO 2

Imports System.IOModule Module2 Public X(4) As Single Public Y(4) As Single

Page 80: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -824-

Public np As Integer = 4 Public Sub RecuperarPuntos(ByVal X() As Single, ByVal Y() As Single, ByVal nf As Integer) Dim fila As Integer Dim cadena As String Dim pos As Integer Dim srLector = New StreamReader("E:\datos\Puntos2x4.txt") For fila = 0 To nf - 1 cadena = srLector.ReadLine() pos = InStr(1, cadena, Chr(9)) X(fila) = Mid(cadena, 1, pos - 1) Y(fila) = Mid(cadena, pos + 1, Len(cadena)) Next srLector.Close() End Sub Function Interseccion(ByVal X() As Single, ByVal Y() As Single) As Integer Dim resultado As Integer Dim XA(4) As Single Dim YA(4) As Single Dim xmin As Single Dim ymin As Single Dim xmax As Single Dim ymax As Single Dim px As Single Dim py As Single copiar(X, XA, 4) limites(XA, xmin, xmax) REM Console.WriteLine(" valores de xmin {0} xmax {1} ", xmin, xmax) copiar(Y, YA, 4) limites(YA, ymin, ymax) If (X(0) = X(2) And Y(0) = Y(2)) Or (X(1) = X(3) And Y(1) = Y(3)) Then resultado = 0 Else px = ((X(0) * Y(1) - Y(0) * X(1)) * (X(2) - X(3)) - (X(0) - X(1)) * (X(2) * Y(3) - Y(2) * X(3))) / ((X(0) - X(1)) * (Y(2) - Y(3)) - (Y(0) - Y(1)) * (X(2) - X(3))) py = ((X(0) * Y(1) - Y(0) * X(1)) * (Y(2) - Y(3)) - (Y(0) - Y(1)) * (X(2) * Y(3) - Y(2) * X(3))) / ((X(0) - X(1)) * (Y(2) - Y(3)) - (Y(0) - Y(1)) * (X(2) - X(3))) If px >= xmin And px <= xmax And py >= ymin And py <= ymax Then resultado = 1 Else resultado = 0 End If End If Return resultado End Function

Sub Imprimir(ByVal X() As Single, ByVal ne As Integer) Dim fila As Integer For fila = 0 To ne - 1 Console.Write(" {0} ", X(fila)) Next End Sub

Page 81: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -825-

Sub copiar(ByVal A() As Single, ByRef B() As Single, ByVal ne As Integer) Dim fila As Integer For fila = 0 To ne - 1 B(fila) = A(fila) Next End Sub Sub Ordenar(ByVal A() As Single, ByVal np As Integer) Dim fila As Integer Dim col As Integer Dim temp As Single For fila = 0 To np - 2 For col = fila + 1 To np - 1 If (A(col) < A(fila)) Then temp = A(fila) A(fila) = A(col) A(col) = temp End If Next col Next fila End Sub Sub limites(ByRef A() As Single, ByRef xmin As Single, ByRef xmax As Single) Ordenar(A, np) xmin = A(1) xmax = A(2) End SubEnd Module

11.12 PROGRAMA DE LOCALIZACION DE LOTES

Page 82: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -826-

Option Explicit OnImports System.DrawingPublic Class Form1 Dim px1 As Integer Dim py1 As Integer Dim Grafico As Graphics Dim ColorFondo As Color = Color.FromArgb(255, 255, 255) Dim pen1 As Pen Dim pen2 As Pen

Page 83: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -827-

Dim X(maxfilas) As Single Dim Y(maxfilas) As Single Dim Cx As Integer = 100 Dim Cy As Integer = 300 Dim ex As Single = 1 Dim ey As Single = -1 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Grafico = PictureBox1.CreateGraphics pen1 = New Pen(Color.FromArgb(255, 0, 0), 2) pen2 = New Pen(Color.FromArgb(0, 0, 255), 3) End Sub Private Sub BtnBorrar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnBorrar.Click Grafico.Clear(Color.White) End Sub Private Sub Btndibujar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Btndibujar.Click Dim fila As Integer Dim resultado1 As Integer = 0 Dim cadena1 As String Dim cadenaPos As String Dim psx As Integer Dim psy As Integer Dim pos As Integer Dim px1 As Integer = 16 Dim py1 As Integer = 6 Dim valor As Integer = 0 Grafico.DrawLine(pen1, 0, Cy, Cx * 2, Cy) Grafico.DrawLine(pen1, Cx, 0, Cx, Cy * 2) RecuperarTabla(Tabla, nreg, ncampos) MostrarTabla(Tabla, nreg, ncampos) For fila = 0 To nreg - 1 cadena1 = Tabla(fila, 2) np = Tabla(fila, 1) cadenaPos = Tabla(fila, 3) pos = InStr(1, cadenaPos, ";") psx = Mid(cadenaPos, 1, pos - 1) psy = Mid(cadenaPos, pos + 1, Len(cadenaPos)) ObtenerVectores(X, Y, np, cadena1) graficar(X, Y, Cx, Cy, ex, ey, np) Next End Sub Sub graficar(ByVal X() As Single, ByVal Y() As Single, ByVal Cx As Integer, ByVal cy As Integer, ByVal ex As Single, ByVal ey As Single, ByVal np As Integer) Dim fila As Integer For fila = 1 To np Grafico.DrawLine(pen2, Cx + X(fila - 1) * ex, cy + Y(fila - 1) * ey, Cx + X(fila) * ex, cy + Y(fila) * ey) Next End Sub

Page 84: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -828-

Private Sub PictureBox1_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseDown ListBox1.Items.Clear() Dim informe As String Dim retorno As Integer = 0 Dim fila As Integer Dim resultado1 As Integer = 0 Dim valor As Integer = 0 Dim psx As Integer Dim psy As Integer Dim pos As Integer Dim cadena1 As String Dim cadenaPos As String Me.Text = "X = " & e.X & " Y = " & e.Y px1 = e.X - Cx py1 = -(e.Y - Cy) txtX.Text = px1 txtY.Text = py1 X1(0) = px1 Y1(0) = py1 fila = 1 For fila = 0 To nreg - 1 cadena1 = Tabla(fila, 2) np = Tabla(fila, 1) cadenaPos = Tabla(fila, 3) pos = InStr(1, cadenaPos, ";") psx = Mid(cadenaPos, 1, pos - 1) psy = Mid(cadenaPos, pos + 1, Len(cadenaPos)) ObtenerVectores(X, Y, np, cadena1) X1(1) = psx Y1(1) = psy valor = 0 For k = 1 To np X1(2) = X(k - 1) : Y1(2) = Y(k - 1) X1(3) = X(k) : Y1(3) = Y(k) resultado1 = Interseccion(X1, Y1) If resultado1 = 1 Then valor = 1 Exit For End If Next ListBox1.Items.Add(" EL valor es == " & valor) If valor = 0 Then informe = Tabla(fila, 4) Exit For End If Next If valor = 0 Then TextBox1.Text = informe Else TextBox1.Text = "FUERA" End If

Page 85: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -829-

End SubEnd Class

CODIGO DEL MODULO

Imports System.IOModule Module2 Public cadena As String Public Const maxfilas As Integer = 20 Public Const maxcol As Integer = 20 Public resultado As Integer = 0 Public Tabla(maxfilas, maxfilas) As String Public X1(maxfilas) As Single Public Y1(maxfilas) As Single Public XA(maxfilas) As Single Public YA(maxfilas) As Single Public xmin As Single Public xmax As Single Public ymin As Single Public ymax As Single Public nreg As Integer = 4 Public ncampos As Integer = 5 Public nf As Integer = maxfilas, nc As Integer = maxcol Public np As Integer Public Ser As Integer = 1 Public espacio As Integer = 0

Public Sub RecuperarTabla(ByVal A(,) As String, ByVal nf As Integer, ByVal nc As Integer) Dim srLector = New StreamReader("E:\datos\Tabla5x2.txt") Dim cadena As String, subcadena As String Dim pos As Integer = 0, fila1 As Integer, longitud As String Dim inicio As Integer = 1, cont As Integer = 0 For fila1 = 0 To nf - 1 cadena = srLector.ReadLine() longitud = Len(cadena) inicio = 1 : cont = 0 Do pos = InStr(inicio, cadena, Chr(9)) If pos > 0 Then subcadena = Mid(cadena, inicio, pos - inicio) A(fila1, cont) = subcadena inicio = pos + 1 cont += 1 Else subcadena = Mid(cadena, inicio, longitud - inicio + 1) A(fila1, cont) = subcadena cont += 1 Exit Do End If Loop While (inicio <= longitud) Next

Page 86: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -830-

srLector.Close() End Sub Sub MostrarTabla(ByVal A(,) As String, ByVal nf As Integer, ByVal nc As Integer) Dim fila As Integer, col As Integer For fila = 0 To nf - 1 Console.WriteLine() For col = 0 To nc - 1 Console.Write("{0} ", A(fila, col)) Next Next End Sub

Function Interseccion(ByVal X() As Single, ByVal Y() As Single) As Integer Dim px As Single Dim py As Single copiar(X, XA, 4) limites(XA, xmin, xmax) copiar(Y, YA, 4) limites(YA, ymin, ymax) px = ((X(0) * Y(1) - Y(0) * X(1)) * (X(2) - X(3)) - (X(0) - X(1)) * (X(2) * Y(3) - Y(2) * X(3))) / ((X(0) - X(1)) * (Y(2) - Y(3)) - (Y(0) - Y(1)) * (X(2) - X(3))) py = ((X(0) * Y(1) - Y(0) * X(1)) * (Y(2) - Y(3)) - (Y(0) - Y(1)) * (X(2) * Y(3) - Y(2) * X(3))) / ((X(0) - X(1)) * (Y(2) - Y(3)) - (Y(0) - Y(1)) * (X(2) - X(3))) If px >= xmin And px <= xmax And py >= ymin And py <= ymax Then resultado = 1 Else resultado = 0 End If Return resultado End Function

Sub copiar(ByVal A() As Single, ByRef B() As Single, ByVal ne As Integer) Dim fila As Integer For fila = 0 To ne - 1 B(fila) = A(fila) Next End Sub

Sub limites(ByRef A() As Single, ByRef xmin As Single, ByRef xmax As Single) Dim fila As Integer Dim col As Integer REM primero ordenamos Dim temp As Single For fila = 0 To 2 For col = fila + 1 To 3 If (A(col) < A(fila)) Then temp = A(fila) A(fila) = A(col) A(col) = temp End If Next col Next fila

Page 87: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -831-

xmin = A(1) xmax = A(2) End Sub Sub ObtenerVectores(ByRef X() As Single, ByRef Y() As Single, ByVal np As Integer, ByVal cadena1 As String) Dim pos1 As Integer Dim pos2 As Integer Dim fila As Integer = 0 pos2 = 1 Dim cadena2 As String For fila = 0 To np - 1 pos1 = InStr(1, cadena1, ";") cadena2 = Mid(cadena1, 1, pos1 - 1) X(fila) = cadena2 cadena1 = Mid(cadena1, pos1 + 1, Len(cadena1)) pos1 = InStr(1, cadena1, ";") cadena2 = Mid(cadena1, 1, pos1 - 1) Y(fila) = cadena2 cadena1 = Mid(cadena1, pos1 + 1, Len(cadena1)) Next X(np) = X(0) Y(np) = Y(0) End SubEnd Module

11.13 MODELADO 3D si tiene los siguientes puntos para un cubo realizar el modelado 3D

EJEX EJEY EJE Z0 1 2 3 4 0 1 2 3 4 0 1 2 3 40 -1 1 1 -1 0 0 -1 -1 1 1 0 0 -1 -1 -1 -1 01 1 1 1 1 0 1 -1 -1 1 1 0 1 -1 1 1 -1 02 -1 -1 1 1 0 2 -1 1 1 -1 0 2 1 1 1 1 03 -1 -1 -1 -1 0 3 -1 1 1 -1 0 3 -1 -1 1 1 04 -1 -1 1 1 0 4 1 1 1 1 0 4 1 -1 -1 1 05 -1 1 1 -1 0 5 -1 -1 -1 -1 0 5 1 1 -1 -1 0

Page 88: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -832-

CODIGO DEL MODULO

Imports System.IOModule Module1 Public MX1(,) As Single = {{-1, 1, 1, -1, 0}, {1, 1, 1, 1, 0}, {-1, -1, 1, 1, 0}, {-1, -1, -1, -1, 0}, {-1, -1, 1, 1, 0}, {-1, 1, 1, -1, 0}} Public MY1(,) As Single = {{-1, -1, 1, 1, 0}, {-1, -1, 1, 1, 0}, {-1, 1, 1, -1, 0}, {-1, 1, 1, -1, 0}, {1, 1, 1, 1, 0}, {-1, -1, -1, -1, 0}} Public MZ1(,) As Single = {{-1, -1, -1, -1, 0}, {-1, 1, 1, -1, 0}, {1, 1, 1, 1, 0}, {-1, -1, 1, 1, 0}, {1, -1, -1, 1, 0}, {1, 1, -1, -1, 0}}

Public MX2(maxfilas, maxcol) As Single Public MY2(maxfilas, maxcol) As Single Public MZ2(maxfilas, maxcol) As Single ' ************** Public AnguloX As Integer = 0 Public AnguloY As Integer = 0 Public AnguloZ As Integer = 0 Public brocha As SolidBrush Public Const limite As Integer = 200 Public Const maxcol As Integer = 5 Public Const maxfilas = 6 Public Cx As Integer = 200 '00 Public Cy As Integer = 200 '200 Public Cz As Integer = 0

Public VXx(2) As Single Public VXy(2) As Single Public VXz(2) As Single

Public VYx(2) As Single Public VYy(2) As Single Public VYz(2) As Single

Public VZx(2) As Single Public VZy(2) As Single Public VZz(2) As Single Public D As Single = 10000 Public Ex As Single = 50

Page 89: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -833-

Public Ey As Single = 50 Public Ez As Integer = 50 Public Grafico As Graphics Public modo As Integer = 1 Public nc As Integer = 5 Public nf As Integer = 6 '6 Public Normales(maxfilas, 4) As Single Public Pen As Pen Public srLector As StreamReader Public tam As Single = 4 Public tx As Single Public ty As Single Public tz As Single Public vel As Integer = 40 Sub CopiarMatriz(ByVal A(,) As Single, ByRef B(,) As Single, ByVal nf As Integer, ByVal nc As Integer) Dim fila As Integer, col As Integer For fila = 0 To nf - 1 For col = 0 To nc - 1 B(fila, col) = A(fila, col) Next B(fila, nc - 1) = B(fila, 0) Next End Sub

Sub IniciarMatriz(ByVal A(,) As Single, ByVal nf As Integer, ByVal nc As Integer) Dim fila As Integer, col As Integer For fila = 0 To nf - 1 For col = 0 To nc - 1 A(fila, col) = 0 Next Next End Sub

Sub EscaladoXYZ(ByVal Ex As Single, ByVal Ey As Single, ByVal Ez As Single) Dim fila, col As Integer For fila = 0 To nf - 1 For col = 0 To nc - 1 MX2(fila, col) = MX2(fila, col) * Ex MY2(fila, col) = MY2(fila, col) * Ey MZ2(fila, col) = MZ2(fila, col) * Ez Next Next ' escalando coordendas For fila = 0 To 1 VXx(fila) = VXx(fila) * Ex VXy(fila) = VXy(fila) * Ey VXz(fila) = VXz(fila) * Ez

VYx(fila) = VYx(fila) * Ex VYy(fila) = VYy(fila) * Ey VYz(fila) = VYz(fila) * Ez

Page 90: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -834-

VZx(fila) = VZx(fila) * Ex VZy(fila) = VZy(fila) * Ey VZz(fila) = VZz(fila) * Ez Next End Sub Sub RotacionXYZ(ByVal AnguloX As Single, ByVal AnguloY As Single, ByVal anguloZ As Single)

Dim x1 As Single, y1 As Single, z1 As Single Dim x2 As Single, y2 As Single, z2 As Single Dim fila As Integer = 0, col As Integer REM rotacion X Dim arx = AnguloX * Math.PI / 180 For fila = 0 To nf - 1 For col = 0 To nc - 1 x1 = MX1(fila, col) y1 = MY1(fila, col) z1 = MZ1(fila, col) x2 = x1 y2 = CSng(y1 * Math.Cos(arx) - z1 * Math.Sin(arx)) z2 = CSng(y1 * Math.Sin(arx) + z1 * Math.Cos(arx)) MX2(fila, col) = x2 MY2(fila, col) = y2 MZ2(fila, col) = z2 Next Next REM rotacion Y Dim ary = AnguloY * Math.PI / 180 For fila = 0 To nf - 1 For col = 0 To nc - 1 x1 = MX2(fila, col) y1 = MY2(fila, col) z1 = MZ2(fila, col) x2 = CSng(x1 * Math.Cos(ary) - z1 * Math.Sin(ary)) y2 = y1 z2 = CSng(-x1 * Math.Sin(ary) + z1 * Math.Cos(ary)) MX2(fila, col) = x2 MY2(fila, col) = y2 MZ2(fila, col) = z2 Next Next REM rotacion Z

Dim arz = anguloZ * Math.PI / 180 For fila = 0 To nf - 1 For col = 0 To nc - 1 x1 = MX2(fila, col) y1 = MY2(fila, col) z1 = MZ2(fila, col) x2 = CSng(x1 * Math.Cos(arz) - y1 * Math.Sin(arz)) y2 = CSng(x1 * Math.Sin(arz) + y1 * Math.Cos(arz))

Page 91: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -835-

z2 = z1 MX2(fila, col) = x2 MY2(fila, col) = y2 MZ2(fila, col) = z2 Next Next End Sub Sub RotarCoordenadasEjeX(ByVal AnguloX As Single, ByVal AnguloY As Single, ByVal anguloZ As Single) Dim x1 As Single, y1 As Single, z1 As Single Dim x2 As Single, y2 As Single, z2 As Single Dim fila As Integer = 0 REM rotacion de la s coordendas REM rotacion del eje X en X Dim arx As Single = AnguloX * Math.PI / 180 For fila = 0 To 1 x1 = VXx(fila) y1 = VXy(fila) z1 = VXz(fila) x2 = x1 y2 = CSng(y1 * Math.Cos(arx) - z1 * Math.Sin(arx)) z2 = CSng(y1 * Math.Sin(arx) + z1 * Math.Cos(arx)) VXx(fila) = x2 VXy(fila) = y2 VXz(fila) = z2 Next

REM rotacion Y Dim ary As Single = AnguloY * Math.PI / 180 For fila = 0 To 1 x1 = VXx(fila) y1 = VXy(fila) z1 = VXz(fila) x2 = CSng(x1 * Math.Cos(ary) - z1 * Math.Sin(ary)) y2 = y1 z2 = CSng(-x1 * Math.Sin(ary) + z1 * Math.Cos(ary)) VXx(fila) = x2 VXy(fila) = y2 VXz(fila) = z2 Next REM rotacion Z

Dim arz As Single = anguloZ * Math.PI / 180 For fila = 0 To 1 x1 = VXx(fila) y1 = VXy(fila) z1 = VXz(fila) x2 = CSng(x1 * Math.Cos(arz) - y1 * Math.Sin(arz)) y2 = CSng(x1 * Math.Sin(arz) + y1 * Math.Cos(arz)) z2 = z1 VXx(fila) = x2 VXy(fila) = y2

Page 92: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -836-

VXz(fila) = z2 Next Grafico.Clear(Color.White) End Sub Sub RotarCoordenadasEjey(ByVal AnguloX As Single, ByVal AnguloY As Single, ByVal anguloZ As Single)

Dim x1 As Single, y1 As Single, z1 As Single Dim x2 As Single, y2 As Single, z2 As Single Dim fila As Integer = 0 REM rotacion de la s coordendas REM rotacion del eje X en X Dim arx As Single = AnguloX * Math.PI / 180 For fila = 0 To 1 x1 = VYx(fila) y1 = VYy(fila) z1 = VYz(fila) x2 = x1 y2 = CSng(y1 * Math.Cos(arx) - z1 * Math.Sin(arx)) z2 = CSng(y1 * Math.Sin(arx) + z1 * Math.Cos(arx)) VYx(fila) = x2 VYy(fila) = y2 VYz(fila) = z2 Next

REM rotacion Y Dim ary As Single = AnguloY * Math.PI / 180

For fila = 0 To 1 x1 = VYx(fila) y1 = VYy(fila) z1 = VYz(fila) x2 = CSng(x1 * Math.Cos(ary) - z1 * Math.Sin(ary)) y2 = y1 z2 = CSng(-x1 * Math.Sin(ary) + z1 * Math.Cos(ary)) VYx(fila) = x2 VYy(fila) = y2 VYz(fila) = z2 Next REM rotacion Z Dim arz As Single = anguloZ * Math.PI / 180 For fila = 0 To 1 x1 = VYx(fila) y1 = VYy(fila) z1 = VYz(fila) x2 = CSng(x1 * Math.Cos(arz) - y1 * Math.Sin(arz)) y2 = CSng(x1 * Math.Sin(arz) + y1 * Math.Cos(arz)) z2 = z1 VYx(fila) = x2 VYy(fila) = y2 VYz(fila) = z2 Next

Page 93: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -837-

Grafico.Clear(Color.White) End Sub Sub RotarCoordenadasEjeZ(ByVal AnguloX As Single, ByVal AnguloY As Single, ByVal anguloZ As Single) Dim x1 As Single, y1 As Single, z1 As Single Dim x2 As Single, y2 As Single, z2 As Single Dim fila As Integer = 0 REM rotacion de la s coordendas REM rotacion del eje X en X Dim arx As Single = AnguloX * Math.PI / 180 For fila = 0 To 1 x1 = VZx(fila) y1 = VZy(fila) z1 = VZz(fila) x2 = x1 y2 = CSng(y1 * Math.Cos(arx) - z1 * Math.Sin(arx)) z2 = CSng(y1 * Math.Sin(arx) + z1 * Math.Cos(arx)) VZx(fila) = x2 VZy(fila) = y2 VZz(fila) = z2 Next REM rotacion Y Dim ary As Single = AnguloY * Math.PI / 180

For fila = 0 To 1 x1 = VZx(fila) y1 = VZy(fila) z1 = VZz(fila) x2 = CSng(x1 * Math.Cos(ary) - z1 * Math.Sin(ary)) y2 = y1 z2 = CSng(-x1 * Math.Sin(ary) + z1 * Math.Cos(ary)) VZx(fila) = x2 VZy(fila) = y2 VZz(fila) = z2 Next REM rotacion Z

Dim arz As Single = anguloZ * Math.PI / 180 For fila = 0 To 1 x1 = VZx(fila) y1 = VZy(fila) z1 = VZz(fila) x2 = CSng(x1 * Math.Cos(arz) - y1 * Math.Sin(arz)) y2 = CSng(x1 * Math.Sin(arz) + y1 * Math.Cos(arz)) z2 = z1 VZx(fila) = x2 VZy(fila) = y2 VZz(fila) = z2 Next Grafico.Clear(Color.White) End Sub

Page 94: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -838-

Sub ObtenerNormales(ByVal MX2(,) As Single, ByVal MY2(,) As Single, ByVal MZ2(,) As Single, ByRef Normales(,) As Single, ByVal nf As Integer) Dim Pe As Single, R As Single Dim AX As Single, Ay As Single, Az As Single, Bx As Single, By As Single, Bz As Single Dim NX As Single, Ny As Single, Nz As Single, Nx1 As Single, Ny1 As Single, Nz1 As Single Dim x1 As Single, y1 As Single, z1 As Single Dim x2 As Single, y2 As Single, z2 As Single Dim x3 As Single, y3 As Single, z3 As Single For fila = 0 To nf - 1 x1 = MX2(fila, 0) y1 = MY2(fila, 0) z1 = MZ2(fila, 0)

x2 = MX2(fila, 1) y2 = MY2(fila, 1) z2 = MZ2(fila, 1)

x3 = MX2(fila, 2) y3 = MY2(fila, 2) z3 = MZ2(fila, 2)

AX = x2 - x1 Ay = y2 - y1 Az = z2 - z1 Bx = x3 - x2 By = y3 - y2 Bz = z3 - z2 NX = Ay * Bz - Az * By Ny = AX * Bz - Az * Bx Nz = AX * By - Ay * Bx 'PRODUCTO(CRUZ) R = Math.Sqrt(NX * NX + Ny * Ny + Nz * Nz) If R > 0 Then Nx1 = NX / R Else Nx1 = 1000 End If If R > 0 Then Ny1 = Ny / R Else Ny1 = 1000 End If If R > 0 Then Nz1 = Nz / R Else Nz1 = 1000 End If Pe = Nx1 * 0 + Ny1 * 0 + Nz1 * D Normales(fila, 0) = Nx1 Normales(fila, 1) = Ny

Page 95: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -839-

Normales(fila, 2) = Nz1 Normales(fila, 3) = Pe Next End Sub

Sub TraslacionXYZ(ByVal tx As Single, ByVal ty As Single, ByVal tz As Single) Dim fila, col As Integer For fila = 0 To nf - 1 For col = 0 To nc - 1 MX2(fila, col) = MX2(fila, col) + tx MY2(fila, col) = MY2(fila, col) + ty MZ2(fila, col) = MZ2(fila, col) + tz Next Next End Sub

Sub RecuperarMatriz(ByVal nombrearchivo As String, ByVal A(,) As Single, ByVal nf As Integer, ByVal nc As Integer) srLector = New StreamReader(nombrearchivo) Dim fila As Integer, col As Integer Dim cadena As String = "" Dim subcadena As String Dim pos As Integer = 0 Dim inicio As Integer = 1 For fila = 0 To nf - 1 cadena = srLector.ReadLine() cadena = cadena & Chr(9) inicio = 1 For col = 0 To nc - 1 pos = InStr(inicio, cadena, Chr(9)) subcadena = Mid(cadena, inicio, pos - inicio) A(fila, col) = Val(subcadena) inicio = pos + 1 Next Next Console.WriteLine("Archivo leido satisfactoriamente") srLector.Close() End Sub Sub IniciarCoordenadas() VXx(0) = -tam VXy(0) = 0 VXz(0) = 0 VXx(1) = tam VXy(1) = 0 VXz(1) = 0

VYx(0) = 0 VYy(0) = -tam VYz(0) = 0 VYx(1) = 0 VYy(1) = tam VYz(1) = 0

Page 96: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -840-

VZx(0) = 0 VZy(0) = 0 VZz(0) = -tam VZx(1) = 0 VZy(1) = 0 VZz(1) = tam End SubEnd Module

CODIGO DEL FORMULARIO

Imports System.DrawingImports System.IOImports System.Drawing.Drawing2DPublic Class Form1 Dim MiFuente As New Font("Verdana", 10, FontStyle.Bold)

Private Sub Coordenadas() Dim px1, py1 As Single Dim px2, py2 As Single REM eje X px1 = (VXx(0) * D) / (D + VXz(0)) py1 = (VXy(0) * D) / (D + VXz(0)) px2 = (VXx(1) * D) / (D + VXz(1)) py2 = (VXy(1) * D) / (D + VXz(1)) Pen.Color = Color.Blue Grafico.DrawLine(Pen, Cx + px1, Cy + py1, Cx + px2, Cy + py2) Grafico.DrawString("X", MiFuente, Brushes.Blue, Cx + px2, Cy + py2)

REM eje Y

px1 = (VYx(0) * D) / (D + VYz(0)) py1 = (VYy(0) * D) / (D + VYz(0)) px2 = (VYx(1) * D) / (D + VYz(1)) py2 = (VYy(1) * D) / (D + VYz(1))

Pen.Color = Color.Red Grafico.DrawLine(Pen, Cx + px1, Cy + py1, Cx + px2, Cy + py2) Grafico.DrawString("Y", MiFuente, Brushes.Red, Cx + px2, Cy + py2) ' eje(z) px1 = (VZx(0) * D) / (D + VZz(0)) py1 = (VZy(0) * D) / (D + VZz(0)) px2 = (VZx(1) * D) / (D + VZz(1)) py2 = (VZy(1) * D) / (D + VZz(1))

Pen.Color = Color.Green Grafico.DrawLine(Pen, Cx + px1, Cy + py1, Cx + px2, Cy + py2) Grafico.DrawString("Z", MiFuente, Brushes.Green, Cx + px2, Cy + py2) End Sub

Page 97: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -841-

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Grafico = PictureBox1.CreateGraphics Pen = New Pen(Color.Red, 2) End Sub

Private Sub BtnIniciar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnIniciar.Click IniciarCoordenadas() DataGridView1.ColumnCount = 6 DataGridView1.RowCount = 5 Dim fila, col As Integer For fila = 2 To 5 DataGridView1.Columns(fila).Width = 70 Next For fila = 0 To DataGridView1.RowCount - 1 DataGridView1.Rows(fila).HeaderCell.Value = fila.ToString Next RecuperarMatriz("e:\datos1\X4x6.TXT", MX1, nf, nc) RecuperarMatriz("e:\datos1\y4x6.TXT", MY1, nf, nc) RecuperarMatriz("e:\datos1\Z4x6.TXT", MZ1, nf, nc)

CopiarMatriz(MX1, MX2, nf, nc) CopiarMatriz(MY1, MY2, nf, nc) CopiarMatriz(MZ1, MZ2, nf, nc) DataGridView1.Columns(0).HeaderText = "PARAMETROS" DataGridView1.Columns(1).HeaderText = "UNIDAD" DataGridView1.Columns(2).HeaderText = "EjeX" DataGridView1.Columns(3).HeaderText = "Eje Y" DataGridView1.Columns(4).HeaderText = "Eje Z" DataGridView1.Columns(5).HeaderText = "D o W"

DataGridView1.Rows(0).Cells(0).Value = "ROTACION EJE" DataGridView1.Rows(0).Cells(1).Value = "Grados" DataGridView1.Rows(0).Cells(2).Value = AnguloX DataGridView1.Rows(0).Cells(3).Value = AnguloY DataGridView1.Rows(0).Cells(4).Value = AnguloZ

DataGridView1.Rows(1).Cells(0).Value = "TRASLACION EJE" DataGridView1.Rows(1).Cells(1).Value = "Unidades" DataGridView1.Rows(1).Cells(2).Value = tx DataGridView1.Rows(1).Cells(3).Value = ty DataGridView1.Rows(1).Cells(4).Value = tz DataGridView1.Rows(1).Cells(5).Value = D

DataGridView1.Rows(2).Cells(0).Value = "ESCALADO EJE" DataGridView1.Rows(2).Cells(1).Value = "Unidades" DataGridView1.Rows(2).Cells(2).Value = Ex DataGridView1.Rows(2).Cells(3).Value = Ey DataGridView1.Rows(2).Cells(4).Value = Ez

DataGridView1.Rows(3).Cells(0).Value = "Modo (0,1) vel "

Page 98: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -842-

DataGridView1.Rows(3).Cells(1).Value = "Unidades" DataGridView1.Rows(3).Cells(2).Value = modo DataGridView1.Rows(3).Cells(3).Value = vel End Sub Sub graficar(ByVal MX2(,) As Single, ByVal MY2(,) As Single, ByVal MZ2(,) As Single, ByRef Normales(,) As Single, ByVal nf As Integer, ByVal nc As Integer) Dim fila, col As Integer Dim x1, y1, z1 As Single Dim px1, py1 As Single Dim cara As Integer = 0 ObtenerNormales(MX2, MY2, MZ2, Normales, nf) For fila = 0 To nf - 1 Dim Figura(nc - 2) As Point cara = fila For col = 0 To nc - 2 x1 = Cx + MX2(fila, col) y1 = Cy + MY2(fila, col) z1 = Cz + MZ2(fila, col) px1 = (x1 * D) / (D + z1) py1 = (y1 * D) / (D + z1) Figura(col).X = px1 Figura(col).Y = py1 Next If modo = 1 Then If Normales(fila, 2) > 0 Then 'solo dibuja si el normal es mayor que 0 Select Case cara Case 0 : Grafico.FillPolygon(Brushes.Green, Figura, FillMode.Alternate) Case 1 : Grafico.FillPolygon(Brushes.Red, Figura, FillMode.Alternate) Case 2 : Grafico.FillPolygon(Brushes.Blue, Figura, FillMode.Alternate) Case 3 : Grafico.FillPolygon(Brushes.Yellow, Figura, FillMode.Alternate) Case 4 : Grafico.FillPolygon(Brushes.Aqua, Figura, FillMode.Alternate) Case 5 : Grafico.FillPolygon(Brushes.Silver, Figura, FillMode.Alternate) End Select End If Else Grafico.DrawPolygon(New Pen(Color.Red, 2), Figura) End If Next fila End Sub

Private Sub BtnIniciarTodo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnIniciarTodo.Click AnguloX = CInt(DataGridView1.Rows(0).Cells(2).Value) AnguloY = CInt(DataGridView1.Rows(0).Cells(3).Value) AnguloZ = CInt(DataGridView1.Rows(0).Cells(4).Value) tx = CInt(DataGridView1.Rows(1).Cells(2).Value) ty = CInt(DataGridView1.Rows(1).Cells(3).Value) tz = CInt(DataGridView1.Rows(1).Cells(4).Value) D = CInt(DataGridView1.Rows(1).Cells(5).Value)

Ex = CSng(DataGridView1.Rows(2).Cells(2).Value) Ey = CSng(DataGridView1.Rows(2).Cells(3).Value)

Page 99: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -843-

Ez = CInt(DataGridView1.Rows(2).Cells(4).Value) modo = DataGridView1.Rows(3).Cells(2).Value vel = DataGridView1.Rows(3).Cells(3).Value CopiarMatriz(MX1, MX2, nf, nc) CopiarMatriz(MY1, MY2, nf, nc) CopiarMatriz(MZ1, MZ2, nf, nc) IniciarCoordenadas() Grafico.Clear(Color.White) RotacionXYZ(AnguloX, AnguloY, AnguloZ) RotarCoordenadasEjeX(AnguloX, AnguloY, AnguloZ) RotarCoordenadasEjey(AnguloX, AnguloY, AnguloZ) RotarCoordenadasEjeZ(AnguloX, AnguloY, AnguloZ) EscaladoXYZ(Ex, Ey, Ez) TraslacionXYZ(tx, ty, tz) Coordenadas() graficar(MX2, MY2, MZ2, Normales, nf, nc) End Sub Private Sub txtRot_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TxtRotacion.KeyDown Select Case e.KeyCode Case CType(65, Keys) ' A inverso de X If AnguloX >= -3600 Then AnguloX = AnguloX - 1 Else ' AnguloX = 360 End If

Case CType(66, Keys) ' B Inverso De Y If AnguloY >= -3600 Then AnguloY = AnguloY - 1 Else ' AnguloY = 360 End If Case CType(67, Keys) ' C traslacion Inverso de C If AnguloZ >= -3600 Then AnguloZ = AnguloZ - 1 Else ' AnguloZ = 360 End If

Case CType(88, Keys) ' ROTACION EJE X If AnguloX <= 3600 Then AnguloX = AnguloX + 1 Else ' AnguloX = 0 End If Case CType(89, Keys) ' ROTACION EJE Y If AnguloY <= 3600 Then AnguloY = AnguloY + 1 Else ' AnguloY = 0

Page 100: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -844-

End If Case CType(90, Keys) ' ROTACION EJE Z If AnguloZ <= 360 Then AnguloZ = AnguloZ + 1 Else ' AnguloZ = 0 End If End Select DataGridView1.Rows(0).Cells(2).Value = AnguloX DataGridView1.Rows(0).Cells(3).Value = AnguloY DataGridView1.Rows(0).Cells(4).Value = AnguloZ BtnIniciarTodo_Click(sender, e) TxtRotacion.Text = "" End Sub Private Sub TxtTraslacion_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtTraslacion.KeyDown Select Case e.KeyCode Case CType(65, Keys) ' A inverso de X If tx >= -limite Then tx = tx - 1 Else tx = limite End If Case CType(66, Keys) ' B Inverso De Y If ty >= -limite Then ty = ty - 1 Else ty = limite End If Case CType(67, Keys) ' C traslacion Inverso de C If tz >= -limite Then tz = tz - 1 Else tz = limite End If Case CType(68, Keys) ' variacion de D W If D >= 1 Then D = D + 1 Else D = limite * 10 End If Case CType(88, Keys) ' ROTACION EJE X If tx <= limite Then tx = tx + 1 Else tx = -limite End If Case CType(89, Keys) ' ROTACION EJE Y If ty <= limite Then ty = ty + 1

Page 101: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -845-

Else ty = -limite End If Case CType(90, Keys) ' ROTACION EJE Z If tz <= limite Then tz = tz + 1 Else tz = -limite End If Case CType(87, Keys) ' variacion de D W If D <= limite * 10 Then D = D + 1 Else D = 1 End If End Select DataGridView1.Rows(1).Cells(2).Value = tx DataGridView1.Rows(1).Cells(3).Value = ty DataGridView1.Rows(1).Cells(4).Value = tz

BtnIniciarTodo_Click(sender, e) txtTraslacion.Text = "" End Sub Private Sub TxtEscala_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtEscalado.KeyDown Select Case e.KeyCode Case CType(65, Keys) ' A inverso de X If Ex >= -limite Then Ex = Ex - 1 Else Ex = limite End If Case CType(66, Keys) ' B Inverso De Y If Ey >= -limite Then Ey = Ey - 1 Else Ey = limite End If Case CType(67, Keys) ' C traslacion Inverso de C If Ez >= -limite Then Ez = Ez - 1 Else Ez = limite End If Case CType(88, Keys) ' ROTACION EJE X If Ex <= limite Then Ex = Ex + 1 Else Ex = -limite

Page 102: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -846-

End If Case CType(89, Keys) ' ROTACION EJE Y If Ey <= limite Then Ey = Ey + 1 Else Ey = -limite End If Case CType(90, Keys) ' ROTACION EJE Z If Ez <= limite Then Ez = Ez + 1 Else Ez = -limite End If End Select DataGridView1.Rows(2).Cells(2).Value = Ex DataGridView1.Rows(2).Cells(3).Value = Ey DataGridView1.Rows(2).Cells(4).Value = Ez BtnIniciarTodo_Click(sender, e) txtTraslacion.Text = "" End Sub Private Sub BtnAuto_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnAuto.Click Timer1.Interval = vel Timer1.Enabled = True End Sub

Private Sub btnDetener_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDetener.Click Timer1.Enabled = False End Sub Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick If AnguloX <= 360 * 5 Then AnguloX = AnguloX + 1 AnguloY = AnguloY + 1 AnguloZ = AnguloZ + 1 tx = tx + 0.1 ty = ty + 0.1 tz = tz + 0.1 Ex = Ex + 0.1 Ey = Ey + 0.1 Ez = Ez + 0.1 Else AnguloX = 0 AnguloY = 0 AnguloZ = 0 tx = 0 ty = 0 tz = 0 Ex = 10 Ey = 10 Ez = 10

Page 103: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -847-

End If DataGridView1.Rows(0).Cells(2).Value = AnguloX DataGridView1.Rows(0).Cells(3).Value = AnguloY DataGridView1.Rows(0).Cells(4).Value = AnguloZ DataGridView1.Rows(1).Cells(2).Value = tx DataGridView1.Rows(1).Cells(3).Value = ty DataGridView1.Rows(1).Cells(4).Value = tz DataGridView1.Rows(2).Cells(2).Value = Ex DataGridView1.Rows(2).Cells(3).Value = Ey DataGridView1.Rows(2).Cells(4).Value = Ez BtnIniciarTodo_Click(sender, e) End Sub Private Sub BtnBorrar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnBorrar.Click Grafico.Clear(Color.Aqua) End SubEnd Class

11.14 PROGRAMACION ADN

Hoy quería presentar un tema un poco relacionado con la entrada sobre combinatoria algorítmica pero más relacionado con lo que considero que va a ser el futuro de la computación y (¿por qué no?) un poco de biología. Además aprovecho para adelantarme a wikipedia que casi no tiene información al respecto de esto.Empecemos por la parte biológica. El ADN (DNA en inglés, ácido desoxirribonucleico) es básicamente la información de todo lo que forma un ser vivo. Cada célula tiene nuestro ADN y éste es quién dicta qué se forma y cuando y de qué manera. Realmente lo que nos interesa de esto es que es una doble cadena de nucleótidos.

Page 104: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -848-

Ejemplo de cadena

La primer parte que nos interesa de todo esto es que en esta doble cadena las dos partes están pegadas entre sí por una regla muy sencilla. Si de un lado hay una Adenina, del otro hay una Timina y si de un lado hay una Citosina, del otro hay una Guanina, por lo que si las escribimos como lista, siempre se ve del siguiente estilo.ATGTTAACGGTG…TACAATTGCCAC…

Resulta que uno de los problemas con que TODA la información de cómo estamos formados esté ahí es que si se modifica en una célula, esa célula puede empezar a funcionar diferente, a producir otras cosas. Eso es justamente lo que hace un virus. Un virus no tiene la capacidad de reproducirse solo, pero puede llegar a una célula, inyectar su ADN y hacer que la célula empiece a producir copias del virus (adentro de ella) hasta que explota y los virus nuevos van infectando células nuevas hasta matar al organismo. Sin embargo, como este es un problema que lleva suficiente tiempo, las células han desarrollado medios para evitar esto (hasta cierto punto). Lo que tienen son una enzimas llamadas enzimas de corte, que van leyendo una parte del ADN y si encuentra cierta secuencia (ajena al ADN usual, como lo que pondría un virus) cortan el ADN en ese momento.

Programa que evalúa si es una cadena adn lo corta y lo replica

Module Module2 Function Replicar(cadena As String) As String Dim fila As Integer Dim letra1 As String = "A" Dim letra2 As String = "A" Dim cadena2 As String = "" For fila = 0 To Len(cadena) - 1 letra1 = cadena(fila) Select Case letra1 Case "A" : letra2 = "T" Case "T" : letra2 = "A" Case "C" : letra2 = "G" Case "G" : letra2 = "C" End Select cadena2 = cadena2 + letra1 + letra2 Next Return cadena2

Page 105: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -849-

End Function Function EvaluarCadena(ByVal adn As String) As Boolean Dim largo As Integer, col As Integer Dim valor As Boolean = True Dim letra As Char, letra1 As Char largo = Len(adn) If largo Mod 2 <> 0 Then valor = False Else For col = 0 To largo - 2 Step 2 letra = adn(col) letra1 = adn(col + 1) Select Case letra Case "A" : If letra1 <> "T" Then valor = False Exit For End If Case "T" : If letra1 <> "A" Then valor = False Exit For End If Case "C" : If letra1 <> "G" Then valor = False Exit For End If Case "G" : If letra1 <> "C" Then valor = False Exit For End If Case Else valor = False Exit For End Select Next End If EvaluarCadena = valor End Function Sub dividir(adn As String, ByRef adn1 As String, ByRef adn2 As String) Dim col As Integer adn1 = "" : adn2 = "" For col = 0 To Len(adn) - 1 If (col Mod 2 = 0) Then adn1 = adn1 + adn(col) Else adn2 = adn2 + adn(col) End If Next End SubEnd Module

Module Module1 Sub Main()

Page 106: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -850-

Dim resultado As Boolean Dim adn As String = "ATCGTA", adn1 As String = "", adn2 As String = "" Console.WriteLine(" Ingrese secuencia") adn1 = Console.ReadLine Console.WriteLine("ADN Original {0}", adn) resultado = EvaluarCadena(adn1) If resultado = True Then Console.WriteLine("secuencia correcta") Else Console.WriteLine("secuencia INCORRECTA") End If If resultado = True Then dividir(adn, adn1, adn2) Console.WriteLine("CADENAS DIVIDIDAS") Console.WriteLine("Cadena 1 {0}", adn1) Console.WriteLine("Cadena 2 {0}", adn2) Console.WriteLine("Cadenas Replicada") Console.WriteLine("Cadena 1 {0}", Replicar(adn1)) Console.WriteLine("Ccadena 2 {0}", Replicar(adn2)) End If Console.ReadLine() End SubEnd Module

Las cadenas son

Cadena1Cadena izquierda I

Cadena2 Cadena derecha D

I I D ICadena1R = Replicar(Cadena1, 1)

Cadena1R = Replicar(Cadena2,1)

I I D DCadena1R = Replicar(Cadena1, 1)

Cadena1R = Replicar(Cadena2,2)

I D D ICadena1R = Replicar(Cadena1, 2)

Cadena1R = Replicar(Cadena2,1)

I D D DCadena1R = Replicar(Cadena1, 2)

Cadena1R = Replicar(Cadena2,2)

Prueba con opción 2

Page 107: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -851-

Pruebe con opción 2, 3 y 4

CODIGO DEL MODULO 2

Module Module2 Public ADN As String Public Cadena As String Public Cadena1, Cadena2 As String Public Cadena1R, Cadena2R As String Public Nrepli As Integer = 4 Public k As Integer = 0 Public Const maxfilas As Integer = 200 Public Const maxcol As Integer = 50 Public CadR(maxfilas) As String Public A(maxfilas, maxcol) As String Public nf As Integer Public nc As Integer Sub CadenasMatriz(CadR() As String, filaini As Integer, nf As Integer, nrocol As Integer) Dim fila As Integer For fila = filaini To nf - 1 A(fila, nrocol) = CadR(fila) Next End Sub Sub ReplicarADN(cadena As String, cont As Integer, lim As Integer) Console.WriteLine("etapa {0} ", cont) dividir(cadena, Cadena1, Cadena2) Cadena1R = Replicar(Cadena1, 2) ' izquierdo Cadena2R = Replicar(Cadena2, 1) ' derecho

k = k + 1 CadR(k) = Cadena1R k = k + 1 CadR(k) = Cadena2R Console.WriteLine("cadena replicada1 IZ {0} ", Cadena1R) Console.WriteLine("cadena replicada2 DER {0} ", Cadena2R) If cont < lim Then

Page 108: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -852-

ReplicarADN(Cadena1R, cont + 1, lim) ReplicarADN(Cadena2R, cont + 1, lim) End If End Sub Function Replicar(cadena As String, tipo As Integer) As String Dim fila As Integer Dim letra1 As String = "A" Dim letra2 As String = "B" Dim cadena2 As String = "" For fila = 0 To Len(cadena) - 1 letra1 = cadena(fila) Select Case letra1 Case "A" : letra2 = "T" Case "T" : letra2 = "A" Case "C" : letra2 = "G" Case "G" : letra2 = "C" End Select Select Case tipo Case 1 : cadena2 = cadena2 + letra2 + letra1 ' izquierdo Case 2 : cadena2 = cadena2 + letra1 + letra2 ' derecho End Select Next Return cadena2 End Function Sub ImprimirCadenas(cadena() As String, nf As String) Dim fila As Integer For fila = 0 To nf + 1 Console.WriteLine("{0} {1} ", fila, cadena(fila)) Next End Sub Sub dividir(adn As String, ByRef adn1 As String, ByRef adn2 As String) Dim col As Integer adn1 = "" : adn2 = "" For col = 0 To Len(adn) - 1 If (col Mod 2 = 0) Then adn1 = adn1 + adn(col) Else adn2 = adn2 + adn(col) End If Next End Sub Sub IniciarMatriz(A(,) As String, nf As Integer, nc As Integer) Dim fila, col As Integer For fila = 0 To nf - 1 For col = 0 To nc - 1 ' A(fila, col) = Str(fila) + ":" + Str(col) A(fila, col) = "" Next Next End Sub Sub ImprimirMatriz(A(,) As String, nf As Integer, nc As Integer) Dim fila, col As Integer

Page 109: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -853-

For fila = 0 To nf - 1 For col = 0 To nc - 1 Console.Write(" {0} {1} ", A(fila, col), vbTab) Next Console.WriteLine() Next End Sub

Function EvaluarCadena(ByVal adn As String) As Boolean Dim largo As Integer, col As Integer Dim valor As Boolean = True Dim letra As Char, letra1 As Char largo = Len(adn) If largo Mod 2 <> 0 Then valor = False Else For col = 0 To largo - 2 Step 2 letra = adn(col) letra1 = adn(col + 1) Select Case letra Case "A" : If letra1 <> "T" Then valor = False Exit For End If Case "T" : If letra1 <> "A" Then valor = False Exit For End If Case "C" : If letra1 <> "G" Then valor = False Exit For End If Case "G" : If letra1 <> "C" Then valor = False Exit For End If Case Else valor = False Exit For End Select Next End If EvaluarCadena = valor End FunctionEnd Module

CODIGO DEL MODULO 1

Module Module1 Sub Main() Dim Vanterior As Integer Dim fila As Integer

Page 110: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -854-

ADN = "ATCG" Dim resultado As Boolean resultado = EvaluarCadena(ADN) Console.WriteLine("cadena original {0}", ADN) Cadena = ADN IniciarMatriz(A, maxfilas, maxcol) Vanterior = 1 A(0, 0) = Cadena fila = 0 For fila = 0 To Nrepli - 1 Console.WriteLine("*********repli {0} ", fila) k = 0 CadR(0) = Cadena ReplicarADN(Cadena, 0, fila) ImprimirCadenas(CadR, k) CadenasMatriz(CadR, Vanterior, k + 1, fila + 1) Vanterior = k + 1 Next nc = Nrepli + 1 nf = k + 1 Console.WriteLine("la Matriz generada es ") ImprimirMatriz(A, nf, nc) Console.ReadLine() End SubEnd Module

Secuencia ADNRealizar la siguiente secuenciaSecuencia

Origen Produce

1 A H2 B M

3 HMsecuencia AB aleatoria de acuerdo a una tas

4 MHSecuencia AB aletoria a la mitad de la tasa

5 H X6 M Y7 X Muere8 Y Muere

Page 111: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -855-

Module Module1 Public cadena As String Dim ng As Integer = 20 Dim nletras As Integer = 8 Dim tnat As Integer = 10 Sub Main() Randomize() Dim fila As Integer cadena = "ABBA" cadena = generar(nletras) cadena = cadena + " " Console.WriteLine("Cadena Original es {0} ", cadena) For fila = 1 To ng cadena = reemplazar(cadena) + " " Console.WriteLine(" fila {0,2} cadena es {1} ", fila, cadena) Next Console.ReadLine() End Sub Function reemplazar(cadena As String) As String Dim pos As Integer Dim r As Integer Dim Cadtemporal As String = "" pos = 0 Do While (pos < Len(cadena) - 1) If cadena(pos) = "H" And cadena(pos + 1) = "M" Then r = Int(Rnd() * tnat) Cadtemporal = Cadtemporal + generarAB(r) pos = pos + 2 Else If cadena(pos) = "M" And cadena(pos + 1) = "H" Then r = Int(Rnd() * tnat / 2) Cadtemporal = Cadtemporal + generarAB(r) pos = pos + 2

Else

Page 112: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -856-

If cadena(pos) = "A" Then Cadtemporal = Cadtemporal + "H" pos = pos + 1 Else If cadena(pos) = "B" Then Cadtemporal = Cadtemporal + "M" pos = pos + 1 Else If cadena(pos) = "H" Then Cadtemporal = Cadtemporal + "X" pos = pos + 1 Else If cadena(pos) = "M" Then Cadtemporal = Cadtemporal + "Y" pos = pos + 1 Else If cadena(pos) = "X" Then Cadtemporal = Cadtemporal + "" pos = pos + 1

Else If cadena(pos) = "Y" Then Cadtemporal = Cadtemporal + "" pos = pos + 1 Else Cadtemporal = Cadtemporal + cadena(pos) pos = pos + 1 End If End If End If End If End If End If End If End If Loop Return Cadtemporal End Function Function generar(ne As Integer) As String Dim fila As Integer Dim r As Integer Dim cadena As String = "" For fila = 0 To ne r = 1 + Int(Rnd() * 6) Select Case r Case 1 : cadena = cadena + "A" Case 2 : cadena = cadena + "B" Case 3 : cadena = cadena + "H" Case 4 : cadena = cadena + "M" Case 5 : cadena = cadena + "X" Case 6 : cadena = cadena + "Y"

Page 113: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -857-

End Select Next Return cadena End Function Function generarAB(ne As Integer) As String Dim fila As Integer Dim r As Integer Dim cadena As String = "" For fila = 0 To ne - 1 r = 1 + Int(Rnd() * 100) If r < 50 Then cadena = cadena + "A" Else cadena = cadena + "B" End If Next Return cadena End FunctionEnd Module

El mismo problema en modo formulario

Module Module1 Public Const maxfilas As Integer = 1000 Public cadenas(maxfilas) As String Public grafico As Graphics Public cadena As String Public nletras As Integer = 20 Public tnat As Integer = 10 Public ngen As Integer = 50 Function reemplazar(cadena As String) As String Dim pos As Integer Dim r As Integer Dim Cadtemporal As String = "" pos = 0 Do While (pos < Len(cadena) - 1) If cadena(pos) = "H" And cadena(pos + 1) = "M" Then

Page 114: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -858-

r = Int(Rnd() * tnat) Cadtemporal = Cadtemporal + "X" + generarAB(r) + "Y" pos = pos + 2 Else If cadena(pos) = "M" And cadena(pos + 1) = "H" Then r = Int(Rnd() * tnat * 0.5) Cadtemporal = Cadtemporal + "Y" + generarAB(r) + "X" pos = pos + 2 Else If cadena(pos) = "A" Then Cadtemporal = Cadtemporal + "H" pos = pos + 1 Else If cadena(pos) = "B" Then Cadtemporal = Cadtemporal + "M" pos = pos + 1 Else If cadena(pos) = "H" Then Cadtemporal = Cadtemporal + "X" pos = pos + 1 Else If cadena(pos) = "M" Then Cadtemporal = Cadtemporal + "Y" pos = pos + 1 Else If cadena(pos) = "X" Then Cadtemporal = Cadtemporal + "" pos = pos + 1

Else If cadena(pos) = "Y" Then Cadtemporal = Cadtemporal + "" pos = pos + 1 Else

Cadtemporal = Cadtemporal + cadena(pos) pos = pos + 1 End If End If End If End If End If End If End If End If Loop Return Cadtemporal End Function Function generar(ne As Integer) As String Dim fila As Integer Dim r As Integer Dim cadena As String = ""

Page 115: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -859-

For fila = 0 To ne r = 1 + Int(Rnd() * 6) Select Case r Case 1 : cadena = cadena + "A" Case 2 : cadena = cadena + "B" Case 3 : cadena = cadena + "H" Case 4 : cadena = cadena + "M" Case 5 : cadena = cadena + "X" Case 6 : cadena = cadena + "Y" End Select Next Return cadena End Function Function generarAB(ne As Integer) As String Dim fila As Integer Dim r As Integer Dim cadena As String = "" For fila = 0 To ne - 1 r = 1 + Int(Rnd() * 100) If r < 50 Then cadena = cadena + "A" Else cadena = cadena + "B" End If Next Return cadena End FunctionEnd Module

CODIGO DEL FORMULARIO

Public Class Form1 Dim ex As Integer = 10 Dim ey As Integer = 10 Dim cx As Integer = 5 Dim cy As Integer = 5 Private Sub ProcesarCadena(sender As Object, e As EventArgs) Handles BtnProcesar.Click grafico.Clear(Color.Black) ListBox1.Items.Clear() Randomize() Dim fila As Integer cadena = "ABBA" ' cadena = generar(nletras) cadena = TextBox1.Text ' TextBox1.Text = cadena cadena = cadena + " " ListBox1.Items.Add("Cadena Original es " & cadena) cadenas(0) = cadena For fila = 1 To ngen cadena = reemplazar(cadena) + " "

Page 116: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -860-

ListBox1.Items.Add(fila & "Cadena " & cadena) cadenas(fila) = cadena Next BtnDibujar_Click(sender, e) End Sub

Sub ImprimirCadenas(cadena() As String, nf As String) Dim fila As Integer For fila = 0 To nf ListBox1.Items.Add(cadena(fila)) Next End Sub Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load grafico = PictureBox1.CreateGraphics End Sub Sub ImprimirCadenaGrafico(cadena As String, nrofila As Integer) Dim col As Integer Dim letra As String For col = 0 To Len(cadena) - 1 letra = cadena(col) Select Case letra Case "A" grafico.FillRectangle(Brushes.Green, cx + ex * col, cy + ey * nrofila, ex, ey) Case "B" grafico.FillRectangle(Brushes.Yellow, cx + ex * col, cy + ey * nrofila, ex, ey) Case "H" grafico.FillRectangle(Brushes.Blue, cx + ex * col, cy + ey * nrofila, ex, ey) Case "M" grafico.FillRectangle(Brushes.Red, cx + ex * col, cy + ey * nrofila, ex, ey) Case "X" grafico.FillRectangle(Brushes.Gray, cx + ex * col, cy + ey * nrofila, ex, ey) Case "Y" grafico.FillRectangle(Brushes.Violet, cx + ex * col, cy + ey * nrofila, ex, ey) End Select Next End Sub

Private Sub BtnDibujar_Click(sender As Object, e As EventArgs) Handles BtnDibujar.Click Dim fila As Integer fila = 1 For fila = 0 To ngen ImprimirCadenaGrafico(cadenas(fila), fila) Next End Sub Private Sub BtnBorrar_Click(sender As Object, e As EventArgs) Handles BtnBorrar.Click ' ListBox1.Items.Clear() grafico.Clear(Color.Black) End SubEnd Class

Page 117: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -861-

La secuencia AB genera AAB o ABB la secuencia BA genera AB o BA , AAA genera AA BBB genera BB

La secuencia AB genera AAB o ABB la secuencia BA genera lA o B

Pruebe otras secuencias

11.15 PROBLEMA DE CONDUCCION DE VEHICULOS

Page 118: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -862-

CODIGO DEL MODULO

Imports System.IOModule Module2 Public velocidad As Integer = 100 Public dir As Integer = 1 Public camino As Integer = 0 Public valor As Integer = 0 Public x1 As Integer = 0 Public y1 As Integer = 0 Public pmx, pmy As Integer Public ancho1 As Integer = 20 '90 Public alto1 As Integer = 10 '90 Public AnchoTotal = 40 Public AltoTotal = 20 Public ex1 As Single = 32, ey1 As Single = 32 Public ex2 As Single = 4, ey2 As Single = 4 Public vel As Integer = 100 Public Posx As Integer = 11 ' col de partida Public Posy As Integer = 13 ' fila de partida ' *************************** Public Const maxfilas As Integer = 42, maxcol As Integer = 42 '700 ' 590 Public A(maxfilas, maxcol) As Integer Public B(maxfilas, maxcol) As Integer

Sub CopiarMatrices(A(,) As Integer, ByRef B(,) As Integer, Cx As Integer, Cy As Integer, Ancho As Integer, alto As Integer) Dim fila, col As Integer For fila = 0 To alto - 1 For col = 0 To Ancho - 1 B(fila, col) = A(Cy + fila, Cx + col) Next Next End Sub

Page 119: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -863-

Sub RecuperarMatriz(ByVal nombrearchivo As String, ByRef A(,) As Integer, ByRef nc As Integer, ByVal nf As Integer) Dim srLector As StreamReader srLector = New StreamReader(nombrearchivo) Dim fila As Integer = 0, col As Integer Dim cadena As String = "" Dim subcadena As String Dim pos As Integer = 0 Dim inicio As Integer = 1 cadena = srLector.ReadLine() Do While Not (cadena Is Nothing) cadena = cadena & Chr(9) inicio = 1 For col = 0 To nc - 1 pos = InStr(inicio, cadena, Chr(9)) subcadena = Mid(cadena, inicio, pos - inicio) A(fila, col) = subcadena inicio = pos + 1 Next fila = fila + 1 cadena = srLector.ReadLine() Loop nf = fila Console.WriteLine("Archivo {0} leido satisfactoriamente", nombrearchivo) srLector.Close() End SubEnd Module

CODIGO DEL FORMULARIO

Option Explicit OnImports System.IOPublic Class Form1 Dim Pen1 As Pen Dim Grafico1 As Graphics Dim brocha1 As SolidBrush Dim Pen2 As Pen Dim Grafico2 As Graphics Dim brocha2 As SolidBrush Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load PictureBox1.Left = 0 PictureBox1.Top = 0 PictureBox1.Width = 800 PictureBox1.Height = 350 Grafico1 = PictureBox1.CreateGraphics Pen1 = New Pen(Color.Red, 2) brocha1 = New SolidBrush(Color.FromArgb(255, 255, 0)) Grafico2 = PictureBox2.CreateGraphics Pen2 = New Pen(Color.Red, 1) brocha2 = New SolidBrush(Color.FromArgb(255, 255, 0)) txtPx.Text = Posx txtPy.Text = Posy

Page 120: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -864-

valor = A(Posy, Posx) txtValor.Text = valor txtVel.Text = velocidad End Sub

Sub MostrarMatriz1(A(,) As Integer, Cx As Integer, Cy As Integer, nc As Integer, ByVal nf As Integer) For fila = 0 To nf - 1 For col = 0 To nc - 1 If A(fila, col) = 1 Then brocha1.Color = Color.Black Else brocha1.Color = Color.Green End If Grafico1.FillRectangle(brocha1, Cx + col * ex1, Cy + fila * ey1, ex1, ey1) Grafico1.DrawRectangle(Pen1, Cx + col * ex1, Cy + fila * ey1, ex1, ey1) Next Next End Sub Sub MostrarMatriz2(A(,) As Integer, Cx As Integer, Cy As Integer, nc As Integer, ByVal nf As Integer) For fila = 0 To nf - 1 For col = 0 To nc - 1 If A(fila, col) = 1 Then brocha2.Color = Color.Black Else brocha2.Color = Color.Green End If Grafico2.FillRectangle(brocha2, Cx + col * ex2, Cy + fila * ey2, ex2, ey2) Next Next End Sub

Private Sub BtnBorrar_Click(sender As Object, e As EventArgs) Handles BtnBorrar.Click Grafico1.Clear(Color.Black) End Sub Private Sub BtnIniciar_Click(sender As Object, e As EventArgs) Handles BtnIniciar.Click Dim NombreArchivo As String = "E:\datos1\circuito40x20.txt" RecuperarMatriz(NombreArchivo, A, AnchoTotal, AltoTotal) CopiarMatrices(A, B, 0, 0, ancho1, alto1) x1 = 0 y1 = 0 pmx = ancho1 / 2.0 pmy = alto1 / 2.0 txtPx.Text = Posx txtPy.Text = Posy dir = 1 BtnPosicionar_Click(sender, e) End Sub

Page 121: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -865-

Private Sub Manual_Click(sender As Object, e As EventArgs) Handles BtnManual.Click Select Case dir Case 1 ' a la derecha If A(Posy, Posx + 1) = camino Then Posx = Posx + 1 dir = 1 Else If A(Posy - 1, Posx) = camino Then Posy = Posy - 1 dir = 2 Else If A(Posy + 1, Posx) = camino Then Posy = Posy + 1 dir = 4 Else If A(Posy, Posx - 1) = camino Then Posx = Posx - 1 dir = 3 End If End If End If End If Case 2 If A(Posy - 1, Posx) = camino Then Posy = Posy - 1 dir = 2 Else If A(Posy, Posx + 1) = camino Then Posx = Posx + 1 dir = 1 Else If A(Posy, Posx - 1) = camino Then Posx = Posx - 1 dir = 3 Else If A(Posy - 1, Posx) = camino Then Posy = Posx + 1 dir = 4 End If End If End If End If Case 3 If A(Posy, Posx - 1) = camino Then Posx = Posx - 1 dir = 3 Else If A(Posy - 1, Posx) = camino Then Posy = Posy - 1 dir = 1 ElseIf A(Posy + 1, Posx) = camino Then

Page 122: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -866-

Posy = Posy + 1 dir = 4 Else If A(Posy, Posx + 1) = camino Then Posy = Posx + 1 dir = 1 End If End If End If Case 4 If A(Posy + 1, Posx) = camino Then Posy = Posy + 1 dir = 4 Else If A(Posy, Posx + 1) = camino Then Posx = Posx + 1 dir = 1 ElseIf A(Posy, Posx - 1) = camino Then Posx = Posx - 1 dir = 3 Else If A(Posy - 1, Posx) = camino Then Posy = Posx - 1 dir = 2 End If End If End If End Select txtPx.Text = Posx txtPy.Text = Posy BtnPosicionar_Click(sender, e) ' 'System.Threading.Thread.Sleep(20) ' 1 milisegundo End Sub

Private Sub btnMover_Click(sender As Object, e As EventArgs) Handles btnMover.Click vel = txtVel.Text Timer1.Interval = vel Timer1.Enabled = True End Sub Private Sub btnParar_Click(sender As Object, e As EventArgs) Handles btnParar.Click Timer1.Enabled = False End Sub

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick Manual_Click(sender, e) End Sub Private Sub txtXY_KeyDown(sender As Object, e As KeyEventArgs) Handles txtXY.KeyDown BtnBorrar_Click(sender, e) Select Case e.KeyCode

Page 123: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -867-

Case 65 ' A If Posx > pmx Then Posx = Posx - 1 End If Case 66 ' B If Posy > pmy Then Posy = Posy - 1 End If Case 88 ' trslacion eeje x If Posx <= AnchoTotal - pmx Then Posx = Posx + 1 End If Case 89 ' ROTACION EJE Y If Posy < AltoTotal - pmy Then Posy = Posy + 1 End If End Select txtPx.Text = Posx txtPy.Text = Posy txtXY.Text = "" BtnPosicionar_Click(sender, e) End Sub

Private Sub Borrar2_Click(sender As Object, e As EventArgs) Handles BtnBorrar2.Click Grafico2.Clear(Color.Black) End Sub Private Sub BtnPosicionar_Click(sender As Object, e As EventArgs) Handles BtnPosicionar.Click Posx = txtPx.Text Posy = txtPy.Text valor = A(Posy, Posx) txtValor.Text = valor If Posx - pmx >= 0 And Posx + pmx <= AnchoTotal And Posy - pmy >= 0 And Posy + pmy <= AltoTotal Then x1 = Posx - ancho1 / 2 y1 = Posy - alto1 / 2 Else MsgBox("valores erroneos") Exit Sub End If Grafico1.Clear(Color.Black) CopiarMatrices(A, B, x1, y1, ancho1, alto1) MostrarMatriz1(B, x1, y1, ancho1, alto1) MostrarMatriz2(A, 0, 0, AnchoTotal, AltoTotal) Grafico2.FillRectangle(Brushes.Yellow, Posx * ex2, Posy * ey2, ex2 * 2, ey2 * 2) Grafico1.FillRectangle(Brushes.Yellow, x1 + pmx * ex1, y1 + pmy * ey1, ex1, ey1) Grafico2.DrawRectangle(Pen2, x1 * ex2, y1 * ey2, ancho1 * ex2, alto1 * ey2) txtValor.Text = valor If (valor <> 0) Then MsgBox("erroneo maneje bien") End Sub

Page 124: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -868-

End Class

11.16 PROBLEMA DE CONDUCCION DE VEHICULOS USADO BITMAPS

CODIGO DEL MODULO

Module Module1 Public nultimos As Integer = 0 Public ultimos As Integer = 100 Public paso As Integer = 20 Public menor As Integer Public Const largo As Integer = 4000 Public li As Integer = 0 Public alcance As Integer = 10 Public Cont As Integer = 0 Public contMalos As Integer = 0 Public Nvecinos As Integer = 0 Public Ndir(4) As Integer ' vector de direcciones Public RutaX(largo) As Integer ' vector de direcciones Public RutaY(largo) As Integer ' vector de direcciones Public RutaXMala(largo) As Integer ' vector de direcciones Public RutaYMala(largo) As Integer ' vector de direcciones Public Dirfac(4) As Integer ' 0 no ses factible Public Sdir(4) As Integer ' vector de suma de direccionesA Public limiteColor As Integer = 50 Public PosXAuto As Integer Public PosYAuto As Integer Public Ex1 As Integer = 1 Public Ey1 As Integer = 1 Public Ex As Integer = 10 Public Ey As Integer = 10 Public AutoX(1) As Integer Public AutoY(1) As Integer Public AnchoImagen As Integer Public AltoImagen As Integer Public BrochaSólida As SolidBrush

Page 125: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -869-

Public Color1 As Color Public tam As Integer = 20 Public camino As Integer = 0 Public dir As Integer = 1 Public velocidad As Integer = 10 Public Grafico1 As Graphics Public grafico2 As Graphics Public Grafico3 As Graphics Public imagen As Bitmap Public fuente1 As RectangleF Public destino1 As RectangleF Public fuente2 As RectangleF Public destino2 As RectangleF Public fuente3 As RectangleF Public destino3 As RectangleF Public rojo, verde, azul As Integer Sub IniciarVectores() Dim col As Integer For col = 0 To 3 Ndir(col) = col + 1 Sdir(col) = 0 Next For col = 0 To largo RutaX(0) = 0 RutaY(0) = 0 Next End Sub Function buscar(ByVal Cx As Integer, ByVal cy As Integer, ByVal li As Integer, ByVal ls As Integer) As Boolean Dim fila As Integer Dim encontrado As Boolean = False For fila = li To ls If Cx = RutaX(fila) And cy = RutaY(fila) Then encontrado = True Exit For End If Next Return encontrado End Function Function Contavecinos(ByVal Cx As Integer, ByVal cy As Integer, ByVal li As Integer, ByVal ls As Integer) Dim fila, col As Integer, nvecinos = 0 For fila = cy - paso To cy + paso For col = Cx - paso To Cx + paso If buscar(col, fila, li, ls) = True Then nvecinos = nvecinos + 1 Next Next Return nvecinos End FunctionEnd Module

Page 126: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -870-

CODIGO DEL FORMULARIO

Imports System.DrawingPublic Class Form1 Function ProbarRuta(ByVal Cx As Integer, ByVal Cy As Integer, ByVal AutoX() As Integer, ByVal Autoy() As Integer) As Boolean Dim f1 As Boolean = True Dim f2 As Boolean = True Dim f3 As Boolean = True Dim f4 As Boolean = True '' probar si esta en la colas If (Cx = AutoX(1) And Cy = Autoy(1)) Then f1 = False ' probar si estan en los ultimos For fila = li To Cont + 1 If (Cx = RutaX(fila) And Cy = RutaY(fila)) Then f2 = False Exit For End If Next Color1 = imagen.GetPixel(Cx, Cy) azul = Color1.B If (azul >= limiteColor) Then f3 = False 'tiene que se todos los poner colores con rojo ' probar si la ruta ha sido y habia retrocidido For fila = 0 To contMalos If (Cx = RutaXMala(fila) And Cy = RutaYMala(fila)) Then f4 = False Exit For End If Next If f1 = True And f2 = True And f3 = True And f4 = True Then Return True Else Return False End If End Function Function ProbarRutaAlterna(ByVal Cx As Integer, ByVal Cy As Integer, ByVal AutoX() As Integer, ByVal Autoy() As Integer) As Boolean Dim fila, col As Integer Dim f1 As Boolean = True Dim f2 As Boolean = True Dim f3 As Boolean = True Dim f4 As Boolean = True Dim f5 As Boolean = True Dim f6 As Boolean = True ' s i los 10 no deben estar mas de 5 'Dim nvecinos As Integer = 0 If (Cx = AutoX(1) And Cy = Autoy(1)) Then f4 = False ' probar si esta en la colas If Cont - ultimos > 0 Then li = Cont - ultimos Else

Page 127: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -871-

li = 0 End If For fila = li To Cont If (Cx = RutaX(fila) And Cy = RutaY(fila)) Then f1 = False Exit For End If Next

'probar si no es camino Color1 = imagen.GetPixel(Cx, Cy) azul = Color1.B If (azul >= limiteColor) Then f2 = False 'tiene que se todos los colores poner colores con rojo ' probar si al menos tiene un vecino Nvecinos = 0 ' saber nro de vecinos For fila = Cy - 1 To Cy + 1 For col = Cx - 1 To Cx + 1 If fila = col Then Continue For Color1 = imagen.GetPixel(col, fila) If (Color1.B > limiteColor) Then Nvecinos = Nvecinos + 1 Next Next If (Nvecinos <= 0) Then f3 = False For fila = 0 To contMalos If (Cx = RutaXMala(fila) And Cy = RutaYMala(fila)) Then f5 = False Exit For End If Next nultimos = 0 If Cont > ultimos Then For fila = Cont - ultimos To Cont If (Cx = RutaX(fila) And Cy = RutaY(fila)) Then nultimos = nultimos + 1 Next If nultimos > ultimos / 2 Then f6 = False End If

If f1 = True And f2 = True And f3 = True And f4 = True And f5 = True And f6 = True Then Return True Else Return False End If End Function Sub traslados() Dim valor1 As Integer = tam / 2 ' se traslada el auto grafico2.DrawRectangle(Pens.Yellow, AutoX(0), AutoY(0), tam, tam) ' gragficara todo el rastro txtPosX.Text = AutoX(0)

Page 128: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -872-

TxtPosy.Text = AutoY(0) fuente3.Width = tam * 2 fuente3.Height = tam * 2 fuente3.X = AutoX(0) - tam fuente3.Y = AutoY(0) - tam destino3.Width = tam * 2 * Ex destino3.Height = tam * 2 * Ey destino3.X = 0 destino3.Y = 0 Grafico3.DrawImage(imagen, destino3, fuente3, GraphicsUnit.Pixel) Grafico1.DrawRectangle(Pens.Blue, AutoX(0) - tam, AutoY(0) - tam, tam * 2, tam * 2) Grafico1.DrawRectangle(Pens.Blue, AutoX(0) - 1, AutoY(0) - 1, 2, 2) grafico2.DrawRectangle(Pens.Blue, AutoX(0) - tam, AutoY(0) - tam, tam * 2, tam * 2) valor1 = Ex / 2 Grafico3.FillRectangle(Brushes.Yellow, tam * Ex - valor1, tam * Ey - valor1, Ex, Ey) End Sub

Private Sub BtnBorrar_Click(ByVal sender As Object, ByVal e As EventArgs) Handles BtnBorrar.Click Grafico1.Clear(Color.White) grafico2.Clear(Color.Black) Grafico3.Clear(Color.Black) End Sub

Private Sub btnMaps_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnMaps.Click fuente1.Width = AnchoImagen fuente1.Height = AltoImagen fuente1.X = 0 fuente1.Y = 0 destino1.Width = AnchoImagen destino1.Height = AltoImagen destino1.X = 0 destino1.Y = 0 fuente2.Width = AnchoImagen fuente2.Height = AltoImagen fuente2.X = 0 fuente2.Y = 0 destino2.Width = AnchoImagen destino2.Height = AltoImagen destino2.X = 0 destino2.Y = 0 Grafico1.DrawImage(imagen, destino1, fuente1, GraphicsUnit.Pixel) grafico2.DrawImage(imagen, destino2, fuente2, GraphicsUnit.Pixel) End Sub

Private Sub BtnIniciar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnIniciar.Click Dim fila As Integer IniciarVectores() Cont = ultimos li = 0

Page 129: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -873-

PosXAuto = 41 PosYAuto = 210 AutoX(0) = PosXAuto AutoY(0) = PosYAuto AutoX(1) = PosXAuto AutoY(1) = PosYAuto + 1 ' inciciar lo vectores de recorrido con los primeros 20 For fila = li To Cont - 1 RutaX(fila) = AutoX(0) RutaY(fila) = AutoY(0) + Cont - fila - 1 Next BtnObtColor_Click(sender, e) traslados() End Sub

Private Sub BtnObtColor_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnObtColor.Click ' obtener color Color1 = imagen.GetPixel(PosXAuto, PosYAuto) rojo = Color1.R verde = Color1.G azul = Color1.B ListBox1.Items.Add(" rojo " & rojo) ListBox1.Items.Add(" verde " & verde) ListBox1.Items.Add(" azul " & azul) End Sub

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Grafico1 = PicFuente.CreateGraphics grafico2 = PicDestino.CreateGraphics Grafico3 = PicZoom.CreateGraphics imagen = New Bitmap("E:\datos1\F1HUNGRIA320X310.BMP") AnchoImagen = imagen.Width AltoImagen = imagen.Height Timer1.Enabled = False End Sub

Private Sub PicFuente_MouseMove(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PicFuente.MouseMove Me.Text = " X= " & e.X & " Y =" & e.Y End Sub Private Sub PicFuente_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PicFuente.MouseDown ' se traslada el auto AutoX(0) = e.X AutoY(0) = e.Y AutoX(1) = e.X AutoY(1) = e.Y + 1 RutaX(0) = AutoX(1) RutaX(0) = AutoX(1) txtPosX.Text = AutoX(0)

Page 130: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -874-

TxtPosy.Text = AutoY(0) PosXAuto = AutoX(0) PosYAuto = AutoY(0) BtnObtColor_Click(sender, e) traslados() End Sub Private Sub txtMover_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtMover.KeyDown ListBox1.Items.Clear() Select Case e.KeyCode Case 65 ' inversa X If PosXAuto > 0 Then PosXAuto = PosXAuto - 1 End If Case 66 ' Inversa Y If PosYAuto > 0 Then PosYAuto = PosYAuto - 1 End If Case 88 ' ROTACION EJE X If PosXAuto < AnchoImagen Then PosXAuto = PosXAuto + 1 End If Case 89 ' If PosYAuto < AltoImagen Then PosYAuto = PosYAuto + 1 End If End Select AutoX(1) = AutoX(0) AutoY(1) = AutoY(0) AutoX(0) = PosXAuto AutoY(0) = PosYAuto txtPosX.Text = AutoX(0) TxtPosy.Text = AutoY(0) btnMaps_Click(sender, e) traslados() BtnObtColor_Click(sender, e) txtMover.Text = "" End Sub Private Sub btnRuta_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRuta.Click Dim valor As Boolean = True ListBox1.Items.Clear() For fila = 0 To 4 Dirfac(fila) = 0 Next Dim posX, posY As Integer Dim resultado As Boolean = True posX = AutoX(0) posY = AutoY(0) If (ProbarRuta(posX + 1, posY, AutoX, AutoY) = True) Then Dirfac(0) = 1 valor = ProbarRuta(posX, posY - 1, AutoX, AutoY)

Page 131: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -875-

If (ProbarRuta(posX, posY - 1, AutoX, AutoY) = True) Then Dirfac(1) = 1 If (ProbarRuta(posX - 1, posY, AutoX, AutoY) = True) Then Dirfac(2) = 1 If (ProbarRuta(posX, posY + 1, AutoX, AutoY) = True) Then Dirfac(3) = 1

' encontrar el menor de los factibles que tiene menos vecinos Sdir(0) = Contavecinos(posX + 1, posY, li, Cont) Sdir(1) = Contavecinos(posX, posY - 1, li, Cont) Sdir(2) = Contavecinos(posX - 1, posY, li, Cont) Sdir(3) = Contavecinos(posX, posY + 1, li, Cont) ListBox1.Items.Add("sDIR 0 " & Sdir(0)) ListBox1.Items.Add("sDIR 1 " & Sdir(1)) ListBox1.Items.Add("sDIR 2 " & Sdir(2)) ListBox1.Items.Add("sDIR 3 " & Sdir(3)) menor = 100 dir = -1 If Sdir(0) < menor And Dirfac(0) = 1 Then menor = Sdir(0) dir = 1 End If If Sdir(1) < menor And Dirfac(1) = 1 Then menor = Sdir(1) dir = 2 End If If Sdir(2) < menor And Dirfac(2) = 1 Then menor = Sdir(2) dir = 3 End If If Sdir(3) < menor And Dirfac(3) = 1 Then menor = Sdir(3) dir = 4 End If If dir <= 0 Then RutaXMala(contMalos) = posX RutaYMala(contMalos) = posY contMalos = contMalos + 1 Cont = Cont - 1 ' ver si hay menos 1 li = li - 1 AutoX(0) = RutaX(Cont) AutoY(0) = RutaY(Cont) AutoX(1) = RutaX(Cont - 1) AutoY(1) = RutaY(Cont - 1) Else Select Case dir Case 1 : posX = posX + 1 Case 2 : posY = posY - 1 Case 3 : posX = posX - 1 Case 4 : posY = posY + 1 Case Else 'finalizado = True End Select AutoX(1) = AutoX(0) AutoY(1) = AutoY(0)

Page 132: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -876-

AutoX(0) = posX AutoY(0) = posY ' se traslada el auto txtPosX.Text = AutoX(0) TxtPosy.Text = AutoY(0) PosXAuto = AutoX(0) PosYAuto = AutoY(0) btnMaps_Click(sender, e) traslados() BtnObtColor_Click(sender, e) RutaX(Cont) = posX RutaY(Cont) = posY Cont = Cont + 1 li = li + 1 End If

ListBox1.Items.Add("CONT " & Cont) ListBox1.Items.Add("li " & li) ListBox1.Items.Add("CONT MALOS " & contMalos) ListBox1.Items.Add("DIR " & dir) ListBox1.Items.Add("CABERZA " & AutoX(0) & "Y " & AutoY(0)) ListBox1.Items.Add("COLA " & AutoX(1) & "Y " & AutoY(1)) ListBox1.Items.Add(" imprimiendo la cola") For col = li To Cont - 1 ListBox1.Items.Add(" col " & " X " & RutaX(col) & " Y " & RutaY(col)) Next BtnDibujarRuta_Click(sender, e) End Sub Private Sub btnMover_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnMover.Click Timer1.Interval = 10 Timer1.Enabled = True

End Sub Private Sub BtnDetener_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnDetener.Click Timer1.Enabled = False End Sub

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick btnRuta_Click(sender, e) End Sub

Private Sub BtnDibujarRuta_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnDibujarRuta.Click Dim fila As Integer For fila = li To Cont - 1 Grafico3.DrawRectangle(Pens.Red, (RutaX(fila) * Ex - AutoX(0) * Ex) + tam * Ex, (RutaY(fila) * Ey - AutoY(0) * Ey) + tam * Ey, Ex, Ey) Grafico1.DrawRectangle(Pens.Red, RutaX(fila) * Ex1, RutaY(fila) * Ey1, Ex1, Ey1)

Page 133: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -877-

Next End Sub

Private Sub BtnPosicionar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnPosicionar.Click ' se traslada el auto IniciarVectores() AutoX(0) = txtPosX.Text AutoY(0) = TxtPosy.Text AutoX(1) = AutoX(0) AutoY(1) = AutoY(0) - 1 RutaX(0) = AutoX(1) RutaY(0) = AutoY(1) Cont = 0 contMalos = 0 PosXAuto = AutoX(0) PosYAuto = AutoY(0) BtnObtColor_Click(sender, e) traslados() End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Retroceder.Click ListBox1.Items.Clear() Cont = Cont - 1 ' ver si hay menos 1 li = li - 1 AutoX(0) = RutaX(Cont) AutoY(0) = RutaY(Cont) AutoX(1) = RutaX(Cont - 1) AutoY(1) = RutaY(Cont - 1) PosXAuto = AutoX(0) PosYAuto = AutoY(0) txtPosX.Text = AutoX(0) TxtPosy.Text = AutoY(0) ListBox1.Items.Add("CONT " & Cont) ListBox1.Items.Add("li " & li) ListBox1.Items.Add("CONT MALOS " & contMalos) ListBox1.Items.Add("DIR " & dir) ListBox1.Items.Add("CABERZA " & AutoX(0) & "Y " & AutoY(0)) ListBox1.Items.Add("COLA " & AutoX(1) & "Y " & AutoY(1)) BtnDibujarRuta_Click(sender, e) End SubEnd ClassSystem.EventArgs) Handles btnGrafico.Click GrabarDatos() End SubEnd Class

11.18 MOVER UN ARCHIVO DE TEXTO Elaborar un programa que mueva un archivo de texto por la pantalla

Page 134: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -878-

CODIGO DEL MODULO

Imports System.IOModule Module2 Public x1, x2 As Integer Public ancho As Integer = 90 Public ex As Single = 30, ey As Single = 30 Public cadena As String = "AREQUIPA, 17 DE MAYO DEL 2010" Public CadenaBusca As String Public ASCII, indice As Integer Public vel As Integer ' *************************** Public NroLetras As Integer = 0 Public Const maxfilas As Integer = 12, maxcol As Integer = 700 ' 590 Public Const maxfilas1 As Integer = 12, maxcol1 As Integer = 100 Public nf As Integer = 10, nc As Integer = 590 Public nf1 As Integer = 10, nc1 As Integer = 100 Public nf2 As Integer = 10, nc2 As Integer = 90 ' se va copiar esa cantidad Public Cx1 As Integer = 0, Cy1 As Integer = 0 ' lugar de donde se va a copiar Public Cx2 As Integer = 60, Cy2 As Integer = 1 ' lugar a pegar en la matriz A Public Cx3 As Integer = 1, Cy3 As Integer = 1 ' lugar a mostrar la matriz B Public separa As Integer = 10 Public A(maxfilas, maxcol) As String Public B(maxfilas1, maxcol1) As String Public MA(maxfilas, maxcol) As String Public MB(maxfilas, maxcol) As String Public cont As Integer = 0

Sub ImprimirMatriz(B(,) As String, ByRef M(,) As String, Cx1 As Integer, Cy1 As Integer, ancho As Integer, alto As Integer) Dim fila, col As Integer For fila = 0 To alto - 1 For col = 0 To ancho - 1 M(Cy1 + fila, Cx1 + col) = B(fila, col) Next Next End Sub

Page 135: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -879-

Sub CopiarMatrices(A(,) As String, ByRef B(,) As String, Cx As Integer, Cy As Integer, Ancho As Integer, alto As Integer) Dim fila, col As Integer For fila = 0 To alto - 1 For col = 0 To Ancho - 1 B(fila, col) = A(Cy + fila, Cx + col) Next Next End Sub Sub RecuperarMatriz(ByVal nombrearchivo As String, ByRef A(,) As String, ByRef nf As Integer, ByVal nc As Integer) Dim srLector As StreamReader srLector = New StreamReader(nombrearchivo) Dim fila As Integer = 0, col As Integer Dim cadena As String = "" Dim subcadena As String Dim pos As Integer = 0 Dim inicio As Integer = 1 cadena = srLector.ReadLine() Do While Not (cadena Is Nothing) cadena = cadena & Chr(9) inicio = 1 For col = 0 To nc - 1 pos = InStr(inicio, cadena, Chr(9)) subcadena = Mid(cadena, inicio, pos - inicio) A(fila, col) = subcadena inicio = pos + 1 Next fila = fila + 1 cadena = srLector.ReadLine() Loop nf = fila Console.WriteLine("Archivo {0} leido satisfactoriamente", nombrearchivo) srLector.Close() End SubEnd Module

CODIGO DEL FORMULARIO

Public Class Form1 Dim Pen As Pen Dim Grafico As Graphics Dim brocha As SolidBrush Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load Grafico = PictureBox1.CreateGraphics Pen = New Pen(Color.Red, 2) brocha = New SolidBrush(Color.FromArgb(0, 255, 0)) End Sub

Sub MostrarMatriz(ByRef A(,) As String, Cx As Integer, Cy As Integer, nc As Integer, ByVal nf As Integer) For fila = 0 To nf - 1

Page 136: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -880-

For col = 0 To nc - 1 If A(fila, col) = 1 Then Grafico.FillRectangle(brocha, Cx + col * ex, Cy + fila * ey, ex, ex) End If Next Next End Sub

Private Sub BtnBorrar_Click(sender As Object, e As EventArgs) Handles BtnBorrar.Click Grafico.Clear(Color.Black) End Sub Private Sub BtnIniciar_Click(sender As Object, e As EventArgs) Handles BtnIniciar.Click Dim col As Integer cadena = TextBox1.Text Dim NombreArchivo As String = "E:\datos1\letras590x10.txt" RecuperarMatriz(NombreArchivo, A, nf, nc) ' MostrarMatriz(Cx, Cy, A, nc, nf) NroLetras = Len(cadena) cont = 0 For col = 0 To NroLetras - 1 CadenaBusca = cadena(col) ASCII = Asc(CadenaBusca) indice = ASCII - 32 Cx1 = separa * indice CopiarMatrices(A, B, Cx1, Cy1, nc1, nf1) ImprimirMatriz(B, MA, cont * separa, Cy1, nc1, nf1) cont = cont + 1 Next CopiarMatrices(MA, MB, 0, 0, NroLetras * 10, nf2) MostrarMatriz(MB, Cx3, Cy3, nc2, nf2) x1 = 10 End Sub

Private Sub Manual_Click(sender As Object, e As EventArgs) Handles BtnManual.Click BtnBorrar_Click(sender, e) If x1 < NroLetras * 10 Then CopiarMatrices(MA, MB, x1, 0, ancho, nf2) MostrarMatriz(MB, 1, Cy3, ancho, nf2) x1 = x1 + 1 'System.Threading.Thread.Sleep(20) ' 1 milisegundo Else x1 = 1 End If End Sub

Private Sub btnMover_Click(sender As Object, e As EventArgs) Handles btnMover.Click vel = TextBox2.Text Timer1.Interval = vel

Page 137: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -881-

Timer1.Enabled = True End Sub

Private Sub btnParar_Click(sender As Object, e As EventArgs) Handles btnParar.Click Timer1.Enabled = False End Sub Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick Manual_Click(sender, e) End SubEnd Class

11.20 MADURACION DE UNA FRUTA (ejemplo platanos)

Imports System.DrawingPublic Class Form1 Dim Grafico1 As Graphics Dim Grafico2 As Graphics Dim Grafico3 As Graphics Dim Grafico4 As Graphics Dim Grafico5 As Graphics Dim Grafico6 As Graphics Dim Grafico7 As Graphics

Dim GraficoCombinado As Graphics Dim Contfactor As Single = 0 Dim Color As Color Dim Pict As Bitmap Dim Pict1 As Bitmap Dim Pict2 As Bitmap Dim Pict3 As Bitmap Dim Pict4 As Bitmap Dim Pict5 As Bitmap Dim Pict6 As Bitmap

Page 138: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -882-

Dim Pict7 As Bitmap Const maxfilas As Integer = 50, maxcol As Integer = 50 Dim alto As Integer = maxfilas, ancho As Integer = maxcol Dim Brocha1 As SolidBrush Dim Brocha2 As SolidBrush Dim Brocha3 As SolidBrush Dim Brocha4 As SolidBrush Dim Brocha5 As SolidBrush Dim Brocha6 As SolidBrush Dim Brocha7 As SolidBrush

Dim brochaG As SolidBrush Dim Rojos1(maxfilas, maxcol) As Integer, Verdes1(maxfilas, maxcol) As Integer, Azules1(maxfilas, maxcol) As Integer Dim Rojos2(maxfilas, maxcol) As Integer, Verdes2(maxfilas, maxcol) As Integer, Azules2(maxfilas, maxcol) As Integer Dim Rojos3(maxfilas, maxcol) As Integer, Verdes3(maxfilas, maxcol) As Integer, Azules3(maxfilas, maxcol) As Integer Dim Rojos4(maxfilas, maxcol) As Integer, Verdes4(maxfilas, maxcol) As Integer, Azules4(maxfilas, maxcol) As Integer Dim Rojos5(maxfilas, maxcol) As Integer, Verdes5(maxfilas, maxcol) As Integer, Azules5(maxfilas, maxcol) As Integer Dim Rojos6(maxfilas, maxcol) As Integer, Verdes6(maxfilas, maxcol) As Integer, Azules6(maxfilas, maxcol) As Integer Dim Rojos7(maxfilas, maxcol) As Integer, Verdes7(maxfilas, maxcol) As Integer, Azules7(maxfilas, maxcol) As Integer

Dim rojo, verde, azul As Byte Dim cx As Integer = 1, cy As Integer = 1 Dim factor As Single = 0.1 Dim velocidad As Single Dim valor As Single = 0

Private Sub CargarGrafico(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCargarGrafico.Click Dim fila As Integer, col As Integer For fila = 0 To alto - 1 For col = 0 To ancho - 1 Color = Pict1.GetPixel(col, fila) Rojos1(fila, col) = Color.R Verdes1(fila, col) = Color.G Azules1(fila, col) = Color.B

Color = Pict2.GetPixel(col, fila) Rojos2(fila, col) = Color.R Verdes2(fila, col) = Color.G Azules2(fila, col) = Color.B

Color = Pict3.GetPixel(col, fila) Rojos3(fila, col) = Color.R Verdes3(fila, col) = Color.G Azules3(fila, col) = Color.B

Page 139: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -883-

Color = Pict4.GetPixel(col, fila) Rojos4(fila, col) = Color.R Verdes4(fila, col) = Color.G Azules4(fila, col) = Color.B

Color = Pict5.GetPixel(col, fila) Rojos5(fila, col) = Color.R Verdes5(fila, col) = Color.G Azules5(fila, col) = Color.B

Color = Pict6.GetPixel(col, fila) Rojos6(fila, col) = Color.R Verdes6(fila, col) = Color.G Azules6(fila, col) = Color.B Color = Pict7.GetPixel(col, fila) Rojos7(fila, col) = Color.R Verdes7(fila, col) = Color.G Azules7(fila, col) = Color.B Next col Next End Sub Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load PictureBox1.Width = ancho + cx PictureBox1.Height = alto + cy PictureBox2.Width = ancho + cx PictureBox2.Height = alto + cy PictureBox3.Width = ancho + cx PictureBox3.Height = alto + cy

PictureBox4.Width = ancho + cx PictureBox4.Height = alto + cy PictureBox5.Width = ancho + cx PictureBox5.Height = alto + cy PictureBox6.Width = ancho + cx PictureBox6.Height = alto + cy PictureBox7.Width = ancho + cx PictureBox7.Height = alto + cy

Cuadro.Width = ancho * 2 + cx Cuadro.Height = alto * 2 + cy Pict1 = New Bitmap("e:\datos2\platano1.bmp") Pict2 = New Bitmap("e:\datos2\platano2.bmp") Pict3 = New Bitmap("e:\datos2\platano3.bmp") Pict4 = New Bitmap("e:\datos2\platano4.bmp") Pict5 = New Bitmap("e:\datos2\platano5.bmp") Pict6 = New Bitmap("e:\datos2\platano6.bmp") Pict7 = New Bitmap("e:\datos2\platano7.bmp")

Brocha1 = New SolidBrush(Drawing.Color.Aqua) Brocha2 = New SolidBrush(Drawing.Color.Aqua)

Page 140: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -884-

Brocha3 = New SolidBrush(Drawing.Color.Aqua) Brocha4 = New SolidBrush(Drawing.Color.Aqua) Brocha5 = New SolidBrush(Drawing.Color.Aqua) Brocha6 = New SolidBrush(Drawing.Color.Aqua) Brocha7 = New SolidBrush(Drawing.Color.Aqua) brochaG = New SolidBrush(Drawing.Color.Aqua)

Grafico1 = PictureBox1.CreateGraphics Grafico2 = PictureBox2.CreateGraphics Grafico3 = PictureBox3.CreateGraphics Grafico4 = PictureBox4.CreateGraphics Grafico5 = PictureBox5.CreateGraphics Grafico6 = PictureBox6.CreateGraphics Grafico7 = PictureBox7.CreateGraphics GraficoCombinado = Cuadro.CreateGraphics End Sub Private Sub Iniciar(sender As Object, e As EventArgs) Handles BtnIniciar.Click For fila = 0 To alto - 1 For col = 0 To ancho - 1 rojo = Rojos1(fila, col) verde = Verdes1(fila, col) azul = Azules1(fila, col) Brocha1.Color = Color.FromArgb(rojo, verde, azul) Grafico1.FillRectangle(Brocha1, cx + col, cy + fila, 1, 1)

rojo = Rojos2(fila, col) verde = Verdes2(fila, col) azul = Azules2(fila, col) Brocha2.Color = Color.FromArgb(rojo, verde, azul) Grafico2.FillRectangle(Brocha2, cx + col, cy + fila, 1, 1)

rojo = Rojos3(fila, col) verde = Verdes3(fila, col) azul = Azules3(fila, col) Brocha3.Color = Color.FromArgb(rojo, verde, azul) Grafico3.FillRectangle(Brocha3, cx + col, cy + fila, 1, 1)

rojo = Rojos4(fila, col) verde = Verdes4(fila, col) azul = Azules4(fila, col) Brocha4.Color = Color.FromArgb(rojo, verde, azul) Grafico4.FillRectangle(Brocha4, cx + col, cy + fila, 1, 1)

rojo = Rojos5(fila, col) verde = Verdes5(fila, col) azul = Azules5(fila, col) Brocha5.Color = Color.FromArgb(rojo, verde, azul) Grafico5.FillRectangle(Brocha5, cx + col, cy + fila, 1, 1)

rojo = Rojos6(fila, col) verde = Verdes6(fila, col)

Page 141: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -885-

azul = Azules6(fila, col) Brocha6.Color = Color.FromArgb(rojo, verde, azul) Grafico6.FillRectangle(Brocha6, cx + col, cy + fila, 1, 1)

rojo = Rojos7(fila, col) verde = Verdes7(fila, col) azul = Azules7(fila, col) Brocha7.Color = Color.FromArgb(rojo, verde, azul) Grafico7.FillRectangle(Brocha7, cx + col, cy + fila, 1, 1) Next Next Contfactor = 0 End Sub

Private Sub btnMadurar_Click_1(sender As Object, e As EventArgs) Handles btnMadurar.Click velocidad = TextBox1.Text factor = TextBox2.Text Timer1.Interval = velocidad Timer1.Enabled = True End Sub Private Sub btnDetener_Click(sender As Object, e As EventArgs) Handles btnDetener.Click Timer1.Enabled = False End Sub

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick Contfactor = Contfactor + factor TextBox4.Text = Contfactor Graficar(sender, e) End Sub Sub graficar12(valor As Single) Dim rojo12, verde12, azul12 As Integer For fila = 0 To alto - 1 For col = 0 To ancho - 1 rojo12 = Rojos1(fila, col) * (1 - valor) + Rojos2(fila, col) * valor verde12 = Verdes1(fila, col) * (1 - valor) + Verdes2(fila, col) * valor azul12 = Azules1(fila, col) * (1 - valor) + Azules2(fila, col) * valor brochaG.Color = Color.FromArgb(rojo12, verde12, azul12) GraficoCombinado.FillRectangle(brochaG, cx + col, cy + fila, 1, 1) Next Next End Sub Sub graficar23(valor As Single) Dim rojo23, verde23, azul23 As Integer For fila = 0 To alto - 1 For col = 0 To ancho - 1 rojo23 = Rojos2(fila, col) * (1 - valor) + Rojos3(fila, col) * valor verde23 = Verdes2(fila, col) * (1 - valor) + Verdes3(fila, col) * valor azul23 = Azules2(fila, col) * (1 - valor) + Azules3(fila, col) * valor brochaG.Color = Color.FromArgb(rojo23, verde23, azul23) GraficoCombinado.FillRectangle(brochaG, cx + col, cy + fila, 1, 1)

Page 142: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -886-

Next Next End Sub

Sub graficar34(valor As Single) Dim rojo34, verde34, azul34 As Integer For fila = 0 To alto - 1 For col = 0 To ancho - 1 rojo34 = Rojos3(fila, col) * (1 - valor) + Rojos4(fila, col) * valor verde34 = Verdes3(fila, col) * (1 - valor) + Verdes4(fila, col) * valor azul34 = Azules3(fila, col) * (1 - valor) + Azules4(fila, col) * valor brochaG.Color = Color.FromArgb(rojo34, verde34, azul34) GraficoCombinado.FillRectangle(brochaG, cx + col, cy + fila, 1, 1) Next Next End Sub

Sub graficar45(valor As Single) Dim rojo45, verde45, azul45 As Integer For fila = 0 To alto - 1 For col = 0 To ancho - 1 rojo45 = Rojos4(fila, col) * (1 - valor) + Rojos5(fila, col) * valor verde45 = Verdes4(fila, col) * (1 - valor) + Verdes5(fila, col) * valor azul45 = Azules4(fila, col) * (1 - valor) + Azules5(fila, col) * valor brochaG.Color = Color.FromArgb(rojo45, verde45, azul45) GraficoCombinado.FillRectangle(brochaG, cx + col, cy + fila, 1, 1) Next Next End Sub

Sub graficar56(valor As Single) Dim rojo56, verde56, azul56 As Integer For fila = 0 To alto - 1 For col = 0 To ancho - 1 rojo56 = Rojos5(fila, col) * (1 - valor) + Rojos6(fila, col) * valor verde56 = Verdes5(fila, col) * (1 - valor) + Verdes6(fila, col) * valor azul56 = Azules5(fila, col) * (1 - valor) + Azules6(fila, col) * valor brochaG.Color = Color.FromArgb(rojo56, verde56, azul56) GraficoCombinado.FillRectangle(brochaG, cx + col, cy + fila, 1, 1) Next Next End Sub

Sub graficar67(valor As Single) Dim rojo67, verde67, azul67 As Integer For fila = 0 To alto - 1 For col = 0 To ancho - 1 rojo67 = Rojos6(fila, col) * (1 - valor) + Rojos7(fila, col) * valor verde67 = Verdes6(fila, col) * (1 - valor) + Verdes7(fila, col) * valor azul67 = Azules6(fila, col) * (1 - valor) + Azules7(fila, col) * valor brochaG.Color = Color.FromArgb(rojo67, verde67, azul67) GraficoCombinado.FillRectangle(brochaG, cx + col, cy + fila, 1, 1)

Page 143: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -887-

Next Next End Sub

Private Sub Graficar(sender As Object, e As EventArgs) Handles btnGraficar.Click Contfactor = TextBox4.Text If Contfactor <= 1 Then graficar12(Contfactor) Else If Contfactor <= 2 Then graficar23(Contfactor - 1) Else If Contfactor <= 3 Then graficar34(Contfactor - 2) Else If Contfactor <= 4 Then graficar45(Contfactor - 3) Else If Contfactor <= 5 Then graficar56(Contfactor - 4) Else If Contfactor <= 6 Then graficar67(Contfactor - 5) Else Contfactor = 0 End If End If End If End If End If End If End Sub

Private Sub btnManual_Click(sender As Object, e As EventArgs) Handles btnManual.Click Contfactor = Contfactor + factor TextBox4.Text = Contfactor Graficar(sender, e) End SubEnd Class

11.21 JUEGO DEL PACMAN

Este juego esta basado en la pagina país de juegos de internet

Page 144: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -888-

http://www.paisdelosjuegos.pe/juegos/pacman

se juega con las teclas direccionales

Option Explicit OnPublic Class Form1 Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load Dim fila, col As Integer DataGridView1.RowCount = nf DataGridView1.ColumnCount = nc For col = 0 To nc - 1 DataGridView1.Columns(col).Width = 24 DataGridView1.Columns(col).HeaderText = col Next For fila = 0 To nf - 1 DataGridView1.Rows(fila).HeaderCell.Value = fila.ToString Next RecuperarMatriz(NombreArchivo, Matriz, nf, nc) Matriz(pmy, pmx) = 3 MostrarMatriz(Matriz, nf, nc) txtPorcentaje.Text = contar(Matriz, nf, nc) * 100 DataGridView1.Focus() End Sub Private Sub BtnRecuperar_Click(sender As Object, e As EventArgs) Handles BtnRecuperar.Click

Page 145: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -889-

RecuperarMatriz(NombreArchivo, Matriz, nf, nc) End Sub Private Sub BtnMostrar_Click(sender As Object, e As EventArgs) Handles BtnMostrar.Click MostrarMatriz(Matriz, nf, nc) End Sub Private Sub DataGridView1_CellEnter(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellEnter col = DataGridView1.CurrentCellAddress.X fila = DataGridView1.CurrentCellAddress.Y 'DataGridView1.CurrentCell.Style.BackColor = Color.FromArgb(255, 0, 0) TextBox1.Text = "F " & fila & "C" & col ValorActual = DataGridView1.CurrentCell.Value txtAnterior.Text = ValorAnterior txtActual.Text = ValorActual TextBox2.Text = cont Select Case ValorActual Case camino ' entre a la celda de color blanco If ValorAnterior = relleno Then ' la celda anterior era verde cont = 0 ' comienza a llenar al vector ' encuentra la fila columna inicial X(cont) = col Y(cont) = fila xini = col yini = fila ListBox1.Items.Clear() ListBox1.Items.Add("Xini " & xini & " Yini " & yini) ListBox1.Items.Add("Yfin " & xfin & " Yfin " & yfin) DataGridView1.CurrentCell.Value = relleno ' ahora la celda es de color verde Matriz(fila, col) = relleno Else ' la celda anterior no era verde sigue incrementando contador cont = cont + 1 X(cont) = col Y(cont) = fila DataGridView1.CurrentCell.Value = relleno ' ahora la celda es de color verde Matriz(fila, col) = relleno End If Case relleno ' entre a la celda de color verde If ValorAnterior = relleno Then ' la celda anterior era verde ' no hace nada Else ' la celda anterior era blanco ' termina la salida xfin = col yfin = fila Y(cont) = fila X(cont) = col ListBox1.Items.Clear() ListBox1.Items.Add("Xini " & xini & " Yini " & yini) ListBox1.Items.Add("Yfin " & xfin & " Yfin " & yfin) If cont > 2 Then nelem = cont cx = (xini + xfin) / 2 cy = (yini + yfin) / 2

Page 146: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -890-

' MostrarMatriz(Matriz, nf, nc) Centroide(X, Y, nelem, centrox, centroy) 'DataGridView1.Rows(cy).Cells(cx).Value = 3 'DataGridView1.Rows(centroy).Cells(centrox).Value = 4 ' CENTRO PROMEDIO If Matriz(cy, cx) = camino Then Rellenar(cx, cy) End If If Matriz(centroy, centrox) = camino Then Rellenar(centrox, centroy) End If MostrarMatriz(Matriz, nf, nc) txtPorcentaje.Text = contar(Matriz, nf, nc) * 100 End If End If End Select ValorAnterior = ValorActual End Sub Private Sub btnVector_Click(sender As Object, e As EventArgs) Handles btnVector.Click nelem = cont MostrarVector(X, Y, nelem) End Sub Private Sub btnRellenar_Click(sender As Object, e As EventArgs) Handles btnRellenar.Click Rellenar(cx, cy) End Sub Private Sub BtnIniciar_Click(sender As Object, e As EventArgs) Handles BtnIniciar.Click Dim fila, col As Integer For fila = 0 To nf - 1 For col = 0 To nc - 1 DataGridView1.Rows(fila).Cells(col).Value = 0 Matriz(fila, col) = 0 Next Next End Sub Sub jugar() Dim pmx1 As Single = pmx Dim pmy1 As Single = pmy Dim dist, distmenor dist = distancia(col, fila, pmx, pmy) distmenor = dist Matriz(pmy, pmx) = camino pmx1 = pmx pmy1 = pmy dist = distancia(col, fila, pmx + 1, pmy) If dist < distmenor And Matriz(pmy, pmx + 1) = camino Then distmenor = dist pmx1 = pmx + 1 End If dist = distancia(col, fila, pmx - 1, pmy)

Page 147: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -891-

If dist < distmenor And Matriz(pmy, pmx - 1) = camino Then distmenor = dist pmx1 = pmx - 1 End If dist = distancia(col, fila, pmx, pmy + 1) If dist < distmenor And Matriz(pmy + 1, pmx) = camino Then distmenor = dist pmy1 = pmy + 1 End If dist = distancia(col, fila, pmx, pmy - 1) If dist < distmenor And Matriz(pmy - 1, pmx) = camino Then distmenor = dist pmy1 = pmy - 1 End If If pmx1 = pmx And pmy1 = pmy Then While (1) pmx = Int(Rnd() * nc) pmy = Int(Rnd() * nf) If (Matriz(pmy, pmx) = camino) Then Exit While End While Else pmy = pmy1 pmx = pmx1 End If vecinos = Contavecinos(Matriz, nf, nc, col, fila) Matriz(pmy, pmx) = 3 MostrarMatriz(Matriz, nf, nc) If distmenor < 2 Then If vecinos < 4 Then txtvecinos.Text = " muerto" Timer1.Enabled = False Else txtvecinos.Text = " VIVO" End If Exit Sub End If txtdistancia.Text = distmenor txtvecinos.Text = vecinos DataGridView1.Focus() End Sub Private Sub btnJugar_Click(sender As Object, e As EventArgs) Handles btnJugar.Click Timer1.Interval = 50 Timer1.Enabled = True End Sub Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick jugar() End SubEnd Class

CODIGO DEL MODULO

Page 148: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -892-

Imports System.IOModule module2 '/*** declaraciones Public NombreArchivo As String = "E:\DATOS\MATRIZ20X20.txt" Public Const maxfilas As Integer = 20, maxcol As Integer = 20 Public Matriz(maxfilas, maxcol) As Integer Public maxelem As Integer = 1000 Public X(maxelem) As Integer ' vector de coordenadas x Public Y(maxelem) As Integer ' vector de coordenadas y Public cont As Integer = 0 Public nf As Integer = 20 Public nc As Integer = 20 Public px As Integer = 2 ' objeto identifico Public py As Integer = 2 Public ser As Integer = 1 Public relleno As Integer = 2 Public camino As Integer = 0 Public nelem As Integer Public cx As Integer = 0 ' centro dela figura Public cy As Integer = 0 Public ValorAnterior As Integer = 2 ' verde Public ValorActual As Integer = 0 Public xini As Integer = 0 Public yini As Integer = 0 Public xfin As Integer = 0 Public yfin As Integer = 0 Public centrox As Integer Public centroy As Integer Public cpromx As Integer Public cpromY As Integer Public pmx As Integer = 10 Public pmy As Integer = 10 Public pacman As Integer = 3 Public fila As Integer ' fila del pacman Public col As Integer Public vecinos As Integer = 0

Sub Rellenar(cx1 As Integer, cy1 As Integer) Form1.DataGridView1.Rows(cy1).Cells(cx1).Value = relleno Matriz(cy1, cx1) = relleno If Matriz(cy1, cx1 + 1) = camino And cx1 < nc - 1 Then Rellenar(cx1 + 1, cy1) End If If cx1 > 0 And Matriz(cy1, cx1 - 1) = camino Then Rellenar(cx1 - 1, cy1) End If If Matriz(cy1 + 1, cx1) = camino And cy1 < nf - 1 Then Rellenar(cx1, cy1 + 1) End If If Matriz(cy1 - 1, cx1) = camino And cy1 > 0 Then Rellenar(cx1, cy1 - 1)

Page 149: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -893-

End If End Sub Sub RecuperarMatriz(ByVal nombrearchivo As String, A(,) As Integer, ByVal nf As Integer, ByVal nc As Integer) Dim srLector As StreamReader srLector = New StreamReader(nombrearchivo) Dim fila As Integer, col As Integer Dim cadena As String = "" Dim subcadena As String Dim pos As Integer = 0 Dim inicio As Integer = 1 For fila = 0 To nf - 1 cadena = srLector.ReadLine() cadena = cadena & Chr(9) inicio = 1 For col = 0 To nc - 1 pos = InStr(inicio, cadena, Chr(9)) subcadena = Mid(cadena, inicio, pos - inicio) A(fila, col) = Val(subcadena) inicio = pos + 1 Next Next srLector.Close() End Sub Sub MostrarVector(X() As Integer, Y() As Integer, n As Integer) Dim col As Integer Form1.ListBox1.Items.Clear() For col = 0 To n - 1 Form1.ListBox1.Items.Add("col " & col & " X= " & X(col) & " Y= " & Y(col)) Next End Sub Sub Centroide(X() As Integer, y() As Integer, Nelem As Integer, ByRef cx As Integer, ByRef cy As Integer) Nelem = cont Dim col Dim sx As Integer = 0 Dim sy As Integer = 0 For col = 0 To Nelem - 1 sx = sx + X(col) sy = sy + y(col) Next cx = (sx / Nelem) cy = (sy / Nelem) End Sub Function contar(A(,) As Integer, ByVal nf As Integer, ByVal nc As Integer) As Single Dim suma, fila, col As Integer For fila = 0 To nf - 1 For col = 0 To nc - 1 If A(fila, col) = relleno Then suma = suma + 1 Next Next Return suma / (nf * nc)

Page 150: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -894-

End Function Sub MostrarMatriz(A(,) As Integer, ByVal nf As Integer, ByVal nc As Integer) Dim fila, col As Integer For fila = 0 To nf - 1 For col = 0 To nc - 1 Form1.DataGridView1.Rows(fila).Cells(col).Value = A(fila, col) Select Case A(fila, col) Case 0 Form1.DataGridView1.Rows(fila).Cells(col).Style.BackColor = Color.FromArgb(250, 255, 255) Case 1 ' pacman Form1.DataGridView1.Rows(fila).Cells(col).Style.BackColor = Color.FromArgb(250, 255, 0) Case 2 ' relleno Form1.DataGridView1.Rows(fila).Cells(col).Style.BackColor = Color.FromArgb(0, 255, 0) Case 3 'malo 1 Form1.DataGridView1.Rows(fila).Cells(col).Style.BackColor = Color.FromArgb(255, 0, 0) End Select Next Next End Sub

Function distancia(x1 As Single, y1 As Single, x2 As Single, y2 As Single) As Single Return Math.Sqrt(Math.Pow(x2 - x1, 2) + Math.Pow(y2 - y1, 2)) End Function Function Contavecinos(A(,) As Integer, nf As Integer, nc As Integer, px As Integer, py As Integer) As Integer Dim vecinos As Integer = 0 If px > 0 Then If A(py, px - 1) = relleno Then vecinos = vecinos + 1 End If If px < nc - 1 Then If A(py, px + 1) = relleno Then vecinos = vecinos + 1 End If If py > 0 Then If A(py - 1, px) = relleno Then vecinos = vecinos + 1 End If If py < nf - 1 Then If A(py + 1, px) = relleno Then vecinos = vecinos + 1 End If Return vecinos End FunctionEnd ModuleTarea: elaborar el siguiente juego del pacman

Page 151: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -895-

11.22 APLICACIONES DE REDES NEURONALES PERCEPTRON

Para ilustrar la regla de aprendizaje del Perceptrón, se dará solución al problema de clasificación de patrones ilustrado en la figura 2.1.9

,  ,  , 

Figura 2.1.9 Patrones de entrenamiento

En este caso las salidas toman valores bipolares de 1 o –1, por lo tanto la función de transferencia a utilizar será hardlims. Según la dimensiones de los patrones de entrenamiento la red debe contener dos entradas y una salida.

Figura 2.1.10 Red Perceptrón que resolverá el problema de clasificación de patrones

Para decidir si una red tipo Perceptrón puede aplicarse al problema de interés, se debe comprobar si el problema es linealmente separable, esto puede determinarse gráficamente de la figura 2.1.9, en donde se observa que existe un gran número de líneas rectas que pueden separar los patrones de una categoría de los patrones de la otra, el siguiente paso es asumir arbitrariamente los valores para los pesos y ganancias iniciales de entrada a la red; el proceso terminará cuando se hayan obtenido los pesos

Page 152: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -896-

y ganancias finales que permitan a la red clasificar correctamente todos los patrones presentados.

Los valores iniciales asignados aleatoriamente a los parámetros de la red son:

Con base en el procedimiento descrito anteriormente, el proceso de aprendizaje de la red es el siguiente:

De la iteración 0p1estaba mal clasificado, la actualización de pesos permite que este patrón sea clasificado correctamente.

La iteración 1 lleva a la característica de decisión de la figura 2.1.12

REM ****** moduleModule Module3 Public Const maxfilas As Integer = 10 Public Const maxcol As Integer = 3 Public nf As Integer = 4 Public nc As Integer = 3 Public limite As Integer = 10 Public Const np As Integer = 2 REM nro de capas Public a As Single Public alto As Integer = 400

Page 153: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -897-

Public ancho As Integer = 400 Public B(np, 1) As Single Public B1(np, 1) As Single Public BrochaSolida As SolidBrush Public C(maxfilas, maxcol) As Single Public ColorApagado As Color = Color.Gray Public Colorprendido As Color = Color.Red Public cont As Integer = 0 Public cx As Integer = 200 Public cy As Integer = 200 Public e As Single Public ex As Integer = 2 Public ey As Integer = -1 Public Grafico As Graphics Public i As Integer Public k As Integer Public MA(maxfilas, maxcol) As Single Public ME1(np, np) As Single Public MiFuente As New Font("Verdana", 10, FontStyle.Bold) Public ne As Integer = 0 ' nro de errores Public pen1 As Pen Public pen2 As Pen Public R(maxfilas, maxcol) As Single Public t As Single ' el resultado deseado Public tam As Integer = 20 Public valorButon1 As Integer = -1 Public valorButon2 As Integer = -1 Public VS(maxfilas) As Single Public VX(maxfilas) As Single Public VY(maxfilas) As Single Public W(1, np) As Single Public W1(1, np) As Single Public WX(np, np) As Single Public X(np, 1) As Single Public xa, ya, xb, yb As Single Public XT(np, 1) As Single Public XT1(np, 1) As SingleEnd Module

REM ************module 1Imports System.IOModule Module1 Sub Escalar(ByVal a(,) As Single, b(,) As Single, e As Single, nc As Integer) Dim col As Integer For col = 0 To nc - 1 b(0, col) = e * a(0, col) Next End Sub Sub CalcularLinea(W(,) As Single, B(,) As Single, n As Single) xa = 0 ya = -B(0, 0) / W(0, 1) yb = 0

Page 154: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -898-

xb = -B(0, 0) / W(0, 0) Console.WriteLine(" valores de x1 {0} y1 {1}", xa, ya) Console.WriteLine(" valores de x2 {0} y2 {1}", xb, yb) End Sub Sub MatrizTranspuesta(ByVal a(,) As Single, ByVal b(,) As Single, ByVal nf As Integer, ByVal nc As Integer) Dim fila, col As Integer For fila = 0 To nf - 1 For col = 0 To nc - 1 b(col, fila) = a(fila, col) Next Next End Sub Sub MultiplicarMatriz(ByVal a(,) As Single, ByVal b(,) As Single, ByRef c(,) As Single, _ ByVal p As Integer, ByVal q As Integer, ByVal r As Integer) Dim i, j, k As Integer Dim aux As Single For i = 0 To p - 1 For k = 0 To r - 1 aux = 0 For j = 0 To q - 1 aux = aux + a(i, j) * b(j, k) Next c(i, k) = aux Next Next End Sub Sub ObtenerVectores(A(,) As Single, X() As Single, Y() As Single, S() As Single, nf As Integer) Dim fila As Integer For fila = 0 To nf - 1 X(fila) = A(fila, 0) Y(fila) = A(fila, 1) S(fila) = A(fila, 2) Next End Sub Sub MostrarVector(X() As Single, nf As Integer) Dim fila As Integer For fila = 0 To nf - 1 Console.Write("{0,4}", X(fila)) Next End Sub Sub CopiarMatriz(ByVal A(,) As Single, ByVal B(,) As Single, ByVal nf As Integer, ByVal nc As Integer) Dim fila, col As Integer For fila = 0 To nf - 1 For col = 0 To nc - 1 B(fila, col) = A(fila, col) Next Next End Sub

Page 155: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -899-

Sub MostrarMatriz(ByVal A(,) As Single, ByVal nf As Integer, ByVal nc As Integer) Dim fila, col As Integer For fila = 0 To nf - 1 For col = 0 To nc - 1 Console.Write("{0,4} ", A(fila, col)) Next Console.WriteLine() Next End Sub Sub SumarMatrices(ByVal A(,) As Single, B(,) As Single, C(,) As Single, nf As Integer, ByVal nc As Integer) Dim fila, col As Integer For fila = 0 To nf - 1 For col = 0 To nc - 1 C(fila, col) = A(fila, col) + B(fila, col) Next Next End Sub Sub RecuperarMatriz(ByVal nombrearchivo As String, ByRef A(,) As Single, ByVal nf As Integer, ByVal nc As Integer) Dim srLector As StreamReader srLector = New StreamReader(nombrearchivo) Dim fila As Integer, col As Integer Dim cadena As String = "" Dim subcadena As String Dim pos As Integer = 0 Dim inicio As Integer = 1 For fila = 0 To nf - 1 cadena = srLector.ReadLine() cadena = cadena & Chr(9) inicio = 1 For col = 0 To nc - 1 pos = InStr(inicio, cadena, Chr(9)) subcadena = Mid(cadena, inicio, pos - inicio) A(fila, col) = CInt(CSng(Val(subcadena))) inicio = pos + 1 Next Next Console.WriteLine("Archivo leido satisfactoriamente") srLector.Close() End Sub Function Hardlims(W(,) As Single, X(,) As Single, t As Single, np As Integer) ' se obtiene el error y la salida Dim res As Single MultiplicarMatriz(W, X, C, 1, 2, 1) Console.WriteLine("resultado producto") MostrarMatriz(C, 1, 1) SumarMatrices(C, B, R, 1, 1) Console.WriteLine("resultado suma") MostrarMatriz(R, 1, 1) If R(0, 0) < 0 Then res = -1

Page 156: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -900-

Else res = 1 End If Return res End Function Sub ModificarPesos(w(,) As Single, ByRef w1(,) As Single, np As Integer) MatrizTranspuesta(X, XT, np, 1) MostrarMatriz(XT, 1, np) ' calcular nuevos pesos Escalar(XT, XT1, ME1(0, 0), np) Console.WriteLine("La matriz escalada es ") MostrarMatriz(XT1, 1, np) SumarMatrices(w, XT1, w1, 1, np) ' calculo del error SumarMatrices(w, XT1, w1, 1, np) End SubEnd ModuleREM ********* codigo del formularioOption Explicit OnPublic Class Form1 Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load DataGridView1.DefaultCellStyle.Font = New Font("Arial", 16) W(0, 0) = -0.7 W(0, 1) = 0.2 B(0, 0) = 0.5 W1(0, 0) = -0.7 W1(0, 1) = 0.2 B1(0, 0) = 0.5 btnFoco.Image = PictureBox3.Image btnE1.BackColor = ColorApagado btnE2.BackColor = ColorApagado btnE1.Text = "OFF" btnE2.Text = "ON" PictureBox3.Width = ancho PictureBox3.Height = alto Grafico = PictureBox3.CreateGraphics pen1 = New Pen(Color.Red, 3) pen2 = New Pen(Color.Blue, 1) BrochaSolida = New SolidBrush(Color.Black) Cambio(valorButon1, valorButon2) End Sub Sub ObtenerMatriz(ByRef A(,) As Single, ByVal nf As Integer, ByVal nc As Integer) Dim fila, col As Integer For fila = 0 To nf - 1 For col = 0 To nc - 1 A(fila, col) = DataGridView1.Rows(fila).Cells(col).Value Next Next End Sub

Sub MostrarMatriz(ByVal A(,) As Single, ByVal nf As Integer, ByVal nc As Integer) Dim fila, col As Integer

Page 157: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -901-

For fila = 0 To nf - 1 For col = 0 To nc - 1 DataGridView1.Rows(fila).Cells(col).Value = A(fila, col) Next Next End Sub Private Sub btnIniciar_Click(sender As Object, e As EventArgs) Handles btnIniciar.Click nf = txtNf.Text DataGridView1.RowCount = nf + 1 DataGridView1.ColumnCount = 3 DataGridView1.Columns(0).Width = 50 DataGridView1.Columns(1).Width = 50 DataGridView1.Columns(2).Width = 50 DataGridView1.Columns(0).HeaderText = "X" DataGridView1.Columns(1).HeaderText = "Y" DataGridView1.Columns(2).HeaderText = "t" End Sub Private Sub btnCargar_Click(sender As Object, e As EventArgs) Handles btnCargar.Click Dim NombreArchivo As String OpenFileDialog1.ShowDialog() NombreArchivo = OpenFileDialog1.FileName RecuperarMatriz(NombreArchivo, MA, nf, nc) ObtenerVectores(MA, VX, VY, VS, nf) MostrarMatriz(MA, nf, nc) Me.Text = "perceptron " + NombreArchivo End Sub Private Sub Probar(sender As Object, e As EventArgs) Handles btnProbar.Click X(0, 0) = TXTe1.Text X(1, 0) = txtE2.Text W(0, 0) = TxtW1.Text W(0, 1) = txtW2.Text B(0, 0) = txtB.Text a = Hardlims(W, X, t, 2) txtSalida.Text = a Select Case a Case -1 btnFoco.Image = PictureBox2.Image Case 1 btnFoco.Image = PictureBox1.Image Case Else btnFoco.Image = PictureBox3.Image End Select End Sub Private Sub btnEntrenar_Click(sender As Object, e As EventArgs) Handles btnEntrenar.Click ne = 0 cont = 0 Do ne = 0 ' Console.WriteLine("*********Ciclo {0} ", cont)

Page 158: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -902-

For i = 0 To nf - 1 ' Console.WriteLine("**************ITERACION {0} ", i) B(0, 0) = B1(0, 0) CopiarMatriz(W1, W, 1, np) X(0, 0) = VX(i) : X(1, 0) = VY(i) : t = VS(i) a = Hardlims(W, X, t, np) ' Console.WriteLine(" *** iteracion {0} salida {1}", i, a) ME1(0, 0) = t - a If ME1(0, 0) <> 0 Then ne = ne + 1 ' Console.WriteLine("el error es {0}", ME1(0, 0)) ' modificacion de pesos y a ModificarPesos(W, W1, np) ' Console.WriteLine("los nuevos pesos son") TxtW1.Text = W1(0, 0) txtW2.Text = W1(0, 1) ' MostrarMatriz(W1, 1, np) ' calcular b SumarMatrices(B, ME1, B1, 1, 1) 'Console.WriteLine("El nuevo B es {0}", B1(0, 0)) txtB.Text = B1(0, 0) Next ' Console.WriteLine("nro de errores {0} ", ne) cont = cont + 1 Loop While (ne > 0) ' Console.WriteLine("***resultados finales ") 'Console.WriteLine("los nuevos pesos son") TxtW1.Text = W1(0, 0) txtW2.Text = W1(0, 1) ' calcular b SumarMatrices(B, ME1, B1, 1, 1) ' Console.WriteLine("El nuevo B es {0}", B1(0, 0)) txtB.Text = B1(0, 0) End Sub Sub Cambio(ve1 As Integer, ve2 As Integer) X(0, 0) = ve1 X(1, 0) = ve2 TXTe1.Text = X(0, 0) txtE2.Text = X(1, 0) W(0, 0) = TxtW1.Text W(0, 1) = txtW2.Text B(0, 0) = txtB.Text a = Hardlims(W, X, t, 2) txtSalida.Text = a Select Case a Case -1 btnFoco.Image = PictureBox2.Image Case 1 btnFoco.Image = PictureBox1.Image Case Else btnFoco.Image = PictureBox3.Image End Select End Sub

Page 159: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -903-

Private Sub entrada1(sender As Object, e As EventArgs) Handles btnE1.Click If valorButon1 = -1 Then valorButon1 = 1 btnE1.BackColor = Colorprendido btnE1.Text = "ON" Else valorButon1 = -1 btnE1.BackColor = ColorApagado btnE1.Text = "OFF" End If Cambio(valorButon1, valorButon2) End Sub Private Sub Entrada2(sender As Object, e As EventArgs) Handles btnE2.Click If valorButon2 = -1 Then valorButon2 = 1 btnE2.BackColor = Colorprendido btnE2.Text = "ON" Else valorButon2 = -1 btnE2.BackColor = ColorApagado btnE2.Text = "OFF" End If Cambio(valorButon1, valorButon2) End Sub

Private Sub BtnGraficar_Click(sender As Object, e As EventArgs) Handles BtnGraficar.Click Dim x1 As Integer Dim y1 As Integer Dim res As Integer Dim valor As Integer For k = -limite To limite Grafico.DrawString(k, MiFuente, BrochaSolida, cx + k * tam, cy) Grafico.DrawLine(pen2, cx + k * tam, 0, cx + k * tam, alto) Next For k = -limite To limite Grafico.DrawString(k, MiFuente, BrochaSolida, cx, cy + k * tam * ey) Grafico.DrawLine(pen2, 0, cy + k * tam, ancho, cy + k * tam) Next Grafico.DrawLine(pen1, 0, cy, ancho, cy) Grafico.DrawLine(pen1, cx, 0, cx, alto) 'REM graficar la funcion For k = 0 To nf - 1 x1 = VX(k) * tam y1 = VY(k) * tam res = VS(k) valor = tam / 4 If res > 0 Then Grafico.FillEllipse(Brushes.Blue, cx + x1 - valor, cy + y1 * ey - valor, valor * 2, valor * 2) Else Grafico.FillEllipse(Brushes.Red, cx + x1 - valor, cy + y1 * ey - valor, valor * 2, valor * 2) End If

Page 160: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -904-

Next End Sub

Private Sub btnBorrar_Click(sender As Object, e As EventArgs) Handles btnBorrar.Click Grafico.Clear(Color.White) End Sub

Private Sub PictureBox3_MouseDown(sender As Object, e As MouseEventArgs) Handles PictureBox3.MouseDown Dim ValorX As Single Dim ValorY As Single Dim valor As Integer ValorX = (e.X - cx) / tam ValorY = -(e.Y - cy) / tam TXTe1.Text = ValorX txtE2.Text = ValorY valor = tam / 2 Grafico.FillRectangle(Brushes.Green, cx + ValorX * tam - valor, cy + ValorY * ey * tam - valor, valor * 2, valor * 2) End Sub Private Sub btnActualizar_Click(sender As Object, e As EventArgs) Handles btnActualizar.Click ObtenerMatriz(MA, nf, nc) ObtenerVectores(MA, VX, VY, VS, nf) End SubEnd Class

Problema 4 resuelva el problema de OR (0,1)

ENTRADA1 ENTRADA 2 OR-1 -1 -1-1 1 11 -1 11 1 1

11.23 APLICACIONES DE LOGICA DIFUSA EN CONTROL DE TEMPERATURA

TEMPERATURASCATEGORIA Valor Min Valor Medio Valor MaximoFRIO 0 15 30TEMPLADO 15 30 45CALIENTE 25 42 60MU CALIENTE 50 70 100

Page 161: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -905-

CLASE CATEGORIA

Public Class Categoria Public nombre As String Public ValorBajo As Single Public ValorMedio As Single Public ValorAlto As Single Public Sub setname(s As String) nombre = s End Sub Public Function getname() As String Return nombre End Function Public Sub PonerValor(ByRef h As Single, ByRef m As Single, ByRef l As Single) ValorAlto = h ValorMedio = m ValorBajo = l End Sub Public Function getlowval() As Single Return ValorBajo End Function

Page 162: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -906-

Public Function getmidval() As Single Return ValorMedio End Function Public Function gethighval() As Single Return ValorAlto End Function Public Function getshare(ByRef input As Single) As Single ' // la función miembro retorna la membresía realtiva '// de en la Entrada en una categoría. con un maximun de 1.0 Dim output As Single Dim midlow, highmid As Single midlow = ValorMedio - ValorBajo highmid = ValorAlto - ValorMedio '// si el rango exceed entonces salida =0 If ((input <= ValorBajo) Or (input >= ValorAlto)) Then output = 0 Else If (input > ValorMedio) Then output = (ValorAlto - input) / highmid Else If (input = ValorMedio) Then output = 1.0 Else output = (input - ValorBajo) / midlow End If End If End If Return output End FunctionEnd Class

CODIGO DEL FORMULARIO

Option Explicit OnPublic Class Form1 Dim Nfilas, Ncol, fila, col As Integer Function randomnum(maxval As Integer) As Single '// genera numero aletorio devolverá un entero a maxval Randomize() Return Rnd() * maxval End Function

Private Sub BtnIniciar_Click(sender As Object, e As EventArgs) Handles BtnIniciar.Click Dim fila1 As Integer Nfilas = txtFilas.Text Ncol = 5 DataGridView1.ColumnCount = Ncol DataGridView1.RowCount = Nfilas + 1 REM //numero de columnas For col1 = 0 To Ncol - 1 DataGridView1.Columns(col1).Width = 50 REM //ancho de las columnas Next

Page 163: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -907-

' REM Poner nro de las filas For fila1 = 0 To Nfilas - 1 DataGridView1.Rows(fila1).HeaderCell.Value = Str(fila1) DataGridView1.Rows(fila1).Cells(0).Value = fila1 + 1 Next DataGridView1.Columns(1).Width = 100 '// Poner TITULOS de COLUMNAS DataGridView1.Columns(0).HeaderText = "Nro" DataGridView1.Columns(1).HeaderText = "CATEGORIA" DataGridView1.Columns(2).HeaderText = "VMin" DataGridView1.Columns(3).HeaderText = "VMedio" DataGridView1.Columns(4).HeaderText = "VMax"

'// valores por defecto DataGridView1.Rows(0).Cells(1).Value = "FRIO" DataGridView1.Rows(1).Cells(1).Value = " TEMPLADO" DataGridView1.Rows(2).Cells(1).Value = "CALIENTE" DataGridView1.Rows(3).Cells(1).Value = "Muy CALIENTE"

DataGridView1.Rows(0).Cells(2).Value = "0" DataGridView1.Rows(1).Cells(2).Value = "15" DataGridView1.Rows(2).Cells(2).Value = "25" DataGridView1.Rows(3).Cells(2).Value = "50"

DataGridView1.Rows(0).Cells(3).Value = "15" DataGridView1.Rows(1).Cells(3).Value = "30" DataGridView1.Rows(2).Cells(3).Value = "42" DataGridView1.Rows(3).Cells(3).Value = "70"

DataGridView1.Rows(0).Cells(4).Value = "30" DataGridView1.Rows(1).Cells(4).Value = "45" DataGridView1.Rows(2).Cells(4).Value = "60" DataGridView1.Rows(3).Cells(4).Value = "100" '// Valores de la cuadricula 2 DataGridView2.ColumnCount = 3 REM //numero de columnas DataGridView2.RowCount = Nfilas + 1 REM //numero de filas

DataGridView2.Columns(0).Width = 40 REM //ancho de la col 0 DataGridView2.Columns(1).Width = 100 REM //ancho de la col 0 DataGridView2.Columns(2).Width = 60 REM //ancho de la col 0

'// Poner numero de COLUMNAS DataGridView2.Columns(0).HeaderText = "Nro" DataGridView2.Columns(1).HeaderText = "CATEGORIA" DataGridView2.Columns(2).HeaderText = "PROB" End Sub

Private Sub BtnCalcular_Click(sender As Object, e As EventArgs) Handles BtnCalcular.Click Dim i As Integer = 0 Dim j As Integer = 0 Dim numcat As Integer = 0

Page 164: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -908-

Dim randnum, k As Integer Dim l, m, h As Single Dim inval As Single = 1.0 Dim input As String '""// ***** ver despuesSIN Dim ptr(10) As Categoria Dim relprob(10) As Single Dim valor As Single Dim total As Single = 0 Dim runtotal As Single = 0 numcat = Nfilas REM // número de categorias total = 0 For i = 0 To numcat - 1 ptr(i) = New Categoria() input = DataGridView1.Rows(i).Cells(1).Value ptr(i).setname(input) l = DataGridView1.Rows(i).Cells(2).Value m = DataGridView1.Rows(i).Cells(3).Value h = DataGridView1.Rows(i).Cells(4).Value ptr(i).PonerValor(h, m, l) Next inval = txtDesc.Text For j = 0 To numcat - 1 relprob(j) = 100 * ptr(j).getshare(inval) total = total + relprob(j) Next If (total = 0) Then MessageBox.Show("Presione el boton OK ") REM Exit if Return End If randnum = randomnum(CInt(total)) j = 0 runtotal = relprob(0) While ((runtotal < randnum) And (j < numcat)) j += 1 runtotal = runtotal + relprob(j) End While txtCat.Text = "" txtCat.Text = ptr(j).getname() For j = 0 To numcat - 1 DataGridView2.Rows(j).Cells(0).Value = j DataGridView2.Rows(j).Cells(1).Value = ptr(j).getname() valor = relprob(j) / total DataGridView2.Rows(j).Cells(2).Value = valor Next End SubEnd Class

11.24 APLICACIÓN DEL MODELOS DEL SIMPLEX

Page 165: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -909-

DESCRIPCION Se ha hecho un programa del método simplex usando visual basic del visual estudio 2012

El programa permite Ingresar los datos escoger la opción de maximización y minimizaciónPermite formar las matrices de variables de holgura exceso y artificialesPermite mostrar las iteraciones paso a paso a coloresY grabar los datos y los resultados para poder analizar en ExcelEsta en proceso el método grafico y el análisis de senisiblidadEl programa ejecutable no necesita del visual estudio para su ejecución

Se hara software para otros modelos

CODIGO FUENTE

Option Explicit OnModule Module2 Public TotalvariablesValidas ' menos las variables artificiales Public B(maximo) As Single 'vector B Public CJ(maximo) As Single ' coefecientes de las variables Public CJ_ZJ(maximo) As Single Public col As Integer Public ColPivote As Integer Public Const maximo As Integer = 10 Public Cx As Integer ' columna de inicio Public Cy As Integer ' fila donde empieza Public fila As Integer Public FilaPivote As Integer Public M1(maximo, maximo) As Single ' matriz de trabajo 1 Public M2(maximo, maximo) As Single ' matriz de trabajo 2 Public MCV(maximo, maximo) As Single ' matriz de coefecientes de las variables Public MVA(maximo, maximo) As Single ' matriz de variables artificiales

Page 166: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -910-

Public MVE(maximo, maximo) As Single ' matriz de variables de exceso Public MVH(maximo, maximo) As Single ' matriz de variables de holgura Public nombresVAR(maximo) As String 'NOMBRES DE LAS VARIABLES Public NombresVB(maximo) As String ' nombres de las variables basicas Public nrestric As Integer Public nva As Integer ' nro de variables artificiales Public nvar As Integer Public nve As Integer ' nro de variables de exceso Public nvh As Integer ' nro de variables de holgura Public opcion As Integer ' es maximizacion o es mminimizacion Public pivote As Single Public Pos1 As Integer ' posicion inicial donde empieza la matriz Public pos2 As Integer ' posicion final Public Ratio(maximo) As Single Public SolOptima As Boolean Public tipo As String Public Totalvariables As Integer ' total de variables Public Vector(maximo) As Integer ' indices de las variables basics Public VH(maximo) As Single ' coefecientes de las variables de holgura Public VVB(maximo) As Single ' coefecientes de las variables basica Public VX(maximo) As Single ' coefecientes de las variables Public ZJ(maximo) As SingleEnd Module

CODIGO DEL MODULO

Option Explicit OnModule Module1 Sub FormarM2(ByVal M1(,) As Single, ByRef M2(,) As Single, ByVal nf As Integer, ByVal nc As Integer, ByVal filapivote As Integer, ByVal colpivote As Integer) pivote = M1(filapivote, colpivote) For fila = 0 To nf - 1 If fila = filapivote Then For col = 0 To nc - 1 M2(filapivote, col) = M1(filapivote, col) / pivote Next Else For col = 0 To nc - 1 M2(fila, col) = M1(fila, col) - M1(filapivote, col) * M1(fila, colpivote) / pivote Next End If Next End Sub Function Primeradecision(ByVal A() As Single, ByVal nc As Integer, ByVal opcion As Integer) ' corrigir cuando primero sin opcio soean artificiales Dim columna As Integer Dim mayor As Single = -10 Dim menor As Single = 10000 Select Case opcion Case 1 ' cuando es maximizacion For col = 1 To nc - 1 ' por que el primero es B If A(col) > mayor Then

Page 167: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -911-

mayor = A(col) columna = col End If Next Case 2 ' cuando es minimizacionn For col = 1 To nc - 1 ' por que el primero es B If A(col) < menor Then menor = A(col) columna = col End If Next End Select Primeradecision = columna End Function Function SolucionOptima(ByVal A() As Single, ByVal nc As Integer, ByVal opcion As Integer) ' corrigir cuando primero sin opcio soean artificiales Dim solucion As Boolean = True Select Case opcion Case 1 ' cuando es maximizacion For col = 1 To nc - 1 ' no debe considerar B If A(col) > 0 Then solucion = False Exit For End If Next Case 2 ' cuando es maximizacion For col = 1 To nc - 1 ' no debe considerar B If A(col) < 0 Then solucion = False Exit For End If Next End Select SolucionOptima = solucion End Function Public Sub IniciarMatriz(ByRef A(,) As Single, ByVal nf As Integer, ByVal nc As Integer) For fila = 0 To nf - 1 For col = 0 To nc - 1 A(fila, col) = 0 Next col Next fila End Sub Public Sub CopiarMatriz(ByVal M1(,) As Single, ByRef M2(,) As Single, ByVal nf As Integer, ByVal nc As Integer) For fila = 0 To nf - 1 For col = 0 To nc - 1 M2(fila, col) = M1(fila, col) Next col Next fila End Sub

Page 168: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -912-

Public Sub ObtenerVariablesBasicas(ByRef A(,) As Single, ByVal nf As Integer, ByVal nc As Integer, ByRef Vector() As Integer) Dim k As Integer Dim unitario As Boolean For fila = 0 To nf - 1 For col = 0 To nc - 1 If A(fila, col) = 1 Then '1 unitario = True For k = 0 To nrestric - 1 '2 If k <> fila Then If A(k, col) <> 0 Then unitario = False Exit For End If End If Next k If unitario = True Then Vector(fila) = col Exit For End If End If Next col Next fila End Sub Sub ObtenerZJ(ByVal M1(,) As Single, ByVal A() As Single, ByVal nf As Integer, ByVal nc As Integer, ByRef ZJ() As Single) For col = 0 To nc - 1 ZJ(col) = 0 For fila = 0 To nf - 1 ZJ(col) = ZJ(col) + A(fila) * M1(fila, col) Next Next End Sub Sub ObtenerCJ_ZJ(ByVal CJ() As Single, ByVal ZJ() As Single, ByRef CJ_ZJ() As Single, ByVal nc As Integer) For col = 0 To nc - 1 CJ_ZJ(col) = CJ(col) - ZJ(col) Next End Sub Function SegundaDecision(ByVal A() As Single, ByVal nf As Integer) Dim MenorPositivo As Single = 1000 For i = 0 To nf - 1 If A(i) >= 0 And A(i) < MenorPositivo Then MenorPositivo = A(i) fila = i End If Next SegundaDecision = fila End FunctionEnd Module

Page 169: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -913-

CODIGO DEL FORMULARIO1

Option Explicit OnImports System.IOPublic Class Form1 Sub ImprimirVector(ByVal A() As Single, ByVal Cy As Integer, ByVal Cx As Integer, ByVal Nc As Integer) For col = 0 To Nc - 1 DataGridView2.Rows(Cy).Cells(Cx + col).Value = A(col) Next End Sub Sub ImprimirVector2(ByVal A() As Single, ByVal Cy As Integer, ByVal Cx As Integer, ByVal Nc As Integer) For fila = 0 To Nc - 1 DataGridView2.Rows(Cy + fila).Cells(Cx).Value = A(fila) Next End Sub Sub ImprimirVectorEntero(ByVal A() As Integer, ByVal Cy As Integer, ByVal Cx As Integer, ByVal Nc As Integer) For col = 0 To Nc - 1 DataGridView2.Rows(Cy).Cells(Cx + col).Value = A(col) Next End Sub Sub ImprimirVectorCadena(ByVal A() As String, ByVal Cy As Integer, ByVal Cx As Integer, ByVal Nc As Integer) For col = 0 To Nc - 1 DataGridView2.Rows(Cy).Cells(Cx + col).Value = A(col) Next End Sub Sub ImprimirVectorCadena2(ByVal A() As String, ByVal Cy As Integer, ByVal Cx As Integer, ByVal Nc As Integer) For fila = 0 To Nc - 1 DataGridView2.Rows(Cy + fila).Cells(Cx).Value = A(fila) Next End Sub Sub cabecera(ByVal Cy As Integer, ByVal Cx As Integer) DataGridView2.Rows(Cy).Cells(Cx).Value = "ZJ" DataGridView2.Rows(Cy + 1).Cells(Cx).Value = "CJ-ZJ"

End Sub Sub ImprimirMatriz(ByRef A(,) As Single, ByVal Cy As Integer, ByVal Cx As Integer, ByVal nf As Integer, ByVal nc As Integer) For fila = 0 To nf - 1 For col = 0 To nc - 1 DataGridView2.Rows(Cy + fila).Cells(Cx + col).Value = A(fila, col) Next col Next fila End Sub Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load nrestric = 2 nvar = 2

Page 170: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -914-

opcion = 1 End Sub Private Sub MnuNroVariables_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuNroVariables.Click nvar = InputBox("Cantidad de variables", "Nvar", 2) End Sub

Private Sub MnuNroRestricciones_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles MnuNroRestricciones.Click nrestric = InputBox("Cantidad de Restricciones", "NRestric", 2) End Sub Private Sub MnuIniciar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuIniciar.Click Dim CboTipo As New DataGridViewComboBoxColumn() DataGridView1.RowCount = nrestric + 2 DataGridView1.ColumnCount = nvar + 2 DataGridView1.Columns(0).HeaderCell.Value = "Variable" For i = 1 To nvar DataGridView1.Columns(i).HeaderCell.Value = "X" & i Next DataGridView1.Rows(0).Cells(0).Value = " Margen Contr" DataGridView1.Rows(1).Cells(0).Value = " Restricciones" DataGridView1.Rows(1).Cells(nvar + 1).Value = " Disponib" For i = 1 To nrestric DataGridView1.Rows(1 + i).Cells(0).Value = "R" & i Next CboTipo.Name = ">=,<=,=" CboTipo.Items.Add("<=") CboTipo.Items.Add(">=") CboTipo.Items.Add("=") DataGridView1.Columns.Add(CboTipo) DataGridView1.Rows(0).Cells(1).Value = 200 DataGridView1.Rows(0).Cells(2).Value = 150 DataGridView1.Rows(2).Cells(1).Value = 3 DataGridView1.Rows(2).Cells(2).Value = 2 DataGridView1.Rows(2).Cells(3).Value = 500 DataGridView1.Rows(3).Cells(1).Value = 1 DataGridView1.Rows(3).Cells(2).Value = 2 DataGridView1.Rows(3).Cells(3).Value = 400 End Sub

Private Sub MnuFormaEstandar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuFormaEstandar.Click nvh = 0 : nve = 0 : nva = 0 IniciarMatriz(MVH, maximo, maximo) IniciarMatriz(MVE, maximo, maximo) IniciarMatriz(MVA, maximo, maximo) Pos1 = 2 pos2 = Pos1 + nrestric For col = 0 To nvar - 1 VX(col) = DataGridView1.Rows(0).Cells(col + 1).Value Next

Page 171: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -915-

' obtener la matriz de valores Cy = 2 Cx = 1 For fila = 0 To nrestric - 1 B(fila) = DataGridView1.Rows(Cy + fila).Cells(3).Value For col = 0 To nvar - 1 MCV(fila, col) = DataGridView1.Rows(Cy + fila).Cells(Cx + col).Value Next col Next fila ' ImprimirVector(B, 3, 2, nrestric) For fila = 0 To nrestric - 1 ' tipo = DataGridView1.Rows(2 + fila).Cells(4).Value tipo = "<=" ' DESPUES BORRAR Select Case tipo Case "<=" : MVH(fila, nvh) = 1 : nvh = nvh + 1 Case ">=" : MVE(fila, nve) = -1 : MVA(fila, nva) = 1 : nve = nve + 1 : nva = nva + 1 Case "=" : MVA(fila, nva) = 1 : nva = nva + 1 End Select Next 'formar la matriz Totalvariables = nvar + nvh + nve + nva + 1 TotalvariablesValidas = nvar + nvh + nve

DataGridView2.RowCount = nrestric + 3 DataGridView2.ColumnCount = 3 + Totalvariables ' forma Cj CJ(0) = 0 nombresVAR(0) = "B" For col = 0 To nvar - 1 CJ(1 + col) = VX(col) nombresVAR(1 + col) = "X" & col + 1 Next col For col = 0 To nvh - 1 CJ(col + nvar + 1) = 0 nombresVAR(col + nvar + 1) = "U" & col + 1 Next col For col = 0 To nve - 1 CJ(col + nvar + nvh + 1) = 0 nombresVAR(col + nvar + nvh + 1) = "E" & col + 1 Next col For col = 0 To nva - 1 CJ(col + nvar + nvh + nve + 1) = 999 nombresVAR(col + nvar + nvh + nve + 1) = "Q" & col + 1 Next col DataGridView2.Rows(0).Cells(0).Value = "CJ" DataGridView2.Rows(1).Cells(0).Value = "CK" DataGridView2.Rows(1).Cells(1).Value = "XK"

ImprimirVector(CJ, 0, 2, Totalvariables) ImprimirVectorCadena(nombresVAR, 1, 2, Totalvariables) ' forma la matriz 1 For fila = 0 To nrestric - 1

Page 172: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -916-

M1(fila, 0) = B(fila) For col = 0 To nvar - 1 M1(fila, col + 1) = MCV(fila, col) Next col For col = 0 To nvh - 1 M1(fila, col + nvar + 1) = MVH(fila, col) Next col For col = 0 To nve - 1 M1(fila, col + nvar + nvh + 1) = MVE(fila, col) Next col For col = 0 To nva - 1 M1(fila, col + nvar + nvh + nve + 1) = MVA(fila, col) Next col Next fila ImprimirMatriz(M1, Pos1, 2, nrestric, Totalvariables) ObtenerVariablesBasicas(M1, nrestric, Totalvariables, Vector) For fila = 0 To nrestric - 1 VVB(fila) = CJ(Vector(fila)) NombresVB(fila) = nombresVAR(Vector(fila)) Next ImprimirVector2(VVB, 2, 0, nrestric) ImprimirVectorCadena2(NombresVB, 2, 1, nrestric) DataGridView2.Rows(1).Cells(Totalvariables + 2).Value = "Ratio" End Sub Private Sub MnuMaximizar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuMaximizar.Click opcion = 1 End Sub

Private Sub mnuMinimizar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuMinimizar.Click opcion = 2 End Sub

Private Sub MnuCalculoInicial_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuCalculoInicial.Click For fila = 0 To nrestric DataGridView2.Rows.Add() Next Pos1 = 2 pos2 = Pos1 + nrestric cabecera(pos2, 0) ObtenerZJ(M1, VVB, nrestric, Totalvariables, ZJ) ImprimirVector(ZJ, pos2, 2, Totalvariables) ObtenerCJ_ZJ(CJ, ZJ, CJ_ZJ, Totalvariables) ImprimirVector(CJ_ZJ, pos2 + 1, 2, Totalvariables) SolOptima = SolucionOptima(CJ_ZJ, TotalvariablesValidas, opcion) If SolOptima = False Then DataGridView2.Rows(pos2 + 1).Cells(Totalvariables + 2).Value = "NO SO" Else DataGridView2.Rows(pos2 + 1).Cells(Totalvariables + 2).Value = "SO" Exit Sub

Page 173: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -917-

End If ColPivote = Primeradecision(CJ_ZJ, Totalvariables, opcion) For fila = 0 To nrestric DataGridView2.Rows(Pos1 + fila).Cells(ColPivote + 2).Style.BackColor = Color.FromArgb(0, 255, 0) Next '' calcular ratio For fila = 0 To nrestric - 1 Ratio(fila) = B(fila) / M1(fila, ColPivote) Next ImprimirVector2(Ratio, Pos1, Totalvariables + 2, nrestric) FilaPivote = SegundaDecision(Ratio, nrestric) pivote = M1(FilaPivote, ColPivote) For col = 0 To Totalvariables + 2 DataGridView2.Rows(Pos1 + FilaPivote).Cells(col).Style.BackColor = Color.FromArgb(255, 125, 0) Next DataGridView2.Rows(Pos1 + FilaPivote).Cells(ColPivote + 2).Style.BackColor = Color.FromArgb(255, 255, 0) End Sub

Private Sub MnuCalculofinal_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuCalculofinal.Click Do For fila = 0 To nrestric DataGridView2.Rows.Add() Next Pos1 = pos2 + 2 pos2 = Pos1 + nrestric VVB(FilaPivote) = CJ(ColPivote) NombresVB(FilaPivote) = nombresVAR(ColPivote) ImprimirVector2(VVB, Pos1, 0, nrestric) ImprimirVectorCadena2(NombresVB, Pos1, 1, nrestric) FormarM2(M1, M2, nrestric, Totalvariables, FilaPivote, ColPivote) ImprimirMatriz(M2, Pos1, 2, nrestric, Totalvariables) cabecera(pos2, 0) CopiarMatriz(M2, M1, nrestric, Totalvariables) ObtenerZJ(M1, VVB, nrestric, Totalvariables, ZJ) ImprimirVector(ZJ, pos2, 2, Totalvariables) ObtenerCJ_ZJ(CJ, ZJ, CJ_ZJ, Totalvariables) ImprimirVector(CJ_ZJ, pos2 + 1, 2, Totalvariables) SolOptima = SolucionOptima(CJ_ZJ, TotalvariablesValidas, opcion) If SolOptima = False Then DataGridView2.Rows(pos2 + 1).Cells(Totalvariables + 2).Value = "NO SO" Else DataGridView2.Rows(pos2 + 1).Cells(Totalvariables + 2).Value = "SO" ListBox1.Items.Clear() ListBox1.Items.Add(" RESULTADOS") For fila = 0 To nrestric - 1 ListBox1.Items.Add(NombresVB(fila) & " = " & M1(fila, 0)) Next Exit Sub

Page 174: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -918-

End If ColPivote = Primeradecision(CJ_ZJ, Totalvariables, opcion) For fila = 0 To nrestric + 1 DataGridView2.Rows(Pos1 + fila).Cells(ColPivote + 2).Style.BackColor = Color.FromArgb(0, 255, 0) Next 'calcular(Ratio) For fila = 0 To nrestric - 1 Ratio(fila) = M1(fila, 0) / M1(fila, ColPivote) Next ImprimirVector2(Ratio, Pos1, Totalvariables + 2, nrestric) FilaPivote = SegundaDecision(Ratio, nrestric) pivote = M1(FilaPivote, ColPivote) For col = 0 To Totalvariables + 2 DataGridView2.Rows(Pos1 + FilaPivote).Cells(col).Style.BackColor = Color.FromArgb(255, 125, 0) Next DataGridView2.Rows(Pos1 + FilaPivote).Cells(ColPivote + 2).Style.BackColor = Color.FromArgb(255, 255, 0) Loop While SolOptima = False End Sub

Private Sub MnuGuardarExcel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuGuardarExcel.Click Dim swEscritor As StreamWriter SaveFileDialog1.ShowDialog() swEscritor = New StreamWriter(SaveFileDialog1.FileName) For fila = 0 To DataGridView2.RowCount - 1 For col = 0 To DataGridView2.ColumnCount - 1 swEscritor.Write("{0}{1}", DataGridView2.Rows(fila).Cells(col).Value, Chr(9)) Next swEscritor.WriteLine() Next swEscritor.Close() End Sub

Private Sub MnuGuardar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuGuardar.Click Dim swEscritor As StreamWriter SaveFileDialog1.ShowDialog() swEscritor = New StreamWriter(SaveFileDialog1.FileName) For fila = 0 To DataGridView1.RowCount - 1 For col = 0 To DataGridView1.ColumnCount - 1 swEscritor.Write("{0}{1}", DataGridView1.Rows(fila).Cells(col).Value, Chr(9)) Next swEscritor.WriteLine() Next swEscritor.Close() End Sub

Private Sub AnalisisSensibilidad1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AnalisisSensibilidad.Click

Page 175: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -919-

Form2.DataGridView1.ColumnCount = 8 Form2.DataGridView1.RowCount = 9 Form2.DataGridView1.Rows(0).Cells(0).Value = "Variable decision" Form2.DataGridView1.Rows(0).Cells(1).Value = "Valor Sol" Form2.DataGridView1.Rows(0).Cells(2).Value = "CJ" Form2.DataGridView1.Rows(0).Cells(3).Value = "Total Contr" Form2.DataGridView1.Rows(0).Cells(4).Value = "Costo reducido" Form2.DataGridView1.Rows(0).Cells(5).Value = "VB" Form2.DataGridView1.Rows(0).Cells(6).Value = "Min" Form2.DataGridView1.Rows(0).Cells(7).Value = "Max" For fila = 0 To nvar Next Form2.Show() End SubEnd Class

APLICACCION DEL programa a los siguientes problemas

Problema de confecciones

Plan de Producción de Confecciones

ProductoTraje

Vestido

Cantidad a producir 50 175ganancia

Margen de Contribución 200 150 36250Restricciones Total LI Disp Holgura

Lana 3 2 500<= 500 - .000.

Algodón 1 2 400<= 400 - .000.

Maximizar (z) = 200x1+ 150x2Sujeto a:3x1 +2x2 <=500 (lana)X1+2x2<=400 (algodón)X1,x2>=0Solucioin

Page 176: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -920-

Page 177: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -921-

Problema de mimimizacion problema dela dieta

Variable x1 x2

Productos Panqueso

Cantidad 1 1 CostoCosto 4 12 16

Restricciones UsadoRequerido ld Exceso

Calorías 2500 5000 7500 7000 >= -500Proteínas 50 200 250 250 >= 0

Forma originalMin (z) = 4x1+12x2s.a 2500x1+5000x2 >=7000 ( calorias)

50x1+200x2≥ 250 (proteinas)X1,X2 ≥0

Forma estándar ( o aumentada con variables artificiales)Min (z) = 4x1+12x2-0u1-0u2+Mq1+Mq2s.a 2500x1+5000x2 –u1+Mq1 =7000 ( calorias)

Page 178: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -922-

Ejercicio Calcule la solución del siguiente problema

Una compañía manufacturera fabrica 2 productos 1 y 2 y es lo suficientemente afortunada como para vender todo lo que se puede producir actualmente se tiene como dato el siguiente Requerimientos de tiempo de manufacturación para producir una unidad de producto por departamentoProducto tiempo de manufactura horas

Depto A Depto B Depto C Utilidad1 2 1 4 102 2 2 2 15Horas Disponibles 160 120 280

Sea x1 la cantidad a producir del producto 1Sea x2 la cantidad a producir del producto 2

El Modelo es

Max(z) = 10x1+ 15x2Sujeto a: 2x1+ 2x2 <=160 ( Depto A) X1+2x2 <=120 ( depto B)4x1+ 2x2 <=280X1, x2 > =0

Page 179: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -923-

11.25 APLICACIÓN DEL MODELOS DEL SIMPLEX METODO GRAFICO

La siguiente aplicación permite resolver los problemas por el método grafico con n restricciones y muestra la solución se puede cambiar las escalas

Solución del problema de los productos por el método gráfico

Solucion del problema de confecciones por el método gráfico

Page 180: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -924-

Problema de minimización

CODIGO DEL MODULO

Module Module2 Public mayor As Single Public rUnidadX As Single Public UnidadX As Single Public UnidadY As Single Public ValorMaximoX As Single Public ValorMaximoY As Single Public tipofo As Integer ' es maximizacion o miminimizacion Public dx As Single ' nro de decimales Public Zmaximo As Single Public maxx1 As Single, maxx2 As Single Public Const paso As Integer = 30 Public Const maxfilas As Integer = 5 Public M1(maxfilas, 2) As Single ' matriz de los coefecientes Public CJ(2) As Single ' coefecientes de la funcion objetiva Public B(maxfilas) As Single ' coefecientes de los recursos Public col As Integer Public fila As Integer Public filaIni As Integer = 1 Public numerador As Single Public denominador As Single Public dato As Single Public Grafico As Graphics Public ColorFondo As Color = Color.FromArgb(255, 255, 255) Public pen As Pen Public brocha As Brush Public ancho = 600, alto = 400 Public Cx As Integer = paso Public Cy As Integer = alto Public ex As Single = 2 Public ey As Single = -2

Page 181: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -925-

Public r1 As Single, r2 As Single Public x1 As Single, x2 As Single, x1a As Single, x2a As Single, z As Single Public r(maxfilas) As Single, menor As Single Public resultado As String Public k As IntegerEnd Module

CODIGO DEL MODULO

Module Module1 Public nrestric As Integer Public nva As Integer ' nro de variables artificiales Public nvar As Integer Function probarlineaMax(ByVal x1 As Single, ByVal y1 As Single, ByVal x2 As Single, ByVal y2 As Single _ , ByVal valor As Single, ByVal C() As Single, ByVal B() As Single, ByRef x As Single, ByRef y As Single) Dim xx As Single, yy As Single Dim factible As Integer = 0 Dim menor As Single = Zmaximo Dim fila1 As Integer xx = x1 yy = (valor - C(0) * xx) / C(1) While yy >= 0 menor = Zmaximo For fila1 = 0 To nrestric - 1 r(fila1) = B(fila1) - (xx * M1(fila1, 0) + yy * M1(fila1, 1)) If r(fila1) < menor Then menor = r(fila1) End If Next If menor >= 0 Then factible = 1 x = xx y = yy Exit While Else xx = xx + dx yy = (valor - C(0) * xx) / C(1) End If End While probarlineaMax = factible End Function

Function probarlineaMin(ByVal x1 As Single, ByVal y1 As Single, ByVal x2 As Single, ByVal y2 As Single _ , ByVal valor As Single, ByVal C() As Single, ByVal B() As Single, ByRef x As Single, ByRef y As Single) Dim xx As Single, yy As Single Dim factible As Integer = 0 Dim fila1 As Integer xx = x1

Page 182: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -926-

yy = (valor - C(0) * xx) / C(1) While yy >= 0 menor = Zmaximo For fila1 = 0 To nrestric - 1 r(fila1) = (xx * M1(fila1, 0) + yy * M1(fila1, 1)) - B(fila1) If r(fila1) < menor Then menor = r(fila1) End If Next If menor >= 0 Then factible = 1 x = xx y = yy Exit While Else xx = xx + dx yy = (valor - C(0) * xx) / C(1) End If End While probarlineaMin = factible End FunctionEnd Module

CODIGO DEL FORMULARIO

Option Explicit OnImports System.DrawingPublic Class Form1 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load tipofo = 1 ' maximizacion nrestric = 3 nvar = 2 Grafico = PictureBox1.CreateGraphics PictureBox1.Width = ancho + paso PictureBox1.Height = alto + paso PictureBox1.BackColor = ColorFondo pen = New Pen(Color.Blue, 2) dx = 0.1 End Sub

Private Sub PictureBox1_MouseMove(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseMove If e.Button = Windows.Forms.MouseButtons.Left Then Me.Text = "X = " & e.X & "Y= " & e.Y ListBox1.Items.Clear() x1 = (e.X - Cx) / ex x2 = -(Cy - e.Y) / ey z = CJ(0) * x1 + CJ(1) * x2 ListBox1.Items.Add("X1 " & x1) ListBox1.Items.Add("X2 " & x2) ListBox1.Items.Add("Z " & z)

Page 183: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -927-

menor = 1000 Select Case tipofo Case 1 For fila = 0 To nrestric - 1 r(fila) = B(fila) - (x1 * M1(fila, 0) + x2 * M1(fila, 1)) ListBox1.Items.Add("r " & fila + 1 & " = " & r(fila)) If r(fila) < menor Then menor = r(fila) End If Next ListBox1.Items.Add("menor " & menor) If menor < 0 Then ListBox1.Items.Add("INFACTIBLE") Else ListBox1.Items.Add("FACTIBLE") End If Case 2 For fila = 0 To nrestric - 1 r(fila) = (x1 * M1(fila, 0) + x2 * M1(fila, 1)) - B(fila) ListBox1.Items.Add("r " & fila + 1 & " = " & r(fila)) If r(fila) < menor Then menor = r(fila) End If Next ListBox1.Items.Add("menor " & menor) If menor < 0 Then ListBox1.Items.Add("INFACTIBLE") Else ListBox1.Items.Add("FACTIBLE") End If End Select End If End Sub

Sub ImprimirMatriz(ByRef A(,) As Single, ByVal Cy As Integer, ByVal Cx As Integer, ByVal nf As Integer, ByVal nc As Integer) For fila = 0 To nf - 1 For col = 0 To nc - 1 DataGridView2.Rows(Cy + fila).Cells(Cx + col).Value = A(fila, col) Next col Next fila End Sub Sub ImprimirVector(ByVal A() As Single, ByVal Cy As Integer, ByVal Cx As Integer, ByVal Nc As Integer) For col = 0 To Nc - 1 DataGridView2.Rows(Cy).Cells(Cx + col).Value = A(col) Next End Sub

Private Sub MnuIniciar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuIniciar.Click ' solo trabaja para caso de dos variables

Page 184: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -928-

Try DataGridView1.RowCount = nrestric + filaIni + 2 DataGridView1.ColumnCount = 4 DataGridView1.Columns(0).HeaderCell.Value = "Variable" For col = 1 To nvar DataGridView1.Columns(col).HeaderCell.Value = "X" & col Next DataGridView1.Rows(0).Cells(0).Value = " Margen Contr" DataGridView1.Rows(1).Cells(0).Value = " Restricciones" DataGridView1.Rows(1).Cells(nvar + 1).Value = " Disponib" For col = 1 To nrestric DataGridView1.Rows(1 + col).Cells(0).Value = "R" & col Next DataGridView1.Rows(0).Cells(1).Value = 4 DataGridView1.Rows(0).Cells(2).Value = 12 DataGridView1.Rows(2).Cells(1).Value = 2500 DataGridView1.Rows(2).Cells(2).Value = 5000 DataGridView1.Rows(2).Cells(3).Value = 7000 DataGridView1.Rows(3).Cells(1).Value = 50 DataGridView1.Rows(3).Cells(2).Value = 200 DataGridView1.Rows(3).Cells(3).Value = 250 ' obtenemos la matriz M1 y B Catch ex As Exception MsgBox(ex.Message) End Try End Sub

Private Sub MnuIniciarGrafico_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuIniciarGrafico.Click DataGridView2.RowCount = nrestric + 3 DataGridView2.ColumnCount = 5 For fila = 0 To nrestric - 1 B(fila) = DataGridView1.Rows(2 + fila).Cells(3).Value For col = 0 To 1 M1(fila, col) = DataGridView1.Rows(2 + fila).Cells(1 + col).Value Next Next ' obtenemos la matriz CJ For col = 0 To 1 CJ(col) = DataGridView1.Rows(0).Cells(1 + col).Value Next ' solo son dos variables DataGridView2.Rows(0).Cells(0).Value = "RESTRICIONES" DataGridView2.Rows(0).Cells(1).Value = "X1" DataGridView2.Rows(0).Cells(2).Value = "X2" DataGridView2.Rows(0).Cells(3).Value = "X1a" DataGridView2.Rows(0).Cells(4).Value = "X2a" ' obtnenemos los maximos de x1 y x2 maxx1 = -1000 maxx2 = -1000 For fila = 0 To nrestric - 1 DataGridView2.Rows(fila + filaIni).Cells(0).Value = "R" & fila + 1

Page 185: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -929-

DataGridView2.Rows(fila + filaIni).Cells(1).Value = 0 numerador = DataGridView1.Rows(fila + filaIni + 1).Cells(3).Value denominador = DataGridView1.Rows(fila + filaIni + 1).Cells(2).Value dato = numerador / denominador If dato > maxx1 Then maxx1 = dato DataGridView2.Rows(filaIni + fila).Cells(2).Value = dato DataGridView2.Rows(filaIni + fila).Cells(4).Value = 0 ' si x2=0 denominador = DataGridView1.Rows(fila + filaIni + 1).Cells(1).Value dato = numerador / denominador If dato > maxx2 Then maxx2 = dato DataGridView2.Rows(filaIni + fila).Cells(3).Value = dato Next DataGridView2.Rows(nrestric + filaIni).Cells(0).Value = "maximo" DataGridView2.Rows(nrestric + filaIni).Cells(2).Value = maxx1 DataGridView2.Rows(nrestric + filaIni).Cells(3).Value = maxx2 Zmaximo = CJ(0) * maxx1 + CJ(1) * maxx2 If maxx1 > maxx2 Then mayor = maxx1 Else mayor = maxx2 End If ValorMaximoX = mayor ValorMaximoY = mayor ex = ancho / ValorMaximoX ey = -ex TextBox1.Text = ex TextBox2.Text = ey TextBox3.Text = ValorMaximoX TextBox4.Text = ValorMaximoY rUnidadX = ex UnidadX = 1 While rUnidadX > 1000 rUnidadX = rUnidadX / 10 UnidadX = UnidadX / 10 End While While rUnidadX < 10 rUnidadX = rUnidadX * 10 UnidadX = UnidadX * 10 End While Unidady = UnidadX TextBox5.Text = UnidadX TextBox6.Text = Unidady End Sub

Private Sub MnuGraficar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuGraficar.Click Dim fila1 As Single Dim col1 As Single ex = TextBox1.Text ey = TextBox2.Text UnidadX = TextBox5.Text

Page 186: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -930-

UnidadY = TextBox6.Text Borrar(sender, e) ' graficar la escala de x Dim MiFuente As New Font("Arial", 10, FontStyle.Bold) Dim Penciles(3) As Color Dim Brocha As SolidBrush = New SolidBrush(Color.LightGreen) pen = New Pen(Color.Blue, 2) Penciles(0) = Color.FromArgb(255, 0, 0) Penciles(1) = Color.FromArgb(0, 0, 255) Penciles(2) = Color.FromArgb(0, 255, 0) Penciles(3) = Color.FromArgb(255, 0, 255) Cx = paso Cy = alto Try Grafico.DrawLine(pen, Cx, 0, Cx, Cy) Grafico.DrawLine(pen, Cx, Cy, Cx + ancho, Cy) Grafico.DrawString("X1", MiFuente, Brushes.Red, ancho - paso, Cy) Grafico.DrawString("X2", MiFuente, Brushes.Green, Cx - paso, paso) fila = 0 For fila = 0 To nrestric - 1 pen.Color = Penciles(fila) Brocha.Color = Penciles(fila) x1 = DataGridView2.Rows(1 + fila).Cells(1).Value x2 = DataGridView2.Rows(1 + fila).Cells(2).Value x1a = DataGridView2.Rows(1 + fila).Cells(3).Value x2a = DataGridView2.Rows(1 + fila).Cells(4).Value Grafico.DrawLine(pen, Cx + x1 * ex, Cy + x2 * ey, Cx + x1a * ex, Cy + x2a * ey) Grafico.DrawString("R" & fila + 1, MiFuente, Brocha, Cx + x1 * ex, Cy + x2 * ey) Next For col1 = 0 To ValorMaximoX Step UnidadX Grafico.DrawString(col1, MiFuente, Brushes.Blue, Cx + col1 * ex, Cy) Next For fila1 = 0 To ValorMaximoY Step UnidadY Grafico.DrawString(fila1, MiFuente, Brushes.Blue, Cx - paso, Cy + fila1 * ey) Next Catch ex As Exception MsgBox(ex.Message) End Try End Sub

Private Sub MnuResolver_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuResolver.Click Dim valor As Single Dim resultado As Integer Dim x As Single, y As Single pen.Color = Color.Red Dim delta As Single = Zmaximo / 10 Select Case tipofo Case 1 For valor = 0 To Zmaximo Step dx x1 = 0 x2 = valor / CJ(1)

Page 187: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -931-

x1a = valor / CJ(0) x2a = 0 resultado = probarlineaMax(x1, x2, x1a, x2a, valor, CJ, B, x, y) If valor Mod delta = 0 Then Grafico.DrawLine(pen, Cx + x1 * ex, Cy + x2 * ey, Cx + x1a * ex, Cy + x2a * ey) End If If resultado = 0 Then ListBox1.Items.Clear() ListBox1.Items.Add("X1 " & x) ListBox1.Items.Add("X2 " & y) ListBox1.Items.Add("Z " & valor - 1) Exit Sub End If Next Case 2 For valor = Zmaximo * 10 To 0 Step -dx x1 = 0 x2 = valor / CJ(1) x1a = valor / CJ(0) x2a = 0 resultado = probarlineaMin(x1, x2, x1a, x2a, valor, CJ, B, x, y) If valor Mod 1 = 0 Then Grafico.DrawLine(pen, Cx + x1 * ex, Cy + x2 * ey, Cx + x1a * ex, Cy + x2a * ey) End If If resultado = 0 Then ListBox1.Items.Clear() ListBox1.Items.Add("X1 " & x) ListBox1.Items.Add("X2 " & y) z = CJ(0) * x + CJ(1) * y ListBox1.Items.Add("Z " & z) Exit Sub End If Next End Select End Sub

Private Sub MnuRellenar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuRellenar.Click pen.Color = Color.FromArgb(0, 255, 0) Dim menor As Single = Zmaximo Dim xx As Single, yy As Single Dim fex As Single = (1.0 / ex) * 5 Dim fey As Single = (1.0 / -ey) * 5 Select Case tipofo Case 1 ' cuando es maximizacion For yy = 0 To ValorMaximoY Step UnidadX / 10 For xx = 0 To ValorMaximoX Step UnidadY / 10 z = CJ(0) * xx + CJ(1) * yy menor = Zmaximo For k = 0 To nrestric - 1 r(k) = B(k) - (xx * M1(k, 0) + yy * M1(k, 1)) If r(k) < menor Then

Page 188: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -932-

menor = r(k) End If Next If menor >= 0 Then Grafico.DrawRectangle(pen, Cx + xx * ex, Cy + yy * ey, 1, 1) End If Next xx Next yy

Case 2 ' cuando es minimizacion For x2a = 0 To ValorMaximoY Step fex For x1a = 0 To ValorMaximoX Step fey z = CJ(0) * x1a + CJ(1) * x2a menor = Zmaximo For k = 0 To nrestric - 1 r(k) = (x1a * M1(k, 0) + x2a * M1(k, 1)) - B(k) If r(k) < menor Then menor = r(k) End If Next If menor >= 0 Then Grafico.DrawRectangle(pen, Cx + x1a * ex, Cy + x2a * ey, 1, 1) End If Next Next End Select End Sub

Private Sub Borrar(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BorrarToolStripMenuItem.Click Grafico.Clear(Color.White) End Sub

Private Sub NroDeRestriccionesToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NroDeRestriccionesToolStripMenuItem.Click nrestric = InputBox("INGRES NRO DE RESTRICCIONES", "nrestric", 2) End Sub Private Sub MaximizacionToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MaximizacionToolStripMenuItem.Click tipofo = 1 End Sub Private Sub MinimizacionToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MinimizacionToolStripMenuItem.Click tipofo = 2 End Sub Private Sub MnuCero_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuCero.Click dx = 1 End Sub

Page 189: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -933-

Private Sub Mnu1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Mnu1.Click dx = 0.1 End Sub

Private Sub MnuDos_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MnuDos.Click dx = 0.01 End Sub

Private Sub mnu3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnu3.Click dx = 0.001 End SubEnd Class

11.27 GRAFICA DE FUNCIONES EN 2D Y 3D

Module Module1

Page 190: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -934-

Public Structure Puntos Public nro As Integer Public X As Single Public Y As Single Public Z As Single Public Rela As Integer End Structure

Public modo As Integer = 1 Public Gradosx As Single = 0 Public Gradosy As Single = 0 Public Gradosz As Single = 0 Public MP(maxfilas, maxcol) As Puntos Public MP1(maxfilas, maxcol) As Puntos Public brocha As SolidBrush Public Const maxcol As Integer = 1000 Public Const maxfilas As Integer = 1000 Public Const maximo As Integer = 8000 Public cont As Integer = 0 Public Cx As Single = 200 Public Cy As Single = 200 Public Cz As Single = 0 Public D As Single = 200 Public dx As Single Public dy As Single Public Ex As Single = 40 Public Ey As Single = -40 Public Ez As Single = 20 Public GPencil As Integer = 1 Public Grafico As Graphics Public Indice As Integer = 1 Public k As Integer Public lix As Single = -5 Public liy As Single = -5 Public lsx As Single = 5 Public lsy As Single = 5 Public nc As Integer = 20 Public nf As Integer = 20 Public np As Integer = 1000 Public Pen As Pen

Public vel As Integer = 10 Public Sub Copiar(MP(,) As Puntos, ByRef MP1(,) As Puntos, nf As Integer, nc As Integer) Dim fila, col As Integer For fila = 0 To nf - 1 For COL = 0 To nc - 1 MP1(fila, COL).X = MP(fila, COL).X MP1(fila, COL).Y = MP(fila, COL).Y MP1(fila, COL).Z = MP(fila, COL).Z Next Next

Page 191: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -935-

End Sub Public Sub escalar(Ex As Single, ey As Single, ez As Single) For fila = 0 To nf - 1 For COL = 0 To nc - 1 MP1(fila, COL).X = MP1(fila, COL).X * Ex MP1(fila, COL).Y = MP1(fila, COL).Y * ey MP1(fila, COL).Z = MP1(fila, COL).Z * ez Next Next End Sub Function f(x As Single) Return x * x End Function Function f3d(x As Single, y As Single) If ((x * x + y * y)) > 0 Then Return Math.Sin(x * x + y * y) / (x * x + y * y) Else Return 1 End If End Function End Module

Imports System.IOPublic Class Form1 Private Sub btnIniciar_Click(sender As Object, e As EventArgs) Handles btnIniciar.Click DataGridView1.RowCount = 8 DataGridView1.ColumnCount = 4 DataGridView1.Columns(0).HeaderText = "PARAMETROS" DataGridView1.Columns(1).HeaderText = "X (min)" DataGridView1.Columns(2).HeaderText = "Y (Max)" DataGridView1.Columns(3).HeaderText = "Z"

DataGridView1.Columns(0).Width = 100 DataGridView1.Columns(1).Width = 40 DataGridView1.Columns(2).Width = 40 DataGridView1.Columns(3).Width = 40

DataGridView1.Rows(0).Cells(0).Value = "nc, nf ,D" DataGridView1.Rows(0).Cells(1).Value = nf DataGridView1.Rows(0).Cells(2).Value = nc DataGridView1.Rows(0).Cells(3).Value = D

DataGridView1.Rows(1).Cells(0).Value = "Lim Inferior" DataGridView1.Rows(1).Cells(1).Value = lix DataGridView1.Rows(1).Cells(2).Value = liy

DataGridView1.Rows(2).Cells(0).Value = "Lim Superior" DataGridView1.Rows(2).Cells(1).Value = lsx DataGridView1.Rows(2).Cells(2).Value = lsy

DataGridView1.Rows(3).Cells(0).Value = "Cx Cy,Cz"

Page 192: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -936-

DataGridView1.Rows(3).Cells(1).Value = Cx DataGridView1.Rows(3).Cells(2).Value = Cy DataGridView1.Rows(3).Cells(3).Value = Cz

DataGridView1.Rows(4).Cells(0).Value = "Ex Ey Ez" DataGridView1.Rows(4).Cells(1).Value = Ex DataGridView1.Rows(4).Cells(2).Value = Ey DataGridView1.Rows(4).Cells(3).Value = Ez

DataGridView1.Rows(5).Cells(0).Value = "Rot Ax Ay Az" DataGridView1.Rows(5).Cells(1).Value = Gradosx DataGridView1.Rows(5).Cells(2).Value = Gradosy DataGridView1.Rows(5).Cells(3).Value = Gradosz

DataGridView1.Rows(6).Cells(0).Value = "Grosor pencil Modo" DataGridView1.Rows(6).Cells(1).Value = GPencil DataGridView1.Rows(6).Cells(2).Value = Indice DataGridView1.Rows(6).Cells(3).Value = modo

DataGridView1.Rows(7).Cells(0).Value = "Dx Dy vel" DataGridView1.Rows(7).Cells(1).Value = dx DataGridView1.Rows(7).Cells(2).Value = dy DataGridView1.Rows(7).Cells(3).Value = vel

For fila = 0 To DataGridView1.RowCount - 1 DataGridView1.Rows(fila).HeaderCell.Value = fila.ToString Next End Sub Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load Grafico = PictureBox1.CreateGraphics Pen = New Pen(Color.Red, 2) brocha = New SolidBrush(Color.FromArgb(0, 255, 0)) End Sub Private Sub btnGenerar_Click(sender As Object, e As EventArgs) Handles btnGenerar.Click Dim col As Integer Dim x, y As Single x = lix For col = 0 To nc - 1 y = f(x) DataGridView2.Rows(col).Cells(0).Value = x DataGridView2.Rows(col).Cells(1).Value = y x = x + dx Next End Sub Private Sub BtnIniciarTodo_Click(sender As Object, e As EventArgs) Handles BtnIniciarTodo.Click BtnBorrar_Click(sender, e) nc = DataGridView1.Rows(0).Cells(1).Value nf = DataGridView1.Rows(0).Cells(2).Value D = DataGridView1.Rows(0).Cells(3).Value lix = DataGridView1.Rows(1).Cells(1).Value

Page 193: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -937-

liy = DataGridView1.Rows(1).Cells(2).Value lsx = DataGridView1.Rows(2).Cells(1).Value lsy = DataGridView1.Rows(2).Cells(2).Value

Cx = DataGridView1.Rows(3).Cells(1).Value Cy = DataGridView1.Rows(3).Cells(2).Value Cz = DataGridView1.Rows(3).Cells(3).Value

Ex = DataGridView1.Rows(4).Cells(1).Value Ey = DataGridView1.Rows(4).Cells(2).Value Ez = DataGridView1.Rows(4).Cells(3).Value

Gradosx = DataGridView1.Rows(5).Cells(1).Value Gradosy = DataGridView1.Rows(5).Cells(2).Value Gradosz = DataGridView1.Rows(5).Cells(3).Value

GPencil = DataGridView1.Rows(6).Cells(1).Value Indice = DataGridView1.Rows(6).Cells(2).Value modo = DataGridView1.Rows(6).Cells(3).Value

dx = (lsx - lix) / nc dy = (lsy - liy) / nf DataGridView1.Rows(7).Cells(1).Value = dx DataGridView1.Rows(7).Cells(2).Value = dy

dx = DataGridView1.Rows(7).Cells(1).Value dy = DataGridView1.Rows(7).Cells(2).Value vel = DataGridView1.Rows(7).Cells(3).Value

DataGridView2.RowCount = nf + 1 DataGridView2.ColumnCount = 2 DataGridView2.Columns(0).Width = 40 DataGridView2.Columns(1).Width = 50 DataGridView2.Columns(0).HeaderText = "X" DataGridView2.Columns(1).HeaderText = "Y" For fila = 0 To DataGridView2.RowCount - 1 DataGridView2.Rows(fila).HeaderCell.Value = fila.ToString Next GenerarGrabar(sender, e) escalar(Ex, Ey, Ez) rotar(Gradosx, Gradosy, Gradosz) grafico3d() End Sub Private Sub btnGraficar_Click(sender As Object, e As EventArgs) Handles btnGraficar.Click Dim x1, y1, x2, y2 As Single Pen.Width = GPencil With DataGridView2 For col = 0 To nc - 2 x1 = CSng(.Rows(col).Cells(0).Value) y1 = CSng(.Rows(col).Cells(1).Value) x2 = CSng(.Rows(col + 1).Cells(0).Value)

Page 194: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -938-

y2 = CSng(.Rows(col + 1).Cells(1).Value) Grafico.DrawLine(Pen, Cx + x1 * Ex, Cy + y1 * Ey, Cx + x2 * Ex, Cy + y2 * Ey) Next End With End Sub Private Sub BtnBorrar_Click(sender As Object, e As EventArgs) Handles BtnBorrar.Click Grafico.Clear(Color.White) End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnCoordenadas.Click Pen.Color = Color.Blue Grafico.DrawLine(Pen, 0, Cy, PictureBox1.Width, Cy) Grafico.DrawLine(Pen, Cx, 0, Cx, PictureBox1.Height) Pen.Color = Color.Red End Sub Sub grafico3d() Dim Color1 As Integer Dim AX As Single, Ay As Single, Az As Single, Bx As Single, By As Single, Bz As Single Dim NX As Single, Ny As Single, Nz As Single, Nx1 As Single, Ny1 As Single, Nz1 As Single Dim R As Single Dim Pe As Single Dim x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4 As Single Dim px1, py1, px2, py2, px3, py3, px4, py4 As Single Dim fila, col As Integer Dim Puntos(3) As Point For fila = 0 To nf - 3 For col = 0 To nc - 3 x1 = MP1(fila, col).X y1 = MP1(fila, col).Y z1 = MP1(fila, col).Z x2 = MP1(fila, col + 1).X y2 = MP1(fila, col + 1).Y z2 = MP1(fila, col + 1).Z

x3 = MP1(fila + 1, col + 1).X y3 = MP1(fila + 1, col + 1).Y z3 = MP1(fila + 1, col + 1).Z x4 = MP1(fila + 1, col).X y4 = MP1(fila + 1, col).Y z4 = MP1(fila + 1, col).Z '******************* px1 = Cx + (x1 * D) / (D + z1) py1 = Cy + (y1 * D) / (D + z1)

px2 = Cx + (x2 * D) / (D + z2) py2 = Cy + (y2 * D) / (D + z2) px3 = Cx + (x3 * D) / (D + z3) py3 = Cy + (y3 * D) / (D + z3)

Page 195: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -939-

px4 = Cx + (x4 * D) / (D + z4) py4 = Cy + (y4 * D) / (D + z4) Puntos(0).X = px1 Puntos(0).Y = py1 Puntos(1).X = px2 Puntos(1).Y = py2 Puntos(2).X = px3 Puntos(2).Y = py3 Puntos(3).X = px4 Puntos(3).Y = py4 ' *************************** AX = x2 - x1 Ay = y2 - y1 Az = z2 - z1 Bx = x3 - x2 By = y3 - y2 Bz = z3 - z2 NX = Ay * Bz - Az * By Ny = AX * Bz - Az * Bx Nz = AX * By - Ay * Bx 'PRODUCTO(CRUZ) R = Math.Sqrt(NX * NX + Ny * Ny + Nz * Nz) If R > 0 Then Nx1 = NX / R Else Nx1 = 1000 End If If R > 0 Then Ny1 = Ny / R Else Ny1 = 1000 End If If R > 0 Then Nz1 = Nz / R Else Nz1 = 1000 End If Pe = Nx1 * 0 + Ny1 * 0 + Nz1 * D Grafico.DrawPolygon(Pen, Puntos) If modo = 1 Then If Nz1 <= 0 Then Color1 = -Nz1 * 255 brocha.Color = Color.FromArgb(0, Color1, 0) Grafico.FillPolygon(brocha, Puntos, Drawing2D.FillMode.Alternate) End If End If Next Next End Sub Private Sub btnGrafica3D_Click(sender As Object, e As EventArgs) Handles btnGrafica3D.Click

Page 196: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -940-

grafico3d() End Sub Private Sub GenerarGrabar(sender As Object, e As EventArgs) Handles btnGenerarGrabar.Click Dim x, y, z1 As Single Dim fila, col As Integer Pen.Width = GPencil dx = (lsx - lix) / nc dy = (lsy - liy) / nf cont = 0 'generamos los puntos y = liy For fila = 0 To nf - 1 x = lix For col = 0 To nc - 1 z1 = f3d(x, y) MP(fila, col).nro = cont MP(fila, col).X = x MP(fila, col).Y = y MP(fila, col).Z = z1 x = x + dx cont = cont + 1 Next y = y + dy Next np = cont Dim archivo As StreamWriter archivo = New StreamWriter("E:\datos\Mp20x20.txt") ' grabamos los puntos de la matriz y mostramos For fila = 0 To nf - 1 For col = 0 To nc - 1 archivo.Write("{0}{1}", MP(fila, col).Z, Chr(9)) Next archivo.WriteLine() Next archivo.Close() Copiar(MP, MP1, nf, nc) End Sub

Sub rotar(gradosx As Single, gradosy As Single, gradosz As Single) Dim x1 As Single, y1 As Single, z1 As Single Dim x2 As Single, y2 As Single, z2 As Single Dim fila As Integer = 0 Dim col As Integer = 0 Dim Ax, Ay, Az As Single ' rotacion x Ax = gradosx * Math.PI / 180 For fila = 0 To nf - 1 For col = 0 To nc - 1 x1 = MP1(fila, col).X y1 = MP1(fila, col).Y z1 = MP1(fila, col).Z

Page 197: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -941-

x2 = x1 y2 = y1 * Math.Cos(Ax) - z1 * Math.Sin(Ax) z2 = y1 * Math.Sin(Ax) + z1 * Math.Cos(Ax) MP1(fila, col).X = x2 MP1(fila, col).Y = y2 MP1(fila, col).Z = z2 Next Next ' rotacion y Ay = gradosy * Math.PI / 180 For fila = 0 To nf - 1 For col = 0 To nc - 1 x1 = MP1(fila, col).X y1 = MP1(fila, col).Y z1 = MP1(fila, col).Z ' rotacion y x2 = x1 * Math.Cos(Ay) + z1 * Math.Sin(Ay) y2 = y1 z2 = -x1 * Math.Sin(Ay) + z1 * Math.Cos(Ay) MP1(fila, col).X = x2 MP1(fila, col).Y = y2 MP1(fila, col).Z = z2 Next Next

' rotacion z Az = gradosz * Math.PI / 180 For fila = 0 To nf - 1 For col = 0 To nc - 1 x1 = MP1(fila, col).X y1 = MP1(fila, col).Y z1 = MP1(fila, col).Z x2 = x1 * Math.Cos(Az) - y1 * Math.Sin(Az) y2 = x1 * Math.Sin(Az) + y1 * Math.Cos(Az) z2 = z1 MP1(fila, col).X = x2 MP1(fila, col).Y = y2 MP1(fila, col).Z = z2 Next Next End Sub Private Sub btnVerDatos_Click(sender As Object, e As EventArgs) Handles btnVerosDatos.Click Form2.DataGridView1.ColumnCount = nc + 1 Form2.DataGridView1.RowCount = nf + 1 For col = 0 To nc Form2.DataGridView1.Columns(col).Width = 70 Next For fila = 0 To nf - 1 For col = 0 To nc - 1 Form2.DataGridView1.Rows(fila).Cells(col).Value = MP1(fila, col).Z Next

Page 198: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -942-

Next Form2.Show() End Sub Private Sub TextBox1_KeyDown_1(sender As Object, e As KeyEventArgs) Handles TextBox1.KeyDown Select Case e.KeyCode Case Keys.Left Gradosx = Gradosx - 1 Case Keys.Right Gradosx = Gradosx + 1 Case Keys.Up Gradosy = Gradosy - 1 Case Keys.Down Gradosy = Gradosy + 1 Case 90 'Z Gradosz = Gradosz + 1 Case 87 'W Gradosz = Gradosz - 1 End Select DataGridView1.Rows(5).Cells(1).Value = Gradosx DataGridView1.Rows(5).Cells(2).Value = Gradosy DataGridView1.Rows(5).Cells(3).Value = Gradosz BtnBorrar_Click(sender, e) BtnIniciarTodo_Click(sender, e) TextBox1.Text = "" End SubEnd Class

11.28 GENERACION DE MONTAÑAS CON AUTOMATAS CELULARES(corregir)

CODIGO DEL MODULO

Imports System.IOModule Module1 Public Structure Puntos Public nro As Integer Public X As Single

Page 199: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -943-

Public Y As Single Public Z As Single Public Rela As Integer End Structure Public Nvecinos1 As Integer = 3 Public altura As Single = 10 Public niter As Integer = 100 Public Vinicial As Single = 0 Public vargx As Single = 0 Public vargy As Single = 0 Public vargz As Single = 0 Public aumento As Single = 10 Public modo As Integer = 0 Public Gradosx As Single = 0 Public Gradosy As Single = 0 Public Gradosz As Single = 0 Public MP(maxfilas, maxcol) As Puntos Public MP1(maxfilas, maxcol) As Puntos Public brocha As SolidBrush Public Const maxcol As Integer = 1000 Public Const maxfilas As Integer = 1000 Public Const maximo As Integer = 8000 Public cont As Integer = 0 Public Cx As Single = 200 Public Cy As Single = 200 Public Cz As Single = 0 Public D As Single = 200 Public dx As Single Public dy As Single Public Ex As Single = 20 Public Ey As Single = -20 Public Ez As Single = 20 Public GPencil As Integer = 1 Public Grafico As Graphics Public Indice As Integer = 1 Public lix As Single = -5 Public liy As Single = -5 Public lsx As Single = 5 Public lsy As Single = 5 Public nc As Integer = 20 Public nf As Integer = 20 Public np As Integer = 1000 Public Pen As Pen Public vel As Integer = 1 Public Sub Copiar(MP(,) As Puntos, ByRef MP1(,) As Puntos, nf As Integer, nc As Integer) Dim fila, col As Integer For fila = 0 To nf - 1 For COL = 0 To nc - 1 MP1(fila, COL).X = MP(fila, COL).X MP1(fila, COL).Y = MP(fila, COL).Y MP1(fila, COL).Z = MP(fila, COL).Z

Page 200: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -944-

Next Next End Sub Public Sub escalar(Ex As Single, ey As Single, ez As Single) For fila = 0 To nf - 1 For COL = 0 To nc - 1 MP1(fila, COL).X = MP1(fila, COL).X * Ex MP1(fila, COL).Y = MP1(fila, COL).Y * ey MP1(fila, COL).Z = MP1(fila, COL).Z * ez Next Next End Sub Sub rotar(gradosx As Single, gradosy As Single, gradosz As Single) Dim x1 As Single, y1 As Single, z1 As Single Dim x2 As Single, y2 As Single, z2 As Single Dim fila As Integer = 0 Dim col As Integer = 0 Dim Ax, Ay, Az As Single ' rotacion x Ax = gradosx * Math.PI / 180 For fila = 0 To nf - 1 For col = 0 To nc - 1 x1 = MP1(fila, col).X y1 = MP1(fila, col).Y z1 = MP1(fila, col).Z x2 = x1 y2 = y1 * Math.Cos(Ax) - z1 * Math.Sin(Ax) z2 = y1 * Math.Sin(Ax) + z1 * Math.Cos(Ax) MP1(fila, col).X = x2 MP1(fila, col).Y = y2 MP1(fila, col).Z = z2 Next Next ' rotacion y Ay = gradosy * Math.PI / 180 For fila = 0 To nf - 1 For col = 0 To nc - 1 x1 = MP1(fila, col).X y1 = MP1(fila, col).Y z1 = MP1(fila, col).Z ' rotacion y x2 = x1 * Math.Cos(Ay) + z1 * Math.Sin(Ay) y2 = y1 z2 = -x1 * Math.Sin(Ay) + z1 * Math.Cos(Ay) MP1(fila, col).X = x2 MP1(fila, col).Y = y2 MP1(fila, col).Z = z2 Next Next

' rotacion z

Page 201: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -945-

Az = gradosz * Math.PI / 180 For fila = 0 To nf - 1 For col = 0 To nc - 1 x1 = MP1(fila, col).X y1 = MP1(fila, col).Y z1 = MP1(fila, col).Z x2 = x1 * Math.Cos(Az) - y1 * Math.Sin(Az) y2 = x1 * Math.Sin(Az) + y1 * Math.Cos(Az) z2 = z1 MP1(fila, col).X = x2 MP1(fila, col).Y = y2 MP1(fila, col).Z = z2 Next Next End Sub Sub Iniciar() Dim x, y, z1 As Single Dim fila, col As Integer Pen.Width = GPencil dx = (lsx - lix) / nc dy = (lsy - liy) / nf cont = 0 'generamos los puntos y = liy For fila = 0 To nf - 1 x = lix For col = 0 To nc - 1 REM z1 = f3d(x, y) MP(fila, col).nro = cont MP(fila, col).X = x MP(fila, col).Y = y MP(fila, col).Z = Vinicial x = x + dx cont = cont + 1 Next y = y + dy Next np = cont Copiar(MP, MP1, nf, nc) End Sub Sub grabar() Dim archivo As StreamWriter archivo = New StreamWriter("E:\datos\Mp20x20.txt") ' grabamos los puntos de la matriz y mostramos For fila = 0 To nf - 1 For col = 0 To nc - 1 archivo.Write("{0}{1}", MP1(fila, col).Z, Chr(9)) Next archivo.WriteLine() Next archivo.Close() End Sub

Page 202: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -946-

End Module

CODIGO DEL FORMULARIO

Public Class Form1 Private Sub btnIniciar_Click(sender As Object, e As EventArgs) Handles btnIniciar.Click DataGridView1.RowCount = 10 DataGridView1.ColumnCount = 4 DataGridView1.Columns(0).HeaderText = "PARAMETROS" DataGridView1.Columns(1).HeaderText = "X (min)" DataGridView1.Columns(2).HeaderText = "Y (Max)" DataGridView1.Columns(3).HeaderText = "Z" DataGridView1.Columns(0).Width = 100 DataGridView1.Columns(1).Width = 40 DataGridView1.Columns(2).Width = 40 DataGridView1.Columns(3).Width = 40

DataGridView1.Rows(0).Cells(0).Value = "nc, nf ,D" DataGridView1.Rows(0).Cells(1).Value = nf DataGridView1.Rows(0).Cells(2).Value = nc DataGridView1.Rows(0).Cells(3).Value = D

DataGridView1.Rows(1).Cells(0).Value = "Lim Inferior" DataGridView1.Rows(1).Cells(1).Value = lix DataGridView1.Rows(1).Cells(2).Value = liy

DataGridView1.Rows(2).Cells(0).Value = "Lim Superior" DataGridView1.Rows(2).Cells(1).Value = lsx DataGridView1.Rows(2).Cells(2).Value = lsy

DataGridView1.Rows(3).Cells(0).Value = "Cx Cy,Cz" DataGridView1.Rows(3).Cells(1).Value = Cx DataGridView1.Rows(3).Cells(2).Value = Cy DataGridView1.Rows(3).Cells(3).Value = Cz

DataGridView1.Rows(4).Cells(0).Value = "Ex Ey Ez" DataGridView1.Rows(4).Cells(1).Value = Ex DataGridView1.Rows(4).Cells(2).Value = Ey DataGridView1.Rows(4).Cells(3).Value = Ez

DataGridView1.Rows(5).Cells(0).Value = "Rot Ax Ay Az" DataGridView1.Rows(5).Cells(1).Value = Gradosx DataGridView1.Rows(5).Cells(2).Value = Gradosy DataGridView1.Rows(5).Cells(3).Value = Gradosz

DataGridView1.Rows(6).Cells(0).Value = "Grosor pencil Modo" DataGridView1.Rows(6).Cells(1).Value = GPencil DataGridView1.Rows(6).Cells(2).Value = Indice DataGridView1.Rows(6).Cells(3).Value = modo

DataGridView1.Rows(7).Cells(0).Value = "Dx Dy vel"

Page 203: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -947-

DataGridView1.Rows(7).Cells(1).Value = dx DataGridView1.Rows(7).Cells(2).Value = dy DataGridView1.Rows(7).Cells(3).Value = vel

DataGridView1.Rows(8).Cells(0).Value = "Niter, Vinicial aumento" DataGridView1.Rows(8).Cells(1).Value = niter DataGridView1.Rows(8).Cells(2).Value = Vinicial DataGridView1.Rows(8).Cells(3).Value = aumento

DataGridView1.Rows(9).Cells(0).Value = "Nvecinos" DataGridView1.Rows(9).Cells(1).Value = Nvecinos1 For fila = 0 To DataGridView1.RowCount - 1 DataGridView1.Rows(fila).HeaderCell.Value = fila.ToString Next End Sub Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load Grafico = PictureBox1.CreateGraphics Pen = New Pen(Color.Red, 2) brocha = New SolidBrush(Color.FromArgb(0, 255, 0)) GroupBox1.Visible = True End Sub Private Sub BtnIniciarTodo_Click(sender As Object, e As EventArgs) Handles BtnIniciarTodo.Click BtnBorrar_Click(sender, e) nc = DataGridView1.Rows(0).Cells(1).Value nf = DataGridView1.Rows(0).Cells(2).Value D = DataGridView1.Rows(0).Cells(3).Value lix = DataGridView1.Rows(1).Cells(1).Value liy = DataGridView1.Rows(1).Cells(2).Value lsx = DataGridView1.Rows(2).Cells(1).Value lsy = DataGridView1.Rows(2).Cells(2).Value

Cx = DataGridView1.Rows(3).Cells(1).Value Cy = DataGridView1.Rows(3).Cells(2).Value Cz = DataGridView1.Rows(3).Cells(3).Value

Ex = DataGridView1.Rows(4).Cells(1).Value Ey = DataGridView1.Rows(4).Cells(2).Value Ez = DataGridView1.Rows(4).Cells(3).Value

Gradosx = DataGridView1.Rows(5).Cells(1).Value Gradosy = DataGridView1.Rows(5).Cells(2).Value Gradosz = DataGridView1.Rows(5).Cells(3).Value

GPencil = DataGridView1.Rows(6).Cells(1).Value Indice = DataGridView1.Rows(6).Cells(2).Value modo = DataGridView1.Rows(6).Cells(3).Value

niter = DataGridView1.Rows(8).Cells(1).Value Vinicial = DataGridView1.Rows(8).Cells(2).Value aumento = DataGridView1.Rows(8).Cells(3).Value

Page 204: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -948-

Nvecinos1 = DataGridView1.Rows(9).Cells(1).Value dx = (lsx - lix) / nc dy = (lsy - liy) / nf DataGridView1.Rows(7).Cells(1).Value = dx DataGridView1.Rows(7).Cells(2).Value = dy dx = DataGridView1.Rows(7).Cells(1).Value dy = DataGridView1.Rows(7).Cells(2).Value vel = DataGridView1.Rows(7).Cells(3).Value Iniciar() escalar(Ex, Ey, Ez) rotar(Gradosx, Gradosy, Gradosz) grafico3d() verdatos() End Sub Private Sub BtnBorrar_Click(sender As Object, e As EventArgs) Handles BtnBorrar.Click Grafico.Clear(Color.White) End Sub Private Sub Coordenadas(sender As Object, e As EventArgs) Handles btnCoordenadas.Click Pen.Color = Color.Blue Grafico.DrawLine(Pen, 0, Cy, PictureBox1.Width, Cy) Grafico.DrawLine(Pen, Cx, 0, Cx, PictureBox1.Height) Pen.Color = Color.Red End Sub Sub grafico3d() Dim Color1 As Integer Dim AX As Single, Ay As Single, Az As Single, Bx As Single, By As Single, Bz As Single Dim NX As Single, Ny As Single, Nz As Single, Nx1 As Single, Ny1 As Single, Nz1 As Single Dim R As Single Dim Pe As Single Dim x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4 As Single Dim px1, py1, px2, py2, px3, py3, px4, py4 As Single Dim fila, col As Integer Dim Puntos(3) As Point For fila = 0 To nf - 3 For col = 0 To nc - 3 x1 = MP1(fila, col).X y1 = MP1(fila, col).Y z1 = MP1(fila, col).Z x2 = MP1(fila, col + 1).X y2 = MP1(fila, col + 1).Y z2 = MP1(fila, col + 1).Z

x3 = MP1(fila + 1, col + 1).X y3 = MP1(fila + 1, col + 1).Y z3 = MP1(fila + 1, col + 1).Z

x4 = MP1(fila + 1, col).X y4 = MP1(fila + 1, col).Y

Page 205: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -949-

z4 = MP1(fila + 1, col).Z '******************* px1 = Cx + (x1 * D) / (D + z1) py1 = Cy + (y1 * D) / (D + z1)

px2 = Cx + (x2 * D) / (D + z2) py2 = Cy + (y2 * D) / (D + z2) px3 = Cx + (x3 * D) / (D + z3) py3 = Cy + (y3 * D) / (D + z3)

px4 = Cx + (x4 * D) / (D + z4) py4 = Cy + (y4 * D) / (D + z4) Puntos(0).X = px1 Puntos(0).Y = py1 Puntos(1).X = px2 Puntos(1).Y = py2 Puntos(2).X = px3 Puntos(2).Y = py3 Puntos(3).X = px4 Puntos(3).Y = py4 ' *************************** AX = x2 - x1 Ay = y2 - y1 Az = z2 - z1 Bx = x3 - x2 By = y3 - y2 Bz = z3 - z2 NX = Ay * Bz - Az * By Ny = AX * Bz - Az * Bx Nz = AX * By - Ay * Bx 'PRODUCTO(CRUZ) R = Math.Sqrt(NX * NX + Ny * Ny + Nz * Nz) If R > 0 Then Nx1 = NX / R Else Nx1 = 1000 End If If R > 0 Then Ny1 = Ny / R Else Ny1 = 1000 End If If R > 0 Then Nz1 = Nz / R Else Nz1 = 1000 End If Pe = Nx1 * 0 + Ny1 * 0 + Nz1 * D Grafico.DrawPolygon(Pen, Puntos) If modo = 1 Then If Nz1 <= 0 Then Color1 = -Nz1 * 255

Page 206: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -950-

brocha.Color = Color.FromArgb(0, Color1, 0) Grafico.FillPolygon(brocha, Puntos, Drawing2D.FillMode.Alternate) End If End If Next Next End Sub Sub verdatos() DataGridView2.ColumnCount = nc + 1 DataGridView2.RowCount = nf + 1 For col = 0 To nc DataGridView2.Columns(col).Width = 30 DataGridView2.Columns(col).HeaderText = col Next For fila = 0 To nf - 1 DataGridView2.Rows(fila).HeaderCell.Value = fila.ToString Next For fila = 0 To nf - 1 For col = 0 To nc - 1 DataGridView2.Rows(fila).Cells(col).Value = MP1(fila, col).Z Next Next End Sub Private Sub TextBox1_KeyDown_1(sender As Object, e As KeyEventArgs) Handles TextBox1.KeyDown Dim gxa As Single = Gradosx Dim gya As Single = Gradosy Dim gza As Single = Gradosz Select Case e.KeyCode Case Keys.Left Gradosx = Gradosx - 1 Case Keys.Right Gradosx = Gradosx + 1 Case Keys.Up Gradosy = Gradosy - 1 Case Keys.Down Gradosy = Gradosy + 1 Case 90 'Z Gradosz = Gradosz + 1 Case 87 'W Gradosz = Gradosz - 1 End Select DataGridView1.Rows(5).Cells(1).Value = Gradosx DataGridView1.Rows(5).Cells(2).Value = Gradosy DataGridView1.Rows(5).Cells(3).Value = Gradosz BtnBorrar_Click(sender, e) vargx = Gradosx - gxa vargy = Gradosy - gya vargz = Gradosz - gza rotar(vargx, vargy, vargz) grafico3d() TextBox1.Text = ""

Page 207: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -951-

End Sub Function Contavecinos(rcol As Integer, rfila As Integer, valor As Single) As Integer For fila = rfila - 1 To rfila + 1 For col = rcol - 1 To rcol + 1 If (MP1(fila, col).Z = valor) Then valor = 1 Exit For End If If valor = 1 Then Exit For Next Next Return valor End Function Private Sub btnAleatorio_Click(sender As Object, e As EventArgs) Handles btnAleatorio.Click Dim rfila, rcol As Integer Dim Pvecinos As Single = 0 BtnBorrar_Click(sender, e) rfila = Nvecinos1 + Int(Rnd() * (nf - Nvecinos1)) rcol = Nvecinos1 + Int(Rnd() * (nc - Nvecinos1)) TextBox2.Text = rcol TextBox3.Text = rfila Dim valor1 As Single MP1(rfila, rcol).Z = MP1(rfila, rcol).Z + aumento valor1 = aumento / Nvecinos1 cont = 1 For k = Nvecinos1 - 1 To 0 Step -1 For fila = rfila - k To rfila + k For col = rcol - k To rcol + k MP1(fila, col).Z = MP1(fila, col).Z + cont * valor1 Next Next Next verdatos() grafico3d() End Sub Private Sub IniciarClick(sender As Object, e As EventArgs) Handles BtnInicializar.Click Dim rfila, rcol As Integer Dim Pvecinos As Single = 0 BtnBorrar_Click(sender, e) rcol = TextBox2.Text rfila = TextBox3.Text MP1(rfila, rcol).Z = altura verdatos() End Sub Private Sub btnProbar_Click(sender As Object, e As EventArgs) Handles btnProbar.Click Dim rfila, rcol As Integer, k As Integer Dim valor1 As Single Dim Pvecinos As Single = 0 BtnBorrar_Click(sender, e)

Page 208: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -952-

rcol = TextBox2.Text rfila = TextBox3.Text MP1(rfila, rcol).Z = MP1(rfila, rcol).Z + aumento valor1 = aumento / Nvecinos1 cont = 1 For k = Nvecinos1 - 1 To 0 Step -1 For fila = rfila - k To rfila + k For col = rcol - k To rcol + k MP1(fila, col).Z = MP1(fila, col).Z + cont * valor1 Next Next Next verdatos() grafico3d() End Sub Private Sub btnGrabar_Click(sender As Object, e As EventArgs) Handles btnGrabar.Click grabar() End Sub

Private Sub btnAutomatico_Click_1(sender As Object, e As EventArgs) Handles btnAutomatico.Click Dim rfila, rcol, m As Integer Dim Pvecinos As Single = 0 BtnBorrar_Click(sender, e) For m = 1 To niter rfila = Nvecinos1 + Int(Rnd() * (nf - Nvecinos1 * 2)) rcol = Nvecinos1 + Int(Rnd() * (nc - Nvecinos1 * 2)) TextBox2.Text = rcol TextBox3.Text = rfila Dim valor1 As Single

MP1(rfila, rcol).Z = MP1(rfila, rcol).Z + aumento valor1 = aumento / Nvecinos1 cont = 1 For k = Nvecinos1 - 1 To 0 Step -1 For fila = rfila - k To rfila + k For col = rcol - k To rcol + k MP1(fila, col).Z = MP1(fila, col).Z + cont * valor1 Next Next Next Next verdatos() grafico3d() End SubEnd Class

12.28 Prender y Apagar un Foco con Arduino

Page 209: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -953-

Se trata de gobernar el Arduino desde Visual Basic 2012. 

Creamos dos botones, cuando pulsamos estos botones se apaga o enciende el LED13 del Arduino.

En Visual Basic 2010, insertamos dos Botones y un SerialPort - Cambia el puerto COM3 por el puerto que tengas en el Arduino (1, 2, 3 o 4)Cuando pulsamos el Button1 se enciende el LED13Cuando pulsamos el Button2 se apaga el LED13

Page 210: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -954-

Imports System.IOImports System.IO.PortsImports System.ThreadingPublic Class Form1 Shared _continue As Boolean Shared _serialPort As SerialPort Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load SerialPort1.Close() SerialPort1.PortName = "COM12" ' Cambia el Puerto SerialPort1.BaudRate = 9600 SerialPort1.DataBits = 8 SerialPort1.Parity = Parity.None SerialPort1.StopBits = StopBits.One SerialPort1.Handshake = Handshake.None SerialPort1.Encoding = System.Text.Encoding.Default End Sub Private Sub PrenderLed(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnPrender.Click SerialPort1.Open() SerialPort1.Write("1") SerialPort1.Close() PicFoco.Image = PictureBox1.Image End Sub

Private Sub ApagarLed(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnApagar.Click SerialPort1.Open() SerialPort1.Write("0") SerialPort1.Close() PicFoco.Image = PictureBox2.Image End Sub

End Class

Programa para el Arduino

Page 211: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -955-

int ledPin = 13; void setup() { Serial.begin(9600); pinMode(ledPin, OUTPUT); digitalWrite(ledPin, LOW); } 

void loop(){ while (Serial.available() == 0); int val = Serial.read() - '0'; if (val == 1) { Serial.println("LED on"); digitalWrite(ledPin, HIGH);} else if (val == 0) { Serial.println("LED OFF"); digitalWrite(ledPin, LOW);} else { //val = val; } Serial.println(val); Serial.flush(); }

11.|11-30 PROCESAMIENTO DE IMAGNES EN VISUAL BASIC 2012

Page 212: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -956-

Indicaciones 1. Abra la imagen menor a 500x500 por ejmplo unsa.bmp2. Dibujar . dibuja la imagen3. Automatico . rota la imagen

Page 213: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -957-

Puede ver todos los efectos que se puede realizar con la imagenSe puede aumentar y desminuir color

Para ver los cambios de color modifique los valores en

Aplique obtener valores y luego dibujar

Module Module1 Public Az As Single = 0 ' rotacion al rededor del eje z Public dex As Single = 0.1 Public dey As Single = 0.1 Public Cx As Integer = 200 Public Cy As Integer = 200 Public drojo As Integer = 10 Public dverde As Integer = 10 Public dazul As Integer Public tipo As Integer = 0 ' es tipo normal 1. Public MBN(maxfilas, maxcol) As Byte Public grafico2 As Graphics Const maxcol As Integer = 550 Const maxfilas As Integer = 400 Public nf As Integer = 100 Public nc As Integer = 100 Public Rojos(maxfilas, maxcol) As Integer

Page 214: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -958-

Public Verdes(maxfilas, maxcol) As Integer Public Azules(maxfilas, maxcol) As Integer Public grafico As Graphics Public imagen As Bitmap Public nfilas As Integer = 7 Public ex As Single = 1 Public ey As Single = 1 Public velocidad As Integer = 10 Public projo As Single = 1 Public pverde As Single = 1 Public pazul As Single = 1 Public vrojo As Single Public vverde As Single Public vazul As SingleEnd Module

CODIGO DEL FORMULARIOImports System.IOPublic Class Form1 Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load grafico = PictureBox1.CreateGraphics() grafico2 = PictureBox2.CreateGraphics() MnuIniciar_Click(sender, e) End Sub Sub procesar(MBN(,) As Byte, nf As Integer, nc As Integer) Dim fila, col As Integer Dim rojo, verde, azul, suma As Integer Dim brocha As SolidBrush brocha = New SolidBrush(Color.Aqua) For fila = 0 To nf - 1 For col = 0 To nc - 1 rojo = Rojos(fila, col) verde = Verdes(fila, col) azul = Azules(fila, col) suma = (rojo + verde + azul) / 3 If suma < 127 Then suma = 0 MBN(fila, col) = 0 Else suma = 255 MBN(fila, col) = 1 End If brocha.Color = Color.FromArgb(suma, suma, suma) grafico2.FillRectangle(brocha, col * ex, fila * ey, ex, ey) Next Next End Sub Private Sub AbrirToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles MnuAbrir.Click Dim nombre As String OpenFileDialog1.ShowDialog() nombre = OpenFileDialog1.FileName

Page 215: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -959-

REM nombre = "E:\datos\unsa1.bmp" imagen = New Bitmap(nombre) REM grafico.DrawImage(New Bitmap(imagen), 0, 0) PictureBox1.Load(nombre) nf = imagen.Height nc = imagen.Width DataGridView1.Rows(0).Cells(1).Value = nc DataGridView1.Rows(0).Cells(2).Value = nf Me.Text = "ancho " & nc & " alto " & nf For fila = 0 To nf - 1 For col = 0 To nc - 1 Rojos(fila, col) = imagen.GetPixel(col, fila).R Verdes(fila, col) = imagen.GetPixel(col, fila).G Azules(fila, col) = imagen.GetPixel(col, fila).B Next Next End Sub Private Sub Salir(sender As Object, e As EventArgs) Handles SalirToolStripMenuItem.Click Me.Close() End End Sub Private Sub MnuIniciar_Click(sender As Object, e As EventArgs) Handles MnuIniciar.Click DataGridView1.RowCount = nfilas DataGridView1.ColumnCount = 4 DataGridView1.Columns(0).Width = 80 DataGridView1.Columns(1).Width = 50 DataGridView1.Columns(2).Width = 50 DataGridView1.Columns(3).Width = 50 DataGridView1.Columns(0).HeaderText = "Propiedad" DataGridView1.Columns(1).HeaderText = "X (rojo)" DataGridView1.Columns(2).HeaderText = "Y(verde)" DataGridView1.Columns(3).HeaderText = "Z(Azul)" For i = 0 To nfilas - 1 DataGridView1.Rows(i).HeaderCell.Value = i.ToString Next DataGridView1.Rows(0).Cells(0).Value = "Tamaño Velocidad" DataGridView1.Rows(0).Cells(1).Value = nc DataGridView1.Rows(0).Cells(2).Value = nf DataGridView1.Rows(0).Cells(3).Value = velocidad

DataGridView1.Rows(1).Cells(0).Value = "Escala" DataGridView1.Rows(1).Cells(1).Value = ex DataGridView1.Rows(1).Cells(2).Value = ey

DataGridView1.Rows(2).Cells(0).Value = "%Color" DataGridView1.Rows(2).Cells(1).Value = projo DataGridView1.Rows(2).Cells(2).Value = pverde DataGridView1.Rows(2).Cells(3).Value = pazul DataGridView1.Rows(3).Cells(0).Value = "Var Color" DataGridView1.Rows(3).Cells(1).Value = vrojo

Page 216: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -960-

DataGridView1.Rows(3).Cells(2).Value = vverde DataGridView1.Rows(3).Cells(3).Value = vazul DataGridView1.Rows(4).Cells(0).Value = "Incremento" DataGridView1.Rows(4).Cells(1).Value = drojo DataGridView1.Rows(4).Cells(2).Value = dverde DataGridView1.Rows(4).Cells(3).Value = dazul

DataGridView1.Rows(5).Cells(0).Value = "CX y Cy" DataGridView1.Rows(5).Cells(1).Value = Cx DataGridView1.Rows(5).Cells(2).Value = Cy DataGridView1.Rows(6).Cells(0).Value = "Rotac z" DataGridView1.Rows(6).Cells(1).Value = Az End Sub Private Sub MnuObtenerValores_Click(sender As Object, e As EventArgs) Handles MnuObtenerValores.Click nc = DataGridView1.Rows(0).Cells(1).Value nf = DataGridView1.Rows(0).Cells(2).Value velocidad = DataGridView1.Rows(0).Cells(3).Value ex = DataGridView1.Rows(1).Cells(1).Value ey = DataGridView1.Rows(1).Cells(2).Value

projo = DataGridView1.Rows(2).Cells(1).Value pverde = DataGridView1.Rows(2).Cells(2).Value pazul = DataGridView1.Rows(2).Cells(3).Value

vrojo = DataGridView1.Rows(3).Cells(1).Value vverde = DataGridView1.Rows(3).Cells(2).Value vazul = DataGridView1.Rows(3).Cells(3).Value drojo = DataGridView1.Rows(4).Cells(1).Value dverde = DataGridView1.Rows(4).Cells(2).Value dazul = DataGridView1.Rows(4).Cells(3).Value Cx = DataGridView1.Rows(5).Cells(1).Value Cy = DataGridView1.Rows(5).Cells(2).Value Az = DataGridView1.Rows(6).Cells(1).Value End Sub

Private Sub mnuBorrar_Click(sender As Object, e As EventArgs) Handles mnuBorrar.Click grafico2.Clear(Color.Black) End Sub Private Sub mnuInverso_Click(sender As Object, e As EventArgs) Handles mnuInverso.Click tipo = 3 Dibujar(tipo) End Sub Private Sub mnuEnfoque_Click(sender As Object, e As EventArgs) Handles mnuEnfoque.Click tipo = 1 Dibujar(tipo) End Sub Private Sub mnuDesenfoque_Click(sender As Object, e As EventArgs) Handles mnuDesenfoque.Click

Page 217: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -961-

tipo = 2 Dibujar(tipo) End Sub Private Sub MnuBajoRelieve_Click(sender As Object, e As EventArgs) Handles MnuBajoRelieve.Click tipo = 5 Dibujar(tipo) End Sub Private Sub mnuGrabarBN_Click(sender As Object, e As EventArgs) Handles mnuGrabarBN.Click Dim fila, col As Integer Dim archivo As StreamWriter archivo = New StreamWriter("E:\datos\MBN" & nc & "x" & nf & ".txt") For fila = 0 To nf - 1 For col = 0 To nc - 1 archivo.Write("{0}{1}", MBN(fila, col), Chr(9)) Next archivo.WriteLine() Next archivo.Close() End Sub

Private Sub mnuDifusion_Click(sender As Object, e As EventArgs) Handles mnuDifusion.Click tipo = 6 Dibujar(tipo) End Sub Private Sub mnuAislamiento_Click(sender As Object, e As EventArgs) Handles mnuAislamiento.Click tipo = 4 Dibujar(tipo) End Sub Private Sub mnuBlancoYNegro_Click(sender As Object, e As EventArgs) Handles mnuBlancoYNegro.Click tipo = 8 Dibujar(tipo) procesar(MBN, nf, nc) End Sub

Private Sub mnuEscalaGrises_Click(sender As Object, e As EventArgs) Handles mnuEscalaGrises.Click tipo = 7 Dibujar(tipo) End Sub Private Sub MnuDeteccionBorde_Click(sender As Object, e As EventArgs) Handles MnuDeteccionBorde.Click Dim F(3, 3) As Integer F(0, 0) = 0 : F(0, 1) = 0 : F(0, 2) = 0 F(1, 0) = 1 : F(1, 1) = -2 : F(1, 2) = 1 F(2, 0) = 0 : F(2, 1) = 0 : F(2, 2) = 0 Dim tfiltro As Integer = 3 Dim fila, col As Integer

Page 218: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -962-

Dim fila1, col1 As Integer Dim rojo, verde, azul As Integer Dim brocha As SolidBrush brocha = New SolidBrush(Color.Aqua) For fila = 1 To nf - 2 For col = 1 To nc - 2 rojo = 0 verde = 0 azul = 0 For fila1 = 0 To tfiltro - 1 For col1 = 0 To tfiltro - 1 rojo = rojo + Rojos(fila + 1 - fila1, col + 1 - col1) * F(fila1, col1) verde = verde + Verdes(fila + 1 - fila1, col + 1 - col1) * F(fila1, col1) azul = azul + Azules(fila + 1 - fila1, col + 1 - col1) * F(fila1, col1) Next Next If rojo > 255 Then rojo = 255 If rojo < 0 Then rojo = 0 If verde > 255 Then verde = 255 If verde < 0 Then verde = 0 If azul > 255 Then azul = 255 If azul < 0 Then azul = 0 brocha.Color = Color.FromArgb(rojo, verde, azul) grafico2.FillRectangle(brocha, col * ex, fila * ey, ex, ey) Next Next End Sub

Sub DibujarNormal() Dim fila, col As Integer Dim rojo, verde, azul As Integer Dim brocha As SolidBrush brocha = New SolidBrush(Color.Aqua) For fila = 1 To nf - 2 For col = 1 To nc - 2 rojo = Rojos(fila, col) * projo If (rojo + vrojo >= 0 And rojo + vrojo <= 255) Then rojo = Rojos(fila, col) * projo + vrojo Else If (rojo + vrojo < 0) Then rojo = 0 If (rojo + vrojo > 255) Then rojo = 255 End If verde = Verdes(fila, col) * pverde If (verde + vverde >= 0 And verde + vverde <= 255) Then verde = Verdes(fila, col) * pverde + vverde Else If (verde + vverde < 0) Then verde = 0 If (verde + vverde > 255) Then verde = 255 End If azul = Azules(fila, col) * pverde If (azul + vazul >= 0 And azul + vazul <= 255) Then azul = Azules(fila, col) * pazul + vazul

Page 219: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -963-

Else If (azul + vazul < 0) Then azul = 0 If (azul + vazul > 255) Then azul = 255 End If brocha.Color = Color.FromArgb(rojo, verde, azul) grafico2.FillRectangle(brocha, Cx + col * ex, Cy + fila * ey, Math.Abs(ex), Math.Abs(ey)) Next Next End Sub

Sub Dibujar(tipo As Integer) Dim dx As Integer = 1 Dim dy As Integer = 1 Dim suma As Integer = 0 Dim fila, col As Integer Dim rojo, verde, azul As Integer Dim brocha As SolidBrush brocha = New SolidBrush(Color.Aqua) For fila = 2 To nf - 2 For col = 2 To nc - 2 Select Case tipo Case 1 ' rojo = Rojos(fila, col) + 0.5 * Rojos(fila, col) - Rojos(fila - dx, col - dy) verde = Verdes(fila, col) + 0.5 * Verdes(fila, col) - Verdes(fila - dx, col - dy) azul = Azules(fila, col) + 0.5 * Azules(fila, col) - Azules(fila - dx, col - dy) If rojo > 255 Then rojo = 255 If rojo < 0 Then rojo = 0

If verde > 255 Then verde = 255 If verde < 0 Then verde = 0

If azul > 255 Then azul = 255 If azul < 0 Then azul = 0 Case 2 'desenfoque rojo = 0 verde = 0 azul = 0 For fila1 = fila - 1 To fila + 1 For col1 = col - 1 To col + 1 rojo = rojo + Rojos(fila1, col1) verde = verde + Verdes(fila1, col1) azul = azul + Azules(fila1, col1) Next Next rojo = rojo / 9 verde = verde / 9 azul = azul / 9 Case 3 ' inverso rojo = 255 - Rojos(fila, col) verde = 255 - Verdes(fila, col) azul = 255 - Azules(fila, col)

Page 220: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -964-

Case 4 'ailamiento rojo = Rojos(fila, col) verde = Verdes(fila, col) azul = Azules(fila, col) If ((rojo < 128) Or (rojo > 255)) Then rojo = 255 - rojo If ((verde < 128) Or (verde > 255)) Then verde = 255 - verde If ((azul < 128) Or (azul > 255)) Then azul = 255 - azul Case 5 ' bajo relieve rojo = Math.Abs(Rojos(fila, col) - Rojos(fila + dx, col + dy) + 128) verde = Math.Abs(Verdes(fila, col) - Verdes(fila + dx, col + dy) + 128) azul = Math.Abs(Azules(fila, col) - Azules(fila + dx, col + dy) + 128) If (rojo > 255) Then rojo = 255 If (verde > 255) Then verde = 255 If (azul > 255) Then azul = 255 Case 6 'difusion Dim rx, ry As Integer rx = Rnd() * 4 - 2 ry = Rnd() * 4 - 2 rojo = Rojos(fila + rx, col + ry) verde = Verdes(fila + rx, col + ry) azul = Azules(fila + rx, col + ry) Case 7 ' gris rojo = Rojos(fila, col) verde = Verdes(fila, col) azul = Azules(fila, col) suma = (rojo + verde + azul) / 3 rojo = suma verde = suma azul = suma End Select brocha.Color = Color.FromArgb(rojo, verde, azul) grafico2.FillRectangle(brocha, Cx + col * ex, Cy + fila * ey, Math.Abs(ex), Math.Abs(ey)) Next Next End Sub Private Sub mnuDibujar_Click(sender As Object, e As EventArgs) Handles mnuDibujar.Click DibujarNormal() End Sub Private Sub BtnNormal_Click(sender As Object, e As EventArgs) Handles BtnNormal.Click tipo = 0 Dibujar(tipo) End Sub

Private Sub txtVarColor_KeyDown(sender As Object, e As KeyEventArgs) Handles txtVarColor.KeyDown Select e.KeyCode Case 88 'rojo If vrojo < 255 Then vrojo = vrojo + drojo

Page 221: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -965-

Else vrojo = 255 End If Case 65 'rojo If vrojo > -255 Then vrojo = vrojo - drojo Else vrojo = -255 End If Case 89 'verde If vverde < 255 Then vverde = vverde + dverde Else vverde = 255 End If Case 66 'verde If vverde > -255 Then vverde = vverde - dverde Else vverde = -255 End If Case 90 'azul If vazul < 255 Then vazul = vazul + dazul Else vazul = 255 End If Case 67 'azul If vazul > -255 Then vazul = vazul - dazul Else vazul = -255 End If Case 87 'wbrillo If vrojo < 255 Then vrojo = vrojo + 1 Else vrojo = 255 End If If vverde < 255 Then vverde = vverde + 1 Else vverde = 255 End If If vazul < 255 Then vazul = vazul + 1 Else vazul = 255 End If Case 68 ' dbrillo If vrojo > 0 Then vrojo = vrojo - 1

Page 222: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -966-

Else vrojo = 0 End If If vverde > 0 Then vverde = vverde - 1 Else vverde = 0 End If If vazul > 0 Then vazul = vazul - 1 Else vazul = 0 End If End Select DataGridView1.Rows(3).Cells(1).Value = vrojo DataGridView1.Rows(3).Cells(2).Value = vverde DataGridView1.Rows(3).Cells(3).Value = vazul MnuObtenerValores_Click(sender, e) txtVarColor.Text = "" DibujarNormal() End Sub Private Sub txtEscala_KeyDown(sender As Object, e As KeyEventArgs) Handles txtEscala.KeyDown Select Case e.KeyCode Case 88 'ex If ex < 10 Then ex = ex + dex Else dex = 10 End If Case 65 'ex If ex > -10 Then ex = ex - dex Else ex = -10 End If Case 89 'ey If ey < 10 Then ey = ey + dey Else ey = 10 End If Case 66 'verde If ey > -10 Then ey = ey - dey Else ey = -10 End If Case 87 'w incremento simultania If ex < 10 Then ex = ex + dex Else

Page 223: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -967-

dex = 10 End If If ey < 10 Then ey = ey + dey Else ey = 10 End If

Case 68 'Dex If ex > -10 Then ex = ex - dex Else ex = -10 End If If ey > -10 Then ey = ey - dey Else ey = -10 End If End Select DataGridView1.Rows(1).Cells(1).Value = ex DataGridView1.Rows(1).Cells(2).Value = ey MnuObtenerValores_Click(sender, e) txtVarColor.Text = "" DibujarNormal() End Sub Private Sub BtnAutomatico_Click(sender As Object, e As EventArgs) Handles BtnAutomatico.Click Timer1.Interval = velocidad Timer1.Enabled = True End Sub Private Sub BtnDetener_Click(sender As Object, e As EventArgs) Handles BtnDetener.Click Timer1.Enabled = False End Sub

Private Sub mnuRotar_Click(sender As Object, e As EventArgs) Handles mnuRotar.Click Dim brocha As SolidBrush brocha = New SolidBrush(Color.Aqua) Dim rojo, verde, azul As Integer Dim fila As Integer Dim x1, y1, x2, y2 As Single Dim azr As Single azr = Az * Math.PI / 180 For fila = 2 To nf - 2 For col = 2 To nc - 2 rojo = Rojos(fila, col) verde = Verdes(fila, col) azul = Azules(fila, col) x1 = col y1 = fila

Page 224: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -968-

x2 = x1 * Math.Cos(azr) - y1 * Math.Sin(azr) y2 = x1 * Math.Sin(azr) + y1 * Math.Cos(azr) brocha.Color = Color.FromArgb(rojo, verde, azul) grafico2.FillRectangle(brocha, Cx + x2 * ex, Cy + y2 * ey, Math.Abs(ex), Math.Abs(ey)) Next Next End Sub

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick If Az < 1000 Then Az = Az + 1 grafico2.Clear(Color.Black) DataGridView1.Rows(6).Cells(1).Value = Az MnuObtenerValores_Click(sender, e) mnuRotar_Click(sender, e) Else Az = 0 End If End SubEnd Class

11.34 TRANSFORMACIONES CON BITMAPS

'************* codigo del moduloModule Module1 Const maxcols As Integer = 500 Const maxfilas As Integer = 500 Public rojos1(maxfilas, maxcols) As Byte Public verdes1(maxfilas, maxcols) As Integer Public azules1(maxfilas, maxcols) As Integer Public rojos2(maxfilas, maxcols) As Integer Public verdes2(maxfilas, maxcols) As Integer Public azules2(maxfilas, maxcols) As Integer Public paso As Single = 0.02 Public velocidad As Integer = 20

Page 225: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -969-

Public Ancho1 As Integer = 333 ' ancho de imagen original Public Alto1 As Integer = 305 ' alto de imagen original Public Ancho2 As Integer = 333 ' ancho de imagen original Public Alto2 As Integer = 305 ' alto de imagen original Public Ancho3 As Integer = 333 ' ancho de imagen original Public Alto3 As Integer = 305 ' alto de imagen original Public nfilas As Integer = 5 Public p1 As Single = 0 Public p2 As Single = 1 - p1 Public Nombre As String Public Bitmap1 As Bitmap Public grafico1 As Graphics Public Bitmap2 As Bitmap Public grafico2 As Graphics Public Bitmap3 As Bitmap Public grafico3 As Graphics Public Color1 As Color Public Color2 As Color Public Color3 As Color Public rojo, verde, azul As IntegerEnd Module

CODIGO DEL FORMULARIO

Public Class Form1 Sub mezclar() 'Bitmap3 = New Bitmap("E:\FOTOSBMP\gato333x305.bmp") For fila = 0 To Alto1 - 1 For col = 0 To Ancho1 - 1 rojo = rojos1(col, fila) * p1 + rojos2(col, fila) * p2 verde = verdes1(col, fila) * p1 + verdes2(col, fila) * p2 azul = azules1(col, fila) * p1 + azules2(col, fila) * p2 Color3 = Color.FromArgb(rojo, verde, azul) Bitmap3.SetPixel(col, fila, Color3) Next Next PictureBox3.Image = Bitmap3 End Sub Private Sub Btmezclar_Click(sender As Object, e As EventArgs) Handles Btmezclar.Click mezclar() End Sub Private Sub btnGrafico1_Click(sender As Object, e As EventArgs) Handles btnGrafico1.Click Dim fila, col As Integer Bitmap1 = New Bitmap("E:\FOTOSBMP\gato333x305.bmp") Ancho1 = Bitmap1.Width Alto1 = Bitmap1.Height For fila = 0 To Alto1 - 1 For col = 0 To Ancho1 - 1 rojos1(col, fila) = Bitmap1.GetPixel(col, fila).R verdes1(col, fila) = Bitmap1.GetPixel(col, fila).G

Page 226: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -970-

azules1(col, fila) = Bitmap1.GetPixel(col, fila).B Next Next DataGridView1.Rows(1).Cells(1).Value = Ancho1 DataGridView1.Rows(1).Cells(2).Value = Alto1 grafico1.DrawImage(Bitmap1, 0, 0) End Sub

Private Sub BtnGrafico2_Click(sender As Object, e As EventArgs) Handles BtnGrafico2.Click Bitmap2 = New Bitmap("E:\FOTOSBMP\perrita333X304.bmp") Ancho2 = Bitmap2.Width Alto2 = Bitmap2.Height For fila = 0 To Alto2 - 1 For col = 0 To Ancho2 - 1 rojos2(col, fila) = Bitmap2.GetPixel(col, fila).R verdes2(col, fila) = Bitmap2.GetPixel(col, fila).G azules2(col, fila) = Bitmap2.GetPixel(col, fila).B Next Next DataGridView1.Rows(2).Cells(1).Value = Ancho2 DataGridView1.Rows(2).Cells(2).Value = Alto2 grafico2.DrawImage(Bitmap2, 0, 0) End Sub Private Sub BtnIniciar_Click(sender As Object, e As EventArgs) Handles BtnIniciar.Click DataGridView1.RowCount = nfilas DataGridView1.ColumnCount = 3 DataGridView1.Columns(0).HeaderText = "Propiedad" DataGridView1.Columns(1).HeaderText = "Valor 1" DataGridView1.Columns(2).HeaderText = "Valor 2" DataGridView1.Columns(1).Width = 50 DataGridView1.Columns(2).Width = 50 For i = 0 To nfilas - 1 DataGridView1.Rows(i).HeaderCell.Value = i.ToString Next DataGridView1.Rows(0).Cells(0).Value = "%p1 p2 " DataGridView1.Rows(0).Cells(1).Value = p1 p2 = 1 - p1 DataGridView1.Rows(0).Cells(2).Value = p2 DataGridView1.Rows(1).Cells(0).Value = "Ancho1 Alto1 " DataGridView1.Rows(1).Cells(1).Value = Ancho1 DataGridView1.Rows(1).Cells(2).Value = Alto1

DataGridView1.Rows(2).Cells(0).Value = "Ancho2 Alto2 " DataGridView1.Rows(2).Cells(1).Value = Ancho2 DataGridView1.Rows(2).Cells(2).Value = Alto2 DataGridView1.Rows(3).Cells(0).Value = "Ancho3 Alto3 " DataGridView1.Rows(3).Cells(1).Value = Ancho3 DataGridView1.Rows(3).Cells(2).Value = Alto3 DataGridView1.Rows(4).Cells(0).Value = "velocidad paso" DataGridView1.Rows(4).Cells(1).Value = velocidad

Page 227: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -971-

DataGridView1.Rows(4).Cells(2).Value = paso End Sub Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load PictureBox1.Width = Ancho1 PictureBox1.Height = Alto1 PictureBox2.Width = Ancho1 PictureBox2.Height = Alto1

PictureBox3.Width = Ancho1 PictureBox3.Height = Alto1

grafico1 = PictureBox1.CreateGraphics grafico2 = PictureBox2.CreateGraphics grafico3 = PictureBox3.CreateGraphics Bitmap1 = New Bitmap("E:\FOTOSBMP\gato333x305.bmp") Bitmap2 = New Bitmap("E:\FOTOSBMP\perrita333X304.bmp") Bitmap3 = New Bitmap("E:\FOTOSBMP\gato333x305.bmp") Ancho1 = Bitmap1.Width Alto1 = Bitmap1.Height End Sub Private Sub BtnValores_Click(sender As Object, e As EventArgs) Handles BtnValores.Click p1 = DataGridView1.Rows(0).Cells(1).Value p2 = 1 - p1 DataGridView1.Rows(0).Cells(2).Value = p2 Ancho1 = DataGridView1.Rows(1).Cells(1).Value Alto1 = DataGridView1.Rows(1).Cells(2).Value velocidad = DataGridView1.Rows(4).Cells(1).Value paso = DataGridView1.Rows(4).Cells(2).Value End Sub

Private Sub btnauto_Click(sender As Object, e As EventArgs) Handles btnauto.Click Timer1.Interval = velocidad Timer1.Enabled = True End Sub

Private Sub BtnDetener_Click(sender As Object, e As EventArgs) Handles BtnDetener.Click Timer1.Enabled = False End Sub

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick If p1 < (1 - paso) Then p1 = p1 + paso Else p1 = 0 End If DataGridView1.Rows(0).Cells(1).Value = p1 p2 = 1 - p1 DataGridView1.Rows(0).Cells(2).Value = p2 ' Btmezclar_Click(sender, e) mezclar()

Page 228: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -972-

End SubEnd Class

11.34 JUEGO DE LA SERPIENTE O GUSANO(USO DE AUTOMATAS CELULARES)Mover un ser con las teclas direccionales y en forma automática

' ******** codigo del moduloModule Module1 Public Const maxcol As Integer = 12 Public velocidad As Integer = 10 Public grafico As Graphics Public lapiz As Pen Public brocha As SolidBrush Public ex As Single = 40 Public ey As Single = 40 Public x1 As Integer = 0 Public y1 As Integer = 0 Public x2 As Integer = 80 Public y2 As Integer = 24 Public x As Integer = 10 Public y As Integer = 5 Public ne, i As Integer Public VX(maxcol) As Integer Public VY(maxcol) As Integer Public cadena As String Public ancho As Integer Public alto As IntegerEnd Module

CODIGO DEL FORMULARIO

' *** codigo del formularioPublic Class Form1

Page 229: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -973-

Function Encontrado(VX() As Integer, VY() As Integer, cx As Integer, cy As Integer, ne As Integer) Dim col As Integer Dim valor As Integer = 0 For col = 0 To ne - 1 If cx = VX(col) And cy = VY(col) Then valor = 1 Exit For End If Next Return valor ' si es 1 End Function

Sub MostrarSer(s As String, VX() As Integer, VY() As Integer, nelem As Integer) Dim col As Integer = 0 For col = 0 To nelem - 1 Select Case s(col) Case "A" : brocha.Color = Drawing.Color.FromArgb(255, 0, 0) 'rojo Case "B" : brocha.Color = Drawing.Color.FromArgb(0, 255, 0) ' verde Case "C" : brocha.Color = Drawing.Color.FromArgb(0, 0, 255) ' "azul" Case "D" : brocha.Color = Drawing.Color.FromArgb(255, 255, 0) ' "amarillo Case "E" : brocha.Color = Drawing.Color.FromArgb(255, 0, 255) '"violeta Case "F" : brocha.Color = Drawing.Color.FromArgb(0, 255, 255) '" celeste Case "G" : brocha.Color = Drawing.Color.FromArgb(255, 255, 255) '" blanco Case "H" : brocha.Color = Drawing.Color.FromArgb(150, 150, 150) ' gris Case "I" : brocha.Color = Drawing.Color.FromArgb(200, 100, 50) 'ladrillo End Select grafico.FillRectangle(brocha, VX(col) * ex, VY(col) * ey, ex, ey) Next End Sub Sub Listar(s As String, VX() As Integer, VY() As Integer, nelem As Integer) Dim col As Integer ListBox1.Items.Clear() For col = 0 To nelem - 1 ListBox1.Items.Add(col & " X " & VX(col) & "Y " & VY(col) & " s " & s(col)) Next End Sub

Private Sub btnIniciar_Click(sender As Object, e As EventArgs) Handles btnIniciar.Click cadena = "ABCDEFGHI" ne = Len(cadena) For i = 0 To ne - 1 VX(i) = 10 - i VY(i) = 5 Next x2 = ancho / ex - 1 y2 = alto / ey - 1 MostrarSer(cadena, VX, VY, ne) Listar(cadena, VX, VY, ne) End Sub

Page 230: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -974-

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load grafico = PictureBox1.CreateGraphics lapiz = New Pen(Brushes.Red) brocha = New SolidBrush(Color.Green) ancho = PictureBox1.Width alto = PictureBox1.Height End Sub

Private Sub TextBox1_KeyDown(sender As Object, e As KeyEventArgs) Handles TextBox1.KeyDown Dim control As Integer = 0 Select Case e.KeyCode Case Keys.Down If y < y2 And Encontrado(VX, VY, x, y + 1, ne) = 0 Then y = y + 1 control = 1 End If Case Keys.Up If y > y1 And Encontrado(VX, VY, x, y - 1, ne) = 0 Then y = y - 1 control = 1 End If Case Keys.Right If x < x2 And Encontrado(VX, VY, x + 1, y, ne) = 0 Then x = x + 1 control = 1 End If Case Keys.Left If x > x1 And Encontrado(VX, VY, x - 1, y, ne) = 0 Then x = x - 1 control = 1 End If End Select REM modificar el vector solo si es factible If control = 1 Then For i = ne - 1 To 1 Step -1 VX(i) = VX(i - 1) VY(i) = VY(i - 1) Next VX(0) = x VY(0) = y grafico.Clear(Color.Black) MostrarSer(cadena, VX, VY, ne) Listar(cadena, VX, VY, ne) End If End Sub Private Sub BtnAuto_Click(sender As Object, e As EventArgs) Handles BtnAuto.Click Timer1.Interval = velocidad Timer1.Enabled = True End Sub

Page 231: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -975-

Private Sub BtnDetener_Click(sender As Object, e As EventArgs) Handles BtnDetener.Click Timer1.Enabled = False End Sub Private Sub btnAleatorio_Click(sender As Object, e As EventArgs) Handles btnAleatorio.Click Dim control As Integer = 0 Dim nroA As Integer Randomize() nroA = Int(Rnd() * 4) Select Case nroA Case 0 If y < y2 And Encontrado(VX, VY, x, y + 1, ne) = 0 Then y = y + 1 control = 1 End If Case 1 If y > y1 And Encontrado(VX, VY, x, y - 1, ne) = 0 Then y = y - 1 control = 1 End If Case 2 If x < x2 And Encontrado(VX, VY, x + 1, y, ne) = 0 Then x = x + 1 control = 1 End If Case 3 If x > x1 And Encontrado(VX, VY, x - 1, y, ne) = 0 Then x = x - 1 control = 1 End If End Select If Encontrado(VX, VY, x, y, ne) = 1 Then control = 0 ' si encuentra entonces no modifica REM modificar el vector solo si es factible If control = 1 Then For i = ne - 1 To 1 Step -1 VX(i) = VX(i - 1) VY(i) = VY(i - 1) Next VX(0) = x VY(0) = y grafico.Clear(Color.Black) MostrarSer(cadena, VX, VY, ne) Listar(cadena, VX, VY, ne) End If End Sub Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick btnAleatorio_Click(sender, e) End SubEnd Class

Page 232: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -976-

11.35 TRABAJO CON BITMAPS . la siguiente aplicación permite ampliar y reducir una imagen y también navegar con las teclas direccionales y con el evento mouse down

'*** codigo del moduloModule Module1 Public Ancho1 As Integer = 200 ' ancho de imagen original Public Alto1 As Integer = 200 ' alto de imagen original Public Ancho2 As Integer = 200 ' ancho de imagen reducida Public Alto2 As Integer = 200 ' alto de imagen reducidad Public Ancho3 As Integer = 600 ' ancho de imagen agrandada Public Alto3 As Integer = 600 ' alto de imagen agrandada Public Cxf As Integer = 0 Public Cyf As Integer = 0 Public Anchof As Integer = 100 Public Altof As Integer = 100 Public Anchod2 As Integer = 50 Public Altod2 As Integer = 50 Public Anchod3 As Integer = 200 Public Altod3 As Integer = 200

Public nombre As String Public nfilas As Integer = 6 Public Cx1 As Integer = 0 Public Cy1 As Integer = 0 Public Cx2 As Integer = 0 Public Cy2 As Integer = 0 Public Cx3 As Integer = 0 Public Cy3 As Integer = 0 Public grafico1 As Graphics Public grafico2 As Graphics Public grafico3 As Graphics Public ex2 As Single

Page 233: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -977-

Public ey2 As Single Public ex3 As Single Public ey3 As Single Public pincel As Pen Public brocha As SolidBrush Public myBitmap As Bitmap Public Rectangle1 As Rectangle Public sourceRectangle As Rectangle Public destRectangle2 As Rectangle Public destRectangle3 As RectangleEnd Module

Public Class Form1 Private Sub BtnIniciar_Click(sender As Object, e As EventArgs) Handles BtnIniciar.Click DataGridView1.RowCount = nfilas DataGridView1.ColumnCount = 3 DataGridView1.Columns(0).HeaderText = "Propiedad" DataGridView1.Columns(1).HeaderText = "Valor X" DataGridView1.Columns(2).HeaderText = "Valor Y" DataGridView1.Columns(1).Width = 50 DataGridView1.Columns(2).Width = 50 For i = 0 To nfilas - 1 DataGridView1.Rows(i).HeaderCell.Value = i.ToString Next DataGridView1.Rows(0).Cells(0).Value = "Fuente Cx1,Cy1 " DataGridView1.Rows(0).Cells(1).Value = Cxf DataGridView1.Rows(0).Cells(2).Value = Cyf DataGridView1.Rows(1).Cells(0).Value = "Fuente Ancho1 Alto1 " DataGridView1.Rows(1).Cells(1).Value = Anchof DataGridView1.Rows(1).Cells(2).Value = Altof

DataGridView1.Rows(2).Cells(0).Value = "Destino1 Cx2,Cy2 " DataGridView1.Rows(2).Cells(1).Value = Cx2 DataGridView1.Rows(2).Cells(2).Value = Cy2 DataGridView1.Rows(3).Cells(0).Value = "Destino 2 Ancho2 Alto2 " DataGridView1.Rows(3).Cells(1).Value = Anchod2 DataGridView1.Rows(3).Cells(2).Value = Altod2 DataGridView1.Rows(4).Cells(0).Value = "Destino3 Cx3,Cy3 " DataGridView1.Rows(4).Cells(1).Value = Cx3 DataGridView1.Rows(4).Cells(2).Value = Cy3 DataGridView1.Rows(5).Cells(0).Value = "Destino 3 Ancho3 Alto3 " DataGridView1.Rows(5).Cells(1).Value = Anchod3 DataGridView1.Rows(5).Cells(2).Value = Altod3 End Sub Private Sub btnModificarBitmap_Click(sender As Object, e As EventArgs) Handles btnModificarBitmap.Click Anchod2 = Anchof * ex2 Altod2 = Altof * ey2 DataGridView1.Rows(3).Cells(1).Value = Anchod2 DataGridView1.Rows(3).Cells(2).Value = Altod2 sourceRectangle = New Rectangle(Cxf, Cyf, Anchof, Altof)

Page 234: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -978-

destRectangle2 = New Rectangle(0, 0, Ancho2, Alto2) destRectangle3 = New Rectangle(0, 0, Ancho3, Alto3) grafico1.DrawImage(myBitmap, 0, 0) grafico2.DrawImage(myBitmap, destRectangle2, Rectangle1, GraphicsUnit.Pixel) grafico3.DrawImage(myBitmap, destRectangle3, sourceRectangle, GraphicsUnit.Pixel) Cx2 = Cxf * ex2 Cy2 = Cyf * ey2 grafico1.DrawRectangle(Pens.Yellow, Cxf, Cyf, Anchof, Altof) grafico2.DrawRectangle(Pens.Yellow, Cx2, Cy2, Anchod2, Altod2) End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnAbrir.Click OpenFileDialog1.ShowDialog() nombre = OpenFileDialog1.FileName myBitmap = New Bitmap(nombre) ' myBitmap = New Bitmap("E:\FOTOSBMP\Partido200x200.bmp") Ancho1 = myBitmap.Width Alto1 = myBitmap.Height ex2 = Ancho2 / Ancho1 ey2 = Alto2 / Alto1 ex3 = Ancho3 / Ancho1 ey3 = Alto3 / Alto1 Anchod2 = Anchof * ex2 Altod2 = Altof * ey2 DataGridView1.Rows(3).Cells(1).Value = Anchod2 DataGridView1.Rows(3).Cells(2).Value = Altod2 sourceRectangle = New Rectangle(Cxf, Cyf, Anchof, Altof) Rectangle1 = New Rectangle(0, 0, Ancho1, Alto1) destRectangle2 = New Rectangle(0, 0, Ancho2, Alto2) destRectangle3 = New Rectangle(0, 0, Ancho3, Alto3) grafico1.DrawImage(myBitmap, 0, 0) grafico2.DrawImage(myBitmap, destRectangle2, Rectangle1, GraphicsUnit.Pixel) grafico3.DrawImage(myBitmap, destRectangle3, sourceRectangle, GraphicsUnit.Pixel) Cx2 = Cxf * ex2 Cy2 = Cyf * ey2 grafico1.DrawRectangle(Pens.Yellow, Cxf, Cyf, Anchof, Altof) grafico2.DrawRectangle(Pens.Yellow, Cx2, Cy2, Anchod2, Altod2) End Sub Private Sub btnObtenerValores_Click(sender As Object, e As EventArgs) Handles btnObtenerValores.Click Cxf = DataGridView1.Rows(0).Cells(1).Value Cyf = DataGridView1.Rows(0).Cells(2).Value Anchof = DataGridView1.Rows(1).Cells(1).Value Altof = DataGridView1.Rows(1).Cells(2).Value Cx2 = DataGridView1.Rows(2).Cells(1).Value Cy2 = DataGridView1.Rows(2).Cells(2).Value

Anchod2 = DataGridView1.Rows(3).Cells(1).Value Altod2 = DataGridView1.Rows(3).Cells(2).Value

Page 235: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -979-

Cx3 = DataGridView1.Rows(4).Cells(1).Value Cy3 = DataGridView1.Rows(4).Cells(2).Value Anchod3 = DataGridView1.Rows(5).Cells(1).Value Altod3 = DataGridView1.Rows(5).Cells(2).Value End Sub

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load pincel = New Pen(Brushes.Azure, 2) brocha = New SolidBrush(Color.AliceBlue) PictureBox1.Width = Ancho1 PictureBox1.Height = Alto1 PictureBox2.Width = Ancho2 PictureBox2.Height = Alto2 PictureBox3.Width = Ancho3 PictureBox3.Height = Alto3 grafico1 = PictureBox1.CreateGraphics grafico2 = PictureBox2.CreateGraphics grafico3 = PictureBox3.CreateGraphics End Sub Private Sub btnBorrar_Click(sender As Object, e As EventArgs) Handles btnBorrar.Click grafico1.Clear(Color.Black) grafico2.Clear(Color.Black) grafico3.Clear(Color.Black) End Sub Private Sub txtCxCyF_KeyDown(sender As Object, e As KeyEventArgs) Handles txtCxCyF.KeyDown Select Case e.KeyCode Case Keys.Down If (Cy2 + Altod2) < Alto2 Then Cy2 = Cy2 + 1 Case Keys.Up If Cy2 > 0 Then Cy2 = Cy2 - 1 Case Keys.Right If (Cx2 + Anchod2) < Ancho2 Then Cx2 = Cx2 + 1 Case Keys.Left If Cx2 > 0 Then Cx2 = Cx2 - 1 End Select Cxf = Cx2 / ex2 Cyf = Cy2 / ey2 DataGridView1.Rows(0).Cells(1).Value = Cxf DataGridView1.Rows(0).Cells(2).Value = Cyf DataGridView1.Rows(2).Cells(1).Value = Cx2 DataGridView1.Rows(2).Cells(2).Value = Cy2 btnModificarBitmap_Click(sender, e) End Sub Private Sub txtTamfuente_KeyDown(sender As Object, e As KeyEventArgs) Handles txtTamfuente.KeyDown Select Case e.KeyCode Case Keys.Down If (Cy2 + Altod2) < Alto2 Then Altod2 = Altod2 + 1 Case Keys.Up If Altod2 > 0 Then Altod2 = Altod2 - 1

Page 236: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -980-

Case Keys.Right If (Cx2 + Anchod2) < Ancho2 Then Anchod2 = Anchod2 + 1 Case Keys.Left If Anchod2 > 0 Then Anchod2 = Anchod2 - 1 End Select Anchof = Anchod2 / ex2 Altof = Altod2 / ey2 DataGridView1.Rows(1).Cells(1).Value = Anchof DataGridView1.Rows(1).Cells(2).Value = Altof DataGridView1.Rows(3).Cells(1).Value = Ancho2 DataGridView1.Rows(3).Cells(2).Value = Alto2 btnModificarBitmap_Click(sender, e) End Sub Private Sub PictureBox2_MouseDown(sender As Object, e As MouseEventArgs) Handles PictureBox2.MouseDown Cx2 = e.X Cy2 = e.Y DataGridView1.Rows(0).Cells(1).Value = Cx2 DataGridView1.Rows(0).Cells(2).Value = Cy2 Cxf = Cx2 / ex2 Cyf = Cy2 / ey2 DataGridView1.Rows(2).Cells(1).Value = Cx2 DataGridView1.Rows(2).Cells(2).Value = Cy2 DataGridView1.Rows(0).Cells(1).Value = Cxf DataGridView1.Rows(0).Cells(2).Value = Cyf btnModificarBitmap_Click(sender, e) End SubEnd Class

11.35 PROBLEMA DEL BARQUITO EN MODO VISUAL El barquito pasa por detrás de la sombrilla y por encima de fondo

Page 237: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -981-

Option Explicit OnOption Strict OnImports System.IOModule module1 Public nombre As String Public backColor As Color Public Grafico1 As Graphics Public MyBitmap1 As Bitmap Public Ancho1 As Integer Public Alto1 As Integer Public Grafico2 As Graphics Public MyBitmap2 As Bitmap Public Ancho2 As Integer Public Alto2 As Integer

Public Grafico3 As Graphics Public MyBitmap3 As Bitmap Public Ancho3 As Integer Public Alto3 As Integer

Public Cx As Integer = 0 Public Cy As Integer = 120 Public Cx2 As Integer = 400 Public Cy2 As Integer = 200 Public Velocidad As Integer = 20End Module

Public Class Form1 Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load grafico1 = PictureBox2.CreateGraphics End Sub

Sub Dibujar(cx As Integer, cy As Integer) nombre = "E:\fotosbmp\copiar\mar800x500.bmp" MyBitmap1 = New Bitmap(nombre) Ancho1 = MyBitmap1.Width Alto1 = MyBitmap1.Height Grafico1.DrawImage(MyBitmap1, 0, 0) nombre = "E:\fotosbmp\copiar\barco454x160.bmp" MyBitmap2 = New Bitmap(nombre) Ancho2 = MyBitmap2.Width Alto2 = MyBitmap2.Height BackColor = MyBitmap2.GetPixel(5, 5) MyBitmap2.MakeTransparent(BackColor) Grafico1.DrawImage(MyBitmap2, cx, cy, Ancho2, Alto2) nombre = "E:\fotosbmp\copiar\SOMBRILLA287X298.bmp" MyBitmap3 = New Bitmap(nombre) Ancho3 = MyBitmap3.Width Alto3 = MyBitmap3.Height BackColor = MyBitmap3.GetPixel(5, 5) MyBitmap3.MakeTransparent(BackColor) Grafico1.DrawImage(MyBitmap3, Cx2, Cy2, Ancho3, Alto3)

Page 238: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -982-

End Sub Private Sub BTNDIBUJAR_Click(sender As Object, e As EventArgs) Handles BTNDIBUJAR.Click Dibujar(Cx, Cy) End Sub Private Sub BtnMover_Click(sender As Object, e As EventArgs) Handles BtnMover.Click 'Grafico1.Clear(Color.Blue) If Cx < Ancho1 Then Cx = Cx + 1 ' necesitas una matriz sobrd otra Else Cx = 1 End If Dibujar(Cx, Cy) End Sub Private Sub btnAuto_Click(sender As Object, e As EventArgs) Handles btnAuto.Click Timer1.Interval = Velocidad Timer1.Enabled = True End Sub

Private Sub BtnDetener_Click(sender As Object, e As EventArgs) Handles BtnDetener.Click Timer1.Enabled = False End Sub Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick BtnMover_Click(sender, e) End Sub

Private Sub txtMover_KeyDown(sender As Object, e As KeyEventArgs) Handles txtMover.KeyDown Select e.KeyCode Case Keys.Down If Cy < Alto1 Then Cy = Cy + 1 Case Keys.Up If Cy > 1 Then Cy = Cy - 1 End If Case Keys.Right If Cx < Ancho1 Then Cx = Cx + 1 End If Case Keys.Left If Cx > 0 Then Cx = Cx - 1 End If End Select Grafico1.DrawImage(MyBitmap1, 0, 0) Dibujar(Cx, Cy) End SubEnd Class

PROGRAMA DE RELLENADO CPN AUTÓMATAS CELULARES MODO CONSOLA

Page 239: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -983-

Imports System.IOModule Module2 Public cont1 As Integer = 0 Public valor1, valor2 As Integer Public lector As StreamReader Public contador As Integer = 0 Public NombreArchivo = "E:\DATOS\PUNTOS80.TXT" Public Maxfilas As Integer = 1000 Public X(Maxfilas) As Integer Public Y(Maxfilas) As Integer Public nelem As Integer = 120 Public ex As Integer = 1 Public ey As Integer = 1 Public cx As Integer = 12 Public cy As Integer = 12 Public XX(Maxfilas) As Integer Public YY(Maxfilas) As Integer

Sub RellenarBorde(cont1 As Integer, X() As Integer, Y() As Integer, nelem As Integer, px As Integer, py As Integer) XX(contador) = px YY(contador) = py contador = contador + 1 Console.SetCursorPosition(cx + px, cy + py) Console.Write("{0}", 3) valor1 = EsPosible(X, Y, nelem, px + 1, py) valor2 = EsPosible(XX, YY, contador, px + 1, py) If valor1 = 0 And valor2 = 0 Then RellenarBorde(cont1 + 1, X, Y, nelem, px + 1, py) End If

valor1 = EsPosible(X, Y, nelem, px, py - 1) valor2 = EsPosible(XX, YY, contador, px, py - 1)

Page 240: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -984-

If valor1 = 0 And valor2 = 0 Then RellenarBorde(cont1, X, Y, nelem, px, py - 1) End If valor1 = EsPosible(X, Y, nelem, px - 1, py) valor2 = EsPosible(XX, YY, contador, px - 1, py) If valor1 = 0 And valor2 = 0 Then RellenarBorde(cont1, X, Y, nelem, px - 1, py) End If valor1 = EsPosible(X, Y, nelem, px, py + 1) valor2 = EsPosible(XX, YY, contador, px, py + 1) If valor1 = 0 And valor2 = 0 Then RellenarBorde(cont1, X, Y, nelem, px, py + 1) End If End Sub

Sub mostrarPuntos(X() As Integer, Y() As Integer, ne As Integer) Dim fila As Integer For fila = 0 To ne - 1 Console.WriteLine(" {0} {1} {2} ", fila, X(fila), Y(fila)) Next End Sub Sub VerPuntos(cx As Integer, cy As Integer, X() As Integer, Y() As Integer, ne As Integer) Dim fila As Integer For fila = 0 To ne - 1 Console.SetCursorPosition(cx + X(fila) * ex, cy + Y(fila) * ey) Console.ForegroundColor = 14 Console.Write("{0}", 2) Next End Sub Sub RecuperarPuntos(NombreArchivo As String, X() As Integer, Y() As Integer, ByRef nelem As Integer) Dim cadena As String, subcadena As String Dim pos As Integer lector = New StreamReader(NombreArchivo) contador = 0 cadena = lector.ReadLine Do While Not (cadena Is Nothing) cadena = cadena & Chr(9) pos = InStr(1, cadena, Chr(9)) subcadena = Mid(cadena, 1, pos - 1) X(contador) = Val(subcadena) subcadena = Mid(cadena, pos + 1, Len(cadena) - pos) Y(contador) = Val(subcadena) cadena = lector.ReadLine contador = contador + 1 Loop lector.Close() nelem = contador - 1 Console.WriteLine("puntos recueprados {0}", nelem) End Sub

Page 241: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -985-

Function EsPosible(X() As Integer, Y() As Integer, nelem As Integer, px As Integer, py As Integer) As Integer Dim valor As Integer = 0 Dim fila As Integer For fila = 0 To nelem - 1 If X(fila) = px And Y(fila) = py Then valor = 1 Exit For End If Next Return valor End FunctionEnd Module

CODIGO DEL MODULO

Module Module1 Sub Main() RecuperarPuntos(NombreArchivo, X, Y, nelem) Console.WriteLine(" puntos recuperados") mostrarPuntos(X, Y, nelem) Console.Clear() VerPuntos(cx, cy, X, Y, nelem) contador = 0 Console.ForegroundColor = 12 cont1 = 0 RellenarBorde(cont1, X, Y, nelem, 2, 2) Console.SetCursorPosition(60, 24) Console.Write("cont {0} ", contador) Console.ReadLine() End SubEnd Module

APLICACIÓN DE AUTOMATAS CELULARES

Este programa permite trabajar con bitmaps, rellena una figura , obtiene el borde , hace transformaciones de un objeto a otro ( modificar el programa para 3d

Page 242: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -986-

CODIGO DEL MODULO 2

Imports System.IOModule Module2 Public relleno As Integer = 0 Public cont1 As Integer = 0 Public Const maximo As Integer = 800 Public XX(4000) As Integer Public YY(4000) As Integer Public txmin As Integer = 0 Public txmax As Integer = 0 Public resn As Integer = 0 Public alfa1 As Single = 1 Public alfa2 As Single = 0 Public alto As Integer = 120 Public ancho As Integer = 120 Public Azules(maxfilas, maxcol) As Integer Public borde1 As Integer = 1 Public brocha As SolidBrush Public lector As StreamReader Public escritor As StreamWriter Public camino As Integer = 0 Public Color As Color Public Const maxfilas As Integer = 400, maxcol As Integer = 400 Public contador As Integer = 0 Public CX As Integer = 0 ' posicion de la figura Public CY As Integer = 0 ' posicion de la figura Public ex As Integer = 4 Public ey As Integer = 4 Public graficodestino As Graphics Public graficofuente As Graphics Public nc As Integer = 100 Public ne1 As Integer ' nro de elementos del vector1 Public ne2 As Integer ' nro de elementos del vector 2

Page 243: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -987-

Public ne3 As Integer ' dimension del vector conbinado Public nelem As Integer = 400 Public nf As Integer = 100 Public NombreArchivo As String Public NombreBitmaps As String Public Pazul As Bitmap Public Pict1 As Bitmap Public pincel As Pen Public px As Integer = 10 Public px1 As Integer = 1 Public py As Integer ' centro de la figura Public py1 As Integer = 1 Public relleno1 As Integer = 2 Public relleno4 As Integer = 4 Public signo As Integer = 1 Public sx As Integer = 0 Public sY As Integer = 0 Public Umbral As Integer = 10 Public varalfa As Single = 0.01 Public vel As Integer = 20 Public X(maximo) As Integer Public X1(maximo) As Integer Public X2(maximo) As Integer Public X3(maximo) As Integer Public Y(maximo) As Integer Public Y1(maximo) As Integer Public Y2(maximo) As Integer Public Y3(maximo) As IntegerEnd Module

CODIGO DEL MODULO 1

Imports System.IOModule Module1 Sub EncontrarSer(a(,) As Integer, nf As Integer, nc As Integer, ByRef px As Integer, ByRef py As Integer, elem As Integer) Dim fila, col As Integer For fila = 0 To nf - 1 For col = 0 To nc - 1 If a(fila, col) = elem Then px = col py = fila Exit Sub End If Next col Next fila End Sub Private Sub cmdGrabarVector_Click() Dim fila As Integer Form1.OpenFileDialog1.ShowDialog() NombreArchivo = Form1.OpenFileDialog1.FileName Dim escritor As StreamWriter

Page 244: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -988-

escritor = New StreamWriter(nombreArchivo) For fila = 1 To nelem escritor.WriteLine(" {0}{1}{2}{4} ", X(fila), vbTab, Y(fila), vbCrLf) Next escritor.Close() End Sub Function evaluar(X() As Integer, Y() As Integer, ne As Integer, _ px As Integer, py As Integer, camino As Integer, borde1 As Integer) As Integer Dim valor1 As Integer, valor2 As Integer, valor3 As Integer, col As Integer Dim suma As Integer Dim fila1 As Integer, col1 As Integer valor1 = 1 valor2 = 1 valor3 = 1 If px = 3 And py = 6 Then px = 3 End If For col = 0 To ne - 1 If (X(col) = px And Y(col) = py) Then valor1 = 0 Exit For End If Next If Azules(py, px) <> camino Then valor2 = 0 suma = 0 For fila1 = py - 1 To py + 1 For col1 = px - 1 To px + 1 If Azules(fila1, col1) = borde1 Then suma = suma + 1 End If Next Next If suma < 1 Then valor3 = 0 evaluar = valor1 * valor2 * valor3 End Function Sub RecuperarPuntos(NombreArchivo As String, X() As Integer, Y() As Integer, ByRef nelem As Integer) Dim cadena As String, subcadena As String Dim pos As Integer lector = New StreamReader(NombreArchivo) contador = 0 cadena = lector.ReadLine Do While Not (cadena Is Nothing) cadena = cadena & Chr(9) pos = InStr(1, cadena, Chr(9)) subcadena = Mid(cadena, 1, pos - 1) X(contador) = Val(subcadena) subcadena = Mid(cadena, pos + 1, Len(cadena) - pos) Y(contador) = Val(subcadena) cadena = lector.ReadLine contador = contador + 1 Loop

Page 245: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -989-

lector.Close() nelem = contador - 1 End Sub Sub RecuperarMatriz(ByVal nombrearchivo As String, ByRef A(,) As Integer, ByVal nf As Integer, ByVal nc As Integer) Dim srLector As StreamReader srLector = New StreamReader(nombrearchivo) Dim fila As Integer, col As Integer Dim cadena As String = "" Dim subcadena As String Dim pos As Integer = 0 Dim inicio As Integer = 1 For fila = 0 To nf - 1 cadena = srLector.ReadLine() cadena = cadena & Chr(9) inicio = 1 For col = 0 To nc - 1 pos = InStr(inicio, cadena, Chr(9)) subcadena = Mid(cadena, inicio, pos - inicio) A(fila, col) = CStr(CInt(CSng(Val(subcadena)))) inicio = pos + 1 Next Next Console.WriteLine("Archivo leido satisfactoriamente") srLector.Close() End Sub Function calcularborde() As Integer Dim res As Integer res = 0 Do res = evaluar(X, Y, contador, px1 + 1, py1, camino, borde1) ' *** derecha If res = 1 Then px1 = px1 + 1 X(contador) = px1 Y(contador) = py1 contador = contador + 1 Exit Do End If res = evaluar(X, Y, contador, px1, py1 + 1, camino, borde1) '**+ abajo If res = 1 Then py1 = py1 + 1 X(contador) = px1 Y(contador) = py1 contador = contador + 1 Exit Do End If res = evaluar(X, Y, contador, px1 - 1, py1, camino, borde1) ' Izquierda If res = 1 Then px1 = px1 - 1 X(contador) = px1 Y(contador) = py1 contador = contador + 1

Page 246: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -990-

Exit Do End If res = evaluar(X, Y, contador, px1, py1 - 1, camino, borde1) ' *** arriba If res = 1 Then py1 = py1 - 1 X(contador) = px1 Y(contador) = py1 contador = contador + 1 Exit Do res = 0 Exit Do End If Loop While res = 1 calcularborde = res End Function Sub GrabarMatriz(NombreArchivo As String, A(,) As Integer, nf As Integer, nc As Integer) Dim fila, col As Integer escritor = New StreamWriter(NombreArchivo) For fila = 0 To nf - 1 For col = 0 To nc - 1 escritor.Write("{0}{1}", A(fila, col), vbTab) Next col escritor.WriteLine() Next escritor.Close() End Sub Sub Centroide(X() As Integer, Y() As Integer, nelem As Integer, ByRef sx As Integer, ByRef sy As Integer) Dim fila As Integer For fila = 0 To nelem - 1 sx = sx + X(fila) sy = sy + Y(fila) Next sx = sx / nelem sy = sy / nelem End Sub Function EsPosible(X() As Integer, Y() As Integer, nelem As Integer, px As Integer, py As Integer) As Integer Dim valor As Integer = 0 Dim fila As Integer For fila = 0 To nelem - 1 If X(fila) = px And Y(fila) = py Then valor = 1 Exit For End If Next Return valor End FunctionEnd Module

CODIGO DEL FORMULARIO

Page 247: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -991-

Imports System.IOPublic Class Form1 Sub Iniciar() DataGridView1.RowCount = 8 DataGridView1.ColumnCount = 3 DataGridView1.Columns(0).Width = 50 DataGridView1.Columns(1).Width = 50 DataGridView1.Columns(2).Width = 50

DataGridView1.Columns(0).HeaderText = "Prop" DataGridView1.Columns(1).HeaderText = "V1" DataGridView1.Columns(2).HeaderText = "V2"

DataGridView1.Rows(0).Cells(0).Value = "Ancho/alto" DataGridView1.Rows(0).Cells(1).Value = nc DataGridView1.Rows(0).Cells(2).Value = nf

DataGridView1.Rows(1).Cells(0).Value = "alfa" DataGridView1.Rows(1).Cells(1).Value = alfa1 DataGridView1.Rows(1).Cells(2).Value = alfa2

DataGridView1.Rows(2).Cells(0).Value = "VarAlfa" DataGridView1.Rows(2).Cells(1).Value = varalfa

DataGridView1.Rows(3).Cells(0).Value = "Npuntos" DataGridView1.Rows(3).Cells(1).Value = ne1 DataGridView1.Rows(3).Cells(2).Value = ne2 DataGridView1.Rows(4).Cells(0).Value = "vel/relleno" DataGridView1.Rows(4).Cells(1).Value = vel DataGridView1.Rows(4).Cells(2).Value = resn

DataGridView1.Rows(5).Cells(0).Value = "Coord Cx,Cy" DataGridView1.Rows(5).Cells(1).Value = CX DataGridView1.Rows(5).Cells(2).Value = CY

DataGridView1.Rows(6).Cells(0).Value = "tx min max" DataGridView1.Rows(6).Cells(1).Value = txmin DataGridView1.Rows(6).Cells(2).Value = txmax End Sub Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load graficofuente = PicFuente.CreateGraphics graficodestino = PicDestino.CreateGraphics pincel = New Pen(Brushes.Red, 2) brocha = New SolidBrush(Drawing.Color.Blue) PicFuente.Width = ancho PicFuente.Height = alto PicDestino.Width = ancho * 4 PicDestino.Height = alto * 4 Iniciar() End Sub

Page 248: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -992-

Sub RellenarMatriz(px As Integer, py As Integer, camino As Integer, relleno As Integer) Azules(py, px) = relleno 'cont = cont + 1 If Azules(py, px + 1) = camino Then Call RellenarMatriz(px + 1, py, camino, relleno) End If If Azules(py + 1, px) = camino Then Call RellenarMatriz(px, py + 1, camino, relleno) End If If Azules(py, px - 1) = camino Then Call RellenarMatriz(px - 1, py, camino, relleno) End If If Azules(py - 1, px) = camino Then Call RellenarMatriz(px, py - 1, camino, relleno) End If End Sub Sub iniciarvector(X() As Integer, ne As Integer, valor As Integer) Dim fila As Integer For fila = 0 To ne - 1 X(fila) = valor Next End Sub Sub RellenarBorde(contador As Integer, X() As Integer, Y() As Integer, nelem As Integer, px As Integer, py As Integer) graficodestino.FillRectangle(brocha, CX + px * ex, CY + py * ey, ex, ey) XX(cont1) = px YY(cont1) = py cont1 = cont1 + 1 ListBox1.Items.Add("cont " & cont1 & " px = " & px & " py " & py) 'If (contador >= 200) Then ' ListarVector(XX, YY, cont1) 'Exit Sub ' End If If EsPosible(X, Y, nelem, px + 1, py) = 0 And EsPosible(XX, YY, cont1, px + 1, py) = 0 Then RellenarBorde(contador + 1, X, Y, nelem, px + 1, py) End If If EsPosible(X, Y, nelem, px, py - 1) = 0 And EsPosible(XX, YY, cont1, px, py - 1) = 0 Then RellenarBorde(contador + 1, X, Y, nelem, px, py - 1) End If If EsPosible(X, Y, nelem, px - 1, py) = 0 And EsPosible(XX, YY, cont1, px - 1, py) = 0 Then RellenarBorde(contador + 1, X, Y, nelem, px - 1, py) End If If EsPosible(X, Y, nelem, px, py + 1) = 0 And EsPosible(XX, YY, cont1, px, py + 1) = 0 Then RellenarBorde(contador + 1, X, Y, nelem, px, py + 1) End If End Sub

Page 249: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -993-

Private Sub MnuBorde_Click(sender As Object, e As EventArgs) Handles MnuBorde.Click Dim valor As Integer valor = 0 Do valor = calcularborde() If valor = 1 Then ListBox1.Items.Add("X=" & px1 & "Y=" & py1) ListBox1.Items.Add("CONT=" & contador) ' graficodestino.DrawRectangle(pincel, col * ex, fila * ey, ex, ey) graficodestino.FillRectangle(brocha, CX + px1 * ex, CY + py1 * ey, ex, ey) Else X(contador) = px1 Y(contador) = py1 nelem = contador + 1 Exit Do End If Loop While valor = 1 End Sub Private Sub MnuCentroide_Click(sender As Object, e As EventArgs) Handles MnuCentroide.Click Centroide(X, Y, nelem, sx, sY) ListBox1.Items.Add("sx" & sx & "Sy " & sY) brocha.Color = Color.FromArgb(255, 0, 0) graficodestino.DrawRectangle(pincel, CX + sx * ex, CY + sY * ey, ex, ey) graficodestino.FillRectangle(brocha, CX + sx * ex, CY + sY * ey, ex, ey) End Sub Private Sub GrabarMatrizClick(sender As Object, e As EventArgs) Handles mnuGrabarMatriz.Click SaveFileDialog1.ShowDialog() NombreArchivo = SaveFileDialog1.FileName ' NombreArchivo = "E:\datos\matriz10X10A.TXT" GrabarMatriz(NombreArchivo, Azules, nf, nc) End Sub Private Sub MnuPunto_Click(sender As Object, e As EventArgs) Handles MnuPunto.Click CX = DataGridView1.Rows(5).Cells(1).Value CY = DataGridView1.Rows(5).Cells(2).Value

EncontrarSer(Azules, nf, nc, px, py, camino) ListBox1.Items.Clear() ListBox1.Items.Add("X=" & px & "Y=" & py) ListBox1.Items.Add("CONT=" & contador) contador = 0 px1 = px py1 = py sx = px sY = py X(contador) = px1 Y(contador) = py1 brocha.Color = Drawing.Color.Red graficodestino.DrawRectangle(pincel, CX + px1 * ex, CY + py1 * ey, ex, ey)

Page 250: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -994-

graficodestino.FillRectangle(brocha, CY + px1 * ex, CY + py1 * ey, ex, ey) contador = 1 End Sub Private Sub MnuBorrar_Click(sender As Object, e As EventArgs) Handles MnuBorrar.Click graficodestino.Clear(Drawing.Color.Aqua) End Sub Private Sub MnuRellenar_Click(sender As Object, e As EventArgs) Handles MnuRellenar.Click RellenarMatriz(sx, sY, camino, relleno4) MostrarMatriz(CX, CY) End Sub Sub MostrarMatriz(cx As Integer, cy As Integer) Dim fila As Integer, col As Integer For fila = 0 To nf - 1 For col = 0 To nc - 1 Select Case Azules(fila, col) Case 0 brocha.Color = Color.FromArgb(0, 0, 0) Case 1 brocha.Color = Color.FromArgb(0, 0, 255) Case 2 brocha.Color = Color.FromArgb(0, 255, 0) Case 3 brocha.Color = Color.FromArgb(255, 0, 0) Case 4 brocha.Color = Color.FromArgb(255, 255, 0) End Select graficodestino.DrawRectangle(pincel, cx + col * ex, cy + fila * ey, ex, ey) graficodestino.FillRectangle(brocha, cx + col * ex, cy + fila * ey, ex, ey) Next Next End Sub Private Sub MnuMostrar_Click(sender As Object, e As EventArgs) Handles MnuMostrar.Click CX = DataGridView1.Rows(5).Cells(1).Value CY = DataGridView1.Rows(5).Cells(2).Value Dim fila As Integer, col As Integer For fila = 0 To nf - 1 For col = 0 To nc - 1 Select Case Azules(fila, col) Case 0 brocha.Color = Color.FromArgb(0, 0, 0) Case 1 brocha.Color = Color.FromArgb(0, 0, 255) Case 2 brocha.Color = Color.FromArgb(0, 255, 0) Case 3 brocha.Color = Color.FromArgb(255, 0, 0) Case 4 brocha.Color = Color.FromArgb(255, 255, 0) End Select

Page 251: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -995-

graficodestino.DrawRectangle(pincel, CX + col * ex, CY + fila * ey, ex, ey) graficodestino.FillRectangle(brocha, CX + col * ex, CY + fila * ey, ex, ey) Next Next End Sub Private Sub MnuAbrirarchivo_Click(sender As Object, e As EventArgs) Handles MnuAbrirMatriz.Click OpenFileDialog1.ShowDialog() NombreArchivo = OpenFileDialog1.FileName ' NombreArchivo = "e:\DATOS\MATRIZ10X10.TXT" RecuperarMatriz(NombreArchivo, Azules, nf, nc) End Sub Private Sub MnuFigura1_Click(sender As Object, e As EventArgs) Handles MnuFigura1.Click OpenFileDialog1.ShowDialog() NombreArchivo = OpenFileDialog1.FileName ' NombreArchivo = "E:\DATOS\FIGURA1.TXT" RecuperarPuntos(NombreArchivo, X1, Y1, ne1) DataGridView1.Rows(3).Cells(1).Value = ne1 End Sub Private Sub MnuFigura2_Click(sender As Object, e As EventArgs) Handles MnuFigura2.Click OpenFileDialog1.ShowDialog() NombreArchivo = OpenFileDialog1.FileName 'NombreArchivo = "E:\DATOS\FIGURA2.TXT" RecuperarPuntos(NombreArchivo, X2, Y2, ne2) DataGridView1.Rows(3).Cells(2).Value = ne2 End Sub Private Sub mnuAbriFigura(sender As Object, e As EventArgs) Handles mnuAbrir.Click ' abre la figura' OpenFileDialog1.ShowDialog() ' NombreArchivo = "E:\DATOS\GATO100X100.BMP" NombreArchivo = OpenFileDialog1.FileName Pict1 = New Bitmap(NombreArchivo) Pazul = New Bitmap(Pict1.Width, Pict1.Height) PicFuente.Image = Pict1 nc = Pict1.Width nf = Pict1.Height '********** obtener For fila = 0 To nf - 1 For col = 0 To nc - 1 Color = Pict1.GetPixel(col, fila) If Color.B > Umbral Then Azules(fila, col) = 1 Else Azules(fila, col) = 0 End If Next col Next End Sub Sub ListarVector(X() As Integer, Y() As Integer, ne As Integer)

Page 252: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -996-

Dim fila As Integer ListBox1.Items.Clear() For fila = 0 To ne - 1 ListBox1.Items.Add(fila & " X =" & X(fila) & "y=" & Y(fila)) Next fila End Sub Private Sub ListarVector(sender As Object, e As EventArgs) Handles MnuListarVector.Click ListarVector(X, Y, nelem) End Sub

Private Sub GrabarVectorClick(sender As Object, e As EventArgs) Handles MnuGrabarVector.Click Dim escritor As StreamWriter SaveFileDialog1.ShowDialog() NombreArchivo = SaveFileDialog1.FileName escritor = New StreamWriter(NombreArchivo) Dim fila As Integer For fila = 0 To nelem - 1 escritor.WriteLine("{0}{1}{2}", X(fila), vbTab, Y(fila)) Next escritor.Close() End Sub Sub BordeFigura(cx As Integer, cy As Integer, X() As Integer, Y() As Integer, nelem As Integer) brocha.Color = Drawing.Color.Red Dim fila As Integer For fila = 0 To nelem - 1 graficodestino.DrawRectangle(pincel, cx + X(fila) * ex, cy + Y(fila) * ey, ex, ey) graficodestino.FillRectangle(brocha, cx + X(fila) * ex, cy + Y(fila) * ey, ex, ey) Next End Sub Private Sub MnuMostrarBorde_Click(sender As Object, e As EventArgs) Handles MnuMostrarBorde.Click CX = DataGridView1.Rows(5).Cells(1).Value CY = DataGridView1.Rows(5).Cells(2).Value BordeFigura(CX, CY, X, Y, nelem) End Sub Private Sub MnuMostrarF1_Click(sender As Object, e As EventArgs) Handles MnuMostrarF1.Click CX = DataGridView1.Rows(5).Cells(1).Value CY = DataGridView1.Rows(5).Cells(2).Value BordeFigura(CX, CY, X1, Y1, ne1) End Sub Private Sub MnuMostrarf2_Click(sender As Object, e As EventArgs) Handles MnuMostrarf2.Click CX = DataGridView1.Rows(5).Cells(1).Value CY = DataGridView1.Rows(5).Cells(2).Value BordeFigura(CX, CY, X2, Y2, ne2) End Sub Private Sub MnuCombinado(sender As Object, e As EventArgs) Handles MnuostrarCombinadoToolStripMenuItem.Click

Page 253: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -997-

MnuBorrar_Click(sender, e) Dim fila As Integer alfa1 = DataGridView1.Rows(1).Cells(1).Value alfa2 = DataGridView1.Rows(1).Cells(2).Value ne1 = DataGridView1.Rows(3).Cells(1).Value ne2 = DataGridView1.Rows(3).Cells(2).Value If ne1 > ne2 Then For fila = ne2 To ne1 X2(fila) = X2(ne2 - 1) Y2(fila) = Y2(ne2 - 1) Next ne3 = ne1 Else For fila = ne1 To ne2 X1(fila) = X1(ne1 - 1) Y1(fila) = Y1(ne1 - 1) Next ne3 = ne2 End If For fila = 0 To ne3 - 1 X3(fila) = X1(fila) * alfa1 + X2(fila) * alfa2 Y3(fila) = Y1(fila) * alfa1 + Y2(fila) * alfa2 Next X3(ne3) = X3(0) Y3(ne3) = Y3(0) ne3 = ne3 + 1 CX = DataGridView1.Rows(5).Cells(1).Value CY = DataGridView1.Rows(5).Cells(2).Value BordeFigura(CX, CY, X3, Y3, ne3) ListarVector(X3, Y3, ne3) End Sub

Private Sub MnuTransformar_Click(sender As Object, e As EventArgs) Handles MnuTransformar.Click MnuBorrar_Click(sender, e) If (alfa1) <= 1 And alfa1 >= 0 Then alfa1 = alfa1 + varalfa * signo If CX < txmax Then CX = CX + 1 Else CX = txmin End If DataGridView1.Rows(5).Cells(1).Value = CX Else If alfa1 > 1 Then alfa1 = 1 signo = signo * (-1) End If If alfa1 < 0 Then alfa1 = 0 signo = signo * (-1) End If

Page 254: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -998-

End If alfa2 = 1 - alfa1 DataGridView1.Rows(1).Cells(1).Value = alfa1 DataGridView1.Rows(1).Cells(2).Value = alfa2 For fila = 0 To ne3 - 1 X3(fila) = X1(fila) * alfa1 + X2(fila) * alfa2 Y3(fila) = Y1(fila) * alfa1 + Y2(fila) * alfa2 Next BordeFigura(CX, CY, X3, Y3, ne3) If relleno = 1 Then Centroide(X3, Y3, ne3, sx, sY) MnuRellenoFigura3_Click(sender, e) End If End Sub

Private Sub MnuDetener_Click(sender As Object, e As EventArgs) Handles MnuDetener.Click Timer1.Enabled = False End Sub Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick MnuBorrar_Click(sender, e) MnuTransformar_Click(sender, e) System.Threading.Thread.Sleep(vel) ' 1 segundo Application.DoEvents() End Sub Private Sub mnuAutomatico_Click(sender As Object, e As EventArgs) Handles mnuAutomatico.Click txmin = DataGridView1.Rows(6).Cells(1).Value txmax = DataGridView1.Rows(6).Cells(2).Value vel = DataGridView1.Rows(4).Cells(1).Value Timer1.Interval = vel Timer1.Enabled = True End Sub

Private Sub mnuSalir_Click(sender As Object, e As EventArgs) Handles mnuSalir.Click Me.Close() End Sub Private Sub MnuObtner_Click(sender As Object, e As EventArgs) Handles MnuObtener.Click nc = DataGridView1.Rows(0).Cells(1).Value nf = DataGridView1.Rows(0).Cells(2).Value alfa1 = DataGridView1.Rows(1).Cells(1).Value alfa2 = DataGridView1.Rows(1).Cells(2).Value varalfa = DataGridView1.Rows(2).Cells(1).Value ne1 = DataGridView1.Rows(3).Cells(1).Value = ne1 ne2 = DataGridView1.Rows(3).Cells(2).Value = ne2 vel = DataGridView1.Rows(4).Cells(1).Value = vel CX = DataGridView1.Rows(5).Cells(1).Value CY = DataGridView1.Rows(5).Cells(2).Value txmin = DataGridView1.Rows(6).Cells(1).Value = txmin txmax = DataGridView1.Rows(6).Cells(2).Value = txmax

Page 255: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -999-

End Sub

Private Sub MnuCentroideFigura3_Click(sender As Object, e As EventArgs) Centroide(X3, Y3, nelem, sx, sY) ListBox1.Items.Add("sx" & sx & "Sy " & sY) brocha.Color = Color.FromArgb(255, 0, 0) graficodestino.DrawRectangle(pincel, CX + sx * ex, CY + sY * ey, ex * 2, ey) graficodestino.FillRectangle(brocha, CX + sx * ex, CY + sY * ey, ex * 2, ey) End Sub Private Sub MnuRellenoFig3_Click(sender As Object, e As EventArgs) RellenarMatriz(sx, sY, camino, relleno4) MostrarMatriz(CX, CY) End Sub Private Sub MnuCentroideFig3_Click(sender As Object, e As EventArgs) Handles MnuCentroideFig3.Click Centroide(X3, Y3, ne3, sx, sY) ListBox1.Items.Add("sx" & sx & "Sy " & sY) brocha.Color = Color.FromArgb(255, 0, 0) graficodestino.DrawRectangle(pincel, CX + sx * ex, CY + sY * ey, ex, ey) graficodestino.FillRectangle(brocha, CX + sx * ex, CY + sY * ey, ex, ey) End Sub

Private Sub MnuRellenoFigura3_Click(sender As Object, e As EventArgs) Handles MnuRellenoFigura3.Click cont1 = 0 brocha.Color = Drawing.Color.Blue contador = 0 RellenarBorde(contador, X3, Y3, ne3, sx, sY) End Sub Private Sub Rellenar_Click(sender As Object, e As EventArgs) Handles Rellenar.Click relleno = 1 End Sub Private Sub NoRellenar_Click(sender As Object, e As EventArgs) Handles NoRellenar.Click relleno = 0 End SubEnd Class

DICCIONARIO TRADUCTOR

Page 256: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -1000-

Imports System.IOModule Module1 Public A(25000, 2) As String Public nf As Integer Sub LeerArchivo(A(,) As String, ByRef nf As Integer) Dim srLector As StreamReader = New StreamReader("e:\DATOS\DIC1.txt") Dim Linea As String Dim cont As Integer = 0 Dim pos As Integer Linea = srLector.ReadLine() Do While Not (Linea Is Nothing) pos = InStr(1, Linea, Chr(9)) A(cont, 0) = Mid(Linea, 1, pos - 1) A(cont, 1) = Mid(Linea, pos + 1, Len(Linea)) cont = cont + 1 Linea = srLector.ReadLine() Loop nf = cont End SubEnd Module

CODIGO DEL MODULO FORM

Public Class Form1 Dim Oreg As ListViewItem Dim nf As Integer Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load ListView1.View = View.Details ListView1.FullRowSelect = True ListView2.FullRowSelect = True

Page 257: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -1001-

ListView1.Columns.Add("Nro ", 50) ListView1.Columns.Add("Ingles", 120) ListView1.Columns.Add("Castellano", 100) LeerArchivo(A, nf) TextBox2.Text = nf For i = 0 To nf - 1 Oreg = New ListViewItem(i) Oreg.SubItems.Add(A(i, 0)) Oreg.SubItems.Add(A(i, 1)) ListView1.Items.Add(Oreg) Oreg = Nothing Next End Sub

Private Sub btnBuscar_Click(sender As Object, e As EventArgs) Handles InglesC.Click ListView2.Clear() ListView2.View = View.Details ListView2.Columns.Add("Nro ", 50) ListView2.Columns.Add("Ingles", 120) ListView2.Columns.Add("Castellano", 100) Dim i As Integer Dim nombre As String Dim nombreABuscar As String nombreABuscar = TextBox1.Text nf = ListView1.Items.Count Dim largo As Integer For i = 0 To nf - 1 nombre = ListView1.Items(i).SubItems(1).Text largo = InStr(nombre, nombreABuscar) If largo > 0 Then ListView1.Items(i).Selected = True Oreg = New ListViewItem(ListView1.Items(i).SubItems(0).Text) nombre = ListView1.Items(i).SubItems(1).Text Oreg.SubItems.Add(nombre) nombre = ListView1.Items(i).SubItems(2).Text Oreg.SubItems.Add(nombre) ListView2.Items.Add(Oreg) Oreg = Nothing End If Next End Sub

Private Sub CastellanoI_Click(sender As Object, e As EventArgs) Handles CastellanoI.Click ListView2.Clear() ListView2.View = View.Details ListView2.Columns.Add("Nro ", 50) ListView2.Columns.Add("Castellano", 120) ListView2.Columns.Add("Ingles", 100) Dim i As Integer Dim nombre As String

Page 258: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -1002-

Dim nombreABuscar As String nombreABuscar = TextBox1.Text nf = ListView1.Items.Count Dim largo As Integer For i = 0 To nf - 1 nombre = ListView1.Items(i).SubItems(2).Text largo = InStr(nombre, nombreABuscar) If largo > 0 Then Oreg = New ListViewItem(ListView1.Items(i).SubItems(0).Text) nombre = ListView1.Items(i).SubItems(2).Text Oreg.SubItems.Add(nombre) nombre = ListView1.Items(i).SubItems(1).Text Oreg.SubItems.Add(nombre) ListView2.Items.Add(Oreg) Oreg = Nothing End If Next End SubEnd Class

DICCIONARIO TRADUCTOR EN MODO CONSOLA

Imports System.IOModule Module1 Public A(25000, 2) As String Public nf As Integer Sub LeerArchivo(A(,) As String, ByRef nf As Integer) Dim srLector As StreamReader = New StreamReader("e:\DATOS\DIC1.txt") Dim Linea As String Dim cont As Integer = 0 Dim pos As Integer Linea = srLector.ReadLine() Do While Not (Linea Is Nothing)

Page 259: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -1003-

pos = InStr(1, Linea, Chr(9)) A(cont, 0) = Mid(Linea, 1, pos - 1) A(cont, 1) = Mid(Linea, pos + 1, Len(Linea)) cont = cont + 1 Linea = srLector.ReadLine() Loop nf = cont End Sub Sub BuscarInglesCastellano(A(,) As String, Ingles As String, nf As Integer) Dim i As Integer Dim largo As Integer Dim cont1 As Integer = 0 For i = 0 To nf - 1 largo = InStr(A(i, 0), Ingles) If largo > 0 Then Console.WriteLine(" {0}===> {1} ====>{2}", cont1, A(i, 0), A(i, 1)) cont1 = cont1 + 1 End If Next Console.WriteLine("Palabras encontradas{0}", cont1) End Sub Sub BuscarCastellanoIngles(A(,) As String, Castellano As String, nf As Integer) Dim i As Integer Dim largo As Integer Dim cont1 As Integer = 0 For i = 0 To nf - 1 largo = InStr(A(i, 1), Castellano) If largo > 0 Then Console.WriteLine(" {0}===> {1} ====>{2}", cont1, A(i, 1), A(i, 0)) cont1 = cont1 + 1 End If Next Console.WriteLine("Palabras encontradas{0}", cont1) End Sub

CODIGO DEL MODULO PRINCIPAL

Sub Main() LeerArchivo(A, nf) Dim opcion As Integer Dim Ingles, Castellano As String Do Console.WriteLine("1. Ingles castellano 2. Castellano Ingles 3.Salir ") Console.Write("ingrese opcion ") opcion = Console.ReadLine() Select Case opcion Case 1 Console.WriteLine("Ingrese palabra en Inglés ") Ingles = Console.ReadLine BuscarInglesCastellano(A, Ingles, nf) Case 2 Console.WriteLine("Ingrese palabra en Castellano ")

Page 260: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -1004-

Castellano = Console.ReadLine BuscarCastellanoIngles(A, Castellano, nf) End Select Loop While opcion <> 3 End SubEnd Module

TRADUCTOR MODIFICADO ( usando cuadros de dialogo)

Diseñe el siguiente formulario

CODIGO DEL FORMULARIO

Imports System.IOPublic Class Form1 Const Maximo As Integer = 25000 Public A(Maximo) As String Public B(Maximo) As String Dim fuente As Font Dim Color As Color Dim camino As Path Dim nterminos As Integer = 2 Dim Texto As String = "" Private Sub InglesEspañol(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnInglesEspañol.Click Dim fila1 As Integer Dim nombre1 As String Dim nombre2 As String Texto = txtFuente.Text For fila1 = 0 To nterminos - 1 nombre1 = A(fila1) ' INGLES nombre2 = B(fila1) ' ESPAÑOL Texto = Replace(Texto, nombre1, nombre2)

Page 261: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -1005-

Next txtDestino.Text = Texto End Sub

Private Sub btnTerminos_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnTerminos.Click OpenFileDialog1.ShowDialog() srLector = New StreamReader(OpenFileDialog1.FileName) Dim cadena As String = "" Dim subcadena1 As String Dim subcadena2 As String Dim cont As Integer = 0 cadena = srLector.ReadLine() Dim pos As Integer = 0 Do While Not (cadena Is Nothing) pos = InStr(1, cadena, Chr(9)) subcadena1 = Mid(cadena, 1, pos - 1) A(cont) = " " & subcadena1 & " " ' español subcadena2 = Mid(cadena, pos + 1, Len(cadena) - pos) B(cont) = " " & subcadena2 & " " cadena = srLector.ReadLine() ' ingles cont += 1 Loop 'Me.Text = "terminos " & cont srLector.Close() ListBox1.Items.Clear() ListBox2.Items.Clear() nterminos = cont For i = 0 To nterminos - 1 ListBox1.Items.Add(A(i)) ListBox2.Items.Add(B(i)) Next End Sub Private Sub Button1_Click(sender As Object, e As EventArgs) Handles BtnAbrir.Click OpenFileDialog1.ShowDialog() Dim Linea As String srLector = New StreamReader(OpenFileDialog1.FileName) Linea = srLector.ReadLine() Texto = "" Do While Not (Linea Is Nothing) Texto = Texto & Linea & vbCrLf Linea = srLector.ReadLine() Loop txtFuente.Text = Texto srLector.Close() End Sub

Private Sub btnInglesEspañol_Click(sender As Object, e As EventArgs) Handles btnEspañolIngles.Click Dim fila1 As Integer Dim nombre1 As String Dim nombre2 As String

Page 262: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -1006-

Texto = txtFuente.Text For fila1 = 0 To nterminos - 1 nombre1 = A(fila1) 'INGLES nombre2 = B(fila1) ' ESPAÑOL Texto = Replace(Texto, nombre2, nombre1) Next txtDestino.Text = Texto End Sub

Private Sub btnGrabar_Click(sender As Object, e As EventArgs) Handles btnGrabar.Click SaveFileDialog1.ShowDialog() Dim escritor As StreamWriter = New StreamWriter(SaveFileDialog1.FileName) escritor.WriteLine("{0}", txtDestino.Text) escritor.Close() End Sub

Private Sub btnfuente_Click(sender As Object, e As EventArgs) Handles btnfuente.Click FontDialog1.ShowDialog() fuente = FontDialog1.Font txtFuente.Font = fuente End Sub

Private Sub btnletra_Click(sender As Object, e As EventArgs) Handles btnletra.Click ColorDialog1.ShowDialog() COLOR = ColorDialog1.Color txtFuente.ForeColor = COLOR End Sub

Private Sub btnfondo_Click(sender As Object, e As EventArgs) Handles btnfondo.Click ColorDialog1.ShowDialog() COLOR = ColorDialog1.Color txtFuente.BackColor = COLOR End Sub

Private Sub btndirectorio_Click(sender As Object, e As EventArgs) Handles btndirectorio.Click FolderBrowserDialog1.ShowDialog() ' camino = FolderBrowserDialog1.SelectedPath End SubEnd Class

Page 263: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -1007-

Tarea : modifique la aplicación parar traducir Código de Lenguaje C++ a Código de Visual Basic

CUADRO CROMATICO

Imports System.DrawingPublic Class Form1 Dim Pen As Pen Dim Grafico As Graphics Dim brocha As SolidBrush Dim ancho As Integer = 255 Dim alto As Integer = 255 Dim color1 As Color Private Sub btnCromatico_Click(sender As Object, e As EventArgs) Handles btnCromatico.Click

Page 264: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -1008-

Dim fila, col As Integer For fila = 0 To alto - 1 For col = 0 To ancho - 1 brocha.Color = Color.FromArgb(fila, col, 0) Grafico.FillRectangle(brocha, fila, col, 1, 1) Next Next End Sub

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load PictureBox1.Width = ancho PictureBox1.Height = alto Grafico = PictureBox1.CreateGraphics Pen = New Pen(Color.Red, 8) brocha = New SolidBrush(Color.FromArgb(0, 255, 0)) End Sub

Private Sub BtnColordialog_Click(sender As Object, e As EventArgs) Handles BtnColordialog.Click ColorDialog1.ShowDialog() color1 = ColorDialog1.Color Panel1.BackColor = color1 End Sub

Private Sub PictureBox1_MouseDown(sender As Object, e As MouseEventArgs) Handles PictureBox1.MouseDown Dim cx, cy As Integer cx = e.X cy = e.Y Label1.Text = "X= " & cx & " Y = " & cy Panel1.BackColor = Color.FromArgb(cx, cy, 0) End SubEnd Class

Tarea.- Elaborar Gama de colores o circulo cromático(use el triangulo para cad color)( Estufiar el cuadro cromaico

Page 265: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -1009-

REDES NEURONALES BACKPROPAGACION .

Problema 2

• El diagrama de la red multicapa se muestra en la figura 1. La red tiene 3 capas una capa de entrada con una neurona, una capa oculta con dos neuronas y una capa de salida con 1 neurona

•  La función de transferencia en la primera capa es la función tangente Sigmoida Hiperbólica (Ec. 1).

• Y la función de transferencia en la segunda capa (capa de salida ) es la función lineal ( Ec. 3)

•Los valores de entrada son

PUNTO X Y0 -3.00 0.001 -2.00 5.002 -1.00 8.003 0.00 9.004 1.00 8.005 2.00 5.006 3.00 0.00

Alfa=0.11- Determine la función de salida obtenida para la entrada -3 ( explicar) (3 puntos)2- Propague el error hacia atrás y calcule los nuevos pesos ( 3 puntos)3- Elabore un programa en visual Basic modo ocnsola o formulario , o lenguaje c (

3 puntos)

EN PROGRAMACION VISUAL

Page 266: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -1010-

Imports System.IOModule Module1 Public Const limite As Integer = 5 Public Const limdatos As Integer = 10

Public nombreErrores As String = "e:\datos\errores.txt" Public nombreEntrenamiento As String = "e:\datos\entrena.txt" Public w1(limite) As Single ' matriz de pesos en la capa 1 Public w2(limite) As Single ' matriz de pesos en la capa 2 Public x(limdatos) As Single ' entradas a la red Public y(limdatos) As Single ' salidas deseadas de la red Public ndatos As Integer = 7 ' nro de entradas y salidas Public ne1 As Integer = 2 REM neuronas en la etapa 1 Public ne2 As Integer = 1 REM neuronas en la etapa 2 Public alfa As Single = 0.1 Public a1(limite) As Single ' salida de la capa 1 Public a2 As Single ' salida de la capa 2 Public b1(limite) As Single ' vector de segos capa 1 Public b2(limite) As Single ' vector de segos capa 2 Public s1(limite) As Single ' vector de errores de capa 1 Public ya2(limdatos) As Single ' vector de salida obtenida Public entrada As Single = -2 Public SalidaDeseada As Single = 1 Public sumacuadratica As Single Public cont As Integer = 0 Public nveces As Integer = 58 Public errorsalida As Single Public prono As Single = 3 Public Ventrena(1000) As Single ' graba la desinuci Sub Iniciar() w1(0) = 1 w1(1) = 2

Page 267: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -1011-

w1(2) = 8 w2(0) = 5 w2(1) = 6 w2(2) = 10

b1(0) = 3 b1(1) = 4 b1(2) = 9 b2(0) = 7 b2(1) = 0

x(1) = -3 : y(1) = 0 x(2) = -2 : y(2) = 5 x(3) = -1 : y(3) = 8 x(4) = 0 : y(4) = 9 x(5) = 1 : y(5) = 8 x(6) = 2 : y(6) = 5 x(7) = 3 : y(7) = 0 alfa = 0.1 End Sub Sub GrabarVector(A() As Single, nf As Integer, nombre As String) Dim escritor As New StreamWriter(nombre) Dim i As Integer For i = 0 To nf - 1 escritor.WriteLine(" suma {0} {1}= {2}", i, vbTab, A(i)) Next escritor.Close() End Sub Sub Mostrar(A() As Single, nf As Integer) Dim i As Integer Dim cadena As String = "" For i = 0 To nf - 1 cadena = cadena + " " + A(i).ToString Next Form1.ListBox1.Items.Add(cadena) End Sub Sub sigmoidea(A() As Single, nf As Single) Dim i As Integer Dim valor As Single For i = 0 To nf - 1 valor = (Math.Exp(A(i)) - Math.Exp(-A(i))) / (Math.Exp(A(i)) + Math.Exp(-A(i))) A(i) = valor Next End Sub Function Probar(entrada As Single, salida As Single) As Single ' funcion suma For i = 0 To ne1 - 1 a1(i) = a1(i) + entrada * w1(i) + b1(i) Next i Form1.ListBox1.Items.Add(" la suma es ") Mostrar(a1, ne1) ' calcular la funcion de salida

Page 268: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -1012-

sigmoidea(a1, ne1) Form1.ListBox1.Items.Add(" salida de capa 1 a1 ") Mostrar(a1, ne1) 'salida de la red a2 = 0 For i = 0 To ne1 - 1 a2 = a2 + a1(i) * w2(i) Next i a2 = a2 + b2(0) Form1.ListBox1.Items.Add(" salida de capa 2 " & a2) Return a2 End FunctionEnd Module

EVALUACION DE EXPRESIONES

Page 269: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -1013-

'***CODIGO DEL MODULO 1

Module Module1 Public EvalRes As Boolean ' Resultado de la evaluacion Public CadA, CadB, CadC, CadD, CadE, CadX As String Public CadenaEcuacion As String Public Cadena As String = "XXXX" Public VSignos As String = "^*/" Public CadSigno As String = "" Public CadenaExpresion As String Public nelem As Integer = 0 Public CadNumeros As String = "0123456789.+-*/^() " Public suma As Single Public ck As Single = 0.279

' ************** Public x1 As Single = 1 Public Li As Single = -5 Public Ls As Single = 5 Public Dx As Single = 1 Public Ndiv As Integer = 10 Public cx As Integer = 200 Public cy As Integer = 200 Public ex As Integer = 10 Public ey As Integer = 10 Public A As Single = 0 Public B As Single = 0 Public C As Single = 1 Public D As Single = 0 Public vE As Single = 0 Public Umbral As Single = 2 Function PotMultiDivi(cadena As String, tipo As Integer) As String Dim Signo1, signo2, signo3, cadsigno As String Dim cad1, cad2, cad3 As String Dim Cadena1, Cadena2, Cadena3 As String Dim CadA, CadB As String Dim pos1, pos2, pos3, posini As Integer Dim R As Single Dim fila As Integer cadena = " " + cadena + " " cadsigno = "" Select Case tipo Case 1 ' si son potencias For fila = 0 To Len(cadena) - 1 If cadena(fila) = "^" Then cadsigno = cadena(fila) pos2 = fila Exit For End If Next Case 2 'multiplicaciones y divisiones tienen igual prioridad

Page 270: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -1014-

For fila = 0 To Len(cadena) - 1 If cadena(fila) = "*" Or cadena(fila) = "/" Then cadsigno = cadena(fila) pos2 = fila Exit For End If Next End Select ' primero buscamos si son las potencias CadA = Extrae(cadena, 0, pos2 - 1) CadB = Extrae(cadena, pos2 + 1, Len(cadena) - 1) ' la cadena anterior For fila = pos2 - 1 To 0 Step -1 If cadena(fila) = "+" Or cadena(fila) = "-" Or cadena(fila) = "*" Or cadena(fila) = "/" Or cadena(fila) = "^" Then pos1 = fila Exit For Else cad1 = cadena(fila) + cad1 End If Next ' busca hacia adelante pos3 = pos2 ' si el primer signo + o - entonces si cuenta 2o If CadB(0) = "+" Or CadB(0) = "-" Then posini = pos2 + 2 cad3 = CadB(0) Else cad3 = "" posini = pos2 + 1 End If pos3 = Len(cadena) - 1 For fila = posini To Len(cadena) - 1 ' cadsigno = cadena(fila) If cadena(fila) = "+" Or cadena(fila) = "-" Or _ cadena(fila) = "*" Or cadena(fila) = "/" Or cadena(fila) = "^" Or fila > Len(cadena) - 1 Then pos3 = fila Exit For Else cad3 = cad3 + cadena(fila) End If Next Select Case cadsigno Case "^" : R = Val(cad1) ^ Val(cad3) 'tiene mayor prioridad Case "*" : R = Val(cad1) * Val(cad3) Case "/" : R = Val(cad1) / Val(cad3) End Select 'reemplazamos el resultado de la multiplicacion Cadena1 = Extrae(cadena, 0, pos1) Cadena3 = Extrae(cadena, pos3, Len(cadena) - 1) ' juntamos la cadena

Page 271: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -1015-

Cadena2 = Str(R) ' Console.WriteLine(" la cadena 1 es {0} ", Cadena1) ' Console.WriteLine(" la cadena 2 es {0} ", Cadena2) ' Console.WriteLine(" la cadena 3 es {0} ", Cadena3) Signo1 = Cadena1(Len(Cadena1) - 1) signo2 = Cadena2(0) Select Case Signo1 Case "+" Select Case signo2 Case "+" : signo3 = "+" Case " " : signo3 = "+" Case "-" : signo3 = "-" End Select Case "-" Select Case signo2 Case "+" : signo3 = "-" Case " " : signo3 = "-" Case "-" : signo3 = "+" End Select Case "*" signo3 = Signo1 Case "/" signo3 = Signo1 End Select Cadena1 = Extrae(Cadena1, 0, Len(Cadena1) - 2) Cadena2 = Extrae(Cadena2, 1, Len(Cadena2) - 1) cadena = Cadena1 + signo3 + Cadena2 + Cadena3 Return cadena End Function

Function Reemplazar(cadena As String, cadbusca As String, cadrempla As String) As String Dim fila As Integer Dim cadTemporal As String = "" For fila = 0 To Len(cadena) - 1 If cadena(fila) = cadbusca Then cadTemporal = cadTemporal + cadrempla Else cadTemporal = cadTemporal + cadena(fila) End If Next Return cadTemporal End Function Sub ImprimirCadena(cadena As String) Dim fila As Integer For fila = 0 To Len(cadena) - 1 Console.WriteLine(" {0} {1} ", fila, cadena(fila)) Next End Sub Function Encontrado(SIGNO As String) As Boolean Dim fila As Integer Dim valor As Boolean = False

Page 272: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -1016-

For fila = 0 To Len(CadNumeros) - 1 If CadNumeros(fila) = SIGNO Then valor = True Exit For End If Next Return valor End Function Function contar(cadena As String, cadsigno As String) As Integer Dim fila, cont As Integer cont = 0 For fila = 0 To Len(cadena) - 1 If cadena(fila) = cadsigno Then cont = cont + 1 Next Return cont End Function Function Encontrar(cadena As String, cadsigno As String, Vinicial As Integer) As String Dim pos As Integer = 0 For fila = Vinicial To Len(cadena) - 1 If cadena(fila) = cadsigno Then pos = fila Exit For End If Next Return pos End Function Function Extrae(cadena As String, pos1 As Integer, pos2 As Integer) As String Dim subcadena As String = "" Dim fila As Integer Dim cont As Integer = 0 For fila = pos1 To pos2 subcadena = subcadena + cadena(fila) Next Return subcadena End Function Function EvaluacionCorrecta(cadena As String) As Boolean Dim fila, pos1, pos2 As Integer Dim valor1 As Boolean = True Dim valor2 As Boolean = True For fila = 0 To Len(cadena) - 1 If Encontrado(cadena(fila)) = False Then valor1 = False Exit For End If Next ' lo parentesis que se abre debe cerrarse Dim punto As Integer punto = 0 While punto < Len(cadena) - 1 pos1 = Encontrar(cadena, "(", punto) If pos1 > 0 Then ' se encuentra el parentesis

Page 273: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -1017-

pos2 = Encontrar(cadena, ")", pos1) If (pos2 > pos1) Then ' se encuentra despue de pos1 valor2 = True punto = pos2 + 1 Else ' si pos2 esta antes de pos1 o no lo encuentre valor2 = False Exit While End If Else ' se no encuentra pos 1 no deberia encontrar el pos 2 pos2 = Encontrar(cadena, ")", punto) If (pos2 > 0) Then valor2 = False Exit While Else valor2 = True Exit While End If End If ' pos2 = Encontrar(cadena, ")", pos1) If pos2 >= pos1 And pos2 >= 0 Then Else valor2 = False Exit While End If End While If valor1 * valor2 >= 1 Then Return True Else Return False End If End Function Function EliminarCar(cadena As String, car As String) As String Dim fila As Integer Dim Cadena1 As String = "" For fila = 0 To Len(cadena) - 1 If cadena(fila) <> car Then Cadena1 = Cadena1 + cadena(fila) Next Return Cadena1 End Function Function Fractal(Li As Single, ByRef cadres As String) As Single Dim x, y As Single Dim fila As Integer Dim cont As Integer cadres = "Dentro" Dim valor As Single = 0 x = Li cont = 0 For fila = 1 To 255 y = Math.Pow(x, 2) - ck ' Console.WriteLine("fila {0} x {1} y {2}", fila, x, y) cont = cont + 1 If Math.Abs(y) > Umbral Then

Page 274: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -1018-

cadres = "FUERA" Exit For End If x = y Next If cont > 24 Then valor = y Else valor = cont End If Return valor

End Function Function EvaluarExpresion(cadena As String) As Single Dim R As Single ' quitamos los parentesis primero cadena = CadLibre(cadena) ' Console.WriteLine(" la cadena resultante es {0} ", cadena) ' evaluamos la cadena nelem = contar(cadena, "^") For fila = 0 To nelem - 1 cadena = PotMultiDivi(cadena, 1) ' es de tipo potencia Next ' Console.WriteLine("cadena es {0} ", cadena) nelem = 0 nelem = contar(cadena, "*") nelem = nelem + contar(cadena, "/") For fila = 0 To nelem - 1 cadena = PotMultiDivi(cadena, 2) 'l multiplicaciones y divisiones Next ' evaluamos la cadena sis parentesis Console.WriteLine("cadena final {0} ", cadena) cadena = " " + cadena + " " R = Sumasrestas(cadena) Return R End Function Function CadLibre(Cadena As String) As String Dim subcadena As String Dim Cadena1, Cadena2, cadena3 As String Dim cpar As Integer Dim R As Single Dim fila, k, pos1, pos2 As Integer cpar = contar(Cadena, "(") For k = 0 To cpar - 1 ' primero quitamos los parentesis pos1 = Encontrar(Cadena, "(", 1) pos2 = Encontrar(Cadena, ")", pos1 + 1) subcadena = Extrae(Cadena, pos1 + 1, pos2 - 1) ' Console.WriteLine(" subcadena {0}", subcadena) ' evaluamos la cadena nelem = contar(subcadena, "^") For fila = 0 To nelem - 1

Page 275: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -1019-

subcadena = PotMultiDivi(subcadena, 1) ' es de tipo potencia Next ' Console.WriteLine("cadena es {0} ", subcadena) nelem = 0 nelem = contar(subcadena, "*") nelem = nelem + contar(subcadena, "/") For fila = 0 To nelem - 1 subcadena = PotMultiDivi(subcadena, 2) Next Console.WriteLine("cadena final {0} ", subcadena) subcadena = " " + subcadena + " " R = Sumasrestas(subcadena) Console.WriteLine(" la suma y resta es {0}", R) ' formando la nueva cadena Cadena1 = Extrae(Cadena, 0, pos1 - 1) Cadena2 = Str(R) cadena3 = Extrae(Cadena, pos2 + 1, Len(Cadena) - 1) Cadena = Cadena1 + Cadena2 + cadena3 Next Return Cadena End Function Function Sumasrestas(cadena As String) As Single Dim suma As Single Dim signo1, signo2, subcadena As String Dim psigno1, psigno2, possigno As Integer Dim cont1, cont2, largo As Integer largo = Len(cadena) ' buscar el primer signo si es mas o menos psigno1 = Encontrar(cadena, "+", 0) psigno2 = Encontrar(cadena, "-", 0) If psigno1 < psigno2 Then possigno = psigno1 Else possigno = psigno2 End If cont1 = possigno + 1 cont2 = possigno + 1 signo1 = cadena(possigno) ' sumas y restas suma = 0 While (cont2 < largo) signo2 = cadena(cont2) If signo2 = "-" Or signo2 = "+" Or cont2 >= largo - 1 Then subcadena = Extrae(cadena, cont1, cont2 - 1) ' Console.WriteLine("subcadena {0} ", subcadena) Select Case signo1 Case "+" : suma = suma + Val(subcadena) Case "-" : suma = suma - Val(subcadena) End Select signo1 = signo2 cont2 = cont2 + 1 cont1 = cont2

Page 276: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -1020-

' Console.WriteLine("la suma es {0}", suma) Else cont2 = cont2 + 1 End If End While Return suma End Function

End Module' *** CODIGO DEL FORMULARIOPublic Class Form1 Dim Grafico As Graphics Dim pen As Pen Sub ObtenerValores() cx = DataGridView1.Rows(0).Cells(1).Value cy = DataGridView1.Rows(1).Cells(1).Value Li = DataGridView1.Rows(2).Cells(1).Value Ls = DataGridView1.Rows(3).Cells(1).Value Ndiv = DataGridView1.Rows(4).Cells(1).Value Dx = DataGridView1.Rows(5).Cells(1).Value A = DataGridView1.Rows(6).Cells(1).Value B = DataGridView1.Rows(7).Cells(1).Value C = DataGridView1.Rows(8).Cells(1).Value D = DataGridView1.Rows(9).Cells(1).Value vE = DataGridView1.Rows(10).Cells(1).Value x1 = DataGridView1.Rows(11).Cells(1).Value ex = DataGridView1.Rows(12).Cells(1).Value ey = DataGridView1.Rows(13).Cells(1).Value ck = DataGridView1.Rows(14).Cells(1).Value End Sub Function ObtenerEcuacion(CadExpresion As String, cadA As String, cadB As String, _ cadC As String, cadD As String, cadE As String, cadX As String) CadExpresion = Reemplazar(CadExpresion, "A", cadA) CadExpresion = Reemplazar(CadExpresion, "B", cadB) CadExpresion = Reemplazar(CadExpresion, "C", cadC) CadExpresion = Reemplazar(CadExpresion, "D", cadD) CadExpresion = Reemplazar(CadExpresion, "E", cadE) CadExpresion = Reemplazar(CadExpresion, "X", cadX) Return CadExpresion End Function Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load Grafico = PictureBox1.CreateGraphics pen = New Pen(Brushes.Red, 2) DataGridView1.RowCount = 15 DataGridView1.ColumnCount = 2 DataGridView1.Columns(0).HeaderText = "Prop" DataGridView1.Columns(1).HeaderText = "Valor" DataGridView1.Columns(0).Width = 60 DataGridView1.Columns(1).Width = 80 DataGridView1.Rows(0).Cells(0).Value = "Cx" DataGridView1.Rows(0).Cells(1).Value = cx

Page 277: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -1021-

DataGridView1.Rows(1).Cells(0).Value = "Cy" DataGridView1.Rows(1).Cells(1).Value = cy DataGridView1.Rows(2).Cells(0).Value = "Li" DataGridView1.Rows(2).Cells(1).Value = Li DataGridView1.Rows(3).Cells(0).Value = "Ls" DataGridView1.Rows(3).Cells(1).Value = Ls DataGridView1.Rows(4).Cells(0).Value = "Nd" DataGridView1.Rows(4).Cells(1).Value = Ndiv DataGridView1.Rows(5).Cells(0).Value = "Dx" DataGridView1.Rows(5).Cells(1).Value = Dx DataGridView1.Rows(6).Cells(0).Value = "A" DataGridView1.Rows(6).Cells(1).Value = A DataGridView1.Rows(7).Cells(0).Value = "B" DataGridView1.Rows(7).Cells(1).Value = B DataGridView1.Rows(8).Cells(0).Value = "C" DataGridView1.Rows(8).Cells(1).Value = C DataGridView1.Rows(9).Cells(0).Value = "D" DataGridView1.Rows(9).Cells(1).Value = D DataGridView1.Rows(10).Cells(0).Value = "E" DataGridView1.Rows(10).Cells(1).Value = vE DataGridView1.Rows(11).Cells(0).Value = "X" DataGridView1.Rows(11).Cells(1).Value = x1

DataGridView1.Rows(12).Cells(0).Value = "EX" DataGridView1.Rows(12).Cells(1).Value = ex

DataGridView1.Rows(13).Cells(0).Value = "EY" DataGridView1.Rows(13).Cells(1).Value = ey DataGridView1.Rows(14).Cells(0).Value = "CK" DataGridView1.Rows(14).Cells(1).Value = ck End Sub Sub ObtenerCadenas() CadenaEcuacion = txtEcuacion.Text CadA = DataGridView1.Rows(6).Cells(1).Value CadB = DataGridView1.Rows(7).Cells(1).Value CadC = DataGridView1.Rows(8).Cells(1).Value CadD = DataGridView1.Rows(9).Cells(1).Value CadE = DataGridView1.Rows(10).Cells(1).Value CadX = DataGridView1.Rows(11).Cells(1).Value End Sub Function Sumasrestas(cadena As String) As Single Dim suma As Single Dim signo1, signo2, subcadena As String Dim psigno1, psigno2, possigno As Integer Dim cont1, cont2, largo As Integer largo = Len(cadena) ' buscar el primer signo si es mas o menos psigno1 = Encontrar(cadena, "+", 0) psigno2 = Encontrar(cadena, "-", 0) If psigno1 < psigno2 Then possigno = psigno1 Else

Page 278: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -1022-

possigno = psigno2 End If cont1 = possigno + 1 cont2 = possigno + 1 signo1 = cadena(possigno) ' sumas y restas suma = 0 While (cont2 < largo) signo2 = cadena(cont2) If signo2 = "-" Or signo2 = "+" Or cont2 >= largo - 1 Then subcadena = Extrae(cadena, cont1, cont2 - 1) ' Console.WriteLine("subcadena {0} ", subcadena) Select Case signo1 Case "+" : suma = suma + Val(subcadena) Case "-" : suma = suma - Val(subcadena) End Select signo1 = signo2 cont2 = cont2 + 1 cont1 = cont2 ' Console.WriteLine("la suma es {0}", suma) Else cont2 = cont2 + 1 End If End While Return suma End Function Function Encontrado(SIGNO As String) As Boolean Dim fila As Integer Dim valor As Boolean = False For fila = 0 To Len(CadNumeros) - 1 If CadNumeros(fila) = SIGNO Then valor = True Exit For End If Next Return valor End Function

Private Sub BtnVarTodo_Click(sender As Object, e As EventArgs) Handles BtnVarTodo.Click CadenaEcuacion = txtEcuacion.Text CadenaEcuacion = " " + CadenaEcuacion + " " ObtenerValores() ObtenerCadenas() CadenaExpresion = ObtenerEcuacion(CadenaEcuacion, CadA, CadB, CadC, CadD, CadE, CadX) TxtExpresion.Text = CadenaExpresion CadenaExpresion = " " + CadenaExpresion + " " EvalRes = EvaluacionCorrecta(CadenaExpresion) If EvalRes = True Then Me.Text = "evalucion correcta" Else

Page 279: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -1023-

MsgBox("expresion incorrecta") End If CadenaExpresion = " +2+(+2-5)+4" ' prueba txtResultado.Text = EvaluarExpresion(CadenaExpresion) End Sub Sub coordenadas(Cx As Integer, Cy As Integer) Grafico.DrawLine(Pens.Blue, 0, Cy, Cx * 2, Cy) Grafico.DrawLine(Pens.Blue, Cx, 0, Cx, Cy * 2) End Sub Private Sub btnGraficarX(sender As Object, e As EventArgs) Handles btnVarX.Click Dim CadTemporal As String Dim x1, y1, x2, y2, x, y As Single ObtenerValores() CadenaEcuacion = txtEcuacion.Text ObtenerCadenas() CadX = "X" CadenaExpresion = ObtenerEcuacion(CadenaEcuacion, CadA, CadB, CadC, CadD, CadE, CadX) CadenaExpresion = " " + CadenaExpresion + " " TxtExpresion.Text = CadenaExpresion coordenadas(cx, cy) Dx = (Ls - Li) / Ndiv DataGridView1.Rows(5).Cells(1).Value = Dx ' mostramos los valores en textbox ListBox1.Items.Clear() ListBox1.Items.Add("valores de la funcion " & CadenaEcuacion) x = Li CadTemporal = Reemplazar(CadenaExpresion, "X", x) CadTemporal = " " + CadTemporal + " " ' reemplaza x con el nuevo y luego calcula la expresion y = EvaluarExpresion(CadTemporal) x1 = cx + x * ex y1 = cy + y * (ey * -1) For x = Li + Dx To Ls Step Dx CadTemporal = Reemplazar(CadenaExpresion, "X", x) CadTemporal = " " + CadTemporal + " "

y = EvaluarExpresion(CadTemporal) x2 = cx + x * ex y2 = cy + y * (ey * -1) Grafico.DrawLine(pen, x1, y1, x2, y2) x1 = x2 y1 = y2 'Grafico.FillRectangle(Brushes.Blue, x2, y2, ex, ey) ListBox1.Items.Add(x & " " & y) Next End Sub Private Sub btnVarXA_Click(sender As Object, e As EventArgs) Handles btnVarXC.Click Dim CadTemporal1, CadTemporal2 As String Dim x1, y1, x2, y2, x, y As Single Dim vc As Single

Page 280: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -1024-

CadenaEcuacion = txtEcuacion.Text ObtenerValores() ObtenerCadenas() CadC = "C" CadX = "X" CadenaExpresion = ObtenerEcuacion(CadenaEcuacion, CadA, CadB, CadC, CadD, CadE, CadX) CadenaExpresion = " " + CadenaExpresion + " " TxtExpresion.Text = CadenaExpresion coordenadas(cx, cy) Dx = (Ls - Li) / Ndiv DataGridView1.Rows(5).Cells(1).Value = Dx For vc = Li To Ls Step Dx CadTemporal1 = Reemplazar(CadenaExpresion, "C", vc) x = Li CadTemporal2 = Reemplazar(CadTemporal1, "X", x) CadTemporal2 = " " + CadTemporal2 + " " y = EvaluarExpresion(CadTemporal2) x1 = cx + x * ex y1 = cy + y * (ey * -1) For x = Li + Dx To Ls Step Dx CadTemporal2 = Reemplazar(CadTemporal1, "X", x) y = EvaluarExpresion(CadTemporal2) x2 = cx + x * ex y2 = cy + y * (ey * -1) Grafico.DrawLine(pen, x1, y1, x2, y2) x1 = x2 y1 = y2 Next Next End Sub Private Sub BtnXd_Click(sender As Object, e As EventArgs) Handles BtnXd.Click Dim CadTemporal1, CadTemporal2 As String Dim x1, y1, x2, y2, x, y As Single Dim vd As Single CadenaEcuacion = txtEcuacion.Text ObtenerValores() ObtenerCadenas() CadD = "D" CadX = "X" CadenaExpresion = ObtenerEcuacion(CadenaEcuacion, CadA, CadB, CadC, CadD, CadE, CadX) CadenaExpresion = " " + CadenaExpresion + " " TxtExpresion.Text = CadenaExpresion coordenadas(cx, cy) Dx = (Ls - Li) / Ndiv DataGridView1.Rows(5).Cells(1).Value = Dx For vd = Li To Ls Step Dx CadTemporal1 = Reemplazar(CadenaExpresion, "D", vd) x = Li CadTemporal2 = Reemplazar(CadTemporal1, "X", x)

Page 281: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -1025-

CadTemporal2 = " " + CadTemporal2 + " " y = EvaluarExpresion(CadTemporal2) x1 = cx + x * ex y1 = cy + y * (ey * -1) For x = Li + Dx To Ls Step Dx CadTemporal2 = Reemplazar(CadTemporal1, "X", x) y = EvaluarExpresion(CadTemporal2) x2 = cx + x * ex y2 = cy + y * (ey * -1) Grafico.DrawLine(pen, x1, y1, x2, y2) x1 = x2 y1 = y2 Next Next End Sub Private Sub BtnVarXE_Click(sender As Object, e As EventArgs) Handles BtnVarXE.Click Dim CadTemporal1, CadTemporal2 As String Dim x1, y1, x2, y2, x, y As Single Dim ve As Single CadenaEcuacion = txtEcuacion.Text ObtenerValores() ObtenerCadenas() CadE = "E" CadX = "X" CadenaExpresion = ObtenerEcuacion(CadenaEcuacion, CadA, CadB, CadC, CadD, CadE, CadX) CadenaExpresion = " " + CadenaExpresion + " " TxtExpresion.Text = CadenaExpresion coordenadas(cx, cy) Dx = (Ls - Li) / Ndiv DataGridView1.Rows(5).Cells(1).Value = Dx For ve = Li To Ls Step Dx CadTemporal1 = Reemplazar(CadenaExpresion, "E", ve) x = Li CadTemporal2 = Reemplazar(CadTemporal1, "X", x) CadTemporal2 = " " + CadTemporal2 + " " y = EvaluarExpresion(CadTemporal2) x1 = cx + x * ex y1 = cy + y * (ey * -1) For x = Li + Dx To Ls Step Dx CadTemporal2 = Reemplazar(CadTemporal1, "X", x) y = EvaluarExpresion(CadTemporal2) x2 = cx + x * ex y2 = cy + y * (ey * -1) Grafico.DrawLine(pen, x1, y1, x2, y2) x1 = x2 y1 = y2 Next Next End Sub

Page 282: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -1026-

Private Sub BtnBorra_Click(sender As Object, e As EventArgs) Handles BtnBorra.Click Grafico.Clear(Color.Black) End Sub Private Sub btnCX_Click(sender As Object, e As EventArgs) Handles btnCX.Click Dim CadTemporal1, CadTemporal2 As String Dim x1, y1, x2, y2, x, y As Single Dim vc As Single CadenaEcuacion = txtEcuacion.Text ObtenerValores() ObtenerCadenas() CadC = "C" CadX = "X" CadenaExpresion = ObtenerEcuacion(CadenaEcuacion, CadA, CadB, CadC, CadD, CadE, CadX) CadenaExpresion = " " + CadenaExpresion + " " TxtExpresion.Text = CadenaExpresion coordenadas(cx, cy) Dx = (Ls - Li) / Ndiv DataGridView1.Rows(5).Cells(1).Value = Dx For x = Li + Dx To Ls Step Dx CadTemporal1 = Reemplazar(CadenaExpresion, "X", x) 'BtnBorra_Click(sender, e) System.Threading.Thread.Sleep(50) ' 1 segundo Application.DoEvents() Grafico.Clear(Color.Black) vc = Li CadTemporal2 = Reemplazar(CadTemporal1, "C", vc) y = EvaluarExpresion(CadTemporal2) x1 = cx + vc * ex y2 = cy + y * (ey * -1) For vc = Li + Dx To Ls Step Dx CadTemporal2 = Reemplazar(CadTemporal1, "C", vc) y = EvaluarExpresion(CadTemporal2) x2 = cx + vc * ex y2 = cy + y * (ey * -1) Grafico.DrawLine(pen, x1, y1, x2, y2) x1 = x2 y1 = y2 Next Next End Sub Private Sub BtnFractal_Click(sender As Object, e As EventArgs) Handles BtnFractal.Click Dim brocha As SolidBrush brocha = New SolidBrush(Color.FromArgb(255, 0, 0)) Dim cadena1 As String Dim Resultado As Single Dim cont As Integer = 0 CadenaEcuacion = txtEcuacion.Text ObtenerValores() ObtenerCadenas()

Page 283: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -1027-

CadenaExpresion = ObtenerEcuacion(CadenaEcuacion, CadA, CadB, CadC, CadD, CadE, CadX) TxtExpresion.Text = CadenaExpresion ListBox1.Items.Clear() Dx = (Ls - Li) / Ndiv For fila = Li To Ls Step Dx cadena1 = "" Resultado = Fractal(fila, cadena1) ' Console.WriteLine("cont {0} X {1} Y {2} {3} ", cont, fila, Resultado, cadena) ListBox1.Items.Add(" cont " & cont & " fila " & fila & "res " & Resultado & " cad " & cadena1) cont = cont + 1 Grafico.FillRectangle(brocha, cx + fila * ex, cy + Resultado * ey * (-1), ex, ey) Next ' Console.ReadLine() End Sub

Private Sub btnEvaluar_Click(sender As Object, e As EventArgs) Handles btnEvaluar.Click CadenaEcuacion = txtEcuacion.Text CadenaExpresion = " " + CadenaEcuacion + " " EvalRes = EvaluacionCorrecta(CadenaExpresion) If EvalRes = True Then Me.Text = "evalucion correcta" Else MsgBox("expresion incorrecta") End If txtResultado.Text = EvaluarExpresion(CadenaExpresion) End SubEnd Class

PROPUESTAS DE TRABAJOS DE INVESTIGACION

Los trabajos tienen que ser en modo visual . se deben presentar en grupos de 31. Aplicación de fractales y recursividad ejemplo modelización de terrenos2. Aplicación de autómatas celulares y computación universal. Juego de la vida en

2d y 3D3. Aplicación del programa del buscador en optimización en modo grafico4. Manejo del puerto USB5. Programación de ADN manejo de secuencias cadenas6. Programación genérica plantillas ( Templates)7. Base de datos biológica8. Aplicación 3d en opengl y visual estudio 2010, Simulación 3D9. Aplicaciones Web Lenguaje HTML, Java, etc. y su importancia10.Temas de inteligencia artificial como programación evolutiva , redes

neuronales,etc11.Sistemas de información en Office Excel12.My sql13.Automatización industrial plc, sensores, 14.Aplicaciones de sistemas de información para optimización15.Simulación 3d, ejemplo simio.etc

Page 284: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -1028-

16.Programación en Windows. Uso de otros controles como por ejemplo el Microsoft char

17.Programación genérica plantillas ( Templates)18.Seguridad de base de datos en sqlserver19.Otros temas relacionados al curso de sistemas de información20.usando recursividad encuentre la posicion de cada objeto y cuantos

elementos tiene cada uno

EVALUACION DE EXPRESIONE

Module Module2 Public Signo As Integer Function Evaluar(ByVal Txt As String) As String Dim i As Integer, oNB As Integer, fNB As Integer Dim P1 As Integer, P2 As Integer Dim Buff As String ' Dim T As String 'Para los calculos es necesario un punto en lugar de la coma Txt = Replace(Txt, ",", ".")

Page 285: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -1029-

'Ver si hay ( For i = 1 To Len(Txt) If Mid(Txt, i, 1) = "(" Then oNB = oNB + 1 Next i 'Si hay ( (abiertos), ver si concuerdan) (cerrados) If oNB > 0 Then For i = 1 To Len(Txt) If Mid(Txt, i, 1) = ")" Then fNB = fNB + 1 Next i Else 'No hay parentesis, Evalua directamente el calculo Evaluar = EvaluaExpresion(Txt) Exit Function End If If oNB <> fNB Then 'Los parentesis no concuerdan, mostrar mensaje de error de parentesis Return "ERROR" Exit Function End If

While oNB > 0 'busca el ultimo parentesis abierto P1 = InStrRev(Txt, "(") 'Busca el parentesis que cierra la expresion P2 = InStr(Mid(Txt, P1 + 1), ")") 'Evalua la expresion que esta entre parentesis Buff = EvaluaExpresion(Mid(Txt, P1 + 1, P2 - 1)) 'Reemplazar la expresion con el resultado y eliminar los parentesis Txt = Left(Txt, P1 - 1) & Buff & Mid(Txt, P1 + P2 + 1) oNB = oNB - 1 End While 'no mas parentesis, evaluar la ultima expresion Evaluar = EvaluaExpresion(Txt) End Function Function EvaluaExpresion(A As String) As String Dim T As Integer, S As Integer Dim B As String, i As Integer, C As Boolean Dim c1 As Double, c2 As Double, Signe As Integer Dim R As String, Fin As Boolean, z As Integer

'quitar los espacios A = Replace(A, " ", "")

While Not Fin For i = 1 To Len(A) T = Asc(Mid(A, i, 1)) If T < 48 And T <> 46 Or i = Len(A) Then If C Then 'evalua If i = Len(A) Then c2 = Val(Mid(A, S)) Else c2 = Val(Mid(A, S, i - S))

Page 286: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -1030-

End If R = Str(CalculSimple(c1, c2, Signo)) If i = Len(A) Then Fin = True Else A = Trim(R & Mid(A, i)) C = False End If Exit For Else 'separa la 1ra cifra c1 = Val(Left(A, i - 1)) Signe = T S = i + 1 C = True End If End If Next i End While 'reemplazar la expresión con el resultado EvaluaExpresion = Trim(R) End Function Function CalculSimple(n1 As Double, n2 As Double, Signe As Integer) As Double Select Case Signe Case 43 ' + CalculSimple = n1 + n2 Case 45 ' - CalculSimple = n1 - n2 Case 42 ' * CalculSimple = n1 * n2 Case 47 ' / CalculSimple = n1 / n2 'Aquí, agregar otro calculo... End Select End FunctionEnd Module

Module Module1 Sub TestCalcul() Dim A As String Dim Ret As String A = "(((3*(12.223+ 15)) - 7)*21)/7" Ret = Evaluar(A) 'Debug.Print Ret '= 224.007 A = "((123.32/2.67)*6)+2127.34" Ret = Evaluar(A) '=2404.46359550562 'Debug.Print Ret End Sub Sub Main() TestCalcul() Console.ReadLine()

Page 287: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -1031-

End SubEnd Module

Fractal

Module Module1 Dim Li, Ls, Dx As Single Dim x, y As Single Dim k As Single = 0.279 Dim umbral As Single = 2 Dim cont As Integer = 0 Function Fractal(Li As Single, ByRef cadres As String) As Single Dim fila As Integer cadres = "Dentro" Dim valor As Single = 0 x = Li cont = 0 For fila = 1 To 25 y = Math.Pow(x, 2) - k ' Console.WriteLine("fila {0} x {1} y {2}", fila, x, y) cont = cont + 1 If Math.Abs(y) > umbral Then cadres = "FUERA" Exit For End If x = y Next If cont > 24 Then valor = y Else valor = cont End If Return valor End Function

Sub Main()

Page 288: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -1032-

Dim cadena As String Dim Resultado As Single Dim cont As Integer = 0 Li = -2 Ls = 2 Dx = 0.05 For fila = Li To Ls Step Dx Resultado = Fractal(fila, cadena) Console.WriteLine("cont {0} X {1} Y {2} {3} ", cont, fila, Resultado, cadena) cont = cont + 1 Next Console.ReadLine() End SubEnd Module

Desarrollar un juego donde se mueve el fondo de la pantalla Usar colores como las que indican en el cuadro

Nro Color Significado0 negro camino limpio1 punto amarillo pequeño cambia la matriz2 naranja premio 10 puntos3 Verde pared4 rojo pierde e juego5 azul pierde una vida6 blanco Meta

11.19 VER UNA PARTE DE LA PANTALLA Modificar el programa para ver parte de una pantalla(corregir)

Page 289: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -1033-

'****** CODIGO DEL MODULO 1Imports System.IOModule Module1 Public Npremios As Integer = 10 Public Px As Integer = 10 ' posicion X del curso en la matrizal Public Py As Integer = 10 ' posicon Y del cursor en la matriz Public RxTem(10) As Integer ' variable para obtener temporal Public RyTem(10) As Integer ' variable y para obtener temporal Public RValor1(10) As Integer ' variable que almacena el valor Public RValor2(10) As Integer ' variable que almacena el valor

Public RX(10) As Integer ' coordenadas Y del enemigo Public RY(10) As Integer ' coordenadas Y del enemigo Public nene As Integer = 5 ' numero de enemigos Public generar As Integer = 0 Public CadRes1, CadRes2 As String Public vidas As Integer = 7 Public puntos As Integer = 0 Public pasos As Integer = 0 Public nvidas As Integer = 3 Public nf As Integer = 44 Public nc As Integer = 24 Public mov As Integer = 0 Public A(nf, nc) As Integer Public lapicero As Pen Public brocha As SolidBrush Public Grafico As Graphics Public Grafico2 As Graphics Public AnchoFigura As Integer = 500 Public AltoFigura As Integer = 500 Public cx As Integer = 0 Public cy As Integer = 0 Public ex As Integer = 50 Public ey As Integer = 50 Public EX1 As Integer = 12 Public EY1 As Integer = 10 Public paso As Integer = 1 Public nfmuestra As Integer = 10 Public ncmuestra As Integer = 10 Public nf1 As Integer = 5 Public nc1 As Integer = 5 Public posx As Integer = cx + nf1 Public posy As Integer = cy + nc1 Public tpx As Integer = cx + nf1 Public tpy As Integer = cy + nc1 Public NombreArchivo As String = "E:\datos\matriz24x44.txt" Sub MostrarMatriz(grafico As Graphics, ByVal Cx As Integer, ByVal Cy As Integer, ByVal A(,) As Integer, ByVal nf As Integer, ByVal nc As Integer, ex As Integer, ey As Integer) Dim ancho1, alto1 As Integer ancho1 = ex / 3 alto1 = ey / 3

Page 290: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -1034-

Dim fila, col As Integer For fila = 0 To nf - 1 For col = 0 To nc - 1 Select Case A(Cy + fila, Cx + col) Case 0 Case 1 : grafico.FillRectangle(Brushes.Yellow, col * ex + ancho1, fila * ey + alto1, ancho1, alto1) Case 2 : grafico.FillRectangle(Brushes.Orange, col * ex, fila * ey, ex, ey) Case 3 : grafico.FillRectangle(Brushes.Green, col * ex, fila * ey, ex, ey) Case 4 : grafico.FillRectangle(Brushes.Blue, col * ex, fila * ey, ex, ey) Case 5 : grafico.FillRectangle(Brushes.Red, col * ex, fila * ey, ex, ey) Case 6 : grafico.FillRectangle(Brushes.White, col * ex, fila * ey, ex, ey) Case 7 : grafico.FillRectangle(Brushes.Yellow, col * ex, fila * ey, ex, ey) End Select grafico.DrawRectangle(Pens.Red, col * ex, fila * ey, ex, ey) Next Next End Sub

Sub RecuperarMatriz(ByVal nombrearchivo As String, ByRef A(,) As Integer, ByRef nf As Integer, ByVal nc As Integer) Dim srLector As StreamReader srLector = New StreamReader(nombrearchivo) Dim fila As Integer = 0, col As Integer Dim cadena As String = "" Dim subcadena As String Dim pos As Integer = 0 Dim inicio As Integer = 1 cadena = srLector.ReadLine() Do While Not (cadena Is Nothing) cadena = cadena & Chr(9) inicio = 1 For col = 0 To nc - 1 pos = InStr(inicio, cadena, Chr(9)) subcadena = Mid(cadena, inicio, pos - inicio) A(fila, col) = Val(subcadena) inicio = pos + 1 Next fila = fila + 1 cadena = srLector.ReadLine() Loop nf = fila srLector.Close() End Sub Function factible(X() As Integer, Y() As Integer, n As Integer, Nx As Integer, ny As Integer) As Integer Dim fila As Integer Dim res As Integer = 1 For fila = 0 To n - 1 If Nx = X(fila) And ny = Y(fila) Then res = 0 Exit For

Page 291: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -1035-

End If Next Return res End Function Sub copiarVector(A() As Integer, B() As Integer, ne As Integer) Dim fila As Integer For fila = 0 To ne - 1 B(fila) = A(fila) Next End Sub Sub premio() Dim fila, rx1, ry1 As Integer For fila = 0 To nene - 1 generar = 0 Do rx1 = 2 + Int(Rnd() * (nc - 4)) ry1 = 2 + Int(Rnd() * (nf - 4)) If A(ry1, rx1) <= 1 Then A(ry1, rx1) = 2 generar = 1 End If Loop While generar = 0 Next End SubEnd Module

' **** CODIGO DEL FORMULARIOPublic Class Form1 Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load PictureBox1.Width = AnchoFigura PictureBox1.Height = AltoFigura Grafico = PictureBox1.CreateGraphics Grafico2 = PictureBox2.CreateGraphics Grafico.DrawRectangle(Pens.Red, cx, cy, ex, ey) brocha = New SolidBrush(Color.FromArgb(255, 255, 0)) lapicero = New Pen(Color.FromArgb(255, 0, 0), 5) RecuperarMatriz(NombreArchivo, A, nf, nc) MostrarMatriz(Grafico, cx, cy, A, nfmuestra, ncmuestra, ex, ey) Grafico.FillRectangle(Brushes.Yellow, posx * ex, posy * ey, ex, ey) MostrarMatriz(Grafico2, 0, 0, A, nf, nc, EX1, EY1) TextBox1.Focus() End Sub Sub ImprimirElementoMatriz(grafico As Graphics, cx As Integer, cy As Integer, dx As Integer, dy As Integer, ex As Integer, ey As Integer, valor As Integer) Dim ancho1, alto1 As Integer ancho1 = ex / 3 alto1 = ey / 3 Select Case valor Case 0 : Grafico.FillRectangle(Brushes.Black, cx + dx * ex, cy + dy * ey, ex, ey) Case 1 : Grafico.FillRectangle(Brushes.Yellow, cx + dx * ex + ancho1, cy + dy * ey + alto1, ancho1, alto1)

Page 292: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -1036-

Case 2 : Grafico.FillRectangle(Brushes.Orange, cx + dx * ex, cy + dy * ey, ex, ey) Case 3 : Grafico.FillRectangle(Brushes.Green, cx + dx * ex, cy + dy * ey, ex, ey) Case 4 : Grafico.FillRectangle(Brushes.Blue, cx + dx * ex, cy + dy * ey, ex, ey) Case 5 : Grafico.FillRectangle(Brushes.Red, cx + dx * ex, cy + dy * ey, ex, ey) Case 6 : Grafico.FillRectangle(Brushes.White, cx + dx * ex, cy + dy * ey, ex, ey) Case 7 : Grafico.FillRectangle(Brushes.Yellow, cx + dx * ex, cy + dy * ey, ex, ey) 'amarillo grande End Select Grafico.DrawRectangle(Pens.Red, cx + dx * ex, cy + dy * ey, ex, ey) End Sub Private Sub TextBox1_KeyDown_1(sender As Object, e As KeyEventArgs) Handles TextBox1.KeyDown Dim tposx, tposy, valor As Integer Dim Cantes, Ctemp, cDespues As String cx = Px - nc1 cy = Py - nf1 Cantes = "py " & posy & "Px" & posx & "valor " & A(posy, posx) tpx = Px tpy = py Select Case e.KeyCode Case Keys.Left If tpx > nc1 Then tpx = tpx - paso Case Keys.Right If tpx < nc - nc1 Then tpx = tpx + paso Case Keys.Up If tpy > nf1 Then tpy = tpy - paso Case Keys.Down If tpy < nf - nf1 Then tpy = tpy + paso End Select pasos = pasos + 1 valor = A(tpy, tpx) Ctemp = " Temp py " & tpy & "Px" & tpx & "valor " & A(tpy, tpx) ' en el juego aumentar velocidad Select Case A(tpy, tpx) Case 0 ' camina limpia no retorna Case 1 ' punto amariloo pequeño cuadro en la matriz no retorna gana puntos y no retorna ' reemplaza a la matriz con 0 A(tpy, tpx) = 0 puntos = puntos + 1 Case 2 'naranja gana 10 puntos no retorna reemplaza a la matriz con cero puntos = puntos + 10 A(tpy, tpx) = 0 Case 3 'verde no puede caminar retorna al anterior tpx = Px tpy = py A(tpy, tpx) = 0 ' Case 4 'Azul pierde una vida retrocede ' vidas = vidas - 1 Case 5 ' rojo pierde el juego MsgBox(" Juego terminado ") Case 6 'blanco llega a la meta

Page 293: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -1037-

MsgBox("llego a la meta ") End Select For fila = 0 To nene - 1 If (tpx = RX(fila)) And (tpy = RY(fila)) Then vidas = vidas - 1 Next Px = tpx Py = tpy cx = Px - nc1 cy = Py - nf1 cDespues = " Despues Temp posy " & Px & "Posx" & Py & "valor " & A(tposy, tposx) ListBox1.Items.Clear() ListBox1.Items.Add(Cantes) ListBox1.Items.Add(Ctemp) ListBox1.Items.Add(cDespues) If vidas > 0 Then Grafico.Clear(Color.Black) Grafico2.Clear(Color.Black) mov = mov + 1 MostrarMatriz(Grafico, cx, cy, A, nfmuestra, ncmuestra, ex, ey) MostrarMatriz(Grafico2, 0, 0, A, nf, nc, EX1, EY1) For fila = 0 To nene - 1 ImprimirElementoMatriz(Grafico, cx, cy, RX(fila) - cx, RY(fila) - cy, ex, ey, 4) ImprimirElementoMatriz(Grafico2, 0, 0, RX(fila), RY(fila), EX1, EY1, 4) Next ImprimirElementoMatriz(Grafico, cx, cy, posx, posy, ex, ey, 7) ImprimirElementoMatriz(Grafico2, 0, 0, Px, Py, EX1, EY1, 7) CadRes1 = "Mov " + Str(mov) + " Puntos " + Str(puntos) + " vidas " + Str(vidas) Label1.Text = CadRes1 TextBox1.Focus() Else MsgBox("juego terminado") End If End Sub Private Sub btnRecuperar_Click(sender As Object, e As EventArgs) Handles btnRecuperar.Click Dim fila, rx1, ry1 As Integer Randomize() RecuperarMatriz(NombreArchivo, A, nf, nc) For fila = 0 To nene - 1 generar = 0 Do rx1 = 2 + Int(Rnd() * (nc - 4)) ry1 = 2 + Int(Rnd() * (nf - 4)) If A(ry1, rx1) <= 1 And factible(RX, RY, fila, rx1, ry1) = 1 Then RX(fila) = rx1 RY(fila) = ry1 generar = 1 End If Loop While generar = 0 Next For fila = 0 To nene - 1

Page 294: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -1038-

RValor2(fila) = A(RY(fila), RX(fila)) Next copiarVector(RX, RxTem, nene) copiarVector(RY, RyTem, nene) copiarVector(RValor2, RValor1, nene) Grafico.Clear(Color.Black) posx = 5 ' nfmuestra/2 posy = 5 cx = 0 cy = 0 Px = cx + nc1 Py = cy + nf1 MostrarMatriz(Grafico, cx, cy, A, nfmuestra, ncmuestra, ex, ey) MostrarMatriz(Grafico2, 0, 0, A, nf, nc, EX1, EY1) ImprimirElementoMatriz(Grafico, cx, cy, posx, posy, ex, ey, 7) For fila = 0 To nene - 1 ImprimirElementoMatriz(Grafico, cx, cy, RX(fila) - cx, RY(fila) - cy, ex, ey, 4) ImprimirElementoMatriz(Grafico2, cx, cy, RX(fila) - cx, RY(fila) - cy, EX1, EY1, 4) Next ImprimirElementoMatriz(Grafico2, 0, 0, Px, Py, EX1, EY1, 7) CadRes1 = "Mov " + Str(mov) + " Puntos " + Str(puntos) + " vidas " + Str(vidas) Label1.Text = CadRes1 CadRes2 = "Cx " + Str(cx) + " Cy " + Str(cy) + "Px " + Str(Px) + "Py " + Str(Py) txtMov.Text = CadRes2 premio() TextBox1.Focus() End Sub Private Sub btnMostrar_Click(sender As Object, e As EventArgs) Handles btnMostrar.Click MostrarMatriz(Grafico, cx, cy, A, nfmuestra, ncmuestra, ex, ey) Grafico.FillRectangle(Brushes.Blue, posx * ex, posy * ey, ex, ey) MostrarMatriz(Grafico2, 0, 0, A, nf, nc, EX1, EY1) End Sub Private Sub btnMover_Click(sender As Object, e As EventArgs) Handles btnMover.Click Timer1.Interval = 200 Timer1.Enabled = True End Sub Sub MoverEnemigo() Dim resultado As Integer = 0 Dim Ancho1, alto1 As Integer Dim Nr As Integer Application.DoEvents() ancho1 = ex / 3 alto1 = ey / 3 ' lo elimina y recupera el valor anterior For fila = 0 To nene - 1 ‘ ImprimirElementoMatriz(Grafico, cx, cy, RxTem(fila) - cx, RyTem(fila) - cy, ex, ey, 0) ' ImprimirElementoMatriz(Grafico2, 0, 0, RxTem(fila), RyTem(fila), EX1, EY1, 0) ImprimirElementoMatriz(Grafico, cx, cy, RxTem(fila) - cx, RyTem(fila) - cy, ex, ey, RValor1(fila))

Page 295: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -1039-

ImprimirElementoMatriz(Grafico2, 0, 0, RxTem(fila), RyTem(fila), EX1, EY1, RValor1(fila)) Next For fila = 0 To nene - 1 resultado = 0 Do Nr = 1 + Int(Rnd() * 4) Select Case Nr Case 1 If A(RY(fila), RX(fila) + 1) <> 3 And RX(fila) + 1 < nc - 2 Then RX(fila) = RX(fila) + 1 RValor2(fila) = A(RY(fila), RX(fila) + 1) resultado = 1 End If Case 2 If A(RY(fila) - 1, RX(fila)) <> 3 And RY(fila) - 1 > 2 Then RY(fila) = RY(fila) - 1 RValor2(fila) = A(RY(fila) - 1, RX(fila)) resultado = 1 End If Case 3 If A(RY(fila), RX(fila) - 1) <> 3 And RX(fila) - 1 > 2 Then RX(fila) = RX(fila) - 1 RValor2(fila) = A(RY(fila), RX(fila) - 1) resultado = 1 End If Case 4 If A(RY(fila) + 1, RX(fila)) <> 3 And RY(fila) + 1 < nf - 2 Then RY(fila) = RY(fila) + 1 RValor2(fila) = A(RY(fila) + 1, RX(fila)) resultado = 1 ' End If End Select Application.DoEvents() Loop While resultado = 0 Next '' quitar vidas For fila = 0 To nene - 1 If (RX(fila) = Px And RY(fila) = Py) Then vidas = vidas - 1 CadRes1 = "Mov " + Str(mov) + " Puntos " + Str(puntos) + " vidas " + Str(vidas) Label1.Text = CadRes1 If vidas <= 0 Then MsgBox("juego terminado ") Exit Sub End If ImprimirElementoMatriz(Grafico, cx, cy, RX(fila) - cx, RY(fila) - cy, ex, ey, 4) ImprimirElementoMatriz(Grafico2, 0, 0, RX(fila), RY(fila), EX1, EY1, 4) Next copiarVector(RX, RxTem, nene) copiarVector(RY, RyTem, nene) copiarVector(RValor2, RValor1, nene)

Page 296: Lp11 Aplicaciones Windows Form

Lenguaje de programación 2014B \11 Aplicaciones Windows Forms \Ismael Véliz Vilca -1040-

Application.DoEvents() End Sub

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick MoverEnemigo() Application.DoEvents() End Sub

Private Sub btnDetener_Click(sender As Object, e As EventArgs) Handles btnDetener.Click Timer1.Enabled = False End Sub End Class