Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add start synching #88

Merged
merged 4 commits into from
Apr 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file not shown.
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
<!--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">
<viewController storyboardIdentifier="GameViewController" title="GameViewController" wantsFullScreenLayout="YES" modalPresentationStyle="fullScreen" useStoryboardIdentifierAsRestorationIdentifier="YES" 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"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
Expand Down Expand Up @@ -628,7 +628,7 @@ Match</string>
<action selector="onLeaveButtonPressed:" destination="FnT-Eh-Bya" eventType="touchUpInside" id="xhU-Xf-OGM"/>
</connections>
</button>
<button opaque="NO" contentMode="scaleToFill" fixedFrame="YES" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="system" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="95L-Ms-1Jv">
<button opaque="NO" contentMode="scaleToFill" fixedFrame="YES" enabled="NO" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="system" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="95L-Ms-1Jv">
<rect key="frame" x="851" y="449" width="476" height="127"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<state key="normal" title="Button"/>
Expand Down Expand Up @@ -662,7 +662,7 @@ Match</string>
<navigationItem key="navigationItem" id="RIh-Gm-msf"/>
<connections>
<outlet property="ListStackView" destination="FSQ-sC-jDO" id="21H-Es-ph1"/>
<segue destination="BV1-FR-VrT" kind="show" identifier="segueToGame" id="22u-0c-ugI"/>
<outlet property="startButton" destination="95L-Ms-1Jv" id="1ak-OX-1gU"/>
</connections>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="srP-KJ-HWs" userLabel="First Responder" customClass="UIResponder" sceneMemberID="firstResponder"/>
Expand Down
62 changes: 58 additions & 4 deletions TowerForge/TowerForge/Networking/RoomNetwork/GameRoom.swift
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,10 @@ class GameRoom {
private func postRoomDataToFirebase(completion: ((_ err: Any?, _ result: String?) -> Void)?) {
let roomRef = FirebaseDatabaseReference(.Rooms).child(roomName)
let roomId = UUID().uuidString
roomRef.updateChildValues(["roomId": roomId ]) { err, _ in
self.roomState = .empty
roomRef.updateChildValues(["roomId": roomId,
"roomState": RoomState.empty.rawValue
]) { err, _ in
if err != nil {
completion?(err, nil)
} else {
Expand All @@ -83,9 +86,50 @@ class GameRoom {
let playerRef = roomRef.child(roomName).child("players").childByAutoId()
playerRef.setValue(player.userName)
player.userPlayerId = playerRef.key
self.isRoomFull(roomName) { isFull in
if isFull {
self.updateRoomState(roomState: .waitingForBothConfirmation)
}
}
completion(true) // Successfully joined the room
}

// Logic to start the game when players are ready
func updatePlayerReady(completion: @escaping (RoomState) -> Void) {
print("Updating player start")
if self.roomState == .waitingForFinalConfirmation {
self.updateRoomState(roomState: .gameOnGoing)
completion(.gameOnGoing)
} else if self.roomState == .waitingForBothConfirmation {
self.updateRoomState(roomState: .waitingForFinalConfirmation)
completion(.waitingForFinalConfirmation)
}
}
func deleteRoom() {
if roomState == .gameOnGoing {
roomRef.child(roomName).removeValue { error, _ in
if let error = error {
print("Error deleting room: \(error.localizedDescription)")
} else {
print("Room deleted successfully.")
}
}
}
}

// Updates the current room state in the class and database
private func updateRoomState(roomState: RoomState) {
print("Updating room state from player")
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)")
} else {
self.roomState = roomState
print("Room state updated successfully.")
}
}
}
func leaveRoom(player: GamePlayer, completion: @escaping (Bool) -> Void) {
let roomPlayersRef = roomRef.child(roomName).child("players")

Expand Down Expand Up @@ -155,9 +199,16 @@ class GameRoom {
completion(nil)
return
}
print("Finding the room and making it")
let room = GameRoom(roomName: roomName, roomState: .waitingForPlayers)
room.roomId = snap.childSnapshot(forPath: "roomId").value as? RoomId

guard let roomId = snap.childSnapshot(forPath: "roomId").value as? String,
let roomStateRawValue = snap.childSnapshot(forPath: "roomState").value as? String,
let roomState = RoomState.fromString(roomStateRawValue) else {
completion(nil)
return
}

let room = GameRoom(roomName: roomName, roomState: roomState)
room.roomId = roomId
completion(room)
}
}
Expand All @@ -180,6 +231,9 @@ class GameRoom {
}
}
}
if let roomStateData = snapshotValue["roomState"] as? String {
self?.roomState = RoomState.fromString(roomStateData)
}
self?.gameRoomDelegate?.onRoomChange()
}
}
Expand Down
18 changes: 16 additions & 2 deletions TowerForge/TowerForge/Networking/RoomNetwork/RoomData.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,28 @@

