IN THIS ARTICLE

    Waving hand

    Good News! We’ve launched an all new Chat Resource Center.

    We recommend checking out our new Chat Resource Center, which includes overviews, tutorials, and design patterns for building and deploying mobile and web chat.

    Take me to the Chat Resource Center →

    Multiplayer game development

    Welcome to the first post of an extensive blog series where we’ll work together to create an entire multiplayer game with Javascript. The game we’re going to build is a multi-user card game called MemeWarz, a browser-based trading card game based on card games like Magic or Pokémon. All the cards are Internet memes, so you can finally put Doge up against Overly Attached Girlfriend in a fight.


    We’ve now covered both building a multiplayer game lobby with a chatroom and the different ways we can use matchmaking to connect two different users. Here’s what we’ve covered so far:

    This blog post is Part One of PubNub Developer Evangelist Ian Jennings‘s series on creating a multiplayer game with JavaScript.


    In the first section, we’ll learn how to build a multiplayer game lobby, complete with a list of online users, private chat, matchmaking, and the ability to challenge other players. In the second section, we’ll build the game server and client.

    So let’s get started!

    Multiplayer game development

    You’ll first need to sign up for a PubNub account. Once you sign up, you can get your unique PubNub keys in the PubNub Developer Portal. Once you have, clone the GitHub repository, and enter your unique PubNub keys on the PubNub initialization, for example:

    We’re going to begin by creating a simple chat room that users will enter when they first load the game. This allows users to talk to one another and meet new challengers. Want to see the end result? Check out the working chat demo here.

    A chatroom is the “Hello World” of realtime communication. It represents the ability for one client to send a message and for another to receive it; the most basic of realtime interaction.

    Include the Libraries

    In order to make our lives easy, we are going to include jQueryTwitter Bootstrap 3, and the PubNub Javascript SDK. PubNub will handle the multiplayer networking while jQuery and Bootstrap will provide lots of great utilities for our page styling and function.

    *This guide is intended to demonstrate Javascript patterns and will not dive into the details of either library. Examples will avoid using utilities specific to either library so that they may be removed or replaced easily.

    First, we’ll include jQuery, Bootstrap CSS and JS, and PubNub at the top of our HTML file.

    All of our examples will take place within the context of Codepen.io. If you would like to follow along, simply create a new pen.

    We’ll also set up a basic HTML structure for the chatroom:

    As you can see, we have a Boostrap panel, a heading, a place for our chat messages to go (#chat-output), and a form with an input where we can type our new chat messages (#chat-input).

    We’ll use the jQuery selector syntax to select the chat input and output elements. We then save them to variables we can use later.

    Declaring a variable with a $ before the name is a reminder the value is a jQuery object.

    Getting Started with PubNub

    Now we’re ready to connect the chat room to PubNub. First we need to initialize PubNub. The PubNub script we included in our HTML page creates a global variable called PUBNUBwhich contains the PubNub library.

    We create a new variable called pubnub and assign the response of PUBNUB.init() to it. This will give us a fully initialized PubNub object which can use to start communicating over the PubNub network.

    The subscribe_key allows us to receive messages from PubNub and the publish_keyallows us to send messages. Leaving either one out means the client won’t be able to complete either function. Because we want users to be able to read chat messages and write messages of their own, we include both keys.

    subscribe_key – This key allows the client access to a data channel on the PubNub network. All client or server side apps that will receive data from your application will need this key.

    publish_key – This key allows access to sending data to a data channel. You only need to supply this key to clients and servers that will send data to your application over the PubNub network. A read-only client for example would not need access to this key.

    For more information, take a look at our PubNub Data Streams JavaScript SDK documentation.

    We plug in ‘demo’ as the value for both keys. This tells PubNub to use the demo account, which gives us trial access to the full array of PubNub features. If you were to deploy this game into production, you would replace these keys with your own as provided in the PubNub account management

    We follow by defining a channel name. A channel is the same concept as a “room”. Some example of channels are IRC rooms, game servers, or a user’s Twitter stream. A channel represents a “stream” of data.

    Channels are a way of dividing up messages between clients. For example, you may have a ‘game-lobby-chat’ channel where every user can talk to one another, but you may also have a ‘john-joe’ channel that only includes messages relative to John Joe.

    Channels are created on the fly and can scale to millions of users making them very easy to use. When you create a PubNub powered application, clients and severs will communicate over a channel.

    In this example, all of our chat will happen over the same channel called ‘memewarz-lobby-demo’. We’ll define this channel name as a variable at the top of the file.

    Next, we set up a jQuery function to listen for when the #chat form is submitted. When that event is fired, we use pubnub.publish() to broadcast $input.val() to anyone listening on our channel.

    PubNub Data Streams

    The user can submit the #chat form by pressing the “send message” button or the “return” key while the form is in focus.

    The line $input.val(''); clears the value of the input field to represent that the message has been sent to the chat room. We also return false; so that we prevent sending a POST request by default which would start a new browser request.

    See Messages Being Broadcast in PubNub Developer Console

    We haven’t written any code to display new messages yet, but we can see the message being broadcast over the network with the PubNub Developer Console.

    PubNub Dev Console

    The PubNub console can be found here: www.pubnub.com/docs/console

    When we launch the console, notice that the publish and subscribe keys are automatically filled out as demo and demo.

    We need to enter our channel memewarz-lobby-demo into console and click “Connect” to see messages being broadcast.

    Now, when we submit the chat form we can see the message being sent over the network.

    Multiplayer game development

    Now let’s subscribe to the channel so we can receive messages in our app. Similarly to pubnub.publish(), we’ll use the pubnub.subscribe() to watch for new messages.

    When we get a message, message: function(text) {} is called.

    Each message has it’s HTML stripped away and is appended as a .list-group-item to the $output element we defined earlier.This gives us a “chatroom” style for our output. We also scroll the chat output to the bottom so the user doesn’t miss new messages.

    Realtime Chat

    Now, when you enter text into the input field and click “Send Message” you should see the message appear within the chat output.

    Realtime Chat

    Demo – See It In Action!

    The full working chat demo can be seen below. Open the demo in two different browser windows to see how messages are replicated across multiple clients.

    See the Pen Memewarz – Basic Chat by Ian Jennings (@ianjennings) on CodePen.5248

    Stay tuned for the upcoming blogs as we’ll continue walking you through building a JavaScript multiplayer game with PubNub.

    Try PubNub today!

    Build realtime applications that perform reliably and securely, at global scale.
    Try Our APIs
    Try PubNub today!
    More From PubNub

    Footer Html for Blog Page