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

In the part 2 of this tutorial series, we added the ability to see and explore the world around us. The only problem was that we were strictly a viewer, and had no ability to interact with it in any way. This meant, for example, that if a door was shut we couldn’t open it to get any further.

This article is going to change this, giving us the ability to open and close doors, and to chat with other players in the same world. At the same time, we are going to gain the ability to see changes that other people make to the world around us, making everything feel like an immersive experience.

The end result will be something like this:

Demo of app

Communicating with other players

We are going to add two different forms of communication with other players – speaking and shouting. Speaking will be heard by anyone in the same room, whilst shouting will be heard by anyone in the entire game world.

Actual RPGs will give a huge variety more choice than this, including whispering to specific players, talker channels for guild chat, and emotes to express actions. This is beyond the scope of this article, but the concepts are all the same.

In order to support this, we are going to add two new mutations to our GraphQL server – speak and shout.

Firstly, we need to be able to broadcast messages to Pusher from our GraphQL API. Update pusher.js in the backend project to change the exports as follows:

    module.exports = {
        router: router,
        pusher: pusher
    };

And then update the app.js in the backend so that the imports are:

    var pusher = require('./routes/pusher').router;

Now, we can make use of this in our GraphQL API. Next, we need to add a couple of mutations:

    speak(room: ID!, sessionId: ID!, message: String!): String
    shout(room: ID!, sessionId: ID!, message: String!): String

In both cases, we are taking the ID of the room that the player is in, and of the player that is speaking/shouting. We also take the message that they are saying. The GraphQL return value is a simple String, purely because we’ve got to return something.

Next, implement these mutations in our Mutation resolver:

    speak: (_, { room, sessionId, message }) => {
        pusher.trigger('presence-room-' + room, 'speak', {
            user: users.getUser(sessionId),
            message: message
          }, sessionId);
          return "Success";
    },
    shout: (_, { room, sessionId, message }) => {
        pusher.trigger('global-events', 'shout', {
            room: room,
            user: users.getUser(sessionId),
            message: message
          }, sessionId);
          return "Success";
    }

Note that we provide the sessionId as the third parameter to these calls. That simply ensures that the user that triggered the events doesn’t also receive a copy of them – since that will be handled differently.

And finally, we need a new import for the Pusher client. This is simply:

    const pusher = require('./pusher').pusher;

Once all of this is done, we can start the server up and use our GraphiQL interface to test it. You will need a valid Session ID which can be captured from the Developer Tools in your browser by logging in to the Frontend, and you can see the broadcast messages using the Pusher Debug Console:

screenshot of debug console

We now need to be able to make use of this functionality. This means that we need to trigger these from our UI, and then be able to display messages received in response from them.

Firstly, let’s refactor our ability to add messages to the message log so that we can re-use it. Let’s add a new method to Game.js:

    _addMessage(message) {
        const messages = this.state.messages;
        messages.unshift({
            timestamp: new Date(),
            message: message
        });
        this.setState({
            messages
        });
    }

Then we can make use of it, initially from failing to exit a room – which we did in the last article. Update _onExitRoom as follows:

    if (result.data.exitRoom.reason === 'DOOR_CLOSED') {
        this._addMessage("That door is closed!");
    }

Next, we’ll add in some command handling. This is using the text input that we created right at the start. Firstly, we need to update that control to be able to submit commands. This is easiest done by wrapping it in an HTML form – they automatically submit on pressing Enter – and handle the form submission. Update the render method as follows:

    <form onSubmit={this._handleCommand}>
        <input type="text" className="form-control" placeholder="Enter command" ref={(input) => { this.commandInput = input; }} />
    </form>

To do this more correctly would involve creating a new React component to represent the command input. However, for the purposes of this tutorial, the above is adequate.

The use of the ref parameter makes it possible to refer to our input field, which we will see soon.

We now need to be able to actually handle the commands. This is done by adding a new method and then binding it to the correct context. First, add the new method:

    _onCommand(e) {
        e.preventDefault();
        const command = this.commandInput.value;
        this.commandInput.value = "";
        if (command.startsWith("/shout ")) {
            const shout = command.substring(7);
            this._addMessage(`You shout "${shout}"`);
        } else {
            this._addMessage(`You say "${command}"`);
        }
    }

This makes use of our _addMessage method that we’ve just factored out. It checks if the input command starts with the string “/shout”, and either shouts what follows that or else says the entire string.