import Foundation

enum RoomState: Codable {
enum RoomState: String, Codable {
case empty
case waitingForPlayers
case waitingForMorePlayers
case waitingForBothConfirmation
case waitingForFinalConfirmation
case disconnected
case gameEnded
case gameOnGoing
}

extension String {
func toRoomState() -> RoomState? {
RoomState(rawValue: self)
}
}

extension RoomState {
static func fromString(_ value: String) -> RoomState? {
value.toRoomState()
}
}

struct RoomData: Codable {
let roomName: String
let roomState: RoomState?
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ class GameRoomViewController: UIViewController {
}

let playerOne = GamePlayer(userName: playerName)
print("Attempting to make a room")
gameRoom = GameRoom(roomName: roomName) { success in
if success {
print("Now joining the room \(success)")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@ class GameWaitingRoomViewController: UIViewController {
var currentPlayer: GamePlayer?
@IBOutlet private var ListStackView: UIStackView!

@IBOutlet private var startButton: UIButton!
deinit {
gameRoom?.deleteRoom()
gameRoom = nil
currentPlayer = nil
print("deinit")
Expand All @@ -21,7 +23,6 @@ class GameWaitingRoomViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
gameRoom?.gameRoomDelegate = self
print("Is there game \(gameRoom)")
updatePlayerList()
}

Expand All @@ -36,7 +37,9 @@ class GameWaitingRoomViewController: UIViewController {
}

@IBAction private func onStartButtonPressed(_ sender: Any) {
self.performSegue(withIdentifier: "segueToGame", sender: self)
gameRoom?.updatePlayerReady { _ in
self.startButton.isHidden = true
}
}

@IBAction private func onLeaveButtonPressed(_ sender: Any) {
Expand All @@ -51,7 +54,6 @@ class GameWaitingRoomViewController: UIViewController {
self.navigationController?.popViewController(animated: true)
}
})
// performSegue(withIdentifier: "segueToGameRoom", sender: self)
}

private func updatePlayerList() {
Expand All @@ -67,6 +69,14 @@ class GameWaitingRoomViewController: UIViewController {
let playerTwoView = createPlayerView(for: playerTwo)
ListStackView.addArrangedSubview(playerTwoView)
}
if gameRoom?.roomState == .gameOnGoing {
guard let gameViewController = self.storyboard?.instantiateViewController(withIdentifier: "GameViewController")
as? GameViewController else {
return
}
self.present(gameViewController, animated: true)
gameRoom?.deleteRoom()
}
}

private func createPlayerView(for player: GamePlayer) -> UIView {
Expand All @@ -83,5 +93,12 @@ class GameWaitingRoomViewController: UIViewController {
func onRoomChange() {
// Update the player list UI when the room changes
updatePlayerList()

// Enable startButton if roomState changes to waitingForBothConfirmation
if gameRoom?.roomState == .waitingForBothConfirmation || gameRoom?.roomState == .waitingForFinalConfirmation {
startButton.isEnabled = true
} else {
startButton.isEnabled = false
}
}
}