Skip to content

Instantly share code, notes, and snippets.

@reefwing
Forked from juaxix/aGameCenter_Codea.h
Created October 14, 2012 04:19
Show Gist options
  • Save reefwing/3887282 to your computer and use it in GitHub Desktop.
Save reefwing/3887282 to your computer and use it in GitHub Desktop.
Tutorial 21 - Game Center for Codea (multiple Leaderboards and Achievements)
//
// aGameCenter_Codea.h
//
// Created by Juan Belón on 28/05/12
// Games -> http://www.xixgames.com
// LGPL - @juaxix - Codea connection!
//
// Modified by Reefwing Software on 14/10/12
// http://www.reefwing.com.au
// @reefwing on the Codea Forums
//
// Version: 1.5
// - Multiple Leaderboard (Easy, Medium & Hard) access added
// - Achievements added.
// 1.6
// - Modified for universal apps (http://codeatuts.blogspot.com.au/2012/10/tutorial-22-building-universal-app-in.html)
// - New showLeaderBoard: (int)ident method
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#import <Foundation/Foundation.h>
#import <GameKit/GameKit.h>
#import <AVFoundation/AVAudioPlayer.h>
@interface aGameCenter_Codea : NSObject <GKLeaderboardViewControllerDelegate, AVAudioPlayerDelegate, GKAchievementViewControllerDelegate>
{
bool hasGameCenter;
bool playing;
AVAudioPlayer *player;
}
- (void) start;
- (void) authenticateLocalPlayer;
- (void) registerForAuthenticationNotification;
- (void) authenticationChanged;
- (BOOL) isGameCenterAvailable;
- (void) leaderboardViewControllerDidFinish: (GKLeaderboardViewController *)viewController;
- (void) showAchievements;
- (void) achievementViewControllerDidFinish:(GKAchievementViewController *)viewController;
- (void) resetAchievements;
- (void) reportAchievementIdentifier: (int) ident;
- (void) showLeaderboard: (int)ident;
- (void) showEasyLeaderboard;
- (void) showMediumLeaderboard;
- (void) showHardLeaderboard;
- (void) reportEasyScore:(int) score;
- (void) reportMediumScore:(int) score;
- (void) reportHardScore:(int) score;
- (void) playMusic:(int) songNumber;
- (void) stopMusic;
@end
//
// aGameCenter_Codea.m
//
// Created by Juan Belón on 28/05/12
// Games -> http://www.xixgames.com
// LGPL - @juaxix - Codea connection!
//
// Modified by Reefwing Software on 14/10/12
// http://www.reefwing.com.au
// @reefwing on the Codea Forums
//
// Version: 1.5
// - Multiple Leaderboard (Easy, Medium & Hard) access added
// - Achievements added.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#import "aGameCenter_Codea.h"
#import "SharedRenderer.h"
@implementation aGameCenter_Codea
- (id)init
{
self = [super init];
player = [[AVAudioPlayer alloc] init];
playing = false;
return self;
}
- (void)dealloc
{
[player release];
[super dealloc];
}
- (void) start
{
//Game Center
hasGameCenter = false;
[self authenticateLocalPlayer];
}
- (BOOL) isGameCenterAvailable
{
// Check for presence of GKLocalPlayer API.
Class gcClass = (NSClassFromString(@"GKLocalPlayer"));
// The device must be running running iOS 4.1 or later.
NSString *reqSysVer = @"4.1";
NSString *currSysVer = [[UIDevice currentDevice] systemVersion];
BOOL osVersionSupported = ([currSysVer compare:reqSysVer options:NSNumericSearch] != NSOrderedAscending);
if (gcClass && osVersionSupported)
NSLog(@"Game Center is Available");
else
NSLog(@"Game Center is not Available");
return (gcClass && osVersionSupported);
}
- (void)authenticateLocalPlayer
{
if(![self isGameCenterAvailable])
{
hasGameCenter = false;
return;
}
[[GKLocalPlayer localPlayer] authenticateWithCompletionHandler:^(NSError *error)
{
if (error == nil)
{
[self registerForAuthenticationNotification];
hasGameCenter = true;
NSLog(@"Game Center - local player authenticated.");
}else
{
hasGameCenter = false;
}
}];
}
- (void)registerForAuthenticationNotification
{
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc addObserver: self selector:@selector(authenticationChanged) name:GKPlayerAuthenticationDidChangeNotificationName object:nil];
}
- (void)authenticationChanged
{
if([self isGameCenterAvailable ])
{
return;
}
if ([GKLocalPlayer localPlayer].isAuthenticated)
{
hasGameCenter = true;
}else
{
hasGameCenter = false;
}
}
// Achievement Methods
- (void) reportAchievementIdentifier: (int) ident
{
NSString *identifier;
// INSERT YOUR ACHIEVEMENT IDENTIFIERS BELOW
switch (ident)
{
case 1:
identifier = @"Easy Winner";
break;
case 2:
identifier = @"Medium Winner";
break;
case 3:
identifier = @"Hard Winner";
break;
case 4:
identifier = @"Boom";
break;
case 5:
identifier = @"Bad Luck";
break;
case 6:
identifier = @"Decathlon";
break;
case 7:
identifier = @"Centurion";
break;
default:
NSLog(@"Warning Unknown Achievement");
break;
}
NSLog(@"Achievement complete: %@", identifier);
GKAchievement *achievement = [[GKAchievement alloc] initWithIdentifier: identifier];
if (achievement)
{
achievement.showsCompletionBanner = YES;
achievement.percentComplete = 100.0;
[achievement reportAchievementWithCompletionHandler:^(NSError *error)
{
if (error != nil)
{
NSLog(@"Error in reporting achievements: %@", error);
}
}];
}
}
- (void)showAchievements
{
GKAchievementViewController *achievements = [[GKAchievementViewController alloc] init];
if (achievements != nil)
{
achievements.achievementDelegate = self;
[[SharedRenderer renderer] presentViewController: achievements animated: YES completion:nil];
}
[achievements release];
}
- (void)achievementViewControllerDidFinish:(GKAchievementViewController *)viewController
{
[[SharedRenderer renderer] dismissViewControllerAnimated:YES completion:nil];
[[SharedRenderer renderer] startAnimation];
}
- (void) resetAchievements
{
// You may want to allow the player to reset their progress on achievements in your game.
// First, this method clears any locally cached achievement objects created by you.
// Then, it calls Game Kit to reset the player’s progress stored on Game Center.
//
// Clear all locally saved achievement objects - Enter your code to clear locally saved achievements below.
// YOUR CODE GOES HERE
// Clear all progress saved on Game Center.
[GKAchievement resetAchievementsWithCompletionHandler:^(NSError *error)
{
if (error != nil)
// handle the error.
NSLog(@"Game Center: Error Resetting Achievements - %@", [error localizedDescription]);
else
NSLog(@"Game Center - Achievements Reset.");
}];
}
// Leaderboard Methods
- (void)showLeaderboard: (int)ident
{
NSString *identifier;
// INSERT YOUR ACHIEVEMENT IDENTIFIERS BELOW
switch (ident)
{
case 1:
identifier = @"Easy Difficulty";
break;
case 2:
identifier = @"Medium Difficulty";
break;
case 3:
identifier = @"Hard Difficulty";
break;
default:
NSLog(@"Warning Unknown Leader Board");
break;
}
GKLeaderboardViewController *leaderBoardCont = [[GKLeaderboardViewController alloc] init];
if (leaderBoardCont)
{
// INSERT YOUR LEADERBOARD IDENTIFIER IN THE LINE BELOW
leaderBoardCont.category=identifier;
leaderBoardCont.timeScope=GKLeaderboardTimeScopeToday;
leaderBoardCont.leaderboardDelegate=self;
[[SharedRenderer renderer] presentModalViewController:leaderBoardCont animated:YES];
}
}
- (void)showEasyLeaderboard
{
GKLeaderboardViewController *leaderBoardCont = [[GKLeaderboardViewController alloc] init];
if (leaderBoardCont)
{
// INSERT YOUR LEADERBOARD IDENTIFIER IN THE LINE BELOW
leaderBoardCont.category=@"Easy Difficulty";
leaderBoardCont.timeScope=GKLeaderboardTimeScopeToday;
leaderBoardCont.leaderboardDelegate=self;
[[SharedRenderer renderer] presentModalViewController:leaderBoardCont animated:YES];
}
}
- (void)showMediumLeaderboard
{
GKLeaderboardViewController *leaderBoardCont = [[GKLeaderboardViewController alloc] init];
if (leaderBoardCont)
{
// INSERT YOUR LEADERBOARD IDENTIFIER IN THE LINE BELOW
leaderBoardCont.category=@"Medium Difficulty";
leaderBoardCont.timeScope=GKLeaderboardTimeScopeToday;
leaderBoardCont.leaderboardDelegate=self;
[[SharedRenderer renderer] presentModalViewController:leaderBoardCont animated:YES];
}
}
- (void)showHardLeaderboard
{
GKLeaderboardViewController *leaderBoardCont = [[GKLeaderboardViewController alloc] init];
if (leaderBoardCont)
{
// INSERT YOUR LEADERBOARD IDENTIFIER IN THE LINE BELOW
leaderBoardCont.category=@"Hard Difficulty";
leaderBoardCont.timeScope=GKLeaderboardTimeScopeToday;
leaderBoardCont.leaderboardDelegate=self;
[[SharedRenderer renderer] presentModalViewController:leaderBoardCont animated:YES];
}
}
- (void)leaderboardViewControllerDidFinish:(GKLeaderboardViewController *)viewController
{
[[SharedRenderer renderer] dismissModalViewControllerAnimated:YES];
[[SharedRenderer renderer] startAnimation];
}
- (void) reportEasyScore:(int) score
{
// INSERT YOUR LEADERBOARD IDENTIFIER IN THE LINE BELOW
GKScore *scoreReporter = [[[GKScore alloc] initWithCategory: @"Easy Difficulty"] autorelease];
if(scoreReporter)
{
scoreReporter.value = score;
[scoreReporter reportScoreWithCompletionHandler:^(NSError *error)
{
if (error != nil)
{
// handle the reporting error
NSLog(@"Game Center: Error Reporting Easy Score - %@", [error localizedDescription]);
}
}];
}
}
- (void)reportMediumScore:(int) score
{
// INSERT YOUR LEADERBOARD IDENTIFIER IN THE LINE BELOW
GKScore *scoreReporter = [[[GKScore alloc] initWithCategory: @"Medium Difficulty"] autorelease];
if(scoreReporter)
{
scoreReporter.value = score;
[scoreReporter reportScoreWithCompletionHandler:^(NSError *error)
{
if (error != nil)
{
// handle the reporting error
NSLog(@"Game Center: Error Reporting Medium Score - %@", [error localizedDescription]);
}
}];
}
}
- (void)reportHardScore:(int) score
{
// INSERT YOUR LEADERBOARD IDENTIFIER IN THE LINE BELOW
GKScore *scoreReporter = [[[GKScore alloc] initWithCategory: @"Hard Difficulty"] autorelease];
if(scoreReporter)
{
scoreReporter.value = score;
[scoreReporter reportScoreWithCompletionHandler:^(NSError *error)
{
if (error != nil)
{
// handle the reporting error
NSLog(@"Game Center: Error Reporting Hard Score - %@", [error localizedDescription]);
}
}];
}
}
// Music Play and Stop Methods
- (void)playMusic:(int) songNumber
{
NSString* resourcePath = [[NSBundle mainBundle] resourcePath];
NSString* song = [[NSString alloc] initWithString:@""];
NSError* err;
switch (songNumber)
{
case 1: //menu song
song = @"/menu.MP3";
break;
case 2:
song = @"/game.MP3";
break;
case 3:
song = @"/winner.MP3";
default:
break;
}
if ([song isEqualToString:@""])
{
return ;
}
//NSLog(@"Playing song %d: %@",songNumber,song);
resourcePath = [resourcePath stringByAppendingString:song];
//NSLog(@"Path to play: %@", resourcePath);
//Initialize our player pointing to the path to our resource
if (playing && player)
{
[player stop];
playing = false;
}
player = [[AVAudioPlayer alloc] initWithContentsOfURL:
[NSURL fileURLWithPath:resourcePath] error:&err];
if( err )
{
//bail!
NSLog(@"Failed with reason: %@", [err localizedDescription]);
}
else
{
//set our delegate and begin playback
player.delegate = self;
[player prepareToPlay];
player.numberOfLoops = -1; //One Infinite Loop (music!) ;)
[player play];
playing = true;
}
}
- (void)stopMusic
{
if (playing)
{
[player stop];
playing = false;
}
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment