ARTICLE - The Beginners Series - Part 1
by Brad Moore

Home

Maintaining checkbox states
Tidbits from the community
Liberty Basic 4
New Alternate Forum
Using the Tsunami Database
Wizard Framework
Links to LB Sites
Update on 10th Anniversary Contest
Extracting Icons And Saving Them As Bitmaps
Applying Symbolic Logic
QuadClicks
Simple Math For Moving Objects
Event Driven Programming - Part 2
The Beginners Series - Part 1

 

Introducing the Series
This month I am starting a new series of articles called just for beginners. It is a tutorial that takes the beginner programmer from square one through to becoming a competent programmer. The series is designed to be followed with Liberty Basic running on the computer in front of you. The version we are targeting is 3.x. You can find out more about Liberty Basic on the Internet at www.libertybasic.com.

Why Program?
We write programs us to express our ideas, simplify tasks or sometimes just to entertain. You may have come to programming hoping to do one of those very things. These tutorials are born out of a process of teaching my son to program. His goal is to write games, so the tutorials to follow will have a definate tilt toward game creation. If you are not interested in creating games - take heart - many of the concepts apply to other types of programming.

Overview of this lesson
In this lesson we will be introducing Variables, Looping, the commands PRINT, INPUT, CLS, GOTO and the control structure IF - THEN - END IF.

Getting Started
We will begin by simply saying hello. This is one of the usual begin programs that any new student will write when they come to a new language. Type in the following code:

Print "Hello"

Here is a screen shot of the result:

The PRINT statement is used to display information on the screen.

Interaction with the user
Well we can display things to the user, how should we get information from the user? This form of interaction is gathering input, and we use the INPUT statement to accomplish it. The INPUT statement gets data from the user, but what does it do with the data? Variables are used to store data that can change during the program execution - they are central to most programming languages. The INPUT statement uses a variable as its target to hold the information the user supplies. Here is an example:

Input A

Before we integrate INPUT into our program lets take a closer look at variable types. Variables are created in Liberty Basic when we assign a value to them. The traditional command for assigning a value to a variable is LET. The command LET is understood in an implicit assignement and the command is not required. Most programmers simply write the variable name, an equals sign and then the value to be assigned. Here is an example:

Count = 15

Which is the same as:

Let Count = 15

Liberty Basic has two basic variable types. Numeric variables and String variables. Numeric variables hold numbers only. They are useful because we can perform numeric operations on them (like adding, subtracting, square root and so on). They can hold any type of number including whole numbers and fractional numbers. Here are some examples of numeric variable types:

Count = 15
items = 24
total = 12.15
a = 77
j = .00001
pi = 3.14

String variables typically hold words. They are however not restricted and can hold any form of data, letters, numbers and special characters. Strings are very versatile, however they can not be used to perform math functions. A string variable is differentiated by the '$' that is appended to the variable name. Additionally when assigning a value to a string the value must be enclosed in quotation marks. Here are some examples of strings:

Name$ = "Brad"
System$ = "Windows XP"
Today$ = "Monday"
Players$ = "12"

In the example above Players$ is a string value that holds a number. This is ok, but math functions can not be performed on the string. There are functions that allow conversion of strings to numeric variable types and from numeric variable types back to strings. We will discuss those in a latter installment.

A final word of caution about variables: Spelling counts, as does the case used in the variable. For instance the variable "close" is not the same as the variable "Close" or "clos" or "cLoSe". These are different variables.

Getting some answers
So with that foundation - lets get some information form the user. Specifically the users name. Here is what the new program will look like:

Print "Enter your name";
Input Name$
Print "Hello ";Name$

Lets play a game
Lets extend the lesson into a simple game. The game if High/Low. The user will try to guess the number the computer has thought of and the computer will tell the user whether thier guess was too high, too low or right on.

This project is going to require a couple new commands we have not yet covered. The first is a control structure. It allows us to make decisions based on the contents of a variable. The command is IF...THEN. We will be using the block form of the IF...THEN which is constructed as follows:

If expression Then
statments...
...
...
End If

In this form the statements between the IF...THEN and the END IF are only executed if the condition of the expression is true. What does that mean. Well lets take an example:

If A = 5 Then
Print "The answer was five"
End If

