a ISSN 0265-2910

a

il

FUN IN A DUNGEON The Multi-User Dungeon is an adventure game on a : 384 mainframe that home computers can access

~ THE SMART SET Coleco’s Adam comes

complete with a printer, word processor and Microdrive-style data storage

HE

aie Ce h oa ae

a. ae

WRITING FOR THE SCREEN

Professional software production uses a lot 381 of sophisticated hardware

ROCKET MAN A game for the Spectrum 30 and Vic-20 that is out of this world o

FROM DAISY WHEEL TO DATA CORRUPTION Our weekly glossary of computing terms

_

~ TREAD LIGHTLY We begin constructing a graphics program using BBC BAsIc 392

SHUFFLE THOSE DIGITS We give you. a numbers game to play around with | 39 9

Sites aa ° 00000000

PRIMITIVE PARTS Good programming benefits from the use of algorithms | 38

_ WINDOW DISPLAY A program that allows windows on the Spectrum screen

GLOBAL ENTERPRISE The Sharp | Corporation has a remarkable sales record 400 |

1) What is the difference between source code and object code? ~—S—rs—eOE _

2) How many pixels can be represented in one byte. in mode 5 on the BBC micro, and why? __

3) To write a program in BASIC on the Coleco : Adam, what must the user do after switching on the 4) What is the name of the company you work for when playing Jet Pac? _ :

Many home programmers dream of writing a best seller: But they rarely realise what they are up against. Professional software companies have enormous resources behind

-them to help produce their chart-toppers.

One UK software house has over £250,000 worth of minicomputers dedicated to creating packages for home micros.

Expensive equipment doesn’t necessarily mean successful programs; some amateur writers have managed to make a small fortune with software they’ve produced on a Spectrum at home. All the same, home programming whizzkids are becoming an endangered species, especially with the development of the big software houses over the past few years. Their powerful computers and sophisticated programming aids give them a real advantage over the home computer owner and allow their programmers to be more productive.

One of the most important attributes of serious software for home machines is the speed of operation; and this means that programs need to be written (at least in part) in machine code. But machine code is extremely difficult to work with in particular, machine code programmers need

WRITING FORTHE SCREEN

other pieces of software to help write their programs. At the very least, an assembler program will be required to translate the programmer’s source code into the object code that the machine understands, and this can be quite a challenging job if a big program is involved. Many software writers work in this way. To write a program for the Spectrum, for example, they will use an assembler program running on the same machine. This method has its limitations.

Primarily, the quality of assembler programs available for home machines is poor. Even the simplest of these packages will use up considerable amounts of memory, and therefore limit the size of the programs that can be written with it. Many home machines are also extremely unpleasant to work with for long periods of time: poor keyboards, poor displays and, in some cases, a lack of disk drives, can make using such equipment a tortuous task.

For these reasons most professional companies don’t use the micro that the program is intended for (called the ‘target machine’), but use business computers with special software (known as

‘development systems’) instead. Programmers

using these machines often write in languages such as PASCAL and c. They use versions of these

_..

_

THE HOME COMPUTER ADVANCED COURSE 381

KEVIN JONES

Intelligent Software Specialising in strategy games such as chess, IS uses IBMs and Apples, with its own specially-developed interfaces, to develop software. Dividing programs into their machine- dependent and universal segments makes it easier for IS to support a range of computers and dedicated chess-playing machines

Visions

Programmers working from home on the target machines provide the bulk of Visions’ programming effort. After the game concept and scenarios have been decided, the component routines are developed in native Assembly language (Z80 or 6502) using assemblers such as HiSoft DevPak on the Spectrum

BOB BROMIDE

languages known as cross-compilers or cross- assemblers, which permit the work to be done ona micro that uses an 8086 processor, for example, while the programs that are produced will work on machines with Z80 processors. These cross- compilers are high-level languages (like Basic), which makes them easy for the programmer to use, but the programs they create are written in machine code. Skilled machine code programmers scrutinise the programs that are

developed, and often succeed in_ further optimising them. Clearly, a development system has an

enormous advantage over the home micro. A disk-based assembler, or one making use of expanded RAM space to store larger tables, will work more efficiently than an assembler that has to be wound in off tape and operates in the confines of a home micro. Debugging routines can

be added into the development version of the

code, with no worries about the code being too big for memory. It is also far better to work on a business computer that has a good keyboard, sharp display and disk drives.

A firm that makes use of this technique of program development is Intelligent Software (IS), founded in 1981 out of a pooling of experience between David Levy, the chess specialist, and Robert Madge’s ANT Microware. The company specialises in strategy games, mostly written on contract for all the popular home micros. They also develop the software side of dedicated chess machines. Although there are no rapid combat displays in games like chess and bridge, a great deal of computation goes on behind the scenes. So, like arcade games, strategy games also need the speed of assembler-written software.

As well as using the target machines themselves for development, IS uses IBM PCs and Apples with specially developed interfaces to allow code to be exchanged across its range of machines. The company is often involved in conversion projects transferring a chess game, say, from one computer to another so its programmers have

REE ee

382 THE HOME COMPUTER ADVANCED COURSE

2

learned to write code in a form that is easily segmented. One level of segmentation that proves useful when the time comes to hand code from one processor to another is the division of the program into playing code and input/output code. The I/ O code on the new machine will have different port or memory addresses, and will perhaps be strategically different too (polling replaced by interrupts, and so forth). Ingenuity may well be required to get round the hardware limitations, but there won’t be a forbidding quantity of input/ output. Playing code, on the other hand, will be there in abundance, but because it is isolated from the hardware (except, of course, the processor) its conversion will be straightforward.

IS wants to avoid restricting programmers’ inventiveness, so there are very few ‘house rules’ to govern the writing of code. One important point that they insist on, though, is that source code includes numerous comments, so it is always clear what the routines are doing.

Where programmers are working at home for a software house, each developing his or her own project, there is little pooling of resources. In this case, individuality is preserved at the cost of a great deal of duplicated effort, because the code for similar routines has to be reinvented by each separate programmer. |

One software company, Psion, is making use of computers even larger than the IBM PC. Among British software houses writing for the home computer games market, Psion is unique in doing the bulk of its development on minicomputers. The company’s hardware installation alone is worth a quarter of a million pounds.

Psion began as a company by developing

software for the 7X81 and used ZX81s to doit.

TONY SLEEP

When it went on to create the Horizons tape issued with every Spectrum, Psion bought a TRS-80 with disks, a machine that uses the same Z80 processor, and built a special interface between the two machines. But by August 1982, the company decided that it couldn’t go on knocking up a completely different development system every time a new home computer went on the market. So it ploughed back profits into buying heavy- weight hardware with plenty of spare processing power. In principle, this hardware should be flexible enough to cope with whatever computers the future might bring. The machines chosen were a pair of Vax 750s, running the DEC operating system VMS.

The Vax 750s brought two advantages to Psion: the quality of the software provided by DEC, with the opportunity it provides to create specially designed software aids, and the sheer ‘muscle- power’ of the operating system and hardware combination. There is plenty of room for a collection of software aids like compilers, libraries of common subroutines, and debugging programs, all shared between the 16 to 20 programmers who may be logged on to a single machine at the same time. The two machines allow software to be easily transferred from one to the other when needed.

Libraries of common subroutines had already been part of Psion’s philosophy in the TRS-80 days, but on a dual floppy system swapping the data between disks became tedious. The new Vax machines allow teams of writers to work together, sharing common project libraries from which modules can be called up almost instantly, and libraries can even be shared between teams working on different projects. This is the big advantage of a timesharing system and as an added bonus it will also take care of their administrative work without having to interrupt the programmers. Psion plans to add a third Vax to shoulder the administration tasks, leaving two machines free for software production.

Even if you could afford it, you would be wrong to think that going out and buying a Vax would instantly put you on a par with Psion. Very little of this well-developed work environment has been handed to Psion on a plate by DEC. It has taken a lot of hard slog, both to get simple tasks performed efficiently and reliably, and in the large number of hand-wrought software aids and utilities (written in c) that Psion has added.

Psion uses c, an ‘intermediate-level’ language

that can produce reasonably compact and fast

object code for 16-bit chips like the 8086, although this is far from the case for eight-bit c compilers. So in writing for target machines like the Spectrum it has been necessary for Psion to develop its own special techniques. Psion is not keen to disclose its secrets, but it is known the company used c to write its own compiler, which in default of a name gets called ‘our table language’. This looks a little like c, is portable between different processors, and creates

extremely efficient code.

There is a universal rule that system maintenance and writing in-house programming aids like the table language generally takes 30 per cent of the entire programming effort, but Psion finds the extra time well worth while. Having the source code developed in-house means total ownership: you can take it to pieces and improve or adapt it in a way completely impossible with commercially acquired software. If a bug turns up in bought-in software it is difficult or impossible to get it fixed, and there is usually no question of making internal changes.

The special software bought by Psion includes programs that are exact simulations of popular microprocessors, such as the Z80 and 6502. Thus,

