com.google.android.gms.games.multiplayer.turnbased.TurnBasedMatch Java Examples

The following examples show how to use com.google.android.gms.games.multiplayer.turnbased.TurnBasedMatch. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SkeletonActivity.java    From android-basic-samples with Apache License 2.0 7 votes vote down vote up
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {

  if (requestCode == RC_SIGN_IN) {

    Task<GoogleSignInAccount> task =
        GoogleSignIn.getSignedInAccountFromIntent(intent);

    try {
      GoogleSignInAccount account = task.getResult(ApiException.class);
      onConnected(account);
    } catch (ApiException apiException) {
      String message = apiException.getMessage();
      if (message == null || message.isEmpty()) {
        message = getString(R.string.signin_other_error);
      }

      onDisconnected();

      new AlertDialog.Builder(this)
          .setMessage(message)
          .setNeutralButton(android.R.string.ok, null)
          .show();
    }
  } else if (requestCode == RC_LOOK_AT_MATCHES) {
    // Returning from the 'Select Match' dialog

    if (resultCode != Activity.RESULT_OK) {
      logBadActivityResult(requestCode, resultCode,
          "User cancelled returning from the 'Select Match' dialog.");
      return;
    }

    TurnBasedMatch match = intent
        .getParcelableExtra(Multiplayer.EXTRA_TURN_BASED_MATCH);

    if (match != null) {
      updateMatch(match);
    }

    Log.d(TAG, "Match = " + match);
  } else if (requestCode == RC_SELECT_PLAYERS) {
    // Returning from 'Select players to Invite' dialog

    if (resultCode != Activity.RESULT_OK) {
      // user canceled
      logBadActivityResult(requestCode, resultCode,
          "User cancelled returning from 'Select players to Invite' dialog");
      return;
    }

    // get the invitee list
    ArrayList<String> invitees = intent
        .getStringArrayListExtra(Games.EXTRA_PLAYER_IDS);

    // get automatch criteria
    Bundle autoMatchCriteria;

    int minAutoMatchPlayers = intent.getIntExtra(Multiplayer.EXTRA_MIN_AUTOMATCH_PLAYERS, 0);
    int maxAutoMatchPlayers = intent.getIntExtra(Multiplayer.EXTRA_MAX_AUTOMATCH_PLAYERS, 0);

    if (minAutoMatchPlayers > 0) {
      autoMatchCriteria = RoomConfig.createAutoMatchCriteria(minAutoMatchPlayers,
          maxAutoMatchPlayers, 0);
    } else {
      autoMatchCriteria = null;
    }

    TurnBasedMatchConfig tbmc = TurnBasedMatchConfig.builder()
        .addInvitedPlayers(invitees)
        .setAutoMatchCriteria(autoMatchCriteria).build();

    // Start the match
    mTurnBasedMultiplayerClient.createMatch(tbmc)
        .addOnSuccessListener(new OnSuccessListener<TurnBasedMatch>() {
          @Override
          public void onSuccess(TurnBasedMatch turnBasedMatch) {
            onInitiateMatch(turnBasedMatch);
          }
        })
        .addOnFailureListener(createFailureListener("There was a problem creating a match!"));
    showSpinner();
  }
}
 
Example #2
Source File: SkeletonActivity.java    From android-basic-samples with Apache License 2.0 6 votes vote down vote up
public void onUpdateMatch(TurnBasedMatch match) {
  dismissSpinner();

  if (match.canRematch()) {
    askForRematch();
  }

  isDoingTurn = (match.getTurnStatus() == TurnBasedMatch.MATCH_TURN_STATUS_MY_TURN);

  if (isDoingTurn) {
    updateMatch(match);
    return;
  }

  setViewVisibility();
}
 
Example #3
Source File: SkeletonActivity.java    From android-basic-samples with Apache License 2.0 6 votes vote down vote up
public void startMatch(TurnBasedMatch match) {
  mTurnData = new SkeletonTurn();
  // Some basic turn data
  mTurnData.data = "First turn";

  mMatch = match;

  String myParticipantId = mMatch.getParticipantId(mPlayerId);

  showSpinner();

  mTurnBasedMultiplayerClient.takeTurn(match.getMatchId(),
      mTurnData.persist(), myParticipantId)
      .addOnSuccessListener(new OnSuccessListener<TurnBasedMatch>() {
        @Override
        public void onSuccess(TurnBasedMatch turnBasedMatch) {
          updateMatch(turnBasedMatch);
        }
      })
      .addOnFailureListener(createFailureListener("There was a problem taking a turn!"));
}
 
