Commodore 64 User Guide

Commodore 64 User Guide

Below is the Commodore 64 User Guide Thanks to the guy's at Project 64. Check out their site for more Commodore 64 documentation.

COMMODORE 64 USER'S GUIDE
_____
/ ___|___
| / |__/ c o m m o d o r e
| \___|__\ C O M P U T E R
\_____|

USER'S MANUAL STATEMENT

"This equipment generates and uses radio frequency energy and if
not installed and used properly, that is, in strict accordance with the
manufacturer's instructions, may cause interference to radio and
television reception. It has been type tested and found to comply with
the limits for a Class B computing device in accordance with the
specifications in Subpart J of Part 15 of FCC rules, which are designed
to provide reasonable protection against such interference in a
residential installation. However, there is no guarantee that
interference will not occur in a particular installation. If this
equipment does cause interference to radio or television reception,
which can be determined by turning the equipment off and on, the user
is encouraged to try to correct the interference by one or more of the
following measures:

- reorient the receiving antenna,

- relocate the computer with respect to the receiver,

- move the computer away from the receiver,

- plug the computer into a different outlet so that computer and
receiver are on different branch circuits.

"If necessary, the user should consult the dealer or an experienced
radio/television technician for additional suggestions. The user may
find the following booklet prepared by the Federal Communications
Commission helpful: 'How to Identify and Resolve Radio-TV Interference
Problems.' This booklet is available from the U.S. Government Printing
Office, Washington, D.C. 20402, Stock No. 004-000-00345-4."

COMMODORE 64 USER'S GUIDE

Published by
Commodore Business Machines, Inc.
and
Howard W. Sams & Co., Inc.

FIRST EDITION
THIRD PRINTING-1983

Copyright (C) 1982 by Commodore Business Machines, Inc.
All rights reserved.

This manual is copyrighted and contains proprietary information. No part
of this publication may be reproduced, stored in a retrieval system, or
transmitted in any form or by any means, electronic, mechanical,
photocopying, recording, or otherwise, without the prior written
permission of COMMODORE BUSINESS MACHINES, Inc.

TABLE OF CONTENTS

INTRODUCTION

1. SETUP
1.1. Unpacking and Connecting the Commodore 64
1.2. Installation
1.3. Optional Connections
1.4. Operation
1.5. Color Adjustment

2. GETTING STARTED
2.1. Keyboard
2.2. Back to Normal
2.3. Loading and Saving Programs
2.4. PRINT and Calculations
2.5. Precedence
2.6. Combining Things

3. BEGINNING BASIC PROGRAMMING
3.1. The Next Step
GOTO
3.2. Editing Tips
3.3. Variables
3.4. IF ... THEN
3.5. FOR ... NEXT Loops

4. ADVANCED BASIC
4.1. Introduction
4.2. Simple Animation
Nested Loops
4.3. INPUT
4.4. GET
4.5. Random Numbers and Other Functions
4.6. Guessing Game
4.7. Your Roll
4.8. Random Graphics
CHR$ and ASC Functions

5. ADVANCED COLOR AND GRAPHIC COMMANDS
5.1. Color and Graphics
5.2. PRINTing Colors
5.3. Color CHR$ Codes
5.4. PEEKs and POKEs
5.5. Screen Graphics
5.6. Screen Memory Map
5.7. Color Memory Map
5.8. More Bouncing Balls

6. SPRITE GRAPHICS
6.1. Introduction to Sprites
6.2. Sprite Creation
6.3. Additional Notes on Sprites
6.4. Binary Arithmetic

7. CREATING SOUND
7.1. Using Sound if You're Not a Computer Programmer
7.2. Structure of a Sound Program
7.3. Sample Sound Program
7.4. Making Music on Your Commodore 64
7.5. Important Sound Settings
7.6. Playing a Song on the Commodore 64
7.7. Creating Sound Effects
7.8. Sample Sound Effects To Try

8. ADVANCED DATA HANDLING
8.1. READ and DATA
8.2. Averages
8.3. Subscripted Variables
One-Dimensional Arrays
Averages Revisited
8.4. DIMENSION
8.5. Simulated Dice Roll With Arrays
8.6. Two-Dimensional Arrays

APPENDICES
Introduction
A: COMMODORE 64 ACCESSORIES AND SOFTWARE
B: ADVANCED CASSETTE OPERATION
C: COMMODORE 64 BASIC
D: ABBREVIATIONS FOR BASIC KEYWORDS
E: SCREEN DISPLAY CODES
F: ASCII AND CHR$ CODES
G: SCREEN AND COLOR MEMORY MAP
H: DERIVING MATHEMATICAL FUNCTIONS
I: PINOUTS FOR INPUT/OUTPUT DEVICES
J: PROGRAMS TO TRY
K: CONVERTING STANDARD BASIC PROGRAMS TO COMMODORE 64 BASIC
L: ERROR MESSAGES
M: MUSIC NOTE VALUES
N: BIBLIOGRAPHY
O: SPRITE REGISTER MAP
P: COMMODORE 64 SOUND CONTROL SETTINGS

INDEX

INTRODUCTION

Congratulations, on your purchase of one of the best computers in the
world. You are now the proud owner of the COMMODORE 64. Commodore is
known as The Friendly Computer company, and part of being friendly is
giving you easy to read, easy to use and easy to understand instruction
manuals. The COMMODORE 64 USER'S GUIDE is designed to give you all the
information you need to properly set up your equipment, get acquainted
with operating the COMMODORE 64, and give you a simple, fun start at
learning to make your own program.
For those of you who don't want to bother learning how to program,
we've put all the information you need to use Commodore programs or other
prepackaged programs and/or game cartridges (third party software) right
up front. This means you don't have to hunt through the entire book to
get started.
Now let's look at some of the exciting features that are just waiting
for you inside your COMMODORE 64. First, when it comes to graphics you've
got the most advanced picture maker in the microcomputer industry. We
call it SPRITE GRAPHICS, and it allows you to design your own pictures in
4 different colors, just like the ones you see on arcade type video
games. Not only that, the SPRITE EDITOR let's you animate as many as 8
different picture levels at one time. The SPRITE EDITOR will soon be
available as software program that you can load directly into your
COMMODORE 64. You can move your creations anywhere on the screen, even
pass one image in front of or behind another. Your COMMODORE 64 even
provides automatic collision detection which instructs the computer to
take the action you want when the sprites hit each other.
Next, the COMMODORE 64 has built-in music and sound effects that rival
many well known music synthesizers. This part of your computer gives you
3 independent voices, each with a full 9 octave "piano-type" range. In
addition you get 4 different waveforms (sawtooth, triangle, variable
pulse, and noise), a programmable ADSR (attack, decay, sustain, release)
envelope generator and a programmable high, low, and bandpass filter for
the voices, and variable resonance and volume controls. If you want your
music to play back with professional sound reproduction, the COMMODORE 64
allows you to connect your audio output to almost any high-quality
amplification system.
While we're on the subject of connecting the COMMODORE 64 to other
pieces of equipment ... your system can be expanded by adding
accessories, known as peripherals, as your computing needs grow. Some of
your options include items like a DATASSETTE recorder or as many as 5,
VIC 1541 disk drive units for the programs you make and/or play. If you
already have a VIC 1540 disk drive your dealer can update it for use with
the COMMODORE 64. You can add a VIC dot matrix printer to give you
printed copies of your programs, letters, invoices, etc... If you want to
connect up with larger computers and their massive data bases then just
plug in a VICMODEM cartridge, and get the services of hundreds of
specialists and a variety of information networks through your home or
business telephone. Finally if you're one of those people interested in
the wide variety of applications software available in CP/M, the
COMMODORE 64 can be fitted with a plug-in Z-80 microprocessor.
Just as important as all the available hardware is the fact that this
USER'S GUIDE will help you develop your understanding of computers. It
won't tell you everything there is to know about computers, but it
will refer you to a wide variety of publications for more detailed
information about the topics presented. Commodore wants you to really
enjoy your new COMMODORE 64. And to have fun, remember: programming is
not the kind of thing you can learn in a day. Be patient with yourself
as you go through the USER'S GUIDE. But before you start, take a few
minutes to fill out and mail in the owner/registration card that come
with your computer. It will ensure that your COMMODORE 64 is properly
registered with Commodore Headquarters and that you receive the most
up-to-date information regarding future enhancements for your machine.
Welcome to a whole new world of fun!

NOTE:
Many programs are under development while this manual is being
produced. Please check with your local Commodore dealer and with
Commodore User's Magazines and Clubs, which will keep you up to date on
the wealth of applications programs being written for the Commodore 64,
worldwide.

1. SETUP

1.1. Unpacking and Connecting the Commodore 64

The following step-by-step instructions show you how to connect the
Commodore 64 to your television set, sound system, or monitor and make
sure everything is working properly.
Before attaching anything to the computer, check the contents of the
Commodore 64 container. Besides this manual, you should find the
following items:

1. Commodore 64
2. Power supply (black box with an AC plug and supply cord)
3. Video cable
4. TV Switchbox (small silver box with short antenna leads).

If any items are missing check back with your dealer immediately for a
replacement.
First, let's take a look at the arrangement of the various connections
on the computer and how each functions.

/####\--------^--\
/#### |
/#### |
____/#### |
/ |
| ---- ---- __ /-\ |
| \--/ \--/ == \_/ |
\________________\___/______/____|__/
\/ / |
3 2 1
GAME POWER POWER
PORTS SWITCH SOCKET

___/###\__/##_##_##_##_##_##_##_##_##_##_##_##_##_##_##_##\__
|-------------------------------------------------------------|
| |
| |
| |
| +--------------+ /-\ /-\ +------+ +----------+ |
| |==============| [=] O \_/ \_/ |======| |==========| |
+-----/-------------/----/-----\-----\--------\---------\-----+
/ / / \ \ \ \
4 5 6 7 8 9 10
CARTRIDGE CHANNEL TV AUDIO/VIDEO SERIAL CASSETTE USER
SLOT SELECTOR CONNECTOR CONNECTOR PORT INTERFACE PORT

SIDE PANEL CONNECTIONS

1. POWER SOCKET. The free end of the cable from the power supply is
attached here to supply power to the Commodore 64.
2. POWER SWITCH. Turns on power to the Commodore 64.
3. GAME PORTS. Each game connector can accept a joystick or game
controller paddle, while the lightpen can only be plugged into the
game port closest to the front of your computer.

REAR CONNECTIONS

4. CARTRIDGE SLOT. The rectangular slot to the left accepts program or
game cartridges.
5. CHANNEL SELECTOR. Use this switch to select which TV channel the
computer's picture will be displayed on.
6. TV CONNECTOR. This connector supplies both the picture and sound to
your television set.
7. AUDIO & VIDEO OUTPUT. This connector supplies direct audio, which
can be connected to a high quality sound system, and a "composite"
video signal, which can be fed into a television "monitor".
8. SERIAL PORT. You can attach a printer or single disk drive directly
to the Commodore 64 through this connector.
9. CASSETTE INTERFACE. A DATASSETTE recorder can be attached to the
computer so you can save information entered for use at a later
time.
10. USER PORT. Various interface cartridges can be attached to the user
port, such as the VICMODEM, or RS 232 communication cartridge.

1.2. Installation

CONNECTIONS TO YOUR TV

Connect the computer to your TV as shown below.

TV
Switchbox +--+-----------------+--+
+-----+ | | /-------------\#| |
/---------------#= =| |= | | | |#| |
| +--#--+ | | | |#| |
| \\_ | | | | | |
| \_ | | | | | |
To TV | To 300 Ohm | | \-------------/ | |
Signal # Antenna Input +==+=================+==+
Jack |
/------------------------\
| |=---\
| #################### ## | |
| #################### ## | |
| ################## ## | |
| ############## ## | |
\________________________/ |
|
|
|
+---+
| | Power
| | Supply
+---+
|
|

1. Attach one end of the TV cable to the phono type TV signal jack at the
rear of the Commodore 64. Just push it in. Either end of the cable can
be used.
2. Connect the other end of the cable to the antenna switchbox. Just push
it in.
3. If you have a VHF antenna, disconnect it from your TV set.
4. Connect your VHF antenna cable to the screw terminals labeled "antenna
input" on the switchbox. If your antenna cable is the round 75-ohm
coax type, use a 75-ohm to 300-ohm adapter (not supplied) to attach
your antenna cable to the switchbox.
5. Connect the twin lead output cable of the antenna switchbox to the VHF
antenna terminals of your TV set. If your set is one of the newer
types with a round 75-ohm VHF connector, you will need a 300-ohm to
75-ohm converter (not supplied) to connect the switchbox to the 75-ohm
VHF antenna input on the set.
6. Set the TV's VHF tuner to the channel number indicated on the
computer's channel selector switch (channel 3 move the switch to the
left, channel 4 move the switch to the right). If a strong local TV
signal is present on one of these channels, select the other channel
to avoid possible interference.
7. Plug the power supply cable into the power socket on the side of the
Commodore 64. Just push it in. It is "keyed" to allow insertion in
only one direction, so you can't connect the power cord the wrong way.
The power supply converts household current into the form the computer
uses.

/+---------------+
+ | |
| | | |
| | | |
/ | | | |
|========| | |
|========| | |
/ | | | |
| | |
| | _ _ /
| | |O| |O| |
+ | # # |
\+-----\---/----+
\ /
| |
| |
| |
++-++
75 Ohm to |___|
300 Ohm ----> | |
Adapter | |
+---+
\=/
###
Your 75 Ohm ----> | |
Coax VHF Antenna | |

/----------- -----------\
| /==\ /==\ /==\ |
| ||__|| ||__|| ||__|| |
| \__/ \__/ \__/ |
\__________________________/
^ To VHF
_|___ ANT.
+---+/
300 Ohm | ||
to 75 Ohm --> | ||
Adapter ++-++/
| |
| |
|_|/
/

The Commodore 64 is now correctly connected. No additional connections
are required to use the computer with your TV. The antenna switchbox will
connect the computer to the TV when the slide switch is in the "computer"
position. When the switch is in the "TV" position your set will operate
normally.

___/###\__/##_##_##_##_##_##_##_##_##_##_##_##_##_##_##_##\__
|-------------------------------------------------------------|
| |
| |
| |
| +--------------+ /-\ /-\ +------+ +----------+ |
| |==============| [=] O \_/ \_/ |======| |==========| |
+-------------------------------------------------------------+
^
To |
TV Signal |
Jack
| Back of Your TV
# _/-----------------------------
| | /
\ / +--------------------------------
| |
\__________I______________________
| \
|-------+ |
| UHF | |
| O O | |#|
| VHF | |
||O| |O|| /---------=-\
/| # # | | COMPUTER |
/ |-|---|-+ | | |
200 Ohm | | | | | |
VHF | | \_____| | |
Input | \_________| | |
| | | |
| | TV |
| Antenna ->| |O| |O| |
| Switch \___#___#___/
| Box | | __
| |___|/
__/
Your VHF
Antenna
(If Used)

1.3. Optional Connections

Since the Commodore 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 Commodore 64 also provides a standard
"composite" video signal, which can be fed into a television monitor.
These options are made possible by the audio/video output jack on the
rear panel of the Commodore 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 audio/video connector on the computer. Two
of the four pins on the opposite end of the cable contain the audio and
video signals. Optionally, you can construct your own cable, using the
pinouts shown in Appendix I as a guide.
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/Video |
| Output |
|-----------------_---_-------------------|
| ========= = o | | | | ===== ========= |
+-----------------------------------------+

^
|

/-\
| |
| |
#
|
|
To AUXILIARY |
INPUT or |
____________ TUNER INPUT |
/ \ / \ To VIDEO IN
+----++------------++----+ +------------+---+
| || ### ====== || | | /--------\ | O |
| || === OoooO || | || || = |
| ||------------|| | || || o |
| || | | | || | | \________/ | |
| || | | | || | +------------+---+
+----++============++----+
TV Monitor
Audio System

If you purchased peripheral equipment, such as a VIC 1541 disk drive or
a VIC 1525E printer, you may wish to connect it at this time. Refer to
the user's manuals supplied with any additional equipment for the
procedure for connecting it to the computer.

A completed system might look like this.

[ Picture omitted ]

1.4. Operation

USING THE COMMODORE 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:

**** COMMODORE 64 BASIC V2 ****
64K RAM SYSTEM 38911 BASIC BYTES FREE

READY.
_

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 setup 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 "On"     Make sure power switch     |
| not "On"                                   is in "On" position        |
|                                                                       |
|                      Power cable not       Check power socket for     |
|                      not plugged in        loose or disconnected      |
|                                            power cable                |
|                                                                       |
|                      Power supply not      Check connection with      |
|                      plugged in            wall outlet                |
|                                                                       |
|                      Bad fuse in           Take system to authorized  |
|                      computer              dealer for replacement of  |
|                                            fuse                       |
|                                                                       |
|                      TV on wrong           Check other channel        |
|                      channel               for picture (3 or 4)       |
|                                                                       |
|                      Incorrect             Computer hooks up to       |
|                      hookup                VHF antenna terminals      |
|                                                                       |
|                      Video cable not       Check TV output cable      |
|                      plugged in            connection                 |
|                                                                       |
|                      Computer set for      Set computer for same      |
|                      wrong channel         channel as TV (3 or 4)     |
|                                                                       |
| Random patterns on   Cartridge not         Reinsert cartridge after   |
| TV with cartridge    properly inserted     turning off power          |
| in place                                                              |
|                                                                       |
| Picture without      Poorly tuned TV       Retune TV                  |
| color                                                                 |
|                                                                       |
| Picture with         Bad color             Adjust color/hue/          |
| poor color           adjustment on TV      brightness controls on TV  |
|                                                                       |
| Sound with excess    TV volume up high     Adjust volume of TV        |
| background noise                                                      |
|                                                                       |
| Picture OK,          TV volume too low     Adjust volume of TV        |
| but no sound                                                          |
|                                                                       |
|                      Aux. output not       Connect sound jack to      |
|                      properly connected    aux. input on amplifier    |
|                                            and select aux. input      |
+-----------------------------------------------------------------------+

 

 

TIP:  The  COMMODORE 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 COMMODORE 64 owners who can help you
gain knowledge and experience.

CURSOR

The  flashing  square  under  READY  is called the cursor and indicates
where what you type on the keyboard  will be displayed on the screen.  As
you  type,  the cursor will move ahead one space,  as the original cursor
position  is  replaced  with  the character you typed.  Try typing on the
keyboard and watch as characters you type are displayed on the TV screen.

1.5. Color Adjustment

There  is  a simple way to get a pattern of colors on the TV 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 the Commodore 64.
First,  look on the left side of the keyboard and locate the key marked
<CTRL>.  This  stands for ConTRoL and is used,  in conjunction with other
keys, to instruct the computer to do a specific task.

[ Picture omitted ]

To  use  a  control  function,  you  hold  down  the  <CTRL>  key while
depressing a second key.
Try this:  hold the <CTRL> key  while also depressing the <9> key. Then
release both keys. Nothing obvious should have happened, but if you touch
any  key  now,  the  screen  will show the character displayed in reverse
type, rather than normal type -- like the opening message or anything you
typed earlier.
Hold down the <SPACE BAR>. What happens? If you did the above procedure
correctly,  you  should  see  a light blue bar move across the screen and
then move down to the next line as long as the <SPACE BAR> is depressed.

