Merge pull request #58 from rubenpirreram/Launcher

Launcher
This commit is contained in:
rubenpirreram
2026-04-30 20:09:03 +02:00
committed by GitHub
11 changed files with 224 additions and 79 deletions
@@ -1,53 +1,84 @@
package it.polimi.ingsw.gc14; package it.polimi.ingsw.gc14;
import it.polimi.ingsw.gc14.Controller.ClientController; import it.polimi.ingsw.gc14.Controller.ClientController;
import it.polimi.ingsw.gc14.Network.NetworkEvent;
import it.polimi.ingsw.gc14.Network.RMI.Client.RMIClient; import it.polimi.ingsw.gc14.Network.RMI.Client.RMIClient;
import it.polimi.ingsw.gc14.View.IView; import it.polimi.ingsw.gc14.Network.TCP.Client.TCPClient;
import it.polimi.ingsw.gc14.View.TUI.TUI;
import java.util.Scanner; import java.util.Scanner;
public class ClientLauncherTUI { public class ClientLauncherTUI {
public void main() throws InterruptedException { public void main() throws InterruptedException {
ClientController controller = new ClientController(); TUI view=new TUI(null);
ClientController controller = new ClientController(view);
Scanner scanner = new Scanner(System.in); Scanner scanner = new Scanner(System.in);
System.out.println("Selezionare nome utente: "); System.out.println("Selezionare nome utente: ");
String username = scanner.next(); String username = scanner.next();
System.out.println(username);
System.out.println("Selezionare numero di giocatori desiderato: "); System.out.println("Selezionare numero di giocatori desiderato: ");
int proposedNumPlayers = scanner.nextInt(); int proposedNumPlayers = scanner.nextInt();
System.out.println(proposedNumPlayers);
System.out.println("Selezionare RMI[0] o TCP[1]: "); System.out.println("Selezionare RMI[0] o TCP[1]: ");
int networkType = scanner.nextInt(); int networkType = scanner.nextInt();
System.out.println(networkType);
scanner.close();
// RMI
if (networkType == 0) { if (networkType == 0) {
RMIClient client = new RMIClient("localhost", 1099); // Connect
if (client.connect(username, proposedNumPlayers, controller)) { RMIClient client = new RMIClient(controller, "localhost", 1099);
if (client.connect(username, proposedNumPlayers)) {
System.out.println("Succesfully connected to RMI server\n\n"); System.out.println("Succesfully connected to RMI server\n\n");
} else { } else {
System.out.println("RMI connection refused\n\n"); System.out.println("RMI connection refused\n\n");
}
while(true) {
System.out.flush();
if (controller.localModel!=null) {
break;
}
Thread.sleep(500);
}
System.out.println("Model set\n\n");
} else if (networkType == 1) {
return; return;
} }
controller.setClient(client);
// Play
//while(controller.localController.getModel()==null){
// scanner.nextInt();
//}
while(true) {
getInput(scanner, controller, username);
}
// TCP
} else if (networkType == 1) {
// Connect
TCPClient client = new TCPClient(controller, "localhost", 8080);
if (client.connect(username, proposedNumPlayers)) {
System.out.println("Succesfully connected to TCP server\n\n");
} else {
System.out.println("TCP connection refused\n\n");
return;
}
controller.setClient(client);
// Play
while(true) {
getInput(scanner, controller, username);
}
}
scanner.close();
}
private void getInput(Scanner scanner, ClientController controller, String username) {
int action = scanner.nextInt();
int pos = scanner.nextInt();
switch(action) {
case 1 -> controller.drawLowerBuildingCard(username, pos);
case 2 -> controller.drawLowerTribeCard(username, pos);
case 3 -> controller.drawUpperBuildingCard(username, pos);
case 4 -> controller.drawUpperTribeCard(username, pos);
case 5 -> controller.pickOptionalBuildingCard(username, pos);
case 6 -> controller.slotChoice(username, pos);
}
return;
} }
} }
@@ -1,35 +1,116 @@
package it.polimi.ingsw.gc14.Controller; package it.polimi.ingsw.gc14.Controller;
import it.polimi.ingsw.gc14.Model.Game; import it.polimi.ingsw.gc14.Model.Game;
import it.polimi.ingsw.gc14.Model.Player;
import it.polimi.ingsw.gc14.Network.IClient;
import it.polimi.ingsw.gc14.Network.NetworkEvents.*;
import it.polimi.ingsw.gc14.Network.Observer; import it.polimi.ingsw.gc14.Network.Observer;
import it.polimi.ingsw.gc14.View.IView; import it.polimi.ingsw.gc14.View.IView;
public class ClientController { public class ClientController {
public Game localModel;
public GameController localController; public GameController localController;
public IView view=null; public IView view=null;
private IClient client;
public ClientController(IView view,Game localModel) { public ClientController(IView view) {
this.view = view; this.view = view;
this.localModel = localModel; this.localController = new GameController();
this.localController = new GameController(localModel);
} }
public void setClient(IClient client) {
public ClientController() { this.client = client;
this.localController = new GameController(localModel);
} }
public void setModel(Game model) { public void setModel(Game model) {
this.localModel = model;
localController.setModel(model); localController.setModel(model);
// localModel.addObserver((Observer) view); // registra la view come observer view.update(localController.getModel());
} }
public void onError(String message) { public void onError(String message) {
view.showError(message); view.showError(message);
} }
/**
* Attempts to draw an upper tribe card for the specified player from the specified position.
*
* @param playerUsername the username of the player performing the action.
* @param pos the position of the upper tribe card to draw.
* @return {@code true} if the action succeeds, {@code false} if the player does not exist
* or if the draw operation fails.
*/
public void drawUpperTribeCard(String playerUsername,int pos) {
client.doEvent(new DrawUpperTribeCard(playerUsername,pos));
}
/**
* Attempts to draw a lower tribe card for the specified player from the specified position.
*
* @param playerUsername the username of the player performing the action.
* @param pos the position of the lower tribe card to draw.
* @return {@code true} if the action succeeds, {@code false} if the player does not exist
* or if the draw operation fails.
*/
public void drawLowerTribeCard(String playerUsername,int pos) {
client.doEvent(new DrawLowerTribeCard(playerUsername,pos));
}
/**
* Attempts to draw an upper building card for the specified player from the specified position.
*
* @param playerUsername the username of the player performing the action.
* @param pos the position of the upper building card to draw.
* @return {@code true} if the action succeeds, {@code false} if the player does not exist
* or if the draw operation fails.
*/
public void drawUpperBuildingCard(String playerUsername,int pos) {
client.doEvent(new DrawUpperBuildingCard(playerUsername,pos));
}
/**
* Attempts to draw a lower building card for the specified player from the specified position.
*
* @param playerUsername the username of the player performing the action.
* @param pos the position of the lower building card to draw.
* @return {@code true} if the action succeeds, {@code false} if the player does not exist
* or if the draw operation fails.
*/
public void drawLowerBuildingCard(String playerUsername,int pos) {
client.doEvent(new DrawLowerBuildingCard(playerUsername,pos));
}
/**
* Attempts to pick an optional tribe card for the specified player from the specified position.
*
* @param playerUsername the username of the player performing the action.
* @param pos the position of the optional tribe card to pick.
* @return {@code true} if the action succeeds, {@code false} if the player does not exist
* or if the pick operation fails.
*/
public void pickOptionalTribeCard(String playerUsername,int pos) {
client.doEvent(new PickOptionalTribeCard(playerUsername,pos));
}
/**
* Attempts to pick an optional building card for the specified player from the specified position.
*
* @param playerUsername the username of the player performing the action.
* @param pos the position of the optional building card to pick.
* @return {@code true} if the action succeeds, {@code false} if the player does not exist
* or if the pick operation fails.
*/
public void pickOptionalBuildingCard(String playerUsername,int pos) {
client.doEvent(new PickOptionalBuildingCard(playerUsername,pos));
}
/**
* Attempts to perform the slot choice action for the specified player at the specified position.
*
* @param playerUsername the username of the player performing the action.
* @param pos the position of the chosen slot.
* @return {@code true} if the action succeeds, {@code false} if the player does not exist
* or if the slot choice operation fails.
*/
public void slotChoice(String playerUsername,int pos) {
client.doEvent(new SlotChoice(playerUsername,pos));
}
} }
@@ -2,12 +2,14 @@ package it.polimi.ingsw.gc14.Model.Orders;
import it.polimi.ingsw.gc14.Model.Player; import it.polimi.ingsw.gc14.Model.Player;
import java.io.Serializable;
/** /**
* Abstract base class for all order logic cards. * Abstract base class for all order logic cards.
* An OrderLogicCard manages a queue of players and defines the effects * An OrderLogicCard manages a queue of players and defines the effects
* applied when players are pushed back into the queue. * applied when players are pushed back into the queue.
*/ */
public class OrderPlayer{ public class OrderPlayer implements Serializable {
public Player player; public Player player;
public boolean played; public boolean played;
public OrderPlayer(Player player,boolean played){ public OrderPlayer(Player player,boolean played){
@@ -0,0 +1,8 @@
package it.polimi.ingsw.gc14.Network;
import java.rmi.RemoteException;
public interface IClient {
public boolean connect(String username,int preferredInt);
public void doEvent(NetworkEvent event) ;
}
@@ -39,6 +39,7 @@ public class ClientCallbackImpl extends UnicastRemoteObject implements IClientCa
@Override @Override
public void onGameInit(Game model) throws RemoteException { public void onGameInit(Game model) throws RemoteException {
clientController.setModel(model); clientController.setModel(model);
clientController.view.render();
} }
@@ -55,7 +56,7 @@ public class ClientCallbackImpl extends UnicastRemoteObject implements IClientCa
System.out.println(event.toString()); System.out.println(event.toString());
} else { } else {
event.apply(clientController.localController); event.apply(clientController.localController);
//clientController.view.update(); TODO clientController.view.render();
} }
} }
} }
@@ -4,6 +4,7 @@ import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry; import java.rmi.registry.Registry;
import it.polimi.ingsw.gc14.Controller.ClientController; import it.polimi.ingsw.gc14.Controller.ClientController;
import it.polimi.ingsw.gc14.Network.IClient;
import it.polimi.ingsw.gc14.Network.NetworkEvent; import it.polimi.ingsw.gc14.Network.NetworkEvent;
import it.polimi.ingsw.gc14.Network.RMI.Common.IClientCallback; import it.polimi.ingsw.gc14.Network.RMI.Common.IClientCallback;
import it.polimi.ingsw.gc14.Network.RMI.Common.IGameServer; import it.polimi.ingsw.gc14.Network.RMI.Common.IGameServer;
@@ -11,7 +12,7 @@ import it.polimi.ingsw.gc14.Network.RMI.Common.IGameServer;
/** /**
* Client RMI. Uses the methods exposed by the server RMI. * Client RMI. Uses the methods exposed by the server RMI.
*/ */
public class RMIClient { public class RMIClient implements IClient {
/** The host address of the RMI server */ /** The host address of the RMI server */
private final String host; private final String host;
@@ -22,13 +23,18 @@ public class RMIClient {
/** The remote stub used to call methods on the server */ /** The remote stub used to call methods on the server */
private IGameServer stub; private IGameServer stub;
/** Client game's controller */
ClientController controller;
/** /**
* Class constructor. * Class constructor.
* @param controller the client controller used to create the callback
* @param host the host address of the RMI server * @param host the host address of the RMI server
* @param port the port of the RMI server * @param port the port of the RMI server
*/ */
public RMIClient(String host, int port) { public RMIClient(ClientController controller, String host, int port) {
this.controller=controller;
this.host = host; this.host = host;
this.port = port; this.port = port;
} }
@@ -40,14 +46,13 @@ public class RMIClient {
* Then, creates a {@link ClientCallbackImpl} and calls {@link RMIServer#joinGame(String, int, IClientCallback)}. * Then, creates a {@link ClientCallbackImpl} and calls {@link RMIServer#joinGame(String, int, IClientCallback)}.
* @param username the player's username * @param username the player's username
* @param preferredInt the desired number of players * @param preferredInt the desired number of players
* @param clientController the client controller used to create the callback
* @return true if the player successfully joined the game, false otherwise * @return true if the player successfully joined the game, false otherwise
*/ */
public boolean connect(String username,int preferredInt, ClientController clientController) { public boolean connect(String username,int preferredInt) {
try { try {
Registry registry = LocateRegistry.getRegistry(host, port); Registry registry = LocateRegistry.getRegistry(host, port);
this.stub = (IGameServer) registry.lookup("RMIGameServer"); this.stub = (IGameServer) registry.lookup("RMIGameServer");
ClientCallbackImpl callback = new ClientCallbackImpl(clientController); ClientCallbackImpl callback = new ClientCallbackImpl(controller);
return stub.joinGame(username, preferredInt, callback); return stub.joinGame(username, preferredInt, callback);
} }
@@ -63,8 +68,12 @@ public class RMIClient {
* @param event the event to send * @param event the event to send
* @throws RemoteException if any RMI error occurs * @throws RemoteException if any RMI error occurs
*/ */
public void doEvent(NetworkEvent event) throws RemoteException { public void doEvent(NetworkEvent event) {
try {
stub.doEvent(event); stub.doEvent(event);
}catch (Exception e) {
}
} }
} }
@@ -1,7 +1,8 @@
package it.polimi.ingsw.gc14.Network.TCP.Client; package it.polimi.ingsw.gc14.Network.TCP.Client;
import it.polimi.ingsw.gc14.Controller.GameController; import it.polimi.ingsw.gc14.Controller.ClientController;
import it.polimi.ingsw.gc14.Model.Game; import it.polimi.ingsw.gc14.Model.Game;
import it.polimi.ingsw.gc14.Network.IClient;
import it.polimi.ingsw.gc14.Network.NetworkEvent; import it.polimi.ingsw.gc14.Network.NetworkEvent;
import it.polimi.ingsw.gc14.Network.NetworkEvents.AddPlayer; import it.polimi.ingsw.gc14.Network.NetworkEvents.AddPlayer;
@@ -11,7 +12,7 @@ import java.net.*;
/** /**
* Client TCP. Sends and receives messages with the TCP server. * Client TCP. Sends and receives messages with the TCP server.
*/ */
public class TCPClient { public class TCPClient implements IClient {
/** Socket TCP */ /** Socket TCP */
Socket communicationSocket; Socket communicationSocket;
@@ -23,7 +24,7 @@ public class TCPClient {
ObjectOutputStream socketSend; ObjectOutputStream socketSend;
/** Client game's controller */ /** Client game's controller */
GameController controller; ClientController controller;
/** IP address of the server to connect to */ /** IP address of the server to connect to */
String hostname; String hostname;
@@ -38,7 +39,7 @@ public class TCPClient {
* @param hostname The IP address of the server * @param hostname The IP address of the server
* @param port The TCP port of the server * @param port The TCP port of the server
*/ */
public TCPClient(GameController controller, String hostname, int port) { public TCPClient(ClientController controller, String hostname, int port) {
this.controller = controller; this.controller = controller;
this.hostname = hostname; this.hostname = hostname;
this.port = port; this.port = port;
@@ -53,13 +54,15 @@ public class TCPClient {
* @param proposedNPlayers The desired number of players for the game * @param proposedNPlayers The desired number of players for the game
* @return true if the connection is successful, false otherwise. * @return true if the connection is successful, false otherwise.
*/ */
public boolean start(String user, int proposedNPlayers) { public boolean connect(String user, int proposedNPlayers) {
try { try {
communicationSocket = new Socket(hostname, port); communicationSocket = new Socket(hostname, port);
socketSend = new ObjectOutputStream(communicationSocket.getOutputStream()); socketSend = new ObjectOutputStream(communicationSocket.getOutputStream());
socketReceive = new ObjectInputStream(communicationSocket.getInputStream()); socketReceive = new ObjectInputStream(communicationSocket.getInputStream());
sendEvent(new AddPlayer(user, proposedNPlayers));
doEvent(new AddPlayer(user, proposedNPlayers));
if (communicationSocket.getInputStream().read() == -1) { if (communicationSocket.getInputStream().read() == -1) {
System.out.println("Could not connect to server"); System.out.println("Could not connect to server");
return false; return false;
@@ -89,11 +92,12 @@ public class TCPClient {
if (event.getIsError()) { if (event.getIsError()) {
System.out.println(event); System.out.println(event);
} else { } else {
event.apply(controller); event.apply(controller.localController);
//clientController.view.update(); TODO controller.view.render();
} }
} else if (read instanceof Game model) { } else if (read instanceof Game model) {
controller.setModel(model); controller.setModel(model);
controller.view.render();
} }
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
@@ -108,7 +112,7 @@ public class TCPClient {
* Sends a {@link NetworkEvent} to the server. * Sends a {@link NetworkEvent} to the server.
* @param event The NetworkEvent to send. * @param event The NetworkEvent to send.
*/ */
private void sendEvent(NetworkEvent event) { public void doEvent(NetworkEvent event) {
try { try {
socketSend.writeObject(event); socketSend.writeObject(event);
} catch (IOException e) { } catch (IOException e) {
@@ -41,8 +41,10 @@ public class ClientHandler implements Runnable {
* @param clientHandlers The shared list of all active client handlers * @param clientHandlers The shared list of all active client handlers
* @param actionQueue The queue containing incoming events * @param actionQueue The queue containing incoming events
*/ */
public ClientHandler(Socket clientSocket, List<ClientHandler> clientHandlers, BlockingQueue<NetworkEvent> actionQueue) { public ClientHandler(Socket clientSocket, ObjectOutputStream out, ObjectInputStream in, List<ClientHandler> clientHandlers, BlockingQueue<NetworkEvent> actionQueue) {
this.clientSocket = clientSocket; this.clientSocket = clientSocket;
this.in = in;
this.out = out;
this.clientHandlers = clientHandlers; this.clientHandlers = clientHandlers;
this.actionQueue = actionQueue; this.actionQueue = actionQueue;
} }
@@ -55,8 +57,7 @@ public class ClientHandler implements Runnable {
@Override @Override
public void run() { public void run() {
try { try {
in = new ObjectInputStream(clientSocket.getInputStream());
out = new ObjectOutputStream(clientSocket.getOutputStream());
while (true) { while (true) {
NetworkEvent event = (NetworkEvent) in.readObject(); NetworkEvent event = (NetworkEvent) in.readObject();
if (!actionQueue.add(event)) { if (!actionQueue.add(event)) {
@@ -76,15 +77,13 @@ public class ClientHandler implements Runnable {
* Sends a {@link NetworkEvent} to the client. * Sends a {@link NetworkEvent} to the client.
* @param event The network event to send to the client. * @param event The network event to send to the client.
*/ */
public void notifyEvent(NetworkEvent event) { public synchronized void notifyEvent(NetworkEvent event) {
synchronized (out) {
try { try {
out = new ObjectOutputStream(clientSocket.getOutputStream());
out.writeObject(event); out.writeObject(event);
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
}
} }
@@ -92,14 +91,11 @@ public class ClientHandler implements Runnable {
* Sends the current game model to this client. * Sends the current game model to this client.
* @param game The current state of the game to send to the client. * @param game The current state of the game to send to the client.
*/ */
public void notifyModel(Game game) { public synchronized void notifyModel(Game game) {
synchronized (out) {
try { try {
out = new ObjectOutputStream(clientSocket.getOutputStream());
out.writeObject(game); out.writeObject(game);
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
}
} }
@@ -88,8 +88,9 @@ public class TCPServer {
try{ try{
clientSocket = socketTCP.accept(); clientSocket = socketTCP.accept();
ObjectInputStream clientSocketObj = new ObjectInputStream(clientSocket.getInputStream()); ObjectOutputStream clientSend = new ObjectOutputStream(clientSocket.getOutputStream());
NetworkEvent event = (NetworkEvent) clientSocketObj.readObject(); ObjectInputStream clientReceive = new ObjectInputStream(clientSocket.getInputStream());
NetworkEvent event = (NetworkEvent) clientReceive.readObject();
if(!(event.getEventType() == EventType.ADD_PLAYER)){ if(!(event.getEventType() == EventType.ADD_PLAYER)){
clientSocket.getOutputStream().write((int)(-1)); clientSocket.getOutputStream().write((int)(-1));
@@ -114,7 +115,7 @@ public class TCPServer {
clientSocket.getOutputStream().write((int) (1)); clientSocket.getOutputStream().write((int) (1));
System.out.println("Accepted player: " + eventAddPlayer.getUsername()); System.out.println("Accepted player: " + eventAddPlayer.getUsername());
ClientHandler clientHandler = new ClientHandler(clientSocket, clientHandlers, actionQueue); ClientHandler clientHandler = new ClientHandler(clientSocket, clientSend, clientReceive, clientHandlers, actionQueue);
clientHandlers.add(clientHandler); clientHandlers.add(clientHandler);
ConnectedPlayers++; ConnectedPlayers++;
@@ -4,8 +4,8 @@ import it.polimi.ingsw.gc14.Model.Game;
import it.polimi.ingsw.gc14.Network.NetworkEvent; import it.polimi.ingsw.gc14.Network.NetworkEvent;
public interface IView { public interface IView {
public void update(Game game);
public void render(Game model); public void render();
public void showMessage(String message); public void showMessage(String message);
public void showError(String message); public void showError(String message);
@@ -7,11 +7,22 @@ public class TUI implements IView {
// ── dati di stato ─────────────────────────────────────────── // ── dati di stato ───────────────────────────────────────────
private BorderStyle style = BorderStyle.UNICODE; private BorderStyle style = BorderStyle.UNICODE;
private Game model; private Game model;
private String username;
public TUI(Game model) { public TUI(Game model) {
this.model = model; this.model = model;
this.username="";
} }
public void setUsername(String username) {
this.username = username;
}
@Override
public void update(Game model) {
this.model = model;
}
// ── punto di ingresso ─────────────────────────────────────── // ── punto di ingresso ───────────────────────────────────────
public void render(Game model) public void render()
{ {
try{ try{
String os = System.getProperty("os.name").toLowerCase(); String os = System.getProperty("os.name").toLowerCase();
@@ -28,7 +39,7 @@ public class TUI implements IView {
System.out.println(model.toString()); System.out.println(model.toString());
} }
public void renderBoard(Game model) public void renderBoard()
{ {
try{ try{
String os = System.getProperty("os.name").toLowerCase(); String os = System.getProperty("os.name").toLowerCase();
@@ -44,7 +55,7 @@ public class TUI implements IView {
} }
System.out.println(model.BoardStamp()); System.out.println(model.BoardStamp());
} }
public void renderPlayer(Game model) public void renderPlayer()
{ {
try{ try{
String os = System.getProperty("os.name").toLowerCase(); String os = System.getProperty("os.name").toLowerCase();
@@ -60,7 +71,7 @@ public class TUI implements IView {
} }
System.out.println(model.BoardStamp()); System.out.println(model.BoardStamp());
} }
public void renderMyHand(Game model,String username) public void renderMyHand()
{ {
try{ try{
String os = System.getProperty("os.name").toLowerCase(); String os = System.getProperty("os.name").toLowerCase();
@@ -77,6 +88,7 @@ public class TUI implements IView {
System.out.println(model.getPlayerByUsername(username)); System.out.println(model.getPlayerByUsername(username));
} }
public void showMessage(String message) public void showMessage(String message)
{ {
System.out.println(message); System.out.println(message);