tutorial_de_aventuras_en_basic

¡Esta es una revisión vieja del documento!


Tutorial de BASIC: "Crea tu propia aventura"

Este tutorial te presenta generalidades, pero está pensado siguiendo el dialecto GW-BASIC. Puedes usar PC-BASIC.

¿Alguna vez has leído uno de esos libros de cuentos de “Sigue tu propia aventura”? En ellos leías algunos párrafos y luego debías tomar una decisión por el personaje principal. Luego pasas a otra página del libro y continuabas la historia. Podías interactuar así con las aventuras que seguía el personaje. Este tipo de libros son divertidos. Lo que es aún más divertido es escribir tu propio programa BASIC para hacer lo mismo.

El programa que abordaremos en este tutorial presentan una pantalla llena de historias y luego se te pide que tomes una decisión. Tu decisión hará que aparezca otra pantalla de la historia. En el camino, aprenderemos algunas declaraciones BÁSICAS más. Verá cómo se toman las decisiones en un programa de computadora y cómo la ejecución puede saltarse dentro de un programa.

Para comenzar, ingrese estas primeras veintiocho líneas del programa exactamente como están escritas. Asegúrese de presionar ENTER después de cada línea. Una pista: después de escribir la línea 70 y presionar ENTER, puede mover el cursor hacia atrás hasta el número de línea, cambiarlo a 80 y presionar ENTER nuevamente. Esto ahorra mucho escribir. Use LIST con frecuencia para verificar su progreso.

10  REM *************************************************************
20  REM *  HISTORIA                                                 *
30  REM *  "Crea tu propio destino" - Una historia arbolada         *
40  REM *************************************************************
50  CLS
60  PRINT "**********************************************************"
70  PRINT "*                                                        *"
80  PRINT "*                                                        *"
90  PRINT "*                                                        *"
100 PRINT "*       Esta es la primer pantalla de tu historia        *"
110 PRINT "*                                                        *"
120 PRINT "*                                                        *"
130 PRINT "*                                                        *"
140 PRINT "*                                                        *"
150 PRINT "*                                                        *"
160 PRINT "*                                                        *"
170 PRINT "*                                                        *"
180 PRINT "*       Elije:                                           *"
190 PRINT "*                                                        *"
200 PRINT "*         1 - Quiero seguir un destino                   *"
210 PRINT "*         2 - Quiero buscar otro destino                 *"
220 PRINT "*                                                        *"
230 PRINT "*                                                        *"
240 PRINT "*                                                        *"
250 PRINT "*                                                        *"
260 PRINT "**********************************************************"
270 INPUT OPCION%
280 IF OPCION% = 2 THEN GOTO 600 ELSE GOTO 300

Observa las líneas 10 a 40. REM es una declaración de BASIC que no hace nada, significa “comentario”. El propósito de REM es agregarle comentarios al programa. Estos comentarios ayudan al programador a comprender cómo funciona el programa. Las palabras a continuación de REM no se imprimen en pantalla durante la ejecución. Solo son visibles listando el código fuente.

Los comentarios son importantes. Cuando termines de escribir tu programa, probablemente comprendas todo de él. Sin embargo, transcurridos unas semanas te resultará irreconocible Los comentarios ayudan. A diferencia de la era del BASIC de Darthmouth, hoy la memoria es prácticamente gratuita! Por lo tanto ¡Usa REM generosamente!

El pequeño rectángulo hecho de asteriscos se llamaba caja de flores. Se acostumbraba colocar el nombre del programa, en este caso, HISTORIA, junto con una breve descripción del cometido del programa. Generealmente la caja de flores solía tener 40 caracteres de ancho. De hecho, algunos programas contenían más comentarios que describen el programa que líneas de instrucciones de BASIC a interpretar. Los asteriscos no tienen relevancia alguna en este caso. Podrás utilizar cualquier carácter. El propósito es únicamente proporcionar un atractivo cartelón informativo.

La línea 270 es una instrucción INPUT. INPUT detiene el programa y espera la entrada del teclado. Lo ingresado con el teclado, en la línea 270, se almacenará en una variable denominada OPCION%. Dado que las variables juegan rol importante en la programación, debemos examinarlas en detalle.

Nombres de Variables

