From c517a36adc1083e3355c034adf91e5d3a9e647ed Mon Sep 17 00:00:00 2001 From: Simon Kellner Date: Wed, 10 Jun 2020 18:32:31 +0200 Subject: [PATCH] Add Leaderboard managing methods --- GoldWars/GoldWars/GameCenterManager.swift | 71 +++++++++++++++++++++++ 1 file changed, 71 insertions(+) diff --git a/GoldWars/GoldWars/GameCenterManager.swift b/GoldWars/GoldWars/GameCenterManager.swift index 8d21a9f..f6b1976 100644 --- a/GoldWars/GoldWars/GameCenterManager.swift +++ b/GoldWars/GoldWars/GameCenterManager.swift @@ -109,6 +109,77 @@ final class GameCenterManager: NSObject, GKMatchmakerViewControllerDelegate, GKG } } + func submitLeaderboardScore(identifier: String, score: Int64) { + let reportedScore = GKScore(leaderboardIdentifier: identifier) + reportedScore.value = score + GKScore.report([reportedScore]) { (error) in + guard error == nil else { + print(error?.localizedDescription ?? "") + return + } + } + } + + func calculateLeaderboardScore(identifier: String, scoreOffset: Int64) { + GKLeaderboard.loadLeaderboards { (leaderboards: [GKLeaderboard]?, err: Error?) in + leaderboards?.forEach({ (leaderboard: GKLeaderboard) in + if leaderboard.identifier == identifier { + leaderboard.loadScores { (scores: [GKScore]?, err: Error?) in + scores?.forEach({ (score: GKScore) in + if score.player == self.localPlayer { + score.value += scoreOffset + GKScore.report([score]) { (error) in + guard error == nil else { + print(error?.localizedDescription ?? "") + return + } + } + } + }) + } + } + }) + } + } + + //TODO: not finished -> DELETE if not usefull + // Possible way to implement matchmaking based on 2 players + // can be changed into method with fixed leaderboard and offset, boolean hasWon: true/false to calculate outcome of a match + func calculateLeaderboardScoreExperimentalMatchmaking(identifier: String, scoreOffset: Int64, opponentPlayer: GKPlayer) { + // Iterate through leaderboards + GKLeaderboard.loadLeaderboards { (leaderboards: [GKLeaderboard]?, err: Error?) in + leaderboards?.forEach({ (leaderboard: GKLeaderboard) in + if leaderboard.identifier == identifier { + leaderboard.loadScores { (scores: [GKScore]?, err: Error?) in + // Iterate through scores + var currentScore: GKScore = GKScore.init() + currentScore.value = -1 + var opponetScore: GKScore = GKScore.init() + currentScore.value = 0 + // Get scores of self and opponent + scores?.forEach({ (score: GKScore) in + if score.player == self.localPlayer { + currentScore = score + opponetScore = score + } + if score.player == opponentPlayer { + opponetScore = score + } + }) + // do silly calculation + currentScore.value += scoreOffset + (opponetScore.value - currentScore.value) + GKScore.report([currentScore]) { (error) in + guard error == nil else { + print(error?.localizedDescription ?? "") + return + } + } + } + } + }) + } + } + func match(_ match: GKMatch, didReceive data: Data, fromRemotePlayer player: GKPlayer) { if myMatch != match { return } let jsonDecoder = JSONDecoder()