**** COMMODORE 64 BASIC V2 ****
64K RAM SYSTEM  38911 BASIC BYTES FREE

READY.
____________________________
__________

Now,  hold <CTRL>  while depressing any of the other number keys.  Each
of  them  has a color  marked on the front.  Anything displayed from this
point will be in that color. For example, hold <CTRL> and the <8> key and
release both. Now hold the <SPACE BAR>.
Watch the display.  The bar is now in yellow!  In a like manner you can
change  the  bar  to  any  of  the colors indicated on the number keys by
holding <CTRL> and the appropriate key.
Change the bar to a few more different colors and then adjust the color
and  tint  controls  on  your  TV  so  the display matches the colors you
selected.
The display should appear something like this:

**** COMMODORE 64 BASIC V2 ****
64K RAM SYSTEM  38911 BASIC BYTES FREE

READY.
_________________________     <------ <3> Red bar
_______ ____________ ____     <------ <3>,<6>,<7> Red, Green, Blue bars
__________ ______________     <------ <7>,<8> Blue, Yellow bars
____________                  <------ <8> Yellow bar

At  this  point  everything is properly adjusted and working correctly.
The following chapters will introduce you to the BASIC language. However,
you can  immediately start using some of the many prewritten applications
and  games available for the Commodore 64  without knowing anything about
computer programming.
Each  of  these packages contains detailed information about how to use
the  program.  It is suggested,  though,  that you read through the first
few  chapters  of  this  manual  to  become  more familiar with the basic
operation of your new system.

2. GETTING STARTED

2.1. Keyboard

Now that you've got everything set up and adjusted,  please  take a few
moments  to  familiarize  yourself  with  the keyboard which is your most
important means of communication with the Commodore 64.
You  will  find  the keyboard similar to a standard typewriter keyboard
found  in  most  areas.  There  are,  however, a number of new keys which
control specialized functions. What follows is a brief description of the
various  keys  and how they function.  The detailed operation of each key
will be covered in later sections.

[ Picture omitted ]

<RETURN>

The <RETURN> key signals the computer  to look at the information  that
you typed and enters that information into memory.

<SHIFT>

The <SHIFT> key works like that on a standard typewriter. Many keys are
capable of displaying two letters or symbols  and two graphic characters.
In  the  "upper/lower case" mode the <SHIFT> key gives you standard upper
case  characters.  In the "upper case/graphic" mode  the <SHIFT> key will
display the graphic character on the right hand side of the front part of
the key.
In the case of special YELLOW function keys,  the <SHIFT> key will give
you the function marked on the front of the key.

EDITING

No  one  is  perfect,  and  the Commodore 64 takes that into account. A
number  of  editing  keys  let  you  correct  typing  mistakes  and  move
information around on the screen.

<CRSR>

There are two keys marked <CRSR> (CuRSoR), one with up and down arrows,
the other with left and right arrows.  You can use these keys to move the
cursor up and down or left and right.  In the unshifted mode,  the <CRSR>
keys  will  let  you  move  the  cursor down and to the right.  Using the
<SHIFT> key and <CRSR> keys allows the cursor to be moved either up or to
the  left.  The  cursor keys have a special repeat feature that keeps the
cursor moving until you release the key.

<INST/DEL>

If  you  hit  the  <INST/DEL>  key,  the cursor will move back a space,
erasing  (DELeting)  the  previous  character you typed. If you're in the
middle of a line, the character to the left is deleted and the characters
to the right automatically move together to close up the space.
A <SHIFT>ed <INST/DEL> allows you to INSerT information on a line.  For
example,  if you noticed a typing mistake  in the beginning of a line  --
perhaps you left out part of the name  -- you could use the <CRSR> key to
move back to the error  and then hit <INST/DEL>  to insert a space.  Then
just type in the missing later.

<CLR/HOME>

<CLR/HOME>  positions  the cursor at the "HOME" position of the screen,
which is the upper left-hand corner.  A shifted <CLR/HOME> will clear the
screen and place the cursor in the home position.

<RESTORE>

<RESTORE>  operates as the name implies.  It stores the computer to the
normal  state  it was in before you changed things with a program or some
command. A lot more will be said on this in later chapters.

FUNCTION KEYS

The  four  function  keys  on  the  right  side  of the keyboard can be
"programmed"  to  handle  a variety of functions.  They can be defined in
many ways to handle repetitive tasks.

[ Picture omitted ]

<CTRL>

The  <CTRL>  key,  which  stands for ConTRoL, allows you to set colors,
and  perform  other  specialized  functions. You hold the <CTRL> key down
while  depressing  another  designated key to get a control function. You
had an opportunity to try the <CTRL> key  when you changed text colors to
create different color bars during the setup procedure.

<RUN/STOP>

Normally,  depressing the <RUN/STOP>  key  will stop the execution of a
BASIC program. It signals the computer to STOP doing something. Using the
<RUN/STOP> key in the shifted mode will allow you to automatically load a
program from tape.

<C=> COMMODORE KEY

The Commodore key <C=> performs a number of functions. First, it allows
you to move between the text and graphic display modes.
When  the computer is first turned on,  it is in the upper case/graphic
mode,  that  is,  everything  you  type is in upper case letters.  As was
mentioned, using the <SHIFT> key in this mode will display the graphic on
the right side of the keys.
If you hold down the <C=> key and <SHIFT> key,  the display will change
to upper and lower case. Now, if you hold down the <C=> key and any other
key with a graphic symbol,  the graphic shown on the left side of the key
will be displayed.
To get back into the upper case/graphic mode hold down the <C=> key and
<SHIFT> key again.
The second function of the <C=> key is to  allow you access to a second
set  of  eight  text colors.  By holding down the <C=> key and any of the
number keys,  any text now typed will be in the alternate color available
from  the  key  you depressed.  Chapter 5 lists the text colors available
from each key.

2.2. Back to Normal

Now  that you've had a chance to look over the keyboard,  let's explore
some of the Commodore 64's many capabilities.
If  you  still have the color bars on the screen from adjusting your TV
set, hold <SHIFT> and <CLR/HOME>.  The screen should clear and the cursor
will  be  positioned  in  the  "home" spot (upper left-hand corner of the
screen).
Now, simultaneously hold <C=> and the <7> key. This sets the text color
back to light blue.  There is one more step needed to get everything back
to normal. Hold <CTRL> and <0> (Zero not Oh!). This sets the display mode
back  to  normal.  If  you  remember,  we turned REVERSE type on with the
<CTRL><9> to create the color bars (the color bars were actually reversed
spaces).  If  we were in the normal text mode during the color test,  the
cursor would have moved, but just left blank spaces.

TIP:

Now  that  you've  done  things  the hard way, there is a simple way to
reset the machine  to the normal display.  First press the <RUN/STOP> key
and then press the <RESTORE> key.  <RUN/STOP> must always be held down in
order to use the <RESTORE> key function.
This will clear the screen and return everything to normal. If there is
a  program  in  the computer,  it will be left untouched.  This is a good
sequence to remember, especially if you do a lot of programming.
If  you  wish  to  reset  the machine as if it were turned off and then
switched on again, type,  SYS 64759  and press <RETURN>. Be careful using
this  command!  It  will  wipe  out  any  program  or information that is
currently in the computer.

2.3. Loading and Saving Programs

One  of  the most important features of the Commodore 64 is the ability
to save and load programs to and from cassette tape or disk.
This  capability allows you to save the programs you write for use at a
later time, or purchase prewritten programs to use with the Commodore 64.
Make  sure  that  either  the  disk  drive or cassette unit is attached
properly.

LOADING PREPACKAGED PROGRAMS

For  those  of  you  interested  in  using  only  prepackaged  programs
available on cartridges, cassette, or disk here's all you have to do:

1. CARTRIDGES: The Commodore 64 computer has a line of programs and games
on cartridge.  The programs offer a wide variety of business and personal
applications  and  the  games  are  just  like real arcade games  --  not
imitations. To load these games, first turn on your TV set. Next turn OFF
your  Commodore 64.  YOU MUST TURN OFF YOUR COMMODORE 64 BEFORE INSERTING
OR  REMOVING  CARTRIDGES  OR  YOU  MAY  DAMAGE  THE CARTRIDGE AND/OR YOUR
COMMODORE 64! Third insert the cartridge.  Now turn your Commodore 64 on.
Finally  type  the  appropriate START key as is listed on the instruction
sheet that comes with each game.

2. CASSETTES:  Use  your  DATASSETTE  recorder  and  the  ordinary  audio
cassettes  that  came as part of your prepackaged program.  Make sure the
tape is completely rewound to the beginning of the first side.  Then just
type  LOAD.  The  computer  will  answer with PRESS PLAY ON TAPE,  so you
respond  by  pressing play on your datassette machine.  At this point the
computer  screen  will go blank until the program is found.  The computer
will say  FOUND (PROGRAM NAME)  on the screen.  Now you press down on the
<C=> key.  This will actually load the program into the computer.  If you
want to stop the loading simply press <RUN/STOP> key.

3. DISK:  Using your disk drive,  carefully insert the preprogrammed disk
so  that  the label on the disk is facing up and is closest to you.  Look
for  a  little notch on the disk (it might be covered with a little piece
of tape). If  you're inserting the disk properly the notch will be on the
left side.  Once the disk is inside  close the protective gate by pushing
down on the lever.  Now type  LOAD "PROGRAM NAME",8  and hit the <RETURN>
key. The disk will make noise and your screen will say:

SEARCHING FOR PROGRAM NAME
LOADING
READY.
_

When  the  READY  comes  on  and  the  _ is on, just type RUN, and your
prepackaged software is ready to use.

LOADING PROGRAMS FROM TAPE

Loading  a program back from tape or disk is just as simple.  For tape,
rewind the tape back to the beginning and type:

LOAD "PROGRAM NAME"