Los nombres de variables deben crearse de acuerdo con ciertas reglas en BASIC. Por ejemplo, los nombres de variables deben comenzar con una letra del alfabeto y no puede tener más de cuarenta caracteres. El nombre puede incluir números. Estas son las reglas de BASIC, y no son muy estrictas. ¡Pero es igual de importante inventar nombres de variables que sean significativos para los seres humanos! Después de todo, BASIC funciona igual de bien con una variable llamada TKBRYIOPESFG% que con una llamada OPCION%. Pero, ¿cuál crees que sería más fácil de entender?

La elección de los nombres de las variables es importante ya que un programa puede tener muchas de ellas. Si usas nombres son confusos, podrías confundir accidentalmente una variable con otra. Por demás, resiste la tentación de inventar nombres de variables lindos e ingeniosos. Nombres como RENGO$ y PORDIOSERA$ son divertidos de imaginar pero difíciles para seguir. Un buen programa debe ser fácil de entender, por lo cual emplea nombres de variables obvios. NOMBRE$ no puede sonar muy épico, pero al menos es evidente qué datos incorpora.

Ciertas palabras no se pueden utilizar como nombres de variables. Estas se llaman PALABRAS RESERVADAS e incluyen todos los comandos de BASIC. Por ejemplo, sabemos que PRINT y CLS son instrucciones de BASIC. Por lo tanto, no podrás utilizarlos también como nombres de variables ya que confundirían al intérprete computarizado. La lista de palabras reservadas es bastante larga. Entre estas palabras se incluyen palabras como NAME y PRINT. Si bien no es posible duplicar exactamente estas palabras como nombres de variables, puede usar nombres que incluyan la palabra reservada, por ejemplo NAMES o PRINTER, que podrían utilizarse perfectamente.

Aunque BASIC consta de una larga lista de palabras reservadas para el idioma inglés, es probable casi ninguna sea molesta en castellano. La mayoría son declaraciones bastante extrañas que no serían muy útiles como nombres de variables. Cuando utilices una palabra reservada como nombre de variable, BASIC emitirá su inefable error de sintaxis “SYNTAX ERROR”. A menudo, este tipo de errores son desconcertantes. La línea de BASIC podría parecer correcta en todos los sentidos. BASIC ni siquiera insinúa que has utilizado una palabra reservada. BASIC solo entiende que tu programa ha estipulado un comando BASIC incorrectamente. Prueba un programa con la declaración INPUT DATE$ para comprender cómo se ve este error.

Aquí hay una lista de las reglas para tu nombre de variable:

  • No uses mas de 40 caracteres.
  • El nombre de variable debe comenzar con una letra.
  • El nombre de variable puede contener letras y números.
  • Un nombre de variable no puede contener espacios.
  • El nombre no puede ser un comando de BASIC.

Tipos de Variable

Compara la declaración INPUT en la línea 270 con la declaración INPUT del capítulo uno. Observe los nombres de las variables utilizadas en cada programa. En el primer programa usamos el nombre QUIEN$. En la línea 270 tenemos OPCION%. Ambos nombres son variables. Sin embargo, son diferentes. QUIEN$ y OPCION% son ejemplos de dos tipos diferentes de variables utilizadas en BASIC.

Anteriormente definimos un nombre de variable como un casilla de correo. Disponíamos de varios tipos de buzones. Dos números de espera. El otro tiene caracteres y números. Por lo tanto, cuando se define una variable, debes decidir qué tipo de buzón será. El tipo de variable está determinado por el último carácter del nombre de la variable. Esto explica la diferencia entre QUIEN$ y OPCION%.

Un nombre de variable terminado con signo de porcentaje (%) se denomina variable entera. Este tipo de variable solo puede contener números enteros. Esto significa que OPCION% solo puede contener números tales como 2, 45, 611 o 10451. No puede contener números fraccionales como 2,5 o 25,75. Por lo tanto, al programar con la instrucción INPUT OPCION%, el usuario solo podrá ingresar un número entero. Si ingresase letras, BASIC emitiría el mensaje:

?Redo from start

…y el programa no continuaría sino hasta que ingresase números enteros. Por otro lado, si el usuario ingresa un número que no es entero, BASIC lo redondeará al entero más cercano. Por ejemplo, si se ingresa 23.6 al pedido de OPCION%, BASIC asignará 24 a dicha variable, sin emitir mensaje de error alguno. Las variables enteras no pueden contener números no mayores de 32.767 ni menores de -32.768.

