From e45566e2ac643be5a241ad507cf6c2522e84ca02 Mon Sep 17 00:00:00 2001 From: MarvionKirito Date: Mon, 5 Aug 2024 20:15:29 +0800 Subject: [PATCH] 1.21 update --- build.gradle | 20 +- gradle.properties | 8 +- gradle/wrapper/gradle-wrapper.properties | 2 +- .../java/adris/altoclef/chains/FoodChain.java | 4 +- .../altoclef/chains/MobDefenseChain.java | 113 +- .../chains/PlayerInteractionFixChain.java | 53 +- .../eventbus/events/ClientRenderEvent.java | 5 +- .../adris/altoclef/mixins/ClientUIMixin.java | 3 +- .../adris/altoclef/mixins/EntityAccessor.java | 11 - .../altoclef/tasks/CraftInInventoryTask.java | 4 +- .../altoclef/tasks/InteractWithBlockTask.java | 12 +- .../tasks/construction/DestroyBlockTask.java | 27 +- .../construction/PlaceBlockNearbyTask.java | 2 +- .../tasks/construction/PlaceBlockTask.java | 7 +- .../construction/PlaceObsidianBucketTask.java | 10 + .../ConstructNetherPortalBucketTask.java | 3 +- .../ConstructNetherPortalObsidianTask.java | 3 +- .../ConstructNetherPortalSpeedrunTask.java | 37 +- .../tasks/container/CraftInTableTask.java | 7 +- .../tasks/misc/PlaceBedAndSetSpawnTask.java | 121 +- .../movement/CustomBaritoneGoalTask.java | 18 +- .../tasks/movement/EscapeFromLavaTask.java | 4 + .../LocateStrongholdCoordinatesTask.java | 13 +- .../tasks/movement/MLGBucketTask.java | 9 +- .../movement/RunAwayFromCreepersTask.java | 7 +- .../movement/RunAwayFromEntitiesTask.java | 13 +- .../movement/RunAwayFromHostilesTask.java | 23 +- .../tasks/movement/TimeoutWanderTask.java | 14 +- .../tasks/resources/CollectBedTask.java | 20 +- .../tasks/resources/CollectBlazeRodsTask.java | 58 +- .../resources/CollectBucketLiquidTask.java | 70 +- .../tasks/resources/CollectFoodTask.java | 65 +- .../resources/GetSmithingTemplateTask.java | 18 +- .../tasks/resources/KillEndermanTask.java | 13 +- .../tasks/speedrun/BeatMinecraft2Task.java | 4 +- .../tasks/speedrun/DragonBreathTracker.java | 7 +- .../tasks/speedrun/KillEnderDragonTask.java | 166 ++- .../speedrun/KillEnderDragonWithBedsTask.java | 150 +-- .../speedrun/MarvionBeatMinecraftTask.java | 1180 ++++++++--------- .../speedrun/WaitForDragonAndPearlTask.java | 10 - .../tasks/stupid/ReplaceBlocksTask.java | 16 +- .../altoclef/tasks/stupid/TerminatorTask.java | 17 +- .../altoclef/trackers/EntityTracker.java | 2 +- .../baritone/GoalRunAwayFromEntities.java | 64 +- .../altoclef/util/helpers/EntityHelper.java | 49 +- .../altoclef/util/helpers/ItemHelper.java | 31 +- .../altoclef/util/helpers/LookHelper.java | 2 +- .../altoclef/util/helpers/StorageHelper.java | 2 +- .../altoclef/util/helpers/WorldHelper.java | 23 +- .../util/serialization/ItemDeserializer.java | 2 +- src/main/resources/altoclef.mixins.json | 1 - src/main/resources/fabric.mod.json | 2 +- 52 files changed, 1247 insertions(+), 1278 deletions(-) delete mode 100644 src/main/java/adris/altoclef/mixins/EntityAccessor.java diff --git a/build.gradle b/build.gradle index e942cbb67..f48564d07 100644 --- a/build.gradle +++ b/build.gradle @@ -36,27 +36,27 @@ dependencies { modImplementation("net.fabricmc.fabric-api:fabric-api:${project.fabric_version}") // Jackson JSON - implementation 'com.fasterxml.jackson.core:jackson-core:2.17.1' - implementation 'com.fasterxml.jackson.core:jackson-annotations:2.17.1' - implementation 'com.fasterxml.jackson.core:jackson-databind:2.17.1' + implementation 'com.fasterxml.jackson.core:jackson-core:2.17.2' + implementation 'com.fasterxml.jackson.core:jackson-annotations:2.17.2' + implementation 'com.fasterxml.jackson.core:jackson-databind:2.17.2' // Nether pathfinder implementation 'dev.babbaj:nether-pathfinder:1.5' // PSA: Some older mods, compiled on Loom 0.2.1, might have outdated Maven POMs. // You may need to force-disable transitiveness on them. - shadow('com.fasterxml.jackson.core:jackson-core:2.17.1') - shadow('com.fasterxml.jackson.core:jackson-annotations:2.17.1') - shadow('com.fasterxml.jackson.core:jackson-databind:2.17.1') + shadow('com.fasterxml.jackson.core:jackson-core:2.17.2') + shadow('com.fasterxml.jackson.core:jackson-annotations:2.17.2') + shadow('com.fasterxml.jackson.core:jackson-databind:2.17.2') // Thank you georgeagostino for fixing my garbage if (getProject().hasProperty("altoclef.development")) { // Must run build from baritone-plus once - modImplementation 'baritone-api-fabric:baritone-unoptimized-fabric-1.20.6-beta1' - include "baritone-api-fabric:baritone-unoptimized-fabric-1.20.6-beta1" + modImplementation 'baritone-api-fabric:baritone-unoptimized-fabric-1.21-beta1' + include "baritone-api-fabric:baritone-unoptimized-fabric-1.21-beta1" } else { - modImplementation "cabaletta:baritone-unoptimized-fabric:1.20.6-beta1" - include "cabaletta:baritone-unoptimized-fabric:1.20.6-beta1" + modImplementation "cabaletta:baritone-unoptimized-fabric:1.21-beta1" + include "cabaletta:baritone-unoptimized-fabric:1.21-beta1" } //modImplementation 'baritone-api-fabric:baritone-api-fabric:1.6.3' //implementation files('baritone-plus/build/libs/baritone-unoptimized-fabric-1.6.3.jar') diff --git a/gradle.properties b/gradle.properties index 3753a1076..2e913968d 100644 --- a/gradle.properties +++ b/gradle.properties @@ -8,13 +8,13 @@ org.gradle.caching=true org.gradle.warning.mode=all # Fabric Properties # check these on https://modmuss50.me/fabric.html -minecraft_version=1.20.6 -yarn_mappings=1.20.6+build.3 +minecraft_version=1.21 +yarn_mappings=1.21+build.9 loader_version=0.15.11 # Mod Properties -mod_version=1.20.6-beta1 +mod_version=1.21-beta1 maven_group=gaucho-matrero.altoclef archives_base_name=altoclef # Dependencies # check this on https://modmuss50.me/fabric.html -fabric_version=0.100.2+1.20.6 +fabric_version=0.100.7+1.21 diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 0d1842103..19cfad969 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,5 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.8-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.9-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/src/main/java/adris/altoclef/chains/FoodChain.java b/src/main/java/adris/altoclef/chains/FoodChain.java index 11fbc7ffe..2915829af 100644 --- a/src/main/java/adris/altoclef/chains/FoodChain.java +++ b/src/main/java/adris/altoclef/chains/FoodChain.java @@ -135,9 +135,7 @@ public float getPriority(AltoClef mod) { !mod.getMLGBucketChain().isChorusFruiting() && !mod.getPlayer().isBlocking()) { Item toUse = _cachedPerfectFood.get(); // Make sure we're not facing a container - if (!LookHelper.tryAvoidingInteractable(mod)) { - return Float.NEGATIVE_INFINITY; - } + LookHelper.tryAvoidingInteractable(mod); startEat(mod, toUse); } else { stopEat(mod); diff --git a/src/main/java/adris/altoclef/chains/MobDefenseChain.java b/src/main/java/adris/altoclef/chains/MobDefenseChain.java index 72b196969..3f2546fba 100644 --- a/src/main/java/adris/altoclef/chains/MobDefenseChain.java +++ b/src/main/java/adris/altoclef/chains/MobDefenseChain.java @@ -14,7 +14,6 @@ import adris.altoclef.util.helpers.*; import adris.altoclef.util.slots.PlayerSlot; import adris.altoclef.util.slots.Slot; -import adris.altoclef.util.time.TimerGame; import baritone.Baritone; import baritone.api.utils.Rotation; import baritone.api.utils.input.Input; @@ -37,7 +36,11 @@ import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; -import java.util.*; +import java.util.ArrayList; +import java.util.ConcurrentModificationException; +import java.util.List; +import java.util.Optional; +import java.util.function.Predicate; import static java.lang.Math.abs; @@ -50,7 +53,6 @@ public class MobDefenseChain extends SingleTaskChain { private static boolean _shielding = false; private final DragonBreathTracker _dragonBreathTracker = new DragonBreathTracker(); private final KillAura _killAura = new KillAura(); - private final HashMap _closeAnnoyingEntities = new HashMap<>(); private Entity _targetEntity; private boolean _doingFunkyStuff = false; private boolean _wasPuttingOutFire = false; @@ -262,69 +264,21 @@ public float getPriorityInner(AltoClef mod) { } List toDealWith = new ArrayList<>(); - // TODO: I don't think this lock is necessary at all. if (!hostiles.isEmpty()) { - synchronized (BaritoneHelper.MINECRAFT_LOCK) { - for (Entity hostile : hostiles) { - int annoyingRange = (hostile instanceof SkeletonEntity || hostile instanceof WitchEntity || hostile - instanceof PillagerEntity || hostile instanceof PiglinEntity || hostile instanceof StrayEntity) ? 15 : 8; - boolean isClose = hostile.isInRange(mod.getPlayer(), annoyingRange); - - if (isClose) { - isClose = LookHelper.seesPlayer(hostile, mod.getPlayer(), annoyingRange); + for (Entity entity : hostiles) { + if (entity instanceof MobEntity mob) { + boolean isAttackingPlayer = EntityHelper.isAngryAtPlayer(mod, mob); + if (isAttackingPlayer) { + toDealWith.add(mob); } - - // Give each hostile a timer, if they're close for too long deal with them. - if (isClose) { - if (!_closeAnnoyingEntities.containsKey(hostile)) { - boolean wardenAttacking = hostile instanceof WardenEntity; - boolean witherAttacking = hostile instanceof WitherEntity; - boolean endermanAttacking = hostile instanceof EndermanEntity; - boolean blazeAttacking = hostile instanceof BlazeEntity; - boolean witherSkeletonAttacking = hostile instanceof WitherSkeletonEntity; - boolean hoglinAttacking = hostile instanceof HoglinEntity; - boolean zoglinAttacking = hostile instanceof ZoglinEntity; - boolean piglinBruteAttacking = hostile instanceof PiglinBruteEntity; - boolean vindicatorAttacking = hostile instanceof VindicatorEntity; - if (blazeAttacking || witherSkeletonAttacking || hoglinAttacking || zoglinAttacking || - piglinBruteAttacking || endermanAttacking || witherAttacking || wardenAttacking || vindicatorAttacking) { - if (mod.getPlayer().getHealth() <= 10) { - _closeAnnoyingEntities.put(hostile, new TimerGame(0)); - } else { - _closeAnnoyingEntities.put(hostile, new TimerGame(Float.POSITIVE_INFINITY)); - } - } else { - _closeAnnoyingEntities.put(hostile, new TimerGame(0)); - } - _closeAnnoyingEntities.get(hostile).reset(); - } - if (_closeAnnoyingEntities.get(hostile).elapsed()) { - toDealWith.add(hostile); - } - } else { - _closeAnnoyingEntities.remove(hostile); - } - } - } - } - - // Clear dead/non existing hostiles - List toRemove = new ArrayList<>(); - if (!_closeAnnoyingEntities.keySet().isEmpty()) { - for (Entity check : _closeAnnoyingEntities.keySet()) { - if (!check.isAlive()) { - toRemove.add(check); } } } - if (!toRemove.isEmpty()) { - for (Entity remove : toRemove) _closeAnnoyingEntities.remove(remove); - } int numberOfProblematicEntities = toDealWith.size(); if (!toDealWith.isEmpty()) { for (Entity ToDealWith : toDealWith) { - if (ToDealWith.getClass() == SlimeEntity.class || ToDealWith.getClass() == MagmaCubeEntity.class) { + if (ToDealWith instanceof SlimeEntity) { numberOfProblematicEntities = 1; break; } @@ -362,31 +316,30 @@ public float getPriorityInner(AltoClef mod) { // We can deal with it. _runAwayTask = null; for (Entity ToDealWith : toDealWith) { + Predicate valid = entity -> EntityHelper.isAngryAtPlayer(mod, entity); + // Prioritize ranged enemies first. if (ToDealWith instanceof SkeletonEntity || ToDealWith instanceof WitchEntity || ToDealWith instanceof PillagerEntity || ToDealWith instanceof PiglinEntity || ToDealWith instanceof StrayEntity) { - setTask(new KillEntitiesTask(ToDealWith.getClass())); + setTask(new KillEntitiesTask(valid, ToDealWith.getClass())); return 65; } - setTask(new KillEntitiesTask(ToDealWith.getClass())); + setTask(new KillEntitiesTask(valid, ToDealWith.getClass())); return 65; } - return 65; - } else { - // We can't deal with it - _runAwayTask = new RunAwayFromHostilesTask(DANGER_KEEP_DISTANCE, true); - setTask(_runAwayTask); - return 80; } + // We can't deal with it + _runAwayTask = new RunAwayFromHostilesTask(DANGER_KEEP_DISTANCE, true); + setTask(_runAwayTask); + return 80; } } // By default if we aren't "immediately" in danger but were running away, keep running away until we're good. if (_runAwayTask != null && !_runAwayTask.isFinished(mod)) { setTask(_runAwayTask); return _cachedLastPriority; - } else { - _runAwayTask = null; } + _runAwayTask = null; return 0; } @@ -474,19 +427,19 @@ private CreeperEntity getClosestFusingCreeper(AltoClef mod) { double worstSafety = Float.POSITIVE_INFINITY; CreeperEntity target = null; try { - List creepers = mod.getEntityTracker().getTrackedEntities(CreeperEntity.class); - if (!creepers.isEmpty()) { - for (CreeperEntity creeper : creepers) { - if (creeper == null) continue; - if (creeper.getClientFuseTime(1) < 0.001) continue; - + Optional creeper = mod.getEntityTracker().getClosestEntity(CreeperEntity.class); + if (creeper.isPresent()) { + CreeperEntity creeperEntity = (CreeperEntity) creeper.get(); + if (!(creeperEntity.getClientFuseTime(1) < 0.001)) { // We want to pick the closest creeper, but FIRST pick creepers about to blow // At max fuse, the cost goes to basically zero. - double safety = getCreeperSafety(mod.getPlayer().getPos(), creeper); + double safety = getCreeperSafety(mod.getPlayer().getPos(), creeperEntity); if (safety < worstSafety) { - target = creeper; + target = creeperEntity; } } + ; + } } catch (ConcurrentModificationException | ArrayIndexOutOfBoundsException | NullPointerException e) { // IDK why but these exceptions happen sometimes. It's extremely bizarre and I have no idea why. @@ -541,7 +494,17 @@ private boolean isProjectileClose(AltoClef mod) { if (horizontalDistanceSq < ARROW_KEEP_DISTANCE_HORIZONTAL * ARROW_KEEP_DISTANCE_HORIZONTAL && verticalDistance < ARROW_KEEP_DISTANCE_VERTICAL) { if (_runAwayTask == null && mod.getClientBaritone().getPathingBehavior().isSafeToCancel()) { mod.getClientBaritone().getPathingBehavior().requestPause(); + if (projectile.projectileType instanceof ProjectileEntity projectileEntity) { + Entity owner = projectileEntity.getOwner(); + if (owner != null) { + LookHelper.lookAt(mod, owner.getEyePos()); + return true; + } + LookHelper.lookAt(mod, projectile.position); + return true; + } LookHelper.lookAt(mod, projectile.position); + return true; } return true; } diff --git a/src/main/java/adris/altoclef/chains/PlayerInteractionFixChain.java b/src/main/java/adris/altoclef/chains/PlayerInteractionFixChain.java index 5a49219b6..602b43f39 100644 --- a/src/main/java/adris/altoclef/chains/PlayerInteractionFixChain.java +++ b/src/main/java/adris/altoclef/chains/PlayerInteractionFixChain.java @@ -7,18 +7,15 @@ import adris.altoclef.util.helpers.ItemHelper; import adris.altoclef.util.helpers.LookHelper; import adris.altoclef.util.helpers.StorageHelper; -import adris.altoclef.util.slots.PlayerSlot; import adris.altoclef.util.slots.Slot; import adris.altoclef.util.time.TimerGame; import baritone.api.utils.Rotation; import baritone.api.utils.input.Input; -import net.minecraft.block.BlockState; import net.minecraft.client.MinecraftClient; import net.minecraft.client.gui.screen.ChatScreen; import net.minecraft.client.gui.screen.DeathScreen; import net.minecraft.client.gui.screen.GameMenuScreen; import net.minecraft.client.gui.screen.Screen; -import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.screen.slot.SlotActionType; @@ -58,31 +55,31 @@ public float getPriority(AltoClef mod) { if (!AltoClef.inGame()) return Float.NEGATIVE_INFINITY; - if (mod.getUserTaskChain().isActive() && _betterToolTimer.elapsed()) { - // Equip the right tool for the job if we're not using one. - _betterToolTimer.reset(); - if (mod.getControllerExtras().isBreakingBlock()) { - BlockState state = mod.getWorld().getBlockState(mod.getControllerExtras().getBreakingBlockPos()); - Optional bestToolSlot = StorageHelper.getBestToolSlot(mod, state); - Slot currentEquipped = PlayerSlot.getEquipSlot(); - - // if baritone is running, only accept tools OUTSIDE OF HOTBAR! - // Baritone will take care of tools inside the hotbar. - if (bestToolSlot.isPresent() && !bestToolSlot.get().equals(currentEquipped)) { - // ONLY equip if the item class is STRICTLY different (otherwise we swap around a lot) - if (StorageHelper.getItemStackInSlot(currentEquipped).getItem() != StorageHelper.getItemStackInSlot(bestToolSlot.get()).getItem()) { - boolean isAllowedToManage = (!mod.getClientBaritone().getPathingBehavior().isPathing() || - bestToolSlot.get().getInventorySlot() >= 9) && !mod.getFoodChain().isTryingToEat(); - if (isAllowedToManage) { - Debug.logMessage("Found better tool in inventory, equipping."); - ItemStack bestToolItemStack = StorageHelper.getItemStackInSlot(bestToolSlot.get()); - Item bestToolItem = bestToolItemStack.getItem(); - mod.getSlotHandler().forceEquipItem(bestToolItem); - } - } - } - } - } +// if (mod.getUserTaskChain().isActive() && _betterToolTimer.elapsed()) { +// // Equip the right tool for the job if we're not using one. +// _betterToolTimer.reset(); +// if (mod.getControllerExtras().isBreakingBlock()) { +// BlockState state = mod.getWorld().getBlockState(mod.getControllerExtras().getBreakingBlockPos()); +// Optional bestToolSlot = StorageHelper.getBestToolSlot(mod, state); +// Slot currentEquipped = PlayerSlot.getEquipSlot(); +// +// // if baritone is running, only accept tools OUTSIDE OF HOTBAR! +// // Baritone will take care of tools inside the hotbar. +// if (bestToolSlot.isPresent() && !bestToolSlot.get().equals(currentEquipped)) { +// // ONLY equip if the item class is STRICTLY different (otherwise we swap around a lot) +// if (StorageHelper.getItemStackInSlot(currentEquipped).getItem() != StorageHelper.getItemStackInSlot(bestToolSlot.get()).getItem()) { +// boolean isAllowedToManage = (!mod.getClientBaritone().getPathingBehavior().isPathing() || +// bestToolSlot.get().getInventorySlot() >= 9) && !mod.getFoodChain().isTryingToEat(); +// if (isAllowedToManage) { +// Debug.logMessage("Found better tool in inventory, equipping."); +// ItemStack bestToolItemStack = StorageHelper.getItemStackInSlot(bestToolSlot.get()); +// Item bestToolItem = bestToolItemStack.getItem(); +// mod.getSlotHandler().forceEquipItem(bestToolItem); +// } +// } +// } +// } +// } // Unpress shift (it gets stuck for some reason???) if (mod.getInputControls().isHeldDown(Input.SNEAK)) { diff --git a/src/main/java/adris/altoclef/eventbus/events/ClientRenderEvent.java b/src/main/java/adris/altoclef/eventbus/events/ClientRenderEvent.java index 32d27a888..be711daf5 100644 --- a/src/main/java/adris/altoclef/eventbus/events/ClientRenderEvent.java +++ b/src/main/java/adris/altoclef/eventbus/events/ClientRenderEvent.java @@ -1,12 +1,13 @@ package adris.altoclef.eventbus.events; +import net.minecraft.client.render.RenderTickCounter; import net.minecraft.client.util.math.MatrixStack; public class ClientRenderEvent { public MatrixStack stack; - public float tickDelta; + public RenderTickCounter tickDelta; - public ClientRenderEvent(MatrixStack stack, float tickDelta) { + public ClientRenderEvent(MatrixStack stack, RenderTickCounter tickDelta) { this.stack = stack; this.tickDelta = tickDelta; } diff --git a/src/main/java/adris/altoclef/mixins/ClientUIMixin.java b/src/main/java/adris/altoclef/mixins/ClientUIMixin.java index 2fdabea6f..122845353 100644 --- a/src/main/java/adris/altoclef/mixins/ClientUIMixin.java +++ b/src/main/java/adris/altoclef/mixins/ClientUIMixin.java @@ -4,6 +4,7 @@ import adris.altoclef.eventbus.events.ClientRenderEvent; import net.minecraft.client.gui.DrawContext; import net.minecraft.client.gui.hud.InGameHud; +import net.minecraft.client.render.RenderTickCounter; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; @@ -15,7 +16,7 @@ public final class ClientUIMixin { method = "render", at = @At("TAIL") ) - private void clientRender(DrawContext context, float tickDelta, CallbackInfo ci) { + private void clientRender(DrawContext context, RenderTickCounter tickDelta, CallbackInfo ci) { EventBus.publish(new ClientRenderEvent(context.getMatrices(), tickDelta)); } } diff --git a/src/main/java/adris/altoclef/mixins/EntityAccessor.java b/src/main/java/adris/altoclef/mixins/EntityAccessor.java deleted file mode 100644 index 77428d632..000000000 --- a/src/main/java/adris/altoclef/mixins/EntityAccessor.java +++ /dev/null @@ -1,11 +0,0 @@ -package adris.altoclef.mixins; - -import net.minecraft.entity.Entity; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.gen.Accessor; - -@Mixin(Entity.class) -public interface EntityAccessor { - @Accessor("inNetherPortal") - boolean isInNetherPortal(); -} diff --git a/src/main/java/adris/altoclef/tasks/CraftInInventoryTask.java b/src/main/java/adris/altoclef/tasks/CraftInInventoryTask.java index b1d5598e3..917b2dfd5 100644 --- a/src/main/java/adris/altoclef/tasks/CraftInInventoryTask.java +++ b/src/main/java/adris/altoclef/tasks/CraftInInventoryTask.java @@ -77,7 +77,9 @@ protected Task onResourceTick(AltoClef mod) { } } } - + if (StorageHelper.isBigCraftingOpen()) { + StorageHelper.closeScreen(); + } ItemTarget toGet = _itemTargets[0]; Item toGetItem = toGet.getMatches()[0]; if (_collect && !StorageHelper.hasRecipeMaterialsOrTarget(mod, _target)) { diff --git a/src/main/java/adris/altoclef/tasks/InteractWithBlockTask.java b/src/main/java/adris/altoclef/tasks/InteractWithBlockTask.java index 8fd30c1e8..f3796340b 100644 --- a/src/main/java/adris/altoclef/tasks/InteractWithBlockTask.java +++ b/src/main/java/adris/altoclef/tasks/InteractWithBlockTask.java @@ -290,7 +290,12 @@ protected Task onTick(AltoClef mod) { } int reachDistance = 0; - Goal moveGoal = createGoalForInteract(_target, reachDistance, _direction, _interactOffset, _walkInto); + Goal moveGoal; + if (mod.getExtraBaritoneSettings().shouldAvoidBreaking(_target.up())) { + moveGoal = new GoalTwoBlocks(_target.north()); + } else { + moveGoal = createGoalForInteract(_target, reachDistance, _direction, _interactOffset, _walkInto); + } ICustomGoalProcess proc = mod.getClientBaritone().getCustomGoalProcess(); _cachedClickStatus = rightClick(mod); @@ -395,18 +400,19 @@ private ClickResponse rightClick(AltoClef mod) { } Optional reachable = getCurrentReach(); - if (reachable.isPresent()) { + if (reachable.isPresent() && mod.getClientBaritone().getPathingBehavior().isSafeToCancel()) { if (LookHelper.isLookingAt(mod, _target)) { if (_toUse != null) { mod.getSlotHandler().forceEquipItem(_toUse, false); } else { mod.getSlotHandler().forceDeequipRightClickableItem(); } - mod.getInputControls().tryPress(_interactInput); + mod.getInputControls().hold(_interactInput); if (mod.getInputControls().isHeldDown(_interactInput)) { if (_shiftClick) { mod.getInputControls().hold(Input.SNEAK); } + mod.getInputControls().release(_interactInput); return ClickResponse.CLICK_ATTEMPTED; } //mod.getClientBaritone().getInputOverrideHandler().setInputForceState(_interactInput, true); diff --git a/src/main/java/adris/altoclef/tasks/construction/DestroyBlockTask.java b/src/main/java/adris/altoclef/tasks/construction/DestroyBlockTask.java index b4d2d6d02..f9b5c98df 100644 --- a/src/main/java/adris/altoclef/tasks/construction/DestroyBlockTask.java +++ b/src/main/java/adris/altoclef/tasks/construction/DestroyBlockTask.java @@ -1,6 +1,7 @@ package adris.altoclef.tasks.construction; import adris.altoclef.AltoClef; +import adris.altoclef.Debug; import adris.altoclef.tasks.movement.RunAwayFromPositionTask; import adris.altoclef.tasks.movement.SafeRandomShimmyTask; import adris.altoclef.tasksystem.ITaskRequiresGrounded; @@ -10,6 +11,7 @@ import adris.altoclef.util.helpers.StorageHelper; import adris.altoclef.util.helpers.WorldHelper; import adris.altoclef.util.progresscheck.MovementProgressChecker; +import adris.altoclef.util.slots.PlayerSlot; import adris.altoclef.util.slots.Slot; import baritone.api.pathing.goals.GoalBlock; import baritone.api.pathing.goals.GoalNear; @@ -18,6 +20,7 @@ import net.minecraft.block.*; import net.minecraft.entity.Entity; import net.minecraft.entity.mob.PillagerEntity; +import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.screen.slot.SlotActionType; import net.minecraft.util.math.BlockPos; @@ -288,7 +291,9 @@ protected Task onTick(AltoClef mod) { } Optional reach = LookHelper.getReach(_pos); - if (reach.isPresent() && (mod.getPlayer().isTouchingWater() || mod.getPlayer().isOnGround()) && !mod.getFoodChain().needsToEat() && !WorldHelper.isInNetherPortal(mod) && mod.getClientBaritone().getPathingBehavior().isSafeToCancel()) { + if (reach.isPresent() && (mod.getPlayer().isTouchingWater() || mod.getPlayer().isOnGround()) + && !mod.getFoodChain().needsToEat() && !WorldHelper.isInNetherPortal(mod) + && mod.getClientBaritone().getPathingBehavior().isSafeToCancel()) { setDebugState("Block in range, mining..."); stuckCheck.reset(); isMining = true; @@ -300,7 +305,25 @@ protected Task onTick(AltoClef mod) { if (!LookHelper.isLookingAt(mod, reach.get())) { LookHelper.lookAt(mod, reach.get()); } - // Tool equip is handled in `PlayerInteractionFixChain`. Oof. + BlockState state = mod.getWorld().getBlockState(_pos); + Optional bestToolSlot = StorageHelper.getBestToolSlot(mod, state); + Slot currentEquipped = PlayerSlot.getEquipSlot(); + // if baritone is running, only accept tools OUTSIDE OF HOTBAR! + // Baritone will take care of tools inside the hotbar. + if (bestToolSlot.isPresent() && bestToolSlot.get() != currentEquipped) { + // ONLY equip if the item class is STRICTLY different (otherwise we swap around a lot) + if (StorageHelper.getItemStackInSlot(currentEquipped).getItem() != StorageHelper.getItemStackInSlot(bestToolSlot.get()).getItem()) { + boolean isAllowedToManage = !mod.getClientBaritone().getPathingBehavior().isPathing() + && !mod.getFoodChain().isTryingToEat(); + if (isAllowedToManage) { + Debug.logMessage("Found better tool in inventory, equipping."); + ItemStack bestToolItemStack = StorageHelper.getItemStackInSlot(bestToolSlot.get()); + Item bestToolItem = bestToolItemStack.getItem(); + mod.getSlotHandler().forceEquipItem(bestToolItem); + } + return null; + } + } mod.getClientBaritone().getInputOverrideHandler().setInputForceState(Input.CLICK_LEFT, true); } else { setDebugState("Getting to block..."); diff --git a/src/main/java/adris/altoclef/tasks/construction/PlaceBlockNearbyTask.java b/src/main/java/adris/altoclef/tasks/construction/PlaceBlockNearbyTask.java index 84f2a41e8..0a940b788 100644 --- a/src/main/java/adris/altoclef/tasks/construction/PlaceBlockNearbyTask.java +++ b/src/main/java/adris/altoclef/tasks/construction/PlaceBlockNearbyTask.java @@ -145,7 +145,7 @@ protected Task onTick(AltoClef mod) { if (_tryPlace != null) { setDebugState("Trying to place at " + _tryPlace); _justPlaced = _tryPlace; - return new PlaceBlockTask(_tryPlace, _toPlace); + return new PlaceBlockTask(_tryPlace, _toPlace, false, true); } // Look in random places to maybe get a random hit diff --git a/src/main/java/adris/altoclef/tasks/construction/PlaceBlockTask.java b/src/main/java/adris/altoclef/tasks/construction/PlaceBlockTask.java index aa6ae3deb..1efaa5627 100644 --- a/src/main/java/adris/altoclef/tasks/construction/PlaceBlockTask.java +++ b/src/main/java/adris/altoclef/tasks/construction/PlaceBlockTask.java @@ -8,6 +8,7 @@ import adris.altoclef.tasksystem.ITaskRequiresGrounded; import adris.altoclef.tasksystem.Task; import adris.altoclef.util.ItemTarget; +import adris.altoclef.util.helpers.ItemHelper; import adris.altoclef.util.helpers.WorldHelper; import adris.altoclef.util.progresscheck.MovementProgressChecker; import baritone.api.schematic.AbstractSchematic; @@ -64,6 +65,8 @@ public static Task getMaterialTask(int count) { @Override protected void onStart(AltoClef mod) { _progressChecker.reset(); + mod.getBehaviour().push(); + mod.getBehaviour().addProtectedItems(ItemHelper.blocksToItems(_toPlace)); // If we get interrupted by another task, this might cause problems... //_wanderTask.resetWander(); } @@ -94,7 +97,6 @@ protected Task onTick(AltoClef mod) { _progressChecker.reset(); return _wanderTask; } - if (_autoCollectStructureBlocks) { if (_materialTask != null && _materialTask.isActive() && !_materialTask.isFinished(mod)) { setDebugState("No structure items, collecting cobblestone + dirt as default."); @@ -145,6 +147,7 @@ protected Task onTick(AltoClef mod) { @Override protected void onStop(AltoClef mod, Task interruptTask) { + mod.getBehaviour().pop(); mod.getClientBaritone().getBuilderProcess().onLostControl(); } @@ -203,7 +206,7 @@ public BlockState desiredState(int x, int y, int z, BlockState blockState, List< } Debug.logInternal("Failed to find throwaway block"); // No throwaways available!! - return new BlockOptionalMeta(Blocks.COBBLESTONE).getAnyBlockState(); + return new BlockOptionalMeta(Blocks.DIRT).getAnyBlockState(); } // Don't care. return blockState; diff --git a/src/main/java/adris/altoclef/tasks/construction/PlaceObsidianBucketTask.java b/src/main/java/adris/altoclef/tasks/construction/PlaceObsidianBucketTask.java index 7b65148c1..fd705959d 100644 --- a/src/main/java/adris/altoclef/tasks/construction/PlaceObsidianBucketTask.java +++ b/src/main/java/adris/altoclef/tasks/construction/PlaceObsidianBucketTask.java @@ -10,6 +10,7 @@ import adris.altoclef.util.ItemTarget; import adris.altoclef.util.helpers.WorldHelper; import adris.altoclef.util.progresscheck.MovementProgressChecker; +import baritone.api.utils.input.Input; import net.minecraft.block.Blocks; import net.minecraft.item.Items; import net.minecraft.util.math.BlockPos; @@ -144,6 +145,15 @@ protected Task onTick(AltoClef mod) { // Would lead to an embarrassing death. BlockPos targetPos = _pos.add(-1, 1, 0); if (!mod.getPlayer().getBlockPos().equals(targetPos) && mod.getItemStorage().hasItem(Items.LAVA_BUCKET)) { + if (!mod.getClientBaritone().getPathingBehavior().isPathing() + && targetPos.isWithinDistance(mod.getPlayer().getBlockPos(), 2)) { + mod.getInputControls().hold(Input.SNEAK); + mod.getInputControls().hold(Input.MOVE_BACK); + } else { + mod.getInputControls().release(Input.SNEAK); + mod.getInputControls().release(Input.MOVE_BACK); + mod.getInputControls().release(Input.MOVE_FORWARD); + } return new GetToBlockTask(targetPos, false); } if (WorldHelper.isSolid(mod, _pos)) { diff --git a/src/main/java/adris/altoclef/tasks/construction/compound/ConstructNetherPortalBucketTask.java b/src/main/java/adris/altoclef/tasks/construction/compound/ConstructNetherPortalBucketTask.java index f551f620d..c217e90f3 100644 --- a/src/main/java/adris/altoclef/tasks/construction/compound/ConstructNetherPortalBucketTask.java +++ b/src/main/java/adris/altoclef/tasks/construction/compound/ConstructNetherPortalBucketTask.java @@ -126,7 +126,8 @@ protected void onStart(AltoClef mod) { @Override protected Task onTick(AltoClef mod) { - if (MarvionBeatMinecraftTask.getConfig().renderDistanceManipulation) { + if (MarvionBeatMinecraftTask.getConfig().renderDistanceManipulation + && !mod.getClientBaritone().getExploreProcess().isActive()) { MinecraftClient.getInstance().options.getViewDistance().setValue(2); MinecraftClient.getInstance().options.getEntityDistanceScaling().setValue(0.5); } diff --git a/src/main/java/adris/altoclef/tasks/construction/compound/ConstructNetherPortalObsidianTask.java b/src/main/java/adris/altoclef/tasks/construction/compound/ConstructNetherPortalObsidianTask.java index 93c708cc9..877d7f130 100644 --- a/src/main/java/adris/altoclef/tasks/construction/compound/ConstructNetherPortalObsidianTask.java +++ b/src/main/java/adris/altoclef/tasks/construction/compound/ConstructNetherPortalObsidianTask.java @@ -11,6 +11,7 @@ import adris.altoclef.util.ItemTarget; import adris.altoclef.util.helpers.WorldHelper; import adris.altoclef.util.time.TimerGame; +import net.minecraft.block.Block; import net.minecraft.block.BlockState; import net.minecraft.block.Blocks; import net.minecraft.client.MinecraftClient; @@ -161,7 +162,7 @@ protected Task onTick(AltoClef mod) { // Place frame if (placeTarget != null) { setDebugState("Placing frame..."); - return new PlaceBlockTask(placeTarget, Blocks.OBSIDIAN); + return new PlaceBlockTask(placeTarget, new Block[]{Blocks.OBSIDIAN}, false, true); } // Clear middle diff --git a/src/main/java/adris/altoclef/tasks/construction/compound/ConstructNetherPortalSpeedrunTask.java b/src/main/java/adris/altoclef/tasks/construction/compound/ConstructNetherPortalSpeedrunTask.java index ab9e60e20..64c21eea1 100644 --- a/src/main/java/adris/altoclef/tasks/construction/compound/ConstructNetherPortalSpeedrunTask.java +++ b/src/main/java/adris/altoclef/tasks/construction/compound/ConstructNetherPortalSpeedrunTask.java @@ -20,7 +20,7 @@ import net.minecraft.util.math.Direction; import net.minecraft.util.math.Vec3i; -import java.util.HashSet; +import java.util.Optional; @SuppressWarnings("ALL") @Deprecated @@ -168,7 +168,7 @@ protected adris.altoclef.tasksystem.Task onTick(AltoClef mod) { _firstSearch = false; _lavaSearchTimer.reset(); Debug.logMessage("(Searching for lava lake with portalable spot nearby...)"); - BlockPos lavaPos = findLavaLake(mod, mod.getPlayer().getBlockPos()); + BlockPos lavaPos = findLavaLake(mod); if (lavaPos != null) { // We have a lava lake, set our portal origin! BlockPos foundPortalRegion = getPortalableRegion(lavaPos, mod.getPlayer().getBlockPos(), new Vec3i(-1, 0, 0), PORTALABLE_REGION_SIZE, 20); @@ -335,34 +335,27 @@ protected String toDebugString() { // Scans to find the nearest lava lake (collection of lava bigger than 12 blocks) - private BlockPos findLavaLake(AltoClef mod, BlockPos playerPos) { - HashSet alreadyExplored = new HashSet<>(); - - double nearestSqDistance = Double.POSITIVE_INFINITY; + private BlockPos findLavaLake(AltoClef mod) { BlockPos nearestLake = null; - for (BlockPos pos : mod.getBlockTracker().getKnownLocations(Blocks.LAVA)) { - if (alreadyExplored.contains(pos)) continue; - double sqDist = playerPos.getSquaredDistance(pos); - if (sqDist < nearestSqDistance) { - int depth = getNumberOfBlocksAdjacent(alreadyExplored, pos); - Debug.logMessage("Found with depth " + depth); - if (depth >= 12) { - nearestSqDistance = sqDist; - nearestLake = pos; + if (mod.getBlockTracker().isTracking(Blocks.LAVA)) { + Optional lavas = mod.getBlockTracker().getNearestTracking(Blocks.LAVA); + if (lavas.isPresent()) { + int depth = getNumberOfBlocksAdjacent(lavas.get()); + if (depth != 0) { + Debug.logMessage("Found with depth " + depth); + if (depth >= 12) { + nearestLake = lavas.get(); + } } } } - return nearestLake; } // Used to flood-scan for blocks of lava. - private int getNumberOfBlocksAdjacent(HashSet alreadyExplored, BlockPos origin) { - // Base case: We already explored this one - if (alreadyExplored.contains(origin)) return 0; - alreadyExplored.add(origin); - + private int getNumberOfBlocksAdjacent(BlockPos origin) { // Base case: We hit a non-full lava block. + assert MinecraftClient.getInstance().world != null; BlockState s = MinecraftClient.getInstance().world.getBlockState(origin); if (s.getBlock() != Blocks.LAVA) { return 0; @@ -380,7 +373,7 @@ private int getNumberOfBlocksAdjacent(HashSet alreadyExplored, BlockPo int bonus = 0; for (BlockPos check : toCheck) { // This block is new! Explore out from it. - bonus += getNumberOfBlocksAdjacent(alreadyExplored, check); + bonus += getNumberOfBlocksAdjacent(check); } return bonus + 1; diff --git a/src/main/java/adris/altoclef/tasks/container/CraftInTableTask.java b/src/main/java/adris/altoclef/tasks/container/CraftInTableTask.java index d4d8a7a20..8183d5a21 100644 --- a/src/main/java/adris/altoclef/tasks/container/CraftInTableTask.java +++ b/src/main/java/adris/altoclef/tasks/container/CraftInTableTask.java @@ -299,11 +299,10 @@ protected Task onTick(AltoClef mod) { mod.getBehaviour().addProtectedItems(getMaterialsArray()); // Avoid breaking crafting tables - List craftingTablePositions = mod.getBlockTracker().getKnownLocations(Blocks.CRAFTING_TABLE); - for (BlockPos craftingTablePos : craftingTablePositions) { - mod.getBehaviour().avoidBlockBreaking(craftingTablePos); + if (mod.getBlockTracker().isTracking(Blocks.CRAFTING_TABLE)) { + Optional craftingTable = mod.getBlockTracker().getNearestTracking(Blocks.CRAFTING_TABLE); + craftingTable.ifPresent(blockPos -> mod.getBehaviour().avoidBlockBreaking(blockPos)); } - // Check if the player inventory is open and the cursor slot is empty if (StorageHelper.isPlayerInventoryOpen() && StorageHelper.getItemStackInCursorSlot().isEmpty()) { // Get the item in the craft output slot diff --git a/src/main/java/adris/altoclef/tasks/misc/PlaceBedAndSetSpawnTask.java b/src/main/java/adris/altoclef/tasks/misc/PlaceBedAndSetSpawnTask.java index a6bc58e0d..3c796c947 100644 --- a/src/main/java/adris/altoclef/tasks/misc/PlaceBedAndSetSpawnTask.java +++ b/src/main/java/adris/altoclef/tasks/misc/PlaceBedAndSetSpawnTask.java @@ -11,6 +11,7 @@ import adris.altoclef.tasks.InteractWithBlockTask; import adris.altoclef.tasks.construction.DestroyBlockTask; import adris.altoclef.tasks.construction.PlaceStructureBlockTask; +import adris.altoclef.tasks.entity.KillEntitiesTask; import adris.altoclef.tasks.movement.DefaultGoToDimensionTask; import adris.altoclef.tasks.movement.GetToBlockTask; import adris.altoclef.tasks.movement.TimeoutWanderTask; @@ -28,14 +29,17 @@ import net.minecraft.client.MinecraftClient; import net.minecraft.client.gui.screen.Screen; import net.minecraft.client.gui.screen.SleepingChatScreen; +import net.minecraft.entity.Entity; +import net.minecraft.entity.mob.HostileEntity; import net.minecraft.util.hit.BlockHitResult; import net.minecraft.util.hit.HitResult; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Direction; -import net.minecraft.util.math.Vec3d; -import net.minecraft.util.math.Vec3i; +import net.minecraft.util.math.*; import org.apache.commons.lang3.ArrayUtils; +import java.util.List; +import java.util.Optional; +import java.util.function.Predicate; + public class PlaceBedAndSetSpawnTask extends Task { private final TimerGame _regionScanTimer = new TimerGame(9); @@ -239,54 +243,73 @@ protected Task onTick(AltoClef mod) { return null; } } - if (mod.getBlockTracker().anyFound(blockPos -> (WorldHelper.canReach(mod, blockPos) && - blockPos.isWithinDistance(mod.getPlayer().getPos(), 40) && - mod.getItemStorage().hasItem(ItemHelper.BED)) || (WorldHelper.canReach(mod, blockPos) && - !mod.getItemStorage().hasItem(ItemHelper.BED)), ItemHelper.itemsToBlocks(ItemHelper.BED))) { - // Sleep in the nearest bed - setDebugState("Going to bed to sleep..."); - return new DoToClosestBlockTask(toSleepIn -> { - boolean closeEnough = toSleepIn.isWithinDistance(mod.getPlayer().getPos(), 3); - if (closeEnough) { - // why 0.2? I'm tired. - Vec3d centerBed = new Vec3d(toSleepIn.getX() + 0.5, toSleepIn.getY() + 0.2, toSleepIn.getZ() + 0.5); - BlockHitResult hit = LookHelper.raycast(mod.getPlayer(), centerBed, 6); - // TODO: Kinda ugly, but I'm tired and fixing for the 2nd attempt speedrun so I will fix this block later - closeEnough = false; - if (hit.getType() != HitResult.Type.MISS) { - // At this poinAt, if we miss, we probably are close enough. - BlockPos p = hit.getBlockPos(); - if (ArrayUtils.contains(ItemHelper.itemsToBlocks(ItemHelper.BED), mod.getWorld().getBlockState(p).getBlock())) { - // We have a bed! - closeEnough = true; - } - } - } - _bedForSpawnPoint = WorldHelper.getBedHead(mod, toSleepIn); - if (_bedForSpawnPoint == null) { - _bedForSpawnPoint = toSleepIn; + Block[] copperBlocks = ItemHelper.itemsToBlocks(ItemHelper.COPPER_BLOCKS); + Optional nearestBed = mod.getBlockTracker().getNearestTracking(ItemHelper.itemsToBlocks(ItemHelper.BED)); + if (nearestBed.isPresent() && !WorldHelper.isAir(mod, nearestBed.get())) { + Block bed = mod.getWorld().getBlockState(nearestBed.get()).getBlock(); + for (Block CopperBlock : copperBlocks) { + Block blockBelow = mod.getWorld().getBlockState(nearestBed.get().down()).getBlock(); + if (blockBelow == CopperBlock) { + mod.getBlockTracker().requestBlockUnreachable(nearestBed.get(), 0); + return null; } - if (!closeEnough) { - try { - Direction face = mod.getWorld().getBlockState(toSleepIn).get(BedBlock.FACING); - Direction side = face.rotateYClockwise(); - /* - BlockPos targetMove = toSleepIn.offset(side).offset(side); // Twice, juust to make sure... - */ - return new GetToBlockTask(_bedForSpawnPoint.add(side.getVector())); - } catch (IllegalArgumentException e) { - // If bed is not loaded, this will happen. In that case just get to the bed first. + } + if (nearestBed.get().isWithinDistance(mod.getPlayer().getPos(), 40)) { + // Check if there are monsters nearby + Vec3d vec3d = Vec3d.ofBottomCenter(nearestBed.get()); + List list = mod.getWorld().getEntitiesByClass(HostileEntity.class, new Box(vec3d.getX() - 8.0, vec3d.getY() - 5.0, vec3d.getZ() - 8.0, vec3d.getX() + 8.0, vec3d.getY() + 5.0, vec3d.getZ() + 8.0), (entity) -> entity.isAngryAt(mod.getPlayer())); + if (!list.isEmpty()) { + for (HostileEntity entity : list) { + setDebugState("Killing monster nearby"); + Predicate valid = e -> e == entity; + return new KillEntitiesTask(valid, entity.getClass()); } - } else { - _inBedTimer.reset(); - } - if (closeEnough) { - _inBedTimer.reset(); } - // Keep track of where our spawn point is - _progressChecker.reset(); - return new InteractWithBlockTask(_bedForSpawnPoint); - }, ItemHelper.itemsToBlocks(ItemHelper.BED)); + // Sleep in the nearest bed + setDebugState("Going to bed to sleep..."); + return new DoToClosestBlockTask(toSleepIn -> { + boolean closeEnough = toSleepIn.isWithinDistance(mod.getPlayer().getPos(), 3); + if (closeEnough) { + // why 0.2? I'm tired. + Vec3d centerBed = new Vec3d(toSleepIn.getX() + 0.5, toSleepIn.getY() + 0.2, toSleepIn.getZ() + 0.5); + BlockHitResult hit = LookHelper.raycast(mod.getPlayer(), centerBed, 6); + // TODO: Kinda ugly, but I'm tired and fixing for the 2nd attempt speedrun so I will fix this block later + closeEnough = false; + if (hit.getType() != HitResult.Type.MISS) { + // At this poinAt, if we miss, we probably are close enough. + BlockPos p = hit.getBlockPos(); + if (ArrayUtils.contains(new Block[]{bed}, mod.getWorld().getBlockState(p).getBlock())) { + // We have a bed! + closeEnough = true; + } + } + } + _bedForSpawnPoint = WorldHelper.getBedHead(mod, toSleepIn); + if (_bedForSpawnPoint == null) { + _bedForSpawnPoint = toSleepIn; + } + if (!closeEnough) { + try { + Direction face = mod.getWorld().getBlockState(toSleepIn).get(BedBlock.FACING); + Direction side = face.rotateYClockwise(); + /* + BlockPos targetMove = toSleepIn.offset(side).offset(side); // Twice, juust to make sure... + */ + return new GetToBlockTask(_bedForSpawnPoint.add(side.getVector())); + } catch (IllegalArgumentException e) { + // If bed is not loaded, this will happen. In that case just get to the bed first. + } + } else { + _inBedTimer.reset(); + } + if (closeEnough) { + _inBedTimer.reset(); + } + // Keep track of where our spawn point is + _progressChecker.reset(); + return new InteractWithBlockTask(_bedForSpawnPoint); + }, bed); + } } if (_currentBedRegion != null) { for (Vec3i BedPlacePos : BED_PLACE_POS_OFFSET) { diff --git a/src/main/java/adris/altoclef/tasks/movement/CustomBaritoneGoalTask.java b/src/main/java/adris/altoclef/tasks/movement/CustomBaritoneGoalTask.java index 277c9c040..e7a427e77 100644 --- a/src/main/java/adris/altoclef/tasks/movement/CustomBaritoneGoalTask.java +++ b/src/main/java/adris/altoclef/tasks/movement/CustomBaritoneGoalTask.java @@ -113,17 +113,15 @@ protected Task onTick(AltoClef mod) { mod.getInputControls().hold(Input.SNEAK); mod.getInputControls().hold(Input.MOVE_FORWARD); return null; - } else { - mod.getInputControls().release(Input.SNEAK); - mod.getInputControls().release(Input.MOVE_BACK); - mod.getInputControls().release(Input.MOVE_FORWARD); - } - } else { - if (mod.getClientBaritone().getPathingBehavior().isPathing()) { - mod.getInputControls().release(Input.SNEAK); - mod.getInputControls().release(Input.MOVE_BACK); - mod.getInputControls().release(Input.MOVE_FORWARD); } + mod.getInputControls().release(Input.SNEAK); + mod.getInputControls().release(Input.MOVE_BACK); + mod.getInputControls().release(Input.MOVE_FORWARD); + } + if (mod.getClientBaritone().getPathingBehavior().isPathing()) { + mod.getInputControls().release(Input.SNEAK); + mod.getInputControls().release(Input.MOVE_BACK); + mod.getInputControls().release(Input.MOVE_FORWARD); } if (_unstuckTask != null && _unstuckTask.isActive() && !_unstuckTask.isFinished(mod) && stuckInBlock(mod) != null) { setDebugState("Getting unstuck from block."); diff --git a/src/main/java/adris/altoclef/tasks/movement/EscapeFromLavaTask.java b/src/main/java/adris/altoclef/tasks/movement/EscapeFromLavaTask.java index 6bc9afbe3..65af80201 100644 --- a/src/main/java/adris/altoclef/tasks/movement/EscapeFromLavaTask.java +++ b/src/main/java/adris/altoclef/tasks/movement/EscapeFromLavaTask.java @@ -24,6 +24,7 @@ public EscapeFromLavaTask() { @Override protected void onStart(AltoClef mod) { + mod.getFoodChain().shouldStop(true); mod.getBehaviour().push(); mod.getClientBaritone().getExploreProcess().onLostControl(); mod.getClientBaritone().getCustomGoalProcess().onLostControl(); @@ -41,15 +42,18 @@ protected Task onTick(AltoClef mod) { if (mod.getPlayer().isInLava() || mod.getWorld().getBlockState(mod.getPlayer().getBlockPos().down()).getBlock() == Blocks.LAVA) { mod.getInputControls().hold(Input.JUMP); mod.getInputControls().hold(Input.SPRINT); + mod.getInputControls().hold(Input.MOVE_FORWARD); } return super.onTick(mod); } @Override protected void onStop(AltoClef mod, Task interruptTask) { + mod.getFoodChain().shouldStop(false); mod.getBehaviour().pop(); mod.getInputControls().release(Input.JUMP); mod.getInputControls().release(Input.SPRINT); + mod.getInputControls().release(Input.MOVE_FORWARD); } @Override diff --git a/src/main/java/adris/altoclef/tasks/movement/LocateStrongholdCoordinatesTask.java b/src/main/java/adris/altoclef/tasks/movement/LocateStrongholdCoordinatesTask.java index 3e7f9de5d..9d24d7864 100644 --- a/src/main/java/adris/altoclef/tasks/movement/LocateStrongholdCoordinatesTask.java +++ b/src/main/java/adris/altoclef/tasks/movement/LocateStrongholdCoordinatesTask.java @@ -18,7 +18,6 @@ import net.minecraft.util.math.Vec3d; import net.minecraft.util.math.Vec3i; -import java.util.List; import java.util.Optional; public class LocateStrongholdCoordinatesTask extends Task { @@ -84,19 +83,15 @@ protected Task onTick(AltoClef mod) { if (mod.getEntityTracker().entityFound(EyeOfEnderEntity.class)) { if (_currentThrownEye == null || !_currentThrownEye.isAlive()) { Debug.logMessage("New eye direction"); - List enderEyes = mod.getEntityTracker().getTrackedEntities(EyeOfEnderEntity.class); - if (!enderEyes.isEmpty()) { - for (EyeOfEnderEntity enderEye : enderEyes) { - _currentThrownEye = enderEye; - } - } + Optional eye = mod.getEntityTracker().getClosestEntity(EyeOfEnderEntity.class); + eye.ifPresent(entity -> _currentThrownEye = entity); if (_cachedEyeDirection2 != null) { _cachedEyeDirection = null; _cachedEyeDirection2 = null; } else if (_cachedEyeDirection == null) { - _cachedEyeDirection = new LocateStrongholdCoordinatesTask.EyeDirection(_currentThrownEye.getPos()); + _cachedEyeDirection = new EyeDirection(_currentThrownEye.getPos()); } else { - _cachedEyeDirection2 = new LocateStrongholdCoordinatesTask.EyeDirection(_currentThrownEye.getPos()); + _cachedEyeDirection2 = new EyeDirection(_currentThrownEye.getPos()); } } if (_cachedEyeDirection2 != null) { diff --git a/src/main/java/adris/altoclef/tasks/movement/MLGBucketTask.java b/src/main/java/adris/altoclef/tasks/movement/MLGBucketTask.java index 14c38aa97..a086d250e 100644 --- a/src/main/java/adris/altoclef/tasks/movement/MLGBucketTask.java +++ b/src/main/java/adris/altoclef/tasks/movement/MLGBucketTask.java @@ -29,7 +29,6 @@ import net.minecraft.util.math.Vec3d; import net.minecraft.world.RaycastContext; -import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.Optional; @@ -182,7 +181,7 @@ private Task placeMLGBucketTask(AltoClef mod, BlockPos toPlaceOn) { } IPlayerContext ctx = mod.getClientBaritone().getPlayerContext(); - Optional reachable = RotationUtils.reachableCenter(ctx.player(), toPlaceOn, ctx.playerController().getBlockReachDistance(), false); + Optional reachable = RotationUtils.reachable(ctx, toPlaceOn); if (reachable.isPresent()) { setDebugState("Performing MLG"); LookHelper.lookAt(mod, reachable.get()); @@ -199,9 +198,7 @@ private Task placeMLGBucketTask(AltoClef mod, BlockPos toPlaceOn) { } } } - // Try to capture tall grass as well... - BlockPos[] toCheckLook = new BlockPos[]{toPlaceOn, toPlaceOn.up(), toPlaceOn.up(2)}; - if (hasClutch && Arrays.stream(toCheckLook).anyMatch(check -> mod.getClientBaritone().getPlayerContext().isLookingAt(check))) { + if (hasClutch) { Debug.logMessage("HIT: " + willLandIn); _placedPos = willLandIn; mod.getInputControls().tryPress(Input.CLICK_RIGHT); @@ -287,8 +284,6 @@ private void handleJumpForLand(AltoClef mod, BlockPos willLandOn) { private Optional getBlockWeWillLandOn(AltoClef mod) { Vec3d velCheck = mod.getPlayer().getVelocity(); - // Flatten and slightly exaggerate the velocity - velCheck.multiply(10, 0, 10); Box b = mod.getPlayer().getBoundingBox().offset(velCheck); Vec3d c = b.getCenter(); Vec3d[] coords = new Vec3d[]{ diff --git a/src/main/java/adris/altoclef/tasks/movement/RunAwayFromCreepersTask.java b/src/main/java/adris/altoclef/tasks/movement/RunAwayFromCreepersTask.java index 49c69bcda..92dfcd6a9 100644 --- a/src/main/java/adris/altoclef/tasks/movement/RunAwayFromCreepersTask.java +++ b/src/main/java/adris/altoclef/tasks/movement/RunAwayFromCreepersTask.java @@ -9,8 +9,7 @@ import net.minecraft.entity.mob.CreeperEntity; import net.minecraft.util.math.Vec3d; -import java.util.ArrayList; -import java.util.List; +import java.util.Optional; public class RunAwayFromCreepersTask extends CustomBaritoneGoalTask { @@ -50,8 +49,8 @@ public GoalRunAwayFromCreepers(AltoClef mod, double distance) { } @Override - protected List getEntities(AltoClef mod) { - return new ArrayList<>(mod.getEntityTracker().getTrackedEntities(CreeperEntity.class)); + protected Optional getEntities(AltoClef mod) { + return mod.getEntityTracker().getClosestEntity(CreeperEntity.class); } @Override diff --git a/src/main/java/adris/altoclef/tasks/movement/RunAwayFromEntitiesTask.java b/src/main/java/adris/altoclef/tasks/movement/RunAwayFromEntitiesTask.java index 23aae3b60..c74b54bcc 100644 --- a/src/main/java/adris/altoclef/tasks/movement/RunAwayFromEntitiesTask.java +++ b/src/main/java/adris/altoclef/tasks/movement/RunAwayFromEntitiesTask.java @@ -5,26 +5,25 @@ import baritone.api.pathing.goals.Goal; import net.minecraft.entity.Entity; -import java.util.List; -import java.util.function.Supplier; +import java.util.Optional; public abstract class RunAwayFromEntitiesTask extends CustomBaritoneGoalTask { - private final Supplier> _runAwaySupplier; + private final Entity _runAwaySupplier; private final double _distanceToRun; private final boolean _xz; // See GoalrunAwayFromEntities penalty value private final double _penalty; - public RunAwayFromEntitiesTask(Supplier> toRunAwayFrom, double distanceToRun, boolean xz, double penalty) { + public RunAwayFromEntitiesTask(Entity toRunAwayFrom, double distanceToRun, boolean xz, double penalty) { _runAwaySupplier = toRunAwayFrom; _distanceToRun = distanceToRun; _xz = xz; _penalty = penalty; } - public RunAwayFromEntitiesTask(Supplier> toRunAwayFrom, double distanceToRun, double penalty) { + public RunAwayFromEntitiesTask(Entity toRunAwayFrom, double distanceToRun, double penalty) { this(toRunAwayFrom, distanceToRun, false, penalty); } @@ -42,8 +41,8 @@ public GoalRunAwayStuff(AltoClef mod, double distance, boolean xz) { } @Override - protected List getEntities(AltoClef mod) { - return _runAwaySupplier.get(); + protected Optional getEntities(AltoClef mod) { + return Optional.ofNullable(_runAwaySupplier); } } } diff --git a/src/main/java/adris/altoclef/tasks/movement/RunAwayFromHostilesTask.java b/src/main/java/adris/altoclef/tasks/movement/RunAwayFromHostilesTask.java index 39163080d..0e1c04854 100644 --- a/src/main/java/adris/altoclef/tasks/movement/RunAwayFromHostilesTask.java +++ b/src/main/java/adris/altoclef/tasks/movement/RunAwayFromHostilesTask.java @@ -3,14 +3,12 @@ import adris.altoclef.AltoClef; import adris.altoclef.tasksystem.Task; import adris.altoclef.util.baritone.GoalRunAwayFromEntities; -import adris.altoclef.util.helpers.BaritoneHelper; import baritone.api.pathing.goals.Goal; import net.minecraft.entity.Entity; import net.minecraft.entity.mob.SkeletonEntity; import java.util.List; -import java.util.stream.Collectors; -import java.util.stream.Stream; +import java.util.Optional; public class RunAwayFromHostilesTask extends CustomBaritoneGoalTask { @@ -54,15 +52,20 @@ public GoalRunAwayFromHostiles(AltoClef mod, double distance) { } @Override - protected List getEntities(AltoClef mod) { - List result; - Stream stream = mod.getEntityTracker().getHostiles().stream(); - synchronized (BaritoneHelper.MINECRAFT_LOCK) { - if (!_includeSkeletons) { - stream = stream.filter(hostile -> !(hostile instanceof SkeletonEntity)); + protected Optional getEntities(AltoClef mod) { + List hostiles = mod.getEntityTracker().getHostiles(); + if (!hostiles.isEmpty()) { + for (Entity hostile : hostiles) { + Optional closestHostile = mod.getEntityTracker().getClosestEntity(hostile.getClass()); + if (closestHostile.isPresent()) { + if (!_includeSkeletons && closestHostile.get() instanceof SkeletonEntity) { + return Optional.empty(); + } + return closestHostile; + } } - return stream.collect(Collectors.toList()); } + return Optional.empty(); } } } diff --git a/src/main/java/adris/altoclef/tasks/movement/TimeoutWanderTask.java b/src/main/java/adris/altoclef/tasks/movement/TimeoutWanderTask.java index 3294745d7..f2390439e 100644 --- a/src/main/java/adris/altoclef/tasks/movement/TimeoutWanderTask.java +++ b/src/main/java/adris/altoclef/tasks/movement/TimeoutWanderTask.java @@ -22,8 +22,8 @@ import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; -import java.util.List; import java.util.Optional; +import java.util.function.Predicate; /** * Call this when the place you're currently at is bad for some reason and you just wanna get away. @@ -184,13 +184,11 @@ protected Task onTick(AltoClef mod) { return _unstuckTask; } if (!_progressChecker.check(mod) || !stuckCheck.check(mod)) { - List closeEntities = mod.getEntityTracker().getCloseEntities(); - for (Entity CloseEntities : closeEntities) { - if (CloseEntities instanceof MobEntity && - CloseEntities.getPos().isInRange(mod.getPlayer().getPos(), 1)) { - setDebugState("Killing annoying entity."); - return new KillEntitiesTask(CloseEntities.getClass()); - } + Optional mob = mod.getEntityTracker().getClosestEntity(MobEntity.class); + if (mob.isPresent() && mob.get().getPos().isInRange(mod.getPlayer().getPos(), 1)) { + setDebugState("Killing annoying entity."); + Predicate valid = entity -> entity == mob.get(); + return new KillEntitiesTask(valid, mob.get().getClass()); } BlockPos blockStuck = stuckInBlock(mod); if (blockStuck != null) { diff --git a/src/main/java/adris/altoclef/tasks/resources/CollectBedTask.java b/src/main/java/adris/altoclef/tasks/resources/CollectBedTask.java index f2a9790e2..929e4349f 100644 --- a/src/main/java/adris/altoclef/tasks/resources/CollectBedTask.java +++ b/src/main/java/adris/altoclef/tasks/resources/CollectBedTask.java @@ -1,6 +1,7 @@ package adris.altoclef.tasks.resources; import adris.altoclef.AltoClef; +import adris.altoclef.Debug; import adris.altoclef.TaskCatalogue; import adris.altoclef.tasks.ResourceTask; import adris.altoclef.tasksystem.Task; @@ -8,8 +9,12 @@ import adris.altoclef.util.ItemTarget; import adris.altoclef.util.MiningRequirement; import adris.altoclef.util.helpers.ItemHelper; +import adris.altoclef.util.helpers.WorldHelper; import net.minecraft.block.Block; import net.minecraft.item.Item; +import net.minecraft.util.math.BlockPos; + +import java.util.Optional; public class CollectBedTask extends CraftWithMatchingWoolTask { @@ -57,9 +62,18 @@ protected void onResourceStop(AltoClef mod, Task interruptTask) { @Override protected Task onResourceTick(AltoClef mod) { // Break beds from the world if possible, that would be pretty fast. - if (mod.getBlockTracker().anyFound(BEDS)) { - // Failure + blacklisting is encapsulated within THIS task - return new MineAndCollectTask(new ItemTarget(ItemHelper.BED, 1), BEDS, MiningRequirement.HAND); + Block[] copperBlocks = ItemHelper.itemsToBlocks(ItemHelper.COPPER_BLOCKS); + Optional nearestBed = mod.getBlockTracker().getNearestTracking(BEDS); + if (nearestBed.isPresent() && WorldHelper.canBreak(mod, nearestBed.get())) { + for (Block CopperBlock : copperBlocks) { + Block blockBelow = mod.getWorld().getBlockState(nearestBed.get().down()).getBlock(); + if (blockBelow == CopperBlock) { + Debug.logMessage("Blacklisting bed in trial chambers."); + mod.getBlockTracker().requestBlockUnreachable(nearestBed.get(), 0); + } + } + // Failure + blacklisting is encapsulated within THIS task) + return new MineAndCollectTask(new ItemTarget(ItemHelper.BED), BEDS, MiningRequirement.HAND); } return super.onResourceTick(mod); } diff --git a/src/main/java/adris/altoclef/tasks/resources/CollectBlazeRodsTask.java b/src/main/java/adris/altoclef/tasks/resources/CollectBlazeRodsTask.java index dc69ed706..ecaf99f8d 100644 --- a/src/main/java/adris/altoclef/tasks/resources/CollectBlazeRodsTask.java +++ b/src/main/java/adris/altoclef/tasks/resources/CollectBlazeRodsTask.java @@ -62,23 +62,19 @@ protected Task onResourceTick(AltoClef mod) { setDebugState("Going to nether"); return new DefaultGoToDimensionTask(Dimension.NETHER); } - - Optional toKill = Optional.empty(); // If there is a blaze, kill it. - if (mod.getEntityTracker().entityFound(BlazeEntity.class)) { - toKill = mod.getEntityTracker().getClosestEntity(BlazeEntity.class); - if (toKill.isPresent()) { - if (mod.getPlayer().getHealth() <= TOO_LITTLE_HEALTH_BLAZE && - mod.getEntityTracker().getTrackedEntities(BlazeEntity.class).size() >= TOO_MANY_BLAZES) { - setDebugState("Running away as there are too many blazes nearby."); - return new RunAwayFromHostilesTask(15 * 2, true); - } + Predicate safeToPursue = entity -> !isHoveringAboveLavaOrTooHigh(mod, entity); + Optional toKill; + toKill = mod.getEntityTracker().getClosestEntity(safeToPursue, BlazeEntity.class); + if (toKill.isPresent()) { + if (mod.getPlayer().getHealth() <= TOO_LITTLE_HEALTH_BLAZE && + mod.getEntityTracker().getTrackedEntities(BlazeEntity.class).size() >= TOO_MANY_BLAZES) { + setDebugState("Running away as there are too many blazes nearby."); + return new RunAwayFromHostilesTask(15 * 2, true); } - - if (_foundBlazeSpawner != null && toKill.isPresent()) { + if (_foundBlazeSpawner != null) { Entity kill = toKill.get(); Vec3d nearest = kill.getPos(); - double sqDistanceToPlayer = nearest.squaredDistanceTo(mod.getPlayer().getPos());//_foundBlazeSpawner.getX(), _foundBlazeSpawner.getY(), _foundBlazeSpawner.getZ()); // Ignore if the blaze is too far away. if (sqDistanceToPlayer > SPAWNER_BLAZE_RADIUS * SPAWNER_BLAZE_RADIUS) { @@ -90,9 +86,8 @@ protected Task onResourceTick(AltoClef mod) { } } } - if (toKill.isPresent() && toKill.get().isAlive() && !isHoveringAboveLavaOrTooHigh(mod, toKill.get())) { + if (toKill.isPresent()) { setDebugState("Killing blaze"); - Predicate safeToPursue = entity -> !isHoveringAboveLavaOrTooHigh(mod, entity); return new KillEntitiesTask(safeToPursue, toKill.get().getClass()); } @@ -108,28 +103,23 @@ protected Task onResourceTick(AltoClef mod) { if (!_foundBlazeSpawner.isWithinDistance(mod.getPlayer().getPos(), 4)) { setDebugState("Going to blaze spawner"); return new GetToBlockTask(_foundBlazeSpawner.up(), false); - } else { - - // Put out fire that might mess with us. - Optional nearestFire = mod.getBlockTracker().getNearestWithinRange(_foundBlazeSpawner, 5, Blocks.FIRE); - if (nearestFire.isPresent()) { - setDebugState("Clearing fire around spawner to prevent loss of blaze rods."); - return new PutOutFireTask(nearestFire.get()); - } - - setDebugState("Waiting near blaze spawner for blazes to spawn"); - return null; } - } else { - // Search for blaze - for (BlockPos pos : mod.getBlockTracker().getKnownLocations(Blocks.SPAWNER)) { - if (isValidBlazeSpawner(mod, pos)) { - _foundBlazeSpawner = pos; - break; - } + // Put out fire that might mess with us. + Optional nearestFire = mod.getBlockTracker().getNearestWithinRange(_foundBlazeSpawner, 5, Blocks.FIRE); + if (nearestFire.isPresent()) { + setDebugState("Clearing fire around spawner to prevent loss of blaze rods."); + return new PutOutFireTask(nearestFire.get()); + } + setDebugState("Waiting near blaze spawner for blazes to spawn"); + return null; + } + // Search for blaze + if (mod.getBlockTracker().isTracking(Blocks.SPAWNER)) { + Optional spawner = mod.getBlockTracker().getNearestTracking(Blocks.SPAWNER); + if (spawner.isPresent() && isValidBlazeSpawner(mod, spawner.get())) { + _foundBlazeSpawner = spawner.get(); } } - // We need to find our fortress. setDebugState("Searching for fortress/Traveling around fortress"); return _searcher; diff --git a/src/main/java/adris/altoclef/tasks/resources/CollectBucketLiquidTask.java b/src/main/java/adris/altoclef/tasks/resources/CollectBucketLiquidTask.java index f47744abf..46446ed8f 100644 --- a/src/main/java/adris/altoclef/tasks/resources/CollectBucketLiquidTask.java +++ b/src/main/java/adris/altoclef/tasks/resources/CollectBucketLiquidTask.java @@ -24,10 +24,10 @@ import net.minecraft.item.Item; import net.minecraft.item.Items; import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Vec3i; import net.minecraft.world.RaycastContext; import java.util.HashSet; +import java.util.Optional; import java.util.function.Predicate; public class CollectBucketLiquidTask extends ResourceTask { @@ -137,40 +137,42 @@ protected Task onResourceTick(AltoClef mod) { }; // Find nearest water and right click it - if (mod.getBlockTracker().anyFound(isSourceLiquid, _toCollect)) { - // We want to MINIMIZE this distance to liquid. - setDebugState("Trying to collect..."); - //Debug.logMessage("TEST: " + RayTraceUtils.fluidHandling); - - return new DoToClosestBlockTask(blockPos -> { - // Clear above if lava because we can't enter. - // but NOT if we're standing right above. - if (WorldHelper.isSolid(mod, blockPos.up())) { - if (!_progressChecker.check(mod)) { - mod.getClientBaritone().getPathingBehavior().cancelEverything(); - mod.getClientBaritone().getPathingBehavior().forceCancel(); - mod.getClientBaritone().getExploreProcess().onLostControl(); - mod.getClientBaritone().getCustomGoalProcess().onLostControl(); - Debug.logMessage("Failed to break, blacklisting."); - mod.getBlockTracker().requestBlockUnreachable(blockPos); - _blacklist.add(blockPos); + if (mod.getBlockTracker().isTracking(_toCollect)) { + Optional nearestSource = mod.getBlockTracker().getNearestTracking(isSourceLiquid, _toCollect); + if (nearestSource.isPresent()) { + Block nearestSourceBlock = mod.getWorld().getBlockState(nearestSource.get()).getBlock(); + // We want to MINIMIZE this distance to liquid. + setDebugState("Trying to collect..."); + //Debug.logMessage("TEST: " + RayTraceUtils.fluidHandling); + return new DoToClosestBlockTask(blockPos -> { + // Clear above if lava because we can't enter. + // but NOT if we're standing right above. + if (WorldHelper.isSolid(mod, blockPos.up())) { + if (!_progressChecker.check(mod)) { + mod.getClientBaritone().getPathingBehavior().cancelEverything(); + mod.getClientBaritone().getPathingBehavior().forceCancel(); + mod.getClientBaritone().getExploreProcess().onLostControl(); + mod.getClientBaritone().getCustomGoalProcess().onLostControl(); + Debug.logMessage("Failed to break, blacklisting."); + mod.getBlockTracker().requestBlockUnreachable(blockPos); + _blacklist.add(blockPos); + } + return new DestroyBlockTask(blockPos.up()); } - return new DestroyBlockTask(blockPos.up()); - } - - // We can reach the block. - if (LookHelper.getReach(blockPos).isPresent() && - mod.getClientBaritone().getPathingBehavior().isSafeToCancel()) { - return new InteractWithBlockTask(new ItemTarget(Items.BUCKET, 1), blockPos, _toCollect != Blocks.LAVA, new Vec3i(0, 1, 0)); - } - // Get close enough. - // up because if we go below we'll try to move next to the liquid (for lava, not a good move) - if (this.thisOrChildAreTimedOut() && !wasWandering) { - mod.getBlockTracker().requestBlockUnreachable(blockPos.up()); - wasWandering = true; - } - return new GetCloseToBlockTask(blockPos.up()); - }, isSourceLiquid, _toCollect); + // We can reach the block. + if (LookHelper.getReach(blockPos).isPresent() && + mod.getClientBaritone().getPathingBehavior().isSafeToCancel()) { + return new InteractWithBlockTask(new ItemTarget(Items.BUCKET, 1), blockPos, _toCollect != Blocks.LAVA); + } + // Get close enough. + // up because if we go below we'll try to move next to the liquid (for lava, not a good move) + if (this.thisOrChildAreTimedOut() && !wasWandering) { + mod.getBlockTracker().requestBlockUnreachable(blockPos.up()); + wasWandering = true; + } + return new GetCloseToBlockTask(blockPos.up()); + }, isSourceLiquid, nearestSourceBlock); + } } // Dimension diff --git a/src/main/java/adris/altoclef/tasks/resources/CollectFoodTask.java b/src/main/java/adris/altoclef/tasks/resources/CollectFoodTask.java index 54b62decb..b6b12ed06 100644 --- a/src/main/java/adris/altoclef/tasks/resources/CollectFoodTask.java +++ b/src/main/java/adris/altoclef/tasks/resources/CollectFoodTask.java @@ -36,25 +36,20 @@ import net.minecraft.screen.SmokerScreenHandler; import net.minecraft.util.math.BlockPos; -import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.function.Predicate; public class CollectFoodTask extends Task { - // Actually screw fish baritone does NOT play nice underwater. - // Fish kinda suck to harvest so heavily penalize them. - private static final double FISH_PENALTY = 0 * 0.03; - // Represents order of preferred mobs to least preferred private static final CookableFoodTarget[] COOKABLE_FOODS = new CookableFoodTarget[]{ - new CookableFoodTarget("beef", CowEntity.class), new CookableFoodTarget("porkchop", PigEntity.class), - new CookableFoodTargetFish("salmon", SalmonEntity.class), + new CookableFoodTarget("beef", CowEntity.class), new CookableFoodTarget("chicken", ChickenEntity.class), + new CookableFoodTarget("mutton", SheepEntity.class), new CookableFoodTargetFish("cod", CodEntity.class), - new CookableFoodTarget("mutton", SheepEntity.class) + new CookableFoodTargetFish("salmon", SalmonEntity.class) }; private static final Item[] ITEMS_TO_PICK_UP = new Item[]{ @@ -155,12 +150,14 @@ protected Task onTick(AltoClef mod) { } } } - List haysPos = mod.getBlockTracker().getKnownLocations(Blocks.HAY_BLOCK); - for (BlockPos HaysPos : haysPos) { - BlockPos haysUpPos = HaysPos.up(); - if (mod.getWorld().getBlockState(haysUpPos).getBlock() == Blocks.CARVED_PUMPKIN) { - Debug.logMessage("Blacklisting pillage hay bales."); - mod.getBlockTracker().requestBlockUnreachable(HaysPos, 0); + if (mod.getBlockTracker().isTracking(Blocks.HAY_BLOCK)) { + Optional hay = mod.getBlockTracker().getNearestTracking(Blocks.HAY_BLOCK); + if (hay.isPresent()) { + BlockPos haysUpPos = hay.get().up(); + if (mod.getWorld().getBlockState(haysUpPos).getBlock() == Blocks.CARVED_PUMPKIN) { + Debug.logMessage("Blacklisting pillage hay bales."); + mod.getBlockTracker().requestBlockUnreachable(hay.get(), 0); + } } } // If we were previously smelting, keep on smelting. @@ -275,30 +272,26 @@ protected Task onTick(AltoClef mod) { } } // Cooked foods - double bestScore = 0; - Entity bestEntity = null; - Item bestRawFood = null; for (CookableFoodTarget cookable : COOKABLE_FOODS) { - if (!mod.getEntityTracker().entityFound(cookable.mobToKill)) continue; - Optional nearest = mod.getEntityTracker().getClosestEntity(mod.getPlayer().getPos(), cookable.mobToKill); - if (nearest.isEmpty()) continue; // ?? This crashed once? - int hungerPerformance = cookable.getCookedUnits(); - double sqDistance = nearest.get().squaredDistanceTo(mod.getPlayer()); - double score = (double) 100 * hungerPerformance / (sqDistance); - if (cookable.isFish()) { - score *= FISH_PENALTY; - } - if (score > bestScore) { - bestScore = score; - bestEntity = nearest.get(); - bestRawFood = cookable.getRaw(); - } - } - if (bestEntity != null) { - setDebugState("Killing " + bestEntity.getType().getTranslationKey()); Predicate notBaby = entity -> entity instanceof LivingEntity livingEntity && !livingEntity.isBaby(); - _currentResourceTask = killTaskOrNull(bestEntity, notBaby, bestRawFood); - return _currentResourceTask; + Optional nearest = mod.getEntityTracker().getClosestEntity(notBaby, cookable.mobToKill); + if (nearest.isPresent()) { + setDebugState("Killing " + nearest.get().getType().getTranslationKey()); + _currentResourceTask = killTaskOrNull(nearest.get(), notBaby, cookable.getRaw()); + return _currentResourceTask; + } +// if (nearest.isEmpty()) continue; // ?? This crashed once? +// int hungerPerformance = cookable.getCookedUnits(); +// double sqDistance = nearest.get().squaredDistanceTo(mod.getPlayer()); +// double score = (double) 100 * hungerPerformance / (sqDistance); +// if (cookable.isFish()) { +// score *= FISH_PENALTY; +// } +// if (score > bestScore) { +// bestScore = score; +// bestEntity = nearest.get(); +// bestRawFood = cookable.getRaw(); +// } } // Sweet berries (separate from crops because they should have a lower priority than everything else cause they suck) diff --git a/src/main/java/adris/altoclef/tasks/resources/GetSmithingTemplateTask.java b/src/main/java/adris/altoclef/tasks/resources/GetSmithingTemplateTask.java index e74195f1a..01069759d 100644 --- a/src/main/java/adris/altoclef/tasks/resources/GetSmithingTemplateTask.java +++ b/src/main/java/adris/altoclef/tasks/resources/GetSmithingTemplateTask.java @@ -12,6 +12,8 @@ import net.minecraft.item.Items; import net.minecraft.util.math.BlockPos; +import java.util.Optional; + public class GetSmithingTemplateTask extends ResourceTask { private final Task _searcher = new SearchChunkForBlockTask(Blocks.BLACKSTONE); @@ -40,10 +42,10 @@ protected Task onResourceTick(AltoClef mod) { // _bastionloc = null; // } if (_chestloc == null) { - for (BlockPos pos : mod.getBlockTracker().getKnownLocations(Blocks.CHEST)) { - if (WorldHelper.isInteractableBlock(mod, pos)) { - _chestloc = pos; - break; + if (mod.getBlockTracker().isTracking(Blocks.CHEST)) { + Optional chest = mod.getBlockTracker().getNearestTracking(Blocks.CHEST); + if (chest.isPresent() && WorldHelper.isInteractableBlock(mod, chest.get())) { + _chestloc = chest.get(); } } } @@ -54,10 +56,10 @@ protected Task onResourceTick(AltoClef mod) { return new DestroyBlockTask(_chestloc); } else { _chestloc = null; - for (BlockPos pos : mod.getBlockTracker().getKnownLocations(Blocks.CHEST)) { - if (WorldHelper.isInteractableBlock(mod, pos)) { - _chestloc = pos; - break; + if (mod.getBlockTracker().isTracking(Blocks.CHEST)) { + Optional chest = mod.getBlockTracker().getNearestTracking(Blocks.CHEST); + if (chest.isPresent() && WorldHelper.isInteractableBlock(mod, chest.get())) { + _chestloc = chest.get(); } } } diff --git a/src/main/java/adris/altoclef/tasks/resources/KillEndermanTask.java b/src/main/java/adris/altoclef/tasks/resources/KillEndermanTask.java index edbcc1b50..a1766e740 100644 --- a/src/main/java/adris/altoclef/tasks/resources/KillEndermanTask.java +++ b/src/main/java/adris/altoclef/tasks/resources/KillEndermanTask.java @@ -7,9 +7,12 @@ import adris.altoclef.tasksystem.Task; import adris.altoclef.util.ItemTarget; import adris.altoclef.util.time.TimerGame; +import net.minecraft.entity.Entity; import net.minecraft.entity.mob.EndermanEntity; import net.minecraft.item.Items; +import java.util.Optional; + public class KillEndermanTask extends ResourceTask { private final int _count; @@ -39,14 +42,14 @@ protected Task onResourceTick(AltoClef mod) { } // Kill the angry one - for (EndermanEntity entity : mod.getEntityTracker().getTrackedEntities(EndermanEntity.class)) { + Optional enderman = mod.getEntityTracker().getClosestEntity(EndermanEntity.class); + if (enderman.isPresent()) { + EndermanEntity endermanEntity = (EndermanEntity) enderman.get(); final int TOO_FAR_AWAY = 256; - - if (entity.isAngry() && entity.getPos().isInRange(mod.getPlayer().getPos(), TOO_FAR_AWAY)) { - return new KillEntityTask(entity); + if (endermanEntity.isAngry() && endermanEntity.getPos().isInRange(mod.getPlayer().getPos(), TOO_FAR_AWAY)) { + return new KillEntityTask(endermanEntity); } } - // Attack the closest one return new KillEntitiesTask(EndermanEntity.class); } diff --git a/src/main/java/adris/altoclef/tasks/speedrun/BeatMinecraft2Task.java b/src/main/java/adris/altoclef/tasks/speedrun/BeatMinecraft2Task.java index b70ecf66e..13d1679cc 100644 --- a/src/main/java/adris/altoclef/tasks/speedrun/BeatMinecraft2Task.java +++ b/src/main/java/adris/altoclef/tasks/speedrun/BeatMinecraft2Task.java @@ -31,13 +31,13 @@ import net.minecraft.block.EndPortalFrameBlock; import net.minecraft.client.MinecraftClient; import net.minecraft.client.gui.screen.CreditsScreen; -import net.minecraft.enchantment.BindingCurseEnchantment; import net.minecraft.entity.ItemEntity; import net.minecraft.entity.mob.EndermanEntity; import net.minecraft.entity.mob.SilverfishEntity; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.Items; +import net.minecraft.registry.tag.EnchantmentTags; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; import net.minecraft.util.math.Vec3i; @@ -83,7 +83,7 @@ public class BeatMinecraft2Task extends Task { private static final double END_PORTAL_BED_SPAWN_RANGE = 8; // We don't want curse of binding private static final Predicate _noCurseOfBinding = stack -> { - if (stack.getEnchantments().getEnchantments() instanceof BindingCurseEnchantment) { + if (stack.getEnchantments().getEnchantments().contains(EnchantmentTags.CURSE)) { return false; } return true; diff --git a/src/main/java/adris/altoclef/tasks/speedrun/DragonBreathTracker.java b/src/main/java/adris/altoclef/tasks/speedrun/DragonBreathTracker.java index cc8af2fdd..67fce56ab 100644 --- a/src/main/java/adris/altoclef/tasks/speedrun/DragonBreathTracker.java +++ b/src/main/java/adris/altoclef/tasks/speedrun/DragonBreathTracker.java @@ -8,17 +8,20 @@ import baritone.api.pathing.goals.Goal; import baritone.api.pathing.goals.GoalRunAway; import net.minecraft.entity.AreaEffectCloudEntity; +import net.minecraft.entity.Entity; import net.minecraft.util.math.BlockPos; import java.util.HashSet; +import java.util.Optional; public class DragonBreathTracker { private final HashSet _breathBlocks = new HashSet<>(); public void updateBreath(AltoClef mod) { _breathBlocks.clear(); - for (AreaEffectCloudEntity cloud : mod.getEntityTracker().getTrackedEntities(AreaEffectCloudEntity.class)) { - for (BlockPos bad : WorldHelper.getBlocksTouchingBox(mod, cloud.getBoundingBox())) { + Optional cloud = mod.getEntityTracker().getClosestEntity(AreaEffectCloudEntity.class); + if (cloud.isPresent()) { + for (BlockPos bad : WorldHelper.getBlocksTouchingBox(mod, cloud.get().getBoundingBox())) { _breathBlocks.add(bad); } } diff --git a/src/main/java/adris/altoclef/tasks/speedrun/KillEnderDragonTask.java b/src/main/java/adris/altoclef/tasks/speedrun/KillEnderDragonTask.java index 0f4c6459d..5081eb68a 100644 --- a/src/main/java/adris/altoclef/tasks/speedrun/KillEnderDragonTask.java +++ b/src/main/java/adris/altoclef/tasks/speedrun/KillEnderDragonTask.java @@ -35,10 +35,7 @@ import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; +import java.util.*; /** * Here we go @@ -269,93 +266,92 @@ protected Task onTick(AltoClef mod) { setDebugState("No dragon found."); return null; } - List dragons = mod.getEntityTracker().getTrackedEntities(EnderDragonEntity.class); - if (!dragons.isEmpty()) { - for (EnderDragonEntity dragon : dragons) { - Phase dragonPhase = dragon.getPhaseManager().getCurrent(); - //Debug.logInternal("PHASE: " + dragonPhase); - boolean perchingOrGettingReady = dragonPhase.getType() == PhaseType.LANDING || dragonPhase.isSittingOrHovering(); - switch (_mode) { - case RAILING -> { - if (!perchingOrGettingReady) { - Debug.logMessage("Dragon no longer perching."); - mod.getClientBaritone().getCustomGoalProcess().onLostControl(); - _mode = Mode.WAITING_FOR_PERCH; - break; - } - //DamageSource.DRAGON_BREATH - Entity head = dragon.head; - // Go for the head - if (head.isInRange(mod.getPlayer(), 7.5) && dragon.ticksSinceDeath <= 1) { - // Equip weapon - AbstractKillEntityTask.equipWeapon(mod); - // Look torwards da dragon - Vec3d targetLookPos = head.getPos().add(0, 3, 0); - Rotation targetRotation = RotationUtils.calcRotationFromVec3d(mod.getClientBaritone().getPlayerContext().playerHead(), targetLookPos, mod.getClientBaritone().getPlayerContext().playerRotations()); - mod.getClientBaritone().getLookBehavior().updateTarget(targetRotation, true); - // Also look towards da dragon - MinecraftClient.getInstance().options.getAutoJump().setValue(false); - mod.getClientBaritone().getInputOverrideHandler().setInputForceState(Input.MOVE_FORWARD, true); - hit(mod); - } else { - stopHitting(mod); - } - if (!mod.getClientBaritone().getCustomGoalProcess().isActive()) { - // Set goal to closest block within the pillar that's by the head. - if (_exitPortalTop != null) { - int bottomYDelta = -3; - BlockPos closest = null; - double closestDist = Double.POSITIVE_INFINITY; - for (int dx = -2; dx <= 2; ++dx) { - for (int dz = -2; dz <= 2; ++dz) { - // We have sort of a rounded circle here. - if (Math.abs(dx) == 2 && Math.abs(dz) == 2) continue; - BlockPos toCheck = _exitPortalTop.add(dx, bottomYDelta, dz); - double distSq = toCheck.getSquaredDistance(head.getPos()); - if (distSq < closestDist) { - closest = toCheck; - closestDist = distSq; - } + Optional dragon = mod.getEntityTracker().getClosestEntity(EnderDragonEntity.class); + if (dragon.isPresent()) { + EnderDragonEntity dragonEntity = (EnderDragonEntity) dragon.get(); + Phase dragonPhase = dragonEntity.getPhaseManager().getCurrent(); + //Debug.logInternal("PHASE: " + dragonPhase); + boolean perchingOrGettingReady = dragonPhase.getType() == PhaseType.LANDING || dragonPhase.isSittingOrHovering(); + switch (_mode) { + case RAILING -> { + if (!perchingOrGettingReady) { + Debug.logMessage("Dragon no longer perching."); + mod.getClientBaritone().getCustomGoalProcess().onLostControl(); + _mode = Mode.WAITING_FOR_PERCH; + break; + } + //DamageSource.DRAGON_BREATH + Entity head = dragonEntity.head; + // Go for the head + if (head.isInRange(mod.getPlayer(), 7.5) && dragonEntity.ticksSinceDeath <= 1) { + // Equip weapon + AbstractKillEntityTask.equipWeapon(mod); + // Look torwards da dragon + Vec3d targetLookPos = head.getPos().add(0, 3, 0); + Rotation targetRotation = RotationUtils.calcRotationFromVec3d(mod.getClientBaritone().getPlayerContext().playerHead(), targetLookPos, mod.getClientBaritone().getPlayerContext().playerRotations()); + mod.getClientBaritone().getLookBehavior().updateTarget(targetRotation, true); + // Also look towards da dragon + MinecraftClient.getInstance().options.getAutoJump().setValue(false); + mod.getClientBaritone().getInputOverrideHandler().setInputForceState(Input.MOVE_FORWARD, true); + hit(mod); + } else { + stopHitting(mod); + } + if (!mod.getClientBaritone().getCustomGoalProcess().isActive()) { + // Set goal to closest block within the pillar that's by the head. + if (_exitPortalTop != null) { + int bottomYDelta = -3; + BlockPos closest = null; + double closestDist = Double.POSITIVE_INFINITY; + for (int dx = -2; dx <= 2; ++dx) { + for (int dz = -2; dz <= 2; ++dz) { + // We have sort of a rounded circle here. + if (Math.abs(dx) == 2 && Math.abs(dz) == 2) continue; + BlockPos toCheck = _exitPortalTop.add(dx, bottomYDelta, dz); + double distSq = toCheck.getSquaredDistance(head.getPos()); + if (distSq < closestDist) { + closest = toCheck; + closestDist = distSq; } } - if (closest != null) { - mod.getClientBaritone().getCustomGoalProcess().setGoalAndPath( - new GoalGetToBlock(closest) - ); - } + } + if (closest != null) { + mod.getClientBaritone().getCustomGoalProcess().setGoalAndPath( + new GoalGetToBlock(closest) + ); } } - setDebugState("Railing on dragon"); } - case WAITING_FOR_PERCH -> { - stopHitting(mod); - if (perchingOrGettingReady) { - // We're perching!! - mod.getClientBaritone().getCustomGoalProcess().onLostControl(); - Debug.logMessage("Dragon perching detected. Dabar duosiu į snuki."); - _mode = Mode.RAILING; - break; - } - // Run around aimlessly, dodging dragon fire - if (_randomWanderPos != null && WorldHelper.inRangeXZ(mod.getPlayer(), _randomWanderPos, 2)) { - _randomWanderPos = null; - } - if (_randomWanderPos != null && _randomWanderChangeTimeout.elapsed()) { - _randomWanderPos = null; - Debug.logMessage("Reset wander pos after timeout, oof"); - } - if (_randomWanderPos == null) { - _randomWanderPos = getRandomWanderPos(mod); - _randomWanderChangeTimeout.reset(); - mod.getClientBaritone().getCustomGoalProcess().onLostControl(); - } - if (!mod.getClientBaritone().getCustomGoalProcess().isActive()) { - mod.getClientBaritone().getCustomGoalProcess().setGoalAndPath( - new GoalGetToBlock(_randomWanderPos) - ); - } - setDebugState("Waiting for perch"); + setDebugState("Railing on dragon"); + } + case WAITING_FOR_PERCH -> { + stopHitting(mod); + if (perchingOrGettingReady) { + // We're perching!! + mod.getClientBaritone().getCustomGoalProcess().onLostControl(); + Debug.logMessage("Dragon perching detected. Dabar duosiu į snuki."); + _mode = Mode.RAILING; + break; + } + // Run around aimlessly, dodging dragon fire + if (_randomWanderPos != null && WorldHelper.inRangeXZ(mod.getPlayer(), _randomWanderPos, 2)) { + _randomWanderPos = null; + } + if (_randomWanderPos != null && _randomWanderChangeTimeout.elapsed()) { + _randomWanderPos = null; + Debug.logMessage("Reset wander pos after timeout, oof"); + } + if (_randomWanderPos == null) { + _randomWanderPos = getRandomWanderPos(mod); + _randomWanderChangeTimeout.reset(); + mod.getClientBaritone().getCustomGoalProcess().onLostControl(); + } + if (!mod.getClientBaritone().getCustomGoalProcess().isActive()) { + mod.getClientBaritone().getCustomGoalProcess().setGoalAndPath( + new GoalGetToBlock(_randomWanderPos) + ); } + setDebugState("Waiting for perch"); } } } diff --git a/src/main/java/adris/altoclef/tasks/speedrun/KillEnderDragonWithBedsTask.java b/src/main/java/adris/altoclef/tasks/speedrun/KillEnderDragonWithBedsTask.java index d90729e58..694f5c13c 100644 --- a/src/main/java/adris/altoclef/tasks/speedrun/KillEnderDragonWithBedsTask.java +++ b/src/main/java/adris/altoclef/tasks/speedrun/KillEnderDragonWithBedsTask.java @@ -11,6 +11,7 @@ import adris.altoclef.util.helpers.WorldHelper; import baritone.api.utils.input.Input; import net.minecraft.block.Blocks; +import net.minecraft.entity.Entity; import net.minecraft.entity.boss.dragon.EnderDragonEntity; import net.minecraft.entity.boss.dragon.phase.Phase; import net.minecraft.entity.boss.dragon.phase.PhaseType; @@ -18,7 +19,7 @@ import net.minecraft.util.math.Direction; import net.minecraft.util.math.Vec3d; -import java.util.List; +import java.util.Optional; public class KillEnderDragonWithBedsTask extends Task { private final Task _whenNotPerchingTask; @@ -61,8 +62,8 @@ Get in position (XZ) Else: // Perform "Default Wander" mode and avoid dragon breath. */ - List dragons = mod.getEntityTracker().getTrackedEntities(EnderDragonEntity.class); - if (dragons.isEmpty() && !isDragonPresent) { + Optional dragon = mod.getEntityTracker().getClosestEntity(EnderDragonEntity.class); + if (dragon.isEmpty() && !isDragonPresent) { setDebugState("Waiting for dragon to spawn."); return null; } @@ -98,85 +99,84 @@ Get in position (XZ) } isDragonDead = true; } - if (!dragons.isEmpty()) { - for (EnderDragonEntity dragon : dragons) { - Phase dragonPhase = dragon.getPhaseManager().getCurrent(); - - boolean perching = dragonPhase.getType() == PhaseType.LANDING || dragonPhase.isSittingOrHovering() || dragonPhase.getType() == PhaseType.LANDING_APPROACH; - if (dragon.getY() < _endPortalTop.getY() + 2) { - // Dragon is already perched. - perching = false; - } - ((IDragonWaiter) _whenNotPerchingTask).setPerchState(perching); - // When the dragon is not perching... - if (_whenNotPerchingTask.isActive() && !_whenNotPerchingTask.isFinished(mod)) { - setDebugState("Dragon not perching, performing special behavior..."); - return _whenNotPerchingTask; + if (dragon.isPresent()) { + EnderDragonEntity dragonEntity = (EnderDragonEntity) dragon.get(); + Phase dragonPhase = dragonEntity.getPhaseManager().getCurrent(); + + boolean perching = dragonPhase.getType() == PhaseType.LANDING || dragonPhase.isSittingOrHovering() || dragonPhase.getType() == PhaseType.LANDING_APPROACH; + if (dragonEntity.getY() < _endPortalTop.getY() + 2) { + // Dragon is already perched. + perching = false; + } + ((IDragonWaiter) _whenNotPerchingTask).setPerchState(perching); + // When the dragon is not perching... + if (_whenNotPerchingTask.isActive() && !_whenNotPerchingTask.isFinished(mod)) { + setDebugState("Dragon not perching, performing special behavior..."); + return _whenNotPerchingTask; + } + if (perching) { + mod.getFoodChain().shouldStop(true); + BlockPos targetStandPosition = _endPortalTop.add(-1, -1, 0); + BlockPos playerPosition = mod.getPlayer().getBlockPos(); + // If we're not positioned (above is OK), go there and make sure we're at the right height. + if (_positionTask != null && _positionTask.isActive() && !_positionTask.isFinished(mod)) { + setDebugState("Going to position for bed cycle..."); + return _positionTask; } - if (perching) { - mod.getFoodChain().shouldStop(true); - BlockPos targetStandPosition = _endPortalTop.add(-1, -1, 0); - BlockPos playerPosition = mod.getPlayer().getBlockPos(); - // If we're not positioned (above is OK), go there and make sure we're at the right height. - if (_positionTask != null && _positionTask.isActive() && !_positionTask.isFinished(mod)) { - setDebugState("Going to position for bed cycle..."); - return _positionTask; - } - if ((!WorldHelper.inRangeXZ(WorldHelper.toVec3d(targetStandPosition), mod.getPlayer().getPos(), 0.50)) + if ((!WorldHelper.inRangeXZ(WorldHelper.toVec3d(targetStandPosition), mod.getPlayer().getPos(), 0.50)) // && mod.getPlayer().getVelocity().getX() == 0 && mod.getPlayer().getVelocity().getY() == 0 && mod.getPlayer().getVelocity().getZ() == 0 - ) { - _positionTask = new GetToBlockTask(targetStandPosition); - Debug.logMessage("Going to position for bed cycle..."); - setDebugState("Moving to target stand position"); - return _positionTask; - } - // We're positioned. Perform bed strats! - BlockPos bedTargetPosition = _endPortalTop.up(); - boolean bedPlaced = mod.getBlockTracker().blockIsValid(bedTargetPosition, ItemHelper.itemsToBlocks(ItemHelper.BED)); - if (!bedPlaced) { - setDebugState("Placing bed"); - // If no bed, place bed. - // Fire messes up our "reach" so we just assume we're good when we're above a height. - boolean canPlace = LookHelper.getCameraPos(mod).y > bedTargetPosition.getY(); - //Optional placeReach = LookHelper.getReach(bedTargetPosition.down(), Direction.UP); - if (canPlace) { - // Look at and place! - if (mod.getSlotHandler().forceEquipItem(ItemHelper.BED, true)) { - LookHelper.lookAt(mod, bedTargetPosition.down(), Direction.UP, true); - //mod.getClientBaritone().getLookBehavior().updateTarget(placeReach.get(), true); - //if (mod.getClientBaritone().getPlayerContext().isLookingAt(bedTargetPosition.down())) { - // There could be fire so eh place right away - mod.getInputControls().tryPress(Input.CLICK_RIGHT); - //} - } - } else { - if (mod.getPlayer().isOnGround()) { - // Jump - mod.getInputControls().tryPress(Input.JUMP); - } + ) { + _positionTask = new GetToBlockTask(targetStandPosition); + Debug.logMessage("Going to position for bed cycle..."); + setDebugState("Moving to target stand position"); + return _positionTask; + } + // We're positioned. Perform bed strats! + BlockPos bedTargetPosition = _endPortalTop.up(); + boolean bedPlaced = mod.getBlockTracker().blockIsValid(bedTargetPosition, ItemHelper.itemsToBlocks(ItemHelper.BED)); + if (!bedPlaced) { + setDebugState("Placing bed"); + // If no bed, place bed. + // Fire messes up our "reach" so we just assume we're good when we're above a height. + boolean canPlace = LookHelper.getCameraPos(mod).y > bedTargetPosition.getY(); + //Optional placeReach = LookHelper.getReach(bedTargetPosition.down(), Direction.UP); + if (canPlace) { + // Look at and place! + if (mod.getSlotHandler().forceEquipItem(ItemHelper.BED, true)) { + LookHelper.lookAt(mod, bedTargetPosition.down(), Direction.UP, true); + //mod.getClientBaritone().getLookBehavior().updateTarget(placeReach.get(), true); + //if (mod.getClientBaritone().getPlayerContext().isLookingAt(bedTargetPosition.down())) { + // There could be fire so eh place right away + mod.getInputControls().tryPress(Input.CLICK_RIGHT); + //} } } else { - setDebugState("Wait for it..."); - // Make sure we're standing on the ground so we don't blow ourselves up lmfao - if (!mod.getPlayer().isOnGround()) { - // Wait to fall - return null; - } - // Wait for dragon head to be close enough to the bed's head... - BlockPos bedfoot = WorldHelper.getBedFoot(mod, bedTargetPosition); - assert bedfoot != null; - Vec3d headPos = dragon.head.getBoundingBox().getCenter(); // dragon.head.getPos(); - double dist = headPos.distanceTo(WorldHelper.toVec3d(bedfoot)); - Debug.logMessage("Dist: " + dist + " Health: " + dragon.getHealth()); - - if (dist < BeatMinecraft2Task.getConfig().dragonHeadCloseEnoughClickBedRange) { - // Interact with the bed. - return new InteractWithBlockTask(bedTargetPosition); + if (mod.getPlayer().isOnGround()) { + // Jump + mod.getInputControls().tryPress(Input.JUMP); } - // Wait for it... } - return null; + } else { + setDebugState("Wait for it..."); + // Make sure we're standing on the ground so we don't blow ourselves up lmfao + if (!mod.getPlayer().isOnGround()) { + // Wait to fall + return null; + } + // Wait for dragon head to be close enough to the bed's head... + BlockPos bedfoot = WorldHelper.getBedFoot(mod, bedTargetPosition); + assert bedfoot != null; + Vec3d headPos = dragonEntity.head.getBoundingBox().getCenter(); // dragon.head.getPos(); + double dist = headPos.distanceTo(WorldHelper.toVec3d(bedfoot)); + Debug.logMessage("Dist: " + dist + " Health: " + dragonEntity.getHealth()); + + if (dist < BeatMinecraft2Task.getConfig().dragonHeadCloseEnoughClickBedRange) { + // Interact with the bed. + return new InteractWithBlockTask(bedTargetPosition); + } + // Wait for it... } + return null; } } mod.getFoodChain().shouldStop(false); diff --git a/src/main/java/adris/altoclef/tasks/speedrun/MarvionBeatMinecraftTask.java b/src/main/java/adris/altoclef/tasks/speedrun/MarvionBeatMinecraftTask.java index ffe503142..3e2704cde 100644 --- a/src/main/java/adris/altoclef/tasks/speedrun/MarvionBeatMinecraftTask.java +++ b/src/main/java/adris/altoclef/tasks/speedrun/MarvionBeatMinecraftTask.java @@ -6,9 +6,7 @@ import adris.altoclef.tasks.DoToClosestBlockTask; import adris.altoclef.tasks.InteractWithBlockTask; import adris.altoclef.tasks.construction.DestroyBlockTask; -import adris.altoclef.tasks.container.DoStuffInContainerTask; -import adris.altoclef.tasks.container.LootContainerTask; -import adris.altoclef.tasks.container.SmeltInSmokerTask; +import adris.altoclef.tasks.container.*; import adris.altoclef.tasks.misc.EquipArmorTask; import adris.altoclef.tasks.misc.LootDesertTempleTask; import adris.altoclef.tasks.misc.PlaceBedAndSetSpawnTask; @@ -29,15 +27,17 @@ import net.minecraft.block.BlockState; import net.minecraft.block.Blocks; import net.minecraft.block.EndPortalFrameBlock; -import net.minecraft.client.MinecraftClient; import net.minecraft.client.gui.screen.CreditsScreen; -import net.minecraft.enchantment.BindingCurseEnchantment; import net.minecraft.entity.Entity; import net.minecraft.entity.ItemEntity; import net.minecraft.entity.LivingEntity; -import net.minecraft.entity.mob.*; +import net.minecraft.entity.mob.EndermanEntity; +import net.minecraft.entity.mob.PillagerEntity; +import net.minecraft.entity.mob.SilverfishEntity; +import net.minecraft.entity.mob.WitchEntity; import net.minecraft.entity.passive.PigEntity; import net.minecraft.item.*; +import net.minecraft.registry.tag.EnchantmentTags; import net.minecraft.screen.slot.SlotActionType; import net.minecraft.util.math.BlockPos; import net.minecraft.world.biome.BiomeKeys; @@ -45,7 +45,6 @@ import java.util.*; import java.util.function.Predicate; -import java.util.stream.Stream; import static net.minecraft.client.MinecraftClient.getInstance; @@ -97,14 +96,13 @@ public class MarvionBeatMinecraftTask extends Task { ); private static final ItemTarget[] IRON_GEAR = combine( toItemTargets(Items.IRON_SWORD, 2), + toItemTargets(Items.IRON_PICKAXE, 2), toItemTargets(Items.STONE_SHOVEL), toItemTargets(Items.STONE_AXE), - toItemTargets(Items.DIAMOND_PICKAXE), toItemTargets(Items.SHIELD) ); private static final ItemTarget[] IRON_GEAR_MIN = combine( - toItemTargets(Items.IRON_SWORD, 2), - toItemTargets(Items.DIAMOND_PICKAXE), + toItemTargets(Items.IRON_SWORD), toItemTargets(Items.SHIELD) ); private static final int END_PORTAL_FRAME_COUNT = 12; @@ -114,7 +112,7 @@ public class MarvionBeatMinecraftTask extends Task { private static final int TWISTING_VINES_COUNT_MIN = 14; // We don't want curse of binding private static final Predicate _noCurseOfBinding = stack -> { - if (stack.getEnchantments().getEnchantments() instanceof BindingCurseEnchantment) { + if (stack.getEnchantments().getEnchantments().contains(EnchantmentTags.CURSE)) { return false; } return true; @@ -144,7 +142,7 @@ public class MarvionBeatMinecraftTask extends Task { boolean _weHaveEyes; private static boolean dragonIsDead; private BlockPos _endPortalCenterLocation; - private boolean _isEquippingDiamondArmor; + private boolean isEquippingDiamondArmor; private boolean _ranStrongholdLocator; private boolean _endPortalOpened; private BlockPos _bedSpawnLocation; @@ -234,11 +232,18 @@ private static List getFrameBlocks(BlockPos endPortalCenter) { * @return an array of ItemTarget objects */ private static ItemTarget[] toItemTargets(Item... items) { - return Arrays.stream(items) - .map(ItemTarget::new) - .toArray(ItemTarget[]::new); + // Create a new array of ItemTarget objects with the same length as the input array + ItemTarget[] itemTargets = new ItemTarget[items.length]; + // Iterate over each item in the input array + for (int i = 0; i < items.length; i++) { + // Create a new ItemTarget object for the current item + itemTargets[i] = new ItemTarget(items[i]); + } + // Return the array of ItemTarget objects + return itemTargets; } + /** * Converts an Item and count into an array of ItemTargets. * @@ -538,27 +543,33 @@ protected String toDebugString() { /** * Checks if the end portal is found at the specified center position. * - * @param mod The AltoClef mod instance + * @param mod The AltoClef mod instance * @param endPortalCenter The center position of the end portal * @return true if the end portal is found, false otherwise */ private boolean endPortalFound(AltoClef mod, BlockPos endPortalCenter) { + // If the end portal center is null, return false if (endPortalCenter == null) { return false; } - + // If the end portal is already opened, return true if (endPortalOpened(mod, endPortalCenter)) { return true; } - // Get the frame blocks of the end portal List frameBlocks = getFrameBlocks(endPortalCenter); - // Check if any of the frame blocks is a valid end portal frame block - return frameBlocks.stream() - .anyMatch(frame -> mod.getBlockTracker().blockIsValid(frame, Blocks.END_PORTAL_FRAME)); + for (BlockPos frame : frameBlocks) { + // If the block is a valid end portal frame block, return true + if (mod.getBlockTracker().blockIsValid(frame, Blocks.END_PORTAL_FRAME)) { + return true; + } + } + // If none of the frame blocks are valid, return false + return false; } + /** * Check if the end portal is already opened and the center position is provided * @@ -821,8 +832,8 @@ private void avoidBreakingBed(AltoClef mod) { @Override protected Task onTick(AltoClef mod) { - if (mod.getPlayer().getMainHandStack().getItem() instanceof EnderEyeItem && - !openingEndPortal) { + if (mod.getPlayer().getMainHandStack().getItem() instanceof EnderEyeItem && !openingEndPortal + && StorageHelper.getItemStackInCursorSlot().isEmpty()) { List itemStacks = mod.getItemStorage().getItemStacksPlayerInventory(true); for (ItemStack itemStack : itemStacks) { Item item = itemStack.getItem(); @@ -834,188 +845,111 @@ protected Task onTick(AltoClef mod) { boolean eyeGearSatisfied = StorageHelper.isArmorEquippedAll(mod, COLLECT_EYE_ARMOR); boolean ironGearSatisfied = StorageHelper.isArmorEquippedAll(mod, COLLECT_IRON_ARMOR); if (mod.getItemStorage().hasItem(Items.DIAMOND_PICKAXE)) { - mod.getBehaviour().setBlockBreakAdditionalPenalty(0); + if (mod.getClientBaritoneSettings().blockBreakAdditionalPenalty.value != 0) { + mod.getBehaviour().setBlockBreakAdditionalPenalty(0); + } } else { - mod.getBehaviour().setBlockBreakAdditionalPenalty(mod.getClientBaritoneSettings().blockBreakAdditionalPenalty.defaultValue); + if (mod.getClientBaritoneSettings().blockBreakAdditionalPenalty.value != mod.getClientBaritoneSettings().blockBreakAdditionalPenalty.defaultValue) { + mod.getBehaviour().setBlockBreakAdditionalPenalty(mod.getClientBaritoneSettings().blockBreakAdditionalPenalty.defaultValue); + } } Predicate isCraftingTableTask = task -> { - if (task instanceof DoStuffInContainerTask cont) { - return cont.getContainerTarget().matches(Items.CRAFTING_TABLE); + if (task instanceof CraftInTableTask || task instanceof PickupFromContainerTask) { + return true; } return false; }; - List craftingTables = mod.getBlockTracker().getKnownLocations(Blocks.CRAFTING_TABLE); - if (!craftingTables.isEmpty()) { - for (BlockPos craftingTable : craftingTables) { - if (mod.getItemStorage().hasItem(Items.CRAFTING_TABLE) && !thisOrChildSatisfies(isCraftingTableTask)) { - if (!mod.getBlockTracker().unreachable(craftingTable)) { - Debug.logMessage("Blacklisting extra crafting table."); - mod.getBlockTracker().requestBlockUnreachable(craftingTable, 0); - } - } - if (!mod.getBlockTracker().unreachable(craftingTable)) { - BlockState craftingTablePosUp = mod.getWorld().getBlockState(craftingTable.up(2)); - if (mod.getEntityTracker().entityFound(WitchEntity.class)) { - Optional witch = mod.getEntityTracker().getClosestEntity(WitchEntity.class); - if (witch.isPresent()) { - if (craftingTable.isWithinDistance(witch.get().getPos(), 15)) { - Debug.logMessage("Blacklisting witch crafting table."); - mod.getBlockTracker().requestBlockUnreachable(craftingTable, 0); - } - } - } - if (craftingTablePosUp.getBlock() == Blocks.WHITE_WOOL) { - Debug.logMessage("Blacklisting pillage crafting table."); - mod.getBlockTracker().requestBlockUnreachable(craftingTable, 0); - } - } + Predicate isSmokerTask = task -> { + if (task instanceof SmeltInSmokerTask || task instanceof PickupFromContainerTask) { + return true; } - } - List smokers = mod.getBlockTracker().getKnownLocations(Blocks.SMOKER); - if (!smokers.isEmpty()) { - for (BlockPos smoker : smokers) { - if (mod.getItemStorage().hasItem(Items.SMOKER) && _smeltTask == null && _foodTask == null) { - if (!mod.getBlockTracker().unreachable(smoker)) { - Debug.logMessage("Blacklisting extra smoker."); - mod.getBlockTracker().requestBlockUnreachable(smoker, 0); - } - } + return false; + }; + Predicate isFurnaceTask = task -> { + if (task instanceof SmeltInFurnaceTask || task instanceof PickupFromContainerTask || task instanceof CraftInTableTask) { + return true; } - } - List furnaces = mod.getBlockTracker().getKnownLocations(Blocks.FURNACE); - if (!furnaces.isEmpty()) { - for (BlockPos furnace : furnaces) { - if ((mod.getItemStorage().hasItem(Items.FURNACE) || mod.getItemStorage().hasItem(Items.BLAST_FURNACE)) && - _starterGearTask == null && _shieldTask == null && _ironGearTask == null && _gearTask == null && - !_goToNetherTask.isActive() && !_ranStrongholdLocator) { - if (!mod.getBlockTracker().unreachable(furnace)) { - Debug.logMessage("Blacklisting extra furnace."); - mod.getBlockTracker().requestBlockUnreachable(furnace, 0); - } - } + return false; + }; + Predicate isBlastFurnaceTask = task -> { + if (task instanceof SmeltInBlastFurnaceTask || task instanceof PickupFromContainerTask) { + return true; } - } - List blastFurnaces = mod.getBlockTracker().getKnownLocations(Blocks.BLAST_FURNACE); - if (!blastFurnaces.isEmpty()) { - for (BlockPos blastFurnace : blastFurnaces) { - if (mod.getItemStorage().hasItem(Items.BLAST_FURNACE) && _starterGearTask == null && _shieldTask == null && - _ironGearTask == null && _gearTask == null && !_goToNetherTask.isActive() && !_ranStrongholdLocator) { - if (!mod.getBlockTracker().unreachable(blastFurnace)) { - Debug.logMessage("Blacklisting extra blast furnace."); - mod.getBlockTracker().requestBlockUnreachable(blastFurnace, 0); - } + return false; + }; + if (mod.getBlockTracker().isTracking(Blocks.CRAFTING_TABLE)) { + Optional craftingTables = mod.getBlockTracker().getNearestTracking(Blocks.CRAFTING_TABLE); + if (craftingTables.isPresent() && mod.getItemStorage().hasItem(Items.CRAFTING_TABLE) + && !thisOrChildSatisfies(isCraftingTableTask) && !mod.getBlockTracker().unreachable(craftingTables.get())) { + Debug.logMessage("Blacklisting extra crafting table."); + mod.getBlockTracker().requestBlockUnreachable(craftingTables.get(), 0); + BlockState craftingTablePosUp = mod.getWorld().getBlockState(craftingTables.get().up(2)); + Optional witch = mod.getEntityTracker().getClosestEntity(WitchEntity.class); + if (witch.isPresent() && craftingTables.get().isWithinDistance(witch.get().getPos(), 15)) { + Debug.logMessage("Blacklisting witch crafting table."); + mod.getBlockTracker().requestBlockUnreachable(craftingTables.get(), 0); + } + if (craftingTablePosUp.getBlock() == Blocks.WHITE_WOOL) { + Debug.logMessage("Blacklisting pillage crafting table."); + mod.getBlockTracker().requestBlockUnreachable(craftingTables.get(), 0); } } } - List logs = mod.getBlockTracker().getKnownLocations(ItemHelper.itemsToBlocks(ItemHelper.LOG)); - if (!logs.isEmpty()) { - for (BlockPos log : logs) { - Iterable entities = mod.getWorld().getEntities(); - for (Entity entity : entities) { - if (entity instanceof PillagerEntity) { - if (!mod.getBlockTracker().unreachable(log)) { - if (log.isWithinDistance(entity.getPos(), 40)) { - Debug.logMessage("Blacklisting pillage log."); - mod.getBlockTracker().requestBlockUnreachable(log, 0); - } - } - } - } - if (log.getY() < 62) { - if (!mod.getBlockTracker().unreachable(log)) { - if (!ironGearSatisfied && !eyeGearSatisfied) { - Debug.logMessage("Blacklisting dangerous log."); - mod.getBlockTracker().requestBlockUnreachable(log, 0); - } - } - } + if (mod.getBlockTracker().isTracking(Blocks.SMOKER)) { + Optional smokers = mod.getBlockTracker().getNearestTracking(Blocks.SMOKER); + if (smokers.isPresent() && mod.getItemStorage().hasItem(Items.SMOKER) + && !thisOrChildSatisfies(isSmokerTask) && !mod.getBlockTracker().unreachable(smokers.get())) { + Debug.logMessage("Blacklisting extra smoker."); + mod.getBlockTracker().requestBlockUnreachable(smokers.get(), 0); } } - if (mod.getBlockTracker().isTracking(Blocks.DEEPSLATE_COAL_ORE)) { - Optional deepslateCoalOre = mod.getBlockTracker().getNearestTracking(Blocks.DEEPSLATE_COAL_ORE); - if (deepslateCoalOre.isPresent()) { - Iterable entities = mod.getWorld().getEntities(); - for (Entity entity : entities) { - if (entity instanceof HostileEntity) { - if (!mod.getBlockTracker().unreachable(deepslateCoalOre.get())) { - if (mod.getPlayer().squaredDistanceTo(entity.getPos()) < 150 && - deepslateCoalOre.get().isWithinDistance(entity.getPos(), 30)) { - if (!ironGearSatisfied && !eyeGearSatisfied) { - Debug.logMessage("Blacklisting dangerous coal ore."); - mod.getBlockTracker().requestBlockUnreachable(deepslateCoalOre.get(), 0); - } - } - } - } - } + if (mod.getBlockTracker().isTracking(Blocks.FURNACE)) { + Optional furnaces = mod.getBlockTracker().getNearestTracking(Blocks.FURNACE); + if (furnaces.isPresent() && (mod.getItemStorage().hasItem(Items.FURNACE) || mod.getItemStorage().hasItem(Items.BLAST_FURNACE)) + && !thisOrChildSatisfies(isFurnaceTask) && !mod.getBlockTracker().unreachable(furnaces.get())) { + Debug.logMessage("Blacklisting extra furnace."); + mod.getBlockTracker().requestBlockUnreachable(furnaces.get(), 0); } } - if (mod.getBlockTracker().isTracking(Blocks.COAL_ORE)) { - Optional coalOrePos = mod.getBlockTracker().getNearestTracking(Blocks.COAL_ORE); - if (coalOrePos.isPresent()) { - Iterable entities = mod.getWorld().getEntities(); - for (Entity entity : entities) { - if (entity instanceof HostileEntity) { - if (!mod.getBlockTracker().unreachable(coalOrePos.get())) { - if (mod.getPlayer().squaredDistanceTo(entity.getPos()) < 150 && - coalOrePos.get().isWithinDistance(entity.getPos(), 30)) { - if (!ironGearSatisfied && !eyeGearSatisfied) { - Debug.logMessage("Blacklisting dangerous coal ore."); - mod.getBlockTracker().requestBlockUnreachable(coalOrePos.get(), 0); - } - } - } - } - } + if (mod.getBlockTracker().isTracking(Blocks.BLAST_FURNACE)) { + Optional blastFurnaces = mod.getBlockTracker().getNearestTracking(Blocks.BLAST_FURNACE); + if (blastFurnaces.isPresent() && mod.getItemStorage().hasItem(Items.BLAST_FURNACE) + && !thisOrChildSatisfies(isBlastFurnaceTask) && !mod.getBlockTracker().unreachable(blastFurnaces.get())) { + Debug.logMessage("Blacklisting extra blast furnace."); + mod.getBlockTracker().requestBlockUnreachable(blastFurnaces.get(), 0); } } - if (mod.getBlockTracker().isTracking(Blocks.DEEPSLATE_IRON_ORE)) { - Optional deepslateIronOrePos = mod.getBlockTracker().getNearestTracking(Blocks.DEEPSLATE_IRON_ORE); - if (deepslateIronOrePos.isPresent()) { - Iterable entities = mod.getWorld().getEntities(); - for (Entity entity : entities) { - if (entity instanceof HostileEntity) { - if (!mod.getBlockTracker().unreachable(deepslateIronOrePos.get())) { - if (mod.getPlayer().squaredDistanceTo(entity.getPos()) < 150 && - deepslateIronOrePos.get().isWithinDistance(entity.getPos(), 30)) { - if (!ironGearSatisfied && !eyeGearSatisfied) { - Debug.logMessage("Blacklisting dangerous iron ore."); - mod.getBlockTracker().requestBlockUnreachable(deepslateIronOrePos.get(), 0); - } - } - } - } + Block[] wools = ItemHelper.itemsToBlocks(ItemHelper.WOOL); + for (Block wool : wools) { + if (mod.getBlockTracker().isTracking(wool)) { + Optional woolsPos = mod.getBlockTracker().getNearestTracking(wool); + if (woolsPos.isPresent() && woolsPos.get().getY() < 62 && !mod.getBlockTracker().unreachable(woolsPos.get())) { + Debug.logMessage("Blacklisting dangerous wool."); + mod.getBlockTracker().requestBlockUnreachable(woolsPos.get(), 0); } } } - if (mod.getBlockTracker().isTracking(Blocks.IRON_ORE)) { - Optional ironOrePos = mod.getBlockTracker().getNearestTracking(Blocks.IRON_ORE); - if (ironOrePos.isPresent()) { - Iterable entities = mod.getWorld().getEntities(); - for (Entity entity : entities) { - if (entity instanceof HostileEntity) { - if (!mod.getBlockTracker().unreachable(ironOrePos.get())) { - if (mod.getPlayer().squaredDistanceTo(entity.getPos()) < 150 && - ironOrePos.get().isWithinDistance(entity.getPos(), 30)) { - if (!ironGearSatisfied && !eyeGearSatisfied) { - Debug.logMessage("Blacklisting dangerous iron ore."); - mod.getBlockTracker().requestBlockUnreachable(ironOrePos.get(), 0); - } - } + Block[] logBlocks = ItemHelper.itemsToBlocks(ItemHelper.LOG); + for (Block logBlock : logBlocks) { + if (mod.getBlockTracker().isTracking(logBlock)) { + Optional logs = mod.getBlockTracker().getNearestTracking(logBlock); + if (logs.isPresent()) { + Iterable entities = mod.getWorld().getEntities(); + for (Entity entity : entities) { + if (entity instanceof PillagerEntity && !mod.getBlockTracker().unreachable(logs.get()) + && logs.get().isWithinDistance(entity.getPos(), 40)) { + Debug.logMessage("Blacklisting pillage log."); + mod.getBlockTracker().requestBlockUnreachable(logs.get(), 0); } } + if (logs.get().getY() < 62 && !mod.getBlockTracker().unreachable(logs.get()) && !ironGearSatisfied + && !eyeGearSatisfied) { + Debug.logMessage("Blacklisting dangerous log."); + mod.getBlockTracker().requestBlockUnreachable(logs.get(), 0); + } } } } - if (!mod.getItemStorage().hasItem(Items.NETHERRACK) && - WorldHelper.getCurrentDimension() == Dimension.NETHER && !isGettingBlazeRods && - !isGettingEnderPearls) { - setDebugState("Getting netherrack."); - if (mod.getEntityTracker().itemDropped(Items.NETHERRACK)) { - return new PickupDroppedItemTask(Items.NETHERRACK, 1, true); - } - return TaskCatalogue.getItemTask(Items.NETHERRACK, 1); - } if (_locateStrongholdTask.isActive()) { if (WorldHelper.getCurrentDimension() == Dimension.OVERWORLD) { if (!mod.getClientBaritone().getExploreProcess().isActive()) { @@ -1073,128 +1007,110 @@ protected Task onTick(AltoClef mod) { } } } - List torches = mod.getItemStorage().getSlotsWithItemPlayerInventory(true, - Items.TORCH); - List beds = mod.getItemStorage().getSlotsWithItemPlayerInventory(true, - ItemHelper.BED); - List excessWaterBuckets = mod.getItemStorage().getSlotsWithItemPlayerInventory(true, - Items.WATER_BUCKET); - List excessLighters = mod.getItemStorage().getSlotsWithItemPlayerInventory(true, - Items.FLINT_AND_STEEL); - List sands = mod.getItemStorage().getSlotsWithItemPlayerInventory(true, - Items.SAND); - List gravels = mod.getItemStorage().getSlotsWithItemPlayerInventory(true, - Items.GRAVEL); - List furnaceSlots = mod.getItemStorage().getSlotsWithItemPlayerInventory(true, - Items.FURNACE); - List shears = mod.getItemStorage().getSlotsWithItemPlayerInventory(true, - Items.SHEARS); - if (!StorageHelper.isBigCraftingOpen() && !StorageHelper.isFurnaceOpen() && - !StorageHelper.isSmokerOpen() && !StorageHelper.isBlastFurnaceOpen()) { - if (!shears.isEmpty() && !needsBeds(mod)) { - for (Slot shear : shears) { - if (Slot.isCursor(shear)) { - if (!mod.getControllerExtras().isBreakingBlock()) { - LookHelper.randomOrientation(mod); - } - mod.getSlotHandler().clickSlot(Slot.UNDEFINED, 0, SlotActionType.PICKUP); - } else { - mod.getSlotHandler().clickSlot(shear, 0, SlotActionType.PICKUP); + List torches = mod.getItemStorage().getSlotsWithItemPlayerInventory(true, Items.TORCH); + if (!torches.isEmpty()) { + for (Slot torch : torches) { + if (Slot.isCursor(torch)) { + if (!mod.getControllerExtras().isBreakingBlock()) { + LookHelper.randomOrientation(mod); } + mod.getSlotHandler().clickSlot(Slot.UNDEFINED, 0, SlotActionType.PICKUP); + } else { + mod.getSlotHandler().clickSlot(torch, 0, SlotActionType.PICKUP); } } - if (!furnaceSlots.isEmpty() && mod.getItemStorage().hasItem(Items.SMOKER) && - mod.getItemStorage().hasItem(Items.BLAST_FURNACE) && mod.getModSettings().shouldUseBlastFurnace()) { - for (Slot furnace : furnaceSlots) { - if (Slot.isCursor(furnace)) { - if (!mod.getControllerExtras().isBreakingBlock()) { - LookHelper.randomOrientation(mod); - } - mod.getSlotHandler().clickSlot(Slot.UNDEFINED, 0, SlotActionType.PICKUP); - } else { - mod.getSlotHandler().clickSlot(furnace, 0, SlotActionType.PICKUP); + } + List beds = mod.getItemStorage().getSlotsWithItemPlayerInventory(true, ItemHelper.BED); + if (!beds.isEmpty() && mod.getItemStorage().getItemCount(ItemHelper.BED) > getTargetBeds(mod) && + !endPortalFound(mod, _endPortalCenterLocation) && WorldHelper.getCurrentDimension() != Dimension.END) { + for (Slot bed : beds) { + if (Slot.isCursor(bed)) { + if (!mod.getControllerExtras().isBreakingBlock()) { + LookHelper.randomOrientation(mod); } + mod.getSlotHandler().clickSlot(Slot.UNDEFINED, 0, SlotActionType.PICKUP); + } else { + mod.getSlotHandler().clickSlot(bed, 0, SlotActionType.PICKUP); } } - if (!sands.isEmpty()) { - for (Slot sand : sands) { - if (Slot.isCursor(sand)) { - if (!mod.getControllerExtras().isBreakingBlock()) { - LookHelper.randomOrientation(mod); - } - mod.getSlotHandler().clickSlot(Slot.UNDEFINED, 0, SlotActionType.PICKUP); - } else { - mod.getSlotHandler().clickSlot(sand, 0, SlotActionType.PICKUP); + } + List excessWaterBuckets = mod.getItemStorage().getSlotsWithItemPlayerInventory(true, Items.WATER_BUCKET); + if (!excessWaterBuckets.isEmpty() && mod.getItemStorage().getItemCount(Items.WATER_BUCKET) > 1) { + for (Slot excessWaterBucket : excessWaterBuckets) { + if (Slot.isCursor(excessWaterBucket)) { + if (!mod.getControllerExtras().isBreakingBlock()) { + LookHelper.randomOrientation(mod); } + mod.getSlotHandler().clickSlot(Slot.UNDEFINED, 0, SlotActionType.PICKUP); + } else { + mod.getSlotHandler().clickSlot(excessWaterBucket, 0, SlotActionType.PICKUP); } } - if (mod.getItemStorage().hasItem(Items.FLINT) || mod.getItemStorage().hasItem(Items.FLINT_AND_STEEL)) { - if (!gravels.isEmpty()) { - for (Slot gravel : gravels) { - if (Slot.isCursor(gravel)) { - if (!mod.getControllerExtras().isBreakingBlock()) { - LookHelper.randomOrientation(mod); - } - mod.getSlotHandler().clickSlot(Slot.UNDEFINED, 0, SlotActionType.PICKUP); - } else { - mod.getSlotHandler().clickSlot(gravel, 0, SlotActionType.PICKUP); - } + } + List excessLighters = mod.getItemStorage().getSlotsWithItemPlayerInventory(true, Items.FLINT_AND_STEEL); + if (!excessLighters.isEmpty() && mod.getItemStorage().getItemCount(Items.FLINT_AND_STEEL) > 1) { + for (Slot excessLighter : excessLighters) { + if (Slot.isCursor(excessLighter)) { + if (!mod.getControllerExtras().isBreakingBlock()) { + LookHelper.randomOrientation(mod); } + mod.getSlotHandler().clickSlot(Slot.UNDEFINED, 0, SlotActionType.PICKUP); + } else { + mod.getSlotHandler().clickSlot(excessLighter, 0, SlotActionType.PICKUP); } } - if (!torches.isEmpty()) { - for (Slot torch : torches) { - if (Slot.isCursor(torch)) { - if (!mod.getControllerExtras().isBreakingBlock()) { - LookHelper.randomOrientation(mod); - } - mod.getSlotHandler().clickSlot(Slot.UNDEFINED, 0, SlotActionType.PICKUP); - } else { - mod.getSlotHandler().clickSlot(torch, 0, SlotActionType.PICKUP); + } + List sands = mod.getItemStorage().getSlotsWithItemPlayerInventory(true, Items.SAND); + if (!sands.isEmpty()) { + for (Slot sand : sands) { + if (Slot.isCursor(sand)) { + if (!mod.getControllerExtras().isBreakingBlock()) { + LookHelper.randomOrientation(mod); } + mod.getSlotHandler().clickSlot(Slot.UNDEFINED, 0, SlotActionType.PICKUP); + } else { + mod.getSlotHandler().clickSlot(sand, 0, SlotActionType.PICKUP); } } - if (mod.getItemStorage().getItemCount(Items.WATER_BUCKET) > 1) { - if (!excessWaterBuckets.isEmpty()) { - for (Slot excessWaterBucket : excessWaterBuckets) { - if (Slot.isCursor(excessWaterBucket)) { - if (!mod.getControllerExtras().isBreakingBlock()) { - LookHelper.randomOrientation(mod); - } - mod.getSlotHandler().clickSlot(Slot.UNDEFINED, 0, SlotActionType.PICKUP); - } else { - mod.getSlotHandler().clickSlot(excessWaterBucket, 0, SlotActionType.PICKUP); - } + } + List gravels = mod.getItemStorage().getSlotsWithItemPlayerInventory(true, Items.GRAVEL); + if (!gravels.isEmpty() && (mod.getItemStorage().hasItem(Items.FLINT) || mod.getItemStorage().hasItem(Items.FLINT_AND_STEEL))) { + for (Slot gravel : gravels) { + if (Slot.isCursor(gravel)) { + if (!mod.getControllerExtras().isBreakingBlock()) { + LookHelper.randomOrientation(mod); } + mod.getSlotHandler().clickSlot(Slot.UNDEFINED, 0, SlotActionType.PICKUP); + } else { + mod.getSlotHandler().clickSlot(gravel, 0, SlotActionType.PICKUP); } } - if (mod.getItemStorage().getItemCount(Items.FLINT_AND_STEEL) > 1) { - if (!excessLighters.isEmpty()) { - for (Slot excessLighter : excessLighters) { - if (Slot.isCursor(excessLighter)) { - if (!mod.getControllerExtras().isBreakingBlock()) { - LookHelper.randomOrientation(mod); - } - mod.getSlotHandler().clickSlot(Slot.UNDEFINED, 0, SlotActionType.PICKUP); - } else { - mod.getSlotHandler().clickSlot(excessLighter, 0, SlotActionType.PICKUP); - } + } + List furnaceSlots = mod.getItemStorage().getSlotsWithItemPlayerInventory(true, Items.FURNACE); + if (!furnaceSlots.isEmpty() && mod.getItemStorage().hasItem(Items.SMOKER) && + mod.getItemStorage().hasItem(Items.BLAST_FURNACE) && mod.getModSettings().shouldUseBlastFurnace()) { + for (Slot furnaceSlot : furnaceSlots) { + if (Slot.isCursor(furnaceSlot)) { + if (!mod.getControllerExtras().isBreakingBlock()) { + LookHelper.randomOrientation(mod); } + mod.getSlotHandler().clickSlot(Slot.UNDEFINED, 0, SlotActionType.PICKUP); + } else { + mod.getSlotHandler().clickSlot(furnaceSlot, 0, SlotActionType.PICKUP); } } - if (mod.getItemStorage().getItemCount(ItemHelper.BED) > getTargetBeds(mod) && - !endPortalFound(mod, _endPortalCenterLocation) && WorldHelper.getCurrentDimension() != Dimension.END) { - if (!beds.isEmpty()) { - for (Slot bed : beds) { - if (Slot.isCursor(bed)) { - if (!mod.getControllerExtras().isBreakingBlock()) { - LookHelper.randomOrientation(mod); - } - mod.getSlotHandler().clickSlot(Slot.UNDEFINED, 0, SlotActionType.PICKUP); - } else { - mod.getSlotHandler().clickSlot(bed, 0, SlotActionType.PICKUP); - } + } + List shears = mod.getItemStorage().getSlotsWithItemPlayerInventory(true, Items.SHEARS); + if (!shears.isEmpty() && !StorageHelper.isBigCraftingOpen() && !StorageHelper.isFurnaceOpen() && + !StorageHelper.isSmokerOpen() && !StorageHelper.isBlastFurnaceOpen() && !needsBeds(mod)) { + for (Slot shear : shears) { + if (Slot.isCursor(shear)) { + if (!mod.getControllerExtras().isBreakingBlock()) { + LookHelper.randomOrientation(mod); } + mod.getSlotHandler().clickSlot(Slot.UNDEFINED, 0, SlotActionType.PICKUP); + } else { + mod.getSlotHandler().clickSlot(shear, 0, SlotActionType.PICKUP); } } } @@ -1306,76 +1222,113 @@ protected Task onTick(AltoClef mod) { // Check for end portals. Always. if (!endPortalOpened(mod, _endPortalCenterLocation) && WorldHelper.getCurrentDimension() == Dimension.OVERWORLD) { - Optional endPortal = mod.getBlockTracker().getNearestTracking(Blocks.END_PORTAL); - if (endPortal.isPresent()) { - _endPortalCenterLocation = endPortal.get(); - _endPortalOpened = true; - } else { - // TODO: Test that this works, for some reason the bot gets stuck near the stronghold and it keeps "Searching" for the portal - _endPortalCenterLocation = doSimpleSearchForEndPortal(mod); + if (mod.getBlockTracker().isTracking(Blocks.END_PORTAL)) { + Optional endPortal = mod.getBlockTracker().getNearestTracking(Blocks.END_PORTAL); + if (endPortal.isPresent()) { + _endPortalCenterLocation = endPortal.get(); + _endPortalOpened = true; + } else { + // TODO: Test that this works, for some reason the bot gets stuck near the stronghold and it keeps "Searching" for the portal + _endPortalCenterLocation = doSimpleSearchForEndPortal(mod); + } } } - if (getBedTask != null) { - // for smoker - _smeltTask = null; - _foodTask = null; - // for furnace - _starterGearTask = null; - _shieldTask = null; - _ironGearTask = null; - _gearTask = null; - } // Portable crafting table. // If we're NOT using our crafting table right now and there's one nearby, grab it. - if (!_endPortalOpened && WorldHelper.getCurrentDimension() != Dimension.END && _config.rePickupCraftingTable && - !mod.getItemStorage().hasItem(Items.CRAFTING_TABLE) && !thisOrChildSatisfies(isCraftingTableTask) - && (mod.getBlockTracker().anyFound(blockPos -> WorldHelper.canBreak(mod, blockPos) && - WorldHelper.canReach(mod, blockPos), Blocks.CRAFTING_TABLE) || - mod.getEntityTracker().itemDropped(Items.CRAFTING_TABLE))) { - setDebugState("Picking up the crafting table while we are at it."); - return new MineAndCollectTask(Items.CRAFTING_TABLE, 1, new Block[]{Blocks.CRAFTING_TABLE}, MiningRequirement.HAND); - } - if (_config.rePickupSmoker && !_endPortalOpened && WorldHelper.getCurrentDimension() != Dimension.END && - !mod.getItemStorage().hasItem(Items.SMOKER) && - (mod.getBlockTracker().anyFound(blockPos -> WorldHelper.canBreak(mod, blockPos) && - WorldHelper.canReach(mod, blockPos), Blocks.SMOKER) - || mod.getEntityTracker().itemDropped(Items.SMOKER)) && _smeltTask == null && - _foodTask == null) { - setDebugState("Picking up the smoker while we are at it."); - return new MineAndCollectTask(Items.SMOKER, 1, new Block[]{Blocks.SMOKER}, MiningRequirement.WOOD); - } - if (_config.rePickupFurnace && !_endPortalOpened && WorldHelper.getCurrentDimension() != Dimension.END && - !mod.getItemStorage().hasItem(Items.FURNACE) && - (mod.getBlockTracker().anyFound(blockPos -> WorldHelper.canBreak(mod, blockPos) && - WorldHelper.canReach(mod, blockPos), Blocks.FURNACE) || - mod.getEntityTracker().itemDropped(Items.FURNACE)) && _starterGearTask == null && - _shieldTask == null && _ironGearTask == null && _gearTask == null && !_goToNetherTask.isActive() && - !_ranStrongholdLocator && !mod.getModSettings().shouldUseBlastFurnace()) { - setDebugState("Picking up the furnace while we are at it."); - return new MineAndCollectTask(Items.FURNACE, 1, new Block[]{Blocks.FURNACE}, MiningRequirement.WOOD); - } - if (_config.rePickupFurnace && !_endPortalOpened && WorldHelper.getCurrentDimension() != Dimension.END && - !mod.getItemStorage().hasItem(Items.BLAST_FURNACE) && - (mod.getBlockTracker().anyFound(blockPos -> WorldHelper.canBreak(mod, blockPos) && - WorldHelper.canReach(mod, blockPos), Blocks.BLAST_FURNACE) || - mod.getEntityTracker().itemDropped(Items.BLAST_FURNACE)) && _starterGearTask == null && - _shieldTask == null && _ironGearTask == null && _gearTask == null && !_goToNetherTask.isActive() && - !_ranStrongholdLocator && mod.getModSettings().shouldUseBlastFurnace()) { - setDebugState("Picking up the blast furnace while we are at it."); - return new MineAndCollectTask(Items.BLAST_FURNACE, 1, new Block[]{Blocks.BLAST_FURNACE}, MiningRequirement.WOOD); + Block[] copperBlocks = ItemHelper.itemsToBlocks(ItemHelper.COPPER_BLOCKS); + if (mod.getBlockTracker().isTracking(Blocks.CRAFTING_TABLE)) { + Optional nearestCraftingTable = mod.getBlockTracker().getNearestTracking(Blocks.CRAFTING_TABLE); + if (nearestCraftingTable.isPresent() && WorldHelper.canBreak(mod, nearestCraftingTable.get())) { + Block craftingTable = mod.getWorld().getBlockState(nearestCraftingTable.get()).getBlock(); + for (Block CopperBlock : copperBlocks) { + Block blockBelow = mod.getWorld().getBlockState(nearestCraftingTable.get().down()).getBlock(); + if (blockBelow == CopperBlock) { + Debug.logMessage("Blacklisting crafting table in trial chambers."); + mod.getBlockTracker().requestBlockUnreachable(nearestCraftingTable.get(), 0); + } + } + } + } + boolean noEyesPlease = (endPortalOpened(mod, _endPortalCenterLocation) || WorldHelper.getCurrentDimension() == Dimension.END); + int filledPortalFrames = getFilledPortalFrames(mod, _endPortalCenterLocation); + int eyesNeededMin = noEyesPlease ? 0 : _config.minimumEyes - filledPortalFrames; + int eyesNeeded = noEyesPlease ? 0 : _config.targetEyes - filledPortalFrames; + int eyes = mod.getItemStorage().getItemCount(Items.ENDER_EYE); + if (eyes < eyesNeededMin || (!_ranStrongholdLocator && _collectingEyes && eyes < eyesNeeded)) { + if (mod.getBlockTracker().isTracking(Blocks.BLAST_FURNACE)) { + Optional blastFurnacePos = mod.getBlockTracker().getNearestTracking(Blocks.BLAST_FURNACE); + Optional blastFurnaceEntity = mod.getEntityTracker().getClosestItemDrop(Items.BLAST_FURNACE); + if (blastFurnacePos.isPresent() && !_endPortalOpened && WorldHelper.getCurrentDimension() != Dimension.END + && _config.rePickupCraftingTable && !mod.getItemStorage().hasItem(Items.BLAST_FURNACE) + && !thisOrChildSatisfies(isBlastFurnaceTask) && WorldHelper.canBreak(mod, blastFurnacePos.get()) + || (blastFurnaceEntity.isPresent() + && mod.getEntityTracker().itemDropped(blastFurnaceEntity.get().getStack().getItem()) + && !thisOrChildSatisfies(isBlastFurnaceTask) && !mod.getItemStorage().hasItem(Items.BLAST_FURNACE))) { + setDebugState("Picking up the blast furnace while we are at it."); + Item blastFurnaceItem = blastFurnaceEntity.isPresent() ? blastFurnaceEntity.get().getStack().getItem() : Items.BLAST_FURNACE; + Block blastFurnaceBlock = blastFurnacePos.isPresent() ? mod.getWorld().getBlockState(blastFurnacePos.get()).getBlock() : Blocks.BLAST_FURNACE; + return new MineAndCollectTask(blastFurnaceItem, 1, new Block[]{blastFurnaceBlock}, MiningRequirement.WOOD); + } + } + if (mod.getBlockTracker().isTracking(Blocks.FURNACE)) { + Optional furnacePos = mod.getBlockTracker().getNearestTracking(Blocks.FURNACE); + Optional furnaceEntity = mod.getEntityTracker().getClosestItemDrop(Items.FURNACE); + if (furnacePos.isPresent() && !_endPortalOpened && WorldHelper.getCurrentDimension() != Dimension.END + && _config.rePickupCraftingTable && !mod.getItemStorage().hasItem(Items.FURNACE) + && !mod.getItemStorage().hasItem(Items.BLAST_FURNACE) && !thisOrChildSatisfies(isFurnaceTask) + && WorldHelper.canBreak(mod, furnacePos.get()) + || (furnaceEntity.isPresent() && mod.getEntityTracker().itemDropped(furnaceEntity.get().getStack().getItem()) + && !thisOrChildSatisfies(isFurnaceTask) && !mod.getItemStorage().hasItem(Items.FURNACE) + && !mod.getItemStorage().hasItem(Items.BLAST_FURNACE))) { + setDebugState("Picking up the furnace while we are at it."); + Item furnaceItem = furnaceEntity.isPresent() ? furnaceEntity.get().getStack().getItem() : Items.FURNACE; + Block furnaceBlock = furnacePos.isPresent() ? mod.getWorld().getBlockState(furnacePos.get()).getBlock() : Blocks.FURNACE; + return new MineAndCollectTask(furnaceItem, 1, new Block[]{furnaceBlock}, MiningRequirement.WOOD); + } + } + if (mod.getBlockTracker().isTracking(Blocks.SMOKER)) { + Optional smokerPos = mod.getBlockTracker().getNearestTracking(Blocks.SMOKER); + Optional smokerEntity = mod.getEntityTracker().getClosestItemDrop(Items.SMOKER); + if (smokerPos.isPresent() && !_endPortalOpened && WorldHelper.getCurrentDimension() != Dimension.END + && _config.rePickupCraftingTable && !mod.getItemStorage().hasItem(Items.SMOKER) + && !thisOrChildSatisfies(isSmokerTask) && WorldHelper.canBreak(mod, smokerPos.get()) + || (smokerEntity.isPresent() + && mod.getEntityTracker().itemDropped(smokerEntity.get().getStack().getItem()) + && !thisOrChildSatisfies(isSmokerTask) && !mod.getItemStorage().hasItem(Items.SMOKER))) { + setDebugState("Picking up the smoker while we are at it."); + Item smokerItem = smokerEntity.isPresent() ? smokerEntity.get().getStack().getItem() : Items.SMOKER; + Block smokerBlock = smokerPos.isPresent() ? mod.getWorld().getBlockState(smokerPos.get()).getBlock() : Blocks.SMOKER; + return new MineAndCollectTask(smokerItem, 1, new Block[]{smokerBlock}, MiningRequirement.WOOD); + } + } + if (mod.getBlockTracker().isTracking(Blocks.CRAFTING_TABLE)) { + Optional craftingTablePos = mod.getBlockTracker().getNearestTracking(Blocks.CRAFTING_TABLE); + Optional craftingTableEntity = mod.getEntityTracker().getClosestItemDrop(Items.CRAFTING_TABLE); + if (craftingTablePos.isPresent() && !_endPortalOpened && WorldHelper.getCurrentDimension() != Dimension.END + && _config.rePickupCraftingTable && !mod.getItemStorage().hasItem(Items.CRAFTING_TABLE) + && !thisOrChildSatisfies(isCraftingTableTask) && WorldHelper.canBreak(mod, craftingTablePos.get()) + || (craftingTableEntity.isPresent() + && mod.getEntityTracker().itemDropped(craftingTableEntity.get().getStack().getItem()) + && !thisOrChildSatisfies(isCraftingTableTask) && !mod.getItemStorage().hasItem(Items.CRAFTING_TABLE))) { + setDebugState("Picking up the crafting table while we are at it."); + Item craftingTableItem = craftingTableEntity.isPresent() ? craftingTableEntity.get().getStack().getItem() : Items.CRAFTING_TABLE; + Block craftingTableBlock = craftingTablePos.isPresent() ? mod.getWorld().getBlockState(craftingTablePos.get()).getBlock() : Blocks.CRAFTING_TABLE; + return new MineAndCollectTask(craftingTableItem, 1, new Block[]{craftingTableBlock}, MiningRequirement.HAND); + } + } + if (!mod.getItemStorage().hasItem(Items.NETHERRACK) && + WorldHelper.getCurrentDimension() == Dimension.NETHER && !isGettingBlazeRods && + !isGettingEnderPearls) { + setDebugState("Getting netherrack."); + if (mod.getEntityTracker().itemDropped(Items.NETHERRACK)) { + return new PickupDroppedItemTask(Items.NETHERRACK, 1, true); + } + return TaskCatalogue.getItemTask(Items.NETHERRACK, 1); + } } - // Sleep through night. if (_config.sleepThroughNight && !_endPortalOpened && WorldHelper.getCurrentDimension() == Dimension.OVERWORLD) { if (WorldHelper.canSleep()) { - // for smoker - _smeltTask = null; - _foodTask = null; - // for furnace - _starterGearTask = null; - _shieldTask = null; - _ironGearTask = null; - _gearTask = null; if (_config.renderDistanceManipulation && mod.getItemStorage().hasItem(ItemHelper.BED)) { if (!mod.getClientBaritone().getExploreProcess().isActive()) { if (_timer1.elapsed()) { @@ -1402,11 +1355,29 @@ protected Task onTick(AltoClef mod) { setDebugState("Sleeping through night"); return _sleepThroughNightTask; } + if (shouldForce(mod, _getOneBedTask)) { + setDebugState("Getting one bed to sleep in at night."); + return _getOneBedTask; + } if (!mod.getItemStorage().hasItem(ItemHelper.BED)) { - if (mod.getBlockTracker().anyFound(blockPos -> WorldHelper.canBreak(mod, blockPos), ItemHelper.itemsToBlocks(ItemHelper.BED)) - || shouldForce(mod, _getOneBedTask)) { - setDebugState("Getting one bed to sleep in at night."); - return _getOneBedTask; + Block[] bedBlocks = ItemHelper.itemsToBlocks(ItemHelper.BED); + for (Block bedBlock : bedBlocks) { + if (mod.getBlockTracker().isTracking(bedBlock)) { + Optional nearestBed = mod.getBlockTracker().getNearestTracking(bedBlock); + if (nearestBed.isPresent() && WorldHelper.canBreak(mod, nearestBed.get())) { + boolean isValid = true; + for (Block CopperBlock : copperBlocks) { + Block blockBelow = mod.getWorld().getBlockState(nearestBed.get().down()).getBlock(); + if (blockBelow == CopperBlock) { + isValid = false; + break; + } + } + if (isValid) { + return _getOneBedTask; + } + } + } } } } @@ -1424,17 +1395,11 @@ protected Task onTick(AltoClef mod) { } getBedTask = getBedTask(mod); return getBedTask; - } else { - getBedTask = null; } + getBedTask = null; } // Do we need more eyes? - boolean noEyesPlease = (endPortalOpened(mod, _endPortalCenterLocation) || WorldHelper.getCurrentDimension() == Dimension.END); - int filledPortalFrames = getFilledPortalFrames(mod, _endPortalCenterLocation); - int eyesNeededMin = noEyesPlease ? 0 : _config.minimumEyes - filledPortalFrames; - int eyesNeeded = noEyesPlease ? 0 : _config.targetEyes - filledPortalFrames; - int eyes = mod.getItemStorage().getItemCount(Items.ENDER_EYE); if (eyes < eyesNeededMin || (!_ranStrongholdLocator && _collectingEyes && eyes < eyesNeeded)) { _collectingEyes = true; _weHaveEyes = false; @@ -1447,38 +1412,34 @@ protected Task onTick(AltoClef mod) { // We have eyes. Locate our portal + enter. switch (WorldHelper.getCurrentDimension()) { case OVERWORLD -> { - if (mod.getItemStorage().hasItem(Items.DIAMOND_PICKAXE)) { + if (mod.getItemStorage().hasItem(Items.DIAMOND_PICKAXE) && !StorageHelper.isBigCraftingOpen() + && !StorageHelper.isFurnaceOpen() && !StorageHelper.isSmokerOpen() + && !StorageHelper.isBlastFurnaceOpen() && (mod.getItemStorage().hasItem(Items.FLINT_AND_STEEL) + || mod.getItemStorage().hasItem(Items.FIRE_CHARGE))) { Item[] throwGearItems = {Items.STONE_SWORD, Items.STONE_PICKAXE, Items.IRON_SWORD, Items.IRON_PICKAXE}; - List ironArmors = mod.getItemStorage().getSlotsWithItemPlayerInventory(true, - COLLECT_IRON_ARMOR); - List throwGears = mod.getItemStorage().getSlotsWithItemPlayerInventory(true, - throwGearItems); - if (!StorageHelper.isBigCraftingOpen() && !StorageHelper.isFurnaceOpen() && - !StorageHelper.isSmokerOpen() && !StorageHelper.isBlastFurnaceOpen() && - (mod.getItemStorage().hasItem(Items.FLINT_AND_STEEL) || - mod.getItemStorage().hasItem(Items.FIRE_CHARGE))) { - if (!throwGears.isEmpty()) { - for (Slot throwGear : throwGears) { - if (Slot.isCursor(throwGear)) { - if (!mod.getControllerExtras().isBreakingBlock()) { - LookHelper.randomOrientation(mod); - } - mod.getSlotHandler().clickSlot(Slot.UNDEFINED, 0, SlotActionType.PICKUP); - } else { - mod.getSlotHandler().clickSlot(throwGear, 0, SlotActionType.PICKUP); + List throwGearSlot = mod.getItemStorage().getSlotsWithItemPlayerInventory(true, throwGearItems); + if (!throwGearSlot.isEmpty()) { + for (Slot slot : throwGearSlot) { + if (Slot.isCursor(slot)) { + if (!mod.getControllerExtras().isBreakingBlock()) { + LookHelper.randomOrientation(mod); } + mod.getSlotHandler().clickSlot(Slot.UNDEFINED, 0, SlotActionType.PICKUP); + } else { + mod.getSlotHandler().clickSlot(slot, 0, SlotActionType.PICKUP); } } - if (!ironArmors.isEmpty()) { - for (Slot ironArmor : ironArmors) { - if (Slot.isCursor(ironArmor)) { - if (!mod.getControllerExtras().isBreakingBlock()) { - LookHelper.randomOrientation(mod); - } - mod.getSlotHandler().clickSlot(Slot.UNDEFINED, 0, SlotActionType.PICKUP); - } else { - mod.getSlotHandler().clickSlot(ironArmor, 0, SlotActionType.PICKUP); + } + List ironArmorSlot = mod.getItemStorage().getSlotsWithItemPlayerInventory(true, COLLECT_IRON_ARMOR); + if (!ironArmorSlot.isEmpty()) { + for (Slot slot : ironArmorSlot) { + if (Slot.isCursor(slot)) { + if (!mod.getControllerExtras().isBreakingBlock()) { + LookHelper.randomOrientation(mod); } + mod.getSlotHandler().clickSlot(Slot.UNDEFINED, 0, SlotActionType.PICKUP); + } else { + mod.getSlotHandler().clickSlot(slot, 0, SlotActionType.PICKUP); } } } @@ -1486,7 +1447,8 @@ protected Task onTick(AltoClef mod) { // If we found our end portal... if (endPortalFound(mod, _endPortalCenterLocation)) { // Destroy silverfish spawner - if (StorageHelper.miningRequirementMetInventory(mod, MiningRequirement.WOOD)) { + if (StorageHelper.miningRequirementMetInventory(mod, MiningRequirement.WOOD) + && mod.getBlockTracker().isTracking(Blocks.SPAWNER)) { Optional silverfish = mod.getBlockTracker().getNearestTracking(blockPos -> { return WorldHelper.getSpawnerEntity(mod, blockPos) instanceof SilverfishEntity; }, Blocks.SPAWNER); @@ -1543,9 +1505,8 @@ protected Task onTick(AltoClef mod) { } getBedTask = getBedTask(mod); return getBedTask; - } else { - getBedTask = null; } + getBedTask = null; if (!mod.getItemStorage().hasItem(Items.WATER_BUCKET)) { setDebugState("Getting water bucket."); return TaskCatalogue.getItemTask(Items.WATER_BUCKET, 1); @@ -1564,36 +1525,33 @@ protected Task onTick(AltoClef mod) { } } case NETHER -> { - Item[] throwGearItems = {Items.STONE_SWORD, Items.STONE_PICKAXE, Items.IRON_SWORD, Items.IRON_PICKAXE}; - List ironArmors = mod.getItemStorage().getSlotsWithItemPlayerInventory(true, - COLLECT_IRON_ARMOR); - List throwGears = mod.getItemStorage().getSlotsWithItemPlayerInventory(true, - throwGearItems); - if (!StorageHelper.isBigCraftingOpen() && !StorageHelper.isFurnaceOpen() && - !StorageHelper.isSmokerOpen() && !StorageHelper.isBlastFurnaceOpen() && - (mod.getItemStorage().hasItem(Items.FLINT_AND_STEEL) || - mod.getItemStorage().hasItem(Items.FIRE_CHARGE))) { - if (!throwGears.isEmpty()) { - for (Slot throwGear : throwGears) { - if (Slot.isCursor(throwGear)) { + if (!StorageHelper.isBigCraftingOpen() && !StorageHelper.isFurnaceOpen() && !StorageHelper.isSmokerOpen() + && !StorageHelper.isBlastFurnaceOpen() && (mod.getItemStorage().hasItem(Items.FLINT_AND_STEEL) + || mod.getItemStorage().hasItem(Items.FIRE_CHARGE))) { + Item[] throwGearItems = {Items.STONE_SWORD, Items.STONE_PICKAXE, Items.IRON_SWORD, Items.IRON_PICKAXE}; + List throwGearSlot = mod.getItemStorage().getSlotsWithItemPlayerInventory(true, throwGearItems); + if (!throwGearSlot.isEmpty()) { + for (Slot slot : throwGearSlot) { + if (Slot.isCursor(slot)) { if (!mod.getControllerExtras().isBreakingBlock()) { LookHelper.randomOrientation(mod); } mod.getSlotHandler().clickSlot(Slot.UNDEFINED, 0, SlotActionType.PICKUP); } else { - mod.getSlotHandler().clickSlot(throwGear, 0, SlotActionType.PICKUP); + mod.getSlotHandler().clickSlot(slot, 0, SlotActionType.PICKUP); } } } - if (!ironArmors.isEmpty()) { - for (Slot ironArmor : ironArmors) { - if (Slot.isCursor(ironArmor)) { + List ironArmorSlot = mod.getItemStorage().getSlotsWithItemPlayerInventory(true, COLLECT_IRON_ARMOR); + if (!ironArmorSlot.isEmpty()) { + for (Slot slot : ironArmorSlot) { + if (Slot.isCursor(slot)) { if (!mod.getControllerExtras().isBreakingBlock()) { LookHelper.randomOrientation(mod); } mod.getSlotHandler().clickSlot(Slot.UNDEFINED, 0, SlotActionType.PICKUP); } else { - mod.getSlotHandler().clickSlot(ironArmor, 0, SlotActionType.PICKUP); + mod.getSlotHandler().clickSlot(slot, 0, SlotActionType.PICKUP); } } } @@ -1693,7 +1651,7 @@ private Task getEnderPearlTask(AltoClef mod, int count) { // Check if we have found an Enderman or Ender Pearl and have enough Twisting Vines. if ((endermanFound || pearlDropped) && hasTwistingVines) { Optional toKill = mod.getEntityTracker().getClosestEntity(EndermanEntity.class); - if (toKill.isPresent() && mod.getEntityTracker().isEntityReachable(toKill.get())) { + if (toKill.isPresent()) { return new KillEndermanTask(count); } } @@ -1711,9 +1669,8 @@ private Task getEnderPearlTask(AltoClef mod, int count) { if (vinesFound) { getTwistingVines = TaskCatalogue.getItemTask(Items.TWISTING_VINES, TWISTING_VINES_COUNT); return getTwistingVines; - } else { - return new SearchChunkForBlockTask(Blocks.TWISTING_VINES, Blocks.TWISTING_VINES_PLANT, Blocks.WARPED_HYPHAE, Blocks.WARPED_NYLIUM); } + return new SearchChunkForBlockTask(Blocks.TWISTING_VINES, Blocks.TWISTING_VINES_PLANT, Blocks.WARPED_HYPHAE, Blocks.WARPED_NYLIUM); } // Search for Ender Pearls within the warped forest biome. @@ -1727,22 +1684,24 @@ private Task getEnderPearlTask(AltoClef mod, int count) { * @return The target number of beds. */ private int getTargetBeds(AltoClef mod) { - // Check if the spawn needs to be set near the end portal - boolean needsToSetSpawn = _config.placeSpawnNearEndPortal - && (!spawnSetNearPortal(mod, _endPortalCenterLocation) - && !shouldForce(mod, _setBedSpawnTask)); - // Calculate the number of beds in the end - int bedsInEnd = Arrays.stream(ItemHelper.BED) - .mapToInt(bed -> _cachedEndItemDrops.getOrDefault(bed, 0)) - .sum(); - + int bedsInEnd = 0; + for (Item bed : ItemHelper.BED) { + bedsInEnd += _cachedEndItemDrops.getOrDefault(bed, 0); + } // Calculate the target number of beds - int targetBeds = _config.requiredBeds + (needsToSetSpawn ? 1 : 0) - bedsInEnd; - + int targetBeds = _config.requiredBeds; + if (_config.placeSpawnNearEndPortal) { + // Check if the spawn should be set near the end portal + if (!spawnSetNearPortal(mod, _endPortalCenterLocation) && !shouldForce(mod, _setBedSpawnTask)) { + targetBeds += 1; // Add 1 bed if the spawn should be set near the end portal + } + } + targetBeds -= bedsInEnd; // Subtract the number of beds already in the end return targetBeds; } + /** * Check if the given AltoClef mod needs more beds based on the item count and cached end item drops. * @@ -1781,7 +1740,22 @@ private Task getBedTask(AltoClef mod) { // Return the task to obtain shears return TaskCatalogue.getItemTask(Items.SHEARS, 1); } - + Block[] copperBlocks = ItemHelper.itemsToBlocks(ItemHelper.COPPER_BLOCKS); + Block[] beds = ItemHelper.itemsToBlocks(ItemHelper.BED); + for (Block bed : beds) { + if (mod.getBlockTracker().isTracking(bed)) { + Optional nearestBed = mod.getBlockTracker().getNearestTracking(bed); + if (nearestBed.isPresent() && WorldHelper.canBreak(mod, nearestBed.get())) { + for (Block CopperBlock : copperBlocks) { + Block blockBelow = mod.getWorld().getBlockState(nearestBed.get().down()).getBlock(); + if (blockBelow == CopperBlock) { + Debug.logMessage("Blacklisting bed in trial chambers."); + mod.getBlockTracker().requestBlockUnreachable(nearestBed.get(), 0); + } + } + } + } + } // Return the task to obtain the target number of beds return TaskCatalogue.getItemTask("bed", targetBeds); } @@ -1797,68 +1771,84 @@ private boolean anyBedsFound(AltoClef mod) { BlockTracker blockTracker = mod.getBlockTracker(); EntityTracker entityTracker = mod.getEntityTracker(); - // Check if any beds are found in blocks. - boolean bedsFoundInBlocks = blockTracker.anyFound(ItemHelper.itemsToBlocks(ItemHelper.BED)); + // Check if the beds are not in the trial chamber. + boolean validBedsFoundInBlocks = false; + Block[] copperBlocks = ItemHelper.itemsToBlocks(ItemHelper.COPPER_BLOCKS); + Block[] beds = ItemHelper.itemsToBlocks(ItemHelper.BED); + for (Block bed : beds) { + if (mod.getBlockTracker().isTracking(bed)) { + Optional nearestBed = blockTracker.getNearestTracking(bed); + if (nearestBed.isPresent() && WorldHelper.canBreak(mod, nearestBed.get())) { + validBedsFoundInBlocks = true; + for (Block CopperBlock : copperBlocks) { + Block blockBelow = mod.getWorld().getBlockState(nearestBed.get().down()).getBlock(); + if (blockBelow == CopperBlock) { + validBedsFoundInBlocks = false; + break; + } + } + } + } + } // Check if any beds are dropped by entities. boolean bedsFoundInEntities = entityTracker.itemDropped(ItemHelper.BED); - // Return true if beds are found either in blocks or entities. - return bedsFoundInBlocks || bedsFoundInEntities; + return validBedsFoundInBlocks || bedsFoundInEntities; } /** * Perform a simple search for the end portal. + *

+ * This method searches for the end portal frames in the world and calculates the average position of those frames. + * If the number of frames found is less than the constant END_PORTAL_FRAME_COUNT, it returns null. + * * @param mod The AltoClef mod instance * @return The average position of the end portal frames, or null if not found */ private BlockPos doSimpleSearchForEndPortal(AltoClef mod) { - // Get the locations of the end portal frames + // Get the known locations of end portal frames List frames = mod.getBlockTracker().getKnownLocations(Blocks.END_PORTAL_FRAME); - - // Check if enough frames are found - if (frames.size() >= END_PORTAL_FRAME_COUNT) { - // Calculate the average position of the frames - Optional average = frames.stream() - .reduce((bpos1, bpos2) -> new BlockPos((bpos1.getX() + bpos2.getX()) / 2, (bpos1.getY() + bpos2.getY()) / 2, (bpos1.getZ() + bpos2.getZ()) / 2)); - - return average.orElse(null); - } - - return null; + // If the number of frames found is less than the constant END_PORTAL_FRAME_COUNT, return null + if (frames.size() < END_PORTAL_FRAME_COUNT) { + return null; + } + // Calculate the sum of the x, y, and z coordinates of the frames + int sumX = 0, sumY = 0, sumZ = 0; + for (BlockPos frame : frames) { + sumX += frame.getX(); + sumY += frame.getY(); + sumZ += frame.getZ(); + } + // Calculate the average position of the frames + return new BlockPos(sumX / frames.size(), sumY / frames.size(), sumZ / frames.size()); } + /** - * Get the count of filled portal frames around the end portal center. + * Counts the number of filled portal frames around the end portal center. * - * @param mod the AltoClef mod - * @param endPortalCenter the center of the end portal - * @return the count of filled portal frames, or 0 if the end portal is not found or the frame blocks are not loaded + * @param mod The AltoClef mod instance. + * @param endPortalCenter The center of the end portal. + * @return The count of filled portal frames, or 0 if the end portal is not found or the frame blocks are not loaded. */ private int getFilledPortalFrames(AltoClef mod, BlockPos endPortalCenter) { - // If the end portal is found, return the constant count. - if (endPortalFound(mod, endPortalCenter)) { - return END_PORTAL_FRAME_COUNT; - } - - // Get all the frame blocks around the end portal center. - List frameBlocks = getFrameBlocks(endPortalCenter); - - // Check if all the frame blocks are loaded. - if (frameBlocks.stream().allMatch(blockPos -> mod.getChunkTracker().isChunkLoaded(blockPos))) { - // Calculate the sum of filled frames using a stream and mapToInt. - int filledFramesCount = frameBlocks.stream() - .mapToInt(blockPos -> { - boolean isFilled = isEndPortalFrameFilled(mod, blockPos); - return isFilled ? 1 : 0; - }) - .sum(); - return filledFramesCount; + // Check if the end portal is found + if (!endPortalFound(mod, endPortalCenter)) { + return 0; + } + int filledFramesCount = 0; + // Iterate over each frame block + for (BlockPos frame : getFrameBlocks(endPortalCenter)) { + // Check if the frame block is loaded and filled + if (mod.getChunkTracker().isChunkLoaded(frame) && isEndPortalFrameFilled(mod, frame)) { + filledFramesCount++; + } } - - return 0; + return filledFramesCount; } + /** * Checks if a chest at the specified position can be looted from a portal * @param mod The game mod @@ -1932,73 +1922,65 @@ private Task getEyesOfEnderTask(AltoClef mod, int targetEyes) { if (_config.renderDistanceManipulation) { if (!mod.getClientBaritone().getExploreProcess().isActive()) { if (_timer1.elapsed()) { - MinecraftClient.getInstance().options.getViewDistance().setValue(2); - MinecraftClient.getInstance().options.getEntityDistanceScaling().setValue(0.5); + getInstance().options.getViewDistance().setValue(2); + getInstance().options.getEntityDistanceScaling().setValue(0.5); _timer1.reset(); } } } getBedTask = getBedTask(mod); return getBedTask; - } else { - getBedTask = null; } + getBedTask = null; if (shouldForce(mod, _logsTask)) { setDebugState("Getting logs for later."); return _logsTask; - } else { - _logsTask = null; } + _logsTask = null; if (shouldForce(mod, _stoneGearTask)) { setDebugState("Getting stone gear for later."); return _stoneGearTask; - } else { - _stoneGearTask = null; } + _stoneGearTask = null; if (shouldForce(mod, _getPorkchopTask)) { setDebugState("Getting pork chop just for fun."); if (_config.renderDistanceManipulation) { if (!mod.getClientBaritone().getExploreProcess().isActive()) { - MinecraftClient.getInstance().options.getViewDistance().setValue(32); - MinecraftClient.getInstance().options.getEntityDistanceScaling().setValue(5.0); + getInstance().options.getViewDistance().setValue(32); + getInstance().options.getEntityDistanceScaling().setValue(5.0); } } return _getPorkchopTask; - } else { - _getPorkchopTask = null; } + _getPorkchopTask = null; if (shouldForce(mod, _starterGearTask)) { setDebugState("Getting starter gear."); return _starterGearTask; - } else { - _starterGearTask = null; } + _starterGearTask = null; if (shouldForce(mod, _shieldTask) && !StorageHelper.isArmorEquipped(mod, COLLECT_SHIELD)) { setDebugState("Getting shield for defense purposes only."); return _shieldTask; - } else { - _shieldTask = null; } + _shieldTask = null; if (shouldForce(mod, _foodTask)) { setDebugState("Getting food for ender eye journey."); return _foodTask; - } else { - _foodTask = null; } + _foodTask = null; if (shouldForce(mod, _smeltTask)) { if (_config.renderDistanceManipulation) { if (!mod.getClientBaritone().getExploreProcess().isActive()) { if (_timer1.elapsed()) { - MinecraftClient.getInstance().options.getViewDistance().setValue(2); - MinecraftClient.getInstance().options.getEntityDistanceScaling().setValue(0.5); + getInstance().options.getViewDistance().setValue(2); + getInstance().options.getEntityDistanceScaling().setValue(0.5); _timer1.reset(); } } } return _smeltTask; - } else { - _smeltTask = null; } + _smeltTask = null; // Smelt remaining raw food if (_config.alwaysCookRawFood) { for (Item raw : ItemHelper.RAW_FOODS) { @@ -2010,140 +1992,134 @@ private Task getEyesOfEnderTask(AltoClef mod, int targetEyes) { _smeltTask = new SmeltInSmokerTask(new SmeltTarget(new ItemTarget(cooked.get(), targetCount), new ItemTarget(raw, targetCount))); return _smeltTask; } - } else { - _smeltTask = null; } } } + _smeltTask = null; // Make sure we have gear, then food. if (shouldForce(mod, _lootTask)) { setDebugState("Looting chest for goodies"); return _lootTask; } + _lootTask = null; if (shouldForce(mod, _ironGearTask) && !StorageHelper.isArmorEquipped(mod, COLLECT_IRON_ARMOR)) { setDebugState("Getting iron gear before diamond gear for defense purposes only."); return _ironGearTask; - } else { - _ironGearTask = null; } + _ironGearTask = null; if (shouldForce(mod, _gearTask) && !StorageHelper.isArmorEquipped(mod, COLLECT_EYE_ARMOR)) { setDebugState("Getting diamond gear for ender eye journey."); return _gearTask; - } else { - _gearTask = null; } + _gearTask = null; boolean eyeGearSatisfied = StorageHelper.itemTargetsMet(mod, COLLECT_EYE_GEAR_MIN) && StorageHelper.isArmorEquippedAll(mod, COLLECT_EYE_ARMOR); boolean ironGearSatisfied = StorageHelper.itemTargetsMet(mod, COLLECT_IRON_GEAR_MIN) && StorageHelper.isArmorEquippedAll(mod, COLLECT_IRON_ARMOR); boolean shieldSatisfied = StorageHelper.isArmorEquipped(mod, COLLECT_SHIELD); - // Search for a better place - if (!mod.getItemStorage().hasItem(Items.PORKCHOP) && - !mod.getItemStorage().hasItem(Items.COOKED_PORKCHOP) && - !StorageHelper.itemTargetsMet(mod, IRON_GEAR_MIN) && !ironGearSatisfied && !eyeGearSatisfied) { - if (mod.getItemStorage().getItemCount(ItemHelper.LOG) < 12 && !StorageHelper.itemTargetsMet(mod, COLLECT_STONE_GEAR) && - !StorageHelper.itemTargetsMet(mod, IRON_GEAR_MIN) && !eyeGearSatisfied && - !ironGearSatisfied) { - _logsTask = TaskCatalogue.getItemTask("log", 18); - return _logsTask; - } else { - _logsTask = null; - } - if (!StorageHelper.itemTargetsMet(mod, COLLECT_STONE_GEAR) && - !StorageHelper.itemTargetsMet(mod, IRON_GEAR_MIN) && !eyeGearSatisfied && - !ironGearSatisfied) { - if (mod.getItemStorage().getItemCount(Items.STICK) < 7) { - _stoneGearTask = TaskCatalogue.getItemTask(Items.STICK, 15); + if (!isEquippingDiamondArmor) { + // Search for a better place + if (!mod.getItemStorage().hasItem(Items.PORKCHOP) && + !mod.getItemStorage().hasItem(Items.COOKED_PORKCHOP) && + !StorageHelper.itemTargetsMet(mod, IRON_GEAR_MIN) && !ironGearSatisfied && !eyeGearSatisfied) { + if (mod.getItemStorage().getItemCount(ItemHelper.LOG) < 12 + && mod.getItemStorage().getItemCount(ItemHelper.PLANKS) < 12 * 4 + && !StorageHelper.itemTargetsMet(mod, COLLECT_STONE_GEAR) + && !StorageHelper.itemTargetsMet(mod, IRON_GEAR_MIN) && !eyeGearSatisfied && !ironGearSatisfied) { + _logsTask = TaskCatalogue.getItemTask("log", 18); + return _logsTask; + } + if (!StorageHelper.itemTargetsMet(mod, COLLECT_STONE_GEAR) && + !StorageHelper.itemTargetsMet(mod, IRON_GEAR_MIN) && !eyeGearSatisfied && + !ironGearSatisfied) { + if (mod.getItemStorage().getItemCount(Items.STICK) < 7) { + _stoneGearTask = TaskCatalogue.getItemTask(Items.STICK, 15); + return _stoneGearTask; + } + _stoneGearTask = TaskCatalogue.getSquashedItemTask(COLLECT_STONE_GEAR); return _stoneGearTask; } - _stoneGearTask = TaskCatalogue.getSquashedItemTask(COLLECT_STONE_GEAR); - return _stoneGearTask; - } else { - _stoneGearTask = null; + if (mod.getEntityTracker().entityFound(PigEntity.class) && (StorageHelper.itemTargetsMet(mod, + COLLECT_STONE_GEAR) || StorageHelper.itemTargetsMet(mod, IRON_GEAR_MIN) || + eyeGearSatisfied || ironGearSatisfied)) { + Predicate notBaby = entity -> entity instanceof LivingEntity livingEntity && !livingEntity.isBaby(); + _getPorkchopTask = new KillAndLootTask(PigEntity.class, notBaby, new ItemTarget(Items.PORKCHOP, 1)); + return _getPorkchopTask; + } + setDebugState("Searching a better place to start with."); + if (_config.renderDistanceManipulation) { + if (!mod.getClientBaritone().getExploreProcess().isActive()) { + if (_timer1.elapsed()) { + getInstance().options.getViewDistance().setValue(32); + getInstance().options.getEntityDistanceScaling().setValue(5.0); + _timer1.reset(); + } + } + } + searchBiomeTask = new SearchWithinBiomeTask(BiomeKeys.PLAINS); + return searchBiomeTask; } - if (mod.getEntityTracker().entityFound(PigEntity.class) && (StorageHelper.itemTargetsMet(mod, - COLLECT_STONE_GEAR) || StorageHelper.itemTargetsMet(mod, IRON_GEAR_MIN) || - eyeGearSatisfied || ironGearSatisfied)) { - Predicate notBaby = entity -> entity instanceof LivingEntity livingEntity && !livingEntity.isBaby(); - _getPorkchopTask = new KillAndLootTask(PigEntity.class, notBaby, new ItemTarget(Items.PORKCHOP, 1)); - return _getPorkchopTask; - } else { - _getPorkchopTask = null; + // Then get one bed + if (!mod.getItemStorage().hasItem(ItemHelper.BED) && _config.sleepThroughNight) { + return _getOneBedTask; } - setDebugState("Searching a better place to start with."); - if (_config.renderDistanceManipulation) { - if (!mod.getClientBaritone().getExploreProcess().isActive()) { - if (_timer1.elapsed()) { - MinecraftClient.getInstance().options.getViewDistance().setValue(32); - MinecraftClient.getInstance().options.getEntityDistanceScaling().setValue(5.0); - _timer1.reset(); - } + // Then starter gear + if (!StorageHelper.itemTargetsMet(mod, IRON_GEAR_MIN) && !eyeGearSatisfied && + !ironGearSatisfied && !StorageHelper.isArmorEquipped(mod, Items.SHIELD)) { + _starterGearTask = TaskCatalogue.getSquashedItemTask(IRON_GEAR); + return _starterGearTask; + } + // Then get shield + if (_config.getShield && !shieldSatisfied && !mod.getFoodChain().needsToEat()) { + ItemTarget shield = new ItemTarget(COLLECT_SHIELD); + if (mod.getItemStorage().hasItem(shield) && !StorageHelper.isArmorEquipped(mod, COLLECT_SHIELD)) { + setDebugState("Equipping shield."); + return new EquipArmorTask(COLLECT_SHIELD); } + _shieldTask = TaskCatalogue.getItemTask(shield); + return _shieldTask; } - searchBiomeTask = new SearchWithinBiomeTask(BiomeKeys.PLAINS); - return searchBiomeTask; - } else { - searchBiomeTask = null; - } - // Then get one bed - if (!mod.getItemStorage().hasItem(ItemHelper.BED) && _config.sleepThroughNight) { - return _getOneBedTask; - } - // Then starter gear - if (!StorageHelper.itemTargetsMet(mod, IRON_GEAR_MIN) && !eyeGearSatisfied && - !ironGearSatisfied && !StorageHelper.isArmorEquipped(mod, Items.SHIELD)) { - _starterGearTask = TaskCatalogue.getSquashedItemTask(IRON_GEAR); - return _starterGearTask; - } else { - _starterGearTask = null; - } - // Then get shield - if (_config.getShield && !shieldSatisfied && !mod.getFoodChain().needsToEat()) { - ItemTarget shield = new ItemTarget(COLLECT_SHIELD); - if (mod.getItemStorage().hasItem(shield) && !StorageHelper.isArmorEquipped(mod, COLLECT_SHIELD)) { - setDebugState("Equipping shield."); - return new EquipArmorTask(COLLECT_SHIELD); + // Then get food + if (StorageHelper.calculateInventoryFoodScore(mod) < _config.minFoodUnits) { + _foodTask = new CollectFoodTask(_config.foodUnits); + return _foodTask; } - _shieldTask = TaskCatalogue.getItemTask(shield); - return _shieldTask; - } else { - _shieldTask = null; - } - // Then get food - if (StorageHelper.calculateInventoryFoodScore(mod) < _config.minFoodUnits) { - _foodTask = new CollectFoodTask(_config.foodUnits); - return _foodTask; - } else { - _foodTask = null; - } - // Then loot chest if there is any - if (_config.searchRuinedPortals) { - // Check for ruined portals - Optional chest = locateClosestUnopenedRuinedPortalChest(mod); - if (chest.isPresent()) { - _lootTask = new LootContainerTask(chest.get(), lootableItems(mod), _noCurseOfBinding); - return _lootTask; + // Then loot chest if there is any + if (_config.searchRuinedPortals) { + // Check for ruined portals + Optional chest = locateClosestUnopenedRuinedPortalChest(mod); + if (chest.isPresent()) { + _lootTask = new LootContainerTask(chest.get(), lootableItems(mod), _noCurseOfBinding); + return _lootTask; + } } - } - if (_config.searchDesertTemples && StorageHelper.miningRequirementMetInventory(mod, MiningRequirement.WOOD)) { - // Check for desert temples - BlockPos temple = WorldHelper.getADesertTemple(mod); - if (temple != null) { - _lootTask = new LootDesertTempleTask(temple, lootableItems(mod)); - return _lootTask; + if (_config.searchDesertTemples && StorageHelper.miningRequirementMetInventory(mod, MiningRequirement.WOOD)) { + // Check for desert temples + BlockPos temple = WorldHelper.getADesertTemple(mod); + if (temple != null) { + _lootTask = new LootDesertTempleTask(temple, lootableItems(mod)); + return _lootTask; + } } - } - // Then get iron - if (_config.ironGearBeforeDiamondGear && !ironGearSatisfied && !eyeGearSatisfied && - !_isEquippingDiamondArmor) { - for (Item iron : COLLECT_IRON_ARMOR) { - if (mod.getItemStorage().hasItem(iron) && !StorageHelper.isArmorEquipped(mod, iron)) { - setDebugState("Equipping armor."); - return new EquipArmorTask(COLLECT_IRON_ARMOR); + // Then get iron + if (_config.ironGearBeforeDiamondGear && !ironGearSatisfied && !eyeGearSatisfied) { + for (Item ironArmor : COLLECT_IRON_ARMOR) { + if (mod.getItemStorage().hasItem(ironArmor) && !StorageHelper.isArmorEquipped(mod, ironArmor)) { + setDebugState("Equipping armor."); + return new EquipArmorTask(ironArmor); + } + } + List ironGearsAndArmors = new ArrayList<>(); + for (ItemTarget ironGear : COLLECT_IRON_GEAR) { + ironGearsAndArmors.add(ironGear); } + for (Item ironArmor : COLLECT_IRON_ARMOR) { + if (!mod.getItemStorage().hasItem(ironArmor) && !StorageHelper.isArmorEquipped(mod, ironArmor)) { + ironGearsAndArmors.add(new ItemTarget(ironArmor, 1)); + } + } + _ironGearTask = TaskCatalogue.getSquashedItemTask(ironGearsAndArmors.toArray(ItemTarget[]::new)); + return _ironGearTask; } - _ironGearTask = TaskCatalogue.getSquashedItemTask(Stream.concat(Arrays.stream(COLLECT_IRON_ARMOR).filter(item -> !mod.getItemStorage().hasItem(item) && !StorageHelper.isArmorEquipped(mod, item)).map(item -> new ItemTarget(item, 1)), Arrays.stream(COLLECT_IRON_GEAR)).toArray(ItemTarget[]::new)); - return _ironGearTask; - } else { _ironGearTask = null; } // Then get diamond @@ -2151,44 +2127,50 @@ private Task getEyesOfEnderTask(AltoClef mod, int targetEyes) { for (Item diamond : COLLECT_EYE_ARMOR) { if (mod.getItemStorage().hasItem(diamond) && !StorageHelper.isArmorEquipped(mod, diamond)) { setDebugState("Equipping armor."); - _isEquippingDiamondArmor = true; - return new EquipArmorTask(COLLECT_EYE_ARMOR); + isEquippingDiamondArmor = true; + return new EquipArmorTask(diamond); } } - _gearTask = TaskCatalogue.getSquashedItemTask(Stream.concat(Arrays.stream(COLLECT_EYE_ARMOR).filter(item -> !mod.getItemStorage().hasItem(item) && !StorageHelper.isArmorEquipped(mod, item)).map(item -> new ItemTarget(item, 1)), Arrays.stream(COLLECT_EYE_GEAR)).toArray(ItemTarget[]::new)); + List diamondGearsAndArmors = new ArrayList<>(); + for (ItemTarget diamondGear : COLLECT_EYE_GEAR) { + diamondGearsAndArmors.add(diamondGear); + } + for (Item diamondArmor : COLLECT_EYE_ARMOR) { + if (!mod.getItemStorage().hasItem(diamondArmor) && !StorageHelper.isArmorEquipped(mod, diamondArmor)) { + diamondGearsAndArmors.add(new ItemTarget(diamondArmor, 1)); + } + } + _gearTask = TaskCatalogue.getSquashedItemTask(diamondGearsAndArmors.toArray(ItemTarget[]::new)); return _gearTask; } else { _gearTask = null; - Item[] throwGearItems = {Items.STONE_SWORD, Items.STONE_PICKAXE, Items.IRON_SWORD, Items.IRON_PICKAXE}; - List ironArmors = mod.getItemStorage().getSlotsWithItemPlayerInventory(true, - COLLECT_IRON_ARMOR); - List throwGears = mod.getItemStorage().getSlotsWithItemPlayerInventory(true, - throwGearItems); - if (!StorageHelper.isBigCraftingOpen() && !StorageHelper.isFurnaceOpen() && - !StorageHelper.isSmokerOpen() && !StorageHelper.isBlastFurnaceOpen() && - (mod.getItemStorage().hasItem(Items.FLINT_AND_STEEL) || - mod.getItemStorage().hasItem(Items.FIRE_CHARGE))) { - if (!throwGears.isEmpty()) { - for (Slot throwGear : throwGears) { - if (Slot.isCursor(throwGear)) { + if (!StorageHelper.isBigCraftingOpen() && !StorageHelper.isFurnaceOpen() && !StorageHelper.isSmokerOpen() + && !StorageHelper.isBlastFurnaceOpen() && (mod.getItemStorage().hasItem(Items.FLINT_AND_STEEL) + || mod.getItemStorage().hasItem(Items.FIRE_CHARGE))) { + Item[] throwGearItems = {Items.STONE_SWORD, Items.STONE_PICKAXE, Items.IRON_SWORD, Items.IRON_PICKAXE}; + List throwGearSlot = mod.getItemStorage().getSlotsWithItemPlayerInventory(true, throwGearItems); + if (!throwGearSlot.isEmpty()) { + for (Slot slot : throwGearSlot) { + if (Slot.isCursor(slot)) { if (!mod.getControllerExtras().isBreakingBlock()) { LookHelper.randomOrientation(mod); } mod.getSlotHandler().clickSlot(Slot.UNDEFINED, 0, SlotActionType.PICKUP); } else { - mod.getSlotHandler().clickSlot(throwGear, 0, SlotActionType.PICKUP); + mod.getSlotHandler().clickSlot(slot, 0, SlotActionType.PICKUP); } } } - if (!ironArmors.isEmpty()) { - for (Slot ironArmor : ironArmors) { - if (Slot.isCursor(ironArmor)) { + List ironArmorSlot = mod.getItemStorage().getSlotsWithItemPlayerInventory(true, COLLECT_IRON_ARMOR); + if (!ironArmorSlot.isEmpty()) { + for (Slot slot : ironArmorSlot) { + if (Slot.isCursor(slot)) { if (!mod.getControllerExtras().isBreakingBlock()) { LookHelper.randomOrientation(mod); } mod.getSlotHandler().clickSlot(Slot.UNDEFINED, 0, SlotActionType.PICKUP); } else { - mod.getSlotHandler().clickSlot(ironArmor, 0, SlotActionType.PICKUP); + mod.getSlotHandler().clickSlot(slot, 0, SlotActionType.PICKUP); } } } diff --git a/src/main/java/adris/altoclef/tasks/speedrun/WaitForDragonAndPearlTask.java b/src/main/java/adris/altoclef/tasks/speedrun/WaitForDragonAndPearlTask.java index 602b95e0d..280b61e50 100644 --- a/src/main/java/adris/altoclef/tasks/speedrun/WaitForDragonAndPearlTask.java +++ b/src/main/java/adris/altoclef/tasks/speedrun/WaitForDragonAndPearlTask.java @@ -4,7 +4,6 @@ import adris.altoclef.Debug; import adris.altoclef.TaskCatalogue; import adris.altoclef.tasks.entity.DoToClosestEntityTask; -import adris.altoclef.tasks.entity.KillEntitiesTask; import adris.altoclef.tasks.movement.GetToBlockTask; import adris.altoclef.tasks.movement.GetToXZTask; import adris.altoclef.tasks.movement.GetToYTask; @@ -18,13 +17,11 @@ import net.minecraft.entity.Entity; import net.minecraft.entity.boss.dragon.EnderDragonEntity; import net.minecraft.entity.decoration.EndCrystalEntity; -import net.minecraft.entity.mob.EndermanEntity; import net.minecraft.entity.projectile.DragonFireballEntity; import net.minecraft.item.Items; import net.minecraft.util.math.BlockPos; import java.util.Optional; -import java.util.function.Predicate; // TODO: // The 10 Portal pillars form a 43 block radius, but the angle offset/cycle is random. @@ -77,13 +74,6 @@ protected void onStart(AltoClef mod) { @Override protected Task onTick(AltoClef mod) { - Optional enderMen = mod.getEntityTracker().getClosestEntity(EndermanEntity.class); - if (enderMen.isPresent() && (enderMen.get() instanceof EndermanEntity endermanEntity) && - endermanEntity.isAngry()) { - setDebugState("Killing angry endermen"); - Predicate angry = entity -> endermanEntity.isAngry(); - return new KillEntitiesTask(angry, enderMen.get().getClass()); - } if (_throwPearlTask != null && _throwPearlTask.isActive() && !_throwPearlTask.isFinished(mod)) { setDebugState("Throwing pearl!"); return _throwPearlTask; diff --git a/src/main/java/adris/altoclef/tasks/stupid/ReplaceBlocksTask.java b/src/main/java/adris/altoclef/tasks/stupid/ReplaceBlocksTask.java index baa6f5f6b..3626cca77 100644 --- a/src/main/java/adris/altoclef/tasks/stupid/ReplaceBlocksTask.java +++ b/src/main/java/adris/altoclef/tasks/stupid/ReplaceBlocksTask.java @@ -20,7 +20,7 @@ import java.util.ArrayDeque; import java.util.Arrays; import java.util.Deque; -import java.util.List; +import java.util.Optional; public class ReplaceBlocksTask extends Task { @@ -92,10 +92,14 @@ protected Task onTick(AltoClef mod) { // Get to replace item if (!mod.getItemStorage().hasItem(_toReplace.getMatches())) { - List locations = mod.getBlockTracker().getKnownLocations(_toFind); int need = 0; - if (!locations.isEmpty()) { - for (BlockPos loc : locations) if (isWithinRange(loc) && need < MAX_MATERIALS_NEEDED_AT_A_TIME) need++; + for (Block toFind : _toFind) { + if (mod.getBlockTracker().isTracking(toFind)) { + Optional location = mod.getBlockTracker().getNearestTracking(toFind); + if (location.isPresent() && isWithinRange(location.get()) && need < MAX_MATERIALS_NEEDED_AT_A_TIME) { + need++; + } + } } if (need == 0) { setDebugState("No replaceable blocks found, wandering."); @@ -112,7 +116,7 @@ protected Task onTick(AltoClef mod) { while (!_forceReplace.isEmpty()) { BlockPos toReplace = _forceReplace.pop(); if (!ArrayUtils.contains(blocksToPlace, mod.getWorld().getBlockState(toReplace).getBlock())) { - _replaceTask = new PlaceBlockTask(toReplace, blocksToPlace); + _replaceTask = new PlaceBlockTask(toReplace, blocksToPlace, false, true); return _replaceTask; } } @@ -120,7 +124,7 @@ protected Task onTick(AltoClef mod) { // Now replace setDebugState("Searching for blocks to replace..."); return new DoToClosestBlockTask(whereToPlace -> { - _replaceTask = new PlaceBlockTask(whereToPlace, blocksToPlace); + _replaceTask = new PlaceBlockTask(whereToPlace, blocksToPlace, false, true); return _replaceTask; }, this::isWithinRange, diff --git a/src/main/java/adris/altoclef/tasks/stupid/TerminatorTask.java b/src/main/java/adris/altoclef/tasks/stupid/TerminatorTask.java index 28183b381..057a39dc7 100644 --- a/src/main/java/adris/altoclef/tasks/stupid/TerminatorTask.java +++ b/src/main/java/adris/altoclef/tasks/stupid/TerminatorTask.java @@ -16,7 +16,6 @@ import adris.altoclef.ui.MessagePriority; import adris.altoclef.util.ItemTarget; import adris.altoclef.util.SmeltTarget; -import adris.altoclef.util.helpers.BaritoneHelper; import adris.altoclef.util.helpers.ItemHelper; import adris.altoclef.util.helpers.LookHelper; import adris.altoclef.util.helpers.StorageHelper; @@ -34,9 +33,6 @@ import java.util.List; import java.util.Optional; import java.util.function.Predicate; -import java.util.function.Supplier; -import java.util.stream.Collectors; -import java.util.stream.Stream; /** * Roams around the world to terminate Sarah Khaannah @@ -126,12 +122,11 @@ protected Task onTick(AltoClef mod) { _runAwayExtraTime.reset(); try { - _runAwayTask = new RunAwayFromPlayersTask(() -> { - Stream stream = mod.getEntityTracker().getTrackedEntities(PlayerEntity.class).stream(); - synchronized (BaritoneHelper.MINECRAFT_LOCK) { - return stream.filter(toAccept -> shouldPunk(mod, toAccept)).collect(Collectors.toList()); - } - }, RUN_AWAY_DISTANCE); + Optional player = mod.getEntityTracker().getClosestEntity(PlayerEntity.class); + if (player.isPresent() && player.get() instanceof PlayerEntity playerEntity + && shouldPunk(mod, playerEntity)) { + _runAwayTask = new RunAwayFromPlayersTask(player.get(), RUN_AWAY_DISTANCE); + } } catch (ConcurrentModificationException e) { // oof Debug.logWarning("Duct tape over ConcurrentModificationException (see log)"); @@ -278,7 +273,7 @@ private String getRandomFunnyMessage() { private static class RunAwayFromPlayersTask extends RunAwayFromEntitiesTask { - public RunAwayFromPlayersTask(Supplier> toRunAwayFrom, double distanceToRun) { + public RunAwayFromPlayersTask(Entity toRunAwayFrom, double distanceToRun) { super(toRunAwayFrom, distanceToRun, true, 0.1); // More lenient progress checker _checker = new MovementProgressChecker(); diff --git a/src/main/java/adris/altoclef/trackers/EntityTracker.java b/src/main/java/adris/altoclef/trackers/EntityTracker.java index a8734adb3..60b4f324b 100644 --- a/src/main/java/adris/altoclef/trackers/EntityTracker.java +++ b/src/main/java/adris/altoclef/trackers/EntityTracker.java @@ -369,7 +369,7 @@ protected synchronized void updateState() { if (EntityHelper.isAngryAtPlayer(_mod, entity)) { // Check if the mob is facing us or is close enough - boolean closeEnough = entity.isInRange(_mod.getPlayer(), 26); + boolean closeEnough = entity.isInRange(_mod.getPlayer(), 16); //Debug.logInternal("TARGET: " + hostile.is); if (closeEnough) { diff --git a/src/main/java/adris/altoclef/util/baritone/GoalRunAwayFromEntities.java b/src/main/java/adris/altoclef/util/baritone/GoalRunAwayFromEntities.java index cee1b3437..357e22f00 100644 --- a/src/main/java/adris/altoclef/util/baritone/GoalRunAwayFromEntities.java +++ b/src/main/java/adris/altoclef/util/baritone/GoalRunAwayFromEntities.java @@ -1,13 +1,12 @@ package adris.altoclef.util.baritone; import adris.altoclef.AltoClef; -import adris.altoclef.util.helpers.BaritoneHelper; import baritone.api.pathing.goals.Goal; import baritone.api.pathing.goals.GoalXZ; import baritone.api.pathing.goals.GoalYLevel; import net.minecraft.entity.Entity; -import java.util.List; +import java.util.Optional; public abstract class GoalRunAwayFromEntities implements Goal { @@ -30,19 +29,16 @@ public GoalRunAwayFromEntities(AltoClef mod, double distance, boolean xzOnly, do @Override public boolean isInGoal(int x, int y, int z) { - List entities = getEntities(_mod); - synchronized (BaritoneHelper.MINECRAFT_LOCK) { - if (!entities.isEmpty()) { - for (Entity entity : entities) { - if (entity == null || !entity.isAlive()) continue; - double sqDistance; - if (_xzOnly) { - sqDistance = entity.getPos().subtract(x, y, z).multiply(1, 0, 1).lengthSquared(); - } else { - sqDistance = entity.squaredDistanceTo(x, y, z); - } - if (sqDistance < _distance * _distance) return false; + if (getEntities(_mod).isPresent()) { + Entity entity = getEntities(_mod).get(); + if (entity.isAlive()) { + double sqDistance; + if (_xzOnly) { + sqDistance = entity.getPos().subtract(x, y, z).multiply(1, 0, 1).lengthSquared(); + } else { + sqDistance = entity.squaredDistanceTo(x, y, z); } + return !(sqDistance < _distance * _distance); } } return true; @@ -52,33 +48,29 @@ public boolean isInGoal(int x, int y, int z) { public double heuristic(int x, int y, int z) { // The lower the cost, the better. double costSum = 0; - List entities = getEntities(_mod); - synchronized (BaritoneHelper.MINECRAFT_LOCK) { - int max = 10; // If we have 100 players, this will never calculate. - int counter = 0; - if (!entities.isEmpty()) { - for (Entity entity : entities) { - counter++; - if (entity == null || !entity.isAlive()) continue; - double cost = getCostOfEntity(entity, x, y, z); - if (cost != 0) { - // We want the CLOSER entities to have a bigger weight than the further ones. - costSum += 1 / cost; - } else { - // Bad >:( - costSum += 1000; - } - if (counter >= max) break; + int counter = 0; + if (getEntities(_mod).isPresent()) { + Entity entity = getEntities(_mod).get(); + counter++; + if (entity.isAlive()) { + double cost = getCostOfEntity(entity, x, y, z); + if (cost != 0) { + // We want the CLOSER entities to have a bigger weight than the further ones. + costSum += 1 / cost; + } else { + // Bad >:( + costSum += 1000; } + ; } - if (counter > 0) { - costSum /= counter; - } - return costSum * _penaltyFactor; } + if (counter > 0) { + costSum /= counter; + } + return costSum * _penaltyFactor; } - protected abstract List getEntities(AltoClef mod); + protected abstract Optional getEntities(AltoClef mod); // Virtual protected double getCostOfEntity(Entity entity, int x, int y, int z) { diff --git a/src/main/java/adris/altoclef/util/helpers/EntityHelper.java b/src/main/java/adris/altoclef/util/helpers/EntityHelper.java index ebd90eee2..abf752153 100644 --- a/src/main/java/adris/altoclef/util/helpers/EntityHelper.java +++ b/src/main/java/adris/altoclef/util/helpers/EntityHelper.java @@ -4,44 +4,43 @@ import net.minecraft.enchantment.EnchantmentHelper; import net.minecraft.entity.DamageUtil; import net.minecraft.entity.Entity; -import net.minecraft.entity.LivingEntity; +import net.minecraft.entity.Tameable; import net.minecraft.entity.attribute.EntityAttributes; import net.minecraft.entity.damage.DamageSource; import net.minecraft.entity.damage.DamageTypes; import net.minecraft.entity.effect.StatusEffects; import net.minecraft.entity.mob.*; import net.minecraft.entity.player.PlayerEntity; +import net.minecraft.entity.raid.RaiderEntity; import net.minecraft.item.ItemStack; import net.minecraft.item.Items; import net.minecraft.registry.tag.DamageTypeTags; +import java.util.Objects; + /** * Helper functions to interpret entity state */ public class EntityHelper { public static final double ENTITY_GRAVITY = 0.08; // per second - public static boolean isAngryAtPlayer(AltoClef mod, Entity mob) { - boolean hostile = isGenerallyHostileToPlayer(mod, mob); - if (mob instanceof LivingEntity entity) { - return hostile && entity.canSee(mod.getPlayer()); - } - return hostile; + public static boolean isAngryAtPlayer(AltoClef mod, Entity entity) { + return isGenerallyHostileToPlayer(mod, entity); } - public static boolean isGenerallyHostileToPlayer(AltoClef mod, Entity hostile) { - // This is only temporary. - if (hostile instanceof MobEntity entity) { - if (entity instanceof HostileEntity entity1) { - return entity1.isAttacking() || !(entity1 instanceof EndermanEntity || entity1 instanceof PiglinEntity || - entity1 instanceof SpiderEntity || entity1 instanceof ZombifiedPiglinEntity); - } - if (entity instanceof SlimeEntity entity1) { - return entity1.canSee(mod.getPlayer()); - } - return entity.isAttacking(); - } - return !isTradingPiglin(hostile); + public static boolean isGenerallyHostileToPlayer(AltoClef mod, Entity entity) { + if (entity instanceof Tameable tameable && tameable.getOwnerUuid() != null + && tameable.getOwnerUuid().equals(mod.getPlayer().getUuid())) return false; + if (entity instanceof SlimeEntity slime && mod.getPlayer().isInRange(slime, 3)) return true; + if (entity instanceof RaiderEntity raider && mod.getPlayer().isInRange(raider, 16)) return true; + if (entity instanceof WardenEntity warden && mod.getPlayer().isInRange(warden, 16)) return true; + if (entity instanceof EndermanEntity enderman && enderman.canSee(mod.getPlayer()) && enderman.isAttacking()) + return true; + if (entity instanceof BlazeEntity blaze && mod.getPlayer().isInRange(blaze, 3)) return true; + if (entity instanceof SlimeEntity || entity instanceof RaiderEntity || entity instanceof WardenEntity + || entity instanceof EndermanEntity || entity instanceof BlazeEntity) return false; + if (entity instanceof MobEntity mob && !mob.isAttacking()) return false; + return !isTradingPiglin(entity); } public static boolean isTradingPiglin(Entity entity) { @@ -70,16 +69,16 @@ public static double calculateResultingPlayerDamage(PlayerEntity player, DamageS // Armor Base if (!source.isIn(DamageTypeTags.BYPASSES_ARMOR)) { - damageAmount = DamageUtil.getDamageLeft((float) damageAmount, source, (float) player.getArmor(), (float) player.getAttributeValue(EntityAttributes.GENERIC_ARMOR_TOUGHNESS)); + damageAmount = DamageUtil.getDamageLeft(player, (float) damageAmount, source, (float) player.getArmor(), (float) player.getAttributeValue(EntityAttributes.GENERIC_ARMOR_TOUGHNESS)); } // Enchantments & Potions if (!source.isIn(DamageTypeTags.BYPASSES_SHIELD)) { - int k; + float k; if (player.hasStatusEffect(StatusEffects.RESISTANCE) && source.isOf(DamageTypes.OUT_OF_WORLD)) { //noinspection ConstantConditions k = (player.getStatusEffect(StatusEffects.RESISTANCE).getAmplifier() + 1) * 5; - int j = 25 - k; + float j = 25 - k; double f = damageAmount * (double) j; double g = damageAmount; damageAmount = Math.max(f / 25.0F, 0.0F); @@ -88,9 +87,9 @@ public static double calculateResultingPlayerDamage(PlayerEntity player, DamageS if (damageAmount <= 0.0) { damageAmount = 0.0; } else { - k = EnchantmentHelper.getProtectionAmount(player.getArmorItems(), source); + k = EnchantmentHelper.getProtectionAmount(Objects.requireNonNull(player.getServer()).getWorld(player.getWorld().getRegistryKey()), player, source); if (k > 0) { - damageAmount = DamageUtil.getInflictedDamage((float) damageAmount, (float) k); + damageAmount = DamageUtil.getInflictedDamage((float) damageAmount, k); } } } diff --git a/src/main/java/adris/altoclef/util/helpers/ItemHelper.java b/src/main/java/adris/altoclef/util/helpers/ItemHelper.java index 76b778e28..4ac40c502 100644 --- a/src/main/java/adris/altoclef/util/helpers/ItemHelper.java +++ b/src/main/java/adris/altoclef/util/helpers/ItemHelper.java @@ -23,6 +23,12 @@ * Helper functions and definitions for useful groupings of items */ public class ItemHelper { + public static final Item[] COPPER_BLOCKS = new Item[]{Items.COPPER_BLOCK, Items.EXPOSED_COPPER, + Items.WEATHERED_COPPER, Items.OXIDIZED_COPPER, Items.CUT_COPPER, Items.EXPOSED_CUT_COPPER, + Items.WEATHERED_CUT_COPPER, Items.OXIDIZED_CUT_COPPER, Items.WAXED_COPPER_BLOCK, + Items.WAXED_EXPOSED_COPPER, Items.WAXED_WEATHERED_COPPER, Items.WAXED_OXIDIZED_COPPER, + Items.WAXED_CUT_COPPER, Items.WAXED_EXPOSED_CUT_COPPER, Items.WAXED_WEATHERED_CUT_COPPER, + Items.WAXED_OXIDIZED_CUT_COPPER}; public static final Item[] SAPLINGS = new Item[]{Items.OAK_SAPLING, Items.SPRUCE_SAPLING, Items.BIRCH_SAPLING, Items.JUNGLE_SAPLING, Items.ACACIA_SAPLING, Items.DARK_OAK_SAPLING, Items.MANGROVE_PROPAGULE, Items.CHERRY_SAPLING}; @@ -366,20 +372,17 @@ public static String trimItemName(String name) { } public static boolean areShearsEffective(Block b) { - return - //b.getRegistryEntry().streamTags().anyMatch(t -> t == - // BlockTags.LEAVES); should also work... but is slower - b instanceof LeavesBlock - || b == Blocks.COBWEB - || b == Blocks.GRASS_BLOCK - || b == Blocks.TALL_GRASS - || b == Blocks.LILY_PAD - || b == Blocks.FERN - || b == Blocks.DEAD_BUSH - || b == Blocks.VINE - || b == Blocks.TRIPWIRE - || isOfBlockType(b, BlockTags.WOOL) - || b == Blocks.NETHER_SPROUTS; + return b instanceof LeavesBlock + || b == Blocks.COBWEB + || b == Blocks.GRASS_BLOCK + || b == Blocks.TALL_GRASS + || b == Blocks.LILY_PAD + || b == Blocks.FERN + || b == Blocks.DEAD_BUSH + || b == Blocks.VINE + || b == Blocks.TRIPWIRE + || isOfBlockType(b, BlockTags.WOOL) + || b == Blocks.NETHER_SPROUTS; } public static boolean isOfBlockType(Block b, TagKey tag) { diff --git a/src/main/java/adris/altoclef/util/helpers/LookHelper.java b/src/main/java/adris/altoclef/util/helpers/LookHelper.java index fa1628261..d2879e8ba 100644 --- a/src/main/java/adris/altoclef/util/helpers/LookHelper.java +++ b/src/main/java/adris/altoclef/util/helpers/LookHelper.java @@ -46,7 +46,7 @@ static Optional getReach(BlockPos target, Direction side) { // Check if the side is null if (side == null) { // Calculate the reachable rotation from the player's position to the target position - reachableRotation = RotationUtils.reachable(context, target, context.playerController().getBlockReachDistance()); + reachableRotation = RotationUtils.reachable(context, target); } else { // Calculate the center offset vector based on the side direction Vec3i sideVector = side.getVector(); diff --git a/src/main/java/adris/altoclef/util/helpers/StorageHelper.java b/src/main/java/adris/altoclef/util/helpers/StorageHelper.java index 3044bb2e9..3e8bc5157 100644 --- a/src/main/java/adris/altoclef/util/helpers/StorageHelper.java +++ b/src/main/java/adris/altoclef/util/helpers/StorageHelper.java @@ -291,7 +291,7 @@ public static Optional getGarbageSlot(AltoClef mod) { assert right.getItem().getComponents().get(DataComponentTypes.FOOD) != null; int leftCost = left.getItem().getComponents().get(DataComponentTypes.FOOD).nutrition() * left.getCount(), rightCost = right.getItem().getComponents().get(DataComponentTypes.FOOD).nutrition() * right.getCount(); - return -1 * (leftCost - rightCost); + return leftCost - rightCost; } // Just discard the one with the smallest quantity, but this doesn't really matter. diff --git a/src/main/java/adris/altoclef/util/helpers/WorldHelper.java b/src/main/java/adris/altoclef/util/helpers/WorldHelper.java index a7349b049..ad8f8ae41 100644 --- a/src/main/java/adris/altoclef/util/helpers/WorldHelper.java +++ b/src/main/java/adris/altoclef/util/helpers/WorldHelper.java @@ -2,7 +2,6 @@ import adris.altoclef.AltoClef; import adris.altoclef.mixins.ClientConnectionAccessor; -import adris.altoclef.mixins.EntityAccessor; import adris.altoclef.util.Dimension; import baritone.api.BaritoneAPI; import baritone.pathing.movement.CalculationContext; @@ -23,6 +22,7 @@ import net.minecraft.world.World; import net.minecraft.world.biome.Biome; import net.minecraft.world.biome.BiomeKeys; +import net.minecraft.world.dimension.PortalManager; import java.util.*; @@ -179,14 +179,12 @@ static int getGroundHeight(AltoClef mod, int x, int z) { } static BlockPos getADesertTemple(AltoClef mod) { - List stonePressurePlates = mod.getBlockTracker().getKnownLocations(Blocks.STONE_PRESSURE_PLATE); - if (!stonePressurePlates.isEmpty()) { - for (BlockPos pos : stonePressurePlates) { - if (mod.getWorld().getBlockState(pos).getBlock() == Blocks.STONE_PRESSURE_PLATE && // Duct tape - mod.getWorld().getBlockState(pos.down()).getBlock() == Blocks.CUT_SANDSTONE && - mod.getWorld().getBlockState(pos.down(2)).getBlock() == Blocks.TNT) { - return pos; - } + if (mod.getBlockTracker().isTracking(Blocks.STONE_PRESSURE_PLATE)) { + Optional stonePressurePlates = mod.getBlockTracker().getNearestTracking(Blocks.STONE_PRESSURE_PLATE); + if (stonePressurePlates.isPresent() && mod.getWorld().getBlockState(stonePressurePlates.get()).getBlock() == Blocks.STONE_PRESSURE_PLATE && // Duct tape + mod.getWorld().getBlockState(stonePressurePlates.get().down()).getBlock() == Blocks.CUT_SANDSTONE && + mod.getWorld().getBlockState(stonePressurePlates.get().down(2)).getBlock() == Blocks.TNT) { + return stonePressurePlates.get(); } } return null; @@ -214,7 +212,7 @@ static boolean canBreak(AltoClef mod, BlockPos pos) { boolean result = mod.getWorld().getBlockState(pos).getHardness(mod.getWorld(), pos) >= 0 && !mod.getExtraBaritoneSettings().shouldAvoidBreaking(pos) && MineProcess.plausibleToBreak(new CalculationContext(mod.getClientBaritone()), pos) - && canReach(mod, pos); + && canReach(mod, pos) && !mod.getBlockTracker().unreachable(pos); mod.getExtraBaritoneSettings().setInteractionPaused(prevInteractionPaused); return result; } @@ -222,7 +220,10 @@ static boolean canBreak(AltoClef mod, BlockPos pos) { static boolean isInNetherPortal(AltoClef mod) { if (mod.getPlayer() == null) return false; - return ((EntityAccessor) mod.getPlayer()).isInNetherPortal(); + PortalManager portalManager = mod.getPlayer().portalManager; + if (portalManager == null) + return false; + return portalManager.isInPortal(); } static boolean dangerousToBreakIfRightAbove(AltoClef mod, BlockPos toBreak) { diff --git a/src/main/java/adris/altoclef/util/serialization/ItemDeserializer.java b/src/main/java/adris/altoclef/util/serialization/ItemDeserializer.java index 36c3d57b1..c70b277d5 100644 --- a/src/main/java/adris/altoclef/util/serialization/ItemDeserializer.java +++ b/src/main/java/adris/altoclef/util/serialization/ItemDeserializer.java @@ -42,7 +42,7 @@ public Object deserialize(JsonParser p, DeserializationContext ctxt) throws IOEx // Translation key (the proper way) String itemKey = p.getText(); itemKey = ItemHelper.trimItemName(itemKey); - Identifier identifier = new Identifier(itemKey); + Identifier identifier = Identifier.of(itemKey); if (Registries.ITEM.containsId(identifier)) { item = Registries.ITEM.get(identifier); } else { diff --git a/src/main/resources/altoclef.mixins.json b/src/main/resources/altoclef.mixins.json index e026edae8..d057dfacd 100644 --- a/src/main/resources/altoclef.mixins.json +++ b/src/main/resources/altoclef.mixins.json @@ -12,7 +12,6 @@ "ClientPlayerInteractionAccessor", "ClientUIMixin", "DeathScreenAccessor", - "EntityAccessor", "GameOverlayMixin", "PersistentProjectileEntityAccessor", "SlotClickMixin", diff --git a/src/main/resources/fabric.mod.json b/src/main/resources/fabric.mod.json index d5d0b33fa..22f7dffc7 100644 --- a/src/main/resources/fabric.mod.json +++ b/src/main/resources/fabric.mod.json @@ -1,7 +1,7 @@ { "schemaVersion": 1, "id": "altoclef", - "version": "1.20.6-beta1", + "version": "1.21-beta1", "name": "Alto Clef", "description": "Plays Block Game", "authors": [