the giant Vax computers can be made to behave

just as if they were Commodore 64s or Spectrums. Despite the power of the Vax computers, the simulators run at a fraction of the speed of the target machine. The advantage is that they allow the programmer to look at the contents of every register inside the microprocessor at any stage of the program. This is particularly useful for tracking down bugs in programs. Normally, when a machine code program goes wrong and crashes, the programmer can’t tell what went wrong. Psion can thus save many hours of debugging.

Much of Psion’s recent development effort has gone into producing the suite of four standard business programs that are provided with the Sinclair QL. The Motorola 68000 family of chips, one of which powers the OL, was designed around high-level languages, and c programs compile down so efficiently on these chips that writing in assembler becomes unnecessary. If all home computers followed the QL lead, c could replace assembler completely, and Psion and the smaller software houses could leave the Dickensian work of hand-coded translation behind forever.

THE HOME COMPUTER ADVANCED COURSE 383

Psion |

In 1982 this company bought a pair of Vax 750 minicomputers as the basis of their software development system. Each machine allows up to 20 programmers at a time to use the range of cross-compilers, software lioraries and debuggers for creating and translating programs

TONY SLEEP

ne

Wrestling With MUD

Mainframe adventures allow the involvement of many players in Multi-User Dungeon, up to 43 Novices, Warriors, Enchantresses, and so on, compete or co-operate to gather treasure and become omnipotent Wizards or Witches. Mainframe adventures also support large detailed scenarios: MUD locations include The Land, various caverns, a forest, a dragon island, The Sea and The Swamp, all of which may ~ contain treasure, goblins and zombies. Six telephone lines permit connection to home micro players

APPLICATION / MULTI-USER DUNGEON

a

FUN IN A DUNGEON

Adventure games usually pit the player against the imagination of the writer, who determines certain actions that must be performed to complete the game. With MUD, the Multi-User Dungeon, many players, at their home computer terminals, can log into a mainframe machine to play an adventure game against each other.

MUD is a real-time adventure where you meet other players, have conversations with them, ask their advice, join- with them against a common enemy or fight them. They are not part of the program, they are playing the game at the same time as you, and so their actions affect yours. MUD runs on a giant DEC10 computer at Essex University, and all you need to play it on your Own microcomputer is a terminal emulator program, a telephone, a modem, and a Packet Switching System (PSS) account. A terminal

SORIA RE SAA MaMa EAD AANA

384 THE HOME COMPUTER ADVANCED COURSE

emulator program allows your micro to communicate with the mainframe via a telephone link. You may choose to write your own emulator or to buy one. It should ideally allow the screen to scroll, and give an 80-character line length. Micronet software is not suitable since it does not permit this. It is possitile to use micros with less than 80-column displays, but this is awkward. There are some excellent packages available; for example, Termi and Communicator are ROM chips for the BBC Micro.

The modem needs to be able to communicate with British Telecom’s PSS, and can be 300/300, 1200/75, or 1200/1200 baud. A Micronet acoustic coupler is quite satisfactory. PSS is a networking service that enables you to contact distant host computers, often for the cost of a local phone call. There is also a charge for data sent over the PSS. For details contact British Telecom.

The procedure for gaining access to the mainframe is straightforward. With the terminal

software running, you dial the PSS exchange at which you are registered,.connect your modem and key in your identity. Then you enter the PSS address of Essex University’s DEC10. A special account has been set up at Essex to permit free access to MUD from midnight to 7am on weekdays, and 10pm to 7am at weekends, when the mainframe is under less pressure. Log in to this special account, and then enter RUN MUD.

The program is continually updated, so the first thing you will see is the date of the latest version. You choose a character name to play under, known as your ‘Persona’, and you tell MUD what this is. If you are playing the game for the first time then a new persona will be created for you, and you will be classified as a Novice. Levels of experience are:

If you end your session without being killed the points that you have accrued will be noted by the program, and you can continue next time from that score. You get points and increase your level of experience by dropping items of treasure in the swamp, by overcoming the odd problem, by destroying various nasties like rats and zombies, and by winning a fight against another player. If you get killed in a fight with another player your persona is removed from the game, and you must begin again as a Novice, with no points. Therefore, it is always wise to consider alternatives to combat, especially as your opponent may have a stronger weapon or more stamina than you.

You start the game on a ‘Narrow road between lands’. Typing ‘WHO’ will provide a list on the screen of all the others who are playing at that time. You may choose to say hello to one of them. For example, typing ‘Jez, hi there I’m new and could use some advice’ would convey that message to the terminal of the player called Jez. You could talk to all the players at the same time by typing ‘Shout, OK you terminal junkies, watch out cos here I come’, but it is not advisable to start your first game in this way.

Typing ‘HELP’ will give you some information about how to move and will give a brief explanation of many of the commands. Movement choices are explained in this way: ‘Most simple movement commands are allowed, e.g. n, SW, west, up, jump, plus others youll have to find out!”

The commands available may be listed by typing ‘COMMANDS’. There is quite a lot of information available, and scribbling a copy on

paper while the words scroll down the screen is not a realistic option. Some terminal software will allow you to copy everything that appears on your screen onto disk for you to look at later. This will

also enable you to construct a proper map of the ©

land, which can be amended after each game. These are the commands that were available on one day:

COMMANDS (abbreviation in upper case)

AutoWho,<seconds> Back BERSERK . BRIEF BUG BYE CONVERSE DRop <item» DRop ALL EMPTY <bag> EXITS Flee<direction> FOLLOW «name> Get <item> Get ALL Glve <item» TO <name> go <direction> Help HELP <name> HINTS, HouRS HUG<«name> INFO Inventory KEEP <item> —_ Kill «name> KISS <name> LEVEL LOG) ‘level>, <message Look around _ Look <bag> Look «direction LOSE <name> MEDITATE NoPassWord PassWord = PERSONA ProNouns QuickWho Quit “<message> REFUSE «name>

RETaliate <item> SAVE SCore SHout,<message> “SLEEP SP ELE STeal <item> From «name>

tell <name> ,«message> UNKEEP VERBOSE WEIGH <item» WHEN WHO WRITE <object>, «message

MUD isalarge text-based adventure, with lengthy and detailed descriptions of the locations. When

you are familiar with the scenario you can type ‘BRIEF’ and not have to read the descriptions each time. Prestel subscribers will be aware of the slowness and inadequacy of teletext graphics, and whilst graphic-based adventures are an interesting novelty, dedicated adventure games players will always choose a text-based game. A text-only adventure allows a_ greater imaginative involvement than a graphic one, in the same way that a radio play can be more enjoyable than one on the television. Another disadvantage of a graphic adventure is that each make of home micro will need a different version of the game, because of the different graphic capabilities of home computers. MUD players are likely to be using a BBC micro, an Apple or a Spectrum, but others will have second-hand terminals from junk shops, and therefore the range of machines using the program is extensive.

MUD is expected to be marketed soon. The

program’s original authors, Richard Bartle and |

Roy Trubshaw, are writing a version to run on a VAX Computer, which will be marketed by Century Communications. (A VAX plus software

and disk drives costs around £50,000.) The game

will still be played via telephone links, like PSS and Prestel, although with enough demand it could well be available on cable, as well. MUD players will then pay a fee to join the game, perhaps £10 or £15 per quarter, plus a small charge for ao hour they play.

THE HOME COMPUTER ADVANCED COURSE 385

Dungeon Master For further details about the ~ Multi-User Dungeon contact:

Richard Bartle

Department of Computer Science 2

University of Essex

Colchester

Essex

describe how some process may be per- formed. A knitting pattern is an algorithm; so is a recipe; and so is a computer program. We discuss how an understanding of the principles of algorithms can improve

of other processes that have already been defined, or in terms of processes that are so basic that they do not need to be defined. Thus, in a recipe, one instruction may be ‘prepare a bechamel sauce’, where a bechamel sauce recipe (algorithm) has been given elsewhere in the cookbook. Another instruction may be ‘bring the mixture to the boul’, where the operation of bringing something to the boil is assumed to be fully understood by the user. In programming terms, algorithms are constructed from instructions that either use algorithms (procedures, routines, functions) written elsewhere in the program, or ones built into the language (commands such as PRINT and DIM, or maths functions like LOG and TAN).

This. article looks at how algorithms are constructed from other algorithms and primitive processes. The primitives at the disposal of a programmer are the commands and functions in the language. From these, algorithms are written that can do small things (move a sprite, say, or accept a number as an input). These algorithms

are then used to build more general algorithms

(updating the game display, or controlling a menu system), and these algorithms are in turn used as parts of larger ones again until the whole program, viewed as a single algorithm, is written in terms of lower-level algorithms. This concept is the basis of what is known as Structured or modular programming and is a subject we will return to later in the course.

DESIGNING ALGORITHMS

