Sie sind auf Seite 1von 217

Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -823-

Contenido
10 APLICACIONES EN WINDOWS FORM................................................................. 825
10.1 EJEMPLO DE APLICACIÓN COMPLETA CON MENUS Y BARRA DE
HERRAMIENTAS ..................................................................................................... 825
10.2 MENU DE MODELADO 2D. ............................................................................. 837
10.3 TEMAS FRACTALES ....................................................................................... 851
La alfombra de Sierpiński...................................................................................... 851
CREACION DE UNA MONTAÑA FRACTAL ........................................................ 853
ARBOLES CON RECURSIVIDAD ........................................................................ 854
El copo de nieve de Koch, .................................................................................... 854
FRACTALES DE MALDEBROT ............................................................................ 863
10.4 MONTAÑA FRACTAL ...................................................................................... 867
10.5 SIMULACION DE POLITICAS DE INVENTARIOS DE CONTROL DE
INVENTARIOS ......................................................................................................... 883
10.6 TRIANGULACION DE DELAUNAY (HECHO CAMBIAR Y MODIFICAR ..... Error!
Bookmark not defined.
10.7 APLICACIÓN DE TRADUCTOR DE ARCHIVOS ............................................. 888
10.8 BUSCADOR MODO FORMUALRIOS .............................................................. 890
10.9 PROBLEMA DE CRUCE .................................................................................. 909
10.10 PROGRAMA DE LOCALIZACION DE LOTES............................................... 912
10.11 MODELADO 3D ................................................. Error! Bookmark not defined.
10.12 MODELADO 3D ( primitivas) REPITIDO ........................................................ 918
10.13 MODELADO 3D (DIBUJO DE MALLAS ) SI ENTRA OPENGL NO
CONSIDERAR ......................................................................................................... 918
10.14 PROBLEMA DE CONDUCCION DE VEHICULOS ( RESUMIR CON OTROS
SIMILARES) ................................................................. Error! Bookmark not defined.
10.15 PROBLEMA DE CONDUCCION DE VEHICULOS USADO BITMAPS LIBRO2
..................................................................................... Error! Bookmark not defined.
10.16 MOVER UN ARCHIVO DE TEXTO ................... Error! Bookmark not defined.
10.17 MADURACION DE UNA FRUTA (ejemplo platanos) ........ Error! Bookmark not
defined.
10.18 JUEGO DEL PACMAN ................................................................................... 929
10.19 GRAFICA DE FUNCIONES EN 2D Y 3D ....................................................... 936
10.20 PROCESAMIENTO DE IMAGNES EN VISUAL BASIC .... Error! Bookmark not
defined.
10.21 JUEGO DE LA SERPIENTE O GUSANO(USO DE AUTOMATAS
CELULARES) ........................................................................................................... 945
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -824-
10,22 DICCIONARIO TRADUCTOR ........................................................................ 949
10.23 DICCIONARIO TRADUCTOR EN MODO CONSOLA. PASAR A MODO
OCNSOLA ................................................................................................................ 952
TRADUCTOR MODIFICADO ( usando cuadros de dialogo) ................................954
10.24 CUADRO CROMATICO ................................................................................. 957
Tarea.- Elaborar Gama de colores o circulo cromático(use el triangulo para cad
color)( Estudiar el cuadro cromaico...................................................................... 958
10.25 EVALUACION DE EXPRESIONES MUY LARGO ......................................... 959
10.26 PROPUESTAS DE TRABAJOS DE INVESTIGACION .................................. 973
10.27 EVALUACION DE ALUACION DE EXPRESIONES PASARLO AL CAPITULO
INTERIRO ................................................................................................................ 974
Desarrollar un juego donde se mueve el fondo de la pantalla .............................. 977
10.28 VER UNA PARTE DE LA PANTALLA REPITIDO ......................................... 977
10.29 DIBUJE EL SIGUIENTE PLANO .................................................................... 985
10.30 TRANSPARENCIAS( Juntarlo con el problema del avion) ............................. 992
10.31 JUEGO DE LA VIDA DE ................................................................................ 995
10.31 La construcción de un brazo Robot articulado. PASA A GRAFICOS .......... 1003
10.33 Problema de objetos usando arreglos(tarea) .............................................. 1005
10.34 APLICACIONES DE 3 COLORES(se observa la mezcla de colores ........... 1012
10.35 Iluminacion ................................................................................................... 1015
10.36 Procesamiento de Imágenes y aplicaciones REPITIDO .............................. 1018
10.37 TAREA. ........................................................................................................ 1030
10.38 APLICACIÓN DEL MODELO EN DETECCION DE MANCHAS DE LANA
REPITIDO .............................................................................................................. 1031
10.39N -30 PROCESAMIENTO DE IMAGNES EN VISUAL BASIC 2012 ........... Error!
Bookmark not defined.
10.40 IMAGEN CON BARRAS DE DEZPLAZAMIENTO ...................................... 1032
ARBOLES ........................................................................................................... 1034
10.42 TRABAJO DE TRAINGULACION CON INTEGRALES ............................... 1035
este progrma obtiene cualquer area de puntos dados ........................................ 1036
1 ................................................................................... Error! Bookmark not defined.
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -825-
10 APLICACIONES EN WINDOWS FORM

10.1 EJEMPLO DE APLICACIÓN COMPLETA CON MENUS Y BARRA DE


HERRAMIENTAS

1. TRABAJANDO CON INTERFACES DE MULTIPLES DOCUMENTOS

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 FormularioMDI


2. 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 Valor


Form1 isMdiContainer True
Text Editor de Documentos v 1.0
MenuStrip1 Name MenuStrip1
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -826-
OpenFileDialog1 Name OpenFileDialog1
SaveFileDialog1 Name SaveFileDialog1
ColorDialog1 Name ColorDialog1
FontDialog1 Name FontDialog1
Timer1 Name Timer1
ToolStrip1 Name ToolStrip1
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 Valor


MenuItem1 Name mnuArchivo
Text &Archivo
MenuItem11 Name mnuNuevo
ShortCut CtrlN
Text &Nuevo
MenuItem12 Name mnuAbrir
ShortCut CtrlA
Text &Abrir
MenuItem13 Name mnuGuardar
ShortCut CtrlG
Text &Guardar
MenuItem14 Name mnuLinea1
Text -
MenuItem15 Name mnuSalir
ShortCut CtrlS
Text &Salir
MenuItem2 Name mnuEdición
Text &Edición
MenuItem21 Name mnuCopiar
ShortCut CtrlC
Text &Copiar
MenuItem22 Name mnuCortar
ShortCut CtrlX
Text Co&rtar
MenuItem23 Name MnuPegar
ShortCut CtrlV
Text &Pegar
MenuItem3 Name mnuFormato
Text &Formato
MenuItem31 Name mnuFuente
Text Fuente
MenuItem32 Name mnuFondo
Text Color de Fondo
MenuItem4 Name mnuUtilitario
Text &Utilitarios
MenuItem41 Name mnuWindows
Text Windows
MenuItem411 Name mnuCalculadora
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -827-
Text Calculadora
MenuItem412 Name MnuBloc
Text Bloc de Notas
MenuItem413 Name mnuExplorador
Text Explorador
MenuItem42 Name MnuOffice
Text Office
MenuItem421 Name MnuWord
Text Word
MenuItem422 Name MnuExcel
Text Excel
MenuItem423 Name mnuInternet
Text Internet Explorer
MenuItem5 Name mnuVentana
Text &Ventana
MenuItem51 Name Cascada
Tag 0
Text Cascada
MenuItem52 Name mnuMHorizontal
Tag 1
Text Mosaico Horizontal
MenuItem53 Name mnuMVertical
Tag 2
Text Mosaico Vertical
MenuItem54 Name mnuOIcons
Tagr 3
Text Organizar Iconos
MenuItem55 Name MnuLinea2
Text -
MenuItem56 Name MnuListar
MdiList True
Text Listar Ventanas
Para cambiar el nombre de cada menú hacer clic en menu strip y luego editar elementos

Aparece el siguiente cuadro


Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -828-

Elija DropDownItems

Hay podria cambiar los nombres


Tambien podria cambiar con el cuadro de propiedades

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:
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -829-

En image escoger

Objeto Propiedad Valor


Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -830-
ToolBarButton1 Name tbbNuevo
Image …\bitmaps\Tlbr_W95\New.bmp
ToolTipText Nuevo
Tag Nuevo
ToolBarButton2 Name tbbAbrir
ImageIndex \bitmaps\Tlbr_W95\Open.bmp
ToolTipText Abrir
Tag Abrir
ToolBarButton3 Name tbbGuardar
ImageIndex Save.bmp
ToolTipText Guardar
Tag Guardar
ToolBarButton4 Name tbbSeparador1
Style Separator
Tag Separator1
ToolBarButton5 Name tbbCopiar
ImageIndex …\bitmaps\Tlbr_W95\Copy.bmp
ToolTipText Copiar
Tag Copiar
ToolBarButton6 Name tbbCortar
ImageIndex …\bitmaps\Tlbr_W95\Copy.bmp
ToolTipText Cortar
Tag Cortar
ToolBarButton7 Name tbbPegar
ImageIndex …\bitmaps\Tlbr_W95\paste.bmp
ToolTipText Pegar
Tag Pegar
ToolBarButton8 Name tbbSeparador2
Style Separator
Tag Separator2
ToolBarButton9 Name tbbSalir
ImageIndex …\bitmaps\Tlbr_W95\redo.bmp6
ToolTipText Salir
Tag Salir

Al final debe quedar así


Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -831-

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 Valor


StatusBarPanel1 Name sbpNombre
Icon …\Icons\Writing\Book01A.ico
Width
StatusBarPanel2 Name sbpMayuscula
Text CAPS
StatusBarPanel3 Name sbpFechaHora
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -832-
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 Valor


Form2 Text Documento
ContextMenuStrip2 Name ContextMenuStrip2
RichTextBox1 Name RichTextBox1
ContextMenu ContextMenuStrip
Dock Fill
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 DEL FORMULARIO

Imports System.IO 'Usar Path


Public 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

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


System.EventArgs) Handles MnuNuevo.Click
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -833-
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
Private Sub CortarTexto(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles mnuCortar.Click
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -834-
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

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


System.EventArgs) Handles MnuExplorador.Click
Process.Start("Explorer.exe")
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -835-
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"
mnuCortar.PerformClick()
Case "Pegar"
MnuPegar.PerformClick()
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -836-
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 Sub
End Class

Ejecute el programa . la aplicación debera quedar asi

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

Y automáticamente se inserta los elementos estándar


Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -837-

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

10.2 MENU DE MODELADO 2D.

La siguiente aplicación tiene por objeto mostrar , como se realiza un menu de opciones,
y manejo de pinceles brochas , metodos graficos colores y transparencias
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -838-

La aplicación tiene el siguiente menu


Menú Archivo

Iniciar.- Permite poner valores iniciales


Abrir Cuad1. Permite abrir la lista de objetos y sus características en este caso ( lo que
se muestra en el cuadro 1 ) y permite mostrar en un DataGridView ( para ello se usa el
control OpenFiLeDialog)

Nro anguloR Radi Nlado Transparenci Roj Verd Azu


tx ty Ex Ey
. z o s a o e l
17 20
0 90 0 0 3 3 40 4 123 255 255 0
30 18
1 100 0 0 2 2 40 6 100 255 0 0
20 17
2 2 0 9 4 2 20 3 50 0 255 0
20 10
3 33 0 0 6 8 10 4 100 0 0 255
17 12 5, 1,
4 4 0 0 6 8 10 5 150 255 255 0
14 15
5 5 5 0 1 1 15 4 200 250 255 255
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -839-
Las columnas del cuadro significan ( en este caso de las filas 1 al 5)

Nro.:- Numero del objeto


AnguloRz. Angulo de giro alrededor del eje Z
Tx= Traslación en el eje X del objeto seleccionado
Ty= Traslación en el eje Y del objeto seleccionado
Ex= Escalado en el eje X del objeto seleccionado
Ex= Escalado en el eje Y del objeto seleccionado
Radio= radio del poligono
Nlados.- Numero de lados que puede tener el polígono de 3 a 12 lados
Transparencia:- El valor de transparencia del objeto seleccionado
Rojo,Verde, Azul- Los color rojo ,verde y azul del objeto seleccionado

GrabarCuadricula.1- permite grabar los datos modificados en el Datagridview1( para


ello se usa el control SaveFileDialog)

GrabarCuadricula 2.- permite grabar los datos modificados en el Datagridview2( en este


caso graba los vértices de cada polígono)
Salir. Permite salir del sistema
Menu Simulación

Borra:- Borra el cuadro de grafico


Manual.- Escoge aleatoriamente un objeto y cambia sus propiedades y de acuerdo
realiza las operaciones adecuadas( esta menú se realiza en forma manual)
Automático. Realiza la operación anterior en forma automática

DetenerAleatorio.- Detiene el menú Automatico


Generar. Genera los vértices de cada polígono en el cuadro 2de acuerdo a los
parámetros dados en el cuadro 1
Graficar Poligono.- Grafica polígono en el Picture Box

Menu Edición

Edición Manual. Modifica los valores de un vértice aleatoriamente en forma manual


Edición Automática. Lo mismo que la opción anterior pero en forma automática
Detener. Detiene la edición automática
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -840-
Nro anguloR E E Radi Nlado Transparenci Roj Verd Azu
tx Ty
. z x y o s a o e l
17 20
0 90 0 0 3 3 40 4 123 255 255 0

El significado de los valores es:

Anguloz: Variación del Angulo de giro de los objetos


Tx.- la variación de traslación en el eje X de los objetos
Ty.- la variación de traslación en el eje Y de los objetos
Ex.- la variación de escalado X de los objetos
Ey.- la variación de escalado Y de los objetos
Radio.- del poligono
Nlados.- aquí se obtiene la velocidad para el modo automático
Transparencia, rojo , verde y azul .- De los objetos

SELECCIÓN DE LOS OBJETOS

Los objetos se seleccionan de la siguiente


Escogiendo el objeto en el cuadro combinado
Las operaciones de rotación ,traslación y escalado se realizan mediante el evento
KeyDows del teclado

Para la operación de rotación posicione el cursor en la caja de texto txtRotacion y rote


el objeto seleccionado con la tecla Z(horario) y tecla C ( anti horario)

Para la traslación posicione el cursor en la caja de texto txtTraslacion y traslade el objeto


seleccionado con la tecla X e Y ( para avanzar) y teclas A yB ( para retroceder)

Para El Escalado posicione el cursor en la caja de texto txtescalado y escale el objeto


seleccionado con la tecla X e Y ( para aumentar) y teclas A yB ( para desminuir)

Puede también modificar cualquier npropiedad del objeto seleccionado cambiando sus
valores en el dataGridView

El evento mousedows del objeto picture box permite acercar el vértice del objetos
seleccionado al coordenadas del ratón

NOTA. Falta agregar opciones de agregar , eliminar objeto , barra de herramientas ,


barra de estado , menú contextual y formularios MDI

CODIGO DEL FORMULARIO

Imports System.IO
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -841-
Imports System.Drawing
Imports System.Drawing.Drawing2D
Public Class Form1
Sub MostrarMatrizFormulario(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
DataGridView1.Rows(fila).Cells(col).Value = A(fila, col)
Next
Next
End Sub
Sub MostrarMatrizPoligonos(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 Ncol1 - 1
DataGridView2.Rows(fila).Cells(col * 2).Value = A(fila, col * 2)
DataGridView2.Rows(fila).Cells(col * 2 + 1).Value = A(fila, col * 2 + 1)
Next
Next
End Sub
Sub IniciarTodo()
Dim col As Integer
DataGridView1.RowCount = Nfilas1
DataGridView1.ColumnCount = 12
For col = 0 To 11 '
DataGridView1.Columns(col).Width = 34
Next col
For fila = 0 To 7
DataGridView1.Rows(fila).HeaderCell.Value = "F" & fila
Next
DataGridView1.Columns(0).HeaderText = "Nro"
DataGridView1.Columns(0).HeaderText = "Nro"
DataGridView1.Columns(1).HeaderText = "Az"
DataGridView1.Columns(2).HeaderText = "Tx"
DataGridView1.Columns(3).HeaderText = "Ty"
DataGridView1.Columns(4).HeaderText = "Ex"
DataGridView1.Columns(5).HeaderText = "Ey"
DataGridView1.Columns(6).HeaderText = "Radio"
DataGridView1.Columns(7).HeaderText = "Nlados"
DataGridView1.Columns(8).HeaderText = "Transparencia"
DataGridView1.Columns(9).HeaderText = "Rojo"
DataGridView1.Columns(10).HeaderText = "Verde"
DataGridView1.Columns(11).HeaderText = "Azul"
End Sub
Sub Coordenadas()
grafico.DrawLine(Pens.Blue, -lim, 0, lim, 0)
grafico.DrawLine(Pens.Blue, 0, -lim, 0, lim)
End Sub
Sub inicio2()
Dim col, fila As Integer
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -842-
DataGridView2.RowCount = 10
DataGridView2.ColumnCount = Ncol1 * 2
DataGridView2.Columns(0).HeaderText = "Punto"
For col = 0 To Ncol1 - 1
DataGridView2.Columns(col * 2).Width = 40
DataGridView2.Columns(col * 2 + 1).Width = 40
DataGridView2.Columns(col * 2).HeaderText = "X" & col
DataGridView2.Columns(col * 2 + 1).HeaderText = "Y" & col
Next
For fila = 0 To nf - 1
DataGridView2.Rows(fila).HeaderCell.Value = "F" & fila
Next
End Sub
Private Sub MnuIniciar_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MnuIniciar.Click
IniciarTodo()
End Sub
Private Sub MenuBorrar_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MnuBorrar.Click
grafico.Clear(Color.Black)
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
grafico = PictureBox1.CreateGraphics
pincel = New Pen(Brushes.Red, 1)
brocha = New SolidBrush(Color.Green)
IniciarTodo()
inicio2()
End Sub
Private Sub MenuAbrir(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MnuAbrirCuad1.Click
OpenFileDialog1.ShowDialog()
NombreArchivo = OpenFileDialog1.FileName
RecuperarDeMatriz(NombreArchivo, A, nf, nc)
MostrarMatrizFormulario(A, nf, nc)
' inicilzalar combobox
ComboBox1.Items.Clear()
For fila = 0 To nf - 1
ComboBox1.Items.Add(fila)
Next
ComboBox1.Text = 1
End Sub
Sub graficarPoligono(ByVal X() As Single, ByVal Y() As Single, ByVal np As Integer)
Dim Puntos(np - 1) As Point
For fila = 0 To np - 1
Puntos(fila).X = X(fila)
Puntos(fila).Y = Y(fila)
Next
grafico.FillPolygon(brocha, Puntos)
grafico.DrawPolygon(pincel, Puntos)
End Sub
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -843-
Sub ObtenerVectoresXY(ByVal nroFila As Integer, ByRef X() As Single, ByRef Y() As
Single, ByVal ne As Integer)
Dim col As Integer
For col = 0 To ne - 1
X(col) = DataGridView2.Rows(nroFila).Cells(col * 2).Value
Y(col) = DataGridView2.Rows(nroFila).Cells(col * 2 + 1).Value
Next
End Sub
Sub GraficarPoligonoNro(ByVal fila As Integer, ByRef X() As Single, ByRef Y() As
Single)
Try
Dim nlados As Integer
grafico.ResetTransform()
AnguloZ = DataGridView1.Rows(fila).Cells(1).Value
tx = DataGridView1.Rows(fila).Cells(2).Value
ty = DataGridView1.Rows(fila).Cells(3).Value
Ex = DataGridView1.Rows(fila).Cells(4).Value
Ey = DataGridView1.Rows(fila).Cells(5).Value
Radio = DataGridView1.Rows(fila).Cells(6).Value
nlados = DataGridView1.Rows(fila).Cells(7).Value
Transparencia = DataGridView1.Rows(fila).Cells(8).Value
rojo = DataGridView1.Rows(fila).Cells(9).Value
verde = DataGridView1.Rows(fila).Cells(10).Value
azul = DataGridView1.Rows(fila).Cells(11).Value
ObtenerVectoresXY(fila, X, Y, nlados)

grafico.TranslateTransform(tx, ty)
grafico.ScaleTransform(Ex, Ey)
grafico.RotateTransform(AnguloZ)
' Coordenadas()
brocha.Color = Color.FromArgb(Transparencia, rojo, verde, azul)
graficarPoligono(X, Y, nlados)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub btnGraficar_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MnuGraficarPoligono1.Click
Dim fila As Integer = 1
For fila = 0 To nf - 1
GraficarPoligonoNro(fila, X, Y)
Next
End Sub
Private Sub txtRotacion_KeyDown(ByVal sender As System.Object, ByVal e As
System.Windows.Forms.KeyEventArgs) Handles txtRotacion.KeyDown
grafico.Clear(Color.Black)
NroObjeto = Val(ComboBox1.Text)
AnguloZ = DataGridView1.Rows(NroObjeto).Cells(1).Value
Select Case e.KeyCode
Case Keys.X, Keys.Right 'X traslacion
AnguloZ = AnguloZ + prot
Case Keys.X, Keys.Right 'X traslacion
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -844-
AnguloZ = AnguloZ - prot
End Select
txtRotacion.Text = ""
DataGridView1.Rows(NroObjeto).Cells(1).Value = AnguloZ
btnGraficar_Click(sender, e)
End Sub

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


System.Windows.Forms.KeyEventArgs) Handles txtTraslacion.KeyDown
grafico.Clear(Color.Black)
NroObjeto = Val(ComboBox1.Text)
tx = DataGridView1.Rows(NroObjeto).Cells(2).Value
ty = DataGridView1.Rows(NroObjeto).Cells(3).Value
Select Case e.KeyCode
Case Keys.X, Keys.Right 'X traslacion
tx = tx + ptrasX
Case Keys.A, Keys.Left 'X traslacion
tx = tx - ptrasX
Case Keys.Y, Keys.Up 'Y traslacion
ty = ty + ptrasY
Case Keys.B, Keys.Down 'Y traslacion
ty = ty - ptrasY
End Select
txtTraslacion.Text = ""
DataGridView1.Rows(NroObjeto).Cells(2).Value = tx
DataGridView1.Rows(NroObjeto).Cells(3).Value = ty
btnGraficar_Click(sender, e)
End Sub

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


System.Windows.Forms.KeyEventArgs) Handles txtEscalado.KeyDown
grafico.Clear(Color.Black)
NroObjeto = Val(ComboBox1.Text)
Ex = DataGridView1.Rows(NroObjeto).Cells(4).Value
Ey = DataGridView1.Rows(NroObjeto).Cells(5).Value
Select Case e.KeyCode
Case Keys.X, Keys.Right 'X traslacion
Ex = Ex + pescaX
Case Keys.A, Keys.Left 'X traslacion
Ex = Ex - pescaX
Case Keys.Y, Keys.Up 'Y traslacion
Ey = Ey + pescaY
Case Keys.B, Keys.Down 'Y traslacion
Ey = Ey - pescaY
End Select
txtEscalado.Text = ""
DataGridView1.Rows(NroObjeto).Cells(4).Value = Ex
DataGridView1.Rows(NroObjeto).Cells(5).Value = Ey
btnGraficar_Click(sender, e)
End Sub
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -845-
Private Sub btnManual_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MnuManual.Click
Randomize()
grafico.Clear(Color.Black)
rfila = Int(Rnd() * nf)
rcol = Int(Rnd() * nc)
rdir = Int(Rnd() * 100)
If rdir > 50 Then
rdir = 1
Else
rdir = -1
End If
With DataGridView1.Rows(rfila).Cells(rcol)
Select Case rcol
Case 1
.Value = .Value + rdir * prot
Case 2
.Value = .Value + rdir * ptrasX
Case 3
.Value = .Value + rdir * ptrasY
Case 4
If .Value = .Value + rdir * pescaX > 1 Then
.Value = .Value + rdir * pescaX ' transparencia
End If
Case 5
If .Value = .Value + rdir * pescaY > 1 Then
.Value = .Value + rdir * pescaY ' transparencia
End If
Case 6
.Value = .Value + rdir 'mradio
Case 7
If .Value = .Value + rdir > 4 Then
.Value = .Value + rdir ' n lados
End If
Case 8, 9, 10, 11
If .Value = .Value + rdir > 1 And .Value = .Value + rdir < 254 Then
.Value = .Value + rdir ' transparencia
End If
End Select
End With
btnGraficar_Click(sender, e)
cont = cont + 1
txtCont.Text = cont
End Sub
Private Sub btnAuto_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MnuAutoamatico.Click
cont = 0
Timer1.Interval = vel
Timer1.Start()
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Timer1.Tick
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -846-
btnManual_Click(sender, e)
End Sub
Private Sub btnDetener_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MnuDetener.Click
Timer1.Stop()
End Sub
Function ObtenerPuntosMenorDistancia(ByVal X() As Single, ByVal Y() As Single,
ByVal nlados As Integer, _
ByVal x2 As Single, ByVal y2 As Single) As Integer
Dim dmenor As Single = 10000
Dim col, lugar As Integer
Dim dist1 As Single
Dim px1, py1 As Single
For col = 0 To nlados - 1
px1 = DataGridView2.Rows(NroObjeto).Cells(col * 2).Value
py1 = DataGridView2.Rows(NroObjeto).Cells(col * 2 + 1).Value
dist1 = Distancia(px1, py1, x2, y2)
If dist1 < dmenor Then
dmenor = dist1
lugar = col
End If
Next
Return lugar
End Function
Private Sub PictureBox1_MouseDown(ByVal sender As System.Object, ByVal e As
System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseDown
Dim x1, y1, x2, y2 As Single
x2 = e.X
y2 = e.Y
Dim nlados As Integer ' nro de poligono
Dim lugar As Integer
nlados = DataGridView1.Rows(NroObjeto).Cells(7).Value
ObtenerVectoresXY(NroObjeto, X, Y, nlados)
lugar = ObtenerPuntosMenorDistancia(X, Y, nlados, x2, y2)
x1 = DataGridView2.Rows(NroObjeto).Cells(lugar * 2).Value
y1 = DataGridView2.Rows(NroObjeto).Cells(lugar * 2 + 1).Value
EdicionPuntos(x1, y1, x2, y2)
DataGridView2.Rows(NroObjeto).Cells(lugar * 2).Value = x1
DataGridView2.Rows(NroObjeto).Cells(lugar * 2 + 1).Value = y1
grafico.Clear(Color.Black)
btnGraficar_Click(sender, e)
txtCont.Text = cont
cont = cont + 1
End Sub
Sub generarPoligono(ByVal Nrofila As Integer)
Dim nlados As Integer = 0
Radio = DataGridView1.Rows(Nrofila).Cells(6).Value
nlados = DataGridView1.Rows(Nrofila).Cells(7).Value
CrearPolygono(X, Y, Radio, nlados)
AdjuntarPuntosPoligono(Nrofila, X, Y, B, nlados)
End Sub
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -847-
Private Sub MenuGenerar_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MnuGenerar.Click
Dim fila As Integer
For fila = 0 To nf - 1
generarPoligono(fila)
Next
MostrarMatrizPoligonos(B, nf, Ncol1 * 2)
End Sub
Sub EdicionPuntos(ByRef x1 As Single, ByRef y1 As Single, ByVal x2 As Single,
ByVal y2 As Single)
Dim dist0, dist1, dist2, dist3, dist4 As Single
Dim dmenor As Single = 10000
dist0 = Distancia(x1, y1, x2, y2)
' el vertice se mueve al punto mas cercano de x2, y2 que puede ser clic del mouse
dist1 = Distancia(x1 + 1, y1, x2, y2)
dist2 = Distancia(x1 - 1, y1, x2, y2)
dist3 = Distancia(x1, y1 + 1, x2, y2)
dist4 = Distancia(x1, y1 - 1, x2, y2)
dmenor = dist1
If dist1 < dmenor Then
dmenor = dist1
x1 = x1 + 1
End If
If dist2 < dmenor Then
dmenor = dist2
x1 = x1 - 1
End If
If dist3 < dmenor Then
dmenor = dist3
y1 = y1 + 1
End If
If dist4 < dmenor Then
dmenor = dist4
y1 = y1 - 1
End If
End Sub
Private Sub btnManual2_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MnuEdicionManual.Click
Randomize()
Dim nlados As Integer = 0
Dim rpol As Integer ' nro de poligono
Dim rver As Integer ' nro de vertice del poligono
Dim x1, y1, x2, y2 As Single
' generar dos puntos aleatoriamente de radio al doble del radio
rpol = Int(Rnd() * nf)
nlados = DataGridView1.Rows(rpol).Cells(7).Value
rver = Int(Rnd() * nlados)
x1 = DataGridView2.Rows(rpol).Cells(rver * 2).Value
y1 = DataGridView2.Rows(rpol).Cells(rver * 2 + 1).Value
x2 = Int(Rnd() * 500)
y2 = Int(Rnd() * 500)
EdicionPuntos(x1, y1, x2, y2)
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -848-
DataGridView2.Rows(rpol).Cells(rver * 2).Value = x1
DataGridView2.Rows(rpol).Cells(rver * 2 + 1).Value = y1
grafico.Clear(Color.Black)
btnGraficar_Click(sender, e)
txtCont.Text = cont
cont = cont + 1
End Sub
Private Sub btnAuto2_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MnuEdicionAutomatica.Click
cont = 0
Timer2.Interval = 10
Timer2.Start()
End Sub
Private Sub btnDetener2_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MnuDetenerEdicion.Click
Timer2.Stop()
End Sub
Private Sub Timer2_Tick(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Timer2.Tick
btnManual2_Click(sender, e)
End Sub
Private Sub MnuGrabar_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MnuGrabar.Click
Dim fila, col As Integer
Dim archivo1 As New StreamWriter("E:\datos\cuadricula1.txt")
For fila = 0 To nf - 1
For col = 0 To nc - 1
archivo1.Write("{0}{1}", DataGridView1.Rows(fila).Cells(col).Value, vbTab)
Next
archivo1.WriteLine()
Next
archivo1.Close()
End Sub

Private Sub GrabarCuadricula2ToolStripMenuItem_Click(ByVal sender As


System.Object, ByVal e As System.EventArgs) Handles MnuGrabarCuadricula2.Click
Dim fila, col As Integer
Dim archivo1 As New StreamWriter("E:\datos\cuadricula2.txt")
For fila = 0 To nf - 1
For col = 0 To nc - 1
archivo1.Write("{0}{1}", DataGridView2.Rows(fila).Cells(col).Value, vbTab)
Next
archivo1.WriteLine()
Next
archivo1.Close()
End Sub

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


System.EventArgs) Handles MnuSalir.Click
End
End Sub
End Class
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -849-

CODIGO DEL MODULO

'**************** module 1
Imports System.IO
Module Module1
Public B(maxfilas, MaxCol) As Single
Public Nfilas1 As Integer = 15
Public Ncol1 As Integer = 8
Public rfila As Integer
Public rcol As Integer
Public rdir As Integer
Public A(maxfilas, MaxCol) As Single
Public AnguloZ As Single = 10
Public azul As Integer = 0
Public brocha As SolidBrush
Public Const MaxCol As Integer = 25
Public Const maxfilas As Integer = 10
Public cont As Integer = 0
Public tx As Single = 200
Public ty As Single = 200
Public Ex As Single = 0.1
Public Ey As Single = 0.1
Public grafico As Graphics
Public lim As Integer = 50
Public nc As Integer = 12
Public nf As Integer = 5
Public NombreArchivo As String = "E:\datos\ObjetosXY.txt"
Public NroObjeto As Integer = 0
Public pescaX As Single = 1
Public pescaY As Single = 1
Public pincel As Pen
Public prot As Single = 10
Public ptrasX As Single = 10
Public ptrasY As Single = 10
Public Transparencia As Integer = 123
Public vel As Integer = 10
Public verde As Integer = 0
Public rojo As Integer = 234
Public X(MaxCol) As Single
Public Y(MaxCol) As Single
Public Radio As Single = 20

Public Sub RecuperarDeMatriz(ByVal nombrearchivo As String, ByRef A(,) As Single,


ByRef nf As Integer, ByVal nc As Integer)
Dim srLector As StreamReader
srLector = New StreamReader(nombrearchivo)
Dim fila As Integer = 0
Dim col As Integer
Dim cadena As String = ""
Dim subcadena As String
Dim pos As Integer = 0
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -850-
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 leido satisfactoriamente")
srLector.Close()
End Sub
Sub AdjuntarPuntosPoligono(ByVal NroP As Integer, ByVal X() As Single, ByVal Y()
As Single, ByRef B(,) As Single, ByVal nlados As Integer)
For col = 0 To nlados - 1
B(NroP, col * 2) = X(col)
B(NroP, col * 2 + 1) = Y(col)
Next
End Sub
Sub CrearPolygono(ByVal X() As Single, ByVal Y() As Single, ByVal Radio As
Single, ByVal nlados As Integer)
Dim alfa, dalfa As Single
Dim cont As Integer = 0
dalfa = 2 * Math.PI / nlados
alfa = 0
cont = 0
For alfa = 0 To 2 * Math.PI Step dalfa
X(cont) = Radio * Math.Cos(alfa)
Y(cont) = Radio * Math.Sin(alfa)
cont = cont + 1
Next
X(cont) = X(0)
Y(cont) = Y(0)
End Sub
Function Distancia(ByVal x1 As Single, ByVal y1 As Single, ByVal x2 As Single,
ByVal y2 As Single) As Single
Return Math.Sqrt(Math.Pow(x2 - x1, 2) + Math.Pow(y2 - y1, 2))
End Function
Sub MostrarMatriz(ByVal A(,) As String, ByVal nf As String, ByVal nc As String)
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)
Next
Next
End Sub
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -851-
Sub main()
End Sub
End Module

10.3 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:
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -852-

Paso 1 Paso 2 Paso 3 Paso 4 Paso 5

Código en Visual Basic (Ver en la aplicación)

Triángulo de Sierpinski De Wikipedia, la enciclopedia libre

El triángulo de Sierpiński es un fractal que se puede construir a partir de cualquier


triángulo.
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -853-

(ver aplicación)

CREACION DE UNA MONTAÑA FRACTAL

Considerando los cuatros triangulos

Aleatorizando (modelizacion de terrenos )

( ver en la aplicacion)
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -854-

ARBOLES CON RECURSIVIDAD

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
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.
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -855-

Código en Visual Basic ( ver en la aplicacion)

CODIGO EN VISUAL BASIC

CODIGO DEL MODULO 1

Imports System.Drawing
Module Module1
Public Const dx As Single = 0.6
Public nro As Integer
Public ColorPen As Color = Color.FromArgb(255, 0, 0)
Public ColorBrocha As Color = Color.FromArgb(0, 255, 0)
Public ColorFondo As Color = Color.FromArgb(255, 255, 255)
Public Nombre As String
Public grosor As Integer = 1
''***********
Public ancho As Integer = 500
Public alto As Integer = 500
Public ancho1 As Integer = 400
Public alto1 As Integer = 400
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -856-
Public Cx As Integer = 0
Public Cy As Integer = 0
Public Cx1 As Integer
Public Cy1 As Integer
Public Const alfa As Single = 1.047
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
End Module

CODIGO DEL FORMULARIO

Imports System.Drawing
Public Class Form1
Private Sub GrosorDeLineaToolStripMenuItem_Click(sender As Object, e As
EventArgs) Handles GrosorDeLineaToolStripMenuItem.Click
grosor = InputBox("Ingrese grosor de linea", "Tamaño Linea", 2)
End Sub
Private Sub MnuAlfombraDeSierpinski_Click(sender As Object, e As EventArgs)
Handles MnuAlfombraDeSierpinski.Click
nro = nro + 1
Nombre = "Alfombra de Sierpiński "
FrmAlfombra.MdiParent = Me
FrmAlfombra.Text = Nombre & nro.ToString
FrmAlfombra.Show()
End Sub
Private Sub MnuTriánguloDeSierpinski_Click(sender As Object, e As EventArgs)
Handles MnuTriánguloDeSierpinski.Click
nro = nro + 1
Nombre = "Alfombra de Sierpiński "
frmTriangulo.MdiParent = Me
frmTriangulo.Text = Nombre & nro.ToString
frmTriangulo.Show()
End Sub
Private Sub MnuMontañaFractal_Click(sender As Object, e As EventArgs) Handles
MnuMontañaFractal.Click
nro = nro + 1
Nombre = "Montaña Fractal "
frmMontaña.MdiParent = Me
frmMontaña.Text = Nombre & nro.ToString
frmMontaña.Show()
End Sub

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


MnuArbolFractal.Click
nro = nro + 1
Nombre = "Arbol Fractal "
FrmArbol.MdiParent = Me
FrmArbol.Text = Nombre & nro.ToString
FrmArbol.Show()
End Sub
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -857-
Private Sub MnuCopoNieveDeKoch_Click(sender As Object, e As EventArgs)
Handles MnuCopoNieveDeKoch.Click
nro = nro + 1
Nombre = "Copo de nieve de Koch "
frmCopoNieve.MdiParent = Me
frmCopoNieve.Text = Nombre & nro.ToString
frmCopoNieve.Show()
End Sub
Private Sub ColorPencilToolStripMenuItem_Click(sender As Object, e As EventArgs)
Handles MnuColorPencil.Click
ColorDialog1.ShowDialog()
ColorPen = ColorDialog1.Color
End Sub
Private Sub ColorFondoToolStripMenuItem_Click(sender As Object, e As EventArgs)
Handles MnuColorFondo.Click
ColorDialog1.ShowDialog()
ColorFondo = ColorDialog1.Color
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ColorPen = Color.FromArgb(255, 0, 0)
ColorBrocha = Color.FromArgb(255, 255, 255)
ColorFondo = Color.FromArgb(0, 0, 0)
End Sub
Private Sub MnuColorBrocha_Click(sender As Object, e As EventArgs) Handles
MnuColorBrocha.Click
ColorDialog1.ShowDialog()
ColorBrocha = ColorDialog1.Color
End Sub
Private Sub MnPresentarVentana(sender As Object, e As EventArgs) Handles
MnCascada.Click, MnuHorizontal.Click, MnuVertical.Click, MnuOrgIconos.Click
Me.LayoutMdi(sender.TAG)
End Sub
End Class

CODIGO DEL FORMULARIO FRMALFOMBRA

Public Class FrmAlfombra


Public grafico1 As Graphics
Public pen1 As Pen
Public brocha1 As SolidBrush
Public colorPen1 As Color
Public colorbrocha1 As Color
Public ColorFondo1 As Color
Dim grosor1 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
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -858-
For col = 1 To 3
If fila = 2 And col = 2 Then
grafico1.FillRectangle(brocha1, 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 frmFractal_Paint(sender As Object, e As PaintEventArgs) Handles


MyBase.Paint
Cx = 10
Cy = 10
grafico1 = CreateGraphics()
pen1 = New Pen(colorPen1, grosor1)
brocha1 = New SolidBrush(ColorBrocha1)
grafico1.Clear(ColorFondo1)
CuadroRecursivo(Cx, Cy, ancho, alto)
End Sub

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


MyBase.Load
Me.Width = alto
Me.Height = alto
colorPen1 = ColorPen
colorbrocha1 = ColorBrocha
ColorFondo1 = ColorFondo
grosor1 = grosor1
End Sub
End Class

CODIGO DEL FORMULARIO FRMTRIANGULO

Public Class frmTriangulo


Dim grafico2 As Graphics
Dim pen2 As Pen
Dim brocha2 As SolidBrush
Dim colorPen2 As Color
Dim colorbrocha2 As Color
Dim ColorFondo2 As Color
Dim grosor2 As Integer
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -859-
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
grafico2.DrawLine(pen2, px1, py1, px2, py2)
grafico2.DrawLine(pen2, px2, py2, px3, py3)
grafico2.DrawLine(pen2, 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(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 frmTriangulo_Paint(sender As Object, e As PaintEventArgs) Handles


Me.Paint
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
grafico2 = CreateGraphics()
pen2 = New Pen(colorPen2, grosor2)
brocha2 = New SolidBrush(colorbrocha2)
grafico2.Clear(ColorFondo2)
triangulo(Px1, py1, px2, py2, px3, py3)
End Sub
Private Sub frmTriangulo_Load(sender As Object, e As EventArgs) Handles
MyBase.Load
Me.Width = ancho
Me.Height = alto
colorPen2 = ColorPen
colorbrocha2 = ColorBrocha
ColorFondo2 = ColorFondo
grosor2 = grosor
End Sub
End Class

CODIGO DEL FORMULARIO MONTAÑA FRACTAL

Public Class frmMontaña


Dim grafico3 As Graphics
Dim pen3 As Pen
Dim brocha3 As SolidBrush
Dim colorPen3 As Color
Dim colorbrocha3 As Color
Dim ColorFondo3 As Color
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -860-
Dim grosor3 As Integer
Sub trianguloM(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 valor As Integer = 10
Dim px12 As Single, py12 As Single, px13 As Single, py13 As Single
Dim px23 As Single, py23 As Single
grafico3.DrawLine(pen3, px1, py1, px2, py2)
grafico3.DrawLine(pen3, px2, py2, px3, py3)
grafico3.DrawLine(pen3, px3, py3, px1, py1)
If (distancia(px1, py1, px2, py2) > 50) Then
' triangulo del punto1
pen3.Color = ColorFondo3
grafico3.DrawLine(pen3, px1, py1, px2, py2)
grafico3.DrawLine(pen3, px2, py2, px3, py3)
grafico3.DrawLine(pen3, px3, py3, px1, py1)
pen3.Color = colorPen3
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))
trianguloM(px12, py12, px23, py23, px13, py13)
trianguloM(px1, py1, px12, py12, px13, py13)
trianguloM(px2, py2, px12, py12, px23, py23)
trianguloM(px3, py3, px13, py13, px23, py23)
End If
End Sub

Private Sub frmMontaña_Paint(sender As Object, e As PaintEventArgs) Handles


Me.Paint
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
grafico3 = CreateGraphics()
pen3 = New Pen(colorPen3, grosor3)
'brocha3 = New SolidBrush(ColorBrocha3)
grafico3.Clear(ColorFondo)
Randomize()
trianguloM(Px1, py1, px2, py2, px3, py3)
End Sub

Private Sub frmMontaña_Load(sender As Object, e As EventArgs) Handles


MyBase.Load
Me.Width = alto
Me.Height = alto
colorPen3 = ColorPen
colorbrocha3 = ColorBrocha
ColorFondo3 = ColorFondo
grosor3 = grosor
End Sub
End Class
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -861-

CODIGO DEL FORMULARIO FRMARBOL

Public Class FrmArbol


Dim grafico4 As Graphics
Dim pen4 As Pen
Dim brocha4 As SolidBrush
Dim colorPen4 As Color
Dim colorbrocha4 As Color
Dim ColorFondo4 As Color
Dim grosor4 As Integer

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
pen4.Width = valor
x1 = x + t * Math.Cos(teta)
y1 = y + t * Math.Sin(teta)
grafico4.DrawLine(pen4, 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 FrmArbol_Paint(sender As Object, e As PaintEventArgs) Handles
Me.Paint
grafico4 = CreateGraphics()
pen4 = New Pen(ColorPen)
brocha4 = New SolidBrush(ColorBrocha)
grafico4.Clear(ColorFondo)
Arbol(150, 300, 120, 3 * Math.PI / 2.0, 0.5, 5)
Arbol(350, 300, 100, 3 * Math.PI / 2.0, 0.4, 4)
Arbol(420, 300, 50, 3 * Math.PI / 2.0, 0.3, 3)
End Sub

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


MyBase.Load
Me.Width = alto
Me.Height = alto
colorPen4 = ColorPen
colorbrocha4 = ColorBrocha
ColorFondo4 = ColorFondo
grosor4 = grosor
End Sub
End Class

CODIGO DEL FORMULARIO COPODE NIEVE


Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -862-

Public Class frmCopoNieve


Dim grafico5 As Graphics
Dim pen5 As Pen
Dim brocha5 As SolidBrush
Dim colorPen5 As Color
Dim colorbrocha5 As Color
Dim ColorFondo5 As Color
Dim grosor5 As Integer

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
pen5.Color = colorPen5
grafico5.DrawLine(pen5, 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
grafico5.DrawLine(pen5, x1, y1, x2, y2)
grafico5.DrawLine(pen5, x2, y2, x3, y3)
pen5.Color = ColorFondo5
grafico5.DrawLine(pen5, x1, y1, x3, y3)
' System.Threading.Thread.Sleep(vel) ' 1 segundo
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 frmCopoNievePaint(sender As Object, e As EventArgs) Handles


MyBase.Paint
Cx = ancho / 2
Cy = alto / 2
grafico5 = CreateGraphics()
pen5 = New Pen(ColorPen, grosor5)
brocha5 = New SolidBrush(colorbrocha5)
grafico5.Clear(ColorFondo5)
grafico5.DrawLine(pen5, Cx, 0, Cx, alto)
grafico5.DrawLine(pen5, 0, Cy, ancho, Cy)
Dim Px1 As Integer = 200, py1 As Integer = 0, px2 As Integer = 200, py2 As
Integer = 0
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -863-
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
grafico5.DrawLine(pen5, Cx + Px1, Cy + py1, Cx + px2, Cy + py2)
grafico5.DrawLine(pen5, Cx + px2, Cy + py2, Cx + Px3, Cy + py3)
grafico5.DrawLine(pen5, 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 frmCopoNieve_Load_1(sender As Object, e As EventArgs) Handles


MyBase.Load
Me.Width = alto
Me.Height = alto
colorPen5 = ColorPen
colorbrocha5 = ColorBrocha
ColorFondo5 = ColorFondo
grosor5 = grosor
End Sub
End Class

FRACTALES DE MALDEBROT

Module 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
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -864-
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
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 Function
End Module
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -865-
CODIGO DE FORMULARIO

Option Explicit On
Option Strict On
Imports System.Drawing
Imports System.Drawing.Drawing2D
Public 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
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
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -866-
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
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"
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -867-
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
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 Sub
End Class

10.4 MONTAÑA FRACTAL

Imports System.IO
Module Module1
Public Structure Puntos
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -868-
Public nro As Integer
Public X As Single
Public Y As Single
Public Z As Single
Public Rela As Integer
End Structure
Public modelo As Integer = 0
Public AnguloX As Integer = 0
Public AnguloY As Integer = 0
Public AnguloZ As Integer = 0
Public Const limite As Integer = 100
Public vel As Integer = 10
Public Const maximo As Integer = 7000
Public P(maximo) As Puntos
Public P1(maximo) As Puntos
Public Grafico As Graphics
Public ColorFondo As Color = Color.FromArgb(255, 255, 255)
Public pincel As Pen
Public Brocha As SolidBrush
Public valor As Single = 100 ' mas alto la monta
Public factor As Single = 0.5 ' 0.5 ' se relaciona con el valor factor proyeccion
Public ancho As Integer = 700
Public alto As Integer = 500
Public Ndivisiones As Integer = 5
Public ContPuntos As Integer
Public MiFuente As New Font("Verdana", 24, FontStyle.Bold)
Public Tx As Single = 0
Public Ty As Single = 0
Public tz As Single = 0
Public Ex As Single = 1
Public Ey As Single = 1
Public Ez As Single = 1
Public VEx As Single = 0.1
Public VEy As Single = 0.1
Public VEz As Single = 0.1
Public CARAS(maximo, 4) As Integer
Public Normales(maximo, 4) As Single
Public D As Single = 1000
Public contcaras As Integer
Public ver1 As Integer, ver2 As Integer, ver3 As Integer, ver4 As Integer
Public Modo As Integer = 0
Public NombreArchivoPuntos = "E:\datos\puntos4x28.txt"
Public NombreArchivoCaras = "E:\datos\caras4x28.txt"
Sub RotacionXYZ(P() As Puntos, ByVal AnguloX As Single, ByVal AnguloY As
Single, ByVal anguloZ As Single, np As Integer)
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 arx = AnguloX * Math.PI / 180
For fila = 0 To np - 1
x1 = P(fila).X
y1 = P(fila).Y
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -869-
z1 = P(fila).Z
x2 = x1
y2 = CSng(y1 * Math.Cos(arx) - z1 * Math.Sin(arx))
z2 = CSng(y1 * Math.Sin(arx) + z1 * Math.Cos(arx))
P(fila).X = x2
P(fila).Y = y2
P(fila).Z = z2
Next
Dim ary = AnguloY * Math.PI / 180
For fila = 0 To np - 1
x1 = P(fila).X
y1 = P(fila).Y
z1 = P(fila).Z
x2 = CSng(x1 * Math.Cos(ary) - z1 * Math.Sin(ary))
y2 = y1
z2 = CSng(-x1 * Math.Sin(ary) + z1 * Math.Cos(ary))
P(fila).X = x2
P(fila).Y = y2
P(fila).Z = z2
Next
REM rotacion Z
Dim arz = anguloZ * Math.PI / 180
For fila = 0 To np - 1
x1 = P(fila).X
y1 = P(fila).Y
z1 = P(fila).Z
x2 = CSng(x1 * Math.Cos(arz) - y1 * Math.Sin(arz))
y2 = CSng(x1 * Math.Sin(arz) + y1 * Math.Cos(arz))
z2 = z1
P(fila).X = x2
P(fila).Y = y2
P(fila).Z = z2
Next
End Sub
Sub TraslacionXYZ(P() As Puntos, ByVal tx As Single, ByVal ty As Single, ByVal tz
As Single, nf As Integer)
Dim fila As Integer
For fila = 0 To nf - 1
P(fila).X = P(fila).X + tx
P(fila).Y = P(fila).Y + ty
P(fila).Z = P(fila).Z + tz
Next
End Sub
Sub EscaladoXYZ(P() As Puntos, ByVal tx As Single, ByVal ty As Single, ByVal tz As
Single, nf As Integer)
Dim fila As Integer
For fila = 0 To nf - 1
P(fila).X = P(fila).X * ex
P(fila).Y = P(fila).Y * ey
P(fila).Z = P(fila).Z * ez
Next
End Sub
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -870-
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 Sub
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
Form1.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)
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
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -871-
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
Form1.ListBox1.Items.Add("normal" & Normales(fila, 2))
Next
End Sub
Sub RecuperarPuntos(ByVal nombrearchivo As String, P() As Puntos, ByRef 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 4
pos = InStr(inicio, cadena, Chr(9))
subcadena = Mid(cadena, inicio, pos - inicio)
Select Case col
Case 0 : P(fila).nro = CInt(subcadena)
Case 1 : P(fila).X = CSng(subcadena)
Case 2 : P(fila).Y = CSng(subcadena)
Case 3 : P(fila).Z = CSng(subcadena)
Case 4 : P(fila).Rela = CInt(subcadena)
P(fila).nro = subcadena
End Select
inicio = pos + 1
Next
fila = fila + 1
cadena = srLector.ReadLine()
Loop
nf = fila - 1
Console.WriteLine("Archivo {0} leido satisfactoriamente", nombrearchivo)
srLector.Close()
End Sub

Sub RecuperarCaras(ByVal nombrearchivo As String, P(,) As Integer, ByRef 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
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -872-
cadena = srLector.ReadLine()
Do While Not (cadena Is Nothing)
cadena = cadena & Chr(9)
inicio = 1
For col = 0 To 3
pos = InStr(inicio, cadena, Chr(9))
subcadena = Mid(cadena, inicio, pos - inicio)
Select Case col
Case 0 : CARAS(fila, 0) = CInt(subcadena)
Case 1 : CARAS(fila, 1) = CInt(subcadena)
Case 2 : CARAS(fila, 2) = CInt(subcadena)
Case 3 : CARAS(fila, 3) = CInt(subcadena)
End Select
inicio = pos + 1
Next
fila = fila + 1
cadena = srLector.ReadLine()
Loop
nf = fila - 1
Console.WriteLine("Archivo {0} leido satisfactoriamente", nombrearchivo)
srLector.Close()
End Sub
End Module

CODIGO DEL FORMULARIO

Option Explicit On
Imports System.IO
Imports System.Drawing
Imports System.Drawing.Drawing2D
Public Class Form1
Sub Iniciar()
DataGridView1.ColumnCount = 6
DataGridView1.RowCount = 5
Dim fila As Integer
For fila = 1 To 5
DataGridView1.Columns(fila).Width = 50
Next
For fila = 0 To DataGridView1.RowCount - 1
DataGridView1.Rows(fila).HeaderCell.Value = fila.ToString
Next
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
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -873-
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 modelo Nro Divisiones"


DataGridView1.Rows(3).Cells(1).Value = "Unidades"
DataGridView1.Rows(3).Cells(2).Value = Modo
DataGridView1.Rows(3).Cells(3).Value = vel
DataGridView1.Rows(3).Cells(4).Value = modelo
DataGridView1.Rows(3).Cells(5).Value = Ndivisiones

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
P(ContPuntos).Z = zmed
P(ContPuntos).Rela = puntocentral
vmedio = puntocentral
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -874-
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
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)
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -875-
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
Select Case Modo
Case 0
Grafico.DrawPolygon(pincel, Figura)
Case 1
color1 = Normales(fila, 2) * 255
Select Case modelo
Case 0 ' gris
Brocha.Color = Color.FromArgb(color1, color1, color1)
Case 1 ' rojo
Brocha.Color = Color.FromArgb(color1, 0, 0)
Case 2 ' verde
Brocha.Color = Color.FromArgb(0, color1, 0)
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -876-
Case 3 ' azul
Brocha.Color = Color.FromArgb(0, 0, color1)
Case 4 ' rojo-verde
Brocha.Color = Color.FromArgb(255 - color1, color1, 0)
Case 5 ' verde-rojo
Brocha.Color = Color.FromArgb(color1, 255 - color1, 0)
Case 6 ' amarillo -azul
Brocha.Color = Color.FromArgb(color1, color1, 255 - color1)
Case 7 ' amarillo -azul
Brocha.Color = Color.FromArgb(255 - color1, 255 - color1, 255 - color1)
End Select
Grafico.FillPolygon(Brocha, Figura, FillMode.Alternate)
Case 2
color1 = Normales(fila, 2) * 255
Select Case modelo
Case 0 ' gris
Brocha.Color = Color.FromArgb(color1, color1, color1)
Case 1 ' rojo
Brocha.Color = Color.FromArgb(color1, 0, 0)
Case 2 ' verde
Brocha.Color = Color.FromArgb(0, color1, 0)
Case 3 ' azul
Brocha.Color = Color.FromArgb(0, 0, color1)
Case 4 ' rojo-verde
Brocha.Color = Color.FromArgb(255 - color1, color1, 0)
Case 5 ' verde-rojo
Brocha.Color = Color.FromArgb(color1, 255 - color1, 0)
Case 6 ' amarillo -azul
Brocha.Color = Color.FromArgb(color1, color1, 255 - color1)
Case 7 ' amarillo -azul
Brocha.Color = Color.FromArgb(255 - color1, 255 - color1, 255 - color1)
End Select
Grafico.FillPolygon(Brocha, Figura, FillMode.Alternate)
Grafico.DrawPolygon(pincel, Figura)
End Select
End If
' Grafico.DrawLine(pincel, px1, py1, px2, py2)
Next
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
Dim col As Integer
PictureBox1.Width = ancho + 10
PictureBox1.Height = alto + 10
PictureBox1.BackColor = ColorFondo
Grafico = PictureBox1.CreateGraphics
MiFuente = New Font("arial", 11, FontStyle.Bold)
Brocha = New SolidBrush(Color.Red)
pincel = New Pen(Color.Blue, 1)
Iniciar()
DataGridView2.ColumnCount = 5
DataGridView2.RowCount = 1
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -877-
For col = 0 To 4
DataGridView2.Columns(col).Width = 60
Next
End Sub
Private Sub MnuMontaña_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnMontaña.Click
Dim i, j As Integer
Grafico.Clear(Color.Black)
Randomize()
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
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)
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
pincel.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}{7}{8}", P(i).nro, Chr(9), P(i).X, Chr(9),
P(i).Y, Chr(9), P(i).Z, Chr(9), P(i).Rela)
Next
swEscritor.Close()
swEscritor = New StreamWriter("E:\DATOS\CARAS.txt")
For i = 0 To contcaras
For j = 0 To 3
swEscritor.Write("{0} {1}", CARAS(i, j), Chr(9))
Next
swEscritor.WriteLine()
Next
swEscritor.Close()
CopiarVector(P, P1, ContPuntos)
ObtenerNormales()
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -878-
graficarCara(contcaras)
End Sub
Private Sub MnGraficar_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnMontaña.Click
graficarCara(contcaras)
End Sub

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


BtnIniciarTodo.Click
Grafico.Clear(Color.Black)
AnguloX = DataGridView1.Rows(0).Cells(2).Value
AnguloY = DataGridView1.Rows(0).Cells(3).Value
AnguloZ = DataGridView1.Rows(0).Cells(4).Value

Tx = DataGridView1.Rows(1).Cells(2).Value
Ty = DataGridView1.Rows(1).Cells(3).Value
tz = DataGridView1.Rows(1).Cells(4).Value
D = DataGridView1.Rows(1).Cells(5).Value

Ex = DataGridView1.Rows(2).Cells(2).Value
Ey = DataGridView1.Rows(2).Cells(3).Value
Ez = DataGridView1.Rows(2).Cells(4).Value
Modo = DataGridView1.Rows(3).Cells(2).Value
vel = DataGridView1.Rows(3).Cells(3).Value
modelo = DataGridView1.Rows(3).Cells(4).Value
Ndivisiones = DataGridView1.Rows(3).Cells(5).Value

CopiarVector(P, P1, ContPuntos)


RotacionXYZ(P1, AnguloX, AnguloY, AnguloZ, ContPuntos)
TraslacionXYZ(P1, Tx, Ty, tz, ContPuntos)
EscaladoXYZ(P1, Ex, Ey, Ez, ContPuntos)
graficarCara(contcaras)
End Sub

Sub MostrarPuntos(np As Integer)


Dim fila As Integer
For fila = 0 To np - 1
DataGridView2.Rows(fila).Cells(0).Value = P(fila).nro
DataGridView2.Rows(fila).Cells(1).Value = P(fila).X
DataGridView2.Rows(fila).Cells(2).Value = P(fila).Y
DataGridView2.Rows(fila).Cells(3).Value = P(fila).Z
DataGridView2.Rows(fila).Cells(4).Value = P(fila).Rela
Next
End Sub

Private Sub MostrarCaras(np As Integer)


Dim fila As Integer
For fila = 0 To np - 1
DataGridView2.Rows(fila).Cells(0).Value = CARAS(fila, 0)
DataGridView2.Rows(fila).Cells(1).Value = CARAS(fila, 1)
DataGridView2.Rows(fila).Cells(2).Value = CARAS(fila, 2)
DataGridView2.Rows(fila).Cells(3).Value = CARAS(fila, 3)
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -879-
Next
End Sub
Sub btnAbrir_Click(sender As Object, e As EventArgs) Handles btnAbrir.Click
RecuperarPuntos(NombreArchivoPuntos, P, ContPuntos)
' DataGridView2.ColumnCount = 5
' DataGridView2.RowCount = ContPuntos
' MostrarPuntos(ContPuntos) ' muestra los datos en el datagrid view
RecuperarCaras(NombreArchivoCaras, CARAS, contcaras)
DataGridView2.ColumnCount = 5
DataGridView2.RowCount = contcaras
MostrarCaras(contcaras) ' muestra los datos en el datagrid view
Grafico.Clear(Color.Black)
ListBox1.Items.Clear()
ListBox1.Items.Add("CANTIDAD DE Caras " & contcaras)
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
CopiarVector(P, P1, ContPuntos)
ObtenerNormales()
graficarCara(contcaras)
End Sub

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


btnBorrar.Click
Grafico.Clear(Color.Black)
End Sub
Private Sub BtnGraficar_Click(sender As Object, e As EventArgs) Handles
BtnGraficar.Click
graficarCara(contcaras)
End Sub

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


txtRotacion.KeyDown
Select Case e.KeyCode
Case 65 ' A rotacion inverso de X
If AnguloX >= -3600 Then
AnguloX = AnguloX - 1
Else
AnguloX = 3600
End If
Case 66 ' B Inverso De Y
If AnguloY >= -3600 Then
AnguloY = AnguloY - 1
Else
AnguloY = 3600
End If

Case 67 ' C ROTACION Inverso de C


If AnguloZ >= -36000 Then
AnguloZ = AnguloZ - 1
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -880-
Else
AnguloZ = 3600
End If
Case 88 ' ROTACION EJE X
If AnguloX <= 3600 Then
AnguloX = AnguloX + 1
Else
AnguloX = 0
End If

Case 89 ' ROTACION EJE Y


If AnguloY <= 3600 Then
AnguloY = AnguloY + 1
Else
AnguloY = 0
End If
Case 90 ' ROTACION EJE Z
If AnguloZ <= 3600 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(sender As Object, e As KeyEventArgs) Handles


txtTraslacion.KeyDown
Select Case e.KeyCode
Case 65 ' A inverso de X
If Tx >= -limite Then
Tx = Tx - 1
Else
Tx = limite
End If
Case 66 ' B Inverso De Y
If Ty >= -limite Then
Ty = Ty - 1
Else
Ty = limite
End If

Case 67 ' C traslacion Inverso de C


If tz >= -limite Then
tz = tz - 1
Else
tz = limite
End If
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -881-

Case 88 ' ROTACION EJE X


If Tx <= limite Then
Tx = Tx + 1
Else
Tx = -limite
End If
Case 89 ' TRASLACION TROTACION EJE Y
If Ty <= limite Then
Ty = Ty + 1
Else
Ty = -limite
End If
Case 90 ' ROTACION EJE Z
If tz <= limite Then
tz = tz + 1
Else
tz = -limite
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
'*************
txtTraslacion.Text = ""
BtnIniciarTodo_Click(sender, e)
End Sub

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


txtescalado.KeyDown
Select Case e.KeyCode
Case 65 ' A inverso de X
If Ex >= -limite Then
Ex = Ex - VEx
Else
Ex = limite
End If
Case 66 ' B Inverso De Y
If Ey >= -limite Then
Ey = Ey - VEy
Else
Ey = limite
End If

Case 67 ' C traslacion Inverso de C


If Ez >= -limite Then
Ez = Ez - VEz
Else
Ez = limite
End If
Case 88 ' ESCALADO EJE X
If Ex <= limite Then
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -882-
Ex = Ex + VEx
Else
Ex = -limite
End If

Case 89 ' ROTACION EJE Y


If Ey <= limite Then
Ey = Ey + VEy
Else
Ey = -limite
End If
Case 90 ' escalado eJE Z
If Ez <= limite Then
Ez = Ez + VEz
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
txtescalado.Text = ""
BtnIniciarTodo_Click(sender, e)
End Sub

Private Sub btnAuto_Click(sender As Object, e As EventArgs) Handles btnAuto.Click


vel = DataGridView1.Rows(3).Cells(3).Value
Timer1.Start()
End Sub
Private Sub BtnDetener_Click(sender As Object, e As EventArgs) Handles
BtnDetener.Click
Timer1.Stop()
End Sub

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick


If AnguloX <= 360 Then
AnguloX = AnguloX + 1
Else
If AnguloY <= 360 Then
AnguloY = AnguloX + 1
Else
If AnguloZ <= 360 Then
AnguloZ = AnguloZ + 1
Else
AnguloX = 0
End If
End If
End If
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)
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -883-
End Sub
End Class

10.5 SIMULACION DE POLITICAS DE INVENTARIOS DE CONTROL DE


INVENTARIOS

x P(x) acum L 2
1 5,00 5 Q 10
2 20,00 25 C1 0,1
3 40,00 65 C3 5
4 25,00 90 Z 10
5 10,00 100 z 4
SUMA 100

CODIGO DEL FORMULARIO

Imports System.Drawing
Public 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)
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -884-
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"
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)
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -885-
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
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 Sub
End Class

CODIGO DEL MODULO 1

Imports System.IO
Module 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
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -886-
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
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
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -887-
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
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
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -888-
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 Sub
End Module

10.7 APLICACIÓN DE TRADUCTOR DE ARCHIVOS

Imports System.IO
Module Module1
Public srLector As StreamReader
Public A(10) As String
Public B(10) As String
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -889-
End Module
Imports System.IO
Public 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 = ""
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))
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -890-
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
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 Sub
End Class

