Original Title: Commodore 128 Personal Computer System Guide Published by: Commodore Business Machines, Ltd. 1985 Typed by: Rene van Belzen Version: April 9, 2000 Hosted at www.commodore.ca or text.commodore.ca SECTIONS 1 - 15 Notes from the typist ===================== Entering (data typing) the Commodore 128 System Guide... This entailed far more than I bargained for. This is because not only because the original text contained errors, which had to be corrected, but also because some useful information and hints were missing. I could have written a separate e-book containing what I feel should have been included in the C128 System Guide as well (and I still may do that one day). In stead I added some words here and there to clarify matters, to avoid wandering off too much from the original text. This means this e-text is not an exact 1:1 replica of the original, but I'm sure the authors of the original System Guide wouldn't object (too much). They pro- bably had to write the System Guide in a jiffie, while I could take as long as I wanted to get the text just right. Credits: ------- Most of the e-text I have typed (and corrected) myself. However, some of the ASCII art and some of the appendixes I have copied and adapted from the C64 Programmer's Reference Guide, the e-text version by Ville Muikkula. Also, where the original text by Commodore had shortcomings I added/corrected text. Many thanks to all those people who pointed me to the existing errors in one of my earlier publications of the C128 System Guide. April 9, 2000 Rene van Belzen mailto:hurray@xs4all.nl http://www.xs4all.nl/~hurray/cbm/ (Note that both the e-mail and web address may change at any point in the future.) System Guide Commodore 128 Personal Computer (c) Commodore Electronics, Ltd. 1985. All rights reserved. Copyright (c) 1985 by Commodore Electronics Limited All rights reserved This manual contains copyrighted and proprietary information. No part of this publication may be reproduced, stored in a retrieval system, or trans- mitted in any form or by any means, electronic, mechanical, photocopying, recording or otherwise, without the prior written permission of Commodore Electronics Limited. Commodore BASIC 7.0 Copyright (c) 1985 by Commodore Electronics Limited; All rights reserved Copyright (c) 1977 by Microsoft Corp. All rights reserved CP/M (R) Plus Version 3.0 Copyright (c) 1982 Digital Research Inc. All rights reserved CP/M is a registered trademark of Digital Research Inc. CONTENTS C128 SYSTEM GUIDE CHAPTER I - INTRODUCTION SECTION 1 - HOW TO USE THIS GUIDE SECTION 2 - OVERVIEW OF THE COMMODORE 128 PERSONAL COMPUTER CHAPTER II - USING C128 MODE SECTION 3 - GETTING STARTED IN BASIC SECTION 4 - ADVANCED BASIC PROGRAMMING SECTION 5 - SOME BASIC COMMANDS AND KEYBOARD OPERATIONS UNIQUE TO C128 SECTION 6 - COLOR, ANIMATION AND SPRITE GRAPHICS SECTION 7 - SOUND AND MUSIC IN C128 MODE SECTION 8 - USING 80 COLUMNS CHAPTER III - USING C64 MODE SECTION 9 - USING BASIC IN C64 MODE SECTION 10 - STORING AND REUSING YOUR PROGRAMS IN C64 MODE CHAPTER IV - CP/M MODE SECTION 11 - INTRODUCTION TO CP/M 3.0 SECTION 12 - FILES, DISKS AND DRIVES IN CP/M 3.0 SECTION 13 - USING THE CONSOLE AND PRINTER IN CP/M 3.0 SECTION 14 - SUMMARY OF MAJOR CP/M 3.0 COMMANDS SECTION 15 - COMMODORE ENHANCEMENTS TO CP/M 3.0 CHAPTER V - BASIC 7.0 ENCYCLOPAEDIA SECTION 16 - INTRODUCTION SECTION 17 - BASIC COMMANDS AND STATEMENTS SECTION 18 - BASIC FUNCTIONS SECTION 19 - VARIABLES AND OPERATIONS SECTION 20 - RESERVED WORDS AND SYMBOLS APPENDICES APPENDIX A - BASIC LANGUAGE ERROR MESSAGES APPENDIX B - DOS ERROR MESSAGES APPENDIX C - CONNECTORS/PORTS FOR PERIPHERAL EQUIPMENT APPENDIX D - SCREEN DISPLAY CODES APPENDIX E - ASCII AND CHR$ CODES APPENDIX F - SCREEN AND COLOR MEMORY MAPS APPENDIX G - DERIVED MATHEMATICAL FUNCTIONS APPENDIX H - MEMORY MAP APPENDIX I - CONTROL AND ESCAPE CODES APPENDIX J - MACHINE LANGUAGE MONITOR APPENDIX K - BASIC 7.0 ABBREVIATIONS APPENDIX L - DISK COMMAND SUMMARY GLOSSARY INDEX CHAPTER 1 INTRODUCTION SECTION 1 1. How to Use This Guide This Commodore 128 System Guide is designed to help you make full use of the advanced capabilities of the Commodore 128 computer. Before you read any further in this System Guide, make sure you have read the other book that comes with your computer, the Commodore 128 Personal Computer Introductory Guide. This introductory guide contains important information on getting started with the Commodore 128. If you are primarily interested in using the BASIC language to create and run your own programs, you should read Chapter II, USING C128 MODE. This chapter introduces you to the BASIC programming language as used in both C128 and C64 modes, describes the Commodore 128 keyboard, defines some advanced commands you can use in both C128 and C64 modes, shows how to use a number of powerful new BASIC commands (including colour, graphic and sound commands) that are unique to C128 Mode, and describes how to use the 80-column capabilities available in C128 Mode. If you want to use BASIC in C64 Mode, read Chapter III, USING C64 MODE. If you want to use CP/M on the Commodore 128, read Chapter IV, USING CP/M MODE. This chapter tells you how to start up and use CP/M on the Commodore 128. In CP/M you can choose from thousands of commercial software packages, including the PERFECT series (PERFECT WRITER, PERFECT CALC, PERFECT FILER). You can also create your own CP/M programs. If you want details on the BASIC 7.0 commands, read Chapter IV, BASIC 7.0 ENCYCLOPAEDIA. This chapter gives format and usage details on all BASIC 7.0 commands, statements and functions. If, after reading Chapters I through V, you are looking for additional technical information about a particular Commodore 128 topic, first check the Appendices to this System Guide. These appendices contain a wide range of information, such as a complete list of BASIC and DOS error messages and a summary of disk commands. A Glossary following the Appendices provides definitions of computing terms. For complete technical details about any feature of the Commodore 128, con- sult the Commodore 128 Programmer's Reference Guide. SECTION 2 2. Overview of the Commodore C128 Personal Computer 2.1 OVERVIEW OF THE COMMODORE C128 PERSONAL COMPUTER 2.1.1 C128 MODE 2.1.2 C64 MODE 2.1.3 CP/M MODE 2.2 SWITCHING BETWEEN MODES 2.2.1 MODE SWITCHING CHART 2.1 OVERVIEW OF THE COMMODORE C128 PERSONAL COMPUTER The Commodore 128 Personal Computer offers three primary operating modes: * C128 Mode * C64 Mode * CP/M Mode 2.1.1 C128 Mode In C128 Mode, the Commodore 128 Personal Computer provides access to 128K of RAM and a powerful extended BASIC language known as BASIC 7.0. BASIC 7.0 offers over 140 commands, statements and functions. C128 Mode also provides both 40 and 80 column output and full use of the 92-key keyboard. A built- in machine language monitor allows you to create and debug your own machine language programs. In C128 Mode you can use a number of new peripheral devices from Commodore, including a new fast serial disk drive (the 1571), a mouse, and a 40/80 column composite video/RGBI monitor (the 1901). You can also use all standard Commodore serial peripherals. 2.1.2 C64 Mode In C64 Mode, the Commodore 128 operates exactly like a Commodore 64 com- puter, allowing you to take full advantage of the wide range of available C64 software. You also have full compatibility with all C64 peripherals. C64 Mode provides BASIC 2.0 language, 40 column output and access to 64K of RAM. 2.1.3 CP/M Mode In CP/M Mode, an onboard Z80 microprocessor gives you all the capabilities of Digital Research's CP/M Plus version 3.0, plus several new capabilities by Commodore. The Commodore 128's CP/M package, called CP/M Plus, provides 128K of RAM, 40 and 80 column output, access to the full keyboard, inclu- ding the numeric keypad and special keys, and access to the new Commodore 1571 fast serial disk drive as well as standard serial peripherals. Chapters II, III and IV, which include Sections 3 through 15, tell you how to access and use the capabilities of the three powerful and versatile operating modes of the Commodore 128 Personal Computer. 2.2 Switching Between Modes The following chart tells you how to switch to one mode from another. NOTE: If you are using a Commodore 1901 dual monitor remember to move the video switch on the monitor from the COMPOSITE or SEPARATED to RGBI when switching from 40 column to 80 column display. Reverse this step when switching from 80 to 40 columns. 2.2.1 MODE SWITCHING CHART FROM T| OFF C128 C128 C64 CP/M CP/M O| 40 COL(1) 80 COL(2) (3) 40 COL(4) 80 COL(5) -+------------+-----------+-----------+-----------+-----------+-----------+ 1|1.Check that| |1.Press |1.Check |1.Check |1.Check | | {40/80} | | {esc} | that | that | that | | key is UP.| | key; | {40/80} | {40/80} | {40/80} | |2.Turn | | release. | key is | key is | key is | | computer | |2.Press X | UP. | UP. | UP. | | ON. | | key. |2.Turn |2.Remove |2.Remove | | | OR | computer | CP/M | CP/M | | | |1.Check | OFF, then| system | system | | | | that | ON. | disk, if | disk, if | | | | {40/80} | | neces- | neces- | | | | key is | | sary. | sary. | | | | UP. | |3.Turn |3.Turn | | | |2.Press | | computer | computer | | | | {reset} | | OFF, then| OFF, then| | | | button. | | ON. | ON. | -+------------+-----------+-----------+-----------+-----------+-----------+ 2|1.Press |1.Press | |1.Press |1.Press |1.Check | | {40/80} | {esc} | | {40/80} | {40/80} | that | | key DOWN. | key; | | key DOWN.| key DOWN.| {40/80} | |2.Turn | release. | |2.Turn |2.Remove | key is | | computer |2.Press X | | computer | CP/M | DOWN. | | ON. | key. | | OFF, then| system |2.Remove | | | OR | | ON. | disk from| CP/M | | |1.Press | | | drive, if| system | | | {40/80} | | | neces- | disk from| | | key DOWN.| | | sary. | drive, if| | |2.Press | | |3.Turn | neces- | | | {reset} | | | computer | sary. | | | button. | | | OFF, then|3.Turn | | | | | | ON. | computer | | | | | | | OFF, then| | | | | | | ON. | -+------------+-----------+-----------+-----------+-----------+-----------+ 3|1.Hold {C=} |1.Type |1.Type | |1.Turn |1.Turn | | key DOWN. | GO 64; | GO 64; | | computer | computer | |2.Turn | press | press | | OFF. | OFF. | | computer | {return}.| {return}.| |2.Check |2.Check | | ON. |2.The |2.The | | that | that | | OR | computer | computer | | {40/80} | {40/80} | |1.Insert C64| responds:| responds:| | key is | key is | | cartridge.| ARE YOU | ARE YOU | | UP. | UP. | |2.Turn | SURE? | SURE? | |3.Hold DOWN|3.Hold DOWN| | computer | Type Y; | Type Y; | | {C=} key | {C=} key | | ON. | press | press | | while | while | | | {return}.| {return}.| | turning | turning | | | | | | computer | computer | | | | | | ON. | ON. | | | | | | OR | OR | | | | | |1.Turn |1.Turn | | | | | | computer | computer | | | | | | OFF. | OFF. | | | | | |2.Insert |2.Insert | | | | | | C64 car- | C64 car- | | | | | | tridge. | tridge. | | | | | |3.Turn |3.Turn | | | | | | power ON.| power ON.| -+------------+-----------+-----------+-----------+-----------+-----------+ 4|1.Turn disk |1.Turn disk|1.Turn disk|1.Check | |1.Insert | | drive ON. | drive ON.| drive ON.| that | | CP/M | |2.Insert |2.Insert |2.Insert | {40/80} | | utilities| | CP/M sys- | CP/M sys-| CP/M sys-| key is | | disk in | | tem disk | tem disk | tem disk | UP. | | drive. | | in disk | in disk | in disk |2.Turn disk| |2.At screen| | drive. | drive. | drive. | drive ON.| | prompt, | |3.Check that|3.Check |3.Check |3.Insert | | A> type: | | {40/80} | that | that | CP/M | | DEVICE | | key is UP.| {40/80} | {40/80} | system | | CONOUT | |4.Turn | key is | key is | disk in | | = 40COL. | | computer | UP. | UP. | drive. | |3.Press | | ON. |4.Type: |4.Type: |4.Turn | | {return}.| | | BOOT. | BOOT. | computer | | | | |5.Press |5.Press | OFF, then| | | | | {return}.| {return} | ON. | | | -+------------+-----------+-----------+-----------+-----------+-----------+ 5|1.Turn disk |1.Turn disk|1.Turn disk|1.Press |1.Insert | | | drive ON. | drive ON.| drive ON.| {40/80} | CP/M | | |2.Insert |2.Insert |2.Insert | key DOWN.| utilities| | | CP/M sys- | CP/M sys-| CP/M sys-|2.Turn disk| disk in | | | tem disk | tem disk | tem disk | drive ON.| drive. | | | in disk | in disk | in disk |3.Insert |2.At screen| | | drive. | drive. | drive. | CP/M | prompt | | |3.Press |3.Press |3.Check | system | A> type: | | | {40/80} | {40/80} | that | disk in | DEVICE | | | key DOWN. | key DOWN.| {40/80} | drive. | CONOUT | | |4.Turn |4.Type: | key is |4.Turn | = 80COL. | | | computer | computer | DOWN. | computer |3.Press | | | ON. | BOOT. |4.Type: | OFF, then| {return}.| | | |5.Press | BOOT. | ON. | | | | | {return}.|5.Press | | | | | | | {return}.| | | | -+------------+-----------+-----------+-----------+-----------+-----------+ NOTE: If you are using a Commodore 1902 dual monitor, remember to move the video switch on the monitor from COMPOSITE or SEPARATED to RGBI when switching from 40-column to 80-column display; reverse this step when switching from 80 to 40 columns. Also, when switching between modes remove any cartridges from the expansion port and any disks from the disk drive. CHAPTER 2 USING C128 MODE SECTION 3 3. Getting Started in Basic 3.1 BASIC PROGRAMMING LANGUAGE 3.1.1 Direct Mode 3.1.2 Program Mode 3.2 USING THE KEYBOARD 3.2.0.1 C128 Keyboard Lay-Out 3.2.1 Keyboard Character Sets 3.2.2 Using the Command Keys 3.2.2.1 Return 3.2.2.2 Shift 3.2.2.3 Shift Lock 3.2.2.4 Moving the cursor 3.2.2.4.1 Using the four Arrow Cursor keys 3.2.2.4.2 Using the CRSR keys 3.2.2.5 INST/DEL 3.2.2.5.1 Insterting characters 3.2.2.5.2 Deleting characters 3.2.2.5.3 Using INSerT and DELete together 3.2.2.6 Control 3.2.2.7 Run/Stop 3.2.2.8 Restore 3.2.2.9 CLR/Home 3.2.2.10 Commodore key 3.2.3 Function Keys 3.2.4 Displaying Graphic Characters 3.2.5 Rules for Typing BASIC Language Programs 3.3 GETTING STARTED - THE PRINT COMMAND 3.3.1 Printing Numbers 3.3.2 Using the Question Mark to Abbreviate the PRINT Command 3.3.3 Printing Text 3.3.4 Printing in Different Colors Table 3-1. Available Colors in 40- and 80-Column Screen Formats. 3.3.5 Using the Cursor Keys Inside Quotes with the PRINT Command 3.4 BEGINNING TO PROGRAM 3.4.1 What a Program Is 3.4.2 Line Numbers 3.4.3 Viewing your Program - The LIST Command 3.4.4 A Simple Loop - The GOTO Command 3.4.5 Clearing the Computer's Memory - The NEW Command 3.4.6 Using Color in a Program 3.5 EDITING YOUR PROGRAM 3.5.1 Erasing a Line from a Program 3.5.2 Duplicating a Line 3.5.3 Replacing a Line 3.5.4 Changing a Line 3.6 MATHEMATICAL OPERATIONS 3.6.1 Addition and Subtraction 3.6.2 Multiplication and Division 3.6.3 Exponentiation 3.6.4 Order of Operations 3.6.5 Using Parentheses to Define the Order of Operations 3.7 CONSTANTS, VARIABLES AND STRINGS 3.7.1 Constants 3.7.2 Variables 3.7.3 Strings 3.8 SAMPLE PROGRAM 3.9 STORING AND REUSING YOUR PROGRAMS 3.9.1 Formatting a Disk - The HEADER Command 3.9.2 SAVEing on Disk 3.9.3 SAVEing on Cassette 3.9.4 LOADing from Disk 3.9.5 LOADing from Cassette Tape 3.9.6 Other Disk-Related Commands 3.9.6.1 Verifying a Program 3.9.6.2 Displaying Your Disk Directory 3.1 BASIC PROGRAMMING LANGUAGE The BASIC programming language is a special language that lets you communi- cate with your Commodore 128. Using BASIC is one means by which you instruct your computer what to do. BASIC has its own vocabulary (made up of commands, statements and func- tions) and its own rules of structure (called syntax). You can use the BASIC vocabulary and syntax to create a set of instructions called a program, which your computer can then perform or "run". Using BASIC, you can communicate with your Commodore 128 in two ways: within a program, or directly (outside a program). 3.1.1 Direct Mode Your Commodore 128 is ready to accept BASIC commands in direct mode as soon as you turn on the computer. In the direct mode, you type commands on the keyboard and enter them into the computer by pressing the {return} key. Most BASIC commands in your Commodore 128 can be used in direct mode as well as in a program. 3.1.2 Program Mode In program mode you enter a set of instructions that perform a specific task. Each instruction is contained in a sequential program line. A state- ment in a program may be as long as 160 characters; this is equivalent to four full screen lines in 40-column format, and two full screen lines in 80-column format. Once you have typed a program, you can use it immediately by typing the RUN command and pressing the {return} key. You can also store the program on disk or tape by using the DSAVE (or SAVE) command. Then you recall it from the disk or tape by using the DLOAD (or LOAD) command. This command copies the program from the disk or tape and places that program in the Commodore 128's memory. You can then use or "execute" the program again by entering the RUN command. All these commands are explained later in this section. Most of the time you will be using you computer with programs, including programs you yourself write, and commercially available software packages. The only time you operate in direct mode is when you are manipulating or editing your programs with commands such as LIST, LOAD, SAVE and RUN. As a rule, the difference between direct mode and operation within a program is that direct mode commands have no line numbers. 3.2 USING THE KEYBOARD Shown below is the keyboard of the Commodore 128 Personal Computer. 3.2.0.1 C128 Keyboard Lay-Out +--------------+ /E\/T\/A\/C\ /H\/L\/4\/N\ /u\/d\/l\/r\ | /F\/F\/F\/F\ | |s a l | |l | |p w f g| | |1 3 5 7| | \c/\b/\t/\L/ \p/\F/\8/\S/ \ /\n/\t/\t/ | \ /\ /\ /\ / | +--------------------------------------------------+--------------+ | /L\/!\/"\/#\/$\/%\/&\/'\/(\/)\/ \/ \/ \/l\/C\/I\ | / \/ \/ \/ \ | | 0 + - b | | |7 8 9 +| | \A/\1/\2/\3/\4/\5/\6/\7/\8/\9/\ /\ /\ /\s/\H/\D/ | \ /\ /\ /\ / | | | /co\/ \/ \/ \/ \/ \/ \/ \/ \/ \/ \/ \/ \/U\/RES\ | / \/ \/ \/ \ | |nt Q W E R T Y U I O P @ * STO| | |4 5 6 -| | \rl/\ /\ /\ /\ /\ /\ /\ /\ /\ /\ /\ /\ /\A/\RE / | \ /\ /\ /\ / | | | /R\/S\/ \/ \/ \/ \/ \/ \/ \/ \/ \/ \/[\/]\/RE \ | / \/ \/ \/ \ | | h A S D E F G H J K L TURN| | |1 2 3||E| | \S/\L/\ /\ /\ /\ /\ /\ /\ /\ /\ /\ /\:/\;/\ / | \ /\ /\ /|N| | | |T| | /C\/SH\/ \/ \/ \/ \/ \/ \/ \/<\/>\/?\/SHI\/C\/C\ | / \/ \|E| | |= IF Z X C V B N M FT ||u||l| | | 0 .||R| | \ /\T /\ /\ /\ /\ /\ /\ /\ /\,/\./\//\ /\d/\r/ | \ /\ /\ / | | | [ spacebar ] | +--------------------------------------------------+ C L = {caps lock} Hlp = {help} L F = {line feed} 4 8 = {40/80 dsp} N S = {no scroll} up = {crsr up} dwn = {crsr down} lft = {crsr left} rgt = {crsr right} L A = {left arrow} lbs = {pound} C H = {clr/home} I D = {inst/del} contrl = {ctrl} U A = {up arrow} R S = {run/stop} ShL = {shift lock} C= = {commodore} Cud = {crsr up/down} Clr = {crsr left/right} Note: Outlined key areas can be used in C64 Mode. Using BASIC is essentially the same in both C64 and C128 modes. Most of the keys, and many of the commands you will learn, can be used to program BASIC in either mode. The keys that are shaded in the diagram above can be used in C64 mode. In C128 mode you can use all of the keys on the keyboard. 3.2.1 Keyboard Character Sets The Commodore 128 keyboard offers two different sets of characters: - Uppercase letters and graphic characters - Upper- and lowercase letters In 80-column format, both character sets are available simultaneously. This gives you a total of 512 different characters that you can display on the screen. In 40-column format you can use only one character set at a time. When you turn on the Commodore 128 in 40-column format, the keyboard nor- mally is using the uppercase/graphic character set. This means that every- thing you type is in capital letters. To switch back and forth between the two character sets, press the {shift} key and the {C=} key (the COMMODORE key) at the same time. To practice using the two character sets turn on your computer and press several letters or graphic characters. Then press the {shift} key and the {C=}(Commodore) key. Notice how the screen changes to upper- and lowercase characters. Press {shift} and {C=} again to return to the uppercase and graphic character set. 3.2.2 Using the Command Keys COMMAND keys are keys that send messages to the computer. Some command keys (such as {return}) are used by themselves. Other keys such as {shift}, {ctrl}, {C=} and {restore}) are used with other keys. The use of each of the command keys is explained below. The keys used in C128 mode are des- cribed in Section 5. 3.2.2.1 Return When you press the {return} key, what you have typed is sent to the Commo- dore 128 computer's memory. Pressing the {return} key also moves the cursor (the small flashing rectangle that marks where the next character you type will appear) to the next line. At times you may misspell a command or type in something the computer does not understand. Then, when you press the {return} key, you probably will get a message like SYNTAX ERROR on the screen. This is called an "Error Message". Appendix A lists the error messages and tells how to correct the errors. 3.2.2.2 Shift There are two {shift} keys on the bottom row of the keyboard. One key is the one on the left and the other on the right, just as on a standard type- writer keyboard. The {shift} key can be used in three ways: 1. With the upper/lowercase character set, the {shift} key is used like the shift key on a regular typewriter. When the {shift} key is hold down, it lets you print capital letters or the top characters on double-character keys. 2. The {shift} key can be used with some of the other command keys to per- form special functions. 3. When the keyboard is set for the uppercase/graphic character set, you can use the {shift} key to print the graphic symbols or characters that appear on the right of the front face of certain keys. See paragraph 3.2.4 at the end of this section for more details. 3.2.2.3 Shift Lock When you press this key down, it locks into place. Then, whatever you type will either be a capital letter, or the top character of a double-character key. To release the lock, press down on the {shift lock} key again. 3.2.2.4 Moving the cursor In C128 mode, you can move the cursor by using either the four arrow keys located just above the top right of the main keyboard, or the two keys labeled {crsr}, at the right of the bottom row of the main keyboard. 3.2.2.4.1 Using the four Arrow Cursor keys In C128 mode, the cursor can be moved in any direction simply by using the arrow key in the top row that points in the direction you want to move the cursor. (These keys cannot be used in C64 mode). 3.2.2.4.2 Using the CRSR keys In both C128 and C64 mode, you can use the two keys on the right side of the bottom row of the main keyboard to move the cursor: - Pressing the {crsr up/down} key alone moves the cursor down. - Pressing the {crsr up/down} and {shift} keys together moves the cursor up. - Pressing the {crsr left/right} key alone moves the cursor right. - Pressing the {crsr left/right} and {shift} keys together moves the cursor left. You don't have to keep tapping a cursor key to move more than one space. Just hold the key down and the cursor continues to move, release it when it reaches the position you want. Notice that when the cursor reaches the right side of the screen, it "wraps", or starts again at the beginning of the next row. When moving left, the cursor will move along until it reaches the edge of the screen, then it will jump up to the end of the preceding line. You should try to become very familiar with the cursor keys, because moving the cursor makes your programming much easier. With a little practice you will find that you can move the cursor almost without thinking about it. 3.2.2.5 Inst/Del This is a dual purpose key. INST stands for INSerT, and DEL for DELete. 3.2.2.5.1 Inserting Characters You must use the {shift} key with the {inst/del} key when you want to insert characters in a line. Suppose you left some characters out of a line like this: WHILE WERE OUT_ To insert the missing characters, first use the cursor keys to move the cursor back to the error. like this: WHILE_WERE OUT Then, while you hold down the {shift} key, press the {inst/del} key until you have enough space to add the missing characters: WHILE_ WERE OUT Notice that {inst} doesn't move the cursor; it just adds space between the cursor and the character to its right. To make the correction type the mis- sing {space}, {y}, {o} and {u} like this: WHILE YOU_WERE OUT 3.2.2.5.2 Deleting characters When you press the {del} key, the cursor move one space to the left and erases the character that is there and moves any characters to the right of the cursor one position to the left. This means that when you want to delete something, you move the cursor just to the right of the character you want to DELete. Suppose you have made a mistake in typing, like this: PRINT "ERROER"_ You wanted to type the word ERROR, not ERROER. To delete the incorrect E that precedes the final R, position the cursor on the final R. When you press the {del} key, the R automatically moves over one space to the left. You now have the correct wording like this: PRINT "ERROR" 3.2.2.5.3 Using INSerT and DELete together You can use the INSerT and DELete functions together to fix incorrect characters. First, move the cursor one space after the incorrect characters and press the {inst/del} key by itself to delete the incorrect characters. Next, press the {shift} key and the {inst/del} key together to add any necessary space. 3.2.2.6 Control The {ctrl} key is used with other keys to do special task called control functions. To perform a control function, hold down the {ctrl} key while you press some other key. A full list of control sequences is given in ASCII, CHR$ and ESC codes. Control functions are often used in prepackaged software such as a word processing system. One control function that is used often is setting the character and cursor color. To select a color, hold down the {ctrl} key while you press a number key ({1} throught {8}), on the top row of the main keyboard. There are eight more colors available to you; these can be selected with the {C=} key, as explained later. 3.2.2.7 Run/Stop This is a dual function key. Under certain conditions you can use the RUN function of this key by pressing the {shift} and {run/stop} key together. It is also possible to use the STOP function of the key to halt a program or a printout by pressing this key while the program is running. However, in most prepackaged programs, the STOP function of the {run/stop} key is intentionally disabled (made unusable). This is done to prevent the user from trying to stop a program that is running before it reaches its normal end point. If the user were able to stop the program, valuable data could be lost. 3.2.2.8 Restore The {restore} key is used with the {run/stop} key to return the computer to its standard condition. Most prepackaged programs disable the {restore} key for the same reason the disable the STOP function of the {run/stop} key: to prevent losing valuable data. 3.2.2.9 CLR/Home CLR stands for CLeaR. HOME refers to the upper left corner of the screen, which is called the HOME position. If you press this by itself the cursor returns to the HOME position. When you use the {shift} key with the {clr/home} key, the screen CLeaRs and the cursor returns to the HOME position. 3.2.2.10 Commodore key The {C=} key (known as the {commodore} key) has a number of functions, including the following ones: 1. When used with the {shift} key, the {C=} key lets you switch between uppercase/graphics mode and upper-/lowercase text modes. 2. When you're in either mode, the {C=} key acts as a shift to let you type graphics symbols pictured on the LEFT front of each key. Just hold down the {C=} and press teh graphic key you want. 3. When you want to change the color you are typing in to one of the 8 colors listed on the BOTTOM row of the face of the color keys (number keys {1} through {8} on the main keyboard): press {C=} and the color you want. 4. When you want to slow down a scrolling program display, hold down the {C=} key. The display scrolling speed slows down considerably. When you release this key, the screen scrolling resumes at normal speed. 5. If you hold down the {C=} key while turning on the computer, you immediately access C64 mode. 3.2.3 Function Keys The four keys above the numeric keypad (marked F1, F3, F5 and F7 on the top and F2, F4, F6 and F8 on the front) are called function keys. In both C128 and C64 modes, you can program the function keys. (See the KEY command des- criptions in Section 5, paragraph 5.9.2 of Chapter II and in Section 17, paragraph 17.53 of Chapter V, BASIC 7.0 Encyclopaedia). These keys are often used by prepackaged software to allow you to perform a task with a single keystroke. 3.2.4 Displaying Graphic Characters To display the graphic symbol on the right front of a key, hold down the {shift} key while you press the key that has the graphic character you want to print. You can display the right side graphic character only when the keyboard is in the uppercase/graphics character set (one normal character set usually available at power-up). To display the graphic character on the left front face of a key, hold down the {C=} key while you press the key that has the graphic character you want. You can display the left graphic character while the keyboard is in either character set. 3.2.5 Rules for Typing BASIC Language Programs You can type and use BASIC language programs even without knowing BASIC. You must type carefully, however, because a typing error may cause the computer to reject your information. The following guidelines will help minimize errors when typing or copying a program listing. 1. Spacing between words is not critical; e.g. typing FORT=1TO10 is the same as typing FORT=1 TO 10. However, a BASIC keyword itself must not be broken up by spaces (see Section 20, paragraph 20.1, of the BASIC 7.0 Encyclopaedia in Chapter V for a list of BASIC keywords). 2. Any characters can be typed inside quotation marks. Some characters have special functions when placed inside quotation marks, These functions are explained later in this guide. 3. Be careful with punctuation marks. Commas, colons and semicolons also have special properties, explained later in this guide. 4. Always press the {return} key after completing a numbered line. 5. Never type more than 160 characters in a program line. Remember, this is the same as four full screen lines in 40-column format, or two full screen lines in 80-column format. See Section 8 for more details on 40- and 80-columns formats. 6. Distinguish clearly between the letter {l} and the numeral {1} and between the capital letter {O} and the numeral {0} (zero). 7. The computer ignores anything following the letters REM on a program line. REM stands for REMark. You can use the REM statement to put com- ments in you program that tell anyone listing the program what is happe- ning at a specific point. Follow these guidelines when you type the examples and programs shown in this section. 3.3 GETTING STARTED - THE PRINT COMMAND The PRINT command tells the computer to display information on the screen. You can print both numbers and text (letters), but there are special rules for each case, described in the following paragraphs. 3.3.1 Printing Numbers To print numbers, use the PRINT command followed by the number(s) you want to print. Try typing this on you Commodore 128: PRINT 5 Then press the {return} key. Notice the number 5 is now displayed on the screen. Now type this and press {return}: PRINT 5,6 In this PRINT command, the comma tells the Commodore 128 that you want to print more than one number. When the computer finds commas in a string of numbers in a PRINT statement, the output is displayed to the nearest tenth column. If you don't want all the extra spaces, use a semicolon (;) in your PRINT statement instead of a comma. The semicolon tells the computer to print the numbers next to each other. A number when printed has either a space or a minus sign preceding it and a skip character after it. Type these examples and see what happens: PRINT 5;6 {return} PRINT 100;-200;300;-400;500 {return} 3.3.2 Using the Question Mark to Abbreviate the PRINT Command You can use a quotation mark (?) as an abbreviation for the PRINT command. Many of the examples in this section use the ? symbol in place of the word PRINT. In fact, most of the BASIC commands can be abbreviated. The abbreviations for BASIC commands can be found in Appendix K of this Guide. 3.3.3 Printing Text Now that you know how to print numbers, it's time to learn how to print text. It's actually very simple. Any words or characters you want to dis- play are typed on the screen, with a quote symbol at each end of the string of characters. String is the BASIC name for any set of characters sur- rounded by quotes. The quote character is obtained by pressing "SHIFT" and the number {2} key on top of the main keyboard (not the {2} in the numeric keypad). Try these examples: ? "COMMODORE 128" {return} ? "4*5" {return} Notice that when you press {return}, the computer displays the character within the quotes on the screen. Also note that the second example did not calculate 4*5 since it was treated as a string and not a mathematical cal- culation. If you want to calculate the result of 4*5, use the following com- mand: ? 4*5 {return} You can PRINT any string you want by using the PRINT command and surroun- ding the printed characters with quotes. You can combine text and calcula- tions in a single PRINT command like this: ? "4*5 = "4*5 {return} See how the computer PRINTs the characters in quotes, makes the calculation and PRINTs the result. It doesn't matter whether the text or calculation comes first. In fact, you can use both several times in one PRINT command. Type the following statement: ? 4*(2+3)" is the same as "4*5 {return} Notice that even spaces inside the quotation marks are printed on the screen. Type: ? " OVER HERE" {return} 3.3.4 Printing in Different Colors The Commodore 128 is capable of displaying 16 different colors on the screen. You can change colors easily. All you do is hold down the {ctrl} key and press a numbered key between one and eight on the top row of the main keyboard. Notice that the cursor changes color according to the num- bered key you pressed. All the succeeding characters are displayed in the color you selected. Hold down the {C=} key and press a numbered key between one and eight, and eight additional colors are displayed on the screen. Table 3-1 list the colors available in C128 mode, for both 40-column and 80-column screen formats. The tables also show the key sequence (CONTROL key plus number key, or {C=} key plus number key) used to specify a given color. Table 3-1. Available Colors in 40- and 80-Column Screen Formats. CONTROL + Color {C=} + Color 1 Black 1 Orange 2 White 2 Brown 3 Red 3 Light Red 4 Cyan 4 Dark Grey 5 Purple 5 Middle Grey 6 Green 6 Light Green 7 Blue 7 Light Blue 8 Yellow 8 Light Grey Colors in 40-Column Format CONTROL + Color {C=} + Color 1 Black 1 Dark Purple 2 White 2 Brown 3 Dark Red 3 Light Red 4 Light Cyan 4 Dark Cyan 5 Light Purple 5 Middle Grey 6 Dark Green 6 Light Green 7 Dark Blue 7 Light Blue 8 Light Yellow 8 Light Grey Colors in 80-Column Format 3.3.5 Using the Cursor Keys Inside Quotes with the PRINT Command When you type the cursor keys inside quotation marks, graphic characters are shown on the screen to represent the keys. These characters will NOT be printed on the screen when you press {return}. Try typing a question mark ({?}), open quotes ({shift}ed {2} key); then press either of the down cursor keys 10 times, enter the words "DOWN HERE", and close the quotes. The line should look like this: ?"QQQQQQQQQQDOWN HERE" Now press {return}. The Commodore 128 prints 10 blank lines, and on the eleventh line, it prints "DOWN HERE". As this example shows, you can tell the computer to print anywhere on your screen by using the cursor control keys inside quotation marks. 3.4 BEGINNING TO PROGRAM So far most of the commands we have discussed have been performed in DIRECT mode. That is, the command was executed as soon as the {return} key was pressed. However, most BASIC commands and functions can also be used in programs. 3.4.1 What a Program Is A program is just a set of numbered BASIC instructions that tell your com- puter what you want it to do. These numbered instructions are referred to as statements or lines. 3.4.2 Line Numbers The lines of a progam are numbered so that the computer knows in what order yo want them executed or RUN. The computer executes the program lines in numerical order, unless the program instructs otherwise. You can use any whole number from 0 to 63999 for a line number. Never use a comma in a line number. Many of the commands you have learned to use in DIRECT mode can easily be made into program statements. For example, type this: 10 ?"COMMODORE 128" {return} Notice the computer did not display COMMODORE 128 when you pressed {return}, as it would do if you were using the PRINT command in DIRECT mode. This is because the number, 10, that comes before the PRINT symbol (?) tells the computer that you are entering a BASIC program. The computer just stores the numbered statement and waits for the next input from you. Now type RUN and press {return}. The computer prints the words COMMODORE 128. This not the same as using the PRINT command in DIRECT mode. What has happened here is that YOU HAVE WRITTEN AND RUN YOUR FIRST BASIC PROGRAM as small as it may seem. The program is still in the computer's memory, so you can run it as many times as you want. 3.4.3 Viewing your Program - The LIST Command Your one-line program is still in the C128 memory. Now clear the screen by pressing the {shift} and {clr/home} keys together. The screen is empty. At this point you may want to see the program listing to be sure it is still in memory. The BASIC language is equipped with a command that lets you do just this - the LIST command. Type LIST and press {return}. The Commodore 128 responds with: 10 PRINT "COMMODORE 128" READY. Anytime you want to see all the lines in your program, type LIST. This is especially helpful if you make changes, because you can check to be sure the new lines have been registered in the computer's memory. In response to the command, the computer displays the changed version of the line, lines, or program. Here are the rules for using the LIST command: - To see line n only, type LIST n and press {return}. - To see from line n to the end of the program, type LIST n- and press {return}. - To see the lines from the beginning of the program to line n, type LIST -n and press {return}. - To see from line n1 to line n2 inclusive, type LIST n1-n2 and press {return}. 3.4.4 A Simple Loop - The GOTO Command The line numbers in a program have another purpose besides putting your commands in the proper order for the computer. The serve as a reference for the computer in case you want to execute the command in that line repeti- tively in your program. You use the GOTO command to tell the computer to go to a line and execute the command(s) in it. Now type: 20 GOTO 10 When you press {return} after typing line 20, you add it to your program in the computer's memory. Notice that we numbered the first line 10 and the second line 20. It is very helpful to number program lines in increments of 10 (that is 10, 20, 30, 40, etc.) in case you want to go back and add lines in between. You can number such added lines by fives (15, 25...), or ones (1, 2...) - in fact, by any whole number - to keep the lines in proper order. (See the RENUMBER and AUTO commands in the BASIC Encyclopaedia, paragraphs.) Type RUN and press {return}, and watch the words COMMODORE 128 move down your screen. To stop the message from printing on the screen, press the {run/stop} key on the left side of the main keyboard. The two lines that you have typed make up a simple program that repeats it- self endlessly, because the second line keeps referring the computer back to the first line. The program will continue indefinitely unless you stop it or turn off the computer. Now type LIST {return} The screen should say: 10 PRINT "COMMODORE 128" 20 GOTO 10 READY. Your program is still in memory. You can RUN it again if you want to. This is an important difference between PROGRAM mode and DIRECT mode. Once a command is executed in DIRECT mode, it is no longer in the computer's memory. Notice that even though you used the ? symbol for the PRINT state- ment, your computer has converted it into the full command. This happens when you LIST any command you have abbreviated in a program. 3.4.5 Clearing the Computer's Memory - The NEW Command Anytime you want to start all over again or erase a BASIC program in the computer's memory, just type NEW and press {return}. This command clears out the computer's BASIC memory, the area where programs are stored. 3.4.6 Using Color in a Program To select color within a program, you must include the color selection information within a PRINT statement. For example, clear your computer's memory by typing NEW and pressing {return}, the type the following, being sure to leave space between each letter: 10 PRINT " R A I N B O W" {return} Now type line 10 again, but this time hold down the {ctrl} key and press the (numeral) {1} key directly after entering the first set of quote marks. Release the {ctrl} key and type the {r}. Now hold down the {ctrl} again and press the {2} key. Release the {ctrl} key and type the {a}. Next hold down the {ctrl} again and press the {3} key. Continue this process until you have typed all the letters in the word RAINBOW and selected a color between each letter. Press the {shift} and the {2} keys to type a set of the clo- sing quotation marks and press the {return} key. Now type RUN and press the {return} key. The computer displays the word RAINBOW with each letter in a different color. Now type LIST and press the {return} key. Notice the graphic characters that appear in the PRINT statement in line 10. These characters tells the computer what color you want for each printed letter. Note that these graphic characters do not appear when the Commodore 128 PRINTs the word RAINBOW in different colors. The color selection characters, known as control characters, in the PRINT statement in line 10 tell the Commodore 128 to change colors. The computer then prints the characters that follow in the new color until another color selection character is encountered. While characters enclosed in quotation marks are usually PRINTed exactly as they appear, control characters are only displayed within a program LISTing. 3.5 EDITING YOUR PROGRAM The following paragraphs will help you to type in your programs and make corrections and additions to them. 3.5.1 Erasing a Line from a Program Use the LIST command to display the program you typed previously. Now type 10 and press {return}. You just erased line 10 from the program. LIST your program and see for yourself. If the old line 10 is still on the screen, move the cursor up so that it is blinking anywhere on that line. Now, if you press {return}, line 10 is back in the computer's memory. 3.5.2 Duplicating a Line Hold down the {shift} key and press the {clr/home} key on the upper right side of the main keyboard. This will clear your screen. Now LIST the pro- gram. Move the cursor up again so that it is blinking in the (numeral) "0" in the line numbered 10. Now type a {5} and press {return}. You have just duplicated (i.e. copied) line 10. The duplicated line is numbered 15. Type LIST and press RETURN to see the program with the duplicated line. 3.5.3 Replacing a Line You can replace a whole line by typing in the old line number followed by the text of the new line, the pressing {return}. The old version of the line will be erased from memory and replaced by the new line as soon as you press {return}. 3.5.4 Changing a Line Suppose you want to add something in the middle of a line. Simply move the cursor to the character or space that immediately follows the spot where you want to insert the new material. Then hold down the {shift} key and the {inst/del} key together until there is enough space to insert your new characters. Try this example. Clear the computer's memory by typing NEW and pressing {return}. The type: 10 ? "MY 128 IS GREAT" {return} Let's say you want to add the word COMMODORE in front of the number 128. Just move the cursor so that it is blinking on the "1" in 128. Hold down the {shift} and {inst/del} keys until you have enough room to type in COMMODORE (don't forget to leave enough room for a space after the last letter "E"). Then type in the word COMMODORE. 3.6 MATHEMATICAL OPERATIONS You can use the PRINT command to perform calculations like addition, sub- traction, multiplication, division and exponentiation. You type the calcu- lation after the PRINT command. 3.6.1 Addition and Subtraction Try typing these examples: PRINT 6 + 4 {return} PRINT 50 - 20 {return} PRINT 10 + 15 - 5 {return} PRINT 75 - 100 {return} PRINT 30 + 40,55 - 25 {return} PRINT 30 + 40;55 - 25 {return} Notice that the fourth calculation (75-100) resulted in a negative number. Also notice that you can tell the computer to make more than one calcula- tion with a single PRINT command. You can use either a comma or semicolon in your command, depending on whether or not you want your results printed tabulated or next to each other. 3.6.2 Multiplication and Division Find the asterisk key (*) on the right side of the main keyboard. This is the symbol that the Commodore 128 uses for multiplication. The slash (/) key, located next to the right {shift} key, is used for division. Try these examples: PRINT 5*3 {return} PRINT 100/2 {return} 3.6.3 Exponentiation Exponentiation means to raise a number to a power. The up arrow key ({up arrow}, located next to the asterisk on the main keyboard, is used for exponentiation. If you want to raise a number to a power, use the PRINT command, followed by the number, the up arrow and the power, in that order. For example, to find out what 3 squared is, type: PRINT 3{up arrow}2 {return} NOTE: From now on, the {up arrow} keystroke is represented by the {^} key- stroke, or simply ^. 3.6.4 Order of Operations You have seen how you can combine addition and subtraction in the same PRINT command. If you combine multiplication or division with addition or subtraction operations, you may not get the result you expect. For example, type: PRINT 4 + 6/2 {return} If you assumed you were dividing 10 by 2, you were probably surprised when the computer responded with the answer 7. The reason you got this answer is that multiplication and division operations are performed by the computer before addition or subtraction. Multiplication and division are said to take precedence over addition and subtraction. It doesn't matter in what order you type the operation. In computing, the order in which mathematical operations are performed is known as the order of operations. Exponentiation, or raising a number to a power, takes precedence over the other four mathematical operations. For example, if you type: PRINT 16/4^2 {return} the Commodore 128 responds with 1, because it squares the 4 before it divides 16. 3.6.5 Using Parentheses to Define the Order of Operations You can tell the Commodore 128 which mathematical operation you want per- formed first by enclosing that operation in parentheses in the PRINT command. For instance, in the first example above, if you want to tell the computer to add before dividing, type: PRINT (4 + 6)/2 {return} This gives you the desired answer, 5. If you want the computer to divide before squaring in the second example, type: PRINT (16/4)^2 {return} Now you have the expected answer, 16. If you don't use parentheses, the computer performs the calculations accor- ding to the above rules. When all operations in a calculation have equal precedence, they are performed from left to right. For example, type: PRINT 4*5/10*6 {return} Since the operations in this example are performed in order from left to right, the result is 12 (4*5 = 20... 20/10 = 2... 2*6 = 12). If you want to divide 4*5 by 10*6 you type: PRINT (4*5)/(10*6) {return} The answer is now .333333333. 3.7 CONSTANTS, VARIABLES AND STRINGS 3.7.1 Constants Constants are numeric values that are permanent: that is, they do not change in value over the course of an equation or program. For example, the number 3 is a constant, as is any number. This statement illustrates how your program uses constants: 10 PRINT 3 No matter how many times you execute this line, the answer will always be 3. 3.7.2 Variables Variables are values that can change over the course of an equation or program statement. There is a part of the computer's BASIC memory that is reserved for the characters (number, letters and symbols) you use in your program. Think of this memory as a number of storage compartments in the computer that store information about your program; this part of the com- puter's memory is referred to as variable storage. Type in this program: 10 X=5 20 ?X Now RUN the program and see how the computer prints a 5 on your screen. You told the computer in line 10 that the letter X will represent the number 5 for the remaninder of the program. The letter X is called a variable, be- cause the value of X varies depending on the value to the right of the equals sign. We call this an assignment statement because now there is a storage compartment labeled X in the computer's memory, and the number 5 has been assigned to it. The = sign tells the computer that whatever comes to the right of it will be assigned to a storage compartment (a memory location) labeled with the letter X to the left of the equals sign. The variable name on the left side of the = sign can be either one or two letters, or one letter and one number (the letter MUST come first). The names can be longer, but the computer only looks at the first two charac- ters. This means the names PA and PART would refer to the same storage compartment. Also, the words used for BASIC commands (LOAD, RUN, LIST, etc.) or functions (INT, ABS, SQR, etc.) cannot be used as names in your programs. Refer to the BASIC Encyclopaedia in Chapter V if you have any questions about whether a variable name is a BASIC keyword. Notice that the = in assigment statements is not the same as the mathematical symbol meaning "equals", but rather means allocate a variable (storage compart- ment) and assign a value to it. In the sample program you just typed, the value of the variable X remains at 5 throughout. You can put calculations to the right of the = sign to assign the result to a variable. You can mix text with constants in a PRINT statement to identify them. Type NEW and press {return} to clear the Commo- dore 128's memory; then try this program: 10 A = 3*100 20 B = 3*200 30 ?"A IS EQUAL TO"A 40 ?"B IS EQUAL TO"B Now there are two variables, labeled A and B, in the computer's memory, containing the numbers 300 and 600 respectively. If, later in the program, you want to change the value of a variable, just put another assignment statement in the program. Add these lines to the program above and RUN it again. 50 A = 900*30/10 60 B = 95 + 32 + 128 70 GOTO 30 You'll have to press the {stop} key to halt the program. Now LIST the program and trace the steps taken by the computer. First, it assigns the value to the right of the = sign in line 10 to the letter A. It does the same thing in line 20 for the letter B. Next, it prints the messa- ges in lines 30 and 40 that give you the values of A and B. Finally, it assigns new values to A and B in lines 50 and 60. The old values are repla- ced and cannot be recovered unless the computer executes lines 10 and 20 again. When the computer is sent to line 30 to begin printing the values of A and B again, it prints the new values calculated in lines 50 and 60. Lines 50 and 60 reassign the same values to A and B and line 70 sends the computer back to line 30. This is called an endless loop, because lines 30 through 70 are executed over and over again until you press the {run/stop} key to halt the program. Other methods of looping are discussed later in this and following two sections. 3.7.3 Strings A string is a character or group of characters enclosed in quotes. These characters are stored in the computer's memory as a variable in much the same way numeric variables are stored. You can also use variable names to represent strings, just as you use them to represent numbers. When you put the dollar sign ($) after the variable name, it tells the computer that the name is for a string variable, and not a numeric variable. Type NEW and press {return} to clear your computer's memory, then type in the program below: 10 A$ = "COMMODORE" 20 X = 128 30 B$ = "COMPUTER" 40 Y = 1 50 ? "THE "A$;X;B$" IS NUMBER"Y See how you can print numeric and string variables in the same statement? Try experimenting with variables in your own short programs. You can print the value of a variable in DIRECT mode, after the program has been RUN. Type ?A$;B$;X;Y {return} after running the program above and see that those four variable values are still in the computer's memory. If you want to clear this area of BASIC memory but still leave your program intact, use the CLR command. Just type CLR {return} and all constants, variables and strings are erased. But when you type LIST, you can see the program is still in memory. The NEW command discussed earlier erases both the program and the variables. 3.8 SAMPLE PROGRAM Here is a sample program incorporating many of the techniques and commands discussed in the section. This program calculates the avarage of three numbers (X, Y and Z) and prints their values and their avarages on the screen. You can edit the pro- gram and change the calculations in line 10 through 30 to change the values of the variables. Line 40 adds the variables and divides them by 3 to get the average. Note the use of parentheses to tell the computer to add the numbers before it divides. TIP: Whenever you are using more than one set of parentheses in a statement, it's a good idea to count the number of left parentheses and right parentheses to make sure they are equal. 10 X = 46 20 Y = 73 30 Z = 114 40 A = (X + Y + Z)/3 50 ?"THE AVERAGE OF"X;Y;"AND"Z;"IS"A; 60 END 3.9 STORING AND REUSING YOUR PROGRAMS Once you have created your program, you will probably want to store it permanently so you will be able to recall and use it at some later time. To do this, you'll need either a Commodore disk drive or the Commodore 1530 (or 1531) Datassette, or similar storing device. You will learn several commands that let you communicate between your com- puter and your disk drive or Datassette. These commands are structured with the use of a command word followed by several parameters. Parameters are letters, words or symbols in a command that supply specific information to the computer, such as a filename, or a numeric variable that specifies a device number. Each command may have several parameters. For example, the parameter of the disk format command include a name for the disk and an identifying number or code, plus several other parameters. Parameters are used in almost every BASIC command; some are variables which change and others are constant. These are the parameters that supply disk information to the C128 and the disk drive: 3.9.0.1 Disk Handling Parameters disk name - arbitrary 16 character identifying name you supply. filename - arbitrary 16 character identifying name you supply. i.d. number - arbitrary two-character identifying code you supply. drive number - must use 0 for a single disk drive, 0 or 1 in a dual disk drive. device number - a preassigned number for a peripheral device. For example, the device number for a Commodore disk drive is 8. 3.9.1 Formatting a Disk - The HEADER Command To store programs on a new (or blank) disk, you must first prepare the disk to receive data. This is called "formatting" the disk. NOTE: Make sure you turn on the disk drive before inserting any disk. The formatting process divides the disk into sections called tracks and sectors. A table of contents, called a directory, is created. Each time you store a program on disk, the name you assign to that program will be added to the directory. The Commodore 128 has two kinds of formatting commands. One can be used in C128 mode only, and one can be used in both C64 and C128 mode. The follo- wing describes the C128 mode formatting command only. See your disk drive manual for the disk handling in C64 mode. The command that formats a diskette is called the HEADER command. It has a long form and a short form. To format a blank (new) disk, you MUST use the long form as follows: HEADER "diskname", Ii.d. [,Ddrive number] [,[ON]Udevice number] After the word HEADER, you type a name of your choice for the disk, within quotes. You can choose any name with up to 16 characters. You should choose disk names that help you identify what will be stored on the disk. Follow the diskname with a comma and the letter "I". Now a two character i.d. Your disk i.d. does not have to be numbers; you can also choose let- ters. You may want to develop a consecutive coding system for your disk, such as A1, A2, B1, B2. If you have one single disk drive, just press {return} at this point since the Commodore 128 automatically assumes the drive number is 0 and the device number is 8. You can specify these parameters if you have more than one drive or a dual drive. The next parameter in the command selects the drive number. Press the {d} key and if you have a single disk drive, press the {zero} key followed by a {comma}. Dual drives are labeled 0 and 1. The device number parameter starts with the letter U so press the {u} key followed by the preassigned device number for a Commodore disk drive which is {8}. Here is an example of the long form of the HEADER command: HEADER"RECS",IA1,D0,U8 {return} This command formats the diskette, calling it "RECS", the i.d. number "A1", on drive 0, unit 8. The default values for disk drive (0) and device number (8) will be used if none are supplied. This is an acceptable long form of the HEADER command: HEADER "MYDISK",I51 {return} The HEADER command can also be used to erase all data from a used disk, so the disk can be reused as if it were a brand new disk. Be careful that you don't erase a disk that contains data you may want someday. The quick form of the HEADER command can be used if the disk was previously formatted with the long form of the HEADER command. The quick form clears the directory, erasing all data in the same way as the long form, but keeps the same i.d. as was previously used. Here is what the quick HEADER might look like: HEADER "NEWPROGS" {return} 3.9.2 SAVEing on Disk In C128 mode, you can store you program on disk by using either of the following commands: DSAVE "program name" {return} SAVE "program name",8 {return} Either command can be used. Remember that the character sequence DSAVE" can be displayed on the screen by pressing the function key labeled {f5}, or you can type the sequence yourself. The progam name can be any name you choose, up to 16 characters long. Be sure to enclose the program name in quotes. You cannot put two programs with the same name on the same disk. If you do, the second program will not be accepted; the disk will retain the first one. In the second example, the 8 indicates that you are saving your program on device number 8. You do not need the 8 with DSAVE, because the computer automatically assumes you are using device number 8. 3.9.3 SAVEing on Cassette If you are using a Datassette to store your program, insert a blank tape in the recorder, rewind the tape if necessary, and type: SAVE "program name" {return} You must type the word SAVE, followed by the program name. The program name can be any name you choose up to 16 characters. NOTE: The 40-column screen will go blank while the program is being SAVEd, but returns to normal when the process is completed. Unlike disk, you can save two programs to tape under the same name. However when you load it back into the computer, the first progam sequentially on the tape will be loaded, so avoid giving programs the same name. Once a program has been SAVEd, you can LOAD it back into the computer's memory and RUN it anytime you wish. 3.9.4 LOADing from Disk Loading a program simply copies the contents of the program from the disk into the computer's memory. If a BASIC program was already in memory before you issued the LOAD command, it is erased. To load your BASIC program from a disk, use either ot the following com- mands in C128 mode: DLOAD "program name" {return} LOAD "program name",8 {return} Remember, in C128 mode you can use the {f2} function key (which you acti- vate by pressing {shift} and {f1} together) to display the sequence DLOAD", or you can type the letters yourself. In the second example, the 8 indi- cates to the computer that you are loading from device number 8. Again, like DSAVE, DLOAD assumes the disk drive device number is 8. Be careful to type the program name exactly as you typed it when SAVEing the program, or the computer will respond FILE NOT FOUND. Once the program is loaded, type RUN to execute. The Commodore 128 has a special form of the RUN command used to LOAD and RUN the program in C128 mode with one command. Type RUN, followed by the name of the program (also known as the filename) in quotes: RUN"MYPROG" {return} 3.9.5 LOADing from Cassette Tape To LOAD your program from cassette tape, type: LOAD "program name" {return} If you do not know the name of the program, you can type: LOAD {return} and the next program on tape will be found. While the Datassette is sear- ching for the program the 40 column screen is blank. When the program is found, the screen displays: FOUND PROGRAM NAME To actually load the program, you then press the Commodore key, or in 128 mode press the space bar to find the next program on tape. You can use the counter on the Datassette to identify the starting position of the programs. Then, when you want to retrieve a program, simple wind the tape forward from 000 to the program's start location, and type: LOAD {return} In this case you don't have to specify the program name; your program will load automatically because it is the next program on the tape. 3.9.6 Other Disk-Related Commands 3.9.6.1 Verifying a Program To verify that a program has been correctly saved, use the following com- mand in C128 mode: DVERIFY "program name" {return} If the program in the computer is identical to the one on the disk, the screen display will respond with the letters "OK". The VERIFY command also works for tape programs. You type: VERIFY "program name" {return} You do not enter the comma and a device number. 3.9.6.2 Displaying Your Disk Directory In C128 mode, you can see a list or directory of the programs on your disk by using the following command: DIRECTORY {return} This lists the contents of the directory. The easy way is to press the {f3} function key. When you press {f3}, the C128 displays the word DIRECTORY and performs the command. For further information on SAVEing and LOADing your programs, or other disk related information refer to your Datassette or disk drive manual. Also consult the LOAD and SAVE command descriptions in the Chapter V, BASIC 7.0 Encyclopaedia. ********** You now know something about the BASIC language and some elementary pro- gramming concepts. The next section builds on these concepts, introducing additional commands, functions and techniques that you can use to program in BASIC. SECTION 4 4. Advanced Basic Programming 4.1 COMPUTER DECISIONS - The IF-THEN Statement 4.1.1 Using the Colon 4.2 LOOPS - The FOR-NEXT Command 4.2.1 Empty Loops - Inserting Delays in a Program 4.2.2 The STEP Command 4.3 INPUTTING DATA 4.3.1 The INPUT Command 4.3.1.1 Assigning a value to a variable 4.3.1.2 Prompt Messages 4.3.2 The GET Command 4.3.3 Sample Program 4.3.4 The READ-DATA Commands 4.3.5 The RESTORE Command 4.3.5.1 Assigning values to string variables 4.3.6 Using Arrays 4.3.6.1 Subscripted Variables 4.3.6.2 Dimensioning Arrays 4.3.6.3 Sample Program 4.4 PROGRAMMING SUBROUTINES 4.4.1 The GOSUB-RETURN Commands 4.4.2 The ON GOTO/GOSUB Commands 4.5 USING MEMORY LOCATION 4.5.1 Using PEEK and POKE for RAM Access 4.5.1.1 Using PEEK 4.5.1.2 Using POKE 4.6 BASIC FUNCTIONS 4.6.1 What is a Function? 4.6.2 The INTEGER Function (INT) 4.6.3 Generating Random Numbers - The RND Function 4.6.4 The ASC and CHR$ Functions 4.6.5 Converting Strings and Numbers 4.6.5.1 The VAL Function 4.6.5.2 The STR$ Function 4.6.6 The Square Root Function (SQR) 4.6.7 The Absolute Value Function (ABS) 4.7 THE STOP AND CONT (CONTINUE) COMMANDS This section describes how to use a number of powerful BASIC commands, functions and programming techniques that can be used in both C128 and C64 modes. These commands and functions allow you to program repeated actions through looping and nesting techniques; handle tables of values; branch or jump to another section of a program, and return from that section; assign varying values to a quantity - and more. Examples and sample programs show just how these BASIC concepts work and interact. 4.1 COMPUTER DECISIONS - The IF-THEN Statement Now you know how to change the values of variables, the next step is to have the computer make decisions based on these updated values. You do this with the IF-THEN statement. You tell the computer to execute a command only IF a condition is true (e.g. IF X=5). The command you want the computer to execute when the condi- tion is true comes after the word THEN in the statement. Clear your computer's memory by typing NEW and pressing {return}, then type in this program: 10 J=0 20 J=J+1 30 ? J,"COMMODORE 128" 40 IF J=5 THEN GOTO 60 50 GOTO 20 60 END You no longer have to press the {stop} key to break out of a looping pro- gram. The IF-THEN statement tells the computer to keep printing "COMMODORE 128" and incrementing (increasing) J until J=5 is true. When an IF condi- tion is false, the computer jumps to the next line of the program, no matter what comes after the word THEN. Notice the END command in line 60. It is good practice to put an END state- ment as the last line in your program. It tells the computer where to stop executing statements. Below is a list of comparison symbols that may be used in the IF statement and their meanings: SYMBOL MEANING = EQUALS > GREATER THAN <> NOT EQUAL TO >= GREATER THAN OR EQUAL TO <= LESS THAN OR EQUAL TO You should be aware that these comparisons work in expected mathematical ways with numbers. There are different ways to determine if one string is greater than, less than, or equal to another. You can learn about these "string handling" functions by referring to Chapter V, Basic 7.0 Encyclo- paedia. Section 5 describes some powerful extensions of the IF-THEN concept, con- sisting of the BASIC 7.0 commands BEGIN, BEND and ELSE. 4.1.1 Using the Colon A very useful tool in programming is the colon (:). You can use the colon to separate two (or more) BASIC commands on the same line. Statements after a colon on a line will be executed in order, from left to right. In one program line you can put as many statements you can fit into 160 characters, including the line number. This is equivalent to four full screen lines in 40-column format, and two full lines in 80-column format. This provides an excellent oppurtunity to take advantage of the THEN part of the IF-THEN statement. You can tell the computer to execute several com- mands when you IF statement is true. Clear the computer's memory and type in the following progam: 10 N=1 20 IF N<5 THEN PRINT N;"LESS THAN 5":GOTO 40 30 ? N;"GREATER THAN OR EQUAL TO 5" 40 END Now change line 10 to read N=20, and RUN the program again. Notice you can tell the computer to execute more than one statement when N is less than 5. You can put any statement(s) you want after the THEN command. Remember that the GOTO 40 will not be reached if N is true. Any command that should be followed whether or not the specified condition is met should appear on a separate line. 4.2 LOOPS - The FOR-NEXT Command In the program used for the IF-THEN example, we made the computer print COMMODORE five times by telling it to increase or "increment" the variable J by units of one, until the value of J equalled five; then we ended the program. There is a simpler way to do this in BASIC. We can use a FOR-NEXT loop, like this: 10 FOR J=1 TO 5 20 ?J,"COMMODORE 128" 30 NEXT J 40 END Type and RUN this program and compare the result with the result of the IF-THEN program - they are the same. In fact, the steps taken by the com- puter are almost identical for the two programs. The FOR-NEXT loop is a very powerful programming tool. You can specify the number of times the computer should repeat an action. Let's trace the computer's steps for the program above. First, the computer assigns a value of 1 to the variable J. The 5 in the FOR statement tells the computer to execute all statements between the FOR statement and the NEXT statement, until J is equal to 5. In this case there is just one statement - the PRINT statement. The computer first assigns 1 to J, it then goes on to execute the PRINT statement. When the computer reaches the NEXT J statement, J is incremented and compared with 5. If J has not exceeded 5 the computer loops back to the PRINT statement. After five executions of this loop the value of J exceeds 5, the program drops down to the statement that comes immediately after the NEXT statement and continues from there. In this case the following statement is the END statement, so the program stops. 4.2.1 Empty Loops - Inserting Delays in a Program Before you proceed any further, it will be helpful to understand about loops and some ways they are used to get the computer to do what you want. You can use a loop to slow down the computer (by now you have witnessed the speed with which the computer executes commands). See if you can predict what this program will do before you run it. 10 A$="COMMODORE 128" 20 FOR J=1 TO 20 30 PRINT 40 FOR K=1 TO 1500 50 NEXT K 60 PRINT A$ 70 NEXT J 80 END Did you get what you expected? The loop contained in line 40 and 50 tells the computer to count to 1500 before executing the remainder of the program. This is known as a delay loop and is often used. Because it is inside the main loop of the program, it is called a nested loop. Nested loops can be very useful when you want the computer to perform a number of tasks in a given order, and repeat the entire sequence of commands a certain number of times. Section 5 describes an advanced way to insert delays through the use of the new BASIC 7.0 command, SLEEP. 4.2.2 The STEP Command You can tell the computer to increment your counter by units (e.g. 10, 0.5 or any other number). You do this by using a STEP command with the FOR statement. For example, if you want the computer to count by tens to 1000, type: 10 FOR X=0 TO 1000 STEP 10 20 ? X 30 NEXT Notice that you do not need the X in the NEXT statement if you are only executing one loop at a time - this is discussed later in this section. Also, note that you do not have to increase (or "increment") your counter - you can decrease (or "decrement") it as well. For example, change line 10 in the program above to read: 10 FOR X=100 TO 0 STEP - 10 The computer will count backward from 100 to 0, in units of 10. If you don't use a STEP command with a FOR statement, the computer will automatically increment the counter by units of 1. The parts of the FOR-NEXT commands are: FOR - word used to indicate beginning of loop. X - counter variable; any number variable can be used. 1 - starting value; may be any number, positive, negative or zero. TO - connects starting value to ending value. 100 - ending value; may be any number, positive, negative or zero. STEP - indicates an increment other than 1 will be used. 2 - increment; can be any number, positive, negative or zero. Section 5 describes DO/LOOP, a new, more powerful BASIC 7.0 command to per- form a similar task to the STEP command. 4.3 INPUTTING DATA 4.3.1 The INPUT Command 4.3.1.1 Assigning a value to a variable Clear the computer's memory by typing NEW and pressing {return}, and then type and RUN this program: 10 K=10 20 FOR I=1 TO K 30 ?"COMMODORE 128" 40 NEXT In this program you can change the value of K in line 10 to make the com- puter execute the loop as many times as you want it to. You have to do this when you are typing in the program, before it is RUN. What if you wanted to be able to tell the computer how many times to execute the loop at the time the program is RUN? In other words, you want to be able to change the value of the variable K each time you run the program, without having to change to program itself. We call this the ability to interact with the computer. You can have the computer ask how many times you want it to execute the loop. To do this, use the INPUT command. For example, replace line 10 in the program with: 10 INPUT K Now when you RUN the program, the computer reponds with a ? to let you know it is waiting for you to enter what you want the value of K to be. Type 15 and press {return}. The computer will execute the loop 15 times. 4.3.1.2 Prompt Messages You can also make the computer print a message in an INPUT statement to tell you what variable it's waiting for. Replace line 10 with: 10 INPUT"PLEASE ENTER A VALUE FOR K";K Remember to enclose the message to be printed in quotes. This message is called a prompt. Also, notice that you must use a semicolon (;) between the ending quote marks of the prompt and the K. You may put any message you want in the prompt, but the INPUT statement must be 160 characters or less, just as any BASIC command must. The INPUT statement can also be used with string variables. The same rules that apply for numeric variables apply for strings. Don't forget to use the {$} to identify all you string variables. Clear you computer's memory by typing NEW and pressing {return}. Then type this program. 10 INPUT"WHAT IS YOUR NAME";NM$ 20 ? "HELLO ";N$ Now RUN the program. When the computer prompts "WHAT IS YOUR NAME?", then type your name. Don't forget to press {return} after you type your name. Once the value of a variable (numeric or string) has been inserted into a program through the use of INPUT, you can refer to it by its variable name any time in the program. Type ?N$ {return} - your computer remembers your name! 4.3.2 The GET Command There are other BASIC commands you can use in your program to interact with the computer. One is the GET command and is similar to INPUT. To see how the GET command works, clear the computer's memory and type this program: 10 GET A$ 20 IF A$="" THEN 10 30 ? A$ 40 END When you type RUN and press {return}, nothing seems to happen. The reason is that the computer is waiting for you to press a key. The GET command, in effect, tells the computer to check the keyboard and find out what character or key is being pressed. The computer is satisfied with a null character (that is, no character). This is the reason for line 20. This line tells the computer that if it gets a null character, indicated by double quotes with no space in between them, it should go back to line 10 and try to GET another character. This loop continues until you press a key. The computer then assigns the character on that key to A$. The GET command is very important because you can use it, in effect, to program a key on your keyboard. The example below prints a message on the screen when {q} is pressed. Type the program and RUN it. The press {q} and see what happens. 10 ?"PRESS Q TO VIEW MESSAGE" 20 GET A$ 30 IF A$="" THEN 20 40 IF A$="Q" THEN 60 50 GOTO 20 60 FOR I=1 TO 25 70 ? "NOW I CAN USE THE GET STATEMENT" 80 NEXT 90 END Notice that if you try to press any key other than the {q}, the computer will not display the message, but will go back to line 20 to GET another character. Section 5 describes how to use the GETKEY statement, which is a new and more powerful BASIC 7.0 command that can be used to perform a similar task. 4.3.3 Sample Program Now that you know how to use the FOR-NEXT loop and the INPUT command, clear the computer's memory by typing NEW {return}, then type the following program: 10 T=0 20 INPUT"HOW MANY NUMBERS";N 30 FOR J=1 TO N 40 INPUT"PLEASE ENTER A NUMBER";X 50 T=T+X 60 NEXT 70 A=T/N 80 PRINT 90 ? "YOU HAVE";N"NUMBERS TOTALING "T 100 ? "AVERAGE = ";A 110 END This program lets you tell the computer how many numbers you want to ave- rage. You can change the numbers every time you run the program without having to change the program itself. Let's see what the program does, line by line: Line 10 assigns a value of 0 to T (which will be the running total of the numbers). Line 20 lets you determine how many numbers to average, stored in variable N. Line 30 tells the computer to execute a loop N times. Line 40 lets you type in the actual numbers to be averaged. Line 50 adds each number to the running total. Line 60 tells the computer to increment the counter (J) and loop back to line 30 while the counter (J) <= N. Line 70 divides the total by the amount of numbers you typed in (N) after the loop has been executed N times. Line 80 prints a blank line on the screen. Line 90 prints the message that gives you the amount of numbers and their total. Line 100 prints the average of the numbers. Line 110 tells the computer that your progam is finished. 4.3.4 The READ-DATA Commands There is another powerful way to tell the computer what numbers or charac- ters to use in your program. You can use the READ statement in your program to tell the computer to get a number or character(s) from the DATA state- ment. For example, if you want the computer to find the average of five numbers, you can use the READ and DATA statements this way: 10 T=0 20 FOR J=1 TO 5 30 READ X 40 T=T+X 50 NEXT 60 A=T/5 70 ? "AVERAGE =";A 80 END 90 DATA 5,12,1,34,18 When you RUN the program, the computer will print AVERAGE = 14. The program uses the variable T to keep a running total, and calculates the average in the same way as the INPUT average program. The READ-DATA average program, however, finds the numbers to average on a DATA line. Notice line 30, READ X. The READ command tells the computer there must be a DATA statement in the program. It finds the DATA line, and uses the first number as the cur- rent value for the variable X. The next time through the loop the second number in the DATA statement will be used as the value for X, and so on. You can put any number you want in a DATA statement, but you cannot put calculations in a DATA statement. The DATA statement can be anywhere you want in the program - even after the END statement, or as the first program line. This is because the computer never really executes the DATA state- ment; it will just refer to it. Be sure to separate your data items with commas, but be sure not to put a comma between the word DATA and the first number in the list. If you have more than one DATA statement in your program, the computer will start READing from the first DATA statement in the program listing when the program is RUN. The computer uses a pointer to remind itself which piece of data it read last. After the computer reads the first number in the DATA statement, the pointer moves to the next number. When the computer comes to the READ statement again, it assigns the value the pointer indicates to the variable in the READ statement. You can use as many READ and DATA statement as you need in a program, but make sure there is enough data in the DATA statements for the computer to READ. Remove one of the numbers from the DATA statement in the last program and RUN it again. The computer responds with ?OUT OF DATA ERROR IN 30. What happened is that when the computer executed the loop for the fifth time, there was no data for it to read. That is what the error message is telling you. Putting too much into the DATA statement doesn't create a problem in this program, because the computer never realizes the extra data exists. 4.3.5 The RESTORE Command You can use the RESTORE command in a program to reset the data pointer to the first piece of data if you need to. Replace the END statement (line 80) in the program above with: 80 RESTORE and add: 85 GOTO 10 Now RUN the program. The program will run continuously using the same DATA statement. NOTE: If the computer gives you an OUT OF DATA error message, it is because you forgot to replace the number that you removed previously from the DATA statement, so the data is all used before the READ statement has been exe- cuted the specific number of times. 4.3.5.1 Assigning values to string variables You can use DATA statements to assign values to string variables. The same rules apply as for numeric data. Clear the computer's memory and type the following program: 10 FOR J=1 TO 3 20 READ A$ 30 ? A$ 40 NEXT 50 END 60 DATA COMMODORE,128,COMPUTER If the READ statement calls for a string variable, you can place letters or numbers in the DATA statement. Notice however, that since the computer is READing a string, numbers will be stored as a string of characters, not as a value which can be manipulated. Numbers stored as strings can be printed, but not used in calculations. Also you cannot place letters in a DATA statement if the READ statement calls for a number variable. 4.3.6 Using Arrays You have seen how to use READ-DATA to provide many values for a variable. But what if you want the computer to remember all the data in the DATA statement instead of replacing the value of a variable with the new data? What if you want to be able to recall the third number, or the second string of characters? Each time you assign a new value to a variable, the computer erases the old value in the variable's box in memory and stores the new value in its place. You can tell the computer to reserve a row of boxes in memory and store every value that you assign to that variable in your program. This row of boxes is called an array. 4.3.6.1 Subscripted Variables If the array contains all of these values assigned to the variable X in the READ-DATA example, it is called the X array. The first value assigned to X in the program is called X(1), the second value is X(2), and so on. These are called subscripted variables. The numbers in the parentheses are called subscripts. You can use the value of a variable or the result of a calcu- lation as a subscript. The following is another version of the averaging program, this time using subscripted variables. 5 DIM X(5) 10 T=0 20 FOR J=1 TO 5 30 READ X(J) 40 T=T+X(J) 50 NEXT 60 A=T/5 70 ? "AVERAGE =";A 80 END 90 DATA 5,12,1,34,18 Notice there are not many changes. Line 5 is the only new statement. It tells the computer to set aside five boxes in memory for the X array. Line 30 has been changed so that each time the computer executes the loop, it assigns a value from the DATA statement to the position in the X array that corresponds to the loop counter (J). Line 40 calculates the total, just as it did before, but you must use a subscipted variable to do it. After you RUN the program, if you want to recall the third number, type: ?X(3) {return} The computer remembers every number in the array X. You can create string arrays to store the charachters in string variables the same way. Try updating the COMMODORE 128 COMPUTER READ-DATA program so the computer will remember the elements in the A$ array. 5 DIM A$(3) 10 FOR J=1 TO 3 20 READ A$(J) 30 ? A$(J) 40 NEXT 50 END 60 DATA COMMODORE,128,COMPUTER TIP: You do not need the DIM statement in your program unless the array you use has more than 10 elements, see the next paragraaf, Dimensioning Arrays. 4.3.6.2 Dimensioning Arrays Arrays can be used with nested loops, so the computer can handle data in a more advanced way. What if you had a large chart with 10 rows and 5 numbers in each row. Suppose you wanted to find the average of the five numbers in each row. You could create 10 arrays and have the computer calculate the average of the five numbers in each one. This is not necessary, because you can put all the numbers in a two-dimensional array. This array would have the same dimensions as the chart of numbers you want to work with - 10 rows by 5 columns. The DIM statement for this array (we will call it array X) should be: 10 DIM X(10,5) This tells the computer to reserve space in its memory for a two dimen- sional array named X. The computer reserves enough space for 50 numbers. You do not have to fill an array with as many numbers as you DIMensioned it for, but the computer will still reserve enough space for all the positions in the array. 4.3.6.3 Sample Program Now it becomes very easy to refer to any number in the chart by its column and row position. Refer to the chart below. Find the third element in the tenth row (1500). You would refer to this number as X(10,3) in your program. The following program reads the numbers from the chart into a two-dimen- sional array (X) and calculates the average of the numbers in each row. Column ----------+-------------------------------------------------- Row | 1 2 3 4 5 ----------+-------------------------------------------------- 1 | 1 3 5 7 9 2 | 2 4 6 8 10 3 | 5 10 15 20 25 4 | 10 20 30 40 50 5 | 20 40 60 80 100 6 | 30 60 90 120 150 7 | 40 80 120 160 180 8 | 50 100 150 200 250 9 | 100 200 300 400 500 10 | 500 1000 1500 2000 2500 10 DIM X(10,5), A(10) 20 FOR R=1 TO 10 30 T=0 40 FOR C=1 TO 5 50 READ X(R,C) 60 T=T+X(R,C) 70 NEXT C 80 A(R)=T/5 90 NEXT R 100 FOR R=1 TO 10 110 PRINT "ROW #";R 120 FOR C=1 TO 5 130 PRINT X(R,C) 140 NEXT C 150 PRINT "AVERAGE =";A(R) 160 FOR D=1 TO 1000:NEXT 170 NEXT R 180 DATA 1,3,5,7,9 190 DATA 2,4,6,8,10 200 DATA 5,10,15,20,25 210 DATA 10,20,30,40,50 220 DATA 20,40,60,80,100 230 DATA 30,60,90,120,150 240 DATA 40,80,120,160,200 250 DATA 50,100,150,200,250 260 DATA 100,200,300,400,500 270 DATA 500,1000,1500,2000,2500 280 END 4.4 PROGRAMMING SUBROUTINES 4.4.1 The GOSUB-RETURN Commands Until now, the only method you have had to tell the computer to jump to another part of your program is to use the GOTO command. What if you want the computer to jump to another part of the program, execute the statements in that section, then return to the point it left off and continue execu- ting the program? The part of program that the computer jumps to and executes is called a subroutine. Clear your computer's memory and enter the program below. 10 A$="SUBROUTINE":B$="PROGRAM" 20 FOR J=1 TO 5 30 INPUT "ENTER A NUMBER";X 40 GOSUB 100 50 PRINT B$:PRINT 60 NEXT 70 END 100 PRINT A$:PRINT 110 Z=X^2:PRINT Z 120 RETURN This program will square the numbers you type and print the result. The other print messages tell you when the computer is executing the subroutine or the main program. Line 40 tells the computer to jump to line 100, exe- cute it and the statements following it until it sees a RETURN command. The RETURN statement tells the computer to go back in the program to the line immediately following the GOSUB command and continue executing. The subrou- tine can be anywhere in the program - including after the END statement. Also, remember that the GOSUB and RETURN commands must always be used to- gether in a program (like FOR-NEXT and IF-THEN), otherwise the computer will give an error message. 4.4.2 The ON GOTO/GOSUB Commands There is another way to make the computer jump to another section of your program (called branching). Using the ON statement, you can have the com- puter decide what part of the program to branch to, based on a calculation or keyboard input. The ON statement is used with either the GOTO or GOSUB-RETURN commands, depending on what you need the program to do. A variable or calculation should be after to ON command. After the GOTO or GOSUB command, there should be a list of line numbers. Type in the program below to see how the ON command works. 10 ?"ENTER A NUMBER BETWEEN ONE AND FIVE" 20 INPUT X 30 ON X GOSUB 100,200,300,400,500 40 END 100 ?"YOUR NUMBER WAS ONE":RETURN 200 ?"YOUR NUMBER WAS TWO":RETURN 300 ?"YOUR NUMBER WAS THREE":RETURN 400 ?"YOUR NUMBER WAS FOUR":RETURN 500 ?"YOUR NUMBER WAS FIVE":RETURN When the value of X is 1, the computer branches to the first line number in the list (100). When X is 2, the computer branches to the second number in the list (200), and so on. 4.5 USING MEMORY LOCATION 4.5.1 Using PEEK and POKE for RAM Access Each area of the computer's memory has a special function. For instance, there is a very large area to store your programs and the variables asso- ciated with them. This part of memory, called RAM, is cleared when you use the NEW command. Other areas are not as large, but they have very specia- lized functions. For instance, there is an area of memory locations that controls the music features of the computer. There are two BASIC keywords - PEEK and POKE - that you can use to access and manipulate the computer's memory. Use of the PEEK function and the POKE command can be a powerful programming device because the contents of the computer's memory locations determine exactly what the computer should be doing at a specific time. 4.5.1.1 Using PEEK PEEK can be used to make the computer tell you what value is being stored in a memory location (a memory location can store any value between 0 and 255). You can PEEK the value of any memory location (RAM or ROM) in DIRECT or PROGRAM mode. Type: P=PEEK(2594) {return} ? P {return} The computer assigns the value in memory location 2594 to the variable P when you press {return} after the first line. Then it prints the value when you press {return} after entering the ? P command. Memory location 2594 determines whether or not keys like the SPACEBAR and CRSR repeat when you hold them down. A 128 in location 2594 tells the computer to repeat these keys when you hold them down. Hold down the SPACEBAR and watch the cursor move across the screen. 4.5.1.2 Using POKE To change the value stored in a RAM location, use the POKE command. Type: POKE 2594,96 {return} The computer stores the value after the comma (i.e. 96) in the memory loca- tion before the comma (i.e. 2594). A 96 in memory location 2594 tells the computer not to repeat keys like the SPACEBAR and CRSR keys when you hold them down. Now hold down the SPACEBAR and watch the cursor. The cursor moves one position to the right, but it does not repeat. To return your computer to its normal state, type: POKE 2594,128 {return} You cannot alter the value of all the memory locations in the computer - the values in ROM can be read, but not changed. NOTE: These examples assume you are in bank 0. See also the descrip- tion of the BANK command in chapter V, BASIC 7.0 Encyclopaedia for details on banks. 4.6 BASIC FUNCTIONS 4.6.1 What is a Function? A function is a predefined operation of the BASIC language that generally provides you with a single value. When the function provides the value, it is said to "return" the value. For instance, the SQR (square) function is a mathematical function that returns the value of a specific number when it is raised to the second power - i.e., squared. There are two kinds of functions: Numeric - returns a result which is a single number. Numeric functions range from calculating mathematical values to specifying the numeric value of a memory location. String - returns a result which is a character. Following are descriptions of some of the more commonly used functions. For a complete list, see Section 18 of Chapter V, BASIC 7.0 Encyclopaedia. 4.6.2 The INTEGER Function (INT) What if you want to round off a number to the nearest integer? You'll need to use INT, the integer function. The INT function takes away everything after the decimal point. Try typing these examples: ? INT(4.25) {return} ? INT(4.75) {return} ? INT(SQR(50)) {return} If you want to round off to the nearest whole number, then the second example should return a value of 5. In fact, you should round up any number with a decimal above 0.5. To do this, you have to add 0.5 to the number before using the INT function. In this way, numbers with decimal portions equal to or above 0.5 will be increased by 1 before rounding down by the INT function. Try this: ? INT(4.75+0.5) {return} The computer added 0.5 to 0.75 before it executed the INT function, so that it rounded 5.25 down to 5 for the result. If you want to round off the result of a calculation, do this: ? INT((100/6)+0.5) {return} You can substitute any calculation for the division shown in the inner parenteses. What if you want to round off numbers to the nearest of 0.01? Instead of adding 0.5 to your number, add 0.005, then multiply by 100. Let's say you want to round 2.876 to the nearest 0.01. Using this method, you start with: ?(2.876 + 0.005)*100 {return} Now use the INT function to get rid of everything after the decimal point (which moves two places to the right when you multiply by 100). You are left with: ?INT((2.876 + 0.005)*100) {return} which gives you a value of 288. All that's left to do is divide by 100 to get the value of 2.88, which is the answer you want. Using this technique, you can round off calculations like the following to the nearest of 0.01: ?INT(((2.876+1.29+16.1-9.534) + 0.005)*100) {return} 4.6.3 Generating Random Numbers - The RND Function The RND function tells the computer to generate a random number. This can be useful in simulating games of chance, and in creating interesting graphics or music programs. All random (RND) numbers are nine digits, in decimal form, between the value 0.000000001 and 0.999999999. Type: ? RND(0) {return} Multiplying the randomly generated number by six makes the range of gene- rated numbers increase to greater than 0 and less than six. In order to in- clude 6 (and exclude zero) among the numbers generated, we add one to the result of RND(0)*6. This makes the range 1 10 R=(INT(RND(1)*6+1) 20 ? R 30 GOTO 10 Each number generated represents one toss of a die. To simulate a pair of dice, use two commands of this nature. Each number is generated separately, and the sum of the two numbers represents the total of the dice. 4.6.4 The ASC and CHR$ Functions Every character that the Commodore 128 can display (including graphic characters) has a number assigned to it. This number is called a character string code (CHR$) and there are 255 of them in the Commodore 128. There are two functions associated with this concept that are very useful. The first is the ASC function. Type: ? ASC(Q) {return} The computer responds with 81. 81 is the character string code for the {q} key. Substitute any key for {q} in the command above to find out the Com- modore ASCII code number for any character. The second function is the CHR$ function. Type: ? CHR$(81) {return} The computer responds with Q. In effect, the CHR$ function is the opposite of the ASC function. They both refer to the table of character string codes in the computer's memory. CHR$ values can be used to program function keys. See Section 5 for more information about the use of these functions. See Appendix E of this Guide for a listing of ASC and CHR$ codes. 4.6.5 Converting Strings and Numbers Sometimes you may need to perform calculations on numeric characters that are stored as string variables in your program. Other times, you may want to perform string operations on numbers. There are two BASIC functions you can use to convert your variables from numeric to string type and vice versa. 4.6.5.1 The VAL Function The VAL function returns a numeric value for a string argument. Clear the computer's memory and type in this program: 10 A$="64" 20 A=VAL(A$) 30 ? "THE VALUE OF ";A$;" IS";A 40 END 4.6.5.2 The STR$ Function The STR$ function returns the string representation of a numeric value. Clear the computer's memory and type this program: 10 A=65 20 A$=STR$(A) 30 ? A"IS THE VALUE OF ";A$ 4.6.6 The Square Root Function (SQR) The square root function is SQR. For example, to find the square root of 50, type: ? SQR(50) {return} You can find the square root of any positive number in this way. 4.6.7 The Absolute Value Function (ABS) The absolute value (ABS) is very useful in dealing with negative numbers. You can use this function to get the positive value of any number, positive or negative. Try these examples: ? ABS(-10) {return} ? ABS(5)"IS EQUAL TO"ABS(-5) {return} 4.7 THE STOP AND CONT (CONTINUE) COMMANDS You can make the computer stop a program, and resume running it when you are ready. The STOP command must be included in the program. You can put a STOP command anywhere you want to in a program. When the computer "breaks" from the program (that is, stops running the program), you can use DIRECT mode commands to find out exactly what is going on in the program. For example, you can find the value of a loop counter or other variable. This is a powerful device when you are "debugging" or fixing your program. Clear the computer's memory and type the progam below. 10 X=INT(SQR(630)) 20 Y=(.025*80)^2 30 X=INT(X*Y) 40 STOP 50 FOR J=0 TO Z STEP Y 60 ? "STOP AND CONTINUE" 70 NEXT 80 END Now RUN this program. The computer responds with BREAK IN 40. At this point, the computer has calculated the values of X, Y and Z. If you want to be able to figure out what the rest of the program is supposed to do, tell the computer to PRINT X;Y;Z. Often when you are debugging a large program (or a complex small one), you'll want to know the value of a variable at a certain point in the program. Once you have all the information you need, you can type CONT (for CONTinue) and press {return} assuming you have not editing anything on the screen. The computer then CONTinues with the program, starting with the statement after the STOP command. *************************************************************************** This section and the preceding one have been designed to familiarize you with the BASIC programming language and its capabilities. The remaining four sections of this chapter describe commands that are unique to Com- modore 128 mode. Some Commodore 128 mode commands provide capabilities that are not available in C64 mode. Other Commodore 128 mode commands let you do the same things as a certain C64 command, but more easily. The syntax for all Commodore 7.0 commands is given in Chapter V, BASIC 7.0 Encyclopaedia. SECTION 5 5. Some BASIC Commands and Keyboard Operations Unique to C128 5.1 INTRODUCTION 5.2 ADVANCED LOOPING 5.2.1 The DO/LOOP Statement 5.2.1.1 UNTIL 5.2.1.2 WHILE 5.2.1.3 EXIT 5.2.2 The ELSE Clause with IF-THEN 5.2.3 The BEGIN/BEND Sequence with IF-THEN 5.2.4 The SLEEP Command 5.3 FORMATTING OUTPUT 5.3.1 The PRINT USING Command 5.3.2 The PUDEF Command 5.4 SAMPLE PROGRAM 5.5 INPUTTING DATA WITH THE GETKEY COMMAND 5.6 PROGRAMMING AIDS 5.6.1 Entering Programs 5.6.1.1 AUTO 5.6.1.2 RENUMBER 5.6.1.3 DELETE 5.6.2 Identifying Problems in Your Programs 5.6.2.1 HELP 5.6.2.2 Error Trapping - The TRAP Command 5.6.2.3 Program Tracing - The TRON and TROFF Commands 5.7 WINDOWING 5.7.1 Using the WINDOW Command to Create a Window 5.7.2 Using the ESC Key to Create a Window 5.8 2 MHZ OPERATION 5.8.1 The FAST and SLOW Commands 5.9 KEYS UNIQUE TO C128 MODE 5.9.1 Function Keys 5.9.2 Redefining Function Keys 5.9.3 Other Keys Used in C128 Mode Only 5.9.3.1 HELP 5.9.3.2 NO SCROLL 5.9.3.3 CAPS LOCK 5.9.3.4 40/80 DISPLAY 5.9.3.5 ALT 5.9.3.6 TAB 5.9.3.7 LINE FEED 5.1 INTRODUCTION This section introduces you to some powerful BASIC commands and statements that you probably have not seen before, even if you are an experienced BASIC programmer. If you are familiar with programming in BASIC, you have probably encountered many situations in which you could have used these commands and statements. This section explains the concepts behind each command and gives examples of how to use each command in a program. (A com- plete list and an explanation of these commands and statements may be found in Chapter V, BASIC 7.0 Encyclopaedia.) This section also describes how to use the special keys that are available to you in C128 mode. 5.2 ADVANCED LOOPING 5.2.1 The DO/LOOP Statement The DO/LOOP statement provides more sophisticated ways to create a loop than do the GOTO, GOSUB or FOR/NEXT statements. The DO/LOOP statement com- bination brings to the BASIC language a very powerful and versatile tech- nique normally only available in structured programming languages. We discuss just a few possible uses of DO/LOOP in this explanation. If you want to create an infinite loop, you start with a DO statement, then enter the line or lines that specify the action you want the computer to perform. Then end with a LOOP statement like this: 100 DO 110 PRINT "REPETITION" 120 LOOP Press the {run/stop} key to stop the program. The directions following the DO statement are carried out until the program reaches the LOOP statement (line 120); control is then transferred back to the DO statement (line 100). Thus any statements in between DO and LOOP are performed indefinitely. 5.2.1.1 UNTIL Another useful technique is to combine the DO/LOOP with the UNTIL state- ment. The UNTIL statement sets up a condition that directs the loop. The loop will run continually unless the condition for UNTIL happens. 100 DO:INPUT "DO YOU LIKE YOUR COMPUTER";A$ 110 LOOP UNTIL A$="YES" 120 PRINT "THANK YOU" The DO/LOOP statement is often used to repeat an entire routine indefinite- ly in the body of a program, as in the following: 10 PRINT "PROGRAM CONTINUES UNTIL YOU TYPE 'QUIT'" 20 DO UNTIL A$="QUIT" 30 INPUT "DEGREES FAHRENHEIT";F 40 C=(5/9)*(F-32) 50 PRINT F;"DEGREES FAHRENHEIT EQUALS ";C;"DEGREES CELCIUS" 60 INPUT "AGAIN OR QUIT";A$ 70 LOOP 80 END Another use of DO/LOOP is as a counter, where the UNTIL statement is used to specify a certain number of repetitions. 10 N=2*2 20 PRINT"TWO DOUBLED EQUALS";N 30 DO UNTIL X=25 40 X=X+1 50 N=N*2 60 PRINT"DOUBLED";X+1;"TIMES...";N 70 LOOP 80 END Notice that if you leave the counter statement out (the UNTIL X=25 part in line 30), the number is doubled indefinitely until an OVERFLOW error occurs. 5.2.1.2 WHILE The WHILE statement works in a similar way to UNTIL, but the loop is re- peated only while the condition is in effect, such as in the reworking of the last brief program: 100 DO:INPUT "DO YOU LIKE YOUR COMPUTER";A$ 110 LOOP WHILE A<>"YES" 120 PRINT "THANK YOU" 5.2.1.3 EXIT An EXIT statement can be placed within the body of a DO/LOOP. When the EXIT statement is encountered, the program jumps to the next statement following the LOOP statement. 5.2.2 The ELSE Clause with IF-THEN The ELSE clause provides a way to tell the computer how to respond if the condition of the IF-THEN statement is false. Rather than continuing to the next program line, the computer will execute the command or branch to the program line mentioned in the ELSE clause. For example, if you wanted the computer to print the square of a number, you could use the ELSE clause like this: 10 INPUT "TYPE A NUMBER TO BE SQUARED";N 20 IF N<100 THEN PRINT N*N:ELSE 40 30 END 40 ?"NUMBER MUST BE < 100":GOTO 10 Notice that you must use a colon (:) between the IF-THEN statement and the ELSE clause. 5.2.3 The BEGIN/BEND Sequence with IF-THEN BASIC 7.0 allows you to take the IF-THEN condition one step further. The BEGIN/BEND sequence permits you to include a number of program lines to be executed if the IF condition is true, rather than one simple action or GOTO. The command is constructed like this: IF condition THEN BEGIN: (program lines): BEND:ELSE Be sure to place a colon (:) between BEGIN and any instruction to the com- puter, and again between the last command in the sequence and the word BEND. BEGIN/BEND can be used without an ELSE clause, or can be used fol- lowing the ELSE clause when only a single command follows THEN and multiple commands follow the ELSE clause (of course BEGIN/BEND can also be used both after THEN and ELSE). Try this program: 10 INPUT A 20 IF A<100 THEN BEGIN: ?"YOUR NUMBER WAS"A 30 SLEEP 2:REM DELAY 40 FOR X=1 TO A 50 ?"THIS IS AN EXAMPLE OF BEGIN/BEND" 60 NEXT X 70 ?"THAT'S ENOUGH":BEND:ELSE ?"TOO MANY" 80 END This program asks for a number from the user. IF the number is less than 100, the statement between the keywords BEGIN and BEND are performed, along with any statements on the same line as BEND (except for ELSE). The message "YOUR NUMBER WAS" n appears on the screen. Line 30 is a delay used to keep the message on the screen long enough so it can be read easily. Then a FOR/NEXT loop is used to display a message the number of times specified by the user. If the number is greater than or equal to 100, the part after the THEN condition is skipped, and part after the ELSE condition (printing "TOO MANY") is carried out. The ELSE keyword must be on the same line as BEND. 5.2.4 The SLEEP Command Note the use of the SLEEP command in line 30 of the program just discussed. SLEEP provides an easier, more accurate way of inserting and timing a delay in program operation. The format of the SLEEP command is: SLEEP n where n indicates the number of seconds (rounded down to a whole number of seconds), in the range of 0 to 65535, that you want the program to delay. In the command shown in line 30, the 2 specifies a delay of two seconds. 5.3 FORMATTING OUTPUT 5.3.1 The PRINT USING Command Suppose you were writing a sales program that calculated a dollar amount. Total sales divided by number of salespeople equals average sales. But per- forming this calculation might result in dollar amounts with four or five decimal places! You can format the result the computer prints so that only two decimal places are displayed. The command which performs this function is PRINT USING. PRINT USING lets you create a format for your output, using spaces, commas, decimal points and dollar signs. Hash marks (the {#} sign) are used to re- present spaces or characters in the displayed result. For example: PRINT USING "#$######.##";A tells the computer that when A is printed, it should be in the form given, with up to six places to the left of the decimal point, and two places to the right. The hash mark in front of the dollar sign indicates that the {$} should float, that is, it should always be placed next to the left-most number in the format. If you want a comma to appear before the last three dollar places (as in $1,000.00), include the comma in the PRINT USING statement. Remember you can format output with spaces, commas, decimal points, and dollar signs. There are several other special characters for PRINT USING, see paragraph 17.68 of the BASIC Encyclopaedia for more information. 5.3.2 The PUDEF Command If you want formatted output representing something other than dollars and cents, use the PUDEF (Print Using DEFine) command. You can replace any of four format characters with any character on the keyboard. The PUDEF command has four positions, but you do not have to redefine all four. The command looks like this: PUDEF " ,.$" 1234 Here: * position 1 is the filler character. A blank will appear if you do not redefine this position. * position 2 is the comma character. Default is the comma. * position 3 is the decimal point. * position 4 is the dollar sign. If you wrote a program that converted a dollar amount to English pounds, you could format the output with these commands: 10 PUDEF " ,.{pound}" 20 PRINT USING "#$####.##";X 5.4 SAMPLE PROGRAM This program calculates interest and loan payments, using some of the com- mands and statements you just learned. It sets a minimum value for the loan using the ELSE clause with an IF-THEN statement, and sets up a dollar and cents format with PRINT USING. 10 INPUT "LOAN AMOUNT IN DOLLARS";A 20 IF A<100 THEN 70:ELSE P=.15 30 I=A*P 40 ?"TOTAL PAYMENT EQUALS"; 50 PRINT USING "#$#####.##";A+1 60 GOTO 80 70 ?"LOANS UNDER $100 ARE NOT AVAILABLE" 80 END 5.5 INPUTTING DATA WITH THE GETKEY COMMAND You have learned to use the INPUT and GET commands to enter DATA during a program. Another way for you to enter data while a program is being RUN is with the GETKEY statement. The GETKEY statement accepts only one key at a time. GETKEY is usually followed by a string variable (A$ for example). Any key that is pressed is assigned to that string variable. GETKEY is useful because it allows you to enter data one character at a time without having to press the RETURN key after each character. The GETKEY statement may only be used in a program. Here is an example of using GETKEY in a program: 1000 PRINT "PLEASE CHOOSE A, B, C, D, E OR F" 1010 GETKEY K$ 1020 PRINT A$;" WAS THE KEY YOU PRESSED." The computer waits until a single key is pressed; when the key is pressed, the character is assigned to variable A$, and printed out in line 1020. The following program features the GETKEY in more complex and useful fashions: for answering multiple-choice question and also asking if the question should be repeated. If the answer given is incorrect, the user has the option to try again by pressing the {y} key (line 80). The key pressed for the multiple choice answer is assigned to variable A$ while the "TRY AGAIN" answer is assigned to B$, through the GETKEY statements in line 60 and 90. IF/THEN statements are used for loops in the program to get the proper computer reaction to the different keyboard inputs. 10 PRINT "WHO WROTE 'THE RAVEN'?" 20 PRINT "A. EDGAR ELLEN POE" 30 PRINT "B. EDGAR ALLEN POE" 40 PRINT "C. IGOR ALLEN POE" 50 PRINT "D. ROB RAVEN" 60 GETKEY A$ 70 IF A$="B" THEN 150 80 PRINT "WRONG. TRY AGAIN? (Y OR N)" 90 GETKEY B$ 100 IF B$="Y" THEN PRINT "A,B,C OR D": GOTO 60 110 IF B$="N" THEN 140 120 PRINT "TYPE EITHER Y OR N - TRY AGAIN" 130 GOTO 90 140 PRINT "THE CORRECT ANSWER IS B." 145 GOTO 160 150 PRINT "CORRECT!" 160 END GETKEY is very similar to GET, except GETKEY will wait for a key to be pressed. 5.6 PROGRAMMING AIDS In earlier sections you learned how to make changes in your programs, and correct typing mistakes with {inst/del}. BASIC also provides other commands and functions which help you locate actual programming errors, and commands which you can use to make programming sessions flow more smoothly. 5.6.1 Entering Programs 5.6.1.1 AUTO C128 BASIC provides an auto-numbering process. You determine the increment for the line numbers. Say you want to number your program in the usual man- ner, by tens. Before you begin to program, while in DIRECT mode, type: AUTO 10 {return} The computer automatically numbers your programs by tens. After you enter a line and press the {return} key, the next line number appears, and the cur- sor is in the correct place for you to type the next statement. You can choose to have the computer number the commands with any increment; you might choose 5 or even 50. Just place the number after the word AUTO and press {return}. To turn off the auto-numbering feature, type AUTO with no increment, and press {return}. 5.6.1.2 RENUMBER If you write a program and later add statements to it, sometimes the line numbering can be awkward. Using the RENUMBER command you can change the line numbers to an even increment for part or all of your program. The RENUMBER command has several optional parameters, as listed below in brackets: RENUMBER [new starting line] [,[increment] [,old starting line]] The new starting line is what the first program line wil be numbered after the RENUMBER command is used. If you do not specify, the default is 10. The increment is the spacing between line numbers, and it also defaults to 10. The old starting line number is the line number where the renumbering is to begin. This feature allows you to renumber a portion of your program, rather than all of it. It defaults to the first line of the program. For example: RENUMBER 40,,80 tells the computer to renumber the program starting at line 80, in incre- ments of 10. Line 80 becomes line 40. Notice that this command, like AUTO, can only be executed in DIRECT mode. 5.6.1.3 DELETE You know how to delete program lines by typing the line number and pressing the {return} key. This can be tedious if you want to erase an entire por- tion of your program. The DELETE command can save you time because you can specify a range of program lines to erase all at once. For example: DELETE 10-50 will erase line 10, 50, and any in between. The use of DELETE is similar to that of LIST, in that you can specify a range of lines up to a given line, or following it, or a single line only, as in these examples: DELETE -120 erases all lines up to and including 120 DELETE 120- erases line 120 and any line after it DELETE 120 erases line 120 only 5.6.2 Identifying Problems in Your Programs When a program does not work the way you expected, an error message usual- ly occurs. Sometimes the messages are vague, however, and you still do not understand the problem. The Commodore 128 computer has several ways of helping you locate the problem. 5.6.2.1 HELP The Commodore 128 provides a HELP command that specifies the line in which a problem has occurred. To actuate the HELP command, just press the special {help} key on the row of keys located above the main keyboard. Type the following statement. It contains an intentional error, so type it just as is: 10?3;4:5;6 When you RUN this one-line program, the computer prints 3 and 4 as expec- ted, but then responds ?SYNTAX ERROR IN 10. Suppose you cannot see the error (a colon instead of a semicolon between 4 and 5). You press the {help} key. (You can also type HELP and press {return}.) The computer dis- plays the line again, but the 5;6 is highlighted to show the error is in that part of the line: 10?3;4:5;6 5.6.2.2 Error Trapping - The TRAP Command Usually, if an error occurs in a program, the program "crashes" (stops run- ning). At that point, you can press the {help} key to track down the error. However, you can use the BASIC 7.0 TRAP command to include an error- trapping capability within your program. The TRAP command advises you to locate and correct an error, then resume program operation. Usually, the error trapping function is set in the first line of a program: 5 TRAP 100 tells the computer that if an error occurs to go to a certain line (in this case, line 100). Line 100 appears at the end of the program, and sets up a contingency. Neither line is executed UNLESS there is an error. When an error occurs, the line with the TRAP statement is enacted, and control is directed to another part of the program. You can uses these statements to catch anticipated errors in entering data, resume execution, or return to text mode from graphics mode, to name just a few options. If you run the last DO/LOOP example (with doubled numbers) without an UNTIL statement, you can get an OVERFLOW error and the program crashes. You can prevent that from happening by adding two lines, one at the beginning and one at the end. For example, you might add these two lines: 5 TRAP 100 100 IF N<1 THEN END Even though N has been much greater than one for the entire program, the statement is not considered until there is an error. When the number "overflows" (is greater than the computer can accept), the TRAP statement goes into effect. Since N is greater than one, the program is directed to END (rather than crashing). Here is an example in which trapping is used to prevent a zero from being input for division. 10 TRAP 1000 100 INPUT "I CAN DIVIDE BY ANY NUMBER, GIVE ME A NUMBER TO DIVIDE";D 110 INPUT "WHAT SHOULD I DIVIDE IT BY";B 120 A=D/B 130 PRINT D;"DIVIDED BY ";B;"EQUALS ";A 140 END 1000 IF B=0 THEN PRINT"EVEN I CAN'T DO THAT" 1100 INPUT "PICK A DIFFERENT NUMBER";B:RESUME 120 Notice the RESUME in line 1100. This tells the computer to return to the line mentioned (in this case, 120) and continue. Depending on the error that was trapped, resuming executing may or may not be possible. For additional information on error trapping, see the error functions ERR$ (paragraph 18.8), EL and ER (paragraph 19.1), described in Chapter V, BASIC 7.0 Encyclopaedia. 5.6.2.3 Program Tracing - The TRON and TROFF Commands When a problem in a program occurs, or you do not get the result you ex- pect, it can be useful to methodically work through the program and do exactly what the computer would do. This process is called tracing. Draw variable boxes and update the values according to the program statements. Perform calculations and print results following each instruction. (All done by hand, using the program listing as a guideline.) This kind of tracing may show you, for example, that you have used a GOTO with an incorect line number, or calculated a result but never stored it in a variable. Many program errors can be located by pretending to be the com- puter, and following only one instruction at a time. Your C128 can perform a type of trace using the special commands TRON and TROFF (short for TRace ON and TRace OFF). When the program is run, with TRace ON, the computer prints the line numbers in the order they are exe- cuted. In this way, you may be able to see why your program is not giving the results you expected. Type any short program we have used so far, or use one of your own design. To activate trace mode, type TRON in DIRECT mode. When you run the program, notice how line numbers appear in brackets before any results are dis- played. Try to follow the line numbers and see how many steps the computer needed to arrive at a certain point. TRON will be more interesting if you pick a program with many branches, such as GOTO, GOSUB and IF-THEN-line number. Type TROFF to turn trace mode off before continuing. You do not have to trace an entire program. You can place TRON within a program as a line prior to the program section causing problems. Put the word TROFF as a program line after the troublesome section. When you run the program, only the lines between TRON and TROFF will be bracketed in the results. 5.7 WINDOWING Windows are a specific area on the screen that you define as your work- space. Everything you type (lines you type, listings of programs, etc.) after setting a window, appears within the window's bounderies, not affec- ting the screen outside the window area. The Commodore 128 provides two methods of creating windows: the WINDOW command and {esc} key functions. 5.7.1 Using the WINDOW Command to Create a Window The Commodore 128 BASIC 7.0 language features a command that allows you to create and manipulate windows: the WINDOW command. The command format is: WINDOW top-left column, top-left row, bottom-right column, bottom-right row [,clear option] The first two numbers after WINDOW specify the column and row number of where you want the top left corner of the window to be; the next two num- bers are the coordinates for the bottom right corner. Remember that the screen format (40- or 80-columns) dictates the acceptable range of these coordinates. You can also include a clear option with this command. If you add 1 onto the end of the command, the window screen area is cleared, as in this example: WINDOW 10,10,20,20,1 Here's a sample program that creates four windows on the screen, in either 40- or 80-column format. 10 SCNCLR :REM CLEAR SCREEN 20 WINDOW 0,0,39,24 :REM SET WINDOW TO FULL SCREEN 30 COLOR 0,13:COLOR 4,13 :REM SET 40 SCREEN TO MED. GREY 40 A$="ABCDEFGHIJKLMNOPQRST" 50 COLOR 5,5 :REM SELECT PURPLE TEXT 60 FOR I=1 TO 25 :REM FILL SCREEN WITH CHARACTERS 70 PRINT A$;A$:NEXT I 80 WINDOW 1,1,7,20 :REM DEFINE WINDOW 1 90 COLOR 5,3 :REM SELECT RED TEXT 100 PRINT CHR$(18);A$; :REM PRINT A$ IN REVERSE RED TEXT 110 WINDOW 15,15,39,20,1 :REM DEFINE SECOND WINDOW 120 COLOR 5,7 :REM SELECT BLUE TEXT 130 FOR I=1 TO 6:PRINT A$;: NEXT :REM FILL WINDOW 2 WITH CHARACTERS 140 WINDOW 30,1,39,22,1 :REM DEFINE THIRD WINDOW 150 COLOR 5,8:LIST :REM LIST IN YELLOW TEXT 160 WINDOW 5,5,33,18,1 :REM DEFINE FOURTH WINDOW 170 COLOR 5,2 :REM SELECT WHITE TEXT 180 PRINT A$:LIST :REM PRINT A$ AND LIST IN WHITE TEXT 190 END 5.7.2 Using the ESC Key to Create a Window To set a window with the {esc} (Escape) key, follow these steps: 1. Move the cursor to the screen position you want as the top left corner of the window. 2. Press the {esc} key and release it, and then press {t}. 3. Move the cursor to the position you want to be the bottom right corner of the window. 4. Press {esc} and release, then {b}. Your window is now set. You can manipulate the window and the text inside using the {esc} key. Screen editing functions, such as inserting and deleting text, scrolling, and changing the size of the window, can be performed by pressing {esc} followed by another key. To use a specific function, press {esc} and re- lease it. Then press any of the following keys listed for the desired func- tion: @ Erase everything from cursor to end of screen window. A Automatic insert mode. B Set the bottom right corner of the screen window (at the current cursor location) C Cancel automatic insert mode. D Delete current line. E Set cursor to non-flashing mode. F Set cursor to flashing mode. G Enable bell (by {ctrl g}). H Disable bell. I Insert a line. J Move to the beginning of the current line. K Move to the end of the current line. L Turn on scrolling. M Turn off scrolling. N Return to normal (non-reverse video) screen display (80-column only). O Cancel insert and quote modes. P Erase everything from the beginning of the line to the cursor. Q Erase everything from the cursor to the end of the line. R Reverse screen display (80-column only). S Change to block cursor. T Set the top left corner of the screen window (at the current cursor location). U Change to underline cursor. V Scroll screen up one line. W Scroll screen down one line. X Toggles between 40- and 80-columns Y Restore default TAB stops. Z Clear all TAB stops. Experiment with the {esc}ape key functions. You will probably find certain functions more useful than others. Note that you can use the usual {inst/del} key to perform text editing inside a window as well. When a window is set up, all screen output is continued to the "box" you have defined. If you want to clear the window area, press {shift} and {clr/home} together. To cancel the window, press the {clr/home} twice. The window is then restored to its maximum size and the cursor is placed in the top left corner of the screen. If you subsequently want to clear the screen, press {shift} and {clr/home} together. Windows are particularly useful in writing, listing and running programs, because they allow you to work in one area of the screen, while the rest of the screen stays as it is. 5.8 2 MHZ OPERATION 5.8.1 The FAST and SLOW Commands The 2 Mhz operation mode allows you to run non-graphic programs in 80- column format at twice the normal speed. You can switch normal and fast operation by using the FAST and SLOW commands. The FAST command places the Commodore 128 in 2 Mhz mode. The format of this command is: FAST The SLOW command returns the Commodore 128 to 1 Mhz mode. The format of this command is: SLOW 5.9 KEYS UNIQUE TO C128 MODE 5.9.1 Function Keys The four keys on the Commodore 128 keyboard on the right side above the numeric keypad are special function keys that let you save time by per- forming repetitive tasks with the stroke of just one key. The first key reads F1/F2, the second F3/F4, the third F5/F6 and the last F7/F8. You can use functions 1, 3, 5 and 7 by pressing the key itself. To use the func- tions 2, 4, 6 and 8, press {shift} and the function key. Here are the standard functions for each key: F1 F2 F3 F4 GRAPHIC DLOAD" DIRECTORY SCNCLR F5 F6 F7 F8 DSAVE" RUN LIST MONITOR Here is what each function involves: KEY 1 enters one of the GRAPHICs modes when you supply the number of the graphics area and press {return}. The GRAPHICs command is necessary for giving graphics commands such as CIRCLE or PAINT. For more on graphics, see Section 6. KEY 2 prints DLOAD" on the screen. All you do is enter the program name and hit {return} to load the program from disk, instead of typing out DLOAD yourself. KEY 3 lists a DIRECTORY of files on the disk in the disk drive. KEY 4 clears the screen using the SCNCLR command. KEY 5 prints DSAVE" on the screen. All you do is enter the program name, and press {return} to save the current program on disk. KEY 6 RUNs the current program. KEY 7 displays a LISTing of the current program. KEY 8 lets you enter the Machine Language Monitor. 5.9.2 Redefining Function Keys You can redefine or program any of these keys to perform a function that suits your needs. Redefining is easy, using the KEY command. You can re- define the keys from BASIC programs, or change them at any time in DIRECT mode. A situtation where you might want to redefine a function key is when you use a command frequently, and want to save time instead of repeatedly typing in the command. The new definitions are erased when you turn off the computer. You can redefine any of the function keys ans as many times as you want. If you want to reprogram the F7 function key to return you to text mode from high resolution or multicolor graphics modes, for example, you would use the key command in this fashion: KEY 7,"GRAPHIC 0" + CHR$(13) CHR$(13) is the ASCII code character for {return}. So when you press the {f7} key after redefining the key, what happens is the command "GRAPHIC 0" is automatically typed out and entered into the computer with {return}. Entire commands or series of commands may be assigned to a function key. 5.9.3 Other Keys Used in C128 Mode Only 5.9.3.1 HELP As noted previously, when you make an error in a program, your computer displays an error message to tell you what you did wrong. These error mes- sages are further explained in Appendix A of this manual. You can get more assistance with errors by using the {help} key. After an error message, press the {help} key to locate the exact point where the error occurred. When you press {help}, the line with the error is highlighted on the screen in reverse video (in 40-column) or underlined (in 80-column). For example: ?SYNTAX ERROR IN LINE 10 Your computer displays this. HELP You pressed the {help} key. 10 PRONT "COMMODORE COMPUTERS" The line with the mistake is high- lighted in reverse if in 40-column out- put or underlined in 80-column output. 5.9.3.2 NO SCROLL Press this key down to stop the text from scrolling when the cursor reaches the bottom of the screen. This key turns off scrolling until you press a key (any character key will do). 5.9.3.3 CAPS LOCK This key lets you type in all capital letters without using the {shift} key. The {caps lock} key locks in when you press it, and must be pressed again to be released. {caps lock} only effects the lettered keys. 5.9.3.4 40/80 DISPLAY The 40/80 key selects the main (default) screen format: either 40- or 80- column. The selected screen displays all the messages and output at power- up, or when the {reset} button, or the key combination {run/stop restore} is pressed. The 40/80 key may be used to set the display format only before turning on or resetting the computer. You cannot change modes with this key after the computer is turned on, unless you use the {reset} button at the right side of the computer, or the key combination {run/stop restore}. Sec- tion 8 provides an explanation of 40/80 column modes. 5.9.3.5 ALT The {alt} allows programs to assign a special meaning to a given key or set of keys. Unless the specific application program redefines it, holding down the {alt} key and any other key has no effect. 5.9.3.6 TAB This key works like the TAB key on a typewriter. It may be used to set or clear tab stops on the screen and to move the cursor to the columns where the tabs are set. 5.9.3.7 LINE FEED Pressing this key advances the cursor to the next line, similar to the {crsr down} key. *************************************************************************** FOR MORE INFORMATION This section covers only some of the concepts, keys and commands that make the Commodore 128 a special machine. You can find further explanation of the BASIC language in the BASIC 7.0 Encyclopaedia in Chapter V. SECTION 6 6. Color, Animation and Sprite Graphics Statements Unique to the C128 6.1 GRAPHICS OVERVIEW 6.1.1 Graphics Features 6.1.2 Command Summary 6.2 GRAPHICS PROGRAMMING ON THE COMMODORE 128 6.2.1 Choosing Colors Figure 6-1. Source Numbers. Figure 6-2. Color Numbers in 40-Column Format. Figure 6-3. Color Numbers in 80-Column Format. 6.2.2 Types of Screen Display 6.2.3 Selecting the Graphic Mode Figure 6-4. Graphic Modes. Figure 6-5. Clear Parameters. 6.2.4 Displaying Graphics on the Screen 6.2.4.1 Drawing a Circle - The CIRCLE Command Figure 6-6. Arrangement of x and y coordinates. 6.2.4.2 Drawing a Box - The BOX Command 6.2.4.3 Drawing Lines, Points and Other Shapes - The DRAW Command 6.2.4.4 Painting Outlined Areas - The PAINT Command 6.2.4.5 Displaying Characters on a Bit-Mapped-Screen - The CHAR Command 6.2.4.6 Creating a Graphics Sample Program 6.2.4.7 Changing the Size of Graphics Images - The SCALE Command 6.3 SPRITES: PROGRAMMABLE, MOVABLE OBJECT BLOCKS 6.3.1 Sprite Creation 6.3.2 Using Sprite Statements in a Program 6.3.3 Drawing the Sprite Image 6.3.4 Storing the Sprite Data with SSHAPE 6.3.5 Saving the Picture Data in a Sprite 6.3.6 Turning on Sprites 6.3.7 Moving Sprites with MOVSPR Figure 6-7. Visible Sprite coordinates. 6.3.8 Creating a Sprite Program 6.3.9 Sprite Definition Mode - The SPRDEF Command 6.3.10 Sprite Creation Procedure in SPRite DEFinition Mode 6.3.11 Adjoining Sprites 6.3.12 Storing Sprite Data in Binary Files Figure 6-8. Sprite Data Requirements. Figure 6-9. Memory Address Ranges for Sprite Storage. 6.3.12.1 BSAVE 6.3.12.2 BLOAD 6.1 GRAPHICS OVERVIEW In C128 mode, the Commodore 128 BASIC 7.0 language provides may new and powerful commands and statements that make graphics programming much easier. Each of the two screen formats available in C128 mode (40 columns and 80 columns) is controlled by a seperate microprocessor chip. The 40- column chip is called the Video Interface Controller, or VIC for short. The 80-column chip is referred to as the 8563, or Video Display Controller (VDC). The VIC chip, which provides 16 colors, controls all the highly de- tailed graphics called bit-mapped graphics. The 80-column chip, which also offers 16 colors, only displays characters and character graphics. Thus, all detailed graphic programs in C128 mode must be done in 40-column format. 6.1.1 Graphics Features As part of its impressive C128 mode graphics capabilities, the Commodore 128 provides: * 13 specialized graphics commands * 16 colors * Six different display modes * Eight programmable movable objects called SPRITES * Combined graphics/text displays All these formats can be integrated to provide a versatile, easy to use graphics system. 6.1.2 Command Summary Here is a brief explanation of each graphic command: BOX - Draws rectangles on the bit map screen. CHAR - Displays characters on the bit map screen. CIRCLE - Draws circles, ellipses and other geometric shapes on the bit map screen. COLOR - Selects colors for screen border, foreground, background and characters. DRAW - Draws lines and points on the bit map screen. GRAPHIC - Selects a screen display (text, bit map or split screen bit map). GSHAPE - Places the image stored into a text string variable on the bit map screen. PAINT - Fill areas on the bit map screen with color. SCALE - Sets the relative size of the images on the bit map screen. SPRDEF - Enters sprite definitions mode to edit sprites. SPRITE - Enables, colors, sets sprite screen priorities, and expands a sprite. SPRSAV - Stores a text string variable into a sprite storage area and vice versa. SSHAPE - Stores the image of a portion of the bit map screen into a text string variable. Most of these commands are described in the examples in this section. See Chapter V, BASIC 7.0 Encyclopaedia for detailed format and information on all graphic commands, and BASIC Functions for all graphic functions discus- sed in this section. 6.2 GRAPHICS PROGRAMMING ON THE COMMODORE 128 This following section describes a step-by-step graphics programming example. As you learn each graphics command, add it to a program, you will build as you read this section. When you are finished, you will have a com- plete graphics program. 6.2.1 Choosing Colors The first step in graphics programming is to choose colors for the screen background, foreground and border. To select colors, type: COLOR source, color where source is the section of the screen you are coloring (background, foreground, border, etc.) and color is the color code for the source. See Figure 6-1 for source numbers, Figure 6-2 for 40-column-format color numbers, and Figure 6-3 for 80-column-format color numbers. Number Source 0 40-column background color (VIC) 1 Foreground for the graphics screen (VIC) 2 Foreground color 1 for the multicolor screen (VIC) 3 Foreground color 2 for the multicolor screen (VIC) 4 40-column (VIC) border (whether in text or graphics mode) 5 Character color for 40- or 80-column text screen 6 80-column background color (8563) Figure 6-1. Source Numbers. Color Code Color Color Code Color 1 Black 9 Orange 2 White 10 Brown 3 Red 11 Light Red 4 Cyan 12 Dark Gray 5 Purple 13 Medium Gray 6 Green 14 Light Green 7 Blue 15 Light Blue 8 Yellow 16 Light Gray Figure 6-2. Color Numbers in 40-Column Format. Color Code Color Color Code Color 1 Black 9 Dark Purple 2 White 10 Brown 3 Dark Red 11 Light Red 4 Light Cyan 12 Dark Cyan 5 Light Purple 13 Medium Gray 6 Dark Green 14 Light Green 7 Dark Blue 15 Light Blue 8 Light Yellow 16 Light Gray Figure 6-3. Color Numbers in 80-Column Format. 6.2.2 Types of Screen Display Your C128 has several different ways of displaying information on the screen; the parameter "source" in the COLOR command pertains to different modes of screen display. The types of video display fall into three cate- gories. The first one is text display, which displays only characters, such as let- ters, numbers, special symbols and the graphics characters on the front faces of most C128 keys. The C128 can display text in both 40-column and 80-column screen formats. The second category of display mode is used for highly detailed graphics, such as pictures and intricate drawings. This type of display mode includes standard bit map mode and multicolor bit map mode. Bit map modes allow you to control each and every individual screen dot or pixel (picture element). This allows considerable detail in drawing pictures and other computer art. The 80 column display is intended to display text. The difference between text and bit map lies in the way in which each screen addresses and stores information. The text screen can only manipu- late entire characters, each of which covers an area of 8 by 8 pixels on your screen. The more powerful bit map mode exercises control over each and every pixel on your screen. The third type of screen display, split screen, is a mixture of the first two types. The split screen display outputs part of the screen as text and part in bit map mode (either standard or multicolor). The C128 is capable of this because it uses two seperate and different parts of the computer's memory to store the two screens: one part for the text, and the other for the graphics screen. Type the following short program: 10 COLOR 0,1:REM TEXT BACKGROUND COLOR = BLACK 20 COLOR 1,3:REM FOREGROUND COLOR FOR BIT MAP SCREEN = RED 30 COLOR 4,1:REM BORDER COLOR = BLACK This example colors the background black, the foreground red and the border black. 6.2.3 Selecting the Graphic Mode The next graphics programming step is to select the appropriate graphic mode. This is done using the GRAPHIC command, whose format is as follows: GRAPHIC where mode is a digit between 0 and 5, c is either an 0 or 1 and s is a value between 0 and 25. Figure 6-4 shows the values corresponding to the graphic modes. Mode Description 0 40-column (VIC) standard text 1 Standard bit map 2 Standard bit map (split screen) 3 Multicolor bit map 4 Multicolor bit map (split screen) 5 80-column text Figure 6-4. Graphic Modes. The parameter c stands for CLEAR. Figure 6-5 explains the values associated with CLEAR. C Value Description 0 Do not clear the graphics screen 1 Clear the graphics screen Figure 6-5. Clear Parameters. When you first run your program, you still want to clear the graphics screen for the first time, so set c equal to 1 in the GRAPHIC command. If you run it a second time, you may want your picture on the screen, instead of drawing it all over again. In this case, set c equal to 0. The s parameter specifies in split screen mode at which line number the text screen starts (line numbers start counting at zero, so line 10 is the eleventh line). If you omit the s parameter and select a split screen graphic mode (2 or 4), the text screen portion is displayed in rows 19 through 24; the portion above is bit mapped. The s parameter allows you to change the starting line of the text screen to any line on the screen, ranging from 1 through 24. A zero as s parameter indicates the screen is not split, and all is text. The final GRAPHIC command parameter is CLR. When you first issue a bit map GRAPHIC command, the Commodore 128 allocates a 9K area for your bit mapped screen information. 8K is reserved for the data for your bit map and the additional 1K is dedicated for the color data (video matrix). Since 9K is a substantial block of memory, you may want to use it again for another pur- pose later in your program. This is the purpose of CLR. It reorganizes the Commodore 128 memory and gives you back the 9K of memory that was dedicated to the bit map screen, so you can use it for other purposes. The format for CLR is as follows: GRAPHIC CLR When using this format, omit all other GRAPHIC command parameters. Add the following command to your program. It places the C128 in standard bit map mode and allocates an 8K bit map screen (and 1K of color data) for you to create graphics. 40 GRAPHIC 1,1 The second 1 in this command clears the bit map screen. If you do not want to clear the screen, change to second 1 to 0 (or omit it completely). NOTE: If you are in bit map mode and are unable to return to the text screen, press the {run/stop} and {restore} keys at the same time, or press the {esc} key followed by {x}, to return to the 80-column screen. Even though you can only display graphics with the VIC (40- column) chip, you can still write graphic programs in 80-column format. If you have the Commodore 1901 and you want to view your graphics program while it is running, you must select the 40-column output by switching the slide switch on the monitor to 40-column output. 6.2.4 Displaying Graphics on the Screen So far, you have selected a graphics mode and the colors you want. Now you can start displaying graphics on the screen. Start with a circle. 6.2.4.1 Drawing a Circle - The CIRCLE Command To draw a circle, use the CIRCLE statement as follows: 60 CIRCLE 1,160,100,40,40 This displays a circle in the center of the screen. The CIRCLE statement has nine parameters you can select to achieve various types of circles and geometric shapes. For example, by changing the numbers in the CIRCLE state- ment in line 60 you can obtain different size circles or variations in the shape (e.g. an oval). The CIRCLE statement adds power and versatility in programming Commodore 128 graphics in BASIC. The meaning of the numbers in the CIRCLE statement is explained under the CIRCLE listing in Chapter V, BASIC 7.0 Encyclopaedia. On your Commodore 128 screen, the point where x=0 and y=0 is at the top left corner of the screen and is referred as the HOME position. In stan- dard geometry however, the point where x and y equal 0 is in the bottom left corner of a graph. Figure 6-6 shows the arrangement of x (horizontal) and y (vertical) screen coordinates and the four points at the corners of the C128 screen. X Coordinate 0,0 +----------------------------------------+ 319,0 | | | | | | | | Y Coordinate | | | | | | | | 0,199 +----------------------------------------+ 319,199 Figure 6-6. Arrangement of x and y coordinates. Here's what the numbers mean: * 1 is the color source (in this case the foreground). * 160 is the starting x (horizontal) coordinate. * 100 is the starting y (vertical) coordinate. * 40 is the radius. 6.2.4.2 Drawing a Box - The BOX Command Now try a box. To draw a box, type: 80 BOX 1,20,60,100,140,0,1 This draws a solid box to the left of the circle. To find out what the numbers in the BOX statement mean, consult Commands and Statements. The BOX statement has seven parameters you can select and modify to produce dif- ferent types of boxes. Change the foreground color an draw the outline of a box to the right of the CIRCLE with these statements: 90 COLOR 1,9:REM CHANGE FOREGROUND COLOR 100 BOX 1,220,60,300,140,0,0 Experiment with the BOX statement to produce different variations of rec- tangles and boxes. 6.2.4.3 Drawing Lines, Points and Other Shapes - The DRAW Command You now know how to select graphic modes and colors and how to display cir- cles and boxes on the screen. Another graphics statement, DRAW, lets you draw lines on the screen just as you would with a pencil and a piece of paper. The following statement draws a line below the boxes and circle. 120 DRAW 1,20,180 TO 300,180 To erase a drawn line, change the source (1) in the DRAW statement to 0. The line is drawn with the background color which actually erases the line. Try using different coordinates and other sources to become accustomed to the DRAW statement. The DRAW statement can take another form that allows you to DRAW a line, change direction and then DRAW another line, so the lines are continuous. For example, try this statement: 130 DRAW 1,250,0 TO 30,0 TO 40,40 TO 250,0 This statement DRAWs a triangle on the top of the screen. The four pairs of number represent the x and y coordinates for the three points on the tri- angle. Notice the first and last coordinates are the same, since you must finish drawing the triangle on the same point you started. This form of DRAW statement gives you the power to DRAW almost any geometric shape, such as trapezoids, parallellograms and polygons. The DRAW statement also has a third form. You can DRAW one point at a time by specifying the starting x and y values as follows: 150 DRAW 1,160,160 As you can see, the DRAW statement has versatile features which give you the capability to create shapes, lines, points and a virtually unlimited number of computer drawings on your screen. 6.2.4.4 Painting Outlined Areas - The PAINT Command The DRAW statement allows you to outline areas on the screen. What if you want to fill areas within your drawn lines? That's where the PAINT state- ment comes in. The PAINT statement does exactly what the name implies - it fills in, or PAINTs, outlined areas with color. Just as a painter covers the canvas with paint, the PAINT statement covers the areas of the screen with one of the 16 colors. For example, type: 160 PAINT 1,150,97 Line 160 PAINTS the circle you have drawn in line 60. The PAINT statement fills a defined area until a specific boundery is detected according to which color source is indicated. When the Commodore 128 finishes PAINTing, it leaves the pixel cursor at the point where PAINTing began (in this case, at point 150,97). Here are two more PAINT statements: 180 PAINT 1,50,25 200 PAINT 1,255,125 Line 180 PAINTs the triangle and line 200 PAINTs the empty box. * IMPORTANT PAINTING TIP: If you choose a starting point in you PAINT statement which is already colored from the same color source, Com- modore 128 will not PAINT the area. You must choose a starting point which is entirely inside the boundery of the shape you want to PAINT. The starting point cannot be on the boundery line of a pixel that is colored from the same source. If you specify a PAINT coordinate that is the same color you are PAINTing, nothing happens. 6.2.4.5 Displaying Characters on a Bit-Mapped-Screen - The CHAR Command So far, the example program has operated in standard bit map mode. Bit map mode uses a completely different area of memory to store the screen data than text mode (the mode in which you enter programs and text). If you enter bit map mode, and try to type characters onto the screen, nothing happens. This is because the characters you are typing are being displayed on the text screen and you are looking at the bit map screen. Sometimes it is necessary to display characters on the bit map screen, when you are creating an plotting charts and graphs. The CHAR command is designed especially for this purpose. To display standard characters on a bit map screen, use the CHAR statement as follows: 220 CHAR 1,11,24,"GRAPHIC EXAMPLE" This displays the text "GRAPHIC EXAMPLE" starting at line 25, column 12. The CHAR command can also be used in text mode, however it is primarily designed for the bit map screen. 6.2.4.6 Creating a Graphics Sample Program So far, you have learned several graphic statements. Now tie the program together and see how the statements work at the same time. Here's how the program looks now. The color statements in lines 70, 110, 140, 170, 190 and 210 are added to display each object in a different color. 10 COLOR 0,1 :REM SELECT BACKGROUND COLOR 20 COLOR 1,3 :REM SELECT FOREGROUND COLOR 30 COLOR 4,1 :REM SELECT BORDER COLOR 40 GRAPHIC 1,1 :REM SELECT BIT MAP MODE 60 CIRCLE 1,160,100,40,40 :REM DRAW A CIRCLE 70 COLOR 1,6 :REM CHANGE FOREGROUND COLOR 80 BOX 1,20,60,100,140,0,1 :REM DRAW A BLOCK 90 COLOR 1,9 :REM CHANGE FOREGROUND COLOR 100 BOX 1,220,62,300,140,0,0 :REM DRAW A BOX 110 COLOR 1,9 :REM CHANGE FOREGROUND COLOR 120 DRAW 1,20,180 TO 300,180 :REM DRAW A LINE 130 DRAW 1,250,0 TO 30,0 TO 40,40 TO 250,0:REM DRAW A TRIANGLE 140 COLOR 1,15 :REM CHANGE FOREGROUND COLOR 150 DRAW 1,160,160 :REM DRAW A POINT 160 PAINT 1,150,97 :REM PAINT IN CIRCLE 170 COLOR 1,5 :REM CHANGE FOREGROUND COLOR 180 PAINT 1,50,25 :REM PAINT IN TRIANGLE 190 COLOR 1,7 :REM CHANGE FOREGROUND COLOR 200 PAINT 1,225,125 :REM PAINT IN EMPTY BOX 210 COLOR 1,11 :REM CHANGE FOREGROUND COLOR 220 CHAR 1,11,24,"GRAPHIC EXAMPLE" :REM DISPLAY TEXT 230 FOR I=1 TO 5000:NEXT:GRAPHIC 0,1:COLOR 1,2 Here's what the program does: * Lines 10 through 30 select a COLOR for the background, foreground and border, respectively. * Line 40 chooses a graphic mode. * Line 60 displays a CIRCLE. * Line 80 draws a colored-in BOX. * Line 100 draws a outline of a BOX. * Line 120 DRAWs a straight line at the bottom of the screen. * Line 130 DRAWs a triangle. * Line 150 DRAWs a single point below the circle. * Line 160 PAINTs the circle. * Line 180 PAINTs the triangle. * Line 200 PAINTs the empty box. * Line 220 prints the CHARacters "GRAPHICS EXAMPLE" at the bottom of the screen. * Line 230 delays the program so you can watch the graphics on the screen, switches back to text mode and colors the characters black. If you want the graphics to remain on the screen, omit the GRAPHIC state- ment in line 230. 6.2.4.7 Changing the Size of Graphics Images - The SCALE Command The Commodore 128 has another graphics statement which offers additional power to your graphics system. The SCALE statement offers the ability to scale down (reduce) the size of graphic images on your screen. The SCALE statement also accomplishes another task, which can be explained as fol- lows. In standard bit map mode, the 40 column screen has 320 horizontal coordi- nates and 200 vertical coordinates. In multicolor bit map mode, the 40 column screen has only half the horizontal resolution of standard bit map mode, which is 160 by 200. This reduction in resolution is compensated for by the additional capability of using two additional colors for a total of four colors, within an 8 by 8 character matrix. Standard bit map mode can only display two colors within an 8 by 8 character matrix. When you use the SCALE statement, both standard bit map and multicolor bit map modes have coordinates which are proportional to another. The scale ranges for 0 through a maximum of 1023 horizontal coordinates. This is true regardless of whether you are in standard bit map or multicolor mode. The SCALE your screen, use: SCALE 1,x,y and the screen coordinates range from 65535 whether you are in standard or multicolor hires mode. To turn off SCALEing, type: SCALE 0 and the coordinates return to their normal values. To see the effect of SCALEing on your program add in line 50: 50 SCALE 1,500,500 and RUN to see the effect. See Section 17, paragraph 17.81, of Chapter V for more details on the SCALE command. NOTE: SCALE comes after GRAPHIC and does not affect CHAR. Here are some additional example programs using the graphics statements you just learned: 10 COLOR 0,1 20 COLOR 1,8 30 COLOR 4,1 40 GRAPHIC 1,1 50 FOR I=80 TO 240 STEP 10 60 CIRCLE 1,I,100,75,75 70 NEXT I 80 COLOR 1,5 90 FOR I=80 TO 250 STEP 10 100 CIRCLE 1,I,100,50,50 110 NEXT I 120 COLOR 1,7 130 FOR I=50 TO 280 STEP 10 140 CIRCLE 1,I,100,25,25 150 NEXT I 160 FOR I=1 TO 7500:NEXT I 170 GRAPHIC 0,1:COLOR 1,2 10 GRAPHIC 1,1 20 COLOR 0,1 30 COLOR 4,1 40 FOR I=1 TO 50 50 Z=INT (((RND (1))*16)+1)*1 60 COLOR 1,Z 70 X=INT (((RND (1))*30)+1)*10 80 Y=INT (((RND (1))*20)+1)*10 90 U=INT (((RND (1))*30)+1)*10 100 V=INT (((RND (1))*20)+1)*10 110 DRAW 1,X,Y TO U,V 120 NEXT I 130 SCNCLR 140 GOTO 40 10 COLOR 4,7:COLOR 0,7:COLOR 1,1 20 GRAPHIC 1,1 30 FOR I=400 TO 1 STEP -5 40 DRAW 1,150,100 TO I,1 50 NEXT I 60 FOR I=1 TO 400 STEP 5 70 DRAW 1,150,100 TO 1,I 80 NEXT I 90 FOR I=40 TO 320 STEP 5 100 DRAW 1,150,100 TO I,320 110 NEXT I 120 FOR I=320 TO 30 STEP -5 130 DRAW 1,150,100 TO 320,I 140 NEXT I 150 FOR I=1 TO 7500:NEXT I 160 GRAPHIC 0,1:COLOR 1,1 Type the examples into your computer. RUN and SAVE them for future refe- rence. One of the best ways to learn programming is to study program exam- ples and see how the statements perform their functions. You'll soon be able to use graphics statements to create impressive graphics with your Commodore 128. If you need more information on any BASIC statement or command, consult Chapter V, BASIC 7.0 Encyclopaedia. You now have a set of graphic commands that allows you to create an almost unlimited number of graphics displays. But Commodore 128 graphics abilities do not end here. The Commodore 128 has another set of statements, known as SPRITE graphics, which make the creation and control of graphic images fast, easy and sophisticated. These high-level statements allow you to create sprites - movable graphic objects - the C128 has its own built-in SPRite DEFinition ability. These statements represent the new technology for creating and controlling sprites. Read the next section and take you first step in learning computer animation. 6.3 SPRITES: PROGRAMMABLE, MOVABLE OBJECT BLOCKS You already have learned about some of the Commodore 128's exceptional graphic capabilities. You've learned how to use the first set of high-level graphics statements to draw circles, boxes, lines and dots. You have also learned how to color the screen, switch graphic modes, paint objects on the screen and scale them. Now it's time to take the next step in graphics programming - sprite animation. If you have worked with the Commomdore 64, you already know something about sprites. For those of you who are not familiar with the subject, a sprite is a movable object that you can form into any shape or image. You can color sprites in up to one of 16 colors. Sprites can even be multicolor. The best part is that you can move them on the screen. Sprites open the door to computer animation. Here is the set of sprite statements you will learn about in this section: MOVSPR SPRDEF SPRITE SPRSAV SSHAPE 6.3.1 Sprite Creation The first step in programming sprites is designing the way the sprites look. For example, suppose you want to design a rocket ship or a racing car sprite. Before you can color or move the sprite, you must first design the image. In C128 mode, you can create sprites in these three ways: 1. Using SPRITE statements within a program 2. Using SPRite DEFinition mode (SPRDEF) 3. Using the same method as the Commodore 64 6.3.2 Using Sprite Statements in a Program This method uses built-in statements so you don't have to use any aids out- side your program to design your sprites as the other two methods require. This method uses some of the graphics statements you learned in the pre- vious section. Here's the general procedure. The details will be added as you progress. 1. Draw a picture with the graphics statements you learned in the last section, such as DRAW, CIRCLE, BOX and PAINT. Make the dimensions of the picture 24 pixels wide by 21 pixels tall in standard bit map mode or 12 pixels wide by 21 tall in multicolor bit map mode. 2. Use the SSHAPE statement to store the picture data into a string variable. 3. Tranfser the picture data from the string variable into a sprite with the SPRSAV statement. 4. Turn on the sprite, color it, select either standard or multicolor mode and expand it, all with the SPRITE statement. 5. Move the sprite with the MOVSPR statement. 6.3.3 Drawing the Sprite Image Here are the actual statements that perform the sprite operations. When you are finished with this section, you will have written your first sprite program. You'll be able to RUN the program as much as you like, and SAVE it for future reference. The first step is to draw a picture (24 by 21 pixels) on the screen using DRAW, CIRCLE, BOX or PAINT. This example is performed in standard bit map mode, using a black background. Here's the statements that set the graphic mode and color the screen background black. 5 COLOR 0,1:REM COLOR BACKGROUND BLACK 10 GRAPHIC 1,1:REM SET STND BIT MAP MODE The following statements DRAW a picture of a racing car in the upperleft corner of the screen. You already learned these statements in the last sec- tion. 5 COLOR 0,1:COLOR 4,1:COLOR 1,2 : REM SET COLORS 10 GRAPHIC 1,1 : REM SET HI-RES GRAPHIC MODE 15 BOX 1,2,2,45,45 : REM PICTURE FRAME 20 DRAW 1,17,10 TO 28,10 TO 26,30 : REM CAR BODY 22 DRAWTO 19,30 TO 17,10 : REM CAR BODY 24 BOX 1,11,10,15,18 : REM UPPER LEFT WHEEL 26 BOX 1,30,10,34,18 : REM UPPER RIGHT WHEEL 28 BOX 1,11,20,15,28 : REM LOWER LEFT WHEEL 30 BOX 1,30,20,34,28 : REM LOWER RIGHT WHEEL 32 DRAW 1,26,28 TO 19,28 : REM GRILLE 34 BOX 1,20,14,26,18,90,1 : REM CAR SEAT 36 BOX 1,150,35,195,40,90,1 : REM WHITE LINES 38 BOX 1,150,135,195,140,90,1 : REM WHITE LINES 40 BOX 1,150,215,195,220,90,1 : REM WHITE LINES 42 BOX 1,50,180,300,195 : REM FINISH OUTLINE 44 CHAR 1,18,23,"FINISH" : REM DISPLAY FINISH RUN the program. You have drawn a white racing car, enclosed in a box, in the upperleft corner of the screen. You have also drawn a raceway with a finish line at the bottom of the screen. At this point, the racing car is still only a stationary picture. The care isn't a sprite yet, but you have just completed the first step in sprite programming - creating the image. 6.3.4 Storing the Sprite Data with SSHAPE The next step is to save the picture into a text string. Here's the SSHAPE statement that does it: 45 SSHAPE A$,11,10,34,30:REM SAVE THE PICTURE IN A STRING The SSHAPE command stores the screen image (bit pattern) into a string variable for later processing, according to the specified screen coordi- nates. The numbers 11, 10, 34, 30 are the coordinates of the picture. You must position the coordinates in the correct place or the SSHAPE statement can't store your picture data correctly into the string variable A$. If you posi- tion the SSHAPE statement on an empty screen location, the data string is empty. When you later transfer it into a sprite, you'll realize there is no data present. Make sure you position the SSHAPE statement correctly on the correct coor- dinates. Also be sure to create the picture with the dimensions 24 pixels wide by 21 pixels tall, the size of a single sprite. The SSHAPE statement transforms the picture of the racing car into a data string that the computer interprets as picture data. The data string, A$, stores a string of zeros and ones in the computer's memory that make up the picture on the screen. As in all computer graphics, the computer has a way it can represent visual graphics with bits in its memory. Each dot on the screen, called a pixel, has a bit in the computer's memory that controls it. In standard bit map mode, if the bit in memory in equal to an 1 (on), then the pixel on the screen is turned on. If the controlling bit in memory is equal to 0 (off), then the pixel is turned off. 6.3.5 Saving the Picture Data in a Sprite Your picture is now stored in a string. The next step is to transfer the picture data from the data string (A$) into the sprite data area so you can turn it on and animate it. The statement that does this is SPRSAV. Here are the statements: 50 SPRSAV A$,1:REM STORE DATA STRING IN SPRITE 1 55 SPRSAV A$,2:REM STORE DATA STRING IN SPRITE 2 Your picture is transferred into sprite 1 and sprite 2. Both sprites have the same data, so they look exactly the same. You can't see the sprites yet, because you have to turn them on. 6.3.6 Turning on Sprites The SPRITE statement turns on a specific sprite (numbered 1 through 8), colors it, specifies its screen priority, expands the sprite's size and determines the type of sprite display. The screen priority refers to whether the sprite passes in front of or behind the objects on the screen. Sprites can be expanded to twice their original size in either horizontal or vertical directions. The type of sprite display determines whether the sprite is a standard bit mapped sprite or a multicolor bit mapped sprite. Here are the two statements that turn on sprites 1 and 2. 60 SPRITE 1,1,7,0,0,0,0:REM TURN ON SPR 1 70 SPRITE 2,1,3,0,0,0,0:REM TURN ON SPR 2 Here's what each of the numbers in the SPRITE statements mean: SPRITE #,O,C,P,X,Y,M # - Sprite number (1 to 8) O - Turn On (O=1) or Off (O=0) C - Color (1-16) P - Priority - if P=0, sprite is in front of objects on the screen - if P=1, sprite is behind objects on the screen X - if X=1, expands sprite in horizontal (X) direction if X=0, sprite in normal horizontal size Y - if Y=1, expands sprite in vertical (Y) direction if Y=0, sprite in normal vertical size M - if M=1, sprite is multicolor if M=0, sprite is standard As you can see, the SPRITE statement is powerful, giving you control over many sprite qualities. 6.3.7 Moving Sprites with MOVSPR Now that your sprite is on the screen, all you have to do is move it. The MOVSPR statement controls the motion of a sprite and allows you to animate it on the screen. The MOVSPR statement can be used in two ways. First, the MOVSPR statement can place a sprite at an absolute location on the screen, using the vertical and horizontal coordinates. Add the following state- ments to your program: 70 MOVSPR 1,240,70:REM POSITION SPRITE 1 - X=240,Y=70 80 MOVSPR 2,120,70:REM POSITION SPRITE 2 - X=120,Y=70 Line 70 positions sprite 1 at sprite coordinates (240,70). Line 80 places sprite 2 at sprite coordinates (120,70). You can also use the MOVSPR state- ment to move sprites relative to their original locations. For example, place sprites 1 and 2 at the coordinates as in lines 70 and 80. You want to move them from their original locations to another location on the screen. Use the following statements to move the sprites along a specific route on the screen: 85 MOVSPR 1,180 #6:REM MOVE SPRITE 1 FROM THE TOP TO THE BOTTOM 87 MOVSPR 2,180 #7:REM MOVE SPRITE 2 FROM THE TOP TO THE BOTTOM The first number in this statement is the sprite number. The second number is the direction expressed as the number of degrees to move in clockwise direction, relative to the original position of the sprite. The hash sign (#) signifies that the sprite is moved at the specific angle and speed relative to a starting position, instead of an absolute location, as in lines 70 and 80. The final number specifies the speed in which the sprite moves along its route on the screen, which ranges from 0 through 15. The MOVSPR command has two alternative forms. See Section 17, paragraph 17.59, of Chapter V, BASIC 7.0 Encyclopaedia for these notations. Sprites use an entirely different coordinate plane from bit map coordi- nates. The bit map coordinates range from points (0,0) (the top left cor- ner) to 319,199 (the bottom right corner). The visible sprite coordinates start at point (50,24) and end at point (250,344). The rest of the sprite coordinates are off the screen and are not visible, but the sprite still moves according to them. The OFF-screen locations allow sprites to move smoothly onto and off the screen. Figure 6-7 illustrates the sprite coor- dinates and the visible sprite positions. 0 ($00) 24 ($18) 296 ($128) 344 ($158) | | | | +----+ 8 ($08) 29 ($1D) | +--+ | | | | | | | 50 ($32) +--+-------------------------------------+----+----+ 50 ($32) | | | | | | +--+--+ | | | | VISIBLE VIEWING AREA | | | | +----+----+ | 40 COLUMNS | | 25 ROWS | 208 ($D0) +----+----+ | | | | | | | | +--+--+ 229 ($E5) | | | | | | 250 ($FA) +----+----+----------------------------------+--+--+ 250 ($FA) | | | | | | | | +--+ +----+ | | 488 ($1E8) | 320 ($140) 344 ($158) 24 ($18) Figure 6-7. Visible Sprite coordinates. Now RUN the entire program with all the steps included. You have just writ- ten you first sprite program. You have created a raceway with two racing cars. Try adding more cars and more objects on the screen. Experiment by drawing other sprites and include them in the raceway. You are now wel on the way in sprite programming. Use your imagination and think of other scenes and objects you can animate. Soon you can create all kinds of ani- mated computer "movies". 6.3.8 Creating a Sprite Program You now have a working sprite program example. Here's the complete program listing. 5 COLOR 0,1:COLOR 4,1:COLOR 1,2 : REM SET COLORS 10 GRAPHIC 1,1 : REM SET HI-RES GRAPHIC MODE 15 BOX 1,2,2,45,45 : REM PICTURE FRAME 20 DRAW 1,17,10 TO 28,10 TO 26,30 : REM CAR BODY 22 DRAWTO 19,30 TO 17,10 : REM CAR BODY 24 BOX 1,11,10,15,18 : REM UPPER LEFT WHEEL 26 BOX 1,30,10,34,18 : REM UPPER RIGHT WHEEL 28 BOX 1,11,20,15,28 : REM LOWER LEFT WHEEL 30 BOX 1,30,20,34,28 : REM LOWER RIGHT WHEEL 32 DRAW 1,26,28 TO 19,28 : REM GRILLE 34 BOX 1,20,14,26,18,90,1 : REM CAR SEAT 36 BOX 1,150,35,195,40,90,1 : REM WHITE LINES 38 BOX 1,150,135,195,140,90,1 : REM WHITE LINES 40 BOX 1,150,215,195,220,90,1 : REM WHITE LINES 42 BOX 1,50,180,300,195 : REM FINISH OUTLINE 44 CHAR 1,18,23,"FINISH" : REM DISPLAY FINISH 45 SSHAPE A$,11,10,34,30 : REM SAVE PICTURE INTO A$ 50 SPRSAV A$,1 : REM STORE A$ IN SPRITE 1 55 SPRSAV A$,2 : REM STORE A$ IN SPRITE 2 60 SPRITE 1,1,7,0,0,0,0 : REM TURN ON SPRITE 1 65 SPRITE 2,1,3,0,0,0,0 : REM TURN ON SPRITE 2 70 MOVSPR 1,240,70 : REM SPRITE 1 X=240, Y=70 80 MOVSPR 2,120,70 : REM SPRITE 2 X=120, Y=70 85 MOVSPR 1,180 #6 : REM MOV SPR 1 DOWN SCREEN 87 MOVSPR 2,180 #7 : REM MOV SPR 2 DOWN SCREEN 90 FOR I=1 TO 5000:NEXT I 99 GRAPHIC 0,1 Here's what the program does: * Line 5 COLORs the screen black. * Line 10 sets standard high resolution GRAPHIC mode. * Line 15 draws a BOX in the top left corner of the screen. * Lines 20 to 32 draw the racing car. * Lines 35 to 44 draw the racing car lanes and a finish line. * Line 45 transfers the picture data from the racing car into a string variable. * Lines 50 and 55 transfer the contents of the string variable into sprites 1 and 2. * Lines 60 and 65 turn on sprites 1 and 2. * Lines 70 and 80 positions the sprites at the top of the screen. * Lines 85 and 87 animate the sprites as though the two cars are racing each other across the finish line. In this section, you have learned how to create sprites, using the built-in C128 graphics statements such as DRAW and BOX. You learned how to control the sprites, using the Commodore 128 sprite statements. The Commodore has two other ways of creating sprites. The first is the built-in SPRite DEFinition ability, as described in the following paragraphs. The other method of creating sprites is similar to that used for the Commodore 64; see the C64 Programmer's Reference Guide for details on this sprite- creation technique. 6.3.9 Sprite Definition Mode - The SPRDEF Command The Commodore 128 has a built-in SPRite DEFinition mode which enables you to create sprites on your Commodore 128. You may be familiar with the Commodore 64 method of creating sprites, in which you required to either have an additional sprite editor, or design a sprite on a piece of graph paper and then READ the coded sprite DATA and POKE it into an available sprite block. With the new Commodore sprite definition command SPRDEF, you can construct and edit your own sprites in a special sprite work area. To enter the SPRDEF mode, type: SPRDEF and press {return}. The Commodore 128 displays a sprite grid on the 40 column screen. In addition, the computer displays the prompt: SPRITE NUMBER ? Enter a number between 1 and 8. The computer displays the corresponding sprite in the upper right corner of the screen. From now on, we will refer to the sprite grid as the work area. The work area has the dimensions of 24 characters wide by 21 characters tall. Each character position within the work area corresponds to 1 pixel within the sprite, since a sprite is 24 pixels wide by 21 pixels tall. While within the work area in SPRDEF mode, you have several editing com- mands available to you. Here's a summary of the commands: Sprite Defintion Mode Command Summary {clr} key - Erases the entire work area {m} key - Turns on/off multicolor sprite {ctrl} {1}-{8} - Selects sprite foreground color 1-8 {C=} {1}-{8} - Selects sprite foreground color 9-16 {1} key - Turns on pixels in background color {2} key - Turns on pixels in foreground color {3} key - Turns on areas in multicolor 1 {4} key - Turns on areas in multicolor 2 {a} key - Turns on/off automatic cursor movement {crsr} keys - Moves the cursor (+) within the work area {return} - moves cursor to the start of the next line {home} key - Moves cursor to the top left corner of the work area {x} key - Controls horizontal expansion {y} key - Controls vertical expansion {shift} {return} - Saves sprite from work area and returns to SPRITE NUMBER prompt {c} key - copies one sprite to another {stop} key - Turns off displayed sprite and returns to SPRITE NUMBER prompt without changing the sprite {return} key - (at the SPRITE NUMBER prompt) Exits SPRDEF mode 6.3.10 Sprite Creation Procedure in SPRite DEFinition Mode Here's the general procedure to create a sprite in SPRite DEFinition mode: 1. Clear the work area by pressing the {shift} and {clr/home} keys at the same time. 2. If you want a multicolor sprite, press the {m} key and an additional cursor appears next to the original one. Two cursors appear since multicolor mode actually turns on two pixels for every one in standard sprite mode. This is why multicolor mode is only half the horizontal resolution of standard hires mode. 3. Select a color for your sprite. For colors between {1} and {8}, hold down the {ctrl} key and press a key between {1} and {8}. To select color codes between 9 and 16, hold down the Commodore ({C=}) key and press a key between {1} and {8}. 4. Now your are ready to start creating the shape of your sprite. The num- bered keys {1} through {4} fill in the sprite and give it shape. For a single color sprite, use the {2} to fill a character position within the work area. Press the {1} key to erase what you have drawn with the {2} key. If you want to fill one character position at a time, press the {a} key. Now you have to move the cursor manually with the cursor keys. If you want the cursor to move automatically to the right while you hold it down, do not press the {a} key since it is already set to automatic cursor movement. As you fill in a character position within the work area, you can see the corresponding pixel in the displayed sprite turn on. Sprite editing occurs as soon as you edit the work area. In multicolor mode, the {3} key fills two character positions within the work area with the multicolor 1 color, the {4} key fills two character positions with the multicolor 2. You can turn off (color the pixel in the background color) filled areas within the work area with the {1} key. In multicolor mode, the {1} key turns off two character positions at a time. 5. While constructing your sprite, you can move freely in the work area without turning on or off any pixels using the {return}, {home} and cursor keys. 6. At any time, you may expand your sprite in both the vertical and hori- zontal directions. To expand vertically, press the {y} key. To expand horizontally, press the {x} key. To return to the normal size sprite display, press the {x} or {y} key again. When a key turns on AND off the same control, it is referred to as toggling, so the {x} and {y} keys toggle the vertical and horizontal expansion of the sprite. 7. When you are finished creating your sprite and happy with the way it looks, save it by holding down the {shift} key and pressing the {return} key. The Commodore 128 SAVEs the sprite data in the appro- priate sprite storage area. The displayed sprite in the upper right corner of the screen is turned off and control is returned to the SPRITE NUMBER prompt. If you want to display the original sprite in the work area again, enter the original sprite number. If you want to exit SPRite DEFinition mode, simply press {return} at the SPRITE NUMBER prompt. 8. You can copy one sprite into another with the {c} key. 9. If you do not want to SAVE your sprite, press the {stop} key. The Com- modore 128 turns off the displayed sprite and returns to the SPRITE NUMBER prompt. 10. To EXIT SPRite DEFinition mode, press the {return} key while the SPRITE NUMBER prompt is displayed on the screen when no sprite number follows it. You can exit under either of the following conditions: Immediately after you SAVE your sprite ({shift} {return}). Immediately after you press the {stop} key. Once you have created a sprite and have exited SPRite DEFinition mode, your sprite data is stored in the appropriate sprite storage area in the Com- modore 128's memory. Since you are now back in control of the BASIC lan- guage, you have to turn on your sprite in order to see it on the screen. To turn it on again, use the SPRITE command you learned previously. For example if you created sprite 1 in SPRDEF mode. To turn it on in BASIC, color it blue and expand it in both the X and Y directions enter this command: SPRITE 1,1,7,0,1,1,0 Now use the MOVSPR command to move it as follows: MOVSPR 1, 45 # 5 Now you know all about SPRDEF mode. First, create the sprite, save the sprite data and exit from SPRDEF mode to BASIC. Next turn on your sprite with the SPRITE command. Move it with the MOVSPR command. When you're finished programming, SAVE your sprite data in a binary file with the BSAVE command as follows: BSAVE "filename", B0, P3584 TO P4096 When you want to use the sprite data again from disk, load the previously BSAVEd binary file with the BLOAD command as follows: BLOAD "filename"[, B0, P3584] The portion in brackets is optional. BLOAD loads data into the address from which it was saved if the optional portion is not specified. Now you know the new method for creating sprites. So you can use the fol- lowing two methods: 1) SSHAPE, SPRSAV, SPRITE, MOVSPR, 2) SPRDEF mode. Experiment with both methods and master sprite animation. See paragraph 16.3.12, "Storing Sprite Data in Binary Files", later in this section for more information. 6.3.11 Adjoining Sprites You have learned how to create, color, turn on and animate a sprite. An oc- casion may arise when you want to create a picture that is too detailed or too large to fit into a single sprite. In this case, you can join two or more sprites so the picture is larger and more detailed than with a single sprite. By joining sprites, each one can move independently of one another. This gives you much more control over animation than with a single sprite. This section includes an example using adjoining sprites. Here's the gene- ral procedure (algorithm) for writing a program with two or more adjoining sprites. 1. Draw a picture on the screen with Commodore 128 graphics statements, such as DRAW, BOX and PAINT, just as you did in the raceway program in the last section. This time, make the picture twice as large as a single sprite with the dimensions 48 pixels wide by 21 pixels tall. 2. Use two SSHAPE statements to store the sprites into two separate data strings. Position the first SSHAPE statement coordinates over the 24 by 21 pixels area of the first half of the picture you drew. Then posi- tion the second SSHAPE statement coordinates over the second 24 by 21 pixel area. Make sure you store each half of the picture data in a dif- ferent string. For example, the first SSHAPE statement stores the first half of the picture into A$, and the second SSHAPE statement stores the second half of the picture into B$. 3. Transfer the picture data from each data string into a separate sprite with the SPRSAV statement. 4. Turn on each sprite with the SPRITE statement. 5. Position the sprites so the beginning of one sprite starts at the pixel next to where the first sprite ends. This is the step that actually joins the sprites. For example, draw a picture 48 by 21 pixels. Posi- tion the first sprite (1, for example) at location 10,10 with this statement: 100 MOVSPR 1,10,10 where the first number is the sprite number, the second number is the horizontal (X) coordinate and the third number is the vertical (Y) coordinate. Position the second sprite 24 pixels to the right of sprite 1 with this statement: 200 MOVSPR 2,34,10 At this point, the two sprites are displayed directly next to each other. They look exactly like the picture you drew in the beginning of the pro- gram, using the DRAW, BOX and PAINT statements. 6. Now you can move the sprites any way you like, again using the MOVSPR statement. You can move them together along the same path or in dif- ferent directions. As you learned in the last section, the MOVSPR statement allows you to move sprites to a specific location on the screen, or to a location relative to the sprite's original position. The following program is an example of adjoining sprites. The program creates an outer space environment. It draws stars, a planet and a space- craft similar to Apollo. The spacecraft is drawn, then stored into two data strings, A$ and B$. The front of the spaceship, the capsule, is stored in sprite 1. The back half of the spaceship, the retro rocket, is stored in sprite 2. The spacecraft flies slowly across the screen. Since it is tra- veling so slowly and is very far from Earth, it needs to be launched earth- ward with the retro rockets. After a while, the retro rockets fire and propel the capsule safely to Earth. Here's the program listing: 5 COLOR 4,1:COLOR 0,1:COLOR 1,2 :REM SELECT COLORS 10 GRAPHIC 1,1 :REM SET HIRES MODE 17 FOR I=1 TO 40 18 X=INT (RND (1)*320)+1 19 Y=INT (RND (1)*200)+1 21 DRAW 1,X,Y:NEXT I :REM DRAW STARS 22 BOX 0,0,5,70,40,,1 :REM CLEAR BOX 23 BOX 1,1,5,70,40:COLOR1,8 :REM BOX-IN SPACESHIP 24 CIRCLE1,190,90,35,25:PAINT1,190,95 :REM DRAW AND PAINT THE PLANET 25 FOR I=90 TO 96 STEP 3:CIRCLE 1,190,I,65,10:NEXT I 26 DRAW 1,10,17TO16,17TO32,10TO33,20TO32,30TO16,23TO10,23TO10,17 28 DRAW 1,19,24TO20,21TO27,25TO26,28 :REM BOTTOM WINDOW 35 DRAW 1,20,19TO20,17TO29,13TO30,18TO28,23TO20,19:REM TOP WINDOW 38 PAINT 1,13,20 :REM PAINT SPACESHIP 40 DRAW 1,34,10TO36,20TO34,30TO45,30TO46,20TO45,10TO34,10 42 DRAW 1,45,10TO51,12TO57,10TO57,17TO51,15TO46,17:REM ENGINE 1 43 DRAW 1,46,22TO51,24TO57,22TO57,29TO51,27TO45,29:REM ENGINE 2 44 PAINT1,40,15:PAINT1,47,12:PAINT1,47,26:DRAW0,45,30TO46,20TO45,10 45 DRAW 0,34,14TO44,14:DRAW 0,34,21TO44,21:DRAW 0,34,28TO44,28 47 SSHAPE A$,10,10,33,32 :REM SAVE SPRITE IN A$ 48 SSHAPE B$,34,10,57,32 :REM SAVE SPRITE IN B$ 50 SPRSAV A$,1 :REM SPRITE1 DATA 55 SPRSAV B$,2 :REM SPRITE2 DATA 60 SPRITE 1,1,3,0,0,0,0 :REM ENABLE SPRITE 1 IN RED 65 SPRITE 2,1,7,0,0,0,0 :REM ENABLE SPRITE 2 IN BLUE 82 MOVSPR 1,150,150 :REM POSITION SPRITE 1 83 MOVSPR 2,172,150 :REM POSITION SPRITE 2 85 MOVSPR 1,270 # 5 :REM ANIMATE SPRITE 1 87 MOVSPR 2,270 # 5 :REM ANIMATE SPRITE 2 90 FOR I=1 TO 5000:NEXT I 92 MOVSPR 1,150,150 :REM RETRO POSITION 93 MOVSPR 2,174,150 95 MOVSPR 1,270 #10 :REM SPLIT SPRITES 1 & 2 96 MOVSPR 2,90 #5 :REM 97 FOR I=1 TO 1200:NEXT I 98 SPRITE 2,0 :REM TURN OFF SPRITE 2 99 FOR I=1 TO 5000:NEXT I 100 GRAPHIC 0,1 :REM RETURN TO TEXT Here's an explanation of the program: * Line 5 COLORs the background black and the foreground white. * Line 10 selects standard high resolution mode and clears the hires screen. * Line 23 BOXes in a display area for the picture of the spacecraft in the top left corner of the screen. * Lines 17 through 21 DRAW the stars. * Line 24 draws and PAINTS the planet. * Line 25 draws the CIRCLEs around the planet. * Line 26 DRAWs the outline of the capsule portion of the spacecraft. * Line 28 DRAWs the bottom window of the space capsule. * Line 35 DRAWs the top window of the space capsule. * Line 38 PAINTs the space capsule white. * Line 40 DRAWs the outline of the retro rocket portion of the space- craft. * Lines 42 and 43 DRAW the retro rocket engines on the back of the spacecraft. * Line 44 PAINTs the retro rocket engines and DRAWs an outline of the back of the retro rocket in the background color. * Line 45 DRAWs lines on the retro rocket portion of the spacecraft in the background color. (At this point, you have displayed only pic- tures on the screen. You have not used any sprite statements, so your rocketship is not yet a sprite.) * Line 47 positions the SSHAPE coordinates above the first half (24 by 21 pixels) - of the capsule - of the spacecraft and stores it in a data string, A$. * Line 48 positions the SSHAPE coordinates above the second half (24 by 21 pixels) of the spacecraft and stores it in a data string, B$. * Line 50 transfers the data from A$ into sprite 1. * Line 55 transfers the data from B$ into sprite 2. * Line 60 turns on sprite 1 and colors it red. * Line 65 turns on sprite 2 and colors it blue. * Line 82 positions sprite 1 at coordinates (150,150). * Line 83 positions sprite 2 24 pixels to the right of the starting coordinate of sprite 1. * Lines 82 and 83 actually join the two sprites. * Lines 85 and 87 move the joined sprites across the screen. * Line 90 delays the program. This time delay is necessary for the sprites to complete the two trips across the screen. If you leave out the delay, the sprites do not have enough time to move across the screen. * Lines 92 and 93 position the sprites in the center of the screen, and prepare the spacecraft to fire the retro rockets. * Line 95 propels sprite 1, the space capsule, forward. The number 10 in line 95 specifies the speed at which the sprite moves. The speed ranges from 1, which is stop, to 15, which is lightning fast. * Line 96 moves the expired retro rocket portion of the spacecraft backwards and off the screen. * Line 97 is another time delay so the retro rocket, sprite 2, has time to move off the screen. * Line 98 turns off sprite 2, once it is off the screen. * Line 100 returns you to text mode. Working with adjoining sprites can be more interesting than working with a single sprite. The main points to remember are: (1) Make sure you position the SSHAPE coordinates at the correct locations on the screen, so you save the picture data properly; and (2) be certain to position the sprite coor- dinates in the correct location when you are joining them with the MOVSPR statement. In this example you positioned sprite 2 at a location 24 pixels to the right of sprite 1. Once you master the technique of joining two sprites, try more than two. The more sprites you join, the better the detail and animation will be in your programs. The C128 has two additional sprite commands, SPRCOLOR and COLLISION, which are not covered in the section. To learn about these commands, refer to Chapter V, BASIC 7.0 Encyclopaedia. 6.3.12 Storing Sprite Data in Binary Files NOTE: The following explanation assumes some knowledge of machine language, memory locations, binary files and object code files. The Commodore 128 has two new commands BLOAD and BSAVE, which make handling sprite data neat and easy. The "B" in BLOAD and BSAVE stands for BINARY. The BSAVE and BLOAD commands save and load binary files to and from disk. A binary file consists of either a portion of machine language program, or a collection of data within a specified address range. You may be familiar with the SAVE command within the built-in machine language monitor. when you use this SAVE command, the resulting file on disk is considered a binary file. A binary file is easier to work with than an object code file since you can load a binary file without any further preparation. An object code file must be loaded with a loader, as in the Commodore 64 Assembler Development System; then the SYSTEM command (SYS) must be used to execute it. When loading binary files, remember to load them in either of these two ways: LOAD "binary filename",8,1 or BLOAD "binary filename",B0,PStart where start is 3584 if you are loading sprite data files. In the first method you must specify the ,1 at the end or else the computer treats it as a BASIC program file and loads it at the beginning of BASIC text. The ,1 tells the computer to load the binary file into the same place from which it was stored. You're probably wondering what this has to do with sprites. Here's the con- nection. The Commodore 128 has a dedicated portion of memory ranging from the address 3584 ($0E00) throught 4095 ($0FFF), where sprite data is stored. This portion of memory takes up 512 bytes. As you know, a sprite is 24 pixels wide and 21 pixels tall. Each pixel requires one bit of memory. If the bit in a sprite is off (equal to 0), the corresponding pixel on the screen is considered off and takes the color of the background. If a pixel within a sprite is on (equal to 1), the corresponding pixel on the screen is turned on in the foreground color. The combination of zeroes and ones produce the image you see on the screen. Since a sprite is 24 by 21 pixels and each pixel requires a bit of storage in memory, one sprite uses 63 bytes of memory. See Figure 6-8 to understand the storage requirements for a sprite's data. 12345678 12345678 12345678 1 ........ ........ ........ 2 ........ ........ ........ 3 ........ ........ ........ 4 ........ ........ ........ 5 ........ ........ ........ 6 ........ ........ ........ 7 ........ ........ ........ 8 ........ ........ ........ 9 ........ ........ ........ 10 ........ ........ ........ 11 ........ ........ ........ 12 ........ ........ ........ 13 ........ ........ ........ 14 ........ ........ ........ 15 ........ ........ ........ 16 ........ ........ ........ 17 ........ ........ ........ 18 ........ ........ ........ 19 ........ ........ ........ 20 ........ ........ ........ 21 ........ ........ ........ Each Row = 24 bits = 3 bytes Figure 6-8. Sprite Data Requirements. A sprite requires 63 bytes of data. Each sprite block is actually made up of 64 bytes; the extra byte is not used. Since the Commodore 128 has eight sprites and each one consists of an 64-byte sprite block, the computer needs 512 (8 x 64) bytes to represent the data of all eight sprite images. The entire area where all eight sprite blocks reside starts at memory loca- tion 3584 ($0E00) and ends at location 4095 ($0FFF). Figure 6-9 lists the memory address ranges where each individual sprite stores its data: $0FFF (4095 decimal) ]- Sprite 8 $0FC0 ]- Sprite 7 $0F80 ]- Sprite 6 $0F40 ]- Sprite 5 $0F00 ]- Sprite 4 $0EC0 ]- Sprite 3 $0E80 ]- Sprite 2 $0E40 ]- Sprite 1 $0E00 (3584 Decimal) Figure 6-9. Memory Address Ranges for Sprite Storage. 6.3.12.1 BSAVE Once you exit from the SPRDEF mode, you can save your sprite data in binary sprite files. This way, you can load any collection of sprites back into the Commodore 128 neatly and easily. Use this command to save your sprite data into a binary file: BSAVE "filename", B0, P3584 TO P4096 The "B0" specifies that you are saving the sprite data from bank 0. The para- meters P3584 TO P4096 signify you are saving the address range 3584 ($0E00) through 4095 ($0FFF), which is the range where all the sprite data is stored. You do not have to define all of the sprites when you BSAVE them. The sprites you do define are BSAVEd from the correct sprite block. The unde- fined sprites are also BSAVEd in the binary file from the appropriate sprite block, but they do not matter to the computer. It is easier to BSAVE the entire 512 bytes of all eight sprites, regardless if all the sprites are used, rather than BSAVE each sprite block individually. 6.3.12.2 BLOAD Later on, when you want to use the sprites again, just BLOAD the entire 512 bytes for all of the sprites into the range starting at 3584 ($0E00) and ending at 4095 ($0FFF). Here's the command to accomplish this: BLOAD "filename"[, B0, P3584] Use the same filename which you BSAVEd your original sprite data. The B0 stands for bank number 0 and the P3584 specifies the starting location where the binary sprite data is loaded. The last two parameters are optional. *************************************************************************** In this section you have seen how much the new Commodore 7.0 BASIC commands can simplify the usually complex process of creating and animating graphic images. The next section describes some other new BASIC 7.0 commands that do the same for music and sound. SECTION 7 7. Sound and Music in C128 Mode 7.1 INTRODUCTION 7.2 THE SOUND STATEMENT 7.2.1 Writing a SOUND Program 7.2.2 Random Sounds 7.3 ADVANCED SOUND AND MUSIC IN C128 MODE 7.3.1 A brief background: The Characteristics of Sound Figure 7-1. Sine Wave. Figure 7-2. Frequencies and harmonics. Figure 7-3. Sound Waveform Types. 7.3.2 Making Music on the Commodore 128 7.3.2.1 The ENVELOPE Statement Figure 7-4. ADSR Phases. Figure 7-5. Default Parameters for ENVELOPE Statement. 7.3.2.2 The TEMPO Statement 7.3.2.3 The PLAY Statement Figure 7-6. Sound Synthesizer Control Characters. 7.3.2.4 The SID Filter Figure 7-7. Low-pass Filter. Figure 7-8. High-pass Filter. Figure 7-9. Band-pass Filter. 7.3.2.5 The FILTER Statement 7.3.3 Tying your Music Program Together 7.3.4 Advanced Filtering Figure 7-10. Notch Reject Filter. 7.4 CODING A SONG FROM SHEET MUSIC Figure 7-11. Musical Staff. Figure 7-12. Part of Bach's Invention 13. 7.1 INTRODUCTION The Commodore 128 has one of the most sophisticated built-in sound synthe- sizers available in a microcomputer. The synthesizer, called Sound Inter- face Device (SID), is a chip capable of producing three independent voices (sounds) simultaneously. Each of the voices can be played in one of four types of sounds, called waveforms. The SID chip also has programmable Attack, Decay, Sustain and Release (ADSR) parameters. These parameters de- fine the quality of a sound. In addition, the synthesizer has a filter you can use to choose certain sounds. In this section you will learn how to control these parameters to produce almost any kind of sound. To make it easy for you to select and manipulate the many capabilities of the SID chip, Commodore has develloped new and powerful BASIC music state- ments. Here are the new sound and music statements available on the Commodore 128: SOUND ENVELOPE VOL TEMPO PLAY FILTER This section explains these sound statements, one at a time, in the process constructing a sample musical program. When you are finished with this sec- tion, you will know the ingredients that go into a musical program. You'll be able to expand on the example and write programs that play intricate musical compositions. Eventually, you'll be able to program your own musi- cal scores, make your own sound effects and play works of the great clas- sical masters such as Beethoven and contemporary artists like the Beatles. You can even add computer-generated music to your graphics programs to create your own "videos." 7.2 THE SOUND STATEMENT The SOUND statement is designed primarily for quick and easy sound effects in your programs. You will learn a more intricate way of playing complete musical arragements with the other sound statements later in this section. The format for the SOUND statement is as follows: SOUND vc, freq, dur [, dir [, min [, sv [, wf [, pw]]]]] Here's what the parameters mean: VC - Select voice 1, 2 or 3 FREQ - Set the frequency level of sound (0-65535) DUR - Set duration of the sound (in sixtieths of a second) DIR - Set the direction in which the sound is incremented/decre- mented: 0 = Increment the frequency upward 1 = Decrement the frequency downward 2 = Oscillate the frequency up and down MIN - Select the minimum frequency (0-65535) if the sweep (DIR) is specified SV - Choose the step value for the sweep (0-65535) WF - Select the waveform (0-3): 0 = Triangle 1 = Sawtooth 2 = Variable Pulse (square) 3 = White Noise PW - Set the pulse width, the width of the variable pulse waveform Note that the DIR, MIN, SV and PW parameters are optional. The first parameter (VC) in the SOUND statement selects which voice will be played. The second parameter (FREQ) determines the frequency of the sound, which ranges from 0 through 65535. The third setting (DUR) is measured in 60ths of a second. If you want to play a sound for one second, set the duration to 60, since 60 times 1/60 equals 1. To play the sound for two seconds, specify the duration to be 120. To play the sound ten seconds, make the duration 600, and so on. The fourth parameter (DIR) selects the direction in which the frequency or the sound is incremented or decremented. This is referred to as the sweep. The fifth setting (MIN) sets the minimum frequency where the sweep begins. The sixth parameter (SV) is the step value of the sweep. It is similar to the step value in a FOR... NEXT loop. If the DIR, MIN and SV values are specified in the SOUND command, the sound is played first at the original level specified by the freq parameter. Then the synthesizer sweeps through and plays each level of the entire range of frequency values starting at the min frequency. The sweep is incremented or decremented by the step value (SV) and the frequency is played at the new level. The seventh parameter (WF) in the SOUND command selects the waveform for the sound. (Waveforms are explained in detail in paragraph titled, "Ad- vanced Sound and Music in C128 Mode.") The final setting in the SOUND command determines the width of the pulse waveform if it is selected as the waveform parameter. (See the discussion in paragraph 7.3, "Advanced Sound and Music in C128 Mode", for an illustration of the pulse waveform.) 7.2.1 Writing a SOUND Program Now it's time to write your first SOUND program. Here's an example of the SOUND statement: 10 VOL 5 20 SOUND 1,4096,60 RUN this program. The Commodore 128 plays a short beep. You must set the volume before you can play the sound statement, so line 10 sets the VOLume of the sound chip. Line 20 plays voice 1 at a frequency of 4096 for a dura- tion of 1 second (60 times 1/60). Change the frequency with this statement: 30 SOUND 1,8192,60 Notice line 30 plays a higher tone than line 20. This shows the direct relationship between the frequency setting and the actual frequency of the sound. As you increase the frequency setting, the Commodore 128 increases the pitch of the tone. Now try this statement: 40 SOUND 1,0,60 This shows that a FREQ value of 0 plays the lowest frequency (which is so low it is inaudible). A FREQ value of 65535 plays the highest possible frequency. Now try placing the sound statement within a FOR... NEXT loop. This allows you to play the complete range of frequencies within the loop. Add these statements to your program: 50 FOR I=1 TO 65535 STEP 100 60 SOUND 1,I,1 70 NEXT This program segment plays the variable pulse waveform in the range of frequencies from 1 to 65535, in increments of 100, from the lowest frequen- cy to the highest. If you don't specify the waveform, the computer selects the default value of waveform 2, the variable pulse waveform. Now change the waveform with the following program line (60) and try the program again: 60 SOUND 1,I,1,0,0,0,0,0 Now the program plays voice 1, using the triangle waveform, for the range of frequency between 1 and 65535 in increments of 100. This sounds like a typical sound effect in popular arcade games. Try waveform 1, the sawtooth waveform, and see how it sounds with this line: 60 SOUND 1,I,1,0,0,0,1,0 The sawtooth waveform sounds similar to the triangle waveform though it has less buzz. Finally, try the white noise waveform (3). Substitute line 60 for this line: 60 SOUND 1,I,1,0,0,0,3,0 Now the program loop plays the white noise generator for the entire range of frequencies. As the frequency increases in the loop the pitch increases and sounds like a rocket taking off. Notice that so far we have not specified all of the parameters in the SOUND statement. Take line 60 for example: 60 SOUND 1,I,1,0,0,0,3,0 The three zeros following 1,I,1 pertain to the sweep parameters within the SOUND statement. Since none of the parameters is specified, the SOUND does not sweep. Add this line to your program: 100 SOUND 1, 49152, 240, 1, 0, 100, 1, 0 ^ ^ ^ ^ ^ ^ ^ ^ | | | | | | | | Voice ---------+ | | | | | | | Frequency ----------+ | | | | | | Duration -----------------+ | | | | | Sweep Direction --------------+ | | | | Minimum Sweep Frequency ---------+ | | | Step Value for Sweep ----------------+ | | Waveform --------------------------------+ | Pulse Width for variable width | waveform --------------------------------+ Line 100 starts the sweep frequency at 49152 and decrements the sweep by 100 in the downward direction, until it reaches the minimum sweep frequency at 0. Voice 1, using the sawtooth waveform (#1), plays each SOUND for four seconds (240 * 1/60 s). Line 100 sounds like a bomb dropping, as in may "shoot 'em up" arcade games. Now try changing some of the parameters in line 100. For instance, change the direction of the sweep to 2 (oscilate); change the minimum frequency of the sweep to 32768; and increase the step value to 3000. Your new SOUND command looks like this: 110 SOUND 1,49152,240,2,32768,3000,1 Line 110 makes a siren sound as though the police were right on your tail. For a more pleasant sound, try this: 110 SOUND 1,65535,250,0,32768,3000,2,2600 This should remind you of a popular space-age TV show, when the space crew unleashed their futuristic weapons on the unsuspecting aliens. Until now, you have been programming only one voice. You can produce inter- esting sound effects with the SOUND statement using up to three voices. Experiment and create a program which utilizes all three voices. Here's a sample program that will help you understand how to program the Commodore 128 synthesizer chip. The program, when RUN, asks for each para- meter, and then plays the sound. Here's the program listing. Type it into your computer and RUN it. 10 SCNCLR:PRINT " SOUND PLAYER":PRINT:PRINT:PRINT 20 PRINT " INPUT SOUND PARAMETERS TO PLAY":PRINT:PRINT 30 INPUT "VOICE (1-3)";V 40 INPUT "FREQUENCY (0-65535)";F 50 INPUT "DURATION (0-32767)";D 60 INPUT "DO YOU WANT TO SPECIFY OPTIONAL PARAMETERS Y/N";B$:PRINT 70 IF B$="N" THEN 130 80 INPUT "SWEEP DIRECTION (0=UP,1=DOWN,2=OSCILL)";DIR 90 INPUT "MINIMUM SWEEP FREQUENCY (0-65535)";M 100 INPUT "SWEEP STEP VALUE (0-32767)";S 110 INPUT "WAVEFORM (0=TRI,1=SAW,2=VAR PUL,3=NOISE)";W 120 IF W=2 THEN INPUT "PULSE WIDTH (0-4096)";P 130 SOUND V,F,D,DIR,M,S,W,P 140 INPUT"DO YOU WANT TO HEAR THE SOUND AGAIN Y/N";A$ 150 IF A$="Y" THEN 130 160 RUN Here's a quick explanation of the program. Lines 10 and 20 PRINT the intro- ductory messages on the screen. Lines 30 through 50 INPUT the voice, frequency and duration parameters. Line 60 asks if you want to enter the optional SOUND parameters, such as the sweep settings and waveform. If you don't want to specify these parameters, press the {n} and then the {return} key and the program jumps to line 130 and plays the sound. I you do want to specify the optional SOUND settings, press the {y} and then the {return} key and the program continues with line 80. Lines 80 through 110 specify the sweep direction, minimum sweep frequency, sweep step value and wave- form. Line 120 INPUTs the pulse width of the variable pulse waveform only if waveform 2 (variable pulse) is selected. Line 130 plays the SOUND accor- ding to the parameters that you specified earlier in the program. Line 140 asks if you want to hear the SOUND again. If you do, press the {y} and then the {return} key. If you did, program control is returned to line 130 and the program plays the SOUND again. If you press any other key as the {y} key, the program continues with line 160. Line 160 reruns the pro- gram. To stop the Sound Player program, press the {run/stop} and {restore} keys at the same time. 7.2.2 Random Sounds The following program generates random sounds using the RND function. Each SOUND parameter is calculated randomly. Type the program into your computer and SAVE it and RUN it. This program illustrates how many thousands of sounds you can produce by specifying various combinations of the SOUND parameters. 10 PRINT "VC FRQ DIR MIN SV WF PW ":VOL 5 20 PRINT "---------------------------------" 30 V=INT (RND (1)*3)+1 :REM VOICE 40 F=INT (RND (1)*65536) :REM FREQUENCY 50 D=INT (RND (1)*240) :REM DURATION 60 DIR=INT (RND(1)*3) :REM STEP DIRECTION 70 M=INT (RND (1)*65536) :REM MINIMUM FREQUENCY 80 S=INT (RND (1)*32678) :REM STEP VALUE 90 W=INT (RND (1)*4) :REM WAVEFORM 100 P=INT (RND (1)*4096) :REM PULSE WIDTH 110 PRINT V;F;DIR;M;S;W;P:PRINT:PRINT :REM DISPLAY VALUE 120 SOUND V,F,D,DIR,M,S,W,P :REM PLAY SOUND 130 SLEEP 4 :REM WAIT A BIT 140 SOUND V,0,0,DIR,0,0,W,P :REM SWITCH SOUND OFF 150 GOTO 10 Lines 10 and 20 PRINT parameter column headings and the underline. Lines 30 through 100 calculate each SOUND parameter within its specific range. For example, line 30 calculates the voice number as follows: 30 V = INT(RND(1)*3)+1 The notation RND(1) specifies the seed value of the random number. The seed is the base number generated by the computer. The 1 tells the computer to generate a new seed each time the command is encountered. Since the Commo- dore 128 has three voices, the notation * 3 tells the computer to generate a random number within the range 0 through 3. Notice however there is no voice 0, so the + 1 tells the computer to generate a random number such that 1 <= Number < 4. The procedure for generating a random number in a specific range is to multiply the given random number times the maximum value of the parameter (in this case, 3). If the minimum value of the para- meter is greater than zero, add to the random number a value that will specify the minimum value of the range of numbers you want to generate (in this case, 1). For instance, line 40 generates a random number such that 0 <= Number < 65535. Since the minimum value is zero in this case, you do not need to add a value to the generated random number. Line 110 PRINTs the values of the parameters. Line 120 plays the SOUND specified by the random numbers generated in lines 30 through 100. Line 130 delays the program for 4 seconds while the sound is playing. Line 140 turns off the SOUND (after the 4 seconds delay). All sounds generated by this program are all turned off after 4 seconds with line 140. Finally, line 150 returns control to line 10, and the process is repeated until you press the {run/stop} and {restore} keys at the same time. So far you have experimented with sample programs using only the SOUND statement. Although you can use the SOUND statement to play musical scores, it is best suited for quick and easy sound effects like the ones in the dogfight program. The Commodore 128 has other statements designed speci- fically for song playing. The following paragraphs describe the advanced sound and music statements that enable you to play complex musical scores and arrangements with your Commodore 128 synthesizer. 7.3 ADVANCED SOUND AND MUSIC IN C128 MODE 7.3.1 A brief background: The Characteristics of Sound Every sound you hear is actually a sound wave traveling through the air. Like any wave, a sound (sine) wave can be represented graphically and mathematically (see Figure 7-1). + + + + + + / \ / \ ./.......\......./.......\. \ / + + + Figure 7-1. Sine Wave. The sound wave moves (oscillates) at a particular rate (frequency) which determines the overall pitch (the highness or lowness of the sound). The sound is also made up of harmonics, which are accompanying multiples of the the overall frequency of the sound or note. The combination of these harmonic sound waves give the note its qualities, called timbre. Figure 7-2 shows the relationship of basic sound frequencies and harmonics. [FIGURE IS MISSING] Figure 7-2. Frequencies and harmonics. The timbre of a musical tone (i.e. the way a tone sounds) is determined by the tone's waveform. The Commodore 128 can generate four types of wave- forms: triangle, sawtooth, variable pulse and noise. See Figure 7-3 for a graphic representation of these four waveforms. + + / \ / \ / \ / \ / \ / \ TRIANGLE ./.......\......./.......\. \ / \ / \ / + + + + /| /| /| / | / | / | / | / | / | SAWTOOTH ./...|.../...|.../...|..... | / | / | / | / | / | / |/ |/ |/ + + + +----+ +----+ +----+ | | | | | | | | | | | | | | | | | | | | | | VARIABLE .|....|..|....|..|....|..|. PULSE | | | | | | | | | | | | | | | | | | | | | | +--+ +--+ +--+ <--> PULSE WIDTH . . . . . . . . . . . . NOISE ........................... . . . . . . . . . . . Figure 7-3. Sound Waveform Types. 7.3.2 Making Music on the Commodore 128 7.3.2.1 The ENVELOPE Statement The volume of a sound changes throughout the duration of the note, from when you first hear it until it is no longer audible. These volume quali- ties are referred to as Attack, Decay, Sustain and Release (ADSR). Attack is the rate at which a musical note reaches its peak volume. Decay is the rate at which a musical not decreases from its peak volume to its midranged (sustain) level. Sustain is the level at which a musical note is played at its midranged volume. Release is the rate at which a musical note decreases from its sustain level to zero volume. The ENVELOPE generator controls the ADSR parameters of sound. See Figure 7-4 for a graphical representation of ADSR. The Commodore 128 can change each ADSR parameter to 16 different rates. This gives you absolute flexibility over the envelope generator and the resulting properties of the volume when the sound is originated. + / \ / \ / \ SUSTAIN LEVEL . ./. . . .+--------+ / \ / \ / \ | | | | | | A | D | S | R | Figure 7-4. ADSR Phases. One of the most powerful Commodore 128 sound statements - the one that con- trols the ADSR and waveform - is the ENVELOPE statement. The ENVELOPE statement sets the different controls in the synthesizer chip which makes each sound unique. The ENVELOPE gives you the power to manipulate the SID synthesizer. With ENVELOPE, you can select particular ADSR settings and choose a waveform for you own music and sound effects. The format for the ENVELOPE statement is as follows: ENVELOPE e[,a[,d[,s[,r[,wf[,pw]]]]]] Here's what the letters mean: e - envelope number (0-9). a - attack rate (0-15) d - decay rate (0-15) s - sustain level (0-15) r - release rate (0-15) wf - waveform - 0 = triangle 1 = sawtooth 2 = pulse (square) 3 = noise 4 = ring modulation pw - pulse width (0-4095) Here are the definitions of the parameters not previously defined: Envelope - The properties of a musical note specified by the waveform and the attack, decay, sustain and release setting of the note. For example, the envelope for a guitar not has a different ADSR and waveform than a flute. Waveform - The type of sound wave created by the combination of accom- panying musical harmonics of a tone. The accompanying harmonic sound waves are multiples of, and are based on the overall frequency of the tone. The qualities of the tone generated by each waveform are recognizably different from one another and are represented graphically in Figure 7-3. Pulse width - The length of time between notes, generated by pulse waveform. Now you can realize the power of the ENVELOPE statement. It controls most of the musical qualities of the notes being played by the sound synthe- sizer. The Commodore 128 has 10 predefined envelopes for 10 different musical instruments. In using the predefined envelopes you do not have to specify the ADSR parameters, waveform and pulse width settings - this is already done for you. All you have to do is specify the envelope number. The rest of the parameters are chose automatically by the Commodore 128. Here are the preselected envelopes for different types of musical instru- ments: Envelope Wave- Number Instrument Attack Decay Sustain Release form Width 0 Piano 0 9 0 0 2 1536 1 Accordion 12 0 12 0 1 2 Calliope 0 0 15 0 0 3 Drum 0 5 5 0 3 4 Flute 9 4 4 0 0 5 Guitar 0 9 2 1 1 6 Harpsicord 0 9 0 0 2 512 7 Organ 0 9 9 0 2 2048 8 Trumpet 8 9 4 1 2 512 9 Xylophone 0 9 0 0 0 Figure 7-5. Default Parameters for ENVELOPE Statement. Now that you have a little background on the ENVELOPE statement, begin an- other example by entering this statement into your Commodore 128: 10 ENVELOPE 0, 5, 9, 2, 2, 2, 1700 This ENVELOPE statement redefines the default piano envelope (0) to the following: Attack = 5, Decay = 9, Sustain=2, Release=2, waveform remains the same (2) and pulse width of the variable pulse waveform is now 1700. The piano envelope will not take on these properties until it is selected by a PLAY statement, which you will learn later in this section. The next step in programming music is setting the volume of the sound chip as follows: 20 VOL 8 The VOL statement sets the volume of the sound chip between 0 and 15, where 15 is the maximum and 0 is off (no volume). 7.3.2.2 The TEMPO Statement The next step in Commodore 128 music programming is controlling the tempo, or speed of your tune. The TEMPO statement does this for you. Here's the format: TEMPO n where n is a digit between 0 and 255 (and 255 is the fastest tempo). If you do not specify the TEMPO statement in your program, the Commodore 128 auto- matically sets the tempo to 8. Add this statement to your musical example program: 30 TEMP 10 7.3.2.3 The PLAY Statement Now it's time to learn how to play the notes in your song. You already know how the PRINT statement works. You play the notes in your tune the same way as PRINTing a text string to the screen, except you use the PLAY statement in place of PRINT. PRINT outputs text, PLAY outputs musical notes. Here's the general format for the play statement: PLAY "string of synthesizer control characters and musical notes" The total number of characters (including the musical notes and synthesizer control characters) that can be put into a PLAY command is 255. However, since this exceeds the maximum number of characters (160) allowed for a single program line in BASIC 7.0, you have to concatenate (that is, add to- gether) at least two strings to reach this length. You can avoid the need to concatenate strings by making sure your PLAY commands do not exceed 160 characters, i.e. one program line length. (This is equivalent with four screen lines in 40-column mode, and two screen lines in 80-column mode.) By doing this, you will produce PLAY command strings that are easier to under- stand and use. To play musical notes, enclose the letter of the note you want to play within quote. For example, here's how to play the musical scale (also known as do-re-mi-fa-sol-la-si): 40 PLAY "CDEFGAB" This plays the notes C, D, E, F, G, A and B in the piano envelope, which is envelope 0. After each time you RUN this example program your are creating, hold down the {run/stop} key and press the {restore} key to reset the syn- thesizer chip. You have the option of specifying the duration of the note by preceding it in quotes with one of the following notations: W - Whole note H - Half note Q - Quarter note I - Eighth note S - Sixteenth note The default setting, if the duration is not specified, is the Whole (W) notes. You can PLAY a rest (no sound) by including the following in the PLAY string: R - Rest You can instruct the computer to wait until all voices currently playing reach the end of a measure by including the following in quotes: M - Wait for end of measure The Commodore 128 also has synthesizer control characters you can include in a PLAY string. This gives you absolute control over each note and allows you to change synthesizer controls within a string of notes. Follow the control character with a number in the allowable range for that character. The control characters and the range of numbers are shown in Figure 7-6. The {n} following the control character refers to the number you select from the specified range. Control Default Character Description Range Setting ---------------------------------------------------- V n Voice 1-3 1 O n Octave 0-6 4 T n Envelope 0-9 0 U n Volume 0-15 9 X n Filter 0=off 0 1=on Figure 7-6. Sound Synthesizer Control Characters. Although the SID chip can process these control characters in any order, for best results, place the control characters in your string in the order that they appear in Figure 7-6. You don't absolutely have to specify any of the control characters, but you should to maximize the power from your synthesizer. The Commodore 128 auto- matically sets the synthesizer controls to the default settings in Figure 7-6. If you don't assign special control characters, the SID chip can PLAY only one envelope, one voice and one octave without any FILTERing. Specify the control characters to exercise the most control over the notes within your PLAY string. If you specify an ENVELOPE statement and select your own settings instead of using the default parameters from Figure 7-5, the envelope control character number in your PLAY string must match the number in your ENVELOPE statement in order to assume the parameters you assigned. You don't have the specify the ENVELOPE statement at all if you just want to PLAY the default settings from Figure 7-6. In this case, simply select an envelope number with the (T) control character in the PLAY statement. Here's an example of the PLAY statement using the SID chip control charac- ters within a string. Add this line to your program and notice the dif- ference between this statement and the PLAY statement in line 40. 50 PLAY "M V2 O5 T7 U5 X0 C D E F G A B" This statement PLAYs the same notes as in line 40, but voice 2 is selected, the notes are played one octave higher (5) than line 40, the volume set- ting is turned down to 5 and the FILTER is specified as off. For now, leave the filter off. When you learn about FILTERing in the next section, you can come back and turn the filter on to see how it affects the notes being played. Notice line 50 selects a new instrument, the organ envelope, with the T7 control character. Now your program PLAYs two different instruments in two of the independent voices. Add this statement to PLAY the third voice: 60 PLAY "M V3 O6 U7 T6 X0 C D E F G A B" Here's how line 60 controls the synthesizer. The V3 selects the third voice, O6 places voice 3 one octave higher (6) than voice two, T6 selects the harpsichord envelope, U7 sets the volume to 7 and X0 leaves the filter off for all three voices. Now your program plays three voices, each one oc- tave higher thant the other, in three seperate instruments, piano, organ and harpsichord. So far, your PLAY statements only played whole notes. Add notes of diffe- rent duration by placing control characters in you PLAY string as follows: 70 PLAY "MV2O6T0U7X0HCDQEFIGASB" Line 70 PLAYs voice 2 in octave 6 at volume level 7 with the redefined piano envelope (0) on and filter turned off. This statement PLAYs the note C and D as half notes, E and F as quarter notes, G and A as eighth notes and B as a sixteenth note. Notice the difference between the piano envelope in line 40 and the redefined piano envelope in line 70. Line 40 actually sounds more like a piano than line 70. You can PLAY sharp, flat and dotted notes by preceding the notes within quotes with the following characters: # - Sharp (half a tone higher). $ - Flat (half a tone lower). . - Dotted (half a duration longer). A dotted note plays one-and-a-half times the duration of a note that is not dotted. Now try adding sharp, flat and dotted notes with this statement: 80 PLAY "MV1O4T4U8X0.HCDQ#EFI$GA.S#B" Line 80 PLAYs voice 1 in octave 4 at volume level 8 with the flute envelope turned on and the filter turned off. It also PLAYs C and D as dotted half notes, E and F as sharp quarter notes, G and A as flat eighth notes and B as a sharp dotted sixteenth note. You can add rests (R) at any place within your PLAY string. Up until now your statement examples have left the filter off within the sound synthesizer and have not realized the true power behind it. Now that you have digested most of the sound and music statements and the SID con- trol characters, move on to the next section to learn how to enhance your musical quality with the FILTER statement. 7.3.2.4 The SID Filter Once you have selected the ENVELOPE, ADSR, VOLume and TEMPO, use the FILTER to perfect your synthesized sounds. In your program, the FILTER statement will precede the PLAY statement. First you should become comfortable with generating the sound and worry about FILTERing last. Since the SID chip has only one filter, it applies to all three voices. Your computerized tunes will play without FILTERing, but to take full advantage of your music syn- thesizer, use the FILTER statement to increase the sharpness and quality of the sound. In the first paragraph of this section (The Characteristics of Sound) we defined a sound as a sound wave traveling (oscilating) through the air at a particular rate. The rate at which a sound oscillates is called the wave's frequency. Recall that a sound wave is made up of an overall frequency and accompanying harmonics, which are multiples of the overall frequency. See Figure 7-2. The accompanying harmonics give the sound its timbre, the qua- lities of the sound which are determined by the waveform. The filter within the SID chip gives you the ability to accent and eliminate the harmonics of a waveform and change its timbre. The SID chip filters sounds in three ways: low-pass, high-pass and band- pass filtering. These filters are additive, meaning you can use more than one filter at a time. This is discussed in the next section. Low-pass fil- ters out frequencies above a certain level you specify, called the cutoff frequency. The cutoff frequency is the dividing line that marks the boun- dery of which frequency level will be played and which will not. In low- pass filtering, the SID chip plays all frequencies below the cutoff frequency and filters out the frequencies above it. As the name implies, the low frequencies are allowed to pass through the filter and high ones are not. The low-pass filter produces full, solid sounds. See Figure 7-7. | AMOUNT | -----+ PASSED | \ | \ | \ +------|------- FREQUENCY Figure 7-7. Low-pass Filter. Conversly, the high-pass filter allows all frequencies above the cutoff frequency to pass through the chip. All the ones below it are filtered out. See Figure 7-8. The high-pass filter produces tinny, hollow sounds. | AMOUNT | +----- PASSED | / | / | / +------|------- FREQUENCY Figure 7-8. High-pass Filter. The band-pass filter allows a range of frequencies partially above and below the cutoff frequency to pass through the SID chip. All other frequen- cies above and below the band surrounding the cutoff frequency are filtered out. See Figure 7-9. | AMOUNT | + PASSED | / \ | / \ | / \ +------|------- FREQUENCY Figure 7-9. Band-pass Filter. 7.3.2.5 The FILTER Statement The FILTER statement specifies the cutoff frequency, the type of filter being used and the resonance. The resonance is the peaking effect of the sound wave frequency as it approaches the cutoff frequency. The resonance determines the sharpness and clearness of a sound: the higher the reso- nance, the sharper the sound. This is the format of the FILTER statement: FILTER cf, lp, bp, hp, res Here's what the parameters mean: cf - Cutoff frequency (0 - 2047) lp - Low-pass filter (0=off, 1=on) bp - Band-pass filter (0=off, 1=on) hp - High-pass filter (0=off, 1=on) res - Resonance (0 - 15) You can specify the cutoff frequency to be any value between 0 and 2047. Turn on the low-pass filter by specifying a 1 as the second parameter in the FILTER statement. Turn on the band-pass filter by specifying a 1 as the third parameter and enable the high-pass filter with a 1 in the fourth parameter position. Turn off any of the three filters by placing a 0 in the respective position of the filter you want to disable. You can enable or disable one, two or all three of the filters at the same time. Now that you have some background on the FILTER statement, add this line to your sound program, but do not RUN the program yet: 45 FILTER 1200, 1, 0, 0, 10 Line 45 sets the cutoff frequency at 1200, turns on the low-pass filter, disables the high-pass and band-pass filters and assigns a 10 to the reso- nance level. Now go back and turn the filter on in your PLAY statements by changing all the X0 control characters to X1. Reset the sound chip by pres- sing the {run/stop} and {restore} keys and RUN your sound program again. Notice the difference between the way the notes sound and how they sounded without the filter. Change line 45 to: 45 FILTER 1200, 0, 1, 0, 10 The new line 45 turns off the low-pass filter and enables the band-pass fil- ter. Press {run/stop} and {restore} and RUN your sound program again. Notice the difference between the low-pass and band-pass filters. Change line 45 again to: 45 FILTER 1200, 0, 0, 1, 10 Reset the sound chip and RUN your example program again. Notice the diffe- rence between the high-pass filter and the low-pass and band-pass filters. Experiment with different cutoff frequencies, resonance levels and filters to perfect the music and sound in you own programs. 7.3.3 Tying your Music Program Together Your first musical program is complete. Now you can program your favorite songs. Let's tie all the components together. Here's the program listing. Don't be alarmed, this is the same program you built in this section except the print statements are added so you know which program lines are being played. 10 ENVELOPE 0,5,9,2,2,2,1700 15 VOL 8 20 TEMPO 10 25 PRINT "LINE 30" 30 PLAY "CDEFGAB" 35 FILTER 1200,0,0,1,10 40 PRINT "LINE 45 - FILTER OFF" 45 PLAY "V2 O5 T7 U5 X0 CDEFGAB" 50 PRINT "SAME AS LINE 45 - FILTER ON" 55 PLAY "V2 O5 T7 U5 X0 CDEFGAB" 60 PRINT "LINE 65 - FILTER OFF" 65 PLAY "V3 O6 T6 U7 X0 CDEFGAB" 70 PRINT "SAME AS LINE 65 - FILTER ON" 75 PLAY "V3 O6 T6 U7 X1 CDEFGAB" 80 PRINT "LINE 85 - FILTER OFF" 85 PLAY "V2 O6 T0 U7 X0 HCD QEF IGA SB" 90 PRINT "SAME AS LINE 85 - FILTER ON" 95 PLAY "V2 O6 T0 U7 X1 HCD QEF IGA SB" 100 PRINT "LINE 105 - FILTER OFF" 105 PLAY "V1 O4 T4 U8 X0 H.CD Q#EF I$GA S.B" 110 PRINT "SAME AS LINE 105 - FILTER ON" 115 PLAY "V1 O4 T4 U8 X1 H.CD Q#EF I$GA S.B" Line 10, the ENVELOPE statement, specifies the envelope for the piano (0), which sets the attack to 5, decay to 9, sustain to 2 and release to 2. It also selects the variable pulse waveform (2), with a pulse width of 1700. Line 15 sets the VOLume to 8. Line 20 chooses the TEMPO to be 10. Line 35 FILTERs the notes that are played in lines 30 to 115. It sets the FILTER cutoff frequency to 1200. In addition, line 35 turns off the low- pass and band-pass filters with the two zeros following the cutoff frequen- cy (1200). The high-pass filter is turned on with the 1 following the two zeros. The resonace is set to 10 by the last parameter in the FILTER statement. Line 30 PLAYs the notes C, D, E, F, G, A, B in that order. Line 45 PLAYs the same notes as line 30, but it specifies the SID control character U5 as volume level 5, V2 as voice 2 and O5 as octave 5. Remember, the SID control characters allow you to change the synthesizer controls within a string and exercise the most control over the synthesizer. The control character T7 selects the organ envelope. Line 65 specifies the control characters U7 for volume level 7, V3 for voice 3, O6 for octave 6, T6 for the harpsichord envelope and X0 to turn off the filter. Line 65 PLAYs the same notes as line 30 and 45, but in a different volume, voice, octave and instrument envelope. Line 85 has the same volume, voice, octave and envelope as line 65, and it specifies half notes for the notes C and D, quarter notes for the notes E and F, eighth notes for the notes G and A and a sixteenth note for the B note. Line 105 sets the volume at 8, voice 1, octave 4, flute envelope (4) and turns off the filter. It also specifies the C and D notes as dotted half notes, E and F as sharp quarter notes, G and A as flat eighth notes and B as a dotted sixteenth note. Line 115 is the same as line 105, but with the filter turned on. 7.3.4 Advanced Filtering Each of the previous FILTERing examples used only one filter at a time. You can combine the SID chip's three filters with each other to achieve different filtering effects. For example, you can enable the low-pass and high-pass filters at the same time to form a notch reject filter. A notch reject filter allows the frequencies below and above the cutoff to pass through the SID chip, while frequencies close to the cutoff frequency are filtered. See Figure 7-10 for a graphical representation of a notch reject filter. | AMOUNT | --+ +--- PASSED | \ / | \ / | + +------|------- FREQUENCY Figure 7-10. Notch Reject Filter. You can also add either the low-pass or high-pass filter to the band-pass filter to obtain interesting effects. By mixing the band-pass filter with the low-pass filter, you can select the band of frequencies beneath the cutoff frequency and below. The rest are filtered out. By mixing the band-pass and the high-pass filters, you can select the band of frequencies above the cutoff frequency and higher. All frequencies below the cutoff frequency are filtered out. Experiment with the different combinations of filters to see all the dif- ferent types of accents you can place on your musical notes and sound effects. The filters are designed to perfect the sounds created by other components of the SID chip. Once you have created the musical notes or sound effects with the SID chip, go back and add FILTERing to your programs to make them as crisp and clean as possible. Now you have all the information you need to write your own musical pro- grams in Commodore 128 BASIC. Experiment with the different waveforms, ADSR settings, TEMPOs and FILTERing. Look in a book of sheet music and enter the notes from a musical scale in sequence within a play string. Accent the notes in the string with the SID control characters. You can combine your Commodore 128 Music Synthesizer with C128 mode graphics to make your own videos or "movies", complete with sound tracks. 7.4 CODING A SONG FROM SHEET MUSIC This section provides a sample piece of sheet music and illustrates hoe to decode notes from a musical staff and translate them into a form the Com- modore 128 can understand. This exercise is substantially faster and easier if you know how to read music. However, you don't have to be a musician to be able to play the tune on your Commodore 128. For those of you who cannot read music, Figure 7-11 shows how a typical musical staff is arranged and how the notes on the staff are related to the keys on a piano. **-**-**--+-**-**--+-**-**-**--+-**-**--+-**-**-**--+-**-**--+-** ** ** ** | ** ** | ** ** ** |M** ** | ** ** ** | ** ** | ** ** ** ** | ** ** | ** ** ** |i** ** | ** ** ** | ** ** | ** | | | | | | | | | | |d | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |G |A |B |C |D |E |F |G |A |B |C |D |E |F |G |A |B |C |D |E |F | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ : : : : : : : : : : ^ : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : [ +----------------------------------------------------------------o------+ [ | : : : : : : : : : : : : : : : : : : : o | [ +----------------------------------------------------------o------------+ [ | : : : : : : : : : : : : : : : : : o | [ +----------------------------------------------------o------------------+ [ | : : : : : : : : : : : : : : : o | [ +-G:-------------------------------------------o------------------------+ [ | : : : : : : : : : : : : : o | [ +----------------------------------------o------------------------------+ [ : : : : : : : : : : v o [ : : : : : : : : : : -o- [ : : : : : : : : : o [ +----------------------------o------------------------------------------+ [ | : : : : : : : o | [ +-F:-------------------o------------------------------------------------+ [ | : : : : : o | [ +----------------o------------------------------------------------------+ [ | : : : o | [ +----------o------------------------------------------------------------+ [ | : o | [ +----o------------------------------------------------------------------+ Middle C Figure 7-11. Musical Staff. Figure 7-12 is an excerpt from a composition titled Invention 13 (Inventio 13 in Italian), by Johann Sebastian Bach. Although this composition was written a few hundred years ago, it can be played and enjoyed on most mo- dern computer synthesizers, such as the SID chip, in the Commodore 128. Here are the opening measures of Invention 13. [IMAGE IS MISSING] Figure 7-12. Part of Bach's Invention 13. The best way to start coding a song into your Commodore 128 is by breaking down the notes down into intermediate code. Write down the upper staff notes on a piece of paper. Now write down the notes for the lower staff. Precede the note values with a duration code. For instance, precede an eighth note with an 8, precede a sixteenth note with a 16 and so on. Next, separate the notes so the notes on the upper staff for one measure are propertional in time with the notes for one measure on the lower staff. If the musical composition has a third staff, you would separate it so the duration is proportional to the two other upper staffs. Once the notes for all the staffs are separated into equal durations, a separate dedicated voice would play each note for a particular staff. For example, voice 1 would play the upper staff, voice 2 will play the second staff and voice 3 would play the lowest staff if it existed. Let's say the upper staff begins with a string of four eighth notes. In ad- dition, say the lower staff begins with a string of eight sixteenth notes. Since a eighth note is proportional in time to two sixteenth notes, sepa- rate the notes as shown in Figure 7-13. V1 = 8A 8B 8C 8C V2 = 16D 16E 16F 16G 16A 16B 16C 16D Figure 7-13. Synchronizing Notes for Two Voices. Since the synchronization and timing in a musical composition is critical, you must make sure the notes in the upper staff for voice 1, for example, are in time agreement with the notes in the lower staff for voice 2. The first note in the upper staff in Figure 7-12 is an A eighth note. The first two notes for voice 2 are D and E sixteenth notes. In this case, you must enter the voice 1 eighth note in the PLAY string first, then follow the voice 2 sixteenth notes immediately after it. To continue the example, the second note in Figure 7-12 for voice 1 (the upper staff) is a B eighth note. The B eighth note is equal in time to the two sixteenth notes, F and G, which appear in the bottom staff for voice 2. In order to coordinate the timing, enter the B eighth note in the string for voice 1 and follow it with the two sixteenth notes F and G for voice 2. As a rule, always start with the note with the longer duration. For example, if a bar starts with a series of two sixteenth notes on the lower staff for voice 2 and the upper staff starts with an eighth note for voice 1, enter the eighth note in the string first since it must play for the du- ration while the two sixteenth notes are being fetched by the Commodore 128. You must give the computer time to play the longer note first, the PLAY the notes of shorter duration, or else the composition will not be synchronized. Here's the program that plays Invention 13. Enter it into your C128, SAVE it for future use and then RUN it. 10 REM INVENTION 13 BY J.S. BACH 20 TEMPO 6 30 A$="V1O4T7U8X0 V2O4T7U8X0":REM V1=ORGAN, V2=PIANO 40 DO 50 PLAY A$ 60 READ A$ 70 LOOP UNTIL A$="END OF MUSIC" 80 END 90 REM **** FIRST MEASURE 100 DATA V2O1IA V1O3IE V2O2QA V1O3SAO4CO3BEM 110 DATA V2O2I#G V1O3SBO4DO4IC V2O2SAEM 120 DATA V1O4IE V2O2SAO3C V1O3I#G V2O2SBEM 130 DATA V1O4IE V2O2SBO3DM 140 REM **** SECOND MEASURE 150 DATA V2O3IC V1O3SAE V2O2IA V1O3SAO4CM 160 DATA V2O2I#G V1O3SBE V2O2IE V1O3SBO4DM 170 DATA V1O4IC V2O2SAE V1O3IA V2O2SAO3CM 180 DATA V1O4QR V2O2SBEBO3DM 190 REM **** THIRD MEASURE 200 DATA V2O3IC V1O4SRE V2O2IA V1O4SCEM 210 DATA V2O3IC V1O3SAO4C V2O2IA V1O2SEGM 220 DATA V1O3IF V2O3SDO2A V1O3IA V2O2SFAM 230 DATA V1O4ID V2O2SDF V1O4IF V2O1SAO2CM 240 REM **** FOURTH MEASURE 250 DATA V2O1IB V1O4SFD V2O2ID V1O3SBO4DM 260 DATA V2O2IG V1O3SGB V2O2IB V1O3SDFM 270 DATA V1O3IE V2O2SGE V1O3IG V2O2SEGM 280 DATA V1O4IC V2O2SCE V1O4IE V2O1SGBM 290 REM **** FIFTH MEASURE 300 DATA V2O1IA V1O4SEC V2O2IC V1O3SAO4CM 310 DATA V1O3IF V2O2SDF V1O4ID V2O1SBO2DM 320 DATA V2O1IG V1O3SDB V2O1IB V1O3SGBM 330 DATA V1O3IE V2O2SCE V1O4IC V2O1SAO2CM 340 REM **** SIXTH MEASURE 350 DATA V2O1IF V1O4SCO3A V2O1ID V1O3SFAM 360 DATA V1O3ID V2O1SGO2G V1O3IB V2O2SFGM 370 DATA V2O1IA V1O4SCO3A V2O2I#F V1O4SCEM 380 DATA V2O1IB V1O4SDO3B V2O2I#G V1O4SDFM 390 REM **** SEVENTH MEASURE 400 DATA V2O2IC V1O4SEC V2O2IA V1O4SEGM 410 DATA V2O2ID V1O4SFE V2O2I$B V1O4SDCM 420 DATA V2O2I#G V1O3SBO4C V2O2IF V1O4SDEM 430 DATA V2O2ID V1O4SFD V2O1IB V1O4S#GDM 440 REM **** EIGHTH MEASURE 450 DATA V2O2I#G V1O4SBD V2O2IA V1O4SCAM 460 DATA V2O2ID V1O4SFD V2O2IE V1O3SBO4DM 470 DATA V2O2IF V1O3S#GB V2O2I#D V1O4SCO3AM 480 DATA V2O2IE V1O3SEA V2O2IE V1O3SB#GM 490 REM **** NINTH MEASURE 500 DATA V2O1HA V1O3SAECEO2QAM 510 REM **** END OF MUSIC **** 520 DATA END OF MUSIC You can use the technique described in this section to code your favorite sheet music and play it on your Commodore 128. *************************************************************************** You now have been introduced to most of the powerful new commands of the BASIC 7.0 language that you can use in C128 mode. In the following section you will learn to use both 40- and 80-column screen displays with the Com- modore 128. SECTION 8 8. Using 80-Columns 8.1 INTRODUCTION 8.2 THE 40/80 KEY 8.3 USING PREPACKAGED 80 COLUMN SOFTWARE 8.4 CREATING 80 COLUMN PROGRAMS 8.5 USING 40 AND 80 COLUMNS TOGETHER 8.1 INTRODUCTION In C128 and CP/M modes, you can choose between a 40- en 80-column screen display. You could even use both in a single program. Each screen size has special uses. The 40-column screen is the same size the Commodore 64 uses. With the 40-column screen you can use the Commodore 128's full graphic capabilities. You can draw circles, graphs, sprite characters, boxes and other shapes in high resolution or multicolor graphic modes. You can also use sprites. If you are using 80-columns, you get twice the number of characters per program line. In 80-column mode you can use the standard graphic characters and colors available through the keyboard. You can also write programs using two monitors to take advantage of both screen display formats with each monitor screen performing different as- pects of the program. For example, text output could be displayed on the 80-column monitor while graphics output could be seen on the 40-column monitor. 8.2 THE 40/80 KEY You can use the {40/80 display} key to set the screen width as either 40 or 80 columns. Pressing this key will only have an effect when one of the fol- lowing actions is taken: 1. The power is turned ON. 2. The {reset} button is pressed. 3. The {run/stop} and {restore} buttons are pressed simultaneously. The {40/80 display} key acts like a {shift lock} key: it locks when you press it, and does not release until you press it again. If this key is up (not pressed) when one of the three conditions above occurs, the screen is set to 40 columns. If you press the key down, causing it to lock, and one of the three conditions listed above then occurs, the screen is set to 80 columns. Once the computer is running in one screen format (40- or 80- columns), you cannot switch to the other format using the {40/80 display} key. In this case you must press and release the {esc} key and then press the {X} key. 8.3 USING PREPACKAGED 80 COLUMN SOFTWARE Most CP/M programs utilize an 80-column screen, as do many of the other business application packages you can use in C128 mode. Since the width of a normal printed page is 80 columns, an 80-column wordprocessor can display information on the screen exactly as that information will appear on paper. Spreadsheet programs often specify an 80-column format, in order to provide enough space for the necessary columns and categories of information. Many database packages and telecommunications programs also require or can use an 80-column screen. 8.4 CREATING 80 COLUMN PROGRAMS In addition to running prepackaged software, the 80-column screen width can be useful in designing you own programs. You've probably noticed what hap- pens when you type a line that is wider than 40 columns on a 40-column screen. The lines "wrap around", that is, the continue onto the next screen line. This may cause confusion in reading the line, and can even lead to progamming errors. An 80-column screen helps eliminate these problems. In general, an 80-column screen allows for a clearer screen and better organi- zation. 8.5 USING 40 AND 80 COLUMNS TOGETHER The main advantage of 40-column composite video is the availability of bit mapped graphics, while 80-columns gives you output for word processing and other business applications. If you have two monitors, you can write pro- grams that are "shared", using the text features 80-columns affords you and the graphics of 40-columns. A special command (GRAPHIC 1,1) can be used within a program to transfer the execution of graphics commands to the 40- column display. If you have a dual monitor (one that can display both 40- and 80-columns format) you can place GRAPHIC 1,1 statements in your program so that graphics will be output in 40-column screen format. In order to view the graphic output, however, you will need to change the video switch on the monitor to 40-columns. If you write a program like this, it might be a good idea to include on-screen directions to the user to change the video switch. For example, you might write a program which asked the user to input data, then create a bar graph based on the user's input. The message "CHANGE TO 40 COLUMN TO VIEW GRAPH" would tell the user to switch modes and see the results. As noted previously, you can switch between 80- and 40-column formats after power-up, with the {esc x} sequence. The following example shows how dual screens can be used within a program: 10 GRAPHIC 5,1:SCNCLR :REM SWITCH TO 80 COLUMN AND CLEAR IT 20 PRINT "START IN 40 COLUMN BY SELECTING THE COMPOSITE VIDEO" 30 PRINT "INPUT OF YOUR DUAL MONITOR." 40 PRINT 50 PRINT "PRESS THE RETURN KEY WHEN READY." 60 GETKEY A$:IF A$ <> CHR$(13) THEN 60 70 GRAPHIC 2,1 :REM SELECT SPLIT SCREEN MODE 80 CHAR 1,8,18,"BIT MAP/TEXT SPLIT SCREEN" 90 FOR I = 70 TO 220 STEP 20:CIRCLE 1,I,50,30,30:NEXT I 100 PRINT 110 PRINT " SWITCH TO 80 COLUMN BY SELECTING THE" 120 PRINT " RGBI VIDEO INPUT OF YOUR DUAL MONITOR," 130 PRINT " THEN PRESS THE RETURN KEY WHEN READY." 140 GETKEY A$:IF A$ <> CHR$(13) THEN 140 150 GRAPHIC 5,1 :REM SWITCH OUTPUT TO THE 80 COLUMN 160 FOR J = 1 TO 10 170 PRINT "YOU ARE NOW IN 80 COLUMN TEXT MODE." 180 NEXT J:PRINT 190 PRINT "NOW SWITCH BACK TO 40 COLUMN OUTPUT." 200 PRINT "PRESS THE RETURN KEY WHEN READY." 210 GETKEY A$:IF A$ <> CHR$(13) THEN 210 220 GRAPHIC 0,1 :REM SWITCH OUTPUT TO THE 40 COLUMN 230 PRINT 240 FOR J = 1 TO 10 250 PRINT " YOU ARE NOW IN 40 COLUMN TEXT OUTPUT." 260 NEXT J 270 END Each screen display format offers certain advantages; yet the two types of displays can be combined in a program to complement each other. Using a 40- column screen, you can get the full power of advanced BASIC graphics. The 80-column display gives you more space for your own programs. In addition, it lets you run the wide variety of software designed to run on an 80- column screen. *************************************************************************** This section of this chapter have introduced you to the many features and capabilities provided by the Commodore 128 in C128 mode. The following chapter tells you how to use the Commodore 128 in C64 mode. CHAPTER 3 USING C64 MODE SECTION 9 9. Using the Keyboard in C64 Mode 9.1 USING BASIC 2.0 9.2 KEYBOARD CHARACTER SETS 9.3 USING THE TYPEWRITER-STYLE KEYS 9.4 USING THE COMMAND KEYS 9.5 MOVING THE CURSOR IN C64 MODE 9.6 PROGRAMMING FUNCTION KEYS IN C64 MODE 9.1 USING BASIC 2.0 The entire BASIC 2.0 language built into the Commodore 64 computer has been incorporated into the BASIC 7.0 language of the Commodore 128. You can use BASIC 2.0 commands in both C128 and C64 modes. Refer to Sections 3 and 4 in Chapter 2 for a description of these commands. 9.2 KEYBOARD CHARACTER SETS In the keyboard illustration in Section 3 the outlined key areas contain the keys that can be used in C64 Mode. The keyboard in C64 Mode has the same two character states as in C128 Mode: - Upper case/graphic character set - Upper/lower case character set When you enter C64 Mode, the keyboard is in the upper case/graphic charac- ter set, so that everything you type is in capital letters. In C64 Mode you can only use one character set at a time. To switch back and forth between character sets, press the {shift} key and the {C=} key (the COMMODORE key) at the same time. 9.3 USING THE TYPEWRITER-STYLE KEYS As in C128 Mode, you can use the typewriter-style keys in C64 Mode to type both upper case letters (capitals) and lower case letters (small letters). You can also type the numerals shown in the top row on the main keyboard. In addition, you can type the graphic symbols on the front of the keys. 9.4 USING THE COMMAND KEYS Most COMMAND keys (i.e. the keys that send messages to the computer, like {return}, {shift}, {ctrl}, etc.) work the same in C64 Mode as they do in C128 Mode. The only difference is that in C64 Mode, you can only move the cursor by using the two {crsr} keys at the bottom right corner of the main keyboard. In C128 Mode, you can also use the four arrow keys located just above the top right side of the main keyboard. 9.5 MOVING THE CURSOR IN C64 MODE In C64 Mode, you use two {crsr} keys on the main keyboard and the {shift} key to move the cursor, as described in Section 3. 9.6 PROGRAMMING FUNCTION KEYS IN C64 MODE The four keys to the right side of the keyboard, just above the numeric keypad, are called function keys. The keys are marked F1, F3, F5 and F7 on the tops and F2, F4, F6 and F8 on the fronts. These keys can be programmed - that is, they can be instructed to perform a specific task or function. For this reason these keys are often called programmable function keys. You must hold down the {shift} key to perform the functions associated with the markings on the front of the keys - that is, F2, F4, F6 and F8. There- fore, these keys are sometimes called the SHIFTed programmable function keys. The function keys in C64 Mode do not have a printed character assigned to them. They do, however, have CHR$ codes assigned. In fact, each of them has two CHR$ codes - one for when you press the key by itself, and one for when you press the key while holding down the {shift} key. To get the even- numbered function keys, hold down the {shift} key while pressing the func- tion key. For example, to get {f2}, hold down {shift} and press {f1}. The CHR$ codes for the F1-F8 keys range from 133 to 140. However, the codes are not assigned to the keys in numerical order. The keys and their corres- ponding CHR$ codes are as follows: {f1} CHR$(133) {f2} CHR$(137) {f3} CHR$(134) {f4} CHR$(138) {f5} CHR$(135) {f6} CHR$(139) {f7} CHR$(136) {f8} CHR$(140) You can use the function keys in your program in several ways. To do this, you need to use the GET statement. (See paragraph 4.3.2 of Section 4 for a description of the GET statement.) As an example, the program below prepares the {f1} key to print a message on the screen. 10 ?"PRESS F1 TO CONTINUE" 20 GET A$:IF A$="" THEN 20 30 IF A$<>CHR$(133) THEN 20 40 ?"YOU HAVE PRESSED F1" Lines 20 and 30 do most of the work in this program. Line 20 makes the com- puter wait until a key is pressed before executing any more of the program. Note that when the command immediately after THEN is a GOTO, only the line number is necessary. Also note that a GOTO command can GOTO the same line it is on. Line 30 tells the computer to go back and wait for another key to be pressed unless the {f1} key has been pressed. SECTION 10 10. Storing and Reusing Your Programs in C64 Mode 10.1 FORMATTING A DISK IN C64 MODE 10.2 THE SAVE COMMAND 10.2.1 SAVEing on Disk 10.2.2 SAVEing on Cassette 10.3 THE LOAD AND RUN COMMANDS 10.3.1 LOADing and RUNning from Disk 10.3.2 LOADing and RUNning from Cassette 10.4 OTHER DISK-RELATED COMMANDS 10.4.1 Verifying a Program 10.4.2 Displaying Your Disk Directory 10.4.3 Initializing a Disk Drive Once you have edited a program, you will probably want to store it permanently so that you will be able to recall and use it at some later time. To do this you need either a Commodore disk drive or the Commodore Datassette. 10.1 FORMATTING A DISK IN C64 MODE To store programs on a new (or blank) disk, you must first prepare the disk to receive data. This is called formatting the disk. Make sure that you turn on the disk drive before inserting any disk. To format a blank disk, in C64 Mode, you type this command: OPEN 15,8,15:PRINT#15,"N0:NAME,ID" {return} In place of NAME, type a disk name of your choice; you can use up to 16 characters to identify the disk. In place of ID, type a two character code of your choice (such as W2 or 10). The cursor disappears during the formatting process. When the cursor blinks again, type the following command: CLOSE 15 {return} NOTE: Once a disk is formatted in C64 or C128 mode, that disk can be used in either mode. 10.2 THE SAVE COMMAND You can use the SAVE command to store your programs on disk or tape. 10.2.1 SAVEing on Disk If you have a Commodore single disk drive, you can store your program on disk by typing: SAVE "PROGRAM NAME",8 {return} The {8} indicates to the computer that your are using a disk drive to store your program. The same rules apply for the PROGRAM NAME whether you are using disk or tape. The PROGRAM NAME can be anything you want it to be. You can use let- ters, numbers and/or symbols - up to 16 characters in all. Note that you must enclose the PROGRAM NAME in quotation marks. The cursor on your com- puter disappears while the program is being SAVEd, but it returns when the process is completed. 10.2.2 SAVEing on Cassette If you are using a Datassette to store your program, insert a blank tape in the recorder, rewind the tape (if necessary) and type: SAVE "PROGRAM NAME" {return} 10.3 THE LOAD AND RUN COMMANDS Once a program has been SAVEd, you can LOAD it back into the computer's memory and RUN it anytime you wish. 10.3.1 LOADing and RUNning from Disk To load your program from a disk, type: LOAD "PROGRAM NAME",8 {return} Again, the {8} indicates to the computer that you are working with a disk drive. To RUN the program, type RUN and press {return} 10.3.2 LOADing and RUNning from Cassette To LOAD your program from cassette tape, type: LOAD "PROGRAM NAME" {return} If you do not know the name of the program, you can type: LOAD {return} and the next progam on the tape will be retrieved. You can use the counter on the Datassette to identify the starting position of the programs. Then, when you want to retrieve a program, simply wind the tape forward from 000 to the program's start location, and type: LOAD {return} In this case, you do not have to specify the PROGRAM NAME; your program will load automatically because it is the next program on the tape. NOTE: During the LOAD process, the program being LOADed is not erased from the tape; it is simply copied into the computer. However, LOADing a program automatically erases any BASIC program that may have been in the computer's memory. 10.4 OTHER DISK-RELATED COMMANDS 10.4.1 Verifying a Program To verify that a program has been correctly saved or loaded, type: VERIFY "PROGRAM NAME",8 {return} If the program in the computer is identical to the one on the disk, the screen display will respond with the letters {OK}. The VERIFY command also works for tape programs. You type: VERIFY "PROGRAM NAME" {return} Note that you do not enter the comma and the number 8, since 8 indicates that you are working with a disk program. 10.4.2 Displaying Your Disk Directory To see a list of the programs on your disk, first type: LOAD "$",8 {return} The cursor disappears during this process. When the cursor reappears, type: LIST {return} A list of the programs on your disk then will be displayed. Note that when you load the directory, any program that was in memory is erased. 10.4.3 Initializing a Disk Drive If the disk drive's ready light is blinking, it indicates a disk error. You can restore the disk drive to the condition it was in before the error oc- curred by using a procedure called INTITIALIZING. To initialize a drive, you type: OPEN 1,8,15,"I":CLOSE 1 {return} If the light is still blinking, remove the disk and turn the drive off, then on. For further information on SAVEing and LOADing your programs, refer to your disk drive or Datassette manual. Also consult the LOAD and SAVE command descriptions in the Chapter V, BASIC 7.0 Encyclopaedia. CHAPTER 4 USING C/PM MODE SECTION 11 11. Introduction to CP/M 3.0 11.1 WHAT CP/M 3.0 IS 11.2 WHAT YOU NEED TO RUN CP/M 3.0 11.3 WHAT IS ON YOUR CP/M 3.0 DISK 11.3.1 CP/M+.SYS 11.3.2 CCP.COM 11.3.3 .COM Files 11.3.4 Other Files 11.4 GETTING STARTED WITH CP/M 3.0 11.4.1 Loading or Booting CP/M 3.0 11.4.2 The Opening CP/M Screen Display 11.5 THE COMMAND LINE 11.5.1 Types of Commands 11.5.2 How CP/M Reads Command Lines 11.6 HOW TO COPY YOUR CP/M 3.0 DISK 11.6.1 Formatting a Disk 11.6.2 Copying Files 11.7 LANGUAGES AND APPLICATION SOFTWARE 11.7.1 What To Buy 11.7.2 How To Install It on Your C128 11.1 WHAT CP/M 3.0 IS CP/M is a product of Digital Research, Inc. The version of CP/M used on the Commodore 128 is CP/M Plus Version 3.0. In this chapter, CP/M is generally referred to as CP/M 3.0, or simply CP/M. This chapter summarizes CP/M on the Commodore 128. For detailed information on CP/M 3.0, follow the instructions on the coupon enclosed in the box in which the Commodore 128 is supplied. CP/M 3.0 is a popular operating system for microcomputers. As an operating system, CP/M 3.0 manages and supervises your computer's resources, inclu- ding memory and disk storage, the console (screen and keyboard), printer, and communication devices. CP/M 3.0 also manages information stored in disk files. CP/M 3.0 can copy files from a disk to your computer's memory, or to a peripheral device such as a printer. To do this, CP/M 3.0 places various programs in memory and executes them in response to commands you enter at your console. Once in memory, a program executes a set of steps that instruct your computer to perform a certain task. You can use CP/M to create your own programs, or you can choose from the wide variety of available CP/M 3.0 application programs. 11.2 WHAT YOU NEED TO RUN CP/M 3.0 The general hardware requirements for CP/M 3.0 are a computer containing a Z80 microprocessor, a console consisting of a keyboard and a display screen, and at least one floppy disk drive. For CP/M 3.0 on the Commodore 128 Personal Computer, the Z80 microprocessor is built-in; the console consists of the full Commodore 128 keyboard, and an 80-column monitor; and the disk drive is the new Commodore 1571 fast disk drive. In addition, there is either one or two CP/M disks packed with the computer. If two CP/M disks are supplied, one contains the CP/M 3.0 system and an extensive HELP utility program, and the other contains a number of other utility programs. If one CP/M disk is supplied, the system and HELP utility are on one side of that disk and the utility programs are on the other. Note: Although CP/M can be used with a 40-column monitor, the display is 80 column but with only 40 columns displayed at one time. To view all 80 columns of the display, you must scroll the screen horizontally by pressing the {ctrl} key and the appropriate cursor key ({crsr left} or {crsr right}). 11.3 WHAT IS ON YOUR CP/M 3.0 DISK 11.3.1 CP/M+.SYS This is the main CP/M Plus system file. It contains all parts of the system that remain permanently resident in memory: the Basic Input/Output System (BIOS) which loads into the top of memory, the Basic Disk Operating System (BDOS) which loads into memory immediately below BIOS, and the System Para- meters which load into the bottom page of memory. 11.3.2 CCP.COM On booting CP/M the Console Command Processor (CCP) is loaded into memory immediately below the BDOS. The remaining memory, below CCP and above page 0, is known as the Transient Program Area (TPA) and is where applications are loaded to. CCP is the program which processes any input (usually en- tered from the keyboard) in response to the system prompt (A>). It contains 6 built-in commands (listed in Table 14-1), and also supports the 14 console editing commands (listed in Table 13-1). Any word entered in response to the system prompt which is not one of the built-in commands is treated by CCP as a transient command, so CCP attempts to find and execute a file named as that word with the .COM extension. If it does not find such a file on the currently logged disk, it displays the word followed by a question mark then brings back the system prompt. If more than one word is entered in response to the system prompt, all words after the first are treated as parameters to be passed to the tran- sient command. A language or application program is loaded and run by invoking it as if it was a command. All CP/M programs include a .COM file WHAT IS ON YOUR CP/M 3.0 DISK show b: B: RW, Space 336k A>dir [full] Scanning Directory... Sorting Directory... Directory for Drive A: User 0 Name Bytes Recs Attributes Name Bytes Recs Attrib. ------------ ------ ------ ------------ ------------ ------ ------ -------- CCP .COM 4k 25 Dir RW CPM+ .SYS 23k 182 Dir RW DIR .COM 15k 114 Dir RW FORMAT .COM 5k 35 Dir RW HELP .COM 7k 56 Dir RW HELP .HLP 83k 664 Dir RW KEYFIG .COM 10k 75 Dir RW KEYFIG .HLP 9k 72 Dir RW PIP .COM 9k 68 Dir RW Total Bytes = 165k Total Records = 1291 Files Found = 9 Total 1k Blocks = 165 Used/Max Dir Entries For Drive A: 15/ 64 A>dir b: [full] Scanning Directory... Sorting Directory... Directory for Drive B: User 0 Name Bytes Recs Attributes Name Bytes Recs Attrib. ------------ ------ ------ ------------ ------------ ------ ------ -------- DATE .COM 8k 25 Dir RW DATEC .ASM 2k 5 Dir RW DATEC .RSX 2k 3 Dir RW DEVICE .COM 16k 58 Dir RW DIR .COM 30k 114 Dir RW DIRLBL .RSX 4k 12 Dir RW DUMP .COM 2k 8 Dir RW ED .COM 20k 73 Dir RW ERASE .COM 8k 29 Dir RW GENCOM .COM 30k 116 Dir RW GET .COM 14k 51 Dir RW INITDIR .COM 64k 250 Dir RW PATCH .COM 6k 19 Dir RW PIP .COM 18k 68 Dir RW PUT .COM 14k 55 Dir RW RENAME .COM 6k 23 Dir RW SAVE .COM 4k 14 Dir RW SET .COM 22k 81 Dir RW SETDEF .COM 8k 32 Dir RW SHOW .COM 18k 66 Dir RW SUBMIT .COM 12k 42 Dir RW TYPE .COM 6k 24 Dir RW Total Bytes = 314k Total Records = 1168 Files Found = 22 Total 1k Blocks = 314 Used/Max Dir Entries For Drive A: 23/ 64 11.3.3 .COM Files The other .COM files all contain transient commands (listed in Table 14-2). HELP.COM displays messages, held in HELP.HLP (whose extension indicates it is a data file, not a program file), about the C128 CP/M system and its commands. If you are not familiar with CP/M and have no other manuals or books about it, you may find it useful to print out any HELP you look at. Pressing {ctrl} and {p} CAUSES any screen output also to go to the printer: pressing {ctrl}{p} again turns off this facility. Enter HELP for the list of subjects covered, or HELP C128_CP/M for informa- tion specific to this implementation. (The character in the middle of C128_CP/M is obtained by pressing the {left arrow} key at the top left of the keyboard.) If you are printing and do not want pauses after each screenful, then enter HELP C128_CP/M [NOPAGE]. 11.3.4 Other Files .ASM indicates an Assembler source file. .RSX indicates a Resident System eXtension, which is a file automatically loaded by a command file as and when it is needed. 11.4 GETTING STARTED WITH CP/M 3.0 The following paragraphs tell you how to start or "boot" CP/M 3.0, how to enter and edit the command line, and how to make back-up copies of your CP/M 3.0 disks. 11.4.1 Loading or Booting CP/M 3.0 Loading or "booting" CP/M 3.0 means reading a copy of the operating system from your CP/M 3.0 System Disk into your computer's memory. You can boot CP/M 3.0 in several ways. If your computer is off, you can boot CP/M by first turning on your disk drive and inserting the CP/M 3.0 system disk, and then turning on the computer. CP/M 3.0 then loads automa- tically. If you are already in C128 BASIC mode, you can boot CP/M 3.0 by inserting the CP/M system disk into the drive, typing the BASIC command BOOT and then pressing {return}. CP/M 3.0 then loads. In C128 mode, you can also boot CP/M by inserting the System Disk and pressing the {reset} button. If you are in C64 mode, and you want to enter CP/M mode, first turn off the computer. The insert the CP/M System Disk into the drive and turn on the computer. Caution: Always make sure that the disk is fully inserted in the drive before you close the drive door. In CP/M 3.0 on the Commodore 128, the user has a 59K TPA (Transient Program Area), which is, in effect, user RAM. 11.4.2 The Opening CP/M Screen Display After CP/M is loaded into memory, a message similar to the following is displayed on your screen: +-------------------------------------------------------------------------+ | CP/M 3.0 On the Commodore 128 3 JUNE 85 | | 80 column display | | | | A>_ | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | R A01 10 | +-------------------------------------------------------------------------+ An important part of the opening display is the following two-character message: A> This is the CP/M 3.0 system prompt. The system prompt tells you that CP/M is ready to read a command entered by you from your keyboard. The prompt also tells you that drive A is your default drive. This means that until you tell CP/M to do otherwise, it looks for program and data files on the disk in drive A. It also tells you that your are logged in as user 0, sim- ply by the absence of any user number other than 0. Note: In CP/M a single disk drive is identified as drive A. This is equi- valent to unit 8, drive 0 in C128 and C64 modes. Usually, the maximum number of drives in CP/M is four. Additional drives are identified as drives B, C, etc. 11.5 THE COMMAND LINE CP/M 3.0 performs tasks according to specific commands that your type at your keyboard. These Commands appear on the screen in what is called a command line. A CP/M 3.0 command line is composed of a command keyword and an optional command tail. The command keyword identifies a command (pro- gram) to be executed. The command tail can contain extra information for the command, such as a filename or parameters. The following example shows a command line. A>DIR MYFILE In this example, DIR is the command keyword and MYFILE is the command tail. To send the command line to CP/M 3.0 for processing, press the {return} key. As you type characters at the keyboard, the appear on your screen. The cursor moves to the right as you type. If you make a typing error, press either the {inst/del} key or CTRL-H to move the cursor to the left and correct the error. CTRL is the abbreviation for the {ctrl} key. To specify a control character, hold down the {ctrl} key and press the appropriate letter key. (A list of control characters and their uses is given in Section 13.) You can type the keyword and command tail in any combination of upper-case and lower-case letters. CP/M 3.0 interprets all letters in the command line as being upper case. Generally, you must type a command line directly after the system prompt. However, CP/M 3.0 does allow spaces between the prompt and the command keyword. 11.5.1 Types of Commands CP/M 3.0 recognizes two different types of commands: built-in commands and transient utility commands. Built-in commands execute programs that reside in memory as a part of the CP/M operating system. Built-in commands can be executed immediately. Transient utility commands are stored on disk as pro- gram files. They must be loaded from disk to perform their task. You can recognize transient utility program files when a directory is displayed on the screen, because their filenames are followed by a period (full stop) and COM (.COM). Section 14 presents lists of CP/M built-in and transient utility commands. For transient utilities, CP/M 3.0 checks only the command keyword. Many utilities require unique command tails. If you include a command tail, CP/M 3.0 passes it to the utility without checking it. A command tail cannot contain more than 128 characters. 11.5.2 How CP/M Reads Command Lines Use the DIR command to demonstrate how CP/M reads command lines. DIR, which is an abbreviation for directory, tells CP/M to display a directory of disk files on your screen. Type the DIR keyword after the system prompt, and press the {return} key: A>DIR {return} CP/M responds to this command by displaying the names of all the files that are stored on whatever disk is in drive A. For example, if the CP/M system disk is in the disk drive A, a list of filenames like this appears on your screen: A: PIP COM:ED COM:CCP COM:HELP COM:HELP HLP A: DIR COM:CPM SYS CP/M recognizes only correctly spelled command keywords. If you make a typing error and press {return} before correcting your mistake, CP/M 3.0 repeats or "echoes" the command line followed by a question mark. For example, suppose you mistype the DIR command, as in the following example: A>DJR {return} CP/M replies with: DJR? This tells you the CP/M cannot find a command keyword spelled DJR. To cor- rect typing errors like this, you can use the {inst/del} key to delete the incorrect letters. Another way to delete characters is to hold down the {ctrl} key and press {h} to move the cursor to the left. CP/M provides a number of other control characters that help you edit command lines. Section 13 tells how to use the control characters to edit command lines and other information you enter at your console. DIR accepts a filename as a command tail. You can use DIR with a filename to see if a specific file is on the disk. For example, to check that the file MYFILE is on your disk, type: A>DIR MYFILE {return} CP/M 3.0 performs this task by displaying either the name of the file you specify, or the message: No File Be sure you type at least one space after DIR to separate the command keyword from the command tail. If you do not, CP/M 3.0 responds as follows: A>DIRMYFILE {return} DIRMYFILE? 11.6 HOW TO COPY YOUR CP/M 3.0 DISK Before doing anything else you should back-up your CP/M system disk. This can be done using either one or two disk drives. If using two disk drives these may be 1541s, 1571s, or one of each. The back-up disks can be new or used. You can either format new disks, or reformat used disks. To make back-ups use the FORMAT and PIP utility programs found on you CP/M system disk. 1) Format the diskette using the FORMAT program, as either C128 single sided (if using a 1541) or C128 double sided (if using a 1571). (The C64 single sided option is for formatting disks compatible with the CP/M 2.2 package once sold for the Commodore 64.) Enter the command FORMAT, select the required disk type with the {crsr down} key, press {return}, and follow the onscreen instructions. Press {y} (Yes) or {n} (No) in response to the 'Do you want to format another disk' question. 2) Use the Peripheral Interchange Program (PIP) - on the second surface of the original disk - to copy files. Enter PIP and the usual system prompt (A>) will be replaced by the PIP prompt (*). If you have a single disk drive use drive A as the source drive and drive E as the destination drive. Drive E is referred to as a virtual drive - that is, it does not exist as an actual piece of hardware. Put the disk to be copied from in the drive and enter E:=A:*.* (You will be prompted each time the source disk and the destination disk have to be swopped.) If you have two disk drives, put the source disk in drive A (which is device 8) and the newly formatted disk in drive B (device 9 - set by put- ting the left DIP switches on the back of the 1571 down while the drive is switched off) and enter B:=A:*.* to copy all the files. Your original CP/M disk is a flippy - i.e. recorded as 2 single sides, so it must be taken out of the drive and turned over to get at the second side. This is required for use in a 1541, which is a single sided drive. If you have a 1541 you should copy the 2 surfaces onto 2 separate disks. How- ever, if you have a 1571 you will find it convenient to copy both surface onto a standard double sided disk: after copying the first side, turn over the original disk and copy the second side onto the same destination disk by again entering the copy instruction in response to the PIP prompt. You may sometimes want to make disks that just have the system files on them. To do this use PIP to copy the files CPM+.SYS and CCP.COM to the newly formatted disk. Note: Only disks that you intend to use to boot CP/M need these 2 files on them - putting them on other disks wastes space. With a single drive, enter E:=A:CPM+.SYS to copy the first file and then E:=A:CCP.COM to copy the second file. When you have finished PIP, press {return} to return from the PIP prompt to the system prompt. A full description of PIP can be obtained by entering HELP PIP, HELP PIP_OPTIONS and HELP PIP_EXAMPLES. 11.7 LANGUAGES AND APPLICATION SOFTWARE CP/M is just an operating system, that is a means to an end - not an end in itself. On its own it does not do anything useful. If you want to write your own programs you will need a language, either assembler or high level, in which to write them. If you want to play games or do business work you will need application programs. 11.7.1 What To Buy Because CP/M has been implemented on almost every computer ever designed that used the Intel 8080 or the Zilog Z80 cpu, there is a very large amount of software available for running on CP/M systems. The most compre- hensive catalogue of commercial software is the 'CP/M Software Finder' pu- blished for Digital Research by Que Corporation and available through good software retailers (ISBN 0-88-022-021-X). Since it is not convenient for the CP/M Users Group to supply its library on Commodore format disks, a selection of public domain CP/M software has been made available through the independent Commodore Products Users Group (ICPUG), for which member- ship application forms can be obtained by sending an s.a.e. to Membership Secretary, ICPUG, 30 Brancaster Rood, Newbury Park, Ilford, IG2 7EP, England. CP/M normally uses Modified Frequency Modulation (MFM) ot record on disks. Commodore DOS normally uses Group Code Recording (GCR). The Commodore 1571 disk drive can read both, but the older 1541 can only read GCR. Off-the- shelf CP/M software packages only come as MFM disks. Even with MFM there are many different formats: the 1571 can read disks formatted for: Epson QX10 (512 byte sectors, double sided, 10 sectors per track) IBM-8 SS (CP/M-86) (512 byte sectors, single sided, 8 sectors per track) IBM-8 DS (CP/M-86) (512 byte sectors, double sided, 8 sectors per track) IBM-9 SS (CP/M-86) (512 byte sectors, single sided, 9 sectors per track) IBM-9 DS (CP/M-86) (512 byte sectors, double sided, 9 sectors per track) KayPro II (512 byte sectors, single sided, 10 sectors per track) KayPro IV (512 byte sectors, double sided, 10 sectors per track) Osborne DD SS (1024 byte sectors, single sided, 5 sectors per track) Osborne DD DS (1024 byte sectors, single sided, 5 sectors per track) Therefore when buying CP/M software you must buy it on a disk in one of the above formats. Also, be aware that your C128 will run software written to run under either CP/M 2.2 or CP/M Plus (which is the newer name for what was originally known as version 3). However, CP/M-86 is the version of CP/M designed for use on 16-bit processors: CP/M-86 software will not run on your C128's 8-bit Z80 processor, although the 1571 drive will let you read CP/M-86 data files. If you only have a 1541 disk drive you will have to get any software you buy transferred from MFM format to (Commodore) GCR format. Some software retailers may be willing to do this for you, but there will probably be a copying charge. Alternatively, you may find that your local ICPUG group provides facilities to do this at its meetings. 11.7.2 How To Install It on Your C128 Because there are so many different computers using the CP/M operating sys- tem, many CP/M programs have to be configured for the particular hardware on which they are to be used. The process of installing a program on your C128 involves setting parameters within the software. The program manual will describe how to install the program if this is required. Most programs provide a list of common terminals which they support. If ADM31 appears in this list, select it. If not, your will have to do a custom installation. Listed below are the entries that should be made when running WINSTALL.COM (the installation program that is part of the Wordstar package). These also provide the information that will be needed for installing other programs, although not all packages ask the same questions. Terminal name Commodore 128 Screen size Screen height 24 Screen width 80 Cursor positioning Function code sequence 1Bh 3Dh Characters to be sent between line number and column number none Characters to be sent after line number and column number none Is the column number sent before the line number? NO What character is sent to the terminal to signify line 1? 20h What character is sent to the terminal to signify column 1? 20h What types of code are sent to signify line and column numbers? Single byte BINARY value Terminal start-up Function code sequence 1Bh 59h 1Bh 1Bh 1Bh 60h Terminal exit Function code sequence none Highlight-on Function code sequence 1Bh 1Bh 1Bh 52h Highlight-off Function code sequence 1Bh 1Bh 1Bh 51h Erase to End of Line 1Bh 54h Delete Line 1Bh 52h Insert Line 1Bh 45h Does your terminal use last character on screen as a scroll command? YES Most Commodore printers require installation as a Standard Printer with NO Communications Protocol and Primary list device as the Printer Driver. Note: The h against the numbers above indicate that they are hexadecimal numbers (using base 16 instead of the decimal base 10). SECTION 12 12. Files, Disks, and Drives in CP/M 3.0 12.1 WHAT IS A FILE? 12.2 CREATING A FILE 12.3 NAMING A FILE 12.3.1 File Specification 12.3.1.1 Drive Specifier 12.3.1.2 Filename 12.3.1.3 Filetype 12.3.1.4 Password 12.3.1.5 Sample File Specification 12.3.4 User Number 12.3.5 Using Wildcard Characters to Access More Than One File 12.3.6 Reserved Characters Table 12-1. CP/M Reserved Characters. 12.3.7 Reserved Filetypes Table 12-2. CP/M 3.0 Reserved Filetypes. 12.1 WHAT IS A FILE? One of CP/M's most important tasks is to access and maintain files on your disks. Files in CP/M are fundamentally the same as in C128 or C64 modes - that is, they are collections of information. However, CP/M handles files somewhat differently than do C128 and C64 modes. This section defines the two types of files used in CP/M, tells how to create, name, and access a file, and describes how files are stored on your CP/M disks. As noted above, a CP/M 3.0 file is a collection of information. Every file must have a unique name by which CP/M identifies the file. A directory is also stored on each disk. The directory contains a list of the filenames stored on that disk and the locations of each file on the disk. There are two kinds of CP/M files: program (command) files, and data files. A program file contains a series of instructions that the computer follows step-by-step to achieve some desired result. A data file is usually a col- lection of related information (e.g. a list of names and addresses, the inventory of a store, the accounting records of a business, the the text of a document). 12.2 CREATING A FILE There are several ways to create a CP/M file. One way is to use a text edi- tor. The CP/M text editor ED is used to create and name a file. You can also create a file by copying an existing file to a new location; you can rename the file in the process. Under CP/M you can use the PIP command to copy and rename files. Finally, some programs (such as MAC, a CP/M machine language program) create output files as they process input files. The ED and PIP commands are summarized in Section 14, together with other commonly used CP/M commands. Details on these and all other CP/M 3.0 com- mands may be found in the CP/M Plus User's Guide, which you can obtain by following the instructions on the coupon enclosed in the box in which the C128 computer is supplied. 12.3 NAMING A FILE 12.3.1 File Specification CP/M identifies every file by a unique file specification. A file specifi- cation can have four parts: a drive specifier, a filename, a filetype, and a password. The only mandatory part is the filename. 12.3.1.1 Drive Specifier The drive specifier is a single letter (A-P) followed by a colon. Each disk drive in your system is assigned a letter. When you include a drive speci- fier as part of the file specification, you are telling CP/M to look for the file on the disk currently in the specified drive. For example, if you enter: B:MYFILE {return} CP/M looks in drive B for the file MYFILE. If you omit the drive specifier, CP/M 3.0 looks for the file in the default drive (usually A). 12.3.1.2 Filename A filename can be from one to eight characters long, such as: MYFILE A file specification can consist simply of a filename. When you make up a filename, try to let the name tell you something about what the file con- tains. For example, if you have a list of customer names for your business, you could name the file: CUSTOMER so that the name gives you some idea of what is in the file. 12.3.1.3 Filetype To help you identify files belonging to the same category, CP/M allows you to add an optional one- to three-character extension, called filetype, to the filename. When you add a filetype to the filename, separate the file- type from the filename with a period. Try to use letters that tell something about the file's category. For example, you could add the following filetype to the file that contains a list of customer names: CUSTOMER.NAM When CP/M displays file specifications, it adds blanks to short filenames so that you can compare filetypes quickly. The program files that CP/M loads into memory from a disk have the filetype COM. DO NOT use this file- type in your own file specifications. 12.3.1.4 Password In the Commodore 128's CP/M 3.0 you can include a password as part of the file specification. The password can be from one to eight characters. If you include a password, separate if from the filetype (or filename, if no filetype is included) with a semicolon, as follows: CUSTOMER.NAM;ACCOUNT A password is optional. However, if a file has been protected with a pass- word, you MUST enter the password as part of the file specification to access the file. 12.3.1.5 Sample File Specification A file specification containing all four possible elements consists of a drive specification, a primary filename, a filetype, and a password, all separated by the appropriate characters or symbols as in the following example: A:DOCUMENT.LAW;SUSAN {return} 12.3.4 User Number CP/M 3.0 further identifies all files by assigning each one a user number which ranges from 0 to 15. CP/M 3.0 assigns the user number to a file when the file is created. User numbers allow you to separate your files into 16 file groups. The user number always precedes the drive identifier except for user 0, which is the default user number and is not displayed in the prompt. Here are some examples of user numbers and their meanings. 4A> User number 4, drive A A> User number 0, drive A 2B> User number 2, drive B You can use the built-in command USER to change the current user number like this: A>USER 3 {return} 3A> You can change both the user number and the drive by entering the new user number and drive specifier together at the system prompt: A>3B: {return} 3B> Most commands can access only those files that have the current user num- ber. However, if a file resides in user 0 and is marked with a special file attribute, the file can be accessed from any user number. 12.3.5 Using Wildcard Characters to Access More Than One File Certain CP/M 3.0 built-in and transient commands can select and process several files when special wildcard characters are included in the filename or filetype. A wildcard is a character that can be used in place of some other characters. CP/M 3.0 uses the asterisk (*) and the question mark (?) as wildcards. For instance, if you use a {?} as the third character in a filename, your are telling CP/M to let the {?} stand for any character that may be encountered in that position. Similarly, an {*} tells CP/M to fill the filename with {?} question marks as indenticated. A file specification containing wildcards is called an ambiguous filespec and can refer to more than one file, because it gives CP/M 3.0 a pattern to match. CP/M 3.0 searches the disk directory and selects any file whose filename or filetype matches the pattern. For example, if you type: ?????TAX.LIB {return} then CP/M 3.0 selects all files whose filename ended in TAX and whose file- type is LIB. 12.3.6 Reserved Characters The characters in Table 12-1 have special meaning in CP/M 3.0, so do not use these characters in file specifications except as indicated. Table 12-1. CP/M Reserved Characters. Character < $ , ! | > [ ] file specification delimiters {tab} {space} ,, {carriage return} ,, : drive delimiter in file specification . filetype delimiter in file specification ; password delimiter in file specification * ? wildcard characters in an ambiguous file specification < > & ! | \ + - option list delimiters [ ] option list delimiters for global and local options ( ) delimiters for multiple modifiers inside square brackets for options that have modifiers / $ option delimiters in a command line ; comment delimiter at the beginning of a command line 12.3.7 Reserved Filetypes CP/M 3.0 has already established several file groups. Table 12-2 lists some of their filetypes with a short description of each. Table 12-2. CP/M 3.0 Reserved Filetypes. Filetype Meaning ASM Assembler source file BAS BASIC source program COM 8080, 8085, Z80 or equivalent machine language program HEX Output file from MAC (used by HEXCOM) HLP HELP message file $$$ Temporary file PRN Print file from MAC or RMAC REL Output file from RMAC (used by LINK) SUB List of commands to be executed by SUBMIT SYM Symbol file from MAC, RMAC or LINK SYS System file SECTION 13 13. Using the Console and Printer in CP/M 3.0 13.1 CONTROLLING CONSOLE OUTPUT 13.2 CONTROLLING PRINTER OUTPUT 13.3 CONSOLE LINE EDITING 13.4 USING CONTROL CHARACTERS FOR LINE EDITING Table 13-1. Banked CP/M 3.0 Line Editing Control Characters. This section describes how CP/M 3.0 communicates with your console and printer. It tells how to start and stop console and printer output, and edit commands you enter at your console. 13.1 CONTROLLING CONSOLE OUTPUT Sometimes CP/M 3.0 displays information on your screen too quickly for you to read it. To ask the system to wait while you read the display, hold down the {ctrl} key and press {s}. A CTRL-S keystroke sequence causes the dis- play to pause. When you are ready, press CTRL-Q to resume the display. Pressing the {no scroll} key will also pause the system and place a pause window on the status line at the bottom of the screen (line 25). To resume the display, press {no scroll} again. If you press any key besides CTRL-Q or {no scroll} during a display pause, CP/M 3.0 sounds the console bell. Some CP/M 3.0 utilities (like DIR and TYPE) support automatic paging at the console. This means that if the program's output is longer than the screen can display at one time, the display automatically halts when the screen is filled. When this occurs, CP/M 3.0 prompts you to press {return} to con- tinue. This option can be turned on or off using the SETDEF command. 13.2 CONTROLLING PRINTER OUTPUT You can also use a control command to echo (that is, display) console out- put to the printer. To start printer echo, press CTRL-P. A beep occurs to tell you that echo is on. To stop, press CTRL-P again. (There is no beep at this point.) While echo is in effect, any characters that appear on your screen are listed at your printer. You can use printer echo with a DIR command to make a list of files stored on a floppy disk. You can also use CTRL-P with CRTL-S and CTRL-Q to make a hard copy of part of a file. Use a TYPE command to start a display of the file at the console. When the display reaches the part you need to print, press CTRL-S to stop the display, CTRL-P to enable printer echo, and then CTRL-Q to resume the display and start printing. You can use another CTRL-S, CTRL-P, CTRL-Q sequence to terminate printer echo. 13.3 CONSOLE LINE EDITING As noted previously, you can correct simple typing errors by using the {inst/del} key or CTRL-H. CP/M 3.0 also supports additional line editing functions that you perform with control characters. You can use the con- trol characters to edit command lines or input lines to most programs. 13.4 USING CONTROL CHARACTERS FOR LINE EDITING Using the line editing control characters listed in Table 13-1, you can move the cursor left and right to insert and delete characters in the mid- dle of a command line. In this way you do not have to retype everything to the right of your correction. In the following example, the user mistypes PIP, and CP/M 3.0 returns an error message. The user recalls the erroneous command line by pressing CTRL-W and corrects the error. A>POP A:=B:*.* (PIP mistyped) POP? A>POP A:=B:*.* (CTRL-W recalls the line) A>POP A:=B:*.* (CTRL-B moves the cursor to beginning of line) A>POP A:=B:*.* (CTRL-F moves cursor to right) A>PP A:=B:*.* (CTRL-G deletes error) A>PIP A:=B:*.* (type I corrects the command name) After the command line is corrected, the user can press {return} even though the cursor is in the middle of the line. A {return} keystroke, (or one of the equivalent control characters) not only executes the command, but also stores the command in a buffer so that you can press CTRL-W to recall it for editing or re-execution. When you insert a character in the middle of a line, characters to the right of the cursor move to the right. If the line becomes longer than your screen is wide, characters disappear off the right side of the screen. These characters are not lost. They reappear if you delete characters from the line or if you press CTRL-E when the cursor is in the middle of the line. CTRL-E moves all characters to the right of the cursor to the next line on the screen. Table 13-1 gives a complete list of line editing control characters for the CP/M 3.0 system on the Commodore 128. Table 13-1. Banked CP/M 3.0 Line Editing Control Characters. Character Meaning CTRL-A Moves the cursor one character to the left. CTRL-B Moves the cursor to the beginning of the command line without having any effect on the contents of the line. If the cursor is at the beginning, CTRL-B moves it to the end of the line. CTRL-E Forces a physical carriage return but does not send the command line to CP/M 3.0. Moves the cursor to the beginning of the next line without era- sing the previous input. CTRL-F Moves the cursor one character to the right. CTRL-G Deletes the character above the cursor. The cursor does not move. Characters to the right of the cursor move left one position. CTRL-H Deletes the character to the left of the cursor and moves the cursor left one character position. Characters to the right of the cursor move left one position. CTRL-I Moves the cursor to the next tab stop. Tab stops are automati- cally set at each eighth column. Has the same effect as pressing the {tab} key. CTRL-J Sends the command line to CP/M 3.0 and returns the cursor to the beginning of a new line. Has the same effect as a {return} or a CTRL-M keystroke. CTRL-K Deletes from the cursor to the end of the line. CTRL-M Sends the command line to CP/M 3.0 and returns the cursor to the beginning of a new line. Has the same effect as a {return} or a CTRL-J keystroke. CTRL-R Retypes the command line. Place a # character at the current cursor location, moves the cursor to the next line, and retypes any partial command you typed so far. CTRL-U Discards all the characters in the command line, places a {#} character at the current cursor position, and moves the cursor to the next line. However, you can use CTRL-W to recall any characters that were to the left of the cursor when you pressed CTRL-U. CTRL-W Recalls and displays previously entered command line both at the operating system level and within executing programs, if the CTRL-W is the first character entered after the prompt. CTRL-J, CTRL-M, CTRL-U, and {return} define the command line you can recall. If the command line contains characters, CTRL-W moves the cursor to the end of the command line. If you press {return}, CP/M 3.0 executes the recalled command. CTRL-X Discards all the characters to the left of the cursor and moves the cursor to the beginning of the current line. CTRL-X saves any characters to the right of the cursor. SECTION 14 14. Summary of Major CP/M 3.0 Commands 14.1 THE TWO TYPES OF CP/M 3.0 COMMANDS 14.2 BUILT-IN COMMANDS Table 14-1. Built-in Commands. 14.3 TRANSIENT UTILITY COMMANDS Table 14-2. Transient Utility Commands. 14.4 REDIRECTING INPUT AND OUTPUT Figure 14-1. PUT Command Example. 14.5 ASSIGNING LOGICAL DEVICES Table 14-3. CP/M 3.0 Logical Devices. 14.6 FINDING PROGRAM FILES 14.7 EXECUTING MULTIPLE COMMANDS 14.8 TERMINATING PROGRAMS 14.9 GETTING HELP As noted in section 11, a CP/M 3.0 command line consists of a command key- word, an optional command tail and a {return} keystroke. This section describes the two kinds of commands the command keyword can identify, and summarizes individual commands and their functions. The section also gives examples of the use of some of the more commonly used commands. In addition, the section explains the concept of logical and physical devices under CP/M 3.0. This section then tells how CP/M 3.0 searches for a program file on a disk, tells how to execute multiple commands, and how to reset the disk system. Finally, the section explains how to use the HELP command to get information on various CP/M topics including command formats and usage, right at the keyboard. 14.1 THE TWO TYPES OF CP/M 3.0 COMMANDS There are two types of commands on CP/M 3.0: * Built-in commands - which identify programs in memory * Transient utility commands - which identify program files on a disk CP/M 3.0 has six built-in commands and over 20 transient utility commands. You can add utilities to your system by purchasing various CP/M 3.0- compatible application programs. If you are an experienced programmer, you can also write your own utilities that operate with CP/M 3.0. 14.2 BUILT-IN COMMANDS Built-in commands are part of CP/M 3.0 that are always available for your use, regardless of which disk your have in which drive. Built-in commands are entered in the computer's memory when CP/M 3.0 is loaded, and are, therefore, executed more quickly than the transient utilities. Table 14-1 lists the Commodore 128 CP/M 3.0 built-in commands. Some built-in commands have options that require support from a related transient utility. The related transient utility command has the same name as the built-in command and has a filetype of COM. Table 14-1. Built-in Commands. Command Function DIR Displays filenames of all files in the directory except those marked with the SYS attribute. DIRSYS Displays filenames of file marked with the SYS (system) attribute in the directory. ERASE Erases a filename from the disk directory and releases the storage space occupied by the file. RENAME Renames a disk file. TYPE Displays contents of an ASCII (TEXT) file at your screen. USER Changes to a different user number. 14.3 TRANSIENT UTILITY COMMANDS The CP/M 3.0 transient utilities are listed in Table 14-2. When you enter a command keyword that identifies a transient utility, CP/M 3.0 loads the program file from the disk and passes to that file any filenames, data, or parameters you entered in the command tail. DIR, RENAME and TYPE are built-in commands which have optional transient extensions. Table 14-2. Transient Utility Commands. DATE Sets or displays the date and time. DEVICE Assigns logical CP/M devices to one or more physical devices, changes device driver protocol and baud rates, or sets console screen size. DIR Displays directory with files and their characteristics. DUMP Displays a file in ASCII and hexadecimal format. ED Creates and alters ASCII files. ERASE Used for wildcard erase. FORMAT Formats a CP/M disk. Clears data from previous used disks. GENCOM Creates a special COM file with attached RSX file. GET Temporarily gets console input from a disk file rather than the keyboard. HELP Displays information on how to use CP/M 3.0 commands. INITDIR Initializes a disk directory to allow time and date stamping. KEYFIG Allows alteration of the definition of the keyboard keys. PATCH Displays or installs patches to the CP/M system. PIP Copies files and combines files. PUT Temporarily directs printer or console output to a disk file. RENAME Changes the name of a file, or a group of files using wildcard characters. SAVE Copies the contents of memory to a file. SET Sets file options including disk labels, file attributes, type of time and date stamping and password protection. SETDEF Sets system options including the drive search chain. SHOW Displays disk and drive statistics. SUBMIT Automatically executes multiple commands. TYPE Displays contents of text file (or group of files, if wildcard characters are used) on screen (and printer if desired). 14.4 REDIRECTING INPUT AND OUTPUT CP/M 3.0's PUT Command allows you to redirect console or printer output to a disk file. You can use a GET command to make CP/M 3.0 or a utility pro- gram take console input from a disk file. The following examples illustrate some of the capabilities offered by GET and PUT. You can use a PUT command to direct console output to a disk file as well as to the console. With PUT, you can create a disk file containing a directory of all files on that disk, as shown in Figure 14-1. A>PUT CONSOLE OUTPUT TO FILE DIR.PRN PUTTING CONSOLE OUTPUT TO FILE: DIR.PRN A>DIR A: FILENAME TEX : FRONT TEX : FRONT BAK : ONE BAK : THREE TEX A: FOUR TEX : ONE TEX : LINEDIT TEX : EXAMP1 TXT : TWO BAK A: TWO TEX : THREE BAK : EXAMP2 TXT A>TYPE DIR.PRN A: FILENAME TEX : FRONT TEX : FRONT BAK : ONE BAK : THREE TEX A: FOUR TEX : ONE TEX : LINEDIT TEX : EXAMP1 TXT : TWO BAK A: TWO TEX : THREE BAK : EXAMP2 TXT Figure 14-1. PUT Command Example. A GET command can direct CP/M 3.0 or a program to read console input from a disk file instead of from the keyboard. If the file is to be read by CP/M 3.0, it must contain standard CP/M 3.0 command lines. If the file is to be read by a utility program, it must contain input appropriate for that pro- gram. A file can contain both CP/M 3.0 command lines and program input if it also includes a command to start a program. 14.5 ASSIGNING LOGICAL DEVICES The minimal Commodore 128 CP/M 3.0 hardware includes a console consisting of a keyboard and screen display and a 1571 disk drive. You may want to add another device to your system, such as a printer or a modem. To help keep track of these physical different input and output devices, Table 14-3 gives the names of CP/M 3.0 logical devices. It also shows the physical devices assigned to these logical devices in the Commodore 128 CP/M 3.0 system. Table 14-3. CP/M 3.0 Logical Devices. Logical Physical Device Device Name Device Type Assigment CONIN: Console input Keyboard CONOUT: Console output 80-column Screen AUXIN: Auxiliary input Null AUXOUT: Auxiliary output Null LST: List output PTR1 or PTR2 You can change these assigments with a DEVICE command. For example, you can, assign AUXIN and AUXOUT to a modem so that your computer can use tele- phone lines to communicate with other computer users, with information ser- vice like Compunet and View Data Systems. 14.6 FINDING PROGRAM FILES If a command keyword identifies a utility, CP/M 3.0 looks for that program file on the default or specified drive. It looks under the current user number, and then under user number 0 for the same file marked with the SYS attribute. At any point in the search process, CP/M 3.0 stops the search if it finds the program file. CP/M 3.0 then loads the program into memory and executes it. When the program terminates, CP/M 3.0 displays the system prompt and waits for your next command. However, if CP/M 3.0 does not find the command file, it repeats the command line followed by a question mark, and waits for your next command. 14.7 EXECUTING MULTIPLE COMMANDS In the examples so far, CP/M 3.0 executed only one command at a time. CP/M 3.0 can also execute a sequence of commands. You can enter a sequence of commands at the system prompt, or you can put a frequently needed sequence of commands in a disk file, using the filetype of SUB. Once you have stored the sequence in a disk file, you can execute the sequence whenever you need to with a SUBMIT command. 14.8 TERMINATING PROGRAMS You can use the two keystroke command CTRL-C to terminate program execution or reset the disk system. To enter a CTRL-C command, hold down the {ctrl} key and press {c}. Most application programs that run under CP/M and most CP/M transient uti- lities can be terminated by a CTRL-C. However, if you try to terminate a program while it is sending a display to the screen, you may need to press a CTRL-S to halt the display before you enter CTRL-C. 14.9 GETTING HELP CP/M 3.0 includes a transient utility command called HELP that displays a summary of the format and use for the most common CP/M commands. To access HELP, simply enter the command: A>HELP {return} You can press the {help} key instead of typing the word HELP and pressing the {return} key. The list of available topics is then displayed, like this: Topics available: COMMANDS CNTRLCHARS DATE DEVICE DIR DUMP ED ERASE FILESPEC GENCOM GET HELP HEXCOM INITDIR LIB LINK MAC PATCH PIP (COPY) PUT RENAME RMAC SAVE SET SETDEF SHOW SID SUBMIT TYPE USER XREF Suppose you type: HELP>PIP {return} CP/M then displays the following information: PIP (COPY) Syntax: DESTINATION SOURCE PIP d: Gn filespec [Gn] =filespec [o],... d: [o] Explanation: The file copy program PIP copies files, combines files, and transfers files between disks, printers, consoles, or other devices attatched to your computer. The first filespec is the destination. The second filespec is the source. Use two or more source filespecs separated by commas to combine two or more source files into one file. [o] is any combination of available options. The [Gn] option in the destination filespec tells PIP to copy your file to that user number. PIP with no command tail displays an * prompt and awaits your series of commands, entered and processed one line at a time. The source or destination can be any CP/M 3.0 logical device. The HELP facility provides information like this on all CP/M 3.0 built-in and transient utility commands. If you want information on a specific area, you can type HELP subject after the system prompt, where the subject is a command tail describing the subject you are interested in. For example: A>HELP PIP A>HELP DIRSYS You can refer to HELP any time you need information on a specific command. Or you can just browse through HELP to broaden your knowledge of CP/M 3.0. SECTION 15 15. Commodore Enhancements to CP/M 3.0 15.1 KEYBOARD ENHANCEMENTS 15.1.1 Defining a Key 15.1.2 Defining a String 15.1.3 Using ALT Mode 15.2 SCREEN ENHANCEMENTS 15.1 KEYBOARD ENHANCEMENTS Commodore has added a number of enhancements to CP/M 3.0. These enhance- ments tailor the capabilities of the Commodore 128 to those of CP/M 3.0. This section describes these enhancements. Any key on the keyboard can be defined to generate a code or function, except the following keys: {left shift} key {right shift} key {C=} key {ctrl} key {restore} key {40/80 display} key {caps lock} key In defining a key, the keyboard recognizes the following special functions. To indicate these functions, hold down the {ctrl} key and the {right shift} key and press the desired function key simultaneously. Key Function {crsr left} key Defines key {crsr right} key Defines string (points to function keys) {alt} key Toggles key filter 15.1.1 Defining a Key A user can define the code that a key can produce. Each key has four pos- sible definitions: Normal, Alpha Shift, Shift and Control. The Alpha Shift is toggle on/off by pressing the {C=} key. After entering this mode a small box appears on the bottom of the screen. The first key that is pressed is the key to be defined. The current HEX (hexadecimal) value assigned to this key is displayed and the user can then type the new HEX code for the key, or abort by typing a non-HEX key. The following is a definition of the codes that can be assigned to a key. (In ALT mode, codes are returned to the application; see "Using ALT Mode" below, in paragraph 15.1.3) Code Function 00h Null (same as not pressing a key) 01h to 7Fh Normal ASCII codes 80h to 9Fh String assigned A0h to AFh 80 column character color B0h to BFh 80 column background color C0h to CFh 40 column character color D0h to DFh 40 column background color E0h to EFh 40 column border color F0h Toggle disk status on/off F1h System Pause F2h (undefined) F3h 40 column screen window right F4h 40 column screen window left F5h to FFh (undefined) 15.1.2 Defining a String This function allows the user to assign more than one key code to a single key. Any key that is typed in this mode is placed in the string. The user can see the result of typing in a long box at the bottom of the screen. Note: Some keys may not display what they are. To provide the user with control over the process of entering data, the following five special key functions are available. To access these functions, press the {ctrl} and {right shift} keys and the desired function keys. Key Function {return} Complete string definition {+} (on main keyboard) Insert space into string {-} (on main keyboard) Delete cursor character {left arrow} Cursor left {right arrow} Cursor right 15.1.3 Using ALT Mode ALT mode is a toggle function (that is, it can be switched between ON and OFF). The default value is OFF. This function allows the user to send 8-bit codes to an application. 15.2 SCREEN ENHANCEMENTS The screen in CP/M 3.0 emulates an ADM31 terminal. The following screen functions emulate ADM 3A operation, which is a subset of ADM31 operation. CTRL-G Sound Bell CTRL-H Cursor left CTRL-J Cursor down CTRL-K Cursor up CTRL-L Cursor right CTRL-M Move cursor to start of current line (CR) CTRL-Z Home and clear screen ESC = RC Cursor position where R is the row location (with values from space to 8) and C is the column location (next values from space to 0), referenced to the status line. Additional functions in ADM31 mode include: ESC T} ESC t} Clear to end of line ESC Y} ESC y} Clear to end of screen ESC :} ESC *} Home and clear screen (including the status line) ESC Q Insert character ESC W Delete character ESC E Insert line ESC R Delete line * {esc} {esc} {esc} [color#] sets a screen color from a table of 16 pos- sible color entries. The [color#] is set as follows: 20h to 2Fh character color 30h to 3Fh background color 40h to 4Fh border color (40 column only) The visual effects associated with following functions are visible only in 80-column screen format: ESC > Half intensity ESC < Full intensity ESC G4 Reverse video ON * ESC G3 Turn underline ON ESC G2 Blink ON * ESC G1 Select the alternate character set ESC G0 All ESC G attributes OFF * Note: This is NOT a normal ADM31 sequence. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * The sections in this chapter provide a summary of the structure and wide- ranging capabilities of CP/M 3.0. Detailed information on any facet of CP/M is given in the Digital Research, Inc. book, CP/M Plus User's Guide. To ob- tain a copy of this, refer to the coupon enclosed in the box in which the Commodore 128 is supplied. CHAPTER 5 BASIC 7.0 ENCYCLOPAEDIA