Merge branch 'SerainaGui' into 'master'

Debugged the UI now its working

See merge request cs108-fs22/Gruppe-8!6
This commit is contained in:
Seraina Schöb 2022-04-17 15:15:40 +00:00
commit 764c06f26b
11 changed files with 214 additions and 149 deletions

View File

@ -277,3 +277,7 @@ ToDo:
14.04.2022 - Alex 14.04.2022 - Alex
- Erste Version des Spiel-Manuals - Erste Version des Spiel-Manuals
17.04.2022 - Sebastian
- Dank Sereina kommuniziert die GUI nun mit dem Client und Nachrichten kommen korrekt an und werden korrekt verschickt.
Im GUI funktioniert der Whisper nun. Folgendes Colorcoding: Eigene Nachrichten sind Lavendelfarben. Normale Chat nachrichten blau,
und im Momentan Whisper Nachrichten violet.

View File

@ -4,6 +4,7 @@ import ch.unibas.dmi.dbis.cs108.BudaLogConfig;
import ch.unibas.dmi.dbis.cs108.multiplayer.client.gui.ClientModel; import ch.unibas.dmi.dbis.cs108.multiplayer.client.gui.ClientModel;
import ch.unibas.dmi.dbis.cs108.multiplayer.client.gui.GUI; import ch.unibas.dmi.dbis.cs108.multiplayer.client.gui.GUI;
import ch.unibas.dmi.dbis.cs108.multiplayer.client.gui.chat.ChatApp; import ch.unibas.dmi.dbis.cs108.multiplayer.client.gui.chat.ChatApp;
import ch.unibas.dmi.dbis.cs108.multiplayer.client.gui.chat.ChatController;
import ch.unibas.dmi.dbis.cs108.multiplayer.helpers.ClientPinger; import ch.unibas.dmi.dbis.cs108.multiplayer.helpers.ClientPinger;
@ -62,6 +63,7 @@ public class Client {
sendMsgToServer(Protocol.clientLogin + "$" + systemName); sendMsgToServer(Protocol.clientLogin + "$" + systemName);
this.chatApp = new ChatApp(new ClientModel(systemName, this)); this.chatApp = new ChatApp(new ClientModel(systemName, this));
this.chatGUi = new GUI(this.chatApp); this.chatGUi = new GUI(this.chatApp);
chatGUi.setName(systemName);
clientPinger = new ClientPinger(this, this.socket); clientPinger = new ClientPinger(this, this.socket);
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
@ -69,6 +71,10 @@ public class Client {
} }
public void changeUsername (String newName) {
ChatController.getClient().setUsername(newName);
}
/** /**
* Sends a message to the Server in a formatted way COMND$msg * Sends a message to the Server in a formatted way COMND$msg
*/ */
@ -220,8 +226,10 @@ public class Client {
cP.start(); cP.start();
client.userInputListener(); //this one blocks. client.userInputListener(); //this one blocks.
//Start the GUI //Start the GUI
Thread guiThread = new Thread(client.chatGUi); GUI gui = new GUI(client.chatApp);
Thread guiThread = new Thread(gui);
guiThread.start(); guiThread.start();
LOGGER.info("7");
} catch (UnknownHostException e) { } catch (UnknownHostException e) {
System.out.println("Invalid host IP"); System.out.println("Invalid host IP");
} catch (IOException e) { } catch (IOException e) {
@ -240,14 +248,17 @@ public class Client {
Thread cP = new Thread(client.clientPinger); Thread cP = new Thread(client.clientPinger);
cP.start(); cP.start();
client.userInputListener(); //this one blocks. client.userInputListener(); //this one blocks.
LOGGER.info("7.1");
Thread guiThread = new Thread(client.chatGUi); Thread guiThread = new Thread(client.chatGUi);
LOGGER.info("8");
guiThread.start(); guiThread.start();
LOGGER.info("9");
} catch (UnknownHostException e) { } catch (UnknownHostException e) {
System.out.println("Invalid host IP"); System.out.println("Invalid host IP");
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
LOGGER.info("10");
} }
public Socket getSocket() { public Socket getSocket() {

View File

@ -58,6 +58,9 @@ public class JClientProtocolParser {
c.positionSetter(msg.substring(6)); c.positionSetter(msg.substring(6));
break; break;
case Protocol.serverDeliversLobbyList: case Protocol.serverDeliversLobbyList:
case Protocol.changedUserName:
c.changeUsername(msg.substring(6));
break;
default: default:
System.out.println("Received unknown command"); System.out.println("Received unknown command");
} }

View File

@ -1,8 +1,13 @@
package ch.unibas.dmi.dbis.cs108.multiplayer.client.gui; package ch.unibas.dmi.dbis.cs108.multiplayer.client.gui;
import ch.unibas.dmi.dbis.cs108.BudaLogConfig;
import ch.unibas.dmi.dbis.cs108.multiplayer.client.Client; import ch.unibas.dmi.dbis.cs108.multiplayer.client.Client;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class ClientModel { public class ClientModel {
public static final Logger LOGGER = LogManager.getLogger(ClientModel.class);
public static final BudaLogConfig l = new BudaLogConfig(LOGGER);
private String username; private String username;
private Client client; private Client client;

View File

@ -1,14 +1,25 @@
package ch.unibas.dmi.dbis.cs108.multiplayer.client.gui; package ch.unibas.dmi.dbis.cs108.multiplayer.client.gui;
import ch.unibas.dmi.dbis.cs108.BudaLogConfig;
import ch.unibas.dmi.dbis.cs108.multiplayer.client.gui.chat.ChatApp; import ch.unibas.dmi.dbis.cs108.multiplayer.client.gui.chat.ChatApp;
import javafx.application.Application; import javafx.application.Application;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class GUI implements Runnable{ public class GUI implements Runnable{
public static final Logger LOGGER = LogManager.getLogger(GUI.class);
public static final BudaLogConfig l = new BudaLogConfig(LOGGER);
ChatApp chatApp; ChatApp chatApp;
private String name;
public GUI (ChatApp chatApp) { public GUI (ChatApp chatApp) {
this.chatApp = chatApp; this.chatApp = chatApp;
} }
public void setName(String name) {
this.name = name;
}
/** /**
* When an object implementing interface {@code Runnable} is used to create a thread, starting the * When an object implementing interface {@code Runnable} is used to create a thread, starting the
* thread causes the object's {@code run} method to be called in that separately executing * thread causes the object's {@code run} method to be called in that separately executing
@ -18,8 +29,12 @@ public class GUI implements Runnable{
* *
* @see Thread#run() * @see Thread#run()
*/ */
@Override @Override
public void run() { public void run() {
LOGGER.info("here");
//String name =
Application.launch(this.chatApp.getClass()); Application.launch(this.chatApp.getClass());
} }
} }

View File

@ -1,5 +1,7 @@
package ch.unibas.dmi.dbis.cs108.multiplayer.client.gui.chat; package ch.unibas.dmi.dbis.cs108.multiplayer.client.gui.chat;
import ch.unibas.dmi.dbis.cs108.BudaLogConfig;
import ch.unibas.dmi.dbis.cs108.multiplayer.client.Client;
import ch.unibas.dmi.dbis.cs108.multiplayer.client.gui.ClientModel; import ch.unibas.dmi.dbis.cs108.multiplayer.client.gui.ClientModel;
import java.net.URL; import java.net.URL;
import java.util.Objects; import java.util.Objects;
@ -8,19 +10,49 @@ import javafx.fxml.FXMLLoader;
import javafx.scene.Parent; import javafx.scene.Parent;
import javafx.scene.Scene; import javafx.scene.Scene;
import javafx.stage.Stage; import javafx.stage.Stage;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class ChatApp extends Application { public class ChatApp extends Application {
ClientModel clientModel; public static final Logger LOGGER = LogManager.getLogger(ChatApp.class);
private ChatController chatController; public static final BudaLogConfig l = new BudaLogConfig(LOGGER);
private static ClientModel clientModel;
private static ChatController chatController;
private ClientModel cModel;
public ChatApp() { public ChatApp() {
super(); super();
LOGGER.info("Empty ChatApp constructor got called: ");
} }
public ChatApp(ClientModel clientModel) { public ChatApp(ClientModel clientModel) {
this.clientModel = clientModel; this.clientModel = clientModel;
this.chatController = new ChatController(clientModel); this.chatController = new ChatController(clientModel);
} }
public static void setChatController(
ChatController chatC) {
chatController = chatC;
}
public void setcModel(ClientModel cModel) {
this.cModel = cModel;
}
public ClientModel getcModel() {
return cModel;
}
public static void setClientModel(ClientModel clientM) {
clientModel = clientM;
}
public static ClientModel getClientModel() {
return clientModel;
}
/** /**
* The main entry point for all JavaFX applications. The start method is called after the init * The main entry point for all JavaFX applications. The start method is called after the init
* method has returned, and after the system is ready for the application to begin running. * method has returned, and after the system is ready for the application to begin running.
@ -36,8 +68,11 @@ public class ChatApp extends Application {
*/ */
@Override @Override
public void start(Stage primaryStage) throws Exception { public void start(Stage primaryStage) throws Exception {
LOGGER.info("made it here");
this.setcModel(clientModel);
URL resource = ChatApp.class.getResource( URL resource = ChatApp.class.getResource(
"splitPaneChatView.fxml"); "splitPaneChatView.fxml");
LOGGER.info("1");
if (resource == null) { if (resource == null) {
System.out.println("File wasnt found"); System.out.println("File wasnt found");
} }
@ -46,16 +81,23 @@ public class ChatApp extends Application {
Parent root = FXMLLoader.load( Parent root = FXMLLoader.load(
Objects.requireNonNull(ChatApp.class.getResource( Objects.requireNonNull(ChatApp.class.getResource(
"splitPaneChatView.fxml"))); "splitPaneChatView.fxml")));
LOGGER.info("2");
// TODO bin chatController.getChatPaneRoot() border to root border for rezising // TODO bin chatController.getChatPaneRoot() border to root border for rezising
Scene scene = new Scene(root); Scene scene = new Scene(root);
LOGGER.info("3");
scene.setRoot(root); scene.setRoot(root);
LOGGER.info("4");
primaryStage.setScene(scene); primaryStage.setScene(scene);
LOGGER.info("5");
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
primaryStage.setResizable(true); primaryStage.setResizable(true);
LOGGER.info("6");
primaryStage.setTitle("Chat"); primaryStage.setTitle("Chat");
LOGGER.info("7");
primaryStage.show(); primaryStage.show();
LOGGER.info("8");
} }

View File

@ -1,6 +1,7 @@
package ch.unibas.dmi.dbis.cs108.multiplayer.client.gui.chat; package ch.unibas.dmi.dbis.cs108.multiplayer.client.gui.chat;
import ch.unibas.dmi.dbis.cs108.BudaLogConfig;
import ch.unibas.dmi.dbis.cs108.multiplayer.client.gui.ClientModel; import ch.unibas.dmi.dbis.cs108.multiplayer.client.gui.ClientModel;
import ch.unibas.dmi.dbis.cs108.multiplayer.helpers.Protocol; import ch.unibas.dmi.dbis.cs108.multiplayer.helpers.Protocol;
import java.net.URL; import java.net.URL;
@ -21,11 +22,17 @@ import javafx.scene.control.SplitPane;
import javafx.scene.control.TextArea; import javafx.scene.control.TextArea;
import javafx.scene.control.TextField; import javafx.scene.control.TextField;
import javafx.scene.layout.Background; import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.VBox; import javafx.scene.layout.VBox;
import javafx.scene.paint.Color; import javafx.scene.paint.Color;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class ChatController implements Initializable { public class ChatController implements Initializable {
public static final Logger LOGGER = LogManager.getLogger(ChatController.class);
public static final BudaLogConfig l = new BudaLogConfig(LOGGER);
@FXML @FXML
private SplitPane chatPaneRoot; private SplitPane chatPaneRoot;
@FXML @FXML
@ -37,7 +44,7 @@ public class ChatController implements Initializable {
@FXML @FXML
private TextArea chatMsgField; private TextArea chatMsgField;
private ClientModel client; private static ClientModel client;
private SimpleBooleanProperty whisperTargetChosen; private SimpleBooleanProperty whisperTargetChosen;
private String cmd; private String cmd;
@ -50,12 +57,14 @@ public class ChatController implements Initializable {
super(); super();
whisperTargetChosen = new SimpleBooleanProperty(); whisperTargetChosen = new SimpleBooleanProperty();
cmd = ""; cmd = "";
LOGGER.info("ChatController empty constructor used");
} }
public ChatController(ClientModel client) {
this.client = client; public ChatController(ClientModel c) {
client = c;
whisperTargetChosen = new SimpleBooleanProperty(); whisperTargetChosen = new SimpleBooleanProperty();
cmd = ""; cmd = "";
LOGGER.info("ChatController single parameter constructor used");
} }
@ -68,7 +77,8 @@ public class ChatController implements Initializable {
*/ */
@Override @Override
public void initialize(URL location, ResourceBundle resources) { public void initialize(URL location, ResourceBundle resources) {
setClient(ChatApp.getClientModel());
ChatApp.setChatController(this);
vBoxChatMessages.getChildren().addListener(new ListChangeListener<Node>() { vBoxChatMessages.getChildren().addListener(new ListChangeListener<Node>() {
@Override @Override
public void onChanged(Change<? extends Node> c) { public void onChanged(Change<? extends Node> c) {
@ -100,10 +110,13 @@ public class ChatController implements Initializable {
String msg = chatMsgField.getText(); String msg = chatMsgField.getText();
if (!msg.isEmpty()) { if (!msg.isEmpty()) {
client.getClient().sendMsgToServer(cmd.toString() + msg); client.getClient().sendMsgToServer(cmd.toString() + msg);
LOGGER.info("Message trying to send is: " + cmd.toString() + msg);
Label l = new Label(client.getUsername() + " (you): " + msg); Label l = new Label(client.getUsername() + " (you): " + msg);
l.setBackground(Background.fill(Color.LAVENDER)); l.setBackground(Background.fill(Color.LAVENDER));
vBoxChatMessages.getChildren().add(l); vBoxChatMessages.getChildren().add(l);
chatMsgField.clear(); chatMsgField.clear();
} else {
LOGGER.debug("Trying to send an empty message.");
} }
} }
}); });
@ -119,30 +132,17 @@ public class ChatController implements Initializable {
} }
}); });
//Bind the the fact if the whisper field contains a name to a boolean //Possibly now the whisperTargetChosenProperty is obsolete
whisperTargetChosen.bind(whisperTargetSelectField.textProperty().isEmpty());
/**
* change the chat command based on the whisper text field.
*/
whisperTargetChosen.addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue,
Boolean newValue) {
//is true if {@code whisperTargetSelectedField} has content
if (!newValue) {
cmd = whisper + "$";
} else {
cmd = chatToLobby + "$";
}
}
});
whisperTargetSelectField.textProperty().addListener(new ChangeListener<String>() { whisperTargetSelectField.textProperty().addListener(new ChangeListener<String>() {
@Override @Override
public void changed(ObservableValue<? extends String> observable, String oldValue, public void changed(ObservableValue<? extends String> observable, String oldValue,
String newValue) { String newValue) {
whisperTargetSelectField.setText(newValue); whisperTargetSelectField.setText(newValue);
if (newValue.isEmpty()) {
cmd = chatToLobby + "$";
} else {
cmd = whisper + "$" + whisperTargetSelectField.getText() + "$";
}
} }
}); });
} }
@ -150,7 +150,7 @@ public class ChatController implements Initializable {
/** /**
* @return the client who's chat controller this is * @return the client who's chat controller this is
*/ */
public ClientModel getClient() { public static ClientModel getClient() {
return client; return client;
} }
@ -172,7 +172,11 @@ public class ChatController implements Initializable {
*/ */
public void addChatMsgToView(String msg) { public void addChatMsgToView(String msg) {
Label l = new Label(msg); Label l = new Label(msg);
if (msg.contains("whispers")) {
l.setBackground(Background.fill(Color.SLATEBLUE));
} else {
l.setBackground(Background.fill(Color.LIGHTSKYBLUE)); l.setBackground(Background.fill(Color.LIGHTSKYBLUE));
}
l.setTextFill(Color.BLACK); l.setTextFill(Color.BLACK);
Platform.runLater(new Runnable() { Platform.runLater(new Runnable() {
@Override @Override

View File

@ -187,7 +187,10 @@ public class Protocol {
*/ */
public static final String serverDeliversLobbyList = "LLIST"; //todo: do we need this? public static final String serverDeliversLobbyList = "LLIST"; //todo: do we need this?
/**
* Informs Client, that their username has been changed
*/
public static final String changedUserName = "CHNAM";
} }

View File

@ -117,18 +117,19 @@ public class ClientHandler implements Runnable {
} }
/** /**
* Lets the client change their username, if the username is already taken, a similar option is * Lets the client change their username, if the username is already taken, a similar option is
* chosen. * chosen.
*
* @param newName The desired new name to replace the old one with. * @param newName The desired new name to replace the old one with.
*/ */
public void changeUsername(String newName) { public void changeUsername(String newName) {
String helper = this.getClientUserName(); String helper = this.getClientUserName();
this.clientUserName = nameDuplicateChecker.checkName(newName); this.clientUserName = nameDuplicateChecker.checkName(newName);
sendMsgToClient(Protocol.changedUserName + "$" + newName);
broadcastAnnouncementToAll(helper + " has changed their nickname to " + clientUserName); broadcastAnnouncementToAll(helper + " has changed their nickname to " + clientUserName);
try { try {
getLobby().getGame().getGameState().changeUsername(helper,newName); getLobby().getGame().getGameState().changeUsername(helper, newName);
} catch (NullPointerException e) { } catch (NullPointerException e) {
} }
} }
@ -152,8 +153,8 @@ public class ClientHandler implements Runnable {
} }
/** /**
* Returns the Lobby this ClientHandler is in. If this ClientHandler is not in a Lobby, * Returns the Lobby this ClientHandler is in. If this ClientHandler is not in a Lobby, it returns
* it returns null. * null.
*/ */
public Lobby getLobby() { public Lobby getLobby() {
try { try {
@ -164,19 +165,23 @@ public class ClientHandler implements Runnable {
} }
/** /**
* Broadcasts a chat Message to all clients in the same lobby in the form "Username: @msg" * Broadcasts a chat Message to all clients in the same lobby in the form "Username: @msg" If this
* If this client isn't in a lobby, it instead sends the message to everyone not in a lobby * client isn't in a lobby, it instead sends the message to everyone not in a lobby
*
* @param msg the Message to be broadcast * @param msg the Message to be broadcast
*/ */
public void broadcastChatMessageToLobby(String msg) { public void broadcastChatMessageToLobby(String msg) {
Lobby l = getLobby(); Lobby l = getLobby();
if (l != null) { if (l != null) {
for (ClientHandler client : l.getLobbyClients()) { for (ClientHandler client : l.getLobbyClients()) {
if(client.getClientUserName().equals(this.getClientUserName())){
continue;
}
client.sendMsgToClient(Protocol.printToClientChat + "$" + clientUserName + ": " + msg); client.sendMsgToClient(Protocol.printToClientChat + "$" + clientUserName + ": " + msg);
} }
} else { } else {
//send msg to all clients who are not in a lobby. //send msg to all clients who are not in a lobby.
for (ClientHandler client: connectedClients) { for (ClientHandler client : connectedClients) {
if (Lobby.clientIsInLobby(client) == -1) { if (Lobby.clientIsInLobby(client) == -1) {
client.sendMsgToClient(Protocol.printToClientChat + "$" + clientUserName + ": " + msg); client.sendMsgToClient(Protocol.printToClientChat + "$" + clientUserName + ": " + msg);
} }
@ -199,8 +204,9 @@ public class ClientHandler implements Runnable {
} }
/** /**
* Broadcasts a chat Message to all clients across all lobbies & clients who are not in a lobby * Broadcasts a chat Message to all clients across all lobbies & clients who are not in a lobby in
* in the form "Username: @msg" * the form "Username: @msg"
*
* @param msg the Message to be broadcast * @param msg the Message to be broadcast
*/ */
public void broadcastChatMessageToAll(String msg) { public void broadcastChatMessageToAll(String msg) {
@ -212,9 +218,11 @@ public class ClientHandler implements Runnable {
/** /**
* Broadcasts a non-chat Message to all active clients. This can be used for server messages / * Broadcasts a non-chat Message to all active clients. This can be used for server messages /
* announcements rather than chat messages. The message will be printed to the user exactly as it * announcements rather than chat messages. The message will be printed to the user exactly as it
* is given to this method. Unlike eg. broadcastChatMessageToLobby, it will also be printed onto the server * is given to this method. Unlike eg. broadcastChatMessageToLobby, it will also be printed onto
* console. * the server console.
* @param msg the Message to be broadcast. Does not have to be protocol-formatted, this method will take care of that. *
* @param msg the Message to be broadcast. Does not have to be protocol-formatted, this method
* will take care of that.
*/ */
public static void broadcastAnnouncementToAll(String msg) { public static void broadcastAnnouncementToAll(String msg) {
System.out.println(msg); System.out.println(msg);
@ -224,12 +232,13 @@ public class ClientHandler implements Runnable {
} }
/** /**
* Broadcasts a non-chat Message to all clients in the same lobby. This can be used for server messages / * Broadcasts a non-chat Message to all clients in the same lobby. This can be used for server
* announcements rather than chat messages. The message will be printed to the user exactly as it * messages / announcements rather than chat messages. The message will be printed to the user
* is given to this method. The announcement will not be printed on the server console. * exactly as it is given to this method. The announcement will not be printed on the server
* If this clienthandler is not in a lobby, it will instead broadcast to all clients. * console. If this clienthandler is not in a lobby, it will instead broadcast to all clients.
* *
* @param msg the Message to be broadcast. Does not have to be protocol-formatted, this method will take care of that. * @param msg the Message to be broadcast. Does not have to be protocol-formatted, this method
* will take care of that.
*/ */
public void broadcastAnnouncementToLobby(String msg) { public void broadcastAnnouncementToLobby(String msg) {
Lobby l = getLobby(); Lobby l = getLobby();
@ -246,13 +255,17 @@ public class ClientHandler implements Runnable {
} }
/** /**
* Sends a message only to the specified user, as well as sending a confirmation to the user who sent the message * Sends a message only to the specified user, as well as sending a confirmation to the user who
* that it has been sent. Syntax: * sent the message that it has been sent. Syntax:
*
* @param target MUST NOT BE NULL! * @param target MUST NOT BE NULL!
*/ */
public void whisper(String msg, ClientHandler target) { public void whisper(String msg, ClientHandler target) {
target.sendMsgToClient(Protocol.printToClientChat + "$" + this.getClientUserName() + " whispers: " + msg); target.sendMsgToClient(
sendMsgToClient(Protocol.printToClientChat + "$You whispered to " + target.getClientUserName() + ": " + msg); Protocol.printToClientChat + "$" + this.getClientUserName() + " whispers: " + msg);
sendMsgToClient(
Protocol.printToClientChat + "$You whispered to " + target.getClientUserName() + ": "
+ msg);
} }
/** /**
@ -275,34 +288,56 @@ public class ClientHandler implements Runnable {
} }
/** /**
* Takes a msg of the form position$vote and extracts vote and position from it and saves it * Decode a whisper mesage
* in VoteHandler.getClientVoteData *
* @param msg to decode. the command has been removed from the front
* @return a String[] containing the target at index 0 and the message at index 1.
*/
public String[] decodeWhisper(String msg) {
int msgIndex = msg.indexOf('$');
String target = "";
String chatMsg = "";
LOGGER.debug("incoming whisper to decode is:" + msg);
try {
target = msg.substring(0, msgIndex);
chatMsg = msg.substring(msgIndex + 1);
LOGGER.debug("whisper target is: " + target);
LOGGER.debug("whisper chatMsg is: " + chatMsg);
} catch (Exception e) {
LOGGER.warn("decode whisper issue: " + e.getMessage());
}
return new String[]{target, chatMsg};
}
/**
* Takes a msg of the form position$vote and extracts vote and position from it and saves it in
* VoteHandler.getClientVoteData
*
* @param msg the messaged to decode * @param msg the messaged to decode
*/ */
public void decodeVote(String msg){ public void decodeVote(String msg) {
int msgIndex = msg.indexOf('$'); int msgIndex = msg.indexOf('$');
int vote = Integer.MAX_VALUE; int vote = Integer.MAX_VALUE;
int position = 0; int position = 0;
LOGGER.debug("Message is " + msg); LOGGER.debug("Message is " + msg);
try { try {
position = Integer.parseInt(msg.substring(0,msgIndex)); position = Integer.parseInt(msg.substring(0, msgIndex));
vote = Integer.parseInt(msg.substring(msgIndex + 1)); vote = Integer.parseInt(msg.substring(msgIndex + 1));
LOGGER.debug("Vote is:" + vote); LOGGER.debug("Vote is:" + vote);
} catch (Exception e) { } catch (Exception e) {
LOGGER.warn("Invalid vote " + e.getMessage()); LOGGER.warn("Invalid vote " + e.getMessage());
} }
LOGGER.debug("Vote is:" + vote); LOGGER.debug("Vote is:" + vote);
if(vote != Integer.MAX_VALUE) { //gets MAX_VALUE when the vote wasn't valid if (vote != Integer.MAX_VALUE) { //gets MAX_VALUE when the vote wasn't valid
getLobby().getGame().getGameState().getClientVoteData().setVote(position,vote); getLobby().getGame().getGameState().getClientVoteData().setVote(position, vote);
LOGGER.debug("Player vote: " + vote); LOGGER.debug("Player vote: " + vote);
getLobby().getGame().getGameState().getClientVoteData().setHasVoted(position,true); getLobby().getGame().getGameState().getClientVoteData().setHasVoted(position, true);
} }
} }
/** /**
* Initializes a new Game instance and starts its run method in a new thread. * Initializes a new Game instance and starts its run method in a new thread. Puts the game in the
* Puts the game in the corresponding lobby. Only the admin of this lobby can start a new * corresponding lobby. Only the admin of this lobby can start a new game.
* game.
*/ */
public void startNewGame() { public void startNewGame() {
try { try {
@ -328,9 +363,9 @@ public class ClientHandler implements Runnable {
} }
/** /**
* Sends an announcement to just this client. Essentially the same as broadcastAnnouncementToAll except * Sends an announcement to just this client. Essentially the same as broadcastAnnouncementToAll
* it only sends an announcement to just this client instead of everyone. * except it only sends an announcement to just this client instead of everyone. Can be used for
* Can be used for private non-chat messages (e.g. "You are now a ghost"). * private non-chat messages (e.g. "You are now a ghost").
*/ */
public void sendAnnouncementToClient(String msg) { public void sendAnnouncementToClient(String msg) {
sendMsgToClient(Protocol.printToClientConsole + "$" + msg); sendMsgToClient(Protocol.printToClientConsole + "$" + msg);
@ -347,7 +382,8 @@ public class ClientHandler implements Runnable {
connectedClients.remove(this); connectedClients.remove(this);
disconnectClient(); disconnectClient();
leaveLobby(); leaveLobby();
broadcastAnnouncementToAll(getClientUserName() + " has left the server due to a connection loss."); broadcastAnnouncementToAll(
getClientUserName() + " has left the server due to a connection loss.");
disconnectedClients.add(this); disconnectedClients.add(this);
} }
@ -377,7 +413,9 @@ public class ClientHandler implements Runnable {
} }
/** /**
* The client wants to join the lobby with the index i. If the lobby is closed, the client will be notified. * The client wants to join the lobby with the index i. If the lobby is closed, the client will be
* notified.
*
* @param i the number of the lobby to join * @param i the number of the lobby to join
*/ */
public void joinLobby(int i) { public void joinLobby(int i) {
@ -386,7 +424,8 @@ public class ClientHandler implements Runnable {
if (l.getLobbyIsOpen()) { if (l.getLobbyIsOpen()) {
l.addPlayer(this); l.addPlayer(this);
} else { } else {
sendAnnouncementToClient("The game in Lobby " + l.getLobbyID() + " has already started, or the lobby is already full."); sendAnnouncementToClient("The game in Lobby " + l.getLobbyID()
+ " has already started, or the lobby is already full.");
} }
} else { } else {
sendAnnouncementToClient("Invalid Lobby nr."); sendAnnouncementToClient("Invalid Lobby nr.");
@ -403,7 +442,7 @@ public class ClientHandler implements Runnable {
if (l != null) { if (l != null) {
l.removePlayer(this); l.removePlayer(this);
Game game = l.getGame(); Game game = l.getGame();
if(game != null) { if (game != null) {
l.getGame().getGameState().handleClientDisconnect(this); l.getGame().getGameState().handleClientDisconnect(this);
} }
} }
@ -411,8 +450,8 @@ public class ClientHandler implements Runnable {
/** /**
* Lists all lobbies and their members, along with players outside lobbies * Lists all lobbies and their members, along with players outside lobbies to this clientHandler's
* to this clientHandler's client as an announcement. * client as an announcement.
*/ */
public void listLobbies() { public void listLobbies() {
if (Lobby.lobbies.isEmpty()) { if (Lobby.lobbies.isEmpty()) {
@ -420,7 +459,7 @@ public class ClientHandler implements Runnable {
} else { } else {
for (Lobby l : Lobby.lobbies) { for (Lobby l : Lobby.lobbies) {
String lobbyStatus = "closed"; String lobbyStatus = "closed";
if(l.getLobbyIsOpen()) { if (l.getLobbyIsOpen()) {
lobbyStatus = "open"; lobbyStatus = "open";
} }
sendAnnouncementToClient("Lobby nr. " + l.getLobbyID() + ": (" + lobbyStatus + ")"); sendAnnouncementToClient("Lobby nr. " + l.getLobbyID() + ": (" + lobbyStatus + ")");
@ -434,7 +473,7 @@ public class ClientHandler implements Runnable {
} }
} }
boolean helper = false; //used to print "Clients not in lobbies" only once, if needed. boolean helper = false; //used to print "Clients not in lobbies" only once, if needed.
for (ClientHandler c: connectedClients) { for (ClientHandler c : connectedClients) {
if (Lobby.clientIsInLobby(c) == -1) { if (Lobby.clientIsInLobby(c) == -1) {
if (!helper) { if (!helper) {
helper = true; helper = true;
@ -449,8 +488,8 @@ public class ClientHandler implements Runnable {
} }
/** /**
* Lists all players in the client's lobby. If the client is not in a Lobby, it will say * Lists all players in the client's lobby. If the client is not in a Lobby, it will say "You are
* "You are not in a lobby." * not in a lobby."
*/ */
public void listPlayersInLobby() { public void listPlayersInLobby() {
Lobby l = getLobby(); Lobby l = getLobby();
@ -469,7 +508,8 @@ public class ClientHandler implements Runnable {
} }
/** /**
* Lists all Games currenty running and already finished and displays it to the client handled by this * Lists all Games currenty running and already finished and displays it to the client handled by
* this
*/ */
public void listGames() { public void listGames() {
if (Lobby.runningGames.isEmpty() && Lobby.finishedGames.isEmpty()) { if (Lobby.runningGames.isEmpty() && Lobby.finishedGames.isEmpty()) {
@ -478,7 +518,8 @@ public class ClientHandler implements Runnable {
sendAnnouncementToClient("Running Games:"); sendAnnouncementToClient("Running Games:");
try { try {
for (Game runningGame : Lobby.runningGames) { for (Game runningGame : Lobby.runningGames) {
sendAnnouncementToClient(" - " + runningGame.getName() + ", Lobby" + runningGame.getLobby().getLobbyID()); sendAnnouncementToClient(
" - " + runningGame.getName() + ", Lobby" + runningGame.getLobby().getLobbyID());
} }
} catch (Exception e) { } catch (Exception e) {
sendAnnouncementToClient(" - No running Games"); sendAnnouncementToClient(" - No running Games");
@ -486,7 +527,8 @@ public class ClientHandler implements Runnable {
sendAnnouncementToClient("Finished Games:"); sendAnnouncementToClient("Finished Games:");
try { try {
for (Game finishedGame : Lobby.finishedGames) { for (Game finishedGame : Lobby.finishedGames) {
sendAnnouncementToClient(" - " + finishedGame.getName() + ", Lobby" + finishedGame.getLobby().getLobbyID()); sendAnnouncementToClient(
" - " + finishedGame.getName() + ", Lobby" + finishedGame.getLobby().getLobbyID());
} }
} catch (Exception e) { } catch (Exception e) {
sendAnnouncementToClient(" - No finished Games"); sendAnnouncementToClient(" - No finished Games");
@ -501,9 +543,10 @@ public class ClientHandler implements Runnable {
Lobby l = getLobby(); Lobby l = getLobby();
if (l != null) { if (l != null) {
Game g = l.getGame(); Game g = l.getGame();
if(g != null) if (g != null) {
l.getGame().getGameState().handleClientDisconnect(this); l.getGame().getGameState().handleClientDisconnect(this);
} }
}
socket = this.getSocket(); socket = this.getSocket();
in = this.getIn(); in = this.getIn();
out = this.getOut(); out = this.getOut();

View File

@ -47,8 +47,9 @@ public class JServerProtocolParser {
//find ClientHandler //find ClientHandler
try { try {
ClientHandler target = null; ClientHandler target = null;
String targetName = msg.substring(6, msg.indexOf("$", 6)); String[] targetAndMsg = h.decodeWhisper(msg.substring(6));
String chatMsg = msg.substring(msg.indexOf("$", 6)+1); String targetName = targetAndMsg[0];
String chatMsg = targetAndMsg[1];
System.out.println(targetName); System.out.println(targetName);
System.out.println(chatMsg); System.out.println(chatMsg);
for (ClientHandler c : ClientHandler.getConnectedClients()) { for (ClientHandler c : ClientHandler.getConnectedClients()) {

View File

@ -1,66 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.ScrollPane?>
<?import javafx.scene.control.SplitPane?>
<?import javafx.scene.control.TextArea?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.VBox?>
<fx:root maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" type="AnchorPane" xmlns="http://javafx.com/javafx/18" xmlns:fx="http://javafx.com/fxml/1" fx:controller="ch.unibas.dmi.dbis.cs108.multiplayer.client.gui.chat.ChatController">
<children>
<SplitPane fx:id ="chatPaneRoot" dividerPositions="0.5" layoutX="214.0" layoutY="92.0" orientation="VERTICAL" prefHeight="400.0" prefWidth="600.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
<items>
<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="100.0" prefWidth="160.0">
<children>
<ScrollPane layoutX="149.0" layoutY="-18.0" prefHeight="196.0" prefWidth="598.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
<content>
<VBox fx:id="vBoxChatMessages" prefHeight="200.0" prefWidth="581.0" />
</content>
</ScrollPane>
</children>
</AnchorPane>
<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="100.0" prefWidth="160.0">
<children>
<SplitPane dividerPositions="0.29797979797979796" layoutX="166.0" layoutY="8.0" prefHeight="195.0" prefWidth="598.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
<items>
<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="160.0" prefWidth="100.0">
<children>
<SplitPane dividerPositions="0.5" layoutY="-3.0" orientation="VERTICAL" prefHeight="193.0" prefWidth="174.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
<items>
<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="100.0" prefWidth="160.0">
<children>
<Button fx:id="sendButton" layoutX="50.0" layoutY="21.0" mnemonicParsing="false" prefHeight="92.0" prefWidth="172.0" text="Send" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0" />
</children>
</AnchorPane>
<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="100.0" prefWidth="160.0">
<children>
<TextField fx:id="whisperTargetSelectField" layoutY="14.0" prefHeight="92.0" prefWidth="172.0" promptText="whisper..." AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0" />
</children>
</AnchorPane>
</items>
</SplitPane>
</children>
<padding>
<Insets bottom="5.0" left="5.0" top="3.0" />
</padding>
</AnchorPane>
<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="160.0" prefWidth="100.0">
<children>
<TextArea fx:id="chatMsgField" layoutX="120.0" layoutY="-30.0" prefHeight="193.0" prefWidth="415.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0" />
</children>
<padding>
<Insets bottom="5.0" right="5.0" />
</padding>
</AnchorPane>
</items>
</SplitPane>
</children>
</AnchorPane>
</items>
</SplitPane>
</children>
</fx:root>