⬅ Arcade

🖥️ Pixel 2001

A 1977-style 40-column BASIC computer, rebuilt from scratch

PIXEL 2001

40×25 · BASIC 2 compatible · 8/16/32K
Press Enter to power on.
💾 Dual floppy drive · device 8 (disks are kept in this browser)0: 1:

Keys: type normally. Shift+letter gives the graphic printed on that key. Esc = RUN/STOP, arrows = cursor, Backspace = DEL, Insert = INST, Home = HOME, End = CLR, Tab = RVS. F8 or ⏸ pauses (P and Esc are needed for typing). SAVE "NAME" keeps the program in this browser and puts it in a share link; SAVE "NAME",8 and LOAD "NAME",8 use the floppy drive, LOAD "$",8 then LIST shows a disk's directory, and data files work with OPEN 2,8,2,"0:NAME,S,W", PRINT#, INPUT#, GET# and CLOSE (OPEN 15,8,15 is the error and command channel); LOAD "NAME" brings it back, and opening a share link loads and runs it.

📘 Learn: character-mode games in BASIC

Seven short lessons and a built-in game, no machine language. Every lesson has a Run it button that types the example into the machine and runs it. Press RUN/STOP (Esc) to stop, type LIST to read it, change a line and RUN again. All example programs are originals written for Pixel 2001.

🔰 How BASIC works (start here)

New to BASIC? These tiny lessons are numbered B1, B2, and so on. Click on the PET screen and type each step yourself, pressing RETURN (Enter) at the end of each line. The Run it button types the finished example for you.

B1 · How BASIC works: line numbers, now or later

The PET understands two kinds of lines. A line without a number runs right away. This is immediate mode, like a calculator. A line that starts with a number is saved in memory to run later. This is program mode.

  1. Type PRINT 2+3 and press RETURN. The PET answers 5 straight away. That was immediate mode.
  2. Type 10 PRINT "I AM LINE 10" and press RETURN. Nothing happens! The line was saved as line 10 of a program.
  3. Type 20 PRINT "I AM LINE 20" and press RETURN.
  4. Type RUN. The PET runs the saved lines in number order.
  5. Type 15 PRINT "I SNUCK IN" and then RUN again. Line 15 runs between 10 and 20, even though you typed it last. This is why programmers count in tens: it leaves gaps for new lines.
  6. Type 10 PRINT "NEW LINE 10" and RUN. Typing an existing number replaces that line.

Remember: no number means do it now. A number means save it for RUN.

10 PRINT "I AM LINE 10"
15 PRINT "I SNUCK IN"
20 PRINT "I AM LINE 20"
30 PRINT "2+3 IS";2+3
B2 · How BASIC works: PRINT, LIST, RUN and NEW

Your first real program, and the three commands you will use all the time: LIST shows the program, RUN starts it, and NEW wipes it.

  1. Type NEW and press RETURN to start with empty memory.
  2. Type 10 PRINT "HELLO WORLD" and then RUN. The words in quotes are printed exactly as you typed them.
  3. Type 20 PRINT "BYE FOR NOW" and then LIST. The PET shows every saved line in order.
  4. Edit a line: type 10 PRINT "HELLO PIXEL" and LIST again. The old line 10 is gone. (You can also move the cursor up onto a listed line, change it and press RETURN.)
  5. Delete a line: type just the number, 20, and press RETURN. LIST shows that line 20 has vanished.
  6. LIST 10 shows only line 10, and LIST 10-30 shows a range.
  7. Type NEW and then LIST: nothing is left. Careful, because NEW can't be undone!

Tip: a ; at the end of a PRINT keeps the cursor on the same line, so the next PRINT carries on right after it.

10 PRINT "HELLO WORLD"
20 PRINT "HELLO ";
30 PRINT "PIXEL"
40 PRINT "TYPE LIST TO SEE ME"
B3 · How BASIC works: variables for numbers and strings

A variable is a labelled box that holds a value. A plain name like A or SC holds a number. A name ending in $, like N$, holds a string (text).

  1. In immediate mode, type A=5, then PRINT A. It prints 5.
  2. Type A=A+1 and PRINT A. Now it's 6. Read = as "becomes": A becomes A plus 1.
  3. Type N$="KAI" and PRINT "HI ";N$.
  4. Type PRINT N$+"!". Using + on strings joins them together.
  5. Type PRINT LEN(N$), which counts the letters (3).
  6. Try N$=5. You get ?TYPE MISMATCH ERROR, because a string box can't hold a number.

Naming rules: only the first two letters of a name count, so SCORE and SCARF are the same box! A name also can't contain a BASIC word: TOTAL hides TO, so it fails. Short names like SC are safest. RUN sets every variable back to 0 or to empty.

10 N$="PIXEL"
20 SC=10
30 PRINT "NAME: ";N$;" (";LEN(N$);"LETTERS)"
40 SC=SC*2+1
50 PRINT "SCORE DOUBLED PLUS ONE:";SC
60 G$=N$+" 2001"
70 PRINT "JOINED: ";G$
B4 · How BASIC works: INPUT asks a question

INPUT stops the program, shows a ? and waits for you to type something and press RETURN. Whatever you type goes into a variable.

  1. Type NEW, then 10 INPUT N$ and 20 PRINT "HELLO ";N$. RUN it, type your name at the ? and press RETURN.
  2. Add a question: change line 10 to 10 INPUT "YOUR NAME";N$. The text in quotes is shown before the ?.
  3. Numbers work too. Type 30 INPUT "HOW OLD";A and 40 PRINT "NEXT YEAR YOU WILL BE";A+1, then RUN.
  4. At the HOW OLD question, try typing a word. The PET says ?REDO FROM START and asks again, because A only holds numbers.

INPUT or GET? INPUT waits for a whole answer. GET (from game lesson 3) grabs one key without stopping, which is what action games need.

10 INPUT "YOUR NAME";N$
20 PRINT "HELLO ";N$;"!"
30 INPUT "HOW OLD";A
40 PRINT "NEXT YEAR YOU WILL BE";A+1
B5 · How BASIC works: IF and THEN make decisions

IF … THEN lets a program make decisions. If the test is true, the rest of the line runs. If it's false, the PET skips straight to the next line.

  1. In immediate mode, type A=7 and then IF A>5 THEN PRINT "BIG". It prints BIG.
  2. Type IF A<5 THEN PRINT "SMALL". Nothing is printed, because the test was false.
  3. The tests are = (equal), <> (not equal), <, >, <= and >=. Strings can be compared too: IF N$="YES" THEN …
  4. Join tests with AND and OR: IF A>5 AND A<10 THEN PRINT "BETWEEN".
  5. Type the example below and RUN it a few times with different numbers.

Watch out: everything after THEN on the same line belongs to the IF. In IF A=1 THEN PRINT "X":PRINT "Y", both PRINTs are skipped when A isn't 1.

10 INPUT "PICK A NUMBER 1 TO 10";A
20 IF A<1 OR A>10 THEN PRINT "THAT IS NOT 1 TO 10!"
30 IF A=7 THEN PRINT "LUCKY SEVEN!"
40 IF A>5 AND A<=10 THEN PRINT "A BIG ONE"
50 IF A>=1 AND A<=5 THEN PRINT "A SMALL ONE"
60 PRINT "DONE"
B6 · How BASIC works: GOTO and loops

GOTO jumps to another line number. Jumping back to an earlier line makes a loop, and that is how a program keeps going.

  1. Type NEW, then 10 PRINT "PIXEL "; and 20 GOTO 10. RUN it. The screen fills up forever!
  2. Press RUN/STOP (Esc) to break out. The PET says BREAK IN 10.
  3. Type CONT to carry on from where it stopped, then stop it again.
  4. Loops need a way out. GOTO is often used with IF: IF G<>S THEN 30 means "if the guess is wrong, go back to line 30". (After THEN, a plain line number is a GOTO.)
  5. RUN the guessing game below. It keeps looping until you guess the number.

Tip: GOTO to a line that doesn't exist gives ?UNDEF'D STATEMENT ERROR. Check your numbers after you renumber anything.

10 S=INT(RND(1)*20)+1:T=0
20 PRINT "I AM THINKING OF 1 TO 20"
30 INPUT "YOUR GUESS";G:T=T+1
40 IF G<S THEN PRINT "HIGHER!":GOTO 30
50 IF G>S THEN PRINT "LOWER!":GOTO 30
60 PRINT "YES! YOU GOT IT IN";T;"TRIES"
B7 · How BASIC works: FOR and NEXT loops

FOR … NEXT repeats lines a set number of times and counts for you. It's tidier than a GOTO loop when you know how many times to repeat.

  1. In immediate mode, type FOR I=1 TO 5:PRINT I:NEXT. It prints 1 to 5.
  2. Add STEP to count in jumps: FOR I=0 TO 20 STEP 5:PRINT I;:NEXT.
  3. Count backwards: FOR I=5 TO 1 STEP -1:PRINT I;:NEXT:PRINT "LIFTOFF!".
  4. Put one loop inside another (a nested loop). The inner one finishes completely each time the outer one goes round once. The times table below uses this.
  5. An empty loop like FOR D=1 TO 500:NEXT is a handy delay. Games use it to slow things down.

Tip: each FOR needs its own NEXT. With nested loops, the last FOR opened is the first one closed.

10 PRINT "{CLR}TIMES TABLE"
20 FOR R=1 TO 6
30 FOR C=1 TO 6
40 PRINT RIGHT$("   "+STR$(R*C),4);
50 NEXT C
60 PRINT
70 NEXT R
80 FOR I=5 TO 1 STEP -1:PRINT I;:FOR D=1 TO 300:NEXT D:NEXT I
90 PRINT "LIFTOFF!"
B8 · How BASIC works: GOSUB and RETURN subroutines

A subroutine is a little job you can use again and again. GOSUB 500 jumps to line 500 and remembers where it came from. When the PET reaches RETURN, it goes back to just after the GOSUB.

  1. Type NEW, then 500 PRINT "*****":RETURN.
  2. Type 10 GOSUB 500, 20 PRINT " HI! ", 30 GOSUB 500 and RUN. The stars line is used twice but only typed once.
  3. Now RUN again and look at the end. You get ?RETURN WITHOUT GOSUB ERROR! After line 30 the program carries on into line 500, and that RETURN has nowhere to go back to.
  4. Fix it with 40 END, which stops the program before it reaches the subroutines. (You'll meet END properly in B10.)
  5. Subroutines can use variables as their inputs. In the example, B sets how many stars to draw.

Why bother? Every game lesson keeps things like "draw the score" at line 900 and calls GOSUB 900 whenever the score changes. You only have one place to fix.

10 B=5:GOSUB 500
20 PRINT "  SUBROUTINES"
30 B=15:GOSUB 500
40 PRINT "  SAVE TYPING"
50 B=25:GOSUB 500
60 END
500 REM DRAW B STARS
510 FOR I=1 TO B:PRINT "*";:NEXT:PRINT
520 RETURN
B9 · How BASIC works: REM notes and screen tricks

REM (remark) lines are notes for people. The PET ignores everything after REM, so use them to label each part of your program. PRINT can also move the cursor and change how text looks, using special control characters.

  1. Type 10 REM MY FIRST SCREEN TRICKS and RUN. Nothing happens, and that's correct: it's just a note.
  2. Clear the screen: PRINT CHR$(147). CHR$ turns a code number into a character, and 147 means "clear screen". In our listings this is written {CLR}. On the PET you get it by typing inside quotes and pressing SHIFT+Home.
  3. Home: PRINT CHR$(19);"TOP!" jumps the cursor to the top-left corner without clearing. It's written {HOME}, and games use it for the score line.
  4. Move the cursor: CHR$(17) moves down, CHR$(145) up, CHR$(29) right and CHR$(157) left. These are {DOWN}, {UP}, {RIGHT} and {LEFT}. Inside quotes, the arrow keys type them for you.
  5. Reverse text: PRINT CHR$(18);"BOLD";CHR$(146);" NORMAL". These are {RVS} and {OFF}.
  6. SPC(10) prints 10 spaces and TAB(20) jumps to column 20.

Tip: when you press Run it, the {…} names in the listings are turned into the real control characters for you.

10 REM CLEAR THE SCREEN
20 PRINT "{CLR}";
30 REM MOVE DOWN 5 LINES AND RIGHT USING TAB
40 PRINT "{DOWN}{DOWN}{DOWN}{DOWN}{DOWN}";TAB(12);"{RVS} PIXEL 2001 {OFF}"
50 PRINT SPC(8);"MADE WITH CURSOR MOVES"
60 REM JUMP HOME AND PRINT A TOP LINE
70 PRINT "{HOME}SCORE 0";CHR$(29);CHR$(29);"<- TOP LINE"
80 REM MOVE BACK DOWN BELOW THE TITLE
90 PRINT "{DOWN}{DOWN}{DOWN}{DOWN}{DOWN}{DOWN}{DOWN}{DOWN}"
B10 · How BASIC works: END, and putting it all together

END stops a program on purpose and returns to READY. This last basics lesson also puts everything from B1–B9 together into one small game.

  1. A program also stops on its own after its last line. You need END when there is more code below that shouldn't run, such as the subroutines from B8.
  2. STOP is END's cousin. It halts with BREAK IN plus the line number, and CONT carries on. That's handy for checking your variables partway through a program.
  3. An IF can end the program: IF A$="N" THEN END. Every game here uses this for "AGAIN? Y/N".
  4. RUN the example below and look for each idea in its LIST. REM (B9), variables (B3), INPUT (B4), IF (B5), GOTO (B6), FOR (B7), GOSUB (B8) and END are all there.

Next: you're ready for the game lessons below. Start with 1 · Hello, screen.

10 REM MATH QUIZ: EVERY BASICS IDEA
20 PRINT "{CLR}{RVS} PIXEL MATH QUIZ {OFF}":SC=0
30 FOR Q=1 TO 3
40 A=INT(RND(1)*10)+1:B=INT(RND(1)*10)+1
50 PRINT "QUESTION";Q;": ";A;"+";B;
60 INPUT N
70 IF N=A+B THEN SC=SC+1:GOSUB 500:GOTO 90
80 PRINT "NOT QUITE, IT IS";A+B
90 NEXT Q
100 PRINT "YOU SCORED";SC;"OUT OF 3"
110 INPUT "AGAIN (Y/N)";A$
120 IF A$="Y" THEN 20
130 END
500 REM A HAPPY CHEER
510 PRINT "{RVS} RIGHT! {OFF}":RETURN

🎓 A complete 1979 high school programming class

Step back into a 1979 college-prep high school. BASIC is a full-year senior elective for seniors who are also taking calculus, and the lab has a few Commodore PETs and one Wang 2200B. The course follows what teachers really taught then. It uses Dartmouth's beginner sequence from Kemeny and Kurtz (PRINT, LET, INPUT, GOTO, FOR/NEXT, IF/THEN, GOSUB, READ/DATA, functions, RND), the number-crunching and puzzle activities from Creative Computing, and the hands-on, project-first spirit of the MECC classroom materials. Every program is our own. Each lesson ends with a teacher's note on why it was on the 1979 syllabus. Finish the How BASIC works lessons (B1–B10) first.

📖 The Freshman Who Wouldn't Go Away: how a pushy ninth-grader got his start, and went on to patent internet search before Google

How a pushy ninth-grader talked his way into the computer lab in 1979, and went on to patent internet search before there was a Google.

In 1979, at a private college-prep high school, computer programming was not for freshmen. The BASIC class was a senior elective, open only to college-bound seniors who were also taking calculus. Garnet Chaney was a freshman. On paper, that was the end of the story.

It wasn't.

The open door

Partway through his first semester, Garnet found the computer lab open after school. He walked in, and something clicked. The machines answered back. You typed, they did what you said (or exactly what you said, which is not always the same thing). He was fascinated.

He wasn't allowed to take the class. So he did what only a freshman can do: he made himself thoroughly, magnificently obnoxious to the seniors. He hovered. He asked questions. He asked more questions. Eventually the seniors did the only sensible thing and lent him their study books, just to make him go away.

He didn't go away. He read the books.

Two computers, a dozen seniors, and one freshman

The school had exactly two computers. About a dozen seniors in the class had priority on them, which was fair: it was their class. So Garnet used the machines whenever they were free, in whatever minutes he could find.

Something funny happened over time. The freshman who had pestered the seniors for help became the person the seniors came to for help. He ended up tutoring many of them. One of his regulars was a senior named Mike, who used FOR/NEXT loops for everything, whether the problem needed one or not. Garnet nicknamed him for it, and to this day he is FOR/NEXT Mike.

Earning the seat

The rule was the rule: calculus first. So Garnet climbed the ladder: advanced algebra 1 and 2, trigonometry and geometry, precalculus, and calculus. By his senior year he could finally enroll in the class he'd been haunting for years.

By then the lab had doubled. There were now eight PETs, all sharing a single floppy drive. Garnet still had his trusty Memorex cassette from freshman year, the only brand the teacher allowed in the machines.

The calculator wars

Garnet had also been trading. He had horse-traded his way into several Texas Instruments programmable calculators, including a TI-59. One trade was with a senior football star, and Garnet threw in a simpler calculator as well, so as not to confuse him.

The calculus teacher, meanwhile, was an HP man: a Reverse Polish Notation snob, through and through. Garnet never did find an HP to trade for. So he went on the offensive. He would write the assigned programs on his TI-59 during his later classes, then stroll in the next morning and announce that he had already finished the assignment on his TI. Could the teacher's precious HP do that?

The teacher had the perfect answer: "The assignment isn't finished until you complete it on one of the school PET computers!" Or on the lab's lone Wang 2200B, which Garnet promptly dubbed "My Wang!", a line his classmates still remind him of at reunions.

Passing it on

Later, when Garnet got his first real PC clone, a Sanyo MBC-550, he gave it to his grandfather. His grandfather had a wonderful time learning early MS-DOS and the EDLIN line editor. Curiosity, it turns out, has no age limit.

Where it led

Today Garnet is an AI researcher. He holds multiple patents on internet search, filed before there was a Google, and Google's own engineers have cited those patents more than 600 times.

It started with an open door, a borrowed book, and a freshman who wouldn't take "seniors only" for an answer.

Your turn

You don't need to be a senior. You don't need calculus. You don't need to be fourteen, or forty, or anything in particular. Garnet's grandfather learned MS-DOS for fun, so you can start at any age. All you need is a computer that answers back, and Pixel 2001 is one, right here in your browser, with nobody to shoo you away.

The class he was too young to take is waiting for you. Start with lesson C1-1 →

Fall semester

  1. C1-1 · Syntax and good style: a table of values
  2. C1-2 · Number crunching: factorials and big numbers
  3. C1-3 · Fibonacci numbers and the golden ratio
  4. C1-4 · Prime numbers and the Sieve of Eratosthenes (DIM)
  5. C1-5 · Euclid's GCD, fractions and LCM
  6. C1-6 · READ, DATA and RESTORE: a grade book
  7. C1-7 · DEF FN: functions, tables and slopes
  8. C1-8 · Random numbers and simulation: dice and coins
  9. C1-9 · Pi, part 1: Monte Carlo darts
  10. C1-10 · Pi, part 2: Leibniz, Wallis, Archimedes and the quarter circle
C1-1 · Fall: Syntax and good style, a table of values

Welcome to Computer Programming! Before we crunch any numbers, we learn the habits that make a program easy to read, fix and grade. On the first day, a 1979 teacher would also hand out a flowchart template and insist that you plan on paper before touching the keyboard, because lab time was precious.

  1. Begin with a header. Use REM lines for the title, your name, the date and what the program does.
  2. Number lines by section. Setup goes in the 100s, the main work in the 200s and output in the 300s. Leave gaps of 10, and keep subroutines high (1000+), after an END.
  3. Choose clear variable names. Only two letters count, so pick ones that mean something: N for a count, SQ for a square. Avoid names that hide BASIC words, such as TO, IF, ON and ST.
  4. Put one idea on each line. Colons are allowed, but a line should do one job.
  5. Use the syntax rules: LET is optional (LET A=5 is the same as A=5). Strings go in quotes. ; keeps printing on the same line, and , jumps to the next 10-column zone.
  6. Make tidy output. Print a heading, line up the columns with TAB() and label every number.
  7. RUN the example, LIST it, then assignment 1: add a column for cube roots, using N^(1/3).

Teacher's note (1979): Dartmouth's first lessons were all about tables of values, and most early class assignments were "print a neat table". On a shared machine with a dozen seniors waiting, a program that someone else could read at a glance was a program that could be helped and graded quickly. Style rules came first because time at the keyboard was the scarcest thing in the room.

10 REM ******************************
20 REM * TABLE OF VALUES            *
30 REM * COMPUTER PROGRAMMING 1979  *
40 REM * SQUARES, CUBES, ROOTS      *
50 REM ******************************
100 REM --- SETUP ---
110 LM=10
120 PRINT "{CLR}    TABLE OF VALUES, 1 TO";LM
130 PRINT
140 PRINT "N";TAB(5);"SQUARE";TAB(14);"CUBE";TAB(22);"SQUARE ROOT"
150 PRINT "--";TAB(5);"------";TAB(14);"----";TAB(22);"-----------"
200 REM --- MAIN WORK ---
210 FOR N=1 TO LM
220 SQ=N*N
230 CU=N*N*N
240 RT=INT(SQR(N)*1000+.5)/1000
250 GOSUB 1000
260 NEXT N
300 REM --- OUTPUT ---
310 PRINT
320 PRINT "DONE. PLAN, THEN TYPE. TYPE LIST!"
330 END
1000 REM --- PRINT ONE ROW ---
1010 PRINT N;TAB(5);SQ;TAB(14);CU;TAB(22);RT
1020 RETURN
C1-2 · Fall: Number crunching, factorials and big numbers

Computers were sold as number crunchers, so the first real workout is factorials: N! = 1×2×3×…×N. They grow astonishingly fast, which is a great way to discover the limits of your machine.

  1. In immediate mode: F=1:FOR I=1 TO 10:F=F*I:NEXT:PRINT F gives 3628800.
  2. Try 20 instead of 10. The answer appears as 2.43290201E+18, which is scientific notation: 2.43 × 1018. The PET keeps only about 9 digits, so the rest are lost.
  3. Try 34. You get ?OVERFLOW ERROR! The PET's largest number is about 1.7 × 1038, and 34! is bigger.
  4. Counting digits without overflowing: add up logarithms instead of multiplying. LOG(N)/LOG(10) is the number of digits minus a bit. The program uses this to show that 100! has 158 digits.
  5. Exact answers: to get every digit, do long multiplication like on paper. Store one digit per array box (DIM D(60)), multiply each digit and carry the tens. The program prints all 33 digits of 30!.
  6. Assignment 2: change line 410 to find exactly how many trailing zeros 30! has, and explain why (count the 5s!).

Teacher's note (1979): "Computing factorials accurately" was a classic Creative Computing exercise. It taught three things at once: loops, the limits of floating point (every student hit OVERFLOW sooner or later), and arrays as a way to beat those limits. Calculus students also met n! in Taylor series that same year.

10 REM FACTORIALS AND BIG NUMBERS
20 REM COMPUTER PROGRAMMING 1979, LESSON C1-2
100 REM --- PART 1: N! FOR N=1 TO 33 (34 WOULD OVERFLOW) ---
110 PRINT "{CLR}N";TAB(5);"N!"
120 FOR N=1 TO 33 STEP 4
130 F=1:FOR I=1 TO N:F=F*I
140 NEXT I
150 PRINT N;TAB(5);F
160 NEXT N
200 REM --- PART 2: DIGITS OF 100! USING LOGARITHMS ---
210 L=0:FOR I=1 TO 100:L=L+LOG(I)/LOG(10):NEXT
220 PRINT "100! HAS";INT(L)+1;"DIGITS"
300 REM --- PART 3: EVERY DIGIT OF 30! ---
310 DIM D(60):D(1)=1:ND=1
320 FOR M=2 TO 30
330 CY=0
340 FOR K=1 TO ND
350 V=D(K)*M+CY:D(K)=V-INT(V/10)*10:CY=INT(V/10)
360 NEXT K
370 IF CY>0 THEN ND=ND+1:D(ND)=CY-INT(CY/10)*10:CY=INT(CY/10):GOTO 370
380 NEXT M
390 PRINT "30! EXACTLY (";ND;"DIGITS):"
400 FOR K=ND TO 1 STEP -1:PRINT MID$(STR$(D(K)),2);:NEXT:PRINT
410 REM ASSIGNMENT: COUNT THE TRAILING ZEROS HERE
420 END
C1-3 · Fall: Fibonacci numbers and the golden ratio

Leonardo of Pisa (Fibonacci) asked in 1202 how fast rabbits breed. The answer is the sequence 1, 1, 2, 3, 5, 8, 13, …, where each number is the sum of the two before it. It's the perfect first loop with a "memory".

  1. The trick is to keep two variables, A (older) and B (newer). Each step makes C=A+B and then shifts: A=B:B=C.
  2. In immediate mode: A=1:B=1:FOR I=1 TO 10:C=A+B:PRINT C;:A=B:B=C:NEXT.
  3. The golden ratio: divide each Fibonacci number by the one before it. The ratios swing above and below and settle on φ = (1+√5)/2 = 1.6180339…, the "golden" proportion of art and architecture.
  4. The program checks the closed formula too. The Nth Fibonacci number is the nearest whole number to φN/√5, which is proof that a pattern built from adding can be described by powers.
  5. Assignment 3: add up the first N Fibonacci numbers and compare the total with F(N+2). What do you notice?

Teacher's note (1979): Fibonacci appeared in almost every 1970s BASIC textbook because it needs only addition, but it forces students to think about order of assignment. Write B=A+B:A=B and the sequence breaks, which makes it a perfect debugging lesson. The ratio column also gave calculus students their first sight of a limit on the screen.

10 REM FIBONACCI NUMBERS AND THE GOLDEN RATIO
20 REM COMPUTER PROGRAMMING 1979, LESSON C1-3
100 REM --- SETUP ---
110 A=1:B=1:PH=(1+SQR(5))/2
120 PRINT "{CLR}N";TAB(4);"FIB(N)";TAB(13);"RATIO";TAB(26);"FORMULA"
130 PRINT 1;TAB(4);1:PRINT 2;TAB(4);1
200 REM --- MAIN LOOP: NEW = OLD + NEWER ---
210 FOR N=3 TO 22
220 C=A+B
230 RA=C/B
240 FO=INT(PH^N/SQR(5)+.5)
250 PRINT N;TAB(4);C;TAB(13);RA;TAB(26);FO
260 A=B:B=C
270 NEXT N
300 REM --- OUTPUT ---
310 PRINT "GOLDEN RATIO PHI =";PH
320 END
C1-4 · Fall: Primes and the Sieve (DIM)

A prime is a whole number above 1 that only 1 and itself divide evenly: 2, 3, 5, 7, 11, … Around 240 B.C. Eratosthenes of Cyrene found a way to list them all without doing a single division. The method is called the Sieve, and it is the perfect reason to learn DIM, our first array.

  1. DIM F(500) sets aside 501 numbered boxes, F(0) to F(500). Each box starts at 0. Here, 0 means "might be prime".
  2. Start at 2. If F(2) is still 0, then 2 is prime. Cross out every multiple of it (4, 6, 8, …) by setting that box to 1.
  3. Move on to 3, then 5, and so on. You only have to sieve up to √500 ≈ 22, because any composite number has a factor no bigger than its square root.
  4. Last, print every box that is still 0, and count them. Below 500 there are exactly 95 primes.
  5. Assignment 4: change the program so it prints "twin primes" too, meaning pairs that differ by 2, such as 11 and 13. How many pairs can you find below 500?

Teacher's note (1979): Students always want to test each number by dividing. Have them time that against the sieve and the sieve wins easily, because it only adds. Memory is the catch: a 4K PET cannot afford DIM F(5000), since each element costs five bytes. That is a good moment to talk about the trade-off between speed and memory, which every programmer faces.

10 REM PRIMES BY THE SIEVE OF ERATOSTHENES
20 REM COMPUTER PROGRAMMING 1979, LESSON C1-4
100 REM --- SETUP: ONE BOX PER NUMBER ---
110 M=500:DIM F(500)
120 PRINT "{CLR}PRIMES BELOW";M
200 REM --- SIEVE: CROSS OUT MULTIPLES ---
210 FOR I=2 TO SQR(M)
220 IF F(I)=1 THEN 250
230 FOR J=I*I TO M STEP I:F(J)=1:NEXT J
250 NEXT I
300 REM --- OUTPUT: WHAT IS LEFT IS PRIME ---
310 C=0
320 FOR I=2 TO M
330 IF F(I)=0 THEN PRINT I;:C=C+1
340 NEXT I
350 PRINT:PRINT "COUNT =";C
360 END
C1-5 · Fall: Euclid's GCD, fractions and LCM

Around 300 B.C. Euclid wrote down what may be the oldest algorithm still in use. It finds the greatest common divisor (GCD) of two numbers, meaning the biggest number that divides both. With the GCD we can reduce fractions to lowest terms, and we can find the least common multiple (LCM) we need to add them.

  1. Euclid's idea: the GCD of A and B is the same as the GCD of B and the remainder of A÷B. BASIC has no MOD, so we build one: R=A-INT(A/B)*B.
  2. Repeat with A=B:B=R until the remainder is 0. The last non-zero number is the GCD. For example, GCD(1071,462): 1071→462→147→21→0, so the GCD is 21.
  3. To reduce a fraction N/D, divide the top and the bottom by their GCD. So 462/1071 becomes 22/51.
  4. LCM(A,B) = A×B ÷ GCD(A,B). The program uses it to add two fractions over a common denominator, then reduces the answer.
  5. Assignment 5: extend the program to multiply and divide fractions too. Then add up 1/1+1/2+…+1/10 exactly, as a reduced fraction.

Teacher's note (1979): This is the first time students write a GOSUB they call more than once, because the GCD routine serves both the reducing and the LCM. Ask them to count the loop passes: even for numbers in the millions, Euclid finishes in a few dozen steps. That is a nice early taste of why some algorithms are fast.

10 REM EUCLID'S GCD, FRACTIONS AND LCM
20 REM COMPUTER PROGRAMMING 1979, LESSON C1-5
100 REM --- SHOW EUCLID'S STEPS ---
110 PRINT "{CLR}EUCLID: GCD(1071,462)"
120 A=1071:B=462
130 R=A-INT(A/B)*B:PRINT A;B;"REM";R
140 A=B:B=R:IF R<>0 THEN 130
150 PRINT "GCD =";A:PRINT
200 REM --- REDUCE A FRACTION ---
210 N=462:D=1071:A=N:B=D:GOSUB 900
220 PRINT N;"/";D;"=";N/G;"/";D/G:PRINT
300 REM --- ADD 5/12 + 7/18 USING THE LCM ---
310 N1=5:D1=12:N2=7:D2=18
320 A=D1:B=D2:GOSUB 900:L=D1*D2/G
330 PRINT "LCM(12,18) =";L
340 N=N1*L/D1+N2*L/D2:D=L
350 A=N:B=D:GOSUB 900
360 PRINT "5/12 + 7/18 =";N/G;"/";D/G
370 END
900 REM --- GCD OF A AND B, RESULT IN G ---
910 R=A-INT(A/B)*B:A=B:B=R:IF R<>0 THEN 910
920 G=A:RETURN
C1-6 · Fall: READ/DATA/RESTORE: a grade book

Typing the same numbers in with INPUT every run gets old fast. BASIC lets you store data inside the program with DATA lines and pick it up with READ. RESTORE rewinds to the first item so you can read it all again. Our example is a teacher's grade book.

  1. DATA lines hold a list of values separated by commas, and they can sit anywhere in the program. Here each student has a name and three test scores.
  2. READ N$,S1,S2,S3 takes the next four items in order. A string goes into a $ variable and a number into a numeric one. If the types don't match you get ?SYNTAX ERROR on the DATA line.
  3. A marker value, "END", tells the loop to stop, so you can add students without changing any count.
  4. The first pass prints each student's average and letter grade, and adds up the class total. After RESTORE, a second pass lists everyone above the class average.
  5. Assignment 6: add a fourth test, and have the program print the highest and lowest single score along with who got them.

Teacher's note (1979): Every school office had its own grade-book program. Students could see right away why it pays to keep data separate from code: next term you change only the DATA lines. Warn them about ?OUT OF DATA ERROR, which is what happens if they forget the END marker. (Names here are made up, of course!)

10 REM READ/DATA/RESTORE: A GRADE BOOK
20 REM COMPUTER PROGRAMMING 1979, LESSON C1-6
100 REM --- PASS 1: AVERAGES AND LETTERS ---
110 PRINT "{CLR}NAME";TAB(10);"T1  T2  T3  AVG GR"
120 T=0:C=0
130 READ N$:IF N$="END" THEN 300
140 READ S1,S2,S3
150 AV=INT((S1+S2+S3)/3+.5):T=T+AV:C=C+1
160 G$="F":IF AV>=60 THEN G$="D"
170 IF AV>=70 THEN G$="C"
180 IF AV>=80 THEN G$="B"
190 IF AV>=90 THEN G$="A"
200 PRINT N$;TAB(9);S1;S2;S3;AV;" ";G$
210 GOTO 130
300 REM --- CLASS AVERAGE, THEN REWIND ---
310 CA=T/C:PRINT:PRINT "CLASS AVERAGE";INT(CA*10+.5)/10
320 RESTORE:PRINT "ABOVE AVERAGE:"
330 READ N$:IF N$="END" THEN 400
340 READ S1,S2,S3
350 IF (S1+S2+S3)/3>CA THEN PRINT "  ";N$
360 GOTO 330
400 END
900 REM --- THE GRADE BOOK ---
910 DATA ALICE,92,88,95,BEN,75,81,68
920 DATA CARLA,64,70,59,DEV,85,90,78
930 DATA ELLEN,99,94,97,FRANK,55,62,48
940 DATA GRACE,71,77,80,END
C1-7 · Fall: DEF FN: functions, tables and slopes

When the same formula keeps showing up, give it a name. DEF FN defines your own one-line function, which you can then use anywhere, just like SQR or INT. We'll use one to print a table of values and to estimate how steep a curve is at each point, which is its slope.

  1. DEF FN F(X)=X*X-2*X-3 defines f(x) = x² − 2x − 3. The X inside is a placeholder, so FN F(5) works it out with X=5 and gives 12.
  2. A FOR loop from −2 to 4 prints a table of x and f(x). Look for where f(x) changes sign: those are the roots, x = −1 and x = 3.
  3. The slope between two very close points is (FN F(X+H)-FN F(X-H))/(2*H), with a small H such as 0.001. We define it as a second function, FN S(X), that calls the first.
  4. Compare the result with the calculus answer, f′(x) = 2x − 2. They match to several decimal places, and the slope is 0 at x = 1, the bottom of the curve.
  5. Assignment 7: change line 110 to f(x) = x³ − 6x and find where the slope is 0. Then try SIN(X) and see whether the slope looks like COS(X).

Teacher's note (1979): On a PET, DEF FN takes only one numeric argument and fits on one line, which is a good limit for beginners. It also must be run before it's used, or you get ?UNDEF'D FUNCTION ERROR. Students taking calculus loved seeing a derivative "computed" instead of memorized. This is a fine moment to talk about why too small an H makes round-off errors worse.

10 REM DEF FN: FUNCTIONS, TABLES AND SLOPES
20 REM COMPUTER PROGRAMMING 1979, LESSON C1-7
100 REM --- DEFINE THE FUNCTIONS ---
110 DEF FN F(X)=X*X-2*X-3
120 H=.001
130 DEF FN S(X)=(FN F(X+H)-FN F(X-H))/(2*H)
200 REM --- TABLE OF VALUES AND SLOPES ---
210 PRINT "{CLR}F(X)=X*X-2*X-3"
220 PRINT "   X    F(X)   SLOPE   2X-2"
230 FOR X=-2 TO 4 STEP .5
240 S=INT(FN S(X)*1000+.5)/1000
250 PRINT X;TAB(7);FN F(X);TAB(14);S;TAB(22);2*X-2
260 NEXT X
300 REM --- WHERE IS IT FLAT? ---
310 PRINT:PRINT "SLOPE IS 0 AT X = 1, F(1) =";FN F(1)
320 END
C1-8 · Fall: Random numbers and simulation: dice and coins

The computer can't really flip a coin, but RND gives it a "random" number between 0 and 1 that is good enough to simulate chance. If we run an experiment a thousand times in a few seconds, the laws of probability start to show up on the screen.

  1. RND(1) returns a number from 0 up to (but not including) 1. To get a whole number from 1 to 6, use INT(6*RND(1))+1. That is a die.
  2. A coin is INT(2*RND(1)), where 0 is tails and 1 is heads. We flip 1000 coins, count the heads, and watch for the longest streak. Most people guess a streak of 4 or 5; in 1000 flips it is usually 8 to 10!
  3. Next we roll two dice 1000 times and count each total from 2 to 12 in an array, DIM T(12). Then we draw a bar chart. Seven is the most common total, because 6 of the 36 ways to roll lands on it.
  4. RND(-1979) at the start seeds the generator, so every run gives the same "random" results, which is handy when you're testing. Change it to RND(0) to seed from the clock and get a fresh experiment every time.
  5. Assignment 8: simulate the "birthday problem". How often do 23 random birthdays include a match? (Hint: DIM B(365).)

Teacher's note (1979): Have each student flip a real coin 20 times while the PET does 1000. Pooling the class results next to the computer's makes the law of large numbers obvious. Warn them that "random" from a computer is really a formula (a pseudo-random sequence), which is why seeding it gives the same numbers again.

10 REM RANDOM NUMBERS AND SIMULATION: DICE AND COINS
20 REM COMPUTER PROGRAMMING 1979, LESSON C1-8
100 REM --- SETUP ---
110 X=RND(-1979):DIM T(12)
120 PRINT "{CLR}FLIPPING 1000 COINS..."
200 REM --- COINS: COUNT HEADS, LONGEST STREAK ---
210 HD=0:RU=0:BE=0:LA=-1
220 FOR I=1 TO 1000
230 C=INT(2*RND(1)):HD=HD+C
240 IF C=LA THEN RU=RU+1:GOTO 260
250 RU=1:LA=C
260 IF RU>BE THEN BE=RU
270 NEXT I
280 PRINT "HEADS";HD;" TAILS";1000-HD
290 PRINT "LONGEST STREAK";BE
300 REM --- TWO DICE, 1000 ROLLS ---
310 PRINT "ROLLING TWO DICE 1000 TIMES..."
320 FOR I=1 TO 1000
330 D=INT(6*RND(1))+1+INT(6*RND(1))+1
340 T(D)=T(D)+1
350 NEXT I
400 REM --- BAR CHART, ONE * PER 6 ROLLS ---
410 FOR D=2 TO 12
420 PRINT RIGHT$(" "+STR$(D),3);RIGHT$("   "+STR$(T(D)),5);" ";
430 FOR J=1 TO T(D)/6:PRINT "*";:NEXT J:PRINT
440 NEXT D
450 END
C1-9 · Fall: Pi part 1: Monte Carlo darts

Here is a way to find π by throwing darts, without a ruler or a compass. Picture a square board 1 unit on each side, with a quarter circle of radius 1 drawn from one corner. The quarter circle's area is π/4 and the square's is 1. Throw darts at random, and the fraction that land inside the curve comes out close to π/4. This is called the Monte Carlo method, named after the famous casino.

  1. A dart is two random numbers: X=RND(1) and Y=RND(1), a point somewhere in the square.
  2. It is inside the quarter circle if X*X+Y*Y<=1 (that's Pythagoras: the distance from the corner is at most 1). Count those hits in H.
  3. After N darts, π ≈ 4·H/N. The program shows the estimate updating as the darts fly.
  4. To make it visible, the board is a 20×20 patch of the screen. Each dart POKEs a symbol into screen memory (which starts at 32768): a filled ball (screen code 81) inside the circle and a small dot (screen code 46) outside. The curve draws itself!
  5. Assignment 9: run 100, 1000 and 10000 darts and record the error each time. How many times more darts does it take to get one more correct digit?

Teacher's note (1979): This is the class favorite every year. Students love watching the circle appear out of pure chance, and they're shocked at how slowly it improves: to get one more digit you need about 100 times the darts. That is a perfect lead-in to next week, when cleverer formulas will beat the darts easily. Physicists really do use this method, starting with the Manhattan Project in the 1940s.

10 REM PI PART 1: MONTE CARLO DARTS
20 REM COMPUTER PROGRAMMING 1979, LESSON C1-9
100 REM --- SETUP: CLEAR, SEED, BOARD EDGE ---
110 PRINT "{CLR}";:X=RND(-1979):SC=32768:H=0
120 FOR I=0 TO 20:POKE SC+20*40+I,64:POKE SC+I*40+20,93:NEXT I
130 D$="{HOME}{RIGHT}{RIGHT}{RIGHT}{RIGHT}{RIGHT}{RIGHT}{RIGHT}{RIGHT}{RIGHT}{RIGHT}{RIGHT}{RIGHT}{RIGHT}{RIGHT}{RIGHT}{RIGHT}{RIGHT}{RIGHT}{RIGHT}{RIGHT}{RIGHT}{RIGHT}"
140 PRINT D$;"MONTE CARLO PI"
200 REM --- THROW THE DARTS ---
210 FOR N=1 TO 2000
220 X=RND(1):Y=RND(1)
230 C=INT(X*20):R=19-INT(Y*20)
240 IF X*X+Y*Y<=1 THEN H=H+1:POKE SC+R*40+C,81:GOTO 260
250 POKE SC+R*40+C,46
260 IF N-INT(N/100)*100 THEN 300
270 PRINT D$;"{DOWN}{DOWN}DARTS";N
280 PRINT D$;"{DOWN}{DOWN}{DOWN}HITS ";H
290 PRINT D$;"{DOWN}{DOWN}{DOWN}{DOWN}PI =";4*H/N;"    "
300 NEXT N
400 REM --- FINAL RESULT ---
410 PRINT D$;"{DOWN}{DOWN}{DOWN}{DOWN}{DOWN}{DOWN}TRUE PI"
420 PRINT D$;"{DOWN}{DOWN}{DOWN}{DOWN}{DOWN}{DOWN}{DOWN}";{255}
430 PRINT D$;"{DOWN}{DOWN}{DOWN}{DOWN}{DOWN}{DOWN}{DOWN}{DOWN}{DOWN}ERROR";
440 PRINT INT(ABS(4*H/2000-{255})*1E4+.5)/1E4
450 PRINT "{HOME}";:FOR I=1 TO 22:PRINT:NEXT I
460 END
C1-10 · Fall: Pi part 2: Leibniz, Wallis, Archimedes and the quarter circle

Last week's darts took 2000 throws to get π to about 2 digits. Mathematicians spent 2,000 years finding cleverer ways. Today we race four of them on the PET, comparing their error and how much work each one needs.

  1. Archimedes (about 250 B.C.) fit polygons inside a circle of radius 1. Start with a hexagon, which has side 1, and keep doubling the number of sides. The new side is S/SQR(2+SQR(4-S*S)), and half the perimeter gets closer and closer to π. Archimedes himself stopped at 96 sides.
  2. Leibniz (1674): π/4 = 1 − 1/3 + 1/5 − 1/7 + … The signs take turns, which is easy with G=-G. It's beautiful but very slow: 1000 terms still get only about 3 digits.
  3. Wallis (1656): π/2 = (2/1·2/3)·(4/3·4/5)·(6/5·6/7)·… is a product instead of a sum. It's also slow, but it approaches π from below.
  4. The quarter circle again: the area under y = √(1−x²) from 0 to 1 is π/4. Add up 1000 thin rectangles, measuring each at its middle, which is the darts idea done in order instead of at random. That gives about 5 digits.
  5. Assignment 10: make a table of error versus terms for Leibniz (10, 100, 1000). Then try averaging two Leibniz sums in a row, N and N+1 terms. Why does that help so much?

Teacher's note (1979): This ends the fall semester. Write the four methods on the board with their error and their running time, and let the class vote on the "winner": Archimedes for speed, the strips for accuracy per line of code. Point out that the PET only keeps about 9 digits, so no method here can do better than 3.14159265. The record, held by computers far bigger than ours, is now millions of digits. Have a merry break, and see the Christmas assignment!

10 REM PI PART 2: LEIBNIZ, WALLIS, ARCHIMEDES
20 REM COMPUTER PROGRAMMING 1979, LESSON C1-10
100 REM --- ARCHIMEDES: DOUBLE THE POLYGON ---
110 PRINT "{CLR}ARCHIMEDES (SIDES, PI)"
120 S=1:N=6
130 FOR I=1 TO 6
140 S=S/SQR(2+SQR(4-S*S)):N=N*2
150 PRINT N;TAB(8);N*S/2
160 NEXT I
200 REM --- LEIBNIZ: 1-1/3+1/5-... ---
210 PRINT "LEIBNIZ, 1000 TERMS"
220 L=0:G=1
230 FOR K=0 TO 999:L=L+G/(2*K+1):G=-G:NEXT K
240 PRINT 4*L;" ERROR";ABS(4*L-{255})
300 REM --- WALLIS: (2/1*2/3)(4/3*4/5)... ---
310 PRINT "WALLIS, 1000 PAIRS"
320 W=1
330 FOR K=1 TO 1000:W=W*4*K*K/(4*K*K-1):NEXT K
340 PRINT 2*W;" ERROR";ABS(2*W-{255})
400 REM --- QUARTER CIRCLE: 1000 STRIPS ---
410 PRINT "QUARTER CIRCLE, 1000 STRIPS"
420 A=0:H=1/1000
430 FOR K=1 TO 1000:X=(K-.5)*H:A=A+SQR(1-X*X)*H:NEXT K
440 PRINT 4*A;" ERROR";ABS(4*A-{255})
500 REM --- THE TARGET ---
510 PRINT:PRINT "TRUE PI";{255}
520 END

Christmas break

  1. XMAS-1 · Christmas break assignment: The Twelve Days Gift Counter and a PET Christmas tree
XMAS-1 · Christmas break: Twelve Days Gift Counter and a PET Christmas tree

Here's a holiday puzzle for the break. In the song "The Twelve Days of Christmas", the true love gives 1 gift on day 1, then 1+2 on day 2, then 1+2+3 on day 3, and so on. How many gifts arrive in all twelve days? Guess first, then let the PET count. As a bonus, it draws a Christmas tree that twinkles.

  1. The gifts on day N are 1+2+…+N. A loop can add them up, but young Gauss's shortcut gives it at once: N*(N+1)/2.
  2. Keep a running total in T. The table prints on the right half of the screen using TAB(21). Did you guess 364? That's one gift for almost every day of the year!
  3. The tree is drawn with POKE straight into screen memory (32768 + 40×row + column). Each layer is a row of solid blocks (screen code 160) centered on column 10. The half-width W=INT(R/2)+(R-INT(R/4)*4) grows each row and pulls back in every fourth row, which gives the tree its tiers.
  4. For the twinkle, pick a random spot on the tree and poke in an ornament: a reversed ball (209), a reversed diamond (218) or a plain block again. Repeat 300 times, and finish with a star on top (42).
  5. Christmas assignment: work out how many of each gift arrive in total (12 partridges, 22 turtle doves, …). Which gift is the most numerous? Then change the tree to snow falling on a house.

Teacher's note (1979): The 364 answer surprises nearly everyone, and the gift-by-gift version ends in a tie: day 6 and day 7 gifts both total 42. That makes it a nice puzzle for the break. The tree shows students that the screen is just memory. Every year someone hands in a version that plays "Jingle Bells" through the cassette port, and it's worth extra credit.

10 REM TWELVE DAYS GIFT COUNTER AND A PET TREE
20 REM COMPUTER PROGRAMMING 1979, CHRISTMAS
100 REM --- THE GIFT TABLE, RIGHT HALF ---
110 PRINT "{CLR}";TAB(21);"TWELVE DAYS"
120 PRINT TAB(21);"DAY GIFTS TOTAL"
130 T=0
140 FOR N=1 TO 12
150 D=N*(N+1)/2:T=T+D
160 PRINT TAB(21);RIGHT$(" "+STR$(N),3);RIGHT$("   "+STR$(D),5);RIGHT$("   "+STR$(T),6)
170 NEXT N
180 PRINT:PRINT TAB(21);"ALL GIFTS:";T
200 REM --- DRAW THE TREE WITH POKE ---
210 SC=32768:X=RND(-25)
220 FOR R=0 TO 15
230 W=INT(R/2)+(R-INT(R/4)*4)
240 FOR C=10-W TO 10+W:POKE SC+(R+3)*40+C,160:NEXT C
250 NEXT R
260 FOR R=19 TO 21:POKE SC+R*40+9,160:POKE SC+R*40+10,160:POKE SC+R*40+11,160:NEXT R
300 REM --- TWINKLE THE ORNAMENTS ---
310 FOR I=1 TO 300
320 R=INT(RND(1)*16):W=INT(R/2)+(R-INT(R/4)*4)
330 C=10-W+INT(RND(1)*(2*W+1))
340 K=160:Z=RND(1):IF Z<.4 THEN K=209
350 IF Z>.8 THEN K=218
360 POKE SC+(R+3)*40+C,K
370 NEXT I
380 POKE SC+2*40+10,42
390 PRINT "{HOME}";:FOR I=1 TO 22:PRINT:NEXT I:PRINT "MERRY CHRISTMAS FROM ROOM 1979!"
400 END

Spring semester

  1. C2-1 · Strings: LEFT$, MID$, RIGHT$, palindromes and a secret code
  2. C2-2 · Arrays and sorting: bubble sort and selection sort
  3. C2-3 · Searching: linear search and binary search
  4. C2-4 · Newton's method: square roots by hand-holding
  5. C2-5 · Roots of equations by bisection
  6. C2-6 · Numerical integration: rectangles, trapezoids and Simpson
  7. C2-7 · Two-dimensional arrays: Pascal's triangle and matrices
  8. C2-8 · Graphics on the PET screen: plotting functions with POKE
  9. C2-9 · The four color theorem: coloring a map by backtracking
  10. C2-10 · Saving your work: data files on cassette and floppy, and your final project
C2-1 · Spring: Strings, palindromes and a secret code

Welcome back for the spring semester! So far we've mostly worked with numbers. BASIC can take strings (text) apart and put them back together too. Today we find palindromes, words that read the same backwards, and we build a secret code of the kind Julius Caesar used.

  1. The string toolkit: LEN(A$) is the length, and MID$(A$,I,1) is the I-th character. LEFT$ and RIGHT$ take the ends, and + joins strings together.
  2. Cleaning: keep only the letters. A character is a letter if C$>="A" AND C$<="Z". That way "A MAN, A PLAN…" loses its spaces and commas.
  3. Reversing: build R$=C$+R$ one letter at a time, so each new letter goes in front. If the cleaned string equals its reverse, it's a palindrome.
  4. Caesar's code: every character has a number, ASC("A")=65. Shift each letter K places, wrapping Z around to A: CHR$(65+(ASC(C$)-65+K)-INT((ASC(C$)-65+K)/26)*26). Shifting by 26−K decodes it again.
  5. Assignment 11: crack a secret message without the key. Try all 25 shifts and look for English words, or count which letter appears most often (it's probably E).

Teacher's note (1979): String handling is where Microsoft BASIC on the PET really shines compared to the older school timeshare BASICs, which often had no strings at all. Students swap coded notes all week, which is exactly the point. Then show them how frequency counting breaks Caesar in a minute, and talk about why real codes need to be harder.

10 REM STRINGS, PALINDROMES AND A SECRET CODE
20 REM COMPUTER PROGRAMMING 1979, LESSON C2-1
100 REM --- PALINDROME TESTER ---
110 PRINT "{CLR}PALINDROMES?"
120 READ A$:IF A$="END" THEN 300
130 GOSUB 800
140 R$="":FOR I=1 TO LEN(W$):R$=MID$(W$,I,1)+R$:NEXT I
150 Y$="NO ":IF W$=R$ THEN Y$="YES"
160 PRINT Y$;" ";A$
170 GOTO 120
300 REM --- CAESAR'S CODE, SHIFT 3 ---
310 PRINT:PRINT "CAESAR CODE, KEY 3"
320 M$="MEET ME AT THE LIBRARY":K=3:GOSUB 900
330 PRINT "PLAIN: ";M$:PRINT "CODED: ";S$
340 M$=S$:K=26-3:GOSUB 900
350 PRINT "BACK:  ";S$
360 END
800 REM --- KEEP ONLY LETTERS: A$ TO W$ ---
810 W$="":FOR I=1 TO LEN(A$):C$=MID$(A$,I,1)
820 IF C$>="A" AND C$<="Z" THEN W$=W$+C$
830 NEXT I:RETURN
900 REM --- SHIFT LETTERS OF M$ BY K: S$ ---
910 S$="":FOR I=1 TO LEN(M$):C$=MID$(M$,I,1)
920 IF C$<"A" OR C$>"Z" THEN 950
930 N=ASC(C$)-65+K:N=N-INT(N/26)*26
940 C$=CHR$(65+N)
950 S$=S$+C$:NEXT I:RETURN
1000 REM --- WORDS TO TEST ---
1010 DATA RACECAR,PIXEL,LEVEL,"NEVER ODD OR EVEN"
1020 DATA "A MAN, A PLAN, A CANAL: PANAMA"
1030 DATA COMPUTER,"WAS IT A CAT I SAW?",END
C2-2 · Spring: Arrays and sorting

Putting things in order is one of the jobs computers do most: grade lists, phone books, high scores. Today we sort an array two ways and count the work each way does, then we alphabetize a list of names.

  1. Fill A(1)…A(20) with random numbers from 1 to 99, and copy them into B() so both methods get the same data.
  2. Bubble sort: walk through the list comparing neighbors, and swap any pair that's out of order. After each pass the biggest number has "bubbled" to the end. If a pass makes no swaps, the list is sorted and we can stop early.
  3. A swap needs a spare variable: T=A(J):A(J)=A(J+1):A(J+1)=T. Try doing it without T and see what goes wrong!
  4. Selection sort: find the smallest number left and swap it into the next place. It always makes n(n−1)/2 comparisons, which is 190 for 20 numbers. That is often fewer than bubble sort, and it makes far fewer swaps. The program counts both.
  5. Strings compare too: "ADA"<"BOB" is true, so the same bubble sort alphabetizes names.
  6. Assignment 12: double the list to 40 numbers. How do the comparison counts change? Predict first, then run it.

Teacher's note (1979): Line the class up by height and have them act out the bubble sort; it's unforgettable. The point of the counters is the n² growth: twice the data means four times the work. That's why the faster sorts (Shell sort, quicksort) mattered so much on machines this slow.

10 REM ARRAYS AND SORTING
20 REM COMPUTER PROGRAMMING 1979, LESSON C2-2
100 REM --- SETUP: 20 RANDOM NUMBERS ---
110 N=20:DIM A(20),B(20),N$(8):X=RND(-1979)
120 FOR I=1 TO N:A(I)=INT(RND(1)*99)+1:B(I)=A(I):NEXT I
130 PRINT "{CLR}UNSORTED:":GOSUB 900
200 REM --- BUBBLE SORT ON A() ---
210 CC=0:SW=0
220 FL=0:FOR J=1 TO N-1:CC=CC+1
230 IF A(J)>A(J+1) THEN T=A(J):A(J)=A(J+1):A(J+1)=T:SW=SW+1:FL=1
240 NEXT J:IF FL THEN 220
250 PRINT "BUBBLE SORTED:":GOSUB 900
260 PRINT "COMPARES";CC;" SWAPS";SW
300 REM --- SELECTION SORT ON B() ---
310 CC=0:SW=0
320 FOR I=1 TO N-1:M=I
330 FOR J=I+1 TO N:CC=CC+1:IF B(J)<B(M) THEN M=J
340 NEXT J
350 IF M<>I THEN T=B(I):B(I)=B(M):B(M)=T:SW=SW+1
360 NEXT I
370 PRINT "SELECTION SORT:":PRINT "COMPARES";CC;" SWAPS";SW
400 REM --- ALPHABETIZE NAMES ---
410 FOR I=1 TO 8:READ N$(I):NEXT I
420 FL=0:FOR J=1 TO 7
430 IF N$(J)>N$(J+1) THEN T$=N$(J):N$(J)=N$(J+1):N$(J+1)=T$:FL=1
440 NEXT J:IF FL THEN 420
450 PRINT:PRINT "NAMES:":FOR I=1 TO 8:PRINT N$(I);" ";:NEXT I:PRINT
460 END
900 REM --- PRINT A() ---
910 FOR I=1 TO N:PRINT A(I);:NEXT I:PRINT:RETURN
1000 DATA WANDA,ADA,KEN,BETTY,GRACE,ALAN,DON,CAROL
C2-3 · Spring: Searching

Now that we can sort, we can search much faster. Today we race two ways of finding a number in a list of 500: checking every item in turn (linear search), and repeatedly cutting a sorted list in half (binary search). It's the same trick as guessing a number from 1 to 100 with "higher" or "lower".

  1. Make a sorted list: A(I)=7*I-3 for I = 1 to 500, which gives 4, 11, 18, … 3497.
  2. Linear search: start at A(1) and step forward until you find the target or run off the end. On average it looks at half the list, and if the number isn't there it looks at all 500.
  3. Binary search: keep a low end LO and a high end HI. Look at the middle, MI=INT((LO+HI)/2). If the target is bigger, move LO=MI+1; if smaller, move HI=MI-1. Each look throws away half of what's left.
  4. The program traces one binary search step by step, then times both methods on five targets (one of them missing) by counting looks.
  5. Assignment 13: how many looks can binary search need, at most, for 1000 items? For a million? (Hint: count how many times you can halve.)

Teacher's note (1979): Play "guess my number" first; every student discovers the halving strategy on their own. Then show that 500 items take at most 9 looks, and a phone book of a million names only 20. The catch is that binary search needs the list sorted first, which is why last week's lesson came first.

10 REM SEARCHING: LINEAR AND BINARY
20 REM COMPUTER PROGRAMMING 1979, LESSON C2-3
100 REM --- A SORTED LIST OF 500 ---
110 N=500:DIM A(500)
120 FOR I=1 TO N:A(I)=7*I-3:NEXT I
130 PRINT "{CLR}LIST: 4, 11, 18 ... 3497"
200 REM --- TRACE ONE BINARY SEARCH ---
210 TG=2454:PRINT "BINARY SEARCH FOR";TG
220 LO=1:HI=N:SP=0
230 IF LO>HI THEN PRINT " NOT FOUND":GOTO 300
240 MI=INT((LO+HI)/2):SP=SP+1
250 PRINT " LOOK";SP;"AT A(";MI;") =";A(MI)
260 IF A(MI)=TG THEN PRINT " FOUND!":GOTO 300
270 IF A(MI)<TG THEN LO=MI+1:GOTO 230
280 HI=MI-1:GOTO 230
300 REM --- RACE: COUNT THE LOOKS ---
310 PRINT:PRINT "TARGET  LINEAR  BINARY"
320 FOR Q=1 TO 5:READ TG
330 L=0:FOR I=1 TO N:L=L+1:IF A(I)=TG THEN I=N
340 NEXT I
350 LO=1:HI=N:B=0
360 IF LO>HI THEN 400
370 MI=INT((LO+HI)/2):B=B+1:IF A(MI)=TG THEN 400
380 IF A(MI)<TG THEN LO=MI+1:GOTO 360
390 HI=MI-1:GOTO 360
400 PRINT TG;TAB(8);L;TAB(16);B
410 NEXT Q
420 PRINT "(1000 IS MISSING FROM THE LIST)"
430 END
500 DATA 4,1754,2454,3497,1000
C2-4 · Spring: Newton's method square roots

How does a calculator find √2? Not with a table: it guesses and improves. Newton's method, which the Babylonians already used almost 4,000 years ago, turns any rough guess into a near-perfect square root in just a few steps.

  1. If X is a guess for √N, then N/X is on the other side of the true root. When X is too big, N/X is too small, and the other way round. So their average is a better guess: X=(X+N/X)/2.
  2. Repeat until the guess stops changing: keep the old guess in G and stop when ABS(X-G)<1E-8.
  3. Watch the trace for √2, starting from 1. The number of correct digits roughly doubles every step (the errors fall from about 0.1 to 0.002, 0.000002, then 0.000000000002, more digits than the PET can display). That is called quadratic convergence.
  4. The table then compares Newton with BASIC's own SQR for several numbers and counts the steps each needs. Even √1000000, starting from a poor guess of 1, takes only 15. The guess roughly halves at first, until it gets close, and then the digits double.
  5. Assignment 14: Newton works for cube roots too, using X=(2*X+N/(X*X))/3. Write it, and check that X*X*X gives N back.

Teacher's note (1979): Have students do two steps of √10 by hand first; they'll be amazed when the PET agrees with them. The digit-doubling is the real lesson, because it's why Newton's idea is inside every calculator and computer. Point out that the stopping test compares guesses, not the answer, since a program can't know the answer in advance.

10 REM NEWTON'S METHOD SQUARE ROOTS
20 REM COMPUTER PROGRAMMING 1979, LESSON C2-4
100 REM --- TRACE: SQUARE ROOT OF 2 ---
110 PRINT "{CLR}NEWTON: SQUARE ROOT OF 2"
120 N=2:X=1:PRINT " START";X
130 FOR K=1 TO 6
140 X=(X+N/X)/2
150 PRINT " STEP";K;X;" ERR";ABS(X-SQR(2))
160 NEXT K
200 REM --- TABLE: NEWTON VS SQR ---
210 PRINT:PRINT "N";TAB(9);"NEWTON";TAB(21);"SQR";TAB(33);"STEPS"
220 FOR Q=1 TO 6:READ N
230 X=1:K=0
240 G=X:X=(X+N/X)/2:K=K+1
250 IF ABS(X-G)>=1E-8*X THEN 240
260 PRINT N;TAB(8);X;TAB(20);SQR(N);TAB(33);K
270 NEXT Q
280 END
300 DATA 2,3,10,144,12345,1000000
C2-5 · Spring: Bisection

Newton's method is fast, but it needs a good formula and it can wander off. Bisection is slow and steady, and it never fails. If a smooth curve is below zero at one end of an interval and above zero at the other, it must cross zero somewhere in between. So cut the interval in half, keep the half where the sign changes, and repeat.

  1. Define the function: DEF FN F(X)=X*X*X-X-2. FN F(1) = −2 and FN F(2) = 4, so there's a root between 1 and 2.
  2. Find the middle, M=(A+B)/2. If FN F(A)*FN F(M)<=0, the signs differ on the left, so the root is in [A,M] and we set B=M. Otherwise set A=M.
  3. Each step halves the interval, so after K steps it is (B−A)/2K wide. To get within 0.0001 of a width of 1 takes 14 steps, because 214 = 16384. That's one more correct digit every 3 or 4 steps, slower than Newton's doubling but guaranteed.
  4. The second run solves an equation you can't rearrange by algebra, COS(X)=X, by finding where COS(X)−X crosses zero.
  5. Assignment 15: use bisection to find where 2X = X + 3, and count the steps. Then try Newton on the same problem. Which would you trust on a test?

Teacher's note (1979): Bisection is the binary search from C2-3, applied to a curve instead of a list. Students who see that connection have understood the whole semester so far. Have them predict the step count before running it. The guarantee is what makes this method the safe choice in engineering programs.

10 REM BISECTION: CUT THE INTERVAL IN HALF
20 REM COMPUTER PROGRAMMING 1979, LESSON C2-5
100 REM --- F(X)=X^3-X-2 ON [1,2] ---
110 DEF FN F(X)=X*X*X-X-2
120 PRINT "{CLR}SOLVE X*X*X-X-2=0 ON [1,2]"
130 PRINT "STEP";TAB(6);"A";TAB(17);"B";TAB(28);"F(M)"
140 A=1:B=2:K=0
200 REM --- HALVE UNTIL NARROW ---
210 M=(A+B)/2:K=K+1
220 PRINT K;TAB(5);A;TAB(16);B;TAB(27);INT(FN F(M)*1E4+.5)/1E4
230 IF FN F(A)*FN F(M)<=0 THEN B=M:GOTO 250
240 A=M
250 IF B-A>1E-4 THEN 210
260 PRINT "ROOT =";(A+B)/2;"IN";K;"STEPS"
300 REM --- COS(X)=X ON [0,1] ---
310 DEF FN G(X)=COS(X)-X
320 A=0:B=1:K=0
330 M=(A+B)/2:K=K+1
340 IF FN G(A)*FN G(M)<=0 THEN B=M:GOTO 360
350 A=M
360 IF B-A>1E-6 THEN 330
370 PRINT "COS(X)=X AT";(A+B)/2;"(";K;"STEPS)"
380 END
C2-6 · Spring: Numerical integration

In C1-10 we found π by adding up thin strips under a curve. That idea, the integral, is the area under a curve, and it's one of the most useful things a computer can work out. Today we compare three ways of adding up the strips and see how much smarter shapes beat more strips.

  1. Rectangles (left sum): split [A,B] into N strips of width H=(B-A)/N. Each strip's height is the curve at its left edge: add up FN F(A+I*H)*H.
  2. Trapezoids: join the top corners of each strip with a straight line. That works out to the average of the left and right heights, and it is far better for the same work.
  3. Simpson's rule (1743): fit little parabolas through each pair of strips, weighting the heights 1, 4, 2, 4, 2, …, 4, 1 and multiplying the total by H/3. N must be even.
  4. The test is ∫01 EXP(X) dX, whose exact answer is e−1 = 1.718281828. The table shows each method's error as N doubles. Rectangle error halves, trapezoid error drops by 4 and Simpson's by 16 each time. A small helper subroutine at line 900 prints each error with just two digits, such as 4.6E-03, so the table fits in 40 columns.
  5. Assignment 16: use Simpson's rule on 4/(1+X*X) from 0 to 1. The answer is π! How many strips do you need for 8 digits?

Teacher's note (1979): This connects straight to the calculus class down the hall. Students who can't do an integral by hand can still compute it, which is how engineers design bridges and rockets. Make sure they notice that Simpson with 8 strips beats rectangles with a thousand: a better idea beats brute force.

10 REM NUMERICAL INTEGRATION
20 REM COMPUTER PROGRAMMING 1979, LESSON C2-6
100 REM --- AREA UNDER EXP(X), 0 TO 1 ---
110 DEF FN F(X)=EXP(X)
120 A=0:B=1:EX=EXP(1)-1
130 PRINT "{CLR}AREA UNDER EXP(X), 0 TO 1"
135 PRINT "EXACT: E-1 =";EX
140 PRINT "ERRORS:":PRINT "  N";TAB(6);"RECTANGLE";TAB(17);"TRAPEZOID";TAB(28);"SIMPSON"
200 REM --- DOUBLE N EACH ROW ---
210 N=2
220 H=(B-A)/N:LS=0:TR=0:SM=0
230 FOR I=0 TO N:Y=FN F(A+I*H)
240 IF I<N THEN LS=LS+Y*H
250 W=2:IF I=0 OR I=N THEN W=1
260 TR=TR+W*Y*H/2
270 V=2:IF I-INT(I/2)*2=1 THEN V=4
280 IF I=0 OR I=N THEN V=1
290 SM=SM+V*Y*H/3
300 NEXT I
310 PRINT RIGHT$("  "+STR$(N),4);TAB(6);
320 E=ABS(LS-EX):GOSUB 900:PRINT E$;TAB(17);
330 E=ABS(TR-EX):GOSUB 900:PRINT E$;TAB(28);
340 E=ABS(SM-EX):GOSUB 900:PRINT E$
350 N=N*2:IF N<=128 THEN 220
400 REM --- FINAL ANSWER AT N=128 ---
410 PRINT:PRINT "SIMPSON, 128 STRIPS:";SM
420 END
900 REM --- ERROR E AS SHORT TEXT, E.G. 4.6E-03 ---
910 Q=INT(LOG(E)/LOG(10)):M=INT(E/10^Q*10+.5)/10
920 IF M>=10 THEN M=1:Q=Q+1
930 E$=MID$(STR$(M),2)+"E"+STR$(Q):RETURN
C2-7 · Spring: 2D arrays: Pascal's triangle and matrices

So far our arrays have been single rows of numbers. BASIC also allows two-dimensional arrays, tables with rows and columns, such as DIM P(10,10). Today we build Pascal's triangle in one and multiply two matrices.

  1. P(N,K) is the number in row N, position K. Each edge is 1, and each inside number is the sum of the two above it: P(N,K)=P(N-1,K-1)+P(N-1,K). Nested FOR loops fill the whole table. Start N at 1, with P(0,0) set by hand: a PET FOR loop always runs at least once, even FOR K=1 TO -1, which would reach for the nonexistent P(−1,0).
  2. Printing each row with TAB(2*(8-N)) in front centers it into the famous triangle. The numbers also count combinations: row 8, position 3 is 56, the number of ways to pick 3 people from 8.
  3. A matrix is just a 2D array of numbers. To multiply A by B, each answer C(I,J) is row I of A times column J of B, added up: C(I,J)=C(I,J)+A(I,K)*B(K,J). That's three nested loops.
  4. The program reads two 3×3 matrices from DATA lines, multiplies them, and prints all three. Then it multiplies A by the identity matrix (1s on the diagonal), which gives A back, just as multiplying by 1 does.
  5. Assignment 17: add up each row of Pascal's triangle. What pattern do the totals make? Then check whether A×B equals B×A.

Teacher's note (1979): Pascal's triangle hides surprises; have students shade the odd numbers on graph paper and watch a triangle-of-triangles appear. The matrix half is for the algebra II crowd. Point out that A×B ≠ B×A, the first multiplication most students have met that doesn't commute. Memory check: DIM P(10,10) uses 121 elements, and the 0 row and column count too!

10 REM 2D ARRAYS: PASCAL'S TRIANGLE AND MATRICES
20 REM COMPUTER PROGRAMMING 1979, LESSON C2-7
100 REM --- BUILD PASCAL'S TRIANGLE ---
110 DIM P(10,10),A(3,3),B(3,3),C(3,3)
120 P(0,0)=1:FOR N=1 TO 8:P(N,0)=1:P(N,N)=1
130 FOR K=1 TO N-1:P(N,K)=P(N-1,K-1)+P(N-1,K):NEXT K
140 NEXT N
150 PRINT "{CLR}PASCAL'S TRIANGLE"
160 FOR N=0 TO 8:PRINT TAB(2*(8-N));
170 FOR K=0 TO N:PRINT RIGHT$("   "+STR$(P(N,K)),4);:NEXT K
180 PRINT:NEXT N
200 REM --- READ TWO 3X3 MATRICES ---
210 FOR I=1 TO 3:FOR J=1 TO 3:READ A(I,J):NEXT J,I
220 FOR I=1 TO 3:FOR J=1 TO 3:READ B(I,J):NEXT J,I
300 REM --- MULTIPLY: C = A X B ---
310 GOSUB 800
320 PRINT:PRINT "   A";TAB(10);"X   B";TAB(21);"=     C"
330 FOR I=1 TO 3:FOR J=1 TO 3:PRINT RIGHT$("  "+STR$(A(I,J)),3);:NEXT J
340 PRINT "  ";:FOR J=1 TO 3:PRINT RIGHT$("  "+STR$(B(I,J)),3);:NEXT J
350 PRINT "  ";:FOR J=1 TO 3:PRINT RIGHT$("    "+STR$(C(I,J)),5);:NEXT J
360 PRINT:NEXT I
400 REM --- A X IDENTITY GIVES A BACK ---
410 FOR I=1 TO 3:FOR J=1 TO 3:B(I,J)=-(I=J):NEXT J,I
420 GOSUB 800:Y$="YES"
430 FOR I=1 TO 3:FOR J=1 TO 3:IF C(I,J)<>A(I,J) THEN Y$="NO"
440 NEXT J,I:PRINT:PRINT "A X IDENTITY = A? ";Y$
450 END
800 REM --- C = A X B, THREE NESTED LOOPS ---
810 FOR I=1 TO 3:FOR J=1 TO 3:C(I,J)=0
820 FOR K=1 TO 3:C(I,J)=C(I,J)+A(I,K)*B(K,J):NEXT K
830 NEXT J,I:RETURN
900 DATA 1,2,3,0,1,4,5,6,0
910 DATA 2,0,1,1,3,0,0,1,2
C2-8 · Spring: PET screen graphics: plotting functions with POKE

The PET's screen is really 1000 bytes of memory, 40 columns × 25 rows starting at address 32768. POKE a character code into one of those bytes and it appears at once. Today we turn the screen into graph paper and plot functions, with axes and two curves.

  1. The address of column C, row R is 32768+40*R+C. Rows count down from the top, so a bigger Y has to mean a smaller R.
  2. Axes: poke a horizontal line character (screen code 64) along the middle row and a vertical line (93) down the middle column, with a cross (91) where they meet.
  3. Scaling is the key idea. Column C stands for X=(C-20)/20*π, so the screen runs from −π to π. A Y value turns into a row with R=11-INT(Y*10+.5), ten rows per unit.
  4. Plot SIN(X) with balls (81) and X*X/4-1 with stars (42). The program skips any point whose row falls off the screen, because a POKE outside screen memory could crash the program.
  5. Assignment 18: add COS(X) with a third symbol. Then plot TAN(X). What happens near ±π/2, and why does the row check matter?

Teacher's note (1979): This is the lesson students show their parents. The PET has no high-resolution graphics, so every graph is made of characters. Talk about resolution: there are only 40 columns, so a curve has only 40 points. That's also why the PET's graphics characters with quarter blocks were so popular for drawing. And remind everyone: never POKE random addresses, or you'll be pressing the reset switch!

10 REM PET SCREEN GRAPHICS: PLOTTING WITH POKE
20 REM COMPUTER PROGRAMMING 1979, LESSON C2-8
100 REM --- CLEAR AND DRAW THE AXES ---
110 PRINT "{CLR}";:SC=32768
120 FOR C=0 TO 39:POKE SC+40*11+C,64:NEXT C
130 FOR R=0 TO 22:POKE SC+40*R+20,93:NEXT R
140 POKE SC+40*11+20,91
200 REM --- PLOT SIN(X) WITH BALLS ---
210 FOR C=0 TO 39
220 X=(C-20)/20*{255}:Y=SIN(X):K=81:GOSUB 900
230 NEXT C
300 REM --- PLOT X*X/4-1 WITH STARS ---
310 FOR C=0 TO 39
320 X=(C-20)/20*{255}:Y=X*X/4-1:K=42:GOSUB 900
330 NEXT C
400 REM --- LABELS BELOW THE GRAPH ---
410 PRINT "{HOME}";:FOR I=1 TO 23:PRINT:NEXT I
420 PRINT CHR$(113);" = SIN(X)   * = X*X/4-1";
430 END
900 REM --- PLOT Y AS SYMBOL K IN COLUMN C ---
910 R=11-INT(Y*10+.5)
920 IF R<0 OR R>22 THEN RETURN
930 POKE SC+40*R+C,K:RETURN
C2-9 · Spring: The four color theorem: map coloring by backtracking

Cartographers have long believed that four colors are enough for any map, so that no two countries sharing a border get the same color. In 1976 Appel and Haken at the University of Illinois finally proved it, and they needed over 1000 hours of computer time to do it. Today our PET colors a map of its own, using a method called backtracking.

  1. The map is stored as five DATA strings. Each letter is one region (A to F). The program compares every cell with the cell to its right and the one below it. When the letters differ, those two regions are neighbors, and it sets AD(P,Q)=1.
  2. Backtracking: give region K the next color. If a neighbor that's already colored has the same color, try the next color (line 550). Once all colors are used up, erase K and go back to region K−1 to change its choice (line 535). When K passes N, the whole map is done. If K falls to 0, every possibility has been tried.
  3. First the program tries 3 colors. Region E touches all five others, and those five form a ring. A ring of five can't be colored with only two colors, so with E taking a third, 3 colors is impossible. The program finds this out on its own, then succeeds with 4 colors and prints the map as R, G, B, Y.
  4. Count the tries. Backtracking is far faster than testing all 46 = 4096 colorings, because it gives up on a bad partial coloring as soon as it hits a clash.
  5. Assignment 19: draw a map of the six New England states on graph paper, enter it as DATA, and color it. How many tries did it take? Does it ever need the fourth color?

Teacher's note (1979): Some mathematicians still don't accept the 1976 proof, because no person can check all of it by hand. Is a proof done by computer really a proof? This makes a great class debate. Backtracking will come back on the final exam: it is how computers solve mazes, the eight queens puzzle and Sudoku-style number puzzles.

10 REM FOUR COLOR MAP BY BACKTRACKING
20 REM PROGRAMMING 1979, LESSON C2-9
100 REM --- READ THE MAP ---
110 N=6:H=5:W=12
115 DIM M$(H),AD(N,N),CL(N)
120 FOR R=1 TO H:READ M$(R):NEXT R
200 REM --- FIND NEIGHBORS ---
210 FOR R=1 TO H:FOR C=1 TO W
220 P=ASC(MID$(M$(R),C,1))-64
230 IF C=W THEN 240
235 Q=ASC(MID$(M$(R),C+1))-64:GOSUB 800
240 IF R=H THEN 250
245 Q=ASC(MID$(M$(R+1),C))-64:GOSUB 800
250 NEXT C:NEXT R
260 PRINT "{CLR}THE MAP:":FOR R=1 TO H
270 PRINT "  ";M$(R):NEXT R
300 REM --- TRY 3 COLORS, THEN 4 ---
310 FOR NC=3 TO 4:GOSUB 500
320 PRINT NC;"COLORS:";T;"TRIES, ";
330 IF K>0 THEN 340
335 PRINT "IMPOSSIBLE":NEXT NC
340 PRINT "SUCCESS!"
350 FOR R=1 TO H:PRINT "  ";
360 FOR C=1 TO W
370 P=ASC(MID$(M$(R),C,1))-64
380 PRINT MID$("RGBY",CL(P),1);
390 NEXT C:PRINT:NEXT R
400 FOR I=1 TO N:PRINT CHR$(64+I);"=";
410 PRINT MID$("RGBY",CL(I),1);" ";
415 NEXT I
420 PRINT:END
500 REM --- BACKTRACKING SEARCH ---
510 FOR I=1 TO N:CL(I)=0:NEXT I:K=1:T=0
520 CL(K)=CL(K)+1:T=T+1
530 IF CL(K)<=NC THEN 540
535 CL(K)=0:K=K-1:GOTO 580
540 FOR J=1 TO K-1
550 IF AD(K,J) AND CL(J)=CL(K) THEN 520
560 NEXT J
570 K=K+1:IF K>N THEN RETURN
580 IF K=0 THEN RETURN
590 GOTO 520
800 REM --- P AND Q ARE NEIGHBORS ---
810 IF P<>Q THEN AD(P,Q)=1:AD(Q,P)=1
820 RETURN
900 DATA AAAABBBBBCCC,AAAEEEEEECCC
910 DATA FFFEEEEEECCC,FFFEEEEEEDDD
920 DATA FFFFFDDDDDDD
C2-10 · Spring: Data files on cassette and floppy, and the final project

Everything in memory disappears when the PET is switched off. To keep data, a program writes it to a file on cassette or floppy disk. Commodore BASIC uses four statements for this: OPEN, PRINT#, INPUT# and CLOSE. Our lab has a dual floppy drive, device 8, and this program really writes a file to the disk in drive 0 and reads it back. This is the last lesson, and after it comes your final project.

  1. OPEN 1,8,2,"@0:GRADES,S,W" opens file number 1 on device 8 (the floppy drive) using channel 2. The file is called GRADES, on drive 0, it is a Sequential file, and it is opened for Writing. The @ means "replace it if it's already there", so you can RUN the program more than once. Device 1 would be the cassette instead: OPEN 1,1,1,"GRADES".
  2. PRINT#1,X works just like PRINT, but sends its output to the file. Put each item on a line of its own, as lines 130 to 150 do. The count goes first, so whoever reads the file later knows how many records follow. Always CLOSE a file you have written, or its last records may never reach the disk.
  3. The drive has its own little computer inside, and you talk to it on channel 15. INPUT#15,EN,EM$,ET,ES reads an error number, a message, a track and a sector. An error number of 0 means OK, and 62 means FILE NOT FOUND.
  4. Reading is the mirror image: open the file with ,S,R, then INPUT#2,N for the count and a loop that does INPUT#2,NB$(I),SB(I). The variable ST becomes 64 once the end of the file has been read. Notice that the report is made from the data read back from the disk, not from the DATA lines.
  5. Afterwards, type LOAD"$",8 and then LIST to see the disk's directory, which shows GRADES as a SEQ file. SAVE"MYPROG",8 saves your program onto the disk and LOAD"MYPROG",8 brings it back. Disks are kept in this browser, and you can use the drive panel under the screen to format, export and import them.
  6. Final project: write a program of at least 100 lines that keeps its data in a file, with a menu for adding, listing, searching and sorting records. Some ideas: a record collection, a stamp album, the team's batting averages, or a recipe file. Use at least three things from this year: string functions, sorting, searching, arrays or graphics. It is due in the last week of May, along with a listing and a user's guide.

Teacher's note (1979): We have only two floppy drives for the whole lab, so book disk time on the sign-up sheet. Everyone else saves to cassette. Remind students to label their tapes and disks and to keep a second copy, because tapes stretch and disks get coffee spilled on them. The listing must be printed on the lab's printer: start it with OPEN 4,4:CMD 4:LIST, and finish with PRINT#4:CLOSE 4. It has been a pleasure teaching you all this year. Have a great summer!

10 REM DATA FILES AND THE FINAL PROJECT
20 REM PROGRAMMING 1979, LESSON C2-10
100 REM --- WRITE THE FILE ---
110 PRINT "{CLR}WRITING GRADES FILE..."
120 OPEN 1,8,2,"@0:GRADES,S,W"
130 READ N:PRINT#1,N
140 FOR I=1 TO N:READ NA$,SC
150 PRINT#1,NA$:PRINT#1,SC
160 NEXT I
170 CLOSE 1
200 REM --- CHECK THE DRIVE ---
210 OPEN 15,8,15
220 INPUT#15,EN,EM$,ET,ES
230 PRINT "DRIVE SAYS:";EN;EM$
240 CLOSE 15
250 IF EN THEN PRINT "THE FILE WASN'T SAVED. FREE SOME":PRINT "SPACE (FORMAT OR SCRATCH), RUN AGAIN.":END
300 REM --- READ IT BACK ---
310 PRINT "READING IT BACK..."
320 OPEN 2,8,3,"0:GRADES,S,R"
330 INPUT#2,N:DIM NB$(N),SB(N)
340 FOR I=1 TO N
350 INPUT#2,NB$(I),SB(I)
360 NEXT I
370 PRINT "LAST STATUS (ST) =";ST
380 CLOSE 2
400 REM --- REPORT FROM THE FILE ---
410 PRINT:PRINT "CLASS REPORT":T=0:B=1
420 FOR I=1 TO N:T=T+SB(I)
430 IF SB(I)>SB(B) THEN B=I
440 PRINT NB$(I);TAB(10);SB(I)
450 NEXT I
460 PRINT "AVERAGE";TAB(10);T/N
470 PRINT "TOP";TAB(10);NB$(B)
475 Q$=CHR$(34):PRINT
480 PRINT "TRY: LOAD";Q$;"$";Q$;",8"
490 PRINT "THEN LIST TO SEE THE DISK."
500 END
900 DATA 4
910 DATA ANN,92,BOB,85,CARLOS,97,DEE,88

CS 100 · Files and records

This is the first of three hands-on Advanced Class courses. In CS 100 you make your programs remember. You'll store records in files on the floppy drive, then read, search, update, sort and merge them. Every lesson has a program you can try with ▶ Run it and an assignment to do yourself, and the course ends with a project. After it come CS 200 (data structures) and CS 300 (parsers, interpreters and the adventure engine). You should know the material in C2-10 first.

  1. CS 100-1 · Records and fields: a roster file, written and read back
  2. CS 100-2 · Adding to a file and updating one: append mode, then copy and rename
  3. CS 100-3 · Searching a file and printing reports
  4. CS 100-4 · Sorting a file in memory
  5. CS 100-5 · Keys and an index file
  6. CS 100-6 · Merging two sorted files
  7. CS 100 project · Your own record keeper
CS 100-1 · Records and fields: a roster file, written and read back

A file is a list of records. A record describes one thing, such as one student, and it is made of fields: a name, a grade and a club. On a sequential file the fields are simply written one after another, and the program that reads them must know what order they come in. This lesson writes a club roster to the disk and reads it back until the file runs out.

  1. The command channel first. Line 110 opens channel 15 once and leaves it open. After each OPEN, the subroutine at 900 reads the drive's status. Any error number other than 0 stops the program with the drive's own message, so a missing disk or file never leaves you guessing.
  2. Writing a record (line 170) takes three PRINT# statements, one per field, and each field goes on a line of its own. Never put a comma or a colon inside a string field: INPUT# treats both as separators, so "SMITH, JO" would come back as two fields.
  3. No count this time. In C2-10 the file began with a record count. This file doesn't, so the reader loops until the drive says the end has been reached: ST becomes 64 after the last field is read. Save ST into S straight away (line 350), because the next PRINT can change it.
  4. Reading a record is one INPUT#2,NA$,GR,CL$ statement that reads the fields in the same order they were written. Lines 360 and 370 pad the fields so the columns line up, and 380 keeps a count and a total for the report.
  5. Afterwards, type LOAD"$",8 and then LIST. ROSTER is listed as a 1-block SEQ file.
  6. Assignment CS 100-1: design your own record with at least four fields, perhaps a book (title, author, year, pages) or a record album. Write ten records, then read them back and print a table with a total and an average. Then break it on purpose: put a comma in one title, and explain what the reader does and why.

Teacher's note: Make students draw the record layout on paper before they write any code: the field names, their types and their order. Nearly every file bug in this course comes from a writer and a reader that disagree about the layout. Lesson 2 shows why sequential files are easy to add to but awkward to change.

10 REM CS 100 LESSON 1: RECORDS AND FIELDS
20 REM A ROSTER FILE, WRITTEN AND READ BACK
100 PRINT "{CLR}CS 100-1  RECORDS AND FIELDS"
110 OPEN 15,8,15
120 OPEN 2,8,2,"@0:ROSTER,S,W"
130 GOSUB 900
140 N=0
150 READ NA$:IF NA$="*" THEN 200
160 READ GR,CL$
170 PRINT#2,NA$:PRINT#2,GR:PRINT#2,CL$
180 N=N+1:GOTO 150
200 CLOSE 2:GOSUB 900
210 PRINT "WROTE";N;"RECORDS, 3 FIELDS EACH"
220 PRINT
300 REM --- READ UNTIL END OF FILE ---
310 OPEN 2,8,2,"0:ROSTER,S,R"
320 GOSUB 900
330 PRINT "{RVS}NAME      GRADE CLUB      {OFF}"
340 C=0:T=0
350 INPUT#2,NA$,GR,CL$:S=ST
360 PRINT LEFT$(NA$+"          ",10);
370 PRINT RIGHT$("  "+STR$(GR),3);"   ";CL$
380 C=C+1:T=T+GR
390 IF S=0 THEN 350
400 CLOSE 2:CLOSE 15
410 PRINT
420 PRINT "READ";C;"RECORDS"
430 PRINT "AVERAGE GRADE";INT(T/C*10)/10
440 END
900 REM --- CHECK THE DRIVE ---
910 INPUT#15,EN,EM$,ET,ES
920 IF EN=0 THEN RETURN
930 PRINT "DISK ERROR";EN;EM$
935 IF EN=72 THEN PRINT "THE FILE WASN'T SAVED. FREE SOME":PRINT "SPACE (FORMAT OR SCRATCH), RUN AGAIN."
940 CLOSE 2:CLOSE 15:END
3000 DATA ADA,10,CHESS
3010 DATA BEN,11,ROBOTICS
3020 DATA CARMEN,9,CHESS
3030 DATA DMITRI,12,BAND
3040 DATA ELLA,10,ROBOTICS
3050 DATA FARID,11,BAND
3060 DATA *
CS 100-2 · Adding to a file and updating one: append mode, then copy and rename

Every CS 100 lesson starts from the same six-student roster. If there isn't a ROSTER on the disk yet, the lesson writes one from its DATA lines, so you can run the lessons in any order. A sequential file is easy to add to: you just write more records on the end. Changing a record in the middle is harder, because you can't rewrite one spot of a sequential file. You copy the whole file to a new one, make the change on the way through, then swap the new file in for the old. That pattern is called copy and rename, and programmers have used it for files and tapes for decades.

  1. Does the file exist? Line 120 tries to open ROSTER and reads the drive's status. Error 62 means there's no roster yet (perhaps you haven't run CS 100-1), so the subroutine at 800 makes one from DATA. Read all four status fields, EN,EM$,ET,ES, every time.
  2. Append mode: OPEN 2,8,2,"0:ROSTER,A" opens the file with its position at the end. Every PRINT# then adds to the file, and the old records are left alone. Lines 220 and 230 add GRETA and HIRO. Append mode itself never checks for duplicates, so that's our job: lines 204 to 209 first read the names already in the file into E$(), and the subroutine at 500 skips any name found there. Run the program twice and the second time it says SKIPPED.
  3. Copy with a change: lines 320 to 390 open ROSTER for reading and ROSTER NEW for writing at the same time, using two files with two channel numbers. Each record is read, changed if it's BEN's and he isn't in Band already (lines 360 and 365, so a re-run reports no change), and written out again.
  4. Swap it in: through the command channel, S0:ROSTER scratches the old file and R0:ROSTER=ROSTER NEW renames the new one. The new name goes on the left. The subroutine at 900 treats status 1 (FILES SCRATCHED) as fine. Only codes of 2 or more are errors.
  5. Safety: notice the order. The old file is scratched only after the new one has been completely written and closed. If the power fails during the copy, the old file is still there. Never write over the only copy of your data.
  6. Assignment CS 100-2: using your record from CS 100-1, add (1) an ADD option that asks for a record with INPUT and, like the subroutine at 500, refuses a name already in the file, and (2) a DELETE option that copies every record except the one being deleted, then swaps the files. Print the file before and after each change.

Teacher's note: Ask the class what would happen if line 400 came before line 390. Then let someone try it on a spare disk. Losing a file once on purpose teaches the "write new, then swap" rule better than any lecture. Lesson 3 searches the file and prints reports from it.

10 REM CS 100 LESSON 2: ADD TO A FILE, UPDATE A FILE
20 REM APPEND MODE, THEN COPY AND RENAME
100 PRINT "{CLR}CS 100-2  ADD AND UPDATE"
110 OPEN 15,8,15
120 OPEN 2,8,2,"0:ROSTER,S,R":INPUT#15,EN,EM$,ET,ES:CLOSE 2
130 IF EN=62 THEN GOSUB 800
140 IF EN>0 AND EN<>62 THEN 990
200 REM --- APPEND: ADD TO THE END ---
202 REM FIRST NOTE WHO IS ALREADY THERE
204 DIM E$(50):E=0:OPEN 2,8,2,"0:ROSTER,S,R":GOSUB 900
206 INPUT#2,NA$,GR,CL$:S=ST:E=E+1:E$(E)=NA$
208 IF S=0 AND E<50 THEN 206
209 CLOSE 2
210 OPEN 2,8,2,"0:ROSTER,A":GOSUB 900
220 NA$="GRETA":GR=9:CL$="BAND":GOSUB 500
230 NA$="HIRO":GR=12:CL$="CHESS":GOSUB 500
240 CLOSE 2:GOSUB 900
250 GOSUB 700
300 REM --- UPDATE: COPY, CHANGING ONE ---
310 PRINT:PRINT "BEN MOVES FROM ROBOTICS TO BAND"
320 OPEN 2,8,2,"0:ROSTER,S,R":GOSUB 900
330 OPEN 3,8,3,"@0:ROSTER NEW,S,W":GOSUB 900
340 C=0
350 INPUT#2,NA$,GR,CL$:S=ST
360 IF NA$="BEN" AND CL$<>"BAND" THEN CL$="BAND":C=C+1
365 IF NA$="BEN" AND C=0 THEN PRINT "BEN IS ALREADY IN BAND"
370 PRINT#3,NA$:PRINT#3,GR:PRINT#3,CL$
380 IF S=0 THEN 350
390 CLOSE 3:CLOSE 2:GOSUB 900
400 PRINT#15,"S0:ROSTER":GOSUB 900
410 PRINT#15,"R0:ROSTER=ROSTER NEW":GOSUB 900
420 PRINT "CHANGED";C;"RECORD(S)":GOSUB 700
430 CLOSE 15:END
500 REM --- APPEND ONE UNLESS ALREADY THERE ---
510 FOR I=1 TO E:IF E$(I)=NA$ THEN PRINT "SKIPPED ";NA$;", ALREADY THERE":RETURN
520 NEXT I
530 PRINT#2,NA$:PRINT#2,GR:PRINT#2,CL$
540 E=E+1:E$(E)=NA$:PRINT "APPENDED ";NA$:RETURN
700 REM --- LIST THE FILE ---
710 OPEN 2,8,2,"0:ROSTER,S,R":GOSUB 900
720 N=0:L$="":PRINT "IN THE FILE NOW:"
730 INPUT#2,NA$,GR,CL$:S=ST:N=N+1
740 L$=L$+LEFT$(NA$,3)+"/"+LEFT$(CL$,1)+" "
745 IF N/5=INT(N/5) THEN PRINT L$:L$=""
750 IF S=0 THEN 730
760 CLOSE 2:IF L$<>"" THEN PRINT L$
765 PRINT N;"RECORDS":RETURN
800 REM --- NO ROSTER YET: MAKE ONE ---
810 PRINT "NO ROSTER FILE, MAKING ONE"
820 OPEN 2,8,2,"0:ROSTER,S,W":GOSUB 900
830 READ NA$:IF NA$="*" THEN CLOSE 2:GOSUB 900:EN=0:RETURN
840 READ GR,CL$:PRINT#2,NA$:PRINT#2,GR:PRINT#2,CL$:GOTO 830
900 REM --- CHECK THE DRIVE ---
910 INPUT#15,EN,EM$,ET,ES
920 IF EN<2 THEN RETURN
990 PRINT "DISK ERROR";EN;EM$
992 IF EN=72 THEN PRINT "THE FILE WASN'T SAVED. FREE SOME":PRINT "SPACE (FORMAT OR SCRATCH), RUN AGAIN."
995 CLOSE 2:CLOSE 3:CLOSE 15:END
3000 DATA ADA,10,CHESS,BEN,11,ROBOTICS
3010 DATA CARMEN,9,CHESS,DMITRI,12,BAND
3020 DATA ELLA,10,ROBOTICS,FARID,11,BAND
3030 DATA *
CS 100-3 · Searching a file and printing reports

Now that the roster is on disk, let's ask it questions. With a sequential file each question means a pass: open the file, read the records from the start, look at each one, and close it. This lesson asks three kinds of question: find one record, filter the records that match, and summarize them with subtotals.

  1. Find, stopping early (lines 210 to 300): read records until the name matches, then GOTO 270 and stop. CARMEN is found at record 3. ZOE isn't in the file, so every record gets read. On average a search reads half the file, and a miss always reads all of it. Remember this when we build an index in CS 100-5.
  2. Filter (lines 410 to 470): read every record and keep the ones that pass the test GR>=11. Any condition works here, such as a club, a grade range or the first letter of a name.
  3. Subtotals (lines 510 to 600): this is one pass per club, counting members and adding up grades, then a grand total. The clubs come from the array C$() rather than from DATA, so the program can be run again and again. (If they were in DATA, a second RUN would read them in the wrong place, because the roster's DATA is only read when the file has to be made.)
  4. One pass instead of three: the report opens the file once for each club. That's fine for 6 records, but slow for 600 on a floppy. A better way reads the file once and adds each record to the right club's totals in arrays N(K) and T(K).
  5. Assignment CS 100-3: (1) rewrite the subtotal report so it reads the file just once. (2) Add a search that asks for a name with INPUT and lists every record whose name begins with the letters typed, so "D" finds DMITRI. (3) Send the report to the printer with OPEN 4,4:CMD 4, then PRINT#4:CLOSE 4.

Teacher's note: Have the class time a search on a 300-record file that they make with a loop. Counting the reads makes the cost of a sequential search obvious, and it motivates the sorting in lesson 4 and the index in lesson 5.

10 REM CS 100 LESSON 3: SEARCH A FILE, PRINT A REPORT
20 REM ONE PASS PER QUESTION
100 PRINT "{CLR}CS 100-3  SEARCH AND REPORT"
110 OPEN 15,8,15
120 OPEN 2,8,2,"0:ROSTER,S,R":INPUT#15,EN,EM$,ET,ES:CLOSE 2
130 IF EN=62 THEN GOSUB 800
140 IF EN>1 THEN 990
200 REM --- 1. FIND BY NAME, STOP WHEN FOUND ---
205 DIM F$(2),C$(3):F$(1)="CARMEN":F$(2)="ZOE"
206 C$(1)="CHESS":C$(2)="ROBOTICS":C$(3)="BAND"
210 FOR K=1 TO 2:F$=F$(K)
220 OPEN 2,8,2,"0:ROSTER,S,R":GOSUB 900
230 R=0:FD=0
240 INPUT#2,NA$,GR,CL$:S=ST:R=R+1
250 IF NA$=F$ THEN FD=1:GOTO 270
260 IF S=0 THEN 240
270 CLOSE 2
280 R$=MID$(STR$(R),2)
285 IF FD THEN PRINT F$;": GRADE";GR;CL$;", RECORD ";R$
290 IF FD=0 THEN PRINT F$;": NOT FOUND IN ";R$;" RECORDS"
300 NEXT K
400 REM --- 2. FILTER: GRADE 11 AND UP ---
410 PRINT:PRINT "SENIORS (GRADE 11+):"
420 OPEN 2,8,2,"0:ROSTER,S,R":GOSUB 900
430 L$=""
440 INPUT#2,NA$,GR,CL$:S=ST
450 IF GR>=11 THEN L$=L$+NA$+" "
460 IF S=0 THEN 440
470 CLOSE 2:PRINT " ";L$
500 REM --- 3. REPORT WITH SUBTOTALS ---
510 PRINT:PRINT "{RVS}CLUB      MEMBERS  AVG GRADE{OFF}"
520 FOR K=1 TO 3:N=0:T=0
530 OPEN 2,8,2,"0:ROSTER,S,R":GOSUB 900
540 INPUT#2,NA$,GR,CL$:S=ST
550 IF CL$=C$(K) THEN N=N+1:T=T+GR
560 IF S=0 THEN 540
570 CLOSE 2:A=0:IF N THEN A=INT(T/N*10)/10
580 PRINT LEFT$(C$(K)+"          ",10);N;TAB(19);A
590 TN=TN+N:NEXT K
600 PRINT "TOTAL";TAB(10);TN
610 CLOSE 15:END
800 REM --- NO ROSTER YET: MAKE ONE ---
810 PRINT "NO ROSTER FILE, MAKING ONE"
820 OPEN 2,8,2,"0:ROSTER,S,W":GOSUB 900
830 READ NA$:IF NA$="*" THEN CLOSE 2:GOSUB 900:EN=0:RETURN
840 READ GR,CL$:PRINT#2,NA$:PRINT#2,GR:PRINT#2,CL$:GOTO 830
900 REM --- CHECK THE DRIVE ---
910 INPUT#15,EN,EM$,ET,ES
920 IF EN<2 THEN RETURN
990 PRINT "DISK ERROR";EN;EM$
992 IF EN=72 THEN PRINT "THE FILE WASN'T SAVED. FREE SOME":PRINT "SPACE (FORMAT OR SCRATCH), RUN AGAIN."
995 CLOSE 2:CLOSE 15:END
3000 DATA ADA,10,CHESS,BEN,11,ROBOTICS
3010 DATA CARMEN,9,CHESS,DMITRI,12,BAND
3020 DATA ELLA,10,ROBOTICS,FARID,11,BAND
3030 DATA *
CS 100-4 · Sorting a file in memory

A sequential file can't be sorted where it sits. Instead we read the whole file into arrays, sort it in memory, and write a new file in the new order. That's fine while the file fits in the PET's RAM, which on a 32K machine means a few hundred records like ours. This lesson sorts the roster by club, then grade, then name, and prints a report with control breaks, where the club name is shown only when it changes.

  1. Two passes to load: pass 1 (lines 210 to 250) just counts the records, so that line 310 can DIM arrays of exactly the right size. Pass 2 then reads every record into NA$(), GR() and CL$().
  2. Sort pointers, not records: P() starts as 1, 2, 3 and so on. The insertion sort (lines 420 to 470) moves only these numbers, so the three fields of a record can never get separated. Afterwards P(1) is the record that comes first. This is the same idea as the index in lesson 5.
  3. A sort key with three parts: the subroutine at 700 decides whether record A belongs after record V. It compares club names first. Only when the clubs are equal does it compare grades, and only when those are equal does it compare names. You can sort by any mix of fields the same way.
  4. Write, then check: lines 510 to 540 write ROSTER BY CLUB in sorted order and check the drive afterwards. The original ROSTER isn't touched, so you have the file in both orders.
  5. Control breaks: while reading back, L$ remembers the last club printed. When a record has the same club (line 650), the club column is left blank, which makes the report easy to scan. This works only because the file is sorted.
  6. Assignment CS 100-4: (1) sort your own file by two different keys, giving two output files. (2) Add a subtotal line at each control break showing the club's member count and average grade. (3) Insertion sort is slow on a big file: count the comparisons for 50 records, then for 100. How does the count grow?

Teacher's note: If a student's records come out in the wrong order, it's nearly always the sort key's tie rules, so have them write the three-part comparison out in words first. Files too big for memory are sorted by splitting them into sorted pieces and merging those, which is lesson 6.

10 REM CS 100 LESSON 4: SORT A FILE IN MEMORY
20 REM READ IT ALL, SORT, WRITE A NEW FILE
100 PRINT "{CLR}CS 100-4  SORTING A FILE"
110 OPEN 15,8,15
120 OPEN 2,8,2,"0:ROSTER,S,R":INPUT#15,EN,EM$,ET,ES:CLOSE 2
130 IF EN=62 THEN GOSUB 800
140 IF EN>1 THEN 990
200 REM --- PASS 1: COUNT THE RECORDS ---
210 OPEN 2,8,2,"0:ROSTER,S,R":GOSUB 900
220 N=0
230 INPUT#2,NA$,GR,CL$:S=ST:N=N+1
240 IF S=0 THEN 230
250 CLOSE 2:PRINT "COUNTED";N;"RECORDS"
300 REM --- PASS 2: LOAD INTO ARRAYS ---
310 DIM NA$(N),GR(N),CL$(N),P(N)
320 OPEN 2,8,2,"0:ROSTER,S,R":GOSUB 900
330 FOR I=1 TO N:INPUT#2,NA$(I),GR(I),CL$(I):P(I)=I:NEXT
340 CLOSE 2
400 REM --- INSERTION SORT OF POINTERS ---
410 REM KEY: CLUB, THEN GRADE, THEN NAME
420 FOR I=2 TO N:V=P(I):J=I-1
430 IF J<1 THEN 470
440 A=P(J):GOSUB 700:IF B=0 THEN 470
450 P(J+1)=P(J):J=J-1:GOTO 430
470 P(J+1)=V:NEXT I
500 REM --- WRITE THE SORTED FILE ---
510 OPEN 3,8,3,"@0:ROSTER BY CLUB,S,W":GOSUB 900
520 FOR I=1 TO N:K=P(I)
530 PRINT#3,NA$(K):PRINT#3,GR(K):PRINT#3,CL$(K)
540 NEXT I:CLOSE 3:GOSUB 900
600 REM --- READ IT BACK, WITH BREAKS ---
610 PRINT "{RVS}CLUB      GRADE NAME      {OFF}"
620 OPEN 2,8,2,"0:ROSTER BY CLUB,S,R":GOSUB 900
630 L$=""
640 INPUT#2,NA$,GR,CL$:S=ST
650 C$=CL$:IF CL$=L$ THEN C$=""
660 PRINT LEFT$(C$+"          ",10);RIGHT$("  "+STR$(GR),3);"   ";NA$
670 L$=CL$:IF S=0 THEN 640
680 CLOSE 2:CLOSE 15:END
700 REM --- B=1 IF RECORD A BELONGS AFTER V ---
710 B=0:IF CL$(A)>CL$(V) THEN B=1:RETURN
720 IF CL$(A)<CL$(V) THEN RETURN
730 IF GR(A)>GR(V) THEN B=1:RETURN
740 IF GR(A)=GR(V) AND NA$(A)>NA$(V) THEN B=1
750 RETURN
800 REM --- NO ROSTER YET: MAKE ONE ---
810 PRINT "NO ROSTER FILE, MAKING ONE"
820 OPEN 2,8,2,"0:ROSTER,S,W":GOSUB 900
830 READ NA$:IF NA$="*" THEN CLOSE 2:GOSUB 900:EN=0:RETURN
840 READ GR,CL$:PRINT#2,NA$:PRINT#2,GR:PRINT#2,CL$:GOTO 830
900 REM --- CHECK THE DRIVE ---
910 INPUT#15,EN,EM$,ET,ES
920 IF EN<2 THEN RETURN
990 PRINT "DISK ERROR";EN;EM$
992 IF EN=72 THEN PRINT "THE FILE WASN'T SAVED. FREE SOME":PRINT "SPACE (FORMAT OR SCRATCH), RUN AGAIN."
995 CLOSE 2:CLOSE 3:CLOSE 15:END
3000 DATA ADA,10,CHESS,BEN,11,ROBOTICS
3010 DATA CARMEN,9,CHESS,DMITRI,12,BAND
3020 DATA ELLA,10,ROBOTICS,FARID,11,BAND
3040 DATA *
CS 100-5 · Keys and an index file

A key is the field you look records up by, which here is the name. An index is a small separate file holding just the keys, sorted, each with the record number of its record in the data file. The big data file stays in whatever order records were added. To find someone you load the small index, find the key by binary search, and go straight to that record number. A library card catalog works the same way.

  1. Building the index (lines 210 to 330): one pass over ROSTER collects each name and its position. The pairs are sorted by name with an insertion sort, which moves the key and its number together, and then written to ROSTER INDEX: the count first, then key and record-number pairs.
  2. A fresh start: line 340 uses CLR to wipe all the variables, just as if a different program were doing the lookups. Everything after it knows only what's in the index file.
  3. Binary search (lines 460 to 510): look at the middle key. If it's too small, search the upper half, and if it's too big, the lower half. Each look halves what's left, so 8 keys take at most 4 looks, 1,000 keys about 10, and 1,000,000 about 20. In CS 100-3 a miss read every record. Here ZOE is ruled out in just 3 looks with the six-student roster, or 4 once CS 100-2 has added two more.
  4. Fetching the record (lines 540 to 570): Pixel DOS files are sequential, so to reach record 5 we read records 1 to 5 and keep the last one. Real disk systems can also jump to a record directly, using what are called relative files, but the index idea is the same either way.
  5. Keeping it current: the index is a copy of information in ROSTER. Whenever you add or change records (as in CS 100-2), you must rebuild the index or it will point at the wrong records. Your record numbers may differ from the ones shown if an earlier lesson's ROSTER is already on the disk.
  6. Assignment CS 100-5: (1) build a second index on club, so one key can have several records, and list every member of a club typed with INPUT. (2) Make the ADD option from CS 100-2 append the record and rebuild the index. (3) Make a 200-record file with a loop, then compare the reads for a sequential search with the looks for an index search.

Teacher's note: Have students play binary search with a phone book before they code it, with one student holding the book and the class calling "higher" or "lower". The bug they'll meet most is an index that wasn't rebuilt, so put "rebuild the index" on the board next to "write new, then swap" from lesson 2.

10 REM CS 100 LESSON 5: KEYS AND AN INDEX FILE
20 REM SORTED KEYS POINT INTO THE DATA FILE
100 PRINT "{CLR}CS 100-5  AN INDEX FILE"
110 OPEN 15,8,15
120 OPEN 2,8,2,"0:ROSTER,S,R":INPUT#15,EN,EM$,ET,ES:CLOSE 2
130 IF EN=62 THEN GOSUB 800
140 IF EN>1 THEN 990
200 REM --- BUILD: KEY + RECORD NUMBER ---
210 DIM K$(50),R(50)
220 OPEN 2,8,2,"0:ROSTER,S,R":GOSUB 900
230 N=0
240 INPUT#2,NA$,GR,CL$:S=ST:N=N+1
250 K$(N)=NA$:R(N)=N:IF S=0 AND N<50 THEN 240
260 CLOSE 2
270 FOR I=2 TO N:V$=K$(I):V=R(I):J=I-1
280 IF J>0 THEN IF K$(J)>V$ THEN K$(J+1)=K$(J):R(J+1)=R(J):J=J-1:GOTO 280
290 K$(J+1)=V$:R(J+1)=V:NEXT I
300 OPEN 3,8,3,"@0:ROSTER INDEX,S,W":GOSUB 900
310 PRINT#3,N:FOR I=1 TO N:PRINT#3,K$(I):PRINT#3,R(I):NEXT
320 CLOSE 3:GOSUB 900
330 PRINT "INDEX OF";N;"KEYS WRITTEN"
340 CLR:OPEN 15,8,15
400 REM --- LOOK UP: LOAD INDEX, BINARY SEARCH ---
410 OPEN 2,8,2,"0:ROSTER INDEX,S,R":GOSUB 900
420 INPUT#2,N:DIM K$(N),R(N)
430 FOR I=1 TO N:INPUT#2,K$(I),R(I):NEXT:CLOSE 2
440 PRINT "INDEX LOADED:";N;"KEYS":PRINT
450 FOR Q=1 TO 3:F$=MID$("HIRO ELLA ZOE  ",Q*5-4,5)
455 IF RIGHT$(F$,1)=" " THEN F$=LEFT$(F$,LEN(F$)-1):GOTO 455
460 LO=1:HI=N:C=0:FD=0
470 IF LO>HI THEN 520
480 M=INT((LO+HI)/2):C=C+1
490 IF K$(M)=F$ THEN FD=R(M):GOTO 520
500 IF K$(M)<F$ THEN LO=M+1:GOTO 470
510 HI=M-1:GOTO 470
520 IF FD=0 THEN PRINT F$;": NOT FOUND,";C;"LOOKS":GOTO 590
530 REM FETCH RECORD FD: READ UP TO IT
540 OPEN 2,8,2,"0:ROSTER,S,R":GOSUB 900
550 FOR I=1 TO FD:INPUT#2,NA$,GR,CL$:NEXT:CLOSE 2
560 PRINT F$;":";C;"LOOKS, RECORD";FD
570 PRINT "  GRADE";GR;CL$
590 NEXT Q
600 CLOSE 15:END
800 REM --- NO ROSTER YET: MAKE ONE ---
810 PRINT "NO ROSTER FILE, MAKING ONE"
820 OPEN 2,8,2,"0:ROSTER,S,W":GOSUB 900
830 READ NA$:IF NA$="*" THEN CLOSE 2:GOSUB 900:EN=0:RETURN
840 READ GR,CL$:PRINT#2,NA$:PRINT#2,GR:PRINT#2,CL$:GOTO 830
900 REM --- CHECK THE DRIVE ---
910 INPUT#15,EN,EM$,ET,ES
920 IF EN<2 THEN RETURN
990 PRINT "DISK ERROR";EN;EM$
992 IF EN=72 THEN PRINT "THE FILE WASN'T SAVED. FREE SOME":PRINT "SPACE (FORMAT OR SCRATCH), RUN AGAIN."
995 CLOSE 2:CLOSE 3:CLOSE 15:END
3000 DATA ADA,10,CHESS,BEN,11,ROBOTICS
3010 DATA CARMEN,9,CHESS,DMITRI,12,BAND
3020 DATA ELLA,10,ROBOTICS,FARID,11,BAND
3040 DATA *
CS 100-6 · Merging two sorted files

If two files are both sorted by the same key, you can combine them into one sorted file in a single pass. Read one record from each, write out whichever comes first, then read the next record from that same file. You never need both files in memory, so this works on files far bigger than the PET's RAM. Before memory was cheap, that's how big files got sorted: sort small pieces in memory, then merge the pieces.

  1. Two sorted inputs: FILE A is the roster sorted by name (lines 210 to 310, with a simple insertion sort that swaps all three fields together). FILE B holds four new sign-ups from DATA that are already in name order. RESTORE and the loop at 350 skip past the roster's DATA to reach them.
  2. Three files open at once (lines 410 to 430): A on channel 2, B on channel 4, and ALL MEMBERS being written on channel 3.
  3. The "current" record from each file: the subroutines at 600 and 650 read the next record from A or B. When a file is used up, its key becomes HV$, a "high value" (CHR$(255)) that sorts after every name. That trick means the main loop never needs special code for "A ran out first" or "B ran out first".
  4. The merge loop (lines 450 to 480): stop when both keys are HV$. If the keys are equal, it's the same student in both files, so keep A's record and skip B's. Otherwise write the smaller key and advance only that file. ELLA is in both files, so 6 + 4 records merge into 9.
  5. Assignment CS 100-6: (1) when a name is in both files, keep B's record instead, as an update, and print what changed. (2) Merge three sorted files. (3) Build a merge sort: split an unsorted 40-record file into five sorted files of 8, then merge them two at a time.

Teacher's note: Act the merge out with two sorted stacks of index cards, one in each hand: compare the top cards and put the lower one down. Students who have done that once rarely get the loop wrong. The high-value end marker is worth a whole discussion, since it's the same idea as a sentinel in a search.

10 REM CS 100 LESSON 6: MERGING TWO SORTED FILES
20 REM ONE PASS, TWO FILES IN, ONE FILE OUT
100 PRINT "{CLR}CS 100-6  MERGING FILES"
110 OPEN 15,8,15:HV$=CHR$(255)
120 OPEN 2,8,2,"0:ROSTER,S,R":INPUT#15,EN,EM$,ET,ES:CLOSE 2
130 IF EN=62 THEN GOSUB 800
140 IF EN>1 THEN 990
200 REM --- FILE A: THE ROSTER, SORTED BY NAME ---
210 DIM NA$(50),GR(50),CL$(50):N=0
220 OPEN 2,8,2,"0:ROSTER,S,R":GOSUB 900
230 N=N+1:INPUT#2,NA$(N),GR(N),CL$(N):S=ST
240 IF S=0 AND N<50 THEN 230
250 CLOSE 2
260 FOR I=2 TO N:FOR J=I TO 2 STEP -1:IF NA$(J-1)<=NA$(J) THEN 280
270 T$=NA$(J):NA$(J)=NA$(J-1):NA$(J-1)=T$:T=GR(J):GR(J)=GR(J-1):GR(J-1)=T:T$=CL$(J):CL$(J)=CL$(J-1):CL$(J-1)=T$:NEXT J
280 NEXT I
290 OPEN 3,8,3,"@0:FILE A,S,W":GOSUB 900
300 FOR I=1 TO N:PRINT#3,NA$(I):PRINT#3,GR(I):PRINT#3,CL$(I):NEXT
310 CLOSE 3:GOSUB 900
320 REM --- FILE B: NEW SIGN-UPS, SORTED ---
330 OPEN 3,8,3,"@0:FILE B,S,W":GOSUB 900
340 RESTORE
350 READ X$:IF X$<>"*" THEN 350
360 READ X$:IF X$="*" THEN 380
370 READ G,C$:PRINT#3,X$:PRINT#3,G:PRINT#3,C$:GOTO 360
380 CLOSE 3:GOSUB 900
390 PRINT "FILE A:";N;"RECORDS. FILE B READY."
400 REM --- THE MERGE ---
410 OPEN 2,8,2,"0:FILE A,S,R":GOSUB 900
420 OPEN 4,8,4,"0:FILE B,S,R":GOSUB 900
430 OPEN 3,8,3,"@0:ALL MEMBERS,S,W":GOSUB 900
440 GOSUB 600:GOSUB 650:W=0:D=0
450 IF A$=HV$ AND B$=HV$ THEN 520
460 IF A$=B$ THEN PRINT "  ";B$;" IS IN BOTH: KEEP A":D=D+1:GOSUB 650:GOTO 450
470 IF A$<B$ THEN PRINT#3,A$:PRINT#3,AG:PRINT#3,AC$:W=W+1:GOSUB 600:GOTO 450
480 PRINT#3,B$:PRINT#3,BG:PRINT#3,BC$:W=W+1:GOSUB 650:GOTO 450
520 CLOSE 3:CLOSE 4:CLOSE 2:GOSUB 900
530 PRINT "MERGED";W;"RECORDS,";D;"DUPLICATE"
540 REM --- SHOW THE RESULT ---
550 OPEN 2,8,2,"0:ALL MEMBERS,S,R":GOSUB 900:L$=""
560 INPUT#2,X$,G,C$:S=ST:L$=L$+X$+" "
570 IF LEN(L$)>30 THEN PRINT L$:L$=""
580 IF S=0 THEN 560
590 CLOSE 2:PRINT L$:CLOSE 15:END
600 REM --- NEXT FROM A (HV$ AT THE END) ---
610 IF AE THEN A$=HV$:RETURN
620 INPUT#2,A$,AG,AC$:AE=ST:RETURN
650 REM --- NEXT FROM B ---
660 IF BE THEN B$=HV$:RETURN
670 INPUT#4,B$,BG,BC$:BE=ST:RETURN
800 REM --- NO ROSTER YET: MAKE ONE ---
810 PRINT "NO ROSTER FILE, MAKING ONE":RESTORE
820 OPEN 2,8,2,"0:ROSTER,S,W":GOSUB 900
830 READ NA$:IF NA$="*" THEN CLOSE 2:GOSUB 900:EN=0:RETURN
840 READ GR,CL$:PRINT#2,NA$:PRINT#2,GR:PRINT#2,CL$:GOTO 830
900 REM --- CHECK THE DRIVE ---
910 INPUT#15,EN,EM$,ET,ES
920 IF EN<2 THEN RETURN
990 PRINT "DISK ERROR";EN;EM$
992 IF EN=72 THEN PRINT "THE FILE WASN'T SAVED. FREE SOME":PRINT "SPACE (FORMAT OR SCRATCH), RUN AGAIN."
995 CLOSE 2:CLOSE 3:CLOSE 4:CLOSE 15:END
3000 DATA ADA,10,CHESS,BEN,11,ROBOTICS
3010 DATA CARMEN,9,CHESS,DMITRI,12,BAND
3020 DATA ELLA,10,ROBOTICS,FARID,11,BAND
3030 DATA *
3100 REM --- FILE B, ALREADY IN NAME ORDER ---
3110 DATA BEA,9,BAND,ELLA,10,ROBOTICS
3120 DATA IVY,10,CHESS,OMAR,12,ROBOTICS
3130 DATA *
CS 100 closing project · Your own record keeper

Build a menu-driven record keeper for something you care about, such as your record albums, a club's dues, the school library's paperbacks, or a high-score table. It should use everything from CS 100. The starter program below already does List, Add (refusing duplicates) and Find on the roster, and it shows the habits you'll need: checking the drive after every OPEN and CLOSE, and keeping the record layout the same in every routine.

  1. Your record: at least four fields, one of them a number. Write the layout on paper first (CS 100-1).
  2. Must have: ADD with a duplicate check, using append mode (CS 100-2); FIND and a filtered report with subtotals (CS 100-3); a sorted listing on two different keys (CS 100-4); and DELETE and CHANGE using copy and rename, never writing over the only copy (CS 100-2).
  3. Choose two more: an index file with binary search that's rebuilt after every change (CS 100-5); a MERGE option that brings in records from a friend's file (CS 100-6); a printed report (OPEN 4,4:CMD 4); or a backup copy kept on drive 1.
  4. Hand in the listing; a disk with your program and a test file of at least 30 records; a one-page user's guide; and a page describing your record layout and every file the program makes.
  5. It's graded on: does it work, does it ever lose data (we'll fill the disk and pull the plug), is the code clear, and is the guide clear.

Teacher's note: During the demonstration, fill the disk and ask the student to add one more record. A good project says DISK FULL and still has the old file intact. Next up is CS 200, where those parallel arrays become real data structures: stacks, queues, linked lists and trees.

10 REM CS 100 CLOSING PROJECT: STARTER
20 REM A MENU-DRIVEN RECORD KEEPER
30 REM ADD YOUR OWN: DELETE, SORT, INDEX, REPORT
100 PRINT "{CLR}";:OPEN 15,8,15:F$="0:ROSTER"
102 OPEN 2,8,2,F$+",S,R":INPUT#15,EN,EM$,ET,ES:CLOSE 2
104 IF EN=62 THEN GOSUB 800:IF EN THEN CLOSE 15:END
110 PRINT "{RVS} CLUB RECORDS {OFF}"
120 PRINT "L)IST  A)DD  F)IND  Q)UIT"
130 INPUT "CHOICE";C$:C$=LEFT$(C$,1)
140 IF C$="L" THEN GOSUB 200
150 IF C$="A" THEN GOSUB 300
160 IF C$="F" THEN GOSUB 400
170 IF C$="Q" THEN CLOSE 15:PRINT "BYE":END
180 PRINT:GOTO 120
200 REM --- LIST ---
210 OPEN 2,8,2,F$+",S,R":GOSUB 900:IF EN THEN RETURN
220 N=0
230 INPUT#2,NA$,GR,CL$:S=ST:N=N+1
240 PRINT LEFT$(NA$+"          ",10);GR;TAB(15);CL$
250 IF S=0 THEN 230
260 CLOSE 2:PRINT N;"RECORDS":RETURN
300 REM --- ADD, REFUSING A NAME ALREADY THERE ---
310 INPUT "NAME";NA$:IF NA$="" THEN RETURN
320 K$=NA$:QU=1:GOSUB 500:QU=0:IF FD THEN PRINT NA$;" IS ALREADY THERE":RETURN
330 INPUT "GRADE";GR:INPUT "CLUB";CL$
340 QU=1:OPEN 2,8,2,F$+",A":GOSUB 900:QU=0
345 IF EN=62 THEN OPEN 2,8,2,F$+",S,W":GOSUB 900
348 IF EN THEN RETURN
350 PRINT#2,NA$:PRINT#2,GR:PRINT#2,CL$:CLOSE 2
360 GOSUB 900:IF EN=0 THEN PRINT "ADDED ";NA$
370 RETURN
400 REM --- FIND ---
410 INPUT "NAME";K$:GOSUB 500
420 IF FD=0 THEN PRINT K$;" NOT FOUND":RETURN
430 PRINT K$;": GRADE";FG;FC$:RETURN
500 REM --- SEARCH FOR K$: FD=RECORD NUMBER OR 0 ---
510 FD=0:R=0:OPEN 2,8,2,F$+",S,R":GOSUB 900:IF EN THEN RETURN
520 INPUT#2,X$,G,C$:S=ST:R=R+1
530 IF X$=K$ THEN FD=R:FG=G:FC$=C$:GOTO 550
540 IF S=0 THEN 520
550 CLOSE 2:RETURN
900 REM --- CHECK THE DRIVE: EN=0 IF OK ---
905 REM QU=1: A MISSING FILE (62) IS EXPECTED
910 INPUT#15,EN,EM$,ET,ES:IF EN<2 THEN EN=0:RETURN
915 CLOSE 2:IF EN=62 AND QU THEN RETURN
920 IF EN=62 THEN PRINT "NO FILE YET. ADD A RECORD FIRST.":RETURN
930 PRINT "DISK ERROR";EN;EM$
935 IF EN=72 THEN PRINT "THE FILE WASN'T SAVED. FREE SOME":PRINT "SPACE (FORMAT OR SCRATCH), RUN AGAIN."
940 RETURN
800 REM --- NO ROSTER YET: START FROM THE USUAL SIX ---
810 OPEN 2,8,2,F$+",S,W":GOSUB 900:IF EN THEN RETURN
820 READ NA$:IF NA$="*" THEN CLOSE 2:GOSUB 900:RETURN
830 READ GR,CL$:PRINT#2,NA$:PRINT#2,GR:PRINT#2,CL$:GOTO 820
3000 DATA ADA,10,CHESS,BEN,11,ROBOTICS
3010 DATA CARMEN,9,CHESS,DMITRI,12,BAND
3020 DATA ELLA,10,ROBOTICS,FARID,11,BAND
3030 DATA *

CS 200 · Data structures

This is the second Advanced Class course. In CS 100 the data lived in files. In CS 200 we organize it in memory, so programs can find, add and remove things quickly. PET BASIC has only arrays and simple variables, so we build every structure out of arrays: a stack, a queue, a linked list, a tree, a hash table and a graph. That's how the structures really work underneath, in any language. Every lesson has a program to try with ▶ Run it and an assignment, and the course ends with a project. You should know CS 100 first. The structures here, especially stacks and trees, are the tools CS 300 uses to build a parser and an interpreter.

  1. CS 200-1 · Stacks: reversing, matching brackets and a postfix calculator
  2. CS 200-2 · Queues: a circular buffer and a waiting line
  3. CS 200-3 · Linked lists: next pointers and a free list
  4. CS 200-4 · Binary search trees
  5. CS 200-5 · Hash tables
  6. CS 200-6 · Graphs: finding the shortest path out of a maze
  7. CS 200 project · A structure of your own
CS 200-1 · Stacks: reversing, matching brackets and a postfix calculator

A stack is a pile: you can only put something on the top (push) or take the top thing off (pop). The last thing in is the first thing out. It's made of an array S$() plus a stack pointer SP that counts how full it is. BASIC itself uses a stack to remember where every GOSUB has to RETURN to.

  1. Push and pop (lines 800 to 870): push adds 1 to SP and stores the item. Pop takes the item at SP and subtracts 1. Always check the two ways it can go wrong: overflow (pushing onto a full stack) and underflow (popping an empty one).
  2. Reversing (lines 210 to 240): push the letters of STACK one at a time, then pop them all. They come out backwards, as KCATS.
  3. Matching brackets (lines 320 to 390): push every ( and [. At a ) or ], pop, and the item must be the matching opener. It's an error if there's nothing to pop, as in A)+(B, if the popped bracket doesn't match, as in (A+B], or if anything is left over at the end, as in ((A). Compilers check your programs this way.
  4. A postfix calculator (lines 420 to 510): in postfix notation the operator comes after its numbers, so 3 4 + 2 * means (3+4)×2. Push each number. At an operator, pop two numbers, combine them and push the result. What's left at the end is the answer. You never need brackets or precedence rules. Some pocket calculators work this way, and in CS 300 we'll turn ordinary (3+4)*2 into postfix.
  5. Assignment CS 200-1: (1) add { } to the bracket checker. (2) Add an ^ (power) operator, and make the calculator print ERROR instead of ending when it pops an empty stack, which a postfix expression like 3 + would cause. (3) Write a palindrome tester that uses a stack.

Teacher's note: A stack of cafeteria trays is the classic demonstration. Have students trace the postfix calculator on paper with a column for the stack, crossing out and writing as they push and pop. The ones who can do that will find CS 300's expression evaluator easy.

10 REM CS 200 LESSON 1: STACKS
20 REM LAST IN, FIRST OUT
100 PRINT "{CLR}CS 200-1  STACKS"
110 DIM S$(20):SZ=20:SP=0
200 REM --- 1. REVERSE A WORD ---
210 W$="STACK":FOR I=1 TO LEN(W$):X$=MID$(W$,I,1):GOSUB 800:NEXT
220 R$=""
230 IF SP>0 THEN GOSUB 850:R$=R$+X$:GOTO 230
240 PRINT W$;" BACKWARDS IS ";R$
300 REM --- 2. DO THE BRACKETS MATCH? ---
310 PRINT:PRINT "BRACKETS:"
320 FOR T=1 TO 4:READ E$:SP=0:OK=1
330 FOR I=1 TO LEN(E$):C$=MID$(E$,I,1)
340 IF C$="(" OR C$="[" THEN X$=C$:GOSUB 800
350 IF C$=")" THEN W$="(":GOSUB 700
360 IF C$="]" THEN W$="[":GOSUB 700
370 NEXT I:IF SP>0 THEN OK=0
380 M$="NO ":IF OK THEN M$="YES"
390 PRINT " ";M$;"  ";E$:NEXT T
400 REM --- 3. A POSTFIX CALCULATOR ---
410 PRINT:PRINT "POSTFIX (NUMBERS THEN THE OPERATOR):"
420 FOR T=1 TO 2:READ E$:SP=0:E$=E$+" ":X$=""
430 FOR I=1 TO LEN(E$):C$=MID$(E$,I,1)
440 IF C$<>" " THEN X$=X$+C$:GOTO 500
450 IF X$="" THEN 500
460 IF X$<>"+" AND X$<>"-" AND X$<>"*" AND X$<>"/" THEN GOSUB 800:X$="":GOTO 500
470 O$=X$:GOSUB 850:B=VAL(X$):GOSUB 850:A=VAL(X$)
480 IF O$="+" THEN A=A+B
482 IF O$="-" THEN A=A-B
484 IF O$="*" THEN A=A*B
486 IF O$="/" THEN A=A/B
490 X$=MID$(STR$(A),2):IF A<0 THEN X$=STR$(A)
495 GOSUB 800:X$=""
500 NEXT I:GOSUB 850
510 PRINT " ";E$;"= ";X$:NEXT T
520 END
700 REM --- CLOSE BRACKET: TOP MUST BE W$ ---
710 IF SP=0 THEN OK=0:RETURN
720 GOSUB 850:IF X$<>W$ THEN OK=0
730 RETURN
800 REM --- PUSH X$ ---
810 IF SP=SZ THEN PRINT "STACK OVERFLOW":END
820 SP=SP+1:S$(SP)=X$:RETURN
850 REM --- POP INTO X$ ---
860 IF SP=0 THEN PRINT "STACK UNDERFLOW":END
870 X$=S$(SP):SP=SP-1:RETURN
3000 DATA "(A+B)*[C-(D+E)]","(A+B]","((A)","A)+(B"
3010 DATA "3 4 + 2 *","10 2 8 * + 3 -"
CS 200-2 · Queues: a circular buffer and a waiting line

A queue is a waiting line: people join at the tail and are served from the head, so the first one in is the first one out. The obvious way to build it, shifting everyone in the array forward each time someone is served, is slow. The usual way is to leave the items where they are and move two pointers instead, letting them wrap around to the start of the array. That's a circular buffer. The PET's keyboard buffer works like this.

  1. The parts (line 110): an array Q$(0) to Q$(4), a head pointer HD, a tail pointer TL and a count N. The count is what tells "empty" (N=0) from "full" (N=5), because in both cases HD and TL point to the same slot.
  2. Enqueue (line 800) stores the item at TL and moves TL along, back to 0 when it reaches the end. Dequeue (line 850) takes the item at HD and moves HD the same way. A full queue turns newcomers away, and an empty one sets OK=0.
  3. Watch it (part 1): each row shows the five slots, with H at the head, T at the tail, and * where they meet. After a few people are served and more join, FAY lands in slot 0. The buffer has wrapped around, but the line is still in order: BO, CY, DEV, EVA, FAY.
  4. A simulation (part 2): every minute some students join the lunch line (from DATA) and one is served. Each item stores the minute the student arrived, so the program can work out how long each one waited. The longest line is measured at line 345, right after the arrivals and before that minute's serve, when the line is at its longest.
  5. A BASIC trap: line 340 says IF A>0 THEN FOR K=1 TO A. Without the IF, FOR K=1 TO 0 still runs once in this BASIC, and a student would appear out of nowhere. Remember this whenever a loop might need to run zero times.
  6. Assignment CS 200-2: (1) add a second server from minute 4 on, and compare the average wait. (2) Use RND for the arrivals and run 60 minutes. How big must the buffer be so nobody is turned away? (3) Build a deque that can add and remove at both ends.

Teacher's note: Draw the five slots in a circle on the board rather than in a row, and move two magnets for H and T. Students find wrap-around natural once they see it as a clock face. The FOR-runs-once trap catches everyone at least once, so let them find it.

10 REM CS 200 LESSON 2: QUEUES
20 REM FIRST IN, FIRST OUT, IN A CIRCLE
100 PRINT "{CLR}CS 200-2  QUEUES"
110 SZ=5:DIM Q$(SZ-1):HD=0:TL=0:N=0
200 REM --- 1. WATCH THE BUFFER WRAP AROUND ---
210 PRINT "+NAME JOINS, - SERVES THE FRONT"
220 READ C$:IF C$="*" THEN 300
230 IF LEFT$(C$,1)="+" THEN X$=MID$(C$,2):GOSUB 800
240 IF C$="-" THEN GOSUB 850:IF OK THEN PRINT "  SERVED ";X$
250 GOSUB 900:GOTO 220
300 REM --- 2. A LUNCH LINE, MINUTE BY MINUTE ---
305 PRINT "{RVS}PRESS A KEY FOR PART 2{OFF}"
306 GET K$:IF K$="" THEN 306
310 PRINT "{CLR}LUNCH LINE: ONE SERVED EACH MINUTE"
320 HD=0:TL=0:N=0:W=0:SV=0:MX=0
330 FOR T=1 TO 8:READ A
340 IF A>0 THEN FOR K=1 TO A:X$=STR$(T):GOSUB 800:NEXT K
345 IF N>MX THEN MX=N
350 GOSUB 850:IF OK THEN SV=SV+1:W=W+T-VAL(X$)
370 PRINT " MIN";T;A;"IN,";N;"WAITING"
380 NEXT T
390 PRINT "SERVED";SV;" LONGEST LINE";MX
400 PRINT "AVERAGE WAIT";INT(W/SV*10)/10;"MINUTES"
410 END
800 REM --- ENQUEUE X$ AT THE TAIL ---
810 IF N=SZ THEN PRINT "  FULL, ";X$;" TURNED AWAY":RETURN
820 Q$(TL)=X$:TL=TL+1:IF TL=SZ THEN TL=0
830 N=N+1:RETURN
850 REM --- DEQUEUE FROM THE HEAD INTO X$ ---
860 OK=0:IF N=0 THEN RETURN
870 X$=Q$(HD):Q$(HD)="":HD=HD+1:IF HD=SZ THEN HD=0
880 N=N-1:OK=1:RETURN
900 REM --- SHOW THE BUFFER: H=HEAD, T=TAIL ---
910 L$="":FOR I=0 TO SZ-1:M$=" ":IF I=HD THEN M$="H"
920 IF I=TL THEN M$="T":IF I=HD THEN M$="*"
930 L$=L$+M$+LEFT$(Q$(I)+"... ",4):NEXT I
940 PRINT " ";L$;N:RETURN
3000 DATA +ANN,+BO,-,+CY,+DEV,+EVA,+FAY,+GUS,-,+HAL,*
3010 DATA 2,1,0,3,2,0,0,1
CS 200-3 · Linked lists: next pointers and a free list

To keep an array in order, inserting a name in the middle means shifting everything after it along by one. A linked list avoids that. Each item is stored in any free slot together with a next pointer, the slot number of the item that follows it. The list's order is the chain of pointers, not the order of the slots. Inserting or deleting just changes a pointer or two.

  1. The parts (lines 110 to 140): V$() holds the values and NX() the next pointers, where 0 means "end of the list". HD is the slot of the first item. All the unused slots are chained together into a second list, the free list, which starts at FR.
  2. Walking the list (line 400): start at HD and follow P=NX(P) until P is 0. Every list routine is built around that loop.
  3. Inserting in order (line 500): take a slot from the front of the free list. If the new name belongs first, it becomes the head. Otherwise walk until the next item is bigger, then link the new slot in: NX(K)=NX(P):NX(P)=K. The order of those two statements matters. Try swapping them!
  4. Deleting (line 600): walk with two pointers, Q on the item and P on the one before it. Unlink Q by pointing around it, then push its slot onto the free list so it can be used again. In the table at the end you can see that ANN reused BO's old slot 2 and CY reused TAL's slot 3, and that slot order (MAY, ANN, CY, ELI) isn't list order.
  5. Assignment CS 200-3: (1) add a COUNT routine and a FIND that reports how many links it followed. (2) Make it a doubly linked list with a PV() pointer to the previous item as well, so you can print it backwards. (3) Keep two lists in the same arrays, such as the chess club and the band, sharing one free list.

Teacher's note: Act it out with students holding cards: each card has a name, and each student points to the next. Inserting means only two students change where they point. Then show the table at the end of the run, because the moment students see that slot order and list order differ is when it clicks.

10 REM CS 200 LESSON 3: LINKED LISTS
20 REM EACH ITEM KNOWS WHERE THE NEXT ONE IS
100 PRINT "{CLR}CS 200-3  LINKED LISTS"
110 SZ=8:DIM V$(SZ),NX(SZ)
120 REM ALL SLOTS START ON THE FREE LIST
130 FOR I=1 TO SZ-1:NX(I)=I+1:NEXT:NX(SZ)=0
140 FR=1:HD=0
200 REM --- +NAME INSERTS IN ORDER, -NAME DELETES ---
210 READ C$:IF C$="*" THEN 300
220 X$=MID$(C$,2):PRINT LEFT$(C$+"       ",7);
230 IF LEFT$(C$,1)="+" THEN GOSUB 500
240 IF LEFT$(C$,1)="-" THEN GOSUB 600
250 GOSUB 400:GOTO 210
300 REM --- THE ARRAYS UNDERNEATH ---
310 PRINT:PRINT "SLOT VALUE  NEXT   HEAD";HD;" FREE";FR
320 FOR I=1 TO SZ:PRINT RIGHT$(" "+STR$(I),3);"  ";LEFT$(V$(I)+"      ",6);NX(I):NEXT
330 END
400 REM --- WALK THE LIST FROM THE HEAD ---
410 P=HD:L$=""
420 IF P THEN L$=L$+V$(P)+">":P=NX(P):GOTO 420
430 PRINT L$;"END":RETURN
500 REM --- INSERT X$ IN ALPHABETICAL ORDER ---
510 IF FR=0 THEN PRINT "NO FREE SLOTS ";:RETURN
520 K=FR:FR=NX(FR):V$(K)=X$
530 IF HD=0 THEN 570
540 IF X$<V$(HD) THEN 570
550 P=HD
555 IF NX(P) THEN IF V$(NX(P))<X$ THEN P=NX(P):GOTO 555
560 NX(K)=NX(P):NX(P)=K:RETURN
570 NX(K)=HD:HD=K:RETURN
600 REM --- DELETE X$, GIVE ITS SLOT BACK ---
610 P=0:Q=HD
620 IF Q THEN IF V$(Q)<>X$ THEN P=Q:Q=NX(Q):GOTO 620
630 IF Q=0 THEN PRINT "NOT FOUND ";:RETURN
640 IF P=0 THEN HD=NX(Q)
650 IF P THEN NX(P)=NX(Q)
660 V$(Q)="":NX(Q)=FR:FR=Q:RETURN
3000 DATA +MAY,+BO,+TAL,+ELI,-BO,+ANN,-TAL,+CY,-ZED,*
CS 200-4 · Binary search trees

A linked list must be walked from the start. A binary search tree gives every node two pointers: left to the smaller names and right to the bigger ones. Searching starts at the top (the root) and goes left or right at each node, just like binary search in CS 100-5. Unlike a sorted array, though, you can keep inserting new names cheaply.

        MAX
       /   \
     DOT    SUE
    /  \   /  \
  BEA  JAN PAM TOM
  /
 AL
  1. The parts (line 110): K$() holds the names, L() and R() the left and right pointers (0 means none), and RT is the root. D() records each node's depth, so we know the tree's height.
  2. Insert (line 500): start at the root and go left if the new name is smaller, right if not, until you reach an empty pointer. Then hang the new node there. The eight names above build the tree in the picture, which is 4 levels high.
  3. Search (line 550): the same walk, counting looks. JAN takes 3 (MAX, DOT, JAN). KIT is ruled out in 3 looks, because JAN has no right child where KIT would have to be.
  4. In order with a stack (line 600): to list the names alphabetically, visit everything to the left, then the node, then everything to the right. A stack from CS 200-1 remembers the nodes we still have to come back to. Push nodes going left; when you can't go further, pop one, print it and go right. The tree is a sort.
  5. A warning (part 3): insert the same names already sorted and every node hangs to the right of the one before. The height is 8 for 8 nodes, and finding TOM takes 8 looks, so it's really a linked list in disguise. Real systems rebalance their trees. Shuffling the names before inserting them works surprisingly well too.
  6. Assignment CS 200-4: (1) print the tree sideways, root at the left and right subtree above, with indentation for depth. (2) Add each record's grade and club from CS 100 to the nodes, and load the roster file into a tree. (3) Delete a node that has no children, then one with a single child. (A node with two children is the bonus.)

Teacher's note: Build the tree on the board as the class calls out names. Then have someone call them out in alphabetical order and watch the tree slide down the right side of the board. Being able to say why it degrades is the most important thing in this lesson.

10 REM CS 200 LESSON 4: BINARY SEARCH TREES
20 REM SMALLER TO THE LEFT, BIGGER TO THE RIGHT
100 PRINT "{CLR}CS 200-4  BINARY SEARCH TREES"
110 SZ=20:DIM K$(SZ),L(SZ),R(SZ),D(SZ),S(SZ)
200 REM --- 1. BUILD A TREE ---
210 GOSUB 700:PRINT "INSERTED:";
220 READ X$:IF X$="*" THEN 240
230 PRINT " ";X$;:GOSUB 500:GOTO 220
240 PRINT:GOSUB 600:PRINT "IN ORDER:";L$
250 PRINT "NODES";N;" HEIGHT";HT
300 REM --- 2. SEARCH IT ---
310 FOR Q=1 TO 3:READ F$:GOSUB 550
320 M$="NOT FOUND":IF FD THEN M$="FOUND"
330 PRINT " ";F$;": ";M$;" IN";C;"LOOKS":NEXT
400 REM --- 3. THE SAME NAMES IN SORTED ORDER ---
410 PRINT:GOSUB 700
420 READ X$:IF X$="*" THEN 440
430 GOSUB 500:GOTO 420
440 GOSUB 600:PRINT "SORTED INPUT: HEIGHT";HT;"FOR";N;"NODES"
450 F$="TOM":GOSUB 550:PRINT " TOM: FOUND IN";C;"LOOKS"
460 PRINT " (A LIST IN DISGUISE!)"
470 END
500 REM --- INSERT X$ ---
510 N=N+1:K$(N)=X$:L(N)=0:R(N)=0:D(N)=1:IF RT=0 THEN RT=N:GOTO 545
520 P=RT
525 D(N)=D(N)+1:IF X$<K$(P) THEN 535
530 IF R(P) THEN P=R(P):GOTO 525
532 R(P)=N:GOTO 545
535 IF L(P) THEN P=L(P):GOTO 525
540 L(P)=N
545 IF D(N)>HT THEN HT=D(N)
548 RETURN
550 REM --- SEARCH FOR F$: FD, C=LOOKS ---
555 P=RT:C=0:FD=0
560 IF P=0 THEN RETURN
565 C=C+1:IF F$=K$(P) THEN FD=P:RETURN
570 IF F$<K$(P) THEN P=L(P):GOTO 560
575 P=R(P):GOTO 560
600 REM --- IN-ORDER WALK WITH A STACK ---
610 L$="":SP=0:P=RT
620 IF P THEN SP=SP+1:S(SP)=P:P=L(P):GOTO 620
630 IF SP=0 THEN RETURN
640 P=S(SP):SP=SP-1:L$=L$+" "+K$(P):P=R(P):GOTO 620
700 REM --- EMPTY TREE ---
710 N=0:RT=0:HT=0:RETURN
3000 DATA MAX,DOT,SUE,BEA,JAN,PAM,TOM,AL,*
3010 DATA JAN,TOM,KIT
3020 DATA AL,BEA,DOT,JAN,MAX,PAM,SUE,TOM,*
CS 200-5 · Hash tables

A list makes you search; a hash table lets you jump. A hash function turns a key into a slot number. Ours adds up the ASC codes of the name and takes the remainder MOD 11, so every name lands in one of 11 slots. The table holds locker numbers for the club roster.

Collisions. Two keys can hash to the same slot: ELLA and ADA both hash to 0. With linear probing, if the slot is taken we try the next one, wrapping round at the end. NED and DEN are the same letters, so they get the same hash. That's a weakness of adding up codes.

Load factor = slots in use ÷ table size. Here 8 of 11 are full (73%). Look at the lookups: DEN needs 5 probes and ZOE needs 7 to learn she isn't here, because the full slots have bunched into a cluster. Keep tables under about 70% full.

Lookup follows the same path as insert and stops at the key or at an empty slot, since an empty slot means the key was never placed further on.

10 REM CS 200 LESSON 5: HASH TABLES
20 REM TURN THE KEY INTO A SLOT NUMBER
100 PRINT "{CLR}CS 200-5  HASH TABLES"
110 SZ=11:DIM T$(SZ-1),V(SZ-1)
200 REM --- 1. STORE NAME AND LOCKER NUMBER ---
210 PRINT "NAME   HASH SLOT"
220 READ X$:IF X$="*" THEN 300
230 READ X:GOSUB 500:GOSUB 600
240 PRINT LEFT$(X$+"      ",6);H;TAB(12);P;:IF P<>H THEN PRINT " (COLLIDED)";
250 PRINT:GOTO 220
300 REM --- 2. THE TABLE ---
310 PRINT:PRINT "TABLE:":FOR I=0 TO SZ-1:Y$=T$(I):IF Y$="" THEN Y$="-"
320 PRINT RIGHT$(" "+STR$(I),3);" ";LEFT$(Y$+"       ",7);:IF I=2 OR I=5 OR I=8 THEN PRINT
325 NEXT:PRINT
330 PRINT "FULL";N;"OF";SZ;"SLOTS"
400 REM --- 3. LOOK UP ---
410 PRINT
420 FOR Q=1 TO 3:READ X$:GOSUB 500:GOSUB 650
430 IF FD THEN PRINT X$;": LOCKER";V(P);"IN";C;"PROBE(S)"
440 IF FD=0 THEN PRINT X$;": NOT HERE AFTER";C;"PROBE(S)"
450 NEXT Q:END
500 REM --- HASH: ADD THE LETTER CODES, MOD SZ ---
510 H=0:FOR I=1 TO LEN(X$):H=H+ASC(MID$(X$,I,1)):NEXT
520 H=H-INT(H/SZ)*SZ:RETURN
600 REM --- INSERT X$,X: STEP ON TO THE NEXT FREE SLOT ---
610 IF N=SZ THEN PRINT "TABLE FULL":END
620 P=H
630 IF T$(P)<>"" THEN P=P+1:IF P=SZ THEN P=0
635 IF T$(P)<>"" THEN 630
640 T$(P)=X$:V(P)=X:N=N+1:RETURN
650 REM --- FIND X$: FD=1 IF FOUND, C=PROBES ---
660 P=H:C=0:FD=0
670 C=C+1:IF T$(P)=X$ THEN FD=1:RETURN
680 IF T$(P)="" OR C=SZ THEN RETURN
690 P=P+1:IF P=SZ THEN P=0
695 GOTO 670
3000 DATA ADA,12,BEN,7,CARMEN,31,DMITRI,4
3010 DATA ELLA,19,FARID,22,NED,9,DEN,15,*
3020 DATA ELLA,DEN,ZOE

Assignment. Add a DELETE that blanks FARID's slot, then look up NED. Why does the lookup now fail? Fix it with a tombstone: mark deleted slots "*", let lookups probe past them, and let inserts reuse them.

CS 200-6 · Graphs: shortest path

A graph is a set of nodes joined by edges. A maze is a graph: every open cell is a node, with an edge to each open neighbour up, right, down and left (lines 700–730 work out the neighbour's number: one row is W cells).

Breadth-first search uses the queue from CS 200-2. Put the start in the queue at distance 0. Then, again and again, take the cell at the front and add each neighbour that isn't a wall and hasn't been seen yet, at distance + 1. Because the queue is first in, first out, every cell 1 step away is visited before any cell 2 steps away. So the first time BFS reaches the exit, it got there by a shortest path.

Each cell remembers its parent, the cell it was reached from, in P(). To draw the route, walk back from E through the parents to S (line 430) and mark each cell with a dot.

This maze has two ways out. BFS finds the 16-step one along the top, not the longer one along the bottom, after visiting 30 cells.

10 REM CS 200 LESSON 6: GRAPHS - SHORTEST PATH
20 REM BREADTH-FIRST SEARCH THROUGH A MAZE
100 PRINT "{CLR}CS 200-6  SHORTEST PATH (BFS)"
110 W=11:H=7:N=W*H:DIM M(N-1),D(N-1),P(N-1),Q(N-1)
200 REM --- 1. READ THE MAZE INTO A GRID ---
210 FOR R=0 TO H-1:READ L$:FOR C=0 TO W-1:I=R*W+C:X$=MID$(L$,C+1,1)
220 M(I)=(X$="#"):D(I)=-1:IF X$="S" THEN S=I
230 IF X$="E" THEN E=I
240 NEXT C,R
300 REM --- 2. BFS: VISIT CELLS IN ORDER OF DISTANCE ---
310 QH=0:QT=0:Q(QT)=S:QT=QT+1:D(S)=0:P(S)=-1:V=0
320 IF QH=QT THEN 400
330 I=Q(QH):QH=QH+1:V=V+1:IF I=E THEN 400
340 FOR K=1 TO 4:ON K GOSUB 700,710,720,730
350 IF M(J)=0 AND D(J)<0 THEN D(J)=D(I)+1:P(J)=I:Q(QT)=J:QT=QT+1
360 NEXT K:GOTO 320
400 REM --- 3. FOLLOW PARENTS BACK FROM THE EXIT ---
410 IF D(E)<0 THEN PRINT "NO WAY OUT!":END
420 J=P(E)
430 IF J<>S THEN M(J)=2:J=P(J):GOTO 430
500 REM --- 4. DRAW IT ---
510 PRINT:FOR R=0 TO H-1:PRINT "  ";:FOR C=0 TO W-1:I=R*W+C
520 Y$=" ":IF M(I)=-1 THEN Y$="#"
530 IF M(I)=2 THEN Y$="."
540 IF I=S THEN Y$="S"
550 IF I=E THEN Y$="E"
560 PRINT Y$;:NEXT C:PRINT:NEXT R
570 PRINT:PRINT "SHORTEST PATH:";D(E);"STEPS"
580 PRINT "CELLS VISITED:";V
590 END
700 J=I-W:RETURN
710 J=I+1:RETURN
720 J=I+W:RETURN
730 J=I-1:RETURN
1000 DATA "###########"
1010 DATA "#S  #     #"
1020 DATA "# # # ### #"
1030 DATA "# #   #   #"
1040 DATA "# ##### # #"
1050 DATA "#       #E#"
1060 DATA "###########"

Assignment. Change the maze DATA to close the top route (put a # at the gap) and run it again. How long is the path now? Then wall E in completely and check that line 410 says NO WAY OUT!

CS 200 closing project · A structure of your own

Real programs combine structures, each doing the job it's best at. The starter program below runs a club with 8 places. It keeps the members in a hash table for fast lookups (CS 200-5) and a stack of adds so U)NDO can take back the last one (CS 200-1). People who join when the club is full go into a queue (CS 200-2), and L)IST builds a binary search tree and walks it in order with a stack (CS 200-4).

  1. Try it: add GINA and HAL, then IKE (the club is full, so IKE is waitlist #1). Press U: HAL is removed and IKE moves up. FIND still works past the "*" tombstone HAL leaves behind (lines 1130–1170).
  2. Must have: pick your own subject, such as a library's loans, a bus route's stops or a tournament. Use at least three of the CS 200 structures, and say in a comment why each one was the right choice.
  3. Choose two more: a linked list of each member's items, with a free list (CS 200-3); a map of the rooms solved with BFS (CS 200-6); saving and loading the table to disk with the checks from CS 100; or a COUNT of probes, so you can measure the load factor as the table fills.
  4. Hand in the listing; a page that draws each structure with a few sample entries in it; and a test log showing every way each one can go wrong (full, empty, not found, duplicate).
10 REM CS 200 PROJECT: CLUB ROSTER TOOLKIT
20 REM HASH TABLE + STACK + QUEUE + TREE
100 PRINT "{CLR}CS 200 PROJECT  CLUB ROSTER"
110 SZ=11:CP=8:DIM T$(SZ-1),U$(20),W$(7),K$(CP),LF(CP),RT(CP),S(CP)
120 QU=1
130 READ X$:IF X$<>"*" THEN GOSUB 1000:GOTO 130
140 QU=0:SP=0:PRINT N;"MEMBERS LOADED. ROOM FOR";CP
200 PRINT:PRINT "A)DD F)IND L)IST U)NDO W)AIT Q)UIT"
210 GET C$:IF C$="" THEN 210
220 IF C$="A" THEN INPUT "NAME";X$:GOSUB 1000:GOTO 200
230 IF C$="F" THEN INPUT "NAME";X$:GOSUB 1100:GOSUB 1200:GOTO 200
240 IF C$="L" THEN GOSUB 1300:GOTO 200
250 IF C$="U" THEN GOSUB 1500:GOTO 200
260 IF C$="W" THEN GOSUB 1600:GOTO 200
270 IF C$="Q" THEN PRINT "BYE":END
280 GOTO 210
1000 REM --- ADD: HASH, CHECK, INSERT, PUSH FOR UNDO ---
1010 GOSUB 1100:IF FD THEN PRINT X$;" IS ALREADY IN":RETURN
1020 IF N<CP THEN 1060
1030 IF WC=8 THEN PRINT "WAITLIST FULL TOO":RETURN
1040 W$(WT)=X$:WT=WT+1:IF WT=8 THEN WT=0
1050 WC=WC+1:PRINT "CLUB FULL: ";X$;" IS WAITLIST #";WC:RETURN
1060 IF FS<0 THEN FS=P
1070 T$(FS)=X$:N=N+1:SP=SP+1:U$(SP)=X$
1080 IF QU=0 THEN PRINT "ADDED ";X$;" IN SLOT";FS
1090 RETURN
1100 REM --- LOOK UP: PROBE PAST TOMBSTONES ---
1110 H=0:FOR I=1 TO LEN(X$):H=H+ASC(MID$(X$,I,1)):NEXT:H=H-INT(H/SZ)*SZ
1120 P=H:C=0:FD=0:FS=-1
1130 C=C+1:IF T$(P)="" THEN RETURN
1140 IF T$(P)="*" AND FS<0 THEN FS=P
1150 IF T$(P)=X$ THEN FD=1:RETURN
1160 P=P+1:IF P=SZ THEN P=0
1170 IF C<SZ THEN 1130
1180 RETURN
1200 IF FD THEN PRINT X$;" IS A MEMBER: SLOT";P;"IN";C;"PROBE(S)":RETURN
1210 PRINT X$;" IS NOT A MEMBER AFTER";C;"PROBE(S)":RETURN
1300 REM --- LIST: BUILD A TREE, WALK IT IN ORDER ---
1310 NN=0:FOR I=0 TO SZ-1:Y$=T$(I):IF Y$="" OR Y$="*" THEN 1380
1320 NN=NN+1:K$(NN)=Y$:LF(NN)=0:RT(NN)=0:IF NN=1 THEN 1380
1330 J=1
1340 IF Y$>=K$(J) THEN 1370
1350 IF LF(J)=0 THEN LF(J)=NN:GOTO 1380
1360 J=LF(J):GOTO 1340
1370 IF RT(J)=0 THEN RT(J)=NN:GOTO 1380
1375 J=RT(J):GOTO 1340
1380 NEXT I
1390 IF NN=0 THEN PRINT "NO MEMBERS":RETURN
1400 SS=0:J=1:CL=0
1410 IF J>0 THEN SS=SS+1:S(SS)=J:J=LF(J):GOTO 1410
1420 IF SS=0 THEN PRINT:PRINT NN;"MEMBERS,";WC;"WAITING":RETURN
1430 J=S(SS):SS=SS-1:IF CL+LEN(K$(J))>39 THEN PRINT:CL=0
1435 PRINT K$(J);" ";:CL=CL+LEN(K$(J))+1:J=RT(J):GOTO 1410
1500 REM --- UNDO: POP THE LAST ADD, LEAVE A TOMBSTONE ---
1510 IF SP=0 THEN PRINT "NOTHING TO UNDO":RETURN
1520 X$=U$(SP):SP=SP-1:GOSUB 1100:T$(P)="*":N=N-1:PRINT "REMOVED ";X$
1530 IF WC=0 THEN RETURN
1540 X$=W$(WH):WH=WH+1:IF WH=8 THEN WH=0
1550 WC=WC-1:PRINT X$;" MOVES UP FROM THE WAITLIST":GOTO 1000
1600 REM --- WAITLIST: FRONT TO BACK ---
1610 IF WC=0 THEN PRINT "NOBODY WAITING":RETURN
1620 J=WH:FOR I=1 TO WC:PRINT I;W$(J):J=J+1:IF J=8 THEN J=0
1630 NEXT:RETURN
2000 DATA ADA,BEN,CARMEN,DMITRI,ELLA,FARID,*

CS 300 · Parsers and interpreters

This is the third Advanced Class course. Every time you type a line, BASIC has to read it, work out what it means and do it. In CS 300 you build those parts yourself, in BASIC: a tokenizer that cuts a line into pieces, parsers that understand expressions with brackets and precedence, and an interpreter that runs a tiny language. Then you put them to work in an adventure engine, where rooms and objects are data and a parser understands what the player types. You should know CS 200 first, because the stacks and tables from there do the heavy lifting here. Every lesson has a program to try with ▶ Run it and an assignment, and the course ends with a project.

  1. CS 300-1 · Tokens: cutting a line into words, numbers and symbols
  2. CS 300-2 · From infix to postfix: the shunting-yard method
  3. CS 300-3 · Recursive descent: an expression evaluator
  4. CS 300-4 · An interpreter for a tiny language
  5. CS 300-5 · The adventure engine: rooms, exits and a two-word parser
  6. CS 300-6 · The adventure engine: objects, inventory and saving the game
  7. CS 300 project · A little language or adventure of your own
CS 300-1 · Tokens: cutting a line into words, numbers and symbols

Before a computer can understand LET AREA=3.5*R^2, it has to see it as pieces: the word LET, the variable AREA, the operator =, the number 3.5 and so on. These pieces are tokens, and the routine that finds them is a tokenizer (or scanner). When you type a line, PET BASIC tokenizes it straight away and stores each keyword as a single byte.

  1. Look at the first character (lines 530–590). It decides what kind of token starts here: a digit or point starts a number, a letter starts a name, a quote mark starts a string, and anything else must be a symbol. Spaces are skipped.
  2. Then keep going while it still fits. A number takes digits and at most one point (lines 600–640). A name takes letters and digits (lines 650–695). A string runs to the closing quote (lines 700–740). Each token is stored as its kind in K$() and its text in V$().
  3. Keywords are names on a list. After reading a name, line 690 checks it against KW$(). If it's there, it's a word (W), and otherwise it's a variable (V).
  4. Look one character ahead. < on its own is a token, but so are <=, >= and <>. Lines 750–780 peek at the next character before deciding.
  5. Errors. A string with no closing quote, or a character that isn't in the symbol list, stops the tokenizer with the column number, just like BASIC's ?SYNTAX ERROR.
10 REM CS 300 LESSON 1: A TOKENIZER
20 REM CUT A LINE INTO WORDS, NUMBERS AND SYMBOLS
30 REM IN THE DATA, ' STANDS FOR A QUOTE MARK
100 PRINT "{CLR}CS 300-1  TOKENS"
110 DIM K$(30),V$(30),KW$(5):FOR W=1 TO 5:READ KW$(W):NEXT
120 SY$="+-*/^()=,;:"
200 READ L$:IF L$="*" THEN PRINT:PRINT "N=NUMBER W=WORD V=VARIABLE":PRINT "S=STRING O=OPERATOR":END
205 X$="":FOR W=1 TO LEN(L$):C$=MID$(L$,W,1):IF C$="'" THEN C$=CHR$(34)
206 X$=X$+C$:NEXT:L$=X$
210 PRINT "> ";L$:GOSUB 500
220 IF ER THEN PRINT "  ERROR AT COLUMN";I;"(";MID$(L$,I,1);")":GOTO 200
230 CL=0:FOR T=1 TO NT:X$=K$(T)+":"+V$(T)+" "
240 IF CL+LEN(X$)>39 THEN PRINT:CL=0
250 PRINT X$;:CL=CL+LEN(X$):NEXT:PRINT:GOTO 200
500 REM --- THE TOKENIZER ---
510 NT=0:ER=0:I=1
520 IF I>LEN(L$) THEN RETURN
530 C$=MID$(L$,I,1):S=I
540 IF C$=" " THEN I=I+1:GOTO 520
550 IF C$>="0" AND C$<="9" OR C$="." THEN 600
560 IF C$>="A" AND C$<="Z" THEN 650
570 IF C$=CHR$(34) THEN 700
580 IF C$="<" OR C$=">" THEN 750
590 GOTO 800
600 REM NUMBER: DIGITS AND AT MOST ONE POINT
610 DP=(C$=".")
620 I=I+1:IF I>LEN(L$) THEN 640
630 C$=MID$(L$,I,1):IF C$>="0" AND C$<="9" THEN 620
635 IF C$="." AND DP=0 THEN DP=1:GOTO 620
640 K$="N":GOTO 850
650 REM NAME: A LETTER, THEN LETTERS OR DIGITS
670 I=I+1:IF I>LEN(L$) THEN 690
680 C$=MID$(L$,I,1):IF C$>="A" AND C$<="Z" OR C$>="0" AND C$<="9" THEN 670
690 K$="V":X$=MID$(L$,S,I-S):FOR W=1 TO 5:IF X$=KW$(W) THEN K$="W"
695 NEXT:GOTO 850
700 REM STRING: UP TO THE CLOSING QUOTE
720 I=I+1:IF I>LEN(L$) THEN ER=1:I=S:RETURN
730 IF MID$(L$,I,1)<>CHR$(34) THEN 720
740 I=I+1:K$="S":GOTO 850
750 REM < AND > CAN PAIR UP: <= >= <>
760 I=I+1:N$=MID$(L$,I,1)
770 IF N$="=" OR (C$="<" AND N$=">") THEN I=I+1
780 K$="O":GOTO 850
800 REM ONE-CHARACTER SYMBOLS
810 FD=0:FOR W=1 TO LEN(SY$):IF C$=MID$(SY$,W,1) THEN FD=1
820 NEXT:IF FD=0 THEN ER=1:RETURN
830 I=I+1:K$="O"
850 NT=NT+1:K$(NT)=K$:V$(NT)=MID$(L$,S,I-S):GOTO 520
1000 DATA LET,PRINT,IF,THEN,GOTO
1010 DATA "LET AREA=3.5*R^2"
1020 DATA "IF X1<>10 THEN GOTO 200"
1030 DATA "PRINT 'HI THERE';(A+B)/2"
1040 DATA "IF N>=.25 THEN X=X-1"
1050 DATA "PRINT 'OOPS"
1060 DATA "LET X=Y#2"
1070 DATA *

Assignment CS 300-1: (1) add the keywords FOR, TO and NEXT, and check that FOR I=1 TO 10 gives W V O N W N. (2) Give UNCLOSED STRING its own message. (3) Allow numbers like 1E3. Which line has to change, and what about the variable E?

CS 300-2 · From infix to postfix: the shunting-yard method

We write (3+4)*2 with the operators between the numbers. That's infix, and it needs brackets and precedence rules (× before +). In CS 200-1 the stack calculator wanted postfix, 3 4 + 2 *, which needs neither. The shunting-yard method turns one into the other with a stack of operators, like railway wagons waiting on a siding.

  1. Numbers go straight out to the postfix list Q$() (lines 600–610).
  2. Operators wait on the stack O$(). Before pushing one, pop to the output every operator on the stack that must happen first: one of higher precedence, or of equal precedence, because 100-20-5 means (100−20)−5 (lines 620–645). Precedence comes from line 750: + − are 1, × ÷ are 2, ^ is 3.
  3. ^ is the exception. 2^3^2 means 2^(3^2) = 512, so an equal ^ is not popped (the C$<>"^" on line 635). This is called being right-associative.
  4. Brackets: ( is pushed and acts as a wall. At ), pop to the output until you reach the matching (, then throw both away (lines 650–665). Running out of stack means too many ), and a ( still on the stack at the end means a missing ).
  5. At the end, pop everything that's left (line 700). Then the postfix is evaluated with the number stack from CS 200-1 (lines 800–870), which also catches 3++4 and dividing by zero.
10 REM CS 300 LESSON 2: INFIX TO POSTFIX
20 REM THE SHUNTING-YARD METHOD
100 PRINT "{CLR}CS 300-2  SHUNTING YARD"
110 DIM O$(20),Q$(40),N(20)
200 READ L$:IF L$="*" THEN END
205 EX=EX+1:IF EX=6 THEN PRINT:PRINT "PRESS A KEY";:GOSUB 950:PRINT "{CLR}"
210 PRINT "INFIX:   ";L$:GOSUB 500
220 IF ER THEN PRINT "ERROR: ";E$:GOTO 200
230 PRINT "POSTFIX:";:FOR T=1 TO NQ:PRINT " ";Q$(T);:NEXT:PRINT
240 GOSUB 800:IF ER THEN PRINT "ERROR: ";E$:GOTO 200
250 PRINT "VALUE:  ";V:GOTO 200
500 REM --- SHUNTING YARD: NUMBERS GO STRAIGHT OUT, ---
510 REM --- OPERATORS WAIT ON A STACK ---
520 NQ=0:SP=0:ER=0:I=1
530 IF I>LEN(L$) THEN 700
540 C$=MID$(L$,I,1)
550 IF C$>="0" AND C$<="9" THEN 600
560 IF C$="(" THEN SP=SP+1:O$(SP)=C$:I=I+1:GOTO 530
570 IF C$=")" THEN 650
580 X$=C$:GOSUB 750:IF P=0 THEN ER=1:E$="WHAT IS "+C$+"?":RETURN
590 GOTO 620
600 S=I
605 I=I+1:IF I<=LEN(L$) THEN IF MID$(L$,I,1)>="0" AND MID$(L$,I,1)<="9" THEN 605
610 NQ=NQ+1:Q$(NQ)=MID$(L$,S,I-S):GOTO 530
620 REM OPERATOR: FIRST POP ANY THAT MUST GO BEFORE IT
625 PC=P:IF SP=0 THEN 645
630 X$=O$(SP):IF X$="(" THEN 645
635 GOSUB 750:IF P>PC OR (P=PC AND C$<>"^") THEN NQ=NQ+1:Q$(NQ)=X$:SP=SP-1:GOTO 625
645 SP=SP+1:O$(SP)=C$:I=I+1:GOTO 530
650 REM ) : POP BACK TO THE MATCHING (
655 IF SP=0 THEN ER=1:E$="TOO MANY )":RETURN
660 IF O$(SP)="(" THEN SP=SP-1:I=I+1:GOTO 530
665 NQ=NQ+1:Q$(NQ)=O$(SP):SP=SP-1:GOTO 655
700 REM END: EVERYTHING LEFT ON THE STACK GOES OUT
710 IF SP=0 THEN RETURN
720 IF O$(SP)="(" THEN ER=1:E$="MISSING )":RETURN
730 NQ=NQ+1:Q$(NQ)=O$(SP):SP=SP-1:GOTO 710
750 REM PRECEDENCE OF X$ (0 = NOT AN OPERATOR)
755 P=0:IF X$="+" OR X$="-" THEN P=1
760 IF X$="*" OR X$="/" THEN P=2
765 IF X$="^" THEN P=3
770 RETURN
800 REM --- EVALUATE THE POSTFIX (CS 200-1) ---
810 SP=0:ER=0:FOR T=1 TO NQ:X$=Q$(T):GOSUB 750
820 IF P=0 THEN SP=SP+1:N(SP)=VAL(X$):GOTO 860
830 IF SP<2 THEN ER=1:E$="NOT ENOUGH NUMBERS":RETURN
840 B=N(SP):SP=SP-1:A=N(SP):IF X$="/" AND B=0 THEN ER=1:E$="DIVIDE BY ZERO":RETURN
850 ON P GOSUB 900,910,920
860 NEXT:IF SP<>1 THEN ER=1:E$="NOT ENOUGH OPERATORS":RETURN
870 V=N(1):RETURN
900 N(SP)=A+B:IF X$="-" THEN N(SP)=A-B
905 RETURN
910 N(SP)=A*B:IF X$="/" THEN N(SP)=A/B
915 RETURN
920 N(SP)=A^B:RETURN
950 GET K$:IF K$="" THEN 950
960 RETURN
1000 DATA "(3+4)*2","3+4*2","100-20-5"
1010 DATA "2^3^2","(1+2)*(3+4)/7","12/(4-4)"
1020 DATA "(5+6","5+6)","3++4","7%2",*

Assignment CS 300-2: (1) let the expressions use single-letter variables, A to Z, with values set in DATA (use the tokenizer from CS 300-1). (2) Handle a minus sign at the start or after (, as in -3+5 or 2*(-4). Hint: push a 0 first. (3) Write the postfix out as an expression tree on paper for (1+2)*(3+4)/7.

CS 300-3 · Recursive descent: an expression evaluator

Shunting-yard works, but there's a way to read expressions that copies their grammar directly. Write the rules down first. An expression is terms joined by + or −. A term is factors joined by × or ÷. A factor is a number, a minus sign and a factor, or a whole expression in brackets. Then write one subroutine per rule. That's a recursive-descent parser, and most real compilers start out this way.

  1. Precedence comes free. EXPR (line 1000) calls TERM, and TERM (line 1100) calls FACTOR, so × and ÷ are finished before + and − ever see the result. There's no precedence table.
  2. Recursion. FACTOR meets a ( and calls EXPR again (line 1222), even though EXPR is what called it. GOSUB can do this because BASIC keeps a stack of return addresses. DEPTH shows how many EXPRs were open at once.
  3. BASIC's catch: its variables are all global. When a nested call returns, R and C$ have been overwritten. So before calling TERM or FACTOR a second time, push the left value and the operator onto our own stack, S() and S$() (lines 1030 and 1130), and pop them afterwards. Languages with local variables do this for you.
  4. Peek, then take. Line 1300 looks at the next character without using it up. A rule only moves I on when the character is one it wants.
  5. Errors say what was expected and where, and every caller passes ER straight back up. Line 230 catches anything left over, as in 2 3.
10 REM CS 300 LESSON 3: RECURSIVE DESCENT
20 REM ONE SUBROUTINE PER GRAMMAR RULE
100 PRINT "{CLR}CS 300-3  RECURSIVE DESCENT"
110 DIM S(30),S$(30)
120 PRINT "EXPR   = TERM   [+ OR - TERM]..."
130 PRINT "TERM   = FACTOR [* OR / FACTOR]..."
140 PRINT "FACTOR = NUMBER, -FACTOR OR (EXPR)"
200 READ L$:IF L$="*" THEN END
205 EX=EX+1:IF EX=6 THEN PRINT:PRINT "PRESS A KEY";:GOSUB 1400:PRINT "{CLR}";
210 PRINT:PRINT L$:I=1:SP=0:DP=0:DM=0:ER=0
220 GOSUB 1000:IF ER THEN 260
230 GOSUB 1300:IF C$<>"" THEN ER=1:E$="EXTRA "+C$:GOTO 260
240 PRINT "  =";R;"  (DEPTH";DM;")"
250 GOTO 200
260 PRINT "  ERROR: ";E$;" AT COLUMN";I:GOTO 200
1000 REM --- EXPR: TERM, THEN MORE TERMS ADDED ON ---
1005 DP=DP+1:IF DP>DM THEN DM=DP
1010 GOSUB 1100:IF ER THEN DP=DP-1:RETURN
1020 GOSUB 1300:IF C$<>"+" AND C$<>"-" THEN DP=DP-1:RETURN
1030 SP=SP+1:S(SP)=R:S$(SP)=C$:I=I+1
1040 GOSUB 1100:A=S(SP):O$=S$(SP):SP=SP-1:IF ER THEN DP=DP-1:RETURN
1050 IF O$="+" THEN R=A+R:GOTO 1020
1060 R=A-R:GOTO 1020
1100 REM --- TERM: FACTOR, THEN MORE FACTORS ---
1110 GOSUB 1200:IF ER THEN RETURN
1120 GOSUB 1300:IF C$<>"*" AND C$<>"/" THEN RETURN
1130 SP=SP+1:S(SP)=R:S$(SP)=C$:I=I+1
1140 GOSUB 1200:A=S(SP):O$=S$(SP):SP=SP-1:IF ER THEN RETURN
1150 IF O$="*" THEN R=A*R:GOTO 1120
1160 IF R=0 THEN ER=1:E$="DIVIDE BY ZERO":RETURN
1170 R=A/R:GOTO 1120
1200 REM --- FACTOR: THE ONLY PLACE THAT RECURSES ---
1210 GOSUB 1300
1220 IF C$<>"(" THEN 1240
1222 I=I+1:GOSUB 1000:IF ER THEN RETURN
1225 GOSUB 1300:IF C$<>")" THEN ER=1:E$="MISSING )":RETURN
1230 I=I+1:RETURN
1240 IF C$="-" THEN I=I+1:GOSUB 1200:R=-R:RETURN
1250 IF C$<"0" OR C$>"9" THEN ER=1:E$="NUMBER EXPECTED":RETURN
1260 S=I
1270 I=I+1:IF I<=LEN(L$) THEN C$=MID$(L$,I,1):IF C$>="0" AND C$<="9" THEN 1270
1280 R=VAL(MID$(L$,S,I-S)):RETURN
1300 REM --- PEEK: SKIP SPACES, LOOK AT THE NEXT CHARACTER ---
1310 C$="":IF I>LEN(L$) THEN RETURN
1320 C$=MID$(L$,I,1):IF C$=" " THEN I=I+1:GOTO 1310
1330 RETURN
1400 GET K$:IF K$="" THEN 1400
1410 RETURN
2000 DATA "2+3*4","(2+3)*4","100-20-5"
2010 DATA "-(6-10)*2","((((((7))))))"
2020 DATA "8/(3-3)","(1+2","1+*2","2 3",*

Assignment CS 300-3: (1) add a POWER rule between TERM and FACTOR so that 2^3^2 is 512. Which rule should it call to be right-associative? (2) Add single-letter variables. (3) Try ((((((((((((7)))))))))))) and longer. When does BASIC run out of GOSUB stack, and what error does it give?

CS 300-4 · An interpreter for a tiny language

Now we can run a whole language. This one has five statements: LET, PRINT, IF … GOTO, GOTO and END, plus the variables A to Z. The programs are stored in DATA, one numbered line per item, and each one ends with RUN. The interpreter loads a program and then runs it. That is exactly what PET BASIC does with yours, just a lot faster, because it's written in machine code.

  1. Load (lines 200–260): split each line into its number LN() and its statement P$().
  2. Fetch, decode, execute (lines 300–390): PC, the program counter, says which statement is next. Fetch it, add 1 to PC, read its first word (line 1500), and jump to the code for that statement. Anything else is ?WHAT IS …, with the line number, just like a real ?SYNTAX ERROR.
  3. LET and PRINT reuse the CS 300-3 evaluator, with one new kind of FACTOR: a letter means "look it up in VR()" (line 1210).
  4. Jumps: GOTO searches for its line number and sets PC (lines 560–580). IF works out both sides and the comparison, and only jumps when it's true. Every loop in the language is built from these.
  5. A safety net: the step counter stops a runaway program after 50 steps (line 335), like pressing STOP. RUN 12 sets a different limit (line 220). The third sample program loops for ever on purpose, so it uses RUN 12 and stops within a few seconds.
10 REM CS 300 LESSON 4: AN INTERPRETER
20 REM A TINY LANGUAGE: LET PRINT IF GOTO END
30 REM IN THE DATA, ' STANDS FOR A QUOTE MARK
100 PRINT "{CLR}CS 300-4  A TINY INTERPRETER"
110 DIM P$(40),LN(40),S(30),S$(30),VR(26)
200 REM --- LOAD ONE PROGRAM: NUMBER, THEN STATEMENT ---
205 IF PG THEN PRINT "PRESS A KEY";:GOSUB 1600:PRINT "{CLR}";
210 NP=0:PG=1:READ T$:IF T$="*" THEN END
220 IF LEFT$(T$,3)="RUN" THEN LM=50:IF LEN(T$)>3 THEN LM=VAL(MID$(T$,4))
225 IF LEFT$(T$,3)="RUN" THEN 300
230 NP=NP+1:FOR K=1 TO LEN(T$):IF MID$(T$,K,1)<>" " THEN NEXT
240 LN(NP)=VAL(LEFT$(T$,K-1)):X$=MID$(T$,K+1):L$=""
250 FOR K=1 TO LEN(X$):C$=MID$(X$,K,1):IF C$="'" THEN C$=CHR$(34)
260 L$=L$+C$:NEXT:P$(NP)=L$:READ T$:GOTO 220
300 REM --- RUN IT: FETCH, DECODE, EXECUTE ---
310 PRINT:PRINT "RUN":IF LM<>50 THEN PRINT "(STOPS AFTER";LM;"STEPS)"
315 FOR K=0 TO 26:VR(K)=0:NEXT:PC=1:NS=0
320 IF PC>NP THEN E$="NO END":GOTO 390
330 L$=P$(PC):PC=PC+1:NS=NS+1:ER=0:I=1
335 IF NS>LM THEN E$="TOO MANY STEPS":GOTO 390
340 GOSUB 1500:W$=X$
350 IF W$="LET" THEN 400
355 IF W$="PRINT" THEN 450
360 IF W$="IF" THEN 500
365 IF W$="GOTO" THEN 560
370 IF W$="END" THEN PRINT "DONE IN";NS;"STEPS":GOTO 200
380 E$="WHAT IS "+W$
390 PRINT "?";E$;:IF PC>1 THEN PRINT " IN";LN(PC-1);
395 PRINT:GOTO 200
400 REM LET V = EXPR
410 GOSUB 1300:V=ASC(C$)-64:IF V<1 OR V>26 THEN E$="VARIABLE?":GOTO 390
420 I=I+1:GOSUB 1300:IF C$<>"=" THEN E$="= EXPECTED":GOTO 390
430 I=I+1:GOSUB 1000:IF ER THEN 390
440 VR(V)=R:GOTO 320
450 REM PRINT "TEXT" OR PRINT EXPR
460 GOSUB 1300:IF C$<>CHR$(34) THEN 480
470 PRINT MID$(L$,I+1,LEN(L$)-I-1):GOTO 320
480 GOSUB 1000:IF ER THEN 390
490 PRINT R:GOTO 320
500 REM IF EXPR REL EXPR GOTO N
510 GOSUB 1000:IF ER THEN 390
515 LV=R:GOSUB 1300:RL$="":IF C$="<" OR C$=">" OR C$="=" THEN RL$=C$:I=I+1
520 GOSUB 1300:IF C$="=" OR C$=">" THEN RL$=RL$+C$:I=I+1
525 IF RL$="" THEN E$="< > OR = EXPECTED":GOTO 390
530 GOSUB 1000:IF ER THEN 390
535 TF=0:IF RL$="=" THEN TF=(LV=R)
540 IF RL$="<" THEN TF=(LV<R)
541 IF RL$=">" THEN TF=(LV>R)
542 IF RL$="<>" THEN TF=(LV<>R)
543 IF RL$="<=" THEN TF=(LV<=R)
544 IF RL$=">=" THEN TF=(LV>=R)
545 GOSUB 1500:IF X$<>"GOTO" THEN E$="GOTO EXPECTED":GOTO 390
550 IF TF=0 THEN 320
560 REM GOTO N: SEARCH FOR THE LINE NUMBER
565 GOSUB 1000:IF ER THEN 390
570 FOR K=1 TO NP:IF LN(K)<>R THEN NEXT:E$="NO LINE"+STR$(R):GOTO 390
580 PC=K:GOTO 320
1000 REM --- EXPRESSIONS: CS 300-3, PLUS VARIABLES ---
1010 GOSUB 1100:IF ER THEN RETURN
1020 GOSUB 1300:IF C$<>"+" AND C$<>"-" THEN RETURN
1030 SP=SP+1:S(SP)=R:S$(SP)=C$:I=I+1
1040 GOSUB 1100:A=S(SP):O$=S$(SP):SP=SP-1:IF ER THEN RETURN
1050 IF O$="+" THEN R=A+R:GOTO 1020
1060 R=A-R:GOTO 1020
1100 GOSUB 1200:IF ER THEN RETURN
1120 GOSUB 1300:IF C$<>"*" AND C$<>"/" THEN RETURN
1130 SP=SP+1:S(SP)=R:S$(SP)=C$:I=I+1
1140 GOSUB 1200:A=S(SP):O$=S$(SP):SP=SP-1:IF ER THEN RETURN
1150 IF O$="*" THEN R=A*R:GOTO 1120
1160 IF R=0 THEN ER=1:E$="DIVIDE BY ZERO":RETURN
1170 R=A/R:GOTO 1120
1200 GOSUB 1300
1210 IF C$>="A" AND C$<="Z" THEN R=VR(ASC(C$)-64):I=I+1:RETURN
1220 IF C$<>"(" THEN 1240
1222 I=I+1:GOSUB 1000:IF ER THEN RETURN
1225 GOSUB 1300:IF C$<>")" THEN ER=1:E$="MISSING )":RETURN
1230 I=I+1:RETURN
1240 IF C$="-" THEN I=I+1:GOSUB 1200:R=-R:RETURN
1250 IF C$<"0" OR C$>"9" THEN ER=1:E$="NUMBER EXPECTED":RETURN
1260 S=I
1270 I=I+1:IF I<=LEN(L$) THEN C$=MID$(L$,I,1):IF C$>="0" AND C$<="9" THEN 1270
1280 R=VAL(MID$(L$,S,I-S)):RETURN
1300 C$="":IF I>LEN(L$) THEN RETURN
1320 C$=MID$(L$,I,1):IF C$=" " THEN I=I+1:GOTO 1300
1330 RETURN
1500 REM --- NEXT WORD: LETTERS ONLY ---
1510 GOSUB 1300:S=I
1520 IF I<=LEN(L$) THEN IF MID$(L$,I,1)>="A" AND MID$(L$,I,1)<="Z" THEN I=I+1:GOTO 1520
1530 X$=MID$(L$,S,I-S):RETURN
1600 GET K$:IF K$="" THEN 1600
1610 RETURN
2000 DATA "10 LET N=1","20 LET F=1","30 LET F=F*N"
2010 DATA "40 PRINT F","50 LET N=N+1","60 IF N<=7 GOTO 30"
2020 DATA "70 END",RUN
2100 DATA "10 LET A=0","20 LET B=1","30 PRINT 'FIBONACCI'"
2110 DATA "40 PRINT A","50 LET C=A+B","60 LET A=B","70 LET B=C"
2120 DATA "80 IF A<30 GOTO 40","90 PRINTT A",RUN
2200 DATA "10 LET X=1","20 GOTO 10","RUN 12",*

Assignment CS 300-4: (1) let PRINT take a list, as in PRINT N;F. (2) Add GOSUB and RETURN. You'll need a stack of return PCs (CS 200-1). (3) The GOTO search starts from the top every time. Build a table once at load time, or use the hash table from CS 200-5, and count how many steps it saves.

CS 300-5 · The adventure engine: rooms, exits and a two-word parser

A text adventure is an interpreter too. The "program" is a world of rooms, and the language is what the player types. The trick that makes adventures easy to write is to keep the engine (the code) apart from the world (the data). Change the DATA and you have a whole new game, without touching a line of code.

  1. The map is a table (lines 1000–1060). Each room has a name, a description and four exits: the room number you reach going north, south, east and west, or 0 for a wall. EX(R,D) holds them all. It's a graph, like the maze in CS 200-6, with the edges written out.
  2. Moving is a lookup: X=EX(R,N-10). If it's 0 you can't go that way, and otherwise X is the new room (lines 320–345).
  3. The vocabulary (lines 1110–1120) gives every word a code, and synonyms share a code: WALK means GO, and N means NORTH. The parser splits the line into two words, a verb and a noun (lines 220–230), then looks each one up (line 500). It matches the whole word or just the first three letters, so SOU works too. Early adventures did this to save memory.
  4. Shortcuts: if the first word is a direction, the engine assumes GO (line 270). Unknown words and missing nouns each get their own answer, never ?SYNTAX ERROR.
  5. Word wrap (line 700): a description longer than the 40-column screen is broken at the last space that fits, so no word is ever split.
10 REM CS 300 LESSON 5: THE ADVENTURE ENGINE
20 REM ROOMS AND EXITS ARE DATA, A PARSER READS THE PLAYER
100 PRINT "{CLR}CS 300-5  AFTER HOURS"
110 NR=6:DIM RN$(NR),RD$(NR),EX(NR,4),VW$(20),VC(20),D$(4)
120 FOR R=1 TO NR:READ RN$(R),RD$(R):FOR D=1 TO 4:READ EX(R,D):NEXT D,R
130 NW=0
140 NW=NW+1:READ VW$(NW),VC(NW):IF VW$(NW)<>"*" THEN 140
150 NW=NW-1:FOR D=1 TO 4:READ D$(D):NEXT
160 PRINT "YOU'RE LOCKED IN SCHOOL AFTER HOURS."
170 PRINT "TYPE HELP FOR THE WORDS I KNOW."
180 R=1:MV=0:GOSUB 600
200 REM --- READ A COMMAND, SPLIT IT INTO TWO WORDS ---
210 PRINT:PRINT "WHAT NOW";:INPUT L$:MV=MV+1
220 W1$=L$:W2$="":FOR I=1 TO LEN(L$):IF MID$(L$,I,1)=" " THEN W1$=LEFT$(L$,I-1):W2$=MID$(L$,I+1):I=LEN(L$)
230 NEXT
240 X$=W1$:GOSUB 500:V=C:IF V=0 THEN 480
250 N=0:IF W2$="" THEN 270
260 X$=W2$:GOSUB 500:N=C:IF N=0 THEN 480
270 IF V>10 THEN N=V:V=1
300 REM --- DO IT ---
310 ON V GOTO 320,350,360,370
320 IF N=0 THEN PRINT "GO WHERE?":GOTO 200
330 IF N<11 THEN PRINT "THAT'S NOT A DIRECTION.":GOTO 200
340 X=EX(R,N-10):IF X=0 THEN PRINT "YOU CAN'T GO THAT WAY.":GOTO 200
345 R=X:GOSUB 600:GOTO 200
350 GOSUB 600:GOTO 200
360 PRINT "YOU GAVE UP AFTER";MV;"MOVES.":END
370 X$="I KNOW:":FOR J=1 TO NW:X$=X$+" "+VW$(J):NEXT:GOSUB 700:GOTO 200
480 PRINT "I DON'T KNOW THE WORD ";X$;".":GOTO 200
500 REM --- LOOK UP A WORD: WHOLE WORD, OR FIRST 3 LETTERS ---
510 C=0:FOR I=1 TO NW:Y$=VW$(I)
520 IF X$=Y$ OR (LEN(X$)>=3 AND LEFT$(X$,3)=LEFT$(Y$,3)) THEN C=VC(I):I=NW
530 NEXT:RETURN
600 REM --- DESCRIBE THE ROOM ---
610 PRINT:PRINT "{RVS}";RN$(R);"{OFF}":X$=RD$(R):GOSUB 700
620 PRINT "EXITS:";:FOR D=1 TO 4:IF EX(R,D) THEN PRINT " ";D$(D);
630 NEXT:PRINT:RETURN
700 REM --- PRINT X$, BREAKING LINES BETWEEN WORDS ---
710 IF LEN(X$)<40 THEN PRINT X$:RETURN
720 FOR I=40 TO 1 STEP -1:IF MID$(X$,I,1)<>" " THEN NEXT
730 PRINT LEFT$(X$,I-1):X$=MID$(X$,I+1):GOTO 710
1000 REM ROOM NAME, DESCRIPTION, EXITS NORTH SOUTH EAST WEST
1010 DATA HALLWAY,"A LONG HALLWAY. LOCKERS LINE THE WALLS.",2,5,3,0
1020 DATA CLASSROOM,"DESKS IN ROWS. A PET WAITS ON THE TEACHER'S DESK.",0,1,4,0
1030 DATA LIBRARY,"SHELVES OF BOOKS. IT'S VERY QUIET.",4,0,0,1
1040 DATA SCIENCE LAB,"BEAKERS, AND A SKELETON IN THE CORNER.",0,3,0,2
1050 DATA GYM,"A HUGE ROOM. A BASKETBALL ROLLS PAST.",1,0,6,0
1060 DATA OFFICE,"THE PRINCIPAL'S OFFICE. YOU SHOULDN'T BE HERE!",0,0,0,5
1100 REM WORDS: 1 GO, 2 LOOK, 3 QUIT, 4 HELP, 11-14 DIRECTIONS
1110 DATA GO,1,WALK,1,LOOK,2,QUIT,3,HELP,4
1120 DATA NORTH,11,N,11,SOUTH,12,S,12,EAST,13,E,13,WEST,14,W,14,*,0
1130 DATA NORTH,SOUTH,EAST,WEST

Assignment CS 300-5: (1) add UP and DOWN exits and a seventh room, a roof or a basement. Which lines have to change, and which only need more DATA? (2) Add BACK, which returns you to the room you came from. (3) Draw the map on paper from the DATA alone. Is there a one-way passage anywhere? Make one on purpose.

CS 300-6 · The adventure engine: objects, inventory and saving the game

An adventure needs things to pick up and puzzles to solve with them. This version of After Hours has a key, a note, a ball and a locked door, and it can save your game to disk. It's still the same engine from CS 300-5, with more words and more DATA.

  1. Objects are a table too. Each object has a name in OB$() and a location in OL(): a room number, or 0 if you're carrying it. That single number does all the work. TAKE checks that OL is the room you're in and sets it to 0 (lines 400–418). DROP does the opposite. INVENTORY lists everything at 0, and the room description lists everything at R (line 615).
  2. Words are numbered by kind (lines 1100–1130): verbs 1–11, directions 21–24 and things 31–35. One look at the code tells the parser what sort of word it has (lines 270–290), so KEY on its own can say "WHAT DO YOU WANT TO DO WITH IT?"
  3. A puzzle is a rule plus a change to the data. OPEN DOOR only works in the hallway, and only if you're carrying the key. Then it writes a new exit into the map, EX(1,4)=7 (line 468). The note tells you where to look.
  4. The game state is everything that can change: the room, the moves, the door and every object's location. SAVE writes exactly that, one number per line, to a sequential file (lines 800–845). It replaces the old save with @. LOAD reads it back in the same order and puts the door's exit back (line 880). The rooms and words never change, so they're never saved.
  5. The CS 100 habits stay: check the drive after every OPEN and CLOSE (line 900). A full disk gives "THE GAME WASN'T SAVED" and you keep playing. LOAD with no save says so.
10 REM CS 300 LESSON 6: OBJECTS, INVENTORY, SAVING
20 REM THE AFTER HOURS ENGINE, NOW WITH THINGS IN IT
100 PRINT "{CLR}CS 300-6  AFTER HOURS II"
110 NR=7:NO=3:DIM RN$(NR),RD$(NR),EX(NR,4),VW$(30),VC(30),D$(4),OB$(NO),OL(NO)
120 FOR R=1 TO NR:READ RN$(R),RD$(R):FOR D=1 TO 4:READ EX(R,D):NEXT D,R
125 FOR J=1 TO NO:READ OB$(J),OL(J):NEXT
130 NW=0
140 NW=NW+1:READ VW$(NW),VC(NW):IF VW$(NW)<>"*" THEN 140
150 NW=NW-1:FOR D=1 TO 4:READ D$(D):NEXT
155 OPEN 15,8,15:F$="0:AFTERHOURS"
160 X$="YOU'RE LOCKED IN SCHOOL AFTER HOURS. FIND A WAY OUT. TYPE HELP FOR THE WORDS I KNOW.":GOSUB 700
180 R=1:MV=0:DO=0:GOSUB 600
200 REM --- READ A COMMAND, SPLIT IT INTO TWO WORDS ---
210 PRINT:PRINT "WHAT NOW";:INPUT L$:MV=MV+1
220 W1$=L$:W2$="":FOR I=1 TO LEN(L$):IF MID$(L$,I,1)=" " THEN W1$=LEFT$(L$,I-1):W2$=MID$(L$,I+1):I=LEN(L$)
230 NEXT
240 X$=W1$:GOSUB 500:V=C:IF V=0 THEN 480
250 N=0:IF W2$="" THEN 270
260 X$=W2$:GOSUB 500:N=C:IF N=0 THEN 480
270 IF V>20 AND V<25 THEN N=V:V=1
280 IF V>20 THEN PRINT "WHAT DO YOU WANT TO DO WITH IT?":GOTO 200
290 OB=0:IF N>30 THEN OB=N-30:IF OB>NO THEN OB=0
300 REM --- DO IT ---
310 ON V GOTO 320,350,360,370,400,420,440,460,800,850,470
320 IF N=0 THEN PRINT "GO WHERE?":GOTO 200
330 IF N<21 OR N>24 THEN PRINT "THAT'S NOT A DIRECTION.":GOTO 200
340 X=EX(R,N-20):IF X=0 THEN PRINT "YOU CAN'T GO THAT WAY.":GOTO 200
345 R=X:GOSUB 600:IF R=7 THEN PRINT:PRINT "YOU'RE FREE, IN";MV;"MOVES!":CLOSE 15:END
347 GOTO 200
350 GOSUB 600:GOTO 200
360 PRINT "YOU GAVE UP AFTER";MV;"MOVES.":CLOSE 15:END
370 X$="I KNOW:":FOR J=1 TO NW:X$=X$+" "+VW$(J):NEXT:GOSUB 700:GOTO 200
400 REM TAKE: THE OBJECT MUST BE HERE
405 IF N<31 THEN PRINT "TAKE WHAT?":GOTO 200
410 IF OB=0 THEN PRINT "YOU CAN'T TAKE THAT.":GOTO 200
412 IF OL(OB)=0 THEN PRINT "YOU ALREADY HAVE IT.":GOTO 200
415 IF OL(OB)<>R THEN PRINT "I DON'T SEE A ";OB$(OB);" HERE.":GOTO 200
418 OL(OB)=0:PRINT "TAKEN.":GOTO 200
420 REM DROP: YOU MUST BE CARRYING IT
425 IF OB=0 THEN PRINT "DROP WHAT?":GOTO 200
430 IF OL(OB)<>0 THEN PRINT "YOU DON'T HAVE IT.":GOTO 200
435 OL(OB)=R:PRINT "DROPPED.":GOTO 200
440 REM INVENTORY: EVERYTHING AT LOCATION 0
445 X$="":FOR J=1 TO NO:IF OL(J)=0 THEN X$=X$+" "+OB$(J)
450 NEXT:IF X$="" THEN X$=" NOTHING"
455 X$="YOU HAVE:"+X$:GOSUB 700:GOTO 200
460 REM OPEN DOOR: ONLY IN THE HALL, ONLY WITH THE KEY
462 IF N<>35 THEN PRINT "OPEN WHAT?":GOTO 200
464 IF R<>1 THEN PRINT "THERE'S NO DOOR HERE.":GOTO 200
466 IF DO THEN PRINT "IT'S ALREADY OPEN.":GOTO 200
467 IF OL(1)<>0 THEN PRINT "IT'S LOCKED.":GOTO 200
468 DO=1:EX(1,4)=7:PRINT "THE KEY TURNS. THE DOOR SWINGS OPEN!":GOTO 200
470 REM READ NOTE
472 IF OB<>2 THEN PRINT "READ WHAT?":GOTO 200
474 IF OL(2)<>0 AND OL(2)<>R THEN PRINT "I DON'T SEE IT.":GOTO 200
476 PRINT "'THE SPARE KEY IS IN THE OFFICE. -J.'":GOTO 200
480 PRINT "I DON'T KNOW THE WORD ";X$;".":GOTO 200
500 REM --- LOOK UP A WORD: WHOLE WORD, OR FIRST 3 LETTERS ---
510 C=0:FOR I=1 TO NW:Y$=VW$(I)
520 IF X$=Y$ OR (LEN(X$)>=3 AND LEFT$(X$,3)=LEFT$(Y$,3)) THEN C=VC(I):I=NW
530 NEXT:RETURN
600 REM --- DESCRIBE THE ROOM, THEN WHAT'S IN IT ---
610 PRINT:PRINT "{RVS}";RN$(R);"{OFF}":X$=RD$(R):GOSUB 700
615 FOR J=1 TO NO:IF OL(J)=R THEN PRINT "THERE IS A ";OB$(J);" HERE."
617 NEXT
620 PRINT "EXITS:";:FOR D=1 TO 4:IF EX(R,D) THEN PRINT " ";D$(D);
630 NEXT:PRINT:RETURN
700 REM --- PRINT X$, BREAKING LINES BETWEEN WORDS ---
710 IF LEN(X$)<40 THEN PRINT X$:RETURN
720 FOR I=40 TO 1 STEP -1:IF MID$(X$,I,1)<>" " THEN NEXT
730 PRINT LEFT$(X$,I-1):X$=MID$(X$,I+1):GOTO 710
800 REM --- SAVE: EVERYTHING THAT CAN CHANGE, ONE PER LINE ---
810 OPEN 2,8,2,"@"+F$+",S,W":GOSUB 900:IF EN THEN 200
820 PRINT#2,R:PRINT#2,MV:PRINT#2,DO
830 FOR J=1 TO NO:PRINT#2,OL(J):NEXT:CLOSE 2
840 GOSUB 900:IF EN=0 THEN PRINT "GAME SAVED."
845 GOTO 200
850 REM --- LOAD: READ IT BACK IN THE SAME ORDER ---
860 OPEN 2,8,2,F$+",S,R":GOSUB 900:IF EN THEN 200
870 INPUT#2,R,MV,DO:FOR J=1 TO NO:INPUT#2,OL(J):NEXT:CLOSE 2
880 EX(1,4)=0:IF DO THEN EX(1,4)=7
890 PRINT "GAME LOADED.":GOSUB 600:GOTO 200
900 REM --- CHECK THE DRIVE (CS 100) ---
910 INPUT#15,EN,EM$,ET,ES:IF EN<2 THEN EN=0:RETURN
915 CLOSE 2:IF EN=62 THEN PRINT "NO SAVED GAME YET.":RETURN
920 PRINT "DISK ERROR";EN;EM$
930 IF EN=72 THEN PRINT "THE GAME WASN'T SAVED. FREE SOME SPACE":PRINT "(FORMAT OR SCRATCH) AND SAVE AGAIN."
940 RETURN
1000 REM ROOM NAME, DESCRIPTION, EXITS NORTH SOUTH EAST WEST
1010 DATA HALLWAY,"A LONG HALLWAY. LOCKERS LINE THE WALLS. THE DOOR TO THE WEST LEADS OUTSIDE.",2,5,3,0
1020 DATA CLASSROOM,"DESKS IN ROWS. A PET WAITS ON THE TEACHER'S DESK.",0,1,4,0
1030 DATA LIBRARY,"SHELVES OF BOOKS. IT'S VERY QUIET.",4,0,0,1
1040 DATA SCIENCE LAB,"BEAKERS, AND A SKELETON IN THE CORNER.",0,3,0,2
1050 DATA GYM,"A HUGE ROOM. IT SMELLS OF SNEAKERS.",1,0,6,0
1060 DATA OFFICE,"THE PRINCIPAL'S OFFICE. YOU SHOULDN'T BE HERE!",0,0,0,5
1070 DATA OUTSIDE,"COOL NIGHT AIR, AND THE BUS STOP.",0,0,0,0
1080 REM OBJECTS AND WHERE THEY START (0 = CARRIED)
1090 DATA KEY,6,NOTE,2,BALL,5
1100 REM WORDS: 1-11 VERBS, 21-24 DIRECTIONS, 31-35 THINGS
1110 DATA GO,1,WALK,1,LOOK,2,QUIT,3,HELP,4,TAKE,5,GET,5,DROP,6
1115 DATA INVENTORY,7,I,7,OPEN,8,UNLOCK,8,SAVE,9,LOAD,10,READ,11
1120 DATA NORTH,21,N,21,SOUTH,22,S,22,EAST,23,E,23,WEST,24,W,24
1130 DATA KEY,31,NOTE,32,BALL,33,DOOR,35,*,0
1140 DATA NORTH,SOUTH,EAST,WEST

Assignment CS 300-6: (1) make the library dark: you can only see what's there while you carry a FLASHLIGHT, which you'll have to place somewhere. (2) Let the player carry at most two things. (3) Add a score: 10 points for each object found, saved and loaded with the game. What else has to go in the save file?

CS 300 closing project · A little language or adventure of your own

In CS 300-6 every puzzle was a few lines of code. In this starter engine, the puzzles are data too. Each rule in lines 2190–2230 says: when the player types this verb and this noun, in this room, carrying this object, do this action and print this message. The rule interpreter (lines 1000–1140) tries the rules in order, and the first one that matches wins. Everything below line 2000 is the world. Replace it, and the same engine plays a different game.

  1. Try it: OPEN DOOR in the hallway is locked (that's rule 2200, which only matches when rule 2190 doesn't). The note's rule says where the key is. OPEN DESK in the office uses action 2 to move the hidden KEY (location 99) into the room. Then the door's rule adds a new exit with action 1, and walking into room 7 wins.
  2. Choose one: (a) An adventure of your own, written only as DATA: at least 10 rooms, 6 objects and 8 rules, and a map on paper. Add at least one new action to the interpreter, such as 3 to end the game or 4 to change a room's description. (b) A little language of your own: take the CS 300-4 interpreter and add GOSUB and RETURN, FOR and NEXT, or string variables. Then write three programs in it that test every statement.
  3. Choose two more: SAVE and LOAD with the CS 100 drive checks (CS 300-6); a two-object parser that understands PUT KEY IN BOX; loading the whole world from a disk file, so the engine has no DATA of its own; a score; or a BFS hint command that tells the player how many moves the exit is (CS 200-6).
  4. Hand in the listing; the map or grammar on one page; a walkthrough that wins (or test programs that run); and a page on the bug that took you longest to find.
10 REM CS 300 PROJECT: A WORLD OF YOUR OWN
20 REM ENGINE + WORLD DATA + PUZZLE RULES AS DATA
100 PRINT "{CLR}CS 300 PROJECT  ADVENTURE ENGINE"
110 DIM RN$(20),RD$(20),EX(20,4),VW$(40),VC(40),D$(4),OB$(10),OL(10)
120 DIM RV(20),RO(20),RR(20),RQ(20),RA(20),R1(20),R2(20),R3(20),RM$(20),RU(20)
130 READ TT$,NR,WR:FOR R=1 TO NR:READ RN$(R),RD$(R):FOR D=1 TO 4:READ EX(R,D):NEXT D,R
140 READ NO:FOR J=1 TO NO:READ OB$(J),OL(J):NEXT
150 NW=0
160 NW=NW+1:READ VW$(NW),VC(NW):IF VW$(NW)<>"*" THEN 160
170 NW=NW-1:NU=0
180 NU=NU+1:READ RV(NU):IF RV(NU)=0 THEN NU=NU-1:GOTO 195
190 READ RO(NU),RR(NU),RQ(NU),RA(NU),R1(NU),R2(NU),R3(NU),RM$(NU):GOTO 180
195 FOR D=1 TO 4:READ D$(D):NEXT
196 PRINT "{CLR}{RVS}";TT$;"{OFF}"
197 READ X$:GOSUB 700
198 R=1:MV=0:GOSUB 600
200 REM --- READ A COMMAND, SPLIT IT INTO TWO WORDS ---
210 PRINT:PRINT "WHAT NOW";:INPUT L$:MV=MV+1
220 W1$=L$:W2$="":FOR I=1 TO LEN(L$):IF MID$(L$,I,1)=" " THEN W1$=LEFT$(L$,I-1):W2$=MID$(L$,I+1):I=LEN(L$)
230 NEXT
240 X$=W1$:GOSUB 500:V=C:IF V=0 THEN 480
250 N=0:IF W2$="" THEN 270
260 X$=W2$:GOSUB 500:N=C:IF N=0 THEN 480
270 IF V>20 AND V<25 THEN N=V:V=1
280 IF V>20 THEN PRINT "WHAT DO YOU WANT TO DO WITH IT?":GOTO 200
290 OB=0:IF N>30 THEN OB=N-30:IF OB>NO THEN OB=0
300 REM --- BUILT-IN VERBS 1-7; ANYTHING ELSE GOES TO THE RULES ---
310 IF V>7 THEN 1000
315 ON V GOTO 320,350,360,370,400,420,440
320 IF N<21 OR N>24 THEN PRINT "GO WHERE?":GOTO 200
340 X=EX(R,N-20):IF X=0 THEN PRINT "YOU CAN'T GO THAT WAY.":GOTO 200
345 R=X:GOSUB 600:IF R=WR THEN PRINT:PRINT "YOU WIN, IN";MV;"MOVES!":END
347 GOTO 200
350 GOSUB 600:GOTO 200
360 PRINT "YOU GAVE UP AFTER";MV;"MOVES.":END
370 X$="I KNOW:":FOR J=1 TO NW:X$=X$+" "+VW$(J):NEXT:GOSUB 700:GOTO 200
400 IF OB=0 THEN PRINT "TAKE WHAT?":GOTO 200
412 IF OL(OB)=0 THEN PRINT "YOU ALREADY HAVE IT.":GOTO 200
415 IF OL(OB)<>R THEN PRINT "I DON'T SEE A ";OB$(OB);" HERE.":GOTO 200
418 OL(OB)=0:PRINT "TAKEN.":GOTO 200
420 IF OB=0 THEN PRINT "DROP WHAT?":GOTO 200
430 IF OL(OB)<>0 THEN PRINT "YOU DON'T HAVE IT.":GOTO 200
435 OL(OB)=R:PRINT "DROPPED.":GOTO 200
440 X$="":FOR J=1 TO NO:IF OL(J)=0 THEN X$=X$+" "+OB$(J)
450 NEXT:IF X$="" THEN X$=" NOTHING"
455 X$="YOU HAVE:"+X$:GOSUB 700:GOTO 200
480 PRINT "I DON'T KNOW THE WORD ";X$;".":GOTO 200
500 REM --- LOOK UP A WORD: WHOLE WORD, OR FIRST 3 LETTERS ---
510 C=0:FOR I=1 TO NW:Y$=VW$(I)
520 IF X$=Y$ OR (LEN(X$)>=3 AND LEFT$(X$,3)=LEFT$(Y$,3)) THEN C=VC(I):I=NW
530 NEXT:RETURN
600 REM --- DESCRIBE THE ROOM, THEN WHAT'S IN IT ---
610 PRINT:PRINT "{RVS}";RN$(R);"{OFF}":X$=RD$(R):GOSUB 700
615 FOR J=1 TO NO:IF OL(J)=R THEN PRINT "THERE IS A ";OB$(J);" HERE."
617 NEXT
620 PRINT "EXITS:";:FOR D=1 TO 4:IF EX(R,D) THEN PRINT " ";D$(D);
630 NEXT:PRINT:RETURN
700 REM --- PRINT X$, BREAKING LINES BETWEEN WORDS ---
710 IF LEN(X$)<40 THEN PRINT X$:RETURN
720 FOR I=40 TO 1 STEP -1:IF MID$(X$,I,1)<>" " THEN NEXT
730 PRINT LEFT$(X$,I-1):X$=MID$(X$,I+1):GOTO 710
1000 REM --- THE RULE INTERPRETER ---
1010 REM A RULE: VERB, NOUN, ROOM (0=ANY), NEEDS (0=NOTHING),
1020 REM ACTION, 3 ARGUMENTS, MESSAGE. FIRST MATCH WINS.
1030 HT=0:FOR U=1 TO NU:IF RV(U)<>V OR RO(U)<>N THEN 1090
1040 IF RR(U)<>0 AND RR(U)<>R THEN 1090
1050 HT=1:IF RQ(U)<>0 THEN IF OL(RQ(U))<>0 THEN 1090
1060 IF RU(U) THEN PRINT "YOU ALREADY DID THAT.":GOTO 200
1070 X$=RM$(U):GOSUB 700:GOSUB 1100:GOTO 200
1090 NEXT
1095 IF HT THEN PRINT "YOU NEED SOMETHING FOR THAT.":GOTO 200
1096 PRINT "NOTHING HAPPENS.":GOTO 200
1100 REM ACTIONS: 0 JUST SAY IT, 1 NEW EXIT (ROOM,DIR,TO),
1110 REM 2 MOVE AN OBJECT (OBJECT,TO ROOM)
1120 IF RA(U)=1 THEN EX(R1(U),R2(U))=R3(U):RU(U)=1
1130 IF RA(U)=2 THEN OL(R1(U))=R2(U):RU(U)=1
1140 RETURN
2000 REM ===== THE WORLD: CHANGE EVERYTHING BELOW =====
2010 REM TITLE, NUMBER OF ROOMS, THE ROOM THAT WINS
2020 DATA AFTER HOURS III,7,7
2030 REM ROOM NAME, DESCRIPTION, EXITS NORTH SOUTH EAST WEST
2040 DATA HALLWAY,"A LONG HALLWAY. LOCKERS LINE THE WALLS. THE DOOR TO THE WEST LEADS OUTSIDE.",2,5,3,0
2050 DATA CLASSROOM,"DESKS IN ROWS. A PET WAITS ON THE TEACHER'S DESK.",0,1,4,0
2060 DATA LIBRARY,"SHELVES OF BOOKS. IT'S VERY QUIET.",4,0,0,1
2070 DATA SCIENCE LAB,"BEAKERS, AND A SKELETON IN THE CORNER.",0,3,0,2
2080 DATA GYM,"A HUGE ROOM. IT SMELLS OF SNEAKERS.",1,0,6,0
2090 DATA OFFICE,"THE PRINCIPAL'S OFFICE. THERE'S A BIG DESK.",0,0,0,5
2100 DATA OUTSIDE,"COOL NIGHT AIR, AND THE BUS STOP.",0,0,0,0
2110 REM OBJECTS: NAME, WHERE IT STARTS (0 CARRIED, 99 HIDDEN)
2120 DATA 3,KEY,99,NOTE,2,BALL,5
2130 REM WORDS: 1-7 BUILT IN, 8+ FOR RULES, 21-24 DIRECTIONS, 31+ THINGS
2140 DATA GO,1,WALK,1,LOOK,2,QUIT,3,HELP,4,TAKE,5,GET,5,DROP,6
2150 DATA INVENTORY,7,I,7,OPEN,8,UNLOCK,8,READ,9,KICK,10
2160 DATA NORTH,21,N,21,SOUTH,22,S,22,EAST,23,E,23,WEST,24,W,24
2170 DATA KEY,31,NOTE,32,BALL,33,DOOR,34,DESK,35,*,0
2180 REM RULES: VERB,NOUN,ROOM,NEEDS,ACTION,A1,A2,A3,MESSAGE
2190 DATA 8,34,1,1,1,1,4,7,"THE KEY TURNS. THE DOOR SWINGS OPEN!"
2200 DATA 8,34,1,0,0,0,0,0,"IT'S LOCKED."
2210 DATA 8,35,6,0,2,1,6,0,"INSIDE THE DESK IS A KEY."
2220 DATA 9,32,0,2,0,0,0,0,"'THE SPARE KEY IS IN THE PRINCIPAL'S DESK. -J.'"
2230 DATA 10,33,0,3,0,0,0,0,"BOING. IT BOUNCES OFF THE WALL."
2240 DATA 0
2250 DATA NORTH,SOUTH,EAST,WEST
2260 DATA "YOU'RE LOCKED IN SCHOOL AFTER HOURS. FIND A WAY OUT. TYPE HELP FOR THE WORDS I KNOW."

Game lessons

1 · Hello, screen

PRINT writes text where the cursor is. CHR$(147) or {CLR} in a string clears the screen, {RVS} turns on reverse letters and ; keeps the cursor on the same line.

10 PRINT "{CLR}{RVS} HELLO FROM PIXEL 2001 {OFF}"
20 PRINT
30 FOR I=1 TO 10
40 PRINT SPC(I);"*";SPC(20-2*I);"*"
50 NEXT
60 PRINT "{DOWN}{DOWN}THAT IS A V MADE OF STARS."
2 · POKE: drawing straight into screen memory

The screen is 1000 bytes of memory starting at 32768: 40 across, 25 down. The cell at column X, row Y is 32768+Y*40+X. POKE puts a screen code there (81 is a ball, 160 a solid block, 32 a space). Adding 128 to a code shows it in reverse.

10 PRINT "{CLR}":S=32768
20 FOR X=0 TO 39:POKE S+X,160:POKE S+24*40+X,160:NEXT
30 FOR Y=0 TO 24:POKE S+Y*40,160:POKE S+Y*40+39,160:NEXT
40 X=1:Y=1:DX=1:DY=1
50 POKE S+Y*40+X,32
60 IF X+DX<1 OR X+DX>38 THEN DX=-DX
70 IF Y+DY<1 OR Y+DY>23 THEN DY=-DY
80 X=X+DX:Y=Y+DY:POKE S+Y*40+X,81
90 FOR D=1 TO 15:NEXT:GOTO 50
3 · GET: steering without stopping the game

INPUT waits for RETURN, which stops the action. GET K$ peeks at the keyboard and returns an empty string if nothing was pressed, so the game keeps moving. Use W A S D, the cursor keys or the arrow pad.

10 PRINT "{CLR}USE W A S D OR CURSOR KEYS. Q QUITS":S=32768
20 X=20:Y=12
30 POKE S+Y*40+X,81
40 GET K$:IF K$="" THEN 40
50 POKE S+Y*40+X,46
60 IF (K$="W" OR K$=CHR$(145)) AND Y>1 THEN Y=Y-1
70 IF (K$="S" OR K$=CHR$(17)) AND Y<24 THEN Y=Y+1
80 IF (K$="A" OR K$=CHR$(157)) AND X>0 THEN X=X-1
90 IF (K$="D" OR K$=CHR$(29)) AND X<39 THEN X=X+1
100 IF K$="Q" THEN END
110 GOTO 30
4 · PEEK: walls, gems and collisions

PEEK reads what is on the screen, so the screen itself is your map. Before moving, look at the next cell: a block (160) means wall, a diamond (90) means a gem. TI counts sixtieths of a second since power-on.

10 PRINT "{CLR}":S=32768:SC=0
20 FOR I=1 TO 60:POKE S+40+INT(RND(1)*920),160:NEXT
30 FOR I=1 TO 15:POKE S+40+INT(RND(1)*920),90:NEXT
40 X=20:Y=12:POKE S+Y*40+X,81:T=TI
50 GET K$:NX=X:NY=Y
60 IF K$="W" OR K$=CHR$(145) THEN NY=Y-1
70 IF K$="S" OR K$=CHR$(17) THEN NY=Y+1
80 IF K$="A" OR K$=CHR$(157) THEN NX=X-1
90 IF K$="D" OR K$=CHR$(29) THEN NX=X+1
100 IF NX<0 OR NX>39 OR NY<1 OR NY>24 THEN 50
110 C=PEEK(S+NY*40+NX):IF C=160 THEN 50
120 IF C=90 THEN SC=SC+1
130 POKE S+Y*40+X,32:X=NX:Y=NY:POKE S+Y*40+X,81
140 PRINT "{HOME}GEMS";SC;"  TIME";INT((TI-T)/60);"  "
150 IF SC<15 THEN 50
160 PRINT "{HOME}ALL GEMS IN";INT((TI-T)/60);"SECONDS!     "
5 · Creature chase AI (the 1979 problem)

Back in 1979 Garnet tried to write a maze chase game on a PET and the monsters kept getting stuck on walls. Here is a simple fix in three steps. 1: work out which way is closer to the player with SGN. 2: try the bigger distance first, then the other axis. 3: if both are blocked, take a random step so the creature slides around the wall. The creature moves every other turn so you can escape.

10 PRINT "{CLR}":S=32768:W=160
20 FOR I=0 TO 39:POKE S+40+I,W:POKE S+960+I,W:NEXT
30 FOR I=1 TO 23:POKE S+I*40,W:POKE S+I*40+39,W:NEXT
40 FOR I=1 TO 8:R=INT(RND(1)*18)+3:C=INT(RND(1)*30)+4
50 FOR J=0 TO 4:POKE S+R*40+C+J,W:NEXT:NEXT
60 PX=3:PY=3:CX=34:CY=20:T=0:T0=TI
70 POKE S+PY*40+PX,81:POKE S+CY*40+CX,88
80 GET K$:NX=PX:NY=PY
90 IF K$="W" OR K$=CHR$(145) THEN NY=PY-1
100 IF K$="S" OR K$=CHR$(17) THEN NY=PY+1
110 IF K$="A" OR K$=CHR$(157) THEN NX=PX-1
120 IF K$="D" OR K$=CHR$(29) THEN NX=PX+1
130 IF PEEK(S+NY*40+NX)=32 THEN POKE S+PY*40+PX,32:PX=NX:PY=NY:POKE S+PY*40+PX,81
140 T=T+1:IF T/2<>INT(T/2) THEN 80
200 DX=SGN(PX-CX):DY=SGN(PY-CY)
210 IF ABS(PX-CX)<ABS(PY-CY) THEN 240
220 IF DX<>0 AND PEEK(S+CY*40+CX+DX)<>W THEN NX=CX+DX:NY=CY:GOTO 270
230 IF DY<>0 AND PEEK(S+(CY+DY)*40+CX)<>W THEN NX=CX:NY=CY+DY:GOTO 270
235 GOTO 250
240 IF DY<>0 AND PEEK(S+(CY+DY)*40+CX)<>W THEN NX=CX:NY=CY+DY:GOTO 270
245 IF DX<>0 AND PEEK(S+CY*40+CX+DX)<>W THEN NX=CX+DX:NY=CY:GOTO 270
250 R=INT(RND(1)*4):NX=CX:NY=CY
255 IF R=0 THEN NX=CX+1
256 IF R=1 THEN NX=CX-1
257 IF R=2 THEN NY=CY+1
258 IF R=3 THEN NY=CY-1
260 IF PEEK(S+NY*40+NX)=W THEN 80
270 POKE S+CY*40+CX,32:CX=NX:CY=NY:POKE S+CY*40+CX,88
280 IF CX<>PX OR CY<>PY THEN 80
290 PRINT "{HOME}{RVS} CAUGHT AFTER";INT((TI-T0)/60);"SECONDS! "

Try it: change line 140 so the creature moves every turn, or delete lines 250 to 260 and watch it get stuck on walls the 1979 way.

6 · Sound and the keyboard matrix

The machine can beep through its CB2 line. POKE 59467,16 turns the sound on, 59466 sets the wave pattern (15 is a square wave) and 59464 sets the pitch (smaller is higher, 0 is silent). PEEK(151) tells you which key is held down right now (255 = none), which is great for smooth movement.

10 PRINT "{CLR}HOLD ANY KEY TO PLAY A NOTE. Q QUITS"
20 POKE 59467,16:POKE 59466,15
30 K=PEEK(151):IF K=255 THEN POKE 59464,0:GOTO 30
40 POKE 59464,40+K*3
50 PRINT "{HOME}{DOWN}{DOWN}KEY CODE";K;"  "
60 GET K$:IF K$<>"Q" THEN 30
70 POKE 59464,0:POKE 59467,0
7 · Putting it together: Moon Moth

A whole little game: collect the glowing spores (diamonds) while two moth-hunters chase you with the lesson 5 brain. Each spore is worth 10, and the hunters speed up as the score climbs. Read the listing, then make it yours: more hunters, a bonus item, or a level 2.

10 PRINT "{CLR}":S=32768:W=160:SC=0:DL=2
20 FOR I=0 TO 39:POKE S+40+I,W:POKE S+960+I,W:NEXT
30 FOR I=1 TO 23:POKE S+I*40,W:POKE S+I*40+39,W:NEXT
40 FOR I=1 TO 10:R=INT(RND(1)*19)+3:C=INT(RND(1)*32)+3
50 FOR J=0 TO 3:POKE S+R*40+C+J,W:NEXT:NEXT
60 FOR I=1 TO 12:GOSUB 600:NEXT
70 DIM HX(2),HY(2):HX(1)=2:HY(1)=22:HX(2)=37:HY(2)=22
80 PX=20:PY=2:POKE S+PY*40+PX,81:T=0:POP=0
90 GET K$:NX=PX:NY=PY
100 IF K$="W" OR K$=CHR$(145) THEN NY=PY-1
110 IF K$="S" OR K$=CHR$(17) THEN NY=PY+1
120 IF K$="A" OR K$=CHR$(157) THEN NX=PX-1
130 IF K$="D" OR K$=CHR$(29) THEN NX=PX+1
140 C=PEEK(S+NY*40+NX):IF C=88 THEN 700
150 IF C=W THEN 190
160 IF C=90 THEN SC=SC+10:GOSUB 600:POKE 59467,16:POKE 59466,15:POKE 59464,60
170 POKE S+PY*40+PX,32:PX=NX:PY=NY:POKE S+PY*40+PX,81
190 PRINT "{HOME}SCORE";SC:IF T=3 THEN POKE 59464,0
200 T=T+1:IF T<DL THEN 90
210 T=0:IF SC>=100 THEN DL=1
220 FOR H=1 TO 2:CX=HX(H):CY=HY(H):GOSUB 400:NEXT:IF POP THEN 700
230 GOTO 90
400 DX=SGN(PX-CX):DY=SGN(PY-CY):NX=CX:NY=CY
410 IF ABS(PX-CX)>=ABS(PY-CY) AND DX<>0 THEN NX=CX+DX:IF PEEK(S+NY*40+NX)<>W THEN 470
420 NX=CX:IF DY<>0 THEN NY=CY+DY:IF PEEK(S+NY*40+NX)<>W THEN 470
430 NY=CY:IF DX<>0 THEN NX=CX+DX:IF PEEK(S+NY*40+NX)<>W THEN 470
440 NX=CX+INT(RND(1)*3)-1:NY=CY+INT(RND(1)*3)-1
450 IF PEEK(S+NY*40+NX)<>32 AND PEEK(S+NY*40+NX)<>81 THEN RETURN
470 C=PEEK(S+NY*40+NX):IF C=88 OR C=90 THEN RETURN
480 POKE S+CY*40+CX,32:HX(H)=NX:HY(H)=NY:POKE S+NY*40+NX,88
490 IF C=81 THEN POP=1
500 RETURN
600 Q=S+80+INT(RND(1)*880):IF PEEK(Q)<>32 THEN 600
610 POKE Q,90:RETURN
700 POKE 59464,0:PRINT "{HOME}{RVS} A HUNTER GOT YOU! FINAL SCORE";SC;"{OFF}"
8 · Built-in program: Crate Corral

Crate Corral is an original type-in written for Pixel 2001 in the style of a 1980 magazine listing (about 3K of BASIC, so it fits an 8K machine). Push rows of crates (the checkerboard ▒ blocks) to wall in the Grumblebugs (♠). A bug with no empty square next to it turns into a gem ◆ worth 100. Walk over a gem for 25 more. Clear every bug for a level bonus. Each level adds a bug and makes them faster, and you pick speed 1 to 3 at the start.

How it works, section by section:

  • Lines 10–70, setup: the title screen, a GET loop that waits for a speed key, and the variables. S is screen memory, W is the wall code (160), B is a crate (102), P is the player (81) and G is a bug (65). The arrays X, Y and A hold each bug's position and whether it is still free. U and V are the four step directions.
  • Lines 110–210, drawing the corral: POKE walls round the edge, then scatter 250 crates on empty cells. Bugs start at least 10 steps from you. DL is how many key checks pass between bug moves, so a higher level or speed means a smaller DL.
  • Lines 310–399, the main loop: GET K$ reads a key without waiting (lesson 3). Every DL passes, each free bug takes a turn.
  • Lines 510–590, pushing: the player looks at the next cell (lesson 4). If it is a crate, line 570 walks along the whole row of crates until it finds the end. If the end is an empty space, one crate moves to that space and the player steps forward, which looks exactly like the whole row sliding along.
  • Lines 610–730, Grumblebug brains: first count the empty neighbours. If there are none, the bug is trapped and turns into a gem. Otherwise it uses the lesson 5 chase (bigger distance first, then the other axis), with a 1 in 4 chance of a random step so bugs wander out of dead ends.
  • Lines 800–995, scoring, lives and sound: the level bonus, losing a life and the replay prompt. Line 950 PRINTs the status at {HOME}, and line 990 beeps through CB2 (lesson 6).
10 REM CRATE CORRAL: AN ORIGINAL PIXEL 2001 TYPE-IN
20 PRINT "{CLR}{RVS} CRATE CORRAL {OFF}":PRINT:PRINT "PUSH ROWS OF CRATES TO TRAP THE"
30 PRINT "GRUMBLEBUGS. A BUG WITH NOWHERE LEFT TO":PRINT "GO TURNS INTO A GEM: 100 POINTS!"
40 PRINT:PRINT "MOVE: W A S D OR CURSOR KEYS":PRINT:PRINT "SPEED 1 (SLOW) TO 3 (FAST)?"
50 GET K$:IF K$<"1" OR K$>"3" THEN 50
60 SP=VAL(K$):S=32768:W=160:B=102:P=81:G=65:SC=0:LV=1:LI=3
70 DIM X(9),Y(9),A(9),U(3),V(3):U(0)=1:U(1)=-1:V(2)=1:V(3)=-1
100 REM BUILD A CORRAL
110 PRINT "{CLR}":NB=2+LV:IF NB>9 THEN NB=9
120 FOR I=0 TO 39:POKE S+40+I,W:POKE S+960+I,W:NEXT
130 FOR I=2 TO 23:POKE S+I*40,W:POKE S+I*40+39,W:NEXT
140 FOR I=1 TO 250:Q=S+80+INT(RND(1)*880):IF PEEK(Q)=32 THEN POKE Q,B
150 NEXT:PX=20:PY=12:GOSUB 900
160 FOR H=1 TO NB:A(H)=1
170 X(H)=INT(RND(1)*36)+2:Y(H)=INT(RND(1)*20)+3
180 IF ABS(X(H)-PX)+ABS(Y(H)-PY)<10 OR PEEK(S+Y(H)*40+X(H))<>32 THEN 170
190 POKE S+Y(H)*40+X(H),G:NEXT
200 NL=NB:DL=(4-SP)*3+4-LV:IF DL<1 THEN DL=1
210 GOSUB 950
300 REM MAIN LOOP
310 GET K$:DX=0:DY=0
320 IF K$="W" OR K$=CHR$(145) THEN DY=-1
330 IF K$="S" OR K$=CHR$(17) THEN DY=1
340 IF K$="A" OR K$=CHR$(157) THEN DX=-1
350 IF K$="D" OR K$=CHR$(29) THEN DX=1
360 IF DX OR DY THEN GOSUB 500
365 IF CA THEN 850
370 T=T+1:IF T<DL THEN 310
380 T=0:POKE 59464,0:FOR H=1 TO NB:IF A(H) THEN GOSUB 600
390 NEXT:IF CA THEN 850
395 IF NL=0 THEN 800
399 GOTO 310
500 REM PLAYER STEP OR PUSH
510 NX=PX+DX:NY=PY+DY:C=PEEK(S+NY*40+NX)
520 IF C=G THEN CA=1:RETURN
530 IF C=90 THEN SC=SC+25:C=32:GOSUB 950
540 IF C=32 THEN POKE S+PY*40+PX,32:PX=NX:PY=NY:GOSUB 900:RETURN
550 IF C<>B THEN RETURN
560 EX=NX:EY=NY
570 EX=EX+DX:EY=EY+DY:C=PEEK(S+EY*40+EX):IF C=B THEN 570
580 IF C<>32 THEN RETURN
590 POKE S+EY*40+EX,B:POKE S+PY*40+PX,32:PX=NX:PY=NY:GOSUB 900:GOTO 990
600 REM GRUMBLEBUG H
610 CX=X(H):CY=Y(H):N=0
620 FOR D=0 TO 3:C=PEEK(S+(CY+V(D))*40+CX+U(D)):IF C=32 OR C=P THEN N=N+1
630 NEXT:IF N>0 THEN 650
640 A(H)=0:NL=NL-1:POKE S+CY*40+CX,90:SC=SC+100:GOSUB 950:POKE 59464,30:GOTO 990
650 E=SGN(PX-CX):F=SGN(PY-CY):IF RND(1)<.25 THEN 690
660 IF ABS(PX-CX)>=ABS(PY-CY) THEN NX=CX+E:NY=CY:GOSUB 700:IF OK THEN 720
670 NX=CX:NY=CY+F:GOSUB 700:IF OK THEN 720
680 NX=CX+E:NY=CY:GOSUB 700:IF OK THEN 720
690 D=INT(RND(1)*4):NX=CX+U(D):NY=CY+V(D):GOSUB 700:IF OK=0 THEN 690
720 POKE S+CY*40+CX,32:X(H)=NX:Y(H)=NY:POKE S+NY*40+NX,G:IF C=P THEN CA=1
730 RETURN
700 C=PEEK(S+NY*40+NX):OK=(C=32 OR C=P):RETURN
800 REM CORRAL CLEARED
810 SC=SC+LV*100:PRINT "{HOME}{RVS} CORRAL CLEARED! BONUS";LV*100;"{OFF}       "
820 LV=LV+1:FOR I=1 TO 1500:NEXT:GOTO 110
850 REM CAUGHT
860 POKE 59464,0:LI=LI-1:CA=0:PRINT "{HOME}{RVS} A GRUMBLEBUG GOT YOU! {OFF}           "
865 FOR I=1 TO 1500:NEXT:IF LI=0 THEN 880
870 IF PEEK(S+PY*40+PX)=P THEN POKE S+PY*40+PX,32
875 PX=INT(RND(1)*36)+2:PY=INT(RND(1)*20)+3:IF PEEK(S+PY*40+PX)<>32 THEN 875
878 GOSUB 900:GOSUB 950:GOTO 310
880 IF SC>HI THEN HI=SC
885 PRINT "{HOME}{RVS} GAME OVER";SC;"BEST";HI;"AGAIN? Y/N {OFF}"
890 GET K$:IF K$="N" THEN END
895 IF K$<>"Y" THEN 890
897 SC=0:LV=1:LI=3:GOTO 110
900 POKE S+PY*40+PX,P:RETURN
950 PRINT "{HOME}SCORE";SC;" LEVEL";LV;" LIVES";LI;" BUGS";NL;"  ":RETURN
990 POKE 59467,16:POKE 59466,15:IF PEEK(59464)=0 THEN POKE 59464,90
995 RETURN

Make it yours: change the 250 on line 140 for more or fewer crates, give the bugs a smarter brain, or add a timer bonus using TI.

9 · Magazine remake: Pie Ambush (after Ambush!, CURSOR #23, 1980)

Pie Ambush is an original Pixel 2001 listing for two players at one keyboard. The idea comes from Ambush!, published on the cassette magazine CURSOR, issue #23 (1980), but the code is our own. In this version every step you take leaves a pie splat behind you, and instead of stepping you can fling a pie 3 squares ahead. Box your friend in so they have nowhere to go. The first player to 3 points wins.

How it works, section by section:

  • Lines 10–95, title and setup: PRINT the rules and wait for a key with a GET loop. The arrays hold each player's position (X, Y), facing (U, V), character (C), wins (WN) and keys (K$). DX and DY turn keys 1–4 into up, left, down and right.
  • Lines 110–150, drawing the screen: POKE a wall of code 160 round the kitchen, scatter 25 pies (code 86, the ╳ shape), then POKE the two players: a ball (81) and a ring (87).
  • Lines 210–230, checking for a trap: before each turn, PEEK the four cells around the current player. If none is empty (32), they are boxed in and lose the round.
  • Lines 310–330, reading keys: GET K$, then MID$ finds the key in that player's string ("WASDF" or "IJKLH"). Keys belonging to the other player are ignored, so no one can move out of turn.
  • Lines 350–385, moving and flinging: a step POKEs a pie where you were standing and your character into the new cell. A fling looks 3 cells ahead in the direction you last moved and drops a pie there if the cell is empty and inside the walls.
  • Lines 390–470, sound and scoring: a short CB2 beep, swap turns with TU=3-TU, add the point, and redraw a fresh kitchen until someone reaches 3.
10 REM PIE AMBUSH: AN ORIGINAL PIXEL 2001 TYPE-IN
20 REM IDEA INSPIRED BY AMBUSH! (CURSOR #23, 1980)
30 PRINT "{CLR}{RVS} PIE AMBUSH {OFF}":PRINT:PRINT "TWO PLAYERS TAKE TURNS. EVERY STEP"
40 PRINT "LEAVES A PIE SPLAT BEHIND YOU. BOX YOUR":PRINT "FRIEND IN SO THEY CANNOT MOVE!"
50 PRINT:PRINT "PLAYER 1 (BALL): W A S D, F FLINGS":PRINT "PLAYER 2 (RING): I J K L, H FLINGS"
60 PRINT:PRINT "FLINGING THROWS A PIE 3 SQUARES AHEAD":PRINT "INSTEAD OF STEPPING. FIRST TO 3 WINS."
70 PRINT:PRINT "PRESS ANY KEY TO START"
80 GET K$:IF K$="" THEN 80
90 S=32768:W=160:Q=86:DIM X(2),Y(2),U(2),V(2),C(2),WN(2),K$(2),DX(4),DY(4)
95 K$(1)="WASDF":K$(2)="IJKLH":C(1)=81:C(2)=87:DY(1)=-1:DX(2)=-1:DY(3)=1:DX(4)=1
100 REM DRAW THE KITCHEN
110 PRINT "{CLR}":FOR I=0 TO 39:POKE S+80+I,W:POKE S+960+I,W:NEXT
120 FOR I=3 TO 23:POKE S+I*40,W:POKE S+I*40+39,W:NEXT
130 FOR I=1 TO 25:R=S+120+INT(RND(1)*840):IF PEEK(R)=32 THEN POKE R,Q
140 NEXT:X(1)=8:Y(1)=13:X(2)=31:Y(2)=13:U(1)=1:V(1)=0:U(2)=-1:V(2)=0
150 FOR P=1 TO 2:POKE S+Y(P)*40+X(P),C(P):NEXT:TU=1
200 REM WHOSE TURN?
210 PRINT "{HOME}P1";WN(1);"  P2";WN(2);"   PLAYER";TU;"TO MOVE  "
220 N=0:FOR D=1 TO 4:IF PEEK(S+(Y(TU)+DY(D))*40+X(TU)+DX(D))=32 THEN N=N+1
230 NEXT:IF N=0 THEN 400
300 REM READ A KEY FOR THIS PLAYER
310 GET K$:IF K$="" THEN 310
320 M=0:FOR J=1 TO 5:IF K$=MID$(K$(TU),J,1) THEN M=J
330 NEXT:IF M=0 THEN 310
340 IF M=5 THEN 370
350 NX=X(TU)+DX(M):NY=Y(TU)+DY(M):IF PEEK(S+NY*40+NX)<>32 THEN 310
360 POKE S+Y(TU)*40+X(TU),Q:X(TU)=NX:Y(TU)=NY:U(TU)=DX(M):V(TU)=DY(M):POKE S+NY*40+NX,C(TU):F=60:GOTO 390
370 TX=X(TU)+3*U(TU):TY=Y(TU)+3*V(TU)
375 IF TX<1 OR TX>38 OR TY<3 OR TY>23 THEN 310
380 IF PEEK(S+TY*40+TX)<>32 THEN 310
385 POKE S+TY*40+TX,Q:F=120
390 POKE 59467,16:POKE 59466,15:POKE 59464,F:FOR I=1 TO 40:NEXT:POKE 59464,0
395 TU=3-TU:GOTO 210
400 REM SOMEBODY IS BOXED IN
410 WI=3-TU:WN(WI)=WN(WI)+1
420 PRINT "{HOME}{RVS} PLAYER";TU;"IS BOXED IN! POINT TO";WI;"{OFF}   "
430 FOR I=1 TO 2000:NEXT:IF WN(WI)<3 THEN 110
440 PRINT "{HOME}{RVS} PLAYER";WI;"WINS THE PIE FIGHT! AGAIN? Y/N {OFF}"
450 GET K$:IF K$="N" THEN END
460 IF K$<>"Y" THEN 450
470 WN(1)=0:WN(2)=0:GOTO 110
10 · Magazine remake: Kitten Copter (after Fire!, CURSOR #16, 1980, Brian Sawyer)

Kitten Copter is an original Pixel 2001 listing. The idea comes from Fire! by Brian Sawyer, published in the cassette magazine CURSOR, issue #16 (1980), but the code is our own. A forest fire spreads from tree (♣) to tree. Fly your copter (@) to rescue the kittens (K) before the flames reach them, and drop water to fight the fire. Refill your water at the lake in the top corner.

How it works, section by section:

  • Lines 10–90, setup: the title screen, then names for the screen codes: wall 160, tree 88, fire 170 (a reverse *), kitten 11 (the letter K) and lake 230. FX and FY form a list of burning cells.
  • Lines 110–210, drawing the forest: walls, 450 random trees, a 4×3 lake, 8 kittens and 3 starting fires on the far side. UC remembers what is under the copter so it can be put back when you fly away.
  • Lines 310–395, reading keys: a non-blocking GET loop. W A S D fly and SPACE drops water. Every 4 passes the fire gets a turn.
  • Lines 510–550, flying: PEEK the next cell. You can't fly into walls or fire. Touching a kitten rescues it, and touching the lake refills your water to 5.
  • Lines 610–640, water: two nested FOR loops visit the 9 cells round the copter and turn any fire into ash (46, a dot).
  • Lines 710–795, how the fire moves: three times a turn, pick a random burning cell from the list. If it has already been put out, remove it by copying the last entry over it. Otherwise it spreads to one random neighbour if that neighbour is a tree or a kitten. About 1 time in 12 it burns out to ash, so fires do end.
  • Lines 800–900, scoring: 50 per kitten, 5 per flame put out, and 100 if you put the whole fire out. Line 900 PRINTs the status at {HOME}.
10 REM KITTEN COPTER: AN ORIGINAL PIXEL 2001 TYPE-IN
20 REM IDEA INSPIRED BY FIRE! (CURSOR #16, 1980, BRIAN SAWYER)
30 PRINT "{CLR}{RVS} KITTEN COPTER {OFF}":PRINT:PRINT "A FOREST FIRE IS SPREADING! FLY YOUR"
40 PRINT "COPTER (@) WITH W A S D. TOUCH A KITTEN":PRINT "(K) TO RESCUE IT FOR 50 POINTS."
50 PRINT "SPACE DROPS WATER ON THE 9 SQUARES":PRINT "AROUND YOU. REFILL AT THE LAKE."
60 PRINT:PRINT "PRESS ANY KEY"
70 GET K$:IF K$="" THEN 70
80 S=32768:W=160:TR=88:FI=170:KI=11:LK=230:DIM FX(300),FY(300),U(3),V(3)
90 U(0)=1:U(1)=-1:V(2)=1:V(3)=-1:SC=0
100 REM DRAW THE FOREST
110 PRINT "{CLR}":FOR I=0 TO 39:POKE S+80+I,W:POKE S+960+I,W:NEXT
120 FOR I=3 TO 23:POKE S+I*40,W:POKE S+I*40+39,W:NEXT
130 FOR I=1 TO 450:R=S+120+INT(RND(1)*840):IF PEEK(R)=32 THEN POKE R,TR
140 NEXT:FOR Y=3 TO 5:FOR X=1 TO 4:POKE S+Y*40+X,LK:NEXT:NEXT
150 NK=8:FOR I=1 TO NK
160 X=INT(RND(1)*30)+8:Y=INT(RND(1)*18)+5:IF PEEK(S+Y*40+X)=KI THEN 160
170 POKE S+Y*40+X,KI:NEXT
180 NF=0:FOR I=1 TO 3:NF=NF+1:FX(NF)=INT(RND(1)*10)+28:FY(NF)=INT(RND(1)*18)+4
190 POKE S+FY(NF)*40+FX(NF),FI:NEXT
200 X=6:Y=4:UC=32:POKE S+Y*40+X,0:WA=5:RK=0:LO=0:T=0
210 GOSUB 900
300 REM MAIN LOOP: READ KEYS
310 GET K$:DX=0:DY=0
320 IF K$="W" THEN DY=-1
330 IF K$="S" THEN DY=1
340 IF K$="A" THEN DX=-1
350 IF K$="D" THEN DX=1
360 IF K$=" " THEN GOSUB 600
370 IF DX OR DY THEN GOSUB 500
380 T=T+1:IF T<4 THEN 310
390 T=0:GOSUB 700:IF NF=0 OR RK+LO=NK THEN 800
395 GOTO 310
500 REM FLY THE COPTER
510 NX=X+DX:NY=Y+DY:C=PEEK(S+NY*40+NX):IF C=W OR C=FI THEN RETURN
520 POKE S+Y*40+X,UC:X=NX:Y=NY:UC=C
530 IF C=KI THEN UC=32:RK=RK+1:SC=SC+50:POKE 59467,16:POKE 59466,15:POKE 59464,40:GOSUB 900
540 IF C=LK THEN WA=5:GOSUB 900
550 POKE S+Y*40+X,0:RETURN
600 REM DROP WATER
610 IF WA=0 THEN RETURN
620 WA=WA-1:FOR DY=-1 TO 1:FOR DX=-1 TO 1:Q=S+(Y+DY)*40+X+DX
630 IF PEEK(Q)=FI THEN POKE Q,46:SC=SC+5
640 NEXT:NEXT:DX=0:DY=0:POKE 59467,16:POKE 59466,51:POKE 59464,120:GOSUB 900:RETURN
700 REM THE FIRE SPREADS
710 POKE 59464,0:FOR Z=1 TO 3:IF NF=0 THEN RETURN
720 J=INT(RND(1)*NF)+1:Q=S+FY(J)*40+FX(J):IF PEEK(Q)<>FI THEN 790
730 D=INT(RND(1)*4):NX=FX(J)+U(D):NY=FY(J)+V(D):C=PEEK(S+NY*40+NX)
740 IF C=KI THEN LO=LO+1:GOSUB 900
750 IF (C=TR OR C=KI) AND NF<300 THEN POKE S+NY*40+NX,FI:NF=NF+1:FX(NF)=NX:FY(NF)=NY
760 IF RND(1)>.08 THEN 795
770 POKE Q,46
790 FX(J)=FX(NF):FY(J)=FY(NF):NF=NF-1
795 NEXT:RETURN
800 REM THE END
810 IF NF=0 THEN SC=SC+100:PRINT "{HOME}{RVS} FIRE OUT! +100{OFF}                   ":FOR I=1 TO 1500:NEXT
820 PRINT "{HOME}{RVS} SAVED";RK;"KITTENS. SCORE";SC;"AGAIN? Y/N {OFF}"
830 GET K$:IF K$="N" THEN END
840 IF K$<>"Y" THEN 830
850 SC=0:GOTO 110
900 PRINT "{HOME}SCORE";SC;" WATER";WA;" SAVED";RK;" LOST";LO;"  ":RETURN
11 · Magazine remake: Deep Digger (after Miner!, CURSOR #19, 1980)

Deep Digger is an original Pixel 2001 listing. The idea comes from Miner!, published in the cassette magazine CURSOR, issue #19 (1980), but the code is our own and it is a separate game from Dynamite Prospector. Dig through the dirt for hidden gold, then climb back up and sell it. The gold price moves up and down with every step, so the trick is to sell when it is high. You have 400 moves.

How it works, section by section:

  • Lines 10–90, setup: the rules, then names: dirt 102 (the checkerboard), boulder 81 and the miner 0 (@).
  • Lines 110–160, drawing the mine: fill rows 5–23 with dirt, scatter 60 boulders, and draw a ground line (99) with one entrance hole at column 20. The assay office is the reverse ball on the surface.
  • Lines 310–360, reading keys: this game waits for a key (IF K$="" THEN 310) because it is turn-based: nothing moves until you do. E sells, but only on the surface (Y<5).
  • Lines 380–420, digging: PEEK the next cell. Walls, boulders and the office block you. Digging into dirt has a 14% chance (RND(1)<.14) of finding a nugget, so the gold is never stored anywhere: it is decided the moment you dig.
  • Lines 430–450, the market: each move the price takes a random step of −4 to +4, kept between 5 and 60 by two IF lines. This is a random walk.
  • Lines 800–910, scoring: your banked cash is the score, and any gold you haven't sold is lost when the day ends.
10 REM DEEP DIGGER: AN ORIGINAL PIXEL 2001 TYPE-IN
20 REM IDEA INSPIRED BY MINER! (CURSOR #19, 1980)
30 PRINT "{CLR}{RVS} DEEP DIGGER {OFF}":PRINT:PRINT "DIG FOR GOLD WITH W A S D. EVERY SQUARE"
40 PRINT "OF DIRT YOU DIG MIGHT HIDE A NUGGET.":PRINT "BOULDERS CANNOT BE DUG."
50 PRINT:PRINT "CLIMB BACK TO THE SURFACE AND PRESS E":PRINT "TO SELL. THE PRICE CHANGES ALL THE"
60 PRINT "TIME: SELL WHEN IT IS HIGH! YOU HAVE":PRINT "400 MOVES. UNSOLD GOLD IS WORTH ZERO."
70 PRINT:PRINT "PRESS ANY KEY"
80 GET K$:IF K$="" THEN 80
90 S=32768:W=160:DI=102:RO=81:ME=0
100 REM DRAW THE MINE
110 PRINT "{CLR}":FOR I=0 TO 39:POKE S+160+I,W:POKE S+960+I,W:NEXT
120 FOR Y=5 TO 23:POKE S+Y*40,W:POKE S+Y*40+39,W:FOR X=1 TO 38:POKE S+Y*40+X,DI:NEXT:NEXT
130 FOR I=1 TO 60:POKE S+200+INT(RND(1)*760),RO:NEXT
140 FOR I=0 TO 39:POKE S+160+I,99:NEXT:POKE S+160+20,32:POKE S+120+30,81+128
150 X=20:Y=3:POKE S+Y*40+X,ME:G=0:CA=0:PR=20:ML=400
160 GOSUB 900
300 REM MAIN LOOP
310 GET K$:IF K$="" THEN 310
320 DX=0:DY=0:IF K$="W" THEN DY=-1
330 IF K$="S" THEN DY=1
340 IF K$="A" THEN DX=-1
350 IF K$="D" THEN DX=1
360 IF K$="E" AND Y<5 THEN CA=CA+G*PR:G=0:POKE 59467,16:POKE 59466,15:POKE 59464,30:GOSUB 900:GOTO 310
370 IF DX=0 AND DY=0 THEN 310
380 NX=X+DX:NY=Y+DY:IF NY<3 OR NX<0 OR NX>39 THEN 310
390 C=PEEK(S+NY*40+NX):IF C=W OR C=RO OR C=209 THEN 310
400 POKE 59464,0:IF C=DI AND RND(1)<.14 THEN G=G+1:POKE 59467,16:POKE 59466,15:POKE 59464,60
410 IF C=99 THEN 310
420 POKE S+Y*40+X,32:X=NX:Y=NY:POKE S+Y*40+X,ME
430 PR=PR+INT(RND(1)*9)-4:IF PR<5 THEN PR=5
440 IF PR>60 THEN PR=60
450 ML=ML-1:GOSUB 900:IF ML>0 THEN 310
800 REM END OF THE DAY
810 PRINT "{HOME}{RVS} DAY OVER! YOU BANKED $";CA;"AGAIN? Y/N {OFF}"
820 GET K$:IF K$="N" THEN END
830 IF K$<>"Y" THEN 820
840 GOTO 110
900 PRINT "{HOME}CASH $";CA;" GOLD";G;" PRICE $";PR;" MOVES";ML;" "
910 PRINT "SURFACE: PRESS E HERE TO SELL GOLD    ":RETURN
12 · Magazine remake: Lily Pad Lunch (after Frog!, CURSOR #19, 1980)

Lily Pad Lunch is an original Pixel 2001 listing. The idea comes from Frog!, published in the cassette magazine CURSOR, issue #19 (1980), but the code is our own. You are a frog on a lily pad. Swing your aim with A and D and press SPACE to flick your tongue at the bugs buzzing over the pond. Higher bugs are worth more, and you have 30 flicks.

How it works, section by section:

  • Lines 10–90, setup: arrays for 5 bugs (BX, BY and direction BD), plus AX and AY for 5 aim directions, read from a DATA line: two left, one left, straight up, one right and two right for every step up.
  • Lines 110–140, drawing the pond: water along the bottom, a lily pad of reverse characters and the frog (@). Subroutine 650 starts a bug at a random height on the left or right edge.
  • Lines 310–330, reading keys: A and D erase the + sight (610), change A, and draw it again (600). SPACE flicks the tongue.
  • Lines 350–370, bug movement: every 3 passes, erase each bug, add its direction, start it again if it flew off the edge, and POKE it back.
  • Lines 410–490, the tongue: step L along the aim line, POKEing dots, until it leaves the screen or PEEK finds a bug (42). Then erase the dots and work out which bug was hit by comparing positions.
  • Scoring: (24-TY)*5 pays more for bugs that are higher up. The game ends when your flicks run out.
10 REM LILY PAD LUNCH: AN ORIGINAL PIXEL 2001 TYPE-IN
20 REM IDEA INSPIRED BY FROG! (CURSOR #19, 1980)
30 PRINT "{CLR}{RVS} LILY PAD LUNCH {OFF}":PRINT:PRINT "YOU ARE A HUNGRY FROG (@) ON A LILY PAD."
40 PRINT "A AND D SWING YOUR AIM (+). SPACE FLICKS":PRINT "YOUR TONGUE. HIGHER BUGS ARE WORTH MORE."
50 PRINT "YOU HAVE 30 FLICKS.":PRINT:PRINT "PRESS ANY KEY"
60 GET K$:IF K$="" THEN 60
70 S=32768:BU=42:DIM BX(5),BY(5),BD(5),AX(4),AY(4)
80 FOR I=0 TO 4:READ AX(I),AY(I):NEXT
90 DATA -2,-1,-1,-1,0,-1,1,-1,2,-1
100 REM DRAW THE POND
110 PRINT "{CLR}":FOR I=0 TO 39:POKE S+920+I,102:NEXT
120 FX=20:FY=22:A=2:SC=0:SH=30
130 FOR I=17 TO 23:POKE S+FY*40+I,79+128:NEXT:POKE S+FY*40+FX,0
140 FOR B=1 TO 5:GOSUB 650:NEXT:GOSUB 600:GOSUB 900
300 REM MAIN LOOP
310 GET K$:IF K$="A" AND A>0 THEN GOSUB 610:A=A-1:GOSUB 600
320 IF K$="D" AND A<4 THEN GOSUB 610:A=A+1:GOSUB 600
330 IF K$=" " AND SH>0 THEN GOSUB 400
340 T=T+1:IF T<3 THEN 310
350 T=0:POKE 59464,0:FOR B=1 TO 5:POKE S+BY(B)*40+BX(B),32
360 BX(B)=BX(B)+BD(B):IF BX(B)<1 OR BX(B)>38 THEN GOSUB 650
370 POKE S+BY(B)*40+BX(B),BU:NEXT:GOSUB 600
380 IF SH=0 THEN 800
390 GOTO 310
400 REM FLICK THE TONGUE
410 SH=SH-1:HIT=0:L=0:GOSUB 610
420 L=L+1:TX=FX+AX(A)*L:TY=FY+AY(A)*L:IF TX<0 OR TX>39 OR TY<3 THEN 460
430 Q=S+TY*40+TX:IF PEEK(Q)=BU THEN HIT=1:GOTO 460
440 POKE Q,46:GOTO 420
460 FOR M=1 TO L-1:POKE S+(FY+AY(A)*M)*40+FX+AX(A)*M,32:NEXT
470 IF HIT=0 THEN GOSUB 600:GOSUB 900:RETURN
480 FOR B=1 TO 5:IF BX(B)=TX AND BY(B)=TY THEN POKE Q,32:SC=SC+(24-TY)*5:GOSUB 650
490 NEXT:POKE 59467,16:POKE 59466,15:POKE 59464,50:GOSUB 600:GOSUB 900:RETURN
600 POKE S+(FY+AY(A)*2)*40+FX+AX(A)*2,43:RETURN
610 POKE S+(FY+AY(A)*2)*40+FX+AX(A)*2,32:RETURN
650 BY(B)=INT(RND(1)*16)+3:BD(B)=1:BX(B)=1:IF RND(1)<.5 THEN BD(B)=-1:BX(B)=38
660 RETURN
800 PRINT "{HOME}{RVS} OUT OF FLICKS! SCORE";SC;"AGAIN? Y/N {OFF}"
810 GET K$:IF K$="N" THEN END
820 IF K$<>"Y" THEN 810
830 GOTO 110
900 PRINT "{HOME}SCORE";SC;"  FLICKS LEFT";SH;"  ":RETURN
13 · Magazine remake: Mower Meadow (after Lawn!, CURSOR, 1981, Kathy Higby)

Mower Meadow is an original Pixel 2001 listing. The idea comes from Lawn! by Kathy Higby, published in the cassette magazine CURSOR (1981), but the code is our own. Mode 1: mow the whole lawn before the fuel runs out, steering round the flower beds. Mode 2: mow only the dark squares to draw a heart in the grass.

How it works, section by section:

  • Lines 10–80, setup: pick mode 1 or 2 with a GET loop that only accepts those keys. Screen codes: grass 102, dark grass 230 and flower bed 88.
  • Lines 110–150, drawing the lawn (mode 1): two nested FOR loops POKE grass everywhere, then 12 random flower beds. Fuel is 1.25 times the number of grass squares, so there is a little room for mistakes.
  • Lines 200–240, the picture (mode 2): each DATA string is one row of the heart. MID$(R$,X,1) looks at one character at a time, and every # becomes dark grass. RESTORE lets the DATA be read again in the next game.
  • Lines 310–360, reading keys: one step per key press.
  • Lines 370–420, mowing: PEEK what you are about to drive onto. Walls stop you and flower beds count as bumps. Mowing grass (or dark grass in mode 2) counts towards MW, but in mode 2 mowing ordinary grass is a mistake.
  • Lines 800–860, scoring: mode 1 scores the percentage mowed, minus bumps, plus leftover fuel. Mode 2 scores 10 per heart square, minus 5 per mistake.
10 REM MOWER MEADOW: AN ORIGINAL PIXEL 2001 TYPE-IN
20 REM IDEA INSPIRED BY LAWN! (CURSOR, 1981, KATHY HIGBY)
30 PRINT "{CLR}{RVS} MOWER MEADOW {OFF}":PRINT:PRINT "STEER THE MOWER (@) WITH W A S D."
40 PRINT "EVERY STEP BURNS FUEL. DODGE THE":PRINT "FLOWER BEDS (CLUBS)."
50 PRINT:PRINT "1 = MOW THE WHOLE LAWN BEFORE THE FUEL":PRINT "    RUNS OUT"
60 PRINT "2 = PICTURE MODE: MOW ONLY THE DARK":PRINT "    SQUARES TO DRAW A HEART"
70 GET K$:IF K$<>"1" AND K$<>"2" THEN 70
80 MO=VAL(K$):S=32768:W=160:GR=102:DK=230:FL=88
100 REM DRAW THE LAWN
110 PRINT "{CLR}":FOR I=0 TO 39:POKE S+80+I,W:POKE S+960+I,W:NEXT
120 FOR Y=3 TO 23:POKE S+Y*40,W:POKE S+Y*40+39,W:FOR X=1 TO 38:POKE S+Y*40+X,GR:NEXT:NEXT
130 NG=798:IF MO=2 THEN 200
140 FOR I=1 TO 12:Q=S+160+INT(RND(1)*760):IF PEEK(Q)=GR THEN POKE Q,FL:NG=NG-1
150 NEXT:FU=INT(NG*1.25):GOTO 250
200 RESTORE:NG=0:FOR Y=0 TO 9:READ R$:FOR X=1 TO LEN(R$)
210 IF MID$(R$,X,1)="#" THEN POKE S+(Y+8)*40+X+9,DK:NG=NG+1
220 NEXT:NEXT:FU=400
230 DATA "   ###     ###","  #####   #####"," ####### #######"," ###############"
240 DATA "  #############","   ###########","    #########","     #######","      #####","       ###"
250 X=1:Y=3:POKE S+Y*40+X,0:MW=1:BD=0:GOSUB 900
300 REM MAIN LOOP
310 GET K$:IF K$="" THEN 310
320 DX=0:DY=0:IF K$="W" THEN DY=-1
330 IF K$="S" THEN DY=1
340 IF K$="A" THEN DX=-1
350 IF K$="D" THEN DX=1
360 IF DX=0 AND DY=0 THEN 310
370 C=PEEK(S+(Y+DY)*40+X+DX):IF C=W THEN 310
380 IF C=FL THEN BD=BD+1:POKE 59467,16:POKE 59466,15:POKE 59464,200:GOTO 450
390 POKE S+Y*40+X,32:X=X+DX:Y=Y+DY:POKE S+Y*40+X,0:FU=FU-1
400 IF C=GR AND MO=1 THEN MW=MW+1:POKE 59467,16:POKE 59466,15:POKE 59464,80
410 IF C=DK THEN MW=MW+1:POKE 59467,16:POKE 59466,15:POKE 59464,60
420 IF C=GR AND MO=2 THEN BD=BD+1
450 GOSUB 900:POKE 59464,0
460 IF MO=1 AND MW>=NG THEN 800
470 IF MO=2 AND MW>NG THEN 800
480 IF FU>0 THEN 310
800 REM FINISHED
810 IF MO=1 THEN SC=INT(100*MW/NG)-BD*5+FU:PRINT "{HOME}{RVS} MOWED";INT(100*MW/NG);"% SCORE";SC;"{OFF}       "
820 IF MO=2 THEN SC=(MW-1)*10-BD*5:PRINT "{HOME}{RVS} HEART";MW-1;"OF";NG;" MISTAKES";BD;"SCORE";SC;"{OFF}"
830 PRINT "AGAIN? 1 OR 2 TO PLAY, N TO STOP       "
840 GET K$:IF K$="N" THEN END
850 IF K$="1" OR K$="2" THEN MO=VAL(K$):GOTO 110
860 GOTO 840
900 PRINT "{HOME}FUEL";FU;" MOWED";MW;"OF";NG;" BUMPS";BD;"   ":RETURN
14 · Magazine remake: Summit Steps (after Everest, CURSOR #15, 1979, Brian Sawyer)

Summit Steps is an original Pixel 2001 listing. The idea comes from Everest by Brian Sawyer, published in the cassette magazine CURSOR, issue #15 (1979), but the code is our own. The screen is a height map: every digit is how high the ground is. Climb from the valley to the 9 at the top using as little energy as you can. Going up costs a lot, and cliffs of 3 or more levels can't be climbed. Your best score on each run is kept.

How it works, section by section:

  • Lines 10–90, setup: the rules. BE holds the best (lowest) energy so far.
  • Lines 110–160, growing the mountain: for every cell, height = 9 minus the distance to the peak divided by 3.6, plus a random wobble of −1, 0 or +1. Stretching the Y distance by 1.7 makes the mountain wider than it is tall. The digit's screen code is 48+H, and the climber is the same digit in reverse (176+H), so you can always see your own height.
  • Lines 310–360, reading keys: one step per key, ignoring moves off the map.
  • Lines 370–400, the energy rule: D is the change in height. A flat step costs 1, going up costs 1+3×D and going down costs 1+|D|. More than 2 levels is too steep.
  • Line 410, sound: the pitch number gets smaller as you climb, so the beep gets higher.
  • Lines 800–860, scoring: reaching the 9 compares your energy with your best, then grows a new random mountain. Try to beat your own route!
10 REM SUMMIT STEPS: AN ORIGINAL PIXEL 2001 TYPE-IN
20 REM IDEA INSPIRED BY EVEREST (CURSOR #15, 1979, BRIAN SAWYER)
30 PRINT "{CLR}{RVS} SUMMIT STEPS {OFF}":PRINT:PRINT "EACH NUMBER IS THE HEIGHT OF THE GROUND."
40 PRINT "CLIMB FROM THE VALLEY TO THE SUMMIT (9)":PRINT "WITH W A S D. A FLAT STEP COSTS 1"
50 PRINT "ENERGY, EACH LEVEL UP COSTS 3 MORE AND":PRINT "EACH LEVEL DOWN 1 MORE. YOU CANNOT"
60 PRINT "CLIMB A CLIFF OF MORE THAN 2 LEVELS.":PRINT "FIND THE CHEAPEST ROUTE!"
70 PRINT:PRINT "PRESS ANY KEY (THE MOUNTAIN TAKES A FEW":PRINT "SECONDS TO GROW)"
80 GET K$:IF K$="" THEN 80
90 S=32768:BE=9999
100 REM GROW THE MOUNTAIN
110 PRINT "{CLR}":FOR Y=3 TO 23:FOR X=0 TO 39
120 H=9-INT(SQR((X-20)^2+((Y-3)*1.7)^2)/3.6)+INT(RND(1)*3)-1
130 IF H<0 THEN H=0
140 IF H>8 THEN H=8
150 POKE S+Y*40+X,48+H:NEXT:NEXT:POKE S+3*40+20,57
160 X=INT(RND(1)*30)+5:Y=23:EN=0:H=PEEK(S+Y*40+X)-48:POKE S+Y*40+X,176+H:GOSUB 900
300 REM MAIN LOOP
310 GET K$:IF K$="" THEN 310
320 DX=0:DY=0:IF K$="W" THEN DY=-1
330 IF K$="S" THEN DY=1
340 IF K$="A" THEN DX=-1
350 IF K$="D" THEN DX=1
360 NX=X+DX:NY=Y+DY:IF (DX=0 AND DY=0) OR NX<0 OR NX>39 OR NY<3 OR NY>23 THEN 310
370 NH=PEEK(S+NY*40+NX)-48:D=NH-H:IF D>2 OR D<-2 THEN PRINT "{HOME}{DOWN}TOO STEEP!              ":GOTO 310
380 C=1:IF D>0 THEN C=1+3*D
390 IF D<0 THEN C=1-D
400 EN=EN+C:POKE S+Y*40+X,48+H:X=NX:Y=NY:H=NH:POKE S+Y*40+X,176+H
410 POKE 59467,16:POKE 59466,15:POKE 59464,140-H*12:FOR I=1 TO 20:NEXT:POKE 59464,0
420 GOSUB 900:IF H<9 THEN 310
800 REM THE SUMMIT!
810 IF EN<BE THEN BE=EN
820 PRINT "{HOME}{RVS} SUMMIT! ENERGY USED";EN;" BEST";BE;"{OFF}     "
830 PRINT "NEW MOUNTAIN? Y/N                      "
840 GET K$:IF K$="N" THEN END
850 IF K$<>"Y" THEN 840
860 GOTO 110
900 PRINT "{HOME}ENERGY USED";EN;"  HEIGHT";H;"  BEST";BE;"   "
910 PRINT "                                       ":RETURN
15 · Magazine remake: Switch Flipper (after Rail, CURSOR #19, 1980, Chris Torkildson)

Switch Flipper is an original Pixel 2001 listing. The idea comes from Rail by Chris Torkildson, published in the cassette magazine CURSOR, issue #19 (1980), but the code is our own. Numbered trains roll in on three tracks. Flip the two crossover switches with keys 1 and 2 so every train reaches the platform with its number. Our twist: trains speed up every five arrivals.

How it works, section by section:

  • Lines 10–90, setup: the rules, then arrays. R() holds the track rows, SC() the switch columns, and TX/TT/TN/AC hold up to five trains (column, track, number, active).
  • Lines 110–140, screen drawing: each track is a row of line characters (screen code 67) ending in a buffer and a reversed platform digit. Subroutines 600 and 610 draw a switch as a vertical bar (code 66) when it is on and as spaces when it is off.
  • Lines 310–320, reading keys: GET never waits, so the trains keep moving while you think. 1 and 2 flip a switch with SW=1-SW.
  • Lines 330–370 and 400–450, train movement: every DL loops, each active train moves one column. At a switch column with the switch on, it hops to the other track (with a click sound). Every 9 ticks, subroutine 500 sends in a train with a random track and number.
  • Lines 460–490, scoring: at column 38 the train either matches its platform (SAFE goes up) or crashes. Every 5 trains DL gets smaller, so the game speeds up. Three crashes close the line.
10 REM SWITCH FLIPPER: AN ORIGINAL PIXEL 2001 TYPE-IN
20 REM IDEA INSPIRED BY RAIL (CURSOR #19, 1980, CHRIS TORKILDSON)
30 PRINT "{CLR}{RVS} SWITCH FLIPPER {OFF}":PRINT:PRINT "RUNAWAY TRAINS ARE ROLLING IN! EACH"
40 PRINT "TRAIN HAS A NUMBER. STEER IT TO THE":PRINT "PLATFORM WITH THE SAME NUMBER."
50 PRINT:PRINT "KEY 1 FLIPS THE SWITCH BETWEEN TRACKS":PRINT "1 AND 2. KEY 2 FLIPS THE ONE BETWEEN"
60 PRINT "TRACKS 2 AND 3. A TRAIN THAT REACHES A":PRINT "SWITCH THAT IS ON CROSSES OVER."
70 PRINT "THE WRONG PLATFORM IS A CRASH! 3 CRASHES":PRINT "AND THE LINE CLOSES.":PRINT:PRINT "PRESS ANY KEY"
80 GET K$:IF K$="" THEN 80
90 S=32768:DIM R(3),TX(5),TT(5),TN(5),AC(5),SW(2),SC(2):R(1)=8:R(2)=13:R(3)=18:SC(1)=13:SC(2)=26
100 REM DRAW THE RAILWAY
110 PRINT "{CLR}":FOR T=1 TO 3:FOR X=0 TO 37:POKE S+R(T)*40+X,67:NEXT
120 POKE S+R(T)*40+38,93:POKE S+R(T)*40+39,48+T+128:NEXT
130 SW(1)=0:SW(2)=0:GOSUB 600:GOSUB 610:SP=0:OK=0:CR=0:DL=6:SN=0
140 GOSUB 900
300 REM MAIN LOOP
310 GET K$:IF K$="1" THEN SW(1)=1-SW(1):GOSUB 600
320 IF K$="2" THEN SW(2)=1-SW(2):GOSUB 610
330 Z=Z+1:IF Z<DL THEN 310
340 Z=0:POKE 59464,0:SP=SP+1:IF SP>=9 THEN SP=0:GOSUB 500
350 FOR I=1 TO 5:IF AC(I) THEN GOSUB 400
360 NEXT:IF CR>=3 THEN 800
370 GOTO 310
400 REM MOVE TRAIN I ONE STEP
410 POKE S+R(TT(I))*40+TX(I),67:TX(I)=TX(I)+1
420 FOR J=1 TO 2:IF TX(I)<>SC(J) OR SW(J)=0 THEN 440
430 IF TT(I)=J THEN TT(I)=J+1:GOTO 445
435 IF TT(I)=J+1 THEN TT(I)=J:GOTO 445
440 NEXT:GOTO 450
445 POKE 59467,16:POKE 59466,85:POKE 59464,100
450 IF TX(I)<38 THEN POKE S+R(TT(I))*40+TX(I),48+TN(I)+128:RETURN
460 AC(I)=0:IF TT(I)=TN(I) THEN OK=OK+1:POKE 59467,16:POKE 59466,15:POKE 59464,40:GOTO 480
470 CR=CR+1:POKE 59467,16:POKE 59466,51:POKE 59464,250:PRINT "{HOME}{DOWN}{RVS} CRASH! TRAIN";TN(I);"WENT TO PLATFORM";TT(I);"{OFF}"
480 SN=SN+1:IF SN/5=INT(SN/5) AND DL>2 THEN DL=DL-1
490 GOSUB 900:RETURN
500 REM SEND IN A NEW TRAIN
510 FOR I=1 TO 5:IF AC(I)=0 THEN AC(I)=1:TX(I)=0:TT(I)=INT(RND(1)*3)+1:TN(I)=INT(RND(1)*3)+1:RETURN
520 NEXT:RETURN
600 FOR Y=R(1)+1 TO R(2)-1:POKE S+Y*40+SC(1),32+34*SW(1):NEXT:RETURN
610 FOR Y=R(2)+1 TO R(3)-1:POKE S+Y*40+SC(2),32+34*SW(2):NEXT:RETURN
800 PRINT "{HOME}{RVS} LINE CLOSED! TRAINS HOME SAFE:";OK;"{OFF}":PRINT "AGAIN? Y/N                             "
810 GET K$:IF K$="N" THEN END
820 IF K$<>"Y" THEN 810
830 FOR I=1 TO 5:AC(I)=0:NEXT:GOTO 110
900 PRINT "{HOME}SAFE";OK;" CRASHES";CR;" FLIP: KEYS 1,2 ":RETURN
16 · Magazine remake: Treasure Trail (after Thunt!, CURSOR #22, 1980)

Treasure Trail is an original Pixel 2001 listing. The idea comes from Thunt!, a treasure hunt published in the cassette magazine CURSOR, issue #22 (1980), but the code is our own. Walk a random maze, gather the golden letters, then unscramble them into the secret word for an anagram bonus.

How it works, section by section:

  • Lines 80–110, setup: W is the wall character (reversed space, 160). A random word is chosen by READing a random number of DATA items.
  • Lines 120–170, screen drawing: a border, then a pillar at every second row and column. Each pillar sometimes grows a wall to the right or downward, which makes a quick maze that always has room to walk.
  • Lines 180–200, hiding letters: each letter of the word goes on an empty spot as a reversed letter (screen code letter+128).
  • Lines 310–390, reading keys and movement: W A S D give DX and DY. PEEK looks ahead: a wall blocks you, and a reversed letter is added to GT$ in the order you find it (so it comes out jumbled). Every step uses up one of MV.
  • Lines 600–640, scoring: 10 per letter. With all the letters, INPUT asks for the word. A correct answer adds 100 plus your leftover steps.
10 REM TREASURE TRAIL: AN ORIGINAL PIXEL 2001 TYPE-IN
20 REM IDEA INSPIRED BY THUNT! (CURSOR #22, 1980)
30 PRINT "{CLR}{RVS} TREASURE TRAIL {OFF}":PRINT:PRINT "WANDER THE MAZE WITH W A S D AND PICK"
40 PRINT "UP THE GOLDEN LETTERS. THEY SPELL A":PRINT "SECRET WORD, BUT IN A JUMBLED ORDER!"
50 PRINT "EACH LETTER IS WORTH 10. WHEN YOU HAVE":PRINT "THEM ALL, UNSCRAMBLE THE WORD FOR AN"
60 PRINT "ANAGRAM BONUS OF 100. YOU HAVE 350 STEPS.":PRINT:PRINT "PRESS ANY KEY"
70 GET K$:IF K$="" THEN 70
80 S=32768:W=160:SC=0
90 DATA PIRATE,ISLAND,PARROT,COMPASS,LANTERN,TREASURE,ANCHOR,JEWELS
100 REM BUILD THE MAZE
110 PRINT "{CLR}":RESTORE:N=INT(RND(1)*8)+1:FOR I=1 TO N:READ WD$:NEXT
120 FOR I=0 TO 39:POKE S+80+I,W:POKE S+960+I,W:NEXT
130 FOR Y=3 TO 23:POKE S+Y*40,W:POKE S+Y*40+39,W:NEXT
140 FOR Y=4 TO 22 STEP 2:FOR X=2 TO 37 STEP 2:POKE S+Y*40+X,W
150 D=INT(RND(1)*4):IF D=0 THEN POKE S+Y*40+X+1,W
160 IF D=1 THEN POKE S+(Y+1)*40+X,W
170 NEXT:NEXT
180 NL=LEN(WD$):FOR I=1 TO NL
190 X=INT(RND(1)*38)+1:Y=INT(RND(1)*21)+3:IF PEEK(S+Y*40+X)<>32 OR (X<4 AND Y<6) THEN 190
200 POKE S+Y*40+X,ASC(MID$(WD$,I,1))-64+128:NEXT
210 X=1:Y=3:POKE S+Y*40+X,81:GT$="":MV=350:GOSUB 900
300 REM MAIN LOOP
310 GET K$:IF K$="" THEN 310
320 DX=0:DY=0:IF K$="W" THEN DY=-1
330 IF K$="S" THEN DY=1
340 IF K$="A" THEN DX=-1
350 IF K$="D" THEN DX=1
360 IF DX=0 AND DY=0 THEN 310
370 C=PEEK(S+(Y+DY)*40+X+DX):IF C=W THEN 310
380 POKE 59464,0:IF C>128 THEN GT$=GT$+CHR$(C-128+64):SC=SC+10:POKE 59467,16:POKE 59466,15:POKE 59464,50
390 POKE S+Y*40+X,32:X=X+DX:Y=Y+DY:POKE S+Y*40+X,81:MV=MV-1:GOSUB 900
400 IF LEN(GT$)=NL THEN 600
410 IF MV>0 THEN 310
420 POKE 59464,0:PRINT "{HOME}{RVS} OUT OF STEPS! THE WORD WAS ";WD$;" {OFF}":GOTO 700
600 REM THE ANAGRAM BONUS
610 POKE 59464,0:PRINT "{HOME}{RVS} ALL LETTERS: ";GT$;" {OFF}                      "
620 PRINT "UNSCRAMBLE IT!                         ":PRINT "{UP}";:INPUT "WORD";A$
630 IF A$=WD$ THEN SC=SC+100+MV:PRINT "{HOME}{RVS} CORRECT! +100 AND +";MV;"FOR STEPS LEFT {OFF}":GOTO 700
640 PRINT "{HOME}{RVS} SO CLOSE! IT WAS ";WD$;" {OFF}                   "
700 PRINT "{HOME}{DOWN}SCORE";SC;" ANOTHER MAZE? Y/N           "
710 GET K$:IF K$="N" THEN END
720 IF K$<>"Y" THEN 710
730 GOTO 110
900 PRINT "{HOME}SCORE";SC;" STEPS";MV;" LETTERS ";GT$;"         ":RETURN
17 · Magazine remake: Pie Thief Patrol (after Police!, CURSOR, 1980, Kurt Carpenter)

Pie Thief Patrol is an original Pixel 2001 listing. The idea comes from Police! by Kurt Carpenter, published in the cassette magazine CURSOR (1980), but the code is our own. A cat burglar sneaks around town eating pies, and you only catch a glimpse of it every few moves. Step onto it to make the arrest.

How it works, section by section:

  • Lines 110–160, screen drawing: a border, a grid of city blocks drawn with nested FOR loops, and 8 pies (screen code 90, a diamond) on random empty spots.
  • Lines 310–350 and 500–560, reading keys: you (screen code 0, @) move one square per key. Walking over a pie just moves it to a new spot, because officers don't eat evidence!
  • Lines 600–690, the thief's movement: UC remembers what was under the thief so it can be put back. Half the time the thief steps randomly, and when you are close it backs away from you with SGN. The thief is only drawn every 4th move (SE/4), so you see just a flash.
  • Line 670, stealing: if the thief steps on a pie, the pie is gone and NP drops.
  • Lines 700–790, scoring: a catch scores 10 for each pie left and raises the level, so the thief moves faster. If NP reaches 0, the thief wins.
10 REM PIE THIEF PATROL: AN ORIGINAL PIXEL 2001 TYPE-IN
20 REM IDEA INSPIRED BY POLICE! (CURSOR, 1980, KURT CARPENTER)
30 PRINT "{CLR}{RVS} PIE THIEF PATROL {OFF}":PRINT:PRINT "A CAT BURGLAR IS STEALING THE TOWN'S"
40 PRINT "PIES! YOU ARE THE OFFICER (@). MOVE":PRINT "WITH W A S D AND STEP ON THE THIEF."
50 PRINT "THE THIEF IS SNEAKY: YOU ONLY SEE A":PRINT "FLASH OF IT NOW AND THEN."
60 PRINT "IF IT GRABS ALL 8 PIES, IT WINS.":PRINT:PRINT "PRESS ANY KEY"
70 GET K$:IF K$="" THEN 70
80 S=32768:W=160:PE=90:CT=88:CA=0:LV=1
100 REM DRAW THE TOWN
110 PRINT "{CLR}":FOR I=0 TO 39:POKE S+80+I,W:POKE S+960+I,W:NEXT
120 FOR Y=3 TO 23:POKE S+Y*40,W:POKE S+Y*40+39,W:NEXT
130 FOR Y=5 TO 21 STEP 4:FOR X=3 TO 34 STEP 6:FOR J=0 TO 2:POKE S+Y*40+X+J,W:POKE S+(Y+1)*40+X+J,W:NEXT:NEXT:NEXT
140 FOR I=1 TO 8
150 Q=S+120+INT(RND(1)*840):IF PEEK(Q)<>32 THEN 150
160 POKE Q,PE:NEXT:NP=8
170 X=2:Y=3:POKE S+Y*40+X,0:TX=36:TY=22:UC=32:T=0:SE=0
180 GOSUB 900
300 REM MAIN LOOP
310 GET K$:DX=0:DY=0:IF K$="W" THEN DY=-1
320 IF K$="S" THEN DY=1
330 IF K$="A" THEN DX=-1
340 IF K$="D" THEN DX=1
350 IF DX OR DY THEN GOSUB 500:IF X=TX AND Y=TY THEN 700
360 T=T+1:IF T<6-LV THEN 310
370 T=0:GOSUB 600:IF TX=X AND TY=Y THEN 700
380 IF NP=0 THEN 750
390 GOTO 310
500 REM OFFICER STEP
510 C=PEEK(S+(Y+DY)*40+X+DX):IF C=W THEN RETURN
520 POKE S+Y*40+X,32:X=X+DX:Y=Y+DY:IF C=PE THEN POKE S+Y*40+X,0:GOSUB 550
530 POKE S+Y*40+X,0
540 RETURN
550 Q=S+120+INT(RND(1)*840):IF PEEK(Q)<>32 THEN 550
560 POKE Q,PE:RETURN
600 REM THE THIEF SNEAKS
610 POKE S+TY*40+TX,UC:POKE 59464,0
620 D=INT(RND(1)*4):NX=TX:NY=TY:IF RND(1)<.5 THEN 650
630 IF ABS(X-TX)+ABS(Y-TY)<8 THEN NX=TX-SGN(X-TX):GOTO 660
650 IF D=0 THEN NX=TX+1
651 IF D=1 THEN NX=TX-1
652 IF D=2 THEN NY=TY+1
653 IF D=3 THEN NY=TY-1
660 C=PEEK(S+NY*40+NX):IF C=W THEN NX=TX:NY=TY:C=UC
670 TX=NX:TY=NY:UC=C:IF UC=PE THEN UC=32:NP=NP-1:POKE 59467,16:POKE 59466,51:POKE 59464,180:GOSUB 900
675 IF UC=0 THEN UC=32
680 SE=SE+1:IF SE/4=INT(SE/4) OR (TX=X AND TY=Y) THEN POKE S+TY*40+TX,CT
690 RETURN
700 POKE S+TY*40+TX,CT:CA=CA+NP*10:LV=LV+1:IF LV>4 THEN LV=4
710 POKE 59467,16:POKE 59466,15:POKE 59464,40:PRINT "{HOME}{RVS} GOTCHA! PIES SAVED:";NP;" SCORE";CA;"{OFF}  "
720 FOR I=1 TO 2000:NEXT:POKE 59464,0:GOTO 110
750 POKE 59464,0:PRINT "{HOME}{RVS} THE THIEF ATE EVERY PIE! SCORE";CA;"{OFF}   "
760 PRINT "AGAIN? Y/N":CA=0:LV=1
770 GET K$:IF K$="N" THEN END
780 IF K$<>"Y" THEN 770
790 GOTO 110
900 PRINT "{HOME}SCORE";CA;" PIES LEFT";NP;" LEVEL";LV;"    ":RETURN
18 · Magazine remake: Kaiju Lullaby (after Godzilla!, CURSOR #19, 1980)

Kaiju Lullaby is an original Pixel 2001 listing. The idea of a giant monster heading for town comes from Godzilla! in the cassette magazine CURSOR, issue #19 (1980), but the code and our monster, Big Grumble, are our own. Instead of fighting him, you put him to bed: drop snacks to steer him and sing lullabies until he falls asleep.

How it works, section by section:

  • Lines 110–140, screen drawing: the ground line (99), eight two-wide houses, and your balloon (87) on row 2. Subroutine 950 draws Grumble as a 3×2 block with a reversed O for an eye, and 960 erases him.
  • Lines 310–340, reading keys: A and D move the balloon, F drops a snack (only one at a time), and L sings.
  • Lines 500–570, creature movement: Grumble heads for the snack's column if there is one, and otherwise for the nearest house. He moves down when he lines up, or now and then at random. Eating a snack calms him by 1 and makes him sit still for 3 turns (EA).
  • Lines 600 and 650–690: the snack falls a row each tick. When Grumble reaches the houses, the one under him becomes rubble and he backs up to row 15.
  • Lines 700–730 and 800–870, the lullaby and scoring: three rising notes. A song only works when he is within 6 columns of the balloon (+3 calm). At 10 calm he sleeps, and you score houses ×20 plus 5 for each snack and song you have left.
10 REM KAIJU LULLABY: AN ORIGINAL PIXEL 2001 TYPE-IN
20 REM IDEA INSPIRED BY GODZILLA! (CURSOR #19, 1980)
30 PRINT "{CLR}{RVS} KAIJU LULLABY {OFF}":PRINT:PRINT "BIG GRUMBLE THE SEA MONSTER IS STOMPING"
40 PRINT "TOWARD TOWN. HE IS NOT MEAN, JUST":PRINT "SLEEPY AND HUNGRY!"
50 PRINT:PRINT "A AND D MOVE YOUR BALLOON. F DROPS A":PRINT "SNACK (HE WALKS TO IT AND MUNCHES)."
60 PRINT "L SINGS A LULLABY WHEN HE IS NEAR THE":PRINT "BALLOON. 10 CALM POINTS = BEDTIME!"
70 PRINT:PRINT "PRESS ANY KEY"
80 GET K$:IF K$="" THEN 80
90 S=32768:HS=0
100 REM SET THE SCENE
110 PRINT "{CLR}":FOR X=0 TO 39:POKE S+23*40+X,99:NEXT:NB=0
120 FOR X=2 TO 37 STEP 5:FOR Y=20 TO 22:POKE S+Y*40+X,160:POKE S+Y*40+X+1,160:NEXT:NB=NB+1:NEXT
130 BX=20:MX=INT(RND(1)*30)+5:MY=4:CL=0:SN=6:SG=4:FX=-1:FY=0:T=0:EA=0:SC=0
140 POKE S+80+BX,87:GOSUB 950:GOSUB 900
300 REM MAIN LOOP
310 GET K$:IF K$="A" AND BX>0 THEN POKE S+80+BX,32:BX=BX-1:POKE S+80+BX,87
320 IF K$="D" AND BX<39 THEN POKE S+80+BX,32:BX=BX+1:POKE S+80+BX,87
330 IF K$="F" AND SN>0 AND FX<0 THEN SN=SN-1:FX=BX:FY=3:GOSUB 900
340 IF K$="L" AND SG>0 THEN GOSUB 700
350 T=T+1:IF T<14 THEN 310
360 T=0:POKE 59464,0:IF FX>=0 THEN GOSUB 600
370 IF EA>0 THEN EA=EA-1:GOTO 310
380 GOSUB 500:IF CL>=10 THEN 800
390 IF NB=0 THEN 850
400 GOTO 310
500 REM GRUMBLE STOMPS
510 GOSUB 960:TX=MX:IF FX>=0 THEN TX=FX
520 IF FX<0 THEN TX=INT(MX/5)*5+2
530 IF MX<>TX THEN MX=MX+SGN(TX-MX)
535 IF MX<1 THEN MX=1
536 IF MX>38 THEN MX=38
540 IF MX=TX OR RND(1)<.3 THEN IF MY<21 THEN MY=MY+1
550 IF FX>=0 AND ABS(FX-MX)<2 AND ABS(FY-MY)<2 THEN POKE S+FY*40+FX,32:FX=-1:EA=3:CL=CL+1:SC=SC+5:GOSUB 900
560 IF MY>=19 THEN GOSUB 650
570 GOSUB 950:RETURN
600 IF FY<22 AND FY<MY+1 THEN POKE S+FY*40+FX,32:FY=FY+1:POKE S+FY*40+FX,90
610 RETURN
650 REM A BUILDING GETS SQUASHED
660 B=INT((MX-2)/5):IF B<0 THEN B=0
670 IF B>7 THEN B=7
680 Q=S+20*40+B*5+2:IF PEEK(Q)=160 THEN NB=NB-1:FOR Y=0 TO 2:POKE Q+Y*40,46:POKE Q+Y*40+1,46:NEXT:POKE 59467,16:POKE 59466,51:POKE 59464,240
690 MY=15:GOSUB 900:RETURN
700 REM THE LULLABY
710 SG=SG-1:POKE 59467,16:POKE 59466,15:FOR N=1 TO 3:POKE 59464,60+N*20:FOR J=1 TO 150:NEXT:NEXT:POKE 59464,0
720 IF ABS(BX-MX)<6 THEN CL=CL+3:SC=SC+10
730 GOSUB 900:RETURN
800 PRINT "{HOME}{RVS} ZZZ... GRUMBLE IS FAST ASLEEP! {OFF}         "
810 SC=SC+NB*20+SN*5+SG*5:GOTO 860
850 PRINT "{HOME}{RVS} GRUMBLE FLATTENED THE TOWN! {OFF}            "
860 IF SC>HS THEN HS=SC
870 PRINT "SCORE";SC;" BEST";HS;" AGAIN? Y/N   "
880 GET K$:IF K$="N" THEN END
890 IF K$<>"Y" THEN 880
895 GOTO 110
900 PRINT "{HOME}CALM";CL;" SNACKS";SN;" SONGS";SG;" HOUSES";NB;" ":RETURN
950 FOR I=0 TO 2:POKE S+MY*40+MX-1+I,160:POKE S+(MY+1)*40+MX-1+I,160:NEXT:POKE S+MY*40+MX,15+128:RETURN
960 FOR I=0 TO 2:POKE S+MY*40+MX-1+I,32:POKE S+(MY+1)*40+MX-1+I,32:NEXT:RETURN
19 · Magazine remake: Puppy Shuttle (after Rescue!, CURSOR, 1981)

Puppy Shuttle is an original Pixel 2001 listing. The idea comes from Rescue! in the cassette magazine CURSOR (1981), but the code is our own. Steer a shuttle down through drifting space dust and land gently beside the space puppies waiting on three pads.

How it works, section by section:

  • Lines 110–130, screen drawing: the ground, three pads (100) with a puppy (81) on each, and 8 dust specks with random rows and columns.
  • Lines 310–330, reading keys: W pushes the vertical speed up (VY−3) and burns fuel with a rocket sound. A and D nudge one column.
  • Lines 350–380, physics: YY is the height in tenths of a row. Gravity adds 1 to VY each tick, up to 10, and Y=INT(YY/10)+2 turns it into a screen row. Keeping position in tenths makes the fall smooth.
  • Lines 500–540, dust movement: odd specks drift left and even ones drift right (1-2*(I AND 1)), wrapping at the edges.
  • Lines 390–396 and 600–750, collisions and scoring: PEEK tells you what you are about to hit. Dust or the ground costs a ship. A puppy reached with VY of 4 or less is rescued for 10 plus your leftover fuel. Save all three and a new wave begins.
10 REM PUPPY SHUTTLE: AN ORIGINAL PIXEL 2001 TYPE-IN
20 REM IDEA INSPIRED BY RESCUE! (CURSOR, 1981)
30 PRINT "{CLR}{RVS} PUPPY SHUTTLE {OFF}":PRINT:PRINT "SPACE PUPPIES ARE WAITING ON THE LANDING"
40 PRINT "PADS BELOW! FLY YOUR SHUTTLE (V) DOWN":PRINT "THROUGH THE DRIFTING SPACE DUST (*)."
50 PRINT:PRINT "W FIRES THE ROCKET, A AND D NUDGE LEFT":PRINT "AND RIGHT. TOUCH DOWN GENTLY ON A PAD"
60 PRINT "WITH A PUPPY. FUEL IS LIMITED!":PRINT:PRINT "PRESS ANY KEY"
70 GET K$:IF K$="" THEN 70
80 S=32768:DIM DX(8),DY(8),PX(3):SC=0:LF=3:WV=1
100 REM BUILD THE SKY AND PADS
110 PRINT "{CLR}":FOR X=0 TO 39:POKE S+24*40+X,99:NEXT
120 FOR I=1 TO 3:PX(I)=I*12-6:FOR J=0 TO 2:POKE S+23*40+PX(I)+J,100:NEXT:POKE S+22*40+PX(I)+1,81:NEXT
130 FOR I=1 TO 8:DY(I)=INT(RND(1)*15)+5:DX(I)=INT(RND(1)*40):NEXT:PL=3
140 GOSUB 400
150 GOSUB 900
300 REM MAIN LOOP
310 GET K$:IF K$="W" AND FU>0 THEN VY=VY-3:FU=FU-1:POKE 59467,16:POKE 59466,15:POKE 59464,200
320 IF K$="A" AND FU>0 THEN VX=-1:FU=FU-1
330 IF K$="D" AND FU>0 THEN VX=1:FU=FU-1
340 T=T+1:IF T<5 THEN 310
350 T=0:POKE 59464,0:GOSUB 500:VY=VY+1:IF VY>10 THEN VY=10
360 POKE S+Y*40+X,32:YY=YY+VY:IF YY<0 THEN YY=0:VY=0
370 Y=INT(YY/10)+2:X=X+VX:VX=0:IF X<0 THEN X=0
380 IF X>39 THEN X=39
390 C=PEEK(S+Y*40+X):IF C=42 THEN 600
392 IF C=81 THEN 700
394 IF Y>=22 THEN 600
396 POKE S+Y*40+X,22:GOSUB 900:GOTO 310
400 X=20:YY=0:Y=2:VX=0:VY=0:FU=60:T=0:RETURN
500 REM DUST DRIFTS
510 FOR I=1 TO 8:POKE S+DY(I)*40+DX(I),32:DX(I)=DX(I)+1-2*(I AND 1)
520 IF DX(I)>39 THEN DX(I)=0
530 IF DX(I)<0 THEN DX(I)=39
540 POKE S+DY(I)*40+DX(I),42:NEXT:RETURN
600 REM BUMP!
610 POKE 59467,16:POKE 59466,51:POKE 59464,250:LF=LF-1:PRINT "{HOME}{DOWN}{RVS} BUMP! THE SHUTTLE NEEDS REPAIRS {OFF}"
620 FOR I=1 TO 1500:NEXT:POKE 59464,0:PRINT "{HOME}{DOWN}                                 "
630 IF LF<=0 THEN 800
640 GOSUB 400:GOTO 310
700 REM A PUPPY!
710 IF VY>4 THEN 600
720 POKE S+Y*40+X,32:PL=PL-1:SC=SC+10+FU:POKE 59467,16:POKE 59466,15
730 FOR N=1 TO 4:POKE 59464,40+N*15:FOR J=1 TO 120:NEXT:NEXT:POKE 59464,0
740 IF PL=0 THEN WV=WV+1:GOTO 110
750 GOSUB 400:GOTO 310
800 PRINT "{HOME}{RVS} MISSION OVER! SCORE";SC;"{OFF}":PRINT "AGAIN? Y/N"
810 GET K$:IF K$="N" THEN END
820 IF K$<>"Y" THEN 810
830 SC=0:LF=3:WV=1:GOTO 110
900 PRINT "{HOME}SCORE";SC;" FUEL";FU;" SHIPS";LF;" PUPS";PL;"  ":RETURN
20 · Magazine remake: Cake Safecracker (after Safe!, CURSOR, 1981)

Cake Safecracker is an original Pixel 2001 listing. The idea comes from Safe! in the cassette magazine CURSOR (1981), but the code is our own. Crack the bakery safe's code using up/down hints for each dial. Our twist: every safe you open adds a dial, up to five.

How it works, section by section:

  • Lines 80–120, setup: C() holds the secret digits and G() your guess. ND is the number of dials.
  • Lines 210–240, reading keys: GET waits for digits only (K$<"0" OR K$>"9"), and each digit clicks with a short beep.
  • Lines 250–280, the hints: for each dial print U (go up), N (go down) or *. R counts the correct dials.
  • Lines 300–420, scoring: 8 tries. Opening the safe scores (9−tries)×10×dials and adds a dial. The alarm resets you to 3 dials.
10 REM CAKE SAFECRACKER: AN ORIGINAL PIXEL 2001 TYPE-IN
20 REM IDEA INSPIRED BY SAFE! (CURSOR, 1981)
30 PRINT "{CLR}{RVS} CAKE SAFECRACKER {OFF}":PRINT:PRINT "THE BAKER LOCKED THE BIRTHDAY CAKE IN A"
40 PRINT "SAFE AND FORGOT THE 3 DIGIT CODE!":PRINT "TYPE 3 DIGITS. UNDER EACH ONE YOU SEE:"
50 PRINT "  U = TURN IT UP, N = TURN IT DOWN,":PRINT "  * = THAT DIAL IS RIGHT."
60 PRINT "CRACK IT IN 8 TRIES. LATER SAFES HAVE":PRINT "4 AND 5 DIALS!":PRINT:PRINT "PRESS ANY KEY"
70 GET K$:IF K$="" THEN 70
80 DIM C(5),G(5):SC=0:ND=3
100 REM A NEW SAFE
110 PRINT "{CLR}{RVS} SAFE WITH";ND;"DIALS {OFF}  SCORE";SC:PRINT
120 FOR I=1 TO ND:C(I)=INT(RND(1)*10):NEXT:TR=0
200 REM READ ONE GUESS
210 TR=TR+1:PRINT "TRY";TR;": ";:I=1
220 GET K$:IF K$<"0" OR K$>"9" THEN 220
230 G(I)=VAL(K$):PRINT K$;:POKE 59467,16:POKE 59466,15:POKE 59464,90:FOR J=1 TO 40:NEXT:POKE 59464,0
240 I=I+1:IF I<=ND THEN 220
250 PRINT "   ";:R=0:FOR I=1 TO ND:H$="*":IF G(I)<C(I) THEN H$="U"
260 IF G(I)>C(I) THEN H$="N"
270 IF H$="*" THEN R=R+1
280 PRINT H$;:NEXT:PRINT
290 IF R=ND THEN 400
300 IF TR<8 THEN 210
310 PRINT:PRINT "{RVS} THE ALARM RINGS! {OFF} CODE WAS ";:FOR I=1 TO ND:PRINT MID$(STR$(C(I)),2);:NEXT:PRINT
320 POKE 59467,16:POKE 59466,51:POKE 59464,240:FOR J=1 TO 800:NEXT:POKE 59464,0:ND=3:GOTO 500
400 PRINT:PRINT "{RVS} CLICK! CAKE TIME! {OFF}":SC=SC+(9-TR)*10*ND
410 FOR N=1 TO 5:POKE 59464,30+N*10:FOR J=1 TO 100:NEXT:NEXT:POKE 59464,0
420 IF ND<5 THEN ND=ND+1
500 PRINT "SCORE";SC;" NEXT SAFE? Y/N"
510 GET K$:IF K$="N" THEN END
520 IF K$<>"Y" THEN 510
530 GOTO 110
21 · Magazine remake: Genie's Ruby (after Boswain, CURSOR #21, 1980)

Genie's Ruby is an original Pixel 2001 listing, inspired by Boswain from the cassette magazine CURSOR, issue #21 (1980); the code is our own. Dig in the desert for a hidden ruby with the genie's hot-and-cold hints. Three wishes reveal its row or column.

How it works, section by section:

  • Lines 110–130, screen drawing: a field of sand (screen code 102). RX/RY is the hidden ruby, and UC remembers what is under you.
  • Lines 310–360, reading keys: W A S D move you, and you put back the cell you leave.
  • Lines 500–590, digging: D is the step distance ABS(X-RX)+ABS(Y-RY). The dug hole shows D/4 as a digit, and the pitch rises as you get close. The genie's words come from a chain of IFs.
  • Lines 600–650, wishes: they alternate between marking the ruby's row and its column with dots.
  • Lines 700–720, scoring: 10 for each dig and 20 for each wish you have left.
10 REM GENIE'S RUBY: AN ORIGINAL PIXEL 2001 TYPE-IN
20 REM IDEA INSPIRED BY BOSWAIN (CURSOR #21, 1980)
30 PRINT "{CLR}{RVS} GENIE'S RUBY {OFF}":PRINT:PRINT "A GENIE HID HIS RUBY UNDER THE DESERT."
40 PRINT "WALK WITH W A S D. PRESS F TO DIG.":PRINT "THE GENIE SAYS HOW WARM YOU ARE."
50 PRINT "PRESS G FOR A WISH: THE GENIE SHOWS":PRINT "WHICH ROW OR COLUMN IT IS IN (3 WISHES)."
60 PRINT "FIND IT IN 12 DIGS!":PRINT:PRINT "PRESS ANY KEY"
70 GET K$:IF K$="" THEN 70
80 S=32768:SC=0:RD=1
100 REM DRAW THE DESERT
110 PRINT "{CLR}":FOR Y=3 TO 22:FOR X=5 TO 34:POKE S+Y*40+X,102:NEXT:NEXT
120 RX=INT(RND(1)*30)+5:RY=INT(RND(1)*20)+3:X=20:Y=12:DG=12:WI=3:UC=102:WS=0
130 POKE S+Y*40+X,0:GOSUB 900
300 REM MAIN LOOP
310 GET K$:IF K$="" THEN 310
320 DX=0:DY=0:IF K$="W" AND Y>3 THEN DY=-1
330 IF K$="S" AND Y<22 THEN DY=1
340 IF K$="A" AND X>5 THEN DX=-1
350 IF K$="D" AND X<34 THEN DX=1
360 IF DX OR DY THEN POKE S+Y*40+X,UC:X=X+DX:Y=Y+DY:UC=PEEK(S+Y*40+X):POKE S+Y*40+X,0
370 IF K$="F" AND UC=102 THEN 500
380 IF K$="G" AND WI>0 THEN 600
390 GOTO 310
500 REM DIGGING
510 DG=DG-1:D=ABS(X-RX)+ABS(Y-RY):POKE 59467,16:POKE 59466,15:POKE 59464,250-D*5
520 IF D=0 THEN 700
530 UC=48+INT(D/4):IF UC>57 THEN UC=57
540 H$="FREEZING!":IF D<20 THEN H$="COLD"
550 IF D<12 THEN H$="WARM"
560 IF D<6 THEN H$="HOT!"
570 IF D<3 THEN H$="SIZZLING!!"
580 FOR J=1 TO 60:NEXT:POKE 59464,0:PRINT "{HOME}{DOWN}GENIE: ";H$;"            ":GOSUB 900
590 IF DG>0 THEN 310
595 POKE S+RY*40+RX,90+128:PRINT "{HOME}{DOWN}{RVS} OUT OF DIGS! THERE IT WAS. {OFF}":RD=1:GOTO 800
600 REM A WISH
610 WI=WI-1:WS=1-WS:IF WS THEN FOR I=5 TO 34:IF PEEK(S+RY*40+I)=102 THEN POKE S+RY*40+I,46
620 IF WS THEN NEXT
630 IF WS=0 THEN FOR I=3 TO 22:IF PEEK(S+I*40+RX)=102 THEN POKE S+I*40+RX,46
640 IF WS=0 THEN NEXT
650 GOSUB 900:GOTO 310
700 POKE S+Y*40+X,90+128:SC=SC+DG*10+WI*20+10:RD=RD+1
710 FOR N=1 TO 6:POKE 59464,20+N*12:FOR J=1 TO 80:NEXT:NEXT:POKE 59464,0
720 PRINT "{HOME}{DOWN}{RVS} THE RUBY! THE GENIE BOWS. {OFF}      "
800 GOSUB 900:PRINT "{HOME}{DOWN}{DOWN}AGAIN? Y/N"
810 GET K$:IF K$="N" THEN END
820 IF K$<>"Y" THEN 810
830 GOTO 110
900 PRINT "{HOME}SCORE";SC;" DIGS";DG;" WISHES";WI;" ROUND";RD;" ":RETURN
22 · Magazine remake: Dynamite Prospector (after Gold Rush!, Compute! #26, 1982)

Dynamite Prospector is an original Pixel 2001 listing. The idea comes from Gold Rush! in Compute! magazine, issue #26 (1982), but the code is our own. Dig through dirt for 12 nuggets and blast boulders with timed dynamite before your lamp oil runs out.

How it works, section by section:

  • Lines 110–140, screen drawing: dirt (46) and 25% boulders (15). Then a FOR loop places exactly 12 gold nuggets ($).
  • Lines 310–360 and 500–540, reading keys: boulders block you, gold scores 25, and F lights a fuse at your spot (BT=4).
  • Lines 600–697, the explosion: the stick blinks each tick. At 0, two nested loops over −1..1 flash a 3×3 area (*) and then clear it. If you stand inside, you lose a heart.
  • Lines 370–399 and 700, scoring: oil drops every 20 loops, and the oil left over is your bonus for clearing a mine.
10 REM DYNAMITE PROSPECTOR: AN ORIGINAL PIXEL 2001 TYPE-IN
20 REM IDEA INSPIRED BY GOLD RUSH! (COMPUTE! #26, 1982)
30 PRINT "{CLR}{RVS} DYNAMITE PROSPECTOR {OFF}":PRINT:PRINT "DIG FOR GOLD ($) WITH W A S D. DIRT (.)"
40 PRINT "IS EASY. BOULDERS (O) BLOCK YOU, SO":PRINT "PRESS F TO LIGHT DYNAMITE. IT BLOWS UP"
50 PRINT "4 TICKS LATER AND CLEARS A 3X3 AREA.":PRINT "DON'T STAND NEXT TO IT! 5 STICKS EACH."
60 PRINT "GET ALL THE GOLD BEFORE THE LAMP OIL":PRINT "RUNS OUT.":PRINT:PRINT "PRESS ANY KEY"
70 GET K$:IF K$="" THEN 70
80 S=32768:SC=0:LF=3
100 REM FILL THE MINE
110 PRINT "{CLR}":FOR Y=3 TO 23:FOR X=0 TO 39:C=46:R=RND(1):IF R<.25 THEN C=15
120 REM GOLD IS ADDED BELOW
130 POKE S+Y*40+X,C:NEXT:NEXT:NG=12:FOR I=1 TO NG
135 Q=S+121+INT(RND(1)*879):IF PEEK(Q)=36 THEN 135
137 POKE Q,36
140 NEXT:X=0:Y=3:POKE S+Y*40+X,0:DY=5:BT=-1:OI=400:T=0
150 GOSUB 900
300 REM MAIN LOOP
310 GET K$:MX=0:MY=0:IF K$="W" AND Y>3 THEN MY=-1
320 IF K$="S" AND Y<23 THEN MY=1
330 IF K$="A" AND X>0 THEN MX=-1
340 IF K$="D" AND X<39 THEN MX=1
350 IF MX OR MY THEN GOSUB 500
360 IF K$="F" AND DY>0 AND BT<0 THEN DY=DY-1:BX=X:BY=Y:BT=4:GOSUB 900
370 T=T+1:IF T<20 THEN 310
380 T=0:OI=OI-1:IF BT>=0 THEN GOSUB 600
390 IF OI<=0 OR LF<=0 THEN 800
395 IF NG=0 THEN 700
397 IF OI/10=INT(OI/10) THEN GOSUB 900
399 GOTO 310
500 C=PEEK(S+(Y+MY)*40+X+MX):IF C=15 OR C=81 THEN RETURN
510 IF (X<>BX OR Y<>BY) OR BT<0 THEN POKE S+Y*40+X,32
520 X=X+MX:Y=Y+MY:POKE S+Y*40+X,0
530 IF C=36 THEN NG=NG-1:SC=SC+25:POKE 59467,16:POKE 59466,15:POKE 59464,60:FOR J=1 TO 30:NEXT:POKE 59464,0:GOSUB 900
540 RETURN
600 REM THE FUSE BURNS
610 BT=BT-1:IF X<>BX OR Y<>BY THEN POKE S+BY*40+BX,81+128*(BT AND 1)
620 IF BT>0 THEN RETURN
630 POKE 59467,16:POKE 59466,51:POKE 59464,250
640 FOR J=-1 TO 1:FOR I=-1 TO 1:XX=BX+I:YY=BY+J:IF XX<0 OR XX>39 OR YY<3 OR YY>23 THEN 660
650 Q=S+YY*40+XX:IF PEEK(Q)<>36 THEN POKE Q,42
660 NEXT:NEXT:FOR J=1 TO 300:NEXT:POKE 59464,0
670 FOR J=-1 TO 1:FOR I=-1 TO 1:XX=BX+I:YY=BY+J:IF XX<0 OR XX>39 OR YY<3 OR YY>23 THEN 690
680 Q=S+YY*40+XX:IF PEEK(Q)=42 THEN POKE Q,32
690 NEXT:NEXT:BT=-1
695 IF ABS(X-BX)<2 AND ABS(Y-BY)<2 THEN LF=LF-1:PRINT "{HOME}{DOWN}{RVS} OUCH! TOO CLOSE! {OFF}"
697 POKE S+Y*40+X,0:GOSUB 900:RETURN
700 SC=SC+OI:PRINT "{HOME}{DOWN}{RVS} ALL THE GOLD! OIL BONUS";OI;"{OFF}":DY=5:FOR J=1 TO 1500:NEXT:GOTO 110
800 PRINT "{HOME}{DOWN}{RVS} THE PROSPECTING IS OVER! {OFF}":PRINT "SCORE";SC;" AGAIN? Y/N"
810 GET K$:IF K$="N" THEN END
820 IF K$<>"Y" THEN 810
830 SC=0:LF=3:GOTO 110
900 PRINT "{HOME}$";SC;" GOLD";NG;" TNT";DY;" OIL";OI;" HP";LF;" ":RETURN
23 · Magazine remake: Cheese Chase Mazes (after Maze Race, Compute! #26, 1982)

Cheese Chase Mazes is an original Pixel 2001 listing. The idea comes from Maze Race in Compute! magazine, issue #26 (1982), but the code is our own. Race a robot mouse through a random maze to the cheese.

How it works, section by section:

  • Lines 90–170, screen drawing: AX/AY are the four direction steps. The maze is made of pillars that each grow one wall.
  • Lines 310–380, reading keys: PEEK ahead, and walls (160) block you.
  • Lines 500–550, creature movement: the robot uses the right-hand rule. It tries right of its heading first, then straight, left and back, and takes the first open way. This always solves a maze like this one.
  • Lines 700–830, scoring: every win makes SP smaller, so the robot moves more often.
10 REM CHEESE CHASE MAZES: AN ORIGINAL PIXEL 2001 TYPE-IN
20 REM IDEA INSPIRED BY MAZE RACE (COMPUTE! #26, 1982)
30 PRINT "{CLR}{RVS} CHEESE CHASE MAZES {OFF}":PRINT:PRINT "YOU ARE A MOUSE (@) RACING A ROBOT"
40 PRINT "MOUSE (X) TO THE CHEESE (C) IN THE FAR":PRINT "CORNER. MOVE WITH W A S D."
50 PRINT "THE ROBOT KEEPS ITS PAW ON THE RIGHT":PRINT "WALL. IT IS SLOW BUT IT NEVER GETS LOST!"
60 PRINT "WIN A RACE AND THE ROBOT GETS FASTER.":PRINT:PRINT "PRESS ANY KEY"
70 GET K$:IF K$="" THEN 70
80 S=32768:W=160:ME=0:RB=0:SP=12:DIM AX(3),AY(3)
90 AX(0)=1:AY(0)=0:AX(1)=0:AY(1)=1:AX(2)=-1:AY(2)=0:AX(3)=0:AY(3)=-1
100 REM BUILD THE MAZE
110 PRINT "{CLR}":FOR I=0 TO 38:POKE S+80+I,W:POKE S+960+I,W:NEXT
120 FOR Y=2 TO 24:POKE S+Y*40,W:POKE S+Y*40+38,W:NEXT
130 FOR Y=4 TO 22 STEP 2:FOR X=2 TO 36 STEP 2:POKE S+Y*40+X,W
140 D=INT(RND(1)*2):IF D=0 THEN POKE S+Y*40+X+1,W
150 IF D=1 THEN POKE S+(Y+1)*40+X,W
160 NEXT:NEXT
170 POKE S+23*40+37,3:X=1:Y=3:CX=1:CY=3:CD=0:POKE S+Y*40+X,0:T=0
180 GOSUB 900
300 REM MAIN LOOP
310 GET K$:DX=0:DY=0:IF K$="W" THEN DY=-1
320 IF K$="S" THEN DY=1
330 IF K$="A" THEN DX=-1
340 IF K$="D" THEN DX=1
350 IF DX=0 AND DY=0 THEN 400
360 C=PEEK(S+(Y+DY)*40+X+DX):IF C=W THEN 400
370 IF X<>CX OR Y<>CY THEN POKE S+Y*40+X,32
380 X=X+DX:Y=Y+DY:POKE S+Y*40+X,0:IF C=3 THEN 700
400 T=T+1:IF T<SP THEN 310
410 T=0:GOSUB 500:IF CX=37 AND CY=23 THEN 750
420 GOTO 310
500 REM ROBOT: RIGHT HAND ON THE WALL
510 IF X<>CX OR Y<>CY THEN POKE S+CY*40+CX,32
520 FOR N=0 TO 3:ND=(CD+1-N+4) AND 3
530 IF PEEK(S+(CY+AY(ND))*40+CX+AX(ND))<>W THEN CD=ND:N=4
540 NEXT:CX=CX+AX(CD):CY=CY+AY(CD):IF CX<>37 OR CY<>23 THEN POKE S+CY*40+CX,24
550 RETURN
700 ME=ME+1:IF SP>3 THEN SP=SP-2
710 POKE 59467,16:POKE 59466,15:FOR N=1 TO 4:POKE 59464,30+N*15:FOR J=1 TO 80:NEXT:NEXT:POKE 59464,0
720 PRINT "{HOME}{RVS} CHEESE! YOU WIN THIS RACE! {OFF}      ":GOTO 800
750 RB=RB+1:POKE 59467,16:POKE 59466,51:POKE 59464,220:FOR J=1 TO 300:NEXT:POKE 59464,0
760 PRINT "{HOME}{RVS} THE ROBOT GOT THE CHEESE! {OFF}      "
800 PRINT "{HOME}{DOWN}YOU";ME;" ROBOT";RB;" AGAIN? Y/N   "
810 GET K$:IF K$="N" THEN END
820 IF K$<>"Y" THEN 810
830 GOTO 110
900 PRINT "{HOME}YOU";ME;" ROBOT";RB;" ROBOT SPEED";13-SP;"   ":RETURN
24 · Magazine remake: Shadow Chase (after Superchase, Compute! #29, 1982)

Shadow Chase is an original Pixel 2001 listing. The idea comes from Superchase in Compute! magazine, issue #29 (1982), but the code is our own. Shadows creep toward you, so lure them into the bushes. Lamps freeze them for a moment.

How it works, section by section:

  • Lines 110–150, screen drawing: 40 bushes, 6 lamps and 2+wave shadows on the left and right edges.
  • Lines 310–350 and 500–540, reading keys: bushes block you. A lamp scores 10, sets FZ=4 freeze ticks and moves to a new spot.
  • Lines 600–640, creature movement: each shadow steps toward you with SGN on both axes, so it moves diagonally. If it would land on a bush it fades (+25). They never stack.
  • Line 700, scoring: clearing every shadow starts a bigger wave.
10 REM SHADOW CHASE: AN ORIGINAL PIXEL 2001 TYPE-IN
20 REM IDEA INSPIRED BY SUPERCHASE (COMPUTE! #29, 1982)
30 PRINT "{CLR}{RVS} SHADOW CHASE {OFF}":PRINT:PRINT "SHADOWS (#) CREEP TOWARD YOU (@) IN THE"
40 PRINT "DARK PARK. MOVE WITH W A S D. GRAB THE":PRINT "LAMPS (*) FOR POINTS."
50 PRINT "EACH LAMP ALSO FREEZES THE SHADOWS FOR":PRINT "A MOMENT. TRICK THEM INTO THE BUSHES"
60 PRINT "(%): A SHADOW THAT BUMPS ONE FADES!":PRINT:PRINT "PRESS ANY KEY"
70 GET K$:IF K$="" THEN 70
80 S=32768:BU=88:LA=42:SH=102:DIM HX(6),HY(6),HA(6):SC=0:WV=1
100 REM SET UP THE PARK
110 PRINT "{CLR}":FOR I=1 TO 40:Q=S+120+INT(RND(1)*880):POKE Q,BU:NEXT
120 FOR I=1 TO 6:GOSUB 650:NEXT
130 NH=2+WV:IF NH>6 THEN NH=6
140 X=20:Y=13:POKE S+Y*40+X,0:FOR I=1 TO NH:HA(I)=1:HX(I)=INT(RND(1)*2)*39:HY(I)=INT(RND(1)*21)+3:NEXT
150 FZ=0:T=0:LV=NH:GOSUB 900
300 REM MAIN LOOP
310 GET K$:DX=0:DY=0:IF K$="W" AND Y>3 THEN DY=-1
320 IF K$="S" AND Y<24 THEN DY=1
330 IF K$="A" AND X>0 THEN DX=-1
340 IF K$="D" AND X<39 THEN DX=1
350 IF DX OR DY THEN GOSUB 500
360 T=T+1:IF T<12 THEN 310
370 T=0:POKE 59464,0:IF FZ>0 THEN FZ=FZ-1:GOTO 310
380 FOR I=1 TO NH:IF HA(I) THEN GOSUB 600
390 NEXT:IF LV=0 THEN 700
395 GOTO 310
500 C=PEEK(S+(Y+DY)*40+X+DX):IF C=BU THEN RETURN
510 IF C=SH THEN 800
520 POKE S+Y*40+X,32:X=X+DX:Y=Y+DY:POKE S+Y*40+X,0
530 IF C=LA THEN SC=SC+10:FZ=4:POKE 59467,16:POKE 59466,15:POKE 59464,40:GOSUB 650:GOSUB 900
540 RETURN
600 REM A SHADOW CREEPS
610 POKE S+HY(I)*40+HX(I),32:NX=HX(I)+SGN(X-HX(I)):NY=HY(I)+SGN(Y-HY(I))
620 C=PEEK(S+NY*40+NX):IF C=BU THEN HA(I)=0:LV=LV-1:SC=SC+25:POKE 59467,16:POKE 59466,51:POKE 59464,200:GOSUB 900:RETURN
630 IF C=0 THEN 800
635 IF C=SH OR C=LA THEN NX=HX(I):NY=HY(I)
640 HX(I)=NX:HY(I)=NY:POKE S+NY*40+NX,SH:RETURN
650 Q=S+120+INT(RND(1)*880):IF PEEK(Q)<>32 THEN 650
660 POKE Q,LA:RETURN
700 WV=WV+1:PRINT "{HOME}{RVS} ALL SHADOWS FADED! DAWN BREAKS {OFF}":FOR J=1 TO 1500:NEXT:GOTO 110
800 POKE 59467,16:POKE 59466,51:POKE 59464,250:PRINT "{HOME}{RVS} A SHADOW GOT YOU! SCORE";SC;"{OFF}  "
810 FOR J=1 TO 500:NEXT:POKE 59464,0:PRINT "AGAIN? Y/N"
820 GET K$:IF K$="N" THEN END
830 IF K$<>"Y" THEN 820
840 SC=0:WV=1:GOTO 110
900 PRINT "{HOME}SCORE";SC;" SHADOWS";LV;" WAVE";WV;"     ":RETURN
25 · Magazine remake: You're It! (after Tag, Compute! #29, 1982)

You're It! is an original Pixel 2001 listing. The idea comes from Tag in Compute! magazine, issue #29 (1982), but the code is our own. Play tag against Robo in a playground of trees. Whoever is 'it' is drawn in reverse. You score for every tick you are not it, and a fresh tag gives you a few safe ticks to get away.

How it works, section by section:

  • Lines 90–150, setup and screen drawing: a border, 35 random trees (screen code 91) and the two players. IT=1 means you are it. SF counts the safe ticks after a tag, and CL is the round clock.
  • Lines 310–370, reading keys: you move one square per key, but only onto empty ground (PEEK=32). Stepping onto Robo is a tag.
  • Lines 500–570, creature movement: SGN gives the direction toward you. If you are it, Robo flips the signs and runs away. A 25% random step stops it from being too perfect. It moves along only one axis per tick, so it can't cut corners through trees.
  • Lines 600–610, drawing 'it': in PET BASIC a true test is −1, so 128*(IT=1)*-1 adds 128 (reverse) only to whoever is it.
  • Lines 700–760 and 390, tagging and scoring: a tag swaps IT, beeps and starts 6 safe ticks. You score a point every tick while Robo is it, and the best score of the session is kept in HS.
10 REM YOU'RE IT!: AN ORIGINAL PIXEL 2001 TYPE-IN
20 REM IDEA INSPIRED BY TAG (COMPUTE! #29, 1982)
30 PRINT "{CLR}{RVS} YOU'RE IT! {OFF}":PRINT:PRINT "A GAME OF TAG IN THE PLAYGROUND WITH"
40 PRINT "ROBO (R). YOU ARE @. WHOEVER IS 'IT'":PRINT "IS SHOWN IN REVERSE. MOVE WITH W A S D."
50 PRINT "IF YOU ARE IT, CATCH ROBO. IF ROBO IS":PRINT "IT, RUN AWAY! TREES (+) BLOCK BOTH."
60 PRINT "YOU SCORE A POINT FOR EVERY TICK YOU":PRINT "ARE NOT IT. A ROUND LASTS 200 TICKS."
70 PRINT:PRINT "PRESS ANY KEY"
80 GET K$:IF K$="" THEN 80
90 S=32768:TR=91:HS=0
100 REM DRAW THE PLAYGROUND
110 PRINT "{CLR}":FOR I=0 TO 39:POKE S+80+I,160:POKE S+960+I,160:NEXT
120 FOR Y=3 TO 23:POKE S+Y*40,160:POKE S+Y*40+39,160:NEXT
130 FOR I=1 TO 35:Q=S+160+INT(RND(1)*760):IF PEEK(Q)=32 THEN POKE Q,TR
140 NEXT
150 X=5:Y=12:BX=34:BY=12:IT=1:SF=0:CL=200:SC=0:T=0:GOSUB 600:GOSUB 900
300 REM MAIN LOOP
310 GET K$:DX=0:DY=0:IF K$="W" THEN DY=-1
320 IF K$="S" THEN DY=1
330 IF K$="A" THEN DX=-1
340 IF K$="D" THEN DX=1
350 IF DX=0 AND DY=0 THEN 380
360 IF PEEK(S+(Y+DY)*40+X+DX)=32 THEN POKE S+Y*40+X,32:X=X+DX:Y=Y+DY:GOSUB 600
370 IF X=BX AND Y=BY THEN GOSUB 700
380 T=T+1:IF T<5 THEN 310
390 T=0:POKE 59464,0:CL=CL-1:IF IT=0 THEN SC=SC+1
400 IF SF>0 THEN SF=SF-1:GOTO 430
410 GOSUB 500
430 IF CL/5=INT(CL/5) THEN GOSUB 900
440 IF CL<=0 THEN 800
450 GOTO 310
500 REM ROBO MOVES
510 SX=SGN(X-BX):SY=SGN(Y-BY):IF IT=1 THEN SX=-SX:SY=-SY
520 IF RND(1)<.25 THEN SX=INT(RND(1)*3)-1:SY=INT(RND(1)*3)-1
530 IF RND(1)<.5 THEN NX=BX+SX:NY=BY:GOTO 550
540 NX=BX:NY=BY+SY
550 C=PEEK(S+NY*40+NX):IF C=32 THEN POKE S+BY*40+BX,32:BX=NX:BY=NY:GOSUB 600:RETURN
560 IF NX=X AND NY=Y THEN BX=NX:BY=NY:GOSUB 700
570 RETURN
600 REM DRAW BOTH: 'IT' IN REVERSE
610 POKE S+Y*40+X,0+128*(IT=1)*-1:POKE S+BY*40+BX,18+128*(IT=0)*-1:RETURN
700 REM TAG!
710 IF SF>0 THEN RETURN
720 IT=1-IT:SF=6:POKE 59467,16:POKE 59466,15:POKE 59464,60+IT*80
730 PRINT "{HOME}{DOWN}";:IF IT THEN PRINT "{RVS} ROBO TAGGED YOU! YOU'RE IT! {OFF}  "
740 IF IT=0 THEN PRINT "{RVS} TAG! ROBO IS IT, RUN!       {OFF}  "
750 IF X=BX AND Y=BY THEN BX=BX+(BX<38)*-2+(BX>=38)*2:IF BX>38 THEN BX=37
760 GOSUB 600:RETURN
800 POKE 59464,0:IF SC>HS THEN HS=SC
810 PRINT "{HOME}{DOWN}{RVS} TIME! SCORE";SC;" BEST";HS;"{OFF}       ":PRINT "AGAIN? Y/N"
820 GET K$:IF K$="N" THEN END
830 IF K$<>"Y" THEN 820
840 GOTO 110
900 PRINT "{HOME}SCORE";SC;" TIME";CL;" ";:IF IT THEN PRINT "YOU'RE IT!    ":RETURN
910 PRINT "ROBO IS IT    ":RETURN
26 · Magazine remake: Picnic Patrol (after Laser Barrage, Compute! #29, 1982)

Picnic Patrol is an original Pixel 2001 listing. The idea comes from Laser Barrage in Compute! magazine, issue #29 (1982), but the code is our own. Instead of lasers, you puff bubbles at a column of marching ants before they reach your picnic blanket, while dodging stingers dropped by a buzzing wasp.

How it works, section by section:

  • Lines 90–140, setup and screen drawing: arrays hold each ant's column, row, direction and whether it is alive (AX, AY, AD, AL). The blanket is a row of checker characters (102). Each wave has one more ant than the last.
  • Lines 310–330, reading keys: A and D slide you (screen code 30, ↑) along row 23 using S+920+X. W launches a bubble, but only one can be on screen at a time (BY<0 means there's no bubble).
  • Lines 400–450, the bubble: it rises one row per tick and checks every live ant. A hit removes both the ant and the bubble and scores 10.
  • Lines 500–560, creature movement: each ant steps sideways. At the edge it turns round and drops a row, just like a marching column. Reaching row 22 means it steals a sandwich (FD).
  • Lines 650–740, the wasp's barrage: the wasp bounces along row 2. Now and then it drops a stinger (:) that falls one row per tick, and a stinger that lands in your column costs a life. Higher waves sting more often.
  • Lines 360–380, scoring: clearing a wave scores 50, and the ants march faster as WV grows. The game ends with no sandwiches or no lives left.
10 REM PICNIC PATROL: AN ORIGINAL PIXEL 2001 TYPE-IN
20 REM IDEA INSPIRED BY LASER BARRAGE (COMPUTE! #29, 1982)
30 PRINT "{CLR}{RVS} PICNIC PATROL {OFF}":PRINT:PRINT "ANTS (*) ARE MARCHING DOWN TO YOUR"
40 PRINT "PICNIC BLANKET! MOVE WITH A AND D AND":PRINT "PRESS W TO PUFF A BUBBLE (!) UP AT THEM."
50 PRINT "A WASP (V) BUZZES OVERHEAD AND DROPS":PRINT "STINGERS (:). DON'T GET STUNG!"
60 PRINT "AN ANT THAT REACHES THE BLANKET TAKES A":PRINT "SANDWICH. 5 SANDWICHES, 3 LIVES."
70 PRINT:PRINT "PRESS ANY KEY"
80 GET K$:IF K$="" THEN 80
90 S=32768:DIM AX(12),AY(12),AD(12),AL(12):SC=0:LF=3:WV=1:FD=5
100 REM A NEW WAVE OF ANTS
110 PRINT "{CLR}":FOR I=0 TO 39:POKE S+22*40+I,102:NEXT
120 NA=6+WV:IF NA>12 THEN NA=12
130 FOR I=1 TO NA:AX(I)=I*3:AY(I)=3+(I AND 1):AD(I)=1:AL(I)=1:NEXT:LV=NA
140 X=20:BY=-1:WX=0:WD=1:SY=-1:T=0:AT=0:POKE S+23*40+X,30:GOSUB 900
300 REM MAIN LOOP
310 GET K$:IF K$="A" AND X>0 THEN POKE S+920+X,32:X=X-1:POKE S+920+X,30
320 IF K$="D" AND X<39 THEN POKE S+920+X,32:X=X+1:POKE S+920+X,30
330 IF K$="W" AND BY<0 THEN BX=X:BY=22
340 T=T+1:IF T<3 THEN 310
350 T=0:POKE 59464,0:IF BY>=0 THEN GOSUB 400
360 GOSUB 650:AT=AT+1:IF AT>=6-INT(WV/2) THEN AT=0:GOSUB 500
370 IF LV=0 THEN WV=WV+1:SC=SC+50:GOTO 110
380 IF FD<=0 OR LF<=0 THEN 800
390 GOTO 310
400 REM THE BUBBLE RISES
410 IF BY<22 THEN POKE S+BY*40+BX,32
420 BY=BY-1:IF BY<3 THEN BY=-1:RETURN
430 FOR I=1 TO NA:IF AL(I)=0 THEN 450
440 IF AX(I)=BX AND AY(I)=BY THEN AL(I)=0:LV=LV-1:SC=SC+10:POKE S+BY*40+BX,32:BY=-1:POKE 59467,16:POKE 59466,15:POKE 59464,50:GOSUB 900:RETURN
450 NEXT:POKE S+BY*40+BX,33:RETURN
500 REM THE ANTS MARCH
510 FOR I=1 TO NA:IF AL(I)=0 THEN 560
520 POKE S+AY(I)*40+AX(I),32:AX(I)=AX(I)+AD(I)
530 IF AX(I)<0 OR AX(I)>39 THEN AD(I)=-AD(I):AX(I)=AX(I)+AD(I):AY(I)=AY(I)+1
540 IF AY(I)>=22 THEN AL(I)=0:LV=LV-1:FD=FD-1:POKE 59467,16:POKE 59466,51:POKE 59464,220:GOSUB 900:GOTO 560
550 POKE S+AY(I)*40+AX(I),42
560 NEXT:RETURN
650 REM THE WASP AND ITS STINGER
660 POKE S+80+WX,32:WX=WX+WD:IF WX<=0 OR WX>=39 THEN WD=-WD
670 POKE S+80+WX,22
680 IF SY<0 AND RND(1)<.15+WV*.02 THEN SX=WX:SY=3
690 IF SY<0 THEN RETURN
700 IF PEEK(S+SY*40+SX)=58 THEN POKE S+SY*40+SX,32
710 SY=SY+1:IF SY=23 AND SX=X THEN LF=LF-1:SY=-1:POKE 59467,16:POKE 59466,51:POKE 59464,250:GOSUB 900:RETURN
720 IF SY>=23 THEN SY=-1:RETURN
730 IF PEEK(S+SY*40+SX)=32 THEN POKE S+SY*40+SX,58
740 RETURN
800 PRINT "{HOME}{RVS} PICNIC OVER! SCORE";SC;"{OFF}            ":PRINT "AGAIN? Y/N"
810 GET K$:IF K$="N" THEN END
820 IF K$<>"Y" THEN 810
830 SC=0:LF=3:WV=1:FD=5:GOTO 110
900 PRINT "{HOME}SCORE";SC;" LIVES";LF;" FOOD";FD;" WAVE";WV;"  ":RETURN
27 · Magazine remake: Pebble Shower (after Meteor Storm, Compute! #29, 1982)

Pebble Shower is an original Pixel 2001 listing. The idea comes from Meteor Storm in Compute! magazine, issue #29 (1982), but the code is our own. Instead of meteors in space, a rockslide rains pebbles on a hiker in a canyon. Dodge the pebbles and catch the sparkling gems that fall among them.

How it works, section by section:

  • Lines 90–130, setup: three arrays track up to 10 falling objects: column PX, row PY (−1 means the slot is free) and screen code PK (81 for a pebble, 43 for a gem). The canyon floor is a row of solid blocks (160) on the bottom line.
  • Lines 310–330, reading keys: A and D move the hiker (screen code 30, ↑) along row 23 at S+920+X. Keys are read twice for every step the falling objects take, so the hiker moves quickly.
  • Lines 500–590, falling: each object is erased, moves down a row, and is drawn again. When it reaches row 23, it either misses (and disappears) or lands on you: a gem scores 25 with a high chirp, and a pebble costs a life with a low thud.
  • Lines 600–650, the shower: at most one new object starts in each tick, in a random column. The chance grows with the level LV, and about one in seven objects is a gem.
  • Lines 340–350, levels: every 50 ticks the level goes up and you earn 10 bonus points, so the shower gets steadily heavier. The game ends when your lives run out, and it remembers your best score.
10 REM PEBBLE SHOWER: AN ORIGINAL PIXEL 2001 TYPE-IN
20 REM IDEA INSPIRED BY METEOR STORM (COMPUTE! #29, 1982)
30 PRINT "{CLR}{RVS} PEBBLE SHOWER {OFF}":PRINT:PRINT "A ROCKSLIDE IS RAINING PEBBLES (O) ON"
40 PRINT "THE CANYON FLOOR! MOVE YOUR HIKER (^)":PRINT "WITH A AND D TO DODGE THEM."
50 PRINT "SPARKLING GEMS (+) FALL TOO: CATCH":PRINT "THEM FOR 25 POINTS EACH."
60 PRINT "YOU HAVE 3 LIVES. THE SHOWER GETS":PRINT "HEAVIER THE LONGER YOU LAST."
70 PRINT:PRINT "PRESS ANY KEY"
80 GET K$:IF K$="" THEN 80
90 S=32768:DIM PX(10),PY(10),PK(10):HS=0
100 REM A NEW GAME
110 PRINT "{CLR}":FOR I=0 TO 39:POKE S+24*40+I,160:NEXT
120 FOR I=1 TO 10:PY(I)=-1:NEXT:SC=0:LF=3:LV=1:TK=0:T=0
130 X=20:POKE S+23*40+X,30:GOSUB 900
300 REM MAIN LOOP
310 GET K$:IF K$="A" AND X>0 THEN POKE S+920+X,32:X=X-1:POKE S+920+X,30
320 IF K$="D" AND X<39 THEN POKE S+920+X,32:X=X+1:POKE S+920+X,30
330 T=T+1:IF T<2 THEN 310
340 T=0:POKE 59464,0:GOSUB 500:TK=TK+1:IF TK<50 THEN 360
350 TK=0:LV=LV+1:SC=SC+10:GOSUB 900
360 IF LF<=0 THEN 800
370 GOTO 310
500 REM PEBBLES AND GEMS FALL
510 FOR I=1 TO 10:IF PY(I)<0 THEN 590
520 POKE S+PY(I)*40+PX(I),32:PY(I)=PY(I)+1
530 IF PY(I)<23 THEN POKE S+PY(I)*40+PX(I),PK(I):GOTO 590
540 IF PX(I)<>X THEN PY(I)=-1:GOTO 590
550 IF PK(I)=43 THEN SC=SC+25:POKE 59467,16:POKE 59466,15:POKE 59464,40
560 IF PK(I)=81 THEN LF=LF-1:POKE 59467,16:POKE 59466,51:POKE 59464,250
570 PY(I)=-1:POKE S+920+X,30:GOSUB 900
590 NEXT
600 REM START NEW ONES AT THE TOP
610 FOR I=1 TO 10:IF PY(I)>=0 THEN 650
620 IF RND(1)>.1+LV*.03 THEN 650
630 PX(I)=INT(RND(1)*40):PY(I)=1:PK(I)=81:IF RND(1)<.15 THEN PK(I)=43
640 POKE S+40+PX(I),PK(I):RETURN
650 NEXT:RETURN
800 POKE 59464,0:IF SC>HS THEN HS=SC
810 PRINT "{HOME}{RVS} BURIED! SCORE";SC;" BEST";HS;"{OFF}        ":PRINT "AGAIN? Y/N"
820 GET K$:IF K$="N" THEN END
830 IF K$<>"Y" THEN 820
840 GOTO 110
900 PRINT "{HOME}SCORE";SC;" LIVES";LF;" LEVEL";LV;"  ":RETURN
28 · Magazine remake: Wizard's Keep (after The Wizard's Castle, Recreational Computing, 1980)

Wizard's Keep is an original Pixel 2001 listing. The idea comes from The Wizard's Castle by Joseph Power in Recreational Computing (1980), but the code is our own. You explore a keep three floors deep, room by room, picking up gold and potions and fighting or fleeing monsters, until you find the wizard's glowing Orb on the bottom floor.

How it works, section by section:

  • Lines 90–200, building the keep: a three-dimensional array R(floor,row,column) holds what is in each room: 0 empty, 1 gold, 2 monster, 3 potion, 4 stairs down, 5 stairs up, 6 the Orb. A second array, V, remembers which rooms you have seen. Each staircase down has a matching staircase up in the same spot on the floor below. The subroutine at 950 picks a random free room.
  • Lines 300–470, entering a room: ON C+1 GOSUB jumps to the right handler for whatever is in the room. This is a neat trick, because one line replaces seven IFs.
  • Lines 500–590, commands: single keystrokes read with GET. The walls of the keep are just bounds checks on X and Y.
  • Lines 600–735, combat: the monster is picked from DATA, and floors further down hold tougher ones. You trade blows round by round with random damage. Win, and the monster drops gold. Run, and you may be clawed on your way back into the room next door.
  • Lines 900–940, the map: shows the rooms you have seen on the current floor, using one letter for each room's contents.
10 REM WIZARD'S KEEP: AN ORIGINAL PIXEL 2001 TYPE-IN
20 REM IDEA INSPIRED BY THE WIZARD'S CASTLE (JOSEPH POWER, RECREATIONAL COMPUTING, 1980)
30 PRINT "{CLR}{RVS} WIZARD'S KEEP {OFF}":PRINT:PRINT "THE OLD WIZARD HID HIS GLOWING ORB IN"
40 PRINT "THE DEEPEST OF THE KEEP'S 3 FLOORS.":PRINT "EACH FLOOR IS A 6 X 6 GRID OF ROOMS."
50 PRINT "MOVE WITH N S E W, TAKE STAIRS WITH":PRINT "U AND D, M SHOWS THE MAP, Q QUITS."
60 PRINT "GRAB GOLD, DRINK POTIONS, FIGHT (F) OR":PRINT "RUN (R) FROM MONSTERS. FIND THE ORB!"
70 PRINT:PRINT "PRESS ANY KEY"
80 GET K$:IF K$="" THEN 80
90 DIM R(3,6,6),V(3,6,6),MN$(6),MS(6)
100 FOR I=1 TO 6:READ MN$(I),MS(I):NEXT
110 REM --- BUILD THE KEEP ---
120 FOR Z=1 TO 3:FOR Y=1 TO 6:FOR X=1 TO 6:V(Z,Y,X)=0
130 C=0:Q=RND(1):IF Q<.15 THEN C=1
140 IF Q>=.15 AND Q<.35 THEN C=2
150 IF Q>=.35 AND Q<.43 THEN C=3
160 R(Z,Y,X)=C:NEXT X,Y,Z
170 R(1,1,1)=0
180 FOR Z=1 TO 2:GOSUB 950:R(Z,Y,X)=4:R(Z+1,Y,X)=5:NEXT
190 Z=3:GOSUB 950:R(3,Y,X)=6
200 Z=1:Y=1:X=1:H=20:GP=0:TN=0
300 REM --- ENTER A ROOM ---
310 V(Z,Y,X)=1:C=R(Z,Y,X):TN=TN+1
320 PRINT:PRINT "FLOOR";Z;" ROOM";X;",";Y;" STR";H;" GOLD";GP
330 ON C+1 GOSUB 400,410,420,440,450,460,470
340 IF H<=0 THEN 800
345 IF FL THEN FL=0:GOTO 310
350 IF C=6 THEN 850
360 PRINT "? ";
370 GET K$:IF K$="" THEN 370
380 PRINT K$:GOTO 500
400 PRINT "AN EMPTY, DUSTY ROOM.":RETURN
410 G=INT(RND(1)*20)+5:GP=GP+G:R(Z,Y,X)=0
415 PRINT "YOU FIND";G;"GOLD PIECES!":RETURN
420 M=INT(RND(1)*(2+Z*1.5))+1:IF M>6 THEN M=6
425 PRINT MN$(M);" BLOCKS YOUR WAY!"
430 PRINT "F)IGHT OR R)UN? ";
432 GET K$:IF K$<>"F" AND K$<>"R" THEN 432
434 PRINT K$:IF K$="R" THEN 700
436 GOTO 600
440 PRINT "A BUBBLING POTION! YOU FEEL STRONGER."
445 H=H+5:R(Z,Y,X)=0:RETURN
450 PRINT "STAIRS LEAD DOWN (D).":RETURN
460 PRINT "STAIRS LEAD UP (U).":RETURN
470 RETURN
500 REM --- COMMANDS ---
510 IF K$="N" AND Y>1 THEN Y=Y-1:GOTO 310
520 IF K$="S" AND Y<6 THEN Y=Y+1:GOTO 310
530 IF K$="W" AND X>1 THEN X=X-1:GOTO 310
540 IF K$="E" AND X<6 THEN X=X+1:GOTO 310
550 IF K$="D" AND C=4 THEN Z=Z+1:GOTO 310
560 IF K$="U" AND C=5 THEN Z=Z-1:GOTO 310
570 IF K$="M" THEN GOSUB 900:GOTO 360
580 IF K$="Q" THEN 820
590 PRINT "YOU CAN'T DO THAT HERE.":GOTO 360
600 REM --- FIGHT, ROUND BY ROUND ---
610 MH=MS(M)
620 D=INT(RND(1)*6)+1:MH=MH-D
630 PRINT "YOU HIT FOR";D;:IF MH<=0 THEN 680
640 E=INT(RND(1)*MS(M)/2)+1:H=H-E
650 PRINT " IT HITS FOR";E
660 IF H<=0 THEN RETURN
670 GOTO 620
680 PRINT " AND WIN!":R(Z,Y,X)=1:C=1
690 GOSUB 410:RETURN
700 REM --- RUN AWAY ---
710 PRINT "YOU FLEE BACK THE WAY YOU CAME."
720 IF RND(1)<.5 THEN H=H-1:PRINT "IT CLAWS YOU AS YOU GO!"
730 FL=1:IF X>1 THEN X=X-1:RETURN
735 X=X+1:RETURN
800 PRINT:PRINT "{RVS}YOU HAVE FALLEN IN THE KEEP.{OFF}"
810 GOTO 860
820 PRINT "YOU LEAVE THE KEEP.":GOTO 860
850 PRINT:PRINT "{RVS}THE ORB GLOWS IN YOUR HANDS!{OFF}"
855 PRINT "YOU WIN WITH";GP;"GOLD IN";TN;"MOVES."
860 PRINT "AGAIN? Y/N"
870 GET K$:IF K$="N" THEN END
880 IF K$<>"Y" THEN 870
890 GOTO 120
900 REM --- MAP OF THIS FLOOR ---
905 PRINT "FLOOR";Z;" (*=YOU ?=UNSEEN)"
910 FOR J=1 TO 6:FOR I=1 TO 6:K$="?"
915 IF V(Z,J,I) THEN K$=MID$(".GMPDUO",R(Z,J,I)+1,1)
920 IF J=Y AND I=X THEN K$="*"
925 PRINT K$;" ";:NEXT I:PRINT:NEXT J
930 PRINT "G=GOLD M=MONSTER P=POTION D/U=STAIRS"
940 RETURN
950 X=INT(RND(1)*6)+1:Y=INT(RND(1)*6)+1
960 IF R(Z,Y,X)>3 OR (X=1 AND Y=1) THEN 950
970 RETURN
990 DATA A GOBLIN,6,A GIANT RAT,4,A SKELETON,9
995 DATA AN OGRE,14,A GARGOYLE,18,A DRAGON,25
29 · Original adventure: Beacon Isle (a disk-based text adventure)

Beacon Isle is an original Pixel 2001 text adventure that uses the floppy drive. A storm is coming and the old lighthouse has gone dark. Explore the island, solve its puzzles and light the beacon before the fishing boats come home. Type two-word commands like TAKE LAMP or OPEN DOOR, or one letter to move (N S E W U D). SAVE and LOAD keep your game on disk, and there are 100 points to earn.

How it works, section by section:

  • Lines 140–200, the world comes from disk: the program opens the file BEACON ROOMS and checks the drive's status on channel 15. Error 62 (FILE NOT FOUND) means this is the first run, so the subroutine at 2000 writes the world from the DATA lines onto the disk. After that, every run reads the rooms, their descriptions, their exits and the items from the file with INPUT#. Type LOAD"$",8 afterwards and you'll see the file in the directory.
  • The world as data: each room has a name, a description and six exits (N S E W U D), stored in the array EX(room,direction), where 0 means there's no way through. Each item has a location in IL(): a room number, −1 when you're carrying it, or 0 while it's hidden. You could change the whole map without touching the game's code.
  • Lines 410–465, the two-word parser: the program splits what you type at the first space into a verb and a noun, and keeps only the first three letters of each, as many classic adventures did. It checks the verb against the direction words first and then against the verb table. ON J GOSUB jumps to the matching handler.
  • Lines 900–965, input and output: a GET loop reads your typing, so pressing RETURN on an empty line can't stop the program the way INPUT would. The subroutine at 950 word-wraps long text to the 40-column screen.
  • Lines 1000–1625, the rules: a few flags hold the state of the puzzles. DL is the locked door, CR the crab, LT the lit lamp, and DK whether the room you're in is dark.
  • Lines 1700–1820, save files: SAVE writes your room, the flags, your score and every item's location to BEACON SAVE. The @ lets it replace an older save. LOAD reads them back, and if there's no saved game, the drive's error 62 says so.
10 REM BEACON ISLE: AN ORIGINAL DISK ADVENTURE FOR PIXEL 2001
20 REM THE WORLD LIVES IN A DISK FILE; GAMES ARE SAVED TO DISK
100 REM --- SET UP ---
110 DIM R$(11),D$(11),EX(11,6),IN$(6),IL(6),VB$(18),DN$(6)
120 FOR J=1 TO 18:READ VB$(J):NEXT:FOR J=1 TO 6:READ DN$(J):NEXT
130 PRINT "{CLR}{RVS} BEACON ISLE {OFF}":PRINT "AN ADVENTURE ON DISK":PRINT
140 OPEN 15,8,15
150 OPEN 2,8,2,"0:BEACON ROOMS,S,R":INPUT#15,EN,EM$
160 IF EN=62 THEN CLOSE 2:GOSUB 2000:GOTO 150
165 IF EN THEN PRINT "DISK ERROR";EN;EM$:CLOSE 2:CLOSE 15:END
170 PRINT "LOADING THE WORLD FROM DISK..."
180 INPUT#2,NR:FOR I=1 TO NR:INPUT#2,R$(I),D$(I)
190 FOR J=1 TO 6:INPUT#2,EX(I,J):NEXT J,I
200 INPUT#2,NI:FOR I=1 TO NI:INPUT#2,IN$(I),IL(I):NEXT:CLOSE 2
210 RM=1:DL=1:CR=1:LT=0:SC=0:MV=0:WN=0
220 PRINT:T$="A STORM IS COMING AND THE OLD LIGHTHOUSE ON BEACON ISLE HAS GONE DARK. LIGHT IT AGAIN BEFORE THE FISHING BOATS COME HOME. TYPE HELP FOR WORDS I KNOW."
230 GOSUB 950:PRINT:GOSUB 1000
400 REM --- READ AND PARSE A COMMAND ---
410 PRINT "> ";:GOSUB 900:IF C$="" THEN 410
415 MV=MV+1:P=0:FOR J=1 TO LEN(C$):IF MID$(C$,J,1)=" " AND P=0 THEN P=J
420 NEXT J:V$=C$:N$=""
430 IF P>0 THEN V$=LEFT$(C$,P-1):N$=MID$(C$,P+1)
435 IF V$="GO" THEN V$=N$:N$=""
440 V$=LEFT$(V$,3):N$=LEFT$(N$,3)
445 DR=0:FOR J=1 TO 6:IF V$=MID$("NSEWUD",J,1) OR V$=DN$(J) THEN DR=J
450 NEXT J:IF DR THEN 500
455 FOR J=1 TO 18:IF V$=VB$(J) THEN 465
460 NEXT J:PRINT "I DON'T KNOW HOW TO ";C$;".":GOTO 410
465 ON J GOSUB 1000,1100,1100,1200,1300,1300,1400,1400,1500,1600,1600,1200,1700,1800,1800,1900,1950,1960
470 IF WN=0 THEN 410
480 IF WN=1 THEN PRINT:PRINT "{RVS}*** YOU WIN! ***{OFF}":GOSUB 1960
490 CLOSE 15:END
500 REM --- MOVING ---
505 IF DK=1 AND (RM<>8 OR DR<>5) THEN PRINT "YOU STUMBLE AROUND IN THE DARK.":GOTO 410
510 X=EX(RM,DR):IF X=0 THEN PRINT "YOU CAN'T GO THAT WAY.":GOTO 410
515 IF RM=3 AND DR=1 AND DL=1 THEN PRINT "THE OAK DOOR IS LOCKED.":GOTO 410
520 RM=X:GOSUB 1000:GOTO 410
900 REM --- TYPE A LINE (GET, SO EMPTY LINES ARE SAFE) ---
905 C$=""
910 GET K$:IF K$="" THEN 910
915 IF K$=CHR$(13) THEN PRINT:RETURN
920 IF K$=CHR$(20) AND LEN(C$)>0 THEN C$=LEFT$(C$,LEN(C$)-1):PRINT K$;:GOTO 910
925 IF K$<" " OR K$>"Z" OR LEN(C$)>30 THEN 910
930 C$=C$+K$:PRINT K$;:GOTO 910
950 REM --- PRINT T$ WITH WORD WRAP ---
955 IF LEN(T$)<40 THEN PRINT T$:RETURN
960 FOR J=40 TO 2 STEP -1:IF MID$(T$,J,1)<>" " THEN NEXT J
965 PRINT LEFT$(T$,J-1):T$=MID$(T$,J+1):GOTO 955
1000 REM --- DESCRIBE THE ROOM ---
1005 DK=0:IF RM>7 AND RM<11 AND (LT=0 OR IL(1)<>-1) THEN DK=1
1010 IF DK=1 THEN PRINT "IT IS PITCH DARK. YOU CAN'T SEE A THING.":RETURN
1015 PRINT "{RVS}";R$(RM);"{OFF}":T$=D$(RM):GOSUB 950
1020 IF RM=11 AND CR=1 THEN PRINT "A GIANT CRAB GUARDS SOMETHING SHINY."
1025 IF RM=3 AND DL=0 THEN PRINT "THE DOOR STANDS OPEN."
1030 FOR I=1 TO NI:IF IL(I)=RM THEN PRINT "THERE IS A ";IN$(I);" HERE."
1035 NEXT I:RETURN
1050 I=0:FOR J=1 TO NI:IF N$=LEFT$(IN$(J),3) THEN I=J
1055 NEXT J:RETURN
1100 REM --- TAKE ---
1105 IF DK=1 THEN PRINT "YOU CAN'T SEE ANYTHING.":RETURN
1110 IF N$="CRA" THEN PRINT "IT SNAPS AT YOUR FINGERS!":RETURN
1115 GOSUB 1050:IF I=0 THEN PRINT "TAKE WHAT?":RETURN
1120 IF IL(I)=-1 THEN PRINT "YOU ALREADY HAVE IT.":RETURN
1125 IF IL(I)<>RM THEN PRINT "I SEE NO ";IN$(I);" HERE.":RETURN
1130 IL(I)=-1:PRINT "TAKEN."
1135 IF I>4 THEN SC=SC+10:PRINT "A TREASURE! (+10)"
1140 RETURN
1200 REM --- DROP OR PUT ---
1205 GOSUB 1050:IF I=0 THEN PRINT "YOU DON'T HAVE THAT.":RETURN
1210 IF IL(I)<>-1 THEN PRINT "YOU DON'T HAVE THAT.":RETURN
1215 IF I=5 AND RM=7 THEN 1240
1220 IL(I)=RM:PRINT "DROPPED.":IF I=1 THEN LT=0
1225 RETURN
1240 T$="YOU SET THE CRYSTAL IN THE GREAT LAMP. A BLAZING BEAM SWEEPS THE SEA AND FAR OUT A FISHING BOAT TURNS SAFELY FOR HOME."
1245 GOSUB 950:IL(5)=0:SC=SC+50:WN=1:RETURN
1300 REM --- INVENTORY ---
1305 PRINT "YOU ARE CARRYING:":F=0:FOR I=1 TO NI:IF IL(I)<>-1 THEN 1320
1310 F=1:PRINT "  ";IN$(I);:IF I=1 AND LT=1 THEN PRINT " (LIT)";
1315 PRINT
1320 NEXT I:IF F=0 THEN PRINT "  NOTHING AT ALL."
1325 RETURN
1400 REM --- UNLOCK OR OPEN THE DOOR ---
1405 IF RM<>3 THEN PRINT "THERE IS NOTHING TO OPEN HERE.":RETURN
1410 IF DL=0 THEN PRINT "IT IS ALREADY OPEN.":RETURN
1415 IF IL(4)<>-1 THEN PRINT "IT IS LOCKED. YOU NEED A KEY.":RETURN
1420 DL=0:SC=SC+10:PRINT "THE KEY TURNS. THE DOOR CREAKS OPEN.":RETURN
1500 REM --- LIGHT THE LAMP ---
1505 IF IL(1)<>-1 THEN PRINT "YOU HAVE NOTHING TO LIGHT.":RETURN
1510 IF IL(2)<>-1 THEN PRINT "YOU HAVE NOTHING TO LIGHT IT WITH.":RETURN
1515 IF LT=1 THEN PRINT "THE LAMP IS ALREADY LIT.":RETURN
1520 LT=1:SC=SC+10:PRINT "THE LAMP GLOWS WARM AND YELLOW."
1525 IF DK=1 THEN GOSUB 1000
1530 RETURN
1600 REM --- CATCH THE CRAB WITH THE NET ---
1605 IF RM<>11 OR CR=0 THEN PRINT "THERE IS NOTHING TO CATCH HERE.":RETURN
1610 IF IL(3)<>-1 THEN PRINT "WITH YOUR BARE HANDS? NO WAY!":RETURN
1615 CR=0:IL(3)=0:IL(4)=11:SC=SC+10
1620 T$="YOU TOSS THE NET OVER THE CRAB. IT SCUTTLES INTO THE SEA DRAGGING THE NET AND LEAVES BEHIND AN IRON KEY!"
1625 GOSUB 950:RETURN
1700 REM --- SAVE THE GAME TO DISK ---
1705 OPEN 3,8,3,"@0:BEACON SAVE,S,W"
1710 PRINT#3,RM:PRINT#3,DL:PRINT#3,CR:PRINT#3,LT:PRINT#3,SC:PRINT#3,MV
1715 FOR I=1 TO NI:PRINT#3,IL(I):NEXT:CLOSE 3
1720 INPUT#15,EN,EM$:IF EN THEN PRINT "DISK ERROR:";EN;EM$:RETURN
1725 PRINT "GAME SAVED TO DISK.":RETURN
1800 REM --- RESTORE A SAVED GAME ---
1805 OPEN 3,8,3,"0:BEACON SAVE,S,R":INPUT#15,EN,EM$
1810 IF EN THEN CLOSE 3:PRINT "NO SAVED GAME ON THIS DISK.":RETURN
1815 INPUT#3,RM,DL,CR,LT,SC,MV:FOR I=1 TO NI:INPUT#3,IL(I):NEXT
1820 CLOSE 3:PRINT "GAME RESTORED.":GOSUB 1000:RETURN
1900 PRINT "THE STORM ROLLS IN WITHOUT YOU.":GOSUB 1960:WN=2:RETURN
1950 PRINT "TRY: N S E W U D, LOOK, TAKE X, DROP X,":PRINT "INV, OPEN X, LIGHT X, CATCH X, SAVE,"
1955 PRINT "LOAD, SCORE, QUIT.":RETURN
1960 PRINT "SCORE";SC;"OF 100 IN";MV;"MOVES.":RETURN
2000 REM --- FIRST RUN: WRITE THE WORLD FILE FROM DATA ---
2005 PRINT "WRITING THE WORLD TO DISK..."
2010 OPEN 3,8,3,"0:BEACON ROOMS,S,W"
2015 READ NR:PRINT#3,NR:FOR I=1 TO NR:READ A$,B$:PRINT#3,A$:PRINT#3,B$
2020 FOR J=1 TO 6:READ E:PRINT#3,E:NEXT J,I
2025 READ NI:PRINT#3,NI:FOR I=1 TO NI:READ A$,E:PRINT#3,A$:PRINT#3,E:NEXT
2030 CLOSE 3:INPUT#15,EN,EM$:IF EN=0 THEN RETURN
2035 PRINT "DISK ERROR";EN;EM$:PRINT "THE WORLD FILE WOULDN'T FIT. FREE SOME":PRINT "SPACE (FORMAT OR SCRATCH) AND RUN AGAIN.":CLOSE 15:END
3000 REM --- WORDS ---
3010 DATA LOO,TAK,GET,DRO,INV,I,OPE,UNL,LIG,CAT,USE,PUT,SAV,LOA,RES,QUI,HEL,SCO
3020 DATA NOR,SOU,EAS,WES,UP,DOW
3100 REM --- ROOMS: NAME, TEXT, EXITS N S E W U D ---
3110 DATA 11
3120 DATA "BEACH","YOU STAND ON A COLD GREY BEACH. A PATH CLIMBS NORTH AND ROCKS LIE EAST.",2,0,11,0,0,0
3130 DATA "CLIFF PATH","A WINDY PATH ON THE CLIFF. THE LIGHTHOUSE IS NORTH; A HUT IS EAST.",3,1,4,0,0,0
3140 DATA "LIGHTHOUSE DOOR","A TALL WHITE TOWER WITH A HEAVY OAK DOOR TO THE NORTH.",5,2,0,0,0,0
3150 DATA "FISHER'S HUT","A SMALL HUT THAT SMELLS OF TAR AND SALT. THE DOOR IS WEST.",0,0,0,2,0,0
3160 DATA "ROUND HALL","STAIRS GO UP AND A TRAPDOOR LEADS DOWN. THE DOOR IS SOUTH.",0,3,0,0,6,8
3170 DATA "SPIRAL STAIR","AN IRON STAIR WINDS UP AND DOWN INTO SHADOW.",0,0,0,0,7,5
3180 DATA "LAMP ROOM","THE GREAT LAMP STANDS HERE BUT ITS HOLDER IS EMPTY. A STORM BREWS AT SEA.",0,0,0,0,0,6
3190 DATA "CELLAR","A DAMP CELLAR FULL OF OLD BARRELS. A TUNNEL RUNS EAST.",0,0,9,0,5,0
3200 DATA "TUNNEL","SEAWATER SLOSHES AROUND YOUR ANKLES. THE TUNNEL GOES EAST AND WEST.",0,0,10,8,0,0
3210 DATA "GROTTO","A GLITTERING SEA CAVE. LIGHT DANCES ON THE WATER. THE WAY OUT IS WEST.",0,0,0,9,0,0
3220 DATA "TIDE POOLS","ROCKY POOLS FULL OF STARFISH. THE BEACH IS WEST.",0,0,0,1,0,0
3300 REM --- ITEMS: NAME, STARTING ROOM (0 = HIDDEN) ---
3310 DATA 6,LAMP,4,TINDERBOX,4,NET,4,KEY,0,CRYSTAL,10,COIN,9
💬 Give us feedback