10.8 BUSCADOR MODO FORMUALRIOS

Se tiene el siguiente diseño (puede usted variar los diseños )en excel encontrar los
puntos deseados si no los encuentra que la computadora muestre un mensaje de que
no se encontro, si la encuentra muestra en que fila y columna se encontro la meta y
cuantos movimiento hizo, y ademas la trayectoria recorrida
Buscador en modo consola grabe la matri con el nombre de 40x20
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -891-
Buscador en modo formulario

8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8
8 8 8 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 8 8
8 8 8 0 0 0 0 0 0 8 8 8 8 8 8 8 0 8 0 8 8 8 8 8 0 0 8 8 0 0 0 0 8 8 8 8 8 0 8 8
8 0 0 0 0 0 0 0 0 8 0 0 0 0 8 8 0 8 0 0 8 8 8 0 0 0 8 8 0 0 0 0 0 0 8 0 8 0 8 8
8 8 8 0 0 0 0 0 0 8 0 8 8 8 8 8 0 8 8 0 8 8 8 0 8 0 8 8 0 0 8 8 8 0 8 0 8 0 8 8
8 8 8 0 8 8 0 8 0 8 0 0 0 0 0 0 0 0 0 0 0 0 0 0 8 0 8 8 0 0 8 0 8 0 8 0 8 0 8 8
8 8 8 0 0 0 0 0 0 8 8 8 8 8 8 8 8 8 8 8 8 8 0 8 8 0 8 8 0 0 8 0 8 0 0 0 8 0 8 8
8 8 8 0 8 8 0 8 0 8 8 8 8 8 8 8 8 8 8 8 8 8 0 8 8 0 8 8 0 8 8 0 8 8 8 8 8 0 8 8
8 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 8 8
8 8 8 0 8 8 8 8 0 8 8 8 8 8 8 8 0 8 8 8 8 8 8 8 8 0 8 8 8 8 8 8 8 8 8 8 8 0 8 8
8 8 8 0 8 8 8 8 0 8 8 8 8 8 8 8 0 8 8 8 8 8 8 8 8 0 8 8 8 8 8 8 8 8 8 8 8 0 8 8
8 8 8 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 8 8
8 8 8 0 8 8 8 8 0 8 8 8 0 8 8 8 0 8 8 8 8 8 8 8 8 0 8 8 8 8 0 8 8 8 8 8 8 0 8 8
8 8 8 0 8 8 8 8 0 8 8 8 0 8 8 8 0 8 0 0 0 0 0 0 8 0 8 0 0 0 0 0 0 0 8 0 0 0 0 8
8 8 8 0 8 8 8 8 0 8 8 8 0 8 8 8 0 8 0 8 8 8 8 0 8 0 8 8 8 8 8 8 8 8 8 0 8 8 0 8
8 8 8 0 8 8 8 8 0 0 0 0 0 0 0 0 0 8 0 8 8 0 8 0 8 0 0 0 0 0 0 0 0 0 0 0 8 8 0 8
8 8 8 0 8 8 8 8 0 0 0 0 0 0 0 0 0 8 0 0 0 0 8 0 8 0 0 0 0 0 0 8 8 0 0 0 0 0 0 8
8 8 8 0 0 0 0 0 0 0 8 8 8 8 8 8 0 8 8 8 8 8 8 0 8 8 8 8 8 8 0 8 8 0 8 8 8 8 8 8
8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 0 0 0 0 0 0 0 0 8 8 8 8 8 8 0 0 0 0 8 8 8 8 8 8
8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8