An algorithm has an input and an output. This is just to say that, as a process, the algorithm will work on some initial data to produce a result. ‘This initial data is passed to the algorithm from outside in the guise of ‘parameters’, which remain constant for any particular use of the algorithm but may change between different uses. Passing parameters will be familiar to even a novice programmer since the simple program:

10 PRINT “Hello World!”

passes the parameter “Hello World!’ to the algorithm called by the PRINT command. Similar

386 THE HOME COMPUTER ADVANCED COURSE

examples are FNA(P), TAN(P), LEFTS(PS,5) and POKE P,5, where P, PS and 5 are all parameters. In the same way, an algorithm’s results are passed back as parameters. If the programming language being used has local variables (e.g. PASCAL and Cc) then the parameters would normally be passed with a procedure cali, as in:

procedure(parameter1, parameter2, etc.);

It is an essential first step in designing an algorithm to consider the contents of the input and output parameters, their types (integer, floating point, real, string, etc.) and their magnitudes and ranges.

When the input and output of the algorithm have been defined, the next step is to form ideas as to how one can be transformed into the other. Unfortunately, there is no ‘cookbook’ method for creating these transformations as they require creativity and ingenuity. However, there are several ways of helping the process along.

The most obvious and most often overlooked is to borrow the algorithm from somewhere else. At the simplest level, the in-built functions of a programming language provide many useful algorithms, such as string-handling, trigonometric functions, input/output, and (possibly) sorting and matrix manipulation. Apart from this, the algorithm needed may already exist in another of your programs. The code for this could be incorporated in the new program (creating your own library of algorithms is extremely useful). In addition, there are published collections of algorithms that are often available from public libraries. The Art of Computer Programming, Vol I: Fundamental Algorithms by D. E. Knuth, although heavy going, is highly recommended.

Programs published in the computer magazines are well worth scrutinising for routines that may be of use. Finally, there are algorithms that are used in other pertinent domains, and although they were never meant for computing they are extremely useful. The accountancy section of the local library will be full of books containing formulae for calculating balances and depreciation. A little research among these could make writing an accounts program a lot easier and the result is likely to be a lot more reliable. The same is true for other disciplines:

engineering, electronics, maths, etc.

Whether adapting an existing algorithm, or creating one from scratch, there are certain criteria that must be applied to each instruction it contains. These are definiteness and effectiveness. Definiteness means that the instruction should

not be ambiguous in any way. Ambiguity is easy to introduce at an early stage when the algorithm is being written down in English. Words like ‘and’ and ‘or’ in English are very different from the AND and OR of Boolean logic. For example, if the algorithm was meant to select all the names in a list that begin with an ‘A’ andall those beginning with ‘B’, you could easily write code like:

IF FIRSTLETTER=“A” AND FIRSTLETTER=“B” THEN

which is wrong because a logical OR is needed!

_ The criterion of effectiveness is a demand that the program should not contain impossible instructions. An instruction is said to be effective if it can be done with a pencil and paper in a finite time. This means that instructions like ‘let X equal

the highest prime number’ are not effective (there

isn’t a highest prime number). |

GENERAL CONSIDERATIONS

There are also criteria to judge the algorithm as a whole. An algorithm must terminate. The algorithm that follows does not terminate (even though its instructions are definite and effective) and if this was coded into a program it would endlessly loop:

Step 1 let | equal 1 Step 2 if! > 3 then exit Step 3 goto step 1

Telling whether an algorithm will terminate is not always easy, but, in general, algorithms that involve loops test for a particular condition before they terminate (e.g. if | > 3 in our example), and it is necessary to check that it is

possible to meet that condition.

_ Efficiency, generality and elegance are ways of judging between different algorithms. Efficiency is usually judged in terms of time and memory use. The two are usually quite compatible fast code may need relatively little space, but bear in mind that this need not be so. Having found an algorithm, it can be ‘tuned’ for efficiency by changing its details. A calculation will be noticeably faster and will use less memory if, for example, integer rather than floating point arithmetic is used. Alternatively, a completely different algorithm for doing the same thing could be found.

Generality is the ability of an algorithm to cope with many different situations apart from the one for which it was designed. It is worth while, in the long run, to attempt to make all algorithms as general as possible. If a program called for a yes/ no response several times, it would be worth writing a routine that prompts the user with ‘please type y or n’, accepts the input, checks whether it is ‘y’ or ‘n’, reprompts if it is neither and otherwise returns the appropriate response. However, the routine could be made more general if it could be fed with different prompts and potential replies, so it could be used in many different situations. Elegance means finding algorithms that are both simple and ingenious. In all cases it is more sensible to find efficient, general algorithms rather than elegant ones.

Another important aspect of algorithms is the flow of control and of data within them and how this can be represented with flow charts. This is the subject of the next instalment in this series.

es

THE HOME COMPUTER ADVANCED COURSE

Pyramids And Primitives

The block-structure diagram on

the left clearly shows the nesting of a program’s

algorithms, while the procedure

flow diagram on the right

emphasises the articulations and process levels of the same program. The most ‘primitive’ algorithms are thie most deeply nested, and the lowest in the

hierarchy

KEVIN JONES

Searching For The Solution The essence of a database management system is the ability to select records on multiple search criteria. The Rubik Cube represents the database, and its facets are the records

DAISY WHEEL

Until recently, microcomputer owners requiring letter-quality printing were restricted to one variety of printer the daisy wheel. The name derives from the printing mechanism: individual letters are mounted on plastic spokes or ‘petals’ arranged in the shape of a wheel about three inches (7.5 cm) in diameter. The wheel spins until the desired character is at the top, and then a hammer strikes the ‘petal’ against the ribbon, making an impression of the character on the paper. Electronic typewriters also use this technique. In some models the letters are mounted in a ‘thimble’ shape.

Daisy wheel printers are considerably slower than their dot matrix counterparts; a £400 model can print only 10 to 15 characters per second (cps), as opposed to typical dot matrix speeds of 100-160 cps. The fastest daisy wheel models can print at 60 cps, but these are priced at around £2,000. The main restriction on speed is the fact that the printer motor must constantly accelerate and decelerate while turning the wheel. Close examination of a daisy wheel may give the impression that letters are arranged at random, but the layout is designed to reduce the average amount that the wheel must turn when printing standard English text.

DATABASE

A database is a _ general-purpose software package that is designed for the easy storage and retrieval of data. All the information about one person (in a mailing list) or object (in cataloguing

or stock control applications) is contained in a

record, which corresponds to a card in a card index file. Each record consists of fields of information, each with its own field name. For example, the field named ‘Price’ in a stock control program may contain the data ‘£34.25’ in one particular record. A collection of records sharing the same layout and field names is called a file.

AVAILABLE TENNIS PLAYER pL CRICKET PLAYER <F READER

cs) FOOTBALLER Bro ARTIST al DARTS PLAYER - WINE LOVER

aes CAR OWNER

scoot PUBLIC TRANSPORT AB) CYCLIST

Simple databases restrict the user to work on a single file at a time, but multi-file packages allow data to be transferred between different types of file. In an invoicing application, for instance, information from a customer file that contains the

388 THE HOME COMPUTER ADVANCED COURSE

customer’s address and credit limit may be merged with data from a product file that gives details of prices, product codes and descriptions.

The most sophisticated microcomputer databases -

are programmable: the package can ‘learn’ sequences of commands that are used frequently and will execute them at a single keystroke. Such packages are also referred to as appHCAHOe generators.

DATA COMPRESSION

The rule of thumb method for evaluating data storage requirements is to allow for one eight-bit

‘byte per character, as well as making some

allowance for operating overheads such as file header information and control characters (see page 348). Data compression involves trying to improve on this rate for two purposes: increasing the effective capacity of a disk drive, and reducing the time needed to transmit data over a distance.

At first this may seem very difficult to achieve, especially as all characters and some commands are ASCII coded. Consider, however, messages that use just upper case text and a maximum of six other punctuation symbols just five bits would then be needed to represent the 32 (2°) possibilities. Characters will no longer correspond one-to-one with the byte locations, and a special program must be employed to compress the data before recording on disk, and then decompress it again for use by an application program. Such utilities (also called compactors) can be purchased to work on standard CP/M files. An additional benefit is some measure of security compressed files can’t easily be read on another system.

Compression rates oreater than eight-to-five rely on frequency analysis some sequences of characters occur more frequently than others. In normal text, a standard list of the 100 most common words (and, the, etc.) will account for half the text. If these words are replaced by a single byte, with a flag-bit to differentiate them from normal characters, the saving will be considerable. This is called tokenising.

DATA CORRUPTION

Data corruption is most likely to happen when writing onto a magnetic surface (because of imperfections in the media), or when transmitting data over a distance (because of extraneous noise). It can happen to data residing in memory, if an individual RAM chip should overheat and behave unreliably, or there is strong electrical interference from nearby.

Magnetic media should always be handled carefully, but the only way to guard against corruption generally is to employ the principle of redundancy the opposite of data compression. This means taking more space or time to represent a single piece of data than is strictly necessary. Parity and Hamming codes are the commonest means of safeguarding against data corruption.

