From 34e6620168c4d5c8186c9c5aa624cd0bbee2dea8 Mon Sep 17 00:00:00 2001 From: akmsw Date: Sun, 19 May 2024 01:55:47 -0300 Subject: [PATCH] enhance algorithm to verify anchorages conflicts, fix documentation --- src/main/java/armameeldoparti/Main.java | 12 +- .../controllers/AnchoragesController.java | 164 ++++++++---------- .../controllers/Controller.java | 4 +- .../java/armameeldoparti/models/Team.java | 22 ++- .../utils/common/CommonFields.java | 20 +-- .../utils/common/CommonFunctions.java | 2 +- .../utils/common/Constants.java | 2 +- .../utils/mixers/BySkillPointsMixer.java | 2 +- .../utils/mixers/RandomMixer.java | 82 ++++----- .../armameeldoparti/views/NamesInputView.java | 2 +- 10 files changed, 148 insertions(+), 164 deletions(-) diff --git a/src/main/java/armameeldoparti/Main.java b/src/main/java/armameeldoparti/Main.java index 37ad6b8..01d5fd3 100644 --- a/src/main/java/armameeldoparti/Main.java +++ b/src/main/java/armameeldoparti/Main.java @@ -70,8 +70,8 @@ public static void main(String[] args) { CommonFields.setActiveMonitor(GraphicsEnvironment.getLocalGraphicsEnvironment() .getDefaultScreenDevice()); CommonFields.setAnchoragesEnabled(false); - CommonFields.setControllerMap(new EnumMap<>(ProgramView.class)); - CommonFields.setPlayersAmountMap(new EnumMap<>(Position.class)); + CommonFields.setControllersMap(new EnumMap<>(ProgramView.class)); + CommonFields.setPlayersLimitPerPosition(new EnumMap<>(Position.class)); CommonFields.setPlayersSets(new TreeMap<>()); CommonFields.setPositionsMap(Map.of(Position.CENTRAL_DEFENDER, Constants.POSITION_CENTRAL_DEFENDERS, Position.LATERAL_DEFENDER, Constants.POSITION_LATERAL_DEFENDERS, @@ -98,7 +98,7 @@ public static void main(String[] args) { private static void populatePlayersSets() { Arrays.stream(Position.values()) .forEach(position -> CommonFields.getPlayersSets() - .put(position, IntStream.range(0, CommonFields.getPlayersAmountMap() + .put(position, IntStream.range(0, CommonFields.getPlayersLimitPerPosition() .get(position) * 2) .mapToObj(_ -> new Player("", position)) .toList())); @@ -134,10 +134,10 @@ private static void setPlayersDistribution() { .toList(); IntStream.range(0, filteredLines.size()) - .forEach(index -> CommonFields.getPlayersAmountMap() + .forEach(index -> CommonFields.getPlayersLimitPerPosition() .put(Position.values()[index], Integer.parseInt(filteredLines.get(index) - .replaceAll(Constants.REGEX_PLAYERS_AMOUNT, "")))); + .replaceAll(Constants.REGEX_PLAYERS_COUNT, "")))); } catch (IOException _) { CommonFunctions.exitProgram(Error.ERROR_FILES); } @@ -147,7 +147,7 @@ private static void setPlayersDistribution() { * Creates the controllers and assigns their corresponding view to control. */ private static void setUpControllers() { - CommonFields.getControllerMap() + CommonFields.getControllersMap() .putAll(Map.of(ProgramView.MAIN_MENU, new MainMenuController(new MainMenuView()), ProgramView.HELP, new HelpController(new HelpView()), ProgramView.NAMES_INPUT, new NamesInputController(new NamesInputView()), diff --git a/src/main/java/armameeldoparti/controllers/AnchoragesController.java b/src/main/java/armameeldoparti/controllers/AnchoragesController.java index 06413f5..6f11c54 100644 --- a/src/main/java/armameeldoparti/controllers/AnchoragesController.java +++ b/src/main/java/armameeldoparti/controllers/AnchoragesController.java @@ -11,10 +11,8 @@ import java.awt.Component; import java.util.Arrays; import java.util.Comparator; -import java.util.EnumMap; import java.util.List; import java.util.Map; -import java.util.stream.Collectors; import java.util.stream.IntStream; import javax.swing.JCheckBox; import javax.swing.JOptionPane; @@ -32,8 +30,8 @@ public class AnchoragesController extends Controller { // ---------- Private constants -------------------------------------------------------------------------------------------------------------------- - private int anchoragesAmount; - private int anchoredPlayersAmount; + private int anchoragesCount; + private int anchoredPlayersCount; // ---------- Constructor -------------------------------------------------------------------------------------------------------------------------- @@ -101,14 +99,18 @@ public void newAnchorageButtonEvent(Component parentComponent) { return; } - int playersToAnchorAmount = (int) view.getCheckboxesMap() - .values() - .stream() - .flatMap(List::stream) - .filter(JCheckBox::isSelected) - .count(); + int playersToAnchorCount = (int) view.getCheckboxesMap() + .values() + .stream() + .flatMap(List::stream) + .filter(JCheckBox::isSelected) + .count(); - if (!validChecksAmount(playersToAnchorAmount)) { + if (playersToAnchorCount == 0) { + CommonFunctions.showErrorMessage("No hay jugadores seleccionados para anclar", parentComponent); + + return; + } else if (!validChecksCount(playersToAnchorCount)) { CommonFunctions.showErrorMessage( "No puede haber más de " + Constants.MAX_PLAYERS_PER_ANCHORAGE + " ni menos de " + Constants.MIN_PLAYERS_PER_ANCHORAGE @@ -119,7 +121,7 @@ public void newAnchorageButtonEvent(Component parentComponent) { return; } - if (!validAnchoredPlayersAmount(playersToAnchorAmount)) { + if (!validAnchoredPlayersCount(playersToAnchorCount)) { CommonFunctions.showErrorMessage("No puede haber más de " + Constants.MAX_ANCHORED_PLAYERS + " jugadores anclados en total", parentComponent); return; @@ -134,7 +136,7 @@ public void newAnchorageButtonEvent(Component parentComponent) { * Deletes the last anchorage made, updating the text area and the state of the buttons. */ public void deleteLastAnchorageButtonEvent() { - deleteAnchorage(anchoragesAmount); + deleteAnchorage(anchoragesCount); updateTextArea(); toggleButtons(); } @@ -145,7 +147,7 @@ public void deleteLastAnchorageButtonEvent() { * @param parentComponent Graphical component where the dialogs associated with the event should be displayed. */ public void deleteAnchorageButtonEvent(Component parentComponent) { - String[] optionsDelete = IntStream.rangeClosed(1, anchoragesAmount) + String[] optionsDelete = IntStream.rangeClosed(1, anchoragesCount) .mapToObj(Integer::toString) .toArray(String[]::new); @@ -203,15 +205,17 @@ protected void resetView() { @Override protected void setUpInitialState() { - anchoragesAmount = 0; - anchoredPlayersAmount = 0; + anchoragesCount = 0; + anchoredPlayersCount = 0; view.getFinishButton() .setEnabled(false); } /** - * The "java:S1190" and "java:S117" warnings are suppressed since JDK22 allows the use of unnamed variables. + * Sets up the GUI components event listeners. + * + *

The "java:S1190" and "java:S117" warnings are suppressed since JDK22 allows the use of unnamed variables. */ @Override @SuppressWarnings({"java:S1190", "java:S117"}) @@ -238,7 +242,7 @@ protected void setUpListeners() { * @see #setAnchorages(List) */ private void newAnchorage() { - anchoragesAmount++; + anchoragesCount++; view.getCheckboxesMap() .values() @@ -247,12 +251,12 @@ private void newAnchorage() { .anyMatch(JCheckBox::isSelected)) .forEach(this::setAnchorages); - anchoredPlayersAmount = (int) CommonFields.getPlayersSets() - .values() - .stream() - .flatMap(List::stream) - .filter(Player::isAnchored) - .count(); + anchoredPlayersCount = (int) CommonFields.getPlayersSets() + .values() + .stream() + .flatMap(List::stream) + .filter(Player::isAnchored) + .count(); } /** @@ -266,7 +270,7 @@ private void updateTextArea() { view.getTextArea() .setText(""); - IntStream.range(0, anchoragesAmount) + IntStream.range(0, anchoragesCount) .forEach(anchorageNumber -> { view.getTextArea() .append("ANCLAJE " + (anchorageNumber + 1) + System.lineSeparator()); @@ -286,7 +290,7 @@ private void updateTextArea() { .append((anchorage.indexOf(player) + 1) + ". " + player.getName() + System.lineSeparator()); } - if ((anchorageNumber + 1) != anchoragesAmount) { + if ((anchorageNumber + 1) != anchoragesCount) { view.getTextArea() .append(System.lineSeparator()); } @@ -300,19 +304,19 @@ private void toggleButtons() { view.getAnchorageButtons() .forEach(button -> button.setEnabled(false)); - if (anchoragesAmount == 1) { + if (anchoragesCount == 1) { view.getFinishButton() .setEnabled(true); view.getDeleteLastAnchorageButton() .setEnabled(true); view.getClearAnchoragesButton() .setEnabled(true); - } else if (anchoragesAmount > 1) { + } else if (anchoragesCount > 1) { view.getAnchorageButtons() .forEach(button -> button.setEnabled(true)); } - if (Constants.MAX_ANCHORED_PLAYERS - anchoredPlayersAmount < 2) { + if (Constants.MAX_ANCHORED_PLAYERS - anchoredPlayersCount < 2) { view.getNewAnchorageButton() .setEnabled(false); view.getCheckboxesMap() @@ -338,8 +342,8 @@ private void toggleButtons() { * @see #deleteAnchorage(int) */ private void clearAnchorages() { - while (anchoragesAmount > 0) { - deleteAnchorage(anchoragesAmount); + while (anchoragesCount > 0) { + deleteAnchorage(anchoragesCount); } } @@ -347,27 +351,27 @@ private void clearAnchorages() { * Deletes a specific anchorage. * *

The players that have the specified anchorage now will have anchorage number 0. If the anchorage number to delete is not the last one, then - * the remaining players (from {@code anchorageToDelete + 1} up to {@code anchoragesAmount}) will have their anchorage number decreased by 1. + * the remaining players (from {@code anchorageToDelete + 1} up to {@code anchoragesCount}) will have their anchorage number decreased by 1. * * @param anchorageToDelete Anchorage number to delete. */ private void deleteAnchorage(int anchorageToDelete) { changeAnchorage(anchorageToDelete, 0); - if (anchorageToDelete != anchoragesAmount) { - for (int anchorageNumber = anchorageToDelete + 1; anchorageNumber <= anchoragesAmount; anchorageNumber++) { + if (anchorageToDelete != anchoragesCount) { + for (int anchorageNumber = anchorageToDelete + 1; anchorageNumber <= anchoragesCount; anchorageNumber++) { changeAnchorage(anchorageNumber, anchorageNumber - 1); } } - anchoragesAmount--; + anchoragesCount--; } /** * Changes the anchorage number of certain players. * *

If the replacement is 0 (an anchorage must be removed), then those players will be set as not-anchored, the players corresponding checkboxes - * will be visible and enabled again, and the anchored players amount will be decreased as needed. + * will be visible and enabled again, and the anchored players count will be decreased as needed. * * @param target Anchorage number to replace. * @param replacement New anchorage number to set. @@ -393,7 +397,7 @@ private void changeAnchorage(int target, int replacement) { .findFirst()) .setVisible(true); - anchoredPlayersAmount--; + anchoredPlayersCount--; } } ); @@ -433,7 +437,7 @@ private void setAnchorages(List cbSet) { .anyMatch(checkbox -> checkbox.getText() .equals(player.getName()))) .forEach(player -> { - player.setAnchorageNumber(anchoragesAmount); + player.setAnchorageNumber(anchoragesCount); player.setAnchored(true); }); @@ -458,19 +462,15 @@ private void clearCheckboxes() { } /** - * Checks if the selected players amount is at least 2 and at most MAX_PLAYERS_PER_ANCHORAGE. + * @param playersToAnchorCount Selected players to anchor. * - * @param playersToAnchorAmount Checked players to anchor. - * - * @return Whether the checked players amount is at least 2 and at most MAX_PLAYERS_PER_ANCHORAGE. + * @return Whether the number of selected players is at least 2 and at most MAX_PLAYERS_PER_ANCHORAGE. */ - private boolean validChecksAmount(int playersToAnchorAmount) { - return playersToAnchorAmount <= Constants.MAX_PLAYERS_PER_ANCHORAGE && playersToAnchorAmount >= 2; + private boolean validChecksCount(int playersToAnchorCount) { + return playersToAnchorCount <= Constants.MAX_PLAYERS_PER_ANCHORAGE && playersToAnchorCount >= 2; } /** - * Checks if more than half of any players set is selected. - * * @return Whether more than half of any players set is checked. */ private boolean validCheckedPlayersPerPosition() { @@ -483,22 +483,27 @@ private boolean validCheckedPlayersPerPosition() { } /** - * Checks if the selected players amount is at most the maximum allowed per anchorage. - * - * @param playersToAnchorAmount Checked players amount. + * @param playersToAnchorCount Number of checked players. * - * @return Whether the selected players amount is at most the maximum allowed per anchorage. + * @return Whether the number of selected players is at most the maximum allowed per anchorage. */ - private boolean validAnchoredPlayersAmount(int playersToAnchorAmount) { - return anchoredPlayersAmount + playersToAnchorAmount <= Constants.MAX_ANCHORED_PLAYERS; + private boolean validAnchoredPlayersCount(int playersToAnchorCount) { + return anchoredPlayersCount + playersToAnchorCount <= Constants.MAX_ANCHORED_PLAYERS; } /** + * Verifies recursively if the existing anchorages combination is possible to distribute (i.e.: no anchorages conflict exists) prior to perform the + * distribution itself. * - * @param recursiveVerificationIndex - * @param teams + *

It starts by gathering the first anchorage: if there's no conflict in the first team, then it is added to it. If not, it tries to add it to + * the second team. If the anchorage can't be added successfully to any team, then an anchorages conflict exists. This procedure is repeated + * recursively with every anchorage. When the final anchorage is reached, the resulting temporary teams are validated to return that as the + * recursion break condition. * - * @return + * @param recursiveVerificationIndex Recursive index used to iterate through the existing anchorages. + * @param teams Empty, temporary teams. + * + * @return Whether the existing anchorages combination is possible to distribute. */ private boolean validAnchoragesCombination(int recursiveVerificationIndex, List teams) { if (recursiveVerificationIndex == CommonFunctions.getAnchoredPlayers() @@ -529,64 +534,39 @@ private boolean validAnchoragesCombination(int recursiveVerificationIndex, List< } /** - * The "java:S1190" and "java:S117" warnings are suppressed since JDK22 allows the use of unnamed variables. - * - * @param team - * @param anchorage + * @param team Temporary team. + * @param anchorage Anchorage to validate. * - * @return + * @return Whether a given anchorage can be added to a given team without exceeding any players limit for their position sets. */ - @SuppressWarnings({"java:S1190", "java:S117"}) private boolean anchoragesConflictExists(Team team, List anchorage) { - Map playersPerPosition = team.getTeamPlayers() - .values() - .stream() - .flatMap(List::stream) - .collect(Collectors.toMap( - Player::getPosition, - _ -> 1, - Integer::sum, - () -> new EnumMap<>(Position.class)) - ); + Map playersCountPerPosition = team.getPlayersCountPerPosition(); for (Player player : anchorage) { - int newCount = playersPerPosition.getOrDefault(player.getPosition(), 0) + 1; + int newCount = playersCountPerPosition.getOrDefault(player.getPosition(), 0) + 1; - if (newCount > CommonFields.getPlayersAmountMap() + if (newCount > CommonFields.getPlayersLimitPerPosition() .get(player.getPosition())) { return true; } - playersPerPosition.put(player.getPosition(), newCount); + playersCountPerPosition.put(player.getPosition(), newCount); } return false; } /** - * The "java:S1190" and "java:S117" warnings are suppressed since JDK22 allows the use of unnamed variables. - * - * @param teams + * @param teams Temporary teams. * - * @return + * @return Whether any of the given teams has any position set with more than its allowed players limit. */ - @SuppressWarnings({"java:S1190", "java:S117"}) private boolean validTeams(List teams) { for (Team team : teams) { - Map playersPerPosition = team.getTeamPlayers() - .values() - .stream() - .flatMap(List::stream) - .collect(Collectors.toMap( - Player::getPosition, - _ -> 1, - Integer::sum, - () -> new EnumMap<>(Position.class)) - ); - - for (Map.Entry entry : CommonFields.getPlayersAmountMap() + for (Map.Entry limit : CommonFields.getPlayersLimitPerPosition() .entrySet()) { - if (playersPerPosition.getOrDefault(entry.getKey(), 0) > entry.getValue()) { + if (team.getPlayersCountPerPosition() + .getOrDefault(limit.getKey(), 0) > limit.getValue()) { return false; } } diff --git a/src/main/java/armameeldoparti/controllers/Controller.java b/src/main/java/armameeldoparti/controllers/Controller.java index 2993785..bbc0572 100644 --- a/src/main/java/armameeldoparti/controllers/Controller.java +++ b/src/main/java/armameeldoparti/controllers/Controller.java @@ -73,12 +73,12 @@ protected void showView() { protected abstract void resetView(); /** - * Sets up the view's GUI components initial state if needed. + * Sets up the controller and GUI components initial state, if needed. */ protected abstract void setUpInitialState(); /** - * Sets up the view's GUI components event listeners. + * Sets up the GUI components event listeners. */ protected abstract void setUpListeners(); diff --git a/src/main/java/armameeldoparti/models/Team.java b/src/main/java/armameeldoparti/models/Team.java index 0a67f56..d9c5942 100644 --- a/src/main/java/armameeldoparti/models/Team.java +++ b/src/main/java/armameeldoparti/models/Team.java @@ -5,6 +5,7 @@ import java.util.EnumMap; import java.util.List; import java.util.Map; +import java.util.stream.Collectors; /** * Team class. @@ -27,6 +28,8 @@ public class Team { /** * Builds a basic team with empty position sets. + * + * @param teamNumber Integer identification for the team. */ public Team(int teamNumber) { setTeamPlayers(new EnumMap<>(Position.class)); @@ -49,7 +52,7 @@ public void clear() { } /** - * @return The amount of players in the team. + * @return The number of players in the team. */ public int getPlayersCount() { return teamPlayers.values() @@ -58,6 +61,19 @@ public int getPlayersCount() { .sum(); } + /** + *

The "java:S1190" and "java:S117" warnings are suppressed since JDK22 allows the use of unnamed variables. + * + * @return The number of players per position in the team. + */ + @SuppressWarnings({"java:S1190", "java:S117"}) + public Map getPlayersCountPerPosition() { + return teamPlayers.values() + .stream() + .flatMap(List::stream) + .collect(Collectors.toMap(Player::getPosition, _ -> 1, Integer::sum, () -> new EnumMap<>(Position.class))); + } + /** * @return The team skill points accumulated so far. */ @@ -70,15 +86,13 @@ public int getTeamSkill() { } /** - * Checks if a particular position set in the team is full. - * * @param position The position of the set to check. * * @return Whether the specified position set in the team is full. */ public boolean isPositionFull(Position position) { return teamPlayers.get(position) - .size() == CommonFields.getPlayersAmountMap() + .size() == CommonFields.getPlayersLimitPerPosition() .get(position); } diff --git a/src/main/java/armameeldoparti/utils/common/CommonFields.java b/src/main/java/armameeldoparti/utils/common/CommonFields.java index 8e6dd7d..ca3e3ed 100644 --- a/src/main/java/armameeldoparti/utils/common/CommonFields.java +++ b/src/main/java/armameeldoparti/utils/common/CommonFields.java @@ -28,10 +28,10 @@ public final class CommonFields { private static GraphicsDevice activeMonitor; - private static Map playersAmountMap; + private static Map playersLimitPerPosition; private static Map> playersSets; private static Map positionsMap; - private static Map> controllerMap; + private static Map> controllersMap; // ---------- Constructor -------------------------------------------------------------------------------------------------------------------------- @@ -56,8 +56,8 @@ public static GraphicsDevice getActiveMonitor() { return activeMonitor; } - public static Map getPlayersAmountMap() { - return playersAmountMap; + public static Map getPlayersLimitPerPosition() { + return playersLimitPerPosition; } public static Map> getPlayersSets() { @@ -72,8 +72,8 @@ public static Map getPositionsMap() { * The "java:S1452" warning is suppressed since the Java compiler can't know at runtime the type of the controlled view. */ @SuppressWarnings("java:S1452") - public static Map> getControllerMap() { - return controllerMap; + public static Map> getControllersMap() { + return controllersMap; } // ---------- Setters ------------------------------------------------------------------------------------------------------------------------------ @@ -90,8 +90,8 @@ public static void setActiveMonitor(GraphicsDevice activeMonitor) { CommonFields.activeMonitor = activeMonitor; } - public static void setPlayersAmountMap(Map playersAmountMap) { - CommonFields.playersAmountMap = playersAmountMap; + public static void setPlayersLimitPerPosition(Map playersLimitPerPosition) { + CommonFields.playersLimitPerPosition = playersLimitPerPosition; } public static void setPlayersSets(Map> playersSets) { @@ -102,7 +102,7 @@ public static void setPositionsMap(Map positionsMap) { CommonFields.positionsMap = positionsMap; } - public static void setControllerMap(Map> controllerMap) { - CommonFields.controllerMap = controllerMap; + public static void setControllersMap(Map> controllerMap) { + CommonFields.controllersMap = controllerMap; } } \ No newline at end of file diff --git a/src/main/java/armameeldoparti/utils/common/CommonFunctions.java b/src/main/java/armameeldoparti/utils/common/CommonFunctions.java index 2ad3df5..54b511c 100644 --- a/src/main/java/armameeldoparti/utils/common/CommonFunctions.java +++ b/src/main/java/armameeldoparti/utils/common/CommonFunctions.java @@ -205,7 +205,7 @@ public static ImageIcon scaleImageIcon(ImageIcon icon, int width, int height, in */ @SuppressWarnings("java:S1452") public static Controller getController(ProgramView view) { - return CommonFields.getControllerMap() + return CommonFields.getControllersMap() .get(view); } diff --git a/src/main/java/armameeldoparti/utils/common/Constants.java b/src/main/java/armameeldoparti/utils/common/Constants.java index 101df4e..1b2be66 100644 --- a/src/main/java/armameeldoparti/utils/common/Constants.java +++ b/src/main/java/armameeldoparti/utils/common/Constants.java @@ -165,7 +165,7 @@ public final class Constants { public static final String PROGRAM_AUTHOR = "@" + PROGRAM_AUTHOR_GITHUB_USERNAME; public static final String REGEX_NAMES_VALIDATION = "[a-z A-ZÁÉÍÓÚáéíóúñÑ]+"; public static final String REGEX_PDA_DATA_RETRIEVE = "[CLMFG].+>.+"; - public static final String REGEX_PLAYERS_AMOUNT = "(?!(?<=" + PLAYERS_PER_TEAM + ")\\d)."; + public static final String REGEX_PLAYERS_COUNT = "(?!(?<=" + PLAYERS_PER_TEAM + ")\\d)."; public static final String URL_CONTACT = "https://github.com/" + PROGRAM_AUTHOR_GITHUB_USERNAME; public static final String URL_ISSUES = URL_CONTACT + "/" + PROGRAM_TITLE.replace(" ", "-") + "/issues"; diff --git a/src/main/java/armameeldoparti/utils/mixers/BySkillPointsMixer.java b/src/main/java/armameeldoparti/utils/mixers/BySkillPointsMixer.java index 4324e06..0044518 100644 --- a/src/main/java/armameeldoparti/utils/mixers/BySkillPointsMixer.java +++ b/src/main/java/armameeldoparti/utils/mixers/BySkillPointsMixer.java @@ -89,7 +89,7 @@ public List withoutAnchorages(List teams) { * with the sets with most anchored players in order to avoid inconsistencies. * *

Then, the players that are not anchored are distributed between the teams as fair as possible based on their skill points. They will be added - * to a team only if the players per position or the players per team amounts are not exceeded. + * to a team only if the players per position or the players per team limits are not exceeded. * * @param teams Teams where to distribute the players. * diff --git a/src/main/java/armameeldoparti/utils/mixers/RandomMixer.java b/src/main/java/armameeldoparti/utils/mixers/RandomMixer.java index 4d2930d..58a0eb2 100644 --- a/src/main/java/armameeldoparti/utils/mixers/RandomMixer.java +++ b/src/main/java/armameeldoparti/utils/mixers/RandomMixer.java @@ -97,7 +97,7 @@ public List withoutAnchorages(List teams) { *

First, the anchored players are grouped in different lists by their anchorage number, and they are distributed randomly starting with the sets * with most anchored players in order to avoid inconsistencies. If a set of anchored players cannot be added to one team, it will be added to the * other. Then, the players that are not anchored are distributed randomly. They will be added to a team only if the players per position or the - * players per team amounts are not exceeded. + * players per team limits are not exceeded. * * @param teams Teams where to distribute the players. * @@ -148,36 +148,6 @@ public List withAnchorages(List teams) { // ---------- Private methods ---------------------------------------------------------------------------------------------------------------------- - /** - * Checks which team a given player can be added to. - * - * @param teams The possible teams where to add the player. - * @param validationPredicate The predicate that will validate if the player can be added to a team, or not. - * - * @return The only available team index, a random team index if the player can be added in every team, or -1 if there's no available team for the - * player. - */ - private int getAvailableTeam(List teams, Predicate validationPredicate) { - shuffleTeamNumbers(teams.size()); - - boolean isRandomTeam1Available = validationPredicate.test(teams.get(randomTeam1)); - boolean isRandomTeam2Available = validationPredicate.test(teams.get(randomTeam2)); - - if (isRandomTeam1Available && isRandomTeam2Available) { - return randomGenerator.nextInt(teams.size()); - } - - if (isRandomTeam1Available) { - return randomTeam1; - } - - if (isRandomTeam2Available) { - return randomTeam2; - } - - return -1; - } - /** * Randomly shuffles the team numbers. * @@ -189,8 +159,6 @@ private void shuffleTeamNumbers(int range) { } /** - * Checks if the given player position in the given team is already complete and, therefore, if the player can be added to it. - * * @param team Team where the player should be added. * @param player The players to add. * @@ -217,25 +185,20 @@ private boolean anchorageCanBeAdded(Team team, List anchoredPlayers) { } /** - * Checks if the amount of anchored players to be added to a team would exceed the maximum allowed amount of players per team. - * * @param team Team to check if the anchored players can be added. * @param anchoredPlayers Anchored players to check. * - * @return Whether the amount of anchored players to be added to a team would exceed the maximum allowed amount of players per team. + * @return Whether the number of anchored players to be added to a team would exceed the limit of players per team. */ private boolean anchorageOverflowsTeamSize(Team team, List anchoredPlayers) { return team.getPlayersCount() + anchoredPlayers.size() > Constants.PLAYERS_PER_TEAM; } /** - * Checks if the amount of anchored players to be added to a team would exceed the maximum allowed amount of players per team in any position set. - * * @param team Team to check if the anchored players can be added. * @param anchoredPlayers Anchored players to check. * - * @return Whether the amount of anchored players to be added to a team would exceed the maximum allowed amount of players per team in any position - * set. + * @return Whether the number of anchored players to be added to a team would exceed the limit of players per team in any position set. */ private boolean anchorageOverflowsAnyPositionSet(Team team, List anchoredPlayers) { return anchoredPlayers.stream() @@ -244,15 +207,12 @@ private boolean anchorageOverflowsAnyPositionSet(Team team, List anchore } /** - * Checks if the amount of anchored players to be added to a position set in a team would exceed the maximum allowed amount of players per team for - * that particular position. - * * @param team Team to check if the anchored players can be added. * @param anchoredPlayers Anchored players to check. * @param position Anchored players position. * - * @return Whether the amount of anchored players to be added to a position set in a team would exceed the maximum allowed amount of players per - * team for that particular position. + * @return Whether the number of anchored players to be added to a position set in a team would exceed the limit of players per team for that + * particular position. */ private boolean anchorageOverflowsPositionSet(Team team, List anchoredPlayers, Position position) { return team.getTeamPlayers() @@ -261,7 +221,37 @@ private boolean anchorageOverflowsPositionSet(Team team, List anchoredPl + anchoredPlayers.stream() .filter(player -> player.getPosition() == position) .count() - > CommonFields.getPlayersAmountMap() + > CommonFields.getPlayersLimitPerPosition() .get(position); } + + /** + * Checks which team a given player can be added to. + * + * @param teams The possible teams where to add the player. + * @param validationPredicate The predicate that will validate if the player can be added to a team, or not. + * + * @return The only available team index, a random team index if the player can be added in every team, or -1 if there's no available team for the + * player. + */ + private int getAvailableTeam(List teams, Predicate validationPredicate) { + shuffleTeamNumbers(teams.size()); + + boolean isRandomTeam1Available = validationPredicate.test(teams.get(randomTeam1)); + boolean isRandomTeam2Available = validationPredicate.test(teams.get(randomTeam2)); + + if (isRandomTeam1Available && isRandomTeam2Available) { + return randomGenerator.nextInt(teams.size()); + } + + if (isRandomTeam1Available) { + return randomTeam1; + } + + if (isRandomTeam2Available) { + return randomTeam2; + } + + return -1; + } } \ No newline at end of file diff --git a/src/main/java/armameeldoparti/views/NamesInputView.java b/src/main/java/armameeldoparti/views/NamesInputView.java index bea312a..b321566 100644 --- a/src/main/java/armameeldoparti/views/NamesInputView.java +++ b/src/main/java/armameeldoparti/views/NamesInputView.java @@ -152,7 +152,7 @@ private void addAnchoragesCheckbox() { private void addTextFields() { for (Position position : Position.values()) { textFieldsMap.get(position) - .addAll(IntStream.range(0, CommonFields.getPlayersAmountMap() + .addAll(IntStream.range(0, CommonFields.getPlayersLimitPerPosition() .get(position) * 2) .mapToObj(_ -> new CustomTextField()) .toList());