CODIGO DEL FORMULARIO

Imports System.Drawing
Public Class Form1
Dim resultado, fila, col As Integer
Sub MostrarMatrizFormulario(A(,) As Integer, nf As Integer, nc As Integer)
Dim fila, col As Integer
Dim Cadena As String
For fila = 0 To nf - 1
Cadena = ""
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -892-
For col = 0 To nc - 1
Cadena = Cadena & Str(A(fila, col) & vbTab)
Next
ListBox1.Items.Add(Cadena)
Next
End Sub
Sub Iniciar()
DataGridView1.ColumnCount = 3
DataGridView1.RowCount = 4
DataGridView1.Columns(0).Width = 60
DataGridView1.Columns(1).Width = 34
DataGridView1.Columns(2).Width = 34
DataGridView1.Columns(0).HeaderText = "Propiedad"
DataGridView1.Columns(1).HeaderText = "X"
DataGridView1.Columns(2).HeaderText = "Y"
DataGridView1.Rows(0).Cells(0).Value = "PosBuscador"
DataGridView1.Rows(0).Cells(1).Value = xbusca
DataGridView1.Rows(0).Cells(2).Value = ybusca
DataGridView1.Rows(1).Cells(0).Value = "PosMeta"
DataGridView1.Rows(1).Cells(1).Value = xmeta
DataGridView1.Rows(1).Cells(2).Value = ymeta
DataGridView1.Rows(2).Cells(0).Value = "Escalas"
DataGridView1.Rows(2).Cells(1).Value = Ex
DataGridView1.Rows(2).Cells(2).Value = Ey
DataGridView1.Rows(3).Cells(0).Value = "velocidad"
DataGridView1.Rows(3).Cells(1).Value = vel
End Sub

Sub VerMatrizFormulario(ByVal A(,) As Integer, ByVal nf As Integer, ByVal nc As


Integer, ByVal cx As Integer, ByVal cy As Integer)
Dim fila, col As Integer
For fila = 0 To nf - 1
For col = 0 To nc - 1
Select Case A(fila, col)
Case 0 : brocha.Color = Drawing.Color.Black
Case 1 : brocha.Color = Drawing.Color.Blue
Case 2 : brocha.Color = Drawing.Color.Aqua
Case 3 : brocha.Color = Drawing.Color.Cyan
Case 4 : brocha.Color = Drawing.Color.Red
Case 5 : brocha.Color = Drawing.Color.Violet
Case 6 : brocha.Color = Drawing.Color.Yellow
Case 7 : brocha.Color = Drawing.Color.Orange
Case 8 : brocha.Color = Drawing.Color.Gray
Case 9 : brocha.Color = Drawing.Color.Lime
End Select
grafico.FillRectangle(brocha, cx + col * Ex, cy + fila * Ey, Ex, Ey)
grafico.DrawRectangle(pluma, cx + col * Ex, cy + fila * Ey, Ex, Ey)
Next
Next
End Sub

Private Sub btnAbrir_Click(sender As Object, e As EventArgs) Handles btnAbrir.Click


Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -893-
RecuperarMatriz(NombreArchivo, Matriz, nfilas, ncol)
CopiarMatriz(Matriz, MatrizW, nfilas, ncol)
px1 = xbusca
py1 = ybusca
px2 = xmeta
py2 = ymeta
'IniciarDistancias(MatrizW, VX1, VY1, VX2, VY2, px1, py1, px2, py2, meta)
VerMatrizFormulario(MatrizW, nfilas, ncol, cx, cy)
End Sub

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load


grafico = PictureBox1.CreateGraphics
pluma = New Pen(Brushes.Red, 2)
brocha = New SolidBrush(Drawing.Color.Green)
txtNroNodos.Text = nfilas
txtNodoInicial.Text = nodoi
txtNodoFinal.Text = nodof
Iniciar()
End Sub
Sub IniciarProceso(meta As Integer)
Cont = 0
ContMov = 0
Iniciar()
CopiarMatriz(Matriz, MatrizW, nfilas, ncol)
px1 = xbusca
py1 = ybusca
px2 = xmeta
py2 = ymeta
IniciarDistancias(MatrizW, VX1, VY1, VX2, VY2, px1, py1, px2, py2, meta)
VerMatrizFormulario(MatrizW, nfilas, ncol, cx, cy)
End Sub

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


btnIniciar.Click
IniciarProceso(meta)
End Sub

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


btnObtener.Click
xbusca = DataGridView1.Rows(0).Cells(1).Value
ybusca = DataGridView1.Rows(0).Cells(2).Value
xmeta = DataGridView1.Rows(1).Cells(1).Value
ymeta = DataGridView1.Rows(1).Cells(2).Value
Ex = DataGridView1.Rows(2).Cells(1).Value
Ey = DataGridView1.Rows(2).Cells(2).Value
vel = DataGridView1.Rows(3).Cells(1).Value
MatrizW(ymeta, xmeta) = meta
MatrizW(ybusca, xbusca) = busca1
VX1(0) = xbusca
VY1(0) = ybusca
VerMatrizFormulario(MatrizW, nfilas, ncol, cx, cy)
End Sub
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -894-

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


btnMostrar.Click
VerMatrizFormulario(MatrizW, nfilas, ncol, cx, cy)
End Sub

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


btnBorrar.Click
grafico.Clear(Drawing.Color.Black)
End Sub

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


btnBuscar.Click
resultado = bUSCAR(MatrizW, VX1, VY1, VX2, VY2, px1, py1, Cont, ContMov)
VerMatrizFormulario(MatrizW, nfilas, ncol, cx, cy)
If resultado >= 0 Then
ne1 = Cont + 1
DejarCamino(MatrizW, VX1, VY1, ne1, busca1)
px1 = VX1(ne1 - 1)
py1 = VY1(ne1 - 1)
ListBox1.Items.Add("meta encontrada X=" & px1 & " Y = " & py1 & "Cont " & ne1
& "Mov = " & ContMov)
Else
ListBox1.Items.Add("meta nO encontrada Mov = " & ContMov)
End If
PonerPuntoFormulario(xbusca, ybusca, Ex, Ey, busca2)
End Sub

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


btnMinimo.Click
Dim fila, col As Integer
Dim menor1, Dir As Integer
Dir = 1
RecuperarMatriz(NombreArchivo, Matriz, nfilas, ncol)
' encuentra la meta
CopiarMatriz(Matriz, MatrizW, nfilas, ncol)
px1 = xbusca
py1 = ybusca
px2 = xmeta
py2 = ymeta
MostrarMatrizFormulario(MatrizW, nfilas, ncol)
IniciarDistancias(MatrizW, VX1, VY1, VX2, VY2, px1, py1, px2, py2, meta)
resultado = bUSCAR(MatrizW, VX1, VY1, VX2, VY2, px1, py1, Cont, ContMov)
If resultado >= 0 Then
ne1 = Cont
DejarCamino(MatrizW, VX1, VY1, ne1, busca1)
px1 = VX1(ne1)
py1 = VY1(ne1)
ListBox1.Items.Add("meta encontrada X=" & px1 & " Y = " & py1 & "Cont " & ne1
& "Mov = " & ContMov)
Else
ListBox1.Items.Add("meta nO encontrada Mov = " & ContMov)
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -895-
End If
bUSCARCruces(MatrizW, VX1, VY1, VA1, VL2, ne1, ne2, busca1, Camino)
'insertar el primer elemento
For col = ne2 To 1 Step -1
VL2(col) = VL2(col - 1)
Next
VL2(0) = 0
VL2(ne2 + 1) = ne1
ne2 = ne2 + 2
' ENCONTRAR DISTANCIAS
For fila = 0 To ne2 - 1
For col = 0 To ne2 - 1
px1 = VX1(VL2(fila))
py1 = VY1(VL2(fila))
px2 = VX1(VL2(col))
py2 = VY1(VL2(col))
menor1 = DistanciaMenorPuntos(px1, py1, px2, py2, VXMenor, VYMenor,
meta)
MatrizD(fila, col) = menor1
MatrizDIR(fila, col) = Dir
'Console.WriteLine("fila {0} col {1} distmenor {2} dir {3} ", fila, col, menor1, Dir)
Next
Next
ListBox1.Items.Add("MATRIZ DISTANCIA")
MostrarMatrizFormulario(MatrizD, ne2, ne2)
ListBox1.Items.Add("MATRIZ DIRECCION")
MostrarMatrizFormulario(MatrizDIR, ne2, ne2)
' GrabarMatriz(NombreArchivoMatriz, MatrizD, ne3, ne3)
ListBox1.Items.Add("ANTES DE FLOYD")
MostrarMatrizFormulario(MatrizD, ne2, ne2)
ListBox1.Items.Add("MATRIZ S")
ObtenerS(S, ne2, ne2)
MostrarMatrizFormulario(S, ne2, ne2)
floyd(MatrizD, S, ne2)
ListBox1.Items.Add(" RESULTADOS DESPUES DE FLOYD")
ListBox1.Items.Add("matriz D")
MostrarMatrizFormulario(MatrizD, ne2, ne2)
ListBox1.Items.Add(" MATRIZ S")
MostrarMatrizFormulario(S, ne2, ne2)
nodoi = 0
nodof = ne2 - 1
dist = RutaMinimaFormulario(MatrizD, S, Ruta, nodoi, nodof, Cont)
ListBox1.Items.Add(" la distancia total es " & dist)
menorTotal = 0
'obtener trayectoria de la ruta en un vector
For col = 0 To ne2 - 1
Ruta1(col) = Ruta(ne2 - 1 - col)
Next
For col = 1 To ne2 - 1
lugar1 = Ruta1(col - 1)
lugar2 = Ruta1(col)
px1 = VX1(VL2(lugar1))
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -896-
py1 = VY1(VL2(lugar1))
px2 = VX1(VL2(lugar2))
py2 = VY1(VL2(lugar2))
menor1 = DistanciaMenorPuntos(px1, py1, px2, py2, VXMenor, VYMenor, meta)
menorTotal = adicionar(VXMenorTotal, VYMenorTotal, menorTotal, VXMenor,
VYMenor, menor1)
Next
VerMatrizFormulario(MatrizW, nfilas, ncol, cx, cy)
trazarRutaFormulario(VXMenorTotal, VYMenorTotal, menorTotal, cx, cy, Ex, Ey, 6)
' color rojo
PonerPuntoFormulario(xbusca, ybusca, Ex, Ey, busca1)
PonerPuntoFormulario(xmeta, ymeta, Ex, Ey, meta)
End Sub