“3

COLECO ADAM/HARDWARE

THE SMART SET

Coleco is an American company that made its name as a manufacturer of television games consoles. Recently, however, _ it moved into the home computer market with the Adam, a machine that boasts 80 Kbytes of RAM, a built-in word processor, a tape

data storage system, and a daisy wheel printer. All for £625.

The Adam system is based around the ColecoVision television games console, and owners of this unit may upgrade it to full Adam specification with add-on units. In fact, all Adams on sale at the present time are based on the ColecoVision module, although a more compact, stand-alone Adam is planned.

When first unpacking the boxes containing the Adam system, the sheer number of components is a little unsettling. The ColecoVision module clips into a large plastic tray, and the ‘memory module’ (which also contains the Z80A microprocessor and the tape drive) connects to the games unit via an expansion port. The module is held in place by

retaining clips on the tray. The keyboard is

connected by a length of coiled cable, and one of the two games controllers supplied may be slotted onto the side of the keyboard to act as a numeric key pad. The printer is connected to the memory module, and the power is supplied to the whole

system via a mains lead to the printer.

The keyboard has 75 keys, including six function keys, a set of word processor control keys, a cursor cluster, and the usual alphanumerics. It is well designed and light, so it is easy to use in a lap-held position.

When the system is first switched on, the Adam is in ‘electronic typewriter’ mode. Pressing a key

displays the character on the screen and at the.

same time it is printed out. The screen is a representation of a sheet of paper and typewriter platen. The usefulness of the Adam in this mode is

limited, but the press of a key switches the system

to “SmartWriter’ mode.

SmartWriter is a simple but effective word processor that is obviously designed with the beginner in mind. The ‘typewriter platen’ display is retained, and the bottom line of the screen displays the commands allocated to the function keys. Sensible use of these keys, together with the various word processor control keys on the keyboard, makes SmartWriter operation extremely easy in fact the manual is largely superfluous as the menu options lead the user through all the steps necessary to store, display and print text. The screen format is 36 columns by 20 lines, but longer lines are dealt with by using the screen as a ‘window’ on the whole text.

The tape drive is similar in principle to Sinclair’s Microdrive, but has a larger capacity (a claimed

CHRIS STEVENS

The Adams Family

The Adam is an all or nothing machine. It is sold as a complete system: micro, high-speed tape drive, daisy wheel printer, keyboard, two joysticks and three pieces of software (two excellent games and a word processor.) This makes the Adam quite a powerful home computer, yet it is essentially an upgrade of a TV games unit

THE HOME COMPUTER ADVANCED COURSE 389

HARDWARE/COLECO ADAM

256 Kbytes per tape). It is much faster than ordinary cassette tape. It is also under full computer control, so the tape can be rewound by the computer to find a particular file. Tapes (or ‘data packs’ in Coleco-speak) are supplied ready- formatted, so ordinary audio cassettes may not be used. New tapes cost up to £5. When the Adam is switched on, the program on any tape present in the drive is loaded this may be a game pack, the SmartBAsIC cassette or a program of the user’s own. If the drive is empty, the system defaults to ‘electronic typewriter’ mode.

The daisy wheel printer uses either fanfold or single-sheet paper, and gives a print quality that is comparable to an electric typewriter, but it is extremely slow and noisy.

Despite the 80 Kbytes of RAM, the cassette- based Smartpasic leaves only 28 Kbytes for the user. Smartsasic itself is similar to Apple’s version

of BASIC, and so is easy to use, with good graphics -

and a choice of 16 colours. The BAsic manual, however, is truly abysmal, written in a condescending tone and full of twee expressions, such as ‘boo-boo’ for ‘error’. But the similarities between Smartpasic and Apple Basic means that users have a large number of books and other material to refer to.

At first sight the Adam system appears to offer excellent value for money. The built-in software is ideal for writing letters, reports or short articles, and the tape system is simplicity itself. An added bonus is the large amount of available high-quality games software not only may ColecoVision cartridges be used on the Adam, but the purchase of an adaptor will make a huge range of games from Activision and Atari available. More serious software is being sold on tape, although the number of packages is rather limited. They

390 THE HOME COMPUTER ADVANCED COURSE

Joystick Handle Although the arm of the joystick handle is much shorter than most joysticks, it still gives re

Detached Keyboard Only two home micros are sold with detached keyboards even though these are considered essential for business computers. The Adam keyboard includes function keys and keys dedicated to the word processing software that comes with the micro

Joystick Storage Two joysticks can be stored here when they are not being used. The joysticks plug into sockets at the side of this area

ColecoVision Video Games System

This unit is sold by itself as a dedicated games computer, but can be expanded into a home computer by adding the other units

Equipment Tray This fits onto the bottom of the two units to hold them firmly together

Printer Connector The printer included with the Adam plugs into this socket. Power is supplied to the Adam through this, so the printer must always be connected, even if it is not being used

Digital Tape Drive This may look like an ordinary cassette player, but itis a high-speed tape unit under full computer control

CHRIS STEVENS

Joystick Fire Buttons

commas Joystick Number Pad

The pair of joysticks that come with the Adam are unusual in having number pads built-in IMENSIONS or ; Adam’s Joysticks Tere mh keyboard Two joysticks are supplied as standard with the Adam. One of and provides a space to rest a these doubles as a numeric keypad and slots into a special joystick holder alongside the keyboard. Coleco also markets two ‘deluxe games control systems, at £50 each. The Super Action Controller set comprises a pair of easy-action joysticks with numeric pads and rifle-style triggers replacing the normal Fire buttons. These are fitted with standard Atari-type D-connectors, Reset Button and so may be used with other systems. A free Baseball games cartridge is included.

The Roller Controller is an arcade-style games control panel. This has two standard Coleco joysticks and a ‘trackball’ controller for fast response and accurate control. Two sets of dual fire buttons allow two-player action, and a mode switch selects either joystick or trackball operation. Supplied with this unit is Slither, a Centipede-style arcade game.

~on Games Cartridge

This plugs into a slot in the games unit. Several dozen good, if expensive, cartridges are available for the machine

LANGUAGES AVAILABLE

«= Expansion Socket This fits into the back of the expansion module

include a spreadsheet, database, revision aid, and a version of the Loco language. The addition of the promised 144 Kbytes memory expansion should give CP/M capability of a kind, and even disks are planned.

But there are drawbacks. The print quality - not as good as one might expect from a daisy wheel,

Keyboard Cable Socket the printer is woefully slow and noisy, there is a

A cable (not shown) plugs in severe lack of user RAM, and the fact that BAsiIc here to link the keyboard to must be loaded from tape soon proves annoying. the main unit With the recent drop in daisy wheel printer prices,

it should be possible to put together a system that out-performs the Adam but costs approximately the same. That said, the Adam would appear to be

Space For Second Tape Drive These are not yet available

Digital Data Pack well worth buying if the user already possesses the | BiVaiW\lascas Not to be confused with a : ColecoVision console. For those who wish to ferret purchase a home computer system with word

formatted tapes which cost processing capabilities, the Adam is certainly

nearly £5 each, and store 256 worth considering but there may well be other,

Kbytes per tape better alternatives.

THE HOME COMPUTER ADVANCED COURSE 391

Routine Procedure

Unlike a flow chart, this structure diagram shows the procedural structure of the program rather than the flow of control through it. A capsule indicates the start of a REPEAT... UNTIL loop; the lozenges are decision boxes when the test fails, the enclosing loop continues. The Level numbers show the program’s block structure: all loop starts and procedure calls open a new block of program and a lower logical level compare this with the diagram on page 387.

In this short series of articles we shall be looking at the construction of a graphics game using BBC Basic. The game is designed to run on the Model A, Model B and the Electron.As each phase of the game is developed, the appropriate section of the program will be listed, allowing you to build up the game with each instalment.

BBC Basic has two major advantages for the programmer over ‘standard’ Microsoft Basic: it is

fast in execution and has features that allow you to

structure programs. The essence of developing a structured program is to develop small, independent sections of code that can be individually debugged before assembly into a larger program. Any BASIC program can be structured to a certain extent by the use of subroutines to code each module of the program, but BBC Basic has special types of subroutines, known as procedures. These can be thought of as blocks of code that are designed to doa specific job within a program. For example, let us imagine a piece of program that has to pause between each

392 THE HOME COMPUTER ADVANCED COURSE

TREAD LIGHTLY

instruction for a given time. In standard sasic this may be written using a dummy loop; that is, a loop that does nothing except take time to execute:

10 PRINT “FIRST SESTION” 20 FOR l=1T0100: NEXT |

30 PRINT “SECOND SECTION” 40 FOR l=1T0100: NEXT |

90 PRINT “THIRD SECTION” 60 FOR l=1T0100: NEXT | 70 PRINT “FOURTH SECTION” 80 END

A better approach, however, would be to place the delay loop in a subroutine:

