q Basic Tutor

Embed Size (px)

Citation preview

  • 8/8/2019 q Basic Tutor

    1/33

    BASIC Programming

    Introduction

    History

    Lets the Game Begin

    Your First Program

    Variable in Qbasic

    More Advance Data Manipulation User Defined Type

    Subroutines and Functions

    Parameters

    Fucntions

    Reading and Writing to Files

    Displaying Graphics

    Designing Application in Qbasic

    Conclusion

    Introduction:

    QBasic is a very simple language to pick up, and yet it can accomplish a great deal. Granted you will probably

    never write Doom or Word Perfect with QBasic, but it has its strong points. One of them is to introduce

    people to programming without having to worry about the internal workings of the computer. It's simple to

    create games, business applications, simple databases, and graphics. The best aspect of the language is its

    close resemblance to English.

    In the early days of programming, it was usually the scientific elite doing the programming, and they were

    usually trained above the average person to do their programming work. It was not until 1964 at Dartsmouth

    college that the Beginner's All-purpose Symbolic Instruction Code would be introduced -- more commonly

    known as BASIC. Using common English to perform processor tasks, BASIC became quickly popular, althoughit was disliked by programmers of more "low-level" languages such as assembly and FORTRAN. In 1985

    Microsoft released a version of BASIC called QBasic with its MS-DOS 5.0 operating system. Since then,

    nearly every PC user has owned their own copy of QBasic, making it a widely known language.

    History

    QuickBASIC is an easier to use version of the original BASIC. BASIC stands for Beginners All purpose

    Symbolic Instruction Code. When it was first made, it was used on mainframes. But later, the language was

    widely accepted as their first computer language because of its easy-to-understand code. Back then, all

    languages were hard to understand because of their abstraction. Although BASIC is a good language forbeginners, it is not a recommended language for a person who wants to become a professional programmer.

    The reason is it is not structural, that means it's easy to write codes that is hard to understand and follow. A

    recommended language for beginners is Pascal. I started with BASIC, I didn't have much problem with

    understanding my own big programs. I believe it is because I made my programs using structural method. So

    if you don't like Pascal, you can just learn BASIC and structural programming.

    Lets the Game Begin

    QBasic is very easy to use. Almost every single computer has it included with it. If you don't already know

    where QBasic is located on your computer, check the \DOS directory, or use a program to find QBASIC.EXE.

    Note (Mar. 19, 2010): This tutorial was written when dinosaurs roamed about. If you're working with Windows

    based computer, you'll have to downloadQBasic.

    http://www.techiwarehouse.com/cat/17/BASIChttp://www.techiwarehouse.com/cms/engine.php?page_id=914f9c44#1%231http://www.techiwarehouse.com/cms/engine.php?page_id=914f9c44#2%232http://www.techiwarehouse.com/cms/engine.php?page_id=914f9c44#3%233http://www.techiwarehouse.com/cms/engine.php?page_id=914f9c44#4%234http://www.techiwarehouse.com/cms/engine.php?page_id=914f9c44#5%235http://www.techiwarehouse.com/cms/engine.php?page_id=914f9c44#6%236http://www.techiwarehouse.com/cms/engine.php?page_id=914f9c44#7%237http://www.techiwarehouse.com/cms/engine.php?page_id=914f9c44#8%238http://www.techiwarehouse.com/cms/engine.php?page_id=914f9c44#9%239http://www.techiwarehouse.com/cms/engine.php?page_id=914f9c44#10%2310http://www.techiwarehouse.com/cms/engine.php?page_id=914f9c44#11%2311http://www.techiwarehouse.com/cms/engine.php?page_id=914f9c44#12%2312http://www.techiwarehouse.com/cms/engine.php?page_id=914f9c44#13%2313http://www.techiwarehouse.com/cms/engine.php?page_id=914f9c44#14%2314http://www.petesqbsite.com/sections/introduction/qbasic11.ziphttp://www.petesqbsite.com/sections/introduction/qbasic11.ziphttp://www.petesqbsite.com/sections/introduction/qbasic11.ziphttp://www.techiwarehouse.com/cms/engine.php?page_id=914f9c44#1%231http://www.techiwarehouse.com/cms/engine.php?page_id=914f9c44#2%232http://www.techiwarehouse.com/cms/engine.php?page_id=914f9c44#3%233http://www.techiwarehouse.com/cms/engine.php?page_id=914f9c44#4%234http://www.techiwarehouse.com/cms/engine.php?page_id=914f9c44#5%235http://www.techiwarehouse.com/cms/engine.php?page_id=914f9c44#6%236http://www.techiwarehouse.com/cms/engine.php?page_id=914f9c44#7%237http://www.techiwarehouse.com/cms/engine.php?page_id=914f9c44#8%238http://www.techiwarehouse.com/cms/engine.php?page_id=914f9c44#9%239http://www.techiwarehouse.com/cms/engine.php?page_id=914f9c44#10%2310http://www.techiwarehouse.com/cms/engine.php?page_id=914f9c44#11%2311http://www.techiwarehouse.com/cms/engine.php?page_id=914f9c44#12%2312http://www.techiwarehouse.com/cms/engine.php?page_id=914f9c44#13%2313http://www.techiwarehouse.com/cms/engine.php?page_id=914f9c44#14%2314http://www.petesqbsite.com/sections/introduction/qbasic11.ziphttp://www.techiwarehouse.com/cat/17/BASIC
  • 8/8/2019 q Basic Tutor

    2/33

    To start using QBasic, load it up from the DOS prompt, and it should look something like the DOS editor. I

    know you'd like to get started right away, so I'll cut to the chase. Here's a sample program for you to type in:

    Your First Program

    --begin program---------------

    CLSPRINT"Hello!"

    PRINT

    PRINT"This is my first program!"

    --end program-----------------

    CLS

    This is just a list of commands that the computer will interpret and execute. Go up to the "RUN" menu and

    click "START". The scren will clear, and look something like this, with a "Press any key to continue" on the

    bottom of the screen.

    Hello!

    This is my first program!

    Notice it doesn't say CLS, or PRINT, or anything. It does give you a "Press any key to continue" message, but

    that's just QBasic's way of telling you it's done with it's work.

    To begin with the explanation, the command 'CLS' stands for CLear Screen, and PRINT is quite self-

    explanatory. Just make sure that when you're PRINTing, have quotes on each side of what you want the

    screen to display. Fool around with the two commands until you get used to them. People who are already

    familiar with the menus at the top of the screen (and their function) can skip the next paragraph.

    To begin a new program, go to the "FILE" menu and click "NEW." BEWARE - any program in memory will be

    LOST FOREVER if it is not saved. If you want to save a program, go to the "FILE" menu and click "SAVE."

    QBasic will prompt you for a file name, and your program will be saved to disk. If you want to load that

    program again, go to the "FILE" menu and click "LOAD". You will get a dialog of what QBasic files are in your

    directory. Double-click on the one you want to load.

    Variables in QBasic

    The Scripting Component contains the scripting languages used to create server-side processing scripts along

    with other objects through which the server's directory and file structures are accessed.

    A variable, simply defined, is a name which can contain a value. Programming involves giving values to these

    names and presenting them in some form to the user. A variable has a type that is defined by the kind of

    value it holds. If the variable holds a number, it may be of integer, floating decimal, long integer, or

    imaginary. If the variable holds symbols or text, it may be a character variable or a string variable. These are

    terms you will become accustomed to as you continue programming.

    Here are some examples of values a variable might contain:

    STRING "hello, this is a string"

    INTEGER 5

    LONG 92883

    SINGLE 39.2932

    DOUBLE 983288.18

  • 8/8/2019 q Basic Tutor

    3/33

    The first is a string. Strings contain text. The last four are number types. But the computer does not know

    what kind of value you are trying to give a variable unless you tell it! There are two methods of telling the

    computer what kind of variable you are using:

    1. Explicitly declare the variable AS a type. This is done by using the DIM statement. Say you wanted to

    make a variable called number which would contain an integer (whole number, no digits after the

    decimal point). You would do it like this:

    DIM number AS INTEGER

    Then you would use that variable as an integer. The word DIM actually originates from the word

    Dimension.

    2. Put a symbol after the variable name which is defined as representing that type. QBasic has a set of

    symbols which represent each variable type:

    3. $ String

    4. % Integer

    5. & Long

    6. ! Single

    # Double

    Appending one of these symbols to the name of a variable when you use it in the program tells the

    computer that you are using it as that type. This topic of data types is actually a difficult concept to

    grasp for newcomers to programming. The most common error in QBasic is the infamous Type

    Mismatch, which you will probably see a lot. This means that you are trying to put a value into a

    variable of the wrong type. You might be trying to put the letters "hi there" into an integer variable.

    If you don't define the type of the variable, then QBasic assumes it is of the Single type, which can

    often yield unexpected results. I prefer to use the type symbols after variable names, but some

    explicitly declare them usually at the head of their programs.

    More Advanced Data Manipulation

    There are numerous methods to manipulate data and present it to the user in QBasic. One is called an array.

    An array is a variable which can contain more than one value. For example, you might have an array called a,

    and you could assign data to the members of that array. There might be a value for a(1), and a different value

    for a(6). Before an array can be used, it must be declared. Arrays are declared with the DIM statement used

    in section 1. Here is an example of an array declaration:

    DIM a(1 TO 100) AS INTEGER

    There are now 100 different values that can be assigned to the array a, and they must all be integers. It

    could also look like this

    DIM a%(1 TO 100)

    Using the symbol % for integer. We call the different values for the array members of the array. Array a has

    100 members. Array members can be assigned values by using a subscript number within parentheses after

    the array name, like this

    a%(1) = 10

    a%(2) = 29

    a%(3) = 39

  • 8/8/2019 q Basic Tutor

    4/33

    And so on. Now you're probably wondering why the statement for declare is DIM. This comes from a term

    used in earlier programming languages that means dimension. That still doesn't answer the question... why not

    use the statement DECLARE? Well, an array can have more than one dimension. Arrays with multiple

    dimensions have y members in the second dimension for every x member of the first dimension in the

    following algorithm:

    DIM array( 1 TO x, 1 TO y) AS INTEGER

    So if the actual declaration looked like this:

    DIM a$( 1 TO 3, 1 TO 3

    You would have the following members to assign values to:

    a$(1,1)

    a$(1,2)

    a$(1,3)

    a$(2,1)

    a$(2,2)a$(2,3)

    a$(3,1)

    a$(3,2)

    a$(3,3)

    A two dimensional array is useful for tracking the status of each piece in a checkers game, or something of

    the like. Recall the last example program of section that we had a program that would ask the user for the

    item name, the item cost, and the quantity of that item, the spit out the data just given in a nice format with

    the total in the right hand column. Well, with only one item, this program isn't very practical. But now with

    our newfound knowledge of arrays and the knowledge we already have of loops, we can create a somewhatuseful application. The process will start with the program prompting the user for the number of items that

    will be calculated. Then the program loops for the number of times that the user entered at the beginning,

    assigning the data entered into a member of an array we will declare.

    User Defined Type

    Now on to a new topic: User defined types. Recall that a type is the type of value a variable can have, such as

    integer, string, long, double, or single. You can create your own types which contain one or more of the already

    defined types. Here is an example of a user defined type:

    TYPE employeeTypefirstname AS STRING * 30

    lastname AS STRING * 30

    age AS INTEGER

    wage AS SINGLE

    END TYPE

    We have defined a new type, which consists of four data members, as I call them. We can now declare a

    variable of this type:

    DIM employee AS employeeType

    A variable of a user defined type is like an array, in that it can have more than one value assigned to it. But

    you can have an array of a variable of a user defined type as well, so things can get rather complex. Anyway,

  • 8/8/2019 q Basic Tutor

    5/33

    now that you have a user defined type, you can assign values to the data members of that variable. Use a

    period to access a data member of a type, like this:

    employee.firstname = "Bob"

    employee.lastname = "Foster"

    employee.age = 24

    employee.wage = 6.78

    This could have been helpful in the last program we made withthe top 10 list. We could have declared a user defined type

    called playerType, like this:

    TYPE playerType

    name AS STRING * 20

    score AS INTEGER

    END TYPE

    and then declared an array of variables of that type

    DIM player(1 TO 10) AS playerType

    That would have made our code more efficient, but not necessarily more readable. Notice when we declare a

    string in a user defined type that it seems as if we are multiplying it by a number. Actually, we the number

    after the * defines the maximum length of the string. You must define this because the size of a user

    defined type must be known by the computer. Any value assigned to this string data member which exceeds

    the length specified is truncated.

    User defined types can serve more than to be efficient. They are the heart of the random access file mode,

    which is commonly used in database files. A database is a method of organizing large quantities of information

    in records and fields. In a record, there are a set of fields which are constant in every record. A field's value

    changes from record to record, however. Just the name of the field remains constant. So how does thisrelate to user defined types? Well think of a variable of a user defined type as a record in the database, and

    the data members fields of the records. Employee may be a record, and firstname, lastname, age, and wage

    may be fields. Values can be assigned to the fields in each record, thus constructing a database. A file opened

    for random access is organized in this fashion, with records split into fields. Each record in the random

    access file is given a record number which can be convenient in a database environment. In the OPEN

    statement for opening a random access file there is one extra argument. We must specify the length in bytes

    of how much space one record will occupy -- the record length. This can be easily taken by taking the LENgth

    of a variable defined as the user defined type we are going to use. So back to our employee example, we could

    use the LEN function to get the size in bytes of the employee variable, which is an employeeType. Here's the

    code:

    recordLen# = LEN(employee)

    OPEN "database.dat" FOR RANDOM AS #

    :LEN = recordLen# LEN stands for length. You can also use the LEN function to get the number of

    characters in a string, but that is kind of irrelevant right now. So let's construct a simple database that will

    keep track of the employees of a business.

    ' Section 1

    CLS

    TYPE employee Type

    firstname AS STRING * 30

  • 8/8/2019 q Basic Tutor

    6/33

    lastname AS STRING * 30

    age AS INTEGER

    wage AS SINGLE

    END TYPE

    DIM employee AS employeeType

    ' Section 2

    PRINT "1.) Create new recordset"

    PRINT "2.) View existing recordset"

    INPUT "Which option? ", selection% '

    Section 3

    IF selection% = 1 THEN

    INPUT "How many employees are in the company? ", numRecords%

    recordLen# = LEN(employee)

    OPEN "database.dat" FOR RANDOM AS #1 LEN = recordLen#

    FOR i% = 1 TO numRecords%

    CLS ", radius!IF radius! = -1 THEN EXIT DOarea! = pi! * radius! ^ 2circum! = pi! * 2 * radius!

  • 8/8/2019 q Basic Tutor

    25/33

    COLOR 14PRINT "Area = "; area!PRINT "Circumference = "; circum!

    CIRCLE (320,240), radius!, INT(RND * 15 + 1)DO: LOOP WHILE INKEY$ = ""CLS

    LOOPCOLOR 9: PRINT "Good Bye!"

    END

    We first set the screen graphics mode and generate a random seed number based on the system timer. Thenwe prompt for the radius in a vivid bright white, and test to see if we should end the program. We thencalculate the area and circumference, and print

    the results in yellow. Then we draw the circle from the middle of the screen at the radius given in a randomcolor. This random color is set by first generating a random number from 0 to 14, adding 1 to it, andconverting it to an integer with the INT fu

    nction. The next line seems weird. The INKEY$ statement reads the keyboard and returns the string

    representation of the key pressed. We are looping while INKEY$ is nothing, or in other words, while the userisn't pressing anything. The loop goes on foreve

    r until the user presses any key, and at this time a value will be given to INKEY$ which you might decide touse. The screen is then cleared for the next entry. If the user breaks the loop by entering -1 for the radius,we print Good Bye! in bright blue l

    etters.

    There are a lot more colors than just 16. In fact, you can change the values of each of the 16 colors torepresent some other color that you specify. You do this with the PALETTE statement. The following applies

    to screen modes 12 and 13. This statement h

    as two arguments: the color you want to change and the color you specify. Specifying a color is the hard part.Here is my version of the syntax of the palette statement

    PALETTE color, blueValue * 256 ^ 2 + greenValue * 256 + redValue

    color is the color you are changing. The _Values are numbers from 0 to 63 which specify the intensity of thatcolor. You must use the multipliers after the values and use the addition operator to separate them. So letsmake a program that fades the screen

    in and out, from black to purple. (blue and red make purple).

    SCREEN 12DOFOR i% = 1 TO 63PALETTE 0, i% * 256 ^ 2 + i%

    NEXT i%FOR i% = 63 TO 1 STEP -1PALETTE 0, i% * 256 ^ 2 + i%

    NEXT i%LOOP WHILE INKEY$ = ""END

  • 8/8/2019 q Basic Tutor

    26/33

    We start by changing the value of black (0), which is the background color to purple, from one degree of blue+ red to the next. Then we bring it back down to black by decreasing the blue + red value. We do this over andover until the user presses a key

    or begins to have seizures.

    Scaling and rotation can be accomplished quite easily with the DRAW statement, although it involves someweird looking code. First, lets define a shape that we can scale and rotate.

    box$ = "bu5 l5 d10 r10 u10 l5 bd5"

    Interpretation: "move up 5 spaces without drawing, draw 5 spaces left, draw 10 spaces down, draw 10 spacesright, draw 10 spaces up, draw 5 spaces left, and move 5 spaces down without drawing." This forms a box.Notice that I started at the center and not

    at a corner or side which would seem to be easier. Well, when you rotate something, it draws based on thestarting point of the object, and we want it to rotate so if we put a pen at each corner of the box, it woulddraw a perfect circle. Therefore we se

    t the center of the box as the starting point of the object. I call this the "object handle," not to be confusedwith the handle used in the Windows API. The ta draw command stands for "turn angle," and obviously turnsthe object in the degrees you specif

    y. So if we turned the box from 0 to 360 degrees, drawing the box at each step and erasing the previousimage, we would get a rotating box. But we need one more function: VARPTR$. VARPTR$ stands for "variablepointer," a term you can completely ignore unl

    ess you get into C or Assembly programming. We need to somehow get the box$ shape into the draw stringcommand we use implement in the loop, so we have to take the address of the object string and plug it intothe draw string. This can be accomplished by

    using the X command, which tells VARPTR$ where to plug in the string's address so it can be used. With box$defined above, here's the code for a rotating box:

    DOangle% = angle% + 1IF angle% >= 360 THEN angle% = 1DRAW "c0 bm320,240 ta" + STR$(angle% - 1) + "X" + VARPTR$(box$)DRAW "c1 bm320,240 ta" + STR$(angle%) + "X" + VARPTR$(box$)LOOP WHILE INKEY$ = ""END

    Not that hard is it? We draw the box at the previous angle in black, and then draw the box at the currentangle in blue.

    Scaling is done pretty much the same way, but instead of changing the angle and erasing the previous image,we change the scale factor and erase the previous image. Recall that the default scale factor for the DRAWstatement is 4 pixels per unit. Well, if

    we increase this factor then we will have more pixels per unit, thus giving the image the effect ofenlargement. So if we set up a FOR...NEXT loop which will increase the scale factor from 2 to, say, 200, wewill get the effect of scaling. But lets start

    with a smaller image which is maybe 8 pixels wide from the start instead of 40 so we get a more dramaticeffect.

  • 8/8/2019 q Basic Tutor

    27/33

    SCREEN 12box$ = "bu4 l4 d8 r8 u8 l4 bd4"FOR s% = 2 TO 200DRAW "c0 bm320,240 s" + STR$(s% - 1) + "X" + VARPTR$(box$)DRAW "c2 bm320,240 s" + STR$(s%) + "X" + VARPTR$(box$)

    NEXT s%END

    Notice what we're doing here. We are starting the scale factor at one half of default (2) because theFOR...NEXT loop starts with s% at 2. The s draw command sets the scale factor. Notice also that we mustcontinuously anchor the object handle at a point

    to keep it scaling about the handle. We do this by moving the object handle to 320,240 (center of screen)each time through the loop. Whenever we want to put a number into the draw string, we must concatenate thestring format (STR$) of the number within

    the string. Instead of concatenating the box$ with the rest of the string, it is faster to only pass theaddress of the substring with the VARPTR$ function.

    So what if you want to scale and rotate something at the same time? Simple, just set up a FOR...NEXT loopwhich increases the scale factor as before, and within the loop increase the angle. But instead of subtractinga factor for the angle to erase the pr

    evious angle, lets do it this way: erase the previous image with the current angle, increase the angle, thendraw the current image with the new current angle. This way if we want to change the factor at which theangle increases, we will only have to cha

    nge one number instead of two

    SCREEN 12

    box$ = "bu4 l4 d8 r8 u8 l4 bd4"FOR s% = 2 TO 250DRAW "c0 bm320,240 ta" + STR$(a%) + "s" + STR$(s% - 1) + "X" + VARPTR$(box$)a% = a% + 1IF a% >= 360 THEN a% = 1DRAW "c1 bm320,240 ta" + STR$(a%) + "s" + STR$(s%) + "X" + VARPTR$(box$)

    NEXT s%END

    Try it out! Draw strings can get fairly complex, but you'll get used to them with practice and when youmemorize the draw string commands.

    The screen coordinates for different screen modes can be fairly difficult to work with, and they do tend tobe weird numbers. To make your code simpler to write, you can define a logical plane over the physical plane.An example of a physical plane is the

    640x480 resolution established by the SCREEN 12 screen mode. You can define a logical, or alternate user-defined plane with the WINDOW statement.

    SCREEN 12WINDOW (0,0)-(100,100)CIRCLE (50,50),10,4LINE (0,0)-(50,50),2END

  • 8/8/2019 q Basic Tutor

    28/33

    This trivial example defines a logical plane which is 100x100. 50,50 is now the center of the screen, so thisdraws a red circle from the center with a radius of 10. The line statement draws a green line from the lowerleft corner to the center of the scr

    een. Notice that defining a logical plane sets the origin (0,0) to the bottom left of the screen, instead of thedefault upper left. If you want the origin to be in the upper left with a logical plane, add the SCREENkeyword after WINDOW. So to define the

    graphics mode 12 screen resolution, the code is:

    SCREEN 12WINDOW SCREEN (0,0)-(640,480)

    Use whatever is more comfortable, but I would recommend using WINDOW SCREEN because there is lessconfusion when converting from logical to physical planes.

    Finally, a little information on creating DRAW effects with the other QBasic graphics routines. Hope youknow some trigonometry for this part. Recall that in the unit circle, which has a radius of 1, that thecoordinates of a point on the circle given an

    angle is defined as ( COS(angle), SIN(angle) ). Furthermore, if we are given a point on the circle, we can findthe angle by drawing a vertical line perpendicular to the x axis from the point. If we take the arctangent ofthe vertical length of this line

    divided by the horizontal distance of this line from the origin, we will get the angle. So the angle is defined asATN(Y/X). With this knowledge, it would be possible to create a spinning line using only the line command. Ifwe create a loop which increme

    nts the angle from 0 to 360 then we can take to COS,SIN of the angle to get the point we should draw to.But there's only one more problem. The QBasic functions COS and SIN think in radians, so we must first

    convert the angle to radians by multiplying PI

    / 180. That is quite easily done. Here is the code:

    SCREEN 12CONST PI = 3.1415WINDOW SCREEN (-1,1)-(1,-1)DOLINE (0,0)-(COS(a% * PI / 180),SIN(a% * PI / 180)), 0a% = a% + 1IF a% >= 360 THEN a% = 1

    LINE (0,0)-(COS(a% * PI / 180),SIN(a% * PI / 180)), 14LOOP WHILE INKEY$ = ""END

    We start by initializing the graphics mode, then defining PI as a constant - a variable which will never changein the program execution. Then define the logical plane, and start the loop. The line starts from the center ofthe screen and goes to the coor

    dinate specified by the COS,SIN of the angle. We loop until the user presses a key.

    There is one more type of graphics that QBasic has a strong point for : text. Graphical effects can be madequite easily using only text in QBasic. There are a few functions that are quite useful when dealing with text.The first is the CHR$ function. If

  • 8/8/2019 q Basic Tutor

    29/33

    you pass a number to the CHR$ function, it will return the ASCII (American standard code for informationinterchange) text value of that number. To find a listing of the ASCII character codes, look in the helpcontents, and there is a listing there. For e

    xample, to print a smiley face on the screen, the code is this:

    CLSPRINT CHR$(1)

    END

    Since the ASCII character code for a smiley face is 1, you can use the CHR$ function to get this. Anotheruseful function is ASC, which returns the ASCII value of a text value you pass to it. So ASC("A") will return65 because the ASCII value of A is 65.

    Every printable character (and then some) have an ASCII value, so these two functions make it quite easy.

    Finally, the LOCATE statement is extremely useful for any text based program. LOCATE sets the text CP tothe coordinates you specify. The first argument is the column, and the second is the row. So

    CLSLOCATE 5,10PRINT CHR$(219)END

    Will print a solid white block at column 5, row 10. And that's it for graphics! You now know nearly everygraphics routine in QBasic, and have the knowledge to make a game or highly graphical program. Graphicsdepend on how you arrange them, so it require

    s an artistic skill to some degree. If you get creative with these graphics commands, you can create nearlyany effect you need.

    ------------------------------------------------------------------------SECTION 5 - DESIGNING APPLICATIONS

    It is not practical in real world terms to set up an application in one long list of code. Many early programminglanguages were purely linear, meaning that they started from one point on a list of code, and ended at anotherpoint. All of the code I have

    written in this tutorial so far has been purely linear. However, linear programming is not practical in a teamenvironment. If one person could write one aspect of code, and another write another part of the program,

    things would be much more organized. Q

    Basic contains the capability to meet these needs, called modular programming. You can break a program intodifferent "modules" which are separate from the main program and yet can be accessed by any part of it. Ihighly recommend the use of separate modu

    les in programming applications, although it is not a simple task to learn.

    These separate modules are also known as procedures in the QBasic environment. There are two types ofprocedures: subs and functions. Subs merely execute a task and return to the main program, which functionsexecute a task and return a value to the main

    program. An example of a sub might be a procedure which displays a title screen on the screen, while afunction may be a procedure that returns a degree in degrees given a number in radians. Function proceduresare also used in Calculus, so you Calculus p

  • 8/8/2019 q Basic Tutor

    30/33

    eople should already be familiar with functions.

    Procedures can accept arguments in what is called an argument list. Each argument in the argument list has adefined type, and an object of that type must be passed to the procedure when it is called. For example, theCHR$ QBasic function accepts a numeri

    c argument. The function itself converts this numeric argument into a string representation of the ASCII

    value of the number passed, and returns this one character string.

    Procedures in QBasic are given their own screen. When you enter the QBasic IDE, you are in the mainprocedure which can access all the others. Other procedures are created by typing the type of procedure(SUB or FUNCTION), the procedure name, followed by

    the complete argument list. You can view your procedures through the VIEW menu. Here is an example of asub procedure which performs some operations for a program that will be using graphics, random numbers,and a logical plane.

    SUB initProgram()

    RANDOMIZE TIMERSCREEN 12WINDOW (0,0)-(100,100)COLOR 15

    END SUB

    The only thing you need to type is SUB initProgram (), and the screen will be switched to that procedure. TheEND SUB is placed there for you, so the only thing you need to type then is the code within the sub. Trytyping this out on your own to see how t

    his works. This procedure is called by simply typing initProgram in the main procedure. An alternative method

    is CALL initProcedure (). Right here the parentheses are optional, but if you were to pass arguments to theprocedure, parentheses would be requi

    red with the CALL statement. Now lets try passing an argument to a procedure. We will pass two argumentsto a procedure called center which are a string containing the text to be centered, and the horizontal locationon the screen at which you wish to cen

    ter it.

    SUB center( text$, hLoc% )LOCATE hLoc%, 41 - (LEN(text$) / 2)

    PRINT text$END SUB

    The first line after the sub declaration positions the starting point of the text at the horizontal location wepassed at the second argument and vertical coordinate. The vertical coordinate is calculated by subtractingone half the screen's width in char

    acters (41) and half the LENgth of the text we passed as the first argument. We would call center from themain procedure like this:

    center "Programmed by QP7", 12

    Or like this

    CALL center ("Programmed by QP7", 12)

  • 8/8/2019 q Basic Tutor

    31/33

    It's quite simple actually. Functions are slightly different and involve an additional part which subs do not: areturn value. The return value is specified by assigning the value you want to return to the function namefrom within the function definition

    . When calling the function from within the main procedure, the name of the function is treated as a valuewhich is evaluated at compile-time. Here is an example of a function definition:

    FUNCTION convert.To.Radians (degree!)LET PI = 3.1415convert.To.Radians = degree! * PI / 180

    END SUB

    The function is implicitly called in this program

    CLSINPUT "Enter a value in degrees: ", degreeValue!radianValue! = convert.To.Radians(degreeValue!)PRINT "The radian equivalent is"; radianValue!; "radians"

    END

    We treat the value returned from the function as a value we can immediately assign to another value. Thevariable radianValue! is given the value returned from convert.To.Radians. These concepts are supported in allprogramming languages, so this informat

    ion will be beneficial to you in the future.

    There is one final concept which has proven to be very successful in programming: a message loop. WithQBasic, you can construct a loop which runs for the length of the program, receives input from the user, andexecutes a message based on what the user d

    oes. We will construct a basic application which receives input from the user in the form of an arrow key, andmoves a box on the screen based on the direction the user pressed. The arrow keys are different fromnormal inputted keys received with INKEY$.

    On the enhanced 101 keyboards which have arrow keys, INKEY$ returns two values: the ASCII textrepresentation of the key pressed, and the keyboard scan code of the key pressed. Since the arrow keys donot have an ASCII text representation, we must use the

    keyboard scan codes for them. The keyboard scan codes can be viewed in the HELP | CONTENTS section ofthe QBasic menus. For this program, we will have two procedures in addition to the main procedure. The first

    will initialize the program settings and po

    sition the character in his starting position. The other will move the guy in the direction which we pass to thefunction. The main procedure will call the sub procedures and contains the main message loop which retrievesinput from the user. First of all

    , here is the code for the main procedure:

    CONST UP = 1CONST DOWN = 2CONST LEFT = 3CONST RIGHT = 4

    TYPE objectTypex AS INTEGER

  • 8/8/2019 q Basic Tutor

    32/33

    y AS INTEGEREND TYPEDIM object AS objectTypeinitScreenobject.x = 41object.y = 24

    DO

    SELECT CASE INKEY$CASE CHR$(0) + CHR$(72): move UP, objectCASE CHR$(0) + CHR$(80): move DOWN, objectCASE CHR$(0) + CHR$(75): move LEFT, objectCASE CHR$(0) + CHR$(77): move RIGHT, objectCASE CHR$(32): EXIT DO

    END SELECTLOOPLOCATE 1,1: PRINT "Thank you for playing"END

    This code is fairly self explanatory with the exception of the SELECT CASE... END SELECT structure whichI have not yet explained. This type of conditional testing format tests a condition, and several cases for thatcondition are then tested. In this cas

    e, we are seeing IF INKEY$ = CHR$(0) + CHR$(72), IF INKEY$ = CHR$(0) + CHR$(80), and so on. This is justa more legible format than IF...THEN...ELSE. Note that in the QuickBasic compiler, a CASE ELSE statementis required in the structure for what reason

    I have no idea. The above code is the driver for the rest of the program. First some CONSTants are declaredwhich remain constant for the duration of the program and in any module. A user defined type is declared tostore the coordinates of the character.

    Then an endless loop is executed, calling the appropriate procedure for the arrow key pressed until the userpresses the space bar (CHR$(32)). Here is the code for the initScreen procedure:

    SUB initScreen ()SCREEN 12COLOR 9WIDTH 80,50LOCATE 24,41PRINT CHR$(1)

    END SUB

    The WIDTH 80,50 statement sets the screen text resolution to 80 columns and 50 rows. We then print asmiley face in the middle of the screen in a nice bright blue color. Next we need to write the move procedure,and then we will be done with the program.

    SUB move (way AS INTEGER, object AS objectType)LOCATE object.y, object.xPRINT CHR$(0) ' erase previous imageSELECT CASE wayCASE UP: IF object.y > 1 THEN object.y = object.y - 1CASE DOWN: IF object.y < 49 THEN object.y = object.y + 1CASE LEFT: IF object.x > 1 THEN object.x = object.x - 1CASE RIGHT: IF object.x < 79 THEN object.x = object.x + 1

    END SELECTLOCATE object.y, object.x

  • 8/8/2019 q Basic Tutor

    33/33

    PRINT CHR$(1) ' draw current imageEND SUB

    And that's the whole program... confusing as it may be! Ideas should be going through your head about whatyou could do with this information. Entire games can be created with this simple construct.

    There are more things to consider, but they are beyond the scope of this tutorial. If you were to design anapplication in QBasic, you would only need the information from this section and one heck of an imagination.

    Programming takes knowledge of the lan

    guage and a creative mind... programs are made by programmers with both. If you can develop a creative mind,then you can develop any program conceivable.

    ------------------------------------------------------------------------SECTION 6 - BEYOND QBASIC

    If you've read this tutorial and understood the information within, you can honestly call yourself a QBasicprogrammer. That might not sound very prestigious, and you probably won't get a job in the real world by

    saying that, but ah well. QBasic is a fun

    and widespread language. But you might be wondering, what do I do now? My suggestion is to continue to learnanother language. I would recommend Pascal if you are serious about programming because there arefundamental concepts that you still need to lear

    n. There is also information which I have deliberately left out of this tutorial with the hope that I can teachyou a style of programming which is becoming increasingly popular.

    BASIC is an extremely popular language with thousands of different versions world-wide, so it is mandatorythat you learn it. But if you will continue in programming, knowing a Mid-level DOS language will not suffice in

    the real world. I suggest learning

    some Pascal next, and then moving on to the world of Windows. When I say "learn" I do not mean memorizeevery command in the language, I mean "get familiar with the concepts." You may not learn how to do anythingbeyond what you can do in QBasic, but that

    's fine.

    ------------------------------------------------------------------------This document was last updated on 3-4-96