Example #4
Source File: Game.java    From chess with Apache License 2.0 6 votes vote down vote up
/**
 * Game over
 */
public static void over() {
    int winnerTeam = getWinnerTeam();
    if (!match.isLocal) {
        if (BuildConfig.DEBUG) Logger.log("Game.over state: " + match.getStatus());
        if (match.getStatus() == TurnBasedMatch.MATCH_STATUS_ACTIVE) {
            List<ParticipantResult> result = new ArrayList<ParticipantResult>(players.length);
            for (Player p : players) {
                result.add(new ParticipantResult(p.id,
                        p.team == winnerTeam ? ParticipantResult.MATCH_RESULT_WIN :
                                ParticipantResult.MATCH_RESULT_LOSS,
                        ParticipantResult.PLACING_UNINITIALIZED));
                if (BuildConfig.DEBUG)
                    Logger.log(p.id + " " + (p.team == winnerTeam ? "win" : "loss"));
            }
            Games.TurnBasedMultiplayer.finishMatch(api, match.id, toBytes(), result);
        } else {
            Games.TurnBasedMultiplayer.finishMatch(api, match.id);
        }
        if (UI != null) UI.gameOver(winnerTeam == getPlayer(myPlayerId).team);
    } else {
        if (UI != null) UI.gameOverLocal(getWinner());
    }
}
 
Example #5
Source File: SkeletonActivity.java    From android-basic-samples with Apache License 2.0 6 votes vote down vote up
public void onQuickMatchClicked(View view) {

    Bundle autoMatchCriteria = RoomConfig.createAutoMatchCriteria(1, 1, 0);

    TurnBasedMatchConfig turnBasedMatchConfig = TurnBasedMatchConfig.builder()
        .setAutoMatchCriteria(autoMatchCriteria).build();

    showSpinner();

    // Start the match
    mTurnBasedMultiplayerClient.createMatch(turnBasedMatchConfig)
        .addOnSuccessListener(new OnSuccessListener<TurnBasedMatch>() {
          @Override
          public void onSuccess(TurnBasedMatch turnBasedMatch) {
            onInitiateMatch(turnBasedMatch);
          }
        })
        .addOnFailureListener(createFailureListener("There was a problem creating a match!"));
  }
 
Example #6
Source File: Main.java    From chess with Apache License 2.0 6 votes vote down vote up
@Override
public void onTurnBasedMatchReceived(final TurnBasedMatch match) {
    if (BuildConfig.DEBUG) Logger.log("Main onTurnBasedMatchReceived: " + match.getMatchId());
    if (match.getTurnStatus() == TurnBasedMatch.MATCH_TURN_STATUS_MY_TURN &&
            match.getStatus() == TurnBasedMatch.MATCH_STATUS_ACTIVE) {
        final Ringtone tone = RingtoneManager.getRingtone(this, RingtoneManager
                .getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_NOTIFICATION));
        tone.setStreamType(AudioManager.STREAM_NOTIFICATION);
        tone.play();
    }
    if (startFragment != null && startFragment.isVisible()) {
        startFragment.loadMatches();
    }
    if (gameFragment != null && gameFragment.isVisible() &&
            match.getMatchId().equals(gameFragment.currentMatch)) {
        if (Game.load(match.getData(), new Match(match), mGoogleApiClient)) {
            gameFragment.update(match.getStatus() != TurnBasedMatch.MATCH_STATUS_ACTIVE &&
                    match.getStatus() != TurnBasedMatch.MATCH_STATUS_AUTO_MATCHING);
        } else {
            updateApp();
        }
    }
}
 
