Learning to Program with the Cybiko Handheld Computer Using B2C By Greg Smith Chapter 1 : Introducing the Cybiko 2 Chapter 2 : Introducing BASIC & B2C 5 Chapter 3 : Downloading B2C 6 Chapter 4 : Editing Your First Program 7 Chapter 5 : Compiling Your First Program 12 Chapter 6 : Downloading and Running Your Application 13 Chapter 7 : Programming Basics : Input/Process/Output 14 Chapter 8 : Variables and DIM 17 Chapter 9 : Looping : For ... Next 20 Chapter 10 : Conditionals : If ... Then ... Else ... End If 22 Chapter 11 : While 25 Chapter 12 : Functions & Subroutines 26 Chapter 13 : Simple Graphics 29 Chapter 14 : Printxy 34 Chapter 15 : Math Operations Error! Bookmark not defined. Chapter 16 : Miscellaneous 35 Chapter 17 : String Manipulation (Right/Mid) 37 Chapter 18 : File I/O 39 Chapter 19 : Role Playing Games 41 The TARDIS Adventure 41 Appendix 1 : Command Summary 43 Appendix 2 : B2C Deliverables 47 Chapter 1 : Introducing the Cybiko Teen Computer Donald Wisniewski and David Yang created the Cybiko as a portable computer for tweens (ages 10-12) and teens (ages 13-17). It was designed to fill a niche left between the Palm Pilot and Nintendo Game boy. Look & Feel The original Cybiko looks like a walkie talkie encased in a transparent shell from one of five colors (black, clear, yellow, blue, and purple - and a promotional red). It has an array of white buttons comprising a QWERTY-style keyboard, a joystick pad, and some function keys. The original, older model (released in April 2000) had a power slide switch on the side, which was later replaced by an "Esc" key. The new Cybiko Xtreme (CyX2) is very different from the original Cybiko. Released in September of 2001, the CyX2 body has a trim feel to it compared to the Cybiko. It is roughly the same size as the original Cybiko. It's molded as all one unit and shaped like a figure 8 (curved edges, wide at the top, narrow waist, and wide near the bottom). In this way it resembles the m100 model of the Palm Pilot. And like the m100 series, there are skins that cover the silverized CyX2 body. There are also separate panels for the areas around the keyboard, arrow keys, and the Enter pad. Red, green, blue, and zebra colors are available. You can even mix and match colors for a unique color scheme. The CyX2 keyboard has larger keys and they are of a solid black rubbarized material. The arrow keys resemble the Game Boy keys and are separate from the ESC key. In a brilliant and very welcome move, there is an ON/OFF key situated in the center of the keyboard. One drawback to the new, larger keyboard is that Cybiko removed the top row of number keys (1-9). To type numbers into the unit you must use the FN key to 'shift'. The F1-F7 keys still exist at the top of the unit. The CyX2 antenna is no longer the 6" long rod rising from the back of the unit. Instead, a slim side-antenna (again resembling the Palm Pilot VII antenna). CyX2 sports a mini USB port at the bottom of the case. This USB port will be used to download games. It also doubles as the battery charger connection. A supplied cable connects the USB port to a power adapter. The display is the same as on the Cybiko. 160x100 pixels, 4-color greyscale. A slot for additional devices is now at the top of the unit. Donald Wisniewski & Cybiko Inc. The creators of the Cybiko - Donald Wisniewski (President of Cybiko, Inc.) and David Yang started the company in early 1999. They recognized a need in the teen marketplace for a handheld wireless entertainment device that teens could call their own. Wisniewski (born in 1960) is a former executive of V-Tech (another high-tech firm in the business of creating devices for young people). He holds a BS in mechanical engineering from Purdue University. "We want to create a social environment where teens can chat and interact," he said in a recent interview, "We see a huge opportunity with 12- to 16-year olds." The Cybiko was released in April of 2000 with a price tag of $170. At that time, New York-based Cybiko had 85 engineers who had created the device. As of January 2001 Cybiko had a staff of around 170 Russian-based software developers and retailed for about $99. They had successfully delivered a new application daily from about January 2000 to July 2001. The product was first introduced at a number of toy and electronics retailers like FAO Schwarz, Virgin Records, CompUSA, Babbage's, and Software Etc. Now, it is available at over 9000 locations across the USA and online at www.cybiko.com. Cybiko is privately held and owns all of the intellectual property. The CyX2 was released in September 2001. The game-a-day policy has changed to a trickle of just one game per week. Teens and Cybiko There are 30 million teens in the United States, 65 percent of whom have a computer in the home. 45 percent have Internet access and none of them had a mobile wireless product. That is a market of 13.5 million people. The Cybiko is aimed at Nine to 20-year-olds. They felt interconnectivity and communication was a key feature left out of other devices for teens. "We wanted to create a social environment where teens can chat and interact," said Wisniewski. And they wanted to create a device that was more than a game machine - so they included single and multiplayer wireless games, support applications like the planner, email, Friend Finder, and a way to chat with anyone in the network. "I've seen users as young as five and old as 55," Wisniewski said in a recent interview. Technical Details *(Note: See the glossary for a description of new terms) The operating system for the Cybiko is called CyOS. It is now (Sept/2001) up to version 1.3.57. The original Cybiko (v1.2) advertised a mere 256KB of RAM. Currently the memory is divided into 2 segments : 512KB of RAM and 512KB or Flash RAM - for a grand total of 1MB. Most of the memory is used up by the Cybiko Operating System (CyOS). Only about 300KB is available for the user. The memory is supposed to be upgradeable to 16MB, but this number is different depending on the published source. (There is a 1MB expansion module but the Cybiko can take advantage of the MP3's memory which can be as large as 64MB). The CyX2 boasts 1MB of RAM and 1MB or Flash RAM. With an additional 500KB of ROM, the CyX2 weighs int at 2.5MB of memory. The Cybiko's display is 160 x 100 pixels of monochrome LCD (actually, its 4-color gray scale). Its Microprocessor is a 32-bit 11-MHz processor manufactured by Hitachi (this is roughly equivalent in capability to an Intel 386 chip - the heart of the original IBM PC) The CyX2 has a 22-MHz processor. The Cybiko broadcasts on 30 digital channels over frequencies between 902 and 928 MHz with a range of up to 300 feet. There has been a lot of talk on the Internet about improving the range with home-brew antennae and so on, but for all practical purposes 300 feet is as far as the Cybiko can broadcast. Wireless eMail is possible with the CyWIG software on the PC. Users can send files (including music, games and applications) between two Cybikos. While Cybiko users can chat and game with other Cybikos within a range of 300 ft. They can also transmit through each other to extend the range, similar to a re-transmitter. The original Cybiko has a small keyboard allows for data entry. The keys are arranged in the traditional QWERTY layout, but are smaller than those used on the popular RIM pager devices. A stylus is provided to allow easier typing. There is a small joystick pad with up, down, left, and right keys. Seven pre-programmed function keys line the top of the unit. And the help, enter, select, tab, and del keys are along the right side. In fact, you will mostly use the arrow keys and the enter key. The CyX2 keyboard has black letters that are larger than its predecessor. The expansion slot is located at the base of the Cybiko. It is able to take an optional MP3 player. Also, a memory card with 1MB of memory is available. The CyX2 expansion slot is at the top of the unit. Two rechargeable nickel-metal hydride batteries that last for 8-10 hours of regular use supply power. The unit can vibrate whenever a similar machine is in range. An RS232 cable connects it to a PC, which allows users to download new games and applications from the Internet. It is also possible to write programs that access the RS232 port. The CyX2 uses a USB port to communicate with the outside world. Chapter 2 : Introducing BASIC & B2C Welcome to programming in B2C. B2C stands for Basic-to-C compiler. With B2C you can create very simple to very complex programs (including video games) with a minimum of effort. In the following pages you will find a step-by-step introduction to programming in B2C. To gain the maximum benefit from this tutorial you are encouraged to do each step one by one in order. When you are done, you will know enough to write any program you can imagine - and we know you have a wild imagination! BASIC is an acronym. It stands for Beginner's All-purpose Symbolic Instruction Code. It was invented in the 1960's as a simplified programming language for people of all types. The original language had a line number for each line of code. This helped to order the statements and make it easier for the newcomer to change something on a particular line. The purpose of the BASIC language is to make programming code more like English so that it can be easily learned by the non-computer professional. B2C is based on the CyBasic2 language by Cybiko, Inc. Unlike the 'C' programming language, CyBasic2 is interpreted. Languages like 'C' are compiled, meaning the instructions are transformed into machine code. CyBasic2 is interpreted at run time. It is never converted into machine code. So, it is slower than 'C'. B2C is a compiler - it transforms B2C code into C that is then compiled into a fast-running application. CyBasic2 was a fairly limited language. It had the ability to get input from the user, process that input, and print the processed results to the screen. The If command allowed CyBasic2 to handle conditionals and the For command allowed it to handle looping. There are only a handful of graphic functions including Point (for setting a pixel) and Line (for drawing a line). B2C on the other hand has commands to work with bitmaps directly. Anything you can do in C you can also do in B2C, only with B2C, it's easier. You can create real video games with B2C, something CyBasic2 was never designed to do. B2C also embeds passwords into the resultant program. The program will run for 60 seconds before the password screen pops up. Passwords can be purchased for $4.95 at www.DevCybiko.com/passwords.com. Follow this link for more information on the origins of BASIC: http://www.digitalcentury.com/encyclo/update/BASIC.html Chapter 3 : Downloading B2C B2C is available as a download at www.DevCybiko.com/basiccompiler.html. It is currently in version 3 (b2cv3.zip). When you download it, you must un-zip the file using a Zip tool (like PKZip or ZipMagic). Be sure to place B2Cv3 in a directory that is easy to use (like C:\b2cv3, for example). The next step is to download and install the Cybiko SDK from www.cybiko.com/devsarea. You will need Version 2.0 or better of the Standard or Professional SDK. (The Professional SDK costs $49.95. It is not necessary to purchase the professional version, the Standard works just fine). DO THIS If you want to cut to the chase and just rush through the tutorial, look for this box. Do the things in this box to learn how to program in B2C faster. If you didn't understand what happened in this box, then re-read the section above it. Chapter 4 : Editing Your First Program Introduction The process for any B2C program is simple: Edit, Compile, Download, Run, and Repeat. In this chapter we'll look at the first part: Editing. There are many good editors for use on the PC. Every programmer has a favorite editor. Here, we will discuss the Notepad editor for Windows, and the Edit program for MS-DOS. You will also be introduced to the MS-DOS Command Prompt, since you will spend much of your time there. Notepad The Notepad editor is a bare-essentials editor, which is precisely what we need for editing B2C programs. You can run Notepad by selecting the "Start" menu and pulling-right on "Accessories". Pull-down to the "Notepad" icon. Here is a summary of the Notepad menu options: Menu Option Keyboard Equivalent Comments File->New Alt-F-N Create a new, empty, text file File->Open Alt-F-O Open an existing file File->Save Alt-F-S Save the current file File->Save As Alt-F-A Save the current file with another name File->Page Setup Alt-F-T Print out setup File->Print Alt-F-P Print the file File->Exit Alt-F-X Exit Notepad Edit->Undo Ctrl-Z Undo edits Edit->Cut Ctrl-X Cut current selection Edit->Copy Ctrl-C Copy current selection Edit->Paste Ctrl-V Paste buffer Edit->Select All Alt-E-S Select entire file Edit->Time/Date F5 Insert Current Time/Date into file Edit->Word Wrap Alt-E-W Wrap words at the end of the line (or let lines go offscreen) Edit->Set Font Alt-E-F Set the font (default : courier) Search->Find Alt-S-F Find text Search->Find Next F3 Find text again Search->Replace Alt-S-R replace text (only on Windows NT) Help->Help Topics Alt-H-H Help information on Notepad Help->About Alt-H-A Copyright information Run Notepad and type the following... print "hello world" dim b input b Now exit the Notepad selecting the File->Exit menu and answer "Yes" when it asks you if you want to save the file. Use the filename "hello.b2c". MS-DOS and Edit The MS-DOS Edit command is a more powerful alternative to the Notepad editor. It offers a more professional set of features than Notepad. As a programmer, these features give you an easier path from your ideas to your code. The faster you can type your ideas into the editor, the more ideas you can code. So what features do we need in an editor? Here is a list of the bare essentials: * open file * save file * enter and edit text * cut, copy and paste of text * tab or indent * search * search & replace You may desire other features, but I find these to be the minimum. Notepad (for Windows 9x) does not have a search & replace and line numbering. MSDOS as Your Working Environment The MS-DOS (Microsoft Disk Operating System) Prompt is still delivered with all MS Windows operating systems. This is a viable working environment for our needs. DO THIS To run the MS DOS Command Prompt, select the Start menu and Programs. Pull right and find MS DOS Prompt (or Command Prompt) in the menu. You may want to modify some of the properties of the MS-DOS window. For example, the default setting is for a 24-line display. I like more lines of text when using the text editor. To change the properties, click the left mouse button over the MS-DOS logo in the upper-left corner of the window - this will display a menu. Select "Properties" at the bottom of the menu. Here are the settings I like to use for MS-DOS: Tab Selection Setting Default Recommended Program -keep all defaults- -keep all defaults- -keep all defaults- Font Bitmap Only Both Font Types Bitmap Only Font Size Auto 8x12 Memory -keep all defaults- -all set to Auto- -keep all defaults- Screen Usage Window Window (not Full Screen) Initial Size Default 50 lines Window Display Toolbar (checked) Do Not Display Toolbar Restore Settings (checked) Restore Settings (checked) Performance Fast ROM Emulation (checked) Fast ROM Emulation (checked) Dynamic Memory Allocation (checked) Dynamic Memory Allocation (checked) Misc -keep all defaults- -keep all defaults- -keep all defaults- MS-DOS Commands There are relatively few MS-DOS commands that you will need to know in this tutorial. Fortunately, the majority of tasks can be handled in Windows. Nevertheless it is useful to know how to do certain, fundamental operations. The following table summarizes them: Command Syntax Remarks Del del filename.ext del *.ext deletes one or more files (*=wildcard characters) Copy copy file1.ext file2.ext copies file1 to file2 Cd cd dirname cd .. change directory from one place to another change directory to parent directory batch file filename.bat a list of MS-DOS commands in a file with the extension .bat. This will be executed when you type in the name of the file (like make.bat in Step1.app) Dir dir dir *.ext - list all files in current directory - list only files with certain extension Introducing MS-DOS Edit DO THIS In the MS-DOS Prompt, type cd C:\...\b2cv3 (where ... is the path to b2cv3) DO THIS Next type "edit" and when the blue screen pops up, type in the following... print "hello world" dim b input b Now exit the editor by typing the ALT-F-X commands (or choosing File->Exit with the mouse) and answer "Y" when it asks you if you want to save the file. Save the filename as "hello.b2c" MS-DOS Edit Commands MS-DOS Edit is a very straightforward editor with a few hidden options. It is "mouse-enabled," meaning that if you click on the menu bar, the expected Windows-like thing will happen. Clicking on some text in the Editor window will move the cursor to that position. You can drag the mouse over text and it will select the text. If you would rather, you can use the keyboard for menu operations by holding down the ALT key (at the bottom of the keyboard, next to the space bar). When you hold down the ALT key, the menu "lights up" and you may press the highlighted character to drop-down the selected menu. For example, selecting ALT-F drops-down the File menu. Also, holding down the SHIFT key and moving the arrow keys will select text for cut and paste operations. In dialog boxes, the TAB key usually will move you from field to field. The arrow keys will move you up, down, left, and right. If you select text in the Editor window and hit the TAB key, the selected region will be indented one tab stop (usually 8 characters). Holding down the SHIFT key and hitting TAB will "outdent" one tab stop. MS-DOS Edit Menu commands Menu Option Keyboard Equivalent Comments File->New Alt-F-N Create a new, empty, text file File->Open Alt-F-O Open a file that has already been created File->Save Alt-F-S Save the currently displayed file File->Save As Alt-F-A Save the currently displayed file with another name File->Close Alt-F-C Close the current file and its window File->Print Alt-F-P Print the currently displayed file File->Exit Alt-F-X Exit the Editor Edit->Cut Ctrl-X Delete the currently selected text and copy it to the buffer Edit->Copy Ctrl-C Copy the currently selected text to the buffer Edit->Paste Ctrl-V Insert the buffer into the currently selected file Edit->Clear Del Delete the currently selected text (but don't copy it to the buffer) Search->Find Alt-S-F Open the Find Dialog Box and search for the first occurrence Search->Repeat Last Find F3 Repeat the last find command Search->Replace Alt-S-R Open the Search/Replace Dialog box View->Split Window Ctrl-F6 Split the current window in two horizontally View->Size Window Ctrl-F8 Begin resizing the split windows. Use the up and down arrow keys View->Close Window Ctrl-F4 Close the currently selected split window, restore to a single window pane View->n Alt-n where n=1-9 - make the selected file the currently selected file Options->Settings Alt-O-S Display the Settings dialog box Options->Colors Alt-O-C Display the Colors dialog box allowing you to customize the colors to your preferences Help->Commands Alt-H-C Display a listing of keyboard commands Help->About Alt-H-A Display copyright information The File->Open and File->Save As menu options will display a dialog box with ... * Filename input field - can hold wildcard (*) patterns or filenames * Current Working Directory * Filename listbox - showing all files matching the pattern in the Filename input field * Directories listbox - showing the parent dir (..), any directories, and other devices ([-A-], [-C-], [-D-], etc...) * Open Read Only Checkbox - select this if you don't want to modify the file when you open it (either click on it with the mouse, or tab over to it and hit the space bar) * Open Binary Checkbox - select this if you want to open files with other than ASCII data (like .app files) * Line Width - for binary files only, the number of characters per line to display The File-Print menu option will give you the option of printing selected text or the entire file. The Search->Find menu option will display a dialog box with ... * Find What - the text string you want to find * Match whole word only checkbox - use this to find the search string as a word (surrounded by white space - space characters, tabs, newlines) * Match case - use this to force upper and lower case letters to match The Search->Replace menu option will display a dialog box with ... * Find What - the text string you want to replace * Replace With - the text string you want to replace the search string with * Match whole word only checkbox - use this to find the search string as a word * Match case - use this to force upper and lower case letters to match * Replace Button - replace a single occurrence of the search string * Replace All - replace all occurrences in the currently selected file The View->Split option splits the current window into 2 panes. You are free to open a second, different file into the second window. You may resize the panes by selecting View->Size Window and moving the "center bar" up and down with the arrow keys. Or, you can use the mouse pointer to grab the "center bar" and drag it to the size you like. Selecting View->Close Window will return the Editor to single-pane viewing. The Options->Settings will display a dialog box with ... * Tab Stop (defaults to 8, but I recommend 4) - the number of spaces to indent when TAB is entered. * Colors - allows you to change many color parameters in the Editor. I recommend keeping the defaults. If you get lost, you can always come here and click on "Defaults". The Help->Commands menu option displays a dialog box with a listing of many "hidden" keyboard commands. I won't repeat their descriptions here. Most of them are obvious (like Home to return to the beginning of a line). But there are a few surprises (like CTRL-Y to delete a line). Use the Page-Up and Page-Down keys to scroll through the list. Chapter 5 : Compiling Your First Program B2C programs require a set of supporting files to create an application. Fortunately for you the B2Cbuild process handles this for you. You may never have to look at these files. DO THIS At the MS DOS command prompt type "build hello.b2c". If any errors occur you will see the word "ERROR", but if all goes well you should see a line which says something like "Done 7 files." In the event of an error, examine the error line. It will show the source file followed by a line number in parenthesis, followed by the error. For Example: hello.b2c(2) - Parse error Indicates an error in line two of hello.b2c. A parse error is some sort of spelling error. Chapter 6 : Downloading and Running Your Application If you have installed CyberLoad on your PC, then you can download your application easily. First, verify that your Cybiko is connected to the computer in the usual way. DO THIS Just double-click on the file "hello.app" in the Windows Explorer (file browser). The file will be automatically downloaded to your Cybiko Now that you have downloaded your application to the Cybiko, find it and run it. It will have the "B2C" logo for an Icon, and may have "Tardis Adventure" as the text (unless you changed it in chapter 5). Run it. It will say "hello world" and wait for you to click on the Enter key. Chapter 7 : Programming Basics : Input/Process/Output Input, Processing, Output All computer programs have three elements - Input, Processing, and Output. Input is information (or data) fed into the computer. Input can be in the form of a textual string of characters from the keyboard, a mouse movement, or a data file. Output is information (or data) sent out of the computer. Output can be in the form of text displayed on the computer screen, mouse movement, graphics, or writing to a data file. Finally, Processing is any action performed on the input data to generate the output data. Input B2C has two commands to get data from the user and into the Cybiko computer. The major one is called 'Input' and the other one is called 'key' (we'll discuss key later). Input takes data from the keypad and inserts it into a variable (we'll discuss variables more in the next chapter). The Input statement looks like this: input a The 'a' in the input statement is the name of a variable, which receives the data. In B2C the input statement accepts a prompt string. This string is displayed on the screen before the user enters their value: dim name[32] input "Enter your name", name Output The command for output to the Cybiko screen is 'Print'. The Print statement takes one or more variables and character strings (separated by commas) and displays them on the screen. In its default mode, the screen holds 7 lines of about 23 characters each (The FONT command, as we'll later see, can change this). print "The value of a is", a The stuff between the quotes (") is called a "Literal String". This is a string of letters, digits, and other characters that you want displayed on the screen. Here, the variable 'a' will be displayed. It is important to realize that 'a' is not displayed, but rather, it's value. Also note that typing this statement into B2C alone will result in an error. You will need to Dimension (Dim) any variables before using them. Dim is covered in the next chapter. Processing Nearly everything else in the B2C set of commands can be considered processing. The simplest sort of processing is assignment. The assignment operation is the equal sign '='. You can assign a value to a variable like this: a = 1 We're giving the variable 'a' a value of one. Consider the next examples... a=1 b=a+1 print b Here, 'b' is given the value 'a+1'. In this case the variable 'a' is replaced with the value of 'a' (which is one). Hence, b=1+1 or b=2. So, the value of 'b' is two. Comments All good computer languages have a way to document the code (programmer lingo for the statements comprising a program) in the program itself. Commenting a program is good practice in the event that you want to share your program with someone else. Commenting is also good as a way of reminding yourself what you intended when you wrote the code to begin with. It is good practice to have one line of commentary for each line of code - on average. In B2C, comments are identified by a single-quote mark (also called the 'apostrophe' mark). ' demo program for chapter 7 dim a dim b a=1 'set a to one b=a+1 'set b to one greater than a Print b 'show the user the value of b As we'll see in the upcoming example program, it is also useful to name your variables in a self-documenting way. If you are summing 4 grades, name the variables grade1, grade2, grade3, grade4, sum (the sum of the grades) and avg (the average of the grades). While variable names like 'a' and 'b' are short and easy to type, they are also cryptic and hard to remember. Upper and Lower Case B2C does not care about upper or lower case. A varaible name written in uppercase (A) in one place can be referred to later in lowercase (a). The names of statements in B2C are also not case sensitive. So Print and PRINT and print are all the same function. Example Program DO THIS Copy the file "c:\...\b2cv3\tutorial\ch7.b2c" to "C:\...\b2cv3\ch7.b2c". Then execute the command "build ch7.b2c". Download the ch7.app file to the cybiko. The example program will take 4 values as input, sum them, and take the average. The average is the sum of a set of numbers divided by the number of items. ' chapter 7 example program ' sum and average of 4 grades ' grades are from 0-100 dim grade0 ' we'll discuss the Dim command in the next chapter dim grade1 ' here are our 4 grades dim grade2 dim grade3 dim sum 'this variable will store the sum of the 4 grades dim avg 'this variable will store the average of the 4 grades ' ---INPUT --- print "Enter grade 0" 'we'll discuss numbering at 0 in the next chapter input grade0 'get the grades from the student print "Enter grade 1" input grade1 print "Enter grade 2" input grade2 print "Enter grade 3" input grade3 '--- PROCESS --- ' compute the sum and the average sum = grade0+grade1+grade2+grade3 avg = sum/4 '--- OUTPUT --- print "The average of your " print "4 grades is", avg print "Press to continue" dim tmp ' a temporary variable input tmp 'wait for the user to press enter Chapter 8 : Variables and DIM Variables As we saw in Chapter 7, variables hold a value. The value can be a number (like 1) or the result of an operation (like a+1). You may think of variable as a shoebox with a label on the outside. Inside the shoebox is a value. On the front of the shoebox is a label with a variable name (like 'a', or 'b' or 'avg'). We also saw that before using a variable we have to declare it. This is done with the 'Dim' statement (short for Dimension). The Dim statement alerts B2C to the fact that we are about to use a variable. The variable is initially set (initialized) to zero. Data Types It turns out that B2C has 4 different variable types. These are Int, Char, Long and Double. Currently, Double (or floating point) data types are not supported. Using the Double type will coerce the variable to Int. 'Long' variables are integer variables (no decimal point) containing 4 bytes. They can range from -2,147,483,648 to +2,147,483,647. Because Longs are integer variables, they are fast variables when it comes to computation. But, since they are 4 bytes long, they still take up a lot of Cybiko computing power when processing. Use the Long data type when you need large values but you don't need a decimal point. To declare a Long variable place the words "as long" after the declaration: dim a as long The usual (default) type is called Int (or integer). 'Int' variables are integer variables which means they cannot hold a decimal point and contain only 2 bytes of data. They can range from -32,768 to +32,767. As you will see, the range is much smaller than a Long. And because this is the favorite size of numbers for the Cybiko's internal microprocessor, Int variables perform the fastest. To declare an Int variable place the words "as int" after the declaration: dim a 'defaults to int dim a as int 'Char' variables are also integer variables, but contain only 1 byte of data. Char variables range from -128 to +127. They are not very useful in computations - and since they are smaller than the Cybiko's favorite word size (2 bytes) it actually takes longer to process a Char than an Int. As we'll see shortly, Char variables are usually used in an array as a character string for input and output, rather than as a numeric quantity for computation. To declare a Char variable place the words "as char" after the declaration dim a as char Names of Variables The name of a variable can be any length with no spaces in it. The first letter must be alphabetic (a-z). Subsequent letters may be alphanumeric (a-z or 0-9). You may also use the underscore (_) character in variable names. As mentioned before, upper and lower case do not matter. Arrays An array is a list, or grouping, of variables. If you have a list of something you will want to declare an array of them. Returning to our shoebox example, suppose you have an exam grade. You can mark the outside of a shoebox with the name "grade" and put the exam inside the box. If you ever want to refer to the grade, you find the shoebox marked "grade" and take out the exam and look at the grade you received. This use of a single variable is called a 'scalar'. But you cannot put more than one grade inside the shoebox. Now, let's assume that you have many students and you want to keep all their grades separated. You might get a set of shoeboxes and line them up in a row. On the front of each box put the student's number (0, 1, 2, 3, etc...). Each student exam goes into the box with that student's number on it. From then on, you access the boxes as "grade[0]", "grade[1]", etc... This is called an array of variables. The part between the brackets is called the subscript. To create an array of variables, use the Dim statement as before and put the number of elements of the array in brackets after the name. Here is an example of an array of 10 grades: Dim grades[10] as int Humans are taught to count starting from one. If I asked you to count to ten, you might reply "1, 2, 3, ...10" But computers prefer to count starting from zero. (Technically speaking, computers use an offset and it is convenient for computation and memory layout if the offset starts at zero). So, the first grade in our example is grade[0] (Does this explain why I used grade0 earlier? I hope so!). The next one is grade[1]. And so on up to grade[9]. (Notice that we cannot use grade[10] - since that would be the eleventh grade and we defined 10 integers.). All data types may be arrays. The Char array is special in that it is treated like a string of text by B2C. When you want to input a name, use the Char array: Dim name[32] as char Input name Print "your name is ", name Example Program DO THIS Copy the file "c:\...\b2cv3\tutorial\ch8.b2c" to "C:\...\b2cv3\ch8.b2c". Then execute the command "build ch8.b2c". Download the ch8.app file to the cybiko. Here we return to our grade-averaging problem, only this time we use an array of grades. In the next chapter we will see the real power of arrays when we introduce loops. ' chapter 8 example program ' sum and average of 4 grades ' grades are from 0-100 dim grade[4] ' an array of 4 grades dim sum 'this variable will store the sum of the 4 grades dim avg 'this variable will store the average of the 4 grades ' ---INPUT --- print "Enter grade 0" input grade[0] 'get the grades from the student print "Enter grade 1" input grade[1] print "Enter grade 2" input grade[2] print "Enter grade 3" input grade[3] '--- PROCESS --- ' compute the sum and the average sum = grade[0]+grade[1]+grade[2]+grade[3] avg = sum/4 '--- OUTPUT --- print "The average of your" print "4 grades is", avg print "Press to continue" dim tmp ' a temporary variable input tmp 'wait for the user to press enter Chapter 9 : Looping : For ... Next The computer is very good at following instructions. Its ability to do what it is told to do, over and over again, is what makes the computer a valuable tool. In this chapter we will learn how to instruct a computer to do the same thing several times. This ability is called looping. It is called looping because in the early days of computers programmers drew pictures of their programs before they ever wrote code. These pictures were called "flow charts." In a flow chart a statement in a program was shown as a box. The next statement was connected to the first by a line with an arrow on it. If a programmer wanted to repeat a step in the process, they would show it by drawing a line back up to the previous step - forming a loop. (There is also the story of how paper tape with little holes in it was used to instruct the computer. To make the computer repeat instructions over and over, the programmer would connect the end of the tape to the beginning - forming a loop.) In B2C the loop is implemented by the For command. The For command has three parts: the initialization, the final value, and the (optional) step. for [initialization] to [final value] [step] for i=0 to 3 step 1 'statements go here next The 'initialization' part uses an un-Dim'd variable name (like i) and is initialized to the start value of the loop. The 'to' part declares the last value of the loop and the 'step' declares the amount to increment 'i' inside the loop. If the 'step' part is omitted "step 1" is assumed. The word "next" indicates the end of the loop and tells B2C to increment the variable by the step value and to go back to the top of the loop (the statement just after the for). If the variable has reached the 'final value' then processing continues on the statement after the next. For readability, the statements inside the for loop are indented 3 or 4 spaces. It is possible to exit a For loop early by executing the "Exit For" command in the middle of the loop. Historical Note: The variables i, j, k, l, m, & n are favorite variables for loops. This is for two reasons. First, the single letter makes for easier typing as a subscript to an array variable. Second, in the early days of programming (1960s) there was a language called FORTRAN that had no DIM statement. Instead, all variables were named a-z, and were assumed to be Double (floating point). Except for the variables i-n, which were integers. Why i-n? Because i & n were the first 2 letters of the word "integer". Infinite Loops It is possible to get caught in a loop that never exits. This is known as an infinite loop. A for loop with a zero step size would create an infinite loop for i=0 to 0 step 0 print i next The example code above will print a screen ful of zeroes. To get out of an infinte loop, press the ESC key. Example program: DO THIS Copy the file "c:\...\b2cv3\tutorial\ch9.b2c" to "C:\...\b2cv3\ch9.b2c". Then execute the command "build ch9.b2c". Download the ch9.app file to the cybiko. With the introduction of loops, our program becomes even simpler. Now we don't have to declare the number of grades up front. It becomes a variable we get from the user at the start. ' chapter 9 example program ' sum and average of n grades ' grades are from 0-100 dim sum 'this variable will store the sum of the n grades dim avg 'this variable will store the average of the n grades dim n as int ' the number of grades to average print "How many grades?" input n dim grade[n] ' an array of n grades ' ---INPUT --- for i=0 to n-1 'get the inputs print "Enter grade ", i ' notice that we indent in loops input grade[i] 'get the grades from the student next '--- PROCESS --- ' compute the sum and the average for i=0 to n-1 sum = sum + grade[i] 'notice we accumulate the sum next avg = sum/n 'compute the average '--- OUTPUT --- print "The average of your" print n, " grades is", avg print "Press to continue" dim tmp ' a temporary variable input tmp 'wait for the user to press enter Chapter 10 : Conditionals : If ... Then ... Else ... End If Another thing computers are good at is making unbiased decisions. In B2C this is implemented with the If statement. The If statement has a conditional followed by the Then clause: if [conditional] then 'statements end if if a < b then print "a is smaller" end if This conditional has a left side and a right side with a relational operator in between. You can compare two variables, or two expressions. There are 6 relational operations: < less than > greater than <= less than or equal to >= greater than or equal to = equal to <> not equal to For example: if a+1 < b*2 then 'statements end if There is also an Else statement, which indicates what to do if the conditional is not met: if [conditional] then 'statements else 'else statements end if if a,<=,>=,=,<>) is either TRUE or FALSE. This type of value is called Boolean (named for the mathematician George Boole). Booleans are either True or False (one or zero). These types of results can be combined with the Boolean operators AND and OR. You can even negate the conditional with the NOT operator. The And operator results in a TRUE value if BOTH of the inputs are TRUE (and results in a FALSE otherwise). The Or operator results in a TRUE value if EITHER of the inputs are TRUE. In B2C, a zero value is FALSE and any other value is considered TRUE. NOT converts a TRUE result into a FALSE result. if ab or a>c then print "a is bigger than either b or c" end if a=1 b=0 if a and b then print "both a and b are true" end if if a or b then print "either a or b is true" end if Example program: DO THIS Copy the file "c:\...\b2cv3\tutorial\ch10.b2c" to "C:\...\b2cv3\ch10.b2c". Then execute the command "build ch10.b2c". Download the ch10.app file to the cybiko. Conditionals will allow us to assign a letter grade to the input grades and the average ' chapter 10 example program ' sum and average of n grades ' grades are from 0-100 dim sum 'this variable will store the sum of the n grades dim avg 'this variable will store the average of the n grades dim n as int ' the number of grades to average print "How many grades?" input n dim grade[n] ' an array of n grades ' ---INPUT --- for i=0 to n-1 'get the inputs print "Enter grade ", i ' notice that we indent in loops input grade[i] 'get the grades from the student next '--- PROCESS --- ' compute the sum and the average for i=0 to n-1 if grade[i] >=94 then print grade[i], "=A" elseif grade[i]>=86 then print grade[i],"=B" elseif grade[i]>=78 then print grade[i], "=C" elseif grade[i]>=70 then print grade[i], "=D" else print grade[i], "=F" end if sum = sum + grade[i] 'notice we accumulate the sum next avg = sum/n '--- OUTPUT --- print "The average of your", print n, " grades is ", avg if avg >=94 then print avg, "=A" elseif avg>=86 then print avg,"=B" elseif avg>=78 then print avg, "=C" elseif avg>=70 then print avg, "=D" else print avg, "=F" end if print "Press to continue" dim tmp ' a temporary variable input tmp 'wait for the user to press enter Chapter 11 : While The While command is another type of looping command. Like the For command, While executes until a condition is met. Here is the form of the While command: while [conditional] 'things to do wend dim a as int a=1 while a<10 print "a=", a a=a+1 wend The Wend command ends a while loop. DO THIS Copy the file "c:\...\b2cv3\tutorial\ch11.b2c" to "C:\...\b2cv3\ch11.b2c". Then execute the command "build ch11.b2c" Download the ch11.app file to the cybiko This example program plays "Hi/Low" - a number game where the user has to guess the computer's random number 'Hi Low Number Guesser dim guess as int dim tries as int dim number as int tries=0 number = rnd(100)+1 while(guess <> number) print "enter your guess" input guess if guess < number then print guess, " is too low" tries=tries+1 elseif guess > number then print guess, " is too high" tries=tries+1 end if wend print "You guessed it." print "The number was ", number print "It took you ", tries, " tries" dim a input a Chapter 12 : Functions & Subroutines You may have noticed in the last example program that we had to create two sets of If/then/else/endif statements to handle the conversion of a grade into a letter grade. This duplication of code is a bad practice. If there are several of these blocks of code, and we find a bug in one of them, we have to update all of them. For example, what if, in our example program, we decided that the grade cutoffs were 90, 80, 70, and 60? We would have to make the modification in each of the two blocks of If statements. This could lead to extra work, or even errors in our program if we forget to make the same changes in both places. Fortunately, B2C has a concept called a Subroutine. In the old days, a program was called a routine. A Subroutine therefore is a routine within a routine. You can declare a subroutine with the word Sub: Sub [routine-name] [(var as type, var as type, ...)] 'statements End Sub The Parameters portion of the Subroutine is a list of variables (declared much in the same way as the Dim statement). These variables are the inputs to the subroutine. Once declared, a subroutine can be called (or invoked) with the Call statement [Call] routine-name [(parameters)] The keyword Call is optional. Here is an example using our grade-averaging program: Sub letterGrade(grade as int) if grade >=94 then print grade, "=A" elseif grade>=86 then print grade,"=B" elseif grade>=80 then print grade, "=C" elseif grade>=74 then print grade, "=D" else print grade, "=F" end if End Sub You may exit a Subroutine early by executing the command Exit Sub. Another way to solve this problem is with a Function. A function is like a subroutine, but it returns a value. In our example a function could return the letter grade, given the numeric grade. To return a value, you set the name of the function to the value, just like an assignment statement. As with the Subroutine, you may exit a function early with the Exit Function command. Function letterGrade(grade as int) as char if grade >=94 then letterGrade = 65 'ascii characters but we didn't teach it elseif grade>=88 then letterGrade = 66 elseif grade>=80 then letterGrade = 67 elseif grade>=74 then letterGrade = 68 else letterGrade = 70 end if End Function Example program: DO THIS Copy the file "c:\...\b2cv3\tutorial\ch12.b2c" to "C:\...\b2cv3\ch12.b2c". Then execute the command "build ch12.bld". Download the ch12.app file to the cybiko Subroutines allow us to simplify our program by taking similar sections of code and condensing them into one subroutine. ' chapter 11 example program ' sum and average of n grades ' grades are from 0-100 Sub letterGrade(grade as double) if grade >=94 then print grade, "=A" elseif grade>=86 then print grade,"=B" elseif grade>=80 then print grade, "=C" elseif grade>=74 then print grade, "=D" else print grade, "=F" end if End Sub dim sum 'this variable will store the sum of the n grades dim avg 'this variable will store the average of the n grades dim n as int ' the number of grades to average print "How many grades?" input n dim grade[n] ' an array of n grades ' ---INPUT --- for i=0 to n-1 'get the inputs print "Enter grade ", i ' notice that we indent in loops input grade[i] 'get the grades from the student next '--- PROCESS --- ' compute the sum and the average for i=0 to n-1 print "Grade ", i, ": ", grade[i] call letterGrade(grade[i]) sum = sum + grade[i] 'notice we accumulate the sum next avg = sum/n '--- OUTPUT --- print "The average of your" print n, " grades is ", avg call letterGrade(avg) print "Press to continue" dim tmp ' a temporary variable input tmp 'wait for the user to press enter Chapter 13 : Math Operations B2C supports a host of math Operations. The ordinary operations exist (+, -, *, /,MOD) with which you can do math calculations. The Order of Operations applies (multiplication and division first, then addition and subtraction) and parentheses are used to change the order of operations. (a=(a+b)*c). B2C currently supports only integer arithmetic. dim a as int a = 5 + 1 print "the answer is ", a > the answer is 6 Random Numbers Random numbers are numbers whose value is unpredictable. You can get a random number with the Rnd() function: Rnd(x) Where 'x' is any number. Rnd(x) will return a number from 0 to 'x' inclusive. x=rnd(5)+1 'return a number from 1 to 6, like a 6-sided die Chapter 14 : Simple Graphics The Cybiko is a very capable graphics machine. In this section we cover the non-bitmapped graphics commands. B2C has 5 basic graphic commands with which to draw on the screen. Cls - Clear screen Cls stands for Clear Screen. It will turn all pixels on the display to the background color (usually white). It will also erase all text on the screen. Cls takes no parameters Cls Paper - set the color of the background B2C has a concept of a foreground color and a background color. The background color is set with the Paper command. Whenever you do a Cls - the entire display is set to the color defined by the Paper command. There are 4 colors to chose from. Color 0 is white. Color 1 is light grey. Color 2 is dark grey. Color 3 is black. There are constants defined for your use: 0 - White 1 - LtGrey 2 - DkGrey 3 - Black Paper Black ' set the background color to black Cls ' color the screen with the background color Ink - set the color of the foreground B2C's foreground color is used to draw text (Print) and lines (Line). There are constants defined for your use: 0 - White 1 - LtGrey 2 - DkGrey 3 - Black Paper White ' set the background to White Ink Black ' set the foreground to black Cls ' clear the background line -80, -50, 80, 50 ' draw a diagonal line Line - draw a line on the screen The B2C display area is an X/Y coordinate system. You place a line on the screen by telling B2C to position the cursor at a horizontal (X) coordinate and a vertical (Y) coordinate. The valid values for the screen coordinates are -80 to 79 in the X (horizontal) direction, and -50 to 49 in the Y (vertical) direction. You may specify values as large as +/- 20,000 in either direction, but only the pixels, which are in the screen coordinates (-80 to 79 and -50 to 49), will be displayed. Paper White ' set the background to White Ink Black ' set the foreground to black Cls ' clear the background line -80, -50, 80, 50 ' draw a diagonal line It is possible to use a different coordinate system. The so-called 'C' coordinate system runs from 0 to 159 in the X direction and from 0 to 99 in the Y direction. You can switch to this system by placing OPTION C_COORDS at the top of your program. Point - draw a single pixel on the screen Draw a single pixel at the x/y coordinates (see Line, above). Paper White ' set the background to White Ink Black ' set the foreground to black Cls ' clear the background Point 0, 0 ' draw a dot in the center Example Program DO THIS Copy the file "c:\...\b2cv3\tutorial\ch13.b2c" to "C:\...\b2cv3\ch13.b2c". Then execute the command "build ch13.bld". Download the ch13.app file to the cybiko. This program is like the old Microsoft Windows screen saver. A set of bouncing lines chase after each other. 'chapter 13 'qix line drawing 'requires B2C-2 'see below for B2C-1 dim n as int print "Number of lines" input n dim n1 as int dim n2 as int n1=n-1 n2=n1-1 dim x0[n] as int dim y0[n] as int dim x1[n] as int dim y1[n] as int dim dx0 as int dim dy0 as int dim dx1 as int dim dy1 as int dim seed as int sub newdirection(j as int) if (x0[j] < -80 or x0[j] > 80) then dx0 = -dx0 end if if (x1[j] < -80 or x1[j] > 80) then dx1 = -dx1 end if if (y0[j] < -43 or y0[j] > 43) then dy0 = -dy0 end if if (y1[j] < -80 or y1[j] > 80) then dy1 = -dy1 end if end sub ' for B2C1 do the following ' dx0=-3 ' dx1=-1 ' dy0=1 ' dy1=2 'and remove the while loops... ' select random motion offsets while dx0=0 dx0 = 4-rnd(9) wend while dx1=0 dx1 = 4-rnd(9) wend while dy0=0 dy0 = 4-rnd(9) wend while dy1=0 dy1 = 4-rnd(9) wend 'select initial random line x0[0] = rnd(80) x1[0] = rnd(80) y0[0] = rnd(43) y1[0] = rnd(43) line x0[0], y0[0], x1[0], y1[0] cls 'fill up queue with trailing lines and print them for i=1 to n-1 x0[i] = x0[i-1] + dx0 x1[i] = x0[i-1] + dx1 y0[i] = y0[i-1] + dy0 y1[i] = y1[i-1] + dy1 line x0[i], y0[i], x1[i], y1[i] newdirection(i) next for i=0 to 1 step 0 ink 0 line x0[0], y0[0], x1[0], y1[0] ink 3 for j=1 to n-1 x0[j-1] = x0[j] x1[j-1] = x1[j] y0[j-1] = y0[j] y1[j-1] = y1[j] next x0[n1] = x0[n2] + dx0 y0[n1] = y0[n2] + dy0 x1[n1] = x1[n2] + dx1 y1[n1] = y1[n2] + dy1 line x0[n1], y0[n1], x1[n1], y1[n1] newdirection(n1) next Chapter 15 : Printxy Printxy is like a combination of the Point function and the Print function. Printxy allows you to position text anywhere on the Cybiko screen. The format of the Printxy command is: printxy x,y, value [, value...] The text string is composed of the values of the variables after the Y coordinate. The text string is printed at the coordinates X, Y. The values will be painted with the X/Y coordinate in the upper left corner of the text. The values can be any collection of comma-separated variables or literals - just as in Print. Our Example Program will print your name on the display and bounce it off the edges of the screen. Try using shorter names to see how the performance improves. DO THIS Copy the file "c:\...\b2cv3\tutorial\ch14.b2c" to "C:\...\b2cv3\ch14.b2c". Then execute the command "build ch14.b2c". Download the ch14.app file to the cybiko. dim name[32] as char'your name dim x as int 'x coordinate of your name dim y as int 'y coordinate of your name dim dx as int 'direction the name moves in x coord dim dy as int 'direction the name moves in y coord input "Enter your name ", name x = 80-rnd(160) 'random x starting point y = 43-rnd(86) 'random y starting point dx = -1 ' moving to the left dy = -1 'moving up while 1 'do forever or until ESC is pressed cls 'clear the screen printxy x,y, name 'print the name onscreen x=x+dx 'move x dir y=y+dy 'move y dir if x>80 then dx=-dx ' bounce off right side end if if x<-80 then dx=-dx ' bounce off left side end if if y>30 then dy=-dy 'bounce off bottom end if if y<-43 then dy=-dy 'bounce off top end if wend Chapter 16 : Miscellaneous Beep B2C includes a simple command for making sound. It is different from the beep command in CyBasic2. The Beep command causes the speaker to make a single tone. Beep takes values from 1 (low-pitch) to 63 (high-pitch). Beep 0 will result in silence. Wait There are 2 ways to create a delay in B2C. One way is to write a For loop which does nothing: for i=0 to 100 next i This is not recommended. It is sloppy coding and will be unpredictable in the event that Cybiko, Inc releases a newer, faster Cybiko. The alternative is the Wait command. The parameter is a number of tenths of seconds to wait. So, to wait one second: wait 10 Key The Key command has two modes. In the first, it acts like a variable. x = key It returns the value of the last key pressed on the keypad. This is very useful for writing interactive games because it does not stop the action like the Input statement does. At the end of this chapter is a table of all the values the Key variable can return. To use the table, find the key you want to check against and add the values in the corresponding row and column. For example, the letter 'a' is 90+7=97. The other format for the key command is as a function to check a single key: x = key(#KEY_ENTER) In this mode you specify the key you want to check and key() returns True or False. Here is a listing of some of the constants you may use (note, these must be in uppercase)... #KEY_A - #KEY_Z #KEY_0 - #KEY_9 #KEY_UP, #KEY_DOWN, #KEY_LEFT, #KEY_RIGHT #KEY_ENTER, #KEY_SPACE, #KEY_INS, #KEY_DEL Key Values 0 1 2 3 4 5 6 7 8 9 30 space quote 40 comma dash period / 0 1 50 2 3 4 5 6 7 8 9 semi-colon 60 = 90 ( \ ) back- quote a b c 100 d e f g h i j k l m 110 n o p q r s t u v w 120 x y z 260 left-arrow up-arrow right-arrow down-arrow ins del 270 tab select enter bspc shift fn DO THIS Copy the file "c:\...\b2cv3\tutorial\ch16.b2c" to "C:\...\b2cv3\ch16.b2c". Then execute the command "build ch16.b2c" Download the ch16.app file to the cybiko. Here is an example of a program that moves a dot left or right: dim x as int 'horizontal component of the dot dim y as int 'vertical component of the dot dim z as int 'the key pressed x=0 'initial x position of the dot y=0 'initial y position of the dot cls 'clear screen point x,y 'show the dot for i=0 to 1 step 0 'loop forever z = key 'save off the key because it changes if z = 264 then 'left key ink 0 point x,y ink 3 x=x-1 'move left point x,y 'print new dot elseif z = 266 then' right key ink 0 point x,y ink 3 x=x+1 ' move right point x,y ' print new dot end if next 'end of forever loop Chapter 17 : String Manipulation (Right/Mid) The B2C language offers no way to assign one string to another: dim a[32] as char dim b[32] as char : a = b 'illegal operation Instead there are 2 statements for copying strings. These are the Mid statement (used for copying the middle of one string to another) and the Right statement (used for copying the right side of a string). The Mid and Right statements takes the form: Mid destination, source, start [, length] 'the length is optional Right destination, source, length For the Mid statement, the 'destination' is a dimensioned string where the result will be stored. The contents of the original string will be discarded. The 'source' is a dimensioned string that holds data to be copied to the destination. The 'start' is a numerical value (variable, constant, or expression) indicating the first character from the 'source' to copy (remember, in B2C we count starting at zero). The optional length indicates how many bytes to copy. If the length is omitted, or if it is larger than the number of characters in the source array, the entire source array is copied. The Right statement has similar parameters. The destination is the dimensioned string to copy into, and the source is the string to copy from. The length parameter is required and indicates how many letters from the RIGHT of the source string to copy into the destination. In our example program we will learn to speak pig latin. It is not perfect. Can you think of ways to improve it? Example Program DO THIS Copy the file "c:\...\b2cv3\tutorial\ch18.b2c" to "C:\...\b2cv3\ch18.b2c". Then execute the command "build ch18.b2c" Download the ch18.app file to the cybiko 'ch 18 dim word[32] as char ' the word to convert dim ordway[32] as char ' the resultant word dim len as int ' the length of ordway input "enter your word ", word 'input mid ordway, word, 1 'copy the word but not the 1st char len = 0 for i=0 to 31 'get the ordway length so we can add 'ay' if ordway[i] = 0 and len = 0 then len = i end if next 'print len ordway[len] = word[0] ' append the first letter of word to the end of ordway ordway[len+1] = 97 ' append 'a' ordway[len+2] = 121 ' append 'y' ordway[len+3] = 0 ' null terminator, very important print word, "=", ordway ' print results input word ' wait for Enter Chapter 18 : File I/O Files on the Cybiko are stored in the non-volatile memory. They are like files on the PC in that they have filenames and they hold data. They even have attributes (like file size), but these attributes are not accessible from B2C. Open a file Before a file can be accessed, it must be opened. In B2C, opening a file is accomplished with the Open command. The Open command has three parts - the pathname, the mode, and the filenumber. The mode is optional. open pathname [for mode] as filenumber The pathname is the name of the file. This can be either a literal string ("filename.dat") or a variable which has been Dim'd previously. The mode is optional and is one of Read, Write, or Append. If left blank, the mode defaults to Read. When a file is opened for Read access the program may only read data from the file, no writing is permitted. Likewise, when a file is opened for Write, no data may be read from the file, only written. If the file already exists, the data in the file is erased. When a file is opened for Append, it is opened for write, but if the file exists, instead of destroying the data, the file pointer is positioned at the end of the file and writing begins there. Finally, the filenumber is a number from 0 to 7. It is used to identify the file for the rest of the program. Dim fname[32] as char print "Enter fname" input fname open fname for read as 1 It is possible to open the same file for Read in more than one place in the program. But for Write and Append modes you must first close the file before reopening it. Close a file When you are done with a file, you must close it. The Close command takes as its only parameter the filenumber... open "filename.dat" as 1 'do some stuff close 1 Writing to a File : Put The Put statement writes data from a variable to a file. It has three parts: filenumber, bytepos, and variable Put filenumber, [bytepos][, variable] The Put command keeps the concept of the file position. Each time data is written to the file the file position is incremented by the size of the variable in bytes. In this way, you can accurately control the data being written to the file. The first byte in the file is byte 0, the next is byte 1, etc... dim foo as int open "filename.dat" for write as 1 put 1, 0, foo ' write two bytes at the beginning of the file put 1, 100, foo ' write the same bytes at the 100th byte of the file Leaving out the variable name positions the file pointer, but does not write dim foo as int open "filename.dat" for write as 1 put 1, 0 ' position file pointer to the beginning of the file To write to the current file pointer position without specifying the value, leave out the bytepos (but remember to include the delimiting commas). Unfortunately string variables and other arrays cannot be written with the Put command. You must create a loop and write each element individually. dim a as double open "filename.dat for write as 1 input a put 1,,a ' write 8 bytes to the current location Reading from a file : Get The Get statement reads data from a file into a variable. It has three parts: filenumber, bytepos, and variable Get filenumber, [bytepos][, variable] The Get command keeps the concept of the file position. Each time data is read from the file the file position is incremented by the size of the variable in bytes. In this way, you can accurately control the data being read from the file. The first byte in the file is byte 0, the next is byte 1, etc... dim foo as int open "filename.dat" for read as 1 get 1, 0, foo ' read two bytes from the beginning of the file get 1, 100, foo ' read two different bytes from the 100th byte of the file Leaving out the variable name positions the file pointer, but does not read dim foo as int open "filename.dat" for read as 1 get 1, 0 ' position file pointer to the beginning of the file To read from the current file pointer position without specifying the value, leave out the bytepos (but remember to include the delimiting commas). dim a as double open "filename.dat for read as 1 get 1,,a ' read 8 bytes from the current location print a Printing to the file : Print # Printing to a file is possible with the print statement, which you are already familiar with. Just add a "#n" where n is the filenumber. This is an easy way to create text files. Strangely, there is no corresponding Input # command for reading data. dim a[10] as char input "your name", a open "filename.txt" for write as 1 print #1, a close 1 Chapter 19 : Role Playing Games The programs that are the most fun to write are games. Graphic games (like Super Mario Brothers) are complex programs requiring bitmapped graphics, which is covered in the guide "BitMap.doc". Other graphic games (like tic-tac-toe) are possible, but text-based games are a good starting point. B2C is well suited to writing all-text role-playing games (RPGs). A role-playing game is one where you act as a character in a world created by the computer. You can interact with objects in that world and move from place to place. I will present a simple role-playing game using a generic approach. There are many ways to write RPGs, so you should experiment and find the one that makes most sense to you. The first step in creating a RPG is deciding what your universe will be like. Is your setting in outer space? Or the deep sea? What is your experience level? Are you an expert spy? Or a novice cowboy? What is your goal in the adventure? Are you trying to get to the end of a maze? Or are you attempting to collect all the Dragon Balls? Regardless of the subject matter, a good RPG tells a story, and the more detailed your descriptions of the adventure, the more interested your user will be and the more exciting your game will be. Once you have decided on a universe, make a map of the universe. Make a box for each room and a line with an arrow showing how to go from one room to the next. Keep it down to 5-10. Make a description for each room. Make a list of objects and decide where in universe these objects reside. Make a description for each object. Make a list of commands, like "north" to go north and "eat" to eat food. The next step is a technical one. How do you get your inputs from the user? Will you list their options and have them input a number selecting what to do? Or will you have them input text strings and discover what commands work best. The TARDIS Adventure This RPG is located in the TARDIS. It stands for Time and Relative Dimensions in Space. The RPG is based on the British TV Series "Dr. Who". The TARDIS is "dimensionally transcendental" which simply means that it is larger on the inside than on the outside. While the TARDIS is about the size of a telephone booth, it has many chambers inside. The goal of our game will be to enter the TARDIS, find the sonic screwdriver, and exit. In this game each room is a separate Function. When you enter the function a description of the room is printed. When the function exits, it returns the number of the next room to go to. This offers our program modularity. Rather than a linear adventure that runs from the top of the program to the bottom, the user can wander from room to room and even get caught in a trap between rooms. There are several tricks in this program. One trick is that the return value from each room is an integer describing the next room to visit. Using this method you can rewrite the adventure by changing descriptions and the return rooms. Another trick is "parsing". I create a variable with the value of the lettername of that variable. (eg: a=97). When I parse I check each letter in the "verb" against the variable. So, for "eat" I check verb[0]=e and verb[1]=a and verb[2]=t as well as verb[3]=0 (null terminator). I allow you to carry 2 objects (one in each hand). And you can drop only 1 object in each room. The only commands are : Command Meaning Description n go north e go east s go south w go west I Inventory Lists all the objects you are carrying eat eat something increase your energy take take something move an object from right hand to left hand and pick up something in your right hand. do nothing if hands full drop drop something drop something from your left hand move other object from right hand to left hand. cannot drop if room is full DO THIS Execute the command "build tardis.bld". Download the tardis.app file to the cybiko. Appendix 1 : Command Summary {something} = optional DIM var{[dimension]} {as type} Dimension - number of objects in array type=char, int, long, double dimension a variable INPUT {"prompt",} var Var - variable to receive input Prompt - prompt string Receives input from the keyboard and puts it in a variable PRINT {obj, ...} Obj - a variable or expression or quoted string Puts text output on the screen. The screen is about 23 chars x7 lines var = exp Var - a variable Exp - some arithmetic expression Assignment 'comment Comment Everything after the ' is ignored FOR var = from-exp TO to-exp {STEP exp} Var - variable From-exp - starting value To-exp - ending value Step-exp - increment Begin a loop with variable var changing value throughout NEXT Increment the var by to-exp and continue execution at the FROM statement IF exp1 cond exp2 THEN Exp1,exp2 - expressions to be compared Cond - conditional =,<,<=,>,>=, and, or but you cannot compare strings Conditinal command if true, executes all statements down to the next ELSEIF, ELSE, and END IF. ELSE If the IF cond fails then each command until the ENDIF is executed ELSEIF exp1 cond exp2 THEN Exp1, exp2 - expressions Cond - conditional =, <, <=, >, >=, and, or But you cannot compare strings If the IF cond fails and the ELSEIF cond is true then all commands until the END IF or ELSE are executed SUB routine-name {(parameter, ...)} Parameter={BYREF|BYVAL} var {AS type} Routine-name is the name of the subroutine Parameter is a dim-like statement No arrays are allowed. BYREF indicates passing by reference BYVAL indicates pasing by value. Type is char, int,long, double Creates a subroutine which includes all commands up to the END SUB command EXIT SUB Exit the subroutine before reaching the END SUB command END SUB End of the subroutine FUNCTION routine-name {(parameter,...)} as type Parameter={BYREF|BYVAL} var {AS type} Routine-name is the name of the function which returns a value Parameter is a dim-like statement No arrays are allowed. BYREF indicates passing by reference BYVAL indicates pasing by value. Type is char, int,long, double Creates a function which includes all commands up to the END SUB command. Declare the value of the returned function by setting the name of the function to a value Routine-name = exp EXIT FUNCTION Exit the function before reaching the END FUNCTION command END FUNCTION End of the FUNCTION OPEN pathname {FOR mode} AS filnumber Mode = {READ|WRITE|APPEND} Pathname=string of a file name Filenumber= value from 0 to 65535 Mode=access mode Opens a file for access. Note that opening for read destroys old content. File writing is constrained to 23KB CLOSE {filenumber} Filenunber = value from 0 to 65535 Closes a file. Specifying no filennumber closes all files currently open PUT filenumber, {bytepos},{var} Bytepos - position in the file to write to Var - variable to write Writes a var to a file at bytepos. If bytepos is omitted the var is written to the current pos. if the var is ommitted the file is positioned at the pos and no var is written GET filenumber, {bytepos},{var} Bytepos - position in the file to read from Var - variale to read into Reads a var from a file at bytepos. If bytepos is omitted the vari is read from the current pos. if the var is omitted the file is positioned at the pos and no var is read. PRINT #filemumber, (obj...) Filenumber - the file to write to Obj - a variable or expression or quoted string Puts text output to the file specified by filenumber CLS Clear the screen Paper n N - the color of the paper (backgrond) Can be one of four values; 0=white, 1=light gray, 2=dark gray, 3=black Paint the screen the color 'n' Ink n N - the color of the paper (backgrond) Can be one of four values; 0=white, 1=light gray, 2=dark gray, 3=black Set the color of text, lines, and points Point x,y X - the x coordinate (-43 to +43) Y - the y coordinate (-80 to +80) Set a single pixe on the display In the current ink color Line x0,y0,x1,y1 X0- the left-most point X1 - the right-most point Y0 - the left most point Y1 -the right most point Draw a line on the display in he current ink color Math Functions: Sin, cos, tan, asin,ascos,atan, actan sinh,cosh,tanh, asinh,acosh,atanh,actanh sqrt, exp, log, log10,log2 pow,sqr_pow,rnd Geometric mathemetaticl fucntion Beep n N = beep command 0-silence 1-bleep 2-oh no 3-laser 4-too bad 5-computing 6-carnival 7-completed task Makes noises on the cybiko WAIT n N - number of 10ths of seconds to wait Waits 10ths of seconds KEY Acts as a variable holding the most recently type keyboard variable. See the documenation for more info WHILE exp1 cond exp2 See IF command, above Initiates a while loop that exectes allcommands up to the WEND command. IF the conditional is still true, processing continues at the WHILE command WEND Terminates the while command TYPE {decl, ...} Decl is as in DIM Creates a structured datatype END TYPE Ends a type definition PRINTXY x, y {,vals} X,Y=the coordinate where the text will display Vals are values as in print to be displayed Positions the cursor on the screen and prints the values RIGHT dest, src, len Src = source string Dest = destination string Len = the number of bytes from the end of the src string to copy to the dest string Copies bytes from the right-hand side of the src string to the left hand side of the dest string MID dest, src, start{, len} Src = source string Dest= destination String Start = where in the src string to start copying Len = number of bytes to copy Copies from the middle of the soruce string to the destination string. If the length is left out it copied all bytes from the source string start point to the end Appendix 2 : B2C Deliverables b2_clicense.txt - license agreement make.bat - script to compile programs metacopy.bat - script to copy programs README.txt - latest new about the compiler tardis.b2c - the tardis adventure source code tardis.bmp - the tardis/b2c icon tardis.help - the tardis help file tardis.inf - the tardis info file tardis.list - the list of files in the tardis.app tardis.spl - the tardis splash page bin - binaries folder b2c.exe - the b2c compiler b2cpp.exe - the b2c preprocessor b2cuser.o - the b2c runtime libarary docs - documentation folder Bitmaps.doc - tutorial on bitmaps (word format) Bitmaps.rtf - tutorial on bitmaps (rich text format) Bitmaps.txt - tutorial on bitmaps (simple text format) LanguageReference.doc - Language Reference guide (word format) LanguageReference.rtf - Language Reference guide (rich text format) LanguageReference.txt - Language Reference guide (simple text format) README.doc - quickstart guide to B2C (word format) README.rtf - quickstart guide to B2C (rich text format) README.txt - quickstart guide to B2C (simple text format) ReleaseNotes.doc - B2C Release Notes (word format) ReleaseNotes.rtf - B2C Release Notes (rich text format) ReleaseNotes.txt - B2C Release Notes (simple text format) ToDoList.doc - B2C things to do list (word format) ToDoList.rtf - B2C things to do list (rich text format) ToDoList.txt - B2C things to do list (simple text format) gfx - gfx folder gfx.app - gfx sample application gfx.b2c - gfx b2c source code gfx.bmp - gfx icon gfx.help - gfx help file gfx.inf - gfx info file gfx.list - gfx list file gfx.spl - gfx splash file img_001.bmp - lemming image img_002.bmp - lemming image img_003.bmp - lemming image img_004.bmp - lemming image img_005.bmp - lemming image make.bat - gfx make file sfx_001.mus - sound effects background for gfx inc - include folder b2cuser.h - runtime library header file sprite1 - sprite 1 example program folder make.bat - make file sprite.pic - sprite icon sprite01.bmp - sprite bitmap sprite1.b2c - sprite1 b2c source code sprite1.bmp - sprite icon sprite1.help - sprite1 help file sprite1.inf - sprite1 info file sprite1.list - sprite 1 file list sprite1.spl - sprite 1 splash text sprite2 - sprite 2 example program folder make.bat - make file sprite01.bmp - sprite bitmap sprite02.bmp - sprite bitmap sprite03.bmp - sprite bitmap sprite04.bmp - sprite bitmap sprite05.bmp - sprite bitmap sprite2.b2c - sprite2 b2c source code sprite2.bmp - sprite 2 icon sprite2.help - sprite2 help file sprite2.inf - sprite2 info file sprite2.list - sprite 2 file list sprite2.spl - sprite 2 splash text sprite3 - sprite 3 example program folder make.bat - make file sprite.mus - music file sprite01.bmp - sprite bitmap sprite02.bmp - sprite bitmap sprite03.bmp - sprite bitmap sprite04.bmp - sprite bitmap sprite05.bmp - sprite bitmap sprite3.b2c - sprite3 b2c source code sprite3.bmp - sprite 3 icon sprite3.help - sprite3 help file sprite3.inf - sprite3 info file sprite3.list - sprite 3 file list sprite3.spl - sprite 3 splash text tutorial - b2c tutorial folder ch10.b2c - chapter 10 example program ch12.b2c - chapter 12 example program ch13.b2c - chapter 13 example program ch14.b2c - chapter 14 example program ch17.b2c - chapter 17 example program ch19a.b2c - chapter 19a example program ch19b.b2c - chapter 19b example program ch20.b2c - chapter 20 example program ch21.b2c - chapter 21 example program ch22.b2c - chapter 22 example program ch6.b2c - chapter 6 example program ch7.b2c - chapter 7 example program ch8.b2c - chapter 8 example program ch9.b2c - chapter 9 example program B2C2.book - B2C2 tutorial in run reader format B2C2.doc - B2C2 tutorial in word format B2C2.rtf - B2C2 tutorial in rich text format B2C2.txt - B2C2 tutorial in simple text format tardis.b2c - tardis adventure program Learning to Program with the 3/13/2001 Cybiko Handheld Computer Using B2C 48/49