Finally, we need to bind this to the correct context. This is done by adding the following line to our constructor:

    this._handleCommand = this._onCommand.bind(this);

At this point, we can use these commands successfully.

use commands

However, this doesn’t yet let anyone else hear us. For that, we need to trigger our mutations and then handle the events from Pusher when they are received.

Firstly, we need to define the mutations that we’re going to call. Add these to the top of Game.js:

    const SPEAK_MUTATION = gql`mutation($room:ID!, $session:ID!, $message: String!) {
        speak(room: $room, sessionId: $session, message: $message)
    }`
    const SHOUT_MUTATION = gql`mutation($room:ID!, $session:ID!, $message: String!) {
        shout(room: $room, sessionId: $session, message: $message)
    }`

Then we need to trigger these. Update the _onCommand method as follows:

    _onCommand(e) {
        e.preventDefault();
        const { room } = this.state;
        const command = this.commandInput.value;
        this.commandInput.value = "";
        if (command.startsWith("/shout ")) {
            const shout = command.substring(7);
            graphqlClient.mutate({
                mutation: SHOUT_MUTATION,
                variables: {
                    room: room,
                    session: pusher.connection.socket_id,
                    message: shout
                }
            }).then((result) => {
                this._addMessage(`You shout "${shout}"`);
            });
        } else {
            graphqlClient.mutate({
                mutation: SPEAK_MUTATION,
                variables: {
                    room: room,
                    session: pusher.connection.socket_id,
                    message: command
                }
            }).then((result) => {
                this._addMessage(`You say "${command}"`);
            });
        }
    }

This will call the appropriate GraphQL mutation based on our command, and then add the message to our message log in response to it returning. This way, we get to add the output at the same time as other players hear it. If, at this point, you try speaking or shouting then you can see the events appear in the Pusher Dashboard.

Add the following new methods to Game.js:

    _receiveShout(data) {
        const { room } = this.state;
        if (room === data.room) {
            this._addMessage(`${data.user.name} shouts "${data.message}"`);
        } else {
            this._addMessage(`Somebody shouts "${data.message}"`);
        }
    }
    _receiveSpeak(data) {
        this._addMessage(`${data.user.name} says "${data.message}"`);
    }

These are used to handle when we receive an event indicating a shout or a speak. Now we simply need to bind to the appropriate events. Update the constructor as follows:

    const channel = pusher.subscribe('presence-room-start');
    channel.bind('pusher:subscription_succeeded', function() {
        channel.bind('speak', function(data) { this._receiveSpeak(data); }.bind(this));
    }.bind(this));

    const globalChannel = pusher.subscribe('global-events');
    globalChannel.bind('pusher:subscription_succeeded', function() {
        globalChannel.bind('shout', function(data) { this._receiveShout(data); }.bind(this));
    }.bind(this));

And then update the _onExitRoom function:

    const channel = pusher.subscribe(`presence-room-${roomName}`);
    channel.bind('pusher:subscription_succeeded', function() {
        channel.bind('speak', function(data) { this._receiveSpeak(data); }.bind(this));
    }.bind(this));

At this point, we can hear speaking from anyone in the same room and shouts from anyone in the entire game. If the shouter is in the same room, we can see who it was, but if not then we just get a vague description:

demo commands fully working

Opening and closing doors

The next thing we want to be able to do is to interact with the world in some manner. We are going to implement this by allowing characters to open and close doors, and to see when the doors are opened and closed by others.

We already have mutations available to actually open and close the doors. We just don’t have them hooked up to the UI in any way at present.

Firstly, let’s display the actions in the UI. Update RoomDescription.js so that the render method in the RoomDescription class has the following:

    const exits = room.exits.map((exit) => {
        let doorAction;
        if (exit.door.state === "closed") {
            doorAction = (
                <span>(<a href="#" onClick={(e) => this._openDoor(e, exit)}>Open</a>)</span>
            );
        } else if (exit.door.state === "open") {
            doorAction = (
                <span>(<a href="#" onClick={(e) => this._closeDoor(e, exit)}>Close</a>)</span>
            );
        }
        return (
         <li className="list-inline-item">
             <a href="#" onClick={(e) => this._handleExitRoom(e, exit)}>
                 {exit.description}
             </a>
             { doorAction }
         </li>
        );
     });