Example #7
Source File: Main.java    From chess with Apache License 2.0 6 votes vote down vote up
@Override
public void onConnected(final Bundle bundle) {
    if (BuildConfig.DEBUG) Logger.log("Main.onConnected");
    TurnBasedMatch match;
    if (bundle != null &&
            (match = bundle.getParcelable(Multiplayer.EXTRA_TURN_BASED_MATCH)) != null) {
        if (gameFragment == null || !gameFragment.isVisible()) {
            if (Game.load(match.getData(), new Match(match), mGoogleApiClient)) {
                startGame(match.getMatchId());
            } else {
                updateApp();
            }
        }
    } else {
        if (startFragment != null && startFragment.isVisible()) startFragment.loadMatches();
    }
    Games.TurnBasedMultiplayer.registerMatchUpdateListener(mGoogleApiClient, this);
}
 
Example #8
Source File: SkeletonActivity.java    From android-basic-samples with Apache License 2.0 6 votes vote down vote up
public void onDoneClicked(View view) {
  showSpinner();

  String nextParticipantId = getNextParticipantId();
  // Create the next turn
  mTurnData.turnCounter += 1;
  mTurnData.data = mDataView.getText().toString();

  mTurnBasedMultiplayerClient.takeTurn(mMatch.getMatchId(),
      mTurnData.persist(), nextParticipantId)
      .addOnSuccessListener(new OnSuccessListener<TurnBasedMatch>() {
        @Override
        public void onSuccess(TurnBasedMatch turnBasedMatch) {
          onUpdateMatch(turnBasedMatch);
        }
      })
      .addOnFailureListener(createFailureListener("There was a problem taking a turn!"));

  mTurnData = null;
}
 
Example #9
Source File: StartFragment.java    From chess with Apache License 2.0 6 votes vote down vote up
void loadMatches() {
    if (BuildConfig.DEBUG) Logger.log("StartFramgnet.loadMatches");
    if (getView() == null) return; // not visible
    getView().findViewById(R.id.inbox).setVisibility(View.VISIBLE);
    Games.TurnBasedMultiplayer.loadMatchesByStatus(((Main) getActivity()).getGC(),
            new int[]{TurnBasedMatch.MATCH_TURN_STATUS_MY_TURN,
                    TurnBasedMatch.MATCH_TURN_STATUS_THEIR_TURN})
            .setResultCallback(new ResultCallback<TurnBasedMultiplayer.LoadMatchesResult>() {
                @Override
                public void onResult(final TurnBasedMultiplayer.LoadMatchesResult result) {
                    myTurns.setMatches(result.getMatches().getMyTurnMatches());
                    pending.setMatches(result.getMatches().getTheirTurnMatches());
                    result.release();
                }
            });
}
 
