This tutorial will expand on that by giving some structure using Graphql and React, allowing our characters to explore the world and to see the other characters as they come and go. Our world is going to be a fairly traditional Dungeons and Dragons dungeon, with a number of rooms and corridors that players can wander around in. The end result will look something like this:

Dungeon Map, generated by https://donjon.bin.sh/fantasy/dungeon/

This article is part of Build an online text RPG with GraphQL and React course.

In the previous article, we created a basic game that allows players to create a character and join into a shared world. Unfortunately, at this point, we don’t have any actual structure to the world. Instead, all characters are simply in the same space and can see each other but nothing else.

Of course, the players themselves will never see this full map – unless they draw it themselves. Instead, they will see descriptions of the room that they are currently in, and a system to allow them to move from room to room and explore the world around them.

Room Definitions

We are building our game using the concept of “Rooms”, where a Room is one area of the game world. In our map, this means that each individual room and each corridor will become one game Room, and will have appropriate exits onto the other rooms. We also need to keep track of the doors between rooms, since these are in various states – either open or closed – and are shared between rooms. For example, there is a door between rooms “11” and “14” at the bottom left of the map. This is the same door from both sides, and if it is opened from one side it should be reflected on the other side.

For the sake of ease, we will represent our world as a single JSON data file that we can load on server startup. In reality, this would be better off in a database, which would then allow for changes to be made to the world whilst the server is running, and for multiple server deployments to work from the same data. That is overkill for this tutorial.

Create a new file in the root of your backend project called world.json. The actual contents for the full map would be too long to display here but will look something like this:

    {
      "doors": {
        "enter": {
          "state": "arch"
        },
        "room-1-corridor-1-8": {
          "state": "closed"
        }
      },
      "rooms": {
        "start": {
          "description": "You stand at the entrance to The Crypts of Kas the Betrayer. Before you is a large stone archway leading into a long room",
          "exits": {
            "south": {
              "name": "Enter",
              "door": "enter"
            }
          }
        },
        "room-1": {
          "description": "A shallow pit lies in the north side of the room. The north and west walls are covered with cracks",
          "exits": {
            "north": {
              "name": "Exit",
              "door": "enter"
            },
            "south": {
              "name": "South",
              "door": "room-1-corridor-1-8"
            }
          }
        },
        "corridor-1-8": {
          "description": "The corridor has flagstone flooring and reinforced masonry walls.",
          "exits": {
            "north": {
              "name": "North",
              "door": "room-1-corridor-1-8"
            }
          }
        }
      }
    }

This file will be used to power the entire game world and lets us work out everything we need to in order for our characters to navigate the map. We have a special room called “start” that characters will start in, and then from that point on navigation is done by following “exits” from one room to the next.

Next, we need to be able to access this data. In the previous article, we created a GraphQL Service to act as the API for the backend service. We will use this to expose our world data for the client to access.

Inside routes/graphql.js, we need to expand our GraphQL Schema to allow the world data to be accessed. Add the following into the GraphqlSchema string:

    type Door {
        name: ID!
        state: String!
    }
    type Exit {
        name: ID!
        description: String!
        door: Door!
    }
    type Room {
        name: ID!
        description: String!
        exits: [Exit!]!
    }
    type Query {
        version: String
        room(name: ID!) : Room
    }

Amongst other things, this defines a new top-level query field that allows us to get the details of any Room from its name. You’ll also notice that there’s no way of using this structure to navigate the world – you can see how to get out of any Room but not where the Exit will take you. This will be rectified later on.

Now we need to actually implement this structure. Firstly we need access to our World data. This is a simple require statement to load our JSON file:

    const worldData = require('../world.json');

Then we need the actual resolvers for our data. We do this by expanding the resolvers object as follows:

        Query: {
            version: () => '1.0.0',
            room: (_, { name }) => {
                const room = worldData.rooms[name];
                if (room) {
                    const roomExits = room.exits || {};
                    const exits = Object.keys(roomExits)
                        .map((exitName) => {
                            const exit = roomExits[exitName];
                            return {
                                name: exitName,
                                description: exit.name,
                                doorName: exit.door
                            };
                        });
                    return {
                        name,
                        description: room.description,
                        exits
                    }
                } else {
                    return null;
                }
            }
        },
        Exit: {
            door: ({ doorName }) => {
                const door = worldData.doors[doorName];
                return {
                    name: doorName,
                    state: door.state
                };
            }
        },