Function RutaMinimaFormulario(D(,) As Integer, S(,) As Integer, Ruta() As Integer, _


nodoi As Integer, nodof As Integer, ByRef Cont As Integer)
Dim valor = 0, col As Integer
Dim Dist, suma As Single
Dim cadena As String
Cont = 0
Ruta(0) = nodof
Dim control As Boolean = False
While (control = False)
valor = S(nodoi, nodof)
Cont = Cont + 1
If (valor = nodof) Then
control = True
Else
Ruta(Cont) = valor
nodof = valor
End If
End While
Ruta(Cont) = nodoi
ListBox1.Items.Add(" la ruta es ")
cadena = ""
For col = Cont To 0 Step -1
cadena = cadena & " ==> " & Ruta(col)
Next
ListBox1.Items.Add(cadena)
ListBox1.Items.Add("Distancias ")
cadena = ""
For col = Cont To 1 Step -1
Dist = D(Ruta(col), Ruta(col - 1))
suma = suma + Dist
cadena = cadena & " ==> " & Dist
Next
Return suma
End Function

Sub PonerPuntoFormulario(px As Integer, py As Integer, Ex As Integer, Ey As


Integer, color As Integer)
Select Case color
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -897-
Case 0 : brocha.Color = Drawing.Color.Black
Case 1 : brocha.Color = Drawing.Color.Blue
Case 2 : brocha.Color = Drawing.Color.Green
Case 9 : brocha.Color = Drawing.Color.Lime
End Select
grafico.FillRectangle(brocha, cx + px * Ex, cy + py * Ey, Ex, Ey)
grafico.DrawRectangle(pluma, cx + px * Ex, cy + py * Ey, Ex, Ey)
End Sub
Sub SembrarGrafico(MatrizW(,) As Integer, VX3() As Integer, VY3() As Integer, VL3()
As Integer, ne3 As Integer, busca2 As Integer)
Dim MiFuente As New Font("Verdana", 12, FontStyle.Bold)
brocha.Color = Drawing.Color.Red
Dim fila As Integer
Dim Lugar, px, py As Integer
For fila = 0 To ne3 - 1
Lugar = VL3(fila)
px = VX3(Lugar)
py = VY3(Lugar)
If MatrizW(py, px) = Camino Then
grafico.DrawString(CStr(fila), MiFuente, brocha, cx + px * Ex, cy + py * Ey)
End If
' MatrizW(py, px) = busca2
Next
End Sub
Sub trazarRutaFormulario(Vx1() As Integer, Vy1() As Integer, ne As Integer, cx As
Integer, cy As Integer, ex As Integer, ey As Integer, color As Integer)
Dim col, px, py As Integer
Select Case color
Case 0 : brocha.Color = Drawing.Color.Black
Case 1 : brocha.Color = Drawing.Color.Blue
Case 2 : brocha.Color = Drawing.Color.Aqua
Case 3 : brocha.Color = Drawing.Color.Cyan
Case 4 : brocha.Color = Drawing.Color.Red
Case 5 : brocha.Color = Drawing.Color.Violet
Case 6 : brocha.Color = Drawing.Color.Yellow
Case 7 : brocha.Color = Drawing.Color.Orange
Case 8 : brocha.Color = Drawing.Color.Gray
Case 9 : brocha.Color = Drawing.Color.Lime
End Select
For col = 0 To ne - 1
px = Vx1(col)
py = Vy1(col)
grafico.FillRectangle(brocha, cx + px * ex, cy + py * ey, ex, ey)
grafico.DrawRectangle(pluma, cx + px * ex, cy + py * ey, ex, ey)
Next
End Sub
Private Sub btnNumerar_Click(sender As Object, e As EventArgs) Handles
btnNumerar.Click
SembrarGrafico(MatrizW, VX2, VY2, VL2, ne2, busca2)
End Sub
End Class
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -898-

CODIGO DEL MODULO 1

Imports System.IO
Module Module1
Sub MAIN()
Dim resultado, fila, col As Integer
Dim menor1, Dir As Integer
Dir = 1
RecuperarMatriz(NombreArchivo, Matriz, nfilas, ncol)
' encuentra la meta
CopiarMatriz(Matriz, MatrizW, nfilas, ncol)
VerMatriz(MatrizW, nfilas, ncol, cx, cy)
px1 = xbusca
py1 = ybusca
px2 = xmeta
py2 = ymeta
'VerMatriz(MatrizW, nfilas, ncol, cx, cy)
IniciarDistancias(MatrizW, VX1, VY1, VX2, VY2, px1, py1, px2, py2, meta)
'VerMatriz(MatrizW, nfilas, ncol, cx, cy)
resultado = bUSCAR(MatrizW, VX1, VY1, VX2, VY2, px1, py1, Cont, ContMov)
'VerMatriz(MatrizW, nfilas, ncol, cx, cy)
If resultado >= 0 Then
ne1 = Cont
DejarCamino(MatrizW, VX1, VY1, ne1, busca1)
'VerMatriz(MatrizW, nfilas, ncol, cx, cy)
px1 = VX1(ne1)
py1 = VY1(ne1)
Console.WriteLine("meta encontrada X={0} y {1} con {2} ne1 {3} cont mov ",
px1, py1, ne1, ContMov)
' Exit Sub
End If
' ne2 = Cont
'VerMatriz(MatrizW, nfilas, ncol, cx, cy)
bUSCARCruces(MatrizW, VX1, VY1, VA1, VL2, ne1, ne2, busca1, Camino)
'insertar el primer elemento
Console.WriteLine()
For col = ne2 To 1 Step -1
VL2(col) = VL2(col - 1)
Next
VL2(0) = 0
VL2(ne2 + 1) = ne1
ne2 = ne2 + 2
'Mostrar3Vectores(VA1, VL2, VL2, ne2)
' ENCONTRAR DISTANCIAS
Console.Clear()
For fila = 0 To ne2 - 1
For col = 0 To ne2 - 1
px1 = VX1(VL2(fila))
py1 = VY1(VL2(fila))
px2 = VX1(VL2(col))
py2 = VY1(VL2(col))
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -899-
menor1 = DistanciaMenorPuntos(px1, py1, px2, py2, VXMenor, VYMenor, meta)
MatrizD(fila, col) = menor1
MatrizDIR(fila, col) = Dir
'Console.WriteLine("fila {0} col {1} distmenor {2} dir {3} ", fila, col, menor1, Dir)
Next
Next
' Console.Clear()
Console.WriteLine("MATRIZ DISTANCIA")
MostrarMatriz(MatrizD, ne2, ne2)
Console.WriteLine("MATRIZ DIRECCION")
MostrarMatriz(MatrizDIR, ne2, ne2)
' GrabarMatriz(NombreArchivoMatriz, MatrizD, ne3, ne3)
' ''' PROCESO DE FLYD
Console.WriteLine("MATRIZ S")
ObtenerS(S, ne2, ne2)
MostrarMatriz(S, ne2, ne2)
floyd(MatrizD, S, ne2)
Console.WriteLine(" RESULTADOS despues de FLOYD")
Console.WriteLine(" matriz D")
MostrarMatriz(MatrizD, ne2, ne2)
Console.WriteLine(" matriz S")
MostrarMatriz(S, ne2, ne2)
'Console.Write(" ingrese nodo inicial de 0 a {0} ", ne3 - 1)
'nodoi = Console.ReadLine
'Console.Write("ingrese nodo final de 0 a {0} ", ne3 - 1)
'nodof = Console.ReadLine
nodoi = 0
nodof = ne2 - 1
dist = RutaMinima(MatrizD, S, Ruta, nodoi, nodof, Cont)
' Console.WriteLine(" la distancia total es {0}", dist)
'obtener trayectoria de la ruta en un vector
For col = 0 To ne2 - 1
Ruta1(col) = Ruta(ne2 - 1 - col)
Next
Console.Clear()
For col = 1 To ne2 - 1
lugar1 = Ruta1(col - 1)
lugar2 = Ruta1(col)
px1 = VX1(VL2(lugar1))
py1 = VY1(VL2(lugar1))
px2 = VX1(VL2(lugar2))
py2 = VY1(VL2(lugar2))
menor1 = DistanciaMenorPuntos(px1, py1, px2, py2, VXMenor, VYMenor, meta)
menorTotal = adicionar(VXMenorTotal, VYMenorTotal, menorTotal, VXMenor,
VYMenor, menor1)
Next
' Console.Clear()
VerMatriz(MatrizW, nfilas, ncol, cx, cy)
trazarRuta(VXMenorTotal, VYMenorTotal, menorTotal, cx, cy, color)
Console.ReadLine()
End Sub
End Module
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -900-

CODIGO DEL MODULO 2

Imports System.IO
Module Module2
Sub ObtenerS(S(,) As Integer, Nfilas As Integer, Ncol As Integer)
Dim fila, col As Integer
For fila = 0 To Nfilas
For col = 0 To Ncol
If (fila = col) Then
S(fila, col) = -1
Else
S(fila, col) = col
End If
Next
Next
End Sub
Sub floyd(ByRef D(,) As Integer, ByRef S(,) As Integer, n As Integer)
Dim i, j, k As Integer
For k = 0 To n - 1
For i = 0 To n - 1
For j = 0 To n - 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
'Console.WriteLine(" ITER {0}", k)
'MostrarMatrizReal(D, nfilas, ncol)
'Console.WriteLine(" matriz S")
'MostrarMatrizE(S, nfilas, ncol)
Next
End Sub
Function RutaMinima(D(,) As Integer, S(,) As Integer, Ruta() As Integer, _
nodoi As Integer, nodof As Integer, ByRef cont As Integer) As Single
Dim valor = 0, col As Integer
Dim Dist, suma As Single
cont = 0
Ruta(0) = nodof
Dim control As Boolean = False
While (control = False)
valor = S(nodoi, nodof)
cont = cont + 1
If (valor = nodof) Then
control = True
Else
Ruta(cont) = valor
nodof = valor
End If
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -901-
End While
Ruta(cont) = nodoi
Console.WriteLine(" la ruta es ")
For col = cont To 0 Step -1
Console.Write(" ==>{0} ", Ruta(col))
Next
Console.WriteLine("Distancias")
For col = cont To 1 Step -1
Dist = D(Ruta(col), Ruta(col - 1))
suma = suma + Dist
Console.Write(" ==> {0}", Dist)
Next
Return suma
End Function
Sub CopiarMatriz(A(,) As Integer, B(,) As Integer, nf As Integer, 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
Function ContarLetra(Cadena As String, letra As Char)
Dim LARGO As Integer = Len(Cadena)
Dim cont, cant As Integer
For cont = 0 To LARGO - 1
If Cadena(cont) = letra Then
cant = cant + 1
End If
Next
Return cant + 1
End Function
Sub RecuperarMatriz(ByVal nombrearchivo As String, ByRef A(,) As Integer, ByRef
nf As Integer, ByRef 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
cadena = srLector.ReadLine()
nc = ContarLetra(cadena, vbTab)
Do While Not (cadena = "")
cadena = cadena & vbTab
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
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -902-
fila = fila + 1
cadena = srLector.ReadLine()
Loop
nf = fila
Console.WriteLine("Archivo leido satisfactoriamente")
srLector.Close()
End Sub
Sub VerMatriz(ByVal A(,) As Integer, ByVal nf As Integer, ByVal nc As Integer, ByVal
cx As Integer, ByVal cy As Integer)
Dim fila, col As Integer
For fila = 0 To nf - 1
For col = 0 To nc - 1
If A(fila, col) <= 15 Then
Console.SetCursorPosition(cx + col, cy + fila)
' Console.BackgroundColor = CType(A(fila, col), ConsoleColor)
Console.ForegroundColor = A(fila, col) + 5
Console.Write("{0}", A(fila, col))
End If
Next
Next
End Sub
Sub GrabarMatriz(NombreArchivo As String, A(,) As Integer, nf As Integer, nc As
Integer)
Dim fila, col As Integer
Dim Archivo As New StreamWriter(NombreArchivo)
For fila = 0 To nf - 1
For col = 0 To nc - 1
Archivo.Write("{0} {1}", A(fila, col), vbTab)
Next
Archivo.WriteLine()
Next
Archivo.Close()
MsgBox("archivo " & NombreArchivo & "grabado")
End Sub
Sub MostrarMatriz(A(,) As Integer, nf As Integer, nc As Integer)
Dim fila, col As Integer
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 encontrarcamino(A(,) As Integer, px As Integer, py As Integer, ByRef
camino As Integer, meta As Integer) As Integer
Dim resultado As Integer = -1
'VerMatriz(A, nfilas, ncol, cx, cy)
If px <= 0 Or py <= 0 Then Return -1
If A(py, px + 1) = meta Or A(py + 1, px) = meta Or A(py, px - 1) = meta Or A(py - 1,
px) = meta Then
Return 8
End If
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -903-

If A(py, px + 1) = camino Then


resultado = 1
Else
If A(py + 1, px) = camino Then
resultado = 2
Else
If A(py, px - 1) = camino Then
resultado = 3
Else
If A(py - 1, px) = camino Then
resultado = 4
Else
resultado = -1
End If
End If
End If
End If
Return resultado
End Function

Sub Grabar3Vectores(NombreArchivoSalida As String, VX() As Integer, VY() As


Integer, Vz() As Integer, ne As Integer)
Dim fila As Integer
Dim Archivo As New StreamWriter(NombreArchivoSalida)
For fila = 0 To ne
Archivo.WriteLine("{0}{1}{2}{3}{4}{5}{6}{7}", fila, vbTab, VX(fila), vbTab, VY(fila),
vbTab, Vz(fila), vbTab)
Next
Archivo.Close()
MsgBox(" archivo grabado " & NombreArchivoSalida)
End Sub
Function bUSCAR(Matriz(,) As Integer, Vx() As Integer, Vy() As Integer, _
vX2() As Integer, VY2() As Integer, xbusca As Integer, ybusca As Integer,
ByRef cont As Integer,
ByRef contmov As Integer) As Integer
Dim retorno As Integer = 1
Do
Dim dir As Integer
'VerMatriz(Matriz, nfilas, ncol, cx, cy)
dir = encontrarcamino(Matriz, xbusca, ybusca, Camino, meta)
' VerMatriz(Matriz, nfilas, ncol, cx, cy)
If dir < 0 Then
If estado = 1 Then
cont = cont + 1
End If
estado = -1
Else
estado = 1
End If
Select Case dir
Case 1 : xbusca = xbusca + 1
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -904-
Case 2 : ybusca = ybusca + 1
Case 3 : xbusca = xbusca - 1
Case 4 : ybusca = ybusca - 1
Case 8
retorno = 1
If cont = 0 Then cont = 1
Exit Do
Case Else
End Select
cont = cont + estado
If estado = -1 Then
If cont < 0 Then
retorno = -1
Exit Do
End If
If Matriz(ybusca, xbusca) = busca1 Then Matriz(ybusca, xbusca) = busca2
xbusca = Vx(cont)
ybusca = Vy(cont)
Else
Vx(cont) = xbusca
Vy(cont) = ybusca
If Matriz(ybusca, xbusca) = Camino Then Matriz(ybusca, xbusca) = busca1
End If
'mostrarbusqueda(Vx, Vy, cont, cx, cy, 15)
contmov = contmov + 1
vX2(contmov) = xbusca
VY2(contmov) = ybusca
' Console.ReadLine()
' System.Threading.Thread.Sleep(vel) ' 1 segundo
Loop While (1)
Return retorno
End Function
Sub DejarCamino(Matriz(,) As Integer, Vx() As Integer, VY() As Integer, ne As
Integer, busca1 As Integer)
Dim fila As Integer
For fila = 0 To ne - 1
Matriz(VY(fila), Vx(fila)) = busca1
Next
End Sub

Sub Mostrar3Vectores(X() As Integer, Y() As Integer, Z() As Integer, ne As Integer)


Dim col As Integer
For col = 0 To ne - 1
Console.WriteLine(" {0} {1} {2} ", X(col), Y(col), Z(col))
Next
End Sub

Sub bUSCARCruces(A(,) As Integer, Vx1() As Integer, Vy1() As Integer, Va1() As


Integer, VL3() As Integer, _
ne1 As Integer, ByRef ne3 As Integer, busca1 As Integer,
camino As Integer)
Dim col, px, py As Integer
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -905-
Dim suma As Integer = 0
ne3 = 0
CopiarMatriz(Matriz, A, nfilas, ncol)
'VerMatriz(A, nfilas, ncol, cx, cy)
For col = 0 To ne1 - 1
px = Vx1(col)
py = Vy1(col)
A(py, px) = busca1
'VerMatriz(A, nfilas, ncol, cx, cy)
suma = 0
If A(py, px + 1) = camino Then suma = suma + 1
If A(py + 1, px) = camino Then suma = suma + 1
If A(py, px - 1) = camino Then suma = suma + 1
If A(py - 1, px) = camino Then suma = suma + 1
Va1(col) = suma
If suma > 1 Then
VL3(ne3) = col
ne3 = ne3 + 1
End If
'VerMatriz(A, nfilas, ncol, cx, cy)
Next
End Sub
Function IniciarDistancias(MatrizW(,) As Integer, VXW1() As Integer, VYW1() As
Integer, _
VXW2() As Integer, VYW2() As Integer, px1 As Integer, py1 As Integer, _
px2 As Integer, py2 As Integer, meta As Integer) As Integer
Dim resultado As Integer = 1
MatrizW(py2, px2) = meta
If MatrizW(py1, px1) = Camino Then
MatrizW(py1, px1) = busca1
ContMov = 0
estado = 1
Cont = 0
VXW1(Cont) = px1
VYW1(Cont) = py1
VXW2(ContMov) = px1
VYW2(ContMov) = py1
resultado = 1
Else
resultado = -1
End If
Return resultado
End Function
Sub Sembrar(MatrizW(,) As Integer, VX3() As Integer, VY3() As Integer, VL3() As
Integer, ne3 As Integer, busca2 As Integer)
Dim fila As Integer
Dim Lugar, px, py As Integer
For fila = 0 To ne3 - 1
Lugar = VL3(fila)
px = VX3(Lugar)
py = VY3(Lugar)
If MatrizW(py, px) = Camino Then MatrizW(py, px) = busca2
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -906-
Next
End Sub

Function DistMenor(MatrizW(,) As Integer, px1 As Integer, py1 As Integer, px2 As


Integer, py2 As Integer, meta As Integer, _
VX1W() As Integer, VY1W() As Integer)
Dim resultado, resultado1, resultado2 As Integer
If px1 = px2 And py1 = py2 Then Return 0
CopiarMatriz(Matriz, MatrizW, nfilas, ncol)
resultado = IniciarDistancias(MatrizW, VXW1, VYW1, VXW2, VYW2, px1, py1,
px2, py2, meta)
'VerMatriz(MatrizW, nfilas, ncol, cx, cy)
resultado = encontrarcamino(MatrizW, px1, py1, Camino, meta)
If resultado = 8 Then Return 1
CopiarMatriz(Matriz, MatrizW, nfilas, ncol)
'VerMatriz(MatrizW, nfilas, ncol, cx, cy)
resultado1 = IniciarDistancias(MatrizW, VXW1, VYW1, VXW2, VYW2, px1, py1,
px2, py2, meta)
'VerMatriz(MatrizW, nfilas, ncol, cx, cy)
If resultado1 = -1 Then Return 99
Sembrar(MatrizW, VX1, VY1, VL2, ne2, busca2)
'VerMatriz(MatrizW, nfilas, ncol, cx, cy)
resultado2 = bUSCAR(MatrizW, VXW1, VYW1, VXW2, VYW2, px1, py1, Cont,
ContMov)
If resultado2 = -1 Then Return 99
'VerMatriz(MatrizW, nfilas, ncol, cx, cy)
Return Cont + 1
End Function

Sub trazarRuta(Vx1() As Integer, Vy1() As Integer, ne As Integer, cx As Integer, cy


As Integer, color As Integer)
Dim col, px, py As Integer
Console.ForegroundColor = color
For col = 0 To ne - 1
px = Vx1(col)
py = Vy1(col)
Console.SetCursorPosition(cx + px, cy + py)
Console.Write("*")
Next
End Sub
Sub CopiarVector(VA() As Integer, VB() As Integer, ne As Integer)
Dim col As Integer
For col = 0 To ne - 1
VB(col) = VA(col)
Next
End Sub
Function adicionar(X1() As Integer, Y1() As Integer, Ne1 As Integer, _
X2() As Integer, Y2() As Integer, Ne2 As Integer) As Integer
Dim col As Integer
For col = 0 To Ne2 - 1
X1(Ne1 + col) = X2(col)
Y1(Ne1 + col) = Y2(col)
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -907-
Next
Return Ne1 + Ne2
End Function
End Module

CODIGO DEL MODULO 3

Imports System.Drawing
Module Module3
Public pluma As Pen
Public brocha As SolidBrush
Public grafico As Graphics
Public menorTotal As Integer = 0
Public lugar1 As Integer = 0
Public lugar2 As Integer = 0

Public color As Integer = 14


Public Ex As Integer = 14
Public Ey As Integer = 14
Public nodoi As Integer = 1
Public nodof As Integer = 5
Public dist As Single
Public vel As Integer = 1
Public NombreArchivo As String = "E:\datos\matriz.txt"
Public NombreArchivoSalida As String = "E:\datos\recorrido.txt"
Public NombreArchivoMatriz As String = "E:\datos\matrizDIST.txt"
Public Const limite = 1500
Public px1 As Integer = 1
Public py1 As Integer = 1
Public px2 As Integer = 1
Public py2 As Integer = 1
Public Maximo = 99
Public Const MaxCol = 80
Public Const MaxFilas = 80
Public Camino = 0
Public estado As Integer = 1
Public Matriz(MaxFilas, MaxCol) As Integer
Public MatrizW(MaxFilas, MaxCol) As Integer
Public MatrizD(MaxFilas, MaxCol) As Integer
Public MatrizDIR(MaxFilas, MaxCol) As Integer
Public S(limite, limite) As Integer
Public Ruta(limite) As Integer
Public Ruta1(limite) As Integer
Public VX1(limite) As Integer ' vector de camino original
Public VY1(limite) As Integer
Public VX2(limite) As Integer ' vector general cruces
Public VY2(limite) As Integer
Public VXW1(limite) As Integer ' vector alt
Public VYW1(limite) As Integer
Public VXW2(limite) As Integer ' vector alt
Public VYW2(limite) As Integer
Public VXMenor(limite) As Integer ' vector alt
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -908-
Public VYMenor(limite) As Integer
Public VXMenorTotal(limite) As Integer ' vector alt
Public VYMenorTotal(limite) As Integer

Public VA1(limite) As Integer ' vector alternoe DE BUCADO


Public VL2(limite) As Integer ' vector de lugares

Public ne1 As Integer = 0 ' nro de elmento del vector tod el vecto
Public ne2 As Integer = 0 ' nro de elmento del vector de cruces
Public Cont As Integer

Public nfilas, ncol As Integer


Public busca1 As Integer = 1
Public busca2 As Integer = 2 'retroceso
Public xbusca As Integer = 4 ' es con respecto en la
Public ybusca As Integer = 4 ' es con respecto en la
Public meta As Integer = 9 ' es con respecto en la

Public xmeta As Integer = 14


Public ymeta As Integer = 3
Public cx As Integer = 1
Public cy As Integer = 4
Public ContMov As Integer = 0
Function DistanciaMenorPuntos(px1 As Integer, py1 As Integer, px2 As Integer, py2
As Integer, _
VXMenor() As Integer, Vymenor() As Integer, meta As Integer)
Dim d1, d2, d3, d4, dir, menor As Integer
menor = 100
dir = 0
'VerMatriz(MatrizW, nfilas, ncol, cx, cy)
dist = DistMenor(MatrizW, px1, py1, px2, py2, meta, VXW1, VYW1)
' ojo *****************
CopiarVector(VXW1, VXMenor, dist)
CopiarVector(VYW1, Vymenor, dist)
If dist >= Maximo Then
menor = Maximo
dir = 0
Else
If dist = 1 Or dist = 0 Then
menor = dist
dir = 0
Else
menor = dist + 1
dir = 0
d1 = DistMenor(MatrizW, px1 + 1, py1, px2, py2, meta, VXW1, VYW1) + 1
If d1 < menor Then
menor = d1
dir = 1
CopiarVector(VXW1, VXMenor, menor)
CopiarVector(VYW1, Vymenor, menor)
End If
d2 = DistMenor(MatrizW, px1, py1 + 1, px2, py2, meta, VXW1, VYW1) + 1
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -909-
If d2 < menor Then
dir = 2
menor = d2
CopiarVector(VXW1, VXMenor, menor)
CopiarVector(VYW1, Vymenor, menor)
End If
d3 = DistMenor(MatrizW, px1 - 1, py1, px2, py2, meta, VXW1, VYW1) + 1
If d3 < menor Then
dir = 3
menor = d3
CopiarVector(VXW1, VXMenor, menor)
CopiarVector(VYW1, Vymenor, menor)
End If
d4 = DistMenor(MatrizW, px1, py1 - 1, px2, py2, meta, VXW1, VYW1) + 1
If d4 < menor Then
dir = 4
menor = d4
CopiarVector(VXW1, VXMenor, menor)
CopiarVector(VYW1, Vymenor, menor)
End If

VXMenor(menor - 1) = px1
Vymenor(menor - 1) = py1
VXMenor(menor) = px2
Vymenor(menor) = py2
End If
End If
Return menor
End Function
End Module

10.9 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
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -910-
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 Sub
End Module

CODIGO DEL MODULO 2

Imports System.IO
Module Module2
Public X(4) As Single
Public Y(4) As Single
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)
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -911-
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
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 Sub
End Module
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -912-

10.10 PROGRAMA DE LOCALIZACION DE LOTES


Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -913-

Option Explicit On
Imports System.Drawing
Public 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
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
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -914-
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
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, ";")
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -915-
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
End Sub
End Class

