0% found this document useful (0 votes)
103 views778 pages

HODBProVol1 PDF

Uploaded by

DavidSmith
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
103 views778 pages

HODBProVol1 PDF

Uploaded by

DavidSmith
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 778

Hands On DarkBASIC Pro

Volume 1
A Self-Study Guide to Games Programming

Alistair Stewart

Digital Skills
Milton
Barr
Girvan
Ayrshire
KA26 9TY

www.digital-skills.co.uk
Copyright © Alistair Stewart 2005

All rights reserved.

No part of this work may be reproduced or used in any form


without the written permission of the author.

Although every effort has been made to ensure accuracy, the


author and publisher accept neither liability nor responsibility
for any loss or damage arising from the information in this book.

All brand names and product names are trademarks of their respective
companies and have been capitalised throughout the text.

DarkBASIC Professional is produced by The Game Creators Ltd

Cover Design by Neil King 2007

Printed September 2005


2nd Printing November 2005
3rd Printing January 2006
4th Printing November 2006
5th Printing February 2007
6th Printing September 2007
7th Printing February 2008
8th Printing September 2009 (with corrections)
9th Printing July 2010 (with corrections)

Title : Hands On DarkBASIC Pro Volume 1

ISBN : 1-874107-08-4
ISBN-13 978-1-874107-08-8

Other Titles Available:

Hands On DarkBASIC Pro Volume 2


Hands On Pascal
Hands On C++
Hands On Java
Hands On XHTML
Table Of Contents
Chapter 1 Designing Algorithms
Designing Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2
Following Instructions . . . . . . . . . . . . . . . . . . . . . . . . . .2
Control Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . .3
Sequence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3
Selection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4
Complex Conditions . . . . . . . . . . . . . . . . . . . . . . . . .9
Iteration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
Operations on Data . . . . . . . . . . . . . . . . . . . . . . . . 22
Levels of Detail . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
Checking for Errors . . . . . . . . . . . . . . . . . . . . . . . . . . 28
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34

Chapter 2 Starting DarkBASIC Pro


Programming a Computer . . . . . . . . . . . . . . . . . . . . . . . . . 38
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
The Compilation Process . . . . . . . . . . . . . . . . . . . . . . . . 38
Starting DarkBASIC Pro . . . . . . . . . . . . . . . . . . . . . . . . . . 40
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
DarkBASIC Pro Files . . . . . . . . . . . . . . . . . . . . . . . . . . 40
Getting Started with DarkBASIC . . . . . . . . . . . . . . . . . . . . 41
First Start-Up . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Subsequent Start-Ups . . . . . . . . . . . . . . . . . . . . . . . 41
Specifying a Project . . . . . . . . . . . . . . . . . . . . . . . . 41
A First Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Saving Your Project . . . . . . . . . . . . . . . . . . . . . . . . 44
First Statements in DarkBASIC Pro . . . . . . . . . . . . . . . . . . . . 45
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
Ending a Program . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
The END Statement . . . . . . . . . . . . . . . . . . . . . . . . 45
The WAIT KEY Statement . . . . . . . . . . . . . . . . . . . . . 45
Adding Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
Outputting to the Screen . . . . . . . . . . . . . . . . . . . . . . . . . . 48
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
The PRINT Statement . . . . . . . . . . . . . . . . . . . . . . . 48
Positioning Text on the Screen . . . . . . . . . . . . . . . . . . . . . 51
The SET CURSOR Statement . . . . . . . . . . . . . . . . . . . 51
The TEXT Statement . . . . . . . . . . . . . . . . . . . . . . . 52
The CENTER TEXT Command . . . . . . . . . . . . . . . . . . 53
Changing the Output Font . . . . . . . . . . . . . . . . . . . . . . . 54
The SET TEXT FONT Statement . . . . . . . . . . . . . . . . . 54
The SET TEXT SIZE Statement . . . . . . . . . . . . . . . . . . 55
The SET TEXT TO Statement . . . . . . . . . . . . . . . . . . . 55
Changing Colours . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
How Colours are Displayed . . . . . . . . . . . . . . . . . . . 56
The RGB Statement . . . . . . . . . . . . . . . . . . . . . . . . 57
The INK Statement . . . . . . . . . . . . . . . . . . . . . . . . . 58
The SET TEXT OPAQUE Statement . . . . . . . . . . . . . . . 60
The SET TEXT TRANSPARENT Statement . . . . . . . . . . . . 60
The CLS Statement . . . . . . . . . . . . . . . . . . . . . . . . 61
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
Some Display Techniques . . . . . . . . . . . . . . . . . . . . . . . . . 64
Screen Resolution . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
The SET DISPLAY MODE Statement . . . . . . . . . . . . . . . 64
Choosing a Text Font . . . . . . . . . . . . . . . . . . . . . . . . . 65
Erasing Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
Shadow Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
Embossed Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69

Chapter 3 Data
Program Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
Integer Variables . . . . . . . . . . . . . . . . . . . . . . . . . . 75
Real Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
String Variables . . . . . . . . . . . . . . . . . . . . . . . . . . 76
Using Meaningful Names . . . . . . . . . . . . . . . . . . . . . 77
Naming Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
Allocating Values to Variables . . . . . . . . . . . . . . . . . . . . . . . 79
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
The Assignment Statement . . . . . . . . . . . . . . . . . . . . . . 79
Assigning a Constant . . . . . . . . . . . . . . . . . . . . . . . 79
Copying a Variable’s Value . . . . . . . . . . . . . . . . . . . . 80
Copying the Result of an Arithmetic Expression . . . . . . . . . . 80
Operator Precedence . . . . . . . . . . . . . . . . . . . . . . . . . 83
Using Parentheses . . . . . . . . . . . . . . . . . . . . . . . . . 84
Variable Range . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
String Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
The PRINT Statement Again . . . . . . . . . . . . . . . . . . . . . . 85
Other Ways to Store a Value in a Variable . . . . . . . . . . . . . . . 87
The INPUT Statement . . . . . . . . . . . . . . . . . . . . . . .87
The READ and DATA Statements . . . . . . . . . . . . . . . . .88
The RESTORE Statement . . . . . . . . . . . . . . . . . . . . .91
The Time and Date . . . . . . . . . . . . . . . . . . . . . . . . . . .91
The TIMER Statement . . . . . . . . . . . . . . . . . . . . . . .91
The GET TIME$ Statement . . . . . . . . . . . . . . . . . . . .92
The GET DATE$ Statement . . . . . . . . . . . . . . . . . . . .93
Generating Random Numbers . . . . . . . . . . . . . . . . . . . . .93
The RND Statement . . . . . . . . . . . . . . . . . . . . . . . .93
The RANDOMIZE Statement . . . . . . . . . . . . . . . . . . .94
Structured English and Programs . . . . . . . . . . . . . . . . . . .95
Using Variables to Store Colour Values . . . . . . . . . . . . . . . .96
Named Constants . . . . . . . . . . . . . . . . . . . . . . . . . . .96
Testing Sequential Code . . . . . . . . . . . . . . . . . . . . . . . .97
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .98
Determining Current Settings . . . . . . . . . . . . . . . . . . . . . . . 100
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
Screen Settings . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
The SCREEN HEIGHT Statement . . . . . . . . . . . . . . . . 100
The SCREEN WIDTH Statement . . . . . . . . . . . . . . . . 100
The SCREEN DEPTH Statement . . . . . . . . . . . . . . . . 101
Colour Components . . . . . . . . . . . . . . . . . . . . . . . . . 101
The RGBR Statement . . . . . . . . . . . . . . . . . . . . . . 101
The RGBG Statement . . . . . . . . . . . . . . . . . . . . . . 102
The RGBB Statement . . . . . . . . . . . . . . . . . . . . . . 102
Text Settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
The TEXT BACKGROUND TYPE Statement . . . . . . . . . . 103
The TEXT STYLE Statement . . . . . . . . . . . . . . . . . . 103
The TEXT SIZE Statement . . . . . . . . . . . . . . . . . . . 104
The TEXT FONT$ Statement . . . . . . . . . . . . . . . . . . 104
The TEXT WIDTH Statement . . . . . . . . . . . . . . . . . . 104
The TEXT HEIGHT Statement . . . . . . . . . . . . . . . . . . 105
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107

Chapter 4 Selection
Binary Selection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
The IF Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
Condition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
Compound Conditions - the AND and OR Operators . . . . . . 116
The NOT Operator . . . . . . . . . . . . . . . . . . . . . . . . 118
ELSE - Creating Two Alternative Actions . . . . . . . . . . . . 119
The Other IF Statement . . . . . . . . . . . . . . . . . . . . . . . 120
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
Multi-Way Selection . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
Nested IF Statements . . . . . . . . . . . . . . . . . . . . . . . . 122
The SELECT Statement . . . . . . . . . . . . . . . . . . . . . . . 124
Testing Selective Code . . . . . . . . . . . . . . . . . . . . . . . . 127
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130

Chapter 5 Iteration
Iteration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
The WHILE .. ENDWHILE Construct . . . . . . . . . . . . . . . . . 134
The REPEAT .. UNTIL Construct . . . . . . . . . . . . . . . . . . 136
The FOR.. NEXT Construct . . . . . . . . . . . . . . . . . . . . . 138
Finding the Smallest Value in a List of Values . . . . . . . . . . 142
Using FOR with READ and DATA . . . . . . . . . . . . . . . . 144
The EXIT Statement . . . . . . . . . . . . . . . . . . . . . . . 145
The DO .. LOOP Construct . . . . . . . . . . . . . . . . . . . . . . 146
The WAIT milliseconds Statement . . . . . . . . . . . . . . . . 147
The SLEEP Statement . . . . . . . . . . . . . . . . . . . . . . 147
Nested Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
Nested FOR Loops . . . . . . . . . . . . . . . . . . . . . . . 149
Testing Iterative Code . . . . . . . . . . . . . . . . . . . . . . . . 150
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153

Chapter 6 Drawing Statements


Drawing On The Screen . . . . . . . . . . . . . . . . . . . . . . . . . 160
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
Basic Drawing Commands . . . . . . . . . . . . . . . . . . . . . . 160
The DOT Statement . . . . . . . . . . . . . . . . . . . . . . . 160
The POINT Statement . . . . . . . . . . . . . . . . . . . . . . 161
The LINE Statement . . . . . . . . . . . . . . . . . . . . . . . 162
The BOX Statement . . . . . . . . . . . . . . . . . . . . . . . 163
The CIRCLE Statement . . . . . . . . . . . . . . . . . . . . . 164
The ELLIPSE Statement . . . . . . . . . . . . . . . . . . . . . 165
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166
Demonstrating Basic Shapes . . . . . . . . . . . . . . . . . . . . . . . 167
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167
A First Look at Animation . . . . . . . . . . . . . . . . . . . . . . . . 169
Basic Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
How to Remove an Object from the Screen . . . . . . . . . . . . . 169
How to Move an Object . . . . . . . . . . . . . . . . . . . . . . . 170
Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171
Chapter 7 Modular Programming
Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176
Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176
Designing a Function . . . . . . . . . . . . . . . . . . . . . . . 176
Coding a Function . . . . . . . . . . . . . . . . . . . . . . . . 177
Calling a Function . . . . . . . . . . . . . . . . . . . . . . . . 177
Another Example . . . . . . . . . . . . . . . . . . . . . . . . . 179
Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
Pre-conditions . . . . . . . . . . . . . . . . . . . . . . . . . . 182
The EXITFUNCTION Statement . . . . . . . . . . . . . . . . . 182
Return Types . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
Local Variables . . . . . . . . . . . . . . . . . . . . . . . . . . 186
Global Variables . . . . . . . . . . . . . . . . . . . . . . . . . 187
Designing Routines . . . . . . . . . . . . . . . . . . . . . . . . . . 188
Specifying a Post-Condition . . . . . . . . . . . . . . . . . . . 188
The DrawTextLine Mini-Spec . . . . . . . . . . . . . . . . . . 188
Creating Modular Software . . . . . . . . . . . . . . . . . . . . . . 191
Top-Down Programming . . . . . . . . . . . . . . . . . . . . . . . 195
Bottom-Up Programming . . . . . . . . . . . . . . . . . . . . . . . 197
Structure Diagrams . . . . . . . . . . . . . . . . . . . . . . . . . . 198
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199
Subroutines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
Creating a Subroutine . . . . . . . . . . . . . . . . . . . . . . . . 201
Calling a Subroutine . . . . . . . . . . . . . . . . . . . . . . . . . 202
The GOSUB Statement . . . . . . . . . . . . . . . . . . . . . 202
Variables in a Subroutine . . . . . . . . . . . . . . . . . . . . 202
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204

Chapter 8 String Functions


Standard String Functions . . . . . . . . . . . . . . . . . . . . . . . . 210
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210
String Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . 210
The LEN Statement . . . . . . . . . . . . . . . . . . . . . . . 210
The UPPER$ Statement . . . . . . . . . . . . . . . . . . . . . 211
The LOWER$ Statement . . . . . . . . . . . . . . . . . . . . 212
The LEFT$ Statement . . . . . . . . . . . . . . . . . . . . . . 212
The RIGHT$ Statement . . . . . . . . . . . . . . . . . . . . . 213
The MID$ Statement . . . . . . . . . . . . . . . . . . . . . . . 213
The ASC Statement . . . . . . . . . . . . . . . . . . . . . . . 214
The CHR$ Statement . . . . . . . . . . . . . . . . . . . . . . 215
The STR$ Statement . . . . . . . . . . . . . . . . . . . . . . 215
The VAL Statement . . . . . . . . . . . . . . . . . . . . . . . 216
The SPACE$ Statement . . . . . . . . . . . . . . . . . . . . . 217
The BIN$ Statement . . . . . . . . . . . . . . . . . . . . . . . 217
The HEX$ Statement . . . . . . . . . . . . . . . . . . . . . . 218
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218
User-Defined String Functions . . . . . . . . . . . . . . . . . . . . . . 220
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220
Creating New String Functions . . . . . . . . . . . . . . . . . . . . 220
The Pos() Function . . . . . . . . . . . . . . . . . . . . . . . . 220
The Occurs() Function . . . . . . . . . . . . . . . . . . . . . . 221
The Insert$() Function . . . . . . . . . . . . . . . . . . . . . . 221
The Delete$() Function . . . . . . . . . . . . . . . . . . . . . . 222
The Replace$() Function . . . . . . . . . . . . . . . . . . . . . 222
The Copy$() Function . . . . . . . . . . . . . . . . . . . . . . 222
Using Your Routines in Other Programs . . . . . . . . . . . . . . . 223
The #INCLUDE Statement . . . . . . . . . . . . . . . . . . . . 223
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225
Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227

Chapter 9 Hangman
Creating a First Game . . . . . . . . . . . . . . . . . . . . . . . . . . 230
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230
The Rules of the Game . . . . . . . . . . . . . . . . . . . . . . . . 230
What Part the Computer Plays in the Game . . . . . . . . . . . . . 230
Designing the Screen Layout . . . . . . . . . . . . . . . . . . . . . 231
Game Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
Game Logic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232
Game Documentation . . . . . . . . . . . . . . . . . . . . . . . . 233
Implementing the Design . . . . . . . . . . . . . . . . . . . . . . . 237
Adding InitialiseGame() . . . . . . . . . . . . . . . . . . . . . 238
Adding ThinkOfWord() . . . . . . . . . . . . . . . . . . . . . . 239
Adding DrawInitialScreen() . . . . . . . . . . . . . . . . . . . . 241
Adding GetGuess() . . . . . . . . . . . . . . . . . . . . . . . 243
Adding CheckForLetter() . . . . . . . . . . . . . . . . . . . . . 247
Adding DrawLetter() . . . . . . . . . . . . . . . . . . . . . . . 248
Adding AddToHangedMan() . . . . . . . . . . . . . . . . . . . 249
Adding WordGuessed() . . . . . . . . . . . . . . . . . . . . . 249
Adding HangedManComplete() . . . . . . . . . . . . . . . . . 249
Adding GameOver() . . . . . . . . . . . . . . . . . . . . . . . 249
Keeping a Test Log . . . . . . . . . . . . . . . . . . . . . . . . . . 250
Flaws in the Game . . . . . . . . . . . . . . . . . . . . . . . . . . 250
Omissions from the Code . . . . . . . . . . . . . . . . . . . . 250
Deviating from the Original Specifications . . . . . . . . . . . . 251
Final Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 252
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 252
Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253

Chapter 10 Arrays
Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258
Creating Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259
The DIM Statement . . . . . . . . . . . . . . . . . . . . . . . 259
Accessing Array Elements . . . . . . . . . . . . . . . . . . . . . . 260
Variable Subscripts . . . . . . . . . . . . . . . . . . . . . . . 261
Basic Algorithms that Use Arrays . . . . . . . . . . . . . . . . . . 264
Calculating the Sum of the Values in an Array . . . . . . . . . . 264
Finding the Smallest Value in an Array . . . . . . . . . . . . . 265
Searching For a Value in an Array . . . . . . . . . . . . . . . . 266
Keeping an Array’s Values in Order . . . . . . . . . . . . . . . 267
Using an Array for Counting . . . . . . . . . . . . . . . . . . . 269
Associating Numbers with Strings . . . . . . . . . . . . . . . . 270
Card Shuffling . . . . . . . . . . . . . . . . . . . . . . . . . . 271
Choosing a Set of Unique Values . . . . . . . . . . . . . . . . 273
Dynamic Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . 275
The UNDIM Statement . . . . . . . . . . . . . . . . . . . . . . 275
Using Arrays in a Game . . . . . . . . . . . . . . . . . . . . . . . 276
Multi-Dimensional Arrays . . . . . . . . . . . . . . . . . . . . . . . 276
Two Dimensional Arrays . . . . . . . . . . . . . . . . . . . . . 276
Inputting Values to a 2D Array . . . . . . . . . . . . . . . . . . 277
Even More Dimensions . . . . . . . . . . . . . . . . . . . . . 277
Arrays and Functions . . . . . . . . . . . . . . . . . . . . . . . . . 278
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278
Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279

Chapter 11 Bull and Touch


Bull and Touch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284
The Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284
The Screen Layout . . . . . . . . . . . . . . . . . . . . . . . . . . 284
Game Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285
Game Logic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285
Game Documentation . . . . . . . . . . . . . . . . . . . . . . . . 285
Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 292

Chapter 12 Advanced Data Types and Operators


Data Storage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298
Declaring Variables . . . . . . . . . . . . . . . . . . . . . . . . . . 298
Boolean Variables . . . . . . . . . . . . . . . . . . . . . . . . 299
Type Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . 300
The TYPE Definition . . . . . . . . . . . . . . . . . . . . . . . 300
Declaring Variables of a Defined Type . . . . . . . . . . . . . . 301
Accessing the Fields in a Composite Variable . . . . . . . . . . 302
Nested Record Structures . . . . . . . . . . . . . . . . . . . . 303
Arrays of Records . . . . . . . . . . . . . . . . . . . . . . . . . . 304
Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
The ARRAY INSERT AT BOTTOM Statement . . . . . . . . . 306
The ARRAY INSERT AT TOP Statement . . . . . . . . . . . . 308
The ARRAY INSERT AT ELEMENT Statement . . . . . . . . . 308
The ARRAY COUNT Statement . . . . . . . . . . . . . . . . . 309
The EMPTY ARRAY Statement . . . . . . . . . . . . . . . . . 310
The ARRAY DELETE ELEMENT Statement . . . . . . . . . . 310
The NEXT ARRAY INDEX Statement . . . . . . . . . . . . . . 311
The PREVIOUS ARRAY INDEX Statement . . . . . . . . . . . 314
The ARRAY INDEX TO TOP Statement . . . . . . . . . . . . . 314
The ARRAY INDEX TO BOTTOM Statement . . . . . . . . . . 314
The ARRAY INDEX VALID Statement . . . . . . . . . . . . . . 315
Queues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316
The ADD TO QUEUE Statement . . . . . . . . . . . . . . . . 318
The REMOVE FROM QUEUE Statement . . . . . . . . . . . . 319
The ARRAY INDEX TO QUEUE Statement . . . . . . . . . . . 319
Stacks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 320
The ADD TO STACK Statement . . . . . . . . . . . . . . . . . 320
The REMOVE FROM STACK Statement . . . . . . . . . . . . 321
The ARRAY INDEX TO STACK Statement . . . . . . . . . . . 321
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322
Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322
Queues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323
Stacks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323
Data Manipulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . 324
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 324
Other Number Systems . . . . . . . . . . . . . . . . . . . . . . . 324
Incrementing and Decrementing . . . . . . . . . . . . . . . . . . . 325
The INC Statement . . . . . . . . . . . . . . . . . . . . . . . 325
The DEC Statement . . . . . . . . . . . . . . . . . . . . . . . 325
Shift Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . 326
The Shift Left Operator (<<) . . . . . . . . . . . . . . . . . . . 327
The Shift Right Operator (>>) . . . . . . . . . . . . . . . . . . 327
Bitwise Boolean Operators . . . . . . . . . . . . . . . . . . . . . . 328
The Bitwise NOT Operator (..) . . . . . . . . . . . . . . . . . . 328
The Bitwise AND Operator (&&) . . . . . . . . . . . . . . . . . 329
The Bitwise OR Operator (||) . . . . . . . . . . . . . . . . . . . 330
The Bitwise Exclusive OR Operator (~~) . . . . . . . . . . . . 331
A Practical Use For Bitwise Operations . . . . . . . . . . . . . 331
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 334
Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335

Chapter 13 Bitmaps
Bitmaps Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 340
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 340
Colour Palette . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341
File Size . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341
File Formats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341
Bitmaps in DarkBASIC Pro . . . . . . . . . . . . . . . . . . . . . . . . 342
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 342
The LOAD BITMAP Statement . . . . . . . . . . . . . . . . . 342
The BITMAP WIDTH Statement . . . . . . . . . . . . . . . . . 344
The BITMAP HEIGHT Statement . . . . . . . . . . . . . . . . 344
The BITMAP DEPTH Statement . . . . . . . . . . . . . . . . . 345
The SET CURRENT BITMAP Statement . . . . . . . . . . . . 345
The CREATE BITMAP Statement . . . . . . . . . . . . . . . . 346
The COPY BITMAP Statement . . . . . . . . . . . . . . . . . 347
The FLIP BITMAP Statement . . . . . . . . . . . . . . . . . . 348
The MIRROR BITMAP Statement . . . . . . . . . . . . . . . . 349
The BLUR BITMAP Statement . . . . . . . . . . . . . . . . . . 350
The FADE BITMAP Statement . . . . . . . . . . . . . . . . . . 351
Copying Only Part of a Bitmap . . . . . . . . . . . . . . . . . . . . 352
The COPY BITMAP Statement - Version 2 . . . . . . . . . . . 352
Zooming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355
Bitmap Status . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356
The BITMAP EXIST Statement . . . . . . . . . . . . . . . . . 356
The BITMAP MIRRORED Statement . . . . . . . . . . . . . . 356
The BITMAP FLIPPED Statement . . . . . . . . . . . . . . . . 357
The CURRENT BITMAP Statement . . . . . . . . . . . . . . . 357
The DELETE BITMAP Statement . . . . . . . . . . . . . . . . 357
Placing More than One Image in the Same Area . . . . . . . . . . 358
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359
Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361

Chapter 14 Video Cards and the Screen


Video Cards and the Screen . . . . . . . . . . . . . . . . . . . . . . . 364
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 364
Your Screen . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 364
The PERFORM CHECKLIST FOR DISPLAY MODES Statement 364
The CHECKLIST QUANTITY Statement . . . . . . . . . . . . 364
The CHECKLIST STRING$ Statement . . . . . . . . . . . . . 365
The CHECKLIST VALUE Statement . . . . . . . . . . . . . . . 366
The EMPTY CHECKLIST Statement . . . . . . . . . . . . . . 366
The CHECK DISPLAY MODE Statement . . . . . . . . . . . . 367
The SCREEN FPS Statement . . . . . . . . . . . . . . . . . . 368
The SCREEN INVALID Statement . . . . . . . . . . . . . . . . 369
Your Graphics Card . . . . . . . . . . . . . . . . . . . . . . . . . 370
The PERFORM CHECKLIST FOR GRAPHICS CARDS Statement . . 370

The SET GRAPHICS CARD Statement . . . . . . . . . . . . . 370


The CURRENT GRAPHICS CARD$ Statement . . . . . . . . . 371
The SCREEN TYPE Statement . . . . . . . . . . . . . . . . . 371
The SET GAMMA Statement . . . . . . . . . . . . . . . . . . 372
Using a Window . . . . . . . . . . . . . . . . . . . . . . . . . . . 373
The SET WINDOW ON Statement . . . . . . . . . . . . . . . 373
The SET WINDOW SIZE Statement . . . . . . . . . . . . . . . 373
The SET WINDOW POSITION Statement . . . . . . . . . . . . 373
The SET WINDOW LAYOUT Statement . . . . . . . . . . . . 374
The SET WINDOW TITLE Statement . . . . . . . . . . . . . . 374
The HIDE WINDOW Statement . . . . . . . . . . . . . . . . . 375
The SHOW WINDOW Statement . . . . . . . . . . . . . . . . 376
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376
Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 378

Chapter 15 File Handling


Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 380
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 380
Disk Housekeeping Statements . . . . . . . . . . . . . . . . . . . 380
The DRIVELIST Statement . . . . . . . . . . . . . . . . . . . 380
The GET DIR$ Statement . . . . . . . . . . . . . . . . . . . . 381
The CD Statement . . . . . . . . . . . . . . . . . . . . . . . . 381
The SET DIR Statement . . . . . . . . . . . . . . . . . . . . . 382
The PATH EXIST Statement . . . . . . . . . . . . . . . . . . . 383
The MAKE DIRECTORY Statement . . . . . . . . . . . . . . . 383
The DELETE DIRECTORY Statement . . . . . . . . . . . . . 384
The DIR Statement . . . . . . . . . . . . . . . . . . . . . . . 385
The DELETE FILE Statement . . . . . . . . . . . . . . . . . . 385
The COPY FILE Statement . . . . . . . . . . . . . . . . . . . 385
The MOVE FILE Statement . . . . . . . . . . . . . . . . . . . 386
The FILE EXIST Statement . . . . . . . . . . . . . . . . . . . 387
The RENAME FILE Statement . . . . . . . . . . . . . . . . . . 387
The EXECUTE FILE Statement . . . . . . . . . . . . . . . . . 388
The FIND FIRST Statement . . . . . . . . . . . . . . . . . . . 389
The FIND NEXT Statement . . . . . . . . . . . . . . . . . . . 389
The GET FILE NAME$ Statement . . . . . . . . . . . . . . . . 389
The GET FILE DATE$ Statement . . . . . . . . . . . . . . . . 390
The GET FILE CREATION$ Statement . . . . . . . . . . . . . 390
The GET FILE TYPE Statement . . . . . . . . . . . . . . . . . 390
The FILE SIZE Statement . . . . . . . . . . . . . . . . . . . . 392
The WINDIR$ Statement . . . . . . . . . . . . . . . . . . . . 392
The APPNAME$ Statement . . . . . . . . . . . . . . . . . . . 392
Using Data Files . . . . . . . . . . . . . . . . . . . . . . . . . . . 393
The OPEN TO WRITE Statement . . . . . . . . . . . . . . . . 393
The WRITE Statement . . . . . . . . . . . . . . . . . . . . . . 394
The CLOSE FILE Statement . . . . . . . . . . . . . . . . . . . 394
The WRITE FILE Statement . . . . . . . . . . . . . . . . . . . 397
The OPEN TO READ Statement . . . . . . . . . . . . . . . . 397
The READ Statement . . . . . . . . . . . . . . . . . . . . . . 398
The READ FILE Statement . . . . . . . . . . . . . . . . . . . 399
Random Access and File Updating . . . . . . . . . . . . . . . . . 400
The SKIP BYTES Statement . . . . . . . . . . . . . . . . . . . 400
The READ BYTE FROM FILE Statement . . . . . . . . . . . . 401
The WRITE BYTE TO FILE Statement . . . . . . . . . . . . . 402
Pack Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403
The WRITE FILEBLOCK Statement . . . . . . . . . . . . . . . 403
The WRITE DIRBLOCK Statement . . . . . . . . . . . . . . . 404
The READ FILEBLOCK Statement . . . . . . . . . . . . . . . 405
The READ DIRBLOCK Statement . . . . . . . . . . . . . . . . 406
Creating an Empty File . . . . . . . . . . . . . . . . . . . . . . . . 407
The MAKE FILE Statement . . . . . . . . . . . . . . . . . . . 407
Arrays and Files . . . . . . . . . . . . . . . . . . . . . . . . . . . 408
The SAVE ARRAY Statement . . . . . . . . . . . . . . . . . . 408
The LOAD ARRAY Statement . . . . . . . . . . . . . . . . . . 409
Checklists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 410
The PERFORM CHECKLIST FOR DRIVES Statement . . . . . 410
The PERFORM CHECKLIST FOR FILES Statement . . . . . . 410
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411
Writing to a Data File . . . . . . . . . . . . . . . . . . . . . . . 412
Reading from a Data File . . . . . . . . . . . . . . . . . . . . 412
Random Access . . . . . . . . . . . . . . . . . . . . . . . . . 412
Pack Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . 412
Arrays and Files . . . . . . . . . . . . . . . . . . . . . . . . . 413
Checklists . . . . . . . . . . . . . . . . . . . . . . . . . . . . 413
Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 414

Chapter 16 Handling Music Files


Handling Music Files . . . . . . . . . . . . . . . . . . . . . . . . . . . 420
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 420
Playing a Sound File . . . . . . . . . . . . . . . . . . . . . . . . . 420
The LOAD MUSIC Statement . . . . . . . . . . . . . . . . . . 420
The PLAY MUSIC Statement . . . . . . . . . . . . . . . . . . 421
The LOOP MUSIC Statement . . . . . . . . . . . . . . . . . . 421
The PAUSE MUSIC Statement . . . . . . . . . . . . . . . . . 422
The RESUME MUSIC Statement . . . . . . . . . . . . . . . . 422
The STOP MUSIC Statement . . . . . . . . . . . . . . . . . . 423
The SET MUSIC SPEED Statement . . . . . . . . . . . . . . . 423
The SET MUSIC VOLUME Statement . . . . . . . . . . . . . . 424
The DELETE MUSIC Statement . . . . . . . . . . . . . . . . . 424
Retrieving Music File Data . . . . . . . . . . . . . . . . . . . . . . 425
The MUSIC EXIST Statement . . . . . . . . . . . . . . . . . . 425
The MUSIC PLAYING Statement . . . . . . . . . . . . . . . . 425
The MUSIC LOOPING Statement . . . . . . . . . . . . . . . . 426
The MUSIC PAUSED Statement . . . . . . . . . . . . . . . . 426
The MUSIC VOLUME Statement . . . . . . . . . . . . . . . . 427
The MUSIC SPEED Statement . . . . . . . . . . . . . . . . . 428
Playing Multiple Music Files . . . . . . . . . . . . . . . . . . . . . 429
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 429
Playing CDs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 431
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 431
CD Control Statements . . . . . . . . . . . . . . . . . . . . . . . . 431
The LOAD CDMUSIC Statement . . . . . . . . . . . . . . . . 431
The GET NUMBER OF CD TRACKS Statement . . . . . . . . 432
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 433
Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 434

Chapter 17 Displaying Video Files


Displaying Video Files . . . . . . . . . . . . . . . . . . . . . . . . . . 436
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 436
Playing Video Files . . . . . . . . . . . . . . . . . . . . . . . . . . 436
The LOAD ANIMATION Statement . . . . . . . . . . . . . . . 436
The PLAY ANIMATION Statement . . . . . . . . . . . . . . . 437
The LOOP ANIMATION Statement . . . . . . . . . . . . . . . 439
The PAUSE ANIMATION Statement . . . . . . . . . . . . . . 440
The RESUME ANIMATION Statement . . . . . . . . . . . . . 441
The STOP ANIMATION Statement . . . . . . . . . . . . . . . 441
The PLACE ANIMATION Statement . . . . . . . . . . . . . . . 442
The SET ANIMATION SPEED Statement . . . . . . . . . . . . 443
The SET ANIMATION VOLUME Statement . . . . . . . . . . . 444
The DELETE ANIMATION Statement . . . . . . . . . . . . . . 444
Retrieving Video Data . . . . . . . . . . . . . . . . . . . . . . . . 444
The ANIMATION EXIST Statement . . . . . . . . . . . . . . . 444
The ANIMATION POSITION Statement . . . . . . . . . . . . . 445
The ANIMATION WIDTH Statement . . . . . . . . . . . . . . . 446
The ANIMATION HEIGHT Statement . . . . . . . . . . . . . . 446
The ANIMATION PLAYING Statement . . . . . . . . . . . . . 447
The ANIMATION LOOPING Statement . . . . . . . . . . . . . 447
The ANIMATION PAUSED Statement . . . . . . . . . . . . . . 447
The ANIMATION VOLUME Statement . . . . . . . . . . . . . 449
The ANIMATION SPEED Statement . . . . . . . . . . . . . . 449
Playing Multiple Videos . . . . . . . . . . . . . . . . . . . . . . . . 450
Playing Sound . . . . . . . . . . . . . . . . . . . . . . . . . . . . 450
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 450
Playing DVDs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 452
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 452
DVD Handling Statements . . . . . . . . . . . . . . . . . . . . . . 452
The LOAD DVD ANIMATION Statement . . . . . . . . . . . . 452
The TOTAL DVD CHAPTERS Statement . . . . . . . . . . . . 452
The SET DVD CHAPTER Statement . . . . . . . . . . . . . . 453
A Sample Program . . . . . . . . . . . . . . . . . . . . . . . . . . 453
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 454
Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 455

Chapter 18 Accessing the Keyboard


Accessing the Keyboard . . . . . . . . . . . . . . . . . . . . . . . . . 458
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 458
Reading a Key . . . . . . . . . . . . . . . . . . . . . . . . . . . . 458
The INKEY$ Statement . . . . . . . . . . . . . . . . . . . . . 458
Checking the Arrow Keys . . . . . . . . . . . . . . . . . . . . . . 460
The UPKEY Statement . . . . . . . . . . . . . . . . . . . . . 460
The DOWNKEY Statement . . . . . . . . . . . . . . . . . . . 460
The LEFTKEY Statement . . . . . . . . . . . . . . . . . . . . 461
The RIGHTKEY Statement . . . . . . . . . . . . . . . . . . . 461
Checking For Other Special Keys . . . . . . . . . . . . . . . . . . 461
Scan Codes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 462
The SCANCODE Statement . . . . . . . . . . . . . . . . . . . 462
The KEYSTATE Statement . . . . . . . . . . . . . . . . . . . 463
The ENTRY$ Statement . . . . . . . . . . . . . . . . . . . . . 466
The CLEAR ENTRY BUFFER Statement . . . . . . . . . . . . 467
The SUSPEND FOR KEY Statement . . . . . . . . . . . . . . 467
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 468
Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 469

Chapter 19 Mathematical Functions


Mathematical Functions . . . . . . . . . . . . . . . . . . . . . . . . . 472
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 472
Coordinates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 472
Mathematical Functions in DarkBASIC Pro . . . . . . . . . . . . . 473
The COS Statement . . . . . . . . . . . . . . . . . . . . . . . 473
The SIN Statement . . . . . . . . . . . . . . . . . . . . . . . . 475
Dealing with Longer Lines . . . . . . . . . . . . . . . . . . . . 476
The SQRT Statement . . . . . . . . . . . . . . . . . . . . . . 476
The ACOS Statement . . . . . . . . . . . . . . . . . . . . . . 477
The ASIN Statement . . . . . . . . . . . . . . . . . . . . . . . 478
The TAN Statement . . . . . . . . . . . . . . . . . . . . . . . 478
The ATAN Statement . . . . . . . . . . . . . . . . . . . . . . 479
The WRAPVALUE Statement . . . . . . . . . . . . . . . . . . 481
Other Mathematical Functions . . . . . . . . . . . . . . . . . . . . 481
The ABS Statement . . . . . . . . . . . . . . . . . . . . . . . 481
The INT Statement . . . . . . . . . . . . . . . . . . . . . . . . 482
The EXP Statement . . . . . . . . . . . . . . . . . . . . . . . 483
The HCOS Statement . . . . . . . . . . . . . . . . . . . . . . 483
The HSIN Statement . . . . . . . . . . . . . . . . . . . . . . . 483
The HTAN Statement . . . . . . . . . . . . . . . . . . . . . . 484
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 484
Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 486

Chapter 20 Images
Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 488
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 488
Image Handling Statements . . . . . . . . . . . . . . . . . . . . . 488
The LOAD IMAGE Statement . . . . . . . . . . . . . . . . . . 488
The PASTE IMAGE Statement . . . . . . . . . . . . . . . . . 489
The SET IMAGE COLORKEY Statement . . . . . . . . . . . . 490
The SAVE IMAGE Statement . . . . . . . . . . . . . . . . . . 490
The DELETE IMAGE Statement . . . . . . . . . . . . . . . . . 491
The GET IMAGE Statement . . . . . . . . . . . . . . . . . . . 492
The IMAGE EXIST Statement . . . . . . . . . . . . . . . . . . 493
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 493
Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 494

Chapter 21 Sprites1
Creating and Moving Sprites . . . . . . . . . . . . . . . . . . . . . . . 496
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 496
Loading a Sprite Image . . . . . . . . . . . . . . . . . . . . . . . . 496
The SPRITE Statement . . . . . . . . . . . . . . . . . . . . . 496
Translating a Sprite . . . . . . . . . . . . . . . . . . . . . . . . . . 498
The PASTE SPRITE Statement . . . . . . . . . . . . . . . . . 498
The MOVE SPRITE Statement . . . . . . . . . . . . . . . . . 499
The ROTATE SPRITE Statement . . . . . . . . . . . . . . . . 500
How MOVE SPRITE Operates . . . . . . . . . . . . . . . . . . . . 502
Moving a Sprite’s Origin . . . . . . . . . . . . . . . . . . . . . . . 503
The OFFSET SPRITE Statement . . . . . . . . . . . . . . . . 503
Sprite Reflection . . . . . . . . . . . . . . . . . . . . . . . . . . . 505
The MIRROR SPRITE Statement . . . . . . . . . . . . . . . . 505
The FLIP SPRITE Statement . . . . . . . . . . . . . . . . . . 506
Reflecting a Tilted Sprite . . . . . . . . . . . . . . . . . . . . . 507
Sprite Background Transparency . . . . . . . . . . . . . . . . . . 507
Giving the User Control of a Sprite . . . . . . . . . . . . . . . . . . 508
Vertical Movement . . . . . . . . . . . . . . . . . . . . . . . . 508
Horizontal Movement . . . . . . . . . . . . . . . . . . . . . . 508
Rotational Movement . . . . . . . . . . . . . . . . . . . . . . 509
Free Movement . . . . . . . . . . . . . . . . . . . . . . . . . 510
Restricting Sprite Movement . . . . . . . . . . . . . . . . . . . 511
Storing the Position of the Sprite in a Record . . . . . . . . . . 512
Velocity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 512
Sprites and the PRINT Statement . . . . . . . . . . . . . . . . . . 521
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 522
Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 523

Chapter 22 Sprites 2
Changing a Sprite’s Appearance . . . . . . . . . . . . . . . . . . . . . 528
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 528
Resizing Sprites . . . . . . . . . . . . . . . . . . . . . . . . . . . 528
The SCALE SPRITE Statement . . . . . . . . . . . . . . . . . 528
The STRETCH SPRITE Statement . . . . . . . . . . . . . . . 529
The SIZE SPRITE Statement . . . . . . . . . . . . . . . . . . 530
Changing Transparency and Colour Brightness . . . . . . . . . . . 530
The SET SPRITE ALPHA Statement . . . . . . . . . . . . . . 530
The SET SPRITE DIFFUSE Statement . . . . . . . . . . . . . 531
Showing and Hiding Sprites . . . . . . . . . . . . . . . . . . . . . 532
The HIDE SPRITE Statement . . . . . . . . . . . . . . . . . . 532
The SHOW SPRITE Statement . . . . . . . . . . . . . . . . . 533
The HIDE ALL SPRITES Statement . . . . . . . . . . . . . . . 533
The SHOW ALL SPRITES Statement . . . . . . . . . . . . . . 533
Duplicating a Sprite . . . . . . . . . . . . . . . . . . . . . . . . . . 533
The CLONE SPRITE Statement . . . . . . . . . . . . . . . . . 533
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 534
Adding a Background . . . . . . . . . . . . . . . . . . . . . . . . . . . 536
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 536
Ways to Change the Background . . . . . . . . . . . . . . . . . . 536
The COLOR BACKDROP Statement . . . . . . . . . . . . . . 536
The BACKDROP ON Statement . . . . . . . . . . . . . . . . . 536
The BACKDROP OFF Statement . . . . . . . . . . . . . . . . 537
Using a Sprite as a BackGround . . . . . . . . . . . . . . . . . 537
Sprite Order . . . . . . . . . . . . . . . . . . . . . . . . . . . 538
The SET SPRITE PRIORITY Statement . . . . . . . . . . . . . 538
The SET SPRITE TEXTURE COORD Statement . . . . . . . . 539
The SET SPRITE Statement . . . . . . . . . . . . . . . . . . . 542
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 543
Retrieving Data About Sprites . . . . . . . . . . . . . . . . . . . . . . 544
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 544
Sprite Data Retrieval Statements . . . . . . . . . . . . . . . . . . 544
The SPRITE EXIST Statement . . . . . . . . . . . . . . . . . 544
The SPRITE X Statement . . . . . . . . . . . . . . . . . . . . 544
The SPRITE Y Statement . . . . . . . . . . . . . . . . . . . . 544
The SPRITE ANGLE Statement . . . . . . . . . . . . . . . . . 545
The SPRITE OFFSET X Statement . . . . . . . . . . . . . . . 545
The SPRITE OFFSET Y Statement . . . . . . . . . . . . . . . 546
The SPRITE SCALE X Statement . . . . . . . . . . . . . . . . 546
The SPRITE SCALE Y Statement . . . . . . . . . . . . . . . . 546
The SPRITE WIDTH Statement . . . . . . . . . . . . . . . . . 547
The SPRITE HEIGHT Statement . . . . . . . . . . . . . . . . 547
The SPRITE MIRRORED Statement . . . . . . . . . . . . . . 547
The SPRITE FLIPPED Statement . . . . . . . . . . . . . . . . 548
The SPRITE VISIBLE Statement . . . . . . . . . . . . . . . . 548
The SPRITE ALPHA Statement . . . . . . . . . . . . . . . . . 548
The SPRITE RED Statement . . . . . . . . . . . . . . . . . . 549
The SPRITE GREEN Statement . . . . . . . . . . . . . . . . . 549
The SPRITE BLUE Statement . . . . . . . . . . . . . . . . . . 549
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 550
Sprite Collision . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 551
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 551
Dealing With Sprite Collisions . . . . . . . . . . . . . . . . . . . . 551
The SPRITE HIT Statement . . . . . . . . . . . . . . . . . . . 551
The SPRITE COLLISION Statement . . . . . . . . . . . . . . 553
A Basic Bat and Ball Game . . . . . . . . . . . . . . . . . . . . . 553
Firing Projectiles . . . . . . . . . . . . . . . . . . . . . . . . . . . 555
The DELETE SPRITE Statement . . . . . . . . . . . . . . . . 555
The Missile Game . . . . . . . . . . . . . . . . . . . . . . . . 556
Extending the Game . . . . . . . . . . . . . . . . . . . . . . . 558
The SET SPRITE IMAGE Statement . . . . . . . . . . . . . . 559
The SPRITE IMAGE Statement . . . . . . . . . . . . . . . . . 560
Updating the Screen . . . . . . . . . . . . . . . . . . . . . . . . . 562
The SYNC ON Statement . . . . . . . . . . . . . . . . . . . . 562
The SYNC Statement . . . . . . . . . . . . . . . . . . . . . . 562
The SYNC OFF Statement . . . . . . . . . . . . . . . . . . . 563
The SYNC RATE Statement . . . . . . . . . . . . . . . . . . . 563
The FASTSYNC Statement . . . . . . . . . . . . . . . . . . . 564
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 564
Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 565

Chapter 23 Animated Sprites


Animated Sprites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 572
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 572
Setting Up the Sprite . . . . . . . . . . . . . . . . . . . . . . . . . 572
The CREATE ANIMATED SPRITE Statement . . . . . . . . . 572
The SET SPRITE FRAME Statement . . . . . . . . . . . . . . 573
The SPRITE FRAME Statement . . . . . . . . . . . . . . . . . 574
A Simple Dice Game . . . . . . . . . . . . . . . . . . . . . . . . . 575
Creating a Sprite that Really is Animated . . . . . . . . . . . . . . 578
The PLAY SPRITE Statement . . . . . . . . . . . . . . . . . . 578
Changing the Transparent Colour . . . . . . . . . . . . . . . . 579
Moving the Sprite . . . . . . . . . . . . . . . . . . . . . . . . 580
Varying the Velocity . . . . . . . . . . . . . . . . . . . . . . . 581
Multiple Asteroids . . . . . . . . . . . . . . . . . . . . . . . . 582
Controlling the Spaceship . . . . . . . . . . . . . . . . . . . . . . 584
The HandleKeyboard() Function . . . . . . . . . . . . . . . . . 584
The HandleShip() Function . . . . . . . . . . . . . . . . . . . 585
The LaunchMissile() Function . . . . . . . . . . . . . . . . . . 588
The HandleMissiles() Routine . . . . . . . . . . . . . . . . . . 590
Adding the Asteroids . . . . . . . . . . . . . . . . . . . . . . . . . 591
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 593
Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 595

Chapter 24 Sound
Mono and Stereo Sound . . . . . . . . . . . . . . . . . . . . . . . . . 604
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 604
The Basics of Loading and Playing Sounds . . . . . . . . . . . . . 604
The LOAD SOUND Statement . . . . . . . . . . . . . . . . . . 604
The PLAY SOUND Statement . . . . . . . . . . . . . . . . . . 604
The LOOP SOUND Statement . . . . . . . . . . . . . . . . . . 606
The PAUSE SOUND Statement . . . . . . . . . . . . . . . . . 607
The RESUME SOUND Statement . . . . . . . . . . . . . . . . 607
The STOP SOUND Statement . . . . . . . . . . . . . . . . . . 608
The SET SOUND SPEED Statement . . . . . . . . . . . . . . 608
The SET SOUND VOLUME Statement . . . . . . . . . . . . . 609
The CLONE SOUND Statement . . . . . . . . . . . . . . . . . 609
The DELETE SOUND Statement . . . . . . . . . . . . . . . . 610
Recording Sound . . . . . . . . . . . . . . . . . . . . . . . . . . . 611
The RECORD SOUND Statement . . . . . . . . . . . . . . . . 611
The STOP RECORDING SOUND Statement . . . . . . . . . . 611
The SAVE SOUND Statement . . . . . . . . . . . . . . . . . . 612
Retrieving Sound File Data . . . . . . . . . . . . . . . . . . . . . . 613
The SOUND EXIST Statement . . . . . . . . . . . . . . . . . 613
The SOUND PLAYING Statement . . . . . . . . . . . . . . . . 613
The SOUND LOOPING Statement . . . . . . . . . . . . . . . 614
The SOUND PAUSED Statement . . . . . . . . . . . . . . . . 614
The SOUND VOLUME Statement . . . . . . . . . . . . . . . . 616
The SOUND SPEED Statement . . . . . . . . . . . . . . . . . 616
Moving a Sound . . . . . . . . . . . . . . . . . . . . . . . . . . . 617
The SET SOUND PAN Statement . . . . . . . . . . . . . . . . 617
The SOUND PAN Statement . . . . . . . . . . . . . . . . . . 617
Playing Multiple Sound Files . . . . . . . . . . . . . . . . . . . . . 618
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 618
3D Sound Effects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 620
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 620
Loading and Playing 3D Sounds . . . . . . . . . . . . . . . . . . . 621
The LOAD 3DSOUND Statement . . . . . . . . . . . . . . . . 621
The POSITION SOUND Statement . . . . . . . . . . . . . . . 621
Controlling the Listener . . . . . . . . . . . . . . . . . . . . . . . . 622
The POSITION LISTENER Statement . . . . . . . . . . . . . . 622
The ROTATE LISTENER Statement . . . . . . . . . . . . . . 623
The SCALE LISTENER Statement . . . . . . . . . . . . . . . 623
Retrieving Data on 3D Sounds and the Listener . . . . . . . . . . . 624
The SOUND POSITION X Statement . . . . . . . . . . . . . . 624
The SOUND POSITION Y Statement . . . . . . . . . . . . . . 624
The SOUND POSITION Z Statement . . . . . . . . . . . . . . 624
The LISTENER POSITION X Statement . . . . . . . . . . . . 625
The LISTENER POSITION Y Statement . . . . . . . . . . . . 625
The LISTENER POSITION Z Statement . . . . . . . . . . . . . 625
The LISTENER ANGLE X Statement . . . . . . . . . . . . . . 625
The LISTENER ANGLE Y Statement . . . . . . . . . . . . . . 625
The LISTENER ANGLE Z Statement . . . . . . . . . . . . . . 626
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 626
Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 628

Chapter 25 2D Vectors
2D Vectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 632
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 632
A Mathematical Description of Vectors . . . . . . . . . . . . . 632
Vectors in DarkBASIC Pro . . . . . . . . . . . . . . . . . . . . 633
Creating a 2D Vector . . . . . . . . . . . . . . . . . . . . . . . . . 633
The MAKE VECTOR2 Statement . . . . . . . . . . . . . . . . 633
The SET VECTOR2 Statement . . . . . . . . . . . . . . . . . 634
The X VECTOR2 Statement . . . . . . . . . . . . . . . . . . . 635
The Y VECTOR2 Statement . . . . . . . . . . . . . . . . . . . 635
The DELETE VECTOR2 Statement . . . . . . . . . . . . . . . 636
The COPY VECTOR2 Statement . . . . . . . . . . . . . . . . 637
The MULTIPLY VECTOR2 Statement . . . . . . . . . . . . . . 638
The SCALE VECTOR2 Statement . . . . . . . . . . . . . . . . 638
The DIVIDE VECTOR2 Statement . . . . . . . . . . . . . . . . 639
The LENGTH VECTOR2 Statement . . . . . . . . . . . . . . . 639
The SQUARED LENGTH VECTOR2 Statement . . . . . . . . 640
The ADD VECTOR2 Statement . . . . . . . . . . . . . . . . . 640
The SUBTRACT VECTOR2 Statement . . . . . . . . . . . . . 643
The DOT PRODUCT VECTOR2 Statement . . . . . . . . . . . 644
The IS EQUAL VECTOR2 Statement . . . . . . . . . . . . . . 645
The MAXIMIZE VECTOR2 Statement . . . . . . . . . . . . . . 646
The MINIMIZE VECTOR2 Statement . . . . . . . . . . . . . . 647
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 648
In Mathematics . . . . . . . . . . . . . . . . . . . . . . . . . . 648
In Geometry . . . . . . . . . . . . . . . . . . . . . . . . . . . 648
In DarkBASIC Pro . . . . . . . . . . . . . . . . . . . . . . . . 648
Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 650

Chapter 26 Space Duel


Creating a Two-Player Game . . . . . . . . . . . . . . . . . . . . . . . 652
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 652
The Rules of the Game . . . . . . . . . . . . . . . . . . . . . . . . 652
Winning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 652
Basic Play . . . . . . . . . . . . . . . . . . . . . . . . . . . . 652
Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 652
The Screen Layout . . . . . . . . . . . . . . . . . . . . . . . . . . 652
Game Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 653
Game Logic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 654
Game Documentation . . . . . . . . . . . . . . . . . . . . . . . . 654
Coding the Program . . . . . . . . . . . . . . . . . . . . . . . . . 659
Adding InitialiseGame() . . . . . . . . . . . . . . . . . . . . . 660
Adding HandleKeyboard() . . . . . . . . . . . . . . . . . . . . 662
Adding HandleShip() . . . . . . . . . . . . . . . . . . . . . . . 662
Adding HandleMissiles() . . . . . . . . . . . . . . . . . . . . . 664
Adding GameOver() . . . . . . . . . . . . . . . . . . . . . . . 665
Space Duel - A Program Listing . . . . . . . . . . . . . . . . . . . . . 666
Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 672

Chapter 27 Using the Mouse


Controlling the Mouse . . . . . . . . . . . . . . . . . . . . . . . . . . 678
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 678
Waiting for a Mouse Click . . . . . . . . . . . . . . . . . . . . . . 678
The WAIT MOUSE Statement . . . . . . . . . . . . . . . . . . 678
The SUSPEND FOR MOUSE Statement . . . . . . . . . . . . 678
The MOUSECLICK Statement . . . . . . . . . . . . . . . . . . 678
The Mouse Pointer . . . . . . . . . . . . . . . . . . . . . . . . . . 680
The HIDE MOUSE Statement . . . . . . . . . . . . . . . . . . 680
The SHOW MOUSE Statement . . . . . . . . . . . . . . . . . 680
The POSITION MOUSE Statement . . . . . . . . . . . . . . . 681
The CHANGE MOUSE Statement . . . . . . . . . . . . . . . . 681
Reading the Mouse Position . . . . . . . . . . . . . . . . . . . . . 683
The MOUSEX Statement . . . . . . . . . . . . . . . . . . . . 683
The MOUSEY Statement . . . . . . . . . . . . . . . . . . . . 683
Mouse Speed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 684
The MOUSEMOVEX Statement . . . . . . . . . . . . . . . . . 684
The MOUSEMOVEY Statement . . . . . . . . . . . . . . . . . 684
The Mouse Wheel . . . . . . . . . . . . . . . . . . . . . . . . . . 685
The MOUSEZ Statement . . . . . . . . . . . . . . . . . . . . 685
The MOUSEMOVEZ Statement . . . . . . . . . . . . . . . . . 686
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 687
Mouse Handling Techniques . . . . . . . . . . . . . . . . . . . . . . . 688
Rollovers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 688
A Second Approach . . . . . . . . . . . . . . . . . . . . . . . 689
Clicking On-Screen Buttons . . . . . . . . . . . . . . . . . . . . . 690
Basic Concept . . . . . . . . . . . . . . . . . . . . . . . . . . 690
Reacting to a Button Click . . . . . . . . . . . . . . . . . . . . 691
Controlling Program Flow . . . . . . . . . . . . . . . . . . . . 693
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 694
Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 695

Chapter 28 Pelmanism
The Game of Pelmanism . . . . . . . . . . . . . . . . . . . . . . . . . 698
Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 698
The Screen Layout . . . . . . . . . . . . . . . . . . . . . . . . . . 698
Game Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 699
Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . 699
Structures Defined . . . . . . . . . . . . . . . . . . . . . . . . 699
Global Variables . . . . . . . . . . . . . . . . . . . . . . . . . 699
Game Logic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 700
The Program Code . . . . . . . . . . . . . . . . . . . . . . . . . . 700
Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . 700
Adding InitialiseGame() . . . . . . . . . . . . . . . . . . . . . 701
Adding HandleMouse() . . . . . . . . . . . . . . . . . . . . . . 703
Adding GameOver() . . . . . . . . . . . . . . . . . . . . . . . 706
Pelmanism - Program Listing . . . . . . . . . . . . . . . . . . . . . . . 707
Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 713

Chapter 29 Using a Joystick


Using a Joystick . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 716
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 716
Checking the System for a Joystick . . . . . . . . . . . . . . . . . 716
The PERFORM CHECKLIST FOR CONTROL DEVICES Statement . 716
Reading the Position of the Joystick . . . . . . . . . . . . . . . . . 717
The JOYSTICK Direction Statement . . . . . . . . . . . . . . . 717
The JOYSTICK Position Statement . . . . . . . . . . . . . . . 718
Joystick Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . 721
The JOYSTICK FIRE Statement . . . . . . . . . . . . . . . . . 721
The JOYSTICK FIRE X Statement . . . . . . . . . . . . . . . 722
The JOYSTICK SLIDER Statement . . . . . . . . . . . . . . . 723
The JOYSTICK TWIST Statement . . . . . . . . . . . . . . . . 723
The JOYSTICK HAT ANGLE Statement . . . . . . . . . . . . . 724
Feedback Effects . . . . . . . . . . . . . . . . . . . . . . . . . . . 725
The FORCE Direction Statement . . . . . . . . . . . . . . . . 726
The FORCE ANGLE Statement . . . . . . . . . . . . . . . . . 727
The FORCE NO EFFECT Statement . . . . . . . . . . . . . . 728
The FORCE AUTO CENTER Statement . . . . . . . . . . . . 728
The FORCE WATER EFFECT Statement . . . . . . . . . . . . 728
The FORCE CHAINSAW Statement . . . . . . . . . . . . . . . 729
The FORCE SHOOT Statement . . . . . . . . . . . . . . . . . 730
The FORCE IMPACT Statement . . . . . . . . . . . . . . . . 731
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 731
A Joystick-Based Game . . . . . . . . . . . . . . . . . . . . . . . . . 733
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 733
The Rules Of the Game . . . . . . . . . . . . . . . . . . . . . . . 733
The Screen Layout . . . . . . . . . . . . . . . . . . . . . . . . . . 733
The Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 733
Media Used . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 734
The Program Code . . . . . . . . . . . . . . . . . . . . . . . . . . 734
Adding InitialiseGame() . . . . . . . . . . . . . . . . . . . . . 735
Adding CreateAlien() . . . . . . . . . . . . . . . . . . . . . . . 736
Adding HandleJoystick() . . . . . . . . . . . . . . . . . . . . . 736
Adding CreateMissile() . . . . . . . . . . . . . . . . . . . . . . 736
Adding HandleAlien() . . . . . . . . . . . . . . . . . . . . . . 736
Adding WrapAlien() . . . . . . . . . . . . . . . . . . . . . . . 737
Adding HandleMissile() . . . . . . . . . . . . . . . . . . . . . 737
Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 739
Appendix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 743
The ASCII Character Set . . . . . . . . . . . . . . . . . . . . . . . 743
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 744
Acknowledgements

I would like to thank all those who helped me prepare the final draft of this book.

In particular, Virginia Marshall who proof-read the original script and Michael Kerr
who did an excellent job of checking the technical contents.

Any errors that remain are probably due to the extra few paragraphs I added after
all the proof-reading was complete!

Thanks also to The Game Creators Ltd for producing an excellent piece of software
- DarkBASIC Professional - known as DarkBASIC Pro to its friends.

Finally, thank you to every one of you who has bought this book. Any constructive
comments would be most welcome.

Email me at [email protected].
Introduction
Welcome to a book that I hope is a little different from any other you've come across.
Instead of just telling you about software design and programming, it makes you
get involved. There's plenty of work for you to do since the book is full of exercises
- most of them programming exercises - but you also get a full set of solutions, just
in case you get stuck!

Learn by Doing
The only way to become a programming expert is to practice. No one ever learned
any skill by just reading about it! Hence, this is not a text book where you can just
sit back in a passive way and read from cover to cover whilst sitting in your favourite
chair. Rather it is designed as a teaching package in which you will do most of the
work.

The tasks embedded in the text are included to test your understanding of what has
gone before and as a method of helping you retain the knowledge you have gained.
It is therefore important that you tackle each task as you come to it. Also, many of
the programming exercises are referred to, or expanded, in later pages so it is
important that you are familar with the code concerned.

What You Need


You'll obviously need a PC and a copy of DarkBASIC Pro.

You don't need any experience of programming, but knowing your bits from your
bytes and understanding binary and hexadecimal number systems would be useful.

How to Get the Most out of this Text


Experience has shown that readers derive most benefit from this material by
approaching its study in an organised way. The following strategy for study is highly
recommended:

1. Read a chapter or section through without taking notes or worrying too


much about topics that are not immediately clear to you. This will give
you an overview of the contents of that chapter/section.

2. Re-read the chapter. This time take things slowly; make notes and
summaries of the material you are reading (even if you understand the
material, making notes helps to retain the facts in your long-term
memory); re-read any parts you are unclear about.

3. Embedded in the material are a series of activities. Do each task as you


reach it (on the second reading). These activities are designed to test
your knowledge and understanding of what has gone before. Do not be
tempted to skip over them, promise to come back to them later, or
to make only a half-hearted attempt at tackling them before looking up
the answer (there are solutions at the end of each chapter). Once you
have attempted a task, look at the solution given. Often there will be
important points emphasised in the solution which will aid higher
understanding.
4. As you progress through the book, go back and re-read earlier chapters,
since you will often get something new from them as your knowledge
increases.

Language Syntax Diagrams


The text contains many syntax diagrams which give a visual representation of the
format of various statements allowed in DarkBASIC Professional. These diagrams
make no attempt to be complete, but merely act as a guide to the format most likely
to be used. The accompanying text and example should highlight the more complex
options available. Below is a typical diagram:

IF condition THEN

statement

ELSE

statement

Each tile in the diagram holds a token of the statement. Raised tiles represent fixed
terms in the statement, which must be entered exactly as shown. Sunken tiles
represent tokens whose exact value is decided by you, the programmer, but again
these values must conform to some stated rule.

ELSE
Items enclosed in brackets may be omitted if not required. In this
example we can see that ELSE and all the terms that follow may be
statement omitted.

Where one or more tokens in a diagram may be repeated indefinitely,


statement
this is shown using the arrowed line. This example shows that any
number of statements can be used so long as a colon appears between
: each statement.

Occasionally, a single line of code will have to be printed over two or more lines
Ä
because of paper width restrictions; these lines are signified by a symbol. Enter
these lines without a break when testing any of the programs in which they are used.
For example, the code

SPRITE crosshairs,(JOYSTICK X()+1000)*xpixels#,


Ä(JOYSTICK Y()+1000)*ypixels#,1

should be entered as a single line.


1

Boolean expressions
Data Variables
Designing Algorithms
Desk Checking
IF Control Structure
FOR Control Structure
REPEAT Control Structure
Stepwise Refinement
Testing
WHILE Control Structure

DarkBASIC Pro: Designing Algorithms 1


Designing Algorithms
Following Instructions
Activity 1.1

Carry out the following set of instructions in your head.

Think of a number between 1 and 10

Multiply that number by 9

Add up the individual digits of this new number


Subtract 5 from this total

Think of the letter at that position in the alphabet

Think of a country in Europe that starts with that letter

Think of a mammal that starts with the second letter of the country’s name

Think of the colour of that mammal

Congratulations! You’ve just become a human computer. You were given a set of
instructions which you have carried out (by the way, did you think of the colour
grey?).

That’s exactly what a computer does. You give it a set of instructions,the machine
carries out those instructions, and that is ALL a computer does. If some computers
seem to be able to do amazing things, that is only because someone has written an
amazingly clever set of instructions. A set of instructions designed to perform some
specific task is known as an algorithm.

There are a few points to note from the algorithm given above:

Ø There is one instruction per line


Ø Each instruction is unambiguous
Ø Each instruction is as short as possible
Activity 1.2

This time let’s see if you can devise your own algorithm.

The task you need to solve is to measure out exactly 4 litres of water. You
have two containers. Container A, if filled, will hold exactly 5 litres of water,
while container B will hold 3 litres of water. You have an unlimited supply of
water and a drain to get rid of any water you no longer need. It is not possible
to know how much water is in a container if you only partly fill it from the
A B supply.

If you managed to come up with a solution, see if you can find a second way
of measuring out the 4 litres.

As you can see, there are at least two ways to solve the problem given in Activity
1.2. Is one better than the other? Well, if we start by filling container A, the solution
needs less instructions, so that might be a good guideline at this point when choosing
which algorithm is best.

2 DarkBASIC Pro: Designing Algorithms


However, the algorithms that a computer carries out are not written in English like
the instructions shown above, but in a more stylised form using a computer
programming language. DarkBASIC Pro is one such language. The set of program
language instructions which make up each algorithm is then known as a computer
program or software.

Just as we may perform a great diversity of tasks by following different sets of


instructions, so the computer can be made to carry out any task for which a program
exists.

Computer programs are normally copied (or loaded) from a magnetic disk into the
computer’s memory and then executed (or run). Execution of a program involves
the computer performing each instruction in the program one after the other. This
it does at impressively high rates, possibly exceeding 2,000 million (or 2 billion)
instructions per second (2,000 mips).

Depending on the program being run, the computer may act as a word processor, a
database, a spreadsheet, a game, a musical instrument or one of many other
possibilities. Of course, as a programmer, you are required to design and write
computer programs rather than use them. And, more specifically, our programs in
this text will be mainly games-related; an area of programming for which
DarkBASIC Pro has been specifically designed.

Activity 1.3

1. A set of instructions that performs a specific task is known as what?

2. What term is used to describe a set of instructions used by a computer?

3. The speed of a computer is measured in what units?

Control Structures
Although writing algorithms and programming computers are certainly
complicated tasks, there are only a few basic concepts and statements which you
need to master before you are ready to start producing software. Luckily, the
concepts are already familiar to you in everyday situations. If you examine any
algorithm, no matter how complex, you will find it consists of three basic structures:

Ø Sequence where one statement follows on from another.


Ø Selection where a choice is made between two or more alternative
actions.
Ø Iteration where one or more instructions are carried out over and
over again.

These are explained in detail over the next few pages. All that is needed is to
formalise the use of these structures within an algorithm. This formalisation better
matches the structure of a computer program.

Sequence
A set of instructions designed to be carried out one after another, beginning at the
first and continuing, without omitting any, until the final instruction is completed,

DarkBASIC Pro: Designing Algorithms 3


is known as a sequence. For example, instructions on how to play Monopoly might
begin with the sequence:

Choose your playing piece


Place your piece on the GO square
Get £1,500 from the bank

The set of instructions given earlier in Activity 1.1 is also an example of a sequence.

Activity 1.4

Re-arrange the following instructions to describe how to play a single shot


during a golf game:

Swing club forwards, attempting to hit ball

Take up correct stance beside ball

Grip club correctly

Swing club backwards


Choose club

Selection
Binary Selection

Often a group of instructions in an algorithm should only be carried out when certain
circumstances arise. For example, if we were playing a simple game with a young
child in which we hide a sweet in one hand and allow the child to have the sweet
if she can guess which hand the sweet is in, then we might explain the core idea
with an instruction such as

Give the sweet to the child if the child guesses which hand the sweet is in

Notice that when we write a sentence containing the word IF, it consists of two main
components:

a condition : the child guesses which hand the sweet is in


and
a command : give the sweet to the child

A condition (also known as a Boolean expression) is a statement that is either true


or false. The command given in the statement is only carried out if the condition is
true and hence this type of instruction is known as an IF statement and the command
as a conditional instruction. Although we could rewrite the above instruction in
many different ways, when we produce a set of instructions in a formal manner, as
we are required to do when writing algorithms, then we use a specific layout as
shown in FIG-1.1 always beginning with the word IF.

FIG-1.1 If condition is true ...

IF condition THEN ..then command is carried out


The IF Statement
command
ENDIF If condition is not true,
then command is ignored

Notice that the layout of this instruction makes use of three terms that are always
included. These are the words IF, which marks the beginning of the instruction;
THEN, which separates the condition from the command; and finally, ENDIF which
marks the end of the instruction.

4 DarkBASIC Pro: Designing Algorithms


The indentation of the command is important since it helps our eye grasp the
structure of our instructions. Appropriate indentation is particularly valuable in
aiding readability once an algorithm becomes long and complex. Using this layout,
the instruction for our game with the child would be written as:

IF the child guesses which hand the sweet is in THEN


Give the sweet to the child
ENDIF

Sometimes, there will be several commands to be carried out when the condition
specified is met. For example, in the game of Scrabble we might describe a turn as:

IF you can make a word THEN


Add the word to the board
Work out the points gained
Add the points to your total
Select more letter tiles
ENDIF

Of course, the conditional statement will almost certainly appear in a longer


sequence of instructions. For example, the instructions for playing our guessing
game with the young child may be given as:

Hide a sweet in one hand


Ask the child to guess which hand contains the sweet
IF the child guesses which hand the sweet is in THEN
Give the sweet to the child
ENDIF
Ask the child if they would like to play again

This longer sequence of instructions highlights the usefulness of the term ENDIF
in separating the conditional command, Give the sweet to the child, from subsequent
unconditional instructions, in this case, Ask the child if they would like to play again.

Activity 1.5

A simple game involves two players. Player 1 thinks of a number between 1


and 100, then Player 2 makes a single attempt at guessing the number. Player
1 responds to a correct guess by saying Correct. The game is then complete
and Player 1 states the value of the number.

Write the set of instructions necessary to play the game.

In your solution, include the statements:

Player 1 says “Correct”

Player 1 thinks of a number

IF guess matches number THEN

The IF structure is also used in an extended form to offer a choice between two
alternative actions. This expanded form of the IF statement includes another formal
term, ELSE, and a second command. If the condition specified in the IF statement
is true, then the command following the term THEN is executed, otherwise that
following ELSE is carried out.

For instance, in our earlier example of playing a guessing game with a child, nothing
happened if the child guessed wrongly. If the person holding the sweet were to eat
it when the child’s guess was incorrect, we could describe this setup with the
following statement:

DarkBASIC Pro: Designing Algorithms 5


IF the child guesses which hand the sweet is in THEN
Give the sweet to the child
ELSE
Eat sweet yourself
ENDIF

The general form of this extended IF statement is shown in FIG-1.2.

If condition is true ...


FIG-1.2 ..then command 1 is carried out
IF condition THEN
The IF ... ELSE Statement command 1
If condition is not true ... ELSE ..then command 2 is carried out
command 2
ENDIF

Activity 1.6

Write an IF statement containing an ELSE section which describes the


alternative actions to be taken when playing Hangman and the player trying to
guess the word suggests a letter.

In the solution include the statements:


Add letter at appropriate position(s)

Add part to hanged man

Choosing between two alternative actions is called binary selection.

When we have several independent selections to make, then we may use several IF
statements. For example, when playing Monopoly, we may buy any unpurchased
property we land on. In addition, we get another turn if we throw a double. This
part of the game might be described using the following statements:

Throw the dice


Move your piece forward by the number indicated
IF you land on an unpurchased property THEN
Buy the property
ENDIF
IF you threw doubles THEN
Throw the dice again
This set of instructions is not
ELSE
complete and is shown here
Hand the dice to the next player
only to illustrate the use of
ENDIF
multiple IF statements in an
algorithm.
Multi-way Selection

Although a single IF statement can be used to select one of two alternative actions,
sometimes we need to choose between more than two alternatives (known as
multi-way selection). For example, imagine that the rules of the simple guessing
game mentioned in Activity 1.5 are changed so that there are three possible
responses to Player 2’s guess; these being:

Ø Correct
Ø Too low
Ø Too high
One way to create an algorithm that describes this situation is just to employ three
separate IF statements:

6 DarkBASIC Pro: Designing Algorithms


IF the guess is equal to the number you thought of THEN
Say “Correct”
ENDIF
IF the guess is lower than the number you thought of THEN
Say “Too low”
ENDIF
IF the guess is higher than the number you thought of THEN
Say “Too high”
ENDIF

This will work, but would not be considered a good design for an algorithm since,
when the first IF statement is true, we still go on and check if the conditions in the
second and third IF statements are true. After all, only one of the three conditions
can be true at any one time.

Where only one of the conditions being considered can be true at a given moment
in time, these conditions are known as mutually exclusive conditions.

The most effective way to deal with mutually exclusive conditions is to check for
one condition, and only if this is not true, are the other conditions tested. So, for
example, in our algorithm for guessing the number, we might begin by writing:

IF guess matches number THEN


Say “Correct”
ELSE
***Check the other conditions***
ENDIF

Of course a statement like ***Check the other conditions*** is too vague to be


much use in an algorithm (hence the asterisks). But what are these other conditions?
They are the guess is lower than the number you thought of and the guess is higher
than the number you thought of.

We already know how to handle a situation where there are only two alternatives:
use an IF statement. So we can chose between Too low and Too high with the
statement

IF guess is less than number THEN


Say “Too low”
ELSE
Say “Too high”
ENDIF

Now, by replacing the phrase ***Check the other conditions*** in our original
algorithm with our new IF statement we get:

IF guess matches number THEN


Say “Correct"
ELSE
IF guess is less than number THEN
Say ”Too low"
ELSE
Say “Too high”
ENDIF
ENDIF

Notice that the second IF statement is now totally contained within the ELSE section
of the first IF statement. This situation is known as nested IF statements. Where
there are even more mutually exclusive alternatives, several IF statements may be
nested in this way. However, in most cases, we’re not likely to need more than two
nested IF statements.

DarkBASIC Pro: Designing Algorithms 7


Activity 1.7

In an old TV programme called The Golden Shot, contestants had to direct a


crossbow in order to shoot an apple. The player sat at home and directed the
crossbow controller via the phone. Directions were limited to the following
phrases: up a bit, down a bit, left a bit, right a bit, and fire.

Write a set of nested IF statements that determine which of the above


statements should be issued. Use statements such as:

IF the crossbow is pointing too high THEN


and
Say “Left a bit”

As you can see from the solution to Activity 1.7, although nested IF statements get
the job done, the general structure can be rather difficult to follow. A better method
would be to change the format of the IF statement so that several, mutually
exclusive, conditions can be declared in a single IF statement along with the action
required for each of these conditions. This would allow us to rewrite the solution
to Activity 1.7 as:

IF
crossbow is too high:
Say “Down a bit”
crossbow is too low:
Say “Up a bit”
crossbow is too far right:
Say “Left a bit”
crossbow is too far left:
Say “ Right a bit”
crossbow is on target:
Say “Fire”
ENDIF

Each option is explicitly named (ending with a colon) and only the one which is
true will be carried out, the others will be ignored.

Of course, we are not limited to merely five options; there can be as many as the
situation requires.

When producing a program for a computer, all possibilities have to be taken into
account. Early adventure games, which were text based, allowed the player to type
a command such as Go East, Go West, Go North, Go South and this moved the
player’s character to new positions in the imaginary world of the computer program.
If the player typed in an unrecognised command such as Go North-East or Move
faster, then the game would issue an error message. This setup can be described by
adding an ELSE section to the structure as shown below:

IF
command is Go East:
Move player’s character eastward
command is Go West:
Move player’s character westward
command is Go North:
Move player’s character northward
command is Go South:
Move player’s character southward
ELSE
Display an error message
ENDIF

8 DarkBASIC Pro: Designing Algorithms


The additional ELSE option will be chosen only if none of the other options are
applicable. In other words, it acts like a catch-all, handling all the possibilities not
explicitly mentioned in the earlier conditions.

This gives us the final form of this style of the IF statement as shown in FIG-1.3:

If condition 1 is true ...


FIG-1.3 IF
condition 1:
If condition 2 is true ...
The Third Version of the command 1
IF Statement condition 2: ... then command 1
command 2 is carried out

... then command 2


is carried out
As many conditions and
commands as required can
be added

If none of the condition


given above are true ...
ELSE
command x
ENDIF
... then command X
is carried out

Activity 1.8

In the TV game Wheel of Fortune (where you have to guess a well-known


phrase), you can, on your turn, either guess a consonant, buy a vowel, or make
a guess at the whole phrase.

If you know the phrase, you should make a guess at what it is; if there are
still many unseen letters, you should guess a consonant; as a last resort you
can buy a vowel.

Write an IF statement in the style given above describing how to choose from
the three options.

Complex Conditions
Often the condition given in an IF statement may be a complex one. For example,
in the TV game Family Fortunes, you only win the star prize if you get 200 points
and guess the most popular answers to a series of questions. This can be described
in our more formal style as:

IF at least 200 points gained AND all most popular answers have been guessed THEN
winning team get the star prize
ENDIF

The AND Operator

Note the use of the word AND in the above example. AND (called a Boolean
operator) is one of the terms used to link simple conditions in order to produce a
more complex one (known as a complex condition). The conditions on either side
of the AND are called the operands. Both operands must be true for the overall result
to be true. We can generalise this to describe the AND operator as being used in the
form:

condition 1 AND condition 2

DarkBASIC Pro: Designing Algorithms 9


The result of the AND operator is determined using the following rules:

1. Determine the truth of condition 1


2. Determine the truth of condition 2
3. IF both conditions are true THEN
the overall result is true
ELSE
the overall result is false
ENDIF

For example, if we assume the group reaching the final of the game show Family
Fortunes has amassed 230 points but have not guessed all of the most popular
answers, then a computer would determine the overall result of the IF statement
given earlier as shown in FIG-1.4.
This condition is true This condition is false
FIG-1.4
Calculating the Result IF at least 200 points gained AND all most popular answers have been guessed THEN
of an AND Operation
giving

IF true AND false THEN

reduces to
IF false THEN
With two conditions there are four possible combinations. The first possibility is
that both conditions are false; another possibility is that condition 1 is false but
condition 2 is true.

Activity 1.9

What are the other two possible combinations of true and false?

The results of the AND operator are summarised in TABLE-1.1.


TABLE-1.1 condition 1 condition 2 condition 1 AND condition 2
The AND Operator
false false false
false true false
true false false
true true true

Activity 1.10

In the card game Snap, you win the cards on the table if you are first to place
your hand over those cards, and the last two cards laid down are of the same
value.

Write an IF statement, which includes the term AND, summarising this


situation.

The OR Operator

Simple conditions may also be linked by the Boolean OR operator. Using OR, only
one of the conditions needs to be true in order to carry out the action that follows.
For example, in the game of Monopoly you go to jail if you land on the GoTo Jail

10 DarkBASIC Pro: Designing Algorithms


square or if you throw three doubles in a row. This can be written as:

IF player lands on Go To Jail OR player has thrown 3 pairs in a row THEN


PIayer goes to jail
ENDIF

Like AND, the OR operator works on two operands:

condition 1 OR condition 2

When OR is used, only one of the conditions involved needs to be true for the overall
result to be true. Hence the results are determined by the following rules:

1. Determine the truth of condition 1


2. Determine the truth of condition 2
3. IF any of the conditions are true THEN
the overall result is true
ELSE
the overall result is false
ENDIF

For example, if a player in the game of Monopoly has not landed on the Go To Jail
square, but has thrown three consecutive pairs, then the result of the IF statement
given above would be determined as shown in FIG-1.5.

FIG-1.5 This condition is false This condition is true

Calculating the Result of IF player lands on Go To Jail OR player has thrown 3 pairs in a row THEN
an OR Operation
giving

IF false OR true THEN

reduces to
IF true THEN

The results of the OR operator are summarised in TABLE-1.2.


TABLE-1.2 condition 1 condition 2 condition 1 OR condition 2

The OR Operator false false false


false true true
true false true
true true true

Activity 1.11

In Monopoly, a player can get out of jail if he throws a double or pays a £50
fine.

Express this information in an IF statement which makes use of the OR


operator.

The NOT Operator

The final Boolean operator which can be used as part of a condition is NOT. This
operator is used to reverse the meaning of a condition. Hence, if property mortgaged
is true, then NOT property mortgaged is false.

DarkBASIC Pro: Designing Algorithms 11


Notice that the word NOT is always placed at the start of the condition and not
where it would appear in everyday English (property NOT mortgaged).

In Monopoly a player can charge rent on a property as long as that property is not
mortgaged. This situation can be described with the statement:

IF NOT property mortgaged THEN


Rent can be charged
ENDIF

The NOT operator works on a single operand:

NOT condition

When NOT is used, the result given by the original condition is reversed. Hence the
results are determined by the following rules:

1. Determine the truth of the condition


2. Complement the result obtained in step 1

For example, if a player lands on a property that is not mortgaged, then the result
of the IF statement given above would be determined as shown in FIG-1.6.
This condition is false
FIG-1.6
Calculating the Result of IF NOT property mortgaged THEN
a NOT Operation
giving

The original result, false,


IF NOT false THEN is complemented by the
NOT operator
reduces to
IF true THEN

The results of the NOT operator are summarised in TABLE-1.3.

TABLE-1.3 condition NOT condition

The NOT Operator false true


true false

Complex conditions are not limited to a single occurrence of a Boolean operator,


hence it is valid to have statements such as:

IF player lands on Go To Jail OR player has thrown 3 pairs in a row OR


player lifts a Go To Jail card
THEN
Player goes to jail
ENDIF

Although us humans might be able to work all of this out in our heads without even
a conscious thought, computers deal with such complex conditions in a slow, but
methodical way.

To calculate the final result of the condition given above, the computer requires
several operations to be performed. These are performed in two stages:

1. Determine the truth of each condition


2. Determine the result of each OR operation, starting with the left-most OR

12 DarkBASIC Pro: Designing Algorithms


FIG-1.7 For example, if a player lifts a Go To Jail card from the Chance pack, then the result
of the IF statement given above would be determined as shown in FIG-1.7.
Using More than One
OR Operator
This condition is false This condition is false This condition is true

IF player lands on Go To Jail OR player throws 3 pairs in a row OR player lifts a Go To Jail card THEN

giving

IF false OR false OR true THEN

reduces to
IF false OR true THEN

reduces to
IF true THEN

That might seem a rather complicated way of achieving what was probably an
obvious result, but when the conditions become even more complex, this methodical
approach is necessary.

Notice that when a complex condition contains only a single Boolean operator type
(OR in the example above), that the expression is worked out from left to right.
However, should the condition contain a mixture of OR, AND and NOT operators,
NOT operations are performed first, ANDs second, and ORs last.

For example, if a game has the following rule

IF player has a magic sword AND player has magic armour OR


player has taken invisibility potion AND player possesses sleep spell
THEN
Player can kill dragon
ENDIF

and a player has magic armour and has drunk the invisibility potion, then to
determine if the player can kill the dragon, the process shown in FIG-1.8 is followed.
FIG-1.8 This condition is false This condition is true

AND Operators have IF player has a magic sword AND player has magic armour
Priority
OR player has taken invisibility potion AND player possesses sleep spell THEN

This condition is true This condition is false

giving

IF false AND true OR true AND false THEN

reduces to
IF false OR true AND false THEN

reduces to

IF false OR false THEN

reduces to

IF false THEN
The final result shows that the player cannot kill the dragon.

DarkBASIC Pro: Designing Algorithms 13


Activity 1.12

A game has the following rule:

IF a player has an Ace AND player has King OR player has two Knaves THEN

Player must pick up extra card


ENDIF

Using a similar approach to that shown in FIG-1.8 above, show the steps
involved in deciding if the player should take an extra card assuming the
player already has an Ace and one Knave.

Sometimes the priority of operators works against what we are trying to express.
For example, if a player receives a bonus if he lands on a red, green or blue square
after throwing 7 on a pair of dice, then we might be tempted to write:

IF landed on red OR landed on green OR landed on blue AND thrown 7 THEN


Add bonus to player’s score
ENDIF

We would not expect a player landing on a red square after throwing 9 to receive
the bonus. But, if we look at the calculation for such a situation, we get the result
shown in FIG-1.9 which means that the bonus is incorrectly added to the player’s
score.

FIG-1.9 This condition is true This condition is false This condition is false This condition is false

How the Final Result is IF landed on red OR landed on green OR landed on blue AND thrown 7 THEN
Calculated

giving

IF true OR false OR false AND false THEN

reduces to
IF true OR false OR false THEN

reduces to

IF true OR false THEN

reduces to

IF true THEN

To achieve the correct results, we need the OR operations to be performed first and
this can be done by giving the OR operators a higher priority than the AND.
Luckily, operator priority can be modified by using parentheses. Operations in
parentheses are always performed first. So, by rewriting our instruction as

IF (landed on red OR landed on green OR landed on blue) AND thrown 7 THEN


Add bonus to player’s score
ENDIF

the condition is calculated as shown in FIG-1.10.

14 DarkBASIC Pro: Designing Algorithms


FIG-1.10
Using Parentheses to This condition is true This condition is false This condition is false This condition is false
Modify Operator
Priority IF ( landed on red OR landed on green OR landed on blue ) AND thrown 7 THEN

giving

IF ( true OR false OR false ) AND false THEN

reduces to

The parentheses are removed IF ( true OR false ) AND false THEN


when their contents are reduced to
a single value reduces to

IF true AND false THEN

reduces to

IF false THEN

Boolean operator priority is summarised in TABLE-1.4.

TABLE-1.4 Priority Operator


Operator Priority 1 ( )
2 NOT
3 AND
4 OR

Activity 1.13

The rules for winning a card game are that your hand of 5 cards must add up
to exactly 43 (faces =10, Ace = 11) or you must have four cards of the same
value. In addition, a player cannot win unless he has a Queen in his hand.

Express these winning conditions as an IF statement.

Activity 1.14

1. Name the three types of control structures.

2. Another term for condition is what?

3. Name the two types of selection.

4. What does the term mutually exclusive conditions mean?

5. Give an example of a Boolean operator.

6. If the terms AND and OR are included in a single complex condition,


which of these operators will be performed first?

7. How can the order in which operations in a complex condition be changed?

DarkBASIC Pro: Designing Algorithms 15


Iteration
There are certain circumstances in which it is necessary to perform the same
sequence of instructions several times. For example, let’s assume that a game
involves throwing a dice three times and adding up the total of the values thrown.
We could write instructions for such a game as follows:

Set the total to zero


Throw dice
Add dice value to total
Throw dice
Add dice value to total
Throw dice
Add dice value to total
Call out the value of total

You can see from the above that two instructions,

Throw dice
Add dice value to total

are carried out three times, once for each turn taken by the player. Not only does it
seem rather time-consuming to have to write the same pair of instructions three
times, but it would be even worse if the player had to throw the dice 10 times!

What is required is a way of showing that a section of the instructions is to be


repeated a fixed number of times. Carrying out one or more statements over and
over again is known as looping or iteration. The statement or statements that we
want to perform over and over again are known as the loop body.

Activity 1.15

What statements make up the loop body in our dice problem given above?

FOR..ENDFOR

When writing a formal algorithm in which we wish to repeat a set of statements a


specific number of times, we use a FOR..ENDFOR structure.

There are two parts to this statement. The first of these is placed just before the loop
body and in it we state how often we want the statements in the loop body to be
carried out. For the dice problem our statement would be:

FOR 3 times DO

Generalising, we can say this statement takes the form

FOR value times DO

where value would be some positive number.

Next come the statements that make up the loop body. These are indented:

FOR 3 times DO
Throw dice
Add dice value to total

Finally, to mark the fact that we have reached the end of the loop body statements
we add the word ENDFOR:

16 DarkBASIC Pro: Designing Algorithms


Note that ENDFOR is FOR 3 times DO
left-aligned with the Throw dice
opening FOR statement. Add dice value to total
ENDFOR

Now we can rewrite our original algorithm as:

Set the total to zero


FOR 3 times DO
Throw dice
Add dice value to total
ENDFOR
Call out the value of total

The instructions between the terms FOR and ENDFOR are now carried out three
times.

Activity 1.16

You can find the average If the player was required to throw the dice 10 times rather than 3, what
of the 10 numbers by changes would we need to make to the algorithm?
dividing the final total by
10. If the player was required to call out the average of these 10 numbers, rather
than the total, show what other changes are required to the set of instructions.

We are free to place any statements we wish within the loop body. For example,
the last version of our number guessing game produced the following algorithm

Player 1 thinks of a number between 1 and 100


Player 2 makes an attempt at guessing the number
IF guess matches number THEN
Player 1 says “Correct"
ELSE
IF guess is less than number THEN
Player 1 says “Too low”
ELSE
Player 1 says “Too high”
ENDIF
ENDIF

player 2 would have more chance of winning if he were allowed several chances at
guessing player 1’s number. To allow several attempts at guessing the number, some
of the statements given above would have to be repeated.

Activity 1.17

What statements in the algorithm above need to be repeated?

To allow for 7 attempts our new algorithm becomes:

Player 1 thinks of a number between 1 and 100


FOR 7 times DO
Player 2 makes an attempt at guessing the number
IF guess matches number THEN
Player 1 says “Correct"
ELSE
IF guess is less than number THEN
Player 1 says “Too low”
ELSE
Player 1 says “Too high”
ENDIF
ENDIF
ENDFOR

DarkBASIC Pro: Designing Algorithms 17


Activity 1.18

Can you see a practical problem with the algorithm?


If not, try playing the game a few times, playing exactly according to the
instructions in the algorithm.

Activity 1.19

During a lottery draw, two actions are performed exactly 6 times. These are:

Pick out ball

Call out number on the ball

Add a FOR loop to the above statements to create an algorithm for the lottery
draw process.

Occasionally, we may have to use a slightly different version of the FOR loop.
Imagine we are trying to write an algorithm explaining how to decide who goes first
in a game. In this game every player throws a dice and the player who throws the
highest value goes first. To describe this activity we know that each player does the
following task:

Player throws dice

But since we can’t know in advance how many players there will be, we write the
algorithm using the statement

FOR every player DO

to give the following algorithm

FOR every player DO


Throw dice
ENDFOR
Player with highest throw goes first

If we had to save the details of a game of chess with the intention of going back to
the game later, we might write:

FOR each piece on the board DO


Write down the name and position of the piece
ENDFOR

Activity 1.20

A game uses cards with images of warriors. At one point in the game the
player has to remove from his hand every card with an image of a knight. To
do this the player must look through every card and, if it is a knight, remove
the card.

Write down a set of instructions which performs the task described above.

Your solution should include the statements

FOR every card in player’s hand DO


and
IF card is a knight THEN

18 DarkBASIC Pro: Designing Algorithms


The general form of the FOR statement is shown in FIG-1.11.
FOR expression DO
FIG-1.11
Typical examples: loop body
The FOR Loop 5 times
every item ENDFOR The statements which make
up the loop body will be executed
a number of times as defined
within expression

Although the FOR loop allows us to perform a set of statements a specific number
of times, this statement is not always suitable for the problem we are trying to solve.
For example, in the guessing game we stated that the loop body was to be performed
7 times, but what if player 2 guesses the number after only three attempts? If we
were to follow the algorithm exactly (as a computer would), then we must make
four more guesses at the number even after we know the correct answer!

To solve this problem, we need another way of expressing looping which does not
commit us to a specific number of iterations.

REPEAT.. UNTIL

The REPEAT .. UNTIL statement allows us to specify that a set of statements should
be repeated until some condition becomes true, at which point iteration should
cease. The word REPEAT is placed at the start of the loop body and, at its end, we
add the UNTIL statement. The UNTIL statement also contains a condition, which,
when true, causes iteration to stop. This is known as the terminating (or exit)
condition. For example, we could use the REPEAT.. UNTIL structure rather than
the FOR loop in our guessing game algorithm. The new version would then be:

Player 1 thinks of a number between 1 and 100


REPEAT
Player 2 makes an attempt at guessing the number
IF guess matches number THEN
Player 1 says “Correct
ELSE
IF guess is less than number THEN
Player 1 says “Too low”
ELSE
Player 1 says “Too high”
ENDIF
ENDIF
UNTIL player 2 guesses correctly

We could also use the REPEAT..UNTIL loop to describe how a slot machine
(one-armed bandit) is played:

REPEAT
Put coin in machine
Pull handle
IF you win THEN
Collect winnings
ENDIF
UNTIL you want to stop

The general form of this structure is shown in FIG-1.12.

FIG-1.12 REPEAT

The REPEAT Loop loop body

UNTIL condition The loop body statements


will be executed continuously
until condition is true

DarkBASIC Pro: Designing Algorithms 19


The terminating condition may use the Boolean operators AND, OR and NOT as
well as parentheses, where necessary.

Activity 1.21

A one-armed bandit costs 50p per play. A player has several 50p pieces and is
determined to play until his coins are gone or until he wins at least £10.00.
Write an algorithm describing the steps in this game. The algorithm should
make use of the following statements:

Collect winnings
Place coin in machine

Pull arm

UNTIL all coins are gone OR winnings are at least £10.00

There is still a problem with our number-guessing game. By using a REPEAT ..


UNTIL loop we are allowing player 2 to have as many guesses as needed to
determine the correct number. That doesn’t lead to a very interesting game. Later
we’ll discover how we might solve this problem.

WHILE.. ENDWHILE

A final method of iteration, differing only subtly from the REPEAT.. UNTIL loop,
is the WHILE .. ENDWHILE structure which has an entry condition at the start
of the loop.

The aim of the card game of Pontoon is to attempt to make the value of your cards
add up to 21 without going over that value. Each player is dealt two cards initially
but can repeatedly ask for more cards by saying “twist”. One player is designated
the dealer. The dealer must twist while his cards have a total value of less than 16.
So we might write the rules for the dealer as:

Calculate the sum of the initial two cards


REPEAT
Take another card
Add new card’s value to sum
UNTIL sum is greater than or equal to 16

But this solution implies that the dealer must take at least one card before deciding
to stop. Using the WHILE..ENDWHILE structure we could describe the logic as

Calculate sum of the initial two cards


WHILE sum is less than 16 DO
Take another card
Add new card’s value to sum
ENDWHILE

Now determining if the sum is less than 16 is performed before Take another card
instruction. If the dealer’s two cards already add up to 16 or more, then the Take
another card instruction will be ignored.

The general form of the WHILE.. ENDWHILE statement is shown in FIG-1.13.


FIG-1.13 WHILE condition
The WHILE Loop If condition is false
loop body when first tested, the loop body
The loop body statements will be skipped completely
will be executed continuously ENDWHILE
until condition is true

20 DarkBASIC Pro: Designing Algorithms


In what way does this differ from the REPEAT statement? There are two
differences:

Ø The condition is given at the beginning of the loop.


Ø Looping stops when the condition is false.
The main consequence of this is that it is possible to bypass the loop body of a
WHILE structure entirely without ever carrying out any of the instructions it
contains, whereas the loop body of a REPEAT structure will always be executed at
least once.

Activity 1.22

A game involves throwing two dice. If the two values thrown are not the
same, then the dice showing the lower value must be rolled again. This
process is continued until both dice show the same value.

Write a set of instructions to perform this game.

Your solution should contain the statements

Roll both dice

and
Choose dice with lower value

Activity 1.23

1. What is the meaning of the term iteration?

2. Name the three types of looping structures.

3. What type of loop structure should be used when looping needs to occur an
exact number of times?

4. What type of loop structure can bypass its loop body without ever executing
it?

5. What type of loop contains an exit condition?

Data
Almost every game requires the players to remember or record some facts and
figures. In our number guessing game described earlier, the players needed to
remember the original number and the guesses made; in Hangman the word being
guessed and the letters guessed so far must be remembered.

These examples introduce the need to process facts and figures (known as data).
Every computer game has to process data. This data may be the name of a character,
the speed of a missile, the strength of a blow, or some other factor.

Every item of data has two basic characteristics :

a name
and a value

DarkBASIC Pro: Designing Algorithms 21


The name of a data item is a description of the type of information it represents.
Hence character’s title, strength and charisma are names of data items; “Fred the
Invincible”, 3, and 9 are examples of the actual values which might be given to these
data items.

In programming, a data item is often referred to as a variable. This term arises from
the fact that, although the name assigned to a data item cannot change, its value may
vary. For example, the value assigned to a variable called lives remaining, will be
reduced if the player’s character is killed.

Activity 1.24

List the names of four data items that might be held about a player in a game
of Monopoly.

Operations on Data
There are four basic operations that a computer can do with data. These are:

Input

This involves being given a value for a data item. For example, in our
number-guessing game, the player who has thought of the original number is given
the value of the guess from the second player. When playing Noughts and Crosses
adding an X (or O) changes the set up on the board. When using a computer, any
value entered at the keyboard, or any movement or action dictated by a mouse or
joystick would be considered as data entry. This type of action is known as an input
operation.

Calculation

Most games involve some basic arithmetic. In Monopoly, the banker has to work
out how much change to give a player buying a property. If a character in an
adventure game is hit, points must be deducted from his strength value. This type
of instruction is referred to as a calculation operation.

Comparison

Often values have to be compared. For example, we need to compare the two
numbers in our guessing game to find out if they are the same. This is known as a
comparison operation.

Output

The final requirement is to communicate with others to give the result of some
calculation or comparison. For example, in the guessing game player 1
communicates with player 2 by saying either that the guess is Correct, Too high or
Too low.

In a computer environment, the equivalent operation would normally involve


displaying information on a screen or printing it on paper. For instance, in a racing
game your speed and time will be displayed on the screen. This is called an output
operation.

22 DarkBASIC Pro: Designing Algorithms


Activity 1.25

Identify input, calculation, comparison and output operations when playing


Hangman
For example, the algorithm needs to compare the letter guessed by the player
with the letters in the word.

When describing a calculation, it is common to use arithmetic operator symbols


rather than English. Hence, instead of writing the word subtract we use the minus
sign (-). A summary of the operators available are given in TABLE-1.5.
TABLE-1.5
English Symbol
Mathematical Operators
Multiply *
Divide /
Add +
Subtract -

Similarly, when we need to compare values, rather than use terms such as is less
than, we use the less than symbol (<). A summary of these relational operators is
given in TABLE-1.6.
TABLE-1.6 English Symbol
Relational Operators is less than <
is less than or equal to <=
is greater than >
is greater than or equal to >=
is equal to =
is not equal to <>

As well as replacing the words used for arithmetic calculations and comparisons
with symbols, the term calculate or set is often replaced by the shorter but more
cryptic symbol := between the variable being assigned a value and the value itself.
Using this abbreviated form, the instruction:

Calculate time to complete course as distance divided by speed

becomes

time := distance / speed

Although the long-winded English form is more readable, this more cryptic style is
briefer and is much closer to the code used when programming a computer.

Below we compare the two methods of describing our guessing game; first in
English:

Player 1 thinks of a number between 1 and 100


REPEAT
Player 2 makes an attempt at guessing the number
IF guess matches number THEN
Player 1 says “Correct
ELSE
IF guess is less than number THEN
Player 1 says ”Too low"
ELSE
Player 1 says “Too high”
ENDIF
ENDIF
UNTIL player 2 guesses correctly

DarkBASIC Pro: Designing Algorithms 23


Using some of the symbols described earlier, we can rewrite this as:

Player 1 thinks of a number between 1 and 100


REPEAT
Player 2 makes an attempt at guessing the number
IF guess = number THEN
Player 1 says “Correct
ELSE
IF guess < number THEN
Player 1 says ”Too low"
ELSE
Player 1 says “Too high”
ENDIF
ENDIF
UNTIL guess = number

Activity 1.26

1. What are the two main characteristics of any data item?

2. When data is input, from where is its value obtained?

3. Give an example of a relational operator.

Levels of Detail
When we start to write an algorithm in English, one of the things we need to consider
is exactly how much detail should be included. For example, we might describe
how to record a programme on a video recorder as:

Put new tape in video


Set timer details

However, this lacks enough detail for anyone unfamiliar with the operation of the
machine. We could replace the first statement with:

Press the eject button


IF there is a tape in the machine THEN
Remove it
ENDIF
Place the new tape in the machine

and the second statement could be substituted by:

Switch to timer mode


Enter start time
Enter finish time
Select channel

This approach of starting with a less detailed sequence of instructions and then,
where necessary, replacing each of these with more detailed instructions can be used
to good effect when tackling long and complex problems.

By using this technique, we are defining the original problem as an equivalent


sequence of simpler tasks before going on to create a set of instructions to handle
each of these simpler problems. This divide-and-conquer strategy is known as
stepwise refinement. The following is a fully worked example of this technique:

Problem:
Describe how to make a cup of tea.

24 DarkBASIC Pro: Designing Algorithms


Outline Solution:

1. Fill kettle
2. Boil water
3. Put tea bag in teapot
4. Add boiling water to teapot
5. Wait 1 minute
6. Pour tea into cup
7. Add milk and sugar to taste

This is termed a LEVEL 1 solution.

As a guideline we should aim for a LEVEL 1 solution with between 5 and 12


instructions. Notice that each instruction has been numbered. This is merely to help
with identification during the stepwise refinement process.

Before going any further, we must assure ourselves that this is a correct and full
(though not detailed) description of all the steps required to tackle the original
problem. If we are not happy with the solution, then changes must be made before
going any further.

Next, we examine each statement in turn and determine if it should be described in


more detail. Where this is necessary, rewrite the statement to be dealt with, and
below it, give the more detailed version. For example. Fill kettle would be expanded
thus:

1. Fill kettle
1.1 Remove kettle lid
1.2 Put kettle under tap
1.3 Turn on tap
1.4 When kettle is full, turn off tap
1.5 Place lid back on kettle

The numbering of the new statement reflects that they are the detailed instructions
pertaining to statement 1. Also note that the number system is not a decimal fraction
so if there were to be many more statements they would be numbered 1.6, 1.7, 1.8,
1.9, 1.10, 1.11, etc.

It is important that these sets of more detailed instructions describe how to perform
only the original task being examined - they must achieve no more and no less.
Sometimes the detailed instructions will contain control structures such as IFs,
WHILEs or FORs. Where this is the case, the whole structure must be included in
the detailed instructions for that task.

Having satisfied ourselves that the breakdown is correct, we proceed to the next
statement from the original solution.

2. Boil water
2.1 Plug in kettle
2.2 Switch on power at socket
2.3 Switch on power at kettle
2.4 When water boils switch off kettle

The next two statements expand as follows:

3. Put tea bag in teapot


3.1 Remove lid from teapot
3.2 Add tea bag to teapot

4. Add boiling water to teapot


4.1 Take kettle over to teapot
4.2 Add required quantity of water from kettle to teapot

DarkBASIC Pro: Designing Algorithms 25


But not every statement from a level 1 solution needs to be expanded. In our case
there is no more detail to add to the statement

5. Wait 1 minute

and therefore, we leave it unchanged.

The last two statements expand as follows:

6. Pour tea into cup


6.1 Take teapot over to cup
6.2 Pour required quantity of tea from teapot into cup

7. Add milk and sugar as required


7.1 IF milk is required THEN
7.2 Add milk
7.3 ENDIF
7.4 IF sugar is required THEN
7.5 Add sugar
7.6 Stir tea
7.7 ENDIF

Notice that this last expansion (step 7) has introduced IF statements. Control
structures (i.e. IF, WHILE, FOR, etc.) can be introduced at any point in an
algorithm.

Finally, we can describe the solution to the original problem in more detail by
substituting the statements in our LEVEL 1 solution by their more detailed
equivalent:

1.1 Remove kettle lid


1.2 Put kettle under tap
1.3 Turn on tap
1.4 When kettle is full, turn off tap
1.5 Place lid back on kettle
2.1 Plug in kettle
2.2 Switch on power at socket
2.3 Switch on power at kettle
2.4 When water boils switch off kettle
3.1 Remove lid from teapot
3.2 Add tea bag to teapot
4.1 Take kettle over to teapot
4.2 Add required quantity of water from kettle to teapot
5. Wait 1 minute
6.1 Take teapot over to cup
6.2 Pour required quantity of tea from teapot into cup
7.1 IF milk is required THEN
7.2 Add milk
7.3 ENDIF
7.4 IF sugar is required THEN
7.5 Add sugar
7.6 Stir tea
7.7 ENDIF

This is a LEVEL 2 solution. Note that a level 2 solution includes any LEVEL 1
statements which were not given more detail (in this case, the statement Wait 1
minute).

For some more complex problems it may be necessary to repeat this process to more
levels before sufficient detail is achieved. That is, statements in LEVEL 2 may need
to be given more detail in a LEVEL 3 breakdown.

26 DarkBASIC Pro: Designing Algorithms


Activity 1.27

The game of battleships involves two players. Each player draws two 10 by 10
grids. Each of these have columns lettered A to J and rows numbered 1 to 10.
In the first grid each player marks squares in the first grid to mark the
position of warships. Ships are added as follows
1 aircraft carrier 4 squares
2 destroyers 3 squares each
3 cruisers 2 squares each
4 submarines 1 square each

The squares of each ship must be adjacent and must be vertical or horizontal.

The first player now calls out a grid reference. The second player responds to
the call by saying HIT or MISS. HIT is called if the grid reference corresponds
to a position of a ship. The first player then marks this result on his second
grid using an o to signify a miss and x for a hit (see diagram below).

A B C D E F G H I J A B C D E F G H I J
1 1 O
2 2
3 A A A A 3 O
4 S 4
5 C C D 5
6 S D 6 X X X
7 D D D D 7 O
8 C S 8
9 S C 9
10 C C 10

Vessels are positioned Results of guesses are


in the left-hand grid placed in the right-hand grid

If the first player achieves a HIT then he continues to call grid references until
MISS is called. In response to a HIT or MISS call the first player marks the
second grid at the reference called: 0 for a MISS, X for a HIT.

When the second player responds with MISS the first player’s turn is over,
and the second player has his turn.

The first player to eliminate all segments of the opponent’s ships is the
winner. However, each player must have an equal number of turns, and if both
sets of ships are eliminated in the same round the game is a draw.

The algorithm describing the task of one player is given in the instructions
below. Create a LEVEL 1 algorithm by assembling the lines in the correct
order, adding line numbers to the finished description.

Add ships to left grid

Call grid position(s)

REPEAT

Respond to other player’s call(s)

Draw grids

UNTIL there is a winner

continued on next page

DarkBASIC Pro: Designing Algorithms 27


Activity 1.27 (continued)

To create a LEVEL 2 algorithm, some of the above lines will have to be


expanded to give more detail. More detailed instructions are given below for
the statements Call grid position(s) and Respond to other player’s call(s). By
reordering and numbering the lines below create LEVEL 2 details for these
two statements

UNTIL other player misses

Mark position in second grid with X

Get other player’s call


Get reply

Get reply

ENDIF

Call HIT

Call MISS

Mark position in second grid with 0

WHILE reply is HIT DO

Call grid reference

Call grid reference

IF other player’s call matches position of ship THEN

ENDWHILE
REPEAT

ELSE

Checking for Errors


Once we’ve created our algorithm we would like to make sure it is correct.
Unfortunately, there is no foolproof way to do this! But we can at least try to find
any errors or omissions in the set of instructions we have created.

We do this by going back to the original description of the task our algorithm is
attempting to solve. For example, let’s assume we want to check our number
guessing game algorithm. In the last version of the game we allowed the second
player to make as many guesses as required until he came up with the correct answer.
The first player responded to each guess by saying either “too low”, “too high” or
“correct”.

To check our algorithm for errors we must come up with typical values that might
be used when carrying out the set of instructions and those values should be chosen
so that each possible result is achieved at least once.

So, as well as making up values, we need to predict what response our algorithm
should give to each value used. Hence, if the first player thinks of the value 42 and
the second player guesses 75, then the first player will respond to the guess by saying
“Too high”.

Our set of test values must evoke each of the possible results from our algorithm.
One possible set of values and the responses are shown in TABLE-1.7.
TABLE-1.7
Test Data Expected Results
Test Data for the Number
number = 42
Guessing Game Algorithm
guess = 75 Says “Too high”
guess = 15 Says “Too low”
guess = 42 Says “Correct”

28 DarkBASIC Pro: Designing Algorithms


Once we’ve created test data, we need to work our way through the algorithm using
that test data and checking that we get the expected results. The algorithm for the
number game is shown below, this time with instruction numbers added.

1. Player 1 thinks of a number between 1 and 100


2. REPEAT
3. Player 2 makes an attempt at guessing the number
4. IF guess = number THEN
5. Player 1 says “Correct"
6. ELSE
7. IF guess < number THEN
8. Player 1 says “Too low”
9. ELSE
10. Player 1 says “Too high”
11. ENDIF
12. ENDIF
13. UNTIL guess = number

Next we create a new table (called a trace table) with the headings as shown in
FIG-1.14.
FIG-1.14
Any condition contained in
The Components of a the statement is written here The value currently
The result of the stored in each variable
Trace Table condition is written is given here
Contains the number here as T or F
of the instruction which Any value displayed
has been executed (or spoken) is shown here

Instruction Condition T/F Variables Output


number guess

Now we work our way through the statements in the algorithm filling in a line of
the trace table for each instruction.

Instruction 1 is for player 1 to think of a number. Using our test data, that number
will be 42, so our trace table starts with the line shown in FIG-1.15.
FIG-1.15 Instruction Condition T/F Variables Output
number guess
Tracing the First
Statement 1 42

The REPEAT word comes next. Although this does not cause any changes,
nevertheless a 2 should be entered in the next line of our trace table. Instruction 3
involves player 2 making a guess at the number (this guess will be 75 according to
our test data). After 3 instructions our trace table is as shown in FIG-1.16.

FIG-1.16 Instruction Condition T/F Variables Output


number guess
Moving through the Trace
1 42
2
3 75

Instruction 4 is an IF statement containing a condition. This condition and its result


are written into columns 2 and 3 as shown in FIG-1.17.

DarkBASIC Pro: Designing Algorithms 29


FIG-1.17 Instruction Condition T/F Variables Output
number guess
Tracing a Condition
1 42
2
3 75
4 guess = number F

Because the condition is false, we now jump to instruction 6 (the ELSE line) and
on to 7. This is another IF statement and our table now becomes that shown in
FIG-1.18.
FIG-1.18
Instruction Condition T/F Variables Output
Tracing a Second number guess
Condition
1 42
2
3 75
4 guess = number F
6
7 guess < number F

Since this second IF statement is also false, we move on to statements 9 and 10.
Instruction 10 causes output (speech) and hence we enter this in the final column
as shown in FIG-1.19.
FIG-1.19
Instruction Condition T/F Variables Output
Recording Output number guess

1 42
2
3 75
4 guess = number F
6
7 guess < number F
9
10 Too high

Now we move on to statements 11,12 and 13 as shown in FIG-1.20.

FIG-1.20
Instruction Condition T/F Variables Output
Reaching the end of the number guess
REPEAT .. UNTIL
Structure 1 42
2
3 75
4 guess = number F
6
7 guess < number F
9
10 Too high
11
12
13 guess = number F

Since statement 13 contains a condition which is false, we return to statement 2 and


then onto 3 where we enter 15 as our second guess (see FIG-1.21).

30 DarkBASIC Pro: Designing Algorithms


FIG-1.21 Instruction Condition T/F Variables Output
number guess
Showing Iteration
1 42
2
3 75
4 guess = number F
6
7 guess < number F
9
10 Too high
11
12
13 guess = number F
2
3 15

This method of checking is known as desk checking or dry running.

Activity 1.28

Create your own trace table for the number-guessing game and, using the
same test data as given in TABLE-1.7 complete the testing of the algorithm.

Were the expected results obtained?

Summary
l Computers can perform many tasks by executing different programs.

l An algorithm is a sequence of instructions which solves a specific problem.

l A program is a sequence of computer instructions which usually manipulates


data and produces results.

l Three control structures are used in programs :

Ø Sequence
Ø Selection
Ø Iteration
l A sequence is a list of instructions which are performed one after the other.

l Selection involves choosing between two or more alternative actions.

l Selection is performed using the IF statement.

l There are three forms of IF statement:


IF condition THEN
instructions
ENDIF

IF condition THEN
instructions
ELSE
instructions
ENDIF

DarkBASIC Pro: Designing Algorithms 31


IF
condition 1:
instructions
condition 2:
instructions
condition x :
instructions
ELSE
instructions
ENDIF

l Iteration is the repeated execution of one or more statements.

l Iteration is performed using one of three instructions:


FOR number of iterations required DO
instructions
ENDFOR

REPEAT
instructions
UNTIL condition

WHILE condition DO
instructions
ENDWHILE

l A condition is an expression which is either true or false.

l Simple conditions can be linked using AND or OR to produce a complex


condition.

l The meaning of a condition can be reversed by adding the word NOT.

l Data items (or variables) hold the information used by the algorithm.

l Data item values may be:

Input
Calculated
Compared
or Output

l Calculations can be performed using the following arithmetic operators:

Multiplication * Addition +
Division / Subtraction -

l The order of priority of an operator may be overridden using parentheses.

l Comparisons can be performed using the relational operators:

Less than <


Less than or equal to <=
Greater than >
Greater than or equal to >=
Equal to =
Not equal to <>

l The symbol := is used to assign a value to a data item. Read this symbol as is

32 DarkBASIC Pro: Designing Algorithms


assigned the value.

l In programming, a data item is referred to as a variable.

l The divide-and-conquer strategy of stepwise refinement can be used when


creating an algorithm.

l LEVEL 1 solution gives an overview of the sub-tasks involved in carrying out


the required operation.

l LEVEL 2 gives a more detailed solution by taking each sub-task from LEVEL
1 and, where necessary, giving a more detailed list of instructions required to
perform that sub-task.

l Not every statement needs to be broken down into more detail.

l Further levels of detail may be necessary when using stepwise refinement for
complex problems.

l Further refinement may not be required for every statement.

l An algorithm can be checked for errors or omissions using a trace table.

DarkBASIC Pro: Designing Algorithms 33


Solutions Activity 1.8
IF
you know the phrase:
Activity 1.1 Make guess at phrase
there are many unseen letters:
No solution required. Guess a consonant
ELSE
Buy a vowel
Activity 1.2 ENDIF
One possible solution is:
Activity 1.9
Fill A
Fill B from A Other possibilities are:
Empty B
Empty A into B
Fill A Both conditions are true
Fill B from A condition 1 is true and condition 2 is false

Activity 1.3 Activity 1.10


IF you are first to place your hand over
1. An algorithm those cards AND the last two cards laid
2. A Computer program down are of the same value
3. mips (millions of instructions per second) THEN
You win the cards already played
ENDIF
Activity 1.4
Choose club
Take up correct stance beside ball
Activity 1.11
Grip club correctly IF double thrown OR fine paid THEN
Swing club backwards Player gets out of jail
Swing club forwards, attempting to hit ball ENDIF

The second and third statements could be interchanged.


Activity 1.12
Activity 1.5 Assuming the player has one Ace and one Knave the
statement
Player 1 thinks of a number
Player 2 makes a guess at the number IF a player has an Ace AND player has
IF guess matches number THEN
King OR player has two Knaves
Player 1 says “Correct”
THEN
ENDIF
Player 1 states the value of the number
would reduce to

Activity 1.6 IF true AND false OR false THEN

IF letter appears in word THEN The AND operation is then performed giving:
Add letter at appropriate position(s)
ELSE IF false OR false THEN
Add part to hanged man
ENDIF
Next, the OR operation is completed giving a final
value of
Activity 1.7
IF false THEN
IF the crossbow is on target THEN
Say “Fire” and, therefore the player does not pick up an extra card.
ELSE
IF the crossbow is pointing too high THEN
Say “Down a bit”
ELSE
Activity 1.13
IF the crossbow is pointing too low THEN IF (total of cards held is 43 OR hand has
Say “Up a bit” 4 cards of the same value ) AND hand
ELSE contains a Queen THEN
IF crossbow is too far left THEN
Say “Right a bit”
ELSE Activity 1.14
Say “Left a bit"
ENDIF 1. Sequence
ENDIF
Selection
ENDIF
ENDIF
Iteration

34 DarkBASIC Pro: Designing Algorithms


2. Boolean expression Activity 1.20
3. Binary selection FOR every card in player’s hand DO
IF card is a knight THEN
Multi-way selection Remove card from hand
ENDIF
4. No more than one of the conditions can be true at any ENDFOR
given time.

5. Boolean operators are: AND, OR, and NOT. Activity 1.21


REPEAT
6. AND is performed before OR . Place coin in machine
Pull arm
7. The order in which operations in a complex condition IF a win THEN
are calculated can changed by using parentheses. Collect winnings
ENDIF
UNTIL all coins are gone OR winnings are
Activity 1.15 at least £10.00

Throw dice
Add dice value to total Activity 1.22
Roll both dice
Activity 1.16 WHILE both dice do not match in value DO
Choose dice with lower value
Only one line, the FOR statement, would need to be Roll the chosen dice
changed, the new version being: ENDWHILE

FOR 10 times DO
Activity 1.23
To call out the average, the algorithm would change to 1. Iteration means executing a set of instructions over and
over again.
Set the total to zero
FOR 10 times DO 2. The three looping structures are:
Throw dice
Add dice value to total FOR .. ENDFOR
ENDFOR REPEAT .. UNTIL
Calculate average as total divided by 10 WHILE .. ENDWHILE
Call out the value of average
3. The FOR .. ENDFOR structure.
4. The WHILE .. ENDWHILE structure.
Activity 1.17 5. The REPEAT .. UNTIL structure.
In fact, only the first line of our algorithm is not repeated,
so the lines that need to be repeated are: Activity 1.24
Player 2 makes an attempt at guessing the Number of properties held
number Amount of money held
IF guess matches number THEN The playing token being used
Player 1 says “Correct “
The position on the board
ELSE
IF guess is less than number THEN
Player 1 says “Too low”
ELSE
Activity 1.25
Player 1 says “Too high”
ENDIF
Input:
ENDIF Letter guessed
Word guessed
Calculations:
Activity 1.18 Where to place a correctly guessed letter
The number of wrong guesses made
The FOR loop forces the loop body to be executed Comparisons:
exactly 7 times. If the player guesses the number in The letter guessed with the letters in the word
less attempts, the algorithm will nevertheless The word guessed with the word to be guessed
continue to ask for the remainder of the 7 guesses. The number of wrong guesses with the value 6
(6 wrong guesses completes the drawing of the
Later, we’ll see how to solve this problem. hanged man)
Output:
Hyphens indicating each letter in the word
Activity 1.19 Gallows
FOR 6 times DO Body parts of the hanged man
Pick out ball Correctly guessed letters
Call out number on the ball
ENDFOR

DarkBASIC Pro: Designing Algorithms 35


Activity 1.26
1. Name and value
2. From outside the system. In a computerised system this is often via a
keyboard.
3. The relational operators are:
<, <=, >, >=, =, and <>

Activity 1.27
The LEVEL 1 is coded as:

1. Draw grids
2. Add ships to left grid
3. REPEAT
4. Call grid position(s)
5. Respond to other player’s call(s)
6. UNTIL there is a winner

The expansion of statement 4 would become:

4.1 Call grid reference


4.2 Get reply
4.3 WHILE reply is HIT DO
4.4 Mark position in second grid with X
4.5 Call grid reference
4.6 Get reply
4.7 ENDWHILE
4.8 Mark position in second grid with 0

The expansion of statement 5 would become:

5.1.REPEAT
5.2 Get other player’s call
5.3 IF other player’s call matches position of ship THEN
5.4 Call HIT
5.5 ELSE
5.6 Call MISS
5.7 ENDIF
5.8 UNTIL other player misses

Activity 1.28
Instruction Condition T/F Variables Output
number guess

1 42
2
3 75
4 guess = number F
6
7 guess < number F
9
10 Too high
11
12
13 guess = number F
2
3 15
4 guess = number F
6
7 guess < number T
8 Too low
11
12
13 guess = number F
2
3 42
4 guess = number T
5 Correct
11
12
13 guess = number T

The expected results were obtained.

36 DarkBASIC Pro: Designing Algorithms


2

Correcting Errors

Creating a Project in DarkBASIC Pro

Executing a Program

Screen Output

Text Colour, Size, Font, and Style

The Compilation Process

Transparent and Opaque Text

Using the DarkBASIC Pro Editor

DarkBASIC Pro: Starting DarkBASIC Pro 37


Programming a Computer
Introduction
In the last chapter we created algorithms written in a style of English known as
structured English. But if we want to create an algorithm that can be followed by a
computer, then we need to convert our structured English instructions into a
programming language.

There are many programming languages; C++, Java, C#, and Visual Basic being
amongst the most widely used. So how do we choose which programming language
to use? Probably the most important consideration is the area of programming that
is best suited to a given language. For example, Java is designed to create programs
that can be executed on a variety of different computers, while C++ was designed
for fast execution times.

We are going to use a language known as DarkBASIC Professional or just


DarkBASIC Pro, which was designed specifically for writing computer games.
Because of this, it has many unique commands for displaying graphics, controlling
joysticks, and creating three dimensional images.

The Compilation Process


As we will soon see, DarkBASIC Pro uses statements that retain some English terms
and phrases, so we can look at the set of instructions and make some sense of what
is happening after only a relatively small amount of training.
Binary is a method of
representing numbers Unfortunately, the computer itself only understands instructions given in a binary
using only the digits 0 code known as machine code and has no capability of directly following a set of
and 1. instructions written in DarkBASIC Pro. But this need not be a problem. If we were
given a set of instructions written in Russian we could easily have them translated
into English and then carry out the translated commands.

This is exactly the approach the computer uses. We begin the process of creating a
new piece of software by mentally converting our structured English into
DarkBASIC Pro commands. These commands are entered using a text editor which
is nothing more than a simple word-processor-like program allowing such basic
operations as inserting and deleting text. Once the complete program has been
entered, we get the machine itself to translate those instructions into machine code.
The original code is known as the source code; the machine code equivalent is
known as the object code.

The translator (known as a compiler) is simply another program installed in the


computer. After typing in our program instructions, we feed these to the compiler
which produces the equivalent instructions in machine code. These instructions are
then executed by the computer and we should see the results of our calculations
appear on the screen (assuming there are output statements in the program).

The compiler is a very exacting task master. The structure, or syntax, of every
statement must be exactly right. If you make the slightest mistake, even something
as simple as missing out a comma or misspelling a word, the translation process
will fail. When this happens in DarkBASIC Pro the incorrect command is
highlighted in red.

38 DarkBASIC Pro: Starting DarkBASIC Pro


A failure of this type is known as a syntax error - a mistake in the grammar of your
commands. Any syntax errors have to be corrected before you can try compiling
the program again.

As we work on the computer entering a DarkBASIC Pro program, we need to save


this source code to a file. This ensures that we have a copy of our work should there
be a power cut or we accidentally delete the program from the computer’s memory.
DarkBASIC Pro refers to this as the source file.

But a second file, known as the project file is also produced. This second file is
created automatically by DarkBASIC Pro and contains details of any images,
sounds or other resources that might be used by your program.

When we compile our program (translating it from source code to object code), yet
another file is produced. This third file, the executable file, contains the object code
and is, again, created automatically.

To run our program, the source code in the executable file is loaded into the
computer’s memory (RAM) and the instructions it contains are carried out.

The whole process is summarised in FIG-2.1.

FIG-2.1 Design
algorithm
Creating Software

Convert
to program code
Save source code
and project details
to disk

Compile
program
Save object code
to disk

Load object code


into memory
Run
program

If we want to make changes to the program, we load the source code into the editor,
make the necessary changes, then save and recompile our program, thereby
replacing the old version of all three files.

Activity 2.1

1. What type of instructions are understood by a computer?

2. What piece of software is used to translate a program from source code to


object code?

3. Misspelling a word in your program is an example of what type of error?

DarkBASIC Pro: Starting DarkBASIC Pro 39


Starting DarkBASIC Pro
Introduction
DarkBASIC Pro is based on one of the earliest computer languages, BASIC, but
has been enhanced specifically to aid the creation of games programs.

The language was invented by Lee Bamber who formed a company to sell
DarkBASIC Pro. Over the last few years the company has grown in size and
expanded to sell other DarkBASIC related products, such as DarkMatter, which
contains many 3D objects that can be used in DarkBASIC programs.

In fact, there are two versions of the language: DarkBASIC and DarkBASIC
Professional. It’s this second, enhanced version of the language we will be using
here.

DarkBASIC Pro Files


Because a typical program written in DarkBASIC Pro is likely to contain images,
sounds and even video, the DarkBASIC Pro package has to save much more than
the set of instructions that make up your program; it also needs to store details of
these images, sounds, etc.

To do this DarkBASIC Pro creates two files every time you produce a new program
(see FIG-2.2).

The first of these files, known as the project file, contains details of the images and
sounds used by your program, as well as other information such as the screen
resolution and number of colours used. This file has a .dbpro extension.

The second file, known as the source file, contains only the program’s code written
in the DarkBASIC Pro language. This file has a .dba extension.
Every DarkBASIC Pro program creates two files

FIG-2.2

The Two Files Created by a Project File Source File


DarkBASIC Pro Program (.dbpro) (.dba)

40 DarkBASIC Pro: Starting DarkBASIC Pro


Getting Started with DarkBASIC Pro
When you first start up DarkBASIC Pro you should see one of the screens shown
in FIG-2.3. Exactly which one you see depends on how often DarkBASIC Pro has
been run on your computer. The first time the program is run, the display will match
that shown on the left of FIG-2.3; every other time your screen will match that
shown on the right.
FIG-2.3
The Start-Up Screen in
DarkBASIC Pro

DarkBASIC Pro Start-Up Screen (First Start-Up Only) DarkBASIC Pro Start-Up Screen (Subsequent Start-Ups)

First Start-Up
If this is the first time DarkBASIC Pro has been run on your machine, as well as
the main window, the Assistant Window also shows on the right-hand side.

If you close down the Assistant Window the display changes to match that shown
in FIG-2.4, showing the Project Dialog box.

FIG-2.4
The Project Dialog Box

Subsequent Start-Ups
Click on this icon
to show the New Project
When DarkBASIC Pro is started up for the second (or subsequent) time, use the
dialog FILE | NEW PROJECT option from the main menu, or click on the New Project icon
near the top left corner, to display the Project Dialog box.

Specifying a Project
The next stage is to create a project file by filling in the details required by the
Project Dialog box.

First the name to be given to the project is entered. This should be something
meaningful like Hangman or SpaceMonsters.

DarkBASIC Pro: Starting DarkBASIC Pro 41


Next the Specify a Folder radio button is selected and the folder in which the
DarkBASIC Pro projects are to be saved is entered. The folder specified must
already exist. See FIG-2.5 for a summary of these steps.
FIG-2.5
1
Filling in the New Enter the name of
Project Dialog Box the project here 3
2
Use the Browse icon
Select
to find the folder where the
Specify a Folder
project is to be stored

A sub-folder will be created


automatically to hold the three
DarkBASIC Pro files that will
be produced

Once the OK button in the Project Dialog box is clicked, the dialog box disappears
and you are left with the main edit area where the program code is entered. Line
numbers appear to the left of this area.

A First Program
Before we begin looking in detail at the commands available in DarkBASIC Pro,
we’ll have a quick look at a simple program and show you how to type it in, run it
and save the code.

The program in LISTING-2.1 gets you to enter your name at the keyboard and then
displays a greeting on the screen.

LISTING-2.1 Rem Project: First


Rem Created: 02/10/2004 07:35:27
A First Program Rem ***** Main Source File *****

REM *** A program to read and display your name ***


INPUT “Enter your name : ”,name$
PRINT “Hello ” ,name$, “ welcome to DarkBASIC Pro.”
WAIT KEY
END

An Explanation of the Code


DarkBASIC Pro allows
words to be given in
REM This is short for REMARK and is used to indicate a
either upper or lower case. comment within the program. Comments are totally
ignored when the source code is translated into object code
and are only included for the benefit of anybody examining
the program code, giving an explanation of what the
program does.

When you type in a INPUT This is a keyword in DarkBASIC Pro. Keywords are words
program, you’ll see that
recognised by the programming language as having a
the instructions are
colour-coded with specific meaning.
keywords appearing in
blue. All keywords are shown throughout this text in uppercase,
but lowercase characters are also acceptable.

The INPUT keyword tells the computer to allow the user


to enter a value from the keyboard.

42 DarkBASIC Pro: Starting DarkBASIC Pro


The need for a space “Enter your name:” This message is displayed on the screen as a prompt,
after the colon will telling the user what information is to be entered.
become clear when you
run this program.
Messages are always enclosed in double quotes (“ ”)
and are more generally known as strings.

name$ This is the variable in which the value entered by the


user will be stored.

PRINT This command is used to tell the computer to display


information on the screen.

“Hello ” This is the first piece of information to be displayed

, Items of data are separated from each other by commas.

name$ The value held in the variable name$ is to be displayed.


This will be whatever value the user typed in when the
earlier INPUT statement was executed.

“ welcome to DarkBASIC Pro.”


Another data item to be displayed.

WAIT KEY This command contains two key words which tell the
computer to wait for a key to be pressed before continuing
to the next instruction.

END Marks the end of the program.

Activity 2.2

In this Activity you are going to type in and run the program given in
LISTING-2.1.

Create a folder in the C: drive (or elsewhere) named DarkBasicProjects

Start up DarkBASIC Pro.

Bring up the Project Dialog box shown in FIG-2.4.

Name the project first.dbpro, select Specify a Folder; browse to your


DarkBASICProjects folder and click OK.

The first three lines of the program will appear automatically (only the date
and time will differ from that in LISTING-2.1).
Click on this icon
to execute your
program Type in the remainder of the program as shown in LISTING-2.1.

Execute the program by pressing the F5 key or clicking on the Run icon.

When requested, type in your name. You should then see a message including
your name displayed on the screen.

Finally, press any key to finish the program and return to the editor.

DarkBASIC Pro: Starting DarkBASIC Pro 43


Activity 2.3

1. PRINT is what type of word?

2. Messages enclosed in quotes are known as what?

3. The WAIT KEY instruction causes what to happen?

If we use Windows Explorer to examine our DarkBasicProjects folder we’ll see


that a new sub-folder called first has been created.

Inside that new folder are three files (see FIG-2.6).

FIG-2.6
Files Created by
DarkBASIC Pro

first.dbpro This is the project file.

first.dba This is the file containing the source code.

first.exe This is the machine code version of your program.


It’s the code in this file that is actually executed
when you run your program.

If you ever want to give away your completed programs to other people, you only
need to give them a copy of the .exe file. This contains everything they need to run
your program without allowing them to see your original DarkBASIC Pro code.

Activity 2.4
When opening the file
in Notepad, change the
File of Type entry to All Without closing down DarkBASIC Pro, load up Notepad (it’s in Accessories)
Files. and open up the file first.dba.

Notice that the file only contains the three REM statements which were
generated automatically when you opened your new project. None of the
lines you typed in are present.

Saving Your Project


When you’ve typed in your program you need to save both the project and the source
files. To do this, select FILE|SAVE PROJECT and then FILE|SAVE SOURCE.

Activity 2.5

Save your project and source files as described above.

44 DarkBASIC Pro: Starting DarkBASIC Pro


First Statements in DarkBASIC Pro
Introduction
Learning to program in DarkBASIC Pro is very simple compared to other languages
such as C++ or Java. Unlike most other programming languages, it has no rigid
structure that must be adhered to. In fact, there are only two statements that you
should include at this stage. These are given below.

Ending a Program
The END Statement
The first statement we examine is the one that should come at the end of any program
you write. It consists of the single keyword END and, as you might have guessed,
marks the end of your program.

We have already seen this statement in LISTING-2.1.

Some of the statements available in DarkBASIC Pro have quite a complex syntax
so, to help show exactly what options are available when using a statement, we’ll
use informal syntax diagrams. FIG-2.7 shows a syntax diagram for the END
statement.
FIG-2.7
The END Statement END

These diagrams contain one or more tiles. A raised tile (like the one above) signifies
a DarkBASIC Pro keyword. The order of the tiles signifies the order in which the
keywords must be placed when using this statement in your program.

So the diagram above tells us that the END statement contains only the single word
END.

The WAIT KEY Statement


We can make a program pause until a key is pressed using the WAIT KEY
statement. The program will only continue after a key has been pressed. Any key
on the keyboard will do.

For example, in the program given in LISTING-2.1, the computer will pause after
the PRINT statement is executed.

For most simple programs, you need to include a WAIT KEY statement
immediately before the END statement, otherwise your program will finish and
close down before you get a chance to view what is being displayed on the screen.

The syntax for this statement is shown in FIG-2.8.


FIG-2.8
WAIT KEY
The WAIT KEY
Statement

DarkBASIC Pro: Starting DarkBASIC Pro 45


Adding Comments
It is important that you add comments to any programs you write. These comments
should explain what each section of code is doing. It’s also good practice, when
writing longer programs, to add comments giving details such as your name, date,
programming language being used, hardware requirements of the program, and
version number.

Comments are totally ignored by the translation process as it turns DarkBASIC Pro
statements into machine code. The purpose of comments is to make a program more
readable to other people who may have to modify a program after you’ve moved
on to other things.

In DarkBASIC Pro there are three ways to add comments:

Ø Add the keyword REM. The remainder of the line becomes a comment
(see FIG-2.9).
FIG-2.9
The REM Comment REM comment

Notice that this syntax diagram introduces the sunken tile. Sunken tiles
signify details that are determined by the programmer. Hence, the
programmer gets to choose exactly what comment should be added after the
keyword REM. For example:
Adding asterisks to a
comment helps it to stand out. REM *** Program to display numbers ***

Ø Add an opening quote character (you’ll find this on the top left key, just
next to the 1). Again the remainder of the line is treated as a comment
(see FIG-2.10).
FIG-2.10
The ‘ Comment ` comment

For example:

‘ Get details from keyboard

Ø Add several lines of comments by starting with the term REMSTART


and ending with REMEND. Everything between these two words is
treated as a comment (see FIG-2.11).

FIG-2.11
REMSTART
The REMSTART ..
REMEND Comment
comment line

REMEND

This diagram introduces another symbol - a looping arrowed line. This is


used to indicate a section of the structure that may be repeated if required.
In the diagram above it is used to signify that any number of comment lines

46 DarkBASIC Pro: Starting DarkBASIC Pro


can be placed between the REMSTART and REMEND keywords.

For example, we can use this statement to create the following comment
which contains three comment lines:

REMSTART
This program is designed to play the game of
battleships. Two peer-to-peer computers are
required.
REMEND

Activity 2.6

1. How are keywords shown in a syntax diagram?

2. What does a sunken tile in a syntax diagram represent?

3. How is a repeatable element in a statement represented in a syntax diagram?

DarkBASIC Pro: Starting DarkBASIC Pro 47


Outputting to the Screen
Introduction
Even the simplest program will require information to be displayed on the screen.

In DarkBASIC Pro the simplest way to display information on the screen is to use
the PRINT statement. Other statements exist which allow changes to the colour,
font and style of displayed characters to be specified.

A description of most of these statements are given over the next few pages

The PRINT Statement


As we saw in LISTING-2.1, information can be displayed using the PRINT
statement.

To use it, we start with the keyword PRINT, followed by whatever information we
want to display. For example, the statement

PRINT “Hello”

displays the word Hello on the screen. The quotes themselves are not displayed.
Absolutely any set of characters can appear between the quotes, including spaces.

Although a set of characters, or strings, must be enclosed in double quotes, if you


want to display a number, quotes are not required. For example, the following are
valid statements:
PRINT 12
PRINT 3.1416
PRINT -7.0

It is possible to display several pieces of information using a single PRINT statement


by separating each value to be displayed by a comma:
PRINT 12,7,1.2

Unfortunately, all the values in this statement will be displayed without any spaces
between them giving the impression of one large number (1271.2) rather than three
separate values.

To solve this problem we need to display some spaces between the numbers:

Spaces are just strings - PRINT 12," ",7," ",1.2


like any other sequence
of characters - and must When several values are displayed by a single PRINT statement they appear on a
be enclosed in double
quotes.
single line of the screen, but by using several PRINT statements we can make the
data appear over several lines:
PRINT 12
PRINT 1
PRINT 1.2

To turn this into a complete program we just need to add the WAIT KEY and END
statements as shown in LISTING-2.2.

48 DarkBASIC Pro: Starting DarkBASIC Pro


LISTING-2.2 REM *** Print some numbers ***
PRINT 12
Displaying Numbers PRINT 7
PRINT 1.2
REM statements
generated when you start a REM *** End program ***
new project have been WAIT KEY
omitted from the listing. END

Activity 2.7

Start up a new DarkBASIC Pro project.

To do this select File | New Project.

In the Project dialog box that appears, call the project printing.dbpro; select
Specify a Folder; browse to your DarkBASICProjects folder and click OK.

Type in and test the program given in LISTING-2.2.

Remember to save the Source and Project files when you have finished.

Creating Blank Lines

The PRINT statement can even be used without any data values being given, as in
the line
PRINT

This has the effect of creating a blank line on the screen. Hence, the lines

PRINT 1
PRINT
PRINT 2

would display the values 1 and 2 with a blank line between them.

Activity 2.8

Modify your last program so that a blank line appears between each number
displayed.

Ending the PRINT Statement with a Semicolon

If you end a PRINT statement with a string and a semicolon, the output produced
by the next PRINT statement will be displayed on the same line. For example, the
lines:

PRINT 12,"";
PRINT 7
PRINT 1.2

would produce the output

127
1.2

As you will see later, this apparently useless option can be used to great effect.

DarkBASIC Pro: Starting DarkBASIC Pro 49


Activity 2.9

Create a new project called Printing2.

Write a program which displays the numbers 1, 2 and 3 on the same line.
There should be a small gap between each number.

Change your program so that the numbers 1, 2 and 3 are displayed on separate
lines.

Modify the code again so that the program pauses before each number is
shown. (HINT: You’ll need to add a WAIT KEY statement after each PRINT
statement.)

Activity 2.10

Write a program (call the project Shapes) to display the following three
shapes (pause the program between each):

a) **********
**********
**********
b) *
**
***
****
*****
c) *
**
***
****
*****

The format of the PRINT statement is shown in FIG-2.12.


FIG-2.12
The PRINT Statement PRINT

[ data item

,
[ ;

This diagram introduces two new concepts. Items within the brackets are optional
and may be omitted. Any number of data items can be displayed, but each must be
separated from the next by a comma.

Activity 2.11

Using the information given in the PRINT statement’s syntax diagram, which
of the following PRINT statements are invalid?
a) PRINT
b) PRINT “Start game”
c) PRINT 7;
d) PRINT "";
e) PRINT 6,5,4;

50 DarkBASIC Pro: Starting DarkBASIC Pro


Positioning Text on the Screen
In DarkBASIC Pro the screen is treated like a piece of paper divided into thousands
of small squares, as shown in FIG-2.13. These small invisible squares are known
as pixels (derived from the phrase picture elements). An individual pixel is
identified by giving its position on the screen.

A pixel’s position is given by the column number (also known as the position on
the x-axis) followed by the row number (the position on the y-axis) separated by a
comma.

The top left pixel is at position (0,0). This point is known as the origin.
FIG-2.13
The origin
The Screen is Made Up of (0,0)
0 1 2 3 4 5 6
The x-axis (columns)
Pixels 0
1
2
3
4
5
6

Position
(6,2)
The y-axis (rows)

The Screen
Exactly how many pixels are on the screen depends on the screen resolution (which
we will examine later) but there will be at least 640 columns by 480 rows.

The SET CURSOR Statement


Normally, the first text that we output to the screen will start at the origin, but we
can change this by using the SET CURSOR statement which allows us to specify
where on the screen the next PRINT statement will begin its output. For example,
the statements

SET CURSOR 350, 100


PRINT “HELLO”

displays the word HELLO, with the top-left comer of the H starting at position
(350,100) (i.e. at column 350, row 100) as shown in FIG-2.14.
FIG-2.14 The
0
0 1 2 x-axis
3 4 5 6 (columns)
1
2
3
4
The top-left corner of
Positioning Text Using the
5
6 the text starts at position
(350,100)
SET CURSOR Statement
The y-axis (rows)

The Screen

DarkBASIC Pro: Starting DarkBASIC Pro 51


The format for the SET CURSOR statement is shown in FIG-2.15.
FIG-2.15
The SET CURSOR SET CURSOR x , y
Statement

In the diagram above:

x,y is a pair of integer values specifying the


position to which the cursor is to be moved.

Activity 2.12

Create a new project (corners.dbpro) that displays the letters A, B, C and D so


that one letter appears at each corner of the screen.

(You’ll have to use trial and error to find the correct positions)

Activity 2.13

Since we can output at any position on the screen, this allows us to display
different values at the same position on the screen.

Create a new project (overwrite.dbpro) containing the following code:

REM *** Output two strings at the same location ***


SET CURSOR 100,100
PRINT “Hello”
WAIT KEY
SET CURSOR 100,100
PRINT “Goodbye”
REM *** End program ***
WAIT KEY
END

Check the output produced by running this program.

The TEXT Statement


The effects of the SET CURSOR and PRINT statements are combined in the TEXT
command which takes both the value to be displayed and the position at which the
data is to be displayed. For example, the statement

TEXT 350, 100, “HELLO”

has the same effect as the SET CURSOR example given earlier, although you may
find that the program uses a different screen resolution when the output is displayed.
Your screen will almost
certainly use a different
resolution when using the Activity 2.14
TEXT statement than it
did in previous programs. Change your corners.dbpro project so that it uses the TEXT command to
This means that in this
Activity you’ll have to
position the letters in the corners of the screen.
change the coordinates
from those used in the
There are a few differences between the PRINT and TEXT commands.
previous example.

52 DarkBASIC Pro: Starting DarkBASIC Pro


Firstly, TEXT makes use of a graphics display mode to create output, PRINT does
not. Because of this, the screen resolution in Activity 2.14 may differ from that used
by the PRINT statement and how output is handled will change.

Activity 2.15

Change your overwrite.dbpro project replacing the SET CURSOR and PRINT
commands with equivalent TEXT statements.

How does the result differ from before?

The second difference is that the TEXT command will only display strings, so a
line such as
TEXT 100, 100, 12

where the statement attempts to display the value 12 is not acceptable and will cause
an error message to appear when you attempt to run the program. Of course, by
enclosing the 12 in quotes you turn it from a number into a string and this would
be accepted:

TEXT 100, 100, “12"

A final difference is that the TEXT command can only be used to display a single
value at a time. Hence, a statement such as

TEXT 100, 100, “Hello”, “again”

would fail since there are two strings in the command. Again, this could be
corrected, this time by joining the two strings:

TEXT 100, 100, “Hello again”

The syntax for the TEXT statement is given in FIG-2.16.


FIG-2.16
The TEXT Statement TEXT x , y , string

In the diagram above:

x,y is a pair of integer values specifying the


position to which the cursor is to be moved.

string is the string value to be displayed on the screen.


All strings should be enclosed in double quotes.

The CENTER TEXT Command


Like most
programming
Whereas the TEXT command starts output at the specified position, CENTER
languages, DarkBASIC TEXT, which uses the same format as TEXT, centres the output horizontally round
Pro keywords use the value given for the x-axis. Hence, the statement
American spelling.
Hence, CENTER and CENTER TEXT 350, 150, “Hello”
not CENTRE.
will display the word Hello as shown in FIG-2.17.

DarkBASIC Pro: Starting DarkBASIC Pro 53


FIG-2.17 The
0 1 2 x-axis
3 4 5 6 (columns)
0
1

Positioning Text Using


2
3
4
The horizontal centre
5
6
of the text is positioned at
CENTER TEXT (350,150)

The y-axis (rows)


The Screen

Activity 2.16

Write a program (project centre.dbpro) to place the word MIDDLE at the


centre of the screen.

The format of the CENTER TEXT statement is given in FIG-2.18.


FIG-2.18
The CENTER TEXT
CENTER TEXT x , y , string
Statement

In the diagram above:

x,y is a pair of integer values specifying the position


where the horizontal centre of the string is to be
output.

string is the string value to be displayed on the screen.

Changing the Output Font


When you display text on your computer, you can choose the size, style, and font
of that text.

We can change the font style and size used when outputting text by using the SET
TEXT FONT and SET TEXT SIZE commands. Once a new font and size has been
set, any subsequent output statements will be done in this style.

The SET TEXT FONT Statement


You have to add a font name in quotes to the end of this statement. Any values
output after this will be shown in that font. For example,

SET TEXT FONT “Courier New”

will result in the Courier New font being used by any subsequent output.

The format for this instruction is given in FIG-2.19.


FIG-2.19
The SET TEXT FONT SET TEXT FONT font name
Statement

54 DarkBASIC Pro: Starting DarkBASIC Pro


In the diagram above:

font name is a string (enclosed in quotes) giving the name of


the font to be used for subsequent output.

The SET TEXT SIZE Statement


The text size is given in points (a point being 1/72 of an inch). For example,

SET TEXT SIZE 20

will result in subsequent output using characters that are 20/72 of an inch tall.

The format of this statement is given in FIG-2.20.


FIG-2.20
The SET TEXT SIZE SET TEXT SIZE point size
Statement

In the diagram above:

point size is an integer value specifying the size of font


(in points) to be used for subsequent output.

The SET TEXT TO Statement


You can also set the text style to produce italics, bold, or bold italics output as well
as the normal default style. This is achieved using the SET TEXT TO commands.
There are four options:
SET TEXT TO BOLD
SET TEXT TO ITALIC
SET TEXT TO BOLDITALIC
SET TEXT TO NORMAL

The following program (LISTING-2.3) outputs the word HELLO in large, bold,
Courier New font:
LISTING-2.3 REM *** Use Courier New size 20 bold ***
SET TEXT FONT “Courier New”
Setting Text Size, Font SET TEXT SIZE 20
and Style SET TEXT TO BOLD
PRINT “HELLO”
WAIT KEY

REM *** Change to italics ***


SET TEXT TO ITALIC
PRINT “HELLO”
WAIT KEY

REM *** Change to bold italics ***


SET TEXT TO BOLDITALIC
PRINT “HELLO”
WAIT KEY

REM *** Change to normal ***


SET TEXT TO NORMAL
PRINT “HELLO”
REM *** End the program ***
WAIT KEY
END

DarkBASIC Pro: Starting DarkBASIC Pro 55


Activity 2.17

Type in and test the program given in LISTING-2.3. Name the project
fonts.dbpro.

Change the code so that all of the text is displayed in Times New Roman.

The format for this statement is shown in FIG-2.21.


FIG-2.21

{ }
BOLD
The SET TEXT TO
Statement
BOLDITALIC
SET TEXT TO
ITALIC

NORMAL

This diagram introduces another new feature. The braces are used to enclose items
which are mutually exclusive alternatives. In other words, the statement is
completed by choosing one of the options given in the braces.

Changing Colours
So far we’ve had white text on a black background, but you’re free to choose any
colours you want for both the text and the background. Before we see how to do
that in DarkBASIC Pro, let’s start with some basic facts about colour.

How Colours are Displayed


Have a close look at your computer monitor. It’s in full colour, showing almost
every colour and shade your eye is capable of seeing. And yet your screen can
generate only three basic colours: red, green and blue.

Every other colour that you see on the screen is made up from those three colours.
For example, to show the colour yellow, the screen combines the colours red and
green; red, green and blue together produce white; when all three basic colours are
switched off, we have black.

This is known as the additive colour process and the colours red, green and blue
are known as the primary colours. The basic colours that can be constructed from
these three primary colours are shown in FIG-2.22.
FIG-2.22
Green
The Additive Colour
Process
Yellow Cyan

White

Red Magenta Blue

As you can see from the figure above, green and blue combine to give a colour

56 DarkBASIC Pro: Starting DarkBASIC Pro


called cyan, while red and blue give magenta.

To create other colours and shades we need only to vary the brightness of the
primary colours. Hence, to create orange we use an intense red, a less intense green,
and no blue.

In computer systems the colour of any spot on the screen is recorded as a series of
three numbers. These numbers represent the intensities of the red, green and blue
(RGB) components (in that order) that make up the colour of the spot. Each number
can range between 0 and 255; 0 means that the colour is not used, while 255 means
that the colour is at full brightness. Hence, a bright yellow spot on the screen will
be recorded as 255, 255, 0, meaning that the red and green are at full intensity, and
the blue is switched off.

The RGB Statement


In DarkBASIC Pro we can define any colour using the RGB statement. This
statement takes three values, enclosed in parentheses. These values define the
intensities of the red, green and blue components that make up the required colour.
The RGB statement combines these three components into a single integer value
which it returns as a result of calling this statement. For example, the statement

PRINT RGB(255,255,0)

will display the integer value representing the colour yellow.

Activity 2.18

Create a new project (colours.dbpro) containing the following code:

PRINT RGB (255,255,0)


WAIT KEY
END

What value is displayed?

Change the values in the RGB command to 255,0,255. What value is


displayed this time?

The syntax for the RGB statement is shown in FIG-2.23.


FIG-2.23
The RGB Statement
RGB ( red , green , blue )

integer

In the diagram:

red is an integer value between 0 and 255

green is an integer value between 0 and 255

blue is an integer value between 0 and 255.

DarkBASIC Pro: Starting DarkBASIC Pro 57


The arrowed line and the term integer signify that this statement returns an integer
value.

How do you find out the red, green and blue values of some particularly nice shade
of orange? Luckily, the DarkBASIC Pro editor can help. If you are busy typing in
a program and suddenly need to supply the three values required by an RGB
statement, you can simply right-click in the edit window. The resulting pop-up menu
(see FIG-2.24) has an RGB Color Picker option which, when selected, displays a
colour palette (see FIG-2.25).
FIG-2.24
The DarkBASIC Pro
Editor’s Pop-Up Menu

Colour values
can be selected
with the help of the
RGB Color Picker option

FIG-2.25
The Colour Palette Box

Selecting a colour from this palette and clicking OK automatically produces an RGB
statement in your program code with the appropriate values to match the colour
selected. We’ll use this in the next Activity.

The INK Statement


In DarkBASIC Pro we can change both the colour used when writing text onto the
screen (known as the foreground colour) and the colour behind that text (known as
the background colour) using the INK. command. This command takes the general
form shown in FIG-2.26.
FIG-2.26
The INK Statement INK foreground , background

In the diagram:

foreground is an integer value representing the colour to be


used for the foreground.

background is an integer value representing the colour to be


used for the background.

The colour values themselves are created using the RGB command. So to have our
text output in yellow on a red background we would use the command:

58 DarkBASIC Pro: Starting DarkBASIC Pro


INK RGB(255,255,0), RGB(255,0,0)

Where you want to use black, rather than use RGB (0, 0, 0) you may simply enter
the value zero. For example, to change the foreground to blue and the background
to black, we would use the statement

INK RGB(0,0,255) ,0

Once you have set the ink colour, any output you do to the screen will be in that
colour. For example, we would expect the program in LISTING-2.4 to display the
word HELLO in yellow on a red background.
LISTING-2.4 REM *** Set yellow foreground and red background ***
INK RGB(255,255,0) , RGB(255,0,0)
Setting Foreground and PRINT “HELLO”
Background Colours
REM *** End program ***
WAIT KEY
END

Activity 2.19

Type in and execute the program in LISTING-2.4 (project colours2.dbpro).

What colour is the background on the screen?

Delete the first RGB command within the INK statement and use the RGB
Color Picker option to replace it with a colour of your choice.

Notice that the background colour in the INK command was set to red and yet the
colour behind the letters is still black. If you want to know why, read on!

There are two main areas to any text that appears on the computer screen: the text
and the text background (see FIG-2.27).

FIG-2.27
Text
Text background
Text Areas

Hello Screen
background

Screen
The foreground colour setting determines the colour of the text itself while the
background colour sets the colour used in the text background. However, normally
the text background is transparent so setting the background colour appears to have
no effect. Usually, a transparent background will be exactly what we want, since it
allows us to do things such as place text on top of an image, and have the image
still show through the text (see FIG-2.28) but, as we’ll see in a moment, we can
change this transparent background setting.

Activity 2.20

Modify your previous program so that the word GOODBYE is displayed in


green after the existing word HELLO.

DarkBASIC Pro: Starting DarkBASIC Pro 59


FIG-2.28
Text with a Transparent
Background

We’ll see how to place


images on the screen later.

The SET TEXT OPAQUE Statement


We can create a block of colour around any text we display by using the SET TEXT
OPAQUE command. The colour used in the text background will be that defined
as the background colour in your INK command. This statement has the format
shown in FIG-2.29.
FIG-2.29
The SET TEXT SET TEXT OPAQUE
OPAQUE Statement

For example, if a program contains the statements

SET TEXT OPAQUE


INK RGB(0,0,255), RGB(255,255,0)
PRINT “Hello”

the word Hello should appear in blue with a yellow background around the text.

Activity 2.21

Add the line SET TEXT OPAQUE to start of your previous program.

Change the program so that the word GOODBYE shows in cyan with a
magenta background.

The SET TEXT TRANSPARENT Statement


Although text normally has a transparent background, if you use the SET TEXT
OPAQUE command, every output statement executed later will have a coloured
background. To return to a transparent background you need to use the statement
SET TEXT TRANSPARENT which has the format shown in FIG-2.30.
FIG-2.30
The SET TEXT
SET TEXT TRANSPARENT
TRANSPARENT
Statement

For example, if a program contains the statements

SET TEXT OPAQUE


INK RGB(0,0,255), RGB(255,255,0)
PRINT “Hello”
SET TEXT TRANSPARENT
PRINT “Goodbye”

60 DarkBASIC Pro: Starting DarkBASIC Pro


Hello will have a yellow background while the word Goodbye would be surrounded
by the black background of the screen.

The CLS Statement


Although when you first run your program it will start with a blank screen, you can
clear everything from the screen at any point in your program by using the CLS
statement (derived from CLear Screen). To use the command, just write the term:

CLS

This gives a empty black screen. However, if you don’t want the screen to be black,
you can clear the screen to another colour by specifying a colour setting in
conjunction with the CLS statement. For example, to create a green screen, use the
line:

CLS RGB(0,255,0)

The format for this statement is shown in FIG-2.31.


FIG-2.31
The CLS Statement
CLS colour

In the diagram:

colour is an integer value representing a colour. The


screen will be filled with this colour after the CLS
statement has been executed.

The program in LISTING-2.5 displays the word HELLO several times using both
opaque and transparent modes. The screen colour is set to red.

REM *** clear screen to red ***


LISTING-2.5 CLS RGB(255,0,0)
REM *** Change text to yellow and the background to green ***
Using Transparent and
INK RGB(255,255,0), RGB(0,255,0)
Opaque Text
REM *** Output the word HELLO with a transparent background ***
PRINT “HELLO”

REM *** Output the word HELLO twice with opaque background ***
SET TEXT OPAQUE
PRINT “HELLO”
PRINT “HELLO”

REM *** Return to transparent output ***


SET TEXT TRANSPARENT
PRINT “HELLO”

REM *** End the program ***


WAIT KEY
END

The output from this program is shown in FIG-2.32.


FIG-2.32
Changing Background
Transparency

DarkBASIC Pro: Starting DarkBASIC Pro 61


Activity 2.22

Type in the program in LISTING-2.5 (backgrounds.dbpro) and check out the


results you obtain.

Activity 2.23

Create a new project (Box) which produces the following output.

*************
* BOX *
*************
Use Courier New, size 20, bold for the text.

The screen background should be red.

The asterisks should be yellow and the word BOX in blue with a black
background.

Summary
l The CLS statement clears the screen using a given colour.

l The PRINT statement can be used to print any type of value.

l A single PRINT statement can display many values.

l The PRINT statement moves the cursor to a new line unless it finishes with a
semicolon.

l The SET CURSOR statement moves the cursor to any position on the screen.

l The TEXT statement will output a single string at any position on the screen.

l The CENTER TEXT statement will output a string centred round a specified
position.

l The INK statement sets the foreground and background colours used.

l The SET TEXT FONT statement sets the font to be used when displaying
information.

l The SET TEXT SIZE statement sets the size to be used in text output.

l The text size is given in points (1/72 of an inch).

l The SET TEXT BOLD statement sets the text style to be used for output to bold.

l The SET TEXT BOLDITALIC statement sets the text style to be used for output
to bold italics.

l The SET TEXT ITALIC statement sets the style to be used for output to italics.

l The SET TEXT NORMAL statement sets the style to be used for output to
normal.

62 DarkBASIC Pro: Starting DarkBASIC Pro


l The SET TEXT OPAQUE statement creates a background colour round any text
that is output.

l The SET TEXT TRANSPARENT statement makes text background transparent.

l The WAIT KEY statement causes the program to halt until any key is pressed.

l The END statement marks the end of the program.

DarkBASIC Pro: Starting DarkBASIC Pro 63


Some Display Techniques
Screen Resolution
Earlier in this chapter you saw how the screen resolution changed when we started
using the TEXT command in place of PRINT and SET CURSOR.

Luckily, we can choose which resolution we want the program’s output to use by
clicking on the brown Settings button at the bottom right of screen. In the resulting
Configure EXE Settings window we can choose the resolution we want to use (see
FIG-2.33).

FIG-2.33
Setting the Screen 1
Resolution Select the type
of display required

Here it is
Fullscreen Exclusive Mode
2
Click on the
Pick button

3
From the Dimensions
combobox, choose the
resolution required

You should consider the following when choosing a resolution.

Ø Output looks better in higher screen resolutions.


Ø Everything looks smaller in higher resolutions.
Ø The memory on your video card may limit what resolutions can be used.
Ø High resolutions take longer to update, so a visually complex game may
seem slower in higher resolutions.

The SET DISPLAY MODE Statement


It is also possible to set the screen resolution and colour depth from within your
program using the SET DISPLAY MODE statement which has the format shown
in FIG-2.34.
FIG-2.34
The SET DISPLAY
MODE Statement
SET DISPLAY MODE width , height , depth

64 DarkBASIC Pro: Starting DarkBASIC Pro


In the diagram:

width is an integer value representing the width of the


display mode required given in pixels.

height is an integer value representing the height of the


display mode required given in pixels.

depth is an integer value representing the number of


bits used to represent a single pixel on the screen.
Typical values are 16, 24 or 32.

To set the screen to a resolution of 1280 by 1024 using 32 bit pixels we would use
the line

SET DISPLAY MODE 1280,1024,32

It is only valid to chose a resolution which can be achieved by your video card and
screen. Attempt to set an invalid resolution will produce an error message.

Choosing a Text Font


The SET TEXT FONT statement allows us to choose a font for any text that we
intend to output. However, that choice depends on what fonts are available on your
computer. You need to also consider what fonts are available on any other
computers that your final software is to be run on. If your game makes use of a font
such as Kidnap and that font is not available to someone who has bought your
program, then the Kidnap font will be missing when your game runs on the buyer’s
machine.

Most fonts are proportional fonts. That is, the horizontal width of a character
depends on what that character is. Hence, w’s take up more width than i’s. You can
see this in the two lines below:

wwwwww
iiiiii

But some fonts are mono-spaced. In this style every character takes up the same
width, as you can see below:

wwwwww
iiiiii

When you’re working in the DarkBASIC Pro editor entering the lines of your
program, the text is displayed in a mono-spaced font, but the default font used by
your program when outputting to the screen is a proportional font.

Erasing Text
Back in Activity 2.15, we saw that when the TEXT command is used to output more
than one item to the same area of the screen it created an unreadable blob. We need
some way of getting rid of the old text before outputting new text at the same
position.

There are two ways to erase text from the screen.

DarkBASIC Pro: Starting DarkBASIC Pro 65


The first of these is to overwrite the text with spaces with the text background set
to opaque. This is demonstrated in LISTING-2.6.

LISTING-2.6 REM *** Set background colour ***


CLS RGB (126,126,126)
Erasing Text Using
Opaque Spaces REM *** Set text font, size, and background colour ***
SET TEXT FONT “Arial”
SET TEXT SIZE 36
INK RGB(255,0,0),RGB(126,126,126)

REM *** Output Text ***


TEXT 100,100,"Hello"
WAIT KEY

REM *** Remove text by writing opaque spaces ***


REM *** at the same position as the original text ***
SET TEXT OPAQUE
TEXT 100,100," “

REM *** End program ***


WAIT KEY
END

Activity 2.24

Type in and test the program given above (TextGone).

There should be 5 spaces between the quotes in the second TEXT statement.

What problem arises? Try to cure the problem.

A second method of erasing text is to overwrite with exactly the same text, but this
time in the background colour. The logic of our strategy is:

Clear screen in required background colour


Set text font, size and colour
Output text
Set foreground colour to match background colour
Output text at same position as before

This logic is implemented in LISTING-2.7.


LISTING-2.7 REM *** Set background colour ***
CLS RGB (126,126,126)
Erasing Text Using The
Same Text in the REM *** Set text font, size, and background colour ***
Background Colour SET TEXT FONT “Arial”
SET TEXT SIZE 36
INK RGB(255,0,0),0

REM *** Output Text ***


TEXT 100,100,"Hello"
WAIT KEY

REM ** Remove text by writing it again in background colour ***


INK RGB(126,126,126),0
TEXT 100,100,"Hello"

REM *** End program ***


WAIT KEY
END

66 DarkBASIC Pro: Starting DarkBASIC Pro


Activity 2.25

Modify your previous project to match the code given above.

Run the program and check that the text (Hello) is correctly erased.

Modify the TEXT statements in the program so that word Goodbye is erased
from position 100,80.

Shadow Text
We can create shadowed text by writing the same text in different colours at slightly

R
offset positions. This needs the following logic:

Set foreground colour to black


Output text
Set foreground colour to red (or some other colour)
Output text at a slightly different position from before

which is coded as:

REM *** Shadow Text ***


INK RGB(0,0,0),0
TEXT 102, 102, “Hello”
INK RGB(255,0,0) ,0
TEXT 100, 100, “Hello”

Activity 2.26

Add the code above to your existing program.


Try modifying the offset value of the black text and see what effect this has on
the display.

Embossed Text
By creating two versions of a text, we achieved shadowed text; by creating three
copies, we can produce an embossed effect.

R To do this we need the following logic:

Clear the screen to grey (or some other colour)


Set foreground to black
Output required text
Set foreground to white
Output required text at an offset position
Set foreground to match background
Output required text at a position between the black and white output.

The code for this is:

CLS RGB(126,126,126)
REM *** Embossed Text ***
INK RGB(0,0,0),0
TEXT 201,201,"Goodbye"
INK RGB(255,255,255),0
TEXT 199,199,"Goodbye"
INK RGB(126,126,126),0
TEXT 200,200,"Goodbye"

DarkBASIC Pro: Starting DarkBASIC Pro 67


Activity 2.27

Add the code above to your existing program.

Try modifying the font, size and colours used as well as the offset values to
create the best effect.

Summary
l The screen resolution used by your program can be set manually using the
Settings button.

l The screen resolution can be set from within your program using the SET
DISPLAY MODE statement.

l In proportional fonts the width of a character depends on the shape of the


character.

l In mono-spaced fonts all characters have the same width.

l Text can be erased from the screen by overwriting it with opaque spaces.

l Text can be removed from the screen by overwriting it with the same text in the
background colour.

l Shadow text can be created by outputting a darker version of the text and then
overwriting it with the same text slightly offset from the original and in a different
colour.

l Embossed text can be created by outputting dark, light, and background


coloured versions of the text. The dark version is written first, then the offset
light text and finally the background coloured text at a mid point between the
dark and light text.

68 DarkBASIC Pro: Starting DarkBASIC Pro


Solutions
Activity 2.1 Version 2:

1. Machine code (or object code) instructions REM *** Display numbers on the separate
2. Compiler lines
3. A syntax error PRINT 1
PRINT 2
PRINT 3
REM *** End program ***
Activity 2.2 WAIT KEY
END
No solution required.
Version 3:
Activity 2.3
REM *** Display numbers on the separate
1. A keyword lines ***
2. Strings PRINT 1
3. Causes the program to pause until a key is pressed. WAIT KEY
PRINT 2
WAIT KEY
PRINT 3
Activity 2.4 REM *** End program ***
WAIT KEY
No solution required.
END

Activity 2.5 Activity 2.10


No solution required.
Program code:

REM *** Shape 1 ***


Activity 2.6 PRINT “**********”
PRINT “**********”
1. Keywords are shown in raised tiles
PRINT “**********”
PRINT “**********”
2. A sunken tile represent information whose exact WAIT KEY
value is determined by the programmer. REM *** Shape 2 ***
PRINT "*"
3. Repeatable elements are shown using a looping PRINT "**"
arrowed line. PRINT "***"
PRINT "****"
PRINT "*****"
Activity 2.7 WAIT KEY
REM *** Shape 3 ***
No solution required. PRINT " *"
PRINT " **"
PRINT " ***"
PRINT " ****"
Activity 2.8 PRINT "*****"
The program code is: REM *** End program ***
WAIT KEY
END
REM *** Print some numbers ***
PRINT 12
PRINT The last shape may not be exact. See Choosing a Text
PRINT 7 Font later in this chapter.
PRINT
PRINT 1.2
REM *** End program *** Activity 2.11
WAIT KEY
END None of the PRINT statements are invalid

Activity 2.9 Activity 2.12


Version 1: The exact values will vary according to your screen
resolution.
REM *** Display numbers on the same line ***
PRINT 1, “ ”, 2, “ ”, 3 The following code will fit a 1280 by 1024 screen
REM *** End program ***
WAIT KEY REM *** A top left ***
END PRINT “A”
REM *** B top right ***
SET CURSOR 1260,0
PRINT “B”

DarkBASIC Pro: Starting DarkBASIC Pro 69


REM *** C bottom left *** displays the value 4294967040
SET CURSOR 0,990
PRINT “C” PRINT RGB(255,0,255)
REM *** D bottom right ***
SET CURSOR 1260,990
PRINT “D” displays 4294902015
REM *** End program ***
WAIT KEY
END Activity 2.19
The background remains black.
Activity 2.13
The word Goodbye overwrites and removes the word Activity 2.20
Hello from the screen.
The program code is:

Activity 2.14 INK RGB(255,255,0), RGB(255,0,0)


PRINT “Hello”
The code for a resolution of 1280 by 1024 is: REM *** Set green foreground ***
INK RGB(0,255,0),0
PRINT “Goodbye”
REM *** A top left ***
REM *** End program ***
TEXT 0,0,"A"
WAIT KEY
REM *** B top right ***
END
TEXT 1260,0,"B"
REM *** C bottom left ***
TEXT 0,990,"C"
REM *** D bottom right *** Activity 2.21
TEXT 1260,990,"D" REM *** Yellow foreground and red background
REM *** End program *** ***
WAIT KEY SET TEXT OPAQUE
END INK RGB(255,255,0), RGB(255,0,0)
PRINT “Hello”
You may find that this program uses a different REM *** Cyan foreg'nd & magenta backg'nd ***
resolution than the earlier version did. INK RGB(0,255,255),RGB(255,0,255)
PRINT “Goodbye”
REM *** End program ***
Activity 2.15 WAIT KEY
END
The program code is:

REM *** Output two strings at same Activity 2.22


location ***
TEXT 100, 100, “Hello” No solution required
WAIT KEY
TEXT 100, 100, “Goodbye”
REM *** End program *** Activity 2.23
WAIT KEY
END The program code is:

The second string writes on top of the first without REM *** Clear screen to red ***
removing it. We'll see a cure for this later in the chapter. CLS RGB(255,0,0)
REM *** Set text characteristics ***
SET TEXT FONT “Courier New”
SET TEXT TO BOLD
Activity 2.16 SET TEXT SIZE 20
REM *** Set colours (yellow and red) ***
For 1248 by 1024, the program code is:
INK RGB(255,255,0),RGB(255,0,0)
REM *** Output box ***
CENTER TEXT 623,500, “MIDDLE” TEXT 0, 0, “**********”
REM *** End program *** TEXT 0,20, “* *”
WAIT KEY TEXT 0,40, “**********”
END REM *** Set opaque text ***
SET TEXT OPAQUE
REM *** Set colours (blue and black) ***
Activity 2.17 INK RGB(0,0,255),RGB(0,0,0)
REM *** Output text ***
The second line of the LISTING-2.3 should be changed TEXT 34,18,"BOX"
to REM *** End program
WAIT KEY
SET TEXT FONT “Times New Roman” END

Activity 2.18
PRINT RGB(255,255,0)
Activity 2.24

70 DarkBASIC Pro: Starting DarkBASIC Pro


The problem can be cured by adding more spaces to the REM *** Embossed Text ***
second TEXT statement. INK RGB(0,0,0),0
TEXT 201, 201, “Goodbye”
INK RGB(255,255,255),0
TEXT 199, 199, "Goodbye"
Activity 2.25 INK RGB(126,126,126),0
REM *** Set background colour *** TEXT 200, 200, "Goodbye"
CLS RGB(126,126,126) REM *** End program ***
REM *** Set text font and size *** WAIT KEY
SET TEXT FONT “Arial” END
SET TEXT SIZE 36
INK RGB (255, 0,0) ,0
REM *** Output Text ***
TEXT 100,80, “Goodbye”
WAIT KEY
REM ** Remove text by writing it again in
background colour ***
INK RGB(126,126,126),0
TEXT 100,80, “Goodbye”
REM *** End program ***
WAIT KEY
END

Activity 2.26
Existing code is in grey:

REM *** Set background colour ***


CLS RGB (126,126,126)
SET TEXT SIZE 36
REM *** Set text font and size ***
SET TEXT FONT “Arial”
SET TEXT SIZE 36
INK RGB (255, 0,0) ,0
REM *** Output Text ***
TEXT 100,80, “Goodbye”
WAIT KEY
REM ** Remove text by writing it again in
background colour ***
INK RGB(126,126,126),0
TEXT 100,80, “Goodbye”
WAIT KEY
REM *** Shadow text ***
INK RGB (0,0,0) ,0
TEXT 102,102, “Hello”
INK RGB (255, 0,0) ,0
TEXT 100, 100, “Hello”
REM *** End program ***
WAIT KEY
END

Activity 2.27
Existing code is in grey:

REM *** Set background colour ***


CLS RGB (126,126,126)
SET TEXT SIZE 36
REM *** Set text font and size ***
SET TEXT FONT “Arial”
SET TEXT SIZE 36
INK RGB (255, 0,0) ,0
REM *** Output Text ***
TEXT 100,80, “Goodbye”
WAIT KEY
REM ** Remove text by writing it again in
background colour ***
INK RGB(126,126,126),0
TEXT 100,80, “Goodbye”
WAIT KEY
REM *** Shadow text ***
INK RGB (0,0,0) ,0
TEXT 102,102, “Hello”
INK RGB (255, 0,0) ,0
TEXT 100, 100, “Hello”

DarkBASIC Pro: Starting DarkBASIC Pro 71


72 DarkBASIC Pro: Starting DarkBASIC Pro
3

Arithmetic Operators

Assignment Statement

Constants

Creating Random Numbers

Input Statement

RANDOMIZE and RND Statements

READ, DATA and RESTORE Statements

String Operations

Testing Sequential Structures

Variables

Variable Names

DarkBASIC Pro: Data 73


Program Data
Introduction
Every computer game has to store and manipulate facts and figures (more
commonly known as data). For example, a program may store the name of a player,
the number of lives remaining or the time the player has remaining in which to
complete a task.

We group information like this into three basic types:

integer - any whole number, positive, negative or zero


real - any number containing a decimal point
strings - any collection of characters (may include numeric characters)

For example, if player Daniel McLaren had 3 lives and 10.6 minutes to complete a
game, then:

3 is an example of an integer value,


10.6 is a real value,
and Daniel McLaren is an example of a string.

Activity 3.1

Identify which type of value each of the following is:

a) -9 f) 0
b) abc g) -3.0
c) 18 h) Mary had a little lamb
d) 12.8 i) 4 minutes
e) ? j) 0.023

Constants
When a specific value appears in a computer program’s code it is usually referred
to as a constant. Hence, in the statement

PRINT 7

the value 7 is a constant. More specifically, we may refer to constant’s type. In the
line

PRINT “Charlotte”, 15, 42.7

Charlotte is a string constant, 15, an integer constant, and 42.7, a real constant.
Note that in DarkBASIC Pro, string constants always appear within double quotes.

Activity 3.2

Identify the constant types in the following line of code:

PRINT “Mary is ”, 12, “ years old”

74 DarkBASIC Pro: Data


Variables
Most programs not only need to display data, but also need to store data and calculate
results. To do this in DarkBASIC Pro we need to use a variable. A variable is simply
somewhere to store a value. Every variable in a program is assigned a unique name
and can store a single value. That value might be an integer, a real or a string but
each variable is designed to store only one type of value. Hence, a variable designed
to store an integer value cannot store a string.

Integer Variables
In DarkBASIC Pro variables are created automatically as soon as we mention them
in our code. For example, let’s assume we want to store the number of lives allocated
to a game player in a variable called lives. To do this in DarkBASIC Pro we simply
write the line:

lives = 3

This sets up a variable called lives and stores the value 3 in that variable (see
FIG-3.1)
FIG-3.1
lives Value stored
Storing Data in a in the variable
Variable name 3
Variable

This is known as an assignment statement since we are assigning a value (3) to a


variable (lives).

You are free to change the contents of a variable at any time by just assigning it a
different value. For example, we can change the contents of lives with a line such
as:

lives = 2

When we do this any previous value will be removed and the new value stored in
its place (see FIG-3.2).
FIG-3.2 The contents of
lives lives are changed
Changing the Value in a
Variable 2

The variable lives is designed to store an integer value. In the lines below, a, b, c,
d, and e are also integer variables. So the following assignments are correct
a = 200
b = 0
c = -8

but the lines below are wrong


d = 3.14
e = -1.9

since they attempt to store real constants in variables designed to hold an integers.
DarkBASIC Pro won’t actually report an error if you try out these last two examples,
it simply ignores the fractional part of the numbers and ends up storing 3 in d and
1 in e (see FIG-3.3).

DarkBASIC Pro: Data 75


d e
FIG-3.3
d = 3.14 3 e = -1.9 -1
Trying to Copy a Real
Value to an Integer
Variable Only the integral part of
each number is stored

Real Variables
If you want to create a variable capable of storing a real number, then we must end
the variable name with the hash (#) symbol. For example, if we write

d# = 3.14
e# = -1.9

we have created variables named d# and e#, both capable of storing real values(see
FIG-3.4).
FIG-3.4 d# e#
d# = 3.14 3.14 e# = -1.9 -1.9
Creating Real Variables

The complete
number is stored

Any number can be stored in a real variable, so we could also write a statement such
as:

d# = 12

and this will be stored as 12.0.

If any value can be stored in a real variable, why bother with integer variables?
Actually, you should always use integer values wherever possible because the
computer is much faster at handling integer values than reals which require much
more processing whenever you want to do any calculations. Also, real numbers can
be slightly inaccurate because of rounding errors within the machine. For example,
the value 2.3 might be stored as 2.2999987.

String Variables
Finally, if you want to store a string value, you need to use a string variable. String
variable names must end with a dollar ($) sign. The value to be stored must be
enclosed in double quotes. We could create a string variable named player$ and
store the name Liz Heron in it using the statement:
player$ = “Liz Heron”

The double quotes are not stored in the variable (see FIG-3.5).
FIG-3.5 player$

Creating String player$ = “Liz Heron” Liz Heron


Variables
Everything within ... is stored in
the quotes... the variable

Absolutely any value can be stored in a string variable as long as that value is
enclosed in double quotes. Below are a few examples:

76 DarkBASIC Pro: Data


a$ = “?>%”
b$ = “Your spaceship has been destroyed”
c$ = “That costs $12.50"

Activity 3.3

Which of the following are valid DarkBASIC Pro statements that will store
the specified value in the named variable?

a) a = 6 d) d# = 5
b) b = 12.89 e) e$ = ‘Goodbye’
c) c$ = Hello f) f# = -12.5

Using Meaningful Names


It is important that you use meaningful names for your variables when you write a
program. This helps you remember what a variable is being used for when you go
back and look at your program a month or two after you wrote it.

So, rather than write statements such as

a = 3
b = 120
c = 2000

a better set of statements would be

lives = 3
points = 120
timeremaining = 2000

which give a much clearer indication of what the variables are being used for.

Naming Rules
DarkBASIC Pro, like all other programming languages, demands that you follow
a few rules when you make up a variable name. These rules are:

Ø The name should start with a letter.


Ø Subsequent characters in the name can be a letter, number, or underscore
Ø The final character can be a # (when creating real variables) or $ (when
creating string variables).
Ø Upper or lower case letters can be used, but such differences are ignored.
Hence, the terms total and TOTAL refer to the same variable.
Ø The name cannot be a DarkBASIC Pro keyword.
This means that variable names such as

a
bc
de_2
fgh$
iJKlmnp#

are valid, while names such as

DarkBASIC Pro: Data 77


2a
time remaining

are invalid.

The most common mistake people make is to have a space in their variable names
(e.g. fuel level). This is not allowed. As a valid alternative, you can replace the space
with an underscore (fuel_level) or join the words together (fuellevel). Using capital
letters for the joined words is also popular (FuelLevel).

Note that the names no, no# and no$ represent three different variables; one
designed to hold an integer value (no), one a real value (no#) and the last a string
(no$).

Activity 3.4

Which of the following are invalid variable names:

a) x e) total score
b) 5 f) ts#o
c) “total” g) end
d) al2$ h) G2_F3

Summary
l Fixed values are known as constants.

l There are three types of constants: integer, real and string.

l String constants are always enclosed in double quotes.

l The double quotes are not part of the string constant.

l A variable is a space within the computer’s memory where a value can be stored.

l Every variable must have a name.

l A variable’s name determines which type of value it may hold.

l Variables that end with the # symbol can hold real values.

l Variables that end with the $ symbol can hold string values.

l Other variables hold integer values.

l The name given to a variable should reflect the value held in that variable.

l When naming a variable the following rules apply:

The name must start with a letter


Subsequent characters in the name can be numeric, alphabetic or the
underscore character.
The name may end with a # or $ symbol.
The name must not be a DarkBASIC Pro keyword.

78 DarkBASIC Pro: Data


Allocating Values to Variables
Introduction
There are several ways to place a value in a variable. The DarkBASIC Pro
statements available to achieve this are described below.

The Assignment Statement


In the last few pages we’ve used DarkBASIC Pro’s assignment statement to store
a value in a variable. This statement allows the programmer to place a specific value
in a variable, or to store the result of some calculation.

In its simplest form the assignment statement has the form shown in FIG-3.6.
FIG-3.6
The Assignment variable = value
Statement

The value copied into the variable may be one of the following types:

Ø a constant
Ø another variable
Ø an arithmetic expression
Examples of each are shown below.

Assigning a Constant
This is the type of assignment we’ve seen earlier, with examples such as

name$ = “Liz Heron”

where a fixed value (a constant) is copied into the variable. Make sure that the
constant is the same type as the variable. For instance, the statement

desc = “tall”

is invalid since it attempts to copy a string constant (“tall”) into an integer variable
(desc). Not every mistake will be signalled by the compiler. For example, if we try
to assign a real constant to an integer variable as in the statement
result = 12.79

the integer variable result stores only the integral part of the constant (i.e. 12), the
fractional part being lost.

However, an integer value may be copied into a real variable, as in the line:

result# = 33

The program deals with this by storing the value assigned to result# as 33.0.

DarkBASIC Pro: Data 79


Activity 3.5

What are the minimum changes required to make the following statements
correct?

1. desc = “tall”
2. result = 12.34

Copying a Variable’s Value


Once we’ve assigned a value to a variable in a statement such as

no1 = 12

we can copy the contents of that variable into another variable with a command
such as:

no2 = no1

The effect of these two statements is shown in FIG-3.7.


FIG-3.7 no1 no2 no1
Copying One Variable’s no1 = 12 12 no2 = no1 12 12
Value to Another
Variable The value held in no1
is copied into no2

As before, you must make sure the two variables are of the same type, although the
contents of an integer variable may be copied to a real variable as in the lines:

ans# = no1

Although not invalid, trying this the other way round (real copied to integer) as in

ans# = 12.94
no1 = ans#

will cause no1 to store only the integral part of ans# contents (i.e. 12).

Activity 3.6

Assuming a program starts with the lines:

no1 = 23
weight# = 125.8
description$ = “sword”

which of the following instructions would be invalid?

a) no2 = no1 d) ans# = no1


b) no3 = weight# e) abc$ = weight#
c) result = description$ f) m# = description$

Copying the Result of an Arithmetic Expression


Another variation for the assignment statement is to perform a calculation and store

80 DarkBASIC Pro: Data


the result of that calculation. Hence we might write

no1 = 7 + 3

which would store the value 10 in the variable no1.

The example shows the use of the addition operator, but there are 5 possible
operators that may be used when performing a calculation. These are shown in
TABLE-3.1.
TABLE-3.1 Operator Function Example

Arithmetic Operators + Addition no1 = no2 + 5


- Subtraction no1 = no2 - 9
* Multiplication ans = no1 * no2
/ Division r1# = no1 / 2
mod Remainder ans = no2 mod 3
^ Power ans = 2 ^ 24

The result of most statements should be obvious. For example, if a program begins
with the statements

no1 = 12
no2 = 3

and then contains the line

total = no1 - no2

then the variable total will contain the value 9, while the line

product = no1 * no2

stores the value 36 in the variable product.

The remainder operator (mod) is used to find the integer remainder after dividing
one integer into another. For example,
ans = 9 mod 5

assigns the value 4 to the variable ans since 5 divides into 9 once with a remainder
of 4. Other examples are given below:

6 mod 3 gives 0
7 mod 9 gives 7
123 mod 10 gives 3

If the first value is negative, then any remainder is also negative:


-11 mod 3 gives -2

Activity 3.7

What is the result of the following calculations:

a) 12 mod 5 c) 5 mod 11
b) -7 mod 2 d) -12 mod -8

The power operator ( ^ ) allows us to perform a calculation of the form xy. For
example, a 24-bit address bus on the microprocessor of your computer allows 224

DarkBASIC Pro: Data 81


memory addresses. We could calculate this number with the statement:

addresses = 2^24

However, the results of some statements are not quite so obvious. The line

ans# = 19/4

will result in the value 4.0 being stored in ans# since the division operator always
returns an integer result if the two values involved are both integer. On the other
hand, if we write

ans# = 19/4.0

and thereby use a real value, then the result stored in ans# will be 4.75.

When a real value is copied into an integer variable, the fractional part of the value
being copied is lost. For example, the variable result would contain the value 4 after
executing the line

result = 19/4.0

When using the division operator, a second situation that you must guard against is
division by zero. In mathematics, dividing any number by zero gives an undefined
result, so computers get quite upset if you try to get them to perform such a
calculation. Hence, the line
ans = 10/0

would cause a program to crash when it attempted to perform that line in the
program. You might be tempted to think that you would never write such a
statement, but a more likely scenario is that your program contains a line such as

ans = no1 / no2

and if no2 contains the value zero attempting to execute the line will still cause the
program to terminate.

Some statements may not appear to make sense if you are used to traditional algebra.
For example, what is the meaning of a line such as:
no1 = no1 + 3

In fact, it means add 3 to no1. See FIG-3.8 for a full explanation.

FIG-3.8
no1
Adding to a Variable’s 20
no1 is assigned
Contents an initial value

no1 = 20

no1 = no1 + 3
3 is added to ...
no1
... the current value of no1 ...
23
... and the result stored in no1

82 DarkBASIC Pro: Data


Another unusual assignment statement is:

no1 = -no1

The effect of this statement is to change the sign of the value held in no1. For
example, if no1 contained the value 12, the above statement would change that value
to -12. Alternatively, if no1 started off containing the value -12, the above statement
would change no1‘s contents to 12.

Activity 3.8

Assuming a program starts with the lines:

no1 = 2
v# = 41.09

what will be the result of the following instructions?

a) no2 = no1^4 d) no4 = no1 + 7


b) x# = v#*2 e) m# = no1/5
c) no3 = no1/5 f) v2# = v# - 0.1

Of course, an arithmetic expression may have several parts to it as in the line

answer = no1 - 3 / v# * 2

and, how the final result of such lines is calculated is determined by operator
precedence.

Operator Precedence
If we have a complex arithmetic expression such as

answer# = 12 + 18 / 3^2 - 6

then there’s a potential problem about what should be done first. Will we start by
adding 12 and 18 or subtracting 6 from 2, raising 3 to the power 2, or even dividing
18 by 3. In fact, calculations are done in a very specific order according to a fixed
set of rules. The rules are that the power operation (^ ) is always done first. After
that comes multiplication and division with addition and subtraction done last. The
power operator ( ^ ) is said to have a higher priority than multiplication and division;
they in turn having a higher priority than addition and subtraction.

So, to calculate the result of the statement above the computer begins by performing
the calculation 3^2 which leaves us with:
answer = 12 + 18 / 9 - 6

Next the division operation is performed (18/9) giving

answer = 12 + 2 - 6

The remaining operators, + and -, have the same priority, so the operations are
performed on a left-to-right basis meaning that we next calculate 12+2 giving

answer = 14 - 6

DarkBASIC Pro: Data 83


Finally, the last calculation (14 -6) is performed leaving

answer = 8

and the value 8 stored in the variable answer.

Activity 3.9

What is the result of the calculation 12 - 5 * 12 / 10 - 5

Using Parentheses
If we need to change the order in which calculations within an expression are
performed, we can use parentheses. Expressions in parentheses are always done
first. Therefore, if we write

answer = (12 + 18) / 9 - 6

then 12+18 will be calculated first, leaving:

answer = 30 / 9 - 6

This will continue as follows:

answer = 3.3333 - 6
answer = -2.6667

An arithmetic expression can contain many sets of parentheses. Normally, the


computer calculates the value in the parentheses by starting with the left-most set.

Activity 3.10

Show the steps involved in calculating the result of the expression


8 * (6-2) / (3-1)

If sets of parentheses are placed inside one another (this is known as nested
parentheses) , then the contents of the inner-most set is calculated first. Hence, in
the expression

12 / (3 * (10 - 6) + 4)

the calculation is performed as follows:

(10 - 6) giving 12 / (3*4+4)


3 * 4 giving 12 / (12 + 4)
12 + 4 giving 12 / 16
12 / 16 giving 0.75

Activity 3.11

Assuming a program begins with the lines


no1 = 12
no2 = 3
no3 = 5
what would be the value stored in answer as a result of the line
answer = no1/(4 + no2 - 1)*5 - no3^2 ?

84 DarkBASIC Pro: Data


Variable Range
When first learning to program, a favourite pastime is to see how large a number
the computer can handle, so people write lines such as:
no1 = 1234567890

They are often disappointed when the program crashes at this point.

There is a limit to the value that can be stored in a variable. That limit is determined
by how much memory is allocated to a variable, and that differs from language to
language. The range of values that can be stored in DarkBASIC Pro variables is
shown in TABLE-3.2.
TABLE-3.2 Variable Type Range of Values
Variable Range
integer -2,147,483,648 to + 2,147,483,647
real ±3.4 E ± 38

String Operations
The + operator can also be used on string values to join them together. For example,
if we write

a$ = “to” + “get”

then the value toget is stored in variable a$. If we then continue with the line

b$ = a$ + “her”

b$ will contain the value together, a result obtained by joining the contents of a$ to
the string constant “her”.

Activity 3.12

What value will be stored as a result of the statement


term$ = “abc”+"123"+"xyz"

The PRINT Statement Again


We’ve already seen that the PRINT command can be used to display values on the
screen using lines such as:

PRINT 12
PRINT “Hello”

We can also get the PRINT statement to display the answer to a calculation. Hence,

PRINT 7+3

will display the value 10 on the screen, while the statement

PRINT “Hello ” + “again”

displays Hello again.

DarkBASIC Pro: Data 85


The PRINT statement can also be used to display the value held within a variable.
This means that if we follow the statement

number = 23

by the line

PRINT number

our program will display the value 23 on the screen, this being the value held in
number. Real and string variables can be displayed in the same way. Hence the lines

name$ = “Charlotte”
weight# = 95.3
PRINT name$
PRINT weight#

will produce the output

Charlotte
95.3

Activity 3.13

A program contains the following lines of code:


number = 23
PRINT “number”
PRINT number
What output will be produced by the two PRINT statements?

Activity 3.14

Type in and test the following program (don’t bother to save the program):

number = 23
PRINT number
WAIT KEY
END

Change the program by removing the first two lines and replacing this with
two statements which will assign the value Jessica McLaren to a variable
called name$ and then display the contents of name$ on the screen.

The PRINT statement can display more than one value at a time. For example, we
can get it to display the number 12 and the word Hello at the same time by writing
PRINT 12,"Hello"

Each value we want displayed must be separated from the next by a comma. We
can use this to display a message alongside the contents of a variable. For example,
the lines

capital$ = “Washington”
PRINT “The capital of the USA is ”, capital$

produce the following output on the screen:

The capital of the USA is Washington

86 DarkBASIC Pro: Data


Activity 3.15

Write a program (name.dbpro) that sets the contents of the variable name$ to
Jessica MacLaren and then uses a PRINT statement that displays the contents
of name$ in such a way that the final message on the screen becomes:

Hello, Jessica MacLaren, how are you today?

Other Ways to Store a Value in a Variable


The INPUT Statement
There will be many values which we cannot know when we are writing the program.
For example, we can’t know the name of the player until someone sits down at the
computer and begins to play our game. The only way we can get access to that sort
of information is to ask the player to type in the information the program requires.
This is done with the INPUT statement. In its simplest form the INPUT keyword
is followed by the name of the variable where we’d like to store the information the
player types in. For example, we might write

INPUT name$

expecting the person at the keyboard to type in their name and then storing what
they type in the variable name$. Of course, the player has to be told what sort of
information they are expected to enter, so we could precede the INPUT statement
with a message telling them what to type in :

PRINT “Please enter your name ”


INPUT name$

DarkBASIC Pro makes things simpler than this by allowing us to include the
message we want displayed as part of the INPUT statement. Hence, we can achieve
the same effect as the two statements above using the line:

INPUT “Please enter your name ”, name$

This gives us the final format for the INPUT statement as shown in FIG-3.9.

FIG-3.9
The INPUT Statement INPUT [ message , variable

In the diagram:

message is a string (enclosed in double quotes) which is


displayed before any data from the keyboard is
accepted.

variable is a variable name. The value entered by the user


at the keyboard will be assigned to this variable.
It is the user’s responsibility to enter a value of
the correct type.

DarkBASIC Pro: Data 87


Activity 3.16

Which of the following are valid INPUT statements?

a) INPUT age
b) INPUT “Enter your height ”, height#
c) INPUT “Enter your salary ” salary

Activity 3.17

Type in and run the following program (input01.dbpro):

INPUT “Player 1, enter your name :”,name$


PRINT “Hello, ”,name$
WAIT KEY
END

We can use the INPUT statement anywhere in our program and as often as
necessary.

Activity 3.18

Modify your last program so that it also reads in the age of the player and
displays a message of the form:

Hello, {name goes here}, I see you are {age goes here} years old.

The READ and DATA Statements


There are times when we want to assign a value to a variable, but we don’t want to
have to enter that value from the keyboard. For example, let’s say a variable,
daysinmonth, is used to store how many days are in January. The contents of
daysinmonth is then to be displayed. After this the program stores within
daysinmonth the number of days in a normal February. Again, the contents of
daysinmonth is displayed. This continues until every month of the year has been
dealt with.

We could start the coding for this as:

daysinmonth = 31
PRINT daysinmonth
daysinmonth = 28
PRINT daysinmonth
daysinmonth = 31
PRINT daysinmonth

Alternatively, we can set up the values we intend to assign to daysinmonth in a


DATA statement:

DATA 31,28,31,30,31,30,31,31,30,31,30,31

and then use a READ statement every time we want to assign a value to
daysinmonth.
READ daysinmonth

88 DarkBASIC Pro: Data


The value given to daysinmonth by the READ statement will be the first value listed
in the DATA statement. When another READ statement is executed, the second
value from the DATA statement will be used. We can therefore rewrite the
statements given earlier as:

DATA 31,28,31,30,31,30,31,31,30,31,30,31
READ daysinmonth
PRINT daysinmonth
READ daysinmonth
PRINT daysinmonth
READ daysinmonth
PRINT daysinmonth

The operation of these statements is shown in FIG-3.10.


FIG-3.10
Using DATA and READ DATA 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31

The DATA statement contains


the values to be read
daysinmonth

31
READ daysinmonth
Each READ statement causes
another value to be taken from
the DATA statement READ daysinmonth
daysinmonth

28

Is this second approach any better than the first? You should have noticed that by
using the DATA/READ approach we repeat exactly the same statements over and
over again. In a later chapter we will see that this code can be shortened by using a
loop statement which would not be possible with the first approach.

Several DATA statements may be used by a program, so we might write:


DATA 31, 28
DATA 31, 30

The computer simply groups the values given in the DATA statements into a single
list, so the two DATA statements above have exactly the same effect as:
DATA 31,28,31,30

The DATA statement can contain values of any type. The next example stores the
names of the first three days of the week:

DATA “Sunday”, “Monday”,"Tuesday"

Of course, when you read from this DATA statement, the variable being assigned
the value must be a string:

READ day$

The type of values in a DATA statement can even be mixed, containing integer,
real or string constants in any order. It is only important that READ statements use
the type of variable appropriate to the next value coming from the DATA statement.

We might write
DATA 12, 2.7, “Hello”

DarkBASIC Pro: Data 89


followed by

READ no1
READ x#
READ word$

and this would be acceptable because variables and values being read are of
matching types. That is, the first READ statement would assign the integer value
12 to the integer variable no1; the second READ would assign the real value 2.7 to
the real variable x# and the third READ would assign the string “Hello” to the string
variable word$. It’s also possible to read the value of more than one variable in a
single READ statement. Hence, we could reduce the three statements above to the
single line:

READ no1, x#, word$

A DATA statement can be placed anywhere in your program. Often it is placed at


the start or end of a program where it can easily be found should the values it holds
need to be examined or changed.

The format for the DATA statement is shown in FIG-3.11 and the format of the
READ statement is shown in FIG-3.12.
FIG-3.11
The DATA Statement DATA constant

,
In the diagram:

constant represents any fixed value. This value can be an


integer, real, or string.
FIG-3.12
The READ Statement READ variable

,
In the diagram:

variable is any variable name. The variable named will


be assigned the next available value from the
DATA statement.

An error will be reported if your program contains a READ statement but no DATA
statement. An error will also occur if a READ statement is executed after all the
values in the DATA statement have been used.

Activity 3.19

Write a short program (days01.dbpro) which displays the names of the days of
the week. Start with Sunday.

The names should be set up in a DATA statement, then accessed using a series
of READ statements.

90 DarkBASIC Pro: Data


The RESTORE Statement
DarkBASIC Pro knows which value is to be used next from a DATA statement by
keeping a marker which indicates which value in the statement is to be used when
the next READ statement is executed.

Initially this marker points to the first value in the first DATA statement. After each
READ the marker moves on one position. However, it is possible to return the
marker to the start of the DATA list by executing the RESTORE statement.

For example, in the code

DATA 3,6,9,12
READ no1
READ no2
RESTORE
READ no3

the variable no3 will be assigned the value 3 because the RESTORE statement will
have moved the DATA marker back to the first value in the list.

The RESTORE statement has the format shown in FIG-3.13.


FIG-3.13
The RESTORE Statement RESTORE

Activity 3.20

Modify your last program so that after all the days of the week have been
displayed the word Sunday is displayed for a second time.

You can achieve this result by adding a RESTORE statement, another READ
statement and a PRINT statement to your program.

The Time and Date


The TIMER Statement
DarkBASIC Pro contains a command that lets you find out how long your computer
has been switched on. This is the TIMER statement which returns an integer
specifying the number of milliseconds that have passed since your machine was last
powered up. This information is actually maintained by the operating system and
the DarkBASIC Pro statement interrogates the area of computer memory where this
data is held.

The TIMER statement has the format given in FIG-3.14.

FIG-3.14
TIMER ( )
The TIMER Statement

integer

DarkBASIC Pro: Data 91


Notice that the parentheses must be included in the statement even though no
information is placed within them. DarkBASIC Pro’s general syntax demands that
any statement that returns a value must always have parentheses.

So the TIMER statement could be used to display how long your machine has been
on with the single line

PRINT TIMER ()

but this would be in milliseconds. Perhaps a better option would be to save the value
returned by TIMER and convert that value to seconds, as in the lines:

millisecondsPassed = TIMER()
seconds = millisecondsPassed / 1000
PRINT “Your computer has been on for ”, seconds, “ seconds”

Activity 3.21

Create a project (minutes.dbpro) which displays how many minutes have


passed since your computer was last switched on.

By using TIMER before and after some event we can measure how long that event
lasts. For example, we could create a simple reaction time game by seeing how
quickly the user can press a key after being told to do so. Such a program requires
the following logic:

Display “Press any key”


Record the start time
Wait for a key press
Record the finish time
Calculate the duration as finish time minus the start time
Display the duration

Activity 3.22

Create a project (reaction.dbpro) that implements the logic given above.

The GET TIME$ Statement


If we need to get the actual time of day then we can use the TIME$ statement which
returns a string giving the current time (as obtained from the system clock) in the
form HH:MM:SS, where HH is the hour (0 to 23), MM is the minutes, and SS the
seconds.

The format for this statement is given in FIG-3.15.

FIG-3.15
The GET TIME$
GET TIME$ ( )
Statement

string
For example, we could display the current time using the line:

PRINT GET TIME$()

92 DarkBASIC Pro: Data


The GET DATE$ Statement
The current date can be returned as a string using the GET DATE$ statement which
has the format shown in FIG-3.16.
FIG-3.16
The GET DATE$
GET DATE$ ( )
Statement

string
The string returned is in the American form MM/DD/YY. For example, when run
at the time of writing, the statement

PRINT GET DATE$()

displayed the output 07/16/05.

Generating Random Numbers


Often in a game we need to throw a dice, choose a card or think of a number. All
of these are random events. That is to say, we cannot predict what value will be
thrown on the dice, what card will be chosen, or what number some other person
will think of.

The RND Statement


There is a need to get computer programs to emulate this randomness and this is
done using the RND statement. In fact, like RGB, RND is a function. It will generate
an integer value within a specified range and return that generated value. For
example, if we wanted to display a random number between 0 and 10, we could
write

PRINT RND(10)

RND has to be supplied with a value enclosed in parentheses. This value lets the
command know what range of possible values may be generated. Notice that the
lowest value that can be generated is always zero, while the largest value is equal
to the number given in the brackets.

Activity 3.23

What expression would we use if we wanted to create a random number in the


range 0 to 48?

The format for the RND statement is given m FIG-3.17.


FIG-3.17
The RND Statement RND ( max )

integer

DarkBASIC Pro: Data 93


In the diagram:

max is any positive integer value. The command will


return an integer in the range 0 to max.

The value given within the parentheses can also be a variable or arithmetic
expression, as in the lines:

num = 25
PRINT RND (num) ‘0 to 25
PRINT RND (num*2-3) ‘0 to 47

The value returned by RND could be stored in a variable using a statement such as:
number = RND(10)

If RND(5) generates a number between 0 and 5, how are we going to emulate a dice
throw which gives values 1 to 6? Often people suggest writing RND(6), but this
gives values in the range 0 to 6, not 1 to 6.

Instead we have to generate a value between 0 and 5 and then add 1 to that number.

We could do this with the line

diceThrow = RND(5)+1

and follow this with a PRINT statement displaying the contents of diceThrow:

PRINT “You threw a ”,diceThrow

The RANDOMIZE Statement


Computers can’t really think of a random number all by themselves. Actually, they
cheat and use a mathematical formula to calculate an apparently random number.
As long as you don’t know that formula, you won’t be able to predict what number
the computer is going to come up with.

But to get the mathematics started correctly, we need to supply it with a start up
value or seed value. Effectively this seed value determines what numbers the
computer is going to generate when RND is used.

The seed value is set up using the RANDOMIZE statement which has the format
shown in FIG-3.18.
FIG-3.18
The RANDOMIZE
Statement RANDOMIZE seed

In the diagram:

seed is an integer value which is used as a start-up


value for the random number generator.

Exactly what seed value you use doesn’t really matter, but if you start with the same
seed value every time, you’ll always get the same set of values from RND. For
example, if a program contained the lines

94 DarkBASIC Pro: Data


RANDOMIZE 12345
PRINT RND(50)
PRINT RND(12)

every time that program is executed, the same numbers would be displayed.

To stop this happening we need to make sure that the seed value is different every
time we run a program. We can achieve this using the TIMER statement. So if we
write
number = TIMER()
RANDOMIZE number

then, since TIMER will return a different value every time it’s carried out
(remember the time in your computer is being updated 1000 times per second), the
seed value for RANDOMIZE will always be different. Actually, we can combine
the two statements above into one:

RANDOMIZE TIMER()

Now we are ready to write a program using random numbers. The program in
LISTING-3.1 simulates a dice throw and displays the number generated.

LISTING-3.1 REM *** Generate random number ***


RANDOMIZE TIMER()
Displaying a Random number = RND(5)+1
Number
REM *** Display number ***
PRINT number

REM *** End program ***


WAIT KEY
END

Activity 3.24

Type in and run the program given above (random.dbpro).


Modify the program so that it generates a number between 1 and 49.

Activity 3.25

Write a program (guess01.dbpro) that performs the following logic:

Computer thinks of a number between 1 and 100

User (you) enters their guess at what the number is

The computer displays both the guess and the original number

Structured English and Programs


When we write a structured English algorithm with the intention of turning that
algorithm into a computer program, we always write the algorithm as if we are
telling the computer what it has to do. Therefore, the rather long winded algorithm
in the Activity above would be better written as:

Generate a random integer between 1 and 100


Get user’s guess
Display number and guess

DarkBASIC Pro: Data 95


Using Variables to Store Colour Values
We’ve seen how the value generated by the RND statement can be stored in a
variable with a statement such as:
number = RND(5)+1

Since the RGB statement also returns a value, we can use that same approach there.
So rather than write

INK RGB(255,0,0),RGB(0,255,0)

we could write

colour1 = RGB(255,0,0)
colour2 = RGB(0,255,0)
INK colour1, colour2

Activity 3.26

Write a program (colours03.dbpro) that performs the following operations

Assigns the colour red to a variable called scarlet;


Assigns the colour blue to a variable called sky;
Clears the screen to create red blank screen (use scarlet);
Writes the word Ocean in blue on the screen (use sky)

Named Constants
When a program uses a fixed value which has an important role (for example,
perhaps the value 1000 is the score a player must achieve to win a game), then we
have the option of assigning a name to that value using the #CONSTANT statement.

The format of this statement is shown in FIG-3.19.


FIG-3.19
The #CONSTANT
statement
#CONSTANT name
[ = value

In the diagram:

name is the name to be assigned to the constant value.

value is the constant value being named.

For example, we can name the value 1000 WinningScore using the line:

#CONSTANT WinningScore = 1000

Since the equal sign ( = ) is optional, it is also valid to write:

#CONSTANT WinningScore 1000

Real and string constants can also be named, but the names assigned must NOT end
with # or $ symbols. Therefore the following lines are valid

96 DarkBASIC Pro: Data


#CONSTANT Pi = 3.14159265
#CONSTANT Vowels = “aeiou”

The value assigned to a name cannot be changed, so having written


#CONSTANT WinningScore = 1000

it is not valid to try to assign a new value with a line such as:

WinningScore = 1900

The two main reasons for using named constants in a program are:

1) Aiding the readability of the program. For example, it is easier to


understand the meaning of the line

IF playerscore >= WinningScore

than

IF playerscore >= 1000

2) If the same constant value is used in several places throughout a


program, it is easier to change its value if it is defined as a named
constant. For example, if, when writing a second version of a game we
decide that the winning score has to be changed from 1000 to 2000,
then we need only change the line

#CONSTANT WinningScore = 1000

to

#CONSTANT WinningScore = 2000

On the other hand, if we’ve used lines such as

IF playerscore >= 1000

throughout our program, every one of those lines will have to be


changed so that the value within them is changed from 1000 to 2000.

Testing Sequential Code


The programs in this chapter are very simple ones, with the statements being
executed one after the other, starting with the first and ending with the last. In other
words, the programs are sequential in structure.

Every program we write needs to be tested. For a simple sequential program that
involves input, the minimum testing involves thinking of a value to be entered,
predicting what result this value should produce, and then running the program to
check that we do indeed obtain the expected result.

The program below (see LISTING-3.2) reads in a value from the keyboard and
displays the square root of that number.

DarkBASIC Pro: Data 97


LISTING-3.2 INPUT “Please enter your number : ”, number#
squareroot# = number#^0.5
Calculating the Square PRINT “The square root of ”, number#, “ is ”,squareroot#
Root of a Value WAIT KEY
END

To test this program we might decide to enter the value 16 with the expectation of
the result being 4.

Activity 3.27

Type in the program given above (root.dbpro) and test it by inputting the
value 16.

Perhaps that would seem sufficient to say that the program is functioning correctly.
However, a more cautious person might try a few more values just to make sure.
But what values should be chosen? Should we try 25 or 9, 3 or 7?

As a general rule it is best to think carefully about what values you choose as test
data. A few carefully chosen values may show up problems when many more
randomly chosen values show nothing.

When the test data is numeric, the most obvious choices are to use a typical value
(in the case of the above program, 16 falls into this category), a very large value, a
negative value and zero. But in each case it is important that you work out the
expected result before entering your test data into the program - otherwise you have
no way of knowing if the results you are seeing on the screen are correct.

Activity 3.28

What results would you expect from root.dbpro if your test data was

401286
0
-9

Run the program with these test values and check that the expected results are
produced.

When entering string test values, an empty string (just press Enter when asked to
enter the data), a single character string, and a multicharacter string should do.

These suggestions for creating test data may need to be modified depending on the
nature of the program you are testing.

Summary
l The assignment statement takes the form
variable = value

l value can be a constant, other variable, or an expression.

l The value assigned should be of the same type as the receiving variable.

98 DarkBASIC Pro: Data


l Arithmetic expressions can use the following operators:
^ * / + - mod

l Calculations are performed on the basis of highest priority operator first and a
left-to-right basis.

l The power operator has the highest priority; multiplication and division and the
mod operator the next highest, followed by addition and subtraction.

l Terms enclosed in parentheses are always performed first.

l The + operator can be used to join strings.

l The INPUT statement reads a value from the keyboard and places that value in
a named variable.

l The INPUT statement can display a message designed to inform the user what
has to be entered.

l The DATA and READ statements can be used to assign a listed value to a
variable.

l The RESTORE statement forces a return to the start of the first DATA statement.

l The TIMER statement returns the time in milliseconds from switch on.

l The GET TIME$ statement returns the current time as a string.

l The GET DATE$ statement returns the current date as a string.

l The RND statement generates a random integer number in the range 0 to a


specified maximum.

l The RANDOMIZE statement ensures that the numbers created by the RND are
truly random.

l The value returned by statements such as RND and RGB can be assigned to a
variable.

l A named constant can be created using the #CONSTANT statement.

l The name assigned to a constant must not end with a # or $ symbol.

DarkBASIC Pro: Data 99


Determining Current Settings
Introduction
Let’s say we want to place the title of our new game in the centre of the screen. We
know that we can place text at any position using TEXT or CENTER TEXT, but
how are we to discover where the centre of the screen is? If we’re working in an
800 by 600 display mode, then the centre is at 400,300 - but how can we be sure
what display mode is being used? Luckily, DarkBASIC Pro has many statements
that allow us to find out this, and other, information. Some of these are given below,
others we’ll discuss in later chapters.

Screen Settings
The SCREEN HEIGHT Statement
The SCREEN HEIGHT statement returns the height of the output screen in pixels
and has the format shown in FIG-3.20.
FIG-3.20
The SCREEN HEIGHT SCREEN HEIGHT ( )
Statement

integer
For example, the statement

PRINT SCREEN HEIGHT()

would display the value 600, assuming the screen resolution was set to 800 by 600.

The SCREEN WIDTH Statement


This statement returns the width of the output screen in pixels. The statement has
the format shown in FIG-3.21.
FIG-3.21
The SCREEN WIDTH
SCREEN WIDTH ( )
Statement

integer
For example, the statement

screenwidth = SCREEN WIDTH()

would assign the value 800 to the variable screenwidth, assuming the screen
resolution was set to 800 by 600.

The program in LISTING-3.3 displays the word WELCOME at the centre of the
screen.

100 DarkBASIC Pro: Data


LISTING-3.3 REM *** Find centre of screen ***
centrex = SCREEN WIDTH()/2
Centring Text centrey = SCREEN HEIGHT()/2

REM *** Display text at centre ***


CENTER TEXT centrex, centrey, “WELCOME”

REM *** End program ***


WAIT KEY
END

Activity 3.29

Type in and test the program above (centred.dbpro).

Is the text correctly centred both vertically and horizontally?

The SCREEN DEPTH Statement


The number of bits used to represent a single pixel on the screen determines the
maximum number of colours that can be shown on the screen. For example, if a
single bit was used to represent a pixel, that bit could have the value 0 or 1, hence
only two colours can be shown. With two bits per pixel, four colours are possible,
represented by the bit patterns 00, 01, 10, and 11.

The SCREEN DEPTH statement returns the number of bits used per pixel and has
the format shown in FIG-3.22.
FIG-3.22
The SCREEN DEPTH SCREEN DEPTH ( )
Statement

integer

If a call to this statement returns the value 16, then the number of colours that can
be shown is calculated as 216. The code required to perform this calculation is:

noofcolours = 2^SCREEN DEPTH()

Colour Components
If we were to generate a random colour with the lines
RANDOMIZE TIMER()
colour = RGB(RND(255),RND(255),RND(255))

we could find out the settings of the red, green and blue components of that colour
using the following statements.

The RGBR Statement


The RGBR statement returns an integer specifying the red component of a specified
colour. The statement has the format shown in FIG-3.23.

DarkBASIC Pro: Data 101


FIG-3.23
The RGBR Statement
RGBR ( colour )

integer

In the diagram:

colour is an integer value representing a colour. This


value will probably have been generated using the
RGB statement.

Hence, assuming the variable colour had been set using the line given earlier, we
could extract the red component of that colour with the line
redvalue = RGBR(colour)

The RGBG Statement


The RGBG statement returns an integer specifying the green component of a
specified colour. The statement has the format shown in FIG-3.24.
FIG-3.24
The RGBG Statement RGBG ( colour )

integer
In the diagram:

colour is an integer value representing a colour. This


value will probably have been generated using the
RGB statement.

The RGBB Statement


The RGBB statement returns an integer specifying the blue component of a
specified colour. The statement has the format shown in FIG-3.25.
FIG-3.25
The RGBB Statement RGBB ( colour )

integer

In the diagram:

colour is an integer value representing a colour. This


value will probably have been generated using the
RGB statement.

102 DarkBASIC Pro: Data


The three statements are used in LISTING-3.4 to display the component values of
a randomly generated colour.
LISTING-3.4 REM *** Create random colour ***
RANDOMIZE TIMER()
Colour Component colour = RGB(RND(255),RND(255),RND(255))
Values
REM *** Extract components of this colour ***
red = RGBR(colour)
green = RGBG(colour)
blue = RGBB(colour)

REM *** Use the new colour ***


INK colour,0

REM *** Display the colour details ***


PRINT “The generated colour has the following settings”
PRINT “Red component : ”,red
PRINT “Green component : ”,green
PRINT “Blue component : ”,blue

REM *** End program ***


WAIT KEY
END

Activity 3.30

Type in and test the program (colours03.dbpro) in LISTING-3.4.

Text Settings
Details of the text font, size and style currently being used by a program can be
retrieved using the following statements.

The TEXT BACKGROUND TYPE Statement


We can discover the current text background mode (opaque or transparent) using
the TEXT BACKGROUND TYPE statement which has the format shown in
FIG-3.26.

FIG-3.26
TEXT BACKGROUND TYPE ( )
The TEXT
BACKGROUND
Statement

integer
The statement returns the value zero if a transparent background is being used; 1 is
returned when the background setting is opaque.

The TEXT STYLE Statement


The style of font, (bold, italic, etc.) can be determined using the TEXT STYLE
statement which has the format shown in FIG-3.27.

The integer value returned lies between 0 and 3 (0 - normal; 1 - italic; 2 - bold; 3 -
bold italic).

DarkBASIC Pro: Data 103


FIG-3.27
The TEXT STYLE TEXT STYLE ( )
Statement

integer

The TEXT SIZE Statement


The TEXT STYLE statement returns the current text size setting in points. This
statement has the format shown in FIG-3.28.
FIG-3.28
The TEXT SIZE TEXT SIZE ( )
Statement

integer

The TEXT FONT$ Statement


The TEXT FONT$ statement returns a string giving the name of the font currently
being used. For example, it would return the string "Arial", assuming this font had
been selected earlier, using the SET TEXT FONT statement. The TEXT FONT$
statement has the format shown in FIG-3.29.
FIG-3.29
The TEXT FONT$
TEXT FONT$ ( )
Statement

string

The TEXT WIDTH Statement


When placing text on the screen it can be very useful to know in advance just how
many pixels wide that piece of text is going to be. The exact width of the text will
obviously depend on the text itself, goodbye being wider than hello, but text font,
style and size settings are also going to effect the width of the text. We can find out
the exact width of any text to be displayed using the TEXT WIDTH statement. This
has the format shown in FIG-3.30.
FIG-3.30
The TEXT WIDTH
TEXT WIDTH ( string )
Statement

integer

In the diagram:

string is the string whose width is to be determined.

104 DarkBASIC Pro: Data


The TEXT HEIGHT Statement
The number of pixels from the lowest point on a piece of text (typically at the bottom
of letters such as g and y) to the highest point (on letters such as t and l) can be found
using the TEXT HEIGHT statement, which has the format shown in FIG-3.31.
FIG-3.31
The TEXT HEIGHT TEXT HEIGHT ( string )
Statement

integer

In the diagram:

string is the string whose height is to be determined.

The program in LISTING-3.5 demonstrates the use of the statements in this section.
LISTING 3.5 REM *** Set text characteristics ***
SET TEXT FONT "Arial"
Display Text
SET TEXT TO BOLD
Characteristics
SET TEXT SIZE 20
SET TEXT OPAQUE

REM *** Read in text ***


INPUT "Enter text : ", text$

REM *** Display details ***


PRINT "Font used is ",TEXT FONT$()
PRINT "Font style is ",TEXT STYLE()," 0 - normal, 1 - italic, 2
Ä- bold, 3 - bold italic"
PRINT "Font size is ", TEXT SIZE()," points"
PRINT "Text background ",TEXT BACKGROUND TYPE()," 0 - transparent
Ä1 - opaque"
PRINT text$," is ",TEXT WIDTH(text$)," pixels wide"
PRINT text$," is ",TEXT HEIGHT(text$)," pixels high"

REM *** End program ***


WAIT KEY
END

Activity 3.31

Type in and test the program in LISTING-3.5 (textdetails.dbpro).

Summary
l Use SCREEN WIDTH to find the current screen width setting.

l Use SCREEN HEIGHT to find the current screen height setting.

l Use SCREEN DEPTH to find how many bits are used to represent one screen
pixel.

l Use RGBR to find the value of the red component in a specified colour.

DarkBASIC Pro: Data 105


l Use RGBG to find the value of the green component in a specified colour.

l Use RGBB to find the value of the blue component in a specified colour.

l Use TEXT BACKGROUND TYPE to determine if transparent or opaque


backgrounds are being used with text output.

l Use TEXT STYLE to determine the current text style setting.

l Use TEXT SIZE to determine the current text size setting.

l Use TEXT FONT$ to determine the current text font name.

l Use TEXT WIDTH to determine the width of a specified piece of text.

l Use TEXT HEIGHT to determine the height of a specified piece of text.

106 DarkBASIC Pro: Data


Solutions
Activity 3.1 Activity 3.8
a) Integer a) no2 is 16
b) String b) x# is 82.18
c) Integer c) no3 is zero
d) Real d) no4 is 9
e) String e) m# is 0.4
f) Integer f) v2# is 40.99
g) Real
h) String
i) String Activity 3.9
j) Real The result is 1

Activity 3.2 The expression is calculated as follows:

“Mary is” - string 12-5* 12/10-5


12 - integer 12-60/10-5
“ years old” - string 12-6-5
6-5

Activity 3.3
Activity 3.10
a) Valid
b) Invalid. Integer variable will store 12 Steps
c) Invalid. Hello should be enclosed in double
quotes(“Hello”) 8*(6-2)/(3-1)
d) Valid 8*4/(3-1)
e) Invalid. Must be double quotes, not single quotes 8*4/2
f) Valid 32/2
16

Activity 3.4
Activity 3.11
a) Valid
b) Invalid. Must start with a letter answer = no1 / (4 + no2 - 1) * 5 - no3 ^ 2
answer = 12 / (4 + 3 - 1) * 5 - 5 ^ 2
c) Invalid. Names cannot be within quotes.
answer = 12 / (7 - 1) * 5 - 5 ^ 2
d) Valid answer = 12 / 6 * 5 - 5 ^ 2
e) Invalid. Spaces are not allowed in a name answer = 12 / 6 * 5 - 25
f) Valid answer = 2 * 5 - 25
g) Invalid, end is a DarkBASIC Pro keyword answer = 10 - 25
h) Valid answer = -15

Activity 3.5 Activity 3.12


1. desc$="tall" term$ will hold the string abcl23xyz
2. result#= 12.34

Activity 3.13
Activity 3.6
Output:
a) Valid
b) Invalid. Fraction part lost number
c) Invalid. A string cannot be copied to an integer 23
variable
d) Valid
e) Invalid. A real cannot be copied to a string variable Activity 3.14
f) Invalid. A string cannot be copied to a real variable
The final version of the program should read:

Activity 3.7 name$ = “Jessica McLaren”


PRINT name$
a) 2 WAIT KEY
b) -1 END
c) 5
d) -4

DarkBASIC Pro: Data 107


Activity 3.15 PRINT day$

REM *** Assign name to variable & display READ day$


it *** PRINT day$
name$ = “Jessica McLaren” READ day$
PRINT “Hello, ”,name$,", how are you today?" PRINT day$
REM *** End program *** READ day$
WAIT KEY PRINT day$
END REM *** Go back to the start of the data ***
RESTORE
REM *** Read and display the first day ***
Activity 3.16 READ day$
PRINT day$
a) Valid REM *** End program ***
b) Valid WAIT KEY
END
c) Invalid. The comma is missing after the message.

Activity 3.17 Activity 3.21


millisecondsPassed = TIMER()
No solution required. seconds = millisecondsPassed / 1000
minutes = seconds / 60
PRINT “Your computer has been on for ”
Activity 3.18 ,minutes, “ minutes”
WAIT KEY
REM *** Get name *** END
INPUT “Player 1, enter your name ”, name$
INPUT “Enter your age ”, age
PRINT “Hello, ”, name$, “, I see you are This could be reduced to just
”,age," years old"
REM *** End program *** minutes = TIMER()/60000
WAIT KEY PRINT “Your computer has been on for ”
END ,minutes, “ minutes”
WAIT KEY
END
Activity 3.19
REM *** Set up names of days of the week *** Activity 3.22
DATA
“Sunday”,“Monday”,“Tuesday”,“Wednesday”, REM *** Display message ***
“Thursday”,“Friday”,“Saturday” PRINT “Press any key”
REM *** Read and display each day *** REM *** Record start time ***
READ day$ start = TIMER()
PRINT day$ REM *** Wait for key press ***
READ day$ WAIT KEY
PRINT day$ REM *** Record finish time ***
READ day$ finish = TIMER()
PRINT day$ REM *** Calculate and display duration ***
READ day$ duration = finish - start
PRINT day$ PRINT “You took ”, duration, “ milliseconds”
READ day$ REM *** End program ***
PRINT day$ WAIT KEY
READ day$ END
PRINT day$
READ day$
PRINT day$ Activity 3.23
REM *** End program ***
WAIT KEY RND(48)
END

Activity 3.24
Activity 3.20
The RND line needs to be changed to read:
Existing lines are in grey.
RND(48) + 1
REM *** Set up names of days of the week ***
DATA
“Sunday”,“Monday”,“Tuesday”,“Wednesday”, Activity 3.25
“Thursday”,“Friday”,“Saturday”
REM *** Generate random value ***
REM *** Read and display each day ***
RANDOMIZE TIMER()
READ day$
number = RND(99)+1
PRINT day$
REM *** Guess the number ***
READ day$
INPUT “Enter your guess (1 to 100) : ”
PRINT day$
,guess
READ day$
REM *** Display both values
PRINT day$
PRINT “Number was ”, number," Guess was “
READ day$
,guess

108 DarkBASIC Pro: Data


REM *** End program ***
WAIT KEY
END

Activity 3.26
REM *** Assign colours ***
scarlet = RGB(255,0,0)
sky = RGB(0,0,255)
CLS scarlet
INK sky, scarlet
PRINT “Ocean”
REM *** End program ***
WAIT KEY
END

Activity 3.27
No solution required.

Activity 3.28
Test Value Expected Result

401286 633.471
0 0
-9 Undefined

Activity 3.29
The text is not centred vertically since the CENTER TEXT
statement positions the top of the text at the y-ordinate
specified. To be correctly centred, the middle of the text
would have to positioned at this y-ordinate.

Activity 3.30
No solution required

Activity 3.31
No solution required.

DarkBASIC Pro: Data 109


110 DarkBASIC Pro: Data
4

AND, OR and NOT Operators

Boolean Conditions

IF..ENDIF Statement

IF..THEN Statement

Nested IF Statements

Relational Operators

SELECT Statement

Testing Selective Structures

DarkBASIC Pro: Selection 111


Binary Selection
Introduction
As we saw in structured English, many algorithms need to perform an action only
when a specified condition is met. The general form for this statement was:

IF condition THEN

action

ENDIF

Hence, in our guessing game we described the response to a correct guess as:

IF guess = number THEN

Say “Correct”

ENDIF

As we’ll see, DarkBASIC Pro also makes use of an IF statement to handle such
situations.

The IF Statement
In its simplest form the IF statement in DarkBASIC Pro takes the format shown in
FIG-4.1.
FIG-4.1
IF condition
The Simple IF Statement

statement
Notice that DarkBASIC
Pro’s IF statement does
ENDIF
not contain the word
THEN
In the diagram:

condition is any term which can be reduced to a true or


false value.

statement is any executable DarkBASIC Pro statement.

If condition evaluates to true, then the set of statements between the IF and ENDIF
terms are executed; if condition evaluates to false, then the set of statements are
ignored and execution moves on to the statements following the ENDIF term.

An unlimited number of statements may be placed between the IF and ENDIF terms.

Condition
Generally, the condition will be an expression in which the relationship between
two quantities is compared. For example, the condition
no < 0

will be true if the content of the variable no is less than zero (i.e. negative).

112 DarkBASIC Pro: Selection


A condition is sometimes referred to as a Boolean expression and has the general
format given in FIG-4.2.
FIG-4.2
value 1 relational operator value 2
A Boolean Expression

In the diagram:

value1 and value2 may be constants, variables, or expressions

relational operator is one of the symbols given in TABLE-4.1.

TABLE-4.1
English Symbol
Relational Operators
is less than <
is less than or equal to <=
is greater than >
is greater than or equal to >=
is equal to =
is not equal to <>

The values being compared should be of the same type, but it is acceptable to mix
integer and real numeric values as in the conditions:

v > x#
t# < 12

However, numeric and string values cannot be compared. Therefore, conditions


such as

name$ = 34
no1 <> “16"

are invalid.

Activity 4.1

Which of the following are not valid Boolean expressions?

a) no1 < 0 d) v# => 12.0


b) name$ = “Fred” e) total <> “0"
c) no1 * 3 >= no2 - 6 f) address$ = 14 High Street

When two strings are checked for equality as in the condition

IF name$ = “Fred”

the condition will only be considered true if the match is an exact one (see FIG-4.3),
even the slightest difference between the two strings will return a false result.
FIG-4.3
“fred” ”Fred” “broadsword” “broad sword”
Comparing Strings

Not equal Not equal


lower case f and upper case F single word two words
(i.e. one of the strings contains a space)

DarkBASIC Pro: Selection 113


Not only is it valid to test if two string values are equal, or not, as in the conditions

IF name$ = “Fred”
IF village$ <> “Turok”

it is also valid to test if one string value is greater or less than another. For example,
it is true that

“B” > “A”

Such a condition is considered true not because B comes after A in the alphabet,
but because the coding used within the computer to store a “B” has a greater numeric
value than the code used to store “A”.

The method of coding characters is known as ASCII (American Standard Code for
Information Interchange). This coding system is given in Appendix A at the back
of the book.

If you are comparing strings which only contain letters, then one string is less than
another if that first string would appear first in an alphabetically ordered list. Hence,

“Aardvark” is less than “Abolish”

But watch out for upper and lower case letters. All upper case letters are less than
all lower case letters. Hence, the condition

“A” < “a”

is true.

If two strings differ in length, with the shorter matching the first part of the longer
as

“abc” < “abcd”

then the shorter string is considered to be less than the longer string. Also, because
the computer compares strings using their internal codes, it can make sense of a
condition such as

“$” < “?”

which is also considered true since the $ sign has a smaller value than the ? character
in the ASCII coding system.

Activity 4.2

Determine the result of each of the following conditions (true or false). You
may have to examine the ASCII coding at the end of the book for part f).

a) “wxy” = “w xy” d) “cat” = “cat.”


b) “def” < “defg” e) “dog” = “Dog”
c) “AB” < “BA” f) “*” > “&”

TABLE-4.2 shows some Structured English IF statements and the DarkBASIC Pro
equivalents.

114 DarkBASIC Pro: Selection


TABLE-4.2 Structured English DarkBASIC Pro Code

Examples of Simple IF IF no is negative THEN IF no < 0


Statements make no positive no = -no
ENDIF ENDIF

IF day is zero THEN IF day = 0


Display “Sunday” PRINT “Sunday”
ENDIF ENDIF

IF value is even THEN IF value mod 2 = 0


Subtract 1 from value value = value - 1
ENDIF ENDIF

The program in LISTING-4.1 reads in two numbers and displays a message if the
numbers are equal. The program employs the following logic:

Get values for no1 and no2

IF no1 = no2 THEN

Display “Numbers are equal”

ENDIF

LISTING-4.1 REM *** Read in two numbers ***


INPUT “Enter first value : ”,no1
Using a Simple IF INPUT “Enter second value ”,no2
Statement
REM *** IF both numbers are the same THEN Display message ***
IF no1 = no2
PRINT “Numbers are equal”
ENDIF

REM *** End program ***


WAIT KEY
END

Notice the use of indentation in the program listings. DarkBASIC Pro does not
demand that this be done, but indentation makes a program easier to read - this is
particularly true when more complex programs are written.

Activity 4.3

Type in and test the program in LISTING-4.1 (Call the project same.dbpro)

Modify the program you created for project guess.dbpro, so that, after the
player has typed in his guess, the program displays the word Correct if the
guess and number are equal.

In the next program (see LISTING-4.2) a real value representing the radius of a
circle is read from the keyboard. As long as a valid value has been entered (i.e. a
value greater than zero) then the area of the circle is calculated and displayed.

Notice that this time we have more than one statement within the IF structure.

LISTING-4.2 REM *** Read radius of circle ***


INPUT “Enter radius : ”, radius#
Placing Several
Statements within the REM *** IF valid radius THEN ***
IF..ENDIF Structure IF radius# > 0
REM *** Calculate and display area ***
area# = 3.14159 * radius# * radius#
PRINT “Area of circle is ”,area#
ENDIF
continued on next page

DarkBASIC Pro: Selection 115


LISTING-4.2 REM *** End program ***
(continued) WAIT KEY
END
Placing Several
Statements within the
IF..ENDIF Structure Activity 4.5

Write separate DarkBASIC Pro programs for each of the following tasks:
(Name the projects act4_5_1.dbpro, act4_5_2.dbpro, etc.)

1. Read in an integer number (no1) and display the message “Negative value”
if the number is less than zero.

2. Read in a real number representing the width and height of a square. If the
number is greater than zero, calculate and display the area of the square.

3. Read in a word. If the word is “yes”, display the message “Access granted".

4. Read in an integer value and display the word “Even” if it is an even


number (HINT: an even number gives no remainder when divided by 2).

Compound Conditions - the AND and OR Operators


Two or more simple conditions (like those given earlier) can be combined using
either the term AND or the term OR (just as we did in structured English in Chapter
1).

The term AND should be used when we need two conditions to be true before an
action should be carried out. For example, if a game requires you to throw two sixes
to win, this could be written as:

RANDOMIZE TIMER ()
dice1 = RND(5) + 1
dice2 = RND(5) + 1
IF dice1 = 6 AND dice2 = 6
PRINT “You win!”
ENDIF

The statement PRINT “You win!” will only be executed if both conditions, dice1=
6 and dice2 = 6, are true.

Activity 4.6

Using the code given above, if dice1 = 6 and dice2 = 5, will the statement
PRINT “You win!” be carried out?

You may recall from Chapter 1 that there are four possible combinations for an IF
statement containing two simple expressions. Because these two conditions are
linked by the AND operator, the overall result will only be true when both conditions
are true. These combinations are shown in TABLE-4.3.
TABLE-4.3
condition 1 condition 2 condition 1 AND condition 2
The AND Operator
false false false
false true false
true false false
true true true

116 DarkBASIC Pro: Selection


We link conditions using the OR operator when we require only one of the
conditions given to be true. For example, if a dice game produces a win when the
total of two dice is either 7 or 11, we could write the code for this as:

RANDOMIZE TIMER ()
dice1 = RND(5) + 1
dice2 = RND(5) + 1
total = dice1 + dice2
IF total = 7 OR total = 11
PRINT “You win!”
ENDIF

Again, the computer reduces the individual Boolean expressions to either true or
false. If at least one of the individual conditions is true, then the overall result is also
true. This time the four possible combinations give the results shown in TABLE-4.4
TABLE-4.4
condition 1 condition 2 condition 1 OR condition 2
The OR Operator
false false false
false true true
true false true
true true true

Activity 4.7

If no1 =10 and no2 = 7, which of the following IF statements will evaluate to
true?

a) IF no1 < no2 OR no2 = 8


b) IF no1 + no2 > 15 OR no1 < 9
c) IF no2 - no1 > 0 OR no1 / no2 > 1
d) IF no1 >= 10 OR no2 <= 10

There is no limit to the number of conditions that can be linked using AND and OR.
For example, a statement of the form
IF condition1 AND condition2 AND condition3

means that all three conditions must be true, while the statement

IF condition1 OR condition2 OR condition3

means that at least one of the conditions must be true.

Activity 4.8

A game requires 3 dice to be thrown. If at least two dice show the same value,
the player has won.

Write a program (dice.dbpro) which contains the following logic:

Throw all three dice

IF any two dice match THEN

Display “You win!”

ENDIF

Display the value of each dice

DarkBASIC Pro: Selection 117


Activity 4.9

Modify your previous project Act4_5_3 so that the message “Access granted"
is displayed if the word input is either “yes” or “YES”.

Once we start to create conditions containing both AND and OR operators, we must
remember that the AND operator takes precedence over the OR operator. Therefore,
the statement
IF dice = 5 OR dice = 2 AND card$ = “Ace”

means that throwing a dice value of 5 is sufficient to give us an overall result of true
and it does not matter what value card$ is. However, it we don’t throw a 5, then we
must throw a 2 and card$ must be equal to “Ace” to achieve an overall true result.

The normal rule of performing the AND operation before OR can be modified by
the use of parentheses. Expressions within parentheses are always evaluated first.
Hence, if we write
IF (dice = 5 OR dice = 2) AND card$ = “Ace”

the expression will be calculated as follows:

(true OR false) AND false

= true AND false

= false

Activity 4.10

What is the overall result of the Boolean expression

(score > 20 OR lives > 2) AND (weaponpower < 1 OR ammunition >= 200)

when score =15, lives = 3, weaponpower = 1, and ammunition = 250

The NOT Operator


DarkBASIC Pro’s NOT operator works in exactly the same way as that described
in Chapter 1. It is used to negate the final result of a Boolean expression.

If we assume dice = 4, then the line


IF NOT (dice = 5 OR dice = 2)

will evaluate as

NOT (false OR false)

= NOT false

= true

Activity 4.11

When money =100 and cards =21, what is the result of the condition:

NOT (money > 80 AND cards > 20)

118 DarkBASIC Pro: Selection


ELSE - Creating Two Alternative Actions
In its present form the IF statement allows us to perform an action when a given
condition is met. But sometimes we need to perform an action only when the
condition is not met. For example, when the user has to guess the number generated
by the computer, we use an IF statement to display the word “Correct” when the
user guesses the number correctly:

IF guess = number
PRINT “Correct”
ENDIF

However, shouldn’t we display an alternative message when the player is wrong?

One way to do this is to follow the first IF statement with another testing the opposite
condition:

IF guess = number
PRINT “Correct”
ENDIF
IF NOT guess = number
PRINT “Wrong”
ENDIF

Although this will work, it’s not very efficient since we always have to test both
conditions - and the second condition can’t be true if the first one is!

As an alternative, we can add the word ELSE to our IF statement and follow this
by the action we wish to have carried out when the stated condition is false:

IF guess = number
PRINT “Correct”
ELSE
PRINT “Wrong”
ENDIF

Activity 4.12

Modify act4_5_1.dbpro to display the phrase “Positive number” if the


variable no1 is greater than or equal to zero and displays the phrase “Negative
number” if no1 contains a value less than zero.

This gives us the longer version of the IF statement format as shown in FIG-4.4.

FIG-4.4
The IF..ELSE Statement IF condition

statement

ELSE

statement

ENDIF

DarkBASIC Pro: Selection 119


Activity 4.13

Modify your guess.dbpro project so that the message “Wrong” appears if the
player guesses the wrong number.

Activity 4.14

Create a project (smaller.dbpro) which reads in two numbers from the


keyboard and displays the smaller of the two values.

Activity 4.15

Modify project act4_5_4.dbpro so that the program displays the word “Odd”
if an odd value is entered.

The Other IF Statement


DarkBASIC Pro actually offers a second version of the IF statement which has the
format shown in FIG-4.5.

FIG-4.5
The Alternative IF IF condition THEN
Statement

statement

Although the syntax


diagram shows the IF :
statement spread over
several lines, this statement
must be entered as a single ELSE
line in your program.

statement

As you can see from the diagram, this version uses the word THEN but omits the
ENDIF term. You can have as many statements as you need in each section (after
THEN and ELSE) but these must be separated by colons.

A major restriction when using this version of the IF statement is that the keyword
ELSE, if used, must appear on the same line as the term IF. Hence, it is invalid to
write:

IF no1 < 0 THEN


PRINT “Negative”
ELSE
PRINT “Positive”

Instead you must write

IF no1 < 0 THEN PRINT “Negative” ELSE PRINT “Positive”

120 DarkBASIC Pro: Selection


Activity 4.16

Rewrite the IF statement you created in Activity 4.12 to use this alternative
version of the IF statement.

It is probably best to avoid this version of the IF statement, since the requirement
to place the IF and ELSE terms on the same line does not allow a good layout for
the program code.

Activity 4.17

1. What is a Boolean expression?

2. How many relation operators are there?

3. If a condition contains both AND and OR operators, which will be


performed first?

Summary
l Conditional statements are created using the IF statement.

l A Boolean expression is one which gives a result of either true or false.

l Conditions linked by the AND operator must all be true for the overall result to
be true.

l Only one of the conditions linked by the OR operator needs to be true for the
overall result to be true.

l When the NOT operation is applied to a condition, it reverses the overall result.

l The statements following a condition are only executed if that condition is true.

l Statements following the term ELSE are only executed if the condition is false.

l A second version of the IF statement is available in DarkBASIC Pro in which


IF and ELSE must appear on the same line.

DarkBASIC Pro: Selection 121


Multi-Way Selection
Introduction
A single IF statement is fine if all we want to do is perform one of two alternative
actions, but what if we need to perform one action from many possible actions? For
example, what if we need to select from three or more alternative actions? How can
we create code to deal with such a situation? In structured English we use a modified
IF statement of the form:

IF

condition 1:

action1

condition 2:

action 2

ELSE

action 3

ENDIF

However, this structure is not available in DarkBASIC Pro and hence we must find
some other way to implement multi-way selection.

Nested IF Statements
One method is to use nested IF statements - where one IF statement is placed within
another. For example, let’s assume in our number guessing game that we want to
display one of three messages: Correct, Your guess is too high, or Your guess is too
low. Our previous solution allowed for two alternative messages: Correct or Wrong
and was coded as:

IF guess = number
PRINT “Correct”
ELSE
PRINT “Wrong”
ENDIF

In this new problem the PRINT “Wrong” statement needs to be replaced by the two
alternatives: Your guess is too high, or Your guess is too low. But we already know
how to deal with two alternatives - use an IF statement. In this case, our IF statement

IF guess > number


PRINT “Your guess is too high”
ELSE
PRINT “Your guess is too low”
ENDIF

If we now remove the PRINT “Wrong” statement from our earlier code and substitute
the four lines given above, we get:

IF guess = number
PRINT “Correct”
ELSE
IF guess > number
PRINT “Your guess is too high”
ELSE
PRINT “Your guess is too low”
ENDIF
ENDIF

122 DarkBASIC Pro: Selection


Activity 4.18

Modify your guess.dbpro project so that the game will respond with one of
three messages as shown in the code given above.

Activity 4.19

In act4_5_1.dbpro we created an IF statement which displayed one of two


messages: Positive Number or Negative number.

Technically, the number zero is neither positive nor negative, hence we should
really produce a third message: Zero when number = 0.

Modify your earlier solution to this previous task to achieve this requirement.

There is no limit to the number of IF statements that can be nested. Hence, if we


required four alternative actions, we might use three nested IF statements, while
four nested IF statements could handle five alternative actions. To demonstrate this
we’ll take our number guessing game a stage further and display the message Your
guess is slightly too high if the guess is no more than 5 above the original number;
the message Your guess is slightly too low will be displayed if the guess is no more
than 5 below the original number.

We’ll start by working out the difference between our guess and the computer’s
number using the line

difference = guess - number

Now, if we’ve guessed the number correctly, then difference will be zero. However,
if we’ve gone too high, then difference will be a positive number. On the other hand,
a low guess will result in difference being negative. When difference is a small value
(either positive or negative) then guess must be close to number. The complete
program is given in LISTING-4.3.

LISTING-4.3 REM *** Generate number ***


RANDOMIZE TIMER()
The Number Guessing number = RND(99)+1
Game Again REM *** Get guess ***
INPUT “Enter your guess (1 - 100) ”, guess
REM *** Calculate difference between the two values ***
difference = guess - number
REM *** Display appropriate message ***
IF difference = 0
PRINT “Correct”
ELSE
IF difference > 0
IF difference <= 5
PRINT “Your guess is slightly too high”
ELSE
PRINT “Your guess is too high”
ENDIF
ELSE
IF difference >= -5
PRINT “Your guess is slightly too low”
ELSE
PRINT ”Your guess is too low"
ENDIF
ENDIF
ENDIF

DarkBASIC Pro: Selection 123


Activity 4.20

Modify your guess.dbpro program to match the code given in LISTING-4.3.

Test the program to check that it operates as expected.

Activity 4.21

In a game a player’s character carries the following items: a sword, a wand, a


bag of dragon’s teeth and a water skin.

Create a new project (items.dbpro) which reads in a number from the


keyboard and displays the name of the corresponding item. Hence, if 1 is
entered, the phrase A sword is displayed, if 2 is entered, A wand is displayed,
etc. If an invalid value is entered, the phrase Unknown item is displayed.

The SELECT Statement


An alternative, and often clearer, way to deal with choosing one action from many
is to employ the SELECT statement. The simplest way to explain the operation of
the SELECT statement is simply to give you an example. In the code snippet given
below we display the name of the day of week corresponding to the number entered.
For example, entering 1 results in the word Sunday being displayed.

INPUT “Enter a number between 1 and 7 ”, day


SELECT day
CASE 1
PRINT “Sunday”
ENDCASE
CASE 2
PRINT “Monday”
ENDCASE
CASE 3
PRINT “Tuesday”
ENDCASE
CASE 4
PRINT “Wednesday”
ENDCASE
CASE 5
PRINT “Thursday”
ENDCASE
CASE 6
PRINT “Friday”
ENDCASE
CASE 7
PRINT “Saturday”
ENDCASE
ENDSELECT

Once a value for day has been entered, the SELECT statement chooses the CASE
statement that matches that value and executes the code given within that section.
All other CASE statements are ignored and the instruction following the END
SELECT statement (not shown above) is the next to be executed. For example, if
day = 3, then the statement given beside CASE 3 will be executed (i.e. PRINT
“Tuesday” ). If day were to be assigned a value not given in any of the CASE
statements (i.e. a value outside the range 1 to 7), the whole SELECT statement
would be ignored and no part of it executed.

Optionally, a special CASE statement can be added at the end of the SELECT

124 DarkBASIC Pro: Selection


statement. This is the CASE DEFAULT option which is used to catch all other
values which have not been mentioned in previous CASE statements. For example,
if we modified our SELECT statement above to end with the code

CASE 7
PRINT “Saturday”
ENDCASE
CASE DEFAULT
PRINT “Invalid day”
ENDCASE
ENDSELECT

then, if a value outside the range 1 to 7 is entered, this last CASE statement will be
executed. FIG-4.6 shows how the SELECT statement is executed.
FIG-4.6 1
expression is evaluated
and reduced to a single value
How the SELECT
statement operates
SELECT expression

CASE value1 2 - option 1


The CASE statement whose
action
value matches expression has
ENDCASE its action executed...

CASE value2
action
ENDCASE 2 - option 2
If expression matches none of
. the values given, the
DEFAULT action is executed...
.
If no DEFAULT option is given
CASE DEFAULT the whole SELECT structure is ignored
action
ENDCASE
ENDSELECT

Several values can be specified for each CASE option. If the SELECT value
matches any of the values listed, then that CASE option will be executed. For
example, using the lines

INPUT “Enter a number ” , num


SELECT num
CASE 1, 3, 5, 7, 9
PRINT “Odd”
ENDCASE
CASE 2,4,6,8,10
PRINT “Even”
ENDCASE
ENDSELECT

the word Odd would be displayed if any odd number between 1 and 9 was entered.

The values given beside the CASE keyword may also be a string as in the example
below:

INPUT “Enter your name ”, name$ ‘


SELECT name$
CASE “Liz”,"John"
PRINT “Hello friend”
ENDCASE
CASE DEFAULT
PRINT “I do not know your name”
ENDCASE
ENDSELECT

Although the value may also be a real value as in the line

DarkBASIC Pro: Selection 125


CASE 1.52

it is a bad idea to use these since the machine cannot store real values accurately. If
a real variable contained the value 1.52000001 it would not match with the CASE
value given above.

The general format of the SELECT statement is given in FIG-4.7.


FIG-4.7
SELECT expression
The SELECT Statement

CASE value

,
statement

ENDCASE

[
CASE DEFAULT

statement

ENDCASE

ENDSELECT

In the diagram:

expression is a variable or expression which reduces to a


single integer, real or string value.

value is a constant of any type (integer, real or string).

statement is any valid DarkBASIC Pro statement


(even another SELECT statement!).

Activity 4.22

Rewrite the Items program so that it uses a SELECT structure when


determining which message is to be displayed.

Activity 4.23

Write a project (Grading) which accepts a score from the keyboard and
displays the grade assigned according to the following rules:

Score 0-99 grade: Pathetic


Score 100-199 grade: Beginner
Score 200 - 299 grade: Apprentice
Score 300-399 grade: Competent
Score 400-499 grade: Master
Score 500-599 grade: Grand Master
Other values Invalid score

126 DarkBASIC Pro: Selection


Testing Selective Code
When a program contains IF or SELECT structures, our test strategy has to change
to cope with these structures. In the case of an IF statement, we must create two test
values: one which results in the IF statement being true, the other in the IF statement
being false. For example, if a program contained the lines

INPUT no
IF no <= 0
PRINT “This is a negative number”
ENDIF

then we need to have a test value for no which is less than zero and another which
is not less than zero. Perhaps the values -8 and 3.

Another important test is to find out what happens when the variable’s value is
exactly equal to the value against which it is being tested. In the above case that
would mean testing the code with no set to 0. Very often this is the only value which
will highlight a problem in the code.

Activity 4.24

If no is zero, will the message “This is a negative number” be displayed by the


code given above?

Since zero is not a negative number we have discovered an error in our code. The
line

IF no <= 0

should actually read

IF no < 0

We would not have detected this error if we hadn’t used zero as our test value.

When an IF statement contains more than one condition linked with AND or OR
operators, testing needs to check each possible combinations of true and false
settings. For example, if a program contained the line

IF dice1 = 6 AND dice2 = 6

then our tests should include all possible combinations for the two conditions as
shown in TABLE-4.5.
TABLE-4.5 dice1 = 6 dice2 = 6 dice1 = 6 AND dice2 = 6

Testing Complex false false false


Conditions false true false
true false false
true true true

So our test values, chosen to meet these combinations, might be

dice1 = 3 dice2 = 5
dice1 = 4 dice2 = 6
dice1 = 6 dice2 = 1
dice1 = 6 dice2 = 6

DarkBASIC Pro: Selection 127


If the dice values are randomly generated in the program we would have to change
lines such as

dice1 = RND(5) +1

to

INPUT “Enter value for dice 1 : ”,dice1

to allow the test to take place. Once the tests have been completed, the INPUT lines
would be replaced by the original code.

In a complex condition it is sometimes not possible to create every theoretical


combination of true and false combinations. For example, if a program contains the
line

IF dice = 5 OR dice = 2 AND card$ = “Ace”

then the combinations of true and false are shown in TABLE-4.6.


TABLE-4.6 dice = 5 dice = 2 card$=”Ace” dice = 5 OR dice = 2 AND card$=”Ace”

Dealing with Impossible false false false false


Combinations false false true false
false true false false
false true true true
true false false true
true false true true
true true false * true
true true true * true

But the last two combinations in the table are impossible to achieve since the
variable dice cannot contain the values 5 and 2 at the same time. So our test data
will have test values which create only the remaining 6 combinations.

When testing nested IF statements, as in the lines


IF guess = number
PRINT “Correct”
ELSE
IF guess > number
PRINT “Your guess is too high”
ELSE
PRINT “Your guess is too low”
ENDIF
ENDIF

then each path through the structure must be tested. For the above code this means
that we must test for the following conditions being true:

guess = number
guess > number
guess < number

To test a SELECT structure, then every value mentioned in every CASE option
must be tested. Hence, the lines
INPUT “Enter a number ” , num
SELECT num
CASE 1, 3, 5, 7, 9
PRINT “Odd”
ENDCASE
CASE 2,4,6,8,10

128 DarkBASIC Pro: Selection


PRINT “Even”
ENDCASE
ENDSELECT

need to be tested using the values 1, 2, 3, 4, 5, 6, 7, 8, and 9. In addition, at least one


test should specify a value not given in any of the CASE statements. This will check
that the DEFAULT option is executed as expected (assuming there is a DEFAULT
option), or that the whole SELECT structure is bypassed as expected.

Summary
l The term nested IF statements refers to the construct where one IF statement is
placed within the structure of another IF statement.

l Multi-way selection can be achieved using either nested IF statements or the


SELECT statement.

l The SELECT statement can be based on integer, real or string values.

l The CASE line can have any number of values, each separated by a comma.

l The CASE DEFAULT option is executed when the value being searched for
matches none of those given in the CASE statements.

l Testing a simple IF statement should ensure that both true and false results are
tested.

l Where a specific value is mentioned in a condition (as in no < 0) , that value


should be part of the test data.

l When a condition contains AND or OR operators, every possible combination


of results should be tested.

l Nested IF statements should be tested by ensuring that every possible path


through the structure is executed by the combination of test data.

l SELECT structures should be tested by using every value specified in the CASE
statements.

l SELECT should also be tested using a value that does not appear in any of the
CASE statements.

DarkBASIC Pro: Selection 129


Solutions
Activity 4.1 REM *** End program ***
WAIT KEY
a) Valid END
b) Valid
c) Valid 3.
d) Invalid. => is not a relational operator (should be >=)
REM *** Read in word ***
e) Invalid. Integer variable compared with string. INPUT “Enter a word : ”,word$
f) Invalid. 14 High Street should be in double quotes. IF word$ = “yes”
PRINT “Access allowed”
ENDIF
Activity 4.2 REM *** End program ***
WAIT KEY
a) False. Only the second string contains a space. END
b) True. “def is shorter and matches the first three
characters of "defg". 4.
c) True A comes before B.
d) False Only the second string contains a full stop. REM *** Read in an integer ***
e) False Only the second string contains a capital D. INPUT “Enter a number : ”,no1
f) True. * has a greater ASCII coding than & REM *** IF an even number THEN Display
“Even” ***
IF no1 mod 2=0
Activity 4.3 PRINT “Even”
ENDIF
No solution required. REM *** End program ***
WAIT KEY
END
Activity 4.4
REM *** Generate random value *** Activity 4.6
RANDOMIZE TIMER ()
number = RND (99)+1 No, the PRINT statement is not executed.
REM *** Guess the number *** The condition
INPUT “Enter your guess (1 to 100) : ” dice1 = 6 AND dice2 = 6
,guess reduces to
REM *** IF the guess is correct THEN ***
REM *** Display “Correct” ***
true AND false
IF guess = number which further reduces to
PRINT “Correct” false
ENDIF
REM *** Display both values ***
PRINT “Number was ”, number," Guess was “ Activity 4.7
,guess
REM *** End program *** a) false OR false = false
WAIT KEY b) true OR false = true
END c) false OR true = true
d) true OR true = true
Activity 4.5
Activity 4.8
1.
REM *** Throw dice ***
REM *** Read in integer *** RANDOMIZE TIMER ()
INPUT “Enter a number : ”, no1 dice1 = RND(5)+1
REM *** IF neg THEN Display message *** dice2 = RND(5)+1
IF no1 < 0 dice3 = RND(5)+1
PRINT “Negative value” REM *** IF at least two dice match THEN
ENDIF display message ***
REM *** End program *** IF dice1 = dice2 OR dice1 = dice3 OR dice2
WAIT KEY = dice3
END PRINT “You win”
ENDIF
2. REM *** Display dice values ***
PRINT “Dice 1 was ”, dice1
PRINT “Dice 2 was ”, dice2
REM *** Read in real ***
PRINT “Dice 3 was ”, dice3
INPUT “Enter length of side : ”, side#
REM *** End program ***
REM *** IF greater than zero THEN ***
WAIT KEY
IF side# > 0
END
REM *** Calculate and display area ***
area# = side# * side#
PRINT “Area of square is ”,area#
ENDIF

130 DarkBASIC Pro: Selection


Activity 4.9 Activity 4.15
REM *** Read in word *** REM *** Read in an integer ***
INPUT “Enter a word : ”,word$ INPUT “Enter a number : ”,no1
IF word$ = “yes” OR word$ = “YES” REM *** IF even THEN Display “Even” ***
PRINT “Access granted” IF no1 mod 2 = 0
ENDIF PRINT “Even”
REM *** End program *** ELSE
WAIT KEY PRINT “Odd”
END ENDIF
REM *** End program ***
WAIT KEY
Activity 4.10 END

Substituting true and false we get:


Activity 4.16
(false OR true) AND (false OR true)
= true AND true IF no1 >= 0 THEN PRINT “Positive number”
=true ELSE PRINT “Negative number”

(this is entered in a single line)


Activity 4.11
Substituting true and false we get: Activity 4.17
NOT (true AND true) 1. A Boolean expression is an expression which reduces to
= NOT true either true or false.
= false
2. Six (<, <=, >, >=, =, <>)
Activity 4.12 3. AND is always performed first unless the OR is
IF no1 >= 0 enclosed in parentheses.
PRINT* “Positive number”
ELSE
PRINT “Negative number” Activity 4.18
ENDIF
REM *** Generate random value ***
RANDOMIZE TIMER()
Activity 4.13 number = RND(99)+1
REM *** Guess the number ***
REM *** Generate random value *** INPUT “Enter your guess (1 to 100) : ”,guess
RANDOMIZE TIMER () REM *** Respond to guess ***
number = RND(99)+1 IF guess = number
REM *** Guess the number *** PRINT “Correct”
INPUT “Enter your guess (1 to 100) : ELSE
”,guess IF guess > number
REM *** IF the guess is correct THEN PRINT “Your guess is too high”
Display ELSE
PRINT “Your guess is too low”
“Correct” *** ENDIF
IF guess = number ENDIF
PRINT “Correct” REM *** Display both values ***
ELSE PRINT “Number was ”, number," Guess was
PRINT “Wrong” “,guess
ENDIF REM *** End program ***
REM *** Display both values WAIT KEY
PRINT “Number was ”, number," Guess was END
“,guess
REM *** End program ***
WAIT KEY Activity 4.19
END
REM *** Read in a number ***
INPUT “Enter number ”, no1
Activity 4.14 REM *** Display appropriate message ***
IF no1 > 0
REM *** Read in two numbers *** PRINT “Positive number”
INPUT “Enter first number : ”, no1 ELSE
INPUT “Enter second number : ”, no2 IF no1 = 0
IF no1 < no2 PRINT “Zero”
PRINT “Smallest number is ”, no1 ELSE
ELSE PRINT “Negative number”
PRINT “Smallest number is ”,no2 ENDIF
ENDIF ENDIF
REM *** End program *** REM *** End program ***
WAIT KEY WAIT KEY
END END

DarkBASIC Pro: Selection 131


ENDCASE
Activity 4.20 CASE DEFAULT
PRINT “Invalid score”
No solution required. ENDCASE
ENDSELECT
REM *** End program ***
Activity 4.21 WAIT KEY
REM *** Get number *** END
INPUT “Enter item number (1 - 4) : ”, no
IF no = 1
PRINT “A sword”
ELSE Activity 4.24
IF no = 2
PRINT “A wand” Yes. The condition no <= 0 is true and hence the PRINT
ELSE statement is executed.
IF no = 3
PRINT “A bag of dragon’s teeth”
ELSE
IF no = 4
PRINT “A water skin”
ELSE
PRINT “Unknown item”
ENDIF
ENDIF
ENDIF
ENDIF

Activity 4.22
REM *** Get number ***
INPUT “Enter item number (1 - 4) : ”, no
REM *** Display appropriate message ***
SELECT no
CASE 1
PRINT “A sword”
ENDCASE
CASE 2
PRINT “A wand”
ENDCASE
CASE 3
PRINT “A bag of dragon’s teeth”
ENDCASE
CASE 4
PRINT “A water skin”
ENDCASE
CASE DEFAULT
PRINT “Unknown item”
ENDCASE
ENDSELECT
REM *** End program ***
WAIT KEY
END

Activity 4.23
REM *** Get numberRead score
INPUT “Enter your score : ”, score
REM *** Display appropriate message ***
SELECT score / 100
CASE 0
PRINT “Pathetic”
ENDCASE
CASE 1
PRINT “Beginner”
ENDCASE
CASE 2
PRINT “Apprentice”
ENDCASE
CASE 3
PRINT “Competent
ENDCASE
CASE 4
PRINT “Master”
ENDCASE
CASE 5
PRINT “Grand master”

132 DarkBASIC Pro: Selection


5

DO .. LOOP Construct

EXIT Statement

FOR .. NEXT Construct

REPEAT .. UNTIL Construct

SLEEP Statement

Testing Iterative Structures

Using DATA and READ in a FOR .. NEXT Construct

WAIT Statement

WHILE .. ENDWHILE Construct

DarkBASIC Pro: Iteration 133


Iteration

Introduction
Iteration is the term used when one or more statements are carried out repeatedly.
As we saw in Chapter 1, structured English has three distinct iterative structures:
FOR .. ENDFOR, REPEAT .. UNTIL and WHILE .. ENDWHILE.

DarkBASIC Pro, on the other hand, has four iterative structures. Most of these take
the same form as their structured English equivalent, but others differ slightly and
therefore care should be taken when translating structured English statements to
DarkBASIC Pro.

The WHILE .. ENDWHILE Construct


The WHILE statement is probably the easiest of DarkBASIC Pro’s loop structures
to understand, since it is identical in operation and syntax to the WHILE loop in
structured English. For example, if a wizard uses 25 units of power every time he
casts a spell to shrink an enemy’s height by 10%, a burst of spell casting could be
described using the logic:

WHILE energy available >= 25 DO


Reduce enemy’s height by 10%
Reduce energy available by 25
ENDWHILE

which can be coded in DarkBASIC Pro as:

WHILE energyavailable >= 25


enemyheight = enemyheight * 0.9
energyavailable = energyavailable - 25
ENDWHILE

The syntax of the WHILE .. ENDWHILE construct is shown in FIG-5.1.


FIG-5.1
The WHILE .. WHILE condition
ENDWHILE Construct

statement

ENDWHILE

In the diagram:

condition is a Boolean expression and may include AND,


OR, NOT and parentheses as required.

statement is any valid DarkBASIC Pro statement.

A visual representation of how this loop operates is shown in FIG-5.2. Note that
the loop body may never be executed if condition is false when first tested.

134 DarkBASIC Pro: Iteration


FIG-5.2 Earlier Statements
1
Executing a WHILE .. condition is tested ...
ENDWHILE Construct

WHILE condition

2 - option 1 2 - option 2
if condition is true, if condition is false,
the loop body statements the program jumps to the
are executed end of the loop
After the loop body
has been executed, the program
returns to the start of the loop
and condition is retested
statement

ENDWHILE

Later Statements

A common use for this loop statement is validation of input. So, for example, in
our number guessing game, we might ensure that the user types in a value between
1 and 100 when entering their guess by using the logic

Get guess
WHILE guess outside the range 1 to 100 DO
Display error message
Get guess
ENDWHILE

which can be coded in DarkBASIC Pro as:


INPUT “Enter your guess (1 - 100) : ”,guess
WHILE guess < 1 OR guess > 100
PRINT “Your guess must be between 1 and 100"
INPUT “Enter your guess again (1 - 100) : ”,guess
ENDWHILE

Activity 5.1

Modify your guess01.dbpro project to incorporate the code given above.

Check that the program works correctly by attempting to make guesses which
are outside the range 1 to 100.

Activity 5.2

Using a WHILE statement similar to that given above, modify project


items.dbpro (which you created in the last chapter) so that the value entered
from the keyboard is checked to be in the range 1 to 4.

An invalid value should result in the message “Invalid selection. Please


re-enter" being displayed and require the user to re-enter the value.

Check that the program correctly deals with invalid entries.

DarkBASIC Pro: Iteration 135


TABLE-5.1 gives examples of structured English WHILE statements and the
equivalent DarkBASIC Pro code.
TABLE-5.1
Structured English DarkBASIC Pro Code
WHILE Examples
Get month INPUT “Enter month “,month
WHILE month outside the range 1 to 12 DO WHILE month < 1 OR month > 12
Display “Invalid month” PRINT “Invalid month”
Get month INPUT “Enter month “,month
ENDWHILE ENDWHILE

Get value INPUT “Enter value “,value


WHILE value not zero DO WHILE value <> 0 DO
Add value to total total = total + value
Get value INPUT “Enter value “,value
ENDWHILE ENDWHILE

Activity 5.3

Write the DarkBASIC Pro equivalent of the following structured English:

Get no1

Get no2

WHILE no1 <> no2 DO


Set no1 equal to no2

Get no2

ENDWHILE

Under what conditions will the WHILE loop terminate?

Activity 5.4

A simple dice game involves counting how many times in a row a pair of
dice can be thrown to produce a value of 8 or less. The game stops as soon as
a value greater than 8 is thrown.

Write a DarkBASIC Pro project (dice01.dbpro) to perform this task.


(You will need RANDOMIZE and RND to simulate dice throws.)

The REPEAT .. UNTIL Construct


Like structured English, DarkBASIC Pro has a REPEAT..UNTIL statement. The
two structures are identical. Hence, if in structured English we write

Set total to zero


REPEAT
Get a number
Add number to total
UNTIL number is zero

then the same logic would be coded in DarkBASIC Pro as

total = 0
REPEAT
INPUT “Enter a number : ”, number
total = total + number
UNTIL number = 0

136 DarkBASIC Pro: Iteration


The REPEAT..UNTIL statement is an exit-controlled loop structure. That is, the
action within the loop is executed and then an exit condition is tested. If that
condition is found to be true, then looping stops, otherwise the action specified
within the loop is executed again. Iteration continues until the exit condition is true.

The syntax of the REPEAT statement is shown in FIG-5.3.


FIG-5.3
The REPEAT .. UNTIL REPEAT
Construct

statement

UNTIL condition

In the diagram:

condition is a Boolean expression and may include AND,


OR, NOT and parentheses as required.

statement is any valid DarkBASIC Pro statement.

The operation of the REPEAT .. UNTIL construct is shown graphically in FIG-5.4.

FIG-5.4 Earlier Statements


Executing the REPEAT
.. UNTIL Construct

1
REPEAT the statements in ...
the
loop body are executed

3 - option 1 statement 2
if condition is false, condition is tested
the loop body statements
are executed again
UNTIL condition

3 - option 2
if condition is true,
the program exits the loop

Later Statements

Activity 5.5

Create a project (total.dbpro) to read in a series of integer values, stopping


only when a zero is entered. The values entered should be totalled and that
total displayed at the end of the program.

Activity 5.6

Modify project guess01.dbpro to allow the player to keep guessing until the
correct number is arrived at.

DarkBASIC Pro: Iteration 137


TABLE-5.2 gives some examples of structured English REPEAT..UNTIL loops
and the DarkBASIC Pro equivalents.
TABLE-5.2
Structured English DarkBASIC Pro Code
REPEAT .. UNTIL
Examples Set target to 401 target = 401
REPEAT REPEAT
Get Score INPUT “Enter score: ”,score
Subtract score from target target = target - score
UNTIL target zero or less UNTIL target <= 0

Set total to zero total = 0


Set count to zero count = 0
REPEAT REPEAT
Get number INPUT “Enter number:”, number
Add 1 to count count = count +1
UNTIL count is 10 or number is zero UNTIL count = 10 OR number = 0

The FOR..NEXT Construct


In structured English, the FOR loop is used to perform an action a specific number
of times. For example, we might describe dealing seven cards to a player using the
logic:

FOR 7 times DO
Deal card
ENDFOR

Sometimes the number of times the action is to be carried out is less explicit. For
example, if each player in a game is to pay a £10 fine we could write:

FOR each player DO


Pay £10 fine
ENDFOR

However, in both examples, the action specified between the FOR and ENDFOR
terms will be executed a known number of times.

In DarkBASIC Pro the FOR construct makes use of a variable to keep a count of
how often the loop is executed and takes the form:

FOR variable = start_value TO finish_value

Hence, if we want a FOR loop to iterate 7 times we would write

FOR c = 1 TO 7

In this case c would be assigned the value 1 when the FOR loop is about to start.
Each time the action within the loop is performed, c will be incremented, and
eventually, once the action is performed with c equal to 7, iteration stops.

The variable used in a FOR loop is known as the loop counter.

Activity 5.7

Write the first line of a FOR loop that is to be executed 10 times, using a
variable j which is to start with a value of 1.

138 DarkBASIC Pro: Iteration


While structured English marks the end of a FOR loop using the term ENDFOR,
in DarkBASIC Pro the end of the loop is indicated by the term NEXT followed by
the name of the loop counter variable used in the FOR statement.

The action to be performed within the loop (known as the loop body) can consist
of any number of statements. For example, the code

FOR k = 1 TO 10
PRINT “*”
NEXT k

contains a single statement within the loop body and will display a column of 10
asterisks.

Activity 5.8

What would be displayed by the code

FOR p = 1 TO 10
PRINT p
NEXT p

The loop counter in a FOR loop can be made to start and finish at any value, so it
is quite valid to start a loop with the line

FOR m = 3 TO 12

When executed, the loop counter m will contain the value 3 when the loop is first
executed and finish with the value 12. The loop will be executed exactly 10 times.

If the start and finish values are identical as in the line

FOR r = 10 TO 10

then the loop is executed once only.

Where the start value is greater than the finish value, the loop will not be executed
at all as in the line
FOR k = 10 TO 9

Normally, one is added to the loop counter each time the loop body is performed.
However, we can change this by adding a STEP value to the FOR loop as shown
below:

FOR c = 2 TO 10 STEP 2

In this last example the loop counter, c, will start at 2 and then increment to 4 on
the next iteration. The program in LISTING-5.1 uses the STEP option to display
the 7 times table from 1 x 7 to 12 x 7.

LISTING-5.1 REM *** Display 7 times table ***


FOR c = 7 TO 84 STEP 7
Using the FOR .. NEXT PRINT c
Structure NEXT c
REM *** End program ***
WAIT KEY
END

DarkBASIC Pro: Iteration 139


Activity 5.9

Type in and test the program in LISTING-5.1. Save it as project table.dbpro.

Modify the program so that it displays the 12 times table from 1 x 12 to 12 x


12.

By using the STEP keyword with a negative value, it is even possible to create a
FOR loop that reduces the loop counter on each iteration as in the line:

FOR d = 10 TO 0 STEP -1

This last example causes the loop counter to start at 10 and finish at 0.

Activity 5.10

Modify the table.dbpro project so that the 12 times table is displayed with the
highest value first. That is, starting with 144 and finishing with 12.

It is possible that the step value given may cause the loop counter never to match
the finish value. For example, in the line

FOR c = 1 TO 12 STEP 5

the variable c will take on the values 1, 6, and 11. The loop will always stop before
the variable passes the finishing value.

The start, finish and even step values of a FOR loop can be defined using a variable
or arithmetic expression as well as a constant. For example, in LISTING-5.2 below
the user is allowed to enter the upper limit of the FOR loop.

LISTING-5.2 REM *** Get a number ***


PRINT “I will display all of the values between 1 and any number
FOR Loops Using a you give me"
Variable Limit INPUT “Please enter your number : ”,num

REM *** Display values ***


FOR c = 1 TO num
PRINT c
NEXT c

REM *** End program ***


WAIT KEY
END

The program will display every integer value between 1 and the number entered by
the user.

Activity 5.11

Type in and test the program above (forloops01.dbpro).

Modify the program so that the user may also specify the starting value of the
FOR loop.

Change the program a second time so that the user can specify a step size for
the FOR loop

140 DarkBASIC Pro: Iteration


The FOR loop counter can also be specified as a real value with a STEP value of
less than 1 as in the lines:

FOR ch# = 1.0 TO 2.0 STEP 0.1


PRINT ch#
NEXT ch#

Activity 5.12

Create a project (forloops02.dbpro) containing the code given above and


check out the result.

Notice that most of the values displayed by the last Activity are slightly out. For
example, instead of the second value displayed being 1.1, it displays as
1.10000002384. This difference is caused by rounding errors when converting from
the decimal values that we use to the binary values favoured by the computer.

Although we might have expected the FOR loop to perform 11 times (1.0,1.1,1.2,
etc. to 2.0), in fact, it only performs 10 times up to 1.90000021458. Again, this
discrepancy is caused by the rounding error problem.

Activity 5.13

Modify forloop02.dbpro so that the upper limit of the loop is 2.01.

How many times is the iteration performed now?

The format of the FOR..NEXT construct is shown in FIG-5.5.


FIG-5.5
The FOR .. NEXT
Structure
FOR variable = start TO finish
[ STEP incr

statement

NEXT variable

In the diagram:

variable is either an integer or real variable. Both variable


tiles refer to the same variable. Hence the name
used after the keywords FOR and NEXT should
be the same. This variable is known as the loop
counter.

start is the initial value of the loop counter. The loop


counter will contain this value the first time the
statements within the loop are executed.

finish is the final value of the loop variable. The loop


variable will usually contain this value the last
time the loop body is executed.

incr is the value to be added to the loop counter after


each iteration. If this value is omitted then a value

DarkBASIC Pro: Iteration 141


of 1 is added to the loop counter on each iteration.

statement is any valid DarkBASIC Pro statement.

The operation of the FOR statement is shown graphically in FIG-5.6.


FIG-5.6 1
variable is set to start

Executing a FOR
.. NEXT Construct

FOR variable = start TO finish STEP incr

If no incr value 2
is specified, 1 is variable is checked to
added to variable discover if it is greater than finish

3 Option 1b 3 Option 1a 3 Option 2


incr is added if variable <= finish the if variable > finish the
to variable loop body is executed program exits the loop

statement

NEXT variable

Later Statements

TABLE-5.3 gives examples of structured English FOR loops and their DarkBASIC
Pro equivalents.

TABLE-5.3 Structured English DarkBASIC Pro Code

FOR .. NEXT Examples Set total to zero total = 0


FOR each value between 1 and 10 DO FOR c = 1 TO 10
Add that value to total total = total + c
ENDFOR NEXT c
Display total PRINT total

Set total to zero total = 0


Get number of players INPUT “Enter number of players:“, players
FOR each player DO FOR c = 1 TO players
Get player’s score INPUT “Enter score:”, score
Add score to total total = total + score
ENDFOR NEXT c
Calculate average as total / players average = total / players
Display average PRINT average

Activity 5.14

Create a new project (total.dbpro) which reads in and displays the total of 12
numbers.

Finding the Smallest Value in a List of Values


There are several tasks you will find yourself (and your programs) having to do over
and over again. One of these is finding the smallest number in a list of numbers. If
someone writes down a list of values on a piece of paper and asks you which value
is the smallest, you shouldn’t have any problem giving them the correct answer.
But if they ask how you managed to come up with the correct answer, you might
have more of a problem trying to describe in precise terms how you did it.

142 DarkBASIC Pro: Iteration


When the list contains only a few, small numbers, then our brain seems to be able
to take them all in at one go and instantly come up with an answer. On the other
hand if the numbers were large (several digits long) and you were only shown one
number every day over a period of several months, you’d have to think of a more
organised strategy to ensure you came up with the correct answer.

The best approach would be to write down the first number you see on a piece of
paper and, every day when you are shown a new number, compare this new value
with what is written on the paper. If you are shown a smaller number than before,
erase the old number from your paper and write in the new one. Do this every day
and, by the end, the piece of paper will have a copy of the smallest number you saw
throughout the period.

This is exactly how we tackle the problem in a computer program. We set up one
variable to hold the smallest value we’ve come across and if a later value is smaller,
it is copied into this variable. The algorithm used is given below and assumes 10
numbers will be entered in total:

Get first number


Set smallest to first number
FOR 9 times DO
Get next number
IF number < smallest THEN
Set smallest to number
ENDIF
ENDFOR
Display smallest

Activity 5.15

Create a new project called smallest.dbpro. In this program implement the


logic shown above to display the smallest of 10 integer values entered at the
keyboard.

Modify the program to find the largest, rather than the smallest, of the
numbers entered.

Activity 5.16

In ice skating, a number of judges (N) award marks. The highest and lowest of
these are ignored and the others averaged to give a result. Write a program
(skating.dbpro) to input N (the number of judges), followed by N marks (the
mark given by each judge), and display the average score ignoring the highest
and lowest mark. (Scores range from 0.0 to 6.0 in increments of 0.1.)
The logic required by the program is:

Get value for N


Get value for score
Set highestscore to score

Set lowestscore to score

Set total to score

FOR N-1 times DO

Get value for score


Add score to total

IF score > highestscore THEN

Set highestscore to score

continued on next page

DarkBASIC Pro: Iteration 143


Activity 5.16 (continued)

ELSE

IF score < lowestscore THEN


Set lowestscore to score

ENDIF
ENDIF

ENDFOR

Subtract highestscore and lowestscore from total


Calculate average as total / (N-2)
Display value of average

Using FOR with READ and DATA


The FOR statement can be useful when reading values from a DATA list. For
example, back in Chapter 3 we set up a DATA statement containing the names of
the days of the week and then displayed these using the code:

DATA ”Sunday", “Monday”, “Tuesday”, “Wednesday”,


DATA “Thursday”, “Friday”, “Saturday”
READ day$
PRINT day$
READ day$
PRINT day$
etc.

But we can simplify this whole process by rewriting the code as

DATA “Sunday”, “Monday”, “Tuesday”, “Wednesday”,


DATA “Thursday”,"Friday", “Saturday”
FOR c = 1 TO 7
READ day$
PRINT day$
NEXT c

Each time the FOR loop body is executed, the next value in the DATA statement
is retrieved by the READ statement, and so all 7 day names are displayed.

Activity 5.17

Modify your days01.dbpro project from Chapter 3 so that it makes use of the
FOR loop as described above to display the days of the week.

Activity 5.18

Earlier we changed the guess01.dbpro project to incorporate a REPEAT ..


UNTIL loop so that the player could have an unlimited number of guesses at
the value of the computer’s number.

This doesn’t make play very exciting since the game now gives no sense of
playing against a deadline.

Modify the code so that a FOR loop is used in place of the REPEAT loop,
allowing the player 7 attempts at guessing the number.

Test this new version of the game.

144 DarkBASIC Pro: Iteration


Once you’ve played the latest version of the guessing game a few times, you will
have encountered a problem. If you guess the number in less than seven attempts,
you still need to keep going until all seven attempts have been completed.
Obviously, it makes more sense to stop as soon as the number has been guessed.
The next statement gives us a way of doing just that.

The EXIT Statement


The EXIT statement is used to exit from a loop structure, making the next statement
to be executed the one immediately after the end of the loop. Normally, the EXIT
statement will appear within an IF statement. The EXIT statement takes the form
shown in FIG-5.7.
FIG-5.7
The EXIT Statement EXIT

The EXIT statement can For example, in a dice game we are allowed to throw a pair of dice 5 times and our
be used in any loop score is the total of the five throws. However, if during our throws we throw a 1,
structure, not just FOR then our turn ends and our final score becomes the total achieved up to that point
loops. (excluding the throw containing a 1). We could code this game as shown in
LISTING-5.3.
LISTING-5.3
REM ** Seed random number generator ***
Using the EXIT Statement RANDOMIZE TIMER ()

REM *** Set total to zero ***


total = 0

REM *** FOR 5 times DO ***


FOR c = 1 TO 5
PRINT “Hit any key to roll the dice”
WAIT KEY
REM *** Throw both dice ***
dice1 = RND(5)+1
dice2 = RND(5)+1
REM *** Display throw number and dice values ***
PRINT “Throw : ”,c," Dice 1 : “,dicel,” Dice 2 : “,dice2
REM *** IF either dice is a 1 THEN quit loop ***
IF dice1 = 1 OR dice2 = 1
EXIT
ENDIF
REM *** Add dice throws to total ***
total = total + dicel + dice2
NEXT c

REM *** Display final score ***


PRINT “Your final score was : ”, total

REM *** End program ***


WAIT KEY
END

Activity 5.19

Create a new project (dicetotal01.dbpro) containing the code given above.

Run the program and check that the loop exits if a 1 is thrown.

Modify the program to exit only if both dice are 1's during a throw.

DarkBASIC Pro: Iteration 145


The DO .. LOOP Construct
The DO..LOOP construct is a rather strange loop structure, since, while other loops
are designed to terminate eventually, the DO .. LOOP structure will continue to
repeat its loop body indefinitely.

It has a very simple structure. In the example below, the code causes the word Hello
to be displayed over and over again:

DO
PRINT “Hello”
LOOP

The nearest equivalent to this in Structured English would be to write


Since false is never true, REPEAT
the REPEAT..UNTIL Display “Hello”
loop will execute forever. UNTIL false

Although there seems little likelihood that such a loop would be useful, it is, in fact,
often used to implement the main part of a game program with logic often following
the pattern:

DO
Get player’s command
Update player’s situation in the game
Update video display
LOOP

The DO .. LOOP Statement takes the format shown in FIG-5.8.


FIG-5.8
DO
The DO .. LOOP
Construct
statement

LOOP

DarkBASIC Pro will allow the user to escape from a DO .. LOOP structure by
pressing the Escape key.

Alternatively, an EXIT statement can be included within the loop to allow the loop
to be exited when a given condition occurs.

Activity 5.20

Create a new project (randomstops.dbpro) which positions full stops of a


random colour at random positions on the screen. The program requires the
following logic:

Seed the random number generator

DO
Set the cursor to a random position

Set the foreground to a random colour

Display a full stop

LOOP continued on next page

146 DarkBASIC Pro: Iteration


Activity 5.20 (continued)

Before you test the program, make sure that the screen resolution is set to an
appropriate value for the random position you have created.

For example, if your random position is anywhere from (0,0) to (799,599)


make sure the output screen is set to at least 800 by 600.

You’ll have to press the Escape key to get the program to stop.

Modify your program to stop automatically if the position generated is


(100,100). (HINT: Use an EXIT statement to achieve this.)

The WAIT milliseconds Statement


The loop in your last program may have iterated quickly with dots appearing very
rapidly (how quickly, depends on the hardware you’re using). However, there’s a
way to slow the machine down. We’ve already encountered the WAIT KEY
statement where the computer stops and waits for a key to be pressed, but there is
a second version of the WAIT statement that waits a specific number of milliseconds
(thousandth of a second) before continuing. This statement takes the form shown
in FIG-5.9.
FIG-5.9
The WAIT milliseconds WAIT time
Statement

In the diagram:

time is an integer value representing the number of


milliseconds the program is to wait at this
statement before continuing.

A typical example of the statement in use would be

WAIT 1000

which would cause the computer to pause for 1 second.

Activity 5.21

Add a half second delay between each iteration in your randomstops.dbpro


project.

The SLEEP Statement


The SLEEP statement has exactly the same effect as the WAIT statement described
above, pausing a program for a specified amount of time. This statement takes the
format shown in FIG-5.10.

FIG-5.10
The SLEEP Statement SLEEP time

DarkBASIC Pro: Iteration 147


Activity 5.22

The reaction game (reaction.dbpro) you created in Chapter 3 would benefit


from a slight delay before the message to press a key appears on the screen.

Modify the program to pause for one second before the message is displayed.

Since a player could predict when the message is going to appear on the
screen, he might be able to press a key just as the message appears. To stop
this, change the delay before the message appears to be anything between 1
and 2 seconds.

(HINT: You’ll need to use RND when setting the pause time.)

Nested Loops
A common requirement is to produce nested loops, that is situations where one loop
control structure appears within another. For example, to read in six game scores
(each between 0 and 100) and then calculate their average, the logic required is:

1. Set total to zero


2. FOR 6 times DO
3. Get valid score
4. Add score to total
5. ENDFOR
6. Calculate average as total / 6
7. Display average

This appears to have only a single loop structure beginning at statement 2 and ending
at statement 5. However, if we add detail to statement 3, this gives us

3. Get valid score


3.1 Read score
3.2 WHILE score is invalid DO
3.3 Display “Score must be between 0 to 100"
3.4 Read score
3.5 ENDWHILE

which, if placed in the original solution, results in a nested loop structure, where a
WHILE loop appears inside a FOR loop.

1. Set total to zero


2. FOR 6 times DO
3.1 Read score
3.2 WHILE score is invalid DO
3.3 Display “Score must be between 0 to 100"
3.4 Read score
3.5 ENDWHILE
4. Add score to total
5. ENDFOR
6. Calculate average as total / 6
7. Display average

Activity 5.23

Turn the above algorithm into a DarkBASIC Pro project (averagescore.dbpro)


and check that it operates as expected.

148 DarkBASIC Pro: Iteration


Nested FOR Loops
Perhaps the most troublesome situation is where FOR loops are nested. The
following example demonstrates the characteristics of such a structure. Consider
the first two digits of a car’s odometer. Initially, they are set to 00. As the car moves,
the least-significant digit (units) increments while the most significant digit (tens)
remains unchanged. But when the units value reaches 9, the tens value increments
and the units value is reset to zero (see FIG-5.11).

FIG-5.11 Initial values


tens units
of loop variables
Incrementing the Units 0 0
Loop Counter

0 1 On each iteration,
the units counter

... ...
is incremented...
0 2

...eventually reaching
its upper limit...

0 9 ...now units resets to


its starting value and
Tens is incremented...
1 0

1 1 ... the whole


process of incrementing

...
1 2
... units is repeated...

...eventually reaching
its upper limit once more...

1 9 ...again units resets and


tens is incremented...

...
2
...
0

... the whole


process continues until
tens and units have both
reached their upper limits.
9 9 At this point, looping ends

This situation is matched exactly by the following code:

FOR tens = 0 TO 9
FOR units = 0 TO 9
PRINT tens,units
NEXT units
NEXT tens

The tens loop is known as the outer loop, while the units loop is known as the inner
loop. A few points to note about nested FOR loops:

Ø The inner loop increments fastest.


Ø Only when the inner loop is complete does the outer loop variable
increment.
Ø The inner loop counter is reset to its starting value each time the outer
loop counter is incremented.

DarkBASIC Pro: Iteration 149


Activity 5.24

What would output by the following code?

FOR no1 = -2 TO 1
FOR no2 = 0 TO 3
PRINT no1," “,no2
NEXT no2
NEXT no1

Activity 5.25

The averagescore.dbpro project calculates the average score achieved by one


player over 6 games. Modify the project so that the average scores of 4
players, each playing six games, are displayed.

Do this by adding an outer FOR loop which executes four times (once for each
player).

Testing Iterative Code


We need a test strategy when looking for errors in iterative code. Where possible,
it is best to create at least three sets of test data:

Ø test data that causes the loop to execute zero times.


Ø test data that causes the loop to execute once.
Ø test data that causes the loop to execute multiple times.
For example, in project guess01.dbpro we checked that the player was entering a
number between 1 and 100 using the code:

INPUT “Enter your guess (1 - 100) : ”,guess


WHILE guess < 1 OR guess > 100
PRINT “Your guess must be between 1 and 100"
INPUT “Enter your guess again (1 - 100) : ”,guess
ENDWHILE

To test the WHILE loop in this section of code we could use the test data shown in
TABLE-5.4.
TABLE-5.4 Test Run Test Data Iterations

Test Data for a WHILE


Loop 1 guess = 77 0

2 guess = 0
guess = 98 1

3 guess = 101
guess = -9
guess = 50 2

The WHILE loop is only executed if guess is outside the range 1 to 100, so Test 1,
which uses a value in that range, will skip the WHILE loop - giving zero iterations.

Test 2 uses an invalid value for guess, causing the WHILE loop body to be executed,
and then uses a valid value. This loop is therefore exited after only one iteration.

150 DarkBASIC Pro: Iteration


Test 3 uses two invalid values, causing the WHILE loop to execute twice.

Activity 5.26

The following code is meant to calculate the average of a sequence of


numbers. The sequence ends when the value zero is entered. This terminating
zero is not considered to be one of the numbers in the sequence.

total = 0
count = 0
INPUT “Enter number (end with 0) : ”, num
WHILE num <> 0
total = total + num
count = count + 1
INPUT “Enter number (end with 0): ”, num
ENDWHILE
average = total / count
PRINT average
WAIT KEY
END

Make up a set of test values (similar in construct to TABLE-5.4) for the


WHILE loop in the code.

Create a new project (average.dbpro) containing the code given above and use
the test data to find out if the code functions correctly.

All three tests are not always possible. For example, a REPEAT loop cannot execute
zero times and, in this case, we have to satisfy ourselves with single and multiple
iteration tests.

A FOR loop, when written for a fixed number of iterations can only be tested for
that number of iterations. So a loop beginning with the line

FOR c = 1 TO 10

can only be tested for multiple iterations (10 iterations in this case). The exception
being if the loop body contains an EXIT statement, in which case zero and one
iteration tests may also be possible.

However, a FOR loop which is coded with a variable upper limit as in

FOR c = 1 TO max

may be fully tested by making sure max has the values 0, 1, and more than 1 during
testing.

A DO loop can only be tested for zero and one iterations if it contains an EXIT
statement.

Summary
l DarkBASIC Pro contains four iteration constructs:
WHILE . . ENDWHILE
REPEAT . . UNTIL

DarkBASIC Pro: Iteration 151


FOR .. NEXT
DO .. LOOP

l The WHILE..ENDWHILE construct executes a minimum of zero times and exits


when the specified condition is false.

l The REPEAT..UNTIL construct executes at least once and exits when the
specified condition is true.

l The FOR..NEXT construct is used when iteration has to be done a specific


number of times.

l A STEP size may be included in the FOR statement. The value specified by the
STEP term is added to the loop counter on each iteration.

l If no STEP size is given in the FOR statement, a value of 1 is used.

l FOR loops counters can be integer or real.

l The start, finish and STEP values in a FOR loop can be defined using variables
or arithmetic expressions.

l If the start value is equal to the finish value, a FOR loop will execute only once.

l If the start value is greater than the finish value and the STEP size is a positive
value, a FOR loop will execute zero times.

l Using the DO..LOOP structure creates an infinite loop.

l The EXIT statement can be used to exit from any loop.

l One loop structure can be placed within another loop structure. Such a structure
is known as a nested loop.

l Loops should be tested by creating test data for zero, one and multiple iterations
during execution whenever possible.

152 DarkBASIC Pro: Iteration


Solutions
Activity 5.1 Activity 5.4
RANDOMIZE TIMER() REM *** Seed random number generator ***
number = RND(99)+1 RANDOMIZE TIMER ()
REM *** Guess the number *** REM *** Set number of throws to zero ***
INPUT “Enter your guess (1 to 100) : ” throws = 0
,guess REM *** Throw both dice ***
WHILE guess < 1 OR guess > 100 dicel = RND(5)+1
PRINT “Your guess must be between 1 and dice2 = RND(5)+1
100" REM *** WHILE 8 or less DO ***
INPUT “Enter your guess again (1-100) : ” WHILE dicel + dice2 <= 8
, guess REM *** Add 1 to throws achieved ***
ENDWHILE throws = throws + 1
REM *** Respond to guess **" REM *** Throw dice again ***
IF guess = number dicel = RND(5)+1
PRINT “Correct” dice2 = RND(5)+1
ELSE ENDWHILE
IF guess > number REM *** Display the number of throws
PRINT “Your guess is too high” achieved ***
ELSE PRINT “You managed ”,throws," throws"
PRINT “Your guess is too low” REM *** End program ***
ENDIF WAIT KEY
ENDIF END
REM *** Display both values ***
PRINT “Number was ”, number," Guess was “
,guess Activity 5.5
REM *** End program ***
WAIT KEY REM *** Set total to zero ***
END total = 0
REPEAT
REM *** Read a number ***
Activity 5.2 INPUT “Enter a value (0 to stop ) : ”, no
REM *** Add number to total ***
REM *** Get number *** total = total + no
INPUT “Enter item selected : ”,no UNTIL no = 0
WHILE no < 1 OR no > 4 REM *** Display total ***
PRINT “Invalid selection. Please PRINT “Total of values entered is ”, total
re-enter.” REM *** End program ***
INPUT “Enter item number (1-4) : ”, no WAIT KEY
ENDWHILE END
REM *** Display name of item ***
SELECT no
CASE 1 Activity 5.6
PRINT “A sword”
ENDCASE REM *** Generate random value ***
CASE 2 RANDOMIZE TIMER()
PRINT “A wand” number = RND(99)+1
ENDCASE REPEAT
CASE 3 REM *** Guess the number ***
PRINT “A bag of dragon’s teeth” INPUT “Enter your guess (1 to 100) : ”,guess
ENDCASE WHILE guess < 1 OR guess > 100
CASE 4 PRINT “Your guess must be between 1 and
PRINT “A water skin” 100"
ENDCASE INPUT “Enter your guess again (1-100): ”,
CASE DEFAULT guess
PRINT “Unknown item” ENDWHILE
ENDCASE REM *** Respond to guess ***
ENDSELECT IF guess = number
REM *** End program *** PRINT “Correct”
WAIT KEY ELSE
END IF guess > number
PRINT “Your guess is too high”
ELSE
Activity 5.3 PRINT “Your guess is too low”
ENDIF
INPUT “Enter a number : ”,nol ENDIF
INPUT “Enter a number : ”,no2 UNTIL guess = number
WHILE nol <> no2 REM *** Display both values ***
nol = no2 PRINT “Number was ”, number," Guess was “
INPUT “Enter a number : ”,no2 ,guess
ENDWHILE REM *** End program ***
WAIT KEY
The loop will terminate when nol and no2 both contain END
the same value.

DarkBASIC Pro: Iteration 153


Activity 5.7 The discrepancy is caused by rounding errors when
converting decimal to binary. (Binary is the number
FOR j = 1 TO 10 system used by the computer.)

Activity 5.8 Activity 5.13


This code would display the values 1 to 10 The iteration now performs the expected 11 times, the last
value displayed being 2.00000023842
Activity 5.9
REM *** Display 12 times table *** Activity 5.14
FOR c = 12 TO 144 STEP 12 REM *** Set total to zero ***
PRINT c total = 0
NEXT c REM *** FOR 12 times DO ***
REM *** End program *** FOR c = 1 TO 12
WAIT KEY REM *** Get a number ***
END INPUT “Enter a number : ”,num
REM *** Add number to total ***
total = total + num
Activity 5.10 NEXT c
PRINT “The total of the 12 numbers is ”
REM *** 12 times table backwards! ***
,total
FOR c = 144 TO 12 STEP -12
REM *** End program ***
PRINT c
WAIT KEY
NEXT c
END
REM *** End program ***
WAIT KEY
END
Activity 5.15
Smallest:
Activity 5.11
The second version of the program should be: REM *** Get first number ***
INPUT “Enter number : ”, num
REM *** Set smallest to first number ***
REM *** Get limit of FOR loop ***
smallest = num
PRINT “I will display all of the values
REM *** FOR 9 times DO ***
between any two numbers you give me"
FOR c = 2 TO 10
INPUT “Enter start value : ”,start
REM *** Get next number ***
INPUT “Enter finish value : ”, num
INPUT “Enter a number : ”, num
FOR c = start TO num
REM *** IF smaller, store in smallest ***
PRINT c
IF num < smallest
NEXT c
smallest = num
REM *** End program ***
ENDIF
WAIT KEY
NEXT c
END
REM *** Display smallest ***
PRINT “The smallest number entered was ”,
The final version is: smallest
REM *** End program ***
PRINT “I will display the appropriate WAIT KEY
values between any two numbers you give me" END
INPUT “Enter start value : ”,start
INPUT “Enter finish value : ”, num Largest:
INPUT “Enter the step size : ”, size
FOR c = start TO num STEP size
REM *** Get first number ***
PRINT c
INPUT “Enter number : ”, num
NEXT c
REM *** Set largest to first number ***
REM *** End program ***
largest = num
WAIT KEY
REM *** FOR 9 times DO ***
END
FOR c = 2 TO 10
REM *** Get next number ***
INPUT “Enter a number : ”, num
Activity 5.12 REM *** IF larger, store in largest ***
IF num > largest
The values displayed are: largest = num
ENDIF
1 NEXT c
1.10000002384 REM *** Display largest ***
1.20000004768 PRINT “The largest number entered was ”,
1.30000007153 largest
1.40000009537 REM *** End program ***
1.50000011921 WAIT KEY
1.60000014305 END
1.70000016689
1.80000019073
1.90000021458

154 DarkBASIC Pro: Iteration


Activity 5.16 IF guess > number
PRINT “Your guess is too high”
REM *** Get the number of judges *** ELSE
INPUT “Enter the number of judges : ”, n PRINT “Your guess is too low”
REM *** Get first score *** ENDIF
INPUT “Enter score of first judge : ”, ENDIF
score# NEXT c
REM *** Set highest, lowest, total to score REM *** Display both values
*** PRINT “Number was ”, number," Guess was “
highestScore# = score# ,guess
lowestScore# = score# REM *** End program ***
total# = score# WAIT KEY
REM *** FOR N-l times DO *** END
FOR c = 1 TO N-l
REM *** Get next score ***
INPUT “Enter next judge’s score : ”,score# Activity 5.19
REM *** Add score to total ***
total# = total# + score# REM *** Seed random number generator ***
REM *** Check highest and lowest *** RANDOMIZE TIMER()
IF score# > highestScore# REM *** Set total to zero ***
highestScore# = score# total= 0
ELSE REM *** FOR 5 times DO
IF score# < lowestScore# FOR c = 1 TO 5
lowestScore# = score# PRINT “Hit any key to roll the dice”
ENDIF WAIT KEY
ENDIF REM *** Throw both dice ***
NEXT c dice1 = RND(5) +1
REM *** Subtract highest & lowest from dice2 = RND(5) +1
total *** REM *** Display throw & dice values ***
total# = total# - (highestScore# + PRINT “Throw : ”,c," Dice 1 : “,dicel,
lowestScore#) ” Dice 2 : “,dice2
REM *** Calculate and display average *** REM *** IF both dice are 1 THEN exit ***
average# = total# / (N-2) IF dice1 = 1 AND dice2 = 1
PRINT “The average score was : ”, average# EXIT
REM *** End program *** ENDIF
WAIT KEY REM *** Add dice throws to total ***
END total = total + dicel + dice2
NEXT c
REM *** Display final score ***
No attempt at validation has been made. You could have PRINT “Your final score was : ”, total
added WHILE loops to make sure the number of judges REM *** End program ***
and the scores were within acceptable limits. WAIT KEY
END

Activity 5.17
REM *** Set up day names ***
Activity 5.20
DATA “Sunday”, “Monday”, “Tuesday”,
First version:
“Wednesday”, “Thursday”, “Friday”,"Saturday"
REM *** Read and display each day ***
REM *** Seed random number generator ***
FOR c = 1 TO 7
RANDOMIZE TIMER()
READ day$
DO
PRINT day$
REM *** Generate random position ***
NEXT c
x = RND(799)
REM *** End program ***
y = RND(599)
WAIT KEY
REM *** Move cursor to position ***
END
SET CURSOR x,y
REM *** Create random foreground colour ***
INK RGB(RND(255) ,RND(255) ,RND(255) ) ,0
Activity 5.18 REM *** Display full stop ***
REM *** Generate random value *** PRINT “.”
RANDOMIZE TIMER() LOOP
number = RND(99)+1 REM *** End program ***
FOR c = 1 TO 7 WAIT KEY
REM *** Guess the number *** END
INPUT “Enter your guess (1 to 100) : ”,
guess Second version:
WHILE guess < 1 OR guess > 100
PRINT “Your guess must be between 1 REM *** Seed random number generator ***
and 100" RANDOMIZE TIMER()
INPUT “Enter your guess again (1-100):”, DO
guess REM *** Generate random position ***
ENDWHILE x = RND(799)
REM *** Respond to guess *** y = RND(599)
IF guess = number REM *** IF (100,100) THEN Exit loop ***
PRINT “Correct” IF x = 100 AND y = 100
ELSE EXIT

DarkBASIC Pro: Iteration 155


ENDIF REM *** Set total to zero ***
REM *** Move cursor to position *** total = 0
SET CURSOR x,y REM *** FOR 6 times DO
REM *** Create random foreground colour *** FOR c = 1 TO 6
INK RGB(RND(255) ,RND(255) ,RND(255) ) ,0 REM ***, Get valid score ***
REM *** Display full stop *** INPUT “Enter score : ”,score
PRINT “.” WHILE score < 0 OR score > 100
LOOP PRINT “Score must be between 0 and 100"
REM *** End program *** INPUT “Re-enter score : ”, score
WAIT KEY ENDWHILE
END REM *** Add score to total ***
total = total + score
NEXT c
Activity 5.21 REM *** Calculate and display average ***
average = total / 6
REM *** Seed random number generator *** PRINT “Average score is ”, average
RANDOMIZE TIMER() REM *** End program ***
DO WAIT KEY
x = RND(799) END
y = RND(599)
IF x = 100 AND y = 100
EXIT Activity 5.24
ENDIF
SET CURSOR x,y Output would be:
INK RGB (RND (255) ,RND(255) ,RND(255)) ,0
PRINT “.” -20
WAIT 500 -21
LOOP -22
REM *** End program *** -23
WAIT KEY -10
END -11
-12
-13
Activity 5.22 00
01
A one second delay: 02
03
REM *** Wait 1 second *** 10
SLEEP 1000 11
REM *** Display message *** 12
PRINT “Press any key” 13
REM *** Record start time ***
start = TIMER()
REM *** Wait for key press *** Activity 5.25
WAIT KEY
REM *** Record finish time *"* REM *** FOR each player DO ***
finish = TIMER() FOR player = 1 TO 4
REM *** Calculate and display duration *** PRINT “Enter scores for player ”, player
duration = finish - start REM *** Set total to zero ***
PRINT “You took ”, duration, “ milliseconds” total = 0
REM *** End program *** REM *** FOR 6 times DO
WAIT KEY FOR game = 1 TO 6
END REM *** Get valid score ***
INPUT “Enter score : ”,score
A variable delay: WHILE score < 0 OR score > 100
PRINT “Score must be between 0 and
100"
REM *** Seed random number generator ***
INPUT “Re-enter score : ”, score
RANDOMIZE TIMER ()
ENDWHILE
REM *** Wait 1 second ***
REM *** Add score to total ***
SLEEP 1000 + RND(2000)
total = total + score
REM *** Display message ***
NEXT game
PRINT “Press any key”
REM *** Calculate and display average ***
REM *** Record start time ***
average = total / 6
start = TIMER()
PRINT “Average score is ”, average
REM *** Wait for key press ***
NEXT player
WAIT KEY
REM *** End program ***
REM “** Record finish time ***
WAIT KEY
finish = TIMER()
END
REM “** Calculate and display duration ***
duration = finish - start
PRINT “You took ”, duration, “ milliseconds” Notice that the line
REM *** End program ***
WAIT KEY PRINT “Enter scores for player ”, player
END
displays the player's number. This helps the user keep
tabs on whose set of game scores is being entered.
Activity 5.23

156 DarkBASIC Pro: Iteration


Activity 5.26
Possible test data is shown below:
Test Run Test Data Iterations

1 num = 0 0

2 num = 50
num = 0 1

3 num = 12
num = 8
num = 0 2

The first test run should highlight a problem with the


code. The line

average = total / count

will be calculated as

average = 0 / 0

and division by zero is an invalid operation which causes


the program to terminate.

DarkBASIC Pro: Iteration 157


158 DarkBASIC Pro: Iteration
6

A First Look at Animation Techniques


Drawing Basic Shapes on the Screen
Erasing Shapes

DarkBASIC PRO: Drawing Statements 159


Drawing On The Screen
Introduction
As well as outputting text to the screen, DarkBASIC Pro contains various
commands which allow us to draw basic shapes such as lines circles, and boxes on
the screen. Like output text, we can select the colour of these shapes.

Basic Drawing Commands


The DOT Statement
This command draws a single pixel at a specified point. The pixel will be drawn in
the current foreground colour (as set using the INK command). The statement takes
the format shown in FIG-6.1.
FIG-6.1
The DOT Statement DOT x , y

In the diagram:

x,y are integer values specifying the coordinates of


the pixel to be drawn. These values should specify
a position within the bounds of the current screen
resolution. For example, if the screen is set to 800
by 600, then the coordinates of the pixel can range
from (0,0) to (799,599).

To draw a yellow pixel at position (100,80) on the screen we would use the
following statements:

REM *** Change foreground colour to yellow ***


INK RGB(255,255,0),0
REM *** Draw the pixel ***
DOT 100,80

The program in LISTING-6.1 places 1000 randomly coloured dots at random


positions on the screen using the following logic:

Clear the screen


FOR 1000 times DO
Change to a randomly chosen foreground colour
Choose a random position on the screen
Place pixel at that position
ENDFOR

LISTING-6.1 REM *** Seed random number generator ***


RANDOMIZE TIMER()
Random Dots REM *** Clear the screen ***
CLS
FOR c = 1 TO 1000
REM *** Choose a colour at random ***
colour = RGB(RND(255),RND(255),RND(255))

continued on next page

160 DarkBASIC PRO: Drawing Statements


LISTING-6.1 INK colour,0
(continued) REM *** Choose random position on screen ***
x = RND(800)
Random Dots y = RND(600)
REM *** Draw pixel on screen ***
DOT x,y
NEXT c
REM *** End program ***
WAIT KEY
END

Activity 6.1

Type in and test the program in LISTING-6.1 (dots01.dbpro).

Modify the program so that 10,000 dots are drawn.

Activity 6.2

dots01.dbpro assumes a screen resolution of 800 by 600. If you are using a


different resolution the pixels will not be spread correctly over the whole
screen.

Modify dots01.dbpro to make sure the random dots occupy the whole screen
no matter what resolution is being used.

(HINT: You’ll need to use SCREEN WIDTH and SCREEN HEIGHT)

The POINT Statement


We can discover the colour of any pixel on the screen using the POINT command.
This statement returns the colour of specified pixel on the screen and has the format
shown in FIG-6.2.
FIG-6.2
The POINT Statement POINT ( x , y )

integer
In the diagram:

x,y is a pair of integer values giving the position of


the screen pixel whose colour is to be returned.

Colours are represented by large integer values (as we saw when using the RGB
statement back in Chapter 2). Therefore, to check if a pixel is a specific colour, say,
red, then we need to use a statement such as:

IF POINT(100,100) = RGB(255,0,0)
PRINT ”The pixel is red"

Alternatively, we might use the colour returned by the POINT statement to set the
foreground (or background) colour with a statement such as:

INK POINT(200,5),0

DarkBASIC PRO: Drawing Statements 161


Activity 6.3

Modify dots01.dbpro so that once the 10,000 dots are showing on the screen,
the program picks a pixel position at random and displays one of two
messages:
The pixel at {position given here} is black
or
The pixel at {position given here} is not black

(HINT: RGB (0, 0, 0) specifies black.)

The LINE Statement


The LINE statement draws a line between two points. The line is drawn using the
foreground colour. The statement takes the format shown in FIG-6.3.
FIG-6.3
The LINE Statement LINE x1 , y1 , x2 , y2

In the diagram:

x1, y1 are the coordinates of the starting point of the line.

x2, y2 are the coordinates of the end point of the line.

For example, the statements

CLS RGB(0,0,255)
The background colour is INK RGB(255,255,0),0
not used when drawing LINE 80,50,300,90
shapes.

would produce a yellow line on a blue background as shown in FIG-6.4.


FIG-6.4
0,0
Drawing a Line on the
Screen 80,50
yellow
300,90

The program in LISTING-6.2 demonstrates the use of the LINE command by


drawing an arrow constructed from three lines.

LISTING-6.2 REM *** Clear the screen ***


CLS
Using the LINE REM *** Set foreground colour to red ***
Statement INK RGB(255,0,0),0

REM *** Draw lines ***


LINE 50,50,250,50
LINE 250,50,200,25
LINE 250,50,200,75

REM *** End program ***


WAIT KEY
END

162 DarkBASIC PRO: Drawing Statements


Activity 6.4

Type in and test LISTING-6.2 (arrow01.dbpro).

Activity 6.5

Write a program (gallows01.dbpro) to draw the following shape:

You may find it useful to


draw the gallows on
some squared paper
before starting to code.

Lines should be in yellow with a red background.

The BOX Statement


The BOX statement is used to draw a filled-in rectangle. There are two versions of
this statement. Using the simplest form, the coordinates of the top-left corner and
bottom-right corner of the required box must be supplied. For example, we could
create a box shown in FIG-6.5 using the statement:

BOX 100,120,400,180

FIG-6.5 (100,120)

Using the BOX


Statement

The rectangle is drawn in (400,180)


the current foreground colour

Activity 6.6

Modify gallows01.dbpro so that the output produced now looks as follows:

The second, longer version of the BOX statement can create a much more colourful
rectangle. This statement takes four additional colour parameters which are used to
fill in the four corners of the rectangle. Away from the corners the colours merge
into each other. The effect is rather psychedelic!

DarkBASIC PRO: Drawing Statements 163


An example of the fill effect is shown in the following code

c1 = RGB(255,0,0)
c2 = RGB(0,255,0)
c3 = RGB(0,0,255)
c4 = RGB(255,255,0)
BOX 10,10,100,100,c1,c2,c3,c4

Activity 6.7

Modify your gallows01.dbpro project so that the box is filled with various
colours.
Feel free to experiment with the colours you use.

FIG-6.6 The format for the BOX statement is shown in FIG-6.6.


The BOX Statement

BOX x1 , y1 , x2 , y2
[ , c1 , c2 , c3 , c4

In the diagram:

x1,y1 represent the coordinates of the top-left corner of


the box.

x2,y2 represent the coordinates of the bottom-right


corner of the box.

c1,c2,c3,c4 represent the fill colours used in the four corners


of the box.

Activity 6.8

By creating a short program, identify which corner is assigned to each of the


colour parameters in the BOX statement.

The CIRCLE Statement


You can draw a circle using the CIRCLE statement. Unlike the rectangle created
by the BOX command, CIRCLE creates an outline only; the inside of the circle is
not filled. The centre of the circle and its radius must be specified. For example,

CIRCLE 100,120,50

creates the circle shown in FIG-6.7.


FIG-6.7
Using the CIRCLE
Statement This isn’t visible
when the circle appears
on the screen

Centre of circle The radius of the


(100,120) circle is 50 pixels

164 DarkBASIC PRO: Drawing Statements


The statement has the format shown in FIG-6.8.
FIG-6.8
The CIRCLE Statement CIRCLE x , y , radius

In the diagram:

x,y are the coordinates of the centre of the circle.

radius is an integer value giving the radius of the circle


(in pixels).

Activity 6.9

Modify your gallows01.dbpro program so that your display now displays the
figure shown below.

The ELLIPSE Statement


You can draw an ellipse using the ELLIPSE statement. Like the CIRCLE command,
ELLIPSE creates an outline only. The ELLIPSE command takes four parameters
detailing the centre of the ellipse, the horizontal radius and the vertical radius. For
example, the line

ELLIPSE 300,200,120,80

will create output similar to that in FIG-6.9.


FIG-6.9
The vertical
Using the ELLIPSE radius is 80 pixels
Statement

Centre of ellipse The horizontal


(300,200) radius is 120 pixels

The format of the ELLIPSE statement is shown in FIG-6.10.

FIG-6.10
The ELLIPSE Statement ELLIPSE x , y , hradius , vradius

DarkBASIC PRO: Drawing Statements 165


In the diagram:

x,y are the coordinates of the centre of the ellipse.

hradius is an integer value giving the horizontal radius of


the ellipse (in pixels).

vradius is an integer value giving the vertical radius of


the ellipse (in pixels).

Activity 6.10

Using an ellipse and four more lines, complete the “hangman” symbol as
shown below.

Summary
l The DOT x,y statement places a single pixel on the screen at position (x,y) using
the current foreground colour.

l The POINT (x,y) statement returns the colour currently showing at position (x,y)
on the screen.

l Use LINE x1,y1,x2,y2 to draw a line between (x1,y1), (x2,y2).

l Use BOX x1,y1,x2,y2 to draw a filled rectangle with top-left corner at the point
(x1,y1) and bottom-right corner at (x2,y2).

l Use BOX x1,y1, x2, y2,c1,c2,c3,c4 to draw a filled box using colours c1, c2, c3
and c4 which radiate from the four corners of the rectangle.

l Use CIRCLE x,y,r to draw the outline of a circle with centre (x,y) radius r.

l Use ELLIPSE x,y,hr,vr to draw the outline of an ellipse with centre (x,y),
horizontal radius hr and vertical radius vr.

166 DarkBASIC PRO: Drawing Statements


Demonstrating Basic Shapes
Introduction
This section contains the longest program we’ve created so far. It allows the user
to select any basic graphics shape (from those described on the previous pages);
choose a colour for the shape, and then draw the requested object on the screen.

The program uses the following logic:

Display a menu of possible shapes


Get the user’s choice of shape
Display a menu of possible colours
Get the user’s choice of colour
Set foreground colour to the one selected
Display the requested object

The implementation of the program is given in LISTING-6.3.


LISTING-6.3 REM *** Display menu of possible shapes ***
PRINT “Choose from the following shapes”
Displaying Basic PRINT “1 - Pixel ”
Graphics Shapes PRINT “2 - Line”
PRINT “3 - Box”
PRINT “4 - Circle”
PRINT “5 - Ellipse”

REM *** Get user’s choice ***


INPUT “Enter option : ”, choiceshape
WHILE choiceshape < 1 OR choiceshape > 5
PRINT “That was an invalid choice. 1 to 5 only”
INPUT “Enter option : ”,choiceshape
ENDWHILE

REM *** Display possible colours ***


PRINT “Choose from the following colours”
PRINT “1 - Red”
PRINT “2 - Green”
PRINT “3 - Blue”
PRINT “4 - Yellow”
PRINT “5 - Cyan”
PRINT “6 - Magenta”

REM *** Get user’s choice ***


INPUT “Enter option : ”, choicecolour
WHILE choicecolour < 1 OR choicecolour > 6
PRINT “That was an invalid choice. 1 to 6 only”
INPUT “Enter option : ”,choicecolour
ENDWHILE

REM *** Change to selected colour ***


SELECT choicecolour
CASE 1
foreground = RGB(255,0,0)
ENDCASE
CASE 2
foreground = RGB(0,255,0)
ENDCASE
CASE 3
foreground = RGB(0,0,255)
ENDCASE

continued on next page

DarkBASIC PRO: Drawing Statements 167


LISTING-6.3 CASE 4
(continued) foreground = RGB(255,255,0)
ENDCASE
Displaying Basic CASE 5
Graphics Shapes foreground = RGB(0,255,255)
ENDCASE
CASE 6
foreground = RGB(255, 0,255)
ENDCASE
ENDSELECT

REM *** Set foreground colour, clear screen and draw shape ***
INK foreground,0
CLS
SELECT choiceshape
CASE 1 ‘*** Pixel ***
DOT 300,250
ENDCASE
CASE 2 ‘*** Line ***
LINE 20,50,300,120
ENDCASE
CASE 3 ‘*** Rectangle ***
BOX 20,50,300,150
ENDCASE
CASE 4 ‘*** Circle ***
CIRCLE 300,250,50
ENDCASE
CASE 5 ‘*** Ellipse ***
ELLIPSE 300,250,50,15
ENDCASE
ENDSELECT

REM *** End program ***


WAIT KEY
END

Activity 6.11

Type in and test the program in LISTING-6.3 (shapes01.dbpro).

Modify the program so that, once a shape has been displayed, the user can
select other shapes and colours. To do this add a loop structure to the code and
insert a QUIT option to the shapes menu. The program should terminate when
this quit option is chosen.

168 DarkBASIC PRO: Drawing Statements


A First Look at Animation
Basic Concepts
To animate a simple object on the screen we need to draw the image on the screen,
wait for a fraction of a second (so that your brain gets time to register that something
has appeared on the screen) and then make the object disappear. These three steps
are repeated, drawing the object in a slightly different position on each occasion.

How to Remove an Object from the Screen


Back in Chapter 2 we saw how to remove text from the screen by overwriting the
text with an exact duplicate of itself using the background colour. This same
technique can also be used to remove drawings from the screen.

If we draw a yellow circle on a black background, we can make that circle disappear
by drawing a black circle in exactly the same place. This technique is demonstrated
in LISTING-6.4 which employs the following logic:

Set the foreground colour to yellow


Draw a circle
Wait for a key press
Set the foreground colour to black
Draw a circle

LISTING-6.4 REM *** Set foreground to yellow ***


foreground = RGB (255,255,0)
Removing an Object from INK foreground, 0
the Screen
REM *** Draw the circle ***
x = 300
y = 250
CIRCLE x, y, 5

REM *** Wait for a key press ***


WAIT KEY

REM *** Change foreground colour to black ***


foreground = RGB (0,0,0)

REM *** Draw the circle in black ***


INK foreground, 0
CIRCLE x, y, 5

REM *** End program ***


WAIT KEY
END

Activity 6.12

Type in and test the program in LISTING-6.4 (disappear.dbpro)

Modify the program to use a box rather than a circle.

Notice that the circle in project disappear.dbpro is not removed until a key is
pressed. However, an alternative approach is to remove the circle automatically
after a given amount of time has passed. We have two statements that can make the

DarkBASIC PRO: Drawing Statements 169


machine halt for a given time - SLEEP and WAIT (as described in the last chapter).

Activity 6.13

Modify your last program by removing the WAIT KEY statement between
displaying and hiding the yellow circle and replacing it with a SLEEP
statement that waits 1 second before making the circle disappear.

How to Move an Object


The next stage in the animation process is to redraw our object at a different position.
If we write a program which uses the following logic

y = 250
FOR x = 1 TO 600 DO
Show circle at position (x,y)
Wait 20 milliseconds
Hide circle at position (x,y)
ENDFOR

then we should see the circle travel across the middle of the screen. This logic is
coded in LISTING-6.5.

LISTING-6.5 REM *** Set y-ordinate of object ***


y = 250
Animating an Object
REM *** FOR x-ordinate varies from 1 TO 600 DO
FOR x = 1 TO 600
REM *** Set foreground to yellow ***
foreground = RGB(255,255,0)
INK foreground,0
REM *** Draw the circle ***
CIRCLE x,y,5
REM *** Wait for 20 milliseconds ***
WAIT 20
REM *** Change foreground colour to black ***
foreground = RGB(0,0,0)
REM *** Draw the circle ***
INK foreground,0
CIRCLE x,y,5
NEXT x

REM *** End program ***


WAIT KEY
END

Activity 6.14

Type in and test the program in LISTING-6.5 (moving.dbpro).

Modify the program so that the circle moves faster.

Modify the program so that the circle moves vertically rather than horizontally.

This gives you some idea of how we can give the impression of movement on the
screen. However, we don’t want too spend too much time using this approach to
animation since DarkBASIC Pro has a much better way of doing this type of
operation using sprites which we’ll find out about in a later chapter.

170 DarkBASIC PRO: Drawing Statements


Solutions REM *** End program ***
Activity 6.1
WAIT KEY
The modified version of the program is: END

REM *** Seed random number generator ***


RANDOMIZE TIMER() Activity 6.4
CLS
FOR c = 1 TO 10000 No solution required.
REM *** Choose a colour at random ***
colour = RGB(RND(255),RND(255),RND(255))
INK colour,0 Activity 6.5
REM *** Choose random position ***
x = RND(800) The code for gallows01.dbpro is :
y = RND(600)
DOT x, y REM *** Set colours ***
NEXT c paint = RGB(255,255,0)
REM *** End program *** paper = RGB(255,0,0)
WAIT KEY REM *** Create a red screen ***
END CLS paper
REM *** Set drawing colour
INK paint,paper
Activity 6.2 REM *** Draw long vertical ***
LINE 50,100,50,200
The code for this new version of Dots is: REM *** Draw horizontal ***
LINE 50,100,100,100
REM *** Seed random number generator *** REM *** Draw short vertical ***
RANDOMIZE TIMER() LINE 100,100,100,120
REM *** Get the screen dimensions *** REM *** End program ***
width = SCREEN WIDTH() WAIT KEY
height = SCREEN HEIGHT() END
REM *** Clear the screen ***
CLS Obviously, you will have used different coordinates from
FOR c = 1 TO 10000 the ones given in this solution.
colour = RGB(RND(255),RND(255),RND(255))
INK colour,0
x = RND(width) Activity 6.6
y = RND(height)
REM *** Draw a pixel on screen *** REM *** Set colours ***
DOT x,y paint = RGB(255,255,0)
NEXT c paper = RGB(255,0,0)
REM *** End program *** REM *** Create a red screen ***
WAIT KEY CLS paper
END REM *** Set drawing colour
INK paint,paper
REM *** Draw long vertical ***
Activity 6.3 LINE 50,100,50,200
REM *** Draw horizontal ***
REM *** Seed random number generator *** LINE 50,100,100,100
RANDOMIZE TIMER () REM *** Draw short vertical ***
REM *** Get the screen dimensions *** LINE 100,100,100,120
width = SCREEN WIDTH () REM *** Draw platform ***
height = SCREEN HEIGHT() BOX 10,200,100,230
REM *** Clear the screen ***
CLS REM *** End program ***
FOR c = 1 TO 10000 WAIT KEY
REM *** Choose a colour at random *** END
colour = RGB(RND(255),RND(255),RND(255))
INK colour,0
REM *** Choose random position *** Activity 6.7
x = RND(width)
Y = RND(height) An example of the new BOX line would be:
REM *** Draw a pixel on screen ***
DOT x, y BOX(10,200,100,230,RGB(0,255,255),
NEXT c RGB(0,255,0),RGB(0,0,255),RGB(255,0,255)
REM *** Check colour of random pixel ***
x = RND(width)
y = RND(height) Activity 6.8
IF POINT(x,y) = RGB(0,0,0)
PRINT “The pixel at position (”,x,",",y, The colours are used in the following order:
“)is black”
ELSE c1 = bottom left
PRINT “The pixel at position (”,x,",",y, c2 = top left
“)is not black” c3 = bottom right
ENDIF c4 = top right

DarkBASIC PRO: Drawing Statements 171


Activity 6.9 WHILE choicecolour < 1 OR choicecolour > 6
PRINT “That was an invalid choice.
From the coordinates used in the Gallows project so far, 1 to 6 only”
INPUT “Enter option : ”,choicecolour
drawing the head requires the lines:
ENDWHILE
REM *** Draw head *** REM *** Change to selected colour ***
CIRCLE 100,125,5 SELECT choicecolour
CASE 1
foreground = RGB (255,0,0)
Activity 6.10 ENDCASE
CASE 2
REM *** Set colours ***
foreground = RGB (0,255,0)
paint = RGB(255,255,0)
ENDCASE
paper = RGB(255,0,0)
CASE 3
REM *** Create a red screen ***
foreground = RGB (0,0,255)
CLS paper
ENDCASE
REM *** Set drawing colour
CASE 4
INK paint,paper
foreground = RGB (255,255,0)
REM *** Draw long vertical ***
ENDCASE
LINE 50,100,50,200
CASE 5
REM *** Draw horizontal ***
foreground = RGB (0,255,255)
LINE 50,100,100,100
ENDCASE
REM *** Draw short vertical ***
CASE 6
LINE 100,100,100,120
foreground = RGB (255, 0,255)
REM *** Draw head ***
ENDCASE
CIRCLE 100,125,5
ENDSELECT
REM *** Draw body ***
REM *** Set foreground colour, ***
ELLIPSE 100,145,7,15
REM *** clear screen and draw shape ***
REM *** Left leg ***
INK foreground, 0
LINE 97,156,90,176
CLS
REM *** Right leg ***
SELECT choiceshape
LINE 103,156,110,176
CASE 1 ‘*** Pixel ***
REM *** Left arm ***
DOT 300,250
LINE 97,132,85,150
ENDCASE
REM *** Right arm ***
CASE 2 ‘*** Line ***
LINE 103,132,115,150
LINE 20,50,300,120
ENDCASE
REM *** End program ***
CASE 3 ‘*** Rectangle ***
WAIT KEY
BOX 20,50,300,150
END
ENDCASE
CASE 4 ‘*** Circle ***
CIRCLE 300,250,50
Activity 6.11 ENDCASE
CASE 5 ‘*** Ellipse ***
The program needs a few small additions to add the ELLIPSE 300,250,50,15
required feature. These additions are highlighted. ENDCASE
ENDSELECT
REPEAT PRINT “Press any key to continue”
REM *** Display menu of possible shapes *** WAIT KEY
PRINT “Choose from the following shapes” UNTIL choiceshape = 6
PRINT “1 - Pixel ”
PRINT “2 - Line” REM *** End program ***
PRINT “3 - Box” WAIT KEY
PRINT “4 - Circle” END
PRINT “5 - Ellipse”
PRINT “6 - QUIT”
Activity 6.12
REM *** Get user’s choice ***
INPUT “Enter option : ”, choiceshape REM *** Set foreground to yellow ***
WHILE choiceshape < 1 OR choiceshape > 6 foreground = RGB(255,255,0)
PRINT “That was an invalid choice. INK foreground,0
1 to 6 only”
INPUT “Enter option : ”,choiceshape REM *** Draw the box ***
ENDWHILE x1 = 300
y1 = 250
REM *** Display possible colours *** x2 = 400
PRINT “Choose from the following colours” y2 = 280
PRINT “1 - Red” BOX x1,y1,x2,y2
PRINT “2 - Green”
PRINT “3 - Blue” REM *** Wait for key press ***
PRINT “4 - Yellow” WAIT KEY
PRINT “5 - Cyan”
PRINT “6 - Magenta” REM *** Set foreground colour to black ***
foreground = RGB(0,0,0)
REM *** Get user’s choice ***
INPUT “Enter option : ”, choicecolour REM *** Draw the box in black ***

172 DarkBASIC PRO: Drawing Statements


INK foreground, 0 CIRCLE x, y, 5
BOX x1,y1,x2,y2 REM *** Wait for 5 milliseconds ***
WAIT 5
REM *** End program *** REM *** Change foreground to black ***
WAIT KEY foreground = RGB (0,0,0)
END REM *** Draw the circle ***
INK foreground, 0
CIRCLE x, y, 5
Activity 6.13 NEXT y

REM *** Set foreground to yellow *** REM *** End program ***
foreground = RGB(255,255,0) WAIT KEY
INK foreground,0 END

REM *** Draw the box ***


x1 = 300
y1 = 250
x2 = 400
y2 = 280
BOX x1,y1,x2,y2

REM *** Wait for 1 second ***


SLEEP 1000

REM *** Set foreground colour to black ***


foreground = RGB(0,0,0)

REM *** Draw the box in black ***


INK foreground, 0
BOX x1,y1,x2,y2

REM *** End program ***


WAIT KEY
END

Activity 6.14
To increase the speed, the delay should be reduced:

REM *** Set y-ordinate of object ***


y = 250

REM *** FOR x-ordinate varies from 1 TO


600 DO
FOR x = 1 TO 600 DO
REM *** Set foreground to yellow ***
foreground = RGB (255,255,0)
INK foreground,0
REM *** Draw the circle ***
CIRCLE x, y, 5
REM *** Wait for 5 milliseconds ***
WAIT 5
REM *** Change foreground to black ***
foreground = RGB (0,0,0)
REM *** Draw the circle ***
INK foreground, 0
CIRCLE x, y, 5
NEXT x

REM *** End program ***


WAIT KEY
END

To make the circle move vertically, the x-ordinate must


remain fixed while the y-ordinate value changes:

REM *** Set x-ordinate of object ***


x = 250

REM *** FOR y-ordinate varies from 1 TO


600 DO
FOR y = 1 TO 600 DO
REM *** Set foreground to yellow ***
foreground = RGB (255,255,0)
INK foreground,0
REM *** Draw the circle ***

DarkBASIC PRO: Drawing Statements 173


174 DarkBASIC PRO: Drawing Statements
7

Creating Functions

Global Variables

GOSUB Statement

Local Variables

Mini-Specs

Modular Programming

Parameter Passing

Pre-Conditions

Post-Conditions

Return Values

DarkBASIC Pro: Modular Programming 175


Functions
Introduction
Look at the computer in front of you. Notice how it is made up of several separate
components: keyboard, screen, mouse, and inside the main casing are other discreet
pieces such as the hard disk and CDROM.

Why are computers made this way, as a collection of separate pieces rather than
have everything encased in a single frame?

Well, there are several reasons. Firstly, by using separate components each can be
designed to perform just one specific task such as: get information from the user
(keyboard); display information (the screen); store information (the disk) etc. This
allows all of these items to be made and tested separately.

Also, if a component breaks down or needs to be replaced, you simply have to


unplug that component and replace it with a new one.

Why is all of this relevant to creating games programs? Years of experience have
shown that the advantages of this modular approach to construction doesn’t just
apply to physical items such as computers, it also applies to software.

Rather than create programs as one continuous set of instructions, we can split the
program into several routines (also known as modules or subroutines), each
routine being designed to perform just one specific function. This is particularly
important in long programs and when several programmers are involved in creating
the software.

In fact, routines in DarkBASIC Pro are often referred to as functions, and that’s the
term we’ll use from here on in.

We’ll demonstrate this technique by rewriting the Basic Shapes program


(LISTING-6.3) that we created in the last chapter in a modular fashion.

Functions
Designing a Function
The first stage in creating a function is to decide on what task the function has to
perform. For example, we might want a function to display a set of menu options
(look back at LISTING-6.3 and you’ll see examples of several simple menus).

When a team of people is involved in creating the software, it is important that the
exact purpose of each routine is written out in detail so there can be no
misconceptions between the people designing the routine and those programming
it.

Functions must also be given a name. This name should reflect the purpose of the
function and usually starts with a verb, since functions perform tasks.

176 DarkBASIC Pro: Modular Programming


Coding a Function
So, let’s start by creating a function called ShowShapeMenu which displays the
various shapes that can be drawn on the screen. The code for this function is shown
below:

FUNCTION ShowShapeMenu()
PRINT “Choose from the following options”
PRINT “1 - Pixel”
PRINT “2 - Line”
PRINT “3 - Box”
PRINT “4 - Circle”
PRINT “5 - Ellipse”
ENDFUNCTION

Notice that the module begins with the keyword FUNCTION and ends with the
keyword ENDFUNCTION.

The first line also contains the name of the function, ShowShapesMenu, and an
empty set of parentheses.

Between the first and last lines go the set of instructions that perform the task the
function has been designed to do.

Calling a Function
When you type in a program’s code, place any functions you have at the end of that
code (see LISTING-7.1).
LISTING-7.1 REM *** Display a message ***
PRINT “Shape drawing program”
Adding a Function
REM *** End program ***
WAIT KEY
END

REM *** Display shape options ***


FUNCTION ShowShapeMenu()
PRINT “Choose from the following options”
PRINT “1 - Pixel”
PRINT “2 - Line”
PRINT “3 - Box”
PRINT “4 - Circle”
PRINT “5 - Ellipse”
ENDFUNCTION

Activity 7.1

Type in and run the program given in LISTING-7.1 (functions01.dbpro).

NOTE: The menu will not appear when you run the program.

As you’ve just had demonstrated, functions are totally ignored when you run your
program. You might as well have saved yourself some typing for all the good it did!
It’s only the code before the function, known as the main section, that is executed.

The code within a function is only executed if you make a call to that function.

Calling a function is taken as a request to execute the code within a function, and

DarkBASIC Pro: Modular Programming 177


you make that call by simply giving the function name (including the parentheses)
at the point in the main program where you’d like the function’s lines to be executed.
So, to execute the code within the ShowShapeMenu function we use the line:

ShowShapeMenu()

An updated version of the program is shown in LISTING-7.2.

LISTING-7.2 REM *** Display a message ***


PRINT “Shape drawing program”
Calling a Function
REM *** Call function ***
ShowShapeMenu()

REM *** End program ***


WAIT KEY
END

REM *** Display shape options ***


FUNCTION ShowShapeMenu ()
PRINT “Choose from the following options”
PRINT “1 - Pixel”
PRINT “2 - Line”
PRINT “3 - Box”
PRINT “4 - Circle”
PRINT “5 - Ellipse”
ENDFUNCTION

Activity 7.2

Modify your project to match LISTING-7.2 and check that the menu is
displayed.

Notice that when you ran the program the message Shape drawing program
appeared before the menu options. This is because the PRINT statement appears
before the line

ShowShapeMenu()

which executes the function.


FIG-7.1
FIG-7.1 shows what’s happening when a function is executed.
How a Function is
Executed

1 2
Execution starts in When a call to ShowShapeMenu
the main section is made, control passes to the routine

Main ShowShapeMenu

REM *** Display a message *** REM *** Display shape options ***
3
PRINT “Shape drawing program” FUNCTION ShowShapeMenu ()
The function is then executed
PRINT “Choose from the following options”
REM *** Call function *** PRINT “1 - Pixel”
ShowShapeMenu() PRINT “2 - Line”
PRINT “3 - Box”
REM *** End program *** PRINT “4 - Circle”
WAIT KEY PRINT “5 - Ellipse”
END ENDFUNCTION

4
5 When the function is complete,
The remainder of main control returns to the main section at the
is then executed first command following the function call

178 DarkBASIC Pro: Modular Programming


Activity 7.3

Reverse the order of the lines

PRINT “Shape drawing program”


ShowShapeMenu()

in your code and run the program again.

Another Example
We’ll leave the shape program for the moment and have a look at another example.
The function in LISTING-7.3 (DrawTextLine()) draws a line of asterisks on the
screen.

LISTING-7.3 REM *** Draw a line of asterisks ***


DrawTextLine ()
Calling the REM *** Display a message ***
DrawTextLine() Function PRINT “ Hello”
REM *** End program ***
WAIT KEY
END

REM *** Draw a line of asterisks ***


FUNCTION DrawTextLine ()
PRINT “*******************”
ENDFUNCTION

Activity 7.4

Enter the program in LISTING-7.3 (testline.dbpro) and run it.

Activity 7.5

Write a function called DrawTextBox which displays a 5 by 5 box of asterisks


as shown below:

*****
*****
*****
*****
*****

Create a project (testbox.dbpro) which calls up this function and check that the
box is drawn successfully.

You can call a function as often as you want from the main program. All you have
to do is repeat the calling line. Hence, if we change the main program in project
testline.dbpro to

DrawTextLine()
PRINT “ Hello”
DrawTextLine()

the DrawTextLine() function will be called twice and we will see a row of asterisks
both above and below the word Hello.

DarkBASIC Pro: Modular Programming 179


Activity 7.6

Modify your testline.dbpro project to draw a line of asterisks both above and
below the word Hello.

Make a second change so that two lines of asterisks appear below Hello.

Parameters
Sometimes we need to supply information to a function. For example, the
DarkBASIC Pro statement DOT is actually a function and, when it is called, we
need to supply it with details of where we want the pixel to be displayed. Each piece
of information that we give to a function is known as a parameter to that function.

We’ll see how parameters work by rewriting the DrawTextLine() so that the number
of asterisks that are to appear in the line can be specified.

When a function needs to be supplied with information, we give that piece of


information a name and place it in the parentheses following the function name. In
DrawTextLine() we want to specify the size of the line to be drawn, so we’ll supply
it with a parameter called size. That makes the first line of our function now read:

FUNCTION DrawTextLine(size)

To make use of this information we’ll have to rewrite the code for our function so
that a single asterisk is output size times. Our new version of the routine is coded
as:

FUNCTION DrawTextLine(size)
FOR c = 1 TO size
PRINT “*”;
NEXT c
PRINT
ENDFUNCTION

Now, if we’re going to call the function, we need to supply a value for size. Hence,

DrawTextLine (25)

FIG-7.2 causes the DrawTextLine() function to be executed and sets the value of size to 25
Passing a Parameter to a
(thereby drawing a line of 25 asterisks). The mechanism involved is shown visually
Function in FIG-7.2.
1 2
Execution starts in When a call to DrawTextLine
the main section is made, control passes to the routine

3
The parameter and local
Main DrawTextLine variables are created

REM *** Draw a line of asterisks *** size


DrawTextLine (25) FUNCTION DrawTextLine(size)
FOR c = 1 TO size 25
REM *** Display a message *** PRINT “*”; 4
PRINT “ Hello” NEXT c c The value used in the
PRINT function call is copied
REM *** End program *** ENDFUNCTION into size
WAIT KEY
END
5
The function is then executed

6
When the function is complete,
7
control returns to the main section at the
The remainder of main
first command following the function call
is then executed

180 DarkBASIC Pro: Modular Programming


Activity 7.7

Modify your testline.dbpro project so that the DrawTextLine() function is


coded with the size parameter as shown earlier.

Change the main program so that the line above Hello contains 5 asterisks,
while the last two rows contain 15 asterisks.

Activity 7.8

Modify your DrawTextBox() function so that the height of the box is passed as
a parameter (it will remain 5 asterisks wide).

To test the function, read in a value from the keyboard and use this value as
the parameter to your routine.

A function can have as many parameters as you require and these parameters can
be of any type: integer, real or string. To demonstrate this we’ll write yet another
version of the DrawTextLine() function in which the character used to construct the
line is also passed as a parameter.

FUNCTION DrawTextLine (size, char$)


REM *** Display size characters ***
FOR c = l TO size
PRINT char$;
NEXT c
REM *** Move cursor to next line ***
PRINT
ENDFUNCTION

Notice that parameters are separated from each other by commas. We can tell that
the second parameter is a string by the fact that its name ends with the dollar ($).

We have to supply two values when we call the function; one to be given to size,
the other to char$. A typical call would be

DrawTextLine (20, “=”)

which would assign the value 20 to size and the string “=” to char$ and thereby
produce a line on the screen created from twenty = symbols.

It’s important that you put the values in the correct order when you call up the
function. For example, the line

DrawTextLine (“=” ,20)

would be invalid since the function expects the first value given in the parentheses
is the integer to be assigned to the size parameter.

Activity 7.9

Modify your DrawTextBox() function so that the character used can be passed
as a parameter.

Check that it works by drawing a box 10 lines high constructed from the #
character.

DarkBASIC Pro: Modular Programming 181


Pre-conditions
When a function uses parameters, we will often need to restrict the range of values
which may sensibly be assigned to the parameter. For example, when we specify
what length of line we want DrawTextLine() to produce, it doesn’t make sense to
specify negative value for the parameter size. Equally, it makes little sense to request
a line hundreds of characters long since there is a limit to how many characters can
fit on a single line of the screen. We might therefore expect the value specified for
size to be in a range such as 0 to 80.

When we place limitations on the conditions under which a function can operate
successfully, these limitations are known as the pre-conditions of the function. We
can therefore state that the pre-condition for DrawTextLine() is that size lies between
0 and 80.

Now we need some way of enforcing this limit. We do this by adding an IF statement
at the beginning of the DrawTextLine() function which causes that function to be
aborted if the value of size is outside the acceptable range.

The EXITFUNCTION Statement


The EXITFUNCTION statement is designed to be placed within a function. When
executed, this statement causes the remaining statements in the function to be
ignored, ending execution of the routine and returning to the code which called the
function in the first place.

We can make use of this statement to terminate execution of a function when its
parameter(s) fall outside an acceptable range. In the case of DrawTextLine(), we
would add the following statement to check the value of size:

REM *** IF size outside range 0 to 80, terminate function ***


IF size < 0 OR size > 80
EXITFUNCTION
ENDIF

The complete routine is now coded as

FUNCTION DrawTextLine(size, char$)


REM *** IF size invalid, terminate function ***
IF size < 0 OR size >80
EXITFUNCTION
ENDIF
REM *** Display size characters ***
FOR c = 1 TO size
PRINT char$;
NEXT c
REM *** Move cursor to next line ***
PRINT
ENDFUNCTION

Now, if we were to make a call to this function with a line such as

DrawTextLine (95, “-”)

the function will abort since the value assigned to size will be outside the range 0
to 80, and no line will be drawn on the screen.

182 DarkBASIC Pro: Modular Programming


Activity 7.10

Modify your TestLines project so that DrawTextLine() contains its


pre-condition check as shown above.

Check that the function now operates only within the limits set by running the
program using size values of -1, 0, 80 and 81.

Activity 7.11

Assuming the pre-condition for DrawTextBox() is that height should lie within
the range 0 to 24, add the appropriate IF structure to the function and test that
the new code operates correctly.

Activity 7.12

Create a new project called testsums.dbpro.

This project is to contain a function named SumIntegers() which takes a


parameter called number and displays the total of all values between 1 and
number (i.e. if number = 5, then the value displayed would be 15, that being
the sum of 1+2+3+4+5).

A pre-condition for this routine is that number should lie between 1 and 50.

Create a main program to read in an integer value which is passed as a


parameter to Sumlntegers(). So that the routine can be tested with several
values, use the following logic in the main program:

Get number

WHILE number not zero DO

Call SumIntegers(number)

Get number
ENDWHILE

Return Types
Not only can we supply values to a function (in the form of parameters), but some
functions also return results. For example, in the Sumlntegers() function that we
designed earlier, we actually limit the usefulness of the routine by displaying the
result rather than returning it. After all, the main program may have wanted to use
the answer in some calculation rather than have it displayed on the screen.

To return a value from a DarkBASIC Pro function we add the value to be returned
immediately after the term ENDFUNCTION. A new version of Sumlntegers() is
shown below:
FUNCTION SumIntegers(number)
total = 0
FOR c = 1 TO number
total = total + c
NEXT c
ENDFUNCTION total

Notice that the pre-condition check has been removed from the function - more
about that later.

DarkBASIC Pro: Modular Programming 183


When a function is designed to return a value, then the main program which calls
that function will want to do something with the value that is returned. For example,
we could still display the result of summing the numbers 1 to 10 by using the line:

PRINT SumIntegers(10)

This line causes the SumIntegers() function to be executed and then displays the
value returned by the function.

We could store the value returned in a variable with a line such as:

ans = SumIntegers(10)

If required, we could use the returned value in a calculation:

result = SumIntegers (10) / 2

or in an IF statement:

IF SumIntegers(12) > 1000

Activity 7.13

Create a project called testfact.dbpro and in it write a function called


Factorial() which takes a single integer parameter, v, and returns the values
produced by multiplying every number between 1 and v. For example, if v had
the value 5 then the value returned would be the result of the calculation
1x2x3x4x5.

Test the function to make sure it operates correctly.

If a function returns a string value, then the name of the function must end with a
dollar sign. For example, the function FilledString$(ch$, num) returns a string
containing num copies of ch$:
A function that returns a FUNCTION FilledString$ (ch$, num)
string is often referred to result$ = ""
as a string function. FOR c = 1 TO num
result$ = result$ + ch$
NEXT c
ENDFUNCTION result$

Why was the pre-condition check for SumIntegers() removed? Well, by creating a
return value, we introduced a problem. It is no longer sufficient to write

IF number < 1 OR number > 50


EXITFUNCTION

because SumIntegers() is now designed to return a value, and it is no longer legal


to exit that function without returning that value. This means that the
EXITFUNCTION statement as shown above is no longer valid since it attempts to
exit the return without returning a value. Luckily, the statement format allows for
a value to be specified after the keyword EXITFUNCTION. But that just leaves us
with another problem - what value should we return when the routine does not meet
its pre-conditions?

We can return any value we like, but usually this is handled by returning some
special value which cannot occur when the function’s pre-conditions are met. For

184 DarkBASIC Pro: Modular Programming


example, here we could return the value -1, since it is an impossible result to achieve
when number does lie between 1 and 50. We would do this with the line:

EXITFUNCTION -1

This allows us to add back the pre-condition to our routine, the final version of the
code being:

FUNCTION SumIntegers(number)
IF number < 1 OR number > 50
EXITFUNCTION -1
total = 0
FOR c = 1 TO number
total = total + c
NEXT c
ENDFUNCTION total

Activity 7.14

Modify your Factorial() function from the last Activity so that it implements
the pre-condition that v must lie between 1 and 25.

When a function such as SumIntegers() (which returns a dummy result if its


pre-condition has not been met) is called, you must check that it has performed
correctly. This is done with code such as:
INPUT “Enter your number ”, number
result = SumIntegers(number)
IF result = -1
PRINT “The program could not calculate the sum 1 to ”,number
ELSE
PRINT “1 to ”,number,"= “, result
ENDIF

Better still, the program should make sure the value passed is acceptable before
making a call to Sumlntegers (). We could do this with the code:

INPUT “Enter your number ”, number


WHILE number < 1 OR number > 50
PRINT “Invalid number, must be between 1 and 50"
INPUT “Re-enter number : ”, number
ENDWHILE
result = SumIntegers(number)

We’ve introduced three new function-related statements in this section; the format
of these are given in FIG-7.3, FIG-7.4 and FIG-7.5.
FIG-7.3
The FUNCTION
Statement

In the diagram:
FUNCTION function name (

[ parameter

,
)

function name is the name of the function. The name chosen


must conform to the rules of identifier name
creation. If a string value is returned by the
function, the name should end with a dollar
symbol.

DarkBASIC Pro: Modular Programming 185


parameter is the name of any value passed to the function.
Names should be appropriate for the type of
value being passed.
FIG-7.4
The ENDFUNCTION
Statement
ENDFUNCTION
[ return value

In the diagram:

return value is the value returned by the function. This can be


specified using a variable, constant or expression.
FIG-7.5
The EXITFUNCTION
Statement
EXITFUNCTION
[ return value

In the diagram:

return value is the value returned by the function. This can be


specified using a variable, constant or expression.

Local Variables
When you make use of a variable inside a function (other than a parameter), that
variable exists only within that function. If you look at the code for SumIntegers()
you’ll see two variables which are used within the function: c and total. This type
of variable is known as a local variable: it exists only while the function is being
executed. Once the function has been executed, these local variables cease to exist.
We can prove this with a little experiment shown in the code below:

REM *** The main program ***


num = 10
Test()
PRINT num
WAIT KEY
END

FUNCTION Test()
num = 15
ENDFUNCTION

Function Test() assigns the value 15 to a variable called num. The main program
assigns the value 10 to num, executes Test() and then displays the value in num.
What value do you think appears on the screen?

Activity 7.15

Type in the code given above (local.dbpro) and check out what value is
displayed on the screen.

There are in fact two variables called num. One of these exists only within Test()
and, although it is assigned the value 15, that variable ceases to exist when Test()
has been completed. When execution returns from the function back to the main
program, we have come back to the part of the program where the other variable
called num exists - and that variable still contains the value 10 as assigned to it.

The program doesn’t have a problem with there being two variables of the same

186 DarkBASIC Pro: Modular Programming


name: it’s like having two students called John - as long as they are in different
classes then there’s no problem if the tutor calls on John he is obviously referring
to the one in the class he is currently teaching.

There is no way to access the main program’s variable called num from within Test()
and there is no way to access Test()‘s num from within the main program (although
you could access it’s value by returning num at the end of the function).

FIG-7.6 gives a visual representation of this situation.


FIG-7.6
Local Variables A variable called num
is created in the main program...
REM *** The main program *** num
num = 10
10
Test()
PRINT num ... and assigned the These are two
value 10 separate variables
num
A variable called num 15
FUNCTION Test() is created in Test()...
num = 15
ENDFUNCTION ... and assigned the
value 15

Global Variables
It is possible to make a variable available anywhere in a program by using the term
GLOBAL when the variable is created. So, if we change the previous example to
now read

REM *** The main program ***


GLOBAL num = 10
Test()
PRINT num
WAIT KEY
END

FUNCTION Test()
num = 15
ENDFUNCTION

by declaring num as GLOBAL, it is no longer possible to create a local variable


named num, and therefore the program lines

GLOBAL num = 10
num = 15
PRINT num

now all refer to the same variable.

Activity 7.16

Add the word GLOBAL to the appropriate line in your local.dbpro program
and find out what difference this makes to the value displayed.

DarkBASIC Pro: Modular Programming 187


Designing Routines
In the real world we have to design routines before we can think of turning them
into code. So far, we’ve been quite informal in how we’ve described a routine before
going on to write it. However, any company involved in creating software will have
a precise standard for designing routines. One possible design is given below using
the SumIntegers() function as an example.

NAME : SumIntegers
PARAMETERS
IN : num : integer
OUT : result : integer
PRE-CONDITION : 1 <= num <= 50
DESCRIPTION : The routine sets result to the sum of all integer values
between 1 and num.
OUTLINE LOGIC : Set result to zero

FOR c = 1 TO num DO

Add c to result

ENDFOR

This specification of a routine is often known as a mini-spec. Most of its contents


should be self-explanatory. We start with the routine’s name, followed by the
parameters. Notice that the value returned by the routine is given as an OUT
parameter.

The pre-condition specifies any limits imposed on an IN parameter. Here, for


example, it states that num must lie between 1 and 50. If a routine is passed a value
which does not meet the stated pre-condition, then the routine will fail to perform
the task for which it is designed.

The Description explains in English what the routine should do, while the Outline
Logic describes in structured English how the task should be done.

Specifying a Post-Condition
Some mini-specs make use of a post-condition statement which specifies what
should be true when the routine has been successfully executed. For example, the
pre-condition for SumIntegers would be:

POST-CONDITION : result = sum of the integer values between 1 and num.

Often a post-condition will be very similar to the description. When used, the
post-condition statement follows immediately after the pre-condition statement.

The DrawTextLine Mini-Spec


Overleaf are the mini-specs for the first and last versions of DrawTextLine().

NAME : DrawTextLine
PARAMETERS
IN : None
OUT : None

188 DarkBASIC Pro: Modular Programming


PRE-CONDITION : None
DESCRIPTION : The routine draws a horizontal line of 20 asterisks.
OUTLINE LOGIC : Display “********************”

NAME : DrawTextLine
PARAMETERS
IN : size : integer
ch : character
OUT : None
PRE-CONDITION : 0<=size<=80
DESCRIPTION : The routine draws a horizontal line constructed
from size occurrences of ch.
OUTLINE LOGIC : FOR c = 1 TO size DO

Display ch (keep cursor on same line)

ENDFOR

Move cursor to start of next line

In the last example, notice that the second parameter does not contain a dollar sign
as part of its name and that its type is declared as character, not string. This is
because a design should be independent of the programming language that you
finally use to implement that design. DarkBASIC Pro-specific requirements, such
as ending string variable names with a dollar symbol, or reals with the hash
character, having string functions end their name with a dollar sign, or using only
integer, real and string types, should be avoided in your designs.

So, just what are you allowed to use in a design? Names (functions and variables)
should conform to the following rules:

Ø Must begin with a letter


Ø Can continue with letter or numeric characters
Variable types can be any of the following:

Ø integer
Ø real
Ø string
Ø character (a single character)
Ø Boolean (a variable that is set to true or false)

Even the main section of the program should be designed in the form of a mini-spec.
For example, in order to test the DrawTextLine() function, we could create a main
program which implements the following specification:

NAME : Main
PARAMETERS
IN : None
OUT : None
PRE-CONDITION : None
DESCRIPTION : The routine is designed to test DrawTextLine(). It
allows the length and character making up the line

DarkBASIC Pro: Modular Programming 189


to be entered from the keyboard and passes these as
parameters when the DrawTextLine() is called.
The program terminates when -99 is entered.
OUTLINE LOGIC : REPEAT

Get size

Get character

Call DrawTextLine(size, character)

UNTIL size = -99

The implementation of both the DrawTextLine and Main mini-specs is shown in


LISTING-7.4.

LISTING-7.4 REPEAT
INPUT “Enter size of line (-99 to end) : ”, size
Displaying the Menu INPUT “Enter character used in line creation : ”, ch$
DrawTextLine(size,ch$)
UNTIL size = -99
END

REM *** Draw a line of characters ***


FUNCTION DrawTextLine(size, ch$)
REM *** IF pre-condition not met THEN exit routine ***
IF size < 0 OR size > 80
EXITFUNCTION
ENDIF
REM *** Draw line ***
FOR c = 1 TO size
PRINT ch$;
NEXT c
REM *** Move cursor to start of next line ***
PRINT
ENDFUNCTION

Activity 7.17

Write a DarkBASIC Pro function (in a project called testsmallest.dbpro)


which implements the following design:

NAME : Smallest
PARAMETERS
IN : no1 : integer
no2 : integer
no3 : integer
OUT : result : integer
PRE-CONDITION : None
DESCRIPTION : The routine sets result equal to the the smallest
of the values no1, no2, and no3.
IF all three values are the same, that value
should be returned in result.
OUTLINE LOGIC : IF no1 < no2 AND no1 < no3 THEN

result := no1

ELSE

IF no2 < no1 AND no2 < no3 THEN

result := no2

ELSE

result := no3

ENDIF

ENDIF

190 DarkBASIC Pro: Modular Programming


Activity 7.18

Create a design for a main section to test function Smallest().


Implement your design and use it to check that Smallest() functions correctly.

Creating Modular Software


Now that we know the basic techniques required to design and implement functions
in DarkBASIC Pro, we’re ready to rewrite the shapes.dbpro project that we
produced in the last program. The original program is listed again below (see
LISTING-7.5).
LISTING-7.5 REM *** Display menu of possible shapes ***^
PRINT “Choose from the following shapes”
The Original PRINT “1 - Pixel ”
shapes.dbpro Program PRINT “2 - Line”
PRINT “3 - Box”
PRINT “4 - Circle”
PRINT “5 - Ellipse”

REM *** Get user’s choice ***


INPUT “Enter option : ”, choiceshape
WHILE choiceshape < 1 OR choiceshape > 5
PRINT “That was an invalid choice. 1 to 5 only”
INPUT “Enter option : ”,choiceshape
ENDWHILE

REM *** Display possible colours ***


PRINT “Choose from the following colours”
PRINT “1 - Red”
PRINT “2 - Green”
PRINT ”3 - Blue”
PRINT “4 - Yellow”
PRINT ”5 - Cyan"
PRINT “6 - Magenta”

REM *** Get user’s choice ***


INPUT “Enter option : ”, choicecolour
WHILE choicecolour < 1 OR choicecolour > 6
PRINT “That was an invalid choice. 1 to 6 only”
INPUT “Enter option : ”,choicecolour
ENDWHILE

REM *** Save foreground colour ***


SELECT choicecolour
CASE 1
foreground = RGB (255,0,0)
ENDCASE
CASE 2
foreground = RGB (0,255,0)
ENDCASE
CASE 3
foreground = RGB (0,0,255)
ENDCASE
CASE 4
foreground = RGB (255,255,0)
ENDCASE
CASE 5
foreground = RGB (0,255,255)
ENDCASE
CASE 6
foreground = RGB (255, 0,255)
ENDCASE continued on next page

DarkBASIC Pro: Modular Programming 191


LISTING-7.5 ENDSELECT
(continued) REM *** Set foreground colour, clear screen and draw shape ***
INK foreground, 0
The Original CLS
shapes.dbpro Program SELECT choiceshape
CASE 1 ‘*** Pixel ***
DOT 300,250
ENDCASE
CASE 2 ‘*** Line ***
LINE 20,50, 300, 120
ENDCASE
CASE 3 ‘*** Rectangle ***
BOX 20,50,300,150
ENDCASE
CASE 4 ‘*** Circle ***
CIRCLE 300,250,50
ENDCASE
CASE 5 ‘*** Ellipse ***
ELLIPSE 300,250,50,15
ENDCASE
ENDSELECT
REM *** End program ***
WAIT KEY
END

Since the code is already divided into obvious sections, each doing a specific job,
it’s quite easy to see what functions are required. The mini-spec for each identified
routine is shown below.

NAME : Main
PARAMETERS
IN : None
OUT : None
PRE-CONDITION : None
DESCRIPTION : The program displays a selected shape in a specified
colour. The user selects which shape is required.
(pixel, line, rectangle, circle or ellipse) and the colour
to be used (red, green, blue, yellow, cyan or magenta).
OUTLINE LOGIC : Display shapes menu

Get user’s choice

Display colour menu

Get user’s choice

Draw chosen shape

NAME : ShowShapeMenu
PARAMETERS
IN : None
OUT : None
PRE-CONDITION : None
DESCRIPTION : The routine displays the option available to the user
when choosing a shape to be displayed.
The display should show the following options:
1 - Pixel; 2 - Line; 3 - Box; 4 - Circle; 5 - Ellipse
OUTLINE LOGIC : Display “1 - Pixel”

Display “2 - Line”

Display “3 - Box”

Display “4 - Circle”

Display “5 - Ellipse”

192 DarkBASIC Pro: Modular Programming


NAME : GetUserChoice
PARAMETERS
IN : max : integer
OUT : choice : integer
PRE-CONDITION : 0<=max<=72
DESCRIPTION : The routine gets an integer value from the keyboard
which is returned in choice.
The value entered must lie between 1 and max
otherwise an error message is displayed and the user
must re-enter the value.
OUTLINE LOGIC : Display “Enter choice 1 - ”,max

Get choice

WHILE choice < 1 OR choice > max DO

Display “That is an invalid choice. 1 to ”,max,“ only”

Get choice

ENDWHILE

Notice that the above specification is flexible enough to be used to get the user’s
choice of both shape and colour.

NAME : ShowColourMenu
PARAMETERS
IN : None
OUT : None
PRE-CONDITION : None
DESCRIPTION : The routine displays the option available to the user
when choosing the colour of the shape.
The display should show the following options:
1 - Red; 2 - Green; 3 - Blue; 4 - Yellow; 5 - Cyan;
6 - Magenta.
OUTLINE LOGIC : Display “1 - Red”

Display “2 - Green”

Display “3 - Blue”

Display “4 - Yellow”

Display “5 - Cyan"

Display “6 - Magenta””

This specification for ShowColourMenu is similar to the one for ShowShapeMenu,


but since the actual options offered differ between the two routines, we are forced
to write separate mini-specs for each.

NAME : SetInkColour
PARAMETERS
IN : choice : integer
OUT : result : integer (colour value)
PRE-CONDITION : 1 <= choice <= 6
DESCRIPTION : The routine sets result to a colour value based on
choice. Settings are as follows:
choice colour
1 red
2 green
3 blue

DarkBASIC Pro: Modular Programming 193


4 yellow
5 cyan
6 magenta
OUTLINE LOGIC : IF

choice = 1: result := red

choice = 2: result := green

choice = 3: result := blue

choice = 4: result := yellow

choice = 5: result := cyan

choice = 6: result := magenta

ENDIF

NAME : DisplayChosenShape
PARAMETERS
IN : choice : integer
colour : integer
OUT : None
PRE-CONDITION : 1 <= choice <= 5
DESCRIPTION : The routine displays the shape chosen by the user.
The screen is cleared and the foreground colour set
to colour.
If choice is 1, a pixel is drawn at (300,250)
If choice is 2, a line is drawn from (20,50) to
(300,120)
If choice is 3, a rectangle is drawn with top-left at
(20,50) and bottom-right at (300,150)
If choice is 4, a circle is drawn with its centre at
(300,250). Its radius is 50.
If choice is 5, an ellipse is drawn. Its centre is at
(300,250). The horizontal radius is 50; the vertical
radius, 15.
OUTLINE LOGIC : Set foreground colour to colour

Clear the screen

IF

choice = 1: Draw pixel at (300,250)

choice = 2: Draw line between points (20,50) and

(300,120)

choice = 3: Draw a rectangle between points

(20,50) and (300,150)

choice = 4: Draw a circle of radius 50 and

centred at (300,250)

choice = 5: Draw an ellipse with centre at

(300,250). The horizontal radius

is 50 and the vertical radius 15.

ENDIF

Now we’re ready to start turning our design into a program.

There are various ways to tackle this. If we had several people working on the
program, we could give each a separate routine to work on at the same time. It would
then just be a matter of bringing together the separate routines to give us the final
program.

On the other hand, if only one person is working on the coding, the routines are

194 DarkBASIC Pro: Modular Programming


coded one after another, usually starting with Main.

Top-Down Programming
When we code our routines one at a time, starting with Main, this is known as
top-down programming. The name is used because we start with the main part of
the program (the top) and then work our way through the routines called by that
main part. We’ll see how it’s done below.

Step 1

We start by turning the outline logic given in the mini-spec for Main into
DarkBASIC Pro program code. An important point to note is that the program code
must match that logic in the mini-spec exactly. If we find we have to deviate from
this logic then we must go back and modify the details given in that mini-spec.
Actually, the code for Main becomes little more than a set of calls to the other
routines:

Rem ***** Main Section *****


ShowShapeMenu()
shapeoption = GetUserOption(5)
ShowColourMenu()
colouroption = GetUserOption(6)
DisplayChosenShape(shapeoption,colouroption)

REM *** End program ***


WAIT KEY
END

Notice that Main really doesn’t do any of the detailed work, it leaves that to the
routines. Main only has to call up each of the routines in the correct order and save
any values returned by one function to pass it on to another function. For example,
it saves the user’s choice of shape (in shapeoption) from GetUserOption() and then
passes that value on to DisplayChosenShape().

In order to write Main you need to know the names and purposes of the other
routines as well as what parameters are passed and what values are returned from
those routines. We should test our program, even at this early stage in its
development, to ensure that the routines are executed in the correct order and that
the proper parameters are passed between the routines. But there’s a problem. The
program can’t run without the routines that Main is attempting to call. The compiler
will simply complain about calls to non-existent routines.

Activity 7.19

Create a new project called shapes2.dbpro.

Type in Main as given above and attempt to compile it.

Step 2

To get Main to run we must write code for the routines that are called. And yet, if
we do that, it would appear that the whole program will need to be completed before
the program can be executed for the first time.

The way round this problem is to write empty routines with the required names,
parameters and return values as shown below.

DarkBASIC Pro: Modular Programming 195


FUNCTION ShowShapeMenu()
PRINT “DisplayShapesMenu”
ENDFUNCTION
FUNCTION GetUserOption(max)
PRINT “GetUserOption”
ENDFUNCTION 1
FUNCTION ShowColourMenu()
PRINT “DisplayColourMenu”
ENDFUNCTION
DarkBASIC Pro will not FUNCTION SetInkColour(choice)
accept the line PRINT “SetInkColour”
result = RGB(255,0,0)
ENDFUNCTION ENDFUNCTION result
RGB(255,0,0) FUNCTION DisplayChosenShape(choice,colour)
PRINT “DisplayChosenShape”
and hence, the test stub ENDFUNCTION
for SetInkColour() has
had an extra line added Take a moment to look at this code. Each function displays its own name, takes
to set up a viable return parameters, and returns a value where necessary. Again, we need to make sure that
value.
the names, parameter names and return types match with those given in the
mini-specs. These empty routines are known as test stubs, and are written so that
we can test Main without having the final code for any of the routines which Main
has to call.

Activity 7.20

Add the stubs given above to your shapes2.dbpro project.

Attempt to run the program again.

Does it execute this time?

Step 3

Now we can begin to remove the stubs in our project and replace them with the final
version of each routine, always testing as each new routine is added to make sure
the new routine, and the program as a whole, are working correctly.

Activity 7.21

We have already written the ShowShapeMenu() function.

Replace the stub for this routine with its full code.

Run the program again and check that the appropriate menu is displayed on
the screen.

The code for GetUserOption() is:

FUNCTION GetUserOption (max)


INPUT “Enter option : ”,choice
WHILE choice < 1 OR choice > max
PRINT “That was an invalid choice. 1 to ”,max," only"
INPUT “Enter option : ”,choice
ENDWHILE
ENDFUNCTION choice

196 DarkBASIC Pro: Modular Programming


Activity 7.22

Add the code for GetUserOption() and check that it operates correctly.

Activity 7.23

Enter the code for each of the remaining routines, checking that the program
operates correctly at each stage.

Bottom-Up Programming
If you’re working as part of a team of programmers, then you’re likely to get landed
with having to code a specific routine which, when completed, will be handed over
to the team leader. He will then add your routine to the main program.

So let’s assume we’ve just been landed with the job of writing the GetUserOption()
function. How do we go about doing this job? Well, it’s just a matter of getting hold
of the mini-spec for the routine and turning it into a coded function. In the case of
GetUserOption() we should end up with the following code:
FUNCTION GetUserOption(max)
INPUT “Enter option : ”, choice
WHILE choice < 1 OR choice > max
PRINT “That was an invalid choice. 1 to ”,max," only."
INPUT “Enter option : ”, choice
ENDWHILE
ENDFUNCTION choice

Although we might be tempted to think our job is done at this point, we really need
to check that our routine is operating correctly. It won’t do your reputation as a
programmer any good if you hand over code which contains obvious faults.

To test a routine, we start by making sure that what we’ve written conforms to the
requirements of the mini-spec. Once we’re happy with that, then the code itself must
be tested. Since a function only executes when called by another piece of code, we
need to write a main program which will call up the function we want to test. This
main program, known as a test driver, needs to perform four main tasks:

Ø Supply a value for any parameters required by the function


Ø Execute the function
Ø Display the value of any parameters passed to the function
Ø Display any value returned by the function
So, our test driver for GetUserOption() could be coded as follows:

DO
REM *** Get a value for parameter ***
INPUT “Enter a value for max : ”,max
REM *** IF -1 entered, exit loop ***
IF max = -1
EXIT
ENDIF
REM *** Call function being tested ***
returnedvalue = GetUserOption(max)
REM *** Display function parameters ***
PRINT “max = ”,max

DarkBASIC Pro: Modular Programming 197


REM *** Display value returned ***
PRINT “Value returned by GetUserOption() = ”,returnedvalue
LOOP
REM *** End program ***
WAIT KEY
END

Notice that the main code is in a loop so that several tests can be carried out in a
single run.

Activity 7.24

Create a new project (bottomup.dbpro) and type in the code for


GetUserOption() and its test driver as given above.

Run the program and check that GetUserOption() is returning the expected
results.

Structure Diagrams
As we begin to develop more complex programs containing several routines, it can
be useful to retain an overview of the program’s structure, showing which routine
is called by which, and the values that pass between them. This is done with a
structure diagram.

FIG-7.7 A structure diagram contains one rectangle for each routine in a program, including
a rectangle representing Main. These rectangles contain the name of the routine they
A Graphical represent. The collection of rectangles for the shapes2.dbpro project is shown in
Representation of the FIG-7.7.
Routines in the System

Shapes System ShowShapeMenu GetUserOption ShowColourMenu SetInkColour DisplayChosenShape

Only Main has been renamed, with a new title to reflect the overall purpose of the
system.

The rectangles are now set in a series of levels, with Shapes System (the renamed
Main) at the top. On the second level are routines called by Shapes System. On the
third level are any routines called by second level routines. In addition, lines are
drawn between the rectangles to reflect which routine calls which (see FIG-7.8).

FIG-7.8
Shapes System
The Calling
Hierarchy of the
Routines

ShowShapeMenu GetUserOption ShowColourMenu GetUserOption DisplayChosenShape

SetInkColour

198 DarkBASIC Pro: Modular Programming


For example, from the diagram we can see that DisplayChosenShape calls the
routine SetInkColour.

Another point to note is that GetUserOption has been included twice. This is
because that routine is used to get two different items of data: on its first call it
returns the choice of shape, on the second call, the choice of colour.

Finally, we add any parameters passed between the routines (see FIG-7.9).

FIG-7.9
Shapes System
The Complete
Structure Diagram choice
Showing Parameters colour
max
max
choice colour

ShowShapeMenu GetUserOption ShowColourMenu GetUserOption DisplayChosenShape

colour

SetInkColour

The circle with arrowed line symbol in the diagram is used to show the direction in
which data is passed, with IN values pointing towards a routine and OUT parameters
pointing away from the routine.

Summary
l Good programming technique requires program code to be partitioned into
routines.

l Each routine should perform a single task.

l A routine’s name should reflect the purpose of that routine.

l Mini-specs should be produced when designing a routine.

l A mini-spec should include the name of the routine, its parameters, restrictions
of the range of values a parameter may take, a detailed description of the routine’s
purpose, and an outline logic specifying how the routine is to operate.

l A mini-spec may contain a post-condition which states what should be true once
the routine has been successfully executed.

l Where possible, a routine should be made as flexible as possible so that it can


be used in situations which differ slightly from the original requirement.

l DarkBASIC Pro allows us to write routines using the FUNCTION keyword.

l A function is executed by specifying the function name followed by parentheses.

l Values may be passed to a function as parameters.

DarkBASIC Pro: Modular Programming 199


l Where the value of a parameter must fall within a limited range, this restriction
should be tested for at the start of the function.

l Variables used within a function are normally local to that function.

l The term GLOBAL can be used to create a variable which can be accessed
anywhere within a program.

l Top-down programming begins by coding the main routine.

l Top-down programming using stubs in place of completed routines.

l Bottom-up programming starts by coding individual routines.

l Bottom-up programming uses test drivers to check that completed routines are
operating correctly.

l A structure diagram shows every routine in a program, how they are called, and
the values that pass between them.

200 DarkBASIC Pro: Modular Programming


Subroutines
Introduction
Using functions is probably the best way to create modular software in DarkBASIC
Pro, but the language does offer another way to achieve a similar effect, and that is
to use subroutines. Although we’ve used the term subroutine earlier to mean any
modular section of code, in DarkBASIC Pro the word has a more specific meaning
as we’ll see below.

Creating a Subroutine
The fact that we are going to use DarkBASIC Pro subroutines rather than functions
makes no difference to the design stage of a project - we still need to create
mini-specs identical to those shown earlier. But when we come to implement these
designs in DarkBASIC Pro, we will use subroutines instead of functions.

The start of a subroutine is marked with a label giving the name of the subroutine.
This will be the name given in the mini-spec.

A label is just a valid name followed by a colon, for example:

ShowShapeMenu:

Next comes the code of the routine:

ShowShapeMenu:
PRINT “Choose from the following shapes”^
PRINT “1 - Pixel ”
PRINT “2 - Line”
PRINT “3 - Box”
PRINT “4 - Circle”
PRINT “5 - Ellipse”

Finally, we end with the keyword RETURN:

ShowShapeMenu:
PRINT “Choose from the following shapes”^
PRINT “1 - Pixel ”
PRINT “2 - Line”
PRINT “3 - Box”
PRINT “4 - Circle”
PRINT “5 - Ellipse”
RETURN

The overall structure is shown in FIG-7.10.

FIG-7.10
label :
The Subroutine Construct

instruction

RETURN

DarkBASIC Pro: Modular Programming 201


Calling a Subroutine
The GOSUB Statement
To execute a subroutine we use the GOSUB statement (the term being a shortening
of GO to SUBroutine). This statement has the format shown in FIG-7.11.
FIG-7.11
GOSUB label
The GOSUB Statement

In the diagram:

label is the label name previously assigned to the


subroutine which is to be executed.

For example, the statement

GOSUB ShowShapesMenu

would cause the subroutine labelled ShowShapesMenu to be executed.

When the execution reaches the RETURN statement, the program jumps back from
the subroutine and continues by executing the line following the call to the
subroutine.

Activity 7.25

Create a project called subroutines.dbpro containing the ShowShapesMenu


subroutine as given earlier.

At the start of the program add the following lines:

REM *** Call subroutine ***


GOSUB ShowShapesMenu
REM *** End program ***
WAIT KEY
END

Run the program and check that the subroutine is correctly executed.

Subroutines are quite restricting since they cannot accept parameters nor return a
value.

This means that a routine such as GetUserChoice which has both an IN parameter
and a return value (OUT parameter) cannot be coded efficiently using a subroutine.

Variables in a Subroutine
Also, it is not possible to create local variables within a subroutine. When variables
of the same name are used in both the main program and a subroutine, these are
assumed be one and the same variable.

202 DarkBASIC Pro: Modular Programming


Activity 7.26

Create a new project (subvariables.dbpro) and enter the following code:

REM *** The main program ***


num = 10
GOSUB Test
PRINT num
WAIT KEY
END

REM *** Subroutine ***


Test:
num = 15
RETURN

Execute the program and check out what value is displayed on the screen.

As a general rule, it is best to avoid the use of DarkBASIC Pro's subroutines and
stick with functions since they offer a much greater flexibility.

Summary
l Subroutines are a group of instructions which begin with a label and end with
the term RETURN.

l A subroutine is called using the term GOSUB.

l A subroutine cannot accept parameters.

l A subroutine cannot return a value.

l A subroutine cannot contain local variables.

DarkBASIC Pro: Modular Programming 203


Solutions
Activity 7.1 Activity 7.7
No solution required. REM *** Execute function ***
DrawTextLine(5)
REM *** Display a message ***
Activity 7.2 PRINT “ Hello”
REM *** Execute function again ***
No solution required. DrawTextLine(15)
DrawTextLine(15)
REM *** End program ***
WAIT KEY
Activity 7.3 END
This time the message appears after the function has been
REM *** Draw a line of asterisks ***
executed. FUNCTION DrawTextLine(size)
FOR c = 1 TO size
PRINT “*”;
Activity 7.4 NEXT c
PRINT
No solution required. ENDFUNCTION

Activity 7.5 Activity 7.8


REM *** Call function *** REM *** Get value from user ***
DrawTextBox() INPUT “Enter number : ”, num
REM *** End program *** REM *** Call function using value input ***
WAIT KEY DrawTextBox(num)
END REM *** End program ***
REM *** Draw box of asterisks *** WAIT KEY
FUNCTION DrawTextBox() END
PRINT “*****”
PRINT “*****” REM *** Draw box of asterisks ***
PRINT “*****” FUNCTION DrawTextBox(height)
PRINT “*****” FOR c = 1 TO height
PRINT “*****” PRINT “*****”
ENDFUNCTION NEXT c
ENDFUNCTION

Activity 7.6
Line above and below text:
Activity 7.9
REM *** Get values from user ***
REM *** Execute function *** INPUT “Enter number : ”, num
DrawTextLine() INPUT “Enter character : ”, c$
REM *** Display a message *** REM *** Call function; use values input ***
PRINT “ Hello” DrawTextBox(num,c$)
REM *** Execute function again *** REM *** End program ***
DrawTextLine() WAIT KEY
REM *** End program *** END
WAIT KEY REM *** Draw box of characters ***
END FUNCTION DrawTextBox(height,ch$)
FOR c = 1 TO height
REM *** Draw a line of asterisks *** FOR k = 1 TO 5
FUNCTION DrawTextLine() PRINT ch$;
PRINT “************************” NEXT k
ENDFUNCTION PRINT
NEXT c
Line above and two lines below text: ENDFUNCTION

REM *** Execute function ***


DrawTextLine() Activity 7.10
REM *** Display a message ***
Rem ***** Main Source File *****
PRINT “ Hello”
INPUT “Enter size : ”, sz
REM *** Execute function again ***
REM *** Execute function ***
DrawTextLine()
DrawTextLine(sz)
DrawTextLine()
REM *** Display a message ***
REM *** End program ***
PRINT “ Hello”
WAIT KEY
REM *** Execute function again ***
END
DrawTextLine(sz)
DrawTextLine(sz)
REM *** Draw a line of asterisks ***
REM *** End program ***
FUNCTION DrawTextLine()
WAIT KEY
PRINT “************************”
END
ENDFUNCTION

204 DarkBASIC Pro: Modular Programming


REM *** Draw a line of asterisks *** WAIT KEY
FUNCTION DrawTextLine(size) END
IF size < 0 OR size > 80
EXITFUNCTION REM *** Calculate product of 1 to v ***
ENDIF FUNCTION Factorial(v)
FOR c = 1 TO size REM *** Start product at 1 ***
PRINT “*”; product = 1
NEXT c REM *** FOR all values 1 to v DO ***
PRINT FOR c = 1 TO v
ENDFUNCTION REM *** Multiply product by value ***
product = product * c
NEXT c
Activity 7.11 ENDFUNCTION product

REM *** Get values from user ***


INPUT “Enter number : ”, num Activity 7.14
INPUT “Enter character : ”, c$
REM *** Call function using values input *** INPUT “Enter a value : ”, num
DrawTextBox(num,c$) REM *** Call function and display result ***
REM *** End program *** PRINT “The product of the numbers 1 to ”,
WAIT KEY num," is “,Factorial(num)
END REM *** End program ***
WAIT KEY
REM *** Draw box of characters *** END
FUNCTION DrawTextBox(height,ch$)
IF height < 0 OR height > 24 REM *** Calculate product of 1 to v ***
EXITFUNCTION FUNCTION Factorial(v)
ENDIF IF v < 1 OR v > 25
FOR c = 1 TO height EXITFUNCTION -1
FOR k = 1 TO 5 ENDIF
PRINT ch$; REM *** Start product at 1 ***
NEXT k product = 1
PRINT REM *** FOR all values 1 to v DO ***
NEXT c FOR c = 1 TO v
ENDFUNCTION REM *** Multiple product by that
value ***
product = product * c
Activity 7.12 NEXT c
ENDFUNCTION product
REM *** Read in a number ***
INPUT “Enter a value : ”, value
REM *** Continue while number not zero *** Activity 7.15
WHILE value <> 0
REM *** Execute function *** The value 10 is displayed.
SumIntegers(value)
REM *** Get another number ***
INPUT “Enter a value : ”, value Activity 7.16
ENDWHILE
REM *** End program *** The value displayed is 15.
WAIT KEY
END
The function is now accessing the same variable (num) as
REM *** Sum values between 1 and number *** the main program.
FUNCTION SumIntegers(number)
REM *** IF pre-cond not met, exit ***
IF number < 1 OR number > 50 Activity 7.17
EXITFUNCTION
ENDIF
REM *** Find smallest of three values ***
REM *** Start sum at zero ***
FUNCTION Smallest(no1,no2,no3)
total = 0
IF no1 < no2 AND no1 < no3
REM *** FOR all values 1 to number DO ***
result = no1
FOR c = 1 TO number
ELSE
REM *** Add that number to sum ***
IF no2 < no1 AND no2 < no3
total = total + c
result = no2
NEXT c
ELSE
REM *** Display sum ***
result = no3
PRINT total
ENDIF
ENDFUNCTION
ENDIF
ENDFUNCTION result
Activity 7.13
REM *** Get a value *** Activity 7.18
INPUT “Enter a value : ”, num
REM *** Call function and display result *** The main section uses a WHILE loop to allow as many
PRINT “The product of the numbers 1 to ”, tests of the function as required. The program stops if -99
num," is “,Factorial(num) is entered as the first of the three values.
REM *** End program ***

DarkBASIC Pro: Modular Programming 205


REM *** Get three numbers ***
INPUT “Enter first number : ”, n1 REM *** Get user’s choice ***
WHILE n1 <> -99 FUNCTION GetUserOption(max)
INPUT “Enter second number : ”, n2 INPUT “Enter option : ”, choice
INPUT “Enter third number : ”, n3 WHILE choice < 1 OR choice > max
REM *** Call function & display result *** PRINT “That was an invalid choice.
PRINT “The smallest value is ” 1 to ”,max," only"
,Smallest(n1,n2,n3) INPUT “Enter option : ”,choice
REM *** Read first number again *** ENDWHILE
INPUT “Enter first number : ”,n1 ENDFUNCTION choice
ENDWHILE
REM *** End program *** REM *** Display possible colours ***
WAIT KEY FUNCTION ShowColourMenu()
END PRINT “Choose from the following
colours”
REM *** Find smallest of three values *** PRINT “1 - Red”
FUNCTION Smallest(no1,no2,no3) PRINT “2 - Green”
IF no1 < no2 AND no1 < no3 PRINT “3 - Blue”
result = no1 PRINT “4 - Yellow”
ELSE PRINT “5 - Cyan”
IF no2 < no1 AND no2 < no3 PRINT “6 - Magenta”
result = no2 ENDFUNCTION
ELSE
result = no3 REM *** Draw shape in selected colour***
ENDIF FUNCTION DisplayChosenShape(choice, colour)
ENDIF INK SetInkColour(colour),0
ENDFUNCTION result CLS
SELECT choice
CASE 1 ‘*** Pixel ***
Activity 7.19 DOT 300,250
ENDCASE
The program will not run since the functions it calls have CASE 2 ‘*** Line ***
not yet been written. LINE 20,50,300,120
ENDCASE
CASE 3 ‘*** Rectangle ***
Activity 7.20 BOX 20,50,300,150
ENDCASE
The program will now execute. CASE 4 ‘*** Circle ***
CIRCLE 300,250,50
ENDCASE
The PRINT statement in every function causes the name
CASE 5 ‘*** Ellipse ***
of each routine called to be displayed on the screen. ELLIPSE 300,250,50,15
ENDCASE
ENDSELECT
Activity 7.21 ENDFUNCTION

The ShowShapeMenu() function now displays the list of REM *** Change to selected colour ***
user options on the screen. FUNCTION SetInkColour(choice)
SELECT choice
CASE 1
Activity 7.22 result = RGB (255,0,0)
ENDCASE
No solution required. CASE 2
result = RGB (0,255,0)
ENDCASE
Activity 7.23 CASE 3
result = RGB (0,0,255)
The complete solution is given below: ENDCASE
CASE 4
REM *** Main program *** result = RGB (255,255,0)
ShowShapeMenu() ENDCASE
shapeoption = GetUserOption(5) CASE 5
ShowColourMenu() result = RGB (0,255,255)
colouroption = GetUserOption(6) ENDCASE
DisplayChosenShape(shapeoption,colouroption) CASE 6
REM *** End program *** result = RGB (255, 0,255)
WAIT KEY ENDCASE
END ENDSELECT
ENDFUNCTION result
REM *** Display menu of possible shapes ***
FUNCTION ShowShapeMenu()
PRINT “Choose from the following shapes” Activity 7.24
PRINT “1 - Pixel ”
PRINT “2 - Line” REM *** Test driver ***
PRINT “3 - Box” DO
PRINT “4 - Circle” REM *** Get a value for parameter ***
PRINT “5 - Ellipse” INPUT “Enter a value for max : ”,max
ENDFUNCTION IF max = -1

206 DarkBASIC Pro: Modular Programming


EXIT
ENDIF
REM *** Call function being tested ***
returnedvalue = GetUserOption(max)
REM *** Display function parameters ***
PRINT “max = ”,max
REM *** Display value returned ***
PRINT “Value returned by GetUserOption() = ”,
returnedvalue
LOOP
REM *** End program ***
WAIT KEY
END

FUNCTION GetUserOption(max)
INPUT “Enter option : ” ,choice
WHILE choice < 1 OR choice > max
PRINT “That was an invalid choice. 1 to ”,
max," only"
INPUT “Enter option : ”,choice
ENDWHILE
ENDFUNCTION choice

Activity 7.25
No solution required.

Activity 7.26
The value 15 is displayed. This is because the num referred to in the
main program and num in the subroutine are the same variable.

DarkBASIC Pro: Modular Programming 207


208 DarkBASIC Pro: Modular Programming
8

Creating a Library of Functions

Including Existing Code in a New Project

String Handling Functions Native to DarkBASIC Pro

User-Defined String-Handling Functions

DarkBASIC Pro: String Functions 209


Standard String Functions
Introduction
Unlike numeric variables which hold only a single value, strings can hold a whole
collection of characters, perhaps several words or even sentences. For example, it’s
quite valid to write:

poem$ = “Mary had a little lamb”

Because a string can contain so many characters, there are several operations that
programmers find themselves needing to do with strings. For example, we might
want to find out how many characters are in the string, convert a string to uppercase,
or extract part of a string.

DarkBASIC Pro contains many statements to help us perform some of these tasks,
as we shall see in the following pages.

String Operations
The LEN Statement
The LEN statement is a function which returns the number of characters in a string.
The string to be examined is given in parentheses. For example, the expression

LEN(“Hello”)

would return the value 5 since there are 5 characters in the word Hello.

The LEN statement has the format shown in FIG-8.1.


FIG-8.1
The LEN Statement
LEN ( string )

integer

In the diagram:

string is a string constant, string variable, or string


expression.

As with any function that returns a value, this value can be displayed, assigned to
a variable, or used in an expression. Hence each of the following lines are valid:

PRINT LEN(“Hello”) ‘displays 5


result = LEN(“Hello”) ‘sets result equal to 5
ans = LEN(“Hello”) *3 ‘sets ans to 15 (5 x 3)
IF LEN(“Hello”) > 3 ‘condition is true since 5 > 3

Of course, it’s much more likely that you’ll use a string variable as an argument
rather than a string constant. For example, the code

210 DarkBASIC Pro: String Functions


INPUT “Enter your name : ”,name$
PRINT “There are ”,LEN(name$), “ characters in your name.”

uses the variable name$ as the argument to LEN().

Activity 8.1

Create a project (stringlength.dbpro) containing the two lines given above and
test out the program.

Activity 8.2

Write a project (comparelengths.dbpro) which reads in two strings and


displays the shorter of the two.

The UPPER$ Statement


The UPPER$ statement takes a string argument and returns the uppercase version
of that string. Notice that the statement name ends with a dollar sign ($). This is an
indication that the statement returns a string and not the more usual integer.

PRINT UPPER$ (“Hello”)

would display the word HELLO.

Any characters in the string that are not letters are returned unchanged by this
statement. Hence,

PRINT UPPER$(“abc123")

would display ABC123.

As in all of these statements in this section, the argument can be a string constant,
variable or expression. The value returned by the function can be stored in a string
variable.

Activity 8.3

What value would be stored in b$ after the following statements are executed?

a$ = “1-by-1"
b$ = UPPER$(a$)

The UPPER$ statement has the format shown in FIG-8.2.


FIG-8.2
The UPPER$ Statement
UPPER$ ( string )

string

In the diagram:

string is any string value.

DarkBASIC Pro: String Functions 211


The LOWER$ Statement
The LOWER$ statement takes a string argument and returns the lowercase version
of that string. Any non-alphabetic characters in the string are returned unchanged.

PRINT LOWER$(“ Hello”)

would display the word hello.

This statement has the format shown in FIG-8.3.


FIG-8.3
The LOWER$ Statement LOWER$ ( string )

string

In the diagram:

string is any string value.

The LEFT$ Statement


It’s possible to extract the left section of a string using the LEFT$ statement. This
time you need to include two parameters: the first is the string itself, and the second
is the number of characters you want to extract. For example,

PRINT LEFT$ (“abcdef” , 2)

would display ab on the screen, LEFT$ having returned the left two characters from
the string abcdef.

If the number given is larger than the number of characters in the string as in

ans$ = LEFT$(“abcdef”,10)

then the complete string is returned (i.e. abcdef)

Should a zero, or negative value be given as in

result$ = LEFT$(“abcdef”,0)

then the returned string contains no characters. That is, result$ will hold an empty
string.

The LEFT$ statement has the format shown in FIG-8.4.

FIG-8.4
LEFT$ ( string , value )
The LEFT$ Statement

string

212 DarkBASIC Pro: String Functions


In the diagram:

string is any string value.

value is a positive integer value in the range 1 to the


number of characters in string.

The RIGHT$ Statement


If we want to extract the right-hand part of a string we can use the RIGHT$
statement. For example, the statement

PRINT RIGHT$(“abcdef”,2)

would display ef on the screen.

The statement has the format shown in FIG-8.5.

FIG-8.5
The RIGHT$ Statement RIGHT$ ( string , value )

string

In the diagram:

string is any string value.