10 PRINT “FIRST SECTION” 20 GOSUB100 30 PRINT “SECOND SECTION” 40 GOSUB100 00 PRINT “THIRD SECTION” 60 GOSUB100 70 PRINT “FOURTH SECTION” 80 END 100 REM ** SUBROUTINE ** 110 FOR |=1T0100:NEXT | 120 RETURN

JANET BARRANCE

re

Replacing the subroutine with a procedure in BBC BASIC gives the following code:

10 PRINT “FIRST SECTION” 20 PROCdelay 30 PRINT “SECOND SECTION” 40 PROCdelay | 50 PRINT “THIRD SECTION” 60 PROCdelay 70 PRINT “FOURTH SECTION” 80 END 100 REM ** DEFINE PROCEDURE ** 110 DEF PROCdelay 120 FOR l=1T0100: NEXT | 130 ENDPROC

There are a number of similarities between the subroutine construction and the procedure construction; for instance, both come after the END statment but can be called repeatedly from within the main program. The principal advantage of the procedure is that it is called by name rather than by line number. The DEFinition of the PROCedure could start anywhere after the END statement.

If we wanted our example program to be able to wait for different lengths of time before each section, then a more important advantage of procedures can be utilised: the ability to pass values into a procedure definition. Let us say that

we wished the pause between the first and second

sections to be 100 loops, the pause between the second and third sections to be 200 loops and the pause between the third and fourth sections to be 175 loops. In standard Basic the value of | would need to be assigned each time before calling the subroutine. Using procedures, the value can be passed by means of a bracket at the end of the calling statement: 10 PRINT “FIRST SECTION” 20 PROCdelay(100) 30 PRINT “SECOND SECTION" 40 PROCdelay(200) 50 PRINT “THIRD SECTION” 60 PROCdelay(175) 70 PRINT “FOURTH SECTION: 80 END 100 REM ** DEFINE PROCEDURE ** 110 DEF PROCdelay(N) 120 FOR I=1TON: NEXT | 130 ENDPROC More than one value can be passed for use within a procedure if the items are separated by commas. Variable names can also be used in this way to pass the value of the variable at the time when the procedure is called. The game we shall be constructing is for one player and uses the keyboard cursor control keys to move a mine detector around a minefield.

Points are scored for each mine successfully dealt

with. There are, however, several things to slow down your progress around the minefield. The chief consideration is your assistant who mirrors your every move. As you go round dealing with the mines you must make sure that he doesn’t tread

on one. You are also being sniped at and there is a

two minute time limit to the game. In the final version, you will have four willing assistants per game and a choice of skill factors from 0, the easiest, to 9, the most difficult.

Because BBC Basic uses procedures, flow charts arent of much use. Instead, a structure diagram can be used to illustrate what procedures are required and how they fit together to make the final program. REPEAT. . . UNTIL loops are shown as ‘sausage’ shapes in our diagram. Decision boxes are like the more usual diamond-shaped box but with the top and bottom cut off to save space. It should be stressed that this diagram was not drawn out in its entirety before programming started, but evolved out of a series of refinements.

SET-UP PROCEDURES

Brfore we can start defining routines to place objects on the screen, we must decide on the

screen display mode we are going to use. There are

three main factors to take into account: resolution, colour and memory. In general terms, the more information the screen has to hold, the more memory it will require. So, higher resolutions and more colours mean more memory. If your program is short this may not be important to you, but the program we are designing is fairly lengthy. We do require a few different colours to distinguish the mines and the detector/assistant and to make the game visually appealing. On the Model B we are offered two medium-resolution modes. Mode 2 gives us 16 colours to play with, wkereas mode 5 offers only four. By looking at how the BBC interprets bit patterns in each mode we can see why mode 5 uses substantially less memory than mode 2.

Unlike some micros, the BBC holds colour and pixel on/off information within one byte for each small area of the screen. In mode 2, four bits are required to represent the 16 different possible colours. Thus, one byte can hold information about the colour of two pixels only. The bits within the byte are arranged as follows:

| | een

As mode 5 restricts itself to four colours, only two bits are needed to hold the colour information. Thus, one byte can represent four pixels as shown:

yaa

Both modes have 160 by 256 pixel resolution, hence the number of bytes required for mode 2 screen memory is (160X256)/2=20 Kbytes,

Picture Points

The user-defined characters representing the mine, the detector and the assistant are described. The pixel : information is divided into

eight bytes, with each byte being the binary ‘picture’ of

one row of the shape

THE HOME COMPUTER ADVANCED COURSE 393

Danger Area

The minefield occupies 20 rows of 16 characters, and the mines are randomly ‘sown’ during the set-up procedure

JANET BARRANCE

whereas mode 5 needs (160X256)/4=10 Kbytes of memory. By choosing mode 5 we allow ourselves an extra 10 Kbytes of memory for our program. An added bonus is that mode 2 is not available on model A machines, but mode 5 is!

The construction of user-defined characters is simple on the BBC. Each character is made up of eight numbers representing the decimal equivalents of each row. The character designs for the mines, detector, and assistant are given.

The command VDU23 allows the programmer to define characters with ASCII codes from 226 to 255. The second number in the VDU command denotes which code you wish to assign to the shape defined by the last eight numbers.

VDU23,224,0,0,56,254 254 124,0,0

defines CHRS(224) as the mine shape. To print this character we simply issue the instruction PRINT CHRS(224). The following procedure defines the ie characters to be used in the game.

we) Er a es a characters

OREM be PINS 4

>t EP VDL oa eae he OO, Ho, 254, 254, 124,0,0

2410 REM ## oh NE DE es : TOR #4 Oa OIE Teale cok DOS, 1B SO ery LE, ES Gy wad 2430 REM * * ASSIST i ip 14% 2440 YOU ee Ms, Eds, Sn bk Gy be BG gl Oe 4G Oe 2400> ENDPROG SCREEN LAY-OUT

Once the shapes have been defined we can print them onto the screen. This is most easily done using the PRINT TAB(X,Y) command. In mode 5 there are 32 rows, each with 20 characters. This means that X ranges from 0 to 19 and Y ranges from 0 to 31. The minefield is to occupy the area shown in the diagram.

To lay the mines randomly within the given area we can make use of the RND(N) command. If Nisa

whole number, then RND(N) returns a whole

number between 1 and N. The horizontal co- ordinate of each mine must be chosen to lie

MINEFIELD AREA

394 THE HOME COMPUTER ADVANCED COURSE

annem meme demenemeeaecmmeamemmenemumemamntueateeeemmn immer meade deemed meee et rere eee

between 2 and 17. RND(16) gives numbers from 1 to 16 so RND(16)+1 will select co-ordinates within the area of the field. This procedure will lay as many mines as ial os e the value base to it:

2360 DEF FROC ay mines (number mines)

eee be i a ANGE COL ‘al ee 2 ere : E ME qed ea [ea VOUS oe

pray POR [a1 TO rmuunkie ma ries gC) PRINTTARB CRND (16) +1, Rh ID ¢ 324 CHR C24)

Aol ME RT +1 2o00 AFRO

In mode 5 we are restricted to four colours and these are normally black, red, yellow and white, corresponding to colour numbers 0, 1, 2 and 3. However, we don’t have to use these colours and can change them using the VDU19 command. The numbers 0 to 3 are known as the logical foreground colours. Each of the 16 colours on the BBC has a number that has nothing to do with the mode used. These are called the actual colour numbers, a table of which appears on page 224 of the user guide. Any of the four logical colours can be assigned one of the sixteen actual colours. For our game we wish the mines to be green (actual colour number 2). We do not want the yellow that is normally given to us as logical colour 2. The VDU19 command does this.

The detector and assistant take up their initial positions in the bottom-left and top-right corners, respectively. As we will probably want to re- position the detector and assistant later, the procedure for positioning them will use variables (xdet,ydet) for the detector’s co-ordinates and (xman,yman) for the assistant’s co-ordinates. 2eou DEF FPROCposI tion chars ~S40 COLOUR 1 2950 PRINTTAR (xdet, yet) SOMERS o 2860 FPRINTTAR Cxman, yma) os CHAS ¢

2a70 COLOUR 2 2380 ENDFROC

he ne

The COLOUR commands at the beginning and end of the procedure select the logical colour that future text will have. COLOUR 1 selects logical colour 1 (red) to print the detector and assistant and COLOUR 2 restores the colour green for future printing. Before this procedure can be used, however, the values of xdet, ydet, xman and yman have to be assigned. This is done in another | procedure, along with initialising some other variables that will be Ue JOT

foe DEF PROC tt < aay ise varlabl es 2S30 xdet=2: ydet=25:xman=1? cy mee 2540 setart=120rnfinis enatiad

es ananan”

oh) 2 ee cbse" 2560 ENDFROC All these procedures can now be tested by a short calling program as follows:

5 MODE 5 10 COLOUR 2 20 PROCinitialise-variables 30 PROCdefine-characters 40 PROClay-mines(40) 50 PROCposition-chars 60 END

