Merge branch 'main' of github.com:rubenpirreram/ing-sw-2026-pirrera-radice-pagani-pellegrino into GUI

This commit is contained in:
rubenpirreram
2026-04-30 20:11:58 +02:00
53 changed files with 1897 additions and 550 deletions
@@ -1,53 +1,85 @@
package it.polimi.ingsw.gc14;
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.View.IView;
import it.polimi.ingsw.gc14.Network.TCP.Client.TCPClient;
import it.polimi.ingsw.gc14.View.TUI.TUI;
import java.util.Scanner;
public class ClientLauncherTUI {
//TODO Javadoc
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);
System.out.println("Selezionare nome utente: ");
String username = scanner.next();
System.out.println(username);
System.out.println("Selezionare numero di giocatori desiderato: ");
int proposedNumPlayers = scanner.nextInt();
System.out.println(proposedNumPlayers);
System.out.println("Selezionare RMI[0] o TCP[1]: ");
int networkType = scanner.nextInt();
System.out.println(networkType);
scanner.close();
// RMI
if (networkType == 0) {
RMIClient client = new RMIClient("localhost", 1099);
if (client.connect(username, proposedNumPlayers, controller)) {
// Connect
RMIClient client = new RMIClient(controller, "localhost", 1099);
if (client.connect(username, proposedNumPlayers)) {
System.out.println("Succesfully connected to RMI server\n\n");
} else {
System.out.println("RMI connection refused\n\n");
return;
}
controller.setClient(client);
// Play
//while(controller.localController.getModel()==null){
// scanner.nextInt();
//}
while(true) {
System.out.flush();
if (controller.localModel!=null) {
break;
}
Thread.sleep(500);
getInput(scanner, controller, username);
}
System.out.println("Model set\n\n");
// TCP
} else if (networkType == 1) {
return;
// 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,119 @@
package it.polimi.ingsw.gc14.Controller;
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.View.IView;
//TODO Javadoc
public class ClientController {
public Game localModel;
public GameController localController;
//TODO Javadoc
public IView view=null;
private IClient client;
public ClientController(IView view,Game localModel) {
public ClientController(IView view) {
this.view = view;
this.localModel = localModel;
this.localController = new GameController(localModel);
this.localController = new GameController();
}
public ClientController() {
this.localController = new GameController(localModel);
public void setClient(IClient client) {
this.client = client;
}
public void setModel(Game model) {
this.localModel = model;
localController.setModel(model);
// localModel.addObserver((Observer) view); // registra la view come observer
view.update(localController.getModel());
}
public void onError(String 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,15 +2,21 @@ package it.polimi.ingsw.gc14;
import java.util.ArrayList;
//TODO Javadoc
public class LimitedList<T> extends ArrayList<T> {
//TODO Javadoc
private int limit;
//TODO Javadoc
private Runnable action;
//TODO Javadoc
public LimitedList(int limit, Runnable action) {
this.limit = limit;
this.action = action;
}
//TODO Javadoc
@Override
public boolean add(T element) {
boolean result = super.add(element);
@@ -20,12 +26,15 @@ public class LimitedList<T> extends ArrayList<T> {
return result;
}
//TODO Javadoc
public void setLimit(int num) {
this.limit=num;
}
//TODO Javadoc
public int getLimit(){return limit;}
//TODO Javadoc
public void setAction(Runnable action) {
this.action=action;
}
@@ -4,7 +4,6 @@ import it.polimi.ingsw.gc14.Model.Cards.Building.EffectType;
import it.polimi.ingsw.gc14.Model.Cards.BuildingCard;
import it.polimi.ingsw.gc14.Model.Cards.TribeCards.CharacterType;
/**
* During the Sustenance Event, you have a discount of 1 food token on the total you
* would have to pay, for each of the indicated characters in your tribe.
@@ -44,6 +43,16 @@ public class Building1 extends BuildingCard {
return new Building1(getEra(),getPrice(),getPrestigeValue(),getIcon());
}
/**
* Prints a string representation of this {@code Building1}. This specific variation is used in the {@code Game}'s
* toString to print a more detailed version.
* <p>includes:
* <li>{@link #icon Icon}
* </p>
* @return {@code String} - a string representation of this {@code Building1}.
* @see it.polimi.ingsw.gc14.Model.Game Game
* @see it.polimi.ingsw.gc14.Model.GamePackage.Board Board
*/
@Override
public String toString() {
return super.toString() + " Icon: " + this.icon.toString().charAt(0);
@@ -7,6 +7,9 @@ import it.polimi.ingsw.gc14.Model.Player;
public class Building11 extends BuildingCard {
/**
* The icon attribute indicates the character type involved in the building effect.
*/
private CharacterType icon ;
/**
@@ -68,6 +71,17 @@ public class Building11 extends BuildingCard {
player.addPrestige(player.getNType(getIcon()) * this.getPrestigeMul());
}
/**
* Prints a string representation of this {@code Building1}. This specific variation is used in the {@code Game}'s
* toString to print a more detailed version.
* <p>includes:
* <li>{@link #icon Icon}
* <li>{@link #PrestigeMul Prestige Multiplier}
* </p>
* @return {@code String} - a string representation of this {@code Building1}.
* @see it.polimi.ingsw.gc14.Model.Game Game
* @see it.polimi.ingsw.gc14.Model.GamePackage.Board Board
*/
@Override
public String toString() {
return super.toString() + " Icon: " + this.icon.toString().charAt(0) + " MP: " + this.PrestigeMul;
@@ -5,7 +5,6 @@ import it.polimi.ingsw.gc14.Model.Cards.BuildingCard;
import it.polimi.ingsw.gc14.Model.Player;
public class Building13 extends BuildingCard{
/**
* Creates a Building13 card with the specified era, price, and prestige value.
*
@@ -60,6 +60,17 @@ public abstract class Character extends TribeCard implements Cloneable {
return super.toString();
}
/**
* Prints a string representation of this {@code Character}. This specific variation is used in the {@code Game}'s
* toString to print a more detailed version.
* <p>Includes:
* <li>{@link it.polimi.ingsw.gc14.Model.Cards.TribeCards.CharacterType Type}
* </p>
* @return {@code String} - a string representation of this {@code Character}.
* @see it.polimi.ingsw.gc14.Model.Game Game
* @see it.polimi.ingsw.gc14.Model.GamePackage.Board Board
*/
@Override
public String toStringBoard()
{
@@ -4,9 +4,7 @@ import it.polimi.ingsw.gc14.Model.Cards.TribeCards.Character;
import it.polimi.ingsw.gc14.Model.Cards.TribeCards.CharacterType;
import it.polimi.ingsw.gc14.Model.Player;
public class Builder extends Character
{
public class Builder extends Character {
/**
* The reduction value provided by this Builder card.
*/
@@ -89,6 +87,19 @@ public class Builder extends Character
public String toString() {
return super.toString() + " RV:" + String.valueOf(reductionValue) + " PV:" + String.valueOf(prestigeValue);
}
/**
* Prints a string representation of this {@code TribeCard}. This specific variation is used in the {@code Game}'s
* toString to print a more detailed version.
* <p>Includes:
* <li>{@link #reductionValue Reduction Value}
* <li>{@link #prestigeValue Prestige Value}
* </p>
* @return {@code String} - a string representation of this {@code TribeCard}.
* @see it.polimi.ingsw.gc14.Model.Cards.TribeCard TribeCard
* @see it.polimi.ingsw.gc14.Model.Game Game
* @see it.polimi.ingsw.gc14.Model.GamePackage.Board Board
*/
@Override
public String toStringBoard()
{
@@ -5,7 +5,6 @@ import it.polimi.ingsw.gc14.Model.Cards.TribeCards.CharacterType;
import it.polimi.ingsw.gc14.Model.Player;
public class Gatherer extends Character {
/**
* Creates a Gatherer character card with the specified era.
*
@@ -5,6 +5,12 @@ import it.polimi.ingsw.gc14.Model.Cards.TribeCards.CharacterType;
import it.polimi.ingsw.gc14.Model.Player;
public class Hunter extends Character {
/**
* Describes whether the {@code Hunter Icon} is present or not. Whenever an
* {@code Hunter} with an {@code Hunter Icon} is added to the tribe, 1 {@code Food token} is awarded for each Hunter in the tribe
* (with or without an icon).
*/
private boolean icon;
/**
@@ -53,6 +59,18 @@ public class Hunter extends Character {
}
return toPrint;
}
/**
* Prints a string representation of this {@code TribeCard}. This specific variation is used in the {@code Game}'s
* toString to print a more detailed version.
* <p>Potentially includes:
* <li>{@link #icon Icon}
* </p>
* @return {@code String} - a string representation of this {@code TribeCard}.
* @see it.polimi.ingsw.gc14.Model.Cards.TribeCard TribeCard
* @see it.polimi.ingsw.gc14.Model.Game Game
* @see it.polimi.ingsw.gc14.Model.GamePackage.Board Board
*/
@Override
public String toStringBoard() {
String toPrint = super.toStringBoard();
@@ -62,7 +80,6 @@ public class Hunter extends Character {
return toPrint;
}
/**
* Creates and returns a copy of this Hunter card.
*
@@ -4,6 +4,9 @@ import it.polimi.ingsw.gc14.Model.Cards.TribeCards.CharacterType;
import it.polimi.ingsw.gc14.Model.Player;
public class Inventor extends Character {
/**
* The {@code Icons}'s ID. There are a total of 10 different Icons.
*/
private int icon;
/**
@@ -54,6 +57,18 @@ public class Inventor extends Character {
public String toString() {
return super.toString() + " I_ID:" + String.valueOf(icon);
}
/**
* Prints a string representation of this {@code TribeCard}. This specific variation is used in the {@code Game}'s
* toString to print a more detailed version.
* <p>Includes:
* <li>{@link #icon Icons's ID}
* </p>
* @return {@code String} - a string representation of this {@code TribeCard}.
* @see it.polimi.ingsw.gc14.Model.Cards.TribeCard TribeCard
* @see it.polimi.ingsw.gc14.Model.Game Game
* @see it.polimi.ingsw.gc14.Model.GamePackage.Board Board
*/
@Override
public String toStringBoard() {
return super.toStringBoard() + " I_ID:" + String.valueOf(icon);
@@ -6,7 +6,13 @@ import it.polimi.ingsw.gc14.Model.Cards.TribeCards.CharacterType;
import it.polimi.ingsw.gc14.Model.Player;
public class Shaman extends Character {
/**
* The number of star {@code Icons} the card possesses.
* During the {@link it.polimi.ingsw.gc14.Model.Cards.TribeCards.Events.ShamanicRitual Shamanic Ritual Event}, having the
* majority of these icons provides Prestige Points;
* having the minority, on the other hand, results in
* losing Prestige Points.
*/
private int icon;
/**
@@ -51,12 +57,23 @@ public class Shaman extends Character {
public String toString() {
return super.toString() + " *:" + String.valueOf(icon);
}
/**
* Prints a string representation of this {@code TribeCard}. This specific variation is used in the {@code Game}'s
* toString to print a more detailed version.
* <p>Includes:
* <li>{@link #icon Number of stars}
* </p>
* @return {@code String} - a string representation of this {@code TribeCard}.
* @see it.polimi.ingsw.gc14.Model.Cards.TribeCard TribeCard
* @see it.polimi.ingsw.gc14.Model.Game Game
* @see it.polimi.ingsw.gc14.Model.GamePackage.Board Board
*/
@Override
public String toStringBoard() {
return super.toStringBoard() + " *:" + String.valueOf(icon);
}
/**
* Creates and returns a copy of this Shaman card.
*
@@ -64,6 +64,17 @@ public abstract class EventCard extends TribeCard {
public String toString() {
return super.toString()+" "+type.toString();
}
/**
* Prints a string representation of this {@code EventCard}. This specific variation is used in the {@code Game}'s
* toString to print a more detailed version.
* <p>Includes:
* <li>{@link #type Type}
* </p>
* @return {@code String} - a string representation of this {@code EventCard}.
* @see it.polimi.ingsw.gc14.Model.Game Game
* @see it.polimi.ingsw.gc14.Model.GamePackage.Board Board
*/
@Override
public String toStringBoard() {
return super.toString()+" "+type.toString();
@@ -86,6 +86,24 @@ public class CavePaintings extends EventCard {
return new CavePaintings(getEra(), NLower, NPrestigeRem, NPrestigeMul) ;
}
/**
* Prints a string representation of this {@code TribeCard}. This specific variation is used in the {@code Game}'s
* toString to print a more detailed version.
* <p>NOTE: {@code NUpper} is not a real attribute used in calculations (only {@code NLower} is needed),
* however it's a parameter on the cards' design.
* </p>
* <p>Includes:
* <li>{@link #NLower}
* <li>{@code NUpper}
* <li>{@link #NPrestigeRem}
* <li>{@link #NPrestigeMul}
* </p>
* @return {@code String} - a string representation of this {@code TribeCard}.
* @see it.polimi.ingsw.gc14.Model.Cards.TribeCard TribeCard
* @see it.polimi.ingsw.gc14.Model.Game Game
* @see it.polimi.ingsw.gc14.Model.GamePackage.Board Board
*/
@Override
public String toStringBoard() {
return super.toString()+" 0-"+(NLower-1)+":"+NPrestigeRem+" "+NLower+"+:"+NPrestigeMul;
@@ -70,6 +70,18 @@ public class Hunt extends EventCard {
public EventCard clone() {
return new Hunt(getEra(), prestigeMultiplier);
}
/**
* Prints a string representation of this {@code TribeCard}. This specific variation is used in the {@code Game}'s
* toString to print a more detailed version.
* <p>includes:
* <li>{@link #prestigeMultiplier}
* </p>
* @return {@code String} - a string representation of this {@code TribeCard}.
* @see it.polimi.ingsw.gc14.Model.Cards.TribeCard TribeCard
* @see it.polimi.ingsw.gc14.Model.Game Game
* @see it.polimi.ingsw.gc14.Model.GamePackage.Board Board
*/
@Override
public String toStringBoard() {
return super.toString()+" 1F+"+prestigeMultiplier+"PP"+" X N Hunter";
@@ -96,6 +96,19 @@ public class ShamanicRitual extends EventCard {
public EventCard clone() {
return new ShamanicRitual(getEra(), prestigeToAdd, prestigeToRemove);
}
/**
* Prints a string representation of this {@code TribeCard}. This specific variation is used in the {@code Game}'s
* toString to print a more detailed version.
* <p>Includes:
* <li>{@link #prestigeToAdd}
* <li>{@link #prestigeToRemove}
* </p>
* @return {@code String} - a string representation of this {@code TribeCard}.
* @see it.polimi.ingsw.gc14.Model.Cards.TribeCard TribeCard
* @see it.polimi.ingsw.gc14.Model.Game Game
* @see it.polimi.ingsw.gc14.Model.GamePackage.Board Board
*/
@Override
public String toStringBoard() {
return super.toString()+" *>:"+prestigeToAdd+" *<:"+prestigeToRemove;
@@ -90,6 +90,17 @@ public class Sustenance extends EventCard {
return new Sustenance(getEra(), PrestigeDebt);
}
/**
* Prints a string representation of this {@code TribeCard}. This specific variation is used in the {@code Game}'s
* toString to print a more detailed version.
* <p>Includes:
* <li>{@link #PrestigeDebt}
* </p>
* @return {@code String} - a string representation of this {@code TribeCard}.
* @see it.polimi.ingsw.gc14.Model.Cards.TribeCard TribeCard
* @see it.polimi.ingsw.gc14.Model.Game Game
* @see it.polimi.ingsw.gc14.Model.GamePackage.Board Board
*/
@Override
public String toStringBoard() {
return super.toString()+" -1F/-"+PrestigeDebt+"PP";
@@ -1,7 +1,6 @@
package it.polimi.ingsw.gc14.Model;
import com.google.gson.*;
import it.polimi.ingsw.gc14.Model.Cards.Building.EffectType;
import it.polimi.ingsw.gc14.Model.Cards.Building.Effects.*;
import it.polimi.ingsw.gc14.Model.Cards.BuildingCard;
import it.polimi.ingsw.gc14.Model.Cards.TribeCards.CharacterType;
@@ -16,9 +15,10 @@ import java.io.*;
import java.lang.reflect.Type;
import java.util.*;
//TODO javadoc
public class DecksCreator {
//TODO javadoc
public static List<TribeCard> loadTribeDeckByEra(int era) throws IllegalArgumentException
{
return switch (era) {
@@ -28,6 +28,8 @@ public class DecksCreator {
default -> throw new IllegalArgumentException();
};
}
//TODO javadoc
public static List<TribeCard> loadTribeDeck(String resourcePath) {
Gson gson = new Gson();
Type listType = new com.google.gson.reflect.TypeToken<List<TribeCardDefinition>>(){}.getType();
@@ -48,11 +50,15 @@ public class DecksCreator {
throw new RuntimeException("Errore caricamento mazzo: " + resourcePath, e);
}
}
//TODO javadoc
public static List<BuildingCard> loadBuildingDeckByEra(int era) throws IllegalArgumentException
{
if(era<=0 || era>3) throw new IllegalArgumentException();
return loadBuildingDeck("/Cards/buildingCards.json").stream().filter(x->x.getEra()==era).toList();
}
//TODO javadoc
public static List<BuildingCard> loadBuildingDeck(String resourcePath) {
Gson gson = new Gson();
Type listType = new com.google.gson.reflect.TypeToken<List<BuildingCardDefinition>>(){}.getType();
@@ -74,6 +80,7 @@ public class DecksCreator {
}
}
//TODO javadoc
public static List<Slot> loadSlotDeck()
{
List<Slot> slots = new ArrayList<>();
@@ -82,6 +89,8 @@ public class DecksCreator {
slots.add(new Slot(c));
return slots;
}
//TODO javadoc
private static TribeCard createCard(TribeCardDefinition def) {
int era = def.era;
@@ -129,6 +138,7 @@ public class DecksCreator {
};
}
//TODO javadoc
private static BuildingCard createCard(BuildingCardDefinition def) {
return switch (def.effectId) {
case 0 -> new Building0(def.era, def.price, def.prestigeValue);
@@ -143,7 +153,7 @@ public class DecksCreator {
}
//TODO javadoc
private static class TribeCardDefinition {
String type;
int era;
@@ -152,6 +162,7 @@ public class DecksCreator {
List<Object> params; // Object per gestire boolean e int misti
}
//TODO javadoc
private static class BuildingCardDefinition {
int effectId;
int era;
@@ -169,8 +169,9 @@ public class Game implements Serializable {
* @throws IllegalArgumentException if {@code nPlayers < 0} or {@code nPlayers > 5}.
*/
public Game(int nPlayers) throws IllegalArgumentException{
if(nPlayers < 0||nPlayers > 5)
if(nPlayers !=0 && (nPlayers < 2 || nPlayers > 5)) {
throw new IllegalArgumentException();
}
this.nPlayers = nPlayers;
board=new Board(nPlayers);
slotMap = new LinkedHashMap<>();
@@ -312,10 +313,9 @@ public class Game implements Serializable {
tempCard.insert(player);
board.removeUpperTribeCard(tempCard);
currentState.UpperDrawn();
if(currentState.getNUpper() ==0 && currentState.getNLower() ==0)
if((currentState.getNLower() ==0 ||( getLowerListTribeCards().size()==0 && getLowerListBuilding().size()==0)) && ((currentState.getNUpper() ==0)||( getUpperListTribeCards().size()==0 && getUpperListBuilding().size()==0)))
nextPlayerSetup();
return true;
}
/**
@@ -354,7 +354,7 @@ public class Game implements Serializable {
tempCard.insert(player);
board.removeLowerTribeCard(tempCard);
currentState.LowerDrawn();
if(currentState.getNLower() ==0 && currentState.getNUpper() ==0)
if((currentState.getNLower() ==0 ||( getLowerListTribeCards().size()==0 && getLowerListBuilding().size()==0)) && ((currentState.getNUpper() ==0)||( getUpperListTribeCards().size()==0 && getUpperListBuilding().size()==0)))
nextPlayerSetup();
return true;
@@ -393,7 +393,7 @@ public class Game implements Serializable {
}
else
return false;
if(currentState.getNLower() ==0 && currentState.getNUpper() ==0)
if((currentState.getNLower() ==0 ||( getLowerListTribeCards().size()==0 && getLowerListBuilding().size()==0)) && ((currentState.getNUpper() ==0)||( getUpperListTribeCards().size()==0 && getUpperListBuilding().size()==0)))
nextPlayerSetup();
return true;
@@ -418,7 +418,7 @@ public class Game implements Serializable {
{
return false;
}
if(!player.equals(currentState.getCurrentPlayer()))
{
return false;
@@ -433,7 +433,7 @@ public class Game implements Serializable {
}
else
return false;
if(currentState.getNLower() ==0 && currentState.getNUpper() ==0)
if((currentState.getNLower() ==0 ||( getLowerListTribeCards().size()==0 && getLowerListBuilding().size()==0)) && ((currentState.getNUpper() ==0)||( getUpperListTribeCards().size()==0 && getUpperListBuilding().size()==0)))
nextPlayerSetup();
return true;
@@ -509,8 +509,8 @@ public class Game implements Serializable {
else {
return false;
}
nextPlayerSetup();
OptionalCardQueue.removeIf(x->x.equals(player));
nextPlayerSetup();
return true;
}
@@ -566,10 +566,16 @@ public class Game implements Serializable {
return;
}
currentState.GameStageUpdate(GameStages.RESOLVING_ACTIONS);
for (Map.Entry<Slot,Player> s : slotMap.entrySet()) {
if (s.getValue()!=null) {
currentState.PlayerUpdate(s.getValue(), s.getKey());
return;
for (Slot s : slotMap.keySet()) {
if (slotMap.get(s) != null) {
currentState.PlayerUpdate(slotMap.get(s), s);
if(!((currentState.getNLower() ==0 ||( getLowerListTribeCards().size()==0 && getLowerListBuilding().size()==0)) && ((currentState.getNUpper() ==0)||( getUpperListTribeCards().size()==0 && getUpperListBuilding().size()==0))))
break;
else
{
orderLogicCard.push(currentState.getCurrentPlayer());
slotMap.put(currentState.getSlot(), null);
}
}
}
return;
@@ -581,7 +587,15 @@ public class Game implements Serializable {
for (Slot s : slotMap.keySet()) {
if (slotMap.get(s) != null) {
currentState.PlayerUpdate(slotMap.get(s), s);
break;
if((currentState.getNLower() ==0 ||( getLowerListTribeCards().size()==0 && getLowerListBuilding().size()==0)) && ((currentState.getNUpper() ==0)||( getUpperListTribeCards().size()==0 && getUpperListBuilding().size()==0))) {
orderLogicCard.push(currentState.getCurrentPlayer());
slotMap.put(currentState.getSlot(), null);
}
else
{
break;
}
}
}
if(slotMap.values().stream().allMatch(v -> v == null))
@@ -600,31 +614,51 @@ public class Game implements Serializable {
{
OptionalCardQueue.add(e.getKey());
}
currentState.PlayerUpdate(OptionalCardQueue.remove(), null);
if(currentState.getCurrentPlayer()==null)
{
currentState.GameStageUpdate(GameStages.RESOLVING_EVENT);
if(currentState.getRound()<10)
{
nextRound();
}
else
{
EventResolution();
currentState.GameStageUpdate(GameStages.ENDING);
endGame();
}
Player optionalPlayer = OptionalCardQueue.poll();
if (optionalPlayer != null) {
currentState.PlayerUpdate(optionalPlayer, null);
return;
}
}
}
if(GameStages.OPTIONAL_CARD_EFFECT==currentState.getGameStage()) {
currentState.PlayerUpdate(OptionalCardQueue.remove(), null);
if(currentState.getCurrentPlayer()==null)
{
currentState.GameStageUpdate(GameStages.RESOLVING_EVENT);
if (currentState.getRound() < 10) {
nextRound();
currentState.PlayerUpdate(orderLogicCard.pull(), null);
currentState.GameStageUpdate(GameStages.SLOT_CHOICE);
} else {
EventResolution();
currentState.GameStageUpdate(GameStages.ENDING);
endGame();
}
return;
}
}
if (GameStages.OPTIONAL_CARD_EFFECT == currentState.getGameStage()) {
Player optionalPlayer = OptionalCardQueue.poll();
if (optionalPlayer != null) {
currentState.PlayerUpdate(optionalPlayer, null);
return;
}
currentState.GameStageUpdate(GameStages.RESOLVING_EVENT);
if (currentState.getRound() < 10) {
nextRound();
currentState.PlayerUpdate(orderLogicCard.pull(), null);
currentState.GameStageUpdate(GameStages.SLOT_CHOICE);
} else {
EventResolution();
currentState.GameStageUpdate(GameStages.ENDING);
endGame();
}
return;
}
}
@@ -669,9 +703,13 @@ public class Game implements Serializable {
{
currentState.GameStageUpdate(GameStages.ENDING);
endGame();
return;
}
if(currentState.getEra()!= board.nextRound())
if(currentState.getEra()!= board.nextRound()) {
currentState.EraUpdate();
}
currentState.RoundUpdate();
}
@@ -695,98 +733,113 @@ public class Game implements Serializable {
* @param nPlayers the new configured number of players.
* @return {@code true} if the number of players is updated, {@code false} otherwise.
*/
public boolean setNPlayer(int nPlayers)
{
if(this.nPlayers!=0)
public boolean setNPlayer(int nPlayers) {
if (this.nPlayers != 0) {
return false;
this.nPlayers=nPlayers;
}
if (nPlayers < 2 || nPlayers > 5) {
return false;
}
this.nPlayers = nPlayers;
board = new Board(nPlayers);
slotMap = new LinkedHashMap<>();
for (Slot s : board.getSlotList()) {
slotMap.put(s, null);
}
currentState = new CurrentState();
playersList = new ArrayList<>();
OptionalCardQueue = new LinkedList<>();
return true;
}
/**
* Prints a string representation of the {@code Game}. Used in the TUI implementation to draw:
* <li>{@link it.polimi.ingsw.gc14.Model.GamePackage.Board Board}
* <li>{@link it.polimi.ingsw.gc14.Model.Player Players}
* <li>{@link #getUpperListTribeCards() Upper TribeCard List} <li>{@link #getUpperListBuilding() Upper Building List}
* <li>{@link #getLowerListTribeCards() Lower TribeCard List} <li>{@link #getLowerListBuilding() Lower Building List}
* <li>{@link it.polimi.ingsw.gc14.Model.OrderLogicCard Offer Track}
*
* @return {@code String} - a string representation of the {@code Game}.
*/
@Override
public String toString() {
var table = new AsciiTable(BorderStyle.UNICODE, slotMap.size());
List<String> stringUp=new ArrayList<>();
List<String> stringEmpty=new ArrayList<>();
List<String> stringDown=new ArrayList<>();
return PlayersStamp()+"\n"+BoardStamp()+"\n";
}
public String PlayersStamp()
{
StringBuilder stringBuilder=new StringBuilder();
for(int i=0;i<playersList.size()/2;i++)
{
stringBuilder.append(AsciiTable.sideBySide(List.of(playersList.get((i*2)).toString().split("\n")),List.of(playersList.get((i*2+1)).toString().split("\n")),2));
}
stringBuilder.append("\n");
if(playersList.size()%2!=0)
{
stringBuilder.append(playersList.get(playersList.size()-1).toString());
stringBuilder.append("\n");
}
return stringBuilder.toString();
}
public String BoardStamp()
{
var offerTrack = new AsciiTable(BorderStyle.UNICODE, slotMap.size());
List<String> stringUpOffer=new ArrayList<>();
List<String> stringDownOffer=new ArrayList<>();
for(Map.Entry<Slot,Player> entry:slotMap.entrySet())
{
stringEmpty.add(" ");
stringDown.add(entry.getKey().toStringTUI());
stringDownOffer.add(entry.getKey().toStringTUI());
if(entry.getValue()!=null)
stringUp.add(entry.getValue().getUserName());
stringUpOffer.add(entry.getValue().getUserName());
else
stringUp.add(" ");
stringUpOffer.add(" ");
}
table.addRow(stringUp);
table.addRow(stringEmpty);
table.addRow(stringDown);
List<String>lines=List.of(orderLogicCard.toString().split("\n"));
List<String> lines2=new ArrayList<>();
lines2.add("OFFER TRACK");
lines2.addAll(List.of(table.build().split("\n")));
var TribeTableUpper = new AsciiTable(BorderStyle.UNICODE,1);
var TribeTableLower = new AsciiTable(BorderStyle.UNICODE,1);
String boardToString=AsciiTable.sideBySide(lines,lines2,1);
var table2 = new AsciiTable(BorderStyle.UNICODE, Math.max(getUpperListTribeCards().size(),getLowerListTribeCards().size()));
List<String> stringUp2=new ArrayList<>();
List<String> stringDown2=new ArrayList<>();
List<String> stringUpperListTribe=new ArrayList<>();
List<String> stringLowerListTribe=new ArrayList<>();
stringUpperListTribe.add("Char/Events");
stringLowerListTribe.add("Char/Events");
for(int i=0;i<Math.max(getUpperListTribeCards().size(),getLowerListTribeCards().size());i++)
{
if(i<getUpperListTribeCards().size())
{
stringUp2.add(getUpperListTribeCards().get(i).toStringBoard());
}
else
{
stringUp2.add("");
stringUpperListTribe.add(getUpperListTribeCards().get(i).toStringBoard());
}
if(i<getLowerListTribeCards().size())
{
stringDown2.add(getLowerListTribeCards().get(i).toStringBoard());
}
else
{
stringDown2.add("");
stringLowerListTribe.add(getLowerListTribeCards().get(i).toStringBoard());
}
}
table2.addRow(stringUp2);
table2.addRow(stringDown2);
var BuildTableUpper = new AsciiTable(BorderStyle.UNICODE,1);
BuildTableUpper.addHeader("Building ");
var BuildTableLower = new AsciiTable(BorderStyle.UNICODE,1);
BuildTableLower.addHeader("Building ");
var table3 = new AsciiTable(BorderStyle.UNICODE, Math.max(getUpperListBuilding().size(),getLowerListBuilding().size()));
List<String> stringUp3=new ArrayList<>();
List<String> stringDown3=new ArrayList<>();
for(int i=0;i<Math.max(getUpperListBuilding().size(),getLowerListBuilding().size());i++)
{
if(i<getUpperListBuilding().size())
{
stringUp3.add(getUpperListBuilding().get(i).toString());
}
else
{
stringUp3.add("-");
BuildTableUpper.addRow(getUpperListBuilding().get(i).toString());
}
if(i<getLowerListBuilding().size())
{
stringDown3.add(getLowerListBuilding().get(i).toString());
}
else
{
stringDown3.add("-");
BuildTableLower.addRow(getLowerListBuilding().get(i).toString());
}
}
table3.addRow(stringUp3);
table3.addRow(stringDown3);
String PlayerToString ="";
for(Player p:playersList)
{
PlayerToString+=p.toString()+"\n";
}
return PlayerToString+"\n"+ boardToString +"UPPERList\\LOWERList\n"+table2.build() + "\nBUILDING\n"+table3.build() + "\n";
//return s.toString()+"\n"++"\nOFFER TRACK\n"+ table.build()+"\n" ;
stringUpperListTribe.forEach(x->TribeTableUpper.addRow(x));
stringLowerListTribe.forEach(x->TribeTableLower.addRow(x));
offerTrack.addRow(stringUpOffer);
offerTrack.addRow(stringDownOffer);
return "CURRENT STATE\n"+getCurrentState()+"\n"+orderLogicCard.toString()+"\n"+ AsciiTable.sideBySide(Arrays.stream((TribeTableUpper.build().split("\n"))).toList(), Arrays.stream(BuildTableUpper.build().split("\n")).toList(),2)+"\n"+offerTrack.build()+"\n"+AsciiTable.sideBySide(List.of(TribeTableLower.build().split("\n")), Arrays.stream(BuildTableLower.build().split("\n")).toList(),2);
}
}
@@ -3,7 +3,12 @@ package it.polimi.ingsw.gc14.Model.GamePackage;
import it.polimi.ingsw.gc14.Model.Player;
import it.polimi.ingsw.gc14.Model.Slot;
import it.polimi.ingsw.gc14.Model.GamePackage.GameStages;
import it.polimi.ingsw.gc14.View.TUI.AsciiTable;
import it.polimi.ingsw.gc14.View.TUI.BorderStyle;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* Represents the current state of the game.
@@ -194,5 +199,27 @@ public class CurrentState implements Serializable {
}
}
@Override
public String toString(){
var table= new AsciiTable(BorderStyle.UNICODE,6);
List<String>header= new ArrayList<>();
header.add("Player");
header.add("NUpper");
header.add("NLower");
header.add("Round");
header.add("Era");
header.add("GameStage");
table.addRow(header);
table.addSeparator();
List<String>values= new ArrayList<>();
values.add(player.getUserName());
values.add(Integer.toString(NUpper));
values.add(Integer.toString(NLower));
values.add(Integer.toString(round));
values.add(Integer.toString(Era));
values.add(GameStage.toString());
table.addRow(values);
return table.build();
}
// endregion functions
}
@@ -12,9 +12,13 @@ import java.util.stream.Collectors;
public abstract class OrderLogicCard implements Serializable {
/**
* The queue of players associated with this order logic card.
* The queue of {@link Player Players} associated with this order logic card.
*/
protected Queue<Player> players;
/**
* The list of {@link Player Players} associated with this order logic card.
*/
protected List<OrderPlayer> playerList;
@@ -98,6 +102,12 @@ public abstract class OrderLogicCard implements Serializable {
player.addFood(1);
}
/**
* Returns the {@code Player}'s position based on it's {@code Username}.
* @param username The desired {@code Player}'s username.
* @return {@code int} - the {@code Player}'s position.
* @see Player
*/
protected int getPosition(String username)
{
int pos = 0;
@@ -26,7 +26,7 @@ public class Order2 extends OrderLogicCard {
/**
* Applies the effect associated with the specified position index for the given player.
* <p>If {@code index == 0}, the player gains 1 Food and the building effect is applied.
* <p>If {@code index == 1}, the player tries to remove 1 Food; if the player cannot remove it,
* <p>If {@code index == 1}, the player tries to remove 1 Food; if the player pay it,
* the player loses 2 Prestige.
*
* @param player the player to whom the effect is applied.
@@ -27,7 +27,8 @@ public class Order3 extends OrderLogicCard {
* Applies the effect associated with the specified position index for the given player.
* <p>If {@code index == 0}, the player gains 2 Food and the building effect is applied.
* <p>If {@code index == 1}, no effect is applied.
* <p>If {@code index == 2}, if the player can remove 1 Food, the player loses 2 Prestige.
* <p>If {@code index == 2}, the player tries to remove 1 Food; if the player pay it,
* the player loses 2 Prestige.
*
* @param player the player to whom the effect is applied.
* @param index the position index of the effect to apply.
@@ -47,7 +48,7 @@ public class Order3 extends OrderLogicCard {
return;
}
if(index==2){
if(player.removeFood(1)){
if(!player.removeFood(1)){
player.removePrestige(2);
}
}
@@ -28,7 +28,7 @@ public class Order4 extends OrderLogicCard {
* <p>If {@code index == 0}, the player gains 2 Food and the building effect is applied.
* <p>If {@code index == 1}, the player gains 1 Food and the building effect is applied.
* <p>If {@code index == 2}, no effect is applied.
* <p>If {@code index == 3}, the player tries to remove 1 Food; if the removal succeeds,
* <p>If {@code index == 3}, the player tries to remove 1 Food; if the player pay it,
* the player loses 2 Prestige.
*
* @param player the player to whom the effect is applied.
@@ -55,7 +55,7 @@ public class Order4 extends OrderLogicCard {
return;
}
if(index==3){
if(player.removeFood(1)){
if(!player.removeFood(1)){
player.removePrestige(2);
}
}
@@ -29,7 +29,7 @@ public class Order5 extends OrderLogicCard {
* <p>If {@code index == 1}, the player gains 1 Food and the building effect is applied.
* <p>If {@code index == 2}, no effect is applied.
* <p>If {@code index == 3}, no effect is applied.
* <p>If {@code index == 4}, the player tries to remove 1 Food; if the removal succeeds,
* <p>If {@code index == 4}, the player tries to remove 1 Food; if the player pay it,
* the player loses 2 Prestige.
*
* @param player the player to whom the effect is applied.
@@ -56,7 +56,7 @@ public class Order5 extends OrderLogicCard {
return;
}
if(index==4){
if(player.removeFood(1)){
if(!player.removeFood(1)){
player.removePrestige(2);
}
}
@@ -2,12 +2,15 @@ package it.polimi.ingsw.gc14.Model.Orders;
import it.polimi.ingsw.gc14.Model.Player;
import java.io.Serializable;
/**
* Abstract base class for all order logic cards.
* An OrderLogicCard manages a queue of players and defines the effects
* applied when players are pushed back into the queue.
* Abstract base class for all order {@code logic cards}.
* An {@code OrderLogicCard} manages a queue of {@code players} and defines the effects
* applied when they are pushed back into the queue.
* @see it.polimi.ingsw.gc14.Model.Player Player
*/
public class OrderPlayer{
public class OrderPlayer implements Serializable {
public Player player;
public boolean played;
public OrderPlayer(Player player,boolean played){
@@ -45,6 +45,14 @@ public abstract class PlayableCard implements Serializable {
public String toString() {
return "⎕:";
}
/**
* Prints a string representation of this {@code PlayableCard}. This specific variation is used in the {@code Game}'s
* toString to print a more detailed version (in this specific case the two methods are equal).
* @return {@code String} - a string representation of this {@code PlayableCard}.
* @see it.polimi.ingsw.gc14.Model.Game Game
* @see it.polimi.ingsw.gc14.Model.GamePackage.Board Board
*/
public String toStringBoard()
{
return "⎕:";
@@ -8,7 +8,6 @@ import it.polimi.ingsw.gc14.View.TUI.AsciiTable;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static it.polimi.ingsw.gc14.View.TUI.BorderStyle.*;
@@ -125,13 +124,6 @@ public class Player implements Serializable {
public int getPrestigeValue() {
return PrestigeValue;
}
/* TODO
* private Game game;
* public Game getGame(){
* return Game;
* }
*/
// endregion getters
// region Setters
@@ -228,17 +220,34 @@ public class Player implements Serializable {
// endregion constructors
// region Functions
/**
* Prints the {@code Player}'s attributes for the {@code Board}'s representation.
* Uses the {@code UNICODE} border style.
* <p><b>Includes:</b>
* <li>{@link #FoodValue Food}
* <li>{@link #PrestigeValue Prestige}
* <li>{@link #artists Artists}
* <li>{@link #builders Builders}
* <li>{@link #gatherers Gatherers}
* <li>{@link #shamans Shamans}
* <li>{@link #inventors Inventors}
* <li>{@link #hunters Hunters}
* <li>{@link #buildingCards Buildings}
* </p>
* @return {@code String} - A string representation of the {@code Player}'s attributes.
* @see it.polimi.ingsw.gc14.View.TUI.BorderStyle BorderStyle
*/
@Override
public String toString() {
int Last = 6;
int Last = -1;
var table = new AsciiTable(UNICODE, 1);
table.addHeader(this.getUserName());
table.addRow("RESOURCES:");
table.addRow("Food: " + this.getFoodValue());
table.addSeparator();
table.addRow("Prestige: " + this.getPrestigeValue());
table.addSeparator();
if(!this.hunters.isEmpty()){
Last = 6;
@@ -267,44 +276,44 @@ public class Player implements Serializable {
}
table.addRow("CHARACTERS:");
if(!this.artists.isEmpty()){
table.addRow("Artists: " + this.artists.toString());
if(Last == 1){
table.addSeparator();
}
table.addRow("Artists: " + this.artists.toString());
}
if(!this.builders.isEmpty()){
table.addRow("Builders: " + this.builders.toString());
if(Last == 2){
table.addSeparator();
}
table.addRow("Builders: " + this.builders.toString());
}
if(!this.gatherers.isEmpty()){
table.addRow("Gatherers: " + this.gatherers.toString());
if(Last == 3){
table.addSeparator();
}
table.addRow("Gatherers: " + this.gatherers.toString());
}
if(!this.shamans.isEmpty()){
table.addRow("Shamans: " + this.shamans.toString());
if(Last == 4){
table.addSeparator();
}
table.addRow("Shamans: " + this.shamans.toString());
}
if(!this.inventors.isEmpty()){
table.addRow("Inventors: " + this.inventors.toString());
if(Last == 5){
table.addSeparator();
}
table.addRow("Inventors: " + this.inventors.toString());
}
if(!this.hunters.isEmpty()){
table.addSeparator();
table.addRow("Hunters: " + this.hunters.toString());
table.addSeparator();
}
table.addRow("BUILDING CARDS:");
@@ -156,6 +156,19 @@ public class Slot implements Serializable {
}
/**
* Prints a string representation of this {@code Slot}. This specific variation is used in the {@code Game}'s
* toString to print a more detailed version for the TUI implementation.
* <p>includes:
* <li>{@link #slotId SlotId}
* <li>{@link #NUpper NUpper}
* <li>{@link #NLower NLower}
* <li>{@link #Food Food}
* </p>
* @return {@code String} - a string representation of this {@code Slot}.
* @see it.polimi.ingsw.gc14.Model.Game Game
* @see it.polimi.ingsw.gc14.Model.GamePackage.Board Board
*/
public String toStringTUI()
{
StringBuilder s = new StringBuilder();
@@ -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) ;
}
@@ -4,23 +4,39 @@ import it.polimi.ingsw.gc14.Controller.GameController;
import java.io.Serializable;
//TODO javadoc
public abstract class NetworkEvent implements Serializable {
//TODO javadoc
protected String username;
//TODO javadoc
public String getUsername() {
return username;
}
//TODO javadoc
protected EventType eventType;
//TODO javadoc
public EventType getEventType() {return eventType;}
//TODO javadoc
protected boolean isError;
//TODO javadoc
public boolean getIsError() {return isError;}
//TODO javadoc
public void setIsError(boolean isError) {this.isError = isError;}
//TODO javadoc
protected NetworkEvent(String username, EventType eventType, boolean isError) {
this.username = username;
this.eventType = eventType;
this.isError = isError;
}
//TODO javadoc
@Override
public String toString() {
if(isError) {
@@ -30,5 +46,6 @@ public abstract class NetworkEvent implements Serializable {
}
}
//TODO javadoc
public abstract boolean apply(GameController gameController);
}
@@ -7,15 +7,23 @@ import it.polimi.ingsw.gc14.View.IView;
import java.io.Serializable;
//TODO javadoc
public class AddPlayer extends NetworkEvent implements Serializable {
//TODO javadoc
private int proposedNPlayer;
//TODO javadoc
public int getProposedNPlayer() {
return proposedNPlayer;
}
//TODO javadoc
public AddPlayer(String username, int proposedNPlayer) {
super(username, EventType.ADD_PLAYER, false);
this.proposedNPlayer = proposedNPlayer;
}
//TODO javadoc
@Override
public boolean apply(GameController gameController)
{
@@ -7,19 +7,24 @@ import it.polimi.ingsw.gc14.View.IView;
import java.io.Serializable;
//TODO javadoc
public class DrawLowerBuildingCard extends NetworkEvent implements Serializable{
//TODO javadoc
private int pos;
//TODO javadoc
public DrawLowerBuildingCard(String username, int pos){
super(username, EventType.DRAW_LOWER_BUILD, false);
this.pos = pos;
}
//TODO javadoc
@Override
public boolean apply(GameController gameController){
return gameController.drawLowerBuildingCard(username, pos);
}
//TODO javadoc
public String apply(IView gameController){
return gameController.toString();
}
@@ -8,18 +8,22 @@ import it.polimi.ingsw.gc14.View.IView;
import java.io.Serializable;
public class DrawLowerTribeCard extends NetworkEvent implements Serializable{
//TODO javadoc
private int pos;
//TODO javadoc
public DrawLowerTribeCard(String username, int pos){
super(username, EventType.DRAW_LOWER_TRIBE, false);
this.pos = pos;
}
//TODO javadoc
@Override
public boolean apply(GameController gameController){
return gameController.drawLowerTribeCard(username, pos);
}
//TODO javadoc
public String apply(IView gameController){
return gameController.toString();
}
@@ -7,19 +7,24 @@ import it.polimi.ingsw.gc14.View.IView;
import java.io.Serializable;
//TODO javadoc
public class DrawUpperBuildingCard extends NetworkEvent implements Serializable{
//TODO javadoc
private int pos;
//TODO javadoc
public DrawUpperBuildingCard(String username, int pos){
super(username, EventType.DRAW_UPPER_BUILD, false);
this.pos = pos;
}
//TODO javadoc
@Override
public boolean apply(GameController gameController){
return gameController.drawUpperBuildingCard(username, pos);
}
//TODO javadoc
public String apply(IView gameController){
return gameController.toString();
}
@@ -7,19 +7,24 @@ import it.polimi.ingsw.gc14.View.IView;
import java.io.Serializable;
//TODO javadoc
public class DrawUpperTribeCard extends NetworkEvent implements Serializable{
//TODO javadoc
private int pos;
//TODO javadoc
public DrawUpperTribeCard(String username, int pos){
super(username, EventType.DRAW_UPPER_TRIBE, false);
this.pos = pos;
}
//TODO javadoc
@Override
public boolean apply(GameController gameController){
return gameController.drawUpperTribeCard(username, pos);
}
//TODO javadoc
public String apply(IView gameController){
return gameController.toString();
}
@@ -7,19 +7,24 @@ import it.polimi.ingsw.gc14.View.IView;
import java.io.Serializable;
//TODO javadoc
public class PickOptionalBuildingCard extends NetworkEvent implements Serializable{
//TODO javadoc
private int pos;
//TODO javadoc
public PickOptionalBuildingCard(String username, int pos){
super(username, EventType.PICK_OPTIONAL_BUILD, false);
this.pos = pos;
}
//TODO javadoc
@Override
public boolean apply(GameController gameController){
return gameController.pickOptionalBuildingCard(username, pos);
}
//TODO javadoc
public String apply(IView gameController){
return gameController.toString();
}
@@ -7,19 +7,25 @@ import it.polimi.ingsw.gc14.View.IView;
import java.io.Serializable;
//TODO javadoc
public class PickOptionalTribeCard extends NetworkEvent implements Serializable{
//TODO javadoc
private int pos;
//TODO javadoc
public PickOptionalTribeCard(String username, int pos){
super(username, EventType.PICK_OPTIONAL_TRIBE, false);
this.pos = pos;
}
//TODO javadoc
@Override
public boolean apply(GameController gameController){
return gameController.pickOptionalTribeCard(username, pos);
}
//TODO javadoc
public String apply(IView gameController){
return gameController.toString();
}
@@ -7,19 +7,24 @@ import it.polimi.ingsw.gc14.View.IView;
import java.io.Serializable;
//TODO javadoc
public class SlotChoice extends NetworkEvent implements Serializable {
//TODO javadoc
private int pos;
//TODO javadoc
public SlotChoice(String username, int pos) {
super(username, EventType.SLOT_CHOICE, false);
this.pos = pos;
}
//TODO javadoc
@Override
public boolean apply(GameController gameController) {
return gameController.slotChoice(username, pos);
}
//TODO javadoc
public String apply(IView gameController) {
return gameController.toString();
}
@@ -39,6 +39,7 @@ public class ClientCallbackImpl extends UnicastRemoteObject implements IClientCa
@Override
public void onGameInit(Game model) throws RemoteException {
clientController.setModel(model);
clientController.view.render();
}
@@ -55,7 +56,7 @@ public class ClientCallbackImpl extends UnicastRemoteObject implements IClientCa
System.out.println(event.toString());
} else {
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 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.RMI.Common.IClientCallback;
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.
*/
public class RMIClient {
public class RMIClient implements IClient {
/** The host address of the RMI server */
private final String host;
@@ -22,32 +23,36 @@ public class RMIClient {
/** The remote stub used to call methods on the server */
private IGameServer stub;
/** Client game's controller */
ClientController controller;
/**
* Class constructor.
* @param controller the client controller used to create the callback
* @param host the host address 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.port = port;
}
//TODO Javadoc fix
/**
* Connects to the RMI server and attempts to join the game.
* Looks up the RMI registry to retrieve the {@link IGameServer} stub.
* Then, creates a {@link ClientCallbackImpl} and calls {@link RMIServer#joinGame(String, int, IClientCallback)}.
* @param username the player's username
* @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
*/
public boolean connect(String username,int preferredInt, ClientController clientController) {
public boolean connect(String username,int preferredInt) {
try {
Registry registry = LocateRegistry.getRegistry(host, port);
this.stub = (IGameServer) registry.lookup("RMIGameServer");
ClientCallbackImpl callback = new ClientCallbackImpl(clientController);
ClientCallbackImpl callback = new ClientCallbackImpl(controller);
return stub.joinGame(username, preferredInt, callback);
}
@@ -63,8 +68,12 @@ public class RMIClient {
* @param event the event to send
* @throws RemoteException if any RMI error occurs
*/
public void doEvent(NetworkEvent event) throws RemoteException {
stub.doEvent(event);
public void doEvent(NetworkEvent event) {
try {
stub.doEvent(event);
}catch (Exception e) {
}
}
}
@@ -1,7 +1,8 @@
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.Network.IClient;
import it.polimi.ingsw.gc14.Network.NetworkEvent;
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.
*/
public class TCPClient {
public class TCPClient implements IClient {
/** Socket TCP */
Socket communicationSocket;
@@ -23,7 +24,7 @@ public class TCPClient {
ObjectOutputStream socketSend;
/** Client game's controller */
GameController controller;
ClientController controller;
/** IP address of the server to connect to */
String hostname;
@@ -38,7 +39,7 @@ public class TCPClient {
* @param hostname The IP address 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.hostname = hostname;
this.port = port;
@@ -53,13 +54,15 @@ public class TCPClient {
* @param proposedNPlayers The desired number of players for the game
* @return true if the connection is successful, false otherwise.
*/
public boolean start(String user, int proposedNPlayers) {
public boolean connect(String user, int proposedNPlayers) {
try {
communicationSocket = new Socket(hostname, port);
socketSend = new ObjectOutputStream(communicationSocket.getOutputStream());
socketReceive = new ObjectInputStream(communicationSocket.getInputStream());
sendEvent(new AddPlayer(user, proposedNPlayers));
doEvent(new AddPlayer(user, proposedNPlayers));
if (communicationSocket.getInputStream().read() == -1) {
System.out.println("Could not connect to server");
return false;
@@ -89,11 +92,12 @@ public class TCPClient {
if (event.getIsError()) {
System.out.println(event);
} else {
event.apply(controller);
//clientController.view.update(); TODO
event.apply(controller.localController);
controller.view.render();
}
} else if (read instanceof Game model) {
controller.setModel(model);
controller.view.render();
}
} catch (IOException e) {
e.printStackTrace();
@@ -108,7 +112,7 @@ public class TCPClient {
* Sends a {@link NetworkEvent} to the server.
* @param event The NetworkEvent to send.
*/
private void sendEvent(NetworkEvent event) {
public void doEvent(NetworkEvent event) {
try {
socketSend.writeObject(event);
} catch (IOException e) {
@@ -41,8 +41,10 @@ public class ClientHandler implements Runnable {
* @param clientHandlers The shared list of all active client handlers
* @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.in = in;
this.out = out;
this.clientHandlers = clientHandlers;
this.actionQueue = actionQueue;
}
@@ -55,8 +57,7 @@ public class ClientHandler implements Runnable {
@Override
public void run() {
try {
in = new ObjectInputStream(clientSocket.getInputStream());
out = new ObjectOutputStream(clientSocket.getOutputStream());
while (true) {
NetworkEvent event = (NetworkEvent) in.readObject();
if (!actionQueue.add(event)) {
@@ -76,15 +77,13 @@ public class ClientHandler implements Runnable {
* Sends a {@link NetworkEvent} to the client.
* @param event The network event to send to the client.
*/
public void notifyEvent(NetworkEvent event) {
synchronized (out) {
try {
out = new ObjectOutputStream(clientSocket.getOutputStream());
out.writeObject(event);
} catch (IOException e) {
e.printStackTrace();
}
public synchronized void notifyEvent(NetworkEvent event) {
try {
out.writeObject(event);
} catch (IOException e) {
e.printStackTrace();
}
}
@@ -92,14 +91,11 @@ public class ClientHandler implements Runnable {
* Sends the current game model to this client.
* @param game The current state of the game to send to the client.
*/
public void notifyModel(Game game) {
synchronized (out) {
try {
out = new ObjectOutputStream(clientSocket.getOutputStream());
out.writeObject(game);
} catch (IOException e) {
e.printStackTrace();
}
public synchronized void notifyModel(Game game) {
try {
out.writeObject(game);
} catch (IOException e) {
e.printStackTrace();
}
}
}
@@ -88,8 +88,9 @@ public class TCPServer {
try{
clientSocket = socketTCP.accept();
ObjectInputStream clientSocketObj = new ObjectInputStream(clientSocket.getInputStream());
NetworkEvent event = (NetworkEvent) clientSocketObj.readObject();
ObjectOutputStream clientSend = new ObjectOutputStream(clientSocket.getOutputStream());
ObjectInputStream clientReceive = new ObjectInputStream(clientSocket.getInputStream());
NetworkEvent event = (NetworkEvent) clientReceive.readObject();
if(!(event.getEventType() == EventType.ADD_PLAYER)){
clientSocket.getOutputStream().write((int)(-1));
@@ -114,7 +115,7 @@ public class TCPServer {
clientSocket.getOutputStream().write((int) (1));
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);
ConnectedPlayers++;
@@ -4,9 +4,9 @@ import it.polimi.ingsw.gc14.Model.Game;
import it.polimi.ingsw.gc14.Network.NetworkEvent;
public interface IView {
void render(Game model);
void showMessage(String message);
void showError(String message);
public void update(Game game);
public void render();
public void showMessage(String message);
public void showError(String message);
}
@@ -1,22 +1,40 @@
package it.polimi.ingsw.gc14.View.TUI;
import java.util.*;
//TODO javadoc
// Helper generale per costruire tabelle ASCII
public class AsciiTable {
//TODO javadoc
private final BorderStyle s;
//TODO javadoc
private final int cols;
//TODO javadoc
private final List<List<String>> rows = new ArrayList<>();
//TODO javadoc
private final List<Integer> separators = new ArrayList<>();
//TODO javadoc
public AsciiTable(BorderStyle s, int cols) {
this.s = s; this.cols = cols;
}
//TODO javadoc
public void addRow(String... cells) { rows.add(Arrays.asList(cells)); }
public void addRow(List<String> cells) { rows.add(cells); }
public void addHeader(String... cells) { rows.add(0, Arrays.asList(cells)); separators.add(0); }
public void addSeparator() { separators.add(rows.size()); }
//TODO javadoc
public void addRow(List<String> cells) { rows.add(cells); }
//TODO javadoc
public void addHeader(String... cells) { rows.add(0, Arrays.asList(cells)); separators.add(0); }
public void addSeparator() { separators.add(rows.size()-1); }
//TODO javadoc
public void addSeparator() { separators.add(rows.size()-1); }
//TODO javadoc
public String build() {
var sb = new StringBuilder();
int maxWidth = rows.stream().mapToInt(x->x.stream().mapToInt(y->y.length()).max().getAsInt()).max().getAsInt()+1;
@@ -34,6 +52,7 @@ public class AsciiTable {
return sb.toString();
}
//TODO javadoc
private String hline(String l, String m, String r,int maxWidth) {
var sb = new StringBuilder(l);
for (int i = 0; i < cols; i++) {
@@ -43,10 +62,13 @@ public class AsciiTable {
return sb.append(r).toString();
}
//TODO javadoc
private static String rpad(String s, int w) {
if (s.length() >= w) return s.substring(0, w);
return s + " ".repeat(w - s.length());
}
//TODO javadoc
public static String sideBySide(List<String> left, List<String> right, int gap) {
int leftWidth = left.stream().mapToInt(String::length).max().orElse(0);
int maxHeight = Math.max(left.size(), right.size());
@@ -1,93 +1,103 @@
//package it.polimi.ingsw.gc14.View.TUI;
//import it.polimi.ingsw.gc14.Model.Game;
//
//public class TUI {
//
// // dati di stato
// private BorderStyle style = BorderStyle.UNICODE;
// private Game model;
// // punto di ingresso
// public String render() {
// var sb = new StringBuilder();
// sb.append(renderHeader());
// sb.append(renderTurnOrder());
// sb.append(renderOfferTrack());
// sb.append(renderCardRows());
// sb.append(renderTableaux());
// sb.append(renderFooter());
// return sb.toString();
// }
//
// // sezioni
// private String renderTurnOrder() {
// var table = new AsciiTable(style, 4, 10); // 4 colonne, largh 10
// table.addRow(model.getPlayers().stream()
// .map(p -> + ". " + p.getUserName())
// .toList());
// table.addRow(state.getPlayers().stream()
// .map(p -> p.getTotemPosition() != null
// ? "totem: " + p.getTotemPosition()
// : "(da piaz)")
// .toList());
// return " TURN ORDER\n" + table.build() + "\n";
// }
//
// private String renderOfferTrack() {
// var table = new AsciiTable(style, 5, 14);
// table.addRow(state.getOfferTiles().stream()
// .map(t -> t.getId() + ": " + t.getLabel()).toList());
// table.addRow(state.getOfferTiles().stream()
// .map(OfferTile::getRowsLabel).toList());
// table.addRow(state.getOfferTiles().stream()
// .map(t -> state.getTotemOnTile(t.getId())).toList());
// return " OFFER TRACK\n" + table.build() + "\n";
// }
//
// private String renderCardRows() {
// int cols = state.getTopRow().size();
// var table = new AsciiTable(style, cols, 13);
// table.addRow(state.getTopRow().stream()
// .map(c -> "[" + c.getTypeLabel() + "]").toList());
// table.addRow(state.getTopRow().stream()
// .map(Card::getName).toList());
// table.addSeparator();
// table.addRow(state.getBotRow().stream()
// .map(c -> "[" + c.getTypeLabel() + "]").toList());
// table.addRow(state.getBotRow().stream()
// .map(Card::getName).toList());
// return " CARTE IN GIOCO\n" + prefix("TOP ", "BOT ", table.build()) + "\n";
// }
//
// private String renderTableaux() {
// var sb = new StringBuilder(" TABLEAU GIOCATORI\n\n");
// for (Player p : state.getPlayers()) {
// String marker = p.isActive() ? ">>>" : " ";
// sb.append(String.format(" %s %s%s Food:%d PP:%d%n",
// marker, p.getName(),
// p.isActive() ? " [TUO TURNO]" : "",
// p.getFood(), p.getPP()));
// sb.append(renderPlayerTableau(p));
// sb.append("\n");
// }
// return sb.toString();
// }
//
// private String renderPlayerTableau(Player p) {
// var table = new AsciiTable(style, 3, 14);
// table.addHeader("PERSONAGGI", "EDIFICI", "RISORSE");
// int rows = Math.max(p.getChars().size(),
// Math.max(p.getBuildings().size(), 3));
// for (int i = 0; i < rows; i++) {
// String ch = i < p.getChars().size() ? p.getChars().get(i) : "";
// String bd = i < p.getBuildings().size() ? p.getBuildings().get(i) : "";
// String rs = switch (i) {
// case 0 -> "Food: " + "O".repeat(p.getFood());
// case 1 -> "PP: " + p.getPP();
// case 2 -> "Chars:" + p.getChars().size() + " Edif:" + p.getBuildings().size();
// default -> "";
// };
// table.addRow(ch, bd, rs);
// }
// return " " + table.build().replace("\n", "\n ");
// }
//}
package it.polimi.ingsw.gc14.View.TUI;
import it.polimi.ingsw.gc14.Model.Game;
import it.polimi.ingsw.gc14.View.IView;
public class TUI implements IView {
// dati di stato
private BorderStyle style = BorderStyle.UNICODE;
private Game model;
private String username;
public TUI(Game 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
public void render()
{
try{
String os = System.getProperty("os.name").toLowerCase();
ProcessBuilder pb;
if (os.contains("win")) {
pb = new ProcessBuilder("cmd", "/c", "cls");
} else {
pb = new ProcessBuilder("clear");
}
pb.inheritIO().start().waitFor();
}
catch(Exception e){
}
System.out.println(model.toString());
}
public void renderBoard()
{
try{
String os = System.getProperty("os.name").toLowerCase();
ProcessBuilder pb;
if (os.contains("win")) {
pb = new ProcessBuilder("cmd", "/c", "cls");
} else {
pb = new ProcessBuilder("clear");
}
pb.inheritIO().start().waitFor();
}
catch(Exception e){
}
System.out.println(model.BoardStamp());
}
public void renderPlayer()
{
try{
String os = System.getProperty("os.name").toLowerCase();
ProcessBuilder pb;
if (os.contains("win")) {
pb = new ProcessBuilder("cmd", "/c", "cls");
} else {
pb = new ProcessBuilder("clear");
}
pb.inheritIO().start().waitFor();
}
catch(Exception e){
}
System.out.println(model.BoardStamp());
}
public void renderMyHand()
{
try{
String os = System.getProperty("os.name").toLowerCase();
ProcessBuilder pb;
if (os.contains("win")) {
pb = new ProcessBuilder("cmd", "/c", "cls");
} else {
pb = new ProcessBuilder("clear");
}
pb.inheritIO().start().waitFor();
}
catch(Exception e){
}
System.out.println(model.getPlayerByUsername(username));
}
public void showMessage(String message)
{
System.out.println(message);
}
public void showError(String message)
{
System.out.println(message);
}
}