So You Want To Learn To - Program - BASIC 256
So You Want To Learn To - Program - BASIC 256
Program?
http://www.basicbook.org
James M. Reneau
P.O. Box 278
Russell, Kentucky 41169-2078 USA
Copyright C) 2010
James Martel Reneau
P.O. Box 278 – Russell KY 41169-0278 USA
Table of Contents
Chapter 1: Meeting BASIC-256 – Say Hello.............1
The BASIC-256 Window:.............................................................1
Menu Bar:.................................................................................................2
Tool Bar:...................................................................................................3
Program Area:...........................................................................................3
Text Output Area:.....................................................................................4
Graphics Output Area:..............................................................................4
Your first program – The say statement:....................................4
BASIC-256 is really good with numbers – Simple Arithmetic:......7
Another use for + (Concatenation):............................................9
The text output area - The print statement:.............................11
What is a “Syntax error”:.........................................................12
Chapter 2: Drawing Basic Shapes........................13
Drawing Rectangles and Circles:..............................................13
Saving Your Program and Loading it Back:...............................22
Drawing with Lines:..................................................................23
Setting Individual Points on the Screen:...................................26
Chapter 3: Sound and Music...............................31
Sound Basics – Things you need to know about sound:............31
Numeric Variables:...................................................................36
Chapter 4: Thinking Like a Programmer..............41
Pseudocode:............................................................................. 41
Flowcharting:............................................................................ 44
Flowcharting Example One:....................................................................45
Flowcharting Example Two:....................................................................46
Radians Function:.................................................................................185
Inverse Cosine:.....................................................................................186
Inverse Sine:.........................................................................................186
Inverse Tangent:...................................................................................187
............................................................................................... 309
dbint – Get an Integer Value From a Database Set (19).........309
dbrow – Advance Database Set to Next Row (19)...................310
dbstring – Get a String Value From a Database Set (19)........310
degrees – Convert a Radian Value to a Degree Value (14).....311
eof – Allow Program to Check for End Of File Condition (16)...311
exists – Check to See if a File Exists (16)................................312
float – Convert a String Value to A Float Value (14)................312
floor – Round Down (14).........................................................313
getcolor – Return the Current Drawing Color..........................314
getslice – Capture Part of the Graphics Output.......................314
graphheight – Return the Height of the Graphic Display (8)...315
graphwidth – Return the Width of the Graphic Display (8)......315
hour – Return the Current System Clock - Hour (9)................316
instr – Return Position of One String in Another (15)..............316
int – Convert Value to an Integer (14)....................................317
key – Return the Currently Pressed Keyboard Key (11)..........318
lasterror – Return Last Error (18)............................................319
lasterrorextra – Return Last Error Extra Information(18)........319
lasterrorline – Return Program Line of Last Error (18)............320
lasterrormessage – Return Last Error as String (18)...............320
left – Extract Left Sub-string (15)............................................320
length – Length of a String (15)..............................................321
lower – Change String to Lower Case (15)..............................321
mid – Extract Part of a String (14)..........................................322
minute - Return the Current System Clock - Minute (9)..........322
month - Return the Current System Clock - Month (9)............323
mouseb- Return the Mouse Current Button Status (10)..........324
mousex- Return the Mouse Current X Position (10)................325
mousey- Return the Mouse Current Y Position (10)................325
netaddress – What Is My IP Address (20)................................326
netdata – Is There Network Data to Read (20)........................326
Index of Programs
Program 1: Say Hello.....................................................................4
Program 2: Say a Number.............................................................6
Program 3: Say the Answer...........................................................8
Program 4: Say another Answer....................................................8
Program 5: Say Hello to Bob..........................................................9
Program 6: Say it One More Time................................................10
Program 7: Print Hello There.......................................................11
Program 8: Many Prints One Line................................................12
Program 9: Grey Spots................................................................13
Program 10: Face with Rectangles..............................................21
Program 11: Smiling Face with Circles.........................................22
Program 12: Draw a Triangle.......................................................23
Program 13: Draw a Cube...........................................................25
Program 14: Use Plot to Draw Points...........................................27
Program 15: Big Program - Talking Face......................................29
Program 16: Play Three Individual Notes.....................................32
Program 17: List of Sounds..........................................................32
Program 18: Charge!...................................................................36
Program 19: Simple Numeric Variables.......................................37
Program 20: Charge! with Variables............................................38
Program 21: Big Program - Little Fuge in G.................................39
Program 22: School Bus..............................................................43
Program 23: I Like Jim.................................................................49
Program 24: I Like?...................................................................... 51
Program 25: Math-wiz..................................................................53
Program 26: Fancy – Say Name...................................................54
Program 27: Big Program - Silly Story Generator.........................55
Program 28: Compare Two Ages.................................................59
Program 29: Coin Flip..................................................................62
Index of Illustrations
Illustration 1: The BASIC-256 Screen.............................................2
Illustration 2: BASIC-256 - New Dialog...........................................5
Illustration 3: Color Names..........................................................17
Illustration 4: The Cartesian Coordinate System of the Graphics
Output Area................................................................................. 18
Illustration 5: Rectangle..............................................................18
Illustration 6: Circle.....................................................................19
Illustration 7: Sound Waves.........................................................31
Illustration 8: Musical Notes........................................................34
Illustration 9: Charge!..................................................................34
Illustration 10: First Line of J.S. Bach's Little Fuge in G................39
Illustration 11: School Bus...........................................................42
Illustration 12: Breakfast - Flowchart...........................................46
Illustration 13: Soda Machine - Flowchart....................................47
Illustration 14: Compare Two Ages - Flowchart............................61
Illustration 15: Common Windows Fonts......................................90
Illustration 16: Big Red Arrow......................................................92
Illustration 17: Equilateral Triangle..............................................94
Illustration 18: Degrees and Radians...........................................97
Illustration 19: Big Program - A Flower For You - Flower Petal
Stamp........................................................................................ 100
Illustration 20: Right Triangle....................................................182
Illustration 21: Cos() Function....................................................183
Illustration 22: Sin() Function....................................................183
Illustration 23: Tan() Function....................................................185
Illustration 24: Acos() Function..................................................186
Illustration 25: Asin() Function...................................................187
Illustration 26: Atan() Function..................................................187
Illustration 27: What is a Stack..................................................216
Acknowledgments:
Shout-outs go to all the people who have worked on the BASIC-256 project,
at Sourceforge. Most especially, Ian Larsen (aka: DrBlast) for creating the
BASIC-256 computer language and his original vision.
Dedications:
This chapter will introduce the BASIC-256 environment using the print
and say statements. You will see the difference between commands
you send to the computer, strings of text, and numbers that will be
used by the program. We will also explore simple mathematics to
show off just how talented your computer is. Lastly you will learn what
a syntax-error is and how to fix them.
The BASIC-256 window is divided into five sections: the Menu Bar, Tool
Bar, Program Area, Text Output Area, and Graphics Output Area (see
Illustration 1: The BASIC-256 Screen below).
Menu Bar:
The menu bar contains several different drop down menus. These
menus include: “File”, “Edit”, “View”, “Run”, and “About”. The “File”
menu allows you to save, reload saved programs, print and exit. The
“Edit” menu allows you to cut, copy and paste text and images from
the program, text output, and graphics output areas. The “View”
menu will allow you to show or hide various parts of the BASIC-256
window. The “Run” menu will allow you to execute and debug your
programs. The “About” menu option will display a pop-up dialog with
information about BASIC-256 and the version you are using.
Tool Bar:
The menu options that you will use the most are also available on the
tool bar.
Program Area:
This area will display the output of your programs. This may include
words and numbers. If the program needs to ask you a question, the
question (and what you type) will be displayed here.
say “hello”
Program 1: Say Hello
Once you have this program typed in, use the mouse, and click on
“Run” in the tool bar.
say expression
“”
To clear out the program you are working on and completely start a
new program we use the “New” button on the tool bar. The new
button will display the following dialog box:
If you are fine with clearing your program from the screen then click on
the “Yes” button. If you accidentally hit “New” and do
You can also have the say statement speak out numbers. Try the
following program:
say 123456789
Program 2: Say a Number
Once you have this program typed in, use the mouse, and click on
“Run” in the tool bar.
numbers
The brain of the computer (called the Central Processing Unit or CPU
for short) works exclusively with numbers. Everything it does from
graphics, sound, and all the rest is done by manipulating numbers.
Operator Operation
+ Addition
expression1 + expression2
- Subtraction
expression1 - expression2
* Multiplication
expression1 * expression2
/ Division
expression1 / expression2
Table 1: Basic Mathematical Operators
say 12 * (2 + 10)
Program 3: Say the Answer
say 5 / 2
Program 4: Say another Answer
+
-
*
/
()
The + operator also will add strings together. This operation is called
concatenation, or “cat” for short. When we concatenate we are joining
the strings together, like train cars, to make a longer string.
Try another.
+ (concatenate)
Another use for the the plus sign (+) is to tell the computer
to concatenate (join) strings together. If one or both
operands are a string, concatenation will be performed; if
both operands are numeric, then addition is performed.
Programs that use the Text to Speech (TTS) say statement can be very
useful and fun but is is also often necessary to write information
(strings and numbers) to the screen so that the output can be read.
The print statement does just that. In the Program Area type the
following two-line program:
print “hello”
print “there”
Program 7: Print Hello There
Once you have this program typed in, use the mouse, and click on
“Run” in the tool bar. The text output area should now show “hello” on
the first line and “there” on the second line.
print expression
print expression;
The print statement, by default, advances the text area so that the
next print is on the next line. If you place a ; (semicolon) on the end
of the expression being printed, it will suppress the line advance so
that the next print will be on the same line.
cls
print “Hello ”;
print “there, ”;
print “my friend.”
Program 8: Many Prints One Line
cls
In this chapter we will be getting graphical. You will learn how to draw
rectangles, circles, lines and points of various colors. These programs
will get more and more complex, so you will also learn how to save
your programs to long term storage and how to load them back in so
you can run them again or change them.
Let's start the graphics off by writing a graphical program for our
favorite sports team, the “Grey Spots”. Their colors are blue and grey.
1 # c2_greyspots.kbs
2 # a program for our team - the grey spots
3 clg
4 color blue
5 rect 0,0,300,300
6 color grey
7 circle 149,149,100
8 say "Grey Spots, Grey Spots, Grey spots rule!"
Program 9: Grey Spots
Let's go line by line through the program above. The first line is called
a remark or comment statement. A remark is a place for the
programmer to place comments in their computer code that are
ignored by the system. Remarks are a good place to describe what
complex blocks of code is doing, the program's name, why we wrote a
program, or who the programmer was.
#
rem
On line two you see the clg statement. It is much like the cls
statement from Chapter 1, except that the clg statement will clear the
graphic output area of the screen.
clg
Line three contains the color statement. It tells BASIC-256 what color
to use for the next drawing action. You may define colors either by
using one of the eighteen standard color names or you may define one
of over 16 million different colors by mixing the primary colors of light
(red, green, and blue) together.
When you are using the numeric method to define your custom color
be sure to limit the values from 0 to 255. Zero (0) represents no light
of that component color and 255 means to shine the maximum. Bright
white is represented by 255, 255, 255 (all colors of light) where black
is represented by 0, 0, 0 (no colors at all). This numeric representation
is known as the RGB triplet. Illustration 3 shows the named colors and
their numeric values.
color color_name
color red, green, blue
color RGB_number
The color statement allows you to set the color that will be
drawn next. You may follow the color statement with a
color name (black, white, red, darkred, green, darkgreen,
blue, darkblue, cyan, darkcyan, purple, darkpurple, yellow,
darkyellow, orange, darkorange, grey/gray,
darkgrey/darkgray), with three numbers (0-255)
representing how much red, blue, and green should be used
to make the color, or with a single value representing red *
256 ^2 + green * 256 + green.
The graphics display area, by default is 300 pixels wide (x) by 300
pixels high (y). A pixel is the smallest dot that can be displayed on
your computer monitor. The top left corner is the origin (0,0) and the
bottom right is (299,299). Each pixel can be represented by two
numbers, the first (x) is how far over it is and the second (y) represents
how far down. This way of marking points is known as the Cartesian
Coordinate System to mathematicians.
Illustration 5: Rectangle
You can see the the rectangle in the program starts in the top left
corner and fills the graphics output area.
Illustration 6:
Circle
circle x, y, radius
Here are a couple of sample programs that use the new statements
clg, color, rect and circle. Type the programs in and modify them.
Make them a frowning face, alien face, or look like somebody you
know.
1 # c2_rectanglesmile.kbs
2
3 # clear the screen
4 clg
5
6 # draw the face
7 color yellow
8 rect 0,0,299,299
9
10 # draw the mouth
11 color black
12 rect 100,200,100,25
13
14 # put on the eyes
15 color black
16 rect 75,75,50,50
17 rect 175,75,50,50
18
19 say "Hello."
Program 10: Face with Rectangles
1 # c2_circlesmile.kbs
2
3 # clear the screen
4 clg
5 color white
6 rect 0,0,300,300
7
8 # draw the face
9 color yellow
10 circle 150,150,150
11
12 # draw the mouth
13 color black
14 circle 150,200,70
15 color yellow
16 circle 150,150,70
17
18 # put on the eyes
19 color black
20 circle 100,100,30
21 circle 200,100,30
Program 11: Smiling Face with Circles
Now that the programs are getting more complex, you may want to
save them so that you can load them back in the future.
You may store a program by using the Save button on the tool bar
or Save option on the File menu. A dialog will display asking you for a
file name, if it is a new program, or will save the changes you have
made (replacing the old file).
If you do not want to replace the old version of the program and you
want to store it using a new name you may use the Save As option on
the File menu to save a copy with a different name.
To load a previously saved program you would use the Open button
The next drawing statement is line. It will draw a line one pixel wide,
of the current color, from one point to another point. Program 12
shows an example of how to use the line statement.
Draw a line one pixel wide from the starting point to the
ending point, using the current color.
The next program is a sample of what you can do with complex lines.
It draws a cube on the screen.
The last graphics statement covered in this chapter is plot. The plot
statement sets a single pixel (dot) on the screen. For most of us these
are so small, they are hard to see. Later we will write programs that
will draw groups of pixels to make very detailed images.
10 plot 101,100
11
12 color darkgreen
13 plot 200,200
Program 14: Use Plot to Draw Points
plot x, y
1 # c2_talkingface.kbs
2 # draw face background with eyes
3 color yellow
4 rect 0,0,300,300
5 color black
6 rect 75,75,50,50
7 rect 175,75,50,50
8
9 #erase old mouth
10 color yellow
11 rect 0,150,300,150
12 # draw new mouth
13 color black
14 rect 125,175,50,100
15 # say word
16 say "i"
17
18 color yellow
19 rect 0,150,300,150
20 color black
21 rect 100,200,100,50
22 say "am"
23
24 color yellow
25 rect 0,150,300,150
26 color black
27 rect 125,175,50,100
28 say "glad"
29
30 color yellow
31 rect 0,150,300,150
32 color black
33 rect 125,200,50,50
34 say "you"
35
36 color yellow
37 rect 0,150,300,150
38 color black
39 rect 100,200,100,50
40 say "are"
41
42 color yellow
43 rect 0,150,300,150
44 color black
45 rect 125,200,50,50
46 say "my"
47
48 # draw whole new face with round smile.
49 color yellow
50 rect 0,0,300,300
51 color black
52 circle 150,175,100
53 color yellow
54 circle 150,150,100
55 color black
56 rect 75,75,50,50
57 rect 175,75,50,50
58 say "friend"
Program 15: Big Program - Talking Face
Now that we have color and graphics, let's add sound and make some
music. Basic concepts of the physics of sound, numeric variables, and
musical notation will be introduced. You will be able to translate a
tune into frequencies and durations to have the computer synthesize a
voice.
Another property of a sound is it's length. Computers are very fast and
can measure times accurately to a millisecond (ms). A millisecond
(ms) is 1/1000 (one thousandths) of a second.
1 # c3_sounds.kbs
2 sound 233, 1000
3 sound 466, 500
4 sound 233, 1000
Program 16: Play Three Individual Notes
You may have heard a clicking noise in your speakers between the
notes played in the last example. This is caused by the computer
creating the sound and needing to stop and think a millisecond or so.
The sound statement also can be written using a list of frequencies and
durations to smooth out the transition from one note to another.
1 # c3_soundslist.kbs
2 sound {233, 1000, 466, 500, 233, 1000}
Program 17: List of Sounds
This second sound program plays the same three tones for the same
duration but the computer creates and plays all of the sounds at once,
making them smoother.
Take a little piece of music and then look up the frequency values for
each of the notes. Why don't we have the computer play “Charge!”.
The music is in Illustration 9. You might notice that the high G in the
music is not on the musical notes; if a note is not on the chart you can
double (to make higher) or half (to make lower) the same note from
one octave away.
Illustration 9: Charge!
Now that we have the frequencies we need the duration for each of the
notes. Table 2 shows most of the common note and rest symbols, how
long they are when compared to each other, and a few typical
durations.
Now with the formula and table to calculate note durations, we can
write the program to play “Charge!”.
Numeric Variables:
Numeric variable
1 # c3_numericvariables.kbs
2 numerator = 30
3 denominator = 5
4 result = numerator / denominator
5 print result
Program 19: Simple Numeric Variables
The program above uses three variables. On line two it stores the
value 30 into the location named “numerator”. Line three stores the
value 5 in the variable “denominator”. Line four takes the value from
“numerator” divides it by the value in the “denominator” variable and
stores the value in the variable named “result”.
1 # c3_charge2.kbs
2 # play charge - use variables
3 beats = 120
4 dottedeighth = 1000 * 60 / beats * .75
5 eighth = 1000 * 60 / beats * .5
6 sound {392, dottedeighth, 523, dottedeighth, 659,
dottedeighth, 784, eighth, 659, eighth, 784,
eighth}
7 say "Charge!"
Program 20: Charge! with Variables
1 # c3_littlefuge.kbs
2 # Music by J.S.Bach - XVIII Fuge in G moll.
3 tempo = 100 # beats per minute
4 milimin = 1000 * 60 # miliseconds in a minute
5 q = milimin / tempo # quarter note is a beat
6 h = q * 2 # half note (2 quarters)
7 e = q / 2 # eight note (1/2 quarter)
8 s = q / 4 # sixteenth note (1/4 quarter)
9 de = e + s # dotted eight - eight + 16th
10 dq = q + e # doted quarter - quarter + eight
11
12 sound{392, q, 587, q, 466, dq, 440, e, 392, e,
466, e, 440, e, 392, e, 370, e, 440, e, 294, q,
392, e, 294, e, 440, e, 294, e, 466, e, 440, s,
392, s, 440, e, 294, e, 392, e, 294, s, 392, s,
440, e, 294, s, 440, s, 466, e, 440, s, 392, s,
440, s, 294, s}
Program 21: Big Program - Little Fuge in G
You are like the great explorers Christopher Columbus, Neil Armstrong,
and Yuri Gagarin (the first human in space). You have an unlimited
universe to explore and to create within the computer. The only
restrictions on where you can go will be your creativity and willingness
to learn.
Pseudocode:
Pseudocode is a fancy word for writing out, step by step, what your
program needs to be doing. The word pseudocode comes from the
Greek prefix “pseudo-” meaning fake and “code” for the actual
computer programming statements. It is not created for the computer
to use directly but it is made to help you understand the complexity of
a problem and to break it down into meaningful pieces.
Now let's break the initial steps into smaller pieces and write our
pseudocode:
Now that we have our program worked out, all we need to do is write
it:
The completed school bus program (Program 22) is listed below. Look
at the finished program and you will see comment statements used in
the program to help the programmer remember the steps used during
the initial problem solving.
1 # schoolbus.kbs
2 clg
3 # draw wheels
4 color black
5 circle 50,120,20
6 circle 200,120,20
7 # draw bus body
8 color yellow
9 rect 50,0,200,100
10 rect 0,50,50,50
Program 22: School Bus
In the school bus example we have just seen there were many
different ways to break up the problem. You could have drawn the bus
first and the wheels last, you could have drawn the front before the
Flowcharting:
This brief introduction to flowcharts will only cover a small part of what
that can be done with them, but with a few simple symbols and
connectors you will be able to model very complex processes. This
technique will serve you well not only in programming but in solving
many problems you will come across. Here are a few of the basic
symbols:
You just rolled out of bed and your mom has given you two choices for
breakfast. You can have your favorite cold cereal or a scrambled egg.
If you do not choose one of those options you can go to school hungry.
Start
No Yes
Cereal?
Fix eggs.
Eat.
Finish
Another food example. You are thirsty and want a soda from the
machine. Take a look at Illustration 13 (below).
Start
No Do we have Yes
enough change
for the machine?
Insert coin.
No Have we Yes
Inserted enough?
Make selection.
No Yes
Sold out?
Get can.
Drink.
Finish
Notice in the second flowchart that there are a couple of times that we
may need to repeat a process. You have not seen how to do that in
BASIC-256, but it will be covered in the next few chapters.
In Chapter 3 you got to see numeric variables, which can only store
whole or decimal numbers. Sometimes you will want to store a string,
text surrounded by “”, in the computer's memory. To do this we use a
new type of variable called the string variable. A string variable is
denoted by appending a dollar sign $ on a variable name.
You may assign and retrieve values from a string variable the same
way you use a numeric variable. Remember, the variable name, case
sensitivity, and reserved word rules are the same with string and
numeric variables.
1 # ilikejim.kbs
2 name$ = "Jim"
3 firstmessage$ = name$ + " is my friend."
4 secondmessage$ = "I like " + name$ + "."
5 print firstmessage$
6 say firstmessage$
7 print secondmessage$
8 say secondmessage$
Program 23: I Like Jim
Jim is my friend.
I like Jim.
Sample Output 23: I Like Jim
String variable
Let's take Program 23 and modify it so that it will ask you for a name
and then say hello to that person.
1 # ilikeinput.kbs
2 input “enter your name>”, name$
3 firstmessage$ = name$ + " is my friend."
4 secondmessage$ = "I like " + name$ + "."
5 print firstmessage$
6 say firstmessage$
7 print secondmessage$
8 say secondmessage$
Program 24: I Like?
1 # mathwiz.kbs
2 input "a? ", a
3 input "b? ", b
4 print a + "+" + b + "=" + (a+b)
5 print a + "-" + b + "=" + (a-b)
6 print b + "-" + a + "=" + (b-a)
7 print a + "*" + b + "=" + (a*b)
8 print a + "/" + b + "=" + (a/b)
9 print b + "/" + a + "=" + (b/a)
Program 25: Math-wiz
a? 7
b? 56
7+56=63
7-56=-49
56-7=49
7*56=392
7/56=0.125
56/7=8
Sample Output 25: Math-wiz
1 # sayname.kbs
2 input "What is your name?", name$
3 input "How old are you?", age
4 greeting$ = "It is nice to meet you, " + name$ +
"."
5 print greeting$
6 say greeting$
7 greeting$ = "In 8 years you will be " + (age +
8) + " years old. Wow, thats old!"
8 print greeting$
9 say greeting$
Program 26: Fancy – Say Name
1 # sillystory.kbs
2
3 print "A Silly Story."
4
5 input "Enter a noun? ", noun1$
6 input "Enter a verb? ", verb1$
A Silly Story.
Enter a noun? car
Enter a verb? walk
Enter a room in your house? kitchen
Enter a verb? sing
Enter a noun? television
Enter an adjective? huge
Enter a verb? watch
Enter a noun? computer
Enter Your Name? Jim
A silly story, by Jim.
One day, not so long ago, I saw a car walk down the
stairs.
It was going to my kitchen to sing a television
The car became huge when I watch with a computer.
The End.
Sample Output 27: Big Program - Silly Story Generator
The BASIC-256 language has one more special type of data that can be
stored in numeric variables. It is the Boolean data type. Boolean
values are either true or false and are usually the result of comparisons
and logical operations. Also to make them easier to work with there
are two Boolean constants that you can use in expressions, they are:
true and false.
true
false
The two Boolean constants true and false can be used in any
numeric or logical expression but are usually the result of a
comparison or logical operator. Actually, the constant true
is stored as the number one (1) and false is stored as the
number zero (0).
Comparison Operators:
Previously we have discussed the basic arithmetic operators, it is now
Operator Operation
< Less Than
expression1 < expression2
Return true if expression1 is less than expression2, else return
false.
<= Less Than or Equal
expression1 <= expression2
Return true if expression1 is less than or equal to expression2,
else return false.
> Greater Than
expression1 > expression2
Return true if expression1 is greater than expression2, else
return false.
>= Greater Than or Equal
expression1 >= expression2
Return true if expression1 is greater than or equal to
expression2, else return false.
= Equal
expression1 = expression2
Return true if expression1 is equal to expression2, else return
false.
<> Not Equal
Expression1 <> expression2
Return true if expression1 is not equal to expression2, else
return false.
Table 6: Comparison Operators
The six comparison operations are: less than (<), less than
or equal (<=), greater than (>), greater than or equal (>=),
equal (=), and not equal (<>). They are used to compare
numbers and strings. Strings are compared alphabetically
left to right. You may also use parenthesis to group
operations together.
Start
Finish
Random Numbers:
When we are developing games and simulations it may become
necessary for us to simulate dice rolls, spinners, and other random
rand
1 # coinflip.kbs
2 coin = rand
3 if coin < .5 then print "Heads."
4 if coin >= .5 then print "Tails."
Program 29: Coin Flip
Tails.
Sample Output 29: Coin Flip
In program 5.2 you may have been tempted to use the rand
expression twice, once in each if statement. This would
have created what we call a “Logical Error”.
Logical Operators:
Operator Operation
expression1
AND
TRUE FALSE
expression TRUE TRUE FALSE
2 FALSE FALSE FALSE
OR Logical Or
expression1 OR expression2
If either expression1 or experssion2 are true then return a true
value, else return false.
expression1
OR
TRUE FALSE
expression TRUE TRUE TRUE
2 FALSE TRUE FALSE
expression1
OR
TRUE FALSE
expression TRUE FALSE TRUE
2 FALSE TRUE FALSE
NOT
expression TRUE FALSE
1 FALSE TRUE
if condition then
statement(s) to execute when true
end if
1 # dice.kbs
2 die1 = int(rand * 6) + 1
3 die2 = int(rand * 6) + 1
4 total = die1 + die2
5
6 print "die 1 = " + die1
7 print "die 2 = " + die2
8 print "you rolled " + total
9 say "you rolled " + total
10
11 if total = 2 then
12 print "snake eyes!"
13 say "snake eyes!"
14 end if
15 if total = 12 then
16 print "box cars!"
17 say "box cars!"
18 end if
19 if die1 = die2 then
20 print "doubles - roll again!"
21 say "doubles - roll again!"
22 end if
Program 30: Rolling Dice
die 1 = 6
die 2 = 6
you rolled 12
box cars!
doubles - roll again!
Sample Output 30: Rolling Dice
The third and last form of the if statement is the if/else/end if. This
extends the if/end if statements by allowing you to create a block of
code to execute if the condition is true and another block to execute
when the condition is false.
if condition then
statement(s) to execute when true
else
statement(s) to execute when false
end if
The if, else, and end if statements allow you to define two
blocks of programming code. The first block, after the then
clause, executes if the condition is true and the second
block, after the else clause, will execute when the condition
if false.
Heads.
Sample Output 31: Coin Flip – With Else
Nesting Decisions:
One last thing. With the if/end if and the if/else/end if statements it is
possible to nest an if inside the code of another. This can become
confusing but you will see this happening in future chapters.
1 # dieroll.kbs
2 # hw - height and width of the dots on the dice
3 hw = 70
4 # margin - space before each dot
So far our program has started, gone step by step through our
instructions, and quit. While this is OK for simple programs, most
programs will have tasks that need to be repeated, things counted, or
both. This chapter will show you the three looping statements, how to
speed up your graphics, and how to slow the program down.
1 # for.kbs
2 for t = 1 to 10
3 print t
4 say t
5 next t
Program 33: For Statement
1
2
3
4
5
6
7
8
9
10
Sample Output 33: For Statement
1 # forstep2.kbs
2 for t = 0 to 10 step 2
3 print t
4 say t
5 next t
Program 34: For Statement – With Step
0
2
4
6
8
10
Sample Output 34: For Statement – With Step
1 # moire.kbs
2 clg
3 color black
4 for t = 1 to 300 step 3
5 line 0,0,300,t
6 line 0,0,t,300
7 next t
Program 35: Moiré Pattern
1 # forstepneg1.kbs
2 for t = 10 to 0 step -1
3 print t
4 pause 1.0
5 next t
Program 36: For Statement – Countdown
10
9
8
7
6
5
4
3
2
1
0
Sample Output 36: For Statement – Countdown
pause seconds
1 # dountil.kbs
2 do
3 input "enter a number from 1 to 10?",n
4 until n>=1 and n<=10
5 print "you entered " + n
Program 37: Get a Number from 1 to 10
do
statement(s)
until condition
1 # dountilfor.kbs
2 t = 1
3 do
4 print t
5 t = t + 1
6 until t >= 11
Program 38: Do/Until Count to 10
1
2
3
4
5
6
7
8
9
10
Sample Output 38: Do/Until Count to 10
The third type of loop is the while/end while. It tests a condition before
executing each iteration and if it evaluates to true then executes the
code in the loop. The while/end while loop may execute the code
inside the loop zero or more times.
Sometimes we will want a program to loop forever, until the user stops
the program. This can easily be accomplished using the Boolean true
constant (see Program 39).
1 # whiletrue.kbs
2 while true
3 print “nevermore “;
4 end while
Program 39: Loop Forever
nevermore.
nevermore.
nevermore.
nevermore.
nevermore.
… runs until you stop it
Sample Output 39: Loop Forever
while condition
statement(s)
end while
Do the statements in the block over and over again while the
condition is true. The statements will be executed zero or
more times.
1 # whilefor.kbs
2 t = 1
3 while t <= 10
4 print t
5 t = t + 1
6 end while
Program 40: While Count to 10
1
2
3
4
5
6
7
8
9
10
Sample Output 40: While Count to 10
Fast Graphics:
fastgraphics
refresh
1 # kalidescope.kbs
2 clg
3 fastgraphics
4 for t = 1 to 100
5 r = int(rand * 256)
6 g = int(rand * 256)
7 b = int(rand * 256)
8 x = int(rand * 300)
9 y = int(rand * 300)
10 h = int(rand * 100)
11 w = int(rand * 100)
12 color rgb(r,g,b)
13 rect x,y,w,h
14 rect 300-x-w,y,w,h
15 rect x,300-y-h,w,h
16 rect 300-x-w,300-y-h,w,h
17 next t
18 refresh
Program 41: Kalidescope
1 # bouncingball.kbs
2 fastgraphics
3 clg
4
5 # starting position of ball
6 x = rand * 300
7 y = rand * 300
8 # size of ball
9 r = 10
10 # speed in x and y directions
11 dx = rand * r + 2
12 dy = rand * r + 2
13
14 color green
15 rect 0,0,300,300
16
17 while true
18 # erase old ball
19 color white
20 circle x,y,r
21 # calculate new position
22 x = x + dx
23 y = y + dy
24 # if off the edges turn the ball around
25 if x < 0 or x > 300 then
26 dx = dx * -1
27 sound 1000,50
28 end if
29 # if off the top or bottom turn the ball
around
30 if y < 0 or y > 300 then
31 dy = dy * -1
32 sound 1500,50
33 end if
This chapter we will show you how to draw colorful words and special
shapes on your graphics window. Several topics will be covered,
including: fancy text; drawing polygons on the graphics output area;
and stamps, where we can position, re-size, and rotate polygons. You
also will be introduced to angles and how to measure them in radians.
You have been introduced to the print statement (Chapter 1) and can
output strings and numbers to the text output area. The text and font
commands allow you to place numbers and text on the graphics output
area.
1 # graphichello.kbs
2 clg
3 color red
4 font "Tahoma",33,100
5 text 100,100,"Hello."
6 font "Impact",33,50
7 text 100,150,"Hello."
8 font "Courier New",33,50
9 text 100,250,"Hello."
Program 43: Hello on the Graphics Output Area
Set the font, size, and weight for the next text statement to
use to render text on the graphics output area.
Argument Description
font_name String containing the system font name to
use. A font must be previously loaded in the
system before it may be used. Common font
names under Windows include: "Verdana",
"Courier New", "Tahoma", "Arial", and "Times
New Roman".
size_in_point Height of text to be rendered in a
measurement known as point. There are 72
points in an inch.
weight Number from 1 to 100 representing how dark
letter should be. Use 25 for light, 50 for
normal, and 75 for bold.
text x, y, expression
1 # resizegraphics.kbs
2 graphsize 500,500
3 xcenter = graphwidth/2
4 ycenter = graphheight/2
5
6 color black
7 line xcenter, ycenter - 10, xcenter, ycenter + 10
8 line xcenter - 10, ycenter, xcenter + 10, ycenter
9
10 font "Tahoma",12,50
11 text xcenter + 10, ycenter + 10, "Center at (" +
xcenter + "," + ycenter + ")"
Program 44: Re-size Graphics
graphwidth or graphwidth()
graphheight or graphheight()
Let's draw a big red arrow in the middle of the graphics output area.
First, draw it on a piece of paper so we can visualize the coordinates of
the vertices of the arrow shape.
Now start at the top of the arrow going clockwise and write down the x
and y values.
1 # bigredarrow.kbs
2 clg
3 color red
4 poly {150, 100, 200, 150, 175, 150, 175, 200,
125, 200, 125, 150, 100, 150}
Program 45: Big Red Arrow
Draw a polygon
Stamping a Polygon:
Let's draw an equilateral triangle (all sides are the same length) on a
piece of paper. Put the point (0,0) at the top and make each leg 10
long (see Illustration 17).
Now we will create a program, using the simplest form of the stamp
statement, to fill the screen with triangles. Program 46 Will do just
that. It uses the triangle stamp inside two nested loops to fill the
screen.
1 # stamptri.kbs
2 clg
3 color black
4 for x = 25 to 200 step 25
5 for y = 25 to 200 step 25
6 stamp x, y, {0, 0, 5, 8.6, -5, 8.6}
7 next y
8 next x
Program 46: Fill Screen with Triangles
Radians 0 to 2π
1 # stamptri2.kbs
2 clg
3 color black
4 for t = 1 to 100
5 x = rand * graphwidth
6 y = rand * graphheight
7 s = rand * 7
8 r = rand * 2 * pi
9 stamp x, y, s, r, {0, 0, 5, 8.6, -5, 8.6}
10 next t
Program 47: One Hundred Random Triangles
pi
1 # aflowerforyou.kbs
2 clg
3
4 color green
5 rect 148,150,4,150
6
7 color 255,128,128
8 for r = 0 to 2*pi step pi/4
9 stamp graphwidth/2, graphheight/2, 2, r, {0,
0, 5, 20, 0, 25, -5, 20}
10 next r
11
12 color 128,128,255
13 for r = 0 to 2*pi step pi/5
14 stamp graphwidth/2, graphheight/2, 1, r, {0,
This chapter introduces the concept of setting labels within your code
and then jumping to those labels. This will allow a program to execute
the code in a more complex order. You will also see the subroutine. A
gosub acts like a jump with the ability to jump back.
1 # gotodemo.kbs
2 top:
3 print "hi"
4 goto top
Program 49: Goto With a Label
hi
hi
hi
hi
... repeats forever
Sample Output 49: Goto With a Label
label:
goto label
1 # textclock.kbs
2 fastgraphics
3 font "Tahoma", 20, 100
4 color blue
5 rect 0, 0, 300, 300
6 color yellow
7 text 0, 0, "My Clock."
8 showtime:
9 color blue
10 rect 100, 100, 200, 100
11 color yellow
12 text 100, 100, hour + ":" + minute + ":" + second
13 refresh
14 pause 1.0
15 goto showtime
Program 50: Text Clock
hour or hour()
minute or minute()
second or second()
month or month()
day or day()
year or year()
1 # gosubdemo.kbs
2 gosub showline
3 print "hi"
4 gosub showline
5 print "there"
6 gosub showline
7 end
8
9 showline:
10 print "------------------"
11 return
Program 51: Gosub
------------------
hi
------------------
there
------------------
Sample Output 51: Gosub
gosub label
return
end
Now that we have seen the subroutine in action let's write a new digital
clock program using a subroutine to format the time and date better
(Program 52).
1 # textclockimproved.kbs
2
3 fastgraphics
4
5 while true
6 color blue
7 rect 0, 0, graphwidth, graphheight
8 color white
9 font "Times New Roman", 40, 100
10
11 line$ = ""
12 n = month + 1
13 gosub addtoline
14 line$ = line$ + "/"
15 n = day
16 gosub addtoline
17 line$ = line$ + "/"
18 line$ = line$ + year
1 # roll2dice.kbs
2 clg
3 total = 0
4
5 x = 30
6 y = 30
7 roll = int(rand * 6) + 1
8 total = total + roll
9 gosub drawdie
10
11 x = 130
12 y = 130
13 roll = int(rand * 6) + 1
14 total = total + roll
15 gosub drawdie
16
17 print "you rolled " + total + "."
18 end
19
20 drawdie:
21 # set x,y for top left and roll for number of
dots
22 # draw 70x70 with dots 10x10 pixels
23 color black
24 rect x,y,70,70
25 color white
26 # top row
27 if roll <> 1 then rect x + 10, y + 10, 10, 10
28 if roll = 6 then rect x + 30, y + 10, 10, 10
29 if roll >= 4 and roll <= 6 then rect x + 50, y +
10, 10, 10
30 # middle
31 if roll = 1 or roll = 3 or roll = 5 then rect x +
30, y + 30, 10, 10
32 # bottom row
This chapter will show you how to make your program respond to a
mouse. There are two different ways to use the mouse: tracking mode
and clicking mode. Both are discussed with sample programs.
Tracking Mode:
In mouse tracking mode, there are three numeric functions (mousex,
mousey, and mouseb) that will return the coordinates of the mouse
pointer over the graphics output area. If the mouse is not over the
graphics display area then the mouse movements will not be recorded
(the last location will be returned).
1 # mousetrack.kbs
2 print "Move the mouse around the graphics window."
3 print "Click left mouse button to quit."
4
5 fastgraphics
6
7 # do it over and over until the user clicks left
8 while mouseb <> 1
9 # erase screen
10 color white
11 rect 0, 0, graphwidth, graphheight
12 # draw new ball
13 color red
14 circle mousex, mousey, 10
15 refresh
16 end while
17
18 print "all done."
19 end
Program 54: Mouse Tracking
mousex or mousex()
mousey or mousey()
mouseb or mouseb()
Clicking Mode:
1 # mouseclick.kbs
2 # X marks the spot where you click
3 print "Move the mouse around the graphics window"
4 print "click left mouse button to mark your spot"
5 print "click right mouse button to stop."
6 clg
7 clickclear
8 while clickb <> 2
9 # clear out last click and
10 # wait for the user to click a button
11 clickclear
12 while clickb = 0
13 pause .01
14 end while
15 #
16 color blue
17 stamp clickx, clicky, 5, {-1, -2, 0, -1, 1,
-2, 2, -1, 1, 0, 2, 1, 1, 2, 0, 1, -1, 2, -2, 1,
-1, 0, -2, -1}
18 end while
19 print "all done."
20 end
Program 55: Mouse Clicking
clickx or clickx()
clicky or clicky()
clickb or clickb()
clickclear
The big program this chapter uses the mouse to move color
sliders so that we can see all 16,777,216 different colors on
the screen.
1 # colorchooser.kbs
2 fastgraphics
3
4 print "colorchooser - find a color"
5 print "click and drag red, green and blue sliders"
6
7 # variables to store the color parts
8 r = 128
9 g = 128
10 b = 128
11
12 gosub display
13
14 while true
15 # wait for click
16 while mouseb = 0
17 pause .01
18 end while
19 # change color sliders
20 if mousey < 75 then
21 r = mousex
22 if r > 255 then r = 255
23 end if
24 if mousey >= 75 and mousey < 150 then
25 g = mousex
26 if g > 255 then g = 255
27 end if
This chapter will show you how to make your program respond to the
user when a key is pressed (arrows, letters, and special keys) on the
keyboard.
The key function returns the last raw keyboard code generated by the
system when a key was pressed. Certain keys (like control-c and
function-1) are captured by the BASIC256 window and will not be
returned by key. After the last key press value has been returned the
function value will be set to zero (0) until another keyboard key has
been pressed.
The key values for printable characters (0-9, symbols, letters) are the
same as their upper case Unicode values regardless of the status of
the caps-lock or shift keys.
1 # readkey.kbs
2 print "press a key - Q to quit"
3 do
4 k = key
5 if k <> 0 then
6 if k >=32 and k <= 127 then
7 print chr(k) + "=";
8 end if
9 print k
10 end if
11 until k = asc("Q")
12 end
Program 57: Read Keyboard
key
key()
The key function returns the value of the last keyboard key
the user has pressed. Once the key value is read by the
function, it is set to zero to denote that no key has been
pressed.
Unicode
See: http://www.unicode.org
asc(expression)
chr(expression)
1 # moveball.kbs
2 print "use i for up, j for left, k for right, m for
down, q to quit"
3
4 fastgraphics
5 clg
6 ballradius = 20
7
8 # position of the ball
9 # start in the center of the screen
10 x = graphwidth /2
11 y = graphheight / 2
12
13 # draw the ball initially on the screen
14 gosub drawball
15
16 # loop and wait for the user to press a key
17 while true
18 k = key
19 if k = asc("I") then
20 y = y - ballradius
21 if y < ballradius then y = graphheight -
ballradius
22 gosub drawball
23 end if
24 if k = asc("J") then
25 x = x - ballradius
26 if x < ballradius then x = graphwidth -
ballradius
27 gosub drawball
28 end if
29 if k = asc("K") then
30 x = x + ballradius
31 if x > graphwidth - ballradius then x =
ballradius
32 gosub drawball
33 end if
34 if k = asc("M") then
35 y = y + ballradius
36 if y > graphheight - ballradius then y =
ballradius
37 gosub drawball
38 end if
39 if k = asc("Q") then end
40 end while
41
42 drawball:
43 color white
44 rect 0, 0, graphwidth, graphheight
45 color red
46 circle x, y, ballradius
47 refresh
48 return
Program 58: Move Ball
1 # fallinglettergame.kbs
2
3 speed = .15 # drop speed - lower to make faster
4 nletters = 10 # letters to play
5
6 score = 0
7 misses = 0
8 color black
9
10 fastgraphics
11
12 clg
13 font "Tahoma", 20, 50
14 text 20, 80, "Falling Letter Game"
15 text 20, 140, "Press Any Key to Start"
16 refresh
17 # clear keyboard and wait for any key to be
pressed
18 k = key
19 while key = 0
20 pause speed
21 end while
22
23 for n = 1 to nletters
24 letter = int((rand * 26)) + asc("A")
25 x = 10 + rand * 225
26 for y = 0 to 250 step 20
27 clg
28 # show letter
29 font "Tahoma", 20, 50
30 text x, y, chr(letter)
31 # show score and points
32 font "Tahoma", 12, 50
33 value = (250 - y)
34 text 10, 270, "Value "+ value
35 text 200, 270, "Score "+ score
36 refresh
37 k = key
38 if k <> 0 then
39 if k = letter then
40 score = score + value
41 else
42 score = score - value
43 end if
44 goto nextletter
45 end if
46 pause speed
47 next y
48 misses = misses + 1
49 nextletter:
50 next n
51
52 clg
53 font "Tahoma", 20, 50
54 text 20, 40, "Falling Letter Game"
55 text 20, 80, "Game Over"
56 text 20, 120, "Score: " + score
57 text 20, 160, "Misses: " + misses
58 refresh
59 end
Program 59: Big Program - Falling Letter Game
So far we have seen how to create shapes and graphics using the built
in drawing statements. The imgload statement allows you to load a
picture from a file and display it in your BASIC-256 programs.
Most of the time you will want to save the program into the
same folder that the image or sound file is in BEFORE you
run the program. This will set your current working directory
so that BASIC-256 can find the file to load.
imgload x, y, filename
imgload x, y, scale, filename
imgload x, y, scale, rotation, filename
The imgload statement also allows optional scaling and rotation like
the stamp statement does. Look at Program 61 for an example.
So far we have explored making sounds and music using the sound
command and text to speech with the say statement. BASIC-256 will
also play sounds stored in WAV files. The playback of a sound from a
WAV file will happen in the background. Once the sound starts the
program will continue to the next statement and the sound will
continue to play.
1 # spinner.kbs
2 fastgraphics
3 wavplay "roll.wav"
4
5 # setup spinner
6 angle = rand * 2 * pi
7 speed = rand * 2
8 color darkred
9 rect 0,0,300,300
10
11 for t = 1 to 100
12 # draw spinner
13 color white
14 circle 150,150,150
15 color black
16 line 150,300,150,0
17 line 300,150,0,150
18 text 100,100,"A"
19 text 200,100,"B"
20 text 200,200,"C"
21 text 100,200,"D"
22 color darkgreen
23 line 150,150,150 + cos(angle)*150, 150 +
sin(angle)*150
24 refresh
25 # update angle for next redraw
26 angle = angle + speed
27 speed = speed * .9
28 pause .05
29 next t
30
31 # wait for sound to complete
32 wavwait
Program 62: Spinner with Sound Effect
wavplay filename
wavwait
wavstop
Sprites are special graphical objects that can be moved around the
screen without having to redraw the entire screen. In addition to being
mobile you can detect when one sprite overlaps (collides) with another.
Sprites make programming complex games and animations much
easier.
1 # sprite_1ball.kbs
2
3 color white
4 rect 0, 0, graphwidth, graphheight
5
6 spritedim 1
7
8 spriteload 0, "blueball.png"
9 spriteplace 0, 100,100
10 spriteshow 0
11
12 dx = rand * 10
13 dy = rand * 10
14
15 while true
16 if spritex(0) <=0 or spritex(0) >= graphwidth
-1 then
17 dx = dx * -1
18 wavplay
"4359__NoiseCollector__PongBlipF4.wav"
19 end if
20 if spritey(0) <= 0 or spritey(0) >=
graphheight -1 then
21 dy = dy * -1
22 wavplay
"4361__NoiseCollector__pongblipA_3.wav"
23 endif
24 spritemove 0, dx, dy
25 pause .05
26 end while
Program 63: Bounce a Ball with Sprite and Sound Effects
As you can see in Program 63 the code to make a ball bounce around
the screen, with sound effects, is much easier than earlier programs to
do this type of animation. When using sprites we must tell BASIC-256
how many there will be (spritedim), we need to set them up
(spriteload or spriteplace), make them visible (spriteshow), and
then move them around (spritemove). In addition to these
statements there are functions that will tell us where the sprite is on
the screen (spritex and spritey), how big the sprite is (spritew and
spriteh) and if the sprite is visible (spritev).
spritedim numberofsprites
By default the sprite will be placed with its center at 0,0 and
it will be hidden. You should move the sprite to the desired
position on the screen (spritemove or spriteplace) and
then show it (spriteshow).
spritehide spritenumber
spriteshow spritenumber
spriteplace spritenumber, x, y
spritev(spritenumber)
spriteh(spritenumber)
spritew(spritenumber)
spritex(spritenumber)
spritey(spritenumber)
The second sprite example (Program 64) we now have two sprites.
The first one (number zero) is stationary and the second one (number
one) will bounce off of the walls and the stationary sprite.
1 # sprite_bumper.kbs
2
3 color white
4 rect 0, 0, graphwidth, graphheight
5
6 spritedim 2
7
8 # stationary bumber
9 spriteload 0, "paddle.png"
10 spriteplace 0,graphwidth/2,graphheight/2
11 spriteshow 0
12
13 # moving ball
14 spriteload 1, "blueball.png"
15 spriteplace 1, 50, 50
16 spriteshow 1
17 dx = rand * 5 + 5
18 dy = rand * 5 + 5
19
20 while true
21 if spritex(1) <=0 or spritex(1) >= graphwidth
-1 then
22 dx = dx * -1
23 end if
24 if spritey(1) <= 0 or spritey(1) >=
graphheight -1 then
25 dy = dy * -1
26 end if
27 if spritecollide(0,1) then
28 dy = dy * -1
29 print "bump"
30 end if
31 spritemove 1, dx, dy
32 pause .05
33 end while
Program 64: Sprite Collision
spritecollide(spritenumber1, spritenumber2)
The “Big Program” for this chapter uses sprites and sounds
to create a paddle ball game.
1 # sprite_paddleball.kbs
2
3 color white
4 rect 0, 0, graphwidth, graphheight
5
6 spritedim 2
7
8 spriteload 1, "greenball.png"
9 spriteplace 1, 100,100
10 spriteshow 1
11 spriteload 0, "paddle.png"
12 spriteplace 0, 100,270
13 spriteshow 0
14
15 dx = rand * .5 + .25
16 dy = rand * .5 + .25
17
18 bounces = 0
19
20 while spritey(1) < graphheight -1
21 k = key
22 if chr(k) = "K" then
23 spritemove 0, 20, 0
24 end if
25 if chr(k) = "J" then
26 spritemove 0, -20, 0
27 end if
28 if spritecollide(0,1) then
29 # bounce back ans speed up
30 dy = dy * -1
31 dx = dx * 1.1
32 bounces = bounces + 1
33 wavstop
34 wavplay
"96633__CGEffex__Ricochet_metal5.wav"
35 # move sprite away from paddle
36 while spritecollide(0,1)
37 spritemove 1, dx, dy
38 end while
39 end if
40 if spritex(1) <=0 or spritex(1) >= graphwidth
-1 then
41 dx = dx * -1
42 wavstop
43 wavplay
"4359__NoiseCollector__PongBlipF4.wav"
44 end if
45 if spritey(1) <= 0 then
46 dy = dy * -1
47 wavstop
48 wavplay
"4361__NoiseCollector__pongblipA_3.wav"
49 end if
50 spritemove 1, dx, dy
51 end while
52
53 print "You bounced the ball " + bounces + "
times."
Program 65: Paddleball with Sprites
1 # numeric1d.kbs
2
3 dim a(10)
4
5 a[0] = 100
6 a[1] = 200
7 a[3] = a[1] + a[2]
8
9 input "Enter a number", a[9]
10 a[8] = a[9] - a[3]
11
12 for t = 0 to 9
13 print "a[" + t + "] = " + a[t]
14 next t
Program 66: One-dimensional Numeric Array
Enter a number63
a[0] = 100
a[1] = 200
a[2] = 0
a[3] = 200
a[4] = 0
a[5] = 0
a[6] = 0
a[7] = 0
a[8] = -137
a[9] = 63
Sample Output 66: One-dimensional Numeric Array
dim variable(items)
dim variable$(items)
dim variable(rows, columns)
dim variable$(rows, columns)
variable[index]
variable[rowindex, columnindex]
variable$[index]
variable$[rowindex, columnindex]
It may be confusing, but BASIC-256 uses zero (0) for the first
element in an array and the last element has an index one
less than the size. Computer people call this a zero-indexed
array.
1 # manyballbounce.kbs
2 fastgraphics
3
4 r = 10 # size of ball
5 balls = 50 # number of balls
6
7 dim x(balls)
8 dim y(balls)
9 dim dx(balls)
10 dim dy(balls)
11 dim colors(balls)
12
13 for b = 0 to balls-1
14 # starting position of balls
15 x[b] = 0
16 y[b] = 0
17 # speed in x and y directions
18 dx[b] = rand * r + 2
19 dy[b] = rand * r + 2
20 # each ball has it's own color
21 colors[b] = rgb(rand*256, rand*256, rand*256)
22 next b
23
24 color green
25 rect 0,0,300,300
26
27 while true
28 # erase screen
29 clg
30 # now position and draw the balls
31 for b = 0 to balls -1
32 x[b] = x[b] + dx[b]
33 y[b] = y[b] + dy[b]
34 # if off the edges turn the ball around
35 if x[b] < 0 or x[b] > 300 then
36 dx[b] = dx[b] * -1
37 end if
38 # if off the top of bottom turn the ball
around
39 if y[b] < 0 or y[b] > 300 then
40 dy[b] = dy[b] * -1
41 end if
42 # draw new ball
43 color colors[b]
44 circle x[b],y[b],r
45 next b
46 # update the display
47 refresh
48 pause .05
49 end while
Program 67: Bounce Many Balls
1 #manyballsprite.kbs
2
3 # another way to bounce many balls using sprites
4
5 fastgraphics
6 color white
7 rect 0, 0, graphwidth, graphheight
8
9 n = 20
10 spritedim n
11
12 dim dx(n)
13 dim dy(n)
14
15 for b = 0 to n-1
16 spriteload b, "greenball.png"
17 spriteplace b,graphwidth/2,graphheight/2
18 spriteshow b
19 dx[b] = rand * 5 + 2
20 dy[b] = rand * 5 + 2
21 next b
22
23 while true
24 for b = 0 to n-1
25 if spritex(b) <=0 or spritex(b) >=
graphwidth -1 then
26 dx[b] = dx[b] * -1
27 end if
28 if spritey(b) <= 0 or spritey(b) >=
graphheight -1 then
29 dy[b] = dy[b] * -1
30 end if
31 spritemove b, dx[b], dy[b]
32 next b
33 refresh
34 end while
Program 68: Bounce Many Balls Using Sprites
Arrays of Strings:
Arrays can also be used to store string values. To create a string array
use a string variable in the dim statement. All of the rules about
numeric arrays apply to a string array except the data type is different.
You can see the use of a string array in Program 69.
1 # listoffriends.kbs
2 print "make a list of my friends"
3 input "how many friends do you have?", n
4
5 dim names$(n)
6
7 for i = 0 to n-1
8 input "enter friend name ?", names$[i]
9 next i
10
11 cls
12 print "my friends"
13 for i = 0 to n-1
14 print "friend number ";
15 print i + 1;
16 print " is " + names$[i]
17 next i
Program 69: List of My Friends
Assigning Arrays:
We have seen the use of the curly brackets ({}) to play music, draw
polygons, and define stamps. The curly brackets can also be used to
assign an entire array with custom values.
1 # arrayassign.kbs
2 dim number(3)
3 dim name$(3)
4
5 number = {1, 2, 3}
6 name$ = {"Bob", "Jim", "Susan"}
7
8 for i = 0 to 2
9 print number[i] + " " + name$[i]
10 next i
Program 70: Assigning an Array With a List
1 Bob
2 Jim
3 Susan
Sample Output 70: Assigning an Array With a List
The sample (Program 71) below uses a simple linear formula to make a
fun sonic chirp.
1 # spacechirp.kbs
2
3 # even values 0,2,4... - frequency
4 # odd values 1,3,5... - duration
5
6 # chirp starts at 100hz and increases by 40 for
each of the 50 total sounds in list, duration is
always 10
7
8 dim a(100)
9 for i = 0 to 98 step 2
10 a[i] = i * 40 + 100
11 a[i+1] = 10
12 next i
13 sound a
Program 71: Space Chirp Sound
In Chapter 8 we also saw the use of lists for creating polygons and
stamps. Arrays may also be used to draw stamps and polygons. This
may help simplify your code by allowing the same stamp or polygon to
be defined once, stored in an array, and used in various places in your
program.
In an array used for stamps and polygons, the even elements (0, 2, 4,
…) contain the x value for each of the points and the odd element (1,
3, 5, …) contain the y value for the points. The array will have two
values for each point in the shape.
In Program 72 we will use the stamp from the mouse chapter to draw a
big X with a shadow. This is accomplished by stamping a gray shape
shifted in the direction of the desired shadow and then stamping the
object that is projecting the shadow.
1 # shadowstamp.kbs
2
3 dim xmark(24)
4 xmark = {-1, -2, 0, -1, 1, -2, 2, -1, 1, 0, 2, 1,
1, 2, 0, 1, -1, 2, -2, 1, -1, 0, -2, -1}
5
6 clg
7 color grey
8 stamp 160,165,50,xmark
9 color black
10 stamp 150,150,50,xmark
Program 72: Shadow Stamp
1 # mathpoly.kbs
2
3 dim shape(10)
4
5 for t = 0 to 8 step 2
6 x = 300 * rand
7 y = 300 * rand
8 shape[t] = x
9 shape[t+1] = y
10 next t
11
12 clg
13 color black
14 poly shape
Program 73: Randomly Create a Polygon
1 # grades.kbs
2 # calculate average grades for each student
3 # and whole class
4
5 nstudents = 3 # number of students
6 nscores = 4 # number of scores per student
7
8 dim students$(nstudents)
9
10 dim grades(nstudents, nscores)
11 # store the scores as columns and the students as
rows
12 # first student
13 students$[0] = "Jim"
14 grades[0,0] = 90
15 grades[0,1] = 92
16 grades[0,2] = 81
17 grades[0,3] = 55
18 # second student
19 students$[1] = "Sue"
20 grades[1,0] = 66
21 grades[1,1] = 99
22 grades[1,2] = 98
23 grades[1,3] = 88
24 # third student
25 students$[2] = "Tony"
26 grades[2,0] = 79
27 grades[2,1] = 81
28 grades[2,2] = 87
29 grades[2,3] = 73
30
31 total = 0
32 for row = 0 to nstudents-1
33 studenttotal = 0
34 for column = 0 to nscores-1
35 studenttotal = studenttotal + grades[row,
column]
36 total = total + grades[row, column]
37 next column
38 print students$[row] + "'s average is ";
39 print studenttotal / nscores
40 next row
41 print "class average is ";
42 print total / (nscores * nstudents)
43
44 end
Program 74: Grade Calculator
1 # size.kbs
2 dim number(3)
3 number = {77, 55, 33}
4 print "before"
5 gosub shownumberarray
6
7 # create a new element on the end
8 redim number(4)
9 number[3] = 22
10 print "after"
11 gosub shownumberarray
12 #
13 end
14 #
15 shownumberarray:
16 for i = 0 to number[?] - 1
17 print i + " " + number[i]
18 next i
19 return
Program 75: Get Array Size
before
0 77
1 55
2 33
after
0 77
1 55
2 33
3 22
Sample Output 75: Get Array Size
array[?]
array$[?]
array[?,]
array$[?,]
array[,?]
array$[,?]
1 # redim.kbs
2 dim number(3)
3 number = {77, 55, 33}
4 # create a new element on the end
5 redim number(4)
6 number[3] = 22
7 #
8 for i = 0 to 3
9 print i + " " + number[i]
10 next i
Program 76: Re-Dimension an Array
0 77
1 55
2 33
3 22
Sample Output 76: Re-Dimension an Array
redim variable(items)
redim variable$(items)
redim variable(rows, columns)
redim variable$(rows, columns)
1 # spacewarp.kbs
2 # The falling space debris game
3
4 balln = 5 # number of balls
5 dim ballx(balln) # arrays to hold ball position
and speed
6 dim bally(balln)
7 dim ballspeed(balln)
8 ballr = 10 # radius of balls
9
10 minx = ballr # minimum x value for balls
11 maxx = graphwidth - ballr # maximum x value
for balls
12 miny = ballr # minimum y value for balls
13 maxy = graphheight - ballr # maximum y value
for balls
14 score = 0 # initial score
15 playerw = 30 # width of player
16 playerm = 10 # size of player move
17 playerh = 10 # height of player
18 playerx = (graphwidth - playerw)/2 # initial
position of player
19 keyj = asc("J") # value for the 'j' key
20 keyk = asc("K") # value for the 'k' key
21 keyq = asc("Q") # value for the 'q' key
22 growpercent = .20 # random growth - bigger is
faster
23 speed = .15 # the lower the faster
24
25 print "spacewarp - use j and k keys to avoid the
falling space debris"
26 print "q to quit"
27
28 fastgraphics
29
30 # setup initial ball positions and speed
31 for n = 0 to balln-1
32 gosub setupball
33 next n
34
35 more = true
36 while more
37 pause speed
38 score = score + 1
39
40 # clear screen
41 color black
42 rect 0, 0, graphwidth, graphheight
43
44 # draw balls and check for collission
45 color white
46 for n = 0 to balln-1
47 bally[n] = bally[n] + ballspeed[n]
48 if bally[n] > maxy then gosub setupball
49 circle ballx[n], bally[n], ballr
50 if ((bally[n]) >= (maxy-playerh-ballr)) and
((ballx[n]+ballr) >= playerx) and ((ballx[n]-
ballr) <= (playerx+playerw)) then more = false
51 next n
52
53 # draw player
54 color red
55 rect playerx, maxy - playerh, playerw, playerh
56 refresh
57
New Operators:
Modulo Operator:
1 # mod.kbs
2 input "enter a number ", n
3 if n % 2 = 0 then print "divisible by 2"
4 if n % 3 = 0 then print "divisible by 3"
5 if n % 5 = 0 then print "divisible by 5"
6 if n % 7 = 0 then print "divisible by 7"
7 end
Program 78: The Modulo Operator
enter a number 10
divisible by 2
divisible by 5
Sample Output 78: The Modulo Operator
expression1 % expression2
You might not think it, but the modulo operator (%) is used quite often
by programmers. Two common uses are; 1) to test if one number
divides into another (Program 78) and 2) to limit a number to a specific
range (Program 79).
1 # moveballmod.kbs
2 # rewrite of moveball.kbs using the modulo
operator to wrap the ball around the screen
3
4 print "use i for up, j for left, k for right, m
for down, q to quit"
5
6 fastgraphics
7 clg
8 ballradius = 20
9
10 # position of the ball
11 # start in the center of the screen
12 x = graphwidth /2
13 y = graphheight / 2
14
15 # draw the ball initially on the screen
16 gosub drawball
17
18 # loop and wait for the user to press a key
19 while true
20 k = key
21 if k = asc("I") then
22 # y can go negative, + graphheight keeps it
positive
23 y = (y - ballradius + graphheight) %
graphheight
24 gosub drawball
25 end if
26 if k = asc("J") then
27 x = (x - ballradius + graphwidth) %
graphwidth
28 gosub drawball
29 end if
30 if k = asc("K") then
31 x = (x + ballradius) % graphwidth
32 gosub drawball
33 end if
34 if k = asc("M") then
35 y = (y + ballradius) % graphheight
36 gosub drawball
37 end if
38 if k = asc("Q") then end
39 end while
40
41 drawball:
42 color white
43 rect 0, 0, graphwidth, graphheight
44 color red
45 circle x, y, ballradius
46 refresh
47 return
Program 79: Move Ball - Use Modulo to Keep on Screen
The Integer Division (\) operator does normal division but it works only
with integers (whole numbers) and returns an integer value. As an
example, 13 divided by 4 is 3 remainder 1 – so the result of the integer
division is 3.
1 # integerdivision.kbs
2 input "dividend ", dividend
3 input "divisor ", divisor
4 print dividend + " / " + divisor + " is ";
5 print dividend \ divisor;
6 print "r";
7 print dividend % divisor;
Program 80: Check Your Long Division
dividend 43
divisor 6
43 / 6 is 7r1
Sample Output 80: Check Your Long Division
expression1 \ expression2
Power Operator:
The power operator will raise one number to the power of another
number.
1 # power.kbs
2 for t = 0 to 16
3 print "2 ^ " + t + " = ";
4 print 2 ^ t
5 next t
Program 81: The Powers of Two
2 ^ 0 = 1
2 ^ 1 = 2
2 ^ 2 = 4
2 ^ 3 = 8
2 ^ 4 = 16
2 ^ 5 = 32
2 ^ 6 = 64
2 ^ 7 = 128
2 ^ 8 = 256
2 ^ 9 = 512
2 ^ 10 = 1024
2 ^ 11 = 2048
2 ^ 12 = 4096
2 ^ 13 = 8192
2 ^ 14 = 16384
2 ^ 15 = 32768
2 ^ 16 = 65536
Sample Output 81: The Powers of Two
expression1 ^ expression2
The three new integer functions in this chapter all deal with how to
convert strings and floating point numbers to integer values. All three
functions handle the decimal part of the conversion differently.
In the int() function the decimal part is just thrown away, this has the
same effect of subtracting the decimal part from positive numbers and
adding it to negative numbers. This can cause troubles if we are trying
to round and there are numbers less than zero (0).
The ceil() and floor() functions sort of fix the problem with int(). Ceil()
always adds enough to every floating point number to bring it up to the
next whole number while floor(0) always subtracts enough to bring the
floating point number down to the closest integer.
Function Description
int(expression) Convert an expression (string,
integer, or decimal value) to an
integer (whole number). When
converting a floating point value
the decimal part is truncated
(ignored). If a string does not
contain a number a zero is
returned.
ceil(expression) Converts a floating point value to
the next highest integer value.
Function Description
floor(expression) Converts a floating point
expression to the next lowers
integer value. You should use this
function for rounding
a= floor b0.5 .
1 # intceilfloor.kbs
2 for t = 1 to 10
3 n = rand * 100 - 50
4 print n;
5 print " int=" + int(n);
6 print " ceil=" + ceil(n);
7 print " floor=" + floor(n)
8 next t
Program 82: Difference Between Int, Ceiling, and Floor
The mathematical functions that wrap up this chapter are ones you
may need to use to write some programs. In the vast majority of
programs these functions will not be needed.
Function Description
float(expression) Convert expression (string, integer,
or decimal value) to a decimal
value. Useful in changing strings
to numbers. If a string does not
contain a number a zero is
returned.
abs(expression) Converts a floating point or integer
expression to an absolute value.
log(expression) Returns the natural logarithm (base
e) of a number.
log10(expression) Returns the base 10 logarithm of a
number.
Function Description
cos(expression) Return the cosine of an angle.
sin(expression) Return the sine of an angle.
tan(expression) Return the tangent of an angle.
degrees(expression) Convert Radians (0 – 2π) to
Degrees (0-360).
radians(expression) Convert Degrees (0-360) to
Radians (0 – 2π).
acos(expression) Return the inverse cosine.
asin(expression) Return the inverse sine.
atan(expression) Return the inverse tangent.
The discussion of the first three functions will refer to the sides of a
right triangle. Illustration 20 shows one of these with it's sides and
angles labeled.
Cosine:
A cosine is the ratio of the length of the adjacent leg over the length of
b
the hypotenuse cos A= . The cosine repeats itself every 2π radians
c
and has a range from -1 to 1. Illustration 20 graphs a cosine wave
from 0 to 2π radians.
Sine:
The sine is the ratio of the adjacent side over the hypotenuse
a
sin A= . The sine repeats itself every 2π radians and has a range
c
from -1 to 1. You have seen diagrams of sine waves in Chapter 3 as
music was discussed.
Tangent:
The tangent is the ratio of the adjacent side over the opposite side
a
tan A= . The sine repeats itself every π radians and has a range
b
from -∞ to ∞. The tangent has this range because when the angle gets
very small the length of the opposite side becomes very small.
Degrees Function:
Radians Function:
angles.
Inverse Cosine:
Inverse Sine:
Inverse Tangent:
The big program this chapter allows the user to enter two
positive whole numbers and then performs long division.
This program used logarithms to calculate how long the
numbers are, modulo and integer division to get the
individual digits, and is generally a very complex program.
Don't be scared or put off if you don't understand exactly
how it works, yet.
1 # longdivision.kbs
2 # show graphically the long division of two
positive integers
3
4 input "dividend? ", b
5 input "divisor? ", a
6
7 originx = 100
8 originy = 20
9 height = 12
10 width = 9
11 margin = 2
12
13 b = int(abs(b))
14 a = int(abs(a))
15
16 clg
17
18 # display original problem
19 row = 0
20 col = -1
21 number = a
22 underline = false
23 gosub drawrightnumber
24 row = 0
25 col = 0
26 number = b
27 gosub drawleftnumber
28 line originx - margin, originy, originx + (width
* 11), originy
29 line originx - margin, originy, originx - margin,
originy + height
30
31 # calculate how many digits are in the dividend
32 lb = ceil(log10(abs(b)))
33
34 r = 0
35 bottomrow = 0 ## row for bottom calculation
display
36
37 # loop through all of the digits from the left to
the right
38 for tb = lb-1 to 0 step -1
39 # drop down the next digit to running
remainder and remove from dividend
40 r = r * 10
41 r = r + (b \ (10 ^ tb))
42 b = b % (10 ^ tb)
43 # display running remainder
44 row = bottomrow
45 bottomrow = bottomrow + 1
46 col = lb - tb - 1
47 number = r
48 underline = false
49 gosub drawrightnumber
50 # calculate new digit in answer and display
51 digit = r \ a
52 row = -1
53 col = lb - tb - 1
54 gosub drawdigit
55 # calculate quantity to remove from running
and display
56 number = digit * a
57 r = r - number
58 col = lb - tb - 1
59 row = bottomrow
60 bottomrow = bottomrow + 1
61 underline = true
62 gosub drawrightnumber
63 next tb
64 #
65 # print remainder at bottom
66 row = bottomrow
67 col = lb - 1
68 number = r
69 underline = false
70 gosub drawrightnumber
71 end
72
73 drawdigit:
74 # pass row and col convert to x y
75 text col * width + originx, row * height +
originy, digit
76 if underline then
77 line col * width + originx - margin, (row + 1)
* height + originy, (col + 1) * width + originx -
margin, (row + 1) * height + originy
78 end if
79 return
80
81 drawleftnumber:
82 # pass start row, col, and number - from left
column
83 if number < 10 then
84 digit = number
85 gosub drawdigit
86 else
87 lnumber = ceil(log10(abs(number)))
88 for tnumber = lnumber-1 to 0 step -1
89 digit = (number \ (10 ^ tnumber)) % 10
90 gosub drawdigit
91 col = col + 1
92 next tnumber
93 endif
94 return
95
96 drawrightnumber:
97 # pass start row, col, and number - from right
column
98 if number < 10 then
99 digit = number
100 gosub drawdigit
101 else
102 lnumber = ceil(log10(abs(number)))
103 for tnumber = 0 to lnumber - 1
104 digit = (number \ (10 ^ tnumber)) % 10
105 gosub drawdigit
106 col = col - 1
107 next tnumber
108 endif
109 return
Program 83: Big Program - Long Division
dividend? 123456
divisor? 78
Sample Output 83: Big Program - Long Division (one)
Sample Output
83: Big Program
- Long Division
This chapter shows several new functions that will allow you to
manipulate string values.
Function Description
string(expression) Convert expression (string, integer,
or decimal value) to a string value.
length(string) Returns the length of a string.
left(string, length) Returns a string of length characters
starting from the left.
right(string, length) Returns a string of length characters
starting from the right.
mid(string, start, length) Returns a string of length characters
starting from the middle of a string.
upper(expression) Returns an upper case string.
lower(expression) Returns a lower case string.
instr(haystack, needle) Searches the string “haystack” for
the “needle” and returns it's location.
String() Function:
The string() function will take an expression of any format and will
return a string. This function is a convenient way to convert an integer
or floating point number into characters so that it may be manipulated
as a string.
1 # string.kbs
2 a$ = string(10 + 13)
3 print a$
4 b$ = string(2 * pi)
5 print b$
Program 84: The String Function
23
6.283185
Sample Output 84: The String Function
string(expression)
Length() Function:
The length() function will take a string expression and return it's length
in characters (or letters).
1 # length.kbs
2 # prints 6, 0, and 17
3 print length("Hello.")
4 print length("")
5 print length("Programming Rulz!")
Program 85: The Length Function
6
0
17
Sample Output 85: The Length Function
length(expression)
The left(), right(), and mid() functions will extract sub-strings (or
parts of a string) from a larger string.
1 # leftrightmid.kbs
2 a$ = "abcdefghijklm"
3 # prints "abcd"
4 print left(a$,4)
5 # prints "lm"
6 print right(a$,2)
7 # prints "def" and "jklm"
8 print mid(a$,4,3)
9 print mid(a$,10,9)
Program 86: The Left, Right, and Mid Functions
abcd
kl
def
jklm
Sample Output 86: The Left, Right, and Mid Functions
left(string, length)
right(string, length)
The upper() and lower() functions simply will return a string of upper
case or lower case letters. These functions are especially helpful when
you are trying to perform a comparison of two strings and you do not
care what case they actually are.
1 # upperlower.kbs
2 a$ = "Hello."
3 # prints "hello."
4 print lower(a$)
5 # prints "HELLO."
6 print upper(a$)
Program 87: The Upper and Lower Functions
hello.
HELLO.
Sample Output 87: The Upper and Lower Functions
lower(string)
upper(string)
Instr() Function:
1 # instr.kbs
2 a$ = "abcdefghijklm"
3 # find location of "hi"
4 print instr(a$,"hi")
5 # find location of "bye"
6 print instr(a$,"bye")
Program 88: The Instr Function
8
0
Sample Output 88: The Instr Function
instr(haystack, needle)
1 # radix.kbs
2 # convert a number from one base (2-36) to
another
3
4 digits$ = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
5
6 message$ = "from base"
7 gosub getbase
8 frombase = base
9
10 input "number in base " + frombase + " >",
number$
11 number$ = upper(number$)
12
13 # convert number to base 10 and store in n
14 n = 0
15 for i = 1 to length(number$)
16 n = n * frombase
17 n = n + instr(digits$, mid(number$, i, 1)) - 1
18 next i
19
20 message$ = "to base"
21 gosub getbase
22 tobase = base
23
24 # now build string in tobase
25 result$ = ""
26 while n <> 0
27 result$ = mid(digits$, n % tobase + 1, 1) +
result$
28 n = n \ tobase
29 end while
30
31 print "in base " + tobase + " that number is " +
result$
32 end
33
34 getbase: # get a base from 2 to 36
35 do
36 input message$+"> ", base
37 until base >= 2 and base <= 36
38 return
Program 89: Big Program - Radix Conversion
from base> 10
number in base 10 >999
to base> 16
in base 16 that number is 3E7
Sample Output 89: Big Program - Radix Conversion
This chapter will show you how to read values from a file and then
write them for long term storage.
Our first program using files is going to show you many of the
statements and constants you will need to use to manipulate file data.
There are several new statements and functions in this program.
1 #readlfile.kbs
2 input "file name>", fn$
3 if not exists(fn$) then
4 print fn$ + " does not exist."
5 end
6 end if
7 #
8 n = 0
9 open fn$
10 while not eof
11 l$ = readline
12 n = n + 1
file name>test.txt
1 These are the times that
2 try men's souls.
3 - Thomas Paine
the file test.txt is 58 bytes long.
Sample Output 90: Read Lines From a File
exist(expression)
open expression
open (expression)
open filenumber, expression
open (filenumber, expression)
eof
eof()
eof(filenumber)
readline
readline()
readline(filenumber)
size
size()
size(filenumber)
close
close()
close filenumber
close(filenumber)
In Program 90 we saw how to read lines from a file. The next two
programs show different variations of how to write information to a file.
In Program 91 we open and clear any data that may have been in the
file to add our new lines and in Program 92 we append our new lines to
the end (saving the previous data).
1 # resetwrite.kbs
2 open "resetwrite.dat"
3
4 print "enter a blank line to close file"
5
6 # clear file (reset) and start over
7 reset
8 repeat:
9 input ">", l$
10 if l$ <> "" then
11 writeline l$
12 goto repeat
13 end if
14
15 # go the the start and display contents
16 seek 0
17 k = 0
18 while not eof()
19 k = k + 1
20 print k + " " + readline()
21 end while
22
23 close
24 end
Program 91: Clear File and Write Lines
reset or
reset() or
reset filenumber
reset(filenumber)
Clear any data in an open file and move the file pointer to
the beginning.
seek expression
seek(expression)
seek filenumber,expression
seek (filenumber,expression)
Move the file pointer for the next read or write operation to a
specific location in the file. To move the current pointer to
the beginning of the file use the value zero (0). To seek to
the end of a file use the size() function as the argument to
the see statement.
writeline expression
writeline(expression)
writeline filenumber,expression
writeline (filenumber,expression)
1 # appendwrite.kbs
2 open "appendwrite.dat"
3
4 print "enter a blank line to close file"
5
6 # move file pointer to end of file and append
7 seek size()
8 repeat:
9 input ">", l$
10 if l$ <> "" then
11 writeline l$
12 goto repeat
13 end if
14
15 # move file pointer to beginning and show
contents
16 seek 0
17 k = 0
18 while not eof()
19 k = k + 1
20 print k + " " + readline()
21 end while
22
23 close
24 end
Program 92: Append Lines to a File
read
read()
read(filenumber)
write expression
write (expression)
write filenumber,expression
write (filenumber,expression)
1 # phonelist.kbs
2 # add a phone number to the list and show
3 filename$ = "phonelist.txt"
4
Stack:
A stack is one of the common data structures used by programmers to
do many tasks. A stack works like the “discard pile” when you play the
card game “crazy-eights”. When you add a piece of data to a stack it
is done on the top (called a “push”) and these items stack upon each
other. When you want a piece of information you take the top one off
the stack and reveal the next one down (called a “pop”). Illustration
27 shows a graphical example.
Push Pop
(Add One) (Take One)
Item
Item
Item
Item
Item
1 # stack.kbs
2 # implementing a stack using an array
3
4 dim stack(1) # array to hold stack with initial
size
5 nstack = 0 # number of elements on stack
6
7 value = 1
8 gosub pushstack
9 value = 2
10 gosub pushstack
11 value = 3
12 gosub pushstack
13 value = 4
14 gosub pushstack
15 value = 5
16 gosub pushstack
17
18 while nstack > 0
19 gosub popstack
20 print value
21 end while
22
23 end
24
25 popstack: #
26 # get the top number from stack and set it in
value
27 if nstack = 0 then
28 print "stack empty"
29 else
30 nstack = nstack - 1
31 value = stack[nstack]
32 end if
33 return
34
35 pushstack: #
36 # push the number in the variable value onto the
stack
37 # nake the stack larger if it is full
38 if nstack = stack[?] then redim stack(stack[?] +
5)
39 stack[nstack] = value
40 nstack = nstack + 1
41 return
Program 94: Stack
Queue:
The queue (pronounced like the letter Q) is another very common data
structure. The queue, in its simplest form, is like the lunch line at
school. The first one in the line is the first one to get to eat.
Illustration 28 shows a block diagram of a queue.
Enqueue
(Add One)
Item
Item
Dequeue
(Take One)
1 # queue.kbs
2 # implementing a queue using an array
3
4 queuesize = 4 # maximum number of entries in
the queue at any one time
5 dim queue(queuesize) # array to hold queue with
initial size
6 tail = 0 # location in queue of next new entry
7 head = 0 # location in queue of next entry to
be returnrd (served)
8 inqueue = 0 # number of entries in queue
9
10 value = 1
11 gosub enqueue
12 value = 2
13 gosub enqueue
14
15 gosub dequeue
16 print value
17
18 value = 3
19 gosub enqueue
20 value = 4
21 gosub enqueue
22
23 gosub dequeue
24 print value
25 gosub dequeue
26 print value
27
28 value = 5
29 gosub enqueue
30 value = 6
31 gosub enqueue
32 value = 7
33 gosub enqueue
34
35 # empty everybody from the queue
36 while inqueue > 0
37 gosub dequeue
38 print value
39 end while
40
41 end
42
43 dequeue: #
44 if inqueue = 0 then
45 print "queue is empty"
46 else
47 inqueue = inqueue - 1
48 value = queue[head]
49 print "dequeue value=" + value + " from=" +
head + " inqueue=" + inqueue
50 # move head pointer - if we are at end of
array go back to the begining
51 head = head + 1
52 if head = queuesize then head = 0
53 end if
54 return
55
56 enqueue: #
57 if inqueue = queuesize then
58 print "queue is full"
59 else
60 inqueue = inqueue + 1
61 queue[tail] = value
62 print "enqueue value=" + value + " to=" +
tail + " inqueue=" + inqueue
63 # move tail pointer - if we are at end of
array go back to the begining
64 tail = tail + 1
65 if tail = queuesize then tail = 0
66 end if
67 return
Program 95: Queue
Linked List:
In most books the discussion of this material starts with the linked list.
Because BASIC-256 handles memory differently than many other
languages this discussion was saved after introducing stacks and
queues.
Pointer
Data
Head
Data
X Data
Tail
to the
Head
Illustration 30: Deleting an Item from a Linked List
1 # linkedlist.kbs
2
3 n = 8 # maximum size of list
4 dim data$(n) # data for item in list
5 dim nextitem(n) # pointer to next item in list
6 dim freeitem(n) # list of free items
7
8 # initialize freeitem stack
9 for t = 0 to n-1
10 freeitem[t] = t
11 next t
12 lastfree = n-1
13
14 head = -1 # start of list - -1 = pointer to
nowhere
15
16 # list of 3 items
17 text$ = "Head"
18 gosub append
19 text$ = "more"
20 gosub append
21 text$ = "stuff"
22 gosub append
23 gosub displaylist
24 gosub displayarrays
25 gosub wait
26
27 print "delete item 2"
28 r = 2
29 gosub delete
30 gosub displaylist
31 gosub displayarrays
32 gosub wait
33
34 print "insert item 1"
35 r = 1
36 text$ = "bar"
37 gosub insert
37 gosub displaylist
39 gosub displayarrays
40 gosub wait
41
42 print "insert item 2"
43 r = 2
44 text$ = "foo"
45 gosub insert
46 gosub displaylist
47 gosub displayarrays
48 gosub wait
49
50 print "delete item 1"
51 r = 1
52 gosub delete
53 gosub displaylist
54 gosub displayarrays
55 gosub wait
56
57 end
58
59 wait: ## wait for enter
60 input "press enter? ", garbage$
61 print
62 return
63
92 else
93 k = 2
94 i = head
95 while i <> -1 and k <> r
96 k = k + 1
97 i = nextitem[i]
98 end while
99 if i <> -1 then
100 gosub createitem
101 nextitem[index] = nextitem[i]
102 nextitem[i] = index
103 else
104 print "can't insert beyond end of list"
105 end if
106 end if
107 return
108
109 delete: # delete element r from linked list
110 if r = 1 then
111 index = head
112 head = nextitem[index]
113 gosub freeitem
114 else
115 k = 2
116 i = head
117 while i <> -1 and k <> r
118 k = k + 1
119 i = nextitem[i]
120 end while
121 if i <> -1 then
122 index = nextitem[i]
153 end
154 end if
155 index = freeitem[lastfree]
156 data$[index] = text$
157 nextitem[index] = -1
158 lastfree = lastfree - 1
159 return
The only real positive thing that can be said about this algorithm is
that it is simple to explain and to implement. Illustration 32 shows a
flow-chart of the algorithm. The bubble sort goes through the array
over and over again swapping the order of adjacent items until the sort
is complete,
Start
yes
no is array
sorted?
no is the next element yes
less than the current?
d[i+1] >d[i]
Finish
swap elements
t =d[i]
d[i] =d[i+1]
d[i+1] =t
1 # bubblesort.kbs
2 # implementing a simple sort
3
4 # a bubble sort is one of the SLOWEST algorithms
5 # for sorting but it is the easiest to implement
6 # and understand.
7 #
8 # The algorithm for a bubble sort is
44 sorted = false
45 temp = d[i+1]
46 d[i+1] = d[i]
47 d[i] = temp
48 end if
49 next i
50 until sorted
51 return
Program 97: Bubble Sort
The insertion sort gets it's name from how it works. The sort goes
through the elements of the array (index = 1 to length -1) and inserts
the value in the correct location in the previous array elements.
Illustration 33 shows a step-by-step example.
Original Array
2 7 1 3 5 4 6
unsorted b 5
unsorted c 4
b a unsorted b 6
a
1 2 7 5 4 6
1 2 3 4 5 6 7
1 # insertionsort.kbs
2 # implementing an efficient sort
3
4 dim d(20)
5
6 # fill array with unsorted numbers
7 for i = 0 to d[?]-1
8 d[i] = rand * 1000
9 next i
10
11 print "*** Un-Sorted ***"
12 gosub displayarray
13
14 gosub insertionsort
15
16 print "*** Sorted ***"
17 gosub displayarray
18 end
19
20 displayarray:
21 # print out the array's values
22 for i = 0 to d[?]-1
23 print d[i] + " ";
24 next i
25 print
26 return
27
28 insertionsort:
29 # loops thru the list starting at the second
element.
30 # takes current element and inserts it
31 # in the the correct sorted place in the
previously
32 # sorted elements
33
34 # moving from backward from the current location
35 # and sliding elements with a larger value
foward
36 # to make room for the current value in the
correct
37 # place (in the partially sorted array)
38
39 for i = 1 to d[?] - 1
40 currentvalue = d[i]
41 j = i - 1
42 done = false
43 do
44 if d[j] > currentvalue then
45 # shift value and stop looping if we
are at begining
46 d[j+1] = d[j]
47 j = j - 1
48 if j < 0 then done = true
49 else
50 # j is the element before where we want
to insert
51 done = true
52 endif
53 until done
54 d[j+1] = currentvalue
55 next i
56 return
Program 98: Insertion Sort
As you have worked through the examples and created your own
programs you have seen errors that happen while the program is
running. These errors are called “runtime errors”. BASIC-256 includes
a group of special commands that allow your program to recover from
or handle these errors.
Trapping errors, when you do not mean too, can cause problems. Error
trapping should only be used when needed and disabled when not.
Error Trap:
When error trapping is turned on, with the onerror statement, the
program will jump to a specified subroutine when an error occurs. If
we look at Program 99 we will see that the program calls the
subroutine when it tries to read the value of z (an undefined variable).
If we try to run the same program with line one commented out or
removed the program will terminate when the error happens.
1 onerror errortrap
2
3 print "z = " + z
4 print "Still running after error"
5 end
6
7 errortrap:
8 print "I trapped an error."
9 return
Program 99: Simple Runtime Error Trap
I trapped an error.
z = 0
Still running after error
Sample Output 99: Simple Runtime Error Trap
onerror label
1 onerror errortrap
2
3 print "z = " + z
4 print "Still running after error"
5 end
6
7 errortrap:
8 print "Error Trap - Activated"
lasterror or lasterror()
lasterrorline or lasterrorline()
lasterrormessage or lasterrormessage()
lasterrorextra or lasterrorextra()
The offerror statement turns error trapping off. This causes all errors
encountered to stop the program.
1 onerror errortrap
2 print "z = " + z
3 print "Still running after first error"
4
5 offerror
6 print "z = " + z
7 print "Still running after second error"
8
9 end
10
11 errortrap:
12 print "Error Trap - Activated"
13 return
Program 101: Turning Off the Trap
What is a Database:
A database is simply an organized collection of numbers, string, and
other types of information. The most common type of database is the
“Relational Database”. Relational Databases are made up of four
major parts: tables, rows, columns, and relationships (see Table 8).
The SQLite library does not require the installation of a database sever
or the setting up of a complex system. The database and all of its
parts are stored in a simple file on your computer. This file can even
be copied to another computer and used, without problem.
owner
ow ner_id integer
ow nernam e text
phonenum ber text
pet
pet_id integer
ow ner_id integer
petnam e text
type text
Illustration 34: Entity Relationship Diagram of
Chapter Database
So far you have seen three new database statements: dbopen – will
open a database file and create it if it does not exist, dbexecute – will
execute an SQL statement on the open database, and dbclose –
closes the open database file.
dbopen filename
dbexecute sqlstatement
dbclose
These same three statements can also be used to execute other SQL
statements. The INSERT INTO statement (Program 103) adds new
rows of data to the tables and the UPDATE statement (Program 104)
will change an existing row's information.
56
57 adderror:
58 print "ERROR: " + lasterror + " " +
lasterrormessage + " " + lasterrorextra
59 return
Program 103: Insert Rows into Database
So far we have seen how to open, close, and execute a SQL statement
that does not return any values. A database would be pretty useless if
we could not get information out of it.
2 dbopen "pets.sqlite3"
3
4 # show owners and their phone numbers
5 print "Owners and Phone Numbers"
6 dbopenset "SELECT ownername, phonenumber FROM
owner ORDER BY ownername;"
7 while dbrow()
8 print dbstring(0) + " " + dbstring(1)
9 end while
10 dbcloseset
11
12 print
13
14 # show owners and their pets
15 print "Owners with Pets"
16 dbopenset "SELECT owner.ownername, pet.pet_id,
pet.petname, pet.type FROM owner JOIN pet ON
pet.owner_id = owner.owner_id ORDER BY
ownername, petname;"
17 while dbrow()
18 print dbstring(0) + " " + dbint(1) + " " +
dbstring(2) + " " + dbstring(3)
19 end while
20 dbcloseset
21
22 print
23
24 # show average number of pets
25 print "Average Number of Pets"
26 dbopenset "SELECT AVG(c) FROM (SELECT COUNT(*)
AS c FROM owner JOIN pet ON pet.owner_id =
owner.owner_id GROUP BY owner.owner_id) AS
numpets;"
27 while dbrow()
28 print dbfloat(0)
29 end while
30 dbcloseset
31
32 # wrap everything up
33 dbclose
Program 105: Selecting Sets of Data from a Database
dbopenset sqlstatement
dbrow or dbrow ()
dbint ( column )
dbfloat ( column )
dbstring ( column )
These functions will return data from the current row of the
record set. You must know the zero based numeric column
number of the desired data.
dbcloseset
Socket Connection:
1.
2.
Server Client
3.
Just like with a telephone call, the person making the call (client) needs
to know the phone number of the person they are calling (server). We
call that number an IP address. BASIC-256 uses IP version 4 addresses
that are usually expressed as four numbers separated by periods
(999.999.999.999).
In addition to having the IP address for the server, the client and server
must also talk to each-other over a port. You can think of the port as a
telephone extension in a large company. A person is assigned an
extension (port) to answer (server) and if you want to talk to that
person you (client) call that extension.
The port number may be between 0 and 65535 but various Internet
and other applications have been reserved ports in the range of 0-
1023. It is recommended that you avoid using these ports.
1 # simple_server.kbs
2 print "listening to port 9999 on " +
netaddress()
3 NetListen 9999
4 NetWrite "The simple server sent this message."
5 NetClose
Program 106: Simple Network Server
1 # simple _client.kbs
2 input "What is the address of the
simple_server?", addr$
3 if addr$ = "" then addr$ = "127.0.0.1"
4 #
5 NetConnect addr$, 9999
6 print NetRead
7 NetClose
Program 107: Simple Network Client
netaddress
netaddress ( )
netlisten portnumber
netlisten ( portnumbrer )
netlisten socketnumber, portnumber
netlisten ( socketnumber, portnumber )
netclose
netclose ( )
netclose socketnumber
netclose ( socketnumber )
netwrite string
netwrite ( string )
netwrite socketnumber, string
netwrite ( socketnumber, string )
netread
netread ( )
netread ( socketnumber )
Network Chat:
The network chat program (Program 108) combines the client and
server program into one. If you start the application and it is unable to
connect to a server the error is trapped and the program then
1 # chat.kbs
2 # uses port 9999 for server
3
4 input "Chat to address (return for server or
local host)?", addr$
5 if addr$ = "" then addr$ = "127.0.0.1"
6 #
7 # try to connect to server - if there is not one
become one
8 OnError startserver
9 NetConnect addr$, 9999
10 OffError
11 print "connected to server"
12
13 chatloop:
14 while true
15 # get key pressed and send it
16 k = key
17 if k <> 0 then
18 gosub show
19 netwrite string(k)
20 end if
21 # get key from network and show it
22 if NetData() then
23 k = int(NetRead())
24 gosub show
25 end if
26 pause .01
27 end while
28 end
29
30 show:
31 if k=16777220 then
32 print
33 else
34 print chr(k);
35 end if
36 return
37
38 startserver:
39 OffError
40 print "starting server - waiting for chat
client"
41 NetListen 9999
42 print "client connected"
43 goto chatloop
44 return
Program 108: Network Chat
The following is observed when the user on the client types the
message “HI SERVER” and then the user on the server types “HI
CLIENT”.
netdata or netdata()
1 # battle.kbs
2 # uses port 9998 for server
3
4 kspace = 32
5 kleft = 16777234
6 kright = 16777236
7 kup = 16777235
8 kdown = 16777237
9 dr = pi / 16 # direction change
10 dxy = 2.5 # move speed
11 scale = 20 # tank size
12 shotscale = 4 # shot size
13 shotdxy = 5 # shot move speed
14 port = 9998 # port to communicate on
15
16 dim tank(30)
17 tank = {-1,-.66, -.66,-.66, -.66,-.33, -.33,
-.33, 0,-1, .33,-.33, .66,-.33, .66,-.66,
1,-.66, 1,1, .66,1, .66,.66, -.66,.66, -.66,1,
-1,1}
18 dim shot(14)
19 shot = {0,-1, .5,-.5, .25,0, .5,.75, -.25,.75,
-.25,0, -.5,-.5}
20
21 print "Tank Battle - You are the white tank."
22 print "Your mission is to shoot and kill the"
23 print "black one. Use arrows to move and"
24 print "space to shoot."
25 print
26 input "Address (return for server or local
host)?", addr$
27 if addr$ = "" then addr$ = "127.0.0.1"
28
29 # try to connect to server - if there is not one
become one
30 OnError startserver
31 NetConnect addr$, port
32 OffError
33 print "connected to server"
34
35 playgame:
36
37 myx = 100
38 myy = 100
39 myr = 0
40 mypx = 0 # projectile position direction and
remaining length (no shot when mypl=0)
41 mypy = 0
42 mypr = 0
43 mypl = 0
44 yourx = 200
45 youry = 200
46 yourr = pi
47 yourpx = 0 # projectile position direction
and remaining length
48 yourpy = 0
49 yourpr = 0
50 yourpl = 0
51 gosub writeposition
52
53 fastgraphics
54 while true
55 # get key pressed and move tank on the screen
56 k = key
57 if k <> 0 then
58 if k = kup then
59 myx = myx + sin(myr) * dxy
60 myy = myy - cos(myr) * dxy
61 end if
62 if k = kdown then
63 myx = myx - sin(myr) * dxy
64 myy = myy + cos(myr) * dxy
65 end if
66 if k = kspace then
67 mypr = myr
68 mypx = myx + sin(mypr) * scale
69 mypy = myy - cos(mypr) * scale
70 mypl = 100
71 end if
72 if myx < scale then myx = graphwidth -
scale
73 if myx > graphwidth-scale then myx = scale
74 if myy < scale then myy = graphheight -
scale
75 if myy > graphheight-scale then myy =
scale
76 if k = kleft then myr = myr - dr
77 if k = kright then myr = myr + dr
78 gosub writeposition
79 end if
80 # move my projectile (if there is one)
81 if mypl > 0 then
82 mypx = mypx + sin(mypr) * shotdxy
83 mypy = mypy - cos(mypr) * shotdxy
84 if mypx < shotscale then mypx = graphwidth
- shotscale
85 if mypx > graphwidth-shotscale then mypx =
shotscale
86 if mypy < shotscale then mypy =
graphheight - shotscale
87 if mypy > graphheight-shotscale then mypy
= shotscale
88 if (mypx-yourx)^2 + (mypy-youry)^2 <
scale^2 then
89 NetWrite "!"
90 print "You killed your opponent. Game
over."
91 end
92 end if
93 mypl = mypl - 1
94 gosub writeposition
95 end if
96 # get position from network
97 gosub getposition
98 #
99 gosub draw
100 #
101 pause .1
102 end while
103
104 writeposition: ###
105 # 10 char for x, 10 char for y, 10 char for r
(rotation)
106 position$ = left(myx + "
",10)+left(myy + " ",10)+left(myr + "
1 – Download:
The download process may ask you what you want to do with the file.
Click the “Save File” button (Illustration 37).
2 – Installing:
Once the file has finished downloading (Illustration 38) use your mouse
and click on the file from the download list. You will then see one or
two dialogs asking if you really want to execute this file (Illustration 39)
(Illustration 40). You need to click the “OK” or “Run” buttons on these
dialogs.
After the security warnings are cleared you will see the actual BASIC-
256 Installer application. Click the “Next>” button on the first screen
(Illustration 41).
Read and agree to the GNU GPL software license and click on “I Agree”
(Illustration 42). The GNU GPL license is one of the most commonly
used “Open Source” and”Free” license to software. You have the right
to use, give away, and modify the programs released under the GPL.
This license only relates to the BASIC-256 software and not the
contents of this book.
The next Installer screen asks you what you want to install (Illustration
43). If you are installing BASIC-256 to a USB or other type of
removable drive then it is suggested that you un-check the “Start
Menu Shortcuts”. For most users who are installing to a hard drive,
should do a complete install. Click “Next>”.
Illustration 44 shows the last screen before the install begins. This
screen asks you what folder to install the BASIC-256 executable files
into. If you are installing to your hard drive then you should accept the
default path.
The installation is complete when you see this screen (Illustration 45).
Click “Close”.
3 – Starting BASIC-256
You will then see a menu for BASIC-256. You may open the program
by clicking on it, uninstall it, or view the documentation from this menu
(Illustration 47).
The circle command draws a filled circle on the graphics output area.
The center of the circle is defined by the x and y parameters and the
size is defined as radius.
Example:
clg
color 255,128,128
circle 150,150,150
color red
circle 150,150,100
This command clears the graphics output area. The graphics output
area is not cleared automatically when an program is run. This will
sometimes leave undesired graphics visible. If you are using graphics
it is advised that you always clear the output window, first.
When the mouse is being read in click mode the x position, y position,
and button click information are stored when the mouse button is
clicked. These values can be retrieved with the clickx(), clicky(), and
clickb() functions. The stored values can be reset to zero (0) using
clickclear.
Closes open file. This will flush any pending disk output. If file number
parameter is not specified then file number zero (0) will be used.
This command clears the Text Output window. The Text Output
window is automatically cleared when a program is run.
Sets the foreground color for all graphical commands. The color may
be specified by the color name (see Appendix E), an integer
representing the RGB value, or by three numbers representing the RGB
value as separate component colors.
Example:
clg
color black
rect 100,100,100,100
color 255,128,128
circle 150,150,75
dbclose (19)
dbclose
dbcloseset (19)
dbcloseset
dbexecute (19)
dbexecute statement
dbexecute ( statement )
dbopen (19)
dbopen filename
dbopen ( filename )
Open an SQLite database file. If the file does not exist then create it.
dbopenset (19)
dbopenset statement
dbopenset ( statement )
Perform an SQL statement and create a record set so that the program
may loop through and use the results.
decimal ()
decimal n
decimal ( n )
Description...
Repeat the statements in the block over and over again. Stop
repeating when the condition is true. The statements will be executed
one or more times.
The font command sets the font that will be used by the next text
command. You must specify the name of the font or font family, the
point size, and the weight.
Example:
clg
color black
n = 5
dim fonts$(n)
fonts$ = {"Helvetica", "Times", "Courier",
"System", "Symbol"}
for t = 0 to n-1
font fonts$[t], 32, 50
text 10, t*50, fonts$[t]
next t
return
Set the graphics output area to the specified height and width.
The if, else, and end if statements allow you to define two blocks of
programming code. The first block, after the then clause, executes if
the condition is true and the second block, after the else clause, will
execute when the condition is false.
Read in the picture found in the file and display it on the graphics
output area. The values of x and y represent the location to place the
CENTER of the image.
The input statement will retrieve a string or a number that the user
types into the text output area of the screen. The result will be stored
in a variable that may be used later in the program.
A prompt message, if specified, will display on the text output area and
the cursor will directly follow the prompt.
Draw a line one pixel wide from the starting point to the ending point,
using the current color.
netclose (20)
netclose
netclose ( )
netclose socket
netclose ( socket )
netconnect (20)
netconnect server, port
netconnect ( server, port )
netconnect socket, server, port
netconnect ( socket, server, port )
netlisten (20)
netlisten port
netlisten ( port )
netlisten socket, port
netlisten ( socket, port )
netwrite (20)
netwrite string
netwrite ( string )
netwrite socket, string
netwrite ( socket, string )
offerror (18)
offerror
Turns off error trapping and restores the default error behavior.
onerror (18)
onerror label
Open the file specified for reading and writing. If the file does not exist
BASIC-256 may have up to eight (8) files opened at any one time. The
files will be numbered from zero(0) to seven(7). If a file number is not
specified then file number zero (0) will be used.
The print statement is used to display text and numbers on the text
output area of the BASIC-256 window. Print normally goes down to the
next line but you may output several things on the same line by using
a ; (semicolon) at the end of the expression.
This statement will draw the captured slice (see the getslice function)
back onto the graphics output area. If an RGB color is specified
then the slice will be drawn with pixels of that color being omitted
(transparent).
Example:
clg
color darkblue
rect 75,75,100,100
color blue
rect 100,100,100,100
# comment text
Clear any data from an open file and move the file pointer to the
beginning.
If file number is not specified then file number zero (0) will be used.
Move the file pointer for the next read or write operation to a specific
location in the file. To move the current pointer to the beginning of the
file use the value zero (0). To seek to the end of a file use the size()
function as the argument to the seek statement.
If file number parameter is not specified then file number zero (0) will
be used.
Sprites are numbered from zero (0) to one less than the number
specified in this command (numberofsprites -1).
This statement will cause the specified sprite to not be drawn on the
screen. It will still exist and may be shown using the spriteshow
statement.
This statement reads an image file (GIF, BMP, PNG, JPG, or JPEG) from
the specified path and creates a sprite. The sprite muse be allocated
using the spritedim statement before you may load it.
By default the sprite will be placed with its center at 0,0 and it will be
hidden. You should move the sprite to the desired position on the
screen (spritemove or spriteplace) and then show it (spriteshow).
Move the specified sprite x pixels to the right and y pixels down.
Negative numbers can also be specified to move the sprite left and up.
A sprite's center will not move beyond the edge of the current graphics
output window.
You may use the spritex and spritey functions to determine the
current location of the sprite.
You can move a hidden sprite but it will not be displayed until you
show the sprite using the showsprite statement.
This statement will allow you to create a sprite by copying it from the
graphics output area. The arguments x, y, width, and height specify a
rectangular area to capture and use for the sprite. Pixels that have not
been drawn since the last cls statement or that were drawn using the
color clear will be transparent when the sprite is drawn.
By default the sprite will be placed with its center at 0,0 and it will be
hidden. You should move the sprite to the desired position on the
screen (spritemove or spriteplace) and then show it (spriteshow).
The first form of the sound statement takes two arguments; (1) the
frequency of the sound in Hz (cycles per second) and (2) the length of
the tone in milliseconds (ms). The second uses curly braces and can
specify several tones and durations in a list. The third form uses an
array containing frequencies and durations.
Draw a polygon with it's origin (0,0) at the screen position (x,y).
Optionally scale (re-size) it by the decimal scale where 1 is full size.
Also you may also rotate the stamp clockwise around it's origin by
specifying how far to rotate as an angle expressed in radians (0 to 2π).
The text command will draw characters on the graphics output area.
The x and y arguments represent the top left corner and will draw the
Example:
clg
font “Helvetica”, 32, 50
color red
text 100, 100, “Hi Mom.”
Load .wav (wave) audio file data from the file name and play. The
playback will be synchronous and the next statement in the program
will begin immediately as soon as the audio begins playing.
If there is a currently playing audio file (see wavplay) then stop the
synchronous playback.
If there is a currently playing audio file (see wavplay) then wait for it
to finish playing.
Do the statements in the block over and over again while the condition
is true. The statements will be executed zero or more times.
Write the string expression to an open file. Do not add an end of line or
a delimiter.
If file number parameter is not specified then file number zero (0) will
be used.
Output the contents of the expression to an open file and then append
an end of line mark to the data. The file pointer will be positioned at
the end of the write so that the next write statement will directly
follow.
If file number parameter is not specified then file number zero (0) will
be used.
Functions perform calculations, get system values, and return them to the
program.
Each function will return a value of a specific type (integer, Boolean, floating
point, or string) and potentially a specific range of values. Chapter number
where this function is introduced is shown in parentheses.
Example:
a = -3
print string(a) + “ “ + string(abs(a))
-3 3
The asc() function will extract the first character of the string
expression and return the character's Unicode value.
Example:
# English
print asc("A")
# Russian
print asc("Ы")
will display:
65
1067
ceil(expression)
Example:
a = ceil(-3.14)
b = ceil(7)
print a
print b
print ceil(9.2)
-3
7
10
The chr() function will return a single character string that contains the
letter or character that corresponds to the Unicode value in the
expression.
Example:
will display:
"In quotes."
Button Description
Value
0 Returns this value when no mouse button has
been pressed, since the last clickclear statement.
1 Returns this value when the “left” mouse button
was pressed.
2 Returns this value when the “right” mouse button
was pressed.
4 Returns this value when the “center” mouse
button was pressed.
This function returns the cosine of the expression. The angle should be
represented in radians. The result is approximate and may not exactly
match expected results.
Example:
a = cos(pi/3)
print a
0.5
This function returns the current day of the month from the current
system clock. It returns the day number from 1 to 28, 29, 30, or 31.
Example:
print day
23
Function that advances the record set to the next row. Returns a true
value if there is a row or false if we are at the end of the record set.
Return a string from the specified column of the current row of the
open recordset.
Returns a Boolean true if the open file pointer is at the end of the file.
If file number parameter is not specified then file number zero (0) will
be used.
Returns a Boolean value of true if the file exists and false if it does not
exist.
Example:
Example:
a$ = “1.234”
b = float(a$)
print a$
print b
will display:
1.234
1.234
Example:
a = floor(-3.14)
b = floor(7)
print a
print b
print floor(9.2)
will display:
-4
7
9
Returns the RGB value of the current drawing color (set by the color
statement). If the color has been set to CLEAR then this function will
return a value of -1.
This function returns the hour part of the current system clock. It
returns the hour number from 0 to 23. Midnight is represented by 0,
AM times are represented by 0-11, Noon is represented as 12, and
Afternoon (PM) hours are 12-23. This type of hour numbering is known
as military time or 24 hour time.
Example:
print hour
15
Return the position of the string needle within the string haystack. If
the needle does not exist in the haystack then the function will return
0 (zero).
Example:
will display:
7
0
When converting a string value the function will return the integer
value in the beginning of the string. If an integer value is not found, the
function will return 0 (zero).
Example:
print int(9)
print int(9.9999)
print int(-8.765)
print int(“ 321 555 foo”)
print int(“I have 42 bananas.”)
will display:
9
9
-8
321
0
Return the key code for the last keyboard key pressed. If no key has
been pressed since the last call to the key function a zero (0) will be
returned. Each key on the keyboard has a unique key code that
typically is the upper-case Unicode value for the letter on the key.
Returns the line number in the program where the runtime error
happened.
Type:
This function will return a string with the upper case characters
changed to lower case characters.
Example:
print lower(“Hello.”)
will display:
hello.
Return Value 0 to 59
Range:
This function returns the number of minutes from the current system
clock. Values range from 0 to 59.
Example:
print minute
47
This function returns the month number from the current system clock.
It returns the month number from 0 to 11. January is 0, February is 1,
March is 2, April is 3, May is 4, June is 5, July is 6, August is 7,
September is 8, October is 9, November is 10, and December is 11.
Example:
dim months$(12)
9
Sept
Button Description
Value
0 Returns this value when no mouse button is being
pressed.
1 Returns this value when the “left” mouse button
is being pressed.
2 Returns this value when the “right” mouse button
is being pressed.
4 Returns this value when the “center” mouse
button is being pressed.
netread()
netread(socket)
Returns the RGB color of a single pixel on the graphics output window.
If the pixel has not been set since the last clg statement or was set to
transparent by drawing with the color CLEAR (-1) then this function will
return -1.
Example:
print rand
# display a number from 1 to 100
print int(rand*100)+1
0.35
22
Read the next word or number (token) from a file. Tokens are delimited
by spaces, tab characters, or end of lines. Multiple delimiters between
tokens will be treated as one. If file number parameter is not specified
then file number zero (0) will be used.
Return Value
Range:
Syntax:
Argument(s): Name: Type:
expression string
length integer
Return Value string
Type:
This function returns the number of seconds from the current system
clock. Values range from 0 to 59.
Example:
17:23:56
This function returns the sine of the expression. The angle should be
represented in radians. The result is approximate and may not exactly
match expected results.
Example:
a = sin(pi/3)
print string(a)
will display
0.87
This function returns the length of an open file in bytes. If file number
parameter is not specified then file number zero (0) will be used.
This function returns true of the two sprites collide with or overlap each
other. The collision detection is done by
Type:
Return Value 0 to ...
Range:
This function returns the height, in pixels, of a loaded sprite. Pass the
sprite number in expression.
This function returns the width, in pixels, of a loaded sprite. Pass the
sprite number in expression.
This function returns the position on the x axis of the center, in pixels,
of a loaded sprite. Pass the sprite number in expression.
This function returns the position on the y axis of the center, in pixels,
Example:
a = 1.234
b$ = string(a)
print a
print b$
will display:
1.234
1.234
This function returns the tangent of the expression. The angle should
be represented in radians. The result is approximate and may not
exactly match expected results.
Example:
a = tan(pi/3)
print string(a)
will display:
1.73
This function will return a string with the lower case characters
changed to upper case characters.
Example:
print upper(“Hello.”)
will display:
HELLO.
This function returns the year part the current system clock. It returns
the full 4 digit Julian year number.
Example:
print year
2009
Mathematical Operators:
Mathematical operators take one or more numeric values, do something, and
return a number.
^ - Exponent (14)
Constant: Value:
pi 3.141593
clear -1
Logical Operators:
Logical operators return a true/false value that can then be used in the
IF statement. They are used to compare values or return the state of a
condition in your program.
<= - Test if One Value is Less Than or Equal Another Value (6)
This chart will help you in converting the keys on a piano into
frequencies to use in the sound statement.
F - 175
F# - 185
G - 196
G# - 208
A - 220
A# - 233
B – 247
Middle C - 262
C# - 277
D - 294
D# - 311
E - 330
F - 349
F# - 370
G - 392
G# - 415
A - 440
A# - 466
B - 494
C - 523
C# - 554
D - 587
D# - 622
E - 659
F - 698
F# - 740
G - 784
G# - 831
A - 880
A# - 932
Key values are returned by the key() function and represent the last
keyboard key pressed since the key was last read. This table lists the
commonly used key values for the standard English keyboard. Other
key values exist.
# dbclose if
abs dbcloseset imgload
acos dbexecute input
and dbfloat instr
asc dbint int
asin dbopen key
atan dbopenset kill
black dbrow lasterror
blue dbstring lasterrorextra
ceil decimal lasterrorline
changedir degrees lasterrormessage
chr dim left
circle do length
clear else line
clg end log
clickb endif log10
clickclear endwhile lower
clickx eof mid
clicky exists minute
close false month
cls fastgraphics mouseb
color float mousex
colour floor mouseynetaddress
cos font netclose
currentdir for netconnect
cyan getcolor netdata
darkblue getslice netlisten
darkcyan gosub netread
darkgray goto netwritenext
darkgrey graphheight not
darkgeeen graphsize offerror
darkorange graphwidth open
darkpurple gray onerror
darkred grey or
darkyellow green orange
day hour pause
pi second system
pixel seek tan
plot sin text
poly size then
print sound to
purple spritecollide true
putslice spritedim until
radians spriteh upper
rand spritehide volume
read spriteload wavplay
readline spritemove wavstop
rect spriteplace wavwait
red spriteshow while
redim spriteslice white
refresh spritev write
rem spritew writeline
reset spritex xor
return spritey year
rgb stamp yellow
right step
say string
Appendix K: Glossary
hertz (hz) – Measure of frequency in cycles per second. Named for German
physicist Heinrich Hertz. See also frequency.
label – A name associated with a specific place in the program. Used for
jumping to with the goto and gosub statements.
list – A collection of values that can be used to assign arrays and in some
statements. In BASIC-256 lists are represented as comma (,)
separated values inside a set of curly-braces ({}).
variable name.