Skip to content

Commit

Permalink
Merge pull request cs3217-2324#124 from sp4ce-cowboy/fix/MiscFixes
Browse files Browse the repository at this point in the history
Restructure StorageAPI and PlayerUI screen
  • Loading branch information
sp4ce-cowboy authored Apr 21, 2024
2 parents 33b31b3 + 9769a04 commit 719312f
Show file tree
Hide file tree
Showing 40 changed files with 1,212 additions and 969 deletions.
88 changes: 46 additions & 42 deletions TowerForge/TowerForge.xcodeproj/project.pbxproj

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
FirebaseApp.configure()

/// Initialize all local storage
StorageManager.initializeAllStorage()
StorageHandler.initializeLocalStorageIfNotPresent()

/// Prepare audio player to begin playing music
AudioManager.shared.setupAllAudioPlayers()
Expand Down

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions TowerForge/TowerForge/Commons/Enums/StorageEnums.swift
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ class StorageEnums {
enum StorageConflictResolution: String {
case MERGE
case KEEP_LATEST_ONLY
case PRESERVE_LOCAL
}

struct DynamicCodingKeys: CodingKey {
Expand Down
10 changes: 5 additions & 5 deletions TowerForge/TowerForge/Commons/Extensions/Double+Extensions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import Foundation

extension Double {
static var unit: Double { 1.0 }
static let unit: Double = 1.0
var half: Double { self * 0.5 }
var twice: Double { self * 2.0 }
var oneHalf: Double { self * 1.5 }
Expand All @@ -18,13 +18,13 @@ extension Double {
}

extension Int {
static var unit: Int { 1 }
static var zero: Int { 0 }
static var negativeUnit: Int { -1 }
static let unit: Int = 1
static let zero: Int = 0
static let negativeUnit: Int = -1
}

extension CGFloat {
static var unit: Double { Double.unit }
static let unit = CGFloat(Double.unit)
var half: Double { Double(self).half }
var twice: Double { Double(self).twice }
var square: Double { Double(self).square }
Expand Down
66 changes: 0 additions & 66 deletions TowerForge/TowerForge/Commons/Utilities/AbstractTypeWrapper.swift

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,9 @@ class AuthenticationManager: AuthenticationProtocol {
let userData = AuthenticationData(userId: user.uid,
email: email,
username: user.displayName)
StorageManager.onLogin(with: userData.userId) // TODO: Consider if there might be a better way to do this
// StorageManager.onLogin(with: userData.userId) // TODO: Consider if there might be a better way to do this
// Constants.CURRENT_PLAYER_ID = userData.userId
Logger.log("LOGIN: userId is \(userData.userId), email is \(userData.email)", self)
self.delegate?.onLogin()
completion(userData, nil)
}
Expand All @@ -96,7 +98,6 @@ class AuthenticationManager: AuthenticationProtocol {
do {
try Auth.auth().signOut()
self.delegate?.onLogout()
StorageManager.onLogout()
completion(nil)
} catch let error as NSError {
completion(error)
Expand All @@ -106,6 +107,7 @@ class AuthenticationManager: AuthenticationProtocol {
if let currentUser = Auth.auth().currentUser {
// User is currently logged in, fetch user data
Logger.log(String(describing: currentUser), self)

let userData = AuthenticationData(userId: currentUser.uid,
email: currentUser.email ?? "",
username: currentUser.displayName)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,12 +55,16 @@ class AuthenticationProvider {
observers.forEach { $0.onLogout() }
}

func getCurrentUserId() -> String? {
var currentUserId: String?
self.authenticationManager.getUserData { authData, _ in
currentUserId = authData?.userId
func getCurrentUserId(completion: @escaping (String?, Error?) -> Void) {
self.authenticationManager.getUserData { authData, error in
if let error = error {
Logger.log("Error retrieving CurrentUserId \(error)", self)
completion(nil, error)
} else if let playerId = authData?.userId {
Logger.log("Successfully retrieved currentUserId", self)
completion(playerId, nil)
}
}
return currentUserId
}
}

Expand Down
8 changes: 6 additions & 2 deletions TowerForge/TowerForge/GameModule/GameWorld.swift
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@ class GameWorld {
private var renderer: Renderer?
private let worldBounds: CGRect
private var popup: StatePopupNode
private var statisticsEngine = StatisticsEngine()

private var storageHandler = StorageHandler()
private var statisticsEngine: StatisticsEngine

unowned var scene: GameScene? { didSet { setUpScene() } }
unowned var delegate: SceneManagerDelegate?
Expand All @@ -33,6 +35,8 @@ class GameWorld {
powerUpSelectionNode = PowerUpSelectionNode(eventManager: gameEngine.eventManager)
grid = Grid(screenSize: worldBounds)
popup = StatePopupNode()
storageHandler = StorageHandler()
statisticsEngine = StatisticsEngine(with: storageHandler)

setUp()
}
Expand Down Expand Up @@ -126,6 +130,6 @@ extension GameWorld: GameEngineDelegate {
func onGameCompleted(gameState: GameState, gameResults: [GameResult]) {
Logger.log("\(gameState)", self)
delegate?.showGameOverScene(isWin: gameState == .WIN, results: gameResults)
statisticsEngine.finalize()
statisticsEngine.finalizeAndSave()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ class AchievementsEngine: InferenceEngine, InferenceDataDelegate {
var achievementsDatabase: AchievementsDatabase

var statisticsDatabase: StatisticsDatabase {
statisticsEngine.statistics
statisticsEngine.statisticsDatabase
}

init(_ statisticsEngine: StatisticsEngine) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ class AchievementsFactory {
static var availableAchievementTypes: [String: Achievement.Type] =
[
String(describing: FiftyKillsAchievement.self): FiftyKillsAchievement.self,
String(describing: HundredKillsAchievement.self): HundredKillsAchievement.self,
String(describing: ThousandKillsAchievement.self): ThousandKillsAchievement.self,
String(describing: CenturionAchievement.self): CenturionAchievement.self
]

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,14 @@

import Foundation

final class HundredKillsAchievement: Achievement {
var name: String = "100 Kills"
var description: String = "Attain 100 total kills in TowerForge"
final class ThousandKillsAchievement: Achievement {
var name: String = "1000 Kills"
var description: String = "Attain 1000 total kills in TowerForge"
var currentParameters: [StatisticTypeWrapper: any Statistic] = [:]

static var definedParameters: [StatisticTypeWrapper: Double] =
[
TotalKillsStatistic.asType: 200.0
TotalKillsStatistic.asType: 1_000.0
]

init(dependentStatistics: [Statistic]) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
//
// MassEffectMission.swift
// TowerForge
//
// Created by Rubesh on 20/4/24.
//

import Foundation

final class MassEffectMission: Mission {
var name: String = "Mass Effect"
var description: String = "Attain 100 Kills & Deaths in 1 game"
var currentParameters: [StatisticTypeWrapper: any Statistic]

static var definedParameters: [StatisticTypeWrapper: Double] {
[
TotalKillsStatistic.asType: 100.0,
TotalDeathsStatistic.asType: 100.0
]
}

init(dependentStatistics: [Statistic]) {
var stats: [StatisticTypeWrapper: any Statistic] = [:]
dependentStatistics.forEach { stats[$0.statisticName] = $0 }
self.currentParameters = stats
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ class MissionsEngine: InferenceEngine, InferenceDataDelegate {
unowned var statisticsEngine: StatisticsEngine
var missionsDatabase: MissionsDatabase
var statisticsDatabase: StatisticsDatabase {
statisticsEngine.statistics
statisticsEngine.statisticsDatabase
}

init(_ statisticsEngine: StatisticsEngine) {
Expand Down
3 changes: 2 additions & 1 deletion TowerForge/TowerForge/Metrics/Missions/MissionsFactory.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ class MissionsFactory {
[
String(describing: MassDamageMission.self): MassDamageMission.self,
String(describing: MassKillMission.self): MassKillMission.self,
String(describing: MassDeathMission.self): MassDeathMission.self
String(describing: MassDeathMission.self): MassDeathMission.self,
String(describing: MassEffectMission.self): MassEffectMission.self
]

static func registerMissionType<T: Mission>(_ stat: T) {
Expand Down
36 changes: 27 additions & 9 deletions TowerForge/TowerForge/Metrics/Ranking/RankingEngine.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,22 @@ import Foundation

/// The RankingEngine is responsible for generating rank and exp information.
class RankingEngine: InferenceEngine, InferenceDataDelegate {
unowned var statisticsEngine: StatisticsEngine

// TODO: Consider expanding to more formula for .e.g double exp.
static var defaultExpFormula: ((StatisticsDatabase) -> Double) = {
$0.statistics.values.map { $0.rankValue }.reduce(into: .zero) { $0 += $1 }
}

unowned var statisticsEngine: StatisticsEngine
init(_ statisticsEngine: StatisticsEngine) {
self.statisticsEngine = statisticsEngine
}

deinit {
Logger.log("DEINIT: RankingEngine is deinitialized", self)
}

var statisticsDatabase: StatisticsDatabase {
statisticsEngine.statistics
statisticsEngine.statisticsDatabase
}

var currentExp: Double {
Expand All @@ -29,8 +35,12 @@ class RankingEngine: InferenceEngine, InferenceDataDelegate {
Rank.allCases.first { $0.valueRange.contains(Int(self.currentExp)) } ?? .PRIVATE
}

var currentKd: Double {
getPermanentValueFor(TotalKillsStatistic.self) / getPermanentValueFor(TotalDeathsStatistic.self)
/// Returns the current kill/death ratio as a double between 0 and 1.
var currentKdRatio: Double {
let kills = getPermanentValueFor(TotalKillsStatistic.self)
let deaths = getPermanentValueFor(TotalDeathsStatistic.self)

return kills > 0 && deaths > 0 ? kills / deaths : .zero
}

var currentExpAsString: String {
Expand All @@ -46,13 +56,21 @@ class RankingEngine: InferenceEngine, InferenceDataDelegate {
currentRank.isOfficer()
}

init(_ statisticsEngine: StatisticsEngine) {
self.statisticsEngine = statisticsEngine
func getPermanentValueFor<T: Statistic>(_ stat: T.Type) -> Double {
statisticsDatabase.getStatistic(for: stat.asType)?.permanentValue ?? .zero
}

func updateOnReceive() { }

func getPermanentValueFor<T: Statistic>(_ stat: T.Type) -> Double {
statisticsDatabase.getStatistic(for: stat.asType)?.permanentValue ?? .zero
func percentageToNextRank() -> Double {
let minScore = currentRank.valueRange.lowerBound
let currentScore = Int(currentExp)
let maxScore = currentRank.valueRange.upperBound
let range = Double(maxScore - minScore)
let adjustedScore = Double(currentScore - minScore)
let percentageToNextRank = adjustedScore / range

return percentageToNextRank

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -54,4 +54,23 @@ final class TotalDamageDealtStatistic: Statistic {

self.init(permanentValue: value, currentValue: current)
}

func merge<T: Statistic>(with that: T) -> T? {
guard let that = that as? Self else {
return nil
}

let largerPermanent = Double.maximum(self.permanentValue, that.permanentValue)
let largerCurrent = Double.maximum(self.currentValue, that.currentValue)
let largerMaxCurrent = Double.maximum(self.maximumCurrentValue, that.maximumCurrentValue)

guard let stat = Self(permanentValue: largerPermanent,
currentValue: largerCurrent,
maxCurrentValue: largerMaxCurrent) as? T else {
Logger.log("Statistic merging failed for \(self.toString())", self)
return nil
}

return stat
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -55,4 +55,23 @@ final class TotalDeathsStatistic: Statistic {
self.init(permanentValue: value, currentValue: current)
}

func merge<T: Statistic>(with that: T) -> T? {
guard let that = that as? Self else {
return nil
}

let largerPermanent = Double.maximum(self.permanentValue, that.permanentValue)
let largerCurrent = Double.maximum(self.currentValue, that.currentValue)
let largerMaxCurrent = Double.maximum(self.maximumCurrentValue, that.maximumCurrentValue)

guard let stat = Self(permanentValue: largerPermanent,
currentValue: largerCurrent,
maxCurrentValue: largerMaxCurrent) as? T else {
Logger.log("Statistic merging failed for \(self.toString())", self)
return nil
}

return stat
}

}
Loading

0 comments on commit 719312f

Please sign in to comment.