Then we need to trigger the mutations. Add the following to the top of RoomDescription.js:

    const OPEN_DOOR_MUTATION = gql`mutation($room:ID!, $door:ID!) {
        openDoor(room:$room, door:$door) {
            state
        }
    }`
    const CLOSE_DOOR_MUTATION = gql`mutation($room:ID!, $door:ID!) {
        closeDoor(room:$room, door:$door) {
            state
        }
    }`

And define our _openDoor and _closeDoor methods in the RoomDescription class:

    _openDoor(e, exit) {
        e.preventDefault();
        this.props.openDoorHandler(exit.name);
    }
    _closeDoor(e, exit) {
        e.preventDefault();
        this.props.closeDoorHandler(exit.name);
    }

Finally, we need to provide these two handlers. They come from the RoomDescriptionWrapper class, as follows:

    _onOpenDoor(door) {
        const { room } = this.props;
        graphqlClient.mutate({
            mutation: OPEN_DOOR_MUTATION,
            variables: {
                room: room,
                door: door
            }
        }).then(() => {
            this._getRoomDetails(room);
        });
    }
    _onCloseDoor(door) {
        const { room } = this.props;
        graphqlClient.mutate({
            mutation: CLOSE_DOOR_MUTATION,
            variables: {
                room: room,
                door: door
            }
        }).then(() => {
            this._getRoomDetails(room);
        });
    }

And get wired in by updating the render method in the RoomDescriptionWrapper as follows:

    return <RoomDescription room={ room } 
        exitRoomHandler={this.props.exitRoomHandler} 
        openDoorHandler={this._onOpenDoor.bind(this)} 
        closeDoorHandler={this._onCloseDoor.bind(this)} />

This will work, but you won’t see anything happen. This is because the Apollo GraphQL Client that we are using automatically caches the response from queries, so if the exact same query is made then the network requests aren’t necessary. We need to clear this cache when fetching room data so that we get the fresh state of the room. This is done by updating the _getRoomDetails method to add the following right at the top:

    graphqlClient.resetStore();

Now, we can go and open and close doors as much as we wish.

The only problem is that we won’t see when somebody else opens or closes a door without leaving and re-entering the room. Let’s fix that again by using Pusher to send updates whenever the door state is changed. This is a subtly different case to above because we need to notify the room on both sides of the door that the door has changed, since they are both affected.

In routes/graphql.js in the backend project, add a new method to broadcast an indication that the state of the door has changed:

    function broadcastRoomUpdatesForDoor(doorName) {
        const targetRoomName = Object.keys(worldData.rooms)
            .filter(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;
            })
            .forEach(roomName => {
                pusher.trigger('presence-room-' + roomName, 'updated', {});
            });
    }

This iterates over every room in our World data finds each room that has the named door as an exit, and then sends a Pusher event on the Presence channel for that room to indicate that the room has been updated. We don’t need a payload because our event details are simply that the room that this channel is for has been updated in some way.

We then simply need to call this from the openDoor and closeDoor handlers:

    broadcastRoomUpdatesForDoor(doorName);

Now, all we need to do is update the UI every time we receive one of these events.

Add the following import to RoomDescription.js in the frontend:

    import pusher from './pusher';

Then add the following method to the RoomDescriptionWrapper class:

    _bindToUpdates(room) {
        const channel = pusher.channel(`presence-room-${room}`);
        channel.bind('pusher:subscription_succeeded', function() {
            channel.bind('updated', function() { this._getRoomDetails(room); }.bind(this));
        }.bind(this));
    }

We never need to worry about unbinding this event because the entire channel subscription is removed when we change rooms.

Next, call this from both the componentDidMount and componentWillReceiveProps functions:

    this._bindToUpdates(room);

And now we have the ability to see whenever the state of any doors in the current room change, regardless of who caused the change to happen.

The end result of all this is something like the following:

demo doors

Conclusion

Throughout this series, we have built a small online world, complete with multiple characters able to explore and interact with it, and able to communicate with each other. This is the very beginning of your very own online roleplaying game, and it doesn’t take a lot of imagination to see how this can be expanded to make something much more enticing for players.

As before, the full source code for this can be found on GitHub. Why not try expanding the world? Adding NPCs in to interact with, or combat, or items, or a whole vast array of other commonly found RPG elements. Or, instead, think up something new and exciting to do instead. We look forward to whatever you come up with.