CODIGO DEL MODULO

Imports System.IO
Module 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
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -916-

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
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
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -917-
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
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 Sub
End Module
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -918-

10.13 MODELADO 3D (DIBUJO DE MALLAS ) SI ENTRA OPENGL NO


CONSIDERAR

GRAFICACION DE CURVAS

Se tiene los siguientes puntos hechos en Excel graficar Elaborar la grafica de los
puntos escaneados en visual Basic
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -919-

Imports System.Drawing
Imports System.IO
Module Module1
Public Const limitetx As Integer = 500
Public Const limitety As Integer = 500
Public Const limitetz As Integer = 500
Public Const limiteex As Integer = 100
Public Const limiteey As Integer = 100
Public Const limiteez As Integer = 100
Public varAngulo As Single = 1
Public varTras As Single = 1
Public varEscalado As Single = 1

Public NombreArchivo As String = "E:\datos\matriz40X30.txt"


Public Const limite As Integer = 2000
Public A(limite, limite) As Single
Public X() As Single = {0, 0, 0, 0}
Public Y() As Single = {0, 0, 0, 0}
Public Z() As Single = {0, 0, 0, 0}
Public XW() As Single = {0, 0, 0, 0}
Public YW() As Single = {0, 0, 0, 0}
Public ZW() As Single = {0, 0, 0, 0}
Public Grafico As Graphics
Public pen As Pen
Public brocha As SolidBrush
Public Cx As Single = 1
Public cy As Single = 1
Public cz As Single = 1
Public ex As Single = 10
Public ey As Single = 10
Public ez As Single = 10
Public tx As Single = 100
Public ty As Single = 100
Public tz As Single = 0
Public AnguloX As Single = 0
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -920-
Public AnguloY As Single = 0
Public AnguloZ As Single = 0
Public np As Single = 4
Public D As Single = 4000
Public nfilas As Integer = 3
Public ncol As Integer = 3
Public mayor As Single
Public Normales(limite, 4) As Single
Function ObtenerNormales(ByVal X() As Single, Y() As Single, Z() As Single, ByRef
Normales() As Single) As Single
Dim r1 As Single
Dim mayor As Single = -100000
Dim Pe As Single, R As Single
Dim pX As Single, py As Single, pz As Single
Dim Qx As Single, Qy As Single, Qz 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 = X(0) : y1 = Y(0) : z1 = Z(0)
x2 = X(1) : y2 = Y(1) : z2 = Z(1)
x3 = X(2) : y3 = Y(2) : z3 = Z(2)

pX = x2 - x1
py = y2 - y1
pz = z2 - z1
Qx = x3 - x1
Qy = y3 - y1
Qz = z3 - z1
NX = py * Qz - pz * Qy
Ny = pz * Qx - pX * Qz
Nz = pX * Qy - py * Qx

'PRODUCTO(CRUZ)
R = Math.Sqrt(NX * NX + Ny * Ny + Nz * Nz)
If R > 0 Then
Nx1 = NX / R
Else
Nx1 = 0
End If
If R > 0 Then
Ny1 = Ny / R
Else
Ny1 = 0
End If
If R > 0 Then
Nz1 = Nz / R
Else
Nz1 = 0
End If
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -921-
Pe = Nx1 * 0 + Ny1 * 0 + Nz1 * D
Normales(0) = Nx1
Normales(1) = Ny1
Normales(2) = Nz1
If Nz1 > mayor Then mayor = Nz1
Normales(3) = Pe
r1 = Math.Sqrt(Nx1 * Nx1 + Ny1 * Ny1 + Nz1 * Nz1)
Return r1
End Function
Function ContarLetra(Cadena As String, letra As Char)
Dim LARGO As Integer = Len(Cadena)
Dim cont, cant As Integer
For cont = 0 To LARGO - 1
If Cadena(cont) = letra Then
cant = cant + 1
End If
Next
Return cant + 1
End Function
Sub MAIN()
RecuperarMatriz(NombreArchivo, A, nfilas, ncol)
MostrarMatriz(A, nfilas, ncol)
Console.ReadLine()
End Sub
Sub RecuperarMatriz(ByVal nombrearchivo As String, ByRef A(,) As Single, ByRef nf
As Integer, ByRef 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
cadena = srLector.ReadLine()
nc = ContarLetra(cadena, vbTab)
Do While Not (cadena = "")
cadena = cadena & vbTab
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
Console.WriteLine("Archivo leido satisfactoriamente")
srLector.Close()
End Sub
Sub MostrarMatriz(A(,) As Single, nf As Integer, nc As Integer)
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -922-
Dim fila, col As Integer
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

Sub EscaladoXYZ(X() As Single, Y() As Single, Z() As Single, _


ByVal Ex As Single, ByVal Ey As Single, ByVal Ez As Single, nf As Integer)
Dim fila As Integer
For fila = 0 To nf - 1
X(fila) = X(fila) * Ex
Y(fila) = Y(fila) * Ey
Z(fila) = Z(fila) * Ez
Next
End Sub
Sub CopiarXYZ(X() As Single, Y() As Single, Z() As Single, _
X1() As Single, Y1() As Single, Z1() As Single, nf As Integer)
For fila = 0 To nf - 1
X1(fila) = X(fila)
Y1(fila) = Y(fila)
Z1(fila) = Z(fila)
Next
End Sub
Sub TraslacionXYZ(X() As Single, Y() As Single, Z() As Single, _
ByVal tx As Single, ByVal ty As Single, ByVal tz As Single, nf As Integer)
Dim fila As Integer
For fila = 0 To nf - 1
X(fila) = X(fila) + tx
Y(fila) = Y(fila) + ty
Z(fila) = Z(fila) + tz
Next
End Sub
Sub RotacionXYZ(X() As Single, Y() As Single, Z() As Single, _
ByVal AnguloX As Single, ByVal AnguloY As Single, ByVal anguloZ As
Single, nf As Integer)
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 X
Dim arx = AnguloX * Math.PI / 180
For fila = 0 To nf - 1
x1 = X(fila)
y1 = Y(fila)
z1 = Z(fila)
x2 = x1
y2 = CSng(y1 * Math.Cos(arx) - z1 * Math.Sin(arx))
z2 = CSng(y1 * Math.Sin(arx) + z1 * Math.Cos(arx))
X(fila) = x2
Y(fila) = y2
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -923-
Z(fila) = z2
Next
REM rotacion Y
Dim ary = AnguloY * Math.PI / 180
For fila = 0 To nf - 1
x1 = X(fila)
y1 = Y(fila)
z1 = Z(fila)
x2 = CSng(x1 * Math.Cos(ary) - z1 * Math.Sin(ary))
y2 = y1
z2 = CSng(-x1 * Math.Sin(ary) + z1 * Math.Cos(ary))
X(fila) = x2
Y(fila) = y2
Z(fila) = z2
Next
REM rotacion Z
Dim arz = anguloZ * Math.PI / 180
For fila = 0 To nf - 1
x1 = X(fila)
y1 = Y(fila)
z1 = Z(fila)
x2 = CSng(x1 * Math.Cos(arz) - y1 * Math.Sin(arz))
y2 = CSng(x1 * Math.Sin(arz) + y1 * Math.Cos(arz))
z2 = z1
X(fila) = x2
Y(fila) = y2
Z(fila) = z2
Next
End Sub
End Module

CODIGO DEL FORMULARIO

Imports System.Drawing
Imports System.Windows.Forms
Public Class Form1
Sub MostrarMatrizFormulario(A(,) As Single, nf As Integer, nc As Integer)
Dim fila, col As Integer
DataGridView2.RowCount = nfilas
DataGridView2.ColumnCount = ncol
For col = 0 To ncol - 1
DataGridView2.Columns(col).Width = 30
DataGridView2.Columns(col).HeaderText = col
Next
For fila = 0 To nf - 1
For col = 0 To nc - 1
DataGridView2.Rows(fila).Cells(col).Value = A(fila, col)
Next
Next
End Sub
Sub Figura(X() As Single, Y() As Single, Z() As Single)
Dim Puntos(3) As Point
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -924-
Dim Rnormal As Single
Dim Normales(4) As Single
Dim verde As Integer
Puntos(0).X = (X(0) * D) / (D + Z(0))
Puntos(0).Y = (Y(0) * D) / (D + Z(0))
Puntos(1).X = (X(1) * D) / (D + Z(1))
Puntos(1).Y = (Y(1) * D) / (D + Z(1))
Puntos(2).X = (X(2) * D) / (D + Z(2))
Puntos(2).Y = (Y(2) * D) / (D + Z(2))
Puntos(3).X = (X(3) * D) / (D + Z(3))
Puntos(3).Y = (Y(3) * D) / (D + Z(3))
RNormal = ObtenerNormales(X, Y, Z, Normales)
If Normales(2) >= 0 Then
'verde = 255 * Normales(2)
verde = 255 * Normales(2)

If verde >= 255 Then verde = 255


brocha.Color = Color.FromArgb(0, verde, 0)
Grafico.FillPolygon(brocha, Puntos)
End If
' Grafico.DrawPolygon(pen, Puntos)
End Sub
Private Sub ObtenerDatos(sender As Object, e As EventArgs) Handles
btnObtener.Click
AnguloX = DataGridView1.Rows(0).Cells(1).Value
AnguloY = DataGridView1.Rows(0).Cells(2).Value
AnguloZ = DataGridView1.Rows(0).Cells(3).Value
varAngulo = DataGridView1.Rows(0).Cells(4).Value
tx = DataGridView1.Rows(1).Cells(1).Value
ty = DataGridView1.Rows(1).Cells(2).Value
tz = DataGridView1.Rows(1).Cells(3).Value
varTras = DataGridView1.Rows(1).Cells(4).Value
ex = DataGridView1.Rows(2).Cells(1).Value
ey = DataGridView1.Rows(2).Cells(2).Value
ez = DataGridView1.Rows(2).Cells(3).Value
D = DataGridView1.Rows(3).Cells(1).Value
varEscalado = DataGridView1.Rows(2).Cells(4).Value
Grafico.Clear(Color.Black)
btnProcesar_Click(sender, e)
'Figura(XW, YW, ZW)
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Grafico = frmgrafico.PictureBox1.CreateGraphics
pen = New Pen(Brushes.Red, 1)
brocha = New SolidBrush(Color.Green)
CopiarXYZ(X, Y, Z, XW, YW, ZW, np)
RotacionXYZ(XW, YW, ZW, AnguloX, AnguloY, AnguloZ, np)
EscaladoXYZ(XW, YW, ZW, ex, ey, ez, np)
TraslacionXYZ(XW, YW, ZW, ex, ey, ez, np)
End Sub
Private Sub txtRot_KeyDown(sender As Object, e As Windows.Forms.KeyEventArgs)
Handles txtRotacion.KeyDown
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -925-
Select Case e.KeyCode
Case Keys.A, Keys.Left ' A rotacion inverso de X
If AnguloX >= -3600 Then
AnguloX = AnguloX - varAngulo
Else
AnguloX = 3600
End If
Case Keys.X, Keys.Right ' ROTACION EJE X
If AnguloX <= 3600 Then
AnguloX = AnguloX + varAngulo
Else
AnguloX = 0
End If

Case Keys.B, Keys.Down ' 66 ' B Inverso De Y


If AnguloY >= -3600 Then
AnguloY = AnguloY - varAngulo
Else
AnguloY = 3600
End If
Case Keys.Y, Keys.Up ' ROTACION EJE Y
If AnguloY <= 3600 Then
AnguloY = AnguloY + varAngulo
Else
AnguloY = 0
End If

Case Keys.C, Keys.PageDown ' C ROTACION Inverso de C


If AnguloZ >= -36000 Then
AnguloZ = AnguloZ - varAngulo
Else
AnguloZ = 3600
End If
Case Keys.Z, Keys.PageUp ' ROTACION EJE Z
If AnguloZ <= 3600 Then
AnguloZ = AnguloZ + varAngulo
Else
AnguloZ = 0
End If
End Select
DataGridView1.Rows(0).Cells(1).Value = AnguloX
DataGridView1.Rows(0).Cells(2).Value = AnguloY
DataGridView1.Rows(0).Cells(3).Value = AnguloZ
Grafico.Clear(Color.Black)

btnProcesar_Click(sender, e)
txtRotacion.Text = ""
End Sub
Private Sub BtnIniciar_Click(sender As Object, e As EventArgs) Handles
BtnIniciar.Click
Dim col As Integer
DataGridView1.RowCount = 4
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -926-
DataGridView1.ColumnCount = 5
For col = 0 To 4
DataGridView1.Columns(col).Width = 30
Next
DataGridView1.Columns(0).HeaderText = "Parametro"
DataGridView1.Columns(1).HeaderText = "X"
DataGridView1.Columns(2).HeaderText = "Y"
DataGridView1.Columns(3).HeaderText = "Z"
DataGridView1.Columns(4).HeaderText = "Var"

DataGridView1.Rows(0).Cells(0).Value = "Angulo"
DataGridView1.Rows(0).Cells(1).Value = AnguloX
DataGridView1.Rows(0).Cells(2).Value = AnguloY
DataGridView1.Rows(0).Cells(3).Value = AnguloZ
DataGridView1.Rows(0).Cells(4).Value = VarAngulo
DataGridView1.Rows(1).Cells(0).Value = "Traslac"
DataGridView1.Rows(1).Cells(1).Value = tx
DataGridView1.Rows(1).Cells(2).Value = ty
DataGridView1.Rows(1).Cells(3).Value = tz
DataGridView1.Rows(1).Cells(4).Value = varTras
DataGridView1.Rows(2).Cells(0).Value = "Escalado"
DataGridView1.Rows(2).Cells(1).Value = ex
DataGridView1.Rows(2).Cells(2).Value = ey
DataGridView1.Rows(2).Cells(3).Value = ez
DataGridView1.Rows(2).Cells(4).Value = varEscalado

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

End Sub
Sub Proceso(A(,) As Single, Xcol As Integer, Yfila As Integer, _
anguloX As Single, anguloY As Single, anguloZ As Single, _
tx As Single, ty As Single, tz As Single, _
ex As Single, ey As Single, ez As Single)

X(0) = Xcol : Y(0) = Yfila : Z(0) = A(Yfila, Xcol)


X(1) = Xcol + 1 : Y(1) = Yfila : Z(1) = A(Yfila, Xcol + 1)
X(2) = Xcol + 1 : Y(2) = Yfila + 1 : Z(2) = A(Yfila + 1, Xcol + 1)
X(3) = Xcol : Y(3) = Yfila + 1 : Z(3) = A(Yfila + 1, Xcol)
CopiarXYZ(X, Y, Z, XW, YW, ZW, np)
RotacionXYZ(XW, YW, ZW, anguloX, anguloY, anguloZ, np)
EscaladoXYZ(XW, YW, ZW, ex, ey, ez, np)
TraslacionXYZ(XW, YW, ZW, tx, ty, tz, np)
Figura(XW, YW, ZW)
End Sub
Private Sub btnProcesar_Click(sender As Object, e As EventArgs) Handles
btnProcesar.Click
Dim col, fila As Integer
For fila = 0 To nfilas - 1
For col = 0 To ncol - 1
Proceso(A, col, fila, AnguloX, AnguloY, AnguloZ, tx, ty, tz, ex, ey, ez)
Next
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -927-
Next
frmgrafico.Show()
End Sub
Private Sub btnBorrar_Click(sender As Object, e As EventArgs) Handles
btnBorrar.Click
Grafico.Clear(Color.Black)
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnAbrir.Click


RecuperarMatriz(NombreArchivo, A, nfilas, ncol)
MostrarMatrizFormulario(A, nfilas, ncol)
End Sub

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


txtTraslacion.KeyDown
Select Case e.KeyCode
Case Keys.A, Keys.Left ' A rotacion inverso de X
If tx >= -limitetx Then
tx = tx - varTras
Else
tx = limitetx
End If
Case Keys.X, Keys.Right ' ROTACION EJE X
If tx <= limitetx Then
tx = tx + varTras
Else
tx = -limitetx
End If

Case Keys.Y, Keys.Up ' 66 ' B Inverso De Y


If ty >= -limitety Then
ty = ty - varTras
Else
ty = limitety
End If
Case Keys.B, Keys.Down ' traslacion
If ty <= limitety Then
ty = ty + varTras
Else
ty = -limitety
End If

Case Keys.C, Keys.PageDown ' C ROTACION Inverso de C


If tz >= -100 Then
tz = tz - varTras
Else
tz = 100
End If
Case Keys.Z, Keys.PageUp ' ROTACION EJE Z
If tz <= limitetz Then
tz = tz + varTras
Else
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -928-
tz = -limitetz
End If
End Select
DataGridView1.Rows(1).Cells(1).Value = tx
DataGridView1.Rows(1).Cells(2).Value = ty
DataGridView1.Rows(1).Cells(3).Value = tz
Grafico.Clear(Color.Black)
btnProcesar_Click(sender, e)
TxtEscalado.Text = ""
End Sub

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


TxtEscalado.KeyDown
Select Case e.KeyCode
Case Keys.A, Keys.Left ' A rotacion inverso de X
If ex >= -limiteex Then
ex = ex - varEscalado
Else
ex = limiteex
End If
Case Keys.X, Keys.Right ' ROTACION EJE X
If ex <= limiteex Then
ex = ex + varEscalado
Else
ex = -limiteex
End If

Case Keys.Y, Keys.Up ' 66 ' B Inverso De Y


If ey >= -limiteey Then
ey = ey - varEscalado
Else
ey = limiteey
End If
Case Keys.B, Keys.Down ' traslacion
If ey <= limiteey Then
ey = ey + varEscalado
Else
ey = -limiteey
End If

Case Keys.C, Keys.PageDown ' C ROTACION Inverso de C


If ez >= -100 Then
ez = ez - varEscalado
Else
ez = 100
End If
Case Keys.Z, Keys.PageUp ' ROTACION EJE Z
If ez <= limiteez Then
ez = ez + varEscalado
Else
ez = -limiteez
End If
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -929-
End Select
DataGridView1.Rows(2).Cells(1).Value = ex
DataGridView1.Rows(2).Cells(2).Value = ey
DataGridView1.Rows(2).Cells(3).Value = ez
Grafico.Clear(Color.Black)
btnProcesar_Click(sender, e)
txtTraslacion.Text = ""
End Sub

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


btnCoordenadas.Click
Grafico.DrawLine(Pens.Red, tx, ty, ex * 4, ty)
Grafico.DrawLine(Pens.Red, tx, ty, tx, ty * 4)
End Sub
End Class

10.18 JUEGO DEL PACMAN

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

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

se juega con las teclas direccionales

Option Explicit On
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -930-
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
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
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -931-
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
' 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
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -932-
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)
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
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -933-
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 Sub
End Class

CODIGO DEL MODULO

Imports System.IO
Module 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
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -934-
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)
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
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -935-
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)
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
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -936-
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 Function
End Module
Tarea: elaborar el siguiente juego del pacman

10.19 GRAFICA DE FUNCIONES EN 2D Y 3D


Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -937-

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 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
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -938-
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
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.IO
Public 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
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -939-
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"


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
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -940-
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
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
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -941-
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)
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
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -942-
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)

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
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -943-
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
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()
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -944-
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
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
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -945-
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
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 Sub
End Class

10.21 JUEGO DE LA SERPIENTE O GUSANO(USO DE AUTOMATAS CELULARES)

Mover un ser con las teclas direccionales y en forma automática


Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -946-

' ******** codigo del modulo


Module 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 Integer
End Module

CODIGO DEL FORMULARIO

' *** codigo del formulario


Public Class Form1
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
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -947-
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

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
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -948-
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

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()
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -949-
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 Sub
End Class

10,22 DICCIONARIO TRADUCTOR


Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -950-

Imports System.IO
Module 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 Sub
End 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
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -951-
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
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -952-
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 Sub
End Class

10.23 DICCIONARIO TRADUCTOR EN MODO CONSOLA. PASAR A MODO


CONSOLA

Imports System.IO
Module 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)
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -953-
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 ")
Castellano = Console.ReadLine
BuscarCastellanoIngles(A, Castellano, nf)
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -954-
End Select
Loop While opcion <> 3
End Sub
End Module

TRADUCTOR MODIFICADO ( usando cuadros de dialogo)


Diseñe el siguiente formulario

CODIGO DEL FORMULARIO

Imports System.IO
Public 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)
Next
txtDestino.Text = Texto
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -955-
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
Texto = txtFuente.Text
For fila1 = 0 To nterminos - 1
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -956-
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 Sub
End Class
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -957-

Tarea : modifique la aplicación parar traducir Código de Lenguaje C++ a Código de


Visual Basic

10.24 CUADRO CROMATICO

Imports System.Drawing
Public 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
Dim fila, col As Integer
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -958-
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 Sub
End Class

Tarea.- Elaborar Gama de colores o circulo cromático(use el triangulo para cad color)(
Estudiar el cuadro cromaico
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -959-
10.25 EVALUACION DE EXPRESIONES MUY LARGO

'***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
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -960-
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
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
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -961-
' 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
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
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -962-
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
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)
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -963-
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
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
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -964-
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
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)
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -965-
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
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
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -966-
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
End Module

' *** CODIGO DEL FORMULARIO


Public 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)
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -967-
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
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
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -968-
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
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
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -969-
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
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)
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -970-
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

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
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -971-
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)
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
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -972-
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 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)
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -973-
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()
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 Sub
End Class

10.26 PROPUESTAS DE TRABAJOS DE INVESTIGACION

Los trabajos tienen que ser en modo visual . se deben presentar en grupos de 3
1. Aplicación de fractales y recursividad ejemplo modelización de terrenos
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -974-
2. Aplicación de autómatas celulares y computación universal. Juego de la vida en 2d y
3D
3. Aplicación del programa del buscador en optimización en modo grafico
4. Manejo del puerto USB
5. Programación de ADN manejo de secuencias cadenas
6. Programación genérica plantillas ( Templates)
7. Base de datos biológica
8. Aplicación 3d en opengl y visual estudio 2010, Simulación 3D
9. Aplicaciones Web Lenguaje HTML, Java, etc. y su importancia
10. Temas de inteligencia artificial como programación evolutiva , redes neuronales,etc
11. Sistemas de información en Office Excel
12. My sql
13. Automatización industrial plc, sensores,
14. Aplicaciones de sistemas de información para optimización
15. Simulación 3d, ejemplo simio.etc
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 sqlserver
19. Otros temas relacionados al curso de sistemas de información
20. usando recursividad encuentre la posicion de cada objeto y cuantos elementos tiene
cada uno

10.27 EVALUACION DE ALUACION DE EXPRESIONES PASARLO AL CAPITULO


INTERIRO
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -975-

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, ",", ".")
'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
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -976-
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))
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 ' *
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -977-
CalculSimple = n1 * n2
Case 47 ' /
CalculSimple = n1 / n2
'Aquí, agregar otro calculo...
End Select
End Function
End 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()
End Sub
End Module

Desarrollar un juego donde se mueve el fondo de la pantalla


Usar colores como las que indican en el cuadro

Nro Color Significado


0 negro camino limpio
1 punto amarillo pequeño cambia la matriz
2 naranja premio 10 puntos
3 Verde pared
4 rojo pierde e juego
5 azul pierde una vida
6 blanco Meta

10.28 VER UNA PARTE DE LA PANTALLA REPITIDO

Modificar el programa para ver parte de una pantalla(corregir)


HACERLO UNO SOLO DES ESTO LIBRO 2019
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -978-

'****** CODIGO DEL MODULO 1


Imports System.IO
Module 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
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -979-
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
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))
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -980-
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
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 Sub
End Module

' **** CODIGO DEL FORMULARIO


Public 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)
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -981-
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)
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
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -982-
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
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
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -983-
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
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
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -984-
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))
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()
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -985-
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)
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

10.29 DIBUJE EL SIGUIENTE PLANO


Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -986-

Imports System.IO
Module Module2
Public Const maxfilas As Integer = 31
Public Const maxcol As Integer = 6
Public A(maxfilas, maxcol) As String
Public Objetos(maxfilas, maxcol) As String
Public Nfilas As Integer = 30
Public Ncol As Integer = 7
Public NfObjetos As Integer = 8
Public NcObjetos As Integer = 4

Public NombreArchivo As String = "e:\datos\plano5x8.txt"


Public NombreArchivoSalida As String = "e:\datos\plano5x8Salida.txt"
Public NombreArchivoObjetos As String = "e:\datos\Objetos.txt"