If  you  don't remember the program name,  just type LOAD and the first
program on the tape will be loaded into memory.
After you press <RETURN> the computer will respond with:

PRESS PLAY ON TAPE

After  you  depress  the  play  key, the screen will blank, turning the
border color of the screen as the computer searches for the program.
When the program is found, the screen will display:

FOUND PROGRAM NAME

To  actually  load  the  program,  depress the <C=> key. To abandon the
loading  procedure,  hit  <RUN/STOP>.  If  you hit the Commodore key, the
screen  will  again  turn  the  border color while the program is loaded.
After  the  loading procedure is completed, the screen will return to the
normal state and the READY prompt will reappear.

LOADING PROGRAMS FROM DISK

Loading a program from disk follows the same format. Type:

LOAD "PROGRAM NAME",8

The  8  is  the  code for the disk, so you're just letting the computer
know that you want the program loaded from the disk.
After  you  hit  <RETURN>  the disk will start whirring and the display
shows:

SEARCHING FOR PROGRAM NAME
LOADING
READY.
_

NOTE:
When   you   load  a  new  program  into  the  computer's  memory,  any
instructions  that  were  in the computer previously will be erased. Make
sure  you  save  a  program  you're  working on before loading a new one.
Once a program has been loaded, you can RUN it, LIST, or make changes and
re-save the new version.

SAVING PROGRAMS ON TAPE

After entering a program, if you wish to save it on tape, type:

SAVE "PROGRAM NAME"

"PROGRAM NAME" can be up to 16 characters long.  After you hit <RETURN>
the computer will respond with:

PRESS PLAY AND RECORD ON TAPE

Press both the record and play keys on the datassette.  The screen will
blank, turning the color of the border.
After  the  program  is  saved on tape, the READY prompt will reappear,
indicating  that  you can start working on another program,  or just turn
off the computer for a while.

SAVING PROGRAMS ON DISK

Saving a program on disk is even simpler. Type:

SAVE "PROGRAM NAME",8

The  8  is  the code for the disk,  so you're just letting the computer
know you want the program saved to disk.
After you press  <RETURN>  the disk will start to turn and the computer
will respond with:

SAVING PROGRAM NAME
OK
READY.
_

2.4. PRINT and Calculations

Now  that  you've  gotten  through  a  couple  of  the  more  difficult
operations  you need  in order to keep the programs you like,  lets start
making some programs for you to save.
Try typing the following exactly as shown:

PRINT "COMMODORE 64"     <----- Type this line and hit <RETURN>
COMMODORE 64            <------ Computer typed

READY.
_

If  you  make  a  typing  mistake,  use the <INST/DEL> key to erase the
character  immediately  to the left of the cursor. You can delete as many
characters as necessary.
Let's  see  what  went on in the example above.  First,  you instructed
(commanded) the computer to PRINT whatever was inside the quote marks. By
hitting  <RETURN>  you  told  the computer to do  what you instructed and
COMMODORE 64 was printed on the screen.
When you use the PRINT statement in this form,  whatever is enclosed in
quotes is printed exactly as you typed it.
If the computer responded with:

?SYNTAX ERROR

ask yourself if you made a mistake in typing,  or forgot the quote marks.
The  computer  is  precise  and  expects  instructions  to  be given in a
specific form.
But don't get worried; just remember to enter things as we present them
in the examples and you'll get along great with the Commodore 64.
Remember, you can't hurt the computer by typing on it, and the best way
to learn BASIC is to try different things and see what happens.
PRINT  is  one  of  the  most useful and powerful commands in the BASIC
language.  With  it,  you  can  display  just  about  anything  you wish,
including graphics and results of computations.
For example,  try the following.  Clear the screen  by holding down the
<SHIFT> key  and  <CLR/HOME> key and type (be sure to use the '1' key for
one, not a letter 'I'):

PRINT 12 + 12            <----- Type this line and hit <RETURN>
24                      <------ Computer printed the answer

READY.
_

What you've discovered is  that the Commodore 64 is a calculator in its
basic form.  The result of "24" was calculated and printed automatically.
In  fact,  you can also perform  subtraction,  multiplication,  division,
exponentiation, and  advanced  math  functions such as calculating square
roots, etc. And you're not limited to a single calculation on a line, but
more on that later.
Note  that in the above form,  PRINT behaved differently from the first
example.  In  this  case,  a value or result of a calculation is printed,
rather  than  the  exact message you entered because the quote marks were
omitted.

ADDITION

The plus sign (+) signals addition: we instructed the computer to print
the result of 12 added to 12.  Other arithmetic operations take a similar
form to addition.  Remember to always hit <RETURN> after typing PRINT and
the calculation.

SUBTRACTION

To subtract, use the conventional minus (-) sign. Type:

PRINT 12 - 9             <----- Hit <RETURN>
3

MULTIPLICATION

If  you  wanted  to  multiply  12  times  12,  use  the asterisk (*) to
represent multiplication. You would type:

PRINT 12 * 12            <----- Hit <RETURN>
144

DIVISION

Division uses the familiar "/". For example, to divide 144 by 12, type:

PRINT 144 / 12           <----- Hit <RETURN>
12

EXPONENTIATION

In  a  like fashion,  you can easily raise a number to a power (this is
the same as multiplying a number by itself  a specified number of times).
The '^' (up arrow) signifies exponentiation.

PRINT 12 ^ 5
248832

This is the same as typing:

PRINT 12 * 12 * 12 * 12 * 12
248832

TIP:
BASIC  has  number  of  shortcut ways of doing things.  One such way is
abbreviating BASIC commands (or keywords).  A '?' can be used in place of
PRINT,  for example.  As we go on you'll be presented with many commands;
Appendix D shows the abbreviations for each and what will be displayed on
the screen when you type the abbreviated form.

The  last example brings up another important point:  many calculations
may be performed on the same line, and they can be of mixed types.
You could calculate this problem:

? 3 + 5 - 7 + 2          (The '?' replaces the word PRINT)
3

Up  to  this  point  we've just used small numbers and simple examples.
However, the Commodore 64 is capable of more complex calculations.
You could,  for example,  add a number of large figures together.  Try
this, but don't use any commas, or you'll get an error:

? 123.45 + 345.78 + 7895.687
8364.917

That looks fine, but now try this:

? 12123123.45 + 345.78 + 7895.687
12131364.9

If you took the time to add this up by hand,  you would get a different
result.
What's  going  on  here?  Even  though the computer has a lot of power,
there's  a limit to the numbers it can handle.  The Commodore 64 can work
with numbers containing 10 digits. However when a number is printed, only
nine digits are displayed.
So in our example, the result was "rounded" to fit in the proper range.
The Commodore 64 rounds up when the next digit is five or more; it rounds
down when the next digit is four or less.
Numbers  between  0.01  and  999,999,999  are  printed  using  standard
notation.  Numbers  outside  this  range  are  printed  using  scientific
notation.
Scientific  notation  is  just  a process of expressing a very large or
small number as a power of 10.
If you type:

? 123000000000000000
1.23E+17

This is the same as 1.23 * 10^17 and is used just to keep things tidy.
There  is  a  limit  to  the  numbers  the computer can handle, even in
scientific notation. The limits are:

Largest: +/- 1.70141183E+38
Smallest (different from zero): +/- 2.93873588-39

2.5. Precedence

If  you  tried  to  perform  some mixed calculations different from the
examples  we  showed  earlier, you might not have gotten the results that
you expected.  The reason is that the computer performs calculations in a
certain order.
In this calculation:

20 + 8 / 2

you  can't  tell  whether the answer should be 24 or 14 until you know in
which order to perform the calculations.  If you add 20 to 8 divided by 2
(or 4), then the result is 24. But,  if you add 20 plus 8 and then divide
by 2 the answer is 14. Try the example and see what result you get.
The reason you got 24 is because the Commodore 64 performs calculations
left to right according to the following:

First :   -   minus sign indicating negative numbers
Second:   ^   exponentiation, left to right
Third :   */  multiplication and divisions, left to right
Fourth:   +-  addition and subtraction, left to right

Follow  along  according  to  the order of precedence, and you will see
that  it  the above example the division was performed first and then the
addition to get a result of 24.
Make  up  some problems of your own and see if you can follow along and
predict the results according to the rules set down above.
There's  also  an  easy  way  to  alter the precedence process by using
parentheses to set off which operations you want performed first.
For example, if you want to divide 35 by 5-plus-2 you type:

? 35 / 5 + 2
9

you  will  get  35  divided by 5 with 2 added to the answer, which is not
what you intended at all. To get what you really wanted, try this:

? 35 / (5 + 2)
5

What  happens  now  is  that  the  computer evaluates what is contained
in  the  parentheses first.  If there are parentheses within parentheses,
the innermost parentheses are evaluated first.
Where there are a number of parentheses on a line, such as:

? (12 + 9) * (6 + 1)
147

the computer evaluates them left to right. Here 21 would be multiplied by
7 for the result 147.

2.6. Combining Things

Even though we've spent a lot of time in areas that might not seem very
important, the details presented here will make more sense once you start
to program, and will prove invaluable.
To  give  you an idea how things fit in place,  consider the following:
how could you combine the two types of PRINT statements we've examined so
far to print something more meaningful on the screen?
We  know  that  by  enclosing  something within quote marks prints that
information  on  the screen exactly as it was entered,  and by using math
operators,  calculations  can  be  performed.  So why not combine the two
types of PRINT statements like this:

? "5 * 9 = "; 5 * 9      (Semicolon means no space)
5 * 9 = 45

