Utilize Optional return types where mostly applicable

This commit is contained in:
Brady 2018-08-06 02:21:47 -05:00
parent 091c19ca72
commit e8149f166f
No known key found for this signature in database
GPG Key ID: 73A788379A197567
5 changed files with 64 additions and 66 deletions

View File

@ -28,6 +28,7 @@ import org.lwjgl.opengl.GL11;
import java.awt.*;
import java.util.List;
import java.util.Optional;
public class PathingBehavior extends Behavior {
@ -55,11 +56,8 @@ public class PathingBehavior extends Behavior {
return current;
}
public IPath getPath() {
if (current == null) {
return null;
}
return current.getPath();
public Optional<IPath> getPath() {
return Optional.ofNullable(current).map(PathExecutor::getPath);
}
@Override
@ -92,10 +90,7 @@ public class PathingBehavior extends Behavior {
}
try {
IPath path = findPath(start);
if (path != null) {
current = new PathExecutor(path);
}
findPath(start).map(PathExecutor::new).ifPresent(path -> current = path);
} catch (Exception ignored) {}
/*isThereAnythingInProgress = false;
if (!currentPath.goal.isInGoal(currentPath.end)) {
@ -115,18 +110,17 @@ public class PathingBehavior extends Behavior {
* @param start
* @return
*/
private IPath findPath(BlockPos start) {
private Optional<IPath> findPath(BlockPos start) {
if (goal == null) {
displayChatMessageRaw("no goal");
return null;
return Optional.empty();
}
try {
IPathFinder pf = new AStarPathFinder(start, goal);
IPath path = pf.calculate();
return path;
return pf.calculate();
} catch (Exception e) {
e.printStackTrace();
return null;
return Optional.empty();
}
}
@ -134,22 +128,21 @@ public class PathingBehavior extends Behavior {
public void onRenderPass(RenderEvent event) {
//System.out.println("Render passing");
//System.out.println(event.getPartialTicks());
IPath path = getPath();
float partialTicks = event.getPartialTicks();
if (path != null) {
drawPath(path, player(), partialTicks, Color.RED);
}
if (AbstractNodeCostSearch.currentlyRunning != null) {
IPath p = AbstractNodeCostSearch.currentlyRunning.bestPathSoFar();
if (p != null) {
// Render the current path, if there is one
getPath().ifPresent(path -> drawPath(path, player(), partialTicks, Color.RED));
// If there is a path calculation currently running, render the path calculation process
AbstractNodeCostSearch.getCurrentlyRunning().ifPresent(currentlyRunning -> {
currentlyRunning.bestPathSoFar().ifPresent(p -> {
drawPath(p, player(), partialTicks, Color.BLUE);
IPath mr = AbstractNodeCostSearch.currentlyRunning.pathToMostRecentNodeConsidered();
if (mr != null) {
currentlyRunning.pathToMostRecentNodeConsidered().ifPresent(mr -> {
drawPath(mr, player(), partialTicks, Color.CYAN);
drawSelectionBox(player(), mr.getDest(), partialTicks, Color.CYAN);
}
}
}
});
});
});
}
public void drawPath(IPath path, EntityPlayerSP player, float partialTicks, Color color) {

View File

@ -13,6 +13,7 @@ import net.minecraft.client.Minecraft;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.chunk.EmptyChunk;
import java.util.Optional;
import java.util.Random;
/**
@ -21,12 +22,13 @@ import java.util.Random;
* @author leijurv
*/
public class AStarPathFinder extends AbstractNodeCostSearch {
public AStarPathFinder(BlockPos start, Goal goal) {
super(start, goal);
}
@Override
protected IPath calculate0() {
protected Optional<IPath> calculate0() {
startNode = getNodeAtPosition(start);
startNode.cost = 0;
startNode.combinedCost = startNode.estimatedCostToGoal;
@ -64,7 +66,7 @@ public class AStarPathFinder extends AbstractNodeCostSearch {
}
if (goal.isInGoal(currentNodePos)) {
currentlyRunning = null;
return new Path(startNode, currentNode, goal);
return Optional.of(new Path(startNode, currentNode, goal));
}
//long constructStart = System.nanoTime();
Movement[] possibleMovements = getConnectedPositions(currentNodePos);//movement that we could take that start at myPos, in random order
@ -125,13 +127,13 @@ public class AStarPathFinder extends AbstractNodeCostSearch {
}
System.out.println("Path goes for " + dist + " blocks");
currentlyRunning = null;
return new Path(startNode, bestSoFar[i], goal);
return Optional.of(new Path(startNode, bestSoFar[i], goal));
}
}
System.out.println("Even with a cost coefficient of " + COEFFICIENTS[COEFFICIENTS.length - 1] + ", I couldn't get more than " + bestDist + " blocks =(");
System.out.println("No path found =(");
currentlyRunning = null;
return null;
return Optional.empty();
}

View File

@ -6,6 +6,7 @@ import net.minecraft.util.math.BlockPos;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
/**
* Any pathfinding algorithm that keeps track of nodes recursively by their cost (e.g. A*, dijkstra)
@ -16,10 +17,8 @@ public abstract class AbstractNodeCostSearch implements IPathFinder {
/**
* The currently running search task
* <p>
* TODO: This shouldn't be necessary, investigate old purpose of this field and determine necessity.
*/
public static AbstractNodeCostSearch currentlyRunning = null;
protected static AbstractNodeCostSearch currentlyRunning = null;
protected final BlockPos start;
@ -53,16 +52,16 @@ public abstract class AbstractNodeCostSearch implements IPathFinder {
this.map = new HashMap<>();
}
public synchronized IPath calculate() {
public synchronized Optional<IPath> calculate() {
if (isFinished) {
throw new IllegalStateException("Path Finder is currently in use! Wait until complete to reuse!");
}
IPath path = calculate0();
Optional<IPath> path = calculate0();
isFinished = true;
return path;
}
protected abstract IPath calculate0();
protected abstract Optional<IPath> calculate0();
/**
* Determines the distance squared from the specified node to the start
@ -103,16 +102,16 @@ public abstract class AbstractNodeCostSearch implements IPathFinder {
}
@Override
public IPath bestPathSoFar() {
if (startNode == null || bestSoFar[0] == null) {
return null;
}
return new Path(startNode, bestSoFar[0], goal);
public Optional<IPath> pathToMostRecentNodeConsidered() {
return Optional.ofNullable(mostRecentConsidered).map(node -> new Path(startNode, node, goal));
}
@Override
public IPath pathToMostRecentNodeConsidered() {
return mostRecentConsidered == null ? null : new Path(startNode, mostRecentConsidered, goal);
public Optional<IPath> bestPathSoFar() {
if (startNode == null || bestSoFar[0] == null)
return Optional.empty();
return Optional.of(new Path(startNode, bestSoFar[0], goal));
}
@Override
@ -129,4 +128,8 @@ public abstract class AbstractNodeCostSearch implements IPathFinder {
public final BlockPos getStart() {
return start;
}
public static Optional<AbstractNodeCostSearch> getCurrentlyRunning() {
return Optional.ofNullable(currentlyRunning);
}
}

View File

@ -4,6 +4,8 @@ import baritone.bot.pathing.goals.Goal;
import baritone.bot.pathing.path.IPath;
import net.minecraft.util.math.BlockPos;
import java.util.Optional;
/**
* Generic path finder interface
*
@ -20,7 +22,7 @@ public interface IPathFinder {
*
* @return The final path
*/
IPath calculate();
Optional<IPath> calculate();
/**
* Intended to be called concurrently with calculatePath from a different thread to tell if it's finished yet
@ -34,7 +36,7 @@ public interface IPathFinder {
*
* @return The temporary path
*/
IPath pathToMostRecentNodeConsidered();
Optional<IPath> pathToMostRecentNodeConsidered();
/**
* The best path so far, according to the most forgiving coefficient heuristic (the reason being that that path is
@ -44,5 +46,5 @@ public interface IPathFinder {
*
* @return The temporary path
*/
IPath bestPathSoFar();
Optional<IPath> bestPathSoFar();
}

View File

@ -11,6 +11,8 @@ import net.minecraft.init.Blocks;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.RayTraceResult;
import java.util.Optional;
/**
* Static helpers for cost calculation
*
@ -153,41 +155,38 @@ public interface MovementHelper extends ActionCosts, Helper {
* The currently highlighted block.
* Updated once a tick by Minecraft.
*
* @return the position of the highlighted block, or null if no block is highlighted
* @return the position of the highlighted block
*/
static BlockPos whatAmILookingAt() {
static Optional<BlockPos> whatAmILookingAt() {
if (mc.objectMouseOver != null && mc.objectMouseOver.typeOfHit == RayTraceResult.Type.BLOCK) {
return mc.objectMouseOver.getBlockPos();
return Optional.of(mc.objectMouseOver.getBlockPos());
}
return null;
return Optional.empty();
}
/**
* The entity the player is currently looking at
*
* @return the entity object, or null if the player isn't looking at an entity
* @return the entity object
*/
static Entity whatEntityAmILookingAt() {
Minecraft mc = Minecraft.getMinecraft();
static Optional<Entity> whatEntityAmILookingAt() {
if (mc.objectMouseOver != null && mc.objectMouseOver.typeOfHit == RayTraceResult.Type.ENTITY) {
return mc.objectMouseOver.entityHit;
return Optional.of(mc.objectMouseOver.entityHit);
}
return null;
return Optional.empty();
}
/**
* AutoTool
*/
static void switchToBestTool() {
BlockPos pos = whatAmILookingAt();
if (pos == null) {
return;
}
whatAmILookingAt().ifPresent(pos -> {
IBlockState state = BlockStateInterface.get(pos);
if (state.getBlock().equals(Blocks.AIR)) {
return;
}
switchToBestToolFor(state);
});
}
/**
@ -206,11 +205,10 @@ public interface MovementHelper extends ActionCosts, Helper {
* @param ts previously calculated ToolSet
*/
static void switchToBestToolFor(IBlockState b, ToolSet ts) {
Minecraft.getMinecraft().player.inventory.currentItem = ts.getBestSlot(b);
mc.player.inventory.currentItem = ts.getBestSlot(b);
}
static boolean isAir(BlockPos pos) {
return BlockStateInterface.get(pos).getBlock().equals(Blocks.AIR);
}
}