Para explorar cómo BASIC maneja las variables enteras, intente ingresarle a la variable varios números, tanto enteros como fraccionales, así como con letras. a este sencillo programa:

10 PRINT "Ingresa algo:"
20 INPUT OPCION%
30 PRINT OPCION%

Un segundo tipo de variable se denomina Variable de Precisión, y van terminadas en un signo de exclamación (!). Estas puede contener números fraccionarios como 35,9 o 3,14159, así como números enteros. Podrá contener casi cualquier valor que necesitemos en nuestros programas. Dado que la variable de precisión puede contener números enteros al igual que las variables enteras, cabría preguntarse para qué usaríamos las variables enteras… nomás para molestar. Pero existen dos razones. En primer lugar, los programas escritos con variables enteras se interpretaban más velozmente que aquellos que utilizaban variables de precisión simple. En segundo lugar, es más fácil escribir un programa que utilice unicamente números enteros. Esto se hará evidente a medida que aprendamos más sobre la programación.

Sigue esta regla: usa variables enteras toda vez que puedas. Usa variables de precisión sólo cuando debas.

El último tipo de variable que exploraremos es la Variable de Cadena (STRING). El nombre de una variable de cadena termina con un signo peso ($). QUIÉN$ es una variable de cadena. Estas variables de cadena contienen caracteres en lugar de números. Una sola variable de cadena puede contener hasta 255 caracteres. Estos caracteres pueden ser cualquiera de caracteres alfanuméricos, incluidos espacios y números (sin incluir letras acentuadas ni eñes).

He aquí una pequeña posibilidad de confusión que debes atender.

Las cifras, no los números, pueden ser caracteres. Considera la diferencia entre numerales y números. El número romano V, la palabra cinco y el número 5 representan el mismo número. Sólo se diferencian en la manaera de escribirlo. Cada vez que almacenas un número como una variable de cadena, será solo un NOMBRE para un número. Esto será importante al hacer aritmética con variables. Podrías tomar dos variables enteras, por ejemplo, y sumarlas. Si intentases esto con variables de cadena, BASIC emitirá un mensaje de error. BASIC está imposibilitado de hacer aritmética con variables de cadena incluso si estas variables contienen nombres de números.

Suena más complicado de lo que es en realidad.

Recuerda: si necesita una variable que contenga caracteres, use una variable de cadena. Si, en cambio, necesita realizar un cálculo, usa un número entero o una sola variable de precisión.

Ejemplos de Variables

Study these example of variables to check your understanding.

Name Contents Description Team1$ Hokies Horrect. DATE$ Incorrect. DATE$ is a reserved word. NUMBER% 123 Correct. STREET% 10 downing incorrect. Integer variables can only contain a number. STREET$ 10 Downing correct 1STPLACE$ Incorrect. Variable names must begin with a letter. COUNT% 45321 Incorrect. Numbers larger than 32,767 cannot be held in an integer variable. GASLEFT! 855.66 Correct. TONE% 600.8 BASIC will round TONE% to 601. WHO$ Elmer P. Fudd Correct.

At line 280 we finally arrive at the real power of programming: the ability to make decisions. BASIC uses the IF-THEN-ELSE statement to make choices, and even change the way the program runs depending on certain conditions. Since the result depends on conditions, the IF statement is called a conditional instruction. Contrast line 280 with all the lines that are listed before it. In every case, BASIC will carry out whatever the instruction asks. But at line 280, BASIC is testing our integer variable CHOICE% to see if it holds the number two. If it does, one result happens. If it does not, another action is taken.

The IF statement has three parts:

IF condition THEN alternative 1 ELSE alternative 2

The three parts are the condition, alternative 1, and alternative 2. The condition is some relationship that BASIC tests to see if it is true. On line 280, the conditional test is whether CHOICE% equals 2. Alternative 1 and alternative 2 are the two choices BASIC can make. If the condition is true, then alternative 1 is executed. If the condition is not true, then alternative 2 is executed. In other words, if the person running our STORY program enters a 2 in response to line 270, then the condition is true, and GOTO 600 is executed (Don't worry about what GOTO means, we'll cover it soon). If the person enters anything other than a 2, GOTO 300 is executed.