Even though this might seem a bit redundant,  what we've done is simply
use  both  types  of  print  statements  together.  The first part prints
"5 * 9 ="  exactly as it was typed.  The second part does the actual work
and prints the result,  with the semicolon separating the message part of
the statement from the actual calculation.
You  can separate the parts of a mixed PRINT statement with punctuation
for  various formats.  Try a comma in place of the semicolon and see what
happens.
For the curious, the semicolon causes the next part of the statement to
be printed immediately after the previous part,  without any spaces.  The
comma   does  something  different.  Even  though  it  is  an  acceptable
separator, it spaces things out more. If you type:

? 2,3,4,5,6   <-------------------------------- Hit <RETURN>
2            3            4             5
6

the  numbers  will  be  printed across the screen and down on to the next
line.
The  Commodore  64's  display  is  organized into 4 areas of 10 columns
each.  The  comma tabs each result into the next available area. Since we
asked  for  more  information  to  be printed than would fit on one line,
(we  tried  to  fit  five  10-column areas on one line) the last item was
moved down to the next line.
The  basic  difference  between  the  comma and semicolon in formatting
PRINT  statements  can  be  used our advantage when creating more complex
displays: it allow us to create some sophisticated results very easily.

3. BEGINNING BASIC PROGRAMMING

3.1. The Next Step

Up  to  now  we've  performed  some  simple  operations  by  entering a
single  line  of  instructions  into  the  computer.  Once  <RETURN>  was
depressed,  the  operation  that  we specified was performed immediately.
This is called the IMMEDIATE or CALCULATOR mode.
But  to  accomplish  anything  significant, we must be able to have the
computer  operate  with  more  than  a single line statement. A number of
statements  combined  together  is called a PROGRAM and allows you to use
the full power of the Commodore 64.
To  see  how  easy  it is to write your first Commodore 64 program, try
this:

Clear the screen by holding down the <SHIFT> key, and then depressing the
<CLR/HOME> key.
Type NEW and press <RETURN>. (This just clears out any numbers that might
have been left in the computer from your experimenting.)
Now type the following exactly as shown  (remember to hit <RETURN>  after
each line)

10 ? "COMMODORE 64"
20 GOTO 10

Now, type RUN and hit <RETURN> -- watch what happens.  Your screen will
come alive with COMMODORE 64. After you've finished watching the display,
hit <RUN/STOP> to stop the program.

COMMODORE 64
COMMODORE 64
COMMODORE 64
COMMODORE 64
COMMODORE 64
COMMODORE 64
COMMODORE 64
COMMODORE 64
COMMODORE 64
COMMODORE 64
COMMODORE 64
COMMODORE 64
BREAK IN 10
READY

A number of important concepts were introduced in  this  short  program
that are the basis for all programming.
Notice  that here we preceded each statement with a number.  This  LINE
number tells the computer in what order  to  work  with  each  statement.
These  numbers  are also a reference point,  in case the program needs to
get  back  to  a  particular  line.  Line numbers can be any whole number
(integer) value between 0-63999.

10 PRINT "COMMODORE 64"
^    ^
|    |-- Statement
|
+------- Line number

It is good programming practice to number lines in increments of 10  --
in case you need to insert some statements later on.
Besides PRINT, our program also used another BASIC command, GOTO.  This
instructs the computer to go directly to a particular  line  and  perform
it, then continue from that point.

+--> 10 PRINT "COMMODORE 64"
|
+--- 20 GOTO 10

In our example,  the program prints the message in line 10, goes to the
next  line  (20),  which instructs it to go back to line 10 and print the
message over again.  Then the cycle repeats.  Since we  didn't  give  the
computer a way out of this loop, the program will cycle endlessly,  until
we physically stop it with the <RUN/STOP> key.
Once  you've stopped the program,  type: LIST.  Your  program  will  be
displayed, intact,  because it's still in the computer's memory.  Notice,
too, that the computer converted the '?' into PRINT for you.  The program
can now be changed, saved, or run again.
Another  important difference between typing something in the immediate
mode  and writing a program is that once you execute and clear the screen
of  an  immediate  statement,  it's lost.  However,  you can always get a
program back by just typing LIST.
By  the  way,  when  it  comes  to  abbreviations don't forget that the
computer may run out of space on a line if you use too many.

3.2. Editing Tips

If you make a mistake on a line, you have a number of editing options.

1. You can retype a line anytime,  and the  computer  will  automatically
substitute the new line for the old one.
2. An unwanted line can be erased by simply typing the  line  number  and
<RETURN>.
3. You can also easily edit an existing line,  using the cursor keys  and
editing keys.

Suppose you made a typing mistake in a line of the example. To correct
it without retyping the entire line, try this:
Type LIST, then using the <SHIFT> and <CRSR UP/DOWN> keys together move
the  cursor  up  until  it  is  positioned  on  the line that needs to be
changed.
Now,  use  the  cursor-right  key  to  move the cursor to the character
you  want  to  change,  typing the change over the old character. Now hit
<RETURN> and the corrected line will replace the old one.
If you need more space on the line, position the cursor where the space
is needed and hit  <SHIFT>  and  <INST/DEL>  at the same time and a space
will  open  up.  Now  just  type  in  the  additional information and hit
<RETURN>.  Likewise,  you  can  delete unwanted characters by placing the
cursor to the right of the unwanted character and hitting the  <INST/DEL>
key.
To verify that changes were entered, type LIST again, and the corrected
program  will  be  displayed!  And  lines  don't  have  to  be entered in
numerical order. The computer will automatically place them in the proper
sequence.
Try editing our sample program on  Section 3.1  by changing line 10 and
adding a comma to the end of the line. Then RUN the program again.

10 PRINT "COMMODORE",

Don't forget to move the cursor past line 20 before you RUN the program.

COMMODORE   COMMODORE   COMMODORE   COMMODORE
COMMODORE   COMMODORE   COMMODORE   COMMODORE
COMMODORE   COMMODORE   COMMODORE   COMMODORE
COMMODORE   COMMODORE   COMMODORE   COMMODORE
COMMODORE   COMMODORE   COMMODORE   COMMODORE
COMMODORE   COMMODORE   COMMODORE   COMMODORE
COMMODORE   COMMODORE   COMMODORE   COMMODORE
COMMODORE   COMMODORE   COMMODORE   COMMODORE
COMMODORE   COMMODORE   COMMODORE   COMMODORE
COMMODORE   COMMODORE   COMMODORE   COMMODORE
COMMODORE   COMMODORE   COMMODORE   COMMODORE
COMMODORE   COMMODORE   COMMODORE   COMMODORE
COMMODORE   COMMODORE   COMMODORE   COMMODORE
BREAK IN 10
READY

3.3. Variables

Variables  are  some  of  the  most  used  features  of any programming
language,  because  variables  can represent much more information in the
computer.  Understanding how variables operate will make computing easier
and allow us to accomplish feats that would not be possible otherwise.
Imagine a number of boxes within the computer that can hold a number or
a string of text characters.  Each of these boxes is to be labeled with a
name  that  we choose.  That name is called a variable and represents the
information in the respective box.
For example, if we say:

10 X% = 15
20 X = 23.5
30 X$ = "THE SUM OF X% + X ="

The computer might represent the variables like this:

X%  15

X   23.5

X$  THE SUM OF X% + X =

A  variable  name  represents  the  box,  or memory location, where the
current  value  of  the variable is stored. As you can see, we can assign
either  an  integer  number, floating point number, or a text string to a
variable.
The '%' symbol  following  a  variable name indicates the variable will
represent  an  integer  number.  The following are valid integer variable
names:

A%
X%
A1%
NM%

The  '$'  following  the  variable  name  indicates  the  variable will
represent a text string. The following are examples of string variables:

A$
X$
MI$

Floating  point  variables  follow  the  same  format,  with  the  type
indicator:

A1
X
Y
MI

In  assigning  a  name  to a variable there are a few things to keep in
mind.  First,  a  variable name can have one or two characters. The first
character  must  be  an  alphabetic  character  from  A to Z;  the second
character  can  be either alphabetic or numeric (in the range 0 to 9).  A
third character can be included to indicate the type of variable (integer
or text string), '%' or '$'.
You can use variable names  having more than two alphabetic characters,
but  only the first two are recognized by the computer.  So PA and PARTNO
are the same and would refer to the same variable box.
The  last  rule  for  variable names is simple:  they can't contain any
BASIC keywords  (reserved  words)  such as GOTO, RUN, etc.  Refer back to
Appendix D for a complete list of BASIC reserved words.
To see how variables can be put to work,  type in  the complete program
that we introduced earlier and  RUN it.  Remember to hit  <RETURN>  after
each line in the program.

NEW

10 X% = 15
20 X = 23.5
30 X$ = "THE SUM OF X% + X ="
40 PRINT "X% = "; X%, "X = "; X
50 PRINT X$; X% + X

If  you  did  everything  as shown, you should get the following result
printed on the screen.

RUN
X% = 15    X = 23.5
THE SUM OF X% + X = 38.5
READY

We've put together all the tricks learned so far  to format the display
as you see it and print the sum of the two variables.
In lines  10 and 20  we assigned an integer value to X%  and assigned a
floating  point  value  to  X.  This puts the number  associated with the
variable in its box. In line 30, we assigned a text string to X$. Line 40
combines  the  two  types  of PRINT statements to print a message and the
actual value of  X% and X.  Line 50 prints the text string assigned to X$
and the sum of X% and X.
Note  that  even  though  X  is used as part of each variable name, the
identifiers '%' and '$' make  X%,  X,  and  X$ unique,  thus representing
three distinct variables.
But  variables are much more powerful.  If you change their value,  the
new value replaces the original value in the same box. This allows you to
write a statement like:

X = X + 1

This would never be accepted in normal algebra,  but is one of the most
used concepts in programming.  It means: take the current value of X, add
one to it and place the new sum into the box representing X.

3.4. IF ... THEN

Armed with the ability to easily update the value of variables,  we can
now try a program such as:

NEW

10 CT = 0
20 ? "COMMODORE 64"
30 CT = CT + 1
40 IF CT < 5 THEN 20
50 END

