Search in sources :

Example 1 with Tuple

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

the class ResearchListener method parseRemoveResearches.

/**
 * Parses out a researches map for elements containing Remove properties, and applies those removals to the researchMap
 *
 * @param object        A Map containing the resource location of each json file, and the element within that json file.
 * @return              A Tuple containing resource locations of Researches (A) and Branches (B) to remove from the global research tree.
 */
private Tuple<Collection<ResourceLocation>, Collection<ResourceLocation>> parseRemoveResearches(final Map<ResourceLocation, JsonElement> object) {
    Collection<ResourceLocation> removeResearches = new HashSet<>();
    Collection<ResourceLocation> removeBranches = new HashSet<>();
    for (final Map.Entry<ResourceLocation, JsonElement> entry : object.entrySet()) {
        final JsonObject researchJson = entry.getValue().getAsJsonObject();
        if (researchJson.has(RESEARCH_REMOVE_PROP)) {
            // Removing an entire branch, and all research on that branch.
            if (researchJson.has(RESEARCH_BRANCH_NAME_PROP) || researchJson.has(RESEARCH_BASE_TIME_PROP)) {
                // Accept arrays, if the data pack makers wants to remove multiple branches.
                if (researchJson.get(RESEARCH_REMOVE_PROP).isJsonArray()) {
                    for (final JsonElement remove : researchJson.get(RESEARCH_REMOVE_PROP).getAsJsonArray()) {
                        if (remove.isJsonPrimitive() && remove.getAsJsonPrimitive().isString()) {
                            removeBranches.add(new ResourceLocation(remove.getAsString()));
                        }
                    }
                } else // The json for such a removal can have an arbitrary filename, and the remove property points to the specific json to remove.
                if (researchJson.get(RESEARCH_REMOVE_PROP).isJsonPrimitive() && researchJson.get(RESEARCH_REMOVE_PROP).getAsJsonPrimitive().isString()) {
                    removeBranches.add(new ResourceLocation(researchJson.get(RESEARCH_REMOVE_PROP).getAsJsonPrimitive().getAsString()));
                } else // Lastly, accept just boolean true, for the simple case of removing this particular branch and all component researches.
                if (researchJson.get(RESEARCH_REMOVE_PROP).isJsonPrimitive() && researchJson.get(RESEARCH_REMOVE_PROP).getAsJsonPrimitive().isBoolean() && researchJson.get(RESEARCH_REMOVE_PROP).getAsBoolean()) {
                    removeBranches.add(entry.getKey());
                }
            } else // The json for such a removal can have an arbitrary filename, and the remove property points to the specific json to remove.
            if (researchJson.get(RESEARCH_REMOVE_PROP).isJsonArray()) {
                for (final JsonElement remove : researchJson.get(RESEARCH_REMOVE_PROP).getAsJsonArray()) {
                    if (remove.isJsonPrimitive() && remove.getAsJsonPrimitive().isString()) {
                        removeResearches.add(new ResourceLocation(remove.getAsString()));
                    }
                }
            } else // Removing individual researches by name.
            if (researchJson.get(RESEARCH_REMOVE_PROP).isJsonPrimitive() && researchJson.get(RESEARCH_REMOVE_PROP).getAsJsonPrimitive().isString()) {
                removeResearches.add(new ResourceLocation(researchJson.get(RESEARCH_REMOVE_PROP).getAsString()));
            } else // Removes with a boolean true, but are not branch removes.
            if (researchJson.get(RESEARCH_REMOVE_PROP).isJsonPrimitive() && researchJson.get(RESEARCH_REMOVE_PROP).getAsJsonPrimitive().isBoolean() && researchJson.get(RESEARCH_REMOVE_PROP).getAsBoolean()) {
                removeResearches.add(entry.getKey());
            } else // Files which declare remove, but are malformed should be reported to help diagnose the error.
            {
                Log.getLogger().error(entry.getKey() + " is a research remove, but does not contain all required fields.  Research Removes must have remove:boolean and id:string.");
            }
        }
    }
    return new Tuple<>(removeResearches, removeBranches);
}
Also used : ResourceLocation(net.minecraft.util.ResourceLocation) HashMap(java.util.HashMap) Map(java.util.Map) Tuple(com.minecolonies.api.util.Tuple) HashSet(java.util.HashSet)

Example 2 with Tuple

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

the class TavernBuildingModule method spawnVisitor.

/**
 * Spawns a recruitable visitor citizen.
 */
