Merge branch 'feat/client-communication' into feat/game-ui

This commit is contained in:
Julian Kropff
2026-04-09 13:35:55 +02:00
27 changed files with 2043 additions and 166 deletions
@@ -0,0 +1,63 @@
This Document states the Network-Protocol as it is currently implemented
## GET_MESSAGE_COUNT
This Command gets the number of messages, currently stored in the queue for the specific client.
(Is used together with GET_NEXT_MESSAGE, to get all messages that are currently in the queue)
Example:
```
GET_MESSAGE_COUNT
1
+OK
```
## GET_NEXT_MESSAGE
This Command gets the next Message that is being stored in the queue for the client.
(Command is being sent the amount of times, the GET_MESSAGE_COUNT Command returns)
Example:
```
GET_NEXT_MESSAGE
TYPE=LOBBY GAME=1 USER=player1 TARGET=null TIME=9:30 TEXT="Guten Tag"
+OK
```
## SEND_MESSAGE
This Command gets sent if the user of that client writes a message to one of the three possible chats
(The Arguments / Parameters of the Command describe all the parameters of the Object "Message" being used internally by both the Client and the Server)
Example:
```
SEND_MESSAGE TYPE=LOBBY GAME=1 USER=player1 TARGET=null TIME=10:30 TEXT="Hallo Welt"
+OK
```
## LOG_IN
This Command is used to create a user on the server and associate that user with a username
Server returns the username, slightly changed if it is already used by someone else, and an ID to identify the client.
Example:
```
LOG_IN USERNAME="Peter"
USERNAME="Peter" ID=<random UUID>
+OK
```
## LOG_OUT
This Command is used to quit the connection between client and server.
Example:
```
LOG_OUT
+OK
```
@@ -0,0 +1,249 @@
# Client Nework Architecture
<!-- vim-markdown-toc GFM -->
* [Architecture Overview](#architecture-overview)
* [network/Card.java](#networkcardjava)
* [network/GameState.java](#networkgamestatejava)
* [network/Player.java](#networkplayerjava)
* [network/ChatClient.java](#networkchatclientjava)
* [ChatClient(ClientService clientService)](#chatclientclientservice-clientservice)
* [sendMessage(Message message)](#sendmessagemessage-message)
* [getMessages()](#getmessages)
* [network/ClientService.java](#networkclientservicejava)
* [ClientService(String ip, int port)](#clientservicestring-ip-int-port)
* [processCommand(String message)](#processcommandstring-message)
* [sendRequest(Runnable request)](#sendrequestrunnable-request)
* [getRuntimeException(Exception e)](#getruntimeexceptionexception-e)
* [closeSocket()](#closesocket)
* [writeToTransport(String s) throws IOException](#writetotransportstring-s-throws-ioexception)
* [network/CoreClient.java](#networkcoreclientjava)
* [CoreClient(ClientService clientservice)](#coreclientclientservice-clientservice)
* [ping()](#ping)
* [login(String user)](#loginstring-user)
* [network/GameClient.java](#networkgameclientjava)
* [GameClient(ClientService client)](#gameclientclientservice-client)
* [getGameState()](#getgamestate)
* [parseGameState(String input)](#parsegamestatestring-input)
* [Example server response](#example-server-response)
* [network/LobbyClient.java](#networklobbyclientjava)
* [LobbyClient(ClientService client)](#lobbyclientclientservice-client)
* [fetchLobbyStatusString(int lobbyId)](#fetchlobbystatusstringint-lobbyid)
* [createLobby()](#createlobby)
* [getLobbyId()](#getlobbyid)
* [joinLobby(int lobbyId)](#joinlobbyint-lobbyid)
<!-- vim-markdown-toc -->
## Architecture Overview
```text
client/
├── game/
│ ├── Card.java
│ ├── GameState.java
│ └── Player.java
└── network/
├── ChatClient.java
├── ClientService.java
├── CoreClient.java
├── GameClient.java
└── LobbyClient.java
```
### game/Card.java
Represents a playing card with a value and suit.
### game/GameState.java
Represents the current state of the poker game, including the phase, pot size, current bet, dealer position, active player, community cards, and player information.
### game/Player.java
Represents a player in the poker game, including their name, chip count, current bet, state (e.g., `active`, `folded`), and their hole cards.
### network/ChatClient.java
The ChatClient class is responsible for sending messages to the server and retrieving messages from the server. It uses the ClientService to send commands and receive responses from the server.
#### ChatClient(ClientService clientService)
Constructs a ChatClient with the given ClientService for communication.
- **Parameter (`clientService`)**: The ClientService instance used to send commands and receive responses from the server.
#### sendMessage(Message message)
Send a Message to the server by converting it to a string format and sending a `SEND_MESSAGE` command with the message content as arguments.
- **Parameter (`message`)**: message The Message object to be sent to the server.
#### getMessages()
Retrieve messages from the server by first sending a `GET_MESSAGE_COUNT` command to determine how many messages are available and then sending `GET_NEXT_MESSAGE` commands in a loop to retrieve each message. The retrieved messages are parsed into Message objects and returned as a list.
- **Parameter (`A`)**: list of Message objects representing the messages retrieved from the server.
### network/ClientService.java
The ClientService class is responsible for managing the connection to the server, sending commands, and receiving responses. It uses a TcpTransport to
communicate with the server and an ExecutorService to handle asynchronous requests.
#### ClientService(String ip, int port)
Constructs a ClientService with the given server IP and port. It establishes a socket connection to the server and initializes the TcpTransport and ExecutorService for communication.
- **Parameter (`ip`)**: The IP address of the server to connect to.
- **Parameter (`port`)**: The port number of the server to connect to.
#### processCommand(String message)
Sends a command to the server and waits for the response. The command is sent using the TcpTransport, and the response is read in a loop until a valid response is received. The method handles `+OK` and `-ERROR` responses from the server and returns the actual response content.
- **Parameter (`message`)**: The command message to be sent to the server.
- **Return**: The response from the server as a string.
#### sendRequest(Runnable request)
Helper method to send a request to the server using the ExecutorService. It submits the request as a Runnable task and waits for its completion. If the task is interrupted or encounters an execution exception, it throws a
RuntimeException with the appropriate cause.
- **Parameter (`request`)**: The Runnable task representing the request to be sent to the server.
#### getRuntimeException(Exception e)
Helper method to extract the cause of an exception and return it as a RuntimeException. If the cause is null, it returns the original exception as a RuntimeException. If the cause is already a RuntimeException, it returns it directly. Otherwise, it wraps the cause in a new RuntimeException and returns it.
- **Parameter (`e`)**: The exception from which to extract the cause.
- **Return**: A RuntimeException representing the cause of the original exception.
#### closeSocket()
Closes the socket connection to the server and shuts down the ExecutorService. It also closes the TcpTransport used for communication. If any IOException occurs during this process, it prints the exception to the console.
#### writeToTransport(String s) throws IOException
Helper method to write a command string to the TcpTransport. It generates a unique ID for the command using the idGenerator and sends a RawPacket containing the ID and the command string to the server. If an IOException occurs during this process, it throws a RuntimeException with the cause.
- **Parameter (`s`)**: The command string to be sent to the server.
- **Throws IOException**: If an I/O error occurs while writing to the transport.
### network/CoreClient.java
The CoreClient class provides basic functionalities for communicating with the server, such as sending a ping command to check connectivity and logging in with a username. It uses the ClientService to send commands and receive responses from the server.
#### CoreClient(ClientService clientservice)
Constructs a CoreClient with the given ClientService for communication.
- **Parameter (`clientservice`)**: The ClientService instance used to send commands and receive responses from the server.
#### ping()
Sends a `PING` command to the server to check connectivity. The server should respond with a `PONG` message if the connection is successful.
#### login(String user)
Logs in to the server with the given username by sending a `LOGIN` command.
- **Parameter (`user`)**: The username to log in with.
### network/GameClient.java
The GameClient class is responsible for communicating with the server to retrieve the current game state. It sends a command to the server and parses the response into a structured GameState object.
#### GameClient(ClientService client)
Constructs a GameClient with the given ClientService for communication.
- **Parameter (`client`)**: The ClientService instance used to send commands and receive responses from the server.
#### getGameState()
Retrieves the current game state from the server by sending a command and parsing the response.
- **Return**: A GameState object representing the current state of the game.
#### parseGameState(String input)
Parses the raw response from the server into a structured GameState object.
- **Parameter (`input`)**: The raw response string from the server.
- **Return**: A GameState object representing the current state of the game.
#### Example server response
```text
+OK
PHASE=FLO P
POT=150
CURRENT_BET=50
DEALER=0
ACTIVE_PLAYER=1
CARDS
CARD
VALUE=10
SUIT=H
CARD
VALUE=7
SUIT=S
CARD
VALUE=A
SUIT=D
PLAYERS
PLAYER
NAME=Max
CHIPS=1200
BET=50
STATE=ACTIVE
CARDS
CARD
VALUE=K
SUIT=H
CARD
VALUE=3
SUIT=C
PLAYER
NAME=Anna
CHIPS=800
BET=0
STATE=FOLDED
CARDS
END
```
### network/LobbyClient.java
The LobbyClient class is responsible for communicating with the server to manage game lobbies. It provides methods to create a lobby, join a lobby, and fetch the current status of a lobby by sending appropriate commands to the server and processing the responses.
#### LobbyClient(ClientService client)
Constructs a LobbyClient with the given ClientService for communication.
- **Parameter (`client`)**: The ClientService instance used to send commands and receive responses from the server.
#### fetchLobbyStatusString(int lobbyId)
Fetch the current status of the lobby with the given id from the server.
- **Parameter (`lobbyId`)**: The id of the lobby to fetch the status for.
- **Return**: A string representing the current status of the lobby, as returned by the server.
#### createLobby()
Request the server to create a new lobby and return the id of the newly created lobby.
- **Return**: The id of the newly created lobby, as returned by the server.
#### getLobbyId()
Request the server to return the id of the lobby that the client is currently in.
- **Return**: The id of the lobby that the client is currently in, as returned by the server.
#### joinLobby(int lobbyId)
Request the server to join the lobby with the given id.
- **Parameter (`lobbyId`)**: The id of the lobby to join.
@@ -36,6 +36,12 @@ public class ClientApp {
int port = Integer.parseInt(parts[1]); int port = Integer.parseInt(parts[1]);
LOGGER.info("You've selected the client. It will connect port {} at host {}", port, host); LOGGER.info("You've selected the client. It will connect port {} at host {}", port, host);
Launcher.main(new String[] {}); // Expose the chosen host/port to the UI via system properties so controllers
// (which read System.getProperty("casono.server.host"/"casono.server.port"))
// can obtain the correct connection information.
System.setProperty("casono.server.host", host);
System.setProperty("casono.server.port", Integer.toString(port));
// Forward the original address argument to the launcher as well.
Launcher.main(new String[] { arg });
} }
} }
@@ -0,0 +1,65 @@
package ch.unibas.dmi.dbis.cs108.casono.client.chat;
import ch.unibas.dmi.dbis.cs108.casono.client.network.ChatClient;
import ch.unibas.dmi.dbis.cs108.casono.client.network.ClientService;
import java.util.List;
/**
* responsible for the transferring of messages from the server to the ChatModel
* or from the ChatViewController to the server
*/
public class ChatController {
private final String username;
private final ClientService clientService;
private final ChatClient chatClient;
private ChatModel chatModel;
private int game_id;
public ChatController(String username, ClientService clientService) {
this.username = username;
this.clientService = clientService;
this.chatClient = new ChatClient(this.clientService);
}
public void createChat(int game_id) {
chatModel = new ChatModel(ChatModel.ChatType.GLOBAL, username);
this.game_id = game_id;
}
public ChatModel getChatModel() {
return chatModel;
}
/**
* method to send a message, the ChatViewController received to the server
*/
public void sendMessage(String msg, String username) {
Message message = new Message(Message.MessageType.GLOBAL, 0, username, null, msg);
onSendToNetwork(message);
}
/**
* method to get all messages from the server
*/
public Boolean receiveMessage() {
List<Message> newMessages = chatClient.getMessages();
if (!newMessages.isEmpty()) {
for (Message msg : newMessages) {
chatModel.addMessage(msg);
}
return true;
} else { return false; }
}
/**
* method to send a message to the server
* @param message
*/
public void onSendToNetwork(Message message) {
chatClient.sendMessage(message);
}
}
@@ -0,0 +1,67 @@
package ch.unibas.dmi.dbis.cs108.casono.client.chat;
import java.util.ArrayList;
/**
* ChatModel, stores the data for a specific chat
*
* Holds the current state of a chat
*/
public class ChatModel {
public ArrayList<Message> messages;
public ChatType chattype;
public String username;
public int count;
public enum ChatType {
GLOBAL,
LOBBY,
WHISPER
}
/**
* Creates a new ChatModel, given a username of the client
* @param chattype
* @param username
*/
public ChatModel(ChatType chattype, String username) {
this.messages = new ArrayList<Message>();
this.chattype = chattype;
this.username = username;
this.count = 0;
}
/**
* method, used by the ChatViewController, to access all new messages, that are stored in the ChatModel
*/
public synchronized String viewNextMessage() {
count--;
Message msg = messages.getLast();
return String.format("[%s] %s: %s", msg.timestamp, msg.user, msg.getMessage());
}
/**
* Adds a new message
* method used by the ChatController
* @param msg
*/
public synchronized void addMessage(Message msg) {
messages.add(msg);
count++;
}
/**
* method to send all current messages to the ChatViewController, if needed
*/
public void addCompleteChat() {
for (int i = 0; i < this.messages.size(); i++) {
Message msg = this.messages.get(i);
}
}
}
@@ -0,0 +1,136 @@
package ch.unibas.dmi.dbis.cs108.casono.client.chat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Message Object for internal handling of Chat-Messages
* TODO: Should be used on both sides of the network
*/
public class Message {
private final MessageType type;
private final String message;
public String user;
public String timestamp;
public int game_id = 0;
public String target = null;
public enum MessageType {
GLOBAL, LOBBY, WHISPER
};
/**
* Constructor for creating Messages with all information given
* @param type - Either global, local or whisper
* @param game_id - lobby id, or null, if the type is global
* @param user - username
* @param target - username of the target user, for whisper chat
* @param message
*/
public Message(MessageType type, int game_id, String user, String target, String timestamp, String message) {
this.type = type;
this.game_id = game_id;
this.user = user;
this.target = target;
this.timestamp = timestamp;
this.message = message;
}
/**
* Constructor for creating the Messages of the current user, using this client -> time of writing is being recorded
* @param type - Either global, local or whisper
* @param game_id - lobby id, or null, if the type is global
* @param user - username
* @param target - username of the target user, for whisper chat
* @param message
*/
public Message(MessageType type, int game_id, String user, String target, String message) {
this.type = type;
this.game_id = game_id;
this.user = user;
this.target = target;
this.message = message;
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");
this.timestamp = now.format(formatter);
}
public String getMessage() {
return message;
}
public MessageType getMessageType() {
return type;
}
/*
* Method to test the system
* @return - String representation of the Message instance, as for example "player1: Hello World"
public String toString() {
return String.format("%s: %s", this.user, this.message);
}
*/
/**
* Method to create the request representation of the message object, to be sent to the server
* @return - request as specified in the network protocol, as String
*/
public String toArgsString() {
return String.format("TYPE=%s GAME=%d USER=%s TARGET=%s TIME=%s TEXT=%s",
this.type.toString(), this.game_id, this.user, this.target, this.timestamp, this.message);
}
/**
* Pattern, to analyze the response String with the given parameters
*/
public static Pattern msgRex = Pattern.compile(
"TYPE=(?<type>\\w+) GAME=(?<game>\\w+) USER=(?<user>\\w+) TARGET=(?<target>\\w+) TIME=(?<time>[0-9:.]+) TEXT=(?<text>.*)$");
/**
* Method to create a Message Object, from the information given by the String
* @param response - String that got sent as a response from the server
* @return - New Message Object
*/
public static Message toMessage(String response) {
Matcher m = msgRex.matcher(response);
if (! m.matches()) {
throw new RuntimeException("Can not parse message: '" + response+"'");
}
String typeString=m.group("type");
switch (typeString) {
case "GLOBAL":
return new Message(MessageType.GLOBAL,
0,
m.group("user"),
null,
m.group("time"),
m.group("text"));
case "LOBBY":
return new Message(MessageType.LOBBY,
Integer.parseInt(m.group("game")),
m.group("user"),
null,
m.group("time"),
m.group("text"));
case "WHISPER":
return new Message(MessageType.WHISPER,
Integer.parseInt(m.group("game")),
m.group("user"),
m.group("target"),
m.group("time"),
m.group("text"));
default:
throw new RuntimeException("Unknown message type " + typeString);
}
}
}
@@ -0,0 +1,9 @@
package ch.unibas.dmi.dbis.cs108.casono.client.game;
/**
* Represents a playing card with a value and suit.
*/
public class Card {
public String value;
public String suit;
}
@@ -0,0 +1,23 @@
package ch.unibas.dmi.dbis.cs108.casono.client.game;
import ch.unibas.dmi.dbis.cs108.casono.client.game.Card;
import ch.unibas.dmi.dbis.cs108.casono.client.game.Player;
import java.util.ArrayList;
import java.util.List;
/**
* Represents the current state of the poker game, including the phase, pot
* size, current bet, dealer position,
* active player, community cards, and player information.
*/
public class GameState {
public String phase;
public int pot;
public int currentBet;
public int dealer;
public int activePlayer;
public List<Card> communityCards = new ArrayList<>();
public List<Player> players = new ArrayList<>();
}
@@ -0,0 +1,17 @@
package ch.unibas.dmi.dbis.cs108.casono.client.game;
import java.util.ArrayList;
import java.util.List;
/**
* Represents a player in the poker game, including their name, chip count,
* current bet, state (e.g., "active", "folded"), and their hole cards.
*/
public class Player {
public String name;
public int chips;
public int bet;
public String state;
public List<Card> cards = new ArrayList<>();
}
@@ -0,0 +1,61 @@
package ch.unibas.dmi.dbis.cs108.casono.client.network;
import ch.unibas.dmi.dbis.cs108.casono.client.chat.Message;
import java.util.ArrayList;
import java.util.List;
/**
* The ChatClient class is responsible for sending messages to the server and
* retrieving messages from the server. It uses the ClientService to send
* commands and receive responses from the server.
*/
public class ChatClient {
private ClientService clientService;
/**
* Constructs a ChatClient with the given ClientService for communication.
*
* @param clientService The ClientService instance used to send commands and
* receive responses from the server.
*/
public ChatClient(ClientService clientService) {
this.clientService = clientService;
}
/**
* Send a Message to the server by converting it to a string format and
* sending a "SEND_MESSAGE" command with the message content as arguments.
*
* @param message The Message object to be sent to the server.
*/
public void sendMessage(Message message) {
String request = "SEND_MESSAGE " + message.toArgsString();
clientService.processCommand(request);
}
/**
* Retrieve messages from the server by first sending a "GET_MESSAGE_COUNT"
* command to determine how many messages are available and then sending
* "GET_NEXT_MESSAGE" commands in a loop to retrieve each message. The
* retrieved messages are parsed into Message objects and returned as a list.
*
* @return A list of Message objects representing the messages retrieved from
* the server.
*/
public List<Message> getMessages() {
String countStr = clientService.processCommand("GET_MESSAGE_COUNT");
int count = Integer.parseInt(countStr);
System.out.println("Got " + count + " messages");
List<Message> messages = new ArrayList<>();
for (int i = 0; i < count; i++) {
String message = clientService.processCommand("GET_NEXT_MESSAGE");
if (message != null) {
Message message1 = Message.toMessage(message);
messages.add(message1);
}
}
return messages;
}
}
@@ -0,0 +1,190 @@
package ch.unibas.dmi.dbis.cs108.casono.client.network;
import ch.unibas.dmi.dbis.cs108.casono.server.network.transport.RawPacket;
import ch.unibas.dmi.dbis.cs108.casono.server.network.transport.TcpTransport;
import java.net.Socket;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
/**
* The ClientService class is responsible for managing the connection to the
* server,
* sending commands, and receiving responses. It uses a TcpTransport to
* communicate
* with the server and an ExecutorService to handle asynchronous requests.
*/
public class ClientService {
private final TcpTransport clienttcptransport;
private final Socket socket;
private final ExecutorService executor;
private final boolean offlineMode;
public static ArrayList<String> response;
private final AtomicInteger idGenerator;
/**
* Constructs a ClientService with the given server IP and port. It establishes
* a socket connection to the server and initializes the TcpTransport and
* ExecutorService for communication.
*
* @param ip The IP address of the server to connect to.
* @param port The port number of the server to connect to.
*/
public ClientService(String ip, int port) {
this.idGenerator = new AtomicInteger(0);
this.offlineMode = false;
try {
socket = new Socket(ip, port);
clienttcptransport = new TcpTransport(socket);
} catch (IOException i) {
throw new RuntimeException(i);
}
executor = Executors.newSingleThreadExecutor();
}
/**
* Constructs a ClientService in offline mode. No network connection will be
* attempted and calls to processCommand will throw a RuntimeException.
*
* @param offline true to create an offline (no-network) client service
*/
public ClientService(boolean offline) {
this.idGenerator = new AtomicInteger(0);
this.offlineMode = offline;
this.socket = null;
this.clienttcptransport = null;
this.executor = Executors.newSingleThreadExecutor();
}
/**
* Returns true if this ClientService is running in offline mode (no network).
*/
public boolean isOffline() {
return offlineMode;
}
/**
* Sends a command to the server and waits for the response. The command is
* sent using the TcpTransport, and the response is read in a loop until a
* valid response is received. The method handles "+OK" and "-ERROR" responses
* from the server and returns the actual response content.
*
* @param message The command message to be sent to the server.
* @return The response from the server as a string.
*/
protected String processCommand(String message) {
if (offlineMode) {
throw new RuntimeException("ClientService is offline: cannot process command");
}
AtomicReference<String> response = new AtomicReference<>();
sendRequest(() -> {
try {
writeToTransport(message);
String responseLine = null;
do {
responseLine = clienttcptransport.read().payload();
System.out.println("Raw message '" + responseLine + "'");
if ("+OK".equals(responseLine)) {
return;
} else if (("-ERROR").equals(responseLine)) {
throw new RuntimeException(responseLine);
}
response.set(responseLine);
} while (true);
} catch (Exception e) {
throw getRuntimeException(e);
}
});
return response.get();
}
/**
* Helper method to send a request to the server using the ExecutorService. It
* submits the request as a Runnable task and waits for its completion. If
* the task is interrupted or encounters an execution exception, it throws a
* RuntimeException with the appropriate cause.
*
* @param request The Runnable task representing the request to be sent to the
* server.
*/
private void sendRequest(Runnable request) {
Future<?> future = executor.submit(request);
try {
future.get();
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (ExecutionException e) {
throw getRuntimeException(e);
}
}
/**
* Helper method to extract the cause of an exception and return it as a
* RuntimeException. If the cause is null, it returns the original exception as
* a RuntimeException. If the cause is already a RuntimeException, it returns
* it directly. Otherwise, it wraps the cause in a new RuntimeException and
* returns it.
*
* @param e The exception from which to extract the cause.
* @return A RuntimeException representing the cause of the original exception.
*/
private static RuntimeException getRuntimeException(Exception e) {
Throwable reason = e.getCause();
RuntimeException re;
if (reason == null) {
reason = e;
} else if (reason instanceof RuntimeException rte) {
re = rte;
}
re = new RuntimeException(reason);
return re;
}
/**
* Closes the socket connection to the server and shuts down the
* ExecutorService.
* It also closes the TcpTransport used for communication. If any IOException
* occurs during this process, it prints the exception to the console.
*/
public void closeSocket() {
try {
executor.shutdown();
if (clienttcptransport != null) {
clienttcptransport.close();
}
if (socket != null) {
socket.close();
}
} catch (IOException j) {
System.out.println(j);
}
}
/**
* Helper method to write a command string to the TcpTransport. It generates a
* unique ID for the command using the idGenerator and sends a RawPacket
* containing the ID and the command string to the server. If an IOException
* occurs during this process, it throws a RuntimeException with the cause.
*
* @param s The command string to be sent to the server.
* @throws IOException If an I/O error occurs while writing to the transport.
*/
private void writeToTransport(String s) throws IOException {
int id = this.idGenerator.incrementAndGet();
this.clienttcptransport.write(new RawPacket(id, s));
}
}
@@ -0,0 +1,39 @@
package ch.unibas.dmi.dbis.cs108.casono.client.network;
/**
* The CoreClient class provides basic functionalities for communicating with
* the
* server, such as sending a ping command to check connectivity and logging in
* with a username. It uses the ClientService to send commands and receive
* responses from the server.
*/
public class CoreClient {
private final ClientService clientService;
/**
* Constructs a CoreClient with the given ClientService for communication.
*
* @param clientservice The ClientService instance used to send commands and
* receive responses from the server.
*/
public CoreClient(ClientService clientservice) {
this.clientService = clientservice;
}
/**
* Sends a "PING" command to the server to check connectivity. The server
* should respond with a "PONG" message if the connection is successful.
*/
public void ping() {
clientService.processCommand("PING");
}
/**
* Logs in to the server with the given username by sending a "LOGIN" command.
*
* @param user The username to log in with.
*/
public void login(String user) {
clientService.processCommand("LOGIN USERNAME=" + user);
}
}
@@ -0,0 +1,125 @@
package ch.unibas.dmi.dbis.cs108.casono.client.network;
import ch.unibas.dmi.dbis.cs108.casono.client.game.Card;
import ch.unibas.dmi.dbis.cs108.casono.client.game.GameState;
import ch.unibas.dmi.dbis.cs108.casono.client.game.Player;
import java.util.ArrayList;
import java.util.List;
/**
* The GameClient class is responsible for communicating with the server to
* retrieve the current game state. It sends a command to the server and
* parses the response into a structured GameState object.
*/
public class GameClient {
private final ClientService client;
/**
* Constructs a GameClient with the given ClientService for communication.
*
* @param client The ClientService instance used to send commands and receive
* responses from the server.
*/
public GameClient(ClientService client) {
this.client = client;
}
/**
* Retrieves the current game state from the server by sending a command and
* parsing the response.
*
* @return A GameState object representing the current state of the game.
*/
public GameState getGameState() {
String response = client.processCommand("GET_GAME_STATE");
return parseGameState(response);
}
/**
* Parses the raw response from the server into a structured GameState object.
*
* @param input The raw response string from the server.
* @return A GameState object representing the current state of the game.
*/
private GameState parseGameState(String input) {
GameState state = new GameState();
String[] lines = input.split("\n");
Player currentPlayer = null;
Card currentCard = null;
for (String rawLine : lines) {
String line = rawLine.trim();
if (line.startsWith("+OK") || line.equals("END")) {
continue;
}
if (line.startsWith("PHASE=")) {
state.phase = line.split("=")[1];
}
else if (line.startsWith("POT=")) {
state.pot = Integer.parseInt(line.split("=")[1]);
}
else if (line.startsWith("CURRENT_BET=")) {
state.currentBet = Integer.parseInt(line.split("=")[1]);
}
else if (line.startsWith("DEALER=")) {
state.dealer = Integer.parseInt(line.split("=")[1]);
}
else if (line.startsWith("ACTIVE_PLAYER=")) {
state.activePlayer = Integer.parseInt(line.split("=")[1]);
}
else if (line.startsWith("PLAYER")) {
currentPlayer = new Player();
state.players.add(currentPlayer);
}
else if (line.startsWith("NAME=") && currentPlayer != null) {
currentPlayer.name = line.split("=")[1];
}
else if (line.startsWith("CHIPS=") && currentPlayer != null) {
currentPlayer.chips = Integer.parseInt(line.split("=")[1]);
}
else if (line.startsWith("BET=") && currentPlayer != null) {
currentPlayer.bet = Integer.parseInt(line.split("=")[1]);
}
else if (line.startsWith("STATE=") && currentPlayer != null) {
currentPlayer.state = line.split("=")[1];
}
else if (line.startsWith("CARD")) {
currentCard = new Card();
if (currentPlayer != null) {
currentPlayer.cards.add(currentCard);
} else {
state.communityCards.add(currentCard);
}
}
else if (line.startsWith("VALUE=") && currentCard != null) {
currentCard.value = line.split("=")[1];
}
else if (line.startsWith("SUIT=") && currentCard != null) {
currentCard.suit = line.split("=")[1];
}
}
return state;
}
}
@@ -0,0 +1,77 @@
package ch.unibas.dmi.dbis.cs108.casono.client.network;
/**
* The LobbyClient class is responsible for communicating with the server to
* manage game lobbies. It provides methods to create a lobby, join a lobby,
* and fetch the current status of a lobby by sending appropriate commands to
* the server and processing the responses.
*/
public class LobbyClient {
private final ClientService client;
/**
* Constructs a LobbyClient with the given ClientService for communication.
*
* @param client The ClientService instance used to send commands and receive
* responses from the server.
*/
public LobbyClient(ClientService client) {
this.client = client;
}
public ClientService getClientService() {
return client;
}
/**
* Fetch the current status of the lobby with the given id from the server.
*
* @param lobbyId The id of the lobby to fetch the status for.
* @return A string representing the current status of the lobby, as returned
* by the server.
*/
public String fetchLobbyStatusString(int lobbyId) {
return client.processCommand("GET_LOBBY_STATUS ID=" + lobbyId);
}
/**
* Request the server to create a new lobby and return the id of the newly
* created lobby.
*
* @return The id of the newly created lobby, as returned by the server.
*/
public int createLobby() {
String response = client.processCommand("CREATE_LOBBY");
return Integer.parseInt(response);
}
/**
* Request the server to return the id of the lobby that the client is
* currently in.
*
* @return The id of the lobby that the client is currently in, as returned by
* the server.
*/
public int getLobbyId() {
String response = client.processCommand("GET_LOBBY_ID");
return Integer.parseInt(response);
}
/**
* Request the server to join the lobby with the given id.
*
* @param lobbyId The id of the lobby to join.
*/
public void joinLobby(int lobbyId) {
client.processCommand("JOIN_LOBBY ID=" + lobbyId);
}
/**
* Logs in to the server with the given username by sending a "LOGIN" command.
*
* @param user The username to log in with.
*/
public void login(String user) {
client.processCommand("LOGIN USERNAME=" + user);
}
}
@@ -1,90 +0,0 @@
package ch.unibas.dmi.dbis.cs108.casono.client.ui.chatui;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
/**
* Controller-Klasse für das Chat-System innerhalb der Spieloberfläche.
*
* <p>Verwaltet das Anzeigen von Chatnachrichten, das Eingabefeld für eigene Nachrichten sowie den
* Senden-Button. Unterstützt drei Arten von Nachrichten: - Player-to-Player (Privat) - Lobby-Chat
* (Raum) - Globaler Chat (Serverweit)
*
* <p>Nachrichten werden in einem {@link VBox}-Container als {@link Label} angezeigt. Eigene
* Nachrichten werden über {@link #onSendToNetwork(String)} an das Netzwerkprotokoll weitergeleitet,
* während eingehende Nachrichten über {@link #receiveMessage(String, String)} verarbeitet und
* angezeigt werden.
*
* <p>Hinweis: Einige TODOs stehen in der zugehörigen FXML-Datei
*/
public class ChatController {
@FXML private VBox chatVBox;
@FXML private TextField inputField;
@FXML private Button sendButton;
@FXML private ScrollPane chatScrollPane;
private static final int CHAT_PADDING = 20;
/** Initialisiert den ChatController nach dem Laden der FXML. */
public void initialize() {
inputField.setOnAction(event -> sendMessage());
chatScrollPane.vvalueProperty().bind(chatVBox.heightProperty());
}
/** Standardkonstruktor. Wird von FXML verwendet. */
public ChatController() {
// default constructor for FXML
}
/**
* Diese Methode wird vom Senden-Button oder Enter ausgelöst. Sie gibt die eigene Nachricht an
* das Netzwerkprotokoll weiter.
*/
@FXML
private void sendMessage() {
String message = inputField.getText().trim();
if (!message.isEmpty()) {
inputField.clear();
// Hier wird die eigene Nachricht ans Netzwerkprotokoll übergeben
onSendToNetwork(message);
}
}
/**
* Diese Funktion muss vom Netzwerkprotokoll aufgerufen werden, wenn eine neue Nachricht von
* einem anderen Spieler kommt.
*
* @param player Name des Spielers
* @param message Nachricht des Spielers
*/
public void receiveMessage(String player, String message) {
String time = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm"));
Label label = new Label("[" + time + "] " + player + ": " + message);
label.getStyleClass().add("info-text");
label.setWrapText(true); // Zeilenumbruch aktivieren
label.maxWidthProperty().bind(chatVBox.widthProperty().subtract(CHAT_PADDING));
chatVBox.getChildren().add(label);
}
/**
* Schnittstelle zum Netzwerkprotokoll. Diese Funktion wird automatisch aufgerufen, wenn der
* Benutzer eine eigene Nachricht sendet.
*
* @param message Nachricht, die der Benutzer abgeschickt hat
*/
public void onSendToNetwork(String message) {
// TODO: Netzwerkcode einfügen
receiveMessage("Du", message);
}
}
@@ -0,0 +1,107 @@
package ch.unibas.dmi.dbis.cs108.casono.client.ui.chatui;
import ch.unibas.dmi.dbis.cs108.casono.client.chat.ChatController;
import ch.unibas.dmi.dbis.cs108.casono.client.chat.ChatModel;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import java.util.Timer;
import java.util.TimerTask;
/**
* Responsible for the presentation of the ChatModel to the Client
*/
public class ChatViewController {
private final ChatModel chatmodel;
private final String username;
private final ChatController controller;
private final Timer timer;
@FXML
private VBox chatVBox;
@FXML
private TextField inputField;
@FXML
private ScrollPane chatScrollPane;
@FXML
private Button sendButton;
@FXML
private Button refreshButton;
private static final int CHAT_PADDING = 20;
public ChatViewController() {
this.username = null;
this.chatmodel = null;
this.controller = null;
this.timer = new Timer();
}
public ChatViewController(String username, ChatModel chatmodel, ChatController controller) {
this.username = username;
this.chatmodel = chatmodel;
this.controller = controller;
this.timer = new Timer();
if (this.controller != null) {
timer.schedule(new TimerTask() {
@Override
public void run() {
System.err.println("tick");
if (ChatViewController.this.controller.receiveMessage()) {
showMessage();
}
}
}, 0, 1000);
}
}
@FXML
public void initialize() {
if (inputField != null) {
inputField.setOnAction(event -> sendMessage());
}
if (sendButton != null) {
sendButton.setOnAction(event -> sendMessage());
}
if (refreshButton != null) {
refreshButton.setOnAction(event -> showMessage());
}
if (chatScrollPane != null && chatVBox != null) {
chatScrollPane.vvalueProperty().bind(chatVBox.heightProperty());
}
}
public void showMessage() {
while (chatmodel.count > 0) {
String msg = chatmodel.viewNextMessage();
Label label = new Label(msg);
label.getStyleClass().add("info-text");
label.setWrapText(true);
label.maxWidthProperty().bind(chatVBox.widthProperty().subtract(CHAT_PADDING));
chatVBox.getChildren().add(label);
}
}
public void sendMessage() {
String message = inputField.getText().trim();
if (!message.isEmpty()) {
inputField.clear();
this.controller.sendMessage(message, username);
}
}
public void endController() {
timer.cancel();
}
}
@@ -1,3 +1,4 @@
package ch.unibas.dmi.dbis.cs108.casono.client.ui.gameui; package ch.unibas.dmi.dbis.cs108.casono.client.ui.gameui;
import java.io.IOException; import java.io.IOException;
@@ -7,17 +8,32 @@ import javafx.scene.Scene;
import javafx.stage.Stage; import javafx.stage.Stage;
/** /**
* Hauptklasse für das Casino-Spiel-UI. * Main class for the casino game UI.
* *
* <p>Startet die JavaFX-Anwendung, lädt die grafische Oberfläche aus der FXML-Datei und * <p>Starts the JavaFX application, loads the graphical interface from the FXML file,
* initialisiert die Haupt-Stage für das Spiel. * and initializes the main stage for the game.
* *
* <p>Aufgaben: - Lädt die FXML-Oberfläche "/ui-structure/Casinogameui.fxml". - Lädt das * <p>Responsibilities:
* Anwendungs-Icon aus "/images/logoinverted.png". - Startet die Anwendung im Vollbildmodus. * - Loads the FXML interface "/ui-structure/Casinogameui.fxml".
* - Loads the application icon from "/images/logoinverted.png".
* - Starts the application in fullscreen mode.
*/ */
import ch.unibas.dmi.dbis.cs108.casono.client.network.ClientService;
public class CasinoGameUI extends Application { public class CasinoGameUI extends Application {
/** Standardkonstruktor. */ // Static field for ClientService (workaround for JavaFX Application launch)
private static ClientService staticClientService;
public static void setClientService(ClientService clientService) {
staticClientService = clientService;
}
public static ClientService getClientService() {
return staticClientService;
}
/** Default no-arg constructor. */
public CasinoGameUI() { public CasinoGameUI() {
// default no-arg constructor // default no-arg constructor
} }
@@ -26,15 +42,14 @@ public class CasinoGameUI extends Application {
private static final int DEFAULT_HEIGHT = 800; private static final int DEFAULT_HEIGHT = 800;
/** /**
* Startet die Haupt-Stage der Anwendung. * Starts the main stage of the application.
* *
* @param stage Die vom System bereitgestellte Haupt-Stage. * @param stage The main stage provided by the system.
* @throws IOException Wenn die FXML-Datei oder Ressourcen nicht geladen werden können. * @throws IOException If the FXML file or resources cannot be loaded.
*/ */
@Override @Override
public void start(Stage stage) throws IOException { public void start(Stage stage) throws IOException {
FXMLLoader fxmlLoader = FXMLLoader fxmlLoader = new FXMLLoader(CasinoGameUI.class.getResource("/ui-structure/Casinogameui.fxml"));
new FXMLLoader(CasinoGameUI.class.getResource("/ui-structure/Casinogameui.fxml"));
Scene scene = new Scene(fxmlLoader.load(), DEFAULT_WIDTH, DEFAULT_HEIGHT); Scene scene = new Scene(fxmlLoader.load(), DEFAULT_WIDTH, DEFAULT_HEIGHT);
stage.setTitle("Casono (GAME)"); stage.setTitle("Casono (GAME)");
@@ -46,9 +61,9 @@ public class CasinoGameUI extends Application {
} }
/** /**
* Startpunkt der Anwendung. * Entry point of the application.
* *
* @param args Befehlszeilenargumente. * @param args Command line arguments.
*/ */
public static void main(String[] args) { public static void main(String[] args) {
launch(); launch();
@@ -30,13 +30,22 @@ public class Casinomainui extends Application {
* @throws IOException If loading the FXML fails. * @throws IOException If loading the FXML fails.
*/ */
public void start(Stage stage) throws IOException { public void start(Stage stage) throws IOException {
FXMLLoader fxmlLoader = // If the launcher passed an address argument (ip:port), expose it as
new FXMLLoader(getClass().getResource("/ui-structure/Casinomainui.fxml")); // system properties so controllers can read it without embedding defaults.
var raw = getParameters().getRaw();
if (raw != null && raw.size() > 0) {
String arg = raw.get(0);
String[] parts = arg.split(":", 2);
if (parts.length == 2) {
System.setProperty("casono.server.host", parts[0]);
System.setProperty("casono.server.port", parts[1]);
}
}
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/ui-structure/Casinomainui.fxml"));
Scene scene = new Scene(fxmlLoader.load(), SCENE_WIDTH, SCENE_HEIGHT); Scene scene = new Scene(fxmlLoader.load(), SCENE_WIDTH, SCENE_HEIGHT);
stage.setTitle("Casono"); stage.setTitle("Casono");
javafx.scene.image.Image icon = javafx.scene.image.Image icon = new javafx.scene.image.Image(
new javafx.scene.image.Image( getClass().getResource("/images/logoinverted.png").toExternalForm());
getClass().getResource("/images/logoinverted.png").toExternalForm());
stage.getIcons().add(icon); stage.getIcons().add(icon);
stage.setScene(scene); stage.setScene(scene);
stage.setFullScreen(true); stage.setFullScreen(true);
@@ -3,6 +3,9 @@ package ch.unibas.dmi.dbis.cs108.casono.client.ui.lobbyui;
import javafx.application.Platform; import javafx.application.Platform;
import javafx.fxml.FXML; import javafx.fxml.FXML;
import javafx.scene.control.Button; import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Label; import javafx.scene.control.Label;
import javafx.scene.image.Image; import javafx.scene.image.Image;
import javafx.scene.image.ImageView; import javafx.scene.image.ImageView;
@@ -11,22 +14,39 @@ import javafx.scene.layout.VBox;
import javafx.scene.shape.Rectangle; import javafx.scene.shape.Rectangle;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import ch.unibas.dmi.dbis.cs108.casono.client.network.ClientService;
import ch.unibas.dmi.dbis.cs108.casono.client.network.LobbyClient;
/** Controller for the Casono main UI lobby. Handles UI initialization and user actions. */ /**
* Controller for the Casono main UI lobby. Handles UI initialization and user
* actions.
*/
public class CasinomainuiController { public class CasinomainuiController {
private static final Logger LOGGER = LogManager.getLogger(CasinomainuiController.class); private static final Logger LOGGER = LogManager.getLogger(CasinomainuiController.class);
@FXML private AnchorPane rootPane; @FXML
@FXML private Label titleLabel; private AnchorPane rootPane;
@FXML private Label subtitleLabel; @FXML
@FXML private ImageView logoView; private Label titleLabel;
@FXML private Rectangle greenBox; @FXML
@FXML private Button exitbutton; private Label subtitleLabel;
@FXML private VBox casinoTable; @FXML
private ImageView logoView;
@FXML
private Rectangle greenBox;
@FXML
private Button exitbutton;
@FXML
private VBox casinoTable;
@FXML
private TextField usernameField;
@FXML
private Button loginButton;
private LobbyButtonTranslationManager translationManager; private LobbyButtonTranslationManager translationManager;
private LobbyButtonGridManager gridManager; private LobbyButtonGridManager gridManager;
private int nextButtonId = 1; private int nextButtonId = 1;
private LobbyClient lobbyClient;
/** Default constructor for dependency injection by FXMLLoader. */ /** Default constructor for dependency injection by FXMLLoader. */
public CasinomainuiController() { public CasinomainuiController() {
@@ -41,8 +61,62 @@ public class CasinomainuiController {
logoView.setImage(new Image(getClass().getResource("/images/logo.png").toExternalForm())); logoView.setImage(new Image(getClass().getResource("/images/logo.png").toExternalForm()));
translationManager = LobbyButtonTranslationManager.getInstance(); translationManager = LobbyButtonTranslationManager.getInstance();
gridManager = String host = System.getProperty("casono.server.host");
new LobbyButtonGridManager(new javafx.scene.layout.GridPane(), translationManager); int port = Integer.parseInt(System.getProperty("casono.server.port"));
ClientService clientService;
try {
clientService = new ClientService(host, port);
} catch (RuntimeException e) {
LOGGER.warn("Could not connect to server {}:{} — starting in offline mode: {}", host, port, e.getMessage());
clientService = new ClientService(true); // offline mode
}
gridManager = new LobbyButtonGridManager(new javafx.scene.layout.GridPane(), translationManager, clientService);
// LobbyClient will use the provided ClientService; in offline mode calls will
// fail with RuntimeException
lobbyClient = new LobbyClient(clientService);
casinoTable.getChildren().clear();
casinoTable.getChildren().add(gridManager.getGridPane());
gridManager.renderLobbyButtons();
}
/**
* Handles the login button action. Validates input and calls
* LobbyClient.login().
*/
@FXML
public void handleLoginButton() {
String username = usernameField.getText();
if (username == null || username.isBlank()) {
showAlert("Please enter a username.");
return;
}
// Only allow alphanumeric, _ and -
if (!username.matches("[a-zA-Z0-9_-]+")) {
showAlert("Only letters, numbers, '_' and '-' are allowed!");
return;
}
if (lobbyClient.getClientService().isOffline()) {
showAlert("Offline mode: cannot send login to server.");
return;
}
try {
lobbyClient.login(username);
showAlert("Login sent: " + username);
} catch (RuntimeException e) {
LOGGER.error("Login failed: {}", e.getMessage());
showAlert("Login failed: " + e.getMessage());
}
}
/**
* Shows an alert dialog with the given message.
*/
private void showAlert(String message) {
Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle("Info");
alert.setHeaderText(null);
alert.setContentText(message);
alert.showAndWait();
casinoTable.getChildren().clear(); casinoTable.getChildren().clear();
casinoTable.getChildren().add(gridManager.getGridPane()); casinoTable.getChildren().add(gridManager.getGridPane());
gridManager.renderLobbyButtons(); gridManager.renderLobbyButtons();
@@ -62,13 +136,21 @@ public class CasinomainuiController {
return; return;
} }
int buttonId = nextButtonId++; int buttonId = nextButtonId++;
int lobbyId = gridManager.createLobby();
try { try {
String username = usernameField != null ? usernameField.getText() : "<unknown>";
LOGGER.info("Creating lobby for user: {}", username);
// avoid attempting to create a lobby when offline
if (lobbyClient.getClientService().isOffline()) {
LOGGER.warn("Cannot create lobby while offline");
showAlert("Offline mode: cannot create lobby.");
return;
}
int lobbyId = gridManager.createLobby();
translationManager.addLobbyButton(buttonId, lobbyId); translationManager.addLobbyButton(buttonId, lobbyId);
LOGGER.info("ButtonID: {}, LobbyID: {}", buttonId, lobbyId); LOGGER.info("ButtonID: {}, LobbyID: {}", buttonId, lobbyId);
gridManager.renderLobbyButtons(); gridManager.renderLobbyButtons();
} catch (Exception e) { } catch (Exception e) {
LOGGER.error("Error while adding lobby button: {}", e.getMessage()); LOGGER.error("Failed to create or add lobby: {}", e.getMessage());
} }
} }
} }
@@ -5,6 +5,18 @@ package ch.unibas.dmi.dbis.cs108.casono.client.ui.lobbyui;
* ButtonID to LobbyID. * ButtonID to LobbyID.
*/ */
import java.util.Map; import java.util.Map;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import ch.unibas.dmi.dbis.cs108.casono.client.network.LobbyClient;
import ch.unibas.dmi.dbis.cs108.casono.client.network.ClientService;
import javafx.scene.Node;
import javafx.scene.control.Button; import javafx.scene.control.Button;
import javafx.scene.image.Image; import javafx.scene.image.Image;
import javafx.scene.image.ImageView; import javafx.scene.image.ImageView;
@@ -13,7 +25,8 @@ import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
/** /**
* Manages the grid for lobby buttons and rendering. Uses LobbyButtonTranslationManager for mapping * Manages the grid for lobby buttons and rendering. Uses
* LobbyButtonTranslationManager for mapping
* ButtonID to LobbyID. * ButtonID to LobbyID.
*/ */
public class LobbyButtonGridManager { public class LobbyButtonGridManager {
@@ -27,54 +40,128 @@ public class LobbyButtonGridManager {
/** Manager for mapping ButtonID to LobbyID. */ /** Manager for mapping ButtonID to LobbyID. */
private final LobbyButtonTranslationManager translationManager; private final LobbyButtonTranslationManager translationManager;
/** Number of rows in the grid. */
private static final int ROWS = 2;
/** Number of columns in the grid. */ /** Number of columns in the grid. */
private static final int COLS = 4; private static final int COLS = 4;
/** Path to the button image. */ /** Image for a lobby in CREATED state. */
private static final String BUTTON_IMAGE_PATH = "/images/logo.png"; /** Default fallback image. */
private static final String BUTTON_FALLBACK_IMAGE = "/images/lobbypictures/error.png";
/** Max random lobby id. */ /**
private static final int MAX_RANDOM_LOBBY_ID = 10000; * Template for per-button images. Use: button index and status
* (created|running). Example:
* /images/lobby_1_created.png
*/
private static final String BUTTON_IMAGE_TEMPLATE = "/images/lobbypictures/lobby_%d_%s.png";
/** Cache for loaded Images keyed by resource path. */
private final ConcurrentHashMap<String, Image> imageCache = new ConcurrentHashMap<>();
private final LobbyClient lobbyClient;
/** Executor for background status/network tasks. */
private final ExecutorService executor = Executors.newCachedThreadPool();
/** Scheduler for periodic refresh of lobby mappings. */
private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
/** /**
* Constructor for the GridManager. * Constructor for the GridManager.
* *
* @param gridPane the GridPane for rendering * @param gridPane the GridPane for rendering
* @param translationManager the manager for mapping ButtonID to LobbyID * @param translationManager the manager for mapping ButtonID to LobbyID
*/ */
public LobbyButtonGridManager( public LobbyButtonGridManager(
GridPane gridPane, LobbyButtonTranslationManager translationManager) { GridPane gridPane, LobbyButtonTranslationManager translationManager, LobbyClient lobbyClient) {
this.gridPane = gridPane; this.gridPane = gridPane;
// Singleton immer verwenden // Always use the singleton
this.translationManager = LobbyButtonTranslationManager.getInstance(); this.translationManager = LobbyButtonTranslationManager.getInstance();
this.lobbyClient = lobbyClient;
// Start periodic refresh to keep mapping in sync with server
startPeriodicRefresh(5, 5);
} }
/** /**
* Renders all lobby buttons in the grid. Creates a button for each mapping with image and event * Convenience constructor: accept a {@link ClientService} and build a
* {@link LobbyClient} from it. This avoids any host/port System.getProperty
* lookups elsewhere — caller controls the ClientService.
*/
public LobbyButtonGridManager(
GridPane gridPane, LobbyButtonTranslationManager translationManager, ClientService clientService) {
this(gridPane, translationManager, new LobbyClient(clientService));
}
/**
* Start periodic refresh of lobby mappings.
*
* @param initialDelay initial delay in seconds
* @param period period in seconds
*/
private void startPeriodicRefresh(long initialDelay, long period) {
scheduler.scheduleAtFixedRate(this::refreshMappings, initialDelay, period, TimeUnit.SECONDS);
}
/**
* Refresh mappings by checking each stored lobby id on the server. If a lobby
* no longer exists (or an error occurs), remove it from the translation map
* and update the UI.
*/
private void refreshMappings() {
Map<Integer, Integer> mapping = translationManager.getButtonIdToLobbyId();
if (mapping.isEmpty()) {
return;
}
// Make a copy of entries to avoid concurrent modification
List<Map.Entry<Integer, Integer>> entries = new ArrayList<>(mapping.entrySet());
for (Map.Entry<Integer, Integer> e : entries) {
int buttonId = e.getKey();
int lobbyId = e.getValue();
CompletableFuture.supplyAsync(() -> {
try {
String status = lobbyClient.fetchLobbyStatusString(lobbyId);
return status;
} catch (Exception ex) {
LOGGER.info("Lobby {} appears missing or error: {}", lobbyId, ex.getMessage());
return null;
}
}, executor).thenAccept(status -> {
if (status == null) {
// remove mapping and update UI
translationManager.removeLobbyButton(buttonId);
javafx.application.Platform.runLater(() -> {
updateLobbyButtonImages();
});
}
});
}
}
// Default client creation removed to avoid implicit IP/port configuration.
// Applications must construct and provide a LobbyClient or ClientService
// explicitly.
/**
* Renders all lobby buttons in the grid. Creates a button for each mapping with
* image and event
* handler. * handler.
*/ */
public void renderLobbyButtons() { public void renderLobbyButtons() {
gridPane.getChildren().clear(); gridPane.getChildren().clear();
int index = 0;
Map<Integer, Integer> mapping = translationManager.getButtonIdToLobbyId(); Map<Integer, Integer> mapping = translationManager.getButtonIdToLobbyId();
if (mapping.isEmpty()) { if (mapping.isEmpty()) {
// No buttons to render
return; return;
} }
for (Map.Entry<Integer, Integer> entry : mapping.entrySet()) { List<Integer> buttonIds = new ArrayList<>(mapping.keySet());
int buttonId = entry.getKey(); Collections.sort(buttonIds);
int index = 0;
for (Integer buttonId : buttonIds) {
int lobbyId = mapping.get(buttonId);
Button btn = new Button(); Button btn = new Button();
btn.setId("lobbyBtn-" + buttonId); btn.setId("lobbyBtn-" + buttonId);
ImageView imageView = // placeholder image so UI remains responsive
new ImageView(new Image(getClass().getResourceAsStream(BUTTON_IMAGE_PATH))); Image placeholder = safeLoadImage(BUTTON_FALLBACK_IMAGE);
ImageView imageView = new ImageView(placeholder);
imageView.setPreserveRatio(true); imageView.setPreserveRatio(true);
// Dynamische Breite: Bindung an die Zellengröße imageView.fitWidthProperty().bind(gridPane.widthProperty().divide(COLS).subtract(BUTTON_WIDTH_MARGIN));
imageView
.fitWidthProperty()
.bind(gridPane.widthProperty().divide(COLS).subtract(BUTTON_WIDTH_MARGIN));
imageView.setSmooth(true); imageView.setSmooth(true);
btn.setGraphic(imageView); btn.setGraphic(imageView);
btn.setMaxWidth(Double.MAX_VALUE); btn.setMaxWidth(Double.MAX_VALUE);
@@ -83,12 +170,27 @@ public class LobbyButtonGridManager {
btn.setMinHeight(BUTTON_MIN_SIZE); btn.setMinHeight(BUTTON_MIN_SIZE);
GridPane.setHgrow(btn, javafx.scene.layout.Priority.ALWAYS); GridPane.setHgrow(btn, javafx.scene.layout.Priority.ALWAYS);
GridPane.setVgrow(btn, javafx.scene.layout.Priority.ALWAYS); GridPane.setVgrow(btn, javafx.scene.layout.Priority.ALWAYS);
btn.setOnAction( final int bId = buttonId;
e -> { btn.setOnAction(e -> {
Integer lobbyId = translationManager.getLobbyIdForButton(buttonId); Integer targetLobbyId = translationManager.getLobbyIdForButton(bId);
if (lobbyId != null) { if (targetLobbyId != null) {
joinLobby(lobbyId); joinLobby(targetLobbyId);
} }
});
// async fetch status and update image
CompletableFuture.supplyAsync(() -> lobbyClient.fetchLobbyStatusString(lobbyId), executor)
.thenAccept(statusStr -> {
LobbyStatus status = parseLobbyStatus(statusStr);
String path = getImagePathForButton(buttonId, status == null ? LobbyStatus.CREATED : status);
Image img = safeLoadImage(path);
javafx.application.Platform.runLater(() -> {
ImageView iv = new ImageView(img);
iv.setPreserveRatio(true);
iv.fitWidthProperty()
.bind(gridPane.widthProperty().divide(COLS).subtract(BUTTON_WIDTH_MARGIN));
iv.setSmooth(true);
btn.setGraphic(iv);
});
}); });
int row = index / COLS; int row = index / COLS;
int col = index % COLS; int col = index % COLS;
@@ -97,16 +199,138 @@ public class LobbyButtonGridManager {
} }
} }
/** Possible lobby statuses. */
private enum LobbyStatus {
CREATED,
RUNNING
}
/** /**
* Placeholder for lobby creation logic. Returns a generated lobbyId. * Return the current status of a lobby.
*
* @param lobbyId the lobby id to query
* @return the lobby status (mapped from server string; CREATED or RUNNING)
*/
public LobbyStatus getLobbyStatus(int lobbyId) {
String serverStatus = lobbyClient.fetchLobbyStatusString(lobbyId);
LobbyStatus parsed = parseLobbyStatus(serverStatus);
if (parsed == null) {
// Defensive fallback
LOGGER.error("Unrecognized lobby status '{}' for lobby {}. Defaulting to CREATED.", serverStatus, lobbyId);
return LobbyStatus.CREATED;
}
return parsed;
}
/**
* Parse a status string returned by the server into the local enum.
* Accepts case-insensitive values like "created" / "CREATED" / "running".
* Returns null if the string is not recognized.
*/
private LobbyStatus parseLobbyStatus(String statusStr) {
if (statusStr == null)
return null;
try {
return LobbyStatus.valueOf(statusStr.trim().toUpperCase());
} catch (IllegalArgumentException e) {
return null;
}
}
private String getImagePathForButton(int buttonId, LobbyStatus status) {
String statusStr = status == LobbyStatus.CREATED ? "created" : "running";
return String.format(BUTTON_IMAGE_TEMPLATE, buttonId, statusStr);
}
private Image safeLoadImage(String path) {
// Return cached image if present
Image cached = imageCache.get(path);
if (cached != null) {
return cached;
}
// Attempt to load the requested resource
java.io.InputStream is = getClass().getResourceAsStream(path);
if (is == null) {
LOGGER.debug(
"Image resource not found: {}. Falling back to {}",
path,
BUTTON_FALLBACK_IMAGE);
is = getClass().getResourceAsStream(BUTTON_FALLBACK_IMAGE);
}
Image loaded = null;
try {
if (is != null) {
loaded = new Image(is);
} else {
LOGGER.error(
"Both requested image '{}' and fallback '{}' are missing. No image will be set.",
path,
BUTTON_FALLBACK_IMAGE);
}
} catch (Exception e) {
LOGGER.error("Failed to load image '{}'", path, e);
}
if (loaded == null) {
// leave
// null
}
if (loaded != null) {
imageCache.put(path, loaded);
}
return loaded;
}
/** Update all lobby buttons' images according to the current lobby statuses. */
public void updateLobbyButtonImages() {
Map<Integer, Integer> mapping = translationManager.getButtonIdToLobbyId();
if (mapping.isEmpty()) {
return;
}
List<Integer> buttonIds = new ArrayList<>(mapping.keySet());
Collections.sort(buttonIds);
for (Integer buttonId : buttonIds) {
int lobbyId = mapping.get(buttonId);
CompletableFuture.supplyAsync(() -> getLobbyStatus(lobbyId), executor)
.thenAccept(status -> {
String path = getImagePathForButton(buttonId, status);
javafx.application.Platform.runLater(() -> {
for (Node node : gridPane.getChildren()) {
if (node instanceof Button && ("lobbyBtn-" + buttonId).equals(node.getId())) {
Button btn = (Button) node;
ImageView iv = new ImageView(safeLoadImage(path));
iv.setPreserveRatio(true);
iv.fitWidthProperty()
.bind(
gridPane.widthProperty()
.divide(COLS)
.subtract(BUTTON_WIDTH_MARGIN));
iv.setSmooth(true);
btn.setGraphic(iv);
break;
}
}
});
});
}
}
/**
* Creates a new lobby via the LobbyClient.
* *
* @return The generated lobbyId * @return The generated lobbyId
*/ */
public int createLobby() { public int createLobby() {
// TODO: Replace with actual lobby creation logic try {
int lobbyId = (int) (Math.random() * MAX_RANDOM_LOBBY_ID + 1); int lobbyId = lobbyClient.createLobby();
LOGGER.info("Lobby created: {}", lobbyId); LOGGER.info("Lobby created via LobbyClient: {}", lobbyId);
return lobbyId; if (lobbyId <= 0) {
throw new RuntimeException("LobbyClient returned invalid lobby id: " + lobbyId);
}
return lobbyId;
} catch (Exception e) {
LOGGER.error("Failed to create lobby via LobbyClient: {}", e.getMessage());
throw new RuntimeException("Failed to create lobby", e);
}
} }
/** /**
@@ -115,20 +339,45 @@ public class LobbyButtonGridManager {
* @param lobbyId The lobbyId to join * @param lobbyId The lobbyId to join
*/ */
public void joinLobby(int lobbyId) { public void joinLobby(int lobbyId) {
// Game-UI starten und Lobby-UI schließen // Request server to join the lobby (blackbox client may throw on failure)
LOGGER.info("Joining lobby: {}", lobbyId); LOGGER.info("Joining lobby: {}", lobbyId);
try {
lobbyClient.joinLobby(lobbyId);
} catch (Exception e) {
LOGGER.error("LobbyClient failed to join lobby {}: {}", lobbyId, e.getMessage());
return;
}
javafx.application.Platform.runLater( javafx.application.Platform.runLater(
() -> { () -> {
// Lobby-Stage schließen // Hide lobby stage (do not close) so we can return later
javafx.stage.Stage currentStage = javafx.scene.Scene scene = gridPane.getScene();
(javafx.stage.Stage) gridPane.getScene().getWindow(); javafx.stage.Stage currentStage = (javafx.stage.Stage) scene.getWindow();
currentStage.close(); currentStage.hide();
// Game-UI starten // Prepare game stage and set a handler so that when it is closed the lobby is
// shown and updated
javafx.stage.Stage gameStage = new javafx.stage.Stage();
gameStage.setOnHidden(
ev -> {
try {
currentStage.show();
// refresh mappings immediately when returning from game
refreshMappings();
updateLobbyButtonImages();
} catch (Exception ex) {
LOGGER.error(
"Error while returning to lobby: {}", ex.getMessage());
}
});
// Start the Game UI using the prepared stage
try { try {
new ch.unibas.dmi.dbis.cs108.casono.client.ui.gameui.CasinoGameUI() // ClientService an GameUI übergeben
.start(new javafx.stage.Stage()); ch.unibas.dmi.dbis.cs108.casono.client.ui.gameui.CasinoGameUI
.setClientService(lobbyClient.getClientService());
new ch.unibas.dmi.dbis.cs108.casono.client.ui.gameui.CasinoGameUI().start(gameStage);
} catch (Exception e) { } catch (Exception e) {
LOGGER.error("Fehler beim Starten der Game-UI: {}", e.getMessage()); LOGGER.error("Error starting Game UI: {}", e.getMessage());
// If starting fails, show the lobby again
currentStage.show();
} }
}); });
} }
@@ -141,4 +390,21 @@ public class LobbyButtonGridManager {
public javafx.scene.layout.GridPane getGridPane() { public javafx.scene.layout.GridPane getGridPane() {
return gridPane; return gridPane;
} }
/**
* Expose the configured LobbyClient so callers can invoke its methods
* directly (createLobby, fetchLobbyStatusString, joinLobby, ...).
*/
public LobbyClient getLobbyClient() {
return lobbyClient;
}
/**
* Trigger an immediate refresh of mappings (poll server and remove missing
* lobbies). Public so callers can force a refresh when UI focus returns.
*/
public void refreshNow() {
refreshMappings();
}
} }
@@ -81,6 +81,23 @@
</GridPane.margin> </GridPane.margin>
</Button> </Button>
<!-- Username input and login button -->
<HBox alignment="CENTER_LEFT" spacing="10"
GridPane.rowIndex="0"
GridPane.columnIndex="0"
GridPane.halignment="LEFT"
GridPane.valignment="TOP">
<GridPane.margin>
<!-- place below the 'Lobby erstellen' button -->
<Insets top="100" left="20" />
</GridPane.margin>
<TextField fx:id="usernameField" promptText="Benutzername" maxWidth="180" />
<Button text="Login"
fx:id="loginButton"
onAction="#handleLoginButton"
styleClass="button-create-lobby" />
</HBox>
<VBox fx:id="casinoTable" <VBox fx:id="casinoTable"
alignment="CENTER" alignment="CENTER"
styleClass="casino-table" styleClass="casino-table"
@@ -19,7 +19,7 @@
<VBox xmlns="http://javafx.com/javafx/21" <VBox xmlns="http://javafx.com/javafx/21"
xmlns:fx="http://javafx.com/fxml/1" xmlns:fx="http://javafx.com/fxml/1"
fx:controller="ch.unibas.dmi.dbis.cs108.casono.client.ui.chatui.ChatController" fx:controller="ch.unibas.dmi.dbis.cs108.casono.client.ui.chatui.ChatViewController"
alignment="CENTER" alignment="CENTER"
stylesheets="@Chatui.css"> stylesheets="@Chatui.css">
@@ -0,0 +1,58 @@
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.geometry.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<!--
Dieses Fenster wird später mit den Serveranfragen verknüpft,
um Nachrichten von Mitspielern und Systemmeldungen in Echtzeit anzuzeigen.
Der Chat unterscheidet intern zwischen:
- Player-to-Player (Privater 2-Personen-Chat)
- Lobby-Chat (Aktueller Raum)
- Globaler Chat (Gesamter Server)
Features, die später implementiert werden sollen:
- Schicke Chat-Bubbles mit Namen und Uhrzeit.
-->
<VBox xmlns="http://javafx.com/javafx/21"
xmlns:fx="http://javafx.com/fxml/1"
fx:controller="ch.unibas.dmi.dbis.cs108.casono.client.ui.chatui.ChatViewController"
alignment="CENTER"
stylesheets="@chatui.css">
<!-- Innenabstand: Schafft oben, rechts und unten 30 Pixel Platz, links nur 10 Pixel (asymmetrisch) -->
<padding>
<Insets top="30" right="30" bottom="30" left="10"/>
</padding>
<children>
<VBox VBox.vgrow="ALWAYS"
styleClass="chat-box"
spacing="10"
maxWidth="Infinity">
<children>
<Label text="== CHAT ==" styleClass="chat-header" alignment="CENTER" maxWidth="Infinity"/>
<Region minHeight="4" styleClass="chat-separator"/>
<!-- Chatnachrichten werden hier hinzugefügt -->
<ScrollPane fx:id="chatScrollPane" fitToWidth="true" vbarPolicy="AS_NEEDED" hbarPolicy="NEVER" VBox.vgrow="ALWAYS" styleClass="chat-scroll-pane">
<content>
<VBox fx:id="chatVBox" spacing="10" styleClass="chat-VBox"/>
</content>
</ScrollPane>
<!-- Eingabebereich -->
<HBox spacing="10">
<!-- TODO: Größe des TextFields dynamisch anpassen -->
<TextField fx:id="inputField" HBox.hgrow="ALWAYS" promptText="Nachricht eingeben..." styleClass="gray-input-field" onAction="#sendMessage"/>
<Button fx:id="sendButton" text="SENDEN" onAction="#sendMessage" styleClass="yellow-button"/>
<Button fx:id="refreshButton" text="NEU" onAction="#showMessage" styleClass="yellow-button"/>
</HBox>
</children>
</VBox>
</children>
</VBox>
@@ -0,0 +1,155 @@
.chat-box {
-fx-background-color: #0d9e3b;
-fx-background-radius: 58;
-fx-border-radius: 50;
-fx-border-color: #5c3d10 #3d260a #3d260a #5c3d10;
-fx-border-width: 12;
-fx-padding: 20;
-fx-effect: dropshadow(one-pass-box, rgba(0,0,0,1), 0, 0, 15, 15);
}
.chat-header {
-fx-text-fill: #ffffff;
-fx-font-size: 22px;
-fx-font-weight: bold;
-fx-padding: 0 0 10 0;
-fx-effect: dropshadow(one-pass-box, #000000, 0, 0, 3, 3);
}
.chat-separator {
-fx-background-color: #ffffff;
-fx-min-height: 4px;
-fx-effect: dropshadow(one-pass-box, #000000, 0, 0, 3, 3);
}
.black-input-field {
-fx-background-color: #1a1a1a;
-fx-text-fill: #ffffff;
-fx-font-family: "Courier New";
-fx-font-weight: bold;
-fx-background-radius: 8;
-fx-border-radius: 8;
-fx-border-color: #444444;
-fx-border-width: 2;
-fx-padding: 5 12;
}
.black-input-field:hover {
-fx-translate-y: -3;
-fx-effect: dropshadow(one-pass-box, rgba(0, 0, 0, 0.8), 0, 0, 3, 3);
}
.black-input-field:focused {
-fx-border-color: #ffffff;
-fx-background-color: #000000;
}
.gray-input-field {
-fx-background-color: #333333;
-fx-text-fill: #ffffff;
-fx-font-family: "Courier New";
-fx-font-weight: bold;
-fx-background-radius: 8;
-fx-border-radius: 8;
-fx-border-color: #666666;
-fx-color-color: #cccccc;
-fx-border-width: 2;
-fx-padding: 5 12;
}
.gray-input-field:hover {
-fx-translate-y: -3;
-fx-effect: dropshadow(one-pass-box, rgba(0, 0, 0, 0.8), 0, 0, 3, 3);
}
.gray-input-field:focused {
-fx-border-color: #ffffff;
-fx-background-color: #333333;
}
.yellow-button {
-fx-background-color: #b8860b;
-fx-border-color: #ffd700;
-fx-text-fill: #ffffff;
}
.red-button {
-fx-background-color: #8b0000;
-fx-border-color: #ff4444;
-fx-text-fill: #ffffff;
}
.gray-button {
-fx-background-color: #333333;
-fx-border-color: #666666;
-fx-text-fill: #cccccc;
}
.gray-button, .yellow-button, .red-button {
-fx-background-radius: 12;
-fx-border-radius: 12;
-fx-font-family: "Courier New";
-fx-font-weight: bold;
-fx-border-width: 2;
-fx-padding: 6 15;
-fx-cursor: hand;
}
.gray-button:hover, .yellow-button:hover, .red-button:hover {
-fx-translate-y: -3;
-fx-effect: dropshadow(one-pass-box, rgba(0, 0, 0, 0.8), 0, 0, 3, 3);
}
.chat-scroll-pane {
-fx-background-color: transparent;
-fx-background: transparent;
-fx-border-color: transparent;
}
.chat-VBox {
-fx-background-color: transparent;
-fx-background: transparent;
}
.scroll-pane {
-fx-background-color: transparent;
-fx-border-color: transparent;
}
.scroll-pane .scroll-bar:vertical {
-fx-background-color: transparent;
}
.scroll-pane .scroll-bar .track {
-fx-background-color: #5c3d10;
-fx-background-insets: 0;
-fx-background-radius: 5;
}
.scroll-pane .scroll-bar .thumb {
-fx-background-color: #3d260a;
-fx-background-insets: 0;
-fx-background-radius: 5;
-fx-pref-width: 6;
-fx-pref-height: 6;
-fx-padding: 0;
}
.scroll-pane .scroll-bar:horizontal {
-fx-background-color: transparent;
}
.scroll-pane .scroll-bar:horizontal .track {
-fx-background-color: #5c3d10;
-fx-background-radius: 5;
}
.scroll-pane .scroll-bar:horizontal .thumb {
-fx-background-color: #3d260a;
-fx-background-radius: 5;
-fx-pref-height: 6;
}
.scroll-pane .scroll-bar:horizontal .thumb:hover {
-fx-pref-height: 10;
}
@@ -0,0 +1,29 @@
package ch.unibas.dmi.dbis.cs108.casono.client.chat;
import ch.unibas.dmi.dbis.cs108.casono.client.network.ClientService;
import ch.unibas.dmi.dbis.cs108.casono.client.ui.gameui.CasinoGameUI;
import ch.unibas.dmi.dbis.cs108.casono.client.ui.lobbyui.Casinomainui;
import ch.unibas.dmi.dbis.cs108.casono.server.ServerApp;
import javafx.application.Application;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class ChatControllerTest {
@BeforeEach
public void setup() {
}
@AfterEach
public void teardown() {
}
/*
* @Test
* public void testChatController() {
* Client client = new Client("user1");
* client.startApplication();
* }
*/
}
@@ -0,0 +1,89 @@
package ch.unibas.dmi.dbis.cs108.casono.client.network;
import ch.unibas.dmi.dbis.cs108.casono.server.network.transport.RawPacket;
import ch.unibas.dmi.dbis.cs108.casono.server.network.transport.TcpTransport;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Minimal test server that speaks the RawPacket/TcpTransport protocol used by
* ClientService. Provides deterministic responses for CREATE_LOBBY and
* GET_LOBBY_STATUS so unit tests can run without a real backend.
*/
public class TestServer implements AutoCloseable {
private final ServerSocket serverSocket;
private final ExecutorService exec = Executors.newSingleThreadExecutor();
private final AtomicInteger nextLobbyId = new AtomicInteger(1);
private final Map<Integer, String> lobbyStatus = new ConcurrentHashMap<>();
private volatile boolean running = true;
public TestServer() throws IOException {
this.serverSocket = new ServerSocket(0);
exec.submit(this::acceptLoop);
}
public int getPort() {
return serverSocket.getLocalPort();
}
private void acceptLoop() {
try (Socket client = serverSocket.accept()) {
TcpTransport transport = new TcpTransport(client);
while (running) {
RawPacket request = transport.read();
String payload = request.payload();
String response = handleRequest(payload);
// send the response payload followed by +OK
transport.write(new RawPacket(request.requestId(), response));
transport.write(new RawPacket(request.requestId(), "+OK"));
}
} catch (IOException e) {
if (running) {
throw new RuntimeException(e);
}
}
}
private String handleRequest(String payload) {
if (payload == null)
return "";
if (payload.startsWith("CREATE_LOBBY")) {
int id = nextLobbyId.getAndIncrement();
lobbyStatus.put(id, "created");
return Integer.toString(id);
}
if (payload.startsWith("GET_LOBBY_STATUS")) {
// payload format: GET_LOBBY_STATUS ID=<id>
String[] parts = payload.split("ID=");
if (parts.length == 2) {
try {
int id = Integer.parseInt(parts[1].trim());
return lobbyStatus.getOrDefault(id, "created");
} catch (NumberFormatException e) {
return "created";
}
}
return "created";
}
if (payload.startsWith("JOIN_LOBBY")) {
// no-op
return "";
}
return "";
}
@Override
public void close() throws Exception {
running = false;
serverSocket.close();
exec.shutdownNow();
}
}
@@ -3,19 +3,32 @@ package ch.unibas.dmi.dbis.cs108.casono.client.ui.lobbyui;
import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.Assertions.*;
import javafx.scene.layout.GridPane; import javafx.scene.layout.GridPane;
import ch.unibas.dmi.dbis.cs108.casono.client.network.ClientService;
import org.junit.jupiter.api.*; import org.junit.jupiter.api.*;
class LobbyButtonGridManagerTest { class LobbyButtonGridManagerTest {
LobbyButtonGridManager gridManager; LobbyButtonGridManager gridManager;
LobbyButtonTranslationManager translationManager; LobbyButtonTranslationManager translationManager;
GridPane gridPane; GridPane gridPane;
ch.unibas.dmi.dbis.cs108.casono.client.network.TestServer testServer;
@BeforeEach @BeforeEach
void setUp() { void setUp() throws Exception {
gridPane = new GridPane(); gridPane = new GridPane();
translationManager = LobbyButtonTranslationManager.getInstance(); translationManager = LobbyButtonTranslationManager.getInstance();
translationManager.getButtonIdToLobbyId().clear(); translationManager.getButtonIdToLobbyId().clear();
gridManager = new LobbyButtonGridManager(gridPane, translationManager); // Start an in-process test server and connect a real ClientService to it.
testServer = new ch.unibas.dmi.dbis.cs108.casono.client.network.TestServer();
String host = "127.0.0.1";
int port = testServer.getPort();
ClientService clientService = new ClientService(host, port);
gridManager = new LobbyButtonGridManager(gridPane, translationManager, clientService);
}
@AfterEach
void tearDown() throws Exception {
if (testServer != null)
testServer.close();
} }
@Test @Test