Search in sources :

Example 6 with Tuple

use of com.minecolonies.api.util.Tuple in project minecolonies by ldtteam.

the class AbstractEntityAIRequestSmelter method fillUpFurnace.

/**
 * Smelt the smeltable after the required items are in the inv.
 *
 * @return the next state to go to.
 */
private IAIState fillUpFurnace() {
    final FurnaceUserModule module = getOwnBuilding().getFirstModuleOccurance(FurnaceUserModule.class);
    if (module.getFurnaces().isEmpty()) {
        if (worker.getCitizenData() != null) {
            worker.getCitizenData().triggerInteraction(new StandardInteraction(new TranslationTextComponent(BAKER_HAS_NO_FURNACES_MESSAGE), ChatPriority.BLOCKING));
        }
        setDelay(STANDARD_DELAY);
        return START_WORKING;
    }
    if (walkTo == null || world.getBlockState(walkTo).getBlock() != Blocks.FURNACE) {
        walkTo = null;
        setDelay(STANDARD_DELAY);
        return START_WORKING;
    }
    final int burningCount = countOfBurningFurnaces();
    final TileEntity entity = world.getBlockEntity(walkTo);
    if (entity instanceof FurnaceTileEntity && currentRecipeStorage != null) {
        final FurnaceTileEntity furnace = (FurnaceTileEntity) entity;
        final int maxFurnaces = getMaxUsableFurnaces();
        final Predicate<ItemStack> smeltable = stack -> ItemStackUtils.compareItemStacksIgnoreStackSize(currentRecipeStorage.getCleanedInput().get(0).getItemStack(), stack);
        final int smeltableInFurnaces = getExtendedCount(currentRecipeStorage.getCleanedInput().get(0).getItemStack());
        final int resultInFurnaces = getExtendedCount(currentRecipeStorage.getPrimaryOutput());
        final int resultInCitizenInv = InventoryUtils.getItemCountInItemHandler(worker.getInventoryCitizen(), stack -> ItemStackUtils.compareItemStacksIgnoreStackSize(stack, currentRecipeStorage.getPrimaryOutput()));
        final int targetCount = currentRequest.getRequest().getCount() - smeltableInFurnaces - resultInFurnaces - resultInCitizenInv;
        if (targetCount <= 0) {
            return START_WORKING;
        }
        final int amountOfSmeltableInBuilding = InventoryUtils.getCountFromBuilding(getOwnBuilding(), smeltable);
        final int amountOfSmeltableInInv = InventoryUtils.getItemCountInItemHandler(worker.getInventoryCitizen(), smeltable);
        if (worker.getItemInHand(Hand.MAIN_HAND).isEmpty()) {
            worker.setItemInHand(Hand.MAIN_HAND, currentRecipeStorage.getCleanedInput().get(0).getItemStack().copy());
        }
        if (amountOfSmeltableInInv > 0) {
            if (hasFuelInFurnaceAndNoSmeltable(furnace) || hasNeitherFuelNorSmeltAble(furnace)) {
                int toTransfer = 0;
                if (burningCount < maxFurnaces) {
                    final int availableFurnaces = maxFurnaces - burningCount;
                    if (targetCount > STACKSIZE * availableFurnaces) {
                        toTransfer = STACKSIZE;
                    } else {
                        // We need to split stacks and spread them across furnaces for best performance
                        // We will front-load the remainder
                        toTransfer = Math.min((targetCount / availableFurnaces) + (targetCount % availableFurnaces), STACKSIZE);
                    }
                }
                if (toTransfer > 0) {
                    if (walkToBlock(walkTo)) {
                        return getState();
                    }
                    worker.getCitizenItemHandler().hitBlockWithToolInHand(walkTo);
                    InventoryUtils.transferXInItemHandlerIntoSlotInItemHandler(worker.getInventoryCitizen(), smeltable, toTransfer, new InvWrapper(furnace), SMELTABLE_SLOT);
                }
            }
        } else if (amountOfSmeltableInBuilding >= targetCount - amountOfSmeltableInInv && currentRecipeStorage.getIntermediate() == Blocks.FURNACE) {
            needsCurrently = new Tuple<>(smeltable, targetCount);
            return GATHERING_REQUIRED_MATERIALS;
        } else {
            // This is a safety net for the AI getting way out of sync with it's tracking. It shouldn't happen.
            job.finishRequest(false);
            resetValues();
            walkTo = null;
            return IDLE;
        }
    } else if (!(world.getBlockState(walkTo).getBlock() instanceof FurnaceBlock)) {
        module.removeFromFurnaces(walkTo);
    }
    walkTo = null;
    setDelay(STANDARD_DELAY);
    return START_WORKING;
}
Also used : FurnaceTileEntity(net.minecraft.tileentity.FurnaceTileEntity) TileEntity(net.minecraft.tileentity.TileEntity) TICKS_20(com.minecolonies.api.util.constant.CitizenConstants.TICKS_20) IRequest(com.minecolonies.api.colony.requestsystem.request.IRequest) StackList(com.minecolonies.api.colony.requestsystem.requestable.StackList) ItemStackUtils(com.minecolonies.api.util.ItemStackUtils) IRecipeStorage(com.minecolonies.api.crafting.IRecipeStorage) TypeToken(com.google.common.reflect.TypeToken) FurnaceUserModule(com.minecolonies.coremod.colony.buildings.modules.FurnaceUserModule) AbstractJobCrafter(com.minecolonies.coremod.colony.jobs.AbstractJobCrafter) TranslationTextComponent(net.minecraft.util.text.TranslationTextComponent) ArrayList(java.util.ArrayList) ItemStack(net.minecraft.item.ItemStack) InvWrapper(net.minecraftforge.items.wrapper.InvWrapper) Tuple(com.minecolonies.api.util.Tuple) ImmutableList(com.google.common.collect.ImmutableList) IAIState(com.minecolonies.api.entity.ai.statemachine.states.IAIState) Hand(net.minecraft.util.Hand) AITarget(com.minecolonies.api.entity.ai.statemachine.AITarget) FUEL_LIST(com.minecolonies.api.util.constant.BuildingConstants.FUEL_LIST) ItemListModule(com.minecolonies.coremod.colony.buildings.modules.ItemListModule) Constants(com.minecolonies.api.util.constant.Constants) TranslationConstants(com.minecolonies.api.util.constant.TranslationConstants) AIEventTarget(com.minecolonies.api.entity.ai.statemachine.AIEventTarget) World(net.minecraft.world.World) Predicate(java.util.function.Predicate) RequestState(com.minecolonies.api.colony.requestsystem.request.RequestState) ChatPriority(com.minecolonies.api.colony.interactionhandling.ChatPriority) AIBlockingEventType(com.minecolonies.api.entity.ai.statemachine.states.AIBlockingEventType) AbstractBuilding(com.minecolonies.coremod.colony.buildings.AbstractBuilding) StandardInteraction(com.minecolonies.coremod.colony.interactionhandling.StandardInteraction) BlockPos(net.minecraft.util.math.BlockPos) FurnaceTileEntity(net.minecraft.tileentity.FurnaceTileEntity) AIWorkerState(com.minecolonies.api.entity.ai.statemachine.states.AIWorkerState) Blocks(net.minecraft.block.Blocks) List(java.util.List) PublicCrafting(com.minecolonies.api.colony.requestsystem.requestable.crafting.PublicCrafting) InventoryUtils(com.minecolonies.api.util.InventoryUtils) TileEntity(net.minecraft.tileentity.TileEntity) ItemStorage(com.minecolonies.api.crafting.ItemStorage) WorldUtil(com.minecolonies.api.util.WorldUtil) FurnaceBlock(net.minecraft.block.FurnaceBlock) NotNull(org.jetbrains.annotations.NotNull) StandardInteraction(com.minecolonies.coremod.colony.interactionhandling.StandardInteraction) InvWrapper(net.minecraftforge.items.wrapper.InvWrapper) TranslationTextComponent(net.minecraft.util.text.TranslationTextComponent) FurnaceTileEntity(net.minecraft.tileentity.FurnaceTileEntity) FurnaceBlock(net.minecraft.block.FurnaceBlock) ItemStack(net.minecraft.item.ItemStack) Tuple(com.minecolonies.api.util.Tuple) FurnaceUserModule(com.minecolonies.coremod.colony.buildings.modules.FurnaceUserModule)