private void spawnVisitor() {
    IVisitorData newCitizen = (IVisitorData) building.getColony().getVisitorManager().createAndRegisterCivilianData();
    externalCitizens.add(newCitizen.getId());
    newCitizen.setBedPos(building.getPosition());
    newCitizen.setHomeBuilding(building);
    int recruitLevel = building.getColony().getWorld().random.nextInt(10 * building.getBuildingLevel()) + 15;
    List<com.minecolonies.api.util.Tuple<Item, Integer>> recruitCosts = IColonyManager.getInstance().getCompatibilityManager().getRecruitmentCostsWeights();
    if (newCitizen.getName().contains("Ray")) {
        newCitizen.setRecruitCosts(new ItemStack(Items.BAKED_POTATO, 64));
    }
    newCitizen.getCitizenSkillHandler().init(recruitLevel);
    BlockPos spawnPos = BlockPosUtil.findSpawnPosAround(building.getColony().getWorld(), building.getPosition());
    if (spawnPos == null) {
        spawnPos = building.getPosition();
    }
    Tuple<Item, Integer> cost = recruitCosts.get(building.getColony().getWorld().random.nextInt(recruitCosts.size()));
    ItemStack boots = ItemStack.EMPTY;
    if (recruitLevel > LEATHER_SKILL_LEVEL) {
        // Leather
        boots = new ItemStack(Items.LEATHER_BOOTS);
    }
    if (recruitLevel > GOLD_SKILL_LEVEL) {
        // Gold
        boots = new ItemStack(Items.GOLDEN_BOOTS);
    }
    if (recruitLevel > IRON_SKILL_LEVEL) {
        if (cost.getB() <= 2) {
            cost = recruitCosts.get(building.getColony().getWorld().random.nextInt(recruitCosts.size()));
        }
        // Iron
        boots = new ItemStack(Items.IRON_BOOTS);
    }
    if (recruitLevel > DIAMOND_SKILL_LEVEL) {
        if (cost.getB() <= 3) {
            cost = recruitCosts.get(building.getColony().getWorld().random.nextInt(recruitCosts.size()));
        }
        // Diamond
        boots = new ItemStack(Items.DIAMOND_BOOTS);
    }
    newCitizen.setRecruitCosts(new ItemStack(cost.getA(), (int) (recruitLevel * 3.0 / cost.getB())));
    if (!CustomVisitorListener.chanceCustomVisitors(newCitizen)) {
        newCitizen.triggerInteraction(new RecruitmentInteraction(new TranslationTextComponent("com.minecolonies.coremod.gui.chat.recruitstory" + (building.getColony().getWorld().random.nextInt(MAX_STORY) + 1), newCitizen.getName().split(" ")[0]), ChatPriority.IMPORTANT));
    }
    building.getColony().getVisitorManager().spawnOrCreateCivilian(newCitizen, building.getColony().getWorld(), spawnPos, true);
    if (newCitizen.getEntity().isPresent()) {
        newCitizen.getEntity().get().setItemSlot(EquipmentSlotType.FEET, boots);
    }
    building.getColony().getEventDescriptionManager().addEventDescription(new VisitorSpawnedEvent(spawnPos, newCitizen.getName()));
}
Also used : VisitorSpawnedEvent(com.minecolonies.coremod.colony.colonyEvents.citizenEvents.VisitorSpawnedEvent) Item(net.minecraft.item.Item) RecruitmentInteraction(com.minecolonies.coremod.colony.interactionhandling.RecruitmentInteraction) TranslationTextComponent(net.minecraft.util.text.TranslationTextComponent) BlockPos(net.minecraft.util.math.BlockPos) ItemStack(net.minecraft.item.ItemStack) Tuple(com.minecolonies.api.util.Tuple)

Example 3 with Tuple

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

the class AbstractWarehouseRequestResolver method getFollowupRequestForCompletion.

