213 Building a 3D Maze with CSS and JavaScript
var len = 16;
var passages = {
'left' : [8, 16],
'right' : [4]
};
This looks simple enough to interpret, right? Well, yes however, turning this data structure into
coherent English is still a little tricky. The basic conversion is easy. Using the data we have, we can
describe the view in coarse terms:
The corridor stretches 16 meters in front of you. To the left there are passages after 8 meters and
16 meters. To the right there are passages after 4 meters.
However, this language is fairly obtuse. For one thing, we wouldnt want to say there are passages
if there was only one. Instead, wed want to say theres a passage. Additionally, the last passage
to the left is at the far end, so it would be nicer to describe that by saying The corridor stretches
16 meters in front of you, then turns left.
We also need to deal with exceptions. For example, if the player is standing directly in front of a
wall, we dont want to say “… stretches 0 meters in front …” Likewise, if the player has just turned
right into a passage, we dont want to say to the right theres a passage after 0 meters.
To cater for all these exceptions, the script accepts a dictionary of sentence fragments with replace-
ment tokens, which are then compiled and parsed as necessary, in order to obtain a result that ap-
proaches decent prose. If you have a look in init.js, youll notice that the DungeonView object is in-
stantiated with this data as an argument. Each of the language properties is a sentence fragment
with replacement tokens; for example, %dir is a direction token that will be replaced with the word
for left or right, as applicable.
Id encourage you now to scroll through the generateViewCaption method in underground.js, and
read the comments there that explain each situation. As it is, theres still room for improvement,
but this is one of those things that you could refine to the n
th
degree, and it would still never be
perfect.
6
That said, I believe that the end result is fairly goodthe captions are verbose enough to
get the information across, theyre succinct enough not to be arduous to read, and they flow well
enough that they dont sound too much like they were generated by a machine (even though they
were!).
Designing a Floor Plan
In the code archive for this book, youll find a floor plan designer, which is a separate JavaScript
application that generates the floorplan matrix used by this game. Its a table of squares, and you
6
Read more about the problems associated with constructing natural-sounding sentences in English in the Wikipedia entry
on natural language processing at http://en.wikipedia.org/wiki/Natural_language_processing/.

Get The Art & Science of JavaScript now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.