Example 7 with Tuple

use of com.minecolonies.api.util.Tuple in project minecolonies by ldtteam.

the class EventHandler method onEntityConverted.

/**
 * Gets called when a Hoglin, Pig, Piglin, Villager, or ZombieVillager gets converted to something else.
 *
 * @param event the event to handle.
 */
@SubscribeEvent
public static void onEntityConverted(@NotNull final LivingConversionEvent.Pre event) {
    LivingEntity entity = event.getEntityLiving();
    if (entity instanceof ZombieVillagerEntity && event.getOutcome() == EntityType.VILLAGER) {
        final World world = entity.getCommandSenderWorld();
        final IColony colony = IColonyManager.getInstance().getIColony(world, entity.blockPosition());
        if (colony != null && colony.hasBuilding("tavern", 1, false)) {
            event.setCanceled(true);
            if (ForgeEventFactory.canLivingConvert(entity, ModEntities.VISITOR, null)) {
                IVisitorData visitorData = (IVisitorData) colony.getVisitorManager().createAndRegisterCivilianData();
                BlockPos tavernPos = colony.getBuildingManager().getRandomBuilding(b -> !b.getModules(TavernBuildingModule.class).isEmpty());
                IBuilding tavern = colony.getBuildingManager().getBuilding(tavernPos);
                visitorData.setHomeBuilding(tavern);
                visitorData.setBedPos(tavernPos);
                tavern.getModules(TavernBuildingModule.class).forEach(mod -> mod.getExternalCitizens().add(visitorData.getId()));
                int recruitLevel = world.random.nextInt(10 * tavern.getBuildingLevel()) + 15;
                List<com.minecolonies.api.util.Tuple<Item, Integer>> recruitCosts = IColonyManager.getInstance().getCompatibilityManager().getRecruitmentCostsWeights();
                visitorData.getCitizenSkillHandler().init(recruitLevel);
                colony.getVisitorManager().spawnOrCreateCivilian(visitorData, world, entity.blockPosition(), false);
                colony.getEventDescriptionManager().addEventDescription(new VisitorSpawnedEvent(entity.blockPosition(), visitorData.getName()));
                if (visitorData.getEntity().isPresent()) {
                    AbstractEntityCitizen visitorEntity = visitorData.getEntity().get();
                    for (EquipmentSlotType slotType : EquipmentSlotType.values()) {
                        ItemStack itemstack = entity.getItemBySlot(slotType);
                        if (slotType.getType() == EquipmentSlotType.Group.ARMOR && !itemstack.isEmpty()) {
                            visitorEntity.setItemSlot(slotType, itemstack);
                        }
                    }
                }
                if (!entity.isSilent()) {
                    world.levelEvent((PlayerEntity) null, 1027, entity.blockPosition(), 0);
                }
                entity.remove();
                Tuple<Item, Integer> cost = recruitCosts.get(world.random.nextInt(recruitCosts.size()));
                visitorData.setRecruitCosts(new ItemStack(cost.getA(), (int) (recruitLevel * 3.0 / cost.getB())));
                visitorData.triggerInteraction(new RecruitmentInteraction(new TranslationTextComponent("com.minecolonies.coremod.gui.chat.recruitstorycured", visitorData.getName().split(" ")[0]), ChatPriority.IMPORTANT));
            }
        }
    }
}
Also used : VisitorSpawnedEvent(com.minecolonies.coremod.colony.colonyEvents.citizenEvents.VisitorSpawnedEvent) IBuilding(com.minecolonies.api.colony.buildings.IBuilding) EquipmentSlotType(net.minecraft.inventory.EquipmentSlotType) AbstractEntityCitizen(com.minecolonies.api.entity.citizen.AbstractEntityCitizen) World(net.minecraft.world.World) ClientWorld(net.minecraft.client.world.ClientWorld) ServerWorld(net.minecraft.world.server.ServerWorld) EntryPoint(com.minecolonies.coremod.commands.EntryPoint) LivingEntity(net.minecraft.entity.LivingEntity) Item(net.minecraft.item.Item) BlockItem(net.minecraft.item.BlockItem) RecruitmentInteraction(com.minecolonies.coremod.colony.interactionhandling.RecruitmentInteraction) ZombieVillagerEntity(net.minecraft.entity.monster.ZombieVillagerEntity) TranslationTextComponent(net.minecraft.util.text.TranslationTextComponent) BlockPos(net.minecraft.util.math.BlockPos) ItemStack(net.minecraft.item.ItemStack) TavernBuildingModule(com.minecolonies.coremod.colony.buildings.modules.TavernBuildingModule) Tuple(com.minecolonies.api.util.Tuple) SubscribeEvent(net.minecraftforge.eventbus.api.SubscribeEvent)

