SMALL BASIC
-PROGRAMACIÓN ORIENTADA A OBJETOS (OOP)-
Enlace de interés: http://codigogx.blogspot.com.es/p/small.html
Ejemplos: https://social.technet.microsoft.com/wiki/contents/articles/17553.wiki-small-basic-portal.aspx#Samples
1.- MI PRIMER PROGRAMA: "HOLA MUNDO"
LOS OBJETOS: Son las instancias de una CLASE. Son la combinación de código y datos que se pueden tratar como una unidad, por ejemplo, un control, un formulario o un componente de una aplicación, una ventana de windows, etc.
Por ejemplo podemos referirnos a objetos como coche, silla, casa, etc. De esta forma, cualquier objeto real de cuatro ruedas, un motor, un chasis,... es un objeto de la clase coche.
Las CLASES son los moldes para crear estos objetos. Los objetos están siempre definidos por una clase.
Para hacer mi primer programa utilizaré el "objeto" de SmallBasic:
TextWindow
TextWindow.WriteLine("Hello World")
LAS PROPIEDADES de los objetos: Las propiedades son los atributos/comportamientos que definen las características de un objeto, como por ejemplo: tamaño, color o su ubicación en la pantalla, o su estado (habilitado/no habilitado).
Todo objeto tiene una serie de propiedades, como por ejemplo color.
Ahora vamos a añadir al texto un tipo de color: Black, Blue, Cyan, Gray, Green, Magenta, Red, White, Yellow, DarkBlue, DarkCyan, DarkGray, DarkGreen, DarkMagenta, DarkRed, DarkYellow.
TextWindow.ForegroundColor = "Yellow"
TextWindow.WriteLine("Hello World")
2.- LAS VARIABLES. Las variables son un lugar de almacenamiento con nombre que puede contener cierto tipo de datos que puede ser modificado durante la ejecución del programa. Cada variable tiene un nombre único que la identifica dentro de su nivel de ámbito. Puede especificar un tipo de datos o no.Nombres de variable deben comenzar con un carácter alfabético, deben ser únicos dentro del mismo ámbito, no deben contener más de 255 caracteres y no pueden contener un punto o carácter de declaración de tipo.
Las variables para guardar texto:
TextWindow.Write("Enter your Name: ")
name = TextWindow.Read()
TextWindow.WriteLine("Hello " + name)
Y ahora añadimos algo más de contenido al mensaje que vemos en la pantalla:
TextWindow.Write("Enter your Name: ")
name = TextWindow.Read()
TextWindow.Write("Hello " + name + ". ")
TextWindow.WriteLine("How are you doing " + name + "?")
Las variables se usan comunmente para trabajar con números:
number1 = 10 number2 = 20
number3 = number1 + number2
TextWindow.WriteLine(number3)
EJERCICIOS:
1.- Haz un programa que haga la resta, multiplicación, división y potenciación de dos números.
3.- MI PRIMER ALGORITMO:
Vamos a hacer un programa que convierta la temperatura de grados fahrenheit en grados centígrados:
TextWindow.Write("Enter temperature in Fahrenheit: ")
fahren = TextWindow.ReadNumber()
celsius = 5 * (fahren - 32) / 9
TextWindow.WriteLine("Temperature in Celsius is " + celsius)
Ahora haz tú estos ejercicios:
- Introducido el lado de un cuadrado que indique cual es su superficie.
- Introducido el radio de una circunferencia que indique su área.
- Introducido la base y la altura de un triángulo que indique su área.
4.- CONDICIONALES (estructura de control):
If ...Then...Else.... Es una estructura de control que hace que se ejecuten una serie de instrucciones siempre y cuando se cumpla una determinada condición. Cuendo se utiliza una condición dentro de otra se dice que es un anidamiento de condiciones.
En el siguiente programa podemos preguntar si vamos a desayunar siempre y cuando sean antes de las doce de la mañana...
If (Clock.Hour < 12) Then
TextWindow.Write("Good Morning. ")
TextWindow.WriteLine("How was breakfast?")
EndIf
En el siguiente programa podemos decir buenos días o buenas tardes según sea la hora del reloj del ordenador.
If (Clock.Hour < 12) Then
TextWindow.WriteLine("Good Morning World")
EndIf
If (Clock.Hour >= 12) Then
TextWindow.WriteLine("Good Evening World")
EndIf
Con el siguiente programa modificamos el código anterior usando la sentencia ELSE
If (Clock.Hour < 12) Then
TextWindow.WriteLine("Good Morning World")
Else
TextWindow.WriteLine("Good Evening World")
EndIf
EJERCICIO:
Introduce tus años y el ordenador te dirá si eres o no mayor de edad.
TextWindow.Write("Cual es tu edad? ")
edad = TextWindow.ReadNumber()
If edad >= 18 Then
TextWindow.WriteLine("Eres mayor de
edad")
EndIf
If edad < 18 Then
TextWindow.WriteLine("Eres menor
de edad")
EndIf
Y ahora con un mayor control sobre los datos ingresados:
inicio:
TextWindow.Write("Cual es tu edad? ")
edad = TextWindow.ReadNumber()
If edad
>= 18 Then
If edad >=120 Then
TextWindow.WriteLine("La edad ingresada es muy alta")
Goto
inicio
EndIf
TextWindow.WriteLine("Eres mayor de edad")
Else
If
edad < 0 Then
TextWindow.WriteLine("La edad no puede ser un numero
negativo")
Goto
inicio
EndIf
TextWindow.WriteLine("Eres menor de edad")
EndIf
Y ahora usando los operadores lógicos:
TextWindow.Write("Cual es tu edad? ")
edad = TextWindow.ReadNumber()
If edad
>= 0 And edad < 18 Then
TextWindow.WriteLine("Eres menor de edad")
EndIf
If edad
>= 18 And edad <= 120 Then
TextWindow.WriteLine("Eres mayor de edad")
EndIf
If edad
< 0 Or edad > 120 Then
TextWindow.WriteLine("La edad ingresada no es valida")
EndIf
EJEMPLO PRÁCTICO: ¿PAR/IMPAR?
TextWindow.Write("Enter a number: ")
num = TextWindow.ReadNumber()
remainder = Math.Remainder(num, 2)
If (remainder = 0) Then
TextWindow.WriteLine("The number is Even")
Else
TextWindow.WriteLine("The number is Odd")
EndIf
5. EL SALTO DE LÍNEA
(la derivación, o salto de línea, en una estructura lineal).
label:...... Goto label
i = 1 start:
TextWindow.WriteLine(i)
i = i + 1
If (i < 25) Then
Goto start
EndIf
En este programa encontramos una etiqueta (label) que hemos llamado start: y nos sirve para ser el punto de retorno junto a esa posición cuendo hagamos un: Goto start
Por otra parte tenemos la sentencia i=i+1 que sirve de acumulador cada vez que pasamos por ella.
Observemos el siguiente programa:
begin:
TextWindow.Write("Enter a number: ")
num = TextWindow.ReadNumber()
remainder = Math.Remainder(num, 2)
If (remainder = 0) Then
TextWindow.WriteLine("The number is Even")
Else
TextWindow.WriteLine("The number is Odd")
EndIf
Goto begin
Con el salto de línea Goto podemos hacer que este programa se repita (loop) tantas veces como queramos hasta que cerremos el programa clickeando en la cruz hay en la esquina superior derecha de la ventana.
6. EL BUCLE FOR
For i=...To... Step .... EndFor Es una estrucura de control que hace repetir unas instrucciones un número determinado de veces hasta agotar el intervalo de acumulación del contador (i) que le hayamos establecido. La cuenta se puede especificar con STEP. Es necesario usar variables para la acumulación y éstas deberán ser diferentes en el caso de bucles anidados.
Analicemos primero el siguiente programa:
i = 1 start:
TextWindow.WriteLine(i)
i = i + 1
If (i < 25) Then
Goto start
EndIf
Si observamos este código, el programa imprimirá en la pantalla de texto del 1 al 24 en orden. Pero los lenguajes de programación utilizan un bucle de repetición (loop) para hacer esto mismo ahorrandose líneas de código, veámoslo:
For i = 1 To 24
TextWindow.WriteLine(i)
EndFor
Si en este tipo de bucles queremos que contador sea de dos en dos utilizamos la sentencia STEP:
For i = 1 To 24 Step 2
TextWindow.WriteLine(i)
EndFor
EJERCICIOS:
- Saca por pantalla una lista de números que vayan de 10 a 1 en este orden.
- Haz una progresión aritmética del tipo: a(n+1)= a(n)*2
7.- EL BUCLE WHILE.
While ( ).... EndWhile Es una estructura de control que hace repetir unas instrucciones un número indefinido de veces mientras que se cumpla una determinada condición. En esta ocasión para que el bucle se inicie por primera vez es necesario que la condición se cumpla previamente. Puede ocurrir que ni siquiera se inicie el bucle. Es este tipo de bucles es necesario declarar y asignar un valor a las variables del contador, previamente.
Al igual que hicimos con el bucle for, podríamos hacer un programa usando el salto de línea con una condición del tipo IF tal como vemos:
number = 100 startLabel:
TextWindow.WriteLine(number)
number = number / 2
If (number > 1) Then
Goto startLabel
EndIf
Pero para conseguir esta estructura de control, los lenguajes de programación utilizan el comando While de la siguiente forma:
number = 100
While (number > 1)
TextWindow.WriteLine(number)
number = number / 2
EndWhile
Con este programa, escribimos la mitad de un número y su consecutivo "mientras" que dicho valor sea mayor que 1. En este caso, no existe un contador i=i+1 propio del bucle for.
Compara esta
8.- VENTANA DE GRÁFICOS.
En esta ocasión vamos a trabajar con el objeto de windows gráfico:
GraphicsWindow.Show( )
Antes de utilizarlo, podremos customizarlo mediante sus propiedades y poniendo ciertos argumentos:
GraphicsWindow.BackgroundColor = "SteelBlue"
GraphicsWindow.Title = "My Graphics Window"
GraphicsWindow.Width = 320
GraphicsWindow.Height = 200
GraphicsWindow.Show()
Con la siguiente instrucción se dibujan puntos en al ventana:
GraphicWindow.SetPixel(0,0, "red")
Por ejemplo se pueden dibuar una línea de puntos azules mediante puntos en horizontal:
For x = 100 To 200
GraphicsWindow.SetPixel(x, 50, "blue")
EndForO también en vertical
For y = 50 To 150
GraphicsWindow.SetPixel(100, y, "blue")
EndForO se puede utilzar la instrucción de trazado de línea para hacer lo mismo más directamente:
DIBUJANDO LÍNEAS:
GraphicsWindow.Width = 200
GraphicsWindow.Height = 200
GraphicsWindow.DrawLine(10, 10, 100, 100)
GraphicsWindow.DrawLine(10, 100, 100, 10)
COLORES RGB:
GraphicsWindow.Width = 200
GraphicsWindow.Height = 200
GraphicsWindow.PenColor = "Green" GraphicsWindow.DrawLine(10, 10, 100, 100) GraphicsWindow.PenColor = "Gold"
GraphicsWindow.DrawLine(10, 100, 100, 10)
EJERCICIOS:
- Dibuja varias líneas con varios colores pero en esta ocasión utiliza la nomenclatura del tipo #RRGGBB en hexadecimal, por ejemplo: #FF0000 para el rojo.
- Dibuja formas geométricas mediante líneas: CUADRADO, RECTÁNGULO Y TRIÁNGULO.
Modifiquemos ahora otras propiedades:
GraphicsWindow.Width = 200
GraphicsWindow.Height = 200
GraphicsWindow.PenWidth = 10
GraphicsWindow.PenColor = "Green"
GraphicsWindow.DrawLine(10, 10, 100, 100)
GraphicsWindow.PenColor = "Gold"
GraphicsWindow.DrawLine(10, 100, 100, 10)
Múltiples grosores de línea con la sentencia For.
GraphicsWindow.BackgroundColor = "Black"
GraphicsWindow.Width = 200
GraphicsWindow.Height = 160
GraphicsWindow.PenColor = "Blue"
For i = 1 To 10
GraphicsWindow.PenWidth = i
GraphicsWindow.DrawLine(20, i * 15, 180, i * 15)
endfor
EJERCICIOS:
- Haz una secuencia parecida a la anterior pero en vertical.
- Y ahora echale imaginación y sorprende al profesor con otro tipo de secuencias.
FIGURAS GEOMÉTRICAS:
GraphicsWindow.Width = 400
GraphicsWindow.Height = 300
GraphicsWindow.PenColor = "Red"
GraphicsWindow.DrawRectangle(20, 20, 300, 60)
GraphicsWindow.BrushColor = "Green"
GraphicsWindow.FillRectangle(60, 100, 300, 60)
EJERCICIOS:
- Haz un dibujo con varios cuadrados de distintos colores.
- Y ahora prueba con elipses según los códigos siguientes:
GraphicsWindow.Width = 400
GraphicsWindow.Height = 300
GraphicsWindow.PenColor = "Red"
GraphicsWindow.DrawEllipse(20, 20, 300, 60)
GraphicsWindow.BrushColor = "Green"
GraphicsWindow.FillEllipse(60, 100, 300, 60)
Para hacer círculos, debemos especificar el mismo ancho y alto:
GraphicsWindow.Width = 400
GraphicsWindow.Height = 300
GraphicsWindow.PenColor = "Red"
GraphicsWindow.DrawEllipse(20, 20, 100, 100)
GraphicsWindow.BrushColor = "Green"
GraphicsWindow.FillEllipse(100, 100, 100, 100)
9.- FORMAS DIVERTIDAS:
RECTANGALORE:
GraphicsWindow.BackgroundColor = "Black" GraphicsWindow.PenColor = "LightBlue" GraphicsWindow.Width = 200
GraphicsWindow.Height = 200
For i = 1 To 100 Step 5
GraphicsWindow.DrawRectangle(100 - i, 100 - i, i * 2, i * 2) EndFor
ESPECTACULAR:
GraphicsWindow.BackgroundColor = "Black"
GraphicsWindow.PenColor = "LightGreen"
GraphicsWindow.Width = 200
GraphicsWindow.Height = 200
For i = 1 To 100 Step 5
GraphicsWindow.DrawEllipse(100 - i, 100 - i, i * 2, i * 2)
EndFor
ALEATORIOS:
GraphicsWindow.BackgroundColor = "Black"
For i = 1 To 1000
GraphicsWindow.BrushColor = GraphicsWindow.GetRandomColor()
x = Math.GetRandomNumber(640)
y = Math.GetRandomNumber(480)
GraphicsWindow.FillEllipse(x, y, 10, 10)
EndFor
FRACTALES:
GraphicsWindow.BackgroundColor = "Black"
x = 100
y = 100
For i = 1 To 100000
r = Math.GetRandomNumber(3)
ux = 150
uy = 30
If (r = 1) then
ux = 30
uy = 1000
EndIf
If (r = 2) Then
ux = 1000
uy = 1000
EndIf
x = (x + ux) / 2
y = (y + uy) / 2
GraphicsWindow.SetPixel(x, y, "LightGreen")
EndFor
EJERCICIOS: Ahora modifica el código anterior y observa que ocurre:
- Añade el siguiente código justo antes del último EndFor: Program.Delay(2)
- Cambia la instrucción:
color = GraphicsWindow.GetRandomColor()
GraphicsWindow.SetPixel(x, y, color)
10.- SUBRRUTINAS:
Una subrrutina es una porción de código dentro de un programa extenso que usualmente hace algo específico y que puede ser llamado en cualquier lugar del programa. Las subrrutinas ayudan a reducir la cantidad de código que hay que escribir en un programa y también ayudan a descomponer un programa complejo en partes simples. Además hace más fácil de leer y comprender un programa.
Se las identifica con un nombre propio y van dentro de las palabras claves:
Sub name....EndSub
Ejemplo de llamada de una subrrutina (PrintTime( ) ) dos veces, en el siguiente programa:
PrintTime( )
TextWindow.Write("Enter your name: ")
name = TextWindow.Read()
TextWindow.Write(name + ", the time now is: ")
PrintTime()
Sub PrintTime
TextWindow.WriteLine(Clock.Time)
EndSub
Ejemplo de cálculo de un número máximo utilizando una subrrutina:
TextWindow.Write("Enter first number: ")
num1 = TextWindow.ReadNumber()
TextWindow.Write("Enter second number: ")
num2 = TextWindow.ReadNumber()
FindMax()
TextWindow.WriteLine("Maximum number is: " + max)
Sub FindMax
If (num1 > num2) Then
max = num1
Else
max = num2
EndIf
EndSub
Toroidal con una subrrutina:
GraphicsWindow.BackgroundColor = "Black"
GraphicsWindow.PenColor = "LightBlue"
GraphicsWindow.Width = 480
For i = 0 To 6.4 Step 0.17
x = Math.Sin(i) * 100 + 200
y = Math.Cos(i) * 100 + 200
DrawCircleUsingCenter()
EndFor
Sub DrawCircleUsingCenter
startX = x - 40
startY = y - 40
GraphicsWindow.DrawEllipse(startX, startY, 120, 120)
EndSub
Número primo con una Subrrutina:
TextWindow.Write("Enter a number: ")
i = TextWindow.ReadNumber()
isPrime = "True"
PrimeCheck()
If (isPrime = "True") Then
TextWindow.WriteLine(i + " is a prime number")
Else
TextWindow.WriteLine(i + " is not a prime number")
EndIf
Sub PrimeCheck
For j = 2 To Math.SquareRoot(i)
If (Math.Remainder(i, j) = 0) Then
isPrime = "False"
Goto EndLoop
EndIf
Endfor
EndLoop:
EndSub
Listado de número primos del 3 al 100.
For i = 3 To 100
isPrime = "True"
PrimeCheck()
If (isPrime = "True") Then
TextWindow.WriteLine(i)
EndIf
EndFor
Sub PrimeCheck
For j = 2 To Math.SquareRoot(i)
If (Math.Remainder(i, j) = 0) Then
isPrime = "False"
Goto EndLoop
EndIf
Endfor
EndLoop:
EndSub
11.- LAS TABLAS (ARRAYS)
var[i]
var["name"]
Un array es un tipo especial de variable que puede contener más de un valor al mismo tiempo según el índice que la identifica, por ejemplo: variable1, variable2, variable3, etc. Los números 1,2,3... son los índices del array.
Imaginate que el profesor necesita guarda en variables el nombre de cada uno de sus alumnos, entonces podría hacer un programa parecido a este:
TextWindow.Write("User1, enter name: ")
name1 = TextWindow.Read()
TextWindow.Write("User2, enter name: ")
name2 = TextWindow.Read()
TextWindow.Write("User3, enter name: ")
name3 = TextWindow.Read()
TextWindow.Write("User4, enter name: ")
name4 = TextWindow.Read()
TextWindow.Write("User5, enter name: ")
name5 = TextWindow.Read()
TextWindow.Write("Hello ")
TextWindow.Write(name1 + ", ")
TextWindow.Write(name2 + ", ")
TextWindow.Write(name3 + ", ")
TextWindow.Write(name4 + ", ")
TextWindow.WriteLine(name5)
Pues bien, esto en programación se hace utilizando tablas de una, dos o más dimensiones. En este caso concreto utilizaremos una tabla vector de una sóla dimensión mediante una varible que llamaremos name[i] siendo i el subindice que identifique por orden a cada uno de los alumnos.
For i = 1 To 5
TextWindow.Write("User" + i + ", enter name: ")
name[i] = TextWindow.Read()
EndFor
TextWindow.Write("Hello ")
For i = 1 To 5
TextWindow.Write(name[i] + ", ")
EndFor
TextWindow.WriteLine("")
Como podemos ver, con el uso de este array el código se simplifica y además permite fácilmente añadir muchos nombres con una sóla variable.
Siempre que operemos con tablas verás como es necesario trabajar con bucles (For) para introducir e imprimir los valores.
Para identificar una tabla no es imprescindible hacerlo con números, también podemos hacerlo con nombres. Echa un vistazo al siguiente programa:
TextWindow.Write("Enter name: ")
usuario["name"] = TextWindow.Read()
TextWindow.Write("Enter age: ")
usuario["age"] = TextWindow.Read()
TextWindow.Write("Enter city: ")
usuario["city"] = TextWindow.Read()
TextWindow.Write("Enter zip: ")
usuario["zip"] = TextWindow.Read()
TextWindow.Write("What info do you want? ")
index = TextWindow.Read()
TextWindow.WriteLine(index + " = " + usuario[index])
ARRAYS DE DOS DIMENSIONES:Las tablas pueden ser también de dos dimensiones (de tres o más no suelen utilizarse en programación). Veamos un ejemplo:
friends["ana"]["Name"] = "Ana Isabel Gómez"
friends["ana"]["Phone"] = "5556789"
friends["cj"]["Name"] = "César Jorge Argoitia"
friends["cj"]["Phone"] = "5554567"
friends["mau"]["Name"] = "Mauro Montes"
friends["mau"]["Phone"] = "666223366"
friends["mila"]["Name"] = "Milagros Ascó"
friends["mila"]["Phone"] = "6454545"
TextWindow.Write("Introduce el apodo: ")
nickname = TextWindow.Read()
TextWindow.WriteLine("Name: " + friends[nickname]["Name"])
TextWindow.WriteLine("Phone: " + friends[nickname]["Phone"])
Ejemlo de array de dos dimensiones con un dibujo en la ventana de texto:
For fila = 1 To 10
For columna = 1 To
10
matriz[fila][columna] =
"/\"
TextWindow.Write(matriz[fila][columna])
EndFor
TextWindow.WriteLine("")
EndForO este otro ejemplo utilizando un gráfico:
rows = 8
columns = 8
size = 40
For r = 1 To rows
For c = 1 To columns
GraphicsWindow.BrushColor = GraphicsWindow.GetRandomColor()
boxes[r][c] = Shapes.AddRectangle(size, size)
Shapes.Move(boxes[r][c], c * size, r * size)
EndFor
EndFor
Y ahora añade después del último EndFor el siguiente código y observa lo que ocurre:
For r = 1 To rows
For c = 1 To columns
Shapes.Animate(boxes[r][c], 0, 0, 1000)
Program.Delay(300)
EndFor
EndFor
EJERCICIOS:
- Modifica el código anterior para desplazar los cuadraditos a otro lugar de la ventana y con otras velocidades.
12.- EVENTOS E INTERACTIVIDAD:
Como ya vimos, los objetos en programación tienen propiedades y operaciones. Pero algunos de estos objetos también tienen lo que llamamos EVENTOS. Los eventos son como una señal de una acción que el objeto pueden hace y que aprovechamos para ejecutar una determinada instrucción cuando ésta se produce. Por ejemplo, cuando movemos el ratón sobre una ventana, cuando clickeamos un botón, etc.
En cierto sentido, los eventos son opuestos a las operaciones. En el caso de las operaciones, usted como programador las invoca para hacer que el equipo haga algo, mientras que en el caso de los eventos, el ordenador le indica cuándo ha ocurrido algo interesante. Los eventos son fundamentales para introducir interactividad a un programa. Si usted desea permitir a un usuario interactuar con su programa, los eventos son lo que usted usará.Digamos que está escribiendo un programa de las tres en raya. Deseará permitir al usuario elegir su jugada, ¿cierto? Ahí es donde intervienen los eventos: usted recibirá la entrada del usuario en su programa usando eventos”
Para poder utilizar los eventos, es necesario utilizar las subrutinas, ya que los eventos son activados cuando son asignados a una de estas.
Veamos como por ejemplo con la siguiente subrrutina se abre un mensae cuando clickeamos el ratón :
GraphicsWindow.MouseDown = click_raton
Sub click_raton
GraphicsWindow.ShowMessage("Tu clickeaste.", "Hola")
EndSub
La primera línea utiliza el evento MouseDown, que sirve para lanzar un evento cada vez que se hace clic con el ratón (derecho o izquierdo). Ese evento, necesariamente tiene que ser asignado a una subrutina para que funcione. En este caso, la subrutina fue llamada “clic”. Más abajo aparece la subrutina “clic”, la cual tiene solamente una instrucción, que es mostrar un mensaje. Como esta subrutina está “enlazada” al evento MouseDown, entonces se ejecutará cada vez que el usuario haga clic con el ratón.
O este otro más bonito, donde se dibujan círculos azules en el lugar donde clickeamos:
GraphicsWindow.BrushColor = "Blue"
GraphicsWindow.MouseDown = ClickRaton
Sub ClickRaton
x = GraphicsWindow.MouseX
y = GraphicsWindow.MouseY
GraphicsWindow.FillEllipse(x, y, 30, 30)
EndSub
Y ahora cambiemos de color cada vez que tecleemos:
GraphicsWindow.BrushColor = "Blue"
GraphicsWindow.MouseDown = Raton
GraphicsWindow.KeyDown = Tecla
Sub Tecla
GraphicsWindow.BrushColor = GraphicsWindow.GetRandomColor()
EndSub
Sub Raton
x = GraphicsWindow.MouseX
y = GraphicsWindow.MouseY
GraphicsWindow.FillEllipse(x, y, 20, 20)
EndSub
Y ahora estudia este otro código:
GraphicsWindow.MouseMove = OnMouseMove
Sub OnMouseMove
x = GraphicsWindow.MouseX
y = GraphicsWindow.MouseY
GraphicsWindow.DrawLine(prevX, prevY, x, y)
prevX = x
prevY = y
EndSub
Pero mejor será si podemos levantar el lápíz (ratón)...No?:
GraphicsWindow.MouseMove = OnMouseMove
GraphicsWindow.MouseDown = OnMouseDown
Sub OnMouseDown
prevX = GraphicsWindow.MouseX
prevY = GraphicsWindow.MouseY
EndSub
Sub OnMouseMove
x = GraphicsWindow.MouseX
y = GraphicsWindow.MouseY
If (Mouse.IsLeftButtonDown) Then
GraphicsWindow.DrawLine(prevX, prevY, x, y)
EndIf
prevX = x
prevY = y
EndSub
Otro ejemplo. Este programa lo que hará será pedir al usuario que ingrese su nombre en un cuadro de texto. Cuando el usuario ingrese su nombre y luego presione el botón “enviar”, se mostrará un mensaje saludándolo.
GraphicsWindow.DrawText(10,10, "Ingresa tu nombre")
texto = Controls.AddTextBox(10,30)
Controls.AddButton("Enviar",10,60)
Controls.ButtonClicked = btnEnviar
Sub btnEnviar
nombre =
Controls.GetTextBoxText(texto)
GraphicsWindow.ShowMessage("Bienvenido " +
nombre,"Saludo")
Las respuestas hasta ahora, solamente se han visto utilizando el ShowMessage, pero también es posible mostrar una respuesta en la misma ventana gráfica, simplemente cambiando el ShowMessage por un DrawText. Quedando así:
GraphicsWindow.DrawText(10,10,
"Ingresa tu nombre")
texto =
Controls.AddTextBox(10,30)
Controls.AddButton("Enviar",10,60)
Controls.ButtonClicked
= btnEnviar
Sub btnEnviar
nombre = Controls.GetTextBoxText(texto)
GraphicsWindow.DrawText(10,90,"Bienvenido " + nombre)
El problema de mostrar un resultado en la pantalla gráfica es que si se vuelve a ingresar un nombre, éste aparecerá encima del resultado anterior ya que el mensaje anterior no se borra.
Una forma que encontré para solucionar esto fue limpiar la pantalla con la instrucción GraphicsWindow.Clear(). Esta instrucción borra todos los elementos de la pantalla gráfica. No estoy muy convencido con esta solución ya que solamente necesito borrar lo escrito y no toda la pantalla. Al borrar toda la pantalla tendría que volver a dibujarla completamente y todo por querer borrar una pequeña parte de ella. Para volver a dibujar o poner todos los elementos nuevamente en la pantalla, necesariamente tuve que dejar todos esos elementos dentro de una subrutina con la cual puedo llamar a esos elementos. Aquí muestro una modificación del programa anterior
Sub inicio
GraphicsWindow.DrawText(10,10, "Ingresa
tu nombre")
texto = Controls.AddTextBox(10,30)
Controls.AddButton("Enviar",10,60)
EndSub
Controls.ButtonClicked
= btnEnviar
Sub btnEnviar
nombre
= Controls.GetTextBoxText(texto)
GraphicsWindow.Clear()
GraphicsWindow.DrawText(10,90,"Bienvenido
" + nombre)
inicio()
EndSub
EJEMPLO DE EVENTO: MOVER UN CÍRCULO CON LAS TECLAS
x = 0
y = 0
circulo =
Shapes.AddEllipse(50,50)' Añade un
circulo de 50x50
GraphicsWindow.KeyDown
= presionar
Sub derecha
x = x + 2
Shapes.move(circulo,x,y)
EndSub
Sub izquierda
x = x - 2
Shapes.Move(circulo,x,y)
EndSub
Sub abajo
y = y + 2
Shapes.Move(circulo,x,y)
EndSub
Sub arriba
y = y - 2
Shapes.Move(circulo,x,y)
EndSub
Sub
presionar
flecha = GraphicsWindow.LastKey
If flecha = "Right" Then
derecha()
EndIf
If flecha = "Left" Then
izquierda()
EndIf
If flecha = "Down" Then
abajo()
EndIf
If flecha = "Up" Then
arriba()
EndIf
EndSubEJERCICIO: Modifica el código anterior con otra figura, añade una imagen de fondo, añade otra figura que se mueva sola al azar, que la figura no se salga de la ventana, etc.
Un ejemplo para añadir imagen de fondo:
imagen = "G:\fondo.png"
un ejemplo de ciclo infinito:
azar = 1
While azar = 1
reloj = Clock.Second
If
Math.Remainder(reloj, 2) = 0 Then
MovCuad()' <-- Subrutina para mover
la figura
EndIf
EndWhile
La
subrutina para mover la figura quedó de la siguiente manera:
Sub MovCuad
azarX = Math.GetRandomNumber(500)
azarY = Math.GetRandomNumber(500)
Shapes.Animate(cuadrado,azarX,azarY,2000)
EndSubEJEMPLO DE PELOTA REBOTANDO:
bola = Shapes.AddEllipse(32, 32)
x = 0
y = 0
deltaX = 1
deltaY = 1
EjecutarBucle:
x = x + deltaX
y = y + deltaY
ancho = GraphicsWindow.Width
alto = GraphicsWindow.Height
If (x >= ancho - 32 Or x <= 0) Then
deltaX = -deltaX
EndIf
If (y >= alto - 32 or y <= 0) Then
deltaY = -deltaY
EndIf
Shapes.Move(bola, x, y)
Program.Delay(5)
If (y < alto) Then
Goto EjecutarBucle
EndIfY ahora juguemos al pádel:
GraphicsWindow.BackgroundColor = "DarkBlue"
paddle = Shapes.AddRectangle(120, 12)
ball = Shapes.AddEllipse(16, 16)
GraphicsWindow.MouseMove = OnMouseMove
x = 0
y = 0
deltaX = 1
deltaY = 1
RunLoop:
x = x + deltaX
y = y + deltaY
gw = GraphicsWindow.Width
gh = GraphicsWindow.Height
If (x >= gw - 16 or x <= 0) Then
deltaX = -deltaX
EndIf
If (y <= 0) Then
deltaY = -deltaY
EndIf
padX = Shapes.GetLeft (paddle)
If (y = gh - 28 and x >= padX and x <= padX + 120) Then
deltaY = -deltaY
EndIf
Shapes.Move(ball, x, y)
Program.Delay(5)
If (y < gh) Then
Goto RunLoop
EndIf
GraphicsWindow.ShowMessage("You Lose", "Paddle")
Sub OnMouseMove
paddleX = GraphicsWindow.MouseX
Shapes.Move(paddle, paddleX - 60, GraphicsWindow.Height - 12)
EndSub
EJERCICIOS RESUELTOS:
- CONVERSOR DE CENTÍMETROS A PULGADAS:
TextWindow.WriteLine("De centimetros a pulgadas")
TextWindow.Write("Ingresa los centimetros ")
centimetro = TextWindow.ReadNumber()
pulgada = centimetro / 2.54
TextWindow.WriteLine("Son " + pulgada + " pulgadas")
- PROMEDIO DE CUATRO NOTAS:
TextWindow.Write("Ingresa la primera nota ")
nota1 = TextWindow.ReadNumber()
TextWindow.Write("Ingresa la segunda nota ")
nota2 = TextWindow.ReadNumber()
TextWindow.Write("Ingresa la tercera nota ")
nota3 = TextWindow.ReadNumber()
TextWindow.Write("Ingresa la cuarta nota ")
nota4 = TextWindow.ReadNumber()
promedio = (nota1 + nota2 + nota3 + nota4) / 4
TextWindow.WriteLine("El promedio es " + promedio)
- ÁREA RECTÁNGULO:
TextWindow.WriteLine("Area rectangulo")
TextWindow.Write("Ingresa el valor de la
base ")
base = TextWindow.ReadNumber()
TextWindow.Write("Ingresa el valor de la
altura ")
altura = TextWindow.ReadNumber()
area = base * altura
TextWindow.WriteLine("El
area es " + area)
- ÁREA CIRCUNFERENCIA:
pi = Math.Pi
radioCuadrado = Math.Power(radio,2)
area = pi * radioCuadrado
TextWindow.WriteLine("El area es " +
area)
EndSub
TextWindow.Write("Ingresa el largo del radio ")
radio = TextWindow.ReadNumber()
BuscaArea()
- SUMATORIA DE "N" NÚMEROS:
TextWindow.Write("Ingresa un numero ")
numero = TextWindow.ReadNumber()
sumatoria = (numero * (numero + 1)) / 2
TextWindow.WriteLine("La suma de todos los
numeros")
TextWindow.WriteLine("desde
1 hasta "+ numero +" es " + sumatoria)- TABLA DE MULTIPLICAR:
TextWindow.WriteLine("TABLA DE
MULTIPLICAR")
TextWindow.WriteLine("Ingresa un numero
")
numero = TextWindow.ReadNumber()
TextWindow.WriteLine(numero + " x 1 = "
+ numero * 1 )
TextWindow.WriteLine(numero + " x 2 = "
+ numero * 2 )
TextWindow.WriteLine(numero + " x 3 = "
+ numero * 3 )
TextWindow.WriteLine(numero + " x 4 = "
+ numero * 4 )
TextWindow.WriteLine(numero + " x 5 = "
+ numero * 5 )
TextWindow.WriteLine(numero + " x 6 = "
+ numero * 6 )
TextWindow.WriteLine(numero + " x 7 = "
+ numero * 7 )
TextWindow.WriteLine(numero + " x 8 = "
+ numero * 8 )
TextWindow.WriteLine(numero + " x 9 = "
+ numero * 9 )
TextWindow.WriteLine(numero
+ " x 10 = " + numero * 10 )
- TABLA DE MULTIPLICAR CON FOR:
For i = 1 To 10
TextWindow.WriteLine(numero + " x " +
i + " = " +
numero * i)
EndFor
EndSub
TextWindow.WriteLine("Tabla de
multiplicar")
TextWindow.Write("Ingresa un
numero ")
numero = TextWindow.ReadNumber()
tabla()
- TABLA MULTIPLICAR CON WHILE:
TextWindow.Write("Ingresa un numero ")
num1 = TextWindow.ReadNumber()
num2 = 0
While num2 < 10
num2 = num2 + 1
TextWindow.WriteLine(num1 + " x " + num2 + " = " +
num1 * num2 )
EndWhile
- TODAS LAS TABLAS DE MULTIPLICAR:
For a = 1 to 10 Step 1
For b = 1 To 10 Step 1
TextWindow.WriteLine(a + " x " + b + " = " + a*b)
EndFor
EndFor
- REPRESENTACIÓN DE LAS TABLAS DE MULTIPLICAR EN UNA TABLA:
TextWindow.WriteLine("Tabla de
multiplicar como matriz")
For a = 1 To 10
For b = 1 To 10
If a * b < 10 Then
TextWindow.Write(a * b + " ")
Else
TextWindow.Write(a * b + " ")
EndIf
If b = 10 Then
TextWindow.WriteLine("")
EndIf
EndFor
EndFor
- ORDENAR DOS NÚMEROS DE MENOR A MAYOR:
TextWindow.WriteLine("ordena 2
numeros")
TextWindow.Write("Ingresa un
numero ")
a[1] = TextWindow.ReadNumber()
TextWindow.Write("Ingresa otro numero ")
a[2] = TextWindow.ReadNumber()
If a[1] < a[2] Then
b[1] = a[1]
b[2] = a[2]
Else
b[1] = a[2]
b[2] = a[1]
EndIf
TextWindow.WriteLine(b[1] + "," + b[2])
- TRES NÚMEROS DE MENOR A MAYOR:
TextWindow.WriteLine("Ordenar 3
numeros... metodo burbuja")
For i = 1 To 3
TextWindow.Write("Ingresa numero ")
a[i] = TextWindow.ReadNumber()
EndFor
For i = 1 To 3
For j = 0 To 3 - i
If a[j] > a[j + 1] Then
aux = a[j]
a[j] = a[j + 1]
a[j + 1] = aux
EndIf
EndFor
EndFor
TextWindow.WriteLine(a[1] + ","
+ a[2] + "," + a[3])
- ORDENACIÓN DE 5 NÚMEROS POR EL MÉTODO DE LA BURBUJA:
For i = 1 To 5
TextWindow.Write("Ingresa numero ")
a[i] = TextWindow.ReadNumber()
EndFor
For i = 1 To 5
For j = 0 To 5 - i
If a[j] > a[j + 1] Then
aux = a[j]
a[j] = a[j + 1]
a[j + 1] = aux
EndIf
EndFor
EndFor
TextWindow.WriteLine(a[1] +
"," + a[2] + "," + a[3] + "," + a[4] +
"," + a[5])
- USUARIO Y CONTRASEÑA
usuario = "@"
clave = 0
While usuario <> "estudiante"
Or clave <> 12345
TextWindow.Write("Ingresa tu nombre de usuario ")
usuario = TextWindow.Read()
TextWindow.Write("Ingresa tu contraseña ")
clave =
TextWindow.Read()
If usuario = "estudiante" And clave = 12345 Then
TextWindow.WriteLine("Bienvenido al
sistema!!!")
EndIf
If usuario <> "estudiante" Or clave <>
12345 Then
TextWindow.WriteLine("Nombre de
usuario o contraseña no valida")
EndIf
- ADIVINANZA DE UN NÚMERO:
azar
= Math.GetRandomNumber(10)
contador = 0
While
numero <> azar
contador = contador +
1
TextWindow.Write("Adivina el numero oculto, se encuentre entre 1 y
10: ")
numero = TextWindow.ReadNumber()
If numero =
azar Then
TextWindow.WriteLine("Bien
hecho")
TextWindow.WriteLine("Te tomó " + contador + " intentos
adivinar")
EndIf
If numero <
azar Then
TextWindow.WriteLine("Muy bajo")
If contador =
3 then
TextWindow.WriteLine("Se te acabaron los intentos")
Goto salir
EndIf
ElseIf numero
> azar then
TextWindow.WriteLine("Muy alto")
If contador
= 3 then
TextWindow.WriteLine("Se te acabaron los intentos")
Goto salir
EndIf
EndIf
EndWhile
- PROMEDIO CON ARRAYS:
TextWindow.WriteLine("Promediando calificaciones...")
suma = 0
For i = 1 To 7
TextWindow.Write("Ingresa
la nota nro." + i + " ")
nota[i]
= TextWindow.ReadNumber()
suma = suma + nota[i]
EndFor
promedio = suma / 7
TextWindow.WriteLine("El promedio es " + promedio)
- INGRESA TRES NÚMEROS Y SE REPRESENTAN AL REVÉS:
TextWindow.WriteLine("Numero invertido")
TextWindow.Write("Ingresa un numero de 3 digitos ")
numero = TextWindow.ReadNumber()
centena = math.Floor(numero / 100)
decena = math.Floor(Math.Remainder(numero,100) / 10)
unidad = math.Floor(math.Remainder(Math.Remainder(numero,100),10))
TextWindow.Write(unidad)
TextWindow.Write(decena)
TextWindow.WriteLine(centena)
- HIPOTENUSA:
TextWindow.WriteLine("Pitagoras")
TextWindow.Write("Ingresa el primer cateto ")
catetoA = TextWindow.ReadNumber()
cA2 = Math.Power(catetoA, 2)
TextWindow.Write("Ingresa el segundo cateto ")
catetoB = TextWindow.ReadNumber()
cB2 = Math.Power(catetoB,2)
sumaCatetos = cA2 + cB2
hipotenusa = Math.SquareRoot(sumaCatetos)
TextWindow.WriteLine("La
hipotenusa es " +
hipotenusa)
- PARTE DECIMAL DE UN NÚMERO REAL:
TextWindow.WriteLine("Parte decimal")
TextWindow.Write("Ingresa un numero real ")
real = TextWindow.ReadNumber()
decimal = real - Math.Floor(real)
TextWindow.WriteLine("La
parte decimal es " +
decimal)
- DIVISIÓN ENTRE DOS NÚMEROS INDICANDO SI ES EXACTA O NO:
TextWindow.WriteLine("Division
exacta")
TextWindow.Write("Ingresa
el dividendo ")
dividendo = TextWindow.ReadNumber()
TextWindow.Write("Ingresa el
divisor ")
divisor = TextWindow.ReadNumber()
If Math.Remainder(dividendo, divisor) = 0 Then
TextWindow.WriteLine("La
division es exacta")
Else
TextWindow.WriteLine("La division no es exacta")
EndIf
- DADAS DOS PALABRAS INDICAR CUAL ES LA MÁS LARGA:
TextWindow.WriteLine("Cuenta
letras")
TextWindow.Write("Ingresa
una palabra ")
primera = TextWindow.Read()
cuenta1 = Text.GetLength(primera)
TextWindow.Write("Ingresa
otra palabra ")
segunda = TextWindow.Read()
cuenta2 = Text.GetLength(segunda)
mayor = Math.Max(cuenta1,cuenta2)
If mayor = cuenta1 Then
palabraMayor = primera
Else
palabraMayor = segunda
EndIf
diferencia = math.Abs(cuenta1 - cuenta2)
TextWindow.WriteLine(palabraMayor + " es mayor por " + diferencia + " letras")
- DADA LA FECHA DE NACIMIENTO INDICAR CUAL ES SU EDAD:
diaActual = Clock.Day
mesActual = Clock.Month
anyoActual = Clock.Year
TextWindow.WriteLine("Fecha de
nacimiento")
TextWindow.Write("Ingresa el
dia ")
diaNacimiento = TextWindow.ReadNumber()
TextWindow.Write("Ingresa el
mes ")
mesNacimiento = TextWindow.ReadNumber()
TextWindow.Write("Ingresa el
año ")
anyoNacimiento = TextWindow.ReadNumber()
edad = anyoActual - anyoNacimiento
If mesNacimiento < mesActual Then
TextWindow.WriteLine("Tu edad es de
" + edad
+ "
años" )
EndIf
If mesNacimiento = mesActual And diaNacimiento < diaActual Then
TextWindow.WriteLine("Tu edad es de
" + (edad - 1) + " años"
)
EndIf
If mesNacimiento = mesActual And diaNacimiento = diaActual Then
TextWindow.WriteLine("Tu edad es de
" + edad
+ "
años" )
EndIf
If mesNacimiento = mesActual And diaNacimiento > diaActual Then
TextWindow.WriteLine("Tu edad es de
" + edad
+ "
años" )
EndIf
If mesNacimiento > mesActual Then
TextWindow.WriteLine("Tu edad es de
" + (edad - 1) + " años"
)
EndIf
- DADOS LOS LADOS DE UN TRIÁNGULO INDICAR DE QUÉ TIPO ES:
If lado1 = lado2 And lado1 = lado3 Then
TextWindow.WriteLine("Es
equilatero")
EndIf
If lado1 = lado2 And lado1 <> lado3 Or lado1 = lado3 And lado1 <> lado2 Or lado2 = lado3 And lado2 <> lado1 Then
TextWindow.WriteLine("Es
isosceles")
EndIf
If lado1 <> lado2 And lado1 <> lado3 And lado2 <> lado3 Then
TextWindow.WriteLine("Es
escaleno")
EndIf
EndSub
desigual = 0
TextWindow.WriteLine("Desigualdad
triangular")
TextWindow.Write("Ingresa el
lado 1: ")
lado1 = TextWindow.ReadNumber()
TextWindow.Write("Ingresa el
lado 2: ")
lado2 = TextWindow.ReadNumber()
TextWindow.Write("Ingresa el
lado 3: ")
lado3 = TextWindow.ReadNumber()
If lado1 + lado2 < lado3 Then
desigual = desigual + 1
EndIf
If lado1 + lado3 < lado2 Then
desigual = desigual + 1
EndIf
If lado2 + lado3 < lado1 Then
desigual = desigual + 1
EndIf
If desigual > 0 Then
TextWindow.WriteLine("No es un
triangulo valido")
Else
tipo()
EndIf
- POTENCIAS DE DOS HASTA EL NÚMERO INTRODUCIDO
For i = 1 To numero
TextWindow.WriteLine(i + " ^ 2 " +
" = " +
Math.Power(i,2))
EndFor
EndSub
TextWindow.WriteLine("Potencia de
2")
TextWindow.Write("Ingresa un
numero ")
numero = TextWindow.ReadNumber()
potencia()
- SUMATORIO DE ENTRE DOS NÚMEROS INTRODUCIDOS:
TextWindow.WriteLine("Sumatoria
entre dos numeros")
aux = 0
TextWindow.Write("Ingresa un
numero ")
num1 = TextWindow.ReadNumber()
TextWindow.Write("Ingresa otro numero ")
num2 = TextWindow.ReadNumber()
For i = (num1 + 1) To (num2 - 1)
aux = aux + i
EndFor
For j = (num1 + 1) To (num2 - 1)
If j = (num2 - 1) Then
TextWindow.Write(j + " = ")
Else
TextWindow.Write(j + " + ")
EndIf
EndFor
TextWindow.WriteLine(aux)
- DIVISORES DE UN NÚMERO INTRODUCIDO
TextWindow.WriteLine("Divisores")
TextWindow.Write("Ingresa un
numero ")
numero = TextWindow.ReadNumber()
divisor = 0
If Math.Remainder(numero,2) = 0 Then
iterar = numero / 2
Else
iterar = (numero - 1) / 2
EndIf
For i = 1 To iterar
If Math.Remainder(numero,i) = 0 Then
aux = numero / i
If aux <> divisor then
divisor = aux
EndIf
If i = iterar Then
TextWindow.WriteLine(divisor)
Else
TextWindow.Write(divisor + ",")
EndIf
EndIf
EndFor
- DADA LA ALTURA DE UN TRIÁNGULO, DIBUJAR LA FIGURA CON ASTERÍSCOS
TextWindow.WriteLine("Rectangulo")
TextWindow.Write("Alto: ")
alto = TextWindow.ReadNumber()
TextWindow.Write("Ancho: ")
ancho = TextWindow.ReadNumber()
For a = 1 To alto
For b = 1 To ancho
TextWindow.Write("*")
If b = ancho Then
TextWindow.WriteLine("")
EndIf
EndFor
EndFor
- DADA LA ALTURA DE UN TRIÁNGULO DIBUJAR SU FIGURA CON ASTERÍSCOS:
TextWindow.WriteLine("Triangulo")
TextWindow.Write("Alto: ")
alto=TextWindow.ReadNumber()
For x = 1 To alto
For g = 1 To alto
If g<= x Then
TextWindow.Write("*")
EndIf
If g = x Then
TextWindow.WriteLine("")
EndIf
EndFor
EndFor- INTRODUCIDO UN NÚMERO HACER SU SERIE DE COLLATZ:
TextWindow.WriteLine("Secuencia Collatz")
TextWindow.Write("Ingresa numero: ")
numero = TextWindow.ReadNumber()
While numero <> 1
If Math.Remainder(numero, 2) = 0 Then
TextWindow.Write(numero + ",")
numero = numero / 2
Else
TextWindow.Write(numero + ",")
numero = (numero * 3) + 1
EndIf
If numero = 1 Then
TextWindow.WriteLine("1")
EndIf
EndWhile- DADO UN NÚMERO SACAR SERIE DE NÚMEROS MENORES QUE NO SEAN MÚLTIPLOS NI DE 3 NI DE 7:
TextWindow.WriteLine("Numeros naturales menores")
TextWindow.Write("Ingresa un numero ")
num=TextWindow.ReadNumber()
For i = 1 To num
If Math.Remainder(i, 3) <> 0 And Math.Remainder(i, 7) <> 0 Then
TextWindow.WriteLine(i)
EndIf
EndFor- INTRODUCIDA UNA SERIE DE NÚMEROS INDICAR CUANTOS HAN SIDO POSITIVOS Y CUANTOS NEGATIVOS:
TextWindow.Write("Ingresa un numero, cero para finalizar ")
num=TextWindow.ReadNumber()
positivo=0
negativo=0
If num > 0 Then
positivo = positivo + 1
EndIf
If num < 0 Then
negativo = negativo + 1
EndIf
While num <> 0
TextWindow.Write("Ingresa un numero ")
num = TextWindow.ReadNumber()
If num > 0 Then
positivo = positivo + 1
EndIf
If num < 0 Then
negativo = negativo + 1
EndIf
EndWhile
TextWindow.Write("Positivos: ")
For a = 1 To positivo
TextWindow.Write("*")
EndFor
TextWindow.WriteLine("")
TextWindow.Write("Negativos: ")
For b = 1 To negativo
TextWindow.Write("*")
EndFor
TextWindow.WriteLine("")
- INTRODUCIDO UN NÚMERO INDICAR CUÁNTOS DÍGITOS TIENE:
TextWindow.WriteLine("Contando digitos")
TextWindow.Write("Ingresa un numero: ")
numero=TextWindow.ReadNumber()
cociente = 0
divisor = 1
contador = 0'para contar
los bucles
While cociente <> 1
contador = contador + 1
divisor = divisor * 10
cociente = math.Floor(numero / divisor)'para que entregue nros. Enteros
If cociente = 1 Then
TextWindow.WriteLine("El numero tiene " + (contador + 1) + "
digitos")
EndIf
' En caso de que el numero ingresado sea de un
digito...
If numero < 10 Then
TextWindow.WriteLine("Tiene un solo digito")
cociente = 1' para
terminar el bucle
EndIf
EndWhile
- INGRESADO UN NÚMERO DE TRES CIFRAS, INDICAR SI ES CAPICÚA:
TextWindow.WriteLine("Capicua")
TextWindow.Write("Ingresa un numero de 3 cifras ")
numero = TextWindow.ReadNumber()
centena = Math.Floor(numero / 100)
decena = Math.Floor(Math.Remainder(numero,100) / 10)
unidad = Math.Floor(Math.Remainder(Math.Remainder(numero,100),10)/1)
If centena = unidad Then
TextWindow.WriteLine("Es capicua")
Else
TextWindow.WriteLine("No es capicua")
EndIf
- DADO UN NÚMERO INDICAR SI ES POSITIVO, NEGATIVO O CERO:
TextWindow.Write("Ingresa un numero ")
num = TextWindow.ReadNumber()
If num > 0Then
TextWindow.WriteLine("Es positivo")
ElseIf num < 0 then
TextWindow.WriteLine("Es negativo")
Elseif num = 0 Then
TextWindow.WriteLine("Es un cero")
EndIf
- DADOS DOS NÚMEROS INDICAR SI SON MÚLTIPLOS:
TextWindow.WriteLine("Multiplos?")
TextWindow.Write("Ingresa un numero ")
num1 = TextWindow.ReadNumber()
TextWindow.Write("Ingresa otro numero ")
num2 = TextWindow.ReadNumber()
If Math.Remainder(num2,num1) = 0 Then
TextWindow.WriteLine(num2 + " es multiplo de " + num1)
ElseIf Math.Remainder(num1,num2) = 0 Then
TextWindow.WriteLine(num2 + " es multiplo de "+ num1)
Else
TextWindow.Write("No son multiplos")
EndIf
- DADO UN NÚMERO INDICAR SI ES NEGATIVO O POSITIVO Y REPERTIR EL PROGRAMA HASTA QUE SE INTRODUZCA UN CERO:
TextWindow.WriteLine("Positivos y
negativos")
numero = 1
While numero <> 0
TextWindow.Write("Ingresa un numero, ingresa cero para finalizar: ")
numero = TextWindow.ReadNumber()
If numero >
0 Then
TextWindow.WriteLine("Ingresaste un numero positivo")
EndIf
If numero < 0 Then
TextWindow.WriteLine("Ingresaste un numero negativo")
EndIf
EndWhile
- INTRODUCIR NÚMEROS Y QUE DIGA CÚANTOS SE HAN INTRODUCIDO:
TextWindow.WriteLine("Cuenta
numeros")
numero = 1
contador = 0
While numero > 0
TextWindow.Write("Ingresa un numero, ingresa negativo para finalizar:
")
numero = TextWindow.ReadNumber()
contador = contador + 1
EndWhile
TextWindow.WriteLine("Numeros
ingresados: " + contador)
- MÍNIMO COMÚN MÚLTIPLO DE DOS NÚMEROS INTRODUCIOS:
'minimo comun multiplo
'primero busco el numero mayor
TextWindow.WriteLine("Ingresa
3 numeros: ")
mayor = 0
casilla = 0
For i = 1 To 3
TextWindow.Write(i + ": ")
num[i] = TextWindow.ReadNumber()
If num[i] > mayor Then
mayor = num[i]
EndIf
EndFor
interruptor = 0
multiplicador = 0
multiplo = 0
While interruptor = 0
contador = 0
multiplicador = multiplicador
+ 1
multiplo = mayor * multiplicador
For i = 1 To 3
If Math.Floor(Math.Remainder(multiplo,num[i])) = 0 Then
contador = contador + 1
EndIf
EndFor
If contador = 3 Then
interruptor = 1'para salir
del while
EndIf
EndWhile
TextWindow.WriteLine("El
M.C.M. es: "+ multiplo)
'divido
el nro mayor por todos los demas y veo si el resto es cero, si es cero entonces
son
'multiplos.
Ej:
'si
ingreso los nros: 2,4,6. El mayor es 6 y lo divido por todos. Con cada resto cero agrego
'un
valor a contador. Si acumulo 3 contadores entonces los 3 numeros son divisores
y salgo
'del
bucle. Como 4 no es divisor de 6, entonces aumento un valor en la variable
multiplo
'entonces
se verifica 6 * 2, o sea 12 y veo si 12 es divisible por 12, 2 y por 4. Como es
cierto
'entonces 12 es el minimo comun multiplo
- DIBUJAR UN CUADRADO:
For x = 100 To 200
GraphicsWindow.SetPixel(x, 50, "blue")
GraphicsWindow.SetPixel(x, 150, "blue")
EndFor
For y = 50 To 150
GraphicsWindow.SetPixel(100, y, "red")
GraphicsWindow.SetPixel(200, y, "red")
EndFor- DIBUJAR UN CUADRADO CON LÍNEAS:
GraphicsWindow.DrawLine(100,10,100,100)'vertical derecha'
GraphicsWindow.DrawLine(10,10,100,10)'horizontal superior
GraphicsWindow.DrawLine(10,100,100,100)'horizontal inferior
- DIBUJAR UN RECTÁNGULO:
GraphicsWindow.BrushColor = "red"
GraphicsWindow.DrawRectangle(50,50,100,100)
- DIBUJAR UNA DIAGONAL:
For d = 50 To 150
GraphicsWindow.SetPixel(d, d, "blue")
EndFor- DIBUJAR UN TRIÁNGULO:
For a = 50 To 150
GraphicsWindow.SetPixel(a, a, "blue")
EndFor
For b = 50 To 150
GraphicsWindow.SetPixel(50, b, "red")
EndFor
For c = 50 To 150
GraphicsWindow.SetPixel(c, 150, "green")
EndFor
- DIBUJAR UN TRIÁNGULO:
GraphicsWindow.DrawTriangle(0,100,100,100,50,10)
'(0,100) = vertice izquierdo
'(100,100) = vertice derecho
'(50,10) = vertice
superior
- DIBUJAR LÍNEAS DE DISTINTO GROSOR:
GraphicsWindow.BackgroundColor = "black"
GraphicsWindow.PenColor = "red"
For i = 1 To 10
GraphicsWindow.PenWidth = i
GraphicsWindow.DrawLine(10,10 * i,100, i * 10)
EndFor
- DIBUJAR CÍRCULOS:
GraphicsWindow.PenColor = "Red"
GraphicsWindow.DrawEllipse(10, 10, 100, 100)
GraphicsWindow.BrushColor = "blue"
GraphicsWindow.FillEllipse(60, 100, 150, 150)
- LÍNEAS DE VARIOS COLORES:
GraphicsWindow.PenColor = GraphicsWindow.GetRandomColor()
GraphicsWindow.DrawLine(50, 50 + i, 300, 50 + i)
EndFor
- CÍRCULOS DE VARIOS COLORES:
GraphicsWindow.BackgroundColor = "Black"
GraphicsWindow.Width = 200
GraphicsWindow.Height = 200
For i = 1 To
100 Step 5
GraphicsWindow.PenColor =
GraphicsWindow.GetRandomColor()
GraphicsWindow.DrawEllipse(100 -
i, 100 - i, i * 2, i * 2)
EndFor
- TEXTOS EN VENTANA GRÁFICAS:
GraphicsWindow.FontSize = "10"
GraphicsWindow.DrawText(10,10, "Hola")
GraphicsWindow.FontSize = "14"
GraphicsWindow.DrawText(10,25, "Hola")
GraphicsWindow.FontSize = "18"
- EVENTO: MOVIMIENTO DE UN CÍRCULO CON EL TECLADO:
x = 0
y = 0
circulo =
Shapes.AddEllipse(50,50)' Añade un
circulo de 50x50
GraphicsWindow.KeyDown
= presionar
Sub derecha
x = x + 2
Shapes.move(circulo,x,y)
EndSub
Sub izquierda
x = x - 2
Shapes.Move(circulo,x,y)
EndSub
Sub abajo
y = y + 2
Shapes.Move(circulo,x,y)
EndSub
Sub arriba
y = y - 2
Shapes.Move(circulo,x,y)
EndSub
Sub
presionar
flecha = GraphicsWindow.LastKey
If flecha = "Right" Then
derecha()
EndIf
If flecha = "Left" Then
izquierda()
EndIf
If flecha = "Down" Then
abajo()
EndIf
If flecha = "Up" Then
arriba()
EndIf
EndSub- EVENTO DE SALUDO
texto = Controls.AddTextBox(10,30)
Controls.AddButton("Enviar",10,60)
Controls.ButtonClicked = btnEnviar
Sub btnEnviar
nombre = Controls.GetTextBoxText(texto)
GraphicsWindow.DrawText(10,90,"Bienvenido " + nombre)
EndSub
Sub inicio
GraphicsWindow.DrawText(10,10, "Ingresa
tu nombre")
texto = Controls.AddTextBox(10,30)
Controls.AddButton("Enviar",10,60)
EndSub
Controls.ButtonClicked
= btnEnviar
Sub btnEnviar
nombre
= Controls.GetTextBoxText(texto)
GraphicsWindow.Clear()
GraphicsWindow.DrawText(10,90,"Bienvenido
" + nombre)
inicio()
EndSub
inicio()
y = 90
GraphicsWindow.DrawText(10,10,
"Ingresa tu nombre")
texto =
Controls.AddTextBox(10,30)
Controls.AddButton("Enviar",10,60)
Controls.ButtonClicked =
btnEnviar
Sub
btnEnviar
nombre = Controls.GetTextBoxText(texto)
GraphicsWindow.DrawText(10,y,"Bienvenido " + nombre)
y = y + 20
EndSub- BOTONES GRÁFICOS
'opciones
GraphicsWindow.FontSize = 14
GraphicsWindow.BrushColor = "black"
objetos = Controls.AddButton("1) Objetos",20,60)
armas = Controls.AddButton("2) Armas",20,100)
accesorios = Controls.AddButton("3)
Accesorios",20,140)
estado = Controls.AddButton("4) Estado",20,180)
salir = Controls.AddButton("5) Salir",20,220)
'Control de lo botones
Controls.ButtonClicked =
botonPresionado
Sub botonPresionado
ultimoBoton = Controls.LastClickedButton
If ultimoBoton = objetos Then
GraphicsWindow.Clear()
menuObjetos()
EndIf
EndSub
Sub menuObjetos
GraphicsWindow.BackgroundColor
= "black"
GraphicsWindow.PenColor = "white"
GraphicsWindow.PenWidth = 4
GraphicsWindow.DrawRectangle(5,5, 390,290)
pocion = "c:\img\potion.png"
GraphicsWindow.DrawResizedImage(pocion,230,80, 128,128)
GraphicsWindow.FontSize = 18
GraphicsWindow.BrushColor = "white"
GraphicsWindow.DrawText(20,20, "OBJETOS")
GraphicsWindow.FontSize = 14
GraphicsWindow.DrawText(20,50, "Poción
curativa x 10")
GraphicsWindow.DrawText(20,80, "Cola de
fenix x 5")
GraphicsWindow.DrawText(20,110, "Poción de mana x 3")
EndSub
Sub menu
'Alto y ancho
de la ventana
GraphicsWindow.Height =
300
GraphicsWindow.Width = 400
GraphicsWindow.CanResize = "false"
'fondo de la ventana
fondo = "c:\img\03.png"
GraphicsWindow.DrawImage(fondo,0,0)
'titulo
GraphicsWindow.FontSize = 18
GraphicsWindow.BrushColor = "white"
GraphicsWindow.DrawText(20,20, "INVENTARIO")
'opciones
GraphicsWindow.FontSize = 14
GraphicsWindow.BrushColor = "black"
objetos = Controls.AddButton("1) Objetos",20,60)
armas = Controls.AddButton("2) Armas",20,100)
accesorios = Controls.AddButton("3)
Accesorios",20,140)
estado = Controls.AddButton("4) Estado",20,180)
salir = Controls.AddButton("5) Salir",20,220)
'terra
terra = "c:\img\terra.png"
GraphicsWindow.DrawResizedImage(terra,230,80, 128,128)
EndSub
'Control de lo botones
Controls.ButtonClicked =
botonPresionado
Sub botonPresionado
ultimoBoton = Controls.LastClickedButton
If ultimoBoton = objetos Then
GraphicsWindow.Clear()
menuObjetos()
ElseIf
ultimoBoton =
volver then
GraphicsWindow.Clear()
menu()
Elseif
ultimoBoton =
armas then
GraphicsWindow.Clear()
menuArmas()
elseif
ultimoBoton =
accesorios then
GraphicsWindow.Clear()
menuAccesorios()
elseif ultimoBoton = estado then
GraphicsWindow.Clear()
menuEstado()
elseif
ultimoBoton =
salir then
Program.End()
EndIf
EndSub
Sub menuObjetos
GraphicsWindow.BackgroundColor
= "black"
GraphicsWindow.PenColor = "white"
GraphicsWindow.PenWidth = 4
GraphicsWindow.DrawRectangle(5,5, 390,290)
pocion = "c:\img\potion.png"
GraphicsWindow.DrawResizedImage(pocion,230,80, 128,128)
GraphicsWindow.FontSize = 18
GraphicsWindow.BrushColor = "white"
GraphicsWindow.DrawText(20,20, "OBJETOS")
GraphicsWindow.FontSize = 14
GraphicsWindow.DrawText(20,50, "Poción
curativa x 10")
GraphicsWindow.DrawText(20,80, "Cola de
fenix x 5")
GraphicsWindow.DrawText(20,110, "Poción de
mana x 3")
GraphicsWindow.BrushColor = "black"
volver = Controls.AddButton("Volver",20,150)
EndSub
Sub menuArmas
GraphicsWindow.BackgroundColor
= "black"
GraphicsWindow.PenColor = "white"
GraphicsWindow.PenWidth = 4
GraphicsWindow.DrawRectangle(5,5, 390,290)
hacha = "c:\img\hacha.png"
GraphicsWindow.DrawResizedImage(hacha,230,80, 128,128)
GraphicsWindow.FontSize = 18
GraphicsWindow.BrushColor = "white"
GraphicsWindow.DrawText(20,20, "ARMAS")
GraphicsWindow.FontSize = 14
GraphicsWindow.DrawText(20,50, "Mandoble x 1")
GraphicsWindow.DrawText(20,80, "Hacha x 1")
GraphicsWindow.DrawText(20,110, "Daga x 1")
GraphicsWindow.BrushColor = "black"
volver = Controls.AddButton("Volver",20,150)
EndSub
Sub menuAccesorios
GraphicsWindow.BackgroundColor
= "black"
GraphicsWindow.PenColor = "white"
GraphicsWindow.PenWidth = 4
GraphicsWindow.DrawRectangle(5,5, 390,290)
aro = "c:\img\aros.png"
GraphicsWindow.DrawResizedImage(aro,230,80, 128,128)
GraphicsWindow.FontSize = 18
GraphicsWindow.BrushColor = "white"
GraphicsWindow.DrawText(20,20, "ACCESORIOS")
GraphicsWindow.FontSize = 14
GraphicsWindow.DrawText(20,50, "Aro de
fuerza x 1")
GraphicsWindow.DrawText(20,80, "Collar de
magia x 1")
GraphicsWindow.DrawText(20,110, "Guante
Gengi x 1")
GraphicsWindow.BrushColor = "black"
volver = Controls.AddButton("Volver",20,150)
EndSub
Sub menuEstado
GraphicsWindow.BackgroundColor
= "black"
GraphicsWindow.PenColor = "white"
GraphicsWindow.PenWidth = 4
GraphicsWindow.DrawRectangle(5,5, 390,290)
warrior = "c:\img\warr.png"
GraphicsWindow.DrawResizedImage(warrior,230,80, 128,128)
GraphicsWindow.FontSize = 18
GraphicsWindow.BrushColor = "white"
GraphicsWindow.DrawText(20,20, "ESTADO")
GraphicsWindow.FontSize = 14
GraphicsWindow.DrawText(20,50, "Nivel :
10")
GraphicsWindow.DrawText(20,80, "Ataque:
15")
GraphicsWindow.DrawText(20,110, "Defensa:
3")
GraphicsWindow.DrawText(20,140, "Inteligencia:
3")
GraphicsWindow.DrawText(20,170, "Agilidad:
9")
GraphicsWindow.DrawText(20,200, "Destreza:
12")
GraphicsWindow.DrawText(20,230, "Suerte: 2")
GraphicsWindow.BrushColor = "black"
volver = Controls.AddButton("Volver",20,260)
EndSub
Juego gráfico dinámico:
https://social.technet.microsoft.com/wiki/contents/articles/20865.small-basic-dynamic-graphics.aspx
https://social.technet.microsoft.com/wiki/contents/articles/20865.small-basic-dynamic-graphics.aspx