Tuesday, May 24, 2011

Beginning Programming with Just BASIC -- Tutorial 7: Graphical User Interface



Tutorial 7 -- Graphical User Interface

We have previously been working out of the main window. We no longer wish to be using this window. We now would like to be able to design our own windows. To do this, at the top of the program issue the command

    nomainwin

... and then go on to describe your window:


    WindowWidth = 232
    WindowHeight = 215
    UpperLeftX = 50
    UpperLeftY = 50
    statictext #1.statictext, "This is static text", 26, 16, 152, 20
    button #1.button, "This is a button", [whenClicked], UL, 22, 101, 138, 25
    textbox #1.textbox, 22, 51, 100, 25
    open "Title" for window as #1
    print #1, "font ms_sans_serif 0 16"
    print #1, "trapclose [quit]"

[1.inputLoop]   'wait here for input event
    wait

[whenClicked]   'Perform action for the button named 'button'
    notice "You pressed the button!"
    wait

[quit]
     close #1
     end

So here's how it works: You first list all the elements of the window, such as the text, the buttons, the text fields, etc. I'm not going to list how to enter all of the different kinds of elements since they can be found in the help files, but in general the syntax is as follows: (1) list the element type (e.g. "statictext"), (2) list the handle for the element with the #-symbol, followed by the handle for the entire window, and then an extension that describes the specific element, (3) the text that goes into it/any functionality that needs to be described on this line, (4) numbers that describe upper-left x, upper-left y, width, and height of the element, in that order. After listing all of the elements, open the window:

open "Title" for window as #1

In this line you give it a title, tell it what kind of window it is (in this case just the default window), and give it a handle. Again, a handle is what you use to refer to the window, and it begins with the #-symbol.

All commands concerning the window go in quotations following the print command, such as

print #1, "trapclose [quit]"

This line is called "trapping the close event," and it tells the program to go to the branch label called [quit] when the user clicks the little red x in the upper right corner of the window. In this case, all it does is close the window

close #1

and end the program.

Suppose you want to get input from a textbox. How do you do that? Sneezy.

[whenClicked]   'Perform action for the button named 'button'
    input #1.textbox, text$
    print #1.textbox, "!contents? text$"
    notice "You entered "; text$; " into the textbox!"
    wait

DON'T WASTE TIME!

Just BASIC has this handy little built-in WYSIWYG program that allows you to design your window, and then it produces the code for you. This program cuts down on the time it takes to program your GUI's by a very large amount. To use this feature, click on the RUN drop-down menu, and then click "FreeForm-J GUI" editor. You will be so glad you learned about it upfront.

Now you can make your programs look just the way you want them!

goto [nextTutorial]

Monday, May 23, 2011

Beginning Programming with Just BASIC -- Tutorial 6: File Input and Output



Tutorial 6: File Input and Output

Suppose we want to be able to close a program to go eat supper and come back later. But we want to save all our data. By now you should be familiar with the fact that variables and arrays reset when you close a program.

You can print data to a file. Like this:

input "Give your file a name: "; filename$
open filename$ for output as #save
print #save, "Yotta yotta homina homina jiggabuh."

Some notes about this code: #save is called a handle, and it is used to refer to the output file. Any variable name preceded by a # is a handle, which are used to describe windows in general. So, if you run this program and name your file "output.txt", a new file will be created in the folder that your basic file is saved in named "output.txt," and it will contain a line that says:

Yotta yotta homina homina jiggabuh.

You can also do input files, so you can load a file into your program that you previously saved.

input "What file would you like to open? "; filename$
open filename$ for input as #load
for i = 1 to n
    input data$(i)
next

Here is an example program that allows you to save your work:

[start]
    print "Would you like to (1) write a story, (2) read one you wrote, or (3) exit?"
    input answer
    select case answer
        case 1: goto [write]
        case 2: goto [read]
        case 3: goto [quit]
    end select