Example 8 with Tuple

use of com.minecolonies.api.util.Tuple in project minecolonies by ldtteam.

the class CitizenDataView method deserialize.

@Override
public void deserialize(@NotNull final PacketBuffer buf) {
    name = buf.readUtf(32767);
    female = buf.readBoolean();
    entityId = buf.readInt();
    paused = buf.readBoolean();
    isChild = buf.readBoolean();
    homeBuilding = buf.readBoolean() ? buf.readBlockPos() : null;
    workBuilding = buf.readBoolean() ? buf.readBlockPos() : null;
    // Attributes
    health = buf.readFloat();
    maxHealth = buf.readFloat();
    saturation = buf.readDouble();
    happiness = buf.readDouble();
    citizenSkillHandler.read(buf.readNbt());
    job = buf.readUtf(32767);
    colonyId = buf.readInt();
    final CompoundNBT compound = buf.readNbt();
    inventory = new InventoryCitizen(this.name, true);
    final ListNBT ListNBT = compound.getList("inventory", 10);
    this.inventory.read(ListNBT);
    this.inventory.setHeldItem(Hand.MAIN_HAND, compound.getInt(TAG_HELD_ITEM_SLOT));
    this.inventory.setHeldItem(Hand.OFF_HAND, compound.getInt(TAG_OFFHAND_HELD_ITEM_SLOT));
    position = buf.readBlockPos();
    citizenChatOptions.clear();
    final int size = buf.readInt();
    for (int i = 0; i < size; i++) {
        final CompoundNBT compoundNBT = buf.readNbt();
        final ServerCitizenInteraction handler = (ServerCitizenInteraction) MinecoloniesAPIProxy.getInstance().getInteractionResponseHandlerDataManager().createFrom(this, compoundNBT);
        citizenChatOptions.put(handler.getInquiry(), handler);
    }
    sortedInteractions = citizenChatOptions.values().stream().sorted(Comparator.comparingInt(e -> e.getPriority().getPriority())).collect(Collectors.toList());
    citizenHappinessHandler.read(buf.readNbt());
    int statusindex = buf.readInt();
    statusIcon = statusindex >= 0 ? VisibleCitizenStatus.getForId(statusindex) : null;
    if (buf.readBoolean()) {
        final IColonyView colonyView = IColonyManager.getInstance().getColonyView(colonyId, Minecraft.getInstance().level.dimension());
        jobView = IJobDataManager.getInstance().createViewFrom(colonyView, this, buf);
    } else {
        jobView = null;
    }
    children.clear();
    siblings.clear();
    partner = buf.readInt();
    final int siblingsSize = buf.readInt();
    for (int i = 0; i < siblingsSize; i++) {
        siblings.add(buf.readInt());
    }
    final int childrenSize = buf.readInt();
    for (int i = 0; i < childrenSize; i++) {
        children.add(buf.readInt());
    }
    final String parentA = buf.readUtf();
    final String parentB = buf.readUtf();
    parents = new Tuple<>(parentA, parentB);
}
Also used : java.util(java.util) Suppression(com.minecolonies.api.util.constant.Suppression) CompoundNBT(net.minecraft.nbt.CompoundNBT) ITextComponent(net.minecraft.util.text.ITextComponent) MinecoloniesAPIProxy(com.minecolonies.api.MinecoloniesAPIProxy) ICitizenSkillHandler(com.minecolonies.api.entity.citizen.citizenhandlers.ICitizenSkillHandler) Tuple(com.minecolonies.api.util.Tuple) TAG_OFFHAND_HELD_ITEM_SLOT(com.minecolonies.api.util.constant.NbtTagConstants.TAG_OFFHAND_HELD_ITEM_SLOT) Minecraft(net.minecraft.client.Minecraft) IJobDataManager(com.minecolonies.api.colony.jobs.registry.IJobDataManager) IInteractionResponseHandler(com.minecolonies.api.colony.interactionhandling.IInteractionResponseHandler) Hand(net.minecraft.util.Hand) CitizenSkillHandler(com.minecolonies.coremod.entity.citizen.citizenhandlers.CitizenSkillHandler) Constants(com.minecolonies.api.util.constant.Constants) ListNBT(net.minecraft.nbt.ListNBT) IColonyView(com.minecolonies.api.colony.IColonyView) ICitizenHappinessHandler(com.minecolonies.api.entity.citizen.citizenhandlers.ICitizenHappinessHandler) IColonyManager(com.minecolonies.api.colony.IColonyManager) VisibleCitizenStatus(com.minecolonies.api.entity.citizen.VisibleCitizenStatus) ICitizenDataView(com.minecolonies.api.colony.ICitizenDataView) ChatPriority(com.minecolonies.api.colony.interactionhandling.ChatPriority) BlockPos(net.minecraft.util.math.BlockPos) Collectors(java.util.stream.Collectors) Nullable(org.jetbrains.annotations.Nullable) InventoryCitizen(com.minecolonies.api.inventory.InventoryCitizen) IJobView(com.minecolonies.api.colony.jobs.IJobView) ResourceLocation(net.minecraft.util.ResourceLocation) ServerCitizenInteraction(com.minecolonies.coremod.colony.interactionhandling.ServerCitizenInteraction) NotNull(org.jetbrains.annotations.NotNull) CitizenHappinessHandler(com.minecolonies.coremod.entity.citizen.citizenhandlers.CitizenHappinessHandler) PacketBuffer(net.minecraft.network.PacketBuffer) ListNBT(net.minecraft.nbt.ListNBT) CompoundNBT(net.minecraft.nbt.CompoundNBT) ServerCitizenInteraction(com.minecolonies.coremod.colony.interactionhandling.ServerCitizenInteraction) InventoryCitizen(com.minecolonies.api.inventory.InventoryCitizen) IColonyView(com.minecolonies.api.colony.IColonyView)

