Skip to content

Commit

Permalink
Add player status direct live
Browse files Browse the repository at this point in the history
  • Loading branch information
zelytra committed Mar 2, 2024
1 parent e7399a8 commit d6a29aa
Show file tree
Hide file tree
Showing 10 changed files with 335 additions and 158 deletions.
37 changes: 28 additions & 9 deletions backend/src/main/java/fr/zelytra/session/SessionManager.java
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
package fr.zelytra.session;

import com.fasterxml.jackson.databind.ObjectMapper;
import fr.zelytra.session.fleet.Fleet;
import fr.zelytra.session.fleet.Player;
import io.quarkus.logging.Log;
import jakarta.annotation.Nullable;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.io.IOException;
import java.util.*;

/**
* Manages sessions for a multiplayer game, allowing players to create, join, and leave sessions.
Expand Down Expand Up @@ -43,7 +43,7 @@ public static SessionManager getInstance() {
* @return UUID of the created session
*/
public String createSession() {
String uuid = UUID.randomUUID().toString().substring(0, 7);
String uuid = UUID.randomUUID().toString().substring(0, 7).toUpperCase();
sessions.put(uuid, new Fleet(uuid));
Log.info("[" + uuid + "] Session created !");
return uuid;
Expand Down Expand Up @@ -110,6 +110,7 @@ public void leaveSession(Player player) {
*/
@Nullable
public Fleet getFleetFromId(String sessionId) {
if (sessionId == null) return null;
return sessions.getOrDefault(sessionId, null);
}

Expand All @@ -123,7 +124,6 @@ public Player getPlayerFromSessionId(String sessionId) {
for (Map.Entry<String, Fleet> sessionEntry : sessions.entrySet()) {
Fleet fleet = sessionEntry.getValue();
for (Player player : fleet.getPlayers()) {
// Assuming the Player class has a method to get the WebSocket Session ID
if (player.getSocket().getId().equals(sessionId)) {
return player;
}
Expand All @@ -135,21 +135,40 @@ public Player getPlayerFromSessionId(String sessionId) {
/**
* Retrieves the Fleet containing a Player by their WebSocket session ID.
*
* @param sessionId The WebSocket session ID of the player.
* @param username The WebSocket session ID of the player.
* @return The Fleet containing the Player with the matching WebSocket session ID, or null if not found.
*/
public Fleet getFleetByPlayerSessionId(String sessionId) {
public Fleet getFleetByPlayerName(String username) {
for (Map.Entry<String, Fleet> sessionEntry : sessions.entrySet()) {
Fleet fleet = sessionEntry.getValue();
for (Player player : fleet.getPlayers()) {
// Assuming the Player class has a method to get the WebSocket Session ID
if (player.getSocket().getId().equals(sessionId)) {
if (player.getUsername().equals(username)) {
return fleet; // Return the Fleet containing the player
}
}
}
return null; // Fleet not found because the player is not in any session
}

/**
* Checks if a specific player is in a specific session by the session ID.
*
* @param player The player to check for in the session.
* @param sessionId The ID of the session to check.
* @return true if the specified player is in the session with the given ID, false otherwise.
*/
public boolean isPlayerInSession(Player player, String sessionId) {
Fleet fleet = sessions.get(sessionId);
if (fleet != null) {
// Iterate through the players in the fleet to check if the specified player is present
for (Player fleetPlayer : fleet.getPlayers()) {
if (fleetPlayer.getUsername().equalsIgnoreCase(player.getUsername())) {
return true; // The specified player is found in the session
}
}
}
return false; // The specified player is not found in the session
}


}
34 changes: 27 additions & 7 deletions backend/src/main/java/fr/zelytra/session/SessionSocket.java
Original file line number Diff line number Diff line change
Expand Up @@ -54,17 +54,34 @@ public void onMessage(String message, Session session, @PathParam("sessionId") S
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS);
Player player = objectMapper.readValue(message, Player.class);

Player player = objectMapper.readValue(message, Player.class);
player.setSocket(session);
Log.info("[" + player.getUsername() + "] Connected !");

SessionManager manager = SessionManager.getInstance();
//TODO Handle states change

//Check if it's an update player request
if (manager.isPlayerInSession(player, player.getSessionId())) {

Fleet fleet = manager.getFleetFromId(player.getSessionId());
assert fleet != null;
Player foundedplayer = fleet.getPlayerFromUsername(player.getUsername());

foundedplayer.setReady(player.isReady());
foundedplayer.setStatus(player.getStatus());

broadcastSessionUpdate(player.getSessionId().toUpperCase());

Log.info("[" + player.getUsername() + "] Data updated for session !");
return;
}

Log.info("[" + player.getUsername() + "] Connected !");
//Create session if no id provided
if (sessionId == null || sessionId.isEmpty()) {
String newSessionId = manager.createSession();
manager.joinSession(newSessionId, player);
player.setMaster(true);
broadcastSessionUpdate(newSessionId);
} else {
manager.joinSession(sessionId, player);
Expand Down Expand Up @@ -92,7 +109,7 @@ public void onClose(Session session) {

@OnError
public void onError(Session session, Throwable throwable) throws IOException {
Log.error("WebSocket error for session " + session.getId() + ": " + throwable.getMessage());
Log.error("WebSocket error for session " + session.getId() + ": " + throwable);

SessionManager manager = SessionManager.getInstance();
Player player = manager.getPlayerFromSessionId(session.getId());
Expand All @@ -104,18 +121,21 @@ public void onError(Session session, Throwable throwable) throws IOException {
}

/**
* @param sessionId Flee session id
* @param sessionId Fleet session id
*/
public static void broadcastSessionUpdate(String sessionId) {
SessionManager manager = SessionManager.getInstance();

if (!manager.isSessionExist(sessionId)) return;
if (!manager.isSessionExist(sessionId)) {
Log.info("[" + sessionId + "] Failed to broadcast, session not found");
return;
}
Fleet fleet = manager.getFleetFromId(sessionId);
assert fleet != null;

// Send to all players the Fleet data
ObjectMapper objectMapper = new ObjectMapper();
String json = null;
String json;
try {
json = objectMapper.writeValueAsString(fleet);
} catch (JsonProcessingException e) {
Expand Down
19 changes: 19 additions & 0 deletions backend/src/main/java/fr/zelytra/session/fleet/Fleet.java
Original file line number Diff line number Diff line change
Expand Up @@ -68,5 +68,24 @@ public SessionStatus getStatus() {
public void setStatus(SessionStatus status) {
this.status = status;
}

/**
* Retrieves a player by their username.
* <p>
* This method iterates through the list of players in the current context (presumably a collection
* of players within a class, such as a game lobby or session) and returns the player whose username
* matches the provided username. If no player with the specified username is found, the method returns
* {@code null}.
*
* @param username The username of the player to retrieve.
* @return The {@link Player} object with the matching username, or {@code null} if no matching player is found.
*/
public Player getPlayerFromUsername(String username){
for (Player player : this.players){
if (player.getUsername().equals(username)) return player;
}
return null;
}

}

15 changes: 15 additions & 0 deletions backend/src/main/java/fr/zelytra/session/fleet/Player.java
Original file line number Diff line number Diff line change
@@ -1,14 +1,21 @@
package fr.zelytra.session.fleet;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.websocket.Session;

public class Player {

private String username;
private PlayerStates status;

@JsonProperty(value="isReady")
private boolean isReady;

@JsonProperty(value="isMaster")
private boolean isMaster;

private String sessionId; // Not always the same as the fleet
@JsonIgnore
private Session socket;

Expand Down Expand Up @@ -58,6 +65,14 @@ public void setMaster(boolean master) {
isMaster = master;
}

public String getSessionId() {
return sessionId;
}

public void setSessionId(String sessionId) {
this.sessionId = sessionId;
}

@Override
public String toString() {
return this.username;
Expand Down
2 changes: 2 additions & 0 deletions frontend/src/assets/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,12 @@
"title": "TODO"
}
},
"id": "Session identifier",
"informations": {
"title": "Informations",
"totalPlayer": "Total Player"
},
"leave": "Leave session",
"player": {
"notReady": "Not ready",
"ready": "Is ready",
Expand Down
2 changes: 2 additions & 0 deletions frontend/src/assets/locales/fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,12 @@
"title": "Insérer votre identifiant de session."
}
},
"id": "Identifiant de la session",
"informations": {
"title": "Informations",
"totalPlayer": "Joueurs Total"
},
"leave": "Quitter la session",
"player": {
"notReady": "Pas prêt",
"ready": "Est prêt",
Expand Down
Loading

0 comments on commit d6a29aa

Please sign in to comment.