********* Welcome to Project 64! The goal of Project 64 is to preserve Commodore 64 related documents in electronic text format that might otherwise cease to exist with the rapid advancement of computer technology and declining interest in 8- bit computers on the part of the general population. Extensive efforts were made to preserve the contents of the original document. However, certain portions, such as diagrams, program listings, and indexes may have been either altered or sacrificed due to the limitations of plain vanilla text. Diagrams may have been eliminated where ASCII-art was not feasible. Program listings may be missing display codes where substitutions were not possible. Tables of contents and indexes may have been changed from page number references to section number references. Please accept our apologies for these limitations, alterations, and possible omissions. Document names are limited to the 8.3 file convention of DOS. The first characters of the file name are an abbreviation of the original document name. The version number of the etext follows next. After that a letter may appear to indicate the particular source of the document. Finally, the document is given a .TXT extension. The author(s) of the original document and members of Project 64 make no representations about the accuracy or suitability of this material for any purpose. This etext is provided "as-is". Please refer to the warantee of the original document, if any, that may included in this etext. No other warantees, express or implied, are made to you as to the etext or any medium it may be on. Neither the author(s) nor the members of Project 64 will assume liability for damages either from the direct or indirect use of this etext or from the distribution of or modification to this etext. Therefore if you read this document or use the information herein you do so at your own risk. ********* The Project 64 etext of the ~Commodore 64 MicroComputer User Manual (2d ed)~, converted to etext by Frank Jeno Kontros . C64UG210.TXT, June 1997, etext #251# ********* Commodore 64 MicroComputer User Manual _____ / ___|___ | / |__/ c o m m o d o r e | \___|__\ C O M P U T E R \_____| COMMODORE 64 USER'S GUIDE Published by Commodore Business Machines, (UK) Ltd. Copyright (C) 1984 by Commodore Business Machines, (UK) Ltd. All rights reserved. This manual is copyrighted and contains proprietary information. No part of this publication may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior written permission of COMMODORE BUSINESS MACHINES, (UK) Ltd. TABLE OF CONTENTS INTRODUCTION 1. SETTING UP 1.1. Unpacking and Connecting the 64 1.2. Installation 1.3. Optional Connections 1.4. Operation 1.5. Troubleshooting Chart 1.6. Color Adjustment 1.7. Expanding Your System With Optional Peripherals 2. GETTING STARTED 2.1. Communicating with your 64: The Keyboard 2.2. Loading Programs 2.3. How to Format a New Disk 2.4. Saving Programs 2.5. Listing a Directory of Programs on a Disk 3. BEGINNING BASIC 3.1. Printing and Calculating 3.2. Mathematical Functions 3.3. Multiple Calculations on One Line 3.4. Execution Order in Calculations 3.5. Combining PRINT's Capabilities 4. WRITING SIMPLE PROGRAMS IN BASIC 4.1. Line Numbers 4.2. The GOTO Statement 4.2. Using the LIST Command 4.3. Editing Tips 4.4. How to Use Variables 4.5. Using FOR ... NEXT Loops 4.6. Using IF ... THEN Statements to Control Programs 5. ADVANCED BASIC 5.1. Simple Animation 5.2. INPUT 5.3. Using the GET Statement for Data Input 5.4. Using GET to Program Function Keys 5.5. Random Numbers and Other Functions 5.6. Guessing Game 5.7. Your Roll 5.8. Random Graphics 6. COLOR AND GRAPHICS 6.1. How to Use Color and Graphics on Your Computer 6.2. PRINTing Colors 6.3. Color CHR$ Codes 6.4. How to use PEEKs and POKEs 6.5. Screen Graphics 6.6. Screen Memory Map 6.7. Color Memory Map 6.8. More Bouncing Balls 7. INTRODUCTION TO SPRITES 7.1. Bits and Bytes 7.2. Creating a Sprite 7.3. Designing a Sprite 7.4. Sprite Pointers 7.5. Turning Sprites On 7.6. Sprite Colors 7.7. Positioning Sprites 7.8. Expanded Sprites 7.9. Creating More Than One Sprite 7.10. Sprite Priorities 7.11. Turning Sprites Off 8. MAKING SOUND AND MUSIC 8.1. The SID Chip 8.2. Sample Sound Program 8.3. Playing a Song on Your 64 8.4. Creating Sound Effects 8.5. Filtering 8.6. Music Composer 9. ADVANCED DATA HANDLING 9.1. READ and DATA Statements 9.2. Calculating Averages 9.3. Subscripted Variables 9.4. Dimensioning Arrays 9.5. Simulated Dice Roll with Arrays 9.6. Two-dimensional Arrays APPENDICES Introduction A: Expanding Your Commodore 64 Computer System B: Description of DOS Error Messages C: Commodore 64 BASIC D: Abbreviations for BASIC Keywords E: Screen Display Codes F: ASCII and CHR$ Codes G: Screen and Color Memory Map H: Deriving Mathematical Functions I: Pinouts for INPUT/OUTPUT Devices J: Programs to Try K: Converting Standard BASIC Programs to Commodore 64 BASIC L: Error Messages M: Music Note Values N: Bibliography O: Sprite Register Map P: 6566/6567 (VIC-II) Chip Register Map Q: Commodore 64 Sound Control Settings R: 6581 Sound Interface Device (SID) Chip Specifications S: Disk and Printer Commands and Statements INDEX THE INFORMATION IN THIS MANUAL HAS BEEN REVIEWED AND IS BELIEVED TO BE ENTIRELY RELIABLE. NO RESPONSIBILITY, HOWEVER, IS ASSUMED FOR INACCURACIES. THE MATERIAL IN THIS MANUAL IS FOR INFORMATION PURPOSES ONLY, AND IS SUBJECT TO CHANGE WITHOUT NOTICE. THIS MANUAL IS COPYRIGHTED AND CONTAINS PROPRIETARY INFORMATION. NO PART OF THIS PUBLICATION MAY BE REPRODUCED, STORED IN A RETRIEVAL SYSTEM, OR TRANSMITTED IN ANY FORM OR BY ANY MEANS, ELECTRONIC, MECHANICAL, PHOTOCOPYING, RECORDING, OR OTHERWISE, WITHOUT THE PRIOR WRITTEN PERMISSION OF COMMODORE BUSINESS MACHINES, (UK) LTD. Copyright (c) 1984 Commodore Business Machines (UK) Ltd. All rights reserved. INTRODUCTION Your new COMMODORE 64 is the best home computer available today. You can use your COMMODORE 64 for everything from business applications to household paperwork to exciting games. The 64 offers you lots of memory (64K), lots of color (16 different colors), lots of sound (music and sound effects), and lots of fun and practical uses. You can use prepackaged software, or you can write your own programs in easy-to-learn BASIC. This easy-to-read user's guide contains all the information you need to set up your equipment properly, understand how to operate your new COMMODORE 64, and learn how to create your own simple BASIC programs. This user's guide is intended to introduce you to computers, but it is beyond the scope of this manual to tell you everything you need to know about computers or about BASIC. However, this guide does refer you to a variety of publications that explain the topics we present here in more detail. For those of you who don't want to learn how to program, you won't have to search through the whole book to learn how to use Commodore prepackaged programs and games, or other prepackaged, third party software. We've put all the information you need to know right up front in Chapters 1 and 2. Many exciting features are waiting for you inside your COMMODORE 64. Your new computer gives you the microcomputer industry's most advanced graphics, which we call SPRITE GRAPHICS. Sprite graphics let you: o Design your own pictures in different colors, just like the ones you see on arcade-type video games. o Animate as many as 8 different picture levels at a time. o Move your creations anywhere on the screen. o Double their size. o Pass images in front or behind each other. o Use automatic collision detection that tells the computer to do whatever you want when sprites hit each other. These features let you design your own games. The COMMODORE 64 also has built-in music and sound effects that rival many well known music synthesizers. This part of your computer gives you: o 3 independent voices, each with a full 9 octave piano-type range. o 4 different waveforms (sawtooth, triangle, variable pulse and noise). o A programmable ADSR (attack, decay, sustain, and release) envelope generator. o A programmable high, low, and bandpass filter that you can use for each voice. o Variable resonance and volume controls. If you want your music to play back with professional sound reproduction, the COMMODORE 64 lets you connect your audio output to almost any high-quality amplification system. As your computing needs grow, so can your system. You can expand your system by connecting your COMMODORE 64 to other pieces of equipment, known as peripherals. These accessories include items like these: o The DATASSETTE* recorder, for tapes. o The VIC 1541 disk drive (as many as five at a time). o The COMMODORE dot matrix printers, for hard copies of your programs, letters, etc. o The MODEM cartridge, for access through your telephone to the massive data bases of larger computers, as well as the services of hundreds of specialists and a variety of information networks. o The Commodore 1701 color monitor. If you already have a VIC 1540 disk drive, your dealer can upgrade it for use with the COMMODORE 64. Commodore wants you to really enjoy your new COMMODORE 64. And to have fun, bear in mind that programming takes time to learn. Be patient with yourself as you go through the USER'S GUIDE. But, before you start, please take a few minutes to fill out and mail in the owner/registration card that came with your computer. This will ensure that your COMMODORE 64 is properly registered with Commodore Headquarters and that you receive the most up-to-date information regarding future enhancements for your machine. NOTE: Many programs are under development while this manual is being produced. Please check with your local Commodore dealer and with Commodore User's Magazines and Clubs, which will keep you up to date on the wealth of applications programs being written for the COMMODORE 64, worldwide. * DATASSETTE is a registered trade mark of Commodore Business Machines, Inc. 1. SETTING UP 1.1. UNPACKING AND CONNECTING THE 64 The following step-by-step instructions show you how to connect the 64 to your television set, sound system, or monitor and make sure everything is working properly. Before attaching anything to the computer, check the contents of the 64 container. Besides this manual, you should find the following items: 1. Commodore 64 2. Power supply (black box with an AC plug and supply cord) 3. Video cable If any items are missing check back with your dealer immediately for a replacement. First, take a look at the arrangement of the various connections on the computer and what each one does. /####\________________ /####______________________| ____/#### | / ---- ---- __ /-\ | | \--/ \--/ == \_/ | \________________\___/______/____|__/ \/ / | 3 2 1 GAME POWER POWER PORTS SWITCH SOCKET SIDE PANEL CONNECTIONS 1. POWER SOCKET. The free end of the cable from the power supply is attached here to supply power to the 64. 2. POWER SWITCH. Turns on power to the 64. 3. GAME PORTS. Each game connector can accept a joystick or game controller paddle, while the lightpen can only be plugged into the game port closest to the front of your computer. ___/###\__/##_##_##_##_##_##_##_##_##_##_##_##_##_##_##_##\__ |-------------------------------------------------------------| | +--------------+ /-\ /-\ +------+ +----------+ | | |==============| [=] O \_/ \_/ |======| |==========| | +-----/-------------/----/-----\-----\--------\---------\-----+ / / / \ \ \ \ 4 5 6 7 8 9 10 CARTRIDGE CHANNEL TV AUDIO/VIDEO SERIAL CASSETTE USER SLOT SELECTOR CONNECTOR CONNECTOR PORT INTERFACE PORT REAR CONNECTIONS 4. CARTRIDGE SLOT. The rectangular slot to the left accepts program or game cartridges. 5. CHANNEL SELECTOR. Use this switch to select which TV channel the computer's picture will be displayed on. 6. TV CONNECTOR. This connector supplies both the picture and sound to your television set. 7. AUDIO & VIDEO OUTPUT. This connector supplies direct audio, which can be connected to a high quality sound system, and a composite video signal, which can be fed into a television, or monitor, such as the Commodore 1701 color monitor. 8. SERIAL PORT. You can attach a COMMODORE printer or a VIC 1541 single disk drive directly to the Commodore 64 through this connector. 9. CASSETTE INTERFACE. A DATASSETTE recorder can be attached to the computer so you can save information on tape for use at a later time. 10. USER PORT. Various interface cartridges can be attached to the user port, such as the MODEM, or RS-232 communication cartridge. 1.2. INSTALLATION CONNECTIONS TO YOUR TV Connect the computer to your TV as shown bellow. +--+-----------------+--+ | | /-------------\#| | /--------------------------| | | |#| | | | | | |#| | | | | | | | | | | | | | | | | | | \-------------/ | | | +==+=================+==+ | /------------------------\ | |=---\ | #################### ## | | | #################### ## | | | ################## ## | | | ############## ## | | \________________________/ | | | | +---+ | | POWER | | SUPPLY +---+ | | 1. Attach one end of the TV cable to the phono type TV signal jack on the rear of the 64. Just push it in. Either end of the cable can be used. 2. Connect the other end of the cable to the antenna switchbox. Just push it in. 3. Plug the power supply cable into the power socket on the side of the Commodore 64. Just push it in. It is "keyed" to allow insertion in only one direction, so you can't connect the power cord the wrong way. The power supply converts household current into the form the computer uses. The 64 is now correctly connected. No additional connections are required to use the computer with your TV. 1701 MONITOR CONNECTIONS [REAR PANEL] Commodore 64 /---------------\ | AUDIO | __###__######################__ | _ | | | +-------------> |O| | |-------------_---_-------------| | | ~ | | ======== | | | | === ===== | # | COMMODORE VIDEO | +------------/------------------+ |W| | _ _ | / ^ \ / +----> |O| |O| <---+ Video Out / | # | | ~ ~ | | # | # | LUMA CHROMA | # | | W = White | |Y| | | |R| \ / Y = Yellow | \ / | SIGNAL SELECT | \ / # R = Red | # | [.##] | # # | | | FRONT | REAR | | # | | \_______|_______/ | # AUDIO = Audio Input | | | | # LUMA = Luminance Input | | ________|___________| # CHROMA = Chroma Input | | | | # \ | / Signal Selector # \|/ ____ # # FRONT | ###| REAR # Monitor Cable # ~~~~ ############################### ---> 1.3. OPTIONAL CONNECTIONS Since the 64 furnishes a channel of high fidelity sound, you may wish to play it through a quality amplifier to realize the best sound possible. In addition, the 64 also provides a standard composite video signal, that can be fed into a television monitor. These options are made possible by the audio/video output jack on the rear panel of the 64. The easiest way to gain access to these signals is by using a standard 5-Pin DIN audio cable (not supplied). This cable connects directly to the audio/video connector on the computer. Two of the four pins on the opposite end of the cable contain the audio and video signals. You can construct your own cable, using the pinouts shown in Appendix I as a guide. Normally, the BLACK connector of the DIN cable supplies the AUDIO signal. This plug may be connected to the AUXILIARY input of an amplifier, or the AUDIO IN connector of a monitor or other video system, such as a video cassette recorder (VCR). The WHITE or RED connector usually supplies the direct VIDEO signal. This plug is connected to the VIDEO IN connector of the monitor or video input section of some other video system, such as a VCR. Depending on the manufacturer of your DIN cable, the color coding of the plugs may be different. Use the pinouts shown in Appendix I to match up the proper plugs if you don't get an audio or video signal using the suggested connections. __###__################################__ | AUDIO/VIDEO | | OUTPUT | |-----------------_---_-------------------| | ========= = o | | | | ===== ========= | +-----------------------------------------+ ^ | /-\ | | | | # | | TO AUXILIARY | INPUT OR | ____________ TUNER INPUT | / \ / \ TO VIDEO IN +----++------------++----+ <-#-/ \-#-> +------------+---+ | || ### ====== || | | /--------\ | O | | || === OoooO || | || || = | | ||------------|| | || || o | | || | | | || | | \________/ | | | || | | | || | +------------+---+ +----++============++----+ TV MONITOR AUDIO SYSTEM If you purchased peripheral equipment, such as a VIC 1541 disk drive, an MPS 801, 802 or 803 printer, a 1520 plotter or a 1701 monitor, you may wish to connect it at this time. Refer to the user's manuals supplied with any additional equipment for the proper procedure for connecting it to the computer. A completed system might look like this. [ Picture omitted ] 1.4. OPERATION USING THE 64 1. Turn on the computer using the rocker switch on the right-side panel when you're looking at the computer from the front. 2. After a few moments the following will be displayed on the TV screen: **** COMMODORE 64 BASIC V2 **** 64K RAM SYSTEM 38911 BASIC BYTES FREE READY. _ <----------- CURSOR SIGNALS COMMODORE 64 IS WAITING FOR YOUR INPUT 3. If your TV has a manual fine tuning knob, adjust the TV until you get a clear picture. 4. You may also want to adjust the color and tint controls on the TV for the best display. You can use the color adjustment procedure described later to get everything set up properly. When you first get a picture, the screen should appear mostly dark blue, with a light blue border and letters. If you don't get the expected results, recheck the cables and connections. The accompanying chart will help you isolate any problem. 1.5. TROUBLESHOOTING CHART +-----------------------------------------------------------------------+ | Symptom Cause Remedy | +-----------------------------------------------------------------------+ | Indicator Light Computer not "On" Make sure power switch | | not "On" is in "On" position | +-----------------------------------------------------------------------+ | Power cable not Check power socket for | | plugged in loose or disconnected | | power cable | +-----------------------------------------------------------------------+ | Power supply not Check connection with | | plugged in wall outlet | +-----------------------------------------------------------------------+ | Bad fuse in Take system to authorized | | computer dealer for replacement of | | fuse | +-----------------------------------------------------------------------+ | No picture TV on wrong Check other channel | | channel for picture (3 or 4) | +-----------------------------------------------------------------------+ | Incorrect Computer hooks up to | | hookup VHF antenna terminals | +-----------------------------------------------------------------------+ | Video cable not Check TV output cable | | plugged in connection | +-----------------------------------------------------------------------+ | Computer set for Set computer for same | | wrong channel channel as TV (3 or 4) | +-----------------------------------------------------------------------+ | Random patterns on Cartridge not Reinsert cartridge after | | TV with cartridge properly inserted turning off power | | in place | +-----------------------------------------------------------------------+ | Picture without Poorly tuned TV Retune TV | | color | +-----------------------------------------------------------------------+ | Picture with Bad color Adjust color/hue/ | | poor color adjustment on TV brightness controls on TV | +-----------------------------------------------------------------------+ | Sound with excess TV volume up high Adjust volume of TV | | background noise | +-----------------------------------------------------------------------+ | Picture OK, TV volume too low Adjust volume of TV | | but no sound | +-----------------------------------------------------------------------+ | Aux. output not Connect sound jack to | | properly connected aux. input on amplifier | | and select aux. input | +-----------------------------------------------------------------------+ +-----------------------------------------------------------------------+ | TIP: The 64 was designed to be used by everyone. | | But we at Commodore recognize that computer users may, occasionally, | | run into difficulties. To help answer your questions and give you | | some fun programming ideas, Commodore has created several | | publications to help you. You might also find that it's a good idea | | to join a Commodore Users Club to help you meet some other 64 owners | | who can help you gain knowledge and experience. | +-----------------------------------------------------------------------+ CURSOR The flashing square under READY is called the cursor. It's a marker that shows where what you type on the keyboard will be displayed on the screen. As you type, the cursor moves ahead one space as the original cursor position is replaced with the character you typed. Try typing on the keyboard and watch the cursor move while characters you type are displayed on the screen. 1.6. COLOR ADJUSTMENT There is a simple way to get a pattern of colors on the monitor so you can easily adjust the set. Even though you may not be familiar with the operation of the computer right now, just follow along, and you'll see how easy it is to use your computer. First, look on the left side of the keyboard and locate the key marked . This stands for ConTRoL and is used, in conjunction with other keys, to instruct the computer to do a specific task. To use a control function, you hold down the key while pressing a second key. Try this: hold the key while also pressing the <9> key. Then release both keys. Nothing obvious should have happened, but if you touch any key now, the screen will show the character displayed in reverse type, rather than normal type -- like the opening message or anything you typed earlier. Hold down the . What happens? If you did the above procedure correctly, you should see a light blue bar move across the screen and then move down to the next line as long as the is pressed. READY. ____________________________ __________ Now, hold while pressing any of the other number keys. Each of them has a color marked on the front. Anything displayed from this point will be in that color. For example, hold and the <8> key and release both. Now hold the . Watch the display. The bar is now in yellow! In a like manner you can change the bar to any of the colors indicated on the number keys by holding and the appropriate key. Change the bar to a few more different colors and then adjust the color and tint controls on your monitor so the display matches the colors you selected. The display should appear something like this: READY. _________________________ <------ <3> RED BAR _______ ____________ ____ <------ <3>,<6>,<7> RED, GREEN, BLUE BARS __________ ______________ <------ <7>,<8> BLUE, YELLOW BARS ____________ <------ <8> YELLOW BAR At this point everything is properly adjusted and working correctly. The following chapters will introduce you to the BASIC language. However, you can immediately start using some of the many prewritten applications and games available without knowing anything about computer programming. Each of these packages contains detailed information about how to use the program. It is suggested, though, that you read through the first few chapters of this manual to become more familiar with the operation of your new system. 1.7. EXPANDING YOUR SYSTEM WITH OPTIONAL PERIPHERALS Commodore offers a variety of peripheral devices that expand the capabilities of your computer. These peripherals include: o storage devices o printers and plotters o monitors o modems for telecommunications o game attachments o speech and graphics modules o desktop controllers STORAGE DEVICES Disk Drives Commodore's disk drives let you store large amounts of information on 5-1/4" floppy diskettes. Diskettes offer fast storage and retrieval, and they automatically keep track of all your files in a directory, or table of contents, that you can display on your screen or print on a printer. In addition, you can add extra disk drives by daisy-chaining them to your computer. Daisy-chaining means connecting one drive to the computer, and then connecting additional drives to each other. By acquiring the Commodore 64 IEEE Interface Expansion Card, you can also attach any IEEE disk drive, such as Commodore's CBM 8050 or 4040 Dual Floppy Disk Drives, to the 64. Chapter 2 contains detailed information on using disk drives. PRINTING AND PLOTTING DEVICES Printers You can attach Commodore printers to the 64. These are inexpensive dot matrix printers. By acquiring the Commodore 64 IEEE Interface Expansion Card, you can also attach any IEEE printer, such as Commodore's 6400 letter quality printer, or the high speed 8023 dot matrix printer, to the 64. Printer/Plotter Commodore's 1520 Printer/Plotter prints and draws graphics in four colors (black, blue, red and green). With the 1520, you can draw bar charts, pies, and a variety of complex graphics. THE 1701/1702 MONITOR Commodore's 14" color monitor offers a superior color picture with high resolution that enhances your computing experience. This monitor can be connected to the 64. The monitor is connected to the computer by an 8-pin DIN cable. The 1701/1702 Color Monitor User's Guide that comes with the monitor clearly explains connections. You can also consult Appendix I for information about the pinouts in the 8-pin connector. ATTACHMENTS FOR GAMES AND OTHER USES Commodore offers joysticks and paddles that enhance game-playing on your computer. These attachments also have other applications. Also available is the Commodore lightpen which, with appropriate software allows communication with the computer on the screen. COMMODORE GRAPHIC AIDS Commodore provides a variety of graphics programming aids, including SIMON'S BASIC which adds 114 powerful new commands to BASIC, including programming help and graphics commands; and LOGO, an easy-to-learn programming language with TURTLE graphics. MUSIC ATTACHMENTS Commodore will also soon offer a Musical Keyboard and a 3-pad percussion attachment called the Digi-drum. Both products will include special software packages. These attachments will increase the music making capabilities of the 64 computers. CONNECTING TO A STEREO SYSTEM The sound and music-making capabilities of the COMMODORE 64 can be enhanced by connecting your computer to a high quality amplifier and stereo speakers. The 8-pin DIN cable discussed in the 1701/1702 Color Monitor section can also be used to connect your computer to an amplifier. DESIGNING A COMPUTER SYSTEM FOR YOUR NEEDS Commodore offers a variety of peripherals that let you create your own customized computer system. We offer different types of storage, printing, and telecommunications devices so you can choose what's best for you. For more information about Commodore peripherals, read The Commodore Peripherals Guide and the Commodore magazines discussed in Appendix H and consult your Commodore dealer. 2. GETTING STARTED 2.1. COMMUNICATING WITH YOUR 64: THE KEYBOARD The computer keyboard lets you communicate with your 64. You use the keys to tell the computer what you want it to do and to answer the questions the computer displays on the screen. The keyboard looks like a regular typewriter, but the computer has special keys that let the 64 do more than a typewriter. While you read the next few pages, take a look at these special keys. The key tells the computer to look at what you typed and put this information in memory. The key also moves the cursor to the next line. NOTE: Memory is all the information the computer currently knows without needing you to tell it where to look. The key works like the shift key on a regular typewriter: it lets you print capital letters or the top characters on double character keys. ___ ___ ___ / ! \ / " \ / # \ || 1 || || 2 || || 3 || /\___/\ /\___/\ /\___/\ |_____| |_____| |_____| When you are using the graphics on the font of the keys, the key displays the graphic character on the RIGHT side of the key. ___ ___ ___ / \ / \ / \ || Q || || W || || E || /\___/\ /\___/\ /\___/\ |_|_-_| |_-_|_| |_|_-_| When you are using the four special function keys at the right side of the keyboard, the key gives you the functions on the FRONT of the key (F2, F4, F6, and F8). KEYS THAT LET YOU MAKE CHANGES The cursor is the little colored rectangle that marks your place on the screen. There are two CuRSoR keys: moves the cursor up and down moves the cursor left and right You must use the key with the key to move the cursor up, and with the key to move the cursor to the left. You don't have to keep tapping a key to get it to move more than one space. Just hold it down until the cursor is where you want it. DEL stands for DELete. When you press the key, the cursor moves back a space and erases the character that's there. PRINT "ERROR"#_ PRINT "ERROR"# When you DELete in the middle of a line, move the cursor just to the left of the character you want to DELete. FIX IT AGAINS, SAM FIX IT AGAINS_ SAM Then press the key. The characters to the right automatically move over to close up the space. FIX IT AGAIN, SAM INST stands for INSerT. You have to use the key with the key when you want to insert characters in a line. If you've left some characters out of a line, use the keys to move the cursor back to the error. WHILE U WERE OUT WHILE _ WERE OUT Then, while you hold down the key, press the key until you have enough space to add the missing characters. doesn't move the cursor; it adds space between the cursor and the character to its right. WHILE _ U WERE OUT WHILE YOU WERE OUT Use the and keys together to fix wrong characters. WE'RE NUMBER TWO! WE'RE NUMBER ! WE'RE NUMBER _ ! WE'RE NUMBER ONE! HOME moves the cursor back to the upper left corner of the screen. This is called the "HOME" position. CLR stands for CLeaR. When you use the key with the key, the screen CLeaRs and the cursor returns to the home position. The RESTORE key returns the computer to its normal state by RESTOREing the default conditions (e.g., the default screen color is blue, the default for I/O chips is OFF, etc.). RESTORE does such things as clear the screen, returning it to the original color, and turn off the picture- and sound-making chips. NOTE: For to work, you must hold down the key while you press the key. For example, suppose you've just played a music program that also turned your screen red and yellow while it LISTed the program. When you press and at the end of the program, the last note from the program will cease, your screen will turn blue and the only thing displayed will be the READY prompt. FUNCTION KEYS The keys on the right side of the keyboard, F1-F8, are function keys that you can program to perform a variety of tasks. The explanation of the GET statement in Chapter 5 tells you how to program function keys in BASIC. The ConTRoL key lets you set colors and do other special tasks called control functions. To set colors, hold down the key while you press the key with the color you want. You can get eight more colors with the key. Chapter 6 also has more about colors. To get a control function, hold the key down while you press the other key. Control functions are commonly used in prepackaged software such as a word processing system. You can halt a BASIC program while it is still RUNning by pressing the key. You can also use the key to halt a printout while it is still printing. lets you load a program automatically from cassette. When you want to use the key, you must also use the key. COMMODORE KEY The Commodore key can do two things: 1. lets you switch back and forth between the upper and lower case display mode (the letters and characters on the tops of the keys) and the upper case/graphic display mode (capital letters and the graphics on the fronts of the keys). To switch modes, press the and keys at the same time. When you first turn on your 64, it is in the upper case/graphic mode, which means that everything you type in is in capital letters. When you are in this mode, you can also print all the graphics on the fronts of the keys. o To print the graphic on the right side of a key, hold down the key while you press the key with the graphic you want to print. You can only print the right side graphics when you are in the upper case/ graphic mode. o To print the graphic on the left side of a key, hold down the key while you press the graphic key. You can print the left side graphic in either mode. 2. The key also lets you use the second set of eight alternate colors not shown on the color keys. To get these other colors, hold down the key while you press the number for the color you want. 1 ORANGE 5 GREY 2 2 BROWN 6 LT. GREEN 3 LT. RED 7 LT. BLUE 4 GREY 1 8 GREY 3 2.2. LOADING PROGRAMS The COMMODORE 64 accepts programs from disk, cartridge, or cassette tapes. This means you can use prewritten software simply by loading it. But more important, the 64 lets you save your own programs for reuse. To reuse a program you wrote and saved on disk or tape, all you do is load and run it. When you use tapes or disks with your COMMODORE 64 be sure that your disk drive or cassette unit is correctly connected. Loading Cartridges You can use a special line of programs and games on cartridge with your 64. The programs include a wide variety of business and personal applications. The games are just like real arcade games, not imitations. Follow these steps to load games and other cartridges: 1. Turn OFF your COMMODORE 64. YOU MUST TURN OFF YOUR COMMODORE 64 BEFORE YOU INSERT OR REMOVE CARTRIDGES. IF YOU DON'T, YOU MAY DAMAGE THE CARTRIDGE AND THE COMPUTER. 2. Insert the cartridge label uppermost in the slot on the back of your computer. 3. Turn on your 64. 4. Begin the game by typing the START key that's listed in the game's instruction sheet. Loading Prepackaged Cassette Tapes You can also buy prepackaged software on cassette tape. These cassettes are just like the ones with recorded music that you can play on a stereo. 1. Insert the cassette into your 1530 DATASSETTE recorder. 2. Make sure the tape is completely rewound to the beginning of the first side. 3. Type LOAD on your keyboard. The computer answers by displaying: PRESS PLAY ON TAPE 4. Press PLAY on your DATASSETTE. The screen goes blank until the computer finds the program. Then the screen displays the message FOUND (PROGRAM NAME). 5. Press the key. This actually loads the program into the computer. If you want to stop the loading, press the key. Loading Your Own Programs From Cassette Tape The COMMODORE 64 lets you write and save programs on any brand of cassette tape. All you need is a 1530 DATASSETTE recorder and the same kind of blank tape you'd use to record music for a stereo tape player. Follow these simple steps to load a program you wrote and saved on tape: 1. Rewind the tape to the beginning. 2. Type LOAD "PROGRAM NAME". If you don't remember the program name, just type LOAD. This loads the first program on the tape into memory. 3. Press . The computer responds with: PRESS PLAY ON TAPE 4. Press the PLAY key. The screen goes blank while the computer searches for the program. When the program is found, the screen displays this message: FOUND PROGRAM NAME 5. Press the key to actually load the program. The screen again goes blank during LOADing. When the program is LOADed, the screen returns to normal and the READY prompt appears. If you want to abort the loading, press the key. NOTE: When you load a new program into the computer's memory, any instructions and unsaved programs in the computer are erased and lost permanently. Before you LOAD a new program, be sure everything you want to keep is saved. After your program is LOADed, you can RUN it, LIST it, or make changes. Remember that you have to reSAVE a changed program if you want to keep the new version. Loading Disks Disks, which are often called "floppy disks", are really easy to use. The advantage of disks over tapes is that you can find data stored on disks much faster. You can also save much more data on a disk than on tape. The steps are the same for loading preprogrammed disks and disks that you program yourself. 1. Insert a disk into your disk drive. Make sure the label on the disk is facing up. Put the disk in so that the labeled end goes in last. Look for a little notch on the disk (it might be covered with a little piece of tape). This notch must be on the left side as you put in the disk, assuming that you're facing your computer. Be sure the disk is all the way in. 2. Close the protective gate on the disk drive after you insert the disk. Just push down the lever. 4. Type LOAD"PROGRAM NAME",8. The 8 is the code for disks. You need to type it here to let the computer know you're loading a disk. NOTE: You can LOAD the first program by using the * sign in place of the program name: LOAD"*",8. 4. Press the key. The disk will spin and your screen will say: SEARCHING FOR PROGRAM NAME LOADING READY _ 5. Type RUN when the screen says READY and the cursor appears. Your software is ready to use. 2.3. HOW TO FORMAT A NEW DISK When you're using a new, unprogrammed disk for the first time, you need to format it. Formatting, which is also called headering, prepares your disk by doing things like dividing the disk into blocks. Formatting also creates a directory that you use as a table of contents for the files you save on the disk. DO NOT header a preprogrammed disk. You only have to format new disks, not disks that already have programs on them unless you want to erase the entire disk and reuse it. To format a new disk, use this special version of the OPEN and NEW commands: OPEN 1,8,15,"N0:," N0 tells the computer to header (NEW) the disk in drive 0. If you have a dual disk drive connected (via a suitable interface) header disks in drive 0. The you use in this command goes in the directory as the name of the entire disk. Give the disk any name up to 16 characters. The is any two characters. Give the disk any you want, but you should give every disk a different code. When the disk drive light goes off, type CLOSE 1 and press . BE CAREFUL! Headering a disk erases all information on the disk, if there is any. Header only a new disk or a disk you are willing to erase. Here are some examples of formatting commands that header a disk: OPEN 1,8,15,"N0:MYFILE,A3" OPEN 1,8,15,"N0:$RECORDS,02" Now that you know how to header a disk, you are ready to use disks to write and save programs on your COMMODORE 64. Appendix S contains more information on the OPEN command. 2.4. SAVING PROGRAMS When you want to reuse a program you've written, be sure to SAVE it before you LOAD another program. If you don't, you'll lose the program. When you change a SAVEd program, you have to SAVE it again if you want to keep the new version. When you reSAVE a program, you are replacing the old version with the new one. If you want to keep both the old and the changed versions, you have to give the new one a different name when you SAVE it. Saving on Disk When you want to SAVE a program you've written on disk, follow these simple steps: 1. Key in SAVE"PROGRAM NAME",8. The 8 is the code for disks. It tells the computer that you're using a disk. 2. Press . The disk makes a noise, and the computer displays this message when the program is saved: SAVING PROGRAM NAME OK READY _ Saving on Cassette Tape When you want to SAVE a program you've written on cassette tape, follow these steps: 1. Key in SAVE"PROGRAM NAME". The program name you use can be up to 16 characters long. 2. Press the key. The computer displays the message PRESS RECORD AND PLAY ON TAPE. 3. Press the RECORD and PLAY keys on your DATASSETTE recorder. The screen goes blank and turns the color of the border. The READY prompt reappears when the program is SAVEd. 2.5. LISTING A DIRECTORY OF PROGRAMS ON A DISK When you SAVE programs on a disk, the computer automatically makes a table of contents, or a DIRECTORY, of the names of the programs on the disk. You can display this directory to see what programs are on your disk. Follow these steps: 1. Key in: LOAD"$",8 and press . The computer displays this message: SEARCHING FOR $ LOADING READY _ 2. Key in: LIST and press . Your programs names are displayed on your screen. 3. BEGINNING BASIC 3.1. PRINTING AND CALCULATING If you don't know BASIC, this section teaches you how to do some simple things like print words and calculate problems. The PRINT statement tells the 64 computer to print something on the screen. PRINT is one of the most useful and powerful commands in the BASIC language. You can use it to display just about anything, including graphics and the results of computations. To use the PRINT command, follow these steps: 1. Key in the word PRINT. This tells the computer what kind of job you want it to do. 2. Key in a quotation mark. This tells the computer where the message you want to print begins. 3. Key in whatever you want to print on the screen. 4. Key in a closing quotation mark. This tells the computer where the message you want to print ends. 5. Press the key. This tells the computer to follow your instructions, which in this case is to print your message exactly as you typed it. When you follow these steps, the computer prints your message and displays the READY prompt. It looks like this: PRINT "I LOVE MY COMMODORE" You key in this and press I LOVE MY COMMODORE The computer prints this READY _ The 64 prints whatever you enclose in quotes. Remember to key in both quotation marks. If you make a mistake in your PRINT statement, use the INST/DEL key to correct your error. You can change as many characters as you like before you press the key. If you made a mistake that you didn't catch before you pressed the key, the computer can't follow your instructions. Instead, it displays an error message to help you figure out what you did wrong. For example: ?SYNTAX ERROR If you get this message, check over what you typed in to see where you made a mistake. The computer is very precise, and it can't follow instructions that contain spelling errors or other mistakes. To avoid mistakes, be sure you type things in the correct form. Remember that the best way to get to know BASIC and your 64 is to try different things and see what happens. USING PRINT TO CALCULATE You can use PRINT to do more than just display what you put in quotation marks. You can also use it to perform calculations and automatically display the results. Follow these steps: 1. Key in PRINT. 2. Key in the calculation you want to solve. DON'T enclose it in quotation marks. 3. Press the key. The computer displays the answer followed by the READY prompt. Here's an example: PRINT 12 + 12 Type this line and press 24 READY The computer displays _ the answer Be sure you leave off the quotation marks when you want the computer to solve a problem. If you type the problem inside quotation marks, the computer assumes you just want to display the problem, not solve it. For example: PRINT "12 + 12" Key in this line and press 12 + 12 READY The computer displays _ what's in quotes So all you have to do to use PRINT as a calculator is omit the quotation marks. You can use PRINT to add, subtract, multiply and divide. You can also use exponents and perform advanced mathematical functions such as figuring square roots. 3.2. MATHEMATICAL FUNCTIONS ADDITION Use the plus sign (+) to tell the computer to add numbers. Remember to press after you type PRINT and the calculation. This tells the computer to follow your instructions. SUBTRACTION Use the minus sign (-) to subtract. Press the key at the end of the calculation. For example: PRINT 12 - 9 Key in this and 3 The computer displays this MULTIPLICATION Use the asterisk (*) to multiply. You can't use the conventional x because the computer would think it's the letter x, not the multiplication sign. Press at the end of the calculation. For example: PRINT 12 * 12 Key in this and 144 The computer displays this DIVISION Use the slash mark (/) for division. Press the key after you type the calculation. For example: PRINT 144/12 Key in this and 12 The computer displays this EXPONENTIATION Use the up arrow (^) to raise a number to a power. Press the key after you type the calculation. For example, to find 12 to the fifth power, type this: PRINT 12^5 Key in this and 248832 The computer displays this This is the same as: PRINT 12*12*12*12*12 248832 +-----------------------------------------------------------------------+ | TIP: | | BASIC has shortcuts that make programming even faster. One shortcut | | is abbreviating BASIC keywords. For example, you can use a ? in place | | of PRINT. Throughout this book, we'll show you other abbreviations | | for BASIC keywords. Appendix D lists these abbreviations and shows | | what is displayed on the screen when you type the abbreviated form. | +-----------------------------------------------------------------------+ 3.3. MULTIPLE CALCULATIONS ON ONE LINE The last example shows that you can perform more than one calculation on a line. You can also perform different kinds of calculations on the same line. For example: ? 3 * 5 - 7 + 2 Key in this and 10 The computer displays this So far our examples have used small numbers and simple problems. But the 64 can do much more complex calculations. The next example adds large numbers. Notice that 78956.87 doesn't have a comma between the 8 and the 9. You can't use commas this way in BASIC. BASIC thinks commas indicate new numbers, so it would think 78,956.87 is two numbers: 78 and 956.87. Remember to press after you type the problem. ? 1234.5 + 3457.8 + 78956.87 83649.17 The next example uses a ten digit number. The 64 can work with numbers that have up to ten digits, but can only display nine digits in the answer. So the 64 rounds numbers that are more than nine digits. Numbers five and over are rounded up, and numbers four and under are rounded down. This means that 12123123.45 is rounded to 12123123.5. Because of rounding, the computer doesn't give the same answer you'd get if you added these numbers by hand. In this case, the answer is 12131364.817. You can see the difference rounding makes. ? 12123123.45 + 345.78 + 7895.687 12131364.9 The 64 prints numbers between 0.01 and 999,999,999 using standard notation, except for leaving out commas in large numbers. Numbers outside this range are printed using scientific notation. Scientific notation lets you express a very large or very small number as a power of 10. For example: ? 123000000000000000 1.23E+17 Another way of expressing this number is 1.23 * 10 ^ 17. The 64 uses scientific notation for numbers with lots of digits to make them easier to read. There is a limit to the numbers the computer can handle, even using scientific notation. These limits are: Largest numbers : +/- 1.70141183E+38 Smallest numbers: +/- 2.93873588E-39 3.4. EXECUTION ORDER IN CALCULATIONS If you tried to perform some mixed calculations of your own, you might not have gotten the results you expected. This is because the computer performs calculations in a certain order. In this calculation: 20 + 8 / 2 the answer is 14 if you add 20 to 8 first, and then divide 28 by 4. But the answer is 24 if you first divide 8 by 2, and then add 20 and 4. On the 64, you always get 24 because the computer always performs calculations in the same order. Problems are solved from left to right, but within that general movement, some types of calculations take precedence over others. Here is the order of precedence: First : - minus sign for negative numbers, not for subtraction. Second: ^ exponentiation, left to right Third : * / multiplication and division, left to right Fourth: + - addition and subtraction, left to right This means that the computer checks the whole calculation for negative numbers before doing anything else. Then it looks for exponents; then it performs all multiplication and division; then it adds and subtracts. This explains why 20 + 8 / 2 is 24: 8 is divided by 2 before 20 is added because division has precedence over addition. There is an easy way to override the order of precedence: enclose any calculation you want solved first in parentheses. If you add parentheses to the equation shown above, here's what happens: ? (20 + 8) / 2 14 You get 14 because the parentheses allow 20 and 8 to be added before the division occurs. Here's another example that shows how you can change the order, and the answer, with parentheses: ? 30 + 15 * 2 - 3 57 ? (30 + 15) * 2 - 3 87 ? 30 + 15 * (2 - 3) 15 ? (30 + 15) * (2 - 3) -45 The last example has two calculations in parentheses. As usual, they're evaluated from left to right, and then the rest of the problem is solved. When you have more than one calculation in parentheses, you can further control the order by using parentheses within parentheses. The problem in the innermost parentheses is solved first. For example: ? 30 + (15 * (2 - 3)) 15 In this case, 3 is subtracted from 2, then 15 is multiplied by -1, and -15 is added to 30. As you experiment with solving calculations, you'll get familiar with the order in which mixed calculations are solved. 3.5. COMBINING PRINT'S CAPABILITIES The 64 computers let you combine the two types of print statements that you've read about in this book. Remember that anything you enclose in quotation marks is displayed exactly as you type it. The next example shows how you can combine the types of PRINT statements. The equation enclosed in quotes is displayed without being solved. The equation not in quotes is solved. The semicolon separates the two parts of the PRINT statement (semicolon means no space). ? "5 * 9 ="; 5 * 9 You key in this and 5 * 9 = 45 The computer displays this Remember, only the second part of the statement actually solves the calculation. The two parts are separated by a semicolon. You always have to separate the parts of a mixed PRINT statement with some punctuation for it to work the way you want it to. If you use a comma instead of a semicolon, there is more space between the two parts when they're displayed. A semicolon leaves out space. The 64's screen is organized into 4 zones of 10 columns each. When you use a comma to separate parts of a PRINT statement, the comma works as a tab, sending each result into the next zone. For example: ? "TOTAL:";95,"SHORTAGE:";15 TOTAL: 95 SHORTAGE: 15 If you have more than four results, they are automatically displayed on the next line. For example: ? 2 * 3,4 - 6,2 ^ 3,6 / 4,100 + (-48) 6 -2 8 1.5 52 Here's the difference when you use semicolons: ? 2 * 3;4 - 6;2 ^ 3;6 / 4;100 + (-48) 6 -2 8 1.5 52 You can use the difference between the comma and the semicolon in formatting PRINT statements to create complex displays. 4. WRITING SIMPLE BASIC PROGRAMS So far this book has shown you how to do simple things with your 64. You've experimented with typing single lines of instructions into your computer and getting instant results by pressing the key. This easy way of doing things on your computer is called the IMMEDIATE or CALCULATOR mode. But you'll probably want to use your computer to do more complex jobs that use more than one statement. When you combine a number of statements into a PROGRAM, you can use the full power of your 64. To see how easy it is to write your first program on 64, follow these steps: 1. Clear the screen by holding down the key while you press the key. 2. Key in NEW and press . This clears out information that might still be in the computer's memory after your experimenting. 3. Key in the following two lines exactly as they appear here: 10 ? "COMMODORE 64" 20 GOTO 10 4. Remember to press the key after each line. After you key in the first line and press , you'll notice that the computer doesn't respond to the PRINT command right away like it did before when you typed in the same kind of commands. This is because you are now beginning the command with a line number (10). When you use line numbers, the computer knows that you're writing a program, so it waits for you to finish keying in the whole program before following any of your instructions. 5. Key in RUN and press . The RUN command tells the computer that you've finished keying in program statements, and you're ready to have your instructions followed. Here's what happens when you RUN this program: COMMODORE 64 COMMODORE 64 COMMODORE 64 COMMODORE 64 COMMODORE 64 COMMODORE 64 6. Stop the program's execution by pressing the key. The computer continues to follow your orders by printing COMMODORE 64 over and over until you interrupt with the key. Here's how your screen looks when you press STOP. COMMODORE 64 COMMODORE 64 COMMODORE 64 COMMODORE 64 COMMODORE 64 COMMODORE 64 BREAK IN 10 READY This simple program introduces several important concepts that are the basis for all programming. 4.1. LINE NUMBERS We mentioned before in step 4 that line numbers tell the computer that you're writing a program. They also tell the computer in what order you want the statements in your program to execute. Without line numbers to tell the computer when to follow which instruction, the computer doesn't know what to do first. The longer and more complex your program is, the more important it is to remember that the computer relies on you to tell it WHEN to do things, as well as WHAT to do. One good thing about this is that you can key in line 20 before line 10 because the computer just checks the line numbers to find out the order for executing the program. The computer doesn't check for the order your lines appear on the screen. Another advantage of line numbers is that you can use the number to refer to the statement on the line. When you want to go back and repeat the execution of a statement, all you do is refer to it by line number in a GOTO statement, as you did in the example above. 4.2. THE GOTO STATEMENT When you told the computer to RUN the sample program above, COMMODORE 64 was PRINTed repeatedly instead of just once because of the GOTO statement in line 20. The GOTO statement tells the computer to go directly to a specified line. Then the computer follows the instructions in the specified line and goes on to the next line. You can use a GOTO statement to tell the computer to go back to a line that's already been executed. Or GOTO can tell the computer to skip forward, even if this means that some lines in the program don't get executed. In our example, the program PRINTs the message in line 10 and moves to line 20. There, the GOTO statement tells the computer to go back to line 10 and do what line 10 says to do. So, the program prints the message in line 10 again, and then moves to line 20, which sends the computer back to line 10 and so on. This repetition is called a LOOP. Because the example doesn't give the computer a way out of the loop, the circle repeats endlessly. You have to halt the cycle by interrupting the program with the key. It's best to include a statement in your program that ends the loop so you don't have to use the key. We'll explain more above ending loops later in this chapter. 4.3. USING THE LIST COMMAND Now that you've interrupted execution of the sample program, type in LIST and press . Your program is now displayed intact because it's still in the computer's memory, even though you interrupted the program's execution. The only difference is that the computer changed your ? into the word PRINT. This doesn't affect your program, it's just the way the computer does things. When you use the LIST command, the computer also displays the lines of the program in correct numerical order, even if you entered the lines out of order. One of the important differences between writing programs and entering single lines in the immediate/calculator mode is that you permanently lose an immediate statement once you execute it and clear the screen. But, until you start a new program, you can always get a program back just by keying in LIST. From here, you can change the program, SAVE it, or RUN it again. 4.4. EDITING TIPS When you make a mistake in a line you've keyed in, or when you just want to change a line, the 64 offers you a number of editing options. 1. You can retype a line any time, and the computer automatically substitutes the new line for the old one. All you have to do to replace a line is use the same line number. For example: 10 ? "MY NAME IS SARAH" 20 ? "I WAS BORN IN CALIFORNIA" 20 ? "I LIVE IN PENNSYLVANIA" RUN MY NAME IS SARAH I LIVE IN PENNSYLVANIA As you can see, the first line 20 never executes because it is replaced by the second line 20. If you now key in a LIST command, you'll see that only the second line 20 is still part of the program. 2. You can easily erase a line you don't want just by keying in the line number and pressing the key. If you now key in LIST, you'll see that the line is gone, and so is the line number. 3. You can easily edit an existing line. Use the CuRSoR keys to move the cursor back to the line you want to change, and then just edit the line any way you want to. As soon as you press the key, the edited line will replace the old line. Remember to use the key to insert or delete. When you finish editing, you can check your program again to verify changes by keying in the LIST command. Remember that LIST also puts lines in numerical order if you've keyed them in out of order. Try editing our sample program by adding a semicolon to the end of the line, and omitting the 64. After you finish the changes, be sure to move the cursor past line 20 before you RUN the program. Here's how the program works now: LIST 10 PRINT "COMMODORE"; 20 GOTO 10 RUN COMMODORE COMMODORE COMMODORE COMMODORE COMMODORE COMMODORE COMMODORE COMMODORE BREAK IN 10 READY 4.5. HOW TO USE VARIABLES A variable is a symbol that stands for a value. Sometimes the value of a variable is unknown before you RUN a program. One of the purposes of a program may be to find one or more values for a variable. Look at this line from a program: 20 LET X = 28 + Y The = sign means "become" or "take the value of". The LET instruction is optional and may be omitted. In this equation, X and Y are variables. Suppose X stands for the number of days in a month. One of the best things about a variable is that you can reuse it in a program, so X can stand for the days in all the months, not just one month. This is where Y comes in. All months have 28 days, so Y stands for the days over 28. Later in this chapter there's a program that gives values to these two variables. The most important thing now is understanding how variables work, because variables allow you to do complex tasks with your computer. Variables also let you write programs that are very reusable. Imagine that your computer contains a bunch of little slots, like a bank of mail boxes. When you write a program, you can use some of these slots to hold values. All you do is give a name to the slots you need, and during the program you can put values into each slot by using the slot's name. For example, in the equation above, we used two slots by naming one X and one Y. At the beginning of a program, these slots have names, but they're empty. Here's what happens when you put a value in Y's slot: +--------+--------+--------+--------+--------+--------+--------+ | X | Y | | | | | | +--------+--------+--------+--------+--------+--------+--------+ | | 3 | | | | | | +--------+--------+--------+--------+--------+--------+--------+ Now the variable Y has the value 3. You can give Y this value just by writing this simple statement: 10 Y = 3 Since X equals 28 plus Y, when you RUN the program X's slot gets a value, too. +--------+--------+--------+--------+--------+--------+--------+ | X | Y | | | | | | +--------+--------+--------+--------+--------+--------+--------+ | 31 | 3 | | | | | | +--------+--------+--------+--------+--------+--------+--------+ Here's how the program looks: 10 Y = 3 20 X = 28 + Y 30 ? "THE NUMBER OF DAYS IN MAY IS ";X RUN THE NUMBER OF DAYS IN MAY IS 31 Here's another program that uses variables: 10 X% = 15 20 X = 23.5 30 X$ = "TOTAL:" 40 Y = X% + X 50 ? X$;Y When you RUN the program, the imaginary slots look like this after line 30 is executed: +--------+--------+--------+--------+--------+ | X% | X | X$ | Y | | +--------+--------+--------+--------+--------+ | 15 | 23.5 | TOTAL: | | | +--------+--------+--------+--------+--------+ On completion of the program, Y has the value: 38.5 The above example uses the three types of variables: EXAMPLE TYPE SYMBOL DESCRIPTION EXAMPLES VALUES --------------------------------------------------------------------- Integer % whole numbers X%, A1% 15,102,3 Text string $ characters in X$, AB$ "TOTAL:", quotes "DAY 1" Floating real (decimal) X, AB 23.5, 12, point or whole numbers 1.3E+2 Be sure you use the right variable types in your programs. If you try to do something like assign a text string to an integer variable, your program won't work. There are a few other things to keep in mind when you assign names to variables: o A variable name can have one or two characters, not counting the special symbol used with integer and text string variables. o You can use more than two alphabetic characters in a variable name, but the computer only recognizes the first two. So the computer would think PA, PARTNO and PAGENO are the same variable referring to the same "slot". o A program is easier for people to read when you use longer variable names, but when you use more than two characters in a name, be sure the first two are unique. o You can use X, X%, and X$ in one program because the special symbols % and $ make each variable name unique. The same is true of A2, A2%, and A2$. o The first character must be alphabetic (A to Z). The second and any later characters can be either alphabetic or numeric (0 to 9). Remember that the computer ignores every character after the second unless it's a % or $ in the third position. o Variable names can't contain BASIC keywords, which are also called reserved words. These are the words like PRINT and RUN that are part of the BASIC language. Appendix D lists all the BASIC reserved words. Here's one more sample program that shows you how to use variables. This example also uses some of the other things you've learned so far. NEW 10 X = 1.05 20 Y = 300 30 Z = X * Y 40 PRINT "SEATS AVAILABLE:";Y 50 PRINT "TICKETS AVAILABLE:";Z 60 Y = Y + 1 70 PRINT "OVERBOOKING POINT:";Y RUN SEATS AVAILABLE: 300 TICKETS AVAILABLE: 315 OVERBOOKING POINT: 301 Lines (10-30) assign variable names. Lines 40 and 50 PRINT a message and the current value of variables Y and Z. Notice that at line 40, the value for Y is 300. Line 60 gives Y a new value, and this new value is PRINTed in line 70. Line 60 shows that a variable can have more than one value in a program. Line 60 also shows another of the powerful features of variables: you can make a variable equal to itself and another value. This isn't allowed in regular algebra, but this kind of statement is commonly used in programming. It means: take the current value of a variable, combine it with another value, and replace the first value of the variable with this new value. You can also use statements like these: Y = Y - 1 Y = Y + X Y = Y / 2 Y = Y * (X + 2) 4.6. USING FOR/NEXT LOOPS We mentioned loops earlier in this chapter during the explanation of the GOTO statement. As you'll recall, loops are repeated executions of one or more lines in a program. The FOR/NEXT statement lets you create very useful loops that control the number of times a segment of a program is executed. The FOR statement sets a limit on the number of times the loop will execute by assigning a range of values to a variable. For example: FOR COUNT=1 TO 4 The NEXT statement marks the end of a FOR/NEXT loop. When the program reaches a NEXT statement, the computer checks the FOR statement to see if the limit of the loop has been reached. If the limit hasn't been reached, the loop continues and the variable in the FOR statement is incremented by one. For example, if you add a FOR/NEXT loop to the program at the beginning of this chapter, here's what happens: 10 FOR CT =1 TO 4 20 ? "COMMODORE 64" 30 NEXT CT RUN COMMODORE 64 COMMODORE 64 COMMODORE 64 COMMODORE 64 Now that you've added the FOR/NEXT loop, you don't have to break in with the STOP key to halt the program's execution. This FOR/NEXT loop works like this: Line 10 gives the variable CT a range of values from 1 to 4, and tells the computer to execute the next lines until CT equals 4. Line 20 tells the computer to print COMMODORE 64. Line 30 tells the computer to add 1 to the current value of CT. As long as the value of CT remains within the range of 1 to 4, the program repeats, and COMMODORE 64 is PRINTed again. When CT equals 4, line 20 executes one more time. When line 30 again adds 1 to CT, the computer knows that CT is now out of range. So the computer stops executing the loop, and the program ends by itself. To make sure you understand how the FOR/NEXT loop works, we'll add more PRINT statements to line 20 that let you keep track of the value of CT. 20 PRINT"COMMODORE 64 ";"COUNT =";CT RUN COMMODORE 64 COUNT = 1 COMMODORE 64 COUNT = 2 COMMODORE 64 COUNT = 3 COMMODORE 64 COUNT = 4 As you can see, the program ends automatically when CT is out of the range set up in the FOR statement. You can increment the value of the variable in a FOR/NEXT statement by values other than 1. All you do is add both the word STEP and the value you want to use to the end of the FOR statement. For example: NEW 10 FOR NB=1 TO 10 STEP .5 This comma tells the computer to print each 20 PRINT NB, value beginning at the first position of 30 NEXT NB the next 10 space zone. RUN 1 1.5 2 2.5 3 3.5 4 4.5 5 5.5 6 6.5 7 7.5 8 8.5 9 9.5 10 NEW 10 FOR A=2 TO 8 STEP 2 20 PRINT A, 30 NEXT A RUN 2 4 6 8 You can also use a FOR/NEXT loop to count backwards. When you do this, make sure your STEP is negative. For example, if you change line 10 to this: 10 FOR A=8 TO 2 STEP -2 Here's how the output looks: RUN 8 6 4 2 4.7. USING IF/THEN STATEMENTS TO CONTROL PROGRAMS An IF/THEN statement is another way to control program execution. This statement tells the computer to check IF a condition is true. IF that condition is true, the instructions after the word THEN execute. IF that condition is false, the program goes on to the next line without following the instructions in the THEN statement. For example: 10 X = 60 20 X = X + 1 30 IF X = 64 THEN PRINT "GOT IT": END 40 GOTO 20 You can use an IF statement to start a loop or to decide whether certain parts of program will execute. For example: 10 A = 0 20 IF A <= 8 THEN 40 30 END 40 ? "FRODO LIVES ";A 50 A = A + 2 60 GOTO 20 RUN FRODO LIVES 0 FRODO LIVES 2 FRODO LIVES 4 FRODO LIVES 6 FRODO LIVES 8 In this example, the IF/THEN statement in line 20 tells the computer to check the current value of A. IF A is equal to or less than 8, THEN the program skips line 30 and continues RUNning at line 40. IF A is more than 8, in other words, IF the condition in line 20 is false, the computer ignores the instructions after the THEN statement. IF line 20 is false, THEN line 30 is executed. Line 40 PRINTs the message and the current value of A. Line 50 adds 2 to the value of A each time the loop RUNs. As soon as A becomes 10, line 20 becomes false, line 30 becomes true, and the program ends immediately. You can use any of these relational operators in IF/THEN statements: SYMBOL MEANING < Less than > Greater than = Equal to < > Not equal to > = Greater than or equal to < = Less than or equal to 5. ADVANCED BASIC The next few chapters are for people who are familiar with BASIC programming language and the concepts necessary to write advanced programs. Those of you who are just starting to learn how to program may find some of the information too technical to understand completely. But you'll find some simple examples that are written for new users in two chapters, SPRITE GRAPHICS and CREATING SOUND. These examples will give you a good idea of how to use the sophisticated graphics and sound capabilities available on your 64. If you want to learn more about writing programs in BASIC, check the bibliography in the back of this manual (Appendix N). If you are already familiar with BASIC programming, the following chapters will help you get started with advanced BASIC programming techniques. You'll find extensive information about advanced programming in the COMMODORE 64 PROGRAMMER'S REFERENCE GUIDE, which is available through your local Commodore dealer. 5.1. SIMPLE ANIMATION You can use some of the 64's graphic capabilities by putting together what you've learned so far in this manual, along with a few new concepts. Try entering the following program to see what you can do with graphics. Notice that you can include cursor controls and screen commands within a PRINT statement. When you see something like (CRSR left) in a program listing, hold down the key and press the key. The screen shows the graphic representation of a cursor left, which is two vertical reversed bars. The graphic representation of the SHIFTed key is a reversed heart. _____________ NEW / \ 10 REM BOUNCING BALL /| ":" INDICATES | 20 PRINT "{CLR/HOME}" / | NEW COMMAND | /--------------------/ \_____________/ 25 FOR X=1 to 10: PRINT "{CRSR DOWN}": NEXT 30 FOR BL=1 to 40 40 PRINT" O{CRSR LEFT}";: REM (O is a SHIFT-Q) \---------------------\ _______________ 50 FOR TM=1 TO 5 \ / \ 60 NEXT TM \ _____| THESE SPACES | 70 NEXT BL / | ARE INTENTIONAL | 75 REM MOVE BALL RIGHT TO LEFT / \_______________/ 80 FOR BL=40 TO 1 STEP -1 / /--------------------/ 90 PRINT" {CRSR LEFT}{CRSR LEFT}O{CRSR LEFT}"; 100 FOR TM=1 TO 5 110 NEXT TM 120 NEXT BL 130 GOTO 20 +-----------------------------------------------------------------------+ | TIP: | | All words in this text will be completed on one line. However, as | | long as you don't hit your 64 will automatically move to the | | next line even in the middle of a word. | +-----------------------------------------------------------------------+ When this program RUNs, it displays a bouncing ball moving across the screen from left to right and back again. Take a close look at the program to see how this is done. NEW 10 REM BOUNCING BALL +---------> 20 PRINT "{CLR/HOME}" | +------> 25 FOR X=1 to 10: PRINT "{CRSR DOWN}": NEXT | | 30 FOR BL=1 to 40 | | 40 PRINT" O{CRSR LEFT}";: REM (O is a SHIFT-Q) | | +---> 50 FOR TM=1 TO 5 | | +---- 60 NEXT TM | + ------ 70 NEXT BL | 75 REM MOVE BALL RIGHT TO LEFT | + -----> 80 FOR BL=40 TO 1 STEP -1 | | 90 PRINT" {CRSR LEFT}{CRSR LEFT}O{CRSR LEFT}"; | | +---> 100 FOR TM=1 TO 5 | | +---- 110 NEXT TM | +------- 120 NEXT BL +---------- 130 GOTO 20 Line 10 is a REMark that tells you what the program does. A REMark statement has no effect on the program itself. Line 20 clears the screen. Line 25 PRINTs ten cursor-down commands. This just positions the ball in the middle of the screen. Without this line, the ball would move across the top line of the screen. Line 30 sets up a loop to move the ball 40 columns from left to right. Line 40 does three things: 1. PRINTs a space to erase the previous ball positions. 2. PRINTs the ball. 3. Performs a cursor-left to get ready to erase the current ball position again. Line 50 and 60 set up a loop that slows down the ball's movement. Without this loop, the ball would move too fast for you to see clearly. Line 70 completes the loop set up in line 30 to PRINT balls on the screen. Each time the loop executes, the ball moves another space to the right. As you can see from the illustration, the program contains a loop within a loop. You can include up to ten loops within a loop. The only time you get in trouble is when the loops cross over each other. The loops have to be NESTED inside each other. In other words, if you start loop A and then start loop B inside loop A, you must finish loop B (the inside loop) first. A maximum of nine loops may be nested in this way. When you're writing a program with loops, it's a good idea to draw arrows from the beginning to the end of the loops. If your loops cross, the computer can't figure out what you want, so it can't execute your program. Lines 80 through 120 just reverse the steps in the first part of the program, and move the ball from right to left. Line 90 is slightly different from line 40 because the ball is moving in the opposite direction, and you have to erase the ball to the right and move to the left. Line 130 sends the program back to line 20 to start the whole process over again. For a variation on the program, change line 40 to read: 40 PRINT "(SHIFT-Q)" Run the program and see what happens now. Because you left out the cursor control, each ball remains on the screen until it is erased by the ball moving right to left in the second part of the program. 5.2. INPUT Up to now, everything in a program has been set up before the program RUNs. Once you executed the program, you couldn't change or add anything. The INPUT statement lets you send information to a program WHILE it is RUNning. Not only does the program act on this information you supply, but the program won't continue until you supply it. To get an idea of how INPUT works, type NEW, press , and enter this short program. 10 INPUT A$ 20 PRINT "YOU TYPED ";A$ 30 PRINT 40 IF A$ = "STOP" THEN END 50 GOTO 10 _________ RUN / \ ? GO ----------------------------------| YOU TYPED | YOU TYPED GO / \_________/ ? CONTINUE ----------------------/ YOU TYPED CONTINUE / ? STOP ----------------------/ YOU TYPED STOP Here's what happens in this program: Line 10 tells the computer to display a question mark to prompt you to INPUT a value for A$, and to wait until you supply the value before continuing the program execution. Line 20 PRINTs a message and the INPUT value, and line 30 PRINTs a blank line. Line 40 tells the computer to end the program immediately IF the value you INPUT for A$ is STOP. Line 50 returns the program to line 10 so you can INPUT another value. IF line 40 is true because the last value you INPUT for A$ was STOP, then line 50 isn't executed. You can INPUT numeric or string variables, and you can have the INPUT statement print a message along with a question mark to describe the kind of INPUT the computer is waiting for. For example, here's what happens when you add a prompt message to line 10 of the previous example: 10 INPUT "KEEP GOING";A$ Prompt message can't be more than 38 RUN characters KEEP GOING? GO YOU TYPED GO KEEP GOING? STOP YOU TYPED STOP Here's a more complex example that demonstrates a lot of what's been presented so far, including the INPUT statement. NEW 1 REM TEMPERATURE CONVERSION PROGRAM 5 PRINT "(SHIFT-CLR/HOME)" 10 PRINT "CONVERT FROM FAHRENHEIT OR CELSIUS (F/C): ": INPUT A$ 20 IF A$ = "" THEN 10 30 IF A$ = "F" THEN 100 40 IF A$ <> "C" THEN 10 50 INPUT "ENTER DEGREES CELSIUS: ";C 60 F = (C*9)/5+32 70 PRINT C;" DEG. CELSIUS ="; F ;"DEG. FAHRENHEIT" 80 PRINT 90 GOTO 10 100 INPUT "ENTER DEGREES FAHRENHEIT: ";F 110 C = (F-32)*5/9 120 PRINT F;" DEG. FAHRENHEIT ="; C ;"DEG. CELSIUS" 130 PRINT 140 GOTO 10 Line 10 uses the INPUT statement to print a prompt message and to wait for you to type in a value for A$. Lines 20, 30 and 40 check what you typed in and tell the computer where to go next. Line 20 tells the computer to go back to line 10 and ask for INPUT again IF nothing was typed in (IF just was pressed). Line 30 tells the computer to go straight to line 100 and perform the Fahrenheit-to-Celsius conversion IF the value you typed for A$ is F. Line 40 checks to be sure that you haven't typed in anything beside F or C. IF you have, line 40 ends the program. IF you typed in a C, the computer automatically moves to line 50 to perform the Celsius-to- Fahrenheit conversion. It may seem like too much detail to include all these IF statements to check what you INPUT. But this is a good programming practice that can spare you a lot of frustration. You should always try to be sure that your program takes care of all possibilities. Back to the example: once the program knows what type of conversion to make, the calculations are made. Then the program PRINTs the temperature you entered and the converted temperature. The calculation this program performs is just straight math, using the standard formula for temperature conversion. After the calculation finishes and the answer is PRINTed, the program loops back and starts over. Here's a sample execution of this program: CONVERT FROM FAHRENHEIT OR CELSIUS (F/C): ? F ENTER DEGREES FAHRENHEIT: 32 32 DEG. FAHRENHEIT = 0 DEG. CELSIUS CONVERT FROM FAHRENHEIT OR CELSIUS (F/C): ? After you RUN this program, you might want to save it on disk. This program, as well as others in this manual, can form part of your program library. 5.3. USING THE GET STATEMENT FOR DATA INPUT GET lets you input one character at a time from the keyboard without pressing the key. This really speeds up entering data in many cases. When you RUN a program that has a GET statement, whatever key you press is assigned to the variable you include in the GET statement. Here's an example: 1 PRINT "(SHIFT-CLR/HOME)" 10 GET A$: IF A$ = "" THEN 10 No space between quotes 20 PRINT A$; 30 GOTO 10 Line 1 clears the screen. Line 10 lets you type in any key on the keyboard. In effect, the loop in line 10 tells the computer to wait until you type in a key before moving to line 20. Line 20 displays the keys you type on the screen. Line 30 sends the program back to GET another character. It's important to remember that the character you type in won't be displayed unless you PRINT it to the screen, as we've done in line 20. The IF statement in line 10 is very important. GET continually works, even if you don't press a key (unlike INPUT, which waits for your response), so the second part of line 10 continually checks the keyboard until you hit a key. Try leaving out the second part of line 10 and see what happens. To stop this program, press the and keys. You can easily rewrite the beginning of the temperature conversion program to use GET instead of INPUT. If you've SAVEd this program, LOAD it and change lines 10 and 20 like this: 10 PRINT "CONVERT FROM FAHRENHEIT OR CELSIUS (F/C)" 20 GET A$: IF A$ = "" THEN 20 This change makes the program operate more smoothly because nothing happens unless you type in one of the two responses (F or C) that selects the type of conversion. If you want to keep the program, be sure to SAVE it again. 5.4. USING GET TO PROGRAM FUNCTION KEYS As you'll recall from an earlier chapter, we told you that the keys on the right side of the keyboard (F1 through F8) are function keys that you can program to perform a variety of tasks. Here's how to program a function key: 1. Use a GET statement to read the keyboard. 2. Use IF statements to compare the key you press to the CHR$ code for the function key you want to use. Every character on the keyboard has a unique CHR$ number. For example, the CHR$ code of F1 is 133. Appendix F lists the CHR$ code for all keys. 3. Use THEN statements to tell the computer what you want the function key to do. When you RUN the program, all you do is press a function key you programmed, and the key will follow the instructions you gave it in the THEN statement. For example: 10 GET A$: IF A$ = "" THEN 10 20 IF A$ = CHR$(137) THEN PRINT CHR$(14) 30 IF A$ = CHR$(134) THEN PRINT "YOURS TRULY" Line 10 tells the program to assign the key you press to the variable A$. As you'll recall from the previous example, the loop in line 10 continually checks the keyboard for input. Line 20 programs function key 2, CHR$(137). Line 20 tells the computer to make A$ equal to CHR$(14) if you press function key 2. CHR$(14) is the switch from upper to lower case letters on the keyboard. When you RUN this program, you'll see that the characters on the screen immediately make this switch if you press F2. Line 30 programs function key 3, CHR$(134). Line 30 tells the computer to make A$ equal to the character string YOURS TRULY and CHR$(13) if you press F3 during program execution. CHR$(13) is the code for the key. THE CHR$ codes for the function keys are: F1 = CHR$(133) F2 = CHR$(137) F3 = CHR$(134) F4 = CHR$(138) F5 = CHR$(135) F6 = CHR$(139) F7 = CHR$(136) F8 = CHR$(140) The COMMODORE 64 PROGRAMMER'S REFERENCE GUIDE has more information about programming function keys. You can purchase this extensive guide from your local Commodore dealer. 5.5. RANDOM NUMBERS AND OTHER FUNCTIONS The 64 also has built-in functions that you can use to perform special tasks. Functions are like built-in programs included in BASIC. The great advantage of these built-in functions is that you don't have to type in a number of statements every time you want to perform a specialized calculation. Instead, all you do is type the command for the function you want and the computer does all the rest. These built-in functions include figuring square roots (SQR), finding out the contents of a memory location (PEEK), generating random numbers (RND), etc. Appendix C lists all the functions available on your computer. One function you can have a lot of fun with is the random number function, RND. If you want to design a game or an educational program, you'll often need to be able to program your computer to make up random numbers. For example, you'd need to do this to simulate the tossing of dice. Of course you could write a program that would generate these random numbers, but it's much easier to be able to do this just by calling upon the prewritten RaNDom number function. To see how RND works, try this short program: NEW 10 FOR X = 1 TO 10 20 PRINT RND(1), IF YOU LEAVE OUT THE COMMA, YOUR 30 NEXT LIST OF NUMBERS APPEARS AS 1 COLUMN When you RUN this program, the screen displays: .789280697 .664673958 .256373663 .0123442287 .682952381 3.90587279E-04 .402343724 .879300926 .158209063 .245596701 Your numbers don't match? It would be incredible if they did because the program generates a completely random list of ten numbers. If you RUN the program a few more times, you'll see that the results are always different. Though the numbers don't have a pattern, you'll notice a few consistencies about the list the program displays. For one thing, the results are always between 1 and 0, but never equal to 1 or 0. For another, the numbers are real numbers (with decimal points). Now, we started out to simulate dice tosses, and the results from this program aren't exactly what we're looking for. Now we'll add a few more features to this program to get what we want. First, add this line to the program to replace line 20, and RUN the program again: 20 PRINT 6*RND(1), RUN 3.60563664 4.52687513 5.48602315 1.09650123 3.10045018 4.39052168 3.91302584 5.06321506 2.32056144 4.10781302 Now we've got results larger than 1, but still have real numbers. To solve this, we'll use another function. The INT function converts real numbers to integer (whole) numbers. So try replacing line 20 again: 20 PRINT INT(6*RND(1), RUN 2 3 1 0 2 4 5 5 0 1 Now we're even closer to our goal, but you'll notice that the numbers range from 0 to 5, not 1 to 6. So as a final step, we'll replace line 20 again: 20 PRINT INT(6*RND(1))+1 Now when you RUN the program, you'll get the results you want. When you want to generate a range of real numbers instead of whole numbers, the formula is slightly different because you must subtract the lower limit of the range from the upper limit. For example, you can generate random numbers between 1 and 25 by typing: 20 PRINT RND(1)*(25-1)+1 The general formula for generating random numbers in a certain range is: NUMBER = RND(1) * (UPPER LIMIT - LOWER LIMIT) + LOWER LIMIT 5.6. GUESSING GAME Here's a game that uses random numbers. This game not only uses the RND function, but it also introduces some additional programming theory. When you RUN this program, the computer generates a random number, NM, whose value you'll try to guess in as few turns as possible. ______________ NEW / \ 1 REM NUMBER GUESSING GAME ___________| INDICATES NO | 2 PRINT "(CLR/HOME)" / | SPACE AFTER | 5 INPUT "ENTER UPPER LIMIT FOR GUESS "; LI | QUOTATION MARK | 10 NM = INT(LI*RND(1))+1 \______________/ 15 CN = 0 20 PRINT "I'VE GOT THE NUMBER.": PRINT 30 INPUT "WHAT'S YOUR GUESS "; GU 35 CN = CN + 1 40 IF GU > NM THEN PRINT "MY NUMBER IS LOWER." : PRINT : GOTO 30 50 IF GU < NM THEN PRINT "MY NUMBER IS HIGHER.": PRINT : GOTO 30 60 IF GU = NM THEN PRINT "GREAT! YOU GOT MY NUMBER" 65 PRINT "IN ONLY"; CN ;"GUESSES." : PRINT 70 PRINT "DO YOU WANT TO TRY ANOTHER (Y/N)?" 80 GET AN$ : IF AN$ = "" THEN 80 90 IF AN$ = "Y" THEN 2 100 IF AN$ <> "N" THEN 70 110 END You can specify how large the number will be at the start of the program. Then, it's up to you to guess what the number is. A sample run follows along with an explanation. ENTER UPPER LIMIT FOR GUESS? 25 I'VE GOT THE NUMBER. WHAT'S YOUR GUESS ? 15 MY NUMBER IS HIGHER. WHAT'S YOUR GUESS ? 20 MY NUMBER IS LOWER. WHAT'S YOUR GUESS ? 19 GREAT! YOU GOT MY NUMBER IN ONLY 3 GUESSES. DO YOU WANT TO TRY ANOTHER (Y/N)? The IF/THEN statement (lines 40-60) compare your guess to the random number (NM) generated by line 10. If your guess is wrong, the program tells you whether your guess is higher or lower than NM. Each time you make a guess, line 35 adds 1 to CN. CN is a counter that keeps track of how many guesses you take to get the right number. The purpose of this game, of course, is to guess the number in as few tries as possible. When you get the right answer, the program displays the message, GREAT! YOU GOT MY NUMBER, and tells you how many guesses you took. Remember that the program creates a new random number each time you play the game. You might want to add a few lines to the program that also specify the lower range of numbers generated by this game. +-----------------------------------------------------------------------+ | PROGRAMMING TIPS: | | In lines 40 and 50, a colon separates multiple statements on a | | single line. This not only saves typing time. but it also conserves | | memory space. | | Also notice that the IF/THEN statements in these two lines PRINT | | something before branching to another line. | +-----------------------------------------------------------------------+ 5.7. YOUR ROLL The following program simulates the throw of two dice. You can play this little game by itself, or use it as part of a larger game. 5 PRINT "CARE TO TRY YOUR LUCK?" 10 PRINT "RED DICE = "; INT(RND(1)*6)+1 20 PRINT "WHITE DICE = "; INT(RND(1)*6)+1 30 PRINT "PRESS SPACE BAR FOR ANOTHER ROLL": PRINT 40 GET A$: IF A$ = "" THEN 40 50 IF A$ = CHR$(32) THEN 10 From what you've learned about BASIC and random numbers, see if you can follow what's going on in this program. As you may recall from the section on programming the function keys, CHR$(32) is the character string code for the space bar. 5.8. RANDOM GRAPHICS As a final note on random numbers, and as an introduction to designing graphics, try entering and RUNning this program: 10 PRINT "(SHIFT-CLR/HOME)" 20 PRINT CHR$(205.5 + RND(1)); 30 GOTO 20 The function CHR$ (CHaracter String) gives you a character, based on a standard code number from 0 to 255. Every character the 64 can print is encoded this way. Appendix F lists the CHR$ codes for all keys. A quick way of finding out the code for any character is to use the function ASC (for the standard ASCII code). Type: PRINT ASC("X") X is the character you're checking. X can be any printable character, including graphics characters. You must enclose the character in quotation marks. Here's an example: PRINT ASC("G") 71 The CHR$ function is the opposite of ASC. PRINT CHR$(71) G If you type: PRINT CHR$(205);CHR$(206) the computer displays the two right side graphics on the M and N keys, which are the characters used in the little maze program you just tried. The formula 205.5 + RND(1) tells the computer to pick a random number between 205.5 and 206.5. There is fifty-fifty chance that the random number will be above or below 206. CHR$ ignores fractional values, so half the time the character with code 205 is printed, and the rest of the time code 206 is displayed. You can experiment with this program by adding or subtracting a couple of tenths from 205.5. This gives either character a greater chance of being displayed. 6. COLOR AND GRAPHICS 6.1. HOW TO USE COLOR AND GRAPHICS ON YOUR COMPUTER So far this book has presented some of the sophisticated computing capabilities of your 64. But one of the most exciting features of your new computer is its outstanding ability to produce 16 different colors and a lot of different graphics. You've already seen a very simple demonstration of the graphics in the bouncing ball program and in the maze program at the end of the last chapter. This chapter introduces you to new concepts that explain graphic and color programming, and that suggest ideas for creating your own games and advanced animation. 6.2. PRINTING COLORS When you tried the color alignment test in Chapter 1, you discovered that you can change text colors by simply holding down the key and pressing one of the color keys. The 64 offers a full range of 16 colors. Though only eight colors are printed on the color keys, you can get eight more by holding down the key and pressing a color key. Here's a list of the colors: KEYBOARD COLOR DISPLAY KEYBOARD COLOR DISPLAY --------------------------------------------------------------------- <1> BLACK <1> ORANGE <2> WHITE <2> BROWN <3> RED <3> LT. RED <4> CYAN <4> GRAY 1 <5> PURPLE <5> GRAY 2 <6> GREEN <6> LT. GREEN <7> BLUE <7> LT. BLUE <8> YELLOW <8> GRAY 3 When we showed you the bouncing ball program in the last chapter, you saw that keyboard commands, such as cursor movement, can be written into PRINT statements. In the same way you can also add text color changes to your programs. Type NEW and try experimenting with changing colors. Hold down the key and at the same time press the <1> key. Now release both keys and press the key. Now hold down the key again and press the <2> key. Release the key and type the key. Move through the numbers, alternating with the letters, and type out the word RAINBOW like this: 10 PRINT " R A I N B O W" ^ ^ ^ ^ ^ ^ ^ <1 2 3 4 5 6 7> You'll recall that cursor controls appear as graphic characters in the PRINT statement. Color controls are also represented as graphic characters. The color chart printed above shows the graphic characters that appear with each color. Because of the graphic characters that are displayed when you select color keys, your PRINT statement will look strange, but when you RUN the program, you'll see that only the text of the message is displayed. The letters in the message automatically change colors according to the color controls you placed in the PRINT statement. Now try making up some examples of your own, mixing any number of colors within a single PRINT statement. Don't forget the second set of colors that you can get by holding down the key while you press a color key. +-----------------------------------------------------------------------+ | TIP: | | After you RUN a program with color or mode (reverse) changes, | | you'll notice that the READY prompt and any additional text you key | | in is the same as the last color or mode change you made. To get back | | to the normal display, press these keys together: | | RUN/STOP and RESTORE | +-----------------------------------------------------------------------+ 6.3. COLOR CHR$ CODES Before you start reading this section, take a look at Appendix F, which lists the CHR$ codes for all keys on the keyboard. As you looked over the list of CHR$ codes, you probably noticed that each color has a unique code, just like all the other keys and the keyboard controls. If you print the codes themselves by using the CHR$ function mentioned in the last chapter, you can get the same results you got by typing or and the color key in a PRINT statement. For example, try this: NEW 10 PRINT CHR$(147): REM 20 PRINT CHR$(28);"CHR$(28) CHANGES ME TO?" RUN CHR$(28) CHANGES ME TO? When you RUN this program, the screen clears before the message in line 20 is PRINTed. The text should be red now. In many cases, you'll find that it's much easier to use the CHR$ function to change colors, especially if you want to experiment. The next page shows another way to get a rainbow of colors. There are a number of similar lines in the program (40 through 110), so use the editing keys to spare yourself a lot of typing. See the notes at the end of the program listing to refresh your memory on editing procedures. NEW 1 REM AUTOMATIC COLOR BARS 5 PRINT CHR$(147): REM CHR$(147) = CLR/HOME 10 PRINT CHR$(18); " ";: REM REVERSE BAR 20 CL = INT(8*RND(1))+1 30 ON CL GOTO 40,50,60,70,80,90,100,110 40 PRINT CHR$(5);: GOTO 10 50 PRINT CHR$(28);: GOTO 10 60 PRINT CHR$(30);: GOTO 10 70 PRINT CHR$(31);: GOTO 10 80 PRINT CHR$(144);: GOTO 10 90 PRINT CHR$(156);: GOTO 10 100 PRINT CHR$(158);: GOTO 10 110 PRINT CHR$(159);: GOTO 10 Type lines 1 through 40 normally. Your display should look like this: 1 REM AUTOMATIC COLOR BARS 5 PRINT CHR$(147): REM CHR$(147) = CLR/HOME 10 PRINT CHR$(18); " ";: REM REVERSE BAR 20 CL = INT(8*RND(1))+1 30 ON CL GOTO 40,50,60,70,80,90,100,110 40 PRINT CHR$(5);: GOTO 10 _ EDITING NOTES: Use the key to position the cursor on line 40. Then type 5 over the 4 of 40. Now use the key to move over to the 5 in the CHR$ parentheses. Press and to open up a space, and key in 28. Now just press with the cursor anywhere on the line. The display should look like this now: NEW 1 REM AUTOMATIC COLOR BARS 5 PRINT CHR$(147): REM CHR$(147) = CLR/HOME 10 PRINT CHR$(18); " ";: REM REVERSE BAR 20 CL = INT(8*RND(1))+1 30 ON CL GOTO 40,50,60,70,80,90,100,110 50 PRINT CHR$(28);: GOTO 10 Don't worry about line 40; it's still there, as you can see by LISTing the program. Follow the same steps to modify line 40 with a new line number and CHR$ code until you've entered all the remaining lines. As a final check, LIST the entire program to make sure all the lines are right before you RUN it. You probably understand the color bar program except for line 30. Here's a brief explanation of how this program works. Line 5 prints the CHR$ code for . Line 10 turns on reverse type and prints 5 spaces, which turn out to be a bar since they're reversed. The first time through the program, the bar is light blue, the normal screen display color. Line 20 uses the random function to select at random a color between 1 and 8. Line 30 uses a variation of the IF/THEN statement, called ON/GOTO, which lets the program choose from as list of line numbers where the program will go next. If the ON variable (in this case CL) has a value of 1, the program goes to the first line number listed (here it's line 40). If the variable has a value of 2, the program goes to the second line listed, and so on. Lines 40 through 110 just convert the random key colors to the appropriate CHR$ code for that color and return the program to line 10 to PRINT a section of the bar in that color. Then the whole process starts again. See if you can figure out how to produce 16 random colors. Expand ON/GOTO to handle the additional colors and add the remaining CHR$ codes. 6.4. HOW TO USE PEEKS AND POKES PEEKS and POKES let you search around inside your computer's memory and stick things in exactly where you want them. You'll recall that in Chapter 4 we explained variables as being like little slots in the computer's memory, with the variable name as the slot's address. Well, imagine some more specially defined slots in the computer that stand for specific memory locations and that have numbers for addresses. Your 64 looks at these memory locations to see what the screen's background and border colors should be, what characters to display on the screen and where to display them, etc. You can change the screen colors, define and move objects, and even create music by POKEing a different value into the specific memory slots. Imagine some memory slots looking something like this: +-----------+ +-----------+ +-----------+ +-----------+ | 53280 | | 53281 | | 53282 | | 53283 | | 2 | | 1 | | | | | +-----------+ +-----------+ +-----------+ +-----------+ BORDER BACKGROUND COLOR COLOR The first two slots are the memory locations for the border and background colors on your screen. We've put 2, the value for RED in the border color box, and 1, the value for WHITE in the background color box. Now try typing this: POKE 53281,7 The background color of your screen will change to yellow because we put the value 7, for yellow, in the location that controls background color. Try POKEing different values into the background color location and see what result you get. Here's a list of the values to POKE for each color available on your 64: 0 BLACK 8 ORANGE 1 WHITE 9 BROWN 2 RED 10 light RED 3 CYAN 11 GRAY 1 4 PURPLE 12 GRAY 2 5 GREEN 13 light GREEN 6 BLUE 14 light BLUE 7 YELLOW 15 GRAY 3 Here's a little program that you can use to display various border and background color combinations: NEW 10 FOR BA = 0 TO 15 20 FOR BO = 0 TO 15 30 POKE 53280, BO 40 POKE 53281, BA 50 FOR X = 1 TO 2000: NEXT X 60 NEXT BO : NEXT BA RUN This program uses two simple loops to POKE various values to change the background and border colors. Line 50 contains a DELAY loop, which just slows the program down a little bit. If you're curious about what value is currently in the memory location for background color, try this: ? PEEK (53280) AND 15 PEEK looks at a whole byte, but colors only use half a byte, called a nybble. To PEEK just this nybble, you have to add the AND 15 to your PEEK statement. If you used this PEEK after RUNning the previous program, you'd get 15 as the answer because the last border color POKEd was GRAY 3, which is 15. In general, PEEK lets you see what value is currently in a specific memory slot. Try adding this line to your program to display the values of BORDER and BACKGROUND as the program RUNs. 25 PRINT CHR$(147); "BORDER = "; PEEK(53280) AND 15, "BACKGROUND = "; PEEK(53281) AND 15 6.5. SCREEN GRAPHICS So far when you've PRINTed information, the computer has handled the information sequentially: one character PRINTed after the next, starting from the current cursor position, except when you asked for a new line, or used a comma in PRINT formatting. You can PRINT data in a particular place by starting from a known place on the screen and PRINTing the correct number of cursor controls to format the display. But this takes time and program steps. But just as there certain locations in the 64's memory to control color, there are also memory locations that you can use to control screen locations. 6.6. SCREEN MEMORY MAP The 64's screen can hold 1000 characters (40 columns by 25 lines), so there are 1000 memory locations set aside to represent what is on the screen. Imagine the screen as a grid, 40 by 25, with each square standing for one memory location. Each memory location can contain one of the 256 different characters the 64 can display (see Appendix E). Each of these 256 characters is represented by a number from 0 to 255. If you POKE the value for a character into a specific screen memory location, that character will be displayed in that specific screen location. Here's a grid that represents your screen, complete with the numbers of each screen memory location. COLUMN 1063 0 10 20 30 39 / +------------------------------------------------------------/ 1024 | | 0 1064 | | 1104 | | 1144 | | 1184 | | 1224 | | 1264 | | 1304 | | 1344 | | 1384 | | 1424 | | 10 1464 | | 1504 | | ROW 1544 | | 1584 | | 1624 | | 1664 | | 1704 | | 1744 | | 1784 | | 1824 | | 20 1864 | | 1904 | | 1944 | | 1984 | | 24 +------------------------------------------------------------\ \ 2023 The 64's screen memory normally begins at memory location 1024 and ends at location 2023. Location 1024 is the upper left corner of the screen. Location 1025 is the position of the next character to the right, and so on. Location 1063 is the right-most position of the first row. Following the last character in a row, the next location is the left-most character on the next row down. Suppose you want to control a ball bouncing on the screen. The ball is in the middle of the screen, column 29, row 12. The formula for calculating the memory location on the screen is: POINT = 1024 + X + 40 * Y <---- row ^--------- column where X is the column and Y is the row. Therefore, the memory location of the ball is: POINT = 1024 + 20 + 480 <-- row (40x12) POINT = 1524 ^------- column Clear the screen with and and type: POKE 1524,81 <--- character code ^------ location This POKE statement makes a ball appear in the middle of the screen. You have placed a character directly into screen memory without using the PRINT statement. However, you can't see the ball yet because it's the same color as the screen background. 6.7. COLOR MEMORY MAP You can change the color of the ball that appeared by altering another range of memory. Type: POKE 55796,2 <--- color ^---- location This changes the ball's color to red. Every spot on the 64's screen has TWO memory locations: one for the character code, and one for the color code. The color memory map begins at location 55296 (upper left corner), and continues on for 1000 locations. You use the same color codes, 0 through 15, that you used to change border and background colors, to directly change character color. We can modify the formula for calculating screen memory locations to give us the locations to POKE colors. Here's the new formula: COLOR PRINT = 55296 + X + 40 * Y <--- row ^--------- column 6.8. MORE BOUNCING BALLS Here's a revised bouncing ball program that directly prints on the screen using POKEs rather than cursor controls within PRINT statements. When you RUN this version, you'll see that it's much more flexible than the earlier program and it leads up to programming more sophisticated animation. NEW 10 POKE 53281,1: PRINT"" 20 POKE 53280,7: POKE 53281,6 30 X = 1 : Y = 1 40 DX = 1 : DY = 1 50 POKE 1024 + X + 40 * Y, 81 60 FOR T = 1 TO 10 : NEXT 70 POKE 1024 + X + 40 * Y, 32 80 X = X + DX 90 IF X <= 0 OR X >= 39 THEN DX = -DX 100 Y = Y + DY 110 IF Y <= 0 OR Y >= 24 THEN DY = -DY 120 GOTO 50 Line 10 sets the cursor color to white and then clears the screen. NOTE: Clearing the screen on (NTSC) 64s sets the color RAM to white but on (PAL) 64s the color RAM is set to the current background color (here white). Line 20 sets the background color to blue and the border color to yellow. The X and Y variables in line 30 keep track of the ball's current row and column position. The DX and DY variables in line 40 are the horizontal and vertical direction of the ball's movement. When a +1 is added to the value of X, the ball moves to the right; when -1 is added, the ball moves to the left. A +1 added to Y moves the ball down a row, and a -1 added to Y moves the ball up a row. Line 50 puts the ball on the screen at the current X,Y position. Line 60 is a delay loop, which is included to keep the ball on the screen long enough for you to be able to see it. Line 70 erases the ball by putting a space (code 32) where the ball was on the screen. Line 80 adds the direction factor to X. Line 90 tests to see if the ball has reached one of the side walls, and reverses the ball's direction if there's a bounce. Lines 100 and 110 do the same thing for the top and bottom walls. Line 120 sends the ball back to display and moves the ball again. You can change the ball to any other character by changing the code in line 50 from 81 to another character code. If you change DX or DY to 0 the ball bounces straight instead of diagonally. We can also add a little intelligence to the bouncing ball program. So far the only thing you checked for is whether the ball is going out of bounds on the screen. Try adding the following lines to the program: 21 FOR L = 1 TO 10 25 POKE 1024 + INT(RND(1)*1000), 160 <---(REVERSE SPACE) 27 NEXT L 115 IF PEEK(1024 + X + 40*Y) = 166 THEN DX = -DX : GOTO 80 Lines 21 to 27 put ten blocks on the screen in random positions. Line 115 PEEKs to see if the ball is about to bounce into a block, and, if so, it changes the ball's direction. 7. INTRODUCTION TO SPRITES In previous chapters, we've shown you how to use graphic symbols in PRINT statements to create animation and other visual effects. In chapter 6, we also showed you how to POKE character codes in specific screen memory locations, which put characters directly on the screen in the place you selected. In both of these cases, you have to create objects from existing graphic symbols, so these methods take a lot of work. When you want to move the object, you must use a number of program statements to keep track of the object and move it to a new place. And sometimes the shape and resolution of the object isn't as good as you'd like it to be because of the limitations of using graphic symbols. You can eliminate a lot of these problems by using sprites in animated sequences. A sprite is a high-resolution programmable object that you can make into just about any shape by using BASIC commands. All you have to do to move the object is simply tell the computer the position where you'd like the sprite to go. The computer takes care of the rest. But this isn't all you can do with sprites. For example, you can change their color, you can tell if one object collides with another, you can make them go in front and behind each other, and you can easily expand their size. You have to learn a few more details about your 64 and the way it handles numbers before you can use sprites. It's not difficult, though, so just follow the examples and you'll be making your own sprites do amazing things in no time. 7.1. BITS AND BYTES Before you can use sprites it's important that you understand a few general things about how computers work. In the decimal system, we count in "tens" using values of 0-9. When a particular position overflows its maximum value of 9, it re-cycles to zero and carries one to the next (left-hand) position. For example, the number 64 means 6 x (10) + 4 x (1). The position of each digit is important. The value of 64 is calculated as follows: 6 x 10^1 + 4 x 10^0 NOTE: Any number raised to the power of zero equals 1. Computers store information as a series of electrical charges, representing 1s and 0s. Each cell within memory holds a pattern of eight ones and zeros called binary digits or BITS. These cells are called BYTES. A bit, which is the smallest amount of information a computer can store, can be turned ON, giving it a value of 1, or OFF, which has a value of 0. When you enter information into the computer via the keyboard, key depressions are converted into 8 bit patterns of ones and zeros, and transferred to memory. The rules for binary arithmetic are much simpler than other systems since digits can only have two values, 0 or 1. As illustrated in the previous example, the decimal system uses the base of 10, whereas the binary system uses the base of 2. One bit can contain one of two combinations, 0 or 1. There are four possible combinations of 1s and 0s in two bits (2^2) and with three bits, eight possible combinations (2^3). The following illustration shows the range of values. +---------+--------------+----------------------------------------------+ | NO. OF |