Example 9 with Tuple

use of com.minecolonies.api.util.Tuple in project minecolonies by ldtteam.

the class WindowInfoPage method createAndSetStatistics.

/**
 * Creates several statistics and sets them in the building GUI.
 */
private void createAndSetStatistics() {
    final DecimalFormat df = new DecimalFormat("#.#");
    df.setRoundingMode(RoundingMode.CEILING);
    final String roundedHappiness = df.format(building.getColony().getOverallHappiness());
    findPaneOfTypeByID(HAPPINESS_LABEL, Text.class).setText(roundedHappiness);
    final int citizensSize = building.getColony().getCitizens().size();
    final int citizensCap;
    if (MinecoloniesAPIProxy.getInstance().getGlobalResearchTree().hasResearchEffect(CITIZEN_CAP)) {
        citizensCap = (int) (Math.min(MineColonies.getConfig().getServer().maxCitizenPerColony.get(), 25 + this.building.getColony().getResearchManager().getResearchEffects().getEffectStrength(CITIZEN_CAP)));
    } else {
        citizensCap = MineColonies.getConfig().getServer().maxCitizenPerColony.get();
    }
    final Text totalCitizenLabel = findPaneOfTypeByID(TOTAL_CITIZENS_LABEL, Text.class);
    totalCitizenLabel.setText(LanguageHandler.format(COM_MINECOLONIES_COREMOD_GUI_TOWNHALL_POPULATION_TOTALCITIZENS_COUNT, citizensSize, Math.max(citizensSize, building.getColony().getCitizenCountLimit())));
    List<IFormattableTextComponent> hoverText = new ArrayList<>();
    if (citizensSize < (citizensCap * 0.9) && citizensSize < (building.getColony().getCitizenCountLimit() * 0.9)) {
        totalCitizenLabel.setColors(DARKGREEN);
    } else if (citizensSize < citizensCap) {
        hoverText.add(new TranslationTextComponent("com.minecolonies.coremod.gui.townhall.population.totalcitizens.houselimited", this.building.getColony().getName()));
        totalCitizenLabel.setColors(ORANGE);
    } else {
        if (citizensCap < MineColonies.getConfig().getServer().maxCitizenPerColony.get()) {
            hoverText.add(new TranslationTextComponent("com.minecolonies.coremod.gui.townhall.population.totalcitizens.researchlimited", this.building.getColony().getName()));
        } else {
            hoverText.add(new TranslationTextComponent("com.minecolonies.coremod.gui.townhall.population.totalcitizens.configlimited", this.building.getColony().getName()));
        }
        totalCitizenLabel.setText(LanguageHandler.format(COM_MINECOLONIES_COREMOD_GUI_TOWNHALL_POPULATION_TOTALCITIZENS_COUNT, citizensSize, citizensCap));
        totalCitizenLabel.setColors(RED);
    }
    PaneBuilders.tooltipBuilder().hoverPane(totalCitizenLabel).build().setText(hoverText);
    int children = 0;
    final Map<String, Tuple<Integer, Integer>> jobMaxCountMap = new HashMap<>();
    for (@NotNull final IBuildingView building : building.getColony().getBuildings()) {
        if (building instanceof AbstractBuildingView) {
            for (final WorkerBuildingModuleView module : building.getModuleViews(WorkerBuildingModuleView.class)) {
                int max = module.getMaxInhabitants();
                int workers = module.getAssignedCitizens().size();
                final String jobName = module.getJobDisplayName().toLowerCase(Locale.ENGLISH);
                final Tuple<Integer, Integer> tuple = jobMaxCountMap.getOrDefault(jobName, new Tuple<>(0, 0));
                jobMaxCountMap.put(jobName, new Tuple<>(tuple.getA() + workers, tuple.getB() + max));
            }
        }
    }
    // calculate number of children
    int unemployedCount = 0;
    for (ICitizenDataView iCitizenDataView : building.getColony().getCitizens().values()) {
        if (iCitizenDataView.isChild()) {
            children++;
        } else if (iCitizenDataView.getJobView() == null) {
            unemployedCount++;
        }
    }
    final String numberOfUnemployed = LanguageHandler.format(COM_MINECOLONIES_COREMOD_GUI_TOWNHALL_POPULATION_UNEMPLOYED, unemployedCount);
    final String numberOfKids = LanguageHandler.format(COM_MINECOLONIES_COREMOD_GUI_TOWNHALL_POPULATION_CHILDS, children);
    final ScrollingList list = findPaneOfTypeByID("citizen-stats", ScrollingList.class);
    if (list == null) {
        return;
    }
    final int maxJobs = jobMaxCountMap.size();
    final List<Map.Entry<String, Tuple<Integer, Integer>>> theList = new ArrayList<>(jobMaxCountMap.entrySet());
    list.setDataProvider(new ScrollingList.DataProvider() {

        @Override
        public int getElementCount() {
            return maxJobs + 2;
        }

        @Override
        public void updateElement(final int index, @NotNull final Pane rowPane) {
            final Text label = rowPane.findPaneOfTypeByID(CITIZENS_AMOUNT_LABEL, Text.class);
            if (index < theList.size()) {
                final Map.Entry<String, Tuple<Integer, Integer>> entry = theList.get(index);
                final String job = LanguageHandler.format(entry.getKey());
                final String numberOfWorkers = LanguageHandler.format(COM_MINECOLONIES_COREMOD_GUI_TOWNHALL_POPULATION_EACH, job, entry.getValue().getA(), entry.getValue().getB());
                label.setText(numberOfWorkers);
            } else {
                if (index == maxJobs + 1) {
                    label.setText(numberOfUnemployed);
                } else {
                    label.setText(numberOfKids);
                }
            }
        }
    });
}
Also used : DecimalFormat(java.text.DecimalFormat) WorkerBuildingModuleView(com.minecolonies.coremod.colony.buildings.moduleviews.WorkerBuildingModuleView) NotNull(org.jetbrains.annotations.NotNull) AbstractBuildingView(com.minecolonies.coremod.colony.buildings.views.AbstractBuildingView) TranslationTextComponent(net.minecraft.util.text.TranslationTextComponent) IFormattableTextComponent(net.minecraft.util.text.IFormattableTextComponent) Pane(com.ldtteam.blockout.Pane) IBuildingView(com.minecolonies.api.colony.buildings.views.IBuildingView) ICitizenDataView(com.minecolonies.api.colony.ICitizenDataView) ScrollingList(com.ldtteam.blockout.views.ScrollingList) Tuple(com.minecolonies.api.util.Tuple)

