Question

I'm writing a Text Adventure game for a Java programming class. I'm setting up the rooms with a parent abstract room class that each room will inherit from and configure.

For exits, a room will just invoke an .addExit() method and pass it an exit object. The game should have only one instance of every room. The exit object should have a target field pointing to one of the game's rooms that gets initialized in the constructor.

My problem is I don't know how to pass the exit constructor a pre-existing room reference and not a new room object. The way I see it, there are two possible ways:

  1. Directly pass the exit constructor a reference to the room instance.
  2. Have a static class that keeps track of all the room instances and has methods that returns an instance from string names or class etc.
    The exit object's constructor is then passed a way to identify the target room, say a unique string name, which the object constructor then uses to call one of the static class's methods that return room instances.

I'm not sure which is the best option, how to implement either option, or if there's a better way altogether.

Was it helpful?

Solution

I don't think having a separate class for each room is a good idea. You're probably better off with a single Room class, where each instance represents a separate room. (I know MUDs were coded this way, but even there you had "virtuals")

But apart from that, the question is: is Exit a property of the room or is it something that can and should be managed separately?

The answer depends on what exactly you want to do with those Exits. If, for example you want to enforce bidirectional exits (that is, if there's an exit from room A to B, there should be one from B to A), a separate exit management class might be appropriate. But if you need nothing more than to be able to list all the exits in a room, then move to another through one of them, they can be properties of Room.

If you don't know in advance, start with the simple (exits are added to each room separately), and if it doesn't work, you can always switch to a more complex solution.

OTHER TIPS

You are overcomplicating this

Here is an example of how you can do this


    public abstract static class Room {
        List exits = new ArrayList();
        public void addExit(Room r) {
           exits.add(r);
        }
    }

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top