In the next instalment we shall look at timing and

controlling movement from the keyboard.

wr amet ae -

ROCKET MAN

Jet Pac marked the debut of the software company Ultimate, Play The Game. Originally written for the Spectrum, Jet Pac set new standards in high-quality graphics on the Sinclair machine and was an instant best-seller. The success of the Spectrum game meant that a version for the Vic-20 followed quickly on its heels.

The ‘blast-the-alien’ type of arcade-style game is iS often denigrated for its simplistic, adolescent approach. Nevertheless, the design of a successful example requires considerable programming skill. Jet Pac is such an example.

As is so often the case, the scenario outlined on the cassette inlay seems more complex than it is. As the chief test pilot for the Acme Interstellar Transport Company, it is your job to travel around the galaxy assembling spaceships on assorted planets, while collecting any precious stones and gold that you can lay your hands on. Rocket assembly is greatly assisted by a Hydrovac Jet Pac, which is capable of lifting almost anything, and allows you to manoeuvre components with ease. You are also conveniently armed with Quad

- Photon Laser Phasers, which are used to blast any

alien being that might be unreasonable enough to complain about you despoiling its planet.

The game’s description may evoke visions of a glorious Technicolor trip through the varied ecologies of different planets, but as usual the truth is more mundane. The planets you visit are virtually identical, so much so that the test pilot/ hero must experience a strong sense of déja vu at each landing. But the aliens make up for this. ee planet is inhabited by a single species only fact there would be little room for any others as all the aliens appear to breed like rabbits. These species vary in form from flying saucers to

bouncing balloons, but they all have one thing in

common one touch from any one of them means instant death.

Scattered around the surface of each planet are three parts of a spaceship; these must be assembled before you can move on to your next port of call. No screwdrivers or monkey wrenches are required on this job you simply drop the components onto the rocket base to see the spaceship form before your very eyes.

It is the aliens that make this game so enjoyable.

There are plenty of them, and at first they give the

impression of moving menacingly and unerringly in your direction. After a while you realise that they are, in fact, following predetermined paths from random starting points. The first wave of

attackers descends slowly, giving you time to blast them with your deadly laser. The second wave is made up of bouncing balls, which ricochet across the screen between the rock ledges and the ground. This mixture of set paths and random movement provides just the right combination, requiring skill and fast reflexes for successful play.

This type of game is often ruined by a poor choice of control keys. Here they have been chosen sensibly. Two keys on the bottom row of the keyboard are used for left and right movement, catering for both left- and right-handed players. Any key on the second row up fires the lasers, which may be left permanently firing. The row above triggers the jets that make you ascend, and the top row allows you to hover. A nice touch is the fact that if no key is pressed you will drift slowly to the planet surface under the force of gravity.

The graphics are excellent. The test pilot is beautifully drawn, as is the Hydrovac Jet Pac, which gives off convincing puffs of smoke when ‘thrust’ or ‘hover’ are activated. The laser streaks the sky with multicoloured lines, and the aliens, when hit, explode in more clouds of smoke.

The game is much the same on either the Spectrum or the Vic-20, although the latter's screen format has the effect of making the test pilot look somewhat overweight. On both machines, Jet Pac is a satisfying and highly addictive game.

4upPp Mx SUF 9@4325 IQSSQs eosrie

BuUP QQ1 4090

THE HOME COMPUTER ADVANCED COURSE 395

LIZ HEANEY

Open Window

~The word “HELLO” is scrolled horizontally and vertically around the screen window, one pixel at a time

The ability to create ‘windows’ on a screen.

display is a particularly useful facility. We take a detailed look at a machine code program to do just this on the Spectrum, and give an accompanying BASIC demonstration program that shows the effect of eh on the screen. |

Out miele eodek program mallee you ‘to mdeane rectangular windows on the Spectrum screen, and to scroll these windows left and right, or up and down. The windows may be of any size and can be placed anywhere on the screen; they do not need to occupy eight by eight pixel character squares.

The machine code program uses tables starting at address $B004 (45060 decimal) to handle window parameters and for temporary data storage. It takes the address of the table for the required window from addresses $B000 and $B001 (45056 and 45057 decimal). The table for each window takes up 11 bytes, so if more than one window is required, the table for the second window will start at SBOOF (45071 decimal), the table for the third window will begin at SBO1A (45082 decimal), and so on.

The BASIC demonstration program uses one window only. The details of this window are POKEd into memory in lines 180-230, and the window initialisation routine is called at line 240. If more than one window is required, each one must be defined in this way before it can be used. ‘To change windows you must POKE the address of the

~ new window table into memory locations WT and

WT+1. Scroll directions are set by POKEing values into memory location WNDWTB + DIR simply POKE 0 to scroll left, 1 to scroll right, 2 for up, or 3 for down. |

The Assembly language program begins by defining a number of constants. PIXADR is a subroutine in the Spectrum ROM that calculates the address of the screen byte, and the bit number within that byte, of a point on the screen that is defined by its PLOT co-ordinates. PIXADR takes the y co-ordinate in the B register and the x co- ordinate in the C register and returns the screen address in the HL register pair and the bit position in the A register.

The routine INITW first checks that the co- ordinates for the bottom right corner of the window are in fact below and to the right of the co- ordinates of the top left corner, and also ensures that the left and right margins are not both in the same byte of screen memory. This last check ensures that the window is at least one character square in width extra code would be required to

396 THE HOME COMPUTER ADVANCED COURSE

WINDOW DISPLAY

scroll a window that is any narrower.

Errors in window initialisation are printed out by the ROM error message routine. The instruction RST 8 (line 2110 of the Assembly listing) calls the ROM routine and returns to BASIC command mode, and the DEFB 25 in line 2120 provides the message ‘Q Parameter error.

The last section of INITW calculates LFTMSK and RTMASK, which are used when scrolling the screen bytes at the window margins, where part of the screen byte may be inside the window and part outside. The individual bits in the masks that

correspond to screen bits that lie outside the

window margins are set to one, while bits corresponding to bits inside the ina area are set to Zero.

The scroll program proper begins at the label SCROLL. The program tests the direction of scrolling and calls HORIZ for left or right scrolling, or VERT for up or down scrolling.

Left and right scrolling are very similar in operation, so instead of using two separate routines we have combined them in one. The correct code for each scroll direction is selected by testing bit zero of the direction byte. To see how HORIZ works, we will look at leftward scrolling.

Both left and right scrolling start with the top row of pixels in the window and work downwards, so HORIZ begins by copying the y co-ordinate for the top row into the temporary store for the current row. When scrolling left, we must start at the right-hand end of each row of pixels in the window and work towards the left. To prepare for this, RMASK and LMASK are copied to MASK1 and MASK2 respectively, the address of the screen byte at the left-hand end of the current row of pixels is calculated and stored in the DE register pair, and the address of the screen byte at the right-hand end of the current row of pixels is calculated and stored in the HL register pair. The subroutine HLNSCR is then called to scroll the row of pixels. The routine tests to see if the bottom row of the window has been reached, and if not it takes the next pixel row and jumps back to HORIZ3 to scroll again.

HLNSCR begins at one end of the pixel row, with a byte that may have some bits inside and some outside the window, then moves along the bytes that are contained wholly inside the window and finishes at the other window margin, where again some bits may be inside and some outside the window area. We illustrate this with a diagram that shows how the code operates on the right-hand byte when scrolling left. The section of HLNSCR beginning at NEXT scrolls the bytes inside the window area. The bit that was moved out of the previous byte into the carry flag has been saved on

nn rN

, | | '

the stack by a PUSH AF instruction, and is restored to the carry flag by POP AF. For a leftward scroll the routine selects the RL (HL) instruction and the byte on the screen is shifted left, with the bit from the carry flag being moved into the left-hand end of the byte and the right-hand bit going into the carry flag. PUSH AF saves the carry flag, so this bit can be moved into the next byte. To test for the end of the row the routine simply compares the L and E registers; this is because the high byte of a screen address will be the same for all screen bytes in the same row. Partial scrolling of the last byte is achieved in a similar way to that of the first byte.

Up and down scrolling routines are combined in a similar way. If we examine what happens when VERT is scrolling upwards, we see that the routine begins by copying the y co-ordinate for the top row into temporary storage for the current row. The screen addresses of both left and right-hand margin bytes in the row are then calculated and the length of the row determined. The routine puts the address of the left-hand margin byte into DE and the address of the corresponding byte of the row immediately below into HL before calling the subroutine VLNSCR to do the scrolling. VERT then tests to see if it has reached the bottom of the window. If it hasn’t, it moves down one line before jumping back to VERT5 to scroll another row of

pixels. If the bottom has been reached, the section of the routine beginning at CLREDG fills the bottom pixel row with zeros to blank the row on the screen.

