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

This commit is contained in:
rubenpirreram
2026-04-21 15:07:18 +02:00
40 changed files with 1810 additions and 90 deletions
@@ -0,0 +1,29 @@
package it.polimi.ingsw.gc14.Controller;
import it.polimi.ingsw.gc14.Model.Game;
import it.polimi.ingsw.gc14.Network.Observer;
import it.polimi.ingsw.gc14.View.IView;
public class ClientController {
private Game localModel;
public GameController localController;
private final IView view;
public ClientController(IView view,Game localModel) {
this.view = view;
this.localModel = localModel;
this.localController = new GameController(localModel);
}
public void setModel(Game model) {
this.localModel = model;
localController.setModel(model);
localModel.addObserver((Observer) view); // registra la view come observer
}
public void onError(String message) {
view.showError(message);
}
}
@@ -3,37 +3,114 @@ package it.polimi.ingsw.gc14.Controller;
import it.polimi.ingsw.gc14.Model.Game;
import it.polimi.ingsw.gc14.Model.Player;
/**
* Controller class that manages interactions between the client-side logic
* and the {@link Game} model.
* It provides methods to add players and to perform game actions by delegating them to the model.
*/
public class GameController {
/**
* The game model managed by this controller.
*/
private Game model;
/**
* Creates a GameController associated with the specified game model.
*
* @param model the game model managed by this controller.
*/
public GameController(Game model) {
this.model = model;
}
/**
* Creates a GameController without an associated game model.
*/
public GameController() {
}
/**
* Returns the game model managed by this controller.
*
* @return the game model managed by this controller.
*/
public Game getModel() {
return model;
}
/**
* Updates the game model managed by this controller.
*
* @param model the new game model managed by this controller.
*/
public void setModel(Game model) {
this.model = model;
}
/**
* Attempts to add a new player with the specified username to the game model.
*
* @param username the username of the player to add.
* @return {@code true} if the player is successfully added, {@code false} otherwise.
*/
public boolean addPlayer(String username) {
return model.addPlayer(new Player(username));
}
/**
* 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 boolean drawUpperTribeCard(String playerUsername,int pos) {
Player player= model.getPlayerByUsername(playerUsername);
if(player==null)
return false;
return model.DrawUpperTribeCardByIndex(model.getPlayerByUsername(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 boolean drawLowerTribeCard(String playerUsername,int pos) {
Player player= model.getPlayerByUsername(playerUsername);
if(player==null)
return false;
return model.DrawLowerTribeCardByIndex(model.getPlayerByUsername(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 boolean drawUpperBuildingCard(String playerUsername,int pos) {
Player player= model.getPlayerByUsername(playerUsername);
if(player==null)
return false;
return model.DrawUpperBuildingCardByIndex(model.getPlayerByUsername(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 boolean drawLowerBuildingCard(String playerUsername,int pos) {
Player player= model.getPlayerByUsername(playerUsername);
if(player==null)
@@ -41,18 +118,44 @@ public class GameController {
return model.DrawLowerBuildingCardByIndex(model.getPlayerByUsername(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 boolean pickOptionalTribeCard(String playerUsername,int pos) {
Player player= model.getPlayerByUsername(playerUsername);
if(player==null)
return false;
return model.PickOptionalTribeCardByIndex(model.getPlayerByUsername(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 boolean pickOptionalBuildingCard(String playerUsername,int pos) {
Player player= model.getPlayerByUsername(playerUsername);
if(player==null)
return false;
return model.PickOptionalBuildingCard(model.getPlayerByUsername(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 boolean slotChoice(String playerUsername,int pos) {
Player player= model.getPlayerByUsername(playerUsername);
if(player==null)//playerIndex>=model.)
@@ -5,28 +5,79 @@ import it.polimi.ingsw.gc14.Model.Cards.Building.EffectType;
import it.polimi.ingsw.gc14.Model.PlayableCard;
import it.polimi.ingsw.gc14.Model.Player;
import java.io.Serializable;
import java.util.ArrayList;
public class BuildingCard extends PlayableCard implements Cloneable , BuildingEffect {
public class BuildingCard extends PlayableCard implements Cloneable , BuildingEffect, Serializable {
/**
* The price of this building card.
*/
private int price;
/**
* Returns the price of this building card.
*
* @return the price of this building card.
*/
public int getPrice() {
return price;
}
/**
* Indicates whether this building card has already been bought.
*/
private boolean bought;
/**
* The type of effect associated with this building card.
*/
protected EffectType effectType;
/**
* The identifier of the effect associated with this building card.
*/
protected int effectId;
/**
* The prestige value of this building card.
*/
private int prestigeValue;
/**
* Returns the prestige value of this building card.
*
* @return the prestige value of this building card.
*/
public int getPrestigeValue() {
return prestigeValue;
}
/**
* Returns the identifier of the effect associated with this building card.
*
* @return the effect identifier of this building card.
*/
public int getEffectId() {
return effectId;
}
/**
* Returns the type of effect associated with this building card.
*
* @return the effect type of this building card.
*/
public EffectType getEffectType() {
return effectType;
}
public BuildingCard(int era,int price,int prestigeValue) throws IllegalArgumentException{
/**
* Creates a building card with the specified era, price, and prestige value.
*
* @param era the era of the building card.
* @param price the price of the building card.
* @param prestigeValue the prestige value of the building card.
* @throws IllegalArgumentException if {@code price <= 0} or {@code prestigeValue < 0}
*/
protected BuildingCard(int era,int price,int prestigeValue) throws IllegalArgumentException{
super(era);
if (price > 0) {
this.price = price;
@@ -41,6 +92,20 @@ public class BuildingCard extends PlayableCard implements Cloneable , BuildingEf
bought = false;
}
/**
* Creates a building card with the specified effect identifier, era, price,
* and prestige value.
* The effect type is determined from the given effect identifier.
*
* @param effectId the identifier of the effect associated with the building card.
* @param era the era of the building card.
* @param price the price of the building card.
* @param prestigeValue the prestige value of the building card.
* @throws IllegalArgumentException if the effect identifier is not valid,
* if {@code price <= 0}, or if {@code prestigeValue < 0}
*/
public BuildingCard(int effectId ,int era,int price,int prestigeValue) throws IllegalArgumentException{
this.effectId = effectId;
switch (effectId){
@@ -72,12 +137,28 @@ public class BuildingCard extends PlayableCard implements Cloneable , BuildingEf
this(era,price,prestigeValue);
}
/**
* Creates and returns a copy of this building card.
*
* @return a clone of this building card.
*/
@Override
public BuildingCard clone()
{
return new BuildingCard(effectId,getEra(),getPrice(),getPrestigeValue());
}
/**
* Attempts to buy this building card for the specified player.
* The purchase succeeds only if the card has not already been bought
* and the player can pay its price in Food.
* If the purchase succeeds, the card is added to the player's building cards
* and marked as bought.
*
* @param player the player attempting to buy the building card.
* @return {@code true} if the building card is successfully bought,
* {@code false} otherwise.
*/
public boolean buy(Player player) {
if( bought || !player.removeFood(getPrice()))
return false;
@@ -85,8 +166,20 @@ public class BuildingCard extends PlayableCard implements Cloneable , BuildingEf
bought=true;
return true;
}
/**
* Applies the effect of this building card to the specified player.
*
* @param player the player to whom the effect is applied.
*/
@Override
public void applyEffect(Player player){};
/**
* Returns the string representation of this building card.
*
* @return the string representation of this building card.
*/
@Override
public String toString() {
return "Era:"+String.valueOf(getEra())+" Price:"+String.valueOf(getPrice())+" Prestige:"+String.valueOf(getPrestigeValue());
@@ -2,25 +2,74 @@ package it.polimi.ingsw.gc14.Model.Cards;
import it.polimi.ingsw.gc14.Model.Cards.TribeCards.Character;
import it.polimi.ingsw.gc14.Model.PlayableCard;
import java.io.Serializable;
public abstract class TribeCard extends PlayableCard {
/**
* Abstract base class for all tribe cards.
* A TribeCard is a {@link PlayableCard} that may either be an event card
* or a non-event card, and may optionally specify a minimum number of players.
*/
public abstract class TribeCard extends PlayableCard implements Serializable {
/**
* Indicates whether this tribe card is an event card.
*/
private boolean isEventCard;
/**
* Returns whether this tribe card is an event card.
*
* @return {@code true} if this card is an event card, {@code false} otherwise.
*/
public boolean IsEventCard() {
return isEventCard;
}
/**
* The minimum number of players required for this tribe card.
*/
private int nMin=0;
/**
* Returns the minimum number of players required for this tribe card.
*
* @return the minimum number of players required for this tribe card.
*/
public int getNMin() {
return nMin;
}
/**
* Creates a tribe card with the specified era and event-card flag.
* The minimum number of players is set to 0.
*
* @param Era the era of the tribe card.
* @param isEventCard whether the card is an event card.
*/
public TribeCard(int Era,boolean isEventCard) {
this(Era,isEventCard,0);
}
/**
* Creates a tribe card with the specified era, event-card flag,
* and minimum number of players.
*
* @param Era the era of the tribe card.
* @param isEventCard whether the card is an event card.
* @param nMin the minimum number of players required for the card.
*/
public TribeCard(int Era,boolean isEventCard,int nMin) {
super(Era);
this.nMin=nMin;
this.isEventCard=isEventCard;
}
/**
* Creates and returns a copy of this tribe card.
*
* @return a clone of this tribe card.
*/
@Override
public abstract TribeCard clone();
}
@@ -3,29 +3,75 @@ package it.polimi.ingsw.gc14.Model.Cards.TribeCards;
import it.polimi.ingsw.gc14.Model.Cards.TribeCard;
import it.polimi.ingsw.gc14.Model.Player;
/**
* Abstract base class for all character cards.
* A Character is a {@link TribeCard} that is not an event card and is associated.
* with a specific {@link CharacterType}.
*/
public abstract class Character extends TribeCard implements Cloneable {
/**
* The specific type of this character card.
*/
private CharacterType type;
/**
* Returns the type of this character card.
*
* @return the type of this character card.
*/
public CharacterType getType() {
return type;
}
/**
* Creates a character card with the specified era and character type.
*
* @param Era the era of the character card.
* @param type the type of the character card.
*/
public Character(int Era, CharacterType type){
super(Era,false );
this.type = type;
}
/**
* Creates a character card with the specified era, character type,
* and minimum number of players.
*
* @param Era the era of the character card.
* @param type the type of the character card.
* @param nMin the minimum number of players required for the card.
*/
public Character(int Era, CharacterType type,int nMin){
super(Era,false ,nMin);
this.type = type;
}
/**
* Returns the string representation of this character card.
* The returned string includes the string representation of the superclass
* and the string representation of the character type.
*
* @return the string representation of this character card.
*/
@Override
public String toString() {
return super.toString()+" "+type.toString();
}
/**
* Creates and returns a copy of this character card.
*
* @return a clone of this character card.
*/
@Override
public abstract Character clone();
/**
* Inserts this character card into the appropriate collection of the specified player.
*
* @param player the player who receives the character card.
*/
public abstract void insert(Player player);
}
@@ -6,13 +6,37 @@ import it.polimi.ingsw.gc14.Model.Player;
import java.util.ArrayList;
import java.lang.reflect.Array;
/**
* Abstract base class for all event cards.
* An EventCard is a {@link TribeCard} marked as an event card and associated.
* with a specific {@link EventType}.
*/
public abstract class EventCard extends TribeCard {
// Getters
/**
* The specific type of this event card.
*/
private EventType type;
/**
* Returns the type of this event card.
*
* @return the type of this event card.
*/
public EventType getType() { return type; }
// End getters
// Constructors
/**
* Creates an event card with the specified era and event type.
*
* @param Era the era of the event card.
* @param type the type of the event card.
*/
public EventCard(int Era, EventType type) {
super(Era,true);
this.type = type;
@@ -20,15 +44,34 @@ public abstract class EventCard extends TribeCard {
// End Constructors
// Function
/**
* Creates and returns a copy of this event card.
*
* @return a clone of this event card.
*/
@Override
public abstract TribeCard clone();
/**
* Returns the string representation of this event card.
* The returned string includes the string representation of the superclass
* and the string representation of the event type.
*
* @return the string representation of this event card.
*/
@Override
public String toString() {
return super.toString()+" "+type.toString();
}
/**
* Activates the effect of this event card on the specified list of players.
*
* @param playerList the list of players affected by the event.
*/
public abstract void activateEvent (ArrayList <Player> playerList);
// End Functions
}
@@ -11,9 +11,31 @@ import it.polimi.ingsw.gc14.Model.Player;
import java.util.ArrayList;
public class CavePaintings extends EventCard {
/**
* The minimum number of Artist cards required to avoid the prestige penalty.
* Also, the bottom number on the card.
*/
private int NLower;
/**
* The amount of Prestige removed if the player has fewer Artist cards than {@code NLower}.
*/
private int NPrestigeRem; // NPrestigeLower
/**
* The Prestige multiplier applied if the player has at least {@code NLower} Artist cards.
*/
private int NPrestigeMul; // NPrestigeUpper
/**
* Creates a CavePaintings event card with the specified era and effect parameters.
*
* @param Era the era of the event card.
* @param NLower the minimum number of Artist cards required to avoid the prestige penalty.
* @param NPrestigeRem the amount of Prestige removed if the player has fewer Artist cards than {@code NLower}.
* @param NPrestigeMul the Prestige multiplier applied if the player has at least {@code NLower} Artist cards.
*/
public CavePaintings(int Era, int NLower, int NPrestigeRem, int NPrestigeMul) {
super(Era, EventType.CAVE_PAINTINGS);
this.NLower = NLower;
@@ -21,6 +43,16 @@ public class CavePaintings extends EventCard {
this.NPrestigeMul = NPrestigeMul;
}
/**
* Activates the CavePaintings event for the specified list of players.
* For each player, the number of Artist cards is computed together with the number
* of owned building cards having effect id equal to 9.
* The player gains Food equal to the number of such buildings multiplied by the number of Artist cards.
* If the player has fewer Artist cards than {@code NLower}, the player loses {@code NPrestigeRem} Prestige.
* Otherwise, the player gains Prestige equal to {@code NPrestigeMul} multiplied by the number of Artist cards.
*
* @param playerList the list of players affected by the event.
*/
@Override
public void activateEvent (ArrayList <Player> playerList){
for (Player player : playerList){
@@ -42,6 +74,12 @@ public class CavePaintings extends EventCard {
}
}
}
/**
* Creates and returns a copy of this CavePaintings event card.
*
* @return a clone of this CavePaintings event card.
*/
@Override
public EventCard clone()
{
@@ -9,17 +9,45 @@ import it.polimi.ingsw.gc14.Model.Player;
import java.util.ArrayList;
public class Sustenance extends EventCard {
/**
* The prestige penalty multiplier applied for each unpaid Food unit.
*/
private int PrestigeDebt;
/**
* Returns the prestige penalty multiplier associated with this Sustenance event.
*
* @return the prestige penalty multiplier associated with this Sustenance event.
*/
public int getPrestigeDebt() {
return PrestigeDebt;
}
/**
* Creates a Sustenance event card with the specified era and prestige debt value.
*
* @param Era the era of the event card.
* @param PrestigeDebt the prestige penalty multiplier for unpaid Food units.
*/
public Sustenance(int Era, int PrestigeDebt) {
super(Era, EventType.SUSTENANCE);
this.PrestigeDebt = PrestigeDebt;
}
// Sustenence va eseguito per ultimo tra gli eventi
/**
* Activates the Sustenance event for the specified list of players.
* For each player, the required Food is computed from the total number of characters,
* reduced by the contribution of Gatherers and by any applicable character discounts
* granted by owned building cards with effect id equal to 1.
* If the resulting Food debt is positive, the player must pay it with available Food.
* If the player does not have enough Food, all remaining Food is removed and the player
* loses Prestige equal to the unpaid Food debt multiplied by {@code PrestigeDebt}.
* This event is intended to be executed last among event effects.
*
* @param playerList the list of players affected by the event.
* @throws NullPointerException if {@code playerList} or one of its required elements is {@code null}.
*/
@Override
public void activateEvent (ArrayList <Player> playerList) throws NullPointerException {
for(Player player : playerList){
@@ -51,6 +79,12 @@ public class Sustenance extends EventCard {
}
}
}
/**
* Creates and returns a copy of this Sustenance event card.
*
* @return a clone of this Sustenance event card.
*/
@Override
public EventCard clone() {
return new Sustenance(getEra(), PrestigeDebt);
@@ -14,52 +14,142 @@ import it.polimi.ingsw.gc14.Model.Orders.Order4;
import it.polimi.ingsw.gc14.Model.Orders.Order5;
import it.polimi.ingsw.gc14.Model.GamePackage.GameStages;
import java.io.Serializable;
import java.util.*;
import java.util.stream.Collectors;
import it.polimi.ingsw.gc14.Network.Observer;
/**
* Represents the main game model.
* A Game object stores the players, the current state of the match,
* the slot assignments, the board, and the logic required to manage the game flow.
*/
public class Game implements Serializable {
public class Game {
private transient List<Observer> observers = new ArrayList<>(); // transient! non serializzare
public void addObserver(Observer observer) {
observers.add(observer);
}
private void notifyObservers() {
for (Observer o : observers) {
o.update(this);
}
}
/**
* The list of players participating in the game.
*/
private ArrayList<Player> playersList;
/**
* The current state of the game.
*/
private CurrentState currentState;
/**
* The mapping between slots and the players assigned to them.
*/
private HashMap<Slot,Player> slotMap;
/**
* The configured number of players for this game.
*/
private int nPlayers;
/**
* The queue of players involved in optional card resolution.
*/
private Queue<Player> OptionalCardQueue;
/**
* The order logic card associated with this game.
*/
private OrderLogicCard orderLogicCard;
/**
* The board associated with this game.
*/
private Board board;
/**
* Returns clones of the upper tribe cards currently available on the board.
*
* @return a list containing clones of the upper tribe cards currently available on the board.
*/
public List<TribeCard>getUpperListTribeCards() {
List<TribeCard> cards = new ArrayList<>();
board.upperListTribe.forEach(x->cards.add(x.clone()));
return cards;
}
/**
* Returns clones of the lower tribe cards currently available on the board.
*
* @return a list containing clones of the lower tribe cards currently available on the board.
*/
public List<TribeCard>getLowerListTribeCards() {
List<TribeCard> cards = new ArrayList<>();
board.lowerListTribe.forEach(x->cards.add(x.clone()));
return cards;
}
/**
* Returns clones of the upper building cards currently available on the board.
*
* @return a list containing clones of the upper building cards currently available on the board.
*/
public List<BuildingCard>getUpperListBuilding() {
List<BuildingCard> cards = new ArrayList<>();
board.upperListBuilding.forEach(x->cards.add(x.clone()));
return cards;
}
/**
* Returns clones of the lower building cards currently available on the board.
*
* @return a list containing clones of the lower building cards currently available on the board.
*/
public List<BuildingCard>getLowerListBuilding() {
List<BuildingCard> cards = new ArrayList<>();
board.lowerListBuilding.forEach(x->cards.add(x.clone()));
return cards;
}
/**
* Returns the current state of the game.
*
* @return the current state of the game.
*/
public CurrentState getCurrentState() {
return currentState;
};
/**
* Returns the player with the specified username, if present.
*
* @param Username the username of the player to search for.
* @return the player with the specified username, or {@code null} if no such player exists.
*/
public Player getPlayerByUsername(String Username) throws IndexOutOfBoundsException {
return playersList.stream().filter(x->x.getUserName().equals(Username)).findFirst().orElse(null);
}
/**
* Returns the configured number of players for this game.
*
* @return the configured number of players for this game.
*/
public int getNPlayers() {
return nPlayers;
}
/**
* Creates a game with the specified number of players.
*
* @param nPlayers the configured number of players for the game.
* @throws IllegalArgumentException if {@code nPlayers < 0} or {@code nPlayers > 5}.
*/
public Game(int nPlayers) throws IllegalArgumentException{
if(nPlayers < 0||nPlayers > 5)
throw new IllegalArgumentException();
@@ -74,11 +164,24 @@ public class Game {
playersList = new ArrayList<>();
OptionalCardQueue = new LinkedList<>();
}
/**
* Creates a game with 0 configured players.
*/
public Game()
{
this(0);
}
/**
* Attempts to add the specified player to the game.
* The operation succeeds only if the configured number of players is not 0,
* the current game stage is {@code WAITING}, and the player is not already present.
* If the number of players reaches the configured maximum, the game is initialized.
*
* @param player the player to add to the game.
* @return {@code true} if the player is successfully added, {@code false} otherwise.
*/
public boolean addPlayer(Player player) {
if(this.nPlayers==0)
{
@@ -95,6 +198,12 @@ public class Game {
}
return true;
}
/**
* Initializes the game after all required players have been added.
* The method creates the appropriate order logic card according to the number of players,
* selects the first current player, and updates the game stage to {@code SLOT_CHOICE}.
*/
public void init() {
switch (nPlayers) {
@@ -115,7 +224,18 @@ public class Game {
currentState.GameStageUpdate(GameStages.SLOT_CHOICE);
}
//region Cotroller Methods
//region Controller Methods
/**
* Attempts to assign the slot at the specified index to the specified player.
* The operation succeeds only if the index is valid, the current game stage is {@code SLOT_CHOICE},
* the specified player is the current player, and the selected slot is not already assigned.
* If the slot is successfully assigned, the next player setup is triggered.
*
* @param player the player performing the slot choice.
* @param slotIndex the index of the selected slot.
* @return {@code true} if the slot choice succeeds, {@code false} otherwise.
*/
public boolean SlotChoiceByIndex(Player player, int slotIndex) {
if(slotIndex<0 || slotIndex>=slotMap.size())
return false;
@@ -139,6 +259,20 @@ public class Game {
}
//region Drawing Methods
/**
* Attempts to draw the upper tribe card at the specified index for the specified player.
* The operation succeeds only if the index is valid, the game stage is {@code RESOLVING_ACTIONS},
* the specified player is the current player, at least one upper card draw is still available,
* and the selected tribe card is not an event card.
* If successful, the card is inserted into the player's collection, removed from the board,
* and the number of remaining upper draws is decremented.
* If both upper and lower draws become zero, the next player setup is triggered.
*
* @param player the player performing the draw.
* @param cardIndex the index of the upper tribe card to draw.
* @return {@code true} if the draw succeeds, {@code false} otherwise.
*/
public boolean DrawUpperTribeCardByIndex(Player player,int cardIndex) {
if( cardIndex<0 || cardIndex >=board.upperListTribe.size())
return false;
@@ -165,6 +299,20 @@ public class Game {
return true;
}
/**
* Attempts to draw the lower tribe card at the specified index for the specified player.
* The operation succeeds only if the index is valid, the game stage is {@code RESOLVING_ACTIONS},
* the specified player is the current player, at least one lower card draw is still available,
* and the selected tribe card is not an event card.
* If successful, the card is inserted into the player's collection, removed from the board,
* and the number of remaining lower draws is decremented.
* If both lower and upper draws become zero, the next player setup is triggered.
*
* @param player the player performing the draw.
* @param cardIndex the index of the lower tribe card to draw.
* @return {@code true} if the draw succeeds, {@code false} otherwise.
*/
public boolean DrawLowerTribeCardByIndex(Player player, int cardIndex) {
if( cardIndex<0 || cardIndex >=board.lowerListTribe.size())
return false;
@@ -194,6 +342,18 @@ public class Game {
}
/**
* Attempts to draw the upper building card at the specified index for the specified player.
* The operation succeeds only if the index is valid, the game stage is {@code RESOLVING_ACTIONS},
* the specified player is the current player, at least one upper card draw is still available,
* and the selected building card can be bought by the player.
* If successful, the building card is removed from the board and the number of remaining upper draws is decremented.
* If both upper and lower draws become zero, the next player setup is triggered.
*
* @param player the player performing the draw.
* @param cardIndex the index of the upper building card to draw.
* @return {@code true} if the draw succeeds, {@code false} otherwise.
*/
public boolean DrawUpperBuildingCardByIndex(Player player,int cardIndex) {
if( cardIndex<0 || cardIndex >=board.upperListBuilding.size())
return false;
@@ -220,6 +380,19 @@ public class Game {
return true;
}
/**
* Attempts to draw the lower building card at the specified index for the specified player.
* The operation succeeds only if the index is valid, the game stage is {@code RESOLVING_ACTIONS},
* the specified player is the current player, at least one lower card draw is still available,
* and the selected building card can be bought by the player.
* If successful, the building card is removed from the board and the number of remaining lower draws is decremented.
* If both lower and upper draws become zero, the next player setup is triggered.
*
* @param player the player performing the draw.
* @param cardIndex the index of the lower building card to draw.
* @return {@code true} if the draw succeeds, {@code false} otherwise.
*/
public boolean DrawLowerBuildingCardByIndex(Player player,int cardIndex) {
if( cardIndex<0 || cardIndex >=board.lowerListBuilding.size())
return false;
@@ -252,6 +425,21 @@ public class Game {
//endregion
//region Optional Card Methods
/**
* Attempts to pick the upper optional tribe card at the specified index for the specified player.
* The operation succeeds only if the current game stage is {@code OPTIONAL_CARD_EFFECT},
* the specified player is the current player, the index is valid,
* and the selected tribe card is not an event card.
* If successful, the card is inserted into the player's collection,
* removed from the board, the player is removed from the optional card queue,
* and the next player setup is triggered.
*
* @param player the player performing the optional tribe card pick.
* @param cardIndex the index of the upper optional tribe card to pick.
* @return {@code true} if the operation succeeds, {@code false} otherwise.
*/
public boolean PickOptionalTribeCardByIndex(Player player,int cardIndex) {
if(currentState.getGameStage() != GameStages.OPTIONAL_CARD_EFFECT){
return false;
@@ -274,6 +462,19 @@ public class Game {
nextPlayerSetup();
return true;
}
/**
* Attempts to pick the upper optional building card at the specified index for the specified player.
* The operation succeeds only if the current game stage is {@code OPTIONAL_CARD_EFFECT},
* the specified player is the current player, the index is valid,
* and the selected building card can be bought by the player.
* If successful, the card is removed from the board, the next player setup is triggered,
* and the player is removed from the optional card queue.
*
* @param player the player performing the optional building card pick.
* @param cardIndex the index of the upper optional building card to pick.
* @return {@code true} if the operation succeeds, {@code false} otherwise.
*/
public boolean PickOptionalBuildingCard(Player player, int cardIndex) {
if(currentState.getGameStage() != GameStages.OPTIONAL_CARD_EFFECT){
return false;
@@ -295,6 +496,17 @@ public class Game {
return true;
}
/**
* Skips the optional card choice for the specified player.
* The operation succeeds only if the current game stage is {@code OPTIONAL_CARD_EFFECT}
* and the specified player is the current player.
* If successful, the player is removed from the optional card queue
* and the next player setup is triggered.
*
* @param player the player skipping the optional card choice.
* @return {@code true} if the operation succeeds, {@code false} otherwise.
*/
public boolean NoOptionalCard(Player player) {
if(currentState.getGameStage() != GameStages.OPTIONAL_CARD_EFFECT){
return false;
@@ -310,6 +522,23 @@ public class Game {
//endregion
/**
* Prepares the next player and updates the game state according to the current game stage.
* If the current stage is {@code SLOT_CHOICE}, the next player is taken from the order logic card.
* If no player is available, the game stage is updated to {@code RESOLVING_ACTIONS}
* and the first assigned slot is selected.
* If the current stage is {@code RESOLVING_ACTIONS}, the current player is pushed back
* into the order logic card, the current slot is freed, and the next assigned slot is selected.
* If no assigned slots remain, the game stage is updated to {@code OPTIONAL_CARD_EFFECT},
* the optional card queue is built from players owning building cards with effect id equal to 12,
* and the first player in that queue is selected.
* If no player is available for optional card resolution, the game stage is updated to
* {@code RESOLVING_EVENT}; then, if the round number is less than 10, the next round is prepared,
* otherwise event resolution is performed, the game stage is updated to {@code ENDING},
* and the game is ended.
* If the current stage is {@code OPTIONAL_CARD_EFFECT}, the next player is taken from the optional card queue.
* If no player is available, the game stage is updated to {@code RESOLVING_EVENT}.
*/
private void nextPlayerSetup() {
if(GameStages.SLOT_CHOICE==currentState.getGameStage()) {
Player tempPlayer = orderLogicCard.pull();
@@ -381,7 +610,11 @@ public class Game {
}
}
/**
* Resolves all pending event cards if the current game stage is {@code RESOLVING_EVENT}.
* All pending events are activated on the player list.
* Event cards of type {@code SUSTENANCE} are resolved after all other pending events.
*/
private void EventResolution() {
if(currentState.getGameStage()!= GameStages.RESOLVING_EVENT)
@@ -403,6 +636,14 @@ public class Game {
}
}
/**
* Advances the game to the next round.
* The method first resolves pending events.
* If the current round is 10, the game stage is updated to {@code ENDING} and the game is ended.
* Otherwise, the era is updated if the board changes era, and the round number is incremented.
*/
private void nextRound() {
EventResolution();
@@ -417,6 +658,10 @@ public class Game {
}
/**
* Ends the game by applying all final building effects owned by each player
* and updating the game stage to {@code ENDED}.
*/
private void endGame() {
playersList.forEach(
p -> p.buildingCards.stream().filter(x -> x.getEffectType() == EffectType.FINAL).
@@ -425,6 +670,13 @@ public class Game {
currentState.GameStageUpdate(GameStages.ENDED);
}
/**
* Sets the configured number of players for this game.
* The operation succeeds only if the current configured number of players is 0.
*
* @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)
@@ -433,10 +685,4 @@ public class Game {
return true;
}
}
@@ -8,13 +8,14 @@ import it.polimi.ingsw.gc14.Model.Cards.TribeCards.Events.Sustenance;
import it.polimi.ingsw.gc14.Model.DecksCreator;
import it.polimi.ingsw.gc14.Model.Slot;
import java.io.Serializable;
import java.util.*;
import java.util.stream.Collectors;
/**
* Board manages all the elements during the game such as decks, upper and lower rows, totems, tiles...
*/
public class Board {
public class Board implements Serializable {
/**
* slotList contains the ordered list of slots (tiles). The slots changes based on the number of players.
* Each slot (tile) has special action as drawing from the upper/lower row or taking food.
@@ -3,40 +3,110 @@ 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 java.io.Serializable;
public class CurrentState {
/**
* Represents the current state of the game.
* A CurrentState object stores the current player, slot, era, round,
* remaining upper and lower cards, and the current game stage.
*/
public class CurrentState implements Serializable {
// region Getters
/**
* The current player associated with the game state.
*/
private Player player;
/**
* Returns the current player.
*
* @return the current player.
*/
public Player getCurrentPlayer(){
return player;
}
/**
* The current slot associated with the game state.
*/
private Slot slot;
/**
* Returns the current slot.
*
* @return the current slot.
*/
public Slot getSlot(){
return slot;
}
/**
* The current era of the game.
*/
private int Era;
/**
* Returns the current era of the game.
*
* @return the current era of the game.
*/
public int getEra(){
return Era;
}
/**
* The current round of the game.
*/
private int round;
/**
* Returns the current round of the game.
*
* @return the current round of the game.
*/
public int getRound(){
return round;
}
/**
* The number of upper cards currently available.
*/
private int NUpper;
/**
* Returns the number of upper cards currently available.
*
* @return the number of upper cards currently available.
*/
public int getNUpper(){
return NUpper;
}
/**
* The number of lower cards currently available.
*/
private int NLower;
/**
* Returns the number of lower cards currently available.
*
* @return the number of lower cards currently available.
*/
public int getNLower(){
return NLower;
}
/**
* The current stage of the game.
*/
private GameStages GameStage;
/**
* Returns the current stage of the game.
*
* @return the current stage of the game.
*/
public GameStages getGameStage(){
return GameStage;
}
@@ -44,28 +114,52 @@ public class CurrentState {
// endregion getters
// region Setters
/**
* Increments the current era by 1.
*/
public void EraUpdate(){
Era++;
}
/**
* Increments the current round by 1.
*/
public void RoundUpdate(){
round++;
}
/**
* Decrements the number of upper cards by 1.
*/
public void UpperDrawn(){
NUpper--;
}
/**
* Decrements the number of lower cards by 1.
*/
public void LowerDrawn(){
NLower--;
}
/**
* Updates the current game stage.
*
* @param GameStage the new game stage.
*/
public void GameStageUpdate(GameStages GameStage){
this.GameStage = GameStage;
}
// endregion setters
// region Constructors
/**
* Creates a new CurrentState object with default initial values.
* The initial player and slot are {@code null}, the era and round are set to 1,
* the number of upper and lower cards is set to 0, and the game stage is set to {@code WAITING}.
*/
public CurrentState(){
this.player = null;
this.slot = null;
@@ -78,6 +172,15 @@ public class CurrentState {
// endregion constructors
// region Functions
/**
* Updates the current player and slot.
* If the specified slot is {@code null}, the numbers of upper and lower cards are both set to 0.
* Otherwise, the numbers of upper and lower cards are updated using the values of the specified slot.
*
* @param player the new current player.
* @param slot the new current slot.
*/
public void PlayerUpdate(Player player, Slot slot){
this.player = player;
this.slot = slot;
@@ -2,27 +2,78 @@ package it.polimi.ingsw.gc14.Model;
import it.polimi.ingsw.gc14.Model.Cards.BuildingCard;
import java.io.Serializable;
import java.util.*;
public abstract class OrderLogicCard {
/**
* 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.
*/
public abstract class OrderLogicCard implements Serializable {
/**
* The queue of players associated with this order logic card.
*/
private Queue<Player> players;
/**
* Creates an order logic card with the specified list of players.
* The input list is shuffled before being inserted into the queue.
*
* @param players the list of players associated with this order logic card.
*/
public OrderLogicCard(ArrayList<Player> players) {
Collections.shuffle(players);
this.players = new LinkedList<>(players);
}
/**
* Applies the effect associated with the current queue position of the player
* and then adds the player to the end of the queue.
*
* @param player the player to be pushed into the queue.
*/
public void push(Player player){
effect(player,players.size());
players.add(player);
}
/**
* Removes and returns the first player in the queue.
*
* @return the first player in the queue, or {@code null} if the queue is empty.
*/
public Player pull(){
return players.poll();
}
/**
* Returns the first player in the queue without removing it.
*
* @return the first player in the queue, or {@code null} if the queue is empty.
*/
public Player getFirst()
{
return players.peek();
}
/**
* Applies the effect associated with the specified player and queue position.
*
* @param player the player to whom the effect is applied.
* @param index the queue position index associated with the effect.
* @throws IndexOutOfBoundsException if the specified index is not valid.
*/
protected abstract void effect(Player player, int index) throws IndexOutOfBoundsException;
/**
* Applies the building-related effect to the specified player.
* For each building card owned by the player with effect id equal to 3,
* the player gains 1 Food.
*
* @param player the player to whom the building effect is applied.
*/
protected void buildingEffect(Player player)
{
for(BuildingCard b : player.buildingCards.stream().filter(x->x.getEffectId()==3).toList())
@@ -1,10 +1,33 @@
package it.polimi.ingsw.gc14.Model;
import java.io.Serializable;
public abstract class PlayableCard {
/**
* Abstract base class for all playable cards.
* A PlayableCard is characterized by an era value.
*/
public abstract class PlayableCard implements Serializable {
/**
* The era associated with this playable card.
*/
private int Era;
/**
* Returns the era of this playable card.
*
* @return the era of this playable card.
*/
public int getEra(){
return Era;
}
/**
* Creates a playable card with the specified era.
*
* @param Era the era of the playable card.
* @throws IllegalArgumentException if {@code Era <= 0} or {@code Era >= 4}.
*/
public PlayableCard (int Era) throws IllegalArgumentException{
if (Era>0 && Era<4) {
this.Era = Era;
@@ -13,6 +36,11 @@ public abstract class PlayableCard {
}
}
/**
* Returns the string representation of this playable card.
*
* @return the string representation of this playable card.
*/
@Override
public String toString() {
return "Era:"+String.valueOf(Era);
@@ -4,13 +4,14 @@ import it.polimi.ingsw.gc14.Model.Cards.BuildingCard;
import it.polimi.ingsw.gc14.Model.Cards.TribeCards.CharacterType;
import it.polimi.ingsw.gc14.Model.Cards.TribeCards.Characters.*;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
/**
* Default Player class; contains all identifiers and methods needed.
*/
public class Player {
public class Player implements Serializable {
/**
* The maximum length allowed for the username string.
*/
@@ -1,26 +1,80 @@
package it.polimi.ingsw.gc14.Model;
import java.io.Serializable;
public class Slot {
/**
* Represents a slot with a specific identifier and associated values
* for upper cards, lower cards, food, and minimum number of players.
* The slot configuration depends on the specified slot identifier.
*/
public class Slot implements Serializable {
// Getters
/**
* The identifier of this slot.
*/
private char slotId;
/**
* Returns the identifier of this slot.
*
* @return the identifier of this slot.
*/
public char getSlotId() {
return slotId;
}
/**
* The number of upper cards associated with this slot.
*/
private int NUpper;
/**
* Returns the number of upper cards associated with this slot.
*
* @return the number of upper cards associated with this slot.
*/
public int getNUpper(){
return NUpper;
}
/**
* The minimum number of players required for this slot.
*/
private int nMinPlayer;
/**
* Returns the minimum number of players required for this slot.
*
* @return the minimum number of players required for this slot.
*/
public int getNMinPlayer()
{
return nMinPlayer;
}
/**
* The number of lower cards associated with this slot.
*/
private int NLower;
/**
* Returns the number of lower cards associated with this slot.
*
* @return the number of lower cards associated with this slot.
*/
public int getNLower(){
return NLower;
}
/**
* The amount of Food associated with this slot.
*/
private int Food;
/**
* Returns the amount of Food associated with this slot.
*
* @return the amount of Food associated with this slot.
*/
public int getFood(){
return Food;
}
@@ -28,7 +82,17 @@ public class Slot {
// Setters
// End setters
// Constructors
/**
* Creates a slot with the specified identifier.
* The slot values for Food, NLower, NUpper, and minimum number of players
* are determined by the given slot identifier.
*
* @param slotId the identifier of the slot.
* @throws IllegalArgumentException if the specified slot identifier is not valid.
*/
public Slot(char slotId) throws IllegalArgumentException
{
this.slotId = slotId;
@@ -78,6 +142,14 @@ public class Slot {
}
}
/**
* Returns the string representation of this slot.
* The returned string includes the slot identifier, number of upper cards,
* number of lower cards, food value, and minimum number of players.
*
* @return the string representation of this slot.
*/
@Override
public String toString() {
return ("SlotID: "+this.getSlotId()+"\nNUpper: "+this.getNUpper()+"\nNLower: "+this.getNLower()+"\nFood: "+this.getFood()+"\nNMinPlayer: "+this.getNMinPlayer()+"\n");
@@ -1,4 +1,4 @@
package it.polimi.ingsw.gc14.Network.TCP;
package it.polimi.ingsw.gc14.Network;
public enum EventType {
ADD_PLAYER,
@@ -0,0 +1,20 @@
package it.polimi.ingsw.gc14.Network;
import it.polimi.ingsw.gc14.Controller.GameController;
import java.io.Serializable;
public abstract class NetworkEvent implements Serializable {
protected String username;
public String getUsername() {
return username;
}
public NetworkEvent()
{
}
public NetworkEvent(String username) {
this.username = username;
}
public abstract boolean apply(GameController gameController);
}
@@ -1,14 +1,13 @@
package it.polimi.ingsw.gc14.Network.TCP.NetworkEvents;
package it.polimi.ingsw.gc14.Network.NetworkEvents;
import it.polimi.ingsw.gc14.Controller.GameController;
import it.polimi.ingsw.gc14.Network.TCP.EventType;
import it.polimi.ingsw.gc14.Network.TCP.NetworkEvent;
import it.polimi.ingsw.gc14.Network.EventType;
import it.polimi.ingsw.gc14.Network.NetworkEvent;
import it.polimi.ingsw.gc14.View.IView;
import java.io.Serializable;
public class AddPlayer extends NetworkEvent implements Serializable {
private String username;
private EventType eventType;
public AddPlayer(String username) {
this.username = username;
@@ -0,0 +1,29 @@
package it.polimi.ingsw.gc14.Network.NetworkEvents;
import it.polimi.ingsw.gc14.Controller.GameController;
import it.polimi.ingsw.gc14.Network.EventType;
import it.polimi.ingsw.gc14.Network.NetworkEvent;
import it.polimi.ingsw.gc14.View.IView;
import java.io.Serializable;
public class DrawLowerBuildingCard extends NetworkEvent implements Serializable{
private EventType eventType;
private int pos;
public DrawLowerBuildingCard(String username, int pos){
this.username = username;
this.eventType = EventType.DRAW_LOWER_BUILD;
this.pos = pos;
}
@Override
public boolean apply(GameController gameController){
return gameController.drawLowerBuildingCard(username, pos);
}
public String apply(IView gameController){
return gameController.toString();
}
}
@@ -0,0 +1,28 @@
package it.polimi.ingsw.gc14.Network.NetworkEvents;
import it.polimi.ingsw.gc14.Controller.GameController;
import it.polimi.ingsw.gc14.Network.EventType;
import it.polimi.ingsw.gc14.Network.NetworkEvent;
import it.polimi.ingsw.gc14.View.IView;
import java.io.Serializable;
public class DrawLowerTribeCard extends NetworkEvent implements Serializable{
private EventType eventType;
private int pos;
public DrawLowerTribeCard(String username, int pos){
this.username = username;
this.eventType = EventType.DRAW_LOWER_TRIBE;
this.pos = pos;
}
@Override
public boolean apply(GameController gameController){
return gameController.drawLowerTribeCard(username, pos);
}
public String apply(IView gameController){
return gameController.toString();
}
}
@@ -0,0 +1,28 @@
package it.polimi.ingsw.gc14.Network.NetworkEvents;
import it.polimi.ingsw.gc14.Controller.GameController;
import it.polimi.ingsw.gc14.Network.EventType;
import it.polimi.ingsw.gc14.Network.NetworkEvent;
import it.polimi.ingsw.gc14.View.IView;
import java.io.Serializable;
public class DrawUpperBuildingCard extends NetworkEvent implements Serializable{
private EventType eventType;
private int pos;
public DrawUpperBuildingCard(String username, int pos){
this.username = username;
this.eventType = EventType.DRAW_UPPER_BUILD;
this.pos = pos;
}
@Override
public boolean apply(GameController gameController){
return gameController.drawUpperBuildingCard(username, pos);
}
public String apply(IView gameController){
return gameController.toString();
}
}
@@ -0,0 +1,28 @@
package it.polimi.ingsw.gc14.Network.NetworkEvents;
import it.polimi.ingsw.gc14.Controller.GameController;
import it.polimi.ingsw.gc14.Network.EventType;
import it.polimi.ingsw.gc14.Network.NetworkEvent;
import it.polimi.ingsw.gc14.View.IView;
import java.io.Serializable;
public class DrawUpperTribeCard extends NetworkEvent implements Serializable{
private EventType eventType;
private int pos;
public DrawUpperTribeCard(String username, int pos){
this.username = username;
this.eventType = EventType.DRAW_UPPER_TRIBE;
this.pos = pos;
}
@Override
public boolean apply(GameController gameController){
return gameController.drawUpperTribeCard(username, pos);
}
public String apply(IView gameController){
return gameController.toString();
}
}
@@ -0,0 +1,28 @@
package it.polimi.ingsw.gc14.Network.NetworkEvents;
import it.polimi.ingsw.gc14.Controller.GameController;
import it.polimi.ingsw.gc14.Network.EventType;
import it.polimi.ingsw.gc14.Network.NetworkEvent;
import it.polimi.ingsw.gc14.View.IView;
import java.io.Serializable;
public class PickOptionalBuildingCard extends NetworkEvent implements Serializable{
private EventType eventType;
private int pos;
public PickOptionalBuildingCard(String username, int pos){
this.username = username;
this.eventType = EventType.PICK_OPTIONAL_BUILD;
this.pos = pos;
}
@Override
public boolean apply(GameController gameController){
return gameController.pickOptionalBuildingCard(username, pos);
}
public String apply(IView gameController){
return gameController.toString();
}
}
@@ -0,0 +1,28 @@
package it.polimi.ingsw.gc14.Network.NetworkEvents;
import it.polimi.ingsw.gc14.Controller.GameController;
import it.polimi.ingsw.gc14.Network.EventType;
import it.polimi.ingsw.gc14.Network.NetworkEvent;
import it.polimi.ingsw.gc14.View.IView;
import java.io.Serializable;
public class PickOptionalTribeCard extends NetworkEvent implements Serializable{
private EventType eventType;
private int pos;
public PickOptionalTribeCard(String username, int pos){
this.username = username;
this.eventType = EventType.PICK_OPTIONAL_TRIBE;
this.pos = pos;
}
@Override
public boolean apply(GameController gameController){
return gameController.pickOptionalTribeCard(username, pos);
}
public String apply(IView gameController){
return gameController.toString();
}
}
@@ -0,0 +1,28 @@
package it.polimi.ingsw.gc14.Network.NetworkEvents;
import it.polimi.ingsw.gc14.Controller.GameController;
import it.polimi.ingsw.gc14.Network.EventType;
import it.polimi.ingsw.gc14.Network.NetworkEvent;
import it.polimi.ingsw.gc14.View.IView;
import java.io.Serializable;
public class SlotChoice extends NetworkEvent implements Serializable {
private EventType eventType;
private int pos;
public SlotChoice(String username, int pos) {
this.username = username;
this.eventType = EventType.SLOT_CHOICE;
this.pos = pos;
}
@Override
public boolean apply(GameController gameController) {
return gameController.slotChoice(username, pos);
}
public String apply(IView gameController) {
return gameController.toString();
}
}
@@ -0,0 +1,7 @@
package it.polimi.ingsw.gc14.Network;
import it.polimi.ingsw.gc14.Model.Game;
public interface Observer {
public void update(Game model);
}
@@ -0,0 +1,34 @@
package it.polimi.ingsw.gc14.Network.RMI.Client;
import it.polimi.ingsw.gc14.Controller.ClientController;
import it.polimi.ingsw.gc14.Model.Game;
import it.polimi.ingsw.gc14.Network.NetworkEvent;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public class ClientCallbackImpl extends UnicastRemoteObject implements IClientCallback {
private final ClientController clientController;
public ClientCallbackImpl(ClientController clientController) throws RemoteException {
this.clientController = clientController;
}
@Override
public void onGameInit(Game model) throws RemoteException {
clientController.setModel(model); // setta il model
}
@Override
public void onAction(NetworkEvent event) throws RemoteException {
event.apply(clientController.localController); // delega tutto al controller
}
@Override
public void onError(String message) throws RemoteException {
clientController.onError(message);
}
}
@@ -0,0 +1,10 @@
package it.polimi.ingsw.gc14.Network.RMI.Client;
import it.polimi.ingsw.gc14.Controller.ClientController;
import it.polimi.ingsw.gc14.Network.NetworkEvent;
import it.polimi.ingsw.gc14.View.IView;
public interface GameClient {
boolean connect( String username,ClientController clientController );
void doEvent(NetworkEvent event) throws Exception;
}
@@ -0,0 +1,12 @@
package it.polimi.ingsw.gc14.Network.RMI.Client;
import it.polimi.ingsw.gc14.Model.Game;
import it.polimi.ingsw.gc14.Network.NetworkEvent;
import java.rmi.*;
public interface IClientCallback extends Remote {
void onGameInit(Game model) throws RemoteException;
void onAction(NetworkEvent action) throws RemoteException;
void onError(String message) throws RemoteException;
}
@@ -0,0 +1,57 @@
package it.polimi.ingsw.gc14.Network.RMI.Client;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import it.polimi.ingsw.gc14.Controller.ClientController;
import it.polimi.ingsw.gc14.Network.NetworkEvent;
import it.polimi.ingsw.gc14.Network.RMI.Server.*;
import it.polimi.ingsw.gc14.View.IView;
public class RMIClient implements GameClient {
private final String host;
private final int port;
private IGameServer stub;
public RMIClient(String host, int port) {
this.host = host;
this.port = port;
}
@Override
public boolean connect(String username,ClientController clientController) {
// 1. Connettiti al registry
try {
Registry registry = LocateRegistry.getRegistry(host, port);
// 2. Prendi lo stub del server
this.stub = (IGameServer) registry.lookup("RMIGameServer");
// 3. Crea il callback e registralo
ClientCallbackImpl callback = new ClientCallbackImpl(clientController);
if (!stub.joinGame(username, callback))
{
stub = null;
return false;
}
else
{
return true;
}
}
catch (Exception e) {
e.printStackTrace();
return false;
}
}
@Override
public void doEvent( NetworkEvent event) throws Exception {
stub.doEvent(event);
}
}
@@ -0,0 +1,13 @@
package it.polimi.ingsw.gc14.Network.RMI.Server;
import it.polimi.ingsw.gc14.Network.RMI.Client.IClientCallback;
import it.polimi.ingsw.gc14.Network.NetworkEvent;
import java.rmi.*;
public interface IGameServer extends Remote {
boolean joinGame(String username, IClientCallback callback) throws RemoteException;
boolean doEvent(NetworkEvent event) throws RemoteException;
}
@@ -0,0 +1,9 @@
package it.polimi.ingsw.gc14.Network.RMI.Server;
import java.rmi.RemoteException;
public interface IRMIServer {
void add(Integer number) throws RemoteException;
void reset() throws RemoteException;
}
@@ -0,0 +1,59 @@
package it.polimi.ingsw.gc14.Network.RMI.Server;
import it.polimi.ingsw.gc14.Controller.GameController;
import it.polimi.ingsw.gc14.Model.Game;
import it.polimi.ingsw.gc14.Network.RMI.Client.IClientCallback;
import it.polimi.ingsw.gc14.Network.NetworkEvent;
import it.polimi.ingsw.gc14.Network.NetworkEvents.DrawUpperBuildingCard;
import java.rmi.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.*;
public class RMIGameController implements IGameServer {
private final GameController controller;
private final Map<String, IClientCallback> clients = new ConcurrentHashMap<>();
public RMIGameController(GameController controller) {
this.controller = controller;
}
@Override
public boolean joinGame(String username, IClientCallback callback) {
if(controller.addPlayer(username))
{
clients.put(username, callback);
return true;
}
return false;
}
@Override
public boolean doEvent(NetworkEvent event) throws RemoteException {
boolean result = event.apply(controller);
if (!result) {
notifyError(event.getUsername(),"Mossa non valida");
} else {
notifyAll(event);
}
return result;
}
private void notifyAll(NetworkEvent action) throws RemoteException {
for (IClientCallback cb : clients.values()) {
cb.onAction(action);
}
}
private void notifyAll(Game model) throws RemoteException {
for (IClientCallback cb : clients.values()) {
cb.onGameInit(model);
}
}
private void notifyError(String username, String message) throws RemoteException {
IClientCallback cb = clients.get(username);
if (cb != null) cb.onError(message);
}
}
@@ -0,0 +1,41 @@
package it.polimi.ingsw.gc14.Network.RMI.Server;
import it.polimi.ingsw.gc14.Controller.GameController;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
public class RMIServer {
private final RMIGameController controller;
private Registry registry;
private int nPort;
public RMIServer(RMIGameController controller, int nPort) {
this.controller = controller;
this.nPort = nPort;
}
public boolean start() throws Exception {
try {
IGameServer stub = (IGameServer) UnicastRemoteObject.exportObject(controller, 0);
registry = LocateRegistry.createRegistry(nPort);
registry.rebind("RMIGameServer", stub);
System.out.println("RMI Server avviato sulla porta "+nPort);
return true;
}
catch (Exception e) {
e.printStackTrace();
return false;
}
}
public void stop() throws Exception {
registry.unbind("RMIGameServer");
UnicastRemoteObject.unexportObject(controller, true);
System.out.println("RMI Server fermato");
}
}
@@ -1,37 +1,69 @@
package it.polimi.ingsw.gc14.Network.TCP.Client;
import it.polimi.ingsw.gc14.View.IView;
import it.polimi.ingsw.gc14.Controller.GameController;
import it.polimi.ingsw.gc14.Network.NetworkEvent;
import it.polimi.ingsw.gc14.Network.NetworkEvents.AddPlayer;
import java.io.*;
import java.net.*;
public class TCPClient implements Serializable {
public TCPClient(IView view) {
IView iView = view;
public class TCPClient implements Serializable{
Socket communicationSocket = null;
ObjectInputStream socketReceive;
ObjectOutputStream socketSend;
GameController controller;
String hostname;
int port;
public TCPClient(GameController controller, String hostname, int port){
this.controller = controller;
this.hostname = hostname;
this.port = port;
}
public static void main(String[] args) {
String hostName = "127.0.0.1";
int portNumber = 5200;
Socket communicationSocket = null;
try {
communicationSocket = new Socket(hostName, portNumber);
public boolean start(String user){
try{
communicationSocket = new Socket(hostname, port);
socketSend = new ObjectOutputStream(communicationSocket.getOutputStream());
socketReceive = new ObjectInputStream(communicationSocket.getInputStream());
socketSend.writeObject(new AddPlayer(user));
if(communicationSocket.getInputStream().read() == -1){
return false;
}
else{
Thread listener = new Thread(() -> ReceiveMessage());
listener.start();
return true;
}
}
catch(Exception e){
return false;
}
}
private void ReceiveMessage(){
while(true){
try{
((NetworkEvent)(socketReceive.readObject())).apply(controller);
}
catch(IOException e){
e.printStackTrace();
}
catch(ClassNotFoundException e){
throw new RuntimeException(e);
}
return;
}
}
private void SendEvent(NetworkEvent event){
try{
socketSend.writeObject(event);
}
catch (IOException e) {
System.err.println(e.toString() + " " + hostName);
System.exit(1);
}
PrintWriter out = null;
BufferedReader in = null;
try {
out = new PrintWriter(communicationSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(communicationSocket.getInputStream()));
} catch (IOException e) {
System.err.println(e.toString() + " " + hostName);
System.exit(1);
}
String userInput = "";
while (true) {
e.printStackTrace();
}
}
@@ -1,10 +0,0 @@
package it.polimi.ingsw.gc14.Network.TCP;
import it.polimi.ingsw.gc14.Controller.GameController;
import java.io.Serializable;
public abstract class NetworkEvent implements Serializable {
public abstract boolean apply(GameController gameController);
}
@@ -1,6 +1,8 @@
package it.polimi.ingsw.gc14.Network.TCP.Server;
import it.polimi.ingsw.gc14.Controller.GameController;
import it.polimi.ingsw.gc14.Network.NetworkEvent;
import it.polimi.ingsw.gc14.Network.EventType;
import java.io.*;
import java.net.*;
@@ -8,42 +10,67 @@ import java.util.List;
public class ClientHandler implements Runnable {
private Socket clientSocket;
BufferedReader in = null;
PrintWriter out = null;
private TCPServer server;
public ObjectInputStream in = null;
public ObjectOutputStream out = null;
List<ClientHandler> clientHandlers;
GameController gameController;
private EventType eventType;
public Socket getClientSocket() {
return clientSocket;
}
public ClientHandler(Socket clientSocket, List<ClientHandler> clientHandlers, GameController gameController) {
this.clientSocket = clientSocket;
this.clientHandlers = clientHandlers;
this.gameController = gameController;
}
@Override
public void run() {
public void run(){
clientLoop();
}
private void clientLoop() {
try {
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
synchronized (out) {
out = new PrintWriter(clientSocket.getOutputStream(), true);
}
} catch (IOException e) {
e.printStackTrace();
}
String s = "";
private void clientLoop(){
try{
while ((s = in.readLine()) != null) {
System.out.println(s);
out.println(s.toUpperCase());
NetworkEvent input = null;
synchronized(in){
in = new ObjectInputStream(clientSocket.getInputStream());
}
while(true){
try{
input = (NetworkEvent) (in.readObject());
if(input.apply(gameController)){
server.broadcastUpdate(input);
}
}
catch(java.io.IOException e){
e.printStackTrace();
}
catch (ClassNotFoundException e){
throw new RuntimeException(e);
}
}
}
catch (IOException e) {
e.printStackTrace();
}
}
private void notifyEvent(Object event) {
synchronized (out) {
out.println(event.toString());
public void notifyEvent(NetworkEvent event){
synchronized(out){
try{
out = new ObjectOutputStream(clientSocket.getOutputStream());
out.writeObject(gameController.getModel());
}
catch(IOException e){
e.printStackTrace();
}
}
}
}
@@ -1,19 +1,27 @@
package it.polimi.ingsw.gc14.Network.TCP.Server;
import it.polimi.ingsw.gc14.Controller.GameController;
import it.polimi.ingsw.gc14.Network.NetworkEvent;
import java.io.IOException;
import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.List;
public class TCPServer {
int port = -1;
int ConnectedPlayers = 0;
ServerSocket serverTCP = null;
GameController gameController;
private List<ClientHandler> clientHandlers;
private int getConnectedPlayers(){
return ConnectedPlayers;
}
public void start(String args[]){
clientHandlers = new ArrayList<>();
@@ -25,27 +33,59 @@ public class TCPServer {
e.printStackTrace();
return;
}
System.out.println("Listening on port " + port);
System.out.println("Listening on port: " + port);
while(true){
Socket clientSocket = null;
try {
try{
clientSocket = serverTCP.accept();
} catch (IOException e) {
if(!gameController.addPlayer(clientSocket.getInputStream().toString()) || ConnectedPlayers > gameController.getModel().getNPlayers()){
clientSocket.getOutputStream().write((int)(-1));
clientSocket.close();
System.out.println("Invalid parameters. Connection terminated.\n");
}
else{
clientSocket.getOutputStream().write((int)(1));
}
// gestione di ADD_PLAYER
}
catch (IOException e){
e.printStackTrace();
}
System.out.println("Accepted");
ClientHandler clientHandler = new ClientHandler(clientSocket, clientHandlers, this.gameController);
System.out.println("Accepted player: " + gameController.getModel().getPlayerByUsername(clientSocket.getInetAddress().toString()));
ConnectedPlayers++;
ClientHandler clientHandler = new ClientHandler(clientSocket, clientHandlers, gameController);
clientHandlers.add(clientHandler);
//Sending model to clients
if(ConnectedPlayers == gameController.getModel().getNPlayers()){
for (ClientHandler handler : clientHandlers) {
try {
synchronized(handler.out){
ObjectOutputStream socketTx = new ObjectOutputStream(handler.getClientSocket().getOutputStream());
socketTx.writeObject(gameController.getModel());
}
}
catch(IOException e){
e.printStackTrace();
}
}
}
Thread t = new Thread(clientHandler);
t.start();
}
}
private TCPServer(GameController gameController, int port) {
private TCPServer(GameController gameController, int port){
this.port = port;
this.gameController = gameController;
}
public void broadcastUpdate(NetworkEvent event){
clientHandlers.forEach((x) -> x.notifyEvent(event));
}
}
@@ -1,4 +1,12 @@
package it.polimi.ingsw.gc14.View;
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);
}
@@ -0,0 +1,228 @@
package it.polimi.ingsw.gc14.Controller;
import it.polimi.ingsw.gc14.Model.Cards.TribeCard;
import it.polimi.ingsw.gc14.Model.Game;
import it.polimi.ingsw.gc14.Model.GamePackage.GameStages;
import it.polimi.ingsw.gc14.Model.Player;
import org.junit.jupiter.api.Test;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import static org.junit.jupiter.api.Assertions.*;
class GameControllerTest {
@Test
void addPlayer() {
Game game = new Game(3);
GameController controller = new GameController(game);
assertTrue(controller.addPlayer("Giorgio"));
assertTrue(controller.addPlayer("Marco"));
assertTrue(controller.addPlayer("Luca"));
assertNotNull(game.getPlayerByUsername("Giorgio"));
assertNotNull(game.getPlayerByUsername("Marco"));
assertNotNull(game.getPlayerByUsername("Luca"));
assertEquals(GameStages.SLOT_CHOICE, game.getCurrentState().getGameStage());
assertFalse(controller.addPlayer("Extra"));
}
@Test
void allMethodsShouldReturnFalseForUnknownUsername() {
Game game = new Game(3);
GameController controller = new GameController(game);
assertFalse(controller.slotChoice("ghost", 0));
assertFalse(controller.drawUpperTribeCard("ghost", 0));
assertFalse(controller.drawLowerTribeCard("ghost", 0));
assertFalse(controller.drawUpperBuildingCard("ghost", 0));
assertFalse(controller.drawLowerBuildingCard("ghost", 0));
assertFalse(controller.pickOptionalTribeCard("ghost", 0));
assertFalse(controller.pickOptionalBuildingCard("ghost", 0));
}
@Test
void slotChoice() {
Game game = new Game(3);
GameController controller = new GameController(game);
assertTrue(controller.addPlayer("Giorgio"));
assertTrue(controller.addPlayer("Marco"));
assertTrue(controller.addPlayer("Luca"));
String cur = game.getCurrentState().getCurrentPlayer().getUserName();
String other = cur.equals("Giorgio") ? "Marco" : "Giorgio";
assertFalse(controller.slotChoice(other, 0));
Queue<Player> order = new LinkedList<>();
for (int i = 0; i < 3; i++) {
Player p = game.getCurrentState().getCurrentPlayer();
order.add(p);
assertTrue(controller.slotChoice(p.getUserName(), i));
}
assertEquals(GameStages.RESOLVING_ACTIONS, game.getCurrentState().getGameStage());
assertEquals(order.poll(), game.getCurrentState().getCurrentPlayer());
}
@Test
void drawLowerTribeCard() {
Game game = new Game(3);
GameController controller = new GameController(game);
assertTrue(controller.addPlayer("Giorgio"));
assertTrue(controller.addPlayer("Marco"));
assertTrue(controller.addPlayer("Luca"));
Queue<Player> order = new LinkedList<>();
for (int i = 0; i < 3; i++) {
Player p = game.getCurrentState().getCurrentPlayer();
order.add(p);
assertTrue(controller.slotChoice(p.getUserName(), i));
}
Player first = order.poll();
assertEquals(first, game.getCurrentState().getCurrentPlayer());
List<TribeCard> cards = game.getLowerListTribeCards();
int idx = cards.indexOf(
cards.stream()
.filter(c -> !c.IsEventCard())
.findFirst()
.orElseThrow()
);
Player wrongPlayer = order.peek();
assertNotNull(wrongPlayer);
int before = first.getTotCharacters();
assertTrue(controller.drawLowerTribeCard(first.getUserName(), idx));
assertEquals(before + 1, first.getTotCharacters());
}
@Test
void drawUpperTribeCard() {
Game game = new Game(3);
GameController controller = new GameController(game);
assertTrue(controller.addPlayer("Giorgio"));
assertTrue(controller.addPlayer("Marco"));
assertTrue(controller.addPlayer("Luca"));
for (int i = 0; i < 3; i++) {
Player p = game.getCurrentState().getCurrentPlayer();
assertTrue(controller.slotChoice(p.getUserName(), i));
}
assertEquals(GameStages.RESOLVING_ACTIONS, game.getCurrentState().getGameStage());
while (game.getCurrentState().getNUpper() == 0) {
assertTrue(game.getCurrentState().getNLower() > 0);
Player current = game.getCurrentState().getCurrentPlayer();
List<TribeCard> lower = game.getLowerListTribeCards();
int lowerIdx = lower.indexOf(
lower.stream()
.filter(c -> !c.IsEventCard())
.findFirst()
.orElseThrow()
);
assertTrue(controller.drawLowerTribeCard(current.getUserName(), lowerIdx));
}
Player current = game.getCurrentState().getCurrentPlayer();
int beforeTot = current.getTotCharacters();
List<TribeCard> upper = game.getUpperListTribeCards();
int upperIdx = upper.indexOf(
upper.stream()
.filter(c -> !c.IsEventCard())
.findFirst()
.orElseThrow()
);
assertTrue(controller.drawUpperTribeCard(current.getUserName(), upperIdx));
assertEquals(beforeTot + 1, current.getTotCharacters());
}
@Test
void drawUpperBuildingCard() {
Game game = new Game(3);
GameController controller = new GameController(game);
assertTrue(controller.addPlayer("Giacomo"));
assertTrue(controller.addPlayer("Marco"));
assertTrue(controller.addPlayer("Luca"));
for (int i = 0; i < 3; i++) {
Player p = game.getCurrentState().getCurrentPlayer();
assertTrue(controller.slotChoice(p.getUserName(), i));
}
assertEquals(GameStages.RESOLVING_ACTIONS, game.getCurrentState().getGameStage());
while (game.getCurrentState().getNUpper() == 0) {
assertTrue(game.getCurrentState().getNLower() > 0);
Player current = game.getCurrentState().getCurrentPlayer();
List<TribeCard> lower = game.getLowerListTribeCards();
int lowerIdx = lower.indexOf(
lower.stream()
.filter(c -> !c.IsEventCard())
.findFirst()
.orElseThrow()
);
assertTrue(controller.drawLowerTribeCard(current.getUserName(), lowerIdx));
}
Player current = game.getCurrentState().getCurrentPlayer();
assertFalse(controller.drawUpperBuildingCard(current.getUserName(), 0));
current.addFood(100);
assertTrue(controller.drawUpperBuildingCard(current.getUserName(), 0));
}
@Test
void drawLowerBuildingCard() {
Game game = new Game(3);
GameController controller = new GameController(game);
assertTrue(controller.addPlayer("Giacomo"));
assertTrue(controller.addPlayer("Marco"));
assertTrue(controller.addPlayer("Luca"));
for (int i = 0; i < 3; i++) {
Player p = game.getCurrentState().getCurrentPlayer();
assertTrue(controller.slotChoice(p.getUserName(), i));
}
String cur = game.getCurrentState().getCurrentPlayer().getUserName();
assertFalse(controller.drawLowerBuildingCard(cur, 0));
}
@Test
void pickOptionalCards() {
Game game = new Game(3);
GameController controller = new GameController(game);
assertTrue(controller.addPlayer("Giacomo"));
assertTrue(controller.addPlayer("Marco"));
assertTrue(controller.addPlayer("Luca"));
for (int i = 0; i < 3; i++) {
Player p = game.getCurrentState().getCurrentPlayer();
assertTrue(controller.slotChoice(p.getUserName(), i));
}
String cur = game.getCurrentState().getCurrentPlayer().getUserName();
assertFalse(controller.pickOptionalTribeCard(cur, 0));
assertFalse(controller.pickOptionalBuildingCard(cur, 0));
}
}