Home > Articles

Creating Games with Google+ Hangouts

Google+ Hangouts provide a means for up to 10 people to communicate using video and text chat. Hangouts also have a rich JavaScript API that permits developers to create apps and extensions for their users to collaborate, ranging from enterprise applications to games. James Williams, author of Learning HTML5 Game Programming: A Hands-on Guide to Building Online Games Using Canvas, SVG, and WebGL, shows how to use the Google+ Hangout API to create a game.
Like this article? We recommend

Exploring the API

If you're familiar with Google gadgets or you've created widgets for Google's OpenSocial platform, you'll feel right at home with the Google+ Hangouts API. Every Google+ Hangout extension or application begins with a gadget XML file.

The most basic gadget file is as follows:

<?xml version="1.0" encoding="UTF-8" ?>
<Module>
  <ModulePrefs title="Your App Name">
    <Require feature="rpc"/>
    <Require feature="views"/>
  </ModulePrefs>
  <Content type="html">
    <![CDATA[
      <script src="//talkgadget.google.com/hangouts/_/api/hangout.js?v=1.2"></script>
      <!-- Application HTML -->
    ]]>
  </Content>
</Module>

A gadget file consists of two parts:

  • The ModulePrefs section (short for module preferences) specifies metadata about the application, such as its title and the features it will use. This section can also include other metadata, such as the author, a description, and a thumbnail.
  • The rpc feature enables your application to make remote procedure calls to the Google+ APIs. This is the only required feature.
  • The views feature (optional) allows you to pass information directly to the app at startup.
  • The Content section contains the HTML code that drives your application.

Basic Blackjack Details

Blackjack is a multiplayer casino card game where the player's goal is to have the numeric values of the cards in his hand total as close to 21 as possible—without going over that number (busting). After all bets are placed, the dealer deals two cards, one face down and one face up, to himself and each of the players. Aces are valued at 1 or 11, and face cards are valued at 10. Each player has the opportunity to hit (add cards to his hand) multiple times, thereby improving his chances of winning the hand, or choosing to stand (stay with the current cards). After all players are satisfied with their hands or can no longer play a hand, in the event that their hand total exceeds 21, the dealer's face-down card is revealed, and each player's hand is evaluated. The hand that is closest to 21 points wins. (Each player competes with only the dealer—not with the other players.)

Several other blackjack elements exist in a casino game, such as double-down, splits, and so on, but they aren't essential to the game we're building today, so I'll leave them as an exercise for you to explore.

Most blackjack games have general strategy suggestions for when players should hit or stand. A dealer might have additional restrictions specifying when he should stand on a particular hand. The code that evaluates player hands and gives suggestions on whether they should hit, stay, or double-down lives in the Evaluator.js file.

Cards for Use in the Game

Much of the core code to draw and interact with the cards comes from the War card game I created with Amino in a previous article. I had to tweak the presentation layer to use HTML5 Canvas instead of Amino, but that wasn't very difficult.

Managing Game State

Google+ Hangouts have a shared state in the gapi.hangout.data namespace that all participants can access and modify. The state object closely resembles a map object. The most important functions for our needs are setValue, getValue, and clearValue, which respectively set, get, and clear a key-value pair from the state object; and getState, which retrieves the complete object. In addition to the state, which persists all changes, you can send messages to all participants.

The code below demonstrates the creation and saving of a card deck to the hangout state object:

BlackJackGame.prototype.resetDeck = function(numDecks) {
  if (numDecks == undefined)
    numDecks = 2;
  groupDeck = new Deck(numDecks);
  gapi.hangout.data.setValue('numDecks', ''+numDecks);
  gapi.hangout.data.setValue('deck', groupDeck.toString());
}

An application that will be sending few updates can function just fine with the functions we've discussed previously. One thing that makes them inadequate, however, is if you have an application like ours that updates the UI whenever the state changes. Imagine the very likely case of a player choosing to hit (add another card to his hand). Several actions take place:

  1. A card is removed from the deck.
  2. The card is added to the player's hand.
  3. If the player busts (his card total exceeds 21), doubles-down, or stays, play transitions to the next player.

In this case, it's important that all actions take place before updating the game state and sending to other clients. Otherwise, depending on latency, you could end up in a state where play transitions to the next player and the deck has one less card, but the dealt card doesn't appear in the player's hand. When multiple changes need to happen at approximately the same time, we should use submitDelta rather than a series of setValue commands:

BlackJackGame.prototype.newRound = function() {
  var updates = {};
  updates['gameState'] = 'DEAL';
  this.players = this.loadPlayerData();
  _.each(this.players, function(player) {
    player.clearCards();
    updates[player.id] = player.toString();
  });

  this.dealer.clearCards();
  updates['dealer'] = this.dealer.toString();
  this.evaluator.setDealer(this.dealer.getCurrentHand());

  game.updateGameBoard();
  gapi.hangout.data.submitDelta(updates);
}