@Nullable
@Override
public List<IRequest<?>> getFollowupRequestForCompletion(@NotNull final IRequestManager manager, @NotNull final IRequest<? extends IDeliverable> completedRequest) {
    if (manager.getColony().getWorld().isClientSide) {
        return null;
    }
    final Colony colony = (Colony) manager.getColony();
    final List<TileEntityWareHouse> wareHouses = getWareHousesInColony(colony, completedRequest.getRequester().getLocation().getInDimensionLocation());
    List<IRequest<?>> deliveries = Lists.newArrayList();
    int remainingCount = completedRequest.getRequest().getCount();
    final Map<ItemStorage, Integer> storages = new HashMap<>();
    final int keep = completedRequest.getRequest() instanceof INonExhaustiveDeliverable ? ((INonExhaustiveDeliverable) completedRequest.getRequest()).getLeftOver() : 0;
    tileentities: for (final TileEntityWareHouse wareHouse : wareHouses) {
        final List<Tuple<ItemStack, BlockPos>> targetStacks = wareHouse.getMatchingItemStacksInWarehouse(itemStack -> completedRequest.getRequest().matches(itemStack));
        for (final Tuple<ItemStack, BlockPos> tuple : targetStacks) {
            if (ItemStackUtils.isEmpty(tuple.getA())) {
                continue;
            }
            int leftOver = tuple.getA().getCount();
            if (keep > 0) {
                int kept = storages.getOrDefault(new ItemStorage(tuple.getA()), 0);
                if (kept < keep) {
                    if (leftOver + kept <= keep) {
                        storages.put(new ItemStorage(tuple.getA()), storages.getOrDefault(new ItemStorage(tuple.getA()), 0) + tuple.getA().getCount());
                        continue;
                    }
                    int toKeep = (leftOver + kept) - keep;
                    leftOver -= toKeep;
                    storages.put(new ItemStorage(tuple.getA()), storages.getOrDefault(new ItemStorage(tuple.getA()), 0) + toKeep);
                }
            }
            int count = Math.min(remainingCount, leftOver);
            final ItemStack matchingStack = tuple.getA().copy();
            matchingStack.setCount(count);
            completedRequest.addDelivery(matchingStack);
            final ILocation itemStackLocation = manager.getFactoryController().getNewInstance(TypeConstants.ILOCATION, tuple.getB(), wareHouse.getLevel().dimension());
            final Delivery delivery = new Delivery(itemStackLocation, completedRequest.getRequester().getLocation(), matchingStack, getDefaultDeliveryPriority(true));
            final IToken<?> requestToken = manager.createRequest(manager.getFactoryController().getNewInstance(TypeToken.of(this.getClass()), completedRequest.getRequester().getLocation(), completedRequest.getId()), delivery);
            deliveries.add(manager.getRequestForToken(requestToken));
            remainingCount -= count;
            if (remainingCount <= 0) {
                break tileentities;
            }
        }
    }
    return deliveries.isEmpty() ? null : deliveries;
}
Also used : IRequest(com.minecolonies.api.colony.requestsystem.request.IRequest) java.util(java.util) ItemStackUtils(com.minecolonies.api.util.ItemStackUtils) AbstractDeliverymanRequestable.getDefaultDeliveryPriority(com.minecolonies.api.colony.requestsystem.requestable.deliveryman.AbstractDeliverymanRequestable.getDefaultDeliveryPriority) IToken(com.minecolonies.api.colony.requestsystem.token.IToken) IFormattableTextComponent(net.minecraft.util.text.IFormattableTextComponent) TypeToken(com.google.common.reflect.TypeToken) BuildingWareHouse(com.minecolonies.coremod.colony.buildings.workerbuildings.BuildingWareHouse) IRequestManager(com.minecolonies.api.colony.requestsystem.manager.IRequestManager) TranslationTextComponent(net.minecraft.util.text.TranslationTextComponent) ItemStack(net.minecraft.item.ItemStack) CONST_WAREHOUSE_RESOLVER_PRIORITY(com.minecolonies.api.util.constant.RSConstants.CONST_WAREHOUSE_RESOLVER_PRIORITY) Lists(com.google.common.collect.Lists) Tuple(com.minecolonies.api.util.Tuple) BuildingBasedRequester(com.minecolonies.coremod.colony.requestsystem.requesters.BuildingBasedRequester) Delivery(com.minecolonies.api.colony.requestsystem.requestable.deliveryman.Delivery) Log(com.minecolonies.api.util.Log) TileEntityWareHouse(com.minecolonies.coremod.tileentities.TileEntityWareHouse) TranslationConstants(com.minecolonies.api.util.constant.TranslationConstants) IDeliverable(com.minecolonies.api.colony.requestsystem.requestable.IDeliverable) IRequester(com.minecolonies.api.colony.requestsystem.requester.IRequester) Colony(com.minecolonies.coremod.colony.Colony) ILocation(com.minecolonies.api.colony.requestsystem.location.ILocation) RequestState(com.minecolonies.api.colony.requestsystem.request.RequestState) BlockPos(net.minecraft.util.math.BlockPos) Nullable(org.jetbrains.annotations.Nullable) TypeConstants(com.minecolonies.api.util.constant.TypeConstants) IBuilding(com.minecolonies.api.colony.buildings.IBuilding) INonExhaustiveDeliverable(com.minecolonies.api.colony.requestsystem.requestable.INonExhaustiveDeliverable) ItemStorage(com.minecolonies.api.crafting.ItemStorage) NotNull(org.jetbrains.annotations.NotNull) TileEntityWareHouse(com.minecolonies.coremod.tileentities.TileEntityWareHouse) ItemStorage(com.minecolonies.api.crafting.ItemStorage) ILocation(com.minecolonies.api.colony.requestsystem.location.ILocation) IToken(com.minecolonies.api.colony.requestsystem.token.IToken) Colony(com.minecolonies.coremod.colony.Colony) INonExhaustiveDeliverable(com.minecolonies.api.colony.requestsystem.requestable.INonExhaustiveDeliverable) BlockPos(net.minecraft.util.math.BlockPos) IRequest(com.minecolonies.api.colony.requestsystem.request.IRequest) Delivery(com.minecolonies.api.colony.requestsystem.requestable.deliveryman.Delivery) ItemStack(net.minecraft.item.ItemStack) Tuple(com.minecolonies.api.util.Tuple) Nullable(org.jetbrains.annotations.Nullable)