[write]
    input "How many lines will your story be? "; n
    dim txt$(n)
    print "Write your story:"
    for i = 1 to n
        input txt$(i)
    next
    input "Enter a name for the file: "; filename$
    open filename$ for output as #save
    for i = 1 to n
        print #save, txt$(i)
    next
    close #save '<- Closes the file afterward
    goto [start]

[read]
    input "What is the file name? "; filename$
    open filename$ for input as #load
    input #load, n
    dim txt$(n)
    for i = 1 to n
        input #load, txt$(i)
        print txt$(i)
    next
    close #load
    goto [start]

[quit]
    end


Some notes about this code: This is a basic example of a program where the user will be producing something (in this case, a story), and then can read it later. Instead of doing it this way, you should look into how to do a file dialog window (it's easier than you might suppose!).

goto [nextTutorial

Sunday, May 22, 2011

Beginning Programming with Just BASIC -- Tutorial 5: Arrays



Tutorial 5: Arrays

Arrays are similar to variables, except that they can hold more than one value. For instance, a list of names and grades. This is a good way to organize data, especially when little is known about the data that is going into them, in particular how many data point there are.

To set up an array in your program requires a little more work than it takes to use a variable. First you have to define how big the array will be, that is, how many values it can hold. You do that with the DIM command:

dim myArray(100)

In parentheses you put a number defining the size of the array. In this case I can put 100 values into the array called myArray(). So how do I do that?

With loops! Arrays are often used in conjunction with FOR loops because of how easy it is to systematically define every value.

for i = 1 to 100
    input myArray(i)
next

This is far easier than having to write out

input myArray(1)
input myArray(2)
input myArray(3)...

You get the picture.

You can also have multidimensional arrays. Say you want to associate two parameters to the same value. You can do that easily:

dim twoDimensional(10,10)
for i = 1 to 10
    for j = 1 to 10
        twoDimensional(i,j) = i*j
    next
next

Those are the essentials of making an array. I decided to include them early on so you don't waste time trying to use variables for some complex program.

goto [nextTutorial]

Friday, May 20, 2011

Beginning Programming with Just BASIC -- Tutorial 4: Loops



Tutorial 4: For Loops and While Loops

Maybe you want to run a piece of code through several times. Instead of using GOTO, here's a snazzy way to accomplish this. There are two types of loops, the FOR loop and the WHILE loop. They are similar but are treated differently.

The FOR loop will run through the code a predetermined number of times, keeping track of how many times it has run through the loop. Here is how you would set up a FOR loop:

for i = 1 to n
    some code
next

For example,

for i = 1 to 1000
    print i
next

This code prints out the numbers 1 through 1000.

You can also have the loop count by an interval other than 1 (the default):

for i = 2 to 1000, step 2
    print i
next

This code prints out all the even numbers from 2 to 1000.

The WHILE loop is treated differently, but it can still function the same way. A WHILE loop will continue to run the code until a certain condition is met. For instance:

x = 1
while x < 1000
     x = 2*x
     print x
wend

As long as the value of x is less than 1000 x will continue to be doubled and print to the screen.

And that is all. There is no secret aspect of loops lurking in the shadows waiting to spring out and surprise you with complexity. What you see is all there is.

That said, let's write a program using loops:

Ever wonder how a computer calculates the square root of a number? Well, read further and you shall be enlightened.

You start with a guess, G, and you loop through this overwrite statement

G = (G + x/G)/2

until G is approximately equal to the square root of x.

Take note, however, that if you actually were going to take the square root of something in everyday programming, you'd use a built in function for that. Or just raise the number to the 1/2 power.

i = 0
print "Square root of what?"
input x
print "To + or - what precision? (%)"
input precision
precision = precision/100
lowerx = (1 - precision)*x
upperx = (1 + precision)*x
print "Guess?"
input G
while G^2 < lowerx and G^2 > upperx
    G = (G + x/G)/2
    i = i + 1
wend
print "The square root of x is "; G; " in "; i; " iterations."
end

This type of calculation is called numerical methods, and the subject is so vast that it has its own field of study.

goto [nextTutorial]

Beginning Programming with Just BASIC -- Tutorial 3: IF Constructs



Tutorial 3: IF Constructs, Boolean Operators and Branch Labels

Sometimes you only want to run a portion of the code if a certain condition is met. This is another basic part of programming, and can be accomplished using IF-constructs. The most basic IF-statement looks like this:

if condition then
    some code
end if

Also, if you have some other code you wish to run, you can issue the ELSE command. As an example,

print "What is x?"
input x
if x = 1 then
    print "x is 1!"
else
    print "x is not 1!"
end if

This is a rather stupid example, because you can always just print the variable. But it's gets the point across, and that's all that matters.

One other thing about if statements that I forgot to mention in the video: suppose you have more than one condition under consideration. If you only care if one or the other condition is true, then you can use the OR Boolean Operator:

if condition1 or condition2 then ...

However, if you want both conditions to be true to run the code, you can use the AND Boolean Operator:

if condition1 and condition2 then ...

I would also like to take the time to show you how to use the GOTO statement, and issue a word of caution regarding this command. The GOTO statement allows you to jump around to different parts of your program called branches. A branch is defined by a branch label, which goes inside square brackets []. This is a very useful thing in programming if you wish to run certain parts of the code more than once.

But watch out! Don't fall snare to the trap of Spaghetti Programming, a problem where beginning programmers overuse the GOTO statement and wrap their codes and their minds in humongous knots and get exceedingly confused. This doesn't tend to be a problem with [branchLabels] so much, but in older versions of BASIC, every line was numbered and you could GOTO any point in your program. Things got a little hairy. Well, there is a way to combat Spaghetti Programming, and it is called for- and while-loops. But I'll save that for a later tutorial.

Anyway, here is an example program that uses everything we have learned so far:

[Start]
    print "Guess a number from 1 to 100!"
    print "You have 7 guesses."
    x = int(100*rnd(1)) + 1
    guesses = 7
[Loop]
    print "Guess number "; 8 - guesses; ":"
    input guess
    if guess = x then goto [youWin]
    if guess < x then print "Too low."
    if guess > x then print "Too high."
    guesses = guesses - 1
    if guesses = 0 then goto [youLose]
    goto [Loop]

[youWin]
    print "You win!"
    goto [playAgain]
[youLose]
    print "You lose!"
    goto [playAgain]
[playAgain]
    print "Play again? (y or n)"
    input answer$
    if answer$ = "y" then goto [Start]
    end

This program is a game that has the user try to guess a randomly generated number from one to one hundred. They win if they can guess it within seven tries, and they lose if they use up all seven guesses. The computer will notify them whether their guess is too high or too low to help them zero in on the correct guess.

A couple of notes about this code:
  1. x is assigned randomly using a few built in functions. You can find a list of all the built in functions in the help files. The rnd(1) function generates a random decimal from 0 to 1. It is then multiplied by 100 because in the game, x can go all the way up to 100. To make it an integer instead of a decimal, we use the int() function to turn it into an integer. Since the int() function rounds down, I added 1 to x so that its range is 1 to 100. You just have to think about it and scratch your head for awhile, and then you'll figure it out.
  2. If you only have one line of code to run if a condition is true, you can have a one-line if-statement. Simply put the code to run after the word THEN.

Thursday, May 19, 2011

Beginning Programming with Just BASIC -- Tutorial 2: Variables



Tutorial 2: Variables and User Input

Now we're going to use variables, which are ubiquitous in programming. Variables are pretty much the meat and potatoes of programming.

A variable is a word or character that holds a value. Just like in algebra, which you may have had in high school, where x = 3, etc. In this case, x is a variable, because it is used in place of the actual value in represents.

In JB there are two types of variables: string variables and number variables. String variables hold text and letters and characters and such. Here is how you define a string variable:

myName$ = "Daniel"

The name of the variable can be anything, but since it is a string variable, it must end in the $-sign so that JB knows it's a string. Everything in the quotation marks following gets stored in the variable. Thus, if your program says

myName$ = "Daniel"
print "Hello "; myName$

The output will be

Hello Daniel.

Number variables hold regular number values, like 6 and 12 and 3.141592654 and -44000000. Defining a number variable is easy, you just say

x = 0.00012
print x

You can also do fancy operations on number variables:

x = 1
print x
x = x + 1 'Read "new x = previous x + 1"
print x
x = 2*x 'Make x twice its previous value
print x
x = x^2 'Square x and put it back in x

(Note, when you put text after a single quotation mark, the compiler skips over it. That's a good way to put comments in your code, or to take out a piece of code that you don't want to actually delete). This has output like this:

1
2
4
16

Now, what good is your program if the user can't control anything? You need to be able to get input from the user. That's really what programming is all about. Input from user, manipulation of input, output back to user. Here's how that's done:

print "What is your name?"
input userName$
print "Hello there, "; userName$
print "Please input a number to square:"
input x
print x " squared is "
x = x^2
print x

This code has output like this:

What is your name?
?Daniel
Hello there, Daniel
Please input a number to square:
?2
2 squared is
4

You now know how to make a basic functional program!

goto [nextTutorial]

Beginning Programming with Just BASIC -- Tutorial 1: Compiling and Running



Tutorial 1: Compiling and Running Your First Program

So you want to try programming.

In these tutorials I assume you are a complete beginner, although you are able to use all the basic functions of your computer already.

I also am assuming you are using Windows. (Sorry Mac-users, JB only works on Windows. Das ist schade. Not to say that the concepts of programming in these tutorials don't apply universally, though).

Introductions aside, let's get started.

The first thing you are going to need is a compiler. A compiler is a program that takes the written commands from the programmer, analyzes it and looks for stuff it doesn't understand, and then turns it into machine language (namely, 1's and 0's). In these tutorials, we will be using a language called Just BASIC, which is a variant of the original BASIC programming language of the 1970's. You can download the compiler here. This language is an excellent choice for beginners because it is
  1. Free
  2. Easy to learn
  3. Offers a wide variety of functions including basic GUI's, graphics commands, sprite programming, and sound effects.
So as you can see, it's great for beginners and yet is complex enough to continue using it even as you get more advanced.

Once you've downloaded the compiler, open it up. It's time to write our first program. Most peoples first programs print the words "Hello, World" on the screen. But if you want your program to be unique, have it write something more creative than that. In the video I use the more informal "Howdy." No matter what you have it say, here is how you have it say it:

print "Howdy, World!"
end

What this does is it tells the computer to display the text "Howdy, World!" in the main window, and then it ends the program. Easy, right?

You're right, it is easy. But in the future, things won't be so easy, so enjoy how easy it is while it lasts.

Congratulations! You've just written your first program. You are now well on your way to becoming an excellent computer coder (if you keep reading, that is).

goto [nextTutorial]

Wednesday, May 18, 2011

Take 2

I originally started this blog on the 10th of May, and then Blogger had that issue on the 11th and my blog disappeared. Eh, not to worry. I'll just re-post what I had written then:

This blog is for exploring the humongous world of computer programming, and other computerish topics. I will likely post tutorials of beginner, intermediate, advanced levels, and talk about interesting anecdotes and stories that I experience in my career as a computer programmer. (I use the word "career" lightly. I'm actually an aerospace engineer).

As of this writing, I am familiar with five programming languages: FORTRAN, JustBASIC, C++, Python, and MatLab. Of these I have been programming in BASIC the longest, and have made many interesting programs on it. I also consider myself an "expert" in FORTRAN, having used it profusely as an aerospace engineer. As for C++ and Python, I'm at the beginner- to intermediate-level, so don't expect anything too highfalutin in that department just yet.

That said, what am I going to post first? Well, I figured I'd post my tutorials on Beginning Programming with Just BASIC. First things first. Learn how to program a computer. I've already made several good video tutorials on my YouTube Channel that would do wonders on this blog.

Thanks for stopping by, and I hope you enjoy your stay!