In the snippet above, if the hangout is full and all participants are playing the game, we need to execute twelve updates to the hangout state. It's much more efficient to batch all the changes into one change set to be evaluated all at once. submitDelta can take a second parameter, an array of values to remove from the hangout state.

You can explore the API further by navigating to the Google+ Hangouts API developers page.

Responding to Events

Several events are fired when the state is updated or a message is sent, onStateChanged and onMessageReceived. We can add or remove an event handler by using the corresponding function:

gapi.hangout.data.onStateChanged.add(window.game.stateUpdated);
gapi.hangout.data.onStateChanged.remove(window.game.stateUpdated);

The event that's fired contains the current state object, the keys that were added and removed, and the state metadata. In the following snippet, we make use of the addedKeys property to determine whether there was a gameState transition and how to respond appropriately:

BlackJackGame.prototype.stateUpdated = function(evt) {
  var gameHost = game.getGameHost();
  var currentPlayer = gapi.hangout.getLocalParticipantId();
  if (game.isGameHost()) {
    // Only run on host
    // Manage game state and evaluators
    game.gameState = evt.state.gameState;
    if (game.gameState != undefined) {
      if (game.gameState.substr(0,5) == "DPLAY") {
        game.gameState = 'DPLAY';
        game.playDealerHand();
      } else if (game.gameState == 'EVAL') {
         // Evaluate game hands and do payouts
        var hand = game.loadState('dealer')[0];
        var handStatus = game.evaluator.evaluate(hand);
        game.evaluateHands(handStatus);
      } else {
        game.players = game.loadPlayerData();
        game.updateGameBoard();
      }
    }
  } else {
    game.players = game.loadPlayerData();
    game.updateGameBoard();

  }
}

onApiReady Event Handler

The onApiReady event handler is our main entry point into the application. It creates our BlackJackGame object and its associated properties, and then attaches our events to their associated handlers. The full onApiReady handler is listed below:

gapi.hangout.onApiReady.add(function(event) {
  console.log('gapi loaded');
  if(event.isApiReady) {
    window.game = new BlackJackGame();
    window.game.players = window.game.loadPlayerData();
    window.game.deck = new Deck(1, window.game.ctx);

    // check for saved deck
    if (gapi.hangout.data.getValue('deck') == undefined) {
      game.resetDeck(2);
    }

    gapi.hangout.data.onStateChanged.add(window.game.stateUpdated);
    gapi.hangout.onAppVisible.add(window.game.participantEnabledApp);
    gapi.hangout.onParticipantsEnabled.add(window.game.participantEnabledApp);
    gapi.hangout.onEnabledParticipantsChanged.add(window.game.participantsChanged);
  }
});

Adding Overlays

In addition to setting a video stream on or off, the Hangout API allows you to control your experience further by overlaying images on an individual video stream. You can see this feature at work if you've played with the Google Effects extension that lets you select crazy accessories to attach to your face.

In Blackjack, we won't use dynamic facial-tracking, as in the Google Effects extension; instead, we'll use an image with a static position. A small gray dot on a player's video stream will indicate that it's his or her turn.

First, we need to create an ImageResource by passing a publicly accessible URL to the createImageResource function in the gapi.hangout.av.effects namespace. We then call the createOverlay function on that object to instantiate the overlay that we'll superimpose on the video stream. You either pass a map containing the specifications of the new overlay, or apply them one at a time using set* functions.

BlackJackGame.prototype.createTurnIndicator = function () {
  var url = "http://example.com/images/button.png";
  var temp = gapi.hangout.av.effects.createImageResource(url);
  this.overlay = temp.createOverlay({
    position:{x:-0.35, y:0.25},
    scale:{
      magnitude:0.25, reference:gapi.hangout.av.effects.ScaleReference.WIDTH
    }});
};

In the snippet above, we first set the image resource to scale itself to 25% of the stream size, based on the width. Next, we set the dot to appear in the lower-right corner of the video stream. The position values for x and y range from -1 to 1 with (0,0) at the center of the stream, positive y toward the bottom of the stream, and positive x toward the viewer's left.

Drawing the Gameboard

Developer Advocate Johnathan Beri notes that the minimum dimensions for a hangout app are 940 × 465, while an extension has minimum dimensions of 300 × 465. The best course of action is to assume that the user may resize the window at will, and make the design responsive. Doing that is outside the scope of this article, so I'll leave it as a exercise for you to accommodate users who are viewing the hangout on a large screen; you should use responsive design to support all window sizes.

Deploying the App

To make your application available to the public, you'll need to do the following:

  1. Create and verify a Chrome Web Store account.
  2. Add application icons in various sizes.
  3. Add URLs for your application's Privacy Policy, Support, and Terms of Service pages.
  4. Create an OAuth 2.0 client ID for the application.

For more details, read more about publishing Hangout apps and extensions, and be sure to check out the source code for the project created in this article.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020