Then the print statement (Print "The answer was five") could only be executed if the value A really was 5.

The other thing we will need to understand is looping. Looping is where we execute several statements of code then we encounter a special statement that redirects the program back up to execute that same code again. There are several statements and programming structures that can be used to cause looping, but we will be using the GOTO statement because it is easy to understand. GOTO simply redirects the program from its current location to another labeled section of code.

What does it mean to have a label. In Liberty Basic labels are used to organize the code, allow a place to branch or goto during program execution and provide navigation within the project during design time. We will cover some of these uses later. Right now we are interested in labels to aid in program branching. A label is any word that is contained in brackets (ie. "[" and "]"). Here are some examples of labels:

[loop]
[main]
[begin_here]

Looping is done by instructing the program to GOTO a specific labeled area of code. Here is an example:

[loop]
'some code here
...
...
Goto [loop]

Most looping is conditional, which is to say that it only executes a GOTO statement if a certain condition is true. The condition is evaluated in an IF...THEN statement. If the expression in the IF..THEN statement is true then the GOTO statement is executed and the program execution is redirected to the labeled area of code. For instance:

[loop]
'some code here
...
...
If A = 5 then
Goto [loop]
End IF

In the example above the program will only loop if A really is 5. Otherwise the program will fall through to the end of the code and terminate. Here is a graphic that demonstrates the program flow in a basic looping program that uses conditional looping.


Developing the game
So getting on with the game... Lets go ahead and introduce the game and then choose our number. We will leverage the hello code we wrote earlier:

Print "Enter your name";
Input Name$
Print "Hello ";Name$;" welcome to High/Low"

Number = 5

Lets add to this some breif instructions so the use knows what is expected.

Print "All right ";Name$;" choose a number between 1 and 10"


One of the things you may have noticed is that I have embedded a string variable into the print statement. It is outside of the quotations and preceded and followed by a semicolon. The semicolons force the elements of the print statement to follow each other on the same line and not to be on separate lines. The also are required with in the syntax of the statement where we are mixing literals (the part contained between quotes) and variables in the same print statement.

We next need a label that we can branch back up to - because the guessing part of the game needs to be in a repeating loop until the correct answer is located.

[loop]

Now lets find out what the users choice is. We will couple a PRINT statement with an INPUT statement. The INPUT statement always prints a question mark ("?") on the screen when it is waiting for input. I like to force the question mark to print at the end of my PRINT statement. Do this by placing a semicolon at the very end of the PRINT statement:

Print "What is your choice";
Input a

Now using the IF...THEN statement we need to evaluate whether the answer is higher, lower or right on compared to our chosen number.

If a > Number then
print "Too High"
goto [loop]
End if

If a < Number then
print "Too Low"
goto [loop]
End if

If a = Number then
print "All right! You got it!"
End if

There it is. The game of High/Low. If you have followed along, typing the program in then go ahead and run it.

Adding Randomness
The game could use a couple embellishments. For instance - it would be nice if the programmer (who is also the tester) did not know what the answer would be. Having five as the magic number each time kind takes some of the charm out of the game. What we need is a way to randomly select a number between 1 and 10.

Liberty Basic does have a random function called RND. It returns a number between 0 and 1 (a fractional number) which can then be scaled to fit our needs. Here is how we do that:

N = RND(0)

Lets say for instance that the function above returned the value .3176. Now we need a number that is greater than, or equal to 1 and less than, or equal to 10. We can get this by moving the decimal one place to the right of our current number. This is accomplished by multiplying it by 10. So we would write the following:

N = RND(0) * 10
That will give us the value of 3.176. But we really wanted a whole number. The INT function will truncate the decimal portion of the number. We would write this as:

N = INT(RND(0) * 10)

Which is great. It will give us the number 3 in the example above, but what if RND(0) had actually produced the value .0245? Then the result of our equation would be 0, which is less than 1. We can solve this by adding a one to the final equation. So the following equation would return a value that is between 1 and 10 inclusive:

N = INT(RND(0) * 10) + 1

So change the part of the part of the program where we set the value the computer has selected. Right now it is a line that reads like this:

Number = 5

Change it to read:

Number = INT(RND(0) * 10) + 1