The two alternatives listed inside of the IF statement can be any ordinary BASIC commands. In this case, both are GOTO statements. They could just as readily be PRINT or CLS commands. For example:

280 IF CHOICE% = 2 THEN CLS ELSE PRINT "Hey Cool"

In our example, CHOICE% is a integer variable. Other variable types may also be used. We could change CHOICE% to CHOICE! and still see if it equalled 2. String variables can likewise be tested.

280 IF WHO$ = "Brian" THEN PRINT "Hi" ELSE PRINT "Who are you?"

Notice that the character string Brian is enclosed in quotation marks. Remember our discussion of the PRINT statement from chapter one. Quotation marks tell BASIC to use the characters exactly as we have written them. If Brian were not in quotation marks, BASIC would try to use it as a variable name. When the program runs, the person at the keyboard does not have to enter quotation marks.

One further note about testing string variables: computers are dumb. They only do exactly what you tell them to do. If you ran the above line of BASIC and entered brian or BRIAN, the program would print

Who are you?

BRIAN is not the same as Brian. A character string inside of quotation marks must EXACTLY match the contents of the variable. The letters, capitalization, even the number of blank spaces, if any, must exactly match. This can be very challenging to a programmer.

The last part of the IF-THEN-ELSE statement is not always required. The ELSE may be omitted along with the second alternative. This would leave us with an IF-THEN command. We could write line 280 as:

280 IF CHOICE% = 2 THEN GOTO 600

If CHOICE% does not equal two, then the first alternative would not be executed. Instead, BASIC would continue with the next line after 280. If that line happened to be line 300 the two IF statements would produce the same result! Thus, every IF statement has an ELSE even if the ELSE is not written as part of the instruction.

In all of our examples so far, we have tested to see if a variable is equal to some value. Other tests can be used. We can use all of the ordinary arithmetic comparisons such as greater than, less than, or not equal. Here is how these OPERATORS, as they are called, are written:

= equal to

< less than

greater than

⇐ less than or equal to

⇒ greater than or equal to

<> not equal to

With the exception of the last, these operators should be familiar. When used in a BASIC program, the operators that have more than one character, such as ⇒, are written without a space between the two characters. Here are some sample IF-THEN statements.Review each one to check your understanding.

280 IF CHOICE% = 2 THEN GOTO 600 ELSE GOTO 300
290 IF CHOICE% <> 2 THEN GOTO 300 ELSE GOTO 600
300 IF GUESS% = NUMBER% THEN GOTO 140
310 IF GUESS% > NUMBER% THEN PRINT "Too High"
320 IF GUESS% < NUMBER% THEN PRINT "Too Low"
330 IF SUB! <= 0 THEN GOTO 500
340 IF SUB! => 4 THEN GOTO 500
350 IF ANSWER$ = "y" THEN ANSWER$ = "Y"
360 IF QUANTITY% - SUB% < 1 THEN GOTO 600
370 IF X% = 2 THEN TWOS% = TWOS% + 1

These statements are not a real program. Don't bother to enter them on your computer. They are for examples, only. Let's discuss some. Line 290 above is a different way of writing line 280 in our STORY program. Note that it has exactly the same effect. Compare the two lines.

In line 300, we compare two variables! Also, note that line 300 does not use an ELSE command. Line 300, and the rest of the examples, are simple IF-THEN statements. Line 310 asks if the number contained in GUESS% is greater than the number contained in NUMBER%. Line 320 tests if GUESS% is less than NUMBER%.

Lines 330 and 340 use less than or equal to and greater than or equal to.

Line 350 is interesting. This checks what is held inside string variable ANSWER$. If it is a lower case “y” then the program changes it to an upper case “Y” inside the variable. Remember that the condition is tested first, and then, only if true, will alternative 1 be executed. This is why the same variable name, ANSWER$, can be used in the conditional test and then changed in the alternative.

Line 360 is an advanced example. BASIC subtracts SUB% from QUANTITY% and then checks to see if this number is less than one. We will explore arithmetic more later. Just consider this example as one of the more powerful uses of the IF-THEN statement. GOTO

