Skip to content

Commit

Permalink
Merge pull request #123 from zheng-ze/main
Browse files Browse the repository at this point in the history
Add Gamemode selection to multiplayer
  • Loading branch information
zheng-ze authored Apr 21, 2024
2 parents 96cf306 + 2fc2405 commit 818f856
Show file tree
Hide file tree
Showing 16 changed files with 154 additions and 36 deletions.
2 changes: 1 addition & 1 deletion TowerForge/TowerForge.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -1304,6 +1304,7 @@
BAFFB93B2BB0A5AD00D8301F /* PlayerEvents */ = {
isa = PBXGroup;
children = (
3CD7DE392BCEB87900CB21F0 /* ConcedeEvent.swift */,
3CE951682BAEB719008B2785 /* RequestSpawnEvent.swift */,
523E5C4B2BC53F70007444DA /* WaveSpawnEvent.swift */,
);
Expand All @@ -1321,7 +1322,6 @@
3CCA1EEF2BD2861B009302F8 /* UpdatePostionEvent.swift */,
527A077B2BB3F4CC00CD9D08 /* KillEvent.swift */,
9BC60BC72BB9BE6D001A6737 /* DisabledEvent.swift */,
3CD7DE392BCEB87900CB21F0 /* ConcedeEvent.swift */,
);
path = GameEvents;
sourceTree = "<group>";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,13 @@
<!--GameViewController-->
<scene sceneID="tXr-a1-R10">
<objects>
<viewController storyboardIdentifier="GameViewController" title="GameViewController" wantsFullScreenLayout="YES" modalPresentationStyle="fullScreen" id="BV1-FR-VrT" customClass="GameViewController" customModule="TowerForge" customModuleProvider="target" sceneMemberID="viewController">
<view key="view" multipleTouchEnabled="YES" contentMode="scaleToFill" id="3se-qz-xqx" customClass="SKView">
<rect key="frame" x="0.0" y="0.0" width="1366" height="1024"/>
<viewController storyboardIdentifier="GameViewController" title="GameViewController" wantsFullScreenLayout="YES" modalPresentationStyle="fullScreen" hidesBottomBarWhenPushed="YES" id="BV1-FR-VrT" customClass="GameViewController" customModule="TowerForge" customModuleProvider="target" sceneMemberID="viewController">
<view key="view" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="scaleToFill" id="3se-qz-xqx" customClass="SKView">
<rect key="frame" x="0.0" y="0.0" width="1366" height="954"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="system" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="FRf-Sx-cuP">
<rect key="frame" x="30.5" y="25.5" width="75.5" height="51.5"/>
<rect key="frame" x="33" y="24" width="70.5" height="47.5"/>
<constraints>
<constraint firstAttribute="width" secondItem="FRf-Sx-cuP" secondAttribute="height" multiplier="114:77" id="lB7-gB-moQ"/>
</constraints>
Expand All @@ -45,6 +45,7 @@
<constraint firstItem="FRf-Sx-cuP" firstAttribute="height" secondItem="3se-qz-xqx" secondAttribute="height" multiplier="0.05" id="RZy-b6-PfV"/>
</constraints>
</view>
<extendedEdge key="edgesForExtendedLayout"/>
<navigationItem key="navigationItem" id="9Rh-a0-sTy"/>
<connections>
<outlet property="gamePopupButton" destination="FRf-Sx-cuP" id="9ja-00-9KT"/>
Expand Down Expand Up @@ -1163,6 +1164,38 @@
<constraint firstItem="Co9-Tp-uCr" firstAttribute="leading" secondItem="5Uk-mA-EC2" secondAttribute="leading" id="x30-A1-Q3C"/>
</constraints>
</view>
<view contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="Aoz-og-1yQ" userLabel="Mode View">
<rect key="frame" x="888" y="256" width="409.5" height="102.5"/>
<subviews>
<button opaque="NO" contentMode="scaleToFill" showsMenuAsPrimaryAction="YES" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="system" lineBreakMode="middleTruncation" changesSelectionAsPrimaryAction="YES" translatesAutoresizingMaskIntoConstraints="NO" id="S7R-Bw-5rH" userLabel="Mode Button">
<rect key="frame" x="0.0" y="0.0" width="409.5" height="102.5"/>
<inset key="imageEdgeInsets" minX="0.0" minY="0.0" maxX="2.2250738585072014e-308" maxY="0.0"/>
<state key="normal" backgroundImage="square-button"/>
</button>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="GameMode" textAlignment="center" lineBreakMode="headTruncation" minimumScaleFactor="0.5" translatesAutoresizingMaskIntoConstraints="NO" id="lmN-ut-46y" userLabel="Mode Label">
<rect key="frame" x="82" y="20.5" width="245.5" height="61.5"/>
<constraints>
<constraint firstAttribute="width" secondItem="lmN-ut-46y" secondAttribute="height" multiplier="4:1" id="xqr-Mm-mKQ"/>
</constraints>
<fontDescription key="fontDescription" name="Nosifer-Regular" family="Nosifer" pointSize="25"/>
<color key="textColor" white="1" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
<nil key="highlightedColor"/>
</label>
</subviews>
<color key="backgroundColor" white="0.0" alpha="0.0" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
<constraints>
<constraint firstItem="S7R-Bw-5rH" firstAttribute="leading" secondItem="Aoz-og-1yQ" secondAttribute="leading" id="1Qj-2n-zuL"/>
<constraint firstItem="lmN-ut-46y" firstAttribute="centerY" secondItem="Aoz-og-1yQ" secondAttribute="centerY" id="4uz-WO-CUt"/>
<constraint firstItem="S7R-Bw-5rH" firstAttribute="trailing" secondItem="Aoz-og-1yQ" secondAttribute="trailing" id="71T-Eb-ztC"/>
<constraint firstItem="S7R-Bw-5rH" firstAttribute="bottom" secondItem="Aoz-og-1yQ" secondAttribute="bottom" id="DJB-4e-Wka"/>
<constraint firstItem="lmN-ut-46y" firstAttribute="centerY" secondItem="Aoz-og-1yQ" secondAttribute="centerY" id="DVo-Ye-uLq"/>
<constraint firstItem="lmN-ut-46y" firstAttribute="centerX" secondItem="Aoz-og-1yQ" secondAttribute="centerX" id="Hm0-6u-wXJ"/>
<constraint firstItem="S7R-Bw-5rH" firstAttribute="top" secondItem="Aoz-og-1yQ" secondAttribute="top" id="klp-sR-8l2"/>
<constraint firstItem="lmN-ut-46y" firstAttribute="height" secondItem="S7R-Bw-5rH" secondAttribute="height" multiplier="0.6" id="o3b-hj-yi6"/>
<constraint firstAttribute="width" secondItem="Aoz-og-1yQ" secondAttribute="height" multiplier="4:1" id="pYV-u4-7Vj"/>
<constraint firstItem="lmN-ut-46y" firstAttribute="centerX" secondItem="Aoz-og-1yQ" secondAttribute="centerX" id="wcc-U2-tOh"/>
</constraints>
</view>
<view contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="Gvy-hn-x7x" userLabel="Leave View">
<rect key="frame" x="888" y="665.5" width="409.5" height="102.5"/>
<subviews>
Expand Down Expand Up @@ -1205,16 +1238,23 @@
<constraint firstItem="Gvy-hn-x7x" firstAttribute="centerX" secondItem="CDD-vN-KX1" secondAttribute="centerX" multiplier="1.6" id="5eD-hh-aU2"/>
<constraint firstItem="FSQ-sC-jDO" firstAttribute="height" secondItem="CDD-vN-KX1" secondAttribute="height" multiplier="0.7" id="9CQ-fQ-MCK"/>
<constraint firstItem="5Uk-mA-EC2" firstAttribute="centerY" secondItem="CDD-vN-KX1" secondAttribute="centerY" id="Avk-yS-EL7"/>
<constraint firstItem="Aoz-og-1yQ" firstAttribute="width" secondItem="Aoz-og-1yQ" secondAttribute="height" multiplier="4:1" id="CcO-iK-n2z"/>
<constraint firstItem="Aoz-og-1yQ" firstAttribute="centerY" secondItem="CDD-vN-KX1" secondAttribute="centerY" multiplier="0.6" id="D2f-gj-QqC"/>
<constraint firstItem="Gvy-hn-x7x" firstAttribute="width" secondItem="5Uk-mA-EC2" secondAttribute="width" id="Dpc-j9-B22"/>
<constraint firstItem="5Uk-mA-EC2" firstAttribute="centerX" secondItem="CDD-vN-KX1" secondAttribute="centerX" multiplier="1.6" id="J8j-7j-lPc"/>
<constraint firstItem="Gvy-hn-x7x" firstAttribute="centerY" secondItem="CDD-vN-KX1" secondAttribute="centerY" multiplier="1.4" id="Qov-Q2-veN"/>
<constraint firstItem="Aoz-og-1yQ" firstAttribute="height" secondItem="5Uk-mA-EC2" secondAttribute="height" id="V6V-Lt-Sog"/>
<constraint firstItem="Gvy-hn-x7x" firstAttribute="height" secondItem="5Uk-mA-EC2" secondAttribute="height" id="aFU-z0-ILN"/>
<constraint firstItem="Aoz-og-1yQ" firstAttribute="centerX" secondItem="CDD-vN-KX1" secondAttribute="centerX" multiplier="1.6" id="d1X-gL-sY7"/>
<constraint firstItem="Aoz-og-1yQ" firstAttribute="width" secondItem="5Uk-mA-EC2" secondAttribute="width" id="frQ-It-D3U"/>
<constraint firstItem="FSQ-sC-jDO" firstAttribute="centerX" secondItem="CDD-vN-KX1" secondAttribute="centerX" multiplier="0.7" id="qU6-Ob-94D"/>
</constraints>
</view>
<navigationItem key="navigationItem" id="RIh-Gm-msf"/>
<connections>
<outlet property="ListStackView" destination="FSQ-sC-jDO" id="21H-Es-ph1"/>
<outlet property="modeButton" destination="S7R-Bw-5rH" id="27p-av-ThH"/>
<outlet property="modeLabel" destination="lmN-ut-46y" id="dZz-9H-HR9"/>
<outlet property="startButton" destination="Co9-Tp-uCr" id="aH9-mw-OQ5"/>
<segue destination="BV1-FR-VrT" kind="show" identifier="segueToGame" id="22u-0c-ugI"/>
</connections>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ class AuthenticationManager: AuthenticationProtocol {
func getUserData(completion: @escaping (AuthenticationData?, Error?) -> Void) {
if let currentUser = Auth.auth().currentUser {
// User is currently logged in, fetch user data
print(currentUser)
Logger.log(String(describing: currentUser), self)
let userData = AuthenticationData(userId: currentUser.uid,
email: currentUser.email ?? "",
username: currentUser.displayName)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,9 @@ class ArrowTower: BaseTower, PlayerSpawnable {
self.addComponent(ShootingComponent(fireRate: ArrowTower.fireRate,
range: ArrowTower.range,
attackPower: ArrowTower.damage, shootingType: Bullet.self))
self.addComponent(DamageComponent(attackRate: .unit,
attackPower: .unit,
temporary: false))
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@ class SoldierUnit: BaseUnit, PlayerSpawnable {
self.addComponent(ShootingComponent(fireRate: SoldierUnit.attackRate,
range: SoldierUnit.range,
attackPower: SoldierUnit.attackPower, shootingType: Bullet.self))
self.addComponent(DamageComponent(attackRate: .unit,
attackPower: .unit,
temporary: false))
}

required init(position: CGPoint, player: Player, id: UUID) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@ class WizardUnit: BaseUnit, PlayerSpawnable {
self.addComponent(ShootingComponent(fireRate: WizardUnit.attackRate,
range: WizardUnit.range,
attackPower: WizardUnit.attackPower, shootingType: WizardBall.self))
self.addComponent(DamageComponent(attackRate: .unit,
attackPower: .unit,
temporary: false))
}

required init(position: CGPoint, player: Player, id: UUID) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ struct UpdatePostionEvent: TFEvent {
}

func execute(in target: any EventTarget) -> EventOutput {
if let movementSystem = target.system(ofType: MovementSystem.self) {
movementSystem.updatePosition(for: entityId, to: position)
if let positionSystem = target.system(ofType: PositionSystem.self) {
positionSystem.updatePosition(for: entityId, to: position)
}
return EventOutput()
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,20 @@

import Foundation

enum Mode {
enum Mode: String {
case deathMatch
case captureTheFlag
case survivalLevelOne
case survivalLevelTwo
case survivalLevelThree
}

extension Mode {
static func fromString(_ value: String) -> Mode? {
Mode(rawValue: value)
}
}

class GameModeFactory {
static func createGameMode(mode: Mode, eventManager: EventManager) -> GameMode {
switch mode {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,15 +49,6 @@ class MovementSystem: TFSystem {
movementComponent.updatePosition(with: displacement)
}

func updatePosition(for entityId: UUID, to position: CGPoint) {
guard let currentEntity = entityManager.entity(with: entityId),
let positionComponent = currentEntity.component(ofType: PositionComponent.self) else {
return
}

positionComponent.changeTo(to: position)
}

private func processMovableComponent(_ movableComponent: MovableComponent, time: CGFloat) {

guard movableComponent.shouldMove, let entity = movableComponent.entity,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,15 @@ class PositionSystem: TFSystem {
}
}

func updatePosition(for entityId: UUID, to position: CGPoint) {
guard let currentEntity = entityManager.entity(with: entityId),
let positionComponent = currentEntity.component(ofType: PositionComponent.self) else {
return
}

positionComponent.changeTo(to: position)
}

func handleOutOfGame(entity: TFEntity) {
guard let playerComponent = entity.component(ofType: PlayerComponent.self) else {
return
Expand Down
2 changes: 1 addition & 1 deletion TowerForge/TowerForge/GameViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ class GameViewController: UIViewController {
let auth = AuthenticationProvider()
if auth.isUserLoggedIn() {
auth.getUserDetails { data, _ in
print(data)
Logger.log(String(describing: data), self)
self.playerData = data
}
}
Expand Down
37 changes: 27 additions & 10 deletions TowerForge/TowerForge/Networking/RoomNetwork/GameRoom.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ class GameRoom {
private(set) var roomState: RoomState?
private(set) var roomId: RoomId?
private(set) var host: UserPlayerId?
private(set) var gameMode: Mode?

private(set) var playerOne: GamePlayer?
private(set) var playerTwo: GamePlayer?
Expand Down Expand Up @@ -62,7 +63,8 @@ class GameRoom {
let roomId = UUID().uuidString
self.roomState = .empty
roomRef.updateChildValues(["roomId": roomId,
"roomState": RoomState.empty.rawValue
"roomState": RoomState.empty.rawValue,
"gameMode": Mode.captureTheFlag.rawValue
]) { err, _ in
if err != nil {
completion?(err, nil)
Expand All @@ -86,7 +88,7 @@ class GameRoom {

let onAddCompleted = { (error: Error?, _: DatabaseReference) -> Void in
if let error = error {
print("Error getting data: \(error.localizedDescription)")
Logger.log("Error getting data: \(error.localizedDescription)", self)
completion(false)
return
}
Expand All @@ -108,7 +110,7 @@ class GameRoom {

// Logic to start the game when players are ready
func updatePlayerReady(completion: @escaping (RoomState) -> Void) {
print("Updating player start")
Logger.log("Updating player start", self)
if self.roomState == .waitingForFinalConfirmation {
self.updateRoomState(roomState: .gameOnGoing)
completion(.gameOnGoing)
Expand All @@ -118,29 +120,41 @@ class GameRoom {
}
}

func updateGameMode(to mode: Mode) {
let roomStateRef = FirebaseDatabaseReference(.Rooms).child(roomName).child("gameMode")
roomStateRef.setValue(mode.rawValue) { error, _ in
if let error = error {
Logger.log("Error updating game mode: \(error.localizedDescription)", self)
} else {
self.gameMode = mode
Logger.log("Game mode updated successfully.", self)
}
}
}

func deleteRoom() {
guard roomState == .gameOnGoing else {
return
}
roomRef.child(roomName).removeValue { error, _ in
if let error = error {
print("Error deleting room: \(error.localizedDescription)")
Logger.log("Error deleting room: \(error.localizedDescription)", self)
} else {
print("Room deleted successfully.")
Logger.log("Room deleted successfully.", self)
}
}
}

// Updates the current room state in the class and database
private func updateRoomState(roomState: RoomState) {
print("Updating room state from player")
Logger.log("Updating room state from player", self)
let roomStateRef = FirebaseDatabaseReference(.Rooms).child(roomName).child("roomState")
roomStateRef.setValue(roomState.rawValue) { error, _ in
if let error = error {
print("Error updating room state: \(error.localizedDescription)")
Logger.log("Error updating room state: \(error.localizedDescription)", self)
} else {
self.roomState = roomState
print("Room state updated successfully.")
Logger.log("Room state updated successfully.", self)
}
}
}
Expand Down Expand Up @@ -197,7 +211,7 @@ class GameRoom {
let playerRef = FirebaseDatabaseReference(.Rooms).child(roomName).child("players")
playerRef.getData { error, snapshot in
if let error = error {
print("Error getting data: \(error.localizedDescription)")
Logger.log("Error getting data: \(error.localizedDescription)", self)
completion(false)
return
}
Expand Down Expand Up @@ -260,6 +274,9 @@ class GameRoom {
if let hostData = snapshotValue["host"] as? UserPlayerId {
self?.host = hostData
}
if let gameModeData = snapshotValue["gameMode"] as? String {
self?.gameMode = Mode.fromString(gameModeData)
}
self?.gameRoomDelegate?.onRoomChange()
}
}
Expand Down Expand Up @@ -287,7 +304,7 @@ class GameRoom {
private func attemptSetHost(player: GamePlayer) {
let delegate = { (error: Error?, snapshot: DataSnapshot?) -> Void in
if let error = error {
print("Error getting data: \(error.localizedDescription)")
Logger.log("Error getting data: \(error.localizedDescription)", self)
return
}

Expand Down
Loading

0 comments on commit 818f856

Please sign in to comment.