TrajectoryUnlimited - multiplayer - Nokia 128x160 - English
|
TrajectoryUnlimited - multiplayer - Nokia 128x160 - English. Play one of the most addictive multiplayer mobile games via Bluetooth for Nokia.
Warning: Real-time and turn-based multiplayer services are deprecated as of September 16th, 2019. These services are unavailable for new games. For more information, see Ending support for multiplayer APIs in Play Games Services.This guide shows you how to implement a real-time multiplayer game using theGoogle Play games services in an Android application. The APIs can be found in the
com.google.android.gms.games.multiplayer
,com.google.android.gms.games.multiplayer.turnbased
, andcom.google.android.gms.games
packages.Before you begin
If you haven't already done so, you might find it helpful to review theturn-based multiplayer game concepts.
Before you start to code your turn-based multiplayer game:
- Make sure to enable turn-based multiplayer support for yourgame in the Google Play Console.
- Download and review the turn-based multiplayer game code samples in theAndroid samples page.
- Familiarize yourself with the recommendations described inQuality Checklist.
Getting the turn-based multiplayer client
To start using the real-time multiplayer API, your game must first obtain a
Note: The TurnBasedMultiplayerClient
object. You can do this by calling theGames.getTurnBasedMultiplayerClient()
method and passing in theactivity and the GoogleSignInAccount
for the current player. To learn how toretrieve the player account information, seeSign-in in Android Games.TurnBasedMultiplayerClient
class makes use of the Google Playservices Task
class to return results asynchronously. To learn more aboutusing tasks to manage threaded work, see theTasks API developer guide.Starting a match
To begin a turn-based match, your game can prompt players to select how theywant to be matched to other participants, or build the match using some defaultcriteria. Google Play games services uses the match configuration data from yourgame to return a
TurnBasedMatch
object to your game; this object is updated and shared asynchronously with allparticipants over the lifecycle of the turn-based match.To start a match, follow these steps:
- In your app, gather specifications for the type of turn-based match that theplayer wants to play and who can participate in the match.
- Your game can display the built-in player picker user interface (UI)provided by the SDK or use a own custom UI to gather this data. To learnhow to use the player picker UI, see Selecting players with the default user interface.
- Alternatively, you can implement a Quick Start button to let usersbypass the player picker UI, and instead use some default criteria to build the match.
- Use a
TurnBasedMatchConfig.Builder
to set the match configuration data in aTurnBasedConfigObject
. - Call
TurnBasedMultiplayerClient.createMatch()
and pass in theTurnBasedConfigObject
you created. If auto-matching is specified, Google Play games services will attempt to matchplayers to an existing game; for more details, seeImplementing auto-matching.
Selecting players with the default user interface
Google Play games services provides a default player picker UI that lets playersselect their friends to invite to a match or select to be auto-matched withrandom players.
To start a match from the default player picker UI, call the
TurnBasedMultiplayerClient.getSelectOpponentsIntent()
method and use the intent it returns tostart an activity.For example:
Next, override the
onActivityResult()
callback to construct a TurnBasedMatchConfig
object using the criteria provided by the user. The TurnBasedMatchConfig
object defines the characteristics of the match that the user wants to play. Google Play games servicesuses this configuration data to determine whether to build a new match or to auto-match the user toan existing game.For example:
If you want to create a match without using the default player picker UI,your game must provide the invitee player IDs and auto-match criteria in the
TurnBasedMatchConfig
object that you pass to TurnBasedMultiplayerClient.createMatch()
.Optionally, you might want to ensure that only players who are interested in aspecific type of game variant are auto-matched together. If there aredifferent versions of your app, your game can also use variants to ensure thatonly players who are on compatible versions are auto-matched.
To specify a variant when creating a turn-based match, use the
setVariant()
method. Your game can also use the exclusiveBitMask
parameter increateAutoMatchCriteria()
to pair auto-matched players who are interested in playing specific exclusiveroles in a game.Taking the first turn
If the
TurnBasedMultiplayerClient.createMatch()
callis successful, Google Play games services returns a Task
object which asynchronously loads a TurnBasedMatch
instance.Before proceeding, remember to initialize the game data as needed by your game.For example, you might need to initialize the starting positions for players ina strategy game or initialize the first hand for players in a card game.
To implement the first turn, follow these steps:
- Call the
getData()
method on theTurnBasedMatch
instance.- If the call returns a
null
value, this indicates that the game data isuninitialized because no player has taken a turn yet (that is, the currentplayer is the first player in this match). Your game can initialize the game data andstore it in a byte array. The size of the game data must be less than the sizereturned byTurnBasedMultiplayerClient.getMaxMatchDataSize()
.The data size returned is guaranteed to be at least 128 KB. - If the call returns a non-
null
value, this indicates that the game hasalready started and the game data is already initialized, so make sure yourgame does not reinitialize the data.
- If the call returns a
- Optionally, call
TurnBasedMultiplayerClient.takeTurn()
now. If your initialstate is based on a random value (for example, a card game where the playerstarts with a random hand) and your game does not callTurnBasedMultiplayerClient.takeTurn()
to persist thedata to Google's servers, the player could keep restarting the first turn totry to get a better starting position. - Let the player perform game actions, and if appropriate, update the bytearray containing the game data.
- Save the game data to Google’s servers by calling
TurnBasedMultiplayerClient.takeTurn()
. Your game can specify the next player'sparticipant ID, or specifynull
to let Google Play games servicesfind a player for auto-matching. Your game can let match participants take turns evenwhen not all invited players have joined or when there are auto-match slotsstill available. To get players into gameplay faster, your game should let playerstake their turn as soon as they join. When you callTurnBasedMultiplayerClient.takeTurn()
, Google Play games services sends anotification to the pending participant and updates the turndata on all participants' devices asynchronously. - When the next player takes a turn, make sure to load the initialized databy calling
getData()
before you let the player perform game actions.
Implementing auto-matching
When your game calls
TurnBasedMultiplayerClient.createMatch()
and requestsauto-matching, Google Play games services first attempts to match the player to anexisting game.If a match is found that meets the player's auto-match criteria,Google Play games services automatically joins the player and any invited playersas auto-matched players into the existing match.
If no match is found, your game should signal that it is available forauto-matching, by performing these steps:
- Prompt the initiating player to take the first turn.
- Optionally, after the initiating player completes their first turn, your gamecan also let other invited players who joined the match take their first turns.
- To trigger auto-matching, call
TurnBasedMultiplayerClient.takeTurn()
andpass innull
in thependingParticipantId
parameter.
The following code shows how your game can get the next participant in around-robin fashion, where all known players take a turn before all automatchplayers:
Handling invitations
Once a player has signed in to your game, the player may receive invitations tojoin a turn-based match created by another player. To save coding time andprovide users with a consistent UI for responding to match invitations acrossapplications, you can use the default match inbox UI provided by the SDK.
To launch the default match inbox UI, call the
Note: If an invited participant declines an invitation without taking aturn, the match is canceled. An auto-matched player can leave withoutcanceling the match as long as that player has not taken a turn.TurnBasedMultiplayerClient.getInboxIntent()
method, then use the intent itreturns to start an activity.Taking a turn
After the first player takes a turn, your game can let the same participant oranother participant take the next turn. Generally, turn-taking involves loadingthe most recent match data from Google Play games services, letting the participantinteract with your game, and calling
TurnBasedMultiplayerClient.takeTurn()
toupdate the match data and pass the turn to another participant.To implement turn-taking, follow these steps:
- Optionally, if you want be notified whenever any participant in the matchtakes a turn, attach a
TurnBasedMatchUpdateCallback
to your activity. Wheneverthe match is updated following a player's turn, your activity is notified viatheTurnBasedMatchUpdateCallback.onTurnBasedMatchedReceived()
method. - In order for a participant to take a turn, the match must be in active stateand it must be that participant's turn. Your game can use the
TurnBasedMatch
object to verify this.- Check the match state by calling
getStatus()
.A result ofMATCH_STATUS_ACTIVE
indicates that the match is active. - Check the match turn status by calling
getTurnStatus()
. A result ofMATCH_TURN_STATUS_MY_TURN
indicates that it is now the user's turn.
- Check the match state by calling
- Load the most recent match data from Google Play games services by calling
getData()
and render your game accordingly. - Let the user perform game actions and, if appropriate, persist theupdated game data to a byte array.
- Determine the pending participant who should take the next turn. This isusually dependent on the order of play specified by your game design. Thepending participant can be another player in the match or the current participantwhose turn it is. Your game can also pass the turn to the next playerjoining by auto-match, by setting the pending participant to
null
. - Call
TurnBasedMultiplayerClient.takeTurn()
to update theGoogle Play games services with the latest game data and pass the turnto the pending participant. If the update is successful, Google Play games servicessends a notification to the pending participant to inform them that it's theirturn.
For example:
Saving game state
You can use the turn-based multiplayer API to manage your game state if yourgame state data fits within the allowed size. The data size limit can beretrieved by calling
TurnBasedMultiplayerClient.getMaxMatchDataSize()
. The data size returned isguaranteed to be at least 128 KB.To save game state with the turn-based multiplayer API:
- Call
TurnBasedMultiplayerClient.takeTurn()
and pass in your game state dataas thematchData
parameter. - If the call is successful, Google Play games services notifies other participantsin the match about the update and makes the match data available on allparticipant devices.
- Your game can then call getData() to retrieve the updated game state.
Your game should try to save game data for a partially-finishedturn whenever a player's turn is interrupted and the player has to temporarilyleave the game (for example, because of an incoming phone call). To do this,override your activity'sonStop()method to call
TurnBasedMultiplayerClient.takeTurn()
. Make sure to specifythe current player as the pending participant by using the same participant IDas in the last call to TurnBasedMultiplayerClient.takeTurn()
. If successful,the call stores the game data in Google’s servers but does not generate a newturn notification.Completing a match
When the match has been played to completion (for example, a user has won thegame), your game should call
TurnBasedMultiplayerClient.finishMatch()
to upload the user’s game data and signal to the other participants that thematch is over. When your game invokes this method for the first time during a match,it must be during the user's turn. The match then appears under theCompleted Matches category in the user's match list UI.Once a player calls
TurnBasedMultiplayerClient.finishMatch()
for the first time in the match, your game cannot callTurnBasedMultiplayerClient.takeTurn()
again in this match.Google Play games services sends a notification to all othermatch participants to inform them that the match is over. These participantssee this match under Your Turn category in their respective match list UIs.At this point, your game can call TurnBasedMultiplayerClient.finishMatch()
for these participants to save their final game data. Invoking this method alsomoves the match to the Completed Matches category in the participant’s matchlist UI.Leaving a match
Participants can choose to leave at any time during the match, while allowingthe match to continue. To signal that a participant is leaving, your game should call either
TurnBasedMultiplayerClient.leaveMatch()
orTurnBasedMultiplayerClient.leaveMatchDuringTurn()
. When a participant leavesa match, the match can still continue with otherparticipants as long as these conditions are met:- There are two or more other remaining participants, or
- There is one remaining participant and at least one empty auto-match slotavailable.
Otherwise, the match is canceled.
In general, when a participant leaves a match, another player cannot join andtake that participant’s place. One exception is when a player who joined byauto-match and who has not taken a turn calls
TurnBasedMultiplayerClient.leaveMatchDuringTurn()
. In this case, the matchreverts to the MATCH_STATUS_AUTO_MATCHING
state and another player can take over theplace of the participant who left.Canceling a match
Your game can end a match for all participants before the match is played to normalcompletion, by calling
TurnBasedMultiplayerClient.cancelMatch()
.After calling this method, your game cannot callTurnBasedMultiplayerClient.takeTurn()
again in this match; the match nowappears under the Completed Matches category in the match list UI.Dismissing a match
To dismiss a match, call
TurnBasedMultiplayerClient.dismissMatch()
.Your game can let users dismiss a turn or invitation so that they do not have to seethe match again. This hides the match from the dismisser's match list UI andcauses the match to eventually expire. Other match participants can continue toplay until the dismissed match expires after two weeks, or until the match isplayed to completion or canceled (whichever happens first). To otherparticipants, the dismisser still appears as a participant in the match. Anotherplayer cannot take the dismisser's place.
Tracking match expiration
A match can expire if a player does not respond to a match or turn notificationfor two weeks (for example, after a player whose turn it is selects Dismissin the default match list UI).
You can use the following approach on the game client to identify which playercaused a game to expire:
- Load a list of the currently signed-in player’s list of games by calling
TurnBasedMultiplayerClient.loadMatchesByStatus()
. - Next, call
getCompletedMatches()
to get aTurnBasedMatchBuffer
that contains a list of matches in theMATCH_TURN_STATUS_COMPLETE
state. - Then, filter that list for matches in the
MATCH_STATUS_EXPIRED
state. - If a match participant has
STATUS_UNRESPONSIVE
state, it indicates that this player has let the game expire.
Implementing a rematch
When a match is over, a participant may want to play a rematch with the sameset of invited and auto-match opponents. Your game can initiate a rematch byinvoking
TurnBasedMultiplayerClient.rematch()
.Your game can only invoke this method when the match state isMATCH_STATUS_COMPLETE
and no other participants have requested a rematch. If the call is successful,Google Play games services sends invitation notifications to all rematched opponents.If your game uses the default match inbox UI, players can also initiate rematchesfrom that UI. When a player initiates a rematch from the match inbox UI,Google Play games services returns a new match object as an
Intent
extra in the onActivityResult()
callback of the match inbox activity. If your gameneeds to initialize game data for the new match, make sure to use the matchobject returned in theonActivityResult()
callback.