RUN
COMMODORE 64
COMMODORE 64
COMMODORE 64
COMMODORE 64
COMMODORE 64

What we've done is introduce two new BASIC commands,  and provided some
control  over our runaway little print program introduced at the start of
this chapter.
IF ... THEN adds some logic to the program.  If  says  IF  a  condition
holds true THEN do something. IF the condition no longer holds true, THEN
do the next line in the program.
A number of conditions can be set up in using an IF ... THEN statement:

SYMBOL      MEANING
<         Less Than
>         Greater Than
=         Equal To
<>        Not Equal To
>=        Greater Than or Equal To
<=        Less Than or Equal To

The  use  of  any  one  of these conditions is simple, yet surprisingly
powerful.

10 CT = 0
+--> 20 ? "COMMODORE 64"
|    30 CT = CT + 1
+-<- 40 IF CT < 5 THEN 20
|
!
50 END

In the sample program,  we've set up a "loop"  that has some constrains
placed  on  it  by  saying:  IF a value is less than some number  THEN do
something.
Line 10 sets CT (CounT) equal to 0. Line 20 prints our message. Line 30
adds one  to the variable CT.  This line counts  how many times we do the
loop. Each time the loop is executed, CT goes up by one.
Line  40  is  our  control  line.  If  CT is less than 5, meaning we've
executed the loop less than 5 times, the program goes back to line 20 and
prints again.  When CT becomes equal to 5  -- indicating 5 COMMODORE 64's
were  printed  --  the program goes to line 50,  which signals to END the
program.
Try  program  and see what we mean. By changing the CT limit in line 40
you can have any number of lines printed.
IF ... THEN  has  a  multitude of other uses, which we'll see in future
examples.

3.5. FOR ... NEXT Loops

There is a simpler,  and preferred way to accomplish what we did in the
previous example by using a FOR ... NEXT loop. Consider the following:

NEW

10 FOR CT = 1 TO 5
20 ? "COMMODORE 64"
30 NEXT CT

RUN
COMMODORE 64
COMMODORE 64
COMMODORE 64
COMMODORE 64
COMMODORE 64

As you can see, the program has become much smaller and more direct.
CT starts at 1 in line 10. Then, line 20 does some printing. In line 30
CT is incremented by 1. The NEXT statement in line 30 automatically sends
the  program  back  to  line 10  where the FOR part  of the  FOR ... NEXT
statement  is  located.  This process will continue  until CT reaches the
limit you entered.
The variable  used in a FOR ... NEXT loop can be incremented by smaller
amounts than 1, if needed.
Try this:

NEW

10 FOR NB = 1 TO 10 STEP .5
20 PRINT NB,
30 NEXT NB

RUN
1          1.5           2             2.5
3          3.5           4             4.5
5          5.5           6             6.5
7          7.5           8             8.5
9          9.5           10

If you enter and run this program, you'll see the numbers from 1 to 10,
by .5, printed across the display.
All we're doing here  is printing the values that NB assumes as it goes
through the loop.
You can even specify  whether the variable is increasing or decreasing.
Substitute the following for line 10:

10 FOR NB = 10 TO 1 STEP -.5

and  watch  the  opposite  occur,  as  NB goes from 10 to 1 in descending
order.

4. ADVANCED BASIC

4.1. Introduction

The  next  few  chapters  have  been written for people who have become
relatively  familiar with the BASIC programming language and the concepts
necessary to write more advanced programs.
For  those of you who are just staring to learn how to program, you may
find   some  of  the  information  a  bit  too  technical  to  understand
completely. But take heart ... because for these two fun chapters, SPRITE
GRAPHICS and  CREATING SOUND,  we've set up some simple examples that are
written  for the new user.  The examples will give you a good idea of how
to  use  the  sophisticated  sound and graphics capabilities available on
your COMMODORE 64.
If  you  decide  that  you want to learn more about writing programs in
BASIC, we've put a bibliography (Appendix N) in the back of this manual.
If you are already familiar with BASIC programming, these chapters will
help  you  get  started with advanced BASIC programming techniques.  More
detailed  information  can  be  found  in  the  COMMODORE 64 PROGRAMMER'S
REFERENCE MANUAL, available through your local Commodore dealer.

4.2. Simple Animation

Let's  exercise  some  of  the  Commodore 64's  graphic capabilities by
putting  together  what  we've  seen  so  far,  together  with  a few new
concepts. If you're ambitious, type in the following program and see what
happens.  You  will  notice  that within the print statements we can also
include cursor controls and screen commands.  When you see something like
{CRSR LEFT} in a program listing,  hold the <SHIFT> key and hit the <CRSR
LEFT/RIGHT>  key.  The  screen  will show the graphic representation of a
cursor  left  (two  vertical reversed bars).  In  the same way,  pressing
<SHIFT> and <CLR/HOME> shows as a reversed heart.

NEW

10  REM BOUNCING BALL
20  PRINT "{CLR/HOME}"
25  FOR X=1 to 10 : PRINT "{CRSR DOWN}" : NEXT
30  FOR BL=1 to 40
40  PRINT" O{CRSR LEFT}"; : REM (O is a SHIFT-Q)
50  FOR TM=1 TO 5
60  NEXT TM
70  NEXT BL
75  REM MOVE BALL RIGHT TO LEFT
80  FOR BL=40 TO 1 STEP -1
90  PRINT" {CRSR LEFT}{CRSR LEFT}O{CRSR LEFT}";
100 FOR TM=1 TO 5
110 NEXT TM
120 NEXT BL
130 GOTO 20

NOTES:  The  ':' in lines 25 and 40 indicates new command.  The spaces in
lines 40 and 90 are intentional.

TIP: All  words in this text will be completed on one line.  However,  as
long  as  you  don't  hit <RETURN> your 64 will automatically move to the
next line even in the middle of a word.

The program will display a bouncing ball moving from left to right, and
back again, across the screen.
If  we  look  at  the  program  closely,  you can see how this feat was
accomplished.

10  REM BOUNCING BALL
+----> 20  PRINT "{CLR/HOME}"
| +--> 25  FOR X=1 to 10 : PRINT "{CRSR DOWN}" : NEXT
| |    30  FOR BL=1 to 40
| |    40  PRINT" O{CRSR LEFT}"; : REM (O is a SHIFT-Q)
| | +> 50  FOR TM=1 TO 5
| | +- 60  NEXT TM
| +--- 70  NEXT BL
|      75  REM MOVE BALL RIGHT TO LEFT
| +--> 80  FOR BL=40 TO 1 STEP -1
| |    90  PRINT" {CRSR LEFT}{CRSR LEFT}O{CRSR LEFT}";
| | +> 100 FOR TM=1 TO 5
| | +- 110 NEXT TM
| +--- 120 NEXT BL
+----- 130 GOTO 20

Line  10  is a REMark that just tells what the program does;  it has no
effect  on  the  program  itself.  Line  20  clears  the  screen  of  any
information.
Line 25 PRINTs 10 cursor-down commands. This just positions the ball in
the middle of the screen.  If line 25 was eliminated  the ball would move
across the top line of the screen.
Line 30 sets up a loop for moving the ball the 40 columns from the left
to right.
Line 40  does  a  lot  of  work.  It  first prints a space to erase the
previous ball positions, then it prints the ball, and finally it performs
a cursor-left  to get everything ready to erase the current ball position
again.
The  loop  set  up  in  lines  50  and  60 slows the ball down a bit by
delaying the program. Without it, the ball would move too fast to see.
Line 70  completes the loop that prints balls on the screen,  set up in
line 30.  Each time the loop is executed, the ball moves another space to
the  right.  As  you notice from the illustration,  we have set up a loop
within a loop.
This is perfectly acceptable.  The only time you get in trouble is when
the  loops  cross  over  each other.  It's helpful in writing programs to
check  yourself  as  illustrated here to make sure the logic of a loop is
correct.
To see what would happen if you cross a loop, reverse the statements in
lines 60 and 70. You will get an error because the computer gets confused
and cannot figure out what's going on.
Lines  80  through  120 just reverse the steps in the first part of the
program,  and  move  the  ball  from  right to left.  Line 90 is slightly
different  from  line  40  because  the  ball  is  moving in the opposite
direction (we have to erase the ball to the right and move to the left).
And when that's all done  the program goes back to line 20 to start the
whole  process  over  again.  Pretty neat!  To stop the program hold down
<RESTORE> and hit <RUN/STOP>.
For a variation on the program, edit line 40 to read:

40 PRINT"O";  To make the O, hold SHIFT key down and hit the letter "Q"

Run  the  program  and  see  what happens now.  Because we left out the
cursor control,  each ball remains on the screen until erased by the ball
moving right to left in the second part of the program.

4.3. INPUT

Up  to now,  everything within a program has been set before it is run.
Once the program was started,  nothing could be changed.  INPUT allows us
to  pass  new information to a program as it is running and have that new
information acted upon.
To get an idea of how INPUT works,  type  NEW  <RETURN>  and enter this
short program:

10 INPUT A$
20 PRINT "YOU TYPED: ";A$
30 PRINT
40 GOTO 10
RUN
? COMMODORE 64  <--------------- You typed
YOU TYPED: COMMODORE 64   <----- Computer responded

What  happens  when  you  run this simple program. A question mark will
appear,  indicating  that  the  computer  is  waiting  for  you  to  type
something. Enter any character, or group of characters, from the keyboard
and  hit  <RETURN>.  The  computer  will  then  respond with "YOU TYPED:"
followed by the information you entered.
This  may  seem  very  elementary,  but  imagine  what you can have the
computer do with any information you enter.
You  can  INPUT  either numeric or string variables,  and even have the
INPUT statement prompt the user with a message. The format of INPUT is:

INPUT "PROMPT MESSAGE";VARIABLE
^
+---- Prompt must be 38 characters or less

