Skip to content

Commit

Permalink
Add start synching
Browse files Browse the repository at this point in the history
  • Loading branch information
Vanessamae23 committed Apr 7, 2024
1 parent 18b8742 commit 344c020
Show file tree
Hide file tree
Showing 5 changed files with 83 additions and 12 deletions.
Binary file not shown.
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="32700.99.1234" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="LaC-gc-01p">
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="22505" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="LaC-gc-01p">
<device id="ipad12_9" orientation="landscape" layout="fullscreen" appearance="light"/>
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="22684"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="22504"/>
<capability name="Named colors" minToolsVersion="9.0"/>
<capability name="Safe area layout guides" minToolsVersion="9.0"/>
<capability name="System colors in document resources" minToolsVersion="11.0"/>
Expand Down Expand Up @@ -366,7 +366,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 @@ -400,6 +400,7 @@ Match</string>
<navigationItem key="navigationItem" id="RIh-Gm-msf"/>
<connections>
<outlet property="ListStackView" destination="FSQ-sC-jDO" id="21H-Es-ph1"/>
<outlet property="startButton" destination="95L-Ms-1Jv" id="Hsc-Qq-ETX"/>
<segue destination="BV1-FR-VrT" kind="show" identifier="segueToGame" id="22u-0c-ugI"/>
</connections>
</viewController>
Expand Down
52 changes: 47 additions & 5 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,39 @@ 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)
}
}

// 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) { 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,10 +188,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
completion(room)

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
}
}

Expand All @@ -180,6 +219,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 @@ -12,6 +12,7 @@ class GameWaitingRoomViewController: UIViewController {
var currentPlayer: GamePlayer?
@IBOutlet private var ListStackView: UIStackView!

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

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

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

@IBAction private func onLeaveButtonPressed(_ sender: Any) {
Expand Down Expand Up @@ -67,6 +71,9 @@ class GameWaitingRoomViewController: UIViewController {
let playerTwoView = createPlayerView(for: playerTwo)
ListStackView.addArrangedSubview(playerTwoView)
}
if gameRoom?.roomState == .gameOnGoing {
self.performSegue(withIdentifier: "segueToGame", sender: self)
}
}

private func createPlayerView(for player: GamePlayer) -> UIView {
Expand All @@ -83,5 +90,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
}
}
}

0 comments on commit 344c020

Please sign in to comment.