100 lines
2.7 KiB
Java
100 lines
2.7 KiB
Java
package uulm.teamname.marvelous.server.LobbyManager;
|
|
|
|
import uulm.teamname.marvelous.server.Lobby.Lobby;
|
|
|
|
import java.net.http.WebSocket;
|
|
import java.util.HashSet;
|
|
|
|
/**
|
|
* A class that handles the connection to the lobby. It contains distinct websockets for player1, player2 and spectators.
|
|
* The class is meant to be used in conjecture with {@link MessageRelay}.
|
|
*/
|
|
public class LobbyConnection {
|
|
private Lobby lobby;
|
|
private WebSocket player1;
|
|
private WebSocket player2;
|
|
private HashSet<WebSocket> spectators;
|
|
|
|
/**
|
|
* Creates a new LobbyConnection from a given lobby
|
|
* @param lobby is the lobby that will be connected to
|
|
*/
|
|
public LobbyConnection(Lobby lobby) {
|
|
this.lobby = lobby;
|
|
this.spectators = new HashSet<>(10);
|
|
}
|
|
|
|
/**
|
|
* @return whether there is a player1
|
|
*/
|
|
public boolean hasPlayer1() {
|
|
return player1 == null;
|
|
}
|
|
|
|
/**
|
|
* @return whether there is a player2
|
|
*/
|
|
public boolean hasPlayer2() {
|
|
return player2 == null;
|
|
}
|
|
|
|
/**
|
|
* Adds a new player into the player1 slot
|
|
* @param player is the websocket to be added
|
|
* @return true if added successfully, and false otherwise
|
|
*/
|
|
public boolean addPlayer1(WebSocket player) {
|
|
if (this.contains(player)) return false;
|
|
if (player1 == null) {
|
|
player1 = player;
|
|
return true;
|
|
} else {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Adds a new player into the player1 slot
|
|
* @param player is the websocket to be added
|
|
* @return true if added successfully, and false otherwise
|
|
*/
|
|
public boolean addPlayer2(WebSocket player) {
|
|
if (this.contains(player)) return false;
|
|
if (player2 == null) {
|
|
player2 = player;
|
|
return true;
|
|
} else {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Adds a new player into either the player1, or if full, player2 slot
|
|
* @param player is the websocket to be added
|
|
* @return true if added successfully, and false otherwise
|
|
*/
|
|
public boolean addPlayer(WebSocket player) {
|
|
if (!addPlayer1(player)) {
|
|
return addPlayer2(player);
|
|
}
|
|
return true;
|
|
}
|
|
|
|
public boolean removePlayer(WebSocket player) {
|
|
if (player1 == player) {
|
|
player1 = null;
|
|
return true;
|
|
} else if (player2 == player) {
|
|
player2 = null;
|
|
return true;
|
|
} else {
|
|
return spectators.remove(player);
|
|
}
|
|
}
|
|
|
|
|
|
public boolean contains(WebSocket webSocket) {
|
|
return player1 == webSocket || player2 == webSocket || spectators.contains(webSocket);
|
|
}
|
|
}
|