Or, just:

INPUT VARIABLE

NOTE:  To  get out of this program hold down the <RUN/STOP> and <RESTORE>
keys.

The  following  program  is not only useful,  but demonstrates a lot of
what has been presented so far, including the new input statement.

NEW

1 REM TEMPERATURE CONVERSION PROGRAM
5 PRINT "{CLR/HOME}"
10 PRINT "CONVERT FROM FAHRENHEIT OR CELSIUS (F/C): ": INPUT A$
20 IF A$ = "" THEN 10  <----------------------- No space within quotes
30 IF A$ = "F" THEN 100
40 IF A$ <> "C" THEN 10
50 INPUT "ENTER DEGREES CELSIUS: ";C
60 F = (C*9)/5+32
70 PRINT C;" DEG. CELSIUS ="; F ;"DEG. FAHRENHEIT"
80 PRINT
90 GOTO 10
100 INPUT "ENTER DEGREES FAHRENHEIT: ";F  <- Don't forget to hit RETURN
110 C = (F-32)*/5/9
120 PRINT F;" DEG. FAHRENHEIT ="; C ;"DEG. CELSIUS"
130 PRINT
140 GOTO 10

If you entered and run this program, you'll see INPUT in action.
Line 10  uses  the input statement to not only gather information,  but
also print our prompt. Also notice that we can ask for either a number or
string (by using a numeric or string variable).
Lines 20, 30, and 40 do some checks on what is typed in. In line 20, if
nothing is entered (just <RETURN> is hit),  then the program goes back to
line 10 and requests the input again. In line 30, if F is typed, you know
the user wants to convert a temperature in degrees Fahrenheit to Celsius,
so the program branches to the part that does that conversion.
Line  40 does one more check.  We know there are only two valid choices
the  user  can enter.  To get to line 40,   the user must have typed some
character other than F.  Now, a check is made to see if that character is
a C; if not, the program requests input again.
This  may  seem  like  a  lot  of  detail,  but  it is good programming
practice. A user not familiar with the program can become very frustrated
if  it  does  something  strange  because  a  mistake  was  made entering
information.
Once we determine what type of conversion to perform,  the program does
the  calculation and prints out the temperature entered and the converted
temperature.
The  calculation  is just straight math,  using the established formula
for temperature conversion.  After the calculation is finished and answer
printed, the program loops back and starts over.
After running, the screen might look like this:

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 running the program,  make sure to save it on disk or tape.  This
program,  as well as others presented throughout the manual, can form the
base of your program library.

4.4. GET

GET  allows  you  to  input  one  character at a time from the keyboard
without  hitting  <RETURN>.  This  really  speeds  entering  data in many
applications.  Whatever  key  is hit is assigned variable to the variable
you specify with GET.
The following routine illustrates how GET works:

NEW

1 PRINT "{CLR/HOME}"
10 GET A$: IF A$ = "" THEN 10
20 PRINT A$;        ^
30 GOTO 10          |-------------- No SPACE here

If you RUN the program,  the screen will clear  and each time you hit a
key,  line  20  will  print  it  on  the  display,  and  then GET another
character. It is important to note that the character entered will not be
displayed  unless you specifically PRINT it to the screen,  as we've done
here.
The  second  statement  on  line 10 is also important.  GET continually
works,  even  if  no  key  is  pressed  (unlike  INPUT  that  waits for a
response),  so  the  second  part  of  this  line  continually checks the
keyboard until a key is hit.
See what happens if the second part of line 10 is eliminated.
To stop this program you can hit the <RUN/STOP> and <RESTORE> keys.
The  first  part  of the temperature conversion program could easily be
rewritten to use GET. LOAD the temperature conversion program, and modify
lines 10,20 and 40 as shown:

10 PRINT "CONVERT FROM FAHRENHEIT OR CELSIUS (F/C) ?"
20 GET A$: IF A$ = "" THEN 20  <---------------- No space within quotes
30 IF A$ <> "C" THEN 20

This  modification  will  make the program operate smoother, as nothing
will  happen  unless  the  user  types in one of the desired responses to
select the type of conversion.
Once  this  change  is made,  make sure you save the new version of the
program.

4.5. Random Numbers and Other Functions

The  Commodore 64  contains  a  number  of  functions  that are used to
perform  special  operations.  Functions  could be thought of as built-in
programs  included  in  BASIC.  But  rather  than  typing  in a number of
statements  each time you need to perform a specialized calculation,  you
just  type the command for the desired function and the computer does the
rest.
Many  times  when designing a game or educational program,  you need to
generate a random number, to simulate the throw of dice, for example. You
could certainly write a program that would generate these numbers, but an
easier way to call upon the RaNDom number function.
To see what RND actually does, try this short program:

NEW

10 FOR X = 1 TO 10
20 PRINT RND(1),    <------------ If you leave out the comma, your list
30 NEXT                           of numbers will appear as 1 column

After running the program, you will see a display like this:

.789280697          .664673958
.256373663          .0123442287
.682952381          3.90587279E-04
.402343724          .879300926
.158209063          .245596701

Your numbers don't match? Well, if they did we would all be in trouble,
as they should be completely random!
Try running the program a few more times to verify that the results are
always  different.  Even  if  the  numbers don't follow any pattern,  you
should  start  to  notice that some things remain the same every time the
program is run.
First,  the results are always between 0 and 1, but never equal to 0 or
1. This will certainly never do if we want to simulate the random toss of
dice, since we're looking for numbers between 1 and 6.
The  other  important  feature  to look for is that we are dealing with
real  numbers  (with decimal places).  This could also be a problem since
whole (integer) numbers are often needed.
There  are  a  number  of  simple  ways to produce numbers from the RND
function in the range desired.
Replace line 20 with following and run the program again:

20 PRINT 6*RND(1),

RUN

3.60563664          4.53660853
5.47238963          8.40850227
3.19265054          4.39547668
3.16331095          5.50620749
9.32527884          4.17090293

That  cured  the  problem  of not having results larger than 1,  but we
still  have  the  decimal part of the result to deal with.  Now,  another
function can be called upon.
The INTeger function converts real numbers into integer values.
Once  more,  replace  line 20 with the following and run the program to
see the effect of the change:

20 PRINT INT(6*RND(1)),

RUN

2         3         1         0
2         4         5         5
0         1

That  took  care  of  a lot,  getting us closer to our original goal of
generating random numbers between 1 and 6. If you examine closely what we
generated this last time, you'll find that the results range from 0 to 5,
only.
As a last step, add a one to the statement, as follows:

20 PRINT INT(6*RND(1))+1,

Now, we have achieved the desired results.
In general,  you can place a number, variable,  or any BASIC expression
within  the  parentheses  of  the  INT  function.  Depending on the range
desired,  you  just  multiply  the  upper limit by the RND function.  For
example, to generate random numbers between 1 and 25, you could type:

20 PRINT INT(25*RND(1))+1,

The general formula for generating a set of random numbers in a certain
range is:

NUMBER=INT(LOWER+(UPPER-LOWER+1)*RND(1))

4.6. Guessing Game

Since we've gone to some lengths to understand random numbers,  why not
put  this  information to use?  The following game not only illustrates a
good  use  of  random  numbers,   but  also  introduces  some  additional
programming theory.
In running this program, a random number, NM, will be generated.

NEW

1 REM NUMBER GUESSING GAME
2 PRINT "{CLR/HOME}"
5 INPUT "ENTER UPPER LIMIT FOR GUESS ";LI
10 NM = INT(LI*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 30
50 IF GU < NM THEN PRINT "MY NUMBER IS HIGHER.": PRINT : GOTO 30
60 PRINT "GREAT! YOU GOT MY NUMBER"
65 PRINT "IN ONLY"; CN ;"GUESSES." : PRINT
70 PRINT "DO YOU WANT TO TRY ANOTHER (Y/N) ?";
80 GET AN$ : IF AN$ = "" THEN 80
90 IF AN$ = "Y" THEN 2
100 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 NUMBER GUESS ? 15
MY NUMBER IS HIGHER.

WHAT'S YOUR NUMBER GUESS ? 20
MY NUMBER IS LOWER.

WHAT'S YOUR NUMBER GUESS ? 19
GREAT! YOU GOT MY NUMBER
IN ONLY 3 GUESSES.

DO YOU WANT TO TRY ANOTHER (Y/N) ?

IF/THEN   statements  compare  your  guess  to  the  number  generated.
Depending  on  your  guess,  the program tells you whether your guess was
higher or lower than the random number generated.
From the formula given for determining random number range,  see if you
can  add  a  few lines to the program that allow the user to also specify
the lower range of numbers generated.
Each time you make a guess, CN is incremented by 1 to keep track of the
number  of  guesses.  In  using  the  program,  see  if  you can use good
reasoning to guess a number in the least number of tries.
When  you get the right answer,  the program prints out the "GREAT! YOU
GOT MY NUMBER" message,  along with the number of tries it took.  You can
then start the process over again.  Remember, the program generates a new
random number each time.

PROGRAMMING TIPS:

In line 40 and 50, a colon is used to separate multiple statements on a
single  line.  This  not  only  saves  typing,  but in long programs will
conserve memory space.
Also  notice  in  the  IF/THEN  statements  on  the same two lines,  we
instructed  the  computer  to  PRINT  something,  rather than immediately
branching to some other point in the program.
The  last  point  illustrates  the  reason behind using line numbers in
increments of  10.  After the program was written,  we decided to add the
count  part.  By  just  adding those new lines at the end of the program,
numbered  to  fall  between  the  proper existing lines,  the program was
easily modified.

4.7. Your Roll

The following program simulates the throw of two dice. You can enjoy it
as it stands, or use it as part of a larger game.

5 PRINT "CARE TO TRY YOUR LUCK?"
10 PRINT "RED DICE   =";INT(6*RND(1))+1
20 PRINT "WHITE DICE =";INT(6*RND(1))+1
30 PRINT "HIT 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 random numbers and BASIC, see if you can
follow what is going on.

4.8. Random Graphics

As a final note on random numbers,  and as an introduction to designing
graphics, take a moment to enter and run this neat little program:

10 REM MAZE
20 PRINT "{CLR/HOME}"
30 PRINT CHR$(205.5+RND(1));
40 GOTO 20

As  you  may have expected,  line 20 is the key here. Another function,
CHR$ (Character String),  gives you a character, based on a standard code
number  from  0  to  255.  Every  character the Commodore 64 can print is
encoded this way (see Appendix F).
To quickly find out the code for any character, just type:

PRINT ASC("X")

where  X  is  the  character  you're checking  (this can be any printable
character,  including  graphics).  The  response  is  the  code  for  the
character  you  typed.  As  you  probably  figured out,  "ASC" is another
function,  which  returns the standard "ASCII" code for the character you
typed.
You can now print that character by typing:

PRINT CHR$(X)

If you try typing:

PRINT CHR$(205); CHR$(206)

you  will  see the two right side graphic characters on the M and N keys.
These are two characters that the program is using for the maze.
By  using  the  formula  205.5 + RND(1) the computer will pick a random
number  between  205.5  and  206.5.  There is a fifty-fifty chance of the
number being above or below 206.  CHR$ ignores any fractional values,  so
half  the  time  the character with code 205 is printed and the remaining
time code 206 is displayed.
If  you'd  like to experiment with this program,  try changing 205.5 by
adding  or  subtracting  a couple  tenths from it.  This will give either
character a greater chance of being selected.

5. ADVANCED COLOR AND GRAPHIC COMMANDS

5.1. Color and Graphics

Up   to   now  we've  explored  some  of  the  sophisticated  computing
capabilities  of  the  Commodore 64.  But  one  of  its  most fascinating
features is an outstanding ability to produce color and graphics.
You've  seen  a  quick example  of  graphics in the "bouncing ball" and
"maze"  programs.  But  these  only  touched  on the power you command. A
number  of  new  concepts  will  be introduced in this section to explain
graphic  and color programming and show how you can create your own games
and advanced animation.
Because  we've  concentrated  on  the  computing  capabilities  of  the
machine,  all  the  displays  we've  generated so far were a single color
(light blue text on a dark blue background, with a light blue border).
In this chapter we'll see how to add color to programs  and control all
those strange graphic symbols on the keyboard.

5.2. PRINTing Colors

As  you discovered  if you tried the color alignment test in Chapter 1,
you  can  change  text colors by simply holding the <CTRL> key and one of
the color keys.  This works fine in the immediate mode,  but what happens
if you want to incorporate color changes in your programs?
When  we  showed  the  "bouncing ball"  program,  you  saw how keyboard
commands,  like  cursor  movement,  could  be  incorporated  within PRINT
statements.  In  a like way,  you can also add text color changes to your
programs.
You have a full range of 16 text colors to work with.  Using <CTRL> key
and a number key, the following colors are available:

1        2        3        4        5       6        7        8
Black    White     Red     Cyan    Purple   Green    Blue    Yellow

If  you  hold  down the <C=> key along with the appropriate number key,
these additional eight colors can be used:

1        2        3        4        5       6        7        8
Orange   Brown   Lt.Red    Gray 1  Gray 2  Lt.Green  Lt.Blue  Gray 3

Type NEW,  and experiment with the following.  Hold down the <CTRL> key
and  at  the  same  time hit the <1> key.  Next,  hit the <R> key without
holding down the <CTRL> key.  Now,  while again depressing the <CTRL> key
at the same time hit the <2> key.  Release the <CTRL> key and hit the <A>
key. Move through the numbers, alternating with the letters, and type out
the word RAINBOW as follows:

10 PRINT " R A I N B O W"
^ ^ ^ ^ ^ ^ ^
<CTRL><1 2 3 4 5 6 7>

RUN
RAINBOW

Just  as  cursor  controls  show as graphic characters within the quote
marks of print statements, color controls are also represented as graphic
characters.
In  the  previous  example,  when  you held down <CTRL> and typed <3> a
"{Pound Sign}"  was displayed.  <CTRL> <7>  displayed a "<-".  Each color
control  will  display its unique graphic code when used in this way. The
table shows the graphic representations of each printable color control.

KEYBOARD    COLOR      DISPLAY         KEYBOARD    COLOR      DISPLAY
---------------------------------------------------------------------
<CTRL><1>   BLACK                      <C=><1>     ORANGE
<CTRL><2>   WHITE                      <C=><2>     BROWN
<CTRL><3>   RED                        <C=><3>     LT. RED
<CTRL><4>   CYAN                       <C=><4>     GRAY 1
<CTRL><5>   PURPLE                     <C=><5>     GRAY 2
<CTRL><6>   GREEN                      <C=><6>     LT. GREEN
<CTRL><7>   BLUE                       <C=><7>     LT. BLUE
<CTRL><8>   YELLOW                     <C=><8>     GRAY 3

Even  though  the PRINT statement may look a bit strange on the screen,
when  you RUN the program,  only the text will be displayed.  And it will
automatically change colors according to the color controls you placed in
the print statement.
Try  a  few examples of your own,  mixing any number of colors within a
single PRINT statement. Remember, too, you can use the second set of text
colors by using the Commodore key and the number keys.

TIP: You will notice after running a program with color or mode (reverse)
changes, that the "READY." prompt and any additional text you type is the
same as the last color or mode change. To get back to the normal display,
remember to depress: <RUN/STOP> and <RESTORE>.

5.3. Color CHR$ Codes

Take a brief look at Appendix F, then turn back to this section.
You may have noticed in looking over the list of CHR$ codes in Appendix
F  that  each  color  (as  well as most other keyboard controls,  such as
cursor movement)  has a unique code.  These codes can be printed directly
to  obtain the same results as typing CTRL and the appropriate key within
the PRINT statement.
For example, try this:

NEW
10 PRINT CHR$(147) : REM {CLR/HOME}
20 PRINT CHR$(30); "CHR$(30) CHANGES ME TO?"

RUN
CHR$(30) CHANGES ME TO?

The  text should now be green.  In many cases,  using the CHR$ function
will  be much easier,  especially if you want to experiment with changing
colors.  The  following  program  is  a different way to get a rainbow of
colors.  Since  there are a number of lines that are similar (40-110) use
editing keys to save a lot of typing.  See the notes after the listing to
refresh your memory on the editing procedures.

NEW

1 REM AUTOMATIC COLOR BARS
5 PRINT CHR$(147) : REM CHR$(147) = CLR/HOME
10 PRINT CHR$(18); "     "; : REM REVERSE BAR
20 CL = INT(8*RND(1))+1
30 ON CL GOTO 40,50,60,70,80,90,100,110
40 PRINT CHR$(5); : GOTO 10
50 PRINT CHR$(28); : GOTO 10
60 PRINT CHR$(30); : GOTO 10
70 PRINT CHR$(31); : GOTO 10
80 PRINT CHR$(144); : GOTO 10
90 PRINT CHR$(156); : GOTO 10
100 PRINT CHR$(158); : GOTO 10
110 PRINT CHR$(159); : GOTO 10

Type lines 1 through 40 normally. Your display should look like this:

1 REM AUTOMATIC COLOR BARS
5 PRINT CHR$(147) : REM CHR$(147) = CLR/HOME
10 PRINT CHR$(18); "     "; : REM REVERSE BAR
20 CL = INT(8*RND(1))+1
30 ON CL GOTO 40,50,60,70,80,90,100,110
40 PRINT CHR$(5); : GOTO 10

EDITING NOTES

Use the  <CRSR UP> key to position the cursor on line 40.  Then type 5
over the 4 of 40. Next, use the <CRSR RIGHT> key to move over to the 5 in
the CHR$ parentheses.  Hit <SHIFT> <INST/DEL> to open up a space and type
'28'. Now just hit <RETURN> with the cursor anywhere on the line.
The display should now look like this:

1 REM AUTOMATIC COLOR BARS
5 PRINT CHR$(147) : REM CHR$(147) = CLR/HOME
10 PRINT CHR$(18); "     "; : REM REVERSE BAR
20 CL = INT(8*RND(1))+1
30 ON CL GOTO 40,50,60,70,80,90,100,110
50 PRINT CHR$(28); : GOTO 10

Don't worry.  Line 40 is still there.  LIST the program and see.  Using
the  same  procedure,  continue  to  modify the last line with a new line
number  and  CHR$  code  until all the remaining lines have been entered.
See,  we told you the editing keys would come in handy. As a final check,
list  the entire program to make sure all the lines were entered properly
before you RUN it.
Here is a short explanation of what's going on.
You've probably figured out most of the color bar program by now except
for some strange new statement in line 30. But let's quickly see what the
whole program actually does. Line 5 prints the CHR$ code for CLR/HOME.
Line 10 turns reverse type on and prints 5 spaces, which turn out to be
a bar, since they're reversed. The first time through the program the bar
will be light blue, the normal text color.
Line 20  uses  our  workhorse,  the  random function to select a random
color between 1 and 8.
Line 30 contains  a  variation  of  the  IF ... THEN statement which is
called ON ... GOTO.  ON ... GOTO allows the program to choose from a list
of  line numbers to go to.  If the variable (in this case CL) has a value
of 1, the first line number is the one chosen (here 40).  If the value is
2, the second number in the list is used, etc.
Lines 40-110 just convert our 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 over again.
See  if you can figure out how to produce 16 random numbers,  expand ON
... GOTO to handle them,  and add the remaining CHR$ codes to display the
remaining 8 colors.

5.4. PEEKs and POKEs

TAGS: ,


Comments are closed.