Here we have two fields that we are resolving. The room field on the top-level Query object will look up a Room from the provided name and, if it was found, return the details of that room, including all of the Exits. For each Exit, it only returns the name of the Door rather than the Door details. Separate to that, we define the door field on the Exit object. This takes the name of the Door, looks it up and returns the details of that specific Door.

We can then test this out in our GraphiQL UI:

The above query gets all of the details of our “start” room, and the result shows exactly what we would expect from it.

Navigating the World

Now that we have the ability to see where we are in the world, we need to be able to move about it. This is a two-fold process. The main thing that we want to do is move from one room to the next using an exit. The second thing, however, is that we want to be able to open and close doors. Any character can open and close any door, but a character can only walk through an open door.

These are going to be handled as Mutations – because we are changing something about the world. To this end, we need to update our GraphqlSchema string as follows:

    type ExitRoomError {
        reason: ID!
    }

    union ExitRoomResult = Room | ExitRoomError

    type Mutation {
        signin(sessionId: ID!, name: String!, race: String!, class: String!): String
        openDoor(room: ID!, exit: ID!): Door!
        closeDoor(room: ID!, exit: ID!): Door!
        exitRoom(room: ID!, exit: ID!): ExitRoomResult!
    }

This defined three new mutations that can be called:

  • openDoor – This will open the door defined by the named exit of the named room. If the door is not currently closed then no action will occur.
  • closeDoor – This will close the door defined by the named exit of the named room. If the door is not currently open then no action will occur.
  • exitRoom – This will follow the exit defined. This might fail, for example, if the door is closed. As such, we return either a success result – the new Room, or a failure result – the reason why exiting the room failed.

These just need implementing now. This is done by adding the following to the Mutation field of the resolvers object:

            openDoor: (_, { room, exit }) => {
                const roomData = worldData.rooms[room];
                const exitData = roomData.exits[exit];
                const doorName = exitData.door;
                const doorData = worldData.doors[doorName];
                if (doorData.state === 'closed') {
                    doorData.state = 'open';
                }
                return {
                    name: doorName,
                    state: doorData.state
                };
            },
            closeDoor: (_, { room, exit }) => {
                const roomData = worldData.rooms[room];
                const exitData = roomData.exits[exit];
                const doorName = exitData.door;
                const doorData = worldData.doors[doorName];
                if (doorData.state === 'open') {
                    doorData.state = 'closed';
                }
                return {
                    name: doorName,
                    state: doorData.state
                };
            },
            exitRoom: (_, { room, exit }) => {
                const roomData = worldData.rooms[room];
                const exitData = roomData.exits[exit];
                const doorName = exitData.door;
                const doorData = worldData.doors[doorName];
                if (doorData.state === 'closed') {
                    return {
                        reason: 'DOOR_CLOSED'
                    };
                }
                const targetRoomName = Object.keys(worldData.rooms)
                    .filter(roomName => room !== roomName)
                    .find(roomName => {
                        const roomDetails = worldData.rooms[roomName];
                        const hasDoor = Object.keys(roomDetails.exits)
                            .map(exitName => roomDetails.exits[exitName])
                            .map(exitDetails => exitDetails.door)
                            .includes(doorName);
                        return hasDoor;
                    });
                const targetRoom = worldData.rooms[targetRoomName];
                const roomExits = targetRoom.exits || {};
                const exits = Object.keys(roomExits)
                    .map((exitName) => {
                        const exit = roomExits[exitName];
                        return {
                            name: exitName,
                            description: exit.name,
                            doorName: exit.door
                        };
                    });
                return {
                    name: targetRoomName,
                    description: targetRoom.description,
                    exits
                }
            }

