Skip to content

Instantly share code, notes, and snippets.

@WesJD
Created August 3, 2016 03:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save WesJD/7a66a2c958e05ac3986ddab5f684c4ea to your computer and use it in GitHub Desktop.
Save WesJD/7a66a2c958e05ac3986ddab5f684c4ea to your computer and use it in GitHub Desktop.
Teleport players to random locations with efficiency from Guava
public class RandomTeleporter {
private final LoadingCache<Pair<Location, Location>, List<Pair<Integer, Integer>>> locationCache = CacheBuilder.newBuilder()
.expireAfterAccess(1, TimeUnit.MINUTES)
.maximumSize(5)
.build(new CacheLoader<Pair<Location, Location>, List<Pair<Integer, Integer>>>() {
@Override
public List<Pair<Integer, Integer>> load(Pair<Location, Location> bounds) throws Exception {
final List<Pair<Integer, Integer>> ret = new ArrayList<>();
final Location bounds1 = bounds.getLeft();
final Location bounds2 = bounds.getRight();
for(int x=Math.min(bounds1.getBlockX(), bounds2.getBlockX()); x < Math.max(bounds1.getBlockX(), bounds2.getBlockX()); x++) {
for(int z=Math.min(bounds1.getBlockZ(), bounds2.getBlockZ()); z < Math.max(bounds1.getBlockZ(), bounds2.getBlockZ()); z++) {
ret.add(ImmutablePair.of(x, z));
}
}
return ret;
}
});
public Location getRandomLocation(Pair<Location, Location> bounds) throws ExecutionException {
final List<Pair<Integer, Integer>> pairs = locationCache.get(bounds);
final Pair<Integer, Integer> randomPair = pairs.get(ThreadLocalRandom.current().nextInt(pairs.size()));
Block safe = Constants.WORLD.getHighestBlockAt(randomPair.getLeft(), randomPair.getRight());
while(safe.isEmpty()) {
final Block below = safe.getRelative(BlockFace.DOWN);
if(!below.isEmpty()) break;
safe = below;
}
if(safe.isLiquid()) return getRandomLocation(bounds);
return safe.getLocation();
}
public void teleportRandomly(Player player, Pair<Location, Location> bounds) throws ExecutionException {
player.teleport(getRandomLocation(bounds));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment