Timex Sinclair BASIC Primer With Graphics
Timex Sinclair BASIC Primer With Graphics
With Graphics
Timex Sinclair
BASI C Primer
With Graphics
by
FIRST EDITION
FIRST PRI TI G- 1984
All rights reserved . No part of this book shall be reproduced . stored in a retrieva l system , or transmitted
by any means. electronic. mechanical. photocop ying. recording. or otherwise. without written permis-
sion from the publisher.
o patent liability is assumed with respect to the use of the information contained herein. While every
precaution has been taken in the preparation of this book . the publisher assumes no responsibility for
errors or ommisions.
either is any liabilit y assumed for damages resulting from the use of the information contained herein .
Timex Sinclair BASIC Primer With Graphics is designed for the person
who is beginning to use a computer. It introduces the Timex Sinclair compu-
ters and teaches you how to write simple programs. By the time you've
finished this book, you'll understand how a computer works and how to
develop a program in BASIC , including graphics. Why BASIC? It is an
extremely popular computer language, taught widely in schools today at
many levels; it is also available on almost all personal computers. Knowledge
of BASIC then, puts you in a position to effectively use not one, but all
personal computers. Furthermore, it gives you an advantage over other per-
sons who are not yet "computer literate" so that you can go on to greater
investments of time and money, and to the greater returns that using a
sophisticated tool such as a computer gives you.
This book is written so t hat you can understand what is happening
whether or not you have a technical background. Jargon is kept to a min-
imum, however, when we have to use "computerese," we carefully explain the
concept behind the word. You may well find that you enjoy using the terms
that let the world know you're one of the club.
Here is an overview of the book and what it contains:
As you read this book, you'll find that one skill quickly builds on
another. Start at the beginning, read everything, try everything, and most
importantly, take your time and have fun.
This book is dedicated with love to my parents, Harriet and AI, for their
unflagging faith and unstinting support- P.c.
CONTENTS
CHAPTER I
CHAPTER 2
CHAPTER 3
BASIC TRAI ING ••..•••• ••.• • ••••••••• •.•.•••••.•••. •• •.•. ••• •• • ....• • 45
Your First Program- Anatomy of the PRI T Sta tement - Eras ing Your Program- Line
umbers - The STOP Statement - La yi ng Out the Information- Graphic Details- LET and
the Variable- The I P UT Statement- Variables at Work and Play':'-Something Really Use-
ful: Loan Payments- Recordi ng Your Program- Tape, Please
CHAPTER 4
CHAPTER 6
CHAPTER 7
CHAPTER 8
CHAPTER 9
ADVANCED BASIC: A TASTE OF THINGS To COME ••••..• ••.. .......• .•••..• 191
New Dimensions- PEEK-a-Boo- Poking Around : The POKE Command- Odds and
Ends- Perfunctory Endings
CHAPTER 10
Introduction
The odds are that, since you're reading this book, you've just purchased
your first home computer. It's a Timex / Sinclair 1500 or 1000 because you're
the curious but cautious type. You want to see for yourself what all the fuss is
about before you spend a whole lot of money buying a big fancy machine.
Well, you've made a good choice!
The Timex represents a lot of computer power for the smallest practical
investment you can make. The T / S 1500 is an updated version of the im-
mensely popular T / S 1000 computer. The first thing you'll notice is that
Timex Computer Corporation has put on a really nice and easy-to-use key-
board. They've also given the computer enough brain power to tackle some
big jobs. Using it- and this book- to start, you'll be able to begin exploring
the wide and expanding world of computers from the comfort of your own
living room at a ridiculously low price.
Of course, you will have to put in some time to learn how to use it! Even
with computers, there's no such thing as a "free lunch." Nothing this power-
ful comes without some work. We'll try to help, though, by giving you simple
examples and by making sure you have a good time while you're learning.
We' ll move at a relaxed pace, too . We'll "hold your hand" a lot in the
beginning chapters to be certain you get the hang of things before we move
on. We've tried to pause often to answer imaginary questions which, from
our ex perience, the beginner is likely to ask . We want to make sure that
several seemingly inconsequential points which often confuse the beginner
are fully explained .
This book is not meant to make you into a professional programmer!
II
TIM EX SI NCLAIR BASIC PR I M ER WI T H GR A PHI CS
Far from it. Its real purpose is to make you into a computer amateur- and
we mean this in the original meaning of the French word amateur: lover.
When you're through with this book, you'll have learned how to control a
real live computer and you'll be ready to branch out and follow your own
personal interests. If you' re going to use your computer as a word processor,
for example, you'll have a much better idea of what's going on inside the
machine while you're typing away . You'd be surprised at how far a little
knowledge of programming can go when you're trying to use someone else's
program in your computer. You'll know enough to get started on a serious
study of programming too , if you find that it suits your temperament.
You've seen the ads: " Use your computer as a word processor" (meaning
fancy-pants, super-smart typewriter); or do your famil y finances; or teach
yourself spelling or French; or, of course, use it to play games. Chameleon-
like, computers appear under a wide variety of guises . From quarter-
swallowing video games like PACMAN and Zaxxon to the quiet, invisible
sentinels keeping watch over the pot roast in your microwave oven, they are
everywhere. Soon , who knows where you' ll be finding them, perhaps in
computerized toothbrushes .
What exactly is a computer and why does everyone want to have one?
Here is one definition: A computer is a machine for processing information .
You may be asking what's information? And who wants processed informa-
tion anyway? Let's start with a familiar example of an information processor
to give you a mental picture you can use for reference: the daily newspaper.
Most big city daily papers have hordes of information in them: interna-
tional, national, and local news, weather report s, tv and radio listings, stock
prices, sports, fashion , cooking tips, want ads, help wanted , and on and on .
The newspaper tries to include a group of facts (that is "information") about
the world that is of interest to its readers . You , the reader, use the paper as
your source of " processed information" about the world .
An interested person could try to go to every ball game and sporting
event, to every council meeting and press conference, to every important
world event, and find out what's happened ; but obviousl y this is not very
12
In / roduc/ ion
INPUT
The people who work for the newspaper get their facts , their informa-
tion, from a bewildering array of different sources. This is called the input to
the newspaper, in computer lingo. There are reporters who snoop around
asking lots of nosey questions and jet off to the White House for press
conferences. News stories can come in already written "over the wires," as
they say (that is, from one of the big international news gathering services
like United Press International or Associated Press). People can call in with
"hot tips."
Moles, snooping about in the underbrush of government, leak stories to
sympathetic reporters. Press releases, churned out by the thousands, come
pouring in to the offices of all the major newspapers, informing them about
everything from the latest product announcements to what the beautiful
people are wearing this spring. The Federal Reserve Bank, the FBI , the
Department of Commerce, and hordes of other federal, state, and local
government agencies issue lengthy formal reports with great regularity. All of
these sources, and more, form the typical inputs to a large metropolitan daily
newspaper.
This seething mass of raw information, far too much to be interpreted
by anyone of us in its raw form , thousands upon thousands of pages of it
each day, is ingested by the staff of the paper and transformed (or processed)
into the 40 or so pages of your morning paper. Stories get written against
tight daily deadlines. New tables, charts, illustrations, and maps are prepared
every day. Think about it. Each word , each comma, semicolon, period, and
parenthesis, was written by someone who got information from an input
source, and processed (transformed) it for publication in the paper.
Once all the stories are written, then the type is set, printing plates are
made, and the ink is put on the rollers. Cut and folded for distribution, the
13
TIMEX SINCLAIR BASIC PRIMER WITH GRAPHICS
In all computers there are three basic elements called: I / O, CPU, and
MEMORY. (See Fig. I-I.)
14
In (r OdUN ion
numbers, using the keys. Input doesn't usually include any processing we do
to that information.
The other side of input is output. The computer has to get its answer out
to us somehow. (Otherwise how would you know what it was: ESP, Elec-
tronic Sensory Perception, maybe?) Most of the time, we'll output informa-
tion by displaying it on a tv screen.
If you want to input a lot of data, the keyboard can be an awfully slow
and cumbersome way to do it, especially when you're going to use the same
instructions or information over and over again. Your Timex is set up to get
input from an ordinary cassette tape recorder, so you can enter pre-recorded
programs and data into your computer.
You can also output programs and information by recording them on
cassette tapes. We'll tell you all about using a tape recorder in Chapter 4,
after you've had a little experience working with the computer.
15
TIM EX SI NC LA IR BASIC PRIM ER WITH GR A PHI CS
revolutionize the very nature of our existence here on earth. Because chips
can be mass-manufactured so cheaply, even the simplest of our machines,
like an iron or a toaster, will soon be "computerized." When you reflect on
the fact that the same electronic circuitry which cost thousands of dollars ten
years ago, now sells for less than $5 .00, the magnitude of changes which are
taking place in the computer industry becomes apparent.
There are a number of CPU chips on the market today. The one used in
the Timex is called a Z-80. On the outside, all chips look very much alike:
rectangular slabs of plastic standing like stiff caterpillars on their flat , metal-
lic legs, as seen in Fig. 1-2.
On the inside, there are great differences between chips. As in any com-
plicated engineering project, all sorts of tradeoffs and compromises have to
be made. Do we want this to be a fast-thinking CPU , or one that's really easy
to give instructions to, or one that's specially gifted at doing graphics or at
translating languages? The Z-80 was adopted as the workhorse of the compu-
ter industry because it's so easy to tell it what to do, that is, to program it. It's
also moderately fast and efficient.
16
In {ro du c{ion
up the words you read in your newspaper have definite size and shape and a
location in the paper. The index reports a page number where you can find a
piece of information. (In computer lingo, this is called the address of the informa-
tion.) Newspapers output their information printed on paper and it follows that
they update the information by putting out a whole new paper.
Computers, on the other hand, can store their information, electronically
coded, in special " memory" chips inside the computer. Some of the memory chips
in your Timex contain permanently written information, just like the newspaper
pages. These are called the ROM .
Other memory chips, called RAM , can temporarily store information and
then change that information under command of the CPU. This is one of the
most powerful concepts of a computer. It is the fundamental operation by which
the computer transforms or processes the information coming in. By reading
information into memory and changing it under CPU control, the information
can be processed in an almost limitless number of ways.
In written language, words have different lengths. Some of the early compu-
ters used words with variable lengths, but computer engineers soon learned that
for most computers, it's a lot more efficient to use words of uniform length. The
Timex, in common with the majority of computers on the market today (includ-
ing Apple, Commodore, Atari, and lots more) uses computer words that are eight
computer "letters" long. (Actually, they don't call them "letters" in the computer
biz, but bits. )
You can think of each letter in a computer word as being the smallest bit
of information that the computer can use. The computer doesn't use 26
letters as we do in standard English. The alphabet that it uses to represent
information has only t wo different letters! They are usually written as "0"
and " I". By using the same principle as Morse code, any letter in our lan-
guage can be represented by a combination of "1"s and "O"s, or dits and dahs.
For example, letter "A" is represented in the computer's memory by the 8-bit
computer word: 01000001.
Don't be confused by the fact that it takes an entire 8-bit computer word
to represent just one letter in our alphabet. You see, each "bit" carries only a
tiny quantity of information so you need a decent-sized group of bits to
encode the amount of information contained in the letter A .
Your Timex can store 16,256 8-bit computer words of information in
changeable memory (called RAM , remember). This works out to over 10
17
TIMEX SI CLA IR BASIC PRIMER WI T H GRAPHICS
typewritten pages of text. The designers also had the foresight to plan for a
cartridge system, similar to the one used in the popular home video-game
systems. You can plug in a hunk of permanently written memory (RO M)
containing lengthy and complex sets of instructions to the computer saying
what to do with the information that you enter into blank memory. These
lengthy sets of instructions are properly called programs. just as surely as the
computer instructions that you type in.
PROGRAMS
When you turn on you r computer, for all intents and purposes its
changeable memory (that'S RAM) is blank. It has all the potential to do
18
In / rodu('/ ion
information processing, but no one has told it what to do with the informa-
tion it takes in. That's another slick trick of computers. Not only can they
store information in changeable memory (RAM), but they can also store the
instructions to the CPU which tell it what to do with the information con-
tained in memory.
You can type in programs that control the computer's operation from
the keyboard. This book will teach you how to get the computer to process
information in the way you want. We'll show you how to write programs that
direct the computer using a special computer language called BASIC. See
Fig. 1-3 .
Fig . 1-4 .
19
TIMEX SI NCLAIR BASIC PRIMER WITH GRAPHICS
written into permanent memory, into ROM. It can translate the BAS IC
command words that you enter into words in the CPU's own internal lan-
guage. (Are you getting the hang of the many abbreviations, like RAM and
ROM, that abound in the computer field? Don't worry if you haven't got it
yet, you will by the time we're through.)
This book will tell you all about the BASIC language that is used on
your Timex. You can use this first computer as an excellent stepping-stone to
computing. So put on your thinking cap and get ready! This is the start of
something big.
20
2
Getting Started
Okay, so now you've got enough computer theory under your belt to get
you ready for the new adventure. You know what memory is and that I / O
refers to the ways of getting information back and forth between the compu-
ter and you. You're ready to set up your Timex / Sinclair computer.
Try to resist the temptation to dump everything out of the box and to
just start hooking things up. BeceJ.use your Timex is such a foolproof compu-
ter, you can't hurt anything by plugging a cable into the wrong place. How-
ever, we're trying to teach you good techniques on the Timex so that when
you have to set up a more complex system, you'll have learned the right way
to proceed.
Your first step is to check and see that everything that should be in the
box is actually there. So let's look at what you've gotten for your money.
UNPACKING
Of course, the main thing you've got to have, and the biggest thing in the
box, is your Timex computer. If it's not there, go right back to the store and
get it! Underneath the computer, you should see your Timex User Manual
and a tape cassette labeled THE ST ARTER. In the upper compartment, you
should find two cables and two, more or less rectangular, box-shaped assem-
blies. One of these is obviously made to plug into your electric outlet and has
a thin wire coming out of it that plugs into the Timex. This converts the
electricity from the IIO-volt alternating current that comes out of your line
21
TIMEX SINCLAIR BASIC PRIMER WITH GRAPHICS
outlets into the 9-volt dc current that your computer likes. The other box,
labeled "Computer/ TV ," is a switc~ing box that is used for connecting the
computer to your tv set so you can get a nice friendly form of output from it.
22
Gelfinf( Started
23
TIMEX SI CLAIR BASIC PRIMER WITH GRAPHICS
Warranty, Anyone?
Make sure to fill out and send in your warranty registration card , too.
It's important. For one thing, it will register your purchase with the Timex
Computer Corporation, which will fix the machine at no cost if anything
goes wrong during the first 90 days after purchase. Information about you is
registered when you return your card. It will also get you on their mailing list,
so that you'll receive new product announcements periodically.
Sending in your warranty will also make it known to many of the
companies that sell accessories and programs for the Timex that you are a
Timex owner. This is a good way for you to find out about many of the
myriad products and services being offered for your computer.
You might also want to get a copy of SYNC Magazine, published by
Ziff-Davis, Inc. Subscriptions are $16 .00 for six issues yearly and should be
sent to SYNC Magazine, 39 East Hanover Avenue, Morris Plains, NJ 07950.
At this point though, before you go out and spend a lot of money on
your Timex computer, you should really look and see what it can do. Infor-
mation is your best friend at this beginning stage.
A QUIET SPOT
24
GelfinK Starled
your programs on tape so you can play them back later. And, you'll probably
want to use some of the hundreds of ready-to-run programs that you can
buy.
The user's manual says that you may have some electrical interference if
you plug all three units into the same line. If you can conveniently find a spot
with access to two different power lines, great; otherwise don't worry about it
unless it proves to be a problem, which it probably won't.
I've found that it's a good idea to put the tv set in a place where it sits a
little bit higher than the computer. I have it on a shelf about 8 inches above
my desk. That way I can put my computer on my desk and still have plenty of
space for writing my programs . Having the tv set sitting above the computer
can also help eliminate some forms of interference. And it makes it easy for
you to switch from working at your desk to looking at the monitor with
comfort.
If you've got an extension cord with two outlets on it, you may want to
25
TIMEX SI CLAIR BASIC PRIMER WITH GRAPHICS
run it conveniently right up onto your desk. You may even want to add a switch
to the cord itself so that you can leave your computer plugged in and just switch
off the power to the cord . Timex recommends that you don't leave the power
supply plugged in for extended periods of time when you're not using your
computer.
Here are two more points which could make using your computer easier.
Make sure that the tv set doesn't have glare on the screen, either from the
overhead lights or from windows that face the set. You might not even realize it at
first , but check it out; glare can be one of those subliminal annoyances that can
increase tension and decrease fun .
Secondly, you'll probably find it a lot easier to work with your computer
if you can mount it firmly to a heavy surface. The nonslip feet work all right
for short periods of typing. For a longer period of time, we recommend
attaching the Timex rigidly to a board or desktop. When you have it solidly
fixed to an immobile surface, you'll see how much easier it is to use the
keyboard.
26
Gellinl? SlOrt ed
27
TIMEX SI CLAIR BASIC PRIMER WITH GRAPHICS
TER ." Be sure the switch is pushed all the way over to the COMPUTER side
because, if it isn't, you may not get a picture or you'll get horrible interfer-
ence, even though everything is working right with your computer. This
problem is likely to happen every once in a while if you use your tv for
watching broadcast shows, too, and are switching back and forth frequently
between the computer and tv.
N ow plug the video input cable into the jack at the upper left of the
Timex, marked "TV." If you turn the computer over, you'll see a switch in
the right midsection, labeled "ch2 ch3." You should set it for the channel
which is unused in your area. Remember to tune your tv set to the same
channel.
Do you have the power supply plugged in? Great, we're getting close to
the big test now.
I. Turn on your tv set and let it warm up for a moment or two. Remember
to tune it to the same channel to which you set the computer.
2. Plug in the power supply.
After a momentary pause, you should see a blank screen with a white II
in a black square in the lower left corner.
WOW! You see it! Everything worked perfectly the first time. Congratu-
lations, you've just installed your first computer.
28
CellinI{ Storied
BACK Of TV SET
If you didn't get anything even close to this, for example, if the picture is
totally black or filled with completely meaningless static, don't worry. The
odds are that there's nothing seriously wrong. Just read the chapter again
with a fresh mind and give the hookup another go . If it still doesn't display
the CI take it down to the store where you purchased it and ask them to
hook it up for you. (If they can't get it to work, see if they'll give you a new
one, and start again.)
Most of what we do in the book will not require anything more than
your Timex and your tv set. Once we start into the thick of writing programs
though, you will probably want to save your programs on tape, so we'll show
you how to use your tape recorder as a storage medium in Chapter 5. Let's
not worry about hooking it up now.
Up and Running
That little square fellow with the K on his chest, who appears when you
first power up your computer, is called the cursor. It tells you where on the
29
TIMEX SINCLAIR BASIC PRIMER WIT H GRAPHICS
screen the next character you enter will appear. It's the computer's way of
saying, "Okay, I'm ready; tell me something to do." See Fig. 2-4.
30
Gelfing SIGrled
31
TIMEX SI NCLAIR BASIC PRIMER WITH GRAPHICS
Crash Reset
Pull the plug out of the side of the Timex and reinsert it. See what
happens? The word you wrote on the screen disappears and a new 13 cursor
appears ready to receive your command. We'll call this procedure of pulling
the plug and reinserting it, a crash reset. Use this only as a last resort since
crash reset erases everything in the computer's memory and starts you out
again completely from scratch.
If you're typing in a long program, the unintentional crash reset is only a
little less welcome than terminal athlete's foot. If you follow our advice in
Chapter 5 and frequently save your programs on tape, you'll have a fairly
recent copy. For now though, since we're only typing in a line at a time to get
the feeling for the keyboard , it won't matter it we lose a line, so we'll use
crash reset to get you going.
If you're a typist, you'll see that the keyboard is laid out, for the most
part, just like a standard typewriter keyboard . We'll refer to the keys by the
letter or number that is printed in bold black on the left side. Try pressing the
P key; it's the one on the extreme right side of the third row up from the
bottom. Notice what's happened? The computer printed PRINT where the
cursor was and then the cursor changed from letter '" to II. Interesting,
huh?
Now press the same P key again . This time you don't get PRINT, just
32
CellinI{ Started
plain old P (the letter printed in bold black on the key). So the cursor not
only tells you where you are on the screen, but it also tells you what mode the
keyboard is in. That is, it tells you which of the various printed symbols
associated with a given key, the computer will actually print. So now we have
our first two simple keyboard rules.
Keyboard rule no . I: When the cursor says K the computer prints the
keywords written in white letters above the keys. These keywords are
commands in the BASIC language and make the computer DO
something.
Keyboard rule no. 2: When the cursor says L, the computer prints the
letter or number which is printed on the left of each key.
The Timex is very smart. It switches automatically from key board mode
to the leller mode, because it expects that once you type in a keyword, you're
going to want to type in some letters or numbers afterwards. You don't have
to remember to do anything. Just keep on typing.
33
TIMEX SINCLAIR BASIC PRIMER WITH GRAPHICS
probably didn't press the SHIFT and the K key simultaneously. Crash reset
and try it again. (We'll teach you about editing mistakes soon, but, for now,
if something doesn't work and you get the S cursor, just crash reset and start
again.)
This brings us to the next keyboard rule.
Keyboard rule no. 3: To get the functions that are printed in RED , press
SHIFT and the key you want simultaneously.
You can guess what's next, can't you? Add a 2 to the end so you've got
"PRINT 2 + 2" showing. Great, you've prepared your first command for the
computer to process: telling it to print the answer to 2 + 2. Now you've got to
tell the computer that you've finished typing in the command and you want it
to DO IT. You've got to enter the command line. The ENTER key is over at
the extreme right side of the second row up from the bottom. You always
have to press the ENTER key for the computer to take it in. Always! ENTER
serves the purpose of telling the computer that you're done with the line and
that you want it to do something. See Fig. 2-6.
Press the ENTER key. After a brief pause, you should see the number 4
displayed in the upper left corner of your screen. Wonderful! You could've
told it that yourself, couldn't you?
In the bottom left, you'll also see 0 /0. These two numbers are called the
"report code." They tell you whether the computer has been able to execute
the command that you've entered. A zero on the left means everything is fine.
Other numbers on the left serve to report the type of error the computer has
encountered in executing a command.
The number on the right of the slash we'll use later, when we start
running whole programs. It tells you which statement in your program has
caused the error. We'll explain these more fully as we progress and you can
find a list of them in your Timex User Manual.
If you have a % displayed, the computer is ready for your next com-
mand , just as if you had a 131 cursor showing. The next keypress is inter-
preted as a keyword . Try it. Press the P key again and you'll see "PRINT"
once agam .
34
GellinR Start ed
PRINT 2+2
ARITHMETIC BY COMPUTER
Good work! You've written and entered your first direct command into
the machine and gotten the correct answer. Take a few minutes now to look
35
TIMEX SIN C LAIR BASIC P RIMER WITH GRAPHI CS
over the keyboard and type in these commands to get some practice.
R e mem ber to enter each command after you type it , that is , remember to
press the ENTER key.
PRINT 10 - 3
PRINT 4 *4
PRINT 25 / 5
You can probably figu re out from these examples that" - " (S HIFT J)
stand s for subtraction, "*,, (S HIFT B) means multiplication, and " /"
(S HIFT V) means division . O f course, you don't have to stick to the small
numbers we've used here. You can use any number you'd like up to a few
billion (see the following box). You can use negative numbers too , just by
putting a minus sign in front of the number. Decimal points, too , are entered
normally, usi ng the "." key (second from the right on the bottom row) .
You don't have to read the information in this box if you don't want to; it
isn't essential to your understanding of computers, but I think you may find
it interesting.
Your Tim ex can handle som e pretty big numbers. Th e largesl number il
can hold wilh complele accuracy is a bil over 4 billion. 4.294.96 7.295 10 be
exacl. Now a little over 4 billion burgers is alaI o{ burgers bUlfour billion
dollars doesn'l seem like 100 much when you read aboUl Ihe federal budgel
defi cils.
To enable your Tim ex 10 k eep up with the modern. multi-billion dollar
world, the designers added a way to enter som e really big numbers. using
what's called exponential or E notation. This m eans you can ''\-'rite a large
number by expressing it as a smaller number TIMES a power of 10.
S o. f or example, let's rake a number lik e:
(A fairll ' typical budget deficir figure being bandied about.) ({ you count rhe
zeroes. vou'll see that's 2 15 fo llowed b l' 9 zeroes. We can wrire rhis using E
nora/ion as 2l5E9 or as 215 f ollowed by 9 zeros. That's a regular E in the
number. Just type the E k ey bet ween the 2 15 and the 9 and your Tim ex
36
Getting Started
aut omatically knows that yo u are using exp onential notation to enter a
really big number.
Th e smaller number is still only stored to eight significant figur es
which means you can 't have any number with more than eight digits of
accuracy. So, if yo u try to:
Order, P lease
As you can see, PRI NT is a pretty powerful statement. And not only for
arithmetic. Because PRI NT is the primary way of getting information from
the computer to you, you'll probably have more PRI NT statements in your
programs than an y other kind . In fact , we can use any of the ten calculator
function s that are built into the Timex and just use PRI NT to see the results.
So you can use your Timex as a super calculator.
You can a l 0 enter more than one operation on a line. Try:
PRINT 2*2+2
If you don't use parentheses to group the numbers into operations, the
computer groups them according to its own rules. Normally, it works its way
37
TIMEX SINCLAIR BASIC PRIM ER WITH GRAPHICS
from left to right doing the operations as it finds them . It does perform all
multiplications and divisions before it does addition and subtraction. Fig. 2-7
shows the precedence of the operators, that is, which operation is done first.
Ar ithmetic
I Unary minu s
Multlptication
Division
- 3= - 3
6'2=12
6/3=2
I
+ Addition 3+6=9
Subtraction 3- 6=- 3
Equat 2=3 false
<> Not equal to 2<>3 true
Relational < Less than 2< 3 true
I
> Greater than 2<3 false
< = or = < Less or equal 2< =3 true
> = or = > Greater than or equal 2> =3 false
NOT Logical Complement NOTI7I> =6 True
Logical AND Logical AND 5AN DIAS= BSI
~
true if AS= BS
OR Logical OR I'A"= ' B'I OR
116=2<51false
Low
PRINT 3+312 - 1
Did you guess that 3.5 is the answer? Now, try it with parentheses. Use
SHIFT I for left and SHIFT 0 for right parenthesis:
PRINT (3 +3)/ (2 - 1)
Now try:
PRINT (3+3)12 - 1
With parentheses, you can always get the computer to perform exactly
38
Gellin[J Slan ed
the calculations that you want. And it's a good idea to use them freely to
make sure that the calculation the computer is doing is what you really want.
Keyboard cursor rule no . 4: To print the white labels under the letter
keys, you have to shift the cursor by pressing SHIFT and ENTER
simultaneously. You'll see the cursor change to an F (that's F for func-
tion). Then, by pressing the key with the function you want, you'll get it
printed on the screen.
Try that now. Press SHIFT ENTER . You' ll see the cursor change to an
Ii and then when you press the H key, you' ll see SQR get printed on the
screen. Okay, enter:
PRINT SQR2
39
TIMEX SINCLAIR BASIC PRIMER WITH GRAPHICS
All along, we've been assuming that if you made a mistake you would
just crash reset the computer and type in the correct thing. There's got to be a
better way than this. After all, what's going to happen later when we've got
an entire program entered into the computer? We certainly don't want to
erase several hours of work merely to correct a mistake in just one line.
There is a better way. Your Timex computer has a set of keys just for the
purpose of correcting mistakes. To show you these keys, let's start by making
a mistake on purpose. Type:
PRINT 25 +*5
When you try to enter it, you'll see that your Timex won't even take the
line in. It just reprints the line with a menacing S in a black cursor to the left
of the *. (Fig. 2-8 .) That's another piece of your computer's built-in intelli-
gence. The II stands for syntax error. Syntax is just another way of saying
grammar, and , in this case, it means that what you've typed doesn't make
sense to the computer. It wants you to retype the line so it can understand
what you want it to do.
40
Gelfing Started
PRINT 25+0*5£!1
The 5 key has a red arrow pointing to the left to tell yo u to use SHIFT to get
to it. Press SHIFT 5 and the cursor moves one space to the left. Now it's
between the 5 and the * symbol. The S message has disappeared because the
computer knows that yo u're trying to correct the line. Look at Fig. 2-9.
4. ENTER L PR INT 25 + 1
30
5
0/0
41
TIMEX SI CLAIR BASIC PRIM ER WITH GRAPHICS
SHIFT 7
fr
SHIFT 5 <i=J c::C> SHIFT 8
SHIFT 6
Now is a good time to try typing in and editing some things until you feel
really comfortable working the editing keys . Try:
PRINT 2478*351
PRINT 459081234
PRINT SQR 69802
Once you get through with these, you should have a pretty good idea of
42
CellinR Start ed
how to type things into the computer. From now on, we will just tell you to
type in the command and expect that you can follow along.
A program is nothing more than a list of commands, just like the ones
you've been typing in. Instead of entering them one at a time, we can store
the list in the computer's memory and have it automatically go from one
instruction to the next.
So, take a break and get read y for the next chapter where, in no time,
we'll get you started writing real programs!
43
3
BASI C Training
45
TIMEX SI CLAIR BASIC PRIMER WITH GRAPHICS
To type in the number, type the I key first and then the 0 (zero) key .
You'll see that the cursor doesn't change to L when you start the line with a
number. That's because it knows that when you start a line with a number,
you're going to be writing a program line, not a direct command. It expects
that a keyword will follow the number.
You should be able to figure out how to type in quotation marks . Since
they're printed in red, you have to use SHIFT P . The space key, which prints
as a blank, can be used for separating words. It's the rightmost key on the
first line up from the bottom of the keyboard . Don't forget to type in the
quotation mark at the end of the line or you'll get a syntax error.
When you finish typing the line, press ENTER. You'll see the tv screen
blip and the statement you just typed in get printed exactly as you typed it in,
line number and all, at the top of the screen. (See Fig. 3-1.)
The arrow after the line number pointing to the statement indicates that
you've just entered that line successfully into the computer's memory. In
computerese, we will call it the current line. Now the line has been entered
into the computer's memory, but it hasn't been executed yet. It's just being
stored waiting for your next move. You can add more statements to this
46
BASIC Training
simple program or you can get the computer to actually process the program,
or as we say in computerland, get the computer to run the program.
Just type RUN (that's the R key, right?) and follow this by ENTER .
After a brief pause, you'll see:
BASIC IS FUN
appear at the top of your screen and a report code 0 / 10 at the bottom.
Congratulations, you've just written and run your first program.
Remember, the 0 in the report code means no problems. The lOin the
second place tells you that the computer stopped at line 10, the last (and also
the first) line of your program.
Notice that we've used PRINT in a new way here: to print out words on
the screen, instead of the results of some mathematical calculations. By
putting quotation marks around something in a PRINT command, you can
get the computer to print out exactly what you've typed between the quota-
tion marks.
So PRINT can not only do mathematical calculations for you, but it can
put on the screen any letters or numbers you want. In fact , your Timex also
has a special set of "graphics" characters you can use to print pictures on the
screen, too, and we'll show you these later.
Press ENTER again , and yo u'll see that your program is still in the
computer's memory just as you wrote it. You can run it again if you like, just
by typing R UN and ENTER.
47
TIMEX S I CLAIR BASIC PRIMER WITH GRAPHICS
That's the keyword over the A. Try it. The program that was listed disap-
pears and you're ready to go again with a blank computer memory.
Now, try typing in this program:
10 PRINT T'
20 PRINT "AM"
30 PRINT " FRIENDLY"
Remember, you have to enter each line to get it stored in the computer's
memory before you go on to the next one. As you enter the lines into the
computer's memory, you should also see them displayed at the top of your
screen. Now, run the program and you'll see:
I
AM
FRIENDLY
Sure, it is. Notice that our report code now says 0 / 30. Can you under-
stand why? Of course, because the computer encountered no problems and
executed your program all the way through to the last statement at line 30.
LINE NUMBERS
As we said before, line numbers tell the computer in what order it should
execute the program. It starts with the smallest number and moves upwards.
You don't even have to type the lines into the computer in the correct
48
BASIC Training
numerical order. It puts the lines in order automatically as you enter them
into memory.
Erase the old program and try typing in this one
Did you notice how the computer listed the second line ahead of the first
line you had typed in? Now run the program and you'll see:
LIKE
YOU
Nice computer.
N ow when you enter this line, you'll see that it has been added in its
proper place to the list between statements IO and 20. Try running the
program and you'll get:
I
DONT
LIKE
YOU
You can see that the order the computer uses to execute the statements is
determined by the line numbers. Can you guess why we use line numbers that
are multiples of ten? That makes it easy to add new statements into the
program that's already in memory between existing line numbers, if we need
49
TIM EX SI NC L A IR BA S IC PRIM ER WI T H GR A PHI CS
to make any changes or corrections. And you most certainly will need to
make lots of changes and corrections as your programs get more and more
complex . Most professional programmers do it this way, so we're going to
start you off on the right foot by getting you in the habit of doing it, also .
On your Timex , you can give your program lines any number ranging
from 0 through 32767. That's a lot of statements, far more than you're ever
likely to need in a program and far more than the Timex memory can hold ,
so you don't have to worry about running out of line numbers.
I
LIKE
YOU
RUN 20
LIKE
YOU
50
BASIC Training
Barring any mistakes encountered along the way, the computer will run
your programs from the beginning to end . Sometimes though, you may want
it to stop somewhere in the middle. Just like a good dog, your Timex under-
stands the command STOP. For instance, add the line:
25 STOP
That's SHIFT A. And run the program. As shown in Fig. 3-3, you'll see:
~'KE}~
(Printed by the PRIN T statements)
(This code tel's you what happened)
9/25 . J
See, the computer didn't even get to the last line. The 9/ 25 in the report
code tells you that a STOP statement was encountered that stopped , or as
they so colorfully put it in the land of bits and bytes, terminated execution,
on line 25. (Check your Timex User Manual if you want to look at a com-
plete list of the report codes.)
Thus far , we've printed out only one word or number on a line, but this
can get rather wasteful of space. We can easily get the computer to print out
more than one item at a time by listing each one we want printed and
separating the list by commas. That's SHIFT " ." (the second key in from the
right on the bottom row) .
51
TIM EX SI NC L A IR BASIC PRIM E R WI T H GRAPHI CS
10 PRINT 5+5.5 - 5
You'll see the computer do the first addition and print the answer on the left
side of line I and then it does the subtraction and prints the answer at the
middle of the same line. The comma tells the computer to move out half a
line and then print the following value.
The Timex uses a line that is 32 spaces across from left to right. They're
numbered from 0 through 31 with 0 the leftmost column . Using a comma
automatically advances the print position to the 16th position on the line.
You can even have more than two items in a PRINT statement separated by
commas . See Fig. 3-4.
Let's modify the line we have by add ing two more items to the PRINT
Line numbers
I
I
21
52
BASIC Training
list. If you've got the program in memory already, you can modify any line
without having to start completely from scratch. To do this, press:
SHIFT EDIT
That's the key on the extreme left side of the top row. See what happened?
The current line (the one pointed to by the arrow) gets rewritten back down
at the bottom of the screen. It's got the cursor in it too, just sitting there
waiting for you to make some changes.
Remember how to use the keys to move the cursor? (S HIFT 5 or 8.)
Move it to the end of the line by pressing the SHIFT key and tapping the 8
key repeatedly. It's a little slow-moving, perhaps, but eventually you get
there. N ow you simply keep on typing. Change line IO by adding: ,5* 5,5 / 5 so
that it reads:
Run it. After the computer prints the answer to 5 - 5, the next comma
causes it to skip half a line, over to the beginning of the second line where it
prints again starting at column O. The next comma makes it move out to the
middle of the second line before it prints the answer to 5/ 5. This shows you
how commas arrange things in columns.
Now try this one. Put a semicolon between the two expressIOns. A
semicolon is SHIFT X.
10 PRINT 5 +5;5 - 5
When you run the program, your answers are printed on the same line, only
now they're printed one right next to the other. Semicolons between items in
a PRINT statement cause the computer to print items without spaces inbet-
weenthem. This shows you how semicolons put things together on the
PRINT line. See Fig. 3-5.
53
TIMEX SINCLA IR BASIC PRIMER WITH GRAPHICS
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
...1
31 ~ Column
N,mb",
l
10 PRINT 5+5:5'5 displays as:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 31 ~ Colu m n
N,mb,"
Fig . 3 - 5 . Comma prints at columns and semicolon prints next to (with no spaces) .
See if you can guess what this will do before you run it. All right, run it.
How about that! Not only do you get your answer, but you can get the
computer to help you remember what the question was. You'll be using this
technique of combining printed strings and calculations over and over again.
54
BASIC Training
SHIFT ENTER first and then pressing the P key. Remember to put in the
semicolons after the numbers following TAB so that the computer knows
that you want to print what follows right after the TAB column. (Can you
guess what would happen if you put a comma there? Try it.)
As you can see, when you run this program, TAB is very easy to use.
You just type in the column number that you want to start printing and TAB
does the rest. When you use TAB, remember that columns are numbered
from 0 through 31, giving you a total of 32 spaces per line. Experiment for a
little while with different TAB settings so you can see exactly where on the
line TAB places things. Notice that you can put numbers in TAB that are
greater than 31 and the computer will just move over and start printing on
the next line (Fig. 3-6).
o 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
o
~ TAB 32: · x· prints on Ihe nexlline.
GRAPHIC DETAILS
Numbers and letters are important, there's no doubt, but we all know
that any computer worth its chips can draw pictures. Or, as they say in the
computer business, has "graphics capabilities." In fact, your Timex has, built
right into it, a remarkably good set of graphics symbols that you can use to
draw pictures. You can combine these built-in picture elements into some
really great looking displays on your tv set. Throughout the rest of this book,
we' ll try to emphasize graphic output as we learn the important words in the
BASIC programming language.
Guess what, you use the old familia r PRINT statement to get the gra-
phics up on the screen. But first you have to learn one more keyboard cursor
rule:
55
TIMEX SI CLAIR BASIC PRIMER WITH GRAPHICS
Keyboard Cursor Rule No.5: Shift into the graphics mode to print
picture elements by pressing: SHIFT 0 (that's the zero key).
This will make the cursor change to G. To get out of graphics mode,
again press: SHIFT 0
Voila! The cursor changes to a G (which stands for Graphics). Now type the
word: BOLD so the line reads:
10 PRINT " BOLD
Neat. The Timex prints the letters "B 0 L D," only now they are rev-
ersed: white on a black background. It looks the way the cursor usually does.
To end the PRINT statement, you have to shift out of graphics mode to
type in the final quotation mark. Just press SHIFT 0 (zero) again, and you'll
see the cursor change back to an L. Finish off the PRINT statement with a
quotation mark, as always. N ow run it. As you can see, this is good for effect
and for emphasizing certain words. You can type any letter or number key,
including the space key, and get it printed in reverse. Experiment and see
how the letters look in graphics mode.
You Ought To Be in Pictures
But wait. Didn't we say you could draw pictures, too? This is the really
fun part. There's more to the graphics mode than just reversed letters.
Go into graphics mode again and try pressing SHIFT R . Instead of a
reversed letter iii you get a little picture: a little square with a smaller square
bite taken out of the lower left corner.
Try SHIFT T; you'll get a checkerboard. Or SHIFT H, a gray box. Get
the idea? In graphics mode, you can print out any of the little figures drawn
on the right side of the keys. You have to remember though, that to print out
the pictures, you've got to be in graphics mode AND use the SHIFT key.
You print out the graphics picture elements exactly the same way that you
print out strings of letters.
56
BASIC Training
Try this little program so you can see how drawing pictures with gra-
phics characters works. (I'll list the keys you have to use by their letters so it's
easy for you to find them on the keyboard , but you've got to see a I!I cursor
and use the SHIFT key to get to them .) Remember, too, do not shift into the
graphics mode until you've typed the opening quotation mark. And finally,
you have to get out of graphics mode (back to the " cursor) before you type
the final quotation mark.
Now, in graphics mode, remember to shift all the characters except 00
and type:
10 PRINT '"YTYT'"
20 PRINT '"ROOE '"
30 PRINT '"8YT5 "
40 PRINT '"8FF5 '"
Don't forget , you have to hold SHIFT down for the letters in quotation
marks. Now run the program and what do you get, a funny little clown. See
Fig. 3-7 .
57
TIM EX SI NCLAIR B ASIC PRIMER WITH GRAPHICS
Poor guy, he seems a little cramped sitting there over at the upper left
corner of the screen, doesn't he? If you put a comma in front of each string,
you could move it over to column 16; or you could use TABs to move him
anywhere on the line.
10 PRINT ,"YTYT"
20 PRINT ," RODE "
30 PRINT ,"SYT5 "
40 PRINT ,"SFF5 "
How about moving him down some to give him some head room? Well,
one way would be to put some blank PRINT statements in the front of the
program; try these statements:
5 PRINT
6 PRINT
Since each new PRINT statement starts a new line, this will move our friend
down two lines from the top. This can be kind of clumsy though. It also takes
up space that we'll need once we start writing longer programs. The designers
of the Timex have provided a better way: using a PRINT statement with AT .
After entering line I 0, you'll want to bring line 20 into the editing buffer.
58
BASIC Training
How? Simple, just use the SHIFT 6 key to move the current line pointer
down one line . Then, if you press SHIFT EDIT, line 20 will be brought into
the working area. Now you can easily move throughout your programs and
bring in any line you want for modifications. Remember to use graphics
mode and the SHIFT key for the Rand E; now change line 20 to read :
20 PRINT AT 11 ,14;"ROOE"
Run the new program and you'll see our little devil smiling comfortably out
from the middle of the screen. See Fig. 3-8.
59
TIM EX SI C LA IR BASIC PR I M ER WI T H GR A PHI CS
puter at what line you want to print. The lines are numbered from 0 to 21 ,
with line 0 at the top of the screen and line 21 at the bottom. This may be a
little confusing at first, since if you want to print one line above another on
the screen you have to print the former AT a lower line number than the
latter. We'll guide you until it becomes second nature.
The second number tells the computer which column on the line it
should begin printing, just like the TAB command. Each line has 32 columns
across.
It's easy to draw all sorts of pictures on the screen. You just have to
figure out how to combine the picture elements to get the image you want. To
design your picture, all you have to do is sketch it on chart paper that has 0 to
32 marked across the top and 0 to 21 marked down the left side. Then use
PRINT AT to place the strings of graphic characters which make up your
finished picture at the correct coordinates. Take a few minutes now to exper-
iment, drawing some pictures on the screen and getting them in the place you
want them , until you feel comfortable designing pictures with the graphics
set.
It may take you a while to get the feel of how the graphics elements
combine to get nice pictures. You'll be surprised at how the different picture
elements fit together to form patterns. You can make your string as wide as
the screen, so be bold!
In the next couple of chapters, we'll show you how to use the picture
drawing capabilities to make pictures that move, and how to draw all sorts of
graphs . Let your creative juices flow; enjoy it. You're on your way to being
an accomplished computer artist. And you know just about everything there
is to know about one of the most important words in the BASIC language:
PRINT .
It's the time to move on into the wonderful world of variables . You may
remember variables from your high school algebra class: all those squiggly
little X's and V's that helped you solve problems. Your computer can work
with variables too. In fact, this is a very powerful feature, as you'll soon see.
And , it's more convenient than having to type in numbers all the time.
60
BASIC Training
Try to imagine that deep inside the computer there are stacks of little
boxes. Each box can hold a number inside it. And just as important, each
box has a label on it so you can refer to it by name. This is shown in Fig. 3-9.
The first box is called A and it contains the value 2. The second box is
called B and it contains the value 23 .8. The third box is called X and it
contains the value 32. You can tell the computer what to name the boxes and
what to put in them using a LET statement. That's the keyword above the L
key.
Clear out the memory and try this program:
10 LET X= 25
20 PRINT X
When you run it, you'll see 25 printed in the top right corner of the screen.
Change line 10 to read:
When you run the program this time, you'll see that the computer prints
out the new value that you've assigned to X. By changing the value in the
LET statement, we've changed the value that was put into the variable box
61
TIM EX SINCLAIR BASIC PRIM ER WI T H GRAPHICS
labeled X. When the computer gets to line 20, it prints the value that has been
stored in X. See Fig. 3-10.
LET X
10 LET A =5
20 LET B= 10
30 LET C= 15
40 LET X=(A+ B+C) / 3
50 LET " THE AVERAGE IS ";X
The first three LET statements put values into variable boxes named A,
B, and C. Notice that we didn't put quotation marks around the X. When the
computer comes across letters in a PRINT statement that aren't in quotation
marks, it checks to see if there is a variable box with that name. If it finds
one, the value sitting in the variable box is printed. See Fig. 3-11.
Strings
You can put words or graphics characters into variable boxes, too. The
only trick is that you have to tell the computer that the box contains a
STRING of characters , instead of a number, by adding a $ on the end of the
variable's name. Try this:
10 LET A$ = "SLEEPY"
20 LET B$ ="GRUMPY"
30 PRINT A$,B$
Believe it or not, strings can be combined into bigger strings with the
62
BASIC Training
CRAMPEDSQUEEZEDWORDS
63
TIM EX SI NC LA IR BASIC PRIM ER WI T H GR A PHIC S
The computer took the three words we had stored in separate strings,
A$, B$ , and C$ . It joined them into one big string called D$ . Then it just
printed the string D$. It's a little tough reading those cramped words, isn't it?
Can you think of a way to make it easier? How about adding a space at the
end of each word before the final quotation mark? Type:
A lot easier to read , no? You see, a space counts just like any other
character when you use it in a string. Remember this; it will come up again
and again as you start writing programs that print lots of "stuff' out on the
screen for you to read . We'll give you more practice on this point soon, just
to make sure you feel at home with the idea.
Variable Names
Because each letter of a variable's name has to be stored in the compu-
ter's memory just like any other information, the designers of the Timex
decided to limit the length of the names of the variables to only two charac-
ters. The first one always has to be a letter. The second character can be
either a letter or a number. So you can use A for a variable name, or X, or
HI , or even QQ . If your variable is a string variable, you always have to add
the "$", but that doesn't count as one of the two allowed characters, so LL$ is
fine and so is V I $ . If you use a variable name that is not allowed by the
computer, it won't let you enter the line. N ow try:
When you try to enter this line, you' ll see that mean, old II cursor,
telling you that the computer doesn't like what you've typed in .
You don' t have to worry about running out of names for variables . With
64
BASIC Training
just two letters and numbers, you can have over 500 different variables, more
than the computer's memory can hold, and plenty for all but the largest and
most complicated programs.
When you run this program, you'll see "ENTER YOUR NAME"
printed at the top of the screen. The cursor will appear in the work area with
quotation marks surrounding it (Fig. 3-12) .
65
TIM EX SIN C L A IR BASIC PRIM E R WI T H GR A PHIC S
"PHILLlP " g
Notice how we used a PRINT statement to tell you which variable the
computer wanted you to enter. When you start writing programs which
require you to enter several different variables, how else are you going to
know which is which? Let's modify the program a little so it can do
something.
66
BASIC Training
50 LET D=A*364.25
60 PRINT " YOU ARE "; 0 ;" DAYS OLD, ";N$
Remember the spaces make it legible. Notice that when you are asked to
enter your age, instead of the quotation marks around the cursor, you'll see
the regular " cursor. This means that your computer is expecting a number
for the next variable you are going to enter. If you type in a letter, you'll get
an error number 2 in the report code. If you run this, you'll see, as Fig 3-14
shows:
Just as before, you can EDIT your numerical answer as much as you like
before you enter it. See Fig. 3-15 .
The INPUT statement on line 20 took your name and put it in N$. The
INPUT statement on line 40 put your age in years into the variable A. Line
50 does the calculation and puts the results into a variable called D, which
gets printed by line 60 . Hope it doesn't make you feel too old.
Any place that you could type in a number or word, you can use a
variable instead. You just have to remember that you must define the varia-
ble using a LET or INPUT statement before you use it. Otherwise, the
67
TIMEX SI CLAIR BASIC PRIM ER WITH GR A PHI CS
computer will also give you the old heave ho: a report code error of 2/ line
number.
Next, you'll get to learn about incrementing a variable. Try this
program:
10 INPUT A
20 PRINT A
30 LET A=A+ 1
40 PRINT A
Wait a minute. How can A be equal to A plus I. That's not like any
mathematics you've ever seen before, right? Remember how we told you to
think of variables as being like boxes with names on them and, that the
computer looks in a given box when you write the name of the box in the
statement line. The LET statement stencils a name on the box, and then
stores in the box the quantity expressed by the right side of the equal sign. All
we're doing here is saying to the computer add I to the current contents of A
and put that result into A again. It's really very simple and not in the least bit
contradictory, right? You can think of it as looking like Fig. 3-\6.
Remem ber TAD and PRINT AT? Well, you can use variables in these
statements, too. For example:
68
BASIC Training
Run this one. When you are asked to enter a st ring, you can use the
graphics character set just by shifti ng into graphics mode before you enter
69
TIM EX SI CLAIR BASIC PRIM ER WITH GRAPHICS
the string. Now you can enter whatever you want and tell the computer to
put it anywhere you want on the screen for you, automatically.
You're really writing programs now. And so far you've only learned how
to use three keywords: PRINT , INPUT , and LET . That's a lot of power.
There are hundreds of programs you could write with just these statements.
Throw in the graphics set and reversed video and the possibilities are endless.
The real trick to programming, as you can probably begin to see from
our examples, is to put all of the individual commands together in the right
order to get the computer to do what you want it to do. The computer is
completely nonthinking. It just does exactly what you tell it, in the sequence
specified by the line numbers of your program .
Let's put everything together now into a program that will do something
for you. We'll write a short program that figures out your monthly payment
on a loan. If you've ever applied for a loan and wondered just exactly how
they figure out what your monthly payment should be, this program will give
you the answer. Once you've got it, you'll be able to see how bad the " dam-
age" will be when you decide to put that big new computer system on credit.
Any real programming job begins in your head . First, you have to figure
out exactly what it is you want the computer to do. In our case, we want to
type the following data into the computer:
After you enter that, we'll have the computer do the calculations and print
out the amount of the monthly payment. We'll use a mathematical formula
developed by bankers which enables them to calculate the monthly payment
given these three numbers .
For the variables, use I as the interest rate per month, L as the total
amount of the loan, and M as the term of loan in months. If the term I + I is
unfamiliar to you, don't worry. You've already used the key on the Timex
70
BASIC Training
that will enable you to do that calculation; it's the ** key, shown in red over
the H key.
To translate this formula from a math formula into BASIC, zust go
from top to bottom and from left to right and group the operations with
parentheses, like this:
Don't worry if you can't really understand the formula or the mathemat-
ics involved. As long as you type the LET statement correctly, we guarantee
that it'll work . We've used parentheses to make the order of operations clear
and unambiguous.
One thing you should notice is that the formula uses the interest rate
expressed as a monthly percentage, not the rate you would ordinarily think
of, which is usually stated as the yearly percentage, i.e. 12.9% financing for
that new car. We might as well make it easy on ourselves and have the
computer convert for us from the yearly to the monthly rate by dividing by
12. You could enter the repayment time in months since this is what the
formula uses, but why should you have to do any arithmetic? The computer's
good at that type of thing and much faster and more accurate. So we'll
convert from years to months by computer, too.
We know that we'll have to use some INPUT statements to take in data,
some PRINT statements to tell us what to type in and to print out the
answers, and some LET statements to do the calculations that come up with
the answer. Naturally, we'll want to print out the results in an easy-to-read
format.
Okay, let's write the INPUT section. First, write the statements that deal
with the amount of the loan:
Now we have all the variables we need. Let's do the conversions and calcula-
71
TIM EX SI NC LAIR BASIC PRIM ER WI TH GR APHI CS
tions. Since the interest rate was entered as a numerical percentage of 12 or 13.3
(or even 18), we have to convert it first to a decimal fraction , and then from a
yearly to a monthly rate. Easy enough, if we divide by 100 and then by 12.
To convert from percent, use: 12% / 100 = . 120 per year and .12 / 12
months in a year = .0 I per month. The BASIC statements look like this:
We've used lots of parentheses to make things clear and to make sure that
the computations are done in the right order. Now, let's print out the result using
this PRINT statement:
When you've checked to make sure that each line is correct, run the pro-
gram. Your screen will look like Fig. 3-17.
72
BASIC Training
If your answer matches this sample, you've just written your first pro-
gram that does something useful. Congratulations are in order.
Perhaps you are still left with a unsatisfied feeling. Each time you enter
the numbers asked for, they disappear into the computer without a trace left
on the screen. That makes the program much harder to use. You have to
remember what values you entered for the different variables. There's no
reason you should have to do that, since the computer has a perfectly good
memory which already has the values stored in it.
Let's add a few PRINT statements to the program to make it easy for
you to use:
12 PRINT LA
22 PRINT RT; " %"
32 PRINT YR
That's much better, isn't it? (Can you see in Fig. 3-18 how to put
the print out on the same line as the questions? Just add semicolons to the
end of lines 10, 20, and 30. N ow when you enter something it is immediately
echoed on the screen so you can see what numbers you' re dealing with. Run
the LOAN program now and you'll probably agree that it's a lot easier to use.
Before we go, maybe you'd like to see how much total interest you' re
going to pay on the loan, too . It's easy enough. The total amount of money
you' re going to pay back is 12 times the number of years- call it M - times
the amount you pay per month. If you subtract the original amount that you
borrowed , variable LA , from this figure , you'll get the total amount of inter-
est you've paid for the use of the money. To do this, add:
73
TIM EX SI NC L A IR BASIC PRIM ER WI T H GRAPHICS
90 LET T=(A*M) - LA
100 PRINT " TOTAL INTEREST PAID : ";T
And just to make things even easier, let's make a plot showing the ratio
of interest to total amount borrowed. It's simple using the TAD statement as
shown in Fig. 3-19.
-t
P R INC I PAL
Basically, we want to plot a solid line which represents the total amount
of money borrowed . You can use the graphics character set for emphasis. In
graphics mode, the space gets printed as a black square. Type these
statements:
For line 110, type 5 inverse spaces, type PRINCIPAL in graphics mode, and
finally type 6 inverse spaces. Line 115 is 20 inverse spaces.
Now we want to put a square beneath the bar representing the total
amount of interest paid expressed as a fraction of the total loan amount.
How do we find the right location for this square which represents the
amount of interest paid?
Well, we know that we have to make the following ratio hold:
74
BASIC Training
Run this new improved program and you'll see the difference a few
PRINT statements and some graphics can have on your understanding of the
figures. See Fig. 3-20.
PRI NCIPAL
75
TIM EX SI NC LAIR BASIC PRIM ER WI T H GRAPHI CS
don't need to use any fancy models either, just about any cassette recorder
will do. In fact , except for some of the very cheapest models, the less expen-
sive recorders seem to work with fewer problems than many of the more
expensive ones.
Remember the double-stranded cable that came in the box with your
Timex? It's time to dig it out now, because that's the cable that we'll use to
attach the computer to the tape machine as shown in Fig. 3-21 .
POWER CORD
Take a look at the left side of your computer. There are still two jacks
that aren't being used. They must be the ones! MIC (for microphone) is used
to send the program from your computer into the tape recorder. It should be
connected to the input jack on your tape recorder, whether it is labeled
"MIC," "Microphone," "INPUT," "CH I ," or ''IN .''
Put one end of the plug into the computer output and the other end into
the input to your tape recorder. If you're using a stereo recorder, it doesn't
matter which channel, though many people have less trouble using the left
channel. It seems to have something to do with the position the signal is
being recorded on the tape.
76
BASIC Training
T APE, PLEASE
After both sides of the cable are securely connected, put a fresh tape into
the recorder. I'd recommend using as short a tape as you can find for record-
ing your programs. There are a number of advantages to this. For one thing,
you don't have to spend a lot of time looking for one little program, lost in
the middle of a 45-minute tape. Unlike your favorite album, where you can
distinguish one song from the next, programs all sound alike. And terrible!
The data is just a horrible screeching noise, like transistors frying. So you
can't sit there for long listening to the tape for your program to come up.
You can put a voice announcement before each program, and use the
footage counter to find the approximate distance into the tape to begin, but
this method , too- I've found from sad practical experience- is not really
very efficient. The best policy is to use short tapes and record only one, or
maybe two, programs per side.
Use a good quality tape, too, if you can. You don't want to spend several
hours laboring over a hot computer, only to lose all your work because of a
fault y tape. Some stores are even beginning to sell special computer data
tapes with only 10 or 20 minutes of recording time. These are excellent for
recording your programs, which will never exceed 20 minutes loading time.
With your program in memory and your tape machine plugged in and ready
to roll, type:
SAVE is the keyword over the S key. Include the quotation marks around
the word TEST but DON'T PRESS ENTER YET!
77
TIMEX SI CLAIR BASIC PRIMER WITH GRAPHICS
This saves the program on tape and gives it the file name TEST. We
don't use a line number here, though we could if we wanted to make a
program that would save itself. You do have to use the quotation marks
around the file name TEST. See Fig. 3-22.
MEMORY
r~~~~~-_;::~r-,L r-~
.- r - r- - ~- ,-- " ,..-- ~
r- r r- r- r- - r ' r- r-
SAVE co pies a program from
memory to the tape.
Zero the footage counter of your tape machine, then press PLAY and
RECORD to start the tape rolling. Press ENTER on the computer.
You should see some thin black lines start dancing across the screen .
This is normal. It means that the program is being output from the computer.
Eventually, in our case, fairly quickly, since we're saving such a short pro-
gram, the lines stop writhing and you'll see a report code % (meaning
A-OK) and an otherwise blank screen. Stop the tape and rewind it to zero.
Playback
Now we're going to try reading the tape back into the computer. Plug
the other cable into the jack on the computer labeled "EAR." It could also be
called "Computer Input, " since it's the route to get programs into the com-
puter. The other end of the cable, naturally enough, goes into the EARphone
jack on your tape recorder which very likely is labeled: "OUTPUT," "OUT,"
78
BASIC Training
"CH lOUT," or "CH2." If you're using a stereo recorder, make sure you take
the output from the same channel that you recorded to.
Clear the memory and type in:
ENTER
79
TIM EX SI C L A IR BASIC PRIMER WITH GRAPHICS
If you still can't get anything, try loading some of the sample programs
supplied on the tape that comes with your computer. The directions are
simple. Try loading the demo program, LIFE. If you can't load from the
demo tape, try another tape recorder. Most of the time that will clear up the
problem and you'll be ready to go.
lf your tape recorder loads the demo program all right, but you can:!
load one of your own, try another tape. The computer data is stored as
high-frequency sound bursts and poor tape quality can make it difficult for
your computer to get an accurate reading of the information coming off the
tape.
Here are a few hints for successful recording experiences. Try recording
your programs twice in a row on the tape. That way if you don't load it
successfully the first time, you can try loading it a second time without
having to rewind the tape. Also, it's a good idea to include a piece of paper
with the tape cassette, giving the program name (and a listing).
Here's another valuable hint. If you forget the name of a program on the
tape, you can always load it by cueing the tape recorder up to the right spot
on tape and typing:
LOAD ....
(That's two quotation marks.) Now the computer will load the next program
on the tape regardless of the program's name. It's also a good idea to put
your program's name in a REM statement at the very front of your program,
just in case.
Have you got tape recording down? Good! Back in the saddle, bucka-
roos; it's time for more programming.
80
4
Well, are you starting to feel like a programmer yet? You should be, yet
you've only got three keywords under your belt: PRINT, LET, and INPUT.
Even though there's a whole lot you can do with just these three, you're
probably thinking that there's got to be more to programming than this.
Something is lacking. Thus far, we've really been using the computer only as
a smart calculator. Instead of having to type in each operation over and over,
you get the computer to store the program in its memory for you, so that, if
you want to go through the same sequence of calculations again with differ-
ent numbers, it's easy. Just run the program again.
The computer is rather stubborn, though. Maybe it reminds you of one
of your bull-headed friends. It has a one-track mind. When it executes or
runs a program, it just goes through the program listing in the same dull
order each time. One at a time, plodding along from line to line until it
reaches the end of the program or finds some kind of error. Surely computers
have to be smarter than this if they can make all those razzle-dazzle video
games work.
In this chapter, we're going to learn about some of the keywords that
you can use to allow the computer to make decisions. By the end of the
chapter, you'll have some programs that show a lot of vitality and look good.
GOING IN CI R CLES
The first keyword to help us get the computer out of its straight line rut
is GOTO , the keyword over G . It might look like the name of an Indonesian
81
TIM EX SI CLA IR BASIC PRIM ER WI T H GRAPHICS
mixed drink the way it's printed on your screen, but it really stands for GO
TO. And , as you might have guessed , it tells the computer to GO TO some
line other than the one immediately following .
Type in this tiny program and run it.
Whew, that's a lot of work from one little two-line program. Do you see
what's happening? The computer prints HELLO as it's told on line 10, and
then , when it gets to line 20, the GOTO tells it to go back to line 10 again.
When it gets back to line 10, it does what it's told; it prints "HELLO" and
then doggedly moves on to line 20 where it comes up against that GOTO
again. See Fig. 4-1 .
Being the faithful machine that it is, it just goes back to line 10 again,
prints "HELLO" and then jogs right along. It'll do this until it runs out of
room on the screen, as indicated by a report code 5/ 10.
Looping
Because running out of room to print on the screen generates an error
condition, the computer stops . If there was no error message, then it would
just keep on like this forever. The computer doesn't get tired, and it doesn't
think to itself, "Hey, this is getting boring." It just loops over and over and
over and over. You can use GOTO to move backwards or forwards to any
line in the program that you want (Fig. 4-2).
In computer lingo, GOTO is called an unconditional branch because,
whenever the computer sees a GOTO , it just GOes TO the line listed with no
questions asked. It's still not very smart and it is pigheaded , but now, at least,
82
Decisions. Decisions. Decisions
the computer can automatically repeat some group of statements over and
over. This concept is called looping in computerese and is very, very
powerful.
As we move along, in this chapter and throughout the book, you'll find a
great deal of what a program does, happens inside one of these repetitive
loops. Looping can get a lot of work done with only a few statements. It's a
real time saver!
Clowning Around
Try this program with our little clown face from last chapter. Type the
characters except 00 in shift-graphics mode:
83
TIM EX SI CLAIR BASIC PRIMER WITH GRAPHICS
him to stop? As we say in the computer game, we're "hung up" here in an
infinite loop, and this time there's no error message to finally take over and
stop the darn thing.
The computer designers have thoughtfully included a key which helps
you escape from these loops. It's called the BREAK key and it's located on
the bottom right corner of the keyboard . Try it; press BREAK and you'll see
the clown stop talking and the report code 0 / 60. This indicates that you
pressed BREAK when the computer was getting ready to do line 60, so it
halted there. The program's still safe in memory though, as you can check by
running it again.
You can halt any program at all, whether it's in a loop or not, by
pressing BREAK . And , if you want to see your program listed again to make
any changes, all you have to do is press ENTER and edit away.
You can get the program to start again where it left off by using the
CONTinue key, located over the C key. You don't have to give it a line
number, either. If you continue our little clown program, all you get are his
chattering teeth because the loop at lines 50, 60 , and 70 was just set up to
print that last line over and over again and the program never gets back to
line 10 to print the upper part of his face. See Fig. 4-3.
So maybe he's only the Cheshire Cat in disguise! Anyway, you've seen
now how to get the computer out of its linear rut. Now it can go in circles!
KEEP ON CHUGGING
We're off to a good start but we really need some more thinking power.
Clear the decks and try this:
10 LET X=O
20 PRINT AT 10X " EEE4"
30 PRINT AT 11,X;"WWAA"
40 PRINT AT 12X " R0701 " (Use SHIFT R, non-shifted letter 'oh:
SHIFT 7 again, 'oh ' again, and SHIFT 1.)
50 LET X=X+ 1
60 GOTO 20
84
Decisions. Decisions. Decisions
When you run this program, you'll see a little bus start up on the left of
the screen and move across to the right until it eventually runs out of room
and you get the report code B/ 20. Officially, the report says "Integer Out of
Range," whatever that means . In our case, it just means you can't be printing
at a location greater than 32 (Fig. 4-4).
You should be able to figure out what's going on here. Line 10 says let X
start off with the value O. In computer parlance, this is called initializing the
value of X . That's just a fancy way of saying we want to make sure that X has
85
TIM EX SI C LA IR BASIC PRIM ER WITH GR A PHIC S
a certain beginning value each time we run the program. Lines 20 through 40
print the bus; line 50 adds one to X and line 60 says go back to line 20 and
print the bus again. Only this time the value of X is one greater than the
initial value. So, instead of printing the bus at 10,0 the computer begins
printing at 10,1. Then at line 50, X, which currently equals I, is made one
bigger and the drawing process is repeated. The next PRINT is at 10,2, and
so on, until the bus crashes off the right side of the screen. The pieces even
overflow to the left side but don't worry about that now!
First off, let's get rid of the smear of pollution following the bus. Maybe
it's an old diesel with bad tuning, but let's at least make it look like it's fit for
the roads . All we have to do is add a blank to print at the left side of the bus.
So change each PRINT line to include a blank:
10 lET X=O
20 PRINT AT 10,X;" EEE4"
30 PRINT AT 11 ,X;" WWAA "
40 PRINT AT 12,X;" R0701 " (Use the letter 'oh· .)
50 LET X=X+ 1
60 GOTO 20
This way, each time we go through the loop, we are printing a blank
character in the spot where previously we had printed a graphics character.
Now run the new improved program and you see a spritely little bus that
stays sharp-looking. See Fig. 4-5 .
What about the problem of the bus running off the end of the screen?
We have to get the computer to use its brains a little more and apply a bit of
logic to the situation. We want it to check and see if there's any more room to
PRINT AT on the line, before we tell it to go ahead and print. So the
computer should check if there are enough spaces and then act accordingly.
A Little Intelligence
From the picture, we can see that when X is equal to 27, we' re going to
run over the line the next time we pass through the loop. So we want to tell
the computer that it should stop when X = 27 . Try adding this statement to
your program:
86
Decisions. Decisions. Decisions
IF is the keyword over the U key; THEN is SHIFT 3. Now, instead of just
doggedly going through the loop over and over again, we've imposed a
condition on the loop so we can take control of it and get the computer to
stop when it should .
Conditionals are among the most critical statements used in any pro-
gram because they're the ones that give the computer some intelligence, some
capacity for making decisions (Fig. 4-6) .
87
TIMEX SI NC LAIR BASIC PRIM ER WITH GRAPHI CS
We've put in a STOP on the other side of the THEN , but you can
substitute or replace it with any keyword you like. Very often an IF THEN
statement is used in conjunction with a GOTO statement.
Try adding these lines to your program:
This time when we make our conditional test, we tell the computer that
IF the condition is true, THEN we want it to go to another location in our
program. So, on the 27th loop through, when X = 27 , the statement "G OTO
I 00" is executed and the computer GOes TO line 100 and begins processing
there. At I 00, we tell it to print a message.
Add these few statements and you can start your bus on an endless
journey:
88
Decisions. Decisions. Decisions
110 PAUSE 30
120 CLS
130GOTO 10
PAUSE is the keyword over the M key; CLS is the keyword over the V key .
P A USE on line 110 "pauses" the program for 30 time units. Each time
unit is equal to 1/ 60 of a second, so PA USE 30 just halts the computer for
1/ 2 second before going on to the next instruction .. You can PA USE for up
to 32,767 time units, (a little under ten minutes).
If you enter a number greater than that, the computer will halt until you
press any key on the keyboard and restart again. Then it will move on to the
next instruction as if nothing had happened.
On the Timex, the PAUSE command has a tendency to slightly disrupt
the display. Did you catch the blip on your set? We'll show you a better way
to make graphic pauses later on.
CLS , as you see when you run the program, CLears the Screen. It's like
an eraser. As we write graphics programs that are more complex, you're
going to have to erase the whole screen from time to time and here's the
simple way to do it.
When you're tired of seeing the bus take its endless journey, you can
stop it using the BREAK key.
LOOP-THE-LOOP
As you can see, loops help you get a lot done with only a few statements.
They are so widely used that BASIC has two keywords specifically used for
setting them up. Since it takes two keywords to make this one work, we' ll
introduce FOR and NEXT together.
Clear the memory and type this in.
10 FOR X= 1 TO 15
20 PRINT " X= " ;X;" FOR LOOP NO. "; X
30 NEXT X
FOR is the keyword over the F key, and NEXT is the keyword over the
89
TIM EX S I NC LAIR BASIC PRIM ER WI T H GRAPHICS
ADD 1 TO X
If it hasn't reached this value yet, then it just goes back up to the
statement following the FOR and goes through the loop again, this time with
the value of X one greater than the last time through . On the 15th loop
through, when we get to the NEXT statement, X is incremented and equals
16. At this point, when the comparison is made, the computer finds that X is
greater than 15, the value specified after TO in the FOR statement. Now the
computer jumps out of the loop and goes on to the statement following
NEXT .
Any loops you can do with IF THEN's you can do with a FOR NEXT.
90
Decisions, Decisions, Decisions
10 FOR X= 1 TO 15 10 LET X= 1
20 PRINT X 20 PRINT X
30 NEXT X 30 LET X=X+ 1
40 IF X= 15 THEN STOP
50 GOTO 20
STEP is SHIFT E. You don't have to use whole numbers like I, 2, 3 in your
FOR NEXT loops. You can let X have any value you want and increment X
by any value you want each time you go through the loop. For each circuit
through, the value of the STEP (increment) is added to the variable and at
the corresponding NEXT statement, a test is made to see if the incremented
value of X is greater than the value after TO. See what the value of X is when
the loop is finished? Just one step above the value after TO .
You can also use negative numbers in the FOR NEXT loop. Try using
this little skeleton program to see how the loop works with negative numbers .
91
TIMEX SI CLAIR BASIC PRIMER WI T H GRAPHICS
Lining Up
If you haven't guessed it already, loops just like the ones we've been
looking at make and move all those wonderful displays around in your video
games. Let's see if we can print a simple graphics image: a straight line.
10 FOR X= l TO 10
20 PRINT AT X.; ··. ··
30 NEXT X
0000000000
Fig . 4-8 . Printing a straight line .
a nice line. Try changing the value of the number to get a feeling for where
different numbers put the line on the screen. Try using PRINT AT X,5.
Want to print a horizontal line? Just switch the order in the PRINT AT
statement. Try adding:
It's the same principle, only in the other direction. Here again, by chang-
ing the number, you can move the horizontal line around on the screen.
Try this program that lets you enter characters from the keyboard and
use them as the elements of lines so you can see what different combinations
look like.
92
Decisions, Decisions, Decisions
You can enter any character you want at the INPUT line, and you'll see
what it looks like in horizontal and vertical lines. Try inputting single gra-
phics characters so you can see what kind of lines they make. You have to
shift into graphics mode first , right?
Action
Lines are okay, and pretty easy, but let's add a little action . Here's the
beginning of a tennis game program:
10 FOR X= 1 TO 20 %RR
20 PRINT AT X,1;''T'';TAB 20;"Y" (Use graphics mode and SHIFT
key for T and Y.)
30 NEXT X
40 LET A =2
50 PRINT AT 10,A; " . " (inverse space)
60 PRINT AT 10,A;"" (regular space)
70 LET A =A + 1
751F A =- 2 OR A = 19 THEN LET A =- A
80 GOTO 50
The OR statement on line 75 is SHIFT W. Run this and what do you get?
Not a bad little ball court. See Fig. 4-9 .
Lines 10 through 30 are a loop to print the two side walls . Line 40
initializes the loop that prints the ball. Do you see why we start at A = 2?
Sure, it's because we have printed our ball at wall. (Try letting A = I , and see
for yourself.) Line 50 actually prints the ball, and line 60 is there to make sure
that the ball gets erased each time after it's printed so it's not just a straight
line across the screen. You saw the same principle before when we made our
little lost bus .
Line 70 increments the value of A which determines where the ball will
get printed next. It's the statement that makes the ball move. See Fig. 4-10 .
Line 75 is our conditional. It's the statement that makes the ball bounce
between the two walls . Let's look at it carefully.
What happens when A equals 18? We know that the ball is now at the
wall so we want to change its direction. This means that we want to start
making A get smaller, instead of larger. Its next value should be 17, then 16,
93
TIM EX S I CLAIR BA S IC PRIM ER WI TH GRAPHI CS
• • • • • • • • • • • • • • • 1920
f-
f-
f-
• r-
f-
f-
f-
r-
f-
10 f-
f- ••••••••••••••••••
r-
f-
r-
• f-
r-
-
r-
20
--
-
then 15, etc. Well, when we let A = - A, the next time through, the loop A
has the value - 18.
You might think that trying to PRINT AT a negative number would
give you an error message, but the Timex has more foresight than this . The
designers knew that it doesn't make any sense to PRINT AT a negative
location, so they made the PRINT AT statement use only the numerical part
of the argument and disregard the sign. This can come in very hand y, as you
will soon see. (If we needed to, we could use the ABS function , under the G
key, to do the same thing. ABS just takes a number and strips away its sign,
so every number that comes back from ABS is a positive number.)
As we go through the loop, when we get to line 70 and add I to A, since
94
Decisions. Decisions. Decisions
00 • • • • • • • • • • • • • • • • • • • 20
I l-
2 I-
3 f-
f-
l-
•••••
f- • •
l- • •
f- • •
l- • •
t- • •
l- • •
r- • •
r- • •
r-
f0-
r-
r-
r-
r-
20 f0-
r-
o I 2 3 20
95
TIMEX SINCLAIR BASIC PRIMER WI T H GRAPHICS
00 • • • • • • • • • • • • • • • • • • • 20
I ~
f-
--
f-
.--- •
-- •
•
- •
.---
•
•
•
-- •
•
f- •
l-
f-
l-
f-
f-
l-
I-
20 ~
f-
Notice that we can combine tests for more than one condition at a time
using our IF statement. In our case, we wanted to check for two different
possibilities: A = - 2 or A = 19. If either case was true, we want to change
A into -A. We can connect our two conditions using the OR connector in
our IF statement. We can also combine two or more conditions using the
AND connector (SHIFT 2) if we want both the conditions to be true before
we take the action following THEN.
Got your bouncing ball bouncing? Let's give it a little more action by
having it move up and down as it bounces. Add these lines:
96
Decisions, Decisions, Decisions
These lines print the top and bottom of the ball court. N ow we want to get
the ball to move up and down (WOW!) too. You're probably thinking that
we have to put the ball in some kind of loop that makes a variable move it up
and down by changing the value in a PRINT AT statement. Follow along,
it's easy.
We have to make the expression that controls the line printed on, into a
variable. So change lines 50 and 60 to read :
We should initialize H first , so t hat the computer will know what line we
want the ball to start on . It's a little tricky because line I is way up at the top
of the screen , so you have to use a bigger number to start the ball lower
down. Let's start it near the bottom .
15 LET H= 15
We've also got to increment H so the ball actually moves up and down:
65 LET H= H+ 1
going out of bounds at the top and bottom . Well, the logic is the same as
before, so the same type of IF statement should work just fine.
Run this one Uust like the other one) and you've really got something going.
Why, it almost looks like that famous game that everyone knows started the
video game revolution.
See what happens when you change line 65 to read:
97
TIMEX SI CLA IR BASIC PRIM E R WITH GRAPHICS
65 LET H=H+2
Interesting. You get some bigger bounces but you bounce right on
through the upper wall. What happened? Well, when we changed the incre-
ment from I to 2, that caused us to pass right on through the IF boundary
condition, because H never does get to equal -2. Since we are subtracting 2
each time (Fig. 4-12) , and we started with an odd number, we'll never get an
even number as our answer. After X = 3, the next time through it equals - I ,
NOT -2.
o I • • • 5 • • • • 10 • • • • 15 • • • • 20
f-
I--
I--
f-
f-
f- •
I--
f- •
10 f-
f-
I--
I--
f-
15 f-
f-
f-
I--
f-
20 f-
I--
98
Decisions. Decisions. Decisions
RELA TIONSHIPS
So let's try to be a little more specific and get the conditional absolutely
right. We want to make sure that when the ball is at line 3, it starts moving
down again. So let's try:
Run the program again. It may be a little better since it doesn't go off the
screen. However it does get trapped down at the bottom.
AHA , you see the problem , don't you? When we check the conditional
statement, after the first time H is made negative, H = - 19 which is less
than -2! (Tricky, those negative numbers.) So the loop is just getting caught
up jumping back and forth between 17 and - 19. You can see this for yourself
by putting in:
77 PRINT H
99
T IM EX S I CLA IR B AS IC PR I M E R WI T H GR A PHI CS
(You didn't think you'd get to use ABS so soon did you? It's the function
under the G key.) Voila! A ball with some speed that stays in bounds .
As an exercise, see if you can modify the program so that it asks you
how much velocity to put on the ball, using an INPUT statement at the front
end . Also try adding an INPUT statement that will ask where to start the
ball. You may have to change some of the conditionals to take care of special
cases, but you should be able to do that easily using our example of the
tennis-game program as a guide.
10 FOR X= 1 TO 20
15 LET H= 15
20 PRINT AT X,1;' T ';TAB 20;"Y" (Use graphics mode and
SHIFT key for T and Y.)
25 PRINT AT 1,X; "G " (Use graphics SHIFT G)
26 PRINT AT 20X " F" (Use graphics SHIFT F)
30 NEXT X
40 LET A = 2
50 PRINT AT H.A; ..... (inverse space)
60 PRINT AT H.A; " .. (regular space)
65 LET H= H+ 2
70 LET A =A + 1
751F A =- 2 OR A = 19 THEN LET A =- A
76 IF H= 19 OR H< - 2 THEN LET H=- H
80 GOTO 50
Announcing INKEY$
We're moving, but there is still something essential missing. You can't
take control of a program while it's running and make the display do what
you want, when you want. Each time you run the program, the computer just
goes through its lists, perhaps going in circles if ordered to, testing things to
see when to leave the circle. But what about you? Don't you feel left out? The
100
Decisions. Decisions. Decisions
designers of the Timex didn't want you to feel left out of things, so they have
included the BASIC function that lets you take direct control of the action
from the keyboard.
10 LET A$ =INKEY$
20 PRINT A$;
30GOT010
101
TIMEX SINCLAIR BASIC PRIM E R WI T H GR A PHI CS
10PRINT AT 10,10;"YTYT"
20 PRINT AT 11 ,1O;"ROOE "
30 PRINT AT 12,1 0;"BYT5"
40 PRINT AT 13,1 0; " BFF5"
50 LET A$=tNKEY$
60 IF A$ ="O" THEN GOTO 40
70IFA$ = "C"THENPRINTAT13,10;" _ "
BOGOTO 50
Can you follow the logic of this program? First, we draw our clown with
statements 10 through 40. Next, we check to see if either the key (the "oh") °
or the C key has been pressed (at lines 60 and 70) . You can see that the equal
sign works just as well for strings as it does for numbers. Line 60 compares
the value of A$ with 0.
If A$ is an 0, we return to line 40 where a PRINT statement opens the
clown's mouth and then returns to line 50 to check the keyboard again.
If A$ isn't an 0 , the program continues on to line 70 where it checks to
see if the C key has been pressed. If C was pressed, so that A$ = "C", the
program prints a graphic that closes the clown's mouth before it returns to
line 50 for another check of the keyboard . By switching back and forth
°
between and C, you can be the puppeteer and control opening and closing
of the clown's mouth directly and instantly from the keyboard! See Fig. 4-14.
NO
OPEN THE
CLOWN·S
MOUTH
CLOSE THE
CLOWN·S
MOUTH
CHECK THE
'--~~ KEYBOARD
AGAIN
102
Decisions. Decisions. Decisions
Let's add one more feature before we finish off this chapter and let you
take a break . We'll put in a little wink button just for fun. First we have to
add another IF THEN conditional to check to see if we want a wink. How
about:
That should give us control of the wink. So let's add it in. The characters
you type are all graphics SHIFT except the ·oh's.
Run this and you'll get a sly little wink every time you press W. If you
keep pressing, the clown keeps winking. The wink's a bit too fast though,
don't you think? We can slow it down with PAUSE, if we want. Try adding:
205 PAUSE 10
The blip is annoying, isn't it? Well, we told you there's a better way and
here it is. It's really a little trick you can use. Change the program to read :
205 FOR 1= 1 TO 10
206 NEXT I
All we are doing here is adding a loop that does nothing at all except use up
time. When the computer gets to 205 it starts a loop and goes on to line 206 .
When it gets there, it just loops back to 205 , 10 times. Because each pass
through the loop takes a small, but finite , amount of time, the effect is just
like pausing the computer, only this time there are no annoying blips to
worry about (Fig. 4-15).
Try experimenting with different values in the FOR statement until you
get a wink that looks right to you. Increasing the final value of the loop
variable will increase the delay introduced by the loop.
103
TIM EX S I C LA IR BASIC PRIM ER WI T H GR A PHI CS
NO
You are cooking with gas now. You can print all sorts of things on the
screen, make decisions to give your programs some intelligence, and control
graphics displays. Maybe you should take a break now before we move on to
hooking up your tape recorder and some more graphics .
104
5
Plotting Along
You've seen how to draw on your scree n with PR INT AT. The state-
ments you need to use are a Little Long maybe and a little cumbersome, but
you can draw some nice-looking pictures. In this chapter, we're going to
introduce a new and easier way of drawing on the screen. There's a built-in
command called PLOT, that's made for putting simple pictures on your
screen. It's on the left side of the keyboard over the Q key.
Try out this program:
10 PLOT 20.20
When you run this one, you'll see a Little dot get plotted left of center on your
screen. It's smaller than the square space that you get using PRINT, as you can
see by adding this line to your program:
20 PRINT AT 11 .8;... ..
In fact, if you compare them you'll find that it's one-fourth the area of the
big space: half as wide and half as tall. So we say in the computer world, PLOT
has a higher resolution than PRI NT AT. In fact, it has four times the resolution
that PRI NT AT does.
This little square dot that makes up the plotted point has a special name:
it's called a pixel. You can't really call them dots, of course, because everyone
knows that dots are round , not square; but computer people wanted to have
105
TIM EX SI CLA IR BA SIC PRIM ER WITH GRAPHICS
a name for the smalkst picture element you can use, so they came up with
pixel, which sort of sounds like "picture element" said fast.
Because it uses a smaller-sized basic picture element (or pixel) than
PRINT AT , the PLOT statement can make more detailed pictures. If you've
been paying attention, you'll probably be saying to yourself now that any-
thing you could do with a pixel, you could recreate using the PRINT AT and
some of the special graphics characters . That's theoretically true, but you'll
soon see how much easier it is to use PLOT for most applications.
Notice how much simpler the PLOT statement looks than the PRINT
AT . There's a lot less to write when you use it. In fact , though you may not
even notice it, PLOT is faster for the computer to execute than PRINT AT .
And it uses less memory, too. Of course, with PLOT you don't get your
choice of characters. PLOT comes in any shade or style you want, as long as
it's a small black squa re. You can think of PLOT as dividing up your tv
screen into a gridwork of squares that can be either black or white.
There are a total of 2816 possible boxes on the screen: 64 running across
from left to right (in the same direction as the X axis in Cartesian coordi-
nates, if you remember them from high school). And 44 running up and
down (in the same direction as the Y axis in Cartesian coordinates).
Notice in Fig. 5-1, this is exactly twice as many positions in each direc-
tion as PRINT AT; or twice the resolution.
You plot a pixel by writing its location; first, the column number (or the
X direction), then the row number (or the Y direction). Let's try plotting a
few more points just so you can get a feel for the screen. Now see if you can
write a short program yourself that lets you enter the coordinates into the
PLOT statement from the keyboard. Give it a tryon your own before you
look at the following program and see how we do it.
106
Plotting Along
Row numbers
I
I
\1
o 1 2 3 4 5 6 7 8 9 10 11 12 13 14 63 ~ Column numbers
43
42
41
40
39
38
3i
36
35
34
o
Area reserved for the computer
50 PRINT X;","; Y
60 GOTO 10
You probably didn't think to add line 50 which actually prints out the
values that yo u're plotting, but this will help you see where things end up and
help you associate locations on the screen with numbers, so it's useful to
have.
Do you see how this short program works? You enter the coordinates
into variables X and Y, and then plot them at line 40 . Don't forget to press
ENTER after each coordinate yo u want to feed into the computer. The next
PRINT statement (following PLOT) prints out the coordinates right after
the plotted location . So whenever you plot something, it's easy to label it,
too. All you have to do is follow the PLOT with a PRINT statement.
You can freely mix PRINT AT graphics and PLOT graphics . All you
have to do is remember that PRINT AT and PLOT use different systems of
addresses. Add these few lines to your program so you can get a feeling for
how to mix the two.
107
TIM EX SI CLA IR BASIC PRIM ER WI T H GR A PHI CS
Now, after you plot a point, you get a chance to PRINT AT a point, too,
so you can see how they match up. Fig. 5-2 presents a picture of the two
systems to make everything crystal clear.
"t- --------------------------/
22 0 '-
PLOT rows
PRINT rows
108
Plotting A lonl?
ERASE. You'll see the dot disappear. You see, UNPLOT works just like
PLOT , only it turns black squares to white. It also moves the cursor position
which determines where the next character will be, in this case unPRINTed,
just like PLOT .
You can see this by adding:
to your program. 00 PS! Did you get a report code B/ 40? That means you
entered a number that was too big for PLOT or UNPLOT. You can't use an
X value greater than 63 or a Y value that's greater than 43.
There's a tricky little point here that you may have missed. We said that
there were 64 boxes across, so how come you can't use a number greater than
63? That's because it's more efficient for the computer to start at 0 and count
up to 63 than it is to start at I , as we humans do, and count up to 64. It takes
up less total memory to start at O.
What about negative numbers in PLOT? Try it; you should know by
now that you can't hurt the computer. The computer just takes the absolute
value (remember ADS from before?) of the number you enter, just as we saw
in PRINT AT in the last chapter.
Okay, let's clear the memory and try plotting a line.
10 FOR X=OTO 63
20 PLOT X. 21
30 NEXT X
15 PLOT X. 0
25 PLOT X, 43
Do you follow how the FOR NEXT loop works to make the straight
lines? Each time the computer passes through the loop, X gets bigger by I
109
TIM EX SI CLAIR BASIC PRIMER WITH GRAPHICS
and simply plots one more space over to the right on each circuit. Since the
second place in the PLOT statement is filled by a constant, we are always
plotting along the same row, in this case, at either Y = 0 or 21 or 43. The
value of the constant Y coordinate determines how far the line is from the
bottom of the screen . 0 is the lowest you can go and 43 is the highest for a
total of 44 lines.
How about vertical lines? Can you figure out how to make them? Try
adding these statements to your program.
D PRINTS NEXT
EJ ~ PRINTS NEXT
PRINTS NE'T
B
Fig . 5-3 . How lOOPs make lines .
Do you get the idea? To draw a vertical line you have to step Y in a FOR
NEXT loop and keep X constant. The value of the X coordinate determines
how far over from the left side of the screen the line starts. 0 is way over on
the left and 63 is the farthest right you can go. See Fig. 5-3.
Add these lines:
and you'll put full borders all around the screen area that you can use to plot
on.
110
Plo f/ inf.: A l o nf.:
Don't worry about the way the picture is blipping while the computer is
working to plot out everything. You'll see a good picture when it's complete.
Each time the computer goes through the loop , it has to replot the picture at
the same time it is doing some statement processing, so the picture gets
broken up as the computer struggles to do two things at once.
Nesting Loops
How about filling in a whole block on the screen? A couple of FOR
NEXT loops should do it. Clear the memory and try this little program to
start.
10 FOR X= 25 TO 35
20 FOR Y= 18 TO 28
30 PLOT X,Y
40 NEXTY
50 NEXT X
R un this and you'll see a black square plotted on the screen. Notice the
order in which the computer plots everything out here. Vertical lines are
plotted starting from the bottom and moving upward s. The vertical lines
themselves are plotted in sequence moving from left to right.
Here's how the program works. First, we set a value for X on line 10, in
our case, 25. Then, we start a FOR NEXT loop with X. At the following line
(20), we set a value for Y, namely 18, and then start another FOR NEXT
loop, this time for Y. We're still in the X loop so when we get to line 30, we
plot out the point 25,18 and then move on to line 40. At 40, we test Y and,
since Y is less than the final value of 28 , we add I and go back to line 20 to go
through the Y, (or inner) loop again.
This time we PLOT 25 , 19; then it's 25,20 and 25,21 and so on. Again
and again, we plot through the loop until eventually Y equals 28. Instead of
going back to line 20, we go on to line 50, where X is now compared to the
values specified in its FOR NEXT on line 10. Since X is less than 35, we add
I and start the outer or X loop over again, only this time X equals 26.
When we enter the inner or Y loop again, Y is set equal to 18 and the
entire inner loop process is repeated, with X equal to 26. When we exhaust
the inner loop again, X will get set to 27 , then to 28, etc. Get the picture?
III
TIM EX SINCLAIR BASIC PRIMER WITH GRAPHICS
In computer talk, putting one loop inside of another is used so often that
it has been given a special name in the trade. We call these nested loops.
You'll see how useful they are for doing all sorts of repetitive tasks. The only
thing you've got to remember is that the inner loop has to be entirely within
the outer one. You can't overlap your loops or you'll get into trouble (Fig.
, 5-4) .
FOR - - - - - - - - . . . .
FOR~
FOR
Let's finish this introduction to PLOT with a simple program that you'll
love. It'll enable you to take complete control of the plotting routine of your
Timex so that you can draw directly on your screen under control from the
keyboard. We'll also incorporate the UN PLOT statement so you can erase
with ease.
You probably have a fairly good idea of how we're going to proceed at
this point, right? We'll use INKEY$ just as we did in Chapter 4, to have the
computer check the keyboard so you can take control. We'll also use some IF
THEN statements to check which key was pressed so that we can have the
computer respond the way we want it to.
Just for fun, let's keep the box-drawing program as part of our new
program which will give you something to start. So let's begin our new
program at line 100. Add these lines:
112
Plo lting Along
You might think we're getting a little batty here. First unplotting X, Y
and then plotting it! But try it first before you growl and see what you get.
You might ask, why not plot first and THEN unplot? The answer will be
clear in a moment.
You see by rapidly plotting and un plotting the pixel, we get a place
indicator that blinks at us so we will always know where it is on the screen.
We'll call this our cursor and, if you've run the program, you'll see it blinking
at you from the lower left side of the screen.
Remember how to use INKEY$ to check the keyboard? Just add this
line right over line ISO:
Up Set Y to Y+ l.
Down Set Y to Y-l.
Right Set X 10 X+ l.
Left Set X to X-I.
Let's use the arrow keys just as they appear on the keyboard to control
the cursor. You can use any keys you want to stand for the directions; just be
consistent. We'll show you the first one and you'll be able to figure things out
from there on your own:
113
T IM EX S I NCLA IR B AS I C PRI ME R WI T H G RA PHI CS
10 FOR X=25 TO 35
20 FOR Y= 18 TO 28
30 PLOT X,Y
40NEXTY
50 NEXT X
100 LET X=O
101 LET Y=O
110 UNPLOT X,Y
111 PLOT X,Y
150 LET A$=INKEY$
160 IF A$="5" THEN LET X=X - 1
161 IF A$= " 8" THEN LET X=X + 1
162 IF A$= " 6" THEN LET Y=Y - 1
163 IF A$= " T' THEN LET Y=Y + 1
180 GOTO 110
N ow run this program starting at line 100. See the cursor sitting at O,O?
If you press any of the control keys - 5, 6, 7, or 8- you'1l see the cursor start
to move and a line get drawn on the screen in its wake. This is why we use
UN PLOT first and then PLOT to make the flickering cursor so you can see
where you are. You see, when the computer runs through the program lines,
the last thing it does before it checks the keyboard, is to PLOT X, Y (at line
III) .
Then we check the keyboard. If you have pressed any keys, this will
114
Plolling A long
This will take care of that problem by making the cursor wrap around
on the screen. If it leaves in any direction it reappears over on the other side
of the screen. Say for example that X = 0, so that the cursor runs off the left
side of the screen. The X will then get set to 63, while Y will be unchanged so
the cursor will magically appear at the same height but way over on the right
side.
Well, we've got a pretty nice program here for drawing on the screen, as
you can see by running it. But we could sure use an eraser. We really need
two erasers. One of them we can use to clear the screen entirely. That's easy;
add:
N ow if you press the C key, you erase everything on the screen (Fig. 5-6).
115
TIMEX SINCLAIR BASIC PRIMER WITH GRAPHICS
We'll turn the switches on by typing D for DRAW. These lines set the
switches:
116
Pla ning A lo ng
75 LET T=O
100 LET X=O
101 LET Y=O
110 UNPLOT X,Y
111 PLOT X,Y
1131F T=O THEN UNPLOT X,Y
150 LET A$ =INKEY$
160 IF A$ = '·5 " TH EN LET X=X - 1
161 IF A$ ="8" THEN LET X=X+ 1
162 IF A$ = "6" TH EN LET Y=Y - 1
163 IF A$ ="r THEN LET Y=Y+ 1
1641F A$ ="E" THEN LET T=O
165 IF A$ ="D" THEN LET T= 1
166 IF A$ ="C" THEN CLS
170 IF X>=63 THEN LET X=O
171 IF Y> =43 THEN LET Y=O
172 IF X< =O THEN LET X= 63
173 IF Y< =O THEN LET Y=43
180 GOTO 110
This way you can move the cursor around on the screen first to your
desired location; then you can press D to start drawing. From then on, you
can automatically switch between drawing and erasing just by pressing D or
E.
Run this program from the beginning and you'll see how much fun your
computer can be when you can take control of it. See if you can figure out
how to add different shapes at the beginning so you can see the sculptural
effects as you carve out areas of white from the basic black shapes.
This last program should have showed you the importance of thinking
ahead a little in programming. We could have just let you type in the whole
unnecessary sequence of the UNPLOT program . Instead , we showed you
that there was repetition between the two groups of statements. A little
thought could show us how to use the same group of statements to do double
duty.
117
TIMEX SINCLAIR BASIC PRIMER WITH GRAPHICS
The importance of these ideas may be a little hard for you to fully
appreciate right now, but, in the next chapter, we're going to show you a
whole new perspective for the process of writing programs. So, save this
drawing program on tape, have some fun drawing, and take a break. Let
your imagination carry you away.
118
6
You're beginning to see that computers aren't really that hard to pro-
gram at all. Each step, or program statement, is very simple in itself. It's the
combination of these simple steps into longer program sequences, and then
these groups into bigger programs, that enables the computer to do very
complex tasks. Thus far, our programs have been so simple that we haven't
had to do much advance planning. Sure, when we made the bouncing ball
program, we had to think a little bit about the situation, so we could make
the computer do what we wanted it to do. But, for the most part, things have
moved along directly from our thoughts into BASIC program statements.
BASIC was designed to be a language that makes this type of seat-of-
the-pants programming easy and to make computer power accessible to a
wide variety of people, people like you, who want to use computers to do
particular jobs without having to learn a whole lot about computers. In
BASIC, you can more or less program as you go. A tweak here, a kluge there
(another great computer word), and eventually you get the whole mess to
work. Remember how we told you to number your program lines by tens so
you can easily add new lines? As we've been going along, we've also been
adding statements "between the lines" as we decided what we wanted to do.
STRUCTURE
119
TIM EX SI CLA IR BASIC PRIM ER WI T H GR A PHI CS
ideas behind this new, more structured approach. We' re going to teach you
about the command GOSUB, over the H key, and its constant sidekick
RETURN, on the Y key. This will introduce the very important concept of a
subprogram, or subroutine, as it is also called.
We talked in Chapter 4 about breaking our programs out of the
"straight line" rut, executing one statement after the other until we come to
the end . And you've seen how important the statements are that allow you to
authorize changes in this plodding approach: GOTO used with an IF THEN
is how you can make the computer exercise some intelligence in what
happens next in your programs. Problems can easily start to arise, though,
when your longer, more complex programs start GOTOing all over the place.
If you're just following along in a book, you don't tend to notice this, since
the person who wrote the program probably wouldn't put it in the book
unless it worked all right. But when you start to write your own programs
and you have to get them to work yourself, you'll see that the clearer the
structure of your program, the easier it is to get it running without problems,
to debug it, as we say in the trade. See Fig. 6-1 .
Subprogram, Anyone?
Subprograms are one of the ways you can make your program's struc-
ture simple to follow. Using subprograms makes programs easier to write,
easier to understand, and easier to change later on. We all know that it's
easier to write a short program than a long one. The idea behind using
subprograms is to write and test relatively short programs and then link them
together into one larger program using the GOSUB keyword.
GOSUB works almost like GOTO , with one critical difference. When
the computer encounters a GOSUB somewhere in your program, it automat-
ically stores in a special location the line number following the one on which
the GOSUB occurs . For example, if you had this code fragment in a
program:
50 GOSUB 1000
60 LET X= 25*8
1500 RETURN
120
Program, Program, Who's GOI the Subprogram?
MAJOR AND
MINOR
PROCESSES
when the program executes line 50, it would first store the number 60 in the
special location and then go to line 1000. From there, it would continue until
it came to the RETURN at line 1500. Then it would check the special
location and RETURN to the next statement following the line number
stored there. In our case, it would GO TO line 60 and continue on its merry
way (Fig. 6-2) .
With subprograms, you set up your program basically in a straight path
and use GOSUB statements to branch to the simpler subprograms and then
RETURN to the main program when you're done. This way, no matter
where you go, as long as you use GOSUB, you' ll always return to a known
location when you're finished. Subprograms also save memory space, since
121
TIMEX SINCLAIR BASIC PRIM ER WITH GR A PHI CS
RETURN
,
groups of program lines that are used in several different places actually have
to be stored only once in memory.
Wise Remarks
Let's write a really simple program to show you how GOSUB works.
122
Program. Program. Who 's Got the Subprogram?
REM is the keyword over the E key. GOSUB is over the H key and
RETURN is over the Y.
Hope we didn't throw you by line 5. REM stands for "remark" and it's a
way for you to add comments into your program listings. When the compu-
ter sees REM as the keyword , it ignores the rest of the line so you can type in
anything you want after the REM statement. As your programs get more
complex , you'll find it's a good idea to put in lots of REM statements
explaining what is going on in the program: what the variables represent,
important formulas , etc. This way anyone, including you, who comes back to
the program, days, weeks, or months later, will know what's going .on.
If you're a T / S 1000 owner, you've got to be pretty stingy with your
REM statements, because the memory space can get a little tight. If you've
got a T / S 1500 with 16K of memory, you can put REM statements any place
in the program where you think there might be a question later on.
When the program is running, press the S key every once in a while to
get the feel of it. The computer just loops around and around in the main
program, from lines 5 to 50, until you press the S key. Then it goes to line 200
just like a GOTO would. It executes all the lines from 200 on, until it comes
to line 210 . The RET URN statement on 210 informs the computer that the
subprogram is done and that it should RETURN to the main program at the
statement following the one that sent it there in the first place.
Every subprogram must end with a RETURN; otherwise the computer
will not know when it should end the subprogram and go back into the main
program. See Fig. 6-3 .
You are probably thinking that anything you can do with a GOSUB you
can also do with a couple of GOTOs. Well, you're right. You could do it, but
the point of the GOSUB command is to make things easier for you. GOSUB
frees you from worrying about where you'll end up when you're done with
some process. You know that you'll come right back into line again . If you
use plain old GOTOs, then, if you add some program lines or change the
structure of the main program, you could easily end up going to the wrong
place on your return. GOSUBs help to make your program easy to design,
easy to test, and easy to understand.
123
T IM EX S I CLAIR BA S IC PRIM ER WI T H GR AP HI CS
124
Program, Program, Who's Got the Subprogram?
0.94124366 0.59408569
0.55688477 0.76686096
0.51483154 0.61291504
0.96907044 0.68031311
0.15130615 0.34892273
0.16993713 0.74623108
0.96765285 0.57159424
0.87005615 0.25434876
0.18086243 0.56561279
10 LET X=RND
20 PRINT X,
30 GOTO 10
10 LET X= 1O*RND
20 PRINT X,
30 GOTO 10
That's better. This time the range is from a little bit more than 0 to
9.999 ... If we wanted our random numbers to range from 0 to 99 .999 ... ,
we could use:
10 LET X= 1OO*RND
125
TIM EX SI NC LA IR BASIC PRIM ER WI T H GR A PHI CS
Notice that if you use 100 as a multiplier, the computer will never
PRINT 100 as one of its random numbers since the RND is never equal to I
but always less than I.
So far , so good, but what about the situation where you need to have
some random whole numbers (or integers, as we call them in the computer
world); for instance, the numbers of spots on the face of a die: from I to 6.
To do that, we have to apply another function to the numbers generated
by RND: INT. All INT does is strip away the numbers (computerists would
say: all the digits) to the right of the decimal point. Sometimes they call this
truncation in the computer world. For example, 8.3487129 would be trun-
cated to 8; 7.99999999 would be truncated to just plain 7.
Change line 10 to read :
INT is the function under the R key. Remember to put in the paren-
theses so that the functions are calculated in t he right order. If you put: 10
INT IO*RND (no parentheses), the computer will think you want to take the
INT of 10 (which is 10) and THEN mUltiply by RND, so you'll be in the same
boat as before. With the parentheses in place, it knows to first mUltiply RND
by 10 and then "take the INT" of that.
Guessing Game
Run the program now and you'll see random integers printed on the
screen. Not bad , now you can generate any set of random numbers that you
like, right?
Try this little program out for some fun .
126
Program, Program, Who's G OI the Subprogram?
70 GOTO 15
100 PRINT "YOU ARE RIGHT"
110 PRINT "IT TOOK YOU " ; T;"TRIES "
120 IF T= 1 THEN PRINT "TRY"
1 30 PRINT " ENTER 0 TO REPEAT GAME"
1351NPUT A$
140 IF A$<>"O" THEN STOP
1 50 CLS
160 RETURN
Can you understand how this program works? Line 5 generates a ran-
dom number between I and 25 for you to guess. The IF THEN statements at
lines 20 through 50 test to see whether your number is bigger or smaller than
the randomly generated number. If you guess wrong, the IF THEN s print the
appropriate message and just loop back and try again. The variable T is used
to count the number of guesses, so we start it at I and then increment it at
line 65 each time we pass through the guessing loop.
When you guess right, we GOSUB to a subprogram which tells you that
you guessed right, prints the number of tries, and then asks you if you want
to go again. We're using the variable T to count the number of guesses that
you make; we print that out for you with lines 110 to 120. See how the
statement on line 140 works? If you enter anything other than an 0, when the
computer checks at 140, it stops.
Line 135 is there to clear the screen after each guessing session so that
you don't run out of screen space.
Here's another technical point about RND . You may be wondering
about RAND, on the top of the T key. Technically, RND makes numbers
that a strict mathematical type wouldn't pass for truly random. Actually, the
computer takes a very big number and, by using a specially designed
mathematical procedure, makes a list of what the mathematician would call
"pseudo-random" numbers. These numbers are really random enough for all
intents and purposes.
The base number that the computer uses to generate its list of random
numbers is called the seed. If you want to make the computer use a new seed
value and thus generate a new list each time you run the program, you have
to put RAND somewhere in your program. That way you can be assured of
getting a different set of genuinely pseudo-random numbers each time.
127
TIMEX SI CLA IR BASIC PRIM ER WI T H GRAPHICS
BUILDING PROGRAMS
Now that we've got RND in our programming tool kit, we have all the
tools we need to do a really good job on our dice program. This time, instead
of just designing as we go along, we're going to think out the problem a little
first. We'll design the program before we go on to write the BASIC language
statements which will accomplish the task at hand: a program that simulates
throwing dice.
This is what we want to have the computer do:
\. THROW
OICE
2. DISPLAY
DICE ON
SCREEN
YES
128
Program, Program, Who's Got the Subprogram?
grammers to help organize their thoughts . Notice that we put the question
THROW AGAIN, in a diamond-shaped box to distinguish it from ordinary
processes. Branch points like this, from which the computer can go in more
than one direction through the program, are called conditionals. Condition-
als are usually set up using IF THEN statements and are customarily put into
these diamonds for quick recognition.
Step I, throwing the dice, is done by these statements:
Now let's consider step 2, the problem of displaying the dice. It's the
biggest chunk of our task.
Dice By Design
Get your graph paper out and start doodling. How big do you want to
make the dice? How many boxes across do you want to use to draw each
face? A 3 X 3 box to form a face is as small as we can go and we'll probably
find it easier to use an odd number of spaces in each direction for easy
centering of our spots. So, let's use dice that are 5 boxes wide and 5 lines
long. And what do we want each face to look like? We've got two real choices
here. Black with white spots and gray with black spots.
When I experimented , I liked gray with black spots much better. I think
it makes for a classy looking face. If you don't like it, use the black with white
spots.
Got your graph paper out? All right, the one-spot is easy. A 5 X 5 gray
box with a black box dead center. See Fig. 6-6.
The two-spot is easy, too. How about the three-spot? A little trickier.
Can you see how to move the top and bottom spots over a little so you can
get it to look like a three-spot. That's where some of the half-and-half charac-
ters come in. We can use the graphics "5" or [ 5 ] key and the graphics "8"
or [ 8 ] key to shift the spots at the top and bottom over a half space. This creates
a nice looking three-spot.
Four-spot is easy.
Five-spot is the same principle as three with two more spots.
Six-spot is a little tricky too. See if you can figure it out before you look
129
TIMEX SI CLA IR BASIC PRIMER WITH GRAPHICS
• --•
• • -
••
III
-
•
,..•-
~
•• III
-
-• •
•
III
~
- III
~
at the picture that explains it. We've got to use the half spaces but this time in
the other direction.
Subprogram Assembly
N ow that we've got each face designed, writing the program statements
to print anyone of them is easy. We'll just make a separate subprogram for
printing each face, and use a GOSUB statement to go to it when we need it.
130
Program, Program, Who 's Got the Subprogram?
Here's a tip for entering a long sequence of program lines all of which
are more or less the same. Enter the first line (1000 PRINT AT 15,7;"AAAAA").
After you've entered the line, bring it back into the editing area and use the
cursor keys to transform it into the next line. In our example, you'd first shift
the cursor over to the right of I 000, DELETE the last 0 and change it to a I.
Then you'd shift over to the right of the 15 and change it to 16; shift right
again and then enter the newly ed ited line. N ow you can bring the line back
into the editing area again and repeat the process making those changes that
are necessary. I find this a much better way to enter repetitive groups of lines .
Run this program and you'll see a one-spot face appear on the left side
of your screen. When we add this subprogram to our main program we'll
have to change that STOP to a RETURN , but for now, let's leave it at STOP
for testing.
How about programming the two-spot? It's also pretty easy. Just add:
131
TIMEX SINCLAIR BASIC PRIM ER WITH GRAPHICS
To runjust the subprogram, enter: RUN 2000. (Remember, this tells the
computer to start running at line 2000 instead of the program's first line.)
Can you think of how we can use the same subprograms to print the
different faces at either the left or the right position? It's easy really. We
specify the column to PRINT AT as a variable; we'll call it P. Change the
PRINT AT statements to:
Using this strategy, we also need to have a little subprogram that will
132
Program. Program. Who's Got the Subprogram?
1. THROWN
DICE
2. DISPLAY DRAW
DICE ON BODY
SCREEN
YES
YES
just draw the body of the dice . This is an easy one. See if you can do it
without looking at our example.
We'll start this subprogram at line 900.
900 FOR 1= 15 TO 19
901 PRINT AT 1.7;"AAAAA ";TAB 5;"AAAAA "
902 NEXT 1
903 STOP
Run this little subprogram and you'll see the two dice bodies. Making
this into a subprogram makes sense, too, because we'll have to keep redraw-
ing the dice faces time and time again, after each throw.
Can you see how to change the two-spot program?
133
T I MEX S I CLA IR B AS I C P RIMER WI T H G RAP HI CS
Now you have a subprogram that prints the die bodies and the subpro-
grams that print each of the possible number of spots . Try adding these lines
to your program so you can try things out before we go any further.
Remembe r to change the STOP statements that we were using to end the
subprograms into RET URN statements.
\ 34
Program, Program, Who's Got the Subprogram?
Test your program from the keyboard by entering the values for Sand
P$. S must lie in the range of I to 6, otherwise you'll be branching to a
nonexistent subprogram and confuse the poor computer.
Take note of how lines 81 and 82 work. We set P to 7 every time. Then,
if you enter R, we set P to 17, otherwise, P gets left alone.
Do you see how line 90 works? Just as in a GOTO , we can use an
arithmetic expression in the GOSUB statement to calculate the line we want
to GOSUB to. Here is a clever way to pick the proper subprogram. By
beginning each subprogram as we did at lines that are even thousands, we
can use one simple program line to easily switch to the one we want. If you
were going to use IF THEN s to do the same task, it would take 6 complex
lines like this:
to accomplish the same thing. And look at how much memory we've saved ,
not to mention your typing time.
20 LET L=INT(6*RND)+ 1
21 LET R=INT(6*RND)+ 1
22 RAND
135
T I MEX S I NCLA I R B AS I C PRI ME R WI T H GR A PHI CS
Then we want to draw the dice bodies so we branch to that code with:
30 GOSUB 500
40 LET P=7
41 GOSUB L*10oo
50 LET P= 17
51 GOSUB R* 10oo
136
Program, Program, Who 's Got the Subprogram?
Now it waits for another keypress to throw again . This is the "waiting" code:
Line 60 compares the key presently being pressed with the null string; that
means, no key was pressed. If NO key is being pressed , we just sit in the loop
at line 60 until you press something on the keyboard; at that point, we
continue on.
That's all folks! You've written the whole thing. It's a long program all
right, but by using subprograms, we've made the job really easy. Can you see
how neatly the program is structured for understandability? To drive this
point home, try a simple modification.
NO
YES
137
TIM EX S I C L A IR BASIC PRIM ER WI T H GRAPHI CS
When you run the dice program, you'll see that the display very quickly
shows you the spots on the dice. There's no drama, no suspense, no action.
With a program as neatly structured as this one is, adding some action is
easy.
Looking at our flowchart, we see that we can put the entire dice throw-
ing and display routine into a FOR NEXT loop so we can let the dice roll
several times before we display the final values. See Fig. 6-9.
Add these two lines and you've got yourself a dice display with plenty of
thrills:
5 FOR 1=1 TO 5
55 NEXT I
See how simple it is to make changes when your program has a nice,
neat, and ordered structure? From now on, we'll use flowcharts to clarify our
thoughts on all the bigger programs we' re going to write. By learning how to
think on paper, you'll be way ahead in the programming game.
Maybe this game is simple to design using structured techniques, but it's
still a long program. You may want to save this program on tape. If so, do
that now and take a break. You've earned one!
138
7
Strings are used for much more than just tying up packages and flying
kites. We've used strings and string variables a whole bunch of times in the
preceding chapters. We used a string variable A$ to get input from the
keyboard with INKEY$ when we wanted to take direct control of the compu-
ter. And, in the dice program in the previous chapter, we used strings of
graphics characters to hold the spots for the dice faces.
Because computers have to do more than just crunch numbers, there's a
lot to be said for using strings. Word processing is essentially souped-up
string processing. Data bases, which you've probably heard or read about
previously, are basically nothing more than huge, structured collections of
strings.
This chapter will show you how to use the powerful string-handling
capabilities that have been built into your Timex computer. In this chapter,
we're going to develop the largest program you've created so far. We'll make
up a simple little language of our own which will enable you to sit at the
keyboard and type in commands to put different simple shapes on the screen
with ease. Not only will this give you some practice in planning a large
program, but it'll teach you how to use strings. You'll also end up with a
program that's fun to play with.
For those of you out there who have a T / S 1500, you'll be able to
incorporate more subprograms into the basic structure of the program, so
that you can make a graphics language of considerable power. We'll start by
learning a bit more about strings.
139
TIM EX SI NCL A IR BASIC PRIM ER WITH GRAPHI CS
First of all, what exactly is a string? Perhaps you remember from Chap-
ter 3 that a string is any group of characters. It doesn't matter whether they
are alphabetic, numeric, graphic, or any combination of these. For instance,
these are all strings:
ABCDE %*%?!* JOHN TIMEX TSI500 12345
You also learned in earlier chapters how to put a given string into a
string variable, or, as they say in the computer business, to assign a value to a
string variable (Fig. 7-1) , like this:
10 LET A$ ="ABCDE"
Probably the simplest string handling you can do is seeing how long a
string is:
when you add two strings together, the second string is just placed right on
the tail of the first.
140
Stringing Things Out
and tryout string multiplication. Fooled you! You can't use any of the other
arithmetic operators, like -, *, or / to work with strings. Only the " + .. sign
has been defined for them.
Using some of the built-in string-handling functions which we' re going
to show you now, you'll be able to make your strings do everything but play
cat's cradle. You can even make up your own string processing subprograms.
Sliced Strings
There is something a little like subtraction that works on strings. This
141
TIMEX SI NCLAIR BASIC PRIMER WITH GRAPHICS
command enables us to slice out pieces of a given string. Fig. 7-2 illustrates
this command.
Try this short program to see how string cutting works.
10 LET A$ = "ABCDEFGHIJKL"
20 PRINT AT 5.5;A$
30 PRINT AT 7.5;"WHICH CHARACTER ?"
40 INPUT A
50 LET B$ =A$ (A)
60 PRINT AT 9.5;A;TAB 5;B$
70 GOTO 30
~
r...........
I
_J..-....-.....
AS
~ ...
Run this program and you can see how to pull a single character out of
a string. You tell the computer which character in the string you want by
putting the position number of the character in parentheses right after the
string. If you enter 5, you get E; 6 returns F; and 7 returns G.
If you enter 13, you'll get error 3/ 50. That means you tried to pull a
character from some position beyond the end of the string. Try entering 0
and see what you get. And how about negative numbers? You get error B / 50
which is defined in the Timex User Manual.
142
Str inging Things OUf
Strings are read just like English words: from left to right with the
leftmost character being assigned position I. S paces count as one position,
for instance, the space between "too" and "tall" in "too tall". That means
that the string "too tall" is 8 characters long and that "too tall( 4)" returns" "
(a space).
Not only can you pick out a single character from a string, but you can
also pick out any continuous group of characters using the same TO as you
use in a FOR statement (the one over the 4 key) . Add:
41 INPUT 8
50 LET B$ =A$(A TO 8)
60 PRINT AT 9,5;A;TAB 1 2;B;TAB 5;8$
N ow run the program. If you enter 3 and then 6, you'll see: "CDEF."
Entering I and 4 returns "ABCD." How about I and 12? Naturally you get
the whole string.
N ow, just for reference, try 2 and 4 as entries. A slight problem has come
up, hasn't it? The computer doesn't erase the entire old answer before it
writes the new one. This means that if the new answer is shorter than the old,
some of the old characters will remain on the screen, confusing things and
adding to the general computer pandemonium.
This is a common occurrence when you are working with strings whose
lengths can change from one PRINT statement to the next. In many cases,
143
TIMEX SI CLA IR BASIC PRIM E R WITH GRAPHICS
including this one, you've got to make sure to erase the old pattern com-
pletely before you print the new one. So , add this line to take care of the
problem and remember it for the future:
You'll notice that if you make A bigger than B, the computer brings
back the empty string (that's a string with no characters in it at all, not even a
blank space! It's called a null string. If you make B greater than the length of
the string, you get your garden variety 3/ 50 error message.
We've done this one before- checked to see if one string was equal to
another. Clear the memory and enter this short program.
144
S tringing Thin gs OUI
Using this little program, you' ll see that two strings are equal if and only
if they have all the same characters.
N ow change lines 30, 40, and 100 to read :
By entering a few different strings (Fig. 7-4), you should be able to figure
out for yourself how the greater-than and less-than operations work with
strings.
GREATER
%...-.. .\:--"""'s:-""\~\~
. T7:::
HEc-:::S::-:
PA~ CE"'"\~s:..---'"\~\..---:I#J::::-
Alphabetics
"One string is less than another" means that the first string comes before the
second in standard alphabetic order. The computer alphabetizes words in the
same way that you would, only faster and with more assurance.
We said before that a string could be any combination of letters or charac-
ters that you could type into the computer. But what's the alphabetic order of a
string beginning with a number, like I ZZZ? Do you think it's greater or less than
ABC? Try it! Or try this, enter a string beginning with an asterisk. Are you
surprised to find out that * comes before A? See Fig. 7-5. How can punctuation
marks have alphabetic order? Don't worry, there is a logical explanation for all
this, which comes from the way in which the computer handles characters.
145
TIM EX SI CLAIR BASIC PRIM ER WI TH GR APHI CS
* STR ING 23
lZZZ 29
ABC 38
Fig . 7-5 . Strings and their corresponding numbers .
You see, each and every possible character is identified to the computer by
giving it its own unique number. For instance, the computer knows that A is
matched to the number 38, B is matched with 39, and so on. Each single digit has
its own numeric equivalent, too. For instance, the digit 0 is matched with number
28, I is matched with 29, etc.
Most computers, in American and around the world, use a standard set of
numbers to represent each character. This set is called the ASCII (pronounced
ASS-KEY) code_ However, the Timex does NOT use these same codes, but a
slightly different set, sometimes called the Clive Code after the inventor of the
Timex / Sinclair computers, Dr. Clive Sinclair. Computer manufacturers usually
provide a list of the equivalent character codes somewhere in their documenta-
tion, usually in an appendix. The complete list of Clive Codes is given in Appen-
dix A.
There's a built-in pair of functions on your computer which will give you the
number that matches a given character. If you know the number and want to
know the corresponding character, another function will give that to you. See
Fig. 7-6.
These complementary functions are called CODE and CHR$, under the I
and U keys. There are 256 distinct character codes, numbered 0-255. Each one is
defined as a unique character. Every keypress has its own unique code number
associated with it. Try out this test program:
146
Slrinf: inf: Things OUI
) ) \
Ciid
Fig . 7 -6 . CODE and CHR$ .
Now you can run this program to explore on your own which numbers
correspond with which characters. If you input characters like " > " or
"< >" for the first part of the program, you'll be able to see which number
corresponds with which character. Conversely, in the second part of the program,
you can type in a number and see which character corresponds to it. Some
numbers like 84 or 97 aren't used for any character by the computer, and so they
print out as question marks.
Try entering number 237 . Interesting! We get an entire command word,
GOSUB, instead of a single character. Can you figure out what's going on here?
Your Timex, unlike most other computers, has single keys which stand for
entire words in the BASIC programming language. Once you learn the keyboard,
it's a lot faster to just type only the P key and get PRINT than to type in
P-R-I-N-T, a character at a time.
If you want to see the entire character set printed, try adding these lines.
147
TIM EX SI CLA IR BASIC PRIM E R WI T H GR A PHI CS
Now, issue the command: RUN 200. Whew, there before you is the entire
character set. The question marks stand for numeric codes which don't have any
characters associated with them.
See how the character codes for inverse graphics characters are equal to the
codes for the regular characters plus 138? This makes for an easy trick of turning
regular letters into BOLD. It's easy for the computer to take a word and display it
in inverse graphics. Can you figure out how to do it on your own?
5 LET B$ =''''
10 PRINT AT 5,5; " STRING PLEASE"
20 INPUT A$
30 PRINT AT 6,5:A$
40 FOR 1= 1 TO LEN A$
50 LET B$=B$+CHR$(CODE A$(I)+ 138)
60 NEXT I
70 PRINT TAB 5;8$
Line 50 is the crux of the program. It takes the CODE of the letters in A$,
which gives you the numeric equivalent of the first letter of the string. Then we
add 138 to get the numeric value of the equivalent graphics character. We use
CHR$ to create a new string B$, one character at a time. It's a good idea to make
sure that B$ is empty by assigning it the null string- two quotation marks
(SHIFT Ps), side by side, as in line 5.
There's another string function that can come in handy. It's called VAL. Try
entering this short program.
10 LET A$="2+2"
20 PRINT A$
30 PRINT 'THE VALUE OF A$ IS "; VAL A$
148
St ringing Things Out
VAL is a little tricky to understand. Do you see what it is doing here? VAL
takes the string "2 + 2" which is contained in the string variable A$ and it gives
you the numeric value of that string which is 4. VAL works with any string that
has a numeric value. So even the string "2**3" can be evaluated by VAL. Type in
the double asterisk, SHIFT H, not two single asterisks in a row!
Remember that a string is just a line of characters, so that the string "2" is a
character (corresponding to computer code 30) while 2 (no quotation marks) is
the actual numeric value 2 (Fig. 7-7).
Try this program to make sure you get the hang of it.
'0 LET A$ ="2"
20 LET A=2
30 PRINT A+A$
Syntax error! The computer won't even let you type in the addition of a
number and a string. It's like comparing walruses and sewing machines, and
nobody, least of all the computer, knows how to do that.
Change line 30 to:
30 PRINT A+VAL A$
N ow you' re cooking with gas.
149
TIM EX SI NC LA IR BASIC PRIM ER WI T H GRAPHIC S
If you give VAL a string that isn't a numeric expression, you generate an
error and your program stops. That's too bad because it would be much nicer
if the computer just told you that it needs to have a valid arithmetic expres-
sion and asked again for input rather than bombing out on you.
Try this program and you'll see how to check your string first before you
feed it to VAL, to prevent computer indigestion.
150
STringing Things OUf
You'll find this approach very useful once you start writing programs
that other people, who don't know all the rules of computers, will be using.
Adding protection features into your programs, checking to make sure that
the information entered is appropriate to the question, is a very worthwhile
habit. This is called making your programs user friendly . You should always
check your input before it goes too deeply into your computer's memory and
fouls up your program with a nasty error message.
You see that STRS takes what would ordinarily be considered a number
and turns it into a string, which the computer will interpret simply as a group
of characters. Now you can add "cents plain" to the newly created string "2".
Try this program and you'll see how to make some cents out of numbers.
151
TIM EX S I NCLA IR BA S I C PRIM ER WI T H GR A PHI CS
20 INPUT A
30 LET A$ =STR$ A
40 LET L=LEN A$
50 LET S$=" $ "+A$(1 TO L - 2W'."+A$(L - 1 TO L)
60 PRINT S$
70 GOTO 20
It shows you the LENgth, VALue and CODE of any number you enter.
It's pretty easy to get the hang of it.
One more tidbit before we go on to put all our string handling capabili-
ties together into one big package.
152
Stringing Things OUI
80 NEXT I
90 PRINT "STRING NOT FOUND "
99 GOTO 10
100 PRINT "FOUND IT"
110 GOTO 10
Do you understand how this little program works? It searches the first
string that you entered (into A$ at line 20) for the specific target word (which
you enter into F$ at line 35). The nested FOR NEXT loops act to step
through the positions of the string A$, one position at a time in order to look
for the target string, F$. This string search program can come in mighty
handy, maybe as a part of a larger program, so make sure you understand
how it works before you go on. Fig. 7-9 should help .
.1 1
Fig . 7 -9 . Moving pointers during string searches .
153
T I MEX S I CLA I R B AS I C PRI MER WI TH G RA PHI CS
the keyboard and translate it into an action. In a way, we could say that we
want to write a program that will enable t he computer to "understand" the
f reshly minted command word s that we make up as our program comes into
existence.
We' ll make our program translate our command words into screen gra-
phics. So , for example, yo u'll be able to t ype in:
10 •
1.1
0.0 " 10
154
StrinKinK Thin gs Out
GO TO ITS
CORRESPONDING
SUBPROCESS
NO
For our program, let's make up some simple commands that will:
We'll stick to these few commands and keep things simple to show you
the basic idea. This is really all that is practical for the T / S 1000. If you've got
a T / S 1500, you've got plenty of room, and you can improve this program
easily just by adding more subprograms into the command section. Once you
see how things are done, you'll find that it is easy to modify this program to
use whatever types of commands you want to use.
155
TIMEX SI CLA IR BASIC PRIM ER WI T H GRAPHICS
Let's draw a more detailed picture so we can see the flow of events at a
more BASIC level. Refer to Fig. 7-12.
We want to set up the program to take in the command in one string,
slice out the parts we need , and pass them to the subprograms which will
actually carry out the commands. The strategy will be very similar to the one
we employed in the last chapter, only we'll get to the subprograms by decod-
ing a command rather than the value of RND .
How about this for a format for our command strings?
TURN ON
UNPLOrs
YES FLAG
NO
GET CODE OF
THE COMMAND
GOTO ITS
SUBPROCESS
156
Stringing Thin gs Out
PAST HISTORY
300 ClS
301 RETURN
2 GOTO 10
5 IF Y< O OR Y>43 OR X< O OR X> 63 THEN GOTO 7
6 PLOT X,Y
157
TIM EX SI NCLA IR BA S IC PRIM ER WI T H GR A PHI CS
We put this most frequently used subprogram up front, because the way
the T imex computer executes subprograms makes it much more efficient to
put the most widely used subprograms in the beginning. You'll find that your
programs will run somewhat faster , if you follow this advice. The GOTO 10
at line 2 skips the computer over the subprogram when you first run it.
Otherwise, you'll get an error 2/ 5 since you haven't had a chance to give Y a
definite value yet.
We're using the variable P as a switch here at line 7 to turn UNPLOT off
and on. Notice that we also include a check on the values we are going to plot
(at line 5) to make sure we aren't plotting off the screen. (You could improve
this program by adding a GOTO 1300 here and printing some sort of mes-
sage, like "BAD COORDINATE" before returning for new input.)
You should also understand here that for plotting in the subprogram, we
always plot the variables X and Y. Our other decoder subprograms thus have
as their job, translating the commands we type in and placing the correct
values into the variables X and Y for the plot subprogram.
Here are the other main subprograms that we'll need for the program.
The first one plots a point, PT; the second makes a square, SQ:
Do you follow this one? We take in the X and Y coordinates of the lower
left corner of the square, and the length, in Z 1. The nested FOR NEXT loops
158
Stringing Thin gs Out
set the variables X and Y to the correct values and then we just GOSUB 5 at
line 562 to plot them out one value at a time.
This subprogram, TX , places text on the screen:
569 REM This is TX for placing text on the screen
570 IF Yl > 2 1 GOTO 1400
571 IF LEN SS+Xl > 32 THEN GOTO 1410
572 PRINT AT Xl,Yl ;SS
573 IF P> O THEN RETURN
575 PRINT AT Xl ,Yl :BS (1 TO LEN SS)
580 RETURN
With our main subprograms in place, it's time to design our command-
line decoder.
159
TIMEX SINCLAIR BA S IC PRIM ER WI T H GRAPHICS
Hmmm, anything that isn't clear? We take in the command string from
line 10. We check it at 12 and 13 to see if it needs special handling and
GOSUB if it does. Lines 15, 16, and 17 initialize some variables we use at
various places in the program.
What actually happens in the subprogram at line 800?
Here's the subprogram we need to get the text out of our command
string for the TX command:
160
1100 LET S$=A$(1 a TO LEN A$)
1101 RETURN
This routine strips off the text from the TX command and puts it into S$
for printing using the subprogram at 570.
Do you see how these two subprograms work? We set T$ to a null string
first. Then we add characters to it from our command string, one character at
a time, until we encounter a comma which tells us that a numeric value is
completely entered . (This happens at line 140.)
The FOR NEXT loop starting on line 110 steps us through the string
starting at TI = 4 (remember we set that up in our main program as one of
our string position pointers. TI = 4 because we know each command has its
first three places taken up by the command code and a comma. When we
come to the next comma, we know that we've got all the digits of our first
number, so we jump out of the subprogram to a program fragment at line
1000 that sets the string position indicator T I, so we'll know at what position
to start our next slice of the string.
161
T IM EX S I C L A IR B AS IC PRIM E R WITH GR A PHI CS
The program then returns to the main program at a line number deter-
mined by how many times we've been through the decoder subprogram.
Each time through we extract one numeric parameter. The variable A con-
trols which line we return to, and so, which variable gets the value that we've
extracted from the command string. See Fig. 7-13.
Each time we pass through the subprogram, A adds 10 to itself. Thus,
the first time we pull a number out, we GOTO 35 , so that the first number we
extract gets put into variable X I at line 35 . The next time through, we go to
line 45 so we get the value placed into Y I. The third time we go to 55, and the
value gets put into Zl. It's easy to see how to add lines here and strip off as
many numeric parameters as you like.
The rest of the program should be easy for you to follow, since you've
already used all the principles before. Here's a complete listing. Once you've
tried it out, why don't you see if you can add your own commands. If you've
got a T / S 1500, t here's plenty of room in memory for you to add commands.
Save the program on tape, and follow along next chapter when we show you how
to graph just about all of the built-in functions on your computer. You should
have an easy time of it adding these functions into your graphics package.
Most of all: Have FUN.
2 GOTO 10
5 IF Y< O OR Y>43 OR X< O OR X>63 THEN GOTO 7
6 PLOT X, Y
7 IF P=O THEN UNPLOT X, Y
8 RETURN
162
Stringing Things Out
800
1000
r=-----t PUT TEXT
IN SS FOR
PRI NTING
163
TIMEX S I CLA IR B AS I C P RI MER W ITH GRAP HI CS
300 CLS
301 RETURN
529 REM Th is is PT
530 LET X=X1
531 LET Y=Y1
532 GOSUB 5
533 RETURN
559 REM Th is is SO
560 FOR X=X1 TO X1 +Z1 - 1
561 FOR Y=Y1 TO Y1 +Z1 - 1
562 GOSUB 5
563 NEXT Y
564 NEXT X
565 RETURN
164
Sf r i ng i ng Things OUf
165
8
Functional Graphics
167
TIM EX S I CLA IR B AS I C PRIM ER WI T H GR A PHI CS
Any point can be identified by specifying its distance from the origin
along the X axis and its distance from the origin along the Y axis. Each point
has its own unique address, given by specifying its two coordinates.
As you can see, we've already been using a system similar to Cartesian
coordinates with both PLOT and PRINT AT . The main difference is where
the point 0,0 appears in the system. With PRINT AT, it's up in the top left
corner; with PLOT 0,0, it's at the lower left. But with Cartesian coordinates,
it's smack dab in the center. All that this means is that we need to have a way
of translating from the computer coordinates into the Cartesian system.
For instance, the point with address 3,2 is located in the upper right
quadrant, 3 units to the right along the X axis and 2 units up along the Y
168
Fun Cl ional Grap hics
+4
Upper lell quadranl Upper righl quadrant
+3
+2 • (3.2)
+1
-3 -2 -\ +1 +2 +3 +4 +5
----------------- 0--------------------- Xaxis
~ 10. 0) origin
- 2
-3
Y axis
axis, in Cartesian coordinates, but way over in the left corner of your screen
in PLOT coordinates.
First, let's draw the Cartesian coordinates on the screen. It's easy! Just
use PLOT and some FOR NEXT loops. Naturally, we should put the origin,
where the two axes meet, at the middle of the screen, namely, the point 31 ,21.
See Fig. 8-3 .
The only problem with using our beautiful coordinate system for plot-
ting graphs is that we have to transform (the mathematical word for
"change") the numbers that we would plot using PLOT coordinates so that
they plot at 0,0 in our new Cartesian coordinate system. Since the origin (0,0)
of our coordinates is at screen coordinates 31 ,21 , we have to add 31 to each X
value and 21 to each Y value.
169
TIMEX SI NC LAIR BASIC PRIM ER WI T H GRAPHICS
+4
+3
+2 o position (3.2)
+1
- 3 - 2 - 1 +1 +2 +3 +4 +5
Xaxis
- 1 (0.0)
- 2
-3
-4
Y axis
o 1 2 3 4 5 6 7 _ _ _ 27 28 29 30 31 32 33 34 _ _ _ 59 60 61 62 63
43 (
42
41
24
23
22
1
o (34.23) is a
transformed (3.2)
21 ------------------------~~ I I
~",i'i"
20
19
18
r ~, ____________________________________ _J
Fig . 8-3 . Comparing PLOT 31 , 21 with position 3, 2 in both systems .
We need to draw the axes first, then the functions. We also might want
to be able to erase a function once it's drawn so we can keep reusing the axes
without them getting all messy. We'll use subprograms to make the structure
of the program easy to follow. (We might also want to label the axes, too, but
we'll leave that to you.)
First, we'll code the subprogram that will draw the axes:
170
Fun Cl i o nal Graphics
50 GOSUB 500
99 STOP
When you run this program, you get your coordinate axes . You also get
a little surprise that makes things look more mathematical. The "hash"
marks every five spaces along both axes give you reference points that make
reading the graphs easier. (Y ou should always strive to make things easier for
the people who are using the computer.)
DRAW X AXIS
AND 5-SPACE
HASH MARKS
HORIZONTALLY
I
DRAW Y AXIS
AND 5-SPACE
HASH MARKS
VERTICALLY
I
LABEL EACH
AXIS AND
HASH MARKS
171
TIM EX S I NC L A IR BASIC PRIM ER WI T H GR A PHI CS
Can you figure out how the hash marks are being placed on either side
ofthe central axes? As the FOR NEXT statement loops through the values of
X and Y, the PLOT statements on lines 515, 516, 545, and 546, plot out by
fives on either side of the center lines. So, for example, the first pass through
the loop, at line 515, we plot at (5*0) + 1 or PLOT 1,22. Similarly we handle
line 516. The next pass through, since X = 1, we plot at this time at (5* 1) + I
or PLOT 6,22 . And so on.
The IF THENs at 512 and 542 check to make sure that the plot stays in
bounds. We need them because of the programming trick we are using. For
example, when X is greater than 12, say 15, (5*14) + I is 71. If we tried to
plot at 71 ,20, we'd get an error message from trying to plot out of range (63 is
the biggest value permitted for the X coordinate).
We plot on the lines above and below the center lines by plotting with
the second value equal to 20 and then 22. Now all our graphs will be centered
on the screen and we'll be able to show the negative as well as positive part
of the graph. Refer to Fig. 8-5.
•
•••
•
...
•
• •
....................•.....•.•......•.•.
• •
•
•••
•
•
•••
172
FunClio nal Graphics
Transformation
N ow, let's put in the actual part of the subprogram that we'll use to plot
over our new Cartesian coordinates. We'll put it way up front for efficiency,
since we'll probably be calling it over and over again.
5 GOTO 50
10 IF X+31 > 63 OR Y+21 < 0 OR Y+21 > 43 THEN GOTO 40
20 PLOT X+31 ,Y+21
30 IF NOT P THEN UNPLOT X+31 ,Y+21
40 RETURN
173
TIM EX SI CLA IR BASIC PRIM E R WI T H GR A PHI CS
Now, if you RUN 800, you can enter some values and see how IF THEN
works. To tryout NOT, change lines:
Try the program out now and you'll see how NOT changes the value of
P . Once you've played for a little while, you can erase these extra lines and
get back to our main topic.
First Shot
Let's start off by allowing you to enter point coordinates into the new
system one at a time so you can see for yourself what goes where. Add these
lines:
25 PRINT X; ... .. ;Y
Just to give you some more visual feedback as to what's going on. You
should also change line 99 to loop around so you can keep getting new
values:
99 GOTO 65
174
Functional Graphics
N ow that you see where a single point plots on our transformed screen,
let's try to plot the graph of a function.
65 FOR X=- 30 TO 30
70 LET Y=X
80 GOSUB 10
99 NEXT X
175
TIMEX SINCLAIR BASIC PRIMER WI T H GRAPHICS
70 LET Y=A *X + 8
55 GOSUB 600
Fig . 8-6 .
176
Fun ctional Graphics
(C) Contours .
Some graphs .
177
TIM EX SI NC LA IR BASIC PRIM ER WI T H GR A PHI CS
• 15.11)
•••
• • • • •
•••••••••••••••••• ••••••••••••••••••••••••••
• • •
•
•••
Fig . 8-7 . Graph of Y=2*X+1 .
If you remember your algebra from school, then you'll remember that
this kind of function , in which Y is some mUltiple of X with perhaps a
constant added for good measure, is called a linear equation.
N ow the program will take in the values of A and B from the keyboard
and then plot the linear equation of your choice on the coordinate system.
You can even start to learn a little about mathematics from it. See what
happens when you increase the value of A? It increases the slope of the line,
that is , the angle that the function makes with the X axis. Try plotting
Y = 2*X , and Y = 3*X to see how the slope changes.
B is called the Y intercept because it determines where the graph touches
the Y axis . Try plotting Y = X + 2 and Y = X + 5 to see the effects of
changing B.
178
Fun ctional Graphics
When you run the program, it plots out a nice screen display and then
asks you to enter the values you want to insert into your generalized equa-
tion. If you've tried this out a bit, you're probably ahead of me on this one;
you've realized that it would be nice to use UNPLOT to get rid of the old
graphs and keep the screen display from getting too crowded. The obvious
way to do this is to add a new subprogram that asks you if you want to
PLOT or UNPLOT before it goes to the screen:
57 GOSUB 700
We jump to the subprogram at 700 and ask you if you want to PLOT or
UNPLOT. Depending on your answer, we set the switch P and then
RETURN to the main program. If you want to erase the equation, answering
o sets P , the switch to UNPLOT. If you answer anything else, the computer
will just return and start plotting.
There are several kinds of functions you can graph out on your coordi-
nate system now. All you have to do is change the LET statement on line 70.
It could easily get to be tedious if we have to type in a new LET
statement every time we want to tryout a new equation though, couldn't it?
Can you see a better way to do it? Remember that we learned about a
statement that can take in a string and give you a numeric value when we
talked about VAL in the string section. How about using VAL here? Add
this subprogram:
58 GOSUB 900
70 LET Y=VAL E$
179
TIM EX SI NC L A IR BASIC PRIM ER WI T H GR A PHI CS
N ow you can enter any valid arithmetic expression into the string E$
and you'll get a plot of it on your graph. You have to make sure that you do
indeed enter a valid arithmetic expression or you'll get an error message.
Complexities
Let's try graphing a function that's a little more complex:
Y=. 5 *X*X
Remember, all you have to enter is: .5*X*X . This one's called a quadratic or
second degree equation because it uses the independent variable squared in
its definition . The graph of this function is called a parabola (Fig. 8-8).
The following function is also a quadratic equation whose graph is a
parabola. Try it!!
and so is this:
Y= .5*X*X+ 5*X + l
When you plot these functions, you'll see they all have the same general
shape but they plot at different places in the coordinate system. Any equation
• •
••••••••••••••••••••••••••••••••••••••••
30 30
180
Functional Graphics
that has at most a squared term for the independent variable has a graph that
looks like this . The general from of the parabolic function is given by:
Y=A*X*X + B*X+C
and change the INPUT subprogram to check the first character and set the
switch accordingly.
and we can eliminate the special subprogram we put in to check for PLOT /
UNPLOT (lines 700 through 740).
Tired of parabolas? How about this one:
Y=50/ X
When you run it , you'll see that at X = 0, you get an error message. You see
why, don't you? Sure, we're dividing by X so when X = 0, then we're trying
to divide by 0, which to the computer, and to most of the rest of us, is a NO
NO.
It's an easy situation to handle, though. All we have to do is add a test
before we do the calculation to exclude the special case when X = 0 like:
181
TIMEX SINCLAIR BASIC PRIM ER WI T H GRAPHICS
So, add this statement to the PLOT subprogram. It will cause us to skip
right over the plot when X is zero. R un the program now and you'll see what
a hyperbola looks like.
Y=X*X*X / 100
This is called a cubic equation because the variable is taken to the third
power. (In case you're wondering, they call it a cubic, because the volume of
a cube, the general form of the cubic function, is:
182
Fun ctional Graph ics
DISAPPEARS
• Y=30 BEYOND SCREEN
...
•
•
•••
•
•
• • •
...•...•..•..•.•••...•....•.•..•....•.••
30 • 30
Y=30
••• Y=20
•
...
•
••••••••••••••••••••••••••••••••••••••••
30 30
183
TIM EX SI C L A IR BASIC PRIM ER WITH GR A PHI CS
57 GOSUB 700
700 PRINT AT 21.0;"SCALE7"
710 INPUT S
715 PRINT S
720 RETURN
Now, when you set up to plot, you can enter a scale factor that will
reduce the size along the vertical, Y dimension. You'll probably want to print
out the scale factor, too, so you know what degree of diminuation (or ampli-
fication) is being used. Besides all of the different functions you can make up
using *, 1, +, and - , there are all sorts of special numeric functions built into
the Timex computer just waiting for you to use. They call it function mode
because there are special calculation functions under the keys for you to use.
Y=SQR X
184
Fun ctional Graphics
x--------~L---------
y y
Y= ABS X
Remember, ADS is the function that takes a number, finds its absolute
value, and makes it positive. So the absolute value of - 6 is 6 and so is the
absolute value of 6 equal to 6.
Trigonometry Service
Now we'll try our hand plotting sines, cosines, and tangents; to do this, use
the SIN, COS, and TAN functions. We'll also introduce their opposite numbers,
or as the mathematicians say, their inverses: ARCSIN, ARCCOS, and ARC-
TAN. If you don't know anything about these functions, you can skip this part or
just follow along and watch. Enter the lines, but don't worry if you don't under-
stand every detail. It really makes no difference to your understanding of compu-
ters whether you understand these functions. They are only included because,
historically, the first heavy users of computers were scientists; and they use sine
and cosine all over the place in their work.
Try this one:
Y=SIN(2*PI *X/60)
185
TIM EX S I C L A IR BASI C PRIM ER WI T H GR A PHI CS
circle's circumference to its diameter, and is the function under the M key.
(The circumference of a circle is equal to pi * the diameter of the circle.) You
may be aware that pi is a constant which pops up all over the place in
mathematics . Because it occurs so much, the designers of the Timex compu-
ters decided to make it easy to type in the value of pi, by providing a special
key for it.
That nice curve we just plotted is called the sine curve and, with its
partner and close companion, the cosine curve (under the W key) , is used
extensively in scientific and engineering calculations.
We used a scale factor of 20 because the value of both the SIN and the
COS functions is always between plus and minus I. If we didn't scale it up
some, we'd get a squashed little straight curve hugging the coordinate axis for
each point, since Y would always be between 0 and 1.
Why the complicated expression in the sine function itself? Well, sine is
what mathematicians call a periodic fun ction. It repeats itself every so often,
forming an endless series of waves as you move in either direction along the
X axis. The total extent (distance) along the X axis that it takes for the sine
graph to complete one full cycle before it starts again is called its period. The
period of the SIN function is 2*pi units long.
Here's one other tricky point. The sine function (and , in fact , all the
trigonometric functions) takes its values not in degrees with which you're
most likely familiar, but in these funny engineering units called radians. 2*pi
radians equals 360 degrees so that I radian equals approximately 57 degrees.
Look at the sine function for a full cycle, from - pi through to pi. To
divide up this 2*pi into 60 equal parts, one for each incremental step of X, the
independent variable, we use that complex expression in the sine:
The first time through the loop, when X = - 30, then the value of the
expression is 2* - 30*pi / 60 = - pi, just where we want to start. Each suc-
cessive time through the loop, we move one small step over until at the end of
the loop when X = 30, the value of the expression is equal to pi. So, using
this expression will take you through one full cycle of a sine curve, as Fig.
8-12 shows.
If you want to graph more than one cycle of the sine curve on the axes,
you have to increase the multiplier inside the sine expression. Try this:
186
Functional Graphics
That's not bad for two full cycles. Try changing 70 to:
and try plotting first the sine function and then its faithful companion, the
cosine function COS , together on the screen.
Sine and cosine have the same basic shape but the curve for cosine is
shifted to the right relative to the sine. This isn't the place to go into it, but it
turns out that by adding together the proper combinations of sine and cosine
, rJ
0
x
" y
,/
187
TIM EX SI NC LA IR BASIC PRIM E R WI T H GR A PHI CS
functions , you can approximate almost any function you could imagine. This
technique of synthesizing functions out of sines and cosines is called Fourier
analysis and is very widely used in engineering.
Off On a Tangent
What about the TAN function? Try this one to give you an idea of what
the tangent curve looks like.
(TAN is the function under the E key. Use a scale factor of 10 for tangent!)
We have to use a slightly different expression for tangent because it has
different behavior than sine or cosine:
Y=ASN(X / 30)
Use a scale factor of 10. Don't be fooled by the fact that ARCSIN prints
out in the screen as ASN . Do you know why we are using X I 30 in the ASN
function? Try substituting the first few values of our basic X loop. When
X = - 30, then, the expression, X / 30 equals -30 / 30 or -I. The next time
through, X = - 29 , so X I 30 is equal to a little less than - I ( - 29 130) . At
t he end of the loop, when X = 30, the value ofX / 30 is I. So, effectively, we
have stepped the ARCSIN function through its entire range of - I to +1. By
188
Functional Graphics
using the expression as we've written it, you get a full period of the ARCSIN
function .
You can also plot out ARCCOS. ARCCOS is under the S key. Use a
scale factor of 10.
Y=ACS(X / 30)
And last but not least, ARCTAN, which is under the D key:
Y=ATN(XI2)
We'll show you two more functions on your Timex before you leave this
chapter. One of them is called LN , which stands for logarithm taken to the
base e.
Y=LN X
Y=EXP(X / 5)
EXP is under the X key; use a scale factor of I. This one is pretty interesting
too.
Y=EXP( - X/ 5)
Both LN and EXP (which are inverses like SIN and ARCSIN) are used
extensively in scientific calculations.
189
TIM EX SI CLAIR BASIC PRIM ER WI T H GR A PHI CS
You've now had a pretty extensive tour of the numeric functions that are
built into your computer. You can combine them any way you like to make
new functions, Y = SIN EXP X, for example, or COS + SIN. The only
thing you have to be careful of is to make sure that your functions stay within
range when you combine them. You're in for some fun and some real learn-
ing as you experiment with plotting the different graphs. Who knows, maybe
you'll discover a new function no one's ever seen before.
190
9
We've come a long way. Can you still remember how confusing your
keyboard looked to you 'way back in Chapter 2 when you first took it out of
the box? A lot of the words looked like English, but they were strange and
mostly unintelligible. To this point, we've covered just about every important
command that's implemented on your computer. We still need to cover a
couple of advanced topics and some commands to control a printer. When
we're done with this chapter, you'll be all set to go off and write almost any
kind of BASIC program the Timex computers will run.
Take another look at the averaging program that we used in Chapter 3.
10 LET A = 5
20 LET 8 = 10
30 LET C= 15
40 LET X=(A + 8+C) / 3
50 PRINT "THE AVERAGE IS "; X
10 LET A=5
20 LET 8 = 10
30 LET C= 15
191
TIMEX SI CLAIR BASIC PRIMER WITH GRAPHICS
NEW DIMENSIONS
Giving each variable its own personal name can be a little cumbersome,
don't you think? Well, computer scientists have figured out an easier way to
handle entire groups of related variables. You can give the whole group a
single name and distinguish one variable from another within the group by
using a number, called an index. It's like giving each variable its own post
office box number. For example, we can have 50 people (variables) each
getting mail (values) at the Silicon Gulch Post Office. The Postmaster knows
which mail goes where because, in addition to the name of the post office,
each piece of mail has a number that tells him where to put it. See Fig. 9-1.
If you visualize variables as boxes , the indexes work just like box
numbers. This procedure of giving each variable a name and numbers is
192
Advan ced BA S IC: A Taste of Thin gs To Co m e
10 DIM A(5)
20 FOR 1= 1 TO 5
30 INPUT A(I)
40 NEXT I
50 FOR 1= 1 TO 5
60 PRINT " A( "; I;")=";A(I)
70 NEXT 1
Run this program and you'll have to input five values, just as in the
averaging program. Each one is put into variable A(I) by line 30. As I steps
from 1 to 5, the INPUT statement puts the values you enter into A( I), then
A(2) , then A(3) , and so on, as shown in Fig. 9-2.
193
TIMEX SI CLAIR BASIC PR I MER WITH GRAPHICS
This is the way the DIM instruction works. You just tell the computer
how many boxes to reserve under the same name by entering DIM and the
variable's name. This is followed by the number of "boxes" you want to use
in parentheses. You must dimension variables at the beginning of a program
so that the computer knows how much space to set aside in storage for them.
Now, instead of giving each variable a distinctive name, we can use a
number, or a variable that takes on a numeric value, to refer to one. You can
certainly see how much easier this is , since now we can use a FOR NEXT
loop to handle a whole group of variables at one time.
Let's see what our averaging program looks like using a dimensioned
variable:
5DIM A(5)
10 FOR 1= 1 TO 5
20 PRINT "ENTER VALUES FOR NO. ";1
30 INPUT A(I)
40 LET A=A+A(I)
50 NEXT I
50 PRINT "THE AVERAGE IS " ;A/ 5
All right, run this and it works fine. It's a little shorter than the original,
but not much. Now, let's change it to average together ten values. Change
lines 5 and 60 to:
5 DIM (A)(10)
60 PRINT "THE AVERAGE IS ";A/ 10
N ow, maybe you can start to see the advantages of using dimensioned or
(as we say in the exciting world of high tech) subscripted variables . We've
saved ourselves quite a bit of work.
There are even more advantages to using dimensioned variables. By
adding a few more lines, and changing a couple more, we can make the
program take in any number of values and average them together. We'll use a
counter to see how many numbers we are actually taking in, and then divide
by this number instead of a fixed number.
We've got to make the DIM statement big enough so that we leave space
for the maximum number of values that we think we'll use, say 25.
194
Advan ced BA S IC: A Tasle of Things To Come
5 DIM A(25)
10 FOR 1= 1 TO 25
20 INPUT A(I)
30 IF A(I)=- 1 THEN GOTO 60
40 LET A =A +A(I)
50 NEXT I
60 LET N==I - 1
65 IF 1==25 THEN LET N= 25
70 PRINT " THE AVERAGE OF ";N ;" VALUES IS " A / N
Now you can enter up to 25 values and average them. This is certainly an
improvement over the old averaging program which used a fixed number of
values.
Can you figure out how the IF THEN at line 30 works? We pick a value
that we know will not normally occur as one of the values we want to
average. Then, when we've input all the numbers we want, we type in the
ending value. In our case, we picked -I , but you should choose any value
that's easy to type in and unlikely to come up as one of the numeric values to
be averaged . (You could use a really big number, for example, I E30) .
If the ending value is entered , we jump to line 60. You see why we
subtract I there, don't you? Sure! It's because the last value we entered is a
dummy value, so we need to subtract I from the counter to make sure that we
are dividing by the actual number of numeric values that we've entered, not
including the last entry which signified END . Line 65 ensures that if we do
enter the maximum number of values, we use the correct number for dividing
by. Otherwise, if we did enter the full 25 values and left the FOR NEXT loop
normally, we'd subtract I and be dividing by 24, which is I too small.
It's easy to make this program reusable, but there's a new command
you've got to learn just to stay on the safe side. Add:
3 CLEAR
80 GOTO 3
195
TIM EX SI NCLAI R BASIC PRIM ER WITH GRAPHICS
around, though, our old val ues will be sitting in our arrays since the compu-
ter won't automatically clear them this time.
To keep things in order, the computer has a CLEAR command, that
takes care of this for you. Now, when we get to 80, we'll jump to line 3 where
we can reset everything to O.
Expanding Dimensions
Let's expand this example just a bit into the real world to give you the
full flavor of dimensioned variables. We'll write a program that will allow
you to take in a group of numbers, say test scores, and compute the average.
You'll also be able to associate the average with a student's name. We'll set
up the program so that you can do this for several people in sequence.
Finally, we'll print out a graphic comparison of the average test scores. See
Fig. 9-3 .
We could follow the same procedure as we did in our first averaging
program .
10 DIM A(10)
11 DIM 8(10)
12 DIM C(10)
and so on, for each one of the students. This, as you can see, gets very
inconvenient fast. It mimics the problem we saw at the very beginning. There
is a better way which uses the same principles that we've used before to go
from the undimensioned to the one-dimensioned variable.
You can give a variable two or more dimensions! Type in and run this
program to see how we can use the two-dimensioned array:
10 DIM T(10,10)
11 DIM S(10)
12DIMN(10)
20 FOR J = l TO 10
30 FOR J = l TO 10
40 PRINT AT 3,0;"ENTER SCORES FOR STUDENT NO: ";I
50 INPUT T(I ,J)
60 IF T(I ,J)=- 1 THEN GOTO 100
70 LET S(I)=S(I)+T(I,J)
80 NEXT J
90 IF J = l 0 THEN LET J = ll
196
A dvan ced BA S IC: A TO.l'le of Thin f{s To Come
YES
YES
We've slipped in a few extra features here. Let's go over this program
carefully to make sure that it's understandable.
First, we've set up a two-dimensional array T( 10, 10) to hold all of the
students' test scores. The first number of the variable T tells which student
number we are going to enter the values into; the second tells you which of
the tests we are entering.
197
TIMEX SINCLAIR BASIC PRIMER WITH GRAPHICS
So, for example, Student l's test scores will go into variables: T(l , I);
T(I ,2); T( I ,3); . ..
The second student's scores go into: T(2, I); T(2,2); T(2, 3) and so on,
down the line until we run out of students (or exceed 10 students).
Besides the array T to hold test values for each student, we need to use
two other dimensioned variables. S( 10) will hold the cumulative sum of each
student's test scores. So, for example, S( I) will be the sum of Student I's test
scores; S(2), Student 2's, and so on. N( 10) will hold the actual number of tests
that each student took (Fig. 9-4).
The nested FOR NEXT loops here handle the two-dimensional array.
With the outer loop, we step through the initial variable to set I to each
student's number in turn. Then we use the inner J loop to enter a given
student's test scores.
When we're done with that student, we enter the ending value, -I, and
line 60 jumps us out of the inner loop. Now, I gets incremented by I and we
198
Advan ced S A SIC: A Taste a/" Things To Come
go on to the next student with I = 2. The inner loop gets all the tests for a
given student; the outer loop steps through the students themselves, one at a
time. Line 70 here has the same function as line 40 in the earlier program . It
adds the newly entered value to the total to get the sum of scores for the
averaging computation.
By taking in the number of scores entered and putting it into a dimen-
sioned variable, N( 10), we can divide each student's average by the actual
number of tests taken, making our program less restrictive than if we
required all of the averages to be computed on the basis of the same number
of exams.
We hope you're getting the idea that there's really something to dimen-
sioned variables . See how easy it is to associate the cumulative numbers with
each student's actual number of tests?
Since we're using dimensioned variables, we just divide the sum for
Student I, S(l) , by the number of tests he took, N(I). Then we do the same
for Student 2, S(2) / N(2); and so on for each student.
Because we have put our values into dimensioned variables, we can
simply match up the right values using a FOR NEXT loop when we print
things out at line 160.
Stringy Dimensions
You can put strings into dimensioned arrays, too. For instance, we
could add some lines which would enable us to associate each student with a
name. Add this line:
5 DIM N$(10.10)
199
TIMEX SINCLAIR BASIC PRIMER WITH GRAPHICS
10 DIM T(5,5)
11 DIM S(5)
12 DIM N(5)
20 FOR 1= 1 TO 5
30 FOR J = 1 TO 5
25 PRINT AT 3,3;"NAME?"
26 INPUT N$ (I)
27 PRINT N$ (I)
We'll print it out too, just for reference. Notice that since we've already told
the computer that N$ is a group or list of strings, by dimensioning N$ at line
5, it doesn't try to pull a single character out of plain old N$. The computer
knows to check for an entire string to put into position on the list.
Change lines 120 and 140 to read :
200
A d van ced BA SIC: A Taste of Things To Com e
5 DIM N$(5,5)
10 DIM T(5,5)
11 DIM S(5)
12 DIM N(5)
20 FOR 1= 1 TO 5
25 PRINT AT 3,3;"NAME? "
26 INPUT N$(I)
30 FOR J = 1 TO 10
40 PRINT AT 3,O; " ENTER SCORES FOR STUDENT NO;"; I
50 INPUT T(I,J)
60 IF T(I,J)= - 1 THEN GOTO 100
70 LET S(I)=S(I)+T(I,J)
80 NEXT J
90 IF J = 5 THEN LET J = 6
100 LET N(I)=J - 1
110 NEXT 1
120 PRINT AT 5, 1;"STUDENT ";TAB 10;"AVERAGE"
201
TIMEX SINCLAIR BASIC PRIMER WITH GRAPHICS
130 FOR 1= 1 TO 5
140 PRINT N$(I);TAB 10;S(I)/ N(I)
150NEXTI
200 PRINT AT 21,1 ;"MORE7"
210 IF INKEY$ = .... THEN GOTO 210
220 LET A$ =INKEY$
230 IF A$ ="N" THEN STOP
240 CLEAR
250 CLS
260 GOTO 20
Run this program a couple of times and see how you like it. It works
pretty well. You enter the student's name, then the scores; this is about as
straightforward as you could expect.
There are still a lot of things we could do to this program to make it
easier to use. We might, for example, cue the user that we want a new name
by adding this line to print as we exit the loop:
You might also want to add some protection routines to check the input
to make sure that we really enter a number when we are supposed to. Other-
wise, you just might get one of those 2/ 50 errors after you've already entered
20 test scores. You should know how to do that by now, so we'll leave it to
you.
What about printing a graphic comparison of the scores? How about
this:
160 FOR 1= 1 TO 5
170 PRINT AT 14+I, O;N$(I);
180 LET S=INT (S(I)/ 5)
190 FOR J = l TO S
200 PRINT AT 14+1, J + 10; ... ..
210 NEXT J
220 NEXT 1
How's that? First we print the name on the line, then we scale the grades,
by dividing all the averages by 5, so that instead of being in the range of I to
202
A d van ced BA SIC: A Taste of Thinf?s To Co m e
100, they lie in the range of 0 to 20. Then we can use a FOR NEXT loop with
PRINT AT in line 200 to print a block of squares proportional to the scaled
length. We've set things up so that the graphics will be printed from columns
10 through 30.
Now that you've got your data array in memory, there are all sorts of
statistical tests you could do on it, if you needed to. And the secret lies in the
efficiency of dimensioned arrays and FOR NEXT loops to handle them. We
won't go into statistics here because that's another subject, but you should
really have a feeling, at this point, of just how powerful subscripted arrays
can be. In fact , much of modern data analysis deals with manipulating large
arrays.
PEEK-A-BOO
There are a few more commands we'll need to cover to give you the
complete introduction. As a beginner, you probably won't have much use for
them now, but hold on to the ideas we introduce here. As you get deeper and
deeper into programming, you're going to want to use them more and more
because they allow you to squeeze a lot more power out of your computer.
They are called PEEK and PO KE, and by using them, you can get right
down into your computer's memory and actually control each word , bit by
bit, if you want to.
You might think of PEEK and POKE as providing you with a means of
controlling the computer that is analogous to the use of standard transmis-
sion on a car. Using regular BASIC is like running with an automatic. This is
fine for most jobs and much easier to use than a standard transmission, but,
when you really need to get every ounce of power out of your engine, you've
got to use a standard (manual) transmission. You may need to work a little
harder, a lot harder, actually, especially in heavy stop-and-go traffic, but
once you get shifting mastered, you can really move along if you want to.
203
TIMEX SI CLAIR BASIC PRIMER WITH GRAPHICS
Hmmm, the numbers are always integers. The smallest is 6, the biggest is
254. In fact, the value returned by PEEK will always lie between 0 and 255 .
That 0-to-255 range has come up a bunch of times before. That's because the
biggest number that can be stored in anyone 8-bit cell of your computer's
memory is 255. The BASIC language actually uses several cells of memory to
store a regular variable. That's why the computer using BASIC can handle
numbers bigger than 255, much bigger, if need be.
You might also understand now why there are 256 different character
codes. Right! Because each character code takes up exactly one memory
location.
Each memory cell in your computer has its own address. Lots of the cells
in your computer have values permanently written into them. These make up
the program that sits permanently in your computer and is activated when
you turn it on. It's this built-in program that takes the BASIC programs that
you write and turns them into programs in the computer's own special inter-
nallanguage. This machine language is much harder for us humans to use so
we let the computer do the translation for us. The computer's internal lan-
guage looks much different than the BASIC language (Fig. 9-6).
To use PEEK, tell the computer which cell you want to look at. The
highest location you can use with a Timex and 2K of memory is 18432. You
see, even though there are more than 2000 memory locations free for you to
use (that's RAM , remember), there are many more locations used by the
permanent program, so the address numbers can get fairl y large. To find out
the highest address of memory, type:
204
Advan ced S A S IC: A Taste of Things To Come
78 PAUSE LD A.B
3D HOLD DEC A
20FD JR NZ.HOLD
C9 RET
CDB B02 START CALL KSCAN
44 LD B.H
51 LD C.L
14 INC 0
28F7 JR NZ.START
16389, the address of the top of memory. The 256 is there as a multiplier,
because of the way in which the computer handles numbers larger than it can
store in one cell. That's only 256, remember, much less than 18432.
Let's enlarge our PEEK program so you can take a little look around in
the Timex's memory at will.
5 lET P= l
7ClS
10 PRINT AT 1,1 ;"START, RANGE"
20 INPUT I
30 INPUT J
40 PRINT AT 1,1 ;" LOCATIONS " ;1;" TO "; I+J
50 PRINT
60 FOR K= l TO I+J
70 IF P>=20 THEN SCROll
80 PRINT TAB5;K;TAB 12;PEEK K
90 lET P=P= l
95 NEXT K
100PRINTAT21 , l ;"MORE?
110 IF INKEY$ =" 'THEN GOTO 110
120 lET A$=INKEY$
130 IF A$= " N" THEN STOP
140 GOTO 5
You shouldn't have any trouble figuring out how this program works.
First, you input the address of the first memory location you want to start
looking at. Then you input how many cells in a row you want to look at.
We've set things up so that if you enter more than 20 cells to look at, the
205
TIMEX SI CLAIR BASIC PRIMER WITH GRAPHICS
screen will automatically scroll upwards. (We use P as line counter and then
use line 70 to SCROLL upwards, if necessary.) We enter these initial values
into a FOR NEXT loop at line 60 and then just print out the PEEKs.
When you're programming in BASIC, you don't have to worry too
much about memory, unless you're about to run out of space. But memory
locations are actually separate physical locations inside the computer. One
can, and computer people do it all the time, make up a map of the memory
showing what values are actually being stored in each location as a program
is being run. Some of these can change, of course, as the computer executes
different lines.
Let's take a look into locations 16509 t hrough 16530. This is the place in
memory where the computer actually begins storing the very program you've
entered into it. So you're actually using the program to look at itself. This is
illustrated in Fig. 9-7.
In location 16510, you see 5, that's the first line number in your pro-
gram. The number 16511 has the total number of cells following that are
saved for line 5, in this case, 11. At 16513 through 16516 are the codes:
Code Meaning
241 LET
53 P
20 =
29
You can check Appendix A for a list of character codes. Don't worry about
the extra numbers, in some of the intermediate locations, they're used by the
computer for things you needn't concern yourself about.
The "7" at 16525 is line 7, the next line of the program. And at 16528, we
have the 251 which corresponds to CLS. How about that? You've discovered
your program's actual location inside of the memory. If you keep on looking
through the memory, you should be able to find each and every program line.
Try looking around 16709. You'll see:
Code Meaning
243 NEXT
48 K
118 ENTER
206
A d van ced BA SI C: A Taste of Thin f?s To Co m e
I t shouldn't take you too long to realize that code 118 follows every
program line. This makes sense, of course, because to enter any line you've
got to press ENTER which, if you check your character code list, has code
number 118.
N eat, isn't it? Now you can browse around right in the computer's
memory at will.
Screen Memory
Try this little experiment. With the program running, get the values in
locations 16396 and 16397. Take these numbers and calculate a new value by
adding the number found in 16396 to 256 times the number in 16397:
(Value in 16396) +(Value in 16397*256)
or in BASIC:
I got 16848, but your number may be different if your program isn't
identical, letter for letter, and keyword for keyword . Using this value, print
out the next 15 or so memory locations.
207
TIMEX SINCLAIR BASIC PRIMER WITH GRAPHICS
Check these against your character code chart and see if you can figure
out what part of the memory we're looking at now. Did you get it right away?
We're looking at the memory locations which contain the code values of the
characters that are being printed to the screen. First there are a couple of
) 18s. These are the boundaries that are used to separate one line of text from
another one.
Check the sequence 49, 52, 40 L 0 C ... What do you know? It's the
words you're already looking at right up on the screen. How do you like that?
This system for creating the screen display is called memory mapping.
Each pixel on the screen has its own memory location (Fig. 9-8). Special
circuits scan these memory locations and continuously redraw on the screen
the characters corresponding to the codes contained in the relevant address.
This is done so quickly that our eyes see a stable, nonflickering image.
N ow that you've found the location of the tv display area we are ready to
try the other half of our dynamic-duo, POKE.
Let's write a little program to tryout POKE. I'd recommend saving the
memory viewer program before you start poking around because it's easy to
make the computer act crazy if you POKE around in any sensitive areas of its
memory. You can easily, as they say in the hallowed halls of computerdom,
crash your program. If this happens, you can't get back to it all. You've got
to turn off the power and you lose everything in memory.
208
A d vanced BA SIC: A Taste of Things To Come
This number is one more than the last available location in memory. (On
a T I S 1000 with 2K memory, the highest memory location is 18304.)
As you can see, you type POKE, followed by the address you want to
look at, comma, and then the value you want to put into memory. Try and
see if you can POKE a value greater than 255. (You can't)
You can use POKE to take very fast and precise control of the computer
once you've learned how to program in the machine's own internal language.
As we've pointed out before, this is different from the BASIC language which
you use to communicate with your machine. Machine language is a fairly
complex topic and we won't go into it in this book. You should be aware of
its existence, though; when you get more advanced in programming you'll be
sure to learn more about how it works.
We'll use a very simple example of POKE to show what you might do
with it. We've already discovered that there's a part of memory which con-
tains the actual characters that the computer is displaying on the screen. We
use this information to make a program that pokes characters directly into
the screen display area in memory. Now, instead of using PRINT AT, you
can POKE the characters right up onto the screen. It's a wee bit tricky
because of the slightly eccentric way in which the Timex works with the
screen, so follow along carefully and type in:
209
TIM EX SI NCLAIR BASIC PRIM ER WITH GRAPHICS
10 FOR 1=0 TO 21
20 PRINT " 32 BLANKS "
30 NEXT I
40 PRINT AT 1,1;"WHAT?"
41 INPUT A
50 PRINT AT 1,1 ;"WHERE?"
51 INPUT B
60 PRINT AT 1,1 ; " (six blanks)"
70 LET M =PEEK 16396+ 256*PEEK 16397
80 POKE M +B,A
90 GOTO 50
Run the program. After a slight pause, you'll see the questions . First,
enter the code of the character you want to put on the screen. You can enter
any number from 0 to 255 , though as you know by now, not all of the
numbers mean something to the computer. Try sticking with things you
know, until you get the hang of it. Don't enter 118! Because of the technical
details of how the computer maps out the screen display, entering 118s will
undoubtedly mess things up and probably crash your program.
In response to "WHERE?," enter the position in which you want to
place the character. There are 22 lines of 32 characters each on the screen.
Position I is the first pixel on the top line, position 2 is the second, etc.
Position 32 is a 118 line separator, and position 33 is the first position in the
second line. Fig. 9-9 shows how the screen is mapped out by the computer.
Row
Starting address 16396 I I 2 3 32
2 33 34 35 65
3 66 67 68 98
4
-
-
-
33
-
-
-
200
210
Advan ced BASIC: A Tas te 0/ Thin f{s To Co m e
There are a couple more minor points to cover before we deliver you to
Mini-Maze in Chapter 10.
211
TIMEX SINCLAIR BASIC PRIMER WITH GRAPHICS
to use it. If you know how to write subprograms in machine language, you
can GOSUB to them using USR in the same way you GOSUB to a BASIC
language subprogram. The only difference is that for USR , you have to give
the actual memory location containing the subprogram.
We're not going to say any more about USR , because that's really a
topic for another book. Just like any other subprogram, you've got to have a
return at the end to get back to the main program again, but this return has
to be written in machine language.
10 FAST
calculations
150 SLOW
graphics routines
You've got to use slow mode for realtime graphics displays, like the ball
bounce or Mini-Maze games. Otherwise, the decision is yours, a gray screen
for a little while, or a slower program.
212
A d van ced S A S IC: A Taste of Things To Co m e
Printers
Thus far we haven't mentioned anything at all about printers because
they've been hard to get and fairly expensive. We've assumed you wanted to
find out about computers with the minimum investment, so that a printer
wouldn't be on your shopping list. You can, however, get a decent quality
printer for less than $100.
There are three commands specially included to control the printer:
LPRINT, LLIST, COPY.
LPRINT (SHIFT S) and LLIST (SHIFT G) work just like PRINT and
LIST, only the strings and variables get sent to your printer instead of going
to the screen. You could rewrite any program in this book, replacing all of
the PRINT statements with LPRINTs and you'd have a complete written
record of your program's output.
LLIST is useful, in the same vein, to save a permanent written copy of
your programs. (In case, you're wondering, the "L" stands for line printer, a
throwback to the old days of computing.)
COPY (over the Z key) allows you to copy the entire contents of the
screen display area to the printer. This is called a screen dump in the trade
and you'll find it quite useful. For instance, you can use your function
plotting program to plot functions on the screen and then copy them to the
printer to get a real-paper graph.
PERFUNCTORY ENDINGS
Well, you've met all of the keywords, functions, and operators that are
implemented on the Timex computers. We hope you've had some fun along
the way and that you've learned to feel comfortable using a computer. Relax
a little now and savor your new-found skills and understanding, before you
plunge ahead to some Mini-Maze action in the final chapter.
213
10
In this chapter, in order to get some practice using what we've learned
and to have some fun at the same time, we are going to design and program a
game. The type of game we've chosen to use is a maze game. It contains some
fundamental elements, in simplified form, of some popular arcade and home
video games.
This chapter tries to do several things:
1. Give you some ideas on how to go about planning and carrying out a
programming project.
2. Provide a game that you can actually enjoy playing.
3. Introduce certain techniques that may be helpful in writing your own
programs.
What are the elements that we want to include in the game? First, we
need a design for the maze. Second, we need a symbol or character which
represents the player and that can be moved around the maze. We need some
way to score points and, of course, we need some form of "danger" or
215
TIM EX SI CLA IR BA S I C PRIM E R WI T H GR A PHI CS
condition under which the game will end. One well-known maze game incor-
porates all these elements. It has a character that moves around a maze,
scoring points as it "eats" dots and other assorted figures , and losing when it
collides with one of the creatures that chase it around the maze.
For the first step then, let's design the maze. In our game, we will use a
maze that will look like Fig. 10-1 .
•• • • • • • • • • • • • ••
••• • • • ••• • • • •••
$
•• •• • • • •• ••
•• • • • ••
$
•• • • • •• • • • ••
•• •• • • • • • ••
••• • • •• • • • • • • •• • •••
R
The maze is made up of the following characters. The black borders and
the barriers in the maze are inverse spaces , that is, "black" spaces. The code
for this character is 128.
The dots are periods, code 27.
The R (code 55) at the bottom of the maze is our hero, the player that we
will move around the maze while playing the game. You can easily change
this to any character you like, the initial of your first name, or one of the
graphics symbols. If you change it, remember to substitute the corresponding
character code where you see code 55 in the program.
The two dollar signs, $, will be programmed to appear in random loca-
tions on the screen. The code for $ is 13 .
The maze in our program is 16 rows by 13 columns. This is a little less
than the maximum size for a rectangular maze. The maximum is 22 X 32 (or
704 characters) which represents the full screen display that is available to
you; that is, it doesn't include the two lines at the bottom that the Timex
system uses.
216
Th e Mini- Ma ze Game
One reason to keep the maze fairly small is that each character in the
screen display takes up one byte of memory. We're designing our program to
work in 2K of memory (2096 bytes). Making the display smaller gives us
more room to do interesting things with the program. We'll be discussing the
display file , the area of memory which contains a record of what's on the
screen, in more detail later.
To play the game, we need a way to move our symbol or character
around the screen. To do this, we will take advantage of the INKEY$ feature
that allows the computer to respond instantly to keyboard input (without the
need to use ENTER). We'll use four separate keys to move the player up,
down, left, or right. We've chosen these keys: W for up, X for down, A for
left, and D for right. See Fig. 10-2.
MOVES UP
Q 0 E
Z 0 C
MOVES DOWN
Here's how we'll score points. Whenever we move the player to a loca-
tion which contains a dot, we will score 10 points and the dot will disappear;
a blank will replace the dot.
Whenever R lands on a $, we'll score 100 points . The $ will disappear
from its current location and a new one will appear randomly somewhere else
on the screen. There will always be two $ symbols on the board .
To provide an element of danger, it would be nice if we could have
monsters which chased us around the screen. However, this would be too
complex to program with the amount of memory available and it would slow
the program down too much. Instead of a gobbling monster, with the limited
memory we're working with, we'll design the game so that we'll lose if we run
into one of the black walls or barriers.
217
TIMEX SINCLAIR BASIC PRIM ER WITH GRAPHICS
218
Th e Mini-Ma ze Gam e
LINE NUMBERS
100
350
400
430
500
The first thing we need to do is to print the maze. Our maze consists of
16 rows of 13 characters each. One way to print the maze would be to write
16 statements like this:
219
T IM EX SI NC LAIR BASIC PRIM ER WI T H GRAPHICS
Another method would take advantage of the fact that there are only 6
different 13-character strings which make up the 16 rows. So we can assign
each of those strings to a variable, like this:
100 PRINT US
110 PRINT VS
120 PRINTWS
etc.
370 CLEAR
after printing the maze . This clears (i.e., releases the memory space devoted
to) the variables that have been used so far in the program . We can do this
because, once we've printed the maze, we have no further use for these
variables.
The next step, initializing the score, is simple. We'll use a variable S to
represent the score and we'll print the score on the first line below the maze .
See lines 380-390.
220
Th e Mini-Ma ze Game
be pretty straightforward. Note that 14,6 is the 15th row and 7th column, since
the first row and first column are numbered 0.
However, we're going to have to do more than just place the R on the screen.
First, we have to have a way to move the character around the screen in response
to input from the keyboard . Second, when we move the character to a new
location, we want to detect what other character was previously in that location.
Then, depending on whether it was a ., . , or $, we'll score 0, 10, or 100 points;
or lose if we crash into a • .
In order to do these things, we will make use of the display file. The display
file is an area of RAM memory that contains a record of whatever is printed on
the tv screen. For our purposes, it is important to understand how the display file
is organized. See Fig. 10-4.
The first byte of the display file contains the character code for an ENTER
character, 118. This is followed by the codes for each character in the first line on
the screen, up to 32 characters. Trailing spaces (i.e. , all spaces after the last
nons pace character) are omitted . Then there is another ENTER , followed by the
next line, and so on. There will be a total of 24 lines (only the first 22 are
accessible by the programmer), each of which will contain 0 to 32 characters,
followed by 118.
In our program, the first 16 display lines will consist of our maze. Each
line is exactly 13 characters long. Therefore, we can visualize the part of the
display file that contains the maze as being organized like Fig. 10-5.
The next task is to use this information to enter the R , move it around
the screen, and detect other characters. This is done by P O KE and PEEK
instructions .
P O KE , as you will recall from Chapter 9, allows us to enter a number
into a memory location in RAM. It takes the form:
When we poke a value into a location that is part of the display file, the
221
TIM EX SINCLAIR BASIC PRIM ER WI TH GR APHIC S
character whose code is that value will appear on the screen in the position
corresponding to the memory location.
So, if we want an R to appear on the screen, we need to know what
location corresponds to the screen position. To answer this, we need to know
the starting address in memory of the display file.
When running a program, the computer assigns an area in memory to
the display file. The starting address of the display file varies from program
to program, but there is a fixed two-byte location in RAM (bytes 16396 and
16397) which contains a variable called D-FILE. D-FILE points to (that is, it
contains) the starting address of the display file. Incidentally, D-FILE is not
a BASIC name but a convenient way of referring to this area of memory.
D-FILE is one of a number of system variables which contain data relating
to the operation of the program. See Fig. 10-6.
D·FllE
xI yI
16347 16396
To obtain the starting address of the display file (where we'll put in D),
we write:
To place R at position 14,6, we have to figure out how far this is from
222
Th e Mini-Maze Game
the beginning of the display file . Each row contains 24 characters plus
ENTER . Therefore, we have to skip 14 X 14 ( = 196) to get to the beginning
of row 14, and then add 7 to get to the 7th character in row 24. This will do it:
has the effect of printing two random dollar signs on the screen.
Let's look at this subroutine;
223
TIM EX SI CLA IR BASIC PR I M ER WI T H GR A PHI CS
which checks for one of these characters and sends us back to generate
another random location if it finds one. If not, we execute:
830 RETURN
which transfers control back to the statement after the one that called the
subroutine. Refer to Fig. 10-7.
LI NE NUMBER
GENERATE
800 RANDOM SCREEN
POSITION
224
The Mini-Maze Game
225
T IM EX S I NCLA IR BAS I C PRIM E R WI T H GR A PHI CS
subroutine will be called during the game part of the program, every time a $
is captured. Fig. 10-8 shows the flowchart for the subroutine.
900
YES
910
NO
920
YES
930
If T becomes zero (i.e. , PEEK 16437 = 128), we want to end the game.
However, if we missed checking the time when PEEK 16437 was exactly 128,
it would recycle to 255 and the value of T would become (255 - J 28)*4.2667
= 54 I and the program wouldn't stop. So we adjust for this possibility with
this:
226
The Mini-Ma ze Game
Then we print the new time. We follow this by two spaces, in order to erase
the previous time in case it had more digits than the current time:
Line 1000 refers to our termination routine which we' ll discuss shortly.
Here is the flowchart (Fig. 10-9) for the game-playing part of the
program.
The first thing that happens in this section of the program is that the
computer reads the keyboard input.
Whatever character you are pressing when this statement is executed will be
assigned to the string variable B$. If you don't happen to be pressing any key
at the time, B$ will be an "empty" string. Therefore, the following statement
is necessary so that further computing will not proceed until you have actu-
ally pressed a key. The computer waits for yo u, looping indefinitely until
INKEY$ detects an actual character.
Earlier we discovered that we could move our symbol on the screen by
changing the value of the position in the display file using these keys:
227
TIM EX SINCLAIR BA S IC PRIM E R WITH GRAPHICS
600
620
630
660 670
710
720
730 740
750
770
760
228
Th e Mini- Maze Game
LET PI=P + II AND B$= "D")- II AND B$= "A")+11 4 AND B$= " X")-1l4 AND B$ = "W")
'----.---' ~ '----"" ~
t
o
to t
14
to
Code Meaning
0 space
13 $
17
$18
•
CODE IRl ls 128 + 55 = 183
Ii1
Line 620 accomplishes the sa me thing in one long statement. This state-
ment may require so me explanation.
229
TIM EX SI CLAIR BASIC PRIM ER WITH GR A PHI CS
620 LET P1 = P+(1 AND 8$ = "0") - (1 AND 8$ = "A " )+ (14 AND 8$ ="X" ) - (14
AND 8$ ="W")
LET P1 = P+ (1 AND 8$ = "0 " ) - (1 AND 8$ = "A")+ (14 AND 8$ ="X" ) - (14 AND
8$ = " W " )
and the net effect is LET P = P + 14. Therefore , by pressing X, we move our
symbol down one line.
If you have a 16K RAM memory pack plugged into your T / S 1000, or if
you have a T / S 1500, you need to change line 620 to read :
620 LET P1 = P+ (1 AND 8$ ="0") - (1 AND 8$ ="A " )+ (33 AND 84="X" )
- (33 AND 84="W " )
checks for this. It se nds control back to line 600 to wait for one of our four
control keys to be pressed .
If PI is indeed different from P , we need :
230
The Mini-Ma ze Gam e
and the game is over. We will also branch to this same routine if we end the
game because we have run out of time.
Assuming we're still in the game, we're at:
Here we actually move R to its new screen position at PI. Now that R has
moved , we can update our position:
700 LET P+ P1
231
TIMEX SI CLAIR BASIC PRIM ER WITH GRAPHICS
If we moved to where there had previously been a space, we get no points and
we're not checking the time, so we go back to get a new keyboard input:
720 LET S =S + 10
After we check the timer, print the updated score, and go back to the
beginning of the game section to get another input:
And that's our program! Except for one thing: since we have a little
more room in memory, we'll print a little introduction to our game (lines
10-90). You can write your own introduction or eliminate it entirely, if you
like.
Enjoy the game and feel free to experiment with your own modifications.
There is one caution. This program very nearly exhausts the 2K memory
space available in the T / S 1000. Therefore if you try to make any major
additions to the program, yo u may find that you don't have enough space.
232
The Mini- Maze Game
370 CLEAR
380 LET S=O
390 PRINT AT 16,1;"'SCORE: 0 ""
233
TIMEX S I CLA IR BASIC PRIM E R WI T H GRAPHICS
234
APPENDIX
0 0 C "' [!
SPACE 9 g 0
""'odD 18 >
1 ~ 0
shifted 1 10 Ej 0
Shlfted 5 19 <
2 ~ 0
shrtteo2 11 " 20 =
~ ....... ,
0
3 12 £ 21 +
4 ~ ",...,.
0
13 $ 22 -
5 IJ -,."0
14 23 *
6 ~ 0
stuf'ted T 15 ? 24 /
7 ~ 0
"""... E 16 ( 25 ,
8 &I 0
stufted A 17 ) 26 ,
235
Code Character Code Character Code Character
27 45 H 63 Z
28 0 46 I 64 RND
29 I 47 J 65 INKEYS
30 2 48 K 66 PI
32 4 50 M 112 cursor up
36 8 54 Q 116 GRAPHICS
37 9 55 R 117 EDIT
38 A 56 S 118 ENTER
39 B 57 T 119 DELETE
40 C 58 U 120 L / K mode
41 D 59 V 121 FUNCTION
43 F 61 X 126 number
44 G 62 Y 127 cursor
236
Code Character Code Character Code Character
128
129
•
~
B
SPACE
B
shifted 0
146
147
inverse>
inverse <
164
165
inverse 8
inverse 9
130 ~ B
shifted W 148 Inverse = 166 inverse A
131 ~ B
Shrtle<l6 149 inverse + 167 inverse B
132 ~ B
shifted A 150 Inverse - 168 inverse C
133 [] B
shifted 8
151 inverse * 169 inverse D
~
B
134 shrfled Y 152 inverse / 170 inverse E
~
B
135 shifted 3 153 Inverse ; 171 inverse F
136 m B
shifted H
154 Inverse , 172 inverse G
137 II B
shllted G 155 Inverse. 173 inverse H
138 II B
shifted F 156 inverse 0 174 inverse I
237
Code Character Code Character Code Character
238
Code Character Code Character Code Character
239
Index
A Building programs, 128-137
ABS , 94
Action, 93-96
C
Address, 17
Adjusting set, 31 Cables and cords, 22-23
Alphabetics, 145-146 Chain of command , breaking, 161-162
Amateur, 12 Chance and necessity (a program),
Am plifica tion, 184 124-127
Anatomy of Character(s) ,
IF T HE statement, 87-88 getting rid of unwanted , 42-43
PRI T statement, 47 set, Timex, 235-239
AND,96 strings, different, 220
Announcing INKEY$ , 100- 101 Chips, silicon, 15
ARCCOS , 185 CHRS , 146
ARCSIN,185 CLEAR , 195
ARCTAN , 185 Clowning around, 83-84
Arithmetic by computer, 35-37 CLS , 89
Arrays, 196 CODE, 146
ASCII , 146 Command , ready to take, 153-157
Assembly, final program , 135-137 Commas make columns, 52-53
Audio plugs, 22 Complexities, 180-182
Computer, arithmetic by, 35-37
B
Concatenation, 140
BASIC, 45 Condition, 87
language, 19-20 Conditionals, 129
training, 45-80 Connecting
Between the lines, 49-50 cords, 28
Bits, 17 television, 27-28
Bottom-up programming, 218 Constructing the game, 215-218
Bouncing ball, follow the, 96-98 CONT,84
Branch, 121 Controlling the cursor, 40-41
unconditional, 82 COPY , 213
BREAK , 84, 89 Cords, cables and , 22-23
Breaking the chain of command, COS, 185
161-162 CPU area, 15-16
241
INDEX
Crash,208 Executes, 81
reset, 32-33 Expanding dimensions, 196-199
Cubic equation, 182 Exponentiation, 189
Current line, 46 Extent, 186
Cursor, 29
F
o Fancy style printing, 58-60
Debug, 120 Fast modes, slow and , 212
Decisions, decisions, decisions, File, using the display, 220-224
8 1-104 Final program assembly, 135-137
Decoding strings: CODE and CHRS, First
146-148 command , 33-35
DELETE , 42 shot, 174-175
Deleting, 40 Flowchart , 128
Dependent variable, 175 Follow the bouncing ball, 96-98
Designing the program , 218-227 FOR,89
D-FILE, 222 FOR NEXT, 90
Dice by design , 129-130 FRAMES, 225
DlM , 30 Friendly, user, 151
Dimensioning, 192- 193 Full control programming. 112-118
Dimensions Functional graphics, 167-190
expanding, 196-199 Function(s)
new, 192-203 graphs and, 175-184
stringy, 199-203 mode. 54, 184
Diminuation, 184 periodic, 186
Display file, using, 220-224 work, fancy. 184-189
E G
EDIT,58 Game
better way to, 40-43 constructing, 215-218
Endings, perfunctory, 213 Mini-Maze, 215-234
ENTER , 34, 79 section , 227-234
Equal or less than, 99 Getting
Equation rid of unwanted characters,
cubic, 182 42-43
linear, 178 started , 21-43
Erasing Going in circles, 81-84
lines, 50 Good value: V A L, 148-151
program , 48 GOSUB, 120-124
242
INDEX
243
INDEX
Parabola, 180
Parts of computers, three
Q
fundamental , 14-20 Quadratic, 180
Past history, 157-159 Quiet spot, 24-26
PAUSE,89
PEEK , 203
R
function, 203-207
PEEK-A-BOO , 203-208 Radians, 186
Perfunctory endings, 213 RA D , 127
Period , 186 Random, 223
Periodic function, 186 Randomly, 217
Pixel, 105-106 Real-time, 101
Playback, 78-80 Recording your program, 75-77
PLOT, 105 Relational symbols , 99
244
INDEX
245
DEX
246
~.~.f..~.N.~ .......................................
More Books
for
Timex Sinclair® Owners!
The se and ot her Sams Books and Soft ware produ cts are available from better retailers
worldwide , or directly from Sams. Call 800·428·SAMS or 317·298·5566 to order, or t o get
the name of a Sams retaile r near you. Ask for you r free Sams Books and Software Cata·
log !
Prices good in USA only. Prices and page counts subject to change without notice.
Timex Sincla ir 1000 and Timex Sinclair 2068 are registered trademarks of Timex Computer Corp.
I,
I,
Need Other Books in the SamsiWaite Primer Series?
I UNIX PAl EA PLUS
II This newest of the Sams/ Walte Primllf$ presents the elements of UNIX clearly, simply, and accurately, for ready understanding by anyone In any
I' fl'eld who needs to learn, use, or work with UNIX in some way. Fully illustrated. Includes two handy, removable summary cards. By Mitchell Waite,
Donald Martin, and Stephen Prata.
I Ask for No. 22028 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ......... . ... . ............... $19.95
I CP 1M PRIMER (2nd Edition)
II Completely updated to give you the know-how you need to begin using and working with new or old CPIM versions immediately, in any
application. Includes CP/M terminology , operation, capabilities. internal structure, and more, plus a convenient, tear-out relerence card listing
CP/ M commands. By Mitchell Waite and Stephen Murtha.
"
II Ask for No. 22170 . . . . . . . .......... . ................... . . ....... . . .. . ... . .. .... $16.95
I SOUL OF CP /M®: HOW TO USE THE HIDDEN POWER OF YOUR CP/M SYSTEM
II Teaches you how to use and modify CP / M's internal features, including how to modify BIOS, use CP / M system calls in your own programs, and
I morel Excellent if you 've read CP/ M PRIMER or are otherwise familiar with CP / M. By Mitchell Waite and Robert Lafore.
Ask for No. 22030 . . . . . . . . . . . . . . . . . . . . . .... . ... . ....... . ... . . . ........... .. ..... . ... . . . ... ...... $18.95
CP/M® BIBLE: THE AUTHORITATIVE REFERENCE GUIDE TO CP/M
Highly detailed, all-version CP / M reference manual that gives you instant, one-stop access to all CP/ M keywords, commands, utilities, conven-
tions, and more. A must if you use any version of CP / M. By Mitchell Waite and John Angermeyer.
Ask for No. 22015 ... .. ................ . ..... . .. . .. . ........ . .. . ........................ .. ..... . . .. .. $19.95
BAIIC PROGRAMMING PRIMER (2nd Edition)
Improved, expanded edition, now usable with the IBM PC and similar computers. Features new advanced BASIC coverage, game-program
IIstlngl and sell-tests with answers! Highly useful, user-friendly, how-te-program material for beginners and more advanced users alike. By
Mitchell Waite and Michael Pardee.
Ask for No. 22014 .................. . ...................................... . ........ ... , , ... . ........ $17.95
PASCAL PRIMER
You'll generate powerful programs in UCS08 Pascal as this Sams powerhouse guides you through Pascal program structure, procedures,
variables, decision-making statements, and numeric functions. A remarkable book that also contains eight appendixes. By Mitchell Waite and
David Fox.
Ask for No. 21793 .. . .. . .. .................. , ............................ .. ...... . .... . ...... , ....... $17.95
COMPUTER GRAPHICS PRIMER
Almost every page of this Sams best-seller has a color drawing , a photograph , a picture, or a schematic that helps you learn graphiCS
programming quickly and easily-Including computer animation! Examples can be easily adapted to any computer running a version of Microsoft
!lASIC. By Mitchell Waite.
Ask for No. 211150 ... .. ............... . . . ......... . .. . ...... . . .. . ... ..... ..... .... .. . ... . .. .. ........ $15.95
MICROCOMPUTER PIIIIME.. (2nd Edition)
A little more technical than the other Primers to better cover basic computer concepts, the electronics behind the logic, what happens Inside the
computer as a program runs, and a little about languages and operating systems. Excellent introductory material. By Mitchell Waite and Michael
Pardee.
Ask for No. 21853 ... .............. . ... . ................. . .... .. ...... . ......... .. . . ... . .. . ... . . . .... $14.50
YOUII OWN COMPUTER (2nd Edition)
Shows how you can go about choosing and buying a computer for your own uses. Explores applications, buzzwords, programs, hardware, and
peripherals. Compares 30 different models of personal and small-business computers. By Mitchell Waite and Michael Pardee.
Ask for No. 218eO . . . . . . . . . . . . . . . . .. . . .. . .. . .. . ....................... . ................... $8.95
Apple II , Apple \I +, and Apple lie are registered trademarks 01 Apple Computers, Inc. 8 CP / M is a registered trademark of Digital Research,
Inc. 8 UCSD is a Irademark 01 UC Regents, San Diego campus 8 UNIX is a Irademark 01 Bell Laboratories, Inc.
I'
It
I
I
Subtotal
II
I o Check 0 Money Order Add local tax where applicable
I o MasterCard o Visa Add Handling Charge 2.00
f Total Amount Enclosed
I
,
Account Number Expires
I
Name (print
I Signature
I.
Address
I
r City State Zip
~ Offer good in USA only . Prices subject to change without notice Full payment must accompany your order .
I X0438
•~
Call 1-800-428-3696 for the name of your (3) Add up the total cost for the books,
nearest Sams retailer or distributor add your state's sales tax if ap-
(residents in IN, AK, HI call 317-298-5566). plicable, and then add $2.00 for
handling.
If your retailer or distributor doesn 't stock
(~) Include your check or money order
the Sams publication you need, you can
order it through him or directly from us. for the full amount due, or
Orders placed directly with us are subject (5) Charge it to your VISA or MASTER
to a $2.00 additional handling charge per CARD. To charge it, list your account
order. number and the card expiration date.
Shipping charges will be added to
PHONE ORDERS credit card orders.
Depending on where you live, call either
number listed above and charge your
Sams publication to your VISA or
MASTERCARD.
(6) Mail your order to :
MAIL ORDERS Howard W. Sams & Co., Inc.
Use the order form below, or if it's Dept. No. X0438
missing, send your order on a plain 4300 West 62nd St. , P.O. Box 7092
piece of paper. Indianapolis, Indiana 46206
See other side for li st of SamslWaite Pri mers and their prices.
Place
Stamp
Here