Note that the result of exitRoom is a union, meaning that the actual value could be one of several types. In order to make this work, the GraphQL Server needs to know exactly which type it is. This is done by adding a special resolver method called __resolveType to the union type, as follows:

        ExitRoomResult: {
            __resolveType: (obj) => {
                if (obj.reason) {
                    return 'ExitRoomError';
                } else {
                    return 'Room';
                }
            }
        }

At this point, we can open and close doors, and we can exit one room into the next:

💡 Note that the query fields are more complicated to account for the fact that we could get one of several types back. This is discussed in the GraphQL documentation here.

Displaying World Details

Once our backend supports returning the details of the world and allows us to navigate from one room to another, we need to be able to actually show this to the player. This will involve displaying the details of the current room, the exits that are available, and ensuring that the list of characters in the room is kept correct.

Firstly, we want a component to render the room description. This will go into src/RoomDescription.js. Firstly we need some imports and a query to execute:

    import React, { Component } from 'react';
    import graphqlClient from './graphql';
    import gql from 'graphql-tag';

    const ROOM_QUERY_MUTATION = gql`query($room:ID!) {
        room(name:$room) {
          description
          exits {
            name
            description
            door {
              state
            }
          }
        }
      }`;

This query will be called with a single parameter – the name of the room to get the details of – and will return those details. Next, we want an actual component that renders the details:

    class RoomDescription extends Component {
        constructor(props) {
            super(props);
            this._handleExitRoom = this._onExitRoom.bind(this);
        }
        _onExitRoom(e, exit) {
            e.preventDefault();
            this.props.exitRoomHandler(exit.name);
        }
        render() {
            const { room } = this.props;
            const exits = room.exits.map((exit) =>
                <li className="list-inline-item">
                    <a href="#" onClick={(e) => this._handleExitRoom(e, exit)}>
                        {exit.description}
                    </a>
                </li>
            );
            return (
                <div>
                    <div>
                        { room.description }
                    </div>
                    <br />
                    <h5>Exits</h5>
                    <ul className="list-inline">
                        { exits }
                    </ul>
                </div>
            );
        }
    }

When this is rendered, this is provided the room details as returned by the GraphQL Query and will render them. It displays the room description, and then the list of exits as clickable links. Clicking on one of these will trigger a provided callback that will, soon, actually move through that exit.

Finally, we are going to write a special Wrapper component that makes the GraphQL call and, when we have a response, renders the above component with the details:

    class RoomDescriptionWrapper extends Component {
        constructor(props) {
            super(props);
            this.state = {};
        }
        componentDidMount() {
            const { room } = this.props;
            this._getRoomDetails(room);
        }
        componentWillReceiveProps(nextProps) {
            const { room } = nextProps;
            this._getRoomDetails(room);
        }
        _getRoomDetails(room) {
            graphqlClient.query({
                query: ROOM_QUERY_MUTATION,
                variables: {
                    room: room
                }
            }).then((roomData) => {
                this.setState({
                    room: roomData.data.room
                });
            });
        }
        render() {
            const { room } = this.state;
            if (room) {
                return <RoomDescription room={ room } exitRoomHandler={this.props.exitRoomHandler} />
            } else {
                return (
                    <div></div>
                );
            }
        }
    }

    export default RoomDescriptionWrapper;

Note that the API call is made in both componentDidMount – for when this is first rendered – and in componentWillReceiveProps – for when a new room name is provided instead.

This file exposes a single component that is rendered with the name of the room and the handler to call to move through an exit. It then retrieves the room details and displays those returned.

Next we need to make use of this component and actually show the room details. This is done in the file src/Game.js. Firstly we want some more imports:

    import RoomDescription from './RoomDescription';
    import graphqlClient from './graphql';
    import gql from 'graphql-tag';

And then a GraphQL Mutation to trigger when the exit is used:

    const EXIT_ROOM_MUTATION = gql`mutation($room:ID!, $exit:ID!) {
        exitRoom(room:$room, exit:$exit) {
          __typename
          ... on Room {
            name
          }
          ... on ExitRoomError {
            reason
          }
        }
      }`;