Public Color1 As Integer = 0 ' si es cero es color azul


Public AltoLetra As Integer = 12
Public Cadena As String

Function BuscarCadena(A(,) As String, nf As Integer, letra As String) As Integer


Dim fila, posletra As Integer
posletra = -1
For fila = 0 To nf - 1
If Trim(A(fila, 6)) = letra Then
posletra = fila
Exit For
End If
Next
Return posletra
End Function

Sub MostrarMatriz(ByVal A(,) As String, 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} {1} ", A(fila, col), vbTab)
Next
Console.WriteLine()
Next
End Sub

Sub GrabarMatriz(NombreArchivo As String, ByVal A(,) As String, ByVal nf As


Integer, ByVal nc As Integer)
Dim archivo As StreamWriter
archivo = New StreamWriter(NombreArchivo)
Dim fila, col As Integer
For fila = 0 To nf - 1
For col = 0 To nc - 1
archivo.Write("{0} {1} ", A(fila, col), vbTab)
Next
archivo.WriteLine()
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -987-
Next
archivo.Close()
End Sub
Sub RecuperarMatriz(ByVal nombrearchivo As String, ByRef A(,) As String, 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) = subcadena
inicio = pos + 1
Next
Next
Console.WriteLine("Archivo leido satisfactoriamente")
srLector.Close()
End Sub
End Module

Module Module1
Dim cadena As String = "ABCEFG"
Sub main()
Dim fila, col, posletra As Integer
RecuperarMatriz(NombreArchivoObjetos, Objetos, NfObjetos, NcObjetos)
MostrarMatriz(Objetos, NfObjetos, NcObjetos)
RecuperarMatriz(NombreArchivo, A, Nfilas, Ncol) ' recupera la matriz A
' MostrarMatriz(A, Nfilas, Ncol)
' For fila = 0 To NfObjetos - 1
Dim sumaX, sumaY As Single
Dim npuntos As Integer
For fila = 0 To 0
sumaX = 0
sumaY = 0
npuntos = Len(cadena)
Console.WriteLine("datos de la fila {0} ={1}", fila, Objetos(fila, 2))
cadena = Objetos(fila, 2)
For col = 0 To npuntos - 1
' Console.WriteLine("{0}", cadena(col))
posletra = BuscarCadena(A, Nfilas, cadena(col))
Console.WriteLine("posletra {0}", posletra)
Console.WriteLine("datos de la fila {0}", posletra)
If posletra >= 0 Then
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -988-
sumaX = sumaX + A(posletra, 1)
sumaY = sumaY + A(posletra, 2)
End If
Next
Console.WriteLine("suma x {0} ", sumaX / npuntos)
Console.WriteLine("suma Y {0} ", sumaY / npuntos)
Next
Console.ReadLine()
End Sub
End Module

CODIGO DEL FORMULARIO

Imports System.Drawing
Public Class Form1
Dim grafico As Graphics
Dim lapiz1 As Pen
Dim lapiz2 As Pen
Dim lapiz As Pen
Dim ex As Single = 40
Dim ey As Single = 40
Dim brocha1 As SolidBrush
Dim brocha2 As SolidBrush
Dim brocha3 As SolidBrush

Dim brocha As SolidBrush


Dim MiFuente As New Font("Verdana", AltoLetra, FontStyle.Bold)
Dim PosFila As Integer
Dim PosCol As Integer
Sub ProcesarFila(A(,) As String, nf As Integer, nc As Integer, FilaNro As Integer,
color1 As Integer)
Dim x1, y1, ancho, alto As Single
Dim tipo As String
Dim Nro As Integer
Nro = CInt(A(FilaNro, 0))
x1 = CSng(A(FilaNro, 1))
y1 = CSng(A(FilaNro, 2))
ancho = CSng(A(FilaNro, 3))
alto = CSng(A(FilaNro, 4))
Select Case color1
Case 0
lapiz = lapiz1
brocha = brocha1
Case 1
lapiz = lapiz2
brocha = brocha2
End Select
tipo = A(FilaNro, 5)
Select Case Trim(tipo)
Case "PARED"
grafico.FillRectangle(brocha, x1 * ex, y1 * ey, ancho * ex, alto * ey)
Case "V1"
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -989-
grafico.DrawRectangle(lapiz, x1 * ex, y1 * ey, ancho * ex, alto * ey)
grafico.DrawRectangle(lapiz, x1 * ex, y1 * ey + alto * ey / 3, ancho * ex, alto * ey / 4)
Case "V2"
grafico.DrawRectangle(lapiz, x1 * ex, y1 * ey, ancho * ex, alto * ey)
grafico.DrawRectangle(lapiz, x1 * ex + ancho * ex / 3, y1 * ey, ancho * ex / 4,
alto * ey)
End Select
End Sub

Private Sub Procesar1(sender As Object, e As EventArgs) Handles btnProcesar.Click


grafico.Clear(Color.Black)
' For fila = 0 To maxfilas - 1
For fila = 0 To 27
ProcesarFila(A, Nfilas, Ncol, fila, Color1)
Next
End Sub

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load


grafico = PictureBox1.CreateGraphics
lapiz = New Pen(Brushes.Green, 1)
lapiz1 = New Pen(Brushes.Blue, 1)
lapiz2 = New Pen(Brushes.Red, 1)
brocha = New SolidBrush(Color.Green)
brocha1 = New SolidBrush(Color.Blue)
brocha2 = New SolidBrush(Color.Red)
brocha3 = New SolidBrush(Color.Yellow)
End Sub
Sub MostrarCuadricula(A(,) As String, nf As Integer, nc As Integer)
Dim fila, col As Integer
DataGridView1.RowCount = nf + 1
DataGridView1.ColumnCount = nc
DataGridView1.Columns(0).HeaderText = "Nro"
DataGridView1.Columns(1).HeaderText = "X"
DataGridView1.Columns(2).HeaderText = "Y"
DataGridView1.Columns(3).HeaderText = "Ancho"
DataGridView1.Columns(4).HeaderText = "Alto"
DataGridView1.Columns(5).HeaderText = "Tipo"
DataGridView1.Columns(6).HeaderText = "Titulo"
For col = 0 To nc - 1
DataGridView1.Columns(col).Width = 60
Next
For fila = 0 To nf - 1
DataGridView1.Rows(fila).HeaderCell.Value = fila.ToString
Next
For fila = 0 To nf - 1
For col = 0 To nc - 1
DataGridView1.Rows(fila).Cells(col).Value = A(fila, col)
Next
Next
' DataGridView1.Refresh()
End Sub
Sub ModificarMatrizdeCuadricula(A(,) As String, nf As Integer, nc As Integer)
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -990-
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
' DataGridView1.Refresh()
End Sub

Private Sub BtnAbrir_Click(sender As Object, e As EventArgs) Handles BtnAbrir.Click


RecuperarMatriz(NombreArchivo, A, Nfilas, Ncol)
MostrarCuadricula(A, Nfilas, Ncol)
End Sub

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


btnModificar.Click
grafico.Clear(Color.Black)
ModificarMatrizdeCuadricula(A, Nfilas, Ncol)
ProcesarFila(A, Nfilas, Ncol, PosFila, Color1)

End Sub