Example #10
Source File: GameHelper.java    From tedroid with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the tbmp match received through an invitation notification. This
 * should be called from your GameHelperListener's
 *
 * @link{GameHelperListener#onSignInSucceeded method, to check if there's a
 *                                            match available.
 * @return The match, or null if none was received.
 */
public TurnBasedMatch getTurnBasedMatch() {
    if (!mGoogleApiClient.isConnected()) {
        Log.w(TAG,
                "Warning: getTurnBasedMatch() should only be called when signed in, "
                        + "that is, after getting onSignInSuceeded()");
    }
    return mTurnBasedMatch;
}
 
Example #11
Source File: GameHelper.java    From Onesearch with MIT License 5 votes vote down vote up
/**
 * Returns the tbmp match received through an invitation notification. This
 * should be called from your GameHelperListener's
 *
 * @link{GameHelperListener#onSignInSucceeded method, to check if there's a
 *                                            match available.
 * @return The match, or null if none was received.
 */
public TurnBasedMatch getTurnBasedMatch() {
    if (!mGoogleApiClient.isConnected()) {
        Log.w(TAG,
                "Warning: getTurnBasedMatch() should only be called when signed in, "
                        + "that is, after getting onSignInSuceeded()");
    }
    return mTurnBasedMatch;
}
 
Example #12
Source File: GameHelper.java    From FlappyCow with MIT License 5 votes vote down vote up
/**
 * Returns the tbmp match received through an invitation notification. This
 * should be called from your GameHelperListener's
 *
 * @link{GameHelperListener#onSignInSucceeded method, to check if there's a
 *                                            match available.
 * @return The match, or null if none was received.
 */
public TurnBasedMatch getTurnBasedMatch() {
    if (!mGoogleApiClient.isConnected()) {
        Log.w(TAG,
                "Warning: getTurnBasedMatch() should only be called when signed in, "
                        + "that is, after getting onSignInSuceeded()");
    }
    return mTurnBasedMatch;
}
 
Example #13
Source File: GameHelper.java    From cordova-google-play-games-services with MIT License 5 votes vote down vote up
/**
 * Returns the tbmp match received through an invitation notification. This
 * should be called from your GameHelperListener's
 *
 * @link{GameHelperListener#onSignInSucceeded method, to check if there's a
 *                                            match available.
 * @return The match, or null if none was received.
 */
public TurnBasedMatch getTurnBasedMatch() {
    if (!mGoogleApiClient.isConnected()) {
        Log.w(TAG,
                "Warning: getTurnBasedMatch() should only be called when signed in, "
                        + "that is, after getting onSignInSuceeded()");
    }
    return mTurnBasedMatch;
}
 
Example #14
Source File: SkeletonActivity.java    From android-basic-samples with Apache License 2.0 5 votes vote down vote up
public void onFinishClicked(View view) {
  showSpinner();
  mTurnBasedMultiplayerClient.finishMatch(mMatch.getMatchId())
      .addOnSuccessListener(new OnSuccessListener<TurnBasedMatch>() {
        @Override
        public void onSuccess(TurnBasedMatch turnBasedMatch) {
          onUpdateMatch(turnBasedMatch);
        }
      })
      .addOnFailureListener(createFailureListener("There was a problem finishing the match!"));

  isDoingTurn = false;
  setViewVisibility();
}
 
Example #15
Source File: SkeletonActivity.java    From android-basic-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Since a lot of the operations use tasks, we can use a common handler for whenever one fails.
 *
 * @param exception The exception to evaluate.  Will try to display a more descriptive reason for
 *                  the exception.
 * @param details   Will display alongside the exception if you wish to provide more details for
 *                  why the exception happened
 */
private void handleException(Exception exception, String details) {
  int status = 0;

  if (exception instanceof TurnBasedMultiplayerClient.MatchOutOfDateApiException) {
    TurnBasedMultiplayerClient.MatchOutOfDateApiException matchOutOfDateApiException =
        (TurnBasedMultiplayerClient.MatchOutOfDateApiException) exception;

    new AlertDialog.Builder(this)
        .setMessage("Match was out of date, updating with latest match data...")
        .setNeutralButton(android.R.string.ok, null)
        .show();

    TurnBasedMatch match = matchOutOfDateApiException.getMatch();
    updateMatch(match);

    return;
  }

  if (exception instanceof ApiException) {
    ApiException apiException = (ApiException) exception;
    status = apiException.getStatusCode();
  }

  if (!checkStatusCode(status)) {
    return;
  }

  String message = getString(R.string.status_exception_error, details, status, exception);

  new AlertDialog.Builder(this)
      .setMessage(message)
      .setNeutralButton(android.R.string.ok, null)
      .show();
}
 
Example #16
Source File: SkeletonActivity.java    From android-basic-samples with Apache License 2.0 5 votes vote down vote up
public void rematch() {
  showSpinner();
  mTurnBasedMultiplayerClient.rematch(mMatch.getMatchId())
      .addOnSuccessListener(new OnSuccessListener<TurnBasedMatch>() {
        @Override
        public void onSuccess(TurnBasedMatch turnBasedMatch) {
          onInitiateMatch(turnBasedMatch);
        }
      })
      .addOnFailureListener(createFailureListener("There was a problem starting a rematch!"));
  mMatch = null;
  isDoingTurn = false;
}
 
Example #17
Source File: SkeletonActivity.java    From android-basic-samples with Apache License 2.0 5 votes vote down vote up
private void onInitiateMatch(TurnBasedMatch match) {
  dismissSpinner();

  if (match.getData() != null) {
    // This is a game that has already started, so I'll just start
    updateMatch(match);
    return;
  }

  startMatch(match);
}
 
Example #18
Source File: GameHelper.java    From ANE-Google-Play-Game-Services with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the tbmp match received through an invitation notification. This
 * should be called from your GameHelperListener's
 *
 * @link{GameHelperListener#onSignInSucceeded method, to check if there's a
 *                                            match available.
 * @return The match, or null if none was received.
 */
public TurnBasedMatch getTurnBasedMatch() {
    if (!mGoogleApiClient.isConnected()) {
        Log.w(TAG,
                "Warning: getTurnBasedMatch() should only be called when signed in, "
                        + "that is, after getting onSignInSuceeded()");
    }
    return mTurnBasedMatch;
}
 
Example #19
Source File: GameHelper.java    From Asteroid with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the tbmp match received through an invitation notification. This
 * should be called from your GameHelperListener's
 *
 * @return The match, or null if none was received.
 * @link{GameHelperListener#onSignInSucceeded method, to check if there's a
 * match available.
 */
public TurnBasedMatch getTurnBasedMatch() {
    if (!mGoogleApiClient.isConnected()) {
        Log.w(TAG,
                "Warning: getTurnBasedMatch() should only be called when signed in, "
                        + "that is, after getting onSignInSucceeded()");
    }
    return mTurnBasedMatch;
}
 
Example #20
Source File: GameHelper.java    From io2014-codelabs with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the tbmp match received through an invitation notification. This
 * should be called from your GameHelperListener's
 *
 * @link{GameHelperListener#onSignInSucceeded method, to check if there's a
 *                                            match available.
 * @return The match, or null if none was received.
 */
public TurnBasedMatch getTurnBasedMatch() {
    if (!mGoogleApiClient.isConnected()) {
        Log.w(TAG,
                "Warning: getTurnBasedMatch() should only be called when signed in, "
                        + "that is, after getting onSignInSuceeded()");
    }
    return mTurnBasedMatch;
}
 
Example #21
Source File: GameHelper.java    From io2014-codelabs with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the tbmp match received through an invitation notification. This
 * should be called from your GameHelperListener's
 *
 * @link{GameHelperListener#onSignInSucceeded method, to check if there's a
 *                                            match available.
 * @return The match, or null if none was received.
 */
public TurnBasedMatch getTurnBasedMatch() {
    if (!mGoogleApiClient.isConnected()) {
        Log.w(TAG,
                "Warning: getTurnBasedMatch() should only be called when signed in, "
                        + "that is, after getting onSignInSuceeded()");
    }
    return mTurnBasedMatch;
}
 
Example #22
Source File: GameHelper.java    From ColorPhun with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the tbmp match received through an invitation notification. This
 * should be called from your GameHelperListener's
 *
 * @link{GameHelperListener#onSignInSucceeded method, to check if there's a
 *                                            match available.
 * @return The match, or null if none was received.
 */
public TurnBasedMatch getTurnBasedMatch() {
    if (!mGoogleApiClient.isConnected()) {
        Log.w(TAG,
                "Warning: getTurnBasedMatch() should only be called when signed in, "
                        + "that is, after getting onSignInSuceeded()");
    }
    return mTurnBasedMatch;
}
 
Example #23
Source File: StartFragment.java    From chess with Apache License 2.0 5 votes vote down vote up
private void setMatches(final TurnBasedMatchBuffer m) {
    matches = new ArrayList<TurnBasedMatch>(m.getCount());
    for (TurnBasedMatch match : m) {
        matches.add(match.freeze());
    }
    m.release();
    notifyDataSetChanged();
    title.setVisibility(matches.isEmpty() ? View.GONE : View.VISIBLE);
    list.setVisibility(matches.isEmpty() ? View.GONE : View.VISIBLE);
}
 
Example #24
Source File: GameHelper.java    From google-play-game-services-ane with MIT License 5 votes vote down vote up
/**
 * Returns the tbmp match received through an invitation notification. This
 * should be called from your GameHelperListener's
 * @link{GameHelperListener#onSignInSucceeded} method, to check if there's a
 * match available.
 * @return The match, or null if none was received.
 */
public TurnBasedMatch getTurnBasedMatch() {
    if (!mGoogleApiClient.isConnected()) {
        Log.w(TAG, "Warning: getTurnBasedMatch() should only be called when signed in, " +
                "that is, after getting onSignInSuceeded()");
    }
    return mTurnBasedMatch;
}
 
Example #25
Source File: GameHelper.java    From martianrun with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the tbmp match received through an invitation notification. This
 * should be called from your GameHelperListener's
 *
 * @return The match, or null if none was received.
 * @link{GameHelperListener#onSignInSucceeded method, to check if there's a
 * match available.
 */
public TurnBasedMatch getTurnBasedMatch() {
    if (!mGoogleApiClient.isConnected()) {
        Log.w(TAG,
                "Warning: getTurnBasedMatch() should only be called when signed in, "
                        + "that is, after getting onSignInSuceeded()");
    }
    return mTurnBasedMatch;
}
 
Example #26
Source File: GameHelper.java    From FixMath with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the tbmp match received through an invitation notification. This
 * should be called from your GameHelperListener's
 *
 * @link{GameHelperListener#onSignInSucceeded method, to check if there's a
 *                                            match available.
 * @return The match, or null if none was received.
 */
public TurnBasedMatch getTurnBasedMatch() {
    if (!mGoogleApiClient.isConnected()) {
        Log.w(TAG,
                "Warning: getTurnBasedMatch() should only be called when signed in, "
                        + "that is, after getting onSignInSuceeded()");
    }
    return mTurnBasedMatch;
}
 
Example #27
Source File: GameHelper.java    From dice-heroes with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns the tbmp match received through an invitation notification. This
 * should be called from your GameHelperListener's
 *
 * @link{GameHelperListener#onSignInSucceeded method, to check if there's a
 *                                            match available.
 * @return The match, or null if none was received.
 */
public TurnBasedMatch getTurnBasedMatch() {
    if (!mGoogleApiClient.isConnected()) {
        Log.w(TAG,
                "Warning: getTurnBasedMatch() should only be called when signed in, "
                        + "that is, after getting onSignInSuceeded()");
    }
    return mTurnBasedMatch;
}
 
Example #28
Source File: GameHelper.java    From Trivia-Knowledge with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the tbmp match received through an invitation notification. This
 * should be called from your GameHelperListener's
 *
 * @link{GameHelperListener#onSignInSucceeded method, to check if there's a
 *                                            match available.
 * @return The match, or null if none was received.
 */
public TurnBasedMatch getTurnBasedMatch() {
    if (!mGoogleApiClient.isConnected()) {
        Log.w(TAG,
                "Warning: getTurnBasedMatch() should only be called when signed in, "
                        + "that is, after getting onSignInSuceeded()");
    }
    return mTurnBasedMatch;
}
 
Example #29
Source File: SkeletonActivity.java    From android-basic-samples with Apache License 2.0 4 votes vote down vote up
private void onConnected(GoogleSignInAccount googleSignInAccount) {
  Log.d(TAG, "onConnected(): connected to Google APIs");

  mTurnBasedMultiplayerClient = Games.getTurnBasedMultiplayerClient(this, googleSignInAccount);
  mInvitationsClient = Games.getInvitationsClient(this, googleSignInAccount);

  Games.getPlayersClient(this, googleSignInAccount)
      .getCurrentPlayer()
      .addOnSuccessListener(
          new OnSuccessListener<Player>() {
            @Override
            public void onSuccess(Player player) {
              mDisplayName = player.getDisplayName();
              mPlayerId = player.getPlayerId();

              setViewVisibility();
            }
          }
      )
      .addOnFailureListener(createFailureListener("There was a problem getting the player!"));

  Log.d(TAG, "onConnected(): Connection successful");

  // Retrieve the TurnBasedMatch from the connectionHint
  GamesClient gamesClient = Games.getGamesClient(this, googleSignInAccount);
  gamesClient.getActivationHint()
      .addOnSuccessListener(new OnSuccessListener<Bundle>() {
        @Override
        public void onSuccess(Bundle hint) {
          if (hint != null) {
            TurnBasedMatch match = hint.getParcelable(Multiplayer.EXTRA_TURN_BASED_MATCH);

            if (match != null) {
              updateMatch(match);
            }
          }
        }
      })
      .addOnFailureListener(createFailureListener(
          "There was a problem getting the activation hint!"));

  setViewVisibility();

  // As a demonstration, we are registering this activity as a handler for
  // invitation and match events.

  // This is *NOT* required; if you do not register a handler for
  // invitation events, you will get standard notifications instead.
  // Standard notifications may be preferable behavior in many cases.
  mInvitationsClient.registerInvitationCallback(mInvitationCallback);

  // Likewise, we are registering the optional MatchUpdateListener, which
  // will replace notifications you would get otherwise. You do *NOT* have
  // to register a MatchUpdateListener.
  mTurnBasedMultiplayerClient.registerTurnBasedMatchUpdateCallback(mMatchUpdateCallback);
}
 
Example #30
Source File: Achievements.java    From chess with Apache License 2.0 4 votes vote down vote up
/**
 * Check the conditions for not-yet-unlocked achievements and unlock them if
 * the condition is met and updates the leaderboard
 *
 * @param gc      the GamesClient
 * @param context the Context
 */
public static void checkAchievements(final GoogleApiClient gc, final Context context) {
    if (gc.isConnected()) {
        Games.TurnBasedMultiplayer
                .loadMatchesByStatus(gc, new int[]{TurnBasedMatch.MATCH_TURN_STATUS_COMPLETE})
                .setResultCallback(
                        new ResultCallback<TurnBasedMultiplayer.LoadMatchesResult>() {
                            @Override
                            public void onResult(final TurnBasedMultiplayer.LoadMatchesResult result) {
                                HashMap<Integer, Integer> wins =
                                        new HashMap<Integer, Integer>(4);
                                wins.put(Game.MODE_2_PLAYER_2_SIDES, 0);
                                wins.put(Game.MODE_2_PLAYER_4_SIDES, 0);
                                wins.put(Game.MODE_4_PLAYER_NO_TEAMS, 0);
                                wins.put(Game.MODE_4_PLAYER_TEAMS, 0);

                                ParticipantResult pResult;
                                for (TurnBasedMatch m : result.getMatches()
                                        .getCompletedMatches()) {
                                    pResult = m.getParticipant(m.getParticipantId(
                                            Games.Players.getCurrentPlayerId(gc))).getResult();
                                    if (pResult != null && pResult.getResult() ==
                                            ParticipantResult.MATCH_RESULT_WIN) {
                                        wins.put(m.getVariant(), wins.get(m.getVariant()) + 1);
                                    }
                                }

                                if (BuildConfig.DEBUG) {
                                    Logger.log("-- Wins --");
                                    for (Integer type : wins.keySet())
                                        Logger.log(type + ": " + wins.get(type));
                                }

                                if (wins.get(Game.MODE_2_PLAYER_2_SIDES) +
                                        wins.get(Game.MODE_2_PLAYER_4_SIDES) > 1) {
                                    Games.Achievements.unlock(gc, context.getString(
                                            R.string.achievement_checkmate_i));
                                }

                                if (wins.get(Game.MODE_2_PLAYER_2_SIDES) +
                                        wins.get(Game.MODE_2_PLAYER_4_SIDES) > 5) {
                                    Games.Achievements.unlock(gc, context.getString(
                                            R.string.achievement_checkmate_ii));
                                }

                                if (wins.get(Game.MODE_2_PLAYER_2_SIDES) +
                                        wins.get(Game.MODE_2_PLAYER_4_SIDES) > 10) {
                                    Games.Achievements.unlock(gc, context.getString(
                                            R.string.achievement_checkmate_iii));
                                }

                                if (wins.get(Game.MODE_4_PLAYER_TEAMS) > 1) {
                                    Games.Achievements.unlock(gc,
                                            context.getString(R.string.achievement_teamplay_i));
                                }

                                if (wins.get(Game.MODE_4_PLAYER_TEAMS) > 5) {
                                    Games.Achievements.unlock(gc, context.getString(
                                            R.string.achievement_teamplay_ii));
                                }

                                if (wins.get(Game.MODE_4_PLAYER_TEAMS) > 10) {
                                    Games.Achievements.unlock(gc, context.getString(
                                            R.string.achievement_teamplay_iii));
                                }

                            }
                        });
    }
}