This may be a duplicate question as I don’t know to phrase the search query. I’m creating a Zork-like text based game in Java where the character moves to different rooms which are connected to each other. I want to be able to list all options a player has available for this room.
For example, Room A is connected east to B, and B is connected west to A, south to C, north to D and so forth.
What data structure should I use or how should I implement this as efficiently as possible?
The first thing to decide is what constitutes a valid direction: is it from a fixed list or can it be freeform text? The simplest solution is to have the four cardinal directions. Some have suggested doing this as an int array. That might be a valid solution in C/C++/C# (enums in all of them are just int constants) but there is no reason to do it in Java.
In Java you can use a (typesafe) enum—which incidentally can have state and behaviour—and use an
EnumMap, which is highly efficient. Internally it’s just an array indexed by enum ordinal value. You might argue what’s the difference between that and an int array? The answer is that the int array insideEnumMapis an internal implementation detail for a typesafe random access collection.If you allow freeform text for the exit direction, your structure will look something like this:
I don’t recommend this however. I recommend enumerating possible directions:
which you then store with:
That gives you type-safety, performance and extensibility.
The first way to think about this is as a Map:
where the key is a freeform direction (north, east, south, etc).
Next question: what is an Exit? In the simplest case, an Exit is simply what Room you end up in but then you start asking all sorts of questions like:
It is necessary to consider the interface for a text adventure game. A player types in commands in the following form:
That’s one possibility at least. Examples would include:
So the above covers a fairly comprehensive set of behaviour. The point of all this is:
so:
(and there will no doubt be behaviour associated with those instances) and:
GameObjects may also have other state such as whether they can be seen or not. Interestingly, the Direction enum instances are also arguably Commands, which again changes the abstraction.
So hopefully that should help point you in the right direction. There is no “right” answer for the abstraction because it all depends on what you need to model and support. This should hopefully give you a starting point however.