Programming For Education On The Commodore 64 (1984)
Programming For Education On The Commodore 64 (1984)
ptogtQmmlng
fot educQtion
on the commodote 64
Q oondbook for primQry educQtion
Scriven, John
Programming for education on the Commodore 64.
I. Education, Elementary-Data processing
2. Commodore 64 (Computer)
I. Title II. Hall, Patrick
372.1 '67 LBI028.43
ISBN 0 946408 27 0
ii
CONTENTS
Page
Program Notes VB
Introduction IX
2 Small is Beautiful. . . 27
5 Story Time 81
6 Logically Speaking 93
iii
Contents in detail
CHAPTER 1
Starting with Maths
Starting off - the computer as calculator - choices and loops - pro-
grams and randomness - Table 1: a table test - improvements - Table 2:
introducing time - using graphics and sound - looking for patterns -
Table Patterns: changing the display - Bingo: a game setting for a tradi-
tional idea - repetitive learning - moving graphics to add interest -
Factor: a program to teach factorisation.
CHAPTER 2
Small is Beautiful ...
Short programs and efficiency - Missing: find the numbers - ordering
numbers - Series: maths as an introduction to strategy - simplicity in
program structure - Number: a program to find a hidden number - using
graphics to brighten up simple ideas - Firework: a program to test general
numerical skills - the problems involved in learning fractions - Fraction:
a program to help with numerators and denominators.
CHAPTER 3
VVords, VVords, VVords
Handling words on a computer - sorting things - Alphasort: a program
to sort words into alphabetical order - numbers in strings - Simon: a
game to improve memory - diversity of subjects in primary schools -
problems in spelling - different approaches - context clues - Hangman:
a multi-purpose spelling program - research skills - Anagram: clues
from word order.
CHAPTER 4
Making Friends with your Keyboard
Tackling entry errors - menus - making programs foolproof - moving
the character set - BigL: writing large on the screen - Keyboard: learning
the keys - Masking: changing binary numbers.
v
Programmingfor Education on the Commodore 64
CHAPTER 5
Story Time
Creativity - artificial intelligence - words at random - Story: a program
to help with creative writing and adjective use - interactive use of
computers - Gosh: more stories.
CHAPTER 6
Logically Speaking
Logical reasoning - problem solving - Treasure: finding pirates' gold-
coordinates - using sound and sprites - Sonar: find the submarine.
CHAPTER 7
The Real Thing
Unique role of computer in simulation - the appeal of computer graphics
- simulation versus immediate experience - the realm of simulations -
Lock: an excursion on the canal - Power: electricity generation - inter-
active simulations - elementary statistics - Coin: probability of
throwing a head - Cascade: Pascal's triangle.
vi
Program Notes
All Commodore computers use special characters to control various func-
tions on the screen. For instance, pressing the [CLR/HOME] key and
[SHIFT] will clear the screen. If those keys are pressed after a double quote
mark, an inverse heart will appear in the listing.
Although this is often a quick way to control print colours, inverse char-
acters and cursor control, there are usually less confusing ways of achiev-
ing the same effect. To avoid confusion in the listings, we have used these
codes as infrequently as possible. The exception is the use of SHIFTed
CLR/HOME to clear the screen as mentioned above.
To make the listings clearer, where this character appears, it has been
substituted by [SHIFTICLR/HOME].
Note: Please be careful when entering programs listed in this book. The
quality of printing from a computer printer means that some characters
can look very similar - commas, in particular, can look very like full
stops.
vii
Introduction
The aim of this book was not originally to teach you BASIC. We had hoped
to let it contain educational programs which we ourselves had found
useful, and merely write about their use, as we have with the other books in
this series. As we were collecting material, however, we began to realise
that many people who used this book might have had little experience of
computers. For those that are new to computers, we have spent more time
introducing the early programs.
We hope to lead you step by step through the initial stages to simple
programming skills. These are combined to produce short programs that
show how the Commodore 64 can be used at home or at school to make
learning more interesting, while also discovering something about the
computer itself.
The 64 is a very advanced microcomputer and has some outstanding
features. Unfortunately, these are not accessible from BASIC without
addressing the memory directly, and this makes some aspects of the 64
more obscure than they need to be.
We will attempt to show you that these drawbacks can be overcome, and
that you will be able to write interesting educational programs once you
have understood a little more about how the 64 operates. If something is
not clear straight away, come back to it at a later stage and with luck you
will understand it.
Above all, this is a book about doing. No one ever learned about
computing simply by reading a book, so do tryout the examples and alter
things as you find necessary.
If you have some experience with computers, you can skip some of the
introductory material and dive into the meatier sections. We hope that you
won't be content simply to copy out the listings, but will modify and adapt
the programs and routines to suit your own needs.
All the programs have been tried and tested, and are printed from the
actual listings, so they should work first time. If they don't, it's probably
due to a tiny typing error that's escaped your notice. Check the listing
against the book, as even a missing semicolon can stop the program. If, in
spite of this, you still find something doesn't work as expected, we'd like to
know about it!
Ultimately, we hope that you will continue to enjoy your computing and
that this book will help you achieve your aims.
ix
CHAPTER 1
Starting with Maths
Ten years ago, it was unusual to find calculators in schools, let alone
computers. The advent of the home computer, and computers in schools,
brings with it the responsibility to make sure a) that the users are familiar
with them and b) that they are used wisely.
In this chapter we shall be looking at how computers use information,
and how they can display this. If you have some knowledge of computers,
then you can skip over the early sections. If you are coming to the 64 as
your first machine, then it should clear up some of the mysteries of how
computers can make simple decisions and appear to act intelligently.
If you have used a calculator, then you know that you enter data, in the
form of numbers, along with operators, like plus or minus, to tell the calcu-
lator what to do with those numbers. For instance,
2+2-1=
At each stage of the calculation, the display shows the last number entered
or the result at that stage. You can use the 64 as a calculator in the same
way. Instead of calculator buttons, you can communicate with the 64 via
the keyboard. If you enter
2 + 2 - 1 [RETURN]
it will calculate the result. (The [RETURN] key can be seen as sending the
information you have entered inside the computer.) The problem is that,
whereas you see the result automatically on a calculator, the 64 has to be
told to display the answer. To speak to the computer, you have to use the
language that it understands. The 64 uses the language BASIC, which is a
Programmmg/or Education on the Commodore 64
fairly small set of words that are quite close to normal English. These
words are entered via the keyboard, just as on a normal typewriter.
To make the 64 print something, you must use the PRINT statement. If
you enter
PRINT 2 + 2 - 1 [RETURN]
If you enter the lines as they are written, the program lines are stored in the
computer's memory.
(Important: Make sure that you enter the lines exactly as they are written.
Humans can understand things even when there are mistakes, but
computers are unforgiving and even putting a letter I instead of a figure 1,
or a letter 0 instead of a figure 0, will prevent program instructions from
working.)
To execute the instructions, the command RUN must be entered and the
[RETURN] key pressed. The computer will obey the instructions in each
line in turn, that is, print the sentence in quotes in line 10 followed by the
answer to the calculation in line 20. As there are no more lines, the program
will end there, and pass control back to you. (From now on remember to
press the [RETURN] key at the end of program lines and after commands.
There won't be any more reminders!)
Programs, then, are simply lists of instructions that the computer obeys
in a particular order. It doesn't matter in which order you enter the lines,
the computer sorts them out for you. So if you now enter
2
Chapter J Starting with Maths
5 [RETURN]
followed by LIST, will show you that line 5 has indeed been deleted.
To delete a whole program from memory, use the command NEW. This
clears the complete BASIC program, so don't use it unless you're sure
that's what you really want.
Try it now and check that your program really has disappeared by LIST-
ing it.
X=4
PRINT X
YEAR = 1984
then
YELLOW=6
3
Programming for Education on the Commodore 64
then
PRINT YEAR
the result 6 will appear, so be careful how you use variable names.
If you want to store a string of characters, ie letters, numbers, graphic
characters, or anything else on the keyboard, you have to use what is called
a string variable. This is just like a numeric variable except that it ends in a
$.
Enter this:
A$ = "CBM 64"
PRINT A$
The string variable A$ now contains the string of cha:acters CBM 64, so
when you tell it to print out A$, that is what is printed.
Just as it is a good idea to use meaningful names for numeric variables,
string variables too are easier to understand when they mean something.
For example, NAME$ is more meaningful than N$.
Remember that the 64 will confuse NAME$ with NAIL$, as it only recog-
nises the first two characters. It is also important that the variable name
should not contain a BASIC keyword. This means that FORT is not
allowed - it contains the BASIC word FOR. The variable BRIGHTON$ is
not allowed as it contains the word TO.
As was mentioned earlier, variables are useful when you want to enter
information during the course of a program.
This program, when RUN, will tell you to enter your name at line 10. In line
20, it will stop program execution until it receives an input, followed by a
press on the [RETURN] key. Whatever is entered in this line becomes
known as NAME$, and will be printed out in line 30, after the word
HELLO.
Line 40 will print the request for the age on the screen, and this will be
stored as variable AGE in line 50. Note that you must enter this in figures or
the computer will tell you to REDO the input. Line 60 will print out the text
in that line plus the name and age that were entered. The semicolon
between AGE and NAME$ is important to separate them.
4
Chapter J Starting with Moths
70 GOTO 10
This will cause the program to go into a never-ending loop. To get out of
this, it is necessary to press the RESTORE key while holding down the
RUN/STOP key at the same time.
If it's at all possible, avoid using GOTOs in your programs. Although in
Commodore BASIC you have to use them sometimes, they can make the
structure difficult to understand.
Some programs
Now that you can use variables and inputs, you can start to use your 64 to
write simple programs, and also make them appear more friendly. Note
that, in line 10, the INPUT statement can include words that are printed.
5
Programming/or Education on the Commodore 64
These statements are very useful in a program, as they can test for correct
answers to problems posed by the computer.
10 Question
20 Answer
30 IF Answer = right THEN PRINT "OK"
40 IF Answer = wrong THEN PRINT "SORRY"
50 Next Question
60 Next Answer
70 IF Answer = ...
etc.
Loops
In the last program, if you had wanted ten questions, you would have had
to repeat the same structure as in the first four lines ten times. As well as
being wasteful on memory, this would take a long time to enter. Luckily,
you can employ a loop to take you through the same section of program a
certain number of times. The only loop that the 64 possesses is the FOR ...
TO ... NEXT loop. Although it looks complicated, it's really quite a
simple idea.
You need to set up a counter in one program line at the beginning of the
loop, and to have a marker line to show the end of the loop. This example
should explain it more clearly. First type NEW to get rid of the last
program.
When the program is RUN, line 10 simply prints a message. Line 20 means
'Set a counter up called N. Start counting from 1 until you reach 10.' Line
30 prints out the number of the loop, which is I. Line 40 means' Increase N
by one and go back to the start of the loop.' N is therefore now 2. Program
control goes back to the start of the loop in line 20; line 30 prints out LOOP
NUMBER 2, N is increased once again, and so on. At the end of the tenth
time through the loop, N becomes 11. When the program returns to line 20,
the program says 'The loop is only supposed to go up to 10, so program
6
Chapter 1 Starting with Maths
control must jump straight to the first line after the end ofthe loop', ie line
50, and the final message is printed out.
If you enter this short program, and RUN it, you can see this in opera-
tion. After it has stopped, enter PRINT N, and you will see that it does
indeed contain the value 11.
When a program is RUN, all the numeric variables are set to zero, and
the string variables emptied, so you can run the program again and again.
Random numbers
If you want the computer to ask specific maths questions, you now have all
the knowledge you need. It's far more useful to have it select the questions
out of a hat, however, and there is a very useful facility to let it do just that.
If you enter PRINT RND(O), then a number between zero and one will
be printed. This number is chosen at random, and the value can be assigned
to a variable.
10 FOR N = 1 TO 10
20 X=RND(O)
30 PRINT X
40 NEXTN
This program will print out ten random numbers between zero and ten.
Numbers this small may not be much use in simple number problems, so
line 20 could be changed to
20 X = RND(O)*I 00
Note: Computers use an asterisk (*) for multiply so that this won't be
confused with the letter X. The divide sign is an oblique line (I).
Line 20 will now generate numbers between zero and 100. If you RUN
this now, you will see that the numbers are so random that they have several
decimal places. To lose the decimal part of the number, change line 20 to
20 X = INT(RND(O)* 100)
This will generate integers, or whole numbers between zero and ninety-
nine.
At this stage you know how to generate numbers at random, how to loop
ten times to produce ten questions, how to input answers and how to check
that the answers are correct. You can combine all these points in a program
designed to test knowledge of one aspect of maths.
7
Programmingfor Education on the Commodore 64
Table 1
1(2) REM
2(2) REM *** TABLE TEST ***
3(2) REM
1(2)(2) SC=(2)
11(2) PRINT"[SHIFT/CLR/HOMEJ"
12(2) PRINT TAB(12) "TABLE TEST"
13(2) FOR N = 1 TO 1(2)
14(2) A = INT(RND«(2)*13)
15(2) B = INT(RND«(2)*13)
16(2) PRINT TAB(4-N*.11>;N;".)"A" x "B TAB(24)"=";
17(2) INPUT G
18(2) IF G = A*B THEN PRINT TAB (3(2)"OK"
19(2) IF G = A*B THEN SC=SC+1
2(2)(2) IF G <>A*BTHEN PRINT TAB (3(2)"NO- ";A*B
21(2) NEXT N
22(2) PRINT"YOU SCORED ";SC
23(2) PRINT"PRESS SPACE BAR TO GO"
24(2) GET Z$
250 IF Z$="" THEN GOTO 24(2)
260 GO TO 1fllQ)
READY.
Commentary
Line 100 sets the variable se, which holds the score, to zero.
Line 120 uses the TAB statement. This moves the print position across the
screen.
Lines 140 and 150 choose two numbers between 0 and 12 at random.
Line 160 prints the question on the screen. Lines 170 to 200 accept an input
and check it against the correct answer.
Line 190 increments the score by one. Lines 220 to 260 print the score and
allow the user to go again.
In the past, computers have always been associated with mathematics and,
even nowadays, computers tend to be used more in the maths and science
departments of schools. In fact, computers are good at operating with any
kind of symbols, not just numbers, and it would be a pity if their 'number-
8
Chapter J Starting with Maths
crunching' capability were the only thing they were used for in the edu-
cational sphere.
In spite of this, maths is an area where a simple introduction can be
made. This is also an area where it is easy to write programs that test recall
without being truly educational. It has been shown by many educational
psychologists since the war, such as Jean Piaget and Jerome Bruner, that
children develop by passing through distinct learning stages. They cannot
learn automatically, but need much practical experience before being able
to manipulate symbols in their minds and finally achieve a stage of logical,
formal thought. The computer in its present form cannot replace practical
experience, but its graphic capabilities can help tremendously where the
child begins to learn to use symbols or concrete images rather than the
objects themselves.
We have tried to avoid as far as possible the type of program that uses a
computer to do what can be just as easily achieved using traditional mater-
ials. Computers are expensive artefacts to have around without careful
thought being given to their most profitable use, whether at home or at
school.
You may think that we have spent some time on showing you how to
write a program that we are now tearing to pieces. The traditional table test
is, unfortunately, an example of a weak, drill-type program. The reason it
is included here is that it demonstrates simple principles of program design
and is easy to understand.
If this was the only sort of program you were ever going to write, we
would consider that we had failed in our aim to introduce a more dynamic
approach to using computers in education. It is true that it merely tests
recall, without reinforcing correct answers, diagnosing problems or
attempting to offer help. It can, however, be used with caution, provided
these shortcomings are realised.
Instead of leaving you with the simple version of the program, here is a
listing that attempts to go one step further. It produces the numbers at
random, but starts a time at the first question, so the user has a target to
aim at, in trying to better his or her previous time. Also included is a facility
for the teacher or parent to check the results of each program run and to
compare the times taken.
Table 2
1121 REM ** J. SCRIVEN **
2Ql REM
3121 REM ** 1121/1121/82 **
412l REM
5121 REM ** TIMED TABLE TEST **
612l REM
7121 REM ** INITIAL! ZATION **
9
Programming/or Education on the Commodore 64
80 REM
85 REM
90 DIM NA.$(30)
1(2)0 DIM SC(30)
110 DIM TM(30)
120 NU = 1
130 FL = 0
140 REM
150 REM ** TEST LOOP **
160 REM
170 FOR NU = 1 TO 30
180 PRINT" [SHIFT ICLR/HOl'lE]"
190 PRINT TAB(12) "TABLE TEST"
200 PRINT TAB(10) "ENTER YOUR NAME"
210 INPUT NA$(NU)
220 PRINT "01<, ";NA$(NU)
230 PRINT "PRESS SPACE BAR TO BEGIN"
240 GET Z$
250 IFZ$="" THEN 240
260 SC(NU)=0
270 TS=TI
280 PRINT"[SHIFT/CLR/HOME]"
290 PRINT TAB(12) "TABLE TEST"
300 PRINT TAB(l)NA$(NU)
310 FOR N = 1 TO 10
320 A = INTCRND(0)*13)
330 B = I~TCRND(0)*13)
340 PRINT TABC4-N*.11>;N;".)"A" X liB TAB(24)"=";
350 INPUT G
360 IF G = A*B THEN PRINT TAB(30) "01<"
370 IF G = A*B THEN SC(NU)=SC(NU)+l
380 IF G <> A*B THEN PRINT TAB(30) "NO- ";A*B
390 NEXT N
400 TT=INT«TI-TS)/60)
410 PRINTNA$(NU);" SCORED ";SCCNU);
420 PRINT" OUT OF 10 IN ";TT;" SECS"
430 TM(NU)=TT
440 PRINT"PRESS SPACE BAR FOR ANOTHER GO";
450 GET Z$
460 IF Z$="" THEN GOTO 450
470 IF Z$="~<" THEN GOTO 100(2)
480 NEXT NU
490 PRINT"CLASS COMPLETED"
500 FOR M = 1 TO 2000: NEXT M
1000 REM
1010 REM ** RESULTS ROUTINE **
1020 REM
1030 PRINT"[SHIFT/CLR/HOME]"
1040 PRINT TAB(15) "RESULTS"
to
Chapter J Starting with Maths
1050 F'RINT
1055 PRINT
1060 PRINT TAB(5)"NAME";TAB(24) "SCORE";TAB(34)
"TIME"
1070 PRINT
1080 FOR NU = 1 TO 30
1090 PRINTNU;TAB(5)NAS(NU);TAB(24)SC(NU);TAB(34)
TM(NU)
1100 IF NU = 15 THEN PRINT"PRESS SPACE BAR TO
CONTINUE"
1110 IF NU = 15 THEN GET ZS
1120 IF ZS = "" THEN 1110
1130 NEXT NU
READY.
Commentary
One exercise, often given to children learning tables, is to discover the
patterns that the answers make when these numbers are shaded in on a grid
of figures, It is usual to make the grid 10 x 100r 12 x 12, and this idea forms
the basis of the next program,
There are many ways in which the 64 could be told to draw a grid of
numbers on the screen, such as printing each line separately. A neater way,
that uses more of the computer's in-built functions, would be to put the
print routine in a loop, If you simply entered
the numbers would certainly appear, but they would not be formatted in
neat lines with units and tens underneath each other, If you consider the
screen layout on the 64, you will see that the numbers could fit in very
regularly. The screen is 40 characters in width, and the largest number
takes three figures (2,0 and 0). If a space is left between each column, you
can see that ten numbers, each one preceded by a space, will exactly fit on
each line.
II
Programming jar Education on the Commodore 64
ters with the row and column values by POKEing, and then call the kernal
routine PLOT. You can do this in one line:
and GOSUB this routine just before you print something. The new print
position will be at the X and Y coordinates you have just entered. This is a
very useful routine and you will find it occurring quite frequently in these
programs. In the next program, it is used to move the print position across
to each new column and row.
When the numbers have been printed, the user is asked to enter the table
that is required. So that these numbers show up, the next routine changes
the colour of just these numbers to white. Again, this is not a very complex
task. The 64 stores the screen text in one set of locations, and the colour in
which the text appears in another. The second set of locations starts at
55296. As the grid of numbers is spaced evenly, starting at every fourth
location, the colour value can be POKEd in another FOR ... NEXT loop.
How can you tell it to act only on the numbers in the particular table
chosen? A useful trick is to test if there is a remainder after division by the
table number. If this seems difficult to grasp, try this program:
10 INPUT A
20 FOR N= 1 TO 100
30 IF INT(NI A) = NI A THEN PRINT A
40 NEXTN
This runs through the numbers from 1 to 100, and divides each one by the
number you input. If the number has a remainder, the INT function will
round down to the nearest whole number below, eg INT(lI.5) = 11. It will
only print those numbers that don't have a remainder, as the INTeger of 12
is 12.
Notice that this program tests the codes of keys that are pressed in GET
statements. If any key other than the numbers 1 to 9 is pressed, the program
loops back to ask for the key to be pressed again.
Table Patterns
12
Chapter I Starting with Maths
7v'l REt-1
80 F'F\I NT" [SH I FT ICLF\/Hm-IE] I!
9~ X=0:Y=0:GOSUB540
1(ofll PRINT"TABL.E PATTERNS"
l1QJ X=2:\(:=2
1 ~?flI REt,ol
130 REM *** LOOP TO PRINT NUMBERS ***
14fl1 F:El'l
150 FOR N = 1 TO 2fl10
160 IFN=10 OR N=10fl1 THEN X=X-1
17~ GOSUB 540:PRINTN
18111 X ::: X + 4
19~ IF INT(N/l~)=N/l~ THEN X=l
2fl1fl1 IF INT(N/lfl1)~N/10 THEN Y=Y+l
210 IF INT(N/10)=N/10 AND N>99 THEN X=fli
220 !'IEXT N
230 REt'1
240 REM *** SELECT TABLE ROUTINE ***
250 REt'1
260 POKE198,0
27111 X=5:Y=23:GOSUB540
280 PRINT"*PRESS THE TABLE NUMBERI(-"
290 GET A,~:: IF A$ :::: "" THEN 290
312HZ) A::::VAL (A$)
31fl1 IFA<1 THEN 260
32~ X::::30: y:-.::0: GOSUB540: PRINT"TABLE"A" "
T:;'0 REM
3 ...1~ REM *** CHANGE NUMBER COLOURS ***
35(7] REl'l
36~ COL == 552<7'6
370 FOR N = 1 TO 200
38~ IF INT(N/A) <> N/A THEN 420
390 POKE COL+81+(N-l)*4,1
394 REl'l
400 POKE COL+81+(N-l)*4+1,1
410 POKE COL+81+(N-1)*4+2,1
420 NEXT N
43~ X=5:Y=23:GOSUB541l1
440 POKE198,0
450 PR I NT" PRESS SP~':iCE BAR TO CLEf.1R"
46fl1 GET A$: IF A$ : -.: "" THEN 460
470 FOR N = 55296 TO 56319
48\(1 POKE N,14
490 NEXT N
13
PrOKrammim: for Education on the Commodore 64
READY.
Commentary
Line 80 clears the screen. Line 90 sets the X and Y coordinates to zero.
Lines 150 to 220 contain the loop that prints the table grid.
Lines 190 to 210 move the print position at the end of the line - when the
value of N is exactly divisible by 10.
Lines 260 to 310 allow the number of the table to be input. Line 320 prints
the table number at the top of the screen.
Variable COL is the location of colour memory. Lines 370 to 420 change
the text colour by POKEing the relevant memory locations. Line 380 skips
over the POKEs if the value ofN is not exactly divisible by the table chosen.
Lines 280 and 450 contain the same number of characters in the print
statements so that they can print on top of one another.
Bingo
After the element programs in this chapter, we move on to a couple in the
area of maths that extend the use of the 64's features. If you are fairly new
to BASIC, you may find the ideas more difficult to grasp. Although they
are explained in some detail in the program notes, you may prefer simply to
type in the listings. As your skills improve in the following chapters, you
can come back to these programs at a later stage.
Bingo is an attempt to move beyond the simple approach of answering
questions on screen. The child is presented with a game format, and,
although the questions still only test recall of previously-learned know-
14
Chapter J Starting with Moths
ledge, there is a reward motive in completing the whole card. When this
stage is reached, there is a visual display.
There is always some problem over how many of a computer's facilities
need to be incorporated in every program. Just because Commodore
computers support voice synthesis, high-resolution graphics and music in
three-part harmony, it does not mean that a good program has to possess
all of these features, or indeed any of them. A happy medium has to be
reached at the planning stage. Some programs benefit from using specialist
features, but usually take more time to program. In some cases, their
implementation can be irritating and work contrary to the expectation of
the teacher or parent.
One example is the addition of loud sound effects, which can be disturb-
ing in a classroom if there are other children engaged in quiet activities. If
this is the case, removal of the offending sound commands will prove an
answer. An alternative, of course, is to reduce the volume by use of the TV
volume control! Flashing displays should usually be avoided. Where
sections of the screen are required to flash, this is done to draw attention to
part of the display. Having had personal experience of a child suffering a
petit mal attack due to the program loading display on a cheaper computer,
we are particularly aware of this possibility. Also, overuse of this feature
is likely to prove distracting in many cases.
15
Programmingjor Education on the Commodore 64
16
Chapter I Starting with Moths
17
Progromming/or Education on the Commodore 64
1160 RESTORE
1170 FOR I = 1 TO 115
1180 READ N
1190 FOR J - 0 TO 1
1200 FOR K = 0 TO 40 STEP 40
1210 POKE N + J + K + 54272, 2
1220 POKE N + J + K, 128
1230 NEXT V
1240 NEXT -J
1250 NEXT I
1260 FOR I = 1 TO 3000 NEXT I
1270 PRINT 1111
1280 RETURN
1290 REI",
1300 REM DATA FOR 'BINGO'
1310 DATA 1024. 1104, 1184, 1264, 1344
1320 DATA 1424, 1504, 1584, 1664· • 1744
1330 DATA 1824, 1904, 1026, 1068, 1110
1340 DATA 1190, 1270, 1350, 1.388, 1466
1350 DATA 1548, 1590, 1670, 1 75<t) , 1830
1360 DATA 1868, 1906, 1034, 1114, 1194
1370 DATA 1274, 1354, 1434, l51 'l, 1594
1380 DATA 1674, 1754, 1834, 1914, 1038
1390 DATA 1118, 1198, 1278, 1358, 1438
1400 DATA 1518, 1598, 1678, 1758, 1838
14 10 DATA 1918, 1080 , 1161, 1241, 1321
1420 DATA 1401, 1481, 1561, 1641, 1.721
1430 DATA 1801, 1882~ 1044, 1124, 1204
1440 DATA 1284, 1364, 1444, 1524, 1604
1450 DATA 1684, 1764, 1844, 1924, 1129
1460 DATA 1209, 1289, 1369, 1449, 1529
1470 DATA 16~9, 1689, 1769, 1849, 1051
1480 DATA 1133, 1213, 1612, 1614, 1693
1490 DATA 1773, 185~5, 1931, 1138, 1218
1500 DATA 1298, 1378, 1458, 1538, 1618
1510 DATA 1698, 1778, 1858, 1060, 1142
1520 DATA 1222, 1302, 1382, 1462, 1542
1530 DATA 1622, 1702, 1782, 1862, 1940
18
Chapter I Starting with Maths
Commentary
The program is controlled by lines 30- 80. Line 70 causes the program to
continue indefinitely until RUN/STOP is depressed.
Lines 100-290 form the first subroutine of the program, called by line 30
in the control module. The routine initialises various variables needed by
Bingo. Five arrays are set up. The A and B arrays hold the twenty pairs of
numbers presented to the child and the C array stores the answer for each
mUltiplication. The D array consists of flags, one for each number pair,
which ensure that the same question is not repeated. Finally the LB array
stores the screen locations of each coloured box the numbers are printed in.
The actual value of each member of the LB array is the location of the top
lefthand corner of the coloured box. These values are calculated by the
two nested FOR ... NEXT loops between lines 160-210. Here the values
that the I and J loop variables STEP through are arranged so that their
sum, 1+ J, gives the exact location. Note the way in which the variable N is
incremented through the loops to identify each box.
This first subroutine also sets the values of S (the score achieved by the
child) and G (the number of 'sheets' completed) to zero. Line 250 sets the
entire screen area to white and then line 280 switches on the Commodore
64's 'extended' colour mode. This allows text to be printed with a different
background colour to the screen background (and is the equivalent of the
command COLOUR (colour + 128) in BBC BASIC). Extended colour
mode is switched on with POKE 53265,91 and off with POKE 53265, 27. It
allows three more background colours to be set up simultaneously on the
screen, but requires a different character set for each.
Lines 310-680 present the bingo sheet. Use is made of the PRINT TAB
routine at lines 700-730. This allows an easy way to format the display. X
and Y screen coordinates have to be defined before calling the routine and
this is done here, for example, at line 360. Lines 480- 500 calculate the
questions and answers and the boxes are drawn by lines 520- 570. The J
and K values in the two nested loops increment the value of LB calculated
before, and this value is then POKEd to screen and colour map by line 550.
Each number is placed in its box by 600-660. Extended colour mode is
used and the two-digit numbers have to be separated by the simple arithme-
tical routine into the individual ten and unit figures. These are POKEd
separately to the screen.
Lines 750-1120 present the test. The Tth box is chosen at line 770 and the
flag is checked by line 790 to make sure that box and question have not
already been chosen. The TAB routine is used again in presenting the ques-
tion and the child's input is error-trapped. A sound effect is produced and
19
Programming/or Education on the Commodore 64
finally the box itself is erased by lines 1040-1090. Line 1100 tests when the
entire screen is cleared.
The reward routine simply places the word 'Bingo' large upon the screen.
This is done in a very similar way to the drawing of the boxes but here the
location of each 'box' is not calculated but held as lines of DATA which are
READ by line 1180. The nested loops between 1190-1240 draw each
section of the letters.
Factor
The last program in this chapter, Factor, extends the approach to that of a
video game. It does not require high-speed manual dexterity, however,
simply the ability to input any factor of a number that appears on the
screen. The number is successively factorised by the inputs until it reaches
1, when another number is chosen. If the factor chosen is permissible, a
plane flies across the screen and drops a bomb on to the number resulting in
an explosion. If the number is incorrect, the bomb misses. There is also an
on-screen scoring facility.
A last point needs to be made about the type of reward offered in a
program. Although an exciting display may offer positive reinforcement
to the child, it is hoped that the reward will become intrinsic, ie that the
child enjoys the success of getting a problem right without any external
reward. When adults succeed in solving a 'whodunnit', or complete the
Times crossword, the achievement alone is enough. This internalisation
has taken a long time to achieve, however, and praise, even from a
machine, is important!
It is also necessary to point out incorrect responses in a gentle manner, or
the child feels despondent and even aggressive. If a computer has ever
beaten you at chess, you will know the feeling. Although it may seem
obvious to state, the difficulty of the problem has to be within the solving
capacity of the child. When designing programs, the incorrect response
should not result in a screen display that is more impressive than that for a
correct response, or the reinforcement effect will be lost, as the child
attempts to fail because the display is prettier!
20
Chapter J Starting with Maths
21
Programming/or Education on the Commodore 64
22
Chapter 1 Starting with Moths
23
Programming/or Education on the Commudure 64
27M) REM
2770 F:EI'1 DATA FOR PRIME NUMBERS
2780 REM
279(2) D{~ T A 2, 3. 5. 7. 11. 13, 1 7. 19
2800 DATA 23, 29, 31, 37, 41, 43, 47
24
Chapter / Starting with Moths
RE?mV.
Commentary
Factor is controlled by lines 1020-1070,
The first subroutine, called by line 1020 of the control module, defines
three sprites used in the program. Sprite 0 is a plane, sprite 1 is the bomb
that it drops and sprite 2 is the flash of the resultant explosion when the
plane successfully hits its target number. Each of the three sprites is defined
in a similar way.
The diagram shows how the plane has been drawn on a rectangular grid
of 21 rows and 24 columns. Each block of eight horizontal squares has
been coded as a binary number and then stored in a special area of memory
reserved by line 1150. Usually after a sprite has been designed and calcu-
lated as a set of 63 numbers, these are held inside a program as DATA.
However, in the case of the plane sprite it can be seen from the diagram that
the first twenty blocks of eight squares have not been filled in at all. Thus
the numbers corresponding to these blocks are each zero.
It is much easier to place these values into memory with the simple FOR
... NEXT loop between lines 1170-1190 than to store them as DATA.
The remaining numbers for the sprite are, however, READ from the
DAT A lines. The values for sprite 0 are held at locations starting at 832.
The two other sprites are stored at locations starting at 896 and 960. Each
time, the 'sprite pointer' is set to indicate where in memory the sprite data is
to be found.
The rest of the routine then attends to other sprite parameters. These are
all done in terms of the number VC defined at line 1120. This is the starting
location of the video chip, which handles all the sprite manipulation.
POKE VC + 29, for example, is the location which controls the size of a
sprite in the horizontal, x, direction. POKEing the sprite number to
VC + 29 will cause it to be stretched sideways. In this program, both sprite
oand sprite 2 need to be expanded and so the value 5 is POKEd. This is the
sum of 1 (sprite 0) and 4 (sprite 2). In a similar way, the colour and location
of sprites on the screen are all controlled with reference to this important
location Vc.
25
Programming/or Education on the Commodore 64
Diagram A
The test routine from lines 1860-2120 present a target number which the
child has to attempt to bomb. This can only be done by typing in a correct
factor. The input routine is error-trapped to prevent the number itself, or
1, or non-numeric values, from being accepted. The target number itself is
carefully tested by the separate subroutine to make sure that a prime
number is not set. This is achieved by using the array of prime numbers set
up earlier in the program.
The routine from 2140-2500 flies the plane over the desert and bombs the
number if a correct factor has been typed. The REMs present in this
routine indicate each stage of the flight. Note how the location VC + 16 has
been set at line 2190 to allow the flight across the righthand side of the
screen.
26
CHAPTER 2
Small is Beautiful. • •
Although it has been pointed out that exciting displays do not turn a
mediocre program into a good one, there is no doubt that some programs
benefit from interesting graphics.
At the beginning of this chapter, we shall show you some short programs
in which the fast calculating power of your 64 is used, rather than its
graphic ability. Towards the end, some of these ideas are put into a more
advanced program that includes graphics.
Firstly though, an indication of simple ways in which the computer can
do tasks faster and more efficiently than humans.
A question of format
In the last chapter, there was a table test program that used the computer to
generate the questions. The same idea can be used with any sort of maths
problem. One difficulty that many children in the early primary years
experience is that of coping with problems posed in an unfamiliar way. If a
sum says
15 -? =7
15 -7 =?
27
Programming/or Education on the Commodore 64
Missing
READY.
Line 50 sets the score to zero and clears the screen. Line 60 starts the loop to
ask 10 problems.
Lines 70 and 80 choose random whole numbers between 0 and 99, and line
90 checks that B is not greater than A.
Line 100 calculates the answer. Line 110 sets out the question line. The
semicolons in this line are not essential, as they are in an INPUT line, eg
line 130.
Line 130 requires an input, GUESS. Lines 140 and 150 check GUESS and
compare it with the correct answer, C. If it is the same, the score is
increased by one.
28
Chapter 2 Small is Beautiful
Line 170 clears the screen. Line 190 prints the score, S.
Everything in order
Sequences and series of numbers sometimes take a long time before the
idea is grasped. The next program shows how the computer can generate a
series of numbers in a particular range. Although not an elaborate pro-
gram, it will generate sequences and mark the responses all day without
getting tired.
The particular sequence chosen is one that increases by the same amount
each time, eg
4 8 12 16 20 24 etc.
It is quite easy to change the program so that it chooses numbers where the
increment alters by a set amount, eg
2 4 7 11 15 etc.
4 9 16 25 36 etc.
Series
29
Programming for Education on the Commodore 64
13121 NEXT X
14121 PHINT
15121 B = A + (INCR * X)
16121 INF1JT "vJHAT IS THE NEXT NUI'1BEH";G
17121 IF G = B THEN PRINT"OK":S=S+1.
18f2l IF G <>B THEN F'RINT"NO"B
190 NEXT N
2f2l1Zl PRINT "YOU SCORED"S"OUT OF 1(2)"
HEADY.
Commentary
Line 50 clears the screen. Line 65 sets the score to 0 at the start.
Lines 110 to 130 contain a loop to generate the next four numbers in the
series. Each number is bigger by the amount INCR.
Line 150 relies on the fact that the FOR ... NEXT loop counters contain a
value one higher than the last count of the loop, ie 5, to set B equal to the
next number in the sequence. Line 160 asks for an input, G.
Lines 170 and 180 compare G with the correct answer, B, and print OK or
NO, as well as increasing the score if necessary.
Logical guessing
There is a game that you can play using the blackboard, a piece of paper, or
just your memory. It is the familiar one of 'I am thinking of a number-
ask me any question about it you like, but I can only reply using yes or no.'
Faced with this problem for the first time, the child may be inclined to
guess. If he or she realises that the number can be anything under (say)
1000, it is not long before it is appreciated that the task is difficult, and that
some sort of logical strategy must be employed.
30
Chapter 2 Small is Beautiful
Number is 242.
31
Programming/or Education on the Commodore 64
Number
READY.
Commentary
Line 40 sets the background colour to white. Up to this point, you have
probably been putting up with the light blue background that appears
when you switch on. POKEing this location in memory with a number
from zero to 16 sets the background colour.
Line 60 initialises the score, Sc. Line 70 sets the bottom limit for the
number to zero.
32
Chapler 2 Small is Beautiful
Line 130 allows the user to set the upper limit for the number. Line 140
chooses the number to be guessed.
Lines 200 to 220 check the guess, GS, against the chosen number, N. If the
guess is larger than the number, then the guess becomes the new upper
limit; and if the guess is smaller than the number, the guess becomes the
new bottom limit.
Although it is not so easy to see, there is a loop between lines 150 and 230.
This loop is negotiated each time a number is guessed, until the correct
answer is given. This causes an exit in line 200. 64 BASIC only supports a
FOR ... NEXT loop, and this entails knowing how many times you will
pass through it, which in this program, of course, you don't.
Line 320 contains the words GET Z$. This waits until a key is pressed, and
then checks the input in line 330. If the key is anything except the space bar,
the program repeats line 320.
Firework
The next program, Firework, is also based on a simple idea - offering
examples of the four rules (add, subtract, multiply and divide). The incen-
tive to do well here is the impressive display after five correct answers.
Each of the graphic routines is held in a module, and may be adapted to
your own use or copied directly into a different program. Fun notes on how
the effects are achieved are to be found at the end of the program.
33
PrOKramminK/or Education on the Commodore 64
1. ~~8~1 F~Et"1
1090 REM DEFINE SPRITES
1100 REM BEGINNING OF 6567 VIDEO CHIP
111 e;VC =: 5:-524·8
1120 REM ROCKET. SPRITE 0
1130 REM SET POINTER FOR SPRITE ~
1140 POKE 2040. 13
1150 REM READ DATA FOR SPRITE 0
1160 FOR I = m TO 8
1170 READ N : POKE 832 + I, N
118~~ NEXT I
1190 FOR I = 9 TO 51 STEP 3
120m POKE 832 + I. 0
1210 127
1220 0
1230
1240 FOR I = 54 TO 6?
1250 READ N ~ POKE 832 + I, N
1260 NEXT I
1270 REM EXHAUST. SPRITE 1
1280 REM SET POINTER FOR SPRITE
1290 POKE 2041. 14
1300 REM READ DATA FOR SPRITE 1
1310 FOR I = 0 TO 62
1320 READ N : POKE 896 + I. N
1330 NEXT I
1340 REI'1 1'1OON, SPR I TE 2.
1350 REM SET POINTER FOR SPRITE 2
1360 POKE 2042, 15
1370 REM READ DATA FOR SPRITE 2
138m FOR I = 0 TO 62
1390 RE~ID N ~ POKE 960 + I • N
14·(ZHZI NEXT I
1410 REl'-1 ENLARGE SPRITES IN X DIRECTION
1420 POKE VC + 29, c- ~l
34
Chapter 2 Small is Beautiful
35
Programming/or Education on the Commodore 64
2010 RETURt'--.l
2(i.~20 REM
36
Chapter 2 Small is Beautiful
37
Programming/or Education on the Commodore 64
38
Chapter 2 Small is Beautiful
READY.
Commentary
The control module for Firework is formed by the lines 1020-1060. It can
be seen that the program is in an overall loop and so RUN/STOP has to be
used to escape from it.
The first routine of the program defines three sprites. First the value ofVC
is initialised by line 1110. Then the rocket, its exhaust and the Moon are
defined in turn as sprites 0-2. The three diagrams show each of the sprites
in detail. It can be seen that the major part of the rocket is a very repetitive
shape and this pattern is reflected in the way that the corresponding sprite
data is built up by the use of the FOR ... NEXT loop from lines
1190-1230. The other two sprites are built up instead simply from the
DATA stored at the end of the program. Lines 1410-1480 then select the
size and colour of the sprites.
Lines 1510-1690colour the screen blue and place grass at the bottom. The
rocket is located on the grass by POKEing the two locations VC and
VC + 1, which control its horizontal and vertical location on the screen.
Finally the rocket is made to appear by POKEing its sprite number, 1, to
VC + 21. This is the location which controls whether a particular sprite
appears on the screen or not. Line 1690 selects white text for the subsequent
test routine.
The test given to the child is simple subtraction of numbers. Line 1770
chooses A to be a number less than 100. Line 1780 then multiplies A by a
random decimal number and takes the integral part. In this way, it is
ensured that the number being subtracted is not larger than the one it is
being subtracted from. Line 1800 then prevents the calculations from
being too easy. Again extensive use is made of a PRINT TAB subroutine to
allow the screen to be neatly arranged. Lines 1840-1890 stop letters being
accepted as an input. The variable S keeps a record of the child's success
and governs exit from the test to the reward routine at line 1950.
Lines 2030-2670 control the flight of the rocket up into the sky. Here the
sprites allow easy animation. An increased sense of upward motion is
attempted by removing the ground between lines 2280- 2340 and by
moving the Moon downwards in the loop 2440- 2480. The sound of the
rocket is created by the separate routine between lines 2740- 2870 and con-
trolled by the value of the flag SD. The loop from 2540-2630 uses another
subroutine to place a starburst on the screen.
39
Programming/or Education on the Commodore 64
Diagram B
.•••
...
•••• • ••.
"
,:" '
'
:
r"
"
'
••
••
--;'.1
••
•••
. '
~", ,
:.-~ ...
"
:t:'
..:'~" . -::~..; ~ ~-
••
• . i
•••••
.. .
••• •••
•• '
40
Chapter 2 Small is Beautiful
Diagram C
41
Programmingfor Education on the Commodore 64
Diagram D
42
Chapter 2 Small is Beautiful
Fraction
There is no doubt that in the whole of maths teaching, there is no topic so
off-putting to children, parents and teachers alike as that of fractions.
Children of seven and eight often have an intuitive grasp of halves and
quarters, but the notation of vulgar fractions is unfamiliar and the terms
numerator and denominator are awkward in themselves. Recent surveys,
such as the Cockroft Report (1982), have implied that work should concen-
trate on decimal fractions at least until the upper end of primary schools.
This does not mean that the idea of fractions can go out of the window.
Children need a lot of practical experience in dividing objects up into
equal-sized parts before they understand fractional concepts. It is usually
in the recognition of what a fraction stands for, and in the manipulation of
its parts, that problems occur. In this chapter, we have attempted to tackle
this problem in different ways.
Fraction displays a rectangle, representing the whole object; it then
colours in a particular fraction and asks the child to input the numerator
and denominator. These terms are used on the screen and there is no doubt
about which is which.
As an aid to knowing how to express the fraction, ie whether t or t is
required, the whole rectangle is divided up into the same number of parts as
the denominator. For instance, if t is required, the rectangle divides into six
clearly-defined sections, and two of these are coloured in. Should the child
make an incorrect input, there is a routine to show how the fraction is built
up. If the child is successful, the examples become progressively more dif-
ficult, whereas those for a child with difficulties remain simple.
43
Programming/or Education on the Commodore 64
44
Chapter 2 Small is Beautiful
45
Programming/or Education on the Commodore 64
46
Chapter 1 Small is Beautiful
READY.
Commentary
The control module for Fraction lies between 1020-1060, which form a
loop calling up initialisation, selection, drawing and testing routines. The
program does not come to an end unless RUNISTOP is pressed.
Lines 1090-1140 are the initialisation routine. The variables Sand G are
set equal to zero at line 1110. They record the score the child has achieved
and the number of fractions attempted. The variable DF is initialised by
line 1130. DF controls how hard each fraction is. The smaller the value of
DF, the smaller the numerator and denominator of the fraction drawn on
the screen. The value of DF is continuously monitored during the execu-
tion of the program, so that when the child types in a correct answer the
level of difficulty increases. If an answer typed in is incorrect, the value of
OF is decreased so that the fractions become easier. It is not quite this
simple, as a random factor is introduced as well, but OF does determine the
overall trend towards harder or easier examples.
The fraction is generated between lines 1160-1320. The denominator, D,
is selected at line 1170. OF enters into the expression as the number that the
random fraction RND(l) is multiplied by. Line 1180 relates the size of the
numerator, N, to that of D. Obviously, the way in which the two numbers
are generated ensures that the numerator is smaller than the denominator,
as is necessary.
Lines 1210-1290 relate the value of the variable W to that of D. W is used
in the following routine when the diagram of the fraction is drawn on the
screen. Here, however, it is adjusted to give the largest possible diagram
for the fraction chosen. Finally, this routine calculates a value for the
47
Programmingjor Education on the Commodore 64
Lines 1340-1890 form the routine which places the fractional diagram on
the screen. It is built up quite naturally in a series of blocks or divisions
corresponding in number to the size of the denominator.
After the screen has been cleared by line 1370 and the title and other
headings placed by lines 1380-1440, a lengthy FOR ... NEXT loop, from
lines 1470-1810, constructs each division of the diagram in turn. At the
beginning of this loop, a new value is first calculated for LD for the current
division. The J loop between lines 1520-1570 draws the top and bottom of
the division in black. A subroutine at lines 1910-1930 is used by this loop,
and also for all successive plotting on the screen. This is followed by a brief
sound effect to help draw attention to the process of building up the dia-
gram and hence to aid the child's counting. The sound is generated by the
various POKEs between lines 1590-1640. After this, the lefthand edge of
the division is plotted by the loop between 1650-1690.
So far, only three sides of the division have been drawn. The enclosed
area is coloured in by the two nested FOR ... NEXT loops from
1750-1800. The colour the area is plotted in is chosen at lines 1710-1740.
The numerator of the fraction appears in green and the remaining divisions
in yellow. Line 1810 ends the I FOR ... NEXT loop.
After the D divisions are drawn, there is still the extreme righthand edge
of the diagram to be filled in. The loop between lines 1850-1880 does this.
Note how the same subroutine has been repeatedly called during the whole
of the construction of the diagram.
Lines 1990-2160 make extensive use of the PRINT TAB routine between
1940-1970 to format the presentation of the question on the screen.
Another subroutine at lines 2190-2290 checks that acceptable values are
typed in. Lines 2140 and 2150 then select either reward or correction
routines at the end of the program. It is here that the value of DF is adjusted
to correspond to the degree of success or failure the child is experiencing.
Success will lead fairly quickly to harder examples, whereas constant
failure would lead to the child using the program being shown a diagram of
t over and over again, together with the correction routine. Although it is
quite simple to arrange for programs to be self-adjusting to the child's level
of ability, nevertheless such an arrangement allows far more effective
learning programs to be constructed.
48
CHAPTER 3
VVords, VVords, VVords
So far in the book, the majority of programs have involved some sort of
maths skills. The 64 contains many facilities that make the handling of
words much easier. As has been mentioned before, computers are just as
happy manipulating letters as figures. Numbers are stored as numeric
variables, such as X or COUNT, and strings of characters as string varia-
bles, such as A$ or BOOK$. Each character in the 64 has acode number that
refers to it, so 65 stands for A, and 90 stands for Z. You can check this out
yourself by entering this short program.
10 FOR N = 65 TO 255
20 PRINT CHR$(N)
30 NEXTN
49
Programming/or Education on the Commodore 64
40 C = ASqZ$)
50 PRINTC
60 GOTO lO
Commentary
Line 20 clears the keyboard buffer (a temporary memory store for key-
board input).
Line 30 reads the keyboard and repeats until a key is pressed. Note that
there is nothing between the two quote marks. This is called an empty
string.
Line 40 assigns the ASCI I code of the key pressed to the variable C.
Lines 50 and 60 print the code and send the program back to the start.
If you run this program, you will discover many useful things. Apart from
pressing letter keys, try pressing number keys, the arrowed cursor keys,
and the function keys. You will find that all the keys generate codes except
[RESTORE], [CTRL], [SHIFT] and [SHIFT LOCK], [C =] and
[RUN/STOP] on their own. Many keys, such as A, have three codes,
depending on whether you are pressing [SHIFT] or [C =] at the same time.
The key A normally has a code of 65, but it produces 193 with [SHIFT]
and 176 if [C =] is also held down. This is useful in programs, as you can
check which keys are being pressed at any time.
If you have a program that requires a word or phrase to be input into a
string, the length of the string can be checked by using the function LEN. If
you enter directly
X$ = "HELLO"
then
PRINT LEN(X$)
lO A$ = "ABCDEFGHIJ"
20 PRINT RIGHT$(A$,4)
50
Chapter 3 Words. Words. Words
30 PRINT LEFT$(A$,4)
40 PRINT MID$(A$,2,6)
If you RUN this, it will print GHIJ in line 20, as these letters are the last
four letters on the right of the string. ABCD will be printed out in line 30, as
they are the first four letters on the left of the string. Line 40 will print out
BCDEFG, as these are the six letters starting from the second character in
the string.
This program will show you how the 64 can search through strings using
these functions:
Alphasort
51
Programmingjor Education on the Commodore 64
READY.
Commentary
There are one or two new ideas in this program. A sorting routine needs to
hold the words, not in one variable, but in an array. This has to be DIMen-
sioned so that some space in memory is reserved for the words that will be
stored in it.
Lines 230 to 300 contain the sorting routine. There are two loops, K and L,
and the ASCII codes of the words are compared in line 250. If a word has a
higher code than the one after it, they are swapped in the list. The loop
compares all the words against each other until they are in alphabetical
order.
52
Chapter 3 Words, Words, Words
the key. Pressing the [C =] key and a letter key gives you the graphic char-
acter printed to the left on the front of the key.
If you hold down the [SHIFT] and [C = ] keys at the same time, you can
switch between upper and lower case modes. Lower case mode is a little like
using a typewriter: pressing a letter key gives you the lower case version,
and pressing [SHIFT] with the letter gives the upper case version of that
letter. Pressing the [C =] key and a letter key still gives you the graphic
character printed to the left on the front of the key.
You can switch to upper case mode in a program by including PRINT
CHR$(l42) in a line. To switch to lower case mode, use PRINT CHR$(14).
The graphics characters can be used to draw pictures on the screen, by
using quotes to surround the graphics, just as if you were printing words.
Numbers in strings
You have probably seen that there are two ways to print 123 on the screen.
You can enter
PRINT 123
or
PRINT "123"
Although you see the same figures appearing on the screen, it is important
to realise the difference that the 64 sees. 123 is seen as a number, with the
value 123. "123" is seen merely as a string of characters. To see the differ-
ence, try this as a direct command:
You should get 246 as the answer, because the computer understands these
to be numbers. If you enter:
A$ = STR$(l23)
53
Programming/or Education on the Commodore 64
The reverse of this is achieved by using the VAL function. Even though
strings can't normally be considered to be numbers, they do have a value.
PRINTVAL("123") + I
Simon
In this program, the fact that strings can be concatenated (added together),
is used as the basis for a memory game. A string contains the STR$ version
of numbers chosen at random from one to eight, and the object is to
remember their order. The length of the string increases by one each time a
correct answer is entered.
The game of Simon is usually played with colours and sounds as extra
memory aids. The 64 stores the code of the colour in which text is printed at
location 646 in the memory. If this is POKEd with numbers from 0 to 15,
the sixteen available colours can be selected.
The number keys on the 64 have colours printed on them, BLK, WHT,
etc. The numbers on the keys are one higher than the code to be POKEd to
646, hence the line that subtracts one from the value of the string.
The sound commands are a little more complicated. They are explained
in more detail in the program notes.
54
Chapter 3 Words, Words, Words
17V1 PRINT
1. 8V1 PR I tH" 1'1UST TYPE THEM IN, I N THE"
1 9V1 P R un
200 PRINT" RIGHT ORDER. THE NUMBER OF"
21V1 PRINT
220 PRINT" FIGURES WILL INCREASE BY ONE"
230 PRINT
240 PRINT" EACH TII'1E."
250 PRINT
260 PRINT" PRESS SPACE BAR TO GO"
270 GET Z$:IF Z$="" THEN 270
280 PRINTCHRS(147):POKE53281,12
29V1 F:E1"1
3Q)0 REM *** MAIN GAME LOOP ***
310 REI'1
320 FOR Z= 1 TO 10
33V1 X=INT(RND(Q)*8)+1
340 X$=STR$(X):X$=MID$(X$,2,1)
350 Y$==Y$+X$
360 GOSUB 490:POKE198,0
370 INPUT"ENTER YOUR GUESS";G:t
380 IF G$ = Y$ THEN S=S+1
390 IF G$ (>Y$ THEN Z=11:GOSUB630
412HZ) NEXT Z
41V1 REM
420 REM *** SCORE ROUTINE ***
430 REM
440 PRINT"YOU SCORED"S
450 PRINT"PRESS ANY KEY TO GO AGAIN"
46121 GET Z$:IF Z$=""THEN 46121
47121 RUN
48(2) REM
490 REM *** COLOUR PRINT SUBROUTINE ***
50121 REM
51121 PF< I NT
520 FOR N = 1 TO LEN(Y$)
530 AS=MID$(Y$,N,l):V = VAL(A$)
540 POKE 646,V-1:REM COLOUR VALUE
55121 PF:INT A$;" ";
56121 GOSUB 700
570 NEXT N
58(21 PRINT
590 FOR PAUSE=l TO 10(21(21:NEXT PAUSE
600 PRINTCHR$(147):POKE646,1
55
Programmingfor Education on the Commodore 64
610 HETURN
620 REM
630 REM *** FAULT SUBROUTINE ***
640 REM
650 PR I NT" t'\ I 5T PI~:::E ! IT WAS "'y':f.
660 RETURN
700 REt1
710 REM *** SOUND SUBROUTINE ***
720 REI'1
T50 5C :::: 54272
740 POKE SC+24,15:REM VOLUME
750 POKE SC+4,33
760 POKE SC+5.10:POKE SC+6,4
770 V==V*2000
780 HIGH = INT(V/256):LOW == V-HIGH*256
790 POKE SC+1,HIGH:POKE SC,LOW
800 FOR PAUSE = 1 TO 400:NEXT PAUSE
810 POKESC+4,0
820 RETURt·"
READY.
Commentary
Line 80 shows another way of clearing the screen - PRINT CHR$(147).
The second statement sets the background colour to black.
Line 270 waits until any key is pressed. Line 280 clears the screen and sets
the background colour to grey.
Line 330 chooses a number at random between 1 and 8. Line 340 turns the
number into a string, and the second statement strips away the first char-
acter, a space. Line 350 adds the new figure to the existing string.
Line 360 sends program control to the print routine and clears the key-
board buffer to prevent cheating!
Line 380 checks the input against the string and increments the score by
one. Line 390 ends the Z loop if the answer is incorrect, and sends the
program to the fault subroutine.
56
Chapter 3 Words. Words. Words
Lines 440 to 470 print the score and start the program running again.
Lines 520 to 570 print the separate figures in the string after their colour
codes have been POKEd into memory location 646. Line 550 prints a space
between each figure.
Lines 590 and 600 provide a delay of about two seconds before the string
disappears.
Line 730 sets SC equal to the starting address of the 6581 SID sound chip.
This makes all the subsequent addressing of locations in this chip easier to
follow.
Line 740 sets the volume to maximum. Line 750 sets the total quality of
voice 1 to a sawtooth waveform. Line 760 sets the envelope of voice 1
(attack/decay and sustain/release).
Line 770 sets the frequency of the note by mUltiplying the value of the
figure in the string (V), by 2000. The SID chip is capable of producing notes
of a frequency that can be stored in two bytes. The highest value that could
be stored is therefore 256*256 or 65536. Line 780 calculates what should be
POKEd into this two-byte frequency store to produce the required note.
Line 800 controls the length of the notes. Line 810 sets the waveform con-
trol register to zero.
57
Programming for Education on the Commodore 64
need to be taught, however, and this book would lack any structure if the
programs were not divided up in some manner.
It is with this in mind that the programs in this chapter have been
included. They attempt to help the teacher or parent instil basic spelling
and comprehension skills.
Hangman
Some children are lucky and have no difficulty in spelling. Others attempt
a phonetic approximation, and yet others never seem to grasp the idea.
Although poor spelling often goes hand-in-hand with poor reading skills,
there are many good readers who reach adulthood and still suffer from
difficulties with their spelling. Traditional methods of learning words by
heart for a weekly test are no bad thing if the words are relevant to the
child's immediate situation, eg if they come from a project or topic that is
being studied. If the child uses the words in their proper context, the spell-
ing is reinforced.
There are two approaches here - one is to show the context of the word
and to offer a multiple choice of possible spellings. The other approach is
to build up the word slowly, with spaces for missing letters. The game of
hangman is an ideal vehicle for this approach. The program that follows
builds up a picture of Ie pendu, as in the traditional game, and 10 guesses
are allowed before the victim is finally throttled.
Words to be selected are held in DATA lines, so there is no problem in
changing these to words relevant to a topic, or to those displaying a parti-
cular spelling point, such as 'ie' and 'ei' words. You could even use the
program to help learn foreign words. The only requirement is that the total
number of words should not change, as the READ statement needs 20
words. If you want a larger selection, then the number may be altered as
detailed in the program notes.
58
Chapter 3 Words, Words, Words
210110 RESTORE
210210 FOR N=ITO INT(RND(ID)*2ID)+1
210310 READ Wt
210410 NEXT
210610 PRINT""
210710 X=5:Y=15:GOSUB4IDID0
210810 FORN=ITOLEN(Wt)
210910 PRINT"-":
211010 NEXT N
21210 SC=ID:Z=ID
21310 X=5:Y=2ID:GOSUB40IDID
21410 G.t="":PRINT"YOUR GUESS";
2145 POKE198.ID
21510 INPUTGt:FLAG=1
2155 IFGS=Wt THEN GOSUB3IDIDID:RETURN
21610 LN=LEN(WS)
21710 IF LEN(GS)<>LN AND LEN(GS»1 THEN X=15:Y=2ID:
GOSUB4IDIDID
21810 IF LEN(GS)<>LN AND LEN(Gt»1 THEN PRINT"
59
Programmmgjor Education on the Commodore 64
261215. REl'l
261121 POKE646.(SC)ANDSC)2:REM COLOURPRINT
262121 X=38:REM *** UPRIGHT ***
263121 IFSC=1 THEN FORY=19T03STEP-l:GOSUB4f21121121:
PRINTCHR$(166):NEXT
264121 Y=2: REM *** CROSSPIECE ***
265121 IFSC=2 THEN FORX=29T038:GOSUB4121121121:PRINTCHR$
(166):NEXT
266121 X=29:REM *** ROPE ***
267121 IFSC=3 THEN FORY=3T05:GOSUB4121121121:PRINTCHR$
(18121):NEXT
272121 X=27:Y=5:GOSUB4f21121I21:REM FACE *
273121 IF SC=4 THEN PRINTCHR$(11210)CHR$(11211);
274121 IF SC=4 THEN PRINTCHR$(1f212)CHR$(11213)
2745 X=27:Y=6:GOSUB4121121121
275121 IF SC=4 THEN PRINTCHR$(1f214)CHR$(11214);
276121 IF SC=4 THEN PRINTCHR$(11216)CHR$(11217)
2765 X=27:Y=7:GOSUB4121121121
277121 IF SC=4 THEN PRINTCHR$(11218)CHR$(11219):
278121 IF SC=4 THEN PRINTCHR$(ill21)CHR$(III)
2785 X=27:Y=8:GOSUB4121121121
279121 IF SC=4 THEN PRINTCHR$(112)CHR$(113):
28121121 IF SC=4 THEN PRINTCHR$(114)CHR$(115)
2815 X=28:REM *** BODY ***
282121 IFSC=5THENFORY=9TOI3:GOSUB4121121I21:PRINTCHR$
(166)CHR$(166):NEXT
2825 X=28:REM *** L.ARM ***
283121 IFSC=6 THEN FORY=9I013:X=X-l:GOSUB4121121I21:
PRINTCHR$(169):NEXT
2835 X=29:REM *** R.ARM ***
284121 IFSC=7 THEN FORY=9TOI3:X=X+l:GOSUB4121f21121:
PRINTCHR$(127):NEXT
2845 X=29:REM *** L.LEG ***
285121 IFSC=8 THEN FORY=14TOI8:X=X-i:GOSUB4121121I21:
PRINTCHR$(169):NEXT
2855 X=28:REM *** R.LEG ***
286121 IFSC=9 THEN FORY=14TOI8:X=X+i:GOSUB4121121121:
PRINTCHR$(127).NEXT
298121 POKE646,11
299121 RETURN
3121121121 REM
31211121 REM *** SUCCESS ROUTINE ***
31212121 REM
31213121 X=5:Y=15:GOSUB4121121121
31214121 PRINTW$
31215121 FOR PAUSE = 1 TO 2121121121: NEXT PAUSE
31216121 X=I2I:Y=11:GOSUB4121121121
31217121 PRINT"THANKS FOR SAVING ME!"
60
Chapter 3 Words. Words. Words
:3080 PR I NT
3090 PRINT"YOU GUESSED "W$
3100 PRINT
::.105 POf:::E 1 98 • 0
3110 PRINT"PRESS SPACE BAR TO GO"
3120 GET Z$:IF Z,f.="" THEN 3120
3130 RETURN
4000 REM
4010 REM *** 'PRINT AT' ROUTINE ***
4020 REM
4030 POKE782.X:POKE781.Y:SYS65520:RETURN
6000 REM
6010 REM *** MOVE CHARACTER SET ***
6020 REl'l
6030 PRINTCHR$(142)
6040 POKE52.48:POKE56.48
6050 POKE56334.PEEK(56334)AND254
6060 POKE1,PEEK(1)AND251
6070 FORN=0TOI023
6080 POKEI2288+N.PEEK(53248+N)
6090 NEXT N
6100 POKE1,PEEK(I)OR4
6110 POKE56334,PEEK(56334)ORI
6120 POKE53272, (PEEK(53272)AND240)+12
6130 REM
6140 FORN=IT020:READZ$:NEXT
6150 FORN=0T0127
6160 READ Z
6170 POKE12288+68*8+N,Z
6180 NEXT N
619(2) RETURN
7000 REM
7010 REM *** INSTRUCTIONS ***
7020 REM
703(2) PRINT""
712150 PRINT" IN THIS GAME, YOU WILL BE"
7060 PRINT
7070 PRINT" GIVEN A ROW OF DASHES"
71218121 PRINT
71219121 PRINT" EACH DASH STANDS FOR A LETTER"
710121 PRINT
711121 PRINT" YOU HAVE TO GUESS THE LETTERS"
712121 PRINT
713121 PRINT" IF YOU ARE RIGHT THE LETTER"
714121 PRINT
715121 PRINT" WILL APPEAR. IF YOU ARE"
716121 PRINT
7171Z1 PRINT" WRONG, PART OF THE MAN APPEARS"
718121 PRINT
61
Programmingfor Education on the Commodore 64
READY.
Commentary
As this is a fairly complicated program, we have inserted a lot of REMs to
inform you of what is happening.
Lines 1040-1070 constitute the control module. Line 2000 begins the game
subroutine.
62
Chapter 3 Words. Words. Words
Lines 2020- 2040 choose a word, W$, at random from data. Line 2070 sets
the 'print at' coordinates. Lines 2080-2100 print dashes according to the
number of letters in the word. Line 2145 empties the keyboard buffer.
Line 2150 accepts the guess, G$, and sets the variable FLAG to a one. This
is only changed to a zero if a correct letter is input, and is used in line 2260 to
check if part of the gallows should be drawn.
Line 2155 checks to see if the whole word has been entered. If it has, the
program jumps to the winning routine.
Line 2160 sets variable LN to the length of the chosen word, W$.
Lines 2170- 221 0 check the length of the guessed word against the chosen
word. If more than one letter is input, it is ignored, unless it has the same
number of letters as W$.
Line 2220 contains the counter for the number of incorrect guesses, Z.
Lines 2230- 2250 check each letter of W$ to see if it contains the guessed
letter, G$. If any letter is the same, subroutine 2500 prints it in the correct
place. The flag is also changed to prevent part of the gallows being built.
Line 2270 and 2280 print the number of lives remaining at the top of the
screen.
Line 2290 sends the program back to the start of the guess loop if less than
lO incorrect guesses have been made. On loop lO, the program continues.
Line 2500 is a short routine to print a letter in the correct place. It uses the
loop counter N, to tell it where to put the letter.
Lines 2600- 2990 contain the rather large drawing routine to construct the
gallows and the man.
Line 2610 uses the number of incorrect guesses, SC, to control the printing
colour.
Lines 2620 and 2630 use a loop to draw the upright post. CHR$(166) is a
graphics character like a tiny chessboard.
Lines 2640 and 2650 use another loop to draw the crosspiece. GOSUB
4000, to the 'print at' routine, ensures that the next print position is con-
trolled by the X value in the loop counter.
63
Programming/or Education on the Commodore 64
Lines 2730- 2800 draw the head. This is made up from defined characters
held in DATA statements. The 'print at' routine is again used to control the
position of the head.
Lines 2815-2860 use the same principle to draw the rest of the body
according to the value of the variable Sc.
Line 2980 POKEs the printing colour back to grey. The success routine also
uses the 'print at' routine to print the correct word and a thank-you
message.
Line 4030 contains the short 'print at' routine where the new X and Y
coordinates are POKEd into memory. Without this routine, the effects in a
program like this would have been much more difficult to achieve.
Lines 9000 onwards contain all the data for the program. It is divided into
two sections, the first containing the words to be used, and the second the
data for the redefined graphics used to draw the face.
Anagram
It is hoped that the programs that are included in this book reflect to some
degree the belief that children do not come to school simply to acquire
knowledge that mayor may not be useful in the future. Children need to
learn many skills at primary age, and, apart from the most important
(social skills), thinking skills and the ability to research and store informa-
tion must rank high in the list.
Although spelling is important in its own right, the child who has diffi-
culty with spelling will be at a disadvantage when it comes to finding
information from reference books. There is little point in giving a child an
64
Chapter 3 Words, Words, Words
encyclopedia and saying 'Find out all you can about beer production in
Belgium' if the child cannot spell Belgium and does not know how to find
the information in the first place. Information from a book may not be as
good as firsthand experience (especially in the example in question!), but it
is better than no experience at all.
The following program can be used as a spelling aid, or in any other
subject area to familiarise children with new words. Anagram allows the
parent or teacher to load data lines with a fresh vocabulary. The child is
presented with a scrambled version of the word on the screen and has to
input the word, spelt correctly. Points are gained for getting the word
right. The final score is shown after 10 words have been displayed.
100 REM
1010 REM *** ANAGRAM GAME ***
1020 REM
11Z131Z1 REM *** AJS 4/10/83 ***
1040 REM
1050 GOSUB 1500:REM INSTR
1060 FOR TRY = 1 TO 10
1070 GOSUB 2000:REM GET WORD
1080 GOSUB 3000:REM MIX WORD
1090 GOSUB 4000:REM GAME
1100 NEXT TRY
1110 GOSUB 5000:REM SCORE
1120 STOP
1499 REM
1500 REM *** INSTRUCTIONS ***
1510 REM
1520 POKE53281,1:POKE 646,0
1530 PRINTCHR$(147)
1540 PRINT
1550 F'R I NT" YOU WILL BE SHOWN A NUMBER"
1560 PRINT
1570 PRINT" OF JUMBLED UP WORDS"
1580 PRINT
1590 PRINT" YOU CAN ASK FOR THEM TO BE"
1600 PRINT
1610 PRINT" MIXED UP AGAIN OR YOU CAN"
1620 PRINT
1630 PRINT" GUESS WHAT YOU THINI< THE"
1640 PRINT
1650 PRINT" WORD REALLY IS"
1660 PRINT
1670 PRINT" AFTER TEN WORDS YOU WILL"
1680 PRINT
1690 PRINT" BE SHOWN YOUR SCORE"
1700 PRINT
65
Programming/or Education on the Commodore 64
GOT03(l)6(l)
3050 NW$=MID$(DUMMY$,N,1J+NW$
3060 NEXT N
31370 DUMMY$=NW$
31380 IF NW$=WD$ THEN 31320
3090 RETURN
3990 REM
40130 REM *** DISPLAY ***
4010 REM
4020 PRINTCHR$(147)
4030 PRINT
4040 PRINT"YOUR JUMBLED LETTERS ARE:-"
4050 PRINT
413613 PRINT NW$
4070 X1=PEEK(782):Y1=PEEK(781)
4080 X=5:Y=22:GOSUB6000
4090 POKE198,0
411313 PRINT"M.TO MIX, G TO GUESS?"
4110 GET l$
4120 IF Z$<>"M" AND Z$<>"G" THEN 4110
4130 X=X1:Y=Yl:GOSUB 6000
41413 IF Z$="M" THEN GOSUB 3000
4150 IF Z$="M" THEN GOTO 4020
4155 X=5:Y=22:GOSUB6000
4160 INPUT"ENTER YOUR GUESS ---)";G$
41713 IFG$ = WD$ THEN GOSUB4500
4190 IFG$ <>WD$ THEN GOSUB4600
4200 RETURN
45013 REM
4510 REM *** SUCCESS ROUTINE ***
4520 REM
66
Chapter 3 Words, Words, Words
READY.
Commentary
Lines 1050-1120 form the control module. Lines 1060-1100 contain the
main loop which selects ten words to guess.
67
Programming/or Education on the Commodore 64
Lines 1500-1730 contain the instructions. Line 1520 sets the background
colour to white, and the printing colour to black. Line 1530 clears the
screen. Line 1720 waits for a key to be pressed before the program
continues.
Lines 2000-2060 get words at random from the DATA lines. If you have
more than twenty words in DATA, you will have to increase the size of the
loop in line 2030. RESTORE in line 2020 sets the data pointer back to the
beginning of the list of words each time.
Lines 3000- 3090 mix the letters of the word. The loop in lines 3030- 3060
goes through the letters of the chosen word one at a time. It builds a new
word by attaching a letter at random to either the front or back of the new
word.
Line 3070 uses DUMMY$ to hold a copy of the new word. Line 3080
checks to ensure that the new word is not the same as the original!
Lines 4000-4200 control the display of the game. Line 4020 clears the
screen. Lines 4040-4060 print the jumbled word.
Line 4070 saves the print coordinates in variables Xl and Yl. Line 4080
resets the print position to the bottom of the screen by jumping to the 'print
at' subroutine. Line 4090 clears the keyboard buffer.
Lines 4100-4120 allow the input of either M or G. If M is pressed, the
program jumps back to the mix subroutine. If G is pressed, the program
continues.
Line 4155 sends the print coordinates for the bottom of the screen to the
'print at' subroutine. Lines 4160-4190 check the guess against the actual
word and send control to the particular subroutine.
Lines 4500-4570 contain the success routine, which simply increases the
score by one and temporarily makes the background green in line 4540.
Lines 4600-4670 contain the mistake routine. This turns the background
colour to red.
Line 6020 is the 'print at' subroutine, which sends the coordinates of the
next print position to the operating system kernal.
Lines 9000-9120 contain all the words used. Any twenty words can be
used here, but avoid those with more than 10 letters, as they will extend on
to the next line.
68
CHAPTER 4
Making Friends with your Keyboard
READY.
Line 150 checks the ASCII code to make sure it lies between 48 (0) and 57
(9).
69
Programming/or Education on the Commodore 64
A routine like this can also make a program easier for the user. One of
the most frustrating things for an inexperienced user is for error messages
to appear on the screen when they are half-way through the program.
Shielding the user from the operating system is an important area of pro-
gramming, for, even if a program works perfectly, it can be spoiled by lack
of foresight on the part of the programmer.
Firstly, the program needs to be self-explanatory, as far as that is pos-
sible. If someone puts a cassette in and presses SHIFT and RUN/ STOP,
instructions on use should be the first thing that appears after the title. If
the program is easy and pleasant to use, it is usually termed 'user- friendly' .
If the program has several options, it is a good idea to make it menu-driven
to increase its friendliness. This means that a list of options appears on the
screen, and the user can make his selection from the displayed menu, eg
1. Instructions
2. Easy Problems
3. Harder Problems
4. Difficult Problems
70
Chapter4 Making Friends with your Keyboard
The example suggests the entry format, so the user knows the correct order
of input, and also that he is expected to enter figures and not words.
If impossible dates, such as -4/15/1983, are entered, they are outside
the permitted range of inputs. If letters are entered, eg APRIL instead of 4,
the 64 generates an error message - REDO FROM START - so the input
loop is repeated once more. If the RETURN key is pressed with nothing
entered, the loop is also repeated.
The way to make the routine check that only figures are entered would
be to make the input lines contain string, rather than numeric, variables,
and check their ASCII codes. This would be a useful exercise for you to try.
In this chapter, we are including some programs that help children find
their way round the keyboard. They also introduce ideas that you may find
useful in your own programs.
Keyboard encourages fast entry of all the characters on the keyboard.
The instructions are presented as a subroutine and the TIME function in
the machine starts when the space bar is pressed. A large version of the
character appears on the screen and three attempts are allowed to find the
correct key.
In the 64, the character definitions are stored at memory location 53248
onwards. Each character on the screen consists of eight rows of eight posi-
tions, like a chess board. Each row is represented by a binary number. If
you imagine a black character on a white background, then ones stand for
blacks, and zeros for whites, so a totally filled-in character would contain
255 in each row, as the binary code for 255 is 11111111.
On some computers, it would be easy to find the character definitions by
PEEKing the locations where they are stored. The 64, however, uses a
system that is more complicated, in order that more is available to the user.
It reads its character set from ROM which shares the same addresses as
user memory and some input/output routines. Every time the 64 needs to
display a character, a pointer in another part of the memory sends it to the
character ROM. If we want to read the definitions, or indeed to change the
set to display our own definitions, the easiest thing is to copy the entire
character set into user RAM (which can be altered). The 64 must also have
the pointer changed so that it points to the new character set.
The following program copies the character set from ROM into RAM at
location 12288. If this is all that is done, your BASIC program may over-
write the new set at a later stage. The 64 must be told that it cannot use this
space, so the pointers to string variable space and the highest address used
by BASIC have to be changed. Then the keyscan interrupts have to be
71
Programming/or Education on the Commodore 64
turned off and the 64 told to look at the character ROM rather than RAM.
At this point, all the necessary characters in the ROM can be scanned and
their definitions POKEd into their new locations in RAM.
If you were to halt the program at this point, you would find that the
keyboard had 'died'. Even the RUN/STOP and RESTORE method
would not retrieve your program, as the keyboard is not being scanned.
With the characters in their new location, the thing to do is first to switch in
the input/output routines, then to start the keyboard scan routine. Now
that the character set is in user RAM, you can look at it easily, or alter it as
necessary.
Once the character definitions are available, it is possible to PEEK them,
and use the codes to produce large versions of them on the screen.
The way this is achieved is by storing the definitions in arrays that hold
the code for each line as a binary number; so 170 is stored as its binary
equivalent, 10101010. This number is now scanned. If a 1 is found, a solid
block is printed; if a 0 is found, a space is printed. This results in a character
sixty-four times normal area being printed on the screen. The actual pro-
gram runs through the entire character set and prints the value held in each
location so you can see how the character is formed.
BigL
1000 REM *** LARGE CHARACTER PROGRAM ***
1010 REM
1020 REM *** MOVE CHARACTER SET )RAM ***
1030 REM
1040 PRINTCHR$CI42)
1050 POf<E52, 48
1060 POKE56,48
112170 CLR
108121 POKE56334,PEEK(56334)AND254
1090 POKE1,PEEK(I)AND251
1100 FORI=0T0511
1110 POKEI+12288,PEEKCI+53248)
1120 NEXT
1130 POKE1,PEEK(1)OR4
1140 POKE56334,PEEK(56334)ORI
1150 REM
1160 REM *** PRINT LARGE LETTERS ***
1170 REM
118121 Z=12288
1190 POKE53281,~
1200 DIMB(8):DIMC(8,8)
1220 FORX=0 TO 511 STEP 8
1230 PRINT"(SHIFT/CLR/HOMEJ"
72
Chapter4 Making Friends with your Keyboard
1240 FORN=0T07
1250 PRINTZ+X+N,PEEK(Z+X+N)
1260 B(N)=PEEK(Z+N+X)
1270 FORJ=0T07
1280 C(N,J)=INT(B(N)/2 A (7-J»
1290 B(N)=«B(N)/2 A (7-J»-C(N,J»*2 A (7-J)
1300 IFC(N,J)=ITHENPOKE(1064+N*40)+15+J,81:POKE
(55336+N*40)+15+J,0
1310 NEXTJ
1330 NEXTN
1340 NEXTX
READY.
Commentary
Line 1040 clears the screen. Lines 1050 and 1060 tell the 64 where to store
strings and the BASIC program so that it won't overwrite the new char-
acter set.
Line 1070 frees all available memory space. Line 1080 turns off the key-
board scan. Line 1090 selects the character ROM. Lines 1I00 to 1I20 copy
the contents of the first section of the character ROM into RAM. Line 1130
deselects the character ROM. Line 1140 turns on the keyboard scan. Line
1180 sets Z equal to the start of the location of the copied character set.
Line 1190 sets the background colour to green. Line 1200 DIMensions
space for the arrays necessary to hold large versions of the character
definitions.
Lines 1220-1340 contain the loop to go through the entire 64 copied char-
acters. Lines 1240-1330 contain the loop to display each line of the
character.
Lines 1250 and 1260 store the decimal (normal) value of each line in a
variable, B(N).
Lines 1270 to 1310 contain a routine to convert the number in B(N) to its
binary equivalent. This is stored as a series of zeros and ones in array
C(N,J).
73
Programmingfor Education on the Commodore 64
user in a random fashion, and they have to input the correct letter from the
keyboard as fast as they can. If they are successful, another letter appears
and the time taken is added to their total time.
Keyboard
74
Chapter 4 Making Friends with your Keyboard
2150 NEXTJ
216121 NEXTN
2170 RETURN
312100 REM
3010 REM *** INSTRUCTIONS ***
31212121 REM
31213121 PRINTCHRS(147':PoKE53281,5:PoKE646,6
31214121 PRINT
305121 PRINT" YOU ARE ABOUT TO BE SHOWN"
312160 PRINT
3070 PRINT" 10 LETTERS AND OTHER SYMBOLS"
3080 PRINT
3090 PRINT" THAT ARE ALL ON THE KEYBOARD"
3100 PRINT
311121 PRINT" FIND THE CORRECT KEY AND PRESS"
312121 PRINT
313121 PRINT" IT AS QUICKLY AS YOU CAN"
3140 FOR X = 1 TO 8: PRINT : NEXT X
315121 PRINT" F'RESS THE SPACE BAR TO GO"
316121 GET ZS:IF Z$="" THEN 316121
3170 RETURN
4121121121 REM
4010 REM *** TEST MODULE ***
41212121 REM
403121 TS=TIME:SC=0
41214121 FOR G= 1 TO 1121
4050 GoSUB21210121
41216121 PoKE782,5:POKE781,20:SYS6552121
41217121 PRINT"THE LETTER IS------->";
41218121 Pol<E 198,121
41219121 GET Z$:IF Z$="" THEN 41219121
41121121 PRINT Z$;
4110 IF ASC(Z$'=R+64 THEN SC=SC+1
412121 IF ASC(ZS'=R+64 THEN PRINT" YES"
413121 IF ASC(Z$'<>R+64 THEN PRINT" NO, "CHR$(R+64'
414121 FOR PAUSE=1 TO 1121121121:NEXT
415121 NEXT G
416121 TT=INT«TIME-TS'/6121)
417121 RETURN
51210121 REM
501121 REM *** SCORE MODULE ***
51212121 REM
51213121 PRINTCHR$(147)
5040 PRINT
51215121 PRINT"YoU SCORED "SC" CORRECT"
51216121 PRINT
507121 PRINT"AND TOOK "TT" SECONDS"
51218121 PRINT
51219121 F'RINT"PRESS SPACE BAR TO GO AGAIN"
75
Programming/or Education on the Commodore 64
READY.
Commentary
Lines 190- 230 contain the control module.
Line 230 loops the program through the instructions and the test for as
many times as is necessary.
In order that the character set can be examined, it is copied from ROM in
the same manner as that used in the last program.
Lines 1000-1150 are responsible for the moving. When you RUN the pro-
gram, you will have to wait for about ten seconds while this is achieved.
The subroutine is the same as the routine in BigL, so refer to that program
for more detailed notes.
Note that this is not a subroutine. If GOSUB 1000 is used in line 190, and
RETURN in line 1150, the program will stop with an error message in line
1150 (that there is a RETURN with no GOSUB). This is because the CLR in
line 1070 resets the stack containing the RETURN addresses.
The routine from line 2000 to line 2170 is also similar to that in BigL, and
is used to print a large version of the selected letter on the screen.
Line 4030 reads the current internal clock time into variable TS, and sets
the score counter, SC, to zero.
Lines 4090 and 4100 check the keyboard for an input, and lines 4110-4130
check this input against the selected letter. If it is correct, the score is incre-
mented and YES printed.
Line 4140 provides a short pause so that the screen can be read.
After ten attempts, line 4160 is used to calculate how many ticks have been
produced by the jiffy clock, and this number is divided by 60 and rounded
off to produce the number of seconds taken.
76
Chapter4 Making Friends with your Keyboard
Lines 5()()()- 5200 contain the score module which simply clears the screen
(in line 5030) and prints the details of the test on the screen.
Masking
In the last program, and in one or two others, you may have found a parti-
cular feature in a line that seemed to make little sense. A typical line might
be
It looks as though it means' POKE a number with the number already there
plus 254'. This is not true, however, as AND is a logical operator, not the
same as +.
Logical operators are fairly easy to understand when they are used to
compare numbers.
to INPUT"A=";A
20 INPUT"B = ";B
30 IF A = 1 AND B = 1 THEN PRINT "YES": GOTO 50
40 PRINT "NO"
50 STOP
A B
0 0 0 ie FALSE
0 1 0 ie FALSE
0 0 ie FALSE
ie TRUE - "YES" printed
This program would print 'YES' if both conditions were true. If either or
both of them were false, it would print 'NO'.
10INPUT"A=";A
20 INPUT"B = ";B
30 IF A= lOR B= 1 THEN PRINT 'YES': GOTO 50
40 PRINT "NO"
50 STOP
77
Programming/or Education on the Commodore 64
OR TRUTH TABLE
A B
0 0 0 ie FALSE
0 1 ie TRUE
0 ie TRUE
ie TRUE
This program would print 'YES' if either of the two conditions were true
and the other were false, or if both of the conditions were true. If both the
conditions were false, then 'NO' would be printed.
When logical operators are used to compare numbers, which they can in
the range - 32768 to 32767, then they compare the way the numbers are
stored in two bytes.
Bytes store numbers using binary digits, ie using only ones and zeros.
DECIMAL BINARY
0 0
1 1
2 10
3 11
4 100
5 101
6 110
7 III
8 1000
If two numbers are compared using AND, the individual bits of each
number are compared one by one, and the results are the same as in the
truth tables above.
Suppose the two numbers are 23 AND 254.23 is 00010111 in binary, and
254 is 11111110. Placing the numbers on top of each other and using AND,
we get:
00010111
11111110
00010110
You will notice, in the result line, the only bit to have altered is the last one
on the right. If the two numbers to be compared are 19 OR 4, the result is:
00010011
00000100
00010111
78
Chapter4 Making Friends with your Keyboard
The technique of masking relies on this effect, to ensure that just one bit of
a number is set to a one or a zero. All the other binary digits remain the
same.
In the examples, it can be seen that, to ensure that the third bit from the
right is set to one, the number should be ORed with 4 (as 100 is 4 in binary).
To alter the fourth bit from the right, the number would have been ORed
with 8 (as 1000 is 8 in binary).
To ensure that the last bit on the right is set to zero, the number should be
ANDed with 255 -I, ie 254. This is because the binary reverse of 1 is 254.
(Zeros instead of ones, and vice versa.)
One is 00000001 and 254 is 11111110. To alter the fourth bit from the
right, the number should be ORed with 255 - 8, ie 247. This is because the
binary reverse of 8 is 247. 8 is 00001000 and 247 is 11110111.
Why all this complexity to achieve such a small thing, you may wonder.
The reason is that, in order to use its memory carefully, several functions in
the 64 are controlled by single bits in a memory location, rather than by the
whole byte. There are several examples of this method being used in the
graphics and sound chips. For instance, location 53269 controls whether
the graphic characters called sprites are turned on. The eight bits of that
location each control one sprite. In a program, you might want to turn one
on and leave the others unaltered. The best way to do this is by ~Ring
location 53269; eg to turn on the first sprite, without affecting the others,
you would enter:
POKE 53269,PEEK(53269)OR 1
POKE 53269,PEEK(53269)AND(255 - I)
79
CHAPTER 5
Story Time
Can a computer be creative? To answer this question would take too long
in discussing the meaning of creativity and the future prospects of artificial
intelligence. At the end, there might not be any firm conclusions. What
would be agreed is that, given sufficient information, computers could
shuffle this information and display it in all possible ways, including some
that might appear creative and original.
For parents and teachers, the problem with children's creativity is often
one of encouraging the child to start writing. Once the initial paragraph has
been written, the material begins to flow more easily.
The first program does not do anything that could not be achieved using
pencil and paper, but it does produce a result in far less time. Various
subjects and locations are held in DATA lines. If the user does not like the
combination selected, the program produces more at random when a key is
pressed.
The READ statement is a very useful feature of the BASIC language.
Instead of entering all the data during the running of a program, it can be
stored in DATA lines, usually placed at the end of the program. When data
is required, the statement READ is used, followed by a numeric or string
variable. When the program is RUN, a pointer moves along the DATA
lines, each time they are called. During the course of the program it is
possible to send this pointer back to the start of the DATA lines by using
the command RESTORE.
Enter this program if you aren't sure about using READ, DATA and
RESTORE.
10 READA
20 READX$
30 READB
40 RESTORE
50 READ C, Y$,D
81
Programming/or Education on the Commodore 64
Data can occupy several lines, and often looks neater in listings presented
in this way. The 64 sees it as one big block of data. Be careful you don't
attempt to READ words into numeric variables, or you will get an error
message.
Story
In the following program, the child is requested to enter adjectives to des-
cribe the subject and the location. On completion, the pro~ram produces
the opening paragraph of a story written around the data that has been
entered.
In terms of program complexity, this does not rank very highly, but it
does show the way in which apparently original text can be generated. It
also requires a lot of thought on the part of the child to enter suitable
descriptions that fit the mood of the opening sentence.
82
Chapter 5 Story Time
83
Programming/or Education on the Commodore 64
READY.
Commentary
Lines 1040 to 1060 contain the control module. Line 1060 loops the pro-
gram back to the start for a new story.
Lines 3000 to 3990 choose words at random. Line 3040 chooses an intro-
duction from the first five phrases held in data. Line 3080 misses the first
five items of data and chooses a character at random from the next 20
items. Line 3120 misses the first 25 items of data and chooses a place at
random from the last 20 items.
Lines 4000 to 4200 print the chosen introduction and request the input of
suitable adjectives to describe the character and the place.
84
Chapter 5 Story Time
Line 4220 onwards prints a framework of text in which the adjectives are
combined to make the first paragraph of a story.
Lines 9000 onwards contain the data lines. The data may be changed pro-
vided the number of items in each section remains the same.
Gosh
After the last program, the time has come for a serious program to demon-
strate the potential of the computer for creating original masterpieces.
Unfortunately, nothing of such high calibre was available!
We could attempt to disguise this program in educational language, to
make it seem highly motivating and wonderful at increasing cognitive
skills. When it comes down to it, however, it's really just a lot of fun.
Gosh is a computerised version of Consequences, and expects inputs of
people, sayings, places and results. It contains some items in data, and
what it lacks in educational terms should be made up for by the amusement
it causes.
85
Programming/or Education on the Commodore 64
1230 HEM
1240 REM MALE NAMES
1250 PF:INT "[SHIFT ICLR/HOMEJ"
1260 X = 7 : Y = 5 : GOSUB 2470
1270 F'R INT "TYPE IN FIVE BOY' S NAt·1ES"
1280 FOR I = 1 TO 5
1290 Y = 5 + I * 2 : GOSUB 2470
1.3(2)(2) GOSLJB 2520
1310 MS( 1 ) - AS
1320 NEXT I
1330 FOR 1 = 6 TO 15
1340 READ AS M$( I = AS
1.350 NEXT I
1360 RETURN
1370 REM
1380 REM FEMALE NAMES
1390 PRINT ""
1400 Y = 5 : GOSUS 2470
1410 PRINT "TYPE 11\1 FIVE GIF:L.· S NAMES"
1420 FOR I = 1 TO 5
1430 Y = 5 + I * 2 : GOSUB 2470
1440 GOSUB 2520
1450 FS( I = AS
1460 NEXT I
1470 FOR I = 6 TO 15
1480 READ AS FS( I
1490 NEXT I
1500 RETURN
1510 REI"1
1520 REI'1 PLACES
15:::;'({) PRINT "[SHIFT ICLR/H0I'1EJ"
1540 Y = 5 : GOSUS 2470
1550 PRINT "TYPE IN FIVE PLACES"
1560 FOR I = 1 TO 5
1570 Y = 5 + I * 2 : GOSUS 2470
1580 GOSUB 2520
1590 PS( I ) = AS
1612H2) NEXT I
1610 FOR I = 6 TO 15
1620 READ AS PS( I = AS
1630 NEXT I
1640 RETURN
1650 REM
1660 REM HIS SPEECH
86
Chapter 5 Story Time
87
Programmingfor Education on the Commodore 64
88
Chapter 5 Story Time
::570 INPUT Al
2:"58(2) IF A$== THEN 25:~0
II II
89
Programming/or Education on the Commodore 64
2990 REl'l
3000 REM DATA FOR REPLY
3010 DATA DON'T BE SO IMFERTINENT
3020 DATA THAT IS NO CONCERN OF MINE
3030 DATA YOU'RE STANDING ON MY FOOT
3040 DATA HUH. I'VE HEARD THAT BEFORE
3050 DATA SIT DOWN. YOU LOOK ILL
3060 DATA PLEASE CARRY MY LUGGAGE
3070 DATA WOWIE' THAT'S FANTASTIC
3080 DATA PLEASE GO AWAY IMMEDIATELY
3090 DATA DANKE SEHR GUT. UNO IHNEN?
3100 DATA J KNEW YOU WOULD SAY THAT
::::110 REI"1
3120 REM DATA FOR CONSEQUENCE
3130 DATA THE SUN WENT SUPERNOVA
3140 DATA A TIDAL WAVE ENGULFED THEM
3150 DATA IT BEGAN TO SNOW
3160 DATA THEY PLAYED HIDE AND SEEK
3170 DATA HE BLUSHED BRIGHT SCARLET
3180 DATA THEY BOTH SULKED
3190 DATA THE POLICE ASKED THEM TO GO
3200 DATA SHE PUSHED HIM OFF HIS BIKE
3210 DATA HE DROPPED HIS CRICKET BAT
3220 DATA HE JOINED THE FOREIGN LEGION
READY.
Commentary
The structure of Gosh is made fairly clear by the REM statements in the
control module between lines 1020-1110.
Lines 1140-1220 form the initialisation routine. Six arrays are set up. M$
holds fifteen male names, F$ fifteen female names, and P$ fifteen places
where the M$ and F$ array elements may happen to meet, etc. S$ is his
speech, R$ her reply and C$ the consequence which happens after their
exchange. The routine sets a white screen and selects blue text.
The array of male names is filled by the routine between lines 1240-1360.
Ten of these names are taken from the lines of DATA, the other five being
chosen by the child using the program. The child's choices are entered first
into the array by the FOR ... NEXT loop between lines 1280-1320. At line
1300, another subroutine, between lines 2510- 2600, is called to check the
length of the child's input. Gosh in operation does tend to encourage ima-
90
Chapter 5 Story Time
The remaining five arrays are filled in exactly the same way by the routines
between lines 1380- 2060.
91
CHAPTER 6
Logically Speaking
Although the majority of the programs in the book so far have been con-
cerned with teaching specific skills, many of them entail some form of
logical reasoning before success can be achieved. This is the case with short
programs such as Number, where, unless a logical strategy is worked out,
correct answers can take a long time to be reached.
Piaget was one of the first psychologists to consider child development
as proceeding through a series of stages. It is fair to say that his work was
taken too literally by some educationists in the 1950s and 196Os, with the
stages being seen as rigid plateaux that children reached. It was considered
that no child of six or seven was capable of formal logical thought; partly
because they were self-centred and therefore unable to see things from the
point of view of others. More recent studies have shown that, if the ques-
tions are phrased in terms that children can understand, they are quite able
on certain occasions to act logically.
Yet again, it is clear that many adults find it easier to understand some
processes when offered models or pictures rather than the ambiguous sym-
bolic jungle of words.
Until recently, logic has been a neglected area in schools, although it is
implicit in most other subjects. Using coloured attribute blocks can demon-
strate logic problems to young children, and many guessing games encou-
rage logical thinking in the players.
In this chapter, we have included two programs that involve solving
particular problems. They can be used individually, but we have found that
a group of three or four children using the program at the same time will be
more beneficial. The reason is that the programs stimulate discussion and a
pooling of ideas.
As in many subjects, there is no one right answer to solving the prob-
lems, simply several strategies that may be tried in different situations.
93
Programming/or Education on the Commodore 64
Treasure
The first program, Treasure, displays an island covered by a grid of
squares. Under one of them is buried some treasure. X and Y coordinates
are explained in the instructions and using the program reinforces basic
graphical ideas: 0,0 is the origin at the bottom lefthand corner, and the X
coordinate is entered first. On entering the first pair, the location is shown
on the screen, and the numbers chosen and their distance from the treasure
is displayed on the right of the screen. Each attempt reduces the size of the
treasure, and after 20 unsuccessful attempts the true position is shown.
The way to discover the distance from the guess to the treasure is to use
Pythagoras' theorem. It is easy to calculate the horizontal and vertical
distances from the treasure, so these form two sides of a right-angled tri-
angle. The distance in a straight line forms the long side or hypotenuse, and
this distance is the square root of the sum of the squares of the other two
sides.
or 81), SQR to produce square roots, ABS to produce the absolute value of
numbers, and SIN, COS, and TAN for trigonometric use. In this program,
it is necessary to use the absolute value for the distances to avoid negative
numbers.
For older children, the program could be adapted to demonstrate three-
dimensional coordinates. The third input would be the depth of the
treasure - this has proved rather difficult to solve quickly, as there are
more than 3000 possible locations!
94
Chapter 6 Logically Speaking
95
Programming/or Education on the Commodore 64
2721ZJ RETURN
31ZJ1ZJ1ZJ REM
31ZJ11ZJ REM *** INSTRUCTIONS ***
31ZJ21ZJ REl'l
31ZJ31ZJ PRINTCHR$(147)
31ZJ41ZJ PRINT" YOU WILL SOON SEE A PLAN OF AN ISLAND"
31ZJ51ZJ PRINT
31ZJ61ZJ PRINT"WHERE A PIRATE HAS BURIED HIS TREASUF:E."
31ZJ71ZJ PRINT
31ZJ81ZJ PRINT"TO FIND HIS TREASURE YOU CAN ENTER THE"
31ZJ91ZJ PRINT
311ZJ1ZJ PRINT"COORDINATES OF WHERE YOU THINK IT IS. "
3111ZJ PRINT
3121ZJ PF:INT"YOU WILL BE TOLD HOW FAR AWAY YOU ARE"
3131ZJ· PRINT
3141ZJ PRINT"BUT NOT THE DIRECTION. UNFORTUNATELY,"
3151ZJ PRINT
3161ZJ PRINT"EACH GUESS COSTS YOU SOME TREASURE."
3171ZJ PRINT
3181ZJ PR I NT" REl'lEMBER THAT THE FIRST COORD I NATE (X)"
3191ZJ PRINT
321ZJ1ZJ PRINT"COUNTS ACROSS, THE SECOND (Y), COUNTS"
3211Zl PRII\IT
3221Zl PR I NT" UPWARDS. GOOD LUCf<!"
3231Zl PRINT:PRINT
324121 PRINT"PRESS THE SPACE BAR TO BEGIN"
3251Zl GET Z$:IF Z$="" THEN 3251Zl
3261Zl RETUF:N
35(2)1Zl REM
3511ZJ REM *** RESULTS ***
3521Zl REl'l
3531Zl X=1:Y=21:GOSUB41Zl1ZJ1Zl
:3541Zl IF WIN=1Zl THEN PRINT"THE PIRATE COULDN'T WAIT"
356121 X=A+6:Y=18-B:GOSUB41Zl1Zl1Zl
:3571Zl PRINT"X"
358121 X=1:Y=22:GOSUB41211Zl1Zl
:5591Zl IF WIN=1 THEN PRINT"WELL DONE, YOU WIN" INT
(lIZlIZlIZl/TRIES) "DIAMONDS"
3595 PRINT" THE TREASURE WAS AT"A;B
361Zl1Zl PRINT" PRESS SPACE BAR TO GO AGAIN";
3611Zl GETZ$:IF Z$=""THEN3611Zl
41Zl1Zl1Zl REM
41Zl1121 REM *** 'PRINT AT' ROUTINE ***
41Zl21ZJ REM
41ZJ31Zl POKE782,X:POKE781,Y:SYS65521Zl:RETURN
READY.
96
Chapter 6 Logically Speaking
Commentary
Lines 1040-1090 contain the control module.
Lines 1510-1700 draw the island. Line 1530 sets the background colour to
blue, and line 1540 clears the screen and sets the printing colour to yellow.
The island is drawn by two nested loops, Nand P. The position of where
CHR$(l66) is plotted is determined by the 'print at' routine held at line
4030.
Line 1630 draws the X coordinates, while the Y coordinates are printed
in line 1570 by the plotting loop.
The initialisation routine in lines 2000- 2070 chooses the values of A and
B, where the treasure is buried. It also sets the number of attempts, TRIES,
and the win flag, WIN, to zero.
Lines 2500-2720 contain the main game loop. This makes extensive use of
the 'print at' routine to ensure that the plotting of points and input does not
interfere with the display. The more traditional method would have been to
POKE the screen memory directly, but this does not show so clearly what is
happening.
Lines 2570, 2580, 2600 and 2610 check the ASCII values of the guesses,
and reject those inputs that are not numbers, and those values that would
not plot on the island (less than zero, and more than 15).
Lines 2620 and 2630 assign the guesses to variables X 1 and Y 1.
Line 2640 calculates the distance the guesses are from the treasure. Note
that the sign after the figure two is an up arrow, signifying that the value
A
Lines 3500- 361 0 contain the results subroutine. Lines 3560 and 3570 print
an X where the treasure was buried. Line 3590 calculates the number of
diamonds left, by dividing it between the number of attempts.
Line 4030 sets the X and Y points of the print position, by initiating a
system call to 65520.
97
Programming/or Education on the Commodore 64
Sonar
The last program showed how an elementary idea can be developed into a
game that teaches strategy. Watching children of different ages play it is an
interesting experience, as different methods of solving the problem are
tried. This is the sort of game where several children using the program at
the same time can stimulate each other into useful discussion.
The next program is similar in concept, in that there is a grid of squares,
with something hidden in it. The last program offered only distance as a
clue to the position, but the next gives a compass clue as well. The program
could be modified to give different clues, such as warm/cold, or the
direction could be shown as an angle.
Programming points to note are the use of sprites and sound. There are
notes after the program to explain these further.
Sound and graphics are two particular features of the 64, but neither of
them is particularly easy to use. To do justice to either topic would take up
a whole separate book. If you want to use sprites in your own programs,
then try adapting ours, and seeing how you can move them round the
screen. To generate them, we cannot do better than recommend a program
in David Lawrence's book, also from Sunshine Books, The Working Com-
modore64.
Now, close the hatches and prepare to dive!
98
Chapter 6 Logically Speaking
1370 NEXT I
1380 FOR I = 0 TO 880 STEP 40
1390 FOR J = 0 TO 24 STEP 24
1400 POKE 55336 + I + J, (2)
1410 POKE 1064 + I + J, 160
:l.l~20 NEXT ,J
1.430 NEXT I
1440 FOR I = ~ TO 22
1.45~ FOR J = 0 TO 8801 STEP 40
1460 POVE 55337 + I + J. 7
1470 POKE 1065 + I + J, 76
1480 NEXT ,J
l/t9~ NEXT I
:1.500 REM CENTRE SIGHTS ON GRID
1510 XS = 101 : VB = 129
:1.520 POKE VC, XS : POKE VC + 1, VS
1530 POKE VC + 21, 1
154lZl RETURN
15~:i!2l PEt1
156lZl REM CONTROLS
157lZl PRINT CHR$( 144 )
1580 X = 27 : V = 0 : BOSUS 2450
1590 PRINT "<:< SONAR »"
160lZl X = 29 : V = 2 : GOSUS 245lZl
1610 PRINT"t'lISSION:"
162lZl PRINT CHRS( 30 )
16~0 X ~ 27 : V = 4 : GOSUS 2450
99
Programming/or Education on the Commodore 64
100
Chapter 6 Logically Speaking
I F X:::; '..;.
170 THEN XS - 17m
;:'09~~J I r'_. Kl _... "a
THEN YS II YS-·
:~~ 1 ~.:l0 J. F V$ -- "L.." THEN Y~'; --. 'ff.-:) + 1
2110. 'rJ. F if:: 59 THEN YS = 59
.;.
101
Programming/or Education on the Commodore 64
2520 REM
2530 REM REWARD ROUTINE
254~ POKE 53280, 3
255~ POKE 53281, 3
256~ PRINT "[SHIFT ICLR/Hm1EJ"
2570 REM SWITCH OFF SPRITE
2580 POKE VC + 21. m
2590 REM DRAW SEA
2612)~ C == 6
2610 FOR I == ~ TO 160 STEP 40
2620 FOR J == 0 TO 39
2630 L = 1824 + I + J
2640 GOSUB 2810
2650 NEXT ,J
2660 NEXT I
2670 REM DRAW SUBMARINE
2680 C ;:: '7
2690 FOR L = 1794 TO 1814
2700 GOSUB 2810
2710 NEXT L.
2720 FOR I = 0 TO 80 STEP 40
27312) FOR J = 12) TO 4
2740 L = 1683 + I + J
2'750 GOSUB 2810
2760 NEXT ~1
2770 NEXT I
2780 RETURN
2790 RH1
2800 REM PL.OT CHARACTER SPACE
2810 POKE L + 54272, C : POKE L, 160
2820 RETlJRN
28::::;(2) REt·l
2840 REM DATA FOR SONAR SIGHTS
2850 REM
2860 DATA 0, 126, 0, 1, 153, 128, 2. 24
2870 DATA 64, 4, 24, 32, 10, 24, 80, 17
2880 DATA 24, 136, 16, 153. 8, 32, 90
2890 DATA 4, 32. 60? 4, 63, 231, 252
29(2)0 DATA 63, 231, 252, 32, 6(2), 4, 32
2910 DATA 9(2), 4, 16, 153, 8, 17, 24
2920 DATA 136, 1(2), 24, 80, 4, 24, 32
2930 DATA 2, 24, 64, 1, 153, 128, 0
2940 DATA 126, 0, 0, (2), 0
READY.
102
Chapter 6 Logically Speaking
Commentary
Sonar is controlled by lines 1020-1060. First the sprite representing the
sights on the sonar screen is defined. Then line 1030 calls the routine which
places the sonar screen on the computer's monitor. This is followed by a
routine which fills the righthand side of the screen with a set of control
instructions and prompts, including the direction to steer in, the distance
of a lost submarine and the time taken so far in the search. Line 1050 calls
the routine which actually allows the sonar scan to take place and finally
line 1060 summons the reward routine, the submarine resurfacing after its
discovery.
Lines 1090- 1250 define sprite 0 as the sonar sight. Line 1110 initialises VC
as the starting location of the 6567 video chip, and all subsequent sprite
control is done with reference to this location. Line 1140 sets the sprite
pointer for sprite 0 with POKE 2040, 13 and then the FOR ... NEXT loop
from 1160 to 1180 reads all the necessary DATA to define the sprite.
Diagram E
103
Programming/or Education on the Commodore 64
The diagram shows how the sonar sight has been constructed on an array
of 21 by 24 squares. Remember that the sprite is coded as a series of hori-
zontal blocks of eight squares. Each is regarded as a binary number. A
filled square gives a I and an empty square a O. For example, the fifth block
of eight squares starting from the top lefthand corner, which is therefore
the block of eight in the middle of the second row, gives the binary number
lOOllOOl. This creates the base lOequivalentof(l28 + 16 + 8 + l)or 153.
This number, 153, is therefore the fifth number in the DATA line 2860.
Checking the values for other blocks of eight squares in the diagram will
help to give confidence in developing Commodore sprite graphics, which
are one of the most useful features of the machine.
One advantage of sprite graphics is the easy way in which they can be
moved over a background display without ruining it. This is much harder
on other machines. The feature is used in Sonar in the way the sonar sight
travels happily around the screen until the submarine is located. To give
added effect, the sprite is enlarged in both horizontal and vertical direct-
ions at lines 1200, 1220 by POKEing the locations VC + 29 and VC + 23
with the sprite number, which in this case, for sprite 0, is l. Line 1240
colours the sprite black by POKEing 0 to location VC + 39, the colour
location for sprite O.
Lines 1270-1540 generate the sonar screen, over which the child has to
steer the sight to locate the submarine. The two pairs of nested FOR ...
NEXT loops between lines 1320-1370 and 1380-1430draw the perimeter
of the screen by POKEing character 160 to locations determined by the
range of the I and J variables and by the way in which they are STEPped.
Colour 0 is POKEd to the corresponding locations of the colour map to
give a black outline to the coordinate grid. The squares themselves are
produced by POKEing character 76 to all the screen locations in the area
enclosed. These values are again derived from the two loop variables, I and
J. This time, colour 7 is chosen, at line 1460. Line 1520 locates the sonar
sight on the screen by POKEing the values XS and YS to the locations VC
and VC + I. The initial values of XS and YS are given at line 1510 but are
subsequently updated as the child types in appropriate directions. Finally,
line 1530 switches on sprite 0 by POKEing VC + 21.
The instructions given to the child are produced by the routine between
lines 1560-1920. All the text is printed on the right of the sonar screen.
Extensive use is made of GOSUB 2450 to arrange the text neatly in the
confined areas involved. Clarity is aided by switching frequently from
black to green text using PRINT CHR$(144) and PRINT CHR$(30). (This
has to be done before GOSUB 2450 or else the new screen location is lost.)
The information on the screen is also carefully arranged to match the mes-
sages printed on the screen and continuously updated by the following
104
Chapter 6 Logically Speaking
routine. Finally TM, which times the search, is initialised at line 1910 by
equating it with TI, the elapsed time since the machine was switched on.
Lines 1940- 2420 allow the sonar sight to be moved around the screen. Line
1960 sets the auto-repeat with POKE 650, 128. This is necessary to prevent
the child constantly having to depress the control keys, A, D, J and L. The
coordinates of the lost submarine are decided at lines 1980 and 1990, the
following line preventing the submarine being found immediately. Here a
further subroutine, lines 2490-2510, is used to calculate the submarine's
distance and to jump back to line 1980 should it be too close. Lines
2040-2120 read the keyboard and adjust the sprite coordinates, XS and
YS. The sprite is moved by lines 2140 and 2150.
Two pieces of information are PRINTed on the screen to aid location of
the submarine. Lines 2200-2230 use a simple arithmetic test to PRINT
'North', 'East', etc., on the screen. By placing the test for North and South
before the test for East and West, and by putting a semicolon after the two
strings, the further combination 'North East' etc., is automatically created
when necessary. Line 2250 uses GOSUB 2500 to determine the submarine's
distance and line 2270 jumps out of the GOTO loop created by line 2410 if
the submarine has been located. Meanwhile, a sound effect is being
generated by lines 2340-2400. The pitch of the note is related to the dis-
tance of the submarine by adjusting the high note POKEd at line 2370 by
subtracting S.
105
CHAPTER 7
The Real Thing
107
Programming/or Education on the Commodore 64
an operation should bring home very clearly one point: computer simu-
lations let you have nearly anything sitting in a cassette next to the
computer.
Lock
Lock allows the child to steer a boat up and down a canal. The gates and
sluices work in the correct sequence and the water level changes, too. This
program uses many of the techniques used in earlier chapters, especially
those involved in defining and moving sprites across the screen.
108
Chapter 7 The Real Thing
109
Programming/or Education on the Commodore 64
110
Chapter 7 The Real Thing
III
Programming/or Education on the Commodore 64
Il2
Chapter 7 The Real Thing
113
PrOKramminKjor Education on the Commodore 64
114
Chapter 7 The Real Thing
READY.
115
Programming/or Education on the Commodore 64
Commentary
The control module for Lock lies between lines 1020- 1070.
The first subroutine called by the control module defines two sprites. The
DATA for sprite 0 is READ by the loop between 1170-1190. This sprite
represents a boat facing up-river and initially on the lower section of the
river. (It is therefore referred to in the REMs as 'Iowboat'.) The diagram of
the 21 x 24 grid shows how lowboat is constructed. For example, the top of
the flag, the first horizontal block of eight squares, is the binary number
10000 or 16 in base ten (our normal counting system). Checking line 4130
shows that the first number of DATA forspriteOis, indeed, 16. The DATA
for sprite 1 is READ by the loop at lines 1240-1260. This defines highboat,
a mirror image of lowboat, which at first appears on the upper section of
the river and faces downstream. Both sprites are enlarged horizontally at
line 1280 by POKEing VC + 29 with 3, the sum of the sprite numbers: 1 for
sprite 0, and 2 for sprite 1. Both are coloured white at 1300 and 1310.
Diagram F
116
Chapter 7 The Real Thing
The display is set up by lines 1340-1770. It shows a green hillside and a blue
river or canal in two sections, upper and lower, separated by the pair of
lock gates. The display is built up with constant calls on a subroutine, lines
2480-2500, which fills in specified screen locations, L, with a chosen
colour, C, as in earlier programs. For example, the hillside is constructed
by lines 1420-1530. The subroutine is called by GOSUB 2490 at line 1480.
The value of L is derived from the way in which the I and J loop variables
are changing. This by itself would create the slope as a series of stepped
bars, but the end of each bar is smoothed out by POKE L + 1, 105 at line
1520.
Similarly, the lower section of the river is constructed by the nested loops
between lines 1560-1610 and the upper river by 1630-1680. The lock is
superimposed on the river by drawing both lock gates in the closed posi-
tion. There are four separate routines for opening and closing the lower
and upper gates, between lines 1840-2100, and the two closing routines
are called by GOSUB 1850 at line 1710 and GOSUB 1920 at line 1720. Note
how the flag, F, is set equal to 1 at line 1700. This is because in the initial
screen display the lock appears filled. F = 1 corresponds to a filled lock:
F = 0 means that the lock has been drained to the lower water level. It is
essential to have this representation of the status of the lock so that, when
the boat is subsequently steered up and down the river, neither lock gate is
ever opened to release a flood of water.
The screen display routine is followed by the PRINT TAB routine,
needed for neat formatting of the screen prompts, and by the four lock gate
routines already mentioned. Then follows a lock draining routine from
lines 2120- 2280. This simply changes the colour of location 56190 of the
colour map to blue, at line 2140, to simulate a sluice opening in the lower
gate. Similarly, the colour locations for the water in the lock are changed to
green, by the instruction POKE 55751 + I + J, in the two nested loops from
lines 2170- 2220. Finally, line 2270 sets the flag F to O. A very similar
routine for filling the lock then follows at lines 2300-2460.
A short routine between lines 2560- 2760 allows the child to choose
whether a boat travels up or down through the lock. It is fully error-
trapped and conveniently placed by calls on the PRINT TAB routine on
the hillside above the lock. Two long routines then follow. Lines
2780- 2280 steer the boat up-river and lines 3400-4000 steer it down-river.
The two routines are identical in structure and both make many calls upon
the routines already set up. Animation is achieved in two principal ways,
by moving the two sprites by POKEing values to the relevant locations
defined with respect to VC and by using the earlier subroutines to change
colours of different parts of the screen. Both techniques can be used to
produce animation in Commodore 64 programs. The two routines are
117
Programming/or Education on the Commodore 64
fully explained by the REMs they contain and should not be too difficult to
understand.
Power
The second program, Power, continues the same theme of moving water.
Here, however, the scene depicts a pumped storage electricity scheme with
an upper and lower reservoir of water. Pipes connect the power station to
each and a high tension line leads away off-screen.
Initially it is simply an idyllic scene taken from the Welsh countryside.
The effect of rotation in the wheel is achieved by plotting three different
sprites on top of each other, and turning them on and off in sequence.
Electricity can actually be seen racing along the power line, either towards
the station or away from it depending upon whether it is pumping water or
generating electricity.
118
Chapter 7 The Real Thing
119
Programmingfor F:ducation on the Commodore 64
2l,;)60 NEXT I
2070 FOR I = 0 TO 240 STEP 40
2080 FOR J = 0 TO 39
::::090 L.. ::-: 174·l + I .!- J
21 ~)0 GOSUB 2560
2:1. H"! NEXT ,]
212~1 NEXT 1
2130 REM POWER STATION
120
Chapter 7 The Real Thing
121
Programming/or Education on the Commodore 64
258~~ REM
259~ REM GENERATE
260~ REM CYAN SKY
2610 POKE 53281. 3
2620 GOSUE 3:::'::::~ : PRINT "DAY "
2630 REM S~LECT DIRECTION TO ROTATE
2640 Dl = 4 : D2 = 1
L650 El = 0 : E2 = 2
2660 FOR I = 0 TO 120 STEP 40
2670 FOR J =- ~ TO 9
2680 REM DRAIN UPPER LAKE
2690 C = 12 : REM SELECT GREY 2
2700 L = 1186 + I + J
2710 GOSUB 2560
2720 REM FILL LOWER LAKE
2730 C =- 6 : REM SELECT BLUE
2740 L = 1892 - I + J
2750 GOSUB 2560
2760 NEXT ,J
2770 REM ROTATE TURBINE
2780 GOSUS 3060
2790 NEXT I
2800 P = 10 : GOSUB 3370 F:ETURN
2810 REM
2820 REM STORE
2830 REM BLACK SKY
2840 POKE 53281, 0
2850 GOSUB T32!t) : F'F.:INT "NIGHT"
286~ REM SELECT DIRECTION TO ROTATE
2870 D1 = 1 : D2 = 4
2880 E1 = 2 : E2 = 0
2890 FOR I = 0 TO 120 STEP 40
2900 REM ROTATE TURBINE
2910 GOSUB 30~J0
2920 FOR J = 0 TO 9
2930 REM DRAIN LOWER LAKE
2940 C = 12 : REM SELECT GREY 2
2950 l = 1772 + I + J
2960 GOSUB 2560
297~ REM FILL UPPER LAKE
298~ C = 6 : REM SELECT BLUE
2990 L = 1306 - I + J
30(2)(7.) GOSUS 2~i6~
3~10 NEXT J
122
Chapter 7 The Real Thing
3'-1)20 NEXT I
3030 P ::::: 1 (lJ : G[)StiB ~;370 RETURN
~::'Q)4it1 FEI'l
3050 REM ROTATE TURBINE
:3"16"1 r.:· =:: 1
3070 REM D1 AND D? DETERMINE ROTATION
308Q) FOR TW = 1 TO 3
3G90 POKE VC + 21. D1
3100 E = El : GOSUS 3220
3110 POKE VC + 21. 0
3120 POKE VC + 21, 2
3130 E = 1 : BOGUB 3220
3140 POKE VC + 21, 0
3150 POKE VC + 21. D2
316Q) E = E2 : GOSUS 3220
3170 t-.lEXT n~
::::'180 RETUFN
319(::,:1 REt-l
3200 REM ELECTRICITY
3210 REM E DETERMINES CURRENT DIRECTION
3220 FOR EL = 56070 TO 56056 STEP -3
3230 POKE EL - E, 2
::::'240 NEXT EL.
3250 GOSUB 3370 : REM PAUSE
3260 FOR EL = 56070 TO 56056 STEP -3
3270 POKE EL - E. 7
:328el t"EXT EL.
3290 RETURN
3300 REM
3310 REM PRINT TAB ROUTINE
3320 POKE 782, X : POKE 781. Y
3330 SYS 65520
3340 RETURN
335(2) Rf.:~,..,.t
3~::'60 REM PAUSE
3370 FOR T = 1 TO P * 200 r~EXT T
3::::'8"1 RETURN
3390 REt'1
3400 REM DATA FOR TURBINE WHEEL
REM
::::'410
REt-I SFR I TE 1
3'1-20
3430 DATA 0, 128, 0, 0, 192, 0, 0, 192
3440 DATA 0, 0. 96, 0, 0. 96, 0, 0, 96
3450 DATA 0, Q), 48, 28, 0, 48, 248, 0
123
Programmingfor Education on the Commodore 64
Commentary
Power is controlled by lines 1020-1060. The routine called by line 1020
defines the three sprites needed for the animation of the turbine wheel in
the power station. The next routine called is simply a screen of text,
explaining the purpose of the computer simulation and giving a little
information about pumped power schemes. Then line 1040 calls the
routine which sets up the display. After that, the two routines, 'Generate'
and 'Store' , cycle indefinitely, the first representing the generation of elec-
tricity during the day and the second the storing of energy at night by
pumping water back up to the higher reservoir.
124
Chapter 7 The Real Thing
Diagram G
~
I-
I-
r-
125
Programmingfor Education on the Commodore 64
Diagram H
f--
-
f--
r-
r-
-
126
Chapler 7 The Real Thing
Diagram I
r-
r-
BR
127
Programming/or Education on the Commodore 64
The screen display is built up by the routine between lines 1910- 2530.
GOSUB 2560 is used frequently to call the subroutine between lines
2550- 2570 to colour in specified screen locations. Lines 1980- 2120 pro-
duce a grey hillside and lines 2140- 2200 a white power station, which coin-
cides with the position of the turbine wheel's sprites on the screen. The
upper reservoir is drawn by lines 2220-2280 and the lower by lines
2430- 2450. Other FOR ... NEXT loops with suitable ranges plot the pipes
connecting the power station to the reservoirs and also, in yellow rather
than blue, the electricity 'cable' .
128
Chapter 7 The Real Thing
Lines 2820- 3030 form an identically structured routine in which water and
electricity both flow in the opposite direction to simulate the energy being
stored at night in the upper reservoir.
Coin
The final two simulations are in elementary statistics. Coin allows the child
to drop up to 25 coins and see what fraction is heads. An animated hand
and coin are shown together with a block graph of results which is conti-
nuously updated. The limiting value of the fraction is clearly shown by the
graph plotted.
There would be little point in using this simulation unless children
already had experience of coin-tossing experiments. However, once they
had a grasp of the basic concepts involved, the program could be used to
great effect. Its endless repetition, crunching of difficult numbers and dis-
play of the approaching limit of 0.5, would all help towards an appreci-
ation of probability as a real mathematical concept.
129
Programming/or Education on the Commodore 64
1270 FOR I = 21 TO 44
1280 POKE 896 + I, 255
129Q) NEXT I
13Q)Q) FOR I = 45 TO 62
1310 READ N : POKE 896 + I, N
1320 NEXT I
1330 REM HAND, SPRITE 2
1340 REM SET POINTER FOR SPRITE 2
1350 pm:::E 2042, 15
....,
1360 REM READ DATA FOR SPRITE "'-
1370 FOR I = Q) TO 62
1380 READ N : POKE 960 + I , N
1390 NEXT I
14Q)Q) REl'l ENLARGE SPRITES IN X DIRECTION
1410 pm:::E VC + 29, 6
142Q) REM ENLARGE SPRITES IN Y DIRECTION
1430 POKE VC + 23, 6
144Q) REM SELECT COLOUR
1450 POKE VC + 39, 0
1460 POKE VC + 40, 8
147~ POKE VC + 41, 8
1480 RETURN
149Q) REM
15Q)Q) REM SET UP DISPLAY
1510 REM CYAN SCREEN
1520 POKE 53280, 3 : POKE 53281, 3
1530 PRINT "[SHIFT/CLR/HOME]" : PRINT CHR$( 144 )
1540 REM LOCATE HAND ON SCREEN
1550 POKE VC + 2, 30 POKE VC + 3, 55
1560 POKE VC + 4, 78 : POKE VC + 5, 55
1570 REM DRAW GRAPH
1580 REM AXES
1590 FOR I = 1118 TO 1918 STEP 40
1600 POKE I + 54272, 1 : POKE I, 160
1610 NEXT I
1620 FOR I = 1919 TO 1943
1630 POKE I + 54272, 1 : POKE I, 160
1640 NEXT I
1650 REM COORDINATE SQUARES
1660 FOR I = 0 TO 760 STEP 40
1670 FOR J = 0 TO 24
1680 POKE 55391 + I + J, 1
1690 POKE 1119 + I + J, 80
1700 NEXT J
1710 NEXT I
1720 REM PRINT TITLE
1730 X = 13 : Y = 2 GOSUB 2280
1740 PRINT "1"
1750 Y = 22 : GOSUB 2280
130
Chapter 7 The Real Thing
131
Programming/or Education on the Commodore 64
225(21 RETURN
2260 REM
2270 REM PRINT TAB ROUTINE
2280 POKE 782, X : POKE 781, Y
2290 SYS 65520
2300 RETURN
2310 REM
2320 REM PAUSE
2330 FOR T = 1 TO 1000 NEXT T
2340 RETURN
2350 REM
236(21 REM
2370 REM DATA FOR COIN, SPRITE 121
2380 REM
2390 DATA 63, 128, (2), 255
2400 DATA 224, 3, 255, 248. 3, 255, 248
2410 DATA 7, 0, 28, 7, 63, 156, 15, 32
2420 DATA 158 , 15, (2), 158, 31. 0. 159
2430 DATA 31, 7, 159, 31, 4, 31, 15, 4
2440 DATA 3(2), 15, (2), 3(21, 7, 4, 28, 7, 0
2450 DATA 28, 3, 255, 248, 3, 255, 248
2460 DATA 0, 255, 224, (2), 63, 128, (2)
2470 DATA 14, (2)
2480 REM
2490 REM DATA FOR HAND, SPRITE 1
2500 REM
2510 DATA 0, 0, 0, 0, (2), 0, 121, (2), I, (2)
2520 DATA ~, 3, ~, 0, 3, 255, 224, 7
2530 DATA 255, 255, 31, 255, 255, 207
254(21 DATA 255, 252, 15, 0, 0, 7, (2), (2)
2550 DATA 1, (2), (2), (2), 0, (2), (2)
256(21 REM
2570 REM DATA FOR HAND, SPRITE 2
2580 REM
2590 DATA 31, 192, (2), 127, 192, (2), 255
2600 DATA (2), 248, 24(2), 15, 252, 224, 63
2610 DATA 248, 255, 255, (2), 255, 240, (2)
2620 DATA 255, 255, 254, 255, 255, 255
2630 DATA 255, 255, 254, 255, 252, (2)
264(21 DATA 255, 240, 0, 255, 255, 252
2650 DATA 255, 255, 254, 255, 255, 252
266121 DATA 255, 224, 0, 255, 255, 24(2)
267(2) DATA 255, 255, 248, 255, 255, 24(2)
268(2) DATA 127, 255, 24(2), 63, 128, (2)
READY.
132
Chapter 7 The Real Thing
Commentary
Coin is controlled by lines 1020-1070. Line 1020 calls the routine which
defines three sprites, one for the coin being tossed and the other two to
produce the hand which tosses it. Line 1030 sets up the screen display and
finally the FOR ... NEXT loop from 1040 to 1070 tosses twenty-five coins
in turn, and draws a block graph of the result.
Diagram J
Lines 1100-1480 define the three sprites. Sprite 0 is the coin shown in the
diagram. There is a question mark in the middle of the coin to indicate that
as it falls the outcome of the result is in doubt. Sprites 1 and 2 define a hand
and these are both enlarged by POKE VC + 29,6 and POKE VC + 23,6 at
lines 1410 and 1430. The coin is left unenlarged for contrast.
The screen display is set up by lines 1500- 1850. A cyan screen is created by
1520. The two FOR ... NEXT loops from 1590-1610 and 1620-1710 add
the coordinate squares by POKEing character 80 to the screen. Lines
1730-1780 calibrate and title the graph. At line 1840, the variables Hand
N are initialised: H records the total number of heads thrown at any stage
of the program's execution and N is the total number of throws.
133
Programming/or Education on the Commodore 64
Lines 1870-1990 animate the fall of the coin. Line 1890 switches on the
hand. After a pause, line 1920 switches on the coin. Then the FOR ...
NEXT loop between lines 1940-1960 moves the coin down the screen.
The routine between lines 2010- 2250 decides and records the result of the
throw. Line 2040 uses RND(l) to select heads or tails. F is a flag indicating
the result: F = 0 is a tail and F = I a head. This result is recorded on the
screen by lines 2070 and 2080. Line 2110 then increments the number of
throws and 2130 the total number of heads. The current fraction of heads is
therefore H/N. Line 2150 then decides how tall a bar has to be added to
the graph to represent this result. The bar is plotted by the loop between
lines 2180-2210.
Cascade
Probability is also the subject of Cascade. This program sets up an array of
pegs and allows marbles to fall down, the totals for each column appearing
beneath the bottom row. This arrangement shows the different paths pos-
sible for the balls to travel, and is a practical demonstration of Pascal's
triangle.
The computer simulation has, however, a number of advantages over
the usual pegboard and nails approach. Children can easily select how
many rows they want for the array, up to seven. Additionally, the program
menu allows the selection of an alternative mode in which no marbles
appear, but instead each possible path through the pegs is plotted
individually.
134
Chapter 7 The Real Thing
135
Programming/or Education on the Commodore 64
136
Chapter 7 The Real Thing
137
Programming/or Education on the Commodore 64
2'l60 F,Et'1
2470 REI'I DETERMINE ALL. PATHS
2480 REM CALCULATE BINARY NUMBERS
2490 N = 2 A ( R - 1 ) - 1
2500 DIM E( N ) : DIM P*< N )
2510 FOR I - 0 TO N
2520 B -_. I
2530 C = 0 D - 0.1
2540 D :: D -if 10
2550 B -- B i 2
2560 IF INT( B )<}8 THEN C ~ C + D
2570 IF INT(B) <> B THEN ECI) = ECI)+1
2580 B = INT( B )
2590 IF B <> 0 THEN 2540
2600 REM IDENTIFY PATH AS BINARY STRING
2610 P$( I ) == STR$( C )
2620 IF LEN( P$(I»)= R THEN 2640
26:30 P$ (I) == "0" + P:t (I) : GOTO 2620
2640 NEXT I
2650 REM SORT INTO ORDER
2660 SW = 0
2670 FOR I = 1 TO N - 1
2680 IF E( I <= E( I + 1 ) THEN 2730
2690 SW := 1
27liJ0 B::::E ( I) : E ( I) = E ( 1+1. ) E ( 1+1. ) =8
2710 B$: :::: p.$: ( I ) : P$ ( I ) - p~~: ( 1+1 )
2720 P$( I + 1 ) = B$
2730 NEXT I
2740 IF SW = 1 THEN 2660
2750 REM PLOT EACH PATH IN TURN
2760 FOR I = 0 TO N
2770 A = 0 : C = 1
2780 LP == 5 - 40
2790 POKE LP + 54272, C : POKE LP, 34
2800 FOR J = 1 TO R + 1
2810 IF MID$ (F':!: (I) '/ J , 1) -::: >"0"THEN2830
2820 D == -1 : GOSUB 2930
2830 IF MI D$ (P$ CI) ,J , 1 ) -< >-" 1" THEN2850
2840 D = 1 : A = A + 1 : GOSUB 2930
2850 NEXT J
2860 IF C == 1 THEN GOSUB 2400
2870 FOR T = 1 TO 500 : NEXT T
2880 IF C = 1 THEN C == 5 : GOrO 2780
2890 NEXT I
138
Chapter 7 The Real Thing
290(2) F,ETURN
291.0 REM
292(2) REM MARK PATH
2930 FOR K = 1 TO 2
294(2) LP = LP + 4·(2) + D
2950 POKE LP + 54272, C POI<E LP, 34
296(2) NEXT ~:::
2970 LP -- LP + 40
2980 POVE LP + 54272. C POKE LP. 34
:,?9!:i(2) RETURI\I
READY.
Commentary
Cascade is controlled by lines 1020-1060. Line 1020 calls an initialisation
routine which gives a green screen and sets the randomness. Line 1030 calls
the explanation routine, and then the value returned for the variable CH
selects either the 'Cascade' or 'Paths' routine. The cascade routine shows a
series of marbles falling down the screen, being deflected by a triangular
array of pegs and collecting at the bottom in columns reflecting the dis-
tribution of Pascal's triangle. The paths routine works systematically
through the entire diagram, showing all the possible routes a given marble
could follow. The cascade routine gives an experimental set of numbers at
the bottom of the pegs, whereas numbers produced by the paths routine
actually are the values found in Pascal's triangle.
Lines 1170-1520 place explanatory text on the screen. At the end of the
routine, a value for CH is obtained which selects which of the two possible
simulations of Pascal's triangle is then executed by the computer.
139
Programmingjor Education on the Commodore 64
The pegs are placed on the screen by lines 2070-2170. R is the number of
rows. Since the vertical spacing of the pegs leaves two rows of the screen
free between each row with pegs, this means that the total height of a trian-
gular array of R pegs is R *3 - 2. As there are 25 rows altogether on the
screen, the top margin above the array will be 25 - (R *3 - 2) divided by 2.
This simplifies to 13.5 - R * 1.5. Hence the location of the top peg of the
array must be 1044 + INT(l3.5 - R* 1.5)*40, as calculated at line 2090. The
location of the first peg of each successive row, LV, is found by incremen-
ting this value by 1I8. This corresponds to three rows down and two
squares back, ie 40*3 - 2. This expression appears in the I loop at line 2110.
Finally, the horizontal position of each peg in any row, LH, is obtained by
incrementing the value of LV by four for each peg. This is done by the J
loop at line 2130. Line 2140 actually places the peg on the screen by POKE
LH,90.
The marble is dropped down the screen by lines 2190- 2310. LB is each
location calculated for the falling marble. GOSUB 2340 calls a separate
routine which then places the ball on the screen and erases it after a short
pause. The initial value of LB must be S - 40, at line 2200, because the ball
begins immediately above the top peg. The I loop which follows now uses
RND(l) to decide whether the ball falls to the left or to the right. D is a flag
indicating the direction: D = - 1 represents a marble bouncing to the left,
and D = 1 is a marble going to the right. Line 2260 adjusts the position of
the marble accordingly: LB = LB + 40 + D. If the marble is deflected to the
right, the variable A is also incremented. This is to allow the final column
arrived at to be identified. The subroutine called by line 2300 increments
the value of the array variable TC(A) and places this total on the screen. It
records the total number of marbles which have fallen into that column.
Lines 2410 and 2420 make sure that each column's total is printed in the
correct place.
All the possible paths are shown on the screen by the routine between lines
2470-2990. The algorithm used to do this first converts all the decimal
numbers, up to the number of possible paths, into binary notation. This is
done by lines 2490-2590. Thus the eleventh path would become 1011. This
binary number is then used as a route map through the pegs. The number is
scanned digit by digit and the 1 or 0 used to give the direction to turn. Lines
2610-2630 turn each of the binary numbers into a string of equal length
and then the routine between lines 2660-2740 sorts all these routes into
order, so that they are shown subsequently on the screen starting at the left
and working across gradually to the righthand side of the pegs. The path is
plotted through the pegs by lines 2760-2890. Line 2810 uses MID$ to
detect a deflection to the left and line 2830 similarly discovers deflections to
the right. The path is erased after a pause by the colour change at 2880.
140
Other titles from Sunshine
SPECTRUM BOOKS .
Spectrum Adventures
A guide to playing and writing adventures
Tony Bridge & Roy Carnell £5.95
ISBN 0 946408 07 6
ZX Spectrum Astronomy
Maurice Gavin £6.95
ISBN 0 946408 24 6
Spectrum Machine Code Applications
David Laine £6.95
ISBN0 946408 17 3
The Working Spectrum
David Lawrence £5.95
ISBN0 946408 ()() 9
Master your ZX Microdrive
Andrew Pennell £6.95
ISBN 0 946408 19 X
COMMODORE 64 BOOKS
Graphic Art for the Commodore 64
Boris Allan £5.95
ISBN 0 946408 15 7
DIY Robotics and Sensors on the Commodore Computer
John Billingsley £6.95
ISBN 0 946408 30 0
Artificial Intelligence on the Commodore 64
Keith & Stephen Brain £6.95
ISBN 0 946408 29 7
Commodore 64 Adventures
Mike Grace £5.95
ISBN0 946408 II 4
Business Applications for the Commodore 64
James Hall £5.95
ISBN 0 946408 12 2
Mathematics on the Commodore 64
Czes Kosniowski £5.95
ISBN 0 946408 14 9
Advanced Programming Techniques on the Commodore 64
David Lawrence £5.95
ISBN0 946408 23 8
141
The Working Commodore 64
David Lawrence £5.95
ISBN0 946408 02 5
Commodore 64 Machine Code Master
David Lawrence & Mark England £6.95
ISBN 0 946408 05 X
ELECTRON BOOKS
Graphic Art for the Electron Computer
Boris Allan £5.95
ISBN 0 946408 20 3
Programming for Education on the Electron Computer
John Scriven & Patrick Hall £5.95
ISBN 0 946408 21 1
DRAGON BOOKS .
142
The Working Dragon
David Lawrence £5.95
ISBN 0 946408 01 7
The Dragon Trainer
A handbook for beginners
Brian Lloyd £5.95
ISBN 0 946408 09 2
ATARIBOOKS .
Atari Adventures
Tony Bridge £5.95
ISBN 0 946408 18 1
143
Sunshine also publishes
POPULAR COMPUTING WEEKLY
The first weekly magazine for home computer users. Each copy contains
Top 10 charts of the best-selling software and books and up-to-the-
minute details of the latest games. Other features in the magazine include
regular hardware and software reviews, programming hints, computer
swap, adventure corner and pages of listings for the Spectrum, Dragon,
BBC, VIC 20 and 64, ZX 81 and other popular micros. Only 35p a week,
a year's subscription costs £19.95 (£9.98 for six months) in the UK and
£37.40 (£18.70 for six months) overseas.
DRAGON USER
The monthly magazine for all users of Dragon microcomputers. Each
issue contains reviews of software and peripherals, programming advice
for beginners and advanced users, program listings, a technical advisory
service and all the latest news related to the Dragon. A year's
subscription (12 issues) costs £10 in the UK and £16 overseas.
MICRO ADVENTURER
The monthly magazine for everyone interested in Adventure games, war
gaming and simulation/role-playing games. Includes reviews of all the
latest software, lists of all the software available and programming
advice. A year's subscription (12 issues) costs £10 in the UK and £16
overseas.
COMMODORE HORIZONS
The monthly magazine for all users of Commodore computers. Each
issue contains reviews of software and peripherals, programming advice
for beginners and advanced users, program listings, a technical advisory
service and all the latest news. A year's subscription costs £10 in the UK
and £16 overseas.
For further information contact:
Sunshine
12-13 Little Newport Street
London WC2R 3LD
01-4374343
144
If you have recently bought a Commodore 64 and are
looking for useful learning programs then this is the
book for you.
Teachers and parents will find it provides a source of
programs in a variety of subjects. Aimed primarily at
younger children these programs show how the
Commodore 64 can be used as a learning machine
as well as teaching different programming skills.
Using a modular approach the programs are
developed in stages and can be freely adapted to
suit a variety of educational needs. Although a
knowledge of BASIC is not essential using this book
will encourage you to develop your programming
style in novel and interesting ways.