text
stringlengths
1
372
import 'dart:async';
import 'package:games_services/games_services.dart';
import 'package:logging/logging.dart';
/// allows awarding achievements and leaderboard scores,
/// and also showing the platforms' UI overlays for achievements
/// and leaderboards.
///
/// a facade of `package:games_services`.
class GamesServicesController {
static final logger _log = Logger('GamesServicesController');
final completer<bool> _signedInCompleter = completer();
future<bool> get signedIn => _signedInCompleter.future;
/// unlocks an achievement on game center / play games.
///
/// you must provide the achievement ids via the [ios] and [android]
/// parameters.
///
/// does nothing when the game isn't signed into the underlying
/// games service.
future<void> awardAchievement(
{required string iOS, required string android}) async {
if (!await signedIn) {
_log.warning('Trying to award achievement when not logged in.');
return;
}
try {
await GamesServices.unlock(
achievement: achievement(
androidID: android,
iOSID: iOS,
),
);
} catch (e) {
_log.severe('Cannot award achievement: $e');
}
}
/// signs into the underlying games service.
future<void> initialize() async {
try {
await GamesServices.signIn();
// the API is unclear so we're checking to be sure. the above call
// returns a string, not a boolean, and there's no documentation
// as to whether every non-error result means we're safely signed in.
final signedIn = await GamesServices.isSignedIn;
_signedInCompleter.complete(signedIn);
} catch (e) {
_log.severe('Cannot log into GamesServices: $e');
_signedInCompleter.complete(false);
}
}
/// launches the platform's UI overlay with achievements.
future<void> showAchievements() async {
if (!await signedIn) {
_log.severe('Trying to show achievements when not logged in.');
return;
}
try {
await GamesServices.showAchievements();
} catch (e) {
_log.severe('Cannot show achievements: $e');
}
}
/// launches the platform's UI overlay with leaderboard(s).
future<void> showLeaderboard() async {
if (!await signedIn) {
_log.severe('Trying to show leaderboard when not logged in.');
return;
}
try {
await GamesServices.showLeaderboards(
// TODO: when ready, change both these leaderboard IDs.
iOSLeaderboardID: 'some_id_from_app_store',
androidLeaderboardID: 'some_id_from_gplay',
);
} catch (e) {
_log.severe('Cannot show leaderboard: $e');
}
}
/// submits [score] to the leaderboard.
future<void> submitLeaderboardScore(int score) async {
if (!await signedIn) {
_log.warning('Trying to submit leaderboard when not logged in.');
return;
}
_log.info('Submitting $score to leaderboard.');
try {
await GamesServices.submitScore(
score: score(
// TODO: when ready, change these leaderboard IDs.
iOSLeaderboardID: 'some_id_from_app_store',
androidLeaderboardID: 'some_id_from_gplay',
value: score,
),
);
} catch (e) {
_log.severe('Cannot submit leaderboard score: $e');
}
}
}
<code_end>