We now want to be able to call this mutation and update the component state as appropriate. We need a new method inside our Game component as follows:

        _onExitRoom(exit) {
            const { room } = this.state;
            graphqlClient.mutate({
                mutation: EXIT_ROOM_MUTATION,
                variables: {
                    room: room,
                    exit: exit
                }
            }).then((result) => {
                if (result.data.exitRoom["__typename"] === 'Room') {
                    const roomName = result.data.exitRoom.name;
                    pusher.unsubscribe(`presence-room-${room}`);
                    pusher.subscribe(`presence-room-${roomName}`);
                    this.setState({
                        room: roomName
                    });
                } else {
                    // Failure to leave the room is handled here
                }
            });
        }

And then bind the handler so that we can easily call it, by adding the following to the constructor:

            this._handleExitRoom = this._onExitRoom.bind(this);

The _onExitRoom will call our exitRoom mutation, and check the response. If we got a Room response then we have successfully used the exit, so we update the component state to reflect this and we then change the Pusher subscriptions from the old room to the new one.

Finally, we update the render method to make use of this information as follows:

    <div className="game-roomDescription">
        <RoomDescription room={ this.state.room } exitRoomHandler={this._handleExitRoom} />
    </div>

Once all of this is done, the room descriptions will display and the links will work to move between rooms:

However, you might notice that the Characters here list doesn’t correctly update as you move between rooms. This is because the component is not re-rendered and so the Pusher bindings are not correctly updated. We are going to take the easy option here and force the component to re-render instead of correctly managing the bindings. This is because there is no need to do better in this case, as we have no component state that we need to manage otherwise. This is done by updating the render method of the Game class again to contain the following:

    <CharacterList room={ this.state.room } key={this.state.room} />

The addition of the key prop is special to React, and it will cause the entire component to be re-rendered when it changes instead of simply being updated with new prop values.

Failing to move between rooms

On occasion, you might find that it’s not possible to move between rooms. For example, our “South” exit from our second room doesn’t work. This is because the API refuses to let you move through a closed door, so send back an error instead. What we need to do now is to display these errors to the player so that they can see what’s going on.

In order to do this we are going to create a message log component in order to display messages to the player and add an appropriate message to it when the door is closed.

Firstly, create a new component in Messages.js as follows:

    import React, { Component } from 'react';
    class Messages extends Component {
        render() {
            const messageRows = this.props.messages
                .map((message) => <li>{message.timestamp.toString()} - {message.message}</li>);
            return (
                <ul className="list-unstyled">
                    {messageRows}
                </ul>
            );
        }
    }
    export default Messages;

This simply takes in a list of messages – consisting of a timestamp and a string – and displays them in a list.

Then we need to display them. This is all done in Game.js. Firstly we need to ensure our new component is imported:

    import Messages from './Messages';

Next, add a new piece of state to store the messages. Update the constructor as follows:

    this.state = {
        room: 'start',
        messages: []
    };

Then update the render method to show the messages:

    <div className="game-messageLog">
        <Messages messages={this.state.messages} />
    </div>

Then we simply need to add a message whenever we fail to move through an exit. This is done by updating the response handler in the _onExitRoom method so that, when we fail to exit the room, a message is added to our state instead:

    if (result.data.exitRoom["__typename"] === 'Room') {
        const roomName = result.data.exitRoom.name;
        pusher.unsubscribe(`presence-room-${room}`);
        pusher.subscribe(`presence-room-${roomName}`);
        this.setState({
            room: roomName
        });
    } else {
        const messages = this.state.messages;
        if (result.data.exitRoom.reason === 'DOOR_CLOSED') {
            messages.unshift({
                timestamp: new Date(),
                message: "That door is closed!"
            });
        }
        this.setState({
            messages
        });
    }

When we try to use a closed door, we are now informed of this fact instead of being left with no idea what happened:

Note that we still can’t actually open this door from the UI. The API will let you do this if you want to use that to manually explore the world, but interacting with it is left for the next article.

Conclusion

This article has taken our initial setup, a game world where people can join and see each other, and extended it to give some depth to the world and to allow you to wander around and explore – at least as much as is possible without being able to affect anything. The full code for this article is available in GitHub.

In our next tutorial, we are going to make the game much more interactive, allowing characters to interact with both the world and each other, and giving realtime updates to all of this as it happens.