Creating Games with Google+ Hangouts
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:
- A card is removed from the deck.
- The card is added to the player's hand.
- 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:
- Create and verify a Chrome Web Store account.
- Add application icons in various sizes.
- Add URLs for your application's Privacy Policy, Support, and Terms of Service pages.
- 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.