This commit is contained in:
MatteoPellegrino05
2026-05-03 18:05:06 +02:00
15 changed files with 467 additions and 179 deletions
+6
View File
@@ -0,0 +1,6 @@
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="DuplicatedCode" enabled="false" level="WEAK WARNING" enabled_by_default="false" />
</profile>
</component>
@@ -5,30 +5,67 @@ import it.polimi.ingsw.gc14.Network.RMI.Client.RMIClient;
import it.polimi.ingsw.gc14.Network.TCP.Client.TCPClient; import it.polimi.ingsw.gc14.Network.TCP.Client.TCPClient;
import it.polimi.ingsw.gc14.View.TUI.TUI; import it.polimi.ingsw.gc14.View.TUI.TUI;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner; import java.util.Scanner;
/**
* Entry point for the TUI-based game client.
* Handles the initial setup by asking the user for a username, the desired number of players,
* and the preferred network protocol (RMI or TCP).
* Once connected to the server, it continuously reads and dispatches user input to the controller.
*/
public class ClientLauncherTUI { public class ClientLauncherTUI {
//TODO Javadoc
TUI view;
public void main() throws InterruptedException {
view=new TUI(null);
ClientController controller = new ClientController(view);
List<String> admissibleChar=new ArrayList<>();
/**
* The TUI view associated with this client.
*/
TUI view;
/**
* Starts the TUI client.
* Prompts the user for a username, the desired number of players, and the network protocol.
* Attempts to connect to the server using either RMI or TCP depending on the selection.
* If the connection is successful, enters a loop to continuously read and process user input.
*
* @throws InterruptedException if the thread is interrupted while waiting.
*/
public void main() throws InterruptedException {
view = new TUI(null);
admissibleChar.add("0");
admissibleChar.add("1");
admissibleChar.add("2");
admissibleChar.add("3");
admissibleChar.add("4");
admissibleChar.add("5");
admissibleChar.add("6");
admissibleChar.add("7");
admissibleChar.add("8");
admissibleChar.add("9");
admissibleChar.add("A");
admissibleChar.add("B");
admissibleChar.add("C");
admissibleChar.add("a");
admissibleChar.add("b");
admissibleChar.add("c");
ClientController controller = new ClientController(view);
Scanner scanner = new Scanner(System.in); Scanner scanner = new Scanner(System.in);
System.out.println("Selezionare nome utente: "); System.out.println("Insert username: ");
String username = scanner.next(); String username = scanner.next();
view.setUsername(username); view.setUsername(username);
System.out.println("Selezionare numero di giocatori desiderato: "); System.out.println("Insert preferred number of players: ");
int proposedNumPlayers = scanner.nextInt(); int proposedNumPlayers = scanner.nextInt();
System.out.println("Selezionare RMI[0] o TCP[1]: "); System.out.println("Select RMI[0] o TCP[1]: ");
int networkType = scanner.nextInt(); int networkType = scanner.nextInt();
System.out.println("Insert server IP: ");
String IP = scanner.next();
// RMI // RMI
if (networkType == 0) { if (networkType == 0) {
// Connect // Connect
RMIClient client = new RMIClient(controller, "localhost", 1099); RMIClient client = new RMIClient(controller, IP, 1099);
if (client.connect(username, proposedNumPlayers)) { if (client.connect(username, proposedNumPlayers)) {
System.out.println("Succesfully connected to RMI server\n\n"); System.out.println("Succesfully connected to RMI server\n\n");
} else { } else {
@@ -36,20 +73,13 @@ public class ClientLauncherTUI {
return; return;
} }
controller.setClient(client); controller.setClient(client);
while (true) {
// Play
//while(controller.localController.getModel()==null){
// scanner.nextInt();
//}
while(true) {
getInput(scanner, controller, username); getInput(scanner, controller, username);
} }
// TCP
// TCP
} else if (networkType == 1) { } else if (networkType == 1) {
// Connect // Connect
TCPClient client = new TCPClient(controller, "localhost", 8080); TCPClient client = new TCPClient(controller, IP, 8080);
if (client.connect(username, proposedNumPlayers)) { if (client.connect(username, proposedNumPlayers)) {
System.out.println("Succesfully connected to TCP server\n\n"); System.out.println("Succesfully connected to TCP server\n\n");
} else { } else {
@@ -57,48 +87,75 @@ public class ClientLauncherTUI {
return; return;
} }
controller.setClient(client); controller.setClient(client);
// Play // Play
while(true) { while (true) {
getInput(scanner, controller, username); getInput(scanner, controller, username);
} }
} }
scanner.close(); scanner.close();
} }
/**
* Reads a single action from the user and dispatches it to the controller.
* The action is identified by a string code. Most actions also require a position index
* (e.g. the index of the card to draw from a list), which is read as a second input.
* Actions that do not require a position (7, 8, 9, A, B, C) skip the position prompt.
* <p>
* Available actions:
* <ul>
* <li>{@code 0} - Choose a slot by index.</li>
* <li>{@code 1} - Draw an upper building card by index.</li>
* <li>{@code 2} - Draw an upper tribe card by index.</li>
* <li>{@code 3} - Draw a lower building card by index.</li>
* <li>{@code 4} - Draw a lower tribe card by index.</li>
* <li>{@code 5} - Pick an optional tribe card by index.</li>
* <li>{@code 6} - Pick an optional building card by index.</li>
* <li>{@code 7} - Skip the optional card choice.</li>
* <li>{@code 8} - Skip the upper draw.</li>
* <li>{@code 9} - Skip the lower draw.</li>
* <li>{@code A} - Render the full game view.</li>
* <li>{@code B} - Render the board view.</li>
* <li>{@code C} - Render the player view.</li>
* </ul>
*
* @param scanner the scanner used to read user input.
* @param controller the client controller to which actions are dispatched.
* @param username the username of the current player.
*/
private void getInput(Scanner scanner, ClientController controller, String username) { private void getInput(Scanner scanner, ClientController controller, String username) {
String action = scanner.next(); String action = scanner.next();
int pos=-1; int pos = -1;
if(!action.equals("7")&&!action.equals("8")&&!action.equals("9")&&!action.equals("A")&&!action.equals("B")&&!action.equals("C")) {
try
{
System.out.println("Insert the required position:");
pos = scanner.nextInt();
}
catch(Exception e)
{
System.out.println("ERROR: Invalid input(expected number)");
}
}
switch(action) {
case "0" -> controller.slotChoice(username, pos);
case "1" -> controller.drawUpperTribeCard(username, pos);
case "2" -> controller.drawUpperBuildingCard(username, pos);
case "3" -> controller.drawLowerTribeCard(username, pos);
case "4" -> controller.drawLowerBuildingCard(username, pos);
case "5" -> controller.pickOptionalTribeCard(username, pos);
case "6" -> controller.pickOptionalBuildingCard(username, pos);
case "7" -> controller.noOptionalCard(username);
case "8" -> controller.skipUpper(username);
case "9" -> controller.skipLower(username);
case "A" -> view.fullRender();
case "B" -> view.renderBoard();
case "C" -> view.renderPlayer();
}
return; if(admissibleChar.contains(username))
{
if (!action.equals("7") && !action.equals("8") && !action.equals("9") && !action.equals("A") && !action.equals("B") && !action.equals("C")) {
try {
System.out.println("Insert the required position:");
pos = scanner.nextInt();
} catch (Exception e) {
System.out.println("ERROR: Invalid input(expected number)");
}
}
switch (action) {
case "0" -> controller.slotChoice(username, pos);
case "1" -> controller.drawUpperTribeCard(username, pos);
case "2" -> controller.drawUpperBuildingCard(username, pos);
case "3" -> controller.drawLowerTribeCard(username, pos);
case "4" -> controller.drawLowerBuildingCard(username, pos);
case "5" -> controller.pickOptionalTribeCard(username, pos);
case "6" -> controller.pickOptionalBuildingCard(username, pos);
case "7" -> controller.noOptionalCard(username);
case "8" -> controller.skipUpper(username);
case "9" -> controller.skipLower(username);
case "A", "a" -> view.fullRender();
case "B", "b" -> view.renderBoard();
case "C", "c" -> view.renderPlayer();
default -> {}
}
}
else
{
System.out.println("ERROR: Invalid input(action not valid)");
}
} }
} }
@@ -1,10 +1,8 @@
package it.polimi.ingsw.gc14.Controller; package it.polimi.ingsw.gc14.Controller;
import it.polimi.ingsw.gc14.Model.Game; import it.polimi.ingsw.gc14.Model.Game;
import it.polimi.ingsw.gc14.Model.Player;
import it.polimi.ingsw.gc14.Network.IClient; import it.polimi.ingsw.gc14.Network.IClient;
import it.polimi.ingsw.gc14.Network.NetworkEvents.*; import it.polimi.ingsw.gc14.Network.NetworkEvents.*;
import it.polimi.ingsw.gc14.Network.Observer;
import it.polimi.ingsw.gc14.View.IView; import it.polimi.ingsw.gc14.View.IView;
/** /**
@@ -1,22 +1,42 @@
package it.polimi.ingsw.gc14; package it.polimi.ingsw.gc14;
import java.util.ArrayList; import java.util.ArrayList;
//TODO Javadoc /**
* An {@link ArrayList} with a configurable size limit and an associated action.
* When the number of elements reaches or exceeds the limit, the specified action is automatically triggered.
*
* @param <T> the type of elements held in this list.
*/
public class LimitedList<T> extends ArrayList<T> { public class LimitedList<T> extends ArrayList<T> {
//TODO Javadoc
/**
* The maximum number of elements allowed in the list before the action is triggered.
*/
private int limit; private int limit;
//TODO Javadoc /**
* The action to execute when the list size reaches or exceeds the limit.
*/
private Runnable action; private Runnable action;
//TODO Javadoc /**
* Creates a new {@code LimitedList} with the specified limit and action.
*
* @param limit the maximum number of elements before the action is triggered.
* @param action the action to execute when the limit is reached.
*/
public LimitedList(int limit, Runnable action) { public LimitedList(int limit, Runnable action) {
this.limit = limit; this.limit = limit;
this.action = action; this.action = action;
} }
//TODO Javadoc /**
* Adds the specified element to the list.
* If the list size reaches or exceeds the limit after the insertion, the configured action is triggered.
*
* @param element the element to add.
* @return {@code true} if the element was successfully added.
*/
@Override @Override
public boolean add(T element) { public boolean add(T element) {
boolean result = super.add(element); boolean result = super.add(element);
@@ -26,16 +46,30 @@ public class LimitedList<T> extends ArrayList<T> {
return result; return result;
} }
//TODO Javadoc /**
* Sets a new size limit for this list.
*
* @param num the new limit.
*/
public void setLimit(int num) { public void setLimit(int num) {
this.limit=num; this.limit = num;
} }
//TODO Javadoc /**
public int getLimit(){return limit;} * Returns the current size limit of this list.
*
* @return the current limit.
*/
public int getLimit() {
return limit;
}
//TODO Javadoc /**
* Sets a new action to execute when the list size reaches or exceeds the limit.
*
* @param action the new action to set.
*/
public void setAction(Runnable action) { public void setAction(Runnable action) {
this.action=action; this.action = action;
} }
} }
@@ -42,7 +42,7 @@ public class Building8 extends BuildingCard {
if(!player.buildingCards.contains(this)) if(!player.buildingCards.contains(this))
throw new IllegalArgumentException(); throw new IllegalArgumentException();
for (Builder builder : player.builders) { for (Builder builder : player.builders) {
player.addPrestige(builder.getPrestigeValue() * 2); player.addPrestige(builder.getPrestigeValue());
} }
} }
@@ -15,10 +15,19 @@ import java.io.*;
import java.lang.reflect.Type; import java.lang.reflect.Type;
import java.util.*; import java.util.*;
//TODO javadoc /**
* Utility class responsible for loading and creating decks of cards and slots for the game.
* Cards are loaded from JSON resource files and instantiated according to their type and parameters.
*/
public class DecksCreator { public class DecksCreator {
//TODO javadoc /**
* Loads the tribe card deck for the specified era from the corresponding JSON resource file.
*
* @param era the era number (1, 2, or 3).
* @return a list of {@link TribeCard} objects for the specified era.
* @throws IllegalArgumentException if {@code era} is not 1, 2, or 3.
*/
public static List<TribeCard> loadTribeDeckByEra(int era) throws IllegalArgumentException public static List<TribeCard> loadTribeDeckByEra(int era) throws IllegalArgumentException
{ {
return switch (era) { return switch (era) {
@@ -29,7 +38,13 @@ public class DecksCreator {
}; };
} }
//TODO javadoc /**
* Loads a tribe card deck from the specified JSON resource file path.
*
* @param resourcePath the path to the JSON resource file.
* @return a list of {@link TribeCard} objects defined in the resource file.
* @throws RuntimeException if the resource file is not found or an error occurs while reading it.
*/
public static List<TribeCard> loadTribeDeck(String resourcePath) { public static List<TribeCard> loadTribeDeck(String resourcePath) {
Gson gson = new Gson(); Gson gson = new Gson();
Type listType = new com.google.gson.reflect.TypeToken<List<TribeCardDefinition>>(){}.getType(); Type listType = new com.google.gson.reflect.TypeToken<List<TribeCardDefinition>>(){}.getType();
@@ -51,14 +66,26 @@ public class DecksCreator {
} }
} }
//TODO javadoc /**
public static List<BuildingCard> loadBuildingDeckByEra(int era) throws IllegalArgumentException * Loads the building card deck for the specified era, filtering cards from the global building deck.
*
* @param era the era number (1, 2, or 3).
* @return a list of {@link BuildingCard} objects belonging to the specified era.
* @throws IllegalArgumentException if {@code era} is not 1, 2, or 3.
*/
public static List<BuildingCard> loadBuildingDeckByEra(int era) throws IllegalArgumentException
{ {
if(era<=0 || era>3) throw new IllegalArgumentException(); if(era<=0 || era>3) throw new IllegalArgumentException();
return loadBuildingDeck("/Cards/buildingCards.json").stream().filter(x->x.getEra()==era).toList(); return loadBuildingDeck("/Cards/buildingCards.json").stream().filter(x->x.getEra()==era).toList();
} }
//TODO javadoc /**
* Loads the full building card deck from the specified JSON resource file path.
*
* @param resourcePath the path to the JSON resource file.
* @return a list of {@link BuildingCard} objects defined in the resource file.
* @throws RuntimeException if the resource file is not found or an error occurs while reading it.
*/
public static List<BuildingCard> loadBuildingDeck(String resourcePath) { public static List<BuildingCard> loadBuildingDeck(String resourcePath) {
Gson gson = new Gson(); Gson gson = new Gson();
Type listType = new com.google.gson.reflect.TypeToken<List<BuildingCardDefinition>>(){}.getType(); Type listType = new com.google.gson.reflect.TypeToken<List<BuildingCardDefinition>>(){}.getType();
@@ -80,7 +107,12 @@ public class DecksCreator {
} }
} }
//TODO javadoc /**
* Creates and returns the list of slots used as the game board.
* Slots are labeled with the letters A through G.
*
* @return a list of {@link Slot} objects representing the game board.
*/
public static List<Slot> loadSlotDeck() public static List<Slot> loadSlotDeck()
{ {
List<Slot> slots = new ArrayList<>(); List<Slot> slots = new ArrayList<>();
@@ -90,7 +122,15 @@ public class DecksCreator {
return slots; return slots;
} }
//TODO javadoc /**
* Instantiates a {@link TribeCard} from the given definition.
* Depending on whether the card is an event or a character, the appropriate subclass is created
* using the type and parameters specified in the definition.
*
* @param def the {@link TribeCardDefinition} containing the card's type, era, and parameters.
* @return the instantiated {@link TribeCard}.
* @throws IllegalArgumentException if the card type is unknown or the parameters are invalid.
*/
private static TribeCard createCard(TribeCardDefinition def) { private static TribeCard createCard(TribeCardDefinition def) {
int era = def.era; int era = def.era;
@@ -138,7 +178,14 @@ public class DecksCreator {
}; };
} }
//TODO javadoc /**
* Instantiates a {@link BuildingCard} from the given definition.
* The appropriate subclass is selected based on the effect ID specified in the definition.
* If no specific subclass matches the effect ID, a base {@link BuildingCard} is created.
*
* @param def the {@link BuildingCardDefinition} containing the card's effect ID, era, price, prestige value, and parameters.
* @return the instantiated {@link BuildingCard}.
*/
private static BuildingCard createCard(BuildingCardDefinition def) { private static BuildingCard createCard(BuildingCardDefinition def) {
return switch (def.effectId) { return switch (def.effectId) {
case 0 -> new Building0(def.era, def.price, def.prestigeValue); case 0 -> new Building0(def.era, def.price, def.prestigeValue);
@@ -153,7 +200,11 @@ public class DecksCreator {
} }
//TODO javadoc /**
* Internal data class representing the raw definition of a tribe card as loaded from a JSON file.
* Contains the card type, era, whether it is armed, whether it is an event card,
* and a list of additional parameters.
*/
private static class TribeCardDefinition { private static class TribeCardDefinition {
String type; String type;
int era; int era;
@@ -162,7 +213,10 @@ public class DecksCreator {
List<Object> params; // Object per gestire boolean e int misti List<Object> params; // Object per gestire boolean e int misti
} }
//TODO javadoc /**
* Internal data class representing the raw definition of a building card as loaded from a JSON file.
* Contains the effect ID, era, price, prestige value, and a list of additional parameters.
*/
private static class BuildingCardDefinition { private static class BuildingCardDefinition {
int effectId; int effectId;
int era; int era;
@@ -22,7 +22,6 @@ import java.util.*;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.Stream; import java.util.stream.Stream;
import it.polimi.ingsw.gc14.Network.Observer;
import it.polimi.ingsw.gc14.View.TUI.AsciiTable; import it.polimi.ingsw.gc14.View.TUI.AsciiTable;
import it.polimi.ingsw.gc14.View.TUI.BorderStyle; import it.polimi.ingsw.gc14.View.TUI.BorderStyle;
@@ -33,18 +32,6 @@ import it.polimi.ingsw.gc14.View.TUI.BorderStyle;
*/ */
public class Game implements Serializable { public class Game implements Serializable {
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);
}
}
/** /**
* Returns the list of players participating in the game. * Returns the list of players participating in the game.
* @return * @return
@@ -245,6 +232,16 @@ public class Game implements Serializable {
orderLogicCard=new Order5(playersList); orderLogicCard=new Order5(playersList);
break; break;
} }
for(Player player : playersList)
{
switch(orderLogicCard.getPosition(player.getUserName()))
{
case 0: player.addFood(2); break;
case 1,2: player.addFood(3); break;
case 3,4: player.addFood(4); break;
}
}
currentState.PlayerUpdate(orderLogicCard.pull(),null); currentState.PlayerUpdate(orderLogicCard.pull(),null);
currentState.GameStageUpdate(GameStages.SLOT_CHOICE); currentState.GameStageUpdate(GameStages.SLOT_CHOICE);
} }
@@ -277,6 +274,10 @@ public class Game implements Serializable {
{ {
return false; return false;
} }
if(slotPlayerEntry.getKey().getSlotId()=='A')
{
player.addFood(3);
}
slotMap.put(slotPlayerEntry.getKey(),player); slotMap.put(slotPlayerEntry.getKey(),player);
nextPlayerSetup(); nextPlayerSetup();
return true; return true;
@@ -301,7 +302,7 @@ public class Game implements Serializable {
public boolean DrawUpperTribeCardByIndex(Player player,int cardIndex) { public boolean DrawUpperTribeCardByIndex(Player player,int cardIndex) {
if( cardIndex<0 || cardIndex >=board.upperListTribe.size()) if( cardIndex<0 || cardIndex >=board.upperListTribe.size())
return false; return false;
if(currentState.getGameStage()!= GameStages.RESOLVING_ACTIONS) if(currentState.getGameStage()!= GameStages.RES_ACTIONS)
{ {
return false; return false;
} }
@@ -337,7 +338,7 @@ public class Game implements Serializable {
* @return {@code true} if the skip succeeds, {@code false} otherwise. * @return {@code true} if the skip succeeds, {@code false} otherwise.
*/ */
public boolean SkipUpperDrawing(Player player) { public boolean SkipUpperDrawing(Player player) {
if(currentState.getGameStage()!= GameStages.RESOLVING_ACTIONS) if(currentState.getGameStage()!= GameStages.RES_ACTIONS)
{ {
return false; return false;
} }
@@ -368,7 +369,7 @@ public class Game implements Serializable {
* @return {@code true} if the skip succeeds, {@code false} otherwise. * @return {@code true} if the skip succeeds, {@code false} otherwise.
*/ */
public boolean SkipLowerDrawing(Player player) { public boolean SkipLowerDrawing(Player player) {
if(currentState.getGameStage()!= GameStages.RESOLVING_ACTIONS) if(currentState.getGameStage()!= GameStages.RES_ACTIONS)
{ {
return false; return false;
} }
@@ -402,7 +403,7 @@ public class Game implements Serializable {
public boolean DrawLowerTribeCardByIndex(Player player, int cardIndex) { public boolean DrawLowerTribeCardByIndex(Player player, int cardIndex) {
if( cardIndex<0 || cardIndex >=board.lowerListTribe.size()) if( cardIndex<0 || cardIndex >=board.lowerListTribe.size())
return false; return false;
if(currentState.getGameStage()!= GameStages.RESOLVING_ACTIONS) if(currentState.getGameStage()!= GameStages.RES_ACTIONS)
{ {
return false; return false;
} }
@@ -443,7 +444,7 @@ public class Game implements Serializable {
public boolean DrawUpperBuildingCardByIndex(Player player,int cardIndex) { public boolean DrawUpperBuildingCardByIndex(Player player,int cardIndex) {
if( cardIndex<0 || cardIndex >=board.upperListBuilding.size()) if( cardIndex<0 || cardIndex >=board.upperListBuilding.size())
return false; return false;
if(currentState.getGameStage()!= GameStages.RESOLVING_ACTIONS) if(currentState.getGameStage()!= GameStages.RES_ACTIONS)
{ {
return false; return false;
} }
@@ -482,7 +483,7 @@ public class Game implements Serializable {
public boolean DrawLowerBuildingCardByIndex(Player player,int cardIndex) { public boolean DrawLowerBuildingCardByIndex(Player player,int cardIndex) {
if( cardIndex<0 || cardIndex >=board.lowerListBuilding.size()) if( cardIndex<0 || cardIndex >=board.lowerListBuilding.size())
return false; return false;
if(currentState.getGameStage()!= GameStages.RESOLVING_ACTIONS) if(currentState.getGameStage()!= GameStages.RES_ACTIONS)
{ {
return false; return false;
} }
@@ -527,7 +528,7 @@ public class Game implements Serializable {
* @return {@code true} if the operation succeeds, {@code false} otherwise. * @return {@code true} if the operation succeeds, {@code false} otherwise.
*/ */
public boolean PickOptionalTribeCardByIndex(Player player,int cardIndex) { public boolean PickOptionalTribeCardByIndex(Player player,int cardIndex) {
if(currentState.getGameStage() != GameStages.OPTIONAL_CARD_EFFECT){ if(currentState.getGameStage() != GameStages.OPT_CARD_E){
return false; return false;
} }
if(!player.equals(currentState.getCurrentPlayer())){ if(!player.equals(currentState.getCurrentPlayer())){
@@ -562,7 +563,7 @@ public class Game implements Serializable {
* @return {@code true} if the operation succeeds, {@code false} otherwise. * @return {@code true} if the operation succeeds, {@code false} otherwise.
*/ */
public boolean PickOptionalBuildingCard(Player player, int cardIndex) { public boolean PickOptionalBuildingCard(Player player, int cardIndex) {
if(currentState.getGameStage() != GameStages.OPTIONAL_CARD_EFFECT){ if(currentState.getGameStage() != GameStages.OPT_CARD_E){
return false; return false;
} }
if(!player.equals(currentState.getCurrentPlayer())){ if(!player.equals(currentState.getCurrentPlayer())){
@@ -594,7 +595,7 @@ public class Game implements Serializable {
* @return {@code true} if the operation succeeds, {@code false} otherwise. * @return {@code true} if the operation succeeds, {@code false} otherwise.
*/ */
public boolean NoOptionalCard(Player player) { public boolean NoOptionalCard(Player player) {
if(currentState.getGameStage() != GameStages.OPTIONAL_CARD_EFFECT){ if(currentState.getGameStage() != GameStages.OPT_CARD_E){
return false; return false;
} }
if(!player.equals(currentState.getCurrentPlayer())){ if(!player.equals(currentState.getCurrentPlayer())){
@@ -633,7 +634,7 @@ public class Game implements Serializable {
currentState.PlayerUpdate(tempPlayer, null); currentState.PlayerUpdate(tempPlayer, null);
return; return;
} }
currentState.GameStageUpdate(GameStages.RESOLVING_ACTIONS); currentState.GameStageUpdate(GameStages.RES_ACTIONS);
for (Slot s : slotMap.keySet()) { for (Slot s : slotMap.keySet()) {
if (slotMap.get(s) != null) { if (slotMap.get(s) != null) {
currentState.PlayerUpdate(slotMap.get(s), s); currentState.PlayerUpdate(slotMap.get(s), s);
@@ -649,7 +650,7 @@ public class Game implements Serializable {
return; return;
} }
if(GameStages.RESOLVING_ACTIONS==currentState.getGameStage()) { if(GameStages.RES_ACTIONS ==currentState.getGameStage()) {
orderLogicCard.push(currentState.getCurrentPlayer()); orderLogicCard.push(currentState.getCurrentPlayer());
slotMap.put(currentState.getSlot(), null); slotMap.put(currentState.getSlot(), null);
for (Slot s : slotMap.keySet()) { for (Slot s : slotMap.keySet()) {
@@ -668,7 +669,7 @@ public class Game implements Serializable {
} }
if(slotMap.values().stream().allMatch(v -> v == null)) if(slotMap.values().stream().allMatch(v -> v == null))
{ {
currentState.GameStageUpdate(GameStages.OPTIONAL_CARD_EFFECT); currentState.GameStageUpdate(GameStages.OPT_CARD_E);
HashMap<Player,Integer> optional=new LinkedHashMap<>(); HashMap<Player,Integer> optional=new LinkedHashMap<>();
for (Player p : orderLogicCard.players) { for (Player p : orderLogicCard.players) {
int tempCount=(int)p.buildingCards.stream().filter(x->x.getEffectId()==12).count(); int tempCount=(int)p.buildingCards.stream().filter(x->x.getEffectId()==12).count();
@@ -689,7 +690,7 @@ public class Game implements Serializable {
return; return;
} }
currentState.GameStageUpdate(GameStages.RESOLVING_EVENT); currentState.GameStageUpdate(GameStages.RES_EVENT);
if (currentState.getRound() < 10) { if (currentState.getRound() < 10) {
nextRound(); nextRound();
@@ -704,7 +705,7 @@ public class Game implements Serializable {
} }
} }
if (GameStages.OPTIONAL_CARD_EFFECT == currentState.getGameStage()) { if (GameStages.OPT_CARD_E == currentState.getGameStage()) {
Player optionalPlayer = OptionalCardQueue.poll(); Player optionalPlayer = OptionalCardQueue.poll();
if (optionalPlayer != null) { if (optionalPlayer != null) {
@@ -712,7 +713,7 @@ public class Game implements Serializable {
return; return;
} }
currentState.GameStageUpdate(GameStages.RESOLVING_EVENT); currentState.GameStageUpdate(GameStages.RES_EVENT);
if (currentState.getRound() < 10) { if (currentState.getRound() < 10) {
nextRound(); nextRound();
@@ -761,7 +762,7 @@ public class Game implements Serializable {
*/ */
private void EventResolution() { private void EventResolution() {
if(currentState.getGameStage()!= GameStages.RESOLVING_EVENT) if(currentState.getGameStage()!= GameStages.RES_EVENT)
{ {
return; return;
} }
@@ -812,18 +813,12 @@ public class Game implements Serializable {
*/ */
private void endGame() { private void endGame() {
Queue<EventCard> events; Queue<EventCard> events;
events=Stream.concat(board.lowerListTribe.stream().filter(x->!x.IsEventCard()),board.upperListTribe.stream().filter(x->!x.IsEventCard())).map(x->((EventCard)x)).collect(Collectors.toCollection(LinkedList::new)); events=Stream.concat(board.lowerListTribe.stream().filter(TribeCard::IsEventCard),board.upperListTribe.stream().filter(TribeCard::IsEventCard)).map(x->((EventCard)x)).collect(Collectors.toCollection(LinkedList::new));
ArrayList<EventCard>sustenance=events.stream().filter(x->x.getType().equals(EventType.SUSTENANCE)).collect(Collectors.toCollection(ArrayList::new)); ArrayList<EventCard>sustenance=events.stream().filter(x->x.getType().equals(EventType.SUSTENANCE)).collect(Collectors.toCollection(ArrayList::new));
events.removeAll(sustenance); events.removeAll(sustenance);
for(EventCard event:events) events.forEach(event->event.activateEvent(playersList));
{ sustenance.forEach(event->event.activateEvent(playersList));
event.activateEvent(playersList);
}
for(EventCard e : sustenance)
{
e.activateEvent(playersList);
}
playersList.forEach(p->{ playersList.forEach(p->{
int temp= p.builders.stream().mapToInt(Builder::getPrestigeValue).sum(); int temp= p.builders.stream().mapToInt(Builder::getPrestigeValue).sum();
p.addPrestige(temp); p.addPrestige(temp);
@@ -1,5 +1,5 @@
package it.polimi.ingsw.gc14.Model.GamePackage; package it.polimi.ingsw.gc14.Model.GamePackage;
public enum GameStages { public enum GameStages {
WAITING, SLOT_CHOICE, RESOLVING_ACTIONS, OPTIONAL_CARD_EFFECT, RESOLVING_EVENT, ENDING, ENDED WAITING, SLOT_CHOICE, RES_ACTIONS, OPT_CARD_E, RES_EVENT, ENDING, ENDED
} }
@@ -1,7 +0,0 @@
package it.polimi.ingsw.gc14.Network;
import it.polimi.ingsw.gc14.Model.Game;
public interface Observer {
public void update(Game model);
}
@@ -40,7 +40,7 @@ public class RMIClient implements IClient {
this.port = port; this.port = port;
} }
//TODO Javadoc fix
/** /**
* Connects to the RMI server and attempts to join the game. * Connects to the RMI server and attempts to join the game.
* Looks up the RMI registry to retrieve the {@link IGameServer} stub. * Looks up the RMI registry to retrieve the {@link IGameServer} stub.
@@ -87,7 +87,14 @@ public class TCPClient implements IClient {
private void receiveMessage() { private void receiveMessage() {
while (true) { while (true) {
try { try {
Object read = socketReceive.readObject(); Object read;
try {
read = socketReceive.readObject();
} catch (IOException e) {
e.printStackTrace();
break;
}
if (read instanceof NetworkEvent event) { //TODO: avoid instanceof if (read instanceof NetworkEvent event) { //TODO: avoid instanceof
if (event.getIsError()) { if (event.getIsError()) {
System.out.println(event); System.out.println(event);
@@ -99,10 +106,9 @@ public class TCPClient implements IClient {
controller.setModel(model); controller.setModel(model);
controller.view.render(); controller.view.render();
} }
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) { } catch (ClassNotFoundException e) {
throw new RuntimeException(e); e.printStackTrace();
break;
} }
} }
} }
@@ -1,9 +1,11 @@
package it.polimi.ingsw.gc14.View.TUI; package it.polimi.ingsw.gc14.View.TUI;
public enum BorderStyle { public enum BorderStyle {
UNICODE("","","","","","","","","","","","","","",""),
ASCII ("+","+","+","+","-","|","+","+","+","+","+","+","+","-","+"), //UNICODE("╔","╗","╚","╝","═","║","╠","╣","╦","╩","╬","├","┤","─","┼"),
ROUNDED("","","","","","","","","","","","","","",""); UNICODE ("+","+","+","+","-","|","+","+","+","+","+","+","+","-","+"),
ROUNDED ("+","+","+","+","-","|","+","+","+","+","+","+","+","-","+");
//ROUNDED("╭","╮","╰","╯","─","│","├","┤","┬","┴","┼","├","┤","─","┼");
private final String tl,tr,bl,br,h,v,ml,mr,mt,mb,x,sl,sr,sh,sx; private final String tl,tr,bl,br,h,v,ml,mr,mt,mb,x,sl,sr,sh,sx;
@@ -36,7 +36,7 @@ class GameControllerTest {
assertTrue(controller.slotChoice(current.getUserName(), i)); assertTrue(controller.slotChoice(current.getUserName(), i));
} }
assertEquals(GameStages.RESOLVING_ACTIONS, game.getCurrentState().getGameStage()); assertEquals(GameStages.RES_ACTIONS, game.getCurrentState().getGameStage());
return order; return order;
} }
@@ -89,12 +89,12 @@ class GameControllerTest {
private void resolveActionsUntilOptionalCardEffect(Game game, GameController controller) { private void resolveActionsUntilOptionalCardEffect(Game game, GameController controller) {
int guard = 0; int guard = 0;
while (game.getCurrentState().getGameStage() == GameStages.RESOLVING_ACTIONS && guard < 100) { while (game.getCurrentState().getGameStage() == GameStages.RES_ACTIONS && guard < 100) {
guard++; guard++;
resolveOneMandatoryAction(game, controller); resolveOneMandatoryAction(game, controller);
} }
assertEquals(GameStages.OPTIONAL_CARD_EFFECT, game.getCurrentState().getGameStage()); assertEquals(GameStages.OPT_CARD_E, game.getCurrentState().getGameStage());
} }
private void resolveOneMandatoryAction(Game game, GameController controller) { private void resolveOneMandatoryAction(Game game, GameController controller) {
@@ -154,7 +154,7 @@ class GameControllerTest {
assertTrue(controller.slotChoice(current.getUserName(), slotIndexes[i])); assertTrue(controller.slotChoice(current.getUserName(), slotIndexes[i]));
} }
assertEquals(GameStages.RESOLVING_ACTIONS, game.getCurrentState().getGameStage()); assertEquals(GameStages.RES_ACTIONS, game.getCurrentState().getGameStage());
return order; return order;
} }
@@ -206,7 +206,7 @@ class GameControllerTest {
Queue<Player> order = completeSlotChoice(game, controller); Queue<Player> order = completeSlotChoice(game, controller);
assertEquals(GameStages.RESOLVING_ACTIONS, game.getCurrentState().getGameStage()); assertEquals(GameStages.RES_ACTIONS, game.getCurrentState().getGameStage());
assertEquals(order.poll(), game.getCurrentState().getCurrentPlayer()); assertEquals(order.poll(), game.getCurrentState().getCurrentPlayer());
} }
@@ -320,7 +320,7 @@ class GameControllerTest {
assertTrue(controller.slotChoice(current.getUserName(), i)); assertTrue(controller.slotChoice(current.getUserName(), i));
} }
assertEquals(GameStages.RESOLVING_ACTIONS, game.getCurrentState().getGameStage()); assertEquals(GameStages.RES_ACTIONS, game.getCurrentState().getGameStage());
Player tempPlayer = players.poll(); Player tempPlayer = players.poll();
assertNotNull(tempPlayer); assertNotNull(tempPlayer);
@@ -395,7 +395,7 @@ class GameControllerTest {
completeSlotChoice(game, controller); completeSlotChoice(game, controller);
assertEquals(GameStages.RESOLVING_ACTIONS, game.getCurrentState().getGameStage()); assertEquals(GameStages.RES_ACTIONS, game.getCurrentState().getGameStage());
String cur = game.getCurrentState().getCurrentPlayer().getUserName(); String cur = game.getCurrentState().getCurrentPlayer().getUserName();
@@ -70,7 +70,7 @@ class CurrentStateTest {
void getGameStage() { void getGameStage() {
Player p = new Player("test"); Player p = new Player("test");
Slot s = new Slot('A'); Slot s = new Slot('A');
GameStages g = GameStages.RESOLVING_ACTIONS; GameStages g = GameStages.RES_ACTIONS;
CurrentState curr = new CurrentState(); CurrentState curr = new CurrentState();
curr.PlayerUpdate(p, s); curr.PlayerUpdate(p, s);
curr.GameStageUpdate(g); curr.GameStageUpdate(g);
@@ -122,12 +122,12 @@ class CurrentStateTest {
void gameStageUpdate() { void gameStageUpdate() {
Player p = new Player("test"); Player p = new Player("test");
Slot s = new Slot('A'); Slot s = new Slot('A');
GameStages g = GameStages.RESOLVING_ACTIONS; GameStages g = GameStages.RES_ACTIONS;
CurrentState curr = new CurrentState(); CurrentState curr = new CurrentState();
assertEquals(GameStages.WAITING, curr.getGameStage()); assertEquals(GameStages.WAITING, curr.getGameStage());
curr.PlayerUpdate(p, s); curr.PlayerUpdate(p, s);
curr.GameStageUpdate(g); curr.GameStageUpdate(g);
assertEquals(GameStages.RESOLVING_ACTIONS, curr.getGameStage()); assertEquals(GameStages.RES_ACTIONS, curr.getGameStage());
} }
@Test @Test
@@ -5,6 +5,9 @@ import it.polimi.ingsw.gc14.Model.Cards.TribeCard;
import it.polimi.ingsw.gc14.Model.Cards.TribeCards.Character; import it.polimi.ingsw.gc14.Model.Cards.TribeCards.Character;
import it.polimi.ingsw.gc14.Model.Cards.TribeCards.CharacterType; import it.polimi.ingsw.gc14.Model.Cards.TribeCards.CharacterType;
import it.polimi.ingsw.gc14.Model.GamePackage.GameStages; import it.polimi.ingsw.gc14.Model.GamePackage.GameStages;
import it.polimi.ingsw.gc14.Model.Cards.TribeCards.Characters.Artist;
import it.polimi.ingsw.gc14.Model.Cards.TribeCards.Characters.Builder;
import it.polimi.ingsw.gc14.Model.Cards.TribeCards.Characters.Inventor;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout; import org.junit.jupiter.api.Timeout;
@@ -27,7 +30,7 @@ class GameTest {
assertTrue(game.SlotChoiceByIndex(current, i)); assertTrue(game.SlotChoiceByIndex(current, i));
} }
assertEquals(GameStages.RESOLVING_ACTIONS, game.getCurrentState().getGameStage()); assertEquals(GameStages.RES_ACTIONS, game.getCurrentState().getGameStage());
return order; return order;
} }
@@ -60,7 +63,7 @@ class GameTest {
} }
private void resolveAllMandatoryActions(Game game) { private void resolveAllMandatoryActions(Game game) {
while (game.getCurrentState().getGameStage() == GameStages.RESOLVING_ACTIONS) { while (game.getCurrentState().getGameStage() == GameStages.RES_ACTIONS) {
resolveOneMandatoryAction(game); resolveOneMandatoryAction(game);
} }
} }
@@ -77,9 +80,8 @@ class GameTest {
return; return;
} }
if (!game.getLowerListBuilding().isEmpty()) { if (!game.getLowerListBuilding().isEmpty()
current.addFood(100); && game.DrawLowerBuildingCardByIndex(current, 0)) {
assertTrue(game.DrawLowerBuildingCardByIndex(current, 0));
return; return;
} }
@@ -95,9 +97,8 @@ class GameTest {
return; return;
} }
if (!game.getUpperListBuilding().isEmpty()) { if (!game.getUpperListBuilding().isEmpty()
current.addFood(100); && game.DrawUpperBuildingCardByIndex(current, 0)) {
assertTrue(game.DrawUpperBuildingCardByIndex(current, 0));
return; return;
} }
@@ -125,15 +126,15 @@ class GameTest {
} }
private void resolveActionsUntilOptionalCardEffect(Game game) { private void resolveActionsUntilOptionalCardEffect(Game game) {
while (game.getCurrentState().getGameStage() == GameStages.RESOLVING_ACTIONS) { while (game.getCurrentState().getGameStage() == GameStages.RES_ACTIONS) {
resolveOneMandatoryAction(game); resolveOneMandatoryAction(game);
} }
assertEquals(GameStages.OPTIONAL_CARD_EFFECT, game.getCurrentState().getGameStage()); assertEquals(GameStages.OPT_CARD_E, game.getCurrentState().getGameStage());
} }
private void resolveOptionalPhaseIfPresent(Game game) { private void resolveOptionalPhaseIfPresent(Game game) {
while (game.getCurrentState().getGameStage() == GameStages.OPTIONAL_CARD_EFFECT) { while (game.getCurrentState().getGameStage() == GameStages.OPT_CARD_E) {
Player current = game.getCurrentState().getCurrentPlayer(); Player current = game.getCurrentState().getCurrentPlayer();
assertNotNull(current); assertNotNull(current);
@@ -146,7 +147,7 @@ class GameTest {
completeSlotChoice(game); completeSlotChoice(game);
assertEquals(GameStages.RESOLVING_ACTIONS, game.getCurrentState().getGameStage()); assertEquals(GameStages.RES_ACTIONS, game.getCurrentState().getGameStage());
resolveAllMandatoryActions(game); resolveAllMandatoryActions(game);
@@ -156,7 +157,7 @@ class GameTest {
private void resolveCurrentPlayerCompletely(Game game, Player expectedPlayer) { private void resolveCurrentPlayerCompletely(Game game, Player expectedPlayer) {
assertEquals(expectedPlayer, game.getCurrentState().getCurrentPlayer()); assertEquals(expectedPlayer, game.getCurrentState().getCurrentPlayer());
while (game.getCurrentState().getGameStage() == GameStages.RESOLVING_ACTIONS while (game.getCurrentState().getGameStage() == GameStages.RES_ACTIONS
&& expectedPlayer.equals(game.getCurrentState().getCurrentPlayer())) { && expectedPlayer.equals(game.getCurrentState().getCurrentPlayer())) {
resolveOneMandatoryAction(game); resolveOneMandatoryAction(game);
} }
@@ -294,7 +295,7 @@ class GameTest {
assertTrue(game.addPlayer(p3)); assertTrue(game.addPlayer(p3));
Queue<Player> players = new LinkedList<>(); Queue<Player> players = new LinkedList<>();
for (int i = 0; i < 3; i++) { for (int i = 0; i < game.getNPlayers(); i++) {
players.add(game.getCurrentState().getCurrentPlayer()); players.add(game.getCurrentState().getCurrentPlayer());
assertTrue(game.SlotChoiceByIndex(game.getCurrentState().getCurrentPlayer(), i)); assertTrue(game.SlotChoiceByIndex(game.getCurrentState().getCurrentPlayer(), i));
} }
@@ -337,11 +338,14 @@ class GameTest {
assertFalse(game.DrawUpperTribeCardByIndex(temp_player, eventIndex)); assertFalse(game.DrawUpperTribeCardByIndex(temp_player, eventIndex));
} }
temp_player.addFood(100);
assertFalse(game.getUpperListBuilding().isEmpty()); assertFalse(game.getUpperListBuilding().isEmpty());
temp_player.builders.clear();
index = 0; index = 0;
BuildingCard selectedBuilding = game.getUpperListBuilding().get(index);
temp_player.addFood(selectedBuilding.getPrice());
assertTrue(game.DrawUpperBuildingCardByIndex(temp_player, index)); assertTrue(game.DrawUpperBuildingCardByIndex(temp_player, index));
int remainingTribeIndex = firstNonEventIndexOrMinusOne(game.getUpperListTribeCards()); int remainingTribeIndex = firstNonEventIndexOrMinusOne(game.getUpperListTribeCards());
@@ -353,7 +357,7 @@ class GameTest {
assertNotNull(thirdPlayer); assertNotNull(thirdPlayer);
assertEquals(thirdPlayer, game.getCurrentState().getCurrentPlayer()); assertEquals(thirdPlayer, game.getCurrentState().getCurrentPlayer());
while (game.getCurrentState().getGameStage() == GameStages.RESOLVING_ACTIONS while (game.getCurrentState().getGameStage() == GameStages.RES_ACTIONS
&& thirdPlayer.equals(game.getCurrentState().getCurrentPlayer())) { && thirdPlayer.equals(game.getCurrentState().getCurrentPlayer())) {
resolveOneMandatoryAction(game); resolveOneMandatoryAction(game);
} }
@@ -445,15 +449,30 @@ class GameTest {
assertFalse(game.getUpperListBuilding().isEmpty()); assertFalse(game.getUpperListBuilding().isEmpty());
current.addFood(100); current.builders.clear();
BuildingCard selectedBuilding = game.getUpperListBuilding().get(0);
int expectedCost = selectedBuilding.getPrice();
current.addFood(expectedCost);
int foodBefore = current.getFoodValue();
int buildingsBefore = current.buildingCards.size(); int buildingsBefore = current.buildingCards.size();
int upperBuildingsBefore = game.getUpperListBuilding().size();
int foodBefore = current.getFoodValue();
assertTrue(game.PickOptionalBuildingCard(current, 0)); assertTrue(game.PickOptionalBuildingCard(current, 0));
assertTrue(current.getFoodValue() < foodBefore);
assertEquals(buildingsBefore + 1, current.buildingCards.size()); assertEquals(buildingsBefore + 1, current.buildingCards.size());
assertEquals(upperBuildingsBefore - 1, game.getUpperListBuilding().size());
assertTrue(current.buildingCards.stream()
.anyMatch(building ->
building.getPrice() == selectedBuilding.getPrice()
&& building.getPrestigeValue() == selectedBuilding.getPrestigeValue()
&& building.getEffectId() == selectedBuilding.getEffectId()
));
assertEquals(foodBefore - expectedCost, current.getFoodValue());
} }
@Test @Test
@@ -478,7 +497,7 @@ class GameTest {
assertTrue(game.NoOptionalCard(current)); assertTrue(game.NoOptionalCard(current));
assertEquals(GameStages.OPTIONAL_CARD_EFFECT, game.getCurrentState().getGameStage()); assertEquals(GameStages.OPT_CARD_E, game.getCurrentState().getGameStage());
assertNotEquals(current, game.getCurrentState().getCurrentPlayer()); assertNotEquals(current, game.getCurrentState().getCurrentPlayer());
} }
@@ -643,7 +662,7 @@ class GameTest {
assertDoesNotThrow(() -> resolveAllMandatoryActions(game)); assertDoesNotThrow(() -> resolveAllMandatoryActions(game));
assertNotEquals(GameStages.OPTIONAL_CARD_EFFECT, game.getCurrentState().getGameStage()); assertNotEquals(GameStages.OPT_CARD_E, game.getCurrentState().getGameStage());
} }
@@ -807,6 +826,8 @@ class GameTest {
assertTrue(current.removeFood(1)); assertTrue(current.removeFood(1));
} }
current.builders.clear();
assertEquals(0, current.getFoodValue()); assertEquals(0, current.getFoodValue());
assertFalse( assertFalse(
@@ -816,6 +837,7 @@ class GameTest {
assertFalse(game.PickOptionalBuildingCard(current, 0)); assertFalse(game.PickOptionalBuildingCard(current, 0));
} }
@Test @Test
void toStringModel() { void toStringModel() {
Game game=new Game(5); Game game=new Game(5);
@@ -832,8 +854,8 @@ class GameTest {
assertTrue(game.addPlayer(p5)); assertTrue(game.addPlayer(p5));
Queue<Player>players=new LinkedList<>(); Queue<Player>players=new LinkedList<>();
for(int i=0;i<3;i++) { for (int i = 0; i < game.getNPlayers(); i++) {
players.add( game.getCurrentState().getCurrentPlayer()); players.add(game.getCurrentState().getCurrentPlayer());
assertTrue(game.SlotChoiceByIndex(game.getCurrentState().getCurrentPlayer(), i)); assertTrue(game.SlotChoiceByIndex(game.getCurrentState().getCurrentPlayer(), i));
} }
@@ -857,14 +879,19 @@ class GameTest {
completeSlotChoice(game); completeSlotChoice(game);
} }
if (game.getCurrentState().getGameStage() == GameStages.RESOLVING_ACTIONS) { if (game.getCurrentState().getGameStage() == GameStages.RES_ACTIONS) {
Player current = game.getCurrentState().getCurrentPlayer(); Player current = game.getCurrentState().getCurrentPlayer();
assertNotNull(current); assertNotNull(current);
if (game.getCurrentState().getNLower() > 0 if (game.getCurrentState().getNLower() > 0
&& !game.getLowerListBuilding().isEmpty()) { && !game.getLowerListBuilding().isEmpty()) {
current.addFood(100); current.builders.clear();
BuildingCard selectedBuilding = game.getLowerListBuilding().get(0);
int expectedCost = selectedBuilding.getPrice();
current.addFood(expectedCost);
int buildingsBefore = current.buildingCards.size(); int buildingsBefore = current.buildingCards.size();
int lowerBuildingsBefore = game.getLowerListBuilding().size(); int lowerBuildingsBefore = game.getLowerListBuilding().size();
@@ -877,15 +904,23 @@ class GameTest {
assertEquals(buildingsBefore + 1, current.buildingCards.size()); assertEquals(buildingsBefore + 1, current.buildingCards.size());
assertEquals(lowerBuildingsBefore - 1, game.getLowerListBuilding().size()); assertEquals(lowerBuildingsBefore - 1, game.getLowerListBuilding().size());
assertTrue(current.getFoodValue() < foodBefore); assertTrue(current.buildingCards.stream()
.anyMatch(building ->
building.getPrice() == selectedBuilding.getPrice()
&& building.getPrestigeValue() == selectedBuilding.getPrestigeValue()
&& building.getEffectId() == selectedBuilding.getEffectId()
));
assertTrue(
current.getFoodValue() >= foodBefore - expectedCost,
"After buying the building, food should not be lower than the price paid because later effects may add food."
);
return; return;
} }
resolveOneMandatoryAction(game); resolveOneMandatoryAction(game);
} }
if (game.getCurrentState().getGameStage() == GameStages.OPTIONAL_CARD_EFFECT) { if (game.getCurrentState().getGameStage() == GameStages.OPT_CARD_E) {
resolveOptionalPhaseIfPresent(game); resolveOptionalPhaseIfPresent(game);
} }
@@ -904,18 +939,20 @@ class GameTest {
completeSlotChoice(game); completeSlotChoice(game);
while (game.getCurrentState().getGameStage() == GameStages.RESOLVING_ACTIONS) { while (game.getCurrentState().getGameStage() == GameStages.RES_ACTIONS) {
Player current = game.getCurrentState().getCurrentPlayer(); Player current = game.getCurrentState().getCurrentPlayer();
if (game.getCurrentState().getNUpper() > 0 if (game.getCurrentState().getNUpper() > 0
&& !game.getUpperListBuilding().isEmpty() && !game.getUpperListBuilding().isEmpty()) {
&& current.builders.isEmpty()) {
while (current.getFoodValue() > 0) { while (current.getFoodValue() > 0) {
assertTrue(current.removeFood(1)); assertTrue(current.removeFood(1));
} }
current.builders.clear();
assertEquals(0, current.getFoodValue()); assertEquals(0, current.getFoodValue());
assertFalse(game.DrawUpperBuildingCardByIndex(current, 0)); assertFalse(game.DrawUpperBuildingCardByIndex(current, 0));
return; return;
} }
@@ -923,7 +960,7 @@ class GameTest {
resolveOneMandatoryAction(game); resolveOneMandatoryAction(game);
} }
fail("No upper building draw state reached with a player without builders."); fail("No upper building draw state reached.");
} }
@Test @Test
@@ -940,7 +977,7 @@ class GameTest {
Player thirdChooser = game.getCurrentState().getCurrentPlayer(); Player thirdChooser = game.getCurrentState().getCurrentPlayer();
assertTrue(game.SlotChoiceByIndex(thirdChooser, 1)); assertTrue(game.SlotChoiceByIndex(thirdChooser, 1));
assertEquals(GameStages.RESOLVING_ACTIONS, game.getCurrentState().getGameStage()); assertEquals(GameStages.RES_ACTIONS, game.getCurrentState().getGameStage());
assertEquals(secondChooser, game.getCurrentState().getCurrentPlayer()); assertEquals(secondChooser, game.getCurrentState().getCurrentPlayer());
@@ -952,4 +989,110 @@ class GameTest {
assertEquals(firstChooser, game.getCurrentState().getCurrentPlayer()); assertEquals(firstChooser, game.getCurrentState().getCurrentPlayer());
} }
@Test
@Timeout(value = 20, unit = TimeUnit.SECONDS)
void endGameShouldNotCrashWhenTriggeredAfterRoundTen() {
Game game = new Game(3);
List<Player> players = addPlayers(game, 3, "end_game_");
giveOptionalEffectToAllPlayers(players.get(0), players.get(1), players.get(2));
while (game.getCurrentState().getRound() < 10) {
playOneFullRound(game);
}
assertEquals(10, game.getCurrentState().getRound());
assertEquals(GameStages.SLOT_CHOICE, game.getCurrentState().getGameStage());
completeSlotChoice(game);
resolveAllMandatoryActions(game);
assertEquals(GameStages.OPT_CARD_E, game.getCurrentState().getGameStage());
assertDoesNotThrow(() -> resolveOptionalPhaseIfPresent(game));
assertEquals(GameStages.ENDED, game.getCurrentState().getGameStage());
}
@Test
@Timeout(value = 20, unit = TimeUnit.SECONDS)
void endGameShouldAddBuildingPrestigeValues() {
Game game = new Game(3);
List<Player> players = addPlayers(game, 3, "building_prestige_");
giveOptionalEffectToAllPlayers(players.get(0), players.get(1), players.get(2));
while (game.getCurrentState().getRound() < 10) {
playOneFullRound(game);
}
completeSlotChoice(game);
resolveAllMandatoryActions(game);
assertEquals(GameStages.OPT_CARD_E, game.getCurrentState().getGameStage());
Player player = players.get(0);
int prestigeBefore = player.getPrestigeValue();
player.buildingCards.add(new BuildingCard(12, 1, 1, 7));
player.buildingCards.add(new BuildingCard(12, 1, 1, 5));
int expectedMinimumIncrease = 7 + 5;
resolveOptionalPhaseIfPresent(game);
assertEquals(GameStages.ENDED, game.getCurrentState().getGameStage());
assertTrue(
player.getPrestigeValue() >= prestigeBefore + expectedMinimumIncrease,
"Final scoring should add at least the prestige values of the two added building cards."
);
}
@Test
@Timeout(value = 20, unit = TimeUnit.SECONDS)
void endGameShouldApplyFinalCharacterPrestigeBonuses() {
Game game = new Game(3);
List<Player> players = addPlayers(game, 3, "final_characters_");
giveOptionalEffectToAllPlayers(players.get(0), players.get(1), players.get(2));
while (game.getCurrentState().getRound() < 10) {
playOneFullRound(game);
}
completeSlotChoice(game);
resolveAllMandatoryActions(game);
assertEquals(GameStages.OPT_CARD_E, game.getCurrentState().getGameStage());
Player player = players.get(0);
assertNotNull(player);
int prestigeBefore = player.getPrestigeValue();
player.builders.add(new Builder(1, 0, 4));
player.inventors.add(new Inventor(1, 0));
player.inventors.add(new Inventor(1, 1));
player.artists.add(new Artist(1));
player.artists.add(new Artist(1));
int expectedMinimumIncrease = 4 + 4 + 10;
resolveOptionalPhaseIfPresent(game);
assertEquals(GameStages.ENDED, game.getCurrentState().getGameStage());
assertTrue(
player.getPrestigeValue() >= prestigeBefore + expectedMinimumIncrease,
"Final scoring should add at least builder prestige, inventor bonus, and artist pair bonus."
);
}
} }