When we first looked at the IF-THEN-ELSE statement in line 280 of our STORY program, we saw that both alternative 1 and alternative 2 used GOTO statements. Now it is time to discuss GOTO.

Fortunately, GOTO is much simpler than IF-THEN-ELSE. When running a program, the BASIC interpreter usually executes statements in line number order. However, when a GOTO is discovered, execution BRANCHES to whatever line number is written as part of the GOTO statement. Line 280 contains two GOTO commands.

280 IF CHOICE% = 2 THEN GOTO 600 ELSE GOTO 300

If CHOICE% is 2 then the next line to execute is line 600. If CHOICE% is not 2, then the next line to execute is line 300.

The GOTO command is useful inside of an IF-THEN statement. It can also be used by itself. To fully understand how this statement works, experiment with the following program:

10 PRINT "This is line 10"
20 GOTO 50
30 PRINT "This is line 30"
40 GOTO 70
50 PRINT "This is line 50"
60 GOTO 30
70 END

GOTO provides the ability to skip around in a program. When our little program runs, it will execute the lines in this order:

10 PRINT "This is line 10"
20 GOTO 50
50 PRINT "This is line 50"
60 GOTO 30
30 PRINT "Esto es la línea 30"
40 GOTO 70
70 END

If you made a mistake in entering this program, you may have discovered something called a LOOP. A loop occurs when the program does not end. Examine this program:

10 PRINT “Esto es la línea 10” 20 GOTO 10

Line 10 will be executed over and over. Indeed, you must press the CTRL-Break key to end the program. In this example, the cause of the loop is clear. Line 20 asks BASIC to execute line 10. Then BASIC executes line 20 again. BASIC does not know that it already executed line 20. Remember, your computer will only do exactly what you tell it to do.

Unfortunately, the cause of loops is not always as clear as in this last example. In long programs, many GOTO statements might be used and it is difficult to see exactly how a loop was created. For this reason, try to avoid using GOTO. Think carefully about your program and plan it so that a GOTO is used only when necessary. A program using many GOTOs is called SPAGHETTI CODE. Understanding spaghetti code is like following a noodle in a plate of spaghetti.

With the IF-THEN and GOTO statements, we introduced the ability to make decisions and change direction. These are powerful capabilities. We know that, although the computer is going to run one line after another, these statements may not necessarily run in line number order. Because of this we must spend some effort thinking about the LOGIC of our programs. This is the part where clear thinking is needed.

Consider line 280 once again:

280 IF CHOICE% = 2 THEN GOTO 600 ELSE GOTO 300

In our PRINT statements in lines 200 and 210, we asked the person running STORY to enter a 1 or a 2. But in line 280 we only check to see if they entered a 2. Why?

The reason: you cannot trust humans! Just because we asked for a 1 or 2 does not mean people will enter a 1 or 2. What if they enter zero or three? We are protected, however, because we built our program to handle any reply. In this case, choice 1 is the default choice. If they just press ENTER, or enter any number other than 2, they will GOTO 300. A default is what happens when someone does not make a decision.

When you write your IF-THEN and GOTO statements, always plan for any input. Don't trust humans. If you ask for a 1, 2, or 3, you can be sure that someone will try a 4. If you do not want to plan for a default choice, you might write an IF-THEN statement that traps the bad choices and simply asks the question again. We could, for example, write:

280 IF CHOICE% = 2 THEN GOTO 600
281 IF CHOICE% = 1 THEN GOTO 300
282 IF CHOICE% < 1 THEN GOTO 50
283 IF CHOICE% >> 2 THEN GOTO 50

There is nothing wrong with using these lines in our STORY program. It is a matter of taste. The original line 280 handles all possible replies in only one line of BASIC code. The above solution uses four lines and the purpose is not as clear. Nevertheless, do what you think is best. Keep in mind our goal of writing understandable programs.

When planning programs you not only have to watch out for humans, you must also think like a computer. Just as we saw in the loop, your computer is going to do what you tell it to do. This may not be what you want it to do! As a human, it is easy to see that “Leonardo” is practically the same as “leonardo.” But the computer is not practical.

Consider this example:

280 IF CHOICE% < 1 THEN GOTO 500
290 IF CHOICE% > 1 THEN GOTO 700