Example 10 with Tuple

use of com.minecolonies.api.util.Tuple in project minecolonies by Minecolonies.

the class WindowInfoPage method createAndSetStatistics.

/**
 * Creates several statistics and sets them in the building GUI.
 */
private void createAndSetStatistics() {
    final DecimalFormat df = new DecimalFormat("#.#");
    df.setRoundingMode(RoundingMode.CEILING);
    final String roundedHappiness = df.format(building.getColony().getOverallHappiness());
    findPaneOfTypeByID(HAPPINESS_LABEL, Text.class).setText(roundedHappiness);
    final int citizensSize = building.getColony().getCitizens().size();
    final int citizensCap;
    if (MinecoloniesAPIProxy.getInstance().getGlobalResearchTree().hasResearchEffect(CITIZEN_CAP)) {
        citizensCap = (int) (Math.min(MineColonies.getConfig().getServer().maxCitizenPerColony.get(), 25 + this.building.getColony().getResearchManager().getResearchEffects().getEffectStrength(CITIZEN_CAP)));
    } else {
        citizensCap = MineColonies.getConfig().getServer().maxCitizenPerColony.get();
    }
    final Text totalCitizenLabel = findPaneOfTypeByID(TOTAL_CITIZENS_LABEL, Text.class);
    totalCitizenLabel.setText(new TranslationTextComponent(COM_MINECOLONIES_COREMOD_GUI_TOWNHALL_POPULATION_TOTALCITIZENS_COUNT, citizensSize, Math.max(citizensSize, building.getColony().getCitizenCountLimit())));
    List<IFormattableTextComponent> hoverText = new ArrayList<>();
    if (citizensSize < (citizensCap * 0.9) && citizensSize < (building.getColony().getCitizenCountLimit() * 0.9)) {
        totalCitizenLabel.setColors(DARKGREEN);
    } else if (citizensSize < citizensCap) {
        hoverText.add(new TranslationTextComponent(WARNING_POPULATION_NEEDS_HOUSING, this.building.getColony().getName()));
        totalCitizenLabel.setColors(ORANGE);
    } else {
        if (citizensCap < MineColonies.getConfig().getServer().maxCitizenPerColony.get()) {
            hoverText.add(new TranslationTextComponent(WARNING_POPULATION_RESEARCH_LIMITED, this.building.getColony().getName()));
        } else {
            hoverText.add(new TranslationTextComponent(WARNING_POPULATION_CONFIG_LIMITED, this.building.getColony().getName()));
        }
        totalCitizenLabel.setText(new TranslationTextComponent(COM_MINECOLONIES_COREMOD_GUI_TOWNHALL_POPULATION_TOTALCITIZENS_COUNT, citizensSize, citizensCap));
        totalCitizenLabel.setColors(RED);
    }
    PaneBuilders.tooltipBuilder().hoverPane(totalCitizenLabel).build().setText(hoverText);
    int children = 0;
    final Map<String, Tuple<Integer, Integer>> jobMaxCountMap = new HashMap<>();
    for (@NotNull final IBuildingView building : building.getColony().getBuildings()) {
        if (building instanceof AbstractBuildingView) {
            for (final WorkerBuildingModuleView module : building.getModuleViews(WorkerBuildingModuleView.class)) {
                int max = module.getMaxInhabitants();
                int workers = module.getAssignedCitizens().size();
                final String jobName = module.getJobDisplayName().toLowerCase(Locale.ENGLISH);
                final Tuple<Integer, Integer> tuple = jobMaxCountMap.getOrDefault(jobName, new Tuple<>(0, 0));
                jobMaxCountMap.put(jobName, new Tuple<>(tuple.getA() + workers, tuple.getB() + max));
            }
        }
    }
    // calculate number of children
    int unemployedCount = 0;
    for (ICitizenDataView iCitizenDataView : building.getColony().getCitizens().values()) {
        if (iCitizenDataView.isChild()) {
            children++;
        } else if (iCitizenDataView.getJobView() == null) {
            unemployedCount++;
        }
    }
    final ITextComponent numberOfUnemployed = new TranslationTextComponent(COM_MINECOLONIES_COREMOD_GUI_TOWNHALL_POPULATION_UNEMPLOYED, unemployedCount);
    final ITextComponent numberOfKids = new TranslationTextComponent(COM_MINECOLONIES_COREMOD_GUI_TOWNHALL_POPULATION_CHILDS, children);
    final ScrollingList list = findPaneOfTypeByID("citizen-stats", ScrollingList.class);
    if (list == null) {
        return;
    }
    final int maxJobs = jobMaxCountMap.size();
    final List<Map.Entry<String, Tuple<Integer, Integer>>> theList = new ArrayList<>(jobMaxCountMap.entrySet());
    theList.sort(Map.Entry.comparingByKey());
    list.setDataProvider(new ScrollingList.DataProvider() {

        @Override
        public int getElementCount() {
            return maxJobs + 2;
        }

        @Override
        public void updateElement(final int index, @NotNull final Pane rowPane) {
            final Text label = rowPane.findPaneOfTypeByID(CITIZENS_AMOUNT_LABEL, Text.class);
            if (index < theList.size()) {
                final Map.Entry<String, Tuple<Integer, Integer>> entry = theList.get(index);
                final ITextComponent job = new TranslationTextComponent(entry.getKey());
                final ITextComponent numberOfWorkers = new TranslationTextComponent(COM_MINECOLONIES_COREMOD_GUI_TOWNHALL_POPULATION_EACH, job, entry.getValue().getA(), entry.getValue().getB());
                label.setText(numberOfWorkers);
            } else {
                if (index == maxJobs + 1) {
                    label.setText(numberOfUnemployed);
                } else {
                    label.setText(numberOfKids);
                }
            }
        }
    });
}
Also used : DecimalFormat(java.text.DecimalFormat) ITextComponent(net.minecraft.util.text.ITextComponent) WorkerBuildingModuleView(com.minecolonies.coremod.colony.buildings.moduleviews.WorkerBuildingModuleView) NotNull(org.jetbrains.annotations.NotNull) AbstractBuildingView(com.minecolonies.coremod.colony.buildings.views.AbstractBuildingView) TranslationTextComponent(net.minecraft.util.text.TranslationTextComponent) IFormattableTextComponent(net.minecraft.util.text.IFormattableTextComponent) Text(com.ldtteam.blockout.controls.Text) Pane(com.ldtteam.blockout.Pane) IBuildingView(com.minecolonies.api.colony.buildings.views.IBuildingView) ICitizenDataView(com.minecolonies.api.colony.ICitizenDataView) ScrollingList(com.ldtteam.blockout.views.ScrollingList) Tuple(com.minecolonies.api.util.Tuple)

