Skip to content

Commit

Permalink
Merge pull request #74 from Vanessamae23/room
Browse files Browse the repository at this point in the history
Fix bug and cascade deletion of room
  • Loading branch information
Vanessamae23 authored Apr 4, 2024
2 parents f08e281 + cf1d044 commit b2fe3be
Show file tree
Hide file tree
Showing 6 changed files with 144 additions and 93 deletions.
Binary file not shown.
130 changes: 67 additions & 63 deletions TowerForge/TowerForge/AppMain/Storyboards/Base.lproj/Main.storyboard

Large diffs are not rendered by default.

10 changes: 9 additions & 1 deletion TowerForge/TowerForge/Networking/GamePlayer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,15 @@ class GamePlayer: Codable {
var userPlayerId: UserPlayerId?
let userName: String

init(userName: String) {
init(userPlayerId: UserPlayerId? = nil, userName: String) {
self.userName = userName
self.userPlayerId = userPlayerId
}
}

extension GamePlayer: Equatable {
static func == (lhs: GamePlayer, rhs: GamePlayer) -> Bool {
lhs.userPlayerId == rhs.userPlayerId
}

}
77 changes: 56 additions & 21 deletions TowerForge/TowerForge/Networking/RoomNetwork/GameRoom.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,6 @@ class GameRoom {
private(set) var playerOne: GamePlayer?
private(set) var playerTwo: GamePlayer?

private(set) var firebaseRepository: FirebaseRepository?

let roomRef = FirebaseDatabaseReference(.Rooms)

var isRoomFull: Bool {
Expand All @@ -32,11 +30,9 @@ class GameRoom {
// the player creating the room will auto join the room
init?(roomName: String,
roomState: RoomState? = nil,
repository: FirebaseRepository,
completion: @escaping (Bool) -> Void) {
self.roomName = roomName
self.roomState = roomState
self.firebaseRepository = repository

// Check if the room name is available
isRoomNameAvailable(roomName: roomName) { isAvailable in
Expand All @@ -48,15 +44,17 @@ class GameRoom {
}

self.postRoomDataToFirebase { _, _ in
print("Making room ...")
self.makeRoomListener()
completion(true)
}
}

self.makeRoomListener()
}
init(roomName: String, roomState: RoomState? = nil) {
self.roomName = roomName
self.roomState = roomState
self.makeRoomListener()
}
private func postRoomDataToFirebase(completion: ((_ err: Any?, _ result: String?) -> Void)?) {
let roomRef = FirebaseDatabaseReference(.Rooms).child(roomName)
Expand All @@ -69,29 +67,30 @@ class GameRoom {
}
}
func joinRoom(player: GamePlayer, completion: @escaping (Bool) -> Void) {
if isRoomFull {
completion(false) // Room is full, cannot join
} else {
if playerOne == nil {
playerOne = player
} else {
playerTwo = player
self.isRoomFull(roomName) { isFull in
if isFull {
completion(false)
}
let playerRef = roomRef.child(roomName).child("players").childByAutoId()
playerRef.setValue(player.userName)
player.userPlayerId = playerRef.key
completion(true) // Successfully joined the room
}
if playerOne == nil {
playerOne = player
} else {
playerTwo = player
}
let playerRef = roomRef.child(roomName).child("players").childByAutoId()
playerRef.setValue(player.userName)
player.userPlayerId = playerRef.key
completion(true) // Successfully joined the room

}

func leaveRoom(player: GamePlayer, completion: @escaping (Bool) -> Void) {
let roomPlayersRef = roomRef.child(roomName).child("players")

roomPlayersRef.observeSingleEvent(of: .value) { snapshot in
print(snapshot)
print(snapshot.value)
if let playerData = snapshot.value as? [String: Any] {
// Check if the leaving player is in the room
if let playerKey = playerData.first(where: { $0.key as? String == player.userPlayerId })?.key {
if let playerKey = playerData.first(where: { $0.key == player.userPlayerId })?.key {
// Remove the player from the room in the database
roomPlayersRef.child(playerKey).removeValue()

Expand All @@ -101,6 +100,10 @@ class GameRoom {
} else if self.playerTwo?.userPlayerId == player.userPlayerId {
self.playerTwo = nil
}
if playerData.count == 1 {
// Delete the room from the database
self.roomRef.child(self.roomName).removeValue()
}
completion(true) // Successfully left the room
} else {
// The player is not in the room, cannot leave
Expand All @@ -112,6 +115,23 @@ class GameRoom {
}
}
}
private func isRoomFull(_ roomName: String, completion: @escaping (Bool) -> Void) {
let roomRef = FirebaseDatabaseReference(.Rooms).child(roomName).child("players")
roomRef.getData { error, snapshot in
if let error = error {
print("Error getting data: \(error.localizedDescription)")
completion(false)
return
}

if let snap = snapshot, snap.exists() {
let playerCount = snap.childrenCount
completion(playerCount >= 2)
} else {
completion(false)
}
}
}
static func findRoomWithName(_ roomName: String, completion: @escaping (GameRoom?) -> Void) {
let roomRef = FirebaseDatabaseReference(.Rooms).child(roomName)
roomRef.getData { _, snapshot in
Expand All @@ -126,12 +146,27 @@ class GameRoom {
} else {
completion(nil)
}

}
}
private func makeRoomListener() {
print("Start listening")
roomRef.removeAllObservers()
roomRef.child(roomName).observe(.value) { [weak self] _ in
roomRef.child(roomName).observe(.value) { [weak self] snap in
guard let snapshotValue = snap.value as? [String: Any] else {
return
}
if let playersData = snapshotValue["players"] as? [String: Any] {
for (playerKey, playerData) in playersData {
if let playerData = playerData as? String {
let player = GamePlayer(userPlayerId: playerKey, userName: playerData)
if self?.playerOne == nil {
self?.playerOne = player
} else if self?.playerTwo == nil && self?.playerOne != player {
self?.playerTwo = player
}
}
}
}
self?.gameRoomDelegate?.onRoomChange()
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,9 @@ class GameRoomViewController: UIViewController {
// Show an alert or some indication to the user that inputs are empty
return
}
print("From user : \(roomName) and playername : \(playerName)")

// Create a sample player for testing
let playerOne = GamePlayer(userName: playerName)
gameRoom = GameRoom(roomName: roomName,
repository: firebaseRepository) { success in
gameRoom = GameRoom(roomName: roomName) { success in
if success {
self.joinRoom(player: playerOne)
}
Expand All @@ -45,11 +42,13 @@ class GameRoomViewController: UIViewController {
// Create a game room
gameRoom?.joinRoom(player: player, completion: { success in
if success {
print("Successfully joined the room")
print("Successfully joined the room")
self.currentPlayer = player
DispatchQueue.main.async {
self.performSegue(withIdentifier: "segueToWaitingRoom", sender: self)
}
} else {
print("Failed to join room")
}
})

Expand All @@ -60,6 +59,7 @@ class GameRoomViewController: UIViewController {
guard let currentPlayer = self.currentPlayer else {
return
}
print("Before segueing \(gameRoom)")
destinationVC.currentPlayer = currentPlayer
destinationVC.gameRoom = gameRoom
}
Expand All @@ -74,9 +74,10 @@ class GameRoomViewController: UIViewController {
let player = GamePlayer(userName: playerName)
GameRoom.findRoomWithName(roomName) { room in
if let room = room {
self.gameRoom = room
self.joinRoom(player: player)
} else {

print("Room not found")
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,11 @@ class GameWaitingRoomViewController: UIViewController {
var currentPlayer: GamePlayer?
override func viewDidLoad() {
super.viewDidLoad()
print(gameRoom)
gameRoom?.gameRoomDelegate = self
updatePlayerList()
}
@IBAction func onLeaveButtonPressed(_ sender: Any) {
@IBAction private func onLeaveButtonPressed(_ sender: Any) {
guard let player = currentPlayer else {
return
}
Expand All @@ -33,7 +35,6 @@ class GameWaitingRoomViewController: UIViewController {

@IBOutlet var ListStackView: UIStackView!
private func updatePlayerList() {

ListStackView.arrangedSubviews.forEach { $0.removeFromSuperview() }

// Add player views to the stack view
Expand All @@ -52,6 +53,8 @@ class GameWaitingRoomViewController: UIViewController {
let playerView = UILabel()
playerView.text = player.userName // Display player's username
playerView.textAlignment = .center
playerView.textAlignment = .center
playerView.font = UIFont(name: "Nosifer-Regular", size: 30.0)
return playerView
}
}
Expand Down

0 comments on commit b2fe3be

Please sign in to comment.