We might believe we are checking to see if someone is cheating on an INPUT statement. But what happens if someone enters a 1? Is the computer doing what we asked? Certainly. Is it doing what we want? That depends. Whenever your program misbehaves, it might help to carefully review each statement IN ORDER OF EXECUTION. On a note pad, write down the names of the variables and keep track of what they should hold as you run the program step-by-step in your imagination.

This chapter began with the promise of a program that would tell a story and allow you to create your own ending. Now that we have explored the new BASIC commands used in the first twenty eight lines, it is time to enter the rest of the program.

As you enter this program, try to type as little as possible. Notice that many lines are either identical or very much alike. For example, lines 60, 260, 320, and 520 are the same. After you press ENTER for line 60, just move the cursor up, change the line number, and press ENTER again. Use LIST to check your progress.

300 REM *****  PANTALLA 1A  *****
310 CLS
320 PRINT "**********************************************************"
330 PRINT "*                                                        *"
340 PRINT "*                                                        *"
350 PRINT "*                                                        *"
360 PRINT "*       Esta es la pantalla 1A de tu historia            *"
370 PRINT "*                                                        *"
380 PRINT "*                                                        *"
390 PRINT "*                                                        *"
400 PRINT "*                                                        *"
410 PRINT "*                                                        *"
420 PRINT "*                                                        *"
430 PRINT "*                                                        *"
440 PRINT "*       Choose one:                                      *"
450 PRINT "*                                                        *"
460 PRINT "*         1 - if you want to go down one path            *"
470 PRINT "*         2 - if you want to go another way              *"
480 PRINT "*                                                        *"
490 PRINT "*                                                        *"
500 PRINT "*                                                        *"
510 PRINT "*                                                        *"
520 PRINT "**********************************************************"
530 INPUT CHOICE%
540 IF CHOICE% = 2 THEN GOTO 900 ELSE GOTO 1200
600 REM *****  PANTALLA 1B  *****
610 CLS
620 PRINT "**********************************************************"
630 PRINT "*                                                        *"
640 PRINT "*                                                        *"
650 PRINT "*                                                        *"
660 PRINT "*        Esta es la pantalla 1B de tu historia           *"
670 PRINT "*                                                        *"
680 PRINT "*                                                        *"
690 PRINT "*                                                        *"
700 PRINT "*                                                        *"
710 PRINT "*                                                        *"
720 PRINT "*                                                        *"
730 PRINT "*                                                        *"
740 PRINT "*       Choose one:                                      *"
750 PRINT "*                                                        *"
760 PRINT "*         1 - if you want to go down one path            *"
770 PRINT "*         2 - if you want to go another way              *"
780 PRINT "*                                                        *"
790 PRINT "*                                                        *"
800 PRINT "*                                                        *"
810 PRINT "*                                                        *"
820 PRINT "**********************************************************"
830 INPUT CHOICE%
840 IF CHOICE% = 2 THEN GOTO 1500 ELSE GOTO 1800
900 END
1200 END
1500 END
1800 END

At long last, we get to see where the GOTO 300 and GOTO 600 statements will take us. Check each IF-THEN and GOTO to insure you understand how the program works. A diagram of the branches might be useful. Note that the last four lines of the program introduce a new BASIC statement. That is END. Its purpose is obvious. Whenever BASIC discovers an END statement, it stops running the program. This happens even if the END is found in the middle of a program.

This program displays one screen that starts the story and has two others as choices. From these others you could branch to another four. However, instead of listing a program with many empty boxes, I will let you finish it. Create additional story boxes that begin at lines 900, 1200, 1500, and 1800. Use as many as you need. Feel free to fill in a real story in the boxes. Just list each flower box (LIST 320 - 520, for example) and type in a story. Remember to press ENTER after each line.

Finally, since this program represents a lot of hard work, be sure to SAVE it in a disk file before you enter SYSTEM. Also, if you have a printer, you may want to use the LLIST command to print out a copy on paper.

In this tutorial we learned about variables and the BASIC REM, IF-THEN-ELSE, GOTO, and END statements. With these commands, we discovered how to make choices in programs and how to move execution around inside of a program. We also had some spaghetti (code, that is). The next chapter is just plain fun; it will be a reward for this effort.

  • tutorial_de_aventuras_en_basic.1643136795.txt.gz
  • Última modificación: 2022/01/25 18:53
  • por peron