Aggregations

Tuple (com.minecolonies.api.util.Tuple)34 BlockPos (net.minecraft.util.math.BlockPos)22 ItemStack (net.minecraft.item.ItemStack)20 TranslationTextComponent (net.minecraft.util.text.TranslationTextComponent)20 NotNull (org.jetbrains.annotations.NotNull)18 IAIState (com.minecolonies.api.entity.ai.statemachine.states.IAIState)14 AIWorkerState (com.minecolonies.api.entity.ai.statemachine.states.AIWorkerState)12 InventoryUtils (com.minecolonies.api.util.InventoryUtils)12 ItemStackUtils (com.minecolonies.api.util.ItemStackUtils)12 ItemStorage (com.minecolonies.api.crafting.ItemStorage)10 AITarget (com.minecolonies.api.entity.ai.statemachine.AITarget)10 ArrayList (java.util.ArrayList)10 List (java.util.List)10 Predicate (java.util.function.Predicate)10 Hand (net.minecraft.util.Hand)10 TypeToken (com.google.common.reflect.TypeToken)8 ICitizenDataView (com.minecolonies.api.colony.ICitizenDataView)8 ChatPriority (com.minecolonies.api.colony.interactionhandling.ChatPriority)8 RequestState (com.minecolonies.api.colony.requestsystem.request.RequestState)8 StackList (com.minecolonies.api.colony.requestsystem.requestable.StackList)8