VLNSCR treats margin bytes separately, in a similar manner to HLNSCR. The way the code handles these edge bytes is illustrated in our second diagram. To move the central section of the pixel row, the routine increments HL and DE so that they point to the first interior byte on the current line and the corresponding byte on the line above. VLNSCR then calculates the length of the central section (the bytes that fall wholly within the window area), loads this information into BC and uses the block move instruction LDIR to move the whole central section of this row of the window up one line. |

These scrolling routines are relatively slow. This is partly because left and right and up and down routines are combined and the program must make frequent tests to decide which piece of code must be used, and partly because the bytes at the left and right-hand margins require special treatment if they straddle the window’s borders. The scrolling could be made faster if the program were rewritten to give a separate routine for each direction of scroll, and if the window were restricted to starting and ending at the boundary of a byte of screen memory.

Down The Line

Horizontal scrolling presents particular problems at the window edge: the screen byte must be masked to isolate the pixel bits inside and outside the window, and the byte contents must be shifted. Both processes employ logical AND, OR and SHIFT, and the stack is used to save the PSR status.

Vertical scrolling is made simpler by the Spectrum’s screen memory map (See page 358). The screen byte must be masked to isolate pixels inside and outside the window, and the EX instruction is used to swap the contents of the DE and HL registers, which contain screen address pointers

THE HOME COMPUTER ADVANCED COURSE 397

Windows On The Spectrum

Operating Instructions

_ MACHINE CODE/SPECTRUM WINDOWS

1) Type in the BASIC Demonstration Program

2) SAVE “SCROLL’ LINE 5

3) Type in and RUN the Machine Code Loader program 4) SAVE “SCROLLMC’ CODE 45312,410 onto tape directly after

the BASIC Program

9) Rewind the tape and LOAD “SCROLL’ Assembly Listing

10 FIR ADR 20 We

2G MASE | AQ MASk 2 cid WADWT Be OW LEFT xX 70 LORY 80 RIGHTS Se ROLY 1@@ LEI Pe RE 120 CURNTY Eee EE LES 140 LMASK 120 RMASE 16@ LENGTH

18@ INIT

250 SURO

Se@ HORI Z

Soe HURT 2

4i8 HORIZ2

440 HORI ZS

40 HORT 24

600 HLUNSCR

710 HLNI Jeg HLNE

7aQ@ NEXT

7760 HUNG 800 HLN4

BEBO HLNS 892 HLNG

FiO LAST

398 THE HOME COMPUTER ADVANCED COURSE

aemmnnnnnnnemmmnnnnnnmnneenn ren SSS SS

EGU EUU EGU EOL EQU EGU EGU a EGU EG EGU EGU

SSA FEOAA IRCA HEROS REO 4

18 #100 HL, (WT)

HL, (WT) HL.

1x

1, (1X+DIR) Ar

7 HORIZ AE

NZ, VERT

A, (1X+TORY) CIX+CURNTY) 6 @, (1X4+DIR) Z,HORIZ1

B, (IX+L MASK) A, (IX+RMASE) HORIZ2

BR, (IX+RMASE) A, (1X+LMASE) (MASE?) 6 A,B

(MASE 1) .4

C, (IX+LEFTX) B, CIX+CURNTY) PIXADR

DE, HL

C, (IX+RIGHTX) B, (IX+CURNTY) PIXADR

@, (IX+DIR) Z,HORIZ4

DE, HL

HLNGCR -

A, (IX4+BOTY) (IX+CURNTY)

Z

CIX+CURNTY) HORIZ3

A, (MASK 1)

BA

(HL)

cA

A,B

(HL) @, (IX+DIR) Z,HLNI

A

HLN2

A

Ar

C

(HL) ,A

@, (1X+DIR) Z,HLNG

HL

@, (1X+DIR) Z,HLNS CHL)

HLNS

(HL)

Ar

NEXT

b, HL)

A, (MASE®) C

BLA

AF

@, (1X4+DIR) Z HEN?

c

HL 7 HLS

VERT

VERT 1 VERT?

VER ES

VERT 4 VER TS

VERTIS VERT 4 CLREDG

ClLRI

VUNSCR

ENDEBY |

INT TW

LETMSE

a

RI MASE.

Le

ERROR

RET Rad DERE

PILING ie @, (MASE Ss)

C B (AL) 8

Clee Lep ry) @, (1K4DIR)

7, VERT

BR, (I X+ROTY VERTS

B, (1X4 TORY) (IX#CURNTY) 8 PIXADR

HL

HL

C, (IX+RIGHTX) BR, (IX +CURNTY) PIXADR

(IX+LENGTH) 6

@, (1X4+DIR)

7, VERTA CTX+CURNTY

VERTS ee

_(DXeLEP TS)

= (TX +CURNTY)

PIXADR

DE

HL

VLNGCR

A, (IX+CURNTY) , (LX4DIR)

Z,VERTS

(1X4 TORY)

VERT7 (TX+BOTY)

NZ,VERT®

HL

A, (IX+LMASh) (HL)

(HL) A

BH, (1X+LENGTH)

A,@

HL

(HL) A

CLRI

HL

A, (IX+RMASE) CHL)

(HL) A

A, CIX+L MASE) ENDBY |

CL, (I Xt+LENGTHD)

A, (IX+RMASE) BLA

(HL) CoA

De aL A,8 (HL)

c (HL) A DE , HL

A, (IX+RIGHTX) CIX#LER TX) 7, ERROR

C, ERROR

A, (IX+TORY) (IX4+BOTY)

7, ERROR

C, ERROR Bixee Te BH, (IX+TORY) FIXADR

HL (IX4+LBIT) (4 C, (IX+RIGHTX: H, (1X4 TORY) FIXADR (IX+RBIT) A AC

a,c

L

7, ERROR

B, CIX+LBIT) A,@

a (IX4+LMASE) 6 BR, (IX+RBIT) A, 255

A

Le (IX+RMASE) A

8

ott ane

BASIC Demonstration Program

10 20

L2U

CLEA LOAD LET LET LET Lee Cer Let eer LET LEE BORD PAPE Ci PORE FRE PI

IN LO,HI

2a 2i@

PEN eae

Lemons eet

24 2a 260 2/70 20 27 208 31 8 420 41@ 420 40 440 472

gs es

PORE roe e ROE E FORE, RAND FOR

PLOT DRAW MEX | a ese

FOR Y=

FAM D NEXT PRIN POPE FOR

RAND MEX] PORE FOR

RAND NEKT PEE FOR

ROnD NEXT PORE BOR

POA) MEAT atl E TLE

Rose hee CODE

Wl =45056

WINDOWTABLE=45046@: REM BU@4 HEX

LEP EX e@

TORY=S1

RIGHT Kee

BOTY=3

DIR=7

SCROLL S45Se 2 INT TS4S312

ERG

Roe ENE

WI,4: PORE WT+1,176 Wr & WT+1 NOW CONTAIN ADDRESS 4504¢ FORMAT WINDOWTABLE+LEFTX,5 WINDOWTABLE+TORY,8@ WINDOWTABLE+RIGHTY, 25@ WINDOWTABLE+BOTY, 35 OMIZE USR INIT Veo To ive

g,¥

BESO

¥

WINDOWTABLE+DIR, © @ 10 45 OMIZE USR SCROLL

Mf YOAT 12, 2@. "HELLO: WINDOWTABLE+DIR,@ i=1 TO 130 OMIZE USR SCROLL

I

WINDOWTABLE+DIR,3 T=1 TO 35 OMIZE USK SCROLL

I

WINDOWTORLE+DIR, 1 i=l fo 130 OMIZE USR SCROLL

i

WINDOWTABLE+DIR, 2 l=1 TO 35 OMIZE USR SCROLL

i Oo 418

Machine Code Loader

Lag 118 12@ 1a LA’ 1o@ 160 17 LO Le a a 1@ie 182g 1220 Tad 1250 1Q60 L740 1280 1ac@ 1182 111 1122 1129 1146 1158 1168 EE 11s 1198 1200 121@ P22

EAH SSN

1240

aod 1260 L278 1280 1290 130 121@ 1320 1230 1340 1258 1260 1270 138 1200 149 1410 1428 1430 1440 1450 1460 1470 1480 1490 150

SEE

FOR fer READ PORE Let NE XE READ

Leo Se

NEX | DATA DATA

DBIA &

DATA DATA DATA DATA DATA DATA DATA DATA DATA DATA DATA DATA DATA DATA DATA DATA DATA DATA DATA DATA

DATA 22

DATA DATA DATA DATA DATA DATA DATA DATA DATA DATA DATA DATA DATA DATA DATA DATA DATA DATA DATA DATA DATA DATA DATA DATA DATA DATA DATA

A=4Sal Pete PO SOR Pee te S=

i)

a, Se St 4 by eo THEN i 420,176. 225,22) 225 205,69. 1147 178,201. 42,0.176,229 221 225 i272 21,203,7,78,245,204.29. 177,1164 eo1,196,164,177, 201,231 ,126,1,1347 221118 ,6,221,203,7, 70,40, 8a7 8,221, 70 Boel 26 9,24, 687 6,221,70,9,221 126,852,711 . 20,50,2,176,22 1, 78,826 Woe el 70.6, ees 17a. 4,255. 941 Sol, 78,2. 201, 7@2,6,205,170,972 34,251, 203,7,70,40,1,225,811 205 5 10551775221, 126,2,221, 190,1246 6,200. 221 55,464,354. 215,568,782 2,176.71, 166.79, 120.47, 146,627 So) 205,7,70,40,4, 205,47, 795 OA > 208 29 ae it tie 221 iase 202,.7,72.40,5, 25, 24,1, 78% 45,125,187,40,146,.241,201,207,1076 7,70,40,4,205,20.24,2, 782 O07, 22,245, 24 COR SUB G2 Earl es ERNE hav 176,161,711, 2541 221, 205,7, 70,1150 42 4, 203,25,24,2,20%.17,518 Be 5 ize. 47,161,176,119, 201,941 21,78,0, 221 202, 7, 70,40,840 5,221, 7@,3.24,3,221, 72, a

L,eel lis. 6, 20s, 170,234,229, 278 229,221, 78.2,221,70,6. 205.1052 ee 167,227, 62,125,461, 1085 21,119,10,221,203,7,70,40,991

5,221 8o 8s eas Gs ee 6,221,78,8,221,70,6,205,807 170,34, 209,729,205,40, 178,221,1286 126,6,221, 205,7,70,40,5,678 221,192.1,24,%,221,190,2,.85: Se, 207, 225,221 126.8, 166,119,1106 221,72,10 62.0 25,119, 16.535 252 55,2271, 126,9, 146,119,201 1129 Sook Lk 6,@,221,78,.10,237,176,221, 949 126. re ers 47, 166 79,235,120, eR 166, 7 119,23 5201, 221, 126.2,1047 221,190,080, 40, oe 63,221,869 124, 1.221, 190, 5, 42,57,56,694 =o, 201, 76 0,221, 70,1,205,851

170, 34,229, 221,119.4.231,78,1076 © eet 76.1 eee ee 4 oi gaa 119,5,195,121,189 48,256,221 ,915 70,4,62,@,55,31,16,252,492

O31, i19 58,221, 70,5, 65,255 csi 167,31. 16,252,221, 119,9,201,1@16 207 ,25,0,8,8,0,0,0,232

PRINT “ERROR IN LINE “st: STOP

REVERSE/PROGRAMMING PROJECTS

SHUFFLE THOSE DIGITS

: ; cos algorithm into the program to help a player who | Our series of short entertaining programs sets stuck.

| continues with a look at a puzzle known as

| Reverse. The object of the game is to Reverse arrange a list of numbers in ascending order 20 DIM a C20,

| in the least number of moves. This may

seem exceedingly simple, but often the best

* puzzles stem from the simplest concepts.

Woy

4 n POTENT ioG) od

ty ig Juans | ¢ 1

PUA D ECR

Mm CR AMO Rr TD

ce Cet at

ed ue

| The program randomly generates a list of numbers | for sorting. Changing the order of the numbers is | possible only by reversing specified groups within | the list. For example, if the computer generates the | following random list in response to the player’s request for nine numbers:

| 284715693

| and the player then specifies ‘Reverse? 5’, the first | five numbers will be inverted and the list becomes:

: 174825693

It shouldn’t take you too much time and effort to solve a puzzle like this, and you would expect that | it could be easily solved by a predefined algorithm. | In practice, however, it is difficult to define a really good one. Suppose that there are n numbers in the list. The most obvious algorithm is this: | @ Find the largest number in the list and reverse all the numbers up to its position. The largest number | is now at the left-hand end of the list.

M Reverse all n numbers so that the largest | number is in its desired position at the right-hand | end of the list. This has taken only two reverses. Dp. @ Find the second largest number and repeat the

whole procedure again. To move this number to its | desired location requires a “Reverse n-1’ move.

M Repeat the procedure until the order is

| obtained. | This algorithm always solves the puzzle in 2n-3

| moves. But it is possible to achieve a solution in

fewer moves than this. To demonstrate how a

| _ forward-looking strategy can reduce the number

of turns, consider the example we give in the box.

Our algorithm would take seven (2X5-3) turns, but a skilled player could doit in four.

This program is a simple example of a whole

series of reversing games that people have created

and explored. You might like to try your hand at

| developing games that reverse from either end of

the line, or where you have to sort out a grid of

numbers rather than just a line. If you do design

your own version of the game, you might like to

jazz it up by using different coloured blocks to

replace the numbers. The object of the game could

then be to rearrange a line of blocks to match a

pattern of coloured blocks at the top of the screen.

You might also like to try incorporating an

PRINT

“1 THEN G0

Te 7

CS TO 14a

tea LEE Ae Lie

o—

.

oS _ o _

THE HOME COMPUTER ADVANCED COURSE 399

Industrial Instruments Group ‘Technological subjects researched at Sharp's Engineering Centre are

transferred to the IIG plant

(shown here) at Yamato- -Koriyama-shi, Nara, Japan, where the Corporation's products (including calculators and personal computers) are designed

GLOBAL ENTERPRISE

The orporation is a Japanese-based company that manufactures an enormous range of products, from transistors and refrigerators to computers and industrial robots. International sales in 1983, the year it entered the UK home computer market, amounted to nearly £2 billion. |

The Sharp Corporation has always been party t major technological innovation. But its first successful product was an extremely humble item the ‘Ever Sharp’ propelling pencil. Its creator, Tokuji Hayakawa, set up Sharp in 1915 to manufacture his invention; and the company

expanded steadily in succeeding years. In 1925 it moved into electronics with a crystal radio set; and

entry into the world’s consumer electronics markets came in the post-war years when it began producing television sets and other domestic

appliances. In the mid-1960s the company

intervened in the business machinery market with a series of desk-top calculators. Today it is a huge multinational corporation, subdivided into six manufacturing groups, with 34 production plants in 30 countries outside Japan.

The first Sharp computer marketed in the UK was the MZ80K, which was launched in 1981. The following year, the company added the MZ380A and MZ380B to its range. Although these computers were marketed as business machines,

they also found favour with home micro users.

Each model comes equipped with a built-in

- monitor and cassette drives. Originally, these

400 THE HOME COMPUTER ADVANCED COURSE

computers were marketed as ‘clean machines’, emphasising their lack of a resident language in ROM. The advantage of this was that a variety of languages, including CP/M, could be loaded on- board from cassette.

Sharp began selling a full range of business and home computers in the UK at the beginning of 1983, when the company’s list of products was extended to include the MZ-3541 business machine and the PC-1500 pocket computer. The success of the latter led to the marketing of the PC-1251 pocket computer. |

The company entered the home computer market with the launch of the Sharp MZ-711. This is the European version of the Japanese MZ-700 series, and the enormous Japanese character set of the original has allowed room for extra graphics facilities on the European model, The machine has a data recorder fitted as standard, and space is included for an optional printer/plotter.

In May 1984, the company released the PC- 1500A, an upgrade of the PC-1500. The new model is fitted with 8.9 Kbytes of RAM, which can be expanded up to 24 Kbytes. In the autumn of 1984 the company plans to launch the PC-1350 pocket machine with a four-line display and graphics capability. Sharp Corporation also intends to introduce the Sharpwriter package, which is a marriage of the Sharp ZX-401 electric typewriter and the MZ-3541 microcomputer. The typewriter is used as a _keyboard/printer connected to an RS232 interface in the computer.

Asked about further developments from Sharp, sales director Rod Goodier says that he is ‘personally very keen to expand the pocket computer market, where there is very great

potential’. This does not mean that the home

computer market will be neglected. “With the MZ- 700 family we will really go to town, and we intend to stay firmly in the home computer market.’

k Company spokesman Peter Fletcher explains:

‘The business equipment division, including home computers, is a relatively recent innovation, and represents 25 per cent of turnover in the UK. The

. plan is to increase the proportion of turnover.’

At the moment Sharp UK has only .a warehousing and marketing operation. The company is currently building a £15 million plant in Wrexham to assemble video recorders. The plant is expected to produce 60,000 machines in

| 1985 for distribution throughout Europe.

On the question of Sharp’s involvement with other Japanese companies in the expected MSX

invasion in the autumn, Rod Goodier replies that

‘Sharp have developed an MSX system, but there are no plans to launch in the UK at the moment.’

leep—or keep yo

Fy

ae

J

cc ete

RSLSALO RAMONE EEL ty,

i

et pvactnet etter ttt it tet nein ed tet ters nnd te ett tase mastercase ADM beADe tbs sree Atte OPMAh Logandale tind 3 5

o

array

al

ction neti

Jessie sicher

EE

RR Naame

bisces, : é ‘Scuitateesmsemamenss™

: femme ¢

ciunusin cierto seem gests wig lrstraansen es tists besser tai eco et tel eels aimee ed titi Shia eet doi eid td z 3 isis