Private Sub DataGridView1_CellContentClick(sender As Object, e As


Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellClick
PosFila = DataGridView1.CurrentCell.RowIndex
PosCol = DataGridView1.CurrentCell.ColumnIndex
txtFila.Text = PosFila
txtCol.Text = PosCol
txtValor.Text = DataGridView1.Rows(PosFila).Cells(PosCol).Value
ListBox1.Items.Clear()
ListBox1.Items.Add("Nro= " & A(PosFila, 0))

ListBox1.Items.Add(" X = " & A(PosFila, 1))


ListBox1.Items.Add("Y = " & A(PosFila, 2))
ListBox1.Items.Add(" ANCHO = " & A(PosFila, 3))
ListBox1.Items.Add(" ALTO = " & A(PosFila, 4))
ListBox1.Items.Add(" TIPO = " & A(PosFila, 5))
ListBox1.Items.Add(" TITULO = " & A(PosFila, 5))

ProcesarFila(A, Nfilas, Ncol, PosFila, 1)


End Sub
Private Sub BtnBorrar_Click(sender As Object, e As EventArgs) Handles
BtnBorrar.Click
grafico.Clear(Color.Black)
End Sub

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


btnGrabar.Click
GrabarMatriz(NombreArchivoSalida, A, Nfilas, Ncol)
End Sub
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -991-
Private Sub btnPonerTitulo_Click(sender As Object, e As EventArgs) Handles
btnPonerTitulo.Click
Dim Titulo As String
Dim fila As Integer
Dim x1, y1, ancho, alto As Single
For fila = 0 To 29
x1 = CSng(A(fila, 1))
y1 = CSng(A(fila, 2))
ancho = CSng(A(fila, 3))
alto = CSng(A(fila, 4))
Titulo = A(fila, 6)
grafico.DrawString(Titulo, MiFuente, brocha3, x1 * ex + ancho * ex / 2, y1 * ey +
alto * ey / 2 - AltoLetra)
Next
End Sub
Sub MostrarObjetos(Objetos(,) As String, nc As Integer, nroobjeto As Integer, ByRef
Px As Single, ByRef py As Single)
Dim Cadena1, letra As String
Dim col As Integer
Dim sumaX, sumaY, sAncho, sAlto As Single
Dim npuntos, posletra As Integer
Dim pancho, palto As Single
ListBox1.Items.Clear()
sumaX = 0
sumaY = 0
sAncho = 0
sAlto = 0
Cadena1 = Objetos(nroobjeto, 2)
npuntos = Len(Cadena1)
For col = 0 To npuntos - 1
letra = Cadena1(col)
posletra = BuscarCadena(A, Nfilas, letra)
If posletra >= 0 Then
sumaX = sumaX + A(posletra, 1)
sumaY = sumaY + A(posletra, 2)
sAncho = sAncho + A(posletra, 3)
sAlto = sAlto + A(posletra, 4)
End If
Next
pancho = sAncho / npuntos
palto = sAlto / npuntos
Px = sumaX / npuntos + pancho - pancho
py = sumaY / npuntos + palto - palto / 2
ListBox1.Items.Add("suma x " & Px)
ListBox1.Items.Add("suma Y " & py)
End Sub
Private Sub btnAbrirObjetos_Click(sender As Object, e As EventArgs) Handles
btnAbrirObjetos.Click
Dim fila, col As Integer
RecuperarMatriz(NombreArchivoObjetos, Objetos, NfObjetos, NcObjetos)
MostrarMatriz(Objetos, NfObjetos, NcObjetos)
DataGridView2.RowCount = NfObjetos + 1
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -992-
DataGridView2.ColumnCount = NcObjetos
DataGridView2.Columns(0).HeaderText = "Nro"
DataGridView2.Columns(1).HeaderText = "SIMBOLO"
DataGridView2.Columns(2).HeaderText = "COMPONENTES"
DataGridView2.Columns(3).HeaderText = "NOMBRE"
For col = 0 To NcObjetos - 1
DataGridView2.Columns(col).Width = 60
Next
For fila = 0 To NfObjetos - 1
DataGridView2.Rows(fila).HeaderCell.Value = fila.ToString
Next
For fila = 0 To NfObjetos - 1
For col = 0 To NcObjetos - 1
DataGridView2.Rows(fila).Cells(col).Value = Objetos(fila, col)
Next
Next
RecuperarMatriz(NombreArchivo, A, Nfilas, Ncol) ' recupera la matriz A
End Sub

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


btnMostrarObjeto.Click
Dim titulo As String
Dim fila As Integer = 0
Dim posfila1, poscol1 As Single
For fila = 0 To NfObjetos - 1
MostrarObjetos(Objetos, NcObjetos, fila, posfila1, poscol1)
titulo = Objetos(fila, 3)
grafico.DrawString(titulo, MiFuente, brocha3, posfila1 * ex, poscol1 * ey)
Next
End Sub
End Class

10.30 TRANSPARENCIAS( Juntarlo con el problema del avion)

En la sigueinte aplicacion se puede puede mover el objeto trnsaparente.

Hacer modelos de trnsaparencia devidreo


Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -993-

Public Class Form1


Public px As Integer = 100
Public py As Integer = 100
Public ancho As Integer = 200
Public alto As Integer = 120
Public alfa As Integer = 120
Public rojo As Integer = 120
Public verde As Integer = 120
Public azul As Integer = 120
Public brocharoja As SolidBrush
Public brochaverde As SolidBrush
Public brochaazul As SolidBrush
Public brocha As SolidBrush
Public grafico As Graphics
Public grafico2 As Graphics
Public Pict1 As Bitmap
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
grafico = PictureBox1.CreateGraphics
grafico2 = PictureBox2.CreateGraphics
brocha = New Drawing.SolidBrush(Drawing.Color.Blue)
brocharoja = New Drawing.SolidBrush(Drawing.Color.Red)
brochaverde = New Drawing.SolidBrush(Drawing.Color.Green)
brochaazul = New Drawing.SolidBrush(Drawing.Color.Blue)
End Sub

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


btnIniciar.Click
PictureBox1.Refresh()
alfa = txtAlfa.Text
rojo = txtRojo.Text
verde = txtVerde.Text
azul = txtAzul.Text
px = txtCx.Text
py = txtCy.Text
ancho = txtAncho.Text
alto = txtAlto.Text
brocha.Color = Color.FromArgb(alfa, rojo, verde, azul)
grafico.FillEllipse(brocha, px, py, ancho, alto)
End Sub
Private Sub HSalfa_Scroll(sender As Object, e As ScrollEventArgs) Handles
HSalfa.Scroll
txtAlfa.Text = HSalfa.Value
btnIniciar_Click(sender, e)
End Sub
Private Sub HSrojo_Scroll(sender As Object, e As ScrollEventArgs) Handles
HSrojo.Scroll
txtRojo.Text = HSrojo.Value
End Sub
Private Sub HSverde_Scroll(sender As Object, e As ScrollEventArgs) Handles
HSverde.Scroll
txtVerde.Text = HSverde.Value
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -994-
End Sub
Private Sub HSAzul_Scroll(sender As Object, e As ScrollEventArgs) Handles
HSAzul.Scroll
txtAzul.Text = HSAzul.Value
End Sub
Private Sub HSCx_Scroll(sender As Object, e As ScrollEventArgs) Handles
HSCx.Scroll
txtCx.Text = HSCx.Value
End Sub
Private Sub HSCy_Scroll(sender As Object, e As ScrollEventArgs) Handles
HSCy.Scroll
txtCy.Text = HSCy.Value
End Sub
Private Sub HSAncho_Scroll(sender As Object, e As ScrollEventArgs) Handles
HSAncho.Scroll
txtAncho.Text = HSAncho.Value
End Sub
Private Sub HSAlto_Scroll(sender As Object, e As ScrollEventArgs) Handles
HSAlto.Scroll
txtAlto.Text = HSAlto.Value
End Sub
Private Sub txtMover_KeyDown(sender As Object, e As KeyEventArgs) Handles
txtMover.KeyDown
btnIniciar_Click(sender, e)
Select Case e.KeyCode
Case Keys.Left
If px > 0 Then px = px - 1
txtCx.Text = px
Case Keys.Right
If px < 555 Then px = px + 1
txtCx.Text = px
Case Keys.Up
If py > 0 Then py = py - 1
txtCy.Text = py
Case Keys.Down
If py < 555 Then py = py + 1
txtCy.Text = py
End Select
btnIniciar_Click(sender, e)
End Sub
Private Sub btPrueba_Click(sender As Object, e As EventArgs) Handles
btPrueba.Click
alfa = txtAlfa.Text
brocharoja.Color = Color.FromArgb(255, 255, 0, 0)
brochaverde.Color = Color.FromArgb(alfa, 0, 255, 0)
brochaazul.Color = Color.FromArgb(alfa / 2, 0, 0, 255)
grafico2.FillEllipse(brocharoja, 50, 50, 200, 150)
grafico2.FillEllipse(brochaverde, 150, 50, 200, 150)
grafico2.FillEllipse(brochaazul, 100, 100, 200, 150)
End Sub
End Class
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -995-
10.31 JUEGO DE LA VIDA DE CONWAY en modo formulario , se permite cambiar
parámetros

0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0
0 1 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 1 1 0 0 0 0 0 0 0 0 1 0 0 0 1 0 1 1 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -996-

Tiene los siguientes menus

El diseño del formulario es


Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -997-

CODIGO DEL FORMULARIO

Imports System.Drawing
Public Class form1

Sub VerPantallaGrafica(cx As Integer, cy As Integer, ByVal A(,) As Integer, ByVal nf


As Integer, ByVal nc As Integer, ex As Single, ey As Single)
Dim fila, col As Integer
For fila = 0 To nf - 1
For col = 0 To nc - 1
Select Case A(fila, col)
Case 0
grafico.FillRectangle(brochamuerte, cx + col * ex, cy + fila * ey, ex, ey)
Case 1
If forma = 1 Then
grafico.FillRectangle(brochavida, cx + col * ex, cy + fila * ey, ex, ey)
Else
grafico.FillEllipse(brochavida, cx + col * ex, cy + fila * ey, ex, ey)
End If

End Select
grafico.DrawRectangle(pluma, cx + col * ex, cy + fila * ey, ex, ey)
Next
Next
End Sub

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


BtnIniciar.Click
cont = 0
txtContGeneracion.Text = cont
End Sub
Private Sub FrmVida_Load(sender As Object, e As EventArgs) Handles
MyBase.Load
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -998-
grafico = PictureBox1.CreateGraphics()
brochavida = New SolidBrush(Color.Yellow)
brochamuerte = New SolidBrush(Color.Blue)
pluma = New Pen(Brushes.Red, 1)
Timer1.Enabled = False
End Sub

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


BtnJugar.Click
JuegoVida(A, B, nf, nc)
VerPantallaGrafica(cx, cy, A, nf, nc, ex, ey)
cont = cont + 1
txtContGeneracion.Text = cont
End Sub
Private Sub btnAuto_Click(sender As Object, e As EventArgs) Handles btnAuto.Click
Timer1.Interval = velocidad
Timer1.Start()
End Sub

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


btnDetener.Click
Timer1.Stop()
End Sub

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick


BtnJugar_Click(sender, e)
End Sub

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


MnuAbrir.Click
RecuperarMatriz(NombreArchivo, Modelo, nf, nc)
CopiarMatriz(Modelo, A, nc, nf)
VerPantallaGrafica(cx, cy, A, nf, nc, ex, ey)
End Sub

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


MnuColorVida.Click
ColorDialog1.ShowDialog()
brochavida.Color = ColorDialog1.Color
VerPantallaGrafica(cx, cy, A, nf, nc, ex, ey)
End Sub

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


ColorMuerte.Click
ColorDialog1.ShowDialog()
brochamuerte.Color = ColorDialog1.Color
VerPantallaGrafica(cx, cy, A, nf, nc, ex, ey)
End Sub

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


MnuColorLinea.Click
ColorDialog1.ShowDialog()
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -999-
pluma.Color = ColorDialog1.Color
VerPantallaGrafica(cx, cy, A, nf, nc, ex, ey)
End Sub

Private Sub MnuEx_Click(sender As Object, e As EventArgs) Handles MnuEx.Click


ex = InputBox("Ingreseex", "Ex", 1)
VerPantallaGrafica(cx, cy, A, nf, nc, ex, ey)
End Sub

Private Sub MnuEy_Click(sender As Object, e As EventArgs) Handles MnuEy.Click


ey = InputBox("Ingrese Ey", "Ey", 1)
VerPantallaGrafica(cx, cy, A, nf, nc, ex, ey)
End Sub

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


btnBorrar.Click
grafico.Clear(brochamuerte.Color)
End Sub

Private Sub VelocidadToolStripMenuItem_Click(sender As Object, e As EventArgs)


Handles MnuVelocidad.Click
velocidad = InputBox("Ingrese Velocidad", "Velocidad", 10)
VerPantallaGrafica(cx, cy, A, nf, nc, ex, ey)
End Sub

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


MnuForma.Click
forma = InputBox("Ingrese Forma 1 rectangulo 2 elipse ", "forma", 1)
VerPantallaGrafica(cx, cy, A, nf, nc, ex, ey)
End Sub
End Class

CODIGO DEL MODULO 1

'******************modulo 1
Module Module1
Sub Main()
Console.WriteLine("juego de la vida de wonway")
Console.WriteLine("Diseño escenarioen Excel y grabe archivo con bloque de
notas ")
Console.WriteLine("juego de la vida de Connway")
RecuperarMatriz(NombreArchivo, Modelo, nf, nc)
CopiarMatriz(Modelo, A, nc, nf)
VerPantalla(10, 4, A, nf, nc)
Console.ReadLine()
While (1)
'For i = 0 To ng
JuegoVida(A, B, nf, nc)
VerPantalla(10, 4, A, nf, nc)
'System.Threading.Thread.Sleep(10) ' 1 segundo
'Next
End While
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -1000-
Console.ReadLine()
End Sub
End Module

CODIGO DEL MODULO 2

'**************** modulo 2
Imports System.IO
Module Module2
Public NombreArchivo As String = "E:\datos\modelo40x30.txt"
Public Const maxfilas As Integer = 30
Public Const maxcol As Integer = 40
Public srLector As StreamReader
Public forma As Integer = 1
Public A(maxfilas, maxcol) As Integer
Public B(maxfilas, maxcol) As Integer
Public Modelo(maxfilas, maxcol) As Integer
Public nf As Integer = 40
Public nc As Integer = 40
Public ng As Integer = 200
Public pluma As Pen
Public grafico As Graphics
Public brochamuerte As SolidBrush
Public brochavida As SolidBrush
Public ex As Single = 14
Public ey As Single = 14
Public cx As Integer = 10
Public cy As Integer = 10
Public cont As Integer = 0
Public velocidad As Integer = 10

Function ContarLetra(Cadena As String, letra As Char)


Dim LARGO As Integer = Len(Cadena)
Dim cont, cant As Integer
For cont = 0 To LARGO - 1
If Cadena(cont) = letra Then
cant = cant + 1
End If
Next
Return cant
End Function

Sub RecuperarMatriz(ByVal nombrearchivo As String, ByRef A(,) As Integer, ByRef


nf As Integer, ByRef 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
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -1001-
cadena = srLector.ReadLine()
nc = ContarLetra(cadena, vbTab)
Do While Not (cadena = "")
cadena = cadena & vbTab
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
Console.WriteLine("Archivo leido satisfactoriamente")
srLector.Close()
End Sub
Sub VerPantalla(cx As Integer, cy As Integer, ByVal 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
Console.SetCursorPosition(cx + col, cy + fila)
If (A(fila, col) > 0) Then
Console.Write("*")
Else
Console.Write(" ")
End If
Next
Next
End Sub

Sub MostrarMatriz(A(,) As Integer, nf As Integer, nc As Integer)


Dim fila, col As Integer
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
Sub CopiarMatriz(ByVal A(,) As Integer, B(,) As Integer, ByVal ancho As Integer,
ByVal alto 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
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -1002-
Sub JuegoVida(ByVal A(,) As Integer, B(,) As Integer, ByVal nf As Integer, ByVal nc
As Integer)
Dim fila, col, vecinos, x1, y1, x2, y2, fila1, col1 As Integer
For fila = 0 To nf - 1
For col = 0 To nc - 1
vecinos = 0
If fila > 0 Then
y1 = fila - 1
Else
y1 = fila
End If
If fila < nf - 2 Then
y2 = fila + 1
Else
y2 = fila
End If
If col > 0 Then
x1 = col - 1
Else
x1 = col
End If
If col < nc - 2 Then
x2 = col + 1
Else
x2 = col
End If
For fila1 = y1 To y2
For col1 = x1 To x2
If (fila1 = fila And col1 = col) Then Continue For
If A(fila1, col1) = 1 Then vecinos = vecinos + 1
Next
Next
Select Case vecinos
Case 0
B(fila, col) = 0
Case 1
B(fila, col) = 0
Case 2
B(fila, col) = A(fila, col)
Case 3
B(fila, col) = 1
Case Else
B(fila, col) = 0
End Select
Next
Next
'Console.Clear()
CopiarMatriz(B, A, nf, nc)
End Sub
End Module
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -1003-
10.31 La construcción de un brazo Robot articulado. PASA A GRAFICOS

Esta sección analiza un programa que crea un brazo robot articulado con dos o más
segmentos. El brazo debe estar conectado con puntos de giro en el hombro, codo u otras
articulaciones. La Figura muestra un único conjunto de tal brazo.

Figura.

Puede utilizar un cubo escalado como un segmento del brazo robot, pero primero debe
llamar a las transformaciones de modelado adecuado para orientar a cada segmento.
Dado que el origen del sistema de coordenadas local está inicialmente en el centro del
cubo, necesita mover el sistema de coordenadas local a un borde del cubo. De lo
contrario, el cubo rota sobre su centro en lugar de hacerlo en el punto de giro.

Teclas H e I para mover el hombro


Teclas B C para mover el brazo

Imports System.Drawing.Drawing2D
Public Class Form1
Dim Grafico As Graphics
Dim pen1 As Pen
Dim pen2 As Pen
Dim brocha1 As SolidBrush
Dim brocha2 As SolidBrush

Dim Cx As Integer = 200


Dim Cy As Integer = 200
Dim Ancho1 As Integer = 140
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -1004-
Dim Alto1 As Integer = 50
Dim Ancho2 As Integer = 100
Dim Alto2 As Integer = 40
Dim RotH As Single = 0
Dim RotCodo As Single = 0
Dim pasoH As Single = 10
Dim pasoB As Single = 10
Private Sub btnGraficar_Click(sender As Object, e As EventArgs) Handles
btnGraficar.Click
Grafico.Clear(Color.Black)
Grafico.ResetTransform()
Grafico.TranslateTransform(Cx, Cy)
Grafico.RotateTransform(RotH)
Grafico.FillRectangle(brocha1, 0, 0, Ancho1, Alto1)

Grafico.DrawRectangle(pen1, 0, 0, Ancho1, Alto1)


Grafico.TranslateTransform(Ancho1, Alto1 / 2)
Grafico.RotateTransform(RotCodo)
Grafico.FillRectangle(brocha2, 0, 0, Ancho2, Alto2)

Grafico.DrawRectangle(pen2, 0, 0, Ancho2, Alto2)


txtRHombro.Text = RotH
txtRBrazo.Text = RotCodo
End Sub

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load


Grafico = PictureBox1.CreateGraphics
pen1 = New Pen(Brushes.Red, 3)
pen2 = New Pen(Brushes.Green, 3)
brocha1 = New SolidBrush(color.blue)
brocha2 = New SolidBrush(Color.Gray)
End Sub

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


KeyEventArgs) Handles txtHC.KeyDown
Grafico.ResetTransform()
Select Case e.KeyCode
Case Keys.H
If RotH < 360 Then RotH = RotH + pasoH
Case Keys.I
If RotH > -360 Then RotH = RotH - pasoH
Case Keys.B
If RotCodo < 360 Then RotCodo = RotCodo + pasoB
Case Keys.C
If RotCodo > -360 Then RotCodo = RotCodo - pasoB
End Select
HScrollBar1.Value = RotH
HScrollBar2.Value = RotCodo
txtHSB.Text = RotH
txtHSC.Text = RotCodo
btnGraficar_Click(sender, e)
txtHC.Text = ""
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -1005-
End Sub
Private Sub HScrollBar1_Scroll(ByVal sender As System.Object, ByVal e As
System.Windows.Forms.ScrollEventArgs) Handles HScrollBar1.Scroll
RotH = HScrollBar1.Value
txtHSB.Text = RotH
btnGraficar_Click(sender, e)
End Sub

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


System.Windows.Forms.ScrollEventArgs) Handles HScrollBar2.Scroll
RotCodo = HScrollBar2.Value
txtHSC.Text = RotCodo
btnGraficar_Click(sender, e)
End Sub
End Class

10.33 Problema de objetos usando arreglos(tarea)

Propiedad RotZ Tx Ty Ex Ey CentroX CentroY Ancho Alto Transparencias Rojo


Objeto1 0 490 200 2 1 0 0 200 120 123
Objeto2 0 300 200 2 2 0 0 100 50 123
Objeto3 0 200 200 2 2 0 0 40 80 129 2

'****************************codigo del formulario


Imports System.Drawing
Imports System.Drawing.Drawing2D
Public Class Form1
Sub iniciarTodo()
DataGridView1.RowCount = 5
DataGridView1.ColumnCount = nc
DataGridView1.Columns(0).HeaderText = "Propiedad"
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -1006-

DataGridView1.Columns(1).HeaderText = "RotZ"
DataGridView1.Columns(2).HeaderText = "Tx"
DataGridView1.Columns(3).HeaderText = "Ty"
DataGridView1.Columns(4).HeaderText = "Ex"
DataGridView1.Columns(5).HeaderText = "Ey"

DataGridView1.Columns(6).HeaderText = "CentroX"
DataGridView1.Columns(7).HeaderText = "CentroY"
DataGridView1.Columns(8).HeaderText = "Ancho"
DataGridView1.Columns(9).HeaderText = "Alto"
DataGridView1.Columns(10).HeaderText = "Transparencia"
DataGridView1.Columns(11).HeaderText = "Rojo"
DataGridView1.Columns(12).HeaderText = "Verde"
DataGridView1.Columns(13).HeaderText = "Azul"
DataGridView1.Columns(14).HeaderText = "Paso"
For i = 1 To nc - 1
DataGridView1.Columns(i).Width = 50
Next
For i = 0 To nfilas - 1
DataGridView1.Rows(i).HeaderCell.Value = i.ToString
Next
End Sub
Sub Obtener(nfila As Integer)
Rotz = DataGridView1.Rows(nfila).Cells(1).Value
tx = DataGridView1.Rows(nfila).Cells(2).Value
ty = DataGridView1.Rows(nfila).Cells(3).Value
Ex = DataGridView1.Rows(nfila).Cells(4).Value
Ey = DataGridView1.Rows(nfila).Cells(5).Value

CentroX = DataGridView1.Rows(nfila).Cells(6).Value
CentroY = DataGridView1.Rows(nfila).Cells(7).Value
ancho = DataGridView1.Rows(nfila).Cells(8).Value
alto = DataGridView1.Rows(nfila).Cells(9).Value
Transparencia = DataGridView1.Rows(nfila).Cells(10).Value
rojo = DataGridView1.Rows(nfila).Cells(11).Value
verde = DataGridView1.Rows(nfila).Cells(12).Value
azul = DataGridView1.Rows(nfila).Cells(13).Value
paso = DataGridView1.Rows(nfila).Cells(14).Value
End Sub
Sub Figura(centrox As Single, centroy As Single, ancho As Single, alto As Single,
brocha As SolidBrush)
grafico.FillEllipse(brocha, centrox - (ancho / 2), centroy - (alto / 2), ancho, alto)
grafico.DrawEllipse(pluma, centrox - (ancho / 2), centroy - (alto / 2), ancho, alto)
End Sub
Sub coordenadas(centrox As Single, centroy As Single, ancho As Single, alto As
Single)
grafico.DrawLine(Pens.Blue, centrox - ancho / 2, centroy, centrox + ancho / 2,
centroy)
grafico.DrawLine(Pens.Blue, centrox, centroy - alto / 2, centrox, centroy + alto / 2)
End Sub
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -1007-
Sub GraficarFigura(centrox As Single, centroy As Single, ancho As Single, alto As
Single, brocha1 As SolidBrush)
' brocha.Color = Color.Yellow
Figura(centrox, centroy, ancho, alto, brocha1)
' la nariz
brocha.Color = Color.Orange
Figura(centrox, centroy - alto * 0.16, ancho * 0.16, alto * 0.14, brocha)
' mas los ojos
brocha.Color = Color.White
Figura(centrox - ancho * 0.12, centroy - alto * 0.43, ancho * 0.16, alto * 0.43,
brocha)
Figura(centrox + ancho * 0.12, centroy - alto * 0.43, ancho * 0.16, alto * 0.43,
brocha)
brocha.Color = Color.Blue
Figura(centrox - ancho * 0.12, centroy - alto * 0.43, ancho * 0.08, alto * 0.2,
brocha)
Figura(centrox + ancho * 0.12, centroy - alto * 0.43, ancho * 0.08, alto * 0.2,
brocha)
brocha.Color = Color.Black
Figura(centrox - ancho * 0.12, centroy - alto * 0.43, ancho * 0.04, alto * 0.1,
brocha)
Figura(centrox + ancho * 0.12, centroy - alto * 0.43, ancho * 0.04, alto * 0.1,
brocha)
' coordenadas(CentroX, CentroY, ancho, alto)
Dim x1, y1, x2, y2 As Integer
x1 = CInt(centrox - ancho * 0.4)
y1 = CInt(centroy - alto * 0.2)
x2 = CInt(ancho * 0.8)
y2 = CInt(alto * 0.4)
Dim Trayecto1 As New GraphicsPath()
Trayecto1.AddArc(x1, y1, x2, y2, 0, 180)
x1 = CInt(centrox - ancho * 0.3)
y1 = CInt(centroy - alto * 0.3)
x2 = CInt(ancho * 0.6)
y2 = CInt(alto * 0.6)
Dim Trayecto2 As New GraphicsPath()
Trayecto2.AddArc(x1, y1, x2, y2, 0, 180)
Dim Región1 As New Region(Trayecto1) 'Creamos un objeto Region
Dim Región2 As New Region(Trayecto2) 'Creamos un objeto Region
Región2.Exclude(Región1)
grafico.FillRegion(brocha, Región2)
grafico.DrawPath(pluma, Trayecto1)
grafico.DrawPath(pluma, Trayecto2)
Trayecto1.Dispose()
Trayecto2.Dispose()
End Sub

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load


Dim fila As Integer
grafico = PictureBox1.CreateGraphics
pluma = New Pen(Brushes.Red)
brocha = New SolidBrush(Color.Bisque)
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -1008-
brocha1 = New SolidBrush(Color.Green)
iniciarTodo()
For fila = 0 To nfilas - 1
ComboBox1.Items.Add(fila)
Next
ComboBox1.Text = 0
nrofila = ComboBox1.Text
End Sub
Private Sub btnBorrar_Click(sender As Object, e As EventArgs) Handles
btnBorrar.Click
grafico.Clear(Color.Black)
End Sub

Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs)


Handles ComboBox1.SelectedIndexChanged
nrofila = ComboBox1.Text
End Sub
Sub graficarfigura(nrofila As Integer, Rotz As Single, tx As Single, ty As Single, ex As
Single, ey As Single)
grafico.ResetTransform()
grafico.TranslateTransform(tx, ty)
grafico.RotateTransform(Rotz)
grafico.ScaleTransform(ex, ey)
brocha1.Color = Color.FromArgb(Transparencia, rojo, verde, azul)
GraficarFigura(CentroX, CentroY, ancho, alto, brocha1)
End Sub

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


btnGraficar.Click
Obtener(nrofila)
GraficarFigura(nrofila, Rotz, tx, ty, Ex, Ey)
End Sub
Private Sub btnGraficarTodo_Click(sender As Object, e As EventArgs) Handles
btnGraficarTodo.Click
Dim fila As Integer
For fila = 0 To nfilas - 1
Obtener(fila)
GraficarFigura(fila, Rotz, tx, ty, Ex, Ey)
Next
End Sub

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


txtTraslacion.KeyDown
Try
' Dim transState As GraphicsState = grafico.Save()
nrofila = ComboBox1.Text
tx = DataGridView1.Rows(nrofila).Cells(2).Value
ty = DataGridView1.Rows(nrofila).Cells(3).Value
paso = DataGridView1.Rows(nrofila).Cells(14).Value
Select Case e.KeyCode
Case Keys.X, Keys.Right
tx = tx + paso
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -1009-
Case Keys.A, Keys.Left
tx = tx - paso
Case Keys.Y, Keys.Up
ty = ty + paso
Case Keys.B, Keys.Down
ty = ty - paso
End Select
DataGridView1.Rows(nrofila).Cells(2).Value = tx
DataGridView1.Rows(nrofila).Cells(3).Value = ty
grafico.Clear(Color.Black)
'grafico.Restore(transState)
btnGraficarTodo_Click(sender, e)
txtTraslacion.Text = ""
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Sub MostrarMatriz(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
DataGridView1.Rows(fila).Cells(col).Value = A(fila, col)
Next
Next
End Sub
Private Sub btnRecuperar_Click(sender As Object, e As EventArgs) Handles
btnRecuperar.Click
RecuperarMatriz(NombreArchivo, A, nfilas, nc)
MostrarMatriz(A, nfilas, nc)
End Sub
Sub ObtenerMatrizdeCuadricula(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) = DataGridView1.Rows(fila).Cells(col).Value
Next
Next
End Sub
Private Sub btnGrabar_Click(sender As Object, e As EventArgs) Handles
btnGrabar.Click
ObtenerMatrizdeCuadricula(A, nfilas, nc)
GrabarMatriz(NombreArchivo, A, nfilas, nc)
End Sub
Private Sub btnRestaurar_Click(sender As Object, e As EventArgs) Handles
btnRestaurar.Click
grafico.ResetTransform()
End Sub

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


TxtEscalado.KeyDown
' Dim transState As GraphicsState = grafico.Save()
nrofila = ComboBox1.Text
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -1010-
Ex = DataGridView1.Rows(nrofila).Cells(4).Value
Ey = DataGridView1.Rows(nrofila).Cells(5).Value
paso = DataGridView1.Rows(nrofila).Cells(14).Value
Select Case e.KeyCode
Case Keys.X, Keys.Right
Ex = Ex + paso
Case Keys.A, Keys.Left
Ex = Ex - paso
Case Keys.Y, Keys.Up
Ey = Ey + paso
Case Keys.B, Keys.Down
Ey = Ey - paso
End Select
DataGridView1.Rows(nrofila).Cells(4).Value = Ex
DataGridView1.Rows(nrofila).Cells(5).Value = Ey
grafico.Clear(Color.Black)
'grafico.Restore(transState)
btnGraficarTodo_Click(sender, e)
TxtEscalado.Text = ""
End Sub

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


txtRot.KeyDown
nrofila = ComboBox1.Text
Rotz = DataGridView1.Rows(nrofila).Cells(1).Value
paso = DataGridView1.Rows(nrofila).Cells(14).Value
Select Case e.KeyCode
Case Keys.Z, Keys.Right
Rotz = Rotz + paso
Case Keys.A, Keys.Left
Rotz = Rotz - paso
End Select
DataGridView1.Rows(nrofila).Cells(1).Value = Rotz
grafico.Clear(Color.Black)
btnGraficarTodo_Click(sender, e)
txtRot.Text = ""
End Sub

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


btnAleatorio.Click
Dim rfila, rcol As Integer
Dim valor, valor1, dato As Single
grafico.Clear(Color.Black)
rfila = Int(Rnd() * nfilas)
rcol = 1 + Int(Rnd() * 5)
dato = DataGridView1.Rows(rfila).Cells(14).Value
valor = DataGridView1.Rows(rfila).Cells(rcol).Value
valor1 = valor - dato + Rnd() * dato * 2
DataGridView1.Rows(rfila).Cells(rcol).Value = valor1
ComboBox1.Text = rfila
btnGraficarTodo_Click(sender, e)
End Sub
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -1011-

Private Sub BtnAuto_Click(sender As Object, e As EventArgs) Handles BtnAuto.Click


Timer1.Interval = 20
Timer1.Start()
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
btnAleatorio_Click(sender, e)
End Sub
Private Sub btndetener_Click(sender As Object, e As EventArgs) Handles
btndetener.Click
Timer1.Stop()
End Sub
Private Sub btnDuplicar_Click(sender As Object, e As EventArgs) Handles
btnDuplicar.Click
' Dim miform As New FRMGRAFICO
Dim fila, col, cont
Obtener(nrofila)
cont = 0
For fila = 1 To 5
For col = 1 To 5
GraficarFigura(nrofila, cont, col * 100, fila * 80, 0.3 + col * 0.03, 0.3 + fila * 0.03)
cont = cont + 10
Next
Next
End Sub
End Class

CODIGO DEL FORMULARIO

'*******************************
Imports System.IO
Module Module1
Public Rotz As Single
Public tx As Single
Public ty As Single
Public Ex As Single
Public Ey As Single

Public Const maxfilas As Integer = 10


Public Const maxcol As Integer = 14
Public A(maxfilas, maxcol) As String
Public grafico As Graphics
Public pluma As Pen
Public brocha As SolidBrush
Public brocha1 As SolidBrush
Public CentroX As Double = 0 ' 200
Public CentroY As Double = 0 ' 200
Public ancho As Double = 160
Public alto As Double = 80
Public nfilas As Integer = 3
Public nc As Integer = 15
Public rojo As Integer = 255
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -1012-
Public verde As Integer = 0
Public azul As Integer = 0
Public Transparencia As Integer = 120
Public nrofila As Integer = 0
Public paso As Single = 10
Public NombreArchivo As String = "E:\datos\objetos12.txt"
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 leido satisfactoriamente")
srLector.Close()
End Sub
Sub GrabarMatriz(ByVal nombrearchivo As String, ByRef A(,) As String, ByRef nf As
Integer, ByVal nc As Integer)
Dim srEscritor As StreamWriter
srEscritor = New StreamWriter(nombrearchivo)
Dim fila As Integer = 0, col As Integer
For fila = 0 To nf - 1
For col = 0 To nc - 1
srEscritor.Write(" {0} {1} ", A(fila, col), Chr(9))
Next
srEscritor.WriteLine()
Next
Console.WriteLine("Archivo grabado satisfactoriamente")
srEscritor.Close()
End Sub
End Module

10.34 APLICACIONES DE 3 COLORES(se observa la mezcla de colores


Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -1013-

'***** aplicacion tres colores


Imports System.Drawing
Public Class Form1
Inherits Form
Dim paso As Integer = 10
Dim grafico4 As Graphics
Dim Cx1 As Single = 40
Dim Cy1 As Single = 40
Dim Cx2 As Single = 60
Dim Cy2 As Single = 40
Dim Cx3 As Single = 50
Dim Cy3 As Single = 50
Dim radio As Integer = 30
Dim AnchoBitmaps As Integer = 120
Dim AltoBitmaps As Integer = 120
Dim brochaRoja As SolidBrush
Dim brochaverde As SolidBrush
Dim brochaAzul As SolidBrush

Sub Graficar(Cx1 As Integer, cy1 As Integer, Cx2 As Integer, cy2 As Integer, Cx3 As
Integer, cy3 As Integer)
Dim fila, col As Integer
Dim MapaBits1 As New Bitmap(AnchoBitmaps, AltoBitmaps)
Dim MapaBits2 As New Bitmap(AnchoBitmaps, AltoBitmaps)
Dim MapaBits3 As New Bitmap(AnchoBitmaps, AltoBitmaps)
Dim MapaBits4 As New Bitmap(AnchoBitmaps, AltoBitmaps)
Dim grafico1 As Graphics = Graphics.FromImage(MapaBits1)
Dim grafico2 As Graphics = Graphics.FromImage(MapaBits2)
Dim grafico3 As Graphics = Graphics.FromImage(MapaBits3)
Dim grafico4 As Graphics = Graphics.FromImage(MapaBits4)

grafico1.FillEllipse(brochaRoja, Cx1 - radio, cy1 - radio, radio * 2, radio * 2)


grafico2.FillEllipse(brochaverde, Cx2 - radio, cy2 - radio, radio * 2, radio * 2)
grafico3.FillEllipse(brochaAzul, Cx3 - radio, cy3 - radio, radio * 2, radio * 2)
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -1014-
Dim rojo1, verde1, azul1, rojo2, verde2, azul2, rojo3, verde3, azul3, rojo4, verde4,
azul4 As Integer
For fila = 0 To AltoBitmaps - 1
For col = 0 To AnchoBitmaps - 1
rojo1 = MapaBits1.GetPixel(fila, col).R
verde1 = MapaBits1.GetPixel(fila, col).G
azul1 = MapaBits1.GetPixel(fila, col).B

rojo2 = MapaBits2.GetPixel(fila, col).R


verde2 = MapaBits2.GetPixel(fila, col).G
azul2 = MapaBits2.GetPixel(fila, col).B

rojo3 = MapaBits3.GetPixel(fila, col).R


verde3 = MapaBits3.GetPixel(fila, col).G
azul3 = MapaBits3.GetPixel(fila, col).B

rojo4 = rojo1 + rojo2 + rojo3


verde4 = verde1 + verde2 + verde3
azul4 = azul1 + azul2 + azul3
Dim mayor = rojo4
If verde4 < mayor Then mayor = verde4
If azul4 < mayor Then mayor = azul4
If mayor > 0 Then
rojo4 = Int(255 * (rojo4 / mayor))
verde4 = Int(255 * (verde4 / mayor))
azul4 = Int(255 * (azul4 / mayor))
End If
MapaBits4.SetPixel(fila, col, Color.FromArgb(rojo4, verde4, azul4))
Next
Next
grafico4 = PictureBox1.CreateGraphics
' grafico2.DrawImage(MapaBits1, 1, 1)
'grafico2.DrawImage(MapaBits2, 1, 1)
'grafico2.DrawImage(MapaBits2, 1, 1)
'grafico5.DrawImage(MapaBits1, 1, 1)
grafico4.ScaleTransform(4, 4)
grafico4.DrawImage(MapaBits4, 0, 0)
grafico4.Dispose()
End Sub
Private Sub btnGraficar_Click(sender As Object, e As EventArgs) Handles
btnGraficar.Click
Graficar(Cx1, Cy1, Cx2, Cy2, Cx3, Cy3)
End Sub
Private Sub TxtRojo_KeyDown(sender As Object, e As KeyEventArgs) Handles
TxtRojo.KeyDown
Select Case e.KeyCode
Case Keys.X, Keys.Right
Cx1 = Cx1 + paso
Case Keys.A, Keys.Left
Cx1 = Cx1 - paso
Case Keys.Y, Keys.Up
Cy1 = Cy1 + paso
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -1015-
Case Keys.B, Keys.Down
Cy1 = Cy1 - paso
End Select
Graficar(Cx1, Cy1, Cx2, Cy2, Cx3, Cy3)
TxtRojo.Text = ""
End Sub
Private Sub TxtVerde_KeyDown(sender As Object, e As KeyEventArgs) Handles
TxtVerde.KeyDown
Select Case e.KeyCode
Case Keys.X, Keys.Right
Cx2 = Cx2 + paso
Case Keys.A, Keys.Left
Cx2 = Cx2 - paso
Case Keys.Y, Keys.Up
Cy2 = Cy2 + paso
Case Keys.B, Keys.Down
Cy2 = Cy2 - paso
End Select
Graficar(Cx1, Cy1, Cx2, Cy2, Cx3, Cy3)
TxtVerde.Text = ""
End Sub
Private Sub TxtAzul_KeyDown(sender As Object, e As KeyEventArgs) Handles
TxtAzul.KeyDown
Select Case e.KeyCode
Case Keys.X, Keys.Right
Cx3 = Cx3 + paso
Case Keys.A, Keys.Left
Cx3 = Cx3 - paso
Case Keys.Y, Keys.Up
Cy3 = Cy3 + paso
Case Keys.B, Keys.Down
Cy3 = Cy3 - paso
End Select
Graficar(Cx1, Cy1, Cx2, Cy2, Cx3, Cy3)
TxtAzul.Text = ""
End Sub

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load


brochaRoja = New SolidBrush(Color.FromArgb(255, 0, 0))
brochaverde = New SolidBrush(Color.FromArgb(0, 255, 0))
brochaAzul = New SolidBrush(Color.FromArgb(0, 0, 255))
End Sub
End Class

10.35 Iluminacion

con un foco ( el foco puede variar de color ,tamaño, el grado de oscuridad tambien
varia) en el ejemplo se ve con foco de color blaco
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -1016-

CODIGO DEL FORMULARIO

Imports System.Drawing
Public Class Form1
Inherits Form
Dim paso As Integer = 10
Dim dradio As Single = 1
Dim dfactor As Single = 0.1
Dim grafico1 As Graphics
Dim grafico2 As Graphics
Dim grafico3 As Graphics
Dim factorluz As Single = 0.5 ' 0.8 '
Dim Cx1 As Single = 20
Dim Cy1 As Single = 20
Dim radio As Integer = 30
Dim AnchoBitmaps As Integer = 183
Dim AltoBitmaps As Integer = 275
Dim brocha As SolidBrush
Sub Graficar(Cx1 As Integer, cy1 As Integer, Radio As Single, factorluz As Single)
Dim fila, col As Integer
Dim MapaBits2 As New Bitmap("E:\datos\UNSA2.jpg")
AnchoBitmaps = MapaBits2.Width
AltoBitmaps = MapaBits2.Height
Dim MapaBits1 As New Bitmap(AnchoBitmaps, AltoBitmaps)

Dim MapaBits3 As New Bitmap(AnchoBitmaps, AltoBitmaps)


Dim grafico1 As Graphics = Graphics.FromImage(MapaBits1)
Dim grafico2 As Graphics = Graphics.FromImage(MapaBits2)
Dim grafico3 As Graphics = Graphics.FromImage(MapaBits3)

grafico1.FillEllipse(brocha, Cx1 - Radio, cy1 - Radio, Radio * 2, Radio * 2)


Dim rojo1, verde1, azul1 As Integer ' son colores de la luz
Dim rojo2, verde2, azul2 As Integer ' son colores del objeto
Dim rojo3, verde3, azul3 As Integer ' el color mezclado
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -1017-

For fila = 0 To AltoBitmaps - 1


For col = 0 To AnchoBitmaps - 1
rojo1 = MapaBits1.GetPixel(col, fila).R
verde1 = MapaBits1.GetPixel(col, fila).G
azul1 = MapaBits1.GetPixel(col, fila).B
rojo2 = MapaBits2.GetPixel(col, fila).R
verde2 = MapaBits2.GetPixel(col, fila).G
azul2 = MapaBits2.GetPixel(col, fila).B
rojo3 = rojo2 * (rojo1 / 255) * factorluz + rojo2 * (1 - factorluz)
verde3 = verde2 * (verde1 / 255) * factorluz + verde2 * (1 - factorluz)
azul3 = azul2 * (azul1 / 255) * factorluz + azul3 * (1 - factorluz)
MapaBits3.SetPixel(col, fila, Color.FromArgb(rojo3, verde3, azul3))
Next
Next
grafico3 = PictureBox1.CreateGraphics
grafico3.ScaleTransform(2, 2)
grafico3.DrawImage(MapaBits3, 0, 0)
grafico3.Dispose()
End Sub
Private Sub btnGraficar_Click(sender As Object, e As EventArgs) Handles
btnGraficar.Click
Graficar(Cx1, Cy1, radio, factorluz)
End Sub
Private Sub Txtespla_KeyDown(sender As Object, e As KeyEventArgs) Handles
txtDezplazamiento.KeyDown
Select Case e.KeyCode
Case Keys.X, Keys.Right
Cx1 = Cx1 + paso
Case Keys.A, Keys.Left
Cx1 = Cx1 - paso
Case Keys.Y, Keys.Down
Cy1 = Cy1 + paso
Case Keys.B, Keys.Up
Cy1 = Cy1 - paso
End Select
Graficar(Cx1, Cy1, radio, factorluz)
txtDezplazamiento.Text = ""
End Sub
Private Sub TxtRadio_KeyDown(sender As Object, e As KeyEventArgs) Handles
Txtradio.KeyDown
Select Case e.KeyCode
Case Keys.X, Keys.Right
radio = radio + dradio
Case Keys.A, Keys.Left
radio = radio - dradio
End Select
Graficar(Cx1, Cy1, radio, factorluz)
Txtradio.Text = ""
End Sub
Private Sub TxtFactor_KeyDown(sender As Object, e As KeyEventArgs) Handles
TxtFactor.KeyDown
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -1018-
Select Case e.KeyCode
Case Keys.X, Keys.Right
If factorluz < 1 - dfactor Then
factorluz = factorluz + dfactor
End If
Case Keys.A, Keys.Left
If factorluz > dfactor Then
factorluz = factorluz - dfactor
End If
End Select
Graficar(Cx1, Cy1, radio, factorluz)
TxtFactor.Text = ""
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
brocha = New SolidBrush(Color.FromArgb(255, 255, 255))
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles
btnCargarColor.Click
ColorDialog1.ShowDialog()
brocha.Color = ColorDialog1.Color
btnCargarColor.BackColor = brocha.Color
Graficar(Cx1, Cy1, radio, factorluz)
End Sub
End Class

EJERCICIO DE BITMAPS

10.36 Procesamiento de Imágenes y aplicaciones Commented [A1]: HACER UNO SOLO

El siguiente Ejercicio permite detectar manchas en una superficie puede ser lana, tela,
papel, maquinas, etc., con algunas mejoras puede detectar firmas, huellas digitales,
reconocer rostros, figuras, etc.

El proyecto tiene la siguiente estructura


Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -1019-

Los botones del Formulario 1 son y realizan las siguientes acciones

Abrir. Permite seleccionar y abrir la foto tomada de la imagen a procesar (la foto
puede tener máximo 600x500 pixeles se puede aumentar más de acuerdo a la
capacidad de la computadora)

Procesar. Procesa los pixeles de la foto (en este caso es un bitmaps) obtiene los
colores rojo, verde, azul en tres matrices, también obtiene la matriz de grises y matriz
de blanco y negro que se usara para determinar la ubicación, tamaño y la cantidad de
las manchas.
Luego muestra el resultado en un cuadro de imagen con escalas Ex e dadas ósea
puede ser más grande o más pequeño, En este caso la escala es Ex=2 y EY = 2

Mostrar, Muestra el procesado en el paso anterior


Al realizar el evento mouse down en el PictureBox muestra s colores rojo, verde y azul
del cursor del Mouse del punto donde se hizo clic
Como se muestra en la figura

Borrar:- Borrar el grafico y el cuadro de lista2


Ver Gris.- Muestra la figura convertida en escala de grises
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -1020-

VerBN.- Muestra un formulario que contiene la figura convertida en blanco y negro de


acuerdo a un umbral dado que en este caso es 150

Figura blanco y negro a escala 2

Ver Rojo.- Ve el componente rojo de la figura en formulario como se muestra


Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -1021-
Ver Verde.- Ve el componente Verde de la figura en formulario

Ver Azul.- Ve el componente azul de la figura en formulario

Ver Todo.- Muestra los componentes rojo, verde y azul de la figura (o sea la figura
original)

Control Estadístico.- Muestra el tamaño y la ubicación de cada una de las manchas


como se muestra en la figura
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -1022-

Detectar borde.- detecta borde de la figura


Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -1023-
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -1024-

Las funciones usadas mas releveantes son

Function UbicarPunto(ByVal A(,) As Byte, ByVal nf As Integer, ByVal nc As Integer, _


ByRef px As Integer, ByRef py As Integer, ByVal valor As Integer) As Integer

Ubica en que columna y fila comienza la mancha

Sub ContarTamaño(ByVal A(,) As Byte, ByVal px As Integer, ByVal py As Integer,


ByVal valor As Integer)

Que cuenta cuantas pixeles forma la mancha en forma recursiva

CODIGO DEL FORMULARIO

Imports System.Drawing
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
txtEx.Text = ex
txtEy.Text = ey
txtLimite.Text = limite
Grafico = PictureBox2.CreateGraphics
brocha1 = New SolidBrush(Drawing.Color.Red)
End Sub
Sub MostrarMatriz(ByVal cx As Integer, ByVal cy 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 Rojo, Verde, Azul As Integer
For fila = 0 To nf - 1
For col = 0 To nc - 1
Rojo = Rojos(fila, col)
Verde = Verdes(fila, col)
Azul = Azules(fila, col)
brocha1.Color = Color.FromArgb(Rojo, Verde, Azul)
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -1025-
Grafico.FillRectangle(brocha1, cx + ex * col, cy + ey * fila, ex, ey)
Next
Next
End Sub
Private Sub BtnMostrar_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnMostrar.Click
ex = txtEx.Text
ey = txtEy.Text
limite = txtLimite.Text
MostrarMatriz(0, 0, nf, nc, ex, ey)
End Sub
Private Sub btnBorrar_Click(ByVal sender As Object, ByVal e As EventArgs) Handles
btnBorrar.Click
Grafico.Clear(Drawing.Color.Black)
ListBox2.Items.Clear()
End Sub
Private Sub btnProcesar_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnProcesar.Click
Dim fila, col As Integer
Dim gris As Byte
For fila = 0 To nf - 1
For col = 0 To nc - 1
Color1 = Pict1.GetPixel(col, fila)
Rojos(fila, col) = Color1.R
Verdes(fila, col) = Color1.G
Azules(fila, col) = Color1.B
gris = CByte(Color1.R * 0.33 + Color1.G * 0.33 + Color1.B * 0.33)
'If gris > 255 Then gris = 255
'If gris < 0 Then gris = 0
Grises(fila, col) = gris
If Grises(fila, col) > limite Then
BN(fila, col) = 1
Else
BN(fila, col) = 0
End If
Next
Next
End Sub

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


System.EventArgs) Handles btnAbrir.Click
Dim nombre As String
OpenFileDialog1.ShowDialog()
nombre = OpenFileDialog1.FileName
' Pict1 = New Bitmap("E:\datos\unsa40X40.bmp")
Pict1 = New Bitmap(nombre)
PictureBox1.Image = Pict1
nc = Pict1.Width
nf = Pict1.Height
Me.Text = "ancho " & nc & " alto " & nf
End Sub
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -1026-
Sub MostrarMatrizColor(ByVal cx As Integer, ByVal cy As Integer, ByVal nf As
Integer, ByVal nc As Integer, _
ByVal ex As Single, ByVal ey As Single, ByVal tipo As Integer)
Dim fila As Integer, col, rojo, verde, azul, gris, blanegro As Integer
For fila = 0 To nf - 1
For col = 0 To nc - 1
Select Case tipo
Case 1
rojo = Rojos(fila, col)
brocha1.Color = Color.FromArgb(rojo, 0, 0)
graficoRojo.FillRectangle(brocha1, cx + ex * col, cy + ey * fila, ex, ey)
Case 2
verde = Verdes(fila, col)
brocha1.Color = Color.FromArgb(0, verde, 0)
graficoVerde.FillRectangle(brocha1, cx + ex * col, cy + ey * fila, ex, ey)
Case 3
azul = Azules(fila, col)
brocha1.Color = Color.FromArgb(0, 0, azul)
graficoAzul.FillRectangle(brocha1, cx + ex * col, cy + ey * fila, ex, ey)
Case 4
rojo = Rojos(fila, col)
verde = Verdes(fila, col)
azul = Azules(fila, col)
brocha1.Color = Color.FromArgb(rojo, verde, azul)
graficoTodo.FillRectangle(brocha1, cx + ex * col, cy + ey * fila, ex, ey)
Case 5
gris = Grises(fila, col)
brocha1.Color = Color.FromArgb(gris, gris, gris)
graficoGris.FillRectangle(brocha1, cx + ex * col, cy + ey * fila, ex, ey)
Case 6
blanegro = BN(fila, col)
If blanegro = 0 Then
brocha1.Color = Color.FromArgb(0, 0, 0)
Else
brocha1.Color = Color.FromArgb(255, 255, 255)
End If
graficoBN.FillRectangle(brocha1, cx + ex * col, cy + ey * fila, ex, ey)
End Select
Next
Next
End Sub

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


System.EventArgs) Handles btnRojo.Click
graficoRojo = frmRojo.PictureBox1.CreateGraphics
graficoRojo.Clear(Color.Black)
MostrarMatrizColor(0, 0, nf, nc, ex, ey, 1)
frmRojo.Show()
End Sub

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


System.EventArgs) Handles btnVerde.Click
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -1027-
graficoVerde = frmVerde.PictureBox1.CreateGraphics
graficoVerde.Clear(Color.Black)
MostrarMatrizColor(0, 0, nf, nc, ex, ey, 2)
frmVerde.Show()
End Sub

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


System.EventArgs) Handles btnAzul.Click
graficoAzul = frmAzul.PictureBox1.CreateGraphics
graficoAzul.Clear(Color.Black)
MostrarMatrizColor(0, 0, nf, nc, ex, ey, 3)
frmAzul.Show()
End Sub

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


System.EventArgs) Handles btnVerTodo.Click
graficoTodo = FrmTodo.PictureBox1.CreateGraphics
graficoTodo.Clear(Color.Black)
MostrarMatrizColor(0, 0, nf, nc, ex, ey, 4)
FrmTodo.Show()
End Sub

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


