From 99b6843606497f1518f691e930cbe280320c51a6 Mon Sep 17 00:00:00 2001 From: 82joni1bif <82joni1bif@hft-stuttgart.de> Date: Sun, 10 May 2020 21:58:42 +0200 Subject: [PATCH 01/28] Create first version of Datatransfermodel --- GoldWars/GoldWars.xcodeproj/project.pbxproj | 16 +++--- GoldWars/GoldWars/Entities/Base.swift | 2 + GoldWars/GoldWars/MatchmakingHelper.swift | 22 +++++++- GoldWars/GoldWars/MessageProtocol.swift | 60 +++++++++++++++++++++ 4 files changed, 93 insertions(+), 7 deletions(-) create mode 100644 GoldWars/GoldWars/MessageProtocol.swift diff --git a/GoldWars/GoldWars.xcodeproj/project.pbxproj b/GoldWars/GoldWars.xcodeproj/project.pbxproj index ebaec53..6a647d3 100644 --- a/GoldWars/GoldWars.xcodeproj/project.pbxproj +++ b/GoldWars/GoldWars.xcodeproj/project.pbxproj @@ -38,6 +38,7 @@ 9EA3ABED245C8143006BC61D /* ModalBackgroundComponent.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9EA3ABEC245C8143006BC61D /* ModalBackgroundComponent.swift */; }; 9EA3ABEF245C834B006BC61D /* ModalContentComponent.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9EA3ABEE245C834B006BC61D /* ModalContentComponent.swift */; }; 9EBFD7552462CF5A00E1E219 /* SliderComponent.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9EBFD7542462CF5A00E1E219 /* SliderComponent.swift */; }; + 9EC239E1246878A900952F74 /* MessageProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9EC239E0246878A900952F74 /* MessageProtocol.swift */; }; 9EC7E48B2461FBF700396BCD /* SliderNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9EC7E48A2461FBF700396BCD /* SliderNode.swift */; }; 9EC86B9F245C88A300796EF3 /* Modal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9EC86B9E245C88A300796EF3 /* Modal.swift */; }; 9EC86BA6245C8AD000796EF3 /* ModalType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9EC86BA5245C8AD000796EF3 /* ModalType.swift */; }; @@ -94,6 +95,7 @@ 9EA3ABEC245C8143006BC61D /* ModalBackgroundComponent.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ModalBackgroundComponent.swift; sourceTree = ""; }; 9EA3ABEE245C834B006BC61D /* ModalContentComponent.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ModalContentComponent.swift; sourceTree = ""; }; 9EBFD7542462CF5A00E1E219 /* SliderComponent.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SliderComponent.swift; sourceTree = ""; }; + 9EC239E0246878A900952F74 /* MessageProtocol.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MessageProtocol.swift; sourceTree = ""; }; 9EC7E48A2461FBF700396BCD /* SliderNode.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SliderNode.swift; sourceTree = ""; }; 9EC86B9E245C88A300796EF3 /* Modal.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Modal.swift; sourceTree = ""; }; 9EC86BA5245C8AD000796EF3 /* ModalType.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ModalType.swift; sourceTree = ""; }; @@ -157,6 +159,7 @@ 110360D2244B101A008610AF /* AppDelegate.swift */, 110360DA244B101A008610AF /* GameViewController.swift */, 110360DF244B101B008610AF /* Assets.xcassets */, + 9EC239E0246878A900952F74 /* MessageProtocol.swift */, 110360E4244B101B008610AF /* Info.plist */, AE151588245F18EF001D363E /* MatchmakingHelper.swift */, 3EBD242B245D8044003CECE7 /* GameCenterHelper.swift */, @@ -367,6 +370,7 @@ 9E78ACB8245CB75B00526FF7 /* TeamComponent.swift in Sources */, 9EA3ABEF245C834B006BC61D /* ModalContentComponent.swift in Sources */, 9EC86BA6245C8AD000796EF3 /* ModalType.swift in Sources */, + 9EC239E1246878A900952F74 /* MessageProtocol.swift in Sources */, 9E78ACBE245CC9C000526FF7 /* AtkBoostSkillComponent.swift in Sources */, 9E78ACC4245CCA3600526FF7 /* SpySkillComponent.swift in Sources */, 9EA3ABEB245C6DFA006BC61D /* BaseNode.swift in Sources */, @@ -557,8 +561,8 @@ buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CODE_SIGN_ENTITLEMENTS = GoldWars/GoldWars.entitlements; - CODE_SIGN_IDENTITY = "iPhone Developer"; - CODE_SIGN_STYLE = Manual; + CODE_SIGN_IDENTITY = "Apple Development"; + CODE_SIGN_STYLE = Automatic; CURRENT_PROJECT_VERSION = 3; DEVELOPMENT_TEAM = DDKFQG46BQ; INFOPLIST_FILE = GoldWars/Info.plist; @@ -569,7 +573,7 @@ MARKETING_VERSION = 1.0; PRODUCT_BUNDLE_IDENTIFIER = de.hft.stuttgart.ip2.goldwars; PRODUCT_NAME = "$(TARGET_NAME)"; - PROVISIONING_PROFILE_SPECIFIER = "Developer Profile"; + PROVISIONING_PROFILE_SPECIFIER = ""; SWIFT_VERSION = 5.0; TARGETED_DEVICE_FAMILY = 2; }; @@ -580,8 +584,8 @@ buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CODE_SIGN_ENTITLEMENTS = GoldWars/GoldWars.entitlements; - CODE_SIGN_IDENTITY = "iPhone Developer"; - CODE_SIGN_STYLE = Manual; + CODE_SIGN_IDENTITY = "Apple Development"; + CODE_SIGN_STYLE = Automatic; CURRENT_PROJECT_VERSION = 3; DEVELOPMENT_TEAM = DDKFQG46BQ; INFOPLIST_FILE = GoldWars/Info.plist; @@ -592,7 +596,7 @@ MARKETING_VERSION = 1.0; PRODUCT_BUNDLE_IDENTIFIER = de.hft.stuttgart.ip2.goldwars; PRODUCT_NAME = "$(TARGET_NAME)"; - PROVISIONING_PROFILE_SPECIFIER = "Developer Profile"; + PROVISIONING_PROFILE_SPECIFIER = ""; SWIFT_VERSION = 5.0; TARGETED_DEVICE_FAMILY = 2; }; diff --git a/GoldWars/GoldWars/Entities/Base.swift b/GoldWars/GoldWars/Entities/Base.swift index 70fe75d..97c4412 100644 --- a/GoldWars/GoldWars/Entities/Base.swift +++ b/GoldWars/GoldWars/Entities/Base.swift @@ -32,7 +32,9 @@ class Base: GKEntity { base.changeOwnerShip = true self.unitCount -= units base.unitCount += units + MultiplayerNetwork.sharedInstance.sendPlayerMove(unitcount: units) return [self, base] + } required init?(coder: NSCoder) { diff --git a/GoldWars/GoldWars/MatchmakingHelper.swift b/GoldWars/GoldWars/MatchmakingHelper.swift index 48628ce..8ad1138 100644 --- a/GoldWars/GoldWars/MatchmakingHelper.swift +++ b/GoldWars/GoldWars/MatchmakingHelper.swift @@ -100,12 +100,32 @@ class MatchmakingHelper: NSObject, GKMatchmakerViewControllerDelegate, GKMatchDe startMatch() } } - + + + func decode(data: NSData) -> T { + let pointer = UnsafeMutablePointer.allocate(capacity: MemoryLayout.size) + data.getBytes(pointer, length: MemoryLayout.size) + return pointer.move() + } + /* Vom match erhaltene Spielerdaten */ private func match(match: GKMatch!, didReceiveData data: NSData!,fromPlayer playerID: String!) { if mpMatch != match { return } + print("Daten empfangen!") + + let pointer = UnsafeMutablePointer.allocate(capacity: MemoryLayout.size) + data.getBytes(pointer, length: MemoryLayout.size) + let message = pointer.move() + + switch message.messageType{ + case MessageType.PlayerMove: + let playerMove = message as! PlayerMove + let count = playerMove.unitCount + + } + delegate?.matchReceivedData(match: match, data: data, fromPlayer: playerID) } diff --git a/GoldWars/GoldWars/MessageProtocol.swift b/GoldWars/GoldWars/MessageProtocol.swift new file mode 100644 index 0000000..62d7e3d --- /dev/null +++ b/GoldWars/GoldWars/MessageProtocol.swift @@ -0,0 +1,60 @@ +// +// MessageProtocol.swift +// GoldWars +// +// Created by Niko Jochim on 10.05.20. +// Copyright © 2020 SP2. All rights reserved. +// + +import GameplayKit +import Foundation + + +protocol MultiplayerProtocol { + +} +enum MessageType : Int{ + case PlayerMove + +} + +protocol Message { + var messageType:MessageType { get } +} + + + +struct PlayerMove : Message{ + let messageType: MessageType + +// let message: Message + //let fromBase: //was? + //let toBase: //was? + let unitCount: Int +} + +class MultiplayerNetwork: NSObject{ + static let sharedInstance = MultiplayerNetwork() + + + func sendData(data: NSData) { + let mmHelper = MatchmakingHelper.sharedInstance + if let multiplayerMatch = mmHelper.mpMatch { + do { + try multiplayerMatch.sendData(toAllPlayers: data as Data, with: .reliable) + } catch { + print("Tim war am Werk") + } + } + } + + func sendPlayerMove(unitcount:Int) { + var playerMoveMsg = PlayerMove(messageType: MessageType.PlayerMove, unitCount: unitcount) + + + let data = NSData(bytes: &playerMoveMsg, length: MemoryLayout.size) + + sendData(data: data) + } + +} From 106a0fe6de335808a7c78b31c3d72d825f5f2eb1 Mon Sep 17 00:00:00 2001 From: 82joni1bif <82joni1bif@hft-stuttgart.de> Date: Sun, 10 May 2020 22:00:17 +0200 Subject: [PATCH 02/28] add print for debug --- GoldWars/GoldWars/MatchmakingHelper.swift | 2 ++ 1 file changed, 2 insertions(+) diff --git a/GoldWars/GoldWars/MatchmakingHelper.swift b/GoldWars/GoldWars/MatchmakingHelper.swift index 8ad1138..16b2fee 100644 --- a/GoldWars/GoldWars/MatchmakingHelper.swift +++ b/GoldWars/GoldWars/MatchmakingHelper.swift @@ -123,6 +123,8 @@ class MatchmakingHelper: NSObject, GKMatchmakerViewControllerDelegate, GKMatchDe case MessageType.PlayerMove: let playerMove = message as! PlayerMove let count = playerMove.unitCount + print("Angekommen \(count)") + } From d99878eb472ab36c15e0db7e111fb515b8676ee7 Mon Sep 17 00:00:00 2001 From: 82joni1bif <82joni1bif@hft-stuttgart.de> Date: Sun, 10 May 2020 22:36:18 +0200 Subject: [PATCH 03/28] TEST: change Datamodel from NSData to Data --- GoldWars/GoldWars/MatchmakingHelper.swift | 9 +++++---- GoldWars/GoldWars/MessageProtocol.swift | 6 +++--- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/GoldWars/GoldWars/MatchmakingHelper.swift b/GoldWars/GoldWars/MatchmakingHelper.swift index 16b2fee..bc557c3 100644 --- a/GoldWars/GoldWars/MatchmakingHelper.swift +++ b/GoldWars/GoldWars/MatchmakingHelper.swift @@ -111,12 +111,13 @@ class MatchmakingHelper: NSObject, GKMatchmakerViewControllerDelegate, GKMatchDe /* Vom match erhaltene Spielerdaten */ - private func match(match: GKMatch!, didReceiveData data: NSData!,fromPlayer playerID: String!) { - if mpMatch != match { return } + private func match(match: GKMatch!, didReceiveData data: Data,fromPlayer playerID: String!) { print("Daten empfangen!") + if mpMatch != match { return } + let pointer = UnsafeMutablePointer.allocate(capacity: MemoryLayout.size) - data.getBytes(pointer, length: MemoryLayout.size) + let message = pointer.move() switch message.messageType{ @@ -128,7 +129,7 @@ class MatchmakingHelper: NSObject, GKMatchmakerViewControllerDelegate, GKMatchDe } - delegate?.matchReceivedData(match: match, data: data, fromPlayer: playerID) + //delegate?.matchReceivedData(match: match, data: data, fromPlayer: playerID) } diff --git a/GoldWars/GoldWars/MessageProtocol.swift b/GoldWars/GoldWars/MessageProtocol.swift index 62d7e3d..f47f0cd 100644 --- a/GoldWars/GoldWars/MessageProtocol.swift +++ b/GoldWars/GoldWars/MessageProtocol.swift @@ -37,11 +37,11 @@ class MultiplayerNetwork: NSObject{ static let sharedInstance = MultiplayerNetwork() - func sendData(data: NSData) { + func sendData(data: Data) { let mmHelper = MatchmakingHelper.sharedInstance if let multiplayerMatch = mmHelper.mpMatch { do { - try multiplayerMatch.sendData(toAllPlayers: data as Data, with: .reliable) + try multiplayerMatch.sendData(toAllPlayers: data, with: .reliable) } catch { print("Tim war am Werk") } @@ -52,7 +52,7 @@ class MultiplayerNetwork: NSObject{ var playerMoveMsg = PlayerMove(messageType: MessageType.PlayerMove, unitCount: unitcount) - let data = NSData(bytes: &playerMoveMsg, length: MemoryLayout.size) + let data = Data(bytes: &playerMoveMsg, count: MemoryLayout.size) sendData(data: data) } From fb01faa1e5b6ed5867578848623249d56bbf50b7 Mon Sep 17 00:00:00 2001 From: Niko Jochim <82joni1bif@hft-stuttgart.de> Date: Wed, 13 May 2020 13:34:34 +0200 Subject: [PATCH 04/28] TEST: Datamodel --- GoldWars/GoldWars/MessageProtocol.swift | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/GoldWars/GoldWars/MessageProtocol.swift b/GoldWars/GoldWars/MessageProtocol.swift index f47f0cd..23ef038 100644 --- a/GoldWars/GoldWars/MessageProtocol.swift +++ b/GoldWars/GoldWars/MessageProtocol.swift @@ -33,10 +33,12 @@ struct PlayerMove : Message{ let unitCount: Int } -class MultiplayerNetwork: NSObject{ +class MultiplayerNetwork{ static let sharedInstance = MultiplayerNetwork() + + func sendData(data: Data) { let mmHelper = MatchmakingHelper.sharedInstance if let multiplayerMatch = mmHelper.mpMatch { From d553b72dafb1c07c3d0146f8bfa33a783cb3e0f8 Mon Sep 17 00:00:00 2001 From: Niko Jochim <82joni1bif@hft-stuttgart.de> Date: Wed, 13 May 2020 14:59:20 +0200 Subject: [PATCH 05/28] Change Datamodel to JSON --- GoldWars/GoldWars/MatchmakingHelper.swift | 30 +++++++---------------- GoldWars/GoldWars/MessageProtocol.swift | 11 +++------ 2 files changed, 12 insertions(+), 29 deletions(-) diff --git a/GoldWars/GoldWars/MatchmakingHelper.swift b/GoldWars/GoldWars/MatchmakingHelper.swift index bc557c3..26f0c00 100644 --- a/GoldWars/GoldWars/MatchmakingHelper.swift +++ b/GoldWars/GoldWars/MatchmakingHelper.swift @@ -102,37 +102,24 @@ class MatchmakingHelper: NSObject, GKMatchmakerViewControllerDelegate, GKMatchDe } - func decode(data: NSData) -> T { - let pointer = UnsafeMutablePointer.allocate(capacity: MemoryLayout.size) - data.getBytes(pointer, length: MemoryLayout.size) - return pointer.move() - } /* Vom match erhaltene Spielerdaten + */ - private func match(match: GKMatch!, didReceiveData data: Data,fromPlayer playerID: String!) { + + func match(_ match: GKMatch, didReceive data: Data, fromRemotePlayer player: GKPlayer) { print("Daten empfangen!") if mpMatch != match { return } + let jsonDecoder = JSONDecoder() - let pointer = UnsafeMutablePointer.allocate(capacity: MemoryLayout.size) - - let message = pointer.move() - - switch message.messageType{ - case MessageType.PlayerMove: - let playerMove = message as! PlayerMove - let count = playerMove.unitCount - print("Angekommen \(count)") - - + if let message = try? jsonDecoder.decode(PlayerMove.self, from: data) { + let count = message.unitCount + print("Angekommen \(count)") } + } - //delegate?.matchReceivedData(match: match, data: data, fromPlayer: playerID) - - } - /* Verbindung/Matchmaking ist fehlgeschlagen */ @@ -147,6 +134,7 @@ class MatchmakingHelper: NSObject, GKMatchmakerViewControllerDelegate, GKMatchDe /* Wird beim ändern des States/Zustands des Spielers aufgerufen udn gibt dessen Zustand zurück. */ + func match(_ match: GKMatch, player: GKPlayer, didChange state: GKPlayerConnectionState) { if mpMatch != match { return diff --git a/GoldWars/GoldWars/MessageProtocol.swift b/GoldWars/GoldWars/MessageProtocol.swift index 23ef038..3d6d14f 100644 --- a/GoldWars/GoldWars/MessageProtocol.swift +++ b/GoldWars/GoldWars/MessageProtocol.swift @@ -9,22 +9,17 @@ import GameplayKit import Foundation - -protocol MultiplayerProtocol { - -} -enum MessageType : Int{ +enum MessageType : Int,Codable{ case PlayerMove } -protocol Message { +protocol Message :Codable{ var messageType:MessageType { get } } +struct PlayerMove : Message,Codable{ - -struct PlayerMove : Message{ let messageType: MessageType // let message: Message From a8e0bac437f7b3090d35c2a7344c7433f7e5e81b Mon Sep 17 00:00:00 2001 From: Niko Jochim <82joni1bif@hft-stuttgart.de> Date: Wed, 13 May 2020 15:07:23 +0200 Subject: [PATCH 06/28] Change send modifications --- GoldWars/GoldWars/MessageProtocol.swift | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/GoldWars/GoldWars/MessageProtocol.swift b/GoldWars/GoldWars/MessageProtocol.swift index 3d6d14f..21ed95c 100644 --- a/GoldWars/GoldWars/MessageProtocol.swift +++ b/GoldWars/GoldWars/MessageProtocol.swift @@ -46,12 +46,10 @@ class MultiplayerNetwork{ } func sendPlayerMove(unitcount:Int) { - var playerMoveMsg = PlayerMove(messageType: MessageType.PlayerMove, unitCount: unitcount) - - - let data = Data(bytes: &playerMoveMsg, count: MemoryLayout.size) - - sendData(data: data) + let playerMoveMsg = PlayerMove(messageType: MessageType.PlayerMove, unitCount: unitcount) + let encoder = JSONEncoder() + let encoded = (try? encoder.encode(playerMoveMsg))! + sendData(data: encoded) } } From a0a6bb9b285efda376ffe0ccffc7f501a9cde312 Mon Sep 17 00:00:00 2001 From: Niko Jochim <82joni1bif@hft-stuttgart.de> Date: Wed, 13 May 2020 15:47:53 +0200 Subject: [PATCH 07/28] create Base ID, added fromBase - toBase to sending data --- GoldWars/GoldWars/Entities/Base.swift | 11 +++++--- .../GoldWars/Entities/EntityManager.swift | 12 ++++++++- GoldWars/GoldWars/MessageProtocol.swift | 27 +++++-------------- 3 files changed, 24 insertions(+), 26 deletions(-) diff --git a/GoldWars/GoldWars/Entities/Base.swift b/GoldWars/GoldWars/Entities/Base.swift index 97c4412..250521d 100644 --- a/GoldWars/GoldWars/Entities/Base.swift +++ b/GoldWars/GoldWars/Entities/Base.swift @@ -9,16 +9,19 @@ import SpriteKit import GameplayKit -class Base: GKEntity { - +class Base: GKEntity{ + static var BASE_ID_COUNT: Int = 0 var unitCount: Int var adjacencyList: Array var changeOwnerShip: Bool + var baseID: Int init(position: CGPoint, team: Team! = nil) { self.unitCount = 0 self.adjacencyList = [Base]() self.changeOwnerShip = false + baseID = Base.BASE_ID_COUNT + Base.BASE_ID_COUNT += 1 super.init() addComponent(DefaultBaseComponent(texture: SKTexture(imageNamed: "Base"), position: position)) @@ -28,11 +31,11 @@ class Base: GKEntity { } } - func attackBase(base: Base, units:Int) -> [GKEntity]{ + func attackBase(base: Base, units: Int) -> [GKEntity]{ base.changeOwnerShip = true self.unitCount -= units base.unitCount += units - MultiplayerNetwork.sharedInstance.sendPlayerMove(unitcount: units) + MultiplayerNetwork.sharedInstance.sendPlayerMove(playerMove: PlayerMove(fromBase: self.baseID, toBase: base.baseID, unitCount: units)) return [self, base] } diff --git a/GoldWars/GoldWars/Entities/EntityManager.swift b/GoldWars/GoldWars/Entities/EntityManager.swift index 0f7166c..54a07ec 100644 --- a/GoldWars/GoldWars/Entities/EntityManager.swift +++ b/GoldWars/GoldWars/Entities/EntityManager.swift @@ -99,6 +99,7 @@ class EntityManager { } } + func getBaseByTeam(for team: Team) -> GKEntity? { for entity in entities { if let teamComponent = entity.component(ofType: TeamComponent.self), @@ -128,7 +129,16 @@ class EntityManager { return nil } - func getBackground() -> GKEntity? { + + func getBasebyID(id: Int) -> Base?{ + for entity in entities { + if entity is Base && (entity as! Base).baseID == id { + return (entity as! Base) + } + } + return nil + } + func getBackground() -> GKEntity? { return entities.filter{$0 is Background}[0] } diff --git a/GoldWars/GoldWars/MessageProtocol.swift b/GoldWars/GoldWars/MessageProtocol.swift index 21ed95c..5038135 100644 --- a/GoldWars/GoldWars/MessageProtocol.swift +++ b/GoldWars/GoldWars/MessageProtocol.swift @@ -9,30 +9,16 @@ import GameplayKit import Foundation -enum MessageType : Int,Codable{ - case PlayerMove -} +struct PlayerMove : Codable{ -protocol Message :Codable{ - var messageType:MessageType { get } -} - -struct PlayerMove : Message,Codable{ - - let messageType: MessageType - -// let message: Message - //let fromBase: //was? - //let toBase: //was? + let fromBase: Int + let toBase: Int let unitCount: Int } class MultiplayerNetwork{ - static let sharedInstance = MultiplayerNetwork() - - - + static let sharedInstance = MultiplayerNetwork() func sendData(data: Data) { let mmHelper = MatchmakingHelper.sharedInstance @@ -45,10 +31,9 @@ class MultiplayerNetwork{ } } - func sendPlayerMove(unitcount:Int) { - let playerMoveMsg = PlayerMove(messageType: MessageType.PlayerMove, unitCount: unitcount) + func sendPlayerMove(playerMove:PlayerMove) { let encoder = JSONEncoder() - let encoded = (try? encoder.encode(playerMoveMsg))! + let encoded = (try? encoder.encode(playerMove))! sendData(data: encoded) } From d2f32f41ee7fd18f730db9077b6250e57e6f1d24 Mon Sep 17 00:00:00 2001 From: 127-Z3R0 <81heti1bif@hft-stuttgart.de> Date: Wed, 13 May 2020 19:13:33 +0200 Subject: [PATCH 08/28] Impl. PlayerMovesService for data transfer --- GoldWars/GoldWars.xcodeproj/project.pbxproj | 4 +++ .../GoldWars/Components/TimerComponent.swift | 1 + GoldWars/GoldWars/Entities/Base.swift | 27 +++++++++---------- GoldWars/GoldWars/MessageProtocol.swift | 9 ++----- GoldWars/GoldWars/PlayerMovesService.swift | 23 ++++++++++++++++ 5 files changed, 43 insertions(+), 21 deletions(-) create mode 100644 GoldWars/GoldWars/PlayerMovesService.swift diff --git a/GoldWars/GoldWars.xcodeproj/project.pbxproj b/GoldWars/GoldWars.xcodeproj/project.pbxproj index 0ff7f49..206c98b 100644 --- a/GoldWars/GoldWars.xcodeproj/project.pbxproj +++ b/GoldWars/GoldWars.xcodeproj/project.pbxproj @@ -53,6 +53,7 @@ C064E9A8246C0EA50022B228 /* LabelNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = C064E9A7246C0EA50022B228 /* LabelNode.swift */; }; C064E9AA246C114C0022B228 /* LabelComponent.swift in Sources */ = {isa = PBXBuildFile; fileRef = C064E9A9246C114C0022B228 /* LabelComponent.swift */; }; C064E9AC246C151F0022B228 /* Label.swift in Sources */ = {isa = PBXBuildFile; fileRef = C064E9AB246C151F0022B228 /* Label.swift */; }; + C099579C246C5E5C0016AA22 /* PlayerMovesService.swift in Sources */ = {isa = PBXBuildFile; fileRef = C099579B246C5E5C0016AA22 /* PlayerMovesService.swift */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -117,6 +118,7 @@ C064E9A7246C0EA50022B228 /* LabelNode.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LabelNode.swift; sourceTree = ""; }; C064E9A9246C114C0022B228 /* LabelComponent.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LabelComponent.swift; sourceTree = ""; }; C064E9AB246C151F0022B228 /* Label.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Label.swift; sourceTree = ""; }; + C099579B246C5E5C0016AA22 /* PlayerMovesService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlayerMovesService.swift; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -174,6 +176,7 @@ 110360DA244B101A008610AF /* GameViewController.swift */, 110360DF244B101B008610AF /* Assets.xcassets */, 9EC239E0246878A900952F74 /* MessageProtocol.swift */, + C099579B246C5E5C0016AA22 /* PlayerMovesService.swift */, 110360E4244B101B008610AF /* Info.plist */, AE151588245F18EF001D363E /* MatchmakingHelper.swift */, 3EBD242B245D8044003CECE7 /* GameCenterHelper.swift */, @@ -405,6 +408,7 @@ 9E174C86245DD91500209FF0 /* ButtonComponent.swift in Sources */, AE151589245F18EF001D363E /* MatchmakingHelper.swift in Sources */, 11036113244B3E30008610AF /* MenuScene.swift in Sources */, + C099579C246C5E5C0016AA22 /* PlayerMovesService.swift in Sources */, 9EA3ABE9245C6DAA006BC61D /* DefaultBaseComponent.swift in Sources */, 9E174C8A245E1A0A00209FF0 /* Background.swift in Sources */, 9EA3ABED245C8143006BC61D /* ModalBackgroundComponent.swift in Sources */, diff --git a/GoldWars/GoldWars/Components/TimerComponent.swift b/GoldWars/GoldWars/Components/TimerComponent.swift index 816ca04..42d27f1 100644 --- a/GoldWars/GoldWars/Components/TimerComponent.swift +++ b/GoldWars/GoldWars/Components/TimerComponent.swift @@ -45,6 +45,7 @@ class TimerComponent: GKComponent { if(isFinished()){ self.labelNode.text = "Synching" + MultiplayerNetwork.sharedInstance.sendPlayerMoves(playerMoves: PlayerMovesService.sharedInstance.playerMoves) } } diff --git a/GoldWars/GoldWars/Entities/Base.swift b/GoldWars/GoldWars/Entities/Base.swift index 250521d..596721e 100644 --- a/GoldWars/GoldWars/Entities/Base.swift +++ b/GoldWars/GoldWars/Entities/Base.swift @@ -10,18 +10,18 @@ import SpriteKit import GameplayKit class Base: GKEntity{ - static var BASE_ID_COUNT: Int = 0 + static var BASE_ID_COUNT: Int = 0 var unitCount: Int var adjacencyList: Array - var changeOwnerShip: Bool - var baseID: Int + var changeOwnerShip: Bool + var baseID: Int init(position: CGPoint, team: Team! = nil) { self.unitCount = 0 self.adjacencyList = [Base]() - self.changeOwnerShip = false - baseID = Base.BASE_ID_COUNT - Base.BASE_ID_COUNT += 1 + self.changeOwnerShip = false + baseID = Base.BASE_ID_COUNT + Base.BASE_ID_COUNT += 1 super.init() addComponent(DefaultBaseComponent(texture: SKTexture(imageNamed: "Base"), position: position)) @@ -31,14 +31,13 @@ class Base: GKEntity{ } } - func attackBase(base: Base, units: Int) -> [GKEntity]{ - base.changeOwnerShip = true - self.unitCount -= units - base.unitCount += units - MultiplayerNetwork.sharedInstance.sendPlayerMove(playerMove: PlayerMove(fromBase: self.baseID, toBase: base.baseID, unitCount: units)) - return [self, base] - - } + func attackBase(base: Base, units: Int) -> [GKEntity]{ + base.changeOwnerShip = true + self.unitCount -= units + base.unitCount += units + PlayerMovesService.sharedInstance.addMove(playerMove: PlayerMove(fromBase: self.baseID, toBase: base.baseID, unitCount: units)) + return [self, base] + } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") diff --git a/GoldWars/GoldWars/MessageProtocol.swift b/GoldWars/GoldWars/MessageProtocol.swift index 5038135..133cf43 100644 --- a/GoldWars/GoldWars/MessageProtocol.swift +++ b/GoldWars/GoldWars/MessageProtocol.swift @@ -10,12 +10,7 @@ import GameplayKit import Foundation -struct PlayerMove : Codable{ - let fromBase: Int - let toBase: Int - let unitCount: Int -} class MultiplayerNetwork{ static let sharedInstance = MultiplayerNetwork() @@ -31,9 +26,9 @@ class MultiplayerNetwork{ } } - func sendPlayerMove(playerMove:PlayerMove) { + func sendPlayerMoves(playerMoves: [PlayerMove]) { let encoder = JSONEncoder() - let encoded = (try? encoder.encode(playerMove))! + let encoded = (try? encoder.encode(playerMoves))! sendData(data: encoded) } diff --git a/GoldWars/GoldWars/PlayerMovesService.swift b/GoldWars/GoldWars/PlayerMovesService.swift new file mode 100644 index 0000000..3dd8de2 --- /dev/null +++ b/GoldWars/GoldWars/PlayerMovesService.swift @@ -0,0 +1,23 @@ +// +// PlayerMovesService.swift +// GoldWars +// +// Created by Tim Herbst on 13.05.20. +// Copyright © 2020 SP2. All rights reserved. +// + +struct PlayerMove : Codable{ + let fromBase: Int + let toBase: Int + let unitCount: Int +} + +class PlayerMovesService { + static let sharedInstance = PlayerMovesService() + var playerMoves: [PlayerMove] = [] + + + func addMove(playerMove: PlayerMove) { + self.playerMoves.append(playerMove) + } +} From ce4d2fe8a2f92391a3d64655424582b3d478e6d4 Mon Sep 17 00:00:00 2001 From: Aldin Duraki Date: Wed, 13 May 2020 20:22:23 +0200 Subject: [PATCH 09/28] Impl. neccessary Server identifier --- GoldWars/GoldWars.xcodeproj/project.pbxproj | 20 +++++++----- .../GoldWars/Components/TimerComponent.swift | 3 +- GoldWars/GoldWars/DataService.swift | 32 +++++++++++++++++++ GoldWars/GoldWars/Entities/Base.swift | 2 +- GoldWars/GoldWars/MatchmakingHelper.swift | 15 +++++++-- ...rotocol.swift => MultiplayerNetwork.swift} | 11 ++++--- GoldWars/GoldWars/PlayerMovesService.swift | 13 ++++++-- .../Storyboards/RoundSimulatorService.swift | 13 ++++++++ 8 files changed, 90 insertions(+), 19 deletions(-) create mode 100644 GoldWars/GoldWars/DataService.swift rename GoldWars/GoldWars/{MessageProtocol.swift => MultiplayerNetwork.swift} (74%) create mode 100644 GoldWars/GoldWars/Storyboards/RoundSimulatorService.swift diff --git a/GoldWars/GoldWars.xcodeproj/project.pbxproj b/GoldWars/GoldWars.xcodeproj/project.pbxproj index 206c98b..abbd510 100644 --- a/GoldWars/GoldWars.xcodeproj/project.pbxproj +++ b/GoldWars/GoldWars.xcodeproj/project.pbxproj @@ -20,6 +20,7 @@ 2086465C2461B66200817C23 /* TimerComponent.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2086465B2461B66200817C23 /* TimerComponent.swift */; }; 3EBD242C245D8044003CECE7 /* GameCenterHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3EBD242B245D8044003CECE7 /* GameCenterHelper.swift */; }; 3EBD242E245D9332003CECE7 /* Team.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3EBD242D245D9332003CECE7 /* Team.swift */; }; + 3FE19DB3246C690B004827AB /* RoundSimulatorService.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3FE19DB2246C690B004827AB /* RoundSimulatorService.swift */; }; 9E04AFAF245E2B73002D5CFC /* AttackActionComponent.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9E04AFAE245E2B73002D5CFC /* AttackActionComponent.swift */; }; 9E11FF79245CD81100EED3BE /* Fire.sks in Resources */ = {isa = PBXBuildFile; fileRef = 9E11FF77245CD81100EED3BE /* Fire.sks */; }; 9E174C82245DD81D00209FF0 /* ButtonNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9E174C81245DD81D00209FF0 /* ButtonNode.swift */; }; @@ -38,7 +39,7 @@ 9EA3ABED245C8143006BC61D /* ModalBackgroundComponent.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9EA3ABEC245C8143006BC61D /* ModalBackgroundComponent.swift */; }; 9EA3ABEF245C834B006BC61D /* ModalContentComponent.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9EA3ABEE245C834B006BC61D /* ModalContentComponent.swift */; }; 9EBFD7552462CF5A00E1E219 /* SliderComponent.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9EBFD7542462CF5A00E1E219 /* SliderComponent.swift */; }; - 9EC239E1246878A900952F74 /* MessageProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9EC239E0246878A900952F74 /* MessageProtocol.swift */; }; + 9EC239E1246878A900952F74 /* MultiplayerNetwork.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9EC239E0246878A900952F74 /* MultiplayerNetwork.swift */; }; 9EC7E48B2461FBF700396BCD /* SliderNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9EC7E48A2461FBF700396BCD /* SliderNode.swift */; }; 9EC86B9F245C88A300796EF3 /* Modal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9EC86B9E245C88A300796EF3 /* Modal.swift */; }; 9EC86BA6245C8AD000796EF3 /* ModalType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9EC86BA5245C8AD000796EF3 /* ModalType.swift */; }; @@ -53,7 +54,7 @@ C064E9A8246C0EA50022B228 /* LabelNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = C064E9A7246C0EA50022B228 /* LabelNode.swift */; }; C064E9AA246C114C0022B228 /* LabelComponent.swift in Sources */ = {isa = PBXBuildFile; fileRef = C064E9A9246C114C0022B228 /* LabelComponent.swift */; }; C064E9AC246C151F0022B228 /* Label.swift in Sources */ = {isa = PBXBuildFile; fileRef = C064E9AB246C151F0022B228 /* Label.swift */; }; - C099579C246C5E5C0016AA22 /* PlayerMovesService.swift in Sources */ = {isa = PBXBuildFile; fileRef = C099579B246C5E5C0016AA22 /* PlayerMovesService.swift */; }; + C099579C246C5E5C0016AA22 /* DataService.swift in Sources */ = {isa = PBXBuildFile; fileRef = C099579B246C5E5C0016AA22 /* DataService.swift */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -84,6 +85,7 @@ 2086465B2461B66200817C23 /* TimerComponent.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TimerComponent.swift; sourceTree = ""; }; 3EBD242B245D8044003CECE7 /* GameCenterHelper.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GameCenterHelper.swift; sourceTree = ""; }; 3EBD242D245D9332003CECE7 /* Team.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Team.swift; sourceTree = ""; }; + 3FE19DB2246C690B004827AB /* RoundSimulatorService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RoundSimulatorService.swift; sourceTree = ""; }; 9E04AFAE245E2B73002D5CFC /* AttackActionComponent.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AttackActionComponent.swift; sourceTree = ""; }; 9E11FF77245CD81100EED3BE /* Fire.sks */ = {isa = PBXFileReference; lastKnownFileType = file.sks; path = Fire.sks; sourceTree = ""; }; 9E174C81245DD81D00209FF0 /* ButtonNode.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ButtonNode.swift; sourceTree = ""; }; @@ -102,7 +104,7 @@ 9EA3ABEC245C8143006BC61D /* ModalBackgroundComponent.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ModalBackgroundComponent.swift; sourceTree = ""; }; 9EA3ABEE245C834B006BC61D /* ModalContentComponent.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ModalContentComponent.swift; sourceTree = ""; }; 9EBFD7542462CF5A00E1E219 /* SliderComponent.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SliderComponent.swift; sourceTree = ""; }; - 9EC239E0246878A900952F74 /* MessageProtocol.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MessageProtocol.swift; sourceTree = ""; }; + 9EC239E0246878A900952F74 /* MultiplayerNetwork.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MultiplayerNetwork.swift; sourceTree = ""; }; 9EC7E48A2461FBF700396BCD /* SliderNode.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SliderNode.swift; sourceTree = ""; }; 9EC86B9E245C88A300796EF3 /* Modal.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Modal.swift; sourceTree = ""; }; 9EC86BA5245C8AD000796EF3 /* ModalType.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ModalType.swift; sourceTree = ""; }; @@ -118,7 +120,7 @@ C064E9A7246C0EA50022B228 /* LabelNode.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LabelNode.swift; sourceTree = ""; }; C064E9A9246C114C0022B228 /* LabelComponent.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LabelComponent.swift; sourceTree = ""; }; C064E9AB246C151F0022B228 /* Label.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Label.swift; sourceTree = ""; }; - C099579B246C5E5C0016AA22 /* PlayerMovesService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlayerMovesService.swift; sourceTree = ""; }; + C099579B246C5E5C0016AA22 /* DataService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DataService.swift; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -175,8 +177,8 @@ C05FAED52468559D0006AF2E /* SoundManager.swift */, 110360DA244B101A008610AF /* GameViewController.swift */, 110360DF244B101B008610AF /* Assets.xcassets */, - 9EC239E0246878A900952F74 /* MessageProtocol.swift */, - C099579B246C5E5C0016AA22 /* PlayerMovesService.swift */, + 9EC239E0246878A900952F74 /* MultiplayerNetwork.swift */, + C099579B246C5E5C0016AA22 /* DataService.swift */, 110360E4244B101B008610AF /* Info.plist */, AE151588245F18EF001D363E /* MatchmakingHelper.swift */, 3EBD242B245D8044003CECE7 /* GameCenterHelper.swift */, @@ -263,6 +265,7 @@ children = ( 110360DC244B101A008610AF /* Main.storyboard */, 110360E1244B101B008610AF /* LaunchScreen.storyboard */, + 3FE19DB2246C690B004827AB /* RoundSimulatorService.swift */, ); path = Storyboards; sourceTree = ""; @@ -392,13 +395,14 @@ 9E78ACB8245CB75B00526FF7 /* TeamComponent.swift in Sources */, 9EA3ABEF245C834B006BC61D /* ModalContentComponent.swift in Sources */, 9EC86BA6245C8AD000796EF3 /* ModalType.swift in Sources */, - 9EC239E1246878A900952F74 /* MessageProtocol.swift in Sources */, + 9EC239E1246878A900952F74 /* MultiplayerNetwork.swift in Sources */, 9E78ACBE245CC9C000526FF7 /* AtkBoostSkillComponent.swift in Sources */, 9E78ACC4245CCA3600526FF7 /* SpySkillComponent.swift in Sources */, 9EA3ABEB245C6DFA006BC61D /* BaseNode.swift in Sources */, 9E04AFAF245E2B73002D5CFC /* AttackActionComponent.swift in Sources */, 110360D9244B101A008610AF /* GameScene.swift in Sources */, C04783F024685995004961FB /* SettingsScene.swift in Sources */, + 3FE19DB3246C690B004827AB /* RoundSimulatorService.swift in Sources */, 116060F7245C57D2004E5A36 /* EntityManager.swift in Sources */, C064E9AA246C114C0022B228 /* LabelComponent.swift in Sources */, 3EBD242E245D9332003CECE7 /* Team.swift in Sources */, @@ -408,7 +412,7 @@ 9E174C86245DD91500209FF0 /* ButtonComponent.swift in Sources */, AE151589245F18EF001D363E /* MatchmakingHelper.swift in Sources */, 11036113244B3E30008610AF /* MenuScene.swift in Sources */, - C099579C246C5E5C0016AA22 /* PlayerMovesService.swift in Sources */, + C099579C246C5E5C0016AA22 /* DataService.swift in Sources */, 9EA3ABE9245C6DAA006BC61D /* DefaultBaseComponent.swift in Sources */, 9E174C8A245E1A0A00209FF0 /* Background.swift in Sources */, 9EA3ABED245C8143006BC61D /* ModalBackgroundComponent.swift in Sources */, diff --git a/GoldWars/GoldWars/Components/TimerComponent.swift b/GoldWars/GoldWars/Components/TimerComponent.swift index 42d27f1..9fa31de 100644 --- a/GoldWars/GoldWars/Components/TimerComponent.swift +++ b/GoldWars/GoldWars/Components/TimerComponent.swift @@ -44,8 +44,9 @@ class TimerComponent: GKComponent { self.labelNode.text = String(timeLeft()) if(isFinished()){ + MatchmakingHelper.shar self.labelNode.text = "Synching" - MultiplayerNetwork.sharedInstance.sendPlayerMoves(playerMoves: PlayerMovesService.sharedInstance.playerMoves) + MultiplayerNetwork.sharedInstance.sendPlayerMoves(playerMoves: DataService.sharedInstance.playerMoves) } } diff --git a/GoldWars/GoldWars/DataService.swift b/GoldWars/GoldWars/DataService.swift new file mode 100644 index 0000000..fb3ddb9 --- /dev/null +++ b/GoldWars/GoldWars/DataService.swift @@ -0,0 +1,32 @@ +// +// PlayerMovesService.swift +// GoldWars +// +// Created by Tim Herbst on 13.05.20. +// Copyright © 2020 SP2. All rights reserved. +// + +struct PlayerMove: Codable{ + let fromBase: Int + let toBase: Int + let unitCount: Int +} + +struct Host: Codable { + let playerID: String +} + +class DataService { + static let sharedInstance = DataService() + var playerMoves: [PlayerMove] = [] + var gameHost: Host? + + + func addMove(playerMove: PlayerMove) { + self.playerMoves.append(playerMove) + } + + func setGameHost(host: Host) { + self.gameHost = host + } +} diff --git a/GoldWars/GoldWars/Entities/Base.swift b/GoldWars/GoldWars/Entities/Base.swift index 596721e..7578e67 100644 --- a/GoldWars/GoldWars/Entities/Base.swift +++ b/GoldWars/GoldWars/Entities/Base.swift @@ -35,7 +35,7 @@ class Base: GKEntity{ base.changeOwnerShip = true self.unitCount -= units base.unitCount += units - PlayerMovesService.sharedInstance.addMove(playerMove: PlayerMove(fromBase: self.baseID, toBase: base.baseID, unitCount: units)) + DataService.sharedInstance.addMove(playerMove: PlayerMove(fromBase: self.baseID, toBase: base.baseID, unitCount: units)) return [self, base] } diff --git a/GoldWars/GoldWars/MatchmakingHelper.swift b/GoldWars/GoldWars/MatchmakingHelper.swift index 26f0c00..0df83ee 100644 --- a/GoldWars/GoldWars/MatchmakingHelper.swift +++ b/GoldWars/GoldWars/MatchmakingHelper.swift @@ -115,9 +115,17 @@ class MatchmakingHelper: NSObject, GKMatchmakerViewControllerDelegate, GKMatchDe let jsonDecoder = JSONDecoder() if let message = try? jsonDecoder.decode(PlayerMove.self, from: data) { - let count = message.unitCount - print("Angekommen \(count)") + //TODO: impl logic } + + if let message = try? jsonDecoder.decode(Host.self, from: data) { + if !self.isServer { + DataService.sharedInstance.gameHost = message + print("LocalID: \(GKLocalPlayer.local.gamePlayerID)") + print("ServerID: \(message.playerID)") + } + + } } /* @@ -167,13 +175,14 @@ class MatchmakingHelper: NSObject, GKMatchmakerViewControllerDelegate, GKMatchDe self.isServer = true self.spieler1 = player self.nameSpieler1 = self.spieler1!.displayName - + DataService.sharedInstance.setGameHost(host: Host(playerName: player!.gamePlayerID)) } else { self.isServer = false } self.delegate?.matchStarted() self.menusc!.loadScene(scene: GameScene(size: self.menusc!.size)) + MultiplayerNetwork.sharedInstance.sendHostIdentifier() }) } diff --git a/GoldWars/GoldWars/MessageProtocol.swift b/GoldWars/GoldWars/MultiplayerNetwork.swift similarity index 74% rename from GoldWars/GoldWars/MessageProtocol.swift rename to GoldWars/GoldWars/MultiplayerNetwork.swift index 133cf43..75f51f9 100644 --- a/GoldWars/GoldWars/MessageProtocol.swift +++ b/GoldWars/GoldWars/MultiplayerNetwork.swift @@ -1,5 +1,5 @@ // -// MessageProtocol.swift +// MultiplayerNetwork.swift // GoldWars // // Created by Niko Jochim on 10.05.20. @@ -9,9 +9,6 @@ import GameplayKit import Foundation - - - class MultiplayerNetwork{ static let sharedInstance = MultiplayerNetwork() @@ -31,5 +28,11 @@ class MultiplayerNetwork{ let encoded = (try? encoder.encode(playerMoves))! sendData(data: encoded) } + + func sendHostIdentifier() { + let encoder = JSONEncoder() + let encoded = (try? encoder.encode(DataService.sharedInstance.gameHost))! + sendData(data: encoded) + } } diff --git a/GoldWars/GoldWars/PlayerMovesService.swift b/GoldWars/GoldWars/PlayerMovesService.swift index 3dd8de2..3c0f41d 100644 --- a/GoldWars/GoldWars/PlayerMovesService.swift +++ b/GoldWars/GoldWars/PlayerMovesService.swift @@ -12,12 +12,21 @@ struct PlayerMove : Codable{ let unitCount: Int } -class PlayerMovesService { - static let sharedInstance = PlayerMovesService() +struct Host: Codable { + let playerName: String +} + +class DataService { + static let sharedInstance = DataService() var playerMoves: [PlayerMove] = [] + var gameHost: Host? func addMove(playerMove: PlayerMove) { self.playerMoves.append(playerMove) } + + func setGameHost(host: Host) { + self.gameHost = host + } } diff --git a/GoldWars/GoldWars/Storyboards/RoundSimulatorService.swift b/GoldWars/GoldWars/Storyboards/RoundSimulatorService.swift new file mode 100644 index 0000000..4847831 --- /dev/null +++ b/GoldWars/GoldWars/Storyboards/RoundSimulatorService.swift @@ -0,0 +1,13 @@ +// +// RoundSimulatorService.swift +// GoldWars +// +// Created by student on 13.05.20. +// Copyright © 2020 SP2. All rights reserved. +// + +import Foundation + +class RoundSimulatorService { + +} From 917769ac24d22a99c6fe9a016abd4e7e59e0770a Mon Sep 17 00:00:00 2001 From: Aldin Duraki Date: Wed, 13 May 2020 20:22:48 +0200 Subject: [PATCH 10/28] Fix Typo --- GoldWars/GoldWars/MatchmakingHelper.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GoldWars/GoldWars/MatchmakingHelper.swift b/GoldWars/GoldWars/MatchmakingHelper.swift index 0df83ee..272c7ad 100644 --- a/GoldWars/GoldWars/MatchmakingHelper.swift +++ b/GoldWars/GoldWars/MatchmakingHelper.swift @@ -175,7 +175,7 @@ class MatchmakingHelper: NSObject, GKMatchmakerViewControllerDelegate, GKMatchDe self.isServer = true self.spieler1 = player self.nameSpieler1 = self.spieler1!.displayName - DataService.sharedInstance.setGameHost(host: Host(playerName: player!.gamePlayerID)) + DataService.sharedInstance.setGameHost(host: Host(playerID: player!.gamePlayerID)) } else { self.isServer = false } From 570099911f701ee21affd925e4af21551a0d584a Mon Sep 17 00:00:00 2001 From: Aldin Duraki Date: Wed, 13 May 2020 21:15:44 +0200 Subject: [PATCH 11/28] Test: Receiving Data on Hostdevice --- GoldWars/GoldWars.xcodeproj/project.pbxproj | 4 ++++ .../GoldWars/Components/TimerComponent.swift | 3 +-- GoldWars/GoldWars/DataService.swift | 17 ++++++++++++-- GoldWars/GoldWars/MatchmakingHelper.swift | 5 ++-- GoldWars/GoldWars/MultiplayerNetwork.swift | 23 +++++++++++++++---- .../GoldWars/RoundCalculatorService.swift | 13 +++++++++++ 6 files changed, 54 insertions(+), 11 deletions(-) create mode 100644 GoldWars/GoldWars/RoundCalculatorService.swift diff --git a/GoldWars/GoldWars.xcodeproj/project.pbxproj b/GoldWars/GoldWars.xcodeproj/project.pbxproj index abbd510..6e22439 100644 --- a/GoldWars/GoldWars.xcodeproj/project.pbxproj +++ b/GoldWars/GoldWars.xcodeproj/project.pbxproj @@ -21,6 +21,7 @@ 3EBD242C245D8044003CECE7 /* GameCenterHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3EBD242B245D8044003CECE7 /* GameCenterHelper.swift */; }; 3EBD242E245D9332003CECE7 /* Team.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3EBD242D245D9332003CECE7 /* Team.swift */; }; 3FE19DB3246C690B004827AB /* RoundSimulatorService.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3FE19DB2246C690B004827AB /* RoundSimulatorService.swift */; }; + 3FE19DB5246C7A22004827AB /* RoundCalculatorService.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3FE19DB4246C7A22004827AB /* RoundCalculatorService.swift */; }; 9E04AFAF245E2B73002D5CFC /* AttackActionComponent.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9E04AFAE245E2B73002D5CFC /* AttackActionComponent.swift */; }; 9E11FF79245CD81100EED3BE /* Fire.sks in Resources */ = {isa = PBXBuildFile; fileRef = 9E11FF77245CD81100EED3BE /* Fire.sks */; }; 9E174C82245DD81D00209FF0 /* ButtonNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9E174C81245DD81D00209FF0 /* ButtonNode.swift */; }; @@ -86,6 +87,7 @@ 3EBD242B245D8044003CECE7 /* GameCenterHelper.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GameCenterHelper.swift; sourceTree = ""; }; 3EBD242D245D9332003CECE7 /* Team.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Team.swift; sourceTree = ""; }; 3FE19DB2246C690B004827AB /* RoundSimulatorService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RoundSimulatorService.swift; sourceTree = ""; }; + 3FE19DB4246C7A22004827AB /* RoundCalculatorService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RoundCalculatorService.swift; sourceTree = ""; }; 9E04AFAE245E2B73002D5CFC /* AttackActionComponent.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AttackActionComponent.swift; sourceTree = ""; }; 9E11FF77245CD81100EED3BE /* Fire.sks */ = {isa = PBXFileReference; lastKnownFileType = file.sks; path = Fire.sks; sourceTree = ""; }; 9E174C81245DD81D00209FF0 /* ButtonNode.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ButtonNode.swift; sourceTree = ""; }; @@ -181,6 +183,7 @@ C099579B246C5E5C0016AA22 /* DataService.swift */, 110360E4244B101B008610AF /* Info.plist */, AE151588245F18EF001D363E /* MatchmakingHelper.swift */, + 3FE19DB4246C7A22004827AB /* RoundCalculatorService.swift */, 3EBD242B245D8044003CECE7 /* GameCenterHelper.swift */, C04783EF24685995004961FB /* SettingsScene.swift */, C064E9A7246C0EA50022B228 /* LabelNode.swift */, @@ -394,6 +397,7 @@ files = ( 9E78ACB8245CB75B00526FF7 /* TeamComponent.swift in Sources */, 9EA3ABEF245C834B006BC61D /* ModalContentComponent.swift in Sources */, + 3FE19DB5246C7A22004827AB /* RoundCalculatorService.swift in Sources */, 9EC86BA6245C8AD000796EF3 /* ModalType.swift in Sources */, 9EC239E1246878A900952F74 /* MultiplayerNetwork.swift in Sources */, 9E78ACBE245CC9C000526FF7 /* AtkBoostSkillComponent.swift in Sources */, diff --git a/GoldWars/GoldWars/Components/TimerComponent.swift b/GoldWars/GoldWars/Components/TimerComponent.swift index 9fa31de..f45026c 100644 --- a/GoldWars/GoldWars/Components/TimerComponent.swift +++ b/GoldWars/GoldWars/Components/TimerComponent.swift @@ -44,9 +44,8 @@ class TimerComponent: GKComponent { self.labelNode.text = String(timeLeft()) if(isFinished()){ - MatchmakingHelper.shar self.labelNode.text = "Synching" - MultiplayerNetwork.sharedInstance.sendPlayerMoves(playerMoves: DataService.sharedInstance.playerMoves) + MultiplayerNetwork.sharedInstance.sendPlayerMoves(playerMoves: DataService.sharedInstance.localPlayerMoves) } } diff --git a/GoldWars/GoldWars/DataService.swift b/GoldWars/GoldWars/DataService.swift index fb3ddb9..30fdde6 100644 --- a/GoldWars/GoldWars/DataService.swift +++ b/GoldWars/GoldWars/DataService.swift @@ -18,12 +18,25 @@ struct Host: Codable { class DataService { static let sharedInstance = DataService() - var playerMoves: [PlayerMove] = [] + var localPlayerMoves: [PlayerMove] = [] + var remotePlayerMoves: [String: [PlayerMove]] = [:] var gameHost: Host? func addMove(playerMove: PlayerMove) { - self.playerMoves.append(playerMove) + self.localPlayerMoves.append(playerMove) + } + + func addRemotePlayerMoves(playerID: String, playerMoves: [PlayerMove]) { + self.remotePlayerMoves[playerID] = playerMoves + + //test + var size = self.remotePlayerMoves.count + if size == 1 { + for (key, value) in remotePlayerMoves { + print("\(key) : \(value)") + } + } } func setGameHost(host: Host) { diff --git a/GoldWars/GoldWars/MatchmakingHelper.swift b/GoldWars/GoldWars/MatchmakingHelper.swift index 272c7ad..0af55c1 100644 --- a/GoldWars/GoldWars/MatchmakingHelper.swift +++ b/GoldWars/GoldWars/MatchmakingHelper.swift @@ -109,13 +109,12 @@ class MatchmakingHelper: NSObject, GKMatchmakerViewControllerDelegate, GKMatchDe */ func match(_ match: GKMatch, didReceive data: Data, fromRemotePlayer player: GKPlayer) { - print("Daten empfangen!") if mpMatch != match { return } let jsonDecoder = JSONDecoder() - if let message = try? jsonDecoder.decode(PlayerMove.self, from: data) { - //TODO: impl logic + if let playerMoves = try? jsonDecoder.decode([PlayerMove].self, from: data) { + DataService.sharedInstance.addRemotePlayerMoves(playerID: player.gamePlayerID, playerMoves: playerMoves) } if let message = try? jsonDecoder.decode(Host.self, from: data) { diff --git a/GoldWars/GoldWars/MultiplayerNetwork.swift b/GoldWars/GoldWars/MultiplayerNetwork.swift index 75f51f9..2cbc4ea 100644 --- a/GoldWars/GoldWars/MultiplayerNetwork.swift +++ b/GoldWars/GoldWars/MultiplayerNetwork.swift @@ -11,7 +11,7 @@ import Foundation class MultiplayerNetwork{ static let sharedInstance = MultiplayerNetwork() - + func sendData(data: Data) { let mmHelper = MatchmakingHelper.sharedInstance if let multiplayerMatch = mmHelper.mpMatch { @@ -22,11 +22,26 @@ class MultiplayerNetwork{ } } } + + func sendDataToHost(data: Data) { + let mmHelper = MatchmakingHelper.sharedInstance + let hostGKPlayer = MatchmakingHelper.sharedInstance.mpMatch?.players.filter{ $0.gamePlayerID == DataService.sharedInstance.gameHost?.playerID} + + if let multiplayerMatch = mmHelper.mpMatch{ + do { + try multiplayerMatch.send(data, to: hostGKPlayer!, dataMode: .reliable) + } catch { + print("Tim war mal wieder am Werk der Krasse") + } + } + } func sendPlayerMoves(playerMoves: [PlayerMove]) { - let encoder = JSONEncoder() - let encoded = (try? encoder.encode(playerMoves))! - sendData(data: encoded) + if !MatchmakingHelper.sharedInstance.isServer { + let encoder = JSONEncoder() + let encoded = (try? encoder.encode(playerMoves))! + sendDataToHost(data: encoded) + } } func sendHostIdentifier() { diff --git a/GoldWars/GoldWars/RoundCalculatorService.swift b/GoldWars/GoldWars/RoundCalculatorService.swift new file mode 100644 index 0000000..b01b676 --- /dev/null +++ b/GoldWars/GoldWars/RoundCalculatorService.swift @@ -0,0 +1,13 @@ +// +// RoundCalculatorService.swift +// GoldWars +// +// Created by student on 13.05.20. +// Copyright © 2020 SP2. All rights reserved. +// + +import Foundation + +class RoundCalculatorServie { + +} From cfe01cde54f51a876df75ebde87a2dd9cfb2ada9 Mon Sep 17 00:00:00 2001 From: Aldin Duraki Date: Wed, 13 May 2020 22:32:05 +0200 Subject: [PATCH 12/28] TEST: Change Host Identifier to displayName, since the ID is not working for some odd reasons --- .../GoldWars/Components/TimerComponent.swift | 5 +- GoldWars/GoldWars/MatchmakingHelper.swift | 65 +++++++++---------- GoldWars/GoldWars/MultiplayerNetwork.swift | 16 +++-- 3 files changed, 48 insertions(+), 38 deletions(-) diff --git a/GoldWars/GoldWars/Components/TimerComponent.swift b/GoldWars/GoldWars/Components/TimerComponent.swift index f45026c..b3adc4a 100644 --- a/GoldWars/GoldWars/Components/TimerComponent.swift +++ b/GoldWars/GoldWars/Components/TimerComponent.swift @@ -45,7 +45,10 @@ class TimerComponent: GKComponent { if(isFinished()){ self.labelNode.text = "Synching" - MultiplayerNetwork.sharedInstance.sendPlayerMoves(playerMoves: DataService.sharedInstance.localPlayerMoves) + if !MultiplayerNetwork.sharedInstance.isSending { + MultiplayerNetwork.sharedInstance.sendPlayerMoves(playerMoves: DataService.sharedInstance.localPlayerMoves) + } + } } diff --git a/GoldWars/GoldWars/MatchmakingHelper.swift b/GoldWars/GoldWars/MatchmakingHelper.swift index 0af55c1..4b499d4 100644 --- a/GoldWars/GoldWars/MatchmakingHelper.swift +++ b/GoldWars/GoldWars/MatchmakingHelper.swift @@ -72,15 +72,15 @@ class MatchmakingHelper: NSObject, GKMatchmakerViewControllerDelegate, GKMatchDe /* Der User hat die Verbindung mit "Abbrechen" unterbrochen. GameCenter MatchMaking wird beendet. - */ + */ func matchmakerViewControllerWasCancelled(_ viewController: GKMatchmakerViewController) { viewController.dismiss(animated: true, completion: nil) delegate?.matchEnded() } /* - Wenn GameCenter kein match erstellen kann, wird der viewcontroller dismissed. - */ + Wenn GameCenter kein match erstellen kann, wird der viewcontroller dismissed. + */ func matchmakerViewController(_ viewController: GKMatchmakerViewController, didFailWithError error: Error) { viewController.dismiss(animated: true, completion: nil) print("Error finding match", error.localizedDescription) @@ -91,7 +91,7 @@ class MatchmakingHelper: NSObject, GKMatchmakerViewControllerDelegate, GKMatchDe Gamecenter hat erfolgreich ein Match gefunden, das Spiel kann gestartet werden. expectedPlayerCount: Die verbleibende Anzahl von Spielern, die sich noch nicht mit dem Spiel verbunden haben z.B 0 gibt an, dass keine weiteren Spieler benötigt werden um das Match zu starten - */ + */ func matchmakerViewController(_ viewController: GKMatchmakerViewController, didFind match: GKMatch) { viewController.dismiss(animated: true, completion: nil) mpMatch = match @@ -100,33 +100,31 @@ class MatchmakingHelper: NSObject, GKMatchmakerViewControllerDelegate, GKMatchDe startMatch() } } - - - + + + /* - Vom match erhaltene Spielerdaten - - */ - - func match(_ match: GKMatch, didReceive data: Data, fromRemotePlayer player: GKPlayer) { - if mpMatch != match { return } - - let jsonDecoder = JSONDecoder() - + Vom match erhaltene Spielerdaten + + */ + + func match(_ match: GKMatch, didReceive data: Data, fromRemotePlayer player: GKPlayer) { + if mpMatch != match { return } + + let jsonDecoder = JSONDecoder() + if let playerMoves = try? jsonDecoder.decode([PlayerMove].self, from: data) { - DataService.sharedInstance.addRemotePlayerMoves(playerID: player.gamePlayerID, playerMoves: playerMoves) - } + DataService.sharedInstance.addRemotePlayerMoves(playerID: player.displayName, playerMoves: playerMoves) + } if let message = try? jsonDecoder.decode(Host.self, from: data) { - if !self.isServer { - DataService.sharedInstance.gameHost = message - print("LocalID: \(GKLocalPlayer.local.gamePlayerID)") - print("ServerID: \(message.playerID)") - } - + DataService.sharedInstance.gameHost = message + print("Name: \(player.displayName)") + print("ServerID: \(message.playerID)") } - } - + MultiplayerNetwork.sharedInstance.isSending = false + } + /* Verbindung/Matchmaking ist fehlgeschlagen */ @@ -141,7 +139,7 @@ class MatchmakingHelper: NSObject, GKMatchmakerViewControllerDelegate, GKMatchDe /* Wird beim ändern des States/Zustands des Spielers aufgerufen udn gibt dessen Zustand zurück. */ - + func match(_ match: GKMatch, player: GKPlayer, didChange state: GKPlayerConnectionState) { if mpMatch != match { return @@ -161,20 +159,21 @@ class MatchmakingHelper: NSObject, GKMatchmakerViewControllerDelegate, GKMatchDe } /* - Ein Spieler wird als Host für das Match gewählt. Dieser ist Spieler 1. Im Anschluss wird die GameScene geladen. - */ + Ein Spieler wird als Host für das Match gewählt. Dieser ist Spieler 1. Im Anschluss wird die GameScene geladen. + */ func startMatch() { - + mpMatch!.chooseBestHostingPlayer(completionHandler: { (player) in self.mpMatchStarted = true - + if player == GKLocalPlayer.local { + print("ich bin host") self.isServer = true self.spieler1 = player self.nameSpieler1 = self.spieler1!.displayName - DataService.sharedInstance.setGameHost(host: Host(playerID: player!.gamePlayerID)) + DataService.sharedInstance.setGameHost(host: Host(playerID: player!.displayName)) } else { self.isServer = false } @@ -184,7 +183,7 @@ class MatchmakingHelper: NSObject, GKMatchmakerViewControllerDelegate, GKMatchDe MultiplayerNetwork.sharedInstance.sendHostIdentifier() }) } - + /* Trennt die Verbindung vom Match diff --git a/GoldWars/GoldWars/MultiplayerNetwork.swift b/GoldWars/GoldWars/MultiplayerNetwork.swift index 2cbc4ea..36503ad 100644 --- a/GoldWars/GoldWars/MultiplayerNetwork.swift +++ b/GoldWars/GoldWars/MultiplayerNetwork.swift @@ -8,9 +8,11 @@ import GameplayKit import Foundation +import GameKit class MultiplayerNetwork{ - static let sharedInstance = MultiplayerNetwork() + static let sharedInstance = MultiplayerNetwork() + var isSending = false func sendData(data: Data) { let mmHelper = MatchmakingHelper.sharedInstance @@ -25,11 +27,16 @@ class MultiplayerNetwork{ func sendDataToHost(data: Data) { let mmHelper = MatchmakingHelper.sharedInstance - let hostGKPlayer = MatchmakingHelper.sharedInstance.mpMatch?.players.filter{ $0.gamePlayerID == DataService.sharedInstance.gameHost?.playerID} + for player in mmHelper.mpMatch!.players { + print(player.displayName) + } + print(DataService.sharedInstance.gameHost!.playerID) + + let hostGKPlayer = MatchmakingHelper.sharedInstance.mpMatch?.players.filter{ $0.displayName == DataService.sharedInstance.gameHost!.playerID}[0] if let multiplayerMatch = mmHelper.mpMatch{ do { - try multiplayerMatch.send(data, to: hostGKPlayer!, dataMode: .reliable) + try multiplayerMatch.send(data, to: [hostGKPlayer!], dataMode: .reliable) } catch { print("Tim war mal wieder am Werk der Krasse") } @@ -37,7 +44,8 @@ class MultiplayerNetwork{ } func sendPlayerMoves(playerMoves: [PlayerMove]) { - if !MatchmakingHelper.sharedInstance.isServer { + if MatchmakingHelper.sharedInstance.isServer == false { + self.isSending = true let encoder = JSONEncoder() let encoded = (try? encoder.encode(playerMoves))! sendDataToHost(data: encoded) From 92dd65a93f9f1e1a0d84e752856a573324c7ed7e Mon Sep 17 00:00:00 2001 From: Aldin Duraki Date: Thu, 14 May 2020 01:00:02 +0200 Subject: [PATCH 13/28] Create RoundCalculatorService --- GoldWars/GoldWars/MatchmakingHelper.swift | 2 -- GoldWars/GoldWars/RoundCalculatorService.swift | 2 ++ 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/GoldWars/GoldWars/MatchmakingHelper.swift b/GoldWars/GoldWars/MatchmakingHelper.swift index 4b499d4..dc19aae 100644 --- a/GoldWars/GoldWars/MatchmakingHelper.swift +++ b/GoldWars/GoldWars/MatchmakingHelper.swift @@ -119,8 +119,6 @@ class MatchmakingHelper: NSObject, GKMatchmakerViewControllerDelegate, GKMatchDe if let message = try? jsonDecoder.decode(Host.self, from: data) { DataService.sharedInstance.gameHost = message - print("Name: \(player.displayName)") - print("ServerID: \(message.playerID)") } MultiplayerNetwork.sharedInstance.isSending = false } diff --git a/GoldWars/GoldWars/RoundCalculatorService.swift b/GoldWars/GoldWars/RoundCalculatorService.swift index b01b676..db1ef90 100644 --- a/GoldWars/GoldWars/RoundCalculatorService.swift +++ b/GoldWars/GoldWars/RoundCalculatorService.swift @@ -10,4 +10,6 @@ import Foundation class RoundCalculatorServie { + + } From 9fe149e59418afd206454d8ccbf5afda24eca519 Mon Sep 17 00:00:00 2001 From: Aldin Duraki Date: Fri, 15 May 2020 16:31:27 +0200 Subject: [PATCH 14/28] TEST: check if we can make a solid iterable foundation for player moves --- .../GoldWars/Components/TimerComponent.swift | 3 ++ GoldWars/GoldWars/DataService.swift | 12 +++---- .../GoldWars/RoundCalculatorService.swift | 31 ++++++++++++++++++- 3 files changed, 37 insertions(+), 9 deletions(-) diff --git a/GoldWars/GoldWars/Components/TimerComponent.swift b/GoldWars/GoldWars/Components/TimerComponent.swift index b3adc4a..894a16e 100644 --- a/GoldWars/GoldWars/Components/TimerComponent.swift +++ b/GoldWars/GoldWars/Components/TimerComponent.swift @@ -48,6 +48,9 @@ class TimerComponent: GKComponent { if !MultiplayerNetwork.sharedInstance.isSending { MultiplayerNetwork.sharedInstance.sendPlayerMoves(playerMoves: DataService.sharedInstance.localPlayerMoves) } + if DataService.sharedInstance.didReceiveAllData() { + RoundCalculatorServie.sharedInstance.calculateRound() + } } } diff --git a/GoldWars/GoldWars/DataService.swift b/GoldWars/GoldWars/DataService.swift index 30fdde6..8d2d331 100644 --- a/GoldWars/GoldWars/DataService.swift +++ b/GoldWars/GoldWars/DataService.swift @@ -29,14 +29,10 @@ class DataService { func addRemotePlayerMoves(playerID: String, playerMoves: [PlayerMove]) { self.remotePlayerMoves[playerID] = playerMoves - - //test - var size = self.remotePlayerMoves.count - if size == 1 { - for (key, value) in remotePlayerMoves { - print("\(key) : \(value)") - } - } + } + + func didReceiveAllData() -> Bool { + return remotePlayerMoves.count == MatchmakingHelper.sharedInstance.mpMatch?.players.count } func setGameHost(host: Host) { diff --git a/GoldWars/GoldWars/RoundCalculatorService.swift b/GoldWars/GoldWars/RoundCalculatorService.swift index db1ef90..273b2b0 100644 --- a/GoldWars/GoldWars/RoundCalculatorService.swift +++ b/GoldWars/GoldWars/RoundCalculatorService.swift @@ -2,14 +2,43 @@ // RoundCalculatorService.swift // GoldWars // -// Created by student on 13.05.20. +// Created by Aldin Duraki on 13.05.20. // Copyright © 2020 SP2. All rights reserved. // import Foundation +import GameKit +import os class RoundCalculatorServie { + + static let sharedInstance = RoundCalculatorServie() + var allPlayerMoves: [String: [PlayerMove]] = [:] + var baseSpecificMove: [Int: [(String, PlayerMove)]] = [:] + func calculateRound() { + for entry in DataService.sharedInstance.remotePlayerMoves { + addPlayerMove(playerID: entry.key, playerMoves: entry.value) + } + addPlayerMove(playerID: GKLocalPlayer.local.displayName, playerMoves: DataService.sharedInstance.localPlayerMoves) + + // berechnen nach minimal substraction + + for entry in allPlayerMoves { + for move in entry.value { + addFiltedMove(playerName: entry.key, playerMove: move) + } + } + print(baseSpecificMove) + // sende an alle anderen spieler die moves + } + func addPlayerMove(playerID: String, playerMoves: [PlayerMove]) { + self.allPlayerMoves[playerID] = playerMoves + } + + func addFiltedMove(playerName: String, playerMove: PlayerMove) { + self.baseSpecificMove[playerMove.toBase]!.append((playerName, playerMove)) + } } From 84effcf6bf660a3a47fc19690afa7e47751934eb Mon Sep 17 00:00:00 2001 From: Aldin Duraki Date: Fri, 15 May 2020 17:21:06 +0200 Subject: [PATCH 15/28] Added missing line --- GoldWars/GoldWars/Entities/Base.swift | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/GoldWars/GoldWars/Entities/Base.swift b/GoldWars/GoldWars/Entities/Base.swift index 02011c4..97b6f1b 100644 --- a/GoldWars/GoldWars/Entities/Base.swift +++ b/GoldWars/GoldWars/Entities/Base.swift @@ -23,6 +23,7 @@ class Base: GKEntity{ self.adjacencyList = [Base]() self.changeOwnership = false self.ownershipPlayer = player + self.baseID = Base.BASE_ID_COUNT Base.BASE_ID_COUNT += 1 super.init() @@ -41,13 +42,7 @@ class Base: GKEntity{ DataService.sharedInstance.addMove(playerMove: PlayerMove(fromBase: self.baseID, toBase: base.baseID, unitCount: units)) return [self, base] } - func attackBase(base: Base, units: Int) -> [GKEntity]{ - base.changeOwnerShip = true - self.unitCount -= units - base.unitCount += units - DataService.sharedInstance.addMove(playerMove: PlayerMove(fromBase: self.baseID, toBase: base.baseID, unitCount: units)) - return [self, base] - } + required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") From 4cf9b8c95e859ce751b50aa51ea567e471353b8d Mon Sep 17 00:00:00 2001 From: Aldin Duraki Date: Fri, 15 May 2020 19:40:13 +0200 Subject: [PATCH 16/28] Re-commit missing lines --- GoldWars/GoldWars/MatchmakingHelper.swift | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/GoldWars/GoldWars/MatchmakingHelper.swift b/GoldWars/GoldWars/MatchmakingHelper.swift index 30b7253..d343e40 100644 --- a/GoldWars/GoldWars/MatchmakingHelper.swift +++ b/GoldWars/GoldWars/MatchmakingHelper.swift @@ -165,13 +165,14 @@ class MatchmakingHelper: NSObject, GKMatchmakerViewControllerDelegate, GKMatchDe self.isServer = true self.spieler1 = player self.nameSpieler1 = self.spieler1!.displayName - + DataService.sharedInstance.setGameHost(host: Host(playerID: player!.displayName)) } else { self.isServer = false } self.delegate?.matchStarted() self.menusc!.loadScene(scene: GameScene(size: self.menusc!.size)) + MultiplayerNetwork.sharedInstance.sendHostIdentifier() }) } From 009b39ca1465a55d399783e899af82c133f3a2f7 Mon Sep 17 00:00:00 2001 From: Aldin Duraki Date: Fri, 15 May 2020 20:45:52 +0200 Subject: [PATCH 17/28] TEST: Get a List of overlapping moves --- GoldWars/GoldWars/Components/TimerComponent.swift | 6 +++--- GoldWars/GoldWars/RoundCalculatorService.swift | 10 +++++++--- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/GoldWars/GoldWars/Components/TimerComponent.swift b/GoldWars/GoldWars/Components/TimerComponent.swift index 894a16e..5ad2695 100644 --- a/GoldWars/GoldWars/Components/TimerComponent.swift +++ b/GoldWars/GoldWars/Components/TimerComponent.swift @@ -48,10 +48,10 @@ class TimerComponent: GKComponent { if !MultiplayerNetwork.sharedInstance.isSending { MultiplayerNetwork.sharedInstance.sendPlayerMoves(playerMoves: DataService.sharedInstance.localPlayerMoves) } - if DataService.sharedInstance.didReceiveAllData() { - RoundCalculatorServie.sharedInstance.calculateRound() + if !RoundCalculatorServie.sharedInstance.isCalculating + && DataService.sharedInstance.didReceiveAllData(){ + RoundCalculatorServie.sharedInstance.calculateRound() } - } } diff --git a/GoldWars/GoldWars/RoundCalculatorService.swift b/GoldWars/GoldWars/RoundCalculatorService.swift index 273b2b0..2032a93 100644 --- a/GoldWars/GoldWars/RoundCalculatorService.swift +++ b/GoldWars/GoldWars/RoundCalculatorService.swift @@ -13,24 +13,28 @@ import os class RoundCalculatorServie { static let sharedInstance = RoundCalculatorServie() + var allPlayerMoves: [String: [PlayerMove]] = [:] var baseSpecificMove: [Int: [(String, PlayerMove)]] = [:] + var isCalculating = false func calculateRound() { + isCalculating = true for entry in DataService.sharedInstance.remotePlayerMoves { addPlayerMove(playerID: entry.key, playerMoves: entry.value) } addPlayerMove(playerID: GKLocalPlayer.local.displayName, playerMoves: DataService.sharedInstance.localPlayerMoves) - // berechnen nach minimal substraction - for entry in allPlayerMoves { for move in entry.value { addFiltedMove(playerName: entry.key, playerMove: move) } } + // berechnen nach minimal substraction + print(baseSpecificMove) + isCalculating = false // sende an alle anderen spieler die moves } @@ -39,6 +43,6 @@ class RoundCalculatorServie { } func addFiltedMove(playerName: String, playerMove: PlayerMove) { - self.baseSpecificMove[playerMove.toBase]!.append((playerName, playerMove)) + self.baseSpecificMove.merge([playerMove.toBase : [(playerName, playerMove)]], uniquingKeysWith: +) } } From dc85d0179e89612e96d5b79ed7dc387e5f260acb Mon Sep 17 00:00:00 2001 From: Aldin Duraki Date: Sun, 17 May 2020 21:40:41 +0200 Subject: [PATCH 18/28] * Impl. RoundCalculationService * Impl. SnapshotModel * Impl. DataTransfer for SnapshotModel * Impl. PlayerMoveType * Changed DataService functionality --- GoldWars/GoldWars.xcodeproj/project.pbxproj | 6 +- .../GoldWars/Components/TimerComponent.swift | 4 +- GoldWars/GoldWars/DataService.swift | 29 ++++++- GoldWars/GoldWars/Entities/Base.swift | 11 +-- .../GoldWars/Entities/EntityManager.swift | 14 +++ GoldWars/GoldWars/Enums/PlayerMoveType.swift | 13 +++ GoldWars/GoldWars/MatchmakingHelper.swift | 5 ++ GoldWars/GoldWars/MultiplayerNetwork.swift | 6 ++ .../GoldWars/RoundCalculatorService.swift | 86 ++++++++++++++++--- GoldWars/GoldWars/Scenes/GameScene.swift | 4 +- 10 files changed, 154 insertions(+), 24 deletions(-) create mode 100644 GoldWars/GoldWars/Enums/PlayerMoveType.swift diff --git a/GoldWars/GoldWars.xcodeproj/project.pbxproj b/GoldWars/GoldWars.xcodeproj/project.pbxproj index 6e22439..b532d49 100644 --- a/GoldWars/GoldWars.xcodeproj/project.pbxproj +++ b/GoldWars/GoldWars.xcodeproj/project.pbxproj @@ -20,6 +20,7 @@ 2086465C2461B66200817C23 /* TimerComponent.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2086465B2461B66200817C23 /* TimerComponent.swift */; }; 3EBD242C245D8044003CECE7 /* GameCenterHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3EBD242B245D8044003CECE7 /* GameCenterHelper.swift */; }; 3EBD242E245D9332003CECE7 /* Team.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3EBD242D245D9332003CECE7 /* Team.swift */; }; + 3F745DF0246F48FC00CE7375 /* PlayerMoveType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3F745DEF246F48FC00CE7375 /* PlayerMoveType.swift */; }; 3FE19DB3246C690B004827AB /* RoundSimulatorService.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3FE19DB2246C690B004827AB /* RoundSimulatorService.swift */; }; 3FE19DB5246C7A22004827AB /* RoundCalculatorService.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3FE19DB4246C7A22004827AB /* RoundCalculatorService.swift */; }; 9E04AFAF245E2B73002D5CFC /* AttackActionComponent.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9E04AFAE245E2B73002D5CFC /* AttackActionComponent.swift */; }; @@ -86,6 +87,7 @@ 2086465B2461B66200817C23 /* TimerComponent.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TimerComponent.swift; sourceTree = ""; }; 3EBD242B245D8044003CECE7 /* GameCenterHelper.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GameCenterHelper.swift; sourceTree = ""; }; 3EBD242D245D9332003CECE7 /* Team.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Team.swift; sourceTree = ""; }; + 3F745DEF246F48FC00CE7375 /* PlayerMoveType.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlayerMoveType.swift; sourceTree = ""; }; 3FE19DB2246C690B004827AB /* RoundSimulatorService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RoundSimulatorService.swift; sourceTree = ""; }; 3FE19DB4246C7A22004827AB /* RoundCalculatorService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RoundCalculatorService.swift; sourceTree = ""; }; 9E04AFAE245E2B73002D5CFC /* AttackActionComponent.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AttackActionComponent.swift; sourceTree = ""; }; @@ -101,7 +103,7 @@ 9E78ACBD245CC9C000526FF7 /* AtkBoostSkillComponent.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AtkBoostSkillComponent.swift; sourceTree = ""; }; 9E78ACC1245CC9EE00526FF7 /* DefBoostSkillComponent.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DefBoostSkillComponent.swift; sourceTree = ""; }; 9E78ACC3245CCA3600526FF7 /* SpySkillComponent.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SpySkillComponent.swift; sourceTree = ""; }; - 9EA3ABE8245C6DAA006BC61D /* DefaultBaseComponent.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DefaultBaseComponent.swift; sourceTree = ""; }; + 9EA3ABE8245C6DAA006BC61D /* DefaultBaseComponent.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DefaultBaseComponent.swift; sourceTree = ""; wrapsLines = 1; }; 9EA3ABEA245C6DFA006BC61D /* BaseNode.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BaseNode.swift; sourceTree = ""; }; 9EA3ABEC245C8143006BC61D /* ModalBackgroundComponent.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ModalBackgroundComponent.swift; sourceTree = ""; }; 9EA3ABEE245C834B006BC61D /* ModalContentComponent.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ModalContentComponent.swift; sourceTree = ""; }; @@ -259,6 +261,7 @@ 11738A3A24508F68004426F1 /* Unit.swift */, 9EC86BA5245C8AD000796EF3 /* ModalType.swift */, 3EBD242D245D9332003CECE7 /* Team.swift */, + 3F745DEF246F48FC00CE7375 /* PlayerMoveType.swift */, ); path = Enums; sourceTree = ""; @@ -422,6 +425,7 @@ 9EA3ABED245C8143006BC61D /* ModalBackgroundComponent.swift in Sources */, C064E9A8246C0EA50022B228 /* LabelNode.swift in Sources */, 3EBD242C245D8044003CECE7 /* GameCenterHelper.swift in Sources */, + 3F745DF0246F48FC00CE7375 /* PlayerMoveType.swift in Sources */, AB1D759C245DD18100671525 /* MapProtocol.swift in Sources */, AB1D75A0245DEC0500671525 /* MapFactory.swift in Sources */, AB1D759D245DD18100671525 /* TwoPlayerDefaultTestMap.swift in Sources */, diff --git a/GoldWars/GoldWars/Components/TimerComponent.swift b/GoldWars/GoldWars/Components/TimerComponent.swift index 5ad2695..0b61efc 100644 --- a/GoldWars/GoldWars/Components/TimerComponent.swift +++ b/GoldWars/GoldWars/Components/TimerComponent.swift @@ -14,7 +14,7 @@ class TimerComponent: GKComponent { var endTime :Date! var duration :Double - init(text: String, anchorPoint: CGPoint, duration: TimeInterval) { + init(text: String, anchorPoint: CGPoint, duration: TimeInterval) { self.labelNode = SKLabelNode(text: text) self.labelNode.fontColor = UIColor.black self.labelNode.fontSize = CGFloat(45) @@ -50,7 +50,7 @@ class TimerComponent: GKComponent { } if !RoundCalculatorServie.sharedInstance.isCalculating && DataService.sharedInstance.didReceiveAllData(){ - RoundCalculatorServie.sharedInstance.calculateRound() + RoundCalculatorServie.sharedInstance.calculateRound() } } } diff --git a/GoldWars/GoldWars/DataService.swift b/GoldWars/GoldWars/DataService.swift index 8d2d331..c093697 100644 --- a/GoldWars/GoldWars/DataService.swift +++ b/GoldWars/GoldWars/DataService.swift @@ -9,22 +9,41 @@ struct PlayerMove: Codable{ let fromBase: Int let toBase: Int - let unitCount: Int + var unitCount: Int } struct Host: Codable { let playerID: String } +struct SnapshotModel: Codable { + var baseEntites: [BaseEntityModel]? +} + +struct BaseEntityModel: Codable { + let baseId: Int + var unitCount: Int + var ownership: String +} + class DataService { static let sharedInstance = DataService() var localPlayerMoves: [PlayerMove] = [] var remotePlayerMoves: [String: [PlayerMove]] = [:] + var snapshotModel = SnapshotModel() var gameHost: Host? - + + // TODO: Update entries to merge equal moves func addMove(playerMove: PlayerMove) { - self.localPlayerMoves.append(playerMove) + var equalMove = localPlayerMoves.filter { (ele) -> Bool in + ele.fromBase == playerMove.fromBase && ele.toBase == playerMove.toBase + } + if equalMove.count == 1 { + equalMove[0].unitCount = Int(equalMove[0].unitCount) + Int(playerMove.unitCount) + } else { + self.localPlayerMoves.append(playerMove) + } } func addRemotePlayerMoves(playerID: String, playerMoves: [PlayerMove]) { @@ -38,4 +57,8 @@ class DataService { func setGameHost(host: Host) { self.gameHost = host } + + func safeSnapshot(snapshotModel: SnapshotModel) { + self.snapshotModel = snapshotModel + } } diff --git a/GoldWars/GoldWars/Entities/Base.swift b/GoldWars/GoldWars/Entities/Base.swift index 97b6f1b..ad05629 100644 --- a/GoldWars/GoldWars/Entities/Base.swift +++ b/GoldWars/GoldWars/Entities/Base.swift @@ -17,7 +17,7 @@ class Base: GKEntity{ var changeOwnership: Bool var ownershipPlayer: GKPlayer? var baseID: Int - + init(position: CGPoint, player: GKPlayer! = nil, team: Team! = nil) { self.unitCount = 0 self.adjacencyList = [Base]() @@ -34,16 +34,17 @@ class Base: GKEntity{ } } - func attackBase(base: Base, units:Int) -> [GKEntity]{ + func doPlayerMoveTypeToBase(base: Base, playerMoveType: PlayerMoveType, units: Int) -> [GKEntity]{ base.changeOwnership = true base.ownershipPlayer = self.ownershipPlayer self.unitCount -= units base.unitCount += units - DataService.sharedInstance.addMove(playerMove: PlayerMove(fromBase: self.baseID, toBase: base.baseID, unitCount: units)) + DataService.sharedInstance.addMove(playerMove: PlayerMove(fromBase: self.baseID, + toBase: base.baseID, + unitCount: units * playerMoveType.rawValue)) return [self, base] } - - + required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } diff --git a/GoldWars/GoldWars/Entities/EntityManager.swift b/GoldWars/GoldWars/Entities/EntityManager.swift index 2f41dcf..a2ddeaa 100644 --- a/GoldWars/GoldWars/Entities/EntityManager.swift +++ b/GoldWars/GoldWars/Entities/EntityManager.swift @@ -181,4 +181,18 @@ class EntityManager { func getHUD() -> GKEntity? { return entities.filter{$0 is HUD}[0] } + + + + func getSnapshotModel() -> SnapshotModel { + let bases = entities.filter{$0 is Base} + var snapBase: [BaseEntityModel] = [] + + for entity in bases { + let base = entity as! Base + snapBase.append(BaseEntityModel(baseId: base.baseID, unitCount: base.unitCount, ownership: base.ownershipPlayer!.displayName)) + } + + return SnapshotModel(baseEntites: snapBase) + } } diff --git a/GoldWars/GoldWars/Enums/PlayerMoveType.swift b/GoldWars/GoldWars/Enums/PlayerMoveType.swift new file mode 100644 index 0000000..2f1bdd6 --- /dev/null +++ b/GoldWars/GoldWars/Enums/PlayerMoveType.swift @@ -0,0 +1,13 @@ +// +// PlayerMoveType.swift +// GoldWars +// +// Created by Aldin Duraki on 16.05.20. +// Copyright © 2020 SP2. All rights reserved. +// + +enum PlayerMoveType: Int, Codable{ + case AtkMove = 1 + case TxnMove = -1 +} + diff --git a/GoldWars/GoldWars/MatchmakingHelper.swift b/GoldWars/GoldWars/MatchmakingHelper.swift index d343e40..ca0ee49 100644 --- a/GoldWars/GoldWars/MatchmakingHelper.swift +++ b/GoldWars/GoldWars/MatchmakingHelper.swift @@ -116,6 +116,11 @@ class MatchmakingHelper: NSObject, GKMatchmakerViewControllerDelegate, GKMatchDe if let message = try? jsonDecoder.decode(Host.self, from: data) { DataService.sharedInstance.gameHost = message } + + if let snapshotModel = try? jsonDecoder.decode(SnapshotModel.self, from: data) { + DataService.sharedInstance.snapshotModel = snapshotModel + } + MultiplayerNetwork.sharedInstance.isSending = false } diff --git a/GoldWars/GoldWars/MultiplayerNetwork.swift b/GoldWars/GoldWars/MultiplayerNetwork.swift index 36503ad..1511377 100644 --- a/GoldWars/GoldWars/MultiplayerNetwork.swift +++ b/GoldWars/GoldWars/MultiplayerNetwork.swift @@ -57,5 +57,11 @@ class MultiplayerNetwork{ let encoded = (try? encoder.encode(DataService.sharedInstance.gameHost))! sendData(data: encoded) } + + func sendSnapshotModelToPlayers() { + let encoder = JSONEncoder() + let encoded = (try? encoder.encode(DataService.sharedInstance.snapshotModel))! + sendData(data: encoded) + } } diff --git a/GoldWars/GoldWars/RoundCalculatorService.swift b/GoldWars/GoldWars/RoundCalculatorService.swift index 2032a93..fd300b7 100644 --- a/GoldWars/GoldWars/RoundCalculatorService.swift +++ b/GoldWars/GoldWars/RoundCalculatorService.swift @@ -11,15 +11,19 @@ import GameKit import os class RoundCalculatorServie { - static let sharedInstance = RoundCalculatorServie() - - var allPlayerMoves: [String: [PlayerMove]] = [:] - var baseSpecificMove: [Int: [(String, PlayerMove)]] = [:] var isCalculating = false + var allPlayerMoves: [String: [PlayerMove]] = [:] + var baseSpecificMoves: [Int: [String: PlayerMove]] = [:] + func calculateRound() { + os_log("Started calculating Round", log: OSLog.default, type: .info) + let startTime = CFAbsoluteTimeGetCurrent() isCalculating = true + let currentSnapshotModel = DataService.sharedInstance.snapshotModel.baseEntites + + // TODO: smarter way? for entry in DataService.sharedInstance.remotePlayerMoves { addPlayerMove(playerID: entry.key, playerMoves: entry.value) } @@ -27,22 +31,80 @@ class RoundCalculatorServie { for entry in allPlayerMoves { for move in entry.value { - addFiltedMove(playerName: entry.key, playerMove: move) + mapPlayerMoveToAttackedBase(playerName: entry.key, playerMove: move) } } - // berechnen nach minimal substraction + // TODO-END: - - print(baseSpecificMove) - isCalculating = false - // sende an alle anderen spieler die moves + for (key, value) in baseSpecificMoves { + let baseId = key + var playerMovesByBase = value + + let targetBase = currentSnapshotModel?.filter { $0.baseId == baseId }[0] + let possiblyOwnershipMoves = playerMovesByBase.filter { $0.key == targetBase?.ownership} + + // spieler verschiebt einheiten beim schieben + for (playerName, playerMove) in possiblyOwnershipMoves { + for var base in currentSnapshotModel! { + if base.baseId == playerMove.fromBase { + base.unitCount -= playerMove.unitCount + } + if base.baseId == playerMove.toBase { + base.unitCount += playerMove.unitCount + } + } + playerMovesByBase.removeValue(forKey: playerName) + } + + for (playerName, playerMove) in playerMovesByBase { + for var base in currentSnapshotModel! { + if base.baseId == playerMove.fromBase { + base.unitCount -= playerMove.unitCount + } + } + } + + + let sorted = playerMovesByBase.sorted { (e1: (key: String, value: PlayerMove), e2: (key: String, value: PlayerMove)) -> Bool in + e1.value.unitCount > e2.value.unitCount + } + + var max = sorted[0] + let secMax = sorted[1] + max.value.unitCount -= secMax.value.unitCount + + for var base in currentSnapshotModel! { + if base.baseId == max.value.toBase { + base.unitCount -= max.value.unitCount + base.ownership = max.key + } + } + + baseSpecificMoves.removeValue(forKey: baseId) + } + + MultiplayerNetwork.sharedInstance.sendSnapshotModelToPlayers() + let calcTime = CFAbsoluteTimeGetCurrent() - startTime + os_log("Finished calculating Round in %{calcTimer}", log: OSLog.default, type: .info, calcTime) } func addPlayerMove(playerID: String, playerMoves: [PlayerMove]) { self.allPlayerMoves[playerID] = playerMoves } - func addFiltedMove(playerName: String, playerMove: PlayerMove) { - self.baseSpecificMove.merge([playerMove.toBase : [(playerName, playerMove)]], uniquingKeysWith: +) + func mapPlayerMoveToAttackedBase(playerName: String, playerMove: PlayerMove) { + if self.baseSpecificMoves.keys.contains(playerMove.toBase) { + var playerMovesForSameBase = self.baseSpecificMoves[playerMove.toBase]! + if playerMovesForSameBase.keys.contains(playerName) { + playerMovesForSameBase[playerName] = playerMove + } + } else { + self.baseSpecificMoves[playerMove.toBase] = [playerName: playerMove] + } } + + func resolvePlayerMove(playerMove: PlayerMove, unitCount: Int, ownership: String?, resolveType: String) { + //outsource playermoves || tnx, remove, add(with calc) + } + } diff --git a/GoldWars/GoldWars/Scenes/GameScene.swift b/GoldWars/GoldWars/Scenes/GameScene.swift index dae1566..3a5a5c8 100644 --- a/GoldWars/GoldWars/Scenes/GameScene.swift +++ b/GoldWars/GoldWars/Scenes/GameScene.swift @@ -26,6 +26,7 @@ class GameScene: SKScene{ func initMap() { MapFactory(scene: self, entityManager: self.entityManager).loadMap(playerCount: 2) + DataService.sharedInstance.safeSnapshot(snapshotModel: entityManager.getSnapshotModel()) } override func touchesEnded(_ touches: Set, with event: UIEvent?) { @@ -49,12 +50,13 @@ class GameScene: SKScene{ base: currentDraggedBase!, anchorPoint: CGPoint(x: self.size.width / 2 , y: self.size.height / 2), entityManager: entityManager, gameScene: self)) - entityManager.update((currentDraggedBase?.attackBase(base: base, units: 100))!) + entityManager.update((currentDraggedBase?.doPlayerMoveTypeToBase(base: base, playerMoveType: PlayerMoveType.AtkMove, units: 100))!) }else { entityManager.add(Modal(modaltype: .BaseAttack, base: currentDraggedBase!, anchorPoint: CGPoint(x: self.size.width / 2 , y: self.size.height / 2), entityManager: entityManager, gameScene: self)) + entityManager.update((currentDraggedBase?.doPlayerMoveTypeToBase(base: base,playerMoveType: PlayerMoveType.TxnMove, units: -100))!) } } From 1dc97c3bab7cf794a6b211da895d6c7dbfdbe321 Mon Sep 17 00:00:00 2001 From: Aldin Duraki Date: Sun, 17 May 2020 21:48:17 +0200 Subject: [PATCH 19/28] Solve Mergeconflicts --- GoldWars/GoldWars/Entities/Modal.swift | 14 +++++++------- GoldWars/GoldWars/RoundCalculatorService.swift | 2 +- GoldWars/GoldWars/Scenes/GameScene.swift | 15 +++++++-------- 3 files changed, 15 insertions(+), 16 deletions(-) diff --git a/GoldWars/GoldWars/Entities/Modal.swift b/GoldWars/GoldWars/Entities/Modal.swift index 516efb0..31b9940 100644 --- a/GoldWars/GoldWars/Entities/Modal.swift +++ b/GoldWars/GoldWars/Entities/Modal.swift @@ -12,7 +12,7 @@ class Modal: GKEntity{ var unitCount:Int - init(modaltype: ModalType, base: Base, anchorPoint: CGPoint, entityManager: EntityManager, gameScene: SKScene) { + init(modaltype: ModalType, base: Base, anchorPoint: CGPoint, gameScene: SKScene) { unitCount = base.unitCount super.init() switch modaltype{ @@ -20,7 +20,7 @@ class Modal: GKEntity{ addComponent(ModalBackgroundComponent(anchorPoint: anchorPoint)) addComponent(ModalContentComponent(header: "Basis Information", body: "Diese Basis enthält \(base.unitCount) Einheiten", footer: "", anchorPoint: anchorPoint)) addComponent(ButtonComponent(iconName: "", text: "Zurück", position: CGPoint(x: anchorPoint.x , y: anchorPoint.y - 120), isEnabled: true, onButtonPress: { - self.removeModalEntities(entityManager: entityManager, gameScene: gameScene) + self.removeModalEntities(gameScene: gameScene) })) case .BaseAttack: addComponent(ModalBackgroundComponent(anchorPoint: anchorPoint)) @@ -28,7 +28,7 @@ class Modal: GKEntity{ addComponent(ModalContentComponent(header: "Angriff", body: "Schicke \(unitCount / 2) Einheiten", footer: "", anchorPoint: anchorPoint)) addComponent(ButtonComponent(iconName: "", text: "Senden", position: CGPoint(x: anchorPoint.x , y: anchorPoint.y - 120), isEnabled: true, onButtonPress: { - self.removeModalEntities(entityManager: entityManager, gameScene: gameScene) + self.removeModalEntities(gameScene: gameScene) })) } } @@ -37,10 +37,10 @@ class Modal: GKEntity{ fatalError("init(coder:) has not been implemented") } - func removeModalEntities(entityManager: EntityManager, gameScene: SKScene){ - for entity in entityManager.entities { - if entityManager.isModal && entity.isMember(of: Modal.self) { - entityManager.remove(entity) + func removeModalEntities(gameScene: SKScene){ + for entity in EntityManager.sharedInstance.entities { + if EntityManager.sharedInstance.isModal && entity.isMember(of: Modal.self) { + EntityManager.sharedInstance.remove(entity) } for child in gameScene.children { if(child.name != "fire"){ diff --git a/GoldWars/GoldWars/RoundCalculatorService.swift b/GoldWars/GoldWars/RoundCalculatorService.swift index fd300b7..117a715 100644 --- a/GoldWars/GoldWars/RoundCalculatorService.swift +++ b/GoldWars/GoldWars/RoundCalculatorService.swift @@ -56,7 +56,7 @@ class RoundCalculatorServie { playerMovesByBase.removeValue(forKey: playerName) } - for (playerName, playerMove) in playerMovesByBase { + for (_, playerMove) in playerMovesByBase { for var base in currentSnapshotModel! { if base.baseId == playerMove.fromBase { base.unitCount -= playerMove.unitCount diff --git a/GoldWars/GoldWars/Scenes/GameScene.swift b/GoldWars/GoldWars/Scenes/GameScene.swift index 58ea2e2..a6934bd 100644 --- a/GoldWars/GoldWars/Scenes/GameScene.swift +++ b/GoldWars/GoldWars/Scenes/GameScene.swift @@ -24,8 +24,8 @@ class GameScene: SKScene{ } func initMap() { - MapFactory(scene: self, entityManager: self.entityManager).loadMap(playerCount: 2) - DataService.sharedInstance.safeSnapshot(snapshotModel: entityManager.getSnapshotModel()) + MapFactory(scene: self, entityManager: EntityManager.sharedInstance).loadMap(playerCount: 2) + DataService.sharedInstance.safeSnapshot(snapshotModel: EntityManager.sharedInstance.getSnapshotModel()) } override func touchesEnded(_ touches: Set, with event: UIEvent?) { @@ -48,14 +48,13 @@ class GameScene: SKScene{ EntityManager.sharedInstance.add(Modal(modaltype: .BaseAttack, base: currentDraggedBase!, anchorPoint: CGPoint(x: self.size.width / 2 , y: self.size.height / 2), - entityManager: EntityManager.sharedInstance, gameScene: self)) - EntityManager.sharedInstance.update((currentDraggedBase?.attackBase(base: base, units: 100))!) + gameScene: self)) + EntityManager.sharedInstance.update((currentDraggedBase?.doPlayerMoveTypeToBase(base: base, playerMoveType: PlayerMoveType.AtkMove, units: 100))!) }else { EntityManager.sharedInstance.add(Modal(modaltype: .BaseAttack, base: currentDraggedBase!, - anchorPoint: CGPoint(x: self.size.width / 2 , y: self.size.height / 2), - entityManager: entityManager, gameScene: self)) - entityManager.update((currentDraggedBase?.doPlayerMoveTypeToBase(base: base,playerMoveType: PlayerMoveType.TxnMove, units: -100))!) + anchorPoint: CGPoint(x: self.size.width / 2 , y: self.size.height / 2), gameScene: self)) + EntityManager.sharedInstance.update((currentDraggedBase?.doPlayerMoveTypeToBase(base: base,playerMoveType: PlayerMoveType.TxnMove, units: -100))!) } } @@ -76,7 +75,7 @@ class GameScene: SKScene{ EntityManager.sharedInstance.add(Modal(modaltype: .BaseDetails, base: entity as! Base, anchorPoint: CGPoint(x: self.size.width / 2 , y: self.size.height / 2), - entityManager: EntityManager.sharedInstance, gameScene: self)) + gameScene: self)) } } } From e08d40dd4a634eded85a62d98a7479a91e221e2d Mon Sep 17 00:00:00 2001 From: Aldin Duraki Date: Mon, 18 May 2020 00:27:53 +0200 Subject: [PATCH 20/28] TEST: snapshotModel not updating --- GoldWars/GoldWars/DataService.swift | 16 +++++--- .../GoldWars/Entities/EntityManager.swift | 27 ++++++++++++- GoldWars/GoldWars/MatchmakingHelper.swift | 20 +++++++++- GoldWars/GoldWars/MultiplayerNetwork.swift | 6 ++- .../GoldWars/RoundCalculatorService.swift | 40 ++++++++++++------- 5 files changed, 84 insertions(+), 25 deletions(-) diff --git a/GoldWars/GoldWars/DataService.swift b/GoldWars/GoldWars/DataService.swift index c093697..44dd5fe 100644 --- a/GoldWars/GoldWars/DataService.swift +++ b/GoldWars/GoldWars/DataService.swift @@ -13,17 +13,23 @@ struct PlayerMove: Codable{ } struct Host: Codable { - let playerID: String + let playerName: String } struct SnapshotModel: Codable { var baseEntites: [BaseEntityModel]? } -struct BaseEntityModel: Codable { +class BaseEntityModel: Codable { let baseId: Int var unitCount: Int - var ownership: String + var ownership: String? + + init(baseId: Int, unitCount: Int, ownership: String?) { + self.baseId = baseId + self.unitCount = unitCount + self.ownership = ownership + } } class DataService { @@ -46,8 +52,8 @@ class DataService { } } - func addRemotePlayerMoves(playerID: String, playerMoves: [PlayerMove]) { - self.remotePlayerMoves[playerID] = playerMoves + func addRemotePlayerMoves(playerName: String, playerMoves: [PlayerMove]) { + self.remotePlayerMoves[playerName] = playerMoves } func didReceiveAllData() -> Bool { diff --git a/GoldWars/GoldWars/Entities/EntityManager.swift b/GoldWars/GoldWars/Entities/EntityManager.swift index 2e4713f..fe32c99 100644 --- a/GoldWars/GoldWars/Entities/EntityManager.swift +++ b/GoldWars/GoldWars/Entities/EntityManager.swift @@ -119,9 +119,32 @@ class EntityManager { scene.addChild(base.component(ofType: TeamComponent.self)!.fire) } } - } + func updateSnapshotModel(snapshotModel: SnapshotModel) { + let bases = entities.filter{$0 is Base} + for entity in bases{ + let base = entity as! Base + let snapBase = self.getSnapshotBaseById(baseId: base.baseID, snapshotModel: snapshotModel) + print("in updateSnap -> Entity \(base)") + print("in updateSnap -> snapBase \(snapBase)") + var getOwnerBySnapBase: GKPlayer? = nil + base.unitCount = snapBase.unitCount + + if snapBase.ownership != nil { + getOwnerBySnapBase = MatchmakingHelper.sharedInstance.getGKPlayerByUsername(displayName: snapBase.ownership!) + } + if getOwnerBySnapBase != nil { + base.ownershipPlayer = getOwnerBySnapBase + } + print("nach updateSnap -> Entity \(base)") + } + } + + func getSnapshotBaseById(baseId: Int, snapshotModel: SnapshotModel) -> BaseEntityModel{ + return (snapshotModel.baseEntites?.filter { $0.baseId == baseId }[0])! + } + func getBaseByPlayer(for player: GKPlayer) -> GKEntity? { for entity in entities { if let teamComponent = entity.component(ofType: TeamComponent.self), @@ -200,7 +223,7 @@ class EntityManager { for entity in bases { let base = entity as! Base - snapBase.append(BaseEntityModel(baseId: base.baseID, unitCount: base.unitCount, ownership: base.ownershipPlayer!.displayName)) + snapBase.append(BaseEntityModel(baseId: base.baseID, unitCount: base.unitCount, ownership: base.ownershipPlayer?.displayName)) } return SnapshotModel(baseEntites: snapBase) diff --git a/GoldWars/GoldWars/MatchmakingHelper.swift b/GoldWars/GoldWars/MatchmakingHelper.swift index ca0ee49..dbdc066 100644 --- a/GoldWars/GoldWars/MatchmakingHelper.swift +++ b/GoldWars/GoldWars/MatchmakingHelper.swift @@ -110,7 +110,7 @@ class MatchmakingHelper: NSObject, GKMatchmakerViewControllerDelegate, GKMatchDe let jsonDecoder = JSONDecoder() if let playerMoves = try? jsonDecoder.decode([PlayerMove].self, from: data) { - DataService.sharedInstance.addRemotePlayerMoves(playerID: player.displayName, playerMoves: playerMoves) + DataService.sharedInstance.addRemotePlayerMoves(playerName: player.displayName, playerMoves: playerMoves) } if let message = try? jsonDecoder.decode(Host.self, from: data) { @@ -118,7 +118,9 @@ class MatchmakingHelper: NSObject, GKMatchmakerViewControllerDelegate, GKMatchDe } if let snapshotModel = try? jsonDecoder.decode(SnapshotModel.self, from: data) { + print("received data package -> \(snapshotModel)") DataService.sharedInstance.snapshotModel = snapshotModel + EntityManager.sharedInstance.updateSnapshotModel(snapshotModel: snapshotModel) } MultiplayerNetwork.sharedInstance.isSending = false @@ -170,7 +172,7 @@ class MatchmakingHelper: NSObject, GKMatchmakerViewControllerDelegate, GKMatchDe self.isServer = true self.spieler1 = player self.nameSpieler1 = self.spieler1!.displayName - DataService.sharedInstance.setGameHost(host: Host(playerID: player!.displayName)) + DataService.sharedInstance.setGameHost(host: Host(playerName: player!.displayName)) } else { self.isServer = false } @@ -181,6 +183,20 @@ class MatchmakingHelper: NSObject, GKMatchmakerViewControllerDelegate, GKMatchDe }) } + func getGKPlayerByUsername(displayName: String) -> GKPlayer? { + let nilGK : GKPlayer? = nil + + if GKLocalPlayer.local.displayName == displayName { + return GKLocalPlayer.local + } + + for player in mpMatch!.players { + if player.displayName == displayName { + return player + } + } + return nilGK + } /* Trennt die Verbindung vom Match diff --git a/GoldWars/GoldWars/MultiplayerNetwork.swift b/GoldWars/GoldWars/MultiplayerNetwork.swift index 1511377..8b470bd 100644 --- a/GoldWars/GoldWars/MultiplayerNetwork.swift +++ b/GoldWars/GoldWars/MultiplayerNetwork.swift @@ -30,9 +30,9 @@ class MultiplayerNetwork{ for player in mmHelper.mpMatch!.players { print(player.displayName) } - print(DataService.sharedInstance.gameHost!.playerID) + print(DataService.sharedInstance.gameHost!.playerName) - let hostGKPlayer = MatchmakingHelper.sharedInstance.mpMatch?.players.filter{ $0.displayName == DataService.sharedInstance.gameHost!.playerID}[0] + let hostGKPlayer = MatchmakingHelper.sharedInstance.mpMatch?.players.filter{ $0.displayName == DataService.sharedInstance.gameHost!.playerName}[0] if let multiplayerMatch = mmHelper.mpMatch{ do { @@ -59,8 +59,10 @@ class MultiplayerNetwork{ } func sendSnapshotModelToPlayers() { + print("sending snapshot -> \(DataService.sharedInstance.snapshotModel)") let encoder = JSONEncoder() let encoded = (try? encoder.encode(DataService.sharedInstance.snapshotModel))! + print("sending package -> \(encoded)") sendData(data: encoded) } diff --git a/GoldWars/GoldWars/RoundCalculatorService.swift b/GoldWars/GoldWars/RoundCalculatorService.swift index 117a715..a8e08bb 100644 --- a/GoldWars/GoldWars/RoundCalculatorService.swift +++ b/GoldWars/GoldWars/RoundCalculatorService.swift @@ -21,14 +21,16 @@ class RoundCalculatorServie { os_log("Started calculating Round", log: OSLog.default, type: .info) let startTime = CFAbsoluteTimeGetCurrent() isCalculating = true - let currentSnapshotModel = DataService.sharedInstance.snapshotModel.baseEntites + + var currentSnapshotModel = DataService.sharedInstance.snapshotModel // TODO: smarter way? for entry in DataService.sharedInstance.remotePlayerMoves { - addPlayerMove(playerID: entry.key, playerMoves: entry.value) + addPlayerMove(playerName: entry.key, playerMoves: entry.value) } - addPlayerMove(playerID: GKLocalPlayer.local.displayName, playerMoves: DataService.sharedInstance.localPlayerMoves) + addPlayerMove(playerName: GKLocalPlayer.local.displayName, playerMoves: DataService.sharedInstance.localPlayerMoves) + print("allPlayerMoves -> \(allPlayerMoves)") for entry in allPlayerMoves { for move in entry.value { mapPlayerMoveToAttackedBase(playerName: entry.key, playerMove: move) @@ -40,12 +42,12 @@ class RoundCalculatorServie { let baseId = key var playerMovesByBase = value - let targetBase = currentSnapshotModel?.filter { $0.baseId == baseId }[0] + let targetBase = currentSnapshotModel.baseEntites?.filter { $0.baseId == baseId }[0] let possiblyOwnershipMoves = playerMovesByBase.filter { $0.key == targetBase?.ownership} // spieler verschiebt einheiten beim schieben for (playerName, playerMove) in possiblyOwnershipMoves { - for var base in currentSnapshotModel! { + for var base in currentSnapshotModel.baseEntites! { if base.baseId == playerMove.fromBase { base.unitCount -= playerMove.unitCount } @@ -57,7 +59,7 @@ class RoundCalculatorServie { } for (_, playerMove) in playerMovesByBase { - for var base in currentSnapshotModel! { + for var base in currentSnapshotModel.baseEntites! { if base.baseId == playerMove.fromBase { base.unitCount -= playerMove.unitCount } @@ -70,26 +72,36 @@ class RoundCalculatorServie { } var max = sorted[0] - let secMax = sorted[1] - max.value.unitCount -= secMax.value.unitCount + if sorted.count == 2 { + let secMax = sorted[1] + max.value.unitCount -= secMax.value.unitCount + + } - for var base in currentSnapshotModel! { + for var base in currentSnapshotModel.baseEntites! { if base.baseId == max.value.toBase { - base.unitCount -= max.value.unitCount - base.ownership = max.key + base.unitCount += max.value.unitCount + if max.value.unitCount == 0 { + base.ownership = nil + } else { + base.ownership = max.key + } + } } baseSpecificMoves.removeValue(forKey: baseId) } + print(currentSnapshotModel) MultiplayerNetwork.sharedInstance.sendSnapshotModelToPlayers() + EntityManager.sharedInstance.updateSnapshotModel(snapshotModel: currentSnapshotModel) let calcTime = CFAbsoluteTimeGetCurrent() - startTime - os_log("Finished calculating Round in %{calcTimer}", log: OSLog.default, type: .info, calcTime) + os_log("Finished calculating Round in %@", log: OSLog.default, type: .info, calcTime) } - func addPlayerMove(playerID: String, playerMoves: [PlayerMove]) { - self.allPlayerMoves[playerID] = playerMoves + func addPlayerMove(playerName: String, playerMoves: [PlayerMove]) { + self.allPlayerMoves[playerName] = playerMoves } func mapPlayerMoveToAttackedBase(playerName: String, playerMove: PlayerMove) { From 4a1b43a70d95ea0c924c549f40aa6035b6c79910 Mon Sep 17 00:00:00 2001 From: Aldin Duraki Date: Mon, 18 May 2020 01:03:25 +0200 Subject: [PATCH 21/28] TEST: Change dependencies of optional types --- GoldWars/GoldWars/Components/TimerComponent.swift | 9 +++++---- GoldWars/GoldWars/DataService.swift | 14 +++++++++++--- GoldWars/GoldWars/Entities/EntityManager.swift | 2 +- GoldWars/GoldWars/RoundCalculatorService.swift | 12 ++++++------ 4 files changed, 23 insertions(+), 14 deletions(-) diff --git a/GoldWars/GoldWars/Components/TimerComponent.swift b/GoldWars/GoldWars/Components/TimerComponent.swift index 0b61efc..596fd7b 100644 --- a/GoldWars/GoldWars/Components/TimerComponent.swift +++ b/GoldWars/GoldWars/Components/TimerComponent.swift @@ -9,11 +9,11 @@ import GameplayKit class TimerComponent: GKComponent { - + let labelNode :SKLabelNode var endTime :Date! var duration :Double - + init(text: String, anchorPoint: CGPoint, duration: TimeInterval) { self.labelNode = SKLabelNode(text: text) self.labelNode.fontColor = UIColor.black @@ -49,7 +49,8 @@ class TimerComponent: GKComponent { MultiplayerNetwork.sharedInstance.sendPlayerMoves(playerMoves: DataService.sharedInstance.localPlayerMoves) } if !RoundCalculatorServie.sharedInstance.isCalculating - && DataService.sharedInstance.didReceiveAllData(){ + && DataService.sharedInstance.didReceiveAllData() + && MatchmakingHelper.sharedInstance.isServer { RoundCalculatorServie.sharedInstance.calculateRound() } } @@ -58,6 +59,6 @@ class TimerComponent: GKComponent { required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } - + } diff --git a/GoldWars/GoldWars/DataService.swift b/GoldWars/GoldWars/DataService.swift index 44dd5fe..452e65f 100644 --- a/GoldWars/GoldWars/DataService.swift +++ b/GoldWars/GoldWars/DataService.swift @@ -16,8 +16,16 @@ struct Host: Codable { let playerName: String } -struct SnapshotModel: Codable { - var baseEntites: [BaseEntityModel]? +class SnapshotModel: Codable { + var baseEntites: [BaseEntityModel] +// +// init() { +// self.baseEntites = [] +// } +// + init(baseEntites: [BaseEntityModel]) { + self.baseEntites = baseEntites + } } class BaseEntityModel: Codable { @@ -36,7 +44,7 @@ class DataService { static let sharedInstance = DataService() var localPlayerMoves: [PlayerMove] = [] var remotePlayerMoves: [String: [PlayerMove]] = [:] - var snapshotModel = SnapshotModel() + var snapshotModel: SnapshotModel? var gameHost: Host? diff --git a/GoldWars/GoldWars/Entities/EntityManager.swift b/GoldWars/GoldWars/Entities/EntityManager.swift index fe32c99..1dbda90 100644 --- a/GoldWars/GoldWars/Entities/EntityManager.swift +++ b/GoldWars/GoldWars/Entities/EntityManager.swift @@ -142,7 +142,7 @@ class EntityManager { } func getSnapshotBaseById(baseId: Int, snapshotModel: SnapshotModel) -> BaseEntityModel{ - return (snapshotModel.baseEntites?.filter { $0.baseId == baseId }[0])! + return snapshotModel.baseEntites.filter { $0.baseId == baseId }[0] } func getBaseByPlayer(for player: GKPlayer) -> GKEntity? { diff --git a/GoldWars/GoldWars/RoundCalculatorService.swift b/GoldWars/GoldWars/RoundCalculatorService.swift index a8e08bb..b8fde43 100644 --- a/GoldWars/GoldWars/RoundCalculatorService.swift +++ b/GoldWars/GoldWars/RoundCalculatorService.swift @@ -42,12 +42,12 @@ class RoundCalculatorServie { let baseId = key var playerMovesByBase = value - let targetBase = currentSnapshotModel.baseEntites?.filter { $0.baseId == baseId }[0] + let targetBase = currentSnapshotModel?.baseEntites.filter { $0.baseId == baseId }[0] let possiblyOwnershipMoves = playerMovesByBase.filter { $0.key == targetBase?.ownership} // spieler verschiebt einheiten beim schieben for (playerName, playerMove) in possiblyOwnershipMoves { - for var base in currentSnapshotModel.baseEntites! { + for var base in currentSnapshotModel!.baseEntites { if base.baseId == playerMove.fromBase { base.unitCount -= playerMove.unitCount } @@ -59,7 +59,7 @@ class RoundCalculatorServie { } for (_, playerMove) in playerMovesByBase { - for var base in currentSnapshotModel.baseEntites! { + for var base in currentSnapshotModel!.baseEntites { if base.baseId == playerMove.fromBase { base.unitCount -= playerMove.unitCount } @@ -78,7 +78,7 @@ class RoundCalculatorServie { } - for var base in currentSnapshotModel.baseEntites! { + for var base in currentSnapshotModel!.baseEntites { if base.baseId == max.value.toBase { base.unitCount += max.value.unitCount if max.value.unitCount == 0 { @@ -95,9 +95,9 @@ class RoundCalculatorServie { print(currentSnapshotModel) MultiplayerNetwork.sharedInstance.sendSnapshotModelToPlayers() - EntityManager.sharedInstance.updateSnapshotModel(snapshotModel: currentSnapshotModel) + EntityManager.sharedInstance.updateSnapshotModel(snapshotModel: currentSnapshotModel!) let calcTime = CFAbsoluteTimeGetCurrent() - startTime - os_log("Finished calculating Round in %@", log: OSLog.default, type: .info, calcTime) + os_log("Finished calculating Round in %@", log: OSLog.default, type: .info) } func addPlayerMove(playerName: String, playerMoves: [PlayerMove]) { From 0db2be86253a2bf7c0e30d6c3fa98e5e2431fc77 Mon Sep 17 00:00:00 2001 From: Aldin Duraki Date: Mon, 18 May 2020 02:00:13 +0200 Subject: [PATCH 22/28] Test: trying to add the TeamComponent to the new captured base [unsafe-state] --- GoldWars/GoldWars/Entities/EntityManager.swift | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/GoldWars/GoldWars/Entities/EntityManager.swift b/GoldWars/GoldWars/Entities/EntityManager.swift index 1dbda90..9ebfc7a 100644 --- a/GoldWars/GoldWars/Entities/EntityManager.swift +++ b/GoldWars/GoldWars/Entities/EntityManager.swift @@ -135,8 +135,18 @@ class EntityManager { getOwnerBySnapBase = MatchmakingHelper.sharedInstance.getGKPlayerByUsername(displayName: snapBase.ownership!) } if getOwnerBySnapBase != nil { + base.changeOwnership = true base.ownershipPlayer = getOwnerBySnapBase + entity.addComponent(TeamComponent( + team: getTeamByPlayer(playerName: snapBase.ownership!), + player: getOwnerBySnapBase!, + position: (entity.component(ofType: DefaultBaseComponent.self)?.spriteNode.position)! + ) + ) + print(entity) + print(getTeamByBase(base: base)) } + print("nach updateSnap -> Entity \(base)") } } @@ -189,6 +199,10 @@ class EntityManager { } return nil } + + func getTeamByPlayer(playerName: String) -> Team { + return entities.filter { $0 is Base && ($0 as! Base).component(ofType: TeamComponent.self)?.player.displayName == playerName }[0].component(ofType: TeamComponent.self)!.team + } func getBasebyID(id: Int) -> Base?{ for entity in entities { From b04bbe5036cc0953b5a893c46aa32ea5d6f2f81f Mon Sep 17 00:00:00 2001 From: Aldin Duraki Date: Tue, 19 May 2020 02:21:41 +0200 Subject: [PATCH 23/28] * Fixed TeamComponent when updating Entities * Minor refactor --- .../GoldWars/Components/TeamComponent.swift | 4 +- GoldWars/GoldWars/DataService.swift | 10 +-- .../GoldWars/Entities/EntityManager.swift | 70 +++++++++++-------- .../GoldWars/RoundCalculatorService.swift | 17 ++--- GoldWars/GoldWars/Scenes/GameScene.swift | 2 +- 5 files changed, 52 insertions(+), 51 deletions(-) diff --git a/GoldWars/GoldWars/Components/TeamComponent.swift b/GoldWars/GoldWars/Components/TeamComponent.swift index 2369f7b..db67deb 100644 --- a/GoldWars/GoldWars/Components/TeamComponent.swift +++ b/GoldWars/GoldWars/Components/TeamComponent.swift @@ -11,9 +11,9 @@ import GameplayKit import GameKit class TeamComponent: GKComponent { - let team: Team + var team: Team + var player: GKPlayer let fire: SKEmitterNode - let player: GKPlayer init(team: Team, player: GKPlayer, position: CGPoint) { fire = SKEmitterNode(fileNamed: "Fire")! diff --git a/GoldWars/GoldWars/DataService.swift b/GoldWars/GoldWars/DataService.swift index 452e65f..e06dff6 100644 --- a/GoldWars/GoldWars/DataService.swift +++ b/GoldWars/GoldWars/DataService.swift @@ -18,11 +18,7 @@ struct Host: Codable { class SnapshotModel: Codable { var baseEntites: [BaseEntityModel] -// -// init() { -// self.baseEntites = [] -// } -// + init(baseEntites: [BaseEntityModel]) { self.baseEntites = baseEntites } @@ -47,8 +43,6 @@ class DataService { var snapshotModel: SnapshotModel? var gameHost: Host? - - // TODO: Update entries to merge equal moves func addMove(playerMove: PlayerMove) { var equalMove = localPlayerMoves.filter { (ele) -> Bool in ele.fromBase == playerMove.fromBase && ele.toBase == playerMove.toBase @@ -72,7 +66,7 @@ class DataService { self.gameHost = host } - func safeSnapshot(snapshotModel: SnapshotModel) { + func setSnapshotModel(snapshotModel: SnapshotModel) { self.snapshotModel = snapshotModel } } diff --git a/GoldWars/GoldWars/Entities/EntityManager.swift b/GoldWars/GoldWars/Entities/EntityManager.swift index 9ebfc7a..82b37d9 100644 --- a/GoldWars/GoldWars/Entities/EntityManager.swift +++ b/GoldWars/GoldWars/Entities/EntityManager.swift @@ -102,25 +102,30 @@ class EntityManager { } entities.remove(entity) } - + func update(_ entities: [GKEntity]){ for entity in entities { self.entities.update(with: entity) let base = (entity as! Base) - + if base.changeOwnership { - base.addComponent(TeamComponent( - team: (entities[0] as! Base).component(ofType: TeamComponent.self)!.team, - player: (entities[0] as! Base).component(ofType: TeamComponent.self)!.player, - position: (base.component(ofType: DefaultBaseComponent.self)?.spriteNode.position)! + if let component = entity.component(ofType: TeamComponent.self) { + component.player = entities[0].component(ofType: TeamComponent.self)!.player + component.team = entities[0].component(ofType: TeamComponent.self)!.team + } else { + base.addComponent(TeamComponent( + team: (entities[0] as! Base).component(ofType: TeamComponent.self)!.team, + player: (entities[0] as! Base).component(ofType: TeamComponent.self)!.player, + position: (base.component(ofType: DefaultBaseComponent.self)?.spriteNode.position)! + ) ) - ) + } base.changeOwnership = false scene.addChild(base.component(ofType: TeamComponent.self)!.fire) } } } - + func updateSnapshotModel(snapshotModel: SnapshotModel) { let bases = entities.filter{$0 is Base} for entity in bases{ @@ -137,14 +142,21 @@ class EntityManager { if getOwnerBySnapBase != nil { base.changeOwnership = true base.ownershipPlayer = getOwnerBySnapBase - entity.addComponent(TeamComponent( + if let component = entity.component(ofType: TeamComponent.self) { + component.player = getOwnerBySnapBase! + component.team = getTeamByPlayer(playerName: snapBase.ownership!) + } else { + entity.addComponent(TeamComponent( team: getTeamByPlayer(playerName: snapBase.ownership!), player: getOwnerBySnapBase!, position: (entity.component(ofType: DefaultBaseComponent.self)?.spriteNode.position)! + ) ) - ) - print(entity) - print(getTeamByBase(base: base)) + if let fire = entity.component(ofType: TeamComponent.self)?.fire{ + scene.addChild(fire) + } + } + } print("nach updateSnap -> Entity \(base)") @@ -166,7 +178,7 @@ class EntityManager { } return nil } - + func getBaseByTeam(for team: Team) -> GKEntity? { for entity in entities { if let teamComponent = entity.component(ofType: TeamComponent.self), @@ -178,15 +190,15 @@ class EntityManager { } return nil } - + func getBasesByTeam(for team: Team) -> Set { return entities.filter{$0 is Base && ($0 as! Base).component(ofType: TeamComponent.self)?.team == team } as! Set } - + func getBasesByPlayer(for player: GKPlayer) -> Set { return entities.filter{$0 is Base && ($0 as! Base).component(ofType: TeamComponent.self)?.player == player } as! Set } - + func getTeamByBase(base: Base) -> Team? { for entity in entities { if entity is Base && entity == base{ @@ -203,24 +215,24 @@ class EntityManager { func getTeamByPlayer(playerName: String) -> Team { return entities.filter { $0 is Base && ($0 as! Base).component(ofType: TeamComponent.self)?.player.displayName == playerName }[0].component(ofType: TeamComponent.self)!.team } - - func getBasebyID(id: Int) -> Base?{ - for entity in entities { - if entity is Base && (entity as! Base).baseID == id { - return (entity as! Base) - } - } - return nil - } - - func getBackground() -> GKEntity? { + + func getBasebyID(id: Int) -> Base?{ + for entity in entities { + if entity is Base && (entity as! Base).baseID == id { + return (entity as! Base) + } + } + return nil + } + + func getBackground() -> GKEntity? { return entities.filter{$0 is Background}[0] } - + func getBaseNodeByTeam(for team: Team) -> SKSpriteNode? { return getBaseByTeam(for: team)?.component(ofType: DefaultBaseComponent.self)?.spriteNode } - + func getButtonByName(buttonName:String) -> Button { return entities.filter{$0 is Button && ($0 as! Button).name == buttonName }[0] as! Button } diff --git a/GoldWars/GoldWars/RoundCalculatorService.swift b/GoldWars/GoldWars/RoundCalculatorService.swift index b8fde43..72e31a2 100644 --- a/GoldWars/GoldWars/RoundCalculatorService.swift +++ b/GoldWars/GoldWars/RoundCalculatorService.swift @@ -30,7 +30,6 @@ class RoundCalculatorServie { } addPlayerMove(playerName: GKLocalPlayer.local.displayName, playerMoves: DataService.sharedInstance.localPlayerMoves) - print("allPlayerMoves -> \(allPlayerMoves)") for entry in allPlayerMoves { for move in entry.value { mapPlayerMoveToAttackedBase(playerName: entry.key, playerMove: move) @@ -38,16 +37,17 @@ class RoundCalculatorServie { } // TODO-END: + + // TODO: Refactor -> O(n*3n^2) to maybe O(n*3n) + // We might not need to map and iterate over toBase for (key, value) in baseSpecificMoves { let baseId = key var playerMovesByBase = value - let targetBase = currentSnapshotModel?.baseEntites.filter { $0.baseId == baseId }[0] let possiblyOwnershipMoves = playerMovesByBase.filter { $0.key == targetBase?.ownership} - // spieler verschiebt einheiten beim schieben for (playerName, playerMove) in possiblyOwnershipMoves { - for var base in currentSnapshotModel!.baseEntites { + for base in currentSnapshotModel!.baseEntites { if base.baseId == playerMove.fromBase { base.unitCount -= playerMove.unitCount } @@ -59,14 +59,13 @@ class RoundCalculatorServie { } for (_, playerMove) in playerMovesByBase { - for var base in currentSnapshotModel!.baseEntites { + for base in currentSnapshotModel!.baseEntites { if base.baseId == playerMove.fromBase { base.unitCount -= playerMove.unitCount } } } - let sorted = playerMovesByBase.sorted { (e1: (key: String, value: PlayerMove), e2: (key: String, value: PlayerMove)) -> Bool in e1.value.unitCount > e2.value.unitCount } @@ -75,10 +74,9 @@ class RoundCalculatorServie { if sorted.count == 2 { let secMax = sorted[1] max.value.unitCount -= secMax.value.unitCount - } - for var base in currentSnapshotModel!.baseEntites { + for base in currentSnapshotModel!.baseEntites { if base.baseId == max.value.toBase { base.unitCount += max.value.unitCount if max.value.unitCount == 0 { @@ -89,11 +87,8 @@ class RoundCalculatorServie { } } - baseSpecificMoves.removeValue(forKey: baseId) } - - print(currentSnapshotModel) MultiplayerNetwork.sharedInstance.sendSnapshotModelToPlayers() EntityManager.sharedInstance.updateSnapshotModel(snapshotModel: currentSnapshotModel!) let calcTime = CFAbsoluteTimeGetCurrent() - startTime diff --git a/GoldWars/GoldWars/Scenes/GameScene.swift b/GoldWars/GoldWars/Scenes/GameScene.swift index a6934bd..913d41a 100644 --- a/GoldWars/GoldWars/Scenes/GameScene.swift +++ b/GoldWars/GoldWars/Scenes/GameScene.swift @@ -25,7 +25,7 @@ class GameScene: SKScene{ func initMap() { MapFactory(scene: self, entityManager: EntityManager.sharedInstance).loadMap(playerCount: 2) - DataService.sharedInstance.safeSnapshot(snapshotModel: EntityManager.sharedInstance.getSnapshotModel()) + DataService.sharedInstance.setSnapshotModel(snapshotModel: EntityManager.sharedInstance.getSnapshotModel()) } override func touchesEnded(_ touches: Set, with event: UIEvent?) { From de5929d0702386194103ed01f0fc890176c8fcc8 Mon Sep 17 00:00:00 2001 From: Aldin Duraki Date: Tue, 19 May 2020 15:53:07 +0200 Subject: [PATCH 24/28] * Fix trying to add fire sprite node to existing component --- GoldWars/GoldWars/Entities/EntityManager.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GoldWars/GoldWars/Entities/EntityManager.swift b/GoldWars/GoldWars/Entities/EntityManager.swift index 82b37d9..e17a264 100644 --- a/GoldWars/GoldWars/Entities/EntityManager.swift +++ b/GoldWars/GoldWars/Entities/EntityManager.swift @@ -119,9 +119,9 @@ class EntityManager { position: (base.component(ofType: DefaultBaseComponent.self)?.spriteNode.position)! ) ) + scene.addChild(base.component(ofType: TeamComponent.self)!.fire) } base.changeOwnership = false - scene.addChild(base.component(ofType: TeamComponent.self)!.fire) } } } From 1571a1e786ade64da1b3c2575eaad86a2f0d4a91 Mon Sep 17 00:00:00 2001 From: Aldin Duraki Date: Wed, 20 May 2020 00:11:49 +0200 Subject: [PATCH 25/28] * Impl. combined forces attack * Minor refactoring * Fixed component updates on updating entities from snapshot * Fixed mapping for incoming player moves --- .../GoldWars/Components/TimerComponent.swift | 4 +- .../GoldWars/Entities/EntityManager.swift | 49 ++++---- GoldWars/GoldWars/MatchmakingHelper.swift | 1 - GoldWars/GoldWars/MultiplayerNetwork.swift | 12 +- .../GoldWars/RoundCalculatorService.swift | 107 +++++++++--------- GoldWars/GoldWars/SoundManager.swift | 2 +- 6 files changed, 83 insertions(+), 92 deletions(-) diff --git a/GoldWars/GoldWars/Components/TimerComponent.swift b/GoldWars/GoldWars/Components/TimerComponent.swift index 596fd7b..0ed4e63 100644 --- a/GoldWars/GoldWars/Components/TimerComponent.swift +++ b/GoldWars/GoldWars/Components/TimerComponent.swift @@ -48,10 +48,10 @@ class TimerComponent: GKComponent { if !MultiplayerNetwork.sharedInstance.isSending { MultiplayerNetwork.sharedInstance.sendPlayerMoves(playerMoves: DataService.sharedInstance.localPlayerMoves) } - if !RoundCalculatorServie.sharedInstance.isCalculating + if !RoundCalculatorService.sharedInstance.isCalculating && DataService.sharedInstance.didReceiveAllData() && MatchmakingHelper.sharedInstance.isServer { - RoundCalculatorServie.sharedInstance.calculateRound() + RoundCalculatorService.sharedInstance.calculateRound() } } } diff --git a/GoldWars/GoldWars/Entities/EntityManager.swift b/GoldWars/GoldWars/Entities/EntityManager.swift index e17a264..7a49701 100644 --- a/GoldWars/GoldWars/Entities/EntityManager.swift +++ b/GoldWars/GoldWars/Entities/EntityManager.swift @@ -109,17 +109,17 @@ class EntityManager { let base = (entity as! Base) if base.changeOwnership { - if let component = entity.component(ofType: TeamComponent.self) { - component.player = entities[0].component(ofType: TeamComponent.self)!.player - component.team = entities[0].component(ofType: TeamComponent.self)!.team - } else { - base.addComponent(TeamComponent( - team: (entities[0] as! Base).component(ofType: TeamComponent.self)!.team, - player: (entities[0] as! Base).component(ofType: TeamComponent.self)!.player, - position: (base.component(ofType: DefaultBaseComponent.self)?.spriteNode.position)! - ) + //FIX-ME: Find a way to update the Component without deleting it upfront + //TODO: outsource component handling to a generic function + base.removeComponent(ofType: TeamComponent.self) + base.addComponent(TeamComponent( + team: (entities[0] as! Base).component(ofType: TeamComponent.self)!.team, + player: (entities[0] as! Base).component(ofType: TeamComponent.self)!.player, + position: (base.component(ofType: DefaultBaseComponent.self)?.spriteNode.position)! ) - scene.addChild(base.component(ofType: TeamComponent.self)!.fire) + ) + if let fire = entity.component(ofType: TeamComponent.self)?.fire{ + scene.addChild(fire) } base.changeOwnership = false } @@ -131,35 +131,28 @@ class EntityManager { for entity in bases{ let base = entity as! Base let snapBase = self.getSnapshotBaseById(baseId: base.baseID, snapshotModel: snapshotModel) - print("in updateSnap -> Entity \(base)") - print("in updateSnap -> snapBase \(snapBase)") var getOwnerBySnapBase: GKPlayer? = nil base.unitCount = snapBase.unitCount - + if snapBase.ownership != nil { getOwnerBySnapBase = MatchmakingHelper.sharedInstance.getGKPlayerByUsername(displayName: snapBase.ownership!) } if getOwnerBySnapBase != nil { base.changeOwnership = true base.ownershipPlayer = getOwnerBySnapBase - if let component = entity.component(ofType: TeamComponent.self) { - component.player = getOwnerBySnapBase! - component.team = getTeamByPlayer(playerName: snapBase.ownership!) - } else { - entity.addComponent(TeamComponent( - team: getTeamByPlayer(playerName: snapBase.ownership!), - player: getOwnerBySnapBase!, - position: (entity.component(ofType: DefaultBaseComponent.self)?.spriteNode.position)! - ) + //FIX-ME: Find a way to update the Component without deleting it upfront + //TODO: outsource component handling to a generic function + entity.removeComponent(ofType: TeamComponent.self) + entity.addComponent(TeamComponent( + team: getTeamByPlayer(playerName: snapBase.ownership!), + player: getOwnerBySnapBase!, + position: (entity.component(ofType: DefaultBaseComponent.self)?.spriteNode.position)! ) - if let fire = entity.component(ofType: TeamComponent.self)?.fire{ - scene.addChild(fire) - } + ) + if let fire = entity.component(ofType: TeamComponent.self)?.fire{ + scene.addChild(fire) } - } - - print("nach updateSnap -> Entity \(base)") } } diff --git a/GoldWars/GoldWars/MatchmakingHelper.swift b/GoldWars/GoldWars/MatchmakingHelper.swift index dbdc066..a695d39 100644 --- a/GoldWars/GoldWars/MatchmakingHelper.swift +++ b/GoldWars/GoldWars/MatchmakingHelper.swift @@ -118,7 +118,6 @@ class MatchmakingHelper: NSObject, GKMatchmakerViewControllerDelegate, GKMatchDe } if let snapshotModel = try? jsonDecoder.decode(SnapshotModel.self, from: data) { - print("received data package -> \(snapshotModel)") DataService.sharedInstance.snapshotModel = snapshotModel EntityManager.sharedInstance.updateSnapshotModel(snapshotModel: snapshotModel) } diff --git a/GoldWars/GoldWars/MultiplayerNetwork.swift b/GoldWars/GoldWars/MultiplayerNetwork.swift index 8b470bd..32926d2 100644 --- a/GoldWars/GoldWars/MultiplayerNetwork.swift +++ b/GoldWars/GoldWars/MultiplayerNetwork.swift @@ -12,6 +12,7 @@ import GameKit class MultiplayerNetwork{ static let sharedInstance = MultiplayerNetwork() + var isSending = false func sendData(data: Data) { @@ -20,25 +21,20 @@ class MultiplayerNetwork{ do { try multiplayerMatch.sendData(toAllPlayers: data, with: .reliable) } catch { - print("Tim war am Werk") + //TODO: Add logging } } } func sendDataToHost(data: Data) { let mmHelper = MatchmakingHelper.sharedInstance - for player in mmHelper.mpMatch!.players { - print(player.displayName) - } - print(DataService.sharedInstance.gameHost!.playerName) - let hostGKPlayer = MatchmakingHelper.sharedInstance.mpMatch?.players.filter{ $0.displayName == DataService.sharedInstance.gameHost!.playerName}[0] if let multiplayerMatch = mmHelper.mpMatch{ do { try multiplayerMatch.send(data, to: [hostGKPlayer!], dataMode: .reliable) } catch { - print("Tim war mal wieder am Werk der Krasse") + //TODO: Add logging } } } @@ -59,10 +55,8 @@ class MultiplayerNetwork{ } func sendSnapshotModelToPlayers() { - print("sending snapshot -> \(DataService.sharedInstance.snapshotModel)") let encoder = JSONEncoder() let encoded = (try? encoder.encode(DataService.sharedInstance.snapshotModel))! - print("sending package -> \(encoded)") sendData(data: encoded) } diff --git a/GoldWars/GoldWars/RoundCalculatorService.swift b/GoldWars/GoldWars/RoundCalculatorService.swift index 72e31a2..4b92575 100644 --- a/GoldWars/GoldWars/RoundCalculatorService.swift +++ b/GoldWars/GoldWars/RoundCalculatorService.swift @@ -6,93 +6,97 @@ // Copyright © 2020 SP2. All rights reserved. // -import Foundation import GameKit import os -class RoundCalculatorServie { - static let sharedInstance = RoundCalculatorServie() - var isCalculating = false +class RoundCalculatorService { + static let sharedInstance = RoundCalculatorService() + static let LOG = OSLog.init(subsystem: "Round Calculator", category: "RoundCalculatorService") var allPlayerMoves: [String: [PlayerMove]] = [:] - var baseSpecificMoves: [Int: [String: PlayerMove]] = [:] + var baseSpecificMoves: [Int: [String: [PlayerMove]]] = [:] + + var isCalculating = false func calculateRound() { - os_log("Started calculating Round", log: OSLog.default, type: .info) - let startTime = CFAbsoluteTimeGetCurrent() + os_log("Started calculating Round", log: RoundCalculatorService.LOG, type: .info) isCalculating = true + let currentSnapshotModel = DataService.sharedInstance.snapshotModel - var currentSnapshotModel = DataService.sharedInstance.snapshotModel - - // TODO: smarter way? - for entry in DataService.sharedInstance.remotePlayerMoves { - addPlayerMove(playerName: entry.key, playerMoves: entry.value) + for playerMove in DataService.sharedInstance.remotePlayerMoves { + addPlayerMove(playerName: playerMove.key, playerMoves: playerMove.value) } addPlayerMove(playerName: GKLocalPlayer.local.displayName, playerMoves: DataService.sharedInstance.localPlayerMoves) - for entry in allPlayerMoves { - for move in entry.value { - mapPlayerMoveToAttackedBase(playerName: entry.key, playerMove: move) + for playerMove in allPlayerMoves { + for move in playerMove.value { + mapPlayerMoveToAttackedBase(playerName: playerMove.key, playerMove: move) } } - // TODO-END: - - // TODO: Refactor -> O(n*3n^2) to maybe O(n*3n) - // We might not need to map and iterate over toBase + // TODO: Refactor to a less complex way for (key, value) in baseSpecificMoves { let baseId = key var playerMovesByBase = value let targetBase = currentSnapshotModel?.baseEntites.filter { $0.baseId == baseId }[0] let possiblyOwnershipMoves = playerMovesByBase.filter { $0.key == targetBase?.ownership} - - for (playerName, playerMove) in possiblyOwnershipMoves { - for base in currentSnapshotModel!.baseEntites { - if base.baseId == playerMove.fromBase { - base.unitCount -= playerMove.unitCount - } - if base.baseId == playerMove.toBase { - base.unitCount += playerMove.unitCount + + for (playerName, playerMoves) in possiblyOwnershipMoves { + for playerMove in playerMoves { + for base in currentSnapshotModel!.baseEntites { + if base.baseId == playerMove.fromBase { + base.unitCount -= playerMove.unitCount + } + if base.baseId == playerMove.toBase { + base.unitCount += playerMove.unitCount + } } } playerMovesByBase.removeValue(forKey: playerName) } - for (_, playerMove) in playerMovesByBase { - for base in currentSnapshotModel!.baseEntites { - if base.baseId == playerMove.fromBase { - base.unitCount -= playerMove.unitCount + for (_, playerMoves) in playerMovesByBase { + for playerMove in playerMoves { + for base in currentSnapshotModel!.baseEntites { + if base.baseId == playerMove.fromBase { + base.unitCount -= playerMove.unitCount + } } } } - let sorted = playerMovesByBase.sorted { (e1: (key: String, value: PlayerMove), e2: (key: String, value: PlayerMove)) -> Bool in - e1.value.unitCount > e2.value.unitCount + var combinePotentionalForces: [String: PlayerMove] = [:] + + for playerMoves in playerMovesByBase { + combinePotentionalForces[playerMoves.key] = PlayerMove(fromBase: playerMoves.value[0].fromBase, toBase: playerMoves.value[0].toBase, unitCount: 0) + for move in playerMoves.value { + combinePotentionalForces[playerMoves.key]!.unitCount += move.unitCount + } } - var max = sorted[0] - if sorted.count == 2 { - let secMax = sorted[1] - max.value.unitCount -= secMax.value.unitCount + let sortedPotentionalCombinedForces = combinePotentionalForces.sorted { $0.1.unitCount > $1.1.unitCount } + + var playerMoveWithMaxUnits = sortedPotentionalCombinedForces[0] + if playerMovesByBase.count >= 2 { + let playerMoveWithSecMaxUnits = sortedPotentionalCombinedForces[1] + playerMoveWithMaxUnits.value.unitCount -= playerMoveWithSecMaxUnits.value.unitCount } for base in currentSnapshotModel!.baseEntites { - if base.baseId == max.value.toBase { - base.unitCount += max.value.unitCount - if max.value.unitCount == 0 { + if base.baseId == playerMoveWithMaxUnits.value.toBase { + base.unitCount += playerMoveWithMaxUnits.value.unitCount + if playerMoveWithMaxUnits.value.unitCount == 0 { base.ownership = nil } else { - base.ownership = max.key + base.ownership = playerMoveWithMaxUnits.key } - - } - } + } + } baseSpecificMoves.removeValue(forKey: baseId) } MultiplayerNetwork.sharedInstance.sendSnapshotModelToPlayers() EntityManager.sharedInstance.updateSnapshotModel(snapshotModel: currentSnapshotModel!) - let calcTime = CFAbsoluteTimeGetCurrent() - startTime - os_log("Finished calculating Round in %@", log: OSLog.default, type: .info) + os_log("Finished calculating Round", log: RoundCalculatorService.LOG, type: .info) } func addPlayerMove(playerName: String, playerMoves: [PlayerMove]) { @@ -101,17 +105,18 @@ class RoundCalculatorServie { func mapPlayerMoveToAttackedBase(playerName: String, playerMove: PlayerMove) { if self.baseSpecificMoves.keys.contains(playerMove.toBase) { - var playerMovesForSameBase = self.baseSpecificMoves[playerMove.toBase]! - if playerMovesForSameBase.keys.contains(playerName) { - playerMovesForSameBase[playerName] = playerMove + if (self.baseSpecificMoves[playerMove.toBase]?.keys.contains(playerName))!{ + self.baseSpecificMoves[playerMove.toBase]?[playerName]?.append(playerMove) + } else { + self.baseSpecificMoves[playerMove.toBase]?.merge([playerName: [playerMove]]){(current, _) in current} } } else { - self.baseSpecificMoves[playerMove.toBase] = [playerName: playerMove] + self.baseSpecificMoves[playerMove.toBase] = [playerName: [playerMove]] } } func resolvePlayerMove(playerMove: PlayerMove, unitCount: Int, ownership: String?, resolveType: String) { - //outsource playermoves || tnx, remove, add(with calc) + //TODO: outsource playermoves } } diff --git a/GoldWars/GoldWars/SoundManager.swift b/GoldWars/GoldWars/SoundManager.swift index 4f8f34d..b6cb5d4 100644 --- a/GoldWars/GoldWars/SoundManager.swift +++ b/GoldWars/GoldWars/SoundManager.swift @@ -23,7 +23,7 @@ class SoundManager { do { audioPlayer = try AVAudioPlayer(contentsOf: backgroundMainMenuAudio!) } catch { - print("Datei nicht gefunden!") + //TODO: Add logging } audioPlayer.numberOfLoops = -1 audioPlayer.prepareToPlay() From 4bb5b9ee484dbaebcae4bcf668ad043ddd8b536a Mon Sep 17 00:00:00 2001 From: Aldin Duraki Date: Wed, 20 May 2020 00:31:31 +0200 Subject: [PATCH 26/28] * Undo removing Teamcomponent upfront since it causes errors when trying to find a team on initial owned base --- GoldWars/GoldWars/Entities/EntityManager.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/GoldWars/GoldWars/Entities/EntityManager.swift b/GoldWars/GoldWars/Entities/EntityManager.swift index 7a49701..48aef0d 100644 --- a/GoldWars/GoldWars/Entities/EntityManager.swift +++ b/GoldWars/GoldWars/Entities/EntityManager.swift @@ -111,7 +111,7 @@ class EntityManager { if base.changeOwnership { //FIX-ME: Find a way to update the Component without deleting it upfront //TODO: outsource component handling to a generic function - base.removeComponent(ofType: TeamComponent.self) + //base.removeComponent(ofType: TeamComponent.self) base.addComponent(TeamComponent( team: (entities[0] as! Base).component(ofType: TeamComponent.self)!.team, player: (entities[0] as! Base).component(ofType: TeamComponent.self)!.player, @@ -142,7 +142,7 @@ class EntityManager { base.ownershipPlayer = getOwnerBySnapBase //FIX-ME: Find a way to update the Component without deleting it upfront //TODO: outsource component handling to a generic function - entity.removeComponent(ofType: TeamComponent.self) + //entity.removeComponent(ofType: TeamComponent.self) entity.addComponent(TeamComponent( team: getTeamByPlayer(playerName: snapBase.ownership!), player: getOwnerBySnapBase!, From f60e97a8667b111fadb44a246f4c7696fef85ccc Mon Sep 17 00:00:00 2001 From: Aldin Duraki Date: Wed, 20 May 2020 00:35:46 +0200 Subject: [PATCH 27/28] Solve missing lines on previous merge --- GoldWars/GoldWars/Entities/Modal.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GoldWars/GoldWars/Entities/Modal.swift b/GoldWars/GoldWars/Entities/Modal.swift index aadd374..c01999e 100644 --- a/GoldWars/GoldWars/Entities/Modal.swift +++ b/GoldWars/GoldWars/Entities/Modal.swift @@ -57,7 +57,7 @@ class Modal: GKEntity{ func sendUnits(currentDraggedBase: Base?, touchLocation: CGPoint, gameScene: GameScene, collisionBase: Base?){ for base in currentDraggedBase!.adjacencyList { if base == collisionBase { - EntityManager.sharedInstance.update((currentDraggedBase?.attackBase(base: base, units: Int(GameScene.sendUnits)))!) + EntityManager.sharedInstance.update((currentDraggedBase?.doPlayerMoveTypeToBase(base: base, playerMoveType: PlayerMoveType.AtkMove, units: Int(GameScene.sendUnits)))!) } } } From 2ac82e5159d249eee3494d7e8077b42a0060294f Mon Sep 17 00:00:00 2001 From: Aldin Duraki Date: Wed, 20 May 2020 01:41:48 +0200 Subject: [PATCH 28/28] * Minor fixes * Open up calculator service --- GoldWars/GoldWars.xcodeproj/project.pbxproj | 4 --- .../GoldWars/Components/TimerComponent.swift | 1 + GoldWars/GoldWars/MultiplayerNetwork.swift | 1 + .../GoldWars/RoundCalculatorService.swift | 34 ++++++++++--------- 4 files changed, 20 insertions(+), 20 deletions(-) diff --git a/GoldWars/GoldWars.xcodeproj/project.pbxproj b/GoldWars/GoldWars.xcodeproj/project.pbxproj index bc36494..58ae06f 100644 --- a/GoldWars/GoldWars.xcodeproj/project.pbxproj +++ b/GoldWars/GoldWars.xcodeproj/project.pbxproj @@ -21,7 +21,6 @@ 3EBD242C245D8044003CECE7 /* GameCenterHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3EBD242B245D8044003CECE7 /* GameCenterHelper.swift */; }; 3EBD242E245D9332003CECE7 /* Team.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3EBD242D245D9332003CECE7 /* Team.swift */; }; 3F745DF0246F48FC00CE7375 /* PlayerMoveType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3F745DEF246F48FC00CE7375 /* PlayerMoveType.swift */; }; - 3FE19DB3246C690B004827AB /* RoundSimulatorService.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3FE19DB2246C690B004827AB /* RoundSimulatorService.swift */; }; 3FE19DB5246C7A22004827AB /* RoundCalculatorService.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3FE19DB4246C7A22004827AB /* RoundCalculatorService.swift */; }; 9E04AFAF245E2B73002D5CFC /* AttackActionComponent.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9E04AFAE245E2B73002D5CFC /* AttackActionComponent.swift */; }; 9E11FF79245CD81100EED3BE /* Fire.sks in Resources */ = {isa = PBXBuildFile; fileRef = 9E11FF77245CD81100EED3BE /* Fire.sks */; }; @@ -92,7 +91,6 @@ 3EBD242B245D8044003CECE7 /* GameCenterHelper.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GameCenterHelper.swift; sourceTree = ""; }; 3EBD242D245D9332003CECE7 /* Team.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Team.swift; sourceTree = ""; }; 3F745DEF246F48FC00CE7375 /* PlayerMoveType.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlayerMoveType.swift; sourceTree = ""; }; - 3FE19DB2246C690B004827AB /* RoundSimulatorService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RoundSimulatorService.swift; sourceTree = ""; }; 3FE19DB4246C7A22004827AB /* RoundCalculatorService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RoundCalculatorService.swift; sourceTree = ""; }; 9E04AFAE245E2B73002D5CFC /* AttackActionComponent.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AttackActionComponent.swift; sourceTree = ""; }; 9E11FF77245CD81100EED3BE /* Fire.sks */ = {isa = PBXFileReference; lastKnownFileType = file.sks; path = Fire.sks; sourceTree = ""; }; @@ -283,7 +281,6 @@ children = ( 110360DC244B101A008610AF /* Main.storyboard */, 110360E1244B101B008610AF /* LaunchScreen.storyboard */, - 3FE19DB2246C690B004827AB /* RoundSimulatorService.swift */, ); path = Storyboards; sourceTree = ""; @@ -421,7 +418,6 @@ 9E04AFAF245E2B73002D5CFC /* AttackActionComponent.swift in Sources */, 110360D9244B101A008610AF /* GameScene.swift in Sources */, C04783F024685995004961FB /* SettingsScene.swift in Sources */, - 3FE19DB3246C690B004827AB /* RoundSimulatorService.swift in Sources */, 116060F7245C57D2004E5A36 /* EntityManager.swift in Sources */, C064E9AA246C114C0022B228 /* LabelComponent.swift in Sources */, 3EBD242E245D9332003CECE7 /* Team.swift in Sources */, diff --git a/GoldWars/GoldWars/Components/TimerComponent.swift b/GoldWars/GoldWars/Components/TimerComponent.swift index 0ed4e63..52c51b6 100644 --- a/GoldWars/GoldWars/Components/TimerComponent.swift +++ b/GoldWars/GoldWars/Components/TimerComponent.swift @@ -26,6 +26,7 @@ class TimerComponent: GKComponent { func startWithDuration(duration: TimeInterval){ endTime = Date().addingTimeInterval(duration) + RoundCalculatorService.sharedInstance.isCalculating = false } func timeLeft() -> Int { diff --git a/GoldWars/GoldWars/MultiplayerNetwork.swift b/GoldWars/GoldWars/MultiplayerNetwork.swift index 32926d2..7ffbc37 100644 --- a/GoldWars/GoldWars/MultiplayerNetwork.swift +++ b/GoldWars/GoldWars/MultiplayerNetwork.swift @@ -46,6 +46,7 @@ class MultiplayerNetwork{ let encoded = (try? encoder.encode(playerMoves))! sendDataToHost(data: encoded) } + DataService.sharedInstance.localPlayerMoves.removeAll() } func sendHostIdentifier() { diff --git a/GoldWars/GoldWars/RoundCalculatorService.swift b/GoldWars/GoldWars/RoundCalculatorService.swift index 4b92575..3704ec8 100644 --- a/GoldWars/GoldWars/RoundCalculatorService.swift +++ b/GoldWars/GoldWars/RoundCalculatorService.swift @@ -73,27 +73,29 @@ class RoundCalculatorService { combinePotentionalForces[playerMoves.key]!.unitCount += move.unitCount } } - - let sortedPotentionalCombinedForces = combinePotentionalForces.sorted { $0.1.unitCount > $1.1.unitCount } - - var playerMoveWithMaxUnits = sortedPotentionalCombinedForces[0] - if playerMovesByBase.count >= 2 { - let playerMoveWithSecMaxUnits = sortedPotentionalCombinedForces[1] - playerMoveWithMaxUnits.value.unitCount -= playerMoveWithSecMaxUnits.value.unitCount - } - - for base in currentSnapshotModel!.baseEntites { - if base.baseId == playerMoveWithMaxUnits.value.toBase { - base.unitCount += playerMoveWithMaxUnits.value.unitCount - if playerMoveWithMaxUnits.value.unitCount == 0 { - base.ownership = nil - } else { - base.ownership = playerMoveWithMaxUnits.key + if(combinePotentionalForces.count > 0) { + let sortedPotentionalCombinedForces = combinePotentionalForces.sorted { $0.1.unitCount > $1.1.unitCount } + + var playerMoveWithMaxUnits = sortedPotentionalCombinedForces[0] + if playerMovesByBase.count >= 2 { + let playerMoveWithSecMaxUnits = sortedPotentionalCombinedForces[1] + playerMoveWithMaxUnits.value.unitCount -= playerMoveWithSecMaxUnits.value.unitCount + } + + for base in currentSnapshotModel!.baseEntites { + if base.baseId == playerMoveWithMaxUnits.value.toBase { + base.unitCount += playerMoveWithMaxUnits.value.unitCount + if playerMoveWithMaxUnits.value.unitCount == 0 { + base.ownership = nil + } else { + base.ownership = playerMoveWithMaxUnits.key + } } } } baseSpecificMoves.removeValue(forKey: baseId) } + allPlayerMoves.removeAll() MultiplayerNetwork.sharedInstance.sendSnapshotModelToPlayers() EntityManager.sharedInstance.updateSnapshotModel(snapshotModel: currentSnapshotModel!) os_log("Finished calculating Round", log: RoundCalculatorService.LOG, type: .info)