Chapter 8 - Role Play
Role play games are regarded both as a generic form and a specific game type. As a generic term it covers all games where you take on a simulated task of some sort, whether a band of thieves in a forest, an airline pilot or a bank manager.
Role play games as a specific game type don't originate with computers at all, but with people acting out character parts within a set of rules and guidelines set out by the creator of the RPG. Generally, a 'world' is described where the players live, fight, and perform (almost) all the normal human activities. As the scenario is an artificial world the game maker can make available whatever characteristics or new sciences he or she likes. The favourite addition is, of course magic.
RPGs are often open ended with no specific task to perform but guidelines are given for improving your status in the game world. From there on, as in the real world, you learn by experience. You must therefore be consistent in any rules you apply. Players will lose interest if they find that the same monster is dispatched in different ways simply because they meet it in a different area of the game.
RPGs fit very easily into computers. At a basic level you can write one using text instructions and keyboard input. The game can be completely open ended in that there need not be a specific set of tasks to perform. This is the typical scenario of the Dungeons and Dragons type games. Players can simply wander around your artificial world picking up treasures and becoming steadily more adept at dealing with obstacles, puzzles and monsters.
The first essential point is that you must have a map of the layout of your game. This can be based on a two dimensional grid or, if the scenario is, for example, a castle, you can create a three dimensional plan. All treasure, wizards and monsters can be identified simply by grid reference. If your player has the same reference then they are in the same area and you can give the player a brief description of the scene and what options are available to him or her.
This structure lends itself very well to desktop working as you can use a set of icons for both objects and activity choices. These can be dropped on a simple sprite background within a window, with mouse clicks over the icons for various actions. In this way no text is needed at all.
For example with a two dimensional forest game world with text and graphic components you can maintain a location map of place description strings with a parallel array with sprite lists for the major drawing. In this simple plan you could limit the area to between 0 and 8 locations in both the X and Y directions. Your player starts off with area coordinates of 4,4. In the absence of any specific alternative the game can assume a standard trees and shrubs background.
Although the game world is two dimensional the scene can be drawn as a three dimensional picture. You need a string array with a list of all the objects and a parallel array giving the X,Y map coordinates of the objects and the object type. The arrays would include screen plotting position and sprite number of the graphic representation of the objects. These arrays are then scanned to see if any objects are located at 4,4 and if so they are plotted and described.
Anything picked up should be marked as at location -1,0. This can be scanned when the object needs to be used, and as we have no negative elements in the map only the X coordinate need be checked. Location -2,0 can be used for objects or monsters that are destroyed or hidden. The game can randomly re-generate these in new locations. This gives an apparently limitless supply of creatures to use. For items permanently destroyed I suggest -3,0 as their location
Using ordinary X,Y movement controls your player can move to 4,5 or 5,4 or 3,4 or 4,3. Logically these would correspond to East, North, West and South respectively. Obviously directions like 5,5 would give Northeast. Once at the new location the arrays can be scanned again and the new scene drawn up.
Listing 8.1 is a skeleton of this idea with minimal text descriptions rather than a graphical display.
REM > RPG
IF action% PROCdescribe
CASE action% OF
WHEN ASC"Z":IF X%>0 X%-=1
WHEN ASC"X":IF X%<wide% X%+=1
WHEN ASC"/":IF Y%>0 Y%-=1
WHEN ASC"'":IF Y%<high% Y%+=1
PRINT TAB(31,5) "Demo RPG Game"
FOR J%=0 TO wide%
FOR I%=0 TO high%
IF place$(I%,J%)="" place$(I%,J%)="You are deep in the forest.
Tall pines block your view."
FOR I%=0 TO numobs%
READ object%(I%,xloc%),object%(I%,yloc%),object%(I%,type%), object$(I%)
DATA Loc.0/0,,,,,You are by a swift river,You are on open heath,
DATA This is the wide road to Hanri
DATA ,,,,,,You are near a babbling brook,
DATA You are on an old gravel road
DATA ,,,,,,You are by a crystal stream,
DATA You you are on a narrow track
DATA 4,4,0,A stone seat
DATA 3,4,1,A silver challice
DATA 2,4,2,An ugly Troll
FOR I%=0 TO numobs%
IF object%(I%,xloc%)=X% AND object%(I%,yloc%)=Y% THEN
PRINT object$(I%) " is here"
CASE object%(I%,type%) OF
PRINT' "Options:"''SPC 5 "Z - West"'SPC 5 "X - East"'
SPC 5 "' - North"'SPC 5 "/ - South"
IF collect% PRINT SPC 5 "C - Collect"
IF fight% PRINT SPC 5 "F - Fight"
PRINT'"Escape - Stop"''"Your choice :"
IF NOT collect% ENDPROC
FOR I%=0 TO numobs%
IF object%(I%,xloc%)=X% AND object%(I%,yloc%)=Y% AND object%(I%,type%)=1 THEN
PRINT object$(I%) " - carried"
IF NOT fight% ENDPROC
FOR I%=0 TO numobs%
IF object%(I%,xloc%)=X% AND object%(I%,yloc%)=Y% AND object%(I%,type%)=2 THEN
PRINT object$(I%) " - killed"
Although there is primitive fight recognition full combat sequences are a bit more complicated as you have to give a real air of urgency and at the same time enable the player to respond quickly to the changing situation. It may be best to expand the object types into parallel arrays of friends, foes, treasures, and utility objects.
Each player takes control of a character in the game, these typically have the following attributes:
- Strength - combat ability
- Psi - magical ability
- Intelligence - general capability
- Experience - learned abilities
The ability to win any combat depends on matching these attributes against those of the adversary and assessing which actions are attempted and the response time
Combat is usually broken down to melee rounds and player attributes updated after each round. As well as giving players strike by strike control this lets you generate multi-character combat. Only one-to-one fights take place in each round but by alternating characters you can give the appearance of a real gang fight.
One way to achieve this is to create a pair of arrays to hold character attributes, one for goodies, the other for baddies. At random you can then match any goodie against any baddie. If a character dies its place in the array is taken by another and the array compacted. The combat session finishes when one or other array holds no more characters. There is an outline of this technique in Listing 8.2
REM > Combat
FOR I%=1 TO weapons%
line$=" Character Strength Psi Intelligence Experience"
IF goodies%>baddies% size%=goodies% ELSE size%=baddies%
DIM attributes%(1,size%,attribnum%):REM goodies/baddies, characters,size%
FOR I%=1 TO goodies%
FOR J%=1 TO attribnum%:REM zero element used as player flag
FOR I%=1 TO baddies%
FOR J%=1 TO attribnum%
PRINT''"Test Combat sequence"'
PRINT "Select your character by number"
UNTIL num%>0 AND num%<=goodies%
attributes%(0,num%,0)=TRUE:REM set player flag
REM could be repeated for several players & with baddies too
FOR I%=1 TO gang%(flag%)
PRINT';I% TAB(2) name$(flag%,I%);
FOR J%=1 TO attribnum%
PRINT TAB(J%*11) attributes%(flag%,I%,J%);
gang%(0)=goodies%:REM temp store for fight only
IF assail%=0 assail%=1
IF attributes%(attack%,assail%,0) PROCselect ELSE PROCmatch
UNTIL gang%(attack%)=0 OR gang%(defend%)=0
PRINT name$(attack%,assail%) ", select your opponent by number"'
UNTIL oppose%>0 AND oppose%<=gang%(defend%)
PRINT'"Select your weapon by number"'
FOR I%=1 TO weapons%
PRINT"(";I%") " weapon$(I%)
UNTIL type%>0 AND type%<=weapons%
IF oppose%=0 oppose%=1
IF attributes%(attack%,assail%,strength%)>attributes%(defend%, oppose%,strength%)
IF attributes%(attack%,assail%, psi%)>attributes%(defend%,oppose%,psi%)
type%=2 ELSE type%=3
PRINT "The " name$(attack%,assail%) " attacks the " name$(defend%,oppose%) " ";
CASE type% OF
IF INKEY 150
IF diff%>90 diff%=90
PRINT "with a blade of true steel."
IF RND(9)=1 THEN
PRINT "Fumbled! The " name$(defend%,oppose%) " has a lucky escape."
IF RND(diff%)>30 THEN
PRINT "The " name$(defend%,oppose%) " is too clever to be caught so easily."
PRINT "A hit. ";
IF attributes%(defend%,oppose%,strength%)<1 THEN
attributes%(attack%,assail%,strength%)+=(sum% DIV 2)
PRINT "The " name$(defend%,oppose%) " is still strong."
attributes%(attack%,assail%,strength%)-=(sum% DIV 2)
IF attributes%(attack%,assail%,strength%)<1 PROCdead(attack%,assail%)
IF diff%>20 diff%=20
PRINT "with a strange enchantment."
IF RND(9)=1 THEN
PRINT "The " name$(defend%,oppose%) " ducks the spell."
IF attributes%(attack%,assail%,psi%)>attributes%(defend%,oppose%, psi%)
AND diff%>3 THEN
PRINT "The " name$(defend%,oppose%) " is ensnared by the spell."
strength%) DIV 3)
IF attributes%(defend%,oppose%,strength%)<1 PROCdead(defend%,oppose%)
PRINT "The " name$(attack%,assail%) " hasn't the mental power to
overcome the " name$(defend%,oppose%)
PRINT "by a cunning feint."
oppose%,experience%) DIV 2 THEN
PRINT "It fools the " name$(defend%,oppose%) ", but saps strength."
PRINT "The "name$(defend%,oppose%)" laughs and continues the fight."
PRINT "The " name$(flag%,character%) " dies."
IF character%<gang%(flag%) PROCmovedown
FOR I%=character% TO gang%(flag%)-1
FOR J%=0 TO attribnum%
IF gang%(0)>0 THEN
FOR I%=1 TO gang%(0)
IF attributes%(0,I%,0) flag%=TRUE
IF NOT flag% PRINT "Unfortunately your character died but t"; ELSE PRINT "T";
PRINT "he good guys won the fight."
IF gang%(1)>0 THEN
PRINT "The baddies rule OK!"
PRINT "Everyone died. There are no victors."
A problem that can arise is where a dying character suddenly unleashes a spell of enormous power that completely destroys the enemy and yet still hasn't the strength to pick up a sword. To avoid this you should make death occur on the basis of several attributes falling below a certain point rather than any single one reaching zero. To add further realism, instead of working directly with the stored figures for attributes work from a continuously updated set of inter-related ones.
If you decide to write an RPG then you must ensure that any magic or pseudo-science you devise is consistent. There is nothing more irritating than finding that (say) a firemaking spell produces a roaring inferno when you have a few wet twigs but not so much as a whiff of smoke from a bundle of old newspapers.
Combining the RPG map routine with the combat program gives a basic text only RPG. This is too crude for today's players, but there is enough here to give an idea as to how you can develop your own ideas into a fully fledged graphical game.
As a final tweak it may be worth considering having the ability for either the goodies or the baddies to decide they are losing too heavily and run away. For this you would keep a check on the average attributes of all the baddies and if it falls below a certain figure then, with a suitable message, re-locate them all to random locations in the game. For the goodies your player would decide when it was time to run away, and possibly which direction to run to.
Adventure games are often thought of as RPGs with the combat section removed, although that is a rather simplistic view. Firstly adventures tend to be more focussed, in that there is a specific set of tasks to be performed, usually in a fixed order. Similarly there is usually a fixed number of objects, monsters, etc.
The map structure is not rigidly defined, but moving to different locations in the game should be logical. Going East from a room that you travelled West to reach should take you back to your original location. The exception is mazes, where experienced players will expect peculiar directions. Unlike RPGs adventures don't usually have all possible locations set on a grid, it's normally a free-flowing map.
Because of this the usual representation of the game map is not a simple two dimensional array but an array of pointers and links. The player's current location is a location number, this being an index to the main location array. This is often referred to as a room list . Typically there will be four other rooms that can be reached from any room. Testing an attempt to move, say, North would involve looking at the first direction link, assuming this represents North, and seeing which room number it points to. Zero would mean that this direction is closed off. This map representation is shown in figure 8.1. Notice how the room numbers don't need to follow any special pattern. This is particularly useful when you want to open or close links as the game progresses. Note the one way link between rooms 6 and 4. This is a common way of dealing with cliff tops, pits, etc. where the player can get in but not back out again. Keeping the West option reserved in room 4 allows you to create a magic door back late in the game.
The Room list will also have flags for any special characteristics that each room may have. For example, caves would need light. Below is a typical room list structure. This can be held in parallel arrays, with the text information a string array. The array index numbers would be the actual room numbers.
- Direction link 1
- Direction link 2
- Room attribute 1
- Room attribute 2
- Sprite pointer(s)
- Description text pointer(s)
8.2.2 Locating objects
Once you have defined your map you must consider how objects are to be placed. This can be done in a similar manner to that of RPGs. However, instead of storing X,Y coordinates you use an array of objects storing room numbers. The array index number itself is a unique identifier, so you don't need a type element in the array. However, you can usefully keep a set of flags determining the generic attributes of the object. These could be combustible, breakable or wearable, etc. Your object structure would be very similar to the place structure, as below.
- Object attribute 1;
- Object attribute 2;
- Sprite pointer(s);
- Description text pointer(s).
All you need do now for descriptions, or any other object handling, is scan the list picking out any object that is marked as at the room in question. It is usual to mark room 0 as hidden objects, room -1 as carried, and room -2 as worn.
One source of confusion arises when an object can be carried by another object. Does location 5 refer to room 5 or object 5? The solution is simple. Add an offset of say, &1000 to the object numbers. You are never likely to want 4096 rooms and it can easily be masked in and out of calculations and array indices as shown.
index%=object% AND &FFF
object%=index% OR &1000
8.2.3 Understanding Instructions
The core of a text adventure game is the parser. This is the part of the program that reads in a player's input and works out exactly what is being requested. All words read from the text are given number representation. If no known words are found then the word identifiers are set to zero. Older adventures used to recognise simple verb/noun combinations such as Get Brick or Drop Fish. Later versions scanned the text for just these two combinations but were able to skip over and discard any unwanted words as rubbish. This didn't improve the flexibility of the parser but it did allow more natural sentences to be decoded.
A useful addition to this simple parser is the handling of prepositions. These are words that indicate how a noun is used or where it may be found such as:
- Put hat on peg
- Sweep floor with broom
- Look under rug
- Hide key in pocket
Two other useful additions are adjectives and adverbs. Adjectives would be noun modifiers giving results like:
- Get the green bottle
- Find a rough spot
- Examine the open box
Adverbs, as their name suggests are verb modifiers. Using all of these word types will give remarkably intelligent decoding results. All of the following can be recognised by such a parser:
- Quietly enter the open door;
- Carefully drop a silver coin into the metal bucket;
- Eat the big cake quickly.
It is doubtful if there is much to be gained by taking the parser much further, even though it might be an interesting challenge to produce really sophisticated parser of the kind that can handle a sentence like:
Use the string to tie all the keys except the red one to the tag and hang them up
Most game players will quickly revert to quick-fire three or four word commands, with only the occasional attempt at something more exotic when all else fails. Therefore effort spent in developing your parser would, sadly, be wasted.
A somewhat ticklish area is that of handling obscenities. Everyone gets frustrated sometimes and then uses words that no decent computer wants to read. If you decide to recognise such words then you must take great care to ensure that it is completely impossible for your game player to accidentally reveal them, otherwise you could cause very real offence to an innocent player. It is best to recognise the offending words as verbs and then give a simple response like:
- I don't like that kind of language
- You can't do that sort of thing in this game
- This is a family game
You can keep an obscenity count if you like, and after a couple of warnings terminate the player with an act of the supreme being's displeasure.
A working verb, noun, adverb, adjective parser is shown in listing 8.3
REM > Parser
FOR I%=0 TO numverbs%
PRINT TAB(I%*10) verb$(I%);
FOR I%=0 TO numnouns%
PRINT TAB(I%*10) noun$(I%);
FOR I%=0 TO numpreps%
PRINT TAB(I%*10) prep$(I%);
FOR I%=0 TO numadjes%
PRINT TAB(I%*10) adje$(I%);
FOR I%=0 TO numadves%
PRINT TAB(I%*10) adve$(I%);
PRINT''"Enter sentence to parse (capitals only), or * to stop."
DATA 7:REM verbs
DATA 6:REM nouns
DATA 11:REM prepositions
DATA 7:REM adjectives
DATA 4:REM adverbs
IF NOT FNmore THEN
WHILE RIGHT$(c$,1)=" "
IF no1%=0 PROCword(adje$(),adje%(),ad1%,numadjes%) ELSE
IF flag%=FALSE PROCdiscard
WHILE LEFT$(c$,1)=" "
IF w%>0 OR flag% ENDPROC
IF a%=0 THEN
UNTIL I%>=n% OR t$(I%)=w$
IF t$(I%)=w$ THEN
IF a%=0 c$="" ELSE c$=MID$(c$,a%+1)
IF a%=0 THEN
To extend the vocabulary you need only alter the data lines, increasing the word counter and fitting in the words. You will see that several words can have the same reference number to allow for players using variants of the same command.
Notice how as it strips out words from the input text the parser re-checks for word types it may have missed. This is to cope with the vagaries of English grammar that allow adverbs, in particular, to be put almost anywhere. Both of the following will be correctly read by the example parser:
- Softly stroke the cat
- Stroke the cat softly
Any words that can't be matched are dumped by the discard procedure. This lets your player use all the common redundant conjunctions, giving the feel of real understanding from your game.
8.2.4 Finding Nouns
In a graphic adventure you can isolate objects simply and unambiguously with a mouse click. With a text adventure things are more difficult. There are two basic approaches to resolving this problem. The first, and commonest, is to keep a list of words, as was done in the example parser. However, as with verbs, you need to allow for the player using a similar but not identical word. Take the sentence:
"You are on a rocky hill path. Sharp flinty stones are all around."
If you have a stone as an object your player could quite easily describe it as a rock or a flint, and be most annoyed if the game refuses to understand. This means you need to look at the text very carefully and make sure that you have covered all reasonable possibilities with duplicate noun names. Once you have a match, you need to make sure that the object referred to is actually there, or has been seen by the player. To simply say "You don't have it yet." is a dead giveaway that the object actually exists somewhere in the game.
An alternative method of finding nouns is to use the description text itself. You scan all the text for the current room and all the objects in that room a word at a time. by doing this you can guarantee that the object or place exists, and also that the player can see it. All you need to do is keep a pointer to the text you are scanning at the time the match is made. This is slightly slower than the other method but far more reliable.
Having described and identified everything in the game you now need to do something with that information. Adventure generator programs use a complex pseudo language to build sets of responses to player input. These puzzle systems can consist of many hundreds of lines that are tested until an exact match is found with the action attempted by the player. However, in a home grown game you can get equally good results by using a simple tree structure.
The first step is to isolate the verbs. This is done with a CASE statement as shown.
CASE verb% OF
Taking the carry situation you can remove some of the tedious checks as below.
CASE TRUE OF
Notice that there may be some valid situations where you appear to carry a room, but are really handling a hidden object, hence the extra procedure.
Finally, in the carryobject procedure you can have the lines testing specific object characteristics and room locations. Anything not handled specifically, would be passed on to a general pickup routine at the end of the procedure.
There is a small group of games that rely on combat only. They still fit with the general classification of role play, but have no storyline or special attributes. These are the martial arts type games. They only really became attractive when there were machines with the ability to run high resolution animated graphics. They are usually single or two player games. The player is given a number of kicks, punches, jumps and rolls, The character on the screen will perform these on a given keypress or mouse click.
The graphical part is really very easy to implement. You simply build up a set of film animations for all the actions you require. These will all take place within a fixed character area. You have an identical set of actions, but with a different sprite set, for the opponent, whether another player or computer driven.
If you use a variant of coordinate collision testing then you can produce a realistic hit system. You relate the damage to your opponent to the distance from the attacking player. Where the two sprites concerned are obviously not in contact at all, the strike just wastes the attacker's energy. As they begin to overlap during the action, you produce a graded energy loss to the character under attack. Hence the reason for keeping the animation within a fixed area.
Usually you need only keep a single energy variable for each combatant, incrementing it with time and successful encounters, decreasing it with failed encounters or unnecessary action. When the energy level falls below a certain level, the character dies. You can give greater realism to this by only allowing the character to perform the more energetic actions, like high kicks, if it's energy level is above a certain figure.
Because these games tend to be particularly fast and furious it is probably best to organise the function keys so that each is assigned a single action, this can be duplicated with a row of matching mouse sensitive icons. This not only allows your player to decide which is more important - speed or keyboard life - but is a useful on screen reminder.
I suppose that simulators can only be thought of as role play in the very broadest sense but nevertheless they still fit the overall classification. The games that most quickly spring to mind when simulations are mentioned are aircraft flight simulators. However, almost any day-to-day activity can provide a basis for simulation. Many education centres use simulated shopping to help teach small children how to handle their money wisely. The logical extension to this is, of course, a trading simulation, where the player run's a large corporate business or even an entire country's economy.
8.4.1 Real World Situation
With real world simulations you need to make a distinction between real time and game time. Logically, if you maintain a ratio of 1 transaction : 1 move, then one year of trading will take you a year to play out on the game. Hardly practical! For many of these games you can use a ratio as coarse as 1 year : 1 move. On the other hand, if you are simulating the running of a power station or chemical works, you would probably work at nearer 1 hour : 1 move.
Unless you are developing a simulation for education use you will need to fine tune the time scale to give a game that is slow enough to be playable without becoming boring. Also, with real world simulators you either need to know a fair bit about statistical analysis, or you will have to develop an idea a bit at a time and make empirical adjustments to keep the simulation in balance.
As an example I'll outline a simulation for I Bodgit, computer manufacturers. Mr Bodgit only makes cheap machines, with no monitor, disk drives, or other accessories. At it's basic level the simulation needs to handle three areas as below.
1 purchase of components
2 manufacture of computers
3 sale of computers
These can be expanded as follows.
1.1 cost of components
1.2 delivery charges
1.3 working capital
1.4 factory storage space
2.1 labour costs
2.4 warehouse facilities
3.1 asking price
3.2 dealer network/delivery costs
3.3 market saturation
We should also, at this point, consider general aspects that will affect all areas of production. Some of these are as below.
4.1 services (gas, electricity)
You could now produce a fair simulation with just this information. We'll look at section one in some detail, so you can see how the ideas develop.
The factory storage space limits how many items you can hold in stock and, with your working capital, will limit your purchasing. Also a reasonable simulation should allow for lower price breaks on bulk orders and lower or free delivery charges over a certain order size. All this can be done with simple maths.
8.4.2 Scaling and Balance
It pays to put everything in terms of anonymous units rather than real figures. It's the ratios that matter not the actual figures. These can be scaled later to give meaningful results to the game player as well as a balanced simulation. In our example we can assume that our main stores has a storage capacity of 500 units and storage units required for the parts needed for one computer are as follows.
1 plain PCB
3 PCB components
6 computer case
This gives us a total requirement of 12 units and our factory can store materials for almost 42 computers. However, you also need storage for finished machines. These would logically require slightly more storage space than empty cases, say 7 units, so the player will have to balance the two.
Component cost can be looked at in exactly the same way. You can start with a working capital of 400 units, and cost the parts so.
2 plain PCB
20 PCB components
1 computer case
Again, not all the working capital can be used as you also have to pay wages and other costs. However you should allow players to make this mistake. Let them find out the hard way exactly what happens when their workers don't get paid!
Component costs, wages and final unit price all have to be kept in proportion. You could assume that component costs only make up about a tenth of the asking price of the completed computer. As a rough guide an average week's wages should be set at about half the asking price of one machine.
You will find that balances develop naturally as the game evolves. If, for example, the player allows too little storage space for completed machines the labour force will have to stop work until some computers are sold but still expect their wages. All you need do is to tweak the figures so you don't get runaway situations.
8.4.3 External influences
The situation is slightly more complicated regarding things like market saturation. Here you have to relate the actual number of computers sold to the apparent reluctance for people to buy. For simplicity, we'll consider that all factors, like inflation, recession, and total competitive computer manufacturing are lumped together as a single negative factor.
A separate factor is the total number of computers you've already sold. As people buy your machine, they won't be likely to want another, unless it fails. Eventually your selling capability could stagnate completely.
Putting it simply you have the very approximate formula below.
computers sold = computers available/(machines sold/time)*asking price*saturation
Time and saturation are pseudo constants you should fiddle to get a reasonable balance. Time partially represents the ageing of I Bodgit's cheap computers. With both this and asking price, I've simplified the situation. A very long ageing time will give poorer sales, but in reality too short a time would have the customers grumbling. Similarly, too low an asking price would look rather suspicious. Also, you obviously can't sell 0.132 of a computer, so you take only the integer value.
Of increasing popularity is whole community simulation. This has enormous scope for programmer and player alike. Below is a brief list of the sort of factors you can integrate into such a simulation. The secondary factors listed are just a sample of the relationships you will need to follow up. In fact, almost everything will inter-relate, so the feel of your simulation for the players will be a direct reflection on how thoroughly you understand your community.
- Population - Birth rate, Death rate, Disasters
- Housing - Building, Population, Civil Engineering
- Employment - Manufactured goods, Agriculture, Services
- Crime - Laws, Poverty, Population
- Services - Politics, Infrastructure
- Disasters - War, Natural
Obviously these whole communities are highly complex living organisms in their own right, and at best, yours will be only a very limited simulation. A key point to remember when planning such a game is that trends are usually more significant that isolated incidents. If you can, you should follow up the following lines of enquiry for more information about how groups of people behave.
- Local government
- Market research
8.4.4 Graphical Simulations
Unfortunately, many graphical simulations require a lot of drawing rather than sprite plotting, and drawing is usually much slower than sprite plotting. This is particularly relevant with flight simulators, where you draw in real time as the plane flies. However it is often possible to work out a compromise. If you look at figure 8.2, a rather crude drawing, you will see that only the central shaded area has to be drawn, using the three dimensional techniques described earlier. All the rest of the aircraft cockpit can be handled by sprite plotting. For example, there is a limit to the practical resolution of the altimeter and heading dials. Rather than try to draw these it is simpler to have a sprite film of their readings, and select the one nearest to the actual figures. Although rather memory hungry, this technique can be used for numeric as well as metered displays to speed up response time.
Initially you would define a graphic viewport where the dotted rectangle is and perform the drawing in this area. Then you mask out the unwanted parts with sprites of the dashboard, window framing and overhead area. These sprites would also contain all the fine detail of switches, dials and lights that are not in fact active. Finally you can plot in the small dynamic detail.
8.4.5 Terrain Mapping
The discussion so far has assumed flat earth scenarios. With many simulations this is far from the case. The game where this is of greatest significance is probably golf. There are two main variables with the impact of the ball with the ground. The first is the obvious relative height above or below the starting point, and the other is the texture of the surface the ball hits.
Height is relatively easy to deal with. You only need maintain a two dimensional array of spot heights. The elements of the array would represent the height above an arbitrary reference point, spaced, say, 100 metres apart. For simplicity, you then calculate the actual height based on the distance of the ball from the nearest four surrounding points and their actual height figures. Listing 8.3 shows this idea in practice with a graphical display of a small map read from data. The algorithm used is accurate enough for our purposes. As it is quite easy to calculate the average height of a square area a recursive procedure is used create progressively smaller squares round the actual point we wish to calculate, until the X,Y differences, and therefore the height differences, are small enough to be insignificant. You will see that by making extensive use of barrel shifting and scaling our dimensions up the routine is almost entirely integer driven, with no complex calculations at all. This makes it very fast.
REM > Terrain
ON ERROR PROCerror:END
INPUT "Start X (1151 max):" xpos
INPUT "Start Y (511 max):" ypos
INPUT "End X (1151 max):" xend%
INPUT "End Y (511 max):" yend%
FOR I%=0 TO width%
IF ERR<>17 PRINT REPORT$ " @ ";ERL
PRINT TAB(30,5) "Terrain Map" TAB(30,7) "Escape to stop"
FOR J%=0 TO Y%
FOR I%=0 TO X%
X%=pX% DIV size%
Y%=pY% DIV size%
pX%=pX% MOD size%
pY%=pY% MOD size%
IF S%<acc% THEN
IF pX%>half% THEN
IF pY%>half% THEN
Mapping surface texture is probably best done slightly differently. You can usually assume that the fairway is of reasonably consistent bounce and roll performance with some minor random deviations. The rough and bunkers will have virtually zero bounce, and water obstructions will lose the ball altogether. Therefore you need to plan a finer set of coordinates for these obstructions. These are best stored as a list rather than a map, and the ball's position compared with the nominal centre of such obstructions. This also lends itself to defining specific, above ground obstructions, such as trees.
It should be possible to integrate these maps with the game drawing routine so you have consistent views and behaviour regardless of the location of the ball.
8.5 Status Saving and Reloading
Most role play games are designed for many hours of play. Where arcade style games can just about survive without game saving facilities, it is quite unreasonable to expect a role-player to start from scratch each time. To facilitate saving and re-loading you should split your game data into distinct static and dynamic parts. Static data will be the overall map or plan of the game, including any text, sprites and the like. Dynamic data is everything that can possibly be modified by the game as it progresses.
It is remarkably easy to leave out dynamic data from a saving routine. The simplest mistake is where most of the data is in arrays but just a few items are ordinary integer variables. What you have to look out for is saving all the arrays but forgetting, say, the number of monsters killed.
Unless your game is vast and takes up all available disk space I recommend that your program saves dynamic data in a special directory within the game application. There is then no need for the game player to hunt out separate disks, remembering which ones is needed. Your saving and loading system becomes simpler too as you only need to scan the relevant directory and present a list of the player positions available.
As usual, there is an exception to this. If your game is implemented as a fully multi-tasking application it makes sense to use a distinct file type so that a player double clicking on this will load the application and game together in true desktop fashion.