Now run the program. A little bit more interesting - huh? Well, not a lot - but this is simple games stuff - we will have to be patient before we can write the next major blockbuster game. There is much more to learn.

Making the game repeat
As you have no doubt noticed - the game ends as soon as you get the answer correct. If you want to play again you must close the output window and then run the program again. Wouldn't be great if it asked you if you wanted to play again? If you chose to play again you would get a new magic number and try to guess what it is, of not then the program would exit.

This is not hard to do. It simply requires another label and another conditional loop using the GOTO statement.

Put the label just before the line where we choose the magic number. I have inserted into the portion of the code as show below:

Print "Enter your name";
Input Name$
Print "Hello ";Name$;" welcome to High/Low"

[begin]

Number = INT(RND(0) * 10) + 1

Now we need an IF…THEN statement to handle the conditional looping. Place this code at the very end of your program. We will be asking a question again, so we will use an INPUT statement. This time the target of the INPUT statement will be a string value. Here is what to add to your code:

Print ""
Print "Do you wish to play again - (y = yes)";
Input answer$

If answer$ = "y" then
Cls
Goto [begin]
End if

I have introduced a couple new items here. First is the idea of printing blank lines. The statement (Print "") places a line of nothing on the output window creating a blank line to help separate and break up the text being printed to the output window. The second new thing is a command CLS. This mean CLear Screen - it only works in the default MainWin which we have been using for output. Issuing this command simply removes all text from the output window.

I also think the program would be nice if it thanked us for playing at the end of the run. If you think so too, add the following to the very end of the program:

Print "Thanks for playing - Good bye"

Now try out the program. Much nicer huh?

Final thoughts
Well the program runs nice, but there are still a couple more things we can do to spruce it up. The first is to add some comments to the code. Comments do nothing durring program execution, but they make the code easier to understand later should we revisit the program at another time, and help us to know what were thinking when we wrote specific sections of code. Traditionally a comment line began with the command REM or REMARK. REM still works in Liberty Basic, but most people today simple use an apostrophe to begin a comment. I like to use liberal comments in my code so that I will understand what I was doing when I wrote it. Here is an example of a comment you might put just before you select your magic number.

'Select a random number between 1 and 10 (inclusive)

Also I want to issue a challenge - something you can do to try out your new skills. Most games have some form of scoring mechanism - wouldn't it be great to keep track of how many guesses it takes to get the right number and also what the best record (fewest guesses) that you obtained for a given run? What you need to do this is a counter. A counter is a numeric variable that you initialize to zero, then count up, each iteration through something. Here is an example:

Count = 0

'some code here

Count = Count + 1

It is not quite like algebra. That equation would never be permitted, but in computer math that is perfectly acceptable. What it means is to take the current value of Count and add one to it and assign the result to Count. It simply increments the variable.

I am not going to tell you how to integrate the solution to the challenge. See if you can do that. However the complete game is included in a zip file called beginners1.zip which accompanied this article.

Also, a couple disclaimers before my fellow Basic Programmers eat me alive:

1) Most people avoid GOTO statements if they can. Somewhere along the way people decided that GOTO statements were bad because they fostered poor coding practices. That is partially true, but if you are going to be a poor coder it really does not matter whether you use GOTO statements or not. I find them to be easy to understand and a good starting place for explaining looping and such topics. A mature programmer will use different looping constructs in a program like this, such as the WHILE…WEND statements. We will visit these at a much later date.
2) The program as written has a lot of places that a bad input will crash the program. It has been designed to be basic and not have a lot of error checking. Error checking is important and bomb proofing concepts - which we will cover later - will improve the runability of the program. Many experienced programmers I am sure will recognize the potential errors that I have introduced in getting a numeric value using an input statement. What if the user enters a letter? Try it and find out.

Thanks and happy computing…

By Brad Moore, copyright 2002, all rights reserved.


Home

Maintaining checkbox states
Tidbits from the community
Liberty Basic 4
New Alternate Forum
Using the Tsunami Database
Wizard Framework
Links to LB Sites
Update on 10th Anniversary Contest
Extracting Icons And Saving Them As Bitmaps
Applying Symbolic Logic
QuadClicks
Simple Math For Moving Objects
Event Driven Programming - Part 2
The Beginners Series - Part 1