System.EventArgs) Handles BtnVGris.Click
graficoGris = FRMGRIS.PictureBox1.CreateGraphics
graficoGris.Clear(Color.Black)
MostrarMatrizColor(0, 0, nf, nc, ex, ey, 5)
FRMGRIS.Show()
End Sub

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


System.EventArgs) Handles VerBN.Click
graficoBN = frmBN.PictureBox1.CreateGraphics
graficoBN.Clear(Color.Black)
MostrarMatrizColor(0, 0, nf, nc, ex, ey, 6)
frmBN.Show()
End Sub

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


System.Windows.Forms.MouseEventArgs) Handles PictureBox2.MouseDown
Dim posX As Integer
Dim posY As Integer
posX = e.X / ex
posY = e.Y / ey
ListBox1.Items.Clear()
ListBox1.Items.Add("ROJO " & Rojos(posY, posX))
ListBox1.Items.Add("VERDE " & Verdes(posY, posX))
ListBox1.Items.Add("AZUL " & Azules(posY, posX))
End Sub

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


System.EventArgs) Handles btnControl.Click
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -1028-
Dim Control1 As Integer = 0
Cont1 = 0
ListBox2.Items.Clear()
Do
Control1 = UbicarPunto(BN, nf, nc, px, py, mancha)
If Control1 = 1 Then
'Matriz(py, px) = blanco
ListBox2.Items.Add("cont " & " px " & px & " py " & py)
' Console.WriteLine("cont1 = {0} px = {1} py = {2} ", Cont1, px, py)
Cont2 = 0
ContarTamaño(BN, px, py, mancha)
ListBox2.Items.Add("tamaño " & Cont2)
' Console.WriteLine("tamaño= {0} ", Cont2)
Cont1 = Cont1 + 1
Else
ListBox2.Items.Add("Punto no encontrado")
End If
Loop While Control1 = 1
ListBox2.Items.Add("Cantidad de puntos" & Cont1)
End Sub
End Class

CODIGO DEL MODULO 1

Imports System.Drawing
Module Module1
Public brocha1 As SolidBrush
Public Grafico As Graphics
Public graficoTodo As Graphics
Public graficoRojo As Graphics
Public graficoVerde As Graphics
Public graficoAzul As Graphics
Public graficoGris As Graphics
Public graficoBN As Graphics
Public limite As Byte = 180 ' 128
Public Color1 As Color
Public Pict1 As Bitmap
Public Const maxfilas As Integer = 500
Public maxcol As Integer = 600
Public ex As Integer = 2
Public ey As Integer = 2
Public nf As Integer = 40
Public nc As Integer = 40
Public Rojos(maxfilas, maxcol) As Byte
Public Verdes(maxfilas, maxcol) As Byte
Public Azules(maxfilas, maxcol) As Byte
Public Grises(maxfilas, maxcol) As Byte
Public BN(maxfilas, maxcol) As Byte
' Public Matriz(maxfilas, maxcol) As Integer
'*******************
Public px As Integer = 2
Public py As Integer = 2
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -1029-
Public Cont1 As Integer = 0 ' contador de puntos iniciales
Public Cont2 As Integer = 0 ' contador de puntos en la mancha
Public mancha As Byte = 0
Public blanco As Byte = 1
Dim control1 As Byte = 0 ' control para determinar si no hay mas manchas
Sub main()
RecuperarMatriz("E:\datos\matriz8x8.txt", BN, nf, nc)
MostrarMatriz(BN, nf, nc)
Cont1 = 0
Do
control1 = UbicarPunto(BN, nf, nc, px, py, mancha)
If control1 = 1 Then
'Matriz(py, px) = blanco
Console.WriteLine("cont1 = {0} px = {1} py = {2} ", Cont1, px, py)
Cont2 = 0
ContarTamaño(BN, px, py, mancha)
Console.WriteLine("tamaño= {0} ", Cont2)
Cont1 = Cont1 + 1
Else
Console.WriteLine("Punto no encontrado ")
End If
Loop While control1 = 1
Console.WriteLine("Cantidad de puntos {0} ", Cont1)
Console.ReadLine()
End Sub
End Module

CODIGO DEL MODULO 2

Imports System.IO
Module Module2
Sub RecuperarMatriz(ByVal nombrearchivo As String, ByRef A(,) As Byte, 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")
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -1030-
srLector.Close()
End Sub
Sub MostrarMatriz(ByVal A(,) As Byte, 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} {1}", A(fila, col), vbTab)
Next
Console.WriteLine()
Next
End Sub

Function UbicarPunto(ByVal A(,) As Byte, ByVal nf As Integer, ByVal nc As Integer, _


ByRef px As Integer, ByRef py As Integer, ByVal valor As Integer) As Integer
For fila = 0 To nf - 1
For col = 0 To nc - 1
If A(fila, col) = valor Then
px = col
py = fila
Return 1
End If
Next
Next
Return 0
End Function

Sub ContarTamaño(ByVal A(,) As Byte, ByVal px As Integer, ByVal py As Integer,


ByVal valor As Integer)
If px > 1 And px < nc - 1 And py > 1 And px < nf - 1 Then
End If
Cont2 = Cont2 + 1
A(py, px) = blanco
If A(py, px + 1) = valor Then
ContarTamaño(A, px + 1, py, valor)
End If
If A(py, px - 1) = valor Then
ContarTamaño(A, px - 1, py, valor)
End If
If A(py + 1, px) = valor Then
ContarTamaño(A, px, py + 1, valor)
End If
If A(py - 1, px) = valor Then
ContarTamaño(A, px, py - 1, valor)
End If
End Sub
End Module

10.37 TAREA.
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -1031-
Mejore el programa para detectar bordes, transparencias, etc. (para detectar bordes
consulte el capítulo 11 del libro de Visual Basic)
Aplique el programa mejorado
1. Para detectar huellas dactilares
2. Para detectar manchas en telas, papel, ropa, etc.
3. Para ver reconocer el estado de maduración de una fruta por cambio de color y
aparición de color por ejemplo el plátano
4. Reconocer una firma
5. Reconocer una figura para usar en el CNC ( ejemplo una plantilla)
6. Reconocer el número de ojos que tiene una papa y otras características por
ejemplo color tamaño y de acuerdo a ello comparando con la base de datos decir
que tipo de papa es
7. Reconocer un rostro
8. Reconocer figuras ,por forma(triangulo, cuadrado, circulo ,etc.) ,color, área, y
Otras características
9. Reconocer una hoja y de acuerdo a ello que tipo de planta es
10. Se tiene semillas de quinua de diferentes colores determinar cuántas semillas de
cada color hay tomando una foto
11. tomar una foto de una semilla y determinar qué tipo de semilla es si es arroz, trigo,
maíz , habas, manzana,etc
12. de acuerdo a la foto la computadora debe identificar un producto por ejemplo un,
lapicero, lápiz, plumón, llaves, etc.
13. Tomando fotografía donde la cámara gira alrededor del objeto y el objeto gira
alrededor de la cámara, obtenga una imagen 3D
14. Escanea una foto a colores y de acuerdo a ello calcular la cantidad de colores rojo,
verde y azul que se necesitara para imprimir o pintar
15. implementar otras aplicaciones por ejemplo en automatización (con leds RGB)

10.38 APLICACIÓN DEL MODELO EN DETECCION DE MANCHAS DE LANA


REPITIDO
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -1032-

Figura blanco y negro a escala 2

10.40 IMAGEN CON BARRAS DE DEZPLAZAMIENTO


Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -1033-

Dibujar un árbol fractal

Public Class Form1


Dim grafico As Graphics
Dim pluma As Pen
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
grafico = Me.CreateGraphics
pluma = New Pen(Brushes.Green, 3)
Me.BackColor = Color.Aqua
End Sub
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -1034-
Sub Arbol(ByVal x As Single, ByVal y As Single, ByVal alto As Single, _
ByVal teta As Single, ByVal w As Single, ByVal valor As Single, dx As Single,
paro As Single, _
rama As Single)
Dim x1 As Single, y1 As Single, t1 As Single
If (alto > paro) Then '//condición de paro
x1 = x + alto * Math.Cos(teta)
y1 = y + alto * Math.Sin(teta)
grafico.DrawLine(pluma, x, y, x1, y1)
't1 = alto / 1.8 '1.7
t1 = alto / rama
Arbol(x1, y1, t1, teta - w, w, valor - dx, dx, paro, rama)
Arbol(x1, y1, t1, teta, w, valor - dx, dx, paro, rama)
Arbol(x1, y1, t1, teta + w, w, valor - dx, dx, paro, rama)
End If
End Sub
Private Sub FrmArbol_Paint(sender As Object, e As PaintEventArgs) Handles
Me.Paint
grafico.Clear(Color.Aqua)
pluma.Width = 8
pluma.Color = Color.Maroon
Arbol(150, 300, 120, 3 * Math.PI / 2.0, 0.9, 5, 0.1, 20, 1.8)
pluma.Color = Color.Blue
pluma.Width = 2
Arbol(250, 300, 100, 3 * Math.PI / 2.0, 0.4, 4, 0.2, 5, 1.5)
pluma.Color = Color.Green
pluma.Width = 1
Arbol(300, 300, 150, 3.2 * Math.PI / 2.0, 0.3, 3, 0.3, 1, 2)
pluma.Color = Color.Red
Arbol(450, 350, 90, 3 * Math.PI / 2.0, 0.6, 2, 0.4, 5, 1.4)
End Sub
End Class

ARBOLES
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -1035-

Public Class Form1


Dim grafico As Graphics
Dim pluma As Pen
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
grafico = PictureBox1.CreateGraphics
pluma = New Pen(Brushes.Green, 3)
alto = 80
End Sub
Sub Arbol(ByVal x As Single, ByVal y As Single, ByVal alto As Single, _
ByVal teta As Single, ByVal w As Single, ByVal valor As Single, dx As Single,
paro As Single, _
rama As Single)
Dim x1 As Single, y1 As Single, t1 As Single
If (alto > paro) Then '//condición de paro
x1 = x + alto * Math.Cos(teta)
y1 = y + alto * Math.Sin(teta)
grafico.DrawLine(pluma, x, y, x1, y1)
't1 = alto / 1.8 '1.7
t1 = alto / rama
Arbol(x1, y1, t1, teta - w, w, valor - dx, dx, paro, rama)
Arbol(x1, y1, t1, teta, w, valor - dx, dx, paro, rama)
Arbol(x1, y1, t1, teta + w, w, valor - dx, dx, paro, rama)
End If
End Sub
Dim X, y, alto As Single
Private Sub HSX_Scroll(sender As Object, e As ScrollEventArgs) Handles
HSX.Scroll
grafico.Clear(Color.Aqua)
X = HSX.Value
txtX.Text = X
Arbol(X, y, 90, 3 * Math.PI / 2.0, 0.6, 2, 0.4, 20, 1.4)
End Sub

Private Sub HSY_Scroll(sender As Object, e As ScrollEventArgs) Handles


HSY.Scroll
grafico.Clear(Color.Aqua)
y = HSY.Value
txtY.Text = y
Arbol(X, y, 90, 3 * Math.PI / 2.0, 0.6, 2, 0.4, 20, 1.4)
End Sub
End Class

10.42 TRABAJO DE TRAINGULACION CON INTEGRALES

1. VER CASO DE TRIANGULOS


Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -1036-
este progrma obtiene cualquer area de puntos dados

Imports System.Drawing
Public Class Form1
Dim Pen As Pen
Dim Grafico As Graphics
Dim brocha As SolidBrush
Dim np As Integer = 6
Dim MiFuente As New Font("Verdana", 12, FontStyle.Bold)
Sub GraficarPoligono(cx As Integer, cy As Integer, X() As Single, Y() As Single,
ex As Single, ey As Single, np As Integer)
Dim fila As Integer
Dim Puntos(np - 1) As Point
For fila = 0 To np - 1
Puntos(fila).X = cx + CInt(X(fila) * ex)
Puntos(fila).Y = cy + CInt(Y(fila) * ey)
Next
Grafico.FillPolygon(brocha, Puntos)
Grafico.DrawPolygon(Pen, Puntos)
End Sub

Sub MostrarVectoresXYFormulario(VX() As Single, VY() As Single, nf As Integer)


Dim fila As Integer
For fila = 0 To nf - 1
ListBox1.Items.Add(VX(fila) & vbTab & VY(fila))
Next
End Sub
Private Sub btnABrir_Click(sender As Object, e As EventArgs) Handles btnABrir.Click
Dim area As Single
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -1037-
RecuperarVectoresXY(NombreArchivo, VX1, VY1, nfilas, ncol)
MostrarVectoresXYFormulario(VX1, VY1, nfilas)
ListBox1.Items.Add("METODO TRAPECIAL")
area = Trapecial(VX1, VY1, nfilas)
ListBox1.Items.Add(" EL AREA es " & area)
End Sub

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load


Grafico = PictureBox1.CreateGraphics
Pen = New Pen(Color.Blue, 2)
brocha = New SolidBrush(Color.FromArgb(255, 255, 0))
End Sub
Sub GraFicarPuntos(VX1() As Single, VY1() As Single, tx As Single, ty As Single, ex
As Single, ey As Single, np As Integer)
Dim fila As Integer
For fila = 0 To np - 1
Grafico.DrawString(fila, MiFuente, brocha, tx + VX1(fila) * ex, ty + VY1(fila) * ey)
Next
End Sub

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


btnGraficar.Click
GraficarPoligono(tx, ty, VX1, VY1, ex, ey, nfilas)
brocha.Color = Color.Red
GraFicarPuntos(VX1, VY1, tx, ty, ex, ey, nfilas)
brocha.Color = Color.Yellow
End Sub

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


btnBorrar.Click
Grafico.Clear(Color.Black)
End Sub
End Class

Module module1
Const tam As Integer = 20
Sub main()
Dim area As Single
RecuperarVectoresXY(NombreArchivo, VX1, VY1, nfilas, ncol)
MostrarVectoresXY(VX1, VY1, nfilas)
Console.WriteLine("METODO TRAPECIAL")
area = Trapecial(VX1, VY1, nfilas)
Console.WriteLine(" EL AREA es {0}", area)
Console.ReadLine()
End Sub
End Module

Imports System.IO
Module Module2
Public NombreArchivo As String = "C:\datos\TRI1.txt"
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -1038-
Public Const limite As Integer = 10
Public VX1(limite) As Single
Public VY1(limite) As Single
Public nfilas, ncol As Integer
Public tx As Single = 10
Public ty As Single = 200
Public ex As Single = 50
Public ey As Single = -50

Function Trapecial(ByVal X() As Single, ByVal Y() As Single, ByVal np As Integer) As


Single
Dim at As Single = 0, ap As Single, dx As Single
Dim fx1, fx2 As Single
Dim i As Integer
For i = 0 To np - 2
dx = X(i + 1) - X(i)
fx1 = Y(i)
fx2 = Y(i + 1)
ap = dx * (fx1 + fx2) / 2
at = at + ap
Next
Return at
End Function
Sub RecuperarVectoresXY(ByVal nombrearchivo As String,
VX() As Single, VY() As Single, ByRef nf As Integer, ByRef nc As
Integer)
Dim srLector As StreamReader
srLector = New StreamReader(nombrearchivo)
Dim fila As Integer
Dim cadena As String = ""
Dim subcadena As String
Dim pos As Integer = 0
cadena = srLector.ReadLine()
Do While Not (cadena = "")
cadena = cadena & vbTab
pos = InStr(1, cadena, Chr(9))
subcadena = Mid(cadena, 1, pos - 1)
VX(fila) = Val(subcadena)
subcadena = Mid(cadena, pos + 1)
VY(fila) = Val(subcadena)
fila = fila + 1
cadena = srLector.ReadLine()
Loop
nf = fila
Console.WriteLine("Archivo leido satisfactoriamente")
srLector.Close()
End Sub
Sub MostrarVectoresXY(VX() As Single, VY() As Single, nf As Integer)
Dim fila As Integer
For fila = 0 To nf - 1
Console.WriteLine("{0} {1} {2}", VX(fila), vbTab, VY(fila))
Next
Programacion y Metodos numéricos 2019a \10 Aplicaciones Windows Forms \Ismael Véliz Vilca -1039-
End Sub
End Module

10 9
7 6
10 7
9 1
4 -6
-1 8
6 -5
6 5
-7 -4
3 -4
1 7
-5 0
2 3
-7 -3
-8 1
-8 -2
-6 2
3 5
-9 7
-4 -8

Das könnte Ihnen auch gefallen