Example 4 with Tuple

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

the class AbstractWarehouseRequestResolver method attemptResolveRequest.

/*
     * Moving the curly braces really makes the code hard to read.
     */
@Nullable
@Override
@SuppressWarnings("squid:LeftCurlyBraceStartLineCheck")
public List<IToken<?>> attemptResolveRequest(@NotNull final IRequestManager manager, @NotNull final IRequest<? extends IDeliverable> request) {
    if (manager.getColony().getWorld().isClientSide) {
        return Lists.newArrayList();
    }
    if (!(manager.getColony() instanceof Colony)) {
        return Lists.newArrayList();
    }
    final Colony colony = (Colony) manager.getColony();
    final List<TileEntityWareHouse> wareHouses = getWareHousesInColony(colony, request.getRequester().getLocation().getInDimensionLocation());
    final int totalRequested = request.getRequest().getCount();
    int totalAvailable = 0;
    if (request.getRequest() instanceof INonExhaustiveDeliverable) {
        totalAvailable -= ((INonExhaustiveDeliverable) request.getRequest()).getLeftOver();
    }
    for (final TileEntityWareHouse tile : wareHouses) {
        final List<Tuple<ItemStack, BlockPos>> inv = tile.getMatchingItemStacksInWarehouse(itemStack -> request.getRequest().matches(itemStack));
        for (final Tuple<ItemStack, BlockPos> stack : inv) {
            if (!stack.getA().isEmpty()) {
                totalAvailable += stack.getA().getCount();
            }
        }
    }
    if (totalAvailable >= totalRequested || totalAvailable >= request.getRequest().getMinimumCount()) {
        return Lists.newArrayList();
    }
    if (totalAvailable < 0) {
        totalAvailable = 0;
    }
    final int totalRemainingRequired = totalRequested - totalAvailable;
    final IDeliverable remainingRequest = request.getRequest().copyWithCount(totalRemainingRequired);
    return Lists.newArrayList(manager.createRequest(this, remainingRequest));
}
Also used : TileEntityWareHouse(com.minecolonies.coremod.tileentities.TileEntityWareHouse) Colony(com.minecolonies.coremod.colony.Colony) INonExhaustiveDeliverable(com.minecolonies.api.colony.requestsystem.requestable.INonExhaustiveDeliverable) BlockPos(net.minecraft.util.math.BlockPos) ItemStack(net.minecraft.item.ItemStack) Tuple(com.minecolonies.api.util.Tuple) IDeliverable(com.minecolonies.api.colony.requestsystem.requestable.IDeliverable) Nullable(org.jetbrains.annotations.Nullable)

Example 5 with Tuple

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

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)

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 RequestState (com.minecolonies.api.colony.requestsystem.request.RequestState)10 ItemStorage (com.minecolonies.api.crafting.ItemStorage)10 AITarget (com.minecolonies.api.entity.ai.statemachine.AITarget)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 IRequest (com.minecolonies.api.colony.requestsystem.request.IRequest)8 StackList (com.minecolonies.api.colony.requestsystem.requestable.StackList)8