C64 User Manual 1984 2nd Edition
C64 User Manual 1984 2nd Edition
C64 User Manual 1984 2nd Edition
p
m
]
(White)
Video Out
Luminance Input (Yellow)
Monitor Cable
OPTIONAL CONNECTIONS
(REAR PANEL)
Audio Input (White)
AI In
.. - .. . 0
(Red)
Signal Selector
FRONT REAR
..
Since the 64 furnishes a channel of high fidelity sound, you may wish to play it
through a quality amplifier to realize the best sound possible. In addition, the 64
also provides a standard composite video signal, that can be fed into a television
monitor.
These options are made possible by the audio/video output jack on the rear
panel of the 64. The easiest way to gain access to these signals is by using a
standard 5-Pin DIN audio cable (not supplied). This cable connects directly to
the audiolvideo connector on the computer. Two of the four pins on the opposite
end of the cable contain the audio and video signals. You can also construct your
own cable, using the pinouts shown in Appendix I as a guide.
5
Normally, the BLACK connector of the DIN cable supplies the AUDIO signal.
This plug may be connected to the AUXILIARY input of an amplifier, or the
AUDIO IN connector of a monitor or other video system, such as a video cassette
recorder (VCR).
The WHITE or RED connector usually supplies the direct VIDEO signal. This
plug is connected to the VIDEO IN connector of the monitor or video input section
of some other video system, such as a VCR.
Depending on the manufacturer of your DIN cable. the color coding of the
plugs may be different. Use the pinouts shown in Appendix I to match up the
proper plugs if you don't get an audio or video signal using the suggested
connections.
AUDIO SYSTEM
AUDIONIDEO
OUTPUT
: .. _-
TO AUXILIARY
INPUT OR .
TUNER INPUT ..TO VIDEO IN
"- |
TV MONITOR
If you purchased peripheral equipment, such as a VIC 1541 disk drive, an MPS
801,802 or 803 printer, a 1520 plotter or a 1701 monitor, you may wish to connect it
at this time. Refer to the user's manuals supplied with any additional equipment
for the proper procedure for connecting it to the computer.
6
A completed system might look like this.
OPERATION
USING THE 64
1. Turn on the computer using the rocker switch on the right-side panel when
you're looking at the computer from the front.
2. After a few moments the following will be displayed on the TV screen:
7
3. If your TV has a manual fine tuning knob, adjust the TV until you get a clear
picture.
4. You may also want to adjust the color and tint controls on the TV for the best
display. You can use the color adjustment procedure described later to get
everything set up properly. When you first get a picture, the screen should
appear mostly dark blue, with a light blue border and letters.
If you don't get the expected results, recheck the cables and connections. The
accompanying chart will help you isolate any problem.
TROUBLESHOOTING CHART
Symptom Cause Remedy
Indicator Light Computer not Make sure power
not "On" "On" switch is in On"
position
Power cable Check power socket
not plugged for loose or dis-
in connected power
cable
Power supply Check connection
not plugged with wall outlet
in
Bad fuse in Take system to
computer authorized dealer
for replacement of
fuse
No picture TV on wrong Check other
channel channel for
picture (3 or 4)
Incorrect Computer hooks up to
hookup VHF antenna terminals
Video cable Check TV output
not plugged cable connection
in
Computer set Set computer for
for wrong same channel as TV
channel (30r 4)
8
Symptom Cause Remedy
Random pattern Cartridge not Reinsert
on TV with properly cartridge after
cartridge in inserted turning off power
place
Picture without Poorly tuned Retune TV
color TV
Picture with Bad color Adjust color/
poor color adjustment hue/brig htness
on TV controls on TV
Sound with TV volume up Adjust volume of
excess high TV
background
noise
Picture OK, TV volume too Adjust volume of
but no sound low TV
Aux. output Connect sound
not properly jack to aux. input
connected on amplifier and
select aux. input
TIP: The 64 was designed to be used by everyone.
But we at Commodore recognize that computer users may, occasionally.
run into difficulties. To help answer your questions and give you some fun
programming ideas, Commodore has created several publications to help
you. You might also find that it's a good idea to join a Commodore Users
Club to help you meet some other 64 owners who can help you gain
knowledge and experience.
9
CURSOR
The flashing square under READY is called the cursor. It's a marker that
shows where what you type on the keyboard will be displayed on the screen. As
you type, the cursor moves ahead one space as the original cursor position is
replaced with the character you typed. Try typing on the keyboard and watch
the cursor move while characters you type are displayed on the screen.
COLOR ADJUSTMENT
There is a simple way to get a pattern of colors on the monitor so you can
easily adjust the set. Even though you may not be familiar with the operation of
the computer right now, just follow along, and you'll see how easy it is to use
your computer.
First, look on the left side of the keyboard and locate the key marked
. This stands for ConTROL and is used, in conjunction with other
keys, to instruct the computer to do a specific task.
To use a control function, you hold down the key while pressing a
second key.
Try this: hold the
16
When you are using the graphics on the front of
the keys, the SHIFT key displays the graphic
character on the RIGHT side of the key.
When you are using the four special function
I<eys at the right side of the keyboard, the SHIFT
I<ey gives you the functions on the FRONT of the
I<ey (f2, f4, f6, and f8).
17
KEYS THAT LET YOU MAKE CHANGES
CRSR
INSTIDEL
The cursor is the little colored rectangle that
marks your place on the screen. There are two
CuRSoR keys:
t CRSR
moves the cursor up and down
+CRSR moves the cursor left and right
You must use the SHIFT key with the
t CRSR . key to move the cursor up, and with
the + CRSR key to move the cursor to the left.
You don't have to keep tapping a CRSR key to
get it to move more than one space. Just hold it
down until the cursor is where you want it.
DEL stands for DELete. When you press the
DEL key, the cursor moves back a space and
erases the character that's there.
PRINT "ERROR"#.
PRINT "ERROR".
When you DELete in the middle of a line, move
the cursor j ust to the left of the character you
want to DELete.
FIX IT AGAINS, SAM
FIX IT AGAINS. SAM
Then press the DEL key. The characters to the
right automatically move over to close up the
space.
FIX IT AGAIN, SAM
INST stands for INSerT. You have to use the
SHIFT key with the INST/DEL key when you want
to insert characters in a line.
If you've left some characters out of a line, use
the CRSR keys to move the cursor back to the er
ror.
WHILE U WERE OUT
WHILE. WERE OUT
Then, while you hold down the SHIFT key,
press the INST/DEL key until you have enough
space to add the missing characters. INST
doesn't move the cursor; it adds space between
the cursor and the character to its right.
WHILE. U WERE OUT
WHILE YOU WERE OUT
18
CLRlHOME
RESTORE
Use the DEL and INST keys together to fix
wrong characters.
WE'RE NUMBER TO!
WE'RE NUMBER!
WE'RE NUMBER .
WE'RE NUMBER ONE!
HOME moves the cursor back to the upper left
corner of the screen. This is called the "HOME"
position.
CLR stands for CLeaR. When you use the
SHIFT key with the CLRlHOME key, the screen
CLeaRs and the cursor returns to the home
positon.
The RETORE key returns the computer to its
normal state by RESTOREing the default condi
tions (e.g., the default screen color is blue, the
default for 1/0 chips is OFF, etc.) RESTORE does
such things as clear the screen, returning it to the
original color, and turn off the picture- and sound
making chips.
NOTE: For RESTORE to work, you must hold
down the STOP key while you press the
RESTORE key.
For example, suppose you've just played a
music program that also turned your screen red
and yellow while it LISTed the program. When you
press STOP and RESTORE at the end of the pro
gram, the last note from the program will cease,
your screen will turn blue and the only thing
displayed will be the READY prompt.
19
FUNCTION KEYS
The keys on the right side of the keyboard, f1-f8, are function keys that you
can program to perform a variety of tasks. The explanation of the GET state
ment in Chapter 5 tells you how to program function keys in BASIC.
CTRL
RUN/STOP
COMMODORE KEY
The ConTRol key lets you set colors and do
other special tasks called control function.s.
To set colors, hold down the CTRl key while
you press the key with the color you want. You
can get eight more colors with the key.
Chapter 6 also has more about colors.
To get a control function, hold the CTRl key
down while you press the other key. Control func
tions are commonly used in prepackaged soft
ware such as a word processing system.
You can halt a BASIC program while it is still
RUNning by pressing the STOP key. You can also
use the STOP key to halt a printout while it is still
printing.
RUN lets you load a program automatically
from cassette.
When you want to use the RUN key, Y9u must
also use the SHIFT key.
The Commodore key can do two things:
1.
lets you switch back and forth between
the upper and lower case display mode (the let
ters and characters on the tops of the keys)
and the upper case/graphic display mode (capi
tal letters and the graphics on the fronts of the
keys).
To switch modes, press the
and SHIFT
keys at the same time.
When you first turn on your 64, it is in the up
per case/graphic mode, which means that
everything you type in is in capital letters.
When you are in this mode, you can also print
all the graphics on the fronts of the keys.
To print the graphic on the right side of a
key, hold down the SHIFT key while you
press the key with the graphic you want to
print. You can only print the right side
graphics when you are in the upper
case/graphic mode.
To print the graphic on the left side of a key,
hold down the key while you press the
graphic key. You can print the left side
graphic in either mode.
20
2. The key also lets you use the second set of
eight alternate colors not shown on the color
keys. To get these other colors, hold down the
key while you press the number for the
color you want.
1 ORANGE
2 BROWN
:J 3 LT. RED
4 GREY 1
5 GREY2
6 LT. GREEN
7 LT. BLUE
8 GREY3
LOADING PROGRAMS
The COMMODORE 64 accepts programs from disk, cartridge, or cassette
tapes. This means you can use prewritten software simply by loading it. But more
important, the 64 lets you save your own programs for reuse. To reuse a program
you wrote and saved on disk or tape, all you do is load and run it.
When you use tapes or disks with your COMMODORE 64 be sure that your
disk drive or cassette unit is correctly connected.
Loading Carridges
You can use a special line of programs and games on cartridge with your 64.
The programs include a wide variety of business and personal applications. The
games are just like real arcade games, not imitations.
Follow these steps to load games and other cartridges:
1. Turn OFF your COMMODORE 64.
YOU MUST TURN OFF YOUR COMMODORE 64 BEFORE YOU INSERT
OR REMOVE CARTRIDGES. IF YOU DON'T, YOU MAY DAMAGE THE
CARTRIDGE AND THE COMPUTER.
2. Insert the cartridge label uppermost in the slot on the back of your computer.
3. Turn on your 64.
4. Begin the game by typing the START key that's listed in the game's instruc
tion sheet.
21
Loading Prepackaged Cassette Tapes
You can also buy prepackaged software on cassette tape. These cassettes
are just like the ones with recorded music that you can play on a stereo.
1. Inser the cassette into your 1 530 DATASSETTE recorder.
2. Make sure the tape is completely rewound to the beginning of the first side.
3. Type LOAD on your keyboard. The computer answers by displaying PRESS
PLAY ON TAPE.
4. Press PLAY on your DATASSETTE. The screen goes blank until the
computer finds the program. Then the screen displays the message FOUND
(PROGRA NAME).
5. Press the key. This actually loads the program into the computer. If you
want to stop the loading, press the RUN/STOP key.
Loading Your On Prorams From Cassette Tape
The COMMODORE 6 lets you write and save programs on any brand of
cassette tape. All you need is a 1 530 DATASSETE recorder and the same kind
of blank tape you'd use to record music for a stereo tape player.
Follow these simple steps to load a program you wrote and saved on tape:
1 . Rewind the tape to the beginning.
2. Type LOAD "PROGRAM NAME". If you don't remember the program name,
just type LOAD. This loads the first program on the tape into memory.
3. Press RETURN. The computer responds with
PRESS PLAY ON TAPE
4. Press the PLAY KEY. The screen goes blank while the computer searches for
the program. When the program is found, the screen displays this message:
FOUND PROGRAM NAME
5. Press the [c:l key to actually load the program. The screen again goes blank
during LOADing. When the program is LOADed, the screen returns to normal
and the READY prompt appears. If you want to abort the loading, press the
RUN/STOP KEY.
NOTE: When you load a new program into the computer's memory, any
instructions and unsaved programs in the computer are erased and lost
permanently. Before you LOAD a new program, be sure everything you want to
keep is saved.
After your program is LOADed, you can RUN it, LIST it, or make changes.
Remember that you have to reSAVE a changed program if you want to keep the
new version.
Loading Disks
Disks, which are often called "floppy disks", are really easy to use. The
advantage of disks over tapes is that you can find data stored on disks much
faster. You can also save much more data on a disk than on tape.
The steps are the same for loading preprogrammed disks and disks that you
program yourself.
22
1. Inser a disk into your disk drive. Make sure the labl on the disk is facing up.
Put the disk in so that the lablle end gos in last. Look for a little notch on
the disk (it might b covered with a little piece of tape). This notch must b
on the left side as you put in the disk, assuming that you're facing your com
puter. Be sure the disk is all the way in.
2. Close the protective gate on the disk drive after you insert the disk. Just
push down the lever.
3. Type LOAD "PROGRAM NAME", 8. The 8 is the coe for disks. You need to
type it here to let the computer know you're loading a disk.
NOTE: You can LOAD the first program by using the sign in place of the
program name: LOAD ".", 8.
.
4. Press the RETURN key. The disk will spin and your screen will say:
SEARCHING FOR PROGRAM NAME
LOADING
READY
5. Type RUN when the screen says READY and the cursor appears. Your soft
ware is ready to use.
HOW TO FORMAT A NEW DISK
When you're using a new, unprogrammed disk for the first time, you need to
format it. Formatting, which is also called headering, prepares your disk by dOing
things like dividing the disk into blocks. Formatting also creates a directory that
you use as a table of contents for the files you save on the disk. DO NOT header a
preprogrammed disk.
You only have to format new disks, not disks that already have programs on
them unless you want to erase the entire disk and reuse it.
To format a new disk, use this special version of the OPEN and NEW com
mands: '
OPEN 1,8,15"NO:<name>, <id>"
NO tells the computer to header (NEW) the disk in drive O. If you have a dual
disk drive connected (via a suitable interface) header disks in drive O.
The name you use in this command goes in the directory as the name of the
entire disk. Give the disk any name up to 16 characters.
The id is any two characters. Give the disk any id you want, but you should give
every disk a different id code.
When the disk drive light goes off, type CLOSE 1 and press RETURN.
BE CAREFUL! Headering a disk erases all information on the disk, if there is
any. Header only a new disk or a disk you are willing to erase. Here are some
examples of formatting commands that header a disk:
OPEN 1,8,15,"NO:MYFILE,A3"
OPEN 1 ,8,15, "NO:$RECORDS,02"
Now that you know how to header a disk, you are ready to use disks to write
and save programs on your COMMODORE 64. Appendix S contains more
information on the OPEN command.
23
SAVING PROGRAMS
When you want to reuse a program you've written, be sure to SAVE it before
you LOAD another program. If you don't, you'll lose the program.
When you change a SAVEd program, you have to SAVE it again if you want to
keep the new version.
When you reSAVE a program, you are replacing the old version with the new
one. If you want to keep both the old and the changed versions, you have to give
the new one a different name when you SAVE it.
Saving on Disk
When you want to SAVE a program you've written on disk, follow these sim
pie steps:
1. Key in SAVE "PROGRAM NAME",8. The 8 is the code for disks. It tells the
computer that you're using a disk.
2. Press RETURN. The disk makes a nOise, and the computer displays this
message when the program is saved:
SAVING "PROGRAM NAME"
OK
READY
Saving on Cassette Tape
When you want to SAVE a program you've written on cassette tape. follow
these steps:
1. Key in SAVE "PROGRAM NAME". The program name you use can be up to
1 6 characters long.
.
2. Press the RETURN key. The computer displays the message PRESS
RECORD AND PLAY ON TAPE.
3. Press the record and play keys on your DATASSETIE recorder. The screen
goes blank and turns the color of the border. The READY prompt reappears
when the program is SAVEd.
LISTING A DIRECTORY OF PROGRAMS ON A DISK
When you SAVE programs on a disk, the computer automatically makes a
table of contents, or a DIRECTORY, of the names of the programs on the disk.
You can display this directory to see what programs are on your disk. Follow
these steps:
1. Key in: LOAD "$",8 and press RETURN. The computer displays this
message:
SEARCHING FOR $
LOADING
READY
2. Key in: LIST and press RETURN
Your programs names are displayed on your screen.
24
CHAPTER 3
BEGINNING BASIC
Printing and Calculating
Mathematical Functions
Multiple Calculations On One Line
Execution Order in Calculations
Combining PRINT's Capabilities
PRINTING AND CALCULATING
If you don't know BASIC, this section teaches you how to do some simple
things like print words and calculate problems.
The PRINT statement tells the 64 computer to print something on the screen.
PRINT is one of the most useful and powerful commands in the BASIC
language. You can use it to display just about anything, including graphics and
the results of computations. To use the PRINT command, follow these steps:
1. Key in the word PRINT. This tells the computer what kind of job you want it
to do.
2. Key in a quotation mark. This tells the computer where the message you
want to print begins.
3. Key in whatever you want to print on the screen.
4. Key in a closing quotation mark. This tells the computer where the message
you want to print ends.
5. Press the RETURN key. This tells the computer to follow your instructions,
which in this case is to print your message exactly as you typed it.
When you follow these steps, the computer prints your message and
displays the READY prompt. It looks like this:
PRINT "I LOVE MY COMMODORE" You key in this and press RETURN
I LOVE MY COMMODORE The computer prints this
READY
The 64 prints whatever you enclose in quotes. Remember to key in both
quotation marks.
If you make a mistake in your PRINT statement, use the INST/DEL key to cor
rect your error. You can change as many characters as you like before you press
the RETURN key.
If you made a mistake that you didn't catch before you pressed the RETURN
key, the computer can't follow your instructions. Instead, it displays an error
message to help you figure out what you did wrong. For example:
?SYNT AX ERROR
If you get this message, check over what you typed in to see where you made
a mistake. The computer is ver precise, and it can't follow instructions that
contain spelling errors or other mistakes. To avoid mistakes, be sure you type
things in the correct form.
Remember that the best way to get to know BASIC and your 64 is to try dif
ferent things and see what happens.
26
USING PRINT TO CALCULATE
You can use PRINT to do more than just display what you put in quotation
marks. You can also use it to perform calculations and automatically display
the results. Follow these steps:
1. Key in PRINT
2. Key in the calculation you want to solve. DON'T enclose it in quotation
marks.
3. Press the RETURN key. The computer displays the answer followed by the
READY prompt.
Here's an example:
PRINT 12 + 12
24
READY
Type this line and press RETURN
The computer displays
the answer
Be sure you leave off the quotation marks when you want the computer to
solve a problem. If you type the problem inside quotation marks, the computer
assumes you just want to display the problem, not solve it. For example:
PRINT "12 + 12" Key in this line and press RETURN
12 + 12
READY
The computer displays
.
what's in quotes
So all you have to do to use PRINT as a calculator is omit the quotation
marks. You can use PRINT to add, subtract, multiply and divide. You can also
use exponents and perform advanced mathematical functions such as figuring
square roots.
MATHEMATICAL FUNCTIONS
ADDITION
Use the plus sign (+ ) to tell the computer to add numbers. Remember to
press RETURN after you type PRINT and the calculation. This tells the com
puter to follow your instructions.
SUBTRACTION
Use the minus sign (- ) to subtract. Press the RETURN key at the end of the
calculation. For example:
PRINT 12 - 9
3
MULTIPLICATION
Key in this and RETURN
The computer displays this
Use the asterisk (
*) to multiply. You can't use the conventional x because
the computer would think it's the letter x, not the multiplication sign. Press
RETURN at the end of the calculation. For example:
PRINT 12 * 12 Key in this and RETURN
144 The computer displays this
27
DIVISION
Use the slash mark (f for division. Press the RETURN key after you type the
calculation. For example:
PRINT 144/12
12
EXPONENTIATION
Key in this and RETURN
The computer displays this
Use the up arrow ( t ) to raise a number to a power. Press the RETURN key
after you type the calculation. For example, to find 12 to the fifth power, type
this:
PRINT 12 t 5
24832
This is the same as:
PRINT 12 * 12 * 12 * 12 * 12
248832
TIP:
Key in this and RETURN
The computer displays this
BASIC has shortcuts that make programming even faster. One shortcut is
abbreviating BASIC keywords. For example, you can use a ? in place of
PRINT. Throughout this book, we'll show you other abbreviations for
BASIC keywords. Appendix 0 lists these abbreviations and shows what is
displayed on the screen when you type the abbreviated form.
28
MULTIPLE CALCULATIONS ON ONE LINE
The last example shows that you can perform more than one calculation on a
line. You can also perform different kinds of calculations on the same line. For
example:
?3 * 5-7+2
10
Key i n this and RETURN
The computer displays this
So far our examples have used small numbers and simple problems. But the
64 can do much more complex calculations. The next example adds large
numbers.
Notice that 7895.87 doesn't have a comma between the 8 and the 9. You
can't use commas this way in BASIC. BASIC thinks commas indicate new
numbers, so it would think 78,95.87 is two numbers: 78 and 95.87. Remember
to press RETURN after you type the problem.
? 1234.5 + 3457.8 + 78956.87
83649.17
The next example uses a ten digit number. The 6 can work with numbers
that have up to ten digits, but can only display nine digits in the answer. So the
64 rounds numbers that are more than nine digits. Numbers five and over are
rounded up, and numbers four and under are rounded down. This means that
12123123.45 is rounded to 12123123.5. Because of rounding, the computer
doesn't give the same answer you'd get if you added these numbers by hand. In
this case, the answer is 12131364.817. You can see the difference rounding
makes.
? 12123123.45 + 345.78 + 7895.687
12131364.9
The 64 prints numbers between 0.01 and 99 ,99 ,99 using standard nota
tion, except for leaving out commas in large numbers. Numbers outside this
range are printed using scientific notation. Scientific notation lets you express
a very large or ver small number as a power of 10. For example:
? 1230 00
1.23E + 17
Another way of expressing this number is 1.23 * 10 T 17. The 64 uses scien
tific notation for numbers with lots of digits to make them easier to read.
There is a limit to the numbers the computer can handle, even using scien
tific notation. These limits are:
Largest numbers: + /- 1.70141183E + 38
Smallest numbers: + /- 2.93873588E - 39
29
EXECUTION ORDER IN CALCULATIONS
If you tried to perform some mixed calculations of your own, you might not
have gotten the results you expected. This is because the computer performs
calculations in a certain order.
In this calculation:
20+8/2
the answer is 14 if you add 20 to 8 first, and then divide 28 by 4. But the answer
is 24 if you first divide 8 by 2, and then add 20 and 4.
On the 64, you always get 24 because the computer always performs calcula
tions in the same order. Problems are solved from left to right, but within that
general movement, some types of calculations take precedence over others.
Here is the order of precedence:
First:
Second: t
Third:
*
Fourth: + -
minus sign for negative numbers, not for subtraction.
exponentiation, left to right
multiplication and division, left to right
addition and subtraction, left to right
This means that the computer checks the whole calculation for negative
numbers before doing anything else. Then it looks for exponents; then it per
forms all multiplication and division; then it adds and subtracts.
This explains why 20 + 8 1 2 is 24: 8 is divided by 2 before 20 is added
because division has precedence over addition.
There is an easy way to override the order of precedence: enclose any
calculation you want solved first in parentheses. If you add parentheses to the
equation shown above, here's what happens:
? (20 + 8) 12
14
You get 14 because the parentheses allow 20 and 8 to be added before the
division occurs.
Here's another example that shows how you can change the order, and the
answer, with parentheses:
? 30 + 15 * 2 - 3
57
? (30 + 15) * 2 - 3
87
? 30 + 15 * (2 -3)
15
? (30 + 15) * (2 - 3)
-45
The last example has two calculations in parentheses. As usual, they're
evaluated from left to right, and then the rest of the problem is solved. When
you have more than one calculation in parentheses, you can further control the
order by using parentheses within parentheses. The problem in the innermost
parentheses is solved first. For example:
? 30 + (15 * (2 - 3))
15
In this case, 3 is subtracted from 2, then 15 is multiplied by - 1, and -15 is
added to 30. As you experiment with solving calculations, you'll get familiar
with the order in which mixed calculations are solved.
30
COMBINING PRINT'S CAPABILITIES
The 64 computers let you combine the two types of print statements that
you've read about in this book. Remember that anything you enclose in quota
tion marks is displayed exactly as you type it.
The next example shows how you can combine the types of PRINT
statements. The equation enclosed in quotes is displayed without being solved.
The equation not in quotes is solved. The semicolon separates the two pars of
the PRINT statement (semicolon means no space).
? "5 * 9 = "; 5 *.9 You key in this and RETURN
5 9 = 45 The computer displays this
Remember, only the second part of the statement actually solves the calcula
tion. The two parts are separated by a semicolon. You always have to separate
the parts of a mixed PRINT statement with some punctuation for it to work the
way you want it to. If you use a comma instead of a semicolon, there is more
space between the two parts when they're displayed. A semicolon leaves out
space.
The 64's screen is organized into 4 zones of 10 columns each. When you use a
comma to separate parts of a PRINT statement, the comma works as a tab,
sending each result into the next zone. For example:
?"total:";95,"shortage:";15
total:95 shortage:15
If you have more than four results, they are automatically displayed on the
next line. For example:
? 2 * 3,4 - 6,2 i 3,6/4,100 + (-48)
6 - 2 8 1.5
52
Here's the difference when you use semicolons:
? 2 * 3;4- 6;2 t 3;6/4;100 + (-48)
6 -2 8 1.5 52
You can use the difference between the comma and the semicolon in format
ting PRINT statements to create complex displays.
31
CHAPTER 4
WRITING SIMPLE PROGRAMS IN BASIC
Line Numbers
The GOTO Statement
Using the LIST Command
Editing Tips
How to Use Variables
Using FOR ... NEXT Loops
Using I F/THEN Statements to Control Variables
So far this book has shown you how to do simple things with your 64. You've
experimented with typing single lines of instructions into your computer and
getting instant results by pressing the RETURN key. This easy way of doing
things on your computer is called the IMMEDIATE or CALCULATOR mode.
But you'll probably want to use your computer to do more complex jobs that
use more than one statement. When you combine a number of statements into
a PROGRAM, you can use the full power of your 64.
To see how easy it is to write your first program on the 64, follow these steps:
1. Clear the screen by holding down the SHI FT key while you press the
CLR/ HOME key.
2. Key in NEW and press RETURN. This clears out information that might still
be in the computer's memory after your experimenting.
3. Key in the following two lines exactly as they appear here:
10 ? "COMMODORE 64"
20 GOTO 10
4. Remember to press the RETURN key after each line. After you key in the first
line and press RETURN, you'll notice that the computer doesn't respond to
the PRINT command right away like it did before when you typed in the same
kind of commands. This is because you are now beginning the command
with a line number (10). When you use line numbers, the computer knows
that you're writing a program, so it waits for you to finish keying in the whole
program before following any of your instructions.
5. Key in RUN and press RETURN. The RUN command tells the computer that
you've finished keying in program statements, and you're ready to have your
instructions followed. Here's what happens when you RUN this program:
COMMODORE 64
COMMODORE 64
COMMODORE 64
COMMODORE 64
COMMODORE 64
COMMODORE 64
34
6. Stop the program's execution by pressing the RUN/STOP key. The computer
continues to follow your orders by printing COMMODORE 64 over and over
until you interrupt with the RUN/STOP key. Here's how your screen looks
when you press STOP.
COMMODORE 64
COMMODORE 64
COMMODORE 64
COMMODORE 64
COMMODORE 64
COMMODORE 64
BREAK IN 10
READY
This simple program introduces several important concepts that are the
basis for all programming.
LINE NUMBERS
We mentioned before in step 4 that line numbers tell the computer that
you're writing a program. They also tell the computer in what order you want the
statements in your program to execute. Without line numbers to tell the computer
when to follow which instruction, the computer doesn't know what to do first.
The longer and more complex your program is, the more important it is to
remember that the computer relies on you to tell it WHEN to do things, as well
as WHAT to do. One good thing about this is that you can key in line 20 before
line 10 because the computer just checks the line numbers to find out the order
for executing the program. The computer doesn't check for the order your lines
appear on the screen.
Another advantage of line numbers is that you can use the number to refer to
the statement on the line. When you want to go back and repeat the execution
of a statement, all you do is refer to it by line number in a GOTO statement, as
you did in the example above.
35
THE GOTO STATEMENT
When you told the computer to RUN the sample program above, COMMODORE
64 was PRINTed repeatedly instead of just once because of the GOTO state
ment in line 20.
The GOTO statement tells the computer to go directly to a specified line.
Then the computer follows the instructions in the specified line and goes on to
the next line.
You can use a GOTO statement to tell the computer to go back to a line
that's already been executed. Or GOTO can tell the computer to skip forward,
even if this means that some lines in the program don't get executed.
In our example, the program PRINTS the message in line 10 and moves to
line 20. There, the GOTO statement tells the computer to go back to line 10 and
do what line 10 says to do. So, the program prints the message in line 10 again,
and then moves to line 20, which sends the computer back to line 10 and so on.
This repetition is called a LOOP. Because the example doesn't give the com
puter a way out of the loop, the circle repeats endlessly. You have to halt the cy
cle by interrupting the program with the RUN/ STOP key.
It's best to include a statement in your program that ends the loop so you
don't have to use the RUN/ STOP key. We'll explain more above ending loops
later in this chapter.
USING THE LIST COMMAND
Now that you've interrupted execution of the sample program, type in LIST
and press RETURN. Your program is now displayed intact because it's still in the
computer's memory, even though you interrupted the program's execution. The
only difference is that the computer changed your? into the word PRINT. This
doesn't affect your program, it's just the way the computer does things. When
you use the LIST command, the computer also displays the lines of the program
in correct numerical order, even if you entered the lines out of order.
One of the important differences between writing programs and entering
single lines in the immediate/calculator mode is that you permanently lose an
immediate statement once you execute it and clear the screen. But, until you
start a new program, you can always get a program back just by keying in LIST.
From here, you can change the program, SAVE it, or RUN it again.
36
EDITING TIPS
When you make a mistake in a line you've keyed in, or when you just want to
change a line, the 6 offers you a number of editing options.
1. You can retype a line any time, and the computer automatical ly substitutes
the new line for the old one. Al l you have to do to replace a line is use the
same line number. For example:
10 ? "My name is Sarah"
20 ? "I was born in California"
20 ? "I live in Pennsylvania"
RUN
My name is Sarah
I live in Pennsylvania
As you can see, the first line 2 never executes bcause it is replace by
the second line 20. If you now key in a LIST command, you' l l se that only
the second line 2 is sti l l part of the program.
2. You can easily erase a line you don't want just by keying in the line numbr
and pressing the RETURN key. If you now key in LIST, you' l l see that the line
is gone, and so is the line numbr.
3. You can easily edit an existing line. Use the CuRSoR keys to move the cur
sor back to the line you want to change, and then just edit the line any way
you want to. As soon as you press the RETURN key, the edited line wi l l
replace the ol d line. Remembr to use the INST/DEL key to insert or delete.
When you finish editing, you can check your program again to verify changes
by keying in the LIST command. Remembr that LIST also puts lines in
numerical order if you've keyed them in out of order.
Try editing our sample program by adding a semicolon to the end of the line,
and omitting the 6. After you finish the changes, be sure to move the cursor past
line 20 before you RUN the program. Here's how the program works now:
LIST
10 PRINT "COMMODORE ";
20 GOTO 10
COMMODORE COMMODORE COMMODORE COMMODORE
COMMODORE COMMODORE COMMODORE COMMODORE
BREAK IN 10
READY
37
HOW TO USE VARIABLES
A variable is a symbl that stands for a value. Sometimes the value of a
variable is unknown bfore you RUN a program. One of the purposes of a pro
gram may b to find one or more values for a variable. Look at this line from a
program:
20 LET X = 28 + V
The = sign means " become" or "take the value of". The LET instruction is
optional and may be omitted.
In this equation, X and V are variables. Suppose X stands for the number of
days in a month. One of the best things about a variable is that you can reuse it
in a program, so X can stand for the days in al l the months, not just one month.
This is where V comes in. Al l months have 28 days, so V stands for the days
over 28. Later in this chapter there's a program that gives values to these two
variables.
The most important thing now is understanding how variables work, because
variables al low you to do complex tasks with you computer. Variables also let
you write programs that are very reusable.
Imagine that your computer contains a bunch of little slots, like a bank of
mail boxes. When you write a program, you can use some of these slots to hold
values. All you do is give a name to the slots you need, and during the program
you can put values into each slot by using the slot's name. For example, in the
equation above, we use two slots by naming one X and one V. At the beginning
of a program, these slots have names, but they're empty. Here's what happens
when you put a value in V's slot:
X
I I
Now the variable V has the value 3. You can give V this value just by writing this
simple statement:
10V = 3
Since X equals 28 plus V, when you RUN the program X's slot gets a value, too.
X
31
Here's how the program looks:
10 V = 3
20X = 28 + V
30 ? "THE NUMBER OF DAVS IN MAV IS ";X
RUN
THE NUMBER OF DAVS IN MAV IS 31
Here's another program that uses variables:
10 X% = 15
20 X = 23.5
30 X$ = "TOTAL:"
40 V = X% + X
50 ? X$;V
38
When you RUN the program, the imaginary slots look like this after line 3 is ex
ecuted:
On completion of the program, Y has the value: 38.5
The above example uses the three types of variables:
EXAMPLE
TYPE SYMBOL DESCRIPTION EXAMPLES
VALUES
Integer
0
/
0
whole numbrs X%, A1% 15,102,3
Text string $ characters in X$, AB$ "TOTAL:",
quotes "DAY 1"
Floating
real (decimal) X, AB 23.5, 12,
point
or whole numbers
1.3E + 2
Be sure you use the right variable types in your programs. If you tr to do
something like assign a text string to an integer variable, your program won't
work.
There are a few other things to keep in mind when you assign names to
variables:
A variable name can have one or two characters, not counting the special
symbol used with integer and text string variables.
You can use more than two alphabetic characters in a variable name, but the
computer only recognizes the first two. So the computer would think PA,
PARTNO and PAGENO are the same variable referring to the same "slot".
A program is easier for people to read when you use longer variable names,
but when you use more than two characters in a name, be sure the first two
are unique.
You can use X, X%, and X$ in one program because the special symbols %
and $ make each variable name unique. The same is true of A2, A2%, and
A2$.
The first character must be alphabetic (A to Z). The second and any later
characters can be either alphabetic or numeric (0 to 9). Remember that the
computer ignores ever character after the second unless it's a % or $ in the
third position.
Variable names can't contain BASIC keywords, which are also cal led reser
ed words. These are the words like PRINT and RUN that are part of the
BASIC language. Appendix D lists al l the BASIC resered words.
39
Here's one more sample program that shows you how to use variables. This
example also uses some of the other things you've learned so far.
NEW
10 X = 1.0
2OY=30
30Z=X*Y
4 PRINT "SEATS AVAILABLE:";Y
5 PRINT "TICKETS AVAILABLE:";Z
6Y=Y+1
70 PRINT "OVERBOOKING POINT:";Y
RUN
SEATS AVAILABLE: 30
TICKETS AVAILBLE: 315
OVERBOOKING POINT: 301
Lines (10 - 3) assign variable names.
Lines 4 and 5 PRINT a message and the current value of variables Y and Z.
Notice that at line 4, the value for Y is 30.
Line 6 gives Y a new value, and this new value is PRINTed in line 70. Line 60
shows that a variable can have more than one value in a program.
Line 6 also shows another of the powerful features of variables: you can
make a variable equal to itself and another value. This isn't allowed in regular
algebra, but this kind of statement is commonly used in programming. It
means: take the current value of a variable, combine it with another value, and
replace the first value of the variable with this new value. You can also use
statements like these:
Y = Y - 1
Y=Y+X
Y = Y 12
Y = Y * (X + 2)
40
USING FORNEXT LOOPS
We mentioned loops earlier in this chapter during the explanation of the
GOTO statement. As you'll recall, loops are repeated executions of one or more
lines in a program.
The FOR/NEXT statement lets you create very useful loops that control the
number of times a segment of a program is executed. The FOR statement sets
a limit on the number of times the loop will execute by assigning a range of
values to a variable. For example:
FOR COUNT = 1 TO 4
The NEXT statement marks the end of a FOR/NEXT loop. When the program
reaches a NEXT statement, the computer checks the FOR statement to see if
the limit of the loop has been reached. If the limit hasn't been reached, the loop
continues and the variable in the FOR statement is incremented by one. For ex
ample, if you add a FOR/NEXT loop to the program at the beginning of this
chapter, here's what happens:
10 FOR CT = 1 TO 4
20 ? "COMMODORE 64
"
30 NEXTCT
RUN
COMMODORE 6
COMMODORE 64
COMMODORE 64
COMMODORE 6
Now that you've added the FOR/NEXT loop, you don't have to break in with
the STOP key to halt the program's execution.
This FOR/NEXT loop works like this:
Line 10 gives the variable CT a range of values from 1 to 4, and tells the com
puter to execute the next lines until CT equals 4.
Line 20 tells the computer to print COMMODORE 64.
Line 30 tells the computer to add 1 to the current value of CT. As long as the
value of CT remains within the range of 1 to 4, the program repeats, and
COMMODORE 6 is PRINTed again. When CT equals 4, line 20 executes one
more time. When line 30 again adds 1 to CT, the computer knows that CT is now
out of range. So the computer stops executing the loop, and the program ends by
itself.
To make sure you understand how the FOR/NEXT loop works, we'll add more
PRINT statements to line 20 that let you keep track of the value of CT.
41
20 PRINT " COMMODORE 64 "; "COUNT ="; CT
30 NEXTCT
RUN
COMMODORE 64 COUNT=1
COMMODORE 64 COUNT=2
COMMODORE 64 COUNT = 3
COMMODORE 64 COUNT = 4
As you can see, the program ends automatically when CT is out of the range
set up in the FOR statement.
You can increment the value of the variable in a FOR/NEXT statement by
values other than 1 . All you do is add both the word STEP and the value you want
to use to the end of the FOR statement. For example:
NEW
10 FOR NB = 1 TO 10 STEP .5
20 PRINT NB,
30 NEXT NB
RUN
1
3
5
7
9
NEW
1.5
3.5
5.5
7.5
9.5
10 FOR A = 2 TO 8 STEP 2
20 PRINT A,
30 NEXT A
RUN
2 4
This comma tells the computer to print each
value beginning at the first position of the
next 10 space zone.
2
4
6
8
10
6
2.5
4.5
6.5
8.5
8
You can also use a FOR/NEXT loop to count backwards. When you do this,
make sure your STEP is negative. For example, if you change line 10 to this:
10 FOR A = 8 TO 2 STEP -2
Here's how the output looks:
RUN
8 6 4 2
42
USING IF/THEN STATEMENTS TO CONTROL PROGRAMS
An I FITHEN statement is another way to control program execution. This
statement tells the computer to check IF a condition is true. IF that condition is
true, the instructions after the word THEN execute. IF that condition is false, the
program goes on to the next line without following the instructions in the THEN
statement. For example:
10 X = 60
20 X = X + 1
30 I F X = 64 THEN PRINT "GOT IT": END
40 GOT020
You can use an IF statement to start a loop or to decide whether certain parts of
program will execute. For example:
10 A = 0
20 I F A < = 8 THEN 40
30 END
40 ? "FRODO LIVES ",A
50 A = A + 2
60 GOT020
RUN
FRODO LIVES 0
FRODO LIVES 2
FRODO LIVES 4
FRODO LIVES 6
FRODO LIVES 8
In this example, the I F/THEN statement in line 20 tells the computer to check
the current value of A. IF A is equal to or less than 8, THEN the program skips line
30 and continues RUNning at line 40. IF A is more than 8, in other words, IF the
condition in line 20 is false, the computer ignores the instructions after the THEN
statement.
IF line 20 is false, THEN line 30 is executed.
Line 40 PRINTs the message and the current value of A.
Line 50 adds 2 to the value of A each time the loop RUNs. As soon as A
becomes 1 O,line 20 becomes false, line 30 becomes true, and the program ends
immediately.
You can use any of these relational operators in IF/THEN statements:
SYMBOL
<
>
<>
>=
<=
MEANING
Less than
Greater than
Equal to
Not equal to
Greater than or equal to
Less than or equal to
43
MPlL b
ADVANCED BASIC
Introduction
Simple Animation
INPUT
Using the GET Statement for Data Input
Using GET to Program Function Keys
Random Numbers and Other Functions
Guessing Game
Your Roll
Random Graphics
INTRODUCTION
The next few chapters are for people who are familiar with BASIC program
ming language and the concepts necessary to write advanced programs.
Those of you who are just starting to learn how to program may find some of
the information too technical to understand completely. But you'll find some
simple examples that are written for new users in two chapters, SPRITE
GRAPHICS and CREATING SOUND. These examples will give you a good idea
of how to use the sophisticated graphics and sound capabilities available on
your 64.
If you want to learn more about writing programs in BASIC, check the
bibliography in the back of this manual (Appendix N).
If you are already familiar with BASIC programming, the following chapters
will help you get started with advanced BASIC programming techniques. You'll
find extensive information about advanced programming in the COMMODORE
64 PROGRAMMER'S REFERENCE GUIDE, which is available through your
local Commodore dealer.
46
SIMPLE ANIMATION
You can use some of the 64's graphic capabilities by putting together what
you've learned so far in this manual, along with a few new concepts.
Try entering the following program to see what you can do with graphics.
Notice that you can include cursor controls and screen commands WITHIN a
PRINT statement. When you see something like (CRSR left) in a program
listing, hold down the SHIFT key and press the CRSR key. The screen
shows the graphic representation of a cursor left, which is two vertical reversed
bars. The graphic representation of the SHIFTed CLR/HOME key is a reversed
:;.
: INDICATENEW
10 REM BOUNCING BAl.l. COMMAND
20 PRINT "(CLR/HOME "
25 FOR X = 1 TO 10: PRINT "(CRSRIDOWN)";:NEXT "'
30 FOR BL = 1 TO 40
40 PRINT" .(CRSR LEFT)";:REM ". is SHIFT -Q"
50 FOR TM = 1 TO 5
60 NEXT TM
70 NEXT Bl.
75 REM MOVE BALL RIGHT TO l.EFT
80 FOR BL = 40 TO 1 STEP - 1
90 PRINT " (CRSR LEFT) (CRSR LEFT).(CRSR LEFT)";
100 FOR TM = 1 TO 5
110 NEXT TM
120 NEXT BL
130 GOT020
'TIP:
All words in this text will be completed on one line. However, as long as you
don't hit @ your 64 will automatically move to the next line even if
middle of a word.
When this program RUNs, it displays a bouncing ball moving across the
screen from left to right and back again. Take a close look at the program to see
how this is done.
47
LV
+ LNL\L1LPL1
~~~ Z |1J (L1MLNL}
ZD L7 = 1 JL 1. |1J `(LLLV},.L7J
\ +J\
!1+` Q(LLLJ},.L ``Q ISB!+-0"
D \ +N 1 JLD
L7+ J
1 L7JL
1D LN\NLPL 1LJ+\L+
U \ +L+JL!+
!1J (LLL+} (L L+}Q(LLJ},
+ \JN 1 J\ D
++ L7+J
+Z L7+ L
+ L\J\Z
LIDO 1 IS B LB!K DB! OS yOU WDB !DO Q!OQ!BR OOOS. P LNBfK SBO
ROD! DBSDO OOC! ODDOQIOQfBR ISO.
IDOZCOBfS !DOSC!OOD.
IDO ZD!1JS !OD CU!SOfOOWD CORRBDOS. +DIS jUS QOSIIODS !DO OB ID
DORIOOOO!DOSCfOOD. VIDOUDISIDO,DOOBWOUOROVOBC!OSSDOOQIDO
ODOSCfOOD.
IDO SOSUQBOOQOROVODOOBCOURDS!ORO! O !IQD!.
IDOOOSD!OO DIDQS.
1. !1+SB SQBCO OO!BSODO Q!OVIOUSOBQOSIIODS
Z. !1+SDO OB.
. !O!O!RS B CU!SO!~O O QO !OBOy O OIBSO DO CU!!OD OBI QOSIIOD BQBID
IDO D BDO SO UQ B OOQ DB SOWS OOWD DO OBS ROVOROD VIDOU
!DISOOQ, !DOOBWOUO ROVO OOBSO!yOU O SOOCOBfy.
IDO 1 CORQO!OS DO OOQ SO UQ ID IDO O !1J OBS OD DO SC!OOD.
LBCD !IRO !DO OOQ OXOCUOS, !DO OB ROVOS BDODOf SQBCO O DO !IQD PS yOU
CBD SOO !OR DO IUS!!BIOD, DO QfOQfBR CODBIDS B OOQ WIDID B OOQ. YOU
CBD IDCUOO UQ O !OD OOQS WIDID B OOQ. +DO ODy IRO yOU QO ID lOUOO IS
WDOD DO OOQS C!OSS OVO! OBCD ODO!. +DO OOQS DBVO O OO L+L! IDSIOO
OBCD O!DO!. !D O!DOf WO!OS, I yOU S!B!OOQP BDODOD S!B! OOQ IDSIOOOOQP,
yOU RUS! IDISD OOQ (DO IDSIOO OOQ} I!S. P RBXIRUR O DIDO OOQS RBy OO
DOSOOID DIS WBy.
VDOD yOU!O W!IIDQ B Q!OQfBR WID OOQS, I!S B QOOO IOOB O OfBW B!!OWS
!OR DO OOQIDDIDQ O DO ODO O DO OOQS. ! yOU! OOQS C!OSS, DO CORQU!O!
CBD IQU!O OU WDByOU WBD, SO ICBDOXOCUO yOU!QfOQ!BR.
LJDOS U !D!OUQD +Z jUS !OVOfSO HO SOQS ID !DO IfS QBf! O DO Q!OQ!BR,
BDO ROVO DO OB !OR !IQD O O. IDO IS SIQDy OIO!OD !OR IDO 4
OOCBUSO DO OB IS ROVIDQ ID DO OQQOSIO OIlOC!IOD, BDO yOU DBVO O O!BSO DO
OB ODO fIQD! BDO ROVO !O!DOO!.
IDO + SODOS !DO QfOQ!BR OBCK O IDO Z O SB! DO WDOOQ!OCOSSOVO!
BQBID.
OfBVB!IB!IODODDOQfOQ!BR,CDBDQOIDO!O!OBO.
!!+ (!!J} (0)"
UD DO Q!OQfBR BDOSOO WDB!DBQQODSDOW.OCBUSO yOU O OU DOCU!SOf
CODfO, OBCDOB !ORBIDS ODDOSC!OODUDIIISOfBSOO OyDO OBROVIDQfIQD
O O! IDDOSOCODOQB!ODOQ!OQ!BR.
U
INPUT
Up to now, everything in a program has been set up before the program
RUNs. Once you executed the program, you couldn't change or add anything.
The INPUT statement lets you send information to a program WHILE it is RUN
ning. Not only does the program act on this information you supply, but the pro
gram won't continue until you supply it.
To get an idea of how INPUT works, type NEW, press RETURN, and enter this
short program.
1 0 INPUT A$
20 PRINT "YOU TYPED ";A$
30 PRINT
40 IF A$ = "STOP" THEN END
50 GOTO 1 0
RUN
?GO
YOU TYPED GO
? CONTINUE
YOU TYPED CONTINUE
? STOP --
YOU TYPED STOP
Here's what happens in this program:
Line 10 tells the computer to display a question mark to prompt you to INPUT
a value for A$, and to wait until you supply the value before continuing the pro
gram execution.
Line 20 PRINTs a message and the INPUT value, and line 30 PRINTs a blank
line.
Line 40 tells the computer to end the program immediately IF the value you
INPUT for A$ is STOP.
Line 50 returns the program to line 10 so you can INPUT another value. IF line
40 is true because the last value you INPUT for A$ was STOP, then line 50 isn't
executed.
You can INPUT numeric or string variables, and you can have the INPUT
statement print a message along with a question mark to describe the kind of
INPUT the computer is waiting for. For example, here's what happens when you
add a prompt message to line 10 of the previous example:
10 INPUT "KEEP GOING";A$
RUN
KEEP GOING? GO
YOU TYPED GO
KEEP GOING? STOP
YOU TYPED STOP
49
Prompt message can't
be more than 38
characters
Here's a more complex example that demonstrates a lot of what's been
presented so far, including the INPUT statement.
NEW
1 REM TEMPERATURE CONVERSION PROGRAM
5 PRINT "(SHIFT/CLR/HOME)"
10 PRINT "CONVERT FROM FAHRENHEIT OR CELSIUS (F/C)":INPUT A$
20 IF A$ :: "" THEN 10
30 IF A$ :: "F" THEN 10
40 IF A$ < > "C" THEN END
50 INPUT "ENTER DEGREES CELSUIS: ";C
60 F:: (C*9)15 + 32
70 PRINT C;" DEG. CELSIUS:: "; F;" DEG. FAHRENHEIT"
80 PRINT
9 GOTO 10
10 INPUT "ENTER DEGREES FAHRENHEIT: ";F
110 C :: ( - 32)*5/9
120 PRINT F;" DEG.FAHRENHEIT :: ";C;" DEG. CELSIUS"
130 PRINT
140 GOTO 10
Line 10 uses the INPUT statement to print a prompt message and to wait for
you to type in a value for A$.
Lines 20, 30 and 40 check what you typed in and tell the computer where to
go next. Line 20 tells the computer to go back to line 10 and ask for INPUT again
IF nothing was typed in (IF just RETURN was pressed). Line 30 tells the com
puter to go straight to line 100 and perform the Fahrenheit-to-Celsius conver
sion IF the value you typed for A$ is F.
Line 40 checks to be sure that you haven't typed in anything beside F or C. IF
you have, line 40 ends the program. IF you typed in a C, the computer
automatically moves to line 50 to perform the Celsius-to-Fahrenheit conversion.
It may seem like too much detail to include all these IF statements to check
what you INPUT. But this is a good programming practice that can spare you a
lot of frustration. You should always try to be sure that your program takes care
of all possibilities.
Back to the example: once the program knows what type of conversion to
make, the calculations are made. Then the program PRINTs the temperature
you entered and the converted temperature.
The calculation this program performs is just straight math, using the stan
dard formula for temperature conversion. After the calculation finishes and the
answer is PRINTed, the program loops back and starts over.
Here's a sample execution of this program:
CONVERT FROM FAHRENHEIT OR CELSIUS (F/C): ?F
ENTER DEGREES FAHRENHEIT: 32
32 DEG. FAHRENHEIT:: 0 DEG. CELSIUS
CONVERT FROM FAHRENHEIT OR CELSIUS (F/C): ?
After you RUN this program, you might want to save it on disk. This program,
as well as others in this manual, can form part of your program library.
50
USING THE GET STATEMENT FOR DATA INPUT
GET lets you input one character at a time from the keyboard without press
ing the RETURN key. This really speeds up entering data in many cases.
When you RUN a program that has a GET statement, whatever key you press
is assigned to the variable you include in the GET statement. Here's an exam
ple:
1 PRINT "(SHIFT/CLR/HOME)"
10 GET A$: IF A$ = "" THEN 10
20 PRINT A$;
30 GOTO 10
Line 1 clears the screen.
No space between
quotes
Line 10 lets you type in any key on the keyboard. In effect, the loop in line 10
tells the computer to wait until you type in a key before moving to line 20.
Line 20 displays the keys you type on the screen.
Line 30 sends the program back to GET another character. It's important to
remember that the character you type in won't be displayed unless you PRINT it
to the screen, as we've done in line 20.
The IF statement in line 10 is ver important. GET continually works, even if
you don't press a key (unlike INPUT, which waits for your response), so the se
cond part of line 10 continually checks the keyboard until you hit a key.
Try leaving out the second part of line 10 and see what happens.
To stop this program, press the RUN/STOP and RESTORE keys.
You can easily rewrite the beginning of the temperature conversion program
to use GET instead of INPUT. If you've SAVEd this program, LOAD it and
change lines 10 and 20 like this:
10 PRINT "CONVERT FROM FAHRENHEIT OR CELSIUS (F/C)"
20 GET A$: IF A$ = "" THEN 20
This change makes the program operate more smoothly because nothing
happens unless you type in one of the two responses (F or C) that selects the
type of conversion. If you want to keep the program, be sure to SAVE it again.
51
USING GET TO PROGRAM FUNCTION KEYS
As you'll recall from an earlier chapter, we told you that the keys on the right
side of the keyboard (f1 through f8) are function keys that you can program to
perform a variety of tasks.
Here's how to program a function key:
1 . Use a GET Statement to read the keyboard.
2. Use IF statements to compare the key you press to the CHR$ code for the
function key you want to use. Every character on the keyboard has a unique
CHR$ number. For example, the CHR$ code of f1 is 133. Appendix F lists the
CHR$ code for all keys.
3. Use THEN statements to tell the computer what you want the function key
to do.
When you RUN the program, all you do is press a function key you program
med, and the key will follow the instructions you gave it in the THEN statement.
For example:
1 0 GET A$: IF A$ = '''' THEN 10
20 IF A$ = CH R$(1 37) TH EN PRI NT CH R$(1 4)
30 IF A$ = CHR$(1 34) THEN PRINT "YOURS TRULY"
Line 1 0 tells the program to assign the key you press to the variable A$. As
you'll recall from the previous example, the loop in line 10 continually checks
the keyboard for input.
Line 20 programs function key 2, CHR$(1 37). Line 20 tells the computer to
make A$ equal to CHR$(1 4) if you press function key 2. CHR$(1 4) is the switch
from upper to lower case letters on the keyboard. When you RUN this program,
you'll see that the characters on the screen immediately make this switch if you
press f2.
Line 30 programs function key 3, CHR$(1 34). Line 30 tells the computer to
make A$ equal to the character string YOURS TRULY and CHR$(13) if you press
f3 during program execution. CHR$(13) is the code for the RETURN key.
THE CHR$ codes for the function keys are:
f1 = CHR$(1 33) f2 = CHR$(1 37)
f3 = CHR$(134) f4 = CHR$(1 38)
f5 = CHR$(135) f6 = CHR$(1 39)
f7 = CHR$(136) f8 = CHR$(140)
The COMMODORE 64 PROGRAMMER'S REFERENCE GUIDE has more in
formation about programming function keys. You can purchase this extensive
guide from your local Commodore dealer.
52
RANDOM NUMBERS AND OTHER FUNCTIONS
The 64 also has built-in functions that you can use to perform special tasks.
Functions are like built-in prorams included in BASIC. The great advantage of
these built-in functions is that you don't have to type in a number of statements
every time you want to perform a specialized calculation. Instead, all you do is
type the command for the function you want and the computer does all the rest.
These built-in functions include figuring square rots (SOR), finding out the
contents of a memor loation (PEEK), generating random numbers (RND), etc.
Appendix C lists all the functions available on your computer.
One function you can have a lot of fun with is the random number function,
RND. If you want to design a game or an educational proram, you'll often need
to be able to proram your computer to make up random numbers. For exam
ple, you'd need to do this to simulate the tossing of dice. Of course you could
write a program that would generate these random numbers, but it's much
easier to be able to do this just by calling upon the prewritten RaNDom numbr
function.
To see how RND works, tr this short program:
NEW
10 FOR X = 1 TO 10 IF YOU LEAVE OUT THE COMMA, YOUR
20 PRINT RND (1),
LIST OF NUMBERS APPEARS AS 1 COLUMN
30 NEXT
When you RUN this program, the screen displays:
.78928097 .667395
.256373663 .012342287
.68295231
3.97279E - 0
.402342724 .87930 2
.1582093 .24559701
Your numbers don't match? It would be incredible if they did because the
program generates a completely random list of ten numbers.
If you RUN the program a few more times, you'll see that the results are
always different. Though the numbers don't have a pattern, you'll notice a few
consistencies about the list the program displays.
For one thing, the results are always between 1 and 0, but never equal to 1 or
O. For another, the numbers are real numbers (with decimal points).
Now, we started out to simulate dice tosses, and the results from this pro
gram aren't exactly what we're looking for. Now we'll add a few more features
to this program to get what we want.
First, add this line to the program to replace line 20, and RUN the program
again:
20 PRINT 6*RND(1),
RUN
3.60563664
5.48602315
3.10045018
3.91302584
2.32056144
4.52687513
1.09650123
4.39052168
5.032150
4.10781302
53
Now we've got results larger than 1, but still have real numbers. To solve this,
we'll use another function.
The INT function converts real numbers to integer (whole) numbers. So try
replacing line 2 again:
20 PRINT INT(6*RND(1)),
RUN
2 3 1 0
2 4 5 5
o 1
Now we're even closer to our goal, but you'll notice that the numbers range
from 0 to 5, not 1 to 6. So as a final step, we'll replace line 20 again:
20 PRINT INT(6*RND(1)) +1
Now when you RUN the program, you'll get the results you want.
When you want to generate a range of real numbers instead of whole
numbers, the formula is slightly different because you must subtract the lower
limit of the range from the upper limit. For example, you can generate random
numbers between 1 and 25 by typing:
20 PRINT RND(1)*(25-1) + 1
The general formula for generating random nmbers in a certain range is:
NUMBER = RND(1) * ( UPPER LIMIT - LOWER L1MIT)+LOWER LIMIT
54
GUESSING GAME
Here's a game that uses random numbers. This game not only uses the RND
function, but it also introuces some additional programming theory.
When you RUN this program, the computer generates a random number, NM,
whose value you'll try to guess in as few turns as possible.
NEW
1 REM NUMBER GUESSING GAME
2 PRINT "(CLRlHOME)"
__
5 INPUT "ENTER UPPER LIMIT FOR GUESS ";LI
10 NM = INT(L,*RND(1) ) + 1
15 CN = 0
20 PRINT "I'VE GOT THE NUMBER.":PRINT
30 INPUT "WHAT'S YOUR GUESS"; GU
35 CN = CN + 1
40 IF GU>NM THEN PRINT "MY NUMBER IS LOWER": PRINT:GOTO 3
50 IF GU< NM THEN PRINT "MY NUMBER IS HIGHER": PRINT:GOTO 3
60 IF GU = NM THEN PRINT "GREAT! YOU GOT MY NUMBER"
65 PRINT "IN ONLY "; CN ;" GUESSES.":PRINT
70 PRiNT "DO YOU WANT TO TRY ANOTHER (YIN) "
80 GET AN$: IF AN$= "" THEN 8
9 IF AN$ = "Y" THEN 2
10 IF AN$ < > "N" THEN 70
110 END
You can specify how large the number will be at the start of the program.
Then, it's up to you to guess what the number is.
A sample run follows along with an explanation.
ENTER UPPER LIMIT FOR GUESS? 25
I'VE GOT THE NUMBER.
WHAT'S YOUR GUESS? 15
MY NUMBER IS HIGHER.
WHAT'S YOUR GUESS? 20
MY NUMBER IS LOWER.
WHAT'S YOUR GUESS? 19
GREAT! YOU GOT MY NUMBER
IN ONLY 3 GUESSES.
DO YOU WANT TO TRY ANOTHER (YIN) ?
55
The IFfHEN statement (lines 4() compare your guess to the random
numbr (NM) generated by line 10. If your guess is wrong, the program tells you
whether your guess is higher or lower than NM.
Each time you make a guess, line 3 adds 1 to CN. CN is a counter that keeps
track of how many guesses you take to get the right number. The purpose of
this game, of course, is to guess the number in as few tries as possible.
When you get the right answer, the program displays the message, GREAT!
YOU GOT MY NUMBER, and tells you how many guesses you took.
Remember that the program creates a new random number each time you
play the game.
You might want to add a few lines to the program that also specify the lower
range of numbrs generated by this game.
f``
PROGRAMMING TIPS:
In lines 40 and 50. a colon separates multiple statements on a single
line. This not only saves typing time. but it also conserves memory space.
Also notice that the IF/THEN statements in these two lines PRINT
something before branching to another line.
YOUR ROLL
The following program simulates the throw of two dice. You can play this lit
tle game by itself, or use it as par of a larger game.
5 PRINT "CARE TO TRY YOUR LUCK?"
10 PRINT "RED DICE ";INT(RND(1 )*6) + 1
20 PRINT "WHITE DICE ";INT(RND(1 )*6) + 1
30 PRINT " PRESS SPACE BAR FOR ANOTHER ROLL": PRINT
40 GET A$: IF A$ = THEN 40
50 IF A$ = CHR$(32) THEN 10
From what you've learned about BASIC and random numbers, see if you can
follow what's going on in this program. As you may recall from the section on
programming the function keys, CHR$(32) is the character string code for the
space bar.
56
RANDOM GRAPHICS
As a final (lote on random numbers, and as an introduction to designing
graphics, try entering and RUNning this program:
10 PRINT "<CLRlHOME>"
20 PRINT CHR$(205.5 + RND (1));
30 GOTO 20
The function CHR$ (CHaracter String) gives you a character, based on a stan
dard code number from 0 to 255. Every character the 64 can print is encoded
this way. Appendix F lists the CHR$ codes for all keys.
A quick way of finding out the code for any character is to use the function
ASC (for the standard ASCII code). Type:
PRINT ASC("X")
X is the character you're checking. X can be any printable character, including
graphics characters. You must enclose the character in quotation marks.
Here's an example:
PRINT ASC("G")
71
The CHR$ function is the opposite of ASC.
PRINT CHR$(71)
G
If you type:
PRINT CHR$(205);CHR$(206)
the computer displays the two right side graphics on the M and N keys, which
are the characters used in the little maze program you just tried.
The formula 205.5 + RND(1) tells the computer to pick a random number bet
ween 205.5 and 206.5 There is fifty-fifty chance that the random number will be
above or below 20. CHR$ ignores fractional values, so half the time the
character with code 205 is printed, and the rest of the time code 206 is
displayed.
You can experiment with this program by adding or subtracting a couple f
tenths from 205.5. This gives either character a greater chance of being
displayed.
57
LMPLH b
COLOR AND GRAPHICS
How to Use Color and Graphics on Your Computer
Printing Colors
Color CHR$ Codes
How to Use PEEKs and POKEs
Screen Graphics
Screen Memor Map
Color Memory Map
More Bouncing Balls
HOW TO USE COLOR AND GRAPHICS ON YOUR COMPUTER
So far this book has presented some of the sophisticated computing
capabilities of your 64. But one of the most exciting features of your new com
puter is its outstanding ability to produce 16 different colors and a lot of dif
ferent graphics.
You've already seen a very simple demonstration of the graphics in the boun
cing ball program and in the maze program at the end of the last chapter. This
chapter introduces you to new concepts that explain graphic and color
programming, and that suggest ideas for creating your own games and advanc
ed animation.
60
PRINTING COLORS
When you tried the color aligment test in Chapter 1 , you discovered that you
can change text colors by simply holding down the CTRL key and pressing one
of the color keys.
The 64 offers a full range of 16 colors. Though only eight colors are printed on
the color keys, you can get eight more by holding down the key and press
ing a color key. Here's a list of the colors:
KEYBOARD COLOR DISPLY KEYBOARD COLOR DISPLY
M
BLCK
a
[
ORANGE
n
4
M
a
WHITE
I
[a
BROWN M
@ W
RED I
[i
LT. RED
la
CYAN
[a
GRAY 1
MW
I
[i
11
PURPLE GRAY 2
II
GREEN D
[i
L. GREEN II
Ia
BLUE G
[a
L. BLUE L
la
m
[a
YELLOW GRAY 3
When we showed you the boucing ball program in the last chapter, you saw
that keyboard commands, such as cursor movement, can be written into PRINT
statements. In the same way you can also add text color changes to your pro
grams.
61
Type NEW and tr experimenting with changing colors. Hold down the CTRL
key and at the same time press the 1 key. Now release both keys and press the
R key. Now hold down the CTRL key again and press the 2 key. Release the
CTRL key and type the A key. Move through the numbers, alternating with the
letters, and type out the word RAINBOW like this:
10 e|N1 _e_A_I _N_B _O_W"
1aBBaEIB
You'll recall that cursor controls appear as graphic characters in the PRINT
statement. Color controls are also represented as graphic characters. The color
chart printed above shows the graphic characters that appear with each color.
Because of the graphic characters that are displayed when you select color
keys, your PRINT statement will look strange, but when you RUN the program,
you'll see that only the text of the message is displayed. The letters in the
message automatically change colors according to the color controls you plac
ed in the PRINT statement.
Now try making up some examples of your own, mixing any number of colors
within a single PRINT statement. Don't forget the second set of colors that you
can get by holding down the key while you press a color key.
TIP:
After you RUN a program with color or mode (reverse) changes, you'll notice
that the READY prompt and any additional text you key in is the same as the
last color or mode change you made. To get back to the normal display, press
these keys together:
RUN/STOP and RESTORE
62
COLOR CHR$ CODES
Before you start reading this section, take a look at Appendix F, which lists
the CHR$ codes for all keys on the keyboard.
As you looked over the list of CHR$ codes, you probably noticed that each
color has a unique code, just like all the other keys and the keyboard controls. If
you print the codes themselves by using the CHR$ function mentioned in the
last chapter, you can get the same results you got by typing CTRL or and
the color key in a PRINT statement.
For example, try this:
NEW
1 0 PRINT CHR$(1 47) : REM < CLR/HOME >
20 PRINT CHR$(28);"CHR$(28) CHANGES ME TO?"
RUN
CHR$(28) CHANGES ME TO?
When you RUN this program, the screen clears before the message in line 20
is PRINTed. The text should be red now.
In many cases, you'll find that it's much easier to use the CHR$ function to
change colors, especially if you want to experiment. The next page shows
another way to get a rainbow of colors. There are a number of similar lines in
the program (40 through 110), so use the editing keys to spare yourself a lot of
typing. See the notes at the end of the program listing to refresh your memory
on editing procedures.
NEW
1 REM AUTOMATIC COLOR BARS
5 PRINT CHR$(1 47) : REM CHR$(147)= CLR/HOME
1 0 PRINT CHR$(1 8);" ";:REM REVERSE BARS
20 CL = INT(8*RND(1 ))+ 1
30 ON CL GOTO 40,50,60,70,80,90,1 00,11 0
40 PRINT CHR$(5);: GOTO 10
50 PRINT CHR$(28);: GOTO 1 0
60 PRINT CHR$(30);: GOTO 10
70 PRINT CHR$(31 );: GOTO 1 0
80 PRINT CHR$(144);: GOTO 10
90 PRINT CHR$(156);: GOTO 10
1 00 PRINT CHR$(1 58);: GOTO 1 0
110 PRINT CHR$(1 59);: GOTO 10
Type lines 5 through 40 normally. Your display should look like this:
1 REM AUTOMATIC COLOR BARS
5 PRINT CHR$(147) : REM CHR$(147) = CLR/HOME
1 0 PRINT CHR$(1 8); .. ";:REM REVERSE BARS
20 CL = INT(8*RND(1 ))+ 1
30 ON CL GOTO 40,50,60,70,80,90,1 00,11 0
40 PRINT CHR$(5);: GOTO 1 0
63
EDITING NOTES:
Use the <CRSR-up > key to position the cursor on line 40. Then type 5 over
the 4 of 40. Now use the < CRSR-right > key to move over to the 5 in the CHR$
parentheses. Press SHIFT and INST/DEl to open up a space, and key in 28.
Now just press RETURN with the cursor anywhere on the line.
The display should look like this now:
NEW
1 REM AUTOMATIC COLOR BARS
5 PRINT CHR$(1 47) : REM CHR$(1 47)= ClR/HOME
10 PRINT CHR$(1 8);" ";:REM REVERSE BAR
20 Cl = INT(8*RND(1))+1
30 ON Cl GOTO 40,50,60,70,80,90, 1 00,1 1 0
50 PRINT CHR$(28);: GOTO 1 0
Don't worr about line 40; it's still there, as you can see by LiSTing the pro
gram. Follow the same steps to modify line 40 with a new line number and
CHR$ code until you've entered all the remaining lines. As a final check, LIST
the entire program to make sure all the lines are right before you RUN it.
You probably understand the color bar program except for line 30. Here's a
brief explanation of how this program works.
Line 5 prints the CHR$ code for ClR/HOME.
Line 1 0 turns on reverse type and prints 5 spaces, which turn out to be a bar
since they're reversed. The first time through the program, the bar is light blue,
the normal screen display color.
Line 20 uses the random function to select at random a color between 1 and
8.
Line 30 uses a variation of the IFIHEN statement, called ON/GOTO, which
lets the program choose from as list of line numbers where the program will go
next. If the ON variable (in this case Cl) has a value of 1, the program goes to
the first line number listed (here it's line 40). If the variable has a value of 2, the
program goes to the second line listed, and so on.
Lines 40 through 110 just convert the random key colors to the appropriate
CHR$ code for that color and return the program to line 10 to PRINT a section
of the bar in that color. Then the whole process starts again.
See if you can figure out how to produce 16 random colors. Expand
ON/GOTO to handle the additional colors and add the remaining CHR$ codes.
64
HOW TO USE PEEKS AND POKES
PEEKS and POKES let you search around inside your computer's memory
and stick things in exactly where you want them.
You'll recall that in Chapter 4 we explained variables as being like little slots
in the computer's memory, with the variable name as the slot's address. Well,
imagine some more specially defined slots in the computer that stand for
specific memory locations and that have numbers for addresses.
Your 64 looks at these memory locations to see what the screen's
background and border colors should be, what characters to display on the
screen and where to display them, etc.
You can change the screen colors, define and move objects, and even create
music by POKEing a different value into the specific memory slots.
Imagine some memory slots looking something like this:
I
53
80
I I
53
81
I
53282
BORDER
COLOR
BACKGROUND
COLOR
The first two slots are the memory locations for the border and background
colors on your screen. We've put 2, the value for RED in the border color box,
and 1, the value for WHITE in the background color box. Now try typing this:
POKE 53281,7 <RETURN>
The background color of your screen will change to yellow because we put
the value 7, for yellow, in the location tha' controls backgound color.
Try POKEing different values intI) the background color location and see
what result you get. Here's a list of the values to POKE for each color available
on your 64:
0 BLACK 8 ORANGE
1 WHITE 9 BROWN
2 RED 10 light RED
3 CYAN 11 GRAY 1
4 PURPLE 12 GRAY 2
5 GREEN 13 light GREEN
6 BLUE 14 light BLUE
7 YELLOW 15 GRAY 3
Here's a little program that you can use to display various border and
background color combinations:
NEW
10 FOR BO = OTO 15
20 FOR BA = 0 TO 15
30 POKE 53280,BA
40 POKE 53281 ,BO
50 FOR X = 1 TO 500: NEXT X
60 NEXT BA: NEXT BO
RUN
65
This program uses two simple loops to POKE various values to change the
background and border colors. Line 50 contains a DELAY loop, which just
slows the program down a little bit.
If you're curious about what value is currently in the memory location for
background color, try this:
?PEEK (53280) AND 15
PEEK looks at a whole byte, but colors only use half a byte, called a nybble.
To PEEK just this nybble, you have to add the AND 15 to your PEEK statement.
If you used this PEEK after RUNning the previous program, you'd get 15 as the
answer because the last border color POKEd was GRAY 3, which is 15.
In general, PEEK lets you see what value is currently in a specific memor
slot. Try adding this line to your program to display the values of BORDER and
BACKGROUND as the program RUNs.
25 PRINT CHR$(147); "BORDER = "; PEEK(53280) AND 15,
"BACKGROUND = "; PEEK (53281) AND 15
SCREEN GRAPHICS
SO far when you've PRINTed information, the computer has handled the in
formation sequentially: one character PRINTed after the next, starting from the
current cursor position, except when you asked for a new line, or used a comma
in PRINT formatting.
You can PRINT data in a particular place by starting from a known place on
the screen and PRINTing the correct number of cursor controls to format the
display. But this takes time and program steps.
But just as there are certain locations in the 64's memory to control color,
there are also memory locations that you can use to control screen locations.
66
SCREEN MEMORY MAP
The 64's screen can hold 100 characters (40 columns by 25 lines), so there
are 100 memory locations set aside to represent what is on the screen. Imag
ine the screen as a grid, 40 by 25, with each square standing for one memor
location.
Each memory location can contain one of the 256 different characters the 64
can display (see Appendix E). Each of these 25 characters is represented by a
number from 0 to 255. If you POKE the value for a character into a specific
screen memory location, that character will be displayed in that specific screen
location.
Here's a grid that represents your screen, complete with the numbers of each
screen memory location.
COLUMN
10
20 30
39
1063
1024-
1064
1104
1144
1184
1224
1264
1304
1344
1384
'
1424 10
0
1464
:
1504
1544
1584
1624
1664
1704
1744
1784
1824
20
1864
1904
1944
1984
24
t
2023
67
The 64's screen memory normally begins at memory location 1 024 and ends
at location 2023. Location 1 024 is the upper left corner of the screen. Location
1 025 is the position of the next character to the right, and so on. Location 1 03
is the right-most position of the first row. Following the last character in a row,
the next location is the left-most character on the next row down.
Suppose you want to control a ball bouncing on the screen. The ball is in the
middle of the screen, column 29, row 1 2. The formula for calculating the
memory location on the screen is:
POINT = 1 024 + X + 40 * Y.-row
+
column
where X is the column and Y is the row.
Therefore, the memory location of the ball is:
POINT = 1 024 + 20 + 480row (40x1 2)
POINT = 1 524 + column
Clear the screen with SHIFT and CLRlHI_ ME and type:
POKE 1 5,81 +character code
location
This POKE statement makes a ball anpear in the middle of the screen. You
have placed a character directly into screen memory without using the PRINT
statement. However, you can't see the ball yet because it's the same color as
the screen background.
COLOR MEMORY MAP
You can change the color of the ball that appeared by altering another range
of memory. Type:
POKE 55796,2+color
L.
location
This changes the ball's color to red.
Every spot on the 64's screen has TWO memory locations: one for the
character code, and one for the color code. The color memory map begins at
location 5529 (upper left corner), and continues on for 1 000 locations. You use
the same color codes, 0 through 1 5, that you used to change border and
background colors, to directly change character color.
We can modify the formula for calculating screen memory locations to give
us the locations to POKE colors. Here's the new formula:
COLOR PRINT = 55296 + + 40 * Y.- row
L----column
68
MORE BOUNCING BALLS
Here's a revised bouncing ball program that directly prints on the screen us
ing POKEs rather than cursor controls within PRINT statements. When you
RUN this version, you'll see that it's much more flexible than the earlier pro
gram and it leads up to programming more sophisticated animation.
NEW
10 POKE 53281,1: PRINT "<CTRUWHITE><SHIFT CLR/HOME>"
20 POKE 53280,7: POKE 53281,6
30 X=1:Y= 1
40 OX = 1 : OY = 1
50 POKE 1024 + X + 40*Y, 81
60 FOR T = 1 TO 10 : NEXT
70 POKE 1024 + X + 40*Y, 32
80 X = X + OX
90 IF X <= 0 OR X > = 39 THEN OX = - OX
100 Y = Y + OY
110 IF Y < = 0 OR Y> = 24 THEN OY = - OY
120 GOTO 50
Line 10 sets the cursor color to white and then clears the screen.
NOTE: Clearing the screen on (NTSC) 64s sets the color RAM to white but on
(PAL) 64s the color RAM is set to the current background color (here white).
Line 20 sets the background color to blue and the border color to yellow.
The X and Y variables in line 3 keep track of the ball's current row and col
umn position. The OX and OY variables in line 40 are the horizontal and vertical
direction of the ball's movement. When a + 1 is added to the value of X, the ball
moves to the right; when - 1 is added, the ball moves to the left. A + 1 added to
Y moves the ball down a row, and a -1 added to Y moves the ball up a row.
Line 50 puts the ball on the screen at the current X,Y position. Line 60 is a
delay loop, which is included to keep the ball on the screen long enough for you
to be able te see it.
Line 70 erases the ball by putting a space (code 32) where the ball was on the
screen.
Line 80 adds the direction factor to X.
Line 90 tests to see if the ball has reached one of the side walls, and reverses
the ball's direction if there's a bounce. Lines 100 and 110 do the same thing for
the top and bottom walls.
Line 120 sends the ball back to display and moves the ball again.
You can change the ball to any other character by changing the code in line
50 from 81 to another character code.
If you change OX or OY to 0 the ball bounces straight instead of diagonally.
We can also add a little intelligence to the bouncing ball program. So far the
only thing you checked for is whether the ball is going out of bounds on the
screen. Try adding the following lines to the program:
21 FOR L = 1 TO 10
25 POKE 1024 + INT(RNO(1 )*1 000),160 +(REVERSE SPACE)
27 NEXT L
115 IF PEEK(1 024 + X + 40*Y) = 166 THEN OX = -OX: GOTO 80
Lines 21 to 27 put ten blocks on the screen in random positions. Line 115
PEEKs to see if the ball is about to bounce into a block, and, if so, it changes
the ball's direction.
69
CHAPTER 7
INTRODUCTION TO SPRITES
Bits and Bytes
Creating a Sprite
Designing a Sprite
Turning Sprites On
Sprite Colors
Positioning Sprites
Expanded Sprites
_
Creating More than One Sprite
Sprite Priorities
Turning Sprites Off.
In previous chapters, we've shown you how to use graphic symbols in PRINT
statements to create animation and other visual effects.
In chapter 6, we also showed you how to POKE character codes in specific
screen memory loations, which put characters directly on the screen in the
place you selected.
In both of these cases, you have to create objects from existing graphic sym
bols, so these methods take a lot of work. When you want to move the object,
you must use a number of program statements to keep track of the object and
move it to a new place. And sometimes the shape and resolution of the object
isn't as good as you'd like it to be because of the limitations of using graphic
symbols.
You can eliminate a lot of these problems by using sprites in animated se
quences. A sprite is a high-resolution porgrammable object that you can make
into just about any shape by using BASIC commands. All you have to do to
move the object is simply tell the computer the position where you'd like the
sprite to go. The computer takes care of the rest.
But this isn't all you can do with sprites. For example, you can change their
color, you can tell if one object collides with another, you can make them go in
front and behind each other, and you can easily expand their size.
You have to learn a few more details about your 64 and the way it handles
numbers before you can use sprites. It's not difficult, though, so just follow the
examples and you'll be making your own sprites do amazing things in no time.
72
BITS AND BYTES
Before you can use sprites it's important that you understand a few general
things abut how computers work.
In the decimal system, we count in "tens" using values of 0-9. When a
paricular position overflows its maximum value of 9, it re-cycles to zero and
carries one to the next (left-hand) position. For example, the number 64 means
6 x (10) + 4 x (1 ). The position of each digit is important. The value of 64 is
calculated as follows:
6 x 1 0T 1 +4 x10TO
NOTE: Any number raised to the power of zero equals 1 .
Computers store information as a series of electrical charges, representing 1 s
and Os. Each cell within memory holds a pattern of eight ones and zeros called
binary digits or BITS. These cells are called BYTES. A bit, which is the smallest
amount of information a computer can store, can be turned ON, giving it a value
of 1, or OFF, which has a value of O.
When you enter information into the computer via the keyboard, key
depressions are converted into 8 bit patterns of ones and zeros, and transferred
to memory.
The rules for binary arithmetic are much simpler than other systems since
digits can only have two values, 0 or 1 . As illustrated in the previous example, the
decimal system uses the base of 1 0, whereas the binary system uses the base of 2.
One bit can contain one of two combinations, 0 or 1 . There are four possible
combinations of 1 s and Os in two bits ( 2T 2) and with three bits, eight possible
combinations ( 213). The following illustration shows the range of values.
NO. OF NO. OF
BITS VALUES POSSIBLE COMBINATIONS
.-
1 2 t 1 ON 1
= 2 OFF 0
2 2 t 2 ON and ON 1 1
= 4 ON and OFF 1 0
OFF and ON 01
OFF and OFF 0 0
3 2t3 ON and ON and ON 1 1 1
= 8 ON and ON and OFF 1 1 0
ON and OFF and ON 1 0 1
ON and OFF and OFF 1 0 0
OFF and ON and ON 01 1
OFF and OFF and ON 0 0 1
OFF and ON and OFF 01 0
OFF and OFF and OFF 0 0 0
73
As you can see, the number of combinations is 2 raised to the power of the
number of bits. For one BYTE, or eight bits, you can store 256 different values i.e.
2j8.
When all eight bits are OFF, i.e. set to 0, the byte contains a value of zero.
When all eight bits are ON, i.e. set to 1 , the byte has a value of 255. Note that the
combinations range from 0 to 255 inclusive.
You may conver any binary number to a decimal value simply by adding those
powers of two where a bit has been set. The example below illustrates how a
decimal value of 1 81 is held in binary form:
BINARY POSITIONS 2F 2j6 2j5 2j4 2j3 2j2 2j1 2jO
DECIMAL EQUIVALENT
BIT VALUES
1 28 64 32 1 6
o
Adding up the values of the ON bits gives:
2j7 + 2j5 + 2j4 + 2j2 + 2jO
or 1 28 + 32 + 1 6 + 4 + = 1 81
8 4 2
o o
The following is a table showing binary to decimal conversion. A zero indicates
that the bit is OFF, and a 1 shows that a bit is ON. To calculate the value of the
entire byte, add the decimal value of each ON bit.
74
BINARY TO DECIMAL CONVERSION
Decimal Vlue
128 64 32 i6 8 4 2 1
0 0 0 0 0 0 0 1 2jO
0 0 0 0 0 0 1 0 2
1
0 0 0 0 0 1 0 0 2j2
0 0 0 0
1
0 0 0 2j3
0 0 0 1 0 0 0 0 2j4
0 0
1
0 0 0 0 0 2j
5
0 1 0 0 0 0 0 0 2j6
1 0 0 0 0 0 0 0 2j7
TIP:
Converting binary numbers to their decimal values is the basis for creating
data to represent and manipulate sprites. Here's a program that does these
conversions for you. Since you'll be using this program often, you should enter
and save it.
5 REM BINARY TO DECIMAL CONVERTER
10 INPUT "ENTER 8-BIT BINARY NUMBER : ";A$
12 IF LEN (A$) < > 8 THEN PRINT " 8 BITS PLEASE. .. ": GOTO 1 0
15 TL = 0: C
,
0
20 FOR X = 8 TO 1 STEP -1 : C = C + 1
3 TL = TL + VAL(MID$(A$, C,1))*2 t(X-1)
40 NEXT X
50 PRINT A$;" BINARY";" = ";TL;" DECIMAL"
60 GOTO 1 0
At line 1 0 you enter a binary number as the string A$. Line 1 2 uses the LEN
(length) function to check to be sure you entered 8 binary digits. If you didn't,
the program asks for more and repeats line 10.
In line 1 5, TL keeps track of the binary number's decimal value, and C in
dicates which bit is being worked on as the program goes through the loop.
Line 30 updates the value of TL. Appendix C explains the VAL and MID$ func
tions.
Line 50 PRINTs the binary and decimal values of the byte. Line 60 returns the
program to the beginning.
75
CREATING A SPRITE
Sprite Reisters
Before going any further you need to know a little about how sprites are
manipulated by the COMMODORE 64.
Sprites are handled by a special chip inside your COMMODORE 64. This is
called the VIC II chip. This chip contains a series of special bytes called
REGISTERS which are provided specifically for sprite handling. Each register
performs a separate function. For example, the ENABLE REGISTER controls
whether a sprite is active or inactive, while the EXPAND REGISTERS control the
size of a sprite. When you work with sprites, think of a register as a byte with a
specific function. The registers we will be talking about in this chapter are listed
below:
REGISTER No.
0-1 5
1 6
21
23
27
28
29
37-38
39-46
DESCRIPTION
SPRITE POSITIONING
EXTRA MOVEMENT
ENABLE ( ON/OFF)
EXPAND ( VERTICAL)
PRIORITIES
MULTI-COLOR SELECT
EXPAND ( HORIZONTAL)
MUL TI-COLORS
COLOR
Each of these registers, or bytes, have been assigned a specific location in the
memory of the computer. They start at location 53248. This is the 'base address'
of the VIC II chip. To access individual registers, it is easier to assign a variable
with the value of the start address and then add the register number to it, e.g.
V=53248: POKE V+21 , 255. This will put the value of 255 into register 21 .
The VIC II chip in your COMMODORE 64 does all the work of creating and
keeping track of characters and graphics, creating colors and moving sprites
around. All you have to do is to tell the computer the following three details about
the sprite:
What it should look like
What color it should be
Where it should appear
The VIC II chip contains 46 registers and controls up to 8 sprites at a time. You
can design, create and move your sprite by POKEing the appropriate decimal
value in the particular memory location.
76
DESIGNING A SPRITE
A sprite is made up of 504 dots. These are arranged in a 24 dot wide by 21 dot
deep grid. As we mentioned earlier, you can use up to 8 sprites at a time,
numbered from 0 to 7. Each dot on the sprite corresponds to a bit. In order to
design a sprite, you simply set the relevant bit on the grid. Each line on the grid
contains 24 bits ( three bytes). Each sprite takes up 64 bytes in memory, i.e. 21
multiplied by 3 plus one spare byte. (For the more technically minded, the
number 64 is much easier for the VIC II chipto work with because it is a power of 2
and therefore easier to multiply.)
Because you can visualise a sprite inside a grid, the design process is greatly
simplified. Suppose you want to create a balloon and make it float around the
screen. The grid on page 78 shows its shape. You can set up your own grid
preferably using lined, or better still, graph paper. Draw a grid that is 21 squares
high and 24 squares across. Divide the 24 squares across into 3 sections of 8
spaces.
The next step is to convert the graphic design into data the computer can use.
Number the 8 squares in each of the three sections 1 28, 64, 32, 1 6, 8, 4, 2 and 1 .
These values are equivalent to 2j7, 2j6, 2j5, 2j 4, 2j3, 212, 211 and 2jO.
Number the squares down the left hand side of the page from 1 -21 for each
row. Now fill in the grid with any design, or use the balloon that we've drawn. It's
easier to outline the shape first, then go back and fill in the grid.
Think of the squares you have filled in as ON bits, and substitute a 1 for each
filled square. Think of the squares tat aren't filled as OFF bits, and give them a
value of zero.
Now look along row 1 and think of each 8 square section as a byte. Convert
each section of 8 bits into a decimal value. You can even use your Binary to
Decimal converter program if you wish. Now convert each of the 21 rows into 3
decimal values, giving 63 values in all.
77
SERIES SERIES SERIES
1 2 3
32 32
1
2
3
4
5
6
7
8
9
10
"11
12
13
14
15
16
17
18
19
20
21
10 15 20 24
COLUMN
Now look at the design of the balloon. The first series of 8 squares on the first
row are all blank, therefore the bits are all OFF giving a value of zerO. The middle
series on row 1 looks like this:
00000000 011 1 1 1 1 1 00000000
The third series of 8 squares on the first row also contains only blanks so it also
equals zero. So the data for the first line is:
DATA 0, 1 27, 0
The three series of dots that make up row two are calculated like this:
Series 1: I 0 o I 0
Series 2: Ll 1
i 1 i
128 + 64 + 32
Series 3:
I I
i
128 +
1 0
i
64
0
1
i
+ 16
0
o 0 I 0
1 1
i i i i
+ 8 + 4 + 2 + 1
0 0 0 0
78
255
192
The data for the second row is:
DATA 1 , 255, 1 92
Use this method to convert the three series of 8 squares in each of the
remaining rows. Once you have completed these calculations, you are ready to
write a BASIC program to use the balloon (or any other shape) since the sprite
has now been converted into values your computer can understand.
To demonstrate the use of sprites, type in the following program:
1 REM UP, UP, AND AWAY
5 PRINT "(CLR/HOME)"
1 0 V=53248 : REM START OF DISPLAY CHIP
1 1 POKE V+ 21 ,4 : REM ENABLE SPRITE 2
1 2 POKE 2042,1 3: REM SPRITE 2 DATA FROM BLOCK 1 3
20 FOR N = TO 62: READ 0 : POKE 832 + N,O: NEXT
30 FOR X = TO 200
40 POKE V + 4,X: REM UPDATE X COORDINATES
50 POKE V + 5,X: REM UPDATE Y COORDINATES
60 NEXT X
70 GOTO 30
200 DATA 0,1 27,0,1 ,255,1 92,3,255,224,3,231 ,224
210 DATA 7,21 7,240,7,223,240,7,21 7,240,3,231 ,224
220 DATA 3,255,224,3,255,224,2,255,1 60,1 ,1 27,64
230 DATA 1 ,62,64,0,1 56,1 28,0,1 56,1 28,0,73,0,0,73,0
240 DATA 0,62,0,0,62,0,0,62,0,0,28,0
If you have entered everything correctly, when you type "RUN" and press
RETURN, your balloon should sail across the screen. At this stage, you will not
understand the meaning of much of the program but, as we explain each stage of
sprite handling, we will use the program to illustrate each feature.
Line numbers 200-240 relate to the definition of your balloon and contain 21
sets of three values, i . e. one set for each row on your design chart.
79
SPRITE POINTERS
The sprite pointer indicates where you have stored your sprite in memory. The
sprite pointers are stored in 8 bytes from location 2040 to 2047 inclusive. The
normal location of the pointer for sprite 0 (the first sprite) is 2040; the location for
the pointer for sprite 1 is 2041 ; and so on with location 2047 used as the location
of the pointer for sprite 7.
Each sprite pointer can contain a value between 0 and 255. This number,
multiplied by 64, corresponds to the start address of your sprite data. Since each
sprite uses 64 bytes, the sprite pOinter can contain a block number anywhere
within the first 1 6K block of memory accessible by the VIC II chip, i.e. 256 * 64. It
is also possible to use other 1 6K blocks. Further details can be found in the
COMMODORE 64 Programmer's Reference Guide.
NOTE: It is always advisable to store the data for your first sprite at block 255 and
then store data for subsequent sprites in the next available blocks working
downwards. This will prevent your sprite data from interfering with the BASIC
program. If you find that the sprite data is writing over the end of your BASIC
program, you must store your sprite data in the next available 1 6K block of
memory or move the BASIC program above the sprite data. Again, details on
how to do this can be found in the COMMODORE 64 Programmer's Reference
Guide.
In the balloon program, line 1 0:
V = 53248
assigns the value of the start address of the VIC II chip to the variable V. Later in
the program you can add the register number to the address stored in V. For
example line 1 1 :
POKE V+21 ,4
references register number 21 .
Line 1 2 of the balloon program:
POKE 2042,255
places the data from sprite 2 into block 255.
80
TURNING SPRITES ON
Before you see and use your sprites, you must first activate them. You do this
by using the SPRITE ENABLE register, register number 21 . As mentioned
above, line 11 in the balloon program turns on sprite 2. This is done by placing
the value 4 in the register. This is 2 to the power of the sprite number 2, i.e. the
sprite you are initializing.
Refer to the structure of a byte earlier in the chapter if you do not understand
how we get this value. If you had wanted to turn on two sprites, you would simply
add the decimal values together. For example, to turn on sprites 2 and 3 add 8
and 4 (2t2 + 2t3). The instruction would then be:
POKE V+21 , 12
TIP:
An easier way to turn on a selected sprite is to use a simple calculation
that sets the required bit in the SPRITE ENABLE register. In the program
statement below, SN equals the sprite number (0-7) that you want to turn on.
POKE V + 21 , PEEK(V + 21 ) OR (2tSN)
SPRITE COLORS
A sprite can be any of the 16 colors available on your COMMODORE 64. The
colors are numbered 0-15. Chapter 6 and Appendix G contain the colors and
their codes. As you can see from the VIC II chip Register Map, each sprite has its
own color register. Register numbers 39-46 are used for this purpose. Register
39 holds the color for sprite 0, register 40 for sprite 1 , and so on with register 46
holding the color for sprite 7.
When you see your sprite on the screen, the dots are displayed in the color
contained in the color register. The rest of the sprite is transparent and shows
whatever color is behind the sprite.
If you wanted to change the color of sprite 2 to light green (code number 13),
simply POKE the color code in the sprite's color register as follows:
POKE V + 41 ,13
81
POSITIONING SPRITES
Now you've made a sprite, you want it to appear and move around the screen.
To do thi
s
your COMMODORE 64 uses three positioning registers:
a) Sprite X Positioning Register
b) Sprite Y Positioning Register
c) Most Significant X Position Register.
The X and Y Position Registers work together to pinpoint where your sprite
appears on the screen. The X Position Register positions the sprite in the
horizontal direction and the Y Position Register positions the sprite in the vertical
direction. On the VIC II chip register map notice that registers 0-1 5 are used for
the X and Y co-ordinates. The registers are arranged in pairs as fol'lws:
Register 0 holds the X co-ordinate for sprite 0
Register 1 holds the Y co-ordinate for sprite 0
Register 2 holds the X co-ordinate for sprite 1
Register 3 holds the Y co-ordinate for sprite 1 .
This pattern is repeated with Registers 1 4 and 1 5 holding the X and Y co
ordinates for sprite 7. There is a further register (1 6) which we shall discuss later.
You can position your sprite. by simply POKEing values into the appropriate
registers. You need both X and Y co-ordinates to position your sprite. Calculate
all positions from the TOP LEFT of your sprite area. It does not matter how many
dots you fill up in the 24 x 21 dots area allocated to your sprite design. The
position is still calculated from the top left corner.
If you look at the balloon program once again, statement numbers 30-70 use a
FOR . . .. NEXT loop to move the balloon diagonally across the screen from left to
right. These statements increment the values of the X and Y co-ordinates by
POKEing the positions into registers 4 and 5, the registers for sprite 2, until both
values reach 200. Line 70 then runs the program again.
You may have noticed that when the program was running, the balloon did not
move to the far right hand side of the screen. Positioning in the horizontal
direction is difficult since you need 320 locations and you therefore need an
additional bit, which will then give you up to 51 2 positions. If you do not
understand how we arrived at this figure, think of an extra bit being added to the
left hand side of a byte. This would be the equivalent of 2 raised to the power of 8.
The extra bits for all sprites are stored in the Most Significant Bit Register
( MSB), register 1 6. Bits 0-7 of this register correspond to sprites 0-7 respectively.
If you are not using positions greater than 255, the corresponding extra bit
position must be turned off, i.e. it must contain a value of zero.
82
Here's how the MSB works: after you've moved the sprite to X location 255,
POKE the sprite's decimal value into register 1 6. For example, to move sprite 6
to horizontal locations 256 through 320, use this statement:
POKE V + 1 6,64
Then use a loop to move sprite 6 the 64 spaces from location 256 to 320:
FOR X = 0 to 63: POKE V + 1 2,X: NEXT
The following program revises the original balloon program so that sprite 2
moves all the way across the screen:
1 0 V = 53248: POKE V + 21 ,4 : POKE 2042, 1 3
20 FOR N = 0 TO 62 : READ Q : POKE 832 + N,Q : NEXT
25 POKE V + 5, 1 00
30 FOR X = 0 TO 255
40 POKE V + 4,X
50 NEXT
60 POKE V + 1 6,4
70 FOR X = 0 TO 63
80 POKE V+ 4, X
90 NEXT
100 POKE V + 1 6,0
1 10 GOTO 30
Line 60 sets the most significant bit for sprite 2.
Lines 70 through 90 contain the loop that moves sprite 2 across screen loca
tions 256 through 320.
Line 1 00 turns OFF the MSB so that sprite 2 can go back to the left edge of
the screen. In other words, when the MSB is ON, the sprite can only move from
locations 256 through 320. You have to turn the MSB back OFF before you can
move the sprite from locations 0 through 255.
Note that the program we used for turning on individual sprites can also be
used to set a specific MSB. The complementary statement which will turn OFF a
specific bit is:
POKE V+21 , PEEK(V+21 ) AND ( 255-(2jSN))
where SN is the number of the sprite you wish to move.
EXPANDED SPRITES
You can increase the size of each dot of the sprite so that the sprite is twice as
wide, twice as deep or expanded in both directions at once.
There are two EXPAND registers:
Register 23 doubles the width of the sprite
Register 29 doubles the height of the sprite.
The method for expanding sprites is the same as that used when enabling
them, e. g. to expand a specific sprite in the X direction only, use the following
statement:
POKE V+23, PEEK ( V+23) OR 2t SN
where SN is the number of the sprite you wish to expand.
83
The same applies when doubling the height of a sprite except that this time you
use V+29.
Try adding the following line to the original balloon program:
POKE V + 23,4: POKE V + 29,4 : REM EXPAND SPRITE
When you type "RUN", the balloon has now doubled in size. This is
because you POKEd the decimal value for sprite 2 (2t2) into register 23 which
doubles the height of the balloon, and into register 29 which doubles the
width of the balloon.
CREATING MORE THAN ONE SPRITE
It is a simple operation to create and store more sprites. Instructions on how to
do this are given earlier in this chapter. To add sprite 3 to your screen, include the
following lines in the original balloon program:
11 POKE V + 21,12
12 POKE 2042,13: POKE 2043,13
30 FOR X = 1 TO 190
45 POKE V + 6,X
55 POKE V + 7,190 - X
Line 11 turns ON sprites 2 and 3 by POKEing their combined decimal values
(4 and 8) into the sprite enable register (21).
Line 12 tells the computer to find the data for the sprites in block 255 of the VIC
II chip memory. Recall that 2042 is sprite 2's pointer and 2043 is the pointer for
sprite 3.
Lines 45 and 55 move sprite 3 around the screen by changing the values of the
X and Y co-ordinate registers of that sprite (V + 6 and V + 7).
When you RUN the program, you will see two balloons moving around the
screen. This is because we POKEd the same address into both sprite pointers.
The following lines put sprite 4 on the screen too:
11 POKE V + 21,28
12 POKE 2042,13:POKE 2043,13:POKE 2044,13
25 POKE V + 23,12: POKE V + 29,12
48 POKE V + 8,X
58 POKE V + 9,100
Line 11 turns ON sprites 2,3 and 4 by POKEing tl1eir combined decimal values
(4, 8 and 16) into the sprite enable register (21).
Line 12 tells the computer to find the data for all three sprites in block 255 of
memory.
Line 25 doubles the size of sprites 2 and 3 by POKEing their combined value
into the registers that control height and width expansion (23 and 29).
Line 48 moves sprite 4 halfway along the X axis (horizontally).
Line 58 positions sprite 4 halfway down the screen at location 100. Previously,
the Y co-ordinate has been changed in the program by the use of a FOR ... NEXT
loop. (See line 50 in the original progra.) But now the value for the Y co-ordinate
for sprite 4 (V + 9) stays the same during the program. This means that sprite 4
only moves horizontally.
84
SPRITE PRIORITIES
If you are using more than one sprite you may wish to make sprites cross over
each other on the screen. Sprite to sprite priority is preset. Sprites having the
lowest numbers have the highest priority, i.e. sprite 0 has the highest priority,
then sprite 1, sprite 2, etc. Sprite 7 has the lowest priority. Sprites with higher
priorities appear in front of sprites with lower priorities.
Sprite to background priority is controlled by the SPRITE BACKGROUND
PRIORITY register, register 27. Bits 0-7 in this register correspond to sprites 0-7.
These bits are normally set OFF (equal to zero) which means that the sprites
have a higher priority than the background, i.e. they pass OVER any data on the
screen. If you wish to switch this priority for any sprite(s) you must turn ON the
relevant bit(s). For example, the statement:
POKE V + 27,8
makes sprite 3 appear behind the characters that are on the screen.
TURNING SPRITES OFF
You can make a sprite disappear by setting the relevant bit in the SPRITE
ENABLE register (21) OFF. Do this using the following statement:
POKE V + 21, PEEK (V + 21) AND (255 - 2tSN)
where SN is the number of the sprite you wish to turn off.
Boolean Operators
This instruction in the previous example uses what is known as a LOGICAL
OPERATOR, sometimes known as a BOOLEAN OPERATOR. In that example,
the AND was the logical operator. It is used to modify the first of two elements in
the statement, i.e. register 21.1t logically compares each corresponding bit of the
result of the PEEK statement according to the following rules:
1 AND 1 = 1
OAND 1 = 0
1 ANDO = 0
OANDO = 0
This is known as a TRUTH TABLE. As you can see, the bit being compared is
set OFF unless both bits contain 1. You can apply the above statement to set
OFF bits in any register for any sprite number. For example, you could have used
the same instruction to reduce the size of a sprite by simply substituting either
register 23 or 29. Let us see what happens when we turn off sprite 3.
Before the instruction is executed, register 21 contains 00001000. The result
of the expression after the PEEK statement is: 255 - 2t3 (8) = 247 or 11110111,
i.e. after the instruction has been executed, register 21 contains zero. If other
sprites had been ON, they would remain in the same state since both bits would
have contained 1.
85
The other Boolean operator we have used is OR. The truth table for this
operator is as follows:
1 OR 1 = 1
a OR 1 = 1
1 OR a = 1
aORa = a
If either bit is set, the correspnding result bit will also be set.
This chapter has only been an introduction to sprites. Try experimenting
yourself with the design and animation of your own sprites. Further details about
sprite handling can be found in the COMMODORE 64 Programmers' Reference
Guide.
86
CHAPTERS
MAKING SOUND AND MUSIC
The SID Chip
Sample Sound Program
Playing a Song on Your 64
Creating Sound Effects
Filtering
Music Composer
Your COMODORE 6 coputer is equipped with one of the most sophisticated
electronic music synthesizers available on any computer. This chapter is an
introuction to using your computer's sound chip, the SID chip. The main
features that the SID chip provides are:
a) Volume control
b) Multiple voices
c) Waveform
d) Frequency
e) Envelope generator ( attack, decay, sustain, release)
THE SID CHIP
The SID (Sound Interface Device) chip contains 29 8-bit registers, numbered
0-28, each of which is respnsible for a certain component of sound generation.
In this chapter, you will only be concerned with the first 25 registers. These are
stored between loations 54272 to 54296 inclusive.
Here is a summary of the SID register map:
REGISTER Nos.
0-6
7-13
14-20
21
22
24
DESCRIPTION
VOICE 1
VOICE 2
VOICE 3
LOW FREQUENCY
HIGH FREQUENCY
VOLUME CONTROL AND FILTERS
Before we go on to discuss how sounds are created, type in the following
program and then RUN it. This will demonstrate just a little of what may be
achieved by the SID chip.
88
EXAMPLE PROGRAM 1
5 S=54272
10 FOR L=S TO S+24: POKE L,O:NEXT:REM CLEAR SOUND CHIP
20 POKE S+5,9:POKE S+6,0
30 POKE S+24, 15:REM SET MAXIMUM VOLUME LEVEL
40 READ HF, LF, DR
50 IF HF<O THEN END
60 POKE S+l , HF: POKE S,LF
70 POKE S+4, 33
80 FOR T=l TO DR:NEXT
90 POKE S+4, 32:FOR T=l TO 50: NEXT
100 GOT040
1 10 DATA 25, 177,250,28,2 14,250
120 DATA25, 177,250,25, 177,250
130 DATA25, 177, 125,28,2 14, 125
140 DATA32,94,750, 25, 177, 250
150 DATA 28,2 14,250, 19,63,250
160 DATA 19,63,250, 19,63,250
170 OATA 2 1, 154,63,24,63,63
180 DATA25, 177,250,24,63, 125
190 DATA 19,63,250,- 1,- 1 ,- 1
Line 5 stores the start location of the SID chip in S. All other registers are
accessed by simply adding their number to S.
Volume Control
Your COMMODORE 64 has 16 volume levels, numbered from (off) to 15
(maximum volume). Register 24 in the SID chip controls the volume level. To set
the volume, yO: simply POKE the value you want into this register. Line 30 in the
example program sets the maximum volume level (15).
You would normally only set the volume at the beginning of your program. Note
that the volume level determines the output from all three of your 64's voices.
Voices
Your COMMODORE 64 has three voices, which may be played separately or
simultaneously. The register map for each voice is shown below:
REGISTER NUMBERS
VOICE 1 VOICE 2 VOICE 3 DESCRIPTION
0 7 1 4 LOW FREQUENCY VALUES
1 8 15 HIGH FREQUENCY VALUES
2 9 16 LOW PULSE WIDTH
3 10 17 HIGH PULSE WIDTH
4 11 18 CONTROL REGISTER
5 12 19 ATACK/DECAY SETIINGS
6 1 3 20 SUSTAIN/RELEASE SETTINGS
89
Frequency
Sound is created by the movement of air. Think of throwing a stone into a pool
and seeing the waves radiate outward. When similar waves are created in air, we
hear a sound. Every sound produced on your 6 is made up from a high and low
frequency value. Each of the three voices has two registers in which the
frequency values are stored. The two values in each voice are combined to form
the frequency value in 16 bit form.
A chart showing the memory locations for each voice's high and low frequency
registers is shown below:
VOICE FREQUENCY POKE NUMBER
1 HIGH 5427 3
1 LOW 54272
2 HIGH 54280
2 LOW 54279
3 HIGH 54287
3 LOW 54286
To play a musical note or sound, you must POKE the sound's high frequency
value into the high frequency location of the voice you want, and POKE the
note's low frequency value into the voice's low frequency location. Line 60 in the
example program POKEs the high and low frequencies from the data statements
into registers 1 and 0 respectively. This sets the frequency for voice 1.
Creating Other Frequencies
To create a frequency other than those listed in the note table, use the
following formula:
F = FYOUT I .06097
where FYOUT is the frequency you require.
To create the high and low frequency values for the note, you must first make F
into an integer, i.e. delete any numbers to the right of the decimal point.
Now use this formula to calculate the high frequency location:
HI = INT( F/256),
and the following formula to give you the low frequency location:
LO = F - (256 * HI)
Then to obtain the note, simply POKE the value for LO into the low frequency
register and the value for HI into the high frequency register of the voice from
which you wish to output the sound.
90
Waveforms
The type of waveform you select determines the timbre or quality of the sound
produced.
There are four types of waveforms:
Triangle. This waveform contains few harmonics and a mellow flute-like sound.
The shape of the triangle waveform looks like this:
Triangular:
Sawtooth. This waveform contains all the harmonics. It has a bright, brassy
quality. Here is what the sawtooth waveform looks like:
Sawtooth:
91
Variable pulse wave. This waveform contains variable rectangular waves.
Changing the pulse width makes sounds ranging from a bright, hollow noise to a
nasal, reedy pulse. Here's what it looks like:
Pulse (variable rectangular waves):
-PLSE WIOTH-
'-
White noise. This waveform is used mainly for sound effects (e.g. explosions,
gunshots, surf) and ranges from a low rumbling to hissing. It looks like this:
White noise (used mainly for sound effects):
The waveform for each voice is held in three control registers. These are
numbered 4, 1 1 and 18 . The component parts of the control register for each
voice are as follows:
92
BIT Nos.
o
1-3
4
5
6
7
DESCRIPTION
GATE
UNUSED
TRIANGLE WAVEFORM
SAWTOOTH WAVEFORM
PULSE WAVEFORM
NOISE WAVEFORM
The GATE bit controls the Envelope Generator. When this bit is set to 1 , it
triggers the Envelope Generator and the ATIACK/DECAY/SUSTAIN cycle
begins. When the bit is reset to zero, the RELEASE cycle begins. Setting bits 4, 5
or 6 to 1 selects that particular waveform.
Line 70 in the program sets the output of the sound for voice 1 using a
Sawtooth waveform. This line also sets the GATE bit.
You can set combinations of these bits, i.e. Pulse and Sawtooth, but this will
produce pretty weird sounds!
The Envelope Generator
The volume of a musical note changes from the moment you first hear it until it
dies out and you can't hear it any more. When a note is first struck, it rises from
zero volume to its peak volume. The rate at which this happens is called the
ATIACK. It then falls from the peak to a mid-range volume level. The rate at
which this occurs is called the DECAY. The mid-range volume is called the
SUSTAIN level. When the note stops playing, it falls from the SUSTAIN level to
zero volume. The rate at which it falls is called the RELEASE. The following is an
illustration of the four phases of a note:
SUSTAIN LEVEL --
A : 0: S
NOTE: ATTACK, DECAY and RELEASE are RATES. SUSTAIN is a LEVEL.
Each of the cycles above give certain qualities and restrictions to the shape, or
ENVELOPE of a sound. These bounds are collectively called parameters. The
A TI ACKIDECAY ISUST AIN/RELEASE parameters are collectively called ADSR.
There are two registers used for the ADSR parameters for each of the three
voices. These are 5 and 6 for voice 1, 12 and 13 for voice 2 and 19 and 20 for
voice 3. The ATIACK and DECAY parameters share the first of each pair of
registers (5, 12, 19) while the SUSTAIN and RELEASE parameters use registers
6, 13 and 20.
93
These pairings are used because the settings only require 4 bits or half a byte.
This amount of storage is called a NYBBLE. The first four bits of a byte are called
the HIGH NYBBLE and the last four bits are called the LOW NYBBLE. The
ATTACK settings for the three voices are stored in the high nybbles of registers
, 5, 12 and 19, while the DECAY settings are stored in the low nybbles of these
registers. The SUSTAIN settings for the three voices use the high nybbles in
registers 6, 13 and 20, while the RELEASE settings use the low nybbles in the
same registers.
Before POKEing any value into the ADSR registers you must first combine the
high and low nybbles by adding them together. For example, the ATTACK rates
occupy the 2j7, 2j6, 2j5, and 2j4 bits, so the values are 128, 64, 32 and 16.
DECAY rates use the 2j3, 2j2, 2j1 and 2jO bits, or 8,4, 2 and 1. Suppose you
want to set a high ATTACK value ( 12) and a low DECAY value (2). An easy way to
combine the two rates is to multiply the ATTACK value by 16 and add it to the
DECAY value. In this example, the resulting value is 194, i.e. 12*16+2. You can
use this formula whenever you wish to combine two values (range 0-15) into a
high/low nybble format.
Line 20 in the example program sets the ATTACK/DECAY rate to 0 ATTACK
and9 DECAY.
The maximum ATTACK rate is achieved by using a value of 15and multiplying
it by 16. You can increase the DECAY rate by adding together all the DECAY
values i.e. 8 + 4 + 2 + 1 = 15, which is the MAXIMUM DECAY RATE.
Here are some sample ATTACK/DECAY POKEs:
VOICE ATACK DECAY
POKE 54277,66 1 MED (64) LOW (2)
POKE 54284,100 2 MED (64) +
LOW (32) MED (4)
POKE 54291,15 3 ZERO MAX
(8+4+2+1)
POKE 54284,255 2 MAX MAX
(128+64+32+ 16 +8+4+2+1)
94
Here's a sample program that illustrates what you can do with attack/decay
settings:
10 FORL= 54272T054296:POKEL,0: N EXT... Clears the SID chip
20 POKE5429,15 ........................................... Set maximum volume
30 POKE54277,64 ........................................... Set attack/decay
40 POKE54273,162:POKE54272,37 ............... POKE one note in voice 1
5 PRINT"PRESS ANY KEY" ........................ Screen message
60 GETK$:IFK$= "'THEN60 ......................... Check the keyboard
70 POKE54276,17:FORT= H0200:NEXT ..... Start triangle waveform
80 POKE54276,16:FORT = H050:NEXT ....... Stop note
9 GOT050 ..................................................... Repeat execution
After you RUN the program a few times, tr changing the ATACKIDECAY
setting by changing line 30:
30 POKE 54277,190
Now RUN the program again and notice the difference in the note. Try other
combinations of attack and decay settings to get an idea of how you can use
different attack/decay rates to create a variety of sound effects.
SUSTAIN/RELEASE SETIING. Like ATACKIDECAY, SUSTAIN/RELEASE
share a byte. But remember that this sharing doesn't mean that SUSTAIN and
RELEASE are alike. SUSTAIN is a LEVEL, while release, attack and decay are
RATES.
SUSTAIN is a proportion of maximum volume. You can sustain, or hold,
notes and sounds at any of 16 volume levels.
This table shows you what numbers to POKE for sustain/release values:
HIGH MEDIUM LOW LOWEST HIGH MED. LOW LOWEST
SUSTAIN SUSTAIN SUSTAIN SUSTAIN RELEASE RELEASE RELEASE RELEASE
128 64 32 16 8 4 2 1
NOTE: You can increase the SUSTAIN level by adding together all the SUSTAIN
values: 128 + 64 + 32 + 16 = 240, which is the MAXIMUM SUSTAIN LEVEL. A
SUSTAIN level of 128 is approximately 50% of volume. You can increase the
RELEASE rate by adding together all the RELEASE values: 8 + 4 + 2 + 1 =
15, which is the MAXIMUM RELEASE RATE.
Combine the sustain level and release rate the same way you combine the at
tack and decay rates: add the two values and POKE the total to the memory
location of the voice you want.
To see the effects of the sustain level setting add this line to the last sample
program:
35 POKE 54278,128
Now RUN the program again and note the change. With line 35, we tell the
computer to sustain the note at a HIGH SUSTAIN LEVEL (128). You can vary the
duration of a note by changing the count in line 70. Remember that the sustain
level maintains a note at a proportion of the volume as the note falls from its
peak volume; this isn't the same thing as the note's duration.
To see the effect of the release rate, try changing line 35 to POKE 54278,89
(sustain = 80, release = 9).
95
SAMPLE SOUND PROGRAM
This brief sound program summarizes what you've learned so far about mak
ing music on your 64:
1. Choose the vOice(s) you want to use. Recall that each voice uses different
memor locations into which you'll POKE values for waveform, attack rate,
etc. You can play 1,2, or 3 voice together, but this program only uses voice 1.
2. Clear the SID chip: 5 FORL= 54272 TO 54296: POKEL,O:NEXT
3. Set VOLUME: 10 POKE54296,15
4. Set An ACKIDECA Y rates:
to define how fast a note rises
to and falls from its peak
volume level (0-255): 20 POKE54277,190
5. Set SUSTAIN/RELEASE to
define level to hold note and
rate to release it: 30 POKE54278,248
6. Find note you want to play in
the TABLE OF MUSICAL
NOTES in App. M and enter
the HIGH-FREQ. and LOW
FREQ. values for that note
(each note requires 2 POKEs): 40 POKE54273,16:POKE54272,195
7. Start WAVEFORM (here,
TRIANGLE): 50 POKE54276,17
8. Enter a timing loop to time be
tween notes (we use 250 for a
quarter note):
60 FORT = H0250:NEXT
9. STOP note by turning off
chosen waveform: 70 POKE54276,16
Here's a longer program that further demonstrates your 64's music-making
abilities:
NEW
5 REM MUSICAL SCALE ......................... .
7 FORL= 54272T054296:POKEL,0:NEXT clears SID chip
10 POKE 54296,15 ..................................... sets vol u me
20 POKE54277,7:POKE54278,133 ............ sets ad/s/r
50 READ A ................................................. READs 1 st number from line 110
55 IF A = - 1 THENEND ........................... ENDs loop
60 READ B .. ............................................... READs 2nd number
80 POKE54273,A:POKE54272,B ............... POKEs 1st number from line 110 as
HI-FREQ and 2nd number as LOW
FREQ.
85 POKE54276, 17 ...................................... starts note
90 FORT= H0250:NEXT:POKE54276,16 lets note play, then stops it
95 FORT = H050:NEXT . ..... ............... ...... sets time for RELEASE, time be-
tween notes
100 GOT020 .................... .......................... restarts program
110 DATA 16,195,18,209,21,31,22,96 ........ lists note value
120 DATA 25,30,28,49,31,165,33,135 .. ...... from chart in App. M. Each part of
numbers = one note (16 and 19 =
4th octave C)
999 DATA-1 ............................ ..... ............... ENDs program (see line 55)
96
You can change to a sawtooth wave by changing line 85 to read
POKE54276,33 and line 90 to read FORT = n0250:NEXT:POKE54276,32.
Changing the waveform can dramatically change the sound your computer
produces.
You can also change the sound in other ways. For example, you can change
the harpsichord-like sound in the previous program to a banjo-like sound by
changing the ATACKDECAY rate of each note. Do this by changing line 20 to
read:
20 POKE54277,3:POKE54278,0 . ..... . .. . ... ... creates banjo effect by setting zero
SUSTAIN
As this program demonstrates, your 64 can sound like a variety of musical il
struments.
97
PLAYING A SONG ON YOUR 64
The next program lets you play a line from a song, "Michael Row Your Boat
Ashore". The program uses the PULSE waveform, which is a variable width rec
tangular wave. The third and fourth POKEs in line 10 define the pulse width for
this song.
In this song, we use a duration COl"t of 125 for an eighth note, 250 for a
quarter note, 375 for a dotted quarter note, 500 for a half note, and 1000 for a
whole note. When you program your own songs, you can increase or decrease
these numbers to match a particular tempo or your own musical taste.
2 FORL= 54272T05429: POKEL,O: NEXT
5 S= 54272
10 POKES + 24,15: POKES + 5,88: POKES + 3,15: POKES + 2,15: POKES + 6,89
20 READH: IFH = -HHENEND
30 READL
40 READD
60 POKES + 1,H: POKES,L: POKES + 4,65
70 FORT = HOD: NEXT: POKES + 4,64
80 FORT = H050: NEXT
9 GOTO 20
100 DAT A33, 135,250,42,62,250,50,60,250,42,62, 125,50,60,250
105 DATA56,99,250
110 DA T A50,60,5oo,0,0, 125,42,62,250,50,60,250,56,99
115 DATA 1000,50,60,500
120 DATA-1
Line 2 clears the SID chip.
Line 5 assigns the lowest SID chip memory location to the variable S.
Throughout the rest of the program, we just add the number of the SID register
to this variable. For example, POKES + 24,15 POKEs 15 to the volume register,
which is 54296, or 54272 + 24.
Line 10 POKEs values into:
1. The volume register: POKES + 24,15
2. Voice 1, ATACKIDELAY rates: POKES + 5,88
3. Pulse width: POKES + 3,15 and POKES + 2,15
4. Voice 1, SUSTAIN level/RELEASE rate: POKES + 6,89
Line 20 READs the first number from the DATA statement. If that number is
- 1, the program ENDs automatically. This occurs when the final DATA state
ment (line 120) is read.
Line 30 READs the second number from the DATA list.
Line 40 READs the third number from the DATA list.
Line 60 POKEs:
1. The value for H that was assigned in the READH statement in line 20. Until
-1 is read, this value is assigned to the HIGH FREQUENCY register.
2. The value for L that was assigned in the READL statement in line 30. This
value is assigned to the LOW FREQUENCY register. Together these two
POKEs determine the pitch for one note.
3. The value that turns ON the variable pulse waveform for voice 1.
98
Line 70 uses a loop to set the duration for the note being played. The value
for D is assigned in the READ statement in line 40. As you can see, the numbers
in the DATA lists are clustered into threes: the first number (e.g., 35) is the high
frequency value for a note, the second number (e.g., 135 is the low frequency
value for the same note, and the third number (e.g., 250) sets the duration for
that note (e.g., a quarter note C).
Line 80 is a timing loop that determines release time between notes.
Line 90 sends the program back to READ the number set for another note.
Lines 100 through 120 contain all the DATA for the line from this song.
CREATING SOUND EFFECTS
Your 64's SID chip lets you create a wide variety of sound effects, such as an
explosion during a game, or a buzer that warns you when you've made a
mistake.
Here are just a few suggestions for creating sound effects:
1. Vary rapidly between two notes to create a tremor sound.
2. Use the multivoice effects to play more than one voice at a time, with each
voice independently controlled, so you have different noises at once. Or use
one voice as an echo or response to another voice.
3. Use the different pulse widths to create different sounds.
4. Use the NOISE WAVEFORM to make white noise to accent tonal sound ef
fects, create explosion nOises, gunshots, footsteps, or alarms. When you
use the noise waveform with the same musical notes that create music, you
can create different types of white noise.
5. Combine several HIGH/LOW FREQUENCIES in rapid succession across dif
ferent octaves.
6. Tr POKEing the extra note settings in Appendix M.
Here are some sample sound effects programs. The Commodore 64 Pro
grammer's Reference Guide contains more examples as well as more informa
tion on creating sound effects.
DOLL CRYING
NEW
5 FORL= 54272T054296:POKEL,0:NEXT ..... Clears SID chip
10 S = 54272:POKE 54275,15:POKE 54274,40
20 POKES + 24,15 .......................................... Sets volume
30 POKES + 4,65 ............................................ Turns ON pulse waveform in
voice 1
40 POKES + 5,15 .............................. .............. Sets attack/decay rate
50 FORX = 200T05STEP - 2 ......................... Sets timing loop for RELEASE or
time between notes
60 POKES + 1 ,40:POKES,X:N EXT ................. Sets hi/lo frequencies
70 FORX = 150T05STEP - 2 ......................... Sets faster timing loop
80 POKES + 1,40:POKES,X:NEXT ................. Sets hillo frequencies
90 POKES + 4,0 ........ ........................... ......... Turns OFF pulse waveform
99
SHOOTING
NEW
5 FORL= 54272T054296:POKEL,0:NEXT.. ... Clears SID chip
10 S= 54272
20 FORX= 15TOOSTEP-1 ........................... Sets up volume loop
30 POKES + 24,X ............................................ POKEs X to vol. register.
40 POKES+ 4,129 .......................................... Starts NOISE waveform
50 POKES+ 5,15 ............................................ Sets ATTACK/DECAY rate
60 POKES + 1,40 ............................................ Sets high frequency
70 POKES,2oo:NEXT ...................................... Sets low frequency
80 POKES + 4,128 .......................................... Stops NOISE waveform
90 POKES + 5,0 .............................................. POKEs 0 to attack/decay
100 GOT020 .... . . . . .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Repeats program
The loop that begins in line 20 sets up fading volume so that the sound of the
gunshot starts at high volume (15) and fades to 0 as the loops executes.
Press the RUN/STOP key to end this program.
As we've said before, the best way to learn a new area of programming is to
experiment.
Filtering
Sometimes a certain waveform may not have quite the timbre you require. For
example, it would be difficult to imagine any of the preset waveforms in the SI D
chip sounding anything like a trumpet. To give you additional control over the
sound parameters, the SID chip is equipped with three FILTERS.
HIGH-PASS FILTER. This filter reduces the level of frequencies below the
specified cutoff frequency. It passes all the frequencies at or above the cutoff.
while cutting down the frequencies below the cutoff.
LOW-PASS FILTER. As its name implies. this filter passes the frequencies
below the cutoff and reduces the level of those above.
BAND-PASS FILTER. This filter passes a narrow band of frequencies around
the cutoff and cuts down the level of all others.
An extra filter. called the NOTCH REJECT FILTER can be synthesized by
combining the high and low pass filters. This passes frequencies away from the
cutoff while reducing the level at the cutoff frequency.
Register 24 determines which filter type you want to use. Remember that this
is also the register used for the volume control. The following bits are used for
filters:
BIT No.
4
5
6
USAGE
SELECT LOW-PASS FILTER
SELECT BAND-PASS FILTER
SELECT HIGH-PASS FILTER
1 00
A filter is activated by setting the relevant bit in register 2 4.
You may not wish to filter all voices at the same time. Register 23 determines
which voices are to be filtered. The bits are as follows:
BITHo.
7 -4
3
2
1
o
USAGE
FILTER RESONANCE 0 -15
FILTER EXTERNAL INPUT
FILTER VOICE 3
FILTER VOICE 2
FILTER VOICE 1
When a speifc bit is set, the outut of that voice will b divered through the filter.
The cutoff frequency is an eleven bit number. The upper eight bits ( 11-3) are
stored in register 22 while the lower three bits (0 -2) are stored in register 2 1. This
gives you a range of values between 0 and 20 47 .
Try adding the following lines to the example program to filter the voice and
hear the difference in sound. We will be using a Low Pass filter which will allow
only the lower components of the sounds to be heard.
30 POKE S+2 4,31 :REM FULL VOLUME PLUS LOW PASS FILTER
35 POKE S + 23,1 :REM SELECT FILTER FOR VOICE 1
37 POKE S+22 ,128:POKE S+21,7:REM SELECT CUTOFF FREQUENCY
Try experimenting with filters. Filtering a sound as it passes through the ADSR
phases of its life can produce interesting effects.
For further information on how to use the SID chip, consult the COMMODORE
6 4 Programmer's Reference Guide.
MUSIC COMPOSER
The Commodore MUSIC COMPOSER carridge allows you to compose music
on your COMMODORE 6 without having to concern yourself with the workings
of the SID chip. Facilities are provided to allow you to type in program lines that
consist purely of special control characters. This enables you to play any
combination of sounds that you require using all the features of the SID chip.
Once you have composed your masterpiece, you can save it on tape and then
play it back at your leisure. While the music is playing, a music stave scrolls
across the screen displaying the notes as they are being played. This allows you
to get the most from the SID chip with the minimum of effor.
101
CHAPTER 9
ADVANCED DATA HANDLING
READ and DATA Statements
Calculating Averages
Subscripted Variables
Dimensioning Arrays
Simulated Dice Roll with Arrays
Two-dimensional Arrays
READ AND DATA STATEMENTS
SO far we've shown you how to assign values to variables directly (A = 2),
and how to assign values while the program is RUNning (INPUT and GET).
But often you'll find that neither way suits your needs for variable assign
ment in a program, especially when you have large amounts of data.
In the chapter 7 when we introduced sprites, we used READ and DATA
statements to assign values for sprites. Here
'
s a short program that shows you
how these two statements work together:
10 READ X
20 PRINT "X IS NOW :";X
3 GOTO 10
40 DATA 1, 34,10.5,16,234.5
RUN
X IS NOW: 1
X IS NOW: 34
X IS NOW: 10.5
X IS NOW: 16
X IS NOW: 234.5
?OUT OF DATA ERROR IN 10
READY
104
Line 10 READs a value from the DATA statement at line 40 and assigns the
value to X.
Line 30 tells the computer to return to line 10, where the READ assigns the
next value in the DATA statement to X. The loop continues until all the DATA
values are read.
There are a few important rules you must remember when you use DATA
statements:
Follow the DATA statement format precisely:
40 DATA 1, 34, 10.5, 16, 234.65
Comma separates each item
Use:
- integer numbers (e.g., 34),
- real numbers (e.g., 234.65),
- numbers expressed in scientific notation (e.g., 2.4E + 0),
- words (as long as you use a string variable in the READ statement),
but DON'T use:
- variables or
- arithmetic operations
in DATA statements. The items listed below are treated as strings if you try
to READ them, and you can only READ them as strings with string variables
in the READ statement.
DATA A, 23/56, 2*5, B + 2
When you use a READ statement, you can only get values from a DATA state
ment because the two statements work as partners. Each time you READ a
value, the computer knows to move to the next value in the DATA statement. In
effect, there's a pOinter in the computer that keeps track of your place in the
DATA statement. After READing the first value, the DATA statement looks like
this:
40 DATA 1,34, 10.5, 16, 34.56
t.
pOinter
When the last DATA value has been assigned to the variable in the READ
statement and the computer tries to execute the loop again, the OUT OF DATA
ERROR is displayed.
Here's an example that shows one way to avoid the OUT OF DATA ERROR.
NEW
10 FOR X = 1 to 3
15 READ A$
20 PRINT "A$ IS NOW: "; A$
30 NEXT
40 DATA THIS, IS, FUN
RUN
A$ IS NOW: THIS
A$ IS NOW: IS
A$ IS NOW: FUN
READY
105
This time we put the READ statement inside a FOR/NEXT loop that limited
the number of READings to equal the numbers of items in the DATA statement.
As long as you know how many items will be in your DATA statements, this
method is fine. But often either you won't know or you won't want to bother to
count.
Sometimes the best way to avoid an OUT OF DATA ERROR is to end your
DATA statement with a FLAG. A flag is some value that would not ordinarily ap
pear in your DATA list, such as a negative number, a very large number, a very
small number, or a special word, such as END or STOP. When you use a flag,
add an IFfHEN statement to tell the computer to branch to another part of the
program when the flag is read. For example:
10 READ A
15 IF A < 0 THEN END
20 DATA 13, 35, 29, -999
25 PRINT "TOTAL = " ; A
30 GOTO 10
This program READs and PRINTs a value for A until it reaches - 999. Line 15
tells the computer to END the program immediately when a negative value is
read.
There is also a way to reuse the items in a DATA statement by RESTOREing
the data pOinter to the beginning of the DATA list. Try adding this line:
45 RESTORE
to the second program in this chapter and RUN it again. You'll see that the data
pOinter has been RESTOREd to the first item in the DATA list, and that you can
reREAD all the items.
CALCULATING AVERAGES
Here's a program that READs a set of numbers from a DATA list and
calculates their average. This program also uses a flag to tell the computer
when to stop READing DATA.
NEW
5 T = 0 : CT = 0
10 READ X
20 IF X = -1 THEN 50: REM CHECK FOR FLAG
25 CT = CT + 1
30 T = T + X : REM UPDATE TOTAL
40 GOTO 10
50 PRINT "THERE WERE " ; CT;" VALUES READ"
60 PRINT "TOTAL = " ;T
70 PRINT "AVERAGE = " ; T/CT
80 DATA 75, 80, 62, 91, 87, 93, 78, - 1
RUN
THERE WERE 7 VALUES READ
TOTAL = 566
AVERAGE = 80.8571429
106
Line 5 sets CT, the CounTer, and T, the Total, to zero.
Line 10 READs a value from the DATA list and assigns it to X.
Line 20 checks to see if the value read to X is our flag (-1). If it is, then the
program skips lines 25-40 and goes straight to line 50.
Line 25 adds one to CT, the counter, if the value of X is not the flag.
Line 30 adds X to T, the running total.
Line 40 sends the program back to repeat line 10.
Line 50, which isn't executed until line 10 READs the flag, PRINTs the
number of values read (Cn.
Line 60 PRINTs the total of the numbers read m.
Line 70 PRINTs the average.
You can also use more than one variable in the READ statement. You can mix
the types of DATA in a DATA list when you also mix the types of variables in the
READ statement. Here's a program that does just that. It READs a name and
some scores and then calculates the average of the scores.
NEW
10 READ N$,A,B,C
20 PRINT N$"'S SCORES WERE "A" " B" " C
30 PRINT "AND THE AVERAGE IS:
'
'' ; iA + s + 6)/3
40 PRINT: GOTO 10
50 DATA MIKE, 190, 185, 165, DICK, 225, 245,190
60 DATA JOHN, 155, 185,205, PAUL, 160, 179, 187
RUN
MIKE'S SCORES WERE: 190 185 165
AND THE AVERAGE IS : 180
DICK'S SCORES WERE: 225 245 190
AND THE AVERAGE IS: 220
Line 10 READs a value for each of the variables. The DATA statement lists its
items in the same order that the READ statement expects to find them. In other
words, there's a name to go with the string variable, and numbers to go with the
integer variables.
107
SUBSCRIPTED VARIABLES
SO far we've only used simple BASIC variables such as X and X$ . It's doubtful
that you'll write a program that requires more variable names than all the com
binations of letters and numbers available in BASIC, but you might want to be
able to group variable names together when you're using groups of data.
Subscripted variables let you use variable names so that they are obviously
grouped together. For example:
A (0), A (1), A (2), A (3)
The numbers in parentheses are the SUBSCRIPTS of variable A. Be aware
that the variable A1 does NOT equal the subscripted variable A (1).
You can use variables and arithmetic operation as subscripts. For example:
A (X) A (X+1) A (4-1) A (2 *X)
The expressions within the parentheses are evaluated according to the same
rules for arithmetic operations outlined in Chapter 3.
Subscripted variables, like simple variables, name a memory location within
the computer. But only subscripted variables name values that are organized in
to an ARRAY.
An ARRAY is understood by the computer to be a unit, such as a list or a
table, of related values.
The following example uses subscripted variables to calculate an average:
5 PRINT CHR$(147)
10 INPUT "HOW MANY NUMBERS :";X
20 FOR A = 1 TO X
30 PRINT "ENTER VALUE # ";A;:INPUT B(A)
40 NEXT
50 SU = 0
60 FOR A = 1 TO X
70 SU = SU + B(A)
80 NEXT
90 PRINT : PRINT "AVERAGE = "; SU/X
RUN
HOW MANY NUMBERS:? 5
ENTER VALUE # 1 ? 125
ENTER VALUE # 2 ? 167
ENTER VALUE # 3 ? 189
ENTER VALUE # 4 ? 167
ENTER VALUE # 5 ? 158
AVERAGE = 161.2
108
Line 5 clears the screen.
Line 10 asks you to enter the total number of items you'll INPUT at line 30.
Line 20 sets up a loop that makes A the subscript for the array B. The loop
adds 1 to A for every execution. This updates array B.
Line 30 prompts you to INPUT a value for the subscripted variable B (A).
Lines 50 through 80 keep a running total (SU) of the numbers INPUT.
Line 90 PRINTs the average.
Each time the INPUT loop executes, A is increased by 1, so the next value
entered is assigned to the rext element in array B. At the end of the program, ar
ray B looks like this:
B (1) 125
B (2)
167
B (3) 189
B (4) 167
B (5) 158
After you INPUT all the values, they are stored in array B. You can now ac
cess these values just by using the subscripted variables. For example, see
what happens when you add these lines:
100 PRINT B (X -1)
120 PRINT B (3)
130 PRINT B (X-3)
DIMENSIONING ARRAYS
If you try to enter more than ten numbers in an array, you'll get a DIMENSION
ERROR. Arrays of more then ten elements need to be predefined in a DIMEN
SION statement. For example, if you want an array to hold 25 values, you'd write
this statement in your program:
DIM B (25)
You can also use a variable in a DIMension statement. For example, in the
last program you could have used this statement since X equaled the total
number of values in array B:
15 DIM B (X)
But be careful when you use variables to define arrays: once an array is
DIMensioned, it can't be reDIMensioned in another part of the program. So
don't use a variable whose value will change in the program.
You can use more than one array in a program, and you can DIMension them
all on the same line:
10
DIM A (12), B (35),
C (3
,
5)
Arrays A and B are one-dimensional arrays, but C is a two-dimensional array.
One-dimensional arrays just have ROWS of data, but two-dimensional arrays
have both rows and columns of data, just like a chart. Array C has 3 rows and 5
columns. Rows are always listed first in a DIMension statement.
109
SIMULATED DICE ROLL WITH ARRAYS
As you begin writing more complex programs, you'll find that subscripted
variables cut down on the number of statements and make programs simpler to
write.
For example, a single subscripted variable can keep track of the number of
times each f ace on a die turns up in a dice roll:
1 REM DICE SIMULATION : PRINT CHR$(147)
10 INPUT "HOW MANY ROLLS:";X
20 FOR L = 1 TO X
30 R = INT(6*RND(1))+ 1
40 F(R) = F(R) + 1
5 NEXT L
6 PRINT "FACE", "NUMBER OF TIMES"
70 FOR C = 1 TO 6 : PRINT C, F(C): NEXT
Line 10 asks you how many times you'll throw the dice iin the simulated roll.
Line 20 sets up a loop to count the number of dice rolls so that the program
ends on the Xth roll.
Line 30 makes R equal to the random number rolled.
Line 40 sets up the array F, for FACE, which keeps track of how many times
each face turns up. Whatever value R acquires in the dice roll becomes the
subscript for the array, and line 40 adds one to the appropriate array variable.
For example, every time a 2 is thrown, F (2) is increased by one.
Line 70 PRINTs the number of times each face shows up. Here's a sample
RUN:
HOW MANY ROLLS: ?
FACE
1
2
3
4
5
6
1 (
NUMBER OF TIMES
148
176
178
166
163
169
110
Now we'll show you how much longer your program would be if you didn't
use an array:
10 INPUT "HOW MANY ROLLS:"; X
20 FOR L = 1 TO X
30 R = INT(6*RND(1 ))+ 1
40 IF R = 1 THEN F1 = F1 + 1 : NEXT
41 IF R = 2 THEN F2 = F2 + 1 : NEXT
42 IF R = 3 THEN F3 = F3 + 1 : NEXT
43 IF R = 4 THEN F4 = F4 + 1 : NEXT
44 IF R = 5 THEN F5 = F5 + 1 : NEXT
45 IF R = 6 THEN F6 = F6 + 1 : NEXT
60 PRINT "FACE", "NUMBER OF TIMES"
70 PRINT 1, F1
71 PRINT 2, F2
72 PRINT 3, F3
73 PRINT 4, F4
74 PRINT 5, F5
75 PRINT 6, F6
As you can see, the program has twice as many lines. The longer the pro
gram, the more space and time you can save when you use arrays.
111
TWODIMENSIONAL ARRAYS
As we mentioned before, two
-
dimensional arrays have both rows and
columns, like a chart or a table. Two
-
dimensional arrays have two subscripts:
the first one is for the ROW number; the second is for the COLUMN number.
For example:
A (4,6) has 4 ROWS
and 6 COLUMNS
Here's what array A would look like as a twodimensional grid in memor:
o 2 3 4 5 6
o
2
3
4
You'll notice that there's a zeroth row and column, so when you DIMension A
(4,6), you're creating an array with 5 rows and 7 columns, or 35 elements.
You can access any element of a two
-
dimensional array by using its row and
column subscripts. For example, suppose you want to assign 255 to A (3,4):
o
2
3
4
10 LET A(3,4) = 255
Here's what the grid looks like now:
o 2 3 4 5 6
255
Twodimensional arrays follow the same rules as one-dimensional arrays:
DIMensioning:
Assigning data values:
Assigning values to
other values:
PRINTing values:
DIM A (20,20)
A(1,1) = 255
AS = A(1,1)
PRINT A(1,1)
112
Here's an example of how two-dimensional arrays can be used. This example
keeps track of responses to a club questionnaire like this:
CLUB QUESTIONNAIRE
Q1: ARE YOU IN FAVOR OF RESOLUTION #1?
1 - YES 2 - NO 3 - UNDECIDED
Let's suppose there are four questions, so the array, which we'll call A, will be
DIMensioned A(4,3). Here's how the array table looks:
QUESTION 1
QUESTION 2
QUESTION 3
QUESTION 4
YES NO UNDECIDED
The program that keeps track of the responses is on the next page. This pro
gram uses many of the programming techniques that have been presented so
far.
Lines 30'S PRINT the questions in numerical order and ask you to INPUT the
response.
Line 70 adds one to the appropriate array element. Remember that R is the
question number, and the questions are in rows. C is the response number, and
the responses are in columns.
Line 90 asks if you have another set of responses to INPUT.
Lines 110 and 120 tell the program where to go, depending on your response
to line 90.
Lines 130
-
170 PRINT the total number of each response.
Each time you INPUT a response at line 61, line 70 updates the right element
of the array. Recall the R is the question number and C is the response number,
so if your response to question 2 is 3 (undecided), line 70 adds one to array ele
ment A(2,3).
You'll notice that we didn't use the zeroth row and column in this example.
You don't have to use this row and column, but remember that they are always
present in every array you use.
113
20 PRINT "(SHIFT/CLR/HOME)"
30 FOR R = 1 TO 4
40 PRINT "QUESTION # : "; R
50 PRINT " 1
-
YES 2
-
NO 3
-
UNDECIDED"
60 PRINT "WHAT WAS THE RESPONSE: ";
61 GET C: IF C <1 or C> 3 THEN 61
65 PRINT C: PRINT
70 A(R,C) = A(R,C) + 1 : REM UPDATE ELEMENT
80 NEXT R
85 PRINT
90 PRINT "DO YOU WANT TO ENTER ANOTHER": PRINT
"RESPONSE (YIN)";
100 GET A$ : IF A$ = " " THEN 100
110 IF A$ = "Y" THEN 20
120 IFA$ <> "N" THEN 100
130 PRINT" (SHIFT/CLR/HOME) ";"THE TOTAL RESPONSES
WERE:":PRINT
140 PRINT SPC(18);"RESPONSE"
141 PRINT "QUESTION" ,"YES" ,"NO" ,"UNDECIDED"
142 PRINT
,,-------- ----------------------------
"
150 FOR R = 1 TO 4
160 PRINT R, A(R,1), A(R,2), A(R,3)
170 NEXT R
RUN
QUESTION #: 1
1
-
YES 2
-
NO 3
-
UNDECIDED
WHAT WAS THE RESPONSE: 1
QUESTION #: 2
1
-
YES 2
-
NO 3
-
UNDECIDED
WHAT WAS THE RESPONSE: 1
And so on . . .
THE TOTAL RESPONSES WERE:
QUESTION YES
1 6
2 5
3 7
4 2
RESPONSE
NO
1
2
0
4
114
UNDECIDED
0
0
0
1
APPENDI CES
INTRODUCTION
Now that you've gotten to know your 64, we want you to know that our
customer support does not stop here. You may not know it, but Commodore
has been in business for over 23 yers. In the 1 970's we introduced the first self
contained personal computer (the PET). We have since become the leading
computer company in many countries of the world. Our ability to design and
manufacture our own computer chips lets us bring you new and better personal
computers at prices way below what you'd expect for this level of technical
excellence.
Commodore is committed to supporting you, the end user. We also assist
you by supporting the dealer who sold you your computer, magaines that
publish hbw-to articles showing you new applications or techniques, and soft
ware developers who produce programs on cartridge and disk for use with your
computer. We encourage you to establish or join a Commodore "user club"
where you can learn new techniques, exchange ideas and share discoveries.
We publish two separate magazines which contain programming tips, informa
tion on new products and ideas for computer applications. (See Appendix N).
In North America, Commodore provides a "Commodore Information Net
work" on the CompuServe Information Serice. To use this network, all you
need is your 64 computer and our low cost VICMODEM telephone interface cart
ridge (or other compatible modem).
The following APPENDICES contain charts, tables, and other information
which help you program your COMMODORE 64 faster and more efficiently. They
also include important information on the wide variety of Commodore products
you may be interested in, and a bibliography listing of over 20 books and
magazines which can help you develop your programming skills and keep you
current on the latest information concerning your computer and peripherals.
1 1 6
APPENDlXA
EXPANDING YOUR COMMODORE 64 COMPUTER SYSTEM
The 6 is an extremely pwerful computer and one that can D used in a wide
variety of applications from word-processing to data base management.
The basic 64 computer system consists of the computer, a suitable television
set or monitor and a cassette unit on which to store your programs. For some
applications, the cassette unit can be somewhat slow. This limitation can be
overcome by using a disk unit to save and recall your programs.
Why USa Disk Drive?
If your programs or data files are very small, storing information on cassette
tape will not cause any great inconvenience. However, there will come a time
when the effective use of your system is restricted by the time it takes to load from
and/or save to tape. This is when you should be thinking about using a
Commodore disk unit.
THE VIC 1 541 DISK DRIVE
The VIC 1 541 disk drive allows you to store up to 144 programs or data files on
a standard 51/4 inch diskette. When using adisk drive, you no longer have to think
about re-winding tapes or worry about overwriting existing information. The
1 541 disk unit is an 'intelligent device', i.e. it does its own processing without
having to use any of the memory resources of the COMMODORE 64. Over
1 74000 characters of information can be stored on each diskette -the size of an
average Dickens' novel! The main advantage of a disk drive over a cassette unit
is speed. An operation on a disk drive is typically up to 40 times faster than the
same operation on cassette. The VIC 1 541 disk unit requires no special interface
-it plugs directly to your COMMODORE 64.
You are not restricted to using one disk drive. By connecting the units together
(called 'daisy-chaining') as many as five disk drives can be used with one
COMMODORE 6 so that you can load and save programs and files without
having to change diskettes.
VIC 1 525 DOT MATRIX PRINTER
A printer adds a great deal of versatility to your computer system. No computer
system is complete without one. It allows you to produce invoices, send letters,
or print out program listings so that you can examine your code away from the
computer. The VIC 1525 is a 'dot matrix' printer. This means that each character
is made up from a pattern of dots in a grid. You can print all the characters on your
COMMODORE 64 keyboard or print characters you have designed yourself. The
VIC 1525 prints at a speed of characters/second at 12 characters/inch on
plain tractor-feed paper up to 10 inches wide. The printer plugs directly into your
COMMODORE 64 and requires no additional interface.
VIC 1 526 BI-DIRECTIONAL DOT MATRIX PRINTER
The VIC 1526 printer differs from the VIC 1525 in two important respects. First,
it is a bi-directional printer. This means that the machine prints from right to left
as well as the conventional left to right. This means that the machine doesn't
waste time sending the printer head to the left edge of the paper every time a new
line of text is to be printed.
117
The second main difference between the 1 526 and 1 525 is in speed of
operation. The time taken to print each line is directly proporional to the width of
page you have set up. On an 80 column wide print out, the speed is 45 lines/
minute; on 40 columns, 78 lines/minute, and on 20 column wide paper, 1 24
lines/minute. The 1 526 allows you to print up to 3 copies of your output including
the original. It has a carridge ribbon for ease of interchange and accepts paper
up to 1 0 inches wide. The 1 526 plugs directly to your COMMODORE 64 -no
special interface is required.
VIC 1 520 PRINTER/PLOnER
The VIC 1 520 can be used both as a standard printer or as a plotter to allow
you to design and draw graphs, histograms, pie charts -in fact any shape you
like in a combination of four colors. You can print upper case/lower case letters
and graphics symbols. A further facility offered by the printer allows you to define
the size of each character you display. The printer prints at 1 4 characters/
second. Depending on the size of character selected, between 1 0 and 40
characters can be printed on each line of the paper. Characters can even be
printed . sideways
,
by rotating them 90 degrees. Shapes are drawn by simply
telling the printer/plotter where the start and end co-ordinates or the shape are
to be on the paper and what type of line you wish to use. These range from solid
lines to coarse, broken lines. The plotter is accurate to 0. 2 of a mm and has a
plotting speed of 60 mm/sec. The plotter uses small ball-point pens each of
which is user-selectable when plotting. The printer/plotter plugs directly into
your COMMODORE 64 and requires no additional interface.
1 701 COLOR MONITOR
A computer with the versatility of the COMMODORE 64 needs a medium on
which to demonstrate its capabilities to the full. The 1 701 color monitor has been
designed specifically for this purpose. The monitor has a 1 4 inch screen with
outstanding resolution. Sound can be generated either from the monitor's
internal speaker or, via a simple connection, from your Hi-Fi system.
1 31 1 JOYSTICK
A joystick can be used not only as a games controller but also, with suitable
software, as a tool for drawing and plotting. The COMMODORE 64
Programmer's Reference Guide gives detailed information on how to
incorporate the use of a joystick in your programs.
1 1 8
SOFTARE
A wide variety of software is available for the COMMODORE 64 covering
applications in the home, at work, entertainment and aids for the prorammer.
Software for Business and the Home
EASYFILE EFI 640 (diskette)
EASYFILE is a comprehensive data-base system for the COMMODORE 64. It
includes all the features of similar, highly-priced packages at a fraction of the
cost. The user decides how he wishes his information to appear when it is printed
out either on the screen or the printer. This means that EASYFILE can be tailored
to suit the needs of a wide variety of applications either in business or in the
home.
CLUB MANAGER CMG 6440 (diskette)
CLUB MANAGER has been designed to aid in the smooth running of sports
clubs, social clubs, associations - in fact any organization that needs to
maintain accurate membership records. The package allows you to record the
details of all the members of your club on diskette, much 8 records are stored
within a filing cabinet. Membership details can be amended where necessary
and records can be added to or deleted from the membership file. CLUB
MANAGER enables you to produce membership lists, subscription reminders,
address labels, and, because the package can be linked to te EASY SCRIPT
word processor, personalized copies of standard letters. CLUB MANAGER also
has a booking facility allowing you to enter details of when members wish to use
squash courts, tennis courts, snooker tables, restaurant tables, dance tickets or
any similar club facility or activity. Overbooking is now a thing of the past. CLUB
MANAGER allows you to maintain a diary and use it to record/amend details of
appointments, meetings, etc. CLUB MANAGER is an ideal tol for the club
owner or club secretary and will greatly reduce the amount of time spent on
maintaining membership records and booking club facilities.
FUTURE FINANCE FFI 6440 (diskette)
FUTURE FINANCE is a low-cost, financial planning package. It enables you to
predict your company's profit and cash-flow position based on expected
production, sales and costs. Details can be altered to view the effect of these
changes on the company's overall performance. Reports can be produced
showing the contribution to profits made by each product and the cash-flow
position at the end of each user-defined period.
EASYCALC ECL 6440 (diskette)
EASY CALC is an electronic spreadsheet package. It contains all the
traditional spreadsheet features - user-defined sheet size, replication of
information from one area of the sheet to the other etc. Allied to these facilities,
EASYCALC includes many other features including a library of trigonometrical,
statistical and other advanced mathematical functions, the ability to draw graphs
in a specific area of the sheet, data protection via a password option and much,
much more.
1 1 9
EASY STOCK EST 6440 (diskette)
EASY STOCK is a powerul inventory system containing a wide range of
stock-reording and reporting features. The details of each stock item are
entered directly from the keybard onto the screen and then stored on diskette.
EASY STOCK also allows you to change the price of an individual item or a range
of proucts on the stock file. Each stock record is accessed by simply typing in
the reference/part number of that item. Records can be amended, added to you r
stock file or deleted from it. If the amount of stock on hand falls below your
speified minimum level, the stock figure is highlighted when the record is
accessed. EASY STOCK allows you to produce a wide range of reports including
stock levels, analysis of stock movements, sales/stock valuation analyses and
much more.
EASY SCRIPT ESC 6440 (diskette)
EASY SCRIPT is a professional, low cost, word-processing package. It
enables you to create, modify and print text quickly and easily. EASY SCRIPT
can be use for writing letters, reports, memos, bok manuscripts -in fact any
kind of document. Text can be stored on diskette or cassette so that it may be
printed or modified as required.
#
EASY SPELL ESP 640 (diskette)
EASY SPELL is a spelling checker for files produced by the EASY SCRIPT
word processing package. It can be used to check text in individual EASY
SCRIPT files or text that is spread over files that have been linked together. The
EASY SPELL package comes complete with a dictionary diskette against which
the spelling of text is checked.
Ai ds for the Prorammer
To assist in the development of your own software, Commodore has
introduced a range of proramming utilities. These will help speed the entry and
debugging of BASIC and machine code programs.
SIMONS' BASIC SIB 641 0 (cartridge)
SIMONS' BASIC has been designed to enable programmers of all levels to
easily utilise the potential of their COMMODORE 64. The SIMONS' BASIC
cartridge is really three packages in one. It contains a Toolkit to remove the
tedious aspects of computer programming, a vast range of commands to
facilitate the use of graphics and sound on the 64 and Structured Programming
commands to help the prorammer write more meaningful coe. The package is
supplied in cartridge form which means that you can use all its features by simply
inserting it into the slot at the rear of the COMMODORE 64 and turning the
computer on - it's as simple as that. You then use the additional SIMONS'
BASIC commands just as you would any other BASIC commands.
Toolkit commands include:
AUTO -for automatic line numbering
RENUMBER - for automatic program re-numbering
KEY - to assign commands to the function keys
and many more.
1 20
Graphics commands include:
HIRES -to put the screen into high-resolution mode
REC -to draw a rectangular shape
CIRCLE - to draw a circular shape
PAINT - to fill a shape with color
plus commands for creating sprites and user-defined graphics:
DESIGN - to set up a design grid for a sprite or user-defined character
MMOB - to move a sprite
DETECT - to detect sprite collision
and much, much more.
The Structured-Programming commands supplied by the SIMONS' BASIC
cartridge are a boon to programmers of all levels of ability. It is now possible to
label BASIC routines and call these routines by name. Other structured
programming commands include:
PROC - to label BASIC routines
CALL - to pass execution to a routine
EXEC - to pass execution to a routine and return from it when
the routine has been completed
REPEAT ... UNTIL - to repeat a loop dependent on a condition test
and many others.
SIMONS' BASIC also includes commands for screen formatting, scrolling the
screen, input validation, character string manipulation, hexadecimal to decimal
and binary to decimal conversion, integer division and much
,
much more. The
cartridge also has a group of commands which allow you to trap certain BASIC
errors. You can even generate your own error messages! The range of
commands supplied by the SIMONS' BASIC cartridge make it an essential tool
for any programmer who wants to easily utilise the special features of his
COMMODORE 64.
Works with cassette or diskette.
ASSEMBLER TUTOR AST 6440 (diskette) AST 6420 (cassette)
The ASSEMBLER TUTOR package is a must for all would-be machine code
programmers. It can also be valuable to those programmers who already know
something about assembly language programming but wish to expand their
knowledge of 6502 machine code. The ASSEMBLER TUTOR is divided into
three modules. Each module covers one aspect of assembly-language
programming and contains an introduction, a self-test and discussion of various
aspects of assembly-language programming.
ASSEMBLER DEVELOPMENT ASM 6440 (diskette)
The ASSEMBLER DEVELOPMENT package allows you to program in
assembler directly onto your COMMODORE 64. It provides all the tools the
assembler programmer needs to create, assemble load and execute 6510
assembly language code.
121
PROGRAMMER'S UTILITIES UTL 6440 (diskette)
The PROGRAMMER'S UTILITIES package contains many useful routines to
help both the new and experienced programmer to get the most from his
COMMODORE 64. These include Disk-Handling routines for changing the
device number of a disk drive and copying disks using a single disk drive,
graphics utilities such as a sprite and character editor, sound commands and
BASIC proqramming aids for easier screen formatting and control operations.
ENTERTAINMENT
As well as a wide range of top quality arcade-style games for the COMMODOR E
64, Commodore have also produced a range of Business Simulation programs
for those who prefer to exercise their brain rather than their joystick fire button
finger. In these games, time is no restriction, only your capabilities to work out
complex scenarios.
LABYRINTH LBY 6420 (cassette)
Dare you enter the twisting Elizabethan maze? Will you ever get out, or will you
be trapped forever? LOST? Well you can take a quick peek at where you are but
remember that this reduces your score. Certainly a game to lose yourself in.
HIGH FLYER HFL 6440 (diskette)
It's 1945. The War has just ended and you have decided to run your own
airline. By making careful management decisions, you have to guide the
enterprise from 1945 up to the present day. The decisions are all yours -plane
schedules and routes; what is the best cargo/passenger ratio to maximise profit;
when is the best time to extend your fleet, make improvements to existing stock,
I:nhance support services; whether or not you need to borrow money from the
hank and which banks can offer you the best deal etc. You can save the position
you have reached until the next time you wish to join the high-flyers.
Available on diskette only.
RAIL BOSS RBO 6440 (diskette)
You are a pioneer railwayman in charge of building a line in the American West
between Base City and Junction City. It's your job to hire and fire surveyors,
workers and guards to protect you and your workforce against marauding
bandits. By building stations along the route, you can generate income to pay
your
'
workforce and buy additional stock should you require it. To thwart your
effors, warlike Indians try to disrupt your work by killing members of the
workforce and ripping up the track. Your only hope is that the cavalry from Fort
Commodore can get to the Indians before they get to you. A game for budding
pioneersmen everywhere.
122
OCEAN RACER OCR 6440 (diskette)
You have entered the round-the-world yacht race. The race starts from
Portsmouth and goes via Cape Town South Africa, Auckland New Zealand, Rio
de Janeiro in Brazil and, finally, back to Portsmouth. You choose the type of ship
you wish to captain: a single-masted cutter/sloop; a twin-masted ketch or a
single-masted multi-hull boat. The race is in four stages, each of which contains
various hazards ranging from icebergs to boat damage caused by passing
whales! You decide which route to sail and how much sail to select for the
prevailing wind conditions. A game for old salts and aspiring mariners alike.
These are just the first of a series of thinking games especially designed for the
COMMODORE 6. More are being developed all the time. For details of release
dates, please keep in close touch with your local Commodore stockist.
123
APPENDI X B
DESCRI PTI ON OF DOS ERROR MESSAGES
NOTE: Error message numbers less than 20 should be ignored with the excep
tion of 01 which gives information about the number of files scratched with the
SCRATCH command.
20: READ ERROR (block header not found)
The disk controller is unable to locate the header of the requested data
block. Caused by an illegal sector number, or the header has been
destroyed.
21 : READ ERROR (no sync character)
The disk controller is unable to detect a sync mark on the desired track.
Caused by misalignment of the read/writer head, no diskette is present, or
unformatted or improperly seated diskette. Can also indicate a hardware
failure.
22: READ ERROR (data block not present)
The disk controller has been requested to read or verify a data block that
was not properly written. This error message occurs in conjunction with
the BLOCK commands and indicates an il legal track and/or sector re
quest.
23: READ ERROR (checksum error in data block)
This error message indicates that there is an error in one or more of the
data bytes. The data has been read into the DOS memory, but the
checksum over the data is in error. This message may also indicate
grounding problems.
24: READ ERROR (byte decoding error)
The data or header as been read into the DOS memory, but a hardware er
ror has been created due to an invalid bit pattern in the data byte. This
message may also indicate grounding problems.
25: WRITE ERROR (write-verify error)
This message is generated if the controller detects a mismatch between
the written data and the data in the DOS memory.
26: WRITE PROTECT ON
This message is generated when the controller has been requested to
write a data block while the write protect switch is depressed. Typically,
this is caused by using a diskette with a write a protect tab over the
notch.
27: READ ERROR (checksum error in header)
The controller has detected an error in the header of the requested data
block. The block has not been read into the DOS memory. This message
may also indicate grounding problems.
124
28: WRITE ERROR (long data block)
The controller attempts to detect the sync mark of the next header after
writing a data block. If the sync mark does not appear within a pre
determined time, the error message is generated. The error is caused by a
bad diskette format (the data extends into the next block), or by hardware
failure.
29: DISK L MISMATCH
This message is generated when the controller has been requested to ac
cess a diskette which has not been initialized. The message can also oc
cur if a diskette has a bad header.
30: SYNTAX ERROR (general syntax)
The DOS cannot interpret the command sent to the command channel.
Typically, this is caused by an illegal number of file names, or patterns are
illegally used. For example, two file names may appear on the left side of
the COpy command.
31: SYNTAX ERROR (invalid command)
The DOS does not recognize the command. The command must start in
the first position.
32: SYNTAX ERROR (invalid command)
The command sent is longer than 58 characters.
33: SYNTAX ERROR (invalid file name)
Pattern matching is invalidly used in the OPEN or SAVE command.
34: SYNTAX ERROR (no file given)
The file name was left out of a command or the DOS does not recognize it
as such. Typically, a colon (:) has been left out of the command.
39 SYNTAX ERROR (invalid command)
This error may result if the command sent to command channel (secon
dary address 1 5) is unrecognized by the DOS.
50: RECORD NOT PRESENT
Result of disk reading past the last record through INPUT#, or GET# com
mands. This message will also occur after positioning to a record beyond
end of file in a relative file. If the intent is to expand the file by adding the
new record (with a PRINT# command), the error message may be ignored.
INPUT or GET should not be attempted after this error is detected without
first repositioning.
51 : OVERFLOW IN RECORD
PRINT# statement exceeds record boundary. Information is truncated.
Since the carriage return which is sent as a record terminator is counted
in the record size, this message will occur if the total characters in the
record (including the final carriage return) exceeds the defined size.
52: FILE TOO LARGE
Record position within a relative file indicates that disk overflow will
result.
1 25
60: WRITE FILE OPEN
This message is generated when a write file that has not been closed is
being opened for reading.
61 : FILE NOT OPEN
This message is generated when a file is being accessed that has not
been opened in the DOS. Sometimes, in this case, a message is not
generated; the request is simply ignored.
62: FILE NOT FOUND
The requested file does not exist on the indicated drive.
63: FILE EXISTS
The file name of the file being created already exists on the diskette.
64: FILE TYPE MISMATCH
The file type does not match the file type in the directory entry for the reo
quested file.
65: NO BLOCK
This message occurs in conjunction with the B-A command. It indicates
that the block to be allocated has been previously allocated. The
parameters indicate the track and sector available with the next highest
number. If the parameters are zero (0), then all blocks higher in number
are in use.
66: ILLEGAL TRACK AND SECTOR
The DOS has attempted to access a track or block which does not exist in
the format being used. This may indicate a problem reading the pOinter to
the next block.
67: ILLEGAL SYSTEM T OR S
This special error message indicates an illegal system track or sector.
70: NO CHANNEL (available)
The requested channel is not available, or all channels are in use. A max
imum of five sequential files may be opened at one time to the DOS.
Direct access channels may have six opened files.
71 : DIRECTORY ERROR
The BAM does not match the internal count. There is a problem in the
BAM allocation or the BAM has been overwritten in DOS memory. To cor
rect this problem, reinitialize the diskette to restore the BAM in memory.
Some active files may be terminated by the corrective action. NOTE:
BAM ^ Block Availability Map
72: DISK FULL
Either the blocks on the diskette are used or the directory is at its entr
limit. DISK FULL is sent when two blocks are available on the 1541 to
allow the current file to be closed.
126
73: DOS MI SMATCH (73, CBM DOS V2.6 1 541 )
DOS 1 and 2 are read compatible but not write compatible. Disks may be
i nterchangeably read with either DOS, but a disk formatted on one ver
sion cannot be written upon wi th the other version because the format is
different. This error is displayed whenever an attempt is made to write
upon a disk which has been formatted in a non-compatible format. (A uti l i
ty routine is avail abl e to assist in converting from one format to another.)
This message may also appear after power up.
74: DRIVE NOT READY
An attempt has been made to access the 1 541 singl e Drive Floppy Disk
without any diskettes present in either drive.
1 27
APPENDlXC
COMMODOREb4 BASlC
Thi s manual has gi ven you an i ntroduction to the BASIC languge -enough
for you to get a feel for computer programmi ng and some of the vocabul ary i n
volver. Thi s appendi x gives a compl ete l i st of the rules (SYNTAX) of 64 BASIC,
along with concise descri pti ons. Pl ease experiment wi th these commands.
Remember, you can't damage the computer by j ust typi ng i n programs, and the
best way to learn computi ng i s by experi menti ng.
Thi s appendix i s divided i nto secti ons accordi ng to the di fferent types of
operations i n BASIC. These i ncl ude:
1. Variables and Operators: descri bes the di fferent type of variables, legal
variable names, and arithmetic and logical operators.
2. Commands: descri bes the commands used to work wi th programs, such as
edi ti ng, storing, and erasi ng.
3. Statements: describes the BASIC program statements used i n numbered
l i nes of programs.
4. Functions: descri bes the stri ng, numeric, and pri nt functi ons.
VARIABLES
The 64 uses three types of variables i n BASIC. These are real numeric, i n
teger numeric, and stri ng (alphanumeri c) variables.
Variable names may consist of a si ngl e letter, a letter fol l owed by a number,
or two letters.
An i nteger variable i s specified by usi ng the percent (%) sign after the
variable name. String variables have the dol lar sign ($) after their name.
EXMPLES
Real Variable Names: A, A5, BZ
I nteger Variable Names: A%, A5%, BZ%
String Variable Names: A$, A5$, BZ$
ARRAYS are l i sts of variables with the same name, usi ng numbers cal led
subscripts to specify the element of the array. Arrays are defi ned usi ng the DI M
statement, and may contai n floati ng poi nt, i nteger, or stri ng variables. The array
variable name is fol l owed by a set of parentheses ( ) encl osi ng the number of
variables i n the l i st.
A(7), BZ%(1 1 ), A$(50), PT(20,20)
NOTE: There are three variable names whi ch are reserved for use by the 64,
and may not be defi ned by you. These variables are: ST, TI , and TI$. ST is a
status variable whi ch relates to i nput/output operati ons. The value of ST wi l l
change i f there i s a problem loadi ng a program from di sk or tape.
TI and TI$ are variables whi ch relate to the realti me clock bui l t i nto the 64.
The variable TI is updated ever 1 /60th of a second. It starts at 0 when the com
puter i s turned on, and i s reset only by changi ng the value of TI$.
1 28
TI$ i s a stri ng whi ch i s constantly updated by the system. The first two
characters contain the number of hours, the 3rd and 4th characters the number
of mi nutes, and the 5th and 6th characters are the number of seconds. Thi s
variable can be given any numeric value, and wi l l be updated from that poi nt.
TI $ ^ "1 01 530" sets the cl ock to 1 0: 1 5 and 30 seconds AM.
Thi s clock i s erased when the computer i s turned off, and starts at zero when
the system i s turned back on.
OPERATORS
The ari thmeti c operators i ncl ude the fol l owi ng si gns:
+ Addi ti on
- Subtracti on
Mul ti pl i cati on
Di vi si on
,
Rai si ng to a power (exponentiation)
On a l i ne contai ni ng more than one operator, there i s a set order i n whi ch
operati ons al ways occur. I f several operati ons are used together on the same
l i ne, the computer assi gns priorities as fol l ows: Fi rst, exponenti ati on. Next,
mul ti pl ication and di vi si on, and last, addi ti on and subtracti on.
You can change the order of operati ons by encl osi ng wi thi n parentheses the
cal cul ati on to be performed fi rst. Operati ons encl osed i n parentheses wi l l take
pl ace before other operati ons.
There are al so operati ons for equal i ti es and i nequal i ties:
^ Equal To
Less Than
` Greater Than
LND L
@
N L
AND A
@
N A
LXP L
@
L
A5C A @5 A g |N
NCNL |N
A1N A @1 A
j
|Ck |
@
C |
CHP| C H C
_
|kL |
@
k |
C|C5L C| @
C|
[
LT
@
L
C|k C @| C
j
LT# NCNL LT#
CND C
@
N c _ C5Ub C
@
5 Cg
CCNT C @C C
j
CTC
@
|
CLb NCNL CC5
l |
NCNL | |
DATA D @A D
_
| NPUT
NCNL l NPUT
DL| D
@
L D
| NPUT# |
@
N
D| N D @| D _ | NT NCNL l NT
1 41
Looks ke Looks ke
Com- Abbrev- fhs on Com- Abbrev-
fhs on
mond ofon screen mond
ofon
screen
LEFT$ LE
@
F LE
Q RI GHT$ R
@
I R E
LEN NONE LEN
RND R
@
N R
f
LET L
BI
E
L
U
RUN R
@ U
R Q
LI ST L
BI
I L t
SAVE S
@
A S
LOAD |
@ C
L
O
SGN S
BI
G S [
LOG NONE LOG
SI N S
@
I S
MI D$ M
BI
I
M E
SPC( S
@
P s
STR$ ST
@
R ST
Q
OR NONE OR SYS S "Y S
PEEK
p E
p E
TAB( T
E
A T
POKE
p
E
C
p O
TAN NONE TAN
POS NONE POS THEN T
@
H
PRI NT ? ? TI ME TI TI
PRI NT# P
B
R P b T I ME$ TI $ TI $
READ R
B
E R
E
USR . @ .
REM NONE REM
V
AL V Bl A V
RESTORE RE BS RE VERI FY V Bl
E . _
RETURN RE
@
T RE ] WAI T W
BI
A W
1 42
APPENDI X E
SCREEN DI SPLAY CODES
The fol l owi ng chart l i sts al l of the characters bui l t i nto the 64's character
sets. It shows whi ch numbers shoul d be POKEd i nto screen memor (locations
1 024-2023) to get a desi red character. Also shown i s which character cor
responds to a number PEEKed from t he screen.
Two character sets are avai lable, but onl y one set at a t i me. Thi s means that
you cannot have characters from one set on the screen at the same t i me you
have characters from the other set di splayed. The sets are switched by hol di ng
down the I and keys si mul taneously.
From BASIC, POKE 53272, 21 wi l l switch to upper case mode and POKE
53272,23 switches to lower case.
Any number on the char may also be di spl ayed in REVERSE. The reverse
character code may be obtained by addi ng 1 28 to the values shown.
I f you want to di spl ay a sol i d ci rcl e at location 1 504, POKE the code for the
ci rcl e (81 ) i nto locati on 1 504: POKE 1 504,81 .
There is a correspondi ng memory location to control the color of each
character di spl ayed on the screen (locations 55296-56295). To change the col or
of the ci rcl e to yellow (col or code 7) you woul d POKE the correspondi ng
memory location (55776) wi th the character color: POKE 55776,7.
Refer to Appendi x G for the compl ete screen and color memory maps, along
with color codes.
NOTE: The fol l owi ng POKEs di spl ay the same symbol in set 1 and 2: 1 , 27-64,
91 -93, 96-1 04, 1 06-1 21 , 1 23-127.
SCREEN CODES
SET 1 SET 2 POKE SET 1 SET 2 POKE SET 1 SET 2 POKE
@
0
C c 3 F
6
A a
L d 4 G
g
7
B b 2
E e 5
H h 8
1 43
8ET 1 8E 2 PKE 8ET 1 8E2 PKE 8E 1 8E 2 PKE
I 9
37
A 65
J 1 0
38
B 6
K k 1 1
39
C 67
L 1 2
%
68
M m 1 3
41
E 69
N n 1 4
42
.
F 70
0 D 1 5
+ 9
G 71
P
P
1 6
4
_
H 72
Q q 1 7
45
~
I 73
R 1 8
46
J 74
5 s 1 9
47
K 75
T 2
0
%
L
L 76
U u 21
49
M 77
V v 22
2 50
Z
N 78
W w 23
3
51
L 79
X x 24
4
52
80
Y
Y
25
5
53
Q 81
Z Z 26
6
.
R 82
27
7 55
5 83
L 28
8 56
T 84
29
9 57
U 85
i
30
58
V 86
+
31
59
L
W 87
32
<
60
X 88
33
61
Y 89
34
>
62
3
Z
P 35
? 63
91
$ 36
6
8
92
1 44
lE 1 lE Z PKE lE 1 lE Z PKE lE 1 lE Z M
J
93
1 05
1 1 7
T &
94
.
1 06
1 1 8
95
1 07
1 1 9
96
1 08
1 20
97
1 09
1 21
98
1 1 0
.
1 22
99
1 1 1
1 23
1 00
1 1 2
1 24
|
1 01
1 1 3
1 25
M
1 02
1 1 4
1 26
1 03
1 1 5
1 27
1 0
1 1 6
Codel from 1 28-255 are reversed Image. of code. 0-127.
1 45
APPENDI X F
ASCI I AN D CH R$ CODES
Thi s appendi x shows you what characters wi l l appear if you PRI NT CHR$(X),
for al l possi bl e values of X. It wi l l also show the values obtained by typi ng
PRI NT ASq"x"), where x i s any character you can type. Thi s i s useful i n
evaluati ng t he character received i n a GET statement, converti ng upperllower
case, and pri nti ng character based commands ( l i ke switch to upperllower case)
that coul d not be encl osed in quotes.
PRINTS CHR$ PRINTS CHR$ PRINTS CHR$ PRINTS CHR$
0
W
1 7 34 3 51
1 8
# 35 4 52
2
W
1 9 $ 36 5 53
3
20
?
/
?
37 6 54
4 21 38 7 55
5 22
39 8 56
6 23 40
9 57
7 24 41
58
DISABLES_t8
25 42
59
ENABLES . t
9
26 ~ 43 C 60
1 0 27 44 61
1 1
28 45
= 62
1 2
W
29 46
63
W
13
30 47
@
64
:
1 4
31 0 48
A 65
1 5
32 49 B 66
1 6 33 2 50 C 67
1 46
PRIN8 CHR PRIN8 CHR$ PRINT8 CHR PRIN8 CHR
_ 97
1 26
t0y ) 1 55
E 69
98
1 27
1 56
F 70
99
1 28
W
1 57
G 71
1 00 r0g0
1 29
1 58
H 72
1 01
130
1 59
I 73
1 02 131
1 60
J 74
1 03 132
8
1 61
K 75
1 04 f1 133
1 62
L 76
n
1 05 f3 134
1 63
M 77
1 06 f5 135
.
1 64
N 78
1 07 f7 136
|
1 65
0 79
L
1 08 f2 137
M
1 66
P 80
1 09 f4 138
1 67
Q 81
Z
1 1 0 f6 139
1 68
R 82
1 1 1 f8 1 40
1 69
5
83
1 1 2
_1 41
1 70
T 84
1 13 1 1 42
1 71
U 85
.
1 1 4 1 43
1 72
V 86 1 1 5
1 44
1 73
W 87
|
1 1 6
W
1 45
1 74
X 88
1 1 7
1 46
1 75
Y 89
1 1 8
W
1 47
d
1 76
Z
90
L 1 1 9
1 48
1 77
[
91
1 20 b|0w0 1 49
1 78
L
92
1 21
Ll. H00 1 50
1 79
1
93
1 22 |0y 1 1 51
l
1 80
i
94
1 23 |0y 1 52
1 81
. 95
8
1 24 Ll. |000 1 53
1 82
96
d
1 25 L!. b|00 1 54
1 83
|
T 4
PRIN8
CODES
CODES
CODE
CHW
1 84
1 85
PRIN8
.
n
1 92-223
224-254
255
CHR
1 86
1 87
PRIN8
~
SAME AS
SAME AS
SAME AS
1 48
CHW
1 88
1 89
PRlN
96-1 27
1 60-1 90
1 26
CHW
1 90
1 91
APPENDI X G
SCREEN AND COLOR MEMORY MAPS
The following charts list which memory locations control pl acing characters
on the screen, which locations are used to change individual character colors,
and they show character color codes.
SCREEN MEMORY MAP
|+
LLM
t+ s+ ss
|+ts
|+tt
| +tt
| |+t
| |tt
| | st
|ttt
|ttt
| s+t
|stt
| sst
|ttt
|ttt
| .+t
|.tt
|.st
|ttt
|ttt
|t+t
| ttt
|tst
|stt
|stt
|s+t
|stt
|sst
. .
t
/U/J
/U
/1
The actual values to POKE into a color memory location to change a
character's color are:
BLCK
1 WHITE
2 RED
3 CYAN
4 PURPLE
5 GREEN
6 BLUE
7 YELLOW
8 ORANGE
9 BROWN
1 0 Li ght RED
1 1 GRAY 1
1 2 GRAY 2
1 3 Li ght GREEN
14 Li ght BLUE
15 GRAY 3
1 49
For example, to change the color of a character located at the upper left-hand
corner of the screen to red, type: POKE 552,2.
|+
COLOR MEMORY MAP
LLM
t+ s: ss
..ss.
..
st
l=l
..sst
..stt
..|t
...t
..st
...st
...tt
..t|t
..t.t
..tst
..tst
..ttt
..t|t
..t.t
..tst
..sst
..stt
.t+| t
.t+.t
.t+st
.tist
.t|tt
.-t|t
.-t.t
1 50
!
.-t-.
|:
t:
t
APPENDI X H
DERIVI NG MATHEMATICAL FUNCTI ONS
Functions that are not i ntrinsic to 64 BASI C may be calculated as follows:
FUNCTION BASIC EQUIVALENT
SECANT SEqX) = lICOS(X)
COSECANT csqX) = 1/SI N(X)
COTANGENT COT(X) = 1 1T AN(X)
I NVERSE SI NE ARCSI N(X) = ATN(X/SQR( - x x + 1 ))
I NVERSE COSI NE ARCCOS(X) = - ATN(XISQR
( - X X+ 1 )) + J/2
I NVERSE SECANT ARCSEqX) = ATN(X/SQR(X X - 1 ))
I NVERSE COSECANT ARCCSqX) = ATN(X/SQR(X X- 1 ))
+ (SGN(X) - 1 J /2)
I NVERSE COTANGENT ARCOT(X) = ATN(X) + J /2
HYPERBOLIC SI NE SINH(X) = (EXP(X) - EXP( - X))/2
HYPERBOLIC COSI NE COSH(X) = (EXP(X) + EXP( - X))/2
HYPERBOLIC TANGENT TANH(X) = EXP( - X)/(EXp(x) + EXP
( - x))2 + 1
HYPERBOLIC SECANT SECH(X) = 21(EXP(X) + EXP( - X))
HYPERBOLIC COSECANT CSCH(X) = 21(EXP(X) - EXP( - X))
HYPERBOLIC COTANGENT COTH(X) = EXP( - X)(EXP(X)
- EXP( - X)) 2+ 1
I NVERSE HYPERBOLIC SI NE ARCSINH(X) = LOG(X + SQR(X X 1 ))
I NVERSE HYPERBOLIC COSI NE ARCCOSH(X) = LOG(X + SQR(X X - 1 ))
I NVERSE HYPERBOLIC TANGENT ARCTANH(X) = LOG((1 + X)/(1 - X))/2
I NVERSE HYPERBOLIC SECANT ARCSECH(X) = LOG((SQR
( - X X+ 1 ) + lIX)
I NVERSE HYPERBOLIC COSECANT ARCCSCH(X) = LOG((SGN(X)* SQR
(X X+ 1/x)
I NVERSE HYPERBOLIC COTANGENT ARCCOTH(X) = LOG((X+ 1 )/(X - 1 ))/2
1 51
APPENDI X I
PI NOUTS FOR I NPUT/OUTPUT DEVI CES
Thi s appendix is designed to show you what connections may be made to
the 64.
1 ) Game I/O
2) Cartridge Slot
3) AudioNideo
4) Serial I/O (Disk/Printer)
Control Po 1
Pin Ty
1 JOYAO
2 JOYA1
3 JOYA2
4 JOYA3
5 POT AY
6 BUTTON ALP
7 + 5V
8 GND
9 POT P
1
2 3 4
b
O O O O O
O O
O O
Control Port 2
Pin Type
1 JOYBO
2 JOYB1
3 JOYB2
4 JOYB3
5 POT BY
6 BUTTON B
7 + 5V
8 GND
9 POT BX
5) Modular Output
6) Cassette
7) User Port
Note
MAX. 1 00mA
Note
MAX. 1 00mA
1 52
Carridge Expansion Slot
Cartridge Expansion Slot
Pin Type Pin Type
1 GND 1 2 BA
2 + 5V 1 3 DMA
3 + 5V 1 4 CD7
4 I RQ 1 5 CD6
5
CAI 1 6 CD5
6 Dot Clock 1 7 CD4
7 I/O 1 1 8 CD3
8 GAME 1 9 CD2
9 EXROM 20 CD1
10 I /O 2 21 CDO
1 1
ROML 22 GND
Pin Type Pin Type
A GND N CA9
B
ROMH P CA8
C
RESET R CA7
D
NMI S CA6
E S 02 T CA5
F CA1 5
U CA4
H CA1 4 V C
A
3
J
CA1 3
W CA2
K
CA1 2 X CA1
L CA1 1 Y CAO
M CA1 0 Z GND
2221 < \ V1 1 7 \ \ \ 41 3\ 2 \ 10 9 7 4 $ ? 1
I :::: :: :::::: : I
] Y X W V Q T S H P N M L K J H F L D A
AudiolVideo
Fin 1
P
NoIe
LUM| NANC|
2 GN0
3 AU0| O OUT
V| 0|O OUT
5 AU0| O | N
Cassette
Fin
1
P
A- I GN0
T Z 4 0 0
8-2 +5V
C-3 CA55|TT| MOTOR
::::::
0- CA55|TT| R|A0
P L
|-5 CA55|TT| WR| T|
F- CA55|TT| 5|N5|
1 53
Serial I/O
Pin Type
1 SERI AL SRQI N
2 GND
3 SERI AL ATN I N/OUT
4 SERI AL ClK I N/OUT
5 SERI AL DATA I N/OUT
6 RESET
User I/O
Pin Type Note
1 GND
2 + 5V MAX. 1 00mA
3 RESET
4 CNTI
5 SP1
6 CNT2
7 SP2
8 PC2
9 SER. ATN I N
1 0 9 VAC MAX. 1 00mA
1 1 9 VAC MAX. 1 00mA
1 2 GND
Pin Type Note
A GND
B FLAG2
C PBO
D PB1
E PB2
F PB3
H PB4
J PB5
K PB6
l PB7
M PA2
N GND
1 Z 3 4 5 6 I 8 9 1 1 1 1 Z
::::::::::::
C L L M J F L N M
1 54
APPENDIX J
PROGRAMS TO TRY
We've i ncl uded a number of useful programs for you to try wi th your .
These programs wi l l prove both entertai ni ng and useful .
1 00 pr i n t " Pj ot t o j i M butt . rf i E l d "
1 2 0 i nput " Pwant i nstruc t i on5 " i z ' : i fasc ( z S ) -78got02O
1 3 0 pr i n t " Ptry to guss tht Mysttry 5 - 1 Et t.r word"
1 40 pr i nt " l\jou Must guoss o n l
'
l og a l 5-1 . tttr"
1 50 pr i n t " words , too "
1 60 pr i n t " you w i l l bE to l d tho numb . r o f Matc hts"
1 7 0 pr i nt " ( or ' j ot s ' ) o f your guoss
.
"
1 8 0 pr i n t " !h i nt : th . tr i c k i s to lar' s l i gh t l y"
1 9 0 pr i nt " fro. ont gUE S S to thE n . x t ; so that "
200 pr i n t " i f you qUE55 ' bat c h ' a n d gEt 2 j ot s "
2 1 0 pr i nt " you M i gh t try ' botc h ' o r ' c h ar t ' "
220 pr i nt " for th . nt>: t gUEs s "
250 data bxbs f , i pc c z , dbd i f , tsfbt , pqgb.
260 data hpshf , i bud i , dj w j M , k pMMz , l b z b l
2 7 0 data s bk b i , .f wf M , n j n j d , boofy , q j qf s
2 8 0 d a t a rlftu , s j wf s , qs f t t , puuf s , fwfou
290 data xfbwf , fyupM , nlt i z , af c sb , gj aaz
300 data u i j d l , . slo l , gMpp . , uj hf s , gb l f s
3 1 b data c ppu i , Mz j oh , trlbu , hblaf , px j oh
320 data u i s f f , tj h i u , bYMf t , hslnq , bs f ob
330 data rlbsu , ds f f q , c fMd i , qs f t t , tqbsl
340 data sb . bs , slsb. , tnfMM , gspXO , oS j gu
400 n-50
41 0 d i M nS ( n f , z ( 5 ) , y ( 5 )
420 for j - l ton : r . adnS ( j ) : n txtj
430 t = t i
440 t = t /l 000 : i f t > = l t hEngot0440
450 z-rnd ( - t )
500 g-O : nS-nS ( rnd ( l ) *n + l )
5 1 0 pr i nt " ! i hal" a f i lE l EttEr word : " : i f r>Ogot0 560
520 pr i nt
o
guess ( w i tt, l E, a l words ) "
530 pr i nt " and i ' l l t . l l 'jOU how Many"
540 pr i nt ' ' ' j ot s ' , or Mat c h i ng l Etters , "
550 pr i nt " IJOll hav l
.
l1
560 g= g+ l : i nput " 'Jour word " ; z S
570 i f \. n ( z S ) < >5thEnpr i nt " 'jou Must 'J UESS a
5 - 1 etttr word '
" : got0560
580 I=O : h=O : II = O
590 for j = l t 05
600 z = asc ( M i dS ( z S , j , l : y-asc ( III i dS ( nS , j , l - I : i f y= 64 t htny=90
6 1 0 i f z<650rz>90th . npr i nt " that ' s not a word ! " : ,] o t0560
620 i f z=650rz= 690rz = 730rz-790rz=850rz=89th . nl=l+ l
630 i f z =yth . n,. -.+1
640 z I = z : 'j t ) = 'j : n . :{ t j
650 i fm= Sgot 0800
660 i f l=00rl=5th . npr i nt" C 0"1 . on wt, at k i nd of
a word i s tt, a t 7 " : got0560
670 f or j - l t 05 : y= Y ( j )
680 for k = l t 0 5 : i f y= z ( k ) thenh=h+ l : z ( k ) = 0 : qot0700
690 n . xt k
-
700 nExt
7 1 0 pr I n t " 00000b0b0000000000" M ' J01 $ `
7 20 i fg< 30got0560
730 ' r i nt " i ' d . b . ttEr t . l l you word w a s
T CC
740 forj = l to5 :r i ntchrt ( y ( j i : nxtj
750 pr nt " '
'
' : goto8 1 0
800 pr i nt " 'jou got i t i n on l 'j " i g i " 'USS" s . "
8 1 0 i nputl l tanother word" ; zt
820 r = l : i f a sc ( zt ) < > 78goto500
2
3
4
6
rllI
fEl
rlfl
rlfI
rtm
reff
7 re:t
+ + +
+ + +
+ + +
+ + +
+ + +
S
E
DUEne E
Ifoi,i
P
Et us ' r group
s o f twar" t }: c ha n
'
.;1?
po loo:-, 3 7 1
Montgof'l lrl. v i l l ' , pa
50 d i ,. a t ( 26 )
1 8936
1 00 zt= " a|c def qh i jk l mnopqfst uvw;: uz "
1 1 0 z l t = " 1 234 567 89 0 1 2 3 4 567890 1 2 3 4 56"
20U r.r i n t " t0. nt'r l ngtt, of s t r i ng to bE s"QuEne Edt"
220 nr ut li Ma>: i NUh\ I tnqth i s 2 6
t
t 5 7
230 i f s Z( 1 Of 5Z>26 t h .. n 200
240 5 =s 7
300 f or i = l to 5
3 1 0 a $ ( i ) =m i d$ ( z $ . i . 1 )
320 n . ;.: t i
400 r"m random i z " s t r i ng
420 for i = l to s
4 30 k = i nt ( r n d ( I ) E s + 1 )
4 4 0 U=a$ ( i )
450 a $ ( i ) = a $ ( |
460 a$ ( U= U
4 70 n">: t i
4 e O g05ub 950
bb t=O
600 rt? m rt vt? rst sut' s t r i ng
605 t = t + 1
6 1 0 i nput " how ti an to r' vrse
:
r I
620 i f r7= O go to 9 00
630 i f rZ > O and r Z < = s go t o 650
640 c'r i nt I ' must bl? bt t w ttn 1 and " ; 5 :
'
.: ot o 6 1 0
6 5 0 r= i nt ( r 7/2 )
660 for i = 1 to r
6 7 0 t $ = a $ ( i )
680 a $ ( i ) = a $ ( r7 - i + l )
6'0 a $ ( r Z - i + 1 ) = t. $
700 n" ,, t i
750 . osut. v5U
800 e = l : for | - 2 O S
8 1 0 i f a $ ( i l > a $ ( i - I ) goto 830
820 e = O
8 3 0 n}: t l
840 i f e = O goto 600
850 [)r i nt " fI O U d i d i t i n I ' ; t ; 1 1 tr i e s "
9 0 0 r ' m e h'e k f o r anoth.r gam"
9 1 0 i nr. ut " Iwant to ro l a ll aga i n " ; y$
9'0 i f l "f t $ ( ') $ , I ) = " ' " or ' $ = " () k " or ') $ =
t
1 " goto 200
930 End
950 pr i nt
960 pr i nt l E f t $ ( z l $ , 5 )
970 for i = 1 to S I pr i nt a $ ( i ) ; : n' >: t i
0 rr | nt " I ' '
990 r ' turn
Ia
` t |L. .
..L = ' ` !.
`
l.' L'r`L I-OGF- -L T` `
,'L L = TOLEt l (f : l :
'
1 `. ' . I1`: L '.| 1 L4
. ' ' = t |.
.L ` ' _
CL m=L L=L t ,L= t L=. t ,'=,|+ \ c +L 1 m'=m* c+|L
'= | : =L ; |'1 = l t 'L=
'
t =, :
acL ! =Lla t ||L.++ * - l* c+LL t !LC+c+ ^ -.' +L
aL ! L`z +a+ * LL|!Lt L.L'z +.+ J +7 LLL.
` ,c : t'IE: : T
<<L LLC+a . t L|+ C+ t |LL:+a. ~
.LL LL| : I m4= ' L.`LL
L = m' m . ' .
'
| t ='^ t l=`++ t =L|LL
<L L|L.+c+. Z : REM | . LLL ''
.: LL': +- . Z :h'Ll'l I| 1 ; m
LL
.='L F' OKECP . ;' t L|L|' . L 1 ' L! .. L
.L L|L.+~ m9 .mb' L| ,L LL
.L |` L|L.+ 1 + - l L t L ,L
.CL L|L,++.'' : L 'L LLL ,L.
.c LIL.++ - m' : |L L m.L}
. +' POKECP ` .+ t l|' T|L*|T t !L..
, POKECP . WV : REM |LL.L
:L =l L|`='+ : r'=.L|'=L
4|0 !JOTO: : OO
LL lm4= ` q'TL l1= t LL= LLJL.'L
L m4= ` @' mL H \, : LL=. : !L!|.' LL
.' m=' | L|l`1=| : OC=2 t ' LL' |L
L I m4= ' ['L|H'1=z t ':' C. 1 : C OTO:;: (tI)
L I m4. " Ll =L .v1`=1 : 1:; OTO'":(tO
L |4=' @' ' I[I!=l t l' =,:*
cL |4= ' ` @` TrLl
--
eo
~
o
o
~~
......~....= ~.~
= .
1 69
APPENDlXw
COMMODORE64
5OUNDCONTROLSETTlNGS
Thi s handy table gives you the key numbers you need to use i n your sound
programs, accordi ng to which of the 64's 3 voices you want to use. To set or ad
just a sound control in your BASIC program, just POKE the number from the se
cond column, followed by a comma (,) and a number from the chart . . . l i ke thi s:
POKE 5276,1 7 (Selects a Triangle Waveform for VOICE 1).
Remember that you must set the VOLUME before you can generate sound.
POKE5429 fol lowed by a number up to 15 to set the vol ume for all 3 voices.
I t takes 2 separate POKEs to generate each musical note. For example
POKE54273,33:POKE54272, 1 35 desi gnates low C in the sample scale below.
Also, you aren't l i mited to the numbrs shown in the tables. I f 33 doesn't
sound "right" for a low C, tr .To provi de a hi gher SUSTAI N or ATACK rate
than those shown, add two or more SUSTAI N numbers together. (Examples:
POKE54277,9 combi nes two attack rates (32 and 64) for a combi ned hi gher at
tack rate, POKE5277,20 provides a low attack rate (16) and a medi um decay
rate (4).
1 70
8ETlNG YOLUME 8AME FOH ALL 3 YOICE8
VOLUME CONTROL |POKE52Settings range from L (off) to 15 (loudest)
VOICENUMBER1
TO CONTROL PKE THIS
THIS SETING: NUMBER:
TO PLY A NOTE
HIGH FREQUENCY 5273
LOW FREQUENCY 5272
WAVEFORM PKE
5276
PULSE RATE (Pulse Waveform)
HI PULSE 5275
LO PULSE 5274
ATIACKIDECAY PKE
5277
SUSTAIN/RELEASE PKE
5278
VOICE NUMBER2
TO PLAY A NOTE
HI GH FREQUENCY 528
LOW FREQUENCY 5279
WAVEFORM POKE
528
PULSE RATE (Pulse Waveform)
HI PULSE 5282
LO PULSE 5281
ATIACKDECAY PKE
526
SUSTAIN/RELEASE PKE
528
VOICENUMBER3
TO PLY A NOTE
HIGH FREQUENCY 5287
LOW FREQUENCY 528
WAVEFORM POKE
52
PULSE RATE (Pulse Waveform)
HI PULSE 5289
LO PULSE 528
ATACKDECAY POKE
521
SUSTAIN/RELEASE PKE
522
FOLLOWED BY ONE OF THESE NUMBERS
(0 to 15 . . . or . . . 0 to 255 depnding on range)
C G D E F F. G A A. B
35 37 39 42 4 47 b M
135 1 3 162 223 b 193 107 57 19 75
TRIANGLE SAWOOTH PULSE NOISE
17 65 12
A value of 0 to 15 (for Pulse waveform only)
A value of 0 to 255 (for Pulse waveform only)
ATK4 ATK3 ATK ArKl DEC4 DEC3 DEC2 DEC 1
128 6 32 16 8 4 2 1
SUS4 SUS3 SUS2 SUSI REL4 REL3 REL REL1
128 6 32 16 8 4 2 1
C G D E F F. G G. A A. B
35 37 39 42 44 47 53 M 59 63
1 35 13 162 223 62 193 107 57 19 75
TRIANGLE SAWOOTH
PULSE NOISE
17
65 12
A value of 0 to 15 (for PuiS waveform only)
A value of 0 to 255 (for Pulse waveform only)
ATK4 ATK3 ATK2 ATKI DEC4 DEC3 DEC2 DECI
128 6 32 16 8 4 2 1
SUS4 SUS3 SUS2 SUSI REL4 REL3 REL REL1
128 6 32 16 8 4 2 1
C G D E F F. G G. A A. B
35 37 39 42 4 47 O M 59 b
135 13 162 223 62 193 107 57 19 75
TRIANGLE SAWTOOTH PULSE NOISE
17 65
A value of to 15 (for Pulse waveform only)
A value of 0 to 255 (for Pulse wavefor only)
ATK4 ATK3
128 6
SUS4 _SUS3
128 6
1 71
ATK2 ATKI
32 16
SUS2 SUSI
32 16
DEC4 DEC3 DEC2
8 4 2
REL4 REL3 REL
8 4 2
12
DECI
1
RELI
1
TRY THESE SETINGS TO SIMULTE DIFFERENT INSTRUMENTS
Instrment Wavefon
Piano Pulse
Flute Triangle
Harpsichord Sawtooth
Xylophone Triangle
Organ Triangle
Col l iape Triangle
Accordian Triangle
Trumpt Sawtooth
MEANI NGS OF SOUND TERMS
ADSR - Attack/Decay/Sustain/Release
Attack - rate sound rises to peak volume
AttackDeay
9
9
9
9
0
0
102
9
Decay - rate sound falls from peak volume to sustain level
Sustain - prolong rate at certain volume level
Release - rate at which volume falls from sustain level
Waveform - "shape" of sound wave
Pulse - tone quality of Pulse Waveform
Sustain/Release Pulse Rate
0 Hi-. Lo-255
0 Not applicable
0 Not applicable
0 Not applicable
240 Not applicable
240 Not applicable
0 Not applicable
0 Not applicable
NOTE: Attack/Decay and Sustain/Release settings should always b POKEd i n your program BEFORE
the Waveform i s POKEd.
1 72
APPENDI X R
6581 SOUND I NTERFACE DEVI CE (SI D)
CHI P SPECI FI CATI ONS
CONCEPT
The 6581 Sound I nterface Devi ce (SI D) is a si ngle-chi p, 3-voi ce el ectroni c
musi c synthesi zer/sound effects generator compat i bl e wi t h t he 651 0 and
si mi lar mi croprocessor fami l ies. SI D provi des wi de-range hi gh-resol uti on con
trol of pitch (frequency), tone color (harmoni c content), and dynamics (vol ume).
Special ized control ci rcui try mi ni mizes software overhead, faci l i tati ng use in ar
cade/home video games and low-cost musi cal i nstruments.
FEATURES
3 TONE OSCI LLATORS
Range: 0-4 kHz
4 WAVEFORMS PER OSCI LLATOR
Triangl e, Sawtooth,
Variable Pul se, Noi se
3 AMPLI TUDE MODULATORS
Range: 48 dB
3 ENVELOPE GENERATORS
Exponential response
Attack Rate: 2 ms-B s
Decay Rate: 6 ms-24 s
Sustain Level: O-peak volume
Release Rate: 6 ms24 s
OSCI LLATOR SYNCHRONIZATI ON
RI NG MODULATION
DESCRI PTION
The 6581 consists of three synthesizer "voices" whi ch can be used i n
dependentl y or in conjuncti on wi th each other (or external audi o sources) to
create compl ex sounds. Each voice consists of a Tone Osci l i atorlWaveform
Generator, an Envelope Generator and an Ampl i tude Modulator. The Tone
Osci l lator controls the pitch of the voice over a wide range. The Osci l lator pro
duces four waveforms at the selected frequency, with the uni que harmoni c con
tent of each waveform provi di ng si mpl e control of tone color. The vol ume
dynamics of the osci l lator are controlled by the Ampl i tude Modul ator under the
di rection of the Envelope Generator. When triggered, the Envelope Generator
creates an ampl i tude envelope with programmable rates of i ncreasi ng and
decreasi ng vol ume. In addi ti on to the three voices, a programmable Fi l ter is pro
vided for generati ng complex, dynamic tone col ors via subtractive syntheses.
SI D al l ows the mi croprocessor to read the changi ng output of the thi rd
Osci l lator and thi rd Envelope Generator. These outputs can be used as a
source of modulation information for creati ng vi brato, frequency/fi l ter sweeps
and si mi l ar effects. The thi rd osci l lator can also act as a random number
generator for games. Two AID converters are provided for i nterfaci ng SID wi th
potentiometers. These can be used for "paddles" i n a game environment or as
front panel controls i n a musi c synthesizer. SI D can process external audio
signals, allowing mul ti pl e SID chi ps to be daisychained or mi xed i n complex
polyphonic systems.
1 73
ADDRESS REG #
A, A, A, A, A
O
IHEX) Dy D
0 0 0 0 0 00
0 0 01
!--
F
,
F" F, .
02
03
W,
'6
04 NOISE O
05
06
ATK)
'
STN) STN2
0
, F F.
08 F" F, .
09 PW, PW.
\0 0A
. .
\ \ 0B NOISE O
\2 OC
ATK) ATK2
\@ 00
STN
J
_
STN,
^
\4 OE F, F.
\5 OF F" F, .
1
'0 PW, PW.
\ / ! \
.
\8 ! 2 NOISE O
\9 ! 3
ATK) ATK2
20
\4
STN2
2
\5
.
22
\ ~e
FCg
23
\ Z
RES, RES2
24
\ 8
3 OFF HP
25
\9 PX, PX.
2
lA PY, PY.
2Z 1 B O O.
28
1 C E, E.
F,
F"
PW,
.
-
ATK,
STN,
F"
PW,
~
ATK,
STN,
F,
F"
PW,
~
ATK,
STN,
.
FC.
RES,
BP
PX,
PY,
O
E,
DATA
D4 03
F. |
F" F"
PW. PW,
.
PW
1 1
Z TEST
ATK DCY,
STNO RLS,
F, F,
F" F"
PW. PW,
PW
1 1
Z TEST
ATKo DCY)
STN
O
RLSJ
F. F,
F" F"
PW, PW,
PW
1 1
Z TEST
ATKa DCY,
STNo ALS,
. .
FC, FC.
RESo FlLTEX
LP VOL,
PX. PX,
PY, PY,
O. O_
E. E,
0,
D
F, F, F
e
F-- Fg F.
PW, PW
^
o
e g
.
SYNC GATE
DCY, DCY, DCYO
RLS2 RlS, ALSO
F, F,
F
l
O Fg F.
PW, PW, PW
e
PW,o PWg
'8
SYNC GATE
DCY, DCY, oeyo
ALS, RlS, RLSo
F, F, Fo
F
lO
Fg F.
PW, PWo
e
PWg PW.
:
SYNC GATE
DCY, DCY, DCYo
ALS2 RlS, ALSo
FC, FC, FCo
FC, FC, FC,
F|L1 3 FI Ll 2 FI Ll \
VOL2 VOL, VOla
PX, PX, PXo
PY, PY, PYo
O_ O O
0
E, E, Eo
REG NAME REG
Voce 1
TYPE
FRED LO WRITEONlY
FREO HI WRITEONLY
PW LO WRITEONLY
PW HI WRITEONLY
CONTROL REG WRITEONLY
ATT ACKIDECA Y WRITE-ONLY
SUSTAIN/RELEASE WRITEONLY
VoIce2
FRED LO WRITEONLY
FRED HI WRITEONLY
PW LO WRITEONLY
PW HI WRITEONLY
CONTROL REG WRITEONLY
ATT ACKIDECAY WRITEONLY
SUSTAIN/RELEASE WRITEONLY
Voice 3
FREO LO WRITEONlY
FREO HI WRITEONLY
PW LO WRITEONLY
PW HI WRITEONLY
CONTROL REG WRITEONLY
ATT ACK/DECA Y WRITE-ONLY
SUSTAIN/RELEASE WRITEONLY
Filler
FC LO
WRITEONLY
FC HI
WRITEONLY
RES/FiLT
WRITEONLY
MODEIVOl WRITE-ONLY
Misc.
POT X
READ-ONLY
POT Y READONLY
OSC,/RANDOM READONLY
ENVJ READONLY
a
o
Z
C
G
M
`
~
G
~ ~
W
t e -
"
O
e
e e
a
* e
x
a
" e
e ;
e C
O
e e
0
=
: e
~
~ U
l
=,
6
"
V
-0
O
J
_
l
P O
C O
6
2 (
M ~
O
a
e
0
l e
= i
U ~
<
@
~ U
O O
C
"
a
.
C
L
0
3
0
f
3
D
G
v
D
3
U
APPENDI X S
DI SK and PRI NTER COMMANDS and
STATEMENTS
The following BASIC commands and statements let you perform a variety of
operations on di sk drives and any compatible Commoore pri nter.
CLOSE
TYPE: UO Statement
FORMAT: CLOSE < file numbr >
Action: This statement shuts off any data fi l e or channel to a device. The fi le
number is the same as when the fi le or device was OPENe (se OPEN state
ment and the section on I NPUT/OUTPUT prorammi ng).
When working with storage devices l i ke di sks, the CLOSE operation stores
any incomplete buffers to the device. When thi s is not performed, the fi le wi l l
be unreadable on the di sk. The CLOSE oprati on i sn' t as necessary wi th other
devices, but it does free up memory for other files. your external device
manual for more details.
EXAMPLES of CLOSE Statement
10 CLOSE 1
20 CLOSE X
3 CLOSE 9 * (1 J) .
CMD
TYPE: I/O Statement
FORMAT: CMD " file numbr > Lstrng
Action: This statement switches the primar output device from the
screen to the fi l e specified. This fi le could b on di sk, printer, or an I/O device
l i ke the moem. The file number must be specified i n a prior OPEN statement.
The string, when specified, is sent to the fi le. This is handy for ti tl i ng printouts,
etc.
When this command is in effect, any PRINT statements and LIST commands
wi l l not di splay on the screen, but will send the text i n the same format to the
fi le.
To re-di rect the output back to the screen, the PRI NT# command should send
a blank l i ne to the CMD device before CLOSEi ng, so it wi l l stop expecting data
(cal led "un-listening" the device).
Any system error (l i ke ?SYNTAX ERROR) wi l l cause output to return to the
screen. Devices aren't un-listened by thi s, so you shoul d send a bl ank l i ne
after an error condi ti on_ (See your pri nter or disk manual for more detai l s. )
1 75
EXAMPLES of CMD Statement:
OPEN 4, 4: CMD 4, "TITLE" : LIST: REM LISTS PROGRAM ON
PRINTER
. PRINTI 4: CLOSE 4: REM UN-LISTENS AND CLOSES PRINTER
10 OPEN 1 , 8, 4, "TEST" : REM CREATE SEa FILE
Z CMD 8: REM OUTPUT TO TAPE FILE, NOT SCREEN
3 FOR L F 1 TO 1 0
% PRINT L: REM PUTS NUMBER I N DISK BUFFER
b NEXT
.
m PRINTI 1 : REM UNLISTEN
70 CLOSE 1: REM WRITE UNFINISHED BUFFER, PROPERLY
FINISH
GE#
TPE: UO Statement
FORMAT: GE' file numbr ,
variable list ,
Action: This statement reads characters one-at-a-ti me from the device or fi l e
specified_ It works the same as the GET statement, except that the data comes
from a di fferent place than the keyboard. If no character i s received, the variable
is set to an empty stri ng (equal to ) or to 0 for numeric variables. Characters
used to separate data in fi l es, l i ke the comma (g) or gkey code (ASC code
of 1 3), are received l i ke any other character.
When used with device #3 (TV screen), thi s statement wi l l read characters
one by one from the screen. Each use of GET# moves the cursor 1 position to
the right The character at the end of the logical l i ne is changed to a CHR$ (13),
the key coe.
EXAMPLES of GET# Statement
5 GET# 1 , A$
10 OPEN 1 , 3: GET# 1 , Z7$
Z GET' 1 , A, B, C$, 0$
1 76
INPUT#
TYPE: 1/0 Statement
FORMAT I NPUTH file number , qvariable list
Action: Thi s i s usual l y the fastest and easiest way to retrieve data stored in a
fi l e on di sk. The data i s in the form of whol e variables of up to 80 characters i n
l ength, as opposed to the one-at-a-ti me method of GET#. First, the fi l e must
have been OPENed, then I NPUT# can f i l l the variables.
The I NPUT# command assumes a vari abl e i s fi nished when i t reads a
RETURN code (CHR$(1 3)), a comma (,), semicolon (;), or col on(:). Quote marks
can be used to enclose these characters when wri ti ng i f they are needed (See
PRI NT# statement).
I f the variable type used i s numeri c, and non-numeric characters are received,
a BAD DATA error resul ts. I NPUT# can read stri ngs up to 80 characters l ong,
beyond whi ch a STRING TOO LONG error resul ts.
When used wi th devi ce #3 (the screen), thi s statement wi l l read an enti re
logical l i ne and move the cursor down to the next l i ne.
EXAMPLES of I NPUTH Statement:
1 0 I NPUT# 1 , A
20 I NPUT# 2, A$, B$
LOAD
TYPE: Command
FORMAT LOAD " (file-name
" ,device
[, address ]
Action: The LOAD statement reads the contents of a program fi l e from di sk
i nto memory. That way you can use the i nformation LOADed or change the i n
formation in some way. The di sk uni t is normal ly device number 8. The LOAD
cl oses al l open fi les and, if it i s used in di rect mode, it performs a CLR (cl ear)
before readi ng the program. If LOAD is executed from wi thi n a program, the
program is RUN. This means that you can use LOAD to "chai n" several pro
grams together. None of the variables are cl eared duri ng a chai n operati on.
I f you are usi ng fi l e-name pattern matchi ng, the fi rst fi l e whi ch matches the
pattern i s loaded. The asterisk i n quotes by i tsel f ( ) causes the fi rst fi l e-name
in the di sk di rectory to be loaded. If the fi l e-name used does not exist or if i t i s
not a program fi le, the BASI C error message ?FI LE NOT FOUND occurs.
If you use the secondary address of 1 thi s wi l l cause the program to LOAD to
the memory l ocati on from whi ch i t was saved.
EXAMPLES of LOAD Command:
LOAD A$,8
LOAD " ",8
LOAD "$",8
LOAD "FUN",8
SEARCHI NG FOR FUN
LOADING
READY.
LOAD "GAME ONE",8,1
SEARCHI NG FOR GAME ONE
LOADI NG
READY.
(Uses the name in A$ to search)
(LOADs first program from disk)
(LOADs disk director)
(LOAD a file from disk)
(LOAD a file to the specific memor
location from which the proram was
saved on the disk)
177
OPEN
TPE: UO Statement
FORMAT: OPEN